]> granicus.if.org Git - apache/blob - server/mpm/winnt/mpm_winnt.c
Watching for tornadoes tonite
[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     context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
866     if (context->accept_socket == INVALID_SOCKET) {
867         ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
868                      "create_acceptex_context: socket() failed. Process will exit.");
869         return -1;
870     }
871     ap_create_pool(&context->ptrans, _pconf);
872     context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
873     context->recv_buf = context->conn_io->inbase;
874     context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
875     ap_get_os_sock(&nsd, context->lr->sd);
876
877     /* AcceptEx on the completion context. The completion context will be signaled
878      * when a connection is accepted. */
879     if (!AcceptEx(nsd, context->accept_socket,
880                   context->recv_buf, 
881                   0, //context->recv_buf_size,
882                   PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
883                   &BytesRead,
884                   (LPOVERLAPPED) context)) {
885         lasterror = WSAGetLastError();
886         if (lasterror != ERROR_IO_PENDING) {
887             ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
888                          "create_acceptex_context: AcceptEx failed. Process will exit.");
889             return -1;
890         }
891         
892         /* SO_UPDATE_ACCEPT_CONTEXT is a Microsoft-ism which is required
893          * if you want to use more than several key socket calls on a
894          * socket initialized via AcceptEx().  In particular, it is
895          * required for shutdown() to work.
896          */
897
898         if (setsockopt(context->accept_socket, SOL_SOCKET,
899                        SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
900                        sizeof(nsd))) {
901             ap_log_error(APLOG_MARK, APLOG_ERR, WSAGetLastError(), server_conf,
902                          "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
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     if (context->accept_socket == -1)
919         context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
920
921     if (context->accept_socket == INVALID_SOCKET) {
922         ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
923                      "reset_acceptex_context: socket() failed. Process will exit.");
924         return -1;
925     }
926
927     ap_clear_pool(context->ptrans);
928     context->sock = NULL;
929     context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
930     context->recv_buf = context->conn_io->inbase;
931     context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
932     ap_get_os_sock(&nsd, context->lr->sd);
933
934     if (!AcceptEx(nsd, context->accept_socket, 
935                   context->recv_buf, 
936                   0, //context->recv_buf_size,
937                   PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
938                   &BytesRead, (LPOVERLAPPED) context)) {
939         lasterror = WSAGetLastError();
940         if (lasterror != ERROR_IO_PENDING) {
941             ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
942                          "reset_acceptex_context: AcceptEx failed. Leaving the process running.");
943             return -1;
944         }
945         
946         /* SO_UPDATE_ACCEPT_CONTEXT is a Microsoft-ism which is required
947          * if you want to use more than several key socket calls on a
948          * socket initialized via AcceptEx().  In particular, it is
949          * required for shutdown() to work.
950          */
951
952         if (setsockopt(context->accept_socket, SOL_SOCKET,
953                        SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
954                        sizeof(nsd))) {
955             ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(),
956                          server_conf,
957                          "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
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 = -1; /* 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     static BOOLEAN bListenersStarted = FALSE;
1058     PCOMP_CONTEXT context = NULL;
1059
1060     if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1061         /* Windows NT/2000: Create AcceptEx completion contexts for each of the
1062          * listeners
1063          */
1064         ap_lock(allowed_globals.jobmutex);
1065         if (!bListenersStarted) {
1066             ap_listen_rec *lr;
1067             int i;
1068             bListenersStarted = TRUE;
1069             for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1070                 for(i=0; i<2; i++) {
1071                     if (lr->count < 2)
1072                         if (create_acceptex_context(pconf, lr) == -1) {
1073                             ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1074                                          "Unable to create an AcceptEx completion context -- process will exit");
1075                             signal_parent(0);   /* tell parent to die */
1076                         }
1077                 }
1078             }
1079         }
1080         ap_unlock(allowed_globals.jobmutex);
1081     }
1082
1083     while (1) {
1084         conn_rec *current_conn;
1085         ap_iol *iol;
1086
1087         /* Grab a connection off the network */
1088         if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1089             context = win9x_get_connection(context);
1090         }
1091         else {
1092             context = winnt_get_connection(context);
1093         }
1094
1095         if (!context)
1096             break;
1097         sock_disable_nagle(context->accept_socket);
1098         ap_put_os_sock(&context->sock, &context->accept_socket, context->ptrans);
1099         ap_register_cleanup(context->ptrans, context->sock, socket_cleanup, ap_null_cleanup);
1100         iol = win32_attach_socket(context->ptrans, context->sock);
1101         if (iol == NULL) {
1102             ap_log_error(APLOG_MARK, APLOG_ERR, APR_ENOMEM, server_conf,
1103                          "worker_main: attach_socket() failed. Continuing...");
1104             closesocket(context->accept_socket);
1105             continue;
1106         }
1107         ap_bpush_iol(context->conn_io, iol);
1108         current_conn = ap_new_connection(context->ptrans, server_conf, context->conn_io,
1109                                          (struct sockaddr_in *) context->sa_client,
1110                                          (struct sockaddr_in *) context->sa_server,
1111                                          child_num);
1112
1113         ap_process_connection(current_conn);
1114     }
1115 #if 0
1116     ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1117                  "child_main: Setting exit_event");
1118     SetEvent(exit_event);
1119 #endif
1120     /* TODO: Add code to clean-up completion contexts here */
1121 }
1122
1123 static void cleanup_thread(thread **handles, int *thread_cnt, int thread_to_clean)
1124 {
1125     int i;
1126
1127     CloseHandle(handles[thread_to_clean]);
1128     for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1129         handles[i] = handles[i + 1];
1130     (*thread_cnt)--;
1131 }
1132
1133
1134
1135 /*
1136  * child_main() is main loop for the child process. The loop in
1137  * this function becomes the controlling thread for the actually working
1138  * threads (which run in a loop in child_sub_main()).
1139  * Globals Used:
1140  *  exit_event, start_mutex, ap_threads_per_child, server_conf,
1141  *  h_errno defined to WSAGetLastError in winsock2.h,
1142  */
1143 static void child_main()
1144 {
1145     char* exit_event_name;
1146     int nthreads = ap_threads_per_child;
1147     int thread_id;
1148     thread **child_handles;
1149     int rv;
1150     ap_status_t status;
1151     time_t end_time;
1152     int i;
1153     ap_pool_t *pchild;
1154
1155     /* This is the child process or we are running in single process
1156      * mode.
1157      */
1158
1159     exit_event_name = ap_psprintf(pconf, "apC%d", my_pid);
1160     setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1161
1162     if (one_process) {
1163         /* Single process mode */
1164         ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1165         exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1166
1167         setup_listeners(server_conf);
1168         bind_listeners_to_completion_port();
1169     }
1170     else {
1171         /* Child process mode */
1172         ap_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1173         exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1174         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1175                      "Child %d: exit_event_name = %s", my_pid, exit_event_name);
1176
1177         setup_inherited_listeners(server_conf);
1178     }
1179     ap_assert(start_mutex);
1180     ap_assert(exit_event);
1181
1182     ap_create_pool(&pchild, pconf);
1183
1184
1185     if (listenmaxfd == INVALID_SOCKET) {
1186         /* No sockets were made, better log something and exit */
1187         ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, NULL,
1188                      "No sockets were created for listening");
1189         signal_parent(0);       /* tell parent to die */
1190         ap_destroy_pool(pchild);
1191         exit(0);
1192     }
1193
1194     allowed_globals.jobsemaphore = create_semaphore(0);
1195     ap_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
1196
1197     /*
1198      * Wait until we have permission to start accepting connections.
1199      * start_mutex is used to ensure that only one child ever
1200      * goes into the listen/accept loop at once.
1201      */
1202     status = ap_lock(start_mutex);
1203     if (status != APR_SUCCESS) {
1204         ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
1205                      "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1206         signal_parent(0);       /* tell parent to die */
1207         ap_destroy_pool(pchild);
1208         exit(0);
1209     }
1210     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, "Child %d: Acquired the start mutex", my_pid);
1211
1212     /* Create the worker thread pool */
1213     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, "Child %d: Creating %d worker threads",my_pid, nthreads);
1214     child_handles = (thread *) alloca(nthreads * sizeof(int));
1215     for (i = 0; i < nthreads; i++) {
1216         child_handles[i] = (thread *) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1217                                                      NULL, 0, &thread_id);
1218     }
1219
1220     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1221         /* Win95/98: Create the accept thread */
1222         _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) accept_and_queue_connections,
1223                        (void *) i, 0, &thread_id);
1224     }
1225
1226     /* Wait for the exit event to be signaled by the parent process */
1227     rv = WaitForSingleObject(exit_event, INFINITE);
1228
1229     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1230                  "Child %d: Exit event signaled. Child process is ending.", my_pid);
1231     workers_may_exit = 1;      
1232
1233     /* Shutdown the worker threads */
1234     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1235         for (i = 0; i < nthreads; i++) {
1236             add_job(-1);
1237         }
1238     }
1239     else { /* Windows NT/2000 */
1240         /* Tell the worker threads to exit. */
1241         for (i=0; i < nthreads; i++) {
1242             if (!PostQueuedCompletionStatus(AcceptExCompPort, 0, 999, NULL)) {
1243                 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1244                              "PostQueuedCompletionStatus failed");
1245             }
1246         }
1247     }
1248
1249     /* Wait for the worker threads to die */
1250     end_time = time(NULL) + 180;
1251     while (nthreads) {
1252         rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1253         if (rv != WAIT_TIMEOUT) {
1254             rv = rv - WAIT_OBJECT_0;
1255             ap_assert((rv >= 0) && (rv < nthreads));
1256             cleanup_thread(child_handles, &nthreads, rv);
1257             continue;
1258         }
1259         break;
1260     }
1261     for (i = 0; i < nthreads; i++) {
1262         TerminateThread(child_handles[i], 1);
1263         CloseHandle(child_handles[i]);
1264     }
1265     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1266                  "Child %d: All worker threads have ended.", my_pid);
1267
1268     if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {    
1269         /* All the worker threads should have exited by now, which will
1270          * cause any outstanding I/O on the completion port to be aborted.
1271          * Drain the completion port of this aborted I/O/
1272          */
1273         drain_acceptex_complport(AcceptExCompPort, TRUE);
1274     }
1275
1276     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1277                  "Child %d: Releasing the start mutex", my_pid);
1278     ap_unlock(start_mutex);
1279
1280     /* Still need to register cleanups for the sockets */
1281     CloseHandle(AcceptExCompPort);
1282     destroy_semaphore(allowed_globals.jobsemaphore);
1283     ap_destroy_lock(allowed_globals.jobmutex);
1284
1285     ap_destroy_pool(pchild);
1286     CloseHandle(exit_event);
1287 }
1288
1289 /*
1290  * Spawn a child Apache process. The child process has the command line arguments from
1291  * argc and argv[], plus a -Z argument giving the name of an event. The child should
1292  * open and poll or wait on this event. When it is signalled, the child should die.
1293  * prefix is a prefix string for the event name.
1294  * 
1295  * The child_num argument on entry contains a serial number for this child (used to create
1296  * a unique event name). On exit, this number will have been incremented by one, ready
1297  * for the next call. 
1298  *
1299  * On exit, the value pointed to be *ev will contain the event created
1300  * to signal the new child process.
1301  *
1302  * The return value is the handle to the child process if successful, else -1. If -1 is
1303  * returned the error will already have been logged by ap_log_error().
1304  */
1305
1306 /**********************************************************************
1307  * master_main - this is the parent (main) process. We create a
1308  * child process to do the work, then sit around waiting for either
1309  * the child to exit, or a restart or exit signal. If the child dies,
1310  * we just respawn a new one. If we have a shutdown or graceful restart,
1311  * tell the child to die when it is ready. If it is a non-graceful
1312  * restart, force the child to die immediately.
1313  **********************************************************************/
1314
1315 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1316
1317 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1318 {
1319     int i;
1320     int handle = 0;
1321
1322     CloseHandle(handles[position]);
1323     CloseHandle(events[position]);
1324
1325     handle = (int)handles[position];
1326
1327     for (i = position; i < (*processes)-1; i++) {
1328         handles[i] = handles[i + 1];
1329         events[i] = events[i + 1];
1330     }
1331     (*processes)--;
1332 }
1333
1334 static int create_process(ap_pool_t *p, HANDLE *handles, HANDLE *events, int *processes)
1335 {
1336
1337     int rv;
1338     char buf[1024];
1339     char *pCommand;
1340     int i;
1341     STARTUPINFO si;           /* Filled in prior to call to CreateProcess */
1342     PROCESS_INFORMATION pi;   /* filled in on call to CreateProces */
1343
1344     ap_listen_rec *lr;
1345     DWORD BytesWritten;
1346     HANDLE hPipeRead = NULL;
1347     HANDLE hPipeWrite = NULL;
1348     SECURITY_ATTRIBUTES sa = {0};  
1349
1350     sa.nLength = sizeof(sa);
1351     sa.bInheritHandle = TRUE;
1352     sa.lpSecurityDescriptor = NULL;
1353
1354     /* Build the command line. Should look something like this:
1355      * C:/apache/bin/apache.exe -f ap_server_confname 
1356      * First, get the path to the executable...
1357      */
1358     rv = GetModuleFileName(NULL, buf, sizeof(buf));
1359     if (rv == sizeof(buf)) {
1360         ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1361                      "Parent: Path to Apache process too long");
1362         return -1;
1363     } else if (rv == 0) {
1364         ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1365                      "Parent: GetModuleFileName() returned NULL for current process.");
1366         return -1;
1367     }
1368
1369     /* Build the command line */
1370     pCommand = ap_psprintf(p, "\"%s\"", buf);  
1371     for (i = 1; i < server_conf->process->argc; i++) {
1372         pCommand = ap_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1373     }
1374
1375     /* Create a pipe to send socket info to the child */
1376     if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1377         ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1378                      "Parent: Unable to create pipe to child process.\n");
1379         return -1;
1380     }
1381
1382     SetEnvironmentVariable("AP_PARENT_PID",ap_psprintf(p,"%d",parent_pid));
1383
1384     /* Give the read end of the pipe (hPipeRead) to the child as stdin. The 
1385      * parent will write the socket data to the child on this pipe.
1386      */
1387     memset(&si, 0, sizeof(si));
1388     memset(&pi, 0, sizeof(pi));
1389     si.cb = sizeof(si);
1390     si.dwFlags     = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1391     si.wShowWindow = SW_HIDE;
1392     si.hStdInput   = hPipeRead;
1393
1394     if (!CreateProcess(NULL, pCommand, NULL, NULL, 
1395                        TRUE,               /* Inherit handles */
1396                        CREATE_SUSPENDED,   /* Creation flags */
1397                        NULL,               /* Environment block */
1398                        NULL,
1399                        &si, &pi)) {
1400         ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1401                      "Parent: Not able to create the child process.");
1402         /*
1403          * We must close the handles to the new process and its main thread
1404          * to prevent handle and memory leaks.
1405          */ 
1406         CloseHandle(pi.hProcess);
1407         CloseHandle(pi.hThread);
1408         return -1;
1409     }
1410     else {
1411         HANDLE kill_event;
1412         LPWSAPROTOCOL_INFO  lpWSAProtocolInfo;
1413         HANDLE hDupedCompPort;
1414
1415         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1416                      "Parent: Created child process %d", pi.dwProcessId);
1417
1418         SetEnvironmentVariable("AP_PARENT_PID",NULL);
1419
1420         /* Create the exit_event, apCchild_pid */
1421         sa.nLength = sizeof(sa);
1422         sa.bInheritHandle = TRUE;
1423         sa.lpSecurityDescriptor = NULL;        
1424         kill_event = CreateEvent(&sa, TRUE, FALSE, ap_psprintf(pconf,"apC%d", pi.dwProcessId));
1425         if (!kill_event) {
1426             ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1427                          "Parent: Could not create exit event for child process");
1428             CloseHandle(pi.hProcess);
1429             CloseHandle(pi.hThread);
1430             return -1;
1431         }
1432         
1433         /* Assume the child process lives. Update the process and event tables */
1434         handles[*processes] = pi.hProcess;
1435         events[*processes] = kill_event;
1436         (*processes)++;
1437
1438         /* We never store the thread's handle, so close it now. */
1439         ResumeThread(pi.hThread);
1440         CloseHandle(pi.hThread);
1441
1442         /* Run the chain of open sockets. For each socket, duplicate it 
1443          * for the target process then send the WSAPROTOCOL_INFO 
1444          * (returned by dup socket) to the child */
1445         for (lr = ap_listeners; lr; lr = lr->next) {
1446             int nsd;
1447             lpWSAProtocolInfo = ap_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1448             ap_get_os_sock(&nsd,lr->sd);
1449             ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_INFO, APR_SUCCESS, server_conf,
1450                          "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1451             if (WSADuplicateSocket(nsd, pi.dwProcessId,
1452                                    lpWSAProtocolInfo) == SOCKET_ERROR) {
1453                 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, server_conf,
1454                              "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1455                 return -1;
1456             }
1457
1458             if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1459                            &BytesWritten,
1460                            (LPOVERLAPPED) NULL)) {
1461                 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1462                              "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1463                 return -1;
1464             }
1465             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1466                          "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1467         }
1468         if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1469             /* Now, send the AcceptEx completion port to the child */
1470             if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort, 
1471                                  pi.hProcess, &hDupedCompPort,  0,
1472                                  TRUE, DUPLICATE_SAME_ACCESS)) {
1473                 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1474                              "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1475                 return -1;
1476             }
1477
1478             WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1479         }
1480     }
1481
1482     CloseHandle(hPipeRead);
1483     CloseHandle(hPipeWrite);        
1484
1485     return 0;
1486 }
1487
1488 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1489 {
1490     int remaining_children_to_start = ap_daemons_to_start;
1491     int i;
1492     int rv, cld;
1493     int child_num = 0;
1494     int restart_pending = 0;
1495     int shutdown_pending = 0;
1496     int current_live_processes = 0; /* number of child process we know about */
1497
1498     HANDLE process_handles[MAX_PROCESSES];
1499     HANDLE process_kill_events[MAX_PROCESSES];
1500
1501     setup_listeners(s);
1502     bind_listeners_to_completion_port();
1503
1504     /* Create child process 
1505      * Should only be one in this version of Apache for WIN32 
1506      */
1507     service_set_status(SERVICE_START_PENDING);
1508     while (remaining_children_to_start--) {
1509         if (create_process(pconf, process_handles, process_kill_events, 
1510                            &current_live_processes) < 0) {
1511             ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1512                          "master_main: create child process failed. Exiting.");
1513             shutdown_pending = 1;
1514             goto die_now;
1515         }
1516     }
1517     service_set_status(SERVICE_RUNNING);
1518
1519     restart_pending = shutdown_pending = 0;
1520     
1521     /* Wait for shutdown or restart events or for child death */
1522     process_handles[current_live_processes] = shutdown_event;
1523     process_handles[current_live_processes+1] = restart_event;
1524
1525     rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles, 
1526                                 FALSE, INFINITE);
1527     cld = rv - WAIT_OBJECT_0;
1528     if (rv == WAIT_FAILED) {
1529         /* Something serious is wrong */
1530         ap_log_error(APLOG_MARK,APLOG_CRIT, GetLastError(), server_conf,
1531                      "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1532         shutdown_pending = 1;
1533     }
1534     else if (rv == WAIT_TIMEOUT) {
1535         /* Hey, this cannot happen */
1536         ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1537                      "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1538         shutdown_pending = 1;
1539     }
1540     else if (cld == current_live_processes) {
1541         /* shutdown_event signalled */
1542         shutdown_pending = 1;
1543         printf("shutdown event signaled\n");
1544         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s, 
1545                      "master_main: Shutdown event signaled -- doing server shutdown.");
1546         if (ResetEvent(shutdown_event) == 0) {
1547             ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1548                          "ResetEvent(shutdown_event)");
1549         }
1550
1551     }
1552     else if (cld == current_live_processes+1) {
1553         /* restart_event signalled */
1554         int children_to_kill = current_live_processes;
1555         restart_pending = 1;
1556         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s, 
1557                      "master_main: Restart event signaled. Doing a graceful restart.");
1558         if (ResetEvent(restart_event) == 0) {
1559             ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1560                          "master_main: ResetEvent(restart_event) failed.");
1561         }
1562         /* Signal each child process to die 
1563          * We are making a big assumption here that the child process, once signaled,
1564          * will REALLY go away. Since this is a restart, we do not want to hold the 
1565          * new child process up waiting for the old child to die. Remove the old 
1566          * child out of the process_handles ap_table_t and hope for the best...
1567          */
1568         for (i = 0; i < children_to_kill; i++) {
1569             printf("SetEvent handle = %d\n", process_kill_events[i]);
1570             if (SetEvent(process_kill_events[i]) == 0)
1571                 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1572                              "master_main: SetEvent for child process in slot #%d failed", i);
1573             cleanup_process(process_handles, process_kill_events, i, &current_live_processes);
1574         }
1575     } 
1576     else {
1577         /* A child process must have exited because of a fatal error condition (seg fault, etc.). 
1578          * Remove the dead process 
1579          * from the process_handles and process_kill_events ap_table_t and create a new
1580          * child process.
1581          * TODO: Consider restarting the child immediately without looping through http_main
1582          * and without rereading the configuration. Will need this if we ever support multiple 
1583          * children. One option, create a parent thread which waits on child death and restarts it.
1584          */
1585         restart_pending = 1;
1586         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf, 
1587                      "master_main: Child process failed. Restarting the child process.");
1588         ap_assert(cld < current_live_processes);
1589         cleanup_process(process_handles, process_kill_events, cld, &current_live_processes);
1590         /* APD2("main_process: child in slot %d died", rv); */
1591         /* restart_child(process_hancles, process_kill_events, cld, &current_live_processes); */
1592
1593         /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead 
1594          * process. */
1595         drain_acceptex_complport(AcceptExCompPort, FALSE);
1596     }
1597
1598 die_now:
1599     if (shutdown_pending) {
1600         int tmstart = time(NULL);
1601         /* Signal each child processes to die */
1602         for (i = 0; i < current_live_processes; i++) {
1603             printf("SetEvent handle = %d\n", process_kill_events[i]);
1604             if (SetEvent(process_kill_events[i]) == 0)
1605                 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1606                              "master_main: SetEvent for child process in slot #%d failed", i);
1607         }
1608
1609         while (current_live_processes && ((tmstart+60) > time(NULL))) {
1610             rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1611             if (rv == WAIT_TIMEOUT)
1612                 continue;
1613             ap_assert(rv != WAIT_FAILED);
1614             cld = rv - WAIT_OBJECT_0;
1615             ap_assert(rv < current_live_processes);
1616             cleanup_process(process_handles, process_kill_events, cld, &current_live_processes);
1617         }
1618         for (i = 0; i < current_live_processes; i++) {
1619             ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1620                          "forcing termination of child #%d (handle %d)", i, process_handles[i]);
1621             TerminateProcess((HANDLE) process_handles[i], 1);
1622         }
1623         return 0;  /* Tell the caller we do not want to restart */
1624     }
1625
1626     return 1;      /* Tell the caller we want a restart */
1627 }
1628
1629 /* 
1630  * winnt_pre_config() hook
1631  */
1632 static void winnt_pre_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp) 
1633 {
1634     char *pid;
1635
1636     one_process = !!getenv("ONE_PROCESS");
1637
1638     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1639     GetVersionEx(&osver);
1640
1641     /* AP_PARENT_PID is only valid in the child */
1642     pid = getenv("AP_PARENT_PID");
1643     if (pid) {
1644         /* This is the child */
1645         parent_pid = atoi(pid);
1646         my_pid = getpid();
1647     }
1648     else {
1649         /* This is the parent */
1650         parent_pid = my_pid = getpid();
1651     }
1652
1653     ap_listen_pre_config();
1654     ap_daemons_to_start = DEFAULT_NUM_DAEMON;
1655     ap_threads_per_child = DEFAULT_START_THREAD;
1656     ap_pid_fname = DEFAULT_PIDLOG;
1657     max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1658
1659     ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1660
1661 }
1662
1663 static void winnt_post_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp, server_rec* server_conf)
1664 {
1665     static int restart_num = 0;
1666     server_conf = server_conf;
1667
1668     if (parent_pid == my_pid) {
1669         if (restart_num++ == 1) {
1670             /* This code should be run once in the parent and not run
1671              * accross a restart
1672              */
1673             PSECURITY_ATTRIBUTES sa = GetNullACL();  /* returns NULL if invalid (Win95?) */
1674             setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1675             if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1676                 /* Create the AcceptEx IoCompletionPort once in the parent.
1677                  * The completion port persists across restarts. 
1678                  */
1679                 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1680                                                           NULL,
1681                                                           0,
1682                                                           0); /* CONCURRENT ACTIVE THREADS */
1683                 if (AcceptExCompPort == NULL) {
1684                     ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1685                                  "Parent: Unable to create the AcceptExCompletionPort -- process will exit");
1686                     exit(1);
1687                 }
1688             }
1689
1690             ap_log_pid(pconf, ap_pid_fname);
1691             service_set_status(SERVICE_START_PENDING);
1692
1693             AMCSocketInitialize();
1694         
1695             /* Create shutdown event, apPID_shutdown, where PID is the parent 
1696              * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
1697              */
1698             shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
1699             if (!shutdown_event) {
1700                 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
1701                              "Parent: Cannot create shutdown event %s", signal_shutdown_name);
1702                 CleanNullACL((void *)sa);
1703                 exit(1);
1704             }
1705
1706             /* Create restart event, apPID_restart, where PID is the parent 
1707              * Apache process ID. Restart is signaled by 'apache -k restart'.
1708              */
1709             restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
1710             if (!restart_event) {
1711                 CloseHandle(shutdown_event);
1712                 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
1713                              "Parent: Cannot create restart event %s", signal_restart_name);
1714                 CleanNullACL((void *)sa);
1715                 exit(1);
1716             }
1717             CleanNullACL((void *)sa);
1718             
1719             /* Create the start mutex, apPID, where PID is the parent Apache process ID.
1720              * Ths start mutex is used during a restart to prevent more than one 
1721              * child process from entering the accept loop at once.
1722              */
1723             ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS, signal_name_prefix,
1724                                server_conf->process->pool);
1725         }
1726     }
1727 }
1728
1729 API_EXPORT(int) ap_mpm_run(ap_pool_t *_pconf, ap_pool_t *plog, server_rec *s )
1730 {
1731     static int restart = 0;            /* Default is "not a restart" */
1732
1733     pconf = _pconf;
1734     server_conf = s;
1735
1736     if ((parent_pid != my_pid) || one_process) {
1737         /* Running as Child process or in one_process (debug) mode */
1738         ap_log_error(APLOG_MARK, APLOG_ERR, APR_SUCCESS, server_conf,
1739                      "Child %d: Child process is running", my_pid);
1740         AMCSocketInitialize();
1741         child_main();
1742         AMCSocketCleanup();
1743         ap_log_error(APLOG_MARK, APLOG_ERR, APR_SUCCESS, server_conf,
1744                      "Child %d: Child process is exiting", my_pid);        
1745
1746         return 1;
1747     }  /* Child or single process */
1748     else { /* Parent process */
1749         restart = master_main(server_conf, shutdown_event, restart_event);
1750
1751         if (!restart) {
1752             /* Shutting down. Clean up... */
1753             const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1754
1755             if (pidfile != NULL && unlink(pidfile) == 0) {
1756                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO,APR_SUCCESS,
1757                              server_conf, "removed PID file %s (pid=%ld)",
1758                              pidfile, (long)getpid());
1759             }
1760             ap_destroy_lock(start_mutex);
1761
1762             CloseHandle(restart_event);
1763             CloseHandle(shutdown_event);
1764             AMCSocketCleanup();
1765
1766             service_set_status(SERVICE_STOPPED);
1767
1768             return 1;
1769         }
1770     }  /* Parent process */
1771
1772     return 0; /* Restart */
1773 }
1774
1775 static void winnt_hooks(void)
1776 {
1777     one_process = 0;
1778     ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
1779 }
1780
1781 /* 
1782  * Command processors 
1783  */
1784 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg) 
1785 {
1786     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1787     if (err != NULL) {
1788         return err;
1789     }
1790
1791     if (cmd->server->is_virtual) {
1792         return "PidFile directive not allowed in <VirtualHost>";
1793     }
1794     ap_pid_fname = arg;
1795     return NULL;
1796 }
1797
1798 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg) 
1799 {
1800     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1801     if (err != NULL) {
1802         return err;
1803     }
1804
1805     ap_threads_per_child = atoi(arg);
1806     if (ap_threads_per_child > HARD_THREAD_LIMIT) {
1807         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1808                      "WARNING: ThreadsPerChild of %d exceeds compile time"
1809                      " limit of %d threads,", ap_threads_per_child, 
1810                      HARD_THREAD_LIMIT);
1811         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1812                      " lowering ThreadsPerChild to %d. To increase, please"
1813                      " see the  HARD_THREAD_LIMIT define in src/include/httpd.h.", 
1814                      HARD_THREAD_LIMIT);
1815     }
1816     else if (ap_threads_per_child < 1) {
1817         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1818                      "WARNING: Require ThreadsPerChild > 0, setting to 1");
1819         ap_threads_per_child = 1;
1820     }
1821     return NULL;
1822 }
1823
1824
1825 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg) 
1826 {
1827     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1828     if (err != NULL) {
1829         return err;
1830     }
1831
1832     max_requests_per_child = atoi(arg);
1833
1834     return NULL;
1835 }
1836
1837 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg) 
1838 {
1839     struct stat finfo;
1840     const char *fname;
1841     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1842     if (err != NULL) {
1843         return err;
1844     }
1845
1846     fname = ap_server_root_relative(cmd->pool, arg);
1847     if ((stat(fname, &finfo) == -1) || !S_ISDIR(finfo.st_mode)) {
1848         return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname, 
1849                           " does not exist or is not a directory", NULL);
1850     }
1851     ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1852     return NULL;
1853 }
1854
1855 /* Stub functions until this MPM supports the connection status API */
1856
1857 API_EXPORT(void) ap_update_connection_status(long conn_id, const char *key, \
1858                                              const char *value)
1859 {
1860     /* NOP */
1861 }
1862
1863 API_EXPORT(void) ap_reset_connection_status(long conn_id)
1864 {
1865     /* NOP */
1866 }
1867
1868 API_EXPORT(ap_array_header_t *) ap_get_status_table(ap_pool_t *p)
1869 {
1870     /* NOP */
1871     return NULL;
1872 }
1873
1874 static const command_rec winnt_cmds[] = {
1875 LISTEN_COMMANDS
1876 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
1877     "A file for logging the server process ID"},
1878 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
1879   "Number of threads each child creates" },
1880 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
1881   "Maximum number of requests a particular child serves before dying." },
1882 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
1883   "The location of the directory Apache changes to before dumping core" },
1884 { NULL }
1885 };
1886
1887 module MODULE_VAR_EXPORT mpm_winnt_module = {
1888     MPM20_MODULE_STUFF,
1889     winnt_pre_config,           /* hook run before configuration is read */
1890     NULL,                       /* create per-directory config structure */
1891     NULL,                       /* merge per-directory config structures */
1892     NULL,                       /* create per-server config structure */
1893     NULL,                       /* merge per-server config structures */
1894     winnt_cmds,                 /* command ap_table_t */
1895     NULL,                       /* handlers */
1896     winnt_hooks                 /* register_hooks */
1897 };