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 
27 #include "cryptlib.h"
28 
29 int OpenSSL_config(const char *);
30 int OpenSSL_no_config(void);
31 
32 static pthread_t crypto_init_thread;
33 
34 static void
35 OPENSSL_init_crypto_internal(void)
36 {
37 	crypto_init_thread = pthread_self();
38 
39 	OPENSSL_cpuid_setup();
40 	ERR_load_crypto_strings();
41 	OpenSSL_add_all_ciphers();
42 	OpenSSL_add_all_digests();
43 }
44 
45 int
46 OPENSSL_init_crypto(uint64_t opts, const void *settings)
47 {
48 	static pthread_once_t once = PTHREAD_ONCE_INIT;
49 
50 	if (pthread_equal(pthread_self(), crypto_init_thread))
51 		return 1; /* don't recurse */
52 
53 	if (pthread_once(&once, OPENSSL_init_crypto_internal) != 0)
54 		return 0;
55 
56 	if ((opts & OPENSSL_INIT_NO_LOAD_CONFIG) &&
57 	    (OpenSSL_no_config() == 0))
58 		return 0;
59 
60 	if ((opts & OPENSSL_INIT_LOAD_CONFIG) &&
61 	    (OpenSSL_config(NULL) == 0))
62 		return 0;
63 
64 	return 1;
65 }
66