Skip to content

Commit 6efa373

Browse files
committed
Change the ossl3 context to be allocated once
Use a pthread_once guard to do intialization only once and a destructore to deinitialize also only once on library unload. Signed-off-by: Simo Sorce <simo@redhat.com>
1 parent 7624c1f commit 6efa373

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed

src/crypto.c

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -98,27 +98,44 @@ typedef struct ossl3_library_context {
9898
OSSL_PROVIDER *default_provider;
9999
} ossl3_context_t;
100100

101-
static ossl3_context_t *init_ossl3_ctx()
101+
static pthread_once_t global_ossl3_ctx_init = PTHREAD_ONCE_INIT;
102+
static ossl3_context_t *global_ossl3_ctx = NULL;
103+
104+
static void init_global_ossl3_ctx(void)
102105
{
103106
ossl3_context_t *ctx = OPENSSL_malloc(sizeof(ossl3_context_t));
104-
if (!ctx) return NULL;
107+
if (!ctx) return;
105108

106109
ctx->libctx = OSSL_LIB_CTX_new();
107110
if (!ctx->libctx) {
108111
OPENSSL_free(ctx);
109-
return NULL;
112+
return;
110113
}
111114

112115
/* Load both legacy and default provider as both may be needed */
113116
/* if they fail keep going and an error will be raised when we try to
114117
* fetch the cipher later */
115118
ctx->legacy_provider = OSSL_PROVIDER_load(ctx->libctx, "legacy");
116119
ctx->default_provider = OSSL_PROVIDER_load(ctx->libctx, "default");
117-
return ctx;
120+
global_ossl3_ctx = ctx;
121+
}
122+
123+
static ossl3_context_t *get_ossl3_ctx()
124+
{
125+
int ret;
126+
127+
ret = pthread_once(&global_ossl3_ctx_init, init_global_ossl3_ctx);
128+
if (ret != 0) {
129+
return NULL;
130+
}
131+
132+
return global_ossl3_ctx;
118133
}
119134

120-
static void free_ossl3_ctx(ossl3_context_t *ctx)
135+
__attribute__((destructor))
136+
static void free_ossl3_ctx()
121137
{
138+
ossl3_context_t *ctx = global_ossl3_ctx;
122139
if (ctx == NULL) return;
123140
if (ctx->legacy_provider) OSSL_PROVIDER_unload(ctx->legacy_provider);
124141
if (ctx->default_provider) OSSL_PROVIDER_unload(ctx->default_provider);
@@ -178,7 +195,7 @@ int MD4_HASH(struct ntlm_buffer *payload,
178195
EVP_MD *md;
179196
int ret;
180197

181-
ossl3_ctx = init_ossl3_ctx();
198+
ossl3_ctx = get_ossl3_ctx();
182199
if (ossl3_ctx == NULL) {
183200
ret = ERR_CRYPTO;
184201
goto done;
@@ -193,7 +210,6 @@ int MD4_HASH(struct ntlm_buffer *payload,
193210
ret = mdx_hash(md, payload, result);
194211

195212
done:
196-
free_ossl3_ctx(ossl3_ctx);
197213
return ret;
198214
#else
199215
return mdx_hash(EVP_md4(), payload, result);

0 commit comments

Comments
 (0)