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