xref: /aosp_15_r20/external/cronet/third_party/boringssl/src/crypto/err/err.c (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 
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 typedef struct library_name_st {
432   const char *str;
433   const char *symbol;
434   const char *reason_symbol;
435 } LIBRARY_NAME;
436 
437 static const LIBRARY_NAME kLibraryNames[ERR_NUM_LIBS] = {
438     {"invalid library (0)", NULL, NULL},
439     {"unknown library", "NONE", "NONE_LIB"},
440     {"system library", "SYS", "SYS_LIB"},
441     {"bignum routines", "BN", "BN_LIB"},
442     {"RSA routines", "RSA", "RSA_LIB"},
443     {"Diffie-Hellman routines", "DH", "DH_LIB"},
444     {"public key routines", "EVP", "EVP_LIB"},
445     {"memory buffer routines", "BUF", "BUF_LIB"},
446     {"object identifier routines", "OBJ", "OBJ_LIB"},
447     {"PEM routines", "PEM", "PEM_LIB"},
448     {"DSA routines", "DSA", "DSA_LIB"},
449     {"X.509 certificate routines", "X509", "X509_LIB"},
450     {"ASN.1 encoding routines", "ASN1", "ASN1_LIB"},
451     {"configuration file routines", "CONF", "CONF_LIB"},
452     {"common libcrypto routines", "CRYPTO", "CRYPTO_LIB"},
453     {"elliptic curve routines", "EC", "EC_LIB"},
454     {"SSL routines", "SSL", "SSL_LIB"},
455     {"BIO routines", "BIO", "BIO_LIB"},
456     {"PKCS7 routines", "PKCS7", "PKCS7_LIB"},
457     {"PKCS8 routines", "PKCS8", "PKCS8_LIB"},
458     {"X509 V3 routines", "X509V3", "X509V3_LIB"},
459     {"random number generator", "RAND", "RAND_LIB"},
460     {"ENGINE routines", "ENGINE", "ENGINE_LIB"},
461     {"OCSP routines", "OCSP", "OCSP_LIB"},
462     {"UI routines", "UI", "UI_LIB"},
463     {"COMP routines", "COMP", "COMP_LIB"},
464     {"ECDSA routines", "ECDSA", "ECDSA_LIB"},
465     {"ECDH routines", "ECDH", "ECDH_LIB"},
466     {"HMAC routines", "HMAC", "HMAC_LIB"},
467     {"Digest functions", "DIGEST", "DIGEST_LIB"},
468     {"Cipher functions", "CIPHER", "CIPHER_LIB"},
469     {"HKDF functions", "HKDF", "HKDF_LIB"},
470     {"Trust Token functions", "TRUST_TOKEN", "TRUST_TOKEN_LIB"},
471     {"User defined functions", "USER", "USER_LIB"},
472 };
473 
err_lib_error_string(uint32_t packed_error)474 static const char *err_lib_error_string(uint32_t packed_error) {
475   const uint32_t lib = ERR_GET_LIB(packed_error);
476   return lib >= ERR_NUM_LIBS ? NULL : kLibraryNames[lib].str;
477 }
478 
ERR_lib_error_string(uint32_t packed_error)479 const char *ERR_lib_error_string(uint32_t packed_error) {
480   const char *ret = err_lib_error_string(packed_error);
481   return ret == NULL ? "unknown library" : ret;
482 }
483 
ERR_lib_symbol_name(uint32_t packed_error)484 const char *ERR_lib_symbol_name(uint32_t packed_error) {
485   const uint32_t lib = ERR_GET_LIB(packed_error);
486   return lib >= ERR_NUM_LIBS ? NULL : kLibraryNames[lib].symbol;
487 }
488 
ERR_func_error_string(uint32_t packed_error)489 const char *ERR_func_error_string(uint32_t packed_error) {
490   return "OPENSSL_internal";
491 }
492 
err_reason_error_string(uint32_t packed_error,int symbol)493 static const char *err_reason_error_string(uint32_t packed_error, int symbol) {
494   const uint32_t lib = ERR_GET_LIB(packed_error);
495   const uint32_t reason = ERR_GET_REASON(packed_error);
496 
497   if (lib == ERR_LIB_SYS) {
498     if (!symbol && reason < 127) {
499       return strerror(reason);
500     }
501     return NULL;
502   }
503 
504   if (reason < ERR_NUM_LIBS) {
505     return symbol ? kLibraryNames[reason].reason_symbol
506                   : kLibraryNames[reason].str;
507   }
508 
509   if (reason < 100) {
510     // TODO(davidben): All our other reason strings match the symbol name. Only
511     // the common ones differ. Should we just consistently return the symbol
512     // name?
513     switch (reason) {
514       case ERR_R_MALLOC_FAILURE:
515         return symbol ? "MALLOC_FAILURE" : "malloc failure";
516       case ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED:
517         return symbol ? "SHOULD_NOT_HAVE_BEEN_CALLED"
518                       : "function should not have been called";
519       case ERR_R_PASSED_NULL_PARAMETER:
520         return symbol ? "PASSED_NULL_PARAMETER" : "passed a null parameter";
521       case ERR_R_INTERNAL_ERROR:
522         return symbol ? "INTERNAL_ERROR" : "internal error";
523       case ERR_R_OVERFLOW:
524         return symbol ? "OVERFLOW" : "overflow";
525       default:
526         return NULL;
527     }
528   }
529 
530   // Unlike OpenSSL, BoringSSL's reason strings already match symbol name, so we
531   // do not need to check |symbol|.
532   return err_string_lookup(lib, reason, kOpenSSLReasonValues,
533                            kOpenSSLReasonValuesLen, kOpenSSLReasonStringData);
534 }
535 
ERR_reason_error_string(uint32_t packed_error)536 const char *ERR_reason_error_string(uint32_t packed_error) {
537   const char *ret = err_reason_error_string(packed_error, /*symbol=*/0);
538   return ret == NULL ? "unknown error" : ret;
539 }
540 
ERR_reason_symbol_name(uint32_t packed_error)541 const char *ERR_reason_symbol_name(uint32_t packed_error) {
542   return err_reason_error_string(packed_error, /*symbol=*/1);
543 }
544 
ERR_error_string(uint32_t packed_error,char * ret)545 char *ERR_error_string(uint32_t packed_error, char *ret) {
546   static char buf[ERR_ERROR_STRING_BUF_LEN];
547 
548   if (ret == NULL) {
549     // TODO(fork): remove this.
550     ret = buf;
551   }
552 
553 #if !defined(NDEBUG)
554   // This is aimed to help catch callers who don't provide
555   // |ERR_ERROR_STRING_BUF_LEN| bytes of space.
556   OPENSSL_memset(ret, 0, ERR_ERROR_STRING_BUF_LEN);
557 #endif
558 
559   return ERR_error_string_n(packed_error, ret, ERR_ERROR_STRING_BUF_LEN);
560 }
561 
ERR_error_string_n(uint32_t packed_error,char * buf,size_t len)562 char *ERR_error_string_n(uint32_t packed_error, char *buf, size_t len) {
563   if (len == 0) {
564     return NULL;
565   }
566 
567   unsigned lib = ERR_GET_LIB(packed_error);
568   unsigned reason = ERR_GET_REASON(packed_error);
569 
570   const char *lib_str = err_lib_error_string(packed_error);
571   const char *reason_str = err_reason_error_string(packed_error, /*symbol=*/0);
572 
573   char lib_buf[32], reason_buf[32];
574   if (lib_str == NULL) {
575     snprintf(lib_buf, sizeof(lib_buf), "lib(%u)", lib);
576     lib_str = lib_buf;
577   }
578 
579   if (reason_str == NULL) {
580     snprintf(reason_buf, sizeof(reason_buf), "reason(%u)", reason);
581     reason_str = reason_buf;
582   }
583 
584   int ret = snprintf(buf, len, "error:%08" PRIx32 ":%s:OPENSSL_internal:%s",
585                      packed_error, lib_str, reason_str);
586   if (ret >= 0 && (size_t)ret >= len) {
587     // The output was truncated; make sure we always have 5 colon-separated
588     // fields, i.e. 4 colons.
589     static const unsigned num_colons = 4;
590     unsigned i;
591     char *s = buf;
592 
593     if (len <= num_colons) {
594       // In this situation it's not possible to ensure that the correct number
595       // of colons are included in the output.
596       return buf;
597     }
598 
599     for (i = 0; i < num_colons; i++) {
600       char *colon = strchr(s, ':');
601       char *last_pos = &buf[len - 1] - num_colons + i;
602 
603       if (colon == NULL || colon > last_pos) {
604         // set colon |i| at last possible position (buf[len-1] is the
605         // terminating 0). If we're setting this colon, then all whole of the
606         // rest of the string must be colons in order to have the correct
607         // number.
608         OPENSSL_memset(last_pos, ':', num_colons - i);
609         break;
610       }
611 
612       s = colon + 1;
613     }
614   }
615 
616   return buf;
617 }
618 
ERR_print_errors_cb(ERR_print_errors_callback_t callback,void * ctx)619 void ERR_print_errors_cb(ERR_print_errors_callback_t callback, void *ctx) {
620   char buf[ERR_ERROR_STRING_BUF_LEN];
621   char buf2[1024];
622   const char *file, *data;
623   int line, flags;
624   uint32_t packed_error;
625 
626   // thread_hash is the least-significant bits of the |ERR_STATE| pointer value
627   // for this thread.
628   const unsigned long thread_hash = (uintptr_t) err_get_state();
629 
630   for (;;) {
631     packed_error = ERR_get_error_line_data(&file, &line, &data, &flags);
632     if (packed_error == 0) {
633       break;
634     }
635 
636     ERR_error_string_n(packed_error, buf, sizeof(buf));
637     snprintf(buf2, sizeof(buf2), "%lu:%s:%s:%d:%s\n", thread_hash, buf, file,
638              line, (flags & ERR_FLAG_STRING) ? data : "");
639     if (callback(buf2, strlen(buf2), ctx) <= 0) {
640       break;
641     }
642   }
643 }
644 
print_errors_to_file(const char * msg,size_t msg_len,void * ctx)645 static int print_errors_to_file(const char* msg, size_t msg_len, void* ctx) {
646   assert(msg[msg_len] == '\0');
647   FILE* fp = ctx;
648   int res = fputs(msg, fp);
649   return res < 0 ? 0 : 1;
650 }
651 
ERR_print_errors_fp(FILE * file)652 void ERR_print_errors_fp(FILE *file) {
653   ERR_print_errors_cb(print_errors_to_file, file);
654 }
655 
656 // err_set_error_data sets the data on the most recent error.
err_set_error_data(char * data)657 static void err_set_error_data(char *data) {
658   ERR_STATE *const state = err_get_state();
659   struct err_error_st *error;
660 
661   if (state == NULL || state->top == state->bottom) {
662     free(data);
663     return;
664   }
665 
666   error = &state->errors[state->top];
667 
668   free(error->data);
669   error->data = data;
670 }
671 
ERR_put_error(int library,int unused,int reason,const char * file,unsigned line)672 void ERR_put_error(int library, int unused, int reason, const char *file,
673                    unsigned line) {
674   ERR_STATE *const state = err_get_state();
675   struct err_error_st *error;
676 
677   if (state == NULL) {
678     return;
679   }
680 
681   if (library == ERR_LIB_SYS && reason == 0) {
682 #if defined(OPENSSL_WINDOWS)
683     reason = GetLastError();
684 #else
685     reason = errno;
686 #endif
687   }
688 
689   state->top = (state->top + 1) % ERR_NUM_ERRORS;
690   if (state->top == state->bottom) {
691     state->bottom = (state->bottom + 1) % ERR_NUM_ERRORS;
692   }
693 
694   error = &state->errors[state->top];
695   err_clear(error);
696   error->file = file;
697   error->line = line;
698   error->packed = ERR_PACK(library, reason);
699 }
700 
701 // ERR_add_error_data_vdata takes a variable number of const char* pointers,
702 // concatenates them and sets the result as the data on the most recent
703 // error.
err_add_error_vdata(unsigned num,va_list args)704 static void err_add_error_vdata(unsigned num, va_list args) {
705   size_t total_size = 0;
706   const char *substr;
707   char *buf;
708 
709   va_list args_copy;
710   va_copy(args_copy, args);
711   for (size_t i = 0; i < num; i++) {
712     substr = va_arg(args_copy, const char *);
713     if (substr == NULL) {
714       continue;
715     }
716     size_t substr_len = strlen(substr);
717     if (SIZE_MAX - total_size < substr_len) {
718       return; // Would overflow.
719     }
720     total_size += substr_len;
721   }
722   va_end(args_copy);
723   if (total_size == SIZE_MAX) {
724       return; // Would overflow.
725   }
726   total_size += 1; // NUL terminator.
727   if ((buf = malloc(total_size)) == NULL) {
728     return;
729   }
730   buf[0] = '\0';
731   for (size_t i = 0; i < num; i++) {
732     substr = va_arg(args, const char *);
733     if (substr == NULL) {
734       continue;
735     }
736     if (OPENSSL_strlcat(buf, substr, total_size) >= total_size) {
737       assert(0); // should not be possible.
738     }
739   }
740   va_end(args);
741   err_set_error_data(buf);
742 }
743 
ERR_add_error_data(unsigned count,...)744 void ERR_add_error_data(unsigned count, ...) {
745   va_list args;
746   va_start(args, count);
747   err_add_error_vdata(count, args);
748   va_end(args);
749 }
750 
ERR_add_error_dataf(const char * format,...)751 void ERR_add_error_dataf(const char *format, ...) {
752   char *buf = NULL;
753   va_list ap;
754 
755   va_start(ap, format);
756   if (OPENSSL_vasprintf_internal(&buf, format, ap, /*system_malloc=*/1) == -1) {
757     return;
758   }
759   va_end(ap);
760 
761   err_set_error_data(buf);
762 }
763 
ERR_set_error_data(char * data,int flags)764 void ERR_set_error_data(char *data, int flags) {
765   if (!(flags & ERR_FLAG_STRING)) {
766     // We do not support non-string error data.
767     assert(0);
768     return;
769   }
770   // Disable deprecated functions on msvc so it doesn't complain about strdup.
771   OPENSSL_MSVC_PRAGMA(warning(push))
772   OPENSSL_MSVC_PRAGMA(warning(disable : 4996))
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(data);
776   OPENSSL_MSVC_PRAGMA(warning(pop))
777   if (copy != NULL) {
778     err_set_error_data(copy);
779   }
780   if (flags & ERR_FLAG_MALLOCED) {
781     // We can not take ownership of |data| directly because it is allocated with
782     // |OPENSSL_malloc| and we will free it with system |free| later.
783     OPENSSL_free(data);
784   }
785 }
786 
ERR_set_mark(void)787 int ERR_set_mark(void) {
788   ERR_STATE *const state = err_get_state();
789 
790   if (state == NULL || state->bottom == state->top) {
791     return 0;
792   }
793   state->errors[state->top].mark = 1;
794   return 1;
795 }
796 
ERR_pop_to_mark(void)797 int ERR_pop_to_mark(void) {
798   ERR_STATE *const state = err_get_state();
799 
800   if (state == NULL) {
801     return 0;
802   }
803 
804   while (state->bottom != state->top) {
805     struct err_error_st *error = &state->errors[state->top];
806 
807     if (error->mark) {
808       error->mark = 0;
809       return 1;
810     }
811 
812     err_clear(error);
813     if (state->top == 0) {
814       state->top = ERR_NUM_ERRORS - 1;
815     } else {
816       state->top--;
817     }
818   }
819 
820   return 0;
821 }
822 
ERR_load_crypto_strings(void)823 void ERR_load_crypto_strings(void) {}
824 
ERR_free_strings(void)825 void ERR_free_strings(void) {}
826 
ERR_load_BIO_strings(void)827 void ERR_load_BIO_strings(void) {}
828 
ERR_load_ERR_strings(void)829 void ERR_load_ERR_strings(void) {}
830 
ERR_load_RAND_strings(void)831 void ERR_load_RAND_strings(void) {}
832 
833 struct err_save_state_st {
834   struct err_error_st *errors;
835   size_t num_errors;
836 };
837 
ERR_SAVE_STATE_free(ERR_SAVE_STATE * state)838 void ERR_SAVE_STATE_free(ERR_SAVE_STATE *state) {
839   if (state == NULL) {
840     return;
841   }
842   for (size_t i = 0; i < state->num_errors; i++) {
843     err_clear(&state->errors[i]);
844   }
845   free(state->errors);
846   free(state);
847 }
848 
ERR_save_state(void)849 ERR_SAVE_STATE *ERR_save_state(void) {
850   ERR_STATE *const state = err_get_state();
851   if (state == NULL || state->top == state->bottom) {
852     return NULL;
853   }
854 
855   ERR_SAVE_STATE *ret = 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 = malloc(num_errors * sizeof(struct err_error_st));
866   if (ret->errors == NULL) {
867     free(ret);
868     return NULL;
869   }
870   OPENSSL_memset(ret->errors, 0, num_errors * sizeof(struct err_error_st));
871   ret->num_errors = num_errors;
872 
873   for (size_t i = 0; i < num_errors; i++) {
874     size_t j = (state->bottom + i + 1) % ERR_NUM_ERRORS;
875     err_copy(&ret->errors[i], &state->errors[j]);
876   }
877   return ret;
878 }
879 
ERR_restore_state(const ERR_SAVE_STATE * state)880 void ERR_restore_state(const ERR_SAVE_STATE *state) {
881   if (state == NULL || state->num_errors == 0) {
882     ERR_clear_error();
883     return;
884   }
885 
886   if (state->num_errors >= ERR_NUM_ERRORS) {
887     abort();
888   }
889 
890   ERR_STATE *const dst = err_get_state();
891   if (dst == NULL) {
892     return;
893   }
894 
895   for (size_t i = 0; i < state->num_errors; i++) {
896     err_copy(&dst->errors[i], &state->errors[i]);
897   }
898   dst->top = (unsigned)(state->num_errors - 1);
899   dst->bottom = ERR_NUM_ERRORS - 1;
900 }
901