]> granicus.if.org Git - apache/blobdiff - server/mpm/winnt/mpm_winnt.c
That's not a -D'ef - its an envar - you can't pass foo=bar in apache!
[apache] / server / mpm / winnt / mpm_winnt.c
index 9cbae716517a50b329f9f7cdaf90e816fb76b1d2..96585a7c5c7b12e68c41d6816b64aa596a9e6cf2 100644 (file)
  */
 
 #define CORE_PRIVATE 
-#include "apr_portable.h"
 #include "httpd.h" 
 #include "http_main.h" 
 #include "http_log.h" 
 #include "http_config.h"       /* for read_config */ 
 #include "http_core.h"         /* for get_remote_host */ 
 #include "http_connection.h"
+#include "apr_portable.h"
+#include "apr_getopt.h"
+#include "apr_strings.h"
 #include "ap_mpm.h"
 #include "ap_config.h"
 #include "ap_listen.h"
 #include "mpm_default.h"
-#include "service.h"
-#include "iol_socket.h"
-#include "winnt.h"
+#include "mpm_winnt.h"
+#include "mpm_common.h"
 
+typedef HANDLE thread;
 
 /*
  * Definitions of WINNT MPM specific config globals
  */
+static int workers_may_exit = 0;
+static int shutdown_in_progress = 0;
+static unsigned int g_blocked_threads = 0;
 
 static char *ap_pid_fname = NULL;
 static int ap_threads_per_child = 0;
-static int workers_may_exit = 0;
+
 static int max_requests_per_child = 0;
 static HANDLE shutdown_event;  /* used to signal shutdown to parent */
 static HANDLE restart_event;   /* used to signal a restart to parent */
 
+#define MAX_SIGNAL_NAME 30  /* Long enough for apPID_shutdown, where PID is an int */
+char signal_name_prefix[MAX_SIGNAL_NAME];
+char signal_restart_name[MAX_SIGNAL_NAME]; 
+char signal_shutdown_name[MAX_SIGNAL_NAME];
+
 static struct fd_set listenfds;
 static int num_listenfds = 0;
 static SOCKET listenmaxfd = INVALID_SOCKET;
 
-static ap_pool_t *pconf;               /* Pool for config stuff */
+static apr_pool_t *pconf;              /* Pool for config stuff */
 
 static char ap_coredump_dir[MAX_STRING_LEN];
 
@@ -96,23 +106,48 @@ static server_rec *server_conf;
 static HANDLE AcceptExCompPort = NULL;
 
 static int one_process = 0;
+static char const* signal_arg;
 
-static OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
+OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
 
 int ap_max_requests_per_child=0;
 int ap_daemons_to_start=0;
 
-static event *exit_event;
-HANDLE maintenance_event;
-ap_lock_t *start_mutex;
-int my_pid;
-int parent_pid;
+static HANDLE exit_event;
+static HANDLE maintenance_event;
+apr_lock_t *start_mutex;
+DWORD my_pid;
+DWORD parent_pid;
+
+/* This is the helper code to resolve late bound entry points 
+ * missing from one or more releases of the Win32 API...
+ * but it sure would be nice if we didn't duplicate this code
+ * from the APR ;-)
+ */
+
+static const char* const lateDllName[DLL_defined] = {
+    "kernel32", "advapi32", "mswsock",  "ws2_32"  };
+static HMODULE lateDllHandle[DLL_defined] = {
+    NULL,       NULL,       NULL,       NULL      };
 
-static ap_status_t socket_cleanup(void *sock)
+FARPROC ap_load_dll_func(ap_dlltoken_e fnLib, char* fnName, int ordinal)
 {
-    ap_socket_t *thesocket = sock;
+    if (!lateDllHandle[fnLib]) { 
+        lateDllHandle[fnLib] = LoadLibrary(lateDllName[fnLib]);
+        if (!lateDllHandle[fnLib])
+            return NULL;
+    }
+    if (ordinal)
+        return GetProcAddress(lateDllHandle[fnLib], (char *) ordinal);
+    else
+        return GetProcAddress(lateDllHandle[fnLib], fnName);
+}
+
+static apr_status_t socket_cleanup(void *sock)
+{
+    apr_socket_t *thesocket = sock;
     SOCKET sd;
-    if (ap_get_os_sock(&sd, thesocket) == APR_SUCCESS) {
+    if (apr_get_os_sock(&sd, thesocket) == APR_SUCCESS) {
         closesocket(sd);
     }
     return APR_SUCCESS;
@@ -122,17 +157,12 @@ static ap_status_t socket_cleanup(void *sock)
  * or thrown out entirely...
  */
 
-
-typedef void semaphore;
-typedef void event;
-
-static semaphore *
-create_semaphore(int initial)
+static HANDLE create_semaphore(int initial)
 {
     return(CreateSemaphore(NULL, initial, 1000000, NULL));
 }
 
-static void acquire_semaphore(semaphore *semaphore_id)
+static void acquire_semaphore(HANDLE semaphore_id)
 {
     int rv;
     
@@ -141,12 +171,12 @@ static void acquire_semaphore(semaphore *semaphore_id)
     return;
 }
 
-static int release_semaphore(semaphore *semaphore_id)
+static int release_semaphore(HANDLE semaphore_id)
 {
     return(ReleaseSemaphore(semaphore_id, 1, NULL));
 }
 
-static void destroy_semaphore(semaphore *semaphore_id)
+static void destroy_semaphore(HANDLE semaphore_id)
 {
     CloseHandle(semaphore_id);
 }
@@ -166,14 +196,15 @@ static PSECURITY_ATTRIBUTES GetNullACL()
     if (pSD == NULL || sa == NULL) {
         return NULL;
     }
+    apr_set_os_error(0);
     if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
-       || GetLastError()) {
+       || apr_get_os_error()) {
         LocalFree( pSD );
         LocalFree( sa );
         return NULL;
     }
     if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
-       || GetLastError()) {
+       || apr_get_os_error()) {
         LocalFree( pSD );
         LocalFree( sa );
         return NULL;
@@ -257,13 +288,11 @@ static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles,
  * On entry, type gives the event to signal. 0 means shutdown, 1 means 
  * graceful restart.
  */
-static void signal_parent(int type)
+void signal_parent(int type)
 {
     HANDLE e;
     char *signal_name;
-    extern char signal_shutdown_name[];
-    extern char signal_restart_name[];
-
+    
     /* after updating the shutdown_pending or restart flags, we need
      * to wake up the parent process so it can see the changes. The
      * parent will normally be waiting for either a child process
@@ -284,87 +313,55 @@ static void signal_parent(int type)
        /* Um, problem, can't signal the parent, which means we can't
         * signal ourselves to die. Ignore for now...
         */
-       ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
+       ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
                      "OpenEvent on %s event", signal_name);
        return;
     }
     if (SetEvent(e) == 0) {
        /* Same problem as above */
-       ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
+       ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
                      "SetEvent on %s event", signal_name);
        CloseHandle(e);
        return;
     }
     CloseHandle(e);
 }
+
 static int volatile is_graceful = 0;
-API_EXPORT(int) ap_graceful_stop_signalled(void)
+
+AP_DECLARE(int) ap_graceful_stop_signalled(void)
 {
     return is_graceful;
 }
-void ap_start_shutdown(void)
+
+AP_DECLARE(void) ap_start_shutdown(void)
 {
     signal_parent(0);
 }
+
+AP_DECLARE(void) ap_start_restart(int gracefully)
+{
+    is_graceful = gracefully;
+    signal_parent(1);
+}
+
 /*
  * Initialise the signal names, in the global variables signal_name_prefix, 
  * signal_restart_name and signal_shutdown_name.
  */
 
-#define MAX_SIGNAL_NAME 30  /* Long enough for apPID_shutdown, where PID is an int */
-char signal_name_prefix[MAX_SIGNAL_NAME];
-char signal_restart_name[MAX_SIGNAL_NAME]; 
-char signal_shutdown_name[MAX_SIGNAL_NAME];
-static void setup_signal_names(char *prefix)
+void setup_signal_names(char *prefix)
 {
-    ap_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);    
-    ap_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name), 
+    apr_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);    
+    apr_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name), 
        "%s_shutdown", signal_name_prefix);    
-    ap_snprintf(signal_restart_name, sizeof(signal_restart_name), 
+    apr_snprintf(signal_restart_name, sizeof(signal_restart_name), 
        "%s_restart", signal_name_prefix);    
 }
 
 /*
  * Routines that deal with sockets, some are WIN32 specific...
  */
-static int s_iInitCount = 0;
-static int AMCSocketInitialize(void)
-{
-    int iVersionRequested;
-    WSADATA wsaData;
-    int err;
-
-    if (s_iInitCount > 0) {
-       s_iInitCount++;
-       return (0);
-    }
-    else if (s_iInitCount < 0)
-       return (s_iInitCount);
-
-    /* s_iInitCount == 0. Do the initailization */
-    iVersionRequested = MAKEWORD(2, 0);
-    err = WSAStartup((WORD) iVersionRequested, &wsaData);
-    if (err) {
-       s_iInitCount = -1;
-       return (s_iInitCount);
-    }
-    if (LOBYTE(wsaData.wVersion) != 1 ||
-       HIBYTE(wsaData.wVersion) != 1) {
-       s_iInitCount = -2;
-       WSACleanup();
-       return (s_iInitCount);
-    }
-
-    s_iInitCount++;
-    return (s_iInitCount);
-
-}
-static void AMCSocketCleanup(void)
-{
-    if (--s_iInitCount == 0)
-       WSACleanup();
-    return;
-}
 
 static void sock_disable_nagle(int s) 
 {
@@ -390,13 +387,14 @@ static void sock_disable_nagle(int s)
  * Routines to deal with managing the list of listening sockets.
  */
 static ap_listen_rec *head_listener;
-static ap_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
+
+static apr_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
 {
     ap_listen_rec *lr;
     SOCKET nsd;
 
     for (lr = head_listener; lr ; lr = lr->next) {
-        ap_get_os_sock(&nsd, lr->sd);
+        apr_get_os_sock(&nsd, lr->sd);
        if (FD_ISSET(nsd, main_fds)) {
            head_listener = lr->next;
             if (head_listener == NULL)
@@ -407,6 +405,7 @@ static ap_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
     }
     return NULL;
 }
+
 static int setup_listeners(server_rec *s)
 {
     ap_listen_rec *lr;
@@ -422,7 +421,7 @@ static int setup_listeners(server_rec *s)
     for (lr = ap_listeners; lr; lr = lr->next) {
         num_listeners++;
         if (lr->sd != NULL) {
-            ap_get_os_sock(&nsd, lr->sd);
+            apr_get_os_sock(&nsd, lr->sd);
             FD_SET(nsd, &listenfds);
             if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
                 listenmaxfd = nsd;
@@ -452,7 +451,7 @@ static int setup_inherited_listeners(server_rec *s)
 
     if (ap_listeners == NULL) {
         ap_listen_rec *lr;
-        lr = ap_palloc(s->process->pool, sizeof(ap_listen_rec));
+        lr = apr_palloc(s->process->pool, sizeof(ap_listen_rec));
         if (!lr)
             return 0;
         lr->sd = NULL;
@@ -467,7 +466,7 @@ static int setup_inherited_listeners(server_rec *s)
     for (lr = ap_listeners; lr; lr = lr->next) {
         if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO), 
                       &BytesRead, (LPOVERLAPPED) NULL)) {
-            ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
+            ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
                          "setup_inherited_listeners: Unable to read socket data from parent");
             signal_parent(0);  /* tell parent to die */
             exit(1);
@@ -477,7 +476,7 @@ static int setup_inherited_listeners(server_rec *s)
         nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
                         &WSAProtocolInfo, 0, 0);
         if (nsd == INVALID_SOCKET) {
-            ap_log_error(APLOG_MARK, APLOG_CRIT, WSAGetLastError(), server_conf,
+            ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), server_conf,
                          "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
             signal_parent(0);  /* tell parent to die */
             exit(1);
@@ -488,8 +487,7 @@ static int setup_inherited_listeners(server_rec *s)
                 listenmaxfd = nsd;
             }
         }
-//        ap_register_cleanup(p, (void *)lr->sd, socket_cleanup, ap_null_cleanup);
-        ap_put_os_sock(&lr->sd, &nsd, pconf);
+        apr_put_os_sock(&lr->sd, &nsd, pconf);
         lr->count = 0;
     }
     /* Now, read the AcceptExCompPort from the parent */
@@ -514,7 +512,7 @@ static void bind_listeners_to_completion_port()
     if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
         for (lr = ap_listeners; lr; lr = lr->next) {
             int nsd;
-            ap_get_os_sock(&nsd,lr->sd);
+            apr_get_os_sock(&nsd,lr->sd);
             CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
         }
     }
@@ -599,11 +597,12 @@ typedef struct joblist_s {
  */
 
 typedef struct globals_s {
-    semaphore *jobsemaphore;
+    HANDLE jobsemaphore;
     joblist *jobhead;
     joblist *jobtail;
-    ap_lock_t *jobmutex;
+    apr_lock_t *jobmutex;
     int jobcount;
+
 } globals;
 
 globals allowed_globals =
@@ -640,7 +639,7 @@ static void add_job(int sock)
     new_job->next = NULL;
     new_job->sock = sock;
 
-    ap_lock(allowed_globals.jobmutex);
+    apr_lock(allowed_globals.jobmutex);
 
     if (allowed_globals.jobtail != NULL)
        allowed_globals.jobtail->next = new_job;
@@ -650,7 +649,7 @@ static void add_job(int sock)
     allowed_globals.jobcount++;
     release_semaphore(allowed_globals.jobsemaphore);
 
-    ap_unlock(allowed_globals.jobmutex);
+    apr_unlock(allowed_globals.jobmutex);
 }
 
 static int remove_job(void)
@@ -659,10 +658,10 @@ static int remove_job(void)
     int sock;
 
     acquire_semaphore(allowed_globals.jobsemaphore);
-    ap_lock(allowed_globals.jobmutex);
+    apr_lock(allowed_globals.jobmutex);
 
-    if (workers_may_exit && !allowed_globals.jobhead) {
-        ap_unlock(allowed_globals.jobmutex);
+    if (shutdown_in_progress && !allowed_globals.jobhead) {
+        apr_unlock(allowed_globals.jobmutex);
        return (-1);
     }
     job = allowed_globals.jobhead;
@@ -670,7 +669,7 @@ static int remove_job(void)
     allowed_globals.jobhead = job->next;
     if (allowed_globals.jobhead == NULL)
        allowed_globals.jobtail = NULL;
-    ap_unlock(allowed_globals.jobmutex);
+    apr_unlock(allowed_globals.jobmutex);
     sock = job->sock;
     free(job);
 
@@ -690,7 +689,7 @@ static void accept_and_queue_connections(void * dummy)
     int rc;
     int clen;
 
-    while (!workers_may_exit) {
+    while (!shutdown_in_progress) {
         if (ap_max_requests_per_child && (requests_this_child > ap_max_requests_per_child)) {
             break;
        }
@@ -699,10 +698,9 @@ static void accept_and_queue_connections(void * dummy)
        tv.tv_usec = 0;
        memcpy(&main_fds, &listenfds, sizeof(fd_set));
 
-//     rc = ap_select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
        rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
 
-        if (rc == 0 || (rc == SOCKET_ERROR && h_errno == WSAEINTR)) {
+        if (rc == 0 || (rc == SOCKET_ERROR && APR_STATUS_IS_EINTR(apr_get_netos_error()))) {
             count_select_errors = 0;    /* reset count of errors */            
             continue;
         }
@@ -711,12 +709,12 @@ static void accept_and_queue_connections(void * dummy)
              * select errors. This count is used to ensure we don't go into
              * a busy loop of continuous errors.
              */
-            ap_log_error(APLOG_MARK, APLOG_INFO, h_errno, server_conf, 
-                         "select failed with errno %d", h_errno);
+            ap_log_error(APLOG_MARK, APLOG_INFO, apr_get_netos_error(), server_conf, 
+                         "select failed with error %d", apr_get_netos_error());
             count_select_errors++;
             if (count_select_errors > MAX_SELECT_ERRORS) {
-                workers_may_exit = 1;
-                ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
+                shutdown_in_progress = 1;
+                ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), server_conf,
                              "Too many errors in select loop. Child process exiting.");
                 break;
             }
@@ -726,7 +724,7 @@ static void accept_and_queue_connections(void * dummy)
            lr = find_ready_listener(&main_fds);
            if (lr != NULL) {
                 /* fetch the native socket descriptor */
-                ap_get_os_sock(&nsd, lr->sd);
+                apr_get_os_sock(&nsd, lr->sd);
            }
        }
 
@@ -736,11 +734,11 @@ static void accept_and_queue_connections(void * dummy)
             if (csd == INVALID_SOCKET) {
                 csd = -1;
             }
-        } while (csd < 0 && h_errno == WSAEINTR);
+        } while (csd < 0 && APR_STATUS_IS_EINTR(apr_get_netos_error()));
 
        if (csd < 0) {
-            if (h_errno != WSAECONNABORTED) {
-               ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
+            if (APR_STATUS_IS_ECONNABORTED(apr_get_netos_error())) {
+               ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), server_conf,
                            "accept: (client socket)");
             }
        }
@@ -757,42 +755,39 @@ static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
 
     if (context == NULL) {
         /* allocate the completion context and the transaction pool */
-        context = ap_pcalloc(pconf, sizeof(COMP_CONTEXT));
+        context = apr_pcalloc(pconf, sizeof(COMP_CONTEXT));
         if (!context) {
-            ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
-                         "win9x_get_connection: ap_pcalloc() failed. Process will exit.");
+            ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
+                         "win9x_get_connection: apr_pcalloc() failed. Process will exit.");
             return NULL;
         }
-        ap_create_pool(&context->ptrans, pconf);
+        apr_create_pool(&context->ptrans, pconf);
     }
     
 
     while (1) {
-        ap_clear_pool(context->ptrans);        
+        apr_clear_pool(context->ptrans);        
         context->accept_socket = remove_job();
         if (context->accept_socket == -1) {
             return NULL;
         }
-       //ap_note_cleanups_for_socket(ptrans, csd);
-        len = sizeof(struct sockaddr);
-        context->sa_server = ap_palloc(context->ptrans, len);
+       len = sizeof(struct sockaddr);
+        context->sa_server = apr_palloc(context->ptrans, len);
         if (getsockname(context->accept_socket, 
                         context->sa_server, &len)== SOCKET_ERROR) {
-            ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(), server_conf, 
+            ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), server_conf, 
                          "getsockname failed");
             continue;
         }
         len = sizeof(struct sockaddr);
-        context->sa_client = ap_palloc(context->ptrans, len);
+        context->sa_client = apr_palloc(context->ptrans, len);
         if ((getpeername(context->accept_socket,
                          context->sa_client, &len)) == SOCKET_ERROR) {
-            ap_log_error(APLOG_MARK, APLOG_WARNING, h_errno, server_conf, 
-                         "getpeername failed with error %d\n", WSAGetLastError());
+            ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), server_conf, 
+                         "getpeername failed");
             memset(&context->sa_client, '\0', sizeof(context->sa_client));
         }
 
-        context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
-
         /* do we NEED_DUPPED_CSD ?? */
         
         return context;
@@ -815,23 +810,24 @@ static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp)
     int rc;
     DWORD BytesRead;
     DWORD CompKey;
-    int lastError;
 
     while (1) {
         context = NULL;
         rc = GetQueuedCompletionStatus(hComplPort, &BytesRead, &CompKey,
                                        &pol, 1000);
         if (!rc) {
-            lastError = GetLastError();
-            if (lastError == ERROR_OPERATION_ABORTED) {
-                ap_log_error(APLOG_MARK,APLOG_INFO,lastError, server_conf,
-                             "Child %d: - Draining a packet off the completion port.", my_pid);
+            rc = apr_get_os_error();
+            if (rc == APR_FROM_OS_ERROR(ERROR_OPERATION_ABORTED)) {
+                ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, server_conf,
+                             "Child %d: Draining an ABORTED packet off "
+                             "the AcceptEx completion port.", my_pid);
                 continue;
             }
             break;
         }
-        ap_log_error(APLOG_MARK,APLOG_INFO,APR_SUCCESS, server_conf,
-                     "Child %d: - Nuking an active connection. context = %x", my_pid, context);
+        ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
+                     "Child %d: Draining and discarding an active connection "
+                     "off the AcceptEx completion port.", my_pid);
         context = (PCOMP_CONTEXT) pol;
         if (context && bCleanUp) {
             /* It is only valid to clean-up in the process that initiated the I/O */
@@ -840,7 +836,7 @@ static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp)
         }
     }
 }
-static int create_acceptex_context(ap_pool_t *_pconf, ap_listen_rec *lr) 
+static int create_acceptex_context(apr_pool_t *_pconf, ap_listen_rec *lr) 
 {
     PCOMP_CONTEXT context;
     DWORD BytesRead;
@@ -848,10 +844,10 @@ static int create_acceptex_context(ap_pool_t *_pconf, ap_listen_rec *lr)
     int lasterror;
 
     /* allocate the completion context */
-    context = ap_pcalloc(_pconf, sizeof(COMP_CONTEXT));
+    context = apr_pcalloc(_pconf, sizeof(COMP_CONTEXT));
     if (!context) {
-        ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
-                     "create_acceptex_context: ap_pcalloc() failed. Process will exit.");
+        ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
+                     "create_acceptex_context: apr_pcalloc() failed. Process will exit.");
         return -1;
     }
 
@@ -859,16 +855,16 @@ static int create_acceptex_context(ap_pool_t *_pconf, ap_listen_rec *lr)
     context->lr = lr;
     context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); 
     if (context->Overlapped.hEvent == NULL) {
-        ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
+        ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
                      "create_acceptex_context: CreateEvent() failed. Process will exit.");
         return -1;
     }
 
     /* create and initialize the accept socket */
-    ap_get_os_sock(&nsd, context->lr->sd);
+    apr_get_os_sock(&nsd, context->lr->sd);
     context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
     if (context->accept_socket == INVALID_SOCKET) {
-        ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
+        ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_netos_error(), server_conf,
                      "create_acceptex_context: socket() failed. Process will exit.");
         return -1;
     }
@@ -877,28 +873,32 @@ static int create_acceptex_context(ap_pool_t *_pconf, ap_listen_rec *lr)
     if (setsockopt(context->accept_socket, SOL_SOCKET,
                    SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
                    sizeof(nsd))) {
-        ap_log_error(APLOG_MARK, APLOG_ERR, WSAGetLastError(), server_conf,
+        ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), server_conf,
                      "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
         /* Not a failure condition. Keep running. */
     }
 
-    ap_create_pool(&context->ptrans, _pconf);
-    context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
-    context->recv_buf = context->conn_io->inbase;
-    context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
+    apr_create_pool(&context->ptrans, _pconf);
 
+    /* recv_buf must be large enough to hold the remote and local
+     * addresses. Note that recv_buf_size is the amount of recv_buf
+     * available for AcceptEx to receive bytes into. Since we 
+     * don't want AcceptEx to do a recv, set the size to 0.
+     */
+    context->recv_buf = apr_pcalloc(_pconf, 2*PADDED_ADDR_SIZE);
+    context->recv_buf_size = 0;
 
     /* AcceptEx on the completion context. The completion context will be signaled
      * when a connection is accepted. */
     if (!AcceptEx(nsd, context->accept_socket,
                   context->recv_buf, 
-                  0, //context->recv_buf_size,
+                  context->recv_buf_size,
                   PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
                   &BytesRead,
                   (LPOVERLAPPED) context)) {
-        lasterror = WSAGetLastError();
-        if (lasterror != ERROR_IO_PENDING) {
-            ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
+        lasterror = apr_get_netos_error();
+        if (lasterror != APR_FROM_OS_ERROR(ERROR_IO_PENDING)) {
+            ap_log_error(APLOG_MARK,APLOG_ERR, lasterror, server_conf,
                          "create_acceptex_context: AcceptEx failed. Process will exit.");
             return -1;
         }
@@ -908,58 +908,71 @@ static int create_acceptex_context(ap_pool_t *_pconf, ap_listen_rec *lr)
 
     return 0;
 }
-static ap_inline int reset_acceptex_context(PCOMP_CONTEXT context) 
+static apr_inline apr_status_t reset_acceptex_context(PCOMP_CONTEXT context) 
 {
     DWORD BytesRead;
     SOCKET nsd;
-    int lasterror;
+    int rc, i;
 
-    context->lr->count++;
+    /* reset the buffer pools */
+    apr_clear_pool(context->ptrans);
+    context->sock = NULL;
 
     /* recreate and initialize the accept socket if it is not being reused */
-    ap_get_os_sock(&nsd, context->lr->sd);
-    if (context->accept_socket == INVALID_SOCKET) {
-        context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+    apr_get_os_sock(&nsd, context->lr->sd);
+
+    /* AcceptEx on the completion context. The completion context will be signaled
+     * when a connection is accepted. Hack Alert: TransmitFile, under certain 
+     * circumstances, can 'recycle' accept sockets, saving the overhead of calling 
+     * socket(). Occasionally this fails (usually when the client closes his end 
+     * of the connection early). When this occurs, AcceptEx will fail with 10022, 
+     * Invalid Parameter. When this occurs, just open a fresh accept socket and 
+     * retry the call.
+     */
+    for (i=0; i<2; i++) {
         if (context->accept_socket == INVALID_SOCKET) {
-            ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
-                         "reset_acceptex_context: socket() failed. Process will exit.");
-            return -1;
-        }
-        
-        /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
-        if (setsockopt(context->accept_socket, SOL_SOCKET,
-                       SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
-                       sizeof(nsd))) {
-            ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(),
-                         server_conf,
-                         "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
-            /* Not a failure condition. Keep running. */
-        }
-    }
+            context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+            if (context->accept_socket == INVALID_SOCKET) {
+                rc = apr_get_netos_error();
+                ap_log_error(APLOG_MARK,APLOG_ERR, rc, server_conf,
+                             "reset_acceptex_context: socket() failed. Process will exit.");
+                return rc;
+            }
 
-    /* reset the completion context */
-    ap_clear_pool(context->ptrans);
-    context->sock = NULL;
-    context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
-    context->recv_buf = context->conn_io->inbase;
-    context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
+            /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
+            if (setsockopt(context->accept_socket, SOL_SOCKET,
+                           SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd, sizeof(nsd))) {
+                ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(),
+                             server_conf,
+                             "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
+            }
+        }
 
-    /* AcceptEx on the completion context. The completion context will be signaled
-     * when a connection is accepted. */
-    if (!AcceptEx(nsd, context->accept_socket, 
-                  context->recv_buf, 
-                  0, //context->recv_buf_size,
-                  PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
-                  &BytesRead, (LPOVERLAPPED) context)) {
-        lasterror = WSAGetLastError();
-        if (lasterror != ERROR_IO_PENDING) {
-            ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
-                         "reset_acceptex_context: AcceptEx failed. Leaving the process running.");
-            return -1;
+        if (!AcceptEx(nsd, context->accept_socket, 
+                      context->recv_buf,                   
+                      context->recv_buf_size,
+                      PADDED_ADDR_SIZE, 
+                      PADDED_ADDR_SIZE, 
+                      &BytesRead, 
+                      (LPOVERLAPPED) context)) {
+
+            rc = apr_get_netos_error();
+            if (rc != APR_FROM_OS_ERROR(ERROR_IO_PENDING)) {
+                ap_log_error(APLOG_MARK, APLOG_DEBUG, rc, server_conf,
+                             "reset_acceptex_context: AcceptEx failed for "
+                             "listening socket: %d and accept socket: %d. Getting a new accept socket.", 
+                             nsd, context->accept_socket);
+                closesocket(context->accept_socket);
+                context->accept_socket = INVALID_SOCKET;
+                continue;
+            }
         }
+        break;
     }
 
-    return 0;
+    context->lr->count++;
+
+    return APR_SUCCESS;
 }
 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
 {
@@ -969,71 +982,112 @@ static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
     DWORD CompKey;
     DWORD BytesRead;
 
+
     if (context != NULL) {
-        /* If child shutdown has been signaled, clean-up the completion context */
-        if (workers_may_exit) {
+        if (shutdown_in_progress) {
+            /* Clean-up the AcceptEx completion context */
             CloseHandle(context->Overlapped.hEvent);
-            /* destroy pool */
+            if (context->accept_socket != INVALID_SOCKET)
+                closesocket(context->accept_socket);
         }
         else {
-            context->accept_socket = INVALID_SOCKET; /* Don't reuse the accept_socket */
-            if (reset_acceptex_context(context) == -1) {
-                if (context->accept_socket != -1)
+            /* Prepare the completion context for reuse */
+            if ((rc = reset_acceptex_context(context)) != APR_SUCCESS) {
+                ap_log_error(APLOG_MARK, APLOG_CRIT, rc, server_conf,
+                             "Child %d: winnt_get_connection: reset_acceptex_context failed.",
+                             my_pid); 
+                if (context->accept_socket != INVALID_SOCKET)
                     closesocket(context->accept_socket);
                 CloseHandle(context->Overlapped.hEvent);
-                return NULL;
+                /* Probably should just die now... */
             }
         }
     }
 
+    /* May need to atomize the workers_may_exit check with the 
+     * g_blocked_threads++ */
+    if (workers_may_exit) {
+        return NULL;
+    }
+    g_blocked_threads++;
+        
     while (1) {
-        rc = GetQueuedCompletionStatus(AcceptExCompPort,
-                                       &BytesRead,
-                                       &CompKey,
-                                       &pol,
-                                       INFINITE);
+        rc = GetQueuedCompletionStatus(AcceptExCompPort, &BytesRead, &CompKey,
+                                       &pol, INFINITE);
         if (!rc) {
-            ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
-                         "Child %d: - GetQueuedCompletionStatus() failed", my_pid);
-            /* During a restart, the new child process can catch 
-             * ERROR_OPERATION_ABORTED completion packets
-             * posted by the old child process. Just continue...
-             */
+            rc = apr_get_os_error();
+            if (rc != APR_FROM_OS_ERROR(ERROR_OPERATION_ABORTED)) {
+                /* Is this a deadly condition? 
+                 * We sometimes get ERROR_NETNAME_DELETED when a client
+                 * disconnects when attempting to reuse sockets. Not sure why 
+                 * we see this now and not during AcceptEx(). Reset the
+                 * AcceptEx context and continue...
+                 */
+                ap_log_error(APLOG_MARK,APLOG_DEBUG, rc, server_conf,
+                             "Child %d: - GetQueuedCompletionStatus() failed", 
+                             my_pid);
+                /* Reset the completion context */
+                if (pol) {
+                    context = (PCOMP_CONTEXT) pol;
+                    if (context->accept_socket != INVALID_SOCKET)
+                        closesocket(context->accept_socket);
+                    if ((rc = reset_acceptex_context(context)) != APR_SUCCESS) {
+                        ap_log_error(APLOG_MARK, APLOG_CRIT, rc, server_conf,
+                                     "Child %d: winnt_get_connection: reset_acceptex_context failed.",
+                                     my_pid); 
+                        if (context->accept_socket != INVALID_SOCKET)
+                            closesocket(context->accept_socket);
+                        CloseHandle(context->Overlapped.hEvent);
+                        /* Probably should just die now... */
+                    }
+                }
+            }
+            else {
+                /* Sometimes we catch ERROR_OPERATION_ABORTED completion packets
+                 * from the old child process (during a restart). Ignore them.
+                 */
+                ap_log_error(APLOG_MARK,APLOG_DEBUG, rc, server_conf,
+                             "Child %d: - Draining ERROR_OPERATION_ABORTED packet off "
+                             "the completion port.", my_pid);
+            }
             continue;
         }
 
-        /* Check the Completion Key.
-         * == my_pid indicate this process wants to exit
-         * == 0 implies valid i/o completion
-         * != 0 implies a posted completion packet by an old
-         *     process. Just ignore it.
-         */
-        if (CompKey == my_pid) {
-            return NULL;
-        }
-        if (CompKey != 0)
+        if (CompKey != 0) {
+            /* CompKey == my_pid means this thread was unblocked by
+             * the shutdown code (not by io completion).
+             */
+            if (CompKey == my_pid) {
+                g_blocked_threads--;
+                return NULL;
+            }
+            /* Sometimes we catch shutdown io completion packets
+             * posted by the old child process (during a restart). Ignore them.
+             */
             continue;
+        }
 
         context = (PCOMP_CONTEXT) pol;
         break;
     }
 
+    g_blocked_threads--;
+
     /* Check to see if we need to create more completion contexts,
      * but only if we are not in the process of shutting down
      */
-    if (!workers_may_exit) {
-        ap_lock(allowed_globals.jobmutex);
+    if (!shutdown_in_progress) {
+        apr_lock(allowed_globals.jobmutex);
         context->lr->count--;
         if (context->lr->count < 2) {
             SetEvent(maintenance_event);
         }
-        ap_unlock(allowed_globals.jobmutex);
+        apr_unlock(allowed_globals.jobmutex);
     }
 
     /* Received a connection */
-    context->conn_io->incnt = BytesRead;
     GetAcceptExSockaddrs(context->recv_buf, 
-                         0, //context->recv_buf_size,
+                         context->recv_buf_size,
                          PADDED_ADDR_SIZE,
                          PADDED_ADDR_SIZE,
                          &context->sa_server,
@@ -1067,10 +1121,11 @@ static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
 static void worker_main(int child_num)
 {
     PCOMP_CONTEXT context = NULL;
+    apr_os_sock_info_t sockinfo;
 
     while (1) {
-        conn_rec *current_conn;
-        ap_iol *iol;
+        conn_rec *c;
+        apr_int32_t disconnected;
 
         /* Grab a connection off the network */
         if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
@@ -1083,25 +1138,28 @@ static void worker_main(int child_num)
         if (!context)
             break;
         sock_disable_nagle(context->accept_socket);
-        ap_put_os_sock(&context->sock, &context->accept_socket, context->ptrans);
-//        ap_register_cleanup(context->ptrans, context->sock, socket_cleanup, ap_null_cleanup);
-        iol = win32_attach_socket(context->ptrans, context->sock);
-        if (iol == NULL) {
-            ap_log_error(APLOG_MARK, APLOG_ERR, APR_ENOMEM, server_conf,
-                         "worker_main: attach_socket() failed. Continuing...");
-            closesocket(context->accept_socket);
-            continue;
-        }
-        ap_bpush_iol(context->conn_io, iol);
-        current_conn = ap_new_connection(context->ptrans, server_conf, context->conn_io,
-                                         (struct sockaddr_in *) context->sa_client,
-                                         (struct sockaddr_in *) context->sa_server,
-                                         child_num);
 
-        ap_process_connection(current_conn);
+        sockinfo.os_sock = &context->accept_socket;
+        sockinfo.local   = context->sa_server;
+        sockinfo.remote  = context->sa_client;
+        sockinfo.family  = APR_INET;
+        sockinfo.type    = SOCK_STREAM;
+        apr_make_os_sock(&context->sock, &sockinfo, context->ptrans);
+
+        c = ap_new_connection(context->ptrans, server_conf, context->sock,
+                              child_num);
+
+        ap_process_connection(c);
+
+
+        apr_getsocketopt(context->sock, APR_SO_DISCONNECTED, &disconnected);
+        if (!disconnected) {
+            context->accept_socket = INVALID_SOCKET;
+            ap_lingering_close(c);
+        }
     }
 
-    ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
+    ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, server_conf,
                  "Child %d: Thread exiting.", my_pid);
 #if 0
 
@@ -1110,7 +1168,7 @@ static void worker_main(int child_num)
     /* TODO: Add code to clean-up completion contexts here */
 }
 
-static void cleanup_thread(thread **handles, int *thread_cnt, int thread_to_clean)
+static void cleanup_thread(thread *handles, int *thread_cnt, int thread_to_clean)
 {
     int i;
 
@@ -1127,7 +1185,7 @@ static void create_listeners()
     for (lr = ap_listeners; lr != NULL; lr = lr->next) {
         while (lr->count < NUM_LISTENERS) {
             if (create_acceptex_context(pconf, lr) == -1) {
-                ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
+                ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
                              "Unable to create an AcceptEx completion context -- process will exit");
                 signal_parent(0);      /* tell parent to die */
             }
@@ -1146,28 +1204,28 @@ static void create_listeners()
  */
 static void child_main()
 {
-    ap_status_t status;
+    apr_status_t status;
     HANDLE child_events[2];
     char* exit_event_name;
     int nthreads = ap_threads_per_child;
-    int thread_id;
-    thread **child_handles;
+    int tid;
+    thread *child_handles;
     int rv;
     time_t end_time;
     int i;
     int cld;
-    ap_pool_t *pchild;
+    apr_pool_t *pchild;
 
 
     /* This is the child process or we are running in single process
      * mode.
      */
-    exit_event_name = ap_psprintf(pconf, "apC%d", my_pid);
-    setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
+    exit_event_name = apr_psprintf(pconf, "apC%d", my_pid);
+    setup_signal_names(apr_psprintf(pconf,"ap%d", parent_pid));
 
     if (one_process) {
         /* Single process mode */
-        ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
+        apr_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
         exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
 
         setup_listeners(server_conf);
@@ -1175,7 +1233,7 @@ static void child_main()
     }
     else {
         /* Child process mode */
-        ap_child_init_lock(&start_mutex, signal_name_prefix, pconf);
+        apr_child_init_lock(&start_mutex, signal_name_prefix, pconf);
         exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
                      "Child %d: exit_event_name = %s", my_pid, exit_event_name);
@@ -1192,16 +1250,16 @@ static void child_main()
     ap_assert(exit_event);
     ap_assert(maintenance_event);
 
-    ap_create_pool(&pchild, pconf);
+    apr_create_pool(&pchild, pconf);
     allowed_globals.jobsemaphore = create_semaphore(0);
-    ap_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
+    apr_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
 
     /*
      * Wait until we have permission to start accepting connections.
      * start_mutex is used to ensure that only one child ever
      * goes into the listen/accept loop at once.
      */
-    status = ap_lock(start_mutex);
+    status = apr_lock(start_mutex);
     if (status != APR_SUCCESS) {
        ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
                      "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
@@ -1214,17 +1272,17 @@ static void child_main()
     /* Create the worker thread pool */
     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
                  "Child %d: Starting %d worker threads.", my_pid, nthreads);
-    child_handles = (thread *) alloca(nthreads * sizeof(int));
+    child_handles = (thread) alloca(nthreads * sizeof(int));
     for (i = 0; i < nthreads; i++) {
-        child_handles[i] = (thread *) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
-                                                     NULL, 0, &thread_id);
+        child_handles[i] = (thread) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
+                                                   NULL, 0, &tid);
     }
 
     /* Begin accepting connections */
     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
         /* Win95/98: Start the accept thread */
         _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) accept_and_queue_connections,
-                       (void *) i, 0, &thread_id);
+                       (void *) i, 0, &tid);
     } else {
         /* Windows NT/2000: Create AcceptEx completion contexts */
         create_listeners();
@@ -1243,33 +1301,26 @@ static void child_main()
      *    To do periodic maintenance on the server (check for thread exits,
      *    number of completion contexts, etc.)
      */
-    while (!workers_may_exit) {
+    while (1) {
         rv = WaitForMultipleObjects(2, (HANDLE *) child_events, FALSE, INFINITE);
         cld = rv - WAIT_OBJECT_0;
         if (rv == WAIT_FAILED) {
             /* Something serious is wrong */
-            workers_may_exit = 1;
-            ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
-                         "Child %d: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
-            /* Give a busy server the chance to drain AcceptEx completion contexts
-             * by servicing connections. Note that the setting of workers_may_exit
-             * prevents new AcceptEx completion contexts from being created.
-             */
-            Sleep(1000);
-
-            /* Drain any remaining contexts. May loose a few connections here. */
-            drain_acceptex_complport(AcceptExCompPort, FALSE);
+            ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
+                         "Child %d: WAIT_FAILED -- shutting down server");
+            break;
         }
         else if (rv == WAIT_TIMEOUT) {
             /* Hey, this cannot happen */
-            ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
-                         "Child %d: Server maintenance...", my_pid);
+            ap_log_error(APLOG_MARK, APLOG_CRIT, APR_SUCCESS, server_conf,
+                         "Child %d: WAIT_TIMEOUT -- shutting down server", my_pid);
+            break;
         }
         else if (cld == 0) {
             /* Exit event was signaled */
-            workers_may_exit = 1;
             ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
                          "Child %d: Exit event signaled. Child process is ending.", my_pid);
+            break;
         }
         else {
             /* Child maintenance event signaled */
@@ -1278,29 +1329,59 @@ static void child_main()
             }
             ResetEvent(maintenance_event);
             ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
-                         "Child %d: Child maintenance event signaled...", my_pid);
+                         "Child %d: Child maintenance event signaled.", my_pid);
         }
     }
 
+    /* Setting is_graceful will close keep-alive connections */
+    is_graceful = 1;
+
     /* Shutdown the worker threads */
     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
+        /* workers_may_exit = 1; Not used on Win9x */
+        shutdown_in_progress = 1;
         for (i = 0; i < nthreads; i++) {
             add_job(-1);
         }
     }
     else { /* Windows NT/2000 */
-        /* Sometimes posted completion contexts intended for this process
-         * are consumed by the new process (during restart). Send a few 
-         * extra to compensate. At worst, this process may hang around
-         * for several minutes because a thread is not exiting because
-         * it is blocked on GetQueuedCompletionStatus.
+        SOCKET nsd;
+        ap_listen_rec *lr;
+        /*
+         * Setting shutdown_in_progress prevents new AcceptEx completion 
+         * contexts from being queued to the port but allows threads to 
+         * continue consuming from the port. This gives the server a 
+         * chance to handle any accepted connections.
+         */
+        shutdown_in_progress = 1;
+        Sleep(1000);
+        
+        /* Setting workers_may_exit prevents threads from consumimg from the 
+         * completion port (especially threads that unblock off of keep-alive
+         * connections later on).
          */
-        for (i=0; i < 2*nthreads; i++) {
-            if (!PostQueuedCompletionStatus(AcceptExCompPort, 0, my_pid, NULL)) {
-                ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
-                             "PostQueuedCompletionStatus failed");
+        workers_may_exit = 1;
+
+        /* Unblock threads blocked on the completion port */
+        apr_lock(allowed_globals.jobmutex);
+        while (g_blocked_threads > 0) {
+            ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
+                         "Child %d: %d threads blocked on the completion port", my_pid, g_blocked_threads);
+            for (i=g_blocked_threads; i > 0; i--) {
+                PostQueuedCompletionStatus(AcceptExCompPort, 0, my_pid, NULL);
             }
+            Sleep(1000);
+        }
+        apr_unlock(allowed_globals.jobmutex);
+
+        /* Cancel any remaining pending AcceptEx completion contexts */
+        for (lr = ap_listeners; lr != NULL; lr = lr->next) {
+            apr_get_os_sock(&nsd,lr->sd);
+            CancelIo((HANDLE) nsd);
         }
+
+        /* Drain the canceled contexts off the port */
+        drain_acceptex_complport(AcceptExCompPort, TRUE);
     }
 
     /* Release the start_mutex to let the new process (in the restart
@@ -1308,7 +1389,7 @@ static void child_main()
      */
     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
                  "Child %d: Releasing the start mutex", my_pid);
-    ap_unlock(start_mutex);
+    apr_unlock(start_mutex);
 
     /* Give busy worker threads a chance to service their connections.
      * Kill them off if they take too long
@@ -1335,9 +1416,9 @@ static void child_main()
 
     CloseHandle(AcceptExCompPort);
     destroy_semaphore(allowed_globals.jobsemaphore);
-    ap_destroy_lock(allowed_globals.jobmutex);
+    apr_destroy_lock(allowed_globals.jobmutex);
 
-    ap_destroy_pool(pchild);
+    apr_destroy_pool(pchild);
     CloseHandle(exit_event);
 }
 
@@ -1386,15 +1467,17 @@ static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *
     (*processes)--;
 }
 
-static int create_process(ap_pool_t *p, HANDLE *handles, HANDLE *events, int *processes)
+static int create_process(apr_pool_t *p, HANDLE *handles, HANDLE *events, int *processes)
 {
-
     int rv;
     char buf[1024];
     char *pCommand;
+    char *pEnvVar;
+    char *pEnvBlock;
     int i;
+    int iEnvBlockLen;
     STARTUPINFO si;           /* Filled in prior to call to CreateProcess */
-    PROCESS_INFORMATION pi;   /* filled in on call to CreateProces */
+    PROCESS_INFORMATION pi;   /* filled in on call to CreateProcess */
 
     ap_listen_rec *lr;
     DWORD BytesWritten;
@@ -1402,6 +1485,10 @@ static int create_process(ap_pool_t *p, HANDLE *handles, HANDLE *events, int *pr
     HANDLE hPipeWrite = NULL;
     SECURITY_ATTRIBUTES sa = {0};  
 
+    HANDLE kill_event;
+    LPWSAPROTOCOL_INFO  lpWSAProtocolInfo;
+    HANDLE hDupedCompPort;
+
     sa.nLength = sizeof(sa);
     sa.bInheritHandle = TRUE;
     sa.lpSecurityDescriptor = NULL;
@@ -1416,26 +1503,49 @@ static int create_process(ap_pool_t *p, HANDLE *handles, HANDLE *events, int *pr
                      "Parent: Path to Apache process too long");
         return -1;
     } else if (rv == 0) {
-        ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
+        ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
                      "Parent: GetModuleFileName() returned NULL for current process.");
         return -1;
     }
 
     /* Build the command line */
-    pCommand = ap_psprintf(p, "\"%s\"", buf);  
+    pCommand = apr_psprintf(p, "\"%s\"", buf);  
     for (i = 1; i < server_conf->process->argc; i++) {
-        pCommand = ap_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
+        pCommand = apr_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
     }
 
+    /* Build the environment, since Win9x disrespects the active env */
+    pEnvVar = apr_psprintf(p, "AP_PARENT_PID=%i", parent_pid);
+    /*
+     * Win32's CreateProcess call requires that the environment
+     * be passed in an environment block, a null terminated block of
+     * null terminated strings.
+     */  
+    i = 0;
+    iEnvBlockLen = 1;
+    while (_environ[i]) {
+        iEnvBlockLen += strlen(_environ[i]) + 1;
+        i++;
+    }
+
+    pEnvBlock = (char *)apr_pcalloc(p, iEnvBlockLen + strlen(pEnvVar) + 1);
+    strcpy(pEnvBlock, pEnvVar);
+    pEnvVar = strchr(pEnvBlock, '\0') + 1;
+
+    i = 0;
+    while (_environ[i]) {
+        strcpy(pEnvVar, _environ[i]);
+        pEnvVar = strchr(pEnvVar, '\0') + 1;
+        i++;
+    }
+    pEnvVar = '\0';
     /* Create a pipe to send socket info to the child */
     if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
-        ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
-                     "Parent: Unable to create pipe to child process.\n");
+        ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
+                     "Parent: Unable to create pipe to child process.");
         return -1;
     }
 
-    SetEnvironmentVariable("AP_PARENT_PID",ap_psprintf(p,"%d",parent_pid));
-
     /* Give the read end of the pipe (hPipeRead) to the child as stdin. The 
      * parent will write the socket data to the child on this pipe.
      */
@@ -1449,10 +1559,10 @@ static int create_process(ap_pool_t *p, HANDLE *handles, HANDLE *events, int *pr
     if (!CreateProcess(NULL, pCommand, NULL, NULL, 
                        TRUE,               /* Inherit handles */
                        CREATE_SUSPENDED,   /* Creation flags */
-                       NULL,               /* Environment block */
+                       pEnvBlock,          /* Environment block */
                        NULL,
                        &si, &pi)) {
-        ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
+        ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
                      "Parent: Not able to create the child process.");
         /*
          * We must close the handles to the new process and its main thread
@@ -1462,78 +1572,73 @@ static int create_process(ap_pool_t *p, HANDLE *handles, HANDLE *events, int *pr
         CloseHandle(pi.hThread);
         return -1;
     }
-    else {
-        HANDLE kill_event;
-        LPWSAPROTOCOL_INFO  lpWSAProtocolInfo;
-        HANDLE hDupedCompPort;
+    
+    ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
+                 "Parent: Created child process %d", pi.dwProcessId);
 
-        ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
-                     "Parent: Created child process %d", pi.dwProcessId);
-
-        SetEnvironmentVariable("AP_PARENT_PID",NULL);
-
-        /* Create the exit_event, apCchild_pid */
-        sa.nLength = sizeof(sa);
-        sa.bInheritHandle = TRUE;
-        sa.lpSecurityDescriptor = NULL;        
-        kill_event = CreateEvent(&sa, TRUE, FALSE, ap_psprintf(pconf,"apC%d", pi.dwProcessId));
-        if (!kill_event) {
-            ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
-                         "Parent: Could not create exit event for child process");
-            CloseHandle(pi.hProcess);
-            CloseHandle(pi.hThread);
-            return -1;
-        }
-        
-        /* Assume the child process lives. Update the process and event tables */
-        handles[*processes] = pi.hProcess;
-        events[*processes] = kill_event;
-        (*processes)++;
+    SetEnvironmentVariable("AP_PARENT_PID",NULL);
 
-        /* We never store the thread's handle, so close it now. */
-        ResumeThread(pi.hThread);
+    /* Create the exit_event, apCchild_pid */
+    sa.nLength = sizeof(sa);
+    sa.bInheritHandle = TRUE;
+    sa.lpSecurityDescriptor = NULL;        
+    kill_event = CreateEvent(&sa, TRUE, FALSE, apr_psprintf(pconf,"apC%d", pi.dwProcessId));
+    if (!kill_event) {
+        ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
+                     "Parent: Could not create exit event for child process");
+        CloseHandle(pi.hProcess);
         CloseHandle(pi.hThread);
-
-        /* Run the chain of open sockets. For each socket, duplicate it 
-         * for the target process then send the WSAPROTOCOL_INFO 
-         * (returned by dup socket) to the child */
-        for (lr = ap_listeners; lr; lr = lr->next) {
-            int nsd;
-            lpWSAProtocolInfo = ap_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
-            ap_get_os_sock(&nsd,lr->sd);
-            ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
-                         "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
-            if (WSADuplicateSocket(nsd, pi.dwProcessId,
-                                   lpWSAProtocolInfo) == SOCKET_ERROR) {
-                ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, server_conf,
-                             "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
-                return -1;
-            }
-
-            if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
-                           &BytesWritten,
-                           (LPOVERLAPPED) NULL)) {
-                ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
-                             "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
-                return -1;
-            }
-            ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
-                         "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
+        return -1;
+    }
+    
+    /* Assume the child process lives. Update the process and event tables */
+    handles[*processes] = pi.hProcess;
+    events[*processes] = kill_event;
+    (*processes)++;
+
+    /* We never store the thread's handle, so close it now. */
+    ResumeThread(pi.hThread);
+    CloseHandle(pi.hThread);
+    /* Run the chain of open sockets. For each socket, duplicate it 
+     * for the target process then send the WSAPROTOCOL_INFO 
+     * (returned by dup socket) to the child */
+    for (lr = ap_listeners; lr; lr = lr->next) {
+        int nsd;
+        lpWSAProtocolInfo = apr_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
+        apr_get_os_sock(&nsd,lr->sd);
+        ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
+                     "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
+        if (WSADuplicateSocket(nsd, pi.dwProcessId,
+                               lpWSAProtocolInfo) == SOCKET_ERROR) {
+            ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), server_conf,
+                         "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
+            return -1;
         }
-        if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
-            /* Now, send the AcceptEx completion port to the child */
-            if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort, 
-                                 pi.hProcess, &hDupedCompPort,  0,
-                                 TRUE, DUPLICATE_SAME_ACCESS)) {
-                ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
-                             "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
-                return -1;
-            }
 
-            WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
+        if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
+                       &BytesWritten,
+                       (LPOVERLAPPED) NULL)) {
+            ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
+                         "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
+            return -1;
         }
+        ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_DEBUG, APR_SUCCESS, server_conf,
+                     "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
     }
+    if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
+        /* Now, send the AcceptEx completion port to the child */
+        if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort, 
+                             pi.hProcess, &hDupedCompPort,  0,
+                             TRUE, DUPLICATE_SAME_ACCESS)) {
+            ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
+                         "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
+            return -1;
+        }
 
+        WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
+    }
+    
     CloseHandle(hPipeRead);
     CloseHandle(hPipeWrite);        
 
@@ -1559,20 +1664,21 @@ static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_even
     /* Create child process 
      * Should only be one in this version of Apache for WIN32 
      */
-    service_set_status(SERVICE_START_PENDING);
     while (remaining_children_to_start--) {
         if (create_process(pconf, process_handles, process_kill_events, 
                            &current_live_processes) < 0) {
-            ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
+            ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
                          "master_main: create child process failed. Exiting.");
             shutdown_pending = 1;
             goto die_now;
         }
     }
-    service_set_status(SERVICE_RUNNING);
-
-    restart_pending = shutdown_pending = 0;
     
+    restart_pending = shutdown_pending = 0;
+
+    if (!strcasecmp(signal_arg, "runservice"))
+        mpm_service_started();
+
     /* Wait for shutdown or restart events or for child death */
     process_handles[current_live_processes] = shutdown_event;
     process_handles[current_live_processes+1] = restart_event;
@@ -1582,13 +1688,13 @@ static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_even
     cld = rv - WAIT_OBJECT_0;
     if (rv == WAIT_FAILED) {
         /* Something serious is wrong */
-        ap_log_error(APLOG_MARK,APLOG_CRIT, GetLastError(), server_conf,
+        ap_log_error(APLOG_MARK,APLOG_CRIT, apr_get_os_error(), server_conf,
                      "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
         shutdown_pending = 1;
     }
     else if (rv == WAIT_TIMEOUT) {
         /* Hey, this cannot happen */
-        ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
+        ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
                      "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
         shutdown_pending = 1;
     }
@@ -1597,9 +1703,9 @@ static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_even
         shutdown_pending = 1;
         printf("shutdown event signaled\n");
         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s, 
-                     "master_main: Shutdown event signaled -- doing server shutdown.");
+                     "Parent: SHUTDOWN EVENT SIGNALED -- Shutting down the server.");
         if (ResetEvent(shutdown_event) == 0) {
-            ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
+            ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
                          "ResetEvent(shutdown_event)");
         }
 
@@ -1609,20 +1715,20 @@ static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_even
         int children_to_kill = current_live_processes;
         restart_pending = 1;
         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, s, 
-                     "master_main: Restart event signaled. Doing a graceful restart.");
+                     "Parent: RESTART EVENT SIGNALED -- Restarting the server.");
         if (ResetEvent(restart_event) == 0) {
-            ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
+            ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
                          "master_main: ResetEvent(restart_event) failed.");
         }
         /* Signal each child process to die 
          * We are making a big assumption here that the child process, once signaled,
          * will REALLY go away. Since this is a restart, we do not want to hold the 
          * new child process up waiting for the old child to die. Remove the old 
-         * child out of the process_handles ap_table_t and hope for the best...
+         * child out of the process_handles apr_table_t and hope for the best...
          */
         for (i = 0; i < children_to_kill; i++) {
             if (SetEvent(process_kill_events[i]) == 0)
-                ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
+                ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
                              "master_main: SetEvent for child process in slot #%d failed", i);
             cleanup_process(process_handles, process_kill_events, i, &current_live_processes);
         }
@@ -1630,15 +1736,17 @@ static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_even
     else {
         /* A child process must have exited because of a fatal error condition (seg fault, etc.). 
          * Remove the dead process 
-         * from the process_handles and process_kill_events ap_table_t and create a new
+         * from the process_handles and process_kill_events apr_table_t and create a new
          * child process.
          * TODO: Consider restarting the child immediately without looping through http_main
          * and without rereading the configuration. Will need this if we ever support multiple 
          * children. One option, create a parent thread which waits on child death and restarts it.
+         * Consider, however, that if the user makes httpd.conf invalid, we want to die before
+         * our child tries it... otherwise we have a nasty loop.
          */
         restart_pending = 1;
         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf, 
-                     "master_main: Child process failed. Restarting the child process.");
+                     "Parent: CHILD PROCESS FAILED -- Restarting the child process.");
         ap_assert(cld < current_live_processes);
         cleanup_process(process_handles, process_kill_events, cld, &current_live_processes);
         /* APD2("main_process: child in slot %d died", rv); */
@@ -1650,13 +1758,18 @@ static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_even
     }
 
 die_now:
-    if (shutdown_pending) {
+    if (shutdown_pending) 
+    {
         int tmstart = time(NULL);
+        
+        if (strcasecmp(signal_arg, "runservice")) {
+            mpm_service_stopping();
+        }
         /* Signal each child processes to die */
         for (i = 0; i < current_live_processes; i++) {
             printf("SetEvent handle = %d\n", process_kill_events[i]);
             if (SetEvent(process_kill_events[i]) == 0)
-                ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
+                ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
                              "master_main: SetEvent for child process in slot #%d failed", i);
         }
 
@@ -1671,7 +1784,7 @@ die_now:
         }
         for (i = 0; i < current_live_processes; i++) {
             ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
-                         "forcing termination of child #%d (handle %d)", i, process_handles[i]);
+                         "Parent: Forcing termination of child #%d (handle %d)", i, process_handles[i]);
             TerminateProcess((HANDLE) process_handles[i], 1);
         }
         return 0;  /* Tell the caller we do not want to restart */
@@ -1680,28 +1793,264 @@ die_now:
     return 1;      /* Tell the caller we want a restart */
 }
 
-/* 
- * winnt_pre_config() hook
+
+#define SERVICE_UNNAMED (-1)
+
+/* service_nt_main_fn needs to append the StartService() args 
+ * outside of our call stack and thread as the service starts...
+ */
+apr_array_header_t *mpm_new_argv;
+
+/* Remember service_to_start failures to log and fail in pre_config.
+ * Remember inst_argc and inst_argv for installing or starting the
+ * service after we preflight the config.
  */
-static void winnt_pre_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp) 
+
+static apr_status_t service_to_start_success;
+static int inst_argc;
+static const char * const *inst_argv;
+    
+void winnt_rewrite_args(process_rec *process) 
 {
+    /* Handle the following SCM aspects in this phase:
+     *
+     *   -k runservice [transition for WinNT, nothing for Win9x]
+     *   -k (!)install [error out if name is not installed]
+     *
+     * We can't leave this phase until we know our identity
+     * and modify the command arguments appropriately.
+     */
+    apr_status_t service_named = SERVICE_UNNAMED;
+    apr_status_t rv;
+    char *def_server_root;
+    char fnbuf[MAX_PATH];
+    char optbuf[3];
+    const char *optarg;
+    int fixed_args;
     char *pid;
-
-    one_process = !!getenv("ONE_PROCESS");
+    apr_getopt_t *opt;
+    int running_as_service = 1;
 
     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
     GetVersionEx(&osver);
 
     /* AP_PARENT_PID is only valid in the child */
     pid = getenv("AP_PARENT_PID");
-    if (pid) {
+    if (pid) 
+    {
         /* This is the child */
-        parent_pid = atoi(pid);
-        my_pid = getpid();
+        my_pid = GetCurrentProcessId();
+        parent_pid = (DWORD) atol(pid);
+
+        /* The parent is responsible for providing the
+         * COMPLETE ARGUMENTS REQUIRED to the child.
+         *
+         * No further argument parsing is needed, but
+         * for good measure we will provide a simple
+         * signal string for later testing.
+         */
+        signal_arg = "runchild";
+        return;
     }
-    else {
-        /* This is the parent */
-        parent_pid = my_pid = getpid();
+    
+    /* This is the parent, we have a long way to go :-) */
+    parent_pid = my_pid = GetCurrentProcessId();
+    
+    /* Rewrite process->argv[]; 
+     *
+     * strip out -k signal into signal_arg
+     * strip out -n servicename into service_name & display_name
+     * add default -d serverroot from the path of this executable
+     * 
+     * The end result will look like:
+     *
+     * The invocation command (%0)
+     *     The -d serverroot default from the running executable
+     *         The requested service's (-n) registry ConfigArgs
+     *             The WinNT SCM's StartService() args
+     */
+    if (!GetModuleFileName(NULL, fnbuf, sizeof(fnbuf))) {
+        rv = apr_get_os_error();
+        ap_log_error(APLOG_MARK,APLOG_ERR, rv, NULL, 
+                     "Failed to get the path of Apache.exe");
+        exit(1);
+    }
+    /* WARNING: There is an implict assumption here that the
+     * executable resides in ServerRoot or ServerRoot\bin
+     */
+    def_server_root = (char *) apr_filename_of_pathname(fnbuf);
+    if (def_server_root > fnbuf) {
+        *(def_server_root - 1) = '\0';
+        def_server_root = (char *) apr_filename_of_pathname(fnbuf);
+        if (!strcasecmp(def_server_root, "bin"))
+            *(def_server_root - 1) = '\0';
+    }
+    def_server_root = ap_os_canonical_filename(process->pool, fnbuf);
+
+    /* Use process->pool so that the rewritten argv
+     * lasts for the lifetime of the server process,
+     * because pconf will be destroyed after the 
+     * initial pre-flight of the config parser.
+     */
+    mpm_new_argv = apr_make_array(process->pool, process->argc + 2,
+                                  sizeof(const char *));
+    *(const char **)apr_push_array(mpm_new_argv) = process->argv[0];
+    *(const char **)apr_push_array(mpm_new_argv) = "-d";
+    *(const char **)apr_push_array(mpm_new_argv) = def_server_root;
+
+    fixed_args = mpm_new_argv->nelts;
+
+    optbuf[0] = '-';
+    optbuf[2] = '\0';
+    apr_initopt(&opt, process->pool, process->argc, (char**) process->argv);
+    while (apr_getopt(opt, "n:k:iu" AP_SERVER_BASEARGS, 
+                      optbuf + 1, &optarg) == APR_SUCCESS) {
+        switch (optbuf[1]) {
+        case 'n':
+            service_named = mpm_service_set_name(process->pool, optarg);
+            break;
+        case 'k':
+            signal_arg = optarg;
+            break;
+        case 'i':
+            ap_log_error(APLOG_MARK,APLOG_WARNING, 0, NULL,
+                "-i is deprecated.  Use -k install.");
+            signal_arg = "install";
+            break;
+        case 'u':
+            ap_log_error(APLOG_MARK,APLOG_WARNING, 0, NULL,
+                "-u is deprecated.  Use -k uninstall.");
+            signal_arg = "uninstall";
+            break;
+        default:
+            *(const char **)apr_push_array(mpm_new_argv) =
+                apr_pstrdup(process->pool, optbuf);
+
+            if (optarg) {
+                *(const char **)apr_push_array(mpm_new_argv) = optarg;
+            }
+            break;
+        }
+    }
+    
+    /* Track the number of args actually entered by the user */
+    inst_argc = mpm_new_argv->nelts - fixed_args;
+
+    /* Provide a default 'run' -k arg to simplify signal_arg tests */
+    if (!signal_arg)
+    {
+        signal_arg = "run";
+        running_as_service = 0;
+    }
+
+    if (!strcasecmp(signal_arg, "runservice")) 
+    {
+        /* Start the NT Service _NOW_ because the WinNT SCM is 
+         * expecting us to rapidly assume control of our own 
+         * process, the SCM will tell us our service name, and
+         * may have extra StartService() command arguments to
+         * add for us.
+         *
+         * Any other process has a console, so we don't to begin
+         * a Win9x service until the configuration is parsed and
+         * any command line errors are reported.
+         *
+         * We hold the return value so that we can die in pre_config
+         * after logging begins, and the failure can land in the log.
+         */
+        if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) {
+            service_to_start_success = mpm_service_to_start();
+            if (service_to_start_success == APR_SUCCESS)
+                service_named = APR_SUCCESS;
+        }
+    }
+
+    if (service_named == SERVICE_UNNAMED && running_as_service) {
+        service_named = mpm_service_set_name(process->pool, 
+                                             DEFAULT_SERVICE_NAME);
+    }
+
+    if (!strcasecmp(signal_arg, "install")) /* -k install */
+    {
+        if (service_named == APR_SUCCESS) 
+        {
+            ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
+                 "%s: Service is already installed.", display_name);
+            exit(1);
+        }
+    }
+    else if (running_as_service)
+    {
+        if (service_named == APR_SUCCESS) 
+        {
+            rv = mpm_merge_service_args(process->pool, mpm_new_argv, 
+                                        fixed_args);
+            if (rv == APR_SUCCESS) {
+                ap_log_error(APLOG_MARK,APLOG_NOERRNO|APLOG_INFO, 0, NULL,
+                             "Using ConfigArgs of the installed service "
+                             "\"%s\".", display_name);
+            }
+           else  {
+                ap_log_error(APLOG_MARK,APLOG_INFO, rv, NULL,
+                             "No installed ConfigArgs for the service "
+                             "\"%s\", using Apache defaults.", display_name);
+           }
+        }
+        else
+        {
+            ap_log_error(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO, 0, NULL,
+                 "No installed service named \"%s\".", display_name);
+            exit(1);
+        }
+    }
+    
+    /* Track the args actually entered by the user.
+     * These will be used for the -k install parameters, as well as
+     * for the -k start service override arguments.
+     */
+    inst_argv = (const char * const *)mpm_new_argv->elts
+        + mpm_new_argv->nelts - inst_argc;
+
+    process->argc = mpm_new_argv->nelts; 
+    process->argv = (const char * const *) mpm_new_argv->elts;
+}
+
+
+static void winnt_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp) 
+{
+    /* Handle the following SCM aspects in this phase:
+     *
+     *   -k runservice [WinNT errors logged from rewrite_args]
+     *   -k uninstall
+     *   -k stop
+     *
+     * in these cases we -don't- care if httpd.conf has config errors!
+     */
+    apr_status_t rv;
+
+    if (ap_exists_config_define("ONE_PROCESS"))
+        one_process = -1;
+
+    if (ap_exists_config_define("ONE_PROCESS"))
+        one_process = -1;
+
+    if (!strcasecmp(signal_arg, "runservice")
+            && (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
+            && (service_to_start_success != APR_SUCCESS)) {
+        ap_log_error(APLOG_MARK,APLOG_ERR, service_to_start_success, NULL, 
+                     "%s: Unable to start the service manager.",
+                     display_name);
+        exit(1);
+    }
+
+    if (!strcasecmp(signal_arg, "uninstall")) {
+        rv = mpm_service_uninstall();
+        exit(rv);
+    }
+
+    if (!strcasecmp(signal_arg, "stop")) {
+        mpm_signal_service(ptemp, 0);
+        exit(0);
     }
 
     ap_listen_pre_config();
@@ -1710,22 +2059,54 @@ static void winnt_pre_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp
     ap_pid_fname = DEFAULT_PIDLOG;
     max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
 
-    ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
-
+    apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
 }
 
-static void winnt_post_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp, server_rec* server_conf)
+static void winnt_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec* server)
 {
     static int restart_num = 0;
-    server_conf = server_conf;
+    apr_status_t rv = 0;
+
+    server_conf = server;
+    
+    /* Handle the following SCM aspects in this phase:
+     *
+     *   -k install
+     *   -k start
+     *   -k restart
+     *   -k runservice [Win95, only once - after we parsed the config]
+     *
+     * because all of these signals are useful _only_ if there
+     * is a valid conf\httpd.conf environment to start.
+     *
+     * We reached this phase by avoiding errors that would cause
+     * these options to fail unexpectedly in another process.
+     */
+
+    if (!strcasecmp(signal_arg, "install")) {
+        rv = mpm_service_install(ptemp, inst_argc, inst_argv);
+        exit (rv);
+    }
+
+    if (!strcasecmp(signal_arg, "start")) {
+        rv = mpm_service_start(ptemp, inst_argc, inst_argv);
+        exit (rv);
+    }
+
+    if (!strcasecmp(signal_arg, "restart")) {
+        mpm_signal_service(ptemp, 1);
+        exit (rv);
+    }
 
-    if (parent_pid == my_pid) {
-        if (restart_num++ == 1) {
+    if (parent_pid == my_pid) 
+    {
+        if (restart_num++ == 1) 
+        {
             /* This code should be run once in the parent and not run
-             * accross a restart
+             * across a restart
              */
             PSECURITY_ATTRIBUTES sa = GetNullACL();  /* returns NULL if invalid (Win95?) */
-            setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
+            setup_signal_names(apr_psprintf(pconf,"ap%d", parent_pid));
             if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
                 /* Create the AcceptEx IoCompletionPort once in the parent.
                  * The completion port persists across restarts. 
@@ -1735,23 +2116,20 @@ static void winnt_post_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptem
                                                           0,
                                                           0); /* CONCURRENT ACTIVE THREADS */
                 if (AcceptExCompPort == NULL) {
-                    ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
+                    ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
                                  "Parent: Unable to create the AcceptExCompletionPort -- process will exit");
                     exit(1);
                 }
             }
 
             ap_log_pid(pconf, ap_pid_fname);
-            service_set_status(SERVICE_START_PENDING);
-
-            AMCSocketInitialize();
-        
+            
             /* Create shutdown event, apPID_shutdown, where PID is the parent 
              * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
              */
             shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
             if (!shutdown_event) {
-                ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
+                ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
                              "Parent: Cannot create shutdown event %s", signal_shutdown_name);
                 CleanNullACL((void *)sa);
                 exit(1);
@@ -1763,24 +2141,51 @@ static void winnt_post_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptem
             restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
             if (!restart_event) {
                 CloseHandle(shutdown_event);
-                ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
+                ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
                              "Parent: Cannot create restart event %s", signal_restart_name);
                 CleanNullACL((void *)sa);
                 exit(1);
             }
             CleanNullACL((void *)sa);
-            
+
+            /* Now that we are flying at 15000 feet... 
+             * wipe out the Win95 service console,
+             * signal the SCM the WinNT service started, or
+             * if not a service, setup console handlers instead.
+             */
+            if (!strcasecmp(signal_arg, "runservice"))
+            {
+                if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT) 
+                {
+                    rv = mpm_service_to_start();
+                    if (rv != APR_SUCCESS) {
+                        ap_log_error(APLOG_MARK,APLOG_ERR, rv, server_conf,
+                                     "%s: Unable to start the service manager.",
+                                     display_name);
+                        exit(1);
+                    }            
+                }
+            }
+            else /* ! -k runservice */
+            {
+                mpm_start_console_handler();
+            }
+
             /* Create the start mutex, apPID, where PID is the parent Apache process ID.
              * Ths start mutex is used during a restart to prevent more than one 
              * child process from entering the accept loop at once.
              */
-            ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS, signal_name_prefix,
+            apr_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS, signal_name_prefix,
                                server_conf->process->pool);
         }
     }
+    else /* parent_pid != my_pid */
+    {
+        mpm_start_child_console_handler();
+    }
 }
 
-API_EXPORT(int) ap_mpm_run(ap_pool_t *_pconf, ap_pool_t *plog, server_rec *s )
+AP_DECLARE(int) ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s )
 {
     static int restart = 0;            /* Default is "not a restart" */
 
@@ -1791,9 +2196,7 @@ API_EXPORT(int) ap_mpm_run(ap_pool_t *_pconf, ap_pool_t *plog, server_rec *s )
         /* Running as Child process or in one_process (debug) mode */
         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
                      "Child %d: Child process is running", my_pid);
-        AMCSocketInitialize();
         child_main();
-        AMCSocketCleanup();
         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
                      "Child %d: Child process is exiting", my_pid);        
 
@@ -1807,17 +2210,14 @@ API_EXPORT(int) ap_mpm_run(ap_pool_t *_pconf, ap_pool_t *plog, server_rec *s )
             const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
 
             if (pidfile != NULL && unlink(pidfile) == 0) {
-                ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO,APR_SUCCESS,
+                ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS,
                              server_conf, "removed PID file %s (pid=%ld)",
-                             pidfile, (long)getpid());
+                             pidfile, GetCurrentProcessId());
             }
-            ap_destroy_lock(start_mutex);
+            apr_destroy_lock(start_mutex);
 
             CloseHandle(restart_event);
             CloseHandle(shutdown_event);
-            AMCSocketCleanup();
-
-            service_set_status(SERVICE_STOPPED);
 
             return 1;
         }
@@ -1828,7 +2228,7 @@ API_EXPORT(int) ap_mpm_run(ap_pool_t *_pconf, ap_pool_t *plog, server_rec *s )
 
 static void winnt_hooks(void)
 {
-    one_process = 0;
+    ap_hook_pre_config(winnt_pre_config, NULL, NULL, AP_HOOK_MIDDLE);
     ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
 }
 
@@ -1864,8 +2264,9 @@ static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg
                      HARD_THREAD_LIMIT);
         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
                      " lowering ThreadsPerChild to %d. To increase, please"
-                     " see the  HARD_THREAD_LIMIT define in src/include/httpd.h.", 
-                     HARD_THREAD_LIMIT);
+                     " see the  HARD_THREAD_LIMIT define in %s.", 
+                     HARD_THREAD_LIMIT, AP_MPM_HARD_LIMITS_FILE);
+        ap_threads_per_child = HARD_THREAD_LIMIT;
     }
     else if (ap_threads_per_child < 1) {
        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
@@ -1890,7 +2291,7 @@ static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg)
 
 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg) 
 {
-    struct stat finfo;
+    apr_finfo_t finfo;
     const char *fname;
     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
     if (err != NULL) {
@@ -1898,28 +2299,29 @@ static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg)
     }
 
     fname = ap_server_root_relative(cmd->pool, arg);
-    if ((stat(fname, &finfo) == -1) || !S_ISDIR(finfo.st_mode)) {
-       return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname, 
+    if ((apr_stat(&finfo, fname, cmd->pool) != APR_SUCCESS) || 
+        (finfo.filetype != APR_DIR)) {
+       return apr_pstrcat(cmd->pool, "CoreDumpDirectory ", fname, 
                          " does not exist or is not a directory", NULL);
     }
-    ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
+    apr_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
     return NULL;
 }
 
 /* Stub functions until this MPM supports the connection status API */
 
-API_EXPORT(void) ap_update_connection_status(long conn_id, const char *key, \
+AP_DECLARE(void) ap_update_connection_status(long conn_id, const char *key, \
                                              const char *value)
 {
     /* NOP */
 }
 
-API_EXPORT(void) ap_reset_connection_status(long conn_id)
+AP_DECLARE(void) ap_reset_connection_status(long conn_id)
 {
     /* NOP */
 }
 
-API_EXPORT(ap_array_header_t *) ap_get_status_table(ap_pool_t *p)
+AP_DECLARE(apr_array_header_t *) ap_get_status_table(apr_pool_t *p)
 {
     /* NOP */
     return NULL;
@@ -1938,14 +2340,13 @@ LISTEN_COMMANDS
 { NULL }
 };
 
-module MODULE_VAR_EXPORT mpm_winnt_module = {
+AP_MODULE_DECLARE_DATA module mpm_winnt_module = {
     MPM20_MODULE_STUFF,
-    winnt_pre_config,           /* hook run before configuration is read */
+    winnt_rewrite_args,         /* hook to run before apache parses args */
     NULL,                      /* create per-directory config structure */
     NULL,                      /* merge per-directory config structures */
     NULL,                      /* create per-server config structure */
     NULL,                      /* merge per-server config structures */
-    winnt_cmds,                        /* command ap_table_t */
-    NULL,                      /* handlers */
+    winnt_cmds,                        /* command apr_table_t */
     winnt_hooks                /* register_hooks */
 };