Coverity CID 1444960: Error handling issues
[openssl.git] / crypto / err / err.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include <stdarg.h>
12 #include <string.h>
13 #include "internal/cryptlib_int.h"
14 #include "internal/err.h"
15 #include "internal/err_int.h"
16 #include <openssl/err.h>
17 #include <openssl/crypto.h>
18 #include <openssl/buffer.h>
19 #include <openssl/bio.h>
20 #include <openssl/opensslconf.h>
21 #include "internal/thread_once.h"
22 #include "internal/ctype.h"
23 #include "internal/constant_time_locl.h"
24 #include "e_os.h"
25
26 static int err_load_strings(const ERR_STRING_DATA *str);
27
28 static void ERR_STATE_free(ERR_STATE *s);
29 #ifndef OPENSSL_NO_ERR
30 static ERR_STRING_DATA ERR_str_libraries[] = {
31     {ERR_PACK(ERR_LIB_NONE, 0, 0), "unknown library"},
32     {ERR_PACK(ERR_LIB_SYS, 0, 0), "system library"},
33     {ERR_PACK(ERR_LIB_BN, 0, 0), "bignum routines"},
34     {ERR_PACK(ERR_LIB_RSA, 0, 0), "rsa routines"},
35     {ERR_PACK(ERR_LIB_DH, 0, 0), "Diffie-Hellman routines"},
36     {ERR_PACK(ERR_LIB_EVP, 0, 0), "digital envelope routines"},
37     {ERR_PACK(ERR_LIB_BUF, 0, 0), "memory buffer routines"},
38     {ERR_PACK(ERR_LIB_OBJ, 0, 0), "object identifier routines"},
39     {ERR_PACK(ERR_LIB_PEM, 0, 0), "PEM routines"},
40     {ERR_PACK(ERR_LIB_DSA, 0, 0), "dsa routines"},
41     {ERR_PACK(ERR_LIB_X509, 0, 0), "x509 certificate routines"},
42     {ERR_PACK(ERR_LIB_ASN1, 0, 0), "asn1 encoding routines"},
43     {ERR_PACK(ERR_LIB_CONF, 0, 0), "configuration file routines"},
44     {ERR_PACK(ERR_LIB_CRYPTO, 0, 0), "common libcrypto routines"},
45     {ERR_PACK(ERR_LIB_EC, 0, 0), "elliptic curve routines"},
46     {ERR_PACK(ERR_LIB_ECDSA, 0, 0), "ECDSA routines"},
47     {ERR_PACK(ERR_LIB_ECDH, 0, 0), "ECDH routines"},
48     {ERR_PACK(ERR_LIB_SSL, 0, 0), "SSL routines"},
49     {ERR_PACK(ERR_LIB_BIO, 0, 0), "BIO routines"},
50     {ERR_PACK(ERR_LIB_PKCS7, 0, 0), "PKCS7 routines"},
51     {ERR_PACK(ERR_LIB_X509V3, 0, 0), "X509 V3 routines"},
52     {ERR_PACK(ERR_LIB_PKCS12, 0, 0), "PKCS12 routines"},
53     {ERR_PACK(ERR_LIB_RAND, 0, 0), "random number generator"},
54     {ERR_PACK(ERR_LIB_DSO, 0, 0), "DSO support routines"},
55     {ERR_PACK(ERR_LIB_TS, 0, 0), "time stamp routines"},
56     {ERR_PACK(ERR_LIB_ENGINE, 0, 0), "engine routines"},
57     {ERR_PACK(ERR_LIB_OCSP, 0, 0), "OCSP routines"},
58     {ERR_PACK(ERR_LIB_UI, 0, 0), "UI routines"},
59     {ERR_PACK(ERR_LIB_FIPS, 0, 0), "FIPS routines"},
60     {ERR_PACK(ERR_LIB_CMS, 0, 0), "CMS routines"},
61     {ERR_PACK(ERR_LIB_CRMF, 0, 0), "CRMF routines"},
62     {ERR_PACK(ERR_LIB_HMAC, 0, 0), "HMAC routines"},
63     {ERR_PACK(ERR_LIB_CT, 0, 0), "CT routines"},
64     {ERR_PACK(ERR_LIB_ASYNC, 0, 0), "ASYNC routines"},
65     {ERR_PACK(ERR_LIB_KDF, 0, 0), "KDF routines"},
66     {ERR_PACK(ERR_LIB_OSSL_STORE, 0, 0), "STORE routines"},
67     {ERR_PACK(ERR_LIB_SM2, 0, 0), "SM2 routines"},
68     {ERR_PACK(ERR_LIB_ESS, 0, 0), "ESS routines"},
69     {ERR_PACK(ERR_LIB_PROV, 0, 0), "Provider routines"},
70     {0, NULL},
71 };
72
73 static ERR_STRING_DATA ERR_str_functs[] = {
74     {ERR_PACK(0, SYS_F_FOPEN, 0), "fopen"},
75     {ERR_PACK(0, SYS_F_CONNECT, 0), "connect"},
76     {ERR_PACK(0, SYS_F_GETSERVBYNAME, 0), "getservbyname"},
77     {ERR_PACK(0, SYS_F_SOCKET, 0), "socket"},
78     {ERR_PACK(0, SYS_F_IOCTLSOCKET, 0), "ioctlsocket"},
79     {ERR_PACK(0, SYS_F_BIND, 0), "bind"},
80     {ERR_PACK(0, SYS_F_LISTEN, 0), "listen"},
81     {ERR_PACK(0, SYS_F_ACCEPT, 0), "accept"},
82 # ifdef OPENSSL_SYS_WINDOWS
83     {ERR_PACK(0, SYS_F_WSASTARTUP, 0), "WSAstartup"},
84 # endif
85     {ERR_PACK(0, SYS_F_OPENDIR, 0), "opendir"},
86     {ERR_PACK(0, SYS_F_FREAD, 0), "fread"},
87     {ERR_PACK(0, SYS_F_GETADDRINFO, 0), "getaddrinfo"},
88     {ERR_PACK(0, SYS_F_GETNAMEINFO, 0), "getnameinfo"},
89     {ERR_PACK(0, SYS_F_SETSOCKOPT, 0), "setsockopt"},
90     {ERR_PACK(0, SYS_F_GETSOCKOPT, 0), "getsockopt"},
91     {ERR_PACK(0, SYS_F_GETSOCKNAME, 0), "getsockname"},
92     {ERR_PACK(0, SYS_F_GETHOSTBYNAME, 0), "gethostbyname"},
93     {ERR_PACK(0, SYS_F_FFLUSH, 0), "fflush"},
94     {ERR_PACK(0, SYS_F_OPEN, 0), "open"},
95     {ERR_PACK(0, SYS_F_CLOSE, 0), "close"},
96     {ERR_PACK(0, SYS_F_IOCTL, 0), "ioctl"},
97     {ERR_PACK(0, SYS_F_STAT, 0), "stat"},
98     {ERR_PACK(0, SYS_F_FCNTL, 0), "fcntl"},
99     {ERR_PACK(0, SYS_F_FSTAT, 0), "fstat"},
100     {0, NULL},
101 };
102
103 static ERR_STRING_DATA ERR_str_reasons[] = {
104     {ERR_R_SYS_LIB, "system lib"},
105     {ERR_R_BN_LIB, "BN lib"},
106     {ERR_R_RSA_LIB, "RSA lib"},
107     {ERR_R_DH_LIB, "DH lib"},
108     {ERR_R_EVP_LIB, "EVP lib"},
109     {ERR_R_BUF_LIB, "BUF lib"},
110     {ERR_R_OBJ_LIB, "OBJ lib"},
111     {ERR_R_PEM_LIB, "PEM lib"},
112     {ERR_R_DSA_LIB, "DSA lib"},
113     {ERR_R_X509_LIB, "X509 lib"},
114     {ERR_R_ASN1_LIB, "ASN1 lib"},
115     {ERR_R_EC_LIB, "EC lib"},
116     {ERR_R_BIO_LIB, "BIO lib"},
117     {ERR_R_PKCS7_LIB, "PKCS7 lib"},
118     {ERR_R_X509V3_LIB, "X509V3 lib"},
119     {ERR_R_ENGINE_LIB, "ENGINE lib"},
120     {ERR_R_UI_LIB, "UI lib"},
121     {ERR_R_OSSL_STORE_LIB, "STORE lib"},
122     {ERR_R_ECDSA_LIB, "ECDSA lib"},
123
124     {ERR_R_NESTED_ASN1_ERROR, "nested asn1 error"},
125     {ERR_R_MISSING_ASN1_EOS, "missing asn1 eos"},
126
127     {ERR_R_FATAL, "fatal"},
128     {ERR_R_MALLOC_FAILURE, "malloc failure"},
129     {ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED,
130      "called a function you should not call"},
131     {ERR_R_PASSED_NULL_PARAMETER, "passed a null parameter"},
132     {ERR_R_INTERNAL_ERROR, "internal error"},
133     {ERR_R_DISABLED, "called a function that was disabled at compile-time"},
134     {ERR_R_INIT_FAIL, "init fail"},
135     {ERR_R_OPERATION_FAIL, "operation fail"},
136
137     {0, NULL},
138 };
139 #endif
140
141 static CRYPTO_ONCE err_init = CRYPTO_ONCE_STATIC_INIT;
142 static int set_err_thread_local;
143 static CRYPTO_THREAD_LOCAL err_thread_local;
144
145 static CRYPTO_ONCE err_string_init = CRYPTO_ONCE_STATIC_INIT;
146 static CRYPTO_RWLOCK *err_string_lock;
147
148 static ERR_STRING_DATA *int_err_get_item(const ERR_STRING_DATA *);
149
150 /*
151  * The internal state
152  */
153
154 static LHASH_OF(ERR_STRING_DATA) *int_error_hash = NULL;
155 static int int_err_library_number = ERR_LIB_USER;
156
157 static unsigned long get_error_values(int inc, int top, const char **file,
158                                       int *line, const char **data,
159                                       int *flags);
160
161 static unsigned long err_string_data_hash(const ERR_STRING_DATA *a)
162 {
163     unsigned long ret, l;
164
165     l = a->error;
166     ret = l ^ ERR_GET_LIB(l) ^ ERR_GET_FUNC(l);
167     return (ret ^ ret % 19 * 13);
168 }
169
170 static int err_string_data_cmp(const ERR_STRING_DATA *a,
171                                const ERR_STRING_DATA *b)
172 {
173     if (a->error == b->error)
174         return 0;
175     return a->error > b->error ? 1 : -1;
176 }
177
178 static ERR_STRING_DATA *int_err_get_item(const ERR_STRING_DATA *d)
179 {
180     ERR_STRING_DATA *p = NULL;
181
182     CRYPTO_THREAD_read_lock(err_string_lock);
183     p = lh_ERR_STRING_DATA_retrieve(int_error_hash, d);
184     CRYPTO_THREAD_unlock(err_string_lock);
185
186     return p;
187 }
188
189 #ifndef OPENSSL_NO_ERR
190 /* A measurement on Linux 2018-11-21 showed about 3.5kib */
191 # define SPACE_SYS_STR_REASONS 4 * 1024
192 # define NUM_SYS_STR_REASONS 127
193
194 static ERR_STRING_DATA SYS_str_reasons[NUM_SYS_STR_REASONS + 1];
195 /*
196  * SYS_str_reasons is filled with copies of strerror() results at
197  * initialization. 'errno' values up to 127 should cover all usual errors,
198  * others will be displayed numerically by ERR_error_string. It is crucial
199  * that we have something for each reason code that occurs in
200  * ERR_str_reasons, or bogus reason strings will be returned for SYSerr(),
201  * which always gets an errno value and never one of those 'standard' reason
202  * codes.
203  */
204
205 static void build_SYS_str_reasons(void)
206 {
207     /* OPENSSL_malloc cannot be used here, use static storage instead */
208     static char strerror_pool[SPACE_SYS_STR_REASONS];
209     char *cur = strerror_pool;
210     size_t cnt = 0;
211     static int init = 1;
212     int i;
213     int saveerrno = get_last_sys_error();
214
215     CRYPTO_THREAD_write_lock(err_string_lock);
216     if (!init) {
217         CRYPTO_THREAD_unlock(err_string_lock);
218         return;
219     }
220
221     for (i = 1; i <= NUM_SYS_STR_REASONS; i++) {
222         ERR_STRING_DATA *str = &SYS_str_reasons[i - 1];
223
224         str->error = ERR_PACK(ERR_LIB_SYS, 0, i);
225         if (str->string == NULL) {
226             if (openssl_strerror_r(i, cur, sizeof(strerror_pool) - cnt)) {
227                 size_t l = strlen(cur);
228
229                 str->string = cur;
230                 cnt += l;
231                 if (cnt > sizeof(strerror_pool))
232                     cnt = sizeof(strerror_pool);
233                 cur += l;
234
235                 /*
236                  * VMS has an unusual quirk of adding spaces at the end of
237                  * some (most? all?) messages.  Lets trim them off.
238                  */
239                 while (ossl_isspace(cur[-1])) {
240                     cur--;
241                     cnt--;
242                 }
243                 *cur++ = '\0';
244                 cnt++;
245             }
246         }
247         if (str->string == NULL)
248             str->string = "unknown";
249     }
250
251     /*
252      * Now we still have SYS_str_reasons[NUM_SYS_STR_REASONS] = {0, NULL}, as
253      * required by ERR_load_strings.
254      */
255
256     init = 0;
257
258     CRYPTO_THREAD_unlock(err_string_lock);
259     /* openssl_strerror_r could change errno, but we want to preserve it */
260     set_sys_error(saveerrno);
261     err_load_strings(SYS_str_reasons);
262 }
263 #endif
264
265 #define err_clear_data(p, i) \
266         do { \
267             if ((p)->err_data_flags[i] & ERR_TXT_MALLOCED) {\
268                 OPENSSL_free((p)->err_data[i]); \
269                 (p)->err_data[i] = NULL; \
270             } \
271             (p)->err_data_flags[i] = 0; \
272         } while (0)
273
274 #define err_clear(p, i) \
275         do { \
276             err_clear_data(p, i); \
277             (p)->err_flags[i] = 0; \
278             (p)->err_buffer[i] = 0; \
279             (p)->err_file[i] = NULL; \
280             (p)->err_line[i] = -1; \
281         } while (0)
282
283 static void ERR_STATE_free(ERR_STATE *s)
284 {
285     int i;
286
287     if (s == NULL)
288         return;
289     for (i = 0; i < ERR_NUM_ERRORS; i++) {
290         err_clear_data(s, i);
291     }
292     OPENSSL_free(s);
293 }
294
295 DEFINE_RUN_ONCE_STATIC(do_err_strings_init)
296 {
297     if (!OPENSSL_init_crypto(0, NULL))
298         return 0;
299     err_string_lock = CRYPTO_THREAD_lock_new();
300     if (err_string_lock == NULL)
301         return 0;
302     int_error_hash = lh_ERR_STRING_DATA_new(err_string_data_hash,
303                                             err_string_data_cmp);
304     if (int_error_hash == NULL) {
305         CRYPTO_THREAD_lock_free(err_string_lock);
306         err_string_lock = NULL;
307         return 0;
308     }
309     return 1;
310 }
311
312 void err_cleanup(void)
313 {
314     if (set_err_thread_local != 0)
315         CRYPTO_THREAD_cleanup_local(&err_thread_local);
316     CRYPTO_THREAD_lock_free(err_string_lock);
317     err_string_lock = NULL;
318     lh_ERR_STRING_DATA_free(int_error_hash);
319     int_error_hash = NULL;
320 }
321
322 /*
323  * Legacy; pack in the library.
324  */
325 static void err_patch(int lib, ERR_STRING_DATA *str)
326 {
327     unsigned long plib = ERR_PACK(lib, 0, 0);
328
329     for (; str->error != 0; str++)
330         str->error |= plib;
331 }
332
333 /*
334  * Hash in |str| error strings. Assumes the URN_ONCE was done.
335  */
336 static int err_load_strings(const ERR_STRING_DATA *str)
337 {
338     CRYPTO_THREAD_write_lock(err_string_lock);
339     for (; str->error; str++)
340         (void)lh_ERR_STRING_DATA_insert(int_error_hash,
341                                        (ERR_STRING_DATA *)str);
342     CRYPTO_THREAD_unlock(err_string_lock);
343     return 1;
344 }
345
346 int ERR_load_ERR_strings(void)
347 {
348 #ifndef OPENSSL_NO_ERR
349     if (!RUN_ONCE(&err_string_init, do_err_strings_init))
350         return 0;
351
352     err_load_strings(ERR_str_libraries);
353     err_load_strings(ERR_str_reasons);
354     err_patch(ERR_LIB_SYS, ERR_str_functs);
355     err_load_strings(ERR_str_functs);
356     build_SYS_str_reasons();
357 #endif
358     return 1;
359 }
360
361 int ERR_load_strings(int lib, ERR_STRING_DATA *str)
362 {
363     if (ERR_load_ERR_strings() == 0)
364         return 0;
365
366     err_patch(lib, str);
367     err_load_strings(str);
368     return 1;
369 }
370
371 int ERR_load_strings_const(const ERR_STRING_DATA *str)
372 {
373     if (ERR_load_ERR_strings() == 0)
374         return 0;
375     err_load_strings(str);
376     return 1;
377 }
378
379 int ERR_unload_strings(int lib, ERR_STRING_DATA *str)
380 {
381     if (!RUN_ONCE(&err_string_init, do_err_strings_init))
382         return 0;
383
384     CRYPTO_THREAD_write_lock(err_string_lock);
385     /*
386      * We don't need to ERR_PACK the lib, since that was done (to
387      * the table) when it was loaded.
388      */
389     for (; str->error; str++)
390         (void)lh_ERR_STRING_DATA_delete(int_error_hash, str);
391     CRYPTO_THREAD_unlock(err_string_lock);
392
393     return 1;
394 }
395
396 void err_free_strings_int(void)
397 {
398     if (!RUN_ONCE(&err_string_init, do_err_strings_init))
399         return;
400 }
401
402 /********************************************************/
403
404 void ERR_put_error(int lib, int func, int reason, const char *file, int line)
405 {
406     ERR_STATE *es;
407
408 #ifdef _OSD_POSIX
409     /*
410      * In the BS2000-OSD POSIX subsystem, the compiler generates path names
411      * in the form "*POSIX(/etc/passwd)". This dirty hack strips them to
412      * something sensible. @@@ We shouldn't modify a const string, though.
413      */
414     if (strncmp(file, "*POSIX(", sizeof("*POSIX(") - 1) == 0) {
415         char *end;
416
417         /* Skip the "*POSIX(" prefix */
418         file += sizeof("*POSIX(") - 1;
419         end = &file[strlen(file) - 1];
420         if (*end == ')')
421             *end = '\0';
422         /* Optional: use the basename of the path only. */
423         if ((end = strrchr(file, '/')) != NULL)
424             file = &end[1];
425     }
426 #endif
427     es = ERR_get_state();
428     if (es == NULL)
429         return;
430
431     es->top = (es->top + 1) % ERR_NUM_ERRORS;
432     if (es->top == es->bottom)
433         es->bottom = (es->bottom + 1) % ERR_NUM_ERRORS;
434     es->err_flags[es->top] = 0;
435     es->err_buffer[es->top] = ERR_PACK(lib, func, reason);
436     es->err_file[es->top] = file;
437     es->err_line[es->top] = line;
438     err_clear_data(es, es->top);
439 }
440
441 void ERR_clear_error(void)
442 {
443     int i;
444     ERR_STATE *es;
445
446     es = ERR_get_state();
447     if (es == NULL)
448         return;
449
450     for (i = 0; i < ERR_NUM_ERRORS; i++) {
451         err_clear(es, i);
452     }
453     es->top = es->bottom = 0;
454 }
455
456 unsigned long ERR_get_error(void)
457 {
458     return get_error_values(1, 0, NULL, NULL, NULL, NULL);
459 }
460
461 unsigned long ERR_get_error_line(const char **file, int *line)
462 {
463     return get_error_values(1, 0, file, line, NULL, NULL);
464 }
465
466 unsigned long ERR_get_error_line_data(const char **file, int *line,
467                                       const char **data, int *flags)
468 {
469     return get_error_values(1, 0, file, line, data, flags);
470 }
471
472 unsigned long ERR_peek_error(void)
473 {
474     return get_error_values(0, 0, NULL, NULL, NULL, NULL);
475 }
476
477 unsigned long ERR_peek_error_line(const char **file, int *line)
478 {
479     return get_error_values(0, 0, file, line, NULL, NULL);
480 }
481
482 unsigned long ERR_peek_error_line_data(const char **file, int *line,
483                                        const char **data, int *flags)
484 {
485     return get_error_values(0, 0, file, line, data, flags);
486 }
487
488 unsigned long ERR_peek_last_error(void)
489 {
490     return get_error_values(0, 1, NULL, NULL, NULL, NULL);
491 }
492
493 unsigned long ERR_peek_last_error_line(const char **file, int *line)
494 {
495     return get_error_values(0, 1, file, line, NULL, NULL);
496 }
497
498 unsigned long ERR_peek_last_error_line_data(const char **file, int *line,
499                                             const char **data, int *flags)
500 {
501     return get_error_values(0, 1, file, line, data, flags);
502 }
503
504 static unsigned long get_error_values(int inc, int top, const char **file,
505                                       int *line, const char **data,
506                                       int *flags)
507 {
508     int i = 0;
509     ERR_STATE *es;
510     unsigned long ret;
511
512     es = ERR_get_state();
513     if (es == NULL)
514         return 0;
515
516     if (inc && top) {
517         if (file)
518             *file = "";
519         if (line)
520             *line = 0;
521         if (data)
522             *data = "";
523         if (flags)
524             *flags = 0;
525
526         return ERR_R_INTERNAL_ERROR;
527     }
528
529     while (es->bottom != es->top) {
530         if (es->err_flags[es->top] & ERR_FLAG_CLEAR) {
531             err_clear(es, es->top);
532             es->top = es->top > 0 ? es->top - 1 : ERR_NUM_ERRORS - 1;
533             continue;
534         }
535         i = (es->bottom + 1) % ERR_NUM_ERRORS;
536         if (es->err_flags[i] & ERR_FLAG_CLEAR) {
537             es->bottom = i;
538             err_clear(es, es->bottom);
539             continue;
540         }
541         break;
542     }
543
544     if (es->bottom == es->top)
545         return 0;
546
547     if (top)
548         i = es->top;            /* last error */
549     else
550         i = (es->bottom + 1) % ERR_NUM_ERRORS; /* first error */
551
552     ret = es->err_buffer[i];
553     if (inc) {
554         es->bottom = i;
555         es->err_buffer[i] = 0;
556     }
557
558     if (file != NULL && line != NULL) {
559         if (es->err_file[i] == NULL) {
560             *file = "NA";
561             *line = 0;
562         } else {
563             *file = es->err_file[i];
564             *line = es->err_line[i];
565         }
566     }
567
568     if (data == NULL) {
569         if (inc) {
570             err_clear_data(es, i);
571         }
572     } else {
573         if (es->err_data[i] == NULL) {
574             *data = "";
575             if (flags != NULL)
576                 *flags = 0;
577         } else {
578             *data = es->err_data[i];
579             if (flags != NULL)
580                 *flags = es->err_data_flags[i];
581         }
582     }
583     return ret;
584 }
585
586 void ERR_error_string_n(unsigned long e, char *buf, size_t len)
587 {
588     char lsbuf[64], fsbuf[64], rsbuf[64];
589     const char *ls, *fs, *rs;
590     unsigned long l, f, r;
591
592     if (len == 0)
593         return;
594
595     l = ERR_GET_LIB(e);
596     ls = ERR_lib_error_string(e);
597     if (ls == NULL) {
598         BIO_snprintf(lsbuf, sizeof(lsbuf), "lib(%lu)", l);
599         ls = lsbuf;
600     }
601
602     fs = ERR_func_error_string(e);
603     f = ERR_GET_FUNC(e);
604     if (fs == NULL) {
605         BIO_snprintf(fsbuf, sizeof(fsbuf), "func(%lu)", f);
606         fs = fsbuf;
607     }
608
609     rs = ERR_reason_error_string(e);
610     r = ERR_GET_REASON(e);
611     if (rs == NULL) {
612         BIO_snprintf(rsbuf, sizeof(rsbuf), "reason(%lu)", r);
613         rs = rsbuf;
614     }
615
616     BIO_snprintf(buf, len, "error:%08lX:%s:%s:%s", e, ls, fs, rs);
617     if (strlen(buf) == len - 1) {
618         /* Didn't fit; use a minimal format. */
619         BIO_snprintf(buf, len, "err:%lx:%lx:%lx:%lx", e, l, f, r);
620     }
621 }
622
623 /*
624  * ERR_error_string_n should be used instead for ret != NULL as
625  * ERR_error_string cannot know how large the buffer is
626  */
627 char *ERR_error_string(unsigned long e, char *ret)
628 {
629     static char buf[256];
630
631     if (ret == NULL)
632         ret = buf;
633     ERR_error_string_n(e, ret, (int)sizeof(buf));
634     return ret;
635 }
636
637 const char *ERR_lib_error_string(unsigned long e)
638 {
639     ERR_STRING_DATA d, *p;
640     unsigned long l;
641
642     if (!RUN_ONCE(&err_string_init, do_err_strings_init)) {
643         return NULL;
644     }
645
646     l = ERR_GET_LIB(e);
647     d.error = ERR_PACK(l, 0, 0);
648     p = int_err_get_item(&d);
649     return ((p == NULL) ? NULL : p->string);
650 }
651
652 const char *ERR_func_error_string(unsigned long e)
653 {
654     ERR_STRING_DATA d, *p;
655     unsigned long l, f;
656
657     if (!RUN_ONCE(&err_string_init, do_err_strings_init)) {
658         return NULL;
659     }
660
661     l = ERR_GET_LIB(e);
662     f = ERR_GET_FUNC(e);
663     d.error = ERR_PACK(l, f, 0);
664     p = int_err_get_item(&d);
665     return ((p == NULL) ? NULL : p->string);
666 }
667
668 const char *ERR_reason_error_string(unsigned long e)
669 {
670     ERR_STRING_DATA d, *p = NULL;
671     unsigned long l, r;
672
673     if (!RUN_ONCE(&err_string_init, do_err_strings_init)) {
674         return NULL;
675     }
676
677     l = ERR_GET_LIB(e);
678     r = ERR_GET_REASON(e);
679     d.error = ERR_PACK(l, 0, r);
680     p = int_err_get_item(&d);
681     if (!p) {
682         d.error = ERR_PACK(0, 0, r);
683         p = int_err_get_item(&d);
684     }
685     return ((p == NULL) ? NULL : p->string);
686 }
687
688 void err_delete_thread_state(void)
689 {
690     ERR_STATE *state = CRYPTO_THREAD_get_local(&err_thread_local);
691     if (state == NULL)
692         return;
693
694     CRYPTO_THREAD_set_local(&err_thread_local, NULL);
695     ERR_STATE_free(state);
696 }
697
698 #if !OPENSSL_API_1_1_0
699 void ERR_remove_thread_state(void *dummy)
700 {
701 }
702 #endif
703
704 #if !OPENSSL_API_1_0_0
705 void ERR_remove_state(unsigned long pid)
706 {
707 }
708 #endif
709
710 DEFINE_RUN_ONCE_STATIC(err_do_init)
711 {
712     set_err_thread_local = 1;
713     return CRYPTO_THREAD_init_local(&err_thread_local, NULL);
714 }
715
716 ERR_STATE *ERR_get_state(void)
717 {
718     ERR_STATE *state;
719     int saveerrno = get_last_sys_error();
720
721     if (!OPENSSL_init_crypto(OPENSSL_INIT_BASE_ONLY, NULL))
722         return NULL;
723
724     if (!RUN_ONCE(&err_init, err_do_init))
725         return NULL;
726
727     state = CRYPTO_THREAD_get_local(&err_thread_local);
728     if (state == (ERR_STATE*)-1)
729         return NULL;
730
731     if (state == NULL) {
732         if (!CRYPTO_THREAD_set_local(&err_thread_local, (ERR_STATE*)-1))
733             return NULL;
734
735         if ((state = OPENSSL_zalloc(sizeof(*state))) == NULL) {
736             CRYPTO_THREAD_set_local(&err_thread_local, NULL);
737             return NULL;
738         }
739
740         if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_ERR_STATE)
741                 || !CRYPTO_THREAD_set_local(&err_thread_local, state)) {
742             ERR_STATE_free(state);
743             CRYPTO_THREAD_set_local(&err_thread_local, NULL);
744             return NULL;
745         }
746
747         /* Ignore failures from these */
748         OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
749     }
750
751     set_sys_error(saveerrno);
752     return state;
753 }
754
755 /*
756  * err_shelve_state returns the current thread local error state
757  * and freezes the error module until err_unshelve_state is called.
758  */
759 int err_shelve_state(void **state)
760 {
761     int saveerrno = get_last_sys_error();
762
763     /*
764      * Note, at present our only caller is OPENSSL_init_crypto(), indirectly
765      * via ossl_init_load_crypto_nodelete(), by which point the requested
766      * "base" initialization has already been performed, so the below call is a
767      * NOOP, that re-enters OPENSSL_init_crypto() only to quickly return.
768      *
769      * If are no other valid callers of this function, the call below can be
770      * removed, avoiding the re-entry into OPENSSL_init_crypto().  If there are
771      * potential uses that are not from inside OPENSSL_init_crypto(), then this
772      * call is needed, but some care is required to make sure that the re-entry
773      * remains a NOOP.
774      */
775     if (!OPENSSL_init_crypto(OPENSSL_INIT_BASE_ONLY, NULL))
776         return 0;
777
778     if (!RUN_ONCE(&err_init, err_do_init))
779         return 0;
780
781     *state = CRYPTO_THREAD_get_local(&err_thread_local);
782     if (!CRYPTO_THREAD_set_local(&err_thread_local, (ERR_STATE*)-1))
783         return 0;
784
785     set_sys_error(saveerrno);
786     return 1;
787 }
788
789 /*
790  * err_unshelve_state restores the error state that was returned
791  * by err_shelve_state previously.
792  */
793 void err_unshelve_state(void* state)
794 {
795     if (state != (void*)-1)
796         CRYPTO_THREAD_set_local(&err_thread_local, (ERR_STATE*)state);
797 }
798
799 int ERR_get_next_error_library(void)
800 {
801     int ret;
802
803     if (!RUN_ONCE(&err_string_init, do_err_strings_init))
804         return 0;
805
806     CRYPTO_THREAD_write_lock(err_string_lock);
807     ret = int_err_library_number++;
808     CRYPTO_THREAD_unlock(err_string_lock);
809     return ret;
810 }
811
812 static int err_set_error_data_int(char *data, int flags)
813 {
814     ERR_STATE *es;
815     int i;
816
817     es = ERR_get_state();
818     if (es == NULL)
819         return 0;
820
821     i = es->top;
822
823     err_clear_data(es, i);
824     es->err_data[i] = data;
825     es->err_data_flags[i] = flags;
826
827     return 1;
828 }
829
830 void ERR_set_error_data(char *data, int flags)
831 {
832     /*
833      * This function is void so we cannot propagate the error return. Since it
834      * is also in the public API we can't change the return type.
835      */
836     err_set_error_data_int(data, flags);
837 }
838
839 void ERR_add_error_data(int num, ...)
840 {
841     va_list args;
842     va_start(args, num);
843     ERR_add_error_vdata(num, args);
844     va_end(args);
845 }
846
847 void ERR_add_error_vdata(int num, va_list args)
848 {
849     int i, n, s;
850     char *str, *p, *a;
851
852     s = 80;
853     if ((str = OPENSSL_malloc(s + 1)) == NULL) {
854         /* ERRerr(ERR_F_ERR_ADD_ERROR_VDATA, ERR_R_MALLOC_FAILURE); */
855         return;
856     }
857     str[0] = '\0';
858
859     n = 0;
860     for (i = 0; i < num; i++) {
861         a = va_arg(args, char *);
862         if (a == NULL)
863             a = "<NULL>";
864         n += strlen(a);
865         if (n > s) {
866             s = n + 20;
867             p = OPENSSL_realloc(str, s + 1);
868             if (p == NULL) {
869                 OPENSSL_free(str);
870                 return;
871             }
872             str = p;
873         }
874         OPENSSL_strlcat(str, a, (size_t)s + 1);
875     }
876     if (!err_set_error_data_int(str, ERR_TXT_MALLOCED | ERR_TXT_STRING))
877         OPENSSL_free(str);
878 }
879
880 int ERR_set_mark(void)
881 {
882     ERR_STATE *es;
883
884     es = ERR_get_state();
885     if (es == NULL)
886         return 0;
887
888     if (es->bottom == es->top)
889         return 0;
890     es->err_flags[es->top] |= ERR_FLAG_MARK;
891     return 1;
892 }
893
894 int ERR_pop_to_mark(void)
895 {
896     ERR_STATE *es;
897
898     es = ERR_get_state();
899     if (es == NULL)
900         return 0;
901
902     while (es->bottom != es->top
903            && (es->err_flags[es->top] & ERR_FLAG_MARK) == 0) {
904         err_clear(es, es->top);
905         es->top = es->top > 0 ? es->top - 1 : ERR_NUM_ERRORS - 1;
906     }
907
908     if (es->bottom == es->top)
909         return 0;
910     es->err_flags[es->top] &= ~ERR_FLAG_MARK;
911     return 1;
912 }
913
914 int ERR_clear_last_mark(void)
915 {
916     ERR_STATE *es;
917     int top;
918
919     es = ERR_get_state();
920     if (es == NULL)
921         return 0;
922
923     top = es->top;
924     while (es->bottom != top
925            && (es->err_flags[top] & ERR_FLAG_MARK) == 0) {
926         top = top > 0 ? top - 1 : ERR_NUM_ERRORS - 1;
927     }
928
929     if (es->bottom == top)
930         return 0;
931     es->err_flags[top] &= ~ERR_FLAG_MARK;
932     return 1;
933 }
934
935 void err_clear_last_constant_time(int clear)
936 {
937     ERR_STATE *es;
938     int top;
939
940     es = ERR_get_state();
941     if (es == NULL)
942         return;
943
944     top = es->top;
945
946     /*
947      * Flag error as cleared but remove it elsewhere to avoid two errors
948      * accessing the same error stack location, revealing timing information.
949      */
950     clear = constant_time_select_int(constant_time_eq_int(clear, 0),
951                                      0, ERR_FLAG_CLEAR);
952     es->err_flags[top] |= clear;
953 }