xref: /openbsd-src/lib/libcrypto/crypto_init.c (revision aa997e528a848ca5596493c2a801bdd6fb26ae61)
1 /*
2  * Copyright (c) 2018 Bob Beck <beck@openbsd.org>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 
17 /* OpenSSL style init */
18 
19 #include <pthread.h>
20 #include <stdio.h>
21 
22 #include <openssl/objects.h>
23 #include <openssl/conf.h>
24 #include <openssl/evp.h>
25 #include <openssl/err.h>
26 #include "cryptlib.h"
27 
28 int OpenSSL_config(const char *);
29 int OpenSSL_no_config(void);
30 
31 static pthread_t crypto_init_thread;
32 
33 static void
34 OPENSSL_init_crypto_internal(void)
35 {
36 	crypto_init_thread = pthread_self();
37 	OPENSSL_cpuid_setup();
38 	ERR_load_crypto_strings();
39 	OpenSSL_add_all_ciphers();
40 	OpenSSL_add_all_digests();
41 }
42 
43 int
44 OPENSSL_init_crypto(uint64_t opts, const void *settings)
45 {
46 	static pthread_once_t once = PTHREAD_ONCE_INIT;
47 
48 	if (pthread_equal(pthread_self(), crypto_init_thread))
49 		return 1; /* don't recurse */
50 
51 	if (pthread_once(&once, OPENSSL_init_crypto_internal) != 0)
52 		return 0;
53 
54 	if ((opts & OPENSSL_INIT_NO_LOAD_CONFIG) &&
55 	    (OpenSSL_no_config() == 0))
56 		return 0;
57 
58 	if ((opts & OPENSSL_INIT_LOAD_CONFIG) &&
59 	    (OpenSSL_config(NULL) == 0))
60 		return 0;
61 
62 	return 1;
63 }
64