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