• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <openssl/err.h>
110 
111 #include <assert.h>
112 #include <errno.h>
113 #include <inttypes.h>
114 #include <string.h>
115 
116 #if defined(OPENSSL_WINDOWS)
117 OPENSSL_MSVC_PRAGMA(warning(push, 3))
118 #include <windows.h>
119 OPENSSL_MSVC_PRAGMA(warning(pop))
120 #endif
121 
122 #include <openssl/mem.h>
123 #include <openssl/thread.h>
124 
125 #include "../internal.h"
126 #include "./internal.h"
127 
128 
129 struct err_error_st {
130   // file contains the filename where the error occurred.
131   const char *file;
132   // data contains a NUL-terminated string with optional data. It must be freed
133   // with |OPENSSL_free|.
134   char *data;
135   // packed contains the error library and reason, as packed by ERR_PACK.
136   uint32_t packed;
137   // line contains the line number where the error occurred.
138   uint16_t line;
139   // mark indicates a reversion point in the queue. See |ERR_pop_to_mark|.
140   unsigned mark : 1;
141 };
142 
143 // ERR_STATE contains the per-thread, error queue.
144 typedef struct err_state_st {
145   // errors contains the ERR_NUM_ERRORS most recent errors, organised as a ring
146   // buffer.
147   struct err_error_st errors[ERR_NUM_ERRORS];
148   // top contains the index one past the most recent error. If |top| equals
149   // |bottom| then the queue is empty.
150   unsigned top;
151   // bottom contains the index of the last error in the queue.
152   unsigned bottom;
153 
154   // to_free, if not NULL, contains a pointer owned by this structure that was
155   // previously a |data| pointer of one of the elements of |errors|.
156   void *to_free;
157 } ERR_STATE;
158 
159 extern const uint32_t kOpenSSLReasonValues[];
160 extern const size_t kOpenSSLReasonValuesLen;
161 extern const char kOpenSSLReasonStringData[];
162 
163 // err_clear clears the given queued error.
err_clear(struct err_error_st * error)164 static void err_clear(struct err_error_st *error) {
165   OPENSSL_free(error->data);
166   OPENSSL_memset(error, 0, sizeof(struct err_error_st));
167 }
168 
err_copy(struct err_error_st * dst,const struct err_error_st * src)169 static void err_copy(struct err_error_st *dst, const struct err_error_st *src) {
170   err_clear(dst);
171   dst->file = src->file;
172   if (src->data != NULL) {
173     dst->data = OPENSSL_strdup(src->data);
174   }
175   dst->packed = src->packed;
176   dst->line = src->line;
177 }
178 
179 // global_next_library contains the next custom library value to return.
180 static int global_next_library = ERR_NUM_LIBS;
181 
182 // global_next_library_mutex protects |global_next_library| from concurrent
183 // updates.
184 static struct CRYPTO_STATIC_MUTEX global_next_library_mutex =
185     CRYPTO_STATIC_MUTEX_INIT;
186 
err_state_free(void * statep)187 static void err_state_free(void *statep) {
188   ERR_STATE *state = statep;
189 
190   if (state == NULL) {
191     return;
192   }
193 
194   for (unsigned i = 0; i < ERR_NUM_ERRORS; i++) {
195     err_clear(&state->errors[i]);
196   }
197   OPENSSL_free(state->to_free);
198   OPENSSL_free(state);
199 }
200 
201 // err_get_state gets the ERR_STATE object for the current thread.
err_get_state(void)202 static ERR_STATE *err_get_state(void) {
203   ERR_STATE *state = CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_ERR);
204   if (state == NULL) {
205     state = OPENSSL_malloc(sizeof(ERR_STATE));
206     if (state == NULL) {
207       return NULL;
208     }
209     OPENSSL_memset(state, 0, sizeof(ERR_STATE));
210     if (!CRYPTO_set_thread_local(OPENSSL_THREAD_LOCAL_ERR, state,
211                                  err_state_free)) {
212       return NULL;
213     }
214   }
215 
216   return state;
217 }
218 
get_error_values(int inc,int top,const char ** file,int * line,const char ** data,int * flags)219 static uint32_t get_error_values(int inc, int top, const char **file, int *line,
220                                  const char **data, int *flags) {
221   unsigned i = 0;
222   ERR_STATE *state;
223   struct err_error_st *error;
224   uint32_t ret;
225 
226   state = err_get_state();
227   if (state == NULL || state->bottom == state->top) {
228     return 0;
229   }
230 
231   if (top) {
232     assert(!inc);
233     // last error
234     i = state->top;
235   } else {
236     i = (state->bottom + 1) % ERR_NUM_ERRORS;
237   }
238 
239   error = &state->errors[i];
240   ret = error->packed;
241 
242   if (file != NULL && line != NULL) {
243     if (error->file == NULL) {
244       *file = "NA";
245       *line = 0;
246     } else {
247       *file = error->file;
248       *line = error->line;
249     }
250   }
251 
252   if (data != NULL) {
253     if (error->data == NULL) {
254       *data = "";
255       if (flags != NULL) {
256         *flags = 0;
257       }
258     } else {
259       *data = error->data;
260       if (flags != NULL) {
261         *flags = ERR_FLAG_STRING;
262       }
263       // If this error is being removed, take ownership of data from
264       // the error. The semantics are such that the caller doesn't
265       // take ownership either. Instead the error system takes
266       // ownership and retains it until the next call that affects the
267       // error queue.
268       if (inc) {
269         if (error->data != NULL) {
270           OPENSSL_free(state->to_free);
271           state->to_free = error->data;
272         }
273         error->data = NULL;
274       }
275     }
276   }
277 
278   if (inc) {
279     assert(!top);
280     err_clear(error);
281     state->bottom = i;
282   }
283 
284   return ret;
285 }
286 
ERR_get_error(void)287 uint32_t ERR_get_error(void) {
288   return get_error_values(1 /* inc */, 0 /* bottom */, NULL, NULL, NULL, NULL);
289 }
290 
ERR_get_error_line(const char ** file,int * line)291 uint32_t ERR_get_error_line(const char **file, int *line) {
292   return get_error_values(1 /* inc */, 0 /* bottom */, file, line, NULL, NULL);
293 }
294 
ERR_get_error_line_data(const char ** file,int * line,const char ** data,int * flags)295 uint32_t ERR_get_error_line_data(const char **file, int *line,
296                                  const char **data, int *flags) {
297   return get_error_values(1 /* inc */, 0 /* bottom */, file, line, data, flags);
298 }
299 
ERR_peek_error(void)300 uint32_t ERR_peek_error(void) {
301   return get_error_values(0 /* peek */, 0 /* bottom */, NULL, NULL, NULL, NULL);
302 }
303 
ERR_peek_error_line(const char ** file,int * line)304 uint32_t ERR_peek_error_line(const char **file, int *line) {
305   return get_error_values(0 /* peek */, 0 /* bottom */, file, line, NULL, NULL);
306 }
307 
ERR_peek_error_line_data(const char ** file,int * line,const char ** data,int * flags)308 uint32_t ERR_peek_error_line_data(const char **file, int *line,
309                                   const char **data, int *flags) {
310   return get_error_values(0 /* peek */, 0 /* bottom */, file, line, data,
311                           flags);
312 }
313 
ERR_peek_last_error(void)314 uint32_t ERR_peek_last_error(void) {
315   return get_error_values(0 /* peek */, 1 /* top */, NULL, NULL, NULL, NULL);
316 }
317 
ERR_peek_last_error_line(const char ** file,int * line)318 uint32_t ERR_peek_last_error_line(const char **file, int *line) {
319   return get_error_values(0 /* peek */, 1 /* top */, file, line, NULL, NULL);
320 }
321 
ERR_peek_last_error_line_data(const char ** file,int * line,const char ** data,int * flags)322 uint32_t ERR_peek_last_error_line_data(const char **file, int *line,
323                                        const char **data, int *flags) {
324   return get_error_values(0 /* peek */, 1 /* top */, file, line, data, flags);
325 }
326 
ERR_clear_error(void)327 void ERR_clear_error(void) {
328   ERR_STATE *const state = err_get_state();
329   unsigned i;
330 
331   if (state == NULL) {
332     return;
333   }
334 
335   for (i = 0; i < ERR_NUM_ERRORS; i++) {
336     err_clear(&state->errors[i]);
337   }
338   OPENSSL_free(state->to_free);
339   state->to_free = NULL;
340 
341   state->top = state->bottom = 0;
342 }
343 
ERR_remove_thread_state(const CRYPTO_THREADID * tid)344 void ERR_remove_thread_state(const CRYPTO_THREADID *tid) {
345   if (tid != NULL) {
346     assert(0);
347     return;
348   }
349 
350   ERR_clear_error();
351 }
352 
ERR_get_next_error_library(void)353 int ERR_get_next_error_library(void) {
354   int ret;
355 
356   CRYPTO_STATIC_MUTEX_lock_write(&global_next_library_mutex);
357   ret = global_next_library++;
358   CRYPTO_STATIC_MUTEX_unlock_write(&global_next_library_mutex);
359 
360   return ret;
361 }
362 
ERR_remove_state(unsigned long pid)363 void ERR_remove_state(unsigned long pid) {
364   ERR_clear_error();
365 }
366 
ERR_clear_system_error(void)367 void ERR_clear_system_error(void) {
368   errno = 0;
369 }
370 
371 // err_string_cmp is a compare function for searching error values with
372 // |bsearch| in |err_string_lookup|.
err_string_cmp(const void * a,const void * b)373 static int err_string_cmp(const void *a, const void *b) {
374   const uint32_t a_key = *((const uint32_t*) a) >> 15;
375   const uint32_t b_key = *((const uint32_t*) b) >> 15;
376 
377   if (a_key < b_key) {
378     return -1;
379   } else if (a_key > b_key) {
380     return 1;
381   } else {
382     return 0;
383   }
384 }
385 
386 // err_string_lookup looks up the string associated with |lib| and |key| in
387 // |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)388 static const char *err_string_lookup(uint32_t lib, uint32_t key,
389                                      const uint32_t *values,
390                                      size_t num_values,
391                                      const char *string_data) {
392   // |values| points to data in err_data.h, which is generated by
393   // err_data_generate.go. It's an array of uint32_t values. Each value has the
394   // following structure:
395   //   | lib  |    key    |    offset     |
396   //   |6 bits|  11 bits  |    15 bits    |
397   //
398   // The |lib| value is a library identifier: one of the |ERR_LIB_*| values.
399   // The |key| is a reason code, depending on the context.
400   // The |offset| is the number of bytes from the start of |string_data| where
401   // the (NUL terminated) string for this value can be found.
402   //
403   // Values are sorted based on treating the |lib| and |key| part as an
404   // unsigned integer.
405   if (lib >= (1 << 6) || key >= (1 << 11)) {
406     return NULL;
407   }
408   uint32_t search_key = lib << 26 | key << 15;
409   const uint32_t *result = bsearch(&search_key, values, num_values,
410                                    sizeof(uint32_t), err_string_cmp);
411   if (result == NULL) {
412     return NULL;
413   }
414 
415   return &string_data[(*result) & 0x7fff];
416 }
417 
418 static const char *const kLibraryNames[ERR_NUM_LIBS] = {
419     "invalid library (0)",
420     "unknown library",              // ERR_LIB_NONE
421     "system library",               // ERR_LIB_SYS
422     "bignum routines",              // ERR_LIB_BN
423     "RSA routines",                 // ERR_LIB_RSA
424     "Diffie-Hellman routines",      // ERR_LIB_DH
425     "public key routines",          // ERR_LIB_EVP
426     "memory buffer routines",       // ERR_LIB_BUF
427     "object identifier routines",   // ERR_LIB_OBJ
428     "PEM routines",                 // ERR_LIB_PEM
429     "DSA routines",                 // ERR_LIB_DSA
430     "X.509 certificate routines",   // ERR_LIB_X509
431     "ASN.1 encoding routines",      // ERR_LIB_ASN1
432     "configuration file routines",  // ERR_LIB_CONF
433     "common libcrypto routines",    // ERR_LIB_CRYPTO
434     "elliptic curve routines",      // ERR_LIB_EC
435     "SSL routines",                 // ERR_LIB_SSL
436     "BIO routines",                 // ERR_LIB_BIO
437     "PKCS7 routines",               // ERR_LIB_PKCS7
438     "PKCS8 routines",               // ERR_LIB_PKCS8
439     "X509 V3 routines",             // ERR_LIB_X509V3
440     "random number generator",      // ERR_LIB_RAND
441     "ENGINE routines",              // ERR_LIB_ENGINE
442     "OCSP routines",                // ERR_LIB_OCSP
443     "UI routines",                  // ERR_LIB_UI
444     "COMP routines",                // ERR_LIB_COMP
445     "ECDSA routines",               // ERR_LIB_ECDSA
446     "ECDH routines",                // ERR_LIB_ECDH
447     "HMAC routines",                // ERR_LIB_HMAC
448     "Digest functions",             // ERR_LIB_DIGEST
449     "Cipher functions",             // ERR_LIB_CIPHER
450     "HKDF functions",               // ERR_LIB_HKDF
451     "Trust Token functions",        // ERR_LIB_TRUST_TOKEN
452     "User defined functions",       // ERR_LIB_USER
453 };
454 
err_lib_error_string(uint32_t packed_error)455 static const char *err_lib_error_string(uint32_t packed_error) {
456   const uint32_t lib = ERR_GET_LIB(packed_error);
457 
458   if (lib >= ERR_NUM_LIBS) {
459     return NULL;
460   }
461   return kLibraryNames[lib];
462 }
463 
ERR_lib_error_string(uint32_t packed_error)464 const char *ERR_lib_error_string(uint32_t packed_error) {
465   const char *ret = err_lib_error_string(packed_error);
466   return ret == NULL ? "unknown library" : ret;
467 }
468 
ERR_func_error_string(uint32_t packed_error)469 const char *ERR_func_error_string(uint32_t packed_error) {
470   return "OPENSSL_internal";
471 }
472 
err_reason_error_string(uint32_t packed_error)473 static const char *err_reason_error_string(uint32_t packed_error) {
474   const uint32_t lib = ERR_GET_LIB(packed_error);
475   const uint32_t reason = ERR_GET_REASON(packed_error);
476 
477   if (lib == ERR_LIB_SYS) {
478     if (reason < 127) {
479       return strerror(reason);
480     }
481     return NULL;
482   }
483 
484   if (reason < ERR_NUM_LIBS) {
485     return kLibraryNames[reason];
486   }
487 
488   if (reason < 100) {
489     switch (reason) {
490       case ERR_R_MALLOC_FAILURE:
491         return "malloc failure";
492       case ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED:
493         return "function should not have been called";
494       case ERR_R_PASSED_NULL_PARAMETER:
495         return "passed a null parameter";
496       case ERR_R_INTERNAL_ERROR:
497         return "internal error";
498       case ERR_R_OVERFLOW:
499         return "overflow";
500       default:
501         return NULL;
502     }
503   }
504 
505   return err_string_lookup(lib, reason, kOpenSSLReasonValues,
506                            kOpenSSLReasonValuesLen, kOpenSSLReasonStringData);
507 }
508 
ERR_reason_error_string(uint32_t packed_error)509 const char *ERR_reason_error_string(uint32_t packed_error) {
510   const char *ret = err_reason_error_string(packed_error);
511   return ret == NULL ? "unknown error" : ret;
512 }
513 
ERR_error_string(uint32_t packed_error,char * ret)514 char *ERR_error_string(uint32_t packed_error, char *ret) {
515   static char buf[ERR_ERROR_STRING_BUF_LEN];
516 
517   if (ret == NULL) {
518     // TODO(fork): remove this.
519     ret = buf;
520   }
521 
522 #if !defined(NDEBUG)
523   // This is aimed to help catch callers who don't provide
524   // |ERR_ERROR_STRING_BUF_LEN| bytes of space.
525   OPENSSL_memset(ret, 0, ERR_ERROR_STRING_BUF_LEN);
526 #endif
527 
528   return ERR_error_string_n(packed_error, ret, ERR_ERROR_STRING_BUF_LEN);
529 }
530 
ERR_error_string_n(uint32_t packed_error,char * buf,size_t len)531 char *ERR_error_string_n(uint32_t packed_error, char *buf, size_t len) {
532   if (len == 0) {
533     return NULL;
534   }
535 
536   unsigned lib = ERR_GET_LIB(packed_error);
537   unsigned reason = ERR_GET_REASON(packed_error);
538 
539   const char *lib_str = err_lib_error_string(packed_error);
540   const char *reason_str = err_reason_error_string(packed_error);
541 
542   char lib_buf[64], reason_buf[64];
543   if (lib_str == NULL) {
544     BIO_snprintf(lib_buf, sizeof(lib_buf), "lib(%u)", lib);
545     lib_str = lib_buf;
546   }
547 
548  if (reason_str == NULL) {
549     BIO_snprintf(reason_buf, sizeof(reason_buf), "reason(%u)", reason);
550     reason_str = reason_buf;
551   }
552 
553   BIO_snprintf(buf, len, "error:%08" PRIx32 ":%s:OPENSSL_internal:%s",
554                packed_error, lib_str, reason_str);
555 
556   if (strlen(buf) == len - 1) {
557     // output may be truncated; make sure we always have 5 colon-separated
558     // fields, i.e. 4 colons.
559     static const unsigned num_colons = 4;
560     unsigned i;
561     char *s = buf;
562 
563     if (len <= num_colons) {
564       // In this situation it's not possible to ensure that the correct number
565       // of colons are included in the output.
566       return buf;
567     }
568 
569     for (i = 0; i < num_colons; i++) {
570       char *colon = strchr(s, ':');
571       char *last_pos = &buf[len - 1] - num_colons + i;
572 
573       if (colon == NULL || colon > last_pos) {
574         // set colon |i| at last possible position (buf[len-1] is the
575         // terminating 0). If we're setting this colon, then all whole of the
576         // rest of the string must be colons in order to have the correct
577         // number.
578         OPENSSL_memset(last_pos, ':', num_colons - i);
579         break;
580       }
581 
582       s = colon + 1;
583     }
584   }
585 
586   return buf;
587 }
588 
ERR_print_errors_cb(ERR_print_errors_callback_t callback,void * ctx)589 void ERR_print_errors_cb(ERR_print_errors_callback_t callback, void *ctx) {
590   char buf[ERR_ERROR_STRING_BUF_LEN];
591   char buf2[1024];
592   const char *file, *data;
593   int line, flags;
594   uint32_t packed_error;
595 
596   // thread_hash is the least-significant bits of the |ERR_STATE| pointer value
597   // for this thread.
598   const unsigned long thread_hash = (uintptr_t) err_get_state();
599 
600   for (;;) {
601     packed_error = ERR_get_error_line_data(&file, &line, &data, &flags);
602     if (packed_error == 0) {
603       break;
604     }
605 
606     ERR_error_string_n(packed_error, buf, sizeof(buf));
607     BIO_snprintf(buf2, sizeof(buf2), "%lu:%s:%s:%d:%s\n", thread_hash, buf,
608                  file, line, (flags & ERR_FLAG_STRING) ? data : "");
609     if (callback(buf2, strlen(buf2), ctx) <= 0) {
610       break;
611     }
612   }
613 }
614 
print_errors_to_file(const char * msg,size_t msg_len,void * ctx)615 static int print_errors_to_file(const char* msg, size_t msg_len, void* ctx) {
616   assert(msg[msg_len] == '\0');
617   FILE* fp = ctx;
618   int res = fputs(msg, fp);
619   return res < 0 ? 0 : 1;
620 }
621 
ERR_print_errors_fp(FILE * file)622 void ERR_print_errors_fp(FILE *file) {
623   ERR_print_errors_cb(print_errors_to_file, file);
624 }
625 
626 // err_set_error_data sets the data on the most recent error.
err_set_error_data(char * data)627 static void err_set_error_data(char *data) {
628   ERR_STATE *const state = err_get_state();
629   struct err_error_st *error;
630 
631   if (state == NULL || state->top == state->bottom) {
632     OPENSSL_free(data);
633     return;
634   }
635 
636   error = &state->errors[state->top];
637 
638   OPENSSL_free(error->data);
639   error->data = data;
640 }
641 
ERR_put_error(int library,int unused,int reason,const char * file,unsigned line)642 void ERR_put_error(int library, int unused, int reason, const char *file,
643                    unsigned line) {
644   ERR_STATE *const state = err_get_state();
645   struct err_error_st *error;
646 
647   if (state == NULL) {
648     return;
649   }
650 
651   if (library == ERR_LIB_SYS && reason == 0) {
652 #if defined(OPENSSL_WINDOWS)
653     reason = GetLastError();
654 #else
655     reason = errno;
656 #endif
657   }
658 
659   state->top = (state->top + 1) % ERR_NUM_ERRORS;
660   if (state->top == state->bottom) {
661     state->bottom = (state->bottom + 1) % ERR_NUM_ERRORS;
662   }
663 
664   error = &state->errors[state->top];
665   err_clear(error);
666   error->file = file;
667   error->line = line;
668   error->packed = ERR_PACK(library, reason);
669 }
670 
671 // ERR_add_error_data_vdata takes a variable number of const char* pointers,
672 // concatenates them and sets the result as the data on the most recent
673 // error.
err_add_error_vdata(unsigned num,va_list args)674 static void err_add_error_vdata(unsigned num, va_list args) {
675   size_t alloced, new_len, len = 0, substr_len;
676   char *buf;
677   const char *substr;
678   unsigned i;
679 
680   alloced = 80;
681   buf = OPENSSL_malloc(alloced + 1);
682   if (buf == NULL) {
683     return;
684   }
685 
686   for (i = 0; i < num; i++) {
687     substr = va_arg(args, const char *);
688     if (substr == NULL) {
689       continue;
690     }
691 
692     substr_len = strlen(substr);
693     new_len = len + substr_len;
694     if (new_len > alloced) {
695       char *new_buf;
696 
697       if (alloced + 20 + 1 < alloced) {
698         // overflow.
699         OPENSSL_free(buf);
700         return;
701       }
702 
703       alloced = new_len + 20;
704       new_buf = OPENSSL_realloc(buf, alloced + 1);
705       if (new_buf == NULL) {
706         OPENSSL_free(buf);
707         return;
708       }
709       buf = new_buf;
710     }
711 
712     OPENSSL_memcpy(buf + len, substr, substr_len);
713     len = new_len;
714   }
715 
716   buf[len] = 0;
717   err_set_error_data(buf);
718 }
719 
ERR_add_error_data(unsigned count,...)720 void ERR_add_error_data(unsigned count, ...) {
721   va_list args;
722   va_start(args, count);
723   err_add_error_vdata(count, args);
724   va_end(args);
725 }
726 
ERR_add_error_dataf(const char * format,...)727 void ERR_add_error_dataf(const char *format, ...) {
728   va_list ap;
729   char *buf;
730   static const unsigned buf_len = 256;
731 
732   // A fixed-size buffer is used because va_copy (which would be needed in
733   // order to call vsnprintf twice and measure the buffer) wasn't defined until
734   // C99.
735   buf = OPENSSL_malloc(buf_len + 1);
736   if (buf == NULL) {
737     return;
738   }
739 
740   va_start(ap, format);
741   BIO_vsnprintf(buf, buf_len, format, ap);
742   buf[buf_len] = 0;
743   va_end(ap);
744 
745   err_set_error_data(buf);
746 }
747 
ERR_set_error_data(char * data,int flags)748 void ERR_set_error_data(char *data, int flags) {
749   if (!(flags & ERR_FLAG_STRING)) {
750     // We do not support non-string error data.
751     assert(0);
752     return;
753   }
754   if (flags & ERR_FLAG_MALLOCED) {
755     err_set_error_data(data);
756   } else {
757     char *copy = OPENSSL_strdup(data);
758     if (copy != NULL) {
759       err_set_error_data(copy);
760     }
761   }
762 }
763 
ERR_set_mark(void)764 int ERR_set_mark(void) {
765   ERR_STATE *const state = err_get_state();
766 
767   if (state == NULL || state->bottom == state->top) {
768     return 0;
769   }
770   state->errors[state->top].mark = 1;
771   return 1;
772 }
773 
ERR_pop_to_mark(void)774 int ERR_pop_to_mark(void) {
775   ERR_STATE *const state = err_get_state();
776 
777   if (state == NULL) {
778     return 0;
779   }
780 
781   while (state->bottom != state->top) {
782     struct err_error_st *error = &state->errors[state->top];
783 
784     if (error->mark) {
785       error->mark = 0;
786       return 1;
787     }
788 
789     err_clear(error);
790     if (state->top == 0) {
791       state->top = ERR_NUM_ERRORS - 1;
792     } else {
793       state->top--;
794     }
795   }
796 
797   return 0;
798 }
799 
ERR_load_crypto_strings(void)800 void ERR_load_crypto_strings(void) {}
801 
ERR_free_strings(void)802 void ERR_free_strings(void) {}
803 
ERR_load_BIO_strings(void)804 void ERR_load_BIO_strings(void) {}
805 
ERR_load_ERR_strings(void)806 void ERR_load_ERR_strings(void) {}
807 
ERR_load_RAND_strings(void)808 void ERR_load_RAND_strings(void) {}
809 
810 struct err_save_state_st {
811   struct err_error_st *errors;
812   size_t num_errors;
813 };
814 
ERR_SAVE_STATE_free(ERR_SAVE_STATE * state)815 void ERR_SAVE_STATE_free(ERR_SAVE_STATE *state) {
816   if (state == NULL) {
817     return;
818   }
819   for (size_t i = 0; i < state->num_errors; i++) {
820     err_clear(&state->errors[i]);
821   }
822   OPENSSL_free(state->errors);
823   OPENSSL_free(state);
824 }
825 
ERR_save_state(void)826 ERR_SAVE_STATE *ERR_save_state(void) {
827   ERR_STATE *const state = err_get_state();
828   if (state == NULL || state->top == state->bottom) {
829     return NULL;
830   }
831 
832   ERR_SAVE_STATE *ret = OPENSSL_malloc(sizeof(ERR_SAVE_STATE));
833   if (ret == NULL) {
834     return NULL;
835   }
836 
837   // Errors are stored in the range (bottom, top].
838   size_t num_errors = state->top >= state->bottom
839                           ? state->top - state->bottom
840                           : ERR_NUM_ERRORS + state->top - state->bottom;
841   assert(num_errors < ERR_NUM_ERRORS);
842   ret->errors = OPENSSL_malloc(num_errors * sizeof(struct err_error_st));
843   if (ret->errors == NULL) {
844     OPENSSL_free(ret);
845     return NULL;
846   }
847   OPENSSL_memset(ret->errors, 0, num_errors * sizeof(struct err_error_st));
848   ret->num_errors = num_errors;
849 
850   for (size_t i = 0; i < num_errors; i++) {
851     size_t j = (state->bottom + i + 1) % ERR_NUM_ERRORS;
852     err_copy(&ret->errors[i], &state->errors[j]);
853   }
854   return ret;
855 }
856 
ERR_restore_state(const ERR_SAVE_STATE * state)857 void ERR_restore_state(const ERR_SAVE_STATE *state) {
858   if (state == NULL || state->num_errors == 0) {
859     ERR_clear_error();
860     return;
861   }
862 
863   ERR_STATE *const dst = err_get_state();
864   if (dst == NULL) {
865     return;
866   }
867 
868   for (size_t i = 0; i < state->num_errors; i++) {
869     err_copy(&dst->errors[i], &state->errors[i]);
870   }
871   dst->top = state->num_errors - 1;
872   dst->bottom = ERR_NUM_ERRORS - 1;
873 }
874