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