OpenSSL: update to 1.0.2a
[tomato.git] / release / src-rt-6.x.4708 / router / openssl / crypto / cryptlib.c
blob98526d73dc29d060f6cc7a61f64345e7b17659fd
1 /* crypto/cryptlib.c */
2 /* ====================================================================
3 * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
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.
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/)"
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.
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.
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/)"
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 * ====================================================================
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).
55 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
56 * All rights reserved.
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.
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).
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.
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)"
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.
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.]
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.
117 #include "cryptlib.h"
118 #include <openssl/safestack.h>
120 #if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16)
121 static double SSLeay_MSVC5_hack = 0.0; /* and for VC1.5 */
122 #endif
124 DECLARE_STACK_OF(CRYPTO_dynlock)
126 /* real #defines in crypto.h, keep these upto date */
127 static const char *const lock_names[CRYPTO_NUM_LOCKS] = {
128 "<<ERROR>>",
129 "err",
130 "ex_data",
131 "x509",
132 "x509_info",
133 "x509_pkey",
134 "x509_crl",
135 "x509_req",
136 "dsa",
137 "rsa",
138 "evp_pkey",
139 "x509_store",
140 "ssl_ctx",
141 "ssl_cert",
142 "ssl_session",
143 "ssl_sess_cert",
144 "ssl",
145 "ssl_method",
146 "rand",
147 "rand2",
148 "debug_malloc",
149 "BIO",
150 "gethostbyname",
151 "getservbyname",
152 "readdir",
153 "RSA_blinding",
154 "dh",
155 "debug_malloc2",
156 "dso",
157 "dynlock",
158 "engine",
159 "ui",
160 "ecdsa",
161 "ec",
162 "ecdh",
163 "bn",
164 "ec_pre_comp",
165 "store",
166 "comp",
167 "fips",
168 "fips2",
169 #if CRYPTO_NUM_LOCKS != 41
170 # error "Inconsistency between crypto.h and cryptlib.c"
171 #endif
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.
178 static STACK_OF(OPENSSL_STRING) *app_locks = NULL;
181 * For applications that want a more dynamic way of handling threads, the
182 * following stack is used. These are externally numbered with negative
183 * numbers.
185 static STACK_OF(CRYPTO_dynlock) *dyn_locks = NULL;
187 static void (MS_FAR *locking_callback) (int mode, int type,
188 const char *file, int line) = 0;
189 static int (MS_FAR *add_lock_callback) (int *pointer, int amount,
190 int type, const char *file,
191 int line) = 0;
192 #ifndef OPENSSL_NO_DEPRECATED
193 static unsigned long (MS_FAR *id_callback) (void) = 0;
194 #endif
195 static void (MS_FAR *threadid_callback) (CRYPTO_THREADID *) = 0;
196 static struct CRYPTO_dynlock_value *(MS_FAR *dynlock_create_callback)
197 (const char *file, int line) = 0;
198 static void (MS_FAR *dynlock_lock_callback) (int mode,
199 struct CRYPTO_dynlock_value *l,
200 const char *file, int line) = 0;
201 static void (MS_FAR *dynlock_destroy_callback) (struct CRYPTO_dynlock_value
202 *l, const char *file,
203 int line) = 0;
205 int CRYPTO_get_new_lockid(char *name)
207 char *str;
208 int i;
210 #if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16)
212 * A hack to make Visual C++ 5.0 work correctly when linking as a DLL
213 * using /MT. Without this, the application cannot use any floating point
214 * printf's. It also seems to be needed for Visual C 1.5 (win16)
216 SSLeay_MSVC5_hack = (double)name[0] * (double)name[1];
217 #endif
219 if ((app_locks == NULL)
220 && ((app_locks = sk_OPENSSL_STRING_new_null()) == NULL)) {
221 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_LOCKID, ERR_R_MALLOC_FAILURE);
222 return (0);
224 if ((str = BUF_strdup(name)) == NULL) {
225 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_LOCKID, ERR_R_MALLOC_FAILURE);
226 return (0);
228 i = sk_OPENSSL_STRING_push(app_locks, str);
229 if (!i)
230 OPENSSL_free(str);
231 else
232 i += CRYPTO_NUM_LOCKS; /* gap of one :-) */
233 return (i);
236 int CRYPTO_num_locks(void)
238 return CRYPTO_NUM_LOCKS;
241 int CRYPTO_get_new_dynlockid(void)
243 int i = 0;
244 CRYPTO_dynlock *pointer = NULL;
246 if (dynlock_create_callback == NULL) {
247 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,
248 CRYPTO_R_NO_DYNLOCK_CREATE_CALLBACK);
249 return (0);
251 CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
252 if ((dyn_locks == NULL)
253 && ((dyn_locks = sk_CRYPTO_dynlock_new_null()) == NULL)) {
254 CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
255 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID, ERR_R_MALLOC_FAILURE);
256 return (0);
258 CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
260 pointer = (CRYPTO_dynlock *) OPENSSL_malloc(sizeof(CRYPTO_dynlock));
261 if (pointer == NULL) {
262 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID, ERR_R_MALLOC_FAILURE);
263 return (0);
265 pointer->references = 1;
266 pointer->data = dynlock_create_callback(__FILE__, __LINE__);
267 if (pointer->data == NULL) {
268 OPENSSL_free(pointer);
269 CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID, ERR_R_MALLOC_FAILURE);
270 return (0);
273 CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
274 /* First, try to find an existing empty slot */
275 i = sk_CRYPTO_dynlock_find(dyn_locks, NULL);
276 /* If there was none, push, thereby creating a new one */
277 if (i == -1)
279 * Since sk_push() returns the number of items on the stack, not the
280 * location of the pushed item, we need to transform the returned
281 * number into a position, by decreasing it.
283 i = sk_CRYPTO_dynlock_push(dyn_locks, pointer) - 1;
284 else
286 * If we found a place with a NULL pointer, put our pointer in it.
288 (void)sk_CRYPTO_dynlock_set(dyn_locks, i, pointer);
289 CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
291 if (i == -1) {
292 dynlock_destroy_callback(pointer->data, __FILE__, __LINE__);
293 OPENSSL_free(pointer);
294 } else
295 i += 1; /* to avoid 0 */
296 return -i;
299 void CRYPTO_destroy_dynlockid(int i)
301 CRYPTO_dynlock *pointer = NULL;
302 if (i)
303 i = -i - 1;
304 if (dynlock_destroy_callback == NULL)
305 return;
307 CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
309 if (dyn_locks == NULL || i >= sk_CRYPTO_dynlock_num(dyn_locks)) {
310 CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
311 return;
313 pointer = sk_CRYPTO_dynlock_value(dyn_locks, i);
314 if (pointer != NULL) {
315 --pointer->references;
316 #ifdef REF_CHECK
317 if (pointer->references < 0) {
318 fprintf(stderr,
319 "CRYPTO_destroy_dynlockid, bad reference count\n");
320 abort();
321 } else
322 #endif
323 if (pointer->references <= 0) {
324 (void)sk_CRYPTO_dynlock_set(dyn_locks, i, NULL);
325 } else
326 pointer = NULL;
328 CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
330 if (pointer) {
331 dynlock_destroy_callback(pointer->data, __FILE__, __LINE__);
332 OPENSSL_free(pointer);
336 struct CRYPTO_dynlock_value *CRYPTO_get_dynlock_value(int i)
338 CRYPTO_dynlock *pointer = NULL;
339 if (i)
340 i = -i - 1;
342 CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
344 if (dyn_locks != NULL && i < sk_CRYPTO_dynlock_num(dyn_locks))
345 pointer = sk_CRYPTO_dynlock_value(dyn_locks, i);
346 if (pointer)
347 pointer->references++;
349 CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
351 if (pointer)
352 return pointer->data;
353 return NULL;
356 struct CRYPTO_dynlock_value *(*CRYPTO_get_dynlock_create_callback(void))
357 (const char *file, int line) {
358 return (dynlock_create_callback);
361 void (*CRYPTO_get_dynlock_lock_callback(void)) (int mode,
362 struct CRYPTO_dynlock_value
363 *l, const char *file,
364 int line) {
365 return (dynlock_lock_callback);
368 void (*CRYPTO_get_dynlock_destroy_callback(void))
369 (struct CRYPTO_dynlock_value *l, const char *file, int line) {
370 return (dynlock_destroy_callback);
373 void CRYPTO_set_dynlock_create_callback(struct CRYPTO_dynlock_value *(*func)
374 (const char *file, int line))
376 dynlock_create_callback = func;
379 void CRYPTO_set_dynlock_lock_callback(void (*func) (int mode,
380 struct
381 CRYPTO_dynlock_value *l,
382 const char *file,
383 int line))
385 dynlock_lock_callback = func;
388 void CRYPTO_set_dynlock_destroy_callback(void (*func)
389 (struct CRYPTO_dynlock_value *l,
390 const char *file, int line))
392 dynlock_destroy_callback = func;
395 void (*CRYPTO_get_locking_callback(void)) (int mode, int type,
396 const char *file, int line) {
397 return (locking_callback);
400 int (*CRYPTO_get_add_lock_callback(void)) (int *num, int mount, int type,
401 const char *file, int line) {
402 return (add_lock_callback);
405 void CRYPTO_set_locking_callback(void (*func) (int mode, int type,
406 const char *file, int line))
409 * Calling this here ensures initialisation before any threads are
410 * started.
412 OPENSSL_init();
413 locking_callback = func;
416 void CRYPTO_set_add_lock_callback(int (*func) (int *num, int mount, int type,
417 const char *file, int line))
419 add_lock_callback = func;
423 * the memset() here and in set_pointer() seem overkill, but for the sake of
424 * CRYPTO_THREADID_cmp() this avoids any platform silliness that might cause
425 * two "equal" THREADID structs to not be memcmp()-identical.
427 void CRYPTO_THREADID_set_numeric(CRYPTO_THREADID *id, unsigned long val)
429 memset(id, 0, sizeof(*id));
430 id->val = val;
433 static const unsigned char hash_coeffs[] = { 3, 5, 7, 11, 13, 17, 19, 23 };
435 void CRYPTO_THREADID_set_pointer(CRYPTO_THREADID *id, void *ptr)
437 unsigned char *dest = (void *)&id->val;
438 unsigned int accum = 0;
439 unsigned char dnum = sizeof(id->val);
441 memset(id, 0, sizeof(*id));
442 id->ptr = ptr;
443 if (sizeof(id->val) >= sizeof(id->ptr)) {
445 * 'ptr' can be embedded in 'val' without loss of uniqueness
447 id->val = (unsigned long)id->ptr;
448 return;
451 * hash ptr ==> val. Each byte of 'val' gets the mod-256 total of a
452 * linear function over the bytes in 'ptr', the co-efficients of which
453 * are a sequence of low-primes (hash_coeffs is an 8-element cycle) - the
454 * starting prime for the sequence varies for each byte of 'val' (unique
455 * polynomials unless pointers are >64-bit). For added spice, the totals
456 * accumulate rather than restarting from zero, and the index of the
457 * 'val' byte is added each time (position dependence). If I was a
458 * black-belt, I'd scan big-endian pointers in reverse to give low-order
459 * bits more play, but this isn't crypto and I'd prefer nobody mistake it
460 * as such. Plus I'm lazy.
462 while (dnum--) {
463 const unsigned char *src = (void *)&id->ptr;
464 unsigned char snum = sizeof(id->ptr);
465 while (snum--)
466 accum += *(src++) * hash_coeffs[(snum + dnum) & 7];
467 accum += dnum;
468 *(dest++) = accum & 255;
472 int CRYPTO_THREADID_set_callback(void (*func) (CRYPTO_THREADID *))
474 if (threadid_callback)
475 return 0;
476 threadid_callback = func;
477 return 1;
480 void (*CRYPTO_THREADID_get_callback(void)) (CRYPTO_THREADID *) {
481 return threadid_callback;
484 void CRYPTO_THREADID_current(CRYPTO_THREADID *id)
486 if (threadid_callback) {
487 threadid_callback(id);
488 return;
490 #ifndef OPENSSL_NO_DEPRECATED
491 /* If the deprecated callback was set, fall back to that */
492 if (id_callback) {
493 CRYPTO_THREADID_set_numeric(id, id_callback());
494 return;
496 #endif
497 /* Else pick a backup */
498 #ifdef OPENSSL_SYS_WIN16
499 CRYPTO_THREADID_set_numeric(id, (unsigned long)GetCurrentTask());
500 #elif defined(OPENSSL_SYS_WIN32)
501 CRYPTO_THREADID_set_numeric(id, (unsigned long)GetCurrentThreadId());
502 #elif defined(OPENSSL_SYS_BEOS)
503 CRYPTO_THREADID_set_numeric(id, (unsigned long)find_thread(NULL));
504 #else
505 /* For everything else, default to using the address of 'errno' */
506 CRYPTO_THREADID_set_pointer(id, (void *)&errno);
507 #endif
510 int CRYPTO_THREADID_cmp(const CRYPTO_THREADID *a, const CRYPTO_THREADID *b)
512 return memcmp(a, b, sizeof(*a));
515 void CRYPTO_THREADID_cpy(CRYPTO_THREADID *dest, const CRYPTO_THREADID *src)
517 memcpy(dest, src, sizeof(*src));
520 unsigned long CRYPTO_THREADID_hash(const CRYPTO_THREADID *id)
522 return id->val;
525 #ifndef OPENSSL_NO_DEPRECATED
526 unsigned long (*CRYPTO_get_id_callback(void)) (void) {
527 return (id_callback);
530 void CRYPTO_set_id_callback(unsigned long (*func) (void))
532 id_callback = func;
535 unsigned long CRYPTO_thread_id(void)
537 unsigned long ret = 0;
539 if (id_callback == NULL) {
540 # ifdef OPENSSL_SYS_WIN16
541 ret = (unsigned long)GetCurrentTask();
542 # elif defined(OPENSSL_SYS_WIN32)
543 ret = (unsigned long)GetCurrentThreadId();
544 # elif defined(GETPID_IS_MEANINGLESS)
545 ret = 1L;
546 # elif defined(OPENSSL_SYS_BEOS)
547 ret = (unsigned long)find_thread(NULL);
548 # else
549 ret = (unsigned long)getpid();
550 # endif
551 } else
552 ret = id_callback();
553 return (ret);
555 #endif
557 void CRYPTO_lock(int mode, int type, const char *file, int line)
559 #ifdef LOCK_DEBUG
561 CRYPTO_THREADID id;
562 char *rw_text, *operation_text;
564 if (mode & CRYPTO_LOCK)
565 operation_text = "lock ";
566 else if (mode & CRYPTO_UNLOCK)
567 operation_text = "unlock";
568 else
569 operation_text = "ERROR ";
571 if (mode & CRYPTO_READ)
572 rw_text = "r";
573 else if (mode & CRYPTO_WRITE)
574 rw_text = "w";
575 else
576 rw_text = "ERROR";
578 CRYPTO_THREADID_current(&id);
579 fprintf(stderr, "lock:%08lx:(%s)%s %-18s %s:%d\n",
580 CRYPTO_THREADID_hash(&id), rw_text, operation_text,
581 CRYPTO_get_lock_name(type), file, line);
583 #endif
584 if (type < 0) {
585 if (dynlock_lock_callback != NULL) {
586 struct CRYPTO_dynlock_value *pointer
587 = CRYPTO_get_dynlock_value(type);
589 OPENSSL_assert(pointer != NULL);
591 dynlock_lock_callback(mode, pointer, file, line);
593 CRYPTO_destroy_dynlockid(type);
595 } else if (locking_callback != NULL)
596 locking_callback(mode, type, file, line);
599 int CRYPTO_add_lock(int *pointer, int amount, int type, const char *file,
600 int line)
602 int ret = 0;
604 if (add_lock_callback != NULL) {
605 #ifdef LOCK_DEBUG
606 int before = *pointer;
607 #endif
609 ret = add_lock_callback(pointer, amount, type, file, line);
610 #ifdef LOCK_DEBUG
612 CRYPTO_THREADID id;
613 CRYPTO_THREADID_current(&id);
614 fprintf(stderr, "ladd:%08lx:%2d+%2d->%2d %-18s %s:%d\n",
615 CRYPTO_THREADID_hash(&id), before, amount, ret,
616 CRYPTO_get_lock_name(type), file, line);
618 #endif
619 } else {
620 CRYPTO_lock(CRYPTO_LOCK | CRYPTO_WRITE, type, file, line);
622 ret = *pointer + amount;
623 #ifdef LOCK_DEBUG
625 CRYPTO_THREADID id;
626 CRYPTO_THREADID_current(&id);
627 fprintf(stderr, "ladd:%08lx:%2d+%2d->%2d %-18s %s:%d\n",
628 CRYPTO_THREADID_hash(&id),
629 *pointer, amount, ret,
630 CRYPTO_get_lock_name(type), file, line);
632 #endif
633 *pointer = ret;
634 CRYPTO_lock(CRYPTO_UNLOCK | CRYPTO_WRITE, type, file, line);
636 return (ret);
639 const char *CRYPTO_get_lock_name(int type)
641 if (type < 0)
642 return ("dynamic");
643 else if (type < CRYPTO_NUM_LOCKS)
644 return (lock_names[type]);
645 else if (type - CRYPTO_NUM_LOCKS > sk_OPENSSL_STRING_num(app_locks))
646 return ("ERROR");
647 else
648 return (sk_OPENSSL_STRING_value(app_locks, type - CRYPTO_NUM_LOCKS));
651 #if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
652 defined(__INTEL__) || \
653 defined(__x86_64) || defined(__x86_64__) || \
654 defined(_M_AMD64) || defined(_M_X64)
656 extern unsigned int OPENSSL_ia32cap_P[4];
657 unsigned long *OPENSSL_ia32cap_loc(void)
659 if (sizeof(long) == 4)
661 * If 32-bit application pulls address of OPENSSL_ia32cap_P[0]
662 * clear second element to maintain the illusion that vector
663 * is 32-bit.
665 OPENSSL_ia32cap_P[1] = 0;
667 OPENSSL_ia32cap_P[2] = 0;
669 return (unsigned long *)OPENSSL_ia32cap_P;
672 # if defined(OPENSSL_CPUID_OBJ) && !defined(OPENSSL_NO_ASM) && !defined(I386_ONLY)
673 # define OPENSSL_CPUID_SETUP
674 # if defined(_WIN32)
675 typedef unsigned __int64 IA32CAP;
676 # else
677 typedef unsigned long long IA32CAP;
678 # endif
679 void OPENSSL_cpuid_setup(void)
681 static int trigger = 0;
682 IA32CAP OPENSSL_ia32_cpuid(unsigned int *);
683 IA32CAP vec;
684 char *env;
686 if (trigger)
687 return;
689 trigger = 1;
690 if ((env = getenv("OPENSSL_ia32cap"))) {
691 int off = (env[0] == '~') ? 1 : 0;
692 # if defined(_WIN32)
693 if (!sscanf(env + off, "%I64i", &vec))
694 vec = strtoul(env + off, NULL, 0);
695 # else
696 if (!sscanf(env + off, "%lli", (long long *)&vec))
697 vec = strtoul(env + off, NULL, 0);
698 # endif
699 if (off)
700 vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P) & ~vec;
701 else if (env[0] == ':')
702 vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
704 OPENSSL_ia32cap_P[2] = 0;
705 if ((env = strchr(env, ':'))) {
706 unsigned int vecx;
707 env++;
708 off = (env[0] == '~') ? 1 : 0;
709 vecx = strtoul(env + off, NULL, 0);
710 if (off)
711 OPENSSL_ia32cap_P[2] &= ~vecx;
712 else
713 OPENSSL_ia32cap_P[2] = vecx;
715 } else
716 vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
719 * |(1<<10) sets a reserved bit to signal that variable
720 * was initialized already... This is to avoid interference
721 * with cpuid snippets in ELF .init segment.
723 OPENSSL_ia32cap_P[0] = (unsigned int)vec | (1 << 10);
724 OPENSSL_ia32cap_P[1] = (unsigned int)(vec >> 32);
726 # else
727 unsigned int OPENSSL_ia32cap_P[4];
728 # endif
730 #else
731 unsigned long *OPENSSL_ia32cap_loc(void)
733 return NULL;
735 #endif
736 int OPENSSL_NONPIC_relocated = 0;
737 #if !defined(OPENSSL_CPUID_SETUP) && !defined(OPENSSL_CPUID_OBJ)
738 void OPENSSL_cpuid_setup(void)
741 #endif
743 #if (defined(_WIN32) || defined(__CYGWIN__)) && defined(_WINDLL)
744 # ifdef __CYGWIN__
745 /* pick DLL_[PROCESS|THREAD]_[ATTACH|DETACH] definitions */
746 # include <windows.h>
748 * this has side-effect of _WIN32 getting defined, which otherwise is
749 * mutually exclusive with __CYGWIN__...
751 # endif
754 * All we really need to do is remove the 'error' state when a thread
755 * detaches
758 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
760 switch (fdwReason) {
761 case DLL_PROCESS_ATTACH:
762 OPENSSL_cpuid_setup();
763 # if defined(_WIN32_WINNT)
765 IMAGE_DOS_HEADER *dos_header = (IMAGE_DOS_HEADER *) hinstDLL;
766 IMAGE_NT_HEADERS *nt_headers;
768 if (dos_header->e_magic == IMAGE_DOS_SIGNATURE) {
769 nt_headers = (IMAGE_NT_HEADERS *) ((char *)dos_header
770 + dos_header->e_lfanew);
771 if (nt_headers->Signature == IMAGE_NT_SIGNATURE &&
772 hinstDLL !=
773 (HINSTANCE) (nt_headers->OptionalHeader.ImageBase))
774 OPENSSL_NONPIC_relocated = 1;
777 # endif
778 break;
779 case DLL_THREAD_ATTACH:
780 break;
781 case DLL_THREAD_DETACH:
782 break;
783 case DLL_PROCESS_DETACH:
784 break;
786 return (TRUE);
788 #endif
790 #if defined(_WIN32) && !defined(__CYGWIN__)
791 # include <tchar.h>
792 # include <signal.h>
793 # ifdef __WATCOMC__
794 # if defined(_UNICODE) || defined(__UNICODE__)
795 # define _vsntprintf _vsnwprintf
796 # else
797 # define _vsntprintf _vsnprintf
798 # endif
799 # endif
800 # ifdef _MSC_VER
801 # define alloca _alloca
802 # endif
804 # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
805 int OPENSSL_isservice(void)
807 HWINSTA h;
808 DWORD len;
809 WCHAR *name;
810 static union {
811 void *p;
812 int (*f) (void);
813 } _OPENSSL_isservice = {
814 NULL
817 if (_OPENSSL_isservice.p == NULL) {
818 HANDLE h = GetModuleHandle(NULL);
819 if (h != NULL)
820 _OPENSSL_isservice.p = GetProcAddress(h, "_OPENSSL_isservice");
821 if (_OPENSSL_isservice.p == NULL)
822 _OPENSSL_isservice.p = (void *)-1;
825 if (_OPENSSL_isservice.p != (void *)-1)
826 return (*_OPENSSL_isservice.f) ();
828 (void)GetDesktopWindow(); /* return value is ignored */
830 h = GetProcessWindowStation();
831 if (h == NULL)
832 return -1;
834 if (GetUserObjectInformationW(h, UOI_NAME, NULL, 0, &len) ||
835 GetLastError() != ERROR_INSUFFICIENT_BUFFER)
836 return -1;
838 if (len > 512)
839 return -1; /* paranoia */
840 len++, len &= ~1; /* paranoia */
841 name = (WCHAR *)alloca(len + sizeof(WCHAR));
842 if (!GetUserObjectInformationW(h, UOI_NAME, name, len, &len))
843 return -1;
845 len++, len &= ~1; /* paranoia */
846 name[len / sizeof(WCHAR)] = L'\0'; /* paranoia */
847 # if 1
849 * This doesn't cover "interactive" services [working with real
850 * WinSta0's] nor programs started non-interactively by Task Scheduler
851 * [those are working with SAWinSta].
853 if (wcsstr(name, L"Service-0x"))
854 return 1;
855 # else
856 /* This covers all non-interactive programs such as services. */
857 if (!wcsstr(name, L"WinSta0"))
858 return 1;
859 # endif
860 else
861 return 0;
863 # else
864 int OPENSSL_isservice(void)
866 return 0;
868 # endif
870 void OPENSSL_showfatal(const char *fmta, ...)
872 va_list ap;
873 TCHAR buf[256];
874 const TCHAR *fmt;
875 # ifdef STD_ERROR_HANDLE /* what a dirty trick! */
876 HANDLE h;
878 if ((h = GetStdHandle(STD_ERROR_HANDLE)) != NULL &&
879 GetFileType(h) != FILE_TYPE_UNKNOWN) {
880 /* must be console application */
881 int len;
882 DWORD out;
884 va_start(ap, fmta);
885 len = _vsnprintf((char *)buf, sizeof(buf), fmta, ap);
886 WriteFile(h, buf, len < 0 ? sizeof(buf) : (DWORD) len, &out, NULL);
887 va_end(ap);
888 return;
890 # endif
892 if (sizeof(TCHAR) == sizeof(char))
893 fmt = (const TCHAR *)fmta;
894 else
895 do {
896 int keepgoing;
897 size_t len_0 = strlen(fmta) + 1, i;
898 WCHAR *fmtw;
900 fmtw = (WCHAR *)alloca(len_0 * sizeof(WCHAR));
901 if (fmtw == NULL) {
902 fmt = (const TCHAR *)L"no stack?";
903 break;
905 # ifndef OPENSSL_NO_MULTIBYTE
906 if (!MultiByteToWideChar(CP_ACP, 0, fmta, len_0, fmtw, len_0))
907 # endif
908 for (i = 0; i < len_0; i++)
909 fmtw[i] = (WCHAR)fmta[i];
911 for (i = 0; i < len_0; i++) {
912 if (fmtw[i] == L'%')
913 do {
914 keepgoing = 0;
915 switch (fmtw[i + 1]) {
916 case L'0':
917 case L'1':
918 case L'2':
919 case L'3':
920 case L'4':
921 case L'5':
922 case L'6':
923 case L'7':
924 case L'8':
925 case L'9':
926 case L'.':
927 case L'*':
928 case L'-':
929 i++;
930 keepgoing = 1;
931 break;
932 case L's':
933 fmtw[i + 1] = L'S';
934 break;
935 case L'S':
936 fmtw[i + 1] = L's';
937 break;
938 case L'c':
939 fmtw[i + 1] = L'C';
940 break;
941 case L'C':
942 fmtw[i + 1] = L'c';
943 break;
945 } while (keepgoing);
947 fmt = (const TCHAR *)fmtw;
948 } while (0);
950 va_start(ap, fmta);
951 _vsntprintf(buf, sizeof(buf) / sizeof(TCHAR) - 1, fmt, ap);
952 buf[sizeof(buf) / sizeof(TCHAR) - 1] = _T('\0');
953 va_end(ap);
955 # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
956 /* this -------------v--- guards NT-specific calls */
957 if (check_winnt() && OPENSSL_isservice() > 0) {
958 HANDLE h = RegisterEventSource(0, _T("OPENSSL"));
959 const TCHAR *pmsg = buf;
960 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, 0, 0, 1, 0, &pmsg, 0);
961 DeregisterEventSource(h);
962 } else
963 # endif
964 MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONSTOP);
966 #else
967 void OPENSSL_showfatal(const char *fmta, ...)
969 va_list ap;
971 va_start(ap, fmta);
972 vfprintf(stderr, fmta, ap);
973 va_end(ap);
976 int OPENSSL_isservice(void)
978 return 0;
980 #endif
982 void OpenSSLDie(const char *file, int line, const char *assertion)
984 OPENSSL_showfatal
985 ("%s(%d): OpenSSL internal error, assertion failed: %s\n", file, line,
986 assertion);
987 #if !defined(_WIN32) || defined(__CYGWIN__)
988 abort();
989 #else
991 * Win32 abort() customarily shows a dialog, but we just did that...
993 # if !defined(_WIN32_WCE)
994 raise(SIGABRT);
995 # endif
996 _exit(3);
997 #endif
1000 void *OPENSSL_stderr(void)
1002 return stderr;
1005 int CRYPTO_memcmp(const void *in_a, const void *in_b, size_t len)
1007 size_t i;
1008 const unsigned char *a = in_a;
1009 const unsigned char *b = in_b;
1010 unsigned char x = 0;
1012 for (i = 0; i < len; i++)
1013 x |= a[i] ^ b[i];
1015 return x;