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