Fix bug with non-blocking I/O and cookies
diff --git a/include/polarssl/ssl.h b/include/polarssl/ssl.h
index ddbac58..202a200 100644
--- a/include/polarssl/ssl.h
+++ b/include/polarssl/ssl.h
@@ -516,6 +516,7 @@
     SSL_HANDSHAKE_WRAPUP,
     SSL_HANDSHAKE_OVER,
     SSL_SERVER_NEW_SESSION_TICKET,
+    SSL_SERVER_HELLO_VERIFY_REQUEST_SENT,
 }
 ssl_states;
 
diff --git a/library/ssl_srv.c b/library/ssl_srv.c
index 219fc01..3cd87f9 100644
--- a/library/ssl_srv.c
+++ b/library/ssl_srv.c
@@ -2052,7 +2052,7 @@
     ssl->out_msgtype = SSL_MSG_HANDSHAKE;
     ssl->out_msg[0]  = SSL_HS_HELLO_VERIFY_REQUEST;
 
-    ssl->state = SSL_CLIENT_HELLO;
+    ssl->state = SSL_SERVER_HELLO_VERIFY_REQUEST_SENT;
 
     if( ( ret = ssl_write_record( ssl ) ) != 0 )
     {
@@ -2084,13 +2084,7 @@
         SSL_DEBUG_MSG( 2, ( "client hello was not authenticated" ) );
         SSL_DEBUG_MSG( 2, ( "<= write server hello" ) );
 
-        if( ( ret = ssl_write_hello_verify_request( ssl ) ) != 0 )
-        {
-            SSL_DEBUG_RET( 1, "ssl_write_hello_verify_request", ret );
-            return( ret );
-        }
-
-        return( POLARSSL_ERR_SSL_HELLO_VERIFY_REQUIRED );
+        return( ssl_write_hello_verify_request( ssl ) );
     }
 #endif /* POLARSSL_SSL_DTLS_HELLO_VERIFY */
 
@@ -3534,6 +3528,11 @@
             ret = ssl_parse_client_hello( ssl );
             break;
 
+#if defined(POLARSSL_SSL_PROTO_DTLS)
+        case SSL_SERVER_HELLO_VERIFY_REQUEST_SENT:
+            return( POLARSSL_ERR_SSL_HELLO_VERIFY_REQUIRED );
+#endif
+
         /*
          *  ==>   ServerHello
          *        Certificate
diff --git a/tests/ssl-opt.sh b/tests/ssl-opt.sh
index 09a94f1..a657f79 100755
--- a/tests/ssl-opt.sh
+++ b/tests/ssl-opt.sh
@@ -2046,6 +2046,16 @@
             -c "received hello verify request" \
             -S "SSL - The requested feature is not available"
 
+run_test    "DTLS cookie: enabled, nbio" \
+            "$P_SRV dtls=1 nbio=2 debug_level=2" \
+            "$P_CLI dtls=1 nbio=2 debug_level=2" \
+            0 \
+            -s "cookie verification failed" \
+            -s "cookie verification passed" \
+            -S "cookie verification skipped" \
+            -c "received hello verify request" \
+            -S "SSL - The requested feature is not available"
+
 # Tests for various cases of client authentication with DTLS
 # (focused on handshake flows and message parsing)