add OpenSSL license
[oweals/openssl.git] / crypto / cryptlib.c
1 /* crypto/cryptlib.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 #include <stdio.h>
60 #include <string.h>
61 #include "cryptlib.h"
62 #include <openssl/crypto.h>
63 #include <openssl/safestack.h>
64
65 #if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16)
66 static double SSLeay_MSVC5_hack=0.0; /* and for VC1.5 */
67 #endif
68
69 #ifdef FIPS
70 int FIPS_mode;
71 void *FIPS_rand_check;
72 #endif /* def FIPS */
73
74 DECLARE_STACK_OF(CRYPTO_dynlock)
75 IMPLEMENT_STACK_OF(CRYPTO_dynlock)
76
77 /* real #defines in crypto.h, keep these upto date */
78 static const char* lock_names[CRYPTO_NUM_LOCKS] =
79         {
80         "<<ERROR>>",
81         "err",
82         "ex_data",
83         "x509",
84         "x509_info",
85         "x509_pkey",
86         "x509_crl",
87         "x509_req",
88         "dsa",
89         "rsa",
90         "evp_pkey",
91         "x509_store",
92         "ssl_ctx",
93         "ssl_cert",
94         "ssl_session",
95         "ssl_sess_cert",
96         "ssl",
97         "ssl_method",
98         "rand",
99         "rand2",
100         "debug_malloc",
101         "BIO",
102         "gethostbyname",
103         "getservbyname",
104         "readdir",
105         "RSA_blinding",
106         "dh",
107         "debug_malloc2",
108         "dso",
109         "dynlock",
110         "engine",
111         "ui",
112         "hwcrhk",               /* This is a HACK which will disappear in 0.9.8 */
113 #if CRYPTO_NUM_LOCKS != 33
114 # error "Inconsistency between crypto.h and cryptlib.c"
115 #endif
116         };
117
118 /* This is for applications to allocate new type names in the non-dynamic
119    array of lock names.  These are numbered with positive numbers.  */
120 static STACK *app_locks=NULL;
121
122 /* For applications that want a more dynamic way of handling threads, the
123    following stack is used.  These are externally numbered with negative
124    numbers.  */
125 static STACK_OF(CRYPTO_dynlock) *dyn_locks=NULL;
126
127
128 static void (MS_FAR *locking_callback)(int mode,int type,
129         const char *file,int line)=NULL;
130 static int (MS_FAR *add_lock_callback)(int *pointer,int amount,
131         int type,const char *file,int line)=NULL;
132 static unsigned long (MS_FAR *id_callback)(void)=NULL;
133 static struct CRYPTO_dynlock_value *(MS_FAR *dynlock_create_callback)
134         (const char *file,int line)=NULL;
135 static void (MS_FAR *dynlock_lock_callback)(int mode,
136         struct CRYPTO_dynlock_value *l, const char *file,int line)=NULL;
137 static void (MS_FAR *dynlock_destroy_callback)(struct CRYPTO_dynlock_value *l,
138         const char *file,int line)=NULL;
139
140 int CRYPTO_get_new_lockid(char *name)
141         {
142         char *str;
143         int i;
144
145 #if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16)
146         /* A hack to make Visual C++ 5.0 work correctly when linking as
147          * a DLL using /MT. Without this, the application cannot use
148          * and floating point printf's.
149          * It also seems to be needed for Visual C 1.5 (win16) */
150         SSLeay_MSVC5_hack=(double)name[0]*(double)name[1];
151 #endif
152
153         if ((app_locks == NULL) && ((app_locks=sk_new_null()) == NULL))
154                 {
155                 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_LOCKID,ERR_R_MALLOC_FAILURE);
156                 return(0);
157                 }
158         if ((str=BUF_strdup(name)) == NULL)
159                 {
160                 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_LOCKID,ERR_R_MALLOC_FAILURE);
161                 return(0);
162                 }
163         i=sk_push(app_locks,str);
164         if (!i)
165                 OPENSSL_free(str);
166         else
167                 i+=CRYPTO_NUM_LOCKS; /* gap of one :-) */
168         return(i);
169         }
170
171 int CRYPTO_num_locks(void)
172         {
173         return CRYPTO_NUM_LOCKS;
174         }
175
176 int CRYPTO_get_new_dynlockid(void)
177         {
178         int i = 0;
179         CRYPTO_dynlock *pointer = NULL;
180
181         if (dynlock_create_callback == NULL)
182                 {
183                 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,CRYPTO_R_NO_DYNLOCK_CREATE_CALLBACK);
184                 return(0);
185                 }
186         CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
187         if ((dyn_locks == NULL)
188                 && ((dyn_locks=sk_CRYPTO_dynlock_new_null()) == NULL))
189                 {
190                 CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
191                 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,ERR_R_MALLOC_FAILURE);
192                 return(0);
193                 }
194         CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
195
196         pointer = (CRYPTO_dynlock *)OPENSSL_malloc(sizeof(CRYPTO_dynlock));
197         if (pointer == NULL)
198                 {
199                 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,ERR_R_MALLOC_FAILURE);
200                 return(0);
201                 }
202         pointer->references = 1;
203         pointer->data = dynlock_create_callback(__FILE__,__LINE__);
204         if (pointer->data == NULL)
205                 {
206                 OPENSSL_free(pointer);
207                 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,ERR_R_MALLOC_FAILURE);
208                 return(0);
209                 }
210
211         CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
212         /* First, try to find an existing empty slot */
213         i=sk_CRYPTO_dynlock_find(dyn_locks,NULL);
214         /* If there was none, push, thereby creating a new one */
215         if (i == -1)
216                 /* Since sk_push() returns the number of items on the
217                    stack, not the location of the pushed item, we need
218                    to transform the returned number into a position,
219                    by decreasing it.  */
220                 i=sk_CRYPTO_dynlock_push(dyn_locks,pointer) - 1;
221         else
222                 /* If we found a place with a NULL pointer, put our pointer
223                    in it.  */
224                 sk_CRYPTO_dynlock_set(dyn_locks,i,pointer);
225         CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
226
227         if (i == -1)
228                 {
229                 dynlock_destroy_callback(pointer->data,__FILE__,__LINE__);
230                 OPENSSL_free(pointer);
231                 }
232         else
233                 i += 1; /* to avoid 0 */
234         return -i;
235         }
236
237 void CRYPTO_destroy_dynlockid(int i)
238         {
239         CRYPTO_dynlock *pointer = NULL;
240         if (i)
241                 i = -i-1;
242         if (dynlock_destroy_callback == NULL)
243                 return;
244
245         CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
246
247         if (dyn_locks == NULL || i >= sk_CRYPTO_dynlock_num(dyn_locks))
248                 {
249                 CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
250                 return;
251                 }
252         pointer = sk_CRYPTO_dynlock_value(dyn_locks, i);
253         if (pointer != NULL)
254                 {
255                 --pointer->references;
256 #ifdef REF_CHECK
257                 if (pointer->references < 0)
258                         {
259                         fprintf(stderr,"CRYPTO_destroy_dynlockid, bad reference count\n");
260                         abort();
261                         }
262                 else
263 #endif
264                         if (pointer->references <= 0)
265                                 {
266                                 sk_CRYPTO_dynlock_set(dyn_locks, i, NULL);
267                                 }
268                         else
269                                 pointer = NULL;
270                 }
271         CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
272
273         if (pointer)
274                 {
275                 dynlock_destroy_callback(pointer->data,__FILE__,__LINE__);
276                 OPENSSL_free(pointer);
277                 }
278         }
279
280 struct CRYPTO_dynlock_value *CRYPTO_get_dynlock_value(int i)
281         {
282         CRYPTO_dynlock *pointer = NULL;
283         if (i)
284                 i = -i-1;
285
286         CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
287
288         if (dyn_locks != NULL && i < sk_CRYPTO_dynlock_num(dyn_locks))
289                 pointer = sk_CRYPTO_dynlock_value(dyn_locks, i);
290         if (pointer)
291                 pointer->references++;
292
293         CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
294
295         if (pointer)
296                 return pointer->data;
297         return NULL;
298         }
299
300 struct CRYPTO_dynlock_value *(*CRYPTO_get_dynlock_create_callback(void))
301         (const char *file,int line)
302         {
303         return(dynlock_create_callback);
304         }
305
306 void (*CRYPTO_get_dynlock_lock_callback(void))(int mode,
307         struct CRYPTO_dynlock_value *l, const char *file,int line)
308         {
309         return(dynlock_lock_callback);
310         }
311
312 void (*CRYPTO_get_dynlock_destroy_callback(void))
313         (struct CRYPTO_dynlock_value *l, const char *file,int line)
314         {
315         return(dynlock_destroy_callback);
316         }
317
318 void CRYPTO_set_dynlock_create_callback(struct CRYPTO_dynlock_value *(*func)
319         (const char *file, int line))
320         {
321         dynlock_create_callback=func;
322         }
323
324 void CRYPTO_set_dynlock_lock_callback(void (*func)(int mode,
325         struct CRYPTO_dynlock_value *l, const char *file, int line))
326         {
327         dynlock_lock_callback=func;
328         }
329
330 void CRYPTO_set_dynlock_destroy_callback(void (*func)
331         (struct CRYPTO_dynlock_value *l, const char *file, int line))
332         {
333         dynlock_destroy_callback=func;
334         }
335
336
337 void (*CRYPTO_get_locking_callback(void))(int mode,int type,const char *file,
338                 int line)
339         {
340         return(locking_callback);
341         }
342
343 int (*CRYPTO_get_add_lock_callback(void))(int *num,int mount,int type,
344                                           const char *file,int line)
345         {
346         return(add_lock_callback);
347         }
348
349 void CRYPTO_set_locking_callback(void (*func)(int mode,int type,
350                                               const char *file,int line))
351         {
352         locking_callback=func;
353         }
354
355 void CRYPTO_set_add_lock_callback(int (*func)(int *num,int mount,int type,
356                                               const char *file,int line))
357         {
358         add_lock_callback=func;
359         }
360
361 unsigned long (*CRYPTO_get_id_callback(void))(void)
362         {
363         return(id_callback);
364         }
365
366 void CRYPTO_set_id_callback(unsigned long (*func)(void))
367         {
368         id_callback=func;
369         }
370
371 unsigned long CRYPTO_thread_id(void)
372         {
373         unsigned long ret=0;
374
375         if (id_callback == NULL)
376                 {
377 #ifdef OPENSSL_SYS_WIN16
378                 ret=(unsigned long)GetCurrentTask();
379 #elif defined(OPENSSL_SYS_WIN32)
380                 ret=(unsigned long)GetCurrentThreadId();
381 #elif defined(GETPID_IS_MEANINGLESS)
382                 ret=1L;
383 #else
384                 ret=(unsigned long)getpid();
385 #endif
386                 }
387         else
388                 ret=id_callback();
389         return(ret);
390         }
391
392 void CRYPTO_lock(int mode, int type, const char *file, int line)
393         {
394 #ifdef LOCK_DEBUG
395                 {
396                 char *rw_text,*operation_text;
397
398                 if (mode & CRYPTO_LOCK)
399                         operation_text="lock  ";
400                 else if (mode & CRYPTO_UNLOCK)
401                         operation_text="unlock";
402                 else
403                         operation_text="ERROR ";
404
405                 if (mode & CRYPTO_READ)
406                         rw_text="r";
407                 else if (mode & CRYPTO_WRITE)
408                         rw_text="w";
409                 else
410                         rw_text="ERROR";
411
412                 fprintf(stderr,"lock:%08lx:(%s)%s %-18s %s:%d\n",
413                         CRYPTO_thread_id(), rw_text, operation_text,
414                         CRYPTO_get_lock_name(type), file, line);
415                 }
416 #endif
417         if (type < 0)
418                 {
419                 if (dynlock_lock_callback != NULL)
420                         {
421                         struct CRYPTO_dynlock_value *pointer
422                                 = CRYPTO_get_dynlock_value(type);
423
424                         OPENSSL_assert(pointer != NULL);
425
426                         dynlock_lock_callback(mode, pointer, file, line);
427
428                         CRYPTO_destroy_dynlockid(type);
429                         }
430                 }
431         else
432                 if (locking_callback != NULL)
433                         locking_callback(mode,type,file,line);
434         }
435
436 int CRYPTO_add_lock(int *pointer, int amount, int type, const char *file,
437              int line)
438         {
439         int ret = 0;
440
441         if (add_lock_callback != NULL)
442                 {
443 #ifdef LOCK_DEBUG
444                 int before= *pointer;
445 #endif
446
447                 ret=add_lock_callback(pointer,amount,type,file,line);
448 #ifdef LOCK_DEBUG
449                 fprintf(stderr,"ladd:%08lx:%2d+%2d->%2d %-18s %s:%d\n",
450                         CRYPTO_thread_id(),
451                         before,amount,ret,
452                         CRYPTO_get_lock_name(type),
453                         file,line);
454 #endif
455                 }
456         else
457                 {
458                 CRYPTO_lock(CRYPTO_LOCK|CRYPTO_WRITE,type,file,line);
459
460                 ret= *pointer+amount;
461 #ifdef LOCK_DEBUG
462                 fprintf(stderr,"ladd:%08lx:%2d+%2d->%2d %-18s %s:%d\n",
463                         CRYPTO_thread_id(),
464                         *pointer,amount,ret,
465                         CRYPTO_get_lock_name(type),
466                         file,line);
467 #endif
468                 *pointer=ret;
469                 CRYPTO_lock(CRYPTO_UNLOCK|CRYPTO_WRITE,type,file,line);
470                 }
471         return(ret);
472         }
473
474 const char *CRYPTO_get_lock_name(int type)
475         {
476         if (type < 0)
477                 return("dynamic");
478         else if (type < CRYPTO_NUM_LOCKS)
479                 return(lock_names[type]);
480         else if (type-CRYPTO_NUM_LOCKS > sk_num(app_locks))
481                 return("ERROR");
482         else
483                 return(sk_value(app_locks,type-CRYPTO_NUM_LOCKS));
484         }
485
486 #ifdef _DLL
487 #ifdef OPENSSL_SYS_WIN32
488
489 /* All we really need to do is remove the 'error' state when a thread
490  * detaches */
491
492 BOOL WINAPI DLLEntryPoint(HINSTANCE hinstDLL, DWORD fdwReason,
493              LPVOID lpvReserved)
494         {
495         switch(fdwReason)
496                 {
497         case DLL_PROCESS_ATTACH:
498                 break;
499         case DLL_THREAD_ATTACH:
500                 break;
501         case DLL_THREAD_DETACH:
502                 ERR_remove_state(0);
503                 break;
504         case DLL_PROCESS_DETACH:
505                 break;
506                 }
507         return(TRUE);
508         }
509 #endif
510
511 #endif
512
513 void OpenSSLDie(const char *file,int line,const char *assertion)
514         {
515         fprintf(stderr,
516                 "%s(%d): OpenSSL internal error, assertion failed: %s\n",
517                 file,line,assertion);
518         abort();
519         }