Add guards for closed socket in net.c
This is particularly problematic when calling FD_SET( -1, ... ), but let's
check it in all functions.
This was introduced with the new API and the fact the net_free() now sets the
internal fd to -1 in order to mark it as closed: now using this information.
diff --git a/include/mbedtls/error.h b/include/mbedtls/error.h
index cb5a697..1ffb876 100644
--- a/include/mbedtls/error.h
+++ b/include/mbedtls/error.h
@@ -62,7 +62,7 @@
* DES 1 0x0032-0x0032
* CTR_DBRG 4 0x0034-0x003A
* ENTROPY 3 0x003C-0x0040 0x003D-0x003F
- * NET 9 0x0042-0x0052 0x0043-0x0043
+ * NET 11 0x0042-0x0052 0x0043-0x0045
* ASN1 7 0x0060-0x006C
* PBKDF2 1 0x007C-0x007C
* HMAC_DRBG 4 0x0003-0x0009
diff --git a/include/mbedtls/net.h b/include/mbedtls/net.h
index 19746e5..1c49763 100644
--- a/include/mbedtls/net.h
+++ b/include/mbedtls/net.h
@@ -45,6 +45,7 @@
#define MBEDTLS_ERR_NET_CONN_RESET -0x0050 /**< Connection was reset by peer. */
#define MBEDTLS_ERR_NET_UNKNOWN_HOST -0x0052 /**< Failed to get an IP address for the given hostname. */
#define MBEDTLS_ERR_NET_BUFFER_TOO_SMALL -0x0043 /**< Buffer is too small to hold the data. */
+#define MBEDTLS_ERR_NET_INVALID_CONTEXT -0x0045 /**< The context is invalid, eg because it was free()ed. */
#define MBEDTLS_NET_LISTEN_BACKLOG 10 /**< The backlog that listen() should use. */
diff --git a/library/error.c b/library/error.c
index 21be423..e78057b 100644
--- a/library/error.c
+++ b/library/error.c
@@ -640,6 +640,8 @@
mbedtls_snprintf( buf, buflen, "NET - Failed to get an IP address for the given hostname" );
if( use_ret == -(MBEDTLS_ERR_NET_BUFFER_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "NET - Buffer is too small to hold the data" );
+ if( use_ret == -(MBEDTLS_ERR_NET_INVALID_CONTEXT) )
+ mbedtls_snprintf( buf, buflen, "NET - The context is invalid, eg because it was free()ed" );
#endif /* MBEDTLS_NET_C */
#if defined(MBEDTLS_OID_C)
diff --git a/library/net.c b/library/net.c
index 3c69646..bcec232 100644
--- a/library/net.c
+++ b/library/net.c
@@ -448,8 +448,13 @@
*/
int mbedtls_net_recv( void *ctx, unsigned char *buf, size_t len )
{
+ int ret;
int fd = ((mbedtls_net_context *) ctx)->fd;
- int ret = (int) read( fd, buf, len );
+
+ if( fd < 0 )
+ return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
+
+ ret = (int) read( fd, buf, len );
if( ret < 0 )
{
@@ -485,6 +490,9 @@
fd_set read_fds;
int fd = ((mbedtls_net_context *) ctx)->fd;
+ if( fd < 0 )
+ return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
+
FD_ZERO( &read_fds );
FD_SET( fd, &read_fds );
@@ -520,8 +528,13 @@
*/
int mbedtls_net_send( void *ctx, const unsigned char *buf, size_t len )
{
+ int ret;
int fd = ((mbedtls_net_context *) ctx)->fd;
- int ret = (int) write( fd, buf, len );
+
+ if( fd < 0 )
+ return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
+
+ ret = (int) write( fd, buf, len );
if( ret < 0 )
{