hkdf: when HMAC key is all zeros, still set a valid key length
[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_clear_error(void)
359 {
360     int i;
361     ERR_STATE *es;
362
363     es = ERR_get_state();
364     if (es == NULL)
365         return;
366
367     for (i = 0; i < ERR_NUM_ERRORS; i++) {
368         err_clear(es, i, 0);
369     }
370     es->top = es->bottom = 0;
371 }
372
373 unsigned long ERR_get_error(void)
374 {
375     return get_error_values(1, 0, NULL, NULL, NULL, NULL);
376 }
377
378 unsigned long ERR_get_error_line(const char **file, int *line)
379 {
380     return get_error_values(1, 0, file, line, NULL, NULL);
381 }
382
383 unsigned long ERR_get_error_line_data(const char **file, int *line,
384                                       const char **data, int *flags)
385 {
386     return get_error_values(1, 0, file, line, data, flags);
387 }
388
389 unsigned long ERR_peek_error(void)
390 {
391     return get_error_values(0, 0, NULL, NULL, NULL, NULL);
392 }
393
394 unsigned long ERR_peek_error_line(const char **file, int *line)
395 {
396     return get_error_values(0, 0, file, line, NULL, NULL);
397 }
398
399 unsigned long ERR_peek_error_line_data(const char **file, int *line,
400                                        const char **data, int *flags)
401 {
402     return get_error_values(0, 0, file, line, data, flags);
403 }
404
405 unsigned long ERR_peek_last_error(void)
406 {
407     return get_error_values(0, 1, NULL, NULL, NULL, NULL);
408 }
409
410 unsigned long ERR_peek_last_error_line(const char **file, int *line)
411 {
412     return get_error_values(0, 1, file, line, NULL, NULL);
413 }
414
415 unsigned long ERR_peek_last_error_line_data(const char **file, int *line,
416                                             const char **data, int *flags)
417 {
418     return get_error_values(0, 1, file, line, data, flags);
419 }
420
421 static unsigned long get_error_values(int inc, int top, const char **file,
422                                       int *line, const char **data,
423                                       int *flags)
424 {
425     int i = 0;
426     ERR_STATE *es;
427     unsigned long ret;
428
429     es = ERR_get_state();
430     if (es == NULL)
431         return 0;
432
433     if (inc && top) {
434         if (file)
435             *file = "";
436         if (line)
437             *line = 0;
438         if (data)
439             *data = "";
440         if (flags)
441             *flags = 0;
442
443         return ERR_R_INTERNAL_ERROR;
444     }
445
446     while (es->bottom != es->top) {
447         if (es->err_flags[es->top] & ERR_FLAG_CLEAR) {
448             err_clear(es, es->top, 0);
449             es->top = es->top > 0 ? es->top - 1 : ERR_NUM_ERRORS - 1;
450             continue;
451         }
452         i = (es->bottom + 1) % ERR_NUM_ERRORS;
453         if (es->err_flags[i] & ERR_FLAG_CLEAR) {
454             es->bottom = i;
455             err_clear(es, es->bottom, 0);
456             continue;
457         }
458         break;
459     }
460
461     if (es->bottom == es->top)
462         return 0;
463
464     if (top)
465         i = es->top;            /* last error */
466     else
467         i = (es->bottom + 1) % ERR_NUM_ERRORS; /* first error */
468
469     ret = es->err_buffer[i];
470     if (inc) {
471         es->bottom = i;
472         es->err_buffer[i] = 0;
473     }
474
475     if (file != NULL && line != NULL) {
476         if (es->err_file[i] == NULL) {
477             *file = "NA";
478             *line = 0;
479         } else {
480             *file = es->err_file[i];
481             *line = es->err_line[i];
482         }
483     }
484
485     if (data == NULL) {
486         if (inc) {
487             err_clear_data(es, i, 0);
488         }
489     } else {
490         if (es->err_data[i] == NULL) {
491             *data = "";
492             if (flags != NULL)
493                 *flags = 0;
494         } else {
495             *data = es->err_data[i];
496             if (flags != NULL)
497                 *flags = es->err_data_flags[i];
498         }
499     }
500     return ret;
501 }
502
503 void ERR_error_string_n(unsigned long e, char *buf, size_t len)
504 {
505     char lsbuf[64], rsbuf[64];
506     const char *ls, *rs;
507     unsigned long f = 0, l, r;
508
509     if (len == 0)
510         return;
511
512     l = ERR_GET_LIB(e);
513     ls = ERR_lib_error_string(e);
514     if (ls == NULL) {
515         BIO_snprintf(lsbuf, sizeof(lsbuf), "lib(%lu)", l);
516         ls = lsbuf;
517     }
518
519     rs = ERR_reason_error_string(e);
520     r = ERR_GET_REASON(e);
521     if (rs == NULL) {
522         BIO_snprintf(rsbuf, sizeof(rsbuf), "reason(%lu)", r);
523         rs = rsbuf;
524     }
525
526     BIO_snprintf(buf, len, "error:%08lX:%s:%s:%s", e, ls, "", rs);
527     if (strlen(buf) == len - 1) {
528         /* Didn't fit; use a minimal format. */
529         BIO_snprintf(buf, len, "err:%lx:%lx:%lx:%lx", e, l, f, r);
530     }
531 }
532
533 /*
534  * ERR_error_string_n should be used instead for ret != NULL as
535  * ERR_error_string cannot know how large the buffer is
536  */
537 char *ERR_error_string(unsigned long e, char *ret)
538 {
539     static char buf[256];
540
541     if (ret == NULL)
542         ret = buf;
543     ERR_error_string_n(e, ret, (int)sizeof(buf));
544     return ret;
545 }
546
547 const char *ERR_lib_error_string(unsigned long e)
548 {
549     ERR_STRING_DATA d, *p;
550     unsigned long l;
551
552     if (!RUN_ONCE(&err_string_init, do_err_strings_init)) {
553         return NULL;
554     }
555
556     l = ERR_GET_LIB(e);
557     d.error = ERR_PACK(l, 0, 0);
558     p = int_err_get_item(&d);
559     return ((p == NULL) ? NULL : p->string);
560 }
561
562 const char *ERR_func_error_string(unsigned long e)
563 {
564     if (!RUN_ONCE(&err_string_init, do_err_strings_init))
565         return NULL;
566     return ERR_GET_LIB(e) == ERR_LIB_SYS ? "system library" : NULL;
567 }
568
569 const char *ERR_reason_error_string(unsigned long e)
570 {
571     ERR_STRING_DATA d, *p = NULL;
572     unsigned long l, r;
573
574     if (!RUN_ONCE(&err_string_init, do_err_strings_init)) {
575         return NULL;
576     }
577
578     l = ERR_GET_LIB(e);
579     r = ERR_GET_REASON(e);
580     d.error = ERR_PACK(l, 0, r);
581     p = int_err_get_item(&d);
582     if (!p) {
583         d.error = ERR_PACK(0, 0, r);
584         p = int_err_get_item(&d);
585     }
586     return ((p == NULL) ? NULL : p->string);
587 }
588
589 /* TODO(3.0): arg ignored for now */
590 static void err_delete_thread_state(void *arg)
591 {
592     ERR_STATE *state = CRYPTO_THREAD_get_local(&err_thread_local);
593     if (state == NULL)
594         return;
595
596     CRYPTO_THREAD_set_local(&err_thread_local, NULL);
597     ERR_STATE_free(state);
598 }
599
600 #if !OPENSSL_API_1_1_0
601 void ERR_remove_thread_state(void *dummy)
602 {
603 }
604 #endif
605
606 #if !OPENSSL_API_1_0_0
607 void ERR_remove_state(unsigned long pid)
608 {
609 }
610 #endif
611
612 DEFINE_RUN_ONCE_STATIC(err_do_init)
613 {
614     set_err_thread_local = 1;
615     return CRYPTO_THREAD_init_local(&err_thread_local, NULL);
616 }
617
618 ERR_STATE *ERR_get_state(void)
619 {
620     ERR_STATE *state;
621     int saveerrno = get_last_sys_error();
622
623     if (!OPENSSL_init_crypto(OPENSSL_INIT_BASE_ONLY, NULL))
624         return NULL;
625
626     if (!RUN_ONCE(&err_init, err_do_init))
627         return NULL;
628
629     state = CRYPTO_THREAD_get_local(&err_thread_local);
630     if (state == (ERR_STATE*)-1)
631         return NULL;
632
633     if (state == NULL) {
634         if (!CRYPTO_THREAD_set_local(&err_thread_local, (ERR_STATE*)-1))
635             return NULL;
636
637         if ((state = OPENSSL_zalloc(sizeof(*state))) == NULL) {
638             CRYPTO_THREAD_set_local(&err_thread_local, NULL);
639             return NULL;
640         }
641
642         if (!ossl_init_thread_start(NULL, NULL, err_delete_thread_state)
643                 || !CRYPTO_THREAD_set_local(&err_thread_local, state)) {
644             ERR_STATE_free(state);
645             CRYPTO_THREAD_set_local(&err_thread_local, NULL);
646             return NULL;
647         }
648
649         /* Ignore failures from these */
650         OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
651     }
652
653     set_sys_error(saveerrno);
654     return state;
655 }
656
657 /*
658  * err_shelve_state returns the current thread local error state
659  * and freezes the error module until err_unshelve_state is called.
660  */
661 int err_shelve_state(void **state)
662 {
663     int saveerrno = get_last_sys_error();
664
665     /*
666      * Note, at present our only caller is OPENSSL_init_crypto(), indirectly
667      * via ossl_init_load_crypto_nodelete(), by which point the requested
668      * "base" initialization has already been performed, so the below call is a
669      * NOOP, that re-enters OPENSSL_init_crypto() only to quickly return.
670      *
671      * If are no other valid callers of this function, the call below can be
672      * removed, avoiding the re-entry into OPENSSL_init_crypto().  If there are
673      * potential uses that are not from inside OPENSSL_init_crypto(), then this
674      * call is needed, but some care is required to make sure that the re-entry
675      * remains a NOOP.
676      */
677     if (!OPENSSL_init_crypto(OPENSSL_INIT_BASE_ONLY, NULL))
678         return 0;
679
680     if (!RUN_ONCE(&err_init, err_do_init))
681         return 0;
682
683     *state = CRYPTO_THREAD_get_local(&err_thread_local);
684     if (!CRYPTO_THREAD_set_local(&err_thread_local, (ERR_STATE*)-1))
685         return 0;
686
687     set_sys_error(saveerrno);
688     return 1;
689 }
690
691 /*
692  * err_unshelve_state restores the error state that was returned
693  * by err_shelve_state previously.
694  */
695 void err_unshelve_state(void* state)
696 {
697     if (state != (void*)-1)
698         CRYPTO_THREAD_set_local(&err_thread_local, (ERR_STATE*)state);
699 }
700
701 int ERR_get_next_error_library(void)
702 {
703     int ret;
704
705     if (!RUN_ONCE(&err_string_init, do_err_strings_init))
706         return 0;
707
708     CRYPTO_THREAD_write_lock(err_string_lock);
709     ret = int_err_library_number++;
710     CRYPTO_THREAD_unlock(err_string_lock);
711     return ret;
712 }
713
714 static int err_set_error_data_int(char *data, size_t size, int flags,
715                                   int deallocate)
716 {
717     ERR_STATE *es;
718
719     es = ERR_get_state();
720     if (es == NULL)
721         return 0;
722
723     err_clear_data(es, es->top, deallocate);
724     err_set_data(es, es->top, data, size, flags);
725
726     return 1;
727 }
728
729 void ERR_set_error_data(char *data, int flags)
730 {
731     /*
732      * This function is void so we cannot propagate the error return. Since it
733      * is also in the public API we can't change the return type.
734      *
735      * We estimate the size of the data.  If it's not flagged as allocated,
736      * then this is safe, and if it is flagged as allocated, then our size
737      * may be smaller than the actual allocation, but that doesn't matter
738      * too much, the buffer will remain untouched or will eventually be
739      * reallocated to a new size.
740      *
741      * callers should be advised that this function takes over ownership of
742      * the allocated memory, i.e. they can't count on the pointer to remain
743      * valid.
744      */
745     err_set_error_data_int(data, strlen(data) + 1, flags, 1);
746 }
747
748 void ERR_add_error_data(int num, ...)
749 {
750     va_list args;
751     va_start(args, num);
752     ERR_add_error_vdata(num, args);
753     va_end(args);
754 }
755
756 void ERR_add_error_vdata(int num, va_list args)
757 {
758     int i, len, size;
759     int flags = ERR_TXT_MALLOCED | ERR_TXT_STRING;
760     char *str, *arg;
761     ERR_STATE *es;
762
763     /* Get the current error data; if an allocated string get it. */
764     es = ERR_get_state();
765     if (es == NULL)
766         return;
767     i = es->top;
768
769     /*
770      * If err_data is allocated already, re-use the space.
771      * Otherwise, allocate a small new buffer.
772      */
773     if ((es->err_data_flags[i] & flags) == flags) {
774         str = es->err_data[i];
775         size = es->err_data_size[i];
776
777         /*
778          * To protect the string we just grabbed from tampering by other
779          * functions we may call, or to protect them from freeing a pointer
780          * that may no longer be valid at that point, we clear away the
781          * data pointer and the flags.  We will set them again at the end
782          * of this function.
783          */
784         es->err_data[i] = NULL;
785         es->err_data_flags[i] = 0;
786     } else if ((str = OPENSSL_malloc(size = 81)) == NULL) {
787         return;
788     } else {
789         str[0] = '\0';
790     }
791     len = strlen(str);
792
793     for (len = 0; --num >= 0; ) {
794         arg = va_arg(args, char *);
795         if (arg == NULL)
796             arg = "<NULL>";
797         len += strlen(arg);
798         if (len >= size) {
799             char *p;
800
801             size = len + 20;
802             p = OPENSSL_realloc(str, size);
803             if (p == NULL) {
804                 OPENSSL_free(str);
805                 return;
806             }
807             str = p;
808         }
809         OPENSSL_strlcat(str, arg, (size_t)size);
810     }
811     if (!err_set_error_data_int(str, size, flags, 0))
812         OPENSSL_free(str);
813 }
814
815 int ERR_set_mark(void)
816 {
817     ERR_STATE *es;
818
819     es = ERR_get_state();
820     if (es == NULL)
821         return 0;
822
823     if (es->bottom == es->top)
824         return 0;
825     es->err_flags[es->top] |= ERR_FLAG_MARK;
826     return 1;
827 }
828
829 int ERR_pop_to_mark(void)
830 {
831     ERR_STATE *es;
832
833     es = ERR_get_state();
834     if (es == NULL)
835         return 0;
836
837     while (es->bottom != es->top
838            && (es->err_flags[es->top] & ERR_FLAG_MARK) == 0) {
839         err_clear(es, es->top, 0);
840         es->top = es->top > 0 ? es->top - 1 : ERR_NUM_ERRORS - 1;
841     }
842
843     if (es->bottom == es->top)
844         return 0;
845     es->err_flags[es->top] &= ~ERR_FLAG_MARK;
846     return 1;
847 }
848
849 int ERR_clear_last_mark(void)
850 {
851     ERR_STATE *es;
852     int top;
853
854     es = ERR_get_state();
855     if (es == NULL)
856         return 0;
857
858     top = es->top;
859     while (es->bottom != top
860            && (es->err_flags[top] & ERR_FLAG_MARK) == 0) {
861         top = top > 0 ? top - 1 : ERR_NUM_ERRORS - 1;
862     }
863
864     if (es->bottom == top)
865         return 0;
866     es->err_flags[top] &= ~ERR_FLAG_MARK;
867     return 1;
868 }
869
870 void err_clear_last_constant_time(int clear)
871 {
872     ERR_STATE *es;
873     int top;
874
875     es = ERR_get_state();
876     if (es == NULL)
877         return;
878
879     top = es->top;
880
881     /*
882      * Flag error as cleared but remove it elsewhere to avoid two errors
883      * accessing the same error stack location, revealing timing information.
884      */
885     clear = constant_time_select_int(constant_time_eq_int(clear, 0),
886                                      0, ERR_FLAG_CLEAR);
887     es->err_flags[top] |= clear;
888 }