2 * QEMU Crypto initialization
4 * Copyright (c) 2015 Red Hat, Inc.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 #include "qemu/osdep.h"
22 #include "crypto/init.h"
23 #include "qapi/error.h"
24 #include "qemu/thread.h"
27 #include <gnutls/gnutls.h>
28 #include <gnutls/crypto.h>
35 #include "crypto/random.h"
37 /* #define DEBUG_GNUTLS */
40 * We need to init gcrypt threading if
46 #if (defined(CONFIG_GCRYPT) && \
47 (GCRYPT_VERSION_NUMBER < 0x010600))
48 #define QCRYPTO_INIT_GCRYPT_THREADS
50 #undef QCRYPTO_INIT_GCRYPT_THREADS
54 static void qcrypto_gnutls_log(int level
, const char *str
)
56 fprintf(stderr
, "%d: %s", level
, str
);
60 #ifdef QCRYPTO_INIT_GCRYPT_THREADS
61 static int qcrypto_gcrypt_mutex_init(void **priv
)
63 QemuMutex
*lock
= NULL
;
64 lock
= g_new0(QemuMutex
, 1);
65 qemu_mutex_init(lock
);
70 static int qcrypto_gcrypt_mutex_destroy(void **priv
)
72 QemuMutex
*lock
= *priv
;
73 qemu_mutex_destroy(lock
);
78 static int qcrypto_gcrypt_mutex_lock(void **priv
)
80 QemuMutex
*lock
= *priv
;
81 qemu_mutex_lock(lock
);
85 static int qcrypto_gcrypt_mutex_unlock(void **priv
)
87 QemuMutex
*lock
= *priv
;
88 qemu_mutex_unlock(lock
);
92 static struct gcry_thread_cbs qcrypto_gcrypt_thread_impl
= {
93 (GCRY_THREAD_OPTION_PTHREAD
| (GCRY_THREAD_OPTION_VERSION
<< 8)),
95 qcrypto_gcrypt_mutex_init
,
96 qcrypto_gcrypt_mutex_destroy
,
97 qcrypto_gcrypt_mutex_lock
,
98 qcrypto_gcrypt_mutex_unlock
,
99 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
101 #endif /* QCRYPTO_INIT_GCRYPT */
103 int qcrypto_init(Error
**errp
)
105 #ifdef QCRYPTO_INIT_GCRYPT_THREADS
106 gcry_control(GCRYCTL_SET_THREAD_CBS
, &qcrypto_gcrypt_thread_impl
);
107 #endif /* QCRYPTO_INIT_GCRYPT_THREADS */
111 ret
= gnutls_global_init();
114 "Unable to initialize GNUTLS library: %s",
115 gnutls_strerror(ret
));
119 gnutls_global_set_log_level(10);
120 gnutls_global_set_log_function(qcrypto_gnutls_log
);
125 if (!gcry_check_version(NULL
)) {
126 error_setg(errp
, "Unable to initialize gcrypt");
129 gcry_control(GCRYCTL_INITIALIZATION_FINISHED
, 0);
132 if (qcrypto_random_init(errp
) < 0) {