From d2747487e320a858db9512ef1ec2ca9637a7d0df Mon Sep 17 00:00:00 2001 From: Benjamin Sergeant Date: Thu, 6 Jun 2019 14:59:22 -0700 Subject: [PATCH] IXSocketMbedTLS: better error handling in close and connect --- CHANGELOG.md | 4 ++++ ixwebsocket/IXSocketMbedTLS.cpp | 23 ++++++++++++++++++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d391b395..9be8259b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,10 @@ # Changelog All notable changes to this project will be documented in this file. +## [Unreleased] - 2019-06-xx +### Changed +- IXSocketMbedTLS: better error handling in close and connect + ## [3.1.2] - 2019-06-06 ### Added - ws connect has a -x option to disable per message deflate diff --git a/ixwebsocket/IXSocketMbedTLS.cpp b/ixwebsocket/IXSocketMbedTLS.cpp index af8f744d..91d696c1 100644 --- a/ixwebsocket/IXSocketMbedTLS.cpp +++ b/ixwebsocket/IXSocketMbedTLS.cpp @@ -24,6 +24,8 @@ namespace ix bool SocketMbedTLS::init(const std::string& host, std::string& errMsg) { + std::lock_guard lock(_mutex); + mbedtls_ssl_init(&_ssl); mbedtls_ssl_config_init(&_conf); mbedtls_ctr_drbg_init(&_ctr_drbg); @@ -75,15 +77,24 @@ namespace ix std::string& errMsg, const CancellationRequest& isCancellationRequested) { - _sockfd = SocketConnect::connect(host, port, errMsg, isCancellationRequested); - if (_sockfd == -1) return false; - if (!init(host, errMsg)) return false; + { + std::lock_guard lock(_mutex); + _sockfd = SocketConnect::connect(host, port, errMsg, isCancellationRequested); + if (_sockfd == -1) return false; + } + + if (!init(host, errMsg)) + { + close(); + return false; + } mbedtls_ssl_set_bio(&_ssl, &_sockfd, mbedtls_net_send, mbedtls_net_recv, NULL); int res; do { + std::lock_guard lock(_mutex); res = mbedtls_ssl_handshake(&_ssl); } while (res == MBEDTLS_ERR_SSL_WANT_READ || res == MBEDTLS_ERR_SSL_WANT_WRITE); @@ -95,6 +106,8 @@ namespace ix errMsg = "error in handshake : "; errMsg += buf; + + close(); return false; } @@ -103,10 +116,14 @@ namespace ix void SocketMbedTLS::close() { + std::lock_guard lock(_mutex); + mbedtls_ssl_free(&_ssl); mbedtls_ssl_config_free(&_conf); mbedtls_ctr_drbg_free(&_ctr_drbg); mbedtls_entropy_free(&_entropy); + + Socket::close(); } ssize_t SocketMbedTLS::send(char* buf, size_t nbyte)