bc023e3f447d50bc22cda23ef3f6629cfb87f782
[openssl.git] / crypto / cryptlib.c
1 /* crypto/cryptlib.c */
2 /* ====================================================================
3  * Copyright (c) 1998-2003 The OpenSSL Project.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer. 
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in
14  *    the documentation and/or other materials provided with the
15  *    distribution.
16  *
17  * 3. All advertising materials mentioning features or use of this
18  *    software must display the following acknowledgment:
19  *    "This product includes software developed by the OpenSSL Project
20  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
21  *
22  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23  *    endorse or promote products derived from this software without
24  *    prior written permission. For written permission, please contact
25  *    openssl-core@openssl.org.
26  *
27  * 5. Products derived from this software may not be called "OpenSSL"
28  *    nor may "OpenSSL" appear in their names without prior written
29  *    permission of the OpenSSL Project.
30  *
31  * 6. Redistributions of any form whatsoever must retain the following
32  *    acknowledgment:
33  *    "This product includes software developed by the OpenSSL Project
34  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
35  *
36  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47  * OF THE POSSIBILITY OF SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This product includes cryptographic software written by Eric Young
51  * (eay@cryptsoft.com).  This product includes software written by Tim
52  * Hudson (tjh@cryptsoft.com).
53  *
54  */
55 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
56  * All rights reserved.
57  *
58  * This package is an SSL implementation written
59  * by Eric Young (eay@cryptsoft.com).
60  * The implementation was written so as to conform with Netscapes SSL.
61  * 
62  * This library is free for commercial and non-commercial use as long as
63  * the following conditions are aheared to.  The following conditions
64  * apply to all code found in this distribution, be it the RC4, RSA,
65  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
66  * included with this distribution is covered by the same copyright terms
67  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
68  * 
69  * Copyright remains Eric Young's, and as such any Copyright notices in
70  * the code are not to be removed.
71  * If this package is used in a product, Eric Young should be given attribution
72  * as the author of the parts of the library used.
73  * This can be in the form of a textual message at program startup or
74  * in documentation (online or textual) provided with the package.
75  * 
76  * Redistribution and use in source and binary forms, with or without
77  * modification, are permitted provided that the following conditions
78  * are met:
79  * 1. Redistributions of source code must retain the copyright
80  *    notice, this list of conditions and the following disclaimer.
81  * 2. Redistributions in binary form must reproduce the above copyright
82  *    notice, this list of conditions and the following disclaimer in the
83  *    documentation and/or other materials provided with the distribution.
84  * 3. All advertising materials mentioning features or use of this software
85  *    must display the following acknowledgement:
86  *    "This product includes cryptographic software written by
87  *     Eric Young (eay@cryptsoft.com)"
88  *    The word 'cryptographic' can be left out if the rouines from the library
89  *    being used are not cryptographic related :-).
90  * 4. If you include any Windows specific code (or a derivative thereof) from 
91  *    the apps directory (application code) you must include an acknowledgement:
92  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
93  * 
94  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
95  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
96  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
97  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
98  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
99  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
100  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
101  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
102  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
103  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
104  * SUCH DAMAGE.
105  * 
106  * The licence and distribution terms for any publically available version or
107  * derivative of this code cannot be changed.  i.e. this code cannot simply be
108  * copied and put under another distribution licence
109  * [including the GNU Public Licence.]
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  * ECDH support in OpenSSL originally developed by 
114  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
115  */
116
117 #include <stdio.h>
118 #include <string.h>
119 #include "cryptlib.h"
120 #include <openssl/crypto.h>
121 #include <openssl/safestack.h>
122
123 #if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16)
124 static double SSLeay_MSVC5_hack=0.0; /* and for VC1.5 */
125 #endif
126
127 DECLARE_STACK_OF(CRYPTO_dynlock)
128 IMPLEMENT_STACK_OF(CRYPTO_dynlock)
129
130 /* real #defines in crypto.h, keep these upto date */
131 static const char* lock_names[CRYPTO_NUM_LOCKS] =
132         {
133         "<<ERROR>>",
134         "err",
135         "ex_data",
136         "x509",
137         "x509_info",
138         "x509_pkey",
139         "x509_crl",
140         "x509_req",
141         "dsa",
142         "rsa",
143         "evp_pkey",
144         "x509_store",
145         "ssl_ctx",
146         "ssl_cert",
147         "ssl_session",
148         "ssl_sess_cert",
149         "ssl",
150         "ssl_method",
151         "rand",
152         "rand2",
153         "debug_malloc",
154         "BIO",
155         "gethostbyname",
156         "getservbyname",
157         "readdir",
158         "RSA_blinding",
159         "dh",
160         "debug_malloc2",
161         "dso",
162         "dynlock",
163         "engine",
164         "ui",
165         "ecdsa",
166         "ec",
167         "ecdh",
168         "bn",
169         "ec_pre_comp",
170 #if CRYPTO_NUM_LOCKS != 37
171 # error "Inconsistency between crypto.h and cryptlib.c"
172 #endif
173         };
174
175 /* This is for applications to allocate new type names in the non-dynamic
176    array of lock names.  These are numbered with positive numbers.  */
177 static STACK *app_locks=NULL;
178
179 /* For applications that want a more dynamic way of handling threads, the
180    following stack is used.  These are externally numbered with negative
181    numbers.  */
182 static STACK_OF(CRYPTO_dynlock) *dyn_locks=NULL;
183
184
185 static void (MS_FAR *locking_callback)(int mode,int type,
186         const char *file,int line)=NULL;
187 static int (MS_FAR *add_lock_callback)(int *pointer,int amount,
188         int type,const char *file,int line)=NULL;
189 static unsigned long (MS_FAR *id_callback)(void)=NULL;
190 static struct CRYPTO_dynlock_value *(MS_FAR *dynlock_create_callback)
191         (const char *file,int line)=NULL;
192 static void (MS_FAR *dynlock_lock_callback)(int mode,
193         struct CRYPTO_dynlock_value *l, const char *file,int line)=NULL;
194 static void (MS_FAR *dynlock_destroy_callback)(struct CRYPTO_dynlock_value *l,
195         const char *file,int line)=NULL;
196
197 int CRYPTO_get_new_lockid(char *name)
198         {
199         char *str;
200         int i;
201
202 #if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16)
203         /* A hack to make Visual C++ 5.0 work correctly when linking as
204          * a DLL using /MT. Without this, the application cannot use
205          * and floating point printf's.
206          * It also seems to be needed for Visual C 1.5 (win16) */
207         SSLeay_MSVC5_hack=(double)name[0]*(double)name[1];
208 #endif
209
210         if ((app_locks == NULL) && ((app_locks=sk_new_null()) == NULL))
211                 {
212                 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_LOCKID,ERR_R_MALLOC_FAILURE);
213                 return(0);
214                 }
215         if ((str=BUF_strdup(name)) == NULL)
216                 {
217                 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_LOCKID,ERR_R_MALLOC_FAILURE);
218                 return(0);
219                 }
220         i=sk_push(app_locks,str);
221         if (!i)
222                 OPENSSL_free(str);
223         else
224                 i+=CRYPTO_NUM_LOCKS; /* gap of one :-) */
225         return(i);
226         }
227
228 int CRYPTO_num_locks(void)
229         {
230         return CRYPTO_NUM_LOCKS;
231         }
232
233 int CRYPTO_get_new_dynlockid(void)
234         {
235         int i = 0;
236         CRYPTO_dynlock *pointer = NULL;
237
238         if (dynlock_create_callback == NULL)
239                 {
240                 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,CRYPTO_R_NO_DYNLOCK_CREATE_CALLBACK);
241                 return(0);
242                 }
243         CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
244         if ((dyn_locks == NULL)
245                 && ((dyn_locks=sk_CRYPTO_dynlock_new_null()) == NULL))
246                 {
247                 CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
248                 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,ERR_R_MALLOC_FAILURE);
249                 return(0);
250                 }
251         CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
252
253         pointer = (CRYPTO_dynlock *)OPENSSL_malloc(sizeof(CRYPTO_dynlock));
254         if (pointer == NULL)
255                 {
256                 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,ERR_R_MALLOC_FAILURE);
257                 return(0);
258                 }
259         pointer->references = 1;
260         pointer->data = dynlock_create_callback(__FILE__,__LINE__);
261         if (pointer->data == NULL)
262                 {
263                 OPENSSL_free(pointer);
264                 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,ERR_R_MALLOC_FAILURE);
265                 return(0);
266                 }
267
268         CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
269         /* First, try to find an existing empty slot */
270         i=sk_CRYPTO_dynlock_find(dyn_locks,NULL);
271         /* If there was none, push, thereby creating a new one */
272         if (i == -1)
273                 /* Since sk_push() returns the number of items on the
274                    stack, not the location of the pushed item, we need
275                    to transform the returned number into a position,
276                    by decreasing it.  */
277                 i=sk_CRYPTO_dynlock_push(dyn_locks,pointer) - 1;
278         else
279                 /* If we found a place with a NULL pointer, put our pointer
280                    in it.  */
281                 sk_CRYPTO_dynlock_set(dyn_locks,i,pointer);
282         CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
283
284         if (i == -1)
285                 {
286                 dynlock_destroy_callback(pointer->data,__FILE__,__LINE__);
287                 OPENSSL_free(pointer);
288                 }
289         else
290                 i += 1; /* to avoid 0 */
291         return -i;
292         }
293
294 void CRYPTO_destroy_dynlockid(int i)
295         {
296         CRYPTO_dynlock *pointer = NULL;
297         if (i)
298                 i = -i-1;
299         if (dynlock_destroy_callback == NULL)
300                 return;
301
302         CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
303
304         if (dyn_locks == NULL || i >= sk_CRYPTO_dynlock_num(dyn_locks))
305                 {
306                 CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
307                 return;
308                 }
309         pointer = sk_CRYPTO_dynlock_value(dyn_locks, i);
310         if (pointer != NULL)
311                 {
312                 --pointer->references;
313 #ifdef REF_CHECK
314                 if (pointer->references < 0)
315                         {
316                         fprintf(stderr,"CRYPTO_destroy_dynlockid, bad reference count\n");
317                         abort();
318                         }
319                 else
320 #endif
321                         if (pointer->references <= 0)
322                                 {
323                                 sk_CRYPTO_dynlock_set(dyn_locks, i, NULL);
324                                 }
325                         else
326                                 pointer = NULL;
327                 }
328         CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
329
330         if (pointer)
331                 {
332                 dynlock_destroy_callback(pointer->data,__FILE__,__LINE__);
333                 OPENSSL_free(pointer);
334                 }
335         }
336
337 struct CRYPTO_dynlock_value *CRYPTO_get_dynlock_value(int i)
338         {
339         CRYPTO_dynlock *pointer = NULL;
340         if (i)
341                 i = -i-1;
342
343         CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
344
345         if (dyn_locks != NULL && i < sk_CRYPTO_dynlock_num(dyn_locks))
346                 pointer = sk_CRYPTO_dynlock_value(dyn_locks, i);
347         if (pointer)
348                 pointer->references++;
349
350         CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
351
352         if (pointer)
353                 return pointer->data;
354         return NULL;
355         }
356
357 struct CRYPTO_dynlock_value *(*CRYPTO_get_dynlock_create_callback(void))
358         (const char *file,int line)
359         {
360         return(dynlock_create_callback);
361         }
362
363 void (*CRYPTO_get_dynlock_lock_callback(void))(int mode,
364         struct CRYPTO_dynlock_value *l, const char *file,int line)
365         {
366         return(dynlock_lock_callback);
367         }
368
369 void (*CRYPTO_get_dynlock_destroy_callback(void))
370         (struct CRYPTO_dynlock_value *l, const char *file,int line)
371         {
372         return(dynlock_destroy_callback);
373         }
374
375 void CRYPTO_set_dynlock_create_callback(struct CRYPTO_dynlock_value *(*func)
376         (const char *file, int line))
377         {
378         dynlock_create_callback=func;
379         }
380
381 void CRYPTO_set_dynlock_lock_callback(void (*func)(int mode,
382         struct CRYPTO_dynlock_value *l, const char *file, int line))
383         {
384         dynlock_lock_callback=func;
385         }
386
387 void CRYPTO_set_dynlock_destroy_callback(void (*func)
388         (struct CRYPTO_dynlock_value *l, const char *file, int line))
389         {
390         dynlock_destroy_callback=func;
391         }
392
393
394 void (*CRYPTO_get_locking_callback(void))(int mode,int type,const char *file,
395                 int line)
396         {
397         return(locking_callback);
398         }
399
400 int (*CRYPTO_get_add_lock_callback(void))(int *num,int mount,int type,
401                                           const char *file,int line)
402         {
403         return(add_lock_callback);
404         }
405
406 void CRYPTO_set_locking_callback(void (*func)(int mode,int type,
407                                               const char *file,int line))
408         {
409         locking_callback=func;
410         }
411
412 void CRYPTO_set_add_lock_callback(int (*func)(int *num,int mount,int type,
413                                               const char *file,int line))
414         {
415         add_lock_callback=func;
416         }
417
418 unsigned long (*CRYPTO_get_id_callback(void))(void)
419         {
420         return(id_callback);
421         }
422
423 void CRYPTO_set_id_callback(unsigned long (*func)(void))
424         {
425         id_callback=func;
426         }
427
428 unsigned long CRYPTO_thread_id(void)
429         {
430         unsigned long ret=0;
431
432         if (id_callback == NULL)
433                 {
434 #ifdef OPENSSL_SYS_WIN16
435                 ret=(unsigned long)GetCurrentTask();
436 #elif defined(OPENSSL_SYS_WIN32)
437                 ret=(unsigned long)GetCurrentThreadId();
438 #elif defined(GETPID_IS_MEANINGLESS)
439                 ret=1L;
440 #else
441                 ret=(unsigned long)getpid();
442 #endif
443                 }
444         else
445                 ret=id_callback();
446         return(ret);
447         }
448
449 void CRYPTO_lock(int mode, int type, const char *file, int line)
450         {
451 #ifdef LOCK_DEBUG
452                 {
453                 char *rw_text,*operation_text;
454
455                 if (mode & CRYPTO_LOCK)
456                         operation_text="lock  ";
457                 else if (mode & CRYPTO_UNLOCK)
458                         operation_text="unlock";
459                 else
460                         operation_text="ERROR ";
461
462                 if (mode & CRYPTO_READ)
463                         rw_text="r";
464                 else if (mode & CRYPTO_WRITE)
465                         rw_text="w";
466                 else
467                         rw_text="ERROR";
468
469                 fprintf(stderr,"lock:%08lx:(%s)%s %-18s %s:%d\n",
470                         CRYPTO_thread_id(), rw_text, operation_text,
471                         CRYPTO_get_lock_name(type), file, line);
472                 }
473 #endif
474         if (type < 0)
475                 {
476                 if (dynlock_lock_callback != NULL)
477                         {
478                         struct CRYPTO_dynlock_value *pointer
479                                 = CRYPTO_get_dynlock_value(type);
480
481                         OPENSSL_assert(pointer != NULL);
482
483                         dynlock_lock_callback(mode, pointer, file, line);
484
485                         CRYPTO_destroy_dynlockid(type);
486                         }
487                 }
488         else
489                 if (locking_callback != NULL)
490                         locking_callback(mode,type,file,line);
491         }
492
493 int CRYPTO_add_lock(int *pointer, int amount, int type, const char *file,
494              int line)
495         {
496         int ret = 0;
497
498         if (add_lock_callback != NULL)
499                 {
500 #ifdef LOCK_DEBUG
501                 int before= *pointer;
502 #endif
503
504                 ret=add_lock_callback(pointer,amount,type,file,line);
505 #ifdef LOCK_DEBUG
506                 fprintf(stderr,"ladd:%08lx:%2d+%2d->%2d %-18s %s:%d\n",
507                         CRYPTO_thread_id(),
508                         before,amount,ret,
509                         CRYPTO_get_lock_name(type),
510                         file,line);
511 #endif
512                 }
513         else
514                 {
515                 CRYPTO_lock(CRYPTO_LOCK|CRYPTO_WRITE,type,file,line);
516
517                 ret= *pointer+amount;
518 #ifdef LOCK_DEBUG
519                 fprintf(stderr,"ladd:%08lx:%2d+%2d->%2d %-18s %s:%d\n",
520                         CRYPTO_thread_id(),
521                         *pointer,amount,ret,
522                         CRYPTO_get_lock_name(type),
523                         file,line);
524 #endif
525                 *pointer=ret;
526                 CRYPTO_lock(CRYPTO_UNLOCK|CRYPTO_WRITE,type,file,line);
527                 }
528         return(ret);
529         }
530
531 const char *CRYPTO_get_lock_name(int type)
532         {
533         if (type < 0)
534                 return("dynamic");
535         else if (type < CRYPTO_NUM_LOCKS)
536                 return(lock_names[type]);
537         else if (type-CRYPTO_NUM_LOCKS > sk_num(app_locks))
538                 return("ERROR");
539         else
540                 return(sk_value(app_locks,type-CRYPTO_NUM_LOCKS));
541         }
542
543 #ifdef _DLL
544 #ifdef OPENSSL_SYS_WIN32
545
546 /* All we really need to do is remove the 'error' state when a thread
547  * detaches */
548
549 BOOL WINAPI DLLEntryPoint(HINSTANCE hinstDLL, DWORD fdwReason,
550              LPVOID lpvReserved)
551         {
552         switch(fdwReason)
553                 {
554         case DLL_PROCESS_ATTACH:
555                 break;
556         case DLL_THREAD_ATTACH:
557                 break;
558         case DLL_THREAD_DETACH:
559                 ERR_remove_state(0);
560                 break;
561         case DLL_PROCESS_DETACH:
562                 break;
563                 }
564         return(TRUE);
565         }
566 #endif
567
568 #endif
569
570 void OpenSSLDie(const char *file,int line,const char *assertion)
571         {
572         fprintf(stderr,
573                 "%s(%d): OpenSSL internal error, assertion failed: %s\n",
574                 file,line,assertion);
575         abort();
576         }