err.c revision 1.31
1/* crypto/err/err.c */
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		{  \
621		free((p)->err_data[i]); \
622		(p)->err_data[i]=NULL; \
623		} \
624	(p)->err_data_flags[i]=0; \
625	} while(0)
626
627#define err_clear(p,i) \
628	do { \
629	(p)->err_flags[i]=0; \
630	(p)->err_buffer[i]=0; \
631	err_clear_data(p,i); \
632	(p)->err_file[i]=NULL; \
633	(p)->err_line[i]= -1; \
634	} while(0)
635
636static void
637ERR_STATE_free(ERR_STATE *s)
638{
639	int i;
640
641	if (s == NULL)
642		return;
643
644	for (i = 0; i < ERR_NUM_ERRORS; i++) {
645		err_clear_data(s, i);
646	}
647	free(s);
648}
649
650void
651ERR_load_ERR_strings(void)
652{
653	err_fns_check();
654#ifndef OPENSSL_NO_ERR
655	err_load_strings(0, ERR_str_libraries);
656	err_load_strings(0, ERR_str_reasons);
657	err_load_strings(ERR_LIB_SYS, ERR_str_functs);
658	build_SYS_str_reasons();
659	err_load_strings(ERR_LIB_SYS, SYS_str_reasons);
660#endif
661}
662
663static void
664err_load_strings(int lib, ERR_STRING_DATA *str)
665{
666	while (str->error) {
667		if (lib)
668			str->error |= ERR_PACK(lib, 0, 0);
669		ERRFN(err_set_item)(str);
670		str++;
671	}
672}
673
674void
675ERR_load_strings(int lib, ERR_STRING_DATA *str)
676{
677	ERR_load_ERR_strings();
678	err_load_strings(lib, str);
679}
680
681void
682ERR_unload_strings(int lib, ERR_STRING_DATA *str)
683{
684	while (str->error) {
685		if (lib)
686			str->error |= ERR_PACK(lib, 0, 0);
687		ERRFN(err_del_item)(str);
688		str++;
689	}
690}
691
692void
693ERR_free_strings(void)
694{
695	err_fns_check();
696	ERRFN(err_del)();
697}
698
699/********************************************************/
700
701void
702ERR_put_error(int lib, int func, int reason, const char *file, int line)
703{
704	ERR_STATE *es;
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}
717
718void
719ERR_clear_error(void)
720{
721	int i;
722	ERR_STATE *es;
723
724	es = ERR_get_state();
725
726	for (i = 0; i < ERR_NUM_ERRORS; i++) {
727		err_clear(es, i);
728	}
729	es->top = es->bottom = 0;
730}
731
732
733unsigned long ERR_get_error(void)
734{
735	return (get_error_values(1, 0,NULL, NULL, NULL, NULL));
736}
737
738unsigned long ERR_get_error_line(const char **file, int *line)
739{
740	return (get_error_values(1, 0,file, line, NULL, NULL));
741}
742
743unsigned long ERR_get_error_line_data(const char **file, int *line,
744    const char **data, int *flags)
745{
746	return (get_error_values(1, 0,file, line, data, flags));
747}
748
749
750unsigned long ERR_peek_error(void)
751{
752	return (get_error_values(0, 0,NULL, NULL, NULL, NULL));
753}
754
755unsigned long ERR_peek_error_line(const char **file, int *line)
756{
757	return (get_error_values(0, 0,file, line, NULL, NULL));
758}
759
760unsigned long ERR_peek_error_line_data(const char **file, int *line,
761    const char **data, int *flags)
762{
763	return (get_error_values(0, 0,file, line, data, flags));
764}
765
766unsigned long ERR_peek_last_error(void)
767{
768	return (get_error_values(0, 1,NULL, NULL, NULL, NULL));
769}
770
771unsigned long ERR_peek_last_error_line(const char **file, int *line)
772{
773	return (get_error_values(0, 1,file, line, NULL, NULL));
774}
775
776unsigned long ERR_peek_last_error_line_data(const char **file, int *line,
777    const char **data, int *flags)
778{
779	return (get_error_values(0, 1,file, line, data, flags));
780}
781
782static unsigned
783long get_error_values(int inc, int top, const char **file, int *line,
784    const char **data, int *flags)
785{
786	int i = 0;
787	ERR_STATE *es;
788	unsigned long ret;
789
790	es = ERR_get_state();
791
792	if (inc && top) {
793		if (file)
794			*file = "";
795		if (line)
796			*line = 0;
797		if (data)
798			*data = "";
799		if (flags)
800			*flags = 0;
801
802		return ERR_R_INTERNAL_ERROR;
803	}
804
805	if (es->bottom == es->top)
806		return 0;
807	if (top)
808		i = es->top;			 /* last error */
809	else
810		i = (es->bottom + 1) % ERR_NUM_ERRORS; /* first error */
811
812	ret = es->err_buffer[i];
813	if (inc) {
814		es->bottom = i;
815		es->err_buffer[i] = 0;
816	}
817
818	if ((file != NULL) && (line != NULL)) {
819		if (es->err_file[i] == NULL) {
820			*file = "NA";
821			if (line != NULL)
822				*line = 0;
823		} else {
824			*file = es->err_file[i];
825			if (line != NULL)
826				*line = es->err_line[i];
827		}
828	}
829
830	if (data == NULL) {
831		if (inc) {
832			err_clear_data(es, i);
833		}
834	} else {
835		if (es->err_data[i] == NULL) {
836			*data = "";
837			if (flags != NULL)
838				*flags = 0;
839		} else {
840			*data = es->err_data[i];
841			if (flags != NULL)
842				*flags = es->err_data_flags[i];
843		}
844	}
845	return ret;
846}
847
848void
849ERR_error_string_n(unsigned long e, char *buf, size_t len)
850{
851	char lsbuf[30], fsbuf[30], rsbuf[30];
852	const char *ls, *fs, *rs;
853	int l, f, r, ret;
854
855	l = ERR_GET_LIB(e);
856	f = ERR_GET_FUNC(e);
857	r = ERR_GET_REASON(e);
858
859	ls = ERR_lib_error_string(e);
860	fs = ERR_func_error_string(e);
861	rs = ERR_reason_error_string(e);
862
863	if (ls == NULL) {
864		(void) snprintf(lsbuf, sizeof(lsbuf), "lib(%d)", l);
865		ls = lsbuf;
866	}
867	if (fs == NULL) {
868		(void) snprintf(fsbuf, sizeof(fsbuf), "func(%d)", f);
869		fs = fsbuf;
870	}
871	if (rs == NULL) {
872		(void) snprintf(rsbuf, sizeof(rsbuf), "reason(%d)", r);
873		rs = rsbuf;
874	}
875
876	ret = snprintf(buf, len, "error:%08lX:%s:%s:%s", e, ls, fs, rs);
877	if (ret == -1)
878		return;	/* can't happen, and can't do better if it does */
879	if (ret >= len) {
880		/* output may be truncated; make sure we always have 5
881		 * colon-separated fields, i.e. 4 colons ... */
882#define NUM_COLONS 4
883		if (len > NUM_COLONS) /* ... if possible */
884		{
885			int i;
886			char *s = buf;
887
888			for (i = 0; i < NUM_COLONS; i++) {
889				char *colon = strchr(s, ':');
890				if (colon == NULL ||
891				    colon > &buf[len - 1] - NUM_COLONS + i) {
892					/* set colon no. i at last possible position
893					 * (buf[len-1] is the terminating 0)*/
894					colon = &buf[len - 1] - NUM_COLONS + i;
895					*colon = ':';
896				}
897				s = colon + 1;
898			}
899		}
900	}
901}
902
903/* BAD for multi-threading: uses a local buffer if ret == NULL */
904/* ERR_error_string_n should be used instead for ret != NULL
905 * as ERR_error_string cannot know how large the buffer is */
906char *
907ERR_error_string(unsigned long e, char *ret)
908{
909	static char buf[256];
910
911	if (ret == NULL)
912		ret = buf;
913	ERR_error_string_n(e, ret, 256);
914
915	return ret;
916}
917
918LHASH_OF(ERR_STRING_DATA) *ERR_get_string_table(void)
919{
920	err_fns_check();
921	return ERRFN(err_get)(0);
922}
923
924LHASH_OF(ERR_STATE) *ERR_get_err_state_table(void)
925{
926	err_fns_check();
927	return ERRFN(thread_get)(0);
928}
929
930void
931ERR_release_err_state_table(LHASH_OF(ERR_STATE) **hash)
932{
933	err_fns_check();
934	ERRFN(thread_release)(hash);
935}
936
937const char *
938ERR_lib_error_string(unsigned long e)
939{
940	ERR_STRING_DATA d, *p;
941	unsigned long l;
942
943	err_fns_check();
944	l = ERR_GET_LIB(e);
945	d.error = ERR_PACK(l, 0, 0);
946	p = ERRFN(err_get_item)(&d);
947	return ((p == NULL) ? NULL : p->string);
948}
949
950const char *
951ERR_func_error_string(unsigned long e)
952{
953	ERR_STRING_DATA d, *p;
954	unsigned long l, f;
955
956	err_fns_check();
957	l = ERR_GET_LIB(e);
958	f = ERR_GET_FUNC(e);
959	d.error = ERR_PACK(l, f, 0);
960	p = ERRFN(err_get_item)(&d);
961	return ((p == NULL) ? NULL : p->string);
962}
963
964const char *
965ERR_reason_error_string(unsigned long e)
966{
967	ERR_STRING_DATA d, *p = NULL;
968	unsigned long l, r;
969
970	err_fns_check();
971	l = ERR_GET_LIB(e);
972	r = ERR_GET_REASON(e);
973	d.error = ERR_PACK(l, 0, r);
974	p = ERRFN(err_get_item)(&d);
975	if (!p) {
976		d.error = ERR_PACK(0, 0, r);
977		p = ERRFN(err_get_item)(&d);
978	}
979	return ((p == NULL) ? NULL : p->string);
980}
981
982void
983ERR_remove_thread_state(const CRYPTO_THREADID *id)
984{
985	ERR_STATE tmp;
986
987	if (id)
988		CRYPTO_THREADID_cpy(&tmp.tid, id);
989	else
990		CRYPTO_THREADID_current(&tmp.tid);
991	err_fns_check();
992	/* thread_del_item automatically destroys the LHASH if the number of
993	 * items reaches zero. */
994	ERRFN(thread_del_item)(&tmp);
995}
996
997#ifndef OPENSSL_NO_DEPRECATED
998void
999ERR_remove_state(unsigned long pid)
1000{
1001	ERR_remove_thread_state(NULL);
1002}
1003#endif
1004
1005ERR_STATE *
1006ERR_get_state(void)
1007{
1008	static ERR_STATE fallback;
1009	ERR_STATE *ret, tmp, *tmpp = NULL;
1010	int i;
1011	CRYPTO_THREADID tid;
1012
1013	err_fns_check();
1014	CRYPTO_THREADID_current(&tid);
1015	CRYPTO_THREADID_cpy(&tmp.tid, &tid);
1016	ret = ERRFN(thread_get_item)(&tmp);
1017
1018	/* ret == the error state, if NULL, make a new one */
1019	if (ret == NULL) {
1020		ret = (ERR_STATE *)malloc(sizeof(ERR_STATE));
1021		if (ret == NULL)
1022			return (&fallback);
1023		CRYPTO_THREADID_cpy(&ret->tid, &tid);
1024		ret->top = 0;
1025		ret->bottom = 0;
1026		for (i = 0; i < ERR_NUM_ERRORS; i++) {
1027			ret->err_data[i] = NULL;
1028			ret->err_data_flags[i] = 0;
1029		}
1030		tmpp = ERRFN(thread_set_item)(ret);
1031		/* To check if insertion failed, do a get. */
1032		if (ERRFN(thread_get_item)(ret) != ret) {
1033			ERR_STATE_free(ret); /* could not insert it */
1034			return (&fallback);
1035		}
1036		/* If a race occured in this function and we came second, tmpp
1037		 * is the first one that we just replaced. */
1038		if (tmpp)
1039			ERR_STATE_free(tmpp);
1040	}
1041	return ret;
1042}
1043
1044int
1045ERR_get_next_error_library(void)
1046{
1047	err_fns_check();
1048	return ERRFN(get_next_lib)();
1049}
1050
1051void
1052ERR_set_error_data(char *data, int flags)
1053{
1054	ERR_STATE *es;
1055	int i;
1056
1057	es = ERR_get_state();
1058
1059	i = es->top;
1060	if (i == 0)
1061		i = ERR_NUM_ERRORS - 1;
1062
1063	err_clear_data(es, i);
1064	es->err_data[i] = data;
1065	es->err_data_flags[i] = flags;
1066}
1067
1068void
1069ERR_asprintf_error_data(char * format, ...) {
1070	char *errbuf = NULL;
1071	va_list ap;
1072	int r;
1073
1074	va_start(ap, format);
1075	r = vasprintf(&errbuf, format, ap);
1076	va_end(ap);
1077	if (r == -1)
1078		ERR_set_error_data("malloc failed", ERR_TXT_STRING);
1079	else
1080		ERR_set_error_data(errbuf, ERR_TXT_MALLOCED|ERR_TXT_STRING);
1081}
1082void
1083ERR_add_error_data(int num, ...)
1084{
1085	va_list args;
1086	va_start(args, num);
1087	ERR_add_error_vdata(num, args);
1088	va_end(args);
1089}
1090
1091void
1092ERR_add_error_vdata(int num, va_list args)
1093{
1094	char format[129];
1095	char *errbuf;
1096	format[0] = '\0';
1097	int i;
1098	for (i = 0; i < num; i++) {
1099		if (strlcat(format, "%s", sizeof(format)) >= sizeof(format)) {
1100			ERR_set_error_data("too many errors", ERR_TXT_STRING);
1101			return;
1102		}
1103	}
1104	if (vasprintf(&errbuf, format, args) == -1)
1105		ERR_set_error_data("malloc failed", ERR_TXT_STRING);
1106	else
1107		ERR_set_error_data(errbuf, ERR_TXT_MALLOCED|ERR_TXT_STRING);
1108}
1109
1110int
1111ERR_set_mark(void)
1112{
1113	ERR_STATE *es;
1114
1115	es = ERR_get_state();
1116
1117	if (es->bottom == es->top)
1118		return 0;
1119	es->err_flags[es->top] |= ERR_FLAG_MARK;
1120	return 1;
1121}
1122
1123int
1124ERR_pop_to_mark(void)
1125{
1126	ERR_STATE *es;
1127
1128	es = ERR_get_state();
1129
1130	while (es->bottom != es->top &&
1131	    (es->err_flags[es->top] & ERR_FLAG_MARK) == 0) {
1132		err_clear(es, es->top);
1133		es->top -= 1;
1134		if (es->top == -1)
1135			es->top = ERR_NUM_ERRORS - 1;
1136	}
1137
1138	if (es->bottom == es->top)
1139		return 0;
1140	es->err_flags[es->top]&=~ERR_FLAG_MARK;
1141	return 1;
1142}
1143