1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2 * All rights reserved.
3 *
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
7 *
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14 *
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39 *
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 * SUCH DAMAGE.
51 *
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
56 */
57 /* ====================================================================
58 * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
59 *
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
62 * are met:
63 *
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
66 *
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
70 * distribution.
71 *
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76 *
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
81 *
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
85 *
86 * 6. Redistributions of any form whatsoever must retain the following
87 * acknowledgment:
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90 *
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
104 *
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com). */
108
109 // Ensure we can't call OPENSSL_malloc circularly.
110 #define _BORINGSSL_PROHIBIT_OPENSSL_MALLOC
111 #include <openssl/err.h>
112
113 #include <assert.h>
114 #include <errno.h>
115 #include <inttypes.h>
116 #include <limits.h>
117 #include <stdarg.h>
118 #include <string.h>
119
120 #if defined(OPENSSL_WINDOWS)
121 OPENSSL_MSVC_PRAGMA(warning(push, 3))
122 #include <windows.h>
123 OPENSSL_MSVC_PRAGMA(warning(pop))
124 #endif
125
126 #include <openssl/mem.h>
127 #include <openssl/thread.h>
128
129 #include "../internal.h"
130 #include "./internal.h"
131
132
133 struct err_error_st {
134 // file contains the filename where the error occurred.
135 const char *file;
136 // data contains a NUL-terminated string with optional data. It is allocated
137 // with system |malloc| and must be freed with |free| (not |OPENSSL_free|)
138 char *data;
139 // packed contains the error library and reason, as packed by ERR_PACK.
140 uint32_t packed;
141 // line contains the line number where the error occurred.
142 uint16_t line;
143 // mark indicates a reversion point in the queue. See |ERR_pop_to_mark|.
144 unsigned mark : 1;
145 };
146
147 // ERR_STATE contains the per-thread, error queue.
148 typedef struct err_state_st {
149 // errors contains up to ERR_NUM_ERRORS - 1 most recent errors, organised as a
150 // ring buffer.
151 struct err_error_st errors[ERR_NUM_ERRORS];
152 // top contains the index of the most recent error. If |top| equals |bottom|
153 // then the queue is empty.
154 unsigned top;
155 // bottom contains the index before the least recent error in the queue.
156 unsigned bottom;
157
158 // to_free, if not NULL, contains a pointer owned by this structure that was
159 // previously a |data| pointer of one of the elements of |errors|.
160 void *to_free;
161 } ERR_STATE;
162
163 extern const uint32_t kOpenSSLReasonValues[];
164 extern const size_t kOpenSSLReasonValuesLen;
165 extern const char kOpenSSLReasonStringData[];
166
167 // err_clear clears the given queued error.
err_clear(struct err_error_st * error)168 static void err_clear(struct err_error_st *error) {
169 free(error->data);
170 OPENSSL_memset(error, 0, sizeof(struct err_error_st));
171 }
172
err_copy(struct err_error_st * dst,const struct err_error_st * src)173 static void err_copy(struct err_error_st *dst, const struct err_error_st *src) {
174 err_clear(dst);
175 dst->file = src->file;
176 if (src->data != NULL) {
177 // Disable deprecated functions on msvc so it doesn't complain about strdup.
178 OPENSSL_MSVC_PRAGMA(warning(push))
179 OPENSSL_MSVC_PRAGMA(warning(disable : 4996))
180 // We can't use OPENSSL_strdup because we don't want to call OPENSSL_malloc,
181 // which can affect the error stack.
182 dst->data = strdup(src->data);
183 OPENSSL_MSVC_PRAGMA(warning(pop))
184 }
185 dst->packed = src->packed;
186 dst->line = src->line;
187 }
188
189
190 // global_next_library contains the next custom library value to return.
191 static int global_next_library = ERR_NUM_LIBS;
192
193 // global_next_library_mutex protects |global_next_library| from concurrent
194 // updates.
195 static CRYPTO_MUTEX global_next_library_mutex = CRYPTO_MUTEX_INIT;
196
err_state_free(void * statep)197 static void err_state_free(void *statep) {
198 ERR_STATE *state = statep;
199
200 if (state == NULL) {
201 return;
202 }
203
204 for (unsigned i = 0; i < ERR_NUM_ERRORS; i++) {
205 err_clear(&state->errors[i]);
206 }
207 free(state->to_free);
208 free(state);
209 }
210
211 // err_get_state gets the ERR_STATE object for the current thread.
err_get_state(void)212 static ERR_STATE *err_get_state(void) {
213 ERR_STATE *state = CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_ERR);
214 if (state == NULL) {
215 state = malloc(sizeof(ERR_STATE));
216 if (state == NULL) {
217 return NULL;
218 }
219 OPENSSL_memset(state, 0, sizeof(ERR_STATE));
220 if (!CRYPTO_set_thread_local(OPENSSL_THREAD_LOCAL_ERR, state,
221 err_state_free)) {
222 return NULL;
223 }
224 }
225
226 return state;
227 }
228
get_error_values(int inc,int top,const char ** file,int * line,const char ** data,int * flags)229 static uint32_t get_error_values(int inc, int top, const char **file, int *line,
230 const char **data, int *flags) {
231 unsigned i = 0;
232 ERR_STATE *state;
233 struct err_error_st *error;
234 uint32_t ret;
235
236 state = err_get_state();
237 if (state == NULL || state->bottom == state->top) {
238 return 0;
239 }
240
241 if (top) {
242 assert(!inc);
243 // last error
244 i = state->top;
245 } else {
246 i = (state->bottom + 1) % ERR_NUM_ERRORS;
247 }
248
249 error = &state->errors[i];
250 ret = error->packed;
251
252 if (file != NULL && line != NULL) {
253 if (error->file == NULL) {
254 *file = "NA";
255 *line = 0;
256 } else {
257 *file = error->file;
258 *line = error->line;
259 }
260 }
261
262 if (data != NULL) {
263 if (error->data == NULL) {
264 *data = "";
265 if (flags != NULL) {
266 *flags = 0;
267 }
268 } else {
269 *data = error->data;
270 if (flags != NULL) {
271 // Without |ERR_FLAG_MALLOCED|, rust-openssl assumes the string has a
272 // static lifetime. In both cases, we retain ownership of the string,
273 // and the caller is not expected to free it.
274 *flags = ERR_FLAG_STRING | ERR_FLAG_MALLOCED;
275 }
276 // If this error is being removed, take ownership of data from
277 // the error. The semantics are such that the caller doesn't
278 // take ownership either. Instead the error system takes
279 // ownership and retains it until the next call that affects the
280 // error queue.
281 if (inc) {
282 if (error->data != NULL) {
283 free(state->to_free);
284 state->to_free = error->data;
285 }
286 error->data = NULL;
287 }
288 }
289 }
290
291 if (inc) {
292 assert(!top);
293 err_clear(error);
294 state->bottom = i;
295 }
296
297 return ret;
298 }
299
ERR_get_error(void)300 uint32_t ERR_get_error(void) {
301 return get_error_values(1 /* inc */, 0 /* bottom */, NULL, NULL, NULL, NULL);
302 }
303
ERR_get_error_line(const char ** file,int * line)304 uint32_t ERR_get_error_line(const char **file, int *line) {
305 return get_error_values(1 /* inc */, 0 /* bottom */, file, line, NULL, NULL);
306 }
307
ERR_get_error_line_data(const char ** file,int * line,const char ** data,int * flags)308 uint32_t ERR_get_error_line_data(const char **file, int *line,
309 const char **data, int *flags) {
310 return get_error_values(1 /* inc */, 0 /* bottom */, file, line, data, flags);
311 }
312
ERR_peek_error(void)313 uint32_t ERR_peek_error(void) {
314 return get_error_values(0 /* peek */, 0 /* bottom */, NULL, NULL, NULL, NULL);
315 }
316
ERR_peek_error_line(const char ** file,int * line)317 uint32_t ERR_peek_error_line(const char **file, int *line) {
318 return get_error_values(0 /* peek */, 0 /* bottom */, file, line, NULL, NULL);
319 }
320
ERR_peek_error_line_data(const char ** file,int * line,const char ** data,int * flags)321 uint32_t ERR_peek_error_line_data(const char **file, int *line,
322 const char **data, int *flags) {
323 return get_error_values(0 /* peek */, 0 /* bottom */, file, line, data,
324 flags);
325 }
326
ERR_peek_last_error(void)327 uint32_t ERR_peek_last_error(void) {
328 return get_error_values(0 /* peek */, 1 /* top */, NULL, NULL, NULL, NULL);
329 }
330
ERR_peek_last_error_line(const char ** file,int * line)331 uint32_t ERR_peek_last_error_line(const char **file, int *line) {
332 return get_error_values(0 /* peek */, 1 /* top */, file, line, NULL, NULL);
333 }
334
ERR_peek_last_error_line_data(const char ** file,int * line,const char ** data,int * flags)335 uint32_t ERR_peek_last_error_line_data(const char **file, int *line,
336 const char **data, int *flags) {
337 return get_error_values(0 /* peek */, 1 /* top */, file, line, data, flags);
338 }
339
ERR_clear_error(void)340 void ERR_clear_error(void) {
341 ERR_STATE *const state = err_get_state();
342 unsigned i;
343
344 if (state == NULL) {
345 return;
346 }
347
348 for (i = 0; i < ERR_NUM_ERRORS; i++) {
349 err_clear(&state->errors[i]);
350 }
351 free(state->to_free);
352 state->to_free = NULL;
353
354 state->top = state->bottom = 0;
355 }
356
ERR_remove_thread_state(const CRYPTO_THREADID * tid)357 void ERR_remove_thread_state(const CRYPTO_THREADID *tid) {
358 if (tid != NULL) {
359 assert(0);
360 return;
361 }
362
363 ERR_clear_error();
364 }
365
ERR_get_next_error_library(void)366 int ERR_get_next_error_library(void) {
367 int ret;
368
369 CRYPTO_MUTEX_lock_write(&global_next_library_mutex);
370 ret = global_next_library++;
371 CRYPTO_MUTEX_unlock_write(&global_next_library_mutex);
372
373 return ret;
374 }
375
ERR_remove_state(unsigned long pid)376 void ERR_remove_state(unsigned long pid) {
377 ERR_clear_error();
378 }
379
ERR_clear_system_error(void)380 void ERR_clear_system_error(void) {
381 errno = 0;
382 }
383
384 // err_string_cmp is a compare function for searching error values with
385 // |bsearch| in |err_string_lookup|.
err_string_cmp(const void * a,const void * b)386 static int err_string_cmp(const void *a, const void *b) {
387 const uint32_t a_key = *((const uint32_t*) a) >> 15;
388 const uint32_t b_key = *((const uint32_t*) b) >> 15;
389
390 if (a_key < b_key) {
391 return -1;
392 } else if (a_key > b_key) {
393 return 1;
394 } else {
395 return 0;
396 }
397 }
398
399 // err_string_lookup looks up the string associated with |lib| and |key| in
400 // |values| and |string_data|. It returns the string or NULL if not found.
err_string_lookup(uint32_t lib,uint32_t key,const uint32_t * values,size_t num_values,const char * string_data)401 static const char *err_string_lookup(uint32_t lib, uint32_t key,
402 const uint32_t *values,
403 size_t num_values,
404 const char *string_data) {
405 // |values| points to data in err_data.h, which is generated by
406 // err_data_generate.go. It's an array of uint32_t values. Each value has the
407 // following structure:
408 // | lib | key | offset |
409 // |6 bits| 11 bits | 15 bits |
410 //
411 // The |lib| value is a library identifier: one of the |ERR_LIB_*| values.
412 // The |key| is a reason code, depending on the context.
413 // The |offset| is the number of bytes from the start of |string_data| where
414 // the (NUL terminated) string for this value can be found.
415 //
416 // Values are sorted based on treating the |lib| and |key| part as an
417 // unsigned integer.
418 if (lib >= (1 << 6) || key >= (1 << 11)) {
419 return NULL;
420 }
421 uint32_t search_key = lib << 26 | key << 15;
422 const uint32_t *result = bsearch(&search_key, values, num_values,
423 sizeof(uint32_t), err_string_cmp);
424 if (result == NULL) {
425 return NULL;
426 }
427
428 return &string_data[(*result) & 0x7fff];
429 }
430
431 static const char *const kLibraryNames[ERR_NUM_LIBS] = {
432 "invalid library (0)",
433 "unknown library", // ERR_LIB_NONE
434 "system library", // ERR_LIB_SYS
435 "bignum routines", // ERR_LIB_BN
436 "RSA routines", // ERR_LIB_RSA
437 "Diffie-Hellman routines", // ERR_LIB_DH
438 "public key routines", // ERR_LIB_EVP
439 "memory buffer routines", // ERR_LIB_BUF
440 "object identifier routines", // ERR_LIB_OBJ
441 "PEM routines", // ERR_LIB_PEM
442 "DSA routines", // ERR_LIB_DSA
443 "X.509 certificate routines", // ERR_LIB_X509
444 "ASN.1 encoding routines", // ERR_LIB_ASN1
445 "configuration file routines", // ERR_LIB_CONF
446 "common libcrypto routines", // ERR_LIB_CRYPTO
447 "elliptic curve routines", // ERR_LIB_EC
448 "SSL routines", // ERR_LIB_SSL
449 "BIO routines", // ERR_LIB_BIO
450 "PKCS7 routines", // ERR_LIB_PKCS7
451 "PKCS8 routines", // ERR_LIB_PKCS8
452 "X509 V3 routines", // ERR_LIB_X509V3
453 "random number generator", // ERR_LIB_RAND
454 "ENGINE routines", // ERR_LIB_ENGINE
455 "OCSP routines", // ERR_LIB_OCSP
456 "UI routines", // ERR_LIB_UI
457 "COMP routines", // ERR_LIB_COMP
458 "ECDSA routines", // ERR_LIB_ECDSA
459 "ECDH routines", // ERR_LIB_ECDH
460 "HMAC routines", // ERR_LIB_HMAC
461 "Digest functions", // ERR_LIB_DIGEST
462 "Cipher functions", // ERR_LIB_CIPHER
463 "HKDF functions", // ERR_LIB_HKDF
464 "Trust Token functions", // ERR_LIB_TRUST_TOKEN
465 "User defined functions", // ERR_LIB_USER
466 };
467
err_lib_error_string(uint32_t packed_error)468 static const char *err_lib_error_string(uint32_t packed_error) {
469 const uint32_t lib = ERR_GET_LIB(packed_error);
470
471 if (lib >= ERR_NUM_LIBS) {
472 return NULL;
473 }
474 return kLibraryNames[lib];
475 }
476
ERR_lib_error_string(uint32_t packed_error)477 const char *ERR_lib_error_string(uint32_t packed_error) {
478 const char *ret = err_lib_error_string(packed_error);
479 return ret == NULL ? "unknown library" : ret;
480 }
481
ERR_func_error_string(uint32_t packed_error)482 const char *ERR_func_error_string(uint32_t packed_error) {
483 return "OPENSSL_internal";
484 }
485
err_reason_error_string(uint32_t packed_error)486 static const char *err_reason_error_string(uint32_t packed_error) {
487 const uint32_t lib = ERR_GET_LIB(packed_error);
488 const uint32_t reason = ERR_GET_REASON(packed_error);
489
490 if (lib == ERR_LIB_SYS) {
491 if (reason < 127) {
492 return strerror(reason);
493 }
494 return NULL;
495 }
496
497 if (reason < ERR_NUM_LIBS) {
498 return kLibraryNames[reason];
499 }
500
501 if (reason < 100) {
502 switch (reason) {
503 case ERR_R_MALLOC_FAILURE:
504 return "malloc failure";
505 case ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED:
506 return "function should not have been called";
507 case ERR_R_PASSED_NULL_PARAMETER:
508 return "passed a null parameter";
509 case ERR_R_INTERNAL_ERROR:
510 return "internal error";
511 case ERR_R_OVERFLOW:
512 return "overflow";
513 default:
514 return NULL;
515 }
516 }
517
518 return err_string_lookup(lib, reason, kOpenSSLReasonValues,
519 kOpenSSLReasonValuesLen, kOpenSSLReasonStringData);
520 }
521
ERR_reason_error_string(uint32_t packed_error)522 const char *ERR_reason_error_string(uint32_t packed_error) {
523 const char *ret = err_reason_error_string(packed_error);
524 return ret == NULL ? "unknown error" : ret;
525 }
526
ERR_error_string(uint32_t packed_error,char * ret)527 char *ERR_error_string(uint32_t packed_error, char *ret) {
528 static char buf[ERR_ERROR_STRING_BUF_LEN];
529
530 if (ret == NULL) {
531 // TODO(fork): remove this.
532 ret = buf;
533 }
534
535 #if !defined(NDEBUG)
536 // This is aimed to help catch callers who don't provide
537 // |ERR_ERROR_STRING_BUF_LEN| bytes of space.
538 OPENSSL_memset(ret, 0, ERR_ERROR_STRING_BUF_LEN);
539 #endif
540
541 return ERR_error_string_n(packed_error, ret, ERR_ERROR_STRING_BUF_LEN);
542 }
543
ERR_error_string_n(uint32_t packed_error,char * buf,size_t len)544 char *ERR_error_string_n(uint32_t packed_error, char *buf, size_t len) {
545 if (len == 0) {
546 return NULL;
547 }
548
549 unsigned lib = ERR_GET_LIB(packed_error);
550 unsigned reason = ERR_GET_REASON(packed_error);
551
552 const char *lib_str = err_lib_error_string(packed_error);
553 const char *reason_str = err_reason_error_string(packed_error);
554
555 char lib_buf[32], reason_buf[32];
556 if (lib_str == NULL) {
557 snprintf(lib_buf, sizeof(lib_buf), "lib(%u)", lib);
558 lib_str = lib_buf;
559 }
560
561 if (reason_str == NULL) {
562 snprintf(reason_buf, sizeof(reason_buf), "reason(%u)", reason);
563 reason_str = reason_buf;
564 }
565
566 int ret = snprintf(buf, len, "error:%08" PRIx32 ":%s:OPENSSL_internal:%s",
567 packed_error, lib_str, reason_str);
568 if (ret >= 0 && (size_t)ret >= len) {
569 // The output was truncated; make sure we always have 5 colon-separated
570 // fields, i.e. 4 colons.
571 static const unsigned num_colons = 4;
572 unsigned i;
573 char *s = buf;
574
575 if (len <= num_colons) {
576 // In this situation it's not possible to ensure that the correct number
577 // of colons are included in the output.
578 return buf;
579 }
580
581 for (i = 0; i < num_colons; i++) {
582 char *colon = strchr(s, ':');
583 char *last_pos = &buf[len - 1] - num_colons + i;
584
585 if (colon == NULL || colon > last_pos) {
586 // set colon |i| at last possible position (buf[len-1] is the
587 // terminating 0). If we're setting this colon, then all whole of the
588 // rest of the string must be colons in order to have the correct
589 // number.
590 OPENSSL_memset(last_pos, ':', num_colons - i);
591 break;
592 }
593
594 s = colon + 1;
595 }
596 }
597
598 return buf;
599 }
600
ERR_print_errors_cb(ERR_print_errors_callback_t callback,void * ctx)601 void ERR_print_errors_cb(ERR_print_errors_callback_t callback, void *ctx) {
602 char buf[ERR_ERROR_STRING_BUF_LEN];
603 char buf2[1024];
604 const char *file, *data;
605 int line, flags;
606 uint32_t packed_error;
607
608 // thread_hash is the least-significant bits of the |ERR_STATE| pointer value
609 // for this thread.
610 const unsigned long thread_hash = (uintptr_t) err_get_state();
611
612 for (;;) {
613 packed_error = ERR_get_error_line_data(&file, &line, &data, &flags);
614 if (packed_error == 0) {
615 break;
616 }
617
618 ERR_error_string_n(packed_error, buf, sizeof(buf));
619 snprintf(buf2, sizeof(buf2), "%lu:%s:%s:%d:%s\n", thread_hash, buf, file,
620 line, (flags & ERR_FLAG_STRING) ? data : "");
621 if (callback(buf2, strlen(buf2), ctx) <= 0) {
622 break;
623 }
624 }
625 }
626
print_errors_to_file(const char * msg,size_t msg_len,void * ctx)627 static int print_errors_to_file(const char* msg, size_t msg_len, void* ctx) {
628 assert(msg[msg_len] == '\0');
629 FILE* fp = ctx;
630 int res = fputs(msg, fp);
631 return res < 0 ? 0 : 1;
632 }
633
ERR_print_errors_fp(FILE * file)634 void ERR_print_errors_fp(FILE *file) {
635 ERR_print_errors_cb(print_errors_to_file, file);
636 }
637
638 // err_set_error_data sets the data on the most recent error.
err_set_error_data(char * data)639 static void err_set_error_data(char *data) {
640 ERR_STATE *const state = err_get_state();
641 struct err_error_st *error;
642
643 if (state == NULL || state->top == state->bottom) {
644 free(data);
645 return;
646 }
647
648 error = &state->errors[state->top];
649
650 free(error->data);
651 error->data = data;
652 }
653
ERR_put_error(int library,int unused,int reason,const char * file,unsigned line)654 void ERR_put_error(int library, int unused, int reason, const char *file,
655 unsigned line) {
656 ERR_STATE *const state = err_get_state();
657 struct err_error_st *error;
658
659 if (state == NULL) {
660 return;
661 }
662
663 if (library == ERR_LIB_SYS && reason == 0) {
664 #if defined(OPENSSL_WINDOWS)
665 reason = GetLastError();
666 #else
667 reason = errno;
668 #endif
669 }
670
671 state->top = (state->top + 1) % ERR_NUM_ERRORS;
672 if (state->top == state->bottom) {
673 state->bottom = (state->bottom + 1) % ERR_NUM_ERRORS;
674 }
675
676 error = &state->errors[state->top];
677 err_clear(error);
678 error->file = file;
679 error->line = line;
680 error->packed = ERR_PACK(library, reason);
681 }
682
683 // ERR_add_error_data_vdata takes a variable number of const char* pointers,
684 // concatenates them and sets the result as the data on the most recent
685 // error.
err_add_error_vdata(unsigned num,va_list args)686 static void err_add_error_vdata(unsigned num, va_list args) {
687 size_t total_size = 0;
688 const char *substr;
689 char *buf;
690
691 va_list args_copy;
692 va_copy(args_copy, args);
693 for (size_t i = 0; i < num; i++) {
694 substr = va_arg(args_copy, const char *);
695 if (substr == NULL) {
696 continue;
697 }
698 size_t substr_len = strlen(substr);
699 if (SIZE_MAX - total_size < substr_len) {
700 return; // Would overflow.
701 }
702 total_size += substr_len;
703 }
704 va_end(args_copy);
705 if (total_size == SIZE_MAX) {
706 return; // Would overflow.
707 }
708 total_size += 1; // NUL terminator.
709 if ((buf = malloc(total_size)) == NULL) {
710 return;
711 }
712 buf[0] = '\0';
713 for (size_t i = 0; i < num; i++) {
714 substr = va_arg(args, const char *);
715 if (substr == NULL) {
716 continue;
717 }
718 if (OPENSSL_strlcat(buf, substr, total_size) >= total_size) {
719 assert(0); // should not be possible.
720 }
721 }
722 va_end(args);
723 err_set_error_data(buf);
724 }
725
ERR_add_error_data(unsigned count,...)726 void ERR_add_error_data(unsigned count, ...) {
727 va_list args;
728 va_start(args, count);
729 err_add_error_vdata(count, args);
730 va_end(args);
731 }
732
ERR_add_error_dataf(const char * format,...)733 void ERR_add_error_dataf(const char *format, ...) {
734 char *buf = NULL;
735 va_list ap;
736
737 va_start(ap, format);
738 if (OPENSSL_vasprintf_internal(&buf, format, ap, /*system_malloc=*/1) == -1) {
739 return;
740 }
741 va_end(ap);
742
743 err_set_error_data(buf);
744 }
745
ERR_set_error_data(char * data,int flags)746 void ERR_set_error_data(char *data, int flags) {
747 if (!(flags & ERR_FLAG_STRING)) {
748 // We do not support non-string error data.
749 assert(0);
750 return;
751 }
752 // Disable deprecated functions on msvc so it doesn't complain about strdup.
753 OPENSSL_MSVC_PRAGMA(warning(push))
754 OPENSSL_MSVC_PRAGMA(warning(disable : 4996))
755 // We can not use OPENSSL_strdup because we don't want to call OPENSSL_malloc,
756 // which can affect the error stack.
757 char *copy = strdup(data);
758 OPENSSL_MSVC_PRAGMA(warning(pop))
759 if (copy != NULL) {
760 err_set_error_data(copy);
761 }
762 if (flags & ERR_FLAG_MALLOCED) {
763 // We can not take ownership of |data| directly because it is allocated with
764 // |OPENSSL_malloc| and we will free it with system |free| later.
765 OPENSSL_free(data);
766 }
767 }
768
ERR_set_mark(void)769 int ERR_set_mark(void) {
770 ERR_STATE *const state = err_get_state();
771
772 if (state == NULL || state->bottom == state->top) {
773 return 0;
774 }
775 state->errors[state->top].mark = 1;
776 return 1;
777 }
778
ERR_pop_to_mark(void)779 int ERR_pop_to_mark(void) {
780 ERR_STATE *const state = err_get_state();
781
782 if (state == NULL) {
783 return 0;
784 }
785
786 while (state->bottom != state->top) {
787 struct err_error_st *error = &state->errors[state->top];
788
789 if (error->mark) {
790 error->mark = 0;
791 return 1;
792 }
793
794 err_clear(error);
795 if (state->top == 0) {
796 state->top = ERR_NUM_ERRORS - 1;
797 } else {
798 state->top--;
799 }
800 }
801
802 return 0;
803 }
804
ERR_load_crypto_strings(void)805 void ERR_load_crypto_strings(void) {}
806
ERR_free_strings(void)807 void ERR_free_strings(void) {}
808
ERR_load_BIO_strings(void)809 void ERR_load_BIO_strings(void) {}
810
ERR_load_ERR_strings(void)811 void ERR_load_ERR_strings(void) {}
812
ERR_load_RAND_strings(void)813 void ERR_load_RAND_strings(void) {}
814
815 struct err_save_state_st {
816 struct err_error_st *errors;
817 size_t num_errors;
818 };
819
ERR_SAVE_STATE_free(ERR_SAVE_STATE * state)820 void ERR_SAVE_STATE_free(ERR_SAVE_STATE *state) {
821 if (state == NULL) {
822 return;
823 }
824 for (size_t i = 0; i < state->num_errors; i++) {
825 err_clear(&state->errors[i]);
826 }
827 free(state->errors);
828 free(state);
829 }
830
ERR_save_state(void)831 ERR_SAVE_STATE *ERR_save_state(void) {
832 ERR_STATE *const state = err_get_state();
833 if (state == NULL || state->top == state->bottom) {
834 return NULL;
835 }
836
837 ERR_SAVE_STATE *ret = malloc(sizeof(ERR_SAVE_STATE));
838 if (ret == NULL) {
839 return NULL;
840 }
841
842 // Errors are stored in the range (bottom, top].
843 size_t num_errors = state->top >= state->bottom
844 ? state->top - state->bottom
845 : ERR_NUM_ERRORS + state->top - state->bottom;
846 assert(num_errors < ERR_NUM_ERRORS);
847 ret->errors = malloc(num_errors * sizeof(struct err_error_st));
848 if (ret->errors == NULL) {
849 free(ret);
850 return NULL;
851 }
852 OPENSSL_memset(ret->errors, 0, num_errors * sizeof(struct err_error_st));
853 ret->num_errors = num_errors;
854
855 for (size_t i = 0; i < num_errors; i++) {
856 size_t j = (state->bottom + i + 1) % ERR_NUM_ERRORS;
857 err_copy(&ret->errors[i], &state->errors[j]);
858 }
859 return ret;
860 }
861
ERR_restore_state(const ERR_SAVE_STATE * state)862 void ERR_restore_state(const ERR_SAVE_STATE *state) {
863 if (state == NULL || state->num_errors == 0) {
864 ERR_clear_error();
865 return;
866 }
867
868 if (state->num_errors >= ERR_NUM_ERRORS) {
869 abort();
870 }
871
872 ERR_STATE *const dst = err_get_state();
873 if (dst == NULL) {
874 return;
875 }
876
877 for (size_t i = 0; i < state->num_errors; i++) {
878 err_copy(&dst->errors[i], &state->errors[i]);
879 }
880 dst->top = (unsigned)(state->num_errors - 1);
881 dst->bottom = ERR_NUM_ERRORS - 1;
882 }
883