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