Convert thread stop handling into a publish/subscribe model
[openssl.git] / crypto / init.c
1 /*
2  * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "e_os.h"
11 #include "internal/cryptlib_int.h"
12 #include <openssl/err.h>
13 #include "internal/rand_int.h"
14 #include "internal/bio.h"
15 #include <openssl/evp.h>
16 #include "internal/evp_int.h"
17 #include "internal/conf.h"
18 #include "internal/async.h"
19 #include "internal/engine.h"
20 #include "internal/comp.h"
21 #include "internal/err.h"
22 #include "internal/err_int.h"
23 #include "internal/objects.h"
24 #include <stdlib.h>
25 #include <assert.h>
26 #include "internal/thread_once.h"
27 #include "internal/dso_conf.h"
28 #include "internal/dso.h"
29 #include "internal/store.h"
30 #include <openssl/trace.h>
31
32 static int stopped = 0;
33
34 typedef struct thread_event_handler_st THREAD_EVENT_HANDLER;
35 struct thread_event_handler_st {
36     OPENSSL_CTX *ctx;
37     ossl_thread_stop_handler_fn handfn;
38     THREAD_EVENT_HANDLER *next;
39 };
40
41 /*
42  * Since per-thread-specific-data destructors are not universally
43  * available, i.e. not on Windows, only below CRYPTO_THREAD_LOCAL key
44  * is assumed to have destructor associated. And then an effort is made
45  * to call this single destructor on non-pthread platform[s].
46  *
47  * Initial value is "impossible". It is used as guard value to shortcut
48  * destructor for threads terminating before libcrypto is initialized or
49  * after it's de-initialized. Access to the key doesn't have to be
50  * serialized for the said threads, because they didn't use libcrypto
51  * and it doesn't matter if they pick "impossible" or derefernce real
52  * key value and pull NULL past initialization in the first thread that
53  * intends to use libcrypto.
54  */
55 static union {
56     long sane;
57     CRYPTO_THREAD_LOCAL value;
58 } destructor_key = { -1 };
59
60 static void ossl_init_thread_stop(THREAD_EVENT_HANDLER **hands);
61
62 static void ossl_init_thread_destructor(void *hands)
63 {
64     ossl_init_thread_stop((THREAD_EVENT_HANDLER **)hands);
65 }
66
67 static THREAD_EVENT_HANDLER **ossl_init_get_thread_local(int alloc)
68 {
69     THREAD_EVENT_HANDLER **hands =
70         CRYPTO_THREAD_get_local(&destructor_key.value);
71
72     if (alloc) {
73         if (hands == NULL
74             && (hands = OPENSSL_zalloc(sizeof(*hands))) != NULL
75             && !CRYPTO_THREAD_set_local(&destructor_key.value, hands)) {
76             OPENSSL_free(hands);
77             return NULL;
78         }
79     } else {
80         CRYPTO_THREAD_set_local(&destructor_key.value, NULL);
81     }
82
83     return hands;
84 }
85
86 typedef struct ossl_init_stop_st OPENSSL_INIT_STOP;
87 struct ossl_init_stop_st {
88     void (*handler)(void);
89     OPENSSL_INIT_STOP *next;
90 };
91
92 static OPENSSL_INIT_STOP *stop_handlers = NULL;
93 static CRYPTO_RWLOCK *init_lock = NULL;
94
95 static CRYPTO_ONCE base = CRYPTO_ONCE_STATIC_INIT;
96 static int base_inited = 0;
97 DEFINE_RUN_ONCE_STATIC(ossl_init_base)
98 {
99     CRYPTO_THREAD_LOCAL key;
100
101     if (ossl_trace_init() == 0)
102         return 0;
103
104     OSSL_TRACE(INIT, "ossl_init_base: setting up stop handlers\n");
105 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
106     ossl_malloc_setup_failures();
107 #endif
108     if (!CRYPTO_THREAD_init_local(&key, ossl_init_thread_destructor))
109         return 0;
110     if ((init_lock = CRYPTO_THREAD_lock_new()) == NULL)
111         goto err;
112     OPENSSL_cpuid_setup();
113
114     destructor_key.value = key;
115     base_inited = 1;
116     return 1;
117
118 err:
119     OSSL_TRACE(INIT, "ossl_init_base failed!\n");
120     CRYPTO_THREAD_lock_free(init_lock);
121     init_lock = NULL;
122
123     CRYPTO_THREAD_cleanup_local(&key);
124     return 0;
125 }
126
127 static CRYPTO_ONCE register_atexit = CRYPTO_ONCE_STATIC_INIT;
128 #if !defined(OPENSSL_SYS_UEFI) && defined(_WIN32)
129 static int win32atexit(void)
130 {
131     OPENSSL_cleanup();
132     return 0;
133 }
134 #endif
135
136 DEFINE_RUN_ONCE_STATIC(ossl_init_register_atexit)
137 {
138 #ifdef OPENSSL_INIT_DEBUG
139     fprintf(stderr, "OPENSSL_INIT: ossl_init_register_atexit()\n");
140 #endif
141 #ifndef OPENSSL_SYS_UEFI
142 # ifdef _WIN32
143     /* We use _onexit() in preference because it gets called on DLL unload */
144     if (_onexit(win32atexit) == NULL)
145         return 0;
146 # else
147     if (atexit(OPENSSL_cleanup) != 0)
148         return 0;
149 # endif
150 #endif
151
152     return 1;
153 }
154
155 DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_register_atexit,
156                            ossl_init_register_atexit)
157 {
158 #ifdef OPENSSL_INIT_DEBUG
159     fprintf(stderr, "OPENSSL_INIT: ossl_init_no_register_atexit ok!\n");
160 #endif
161     /* Do nothing in this case */
162     return 1;
163 }
164
165 static CRYPTO_ONCE load_crypto_nodelete = CRYPTO_ONCE_STATIC_INIT;
166 DEFINE_RUN_ONCE_STATIC(ossl_init_load_crypto_nodelete)
167 {
168     OSSL_TRACE(INIT, "ossl_init_load_crypto_nodelete()\n");
169
170 #if !defined(OPENSSL_USE_NODELETE) \
171     && !defined(OPENSSL_NO_PINSHARED)
172 # if defined(DSO_WIN32) && !defined(_WIN32_WCE)
173     {
174         HMODULE handle = NULL;
175         BOOL ret;
176
177         /* We don't use the DSO route for WIN32 because there is a better way */
178         ret = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
179                                 | GET_MODULE_HANDLE_EX_FLAG_PIN,
180                                 (void *)&base_inited, &handle);
181
182         OSSL_TRACE1(INIT,
183                     "ossl_init_load_crypto_nodelete: "
184                     "obtained DSO reference? %s\n",
185                     (ret == TRUE ? "No!" : "Yes."));
186         return (ret == TRUE) ? 1 : 0;
187     }
188 # elif !defined(DSO_NONE)
189     /*
190      * Deliberately leak a reference to ourselves. This will force the library
191      * to remain loaded until the atexit() handler is run at process exit.
192      */
193     {
194         DSO *dso;
195         void *err;
196
197         if (!err_shelve_state(&err))
198             return 0;
199
200         dso = DSO_dsobyaddr(&base_inited, DSO_FLAG_NO_UNLOAD_ON_FREE);
201         /*
202          * In case of No!, it is uncertain our exit()-handlers can still be
203          * called. After dlclose() the whole library might have been unloaded
204          * already.
205          */
206         OSSL_TRACE1(INIT, "obtained DSO reference? %s\n",
207                     (dso == NULL ? "No!" : "Yes."));
208         DSO_free(dso);
209         err_unshelve_state(err);
210     }
211 # endif
212 #endif
213
214     return 1;
215 }
216
217 static CRYPTO_ONCE load_crypto_strings = CRYPTO_ONCE_STATIC_INIT;
218 static int load_crypto_strings_inited = 0;
219 DEFINE_RUN_ONCE_STATIC(ossl_init_load_crypto_strings)
220 {
221     int ret = 1;
222     /*
223      * OPENSSL_NO_AUTOERRINIT is provided here to prevent at compile time
224      * pulling in all the error strings during static linking
225      */
226 #if !defined(OPENSSL_NO_ERR) && !defined(OPENSSL_NO_AUTOERRINIT)
227     OSSL_TRACE(INIT, "err_load_crypto_strings_int()\n");
228     ret = err_load_crypto_strings_int();
229     load_crypto_strings_inited = 1;
230 #endif
231     return ret;
232 }
233
234 DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_load_crypto_strings,
235                            ossl_init_load_crypto_strings)
236 {
237     /* Do nothing in this case */
238     return 1;
239 }
240
241 static CRYPTO_ONCE add_all_ciphers = CRYPTO_ONCE_STATIC_INIT;
242 DEFINE_RUN_ONCE_STATIC(ossl_init_add_all_ciphers)
243 {
244     /*
245      * OPENSSL_NO_AUTOALGINIT is provided here to prevent at compile time
246      * pulling in all the ciphers during static linking
247      */
248 #ifndef OPENSSL_NO_AUTOALGINIT
249     OSSL_TRACE(INIT, "openssl_add_all_ciphers_int()\n");
250     openssl_add_all_ciphers_int();
251 #endif
252     return 1;
253 }
254
255 DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_add_all_ciphers,
256                            ossl_init_add_all_ciphers)
257 {
258     /* Do nothing */
259     return 1;
260 }
261
262 static CRYPTO_ONCE add_all_digests = CRYPTO_ONCE_STATIC_INIT;
263 DEFINE_RUN_ONCE_STATIC(ossl_init_add_all_digests)
264 {
265     /*
266      * OPENSSL_NO_AUTOALGINIT is provided here to prevent at compile time
267      * pulling in all the ciphers during static linking
268      */
269 #ifndef OPENSSL_NO_AUTOALGINIT
270     OSSL_TRACE(INIT, "openssl_add_all_digests()\n");
271     openssl_add_all_digests_int();
272 #endif
273     return 1;
274 }
275
276 DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_add_all_digests,
277                            ossl_init_add_all_digests)
278 {
279     /* Do nothing */
280     return 1;
281 }
282
283 static CRYPTO_ONCE add_all_macs = CRYPTO_ONCE_STATIC_INIT;
284 DEFINE_RUN_ONCE_STATIC(ossl_init_add_all_macs)
285 {
286     /*
287      * OPENSSL_NO_AUTOALGINIT is provided here to prevent at compile time
288      * pulling in all the macs during static linking
289      */
290 #ifndef OPENSSL_NO_AUTOALGINIT
291     OSSL_TRACE(INIT, "openssl_add_all_macs_int()\n");
292     openssl_add_all_macs_int();
293 #endif
294     return 1;
295 }
296
297 DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_add_all_macs, ossl_init_add_all_macs)
298 {
299     /* Do nothing */
300     return 1;
301 }
302
303 static CRYPTO_ONCE add_all_kdfs = CRYPTO_ONCE_STATIC_INIT;
304 DEFINE_RUN_ONCE_STATIC(ossl_init_add_all_kdfs)
305 {
306     /*
307      * OPENSSL_NO_AUTOALGINIT is provided here to prevent at compile time
308      * pulling in all the macs during static linking
309      */
310 #ifndef OPENSSL_NO_AUTOALGINIT
311     OSSL_TRACE(INIT, "openssl_add_all_kdfs_int()\n");
312     openssl_add_all_kdfs_int();
313 #endif
314     return 1;
315 }
316
317 DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_add_all_kdfs, ossl_init_add_all_kdfs)
318 {
319     /* Do nothing */
320     return 1;
321 }
322
323 static CRYPTO_ONCE config = CRYPTO_ONCE_STATIC_INIT;
324 static int config_inited = 0;
325 static const OPENSSL_INIT_SETTINGS *conf_settings = NULL;
326 DEFINE_RUN_ONCE_STATIC(ossl_init_config)
327 {
328     int ret = openssl_config_int(conf_settings);
329     config_inited = 1;
330     return ret;
331 }
332 DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_config, ossl_init_config)
333 {
334     OSSL_TRACE(INIT, "openssl_no_config_int()\n");
335     openssl_no_config_int();
336     config_inited = 1;
337     return 1;
338 }
339
340 static CRYPTO_ONCE async = CRYPTO_ONCE_STATIC_INIT;
341 static int async_inited = 0;
342 DEFINE_RUN_ONCE_STATIC(ossl_init_async)
343 {
344     OSSL_TRACE(INIT, "async_init()\n");
345     if (!async_init())
346         return 0;
347     async_inited = 1;
348     return 1;
349 }
350
351 #ifndef OPENSSL_NO_ENGINE
352 static CRYPTO_ONCE engine_openssl = CRYPTO_ONCE_STATIC_INIT;
353 DEFINE_RUN_ONCE_STATIC(ossl_init_engine_openssl)
354 {
355     OSSL_TRACE(INIT, "engine_load_openssl_int()\n");
356     engine_load_openssl_int();
357     return 1;
358 }
359 # ifndef OPENSSL_NO_RDRAND
360 static CRYPTO_ONCE engine_rdrand = CRYPTO_ONCE_STATIC_INIT;
361 DEFINE_RUN_ONCE_STATIC(ossl_init_engine_rdrand)
362 {
363     OSSL_TRACE(INIT, "engine_load_rdrand_int()\n");
364     engine_load_rdrand_int();
365     return 1;
366 }
367 # endif
368 static CRYPTO_ONCE engine_dynamic = CRYPTO_ONCE_STATIC_INIT;
369 DEFINE_RUN_ONCE_STATIC(ossl_init_engine_dynamic)
370 {
371     OSSL_TRACE(INIT, "engine_load_dynamic_int()\n");
372     engine_load_dynamic_int();
373     return 1;
374 }
375 # ifndef OPENSSL_NO_STATIC_ENGINE
376 #  ifndef OPENSSL_NO_DEVCRYPTOENG
377 static CRYPTO_ONCE engine_devcrypto = CRYPTO_ONCE_STATIC_INIT;
378 DEFINE_RUN_ONCE_STATIC(ossl_init_engine_devcrypto)
379 {
380     OSSL_TRACE(INIT, "engine_load_devcrypto_int()\n");
381     engine_load_devcrypto_int();
382     return 1;
383 }
384 #  endif
385 #  if !defined(OPENSSL_NO_PADLOCKENG)
386 static CRYPTO_ONCE engine_padlock = CRYPTO_ONCE_STATIC_INIT;
387 DEFINE_RUN_ONCE_STATIC(ossl_init_engine_padlock)
388 {
389     OSSL_TRACE(INIT, "engine_load_padlock_int()\n");
390     engine_load_padlock_int();
391     return 1;
392 }
393 #  endif
394 #  if defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_NO_CAPIENG)
395 static CRYPTO_ONCE engine_capi = CRYPTO_ONCE_STATIC_INIT;
396 DEFINE_RUN_ONCE_STATIC(ossl_init_engine_capi)
397 {
398     OSSL_TRACE(INIT, "engine_load_capi_int()\n");
399     engine_load_capi_int();
400     return 1;
401 }
402 #  endif
403 #  if !defined(OPENSSL_NO_AFALGENG)
404 static CRYPTO_ONCE engine_afalg = CRYPTO_ONCE_STATIC_INIT;
405 DEFINE_RUN_ONCE_STATIC(ossl_init_engine_afalg)
406 {
407     OSSL_TRACE(INIT, "engine_load_afalg_int()\n");
408     engine_load_afalg_int();
409     return 1;
410 }
411 #  endif
412 # endif
413 #endif
414
415 #ifndef OPENSSL_NO_COMP
416 static CRYPTO_ONCE zlib = CRYPTO_ONCE_STATIC_INIT;
417
418 static int zlib_inited = 0;
419 DEFINE_RUN_ONCE_STATIC(ossl_init_zlib)
420 {
421     /* Do nothing - we need to know about this for the later cleanup */
422     zlib_inited = 1;
423     return 1;
424 }
425 #endif
426
427 static void ossl_init_thread_stop(THREAD_EVENT_HANDLER **hands)
428 {
429     THREAD_EVENT_HANDLER *curr, *prev = NULL;
430
431     /* Can't do much about this */
432     if (hands == NULL)
433         return;
434
435     curr = *hands;
436     while (curr != NULL) {
437         curr->handfn(curr->ctx);
438         prev = curr;
439         curr = curr->next;
440         OPENSSL_free(prev);
441     }
442
443     OPENSSL_free(hands);
444 }
445
446 void OPENSSL_thread_stop(void)
447 {
448     if (destructor_key.sane != -1)
449         ossl_init_thread_stop(ossl_init_get_thread_local(0));
450 }
451
452 int ossl_init_thread_start(OPENSSL_CTX *ctx, ossl_thread_stop_handler_fn handfn)
453 {
454     THREAD_EVENT_HANDLER **hands;
455     THREAD_EVENT_HANDLER *hand;
456
457     if (!OPENSSL_init_crypto(0, NULL))
458         return 0;
459
460     hands = ossl_init_get_thread_local(1);
461
462     if (hands == NULL)
463         return 0;
464
465     hand = OPENSSL_malloc(sizeof(*hand));
466     if (hand == NULL)
467         return 0;
468
469     hand->handfn = handfn;
470     hand->ctx = ctx;
471     hand->next = *hands;
472     *hands = hand;
473
474     return 1;
475 }
476
477 void OPENSSL_cleanup(void)
478 {
479     OPENSSL_INIT_STOP *currhandler, *lasthandler;
480     CRYPTO_THREAD_LOCAL key;
481
482     /*
483      * TODO(3.0): This function needs looking at with a view to moving most/all
484      * of this into onfree handlers in OPENSSL_CTX.
485      */
486
487     /* If we've not been inited then no need to deinit */
488     if (!base_inited)
489         return;
490
491     /* Might be explicitly called and also by atexit */
492     if (stopped)
493         return;
494     stopped = 1;
495
496     /*
497      * Thread stop may not get automatically called by the thread library for
498      * the very last thread in some situations, so call it directly.
499      */
500     ossl_init_thread_stop(ossl_init_get_thread_local(0));
501
502     currhandler = stop_handlers;
503     while (currhandler != NULL) {
504         currhandler->handler();
505         lasthandler = currhandler;
506         currhandler = currhandler->next;
507         OPENSSL_free(lasthandler);
508     }
509     stop_handlers = NULL;
510
511     CRYPTO_THREAD_lock_free(init_lock);
512     init_lock = NULL;
513
514     /*
515      * We assume we are single-threaded for this function, i.e. no race
516      * conditions for the various "*_inited" vars below.
517      */
518
519 #ifndef OPENSSL_NO_COMP
520     if (zlib_inited) {
521         OSSL_TRACE(INIT, "OPENSSL_cleanup: comp_zlib_cleanup_int()\n");
522         comp_zlib_cleanup_int();
523     }
524 #endif
525
526     if (async_inited) {
527         OSSL_TRACE(INIT, "OPENSSL_cleanup: async_deinit()\n");
528         async_deinit();
529     }
530
531     if (load_crypto_strings_inited) {
532         OSSL_TRACE(INIT, "OPENSSL_cleanup: err_free_strings_int()\n");
533         err_free_strings_int();
534     }
535
536     key = destructor_key.value;
537     destructor_key.sane = -1;
538     CRYPTO_THREAD_cleanup_local(&key);
539
540     /*
541      * Note that cleanup order is important:
542      * - rand_cleanup_int could call an ENGINE's RAND cleanup function so
543      * must be called before engine_cleanup_int()
544      * - ENGINEs use CRYPTO_EX_DATA and therefore, must be cleaned up
545      * before the ex data handlers are wiped during default openssl_ctx deinit.
546      * - conf_modules_free_int() can end up in ENGINE code so must be called
547      * before engine_cleanup_int()
548      * - ENGINEs and additional EVP algorithms might use added OIDs names so
549      * obj_cleanup_int() must be called last
550      */
551     OSSL_TRACE(INIT, "OPENSSL_cleanup: rand_cleanup_int()\n");
552     rand_cleanup_int();
553
554     OSSL_TRACE(INIT, "OPENSSL_cleanup: conf_modules_free_int()\n");
555     conf_modules_free_int();
556
557 #ifndef OPENSSL_NO_ENGINE
558     OSSL_TRACE(INIT, "OPENSSL_cleanup: engine_cleanup_int()\n");
559     engine_cleanup_int();
560 #endif
561     OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_store_cleanup_int()\n");
562     ossl_store_cleanup_int();
563
564     OSSL_TRACE(INIT, "OPENSSL_cleanup: openssl_ctx_default_deinit()\n");
565     openssl_ctx_default_deinit();
566
567     OSSL_TRACE(INIT, "OPENSSL_cleanup: bio_cleanup()\n");
568     bio_cleanup();
569
570     OSSL_TRACE(INIT, "OPENSSL_cleanup: evp_cleanup_int()\n");
571     evp_cleanup_int();
572
573     OSSL_TRACE(INIT, "OPENSSL_cleanup: obj_cleanup_int()\n");
574     obj_cleanup_int();
575
576     OSSL_TRACE(INIT, "OPENSSL_cleanup: err_int()\n");
577     err_cleanup();
578
579     OSSL_TRACE(INIT, "OPENSSL_cleanup: CRYPTO_secure_malloc_done()\n");
580     CRYPTO_secure_malloc_done();
581
582     OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_trace_cleanup()\n");
583     ossl_trace_cleanup();
584
585     base_inited = 0;
586 }
587
588 /*
589  * If this function is called with a non NULL settings value then it must be
590  * called prior to any threads making calls to any OpenSSL functions,
591  * i.e. passing a non-null settings value is assumed to be single-threaded.
592  */
593 int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings)
594 {
595     /*
596      * TODO(3.0): This function needs looking at with a view to moving most/all
597      * of this into OPENSSL_CTX.
598      */
599
600     if (stopped) {
601         if (!(opts & OPENSSL_INIT_BASE_ONLY))
602             CRYPTOerr(CRYPTO_F_OPENSSL_INIT_CRYPTO, ERR_R_INIT_FAIL);
603         return 0;
604     }
605
606     /*
607      * When the caller specifies OPENSSL_INIT_BASE_ONLY, that should be the
608      * *only* option specified.  With that option we return immediately after
609      * doing the requested limited initialization.  Note that
610      * err_shelve_state() called by us via ossl_init_load_crypto_nodelete()
611      * re-enters OPENSSL_init_crypto() with OPENSSL_INIT_BASE_ONLY, but with
612      * base already initialized this is a harmless NOOP.
613      *
614      * If we remain the only caller of err_shelve_state() the recursion should
615      * perhaps be removed, but if in doubt, it can be left in place.
616      */
617     if (!RUN_ONCE(&base, ossl_init_base))
618         return 0;
619
620     if (opts & OPENSSL_INIT_BASE_ONLY)
621         return 1;
622
623     /*
624      * Now we don't always set up exit handlers, the INIT_BASE_ONLY calls
625      * should not have the side-effect of setting up exit handlers, and
626      * therefore, this code block is below the INIT_BASE_ONLY-conditioned early
627      * return above.
628      */
629     if ((opts & OPENSSL_INIT_NO_ATEXIT) != 0) {
630         if (!RUN_ONCE_ALT(&register_atexit, ossl_init_no_register_atexit,
631                           ossl_init_register_atexit))
632             return 0;
633     } else if (!RUN_ONCE(&register_atexit, ossl_init_register_atexit)) {
634         return 0;
635     }
636
637     if (!RUN_ONCE(&load_crypto_nodelete, ossl_init_load_crypto_nodelete))
638         return 0;
639
640     if ((opts & OPENSSL_INIT_NO_LOAD_CRYPTO_STRINGS)
641             && !RUN_ONCE_ALT(&load_crypto_strings,
642                              ossl_init_no_load_crypto_strings,
643                              ossl_init_load_crypto_strings))
644         return 0;
645
646     if ((opts & OPENSSL_INIT_LOAD_CRYPTO_STRINGS)
647             && !RUN_ONCE(&load_crypto_strings, ossl_init_load_crypto_strings))
648         return 0;
649
650     if ((opts & OPENSSL_INIT_NO_ADD_ALL_CIPHERS)
651             && !RUN_ONCE_ALT(&add_all_ciphers, ossl_init_no_add_all_ciphers,
652                              ossl_init_add_all_ciphers))
653         return 0;
654
655     if ((opts & OPENSSL_INIT_ADD_ALL_CIPHERS)
656             && !RUN_ONCE(&add_all_ciphers, ossl_init_add_all_ciphers))
657         return 0;
658
659     if ((opts & OPENSSL_INIT_NO_ADD_ALL_DIGESTS)
660             && !RUN_ONCE_ALT(&add_all_digests, ossl_init_no_add_all_digests,
661                              ossl_init_add_all_digests))
662         return 0;
663
664     if ((opts & OPENSSL_INIT_ADD_ALL_DIGESTS)
665             && !RUN_ONCE(&add_all_digests, ossl_init_add_all_digests))
666         return 0;
667
668     if ((opts & OPENSSL_INIT_NO_ADD_ALL_MACS)
669             && !RUN_ONCE_ALT(&add_all_macs, ossl_init_no_add_all_macs,
670                              ossl_init_add_all_macs))
671         return 0;
672
673     if ((opts & OPENSSL_INIT_ADD_ALL_MACS)
674             && !RUN_ONCE(&add_all_macs, ossl_init_add_all_macs))
675         return 0;
676
677     if ((opts & OPENSSL_INIT_NO_ADD_ALL_KDFS)
678             && !RUN_ONCE_ALT(&add_all_kdfs, ossl_init_no_add_all_kdfs,
679                              ossl_init_add_all_kdfs))
680         return 0;
681
682     if ((opts & OPENSSL_INIT_ADD_ALL_KDFS)
683             && !RUN_ONCE(&add_all_kdfs, ossl_init_add_all_kdfs))
684         return 0;
685
686     if ((opts & OPENSSL_INIT_ATFORK)
687             && !openssl_init_fork_handlers())
688         return 0;
689
690     if ((opts & OPENSSL_INIT_NO_LOAD_CONFIG)
691             && !RUN_ONCE_ALT(&config, ossl_init_no_config, ossl_init_config))
692         return 0;
693
694     if (opts & OPENSSL_INIT_LOAD_CONFIG) {
695         int ret;
696         CRYPTO_THREAD_write_lock(init_lock);
697         conf_settings = settings;
698         ret = RUN_ONCE(&config, ossl_init_config);
699         conf_settings = NULL;
700         CRYPTO_THREAD_unlock(init_lock);
701         if (ret <= 0)
702             return 0;
703     }
704
705     if ((opts & OPENSSL_INIT_ASYNC)
706             && !RUN_ONCE(&async, ossl_init_async))
707         return 0;
708
709 #ifndef OPENSSL_NO_ENGINE
710     if ((opts & OPENSSL_INIT_ENGINE_OPENSSL)
711             && !RUN_ONCE(&engine_openssl, ossl_init_engine_openssl))
712         return 0;
713 # ifndef OPENSSL_NO_RDRAND
714     if ((opts & OPENSSL_INIT_ENGINE_RDRAND)
715             && !RUN_ONCE(&engine_rdrand, ossl_init_engine_rdrand))
716         return 0;
717 # endif
718     if ((opts & OPENSSL_INIT_ENGINE_DYNAMIC)
719             && !RUN_ONCE(&engine_dynamic, ossl_init_engine_dynamic))
720         return 0;
721 # ifndef OPENSSL_NO_STATIC_ENGINE
722 #  ifndef OPENSSL_NO_DEVCRYPTOENG
723     if ((opts & OPENSSL_INIT_ENGINE_CRYPTODEV)
724             && !RUN_ONCE(&engine_devcrypto, ossl_init_engine_devcrypto))
725         return 0;
726 #  endif
727 #  if !defined(OPENSSL_NO_PADLOCKENG)
728     if ((opts & OPENSSL_INIT_ENGINE_PADLOCK)
729             && !RUN_ONCE(&engine_padlock, ossl_init_engine_padlock))
730         return 0;
731 #  endif
732 #  if defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_NO_CAPIENG)
733     if ((opts & OPENSSL_INIT_ENGINE_CAPI)
734             && !RUN_ONCE(&engine_capi, ossl_init_engine_capi))
735         return 0;
736 #  endif
737 #  if !defined(OPENSSL_NO_AFALGENG)
738     if ((opts & OPENSSL_INIT_ENGINE_AFALG)
739             && !RUN_ONCE(&engine_afalg, ossl_init_engine_afalg))
740         return 0;
741 #  endif
742 # endif
743     if (opts & (OPENSSL_INIT_ENGINE_ALL_BUILTIN
744                 | OPENSSL_INIT_ENGINE_OPENSSL
745                 | OPENSSL_INIT_ENGINE_AFALG)) {
746         ENGINE_register_all_complete();
747     }
748 #endif
749
750 #ifndef OPENSSL_NO_COMP
751     if ((opts & OPENSSL_INIT_ZLIB)
752             && !RUN_ONCE(&zlib, ossl_init_zlib))
753         return 0;
754 #endif
755
756     return 1;
757 }
758
759 int OPENSSL_atexit(void (*handler)(void))
760 {
761     OPENSSL_INIT_STOP *newhand;
762
763 #if !defined(OPENSSL_USE_NODELETE)\
764     && !defined(OPENSSL_NO_PINSHARED)
765     {
766         union {
767             void *sym;
768             void (*func)(void);
769         } handlersym;
770
771         handlersym.func = handler;
772 # if defined(DSO_WIN32) && !defined(_WIN32_WCE)
773         {
774             HMODULE handle = NULL;
775             BOOL ret;
776
777             /*
778              * We don't use the DSO route for WIN32 because there is a better
779              * way
780              */
781             ret = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
782                                     | GET_MODULE_HANDLE_EX_FLAG_PIN,
783                                     handlersym.sym, &handle);
784
785             if (!ret)
786                 return 0;
787         }
788 # elif !defined(DSO_NONE)
789         /*
790          * Deliberately leak a reference to the handler. This will force the
791          * library/code containing the handler to remain loaded until we run the
792          * atexit handler. If -znodelete has been used then this is
793          * unnecessary.
794          */
795         {
796             DSO *dso = NULL;
797
798             ERR_set_mark();
799             dso = DSO_dsobyaddr(handlersym.sym, DSO_FLAG_NO_UNLOAD_ON_FREE);
800             /* See same code above in ossl_init_base() for an explanation. */
801             OSSL_TRACE1(INIT,
802                        "atexit: obtained DSO reference? %s\n",
803                        (dso == NULL ? "No!" : "Yes."));
804             DSO_free(dso);
805             ERR_pop_to_mark();
806         }
807 # endif
808     }
809 #endif
810
811     if ((newhand = OPENSSL_malloc(sizeof(*newhand))) == NULL) {
812         CRYPTOerr(CRYPTO_F_OPENSSL_ATEXIT, ERR_R_MALLOC_FAILURE);
813         return 0;
814     }
815
816     newhand->handler = handler;
817     newhand->next = stop_handlers;
818     stop_handlers = newhand;
819
820     return 1;
821 }
822
823 #ifdef OPENSSL_SYS_UNIX
824 /*
825  * The following three functions are for OpenSSL developers.  This is
826  * where we set/reset state across fork (called via pthread_atfork when
827  * it exists, or manually by the application when it doesn't).
828  *
829  * WARNING!  If you put code in either OPENSSL_fork_parent or
830  * OPENSSL_fork_child, you MUST MAKE SURE that they are async-signal-
831  * safe.  See this link, for example:
832  *      http://man7.org/linux/man-pages/man7/signal-safety.7.html
833  */
834
835 void OPENSSL_fork_prepare(void)
836 {
837 }
838
839 void OPENSSL_fork_parent(void)
840 {
841 }
842
843 void OPENSSL_fork_child(void)
844 {
845     rand_fork();
846     /* TODO(3.0): Inform all providers about a fork event */
847 }
848 #endif