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