xref: /openbsd-src/lib/libcrypto/crypto_init.c (revision 521ba2f2ab0e0e89d1776559874b3ecc227442fc)
1 /*	$OpenBSD: crypto_init.c,v 1.9 2023/06/19 18:32:05 tb Exp $ */
2 /*
3  * Copyright (c) 2018 Bob Beck <beck@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 /* OpenSSL style init */
19 
20 #include <pthread.h>
21 #include <stdio.h>
22 
23 #include <openssl/conf.h>
24 #ifndef OPENSSL_NO_ENGINE
25 #include <openssl/engine.h>
26 #endif
27 #include <openssl/err.h>
28 #include <openssl/evp.h>
29 #include <openssl/objects.h>
30 
31 #include "cryptlib.h"
32 #include "x509_issuer_cache.h"
33 
34 int OpenSSL_config(const char *);
35 int OpenSSL_no_config(void);
36 
37 static pthread_once_t crypto_init_once = PTHREAD_ONCE_INIT;
38 static pthread_t crypto_init_thread;
39 static int crypto_init_cleaned_up;
40 
41 static void
42 OPENSSL_init_crypto_internal(void)
43 {
44 	crypto_init_thread = pthread_self();
45 
46 	OPENSSL_cpuid_setup();
47 	ERR_load_crypto_strings();
48 	OpenSSL_add_all_ciphers();
49 	OpenSSL_add_all_digests();
50 }
51 
52 int
53 OPENSSL_init_crypto(uint64_t opts, const void *settings)
54 {
55 	if (crypto_init_cleaned_up) {
56 		CRYPTOerror(ERR_R_INIT_FAIL);
57 		return 0;
58 	}
59 
60 	if (pthread_equal(pthread_self(), crypto_init_thread))
61 		return 1; /* don't recurse */
62 
63 	if (pthread_once(&crypto_init_once, OPENSSL_init_crypto_internal) != 0)
64 		return 0;
65 
66 	if ((opts & OPENSSL_INIT_NO_LOAD_CONFIG) &&
67 	    (OpenSSL_no_config() == 0))
68 		return 0;
69 
70 	if ((opts & OPENSSL_INIT_LOAD_CONFIG) &&
71 	    (OpenSSL_config(NULL) == 0))
72 		return 0;
73 
74 	return 1;
75 }
76 
77 void
78 OPENSSL_cleanup(void)
79 {
80 	/* This currently calls init... */
81 	ERR_free_strings();
82 
83 	CRYPTO_cleanup_all_ex_data();
84 #ifndef OPENSSL_NO_ENGINE
85 	ENGINE_cleanup();
86 #endif
87 	EVP_cleanup();
88 	x509_issuer_cache_free();
89 
90 	crypto_init_cleaned_up = 1;
91 }
92