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