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