xref: /openbsd-src/lib/libcrypto/crypto_init.c (revision ff0e7be1ebbcc809ea8ad2b6dafe215824da9e46)
1 /*	$OpenBSD: crypto_init.c,v 1.8 2023/05/08 13:53:26 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 #include <openssl/engine.h>
25 #include <openssl/err.h>
26 #include <openssl/evp.h>
27 #include <openssl/objects.h>
28 
29 #include "cryptlib.h"
30 #include "x509_issuer_cache.h"
31 
32 int OpenSSL_config(const char *);
33 int OpenSSL_no_config(void);
34 
35 static pthread_once_t crypto_init_once = PTHREAD_ONCE_INIT;
36 static pthread_t crypto_init_thread;
37 static int crypto_init_cleaned_up;
38 
39 static void
40 OPENSSL_init_crypto_internal(void)
41 {
42 	crypto_init_thread = pthread_self();
43 
44 	OPENSSL_cpuid_setup();
45 	ERR_load_crypto_strings();
46 	OpenSSL_add_all_ciphers();
47 	OpenSSL_add_all_digests();
48 }
49 
50 int
51 OPENSSL_init_crypto(uint64_t opts, const void *settings)
52 {
53 	if (crypto_init_cleaned_up) {
54 		CRYPTOerror(ERR_R_INIT_FAIL);
55 		return 0;
56 	}
57 
58 	if (pthread_equal(pthread_self(), crypto_init_thread))
59 		return 1; /* don't recurse */
60 
61 	if (pthread_once(&crypto_init_once, OPENSSL_init_crypto_internal) != 0)
62 		return 0;
63 
64 	if ((opts & OPENSSL_INIT_NO_LOAD_CONFIG) &&
65 	    (OpenSSL_no_config() == 0))
66 		return 0;
67 
68 	if ((opts & OPENSSL_INIT_LOAD_CONFIG) &&
69 	    (OpenSSL_config(NULL) == 0))
70 		return 0;
71 
72 	return 1;
73 }
74 
75 void
76 OPENSSL_cleanup(void)
77 {
78 	/* This currently calls init... */
79 	ERR_free_strings();
80 
81 	CRYPTO_cleanup_all_ex_data();
82 	ENGINE_cleanup();
83 	EVP_cleanup();
84 	x509_issuer_cache_free();
85 
86 	crypto_init_cleaned_up = 1;
87 }
88