1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21#include "qemu/osdep.h"
22#include "crypto/init.h"
23#include "qapi/error.h"
24#include "qemu/thread.h"
25
26#ifdef CONFIG_GNUTLS
27#include <gnutls/gnutls.h>
28#include <gnutls/crypto.h>
29#endif
30
31#ifdef CONFIG_GCRYPT
32#include <gcrypt.h>
33#endif
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60#if (defined(CONFIG_GCRYPT) && \
61 (!defined(CONFIG_GNUTLS) || \
62 !defined(GNUTLS_VERSION_NUMBER) || \
63 (GNUTLS_VERSION_NUMBER < 0x020c00)) && \
64 (!defined(GCRYPT_VERSION_NUMBER) || \
65 (GCRYPT_VERSION_NUMBER < 0x010600)))
66#define QCRYPTO_INIT_GCRYPT_THREADS
67#else
68#undef QCRYPTO_INIT_GCRYPT_THREADS
69#endif
70
71#ifdef DEBUG_GNUTLS
72static void qcrypto_gnutls_log(int level, const char *str)
73{
74 fprintf(stderr, "%d: %s", level, str);
75}
76#endif
77
78#ifdef QCRYPTO_INIT_GCRYPT_THREADS
79static int qcrypto_gcrypt_mutex_init(void **priv)
80{ \
81 QemuMutex *lock = NULL;
82 lock = g_new0(QemuMutex, 1);
83 qemu_mutex_init(lock);
84 *priv = lock;
85 return 0;
86}
87
88static int qcrypto_gcrypt_mutex_destroy(void **priv)
89{
90 QemuMutex *lock = *priv;
91 qemu_mutex_destroy(lock);
92 g_free(lock);
93 return 0;
94}
95
96static int qcrypto_gcrypt_mutex_lock(void **priv)
97{
98 QemuMutex *lock = *priv;
99 qemu_mutex_lock(lock);
100 return 0;
101}
102
103static int qcrypto_gcrypt_mutex_unlock(void **priv)
104{
105 QemuMutex *lock = *priv;
106 qemu_mutex_unlock(lock);
107 return 0;
108}
109
110static struct gcry_thread_cbs qcrypto_gcrypt_thread_impl = {
111 (GCRY_THREAD_OPTION_PTHREAD | (GCRY_THREAD_OPTION_VERSION << 8)),
112 NULL,
113 qcrypto_gcrypt_mutex_init,
114 qcrypto_gcrypt_mutex_destroy,
115 qcrypto_gcrypt_mutex_lock,
116 qcrypto_gcrypt_mutex_unlock,
117 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
118};
119#endif
120
121int qcrypto_init(Error **errp)
122{
123#ifdef CONFIG_GNUTLS
124 int ret;
125 ret = gnutls_global_init();
126 if (ret < 0) {
127 error_setg(errp,
128 "Unable to initialize GNUTLS library: %s",
129 gnutls_strerror(ret));
130 return -1;
131 }
132#ifdef DEBUG_GNUTLS
133 gnutls_global_set_log_level(10);
134 gnutls_global_set_log_function(qcrypto_gnutls_log);
135#endif
136#endif
137
138#ifdef CONFIG_GCRYPT
139 if (!gcry_check_version(GCRYPT_VERSION)) {
140 error_setg(errp, "Unable to initialize gcrypt");
141 return -1;
142 }
143#ifdef QCRYPTO_INIT_GCRYPT_THREADS
144 gcry_control(GCRYCTL_SET_THREAD_CBS, &qcrypto_gcrypt_thread_impl);
145#endif
146 gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
147#endif
148
149 return 0;
150}
151