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