Revert "Update to 7.40.1"
[platform/upstream/curl.git] / tests / server / sockfilt.c
index 8acad96..84b1be4 100644 (file)
@@ -5,7 +5,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
 #include "inet_pton.h"
 #include "util.h"
 #include "server_sockaddr.h"
+#include "warnless.h"
 
 /* include memdebug.h last */
 #include "memdebug.h"
 
+#ifdef USE_WINSOCK
+#undef  EINTR
+#define EINTR    4 /* errno.h value */
+#undef  EAGAIN
+#define EAGAIN  11 /* errno.h value */
+#undef  ENOMEM
+#define ENOMEM  12 /* errno.h value */
+#undef  EINVAL
+#define EINVAL  22 /* errno.h value */
+#endif
+
 #define DEFAULT_PORT 8999
 
 #ifndef DEFAULT_LOGFILE
@@ -159,6 +171,10 @@ static SIGHANDLER_T old_sigint_handler  = SIG_ERR;
 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
 #endif
 
+#if defined(SIGBREAK) && defined(WIN32)
+static SIGHANDLER_T old_sigbreak_handler = SIG_ERR;
+#endif
+
 /* var which if set indicates that the program should finish execution */
 
 SIG_ATOMIC_T got_exit_signal = 0;
@@ -174,13 +190,13 @@ static volatile int exit_signal = 0;
 
 static RETSIGTYPE exit_signal_handler(int signum)
 {
-  int old_errno = ERRNO;
+  int old_errno = errno;
   if(got_exit_signal == 0) {
     got_exit_signal = 1;
     exit_signal = signum;
   }
   (void)signal(signum, exit_signal_handler);
-  SET_ERRNO(old_errno);
+  errno = old_errno;
 }
 
 static void install_signal_handlers(void)
@@ -188,32 +204,39 @@ static void install_signal_handlers(void)
 #ifdef SIGHUP
   /* ignore SIGHUP signal */
   if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
-    logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
+    logmsg("cannot install SIGHUP handler: %s", strerror(errno));
 #endif
 #ifdef SIGPIPE
   /* ignore SIGPIPE signal */
   if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
-    logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
+    logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
 #endif
 #ifdef SIGALRM
   /* ignore SIGALRM signal */
   if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
-    logmsg("cannot install SIGALRM handler: %s", strerror(ERRNO));
+    logmsg("cannot install SIGALRM handler: %s", strerror(errno));
 #endif
 #ifdef SIGINT
   /* handle SIGINT signal with our exit_signal_handler */
   if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
-    logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
+    logmsg("cannot install SIGINT handler: %s", strerror(errno));
   else
     siginterrupt(SIGINT, 1);
 #endif
 #ifdef SIGTERM
   /* handle SIGTERM signal with our exit_signal_handler */
   if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
-    logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
+    logmsg("cannot install SIGTERM handler: %s", strerror(errno));
   else
     siginterrupt(SIGTERM, 1);
 #endif
+#if defined(SIGBREAK) && defined(WIN32)
+  /* handle SIGBREAK signal with our exit_signal_handler */
+  if((old_sigbreak_handler = signal(SIGBREAK, exit_signal_handler)) == SIG_ERR)
+    logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
+  else
+    siginterrupt(SIGBREAK, 1);
+#endif
 }
 
 static void restore_signal_handlers(void)
@@ -238,7 +261,80 @@ static void restore_signal_handlers(void)
   if(SIG_ERR != old_sigterm_handler)
     (void)signal(SIGTERM, old_sigterm_handler);
 #endif
+#if defined(SIGBREAK) && defined(WIN32)
+  if(SIG_ERR != old_sigbreak_handler)
+    (void)signal(SIGBREAK, old_sigbreak_handler);
+#endif
+}
+
+#ifdef WIN32
+/*
+ * read-wrapper to support reading from stdin on Windows.
+ */
+static ssize_t read_wincon(int fd, void *buf, size_t count)
+{
+  HANDLE handle = NULL;
+  DWORD mode, rcount = 0;
+  BOOL success;
+
+  if(fd == fileno(stdin)) {
+    handle = GetStdHandle(STD_INPUT_HANDLE);
+  }
+  else {
+    return read(fd, buf, count);
+  }
+
+  if(GetConsoleMode(handle, &mode)) {
+    success = ReadConsole(handle, buf, count, &rcount, NULL);
+  }
+  else {
+    success = ReadFile(handle, buf, count, &rcount, NULL);
+  }
+  if(success) {
+    return rcount;
+  }
+
+  errno = GetLastError();
+  return -1;
+}
+#undef  read
+#define read(a,b,c) read_wincon(a,b,c)
+
+/*
+ * write-wrapper to support writing to stdout and stderr on Windows.
+ */
+static ssize_t write_wincon(int fd, const void *buf, size_t count)
+{
+  HANDLE handle = NULL;
+  DWORD mode, wcount = 0;
+  BOOL success;
+
+  if(fd == fileno(stdout)) {
+    handle = GetStdHandle(STD_OUTPUT_HANDLE);
+  }
+  else if(fd == fileno(stderr)) {
+    handle = GetStdHandle(STD_ERROR_HANDLE);
+  }
+  else {
+    return write(fd, buf, count);
+  }
+
+  if(GetConsoleMode(handle, &mode)) {
+    success = WriteConsole(handle, buf, count, &wcount, NULL);
+  }
+  else {
+    success = WriteFile(handle, buf, count, &wcount, NULL);
+  }
+  if(success) {
+    return wcount;
+  }
+
+  errno = GetLastError();
+  return -1;
 }
+#undef  write
+#define write(a,b,c) write_wincon(a,b,c)
+#endif
 
 /*
  * fullread is a wrapper around the read() function. This will repeat the call
@@ -262,9 +358,10 @@ static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
     }
 
     if(rc < 0) {
-      error = ERRNO;
+      error = errno;
       if((error == EINTR) || (error == EAGAIN))
         continue;
+      logmsg("reading from file descriptor: %d,", filedes);
       logmsg("unrecoverable read() failure: (%d) %s",
              error, strerror(error));
       return -1;
@@ -307,9 +404,10 @@ static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
     }
 
     if(wc < 0) {
-      error = ERRNO;
+      error = errno;
       if((error == EINTR) || (error == EAGAIN))
         continue;
+      logmsg("writing to file descriptor: %d,", filedes);
       logmsg("unrecoverable write() failure: (%d) %s",
              error, strerror(error));
       return -1;
@@ -401,38 +499,182 @@ static void lograw(unsigned char *buffer, ssize_t len)
     logmsg("'%s'", data);
 }
 
+#ifdef USE_WINSOCK
 /*
  * WinSock select() does not support standard file descriptors,
  * it can only check SOCKETs. The following function is an attempt
  * to re-create a select() function with support for other handle types.
- */
-#ifdef USE_WINSOCK
-/*
- * select() function with support for WINSOCK2 sockets and all
- * other handle types supported by WaitForMultipleObjectsEx().
  *
- * TODO: Differentiate between read/write/except for non-SOCKET handles.
+ * select() function with support for WINSOCK2 sockets and all
+ * other handle types supported by WaitForMultipleObjectsEx() as
+ * well as disk files, anonymous and names pipes, and character input.
  *
  * http://msdn.microsoft.com/en-us/library/windows/desktop/ms687028.aspx
  * http://msdn.microsoft.com/en-us/library/windows/desktop/ms741572.aspx
  */
+struct select_ws_wait_data {
+  HANDLE handle; /* actual handle to wait for during select */
+  HANDLE event;  /* internal event to abort waiting thread */
+};
+static DWORD WINAPI select_ws_wait_thread(LPVOID lpParameter)
+{
+  struct select_ws_wait_data *data;
+  HANDLE handle, handles[2];
+  INPUT_RECORD inputrecord;
+  LARGE_INTEGER size, pos;
+  DWORD type, length;
+
+  /* retrieve handles from internal structure */
+  data = (struct select_ws_wait_data *) lpParameter;
+  if(data) {
+    handle = data->handle;
+    handles[0] = data->event;
+    handles[1] = handle;
+    free(data);
+  }
+  else
+    return -1;
+
+  /* retrieve the type of file to wait on */
+  type = GetFileType(handle);
+  switch(type) {
+    case FILE_TYPE_DISK:
+       /* The handle represents a file on disk, this means:
+        * - WaitForMultipleObjectsEx will always be signalled for it.
+        * - comparison of current position in file and total size of
+        *   the file can be used to check if we reached the end yet.
+        *
+        * Approach: Loop till either the internal event is signalled
+        *           or if the end of the file has already been reached.
+        */
+      while(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE)
+            == WAIT_OBJECT_0 + 1) {
+        /* get total size of file */
+        size.QuadPart = 0;
+        if(GetFileSizeEx(handle, &size)) {
+          /* get the current position within the file */
+          pos.QuadPart = 0;
+          if(SetFilePointerEx(handle, pos, &pos, FILE_CURRENT)) {
+            /* compare position with size, abort if not equal */
+            if(size.QuadPart == pos.QuadPart) {
+              /* sleep and continue waiting */
+              SleepEx(100, FALSE);
+              continue;
+            }
+          }
+        }
+        /* there is some data available, stop waiting */
+        break;
+      }
+      break;
+
+    case FILE_TYPE_CHAR:
+       /* The handle represents a character input, this means:
+        * - WaitForMultipleObjectsEx will be signalled on any kind of input,
+        *   including mouse and window size events we do not care about.
+        *
+        * Approach: Loop till either the internal event is signalled
+        *           or we get signalled for an actual key-event.
+        */
+      while(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE)
+            == WAIT_OBJECT_0 + 1) {
+        /* check if this is an actual console handle */
+        if(GetConsoleMode(handle, &length)) {
+          /* retrieve an event from the console buffer */
+          length = 0;
+          if(PeekConsoleInput(handle, &inputrecord, 1, &length)) {
+            /* check if the event is not an actual key-event */
+            if(length == 1 && inputrecord.EventType != KEY_EVENT) {
+              /* purge the non-key-event and continue waiting */
+              ReadConsoleInput(handle, &inputrecord, 1, &length);
+              continue;
+            }
+          }
+        }
+        /* there is some data available, stop waiting */
+        break;
+      }
+      break;
+
+    case FILE_TYPE_PIPE:
+       /* The handle represents an anonymous or named pipe, this means:
+        * - WaitForMultipleObjectsEx will always be signalled for it.
+        * - peek into the pipe and retrieve the amount of data available.
+        *
+        * Approach: Loop till either the internal event is signalled
+        *           or there is data in the pipe available for reading.
+        */
+      while(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE)
+            == WAIT_OBJECT_0 + 1) {
+        /* peek into the pipe and retrieve the amount of data available */
+        if(PeekNamedPipe(handle, NULL, 0, NULL, &length, NULL)) {
+          /* if there is no data available, sleep and continue waiting */
+          if(length == 0) {
+            SleepEx(100, FALSE);
+            continue;
+          }
+        }
+        else {
+          /* if the pipe has been closed, sleep and continue waiting */
+          if(GetLastError() == ERROR_BROKEN_PIPE) {
+            SleepEx(100, FALSE);
+            continue;
+          }
+        }
+        /* there is some data available, stop waiting */
+        break;
+      }
+      break;
+
+    default:
+      /* The handle has an unknown type, try to wait on it */
+      WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE);
+      break;
+  }
+
+  return 0;
+}
+static HANDLE select_ws_wait(HANDLE handle, HANDLE event)
+{
+  struct select_ws_wait_data *data;
+  HANDLE thread = NULL;
+
+  /* allocate internal waiting data structure */
+  data = malloc(sizeof(struct select_ws_wait_data));
+  if(data) {
+    data->handle = handle;
+    data->event = event;
+
+    /* launch waiting thread */
+    thread = CreateThread(NULL, 0,
+                          &select_ws_wait_thread,
+                          data, 0, NULL);
+
+    /* free data if thread failed to launch */
+    if(!thread) {
+      free(data);
+    }
+  }
+
+  return thread;
+}
 static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
                      fd_set *exceptfds, struct timeval *timeout)
 {
-  long networkevents;
-  DWORD milliseconds, wait, idx, avail, events, inputs;
+  DWORD milliseconds, wait, idx;
   WSAEVENT wsaevent, *wsaevents;
   WSANETWORKEVENTS wsanetevents;
-  INPUT_RECORD *inputrecords;
-  HANDLE handle, *handles;
-  curl_socket_t *fdarr, *wsasocks;
+  HANDLE handle, *handles, *threads;
+  curl_socket_t sock, *fdarr, *wsasocks;
+  long networkevents;
   int error, fds;
-  DWORD nfd = 0, wsa = 0;
+  HANDLE waitevent = NULL;
+  DWORD nfd = 0, thd = 0, wsa = 0;
   int ret = 0;
 
   /* check if the input value is valid */
   if(nfds < 0) {
-    SET_SOCKERRNO(EINVAL);
+    errno = EINVAL;
     return -1;
   }
 
@@ -442,31 +684,55 @@ static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
     return 0;
   }
 
+  /* create internal event to signal waiting threads */
+  waitevent = CreateEvent(NULL, TRUE, FALSE, NULL);
+  if(!waitevent) {
+    errno = ENOMEM;
+    return -1;
+  }
+
   /* allocate internal array for the original input handles */
   fdarr = malloc(nfds * sizeof(curl_socket_t));
   if(fdarr == NULL) {
-    SET_SOCKERRNO(ENOMEM);
+    errno = ENOMEM;
     return -1;
   }
 
   /* allocate internal array for the internal event handles */
   handles = malloc(nfds * sizeof(HANDLE));
   if(handles == NULL) {
-    SET_SOCKERRNO(ENOMEM);
+    free(fdarr);
+    errno = ENOMEM;
+    return -1;
+  }
+
+  /* allocate internal array for the internal threads handles */
+  threads = malloc(nfds * sizeof(HANDLE));
+  if(threads == NULL) {
+    free(handles);
+    free(fdarr);
+    errno = ENOMEM;
     return -1;
   }
 
   /* allocate internal array for the internal socket handles */
   wsasocks = malloc(nfds * sizeof(curl_socket_t));
   if(wsasocks == NULL) {
-    SET_SOCKERRNO(ENOMEM);
+    free(threads);
+    free(handles);
+    free(fdarr);
+    errno = ENOMEM;
     return -1;
   }
 
   /* allocate internal array for the internal WINSOCK2 events */
   wsaevents = malloc(nfds * sizeof(WSAEVENT));
   if(wsaevents == NULL) {
-    SET_SOCKERRNO(ENOMEM);
+    free(threads);
+    free(wsasocks);
+    free(handles);
+    free(fdarr);
+    errno = ENOMEM;
     return -1;
   }
 
@@ -482,13 +748,17 @@ static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
       networkevents |= FD_WRITE|FD_CONNECT;
 
     if(FD_ISSET(fds, exceptfds))
-      networkevents |= FD_OOB;
+      networkevents |= FD_OOB|FD_CLOSE;
 
     /* only wait for events for which we actually care */
     if(networkevents) {
-      fdarr[nfd] = (curl_socket_t)fds;
+      fdarr[nfd] = curlx_sitosk(fds);
       if(fds == fileno(stdin)) {
-        handles[nfd] = GetStdHandle(STD_INPUT_HANDLE);
+        handle = GetStdHandle(STD_INPUT_HANDLE);
+        handle = select_ws_wait(handle, waitevent);
+        handles[nfd] = handle;
+        threads[thd] = handle;
+        thd++;
       }
       else if(fds == fileno(stdout)) {
         handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE);
@@ -501,14 +771,19 @@ static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
         if(wsaevent != WSA_INVALID_EVENT) {
           error = WSAEventSelect(fds, wsaevent, networkevents);
           if(error != SOCKET_ERROR) {
-            handles[nfd] = wsaevent;
-            wsasocks[wsa] = (curl_socket_t)fds;
+            handle = (HANDLE) wsaevent;
+            handles[nfd] = handle;
+            wsasocks[wsa] = curlx_sitosk(fds);
             wsaevents[wsa] = wsaevent;
             wsa++;
           }
           else {
-            handles[nfd] = (HANDLE)fds;
             WSACloseEvent(wsaevent);
+            handle = (HANDLE) curlx_sitosk(fds);
+            handle = select_ws_wait(handle, waitevent);
+            handles[nfd] = handle;
+            threads[thd] = handle;
+            thd++;
           }
         }
       }
@@ -527,89 +802,68 @@ static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
   /* wait for one of the internal handles to trigger */
   wait = WaitForMultipleObjectsEx(nfd, handles, FALSE, milliseconds, FALSE);
 
+  /* signal the event handle for the waiting threads */
+  SetEvent(waitevent);
+
   /* loop over the internal handles returned in the descriptors */
   for(idx = 0; idx < nfd; idx++) {
-    fds = fdarr[idx];
     handle = handles[idx];
+    sock = fdarr[idx];
+    fds = curlx_sktosi(sock);
 
     /* check if the current internal handle was triggered */
-    if(wait != WAIT_FAILED && (wait - WAIT_OBJECT_0) >= idx &&
+    if(wait != WAIT_FAILED && (wait - WAIT_OBJECT_0) <= idx &&
        WaitForSingleObjectEx(handle, 0, FALSE) == WAIT_OBJECT_0) {
-      /* try to handle the event with STD* handle functions */
+      /* first handle stdin, stdout and stderr */
       if(fds == fileno(stdin)) {
-        /* check if there is no data in the input buffer */
-        if(!stdin->_cnt) {
-          /* check if we are getting data from a PIPE */
-          if(!GetConsoleMode(handle, &avail)) {
-            /* check if there is no data from PIPE input */
-            if(!PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL))
-              avail = 0;
-            if(!avail)
-              FD_CLR(fds, readfds);
-          } /* check if there is no data from keyboard input */
-          else if (!_kbhit()) {
-            /* check if there are INPUT_RECORDs in the input buffer */
-            if(GetNumberOfConsoleInputEvents(handle, &events)) {
-              if(events > 0) {
-                /* remove INPUT_RECORDs from the input buffer */
-                inputrecords = (INPUT_RECORD*)malloc(events *
-                                                     sizeof(INPUT_RECORD));
-                if(inputrecords) {
-                  if(!ReadConsoleInput(handle, inputrecords,
-                                       events, &inputs))
-                    inputs = 0;
-                  free(inputrecords);
-                }
-
-                /* check if we got all inputs, otherwise clear buffer */
-                if(events != inputs)
-                  FlushConsoleInputBuffer(handle);
-              }
-            }
-
-            /* remove from descriptor set since there is no real data */
-            FD_CLR(fds, readfds);
-          }
-        }
-
         /* stdin is never ready for write or exceptional */
-        FD_CLR(fds, writefds);
-        FD_CLR(fds, exceptfds);
+        FD_CLR(sock, writefds);
+        FD_CLR(sock, exceptfds);
       }
       else if(fds == fileno(stdout) || fds == fileno(stderr)) {
         /* stdout and stderr are never ready for read or exceptional */
-        FD_CLR(fds, readfds);
-        FD_CLR(fds, exceptfds);
+        FD_CLR(sock, readfds);
+        FD_CLR(sock, exceptfds);
       }
       else {
         /* try to handle the event with the WINSOCK2 functions */
-        error = WSAEnumNetworkEvents(fds, NULL, &wsanetevents);
+        wsanetevents.lNetworkEvents = 0;
+        error = WSAEnumNetworkEvents(fds, handle, &wsanetevents);
         if(error != SOCKET_ERROR) {
           /* remove from descriptor set if not ready for read/accept/close */
           if(!(wsanetevents.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE)))
-            FD_CLR(fds, readfds);
+            FD_CLR(sock, readfds);
 
           /* remove from descriptor set if not ready for write/connect */
           if(!(wsanetevents.lNetworkEvents & (FD_WRITE|FD_CONNECT)))
-            FD_CLR(fds, writefds);
-
+            FD_CLR(sock, writefds);
+
+          /* HACK:
+           * use exceptfds together with readfds to signal
+           * that the connection was closed by the client.
+           *
+           * Reason: FD_CLOSE is only signaled once, sometimes
+           * at the same time as FD_READ with data being available.
+           * This means that recv/sread is not reliable to detect
+           * that the connection is closed.
+           */
           /* remove from descriptor set if not exceptional */
-          if(!(wsanetevents.lNetworkEvents & FD_OOB))
-            FD_CLR(fds, exceptfds);
+          if(!(wsanetevents.lNetworkEvents & (FD_OOB|FD_CLOSE)))
+            FD_CLR(sock, exceptfds);
         }
       }
 
       /* check if the event has not been filtered using specific tests */
-      if(FD_ISSET(fds, readfds) || FD_ISSET(fds, writefds) ||
-         FD_ISSET(fds, exceptfds)) {
+      if(FD_ISSET(sock, readfds) || FD_ISSET(sock, writefds) ||
+         FD_ISSET(sock, exceptfds)) {
         ret++;
       }
     }
     else {
       /* remove from all descriptor sets since this handle did not trigger */
-      FD_CLR(fds, readfds);
-      FD_CLR(fds, writefds);
-      FD_CLR(fds, exceptfds);
+      FD_CLR(sock, readfds);
+      FD_CLR(sock, writefds);
+      FD_CLR(sock, exceptfds);
     }
   }
 
@@ -618,15 +872,23 @@ static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
     WSACloseEvent(wsaevents[idx]);
   }
 
+  for(idx = 0; idx < thd; idx++) {
+    WaitForSingleObject(threads[thd], INFINITE);
+    CloseHandle(threads[thd]);
+  }
+
+  CloseHandle(waitevent);
+
   free(wsaevents);
   free(wsasocks);
+  free(threads);
   free(handles);
   free(fdarr);
 
   return ret;
 }
 #define select(a,b,c,d,e) select_ws(a,b,c,d,e)
-#endif
+#endif  /* USE_WINSOCK */
 
 /*
   sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
@@ -700,6 +962,9 @@ static bool juggle(curl_socket_t *sockfdp,
     else {
       /* there's always a socket to wait for */
       FD_SET(sockfd, &fds_read);
+#ifdef USE_WINSOCK
+      FD_SET(sockfd, &fds_err);
+#endif
       maxfd = (int)sockfd;
     }
     break;
@@ -710,6 +975,9 @@ static bool juggle(curl_socket_t *sockfdp,
     /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
     if(CURL_SOCKET_BAD != sockfd) {
       FD_SET(sockfd, &fds_read);
+#ifdef USE_WINSOCK
+      FD_SET(sockfd, &fds_err);
+#endif
       maxfd = (int)sockfd;
     }
     else {
@@ -739,7 +1007,7 @@ static bool juggle(curl_socket_t *sockfdp,
       return FALSE;
     }
 
-  } while((rc == -1) && ((error = SOCKERRNO) == EINTR));
+  } while((rc == -1) && ((error = errno) == EINTR));
 
   if(rc < 0) {
     logmsg("select() failed with error: (%d) %s",
@@ -853,21 +1121,22 @@ static bool juggle(curl_socket_t *sockfdp,
 
   if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
 
+    curl_socket_t newfd = CURL_SOCKET_BAD; /* newly accepted socket */
+
     if(*mode == PASSIVE_LISTEN) {
       /* there's no stream set up yet, this is an indication that there's a
          client connecting. */
-      listenfd = sockfd;
-      sockfd = accept(listenfd, NULL, NULL);
-      if(CURL_SOCKET_BAD == sockfd) {
+      newfd = accept(sockfd, NULL, NULL);
+      if(CURL_SOCKET_BAD == newfd) {
         error = SOCKERRNO;
         logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s",
-               listenfd, error, strerror(error));
+               sockfd, error, strerror(error));
       }
       else {
         logmsg("====> Client connect");
         if(!write_stdout("CNCT\n", 5))
           return FALSE;
-        *sockfdp = sockfd; /* store the new socket */
+        *sockfdp = newfd; /* store the new socket */
         *mode = PASSIVE_CONNECT; /* we have connected */
       }
       return TRUE;
@@ -876,7 +1145,22 @@ static bool juggle(curl_socket_t *sockfdp,
     /* read from socket, pass on data to stdout */
     nread_socket = sread(sockfd, buffer, sizeof(buffer));
 
-    if(nread_socket <= 0) {
+    if(nread_socket > 0) {
+      snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
+      if(!write_stdout(data, 10))
+        return FALSE;
+      if(!write_stdout(buffer, nread_socket))
+        return FALSE;
+
+      logmsg("< %zd bytes data, client => server", nread_socket);
+      lograw(buffer, nread_socket);
+    }
+
+    if(nread_socket <= 0
+#ifdef USE_WINSOCK
+       || FD_ISSET(sockfd, &fds_err)
+#endif
+       ) {
       logmsg("====> Client disconnect");
       if(!write_stdout("DISC\n", 5))
         return FALSE;
@@ -888,15 +1172,6 @@ static bool juggle(curl_socket_t *sockfdp,
         *mode = ACTIVE_DISCONNECT;
       return TRUE;
     }
-
-    snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
-    if(!write_stdout(data, 10))
-      return FALSE;
-    if(!write_stdout(buffer, nread_socket))
-      return FALSE;
-
-    logmsg("< %zd bytes data, client => server", nread_socket);
-    lograw(buffer, nread_socket);
   }
 
   return TRUE;
@@ -928,7 +1203,7 @@ static curl_socket_t sockdaemon(curl_socket_t sock,
         rc = wait_ms(delay);
         if(rc) {
           /* should not happen */
-          error = SOCKERRNO;
+          error = errno;
           logmsg("wait_ms() failed with error: (%d) %s",
                  error, strerror(error));
           sclose(sock);