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 (LIBGNUTLS_VERSION_NUMBER < 0x020c00)) && \
63 (!defined(GCRYPT_VERSION_NUMBER) || \
64 (GCRYPT_VERSION_NUMBER < 0x010600)))
65#define QCRYPTO_INIT_GCRYPT_THREADS
66#else
67#undef QCRYPTO_INIT_GCRYPT_THREADS
68#endif
69
70#ifdef DEBUG_GNUTLS
71static void qcrypto_gnutls_log(int level, const char *str)
72{
73 fprintf(stderr, "%d: %s", level, str);
74}
75#endif
76
77#ifdef QCRYPTO_INIT_GCRYPT_THREADS
78static int qcrypto_gcrypt_mutex_init(void **priv)
79{ \
80 QemuMutex *lock = NULL;
81 lock = g_new0(QemuMutex, 1);
82 qemu_mutex_init(lock);
83 *priv = lock;
84 return 0;
85}
86
87static int qcrypto_gcrypt_mutex_destroy(void **priv)
88{
89 QemuMutex *lock = *priv;
90 qemu_mutex_destroy(lock);
91 g_free(lock);
92 return 0;
93}
94
95static int qcrypto_gcrypt_mutex_lock(void **priv)
96{
97 QemuMutex *lock = *priv;
98 qemu_mutex_lock(lock);
99 return 0;
100}
101
102static int qcrypto_gcrypt_mutex_unlock(void **priv)
103{
104 QemuMutex *lock = *priv;
105 qemu_mutex_unlock(lock);
106 return 0;
107}
108
109static struct gcry_thread_cbs qcrypto_gcrypt_thread_impl = {
110 (GCRY_THREAD_OPTION_PTHREAD | (GCRY_THREAD_OPTION_VERSION << 8)),
111 NULL,
112 qcrypto_gcrypt_mutex_init,
113 qcrypto_gcrypt_mutex_destroy,
114 qcrypto_gcrypt_mutex_lock,
115 qcrypto_gcrypt_mutex_unlock,
116 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
117};
118#endif
119
120int qcrypto_init(Error **errp)
121{
122#ifdef QCRYPTO_INIT_GCRYPT_THREADS
123 gcry_control(GCRYCTL_SET_THREAD_CBS, &qcrypto_gcrypt_thread_impl);
124#endif
125
126#ifdef CONFIG_GNUTLS
127 int ret;
128 ret = gnutls_global_init();
129 if (ret < 0) {
130 error_setg(errp,
131 "Unable to initialize GNUTLS library: %s",
132 gnutls_strerror(ret));
133 return -1;
134 }
135#ifdef DEBUG_GNUTLS
136 gnutls_global_set_log_level(10);
137 gnutls_global_set_log_function(qcrypto_gnutls_log);
138#endif
139#endif
140
141#ifdef CONFIG_GCRYPT
142 if (!gcry_check_version(GCRYPT_VERSION)) {
143 error_setg(errp, "Unable to initialize gcrypt");
144 return -1;
145 }
146 gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
147#endif
148
149 return 0;
150}
151