From a4ab82d900bcba65011b0fdfd74a76b8cb1e35da Mon Sep 17 00:00:00 2001 From: Jos Kuijpers Date: Sat, 22 Oct 2011 18:36:08 +0200 Subject: [PATCH] Register helpers for thread-safety with OpenSSL. --- src/SSLSocket.m | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/SSLSocket.m b/src/SSLSocket.m index 4fc16c0..8d14faa 100644 --- a/src/SSLSocket.m +++ b/src/SSLSocket.m @@ -27,6 +27,8 @@ #import #import +#include + #import "SSLSocket.h" #import @@ -38,12 +40,28 @@ #import #import #import +#import #ifndef INVALID_SOCKET # define INVALID_SOCKET -1 #endif static SSL_CTX *ctx; +static of_mutex_t *ssl_mutexes; + +static void +ssl_locking_callback(int mode, int n, const char *file, int line) +{ + /* + * This function must handle up to CRYPTO_num_locks() mutexes. + * It must set the n-th lock if mode & CRYPTO_LOCK, + * release it otherwise. + */ + if (mode & CRYPTO_LOCK) + of_mutex_lock(&ssl_mutexes[n]); + else + of_mutex_unlock(&ssl_mutexes[n]); +} @implementation SSLSocket + (void)load @@ -53,9 +71,21 @@ static SSL_CTX *ctx; + (void)initialize { + int m; + if (self != [SSLSocket class]) return; + CRYPTO_set_id_callback(&of_thread_current); + + /* Generate number of mutexes needed */ + m = CRYPTO_num_locks(); + ssl_mutexes = malloc(m * sizeof(of_mutex_t)); + for (m--; m >= 0; m--) + of_mutex_new(&ssl_mutexes[m]); + + CRYPTO_set_locking_callback(&ssl_locking_callback); + SSL_library_init(); if ((ctx = SSL_CTX_new(SSLv23_method())) == NULL)