Skip to content

Commit 86a52e4

Browse files
committed
Bug#29667091: Fix Race condition on OpenSSL 1.0.x
1 parent abb3ab1 commit 86a52e4

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

cdk/foundation/socket_detail.cc

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ PUSH_SYS_WARNINGS_CDK
4444
#include <limits>
4545
#include <chrono>
4646
#include <sstream>
47+
#include <mutex>
48+
#include <thread>
4749

4850
#ifndef _WIN32
4951
#include <arpa/inet.h>
@@ -353,6 +355,44 @@ void set_nonblocking(Socket socket, bool nonblocking)
353355
}
354356

355357

358+
#if defined WITH_SSL && OPENSSL_VERSION_NUMBER < 0x10100000L
359+
//Not needed after 1.1
360+
361+
static std::mutex* m_openssl_mutex = nullptr;
362+
363+
void thread_setup()
364+
{
365+
m_openssl_mutex = new std::mutex[CRYPTO_num_locks()];
366+
}
367+
368+
void thread_cleanup()
369+
{
370+
delete[] m_openssl_mutex;
371+
}
372+
373+
static void locking_function(int mode, int n, const char *file, int line)
374+
{
375+
if(mode & CRYPTO_LOCK)
376+
{
377+
m_openssl_mutex[n].lock();
378+
}
379+
else if(mode & CRYPTO_UNLOCK)
380+
{
381+
m_openssl_mutex[n].unlock();
382+
}
383+
}
384+
385+
static void id_function(CRYPTO_THREADID *id)
386+
{
387+
CRYPTO_THREADID_set_numeric(
388+
id,
389+
static_cast<unsigned long>(
390+
std::hash<std::thread::id>()(std::this_thread::get_id())
391+
)
392+
);
393+
}
394+
#endif
395+
356396
void initialize_socket_system()
357397
{
358398
#ifdef _WIN32
@@ -367,6 +407,11 @@ void initialize_socket_system()
367407
SSL_library_init();
368408
OpenSSL_add_all_algorithms();
369409
SSL_load_error_strings();
410+
# if OPENSSL_VERSION_NUMBER < 0x10100000L
411+
thread_setup();
412+
CRYPTO_set_locking_callback(locking_function);
413+
CRYPTO_THREADID_set_callback(id_function);
414+
# endif
370415
#endif
371416

372417
#ifndef WIN32
@@ -382,6 +427,11 @@ void uninitialize_socket_system()
382427
if (::WSACleanup() != 0)
383428
throw_socket_error();
384429
#endif
430+
#ifdef WITH_SSL
431+
# if OPENSSL_VERSION_NUMBER < 0x10100000L
432+
thread_cleanup();
433+
# endif
434+
#endif
385435
}
386436

387437

0 commit comments

Comments
 (0)