]> granicus.if.org Git - apache/blob - server/mpm/winnt/mpm_winnt.c
Fix a few listener-related lifetime issues [they are created in the
[apache] / server / mpm / winnt / mpm_winnt.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2002 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 "httpd.h" 
61 #include "http_main.h" 
62 #include "http_log.h" 
63 #include "http_config.h"        /* for read_config */ 
64 #include "http_core.h"          /* for get_remote_host */ 
65 #include "http_connection.h"
66 #include "apr_portable.h"
67 #include "apr_getopt.h"
68 #include "apr_strings.h"
69 #include "apr_lib.h"
70 #include "apr_shm.h"
71 #include "apr_thread_mutex.h"
72 #include "ap_mpm.h"
73 #include "ap_config.h"
74 #include "ap_listen.h"
75 #include "mpm_default.h"
76 #include "mpm_winnt.h"
77 #include "mpm_common.h"
78 #include <malloc.h>
79
80 /* Limit on the threads per process.  Clients will be locked out if more than
81  * this  * HARD_SERVER_LIMIT are needed.
82  *
83  * We keep this for one reason it keeps the size of the scoreboard file small
84  * enough that we can read the whole thing without worrying too much about
85  * the overhead.
86  */
87 #ifndef HARD_THREAD_LIMIT
88 #define HARD_THREAD_LIMIT 1920
89 #endif
90
91 /* Limit on the total --- clients will be locked out if more servers than
92  * this are needed.  It is intended solely to keep the server from crashing
93  * when things get out of hand.
94  *
95  * We keep a hard maximum number of servers, for two reasons --- first off,
96  * in case something goes seriously wrong, we want to stop the fork bomb
97  * short of actually crashing the machine we're running on by filling some
98  * kernel table.  Secondly, it keeps the size of the scoreboard file small
99  * enough that we can read the whole thing without worrying too much about
100  * the overhead.
101  */
102 #define HARD_SERVER_LIMIT 1
103
104 /* scoreboard.c does the heavy lifting; all we do is create the child
105  * score by moving a handle down the pipe into the child's stdin.
106  */
107 extern apr_shm_t *ap_scoreboard_shm;
108 server_rec *ap_server_conf;
109 typedef HANDLE thread;
110
111 /* Definitions of WINNT MPM specific config globals */
112 static apr_pool_t *pconf;
113 static apr_pool_t *pchild = NULL;
114 static int workers_may_exit = 0;
115 static int shutdown_in_progress = 0;
116 static unsigned int g_blocked_threads = 0;
117
118 static HANDLE shutdown_event;   /* used to signal the parent to shutdown */
119 static HANDLE restart_event;    /* used to signal the parent to restart */
120 static HANDLE exit_event;       /* used by parent to signal the child to exit */
121 static HANDLE max_requests_per_child_event;
122
123 static char ap_coredump_dir[MAX_STRING_LEN];
124
125 static int one_process = 0;
126 static char const* signal_arg = NULL;
127
128 OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
129
130 apr_proc_mutex_t *start_mutex;
131 static DWORD my_pid;
132 static DWORD parent_pid;
133
134 int ap_threads_per_child = 0;
135
136 /* ap_my_generation are used by the scoreboard code */
137 ap_generation_t volatile ap_my_generation=0;
138
139 /* Queue for managing the passing of COMP_CONTEXTs between
140  * the accept and worker threads.
141  */
142 static apr_thread_mutex_t  *qlock;
143 static PCOMP_CONTEXT qhead = NULL;
144 static PCOMP_CONTEXT qtail = NULL;
145 static int num_completion_contexts = 0;
146 static HANDLE ThreadDispatchIOCP = NULL;
147
148 /* Stub functions until this MPM supports the connection status API */
149
150 AP_DECLARE(void) ap_update_connection_status(long conn_id, const char *key, \
151                                              const char *value)
152 {
153     /* NOP */
154 }
155
156 AP_DECLARE(void) ap_reset_connection_status(long conn_id)
157 {
158     /* NOP */
159 }
160
161 AP_DECLARE(apr_array_header_t *) ap_get_status_table(apr_pool_t *p)
162 {
163     /* NOP */
164     return NULL;
165 }
166
167 /* 
168  * Command processors 
169  */
170
171 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg) 
172 {
173     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
174     if (err != NULL) {
175         return err;
176     }
177
178     ap_threads_per_child = atoi(arg);
179     if (ap_threads_per_child > HARD_THREAD_LIMIT) {
180         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
181                      "WARNING: ThreadsPerChild of %d exceeds compile time"
182                      " limit of %d threads,", ap_threads_per_child, 
183                      HARD_THREAD_LIMIT);
184         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
185                      " lowering ThreadsPerChild to %d. To increase, please"
186                      " see the  HARD_THREAD_LIMIT define in %s.", 
187                      HARD_THREAD_LIMIT, AP_MPM_HARD_LIMITS_FILE);
188         ap_threads_per_child = HARD_THREAD_LIMIT;
189     }
190     else if (ap_threads_per_child < 1) {
191         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
192                      "WARNING: Require ThreadsPerChild > 0, setting to 1");
193         ap_threads_per_child = 1;
194     }
195     return NULL;
196 }
197
198 static const command_rec winnt_cmds[] = {
199 LISTEN_COMMANDS,
200 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
201   "Number of threads each child creates" },
202 { NULL }
203 };
204
205
206 AP_DECLARE(void) mpm_recycle_completion_context(PCOMP_CONTEXT pCompContext)
207 {
208     /* Recycle the completion context.
209      * - destroy the ptrans pool
210      * - put the context on the queue to be consumed by the accept thread
211      * Note: 
212      * pCompContext->accept_socket may be in a disconnected but reusable 
213      * state so -don't- close it.
214      */
215     if (pCompContext) {
216         apr_pool_clear(pCompContext->ptrans);
217         apr_pool_destroy(pCompContext->ptrans);
218         pCompContext->ptrans = NULL;
219         pCompContext->next = NULL;
220         apr_thread_mutex_lock(qlock);
221         if (qtail)
222             qtail->next = pCompContext;
223         else
224             qhead = pCompContext;
225         qtail = pCompContext;
226         apr_thread_mutex_unlock(qlock);
227     }
228 }
229
230 AP_DECLARE(PCOMP_CONTEXT) mpm_get_completion_context(void)
231 {
232     PCOMP_CONTEXT pCompContext = NULL;
233
234     /* Grab a context off the queue */
235     apr_thread_mutex_lock(qlock);
236     if (qhead) {
237         pCompContext = qhead;
238         qhead = qhead->next;
239         if (!qhead)
240             qtail = NULL;
241     }
242     apr_thread_mutex_unlock(qlock);
243
244     /* If we failed to grab a context off the queue, alloc one out of 
245      * the child pool. There may be up to ap_threads_per_child contexts
246      * in the system at once.
247      */
248     if (!pCompContext) {
249         if (num_completion_contexts >= ap_threads_per_child) {
250             static int reported = 0;
251             if (!reported) {
252                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, ap_server_conf,
253                              "Server ran out of threads to serve requests. Consider "
254                              "raising the ThreadsPerChild setting");
255                 reported = 1;
256             }
257             return NULL;
258         }
259         pCompContext = (PCOMP_CONTEXT) apr_pcalloc(pchild, sizeof(COMP_CONTEXT));
260
261         pCompContext->Overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); 
262         if (pCompContext->Overlapped.hEvent == NULL) {
263             /* Hopefully this is a temporary condition ... */
264             ap_log_error(APLOG_MARK,APLOG_WARNING, apr_get_os_error(), ap_server_conf,
265                          "mpm_get_completion_context: CreateEvent failed.");
266             return NULL;
267         }
268         pCompContext->accept_socket = INVALID_SOCKET;
269         num_completion_contexts++;
270     }
271     return pCompContext;
272 }
273
274 AP_DECLARE(apr_status_t) mpm_post_completion_context(PCOMP_CONTEXT pCompContext, 
275                                                      io_state_e state)
276 {
277     LPOVERLAPPED pOverlapped;
278     if (pCompContext)
279         pOverlapped = &pCompContext->Overlapped;
280     else
281         pOverlapped = NULL;
282
283     PostQueuedCompletionStatus(ThreadDispatchIOCP, 0, state, pOverlapped);
284     return APR_SUCCESS;
285 }
286
287 /* This is the helper code to resolve late bound entry points 
288  * missing from one or more releases of the Win32 API...
289  * but it sure would be nice if we didn't duplicate this code
290  * from the APR ;-)
291  */
292 static const char* const lateDllName[DLL_defined] = {
293     "kernel32", "advapi32", "mswsock",  "ws2_32"  };
294 static HMODULE lateDllHandle[DLL_defined] = {
295     NULL,       NULL,       NULL,       NULL      };
296
297 FARPROC ap_load_dll_func(ap_dlltoken_e fnLib, char* fnName, int ordinal)
298 {
299     if (!lateDllHandle[fnLib]) { 
300         lateDllHandle[fnLib] = LoadLibrary(lateDllName[fnLib]);
301         if (!lateDllHandle[fnLib])
302             return NULL;
303     }
304     if (ordinal)
305         return GetProcAddress(lateDllHandle[fnLib], (char *) ordinal);
306     else
307         return GetProcAddress(lateDllHandle[fnLib], fnName);
308 }
309
310 /* To share the semaphores with other processes, we need a NULL ACL
311  * Code from MS KB Q106387
312  */
313 static PSECURITY_ATTRIBUTES GetNullACL()
314 {
315     PSECURITY_DESCRIPTOR pSD;
316     PSECURITY_ATTRIBUTES sa;
317
318     sa  = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES));
319     sa->nLength = sizeof(sizeof(SECURITY_ATTRIBUTES));
320
321     pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
322     sa->lpSecurityDescriptor = pSD;
323
324     if (pSD == NULL || sa == NULL) {
325         return NULL;
326     }
327     apr_set_os_error(0);
328     if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
329         || apr_get_os_error()) {
330         LocalFree( pSD );
331         LocalFree( sa );
332         return NULL;
333     }
334     if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
335         || apr_get_os_error()) {
336         LocalFree( pSD );
337         LocalFree( sa );
338         return NULL;
339     }
340
341     sa->bInheritHandle = TRUE;
342     return sa;
343 }
344
345 static void CleanNullACL( void *sa ) {
346     if( sa ) {
347         LocalFree( ((PSECURITY_ATTRIBUTES)sa)->lpSecurityDescriptor);
348         LocalFree( sa );
349     }
350 }
351
352 /*
353  * The Win32 call WaitForMultipleObjects will only allow you to wait for 
354  * a maximum of MAXIMUM_WAIT_OBJECTS (current 64).  Since the threading 
355  * model in the multithreaded version of apache wants to use this call, 
356  * we are restricted to a maximum of 64 threads.  This is a simplistic 
357  * routine that will increase this size.
358  */
359 static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles, 
360                                    DWORD dwSeconds)
361 {
362     time_t tStopTime;
363     DWORD dwRet = WAIT_TIMEOUT;
364     DWORD dwIndex=0;
365     BOOL bFirst = TRUE;
366   
367     tStopTime = time(NULL) + dwSeconds;
368   
369     do {
370         if (!bFirst)
371             Sleep(1000);
372         else
373             bFirst = FALSE;
374           
375         for (dwIndex = 0; dwIndex * MAXIMUM_WAIT_OBJECTS < nCount; dwIndex++) {
376             dwRet = WaitForMultipleObjects( 
377                 min(MAXIMUM_WAIT_OBJECTS, nCount - (dwIndex * MAXIMUM_WAIT_OBJECTS)),
378                 lpHandles + (dwIndex * MAXIMUM_WAIT_OBJECTS), 
379                 0, 0);
380                                            
381             if (dwRet != WAIT_TIMEOUT) {                                          
382               break;
383             }
384         }
385     } while((time(NULL) < tStopTime) && (dwRet == WAIT_TIMEOUT));
386     
387     return dwRet;
388 }
389
390 /*
391  * Signalling Apache on NT.
392  *
393  * Under Unix, Apache can be told to shutdown or restart by sending various
394  * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
395  * we use "events" instead. The parent apache process goes into a loop
396  * where it waits forever for a set of events. Two of those events are
397  * called
398  *
399  *    apPID_shutdown
400  *    apPID_restart
401  *
402  * (where PID is the PID of the apache parent process). When one of these
403  * is signalled, the Apache parent performs the appropriate action. The events
404  * can become signalled through internal Apache methods (e.g. if the child
405  * finds a fatal error and needs to kill its parent), via the service
406  * control manager (the control thread will signal the shutdown event when
407  * requested to stop the Apache service), from the -k Apache command line,
408  * or from any external program which finds the Apache PID from the
409  * httpd.pid file.
410  *
411  * The signal_parent() function, below, is used to signal one of these events.
412  * It can be called by any child or parent process, since it does not
413  * rely on global variables.
414  *
415  * On entry, type gives the event to signal. 0 means shutdown, 1 means 
416  * graceful restart.
417  */
418 /*
419  * Initialise the signal names, in the global variables signal_name_prefix, 
420  * signal_restart_name and signal_shutdown_name.
421  */
422 #define MAX_SIGNAL_NAME 30  /* Long enough for apPID_shutdown, where PID is an int */
423 char signal_name_prefix[MAX_SIGNAL_NAME];
424 char signal_restart_name[MAX_SIGNAL_NAME]; 
425 char signal_shutdown_name[MAX_SIGNAL_NAME];
426 void setup_signal_names(char *prefix)
427 {
428     apr_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);    
429     apr_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name), 
430         "%s_shutdown", signal_name_prefix);    
431     apr_snprintf(signal_restart_name, sizeof(signal_restart_name), 
432         "%s_restart", signal_name_prefix);    
433 }
434
435 static int volatile is_graceful = 0;
436 AP_DECLARE(int) ap_graceful_stop_signalled(void)
437 {
438     return is_graceful;
439 }
440
441 AP_DECLARE(void) ap_signal_parent(ap_signal_parent_e type)
442 {
443     HANDLE e;
444     char *signal_name;
445     
446     if (one_process) {
447         return;
448     }
449
450     switch(type) {
451        case SIGNAL_PARENT_SHUTDOWN: 
452        {
453            signal_name = signal_shutdown_name; 
454            break;
455        }
456        /* This MPM supports only graceful restarts right now */
457        case SIGNAL_PARENT_RESTART: 
458        case SIGNAL_PARENT_RESTART_GRACEFUL:
459        {
460            signal_name = signal_restart_name;     
461            is_graceful = 1;
462            break;
463        }
464        default: 
465            return;
466     }
467
468     e = OpenEvent(EVENT_MODIFY_STATE, FALSE, signal_name);
469     if (!e) {
470         /* Um, problem, can't signal the parent, which means we can't
471          * signal ourselves to die. Ignore for now...
472          */
473         ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf,
474                      "OpenEvent on %s event", signal_name);
475         return;
476     }
477     if (SetEvent(e) == 0) {
478         /* Same problem as above */
479         ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf,
480                      "SetEvent on %s event", signal_name);
481         CloseHandle(e);
482         return;
483     }
484     CloseHandle(e);
485 }
486
487 /* set_listeners_noninheritable()
488  * Make the listening socket handles noninheritable by processes
489  * started out of this process.
490  */
491 static int set_listeners_noninheritable(apr_pool_t *p) 
492 {
493     ap_listen_rec *lr;
494     HANDLE dup;
495     SOCKET nsd;
496     HANDLE hProcess = GetCurrentProcess();
497
498     for (lr = ap_listeners; lr; lr = lr->next) {
499         apr_os_sock_get(&nsd,lr->sd);
500         if (!DuplicateHandle(hProcess, (HANDLE) nsd, hProcess, &dup, 
501                              0, FALSE, DUPLICATE_SAME_ACCESS)) {
502             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), ap_server_conf,
503                          "set_listeners_noninheritable: DuplicateHandle failed.");
504         }
505         else {
506             closesocket(nsd);
507             nsd = (SOCKET) dup;
508             apr_os_sock_put(&lr->sd, &nsd, p);
509         }
510     }
511
512     if (my_pid == parent_pid) {
513         ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
514                      "Parent: Marked listeners as not inheritable.");
515     } else {
516         ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
517                      "Child %d: Marked listeners as not inheritable.", my_pid);
518     }
519     return 1;
520 }
521
522 /*
523  * find_ready_listener()
524  * Only used by Win9* and should go away when the win9*_accept() function is 
525  * reimplemented using apr_poll().
526  */
527 static ap_listen_rec *head_listener;
528 static APR_INLINE ap_listen_rec *find_ready_listener(fd_set * main_fds)
529 {
530     ap_listen_rec *lr;
531     SOCKET nsd;
532
533     for (lr = head_listener; lr ; lr = lr->next) {
534         apr_os_sock_get(&nsd, lr->sd);
535         if (FD_ISSET(nsd, main_fds)) {
536             head_listener = lr->next;
537             if (head_listener == NULL)
538                 head_listener = ap_listeners;
539
540             return (lr);
541         }
542     }
543     return NULL;
544 }
545
546 /*
547  *
548  */
549 void get_handles_from_parent(server_rec *s)
550 {
551     HANDLE pipe;
552     HANDLE hScore;
553     DWORD BytesRead;
554     void *sb_shared;
555     apr_status_t rv;
556     
557     pipe = GetStdHandle(STD_INPUT_HANDLE);
558     if (!ReadFile(pipe, &exit_event, sizeof(HANDLE),
559                   &BytesRead, (LPOVERLAPPED) NULL)
560         || (BytesRead != sizeof(HANDLE))) {
561         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
562                      "Child %d: Unable to retrieve the exit event from the parent", my_pid);
563         exit(APEXIT_CHILDINIT);
564     }
565
566     if (!ReadFile(pipe, &hScore, sizeof(hScore),
567                   &BytesRead, (LPOVERLAPPED) NULL)
568         || (BytesRead != sizeof(hScore))) {
569         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
570                      "Child %d: Unable to retrieve the scoreboard from the parent", my_pid);
571         exit(APEXIT_CHILDINIT);
572     }
573
574     if ((rv = apr_os_shm_put(&ap_scoreboard_shm, &hScore, s->process->pool)) 
575             != APR_SUCCESS) {
576         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
577                      "Child %d: Unable to access the scoreboard from the parent", my_pid);
578         exit(APEXIT_CHILDINIT);
579     }
580
581     rv = ap_reopen_scoreboard(s->process->pool, &ap_scoreboard_shm, 1);
582     if (rv || !(sb_shared = apr_shm_baseaddr_get(ap_scoreboard_shm))) {
583         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, 
584                      "Child %d: Unable to reopen the scoreboard from the parent", my_pid);
585         exit(APEXIT_CHILDINIT);
586     }
587     ap_init_scoreboard(sb_shared);
588
589     ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
590                  "Child %d: Retrieved our scoreboard from the parent.", my_pid);
591 }
592
593 /* 
594  * get_listeners_from_parent()
595  * The listen sockets are opened in the parent. This function, which runs
596  * exclusively in the child process, receives them from the parent and
597  * makes them availeble in the child.
598  */
599 void get_listeners_from_parent(server_rec *s)
600 {
601     WSAPROTOCOL_INFO WSAProtocolInfo;
602     HANDLE pipe;
603     ap_listen_rec *lr;
604     DWORD BytesRead;
605     int lcnt = 0;
606     SOCKET nsd;
607
608     /* Set up a default listener if necessary */
609     if (ap_listeners == NULL) {
610         ap_listen_rec *lr;
611         lr = apr_palloc(s->process->pool, sizeof(ap_listen_rec));
612         lr->sd = NULL;
613         lr->next = ap_listeners;
614         ap_listeners = lr;
615     }
616
617     /* Open the pipe to the parent process to receive the inherited socket
618      * data. The sockets have been set to listening in the parent process.
619      */
620     pipe = GetStdHandle(STD_INPUT_HANDLE);
621
622     for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) {
623         if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO), 
624                       &BytesRead, (LPOVERLAPPED) NULL)) {
625             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
626                          "setup_inherited_listeners: Unable to read socket data from parent");
627             exit(APEXIT_CHILDINIT);
628         }
629         nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
630                         &WSAProtocolInfo, 0, 0);
631         if (nsd == INVALID_SOCKET) {
632             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf,
633                          "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
634             exit(APEXIT_CHILDINIT);
635         }
636         apr_os_sock_put(&lr->sd, &nsd, s->process->pool);
637     }
638
639     ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
640                  "Child %d: retrieved %d listeners from parent", my_pid, lcnt);
641
642     if (!set_listeners_noninheritable(s->process->pool)) {
643         exit(APEXIT_CHILDINIT);
644     }
645 }
646
647
648 /* Windows 9x specific code...
649  * Accept processing for on Windows 95/98 uses a producer/consumer queue 
650  * model. A single thread accepts connections and queues the accepted socket 
651  * to the accept queue for consumption by a pool of worker threads.
652  *
653  * win9x_accept()
654  *    The accept threads runs this function, which accepts connections off 
655  *    the network and calls add_job() to queue jobs to the accept_queue.
656  * add_job()/remove_job()
657  *    Add or remove an accepted socket from the list of sockets 
658  *    connected to clients. allowed_globals.jobmutex protects
659  *    against multiple concurrent access to the linked list of jobs.
660  * win9x_get_connection()
661  *    Calls remove_job() to pull a job from the accept queue. All the worker 
662  *    threads block on remove_job.
663  */
664
665 typedef struct joblist_s {
666     struct joblist_s *next;
667     int sock;
668 } joblist;
669
670 typedef struct globals_s {
671     HANDLE jobsemaphore;
672     joblist *jobhead;
673     joblist *jobtail;
674     apr_thread_mutex_t *jobmutex;
675     int jobcount;
676 } globals;
677
678 globals allowed_globals = {NULL, NULL, NULL, NULL, 0};
679 #define MAX_SELECT_ERRORS 100
680
681 static void add_job(int sock)
682 {
683     joblist *new_job;
684
685     new_job = (joblist *) malloc(sizeof(joblist));
686     if (new_job == NULL) {
687         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
688                      "Ouch!  Out of memory in add_job()!");
689         return;
690     }
691     new_job->next = NULL;
692     new_job->sock = sock;
693
694     apr_thread_mutex_lock(allowed_globals.jobmutex);
695
696     if (allowed_globals.jobtail != NULL)
697         allowed_globals.jobtail->next = new_job;
698     allowed_globals.jobtail = new_job;
699     if (!allowed_globals.jobhead)
700         allowed_globals.jobhead = new_job;
701     allowed_globals.jobcount++;
702     ReleaseSemaphore(allowed_globals.jobsemaphore, 1, NULL);
703
704     apr_thread_mutex_unlock(allowed_globals.jobmutex);
705 }
706
707 static int remove_job(void)
708 {
709     joblist *job;
710     int sock;
711
712     WaitForSingleObject(allowed_globals.jobsemaphore, INFINITE);
713     apr_thread_mutex_lock(allowed_globals.jobmutex);
714
715     if (shutdown_in_progress && !allowed_globals.jobhead) {
716         apr_thread_mutex_unlock(allowed_globals.jobmutex);
717         return (-1);
718     }
719     job = allowed_globals.jobhead;
720     ap_assert(job);
721     allowed_globals.jobhead = job->next;
722     if (allowed_globals.jobhead == NULL)
723         allowed_globals.jobtail = NULL;
724     apr_thread_mutex_unlock(allowed_globals.jobmutex);
725     sock = job->sock;
726     free(job);
727
728     return (sock);
729 }
730
731 static void win9x_accept(void * dummy)
732 {
733     struct timeval tv;
734     fd_set main_fds;
735     int wait_time = 1;
736     int csd;
737     SOCKET nsd = INVALID_SOCKET;
738     struct sockaddr_in sa_client;
739     int count_select_errors = 0;
740     int rc;
741     int clen;
742     ap_listen_rec *lr;
743     struct fd_set listenfds;
744     SOCKET listenmaxfd = INVALID_SOCKET;
745
746     /* Setup the listeners 
747      * ToDo: Use apr_poll()
748      */
749     FD_ZERO(&listenfds);
750     for (lr = ap_listeners; lr; lr = lr->next) {
751         if (lr->sd != NULL) {
752             apr_os_sock_get(&nsd, lr->sd);
753             FD_SET(nsd, &listenfds);
754             if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
755                 listenmaxfd = nsd;
756             }
757         }
758     }
759     head_listener = ap_listeners;
760
761     while (!shutdown_in_progress) {
762         tv.tv_sec = wait_time;
763         tv.tv_usec = 0;
764         memcpy(&main_fds, &listenfds, sizeof(fd_set));
765
766         rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
767
768         if (rc == 0 || (rc == SOCKET_ERROR && APR_STATUS_IS_EINTR(apr_get_netos_error()))) {
769             count_select_errors = 0;    /* reset count of errors */            
770             continue;
771         }
772         else if (rc == SOCKET_ERROR) {
773             /* A "real" error occurred, log it and increment the count of
774              * select errors. This count is used to ensure we don't go into
775              * a busy loop of continuous errors.
776              */
777             ap_log_error(APLOG_MARK, APLOG_INFO, apr_get_netos_error(), ap_server_conf, 
778                          "select failed with error %d", apr_get_netos_error());
779             count_select_errors++;
780             if (count_select_errors > MAX_SELECT_ERRORS) {
781                 shutdown_in_progress = 1;
782                 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), ap_server_conf,
783                              "Too many errors in select loop. Child process exiting.");
784                 break;
785             }
786         } else {
787             ap_listen_rec *lr;
788
789             lr = find_ready_listener(&main_fds);
790             if (lr != NULL) {
791                 /* fetch the native socket descriptor */
792                 apr_os_sock_get(&nsd, lr->sd);
793             }
794         }
795
796         do {
797             clen = sizeof(sa_client);
798             csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
799             if (csd == INVALID_SOCKET) {
800                 csd = -1;
801             }
802         } while (csd < 0 && APR_STATUS_IS_EINTR(apr_get_netos_error()));
803
804         if (csd < 0) {
805             if (APR_STATUS_IS_ECONNABORTED(apr_get_netos_error())) {
806                 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), ap_server_conf,
807                             "accept: (client socket)");
808             }
809         }
810         else {
811             add_job(csd);
812         }
813     }
814     SetEvent(exit_event);
815 }
816
817 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
818 {
819     int len;
820
821     if (context == NULL) {
822         /* allocate the completion context and the transaction pool */
823         context = apr_pcalloc(pconf, sizeof(COMP_CONTEXT));
824         apr_pool_create(&context->ptrans, pconf);
825     }
826     
827
828     while (1) {
829         apr_pool_clear(context->ptrans);        
830         context->accept_socket = remove_job();
831         if (context->accept_socket == -1) {
832             return NULL;
833         }
834         len = sizeof(struct sockaddr);
835         context->sa_server = apr_palloc(context->ptrans, len);
836         if (getsockname(context->accept_socket, 
837                         context->sa_server, &len)== SOCKET_ERROR) {
838             ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), ap_server_conf, 
839                          "getsockname failed");
840             continue;
841         }
842         len = sizeof(struct sockaddr);
843         context->sa_client = apr_palloc(context->ptrans, len);
844         if ((getpeername(context->accept_socket,
845                          context->sa_client, &len)) == SOCKET_ERROR) {
846             ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), ap_server_conf, 
847                          "getpeername failed");
848             memset(&context->sa_client, '\0', sizeof(context->sa_client));
849         }
850
851         /* do we NEED_DUPPED_CSD ?? */
852         
853         return context;
854     }
855 }
856 /* Windows NT/2000 specific code...
857  * Accept processing for on Windows NT uses a producer/consumer queue 
858  * model. An accept thread accepts connections off the network then issues
859  * PostQueuedCompletionStatus() to awake a thread blocked on the ThreadDispatch 
860  * IOCompletionPort.
861  *
862  * winnt_accept()
863  *    One or more accept threads run in this function, each of which accepts 
864  *    connections off the network and calls PostQueuedCompletionStatus() to
865  *    queue an io completion packet to the ThreadDispatch IOCompletionPort.
866  * winnt_get_connection()
867  *    Worker threads block on the ThreadDispatch IOCompletionPort awaiting 
868  *    connections to service.
869  */
870 static void winnt_accept(void *listen_socket) 
871 {
872
873     PCOMP_CONTEXT pCompContext;
874     DWORD BytesRead;
875     SOCKET nlsd;
876     int lasterror;
877
878     nlsd = (SOCKET) listen_socket;
879
880     while (!shutdown_in_progress) {
881         pCompContext = mpm_get_completion_context();
882         if (!pCompContext) {
883             /* Hopefully whatever is preventing us from getting a 
884              * completion context is a temporary resource constraint.
885              */
886             Sleep(750);
887             continue;
888         }
889
890     again:            
891         /* Create and initialize the accept socket */
892         if (pCompContext->accept_socket == INVALID_SOCKET) {
893             pCompContext->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
894             if (pCompContext->accept_socket == INVALID_SOCKET) {
895                 /* Hopefully another temporary condition. Be graceful. */
896                 ap_log_error(APLOG_MARK,APLOG_WARNING, apr_get_netos_error(), ap_server_conf,
897                              "winnt_accept: Failed to allocate an accept socket. "
898                              "Temporary resource constraint? Try again.");
899                 Sleep(500);
900                 goto again;
901             }
902         }
903
904         /* AcceptEx on the completion context. The completion context will be 
905          * signaled when a connection is accepted. 
906          */
907         if (!AcceptEx(nlsd, pCompContext->accept_socket,
908                       pCompContext->buff,
909                       0,
910                       PADDED_ADDR_SIZE, 
911                       PADDED_ADDR_SIZE,
912                       &BytesRead,
913                       &pCompContext->Overlapped)) {
914             lasterror = apr_get_netos_error();
915             if (lasterror == APR_FROM_OS_ERROR(WSAEINVAL)) {
916                 /* Hack alert. Occasionally, TransmitFile will not recycle the 
917                  * accept socket (usually when the client disconnects early). 
918                  * Get a new socket and try the call again.
919                  */
920                 closesocket(pCompContext->accept_socket);
921                 pCompContext->accept_socket = INVALID_SOCKET;
922                 ap_log_error(APLOG_MARK, APLOG_DEBUG, lasterror, ap_server_conf,
923                        "winnt_accept: AcceptEx failed due to early client "
924                        "disconnect. Reallocate the accept socket and try again.");
925                 if (shutdown_in_progress)
926                     break;
927                 else
928                     goto again;
929             }
930             else if (lasterror != APR_FROM_OS_ERROR(ERROR_IO_PENDING)) {
931                 ap_log_error(APLOG_MARK,APLOG_ERR, lasterror, ap_server_conf,
932                              "winnt_accept: AcceptEx failed. Attempting to recover.");
933                 closesocket(pCompContext->accept_socket);
934                 pCompContext->accept_socket = INVALID_SOCKET;
935                 Sleep(500);
936                 goto again;
937             }
938
939             /* Wait for pending i/o */
940             WaitForSingleObject(pCompContext->Overlapped.hEvent, INFINITE);
941         }
942
943         /* Inherit the listen socket settings. Required for 
944          * shutdown() to work 
945          */
946         if (setsockopt(pCompContext->accept_socket, SOL_SOCKET,
947                        SO_UPDATE_ACCEPT_CONTEXT, (char *)&nlsd,
948                        sizeof(nlsd))) {
949             ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), ap_server_conf,
950                          "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
951             /* Not a failure condition. Keep running. */
952         }
953
954         /* Get the local & remote address */
955         GetAcceptExSockaddrs(pCompContext->buff,
956                              0,
957                              PADDED_ADDR_SIZE,
958                              PADDED_ADDR_SIZE,
959                              &pCompContext->sa_server,
960                              &pCompContext->sa_server_len,
961                              &pCompContext->sa_client,
962                              &pCompContext->sa_client_len);
963
964         /* When a connection is received, send an io completion notification to
965          * the ThreadDispatchIOCP. This function could be replaced by
966          * mpm_post_completion_context(), but why do an extra function call...
967          */
968         PostQueuedCompletionStatus(ThreadDispatchIOCP, 0, IOCP_CONNECTION_ACCEPTED,
969                                    &pCompContext->Overlapped);
970     }
971
972     if (!shutdown_in_progress) {
973         /* Yow, hit an irrecoverable error! Tell the child to die. */
974         SetEvent(exit_event);
975     }
976 }
977 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT pCompContext)
978 {
979     int rc;
980     DWORD BytesRead;
981     DWORD CompKey;
982     LPOVERLAPPED pol;
983
984     mpm_recycle_completion_context(pCompContext);
985
986     g_blocked_threads++;        
987     while (1) {
988         if (workers_may_exit) {
989             g_blocked_threads--;
990             return NULL;
991         }
992         rc = GetQueuedCompletionStatus(ThreadDispatchIOCP, &BytesRead, &CompKey,
993                                        &pol, INFINITE);
994         if (!rc) {
995             rc = apr_get_os_error();
996             ap_log_error(APLOG_MARK,APLOG_DEBUG, rc, ap_server_conf,
997                              "Child %d: GetQueuedComplationStatus returned %d", my_pid, rc);
998             continue;
999         }
1000
1001         switch (CompKey) {
1002         case IOCP_CONNECTION_ACCEPTED:
1003             pCompContext = CONTAINING_RECORD(pol, COMP_CONTEXT, Overlapped);
1004             break;
1005         case IOCP_SHUTDOWN:
1006             g_blocked_threads--;
1007             return NULL;
1008         default:
1009             g_blocked_threads--;
1010             return NULL;
1011         }
1012         break;
1013     }
1014
1015     g_blocked_threads--;    
1016
1017     if ((rc = apr_pool_create(&pCompContext->ptrans, pconf)) != APR_SUCCESS) {
1018         ap_log_error(APLOG_MARK,APLOG_DEBUG, rc, ap_server_conf,
1019                      "Child %d: apr_pool_create failed with rc %d", my_pid, rc);
1020     }
1021
1022     return pCompContext;
1023 }
1024
1025 /*
1026  * worker_main()
1027  * Main entry point for the worker threads. Worker threads block in 
1028  * win*_get_connection() awaiting a connection to service.
1029  */
1030 static void worker_main(long thread_num)
1031 {
1032     static int requests_this_child = 0;
1033     PCOMP_CONTEXT context = NULL;
1034     apr_os_sock_info_t sockinfo;
1035     ap_sb_handle_t *sbh;
1036
1037     while (1) {
1038         conn_rec *c;
1039         apr_int32_t disconnected;
1040
1041         ap_update_child_status_from_indexes(0, thread_num, SERVER_READY, 
1042                                             (request_rec *) NULL);
1043
1044
1045         /* Grab a connection off the network */
1046         if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1047             context = win9x_get_connection(context);
1048         }
1049         else {
1050             context = winnt_get_connection(context);
1051         }
1052         if (!context) {
1053             /* Time for the thread to exit */
1054             break;
1055         }
1056
1057         /* Have we hit MaxRequestPerChild connections? */
1058         if (ap_max_requests_per_child) {
1059             requests_this_child++;
1060             if (requests_this_child > ap_max_requests_per_child) {
1061                 SetEvent(max_requests_per_child_event);
1062             }
1063         }
1064
1065         sockinfo.os_sock = &context->accept_socket;
1066         sockinfo.local   = context->sa_server;
1067         sockinfo.remote  = context->sa_client;
1068         sockinfo.family  = APR_INET;
1069         sockinfo.type    = SOCK_STREAM;
1070         /* ### is this correct?  Shouldn't be inheritable (at this point) */
1071         apr_os_sock_make(&context->sock, &sockinfo, context->ptrans);
1072
1073         ap_create_sb_handle(&sbh, context->ptrans, 0, thread_num);
1074         c = ap_run_create_connection(context->ptrans, ap_server_conf, context->sock,
1075                                      thread_num, sbh);
1076
1077         if (c) {
1078             ap_process_connection(c, context->sock);
1079             apr_getsocketopt(context->sock, APR_SO_DISCONNECTED, &disconnected);
1080             if (!disconnected) {
1081                 context->accept_socket = INVALID_SOCKET;
1082                 ap_lingering_close(c);
1083             }
1084         }
1085         else {
1086             /* ap_run_create_connection closes the socket on failure */
1087             context->accept_socket = INVALID_SOCKET;
1088         }
1089     }
1090
1091     ap_update_child_status_from_indexes(0, thread_num, SERVER_DEAD, 
1092                                         (request_rec *) NULL);
1093
1094     ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
1095                  "Child %d: Thread exiting.", my_pid);
1096 }
1097
1098 static void cleanup_thread(thread *handles, int *thread_cnt, int thread_to_clean)
1099 {
1100     int i;
1101
1102     CloseHandle(handles[thread_to_clean]);
1103     for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1104         handles[i] = handles[i + 1];
1105     (*thread_cnt)--;
1106 }
1107
1108 /*
1109  * child_main() 
1110  * Entry point for the main control thread for the child process. 
1111  * This thread creates the accept thread, worker threads and
1112  * monitors the child process for maintenance and shutdown
1113  * events.
1114  */
1115 static void child_main()
1116 {
1117     apr_status_t status;
1118     ap_listen_rec *lr;
1119     HANDLE child_events[2];
1120     int nthreads = ap_threads_per_child;
1121     int tid;
1122     thread *child_handles;
1123     int rv;
1124     time_t end_time;
1125     int i;
1126     int cld;
1127
1128     apr_pool_create(&pchild, pconf);
1129
1130     ap_run_child_init(pchild, ap_server_conf);
1131     
1132     /* Initialize the child_events */
1133     max_requests_per_child_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1134     if (!max_requests_per_child_event) {
1135         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1136                      "Child %d: Failed to create a max_requests event.", my_pid);
1137         exit(APEXIT_CHILDINIT);
1138     }
1139     child_events[0] = exit_event;
1140     child_events[1] = max_requests_per_child_event;
1141
1142     allowed_globals.jobsemaphore = CreateSemaphore(NULL, 0, 1000000, NULL);
1143     apr_thread_mutex_create(&allowed_globals.jobmutex, 
1144                             APR_THREAD_MUTEX_DEFAULT, pchild);
1145
1146     /*
1147      * Wait until we have permission to start accepting connections.
1148      * start_mutex is used to ensure that only one child ever
1149      * goes into the listen/accept loop at once.
1150      */
1151     status = apr_proc_mutex_lock(start_mutex);
1152     if (status != APR_SUCCESS) {
1153         ap_log_error(APLOG_MARK,APLOG_ERR, status, ap_server_conf,
1154                      "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1155         exit(APEXIT_CHILDINIT);
1156     }
1157     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, ap_server_conf, 
1158                  "Child %d: Acquired the start mutex.", my_pid);
1159
1160     /*
1161      * Create the worker thread dispatch IOCompletionPort
1162      * on Windows NT/2000
1163      */
1164     if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1165         /* Create the worker thread dispatch IOCP */
1166         ThreadDispatchIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1167                                                     NULL,
1168                                                     0,
1169                                                     0); /* CONCURRENT ACTIVE THREADS */
1170         apr_thread_mutex_create(&qlock, APR_THREAD_MUTEX_DEFAULT, pchild);
1171     }
1172
1173     /* 
1174      * Create the pool of worker threads
1175      */
1176     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, ap_server_conf, 
1177                  "Child %d: Starting %d worker threads.", my_pid, nthreads);
1178     child_handles = (thread) alloca(nthreads * sizeof(int));
1179     for (i = 0; i < nthreads; i++) {
1180         ap_update_child_status_from_indexes(0, i, SERVER_STARTING, 
1181                                             (request_rec *) NULL);
1182         child_handles[i] = (thread) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1183                                                    (void *) i, 0, &tid);
1184     }
1185
1186     /* 
1187      * Start the accept thread
1188      */
1189     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1190         _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) win9x_accept,
1191                        (void *) i, 0, &tid);
1192     } else {
1193         /* Start an accept thread per listener */
1194         SOCKET nlsd; /* native listening sock descriptor */
1195         ap_listen_rec *lr;
1196         for (lr = ap_listeners; lr; lr = lr->next) {
1197             if (lr->sd != NULL) {
1198                 apr_os_sock_get(&nlsd, lr->sd);
1199                 _beginthreadex(NULL, 1000, (LPTHREAD_START_ROUTINE) winnt_accept,
1200                                (void *) nlsd, 0, &tid);
1201             }
1202         }
1203     }
1204
1205     /* Wait for one of three events:
1206      * exit_event: 
1207      *    The exit_event is signaled by the parent process to notify 
1208      *    the child that it is time to exit.
1209      *
1210      * max_requests_per_child_event: 
1211      *    This event is signaled by the worker threads to indicate that
1212      *    the process has handled MaxRequestsPerChild connections.
1213      *
1214      * TIMEOUT:
1215      *    To do periodic maintenance on the server (check for thread exits,
1216      *    number of completion contexts, etc.)
1217      */
1218     while (1) {
1219         rv = WaitForMultipleObjects(2, (HANDLE *) child_events, FALSE, 1000);
1220         cld = rv - WAIT_OBJECT_0;
1221         if (rv == WAIT_FAILED) {
1222             /* Something serious is wrong */
1223             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1224                          "Child %d: WAIT_FAILED -- shutting down server");
1225             break;
1226         }
1227         else if (rv == WAIT_TIMEOUT) {
1228             apr_proc_other_child_check();
1229         }
1230         else if (cld == 0) {
1231             /* Exit event was signaled */
1232             ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
1233                          "Child %d: Exit event signaled. Child process is ending.", my_pid);
1234             break;
1235         }
1236         else {
1237             /* MaxRequestsPerChild event set by the worker threads.
1238              * Signal the parent to restart
1239              */
1240             ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
1241                          "Child %d: Process exiting because it reached "
1242                          "MaxRequestsPerChild. Signaling the parent to "
1243                          "restart a new child process.", my_pid);
1244             ap_signal_parent(SIGNAL_PARENT_RESTART);
1245             break;
1246         }
1247     }
1248
1249     /* Setting is_graceful will cause keep-alive connections to be closed
1250      * rather than block on the next network read.
1251      */
1252     is_graceful = 1;
1253
1254     /* Setting shutdown_in_progress prevents new connections from
1255      * being accepted but allows the worker threads to continue
1256      * handling connections that have already been accepted.
1257      */
1258     shutdown_in_progress = 1;
1259
1260     /* Close the listening sockets. */
1261     for (lr = ap_listeners; lr ; lr = lr->next) {
1262         apr_socket_close(lr->sd);
1263     }
1264     Sleep(1000);
1265
1266     /* Release the start_mutex to let the new process (in the restart
1267      * scenario) a chance to begin accepting and servicing requests 
1268      */
1269     rv = apr_proc_mutex_unlock(start_mutex);
1270     if (rv == APR_SUCCESS) {
1271         ap_log_error(APLOG_MARK,APLOG_INFO | APLOG_NOERRNO, rv, ap_server_conf, 
1272                      "Child %d: Released the start mutex", my_pid);
1273     }
1274     else {
1275         ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf, 
1276                      "Child %d: Failure releasing the start mutex", my_pid);
1277     }
1278
1279     /* Tell the worker threads they may exit when done handling
1280      * a connection.
1281      */
1282     workers_may_exit = 1;
1283
1284     /* Shutdown the worker threads */
1285     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1286         for (i = 0; i < nthreads; i++) {
1287             add_job(-1);
1288         }
1289     }
1290     else { /* Windows NT/2000 */
1291         /* Post worker threads blocked on the ThreadDispatch IOCompletion port */
1292         while (g_blocked_threads > 0) {
1293             ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, ap_server_conf, 
1294                          "Child %d: %d threads blocked on the completion port", my_pid, g_blocked_threads);
1295             for (i=g_blocked_threads; i > 0; i--) {
1296                 PostQueuedCompletionStatus(ThreadDispatchIOCP, 0, IOCP_SHUTDOWN, NULL);
1297             }
1298             Sleep(1000);
1299         }
1300         /* Empty the accept queue of completion contexts */
1301         apr_thread_mutex_lock(qlock);
1302         while (qhead) {
1303             CloseHandle(qhead->Overlapped.hEvent);
1304             closesocket(qhead->accept_socket);
1305             qhead = qhead->next;
1306         }
1307         apr_thread_mutex_unlock(qlock);
1308     }
1309
1310     /* Give busy worker threads a chance to service their connections */
1311     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, ap_server_conf, 
1312                  "Child %d: Waiting for %d threads to die.", my_pid, nthreads);
1313     end_time = time(NULL) + 180;
1314     while (nthreads) {
1315         rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1316         if (rv != WAIT_TIMEOUT) {
1317             rv = rv - WAIT_OBJECT_0;
1318             ap_assert((rv >= 0) && (rv < nthreads));
1319             cleanup_thread(child_handles, &nthreads, rv);
1320             continue;
1321         }
1322         break;
1323     }
1324
1325     /* Kill remaining threads off the hard way */
1326     for (i = 0; i < nthreads; i++) {
1327         TerminateThread(child_handles[i], 1);
1328         CloseHandle(child_handles[i]);
1329     }
1330     ap_log_error(APLOG_MARK,APLOG_DEBUG, APR_SUCCESS, ap_server_conf, 
1331                  "Child %d: All worker threads have ended.", my_pid);
1332
1333     CloseHandle(allowed_globals.jobsemaphore);
1334     apr_thread_mutex_destroy(allowed_globals.jobmutex);
1335     if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS)
1336         apr_thread_mutex_destroy(qlock);
1337
1338     apr_pool_destroy(pchild);
1339     CloseHandle(exit_event);
1340 }
1341
1342 static int send_handles_to_child(apr_pool_t *p, HANDLE child_exit_event, HANDLE hProcess, HANDLE hPipeWrite)
1343 {
1344     apr_status_t rv;
1345     HANDLE hScore;
1346     HANDLE hDup;
1347     HANDLE hCurrentProcess = GetCurrentProcess();
1348     DWORD BytesWritten;
1349
1350     if (!DuplicateHandle(hCurrentProcess, child_exit_event, hProcess, &hDup,
1351                          EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, 0)) {
1352         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1353                      "Parent: Unable to duplicate the exit event handle for the child");
1354         return -1;
1355     }
1356     if (!WriteFile(hPipeWrite, &hDup, sizeof(hDup),
1357                    &BytesWritten, (LPOVERLAPPED) NULL)
1358             || (BytesWritten != sizeof(hDup))) {
1359         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1360                      "Parent: Unable to send the exit event handle to the child");
1361         return -1;
1362     }
1363
1364     if ((rv = apr_os_shm_get(&hScore, ap_scoreboard_shm)) != APR_SUCCESS) {
1365         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
1366                      "Parent: Unable to retrieve the scoreboard handle for the child");
1367         return -1;
1368     }
1369     if (!DuplicateHandle(hCurrentProcess, hScore, hProcess, &hDup,
1370                          FILE_MAP_READ | FILE_MAP_WRITE, FALSE, 0)) {
1371         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1372                      "Parent: Unable to duplicate the scoreboard handle to the child");
1373         return -1;
1374     }
1375     if (!WriteFile(hPipeWrite, &hDup, sizeof(hDup),
1376                    &BytesWritten, (LPOVERLAPPED) NULL)
1377             || (BytesWritten != sizeof(hDup))) {
1378         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1379                      "Parent: Unable to send the scoreboard handle to the child");
1380         return -1;
1381     }
1382
1383     ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
1384                  "Parent: Sent the scoreboard to the child");
1385     return 0;
1386 }
1387
1388 static int send_listeners_to_child(apr_pool_t *p, DWORD dwProcessId, HANDLE hPipeWrite)
1389 {
1390     int lcnt = 0;
1391     ap_listen_rec *lr;
1392     LPWSAPROTOCOL_INFO  lpWSAProtocolInfo;
1393     DWORD BytesWritten;
1394
1395     /* Run the chain of open sockets. For each socket, duplicate it 
1396      * for the target process then send the WSAPROTOCOL_INFO 
1397      * (returned by dup socket) to the child.
1398      */
1399     for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) {
1400         int nsd;
1401         lpWSAProtocolInfo = apr_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1402         apr_os_sock_get(&nsd,lr->sd);
1403         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
1404                      "Parent: Duplicating socket %d and sending it to child process %d", 
1405                      nsd, dwProcessId);
1406         if (WSADuplicateSocket(nsd, dwProcessId,
1407                                lpWSAProtocolInfo) == SOCKET_ERROR) {
1408             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf,
1409                          "Parent: WSADuplicateSocket failed for socket %d. Check the FAQ.", lr->sd );
1410             return -1;
1411         }
1412
1413         if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1414                        &BytesWritten,
1415                        (LPOVERLAPPED) NULL)
1416                 || BytesWritten != sizeof(WSAPROTOCOL_INFO)) {
1417             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1418                          "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1419             return -1;
1420         }
1421     }
1422
1423     ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
1424                  "Parent: Sent %d listeners to child %d", lcnt, dwProcessId);
1425     return 0;
1426 }
1427
1428 static int create_process(apr_pool_t *p, HANDLE *child_proc, HANDLE *child_exit_event)
1429 {
1430     int rv;
1431     char buf[1024];
1432     char *pCommand;
1433     char *pEnvVar;
1434     char *pEnvBlock;
1435     int i;
1436     int iEnvBlockLen;
1437     STARTUPINFO si;           /* Filled in prior to call to CreateProcess */
1438     PROCESS_INFORMATION pi;   /* filled in on call to CreateProcess */
1439     HANDLE hDup;
1440     HANDLE hPipeRead;
1441     HANDLE hPipeWrite;
1442     HANDLE hNullOutput;
1443     HANDLE hShareError;
1444     HANDLE hExitEvent;
1445     HANDLE hCurrentProcess = GetCurrentProcess();
1446     SECURITY_ATTRIBUTES sa;
1447
1448     sa.nLength = sizeof(sa);
1449     sa.bInheritHandle = TRUE;
1450     sa.lpSecurityDescriptor = NULL;
1451
1452     /* Build the command line. Should look something like this:
1453      * C:/apache/bin/apache.exe -f ap_server_confname 
1454      * First, get the path to the executable...
1455      */
1456     rv = GetModuleFileName(NULL, buf, sizeof(buf));
1457     if (rv == sizeof(buf)) {
1458         ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, ap_server_conf,
1459                      "Parent: Path to Apache process too long");
1460         return -1;
1461     } else if (rv == 0) {
1462         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1463                      "Parent: GetModuleFileName() returned NULL for current process.");
1464         return -1;
1465     }
1466
1467     /* Build the command line */
1468     pCommand = apr_psprintf(p, "\"%s\"", buf);  
1469     for (i = 1; i < ap_server_conf->process->argc; i++) {
1470         pCommand = apr_pstrcat(p, pCommand, " \"", ap_server_conf->process->argv[i], "\"", NULL);
1471     }
1472
1473     /* Create a pipe to send socket info to the child */
1474     if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1475         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1476                      "Parent: Unable to create pipe to child process.");
1477         return -1;
1478     }
1479
1480     /* Make our end of the handle non-inherited */
1481     if (DuplicateHandle(hCurrentProcess, hPipeWrite, hCurrentProcess,
1482                         &hDup, 0, FALSE, DUPLICATE_SAME_ACCESS)) {
1483         CloseHandle(hPipeWrite);
1484         hPipeWrite = hDup;
1485     }
1486     else {
1487         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1488                      "Parent: Unable to duplicate pipe to child.\n");
1489         CloseHandle(hPipeWrite);
1490         CloseHandle(hPipeRead);
1491         return -1;
1492     }
1493
1494     /* Open a null handle to soak info from the child */
1495     hNullOutput = CreateFile("nul", GENERIC_READ | GENERIC_WRITE, 
1496                              FILE_SHARE_READ | FILE_SHARE_WRITE, 
1497                              &sa, OPEN_EXISTING, 0, NULL);
1498     if (hNullOutput == INVALID_HANDLE_VALUE) {
1499         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1500                      "Parent: Unable to create null output pipe for child process.\n");
1501         CloseHandle(hPipeWrite);
1502         CloseHandle(hPipeRead);
1503         return -1;
1504     }
1505
1506     /* Child's initial stderr -> our main server error log (or, failing that, stderr) */
1507     if (ap_server_conf->error_log) { /* Is this check really necessary?*/
1508         rv = apr_os_file_get(&hShareError, ap_server_conf->error_log);
1509         if (rv == APR_SUCCESS && hShareError != INVALID_HANDLE_VALUE) {
1510             if (DuplicateHandle(hCurrentProcess, hShareError, 
1511                                 hCurrentProcess, &hDup, 
1512                                 GENERIC_WRITE, TRUE, 0)) {
1513                 hShareError = hDup;
1514             }
1515             else {
1516                 rv = apr_get_os_error();
1517             }
1518         }
1519         if (rv != APR_SUCCESS) {
1520             ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
1521                          "Parent: Unable to share error log with child.\n");
1522             CloseHandle(hPipeWrite);
1523             CloseHandle(hPipeRead);
1524             CloseHandle(hNullOutput);
1525             return -1;
1526         }
1527         else if (hShareError == INVALID_HANDLE_VALUE) {
1528             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_CRIT, 0, ap_server_conf,
1529                          "Parent: Failed to share error log with child.\n");
1530             CloseHandle(hPipeWrite);
1531             CloseHandle(hPipeRead);
1532             CloseHandle(hNullOutput);
1533             return -1;
1534         }
1535     }
1536     else {
1537         hShareError = GetStdHandle(STD_ERROR_HANDLE);
1538     }
1539
1540     /* Create the child_exit_event */
1541     hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1542     if (!hExitEvent) {
1543         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1544                      "Parent: Could not create exit event for child process");
1545         CloseHandle(hPipeWrite);
1546         CloseHandle(hPipeRead);
1547         CloseHandle(hNullOutput);
1548         if (GetStdHandle(STD_ERROR_HANDLE) != hShareError) {
1549             CloseHandle(hShareError);
1550         }
1551         return -1;
1552     }
1553     
1554     /*
1555      * Build the environment
1556      * Win32's CreateProcess call requires that the environment
1557      * be passed in an environment block, a null terminated block of
1558      * null terminated strings.
1559      */  
1560     _putenv(apr_psprintf(p,"AP_PARENT_PID=%i", parent_pid));
1561     _putenv(apr_psprintf(p,"AP_MY_GENERATION=%i", ap_my_generation));
1562
1563     i = 0;
1564     iEnvBlockLen = 1;
1565     while (_environ[i]) {
1566         iEnvBlockLen += strlen(_environ[i]) + 1;
1567         i++;
1568     }
1569     pEnvBlock = (char *)apr_pcalloc(p, iEnvBlockLen);
1570     pEnvVar = pEnvBlock;
1571     i = 0;
1572     while (_environ[i]) {
1573         strcpy(pEnvVar, _environ[i]);
1574         pEnvVar = strchr(pEnvVar, '\0') + 1;
1575         i++;
1576     }
1577     pEnvVar = '\0';
1578
1579     /* Give the read end of the pipe (hPipeRead) to the child as stdin. The 
1580      * parent will write the socket data to the child on this pipe.
1581      */
1582     memset(&si, 0, sizeof(si));
1583     memset(&pi, 0, sizeof(pi));
1584     si.cb = sizeof(si);
1585     si.dwFlags     = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1586     si.wShowWindow = SW_HIDE;
1587     si.hStdInput   = hPipeRead;
1588     si.hStdOutput  = hNullOutput;
1589     si.hStdError   = hShareError;
1590
1591     rv = CreateProcess(NULL, pCommand, NULL, NULL, 
1592                        TRUE,               /* Inherit handles */
1593                        0,                  /* Creation flags */
1594                        pEnvBlock,          /* Environment block */
1595                        NULL,
1596                        &si, &pi);
1597
1598     /* Undo everything created for the child alone
1599      */
1600     CloseHandle(pi.hThread);
1601     CloseHandle(hPipeRead);
1602     CloseHandle(hNullOutput);
1603     if (GetStdHandle(STD_ERROR_HANDLE) != hShareError) {
1604         /* Handles opened with GetStdHandle are psuedo handles
1605          * and should not be closed else bad things will happen.
1606          */
1607         CloseHandle(hShareError);
1608     }
1609     _putenv("AP_PARENT_PID=");
1610     _putenv("AP_MY_GENERATION=");
1611
1612     if (!rv) {
1613         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1614                      "Parent: Failed to create the child process.");
1615         CloseHandle(hExitEvent);
1616         CloseHandle(hPipeWrite);
1617         CloseHandle(pi.hProcess);
1618         return -1;
1619     }
1620
1621     ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
1622                  "Parent: Created child process %d", pi.dwProcessId);
1623
1624     if (send_handles_to_child(p, hExitEvent, pi.hProcess, hPipeWrite)) {
1625         /*
1626          * This error is fatal, mop up the child and move on
1627          * We toggle the child's exit event to cause this child 
1628          * to quit even as it is attempting to start.
1629          */
1630         SetEvent(hExitEvent);
1631         CloseHandle(hExitEvent);
1632         CloseHandle(hPipeWrite);
1633         CloseHandle(pi.hProcess);
1634         return -1;
1635     }
1636
1637     /* Important:
1638      * Give the child process a chance to run before dup'ing the sockets.
1639      * We have already set the listening sockets noninheritable, but if 
1640      * WSADuplicateSocket runs before the child process initializes
1641      * the listeners will be inherited anyway.
1642      *
1643      * XXX: This is badness; needs some mutex interlocking
1644      */
1645     Sleep(1000);
1646
1647     if (send_listeners_to_child(p, pi.dwProcessId, hPipeWrite)) {
1648         /*
1649          * This error is fatal, mop up the child and move on
1650          * We toggle the child's exit event to cause this child 
1651          * to quit even as it is attempting to start.
1652          */
1653         SetEvent(hExitEvent);
1654         CloseHandle(hExitEvent);
1655         CloseHandle(hPipeWrite);        
1656         CloseHandle(pi.hProcess);
1657         return -1;
1658     }
1659
1660     CloseHandle(hPipeWrite);        
1661
1662     *child_proc = pi.hProcess;
1663     *child_exit_event = hExitEvent;
1664
1665     return 0;
1666 }
1667
1668 /***********************************************************************
1669  * master_main()
1670  * master_main() runs in the parent process.  It creates the child 
1671  * process which handles HTTP requests then waits on one of three 
1672  * events:
1673  *
1674  * restart_event
1675  * -------------
1676  * The restart event causes master_main to start a new child process and
1677  * tells the old child process to exit (by setting the child_exit_event).
1678  * The restart event is set as a result of one of the following:
1679  * 1. An apache -k restart command on the command line
1680  * 2. A command received from Windows service manager which gets 
1681  *    translated into an ap_signal_parent(SIGNAL_PARENT_RESTART)
1682  *    call by code in service.c.
1683  * 3. The child process calling ap_signal_parent(SIGNAL_PARENT_RESTART)
1684  *    as a result of hitting MaxRequestsPerChild.
1685  *
1686  * shutdown_event 
1687  * --------------
1688  * The shutdown event causes master_main to tell the child process to 
1689  * exit and that the server is shutting down. The shutdown event is
1690  * set as a result of one of the following:
1691  * 1. An apache -k shutdown command on the command line
1692  * 2. A command received from Windows service manager which gets
1693  *    translated into an ap_signal_parent(SIGNAL_PARENT_SHUTDOWN)
1694  *    call by code in service.c.
1695  *
1696  * child process handle
1697  * --------------------
1698  * The child process handle will be signaled if the child process 
1699  * exits for any reason. In a normal running server, the signaling
1700  * of this event means that the child process has exited prematurely
1701  * due to a seg fault or other irrecoverable error. For server
1702  * robustness, master_main will restart the child process under this 
1703  * condtion.
1704  *
1705  * master_main uses the child_exit_event to signal the child process
1706  * to exit.
1707  **********************************************************************/
1708 #define NUM_WAIT_HANDLES 3
1709 #define CHILD_HANDLE     0
1710 #define SHUTDOWN_HANDLE  1
1711 #define RESTART_HANDLE   2
1712 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1713 {
1714     int rv, cld;
1715     int restart_pending;
1716     int shutdown_pending;
1717     HANDLE child_exit_event;
1718     HANDLE event_handles[NUM_WAIT_HANDLES];
1719
1720     restart_pending = shutdown_pending = 0;
1721
1722     event_handles[SHUTDOWN_HANDLE] = shutdown_event;
1723     event_handles[RESTART_HANDLE] = restart_event;
1724
1725     /* Create a single child process */
1726     rv = create_process(pconf, &event_handles[CHILD_HANDLE], 
1727                         &child_exit_event);
1728     if (rv < 0) 
1729     {
1730         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1731                      "master_main: create child process failed. Exiting.");
1732         shutdown_pending = 1;
1733         goto die_now;
1734     }
1735     
1736     if (!strcasecmp(signal_arg, "runservice")) {
1737         mpm_service_started();
1738     }
1739
1740     /* Wait for shutdown or restart events or for child death */
1741     rv = WaitForMultipleObjects(NUM_WAIT_HANDLES, (HANDLE *) event_handles, FALSE, INFINITE);
1742     cld = rv - WAIT_OBJECT_0;
1743     if (rv == WAIT_FAILED) {
1744         /* Something serious is wrong */
1745         ap_log_error(APLOG_MARK,APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1746                      "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1747         shutdown_pending = 1;
1748     }
1749     else if (rv == WAIT_TIMEOUT) {
1750         /* Hey, this cannot happen */
1751         ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1752                      "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1753         shutdown_pending = 1;
1754     }
1755     else if (cld == SHUTDOWN_HANDLE) {
1756         /* shutdown_event signalled */
1757         shutdown_pending = 1;
1758         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s, 
1759                      "Parent: Received shutdown signal -- Shutting down the server.");
1760         if (ResetEvent(shutdown_event) == 0) {
1761             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1762                          "ResetEvent(shutdown_event)");
1763         }
1764
1765     }
1766     else if (cld == RESTART_HANDLE) {
1767         /* Received a restart event. Prepare the restart_event to be reused 
1768          * then signal the child process to exit. 
1769          */
1770         restart_pending = 1;
1771         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, s, 
1772                      "Parent: Received restart signal -- Restarting the server.");
1773         if (ResetEvent(restart_event) == 0) {
1774             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1775                          "Parent: ResetEvent(restart_event) failed.");
1776         }
1777         if (SetEvent(child_exit_event) == 0) {
1778             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1779                          "Parent: SetEvent for child process %d failed.", 
1780                          event_handles[CHILD_HANDLE]);
1781         }
1782         /* Don't wait to verify that the child process really exits, 
1783          * just move on with the restart.
1784          */
1785         CloseHandle(event_handles[CHILD_HANDLE]);
1786         event_handles[CHILD_HANDLE] = NULL;
1787         ++ap_my_generation;
1788     }
1789     else {
1790         /* The child process exited prematurely due to a fatal error. */
1791         DWORD exitcode;
1792         if (!GetExitCodeProcess(event_handles[CHILD_HANDLE], &exitcode)) {
1793             /* HUH? We did exit, didn't we? */
1794             exitcode = APEXIT_CHILDFATAL;
1795         }
1796         if (   exitcode == APEXIT_CHILDFATAL 
1797             || exitcode == APEXIT_CHILDINIT
1798             || exitcode == APEXIT_INIT) {
1799             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, ap_server_conf, 
1800                          "Parent: child process exited with status %u -- Aborting.", exitcode);
1801         }
1802         else {
1803             restart_pending = 1;
1804             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, ap_server_conf, 
1805                          "Parent: child process exited with status %u -- Restarting.", exitcode);
1806         }
1807         CloseHandle(event_handles[CHILD_HANDLE]);
1808         event_handles[CHILD_HANDLE] = NULL;
1809         ++ap_my_generation;
1810     }
1811
1812 die_now:
1813     if (shutdown_pending) 
1814     {
1815         int timeout = 30000;  /* Timeout is milliseconds */
1816
1817         /* This shutdown is only marginally graceful. We will give the 
1818          * child a bit of time to exit gracefully. If the time expires,
1819          * the child will be wacked.
1820          */
1821         if (strcasecmp(signal_arg, "runservice")) {
1822             mpm_service_stopping();
1823         }
1824         /* Signal the child processes to exit */
1825         if (SetEvent(child_exit_event) == 0) {
1826                 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), ap_server_conf,
1827                              "Parent: SetEvent for child process %d failed", event_handles[CHILD_HANDLE]);
1828         }
1829         if (event_handles[CHILD_HANDLE]) {
1830             rv = WaitForSingleObject(event_handles[CHILD_HANDLE], timeout);
1831             if (rv == WAIT_OBJECT_0) {
1832                 ap_log_error(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO, APR_SUCCESS, ap_server_conf,
1833                              "Parent: Child process %d exited successfully.", event_handles[CHILD_HANDLE]);
1834                 CloseHandle(event_handles[CHILD_HANDLE]);
1835                 event_handles[CHILD_HANDLE] = NULL;
1836             }
1837             else {
1838                 ap_log_error(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO, APR_SUCCESS, ap_server_conf,
1839                              "Parent: Forcing termination of child process %d ", event_handles[CHILD_HANDLE]);
1840                 TerminateProcess(event_handles[CHILD_HANDLE], 1);
1841                 CloseHandle(event_handles[CHILD_HANDLE]);
1842                 event_handles[CHILD_HANDLE] = NULL;
1843             }
1844         }
1845         return 0;  /* Tell the caller we do not want to restart */
1846     }
1847
1848     return 1;      /* Tell the caller we want a restart */
1849 }
1850
1851 /* service_nt_main_fn needs to append the StartService() args 
1852  * outside of our call stack and thread as the service starts...
1853  */
1854 apr_array_header_t *mpm_new_argv;
1855
1856 /* Remember service_to_start failures to log and fail in pre_config.
1857  * Remember inst_argc and inst_argv for installing or starting the
1858  * service after we preflight the config.
1859  */
1860
1861 AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
1862 {
1863     switch(query_code){
1864         case AP_MPMQ_MAX_DAEMON_USED:
1865             *result = MAXIMUM_WAIT_OBJECTS;
1866             return APR_SUCCESS;
1867         case AP_MPMQ_IS_THREADED:
1868             *result = AP_MPMQ_STATIC;
1869             return APR_SUCCESS;
1870         case AP_MPMQ_IS_FORKED:
1871             *result = AP_MPMQ_NOT_SUPPORTED;
1872             return APR_SUCCESS;
1873         case AP_MPMQ_HARD_LIMIT_DAEMONS:
1874             *result = HARD_SERVER_LIMIT;
1875             return APR_SUCCESS;
1876         case AP_MPMQ_HARD_LIMIT_THREADS:
1877             *result = HARD_THREAD_LIMIT;
1878             return APR_SUCCESS;
1879         case AP_MPMQ_MAX_THREADS:
1880             *result = ap_threads_per_child;
1881             return APR_SUCCESS;
1882         case AP_MPMQ_MIN_SPARE_DAEMONS:
1883             *result = 0;
1884             return APR_SUCCESS;
1885         case AP_MPMQ_MIN_SPARE_THREADS:    
1886             *result = 0;
1887             return APR_SUCCESS;
1888         case AP_MPMQ_MAX_SPARE_DAEMONS:
1889             *result = 0;
1890             return APR_SUCCESS;
1891         case AP_MPMQ_MAX_SPARE_THREADS:
1892             *result = 0;
1893             return APR_SUCCESS;
1894         case AP_MPMQ_MAX_REQUESTS_DAEMON:
1895             *result = ap_max_requests_per_child;
1896             return APR_SUCCESS;
1897         case AP_MPMQ_MAX_DAEMONS:
1898             *result = 0;
1899             return APR_SUCCESS;
1900     }
1901     return APR_ENOTIMPL;
1902
1903
1904 #define SERVICE_UNSET (-1)
1905 static apr_status_t service_set = SERVICE_UNSET;
1906 static apr_status_t service_to_start_success;
1907 static int inst_argc;
1908 static const char * const *inst_argv;
1909 static char *service_name = NULL;
1910     
1911 void winnt_rewrite_args(process_rec *process) 
1912 {
1913     /* Handle the following SCM aspects in this phase:
1914      *
1915      *   -k runservice [transition for WinNT, nothing for Win9x]
1916      *   -k (!)install [error out if name is not installed]
1917      *
1918      * We can't leave this phase until we know our identity
1919      * and modify the command arguments appropriately.
1920      */
1921     apr_status_t rv;
1922     char *def_server_root;
1923     char fnbuf[MAX_PATH];
1924     char optbuf[3];
1925     const char *optarg;
1926     int fixed_args;
1927     char *pid;
1928     apr_getopt_t *opt;
1929     int running_as_service = 1;
1930
1931     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1932     GetVersionEx(&osver);
1933
1934     /* AP_PARENT_PID is only valid in the child */
1935     pid = getenv("AP_PARENT_PID");
1936     if (pid) 
1937     {
1938         /* This is the child */
1939         my_pid = GetCurrentProcessId();
1940         parent_pid = (DWORD) atol(pid);
1941
1942         /* The parent is responsible for providing the
1943          * COMPLETE ARGUMENTS REQUIRED to the child.
1944          *
1945          * No further argument parsing is needed, but
1946          * for good measure we will provide a simple
1947          * signal string for later testing.
1948          */
1949         signal_arg = "runchild";
1950         return;
1951     }
1952     
1953     /* This is the parent, we have a long way to go :-) */
1954     parent_pid = my_pid = GetCurrentProcessId();
1955     
1956     /* Rewrite process->argv[]; 
1957      *
1958      * strip out -k signal into signal_arg
1959      * strip out -n servicename and set the names
1960      * add default -d serverroot from the path of this executable
1961      * 
1962      * The end result will look like:
1963      *
1964      * The invocation command (%0)
1965      *     The -d serverroot default from the running executable
1966      *         The requested service's (-n) registry ConfigArgs
1967      *             The WinNT SCM's StartService() args
1968      */
1969     if (!GetModuleFileName(NULL, fnbuf, sizeof(fnbuf))) {
1970         rv = apr_get_os_error();
1971         ap_log_error(APLOG_MARK,APLOG_CRIT, rv, NULL, 
1972                      "Failed to get the path of Apache.exe");
1973         exit(APEXIT_INIT);
1974     }
1975     /* WARNING: There is an implict assumption here that the
1976      * executable resides in ServerRoot or ServerRoot\bin
1977      */
1978     def_server_root = (char *) apr_filename_of_pathname(fnbuf);
1979     if (def_server_root > fnbuf) {
1980         *(def_server_root - 1) = '\0';
1981         def_server_root = (char *) apr_filename_of_pathname(fnbuf);
1982         if (!strcasecmp(def_server_root, "bin"))
1983             *(def_server_root - 1) = '\0';
1984     }
1985     apr_filepath_merge(&def_server_root, NULL, fnbuf, 
1986                        APR_FILEPATH_TRUENAME, process->pool);
1987
1988     /* Use process->pool so that the rewritten argv
1989      * lasts for the lifetime of the server process,
1990      * because pconf will be destroyed after the 
1991      * initial pre-flight of the config parser.
1992      */
1993     mpm_new_argv = apr_array_make(process->pool, process->argc + 2,
1994                                   sizeof(const char *));
1995     *(const char **)apr_array_push(mpm_new_argv) = process->argv[0];
1996     *(const char **)apr_array_push(mpm_new_argv) = "-d";
1997     *(const char **)apr_array_push(mpm_new_argv) = def_server_root;
1998
1999     fixed_args = mpm_new_argv->nelts;
2000
2001     optbuf[0] = '-';
2002     optbuf[2] = '\0';
2003     apr_getopt_init(&opt, process->pool, process->argc, (char**) process->argv);
2004     opt->errfn = NULL;
2005     while ((rv = apr_getopt(opt, "n:k:iu" AP_SERVER_BASEARGS, 
2006                             optbuf + 1, &optarg)) == APR_SUCCESS) {
2007         switch (optbuf[1]) {
2008         case 'n':
2009             service_set = mpm_service_set_name(process->pool, &service_name, 
2010                                                optarg);
2011             break;
2012         case 'k':
2013             signal_arg = optarg;
2014             break;
2015         case 'i':
2016             ap_log_error(APLOG_MARK,APLOG_WARNING, 0, NULL,
2017                 "-i is deprecated.  Use -k install.");
2018             signal_arg = "install";
2019             break;
2020         case 'u':
2021             ap_log_error(APLOG_MARK,APLOG_WARNING, 0, NULL,
2022                 "-u is deprecated.  Use -k uninstall.");
2023             signal_arg = "uninstall";
2024             break;
2025         default:
2026             *(const char **)apr_array_push(mpm_new_argv) =
2027                 apr_pstrdup(process->pool, optbuf);
2028
2029             if (optarg) {
2030                 *(const char **)apr_array_push(mpm_new_argv) = optarg;
2031             }
2032             break;
2033         }
2034     }
2035     
2036     /* back up to capture the bad argument */
2037     if (rv == APR_BADCH || rv == APR_BADARG) {
2038         opt->ind--;
2039     }
2040
2041     while (opt->ind < opt->argc) {
2042         *(const char **)apr_array_push(mpm_new_argv) =
2043             apr_pstrdup(process->pool, opt->argv[opt->ind++]);
2044     }
2045
2046     /* Track the number of args actually entered by the user */
2047     inst_argc = mpm_new_argv->nelts - fixed_args;
2048
2049     /* Provide a default 'run' -k arg to simplify signal_arg tests */
2050     if (!signal_arg)
2051     {
2052         signal_arg = "run";
2053         running_as_service = 0;
2054     }
2055
2056     if (!strcasecmp(signal_arg, "runservice")) 
2057     {
2058         /* Start the NT Service _NOW_ because the WinNT SCM is 
2059          * expecting us to rapidly assume control of our own 
2060          * process, the SCM will tell us our service name, and
2061          * may have extra StartService() command arguments to
2062          * add for us.
2063          *
2064          * Any other process has a console, so we don't to begin
2065          * a Win9x service until the configuration is parsed and
2066          * any command line errors are reported.
2067          *
2068          * We hold the return value so that we can die in pre_config
2069          * after logging begins, and the failure can land in the log.
2070          */
2071         if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) {
2072             service_to_start_success = mpm_service_to_start(&service_name,
2073                                                             process->pool);
2074             if (service_to_start_success == APR_SUCCESS) {
2075                 service_set = APR_SUCCESS;
2076             }
2077         }
2078     }
2079
2080     /* Get the default for any -k option, except run */
2081     if (service_set == SERVICE_UNSET && strcasecmp(signal_arg, "run")) {
2082         service_set = mpm_service_set_name(process->pool, &service_name,
2083                                            AP_DEFAULT_SERVICE_NAME);
2084     }
2085
2086     if (!strcasecmp(signal_arg, "install")) /* -k install */
2087     {
2088         if (service_set == APR_SUCCESS) 
2089         {
2090             ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
2091                  "%s: Service is already installed.", service_name);
2092             exit(APEXIT_INIT);
2093         }
2094     }
2095     else if (running_as_service)
2096     {
2097         if (service_set == APR_SUCCESS) 
2098         {
2099             rv = mpm_merge_service_args(process->pool, mpm_new_argv, 
2100                                         fixed_args);
2101             if (rv == APR_SUCCESS) {
2102                 ap_log_error(APLOG_MARK,APLOG_NOERRNO|APLOG_INFO, 0, NULL,
2103                              "Using ConfigArgs of the installed service "
2104                              "\"%s\".", service_name);
2105             }
2106             else  {
2107                 ap_log_error(APLOG_MARK,APLOG_WARNING, rv, NULL,
2108                              "No installed ConfigArgs for the service "
2109                              "\"%s\", using Apache defaults.", service_name);
2110             }
2111         }
2112         else
2113         {
2114             ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL,
2115                  "No installed service named \"%s\".", service_name);
2116             exit(APEXIT_INIT);
2117         }
2118     }
2119     if (strcasecmp(signal_arg, "install") && service_set && service_set != SERVICE_UNSET) 
2120     {
2121         ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL,
2122              "No installed service named \"%s\".", service_name);
2123         exit(APEXIT_INIT);
2124     }
2125     
2126     /* Track the args actually entered by the user.
2127      * These will be used for the -k install parameters, as well as
2128      * for the -k start service override arguments.
2129      */
2130     inst_argv = (const char * const *)mpm_new_argv->elts
2131         + mpm_new_argv->nelts - inst_argc;
2132
2133     process->argc = mpm_new_argv->nelts; 
2134     process->argv = (const char * const *) mpm_new_argv->elts;
2135 }
2136
2137
2138 static int winnt_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp) 
2139 {
2140     /* Handle the following SCM aspects in this phase:
2141      *
2142      *   -k runservice [WinNT errors logged from rewrite_args]
2143      *   -k uninstall
2144      *   -k stop
2145      *   -k shutdown (same as -k stop). Maintained for backward compatability.
2146      *
2147      * in these cases we -don't- care if httpd.conf has config errors!
2148      */
2149     apr_status_t rv;
2150
2151     if (ap_exists_config_define("ONE_PROCESS") ||
2152         ap_exists_config_define("DEBUG"))
2153         one_process = -1;
2154
2155     if (!strcasecmp(signal_arg, "runservice")
2156             && (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
2157             && (service_to_start_success != APR_SUCCESS)) {
2158         ap_log_error(APLOG_MARK,APLOG_CRIT, service_to_start_success, NULL, 
2159                      "%s: Unable to start the service manager.",
2160                      service_name);
2161         exit(APEXIT_INIT);
2162     }
2163
2164     if (!strcasecmp(signal_arg, "uninstall")) {
2165         rv = mpm_service_uninstall();
2166         exit(rv);
2167     }
2168
2169     if ((!strcasecmp(signal_arg, "stop")) || 
2170         (!strcasecmp(signal_arg, "shutdown"))) {
2171         mpm_signal_service(ptemp, 0);
2172         exit(0);
2173     }
2174
2175     ap_listen_pre_config();
2176     ap_threads_per_child = DEFAULT_START_THREAD;
2177     ap_pid_fname = DEFAULT_PIDLOG;
2178     ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
2179
2180     apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
2181
2182     return OK;
2183 }
2184
2185 static int winnt_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec* server)
2186 {
2187     static int restart_num = 0;
2188     apr_status_t rv = 0;
2189
2190     ap_server_conf = server;
2191     
2192     /* Handle the following SCM aspects in this phase:
2193      *
2194      *   -k install
2195      *   -k start
2196      *   -k restart
2197      *   -k runservice [Win95, only once - after we parsed the config]
2198      *
2199      * because all of these signals are useful _only_ if there
2200      * is a valid conf\httpd.conf environment to start.
2201      *
2202      * We reached this phase by avoiding errors that would cause
2203      * these options to fail unexpectedly in another process.
2204      */
2205
2206     if (!strcasecmp(signal_arg, "install")) {
2207         rv = mpm_service_install(ptemp, inst_argc, inst_argv);
2208         exit (rv);
2209     }
2210
2211     if (!strcasecmp(signal_arg, "start")) {
2212         ap_listen_rec *lr;
2213
2214         /* Close the listening sockets. */
2215         for (lr = ap_listeners; lr; lr = lr->next) {
2216             apr_socket_close(lr->sd);
2217             lr->active = 0;
2218         }
2219         rv = mpm_service_start(ptemp, inst_argc, inst_argv);
2220         exit (rv);
2221     }
2222
2223     if (!strcasecmp(signal_arg, "restart")) {
2224         mpm_signal_service(ptemp, 1);
2225         exit (rv);
2226     }
2227
2228     if (parent_pid == my_pid) 
2229     {
2230         if (restart_num++ == 1) 
2231         {
2232             /* This code should be run once in the parent and not run
2233              * across a restart
2234              */
2235             PSECURITY_ATTRIBUTES sa = GetNullACL();  /* returns NULL if invalid (Win95?) */
2236             setup_signal_names(apr_psprintf(pconf,"ap%d", parent_pid));
2237
2238             ap_log_pid(pconf, ap_pid_fname);
2239             
2240             /* Create shutdown event, apPID_shutdown, where PID is the parent 
2241              * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
2242              */
2243             shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
2244             if (!shutdown_event) {
2245                 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
2246                              "Parent: Cannot create shutdown event %s", signal_shutdown_name);
2247                 CleanNullACL((void *)sa);
2248                 return HTTP_INTERNAL_SERVER_ERROR;
2249             }
2250
2251             /* Create restart event, apPID_restart, where PID is the parent 
2252              * Apache process ID. Restart is signaled by 'apache -k restart'.
2253              */
2254             restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
2255             if (!restart_event) {
2256                 CloseHandle(shutdown_event);
2257                 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
2258                              "Parent: Cannot create restart event %s", signal_restart_name);
2259                 CleanNullACL((void *)sa);
2260                 return HTTP_INTERNAL_SERVER_ERROR;
2261             }
2262             CleanNullACL((void *)sa);
2263
2264             /* Now that we are flying at 15000 feet... 
2265              * wipe out the Win95 service console,
2266              * signal the SCM the WinNT service started, or
2267              * if not a service, setup console handlers instead.
2268              */
2269             if (!strcasecmp(signal_arg, "runservice"))
2270             {
2271                 if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT) 
2272                 {
2273                     rv = mpm_service_to_start(&service_name,
2274                                               server->process->pool);
2275                     if (rv != APR_SUCCESS) {
2276                         ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
2277                                      "%s: Unable to start the service manager.",
2278                                      service_name);
2279                         return HTTP_INTERNAL_SERVER_ERROR;
2280                     }            
2281                 }
2282             }
2283             else /* ! -k runservice */
2284             {
2285                 mpm_start_console_handler();
2286             }
2287
2288             /* Create the start mutex, apPID, where PID is the parent Apache process ID.
2289              * Ths start mutex is used during a restart to prevent more than one 
2290              * child process from entering the accept loop at once.
2291              */
2292             rv =  apr_proc_mutex_create(&start_mutex, 
2293                                         signal_name_prefix,
2294                                         APR_LOCK_DEFAULT,
2295                                         ap_server_conf->process->pool);
2296             if (rv != APR_SUCCESS) {
2297                 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
2298                              "%s: Unable to create the start_mutex.",
2299                              service_name);
2300                 return HTTP_INTERNAL_SERVER_ERROR;
2301             }            
2302         }
2303     }
2304     else /* parent_pid != my_pid */
2305     {
2306         mpm_start_child_console_handler();
2307     }
2308     return OK;
2309 }
2310
2311 /* This really should be a post_config hook, but the error log is already
2312  * redirected by that point, so we need to do this in the open_logs phase.
2313  */
2314 static int winnt_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
2315 {
2316     pconf = p;
2317     ap_server_conf = s;
2318
2319     if (parent_pid != my_pid) {
2320         return OK;
2321     }
2322
2323     /* We cannot initialize our listeners if we are restarting
2324      * (the parent process already has glomed on to them)
2325      * nor should we do so for service reconfiguration 
2326      * (since the service may already be running.)
2327      */
2328     if (!strcasecmp(signal_arg, "restart") 
2329             || !strcasecmp(signal_arg, "config")) {
2330         return OK;
2331     }
2332
2333     if (ap_setup_listeners(ap_server_conf) < 1) {
2334         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT|APLOG_STARTUP, 0, 
2335                      NULL, "no listening sockets available, shutting down");
2336         return DONE;
2337     }
2338
2339     if (!set_listeners_noninheritable(s->process->pool)) {
2340         return 1;
2341     }
2342
2343     return OK;
2344 }
2345
2346 static void winnt_child_init(apr_pool_t *pchild, struct server_rec *ap_server_conf)
2347 {
2348     apr_status_t rv;
2349
2350     setup_signal_names(apr_psprintf(pchild,"ap%d", parent_pid));
2351
2352     /* This is a child process, not in single process mode */
2353     if (!one_process) {
2354         /* Set up events and the scoreboard */
2355         get_handles_from_parent(ap_server_conf);
2356
2357         /* Set up the listeners */
2358         get_listeners_from_parent(ap_server_conf);
2359
2360         ap_my_generation = atoi(getenv("AP_MY_GENERATION"));
2361
2362         rv = apr_proc_mutex_child_init(&start_mutex, signal_name_prefix, pconf);
2363     }
2364     else {
2365         /* Single process mode - this lock doesn't even need to exist */
2366         rv = apr_proc_mutex_create(&start_mutex, signal_name_prefix, 
2367                                    APR_LOCK_DEFAULT, pconf);
2368         
2369         /* Borrow the shutdown_even as our _child_ loop exit event */
2370         exit_event = shutdown_event;
2371     }
2372     if (rv != APR_SUCCESS) {
2373         ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
2374                      "%s child %d: Unable to init the start_mutex.",
2375                      service_name, my_pid);
2376         exit(APEXIT_CHILDINIT);
2377     }
2378 }
2379
2380
2381 AP_DECLARE(int) ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s )
2382 {
2383     static int restart = 0;            /* Default is "not a restart" */
2384
2385     /* ### If non-graceful restarts are ever introduced - we need to rerun 
2386      * the pre_mpm hook on subsequent non-graceful restarts.  But Win32 
2387      * has only graceful style restarts - and we need this hook to act 
2388      * the same on Win32 as on Unix.
2389      */
2390     if (!restart && ((parent_pid == my_pid) || one_process)) {
2391         /* Set up the scoreboard. */
2392         if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
2393             return 1;
2394         }
2395     }
2396     
2397     if ((parent_pid != my_pid) || one_process) 
2398     {
2399         /* The child process or in one_process (debug) mode 
2400          */
2401         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
2402                      "Child %d: Child process is running", my_pid);
2403
2404         child_main();
2405
2406         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
2407                      "Child %d: Child process is exiting", my_pid);        
2408         return 1;
2409     }
2410     else 
2411     {
2412         /* A real-honest to goodness parent */
2413
2414         restart = master_main(ap_server_conf, shutdown_event, restart_event);
2415
2416         if (!restart) 
2417         {
2418             /* Shutting down. Clean up... */
2419             const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
2420
2421             if (pidfile != NULL && unlink(pidfile) == 0) {
2422                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS,
2423                              ap_server_conf, "removed PID file %s (pid=%ld)",
2424                              pidfile, GetCurrentProcessId());
2425             }
2426             apr_proc_mutex_destroy(start_mutex);
2427
2428             CloseHandle(restart_event);
2429             CloseHandle(shutdown_event);
2430
2431             return 1;
2432         }
2433     }
2434
2435     return 0; /* Restart */
2436 }
2437
2438 static void winnt_hooks(apr_pool_t *p)
2439 {
2440     /* The prefork open_logs phase must run before the core's, or stderr
2441      * will be redirected to a file, and the messages won't print to the
2442      * console.
2443      */
2444     static const char *const aszSucc[] = {"core.c", NULL};
2445
2446     ap_hook_pre_config(winnt_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2447     ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
2448     ap_hook_child_init(winnt_child_init, NULL, NULL, APR_HOOK_MIDDLE);
2449     ap_hook_open_logs(winnt_open_logs, NULL, aszSucc, APR_HOOK_MIDDLE);
2450 }
2451
2452 AP_MODULE_DECLARE_DATA module mpm_winnt_module = {
2453     MPM20_MODULE_STUFF,
2454     winnt_rewrite_args,         /* hook to run before apache parses args */
2455     NULL,                       /* create per-directory config structure */
2456     NULL,                       /* merge per-directory config structures */
2457     NULL,                       /* create per-server config structure */
2458     NULL,                       /* merge per-server config structures */
2459     winnt_cmds,                 /* command apr_table_t */
2460     winnt_hooks                 /* register_hooks */
2461 };