-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathssl_guard.cpp
111 lines (89 loc) · 2.37 KB
/
ssl_guard.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#ifdef SOCKPUPPET_WITH_TLS
#include "ssl_guard.h"
#include <openssl/crypto.h> // for CRYPTO_set_locking_callback
#include <openssl/ssl.h> // for SSL_library_init
#include <memory> // for std::unique_ptr
#include <mutex> // for std::mutex
#include <thread> // for std::this_thread::get_id
#include <stdexcept> // for std::logic_error
struct CRYPTO_dynlock_value
{
std::mutex mtx;
};
namespace {
CRYPTO_dynlock_value *DynlockCreate(char const *, int)
{
return new CRYPTO_dynlock_value;
}
void DynlockLock(int mode, CRYPTO_dynlock_value *v, char const *, int)
{
if(mode & CRYPTO_LOCK) {
v->mtx.lock();
} else {
v->mtx.unlock();
}
}
void DynlockDestroy(CRYPTO_dynlock_value *v, char const *, int)
{
delete v;
}
std::mutex &Mutex(size_t n)
{
static auto const count = static_cast<size_t>(CRYPTO_num_locks());
static std::unique_ptr<std::mutex[]> const mutices(new std::mutex[count]);
if(n >= count) {
throw std::logic_error("invalid SSL locking index");
}
return mutices[n];
}
void Locking(int mode, int n, char const *, int)
{
if(mode & CRYPTO_LOCK) {
Mutex(static_cast<size_t>(n)).lock();
} else {
Mutex(static_cast<size_t>(n)).unlock();
}
}
unsigned long Id()
{
std::hash<std::thread::id> hasher;
return static_cast<unsigned long>(hasher(std::this_thread::get_id()));
}
void UpdateInstanceCount(int modifier)
{
static std::mutex mtx;
static int curr = 0;
std::lock_guard<std::mutex> lock(mtx);
auto prev = curr;
curr += modifier;
if(prev == 0 && curr == 1) {
// we are the first instance -> initialize
(void)SSL_library_init();
SSL_load_error_strings();
CRYPTO_set_id_callback(Id);
CRYPTO_set_locking_callback(Locking);
CRYPTO_set_dynlock_create_callback(DynlockCreate);
CRYPTO_set_dynlock_lock_callback(DynlockLock);
CRYPTO_set_dynlock_destroy_callback(DynlockDestroy);
} else if(prev == 1 && curr == 0) {
// we are the last instance -> cleanup
CRYPTO_set_dynlock_destroy_callback(nullptr);
CRYPTO_set_dynlock_lock_callback(nullptr);
CRYPTO_set_dynlock_create_callback(nullptr);
CRYPTO_set_locking_callback(nullptr);
CRYPTO_set_id_callback(nullptr);
EVP_cleanup();
}
}
} // unnamed namespace
namespace sockpuppet {
SslGuard::SslGuard()
{
UpdateInstanceCount(1);
}
SslGuard::~SslGuard()
{
UpdateInstanceCount(-1);
}
} // namespace sockpuppet
#endif // SOCKPUPPET_WITH_TLS