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