Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / common / ceph_crypto.cc
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3 /*
4  * Ceph - scalable distributed file system
5  *
6  * Copyright (C) 2010-2011 Dreamhost
7  *
8  * This is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License version 2.1, as published by the Free Software
11  * Foundation.  See file COPYING.
12  *
13  */
14
15 #include "common/config.h"
16 #include "ceph_crypto.h"
17
18 #ifdef USE_CRYPTOPP
19 void ceph::crypto::init(CephContext *cct)
20 {
21 }
22
23 void ceph::crypto::shutdown(bool)
24 {
25 }
26
27 // nothing
28 ceph::crypto::HMACSHA1::~HMACSHA1()
29 {
30 }
31
32 ceph::crypto::HMACSHA256::~HMACSHA256()
33 {
34 }
35
36 #elif defined(USE_NSS)
37
38 // for SECMOD_RestartModules()
39 #include <secmod.h>
40 #include <nspr.h>
41
42 static pthread_mutex_t crypto_init_mutex = PTHREAD_MUTEX_INITIALIZER;
43 static uint32_t crypto_refs = 0;
44 static NSSInitContext *crypto_context = NULL;
45 static pid_t crypto_init_pid = 0;
46
47 void ceph::crypto::init(CephContext *cct)
48 {
49   pid_t pid = getpid();
50   pthread_mutex_lock(&crypto_init_mutex);
51   if (crypto_init_pid != pid) {
52     if (crypto_init_pid > 0) {
53       SECMOD_RestartModules(PR_FALSE);
54     }
55     crypto_init_pid = pid;
56   }
57
58   if (++crypto_refs == 1) {
59     NSSInitParameters init_params;
60     memset(&init_params, 0, sizeof(init_params));
61     init_params.length = sizeof(init_params);
62
63     uint32_t flags = (NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
64     if (cct->_conf->nss_db_path.empty()) {
65       flags |= (NSS_INIT_NOCERTDB | NSS_INIT_NOMODDB);
66     }
67     crypto_context = NSS_InitContext(cct->_conf->nss_db_path.c_str(), "", "",
68                                      SECMOD_DB, &init_params, flags);
69   }
70   pthread_mutex_unlock(&crypto_init_mutex);
71   assert(crypto_context != NULL);
72 }
73
74 void ceph::crypto::shutdown(bool shared)
75 {
76   pthread_mutex_lock(&crypto_init_mutex);
77   assert(crypto_refs > 0);
78   if (--crypto_refs == 0) {
79     NSS_ShutdownContext(crypto_context);
80     if (!shared) {
81       PR_Cleanup();
82     }
83     crypto_context = NULL;
84     crypto_init_pid = 0;
85   }
86   pthread_mutex_unlock(&crypto_init_mutex);
87 }
88
89 ceph::crypto::HMAC::~HMAC()
90 {
91   PK11_DestroyContext(ctx, PR_TRUE);
92   PK11_FreeSymKey(symkey);
93   PK11_FreeSlot(slot);
94 }
95
96 #else
97 # error "No supported crypto implementation found."
98 #endif