Base code merged to SPIN 2.4
[platform/upstream/curl.git] / tests / server / sockfilt.c
index 0ceaae2..a4496e0 100644 (file)
@@ -23,7 +23,7 @@
 
 /* Purpose
  *
- * 1. Accept a TCP connection on a custom port (ipv4 or ipv6), or connect
+ * 1. Accept a TCP connection on a custom port (IPv4 or IPv6), or connect
  *    to a given (localhost) port.
  *
  * 2. Get commands on STDIN. Pass data on to the TCP stream.
@@ -285,10 +285,10 @@ static ssize_t read_wincon(int fd, void *buf, size_t count)
   }
 
   if(GetConsoleMode(handle, &mode)) {
-    success = ReadConsole(handle, buf, count, &rcount, NULL);
+    success = ReadConsole(handle, buf, curlx_uztoul(count), &rcount, NULL);
   }
   else {
-    success = ReadFile(handle, buf, count, &rcount, NULL);
+    success = ReadFile(handle, buf, curlx_uztoul(count), &rcount, NULL);
   }
   if(success) {
     return rcount;
@@ -320,10 +320,10 @@ static ssize_t write_wincon(int fd, const void *buf, size_t count)
   }
 
   if(GetConsoleMode(handle, &mode)) {
-    success = WriteConsole(handle, buf, count, &wcount, NULL);
+    success = WriteConsole(handle, buf, curlx_uztoul(count), &wcount, NULL);
   }
   else {
-    success = WriteFile(handle, buf, count, &wcount, NULL);
+    success = WriteFile(handle, buf, curlx_uztoul(count), &wcount, NULL);
   }
   if(success) {
     return wcount;
@@ -506,102 +506,185 @@ static void lograw(unsigned char *buffer, ssize_t len)
  * to re-create a select() function with support for other handle types.
  *
  * 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.
+ * 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
  */
-static DWORD WINAPI select_ws_stdin_wait_thread(LPVOID lpParameter)
+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;
 
-  handle = GetStdHandle(STD_INPUT_HANDLE);
-  handles[0] = (HANDLE) lpParameter;
-  handles[1] = handle;
-  type = GetFileType(handle);
+  /* 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 */
+        length = 0;
         size.QuadPart = 0;
-        if(GetFileSizeEx(handle, &size)) {
+        size.LowPart = GetFileSize(handle, &length);
+        if((size.LowPart != INVALID_FILE_SIZE) ||
+           (GetLastError() == NO_ERROR)) {
+          size.HighPart = length;
+          /* get the current position within the file */
           pos.QuadPart = 0;
-          if(SetFilePointerEx(handle, pos, &pos, FILE_CURRENT)) {
-            if(size.QuadPart == pos.QuadPart)
-              SleepEx(100, FALSE);
-            else
-              break;
+          pos.LowPart = SetFilePointer(handle, 0, &pos.HighPart, FILE_CURRENT);
+          if((pos.LowPart != INVALID_SET_FILE_POINTER) ||
+             (GetLastError() == NO_ERROR)) {
+            /* compare position with size, abort if not equal */
+            if(size.QuadPart == pos.QuadPart) {
+              /* sleep and continue waiting */
+              SleepEx(0, FALSE);
+              continue;
+            }
           }
-          else
-            break;
         }
-        else
-          break;
+        /* 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 */
+        length = 0;
         if(GetConsoleMode(handle, &length)) {
+          /* retrieve an event from the console buffer */
           length = 0;
           if(PeekConsoleInput(handle, &inputrecord, 1, &length)) {
-            if(length == 1 && inputrecord.EventType != KEY_EVENT)
+            /* 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);
-            else
-              break;
+              continue;
+            }
           }
-          else
-            break;
         }
-        else
-          break;
+        /* 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 */
+        length = 0;
         if(PeekNamedPipe(handle, NULL, 0, NULL, &length, NULL)) {
-          if(length == 0)
-            SleepEx(100, FALSE);
-          else
-            break;
+          /* if there is no data available, sleep and continue waiting */
+          if(length == 0) {
+            SleepEx(0, FALSE);
+            continue;
+          }
         }
         else {
-          if(GetLastError() == ERROR_BROKEN_PIPE)
-            SleepEx(100, FALSE);
-          else
-            break;
+          /* if the pipe has been closed, sleep and continue waiting */
+          if(GetLastError() == ERROR_BROKEN_PIPE) {
+            SleepEx(0, 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;
+}
+struct select_ws_data {
+  curl_socket_t fd;      /* the original input handle   (indexed by fds) */
+  curl_socket_t wsasock; /* the internal socket handle  (indexed by wsa) */
+  WSAEVENT wsaevent;     /* the internal WINSOCK2 event (indexed by wsa) */
+  HANDLE thread;         /* the internal threads handle (indexed by thd) */
+};
 static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
                      fd_set *exceptfds, struct timeval *timeout)
 {
   DWORD milliseconds, wait, idx;
-  WSAEVENT wsaevent, *wsaevents;
   WSANETWORKEVENTS wsanetevents;
+  struct select_ws_data *data;
   HANDLE handle, *handles;
-  curl_socket_t sock, *fdarr, *wsasocks;
+  curl_socket_t sock;
   long networkevents;
+  WSAEVENT wsaevent;
   int error, fds;
-  HANDLE threadevent = NULL, threadhandle = NULL;
-  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 */
@@ -616,39 +699,31 @@ static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
     return 0;
   }
 
-  /* allocate internal array for the original input handles */
-  fdarr = malloc(nfds * sizeof(curl_socket_t));
-  if(fdarr == NULL) {
+  /* create internal event to signal waiting threads */
+  waitevent = CreateEvent(NULL, TRUE, FALSE, NULL);
+  if(!waitevent) {
     errno = ENOMEM;
     return -1;
   }
 
-  /* allocate internal array for the internal event handles */
-  handles = malloc(nfds * sizeof(HANDLE));
-  if(handles == NULL) {
-    free(fdarr);
+  /* allocate internal array for the internal data */
+  data = malloc(nfds * sizeof(struct select_ws_data));
+  if(data == NULL) {
     errno = ENOMEM;
     return -1;
   }
 
-  /* allocate internal array for the internal socket handles */
-  wsasocks = malloc(nfds * sizeof(curl_socket_t));
-  if(wsasocks == NULL) {
-    free(handles);
-    free(fdarr);
+  /* allocate internal array for the internal event handles */
+  handles = malloc(nfds * sizeof(HANDLE));
+  if(handles == NULL) {
+    free(data);
     errno = ENOMEM;
     return -1;
   }
 
-  /* allocate internal array for the internal WINSOCK2 events */
-  wsaevents = malloc(nfds * sizeof(WSAEVENT));
-  if(wsaevents == NULL) {
-    free(wsasocks);
-    free(handles);
-    free(fdarr);
-    errno = ENOMEM;
-    return -1;
-  }
+  /* clear internal arrays */
+  memset(data, 0, nfds * sizeof(struct select_ws_data));
+  memset(handles, 0, nfds * sizeof(HANDLE));
 
   /* loop over the handles in the input descriptor sets */
   for(fds = 0; fds < nfds; fds++) {
@@ -666,13 +741,13 @@ static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
 
     /* only wait for events for which we actually care */
     if(networkevents) {
-      fdarr[nfd] = curlx_sitosk(fds);
+      data[nfd].fd = curlx_sitosk(fds);
       if(fds == fileno(stdin)) {
-        threadevent = CreateEvent(NULL, TRUE, FALSE, NULL);
-        threadhandle = CreateThread(NULL, 0,
-                                    &select_ws_stdin_wait_thread,
-                                    threadevent, 0, NULL);
-        handles[nfd] = threadhandle;
+        handle = GetStdHandle(STD_INPUT_HANDLE);
+        handle = select_ws_wait(handle, waitevent);
+        handles[nfd] = handle;
+        data[thd].thread = handle;
+        thd++;
       }
       else if(fds == fileno(stdout)) {
         handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE);
@@ -685,14 +760,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] = curlx_sitosk(fds);
-            wsaevents[wsa] = wsaevent;
+            handle = (HANDLE) wsaevent;
+            handles[nfd] = handle;
+            data[wsa].wsasock = curlx_sitosk(fds);
+            data[wsa].wsaevent = wsaevent;
             wsa++;
           }
           else {
-            handles[nfd] = (HANDLE) curlx_sitosk(fds);
             WSACloseEvent(wsaevent);
+            handle = (HANDLE) curlx_sitosk(fds);
+            handle = select_ws_wait(handle, waitevent);
+            handles[nfd] = handle;
+            data[thd].thread = handle;
+            thd++;
           }
         }
       }
@@ -711,15 +791,13 @@ 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 thread */
-  if(threadevent) {
-    SetEvent(threadevent);
-  }
+  /* 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++) {
     handle = handles[idx];
-    sock = fdarr[idx];
+    sock = data[idx].fd;
     fds = curlx_sktosi(sock);
 
     /* check if the current internal handle was triggered */
@@ -738,6 +816,7 @@ static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
       }
       else {
         /* try to handle the event with the WINSOCK2 functions */
+        wsanetevents.lNetworkEvents = 0;
         error = WSAEnumNetworkEvents(fds, handle, &wsanetevents);
         if(error != SOCKET_ERROR) {
           /* remove from descriptor set if not ready for read/accept/close */
@@ -778,22 +857,19 @@ static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
   }
 
   for(idx = 0; idx < wsa; idx++) {
-    WSAEventSelect(wsasocks[idx], NULL, 0);
-    WSACloseEvent(wsaevents[idx]);
+    WSAEventSelect(data[idx].wsasock, NULL, 0);
+    WSACloseEvent(data[idx].wsaevent);
   }
 
-  if(threadhandle) {
-    WaitForSingleObject(threadhandle, INFINITE);
-    CloseHandle(threadhandle);
-  }
-  if(threadevent) {
-    CloseHandle(threadevent);
+  for(idx = 0; idx < thd; idx++) {
+    WaitForSingleObject(data[idx].thread, INFINITE);
+    CloseHandle(data[idx].thread);
   }
 
-  free(wsaevents);
-  free(wsasocks);
+  CloseHandle(waitevent);
+
   free(handles);
-  free(fdarr);
+  free(data);
 
   return ret;
 }