Skip to content

Commit

Permalink
Fix SSL context refcount
Browse files Browse the repository at this point in the history
  • Loading branch information
twose committed Dec 6, 2023
1 parent 92bb165 commit bc6ec0a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
2 changes: 2 additions & 0 deletions include/cat_ssl.h
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,8 @@ typedef struct cat_ssl_s {
cat_buffer_t write_buffer;
/* options */
cat_bool_t allow_self_signed;
/* internals */
cat_ssl_context_t *context; // for free data before SSL_free()
} cat_ssl_t;

typedef enum cat_ssl_ret_e {
Expand Down
17 changes: 14 additions & 3 deletions src/cat_ssl.c
Original file line number Diff line number Diff line change
Expand Up @@ -230,9 +230,8 @@ CAT_API cat_ssl_context_t *cat_ssl_context_create(cat_ssl_method_t method, cat_s
return NULL;
}

CAT_API void cat_ssl_context_close(cat_ssl_context_t *context)
static cat_always_inline void cat_ssl_context_close_data(cat_ssl_context_t *context)
{
SSL_CTX_free(context->ctx);
if (CAT_REF_DEL(context) != 0) {
return;
}
Expand All @@ -241,6 +240,12 @@ CAT_API void cat_ssl_context_close(cat_ssl_context_t *context)
cat_free(context);
}

CAT_API void cat_ssl_context_close(cat_ssl_context_t *context)
{
SSL_CTX_free(context->ctx);
cat_ssl_context_close_data(context);
}

CAT_API void cat_ssl_context_set_protocols(cat_ssl_context_t *context, cat_ssl_protocols_t protocols)
{
cat_ssl_ctx_t *ctx = context->ctx;
Expand Down Expand Up @@ -697,6 +702,7 @@ CAT_API cat_ssl_t *cat_ssl_create(cat_ssl_t *ssl, cat_ssl_context_t *context)
cat_ssl_update_last_error(CAT_ESSL, "SSL_new() failed");
goto _new_failed;
}
CAT_REF_ADD(context);

/* malloc for SSL handle */
if (ssl == NULL) {
Expand Down Expand Up @@ -736,6 +742,7 @@ CAT_API cat_ssl_t *cat_ssl_create(cat_ssl_t *ssl, cat_ssl_context_t *context)

/* init ssl fields */
ssl->connection = connection;
ssl->context = context;
ssl->allow_self_signed = cat_false;

return ssl;
Expand All @@ -745,8 +752,11 @@ CAT_API cat_ssl_t *cat_ssl_create(cat_ssl_t *ssl, cat_ssl_context_t *context)
BIO_free(ssl->nbio);
_set_ex_data_failed:
_new_bio_pair_failed:
CAT_REF_DEL(context);
/* When context can be passed as a parameter,
* its reference count must be greater than or equal to 1. */
CAT_ASSERT(CAT_REF_GET(context) >= 1);
SSL_free(connection);
ssl->connection = NULL;
#if CAT_ALLOC_HANDLE_ERRORS
_malloc_failed:
#endif
Expand All @@ -763,6 +773,7 @@ CAT_API void cat_ssl_close(cat_ssl_t *ssl)
cat_buffer_close(&ssl->read_buffer);
/* ibio will be free'd by SSL_free */
BIO_free(ssl->nbio);
cat_ssl_context_close_data(ssl->context);
/* implicitly frees internal_bio */
SSL_free(ssl->connection);
/* free */
Expand Down

0 comments on commit bc6ec0a

Please sign in to comment.