type changes, casts, and arg touching to prevent warnings.
[catagits/fcgi2.git] / libfcgi / os_win32.c
index a29e62b..ff53ad0 100755 (executable)
  *  significantly more enjoyable.)
  */
 #ifndef lint
-static const char rcsid[] = "$Id: os_win32.c,v 1.9 2001/03/26 20:04:56 robs Exp $";
+static const char rcsid[] = "$Id: os_win32.c,v 1.18 2001/06/20 17:02:09 robs Exp $";
 #endif /* not lint */
 
-#include "fcgi_config.h"
-
-#define DLLAPI  __declspec(dllexport)
-
+#define WIN32_LEAN_AND_MEAN 
+#include <windows.h>
+#include <winsock2.h>
+#include <stdlib.h>
 #include <assert.h>
 #include <stdio.h>
 #include <sys/timeb.h>
-#include <Winsock2.h>
-#include <Windows.h>
 
+#define DLLAPI  __declspec(dllexport)
 #include "fcgios.h"
-
-#define ASSERT assert
+#include "fcgimisc.h"
 
 #define WIN32_OPEN_MAX 128 /* XXX: Small hack */
+
+/*
+ * millisecs to wait for a client connection before checking the 
+ * shutdown flag (then go back to waiting for a connection, etc).
+ */
+#define ACCEPT_TIMEOUT 1000
+
 #define MUTEX_VARNAME "_FCGI_MUTEX_"
 #define SHUTDOWN_EVENT_NAME "_FCGI_SHUTDOWN_EVENT_"
+#define LOCALHOST "localhost"
 
 static HANDLE hIoCompPort = INVALID_HANDLE_VALUE;
 static HANDLE hStdinCompPort = INVALID_HANDLE_VALUE;
@@ -91,8 +97,6 @@ struct FD_TABLE {
     LPVOID  ovList;            /* List of associated OVERLAPPED_REQUESTs */
 };
 
-typedef struct FD_TABLE *PFD_TABLE;
-
 /* 
  * XXX Note there is no dyanmic sizing of this table, so if the
  * number of open file descriptors exceeds WIN32_OPEN_MAX the 
@@ -100,6 +104,8 @@ typedef struct FD_TABLE *PFD_TABLE;
  */
 static struct FD_TABLE fdTable[WIN32_OPEN_MAX];
 
+static CRITICAL_SECTION  fdTableCritical;
+
 struct OVERLAPPED_REQUEST {
     OVERLAPPED overlapped;
     unsigned long instance;    /* file instance (won't match after a close) */
@@ -111,7 +117,7 @@ typedef struct OVERLAPPED_REQUEST *POVERLAPPED_REQUEST;
 
 static const char *bindPathPrefix = "\\\\.\\pipe\\FastCGI\\";
 
-static int listenType = FD_UNUSED;
+static enum FILE_TYPE listenType = FD_UNUSED;
 
 // XXX This should be a DESCRIPTOR
 static HANDLE hListen = INVALID_HANDLE_VALUE;
@@ -119,7 +125,6 @@ static HANDLE hListen = INVALID_HANDLE_VALUE;
 static OVERLAPPED listenOverlapped;
 static BOOLEAN libInitialized = FALSE;
 
-\f
 /*
  *--------------------------------------------------------------
  *
@@ -140,69 +145,60 @@ static BOOLEAN libInitialized = FALSE;
  */
 static int Win32NewDescriptor(FILE_TYPE type, int fd, int desiredFd)
 {
-    int index;
+    int index = -1;
+
+    EnterCriticalSection(&fdTableCritical);
 
     /*
-     * If the "desiredFd" is not -1, try to get this entry for our
-     * pseudo file descriptor.  If this is not available, return -1
-     * as the caller wanted to get this mapping.  This is typically
-     * only used for mapping stdio handles.
+     * If desiredFd is set, try to get this entry (this is used for
+     * mapping stdio handles).  Otherwise try to get the fd entry.
+     * If this is not available, find a the first empty slot.  .
      */
     if (desiredFd >= 0 && desiredFd < WIN32_OPEN_MAX)
     {
-        if (fdTable[desiredFd].type != FD_UNUSED) 
+        if (fdTable[desiredFd].type == FD_UNUSED) 
         {
-            return -1;
+            index = desiredFd;
         }
-           index = desiredFd;
        }
-    else
+    else if (fd > 0)
     {
-        // See if the entry that matches "fd" is available.
-
-        if (fd <= 0 || fd >= WIN32_OPEN_MAX)
-        {
-            return -1;
-        }
-
-        if (fdTable[fd].type == FD_UNUSED)
+        if (fd < WIN32_OPEN_MAX && fdTable[fd].type == FD_UNUSED)
         {
                index = fd;
         }
         else 
         {
-            // Find an entry we can use. 
-            // Start at 1 (0 fake id fails in some cases).
+            int i;
 
-            for (index = 1; index < WIN32_OPEN_MAX; index++)
+            for (i = 1; i < WIN32_OPEN_MAX; ++i)
             {
-                   if (fdTable[index].type == FD_UNUSED)
+                   if (fdTable[i].type == FD_UNUSED)
                 {
+                    index = i;
                     break;
                 }
             }
-
-            if (index == WIN32_OPEN_MAX) 
-            {
-                   SetLastError(WSAEMFILE);
-                   return -1;
-            }
         }
     }
+    
+    if (index != -1) 
+    {
+        fdTable[index].fid.value = fd;
+        fdTable[index].type = type;
+        fdTable[index].path = NULL;
+        fdTable[index].Errno = NO_ERROR;
+        fdTable[index].status = 0;
+        fdTable[index].offset = -1;
+        fdTable[index].offsetHighPtr = fdTable[index].offsetLowPtr = NULL;
+        fdTable[index].hMapMutex = NULL;
+        fdTable[index].ovList = NULL;
+    }
 
-    fdTable[index].fid.value = fd;
-    fdTable[index].type = type;
-    fdTable[index].path = NULL;
-    fdTable[index].Errno = NO_ERROR;
-    fdTable[index].status = 0;
-    fdTable[index].offset = -1;
-    fdTable[index].offsetHighPtr = fdTable[index].offsetLowPtr = NULL;
-    fdTable[index].hMapMutex = NULL;
-    fdTable[index].ovList = NULL;
-
+    LeaveCriticalSection(&fdTableCritical);
     return index;
 }
-\f
+
 /*
  *--------------------------------------------------------------
  *
@@ -227,10 +223,13 @@ static int Win32NewDescriptor(FILE_TYPE type, int fd, int desiredFd)
 static void StdinThread(LPDWORD startup){
 
     int doIo = TRUE;
-    int fd;
-    int bytesRead;
+    unsigned long fd;
+    unsigned long bytesRead;
     POVERLAPPED_REQUEST pOv;
 
+    // Touch the arg to prevent warning
+    startup = NULL;
+
     while(doIo) {
         /*
          * Block until a request to read from stdin comes in or a
@@ -269,7 +268,7 @@ static DWORD WINAPI ShutdownRequestThread(LPVOID arg)
     if (WaitForSingleObject(shutdownEvent, INFINITE) == WAIT_FAILED)
     {
         // Assuming it will happen again, all we can do is exit the thread
-        return -1;
+        return 1;
     }
     else
     {
@@ -313,6 +312,8 @@ int OS_LibInit(int stdioFds[3])
     if(libInitialized)
         return 0;
 
+    InitializeCriticalSection(&fdTableCritical);   
+        
     /*
      * Initialize windows sockets library.
      */
@@ -540,7 +541,6 @@ int OS_LibInit(int stdioFds[3])
     return 0;
 }
 
-\f
 /*
  *--------------------------------------------------------------
  *
@@ -559,24 +559,31 @@ int OS_LibInit(int stdioFds[3])
 void OS_LibShutdown()
 {
 
-    if(hIoCompPort != INVALID_HANDLE_VALUE) {
+    if (hIoCompPort != INVALID_HANDLE_VALUE) 
+    {
         CloseHandle(hIoCompPort);
-       hIoCompPort = INVALID_HANDLE_VALUE;
+        hIoCompPort = INVALID_HANDLE_VALUE;
     }
 
-    if(hStdinCompPort != INVALID_HANDLE_VALUE) {
+    if (hStdinCompPort != INVALID_HANDLE_VALUE) 
+    {
         CloseHandle(hStdinCompPort);
-       hStdinCompPort = INVALID_HANDLE_VALUE;
+        hStdinCompPort = INVALID_HANDLE_VALUE;
     }
 
-    /*
-     * Shutdown the socket library.
-     */
+    if (acceptMutex != INVALID_HANDLE_VALUE) 
+    {
+        ReleaseMutex(acceptMutex);
+    }
+
+    DisconnectNamedPipe(hListen);
+
+    CancelIo(hListen);
+
+
     WSACleanup();
-    return;
 }
 
-\f
 /*
  *--------------------------------------------------------------
  *
@@ -596,36 +603,63 @@ static void Win32FreeDescriptor(int fd)
 {
     /* Catch it if fd is a bogus value */
     ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
-    ASSERT(fdTable[fd].type != FD_UNUSED);
 
-    switch (fdTable[fd].type) {
-       case FD_FILE_SYNC:
-       case FD_FILE_ASYNC:
-           /* Free file path string */
-           ASSERT(fdTable[fd].path != NULL);
-           free(fdTable[fd].path);
-           fdTable[fd].path = NULL;
-           break;
-       default:
-           /*
-            * Break through to generic fdTable free-descriptor code
-            */
-           break;
+    EnterCriticalSection(&fdTableCritical);
+    
+    if (fdTable[fd].type != FD_UNUSED)
+    {   
+        switch (fdTable[fd].type) 
+        {
+           case FD_FILE_SYNC:
+           case FD_FILE_ASYNC:
+        
+               /* Free file path string */
+               ASSERT(fdTable[fd].path != NULL);
+               free(fdTable[fd].path);
+               fdTable[fd].path = NULL;
+               break;
+
+           default:
+               break;
+        }
 
+        ASSERT(fdTable[fd].path == NULL);
+
+        fdTable[fd].type = FD_UNUSED;
+        fdTable[fd].path = NULL;
+        fdTable[fd].Errno = NO_ERROR;
+        fdTable[fd].offsetHighPtr = fdTable[fd].offsetLowPtr = NULL;
+
+        if (fdTable[fd].hMapMutex != NULL) 
+        {
+            CloseHandle(fdTable[fd].hMapMutex);
+            fdTable[fd].hMapMutex = NULL;
+        }
     }
-    ASSERT(fdTable[fd].path == NULL);
-    fdTable[fd].type = FD_UNUSED;
-    fdTable[fd].path = NULL;
-    fdTable[fd].Errno = NO_ERROR;
-    fdTable[fd].offsetHighPtr = fdTable[fd].offsetLowPtr = NULL;
-    if (fdTable[fd].hMapMutex != NULL) {
-        CloseHandle(fdTable[fd].hMapMutex);
-        fdTable[fd].hMapMutex = NULL;
-    }
+
+    LeaveCriticalSection(&fdTableCritical);
+
     return;
 }
 
-\f
+static short getPort(const char * bindPath)
+{
+    short port = 0;
+    char * p = strchr(bindPath, ':');
+
+    if (p && *++p) 
+    {
+        char buf[6];
+
+        strncpy(buf, p, 6);
+        buf[5] = '\0';
+
+        port = (short) atoi(buf);
+    }
+    return port;
+}
+
 /*
  * OS_CreateLocalIpcFd --
  *
@@ -646,20 +680,10 @@ static void Win32FreeDescriptor(int fd)
  */
 int OS_CreateLocalIpcFd(const char *bindPath, int backlog)
 {
-    int retFd = -1;
-    SECURITY_ATTRIBUTES     sa;
-    HANDLE hListenPipe = INVALID_HANDLE_VALUE;
-    char *localPath;
-    SOCKET listenSock;
-    int bpLen;
-    int servLen;
-    struct  sockaddr_in        sockAddr;
-    char    buf[1024];
-    short   port;
-    int            tcp = FALSE;
-    int flag = 1;
-    char    *tp;
+    int pseudoFd = -1;
+    short port = getPort(bindPath);
     HANDLE mutex = CreateMutex(NULL, FALSE, NULL);
+    char * mutexEnvString;
 
     if (mutex == NULL)
     {
@@ -673,105 +697,102 @@ int OS_CreateLocalIpcFd(const char *bindPath, int backlog)
 
     // This is a nail for listening to more than one port..
     // This should really be handled by the caller.
-    _snprintf(buf, 1024, MUTEX_VARNAME "=%d", (int) mutex);
-    buf[1023] = '\0';
-    putenv(strdup(buf));
 
-    // There's nothing to be gained (at the moment) by a shutdown Event    
+    mutexEnvString = malloc(strlen(MUTEX_VARNAME) + 7);
+    sprintf(mutexEnvString, MUTEX_VARNAME "=%d", (int) mutex);
+    putenv(mutexEnvString);
 
-    strncpy(buf, bindPath, 1024);
-    buf[1023] = '\0';
+    // There's nothing to be gained (at the moment) by a shutdown Event    
 
-    if((tp = strchr(buf, ':')) != 0) {
-       *tp++ = 0;
-       if((port = atoi(tp)) == 0) {
-           *--tp = ':';
-        } else {
-           tcp = TRUE;
-        }
+    if (port && *bindPath != ':' && strncmp(bindPath, LOCALHOST, strlen(LOCALHOST)))
+    {
+           fprintf(stderr, "To start a service on a TCP port can not "
+                           "specify a host name.\n"
+                           "You should either use \"localhost:<port>\" or "
+                           " just use \":<port>.\"\n");
+           exit(1);
     }
+
+    listenType = (port) ? FD_SOCKET_SYNC : FD_PIPE_ASYNC;
     
-    if(tcp && (*buf && strcmp(buf, "localhost") != 0)) {
-       fprintf(stderr, "To start a service on a TCP port can not "
-                       "specify a host name.\n"
-                       "You should either use \"localhost:<port>\" or "
-                       " just use \":<port>.\"\n");
-       exit(1);
-    }
+    if (port) 
+    {
+        SOCKET listenSock;
+        struct  sockaddr_in    sockAddr;
+        int sockLen = sizeof(sockAddr);
+        
+        memset(&sockAddr, 0, sizeof(sockAddr));
+        sockAddr.sin_family = AF_INET;
+        sockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
+        sockAddr.sin_port = htons(port);
 
-    if(tcp) {
-       listenSock = socket(AF_INET, SOCK_STREAM, 0);
-        if(listenSock == SOCKET_ERROR) {
-           return -1;
-       }
-       /*
-        * Bind the listening socket.
-        */
-       memset((char *) &sockAddr, 0, sizeof(sockAddr));
-       sockAddr.sin_family = AF_INET;
-       sockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
-       sockAddr.sin_port = htons(port);
-       servLen = sizeof(sockAddr);
-
-       if(bind(listenSock, (struct sockaddr *) &sockAddr, servLen) < 0
-          || listen(listenSock, backlog) < 0) {
-           perror("bind/listen");
-           exit(errno);
-       }
+        listenSock = socket(AF_INET, SOCK_STREAM, 0);
+        if (listenSock == INVALID_SOCKET) 
+        {
+               return -1;
+           }
+
+           if (! bind(listenSock, (struct sockaddr *) &sockAddr, sockLen)
+               || ! listen(listenSock, backlog)) 
+        {
+               return -1;
+           }
+
+        pseudoFd = Win32NewDescriptor(listenType, listenSock, -1);
+        
+        if (pseudoFd == -1) 
+        {
+            closesocket(listenSock);
+            return -1;
+        }
 
-       retFd = Win32NewDescriptor(FD_SOCKET_SYNC, (int)listenSock, -1);
-       return retFd;
+        hListen = (HANDLE) listenSock;        
     }
+    else
+    {
+        HANDLE hListenPipe = INVALID_HANDLE_VALUE;
+        char *pipePath = malloc(strlen(bindPathPrefix) + strlen(bindPath) + 1);
+        
+        if (! pipePath) 
+        {
+            return -1;
+        }
 
+        strcpy(pipePath, bindPathPrefix);
+        strcat(pipePath, bindPath);
 
-    /*
-     * Initialize the SECURITY_ATTRIUBTES structure.
-     */
-    sa.nLength = sizeof(sa);
-    sa.lpSecurityDescriptor = NULL;
-    sa.bInheritHandle = TRUE;       /* This will be inherited by the
-                                     * FastCGI process
-                                     */
-    /*
-     * Create a unique name to be used for the socket bind path.
-     * Make sure that this name is unique and that there's no process
-     * bound to it.
-     *
-     * Named Pipe Pathname: \\.\pipe\FastCGI\OM_WS.pid.N
-     * Where: N is the pipe instance on the machine.
-     *
-     */
-    bpLen = (int)strlen(bindPathPrefix);
-    bpLen += strlen(bindPath);
-    localPath = malloc(bpLen+2);
-    strcpy(localPath, bindPathPrefix);
-    strcat(localPath, bindPath);
+        hListenPipe = CreateNamedPipe(pipePath,
+                       PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
+                       PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_READMODE_BYTE,
+                       PIPE_UNLIMITED_INSTANCES,
+                       4096, 4096, 0, NULL);
+        
+        free(pipePath);
 
-    /*
-     * Create and setup the named pipe to be used by the fcgi server.
-     */
-    hListenPipe = CreateNamedPipe(localPath, /* name of pipe */
-                   PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
-                   PIPE_TYPE_BYTE | PIPE_WAIT |
-                   PIPE_READMODE_BYTE,         /* pipe IO type */
-                   PIPE_UNLIMITED_INSTANCES,   /* number of instances */
-                   4096,                       /* size of outbuf (0 == allocate as necessary) */
-                   4096,                               /* size of inbuf */
-                   0, /*1000,*/                /* default time-out value */
-                   &sa);                       /* security attributes */
-    free(localPath);
-    /*
-     * Can't create an instance of the pipe, fail...
-     */
-    if (hListenPipe == INVALID_HANDLE_VALUE) {
-       return -1;
+        if (hListenPipe == INVALID_HANDLE_VALUE)
+        {
+            return -1;
+        }
+
+        if (! SetHandleInformation(hListenPipe, HANDLE_FLAG_INHERIT, TRUE))
+        {
+            return -1;
+        }
+
+        pseudoFd = Win32NewDescriptor(listenType, (int) hListenPipe, -1);
+        
+        if (pseudoFd == -1) 
+        {
+            CloseHandle(hListenPipe);
+            return -1;
+        }
+
+        hListen = (HANDLE) hListenPipe;
     }
 
-    retFd = Win32NewDescriptor(FD_PIPE_SYNC, (int)hListenPipe, -1);
-    return retFd;
+    return pseudoFd;
 }
 
-\f
 /*
  *----------------------------------------------------------------------
  *
@@ -790,104 +811,115 @@ int OS_CreateLocalIpcFd(const char *bindPath, int backlog)
  */
 int OS_FcgiConnect(char *bindPath)
 {
-    char *pipePath = NULL;
-    HANDLE hPipe;
-    int pseudoFd, err;
-
-    struct  sockaddr_in        sockAddr;
-    int servLen, resultSock;
-    int connectStatus;
-    char    *tp;
-    char    host[1024];
-    short   port;
-    int            tcp = FALSE;
-
-    strncpy(host, bindPath, 1024);
-    host[1023] = '\0';
-
-    if ((tp = strchr(host, ':')) != 0) {
-       *tp++ = 0;
-       if((port = atoi(tp)) == 0) {
-           *--tp = ':';
-        } else {
-           tcp = TRUE;
-        }
-    }
+    short port = getPort(bindPath);
+    int pseudoFd = -1;
     
-    if(tcp == TRUE) {
-       struct  hostent *hp;
-       if((hp = gethostbyname((*host ? host : "localhost"))) == NULL) {
-           fprintf(stderr, "Unknown host: %s\n", bindPath);
-           exit(1000);
-       }
-       sockAddr.sin_family = AF_INET;
-       memcpy(&sockAddr.sin_addr, hp->h_addr, hp->h_length);
-       sockAddr.sin_port = htons(port);
-       servLen = sizeof(sockAddr);
-       resultSock = socket(AF_INET, SOCK_STREAM, 0);
-
-       ASSERT(resultSock >= 0);
-       connectStatus = connect(resultSock, (struct sockaddr *)
-                               &sockAddr, servLen);
-       if(connectStatus < 0) {
-           /*
-            * Most likely (errno == ENOENT || errno == ECONNREFUSED)
-            * and no FCGI application server is running.
-            */
-           closesocket(resultSock);
-           return -1;
-       }
-       pseudoFd = Win32NewDescriptor(FD_SOCKET_SYNC, resultSock, -1);
-       if(pseudoFd == -1) {
-           closesocket(resultSock);
-       }
-       return pseudoFd;
-    }
+    if (port) 
+    {
+           struct hostent *hp;
+        char *host = NULL;
+        struct sockaddr_in sockAddr;
+        int sockLen = sizeof(sockAddr);
+        SOCKET sock;
+        
+        if (*bindPath != ':')
+        {
+            char * p = strchr(bindPath, ':');
+            int len = p - bindPath + 1;
 
-    /*
-     * Not a TCP connection, create and connect to a named pipe.
-     */
-    pipePath = malloc((size_t)(strlen(bindPathPrefix) + strlen(bindPath) + 2));
-    if(pipePath == NULL) {
-        return -1;
-    }
-    strcpy(pipePath, bindPathPrefix);
-    strcat(pipePath, bindPath);
-
-    hPipe = CreateFile (pipePath,
-                       /* Generic access, read/write. */
-                       GENERIC_WRITE | GENERIC_READ,
-                       /* Share both read and write. */
-                       FILE_SHARE_READ | FILE_SHARE_WRITE ,
-                       NULL,                  /* No security.*/
-                       OPEN_EXISTING,         /* Fail if not existing. */
-                       FILE_FLAG_OVERLAPPED,  /* Use overlap. */
-                       NULL);                 /* No template. */
-
-    free(pipePath);
-    if(hPipe == INVALID_HANDLE_VALUE) {
-        return -1;
+            host = malloc(len);
+            strncpy(host, bindPath, len);
+            host[len] = '\0';
+        }
+        
+        hp = gethostbyname(host ? host : LOCALHOST);
+
+        if (host)
+        {
+            free(host);
+        }
+
+           if (hp == NULL) 
+        {
+               fprintf(stderr, "Unknown host: %s\n", bindPath);
+               return -1;
+           }
+       
+        memset(&sockAddr, 0, sizeof(sockAddr));
+        sockAddr.sin_family = AF_INET;
+           memcpy(&sockAddr.sin_addr, hp->h_addr, hp->h_length);
+           sockAddr.sin_port = htons(port);
+
+           sock = socket(AF_INET, SOCK_STREAM, 0);
+        if (sock == INVALID_SOCKET)
+        {
+            return -1;
+        }
+
+           if (! connect(sock, (struct sockaddr *) &sockAddr, sockLen)) 
+        {
+               closesocket(sock);
+               return -1;
+           }
+
+           pseudoFd = Win32NewDescriptor(FD_SOCKET_SYNC, sock, -1);
+           if (pseudoFd == -1) 
+        {
+               closesocket(sock);
+            return -1;
+           }
     }
+    else
+    {
+        char *pipePath = malloc(strlen(bindPathPrefix) + strlen(bindPath) + 1);
+        HANDLE hPipe;
+        
+        if (! pipePath) 
+        {
+            return -1;
+        }
 
-    if ((pseudoFd = Win32NewDescriptor(FD_PIPE_ASYNC, (int)hPipe, -1)) == -1) {
-        CloseHandle(hPipe);
-        return -1;
-    } else {
+        strcpy(pipePath, bindPathPrefix);
+        strcat(pipePath, bindPath);
+
+        hPipe = CreateFile(pipePath,
+                           GENERIC_WRITE | GENERIC_READ,
+                           FILE_SHARE_READ | FILE_SHARE_WRITE,
+                           NULL,
+                           OPEN_EXISTING,
+                           FILE_FLAG_OVERLAPPED,
+                           NULL);
+
+        free(pipePath);
+
+        if( hPipe == INVALID_HANDLE_VALUE) 
+        {
+            return -1;
+        }
+
+        pseudoFd = Win32NewDescriptor(FD_PIPE_ASYNC, (int) hPipe, -1);
+        
+        if (pseudoFd == -1) 
+        {
+            CloseHandle(hPipe);
+            return -1;
+        } 
+        
         /*
-        * Set stdin equal to our pseudo FD and create the I/O completion
-        * port to be used for async I/O.
-        */
-        if (!CreateIoCompletionPort(hPipe, hIoCompPort, pseudoFd, 1)) {
-           err = GetLastError();
-           Win32FreeDescriptor(pseudoFd);
-           CloseHandle(hPipe);
-           return -1;
-       }
+            * Set stdin equal to our pseudo FD and create the I/O completion
+            * port to be used for async I/O.
+            */
+        if (! CreateIoCompletionPort(hPipe, hIoCompPort, pseudoFd, 1))
+        {
+               Win32FreeDescriptor(pseudoFd);
+               CloseHandle(hPipe);
+               return -1;
+           }
     }
-    return pseudoFd;
+
+    return pseudoFd;    
 }
 
-\f
 /*
  *--------------------------------------------------------------
  *
@@ -907,47 +939,48 @@ int OS_FcgiConnect(char *bindPath)
 int OS_Read(int fd, char * buf, size_t len)
 {
     DWORD bytesRead;
-    int ret;
+    int ret = -1;
 
-    /*
-     * Catch any bogus fd values
-     */
     ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
 
-    switch (fdTable[fd].type) {
+    switch (fdTable[fd].type) 
+    {
        case FD_FILE_SYNC:
        case FD_FILE_ASYNC:
        case FD_PIPE_SYNC:
        case FD_PIPE_ASYNC:
-           bytesRead = fd;
-           /*
-            * ReadFile returns: TRUE success, FALSE failure
-            */
-           if (!ReadFile(fdTable[fd].fid.fileHandle, buf, len, &bytesRead,
-               NULL)) {
-               fdTable[fd].Errno = GetLastError();
-               return -1;
+
+           if (ReadFile(fdTable[fd].fid.fileHandle, buf, len, &bytesRead, NULL)) 
+        {
+            ret = bytesRead;
+        }
+        else
+        {
+                   fdTable[fd].Errno = GetLastError();
            }
-           return bytesRead;
+
+        break;
 
        case FD_SOCKET_SYNC:
        case FD_SOCKET_ASYNC:
-           /* winsock recv returns n bytes recv'ed, SOCKET_ERROR failure */
-           /*
-            * XXX: Test this with ReadFile.  If it works, remove this code
-            *      to simplify the routine.
-            */
-           if ((ret = recv(fdTable[fd].fid.sock, buf, len, 0)) ==
-               SOCKET_ERROR) {
-               fdTable[fd].Errno = WSAGetLastError();
-               return -1;
+
+        ret = recv(fdTable[fd].fid.sock, buf, len, 0);
+           if (ret == SOCKET_ERROR) 
+        {
+                   fdTable[fd].Errno = WSAGetLastError();
+                   ret = -1;
            }
-           return ret;
-       default:
-               return -1;
+
+        break;
+        
+    default:
+
+        ASSERT(0);
     }
+
+    return ret;
 }
-\f
+
 /*
  *--------------------------------------------------------------
  *
@@ -967,49 +1000,48 @@ int OS_Read(int fd, char * buf, size_t len)
 int OS_Write(int fd, char * buf, size_t len)
 {
     DWORD bytesWritten;
-    int ret;
+    int ret = -1;
 
-    /*
-     * Catch any bogus fd values
-     */
-    ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
-    ASSERT((fdTable[fd].type > FD_UNUSED) &&
-          (fdTable[fd].type <= FD_PIPE_ASYNC));
+    ASSERT(fd >= 0 && fd < WIN32_OPEN_MAX);
 
-    switch (fdTable[fd].type) {
+    switch (fdTable[fd].type) 
+    {
        case FD_FILE_SYNC:
        case FD_FILE_ASYNC:
        case FD_PIPE_SYNC:
        case FD_PIPE_ASYNC:
-           bytesWritten = fd;
-           /*
-            * WriteFile returns: TRUE success, FALSE failure
-            */
-           if (!WriteFile(fdTable[fd].fid.fileHandle, buf, len,
-               &bytesWritten, NULL)) {
-               fdTable[fd].Errno = GetLastError();
-               return -1;
+
+        if (WriteFile(fdTable[fd].fid.fileHandle, buf, len, &bytesWritten, NULL)) 
+        {
+            ret = bytesWritten;
+        }
+        else
+        {
+                   fdTable[fd].Errno = GetLastError();
            }
-           return bytesWritten;
+
+        break;
+
        case FD_SOCKET_SYNC:
        case FD_SOCKET_ASYNC:
-           /* winsock send returns n bytes written, SOCKET_ERROR failure */
-           /*
-            * XXX: Test this with WriteFile.  If it works, remove this code
-            *      to simplify the routine.
-            */
-           if ((ret = send(fdTable[fd].fid.sock, buf, len, 0)) ==
-               SOCKET_ERROR) {
-               fdTable[fd].Errno = WSAGetLastError();
-               return -1;
+
+        ret = send(fdTable[fd].fid.sock, buf, len, 0);
+        if (ret == SOCKET_ERROR) 
+        {
+                   fdTable[fd].Errno = WSAGetLastError();
+                   ret = -1;
            }
-           return ret;
-       default:
-           return -1;
+
+        break;
+
+    default:
+
+        ASSERT(0);
     }
+
+    return ret;
 }
 
-\f
 /*
  *----------------------------------------------------------------------
  *
@@ -1089,7 +1121,6 @@ int OS_SpawnChild(char *execPath, int listenFd)
     }
 }
 
-\f
 /*
  *--------------------------------------------------------------
  *
@@ -1129,7 +1160,6 @@ int OS_AsyncReadStdin(void *buf, int len, OS_AsyncProc procPtr,
     return 0;
 }
 
-\f
 /*
  *--------------------------------------------------------------
  *
@@ -1206,7 +1236,7 @@ int OS_AsyncRead(int fd, int offset, void *buf, int len,
     }
     return 0;
 }
-\f
+
 /*
  *--------------------------------------------------------------
  *
@@ -1308,7 +1338,6 @@ int OS_AsyncWrite(int fd, int offset, void *buf, int len,
     return 0;
 }
 
-\f
 /*
  *--------------------------------------------------------------
  *
@@ -1364,7 +1393,7 @@ int OS_Close(int fd)
     Win32FreeDescriptor(fd);
     return ret;
 }
-\f
+
 /*
  *--------------------------------------------------------------
  *
@@ -1394,7 +1423,7 @@ int OS_CloseRead(int fd)
        ret = -1;
     return ret;
 }
-\f
+
 /*
  *--------------------------------------------------------------
  *
@@ -1414,8 +1443,8 @@ int OS_CloseRead(int fd)
  */
 int OS_DoIo(struct timeval *tmo)
 {
-    int fd;
-    int bytes;
+    unsigned long fd;
+    unsigned long bytes;
     POVERLAPPED_REQUEST pOv;
     struct timeb tb;
     int ms;
@@ -1470,6 +1499,9 @@ static int CALLBACK isAddrOK(LPWSABUF  lpCallerId,
     const char *okAddrs = (char *) dwCallbackData;
     struct sockaddr *sockaddr = (struct sockaddr *) lpCallerId->buf;
 
+    // Touch the args to avoid warnings
+    dc0 = NULL; dc1 = NULL; dc2 = NULL; dc3 = NULL; dc4 = NULL; dc5 = NULL;
+
     if (okAddrs == NULL || sockaddr->sa_family != AF_INET)
     {
         return TRUE;
@@ -1501,33 +1533,158 @@ static int CALLBACK isAddrOK(LPWSABUF  lpCallerId,
         }
     }
 }
+
+static printLastError(const char * text)
+{
+    LPVOID buf;
+
+    FormatMessage( 
+        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
+        FORMAT_MESSAGE_FROM_SYSTEM | 
+        FORMAT_MESSAGE_IGNORE_INSERTS,
+        NULL,
+        GetLastError(),
+        0,
+        (LPTSTR) &buf,
+        0,
+        NULL 
+    );
     
-\f
+    fprintf(stderr, "%s: %s\n", text, (LPCTSTR) buf);
+    LocalFree(buf);
+}
+
+static int acceptNamedPipe()
+{
+    int ipcFd = -1;
+
+    if (! ConnectNamedPipe(hListen, &listenOverlapped))
+    {
+        switch (GetLastError())
+        {
+            case ERROR_PIPE_CONNECTED:
+
+                // A client connected after CreateNamedPipe but
+                // before ConnectNamedPipe. Its a good connection.
+
+                break;
+        
+            case ERROR_IO_PENDING:
+
+                // Wait for a connection to complete.
+
+                while (WaitForSingleObject(listenOverlapped.hEvent, 
+                                           ACCEPT_TIMEOUT) == WAIT_TIMEOUT) 
+                {
+                    if (shutdownPending) 
+                    {
+                        OS_LibShutdown();
+                        return -1;
+                    }            
+                }
+
+                break;
+
+            case ERROR_PIPE_LISTENING:
+
+                // The pipe handle is in nonblocking mode.
+
+            case ERROR_NO_DATA:
+
+                // The previous client closed its handle (and we failed
+                // to call DisconnectNamedPipe)
+
+            default:
+
+                printLastError("unexpected ConnectNamedPipe() error");
+        }
+    }
+
+    ipcFd = Win32NewDescriptor(FD_PIPE_SYNC, (int) hListen, -1);
+       if (ipcFd == -1) 
+    {
+        DisconnectNamedPipe(hListen);
+    }
+
+    return ipcFd;
+}
+
+static int acceptSocket(const char *webServerAddrs)
+{
+    struct sockaddr sockaddr;
+    int sockaddrLen = sizeof(sockaddr);
+    fd_set readfds;
+    const struct timeval timeout = {1, 0};
+    SOCKET hSock;
+    int ipcFd = -1;
+    FD_ZERO(&readfds);
+    FD_SET((unsigned int) hListen, &readfds);
+    
+    while (select(0, &readfds, NULL, NULL, &timeout) == 0)
+    {
+        if (shutdownPending) 
+        {
+            OS_LibShutdown();
+            return -1;
+        }
+    }
+    
+    hSock = (webServerAddrs == NULL)
+        ? accept((SOCKET) hListen, 
+                          &sockaddr, 
+                          &sockaddrLen)
+        : WSAAccept((unsigned int) hListen,                    
+                                   &sockaddr,  
+                                   &sockaddrLen,               
+                                   isAddrOK,  
+                           (DWORD) webServerAddrs);
+    
+
+    if (hSock == INVALID_SOCKET) 
+    {
+        // Can I use FormatMessage()?
+        fprintf(stderr, "accept()/WSAAccept() failed: %d", WSAGetLastError());
+        return -1;
+    }
+    
+    ipcFd = Win32NewDescriptor(FD_SOCKET_SYNC, hSock, -1);
+       if (ipcFd == -1) 
+    {
+           closesocket(hSock);
+       }
+
+    return ipcFd;
+}
+
 /*
  *----------------------------------------------------------------------
  *
  * OS_Accept --
  *
- *     Accepts a new FastCGI connection.  This routine knows whether
- *      we're dealing with TCP based sockets or NT Named Pipes for IPC.
+ *  Accepts a new FastCGI connection.  This routine knows whether
+ *  we're dealing with TCP based sockets or NT Named Pipes for IPC.
+ *
+ *  fail_on_intr is ignored in the Win lib.
  *
  * Results:
  *      -1 if the operation fails, otherwise this is a valid IPC fd.
  *
- * Side effects:
- *      New IPC connection is accepted.
- *
  *----------------------------------------------------------------------
  */
 int OS_Accept(int listen_sock, int fail_on_intr, const char *webServerAddrs)
 {
-    /* XXX This is broken for listen_sock & fail_on_intr */
     int ipcFd = -1;
-    BOOL pConnected;
-    SOCKET hSock;
+
+    // Touch args to prevent warnings
+    listen_sock = 0; fail_on_intr = 0;
+
+    // @todo Muliple listen sockets and sockets other than 0 are not
+    // supported due to the use of globals.
 
     if (shutdownPending) 
     {
+        OS_LibShutdown();
         return -1;
     }
 
@@ -1540,104 +1697,36 @@ int OS_Accept(int listen_sock, int fail_on_intr, const char *webServerAddrs)
     {
         if (WaitForSingleObject(acceptMutex, INFINITE) == WAIT_FAILED) 
         {
+            printLastError("WaitForSingleObject() failed");
             return -1;
         }
     }
     
     if (shutdownPending) 
     {
-        if (acceptMutex != INVALID_HANDLE_VALUE) 
-        {
-            ReleaseMutex(acceptMutex);
-        }
-        return -1;
+        OS_LibShutdown();
     }
-    
-    if (listenType == FD_PIPE_SYNC) 
+    else if (listenType == FD_PIPE_SYNC) 
     {
-        pConnected = ConnectNamedPipe(hListen, &listenOverlapped) 
-            ? TRUE 
-            : (GetLastError() == ERROR_PIPE_CONNECTED);
-
-        if (! pConnected) 
-        {
-            while (WaitForSingleObject(listenOverlapped.hEvent, 1000) == WAIT_TIMEOUT) 
-            {
-                if (shutdownPending) 
-                {
-                    if (acceptMutex != INVALID_HANDLE_VALUE) 
-                    {
-                        ReleaseMutex(acceptMutex);
-                    }
-                    CancelIo(hListen);
-                    return -1;
-                }            
-            }
-        }
-        
-        if (acceptMutex != INVALID_HANDLE_VALUE) 
-        {
-            ReleaseMutex(acceptMutex);
-        }
-
-        ipcFd = Win32NewDescriptor(FD_PIPE_SYNC, (int) hListen, -1);
-           if (ipcFd == -1) 
-        {
-            DisconnectNamedPipe(hListen);
-        }
+        ipcFd = acceptNamedPipe();
     }
     else if (listenType == FD_SOCKET_SYNC)
     {
-        struct sockaddr sockaddr;
-        int sockaddrLen = sizeof(sockaddr);
-        fd_set readfds;
-        const struct timeval timeout = {1, 0};
-     
-        FD_ZERO(&readfds);
-        FD_SET((unsigned int) hListen, &readfds);
-        
-        while (select(0, &readfds, NULL, NULL, &timeout) == 0)
-        {
-            if (shutdownPending) 
-            {
-                return -1;
-            }
-        }
-        
-        hSock = (webServerAddrs == NULL)
-            ? accept((SOCKET) hListen, 
-                              &sockaddr, 
-                              &sockaddrLen)
-            : WSAAccept((unsigned int) hListen,                    
-                                       &sockaddr,  
-                                       &sockaddrLen,               
-                                       isAddrOK,  
-                               (DWORD) webServerAddrs);
-        
-        if (acceptMutex != INVALID_HANDLE_VALUE) 
-        {
-            ReleaseMutex(acceptMutex);
-        }
-
-        if (hSock == -1) 
-        {
-            return -1;
-        }
-        
-        ipcFd = Win32NewDescriptor(FD_SOCKET_SYNC, hSock, -1);
-           if (ipcFd == -1) 
-        {
-               closesocket(hSock);
-           }
+        ipcFd = acceptSocket(webServerAddrs);
     }
     else
     {
-        ASSERT(0);
+        fprintf(stderr, "unknown listenType (%d)\n", listenType);
     }
            
+    if (acceptMutex != INVALID_HANDLE_VALUE) 
+    {
+        ReleaseMutex(acceptMutex);
+    }
+
     return ipcFd;
 }
-\f
+
 /*
  *----------------------------------------------------------------------
  *
@@ -1693,7 +1782,6 @@ int OS_IpcClose(int ipcFd)
     }
 }
 
-\f
 /*
  *----------------------------------------------------------------------
  *
@@ -1711,15 +1799,14 @@ int OS_IpcClose(int ipcFd)
  */
 int OS_IsFcgi(int sock)
 {
+    // Touch args to prevent warnings
+    sock = 0;
+
     /* XXX This is broken for sock */
-    if(listenType == FD_UNUSED) {
-        return FALSE;
-    } else {
-        return TRUE;
-    }
+
+       return (listenType != FD_UNUSED); 
 }
 
-\f
 /*
  *----------------------------------------------------------------------
  *