From 12cd565ad7983dbf6aa3fa336b991b71e9745779 Mon Sep 17 00:00:00 2001 From: Adrien Destugues Date: Mon, 1 Sep 2014 09:54:46 +0200 Subject: [PATCH] SecureSocket: add OpenSSL locking. This shoiuld make OpenSSL more thread safe and help with the random network related crashes in Web+ (and anything else using SecureSocket with more than one thread). --- src/kits/network/libnetapi/SSL.cpp | 38 ++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/kits/network/libnetapi/SSL.cpp b/src/kits/network/libnetapi/SSL.cpp index f60c673d35..c8cb75cd2a 100644 --- a/src/kits/network/libnetapi/SSL.cpp +++ b/src/kits/network/libnetapi/SSL.cpp @@ -1,5 +1,7 @@ /* * Copyright 2011, Axel Dörfler, axeld@pinc-software.de. + * Copyright 2014 Haiku, inc. + * * Distributed under the terms of the MIT License. */ @@ -8,6 +10,7 @@ #include #include +#include namespace BPrivate { @@ -21,11 +24,46 @@ public: int64 seed = find_thread(NULL) ^ system_time(); RAND_seed(&seed, sizeof(seed)); + + // Set callbacks required for thread-safe operation of OpenSSL. + sMutexBuf = new pthread_mutex_t[CRYPTO_num_locks()]; + for (int i = 0; i < CRYPTO_num_locks(); i++) + pthread_mutex_init(&sMutexBuf[i], NULL); + CRYPTO_set_id_callback(_GetThreadId); + CRYPTO_set_locking_callback(_LockingFunction); } + + ~SSL() + { + CRYPTO_set_id_callback(NULL); + CRYPTO_set_locking_callback(NULL); + + for (int i = 0; i < CRYPTO_num_locks(); i++) + pthread_mutex_destroy(&sMutexBuf[i]); + delete sMutexBuf; + } + +private: + static void _LockingFunction(int mode, int n, const char * file, int line) + { + if (mode & CRYPTO_LOCK) + pthread_mutex_lock(&sMutexBuf[n]); + else + pthread_mutex_unlock(&sMutexBuf[n]); + } + + static unsigned long _GetThreadId() + { + return find_thread(NULL); + } + +private: + static pthread_mutex_t* sMutexBuf; }; static SSL sSSL; +pthread_mutex_t* SSL::sMutexBuf; } // namespace BPrivate