err.c revision 1.55
1/* $OpenBSD: err.c,v 1.55 2023/07/28 10:21:01 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
125DECLARE_LHASH_OF(ERR_STRING_DATA);
126DECLARE_LHASH_OF(ERR_STATE);
127
128typedef struct st_ERR_FNS ERR_FNS;
129
130static void err_load_strings(int lib, ERR_STRING_DATA *str);
131
132static void ERR_STATE_free(ERR_STATE *s);
133#ifndef OPENSSL_NO_ERR
134static 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
167static 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
181static 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 */
228struct 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 */
246static LHASH_OF(ERR_STRING_DATA) *int_err_get(int create);
247static void int_err_del(void);
248static ERR_STRING_DATA *int_err_get_item(const ERR_STRING_DATA *);
249static ERR_STRING_DATA *int_err_set_item(ERR_STRING_DATA *);
250static ERR_STRING_DATA *int_err_del_item(ERR_STRING_DATA *);
251static LHASH_OF(ERR_STATE) *int_thread_get(int create);
252static void int_thread_release(LHASH_OF(ERR_STATE) **hash);
253static ERR_STATE *int_thread_get_item(const ERR_STATE *);
254static ERR_STATE *int_thread_set_item(ERR_STATE *);
255static void int_thread_del_item(const ERR_STATE *);
256static int int_err_get_next_lib(void);
257
258/* The static ERR_FNS table using these defaults functions */
259static 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 */
274static 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. */
284static LHASH_OF(ERR_STRING_DATA) *int_error_hash = NULL;
285static LHASH_OF(ERR_STATE) *int_thread_hash = NULL;
286static int int_thread_hash_references = 0;
287static int int_err_library_number = ERR_LIB_USER;
288
289static 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. */
293static void
294err_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
308static 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
313static unsigned long
314err_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}
322static IMPLEMENT_LHASH_HASH_FN(err_string_data, ERR_STRING_DATA)
323
324static int
325err_string_data_cmp(const ERR_STRING_DATA *a, const ERR_STRING_DATA *b)
326{
327	return (int)(a->error - b->error);
328}
329static IMPLEMENT_LHASH_COMP_FN(err_string_data, ERR_STRING_DATA)
330
331static
332LHASH_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
349static void
350int_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
360static ERR_STRING_DATA *
361int_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
378static ERR_STRING_DATA *
379int_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
396static ERR_STRING_DATA *
397int_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
414static unsigned long
415err_state_hash(const ERR_STATE *a)
416{
417	return CRYPTO_THREADID_hash(&a->tid) * 13;
418}
419static IMPLEMENT_LHASH_HASH_FN(err_state, ERR_STATE)
420
421static int
422err_state_cmp(const ERR_STATE *a, const ERR_STATE *b)
423{
424	return CRYPTO_THREADID_cmp(&a->tid, &b->tid);
425}
426static IMPLEMENT_LHASH_COMP_FN(err_state, ERR_STATE)
427
428static
429LHASH_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
447static void
448int_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
462static ERR_STATE *
463int_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
481static ERR_STATE *
482int_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
500static void
501int_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
526static int
527int_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
543static 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
553static void
554build_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
623static void
624ERR_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
637void
638ERR_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
652void
653ERR_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}
665LCRYPTO_ALIAS(ERR_load_ERR_strings);
666
667static void
668err_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
678void
679ERR_load_strings(int lib, ERR_STRING_DATA *str)
680{
681	ERR_load_ERR_strings();
682	err_load_strings(lib, str);
683}
684LCRYPTO_ALIAS(ERR_load_strings);
685
686void
687ERR_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}
699LCRYPTO_ALIAS(ERR_unload_strings);
700
701void
702ERR_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}
710LCRYPTO_ALIAS(ERR_free_strings);
711
712/********************************************************/
713
714void
715ERR_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}
732LCRYPTO_ALIAS(ERR_put_error);
733
734void
735ERR_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}
747LCRYPTO_ALIAS(ERR_clear_error);
748
749
750unsigned long
751ERR_get_error(void)
752{
753	return (get_error_values(1, 0, NULL, NULL, NULL, NULL));
754}
755LCRYPTO_ALIAS(ERR_get_error);
756
757unsigned long
758ERR_get_error_line(const char **file, int *line)
759{
760	return (get_error_values(1, 0, file, line, NULL, NULL));
761}
762LCRYPTO_ALIAS(ERR_get_error_line);
763
764unsigned long
765ERR_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}
770LCRYPTO_ALIAS(ERR_get_error_line_data);
771
772
773unsigned long
774ERR_peek_error(void)
775{
776	return (get_error_values(0, 0, NULL, NULL, NULL, NULL));
777}
778LCRYPTO_ALIAS(ERR_peek_error);
779
780unsigned long
781ERR_peek_error_line(const char **file, int *line)
782{
783	return (get_error_values(0, 0, file, line, NULL, NULL));
784}
785LCRYPTO_ALIAS(ERR_peek_error_line);
786
787unsigned long
788ERR_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}
793LCRYPTO_ALIAS(ERR_peek_error_line_data);
794
795unsigned long
796ERR_peek_last_error(void)
797{
798	return (get_error_values(0, 1, NULL, NULL, NULL, NULL));
799}
800LCRYPTO_ALIAS(ERR_peek_last_error);
801
802unsigned long
803ERR_peek_last_error_line(const char **file, int *line)
804{
805	return (get_error_values(0, 1, file, line, NULL, NULL));
806}
807LCRYPTO_ALIAS(ERR_peek_last_error_line);
808
809unsigned long
810ERR_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}
815LCRYPTO_ALIAS(ERR_peek_last_error_line_data);
816
817static unsigned long
818get_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
883void
884ERR_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}
937LCRYPTO_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 */
942char *
943ERR_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}
953LCRYPTO_ALIAS(ERR_error_string);
954
955LHASH_OF(ERR_STRING_DATA) *ERR_get_string_table(void)
956{
957	err_fns_check();
958	return ERRFN(err_get)(0);
959}
960LCRYPTO_ALIAS(ERR_get_string_table);
961
962LHASH_OF(ERR_STATE) *ERR_get_err_state_table(void)
963{
964	err_fns_check();
965	return ERRFN(thread_get)(0);
966}
967LCRYPTO_ALIAS(ERR_get_err_state_table);
968
969void
970ERR_release_err_state_table(LHASH_OF(ERR_STATE) **hash)
971{
972	err_fns_check();
973	ERRFN(thread_release)(hash);
974}
975LCRYPTO_ALIAS(ERR_release_err_state_table);
976
977const char *
978ERR_lib_error_string(unsigned long e)
979{
980	ERR_STRING_DATA d, *p;
981	unsigned long l;
982
983	if (!OPENSSL_init_crypto(0, NULL))
984		return NULL;
985
986	err_fns_check();
987	l = ERR_GET_LIB(e);
988	d.error = ERR_PACK(l, 0, 0);
989	p = ERRFN(err_get_item)(&d);
990	return ((p == NULL) ? NULL : p->string);
991}
992LCRYPTO_ALIAS(ERR_lib_error_string);
993
994const char *
995ERR_func_error_string(unsigned long e)
996{
997	ERR_STRING_DATA d, *p;
998	unsigned long l, f;
999
1000	err_fns_check();
1001	l = ERR_GET_LIB(e);
1002	f = ERR_GET_FUNC(e);
1003	d.error = ERR_PACK(l, f, 0);
1004	p = ERRFN(err_get_item)(&d);
1005	return ((p == NULL) ? NULL : p->string);
1006}
1007LCRYPTO_ALIAS(ERR_func_error_string);
1008
1009const char *
1010ERR_reason_error_string(unsigned long e)
1011{
1012	ERR_STRING_DATA d, *p = NULL;
1013	unsigned long l, r;
1014
1015	err_fns_check();
1016	l = ERR_GET_LIB(e);
1017	r = ERR_GET_REASON(e);
1018	d.error = ERR_PACK(l, 0, r);
1019	p = ERRFN(err_get_item)(&d);
1020	if (!p) {
1021		d.error = ERR_PACK(0, 0, r);
1022		p = ERRFN(err_get_item)(&d);
1023	}
1024	return ((p == NULL) ? NULL : p->string);
1025}
1026LCRYPTO_ALIAS(ERR_reason_error_string);
1027
1028void
1029ERR_remove_thread_state(const CRYPTO_THREADID *id)
1030{
1031	ERR_STATE tmp;
1032
1033	if (id)
1034		CRYPTO_THREADID_cpy(&tmp.tid, id);
1035	else
1036		CRYPTO_THREADID_current(&tmp.tid);
1037	err_fns_check();
1038	/* thread_del_item automatically destroys the LHASH if the number of
1039	 * items reaches zero. */
1040	ERRFN(thread_del_item)(&tmp);
1041}
1042LCRYPTO_ALIAS(ERR_remove_thread_state);
1043
1044void
1045ERR_remove_state(unsigned long pid)
1046{
1047	ERR_remove_thread_state(NULL);
1048}
1049LCRYPTO_ALIAS(ERR_remove_state);
1050
1051ERR_STATE *
1052ERR_get_state(void)
1053{
1054	static ERR_STATE fallback;
1055	ERR_STATE *ret, tmp, *tmpp = NULL;
1056	int i;
1057	CRYPTO_THREADID tid;
1058
1059	err_fns_check();
1060	CRYPTO_THREADID_current(&tid);
1061	CRYPTO_THREADID_cpy(&tmp.tid, &tid);
1062	ret = ERRFN(thread_get_item)(&tmp);
1063
1064	/* ret == the error state, if NULL, make a new one */
1065	if (ret == NULL) {
1066		ret = malloc(sizeof(ERR_STATE));
1067		if (ret == NULL)
1068			return (&fallback);
1069		CRYPTO_THREADID_cpy(&ret->tid, &tid);
1070		ret->top = 0;
1071		ret->bottom = 0;
1072		for (i = 0; i < ERR_NUM_ERRORS; i++) {
1073			ret->err_data[i] = NULL;
1074			ret->err_data_flags[i] = 0;
1075		}
1076		tmpp = ERRFN(thread_set_item)(ret);
1077		/* To check if insertion failed, do a get. */
1078		if (ERRFN(thread_get_item)(ret) != ret) {
1079			ERR_STATE_free(ret); /* could not insert it */
1080			return (&fallback);
1081		}
1082		/* If a race occurred in this function and we came second, tmpp
1083		 * is the first one that we just replaced. */
1084		if (tmpp)
1085			ERR_STATE_free(tmpp);
1086	}
1087	return ret;
1088}
1089LCRYPTO_ALIAS(ERR_get_state);
1090
1091int
1092ERR_get_next_error_library(void)
1093{
1094	err_fns_check();
1095	return ERRFN(get_next_lib)();
1096}
1097LCRYPTO_ALIAS(ERR_get_next_error_library);
1098
1099void
1100ERR_set_error_data(char *data, int flags)
1101{
1102	ERR_STATE *es;
1103	int i;
1104
1105	es = ERR_get_state();
1106
1107	i = es->top;
1108	if (i == 0)
1109		i = ERR_NUM_ERRORS - 1;
1110
1111	err_clear_data(es, i);
1112	es->err_data[i] = data;
1113	es->err_data_flags[i] = flags;
1114}
1115LCRYPTO_ALIAS(ERR_set_error_data);
1116
1117void
1118ERR_asprintf_error_data(char * format, ...)
1119{
1120	char *errbuf = NULL;
1121	va_list ap;
1122	int r;
1123
1124	va_start(ap, format);
1125	r = vasprintf(&errbuf, format, ap);
1126	va_end(ap);
1127	if (r == -1)
1128		ERR_set_error_data("malloc failed", ERR_TXT_STRING);
1129	else
1130		ERR_set_error_data(errbuf, ERR_TXT_MALLOCED|ERR_TXT_STRING);
1131}
1132LCRYPTO_ALIAS(ERR_asprintf_error_data);
1133
1134void
1135ERR_add_error_vdata(int num, va_list args)
1136{
1137	char format[129];
1138	char *errbuf;
1139	int i;
1140
1141	format[0] = '\0';
1142	for (i = 0; i < num; i++) {
1143		if (strlcat(format, "%s", sizeof(format)) >= sizeof(format)) {
1144			ERR_set_error_data("too many errors", ERR_TXT_STRING);
1145			return;
1146		}
1147	}
1148	if (vasprintf(&errbuf, format, args) == -1)
1149		ERR_set_error_data("malloc failed", ERR_TXT_STRING);
1150	else
1151		ERR_set_error_data(errbuf, ERR_TXT_MALLOCED|ERR_TXT_STRING);
1152}
1153
1154void
1155ERR_add_error_data(int num, ...)
1156{
1157	va_list args;
1158	va_start(args, num);
1159	ERR_add_error_vdata(num, args);
1160	va_end(args);
1161}
1162
1163int
1164ERR_set_mark(void)
1165{
1166	ERR_STATE *es;
1167
1168	es = ERR_get_state();
1169
1170	if (es->bottom == es->top)
1171		return 0;
1172	es->err_flags[es->top] |= ERR_FLAG_MARK;
1173	return 1;
1174}
1175LCRYPTO_ALIAS(ERR_set_mark);
1176
1177int
1178ERR_pop_to_mark(void)
1179{
1180	ERR_STATE *es;
1181
1182	es = ERR_get_state();
1183
1184	while (es->bottom != es->top &&
1185	    (es->err_flags[es->top] & ERR_FLAG_MARK) == 0) {
1186		err_clear(es, es->top);
1187		es->top -= 1;
1188		if (es->top == -1)
1189			es->top = ERR_NUM_ERRORS - 1;
1190	}
1191
1192	if (es->bottom == es->top)
1193		return 0;
1194	es->err_flags[es->top]&=~ERR_FLAG_MARK;
1195	return 1;
1196}
1197LCRYPTO_ALIAS(ERR_pop_to_mark);
1198
1199void
1200err_clear_last_constant_time(int clear)
1201{
1202	ERR_STATE *es;
1203	int top;
1204
1205	es = ERR_get_state();
1206	if (es == NULL)
1207        return;
1208
1209	top = es->top;
1210
1211	es->err_flags[top] &= ~(0 - clear);
1212	es->err_buffer[top] &= ~(0UL - clear);
1213	es->err_file[top] = (const char *)((uintptr_t)es->err_file[top] &
1214	    ~((uintptr_t)0 - clear));
1215	es->err_line[top] |= 0 - clear;
1216
1217	es->top = (top + ERR_NUM_ERRORS - clear) % ERR_NUM_ERRORS;
1218}
1219