cryptlib.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. /* crypto/cryptlib.c */
  2. /* ====================================================================
  3. * Copyright (c) 1998-2006 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. * [email protected].
  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. * ([email protected]). This product includes software written by Tim
  52. * Hudson ([email protected]).
  53. *
  54. */
  55. /* Copyright (C) 1995-1998 Eric Young ([email protected])
  56. * All rights reserved.
  57. *
  58. * This package is an SSL implementation written
  59. * by Eric Young ([email protected]).
  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 ([email protected]).
  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 ([email protected])"
  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 ([email protected])"
  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. #include "cryptlib.h"
  117. #include <openssl/safestack.h>
  118. #if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16)
  119. static double SSLeay_MSVC5_hack=0.0; /* and for VC1.5 */
  120. #endif
  121. DECLARE_STACK_OF(CRYPTO_dynlock)
  122. /* real #defines in crypto.h, keep these upto date */
  123. static const char* const lock_names[CRYPTO_NUM_LOCKS] =
  124. {
  125. "<<ERROR>>",
  126. "err",
  127. "ex_data",
  128. "x509",
  129. "x509_info",
  130. "x509_pkey",
  131. "x509_crl",
  132. "x509_req",
  133. "dsa",
  134. "rsa",
  135. "evp_pkey",
  136. "x509_store",
  137. "ssl_ctx",
  138. "ssl_cert",
  139. "ssl_session",
  140. "ssl_sess_cert",
  141. "ssl",
  142. "ssl_method",
  143. "rand",
  144. "rand2",
  145. "debug_malloc",
  146. "BIO",
  147. "gethostbyname",
  148. "getservbyname",
  149. "readdir",
  150. "RSA_blinding",
  151. "dh",
  152. "debug_malloc2",
  153. "dso",
  154. "dynlock",
  155. "engine",
  156. "ui",
  157. "ecdsa",
  158. "ec",
  159. "ecdh",
  160. "bn",
  161. "ec_pre_comp",
  162. "store",
  163. "comp",
  164. "fips",
  165. "fips2",
  166. #if CRYPTO_NUM_LOCKS != 41
  167. # error "Inconsistency between crypto.h and cryptlib.c"
  168. #endif
  169. };
  170. /* This is for applications to allocate new type names in the non-dynamic
  171. array of lock names. These are numbered with positive numbers. */
  172. static STACK_OF(OPENSSL_STRING) *app_locks=NULL;
  173. /* For applications that want a more dynamic way of handling threads, the
  174. following stack is used. These are externally numbered with negative
  175. numbers. */
  176. static STACK_OF(CRYPTO_dynlock) *dyn_locks=NULL;
  177. static void (MS_FAR *locking_callback)(int mode,int type,
  178. const char *file,int line)=0;
  179. static int (MS_FAR *add_lock_callback)(int *pointer,int amount,
  180. int type,const char *file,int line)=0;
  181. #ifndef OPENSSL_NO_DEPRECATED
  182. static unsigned long (MS_FAR *id_callback)(void)=0;
  183. #endif
  184. static void (MS_FAR *threadid_callback)(CRYPTO_THREADID *)=0;
  185. static struct CRYPTO_dynlock_value *(MS_FAR *dynlock_create_callback)
  186. (const char *file,int line)=0;
  187. static void (MS_FAR *dynlock_lock_callback)(int mode,
  188. struct CRYPTO_dynlock_value *l, const char *file,int line)=0;
  189. static void (MS_FAR *dynlock_destroy_callback)(struct CRYPTO_dynlock_value *l,
  190. const char *file,int line)=0;
  191. int CRYPTO_get_new_lockid(char *name)
  192. {
  193. char *str;
  194. int i;
  195. #if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16)
  196. /* A hack to make Visual C++ 5.0 work correctly when linking as
  197. * a DLL using /MT. Without this, the application cannot use
  198. * any floating point printf's.
  199. * It also seems to be needed for Visual C 1.5 (win16) */
  200. SSLeay_MSVC5_hack=(double)name[0]*(double)name[1];
  201. #endif
  202. if ((app_locks == NULL) && ((app_locks=sk_OPENSSL_STRING_new_null()) == NULL))
  203. {
  204. CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_LOCKID,ERR_R_MALLOC_FAILURE);
  205. return(0);
  206. }
  207. if ((str=BUF_strdup(name)) == NULL)
  208. {
  209. CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_LOCKID,ERR_R_MALLOC_FAILURE);
  210. return(0);
  211. }
  212. i=sk_OPENSSL_STRING_push(app_locks,str);
  213. if (!i)
  214. OPENSSL_free(str);
  215. else
  216. i+=CRYPTO_NUM_LOCKS; /* gap of one :-) */
  217. return(i);
  218. }
  219. int CRYPTO_num_locks(void)
  220. {
  221. return CRYPTO_NUM_LOCKS;
  222. }
  223. int CRYPTO_get_new_dynlockid(void)
  224. {
  225. int i = 0;
  226. CRYPTO_dynlock *pointer = NULL;
  227. if (dynlock_create_callback == NULL)
  228. {
  229. CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,CRYPTO_R_NO_DYNLOCK_CREATE_CALLBACK);
  230. return(0);
  231. }
  232. CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
  233. if ((dyn_locks == NULL)
  234. && ((dyn_locks=sk_CRYPTO_dynlock_new_null()) == NULL))
  235. {
  236. CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
  237. CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,ERR_R_MALLOC_FAILURE);
  238. return(0);
  239. }
  240. CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
  241. pointer = (CRYPTO_dynlock *)OPENSSL_malloc(sizeof(CRYPTO_dynlock));
  242. if (pointer == NULL)
  243. {
  244. CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,ERR_R_MALLOC_FAILURE);
  245. return(0);
  246. }
  247. pointer->references = 1;
  248. pointer->data = dynlock_create_callback(__FILE__,__LINE__);
  249. if (pointer->data == NULL)
  250. {
  251. OPENSSL_free(pointer);
  252. CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID,ERR_R_MALLOC_FAILURE);
  253. return(0);
  254. }
  255. CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
  256. /* First, try to find an existing empty slot */
  257. i=sk_CRYPTO_dynlock_find(dyn_locks,NULL);
  258. /* If there was none, push, thereby creating a new one */
  259. if (i == -1)
  260. /* Since sk_push() returns the number of items on the
  261. stack, not the location of the pushed item, we need
  262. to transform the returned number into a position,
  263. by decreasing it. */
  264. i=sk_CRYPTO_dynlock_push(dyn_locks,pointer) - 1;
  265. else
  266. /* If we found a place with a NULL pointer, put our pointer
  267. in it. */
  268. (void)sk_CRYPTO_dynlock_set(dyn_locks,i,pointer);
  269. CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
  270. if (i == -1)
  271. {
  272. dynlock_destroy_callback(pointer->data,__FILE__,__LINE__);
  273. OPENSSL_free(pointer);
  274. }
  275. else
  276. i += 1; /* to avoid 0 */
  277. return -i;
  278. }
  279. void CRYPTO_destroy_dynlockid(int i)
  280. {
  281. CRYPTO_dynlock *pointer = NULL;
  282. if (i)
  283. i = -i-1;
  284. if (dynlock_destroy_callback == NULL)
  285. return;
  286. CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
  287. if (dyn_locks == NULL || i >= sk_CRYPTO_dynlock_num(dyn_locks))
  288. {
  289. CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
  290. return;
  291. }
  292. pointer = sk_CRYPTO_dynlock_value(dyn_locks, i);
  293. if (pointer != NULL)
  294. {
  295. --pointer->references;
  296. #ifdef REF_CHECK
  297. if (pointer->references < 0)
  298. {
  299. fprintf(stderr,"CRYPTO_destroy_dynlockid, bad reference count\n");
  300. abort();
  301. }
  302. else
  303. #endif
  304. if (pointer->references <= 0)
  305. {
  306. (void)sk_CRYPTO_dynlock_set(dyn_locks, i, NULL);
  307. }
  308. else
  309. pointer = NULL;
  310. }
  311. CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
  312. if (pointer)
  313. {
  314. dynlock_destroy_callback(pointer->data,__FILE__,__LINE__);
  315. OPENSSL_free(pointer);
  316. }
  317. }
  318. struct CRYPTO_dynlock_value *CRYPTO_get_dynlock_value(int i)
  319. {
  320. CRYPTO_dynlock *pointer = NULL;
  321. if (i)
  322. i = -i-1;
  323. CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
  324. if (dyn_locks != NULL && i < sk_CRYPTO_dynlock_num(dyn_locks))
  325. pointer = sk_CRYPTO_dynlock_value(dyn_locks, i);
  326. if (pointer)
  327. pointer->references++;
  328. CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
  329. if (pointer)
  330. return pointer->data;
  331. return NULL;
  332. }
  333. struct CRYPTO_dynlock_value *(*CRYPTO_get_dynlock_create_callback(void))
  334. (const char *file,int line)
  335. {
  336. return(dynlock_create_callback);
  337. }
  338. void (*CRYPTO_get_dynlock_lock_callback(void))(int mode,
  339. struct CRYPTO_dynlock_value *l, const char *file,int line)
  340. {
  341. return(dynlock_lock_callback);
  342. }
  343. void (*CRYPTO_get_dynlock_destroy_callback(void))
  344. (struct CRYPTO_dynlock_value *l, const char *file,int line)
  345. {
  346. return(dynlock_destroy_callback);
  347. }
  348. void CRYPTO_set_dynlock_create_callback(struct CRYPTO_dynlock_value *(*func)
  349. (const char *file, int line))
  350. {
  351. dynlock_create_callback=func;
  352. }
  353. void CRYPTO_set_dynlock_lock_callback(void (*func)(int mode,
  354. struct CRYPTO_dynlock_value *l, const char *file, int line))
  355. {
  356. dynlock_lock_callback=func;
  357. }
  358. void CRYPTO_set_dynlock_destroy_callback(void (*func)
  359. (struct CRYPTO_dynlock_value *l, const char *file, int line))
  360. {
  361. dynlock_destroy_callback=func;
  362. }
  363. void (*CRYPTO_get_locking_callback(void))(int mode,int type,const char *file,
  364. int line)
  365. {
  366. return(locking_callback);
  367. }
  368. int (*CRYPTO_get_add_lock_callback(void))(int *num,int mount,int type,
  369. const char *file,int line)
  370. {
  371. return(add_lock_callback);
  372. }
  373. void CRYPTO_set_locking_callback(void (*func)(int mode,int type,
  374. const char *file,int line))
  375. {
  376. /* Calling this here ensures initialisation before any threads
  377. * are started.
  378. */
  379. OPENSSL_init();
  380. locking_callback=func;
  381. }
  382. void CRYPTO_set_add_lock_callback(int (*func)(int *num,int mount,int type,
  383. const char *file,int line))
  384. {
  385. add_lock_callback=func;
  386. }
  387. /* the memset() here and in set_pointer() seem overkill, but for the sake of
  388. * CRYPTO_THREADID_cmp() this avoids any platform silliness that might cause two
  389. * "equal" THREADID structs to not be memcmp()-identical. */
  390. void CRYPTO_THREADID_set_numeric(CRYPTO_THREADID *id, unsigned long val)
  391. {
  392. memset(id, 0, sizeof(*id));
  393. id->val = val;
  394. }
  395. static const unsigned char hash_coeffs[] = { 3, 5, 7, 11, 13, 17, 19, 23 };
  396. void CRYPTO_THREADID_set_pointer(CRYPTO_THREADID *id, void *ptr)
  397. {
  398. unsigned char *dest = (void *)&id->val;
  399. unsigned int accum = 0;
  400. unsigned char dnum = sizeof(id->val);
  401. memset(id, 0, sizeof(*id));
  402. id->ptr = ptr;
  403. if (sizeof(id->val) >= sizeof(id->ptr))
  404. {
  405. /* 'ptr' can be embedded in 'val' without loss of uniqueness */
  406. id->val = (unsigned long)id->ptr;
  407. return;
  408. }
  409. /* hash ptr ==> val. Each byte of 'val' gets the mod-256 total of a
  410. * linear function over the bytes in 'ptr', the co-efficients of which
  411. * are a sequence of low-primes (hash_coeffs is an 8-element cycle) -
  412. * the starting prime for the sequence varies for each byte of 'val'
  413. * (unique polynomials unless pointers are >64-bit). For added spice,
  414. * the totals accumulate rather than restarting from zero, and the index
  415. * of the 'val' byte is added each time (position dependence). If I was
  416. * a black-belt, I'd scan big-endian pointers in reverse to give
  417. * low-order bits more play, but this isn't crypto and I'd prefer nobody
  418. * mistake it as such. Plus I'm lazy. */
  419. while (dnum--)
  420. {
  421. const unsigned char *src = (void *)&id->ptr;
  422. unsigned char snum = sizeof(id->ptr);
  423. while (snum--)
  424. accum += *(src++) * hash_coeffs[(snum + dnum) & 7];
  425. accum += dnum;
  426. *(dest++) = accum & 255;
  427. }
  428. }
  429. int CRYPTO_THREADID_set_callback(void (*func)(CRYPTO_THREADID *))
  430. {
  431. if (threadid_callback)
  432. return 0;
  433. threadid_callback = func;
  434. return 1;
  435. }
  436. void (*CRYPTO_THREADID_get_callback(void))(CRYPTO_THREADID *)
  437. {
  438. return threadid_callback;
  439. }
  440. void CRYPTO_THREADID_current(CRYPTO_THREADID *id)
  441. {
  442. if (threadid_callback)
  443. {
  444. threadid_callback(id);
  445. return;
  446. }
  447. #ifndef OPENSSL_NO_DEPRECATED
  448. /* If the deprecated callback was set, fall back to that */
  449. if (id_callback)
  450. {
  451. CRYPTO_THREADID_set_numeric(id, id_callback());
  452. return;
  453. }
  454. #endif
  455. /* Else pick a backup */
  456. #ifdef OPENSSL_SYS_WIN16
  457. CRYPTO_THREADID_set_numeric(id, (unsigned long)GetCurrentTask());
  458. #elif defined(OPENSSL_SYS_WIN32)
  459. CRYPTO_THREADID_set_numeric(id, (unsigned long)GetCurrentThreadId());
  460. #elif defined(OPENSSL_SYS_BEOS)
  461. CRYPTO_THREADID_set_numeric(id, (unsigned long)find_thread(NULL));
  462. #else
  463. /* For everything else, default to using the address of 'errno' */
  464. CRYPTO_THREADID_set_pointer(id, (void*)&errno);
  465. #endif
  466. }
  467. int CRYPTO_THREADID_cmp(const CRYPTO_THREADID *a, const CRYPTO_THREADID *b)
  468. {
  469. return memcmp(a, b, sizeof(*a));
  470. }
  471. void CRYPTO_THREADID_cpy(CRYPTO_THREADID *dest, const CRYPTO_THREADID *src)
  472. {
  473. memcpy(dest, src, sizeof(*src));
  474. }
  475. unsigned long CRYPTO_THREADID_hash(const CRYPTO_THREADID *id)
  476. {
  477. return id->val;
  478. }
  479. #ifndef OPENSSL_NO_DEPRECATED
  480. unsigned long (*CRYPTO_get_id_callback(void))(void)
  481. {
  482. return(id_callback);
  483. }
  484. void CRYPTO_set_id_callback(unsigned long (*func)(void))
  485. {
  486. id_callback=func;
  487. }
  488. unsigned long CRYPTO_thread_id(void)
  489. {
  490. unsigned long ret=0;
  491. if (id_callback == NULL)
  492. {
  493. #ifdef OPENSSL_SYS_WIN16
  494. ret=(unsigned long)GetCurrentTask();
  495. #elif defined(OPENSSL_SYS_WIN32)
  496. ret=(unsigned long)GetCurrentThreadId();
  497. #elif defined(GETPID_IS_MEANINGLESS)
  498. ret=1L;
  499. #elif defined(OPENSSL_SYS_BEOS)
  500. ret=(unsigned long)find_thread(NULL);
  501. #else
  502. ret=(unsigned long)getpid();
  503. #endif
  504. }
  505. else
  506. ret=id_callback();
  507. return(ret);
  508. }
  509. #endif
  510. void CRYPTO_lock(int mode, int type, const char *file, int line)
  511. {
  512. #ifdef LOCK_DEBUG
  513. {
  514. CRYPTO_THREADID id;
  515. char *rw_text,*operation_text;
  516. if (mode & CRYPTO_LOCK)
  517. operation_text="lock ";
  518. else if (mode & CRYPTO_UNLOCK)
  519. operation_text="unlock";
  520. else
  521. operation_text="ERROR ";
  522. if (mode & CRYPTO_READ)
  523. rw_text="r";
  524. else if (mode & CRYPTO_WRITE)
  525. rw_text="w";
  526. else
  527. rw_text="ERROR";
  528. CRYPTO_THREADID_current(&id);
  529. fprintf(stderr,"lock:%08lx:(%s)%s %-18s %s:%d\n",
  530. CRYPTO_THREADID_hash(&id), rw_text, operation_text,
  531. CRYPTO_get_lock_name(type), file, line);
  532. }
  533. #endif
  534. if (type < 0)
  535. {
  536. if (dynlock_lock_callback != NULL)
  537. {
  538. struct CRYPTO_dynlock_value *pointer
  539. = CRYPTO_get_dynlock_value(type);
  540. OPENSSL_assert(pointer != NULL);
  541. dynlock_lock_callback(mode, pointer, file, line);
  542. CRYPTO_destroy_dynlockid(type);
  543. }
  544. }
  545. else
  546. if (locking_callback != NULL)
  547. locking_callback(mode,type,file,line);
  548. }
  549. int CRYPTO_add_lock(int *pointer, int amount, int type, const char *file,
  550. int line)
  551. {
  552. int ret = 0;
  553. if (add_lock_callback != NULL)
  554. {
  555. #ifdef LOCK_DEBUG
  556. int before= *pointer;
  557. #endif
  558. ret=add_lock_callback(pointer,amount,type,file,line);
  559. #ifdef LOCK_DEBUG
  560. {
  561. CRYPTO_THREADID id;
  562. CRYPTO_THREADID_current(&id);
  563. fprintf(stderr,"ladd:%08lx:%2d+%2d->%2d %-18s %s:%d\n",
  564. CRYPTO_THREADID_hash(&id), before,amount,ret,
  565. CRYPTO_get_lock_name(type),
  566. file,line);
  567. }
  568. #endif
  569. }
  570. else
  571. {
  572. CRYPTO_lock(CRYPTO_LOCK|CRYPTO_WRITE,type,file,line);
  573. ret= *pointer+amount;
  574. #ifdef LOCK_DEBUG
  575. {
  576. CRYPTO_THREADID id;
  577. CRYPTO_THREADID_current(&id);
  578. fprintf(stderr,"ladd:%08lx:%2d+%2d->%2d %-18s %s:%d\n",
  579. CRYPTO_THREADID_hash(&id),
  580. *pointer,amount,ret,
  581. CRYPTO_get_lock_name(type),
  582. file,line);
  583. }
  584. #endif
  585. *pointer=ret;
  586. CRYPTO_lock(CRYPTO_UNLOCK|CRYPTO_WRITE,type,file,line);
  587. }
  588. return(ret);
  589. }
  590. const char *CRYPTO_get_lock_name(int type)
  591. {
  592. if (type < 0)
  593. return("dynamic");
  594. else if (type < CRYPTO_NUM_LOCKS)
  595. return(lock_names[type]);
  596. else if (type-CRYPTO_NUM_LOCKS > sk_OPENSSL_STRING_num(app_locks))
  597. return("ERROR");
  598. else
  599. return(sk_OPENSSL_STRING_value(app_locks,type-CRYPTO_NUM_LOCKS));
  600. }
  601. #if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
  602. defined(__INTEL__) || \
  603. defined(__x86_64) || defined(__x86_64__) || defined(_M_AMD64) || defined(_M_X64)
  604. unsigned int OPENSSL_ia32cap_P[2];
  605. unsigned long *OPENSSL_ia32cap_loc(void)
  606. { if (sizeof(long)==4)
  607. /*
  608. * If 32-bit application pulls address of OPENSSL_ia32cap_P[0]
  609. * clear second element to maintain the illusion that vector
  610. * is 32-bit.
  611. */
  612. OPENSSL_ia32cap_P[1]=0;
  613. return (unsigned long *)OPENSSL_ia32cap_P;
  614. }
  615. #if defined(OPENSSL_CPUID_OBJ) && !defined(OPENSSL_NO_ASM) && !defined(I386_ONLY)
  616. #define OPENSSL_CPUID_SETUP
  617. #if defined(_WIN32)
  618. typedef unsigned __int64 IA32CAP;
  619. #else
  620. typedef unsigned long long IA32CAP;
  621. #endif
  622. void OPENSSL_cpuid_setup(void)
  623. { static int trigger=0;
  624. IA32CAP OPENSSL_ia32_cpuid(void);
  625. IA32CAP vec;
  626. char *env;
  627. if (trigger) return;
  628. trigger=1;
  629. if ((env=getenv("OPENSSL_ia32cap"))) {
  630. int off = (env[0]=='~')?1:0;
  631. #if defined(_WIN32)
  632. if (!sscanf(env+off,"%I64i",&vec)) vec = strtoul(env+off,NULL,0);
  633. #else
  634. if (!sscanf(env+off,"%lli",(long long *)&vec)) vec = strtoul(env+off,NULL,0);
  635. #endif
  636. if (off) vec = OPENSSL_ia32_cpuid()&~vec;
  637. }
  638. else
  639. vec = OPENSSL_ia32_cpuid();
  640. /*
  641. * |(1<<10) sets a reserved bit to signal that variable
  642. * was initialized already... This is to avoid interference
  643. * with cpuid snippets in ELF .init segment.
  644. */
  645. OPENSSL_ia32cap_P[0] = (unsigned int)vec|(1<<10);
  646. OPENSSL_ia32cap_P[1] = (unsigned int)(vec>>32);
  647. }
  648. #endif
  649. #else
  650. unsigned long *OPENSSL_ia32cap_loc(void) { return NULL; }
  651. #endif
  652. int OPENSSL_NONPIC_relocated = 0;
  653. #if !defined(OPENSSL_CPUID_SETUP) && !defined(OPENSSL_CPUID_OBJ)
  654. void OPENSSL_cpuid_setup(void) {}
  655. #endif
  656. #if (defined(_WIN32) || defined(__CYGWIN__)) && defined(_WINDLL)
  657. #ifdef __CYGWIN__
  658. /* pick DLL_[PROCESS|THREAD]_[ATTACH|DETACH] definitions */
  659. #include <windows.h>
  660. /* this has side-effect of _WIN32 getting defined, which otherwise
  661. * is mutually exclusive with __CYGWIN__... */
  662. #endif
  663. /* All we really need to do is remove the 'error' state when a thread
  664. * detaches */
  665. BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason,
  666. LPVOID lpvReserved)
  667. {
  668. switch(fdwReason)
  669. {
  670. case DLL_PROCESS_ATTACH:
  671. OPENSSL_cpuid_setup();
  672. #if defined(_WIN32_WINNT)
  673. {
  674. IMAGE_DOS_HEADER *dos_header = (IMAGE_DOS_HEADER *)hinstDLL;
  675. IMAGE_NT_HEADERS *nt_headers;
  676. if (dos_header->e_magic==IMAGE_DOS_SIGNATURE)
  677. {
  678. nt_headers = (IMAGE_NT_HEADERS *)((char *)dos_header
  679. + dos_header->e_lfanew);
  680. if (nt_headers->Signature==IMAGE_NT_SIGNATURE &&
  681. hinstDLL!=(HINSTANCE)(nt_headers->OptionalHeader.ImageBase))
  682. OPENSSL_NONPIC_relocated=1;
  683. }
  684. }
  685. #endif
  686. break;
  687. case DLL_THREAD_ATTACH:
  688. break;
  689. case DLL_THREAD_DETACH:
  690. break;
  691. case DLL_PROCESS_DETACH:
  692. break;
  693. }
  694. return(TRUE);
  695. }
  696. #endif
  697. #if defined(_WIN32) && !defined(__CYGWIN__)
  698. #include <tchar.h>
  699. #include <signal.h>
  700. #ifdef __WATCOMC__
  701. #if defined(_UNICODE) || defined(__UNICODE__)
  702. #define _vsntprintf _vsnwprintf
  703. #else
  704. #define _vsntprintf _vsnprintf
  705. #endif
  706. #endif
  707. #ifdef _MSC_VER
  708. #define alloca _alloca
  709. #endif
  710. #if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
  711. int OPENSSL_isservice(void)
  712. { HWINSTA h;
  713. DWORD len;
  714. WCHAR *name;
  715. static union { void *p; int (*f)(void); } _OPENSSL_isservice = { NULL };
  716. if (_OPENSSL_isservice.p == NULL) {
  717. HANDLE h = GetModuleHandle(NULL);
  718. if (h != NULL)
  719. _OPENSSL_isservice.p = GetProcAddress(h,"_OPENSSL_isservice");
  720. if (_OPENSSL_isservice.p == NULL)
  721. _OPENSSL_isservice.p = (void *)-1;
  722. }
  723. if (_OPENSSL_isservice.p != (void *)-1)
  724. return (*_OPENSSL_isservice.f)();
  725. (void)GetDesktopWindow(); /* return value is ignored */
  726. h = GetProcessWindowStation();
  727. if (h==NULL) return -1;
  728. if (GetUserObjectInformationW (h,UOI_NAME,NULL,0,&len) ||
  729. GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  730. return -1;
  731. if (len>512) return -1; /* paranoia */
  732. len++,len&=~1; /* paranoia */
  733. name=(WCHAR *)alloca(len+sizeof(WCHAR));
  734. if (!GetUserObjectInformationW (h,UOI_NAME,name,len,&len))
  735. return -1;
  736. len++,len&=~1; /* paranoia */
  737. name[len/sizeof(WCHAR)]=L'\0'; /* paranoia */
  738. #if 1
  739. /* This doesn't cover "interactive" services [working with real
  740. * WinSta0's] nor programs started non-interactively by Task
  741. * Scheduler [those are working with SAWinSta]. */
  742. if (wcsstr(name,L"Service-0x")) return 1;
  743. #else
  744. /* This covers all non-interactive programs such as services. */
  745. if (!wcsstr(name,L"WinSta0")) return 1;
  746. #endif
  747. else return 0;
  748. }
  749. #else
  750. int OPENSSL_isservice(void) { return 0; }
  751. #endif
  752. void OPENSSL_showfatal (const char *fmta,...)
  753. { va_list ap;
  754. TCHAR buf[256];
  755. const TCHAR *fmt;
  756. #ifdef STD_ERROR_HANDLE /* what a dirty trick! */
  757. HANDLE h;
  758. if ((h=GetStdHandle(STD_ERROR_HANDLE)) != NULL &&
  759. GetFileType(h)!=FILE_TYPE_UNKNOWN)
  760. { /* must be console application */
  761. va_start (ap,fmta);
  762. vfprintf (stderr,fmta,ap);
  763. va_end (ap);
  764. return;
  765. }
  766. #endif
  767. if (sizeof(TCHAR)==sizeof(char))
  768. fmt=(const TCHAR *)fmta;
  769. else do
  770. { int keepgoing;
  771. size_t len_0=strlen(fmta)+1,i;
  772. WCHAR *fmtw;
  773. fmtw = (WCHAR *)alloca(len_0*sizeof(WCHAR));
  774. if (fmtw == NULL) { fmt=(const TCHAR *)L"no stack?"; break; }
  775. #ifndef OPENSSL_NO_MULTIBYTE
  776. if (!MultiByteToWideChar(CP_ACP,0,fmta,len_0,fmtw,len_0))
  777. #endif
  778. for (i=0;i<len_0;i++) fmtw[i]=(WCHAR)fmta[i];
  779. for (i=0;i<len_0;i++)
  780. { if (fmtw[i]==L'%') do
  781. { keepgoing=0;
  782. switch (fmtw[i+1])
  783. { case L'0': case L'1': case L'2': case L'3': case L'4':
  784. case L'5': case L'6': case L'7': case L'8': case L'9':
  785. case L'.': case L'*':
  786. case L'-': i++; keepgoing=1; break;
  787. case L's': fmtw[i+1]=L'S'; break;
  788. case L'S': fmtw[i+1]=L's'; break;
  789. case L'c': fmtw[i+1]=L'C'; break;
  790. case L'C': fmtw[i+1]=L'c'; break;
  791. }
  792. } while (keepgoing);
  793. }
  794. fmt = (const TCHAR *)fmtw;
  795. } while (0);
  796. va_start (ap,fmta);
  797. _vsntprintf (buf,sizeof(buf)/sizeof(TCHAR)-1,fmt,ap);
  798. buf [sizeof(buf)/sizeof(TCHAR)-1] = _T('\0');
  799. va_end (ap);
  800. #if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
  801. /* this -------------v--- guards NT-specific calls */
  802. if (GetVersion() < 0x80000000 && OPENSSL_isservice() > 0)
  803. { HANDLE h = RegisterEventSource(0,_T("OPENSSL"));
  804. const TCHAR *pmsg=buf;
  805. ReportEvent(h,EVENTLOG_ERROR_TYPE,0,0,0,1,0,&pmsg,0);
  806. DeregisterEventSource(h);
  807. }
  808. else
  809. #endif
  810. MessageBox (NULL,buf,_T("OpenSSL: FATAL"),MB_OK|MB_ICONSTOP);
  811. }
  812. #else
  813. void OPENSSL_showfatal (const char *fmta,...)
  814. { va_list ap;
  815. va_start (ap,fmta);
  816. vfprintf (stderr,fmta,ap);
  817. va_end (ap);
  818. }
  819. int OPENSSL_isservice (void) { return 0; }
  820. #endif
  821. void OpenSSLDie(const char *file,int line,const char *assertion)
  822. {
  823. OPENSSL_showfatal(
  824. "%s(%d): OpenSSL internal error, assertion failed: %s\n",
  825. file,line,assertion);
  826. #if !defined(_WIN32) || defined(__CYGWIN__)
  827. abort();
  828. #else
  829. /* Win32 abort() customarily shows a dialog, but we just did that... */
  830. raise(SIGABRT);
  831. _exit(3);
  832. #endif
  833. }
  834. void *OPENSSL_stderr(void) { return stderr; }
  835. int CRYPTO_memcmp(const void *in_a, const void *in_b, size_t len)
  836. {
  837. size_t i;
  838. const unsigned char *a = in_a;
  839. const unsigned char *b = in_b;
  840. unsigned char x = 0;
  841. for (i = 0; i < len; i++)
  842. x |= a[i] ^ b[i];
  843. return x;
  844. }