]> granicus.if.org Git - apache/blob - server/mpm/winnt/mpm_winnt.c
Fix a nit, unreferenced symbol
[apache] / server / mpm / winnt / mpm_winnt.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 #define CORE_PRIVATE 
60 #include "httpd.h" 
61 #include "http_main.h" 
62 #include "http_log.h" 
63 #include "http_config.h"        /* for read_config */ 
64 #include "http_core.h"          /* for get_remote_host */ 
65 #include "http_connection.h"
66 #include "apr_portable.h"
67 #include "apr_getopt.h"
68 #include "apr_strings.h"
69 #include "ap_mpm.h"
70 #include "ap_config.h"
71 #include "ap_listen.h"
72 #include "mpm_default.h"
73 #include "mpm_winnt.h"
74 #include "mpm_common.h"
75
76 typedef HANDLE thread;
77
78 /*
79  * Definitions of WINNT MPM specific config globals
80  */
81 static int workers_may_exit = 0;
82 static int shutdown_in_progress = 0;
83 static unsigned int g_blocked_threads = 0;
84
85 static char *ap_pid_fname = NULL;
86 static int ap_threads_per_child = 0;
87
88 static int max_requests_per_child = 0;
89 static HANDLE shutdown_event;   /* used to signal shutdown to parent */
90 static HANDLE restart_event;    /* used to signal a restart to parent */
91
92 #define MAX_SIGNAL_NAME 30  /* Long enough for apPID_shutdown, where PID is an int */
93 char signal_name_prefix[MAX_SIGNAL_NAME];
94 char signal_restart_name[MAX_SIGNAL_NAME]; 
95 char signal_shutdown_name[MAX_SIGNAL_NAME];
96
97 static struct fd_set listenfds;
98 static int num_listenfds = 0;
99 static SOCKET listenmaxfd = INVALID_SOCKET;
100
101 static apr_pool_t *pconf;               /* Pool for config stuff */
102
103 static char ap_coredump_dir[MAX_STRING_LEN];
104
105 static server_rec *server_conf;
106 static HANDLE AcceptExCompPort = NULL;
107
108 static int one_process = 0;
109 static char const* signal_arg;
110
111 OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
112
113 int ap_max_requests_per_child=0;
114 int ap_daemons_to_start=0;
115
116 static HANDLE exit_event;
117 static HANDLE maintenance_event;
118 apr_lock_t *start_mutex;
119 DWORD my_pid;
120 DWORD parent_pid;
121
122 /* This is the helper code to resolve late bound entry points 
123  * missing from one or more releases of the Win32 API...
124  * but it sure would be nice if we didn't duplicate this code
125  * from the APR ;-)
126  */
127
128 static const char* const lateDllName[DLL_defined] = {
129     "kernel32", "advapi32", "mswsock",  "ws2_32"  };
130 static HMODULE lateDllHandle[DLL_defined] = {
131     NULL,       NULL,       NULL,       NULL      };
132
133 FARPROC ap_load_dll_func(ap_dlltoken_e fnLib, char* fnName, int ordinal)
134 {
135     if (!lateDllHandle[fnLib]) { 
136         lateDllHandle[fnLib] = LoadLibrary(lateDllName[fnLib]);
137         if (!lateDllHandle[fnLib])
138             return NULL;
139     }
140     if (ordinal)
141         return GetProcAddress(lateDllHandle[fnLib], (char *) ordinal);
142     else
143         return GetProcAddress(lateDllHandle[fnLib], fnName);
144 }
145
146 static apr_status_t socket_cleanup(void *sock)
147 {
148     apr_socket_t *thesocket = sock;
149     SOCKET sd;
150     if (apr_get_os_sock(&sd, thesocket) == APR_SUCCESS) {
151         closesocket(sd);
152     }
153     return APR_SUCCESS;
154 }
155
156 /* A bunch or routines from os/win32/multithread.c that need to be merged into APR
157  * or thrown out entirely...
158  */
159
160 static HANDLE create_semaphore(int initial)
161 {
162     return(CreateSemaphore(NULL, initial, 1000000, NULL));
163 }
164
165 static void acquire_semaphore(HANDLE semaphore_id)
166 {
167     int rv;
168     
169     rv = WaitForSingleObject(semaphore_id, INFINITE);
170     
171     return;
172 }
173
174 static int release_semaphore(HANDLE semaphore_id)
175 {
176     return(ReleaseSemaphore(semaphore_id, 1, NULL));
177 }
178
179 static void destroy_semaphore(HANDLE semaphore_id)
180 {
181     CloseHandle(semaphore_id);
182 }
183
184
185 /* To share the semaphores with other processes, we need a NULL ACL
186  * Code from MS KB Q106387
187  */
188 static PSECURITY_ATTRIBUTES GetNullACL()
189 {
190     PSECURITY_DESCRIPTOR pSD;
191     PSECURITY_ATTRIBUTES sa;
192
193     sa  = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES));
194     pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,
195                                             SECURITY_DESCRIPTOR_MIN_LENGTH);
196     if (pSD == NULL || sa == NULL) {
197         return NULL;
198     }
199     apr_set_os_error(0);
200     if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
201         || apr_get_os_error()) {
202         LocalFree( pSD );
203         LocalFree( sa );
204         return NULL;
205     }
206     if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
207         || apr_get_os_error()) {
208         LocalFree( pSD );
209         LocalFree( sa );
210         return NULL;
211     }
212     sa->nLength = sizeof(sa);
213     sa->lpSecurityDescriptor = pSD;
214     sa->bInheritHandle = TRUE;
215     return sa;
216 }
217
218 static void CleanNullACL( void *sa ) {
219     if( sa ) {
220         LocalFree( ((PSECURITY_ATTRIBUTES)sa)->lpSecurityDescriptor);
221         LocalFree( sa );
222     }
223 }
224
225 /*
226  * The Win32 call WaitForMultipleObjects will only allow you to wait for 
227  * a maximum of MAXIMUM_WAIT_OBJECTS (current 64).  Since the threading 
228  * model in the multithreaded version of apache wants to use this call, 
229  * we are restricted to a maximum of 64 threads.  This is a simplistic 
230  * routine that will increase this size.
231  */
232 static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles, 
233                                    DWORD dwSeconds)
234 {
235     time_t tStopTime;
236     DWORD dwRet = WAIT_TIMEOUT;
237     DWORD dwIndex=0;
238     BOOL bFirst = TRUE;
239   
240     tStopTime = time(NULL) + dwSeconds;
241   
242     do {
243         if (!bFirst)
244             Sleep(1000);
245         else
246             bFirst = FALSE;
247           
248         for (dwIndex = 0; dwIndex * MAXIMUM_WAIT_OBJECTS < nCount; dwIndex++) {
249             dwRet = WaitForMultipleObjects( 
250                 min(MAXIMUM_WAIT_OBJECTS, nCount - (dwIndex * MAXIMUM_WAIT_OBJECTS)),
251                 lpHandles + (dwIndex * MAXIMUM_WAIT_OBJECTS), 
252                 0, 0);
253                                            
254             if (dwRet != WAIT_TIMEOUT) {                                          
255               break;
256             }
257         }
258     } while((time(NULL) < tStopTime) && (dwRet == WAIT_TIMEOUT));
259     
260     return dwRet;
261 }
262
263 /*
264  * Signalling Apache on NT.
265  *
266  * Under Unix, Apache can be told to shutdown or restart by sending various
267  * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
268  * we use "events" instead. The parent apache process goes into a loop
269  * where it waits forever for a set of events. Two of those events are
270  * called
271  *
272  *    apPID_shutdown
273  *    apPID_restart
274  *
275  * (where PID is the PID of the apache parent process). When one of these
276  * is signalled, the Apache parent performs the appropriate action. The events
277  * can become signalled through internal Apache methods (e.g. if the child
278  * finds a fatal error and needs to kill its parent), via the service
279  * control manager (the control thread will signal the shutdown event when
280  * requested to stop the Apache service), from the -k Apache command line,
281  * or from any external program which finds the Apache PID from the
282  * httpd.pid file.
283  *
284  * The signal_parent() function, below, is used to signal one of these events.
285  * It can be called by any child or parent process, since it does not
286  * rely on global variables.
287  *
288  * On entry, type gives the event to signal. 0 means shutdown, 1 means 
289  * graceful restart.
290  */
291 void signal_parent(int type)
292 {
293     HANDLE e;
294     char *signal_name;
295     
296     /* after updating the shutdown_pending or restart flags, we need
297      * to wake up the parent process so it can see the changes. The
298      * parent will normally be waiting for either a child process
299      * to die, or for a signal on the "spache-signal" event. So set the
300      * "apache-signal" event here.
301      */
302     if (one_process) {
303         return;
304     }
305
306     switch(type) {
307     case 0: signal_name = signal_shutdown_name; break;
308     case 1: signal_name = signal_restart_name; break;
309     default: return;
310     }
311     e = OpenEvent(EVENT_ALL_ACCESS, FALSE, signal_name);
312     if (!e) {
313         /* Um, problem, can't signal the parent, which means we can't
314          * signal ourselves to die. Ignore for now...
315          */
316         ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
317                      "OpenEvent on %s event", signal_name);
318         return;
319     }
320     if (SetEvent(e) == 0) {
321         /* Same problem as above */
322         ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
323                      "SetEvent on %s event", signal_name);
324         CloseHandle(e);
325         return;
326     }
327     CloseHandle(e);
328 }
329
330 static int volatile is_graceful = 0;
331
332 AP_DECLARE(int) ap_graceful_stop_signalled(void)
333 {
334     return is_graceful;
335 }
336
337 AP_DECLARE(void) ap_start_shutdown(void)
338 {
339     signal_parent(0);
340 }
341
342 AP_DECLARE(void) ap_start_restart(int gracefully)
343 {
344     is_graceful = gracefully;
345     signal_parent(1);
346 }
347
348 /*
349  * Initialise the signal names, in the global variables signal_name_prefix, 
350  * signal_restart_name and signal_shutdown_name.
351  */
352
353 void setup_signal_names(char *prefix)
354 {
355     apr_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);    
356     apr_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name), 
357         "%s_shutdown", signal_name_prefix);    
358     apr_snprintf(signal_restart_name, sizeof(signal_restart_name), 
359         "%s_restart", signal_name_prefix);    
360 }
361
362 /*
363  * Routines that deal with sockets, some are WIN32 specific...
364  */
365
366 static void sock_disable_nagle(int s) 
367 {
368     /* The Nagle algorithm says that we should delay sending partial
369      * packets in hopes of getting more data.  We don't want to do
370      * this; we are not telnet.  There are bad interactions between
371      * persistent connections and Nagle's algorithm that have very severe
372      * performance penalties.  (Failing to disable Nagle is not much of a
373      * problem with simple HTTP.)
374      *
375      * In spite of these problems, failure here is not a shooting offense.
376      */
377     int just_say_no = 1;
378
379     if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
380                    sizeof(int)) < 0) {
381         ap_log_error(APLOG_MARK, APLOG_WARNING, APR_SUCCESS, server_conf,
382                     "setsockopt: (TCP_NODELAY)");
383     }
384 }
385
386 /*
387  * Routines to deal with managing the list of listening sockets.
388  */
389 static ap_listen_rec *head_listener;
390
391 static apr_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
392 {
393     ap_listen_rec *lr;
394     SOCKET nsd;
395
396     for (lr = head_listener; lr ; lr = lr->next) {
397         apr_get_os_sock(&nsd, lr->sd);
398         if (FD_ISSET(nsd, main_fds)) {
399             head_listener = lr->next;
400             if (head_listener == NULL)
401                 head_listener = ap_listeners;
402
403             return (lr);
404         }
405     }
406     return NULL;
407 }
408
409 static int setup_listeners(server_rec *s)
410 {
411     ap_listen_rec *lr;
412     int num_listeners = 0;
413     SOCKET nsd;
414
415     /* Setup the listeners */
416     FD_ZERO(&listenfds);
417
418     if (ap_listen_open(s->process, s->port)) {
419        return 0;
420     }
421     for (lr = ap_listeners; lr; lr = lr->next) {
422         num_listeners++;
423         if (lr->sd != NULL) {
424             apr_get_os_sock(&nsd, lr->sd);
425             FD_SET(nsd, &listenfds);
426             if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
427                 listenmaxfd = nsd;
428             }
429         }
430         lr->count = 0;
431     }
432
433     head_listener = ap_listeners;
434
435     return num_listeners;
436 }
437
438 static int setup_inherited_listeners(server_rec *s)
439 {
440     WSAPROTOCOL_INFO WSAProtocolInfo;
441     HANDLE pipe;
442     ap_listen_rec *lr;
443     DWORD BytesRead;
444     int num_listeners = 0;
445     SOCKET nsd;
446
447     /* Setup the listeners */
448     FD_ZERO(&listenfds);
449
450     /* Set up a default listener if necessary */
451
452     if (ap_listeners == NULL) {
453         ap_listen_rec *lr;
454         lr = apr_palloc(s->process->pool, sizeof(ap_listen_rec));
455         if (!lr)
456             return 0;
457         lr->sd = NULL;
458         lr->next = ap_listeners;
459         ap_listeners = lr;
460     }
461
462     /* Open the pipe to the parent process to receive the inherited socket
463      * data. The sockets have been set to listening in the parent process.
464      */
465     pipe = GetStdHandle(STD_INPUT_HANDLE);
466     for (lr = ap_listeners; lr; lr = lr->next) {
467         if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO), 
468                       &BytesRead, (LPOVERLAPPED) NULL)) {
469             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
470                          "setup_inherited_listeners: Unable to read socket data from parent");
471             signal_parent(0);   /* tell parent to die */
472             exit(1);
473         }
474         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
475                      "Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.", my_pid);
476         nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
477                         &WSAProtocolInfo, 0, 0);
478         if (nsd == INVALID_SOCKET) {
479             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), server_conf,
480                          "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
481             signal_parent(0);   /* tell parent to die */
482             exit(1);
483         }
484         if (nsd >= 0) {
485             FD_SET(nsd, &listenfds);
486             if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
487                 listenmaxfd = nsd;
488             }
489         }
490         apr_put_os_sock(&lr->sd, &nsd, pconf);
491         lr->count = 0;
492     }
493     /* Now, read the AcceptExCompPort from the parent */
494     ReadFile(pipe, &AcceptExCompPort, sizeof(AcceptExCompPort), &BytesRead, (LPOVERLAPPED) NULL);
495     CloseHandle(pipe);
496
497     for (lr = ap_listeners; lr; lr = lr->next) {
498         num_listeners++;
499     }
500
501     head_listener = ap_listeners;
502     return num_listeners;
503 }
504
505 static void bind_listeners_to_completion_port()
506 {
507     /* Associate the open listeners with the completion port.
508      * Bypass the operation for Windows 95/98
509      */
510     ap_listen_rec *lr;
511
512     if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
513         for (lr = ap_listeners; lr; lr = lr->next) {
514             int nsd;
515             apr_get_os_sock(&nsd,lr->sd);
516             CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
517         }
518     }
519 }
520
521 /**********************************************************************
522  * Multithreaded implementation
523  *
524  * This code is fairly specific to Win32.
525  *
526  * The model used to handle requests is a set of threads. One "main"
527  * thread listens for new requests. When something becomes
528  * available, it does a select and places the newly available socket
529  * onto a list of "jobs" (add_job()). Then any one of a fixed number
530  * of "worker" threads takes the top job off the job list with
531  * remove_job() and handles that connection to completion. After
532  * the connection has finished the thread is free to take another
533  * job from the job list.
534  *
535  * In the code, the "main" thread is running within the child_main()
536  * function. The first thing this function does is create the
537  * worker threads, which operate in the child_sub_main() function. The
538  * main thread then goes into a loop within child_main() where they
539  * do a select() on the listening sockets. The select times out once
540  * per second so that the thread can check for an "exit" signal
541  * from the parent process (see below). If this signal is set, the 
542  * thread can exit, but only after it has accepted all incoming
543  * connections already in the listen queue (since Win32 appears
544  * to through away listened but unaccepted connections when a 
545  * process dies).
546  *
547  * Because the main and worker threads exist within a single process
548  * they are vulnerable to crashes or memory leaks (crashes can also
549  * be caused within modules, of course). There also needs to be a 
550  * mechanism to perform restarts and shutdowns. This is done by
551  * creating the main & worker threads within a subprocess. A
552  * main process (the "parent process") creates one (or more) 
553  * processes to do the work, then the parent sits around waiting
554  * for the working process to die, in which case it starts a new
555  * one. The parent process also handles restarts (by creating
556  * a new working process then signalling the previous working process 
557  * exit ) and shutdowns (by signalling the working process to exit).
558  * The parent process operates within the master_main() function. This
559  * process also handles requests from the service manager (NT only).
560  *
561  * Signalling between the parent and working process uses a Win32
562  * event. Each child has a unique name for the event, which is
563  * passed to it with the -Z argument when the child is spawned. The
564  * parent sets (signals) this event to tell the child to die.
565  * At present all children do a graceful die - they finish all
566  * current jobs _and_ empty the listen queue before they exit.
567  * A non-graceful die would need a second event. The -Z argument in
568  * the child is also used to create the shutdown and restart events,
569  * since the prefix (apPID) contains the parent process PID.
570  *
571  * The code below starts with functions at the lowest level -
572  * worker threads, and works up to the top level - the main()
573  * function of the parent process.
574  *
575  * The scoreboard (in process memory) contains details of the worker
576  * threads (within the active working process). There is no shared
577  * "scoreboard" between processes, since only one is ever active
578  * at once (or at most, two, when one has been told to shutdown but
579  * is processes outstanding requests, and a new one has been started).
580  * This is controlled by a "start_mutex" which ensures only one working
581  * process is active at once.
582  **********************************************************************/
583
584
585 /*
586  * Definition of jobs, shared by main and worker threads.
587  */
588
589 typedef struct joblist_s {
590     struct joblist_s *next;
591     int sock;
592 } joblist;
593
594 /*
595  * Globals common to main and worker threads. This structure is not
596  * used by the parent process.
597  */
598
599 typedef struct globals_s {
600     HANDLE jobsemaphore;
601     joblist *jobhead;
602     joblist *jobtail;
603     apr_lock_t *jobmutex;
604     int jobcount;
605
606 } globals;
607
608 globals allowed_globals =
609 {NULL, NULL, NULL, NULL, 0};
610 #define MAX_SELECT_ERRORS 100
611 #define PADDED_ADDR_SIZE sizeof(SOCKADDR_IN)+16
612
613 /* Windows 9x specific code...
614  * Accept processing for on Windows 95/98 uses a producer/consumer queue 
615  * model. A single thread accepts connections and queues the accepted socket 
616  * to the accept queue for consumption by a pool of worker threads.
617  *
618  * win9x_get_connection()
619  *    Calls remove_job() to pull a job from the accept queue. All the worker 
620  *    threads block on remove_job.
621  * accept_and_queue_connections()
622  *    The accept threads runs this function, which accepts connections off 
623  *    the network and calls add_job() to queue jobs to the accept_queue.
624  * add_job()/remove_job()
625  *    Add or remove an accepted socket from the list of sockets 
626  *    connected to clients. allowed_globals.jobmutex protects
627  *    against multiple concurrent access to the linked list of jobs.
628  */
629 static void add_job(int sock)
630 {
631     joblist *new_job;
632
633     new_job = (joblist *) malloc(sizeof(joblist));
634     if (new_job == NULL) {
635         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
636                      "Ouch!  Out of memory in add_job()!");
637         return;
638     }
639     new_job->next = NULL;
640     new_job->sock = sock;
641
642     apr_lock(allowed_globals.jobmutex);
643
644     if (allowed_globals.jobtail != NULL)
645         allowed_globals.jobtail->next = new_job;
646     allowed_globals.jobtail = new_job;
647     if (!allowed_globals.jobhead)
648         allowed_globals.jobhead = new_job;
649     allowed_globals.jobcount++;
650     release_semaphore(allowed_globals.jobsemaphore);
651
652     apr_unlock(allowed_globals.jobmutex);
653 }
654
655 static int remove_job(void)
656 {
657     joblist *job;
658     int sock;
659
660     acquire_semaphore(allowed_globals.jobsemaphore);
661     apr_lock(allowed_globals.jobmutex);
662
663     if (shutdown_in_progress && !allowed_globals.jobhead) {
664         apr_unlock(allowed_globals.jobmutex);
665         return (-1);
666     }
667     job = allowed_globals.jobhead;
668     ap_assert(job);
669     allowed_globals.jobhead = job->next;
670     if (allowed_globals.jobhead == NULL)
671         allowed_globals.jobtail = NULL;
672     apr_unlock(allowed_globals.jobmutex);
673     sock = job->sock;
674     free(job);
675
676     return (sock);
677 }
678
679 static void accept_and_queue_connections(void * dummy)
680 {
681     int requests_this_child = 0;
682     struct timeval tv;
683     fd_set main_fds;
684     int wait_time = 1;
685     int csd;
686     int nsd = INVALID_SOCKET;
687     struct sockaddr_in sa_client;
688     int count_select_errors = 0;
689     int rc;
690     int clen;
691
692     while (!shutdown_in_progress) {
693         if (ap_max_requests_per_child && (requests_this_child > ap_max_requests_per_child)) {
694             break;
695         }
696
697         tv.tv_sec = wait_time;
698         tv.tv_usec = 0;
699         memcpy(&main_fds, &listenfds, sizeof(fd_set));
700
701         rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
702
703         if (rc == 0 || (rc == SOCKET_ERROR && APR_STATUS_IS_EINTR(apr_get_netos_error()))) {
704             count_select_errors = 0;    /* reset count of errors */            
705             continue;
706         }
707         else if (rc == SOCKET_ERROR) {
708             /* A "real" error occurred, log it and increment the count of
709              * select errors. This count is used to ensure we don't go into
710              * a busy loop of continuous errors.
711              */
712             ap_log_error(APLOG_MARK, APLOG_INFO, apr_get_netos_error(), server_conf, 
713                          "select failed with error %d", apr_get_netos_error());
714             count_select_errors++;
715             if (count_select_errors > MAX_SELECT_ERRORS) {
716                 shutdown_in_progress = 1;
717                 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), server_conf,
718                              "Too many errors in select loop. Child process exiting.");
719                 break;
720             }
721         } else {
722             ap_listen_rec *lr;
723
724             lr = find_ready_listener(&main_fds);
725             if (lr != NULL) {
726                 /* fetch the native socket descriptor */
727                 apr_get_os_sock(&nsd, lr->sd);
728             }
729         }
730
731         do {
732             clen = sizeof(sa_client);
733             csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
734             if (csd == INVALID_SOCKET) {
735                 csd = -1;
736             }
737         } while (csd < 0 && APR_STATUS_IS_EINTR(apr_get_netos_error()));
738
739         if (csd < 0) {
740             if (APR_STATUS_IS_ECONNABORTED(apr_get_netos_error())) {
741                 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), server_conf,
742                             "accept: (client socket)");
743             }
744         }
745         else {
746             add_job(csd);
747             requests_this_child++;
748         }
749     }
750     SetEvent(exit_event);
751 }
752 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
753 {
754     int len;
755
756     if (context == NULL) {
757         /* allocate the completion context and the transaction pool */
758         context = apr_pcalloc(pconf, sizeof(COMP_CONTEXT));
759         if (!context) {
760             ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
761                          "win9x_get_connection: apr_pcalloc() failed. Process will exit.");
762             return NULL;
763         }
764         apr_create_pool(&context->ptrans, pconf);
765     }
766     
767
768     while (1) {
769         apr_clear_pool(context->ptrans);        
770         context->accept_socket = remove_job();
771         if (context->accept_socket == -1) {
772             return NULL;
773         }
774         len = sizeof(struct sockaddr);
775         context->sa_server = apr_palloc(context->ptrans, len);
776         if (getsockname(context->accept_socket, 
777                         context->sa_server, &len)== SOCKET_ERROR) {
778             ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), server_conf, 
779                          "getsockname failed");
780             continue;
781         }
782         len = sizeof(struct sockaddr);
783         context->sa_client = apr_palloc(context->ptrans, len);
784         if ((getpeername(context->accept_socket,
785                          context->sa_client, &len)) == SOCKET_ERROR) {
786             ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), server_conf, 
787                          "getpeername failed");
788             memset(&context->sa_client, '\0', sizeof(context->sa_client));
789         }
790
791         /* do we NEED_DUPPED_CSD ?? */
792         
793         return context;
794     }
795 }
796
797 /* 
798  * Windows 2000/NT specific code...
799  * create_acceptex_context()
800  * reset_acceptex_context()
801  * drain_acceptex_complport()
802  * winnt_get_connection()
803  *
804  * TODO: Insert a discussion of 'completion contexts' and what these function do here...
805  */
806 static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp) 
807 {
808     LPOVERLAPPED pol;
809     PCOMP_CONTEXT context;
810     int rc;
811     DWORD BytesRead;
812     DWORD CompKey;
813
814     while (1) {
815         context = NULL;
816         rc = GetQueuedCompletionStatus(hComplPort, &BytesRead, &CompKey,
817                                        &pol, 1000);
818         if (!rc) {
819             rc = apr_get_os_error();
820             if (rc == APR_FROM_OS_ERROR(ERROR_OPERATION_ABORTED)) {
821                 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
822                              "Child %d: - Draining an ABORTED packet off "
823                              "the AcceptEx completion port.", my_pid);
824                 continue;
825             }
826             break;
827         }
828         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
829                      "Child %d: - Draining and discarding an active connection "
830                      "off the AcceptEx completion port.", my_pid);
831         context = (PCOMP_CONTEXT) pol;
832         if (context && bCleanUp) {
833             /* It is only valid to clean-up in the process that initiated the I/O */
834             closesocket(context->accept_socket);
835             CloseHandle(context->Overlapped.hEvent);
836         }
837     }
838 }
839 static int create_acceptex_context(apr_pool_t *_pconf, ap_listen_rec *lr) 
840 {
841     PCOMP_CONTEXT context;
842     DWORD BytesRead;
843     SOCKET nsd;
844     int lasterror;
845
846     /* allocate the completion context */
847     context = apr_pcalloc(_pconf, sizeof(COMP_CONTEXT));
848     if (!context) {
849         ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
850                      "create_acceptex_context: apr_pcalloc() failed. Process will exit.");
851         return -1;
852     }
853
854     /* initialize the completion context */
855     context->lr = lr;
856     context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); 
857     if (context->Overlapped.hEvent == NULL) {
858         ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
859                      "create_acceptex_context: CreateEvent() failed. Process will exit.");
860         return -1;
861     }
862
863     /* create and initialize the accept socket */
864     apr_get_os_sock(&nsd, context->lr->sd);
865     context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
866     if (context->accept_socket == INVALID_SOCKET) {
867         ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_netos_error(), server_conf,
868                      "create_acceptex_context: socket() failed. Process will exit.");
869         return -1;
870     }
871
872     /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
873     if (setsockopt(context->accept_socket, SOL_SOCKET,
874                    SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
875                    sizeof(nsd))) {
876         ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), server_conf,
877                      "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
878         /* Not a failure condition. Keep running. */
879     }
880
881     apr_create_pool(&context->ptrans, _pconf);
882
883     /* recv_buf must be large enough to hold the remote and local
884      * addresses. Note that recv_buf_size is the amount of recv_buf
885      * available for AcceptEx to receive bytes into. Since we 
886      * don't want AcceptEx to do a recv, set the size to 0.
887      */
888     context->recv_buf = apr_pcalloc(_pconf, 2*PADDED_ADDR_SIZE);
889     context->recv_buf_size = 0;
890
891     /* AcceptEx on the completion context. The completion context will be signaled
892      * when a connection is accepted. */
893     if (!AcceptEx(nsd, context->accept_socket,
894                   context->recv_buf, 
895                   context->recv_buf_size,
896                   PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
897                   &BytesRead,
898                   (LPOVERLAPPED) context)) {
899         lasterror = apr_get_netos_error();
900         if (lasterror != APR_FROM_OS_ERROR(ERROR_IO_PENDING)) {
901             ap_log_error(APLOG_MARK,APLOG_ERR, lasterror, server_conf,
902                          "create_acceptex_context: AcceptEx failed. Process will exit.");
903             return -1;
904         }
905
906     }
907     lr->count++;
908
909     return 0;
910 }
911 static apr_inline apr_status_t reset_acceptex_context(PCOMP_CONTEXT context) 
912 {
913     DWORD BytesRead;
914     SOCKET nsd;
915     int rc, i;
916
917     /* reset the buffer pools */
918     apr_clear_pool(context->ptrans);
919     context->sock = NULL;
920
921     /* recreate and initialize the accept socket if it is not being reused */
922     apr_get_os_sock(&nsd, context->lr->sd);
923
924     /* AcceptEx on the completion context. The completion context will be signaled
925      * when a connection is accepted. Hack Alert: TransmitFile, under certain 
926      * circumstances, can 'recycle' accept sockets, saving the overhead of calling 
927      * socket(). Occasionally this fails (usually when the client closes his end 
928      * of the connection early). When this occurs, AcceptEx will fail with 10022, 
929      * Invalid Parameter. When this occurs, just open a fresh accept socket and 
930      * retry the call.
931      */
932     for (i=0; i<2; i++) {
933         if (context->accept_socket == INVALID_SOCKET) {
934             context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
935             if (context->accept_socket == INVALID_SOCKET) {
936                 rc = apr_get_netos_error();
937                 ap_log_error(APLOG_MARK,APLOG_ERR, rc, server_conf,
938                              "reset_acceptex_context: socket() failed. Process will exit.");
939                 return rc;
940             }
941
942             /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
943             if (setsockopt(context->accept_socket, SOL_SOCKET,
944                            SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd, sizeof(nsd))) {
945                 ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(),
946                              server_conf,
947                              "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
948             }
949         }
950
951         if (!AcceptEx(nsd, context->accept_socket, 
952                       context->recv_buf,                   
953                       context->recv_buf_size,
954                       PADDED_ADDR_SIZE, 
955                       PADDED_ADDR_SIZE, 
956                       &BytesRead, 
957                       (LPOVERLAPPED) context)) {
958
959             rc = apr_get_netos_error();
960             if (rc != APR_FROM_OS_ERROR(ERROR_IO_PENDING)) {
961                 ap_log_error(APLOG_MARK, APLOG_INFO, rc, server_conf,
962                              "reset_acceptex_context: AcceptEx failed for "
963                              "listening socket: %d and accept socket: %d", 
964                              nsd, context->accept_socket);
965                 closesocket(context->accept_socket);
966                 context->accept_socket = INVALID_SOCKET;
967                 continue;
968             }
969         }
970         break;
971     }
972
973     context->lr->count++;
974
975     return APR_SUCCESS;
976 }
977 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
978 {
979     int requests_this_child = 0;
980     int rc;
981     LPOVERLAPPED pol;
982     DWORD CompKey;
983     DWORD BytesRead;
984
985
986     if (context != NULL) {
987         if (shutdown_in_progress) {
988             /* Clean-up the AcceptEx completion context */
989             CloseHandle(context->Overlapped.hEvent);
990             if (context->accept_socket != INVALID_SOCKET)
991                 closesocket(context->accept_socket);
992         }
993         else {
994             /* Prepare the completion context for reuse */
995             if ((rc = reset_acceptex_context(context)) != APR_SUCCESS) {
996                 ap_log_error(APLOG_MARK, APLOG_CRIT, rc, server_conf,
997                              "Child %d: winnt_get_connection: reset_acceptex_context failed.",
998                              my_pid); 
999                 if (context->accept_socket != INVALID_SOCKET)
1000                     closesocket(context->accept_socket);
1001                 CloseHandle(context->Overlapped.hEvent);
1002                 /* Probably should just die now... */
1003             }
1004         }
1005     }
1006
1007     /* May need to atomize the workers_may_exit check with the 
1008      * g_blocked_threads++ */
1009     if (workers_may_exit) {
1010         return NULL;
1011     }
1012     g_blocked_threads++;
1013         
1014     while (1) {
1015         rc = GetQueuedCompletionStatus(AcceptExCompPort, &BytesRead, &CompKey,
1016                                        &pol, INFINITE);
1017         if (!rc) {
1018             rc = apr_get_os_error();
1019             if (rc != APR_FROM_OS_ERROR(ERROR_OPERATION_ABORTED)) {
1020                 /* Is this a deadly condition? 
1021                  * We sometimes get ERROR_NETNAME_DELETED when a client
1022                  * disconnects when attempting to reuse sockets. Not sure why 
1023                  * we see this now and not during AcceptEx(). Reset the
1024                  * AcceptEx context and continue...
1025                  */
1026                 ap_log_error(APLOG_MARK,APLOG_INFO, rc, server_conf,
1027                              "Child %d: - GetQueuedCompletionStatus() failed", 
1028                              my_pid);
1029                 /* Reset the completion context */
1030                 if (pol) {
1031                     context = (PCOMP_CONTEXT) pol;
1032                     if (context->accept_socket != INVALID_SOCKET)
1033                         closesocket(context->accept_socket);
1034                     if ((rc = reset_acceptex_context(context)) != APR_SUCCESS) {
1035                         ap_log_error(APLOG_MARK, APLOG_CRIT, rc, server_conf,
1036                                      "Child %d: winnt_get_connection: reset_acceptex_context failed.",
1037                                      my_pid); 
1038                         if (context->accept_socket != INVALID_SOCKET)
1039                             closesocket(context->accept_socket);
1040                         CloseHandle(context->Overlapped.hEvent);
1041                         /* Probably should just die now... */
1042                     }
1043                 }
1044             }
1045             else {
1046                 /* Sometimes we catch ERROR_OPERATION_ABORTED completion packets
1047                  * from the old child process (during a restart). Ignore them.
1048                  */
1049                 ap_log_error(APLOG_MARK,APLOG_INFO, rc, server_conf,
1050                              "Child %d: - Draining ERROR_OPERATION_ABORTED packet off "
1051                              "the completion port.", my_pid);
1052             }
1053             continue;
1054         }
1055
1056         if (CompKey != 0) {
1057             /* CompKey == my_pid means this thread was unblocked by
1058              * the shutdown code (not by io completion).
1059              */
1060             if (CompKey == my_pid) {
1061                 g_blocked_threads--;
1062                 return NULL;
1063             }
1064             /* Sometimes we catch shutdown io completion packets
1065              * posted by the old child process (during a restart). Ignore them.
1066              */
1067             continue;
1068         }
1069
1070         context = (PCOMP_CONTEXT) pol;
1071         break;
1072     }
1073
1074     g_blocked_threads--;
1075
1076     /* Check to see if we need to create more completion contexts,
1077      * but only if we are not in the process of shutting down
1078      */
1079     if (!shutdown_in_progress) {
1080         apr_lock(allowed_globals.jobmutex);
1081         context->lr->count--;
1082         if (context->lr->count < 2) {
1083             SetEvent(maintenance_event);
1084         }
1085         apr_unlock(allowed_globals.jobmutex);
1086     }
1087
1088     /* Received a connection */
1089     GetAcceptExSockaddrs(context->recv_buf, 
1090                          context->recv_buf_size,
1091                          PADDED_ADDR_SIZE,
1092                          PADDED_ADDR_SIZE,
1093                          &context->sa_server,
1094                          &context->sa_server_len,
1095                          &context->sa_client,
1096                          &context->sa_client_len);
1097
1098     return context;
1099
1100 }
1101 /*
1102  * worker_main() - this is the main loop for the worker threads
1103  *
1104  * Windows 95/98
1105  * Each thread runs within this function. They wait within remove_job()
1106  * for a job to become available, then handle all the requests on that
1107  * connection until it is closed, then return to remove_job().
1108  *
1109  * The worker thread will exit when it removes a job which contains
1110  * socket number -1. This provides a graceful thread exit, since
1111  * it will never exit during a connection.
1112  *
1113  * This code in this function is basically equivalent to the child_main()
1114  * from the multi-process (Unix) environment, except that we
1115  *
1116  *  - do not call child_init_modules (child init API phase)
1117  *  - block in remove_job, and when unblocked we have an already
1118  *    accepted socket, instead of blocking on a mutex or select().
1119  */
1120
1121 static void worker_main(int child_num)
1122 {
1123     PCOMP_CONTEXT context = NULL;
1124     apr_os_sock_info_t sockinfo;
1125
1126     while (1) {
1127         conn_rec *c;
1128         apr_int32_t disconnected;
1129
1130         /* Grab a connection off the network */
1131         if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1132             context = win9x_get_connection(context);
1133         }
1134         else {
1135             context = winnt_get_connection(context);
1136         }
1137
1138         if (!context)
1139             break;
1140         sock_disable_nagle(context->accept_socket);
1141
1142         sockinfo.os_sock = &context->accept_socket;
1143         sockinfo.local   = context->sa_server;
1144         sockinfo.remote  = context->sa_client;
1145         sockinfo.family  = APR_INET;
1146         sockinfo.type    = SOCK_STREAM;
1147         apr_make_os_sock(&context->sock, &sockinfo, context->ptrans);
1148
1149         c = ap_new_connection(context->ptrans, server_conf, context->sock,
1150                               (struct sockaddr_in *) context->sa_client,
1151                               (struct sockaddr_in *) context->sa_server,
1152                               child_num);
1153
1154         ap_process_connection(c);
1155
1156
1157         apr_getsocketopt(context->sock, APR_SO_DISCONNECTED, &disconnected);
1158         if (!disconnected) {
1159             context->accept_socket = INVALID_SOCKET;
1160             ap_lingering_close(c);
1161         }
1162     }
1163
1164     ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1165                  "Child %d: Thread exiting.", my_pid);
1166 #if 0
1167
1168     SetEvent(exit_event);
1169 #endif
1170     /* TODO: Add code to clean-up completion contexts here */
1171 }
1172
1173 static void cleanup_thread(thread *handles, int *thread_cnt, int thread_to_clean)
1174 {
1175     int i;
1176
1177     CloseHandle(handles[thread_to_clean]);
1178     for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1179         handles[i] = handles[i + 1];
1180     (*thread_cnt)--;
1181 }
1182
1183 static void create_listeners() 
1184 {
1185 #define NUM_LISTENERS 5
1186     ap_listen_rec *lr;
1187     for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1188         while (lr->count < NUM_LISTENERS) {
1189             if (create_acceptex_context(pconf, lr) == -1) {
1190                 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
1191                              "Unable to create an AcceptEx completion context -- process will exit");
1192                 signal_parent(0);       /* tell parent to die */
1193             }
1194         }
1195     }
1196 }
1197 /*
1198  * child_main() runs the main control thread for the child process. 
1199  *
1200  * The control thread:
1201  * - sets up the worker thread pool
1202  * - starts the accept thread (Win 9x)
1203  * - creates AcceptEx contexts (Win NT)
1204  * - waits for exit_event, maintenance_event or maintenance timeout
1205  *   and does the right thing depending on which event is received.
1206  */
1207 static void child_main()
1208 {
1209     apr_status_t status;
1210     HANDLE child_events[2];
1211     char* exit_event_name;
1212     int nthreads = ap_threads_per_child;
1213     int tid;
1214     thread *child_handles;
1215     int rv;
1216     time_t end_time;
1217     int i;
1218     int cld;
1219     apr_pool_t *pchild;
1220
1221
1222     /* This is the child process or we are running in single process
1223      * mode.
1224      */
1225     exit_event_name = apr_psprintf(pconf, "apC%d", my_pid);
1226     setup_signal_names(apr_psprintf(pconf,"ap%d", parent_pid));
1227
1228     if (one_process) {
1229         /* Single process mode */
1230         apr_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1231         exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1232
1233         setup_listeners(server_conf);
1234         bind_listeners_to_completion_port();
1235     }
1236     else {
1237         /* Child process mode */
1238         apr_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1239         exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1240         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1241                      "Child %d: exit_event_name = %s", my_pid, exit_event_name);
1242
1243         setup_inherited_listeners(server_conf);
1244     }
1245
1246     /* Initialize the child_events */
1247     maintenance_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1248     child_events[0] = exit_event;
1249     child_events[1] = maintenance_event;
1250
1251     ap_assert(start_mutex);
1252     ap_assert(exit_event);
1253     ap_assert(maintenance_event);
1254
1255     apr_create_pool(&pchild, pconf);
1256     allowed_globals.jobsemaphore = create_semaphore(0);
1257     apr_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
1258
1259     /*
1260      * Wait until we have permission to start accepting connections.
1261      * start_mutex is used to ensure that only one child ever
1262      * goes into the listen/accept loop at once.
1263      */
1264     status = apr_lock(start_mutex);
1265     if (status != APR_SUCCESS) {
1266         ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
1267                      "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1268         signal_parent(0);       /* tell parent to die */
1269         exit(0);
1270     }
1271     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1272                  "Child %d: Acquired the start mutex.", my_pid);
1273
1274     /* Create the worker thread pool */
1275     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1276                  "Child %d: Starting %d worker threads.", my_pid, nthreads);
1277     child_handles = (thread) alloca(nthreads * sizeof(int));
1278     for (i = 0; i < nthreads; i++) {
1279         child_handles[i] = (thread) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1280                                                    NULL, 0, &tid);
1281     }
1282
1283     /* Begin accepting connections */
1284     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1285         /* Win95/98: Start the accept thread */
1286         _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) accept_and_queue_connections,
1287                        (void *) i, 0, &tid);
1288     } else {
1289         /* Windows NT/2000: Create AcceptEx completion contexts */
1290         create_listeners();
1291     }
1292
1293     /* Wait for one of three events:
1294      * exit_event: 
1295      *    The exit_event is signaled by the parent process to notify 
1296      *    the child that it is time to exit.
1297      *
1298      * maintenance_event: 
1299      *    This event is signaled by the worker thread pool to direct 
1300      *    this thread to create more completion contexts.
1301      *
1302      * TIMEOUT:
1303      *    To do periodic maintenance on the server (check for thread exits,
1304      *    number of completion contexts, etc.)
1305      */
1306     while (1) {
1307         rv = WaitForMultipleObjects(2, (HANDLE *) child_events, FALSE, INFINITE);
1308         cld = rv - WAIT_OBJECT_0;
1309         if (rv == WAIT_FAILED) {
1310             /* Something serious is wrong */
1311             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1312                          "Child %d: WAIT_FAILED -- shutting down server");
1313             break;
1314         }
1315         else if (rv == WAIT_TIMEOUT) {
1316             /* Hey, this cannot happen */
1317             ap_log_error(APLOG_MARK, APLOG_CRIT, APR_SUCCESS, server_conf,
1318                          "Child %d: WAIT_TIMEOUT -- shutting down server", my_pid);
1319             break;
1320         }
1321         else if (cld == 0) {
1322             /* Exit event was signaled */
1323             ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1324                          "Child %d: Exit event signaled. Child process is ending.", my_pid);
1325             break;
1326         }
1327         else {
1328             /* Child maintenance event signaled */
1329             if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1330                 create_listeners();
1331             }
1332             ResetEvent(maintenance_event);
1333             ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1334                          "Child %d: Child maintenance event signaled.", my_pid);
1335         }
1336     }
1337
1338     /* Setting is_graceful will close keep-alive connections */
1339     is_graceful = 1;
1340
1341     /* Shutdown the worker threads */
1342     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1343         /* workers_may_exit = 1; Not used on Win9x */
1344         shutdown_in_progress = 1;
1345         for (i = 0; i < nthreads; i++) {
1346             add_job(-1);
1347         }
1348     }
1349     else { /* Windows NT/2000 */
1350         SOCKET nsd;
1351         ap_listen_rec *lr;
1352         /*
1353          * Setting shutdown_in_progress prevents new AcceptEx completion 
1354          * contexts from being queued to the port but allows threads to 
1355          * continue consuming from the port. This gives the server a 
1356          * chance to handle any accepted connections.
1357          */
1358         shutdown_in_progress = 1;
1359         Sleep(1000);
1360         
1361         /* Setting workers_may_exit prevents threads from consumimg from the 
1362          * completion port (especially threads that unblock off of keep-alive
1363          * connections later on).
1364          */
1365         workers_may_exit = 1;
1366
1367         /* Unblock threads blocked on the completion port */
1368         apr_lock(allowed_globals.jobmutex);
1369         while (g_blocked_threads > 0) {
1370             ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1371                          "Child %d: %d threads blocked on the completion port", my_pid, g_blocked_threads);
1372             for (i=g_blocked_threads; i > 0; i--) {
1373                 PostQueuedCompletionStatus(AcceptExCompPort, 0, my_pid, NULL);
1374             }
1375             Sleep(1000);
1376         }
1377         apr_unlock(allowed_globals.jobmutex);
1378
1379         /* Cancel any remaining pending AcceptEx completion contexts */
1380         for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1381             apr_get_os_sock(&nsd,lr->sd);
1382             CancelIo((HANDLE) nsd);
1383         }
1384
1385         /* Drain the canceled contexts off the port */
1386         drain_acceptex_complport(AcceptExCompPort, TRUE);
1387     }
1388
1389     /* Release the start_mutex to let the new process (in the restart
1390      * scenario) a chance to begin servicing requests 
1391      */
1392     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1393                  "Child %d: Releasing the start mutex", my_pid);
1394     apr_unlock(start_mutex);
1395
1396     /* Give busy worker threads a chance to service their connections.
1397      * Kill them off if they take too long
1398      */
1399     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1400                  "Child %d: Waiting for %d threads to die.", my_pid, nthreads);
1401     end_time = time(NULL) + 180;
1402     while (nthreads) {
1403         rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1404         if (rv != WAIT_TIMEOUT) {
1405             rv = rv - WAIT_OBJECT_0;
1406             ap_assert((rv >= 0) && (rv < nthreads));
1407             cleanup_thread(child_handles, &nthreads, rv);
1408             continue;
1409         }
1410         break;
1411     }
1412     for (i = 0; i < nthreads; i++) {
1413         TerminateThread(child_handles[i], 1);
1414         CloseHandle(child_handles[i]);
1415     }
1416     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1417                  "Child %d: All worker threads have ended.", my_pid);
1418
1419     CloseHandle(AcceptExCompPort);
1420     destroy_semaphore(allowed_globals.jobsemaphore);
1421     apr_destroy_lock(allowed_globals.jobmutex);
1422
1423     apr_destroy_pool(pchild);
1424     CloseHandle(exit_event);
1425 }
1426
1427 /*
1428  * Spawn a child Apache process. The child process has the command line arguments from
1429  * argc and argv[], plus a -Z argument giving the name of an event. The child should
1430  * open and poll or wait on this event. When it is signalled, the child should die.
1431  * prefix is a prefix string for the event name.
1432  * 
1433  * The child_num argument on entry contains a serial number for this child (used to create
1434  * a unique event name). On exit, this number will have been incremented by one, ready
1435  * for the next call. 
1436  *
1437  * On exit, the value pointed to be *ev will contain the event created
1438  * to signal the new child process.
1439  *
1440  * The return value is the handle to the child process if successful, else -1. If -1 is
1441  * returned the error will already have been logged by ap_log_error().
1442  */
1443
1444 /**********************************************************************
1445  * master_main - this is the parent (main) process. We create a
1446  * child process to do the work, then sit around waiting for either
1447  * the child to exit, or a restart or exit signal. If the child dies,
1448  * we just respawn a new one. If we have a shutdown or graceful restart,
1449  * tell the child to die when it is ready. If it is a non-graceful
1450  * restart, force the child to die immediately.
1451  **********************************************************************/
1452
1453 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1454
1455 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1456 {
1457     int i;
1458     int handle = 0;
1459
1460     CloseHandle(handles[position]);
1461     CloseHandle(events[position]);
1462
1463     handle = (int)handles[position];
1464
1465     for (i = position; i < (*processes)-1; i++) {
1466         handles[i] = handles[i + 1];
1467         events[i] = events[i + 1];
1468     }
1469     (*processes)--;
1470 }
1471
1472 static int create_process(apr_pool_t *p, HANDLE *handles, HANDLE *events, int *processes)
1473 {
1474     int rv;
1475     char buf[1024];
1476     char *pCommand;
1477     char *pEnvVar;
1478     char *pEnvBlock;
1479     int i;
1480     int iEnvBlockLen;
1481     STARTUPINFO si;           /* Filled in prior to call to CreateProcess */
1482     PROCESS_INFORMATION pi;   /* filled in on call to CreateProcess */
1483
1484     ap_listen_rec *lr;
1485     DWORD BytesWritten;
1486     HANDLE hPipeRead = NULL;
1487     HANDLE hPipeWrite = NULL;
1488     SECURITY_ATTRIBUTES sa = {0};  
1489
1490     HANDLE kill_event;
1491     LPWSAPROTOCOL_INFO  lpWSAProtocolInfo;
1492     HANDLE hDupedCompPort;
1493
1494     sa.nLength = sizeof(sa);
1495     sa.bInheritHandle = TRUE;
1496     sa.lpSecurityDescriptor = NULL;
1497
1498     /* Build the command line. Should look something like this:
1499      * C:/apache/bin/apache.exe -f ap_server_confname 
1500      * First, get the path to the executable...
1501      */
1502     rv = GetModuleFileName(NULL, buf, sizeof(buf));
1503     if (rv == sizeof(buf)) {
1504         ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1505                      "Parent: Path to Apache process too long");
1506         return -1;
1507     } else if (rv == 0) {
1508         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1509                      "Parent: GetModuleFileName() returned NULL for current process.");
1510         return -1;
1511     }
1512
1513     /* Build the command line */
1514     pCommand = apr_psprintf(p, "\"%s\"", buf);  
1515     for (i = 1; i < server_conf->process->argc; i++) {
1516         pCommand = apr_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1517     }
1518
1519     /* Build the environment, since Win9x disrespects the active env */
1520     pEnvVar = apr_psprintf(p, "AP_PARENT_PID=%i", parent_pid);
1521     /*
1522      * Win32's CreateProcess call requires that the environment
1523      * be passed in an environment block, a null terminated block of
1524      * null terminated strings.
1525      */  
1526     i = 0;
1527     iEnvBlockLen = 1;
1528     while (_environ[i]) {
1529         iEnvBlockLen += strlen(_environ[i]) + 1;
1530         i++;
1531     }
1532
1533     pEnvBlock = (char *)apr_pcalloc(p, iEnvBlockLen + strlen(pEnvVar) + 1);
1534     strcpy(pEnvBlock, pEnvVar);
1535     pEnvVar = strchr(pEnvBlock, '\0') + 1;
1536
1537     i = 0;
1538     while (_environ[i]) {
1539         strcpy(pEnvVar, _environ[i]);
1540         pEnvVar = strchr(pEnvVar, '\0') + 1;
1541         i++;
1542     }
1543     pEnvVar = '\0';
1544     /* Create a pipe to send socket info to the child */
1545     if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1546         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1547                      "Parent: Unable to create pipe to child process.");
1548         return -1;
1549     }
1550
1551     /* Give the read end of the pipe (hPipeRead) to the child as stdin. The 
1552      * parent will write the socket data to the child on this pipe.
1553      */
1554     memset(&si, 0, sizeof(si));
1555     memset(&pi, 0, sizeof(pi));
1556     si.cb = sizeof(si);
1557     si.dwFlags     = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1558     si.wShowWindow = SW_HIDE;
1559     si.hStdInput   = hPipeRead;
1560
1561     if (!CreateProcess(NULL, pCommand, NULL, NULL, 
1562                        TRUE,               /* Inherit handles */
1563                        CREATE_SUSPENDED,   /* Creation flags */
1564                        pEnvBlock,          /* Environment block */
1565                        NULL,
1566                        &si, &pi)) {
1567         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1568                      "Parent: Not able to create the child process.");
1569         /*
1570          * We must close the handles to the new process and its main thread
1571          * to prevent handle and memory leaks.
1572          */ 
1573         CloseHandle(pi.hProcess);
1574         CloseHandle(pi.hThread);
1575         return -1;
1576     }
1577     
1578     ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1579                  "Parent: Created child process %d", pi.dwProcessId);
1580
1581     SetEnvironmentVariable("AP_PARENT_PID",NULL);
1582
1583     /* Create the exit_event, apCchild_pid */
1584     sa.nLength = sizeof(sa);
1585     sa.bInheritHandle = TRUE;
1586     sa.lpSecurityDescriptor = NULL;        
1587     kill_event = CreateEvent(&sa, TRUE, FALSE, apr_psprintf(pconf,"apC%d", pi.dwProcessId));
1588     if (!kill_event) {
1589         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1590                      "Parent: Could not create exit event for child process");
1591         CloseHandle(pi.hProcess);
1592         CloseHandle(pi.hThread);
1593         return -1;
1594     }
1595     
1596     /* Assume the child process lives. Update the process and event tables */
1597     handles[*processes] = pi.hProcess;
1598     events[*processes] = kill_event;
1599     (*processes)++;
1600
1601     /* We never store the thread's handle, so close it now. */
1602     ResumeThread(pi.hThread);
1603     CloseHandle(pi.hThread);
1604  
1605     /* Run the chain of open sockets. For each socket, duplicate it 
1606      * for the target process then send the WSAPROTOCOL_INFO 
1607      * (returned by dup socket) to the child */
1608     for (lr = ap_listeners; lr; lr = lr->next) {
1609         int nsd;
1610         lpWSAProtocolInfo = apr_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1611         apr_get_os_sock(&nsd,lr->sd);
1612         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1613                      "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1614         if (WSADuplicateSocket(nsd, pi.dwProcessId,
1615                                lpWSAProtocolInfo) == SOCKET_ERROR) {
1616             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), server_conf,
1617                          "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1618             return -1;
1619         }
1620
1621         if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1622                        &BytesWritten,
1623                        (LPOVERLAPPED) NULL)) {
1624             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1625                          "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1626             return -1;
1627         }
1628         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1629                      "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1630     }
1631     if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1632         /* Now, send the AcceptEx completion port to the child */
1633         if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort, 
1634                              pi.hProcess, &hDupedCompPort,  0,
1635                              TRUE, DUPLICATE_SAME_ACCESS)) {
1636             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1637                          "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1638             return -1;
1639         }
1640
1641         WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1642     }
1643     
1644     CloseHandle(hPipeRead);
1645     CloseHandle(hPipeWrite);        
1646
1647     return 0;
1648 }
1649
1650 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1651 {
1652     int remaining_children_to_start = ap_daemons_to_start;
1653     int i;
1654     int rv, cld;
1655     int child_num = 0;
1656     int restart_pending = 0;
1657     int shutdown_pending = 0;
1658     int current_live_processes = 0; /* number of child process we know about */
1659
1660     HANDLE process_handles[MAX_PROCESSES];
1661     HANDLE process_kill_events[MAX_PROCESSES];
1662
1663     setup_listeners(s);
1664     bind_listeners_to_completion_port();
1665
1666     /* Create child process 
1667      * Should only be one in this version of Apache for WIN32 
1668      */
1669     while (remaining_children_to_start--) {
1670         if (create_process(pconf, process_handles, process_kill_events, 
1671                            &current_live_processes) < 0) {
1672             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1673                          "master_main: create child process failed. Exiting.");
1674             shutdown_pending = 1;
1675             goto die_now;
1676         }
1677     }
1678     
1679     restart_pending = shutdown_pending = 0;
1680
1681     if (!strcasecmp(signal_arg, "runservice"))
1682         mpm_service_started();
1683
1684     /* Wait for shutdown or restart events or for child death */
1685     process_handles[current_live_processes] = shutdown_event;
1686     process_handles[current_live_processes+1] = restart_event;
1687
1688     rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles, 
1689                                 FALSE, INFINITE);
1690     cld = rv - WAIT_OBJECT_0;
1691     if (rv == WAIT_FAILED) {
1692         /* Something serious is wrong */
1693         ap_log_error(APLOG_MARK,APLOG_CRIT, apr_get_os_error(), server_conf,
1694                      "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1695         shutdown_pending = 1;
1696     }
1697     else if (rv == WAIT_TIMEOUT) {
1698         /* Hey, this cannot happen */
1699         ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1700                      "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1701         shutdown_pending = 1;
1702     }
1703     else if (cld == current_live_processes) {
1704         /* shutdown_event signalled */
1705         shutdown_pending = 1;
1706         printf("shutdown event signaled\n");
1707         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s, 
1708                      "master_main: Shutdown event signaled -- doing server shutdown.");
1709         if (ResetEvent(shutdown_event) == 0) {
1710             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1711                          "ResetEvent(shutdown_event)");
1712         }
1713
1714     }
1715     else if (cld == current_live_processes+1) {
1716         /* restart_event signalled */
1717         int children_to_kill = current_live_processes;
1718         restart_pending = 1;
1719         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, s, 
1720                      "master_main: Restart event signaled. Doing a graceful restart.");
1721         if (ResetEvent(restart_event) == 0) {
1722             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1723                          "master_main: ResetEvent(restart_event) failed.");
1724         }
1725         /* Signal each child process to die 
1726          * We are making a big assumption here that the child process, once signaled,
1727          * will REALLY go away. Since this is a restart, we do not want to hold the 
1728          * new child process up waiting for the old child to die. Remove the old 
1729          * child out of the process_handles apr_table_t and hope for the best...
1730          */
1731         for (i = 0; i < children_to_kill; i++) {
1732             if (SetEvent(process_kill_events[i]) == 0)
1733                 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1734                              "master_main: SetEvent for child process in slot #%d failed", i);
1735             cleanup_process(process_handles, process_kill_events, i, &current_live_processes);
1736         }
1737     } 
1738     else {
1739         /* A child process must have exited because of a fatal error condition (seg fault, etc.). 
1740          * Remove the dead process 
1741          * from the process_handles and process_kill_events apr_table_t and create a new
1742          * child process.
1743          * TODO: Consider restarting the child immediately without looping through http_main
1744          * and without rereading the configuration. Will need this if we ever support multiple 
1745          * children. One option, create a parent thread which waits on child death and restarts it.
1746          * Consider, however, that if the user makes httpd.conf invalid, we want to die before
1747          * our child tries it... otherwise we have a nasty loop.
1748          */
1749         restart_pending = 1;
1750         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf, 
1751                      "master_main: Child process failed. Restarting the child process.");
1752         ap_assert(cld < current_live_processes);
1753         cleanup_process(process_handles, process_kill_events, cld, &current_live_processes);
1754         /* APD2("main_process: child in slot %d died", rv); */
1755         /* restart_child(process_hancles, process_kill_events, cld, &current_live_processes); */
1756
1757         /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead 
1758          * process. */
1759         drain_acceptex_complport(AcceptExCompPort, FALSE);
1760     }
1761
1762 die_now:
1763     if (shutdown_pending) 
1764     {
1765         int tmstart = time(NULL);
1766         
1767         if (strcasecmp(signal_arg, "runservice")) {
1768             mpm_service_stopping();
1769         }
1770         /* Signal each child processes to die */
1771         for (i = 0; i < current_live_processes; i++) {
1772             printf("SetEvent handle = %d\n", process_kill_events[i]);
1773             if (SetEvent(process_kill_events[i]) == 0)
1774                 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
1775                              "master_main: SetEvent for child process in slot #%d failed", i);
1776         }
1777
1778         while (current_live_processes && ((tmstart+60) > time(NULL))) {
1779             rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1780             if (rv == WAIT_TIMEOUT)
1781                 continue;
1782             ap_assert(rv != WAIT_FAILED);
1783             cld = rv - WAIT_OBJECT_0;
1784             ap_assert(rv < current_live_processes);
1785             cleanup_process(process_handles, process_kill_events, cld, &current_live_processes);
1786         }
1787         for (i = 0; i < current_live_processes; i++) {
1788             ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1789                          "forcing termination of child #%d (handle %d)", i, process_handles[i]);
1790             TerminateProcess((HANDLE) process_handles[i], 1);
1791         }
1792         return 0;  /* Tell the caller we do not want to restart */
1793     }
1794
1795     return 1;      /* Tell the caller we want a restart */
1796 }
1797
1798
1799 #define SERVICE_UNNAMED (-1)
1800
1801 /* service_nt_main_fn needs to append the StartService() args 
1802  * outside of our call stack and thread as the service starts...
1803  */
1804 apr_array_header_t *mpm_new_argv;
1805
1806 /* Remember service_to_start failures to log and fail in pre_config.
1807  * Remember inst_argc and inst_argv for installing or starting the
1808  * service after we preflight the config.
1809  */
1810
1811 static apr_status_t service_to_start_success;
1812 static int inst_argc;
1813 static const char * const *inst_argv;
1814     
1815 void winnt_rewrite_args(process_rec *process) 
1816 {
1817     /* Handle the following SCM aspects in this phase:
1818      *
1819      *   -k runservice [transition for WinNT, nothing for Win9x]
1820      *   -k (!)install [error out if name is not installed]
1821      *
1822      * We can't leave this phase until we know our identity
1823      * and modify the command arguments appropriately.
1824      */
1825     apr_status_t service_named = SERVICE_UNNAMED;
1826     apr_status_t rv;
1827     char *def_server_root;
1828     char fnbuf[MAX_PATH];
1829     char optbuf[3];
1830     const char *optarg;
1831     int fixed_args;
1832     char *pid;
1833     apr_getopt_t *opt;
1834     int running_as_service = 1;
1835
1836     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1837     GetVersionEx(&osver);
1838
1839     /* AP_PARENT_PID is only valid in the child */
1840     pid = getenv("AP_PARENT_PID");
1841     if (pid) 
1842     {
1843         /* This is the child */
1844         parent_pid = (DWORD) atol(pid);
1845         my_pid = GetCurrentProcessId();
1846
1847         /* The parent is responsible for providing the
1848          * COMPLETE ARGUMENTS REQUIRED to the child.
1849          *
1850          * No further argument parsing is needed, but
1851          * for good measure we will provide a simple
1852          * signal string for later testing.
1853          */
1854         signal_arg = "runchild";
1855         return;
1856     }
1857     
1858     /* This is the parent, we have a long way to go :-) */
1859     parent_pid = my_pid = GetCurrentProcessId();
1860     
1861     /* Rewrite process->argv[]; 
1862      *
1863      * strip out -k signal into signal_arg
1864      * strip out -n servicename into service_name & display_name
1865      * add default -d serverroot from the path of this executable
1866      * 
1867      * The end result will look like:
1868      *
1869      * The invocation command (%0)
1870      *     The -d serverroot default from the running executable
1871      *         The requested service's (-n) registry ConfigArgs
1872      *             The WinNT SCM's StartService() args
1873      */
1874
1875     if (!GetModuleFileName(NULL, fnbuf, sizeof(fnbuf))) {
1876         /* WARNING: There is an implict assumption here that the
1877          * executable resides in the ServerRoot!
1878          */
1879         rv = apr_get_os_error();
1880         ap_log_error(APLOG_MARK,APLOG_ERR, rv, NULL, 
1881                      "Failed to get the running module's file name");
1882         exit(1);
1883     }
1884     def_server_root = (char *) apr_filename_of_pathname(fnbuf);
1885     if (def_server_root > fnbuf) {
1886         *(def_server_root - 1) = '\0';
1887         def_server_root = ap_os_canonical_filename(process->pool, fnbuf);
1888     }
1889
1890     /* Use process->pool so that the rewritten argv
1891      * lasts for the lifetime of the server process,
1892      * because pconf will be destroyed after the 
1893      * initial pre-flight of the config parser.
1894      */
1895
1896     mpm_new_argv = apr_make_array(process->pool, process->argc + 2,
1897                                   sizeof(const char *));
1898     *(const char **)apr_push_array(mpm_new_argv) = process->argv[0];
1899     *(const char **)apr_push_array(mpm_new_argv) = "-d";
1900     *(const char **)apr_push_array(mpm_new_argv) = def_server_root;
1901
1902     fixed_args = mpm_new_argv->nelts;
1903
1904     optbuf[0] = '-';
1905     optbuf[2] = '\0';
1906     apr_initopt(&opt, process->pool, process->argc, (char**) process->argv);
1907     while (apr_getopt(opt, "n:k:iu" AP_SERVER_BASEARGS, 
1908                       optbuf + 1, &optarg) == APR_SUCCESS) {
1909         switch (optbuf[1]) {
1910         case 'n':
1911             service_named = mpm_service_set_name(process->pool, optarg);
1912             break;
1913         case 'k':
1914             signal_arg = optarg;
1915             break;
1916         case 'i':
1917             ap_log_error(APLOG_MARK,APLOG_WARNING, 0, NULL,
1918                 "-i is deprecated.  Use -k install.");
1919             signal_arg = "install";
1920             break;
1921         case 'u':
1922             ap_log_error(APLOG_MARK,APLOG_WARNING, 0, NULL,
1923                 "-u is deprecated.  Use -k uninstall.");
1924             signal_arg = "uninstall";
1925             break;
1926         default:
1927             *(const char **)apr_push_array(mpm_new_argv) =
1928                 apr_pstrdup(process->pool, optbuf);
1929
1930             if (optarg) {
1931                 *(const char **)apr_push_array(mpm_new_argv) = optarg;
1932             }
1933             break;
1934         }
1935     }
1936     
1937     /* Track the number of args actually entered by the user */
1938     inst_argc = mpm_new_argv->nelts - fixed_args;
1939
1940     /* Provide a default 'run' -k arg to simplify signal_arg tests */
1941     if (!signal_arg)
1942     {
1943         signal_arg = "run";
1944         running_as_service = 0;
1945     }
1946
1947     if (!strcasecmp(signal_arg, "runservice")) 
1948     {
1949         /* Start the NT Service _NOW_ because the WinNT SCM is 
1950          * expecting us to rapidly assume control of our own 
1951          * process, the SCM will tell us our service name, and
1952          * may have extra StartService() command arguments to
1953          * add for us.
1954          *
1955          * Any other process has a console, so we don't to begin
1956          * a Win9x service until the configuration is parsed and
1957          * any command line errors are reported.
1958          *
1959          * We hold the return value so that we can die in pre_config
1960          * after logging begins, and the failure can land in the log.
1961          */
1962         if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) {
1963             service_to_start_success = mpm_service_to_start();
1964             if (service_to_start_success == APR_SUCCESS)
1965                 service_named = APR_SUCCESS;
1966         }
1967     }
1968
1969     if (service_named == SERVICE_UNNAMED && running_as_service) {
1970         service_named = mpm_service_set_name(process->pool, 
1971                                              DEFAULT_SERVICE_NAME);
1972     }
1973
1974     if (!strcasecmp(signal_arg, "install")) /* -k install */
1975     {
1976         if (service_named == APR_SUCCESS) 
1977         {
1978             ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
1979                  "%s: Service is already installed.", display_name);
1980             exit(1);
1981         }
1982     }
1983     else if (running_as_service)
1984     {
1985         if (service_named == APR_SUCCESS) 
1986         {
1987             rv = mpm_merge_service_args(process->pool, mpm_new_argv, 
1988                                         fixed_args);
1989             if (rv == APR_SUCCESS) {
1990                 ap_log_error(APLOG_MARK,APLOG_NOERRNO|APLOG_INFO, 0, NULL,
1991                              "Using ConfigArgs of the installed service "
1992                              "\"%s\".", display_name);
1993             }
1994                         else  {
1995                 ap_log_error(APLOG_MARK,APLOG_INFO, rv, NULL,
1996                              "No installed ConfigArgs for the service "
1997                              "\"%s\", using Apache defaults.", display_name);
1998                         }
1999         }
2000         else
2001         {
2002             ap_log_error(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO, 0, NULL,
2003                  "No installed service named \"%s\".", display_name);
2004             exit(1);
2005         }
2006     }
2007     
2008     /* Track the args actually entered by the user.
2009      * These will be used for the -k install parameters, as well as
2010      * for the -k start service override arguments.
2011      */
2012     inst_argv = (const char * const *)mpm_new_argv->elts
2013         + mpm_new_argv->nelts - inst_argc;
2014
2015     process->argc = mpm_new_argv->nelts; 
2016     process->argv = (const char * const *) mpm_new_argv->elts;
2017 }
2018
2019
2020 static void winnt_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp) 
2021 {
2022     /* Handle the following SCM aspects in this phase:
2023      *
2024      *   -k runservice [WinNT errors logged from rewrite_args]
2025      *   -k uninstall
2026      *   -k stop
2027      *
2028      * in these cases we -don't- care if httpd.conf has config errors!
2029      */
2030     apr_status_t rv;
2031
2032     if (getenv("ONE_PROCESS"))
2033         one_process = -1;
2034
2035     if (ap_exists_config_define("ONE_PROCESS"))
2036         one_process = -1;
2037
2038     if (!strcasecmp(signal_arg, "runservice")
2039             && (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
2040             && (service_to_start_success != APR_SUCCESS)) {
2041         ap_log_error(APLOG_MARK,APLOG_ERR, service_to_start_success, NULL, 
2042                      "%s: Unable to start the service manager.",
2043                      display_name);
2044         exit(1);
2045     }
2046
2047     if (!strcasecmp(signal_arg, "uninstall")) {
2048         rv = mpm_service_uninstall();
2049         exit(rv);
2050     }
2051
2052     if (!strcasecmp(signal_arg, "stop")) {
2053         mpm_signal_service(ptemp, 0);
2054         exit(0);
2055     }
2056
2057     ap_listen_pre_config();
2058     ap_daemons_to_start = DEFAULT_NUM_DAEMON;
2059     ap_threads_per_child = DEFAULT_START_THREAD;
2060     ap_pid_fname = DEFAULT_PIDLOG;
2061     max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
2062
2063     apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
2064 }
2065
2066 static void winnt_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec* server)
2067 {
2068     static int restart_num = 0;
2069     apr_status_t rv = 0;
2070
2071     server_conf = server;
2072     
2073     /* Handle the following SCM aspects in this phase:
2074      *
2075      *   -k install
2076      *   -k start
2077      *   -k restart
2078      *   -k runservice [Win95, only once - after we parsed the config]
2079      *
2080      * because all of these signals are useful _only_ if there
2081      * is a valid conf\httpd.conf environment to start.
2082      *
2083      * We reached this phase by avoiding errors that would cause
2084      * these options to fail unexpectedly in another process.
2085      */
2086
2087     if (!strcasecmp(signal_arg, "install")) {
2088         rv = mpm_service_install(ptemp, inst_argc, inst_argv);
2089         exit (rv);
2090     }
2091
2092     if (!strcasecmp(signal_arg, "start")) {
2093         rv = mpm_service_start(ptemp, inst_argc, inst_argv);
2094         exit (rv);
2095     }
2096
2097     if (!strcasecmp(signal_arg, "restart")) {
2098         mpm_signal_service(ptemp, 1);
2099         exit (rv);
2100     }
2101
2102     if (parent_pid == my_pid) 
2103     {
2104         if (restart_num++ == 1) 
2105         {
2106             /* This code should be run once in the parent and not run
2107              * across a restart
2108              */
2109             PSECURITY_ATTRIBUTES sa = GetNullACL();  /* returns NULL if invalid (Win95?) */
2110             setup_signal_names(apr_psprintf(pconf,"ap%d", parent_pid));
2111             if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
2112                 /* Create the AcceptEx IoCompletionPort once in the parent.
2113                  * The completion port persists across restarts. 
2114                  */
2115                 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
2116                                                           NULL,
2117                                                           0,
2118                                                           0); /* CONCURRENT ACTIVE THREADS */
2119                 if (AcceptExCompPort == NULL) {
2120                     ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
2121                                  "Parent: Unable to create the AcceptExCompletionPort -- process will exit");
2122                     exit(1);
2123                 }
2124             }
2125
2126             ap_log_pid(pconf, ap_pid_fname);
2127             
2128             /* Create shutdown event, apPID_shutdown, where PID is the parent 
2129              * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
2130              */
2131             shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
2132             if (!shutdown_event) {
2133                 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
2134                              "Parent: Cannot create shutdown event %s", signal_shutdown_name);
2135                 CleanNullACL((void *)sa);
2136                 exit(1);
2137             }
2138
2139             /* Create restart event, apPID_restart, where PID is the parent 
2140              * Apache process ID. Restart is signaled by 'apache -k restart'.
2141              */
2142             restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
2143             if (!restart_event) {
2144                 CloseHandle(shutdown_event);
2145                 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
2146                              "Parent: Cannot create restart event %s", signal_restart_name);
2147                 CleanNullACL((void *)sa);
2148                 exit(1);
2149             }
2150             CleanNullACL((void *)sa);
2151
2152             /* Now that we are flying at 15000 feet... 
2153              * wipe out the Win95 service console,
2154              * signal the SCM the WinNT service started, or
2155              * if not a service, setup console handlers instead.
2156              */
2157             if (!strcasecmp(signal_arg, "runservice"))
2158             {
2159                 if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT) 
2160                 {
2161                     rv = mpm_service_to_start();
2162                     if (rv != APR_SUCCESS) {
2163                         ap_log_error(APLOG_MARK,APLOG_ERR, rv, server_conf,
2164                                      "%s: Unable to start the service manager.",
2165                                      display_name);
2166                         exit(1);
2167                     }            
2168                 }
2169             }
2170             else /* ! -k runservice */
2171             {
2172                 mpm_start_console_handler();
2173             }
2174
2175             /* Create the start mutex, apPID, where PID is the parent Apache process ID.
2176              * Ths start mutex is used during a restart to prevent more than one 
2177              * child process from entering the accept loop at once.
2178              */
2179             apr_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS, signal_name_prefix,
2180                                server_conf->process->pool);
2181         }
2182     }
2183     else /* parent_pid != my_pid */
2184     {
2185         mpm_start_child_console_handler();
2186     }
2187 }
2188
2189 AP_DECLARE(int) ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s )
2190 {
2191     static int restart = 0;            /* Default is "not a restart" */
2192
2193     pconf = _pconf;
2194     server_conf = s;
2195
2196     if ((parent_pid != my_pid) || one_process) {
2197         /* Running as Child process or in one_process (debug) mode */
2198         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
2199                      "Child %d: Child process is running", my_pid);
2200         child_main();
2201         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
2202                      "Child %d: Child process is exiting", my_pid);        
2203
2204         return 1;
2205     }  /* Child or single process */
2206     else { /* Parent process */
2207         restart = master_main(server_conf, shutdown_event, restart_event);
2208
2209         if (!restart) {
2210             /* Shutting down. Clean up... */
2211             const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
2212
2213             if (pidfile != NULL && unlink(pidfile) == 0) {
2214                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS,
2215                              server_conf, "removed PID file %s (pid=%ld)",
2216                              pidfile, GetCurrentProcessId());
2217             }
2218             apr_destroy_lock(start_mutex);
2219
2220             CloseHandle(restart_event);
2221             CloseHandle(shutdown_event);
2222
2223             return 1;
2224         }
2225     }  /* Parent process */
2226
2227     return 0; /* Restart */
2228 }
2229
2230 static void winnt_hooks(void)
2231 {
2232     ap_hook_pre_config(winnt_pre_config, NULL, NULL, AP_HOOK_MIDDLE);
2233     ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
2234 }
2235
2236 /* 
2237  * Command processors 
2238  */
2239 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg) 
2240 {
2241     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2242     if (err != NULL) {
2243         return err;
2244     }
2245
2246     if (cmd->server->is_virtual) {
2247         return "PidFile directive not allowed in <VirtualHost>";
2248     }
2249     ap_pid_fname = arg;
2250     return NULL;
2251 }
2252
2253 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg) 
2254 {
2255     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2256     if (err != NULL) {
2257         return err;
2258     }
2259
2260     ap_threads_per_child = atoi(arg);
2261     if (ap_threads_per_child > HARD_THREAD_LIMIT) {
2262         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
2263                      "WARNING: ThreadsPerChild of %d exceeds compile time"
2264                      " limit of %d threads,", ap_threads_per_child, 
2265                      HARD_THREAD_LIMIT);
2266         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2267                      " lowering ThreadsPerChild to %d. To increase, please"
2268                      " see the  HARD_THREAD_LIMIT define in %s.", 
2269                      HARD_THREAD_LIMIT, AP_MPM_HARD_LIMITS_FILE);
2270         ap_threads_per_child = HARD_THREAD_LIMIT;
2271     }
2272     else if (ap_threads_per_child < 1) {
2273         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
2274                      "WARNING: Require ThreadsPerChild > 0, setting to 1");
2275         ap_threads_per_child = 1;
2276     }
2277     return NULL;
2278 }
2279
2280
2281 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg) 
2282 {
2283     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2284     if (err != NULL) {
2285         return err;
2286     }
2287
2288     max_requests_per_child = atoi(arg);
2289
2290     return NULL;
2291 }
2292
2293 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg) 
2294 {
2295     apr_finfo_t finfo;
2296     const char *fname;
2297     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2298     if (err != NULL) {
2299         return err;
2300     }
2301
2302     fname = ap_server_root_relative(cmd->pool, arg);
2303     if ((apr_stat(&finfo, fname, cmd->pool) != APR_SUCCESS) || 
2304         (finfo.filetype != APR_DIR)) {
2305         return apr_pstrcat(cmd->pool, "CoreDumpDirectory ", fname, 
2306                           " does not exist or is not a directory", NULL);
2307     }
2308     apr_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
2309     return NULL;
2310 }
2311
2312 /* Stub functions until this MPM supports the connection status API */
2313
2314 AP_DECLARE(void) ap_update_connection_status(long conn_id, const char *key, \
2315                                              const char *value)
2316 {
2317     /* NOP */
2318 }
2319
2320 AP_DECLARE(void) ap_reset_connection_status(long conn_id)
2321 {
2322     /* NOP */
2323 }
2324
2325 AP_DECLARE(apr_array_header_t *) ap_get_status_table(apr_pool_t *p)
2326 {
2327     /* NOP */
2328     return NULL;
2329 }
2330
2331 static const command_rec winnt_cmds[] = {
2332 LISTEN_COMMANDS
2333 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
2334     "A file for logging the server process ID"},
2335 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
2336   "Number of threads each child creates" },
2337 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
2338   "Maximum number of requests a particular child serves before dying." },
2339 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
2340   "The location of the directory Apache changes to before dumping core" },
2341 { NULL }
2342 };
2343
2344 AP_MODULE_DECLARE_DATA module mpm_winnt_module = {
2345     MPM20_MODULE_STUFF,
2346     winnt_rewrite_args,         /* hook to run before apache parses args */
2347     NULL,                       /* create per-directory config structure */
2348     NULL,                       /* merge per-directory config structures */
2349     NULL,                       /* create per-server config structure */
2350     NULL,                       /* merge per-server config structures */
2351     winnt_cmds,                 /* command apr_table_t */
2352     NULL,                       /* handlers */
2353     winnt_hooks                 /* register_hooks */
2354 };