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