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