@@ -166,6 +166,13 @@ static NORETURN void mbedtls_raise_error(int err) {
166166 #endif
167167}
168168
169+ // Stores the current SSLContext for use in mbedtls callbacks where the current state is not passed.
170+ static inline void store_active_context (mp_obj_ssl_context_t * ssl_context ) {
171+ #if MICROPY_PY_SSL_MBEDTLS_NEED_ACTIVE_CONTEXT
172+ MP_STATE_THREAD (tls_ssl_context ) = ssl_context ;
173+ #endif
174+ }
175+
169176static void ssl_check_async_handshake_failure (mp_obj_ssl_socket_t * sslsock , int * errcode ) {
170177 if (
171178 #if MBEDTLS_VERSION_NUMBER >= 0x03000000
@@ -497,6 +504,9 @@ static int _mbedtls_ssl_recv(void *ctx, byte *buf, size_t len) {
497504static mp_obj_t ssl_socket_make_new (mp_obj_ssl_context_t * ssl_context , mp_obj_t sock ,
498505 bool server_side , bool do_handshake_on_connect , mp_obj_t server_hostname ) {
499506
507+ // Store the current SSL context.
508+ store_active_context (ssl_context );
509+
500510 // Verify the socket object has the full stream protocol
501511 mp_get_stream_raise (sock , MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL );
502512
@@ -602,6 +612,9 @@ static mp_uint_t socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errc
602612 return MP_STREAM_ERROR ;
603613 }
604614
615+ // Store the current SSL context.
616+ store_active_context (o -> ssl_context );
617+
605618 int ret = mbedtls_ssl_read (& o -> ssl , buf , size );
606619 if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ) {
607620 // end of stream
@@ -643,6 +656,9 @@ static mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, in
643656 return MP_STREAM_ERROR ;
644657 }
645658
659+ // Store the current SSL context.
660+ store_active_context (o -> ssl_context );
661+
646662 int ret = mbedtls_ssl_write (& o -> ssl , buf , size );
647663 if (ret >= 0 ) {
648664 return ret ;
@@ -680,6 +696,9 @@ static mp_uint_t socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, i
680696 mp_obj_t sock = self -> sock ;
681697
682698 if (request == MP_STREAM_CLOSE ) {
699+ // Clear the SSL context.
700+ store_active_context (NULL );
701+
683702 if (sock == MP_OBJ_NULL ) {
684703 // Already closed socket, do nothing.
685704 return 0 ;
0 commit comments