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