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