cryptlib.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  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. * 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. #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(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. * and 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_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_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. locking_callback=func;
  377. }
  378. void CRYPTO_set_add_lock_callback(int (*func)(int *num,int mount,int type,
  379. const char *file,int line))
  380. {
  381. add_lock_callback=func;
  382. }
  383. /* the memset() here and in set_pointer() seem overkill, but for the sake of
  384. * CRYPTO_THREADID_cmp() this avoids any platform silliness that might cause two
  385. * "equal" THREADID structs to not be memcmp()-identical. */
  386. void CRYPTO_THREADID_set_numeric(CRYPTO_THREADID *id, unsigned long val)
  387. {
  388. memset(id, 0, sizeof(*id));
  389. id->val = val;
  390. }
  391. static const unsigned char hash_coeffs[] = { 3, 5, 7, 11, 13, 17, 19, 23 };
  392. void CRYPTO_THREADID_set_pointer(CRYPTO_THREADID *id, void *ptr)
  393. {
  394. unsigned char *dest = (void *)&id->val;
  395. unsigned int accum = 0;
  396. unsigned char dnum = sizeof(id->val);
  397. memset(id, 0, sizeof(*id));
  398. id->ptr = ptr;
  399. if (sizeof(id->val) >= sizeof(id->ptr))
  400. {
  401. /* 'ptr' can be embedded in 'val' without loss of uniqueness */
  402. id->val = (unsigned long)id->ptr;
  403. return;
  404. }
  405. /* hash ptr ==> val. Each byte of 'val' gets the mod-256 total of a
  406. * linear function over the bytes in 'ptr', the co-efficients of which
  407. * are a sequence of low-primes (hash_coeffs is an 8-element cycle) -
  408. * the starting prime for the sequence varies for each byte of 'val'
  409. * (unique polynomials unless pointers are >64-bit). For added spice,
  410. * the totals accumulate rather than restarting from zero, and the index
  411. * of the 'val' byte is added each time (position dependence). If I was
  412. * a black-belt, I'd scan big-endian pointers in reverse to give
  413. * low-order bits more play, but this isn't crypto and I'd prefer nobody
  414. * mistake it as such. Plus I'm lazy. */
  415. while (dnum--)
  416. {
  417. const unsigned char *src = (void *)&id->ptr;
  418. unsigned char snum = sizeof(id->ptr);
  419. while (snum--)
  420. accum += *(src++) * hash_coeffs[(snum + dnum) & 7];
  421. accum += dnum;
  422. *(dest++) = accum & 255;
  423. }
  424. }
  425. int CRYPTO_THREADID_set_callback(void (*func)(CRYPTO_THREADID *))
  426. {
  427. if (threadid_callback)
  428. return 0;
  429. threadid_callback = func;
  430. return 1;
  431. }
  432. void (*CRYPTO_THREADID_get_callback(void))(CRYPTO_THREADID *)
  433. {
  434. return threadid_callback;
  435. }
  436. void CRYPTO_THREADID_current(CRYPTO_THREADID *id)
  437. {
  438. if (threadid_callback)
  439. {
  440. threadid_callback(id);
  441. return;
  442. }
  443. #ifndef OPENSSL_NO_DEPRECATED
  444. /* If the deprecated callback was set, fall back to that */
  445. if (id_callback)
  446. {
  447. CRYPTO_THREADID_set_numeric(id, id_callback());
  448. return;
  449. }
  450. #endif
  451. /* Else pick a backup */
  452. #ifdef OPENSSL_SYS_WIN16
  453. CRYPTO_THREADID_set_numeric(id, (unsigned long)GetCurrentTask());
  454. #elif defined(OPENSSL_SYS_WIN32)
  455. CRYPTO_THREADID_set_numeric(id, (unsigned long)GetCurrentThreadId());
  456. #elif defined(OPENSSL_SYS_BEOS)
  457. CRYPTO_THREADID_set_numeric(id, (unsigned long)find_thread(NULL));
  458. #else
  459. /* For everything else, default to using the address of 'errno' */
  460. CRYPTO_THREADID_set_pointer(id, &errno);
  461. #endif
  462. }
  463. int CRYPTO_THREADID_cmp(const CRYPTO_THREADID *a, const CRYPTO_THREADID *b)
  464. {
  465. return memcmp(a, b, sizeof(*a));
  466. }
  467. void CRYPTO_THREADID_cpy(CRYPTO_THREADID *dest, const CRYPTO_THREADID *src)
  468. {
  469. memcpy(dest, src, sizeof(*src));
  470. }
  471. unsigned long CRYPTO_THREADID_hash(const CRYPTO_THREADID *id)
  472. {
  473. return id->val;
  474. }
  475. #ifndef OPENSSL_NO_DEPRECATED
  476. unsigned long (*CRYPTO_get_id_callback(void))(void)
  477. {
  478. return(id_callback);
  479. }
  480. void CRYPTO_set_id_callback(unsigned long (*func)(void))
  481. {
  482. id_callback=func;
  483. }
  484. unsigned long CRYPTO_thread_id(void)
  485. {
  486. unsigned long ret=0;
  487. if (id_callback == NULL)
  488. {
  489. #ifdef OPENSSL_SYS_WIN16
  490. ret=(unsigned long)GetCurrentTask();
  491. #elif defined(OPENSSL_SYS_WIN32)
  492. ret=(unsigned long)GetCurrentThreadId();
  493. #elif defined(GETPID_IS_MEANINGLESS)
  494. ret=1L;
  495. #elif defined(OPENSSL_SYS_BEOS)
  496. ret=(unsigned long)find_thread(NULL);
  497. #else
  498. ret=(unsigned long)getpid();
  499. #endif
  500. }
  501. else
  502. ret=id_callback();
  503. return(ret);
  504. }
  505. #endif
  506. void CRYPTO_lock(int mode, int type, const char *file, int line)
  507. {
  508. #ifdef LOCK_DEBUG
  509. {
  510. CRYPTO_THREADID id;
  511. char *rw_text,*operation_text;
  512. if (mode & CRYPTO_LOCK)
  513. operation_text="lock ";
  514. else if (mode & CRYPTO_UNLOCK)
  515. operation_text="unlock";
  516. else
  517. operation_text="ERROR ";
  518. if (mode & CRYPTO_READ)
  519. rw_text="r";
  520. else if (mode & CRYPTO_WRITE)
  521. rw_text="w";
  522. else
  523. rw_text="ERROR";
  524. CRYPTO_THREADID_current(&id);
  525. fprintf(stderr,"lock:%08lx:(%s)%s %-18s %s:%d\n",
  526. CRYPTO_THREADID_hash(&id), rw_text, operation_text,
  527. CRYPTO_get_lock_name(type), file, line);
  528. }
  529. #endif
  530. if (type < 0)
  531. {
  532. if (dynlock_lock_callback != NULL)
  533. {
  534. struct CRYPTO_dynlock_value *pointer
  535. = CRYPTO_get_dynlock_value(type);
  536. OPENSSL_assert(pointer != NULL);
  537. dynlock_lock_callback(mode, pointer, file, line);
  538. CRYPTO_destroy_dynlockid(type);
  539. }
  540. }
  541. else
  542. if (locking_callback != NULL)
  543. locking_callback(mode,type,file,line);
  544. }
  545. int CRYPTO_add_lock(int *pointer, int amount, int type, const char *file,
  546. int line)
  547. {
  548. int ret = 0;
  549. if (add_lock_callback != NULL)
  550. {
  551. #ifdef LOCK_DEBUG
  552. int before= *pointer;
  553. #endif
  554. ret=add_lock_callback(pointer,amount,type,file,line);
  555. #ifdef LOCK_DEBUG
  556. {
  557. CRYPTO_THREADID id;
  558. CRYPTO_THREADID_current(&id);
  559. fprintf(stderr,"ladd:%08lx:%2d+%2d->%2d %-18s %s:%d\n",
  560. CRYPTO_THREADID_hash(&id), before,amount,ret,
  561. CRYPTO_get_lock_name(type),
  562. file,line);
  563. }
  564. #endif
  565. }
  566. else
  567. {
  568. CRYPTO_lock(CRYPTO_LOCK|CRYPTO_WRITE,type,file,line);
  569. ret= *pointer+amount;
  570. #ifdef LOCK_DEBUG
  571. {
  572. CRYPTO_THREADID id;
  573. CRYPTO_THREADID_current(&id);
  574. fprintf(stderr,"ladd:%08lx:%2d+%2d->%2d %-18s %s:%d\n",
  575. CRYPTO_THREADID_hash(&id),
  576. *pointer,amount,ret,
  577. CRYPTO_get_lock_name(type),
  578. file,line);
  579. }
  580. #endif
  581. *pointer=ret;
  582. CRYPTO_lock(CRYPTO_UNLOCK|CRYPTO_WRITE,type,file,line);
  583. }
  584. return(ret);
  585. }
  586. const char *CRYPTO_get_lock_name(int type)
  587. {
  588. if (type < 0)
  589. return("dynamic");
  590. else if (type < CRYPTO_NUM_LOCKS)
  591. return(lock_names[type]);
  592. else if (type-CRYPTO_NUM_LOCKS > sk_STRING_num(app_locks))
  593. return("ERROR");
  594. else
  595. return(sk_STRING_value(app_locks,type-CRYPTO_NUM_LOCKS));
  596. }
  597. #if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
  598. defined(__INTEL__) || \
  599. defined(__x86_64) || defined(__x86_64__) || defined(_M_AMD64)
  600. unsigned long OPENSSL_ia32cap_P=0;
  601. unsigned long *OPENSSL_ia32cap_loc(void) { return &OPENSSL_ia32cap_P; }
  602. #if defined(OPENSSL_CPUID_OBJ) && !defined(OPENSSL_NO_ASM) && !defined(I386_ONLY)
  603. #define OPENSSL_CPUID_SETUP
  604. void OPENSSL_cpuid_setup(void)
  605. { static int trigger=0;
  606. unsigned long OPENSSL_ia32_cpuid(void);
  607. char *env;
  608. if (trigger) return;
  609. trigger=1;
  610. if ((env=getenv("OPENSSL_ia32cap")))
  611. OPENSSL_ia32cap_P = strtoul(env,NULL,0)|(1<<10);
  612. else
  613. OPENSSL_ia32cap_P = OPENSSL_ia32_cpuid()|(1<<10);
  614. /*
  615. * |(1<<10) sets a reserved bit to signal that variable
  616. * was initialized already... This is to avoid interference
  617. * with cpuid snippets in ELF .init segment.
  618. */
  619. }
  620. #endif
  621. #else
  622. unsigned long *OPENSSL_ia32cap_loc(void) { return NULL; }
  623. #endif
  624. int OPENSSL_NONPIC_relocated = 0;
  625. #if !defined(OPENSSL_CPUID_SETUP) && !defined(OPENSSL_CPUID_OBJ)
  626. void OPENSSL_cpuid_setup(void) {}
  627. #endif
  628. #if (defined(_WIN32) || defined(__CYGWIN__)) && defined(_WINDLL)
  629. #ifdef __CYGWIN__
  630. /* pick DLL_[PROCESS|THREAD]_[ATTACH|DETACH] definitions */
  631. #include <windows.h>
  632. #endif
  633. /* All we really need to do is remove the 'error' state when a thread
  634. * detaches */
  635. BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason,
  636. LPVOID lpvReserved)
  637. {
  638. switch(fdwReason)
  639. {
  640. case DLL_PROCESS_ATTACH:
  641. OPENSSL_cpuid_setup();
  642. #if defined(_WIN32_WINNT)
  643. {
  644. IMAGE_DOS_HEADER *dos_header = (IMAGE_DOS_HEADER *)hinstDLL;
  645. IMAGE_NT_HEADERS *nt_headers;
  646. if (dos_header->e_magic==IMAGE_DOS_SIGNATURE)
  647. {
  648. nt_headers = (IMAGE_NT_HEADERS *)((char *)dos_header
  649. + dos_header->e_lfanew);
  650. if (nt_headers->Signature==IMAGE_NT_SIGNATURE &&
  651. hinstDLL!=(HINSTANCE)(nt_headers->OptionalHeader.ImageBase))
  652. OPENSSL_NONPIC_relocated=1;
  653. }
  654. }
  655. #endif
  656. break;
  657. case DLL_THREAD_ATTACH:
  658. break;
  659. case DLL_THREAD_DETACH:
  660. ERR_remove_state(0);
  661. break;
  662. case DLL_PROCESS_DETACH:
  663. break;
  664. }
  665. return(TRUE);
  666. }
  667. #endif
  668. #if defined(_WIN32) && !defined(__CYGWIN__)
  669. #include <tchar.h>
  670. #if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
  671. int OPENSSL_isservice(void)
  672. { HWINSTA h;
  673. DWORD len;
  674. WCHAR *name;
  675. (void)GetDesktopWindow(); /* return value is ignored */
  676. h = GetProcessWindowStation();
  677. if (h==NULL) return -1;
  678. if (GetUserObjectInformationW (h,UOI_NAME,NULL,0,&len) ||
  679. GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  680. return -1;
  681. if (len>512) return -1; /* paranoia */
  682. len++,len&=~1; /* paranoia */
  683. #ifdef _MSC_VER
  684. name=(WCHAR *)_alloca(len+sizeof(WCHAR));
  685. #else
  686. name=(WCHAR *)alloca(len+sizeof(WCHAR));
  687. #endif
  688. if (!GetUserObjectInformationW (h,UOI_NAME,name,len,&len))
  689. return -1;
  690. len++,len&=~1; /* paranoia */
  691. name[len/sizeof(WCHAR)]=L'\0'; /* paranoia */
  692. #if 1
  693. /* This doesn't cover "interactive" services [working with real
  694. * WinSta0's] nor programs started non-interactively by Task
  695. * Scheduler [those are working with SAWinSta]. */
  696. if (wcsstr(name,L"Service-0x")) return 1;
  697. #else
  698. /* This covers all non-interactive programs such as services. */
  699. if (!wcsstr(name,L"WinSta0")) return 1;
  700. #endif
  701. else return 0;
  702. }
  703. #else
  704. int OPENSSL_isservice(void) { return 0; }
  705. #endif
  706. void OPENSSL_showfatal (const char *fmta,...)
  707. { va_list ap;
  708. TCHAR buf[256];
  709. const TCHAR *fmt;
  710. #ifdef STD_ERROR_HANDLE /* what a dirty trick! */
  711. HANDLE h;
  712. if ((h=GetStdHandle(STD_ERROR_HANDLE)) != NULL &&
  713. GetFileType(h)!=FILE_TYPE_UNKNOWN)
  714. { /* must be console application */
  715. va_start (ap,fmta);
  716. vfprintf (stderr,fmta,ap);
  717. va_end (ap);
  718. return;
  719. }
  720. #endif
  721. if (sizeof(TCHAR)==sizeof(char))
  722. fmt=(const TCHAR *)fmta;
  723. else do
  724. { int keepgoing;
  725. size_t len_0=strlen(fmta)+1,i;
  726. WCHAR *fmtw;
  727. #ifdef _MSC_VER
  728. fmtw = (WCHAR *)_alloca (len_0*sizeof(WCHAR));
  729. #else
  730. fmtw = (WCHAR *)alloca (len_0*sizeof(WCHAR));
  731. #endif
  732. if (fmtw == NULL) { fmt=(const TCHAR *)L"no stack?"; break; }
  733. #ifndef OPENSSL_NO_MULTIBYTE
  734. if (!MultiByteToWideChar(CP_ACP,0,fmta,len_0,fmtw,len_0))
  735. #endif
  736. for (i=0;i<len_0;i++) fmtw[i]=(WCHAR)fmta[i];
  737. for (i=0;i<len_0;i++)
  738. { if (fmtw[i]==L'%') do
  739. { keepgoing=0;
  740. switch (fmtw[i+1])
  741. { case L'0': case L'1': case L'2': case L'3': case L'4':
  742. case L'5': case L'6': case L'7': case L'8': case L'9':
  743. case L'.': case L'*':
  744. case L'-': i++; keepgoing=1; break;
  745. case L's': fmtw[i+1]=L'S'; break;
  746. case L'S': fmtw[i+1]=L's'; break;
  747. case L'c': fmtw[i+1]=L'C'; break;
  748. case L'C': fmtw[i+1]=L'c'; break;
  749. }
  750. } while (keepgoing);
  751. }
  752. fmt = (const TCHAR *)fmtw;
  753. } while (0);
  754. va_start (ap,fmta);
  755. _vsntprintf (buf,sizeof(buf)/sizeof(TCHAR)-1,fmt,ap);
  756. buf [sizeof(buf)/sizeof(TCHAR)-1] = _T('\0');
  757. va_end (ap);
  758. #if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
  759. /* this -------------v--- guards NT-specific calls */
  760. if (GetVersion() < 0x80000000 && OPENSSL_isservice())
  761. { HANDLE h = RegisterEventSource(0,_T("OPENSSL"));
  762. const TCHAR *pmsg=buf;
  763. ReportEvent(h,EVENTLOG_ERROR_TYPE,0,0,0,1,0,&pmsg,0);
  764. DeregisterEventSource(h);
  765. }
  766. else
  767. #endif
  768. MessageBox (NULL,buf,_T("OpenSSL: FATAL"),MB_OK|MB_ICONSTOP);
  769. }
  770. #else
  771. void OPENSSL_showfatal (const char *fmta,...)
  772. { va_list ap;
  773. va_start (ap,fmta);
  774. vfprintf (stderr,fmta,ap);
  775. va_end (ap);
  776. }
  777. int OPENSSL_isservice (void) { return 0; }
  778. #endif
  779. void OpenSSLDie(const char *file,int line,const char *assertion)
  780. {
  781. OPENSSL_showfatal(
  782. "%s(%d): OpenSSL internal error, assertion failed: %s\n",
  783. file,line,assertion);
  784. abort();
  785. }
  786. void *OPENSSL_stderr(void) { return stderr; }