@@ -141,16 +141,15 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) {
141141 const byte seed [] = "upy" ;
142142 ret = mbedtls_ctr_drbg_seed (& o -> ctr_drbg , null_entropy_func /*mbedtls_entropy_func*/ , & o -> entropy , seed , sizeof (seed ));
143143 if (ret != 0 ) {
144- printf ("ret=%d\n" , ret );
145- assert (0 );
144+ goto cleanup ;
146145 }
147146
148147 ret = mbedtls_ssl_config_defaults (& o -> conf ,
149148 args -> server_side .u_bool ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT ,
150149 MBEDTLS_SSL_TRANSPORT_STREAM ,
151150 MBEDTLS_SSL_PRESET_DEFAULT );
152151 if (ret != 0 ) {
153- assert ( 0 ) ;
152+ goto cleanup ;
154153 }
155154
156155 mbedtls_ssl_conf_authmode (& o -> conf , MBEDTLS_SSL_VERIFY_NONE );
@@ -161,14 +160,14 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) {
161160
162161 ret = mbedtls_ssl_setup (& o -> ssl , & o -> conf );
163162 if (ret != 0 ) {
164- assert ( 0 ) ;
163+ goto cleanup ;
165164 }
166165
167166 if (args -> server_hostname .u_obj != mp_const_none ) {
168167 const char * sni = mp_obj_str_get_str (args -> server_hostname .u_obj );
169168 ret = mbedtls_ssl_set_hostname (& o -> ssl , sni );
170169 if (ret != 0 ) {
171- assert ( 0 ) ;
170+ goto cleanup ;
172171 }
173172 }
174173
@@ -194,13 +193,27 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) {
194193
195194 while ((ret = mbedtls_ssl_handshake (& o -> ssl )) != 0 ) {
196195 if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE ) {
197- //assert(0);
198196 printf ("mbedtls_ssl_handshake error: -%x\n" , - ret );
199- mp_raise_OSError ( MP_EIO ) ;
197+ goto cleanup ;
200198 }
201199 }
202200
203201 return o ;
202+
203+ cleanup :
204+ mbedtls_pk_free (& o -> pkey );
205+ mbedtls_x509_crt_free (& o -> cert );
206+ mbedtls_x509_crt_free (& o -> cacert );
207+ mbedtls_ssl_free (& o -> ssl );
208+ mbedtls_ssl_config_free (& o -> conf );
209+ mbedtls_ctr_drbg_free (& o -> ctr_drbg );
210+ mbedtls_entropy_free (& o -> entropy );
211+
212+ if (ret == MBEDTLS_ERR_SSL_ALLOC_FAILED ) {
213+ mp_raise_OSError (MP_ENOMEM );
214+ } else {
215+ mp_raise_OSError (MP_EIO );
216+ }
204217}
205218
206219STATIC mp_obj_t mod_ssl_getpeercert (mp_obj_t o_in , mp_obj_t binary_form ) {
0 commit comments