xref: /openbsd-src/lib/libcrypto/err/err.c (revision 68dd5bb1859285b71cb62a10bf107b8ad54064d9)
1 /* $OpenBSD: err.c,v 1.56 2023/07/28 10:23:19 tb Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 
112 #include <pthread.h>
113 #include <stdarg.h>
114 #include <stdio.h>
115 #include <string.h>
116 
117 #include <openssl/opensslconf.h>
118 
119 #include <openssl/bio.h>
120 #include <openssl/buffer.h>
121 #include <openssl/crypto.h>
122 #include <openssl/err.h>
123 #include <openssl/lhash.h>
124 
125 DECLARE_LHASH_OF(ERR_STRING_DATA);
126 DECLARE_LHASH_OF(ERR_STATE);
127 
128 typedef struct st_ERR_FNS ERR_FNS;
129 
130 static void err_load_strings(int lib, ERR_STRING_DATA *str);
131 
132 static void ERR_STATE_free(ERR_STATE *s);
133 #ifndef OPENSSL_NO_ERR
134 static ERR_STRING_DATA ERR_str_libraries[] = {
135 	{ERR_PACK(ERR_LIB_NONE,0,0),		"unknown library"},
136 	{ERR_PACK(ERR_LIB_SYS,0,0),		"system library"},
137 	{ERR_PACK(ERR_LIB_BN,0,0),		"bignum routines"},
138 	{ERR_PACK(ERR_LIB_RSA,0,0),		"rsa routines"},
139 	{ERR_PACK(ERR_LIB_DH,0,0),		"Diffie-Hellman routines"},
140 	{ERR_PACK(ERR_LIB_EVP,0,0),		"digital envelope routines"},
141 	{ERR_PACK(ERR_LIB_BUF,0,0),		"memory buffer routines"},
142 	{ERR_PACK(ERR_LIB_OBJ,0,0),		"object identifier routines"},
143 	{ERR_PACK(ERR_LIB_PEM,0,0),		"PEM routines"},
144 	{ERR_PACK(ERR_LIB_DSA,0,0),		"dsa routines"},
145 	{ERR_PACK(ERR_LIB_X509,0,0),		"x509 certificate routines"},
146 	{ERR_PACK(ERR_LIB_ASN1,0,0),		"asn1 encoding routines"},
147 	{ERR_PACK(ERR_LIB_CONF,0,0),		"configuration file routines"},
148 	{ERR_PACK(ERR_LIB_CRYPTO,0,0),		"common libcrypto routines"},
149 	{ERR_PACK(ERR_LIB_EC,0,0),		"elliptic curve routines"},
150 	{ERR_PACK(ERR_LIB_SSL,0,0),		"SSL routines"},
151 	{ERR_PACK(ERR_LIB_BIO,0,0),		"BIO routines"},
152 	{ERR_PACK(ERR_LIB_PKCS7,0,0),		"PKCS7 routines"},
153 	{ERR_PACK(ERR_LIB_X509V3,0,0),		"X509 V3 routines"},
154 	{ERR_PACK(ERR_LIB_PKCS12,0,0),		"PKCS12 routines"},
155 	{ERR_PACK(ERR_LIB_RAND,0,0),		"random number generator"},
156 	{ERR_PACK(ERR_LIB_DSO,0,0),		"DSO support routines"},
157 	{ERR_PACK(ERR_LIB_TS,0,0),		"time stamp routines"},
158 	{ERR_PACK(ERR_LIB_ENGINE,0,0),		"engine routines"},
159 	{ERR_PACK(ERR_LIB_OCSP,0,0),		"OCSP routines"},
160 	{ERR_PACK(ERR_LIB_FIPS,0,0),		"FIPS routines"},
161 	{ERR_PACK(ERR_LIB_CMS,0,0),		"CMS routines"},
162 	{ERR_PACK(ERR_LIB_HMAC,0,0),		"HMAC routines"},
163 	{ERR_PACK(ERR_LIB_GOST,0,0),		"GOST routines"},
164 	{0, NULL},
165 };
166 
167 static ERR_STRING_DATA ERR_str_functs[] = {
168 	{ERR_PACK(0,SYS_F_FOPEN, 0),     	"fopen"},
169 	{ERR_PACK(0,SYS_F_CONNECT, 0),		"connect"},
170 	{ERR_PACK(0,SYS_F_GETSERVBYNAME, 0),	"getservbyname"},
171 	{ERR_PACK(0,SYS_F_SOCKET, 0),		"socket"},
172 	{ERR_PACK(0,SYS_F_IOCTLSOCKET, 0),	"ioctl"},
173 	{ERR_PACK(0,SYS_F_BIND, 0),		"bind"},
174 	{ERR_PACK(0,SYS_F_LISTEN, 0),		"listen"},
175 	{ERR_PACK(0,SYS_F_ACCEPT, 0),		"accept"},
176 	{ERR_PACK(0,SYS_F_OPENDIR, 0),		"opendir"},
177 	{ERR_PACK(0,SYS_F_FREAD, 0),		"fread"},
178 	{0, NULL},
179 };
180 
181 static ERR_STRING_DATA ERR_str_reasons[] = {
182 	{ERR_R_SYS_LIB,				"system lib"},
183 	{ERR_R_BN_LIB,				"BN lib"},
184 	{ERR_R_RSA_LIB,				"RSA lib"},
185 	{ERR_R_DH_LIB,				"DH lib"},
186 	{ERR_R_EVP_LIB,				"EVP lib"},
187 	{ERR_R_BUF_LIB,				"BUF lib"},
188 	{ERR_R_OBJ_LIB,				"OBJ lib"},
189 	{ERR_R_PEM_LIB,				"PEM lib"},
190 	{ERR_R_DSA_LIB,				"DSA lib"},
191 	{ERR_R_X509_LIB,			"X509 lib"},
192 	{ERR_R_ASN1_LIB,			"ASN1 lib"},
193 	{ERR_R_CONF_LIB,			"CONF lib"},
194 	{ERR_R_CRYPTO_LIB,			"CRYPTO lib"},
195 	{ERR_R_EC_LIB,				"EC lib"},
196 	{ERR_R_SSL_LIB,				"SSL lib"},
197 	{ERR_R_BIO_LIB,				"BIO lib"},
198 	{ERR_R_PKCS7_LIB,			"PKCS7 lib"},
199 	{ERR_R_X509V3_LIB,			"X509V3 lib"},
200 	{ERR_R_PKCS12_LIB,			"PKCS12 lib"},
201 	{ERR_R_RAND_LIB,			"RAND lib"},
202 	{ERR_R_DSO_LIB,				"DSO lib"},
203 	{ERR_R_ENGINE_LIB,			"ENGINE lib"},
204 	{ERR_R_OCSP_LIB,			"OCSP lib"},
205 	{ERR_R_TS_LIB,				"TS lib"},
206 
207 	{ERR_R_NESTED_ASN1_ERROR,		"nested asn1 error"},
208 	{ERR_R_BAD_ASN1_OBJECT_HEADER,		"bad asn1 object header"},
209 	{ERR_R_BAD_GET_ASN1_OBJECT_CALL,	"bad get asn1 object call"},
210 	{ERR_R_EXPECTING_AN_ASN1_SEQUENCE,	"expecting an asn1 sequence"},
211 	{ERR_R_ASN1_LENGTH_MISMATCH,		"asn1 length mismatch"},
212 	{ERR_R_MISSING_ASN1_EOS,		"missing asn1 eos"},
213 
214 	{ERR_R_FATAL,				"fatal"},
215 	{ERR_R_MALLOC_FAILURE,			"malloc failure"},
216 	{ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED,	"called a function you should not call"},
217 	{ERR_R_PASSED_NULL_PARAMETER,		"passed a null parameter"},
218 	{ERR_R_INTERNAL_ERROR,			"internal error"},
219 	{ERR_R_DISABLED	,			"called a function that was disabled at compile-time"},
220 	{ERR_R_INIT_FAIL,			"initialization failure"},
221 
222 	{0, NULL},
223 };
224 #endif
225 
226 
227 /* Define the predeclared (but externally opaque) "ERR_FNS" type */
228 struct st_ERR_FNS {
229 	/* Works on the "error_hash" string table */
230 	LHASH_OF(ERR_STRING_DATA) *(*cb_err_get)(int create);
231 	void (*cb_err_del)(void);
232 	ERR_STRING_DATA *(*cb_err_get_item)(const ERR_STRING_DATA *);
233 	ERR_STRING_DATA *(*cb_err_set_item)(ERR_STRING_DATA *);
234 	ERR_STRING_DATA *(*cb_err_del_item)(ERR_STRING_DATA *);
235 	/* Works on the "thread_hash" error-state table */
236 	LHASH_OF(ERR_STATE) *(*cb_thread_get)(int create);
237 	void (*cb_thread_release)(LHASH_OF(ERR_STATE) **hash);
238 	ERR_STATE *(*cb_thread_get_item)(const ERR_STATE *);
239 	ERR_STATE *(*cb_thread_set_item)(ERR_STATE *);
240 	void (*cb_thread_del_item)(const ERR_STATE *);
241 	/* Returns the next available error "library" numbers */
242 	int (*cb_get_next_lib)(void);
243 };
244 
245 /* Predeclarations of the "err_defaults" functions */
246 static LHASH_OF(ERR_STRING_DATA) *int_err_get(int create);
247 static void int_err_del(void);
248 static ERR_STRING_DATA *int_err_get_item(const ERR_STRING_DATA *);
249 static ERR_STRING_DATA *int_err_set_item(ERR_STRING_DATA *);
250 static ERR_STRING_DATA *int_err_del_item(ERR_STRING_DATA *);
251 static LHASH_OF(ERR_STATE) *int_thread_get(int create);
252 static void int_thread_release(LHASH_OF(ERR_STATE) **hash);
253 static ERR_STATE *int_thread_get_item(const ERR_STATE *);
254 static ERR_STATE *int_thread_set_item(ERR_STATE *);
255 static void int_thread_del_item(const ERR_STATE *);
256 static int int_err_get_next_lib(void);
257 
258 /* The static ERR_FNS table using these defaults functions */
259 static const ERR_FNS err_defaults = {
260 	int_err_get,
261 	int_err_del,
262 	int_err_get_item,
263 	int_err_set_item,
264 	int_err_del_item,
265 	int_thread_get,
266 	int_thread_release,
267 	int_thread_get_item,
268 	int_thread_set_item,
269 	int_thread_del_item,
270 	int_err_get_next_lib
271 };
272 
273 /* The replacable table of ERR_FNS functions we use at run-time */
274 static const ERR_FNS *err_fns = NULL;
275 
276 /* Eg. rather than using "err_get()", use "ERRFN(err_get)()". */
277 #define ERRFN(a) err_fns->cb_##a
278 
279 /* The internal state used by "err_defaults" - as such, the setting, reading,
280  * creating, and deleting of this data should only be permitted via the
281  * "err_defaults" functions. This way, a linked module can completely defer all
282  * ERR state operation (together with requisite locking) to the implementations
283  * and state in the loading application. */
284 static LHASH_OF(ERR_STRING_DATA) *int_error_hash = NULL;
285 static LHASH_OF(ERR_STATE) *int_thread_hash = NULL;
286 static int int_thread_hash_references = 0;
287 static int int_err_library_number = ERR_LIB_USER;
288 
289 static pthread_t err_init_thread;
290 
291 /* Internal function that checks whether "err_fns" is set and if not, sets it to
292  * the defaults. */
293 static void
294 err_fns_check(void)
295 {
296 	if (err_fns)
297 		return;
298 
299 	CRYPTO_w_lock(CRYPTO_LOCK_ERR);
300 	if (!err_fns)
301 		err_fns = &err_defaults;
302 	CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
303 }
304 
305 /* These are the callbacks provided to "lh_new()" when creating the LHASH tables
306  * internal to the "err_defaults" implementation. */
307 
308 static unsigned long get_error_values(int inc, int top, const char **file,
309     int *line, const char **data, int *flags);
310 
311 /* The internal functions used in the "err_defaults" implementation */
312 
313 static unsigned long
314 err_string_data_hash(const ERR_STRING_DATA *a)
315 {
316 	unsigned long ret, l;
317 
318 	l = a->error;
319 	ret = l^ERR_GET_LIB(l)^ERR_GET_FUNC(l);
320 	return (ret^ret % 19*13);
321 }
322 static IMPLEMENT_LHASH_HASH_FN(err_string_data, ERR_STRING_DATA)
323 
324 static int
325 err_string_data_cmp(const ERR_STRING_DATA *a, const ERR_STRING_DATA *b)
326 {
327 	return (int)(a->error - b->error);
328 }
329 static IMPLEMENT_LHASH_COMP_FN(err_string_data, ERR_STRING_DATA)
330 
331 static
332 LHASH_OF(ERR_STRING_DATA) *int_err_get(int create)
333 {
334 	LHASH_OF(ERR_STRING_DATA) *ret = NULL;
335 
336 	CRYPTO_w_lock(CRYPTO_LOCK_ERR);
337 	if (!int_error_hash && create) {
338 		CRYPTO_push_info("int_err_get (err.c)");
339 		int_error_hash = lh_ERR_STRING_DATA_new();
340 		CRYPTO_pop_info();
341 	}
342 	if (int_error_hash)
343 		ret = int_error_hash;
344 	CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
345 
346 	return ret;
347 }
348 
349 static void
350 int_err_del(void)
351 {
352 	CRYPTO_w_lock(CRYPTO_LOCK_ERR);
353 	if (int_error_hash) {
354 		lh_ERR_STRING_DATA_free(int_error_hash);
355 		int_error_hash = NULL;
356 	}
357 	CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
358 }
359 
360 static ERR_STRING_DATA *
361 int_err_get_item(const ERR_STRING_DATA *d)
362 {
363 	ERR_STRING_DATA *p;
364 	LHASH_OF(ERR_STRING_DATA) *hash;
365 
366 	err_fns_check();
367 	hash = ERRFN(err_get)(0);
368 	if (!hash)
369 		return NULL;
370 
371 	CRYPTO_r_lock(CRYPTO_LOCK_ERR);
372 	p = lh_ERR_STRING_DATA_retrieve(hash, d);
373 	CRYPTO_r_unlock(CRYPTO_LOCK_ERR);
374 
375 	return p;
376 }
377 
378 static ERR_STRING_DATA *
379 int_err_set_item(ERR_STRING_DATA *d)
380 {
381 	ERR_STRING_DATA *p;
382 	LHASH_OF(ERR_STRING_DATA) *hash;
383 
384 	err_fns_check();
385 	hash = ERRFN(err_get)(1);
386 	if (!hash)
387 		return NULL;
388 
389 	CRYPTO_w_lock(CRYPTO_LOCK_ERR);
390 	p = lh_ERR_STRING_DATA_insert(hash, d);
391 	CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
392 
393 	return p;
394 }
395 
396 static ERR_STRING_DATA *
397 int_err_del_item(ERR_STRING_DATA *d)
398 {
399 	ERR_STRING_DATA *p;
400 	LHASH_OF(ERR_STRING_DATA) *hash;
401 
402 	err_fns_check();
403 	hash = ERRFN(err_get)(0);
404 	if (!hash)
405 		return NULL;
406 
407 	CRYPTO_w_lock(CRYPTO_LOCK_ERR);
408 	p = lh_ERR_STRING_DATA_delete(hash, d);
409 	CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
410 
411 	return p;
412 }
413 
414 static unsigned long
415 err_state_hash(const ERR_STATE *a)
416 {
417 	return CRYPTO_THREADID_hash(&a->tid) * 13;
418 }
419 static IMPLEMENT_LHASH_HASH_FN(err_state, ERR_STATE)
420 
421 static int
422 err_state_cmp(const ERR_STATE *a, const ERR_STATE *b)
423 {
424 	return CRYPTO_THREADID_cmp(&a->tid, &b->tid);
425 }
426 static IMPLEMENT_LHASH_COMP_FN(err_state, ERR_STATE)
427 
428 static
429 LHASH_OF(ERR_STATE) *int_thread_get(int create)
430 {
431 	LHASH_OF(ERR_STATE) *ret = NULL;
432 
433 	CRYPTO_w_lock(CRYPTO_LOCK_ERR);
434 	if (!int_thread_hash && create) {
435 		CRYPTO_push_info("int_thread_get (err.c)");
436 		int_thread_hash = lh_ERR_STATE_new();
437 		CRYPTO_pop_info();
438 	}
439 	if (int_thread_hash) {
440 		int_thread_hash_references++;
441 		ret = int_thread_hash;
442 	}
443 	CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
444 	return ret;
445 }
446 
447 static void
448 int_thread_release(LHASH_OF(ERR_STATE) **hash)
449 {
450 	int i;
451 
452 	if (hash == NULL || *hash == NULL)
453 		return;
454 
455 	i = CRYPTO_add(&int_thread_hash_references, -1, CRYPTO_LOCK_ERR);
456 	if (i > 0)
457 		return;
458 
459 	*hash = NULL;
460 }
461 
462 static ERR_STATE *
463 int_thread_get_item(const ERR_STATE *d)
464 {
465 	ERR_STATE *p;
466 	LHASH_OF(ERR_STATE) *hash;
467 
468 	err_fns_check();
469 	hash = ERRFN(thread_get)(0);
470 	if (!hash)
471 		return NULL;
472 
473 	CRYPTO_r_lock(CRYPTO_LOCK_ERR);
474 	p = lh_ERR_STATE_retrieve(hash, d);
475 	CRYPTO_r_unlock(CRYPTO_LOCK_ERR);
476 
477 	ERRFN(thread_release)(&hash);
478 	return p;
479 }
480 
481 static ERR_STATE *
482 int_thread_set_item(ERR_STATE *d)
483 {
484 	ERR_STATE *p;
485 	LHASH_OF(ERR_STATE) *hash;
486 
487 	err_fns_check();
488 	hash = ERRFN(thread_get)(1);
489 	if (!hash)
490 		return NULL;
491 
492 	CRYPTO_w_lock(CRYPTO_LOCK_ERR);
493 	p = lh_ERR_STATE_insert(hash, d);
494 	CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
495 
496 	ERRFN(thread_release)(&hash);
497 	return p;
498 }
499 
500 static void
501 int_thread_del_item(const ERR_STATE *d)
502 {
503 	ERR_STATE *p;
504 	LHASH_OF(ERR_STATE) *hash;
505 
506 	err_fns_check();
507 	hash = ERRFN(thread_get)(0);
508 	if (!hash)
509 		return;
510 
511 	CRYPTO_w_lock(CRYPTO_LOCK_ERR);
512 	p = lh_ERR_STATE_delete(hash, d);
513 	/* make sure we don't leak memory */
514 	if (int_thread_hash_references == 1 &&
515 	    int_thread_hash && lh_ERR_STATE_num_items(int_thread_hash) == 0) {
516 		lh_ERR_STATE_free(int_thread_hash);
517 		int_thread_hash = NULL;
518 	}
519 	CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
520 
521 	ERRFN(thread_release)(&hash);
522 	if (p)
523 		ERR_STATE_free(p);
524 }
525 
526 static int
527 int_err_get_next_lib(void)
528 {
529 	int ret;
530 
531 	CRYPTO_w_lock(CRYPTO_LOCK_ERR);
532 	ret = int_err_library_number++;
533 	CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
534 
535 	return ret;
536 }
537 
538 
539 #ifndef OPENSSL_NO_ERR
540 #define NUM_SYS_STR_REASONS 127
541 #define LEN_SYS_STR_REASON 32
542 
543 static ERR_STRING_DATA SYS_str_reasons[NUM_SYS_STR_REASONS + 1];
544 /* SYS_str_reasons is filled with copies of strerror() results at
545  * initialization.
546  * 'errno' values up to 127 should cover all usual errors,
547  * others will be displayed numerically by ERR_error_string.
548  * It is crucial that we have something for each reason code
549  * that occurs in ERR_str_reasons, or bogus reason strings
550  * will be returned for SYSerror(which always gets an errno
551  * value and never one of those 'standard' reason codes. */
552 
553 static void
554 build_SYS_str_reasons(void)
555 {
556 	/* malloc cannot be used here, use static storage instead */
557 	static char strerror_tab[NUM_SYS_STR_REASONS][LEN_SYS_STR_REASON];
558 	int i;
559 	static int init = 1;
560 	int save_errno;
561 
562 	CRYPTO_r_lock(CRYPTO_LOCK_ERR);
563 	if (!init) {
564 		CRYPTO_r_unlock(CRYPTO_LOCK_ERR);
565 		return;
566 	}
567 
568 	CRYPTO_r_unlock(CRYPTO_LOCK_ERR);
569 	CRYPTO_w_lock(CRYPTO_LOCK_ERR);
570 	if (!init) {
571 		CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
572 		return;
573 	}
574 
575 	/* strerror(3) will set errno to EINVAL when i is an unknown errno. */
576 	save_errno = errno;
577 	for (i = 1; i <= NUM_SYS_STR_REASONS; i++) {
578 		ERR_STRING_DATA *str = &SYS_str_reasons[i - 1];
579 
580 		str->error = (unsigned long)i;
581 		if (str->string == NULL) {
582 			char (*dest)[LEN_SYS_STR_REASON] =
583 			    &(strerror_tab[i - 1]);
584 			const char *src = strerror(i);
585 			if (src != NULL) {
586 				strlcpy(*dest, src, sizeof *dest);
587 				str->string = *dest;
588 			}
589 		}
590 		if (str->string == NULL)
591 			str->string = "unknown";
592 	}
593 	errno = save_errno;
594 
595 	/* Now we still have SYS_str_reasons[NUM_SYS_STR_REASONS] = {0, NULL},
596 	 * as required by ERR_load_strings. */
597 
598 	init = 0;
599 
600 	CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
601 }
602 #endif
603 
604 #define err_clear_data(p,i) \
605 	do { \
606 		if (((p)->err_data[i] != NULL) && \
607 		    (p)->err_data_flags[i] & ERR_TXT_MALLOCED) { \
608 			free((p)->err_data[i]); \
609 			(p)->err_data[i] = NULL; \
610 		} \
611 		(p)->err_data_flags[i] = 0; \
612 	} while(0)
613 
614 #define err_clear(p,i) \
615 	do { \
616 		(p)->err_flags[i] = 0; \
617 		(p)->err_buffer[i] = 0; \
618 		err_clear_data(p, i); \
619 		(p)->err_file[i] = NULL; \
620 		(p)->err_line[i] = -1; \
621 	} while(0)
622 
623 static void
624 ERR_STATE_free(ERR_STATE *s)
625 {
626 	int i;
627 
628 	if (s == NULL)
629 		return;
630 
631 	for (i = 0; i < ERR_NUM_ERRORS; i++) {
632 		err_clear_data(s, i);
633 	}
634 	free(s);
635 }
636 
637 void
638 ERR_load_ERR_strings_internal(void)
639 {
640 	err_init_thread = pthread_self();
641 	err_fns_check();
642 #ifndef OPENSSL_NO_ERR
643 	err_load_strings(0, ERR_str_libraries);
644 	err_load_strings(0, ERR_str_reasons);
645 	err_load_strings(ERR_LIB_SYS, ERR_str_functs);
646 	build_SYS_str_reasons();
647 	err_load_strings(ERR_LIB_SYS, SYS_str_reasons);
648 #endif
649 }
650 
651 
652 void
653 ERR_load_ERR_strings(void)
654 {
655 	static pthread_once_t once = PTHREAD_ONCE_INIT;
656 
657 	if (pthread_equal(pthread_self(), err_init_thread))
658 		return; /* don't recurse */
659 
660 	/* Prayer and clean living lets you ignore errors, OpenSSL style */
661 	(void) OPENSSL_init_crypto(0, NULL);
662 
663 	(void) pthread_once(&once, ERR_load_ERR_strings_internal);
664 }
665 LCRYPTO_ALIAS(ERR_load_ERR_strings);
666 
667 static void
668 err_load_strings(int lib, ERR_STRING_DATA *str)
669 {
670 	while (str->error) {
671 		if (lib)
672 			str->error |= ERR_PACK(lib, 0, 0);
673 		ERRFN(err_set_item)(str);
674 		str++;
675 	}
676 }
677 
678 void
679 ERR_load_strings(int lib, ERR_STRING_DATA *str)
680 {
681 	ERR_load_ERR_strings();
682 	err_load_strings(lib, str);
683 }
684 LCRYPTO_ALIAS(ERR_load_strings);
685 
686 void
687 ERR_unload_strings(int lib, ERR_STRING_DATA *str)
688 {
689 	/* Prayer and clean living lets you ignore errors, OpenSSL style */
690 	(void) OPENSSL_init_crypto(0, NULL);
691 
692 	while (str->error) {
693 		if (lib)
694 			str->error |= ERR_PACK(lib, 0, 0);
695 		ERRFN(err_del_item)(str);
696 		str++;
697 	}
698 }
699 LCRYPTO_ALIAS(ERR_unload_strings);
700 
701 void
702 ERR_free_strings(void)
703 {
704 	/* Prayer and clean living lets you ignore errors, OpenSSL style */
705 	(void) OPENSSL_init_crypto(0, NULL);
706 
707 	err_fns_check();
708 	ERRFN(err_del)();
709 }
710 LCRYPTO_ALIAS(ERR_free_strings);
711 
712 /********************************************************/
713 
714 void
715 ERR_put_error(int lib, int func, int reason, const char *file, int line)
716 {
717 	ERR_STATE *es;
718 	int save_errno = errno;
719 
720 	es = ERR_get_state();
721 
722 	es->top = (es->top + 1) % ERR_NUM_ERRORS;
723 	if (es->top == es->bottom)
724 		es->bottom = (es->bottom + 1) % ERR_NUM_ERRORS;
725 	es->err_flags[es->top] = 0;
726 	es->err_buffer[es->top] = ERR_PACK(lib, func, reason);
727 	es->err_file[es->top] = file;
728 	es->err_line[es->top] = line;
729 	err_clear_data(es, es->top);
730 	errno = save_errno;
731 }
732 LCRYPTO_ALIAS(ERR_put_error);
733 
734 void
735 ERR_clear_error(void)
736 {
737 	int i;
738 	ERR_STATE *es;
739 
740 	es = ERR_get_state();
741 
742 	for (i = 0; i < ERR_NUM_ERRORS; i++) {
743 		err_clear(es, i);
744 	}
745 	es->top = es->bottom = 0;
746 }
747 LCRYPTO_ALIAS(ERR_clear_error);
748 
749 
750 unsigned long
751 ERR_get_error(void)
752 {
753 	return (get_error_values(1, 0, NULL, NULL, NULL, NULL));
754 }
755 LCRYPTO_ALIAS(ERR_get_error);
756 
757 unsigned long
758 ERR_get_error_line(const char **file, int *line)
759 {
760 	return (get_error_values(1, 0, file, line, NULL, NULL));
761 }
762 LCRYPTO_ALIAS(ERR_get_error_line);
763 
764 unsigned long
765 ERR_get_error_line_data(const char **file, int *line,
766     const char **data, int *flags)
767 {
768 	return (get_error_values(1, 0, file, line, data, flags));
769 }
770 LCRYPTO_ALIAS(ERR_get_error_line_data);
771 
772 
773 unsigned long
774 ERR_peek_error(void)
775 {
776 	return (get_error_values(0, 0, NULL, NULL, NULL, NULL));
777 }
778 LCRYPTO_ALIAS(ERR_peek_error);
779 
780 unsigned long
781 ERR_peek_error_line(const char **file, int *line)
782 {
783 	return (get_error_values(0, 0, file, line, NULL, NULL));
784 }
785 LCRYPTO_ALIAS(ERR_peek_error_line);
786 
787 unsigned long
788 ERR_peek_error_line_data(const char **file, int *line,
789     const char **data, int *flags)
790 {
791 	return (get_error_values(0, 0, file, line, data, flags));
792 }
793 LCRYPTO_ALIAS(ERR_peek_error_line_data);
794 
795 unsigned long
796 ERR_peek_last_error(void)
797 {
798 	return (get_error_values(0, 1, NULL, NULL, NULL, NULL));
799 }
800 LCRYPTO_ALIAS(ERR_peek_last_error);
801 
802 unsigned long
803 ERR_peek_last_error_line(const char **file, int *line)
804 {
805 	return (get_error_values(0, 1, file, line, NULL, NULL));
806 }
807 LCRYPTO_ALIAS(ERR_peek_last_error_line);
808 
809 unsigned long
810 ERR_peek_last_error_line_data(const char **file, int *line,
811     const char **data, int *flags)
812 {
813 	return (get_error_values(0, 1, file, line, data, flags));
814 }
815 LCRYPTO_ALIAS(ERR_peek_last_error_line_data);
816 
817 static unsigned long
818 get_error_values(int inc, int top, const char **file, int *line,
819     const char **data, int *flags)
820 {
821 	int i = 0;
822 	ERR_STATE *es;
823 	unsigned long ret;
824 
825 	es = ERR_get_state();
826 
827 	if (inc && top) {
828 		if (file)
829 			*file = "";
830 		if (line)
831 			*line = 0;
832 		if (data)
833 			*data = "";
834 		if (flags)
835 			*flags = 0;
836 
837 		return ERR_R_INTERNAL_ERROR;
838 	}
839 
840 	if (es->bottom == es->top)
841 		return 0;
842 	if (top)
843 		i = es->top;			 /* last error */
844 	else
845 		i = (es->bottom + 1) % ERR_NUM_ERRORS; /* first error */
846 
847 	ret = es->err_buffer[i];
848 	if (inc) {
849 		es->bottom = i;
850 		es->err_buffer[i] = 0;
851 	}
852 
853 	if ((file != NULL) && (line != NULL)) {
854 		if (es->err_file[i] == NULL) {
855 			*file = "NA";
856 			if (line != NULL)
857 				*line = 0;
858 		} else {
859 			*file = es->err_file[i];
860 			if (line != NULL)
861 				*line = es->err_line[i];
862 		}
863 	}
864 
865 	if (data == NULL) {
866 		if (inc) {
867 			err_clear_data(es, i);
868 		}
869 	} else {
870 		if (es->err_data[i] == NULL) {
871 			*data = "";
872 			if (flags != NULL)
873 				*flags = 0;
874 		} else {
875 			*data = es->err_data[i];
876 			if (flags != NULL)
877 				*flags = es->err_data_flags[i];
878 		}
879 	}
880 	return ret;
881 }
882 
883 void
884 ERR_error_string_n(unsigned long e, char *buf, size_t len)
885 {
886 	char lsbuf[30], fsbuf[30], rsbuf[30];
887 	const char *ls, *fs, *rs;
888 	int l, f, r, ret;
889 
890 	l = ERR_GET_LIB(e);
891 	f = ERR_GET_FUNC(e);
892 	r = ERR_GET_REASON(e);
893 
894 	ls = ERR_lib_error_string(e);
895 	fs = ERR_func_error_string(e);
896 	rs = ERR_reason_error_string(e);
897 
898 	if (ls == NULL) {
899 		(void) snprintf(lsbuf, sizeof(lsbuf), "lib(%d)", l);
900 		ls = lsbuf;
901 	}
902 	if (fs == NULL) {
903 		(void) snprintf(fsbuf, sizeof(fsbuf), "func(%d)", f);
904 		fs = fsbuf;
905 	}
906 	if (rs == NULL) {
907 		(void) snprintf(rsbuf, sizeof(rsbuf), "reason(%d)", r);
908 		rs = rsbuf;
909 	}
910 
911 	ret = snprintf(buf, len, "error:%08lX:%s:%s:%s", e, ls, fs, rs);
912 	if (ret == -1)
913 		return;	/* can't happen, and can't do better if it does */
914 	if (ret >= len) {
915 		/* output may be truncated; make sure we always have 5
916 		 * colon-separated fields, i.e. 4 colons ... */
917 #define NUM_COLONS 4
918 		if (len > NUM_COLONS) /* ... if possible */
919 		{
920 			int i;
921 			char *s = buf;
922 
923 			for (i = 0; i < NUM_COLONS; i++) {
924 				char *colon = strchr(s, ':');
925 				if (colon == NULL ||
926 				    colon > &buf[len - 1] - NUM_COLONS + i) {
927 					/* set colon no. i at last possible position
928 					 * (buf[len-1] is the terminating 0)*/
929 					colon = &buf[len - 1] - NUM_COLONS + i;
930 					*colon = ':';
931 				}
932 				s = colon + 1;
933 			}
934 		}
935 	}
936 }
937 LCRYPTO_ALIAS(ERR_error_string_n);
938 
939 /* BAD for multi-threading: uses a local buffer if ret == NULL */
940 /* ERR_error_string_n should be used instead for ret != NULL
941  * as ERR_error_string cannot know how large the buffer is */
942 char *
943 ERR_error_string(unsigned long e, char *ret)
944 {
945 	static char buf[256];
946 
947 	if (ret == NULL)
948 		ret = buf;
949 	ERR_error_string_n(e, ret, 256);
950 
951 	return ret;
952 }
953 LCRYPTO_ALIAS(ERR_error_string);
954 
955 const char *
956 ERR_lib_error_string(unsigned long e)
957 {
958 	ERR_STRING_DATA d, *p;
959 	unsigned long l;
960 
961 	if (!OPENSSL_init_crypto(0, NULL))
962 		return NULL;
963 
964 	err_fns_check();
965 	l = ERR_GET_LIB(e);
966 	d.error = ERR_PACK(l, 0, 0);
967 	p = ERRFN(err_get_item)(&d);
968 	return ((p == NULL) ? NULL : p->string);
969 }
970 LCRYPTO_ALIAS(ERR_lib_error_string);
971 
972 const char *
973 ERR_func_error_string(unsigned long e)
974 {
975 	ERR_STRING_DATA d, *p;
976 	unsigned long l, f;
977 
978 	err_fns_check();
979 	l = ERR_GET_LIB(e);
980 	f = ERR_GET_FUNC(e);
981 	d.error = ERR_PACK(l, f, 0);
982 	p = ERRFN(err_get_item)(&d);
983 	return ((p == NULL) ? NULL : p->string);
984 }
985 LCRYPTO_ALIAS(ERR_func_error_string);
986 
987 const char *
988 ERR_reason_error_string(unsigned long e)
989 {
990 	ERR_STRING_DATA d, *p = NULL;
991 	unsigned long l, r;
992 
993 	err_fns_check();
994 	l = ERR_GET_LIB(e);
995 	r = ERR_GET_REASON(e);
996 	d.error = ERR_PACK(l, 0, r);
997 	p = ERRFN(err_get_item)(&d);
998 	if (!p) {
999 		d.error = ERR_PACK(0, 0, r);
1000 		p = ERRFN(err_get_item)(&d);
1001 	}
1002 	return ((p == NULL) ? NULL : p->string);
1003 }
1004 LCRYPTO_ALIAS(ERR_reason_error_string);
1005 
1006 void
1007 ERR_remove_thread_state(const CRYPTO_THREADID *id)
1008 {
1009 	ERR_STATE tmp;
1010 
1011 	if (id)
1012 		CRYPTO_THREADID_cpy(&tmp.tid, id);
1013 	else
1014 		CRYPTO_THREADID_current(&tmp.tid);
1015 	err_fns_check();
1016 	/* thread_del_item automatically destroys the LHASH if the number of
1017 	 * items reaches zero. */
1018 	ERRFN(thread_del_item)(&tmp);
1019 }
1020 LCRYPTO_ALIAS(ERR_remove_thread_state);
1021 
1022 void
1023 ERR_remove_state(unsigned long pid)
1024 {
1025 	ERR_remove_thread_state(NULL);
1026 }
1027 LCRYPTO_ALIAS(ERR_remove_state);
1028 
1029 ERR_STATE *
1030 ERR_get_state(void)
1031 {
1032 	static ERR_STATE fallback;
1033 	ERR_STATE *ret, tmp, *tmpp = NULL;
1034 	int i;
1035 	CRYPTO_THREADID tid;
1036 
1037 	err_fns_check();
1038 	CRYPTO_THREADID_current(&tid);
1039 	CRYPTO_THREADID_cpy(&tmp.tid, &tid);
1040 	ret = ERRFN(thread_get_item)(&tmp);
1041 
1042 	/* ret == the error state, if NULL, make a new one */
1043 	if (ret == NULL) {
1044 		ret = malloc(sizeof(ERR_STATE));
1045 		if (ret == NULL)
1046 			return (&fallback);
1047 		CRYPTO_THREADID_cpy(&ret->tid, &tid);
1048 		ret->top = 0;
1049 		ret->bottom = 0;
1050 		for (i = 0; i < ERR_NUM_ERRORS; i++) {
1051 			ret->err_data[i] = NULL;
1052 			ret->err_data_flags[i] = 0;
1053 		}
1054 		tmpp = ERRFN(thread_set_item)(ret);
1055 		/* To check if insertion failed, do a get. */
1056 		if (ERRFN(thread_get_item)(ret) != ret) {
1057 			ERR_STATE_free(ret); /* could not insert it */
1058 			return (&fallback);
1059 		}
1060 		/* If a race occurred in this function and we came second, tmpp
1061 		 * is the first one that we just replaced. */
1062 		if (tmpp)
1063 			ERR_STATE_free(tmpp);
1064 	}
1065 	return ret;
1066 }
1067 LCRYPTO_ALIAS(ERR_get_state);
1068 
1069 int
1070 ERR_get_next_error_library(void)
1071 {
1072 	err_fns_check();
1073 	return ERRFN(get_next_lib)();
1074 }
1075 LCRYPTO_ALIAS(ERR_get_next_error_library);
1076 
1077 void
1078 ERR_set_error_data(char *data, int flags)
1079 {
1080 	ERR_STATE *es;
1081 	int i;
1082 
1083 	es = ERR_get_state();
1084 
1085 	i = es->top;
1086 	if (i == 0)
1087 		i = ERR_NUM_ERRORS - 1;
1088 
1089 	err_clear_data(es, i);
1090 	es->err_data[i] = data;
1091 	es->err_data_flags[i] = flags;
1092 }
1093 LCRYPTO_ALIAS(ERR_set_error_data);
1094 
1095 void
1096 ERR_asprintf_error_data(char * format, ...)
1097 {
1098 	char *errbuf = NULL;
1099 	va_list ap;
1100 	int r;
1101 
1102 	va_start(ap, format);
1103 	r = vasprintf(&errbuf, format, ap);
1104 	va_end(ap);
1105 	if (r == -1)
1106 		ERR_set_error_data("malloc failed", ERR_TXT_STRING);
1107 	else
1108 		ERR_set_error_data(errbuf, ERR_TXT_MALLOCED|ERR_TXT_STRING);
1109 }
1110 LCRYPTO_ALIAS(ERR_asprintf_error_data);
1111 
1112 void
1113 ERR_add_error_vdata(int num, va_list args)
1114 {
1115 	char format[129];
1116 	char *errbuf;
1117 	int i;
1118 
1119 	format[0] = '\0';
1120 	for (i = 0; i < num; i++) {
1121 		if (strlcat(format, "%s", sizeof(format)) >= sizeof(format)) {
1122 			ERR_set_error_data("too many errors", ERR_TXT_STRING);
1123 			return;
1124 		}
1125 	}
1126 	if (vasprintf(&errbuf, format, args) == -1)
1127 		ERR_set_error_data("malloc failed", ERR_TXT_STRING);
1128 	else
1129 		ERR_set_error_data(errbuf, ERR_TXT_MALLOCED|ERR_TXT_STRING);
1130 }
1131 
1132 void
1133 ERR_add_error_data(int num, ...)
1134 {
1135 	va_list args;
1136 	va_start(args, num);
1137 	ERR_add_error_vdata(num, args);
1138 	va_end(args);
1139 }
1140 
1141 int
1142 ERR_set_mark(void)
1143 {
1144 	ERR_STATE *es;
1145 
1146 	es = ERR_get_state();
1147 
1148 	if (es->bottom == es->top)
1149 		return 0;
1150 	es->err_flags[es->top] |= ERR_FLAG_MARK;
1151 	return 1;
1152 }
1153 LCRYPTO_ALIAS(ERR_set_mark);
1154 
1155 int
1156 ERR_pop_to_mark(void)
1157 {
1158 	ERR_STATE *es;
1159 
1160 	es = ERR_get_state();
1161 
1162 	while (es->bottom != es->top &&
1163 	    (es->err_flags[es->top] & ERR_FLAG_MARK) == 0) {
1164 		err_clear(es, es->top);
1165 		es->top -= 1;
1166 		if (es->top == -1)
1167 			es->top = ERR_NUM_ERRORS - 1;
1168 	}
1169 
1170 	if (es->bottom == es->top)
1171 		return 0;
1172 	es->err_flags[es->top]&=~ERR_FLAG_MARK;
1173 	return 1;
1174 }
1175 LCRYPTO_ALIAS(ERR_pop_to_mark);
1176 
1177 void
1178 err_clear_last_constant_time(int clear)
1179 {
1180 	ERR_STATE *es;
1181 	int top;
1182 
1183 	es = ERR_get_state();
1184 	if (es == NULL)
1185         return;
1186 
1187 	top = es->top;
1188 
1189 	es->err_flags[top] &= ~(0 - clear);
1190 	es->err_buffer[top] &= ~(0UL - clear);
1191 	es->err_file[top] = (const char *)((uintptr_t)es->err_file[top] &
1192 	    ~((uintptr_t)0 - clear));
1193 	es->err_line[top] |= 0 - clear;
1194 
1195 	es->top = (top + ERR_NUM_ERRORS - clear) % ERR_NUM_ERRORS;
1196 }
1197