From 1e7c3d2500404c89ab021561595a2ec5a68a0513 Mon Sep 17 00:00:00 2001
From: Paul Bakker
Date: Mon, 7 Jul 2014 16:41:31 +0200
Subject: [PATCH] net_is_block() renamed to net_would_block() and corrected
behaviour on non-blocking sockets
net_would_block() now does not return 1 if the socket is blocking.
---
library/net.c | 38 ++++++++++++++++++++++++++++----------
1 file changed, 28 insertions(+), 10 deletions(-)
diff --git a/library/net.c b/library/net.c
index cb615a513..3e1446694 100644
--- a/library/net.c
+++ b/library/net.c
@@ -216,14 +216,30 @@ int net_bind( int *fd, const char *bind_ip, int port )
return( 0 );
}
+#if ( defined(_WIN32) || defined(_WIN32_WCE) )
/*
- * Check if the current operation is blocking
+ * Check if the requested operation would be blocking on a non-blocking socket
+ * and thus 'failed' with a negative return value.
*/
-static int net_is_blocking( void )
+static int net_would_block( int fd )
{
-#if defined(_WIN32) || defined(_WIN32_WCE)
return( WSAGetLastError() == WSAEWOULDBLOCK );
+}
#else
+/*
+ * Check if the requested operation would be blocking on a non-blocking socket
+ * and thus 'failed' with a negative return value.
+ *
+ * Note: on a blocking socket this function always returns 0!
+ */
+static int net_would_block( int fd )
+{
+ /*
+ * Never return 'WOULD BLOCK' on a non-blocking socket
+ */
+ if( ( fcntl( fd, F_GETFL ) & O_NONBLOCK ) != O_NONBLOCK )
+ return( 0 );
+
switch( errno )
{
#if defined EAGAIN
@@ -235,8 +251,8 @@ static int net_is_blocking( void )
return( 1 );
}
return( 0 );
-#endif
}
+#endif
/*
* Accept a connection from a remote client
@@ -257,7 +273,7 @@ int net_accept( int bind_fd, int *client_fd, void *client_ip )
if( *client_fd < 0 )
{
- if( net_is_blocking() != 0 )
+ if( net_would_block( *client_fd ) != 0 )
return( POLARSSL_ERR_NET_WANT_READ );
return( POLARSSL_ERR_NET_ACCEPT_FAILED );
@@ -308,12 +324,13 @@ void net_usleep( unsigned long usec )
* Read at most 'len' characters
*/
int net_recv( void *ctx, unsigned char *buf, size_t len )
-{
- int ret = read( *((int *) ctx), buf, len );
+{
+ int fd = *((int *) ctx);
+ int ret = read( fd, buf, len );
if( ret < 0 )
{
- if( net_is_blocking() != 0 )
+ if( net_would_block( fd ) != 0 )
return( POLARSSL_ERR_NET_WANT_READ );
#if defined(_WIN32) || defined(_WIN32_WCE)
@@ -338,11 +355,12 @@ int net_recv( void *ctx, unsigned char *buf, size_t len )
*/
int net_send( void *ctx, const unsigned char *buf, size_t len )
{
- int ret = write( *((int *) ctx), buf, len );
+ int fd = *((int *) ctx);
+ int ret = write( fd, buf, len );
if( ret < 0 )
{
- if( net_is_blocking() != 0 )
+ if( net_would_block( fd ) != 0 )
return( POLARSSL_ERR_NET_WANT_WRITE );
#if defined(_WIN32) || defined(_WIN32_WCE)