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
strdup_libc_malloc(const char * str)167 static char *strdup_libc_malloc(const char *str) {
168 // |strdup| is not in C until C23, so MSVC triggers deprecation warnings, and
169 // glibc and musl gate it on a feature macro. Reimplementing it is easier.
170 size_t len = strlen(str);
171 char *ret = reinterpret_cast<char *>(malloc(len + 1));
172 if (ret != NULL) {
173 memcpy(ret, str, len + 1);
174 }
175 return ret;
176 }
177
178 // err_clear clears the given queued error.
err_clear(struct err_error_st * error)179 static void err_clear(struct err_error_st *error) {
180 free(error->data);
181 OPENSSL_memset(error, 0, sizeof(struct err_error_st));
182 }
183
err_copy(struct err_error_st * dst,const struct err_error_st * src)184 static void err_copy(struct err_error_st *dst, const struct err_error_st *src) {
185 err_clear(dst);
186 dst->file = src->file;
187 if (src->data != NULL) {
188 // We can't use OPENSSL_strdup because we don't want to call OPENSSL_malloc,
189 // which can affect the error stack.
190 dst->data = strdup_libc_malloc(src->data);
191 }
192 dst->packed = src->packed;
193 dst->line = src->line;
194 }
195
196
197 // global_next_library contains the next custom library value to return.
198 static int global_next_library = ERR_NUM_LIBS;
199
200 // global_next_library_mutex protects |global_next_library| from concurrent
201 // updates.
202 static CRYPTO_MUTEX global_next_library_mutex = CRYPTO_MUTEX_INIT;
203
err_state_free(void * statep)204 static void err_state_free(void *statep) {
205 ERR_STATE *state = reinterpret_cast<ERR_STATE *>(statep);
206
207 if (state == NULL) {
208 return;
209 }
210
211 for (unsigned i = 0; i < ERR_NUM_ERRORS; i++) {
212 err_clear(&state->errors[i]);
213 }
214 free(state->to_free);
215 free(state);
216 }
217
218 // err_get_state gets the ERR_STATE object for the current thread.
err_get_state(void)219 static ERR_STATE *err_get_state(void) {
220 ERR_STATE *state = reinterpret_cast<ERR_STATE *>(
221 CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_ERR));
222 if (state == NULL) {
223 state = reinterpret_cast<ERR_STATE *>(malloc(sizeof(ERR_STATE)));
224 if (state == NULL) {
225 return NULL;
226 }
227 OPENSSL_memset(state, 0, sizeof(ERR_STATE));
228 if (!CRYPTO_set_thread_local(OPENSSL_THREAD_LOCAL_ERR, state,
229 err_state_free)) {
230 return NULL;
231 }
232 }
233
234 return state;
235 }
236
get_error_values(int inc,int top,const char ** file,int * line,const char ** data,int * flags)237 static uint32_t get_error_values(int inc, int top, const char **file, int *line,
238 const char **data, int *flags) {
239 unsigned i = 0;
240 ERR_STATE *state;
241 struct err_error_st *error;
242 uint32_t ret;
243
244 state = err_get_state();
245 if (state == NULL || state->bottom == state->top) {
246 return 0;
247 }
248
249 if (top) {
250 assert(!inc);
251 // last error
252 i = state->top;
253 } else {
254 i = (state->bottom + 1) % ERR_NUM_ERRORS;
255 }
256
257 error = &state->errors[i];
258 ret = error->packed;
259
260 if (file != NULL && line != NULL) {
261 if (error->file == NULL) {
262 *file = "NA";
263 *line = 0;
264 } else {
265 *file = error->file;
266 *line = error->line;
267 }
268 }
269
270 if (data != NULL) {
271 if (error->data == NULL) {
272 *data = "";
273 if (flags != NULL) {
274 *flags = 0;
275 }
276 } else {
277 *data = error->data;
278 if (flags != NULL) {
279 // Without |ERR_FLAG_MALLOCED|, rust-openssl assumes the string has a
280 // static lifetime. In both cases, we retain ownership of the string,
281 // and the caller is not expected to free it.
282 *flags = ERR_FLAG_STRING | ERR_FLAG_MALLOCED;
283 }
284 // If this error is being removed, take ownership of data from
285 // the error. The semantics are such that the caller doesn't
286 // take ownership either. Instead the error system takes
287 // ownership and retains it until the next call that affects the
288 // error queue.
289 if (inc) {
290 if (error->data != NULL) {
291 free(state->to_free);
292 state->to_free = error->data;
293 }
294 error->data = NULL;
295 }
296 }
297 }
298
299 if (inc) {
300 assert(!top);
301 err_clear(error);
302 state->bottom = i;
303 }
304
305 return ret;
306 }
307
ERR_get_error(void)308 uint32_t ERR_get_error(void) {
309 return get_error_values(1 /* inc */, 0 /* bottom */, NULL, NULL, NULL, NULL);
310 }
311
ERR_get_error_line(const char ** file,int * line)312 uint32_t ERR_get_error_line(const char **file, int *line) {
313 return get_error_values(1 /* inc */, 0 /* bottom */, file, line, NULL, NULL);
314 }
315
ERR_get_error_line_data(const char ** file,int * line,const char ** data,int * flags)316 uint32_t ERR_get_error_line_data(const char **file, int *line,
317 const char **data, int *flags) {
318 return get_error_values(1 /* inc */, 0 /* bottom */, file, line, data, flags);
319 }
320
ERR_peek_error(void)321 uint32_t ERR_peek_error(void) {
322 return get_error_values(0 /* peek */, 0 /* bottom */, NULL, NULL, NULL, NULL);
323 }
324
ERR_peek_error_line(const char ** file,int * line)325 uint32_t ERR_peek_error_line(const char **file, int *line) {
326 return get_error_values(0 /* peek */, 0 /* bottom */, file, line, NULL, NULL);
327 }
328
ERR_peek_error_line_data(const char ** file,int * line,const char ** data,int * flags)329 uint32_t ERR_peek_error_line_data(const char **file, int *line,
330 const char **data, int *flags) {
331 return get_error_values(0 /* peek */, 0 /* bottom */, file, line, data,
332 flags);
333 }
334
ERR_peek_last_error(void)335 uint32_t ERR_peek_last_error(void) {
336 return get_error_values(0 /* peek */, 1 /* top */, NULL, NULL, NULL, NULL);
337 }
338
ERR_peek_last_error_line(const char ** file,int * line)339 uint32_t ERR_peek_last_error_line(const char **file, int *line) {
340 return get_error_values(0 /* peek */, 1 /* top */, file, line, NULL, NULL);
341 }
342
ERR_peek_last_error_line_data(const char ** file,int * line,const char ** data,int * flags)343 uint32_t ERR_peek_last_error_line_data(const char **file, int *line,
344 const char **data, int *flags) {
345 return get_error_values(0 /* peek */, 1 /* top */, file, line, data, flags);
346 }
347
ERR_clear_error(void)348 void ERR_clear_error(void) {
349 ERR_STATE *const state = err_get_state();
350 unsigned i;
351
352 if (state == NULL) {
353 return;
354 }
355
356 for (i = 0; i < ERR_NUM_ERRORS; i++) {
357 err_clear(&state->errors[i]);
358 }
359 free(state->to_free);
360 state->to_free = NULL;
361
362 state->top = state->bottom = 0;
363 }
364
ERR_remove_thread_state(const CRYPTO_THREADID * tid)365 void ERR_remove_thread_state(const CRYPTO_THREADID *tid) {
366 if (tid != NULL) {
367 assert(0);
368 return;
369 }
370
371 ERR_clear_error();
372 }
373
ERR_get_next_error_library(void)374 int ERR_get_next_error_library(void) {
375 int ret;
376
377 CRYPTO_MUTEX_lock_write(&global_next_library_mutex);
378 ret = global_next_library++;
379 CRYPTO_MUTEX_unlock_write(&global_next_library_mutex);
380
381 return ret;
382 }
383
ERR_remove_state(unsigned long pid)384 void ERR_remove_state(unsigned long pid) { ERR_clear_error(); }
385
ERR_clear_system_error(void)386 void ERR_clear_system_error(void) { errno = 0; }
387
388 // err_string_cmp is a compare function for searching error values with
389 // |bsearch| in |err_string_lookup|.
err_string_cmp(const void * a,const void * b)390 static int err_string_cmp(const void *a, const void *b) {
391 const uint32_t a_key = *((const uint32_t *)a) >> 15;
392 const uint32_t b_key = *((const uint32_t *)b) >> 15;
393
394 if (a_key < b_key) {
395 return -1;
396 } else if (a_key > b_key) {
397 return 1;
398 } else {
399 return 0;
400 }
401 }
402
403 // err_string_lookup looks up the string associated with |lib| and |key| in
404 // |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)405 static const char *err_string_lookup(uint32_t lib, uint32_t key,
406 const uint32_t *values, size_t num_values,
407 const char *string_data) {
408 // |values| points to data in err_data.h, which is generated by
409 // err_data_generate.go. It's an array of uint32_t values. Each value has the
410 // following structure:
411 // | lib | key | offset |
412 // |6 bits| 11 bits | 15 bits |
413 //
414 // The |lib| value is a library identifier: one of the |ERR_LIB_*| values.
415 // The |key| is a reason code, depending on the context.
416 // The |offset| is the number of bytes from the start of |string_data| where
417 // the (NUL terminated) string for this value can be found.
418 //
419 // Values are sorted based on treating the |lib| and |key| part as an
420 // unsigned integer.
421 if (lib >= (1 << 6) || key >= (1 << 11)) {
422 return NULL;
423 }
424 uint32_t search_key = lib << 26 | key << 15;
425 const uint32_t *result = reinterpret_cast<const uint32_t *>(bsearch(
426 &search_key, values, num_values, sizeof(uint32_t), err_string_cmp));
427 if (result == NULL) {
428 return NULL;
429 }
430
431 return &string_data[(*result) & 0x7fff];
432 }
433
434 typedef struct library_name_st {
435 const char *str;
436 const char *symbol;
437 const char *reason_symbol;
438 } LIBRARY_NAME;
439
440 static const LIBRARY_NAME kLibraryNames[ERR_NUM_LIBS] = {
441 {"invalid library (0)", NULL, NULL},
442 {"unknown library", "NONE", "NONE_LIB"},
443 {"system library", "SYS", "SYS_LIB"},
444 {"bignum routines", "BN", "BN_LIB"},
445 {"RSA routines", "RSA", "RSA_LIB"},
446 {"Diffie-Hellman routines", "DH", "DH_LIB"},
447 {"public key routines", "EVP", "EVP_LIB"},
448 {"memory buffer routines", "BUF", "BUF_LIB"},
449 {"object identifier routines", "OBJ", "OBJ_LIB"},
450 {"PEM routines", "PEM", "PEM_LIB"},
451 {"DSA routines", "DSA", "DSA_LIB"},
452 {"X.509 certificate routines", "X509", "X509_LIB"},
453 {"ASN.1 encoding routines", "ASN1", "ASN1_LIB"},
454 {"configuration file routines", "CONF", "CONF_LIB"},
455 {"common libcrypto routines", "CRYPTO", "CRYPTO_LIB"},
456 {"elliptic curve routines", "EC", "EC_LIB"},
457 {"SSL routines", "SSL", "SSL_LIB"},
458 {"BIO routines", "BIO", "BIO_LIB"},
459 {"PKCS7 routines", "PKCS7", "PKCS7_LIB"},
460 {"PKCS8 routines", "PKCS8", "PKCS8_LIB"},
461 {"X509 V3 routines", "X509V3", "X509V3_LIB"},
462 {"random number generator", "RAND", "RAND_LIB"},
463 {"ENGINE routines", "ENGINE", "ENGINE_LIB"},
464 {"OCSP routines", "OCSP", "OCSP_LIB"},
465 {"UI routines", "UI", "UI_LIB"},
466 {"COMP routines", "COMP", "COMP_LIB"},
467 {"ECDSA routines", "ECDSA", "ECDSA_LIB"},
468 {"ECDH routines", "ECDH", "ECDH_LIB"},
469 {"HMAC routines", "HMAC", "HMAC_LIB"},
470 {"Digest functions", "DIGEST", "DIGEST_LIB"},
471 {"Cipher functions", "CIPHER", "CIPHER_LIB"},
472 {"HKDF functions", "HKDF", "HKDF_LIB"},
473 {"Trust Token functions", "TRUST_TOKEN", "TRUST_TOKEN_LIB"},
474 {"User defined functions", "USER", "USER_LIB"},
475 };
476
err_lib_error_string(uint32_t packed_error)477 static const char *err_lib_error_string(uint32_t packed_error) {
478 const uint32_t lib = ERR_GET_LIB(packed_error);
479 return lib >= ERR_NUM_LIBS ? NULL : kLibraryNames[lib].str;
480 }
481
ERR_lib_error_string(uint32_t packed_error)482 const char *ERR_lib_error_string(uint32_t packed_error) {
483 const char *ret = err_lib_error_string(packed_error);
484 return ret == NULL ? "unknown library" : ret;
485 }
486
ERR_lib_symbol_name(uint32_t packed_error)487 const char *ERR_lib_symbol_name(uint32_t packed_error) {
488 const uint32_t lib = ERR_GET_LIB(packed_error);
489 return lib >= ERR_NUM_LIBS ? NULL : kLibraryNames[lib].symbol;
490 }
491
ERR_func_error_string(uint32_t packed_error)492 const char *ERR_func_error_string(uint32_t packed_error) {
493 return "OPENSSL_internal";
494 }
495
err_reason_error_string(uint32_t packed_error,int symbol)496 static const char *err_reason_error_string(uint32_t packed_error, int symbol) {
497 const uint32_t lib = ERR_GET_LIB(packed_error);
498 const uint32_t reason = ERR_GET_REASON(packed_error);
499
500 if (lib == ERR_LIB_SYS) {
501 if (!symbol && reason < 127) {
502 return strerror(reason);
503 }
504 return NULL;
505 }
506
507 if (reason < ERR_NUM_LIBS) {
508 return symbol ? kLibraryNames[reason].reason_symbol
509 : kLibraryNames[reason].str;
510 }
511
512 if (reason < 100) {
513 // TODO(davidben): All our other reason strings match the symbol name. Only
514 // the common ones differ. Should we just consistently return the symbol
515 // name?
516 switch (reason) {
517 case ERR_R_MALLOC_FAILURE:
518 return symbol ? "MALLOC_FAILURE" : "malloc failure";
519 case ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED:
520 return symbol ? "SHOULD_NOT_HAVE_BEEN_CALLED"
521 : "function should not have been called";
522 case ERR_R_PASSED_NULL_PARAMETER:
523 return symbol ? "PASSED_NULL_PARAMETER" : "passed a null parameter";
524 case ERR_R_INTERNAL_ERROR:
525 return symbol ? "INTERNAL_ERROR" : "internal error";
526 case ERR_R_OVERFLOW:
527 return symbol ? "OVERFLOW" : "overflow";
528 default:
529 return NULL;
530 }
531 }
532
533 // Unlike OpenSSL, BoringSSL's reason strings already match symbol name, so we
534 // do not need to check |symbol|.
535 return err_string_lookup(lib, reason, kOpenSSLReasonValues,
536 kOpenSSLReasonValuesLen, kOpenSSLReasonStringData);
537 }
538
ERR_reason_error_string(uint32_t packed_error)539 const char *ERR_reason_error_string(uint32_t packed_error) {
540 const char *ret = err_reason_error_string(packed_error, /*symbol=*/0);
541 return ret == NULL ? "unknown error" : ret;
542 }
543
ERR_reason_symbol_name(uint32_t packed_error)544 const char *ERR_reason_symbol_name(uint32_t packed_error) {
545 return err_reason_error_string(packed_error, /*symbol=*/1);
546 }
547
ERR_error_string(uint32_t packed_error,char * ret)548 char *ERR_error_string(uint32_t packed_error, char *ret) {
549 static char buf[ERR_ERROR_STRING_BUF_LEN];
550
551 if (ret == NULL) {
552 // TODO(fork): remove this.
553 ret = buf;
554 }
555
556 #if !defined(NDEBUG)
557 // This is aimed to help catch callers who don't provide
558 // |ERR_ERROR_STRING_BUF_LEN| bytes of space.
559 OPENSSL_memset(ret, 0, ERR_ERROR_STRING_BUF_LEN);
560 #endif
561
562 return ERR_error_string_n(packed_error, ret, ERR_ERROR_STRING_BUF_LEN);
563 }
564
ERR_error_string_n(uint32_t packed_error,char * buf,size_t len)565 char *ERR_error_string_n(uint32_t packed_error, char *buf, size_t len) {
566 if (len == 0) {
567 return NULL;
568 }
569
570 unsigned lib = ERR_GET_LIB(packed_error);
571 unsigned reason = ERR_GET_REASON(packed_error);
572
573 const char *lib_str = err_lib_error_string(packed_error);
574 const char *reason_str = err_reason_error_string(packed_error, /*symbol=*/0);
575
576 char lib_buf[32], reason_buf[32];
577 if (lib_str == NULL) {
578 snprintf(lib_buf, sizeof(lib_buf), "lib(%u)", lib);
579 lib_str = lib_buf;
580 }
581
582 if (reason_str == NULL) {
583 snprintf(reason_buf, sizeof(reason_buf), "reason(%u)", reason);
584 reason_str = reason_buf;
585 }
586
587 int ret = snprintf(buf, len, "error:%08" PRIx32 ":%s:OPENSSL_internal:%s",
588 packed_error, lib_str, reason_str);
589 if (ret >= 0 && (size_t)ret >= len) {
590 // The output was truncated; make sure we always have 5 colon-separated
591 // fields, i.e. 4 colons.
592 static const unsigned num_colons = 4;
593 unsigned i;
594 char *s = buf;
595
596 if (len <= num_colons) {
597 // In this situation it's not possible to ensure that the correct number
598 // of colons are included in the output.
599 return buf;
600 }
601
602 for (i = 0; i < num_colons; i++) {
603 char *colon = strchr(s, ':');
604 char *last_pos = &buf[len - 1] - num_colons + i;
605
606 if (colon == NULL || colon > last_pos) {
607 // set colon |i| at last possible position (buf[len-1] is the
608 // terminating 0). If we're setting this colon, then all whole of the
609 // rest of the string must be colons in order to have the correct
610 // number.
611 OPENSSL_memset(last_pos, ':', num_colons - i);
612 break;
613 }
614
615 s = colon + 1;
616 }
617 }
618
619 return buf;
620 }
621
ERR_print_errors_cb(ERR_print_errors_callback_t callback,void * ctx)622 void ERR_print_errors_cb(ERR_print_errors_callback_t callback, void *ctx) {
623 char buf[ERR_ERROR_STRING_BUF_LEN];
624 char buf2[1024];
625 const char *file, *data;
626 int line, flags;
627 uint32_t packed_error;
628
629 // thread_hash is the least-significant bits of the |ERR_STATE| pointer value
630 // for this thread.
631 const unsigned long thread_hash = (uintptr_t)err_get_state();
632
633 for (;;) {
634 packed_error = ERR_get_error_line_data(&file, &line, &data, &flags);
635 if (packed_error == 0) {
636 break;
637 }
638
639 ERR_error_string_n(packed_error, buf, sizeof(buf));
640 snprintf(buf2, sizeof(buf2), "%lu:%s:%s:%d:%s\n", thread_hash, buf, file,
641 line, (flags & ERR_FLAG_STRING) ? data : "");
642 if (callback(buf2, strlen(buf2), ctx) <= 0) {
643 break;
644 }
645 }
646 }
647
print_errors_to_file(const char * msg,size_t msg_len,void * ctx)648 static int print_errors_to_file(const char *msg, size_t msg_len, void *ctx) {
649 assert(msg[msg_len] == '\0');
650 FILE *fp = reinterpret_cast<FILE *>(ctx);
651 int res = fputs(msg, fp);
652 return res < 0 ? 0 : 1;
653 }
654
ERR_print_errors_fp(FILE * file)655 void ERR_print_errors_fp(FILE *file) {
656 ERR_print_errors_cb(print_errors_to_file, file);
657 }
658
659 // err_set_error_data sets the data on the most recent error.
err_set_error_data(char * data)660 static void err_set_error_data(char *data) {
661 ERR_STATE *const state = err_get_state();
662 struct err_error_st *error;
663
664 if (state == NULL || state->top == state->bottom) {
665 free(data);
666 return;
667 }
668
669 error = &state->errors[state->top];
670
671 free(error->data);
672 error->data = data;
673 }
674
ERR_put_error(int library,int unused,int reason,const char * file,unsigned line)675 void ERR_put_error(int library, int unused, int reason, const char *file,
676 unsigned line) {
677 ERR_STATE *const state = err_get_state();
678 struct err_error_st *error;
679
680 if (state == NULL) {
681 return;
682 }
683
684 if (library == ERR_LIB_SYS && reason == 0) {
685 #if defined(OPENSSL_WINDOWS)
686 reason = GetLastError();
687 #else
688 reason = errno;
689 #endif
690 }
691
692 state->top = (state->top + 1) % ERR_NUM_ERRORS;
693 if (state->top == state->bottom) {
694 state->bottom = (state->bottom + 1) % ERR_NUM_ERRORS;
695 }
696
697 error = &state->errors[state->top];
698 err_clear(error);
699 error->file = file;
700 error->line = line;
701 error->packed = ERR_PACK(library, reason);
702 }
703
704 // ERR_add_error_data_vdata takes a variable number of const char* pointers,
705 // concatenates them and sets the result as the data on the most recent
706 // error.
err_add_error_vdata(unsigned num,va_list args)707 static void err_add_error_vdata(unsigned num, va_list args) {
708 size_t total_size = 0;
709 const char *substr;
710 char *buf;
711
712 va_list args_copy;
713 va_copy(args_copy, args);
714 for (size_t i = 0; i < num; i++) {
715 substr = va_arg(args_copy, const char *);
716 if (substr == NULL) {
717 continue;
718 }
719 size_t substr_len = strlen(substr);
720 if (SIZE_MAX - total_size < substr_len) {
721 return; // Would overflow.
722 }
723 total_size += substr_len;
724 }
725 va_end(args_copy);
726 if (total_size == SIZE_MAX) {
727 return; // Would overflow.
728 }
729 total_size += 1; // NUL terminator.
730 if ((buf = reinterpret_cast<char *>(malloc(total_size))) == NULL) {
731 return;
732 }
733 buf[0] = '\0';
734 for (size_t i = 0; i < num; i++) {
735 substr = va_arg(args, const char *);
736 if (substr == NULL) {
737 continue;
738 }
739 if (OPENSSL_strlcat(buf, substr, total_size) >= total_size) {
740 assert(0); // should not be possible.
741 }
742 }
743 va_end(args);
744 err_set_error_data(buf);
745 }
746
ERR_add_error_data(unsigned count,...)747 void ERR_add_error_data(unsigned count, ...) {
748 va_list args;
749 va_start(args, count);
750 err_add_error_vdata(count, args);
751 va_end(args);
752 }
753
ERR_add_error_dataf(const char * format,...)754 void ERR_add_error_dataf(const char *format, ...) {
755 char *buf = NULL;
756 va_list ap;
757
758 va_start(ap, format);
759 if (OPENSSL_vasprintf_internal(&buf, format, ap, /*system_malloc=*/1) == -1) {
760 return;
761 }
762 va_end(ap);
763
764 err_set_error_data(buf);
765 }
766
ERR_set_error_data(char * data,int flags)767 void ERR_set_error_data(char *data, int flags) {
768 if (!(flags & ERR_FLAG_STRING)) {
769 // We do not support non-string error data.
770 assert(0);
771 return;
772 }
773 // We can not use OPENSSL_strdup because we don't want to call OPENSSL_malloc,
774 // which can affect the error stack.
775 char *copy = strdup_libc_malloc(data);
776 if (copy != NULL) {
777 err_set_error_data(copy);
778 }
779 if (flags & ERR_FLAG_MALLOCED) {
780 // We can not take ownership of |data| directly because it is allocated with
781 // |OPENSSL_malloc| and we will free it with system |free| later.
782 OPENSSL_free(data);
783 }
784 }
785
ERR_set_mark(void)786 int ERR_set_mark(void) {
787 ERR_STATE *const state = err_get_state();
788
789 if (state == NULL || state->bottom == state->top) {
790 return 0;
791 }
792 state->errors[state->top].mark = 1;
793 return 1;
794 }
795
ERR_pop_to_mark(void)796 int ERR_pop_to_mark(void) {
797 ERR_STATE *const state = err_get_state();
798
799 if (state == NULL) {
800 return 0;
801 }
802
803 while (state->bottom != state->top) {
804 struct err_error_st *error = &state->errors[state->top];
805
806 if (error->mark) {
807 error->mark = 0;
808 return 1;
809 }
810
811 err_clear(error);
812 if (state->top == 0) {
813 state->top = ERR_NUM_ERRORS - 1;
814 } else {
815 state->top--;
816 }
817 }
818
819 return 0;
820 }
821
ERR_load_crypto_strings(void)822 void ERR_load_crypto_strings(void) {}
823
ERR_free_strings(void)824 void ERR_free_strings(void) {}
825
ERR_load_BIO_strings(void)826 void ERR_load_BIO_strings(void) {}
827
ERR_load_ERR_strings(void)828 void ERR_load_ERR_strings(void) {}
829
ERR_load_RAND_strings(void)830 void ERR_load_RAND_strings(void) {}
831
832 struct err_save_state_st {
833 struct err_error_st *errors;
834 size_t num_errors;
835 };
836
ERR_SAVE_STATE_free(ERR_SAVE_STATE * state)837 void ERR_SAVE_STATE_free(ERR_SAVE_STATE *state) {
838 if (state == NULL) {
839 return;
840 }
841 for (size_t i = 0; i < state->num_errors; i++) {
842 err_clear(&state->errors[i]);
843 }
844 free(state->errors);
845 free(state);
846 }
847
ERR_save_state(void)848 ERR_SAVE_STATE *ERR_save_state(void) {
849 ERR_STATE *const state = err_get_state();
850 if (state == NULL || state->top == state->bottom) {
851 return NULL;
852 }
853
854 ERR_SAVE_STATE *ret =
855 reinterpret_cast<ERR_SAVE_STATE *>(malloc(sizeof(ERR_SAVE_STATE)));
856 if (ret == NULL) {
857 return NULL;
858 }
859
860 // Errors are stored in the range (bottom, top].
861 size_t num_errors = state->top >= state->bottom
862 ? state->top - state->bottom
863 : ERR_NUM_ERRORS + state->top - state->bottom;
864 assert(num_errors < ERR_NUM_ERRORS);
865 ret->errors = reinterpret_cast<err_error_st *>(
866 malloc(num_errors * sizeof(struct err_error_st)));
867 if (ret->errors == NULL) {
868 free(ret);
869 return NULL;
870 }
871 OPENSSL_memset(ret->errors, 0, num_errors * sizeof(struct err_error_st));
872 ret->num_errors = num_errors;
873
874 for (size_t i = 0; i < num_errors; i++) {
875 size_t j = (state->bottom + i + 1) % ERR_NUM_ERRORS;
876 err_copy(&ret->errors[i], &state->errors[j]);
877 }
878 return ret;
879 }
880
ERR_restore_state(const ERR_SAVE_STATE * state)881 void ERR_restore_state(const ERR_SAVE_STATE *state) {
882 if (state == NULL || state->num_errors == 0) {
883 ERR_clear_error();
884 return;
885 }
886
887 if (state->num_errors >= ERR_NUM_ERRORS) {
888 abort();
889 }
890
891 ERR_STATE *const dst = err_get_state();
892 if (dst == NULL) {
893 return;
894 }
895
896 for (size_t i = 0; i < state->num_errors; i++) {
897 err_copy(&dst->errors[i], &state->errors[i]);
898 }
899 dst->top = (unsigned)(state->num_errors - 1);
900 dst->bottom = ERR_NUM_ERRORS - 1;
901 }
902