Skip to content

Commit 9e7cf9e

Browse files
ko1nobu
authored andcommitted
openssl is ractor-safe
ossl_bn_ctx is C's global variable and it should be ractor-local to make it ractor-safe. ruby/ruby@b5588ed
1 parent f2d0046 commit 9e7cf9e

File tree

3 files changed

+37
-10
lines changed

3 files changed

+37
-10
lines changed

ext/openssl/ossl.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1126,6 +1126,10 @@ ossl_crypto_fixed_length_secure_compare(VALUE dummy, VALUE str1, VALUE str2)
11261126
void
11271127
Init_openssl(void)
11281128
{
1129+
#if HAVE_RB_EXT_RACTOR_SAFE
1130+
rb_ext_ractor_safe(true);
1131+
#endif
1132+
11291133
#undef rb_intern
11301134
/*
11311135
* Init timezone info

ext/openssl/ossl_bn.c

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
*/
1010
/* modified by Michal Rokos <[email protected]> */
1111
#include "ossl.h"
12+
#include <ruby/ractor.h>
1213

1314
#define NewBN(klass) \
1415
TypedData_Wrap_Struct((klass), &ossl_bn_type, 0)
@@ -150,12 +151,35 @@ ossl_bn_value_ptr(volatile VALUE *ptr)
150151
/*
151152
* Private
152153
*/
153-
/*
154-
* BN_CTX - is used in more difficult math. ops
155-
* (Why just 1? Because Ruby itself isn't thread safe,
156-
* we don't need to care about threads)
157-
*/
158-
BN_CTX *ossl_bn_ctx;
154+
155+
void
156+
ossl_bn_ctx_free(void *ptr)
157+
{
158+
BN_CTX *ctx = (BN_CTX *)ptr;
159+
BN_CTX_free(ctx);
160+
}
161+
162+
struct rb_ractor_local_storage_type ossl_bn_ctx_key_type = {
163+
NULL, // mark
164+
ossl_bn_ctx_free,
165+
};
166+
167+
rb_ractor_local_key_t ossl_bn_ctx_key;
168+
169+
BN_CTX *
170+
ossl_bn_ctx_get(void)
171+
{
172+
// stored in ractor local storage
173+
174+
BN_CTX *ctx = rb_ractor_local_storage_ptr(ossl_bn_ctx_key);
175+
if (!ctx) {
176+
if (!(ctx = BN_CTX_new())) {
177+
ossl_raise(rb_eRuntimeError, "Cannot init BN_CTX");
178+
}
179+
rb_ractor_local_storage_ptr_set(ossl_bn_ctx_key, ctx);
180+
}
181+
return ctx;
182+
}
159183

160184
static VALUE
161185
ossl_bn_alloc(VALUE klass)
@@ -1092,9 +1116,7 @@ Init_ossl_bn(void)
10921116
eOSSLError = rb_define_class_under(mOSSL, "OpenSSLError", rb_eStandardError);
10931117
#endif
10941118

1095-
if (!(ossl_bn_ctx = BN_CTX_new())) {
1096-
ossl_raise(rb_eRuntimeError, "Cannot init BN_CTX");
1097-
}
1119+
ossl_bn_ctx_key = rb_ractor_local_storage_ptr_newkey(&ossl_bn_ctx_key_type);
10981120

10991121
eBNError = rb_define_class_under(mOSSL, "BNError", eOSSLError);
11001122

ext/openssl/ossl_bn.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
extern VALUE cBN;
1414
extern VALUE eBNError;
1515

16-
extern BN_CTX *ossl_bn_ctx;
16+
BN_CTX *ossl_bn_ctx_get(void);
17+
#define ossl_bn_ctx ossl_bn_ctx_get()
1718

1819
#define GetBNPtr(obj) ossl_bn_value_ptr(&(obj))
1920

0 commit comments

Comments
 (0)