]> granicus.if.org Git - apache/blob - server/mpm/winnt/mpm_winnt.c
Get mod_rewrite building and running, and mod_status building for Win NT
[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 "apr_portable.h"
61 #include "httpd.h" 
62 #include "http_main.h" 
63 #include "http_log.h" 
64 #include "http_config.h"        /* for read_config */ 
65 #include "http_core.h"          /* for get_remote_host */ 
66 #include "http_connection.h"
67 #include "ap_mpm.h"
68 #include "ap_config.h"
69 #include "ap_listen.h"
70 #include "mpm_default.h"
71 #include "service.h"
72 #include "iol_socket.h"
73 #include "winnt.h"
74
75
76 /*
77  * Definitions of WINNT MPM specific config globals
78  */
79
80 static char *ap_pid_fname = NULL;
81 static int ap_threads_per_child = 0;
82 static int workers_may_exit = 0;
83 static int max_requests_per_child = 0;
84
85 static struct fd_set listenfds;
86 static int num_listenfds = 0;
87 static SOCKET listenmaxfd = INVALID_SOCKET;
88
89 static ap_context_t *pconf;             /* Pool for config stuff */
90
91 static char ap_coredump_dir[MAX_STRING_LEN];
92
93 static server_rec *server_conf;
94 static HANDLE AcceptExCompPort = NULL;
95
96 static int one_process = 0;
97
98 static OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
99
100 int ap_max_requests_per_child=0;
101 int ap_daemons_to_start=0;
102
103 static event *exit_event;
104 ap_lock_t *start_mutex;
105 int my_pid;
106 int parent_pid;
107
108 static ap_status_t socket_cleanup(void *sock)
109 {
110     ap_socket_t *thesocket = sock;
111     SOCKET sd;
112     if (ap_get_os_sock(&sd, thesocket) == APR_SUCCESS) {
113         closesocket(sd);
114     }
115     return APR_SUCCESS;
116 }
117
118 /* A bunch or routines from os/win32/multithread.c that need to be merged into APR
119  * or thrown out entirely...
120  */
121
122
123 typedef void semaphore;
124 typedef void event;
125
126 static semaphore *
127 create_semaphore(int initial)
128 {
129     return(CreateSemaphore(NULL, initial, 1000000, NULL));
130 }
131
132 static void acquire_semaphore(semaphore *semaphore_id)
133 {
134     int rv;
135     
136     rv = WaitForSingleObject(semaphore_id, INFINITE);
137     
138     return;
139 }
140
141 static int release_semaphore(semaphore *semaphore_id)
142 {
143     return(ReleaseSemaphore(semaphore_id, 1, NULL));
144 }
145
146 static void destroy_semaphore(semaphore *semaphore_id)
147 {
148     CloseHandle(semaphore_id);
149 }
150
151
152 /* To share the semaphores with other processes, we need a NULL ACL
153  * Code from MS KB Q106387
154  */
155 static PSECURITY_ATTRIBUTES GetNullACL()
156 {
157     PSECURITY_DESCRIPTOR pSD;
158     PSECURITY_ATTRIBUTES sa;
159
160     sa  = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES));
161     pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,
162                                             SECURITY_DESCRIPTOR_MIN_LENGTH);
163     if (pSD == NULL || sa == NULL) {
164         return NULL;
165     }
166     if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
167         || GetLastError()) {
168         LocalFree( pSD );
169         LocalFree( sa );
170         return NULL;
171     }
172     if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
173         || GetLastError()) {
174         LocalFree( pSD );
175         LocalFree( sa );
176         return NULL;
177     }
178     sa->nLength = sizeof(sa);
179     sa->lpSecurityDescriptor = pSD;
180     sa->bInheritHandle = TRUE;
181     return sa;
182 }
183
184 static void CleanNullACL( void *sa ) {
185     if( sa ) {
186         LocalFree( ((PSECURITY_ATTRIBUTES)sa)->lpSecurityDescriptor);
187         LocalFree( sa );
188     }
189 }
190
191 /*
192  * The Win32 call WaitForMultipleObjects will only allow you to wait for 
193  * a maximum of MAXIMUM_WAIT_OBJECTS (current 64).  Since the threading 
194  * model in the multithreaded version of apache wants to use this call, 
195  * we are restricted to a maximum of 64 threads.  This is a simplistic 
196  * routine that will increase this size.
197  */
198 static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles, 
199                                    DWORD dwSeconds)
200 {
201     time_t tStopTime;
202     DWORD dwRet = WAIT_TIMEOUT;
203     DWORD dwIndex=0;
204     BOOL bFirst = TRUE;
205   
206     tStopTime = time(NULL) + dwSeconds;
207   
208     do {
209         if (!bFirst)
210             Sleep(1000);
211         else
212             bFirst = FALSE;
213           
214         for (dwIndex = 0; dwIndex * MAXIMUM_WAIT_OBJECTS < nCount; dwIndex++) {
215             dwRet = WaitForMultipleObjects( 
216                 min(MAXIMUM_WAIT_OBJECTS, nCount - (dwIndex * MAXIMUM_WAIT_OBJECTS)),
217                 lpHandles + (dwIndex * MAXIMUM_WAIT_OBJECTS), 
218                 0, 0);
219                                            
220             if (dwRet != WAIT_TIMEOUT) {                                          
221               break;
222             }
223         }
224     } while((time(NULL) < tStopTime) && (dwRet == WAIT_TIMEOUT));
225     
226     return dwRet;
227 }
228
229 /*
230  * Signalling Apache on NT.
231  *
232  * Under Unix, Apache can be told to shutdown or restart by sending various
233  * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
234  * we use "events" instead. The parent apache process goes into a loop
235  * where it waits forever for a set of events. Two of those events are
236  * called
237  *
238  *    apPID_shutdown
239  *    apPID_restart
240  *
241  * (where PID is the PID of the apache parent process). When one of these
242  * is signalled, the Apache parent performs the appropriate action. The events
243  * can become signalled through internal Apache methods (e.g. if the child
244  * finds a fatal error and needs to kill its parent), via the service
245  * control manager (the control thread will signal the shutdown event when
246  * requested to stop the Apache service), from the -k Apache command line,
247  * or from any external program which finds the Apache PID from the
248  * httpd.pid file.
249  *
250  * The signal_parent() function, below, is used to signal one of these events.
251  * It can be called by any child or parent process, since it does not
252  * rely on global variables.
253  *
254  * On entry, type gives the event to signal. 0 means shutdown, 1 means 
255  * graceful restart.
256  */
257 static void signal_parent(int type)
258 {
259     HANDLE e;
260     char *signal_name;
261     extern char signal_shutdown_name[];
262     extern char signal_restart_name[];
263
264     /* after updating the shutdown_pending or restart flags, we need
265      * to wake up the parent process so it can see the changes. The
266      * parent will normally be waiting for either a child process
267      * to die, or for a signal on the "spache-signal" event. So set the
268      * "apache-signal" event here.
269      */
270     if (one_process) {
271         return;
272     }
273
274     switch(type) {
275     case 0: signal_name = signal_shutdown_name; break;
276     case 1: signal_name = signal_restart_name; break;
277     default: return;
278     }
279     e = OpenEvent(EVENT_ALL_ACCESS, FALSE, signal_name);
280     if (!e) {
281         /* Um, problem, can't signal the parent, which means we can't
282          * signal ourselves to die. Ignore for now...
283          */
284         ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
285                      "OpenEvent on %s event", signal_name);
286         return;
287     }
288     if (SetEvent(e) == 0) {
289         /* Same problem as above */
290         ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
291                      "SetEvent on %s event", signal_name);
292         CloseHandle(e);
293         return;
294     }
295     CloseHandle(e);
296 }
297 static int volatile is_graceful = 0;
298 API_EXPORT(int) ap_graceful_stop_signalled(void)
299 {
300     return is_graceful;
301 }
302 void ap_start_shutdown(void)
303 {
304     signal_parent(0);
305 }
306 /*
307  * Initialise the signal names, in the global variables signal_name_prefix, 
308  * signal_restart_name and signal_shutdown_name.
309  */
310
311 #define MAX_SIGNAL_NAME 30  /* Long enough for apPID_shutdown, where PID is an int */
312 char signal_name_prefix[MAX_SIGNAL_NAME];
313 char signal_restart_name[MAX_SIGNAL_NAME]; 
314 char signal_shutdown_name[MAX_SIGNAL_NAME];
315 static void setup_signal_names(char *prefix)
316 {
317     ap_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);    
318     ap_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name), 
319         "%s_shutdown", signal_name_prefix);    
320     ap_snprintf(signal_restart_name, sizeof(signal_restart_name), 
321         "%s_restart", signal_name_prefix);    
322 }
323
324 /*
325  * Routines that deal with sockets, some are WIN32 specific...
326  */
327 static int s_iInitCount = 0;
328 static int AMCSocketInitialize(void)
329 {
330     int iVersionRequested;
331     WSADATA wsaData;
332     int err;
333
334     if (s_iInitCount > 0) {
335         s_iInitCount++;
336         return (0);
337     }
338     else if (s_iInitCount < 0)
339         return (s_iInitCount);
340
341     /* s_iInitCount == 0. Do the initailization */
342     iVersionRequested = MAKEWORD(2, 0);
343     err = WSAStartup((WORD) iVersionRequested, &wsaData);
344     if (err) {
345         s_iInitCount = -1;
346         return (s_iInitCount);
347     }
348     if (LOBYTE(wsaData.wVersion) != 1 ||
349         HIBYTE(wsaData.wVersion) != 1) {
350         s_iInitCount = -2;
351         WSACleanup();
352         return (s_iInitCount);
353     }
354
355     s_iInitCount++;
356     return (s_iInitCount);
357
358 }
359 static void AMCSocketCleanup(void)
360 {
361     if (--s_iInitCount == 0)
362         WSACleanup();
363     return;
364 }
365
366 static void sock_disable_nagle(int s) 
367 {
368     /* The Nagle algorithm says that we should delay sending partial
369      * packets in hopes of getting more data.  We don't want to do
370      * this; we are not telnet.  There are bad interactions between
371      * persistent connections and Nagle's algorithm that have very severe
372      * performance penalties.  (Failing to disable Nagle is not much of a
373      * problem with simple HTTP.)
374      *
375      * In spite of these problems, failure here is not a shooting offense.
376      */
377     int just_say_no = 1;
378
379     if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
380                    sizeof(int)) < 0) {
381         ap_log_error(APLOG_MARK, APLOG_WARNING, APR_SUCCESS, server_conf,
382                     "setsockopt: (TCP_NODELAY)");
383     }
384 }
385
386 /*
387  * Routines to deal with managing the list of listening sockets.
388  */
389 static ap_listen_rec *head_listener;
390 static ap_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
391 {
392     ap_listen_rec *lr;
393     SOCKET nsd;
394
395     for (lr = head_listener; lr ; lr = lr->next) {
396         ap_get_os_sock(&nsd, lr->sd);
397         if (FD_ISSET(nsd, main_fds)) {
398             head_listener = lr->next;
399             if (head_listener == NULL)
400                 head_listener = ap_listeners;
401
402             return (lr);
403         }
404     }
405     return NULL;
406 }
407 static int setup_listeners(server_rec *s)
408 {
409     ap_listen_rec *lr;
410     int num_listeners = 0;
411     SOCKET nsd;
412
413     /* Setup the listeners */
414     FD_ZERO(&listenfds);
415
416     if (ap_listen_open(s->process, s->port)) {
417        return 0;
418     }
419     for (lr = ap_listeners; lr; lr = lr->next) {
420         num_listeners++;
421         if (lr->sd != NULL) {
422             ap_get_os_sock(&nsd, lr->sd);
423             FD_SET(nsd, &listenfds);
424             if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
425                 listenmaxfd = nsd;
426             }
427         }
428         lr->count = 0;
429     }
430
431     head_listener = ap_listeners;
432
433     return num_listeners;
434 }
435
436 static int setup_inherited_listeners(server_rec *s)
437 {
438     WSAPROTOCOL_INFO WSAProtocolInfo;
439     HANDLE pipe;
440     ap_listen_rec *lr;
441     DWORD BytesRead;
442     int num_listeners = 0;
443     SOCKET nsd;
444
445     /* Setup the listeners */
446     FD_ZERO(&listenfds);
447
448     /* Set up a default listener if necessary */
449
450     if (ap_listeners == NULL) {
451         ap_listen_rec *lr;
452         lr = ap_palloc(s->process->pool, sizeof(ap_listen_rec));
453         if (!lr)
454             return 0;
455         lr->sd = NULL;
456         lr->next = ap_listeners;
457         ap_listeners = lr;
458     }
459
460     /* Open the pipe to the parent process to receive the inherited socket
461      * data. The sockets have been set to listening in the parent process.
462      */
463     pipe = GetStdHandle(STD_INPUT_HANDLE);
464     for (lr = ap_listeners; lr; lr = lr->next) {
465         if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO), 
466                       &BytesRead, (LPOVERLAPPED) NULL)) {
467             ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
468                          "setup_inherited_listeners: Unable to read socket data from parent");
469             signal_parent(0);   /* tell parent to die */
470             exit(1);
471         }
472         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
473                      "Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.", my_pid);
474         nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
475                         &WSAProtocolInfo, 0, 0);
476         if (nsd == INVALID_SOCKET) {
477             ap_log_error(APLOG_MARK, APLOG_CRIT, WSAGetLastError(), server_conf,
478                          "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
479             signal_parent(0);   /* tell parent to die */
480             exit(1);
481         }
482         if (nsd >= 0) {
483             FD_SET(nsd, &listenfds);
484             if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
485                 listenmaxfd = nsd;
486             }
487         }
488 //        ap_register_cleanup(p, (void *)lr->sd, socket_cleanup, ap_null_cleanup);
489         ap_put_os_sock(&lr->sd, &nsd, pconf);
490         lr->count = 0;
491     }
492     /* Now, read the AcceptExCompPort from the parent */
493     ReadFile(pipe, &AcceptExCompPort, sizeof(AcceptExCompPort), &BytesRead, (LPOVERLAPPED) NULL);
494     CloseHandle(pipe);
495
496     for (lr = ap_listeners; lr; lr = lr->next) {
497         num_listeners++;
498     }
499
500     head_listener = ap_listeners;
501     return num_listeners;
502 }
503
504
505 /**********************************************************************
506  * Multithreaded implementation
507  *
508  * This code is fairly specific to Win32.
509  *
510  * The model used to handle requests is a set of threads. One "main"
511  * thread listens for new requests. When something becomes
512  * available, it does a select and places the newly available socket
513  * onto a list of "jobs" (add_job()). Then any one of a fixed number
514  * of "worker" threads takes the top job off the job list with
515  * remove_job() and handles that connection to completion. After
516  * the connection has finished the thread is free to take another
517  * job from the job list.
518  *
519  * In the code, the "main" thread is running within the child_main()
520  * function. The first thing this function does is create the
521  * worker threads, which operate in the child_sub_main() function. The
522  * main thread then goes into a loop within child_main() where they
523  * do a select() on the listening sockets. The select times out once
524  * per second so that the thread can check for an "exit" signal
525  * from the parent process (see below). If this signal is set, the 
526  * thread can exit, but only after it has accepted all incoming
527  * connections already in the listen queue (since Win32 appears
528  * to through away listened but unaccepted connections when a 
529  * process dies).
530  *
531  * Because the main and worker threads exist within a single process
532  * they are vulnerable to crashes or memory leaks (crashes can also
533  * be caused within modules, of course). There also needs to be a 
534  * mechanism to perform restarts and shutdowns. This is done by
535  * creating the main & worker threads within a subprocess. A
536  * main process (the "parent process") creates one (or more) 
537  * processes to do the work, then the parent sits around waiting
538  * for the working process to die, in which case it starts a new
539  * one. The parent process also handles restarts (by creating
540  * a new working process then signalling the previous working process 
541  * exit ) and shutdowns (by signalling the working process to exit).
542  * The parent process operates within the master_main() function. This
543  * process also handles requests from the service manager (NT only).
544  *
545  * Signalling between the parent and working process uses a Win32
546  * event. Each child has a unique name for the event, which is
547  * passed to it with the -Z argument when the child is spawned. The
548  * parent sets (signals) this event to tell the child to die.
549  * At present all children do a graceful die - they finish all
550  * current jobs _and_ empty the listen queue before they exit.
551  * A non-graceful die would need a second event. The -Z argument in
552  * the child is also used to create the shutdown and restart events,
553  * since the prefix (apPID) contains the parent process PID.
554  *
555  * The code below starts with functions at the lowest level -
556  * worker threads, and works up to the top level - the main()
557  * function of the parent process.
558  *
559  * The scoreboard (in process memory) contains details of the worker
560  * threads (within the active working process). There is no shared
561  * "scoreboard" between processes, since only one is ever active
562  * at once (or at most, two, when one has been told to shutdown but
563  * is processes outstanding requests, and a new one has been started).
564  * This is controlled by a "start_mutex" which ensures only one working
565  * process is active at once.
566  **********************************************************************/
567
568
569 /*
570  * Definition of jobs, shared by main and worker threads.
571  */
572
573 typedef struct joblist_s {
574     struct joblist_s *next;
575     int sock;
576 } joblist;
577
578 /*
579  * Globals common to main and worker threads. This structure is not
580  * used by the parent process.
581  */
582
583 typedef struct globals_s {
584     semaphore *jobsemaphore;
585     joblist *jobhead;
586     joblist *jobtail;
587     ap_lock_t *jobmutex;
588     int jobcount;
589 } globals;
590
591 globals allowed_globals =
592 {NULL, NULL, NULL, NULL, 0};
593 #define MAX_SELECT_ERRORS 100
594 #define PADDED_ADDR_SIZE sizeof(SOCKADDR_IN)+16
595
596 /* Windows 9x specific code...
597  * Accept processing for on Windows 95/98 uses a producer/consumer queue 
598  * model. A single thread accepts connections and queues the accepted socket 
599  * to the accept queue for consumption by a pool of worker threads.
600  *
601  * win9x_get_connection()
602  *    Calls remove_job() to pull a job from the accept queue. All the worker 
603  *    threads block on remove_job.
604  * accept_and_queue_connections()
605  *    The accept threads runs this function, which accepts connections off 
606  *    the network and calls add_job() to queue jobs to the accept_queue.
607  * add_job()/remove_job()
608  *    Add or remove an accepted socket from the list of sockets 
609  *    connected to clients. allowed_globals.jobmutex protects
610  *    against multiple concurrent access to the linked list of jobs.
611  */
612 static void add_job(int sock)
613 {
614     joblist *new_job;
615
616     new_job = (joblist *) malloc(sizeof(joblist));
617     if (new_job == NULL) {
618         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
619                      "Ouch!  Out of memory in add_job()!");
620         return;
621     }
622     new_job->next = NULL;
623     new_job->sock = sock;
624
625     ap_lock(allowed_globals.jobmutex);
626
627     if (allowed_globals.jobtail != NULL)
628         allowed_globals.jobtail->next = new_job;
629     allowed_globals.jobtail = new_job;
630     if (!allowed_globals.jobhead)
631         allowed_globals.jobhead = new_job;
632     allowed_globals.jobcount++;
633     release_semaphore(allowed_globals.jobsemaphore);
634
635     ap_unlock(allowed_globals.jobmutex);
636 }
637
638 static int remove_job(void)
639 {
640     joblist *job;
641     int sock;
642
643     acquire_semaphore(allowed_globals.jobsemaphore);
644     ap_lock(allowed_globals.jobmutex);
645
646     if (workers_may_exit && !allowed_globals.jobhead) {
647         ap_unlock(allowed_globals.jobmutex);
648         return (-1);
649     }
650     job = allowed_globals.jobhead;
651     ap_assert(job);
652     allowed_globals.jobhead = job->next;
653     if (allowed_globals.jobhead == NULL)
654         allowed_globals.jobtail = NULL;
655     ap_unlock(allowed_globals.jobmutex);
656     sock = job->sock;
657     free(job);
658
659     return (sock);
660 }
661
662 static void accept_and_queue_connections(void * dummy)
663 {
664     int requests_this_child = 0;
665     struct timeval tv;
666     fd_set main_fds;
667     int wait_time = 1;
668     int csd;
669     int nsd = INVALID_SOCKET;
670     struct sockaddr_in sa_client;
671     int count_select_errors = 0;
672     int rc;
673     int clen;
674
675     while (!workers_may_exit) {
676         if (ap_max_requests_per_child && (requests_this_child > ap_max_requests_per_child)) {
677             break;
678         }
679
680         tv.tv_sec = wait_time;
681         tv.tv_usec = 0;
682         memcpy(&main_fds, &listenfds, sizeof(fd_set));
683
684 //      rc = ap_select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
685         rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
686
687         if (rc == 0 || (rc == SOCKET_ERROR && h_errno == WSAEINTR)) {
688             count_select_errors = 0;    /* reset count of errors */            
689             continue;
690         }
691         else if (rc == SOCKET_ERROR) {
692             /* A "real" error occurred, log it and increment the count of
693              * select errors. This count is used to ensure we don't go into
694              * a busy loop of continuous errors.
695              */
696             ap_log_error(APLOG_MARK, APLOG_INFO, h_errno, server_conf, 
697                          "select failed with errno %d", h_errno);
698             count_select_errors++;
699             if (count_select_errors > MAX_SELECT_ERRORS) {
700                 workers_may_exit = 1;
701                 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
702                              "Too many errors in select loop. Child process exiting.");
703                 break;
704             }
705         } else {
706             ap_listen_rec *lr;
707
708             lr = find_ready_listener(&main_fds);
709             if (lr != NULL) {
710                 /* fetch the native socket descriptor */
711                 ap_get_os_sock(&nsd, lr->sd);
712             }
713         }
714
715         do {
716             clen = sizeof(sa_client);
717             csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
718             if (csd == INVALID_SOCKET) {
719                 csd = -1;
720             }
721         } while (csd < 0 && h_errno == WSAEINTR);
722
723         if (csd < 0) {
724             if (h_errno != WSAECONNABORTED) {
725                 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
726                             "accept: (client socket)");
727             }
728         }
729         else {
730             add_job(csd);
731             requests_this_child++;
732         }
733     }
734     SetEvent(exit_event);
735 }
736 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
737 {
738     int len;
739
740     if (context == NULL) {
741         /* allocate the completion context and the transaction pool */
742         context = ap_pcalloc(pconf, sizeof(COMP_CONTEXT));
743         if (!context) {
744             ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
745                          "win9x_get_connection: ap_pcalloc() failed. Process will exit.");
746             return NULL;
747         }
748         ap_create_context(&context->ptrans, pconf);
749     }
750     
751
752     while (1) {
753         ap_clear_pool(context->ptrans);        
754         context->accept_socket = remove_job();
755         if (context->accept_socket == -1) {
756             return NULL;
757         }
758         //ap_note_cleanups_for_socket(ptrans, csd);
759         len = sizeof(struct sockaddr);
760         context->sa_server = ap_palloc(context->ptrans, len);
761         if (getsockname(context->accept_socket, 
762                         context->sa_server, &len)== SOCKET_ERROR) {
763             ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(), server_conf, 
764                          "getsockname failed");
765             continue;
766         }
767         len = sizeof(struct sockaddr);
768         context->sa_client = ap_palloc(context->ptrans, len);
769         if ((getpeername(context->accept_socket,
770                          context->sa_client, &len)) == SOCKET_ERROR) {
771             ap_log_error(APLOG_MARK, APLOG_WARNING, h_errno, server_conf, 
772                          "getpeername failed with error %d\n", WSAGetLastError());
773             memset(&context->sa_client, '\0', sizeof(context->sa_client));
774         }
775
776         context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
777
778         /* do we NEED_DUPPED_CSD ?? */
779         
780         return context;
781     }
782 }
783
784 /* 
785  * Windows 2000/NT specific code...
786  * create_acceptex_context()
787  * reset_acceptex_context()
788  * drain_acceptex_complport()
789  * winnt_get_connection()
790  *
791  * TODO: Insert a discussion of 'completion contexts' and what these function do here...
792  */
793 static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp) 
794 {
795     LPOVERLAPPED pol;
796     PCOMP_CONTEXT context;
797     int rc;
798     DWORD BytesRead;
799     DWORD CompKey;
800     int lastError;
801
802     while (1) {
803         context = NULL;
804         rc = GetQueuedCompletionStatus(hComplPort, &BytesRead, &CompKey,
805                                        &pol, 1000);
806         if (!rc) {
807             lastError = GetLastError();
808             if (lastError == ERROR_OPERATION_ABORTED) {
809                 ap_log_error(APLOG_MARK,APLOG_INFO,lastError, server_conf,
810                              "Child: %d - Draining a packet off the completion port.", my_pid);
811                 continue;
812             }
813             break;
814         }
815         ap_log_error(APLOG_MARK,APLOG_INFO,APR_SUCCESS, server_conf,
816                      "Child: %d - Nuking an active connection. context = %x", my_pid, context);
817         context = (PCOMP_CONTEXT) pol;
818         if (context && bCleanUp) {
819             /* It is only valid to clean-up in the process that initiated the I/O */
820             closesocket(context->accept_socket);
821             CloseHandle(context->Overlapped.hEvent);
822         }
823     }
824 }
825 static int create_acceptex_context(ap_context_t *_pconf, ap_listen_rec *lr) 
826 {
827     PCOMP_CONTEXT context;
828     DWORD BytesRead;
829     SOCKET nsd;
830     int lasterror;
831     
832     /* allocate the completion context */
833     context = ap_pcalloc(_pconf, sizeof(COMP_CONTEXT));
834     if (!context) {
835         ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
836                      "create_acceptex_context: ap_pcalloc() failed. Process will exit.");
837         return -1;
838     }
839
840     /* initialize the completion context */
841     context->lr = lr;
842     context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); 
843     if (context->Overlapped.hEvent == NULL) {
844         ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
845                      "create_acceptex_context: CreateEvent() failed. Process will exit.");
846         return -1;
847     }
848     context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
849     if (context->accept_socket == INVALID_SOCKET) {
850         ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
851                      "create_acceptex_context: socket() failed. Process will exit.");
852         return -1;
853     }
854     ap_create_context(&context->ptrans, _pconf);
855     context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
856     context->recv_buf = context->conn_io->inbase;
857     context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
858     ap_get_os_sock(&nsd, context->lr->sd);
859
860     /* AcceptEx on the completion context. The completion context will be signaled
861      * when a connection is accepted. */
862     if (!AcceptEx(nsd, context->accept_socket,
863                   context->recv_buf, 
864                   0, //context->recv_buf_size,
865                   PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
866                   &BytesRead,
867                   (LPOVERLAPPED) context)) {
868         lasterror = WSAGetLastError();
869         if (lasterror != ERROR_IO_PENDING) {
870             ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
871                          "create_acceptex_context: AcceptEx failed. Process will exit.");
872             return -1;
873         }
874     }
875     lr->count++;
876
877     return 0;
878 }
879 static ap_inline int reset_acceptex_context(PCOMP_CONTEXT context) 
880 {
881     DWORD BytesRead;
882     SOCKET nsd;
883     int lasterror;
884
885     context->lr->count++;
886
887     if (context->accept_socket == -1)
888         context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
889
890     if (context->accept_socket == INVALID_SOCKET) {
891         ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
892                      "reset_acceptex_context: socket() failed. Process will exit.");
893         return -1;
894     }
895
896     ap_clear_pool(context->ptrans);
897     context->sock = NULL;
898     context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
899     context->recv_buf = context->conn_io->inbase;
900     context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
901     ap_get_os_sock(&nsd, context->lr->sd);
902
903     if (!AcceptEx(nsd, context->accept_socket, 
904                   context->recv_buf, 
905                   0, //context->recv_buf_size,
906                   PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
907                   &BytesRead, (LPOVERLAPPED) context)) {
908         lasterror = WSAGetLastError();
909         if (lasterror != ERROR_IO_PENDING) {
910             ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
911                          "reset_acceptex_context: AcceptEx failed. Leaving the process running.");
912             return -1;
913         }
914     }
915
916     return 0;
917 }
918 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
919 {
920     int requests_this_child = 0;
921     int rc;
922     LPOVERLAPPED pol;
923     DWORD CompKey;
924     DWORD BytesRead;
925
926     if (context != NULL) {
927         /* If child shutdown has been signaled, clean-up the completion context */
928         if (workers_may_exit) {
929             CloseHandle(context->Overlapped.hEvent);
930             /* destroy pool */
931         }
932         else {
933             context->accept_socket = -1; /* Don't reuse the accept_socket */
934             if (reset_acceptex_context(context) == -1) {
935                 if (context->accept_socket != -1)
936                     closesocket(context->accept_socket);
937                 CloseHandle(context->Overlapped.hEvent);
938                 return NULL;
939             }
940         }
941     }
942
943     while (1) {
944         rc = GetQueuedCompletionStatus(AcceptExCompPort,
945                                        &BytesRead,
946                                        &CompKey,
947                                        &pol,
948                                        INFINITE);
949         if (!rc) {
950             ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
951                          "Child: %d - GetQueuedCompletionStatus() failed", my_pid);
952             continue;
953         }
954         break;
955     }
956     context = (PCOMP_CONTEXT) pol;
957     if (CompKey == 999) {
958         return NULL;
959     }
960
961     /* Each listener needs at least 1 context available to receive connections on.
962      * Create additional listener contexts if needed. 
963      */
964     ap_lock(allowed_globals.jobmutex);
965     context->lr->count--;
966     if ((context->lr->count < 2) && !workers_may_exit) {
967         if (create_acceptex_context(pconf, context->lr) == -1) {
968             ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
969                          "Unable to create an AcceptEx completion context -- process will exit");
970             signal_parent(0);
971             return NULL;
972         }
973     }
974     ap_unlock(allowed_globals.jobmutex);
975
976     /* Received a connection */
977     context->conn_io->incnt = BytesRead;
978     GetAcceptExSockaddrs(context->recv_buf, 
979                          0, //context->recv_buf_size,
980                          PADDED_ADDR_SIZE,
981                          PADDED_ADDR_SIZE,
982                          &context->sa_server,
983                          &context->sa_server_len,
984                          &context->sa_client,
985                          &context->sa_client_len);
986
987     return context;
988
989 }
990 /*
991  * worker_main() - this is the main loop for the worker threads
992  *
993  * Windows 95/98
994  * Each thread runs within this function. They wait within remove_job()
995  * for a job to become available, then handle all the requests on that
996  * connection until it is closed, then return to remove_job().
997  *
998  * The worker thread will exit when it removes a job which contains
999  * socket number -1. This provides a graceful thread exit, since
1000  * it will never exit during a connection.
1001  *
1002  * This code in this function is basically equivalent to the child_main()
1003  * from the multi-process (Unix) environment, except that we
1004  *
1005  *  - do not call child_init_modules (child init API phase)
1006  *  - block in remove_job, and when unblocked we have an already
1007  *    accepted socket, instead of blocking on a mutex or select().
1008  */
1009
1010 static void worker_main(int child_num)
1011 {
1012     static BOOLEAN bListenersStarted = FALSE;
1013     PCOMP_CONTEXT context = NULL;
1014
1015     if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1016         /* Windows NT/2000: Create AcceptEx completion contexts for each of the
1017          * listeners
1018          */
1019         ap_lock(allowed_globals.jobmutex);
1020         if (!bListenersStarted) {
1021             ap_listen_rec *lr;
1022             int i;
1023             bListenersStarted = TRUE;
1024             for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1025                 for(i=0; i<2; i++) {
1026                     if (lr->count < 2)
1027                         if (create_acceptex_context(pconf, lr) == -1) {
1028                             ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1029                                          "Unable to create an AcceptEx completion context -- process will exit");
1030                             signal_parent(0);   /* tell parent to die */
1031                         }
1032                 }
1033             }
1034         }
1035         ap_unlock(allowed_globals.jobmutex);
1036     }
1037
1038     while (1) {
1039         conn_rec *current_conn;
1040         ap_iol *iol;
1041
1042         /* Grab a connection off the network */
1043         if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1044             context = win9x_get_connection(context);
1045         }
1046         else {
1047             context = winnt_get_connection(context);
1048         }
1049
1050         if (!context)
1051             break;
1052         sock_disable_nagle(context->accept_socket);
1053         ap_put_os_sock(&context->sock, &context->accept_socket, context->ptrans);
1054         ap_register_cleanup(context->ptrans, context->sock, socket_cleanup, ap_null_cleanup);
1055         iol = win32_attach_socket(context->ptrans, context->sock);
1056         if (iol == NULL) {
1057             ap_log_error(APLOG_MARK, APLOG_ERR, APR_ENOMEM, server_conf,
1058                          "worker_main: attach_socket() failed. Continuing...");
1059             closesocket(context->accept_socket);
1060             continue;
1061         }
1062         ap_bpush_iol(context->conn_io, iol);
1063         current_conn = ap_new_connection(context->ptrans, server_conf, context->conn_io,
1064                                          (struct sockaddr_in *) context->sa_client,
1065                                          (struct sockaddr_in *) context->sa_server,
1066                                          child_num);
1067
1068         ap_process_connection(current_conn);
1069     }
1070 #if 0
1071     ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1072                  "child_main: Setting exit_event");
1073     SetEvent(exit_event);
1074 #endif
1075     /* TODO: Add code to clean-up completion contexts here */
1076 }
1077
1078 static void cleanup_thread(thread **handles, int *thread_cnt, int thread_to_clean)
1079 {
1080     int i;
1081
1082     CloseHandle(handles[thread_to_clean]);
1083     for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1084         handles[i] = handles[i + 1];
1085     (*thread_cnt)--;
1086 }
1087
1088
1089
1090 /*
1091  * child_main() is main loop for the child process. The loop in
1092  * this function becomes the controlling thread for the actually working
1093  * threads (which run in a loop in child_sub_main()).
1094  * Globals Used:
1095  *  exit_event, start_mutex, ap_threads_per_child, server_conf,
1096  *  h_errno defined to WSAGetLastError in winsock2.h,
1097  */
1098 static void child_main()
1099 {
1100     int nthreads = ap_threads_per_child;
1101     int thread_id;
1102     thread **child_handles;
1103     int rv;
1104     ap_status_t status;
1105     time_t end_time;
1106     int i;
1107     ap_context_t *pchild;
1108
1109     ap_create_context(&pchild, pconf);
1110
1111 //    ap_restart_time = time(NULL);
1112     /*
1113      * Wait until we have permission to start accepting connections.
1114      * start_mutex is used to ensure that only one child ever
1115      * goes into the listen/accept loop at once.
1116      */
1117     status = ap_lock(start_mutex);
1118     if (status != APR_SUCCESS) {
1119         ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
1120                      "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1121         signal_parent(0);       /* tell parent to die */
1122         ap_destroy_context(pchild);
1123         exit(0);
1124     }
1125     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, "Child %d: Acquired the start mutex", my_pid);
1126
1127     /* Setup the listening sockets */
1128     if (one_process) {
1129         ap_listen_rec *lr;
1130         setup_listeners(server_conf);
1131
1132         /* Associate the socket with the IO Completion port */
1133         for (lr = ap_listeners; lr; lr = lr->next) {
1134             int nsd;
1135             ap_get_os_sock(&nsd,lr->sd);
1136             CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
1137         }
1138   
1139     } else {
1140         setup_inherited_listeners(server_conf);
1141     }
1142     if (listenmaxfd == INVALID_SOCKET) {
1143         /* No sockets were made, better log something and exit */
1144         ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, NULL,
1145                      "No sockets were created for listening");
1146         signal_parent(0);       /* tell parent to die */
1147         ap_destroy_context(pchild);
1148         exit(0);
1149     }
1150
1151     allowed_globals.jobsemaphore = create_semaphore(0);
1152     ap_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
1153
1154     /* Create the worker thread pool */
1155     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, "Child %d: Creating %d worker threads",my_pid, nthreads);
1156     child_handles = (thread *) alloca(nthreads * sizeof(int));
1157     for (i = 0; i < nthreads; i++) {
1158         child_handles[i] = (thread *) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1159                                                      NULL, 0, &thread_id);
1160     }
1161
1162     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1163         /* Win95/98: Create the accept thread */
1164         _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) accept_and_queue_connections,
1165                        (void *) i, 0, &thread_id);
1166     }
1167
1168     /* Wait for the exit event to be signaled by the parent process */
1169     rv = WaitForSingleObject(exit_event, INFINITE);
1170
1171     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1172                  "Child %d: Exit event signaled. Child process is ending.", my_pid);
1173     workers_may_exit = 1;      
1174
1175     /* Shutdown the worker threads */
1176     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1177         for (i = 0; i < nthreads; i++) {
1178             add_job(-1);
1179         }
1180     }
1181     else { /* Windows NT/2000 */
1182         /* Hack alert... Give the server a couple of seconds to receive 
1183          * connections and drain AcceptEx completion contexts. We will
1184          * probably drop a few connections across a graceful restart, but
1185          * hopefully not many. This needs work...*/
1186         Sleep(2000);
1187
1188         /* Tell the worker threads to exit. Any connections accepted on 
1189          * the completion port from now will be dropped */
1190         for (i=0; i < nthreads; i++) {
1191             if (!PostQueuedCompletionStatus(AcceptExCompPort, 0, 999, NULL)) {
1192                 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1193                              "PostQueuedCompletionStatus failed");
1194             }
1195         }
1196     }
1197
1198     /* Wait for the worker threads to die */
1199     end_time = time(NULL) + 180;
1200     while (nthreads) {
1201         rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1202         if (rv != WAIT_TIMEOUT) {
1203             rv = rv - WAIT_OBJECT_0;
1204             ap_assert((rv >= 0) && (rv < nthreads));
1205             cleanup_thread(child_handles, &nthreads, rv);
1206             continue;
1207         }
1208         break;
1209     }
1210     for (i = 0; i < nthreads; i++) {
1211         TerminateThread(child_handles[i], 1);
1212         CloseHandle(child_handles[i]);
1213     }
1214     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1215                  "Child %d: All worker threads have ended.", my_pid);
1216
1217     if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {    
1218         /* All the worker threads should have exited by now, which will
1219          * cause any outstanding I/O on the completion port to be aborted.
1220          * Drain the completion port of this aborted I/O/
1221          */
1222         drain_acceptex_complport(AcceptExCompPort, TRUE);
1223     }
1224
1225     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1226                  "Child %d: Releasing the start mutex", my_pid);
1227     ap_unlock(start_mutex);
1228
1229     /* Still need to register cleanups for the sockets */
1230     CloseHandle(AcceptExCompPort);
1231     destroy_semaphore(allowed_globals.jobsemaphore);
1232     ap_destroy_lock(allowed_globals.jobmutex);
1233
1234     ap_destroy_context(pchild);
1235 }
1236
1237 /*
1238  * Spawn a child Apache process. The child process has the command line arguments from
1239  * argc and argv[], plus a -Z argument giving the name of an event. The child should
1240  * open and poll or wait on this event. When it is signalled, the child should die.
1241  * prefix is a prefix string for the event name.
1242  * 
1243  * The child_num argument on entry contains a serial number for this child (used to create
1244  * a unique event name). On exit, this number will have been incremented by one, ready
1245  * for the next call. 
1246  *
1247  * On exit, the value pointed to be *ev will contain the event created
1248  * to signal the new child process.
1249  *
1250  * The return value is the handle to the child process if successful, else -1. If -1 is
1251  * returned the error will already have been logged by ap_log_error().
1252  */
1253
1254 /**********************************************************************
1255  * master_main - this is the parent (main) process. We create a
1256  * child process to do the work, then sit around waiting for either
1257  * the child to exit, or a restart or exit signal. If the child dies,
1258  * we just respawn a new one. If we have a shutdown or graceful restart,
1259  * tell the child to die when it is ready. If it is a non-graceful
1260  * restart, force the child to die immediately.
1261  **********************************************************************/
1262
1263 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1264
1265 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1266 {
1267     int i;
1268     int handle = 0;
1269
1270     CloseHandle(handles[position]);
1271     CloseHandle(events[position]);
1272
1273     handle = (int)handles[position];
1274
1275     for (i = position; i < (*processes)-1; i++) {
1276         handles[i] = handles[i + 1];
1277         events[i] = events[i + 1];
1278     }
1279     (*processes)--;
1280 }
1281
1282 static int create_process(ap_context_t *p, HANDLE *handles, HANDLE *events, int *processes)
1283 {
1284
1285     int rv;
1286     char buf[1024];
1287     char *pCommand;
1288     int i;
1289     STARTUPINFO si;           /* Filled in prior to call to CreateProcess */
1290     PROCESS_INFORMATION pi;   /* filled in on call to CreateProces */
1291
1292     ap_listen_rec *lr;
1293     DWORD BytesWritten;
1294     HANDLE hPipeRead = NULL;
1295     HANDLE hPipeWrite = NULL;
1296     SECURITY_ATTRIBUTES sa = {0};  
1297
1298     sa.nLength = sizeof(sa);
1299     sa.bInheritHandle = TRUE;
1300     sa.lpSecurityDescriptor = NULL;
1301
1302     /* Create the IOCompletionPort */
1303     if (AcceptExCompPort == NULL) {
1304         AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1305                                                   NULL,
1306                                                   0,
1307                                                   0); /* CONCURRENT ACTIVE THREADS */
1308         if (AcceptExCompPort == NULL) {
1309             ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1310                          "Unable to create the AcceptExCompletionPort -- process will exit");
1311             return -1;
1312         }
1313     }
1314
1315     /* Build the command line. Should look something like this:
1316      * C:/apache/bin/apache.exe -f ap_server_confname 
1317      * First, get the path to the executable...
1318      */
1319     rv = GetModuleFileName(NULL, buf, sizeof(buf));
1320     if (rv == sizeof(buf)) {
1321         ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1322                      "Parent: Path to Apache process too long");
1323         return -1;
1324     } else if (rv == 0) {
1325         ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1326                      "Parent: GetModuleFileName() returned NULL for current process.");
1327         return -1;
1328     }
1329
1330     /* Build the command line */
1331     pCommand = ap_psprintf(p, "\"%s\"", buf);  
1332     for (i = 1; i < server_conf->process->argc; i++) {
1333         pCommand = ap_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1334     }
1335
1336     /* Create a pipe to send socket info to the child */
1337     if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1338         ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1339                      "Parent: Unable to create pipe to child process.\n");
1340         return -1;
1341     }
1342
1343     SetEnvironmentVariable("AP_PARENT_PID",ap_psprintf(p,"%d",parent_pid));
1344
1345     /* Give the read end of the pipe (hPipeRead) to the child as stdin. The 
1346      * parent will write the socket data to the child on this pipe.
1347      */
1348     memset(&si, 0, sizeof(si));
1349     memset(&pi, 0, sizeof(pi));
1350     si.cb = sizeof(si);
1351     si.dwFlags     = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1352     si.wShowWindow = SW_HIDE;
1353     si.hStdInput   = hPipeRead;
1354
1355     if (!CreateProcess(NULL, pCommand, NULL, NULL, 
1356                        TRUE,               /* Inherit handles */
1357                        CREATE_SUSPENDED,   /* Creation flags */
1358                        NULL,               /* Environment block */
1359                        NULL,
1360                        &si, &pi)) {
1361         ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1362                      "Parent: Not able to create the child process.");
1363         /*
1364          * We must close the handles to the new process and its main thread
1365          * to prevent handle and memory leaks.
1366          */ 
1367         CloseHandle(pi.hProcess);
1368         CloseHandle(pi.hThread);
1369         return -1;
1370     }
1371     else {
1372         HANDLE kill_event;
1373         LPWSAPROTOCOL_INFO  lpWSAProtocolInfo;
1374         HANDLE hDupedCompPort;
1375
1376         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1377                      "Parent: Created child process %d", pi.dwProcessId);
1378
1379         SetEnvironmentVariable("AP_PARENT_PID",NULL);
1380
1381         /* Create the exit_event, apCchild_pid */
1382         sa.nLength = sizeof(sa);
1383         sa.bInheritHandle = TRUE;
1384         sa.lpSecurityDescriptor = NULL;        
1385         kill_event = CreateEvent(&sa, TRUE, FALSE, ap_psprintf(pconf,"apC%d", pi.dwProcessId));
1386         if (!kill_event) {
1387             ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1388                          "Parent: Could not create exit event for child process");
1389             CloseHandle(pi.hProcess);
1390             CloseHandle(pi.hThread);
1391             return -1;
1392         }
1393         
1394         /* Assume the child process lives. Update the process and event tables */
1395         handles[*processes] = pi.hProcess;
1396         events[*processes] = kill_event;
1397         (*processes)++;
1398
1399         /* We never store the thread's handle, so close it now. */
1400         ResumeThread(pi.hThread);
1401         CloseHandle(pi.hThread);
1402
1403         /* Run the chain of open sockets. For each socket, duplicate it 
1404          * for the target process then send the WSAPROTOCOL_INFO 
1405          * (returned by dup socket) to the child */
1406         for (lr = ap_listeners; lr; lr = lr->next) {
1407             int nsd;
1408             lpWSAProtocolInfo = ap_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1409             ap_get_os_sock(&nsd,lr->sd);
1410             /* Associate the socket with the IOcompletion port */
1411             CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
1412             ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_INFO, APR_SUCCESS, server_conf,
1413                          "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1414             if (WSADuplicateSocket(nsd, pi.dwProcessId,
1415                                    lpWSAProtocolInfo) == SOCKET_ERROR) {
1416                 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, server_conf,
1417                              "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1418                 return -1;
1419             }
1420
1421             if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1422                            &BytesWritten,
1423                            (LPOVERLAPPED) NULL)) {
1424                 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1425                              "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1426                 return -1;
1427             }
1428             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1429                          "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1430         }
1431         /* Now, send the AcceptEx completion port to the child */
1432         if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort, 
1433                              pi.hProcess, &hDupedCompPort,  0,
1434                              TRUE, DUPLICATE_SAME_ACCESS)) {
1435             ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1436                          "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1437             return -1;
1438         }
1439         WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1440     }
1441
1442     CloseHandle(hPipeRead);
1443     CloseHandle(hPipeWrite);        
1444
1445     return 0;
1446 }
1447
1448 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1449 {
1450     int remaining_children_to_start = ap_daemons_to_start;
1451     int i;
1452     int rv, cld;
1453     int child_num = 0;
1454     int restart_pending = 0;
1455     int shutdown_pending = 0;
1456     int current_live_processes = 0; /* number of child process we know about */
1457
1458     HANDLE process_handles[MAX_PROCESSES];
1459     HANDLE process_kill_events[MAX_PROCESSES];
1460
1461     setup_listeners(s);
1462
1463     /* Create child process 
1464      * Should only be one in this version of Apache for WIN32 
1465      */
1466     service_set_status(SERVICE_START_PENDING);
1467     while (remaining_children_to_start--) {
1468         if (create_process(pconf, process_handles, process_kill_events, 
1469                            &current_live_processes) < 0) {
1470             ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1471                          "master_main: create child process failed. Exiting.");
1472             shutdown_pending = 1;
1473             goto die_now;
1474         }
1475     }
1476     service_set_status(SERVICE_RUNNING);
1477
1478     restart_pending = shutdown_pending = 0;
1479     
1480     /* Wait for shutdown or restart events or for child death */
1481     process_handles[current_live_processes] = shutdown_event;
1482     process_handles[current_live_processes+1] = restart_event;
1483     printf("process/shutdown/restart %d %d %d\n", process_handles[0], process_handles[1], process_handles[2]);
1484     rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles, 
1485                                 FALSE, INFINITE);
1486     cld = rv - WAIT_OBJECT_0;
1487     if (rv == WAIT_FAILED) {
1488         /* Something serious is wrong */
1489         ap_log_error(APLOG_MARK,APLOG_CRIT, GetLastError(), server_conf,
1490                      "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1491         shutdown_pending = 1;
1492     }
1493     else if (rv == WAIT_TIMEOUT) {
1494         /* Hey, this cannot happen */
1495         ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1496                      "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1497         shutdown_pending = 1;
1498     }
1499     else if (cld == current_live_processes) {
1500         /* shutdown_event signalled */
1501         shutdown_pending = 1;
1502         printf("shutdown event signaled\n");
1503         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s, 
1504                      "master_main: Shutdown event signaled -- doing server shutdown.");
1505         if (ResetEvent(shutdown_event) == 0) {
1506             ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1507                          "ResetEvent(shutdown_event)");
1508         }
1509
1510     }
1511     else if (cld == current_live_processes+1) {
1512         /* restart_event signalled */
1513         int children_to_kill = current_live_processes;
1514         restart_pending = 1;
1515         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s, 
1516                      "master_main: Restart event signaled. Doing a graceful restart.");
1517         if (ResetEvent(restart_event) == 0) {
1518             ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1519                          "master_main: ResetEvent(restart_event) failed.");
1520         }
1521         /* Signal each child process to die 
1522          * We are making a big assumption here that the child process, once signaled,
1523          * will REALLY go away. Since this is a restart, we do not want to hold the 
1524          * new child process up waiting for the old child to die. Remove the old 
1525          * child out of the process_handles ap_table_t and hope for the best...
1526          */
1527         for (i = 0; i < children_to_kill; i++) {
1528             printf("SetEvent handle = %d\n", process_kill_events[i]);
1529             if (SetEvent(process_kill_events[i]) == 0)
1530                 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1531                              "master_main: SetEvent for child process in slot #%d failed", i);
1532             cleanup_process(process_handles, process_kill_events, i, &current_live_processes);
1533         }
1534     } 
1535     else {
1536         /* A child process must have exited because of a fatal error condition (seg fault, etc.). 
1537          * Remove the dead process 
1538          * from the process_handles and process_kill_events ap_table_t and create a new
1539          * child process.
1540          * TODO: Consider restarting the child immediately without looping through http_main
1541          * and without rereading the configuration. Will need this if we ever support multiple 
1542          * children. One option, create a parent thread which waits on child death and restarts it.
1543          */
1544         restart_pending = 1;
1545         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf, 
1546                      "master_main: Child process failed. Restarting the child process.");
1547         ap_assert(cld < current_live_processes);
1548         cleanup_process(process_handles, process_kill_events, cld, &current_live_processes);
1549         /* APD2("main_process: child in slot %d died", rv); */
1550         /* restart_child(process_hancles, process_kill_events, cld, &current_live_processes); */
1551
1552         /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead 
1553          * process. */
1554         drain_acceptex_complport(AcceptExCompPort, FALSE);
1555     }
1556
1557 die_now:
1558     if (shutdown_pending) {
1559         int tmstart = time(NULL);
1560         /* Signal each child processes to die */
1561         for (i = 0; i < current_live_processes; i++) {
1562             printf("SetEvent handle = %d\n", process_kill_events[i]);
1563             if (SetEvent(process_kill_events[i]) == 0)
1564                 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1565                              "master_main: SetEvent for child process in slot #%d failed", i);
1566         }
1567
1568         while (current_live_processes && ((tmstart+60) > time(NULL))) {
1569             rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1570             if (rv == WAIT_TIMEOUT)
1571                 continue;
1572             ap_assert(rv != WAIT_FAILED);
1573             cld = rv - WAIT_OBJECT_0;
1574             ap_assert(rv < current_live_processes);
1575             cleanup_process(process_handles, process_kill_events, cld, &current_live_processes);
1576         }
1577         for (i = 0; i < current_live_processes; i++) {
1578             ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1579                          "forcing termination of child #%d (handle %d)", i, process_handles[i]);
1580             TerminateProcess((HANDLE) process_handles[i], 1);
1581         }
1582         return (0); /* Tell the caller we are shutting down */
1583     }
1584
1585     return (1); /* Tell the caller we want a restart */
1586 }
1587
1588 /* 
1589  * winnt_pre_config() hook
1590  */
1591 static void winnt_pre_config(ap_context_t *pconf, ap_context_t *plog, ap_context_t *ptemp) 
1592 {
1593     char *pid;
1594
1595     one_process = !!getenv("ONE_PROCESS");
1596
1597     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1598     GetVersionEx(&osver);
1599
1600     /* AP_PARENT_PID is only valid in the child */
1601     pid = getenv("AP_PARENT_PID");
1602     if (pid) {
1603         /* This is the child */
1604         parent_pid = atoi(pid);
1605         my_pid = getpid();
1606     }
1607     else {
1608         /* This is the parent */
1609         parent_pid = my_pid = getpid();
1610
1611     }
1612
1613     ap_listen_pre_config();
1614     ap_daemons_to_start = DEFAULT_NUM_DAEMON;
1615     ap_threads_per_child = DEFAULT_START_THREAD;
1616     ap_pid_fname = DEFAULT_PIDLOG;
1617     max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1618
1619     ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1620
1621 }
1622
1623 static void winnt_post_config(ap_context_t *pconf, ap_context_t *plog, ap_context_t *ptemp, server_rec* server_conf)
1624 {
1625     server_conf = server_conf;
1626 }
1627
1628 API_EXPORT(int) ap_mpm_run(ap_context_t *_pconf, ap_context_t *plog, server_rec *s )
1629 {
1630
1631     char* exit_event_name;
1632     static int restart = 0;             /* Default is to not restart */
1633 //    time_t tmstart;
1634     static HANDLE shutdown_event;       /* used to signal shutdown to parent */
1635     static HANDLE restart_event;        /* used to signal a restart to parent */
1636
1637     pconf = _pconf;
1638     server_conf = s;
1639
1640     if ((parent_pid != my_pid) || one_process) {
1641         /* Child process */
1642         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1643                      "Child %d: Child process is running", my_pid);        
1644         AMCSocketInitialize();
1645         exit_event_name = ap_psprintf(pconf, "apC%d", my_pid);
1646         setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1647
1648         if (one_process) {
1649             /* Create the IO CompletionPort */
1650             if (AcceptExCompPort == NULL) {
1651                 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1652                                                           NULL, 0, 0); 
1653                 if (AcceptExCompPort == NULL) {
1654                     ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1655                                  "Unable to create the AcceptExCompletionPort -- process will exit");
1656                     return -1;
1657                 }
1658             }
1659             ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1660             exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1661         }
1662         else {
1663             ap_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1664             exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1665             ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1666                          "Child %d: exit_event_name = %s", my_pid, exit_event_name);        
1667         }
1668         ap_assert(start_mutex);
1669         ap_assert(exit_event);
1670
1671         child_main();
1672
1673         CloseHandle(exit_event);
1674         AMCSocketCleanup();
1675         restart = 0;
1676     }
1677     else {
1678         /* Parent process */
1679         PSECURITY_ATTRIBUTES sa = GetNullACL();  /* returns NULL if invalid (Win95?) */
1680
1681         setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1682         if (!restart) {
1683             ap_log_pid(pconf, ap_pid_fname);
1684
1685             service_set_status(SERVICE_START_PENDING);
1686             AMCSocketInitialize();
1687 //            setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1688         
1689             /* Create shutdown event, apPID_shutdown, where PID is the parent 
1690              * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
1691              */
1692             shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
1693             if (!shutdown_event) {
1694                 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), s,
1695                              "master_main: Cannot create shutdown event %s", signal_shutdown_name);
1696                 CleanNullACL((void *)sa);
1697                 exit(1);
1698             }
1699
1700             /* Create restart event, apPID_restart, where PID is the parent 
1701              * Apache process ID. Restart is signaled by 'apache -k restart'.
1702              */
1703 //            restart_event = CreateEvent(sa, TRUE, FALSE, signal_restart_name);
1704             restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
1705             if (!restart_event) {
1706                 CloseHandle(shutdown_event);
1707                 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), s,
1708                              "ap_run_mpm: Cannot create restart event %s", signal_restart_name);
1709                 CleanNullACL((void *)sa);
1710                 exit(1);
1711             }
1712             CleanNullACL((void *)sa);
1713             
1714             /* Create the start mutex, apPID, where PID is the parent Apache process ID.
1715              * Ths start mutex is used during a restart to prevent more than one 
1716              * child process from entering the accept loop at once.
1717              */
1718 //            ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1719             ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,s->process->pool);
1720             /* TODO: Add some code to detect failure */
1721         }
1722
1723         /* Go to work... */
1724         restart = master_main(server_conf, shutdown_event, restart_event);
1725
1726         if (!restart) {
1727             const char *pidfile = NULL;
1728             /* Shutting down. Clean up... */
1729             pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1730             if ( pidfile != NULL && unlink(pidfile) == 0)
1731                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO,APR_SUCCESS,
1732                              server_conf, "removed PID file %s (pid=%ld)",
1733                              pidfile, (long)getpid());
1734             ap_destroy_lock(start_mutex);
1735
1736             CloseHandle(restart_event);
1737             CloseHandle(shutdown_event);
1738             AMCSocketCleanup();
1739
1740             service_set_status(SERVICE_STOPPED);
1741         }
1742     }
1743     return !restart;
1744 }
1745
1746 static void winnt_hooks(void)
1747 {
1748 //    INIT_SIGLIST()
1749     one_process = 0;
1750     /* Configuration hooks implemented by http_config.c ... */
1751 }
1752
1753 /* 
1754  * Command processors 
1755  */
1756 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg) 
1757 {
1758     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1759     if (err != NULL) {
1760         return err;
1761     }
1762
1763     if (cmd->server->is_virtual) {
1764         return "PidFile directive not allowed in <VirtualHost>";
1765     }
1766     ap_pid_fname = arg;
1767     return NULL;
1768 }
1769
1770 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg) 
1771 {
1772     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1773     if (err != NULL) {
1774         return err;
1775     }
1776
1777     ap_threads_per_child = atoi(arg);
1778     if (ap_threads_per_child > HARD_THREAD_LIMIT) {
1779         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1780                      "WARNING: ThreadsPerChild of %d exceeds compile time"
1781                      " limit of %d threads,", ap_threads_per_child, 
1782                      HARD_THREAD_LIMIT);
1783         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1784                      " lowering ThreadsPerChild to %d. To increase, please"
1785                      " see the  HARD_THREAD_LIMIT define in src/include/httpd.h.", 
1786                      HARD_THREAD_LIMIT);
1787     }
1788     else if (ap_threads_per_child < 1) {
1789         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1790                      "WARNING: Require ThreadsPerChild > 0, setting to 1");
1791         ap_threads_per_child = 1;
1792     }
1793     return NULL;
1794 }
1795
1796
1797 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg) 
1798 {
1799     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1800     if (err != NULL) {
1801         return err;
1802     }
1803
1804     max_requests_per_child = atoi(arg);
1805
1806     return NULL;
1807 }
1808
1809 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg) 
1810 {
1811     struct stat finfo;
1812     const char *fname;
1813     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1814     if (err != NULL) {
1815         return err;
1816     }
1817
1818     fname = ap_server_root_relative(cmd->pool, arg);
1819     if ((stat(fname, &finfo) == -1) || !S_ISDIR(finfo.st_mode)) {
1820         return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname, 
1821                           " does not exist or is not a directory", NULL);
1822     }
1823     ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1824     return NULL;
1825 }
1826
1827 /* Stub functions until this MPM supports the connection status API */
1828
1829 API_EXPORT(void) ap_update_connection_status(long conn_id, const char *key, \
1830                                              const char *value)
1831 {
1832     /* NOP */
1833 }
1834
1835 API_EXPORT(void) ap_reset_connection_status(long conn_id)
1836 {
1837     /* NOP */
1838 }
1839
1840 API_EXPORT(ap_array_header_t *) ap_get_status_table(ap_context_t *p)
1841 {
1842     /* NOP */
1843     return NULL;
1844 }
1845
1846 static const command_rec winnt_cmds[] = {
1847 LISTEN_COMMANDS
1848 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
1849     "A file for logging the server process ID"},
1850 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
1851   "Number of threads each child creates" },
1852 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
1853   "Maximum number of requests a particular child serves before dying." },
1854 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
1855   "The location of the directory Apache changes to before dumping core" },
1856 { NULL }
1857 };
1858
1859 module MODULE_VAR_EXPORT mpm_winnt_module = {
1860     MPM20_MODULE_STUFF,
1861     winnt_pre_config,           /* hook run before configuration is read */
1862     NULL,                       /* create per-directory config structure */
1863     NULL,                       /* merge per-directory config structures */
1864     NULL,                       /* create per-server config structure */
1865     NULL,                       /* merge per-server config structures */
1866     winnt_cmds,                 /* command ap_table_t */
1867     NULL,                       /* handlers */
1868     winnt_hooks                 /* register_hooks */
1869 };