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