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