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