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