]> granicus.if.org Git - apache/blob - server/mpm/winnt/mpm_winnt.c
Eliminate a warning, pid is an int.
[apache] / server / mpm / winnt / mpm_winnt.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 #define CORE_PRIVATE 
60 #include "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 "ap_mpm.h"
70 #include "ap_config.h"
71 #include "ap_listen.h"
72 #include "mpm_default.h"
73 #include "mpm_winnt.h"
74 #include "mpm_common.h"
75
76 typedef HANDLE thread;
77
78 /*
79  * Definitions of WINNT MPM specific config globals
80  */
81 static int workers_may_exit = 0;
82 static int shutdown_in_progress = 0;
83 static unsigned int g_blocked_threads = 0;
84
85 static char *ap_pid_fname = NULL;
86 static int ap_threads_per_child = 0;
87
88 static int max_requests_per_child = 0;
89 static HANDLE shutdown_event;   /* used to signal shutdown to parent */
90 static HANDLE restart_event;    /* used to signal a restart to parent */
91
92 #define MAX_SIGNAL_NAME 30  /* Long enough for apPID_shutdown, where PID is an int */
93 char signal_name_prefix[MAX_SIGNAL_NAME];
94 char signal_restart_name[MAX_SIGNAL_NAME]; 
95 char signal_shutdown_name[MAX_SIGNAL_NAME];
96
97 static struct fd_set listenfds;
98 static int num_listenfds = 0;
99 static SOCKET listenmaxfd = INVALID_SOCKET;
100
101 static apr_pool_t *pconf;               /* Pool for config stuff */
102
103 static char ap_coredump_dir[MAX_STRING_LEN];
104
105 static server_rec *server_conf;
106 static HANDLE AcceptExCompPort = NULL;
107
108 static int one_process = 0;
109 static char const* signal_arg;
110
111 OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
112
113 int ap_max_requests_per_child=0;
114 int ap_daemons_to_start=0;
115
116 static HANDLE exit_event;
117 static HANDLE maintenance_event;
118 apr_lock_t *start_mutex;
119 DWORD my_pid;
120 DWORD parent_pid;
121
122 /* This is the helper code to resolve late bound entry points 
123  * missing from one or more releases of the Win32 API...
124  * but it sure would be nice if we didn't duplicate this code
125  * from the APR ;-)
126  */
127
128 static const char* const lateDllName[DLL_defined] = {
129     "kernel32", "advapi32", "mswsock",  "ws2_32"  };
130 static HMODULE lateDllHandle[DLL_defined] = {
131     NULL,       NULL,       NULL,       NULL      };
132
133 FARPROC ap_load_dll_func(ap_dlltoken_e fnLib, char* fnName, int ordinal)
134 {
135     if (!lateDllHandle[fnLib]) { 
136         lateDllHandle[fnLib] = LoadLibrary(lateDllName[fnLib]);
137         if (!lateDllHandle[fnLib])
138             return NULL;
139     }
140     if (ordinal)
141         return GetProcAddress(lateDllHandle[fnLib], (char *) ordinal);
142     else
143         return GetProcAddress(lateDllHandle[fnLib], fnName);
144 }
145
146 static apr_status_t socket_cleanup(void *sock)
147 {
148     apr_socket_t *thesocket = sock;
149     SOCKET sd;
150     if (apr_get_os_sock(&sd, thesocket) == APR_SUCCESS) {
151         closesocket(sd);
152     }
153     return APR_SUCCESS;
154 }
155
156 /* A bunch or routines from os/win32/multithread.c that need to be merged into APR
157  * or thrown out entirely...
158  */
159
160 static HANDLE create_semaphore(int initial)
161 {
162     return(CreateSemaphore(NULL, initial, 1000000, NULL));
163 }
164
165 static void acquire_semaphore(HANDLE semaphore_id)
166 {
167     int rv;
168     
169     rv = WaitForSingleObject(semaphore_id, INFINITE);
170     
171     return;
172 }
173
174 static int release_semaphore(HANDLE semaphore_id)
175 {
176     return(ReleaseSemaphore(semaphore_id, 1, NULL));
177 }
178
179 static void destroy_semaphore(HANDLE semaphore_id)
180 {
181     CloseHandle(semaphore_id);
182 }
183
184
185 /* To share the semaphores with other processes, we need a NULL ACL
186  * Code from MS KB Q106387
187  */
188 static PSECURITY_ATTRIBUTES GetNullACL()
189 {
190     PSECURITY_DESCRIPTOR pSD;
191     PSECURITY_ATTRIBUTES sa;
192
193     sa  = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES));
194     pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,
195                                             SECURITY_DESCRIPTOR_MIN_LENGTH);
196     if (pSD == NULL || sa == NULL) {
197         return NULL;
198     }
199     apr_set_os_error(0);
200     if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
201         || apr_get_os_error()) {
202         LocalFree( pSD );
203         LocalFree( sa );
204         return NULL;
205     }
206     if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
207         || apr_get_os_error()) {
208         LocalFree( pSD );
209         LocalFree( sa );
210         return NULL;
211     }
212     sa->nLength = sizeof(sa);
213     sa->lpSecurityDescriptor = pSD;
214     sa->bInheritHandle = TRUE;
215     return sa;
216 }
217
218 static void CleanNullACL( void *sa ) {
219     if( sa ) {
220         LocalFree( ((PSECURITY_ATTRIBUTES)sa)->lpSecurityDescriptor);
221         LocalFree( sa );
222     }
223 }
224
225 /*
226  * The Win32 call WaitForMultipleObjects will only allow you to wait for 
227  * a maximum of MAXIMUM_WAIT_OBJECTS (current 64).  Since the threading 
228  * model in the multithreaded version of apache wants to use this call, 
229  * we are restricted to a maximum of 64 threads.  This is a simplistic 
230  * routine that will increase this size.
231  */
232 static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles, 
233                                    DWORD dwSeconds)
234 {
235     time_t tStopTime;
236     DWORD dwRet = WAIT_TIMEOUT;
237     DWORD dwIndex=0;
238     BOOL bFirst = TRUE;
239   
240     tStopTime = time(NULL) + dwSeconds;
241   
242     do {
243         if (!bFirst)
244             Sleep(1000);
245         else
246             bFirst = FALSE;
247           
248         for (dwIndex = 0; dwIndex * MAXIMUM_WAIT_OBJECTS < nCount; dwIndex++) {
249             dwRet = WaitForMultipleObjects( 
250                 min(MAXIMUM_WAIT_OBJECTS, nCount - (dwIndex * MAXIMUM_WAIT_OBJECTS)),
251                 lpHandles + (dwIndex * MAXIMUM_WAIT_OBJECTS), 
252                 0, 0);
253                                            
254             if (dwRet != WAIT_TIMEOUT) {                                          
255               break;
256             }
257         }
258     } while((time(NULL) < tStopTime) && (dwRet == WAIT_TIMEOUT));
259     
260     return dwRet;
261 }
262
263 /*
264  * Signalling Apache on NT.
265  *
266  * Under Unix, Apache can be told to shutdown or restart by sending various
267  * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
268  * we use "events" instead. The parent apache process goes into a loop
269  * where it waits forever for a set of events. Two of those events are
270  * called
271  *
272  *    apPID_shutdown
273  *    apPID_restart
274  *
275  * (where PID is the PID of the apache parent process). When one of these
276  * is signalled, the Apache parent performs the appropriate action. The events
277  * can become signalled through internal Apache methods (e.g. if the child
278  * finds a fatal error and needs to kill its parent), via the service
279  * control manager (the control thread will signal the shutdown event when
280  * requested to stop the Apache service), from the -k Apache command line,
281  * or from any external program which finds the Apache PID from the
282  * httpd.pid file.
283  *
284  * The signal_parent() function, below, is used to signal one of these events.
285  * It can be called by any child or parent process, since it does not
286  * rely on global variables.
287  *
288  * On entry, type gives the event to signal. 0 means shutdown, 1 means 
289  * graceful restart.
290  */
291 void signal_parent(int type)
292 {
293     HANDLE e;
294     char *signal_name;
295     
296     /* after updating the shutdown_pending or restart flags, we need
297      * to wake up the parent process so it can see the changes. The
298      * parent will normally be waiting for either a child process
299      * to die, or for a signal on the "spache-signal" event. So set the
300      * "apache-signal" event here.
301      */
302     if (one_process) {
303         return;
304     }
305
306     switch(type) {
307     case 0: signal_name = signal_shutdown_name; break;
308     case 1: signal_name = signal_restart_name; break;
309     default: return;
310     }
311     e = OpenEvent(EVENT_ALL_ACCESS, FALSE, signal_name);
312     if (!e) {
313         /* Um, problem, can't signal the parent, which means we can't
314          * signal ourselves to die. Ignore for now...
315          */
316         ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
317                      "OpenEvent on %s event", signal_name);
318         return;
319     }
320     if (SetEvent(e) == 0) {
321         /* Same problem as above */
322         ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
323                      "SetEvent on %s event", signal_name);
324         CloseHandle(e);
325         return;
326     }
327     CloseHandle(e);
328 }
329
330 static int volatile is_graceful = 0;
331
332 AP_DECLARE(int) ap_graceful_stop_signalled(void)
333 {
334     return is_graceful;
335 }
336
337 AP_DECLARE(void) ap_start_shutdown(void)
338 {
339     signal_parent(0);
340 }
341
342 AP_DECLARE(void) ap_start_restart(int gracefully)
343 {
344     is_graceful = gracefully;
345     signal_parent(1);
346 }
347
348 /*
349  * Initialise the signal names, in the global variables signal_name_prefix, 
350  * signal_restart_name and signal_shutdown_name.
351  */
352
353 void setup_signal_names(char *prefix)
354 {
355     apr_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);    
356     apr_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name), 
357         "%s_shutdown", signal_name_prefix);    
358     apr_snprintf(signal_restart_name, sizeof(signal_restart_name), 
359         "%s_restart", signal_name_prefix);    
360 }
361
362 /*
363  * Routines that deal with sockets, some are WIN32 specific...
364  */
365
366 static void sock_disable_nagle(int s) 
367 {
368     /* The Nagle algorithm says that we should delay sending partial
369      * packets in hopes of getting more data.  We don't want to do
370      * this; we are not telnet.  There are bad interactions between
371      * persistent connections and Nagle's algorithm that have very severe
372      * performance penalties.  (Failing to disable Nagle is not much of a
373      * problem with simple HTTP.)
374      *
375      * In spite of these problems, failure here is not a shooting offense.
376      */
377     int just_say_no = 1;
378
379     if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
380                    sizeof(int)) < 0) {
381         ap_log_error(APLOG_MARK, APLOG_WARNING, APR_SUCCESS, server_conf,
382                     "setsockopt: (TCP_NODELAY)");
383     }
384 }
385
386 /*
387  * Routines to deal with managing the list of listening sockets.
388  */
389 static ap_listen_rec *head_listener;
390
391 static apr_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
392 {
393     ap_listen_rec *lr;
394     SOCKET nsd;
395
396     for (lr = head_listener; lr ; lr = lr->next) {
397         apr_get_os_sock(&nsd, lr->sd);
398         if (FD_ISSET(nsd, main_fds)) {
399             head_listener = lr->next;
400             if (head_listener == NULL)
401                 head_listener = ap_listeners;
402
403             return (lr);
404         }
405     }
406     return NULL;
407 }
408
409 static int setup_listeners(server_rec *s)
410 {
411     ap_listen_rec *lr;
412     int num_listeners = 0;
413     SOCKET nsd;
414
415     /* Setup the listeners */
416     FD_ZERO(&listenfds);
417
418     if (ap_listen_open(s->process, s->port)) {
419        return 0;
420     }
421     for (lr = ap_listeners; lr; lr = lr->next) {
422         num_listeners++;
423         if (lr->sd != NULL) {
424             apr_get_os_sock(&nsd, lr->sd);
425             FD_SET(nsd, &listenfds);
426             if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
427                 listenmaxfd = nsd;
428             }
429         }
430         lr->count = 0;
431     }
432
433     head_listener = ap_listeners;
434
435     return num_listeners;
436 }
437
438 static int setup_inherited_listeners(server_rec *s)
439 {
440     WSAPROTOCOL_INFO WSAProtocolInfo;
441     HANDLE pipe;
442     ap_listen_rec *lr;
443     DWORD BytesRead;
444     int num_listeners = 0;
445     SOCKET nsd;
446
447     /* Setup the listeners */
448     FD_ZERO(&listenfds);
449
450     /* Set up a default listener if necessary */
451
452     if (ap_listeners == NULL) {
453         ap_listen_rec *lr;
454         lr = apr_palloc(s->process->pool, sizeof(ap_listen_rec));
455         if (!lr)
456             return 0;
457         lr->sd = NULL;
458         lr->next = ap_listeners;
459         ap_listeners = lr;
460     }
461
462     /* Open the pipe to the parent process to receive the inherited socket
463      * data. The sockets have been set to listening in the parent process.
464      */
465     pipe = GetStdHandle(STD_INPUT_HANDLE);
466     for (lr = ap_listeners; lr; lr = lr->next) {
467         if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO), 
468                       &BytesRead, (LPOVERLAPPED) NULL)) {
469             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
470                          "setup_inherited_listeners: Unable to read socket data from parent");
471             signal_parent(0);   /* tell parent to die */
472             exit(1);
473         }
474         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
475                      "Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.", my_pid);
476         nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
477                         &WSAProtocolInfo, 0, 0);
478         if (nsd == INVALID_SOCKET) {
479             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), server_conf,
480                          "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
481             signal_parent(0);   /* tell parent to die */
482             exit(1);
483         }
484         if (nsd >= 0) {
485             FD_SET(nsd, &listenfds);
486             if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
487                 listenmaxfd = nsd;
488             }
489         }
490         apr_put_os_sock(&lr->sd, &nsd, pconf);
491         lr->count = 0;
492     }
493     /* Now, read the AcceptExCompPort from the parent */
494     ReadFile(pipe, &AcceptExCompPort, sizeof(AcceptExCompPort), &BytesRead, (LPOVERLAPPED) NULL);
495     CloseHandle(pipe);
496
497     for (lr = ap_listeners; lr; lr = lr->next) {
498         num_listeners++;
499     }
500
501     head_listener = ap_listeners;
502     return num_listeners;
503 }
504
505 static void bind_listeners_to_completion_port()
506 {
507     /* Associate the open listeners with the completion port.
508      * Bypass the operation for Windows 95/98
509      */
510     ap_listen_rec *lr;
511
512     if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
513         for (lr = ap_listeners; lr; lr = lr->next) {
514             int nsd;
515             apr_get_os_sock(&nsd,lr->sd);
516             CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
517         }
518     }
519 }
520
521 /**********************************************************************
522  * Multithreaded implementation
523  *
524  * This code is fairly specific to Win32.
525  *
526  * The model used to handle requests is a set of threads. One "main"
527  * thread listens for new requests. When something becomes
528  * available, it does a select and places the newly available socket
529  * onto a list of "jobs" (add_job()). Then any one of a fixed number
530  * of "worker" threads takes the top job off the job list with
531  * remove_job() and handles that connection to completion. After
532  * the connection has finished the thread is free to take another
533  * job from the job list.
534  *
535  * In the code, the "main" thread is running within the child_main()
536  * function. The first thing this function does is create the
537  * worker threads, which operate in the child_sub_main() function. The
538  * main thread then goes into a loop within child_main() where they
539  * do a select() on the listening sockets. The select times out once
540  * per second so that the thread can check for an "exit" signal
541  * from the parent process (see below). If this signal is set, the 
542  * thread can exit, but only after it has accepted all incoming
543  * connections already in the listen queue (since Win32 appears
544  * to through away listened but unaccepted connections when a 
545  * process dies).
546  *
547  * Because the main and worker threads exist within a single process
548  * they are vulnerable to crashes or memory leaks (crashes can also
549  * be caused within modules, of course). There also needs to be a 
550  * mechanism to perform restarts and shutdowns. This is done by
551  * creating the main & worker threads within a subprocess. A
552  * main process (the "parent process") creates one (or more) 
553  * processes to do the work, then the parent sits around waiting
554  * for the working process to die, in which case it starts a new
555  * one. The parent process also handles restarts (by creating
556  * a new working process then signalling the previous working process 
557  * exit ) and shutdowns (by signalling the working process to exit).
558  * The parent process operates within the master_main() function. This
559  * process also handles requests from the service manager (NT only).
560  *
561  * Signalling between the parent and working process uses a Win32
562  * event. Each child has a unique name for the event, which is
563  * passed to it with the -Z argument when the child is spawned. The
564  * parent sets (signals) this event to tell the child to die.
565  * At present all children do a graceful die - they finish all
566  * current jobs _and_ empty the listen queue before they exit.
567  * A non-graceful die would need a second event. The -Z argument in
568  * the child is also used to create the shutdown and restart events,
569  * since the prefix (apPID) contains the parent process PID.
570  *
571  * The code below starts with functions at the lowest level -
572  * worker threads, and works up to the top level - the main()
573  * function of the parent process.
574  *
575  * The scoreboard (in process memory) contains details of the worker
576  * threads (within the active working process). There is no shared
577  * "scoreboard" between processes, since only one is ever active
578  * at once (or at most, two, when one has been told to shutdown but
579  * is processes outstanding requests, and a new one has been started).
580  * This is controlled by a "start_mutex" which ensures only one working
581  * process is active at once.
582  **********************************************************************/
583
584
585 /*
586  * Definition of jobs, shared by main and worker threads.
587  */
588
589 typedef struct joblist_s {
590     struct joblist_s *next;
591     int sock;
592 } joblist;
593
594 /*
595  * Globals common to main and worker threads. This structure is not
596  * used by the parent process.
597  */
598
599 typedef struct globals_s {
600     HANDLE jobsemaphore;
601     joblist *jobhead;
602     joblist *jobtail;
603     apr_lock_t *jobmutex;
604     int jobcount;
605
606 } globals;
607
608 globals allowed_globals =
609 {NULL, NULL, NULL, NULL, 0};
610 #define MAX_SELECT_ERRORS 100
611 #define PADDED_ADDR_SIZE sizeof(SOCKADDR_IN)+16
612
613 /* Windows 9x specific code...
614  * Accept processing for on Windows 95/98 uses a producer/consumer queue 
615  * model. A single thread accepts connections and queues the accepted socket 
616  * to the accept queue for consumption by a pool of worker threads.
617  *
618  * win9x_get_connection()
619  *    Calls remove_job() to pull a job from the accept queue. All the worker 
620  *    threads block on remove_job.
621  * accept_and_queue_connections()
622  *    The accept threads runs this function, which accepts connections off 
623  *    the network and calls add_job() to queue jobs to the accept_queue.
624  * add_job()/remove_job()
625  *    Add or remove an accepted socket from the list of sockets 
626  *    connected to clients. allowed_globals.jobmutex protects
627  *    against multiple concurrent access to the linked list of jobs.
628  */
629 static void add_job(int sock)
630 {
631     joblist *new_job;
632
633     new_job = (joblist *) malloc(sizeof(joblist));
634     if (new_job == NULL) {
635         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
636                      "Ouch!  Out of memory in add_job()!");
637         return;
638     }
639     new_job->next = NULL;
640     new_job->sock = sock;
641
642     apr_lock(allowed_globals.jobmutex);
643
644     if (allowed_globals.jobtail != NULL)
645         allowed_globals.jobtail->next = new_job;
646     allowed_globals.jobtail = new_job;
647     if (!allowed_globals.jobhead)
648         allowed_globals.jobhead = new_job;
649     allowed_globals.jobcount++;
650     release_semaphore(allowed_globals.jobsemaphore);
651
652     apr_unlock(allowed_globals.jobmutex);
653 }
654
655 static int remove_job(void)
656 {
657     joblist *job;
658     int sock;
659
660     acquire_semaphore(allowed_globals.jobsemaphore);
661     apr_lock(allowed_globals.jobmutex);
662
663     if (shutdown_in_progress && !allowed_globals.jobhead) {
664         apr_unlock(allowed_globals.jobmutex);
665         return (-1);
666     }
667     job = allowed_globals.jobhead;
668     ap_assert(job);
669     allowed_globals.jobhead = job->next;
670     if (allowed_globals.jobhead == NULL)
671         allowed_globals.jobtail = NULL;
672     apr_unlock(allowed_globals.jobmutex);
673     sock = job->sock;
674     free(job);
675
676     return (sock);
677 }
678
679 static void accept_and_queue_connections(void * dummy)
680 {
681     int requests_this_child = 0;
682     struct timeval tv;
683     fd_set main_fds;
684     int wait_time = 1;
685     int csd;
686     int nsd = INVALID_SOCKET;
687     struct sockaddr_in sa_client;
688     int count_select_errors = 0;
689     int rc;
690     int clen;
691
692     while (!shutdown_in_progress) {
693         if (ap_max_requests_per_child && (requests_this_child > ap_max_requests_per_child)) {
694             break;
695         }
696
697         tv.tv_sec = wait_time;
698         tv.tv_usec = 0;
699         memcpy(&main_fds, &listenfds, sizeof(fd_set));
700
701         rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
702
703         if (rc == 0 || (rc == SOCKET_ERROR && APR_STATUS_IS_EINTR(apr_get_netos_error()))) {
704             count_select_errors = 0;    /* reset count of errors */            
705             continue;
706         }
707         else if (rc == SOCKET_ERROR) {
708             /* A "real" error occurred, log it and increment the count of
709              * select errors. This count is used to ensure we don't go into
710              * a busy loop of continuous errors.
711              */
712             ap_log_error(APLOG_MARK, APLOG_INFO, apr_get_netos_error(), server_conf, 
713                          "select failed with error %d", apr_get_netos_error());
714             count_select_errors++;
715             if (count_select_errors > MAX_SELECT_ERRORS) {
716                 shutdown_in_progress = 1;
717                 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), server_conf,
718                              "Too many errors in select loop. Child process exiting.");
719                 break;
720             }
721         } else {
722             ap_listen_rec *lr;
723
724             lr = find_ready_listener(&main_fds);
725             if (lr != NULL) {
726                 /* fetch the native socket descriptor */
727                 apr_get_os_sock(&nsd, lr->sd);
728             }
729         }
730
731         do {
732             clen = sizeof(sa_client);
733             csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
734             if (csd == INVALID_SOCKET) {
735                 csd = -1;
736             }
737         } while (csd < 0 && APR_STATUS_IS_EINTR(apr_get_netos_error()));
738
739         if (csd < 0) {
740             if (APR_STATUS_IS_ECONNABORTED(apr_get_netos_error())) {
741                 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), server_conf,
742                             "accept: (client socket)");
743             }
744         }
745         else {
746             add_job(csd);
747             requests_this_child++;
748         }
749     }
750     SetEvent(exit_event);
751 }
752 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
753 {
754     int len;
755
756     if (context == NULL) {
757         /* allocate the completion context and the transaction pool */
758         context = apr_pcalloc(pconf, sizeof(COMP_CONTEXT));
759         if (!context) {
760             ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
761                          "win9x_get_connection: apr_pcalloc() failed. Process will exit.");
762             return NULL;
763         }
764         apr_create_pool(&context->ptrans, pconf);
765     }
766     
767
768     while (1) {
769         apr_clear_pool(context->ptrans);        
770         context->accept_socket = remove_job();
771         if (context->accept_socket == -1) {
772             return NULL;
773         }
774         len = sizeof(struct sockaddr);
775         context->sa_server = apr_palloc(context->ptrans, len);
776         if (getsockname(context->accept_socket, 
777                         context->sa_server, &len)== SOCKET_ERROR) {
778             ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), server_conf, 
779                          "getsockname failed");
780             continue;
781         }
782         len = sizeof(struct sockaddr);
783         context->sa_client = apr_palloc(context->ptrans, len);
784         if ((getpeername(context->accept_socket,
785                          context->sa_client, &len)) == SOCKET_ERROR) {
786             ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), server_conf, 
787                          "getpeername failed");
788             memset(&context->sa_client, '\0', sizeof(context->sa_client));
789         }
790
791         /* do we NEED_DUPPED_CSD ?? */
792         
793         return context;
794     }
795 }
796
797 /* 
798  * Windows 2000/NT specific code...
799  * create_acceptex_context()
800  * reset_acceptex_context()
801  * drain_acceptex_complport()
802  * winnt_get_connection()
803  *
804  * TODO: Insert a discussion of 'completion contexts' and what these function do here...
805  */
806 static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp) 
807 {
808     LPOVERLAPPED pol;
809     PCOMP_CONTEXT context;
810     int rc;
811     DWORD BytesRead;
812     DWORD CompKey;
813
814     while (1) {
815         context = NULL;
816         rc = GetQueuedCompletionStatus(hComplPort, &BytesRead, &CompKey,
817                                        &pol, 1000);
818         if (!rc) {
819             rc = apr_get_os_error();
820             if (rc == APR_FROM_OS_ERROR(ERROR_OPERATION_ABORTED)) {
821                 ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, server_conf,
822                              "Child %d: Draining an ABORTED packet off "
823                              "the AcceptEx completion port.", my_pid);
824                 continue;
825             }
826             break;
827         }
828         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
829                      "Child %d: Draining and discarding an active connection "
830                      "off the AcceptEx completion port.", my_pid);
831         context = (PCOMP_CONTEXT) pol;
832         if (context && bCleanUp) {
833             /* It is only valid to clean-up in the process that initiated the I/O */
834             closesocket(context->accept_socket);
835             CloseHandle(context->Overlapped.hEvent);
836         }
837     }
838 }
839 static int create_acceptex_context(apr_pool_t *_pconf, ap_listen_rec *lr) 
840 {
841     PCOMP_CONTEXT context;
842     DWORD BytesRead;
843     SOCKET nsd;
844     int lasterror;
845
846     /* allocate the completion context */
847     context = apr_pcalloc(_pconf, sizeof(COMP_CONTEXT));
848     if (!context) {
849         ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
850                      "create_acceptex_context: apr_pcalloc() failed. Process will exit.");
851         return -1;
852     }
853
854     /* initialize the completion context */
855     context->lr = lr;
856     context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); 
857     if (context->Overlapped.hEvent == NULL) {
858         ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
859                      "create_acceptex_context: CreateEvent() failed. Process will exit.");
860         return -1;
861     }
862
863     /* create and initialize the accept socket */
864     apr_get_os_sock(&nsd, context->lr->sd);
865     context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
866     if (context->accept_socket == INVALID_SOCKET) {
867         ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_netos_error(), server_conf,
868                      "create_acceptex_context: socket() failed. Process will exit.");
869         return -1;
870     }
871
872     /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
873     if (setsockopt(context->accept_socket, SOL_SOCKET,
874                    SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
875                    sizeof(nsd))) {
876         ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), server_conf,
877                      "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
878         /* Not a failure condition. Keep running. */
879     }
880
881     apr_create_pool(&context->ptrans, _pconf);
882
883     /* recv_buf must be large enough to hold the remote and local
884      * addresses. Note that recv_buf_size is the amount of recv_buf
885      * available for AcceptEx to receive bytes into. Since we 
886      * don't want AcceptEx to do a recv, set the size to 0.
887      */
888     context->recv_buf = apr_pcalloc(_pconf, 2*PADDED_ADDR_SIZE);
889     context->recv_buf_size = 0;
890
891     /* AcceptEx on the completion context. The completion context will be signaled
892      * when a connection is accepted. */
893     if (!AcceptEx(nsd, context->accept_socket,
894                   context->recv_buf, 
895                   context->recv_buf_size,
896                   PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
897                   &BytesRead,
898                   (LPOVERLAPPED) context)) {
899         lasterror = apr_get_netos_error();
900         if (lasterror != APR_FROM_OS_ERROR(ERROR_IO_PENDING)) {
901             ap_log_error(APLOG_MARK,APLOG_ERR, lasterror, server_conf,
902                          "create_acceptex_context: AcceptEx failed. Process will exit.");
903             return -1;
904         }
905
906     }
907     lr->count++;
908
909     return 0;
910 }
911 static apr_inline apr_status_t reset_acceptex_context(PCOMP_CONTEXT context) 
912 {
913     DWORD BytesRead;
914     SOCKET nsd;
915     int rc, i;
916
917     /* reset the buffer pools */
918     apr_clear_pool(context->ptrans);
919     context->sock = NULL;
920
921     /* recreate and initialize the accept socket if it is not being reused */
922     apr_get_os_sock(&nsd, context->lr->sd);
923
924     /* AcceptEx on the completion context. The completion context will be signaled
925      * when a connection is accepted. Hack Alert: TransmitFile, under certain 
926      * circumstances, can 'recycle' accept sockets, saving the overhead of calling 
927      * socket(). Occasionally this fails (usually when the client closes his end 
928      * of the connection early). When this occurs, AcceptEx will fail with 10022, 
929      * Invalid Parameter. When this occurs, just open a fresh accept socket and 
930      * retry the call.
931      */
932     for (i=0; i<2; i++) {
933         if (context->accept_socket == INVALID_SOCKET) {
934             context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
935             if (context->accept_socket == INVALID_SOCKET) {
936                 rc = apr_get_netos_error();
937                 ap_log_error(APLOG_MARK,APLOG_ERR, rc, server_conf,
938                              "reset_acceptex_context: socket() failed. Process will exit.");
939                 return rc;
940             }
941
942             /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
943             if (setsockopt(context->accept_socket, SOL_SOCKET,
944                            SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd, sizeof(nsd))) {
945                 ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(),
946                              server_conf,
947                              "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
948             }
949         }
950
951         if (!AcceptEx(nsd, context->accept_socket, 
952                       context->recv_buf,                   
953                       context->recv_buf_size,
954                       PADDED_ADDR_SIZE, 
955                       PADDED_ADDR_SIZE, 
956                       &BytesRead, 
957                       (LPOVERLAPPED) context)) {
958
959             rc = apr_get_netos_error();
960             if (rc != APR_FROM_OS_ERROR(ERROR_IO_PENDING)) {
961                 ap_log_error(APLOG_MARK, APLOG_DEBUG, rc, server_conf,
962                              "reset_acceptex_context: AcceptEx failed for "
963                              "listening socket: %d and accept socket: %d. Getting a new accept socket.", 
964                              nsd, context->accept_socket);
965                 closesocket(context->accept_socket);
966                 context->accept_socket = INVALID_SOCKET;
967                 continue;
968             }
969         }
970         break;
971     }
972
973     context->lr->count++;
974
975     return APR_SUCCESS;
976 }
977 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
978 {
979     int requests_this_child = 0;
980     int rc;
981     LPOVERLAPPED pol;
982     DWORD CompKey;
983     DWORD BytesRead;
984
985
986     if (context != NULL) {
987         if (shutdown_in_progress) {
988             /* Clean-up the AcceptEx completion context */
989             CloseHandle(context->Overlapped.hEvent);
990             if (context->accept_socket != INVALID_SOCKET)
991                 closesocket(context->accept_socket);
992         }
993         else {
994             /* Prepare the completion context for reuse */
995             if ((rc = reset_acceptex_context(context)) != APR_SUCCESS) {
996                 ap_log_error(APLOG_MARK, APLOG_CRIT, rc, server_conf,
997                              "Child %d: winnt_get_connection: reset_acceptex_context failed.",
998                              my_pid); 
999                 if (context->accept_socket != INVALID_SOCKET)
1000                     closesocket(context->accept_socket);
1001                 CloseHandle(context->Overlapped.hEvent);
1002                 /* Probably should just die now... */
1003             }
1004         }
1005     }
1006
1007     /* May need to atomize the workers_may_exit check with the 
1008      * g_blocked_threads++ */
1009     if (workers_may_exit) {
1010         return NULL;
1011     }
1012     g_blocked_threads++;
1013         
1014     while (1) {
1015         rc = GetQueuedCompletionStatus(AcceptExCompPort, &BytesRead, &CompKey,
1016                                        &pol, INFINITE);
1017         if (!rc) {
1018             rc = apr_get_os_error();
1019             if (rc != APR_FROM_OS_ERROR(ERROR_OPERATION_ABORTED)) {
1020                 /* Is this a deadly condition? 
1021                  * We sometimes get ERROR_NETNAME_DELETED when a client
1022                  * disconnects when attempting to reuse sockets. Not sure why 
1023                  * we see this now and not during AcceptEx(). Reset the
1024                  * AcceptEx context and continue...
1025                  */
1026                 ap_log_error(APLOG_MARK,APLOG_DEBUG, rc, server_conf,
1027                              "Child %d: - GetQueuedCompletionStatus() failed", 
1028                              my_pid);
1029                 /* Reset the completion context */
1030                 if (pol) {
1031                     context = (PCOMP_CONTEXT) pol;
1032                     if (context->accept_socket != INVALID_SOCKET)
1033                         closesocket(context->accept_socket);
1034                     if ((rc = reset_acceptex_context(context)) != APR_SUCCESS) {
1035                         ap_log_error(APLOG_MARK, APLOG_CRIT, rc, server_conf,
1036                                      "Child %d: winnt_get_connection: reset_acceptex_context failed.",
1037                                      my_pid); 
1038                         if (context->accept_socket != INVALID_SOCKET)
1039                             closesocket(context->accept_socket);
1040                         CloseHandle(context->Overlapped.hEvent);
1041                         /* Probably should just die now... */
1042                     }
1043                 }
1044             }
1045             else {
1046                 /* Sometimes we catch ERROR_OPERATION_ABORTED completion packets
1047                  * from the old child process (during a restart). Ignore them.
1048                  */
1049                 ap_log_error(APLOG_MARK,APLOG_DEBUG, rc, server_conf,
1050                              "Child %d: - Draining ERROR_OPERATION_ABORTED packet off "
1051                              "the completion port.", my_pid);
1052             }
1053             continue;
1054         }
1055
1056         if (CompKey != 0) {
1057             /* CompKey == my_pid means this thread was unblocked by
1058              * the shutdown code (not by io completion).
1059              */
1060             if (CompKey == my_pid) {
1061                 g_blocked_threads--;
1062                 return NULL;
1063             }
1064             /* Sometimes we catch shutdown io completion packets
1065              * posted by the old child process (during a restart). Ignore them.
1066              */
1067             continue;
1068         }
1069
1070         context = (PCOMP_CONTEXT) pol;
1071         break;
1072     }
1073
1074     g_blocked_threads--;
1075
1076     /* Check to see if we need to create more completion contexts,
1077      * but only if we are not in the process of shutting down
1078      */
1079     if (!shutdown_in_progress) {
1080         apr_lock(allowed_globals.jobmutex);
1081         context->lr->count--;
1082         if (context->lr->count < 2) {
1083             SetEvent(maintenance_event);
1084         }
1085         apr_unlock(allowed_globals.jobmutex);
1086     }
1087
1088     /* Received a connection */
1089     GetAcceptExSockaddrs(context->recv_buf, 
1090                          context->recv_buf_size,
1091                          PADDED_ADDR_SIZE,
1092                          PADDED_ADDR_SIZE,
1093                          &context->sa_server,
1094                          &context->sa_server_len,
1095                          &context->sa_client,
1096                          &context->sa_client_len);
1097
1098     return context;
1099
1100 }
1101 /*
1102  * worker_main() - this is the main loop for the worker threads
1103  *
1104  * Windows 95/98
1105  * Each thread runs within this function. They wait within remove_job()
1106  * for a job to become available, then handle all the requests on that
1107  * connection until it is closed, then return to remove_job().
1108  *
1109  * The worker thread will exit when it removes a job which contains
1110  * socket number -1. This provides a graceful thread exit, since
1111  * it will never exit during a connection.
1112  *
1113  * This code in this function is basically equivalent to the child_main()
1114  * from the multi-process (Unix) environment, except that we
1115  *
1116  *  - do not call child_init_modules (child init API phase)
1117  *  - block in remove_job, and when unblocked we have an already
1118  *    accepted socket, instead of blocking on a mutex or select().
1119  */
1120
1121 static void worker_main(int child_num)
1122 {
1123     PCOMP_CONTEXT context = NULL;
1124     apr_os_sock_info_t sockinfo;
1125
1126     while (1) {
1127         conn_rec *c;
1128         apr_int32_t disconnected;
1129
1130         /* Grab a connection off the network */
1131         if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1132             context = win9x_get_connection(context);
1133         }
1134         else {
1135             context = winnt_get_connection(context);
1136         }
1137
1138         if (!context)
1139             break;
1140         sock_disable_nagle(context->accept_socket);
1141
1142         sockinfo.os_sock = &context->accept_socket;
1143         sockinfo.local   = context->sa_server;
1144         sockinfo.remote  = context->sa_client;
1145         sockinfo.family  = APR_INET;
1146         sockinfo.type    = SOCK_STREAM;
1147         apr_make_os_sock(&context->sock, &sockinfo, context->ptrans);
1148
1149         c = ap_new_connection(context->ptrans, server_conf, context->sock,
1150                               child_num);
1151
1152         ap_process_connection(c);
1153
1154
1155         apr_getsocketopt(context->sock, APR_SO_DISCONNECTED, &disconnected);
1156         if (!disconnected) {
1157             context->accept_socket = INVALID_SOCKET;
1158             ap_lingering_close(c);
1159         }
1160     }
1161
1162     ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, server_conf,
1163                  "Child %d: Thread exiting.", my_pid);
1164 #if 0
1165
1166     SetEvent(exit_event);
1167 #endif
1168     /* TODO: Add code to clean-up completion contexts here */
1169 }
1170
1171 static void cleanup_thread(thread *handles, int *thread_cnt, int thread_to_clean)
1172 {
1173     int i;
1174
1175     CloseHandle(handles[thread_to_clean]);
1176     for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1177         handles[i] = handles[i + 1];
1178     (*thread_cnt)--;
1179 }
1180
1181 static void create_listeners() 
1182 {
1183 #define NUM_LISTENERS 5
1184     ap_listen_rec *lr;
1185     for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1186         while (lr->count < NUM_LISTENERS) {
1187             if (create_acceptex_context(pconf, lr) == -1) {
1188                 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
1189                              "Unable to create an AcceptEx completion context -- process will exit");
1190                 signal_parent(0);       /* tell parent to die */
1191             }
1192         }
1193     }
1194 }
1195 /*
1196  * child_main() runs the main control thread for the child process. 
1197  *
1198  * The control thread:
1199  * - sets up the worker thread pool
1200  * - starts the accept thread (Win 9x)
1201  * - creates AcceptEx contexts (Win NT)
1202  * - waits for exit_event, maintenance_event or maintenance timeout
1203  *   and does the right thing depending on which event is received.
1204  */
1205 static void child_main()
1206 {
1207     apr_status_t status;
1208     HANDLE child_events[2];
1209     char* exit_event_name;
1210     int nthreads = ap_threads_per_child;
1211     int tid;
1212     thread *child_handles;
1213     int rv;
1214     time_t end_time;
1215     int i;
1216     int cld;
1217     apr_pool_t *pchild;
1218
1219
1220     /* This is the child process or we are running in single process
1221      * mode.
1222      */
1223     exit_event_name = apr_psprintf(pconf, "apC%d", my_pid);
1224     setup_signal_names(apr_psprintf(pconf,"ap%d", parent_pid));
1225
1226     if (one_process) {
1227         /* Single process mode */
1228         apr_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1229         exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1230
1231         setup_listeners(server_conf);
1232         bind_listeners_to_completion_port();
1233     }
1234     else {
1235         /* Child process mode */
1236         apr_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1237         exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1238         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1239                      "Child %d: exit_event_name = %s", my_pid, exit_event_name);
1240
1241         setup_inherited_listeners(server_conf);
1242     }
1243
1244     /* Initialize the child_events */
1245     maintenance_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1246     child_events[0] = exit_event;
1247     child_events[1] = maintenance_event;
1248
1249     ap_assert(start_mutex);
1250     ap_assert(exit_event);
1251     ap_assert(maintenance_event);
1252
1253     apr_create_pool(&pchild, pconf);
1254     allowed_globals.jobsemaphore = create_semaphore(0);
1255     apr_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
1256
1257     /*
1258      * Wait until we have permission to start accepting connections.
1259      * start_mutex is used to ensure that only one child ever
1260      * goes into the listen/accept loop at once.
1261      */
1262     status = apr_lock(start_mutex);
1263     if (status != APR_SUCCESS) {
1264         ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
1265                      "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1266         signal_parent(0);       /* tell parent to die */
1267         exit(0);
1268     }
1269     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1270                  "Child %d: Acquired the start mutex.", my_pid);
1271
1272     /* Create the worker thread pool */
1273     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1274                  "Child %d: Starting %d worker threads.", my_pid, nthreads);
1275     child_handles = (thread) alloca(nthreads * sizeof(int));
1276     for (i = 0; i < nthreads; i++) {
1277         child_handles[i] = (thread) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1278                                                    NULL, 0, &tid);
1279     }
1280
1281     /* Begin accepting connections */
1282     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1283         /* Win95/98: Start the accept thread */
1284         _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) accept_and_queue_connections,
1285                        (void *) i, 0, &tid);
1286     } else {
1287         /* Windows NT/2000: Create AcceptEx completion contexts */
1288         create_listeners();
1289     }
1290
1291     /* Wait for one of three events:
1292      * exit_event: 
1293      *    The exit_event is signaled by the parent process to notify 
1294      *    the child that it is time to exit.
1295      *
1296      * maintenance_event: 
1297      *    This event is signaled by the worker thread pool to direct 
1298      *    this thread to create more completion contexts.
1299      *
1300      * TIMEOUT:
1301      *    To do periodic maintenance on the server (check for thread exits,
1302      *    number of completion contexts, etc.)
1303      */
1304     while (1) {
1305         rv = WaitForMultipleObjects(2, (HANDLE *) child_events, FALSE, INFINITE);
1306         cld = rv - WAIT_OBJECT_0;
1307         if (rv == WAIT_FAILED) {
1308             /* Something serious is wrong */
1309             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1310                          "Child %d: WAIT_FAILED -- shutting down server");
1311             break;
1312         }
1313         else if (rv == WAIT_TIMEOUT) {
1314             /* Hey, this cannot happen */
1315             ap_log_error(APLOG_MARK, APLOG_CRIT, APR_SUCCESS, server_conf,
1316                          "Child %d: WAIT_TIMEOUT -- shutting down server", my_pid);
1317             break;
1318         }
1319         else if (cld == 0) {
1320             /* Exit event was signaled */
1321             ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1322                          "Child %d: Exit event signaled. Child process is ending.", my_pid);
1323             break;
1324         }
1325         else {
1326             /* Child maintenance event signaled */
1327             if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1328                 create_listeners();
1329             }
1330             ResetEvent(maintenance_event);
1331             ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1332                          "Child %d: Child maintenance event signaled.", my_pid);
1333         }
1334     }
1335
1336     /* Setting is_graceful will close keep-alive connections */
1337     is_graceful = 1;
1338
1339     /* Shutdown the worker threads */
1340     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1341         /* workers_may_exit = 1; Not used on Win9x */
1342         shutdown_in_progress = 1;
1343         for (i = 0; i < nthreads; i++) {
1344             add_job(-1);
1345         }
1346     }
1347     else { /* Windows NT/2000 */
1348         SOCKET nsd;
1349         ap_listen_rec *lr;
1350         /*
1351          * Setting shutdown_in_progress prevents new AcceptEx completion 
1352          * contexts from being queued to the port but allows threads to 
1353          * continue consuming from the port. This gives the server a 
1354          * chance to handle any accepted connections.
1355          */
1356         shutdown_in_progress = 1;
1357         Sleep(1000);
1358         
1359         /* Setting workers_may_exit prevents threads from consumimg from the 
1360          * completion port (especially threads that unblock off of keep-alive
1361          * connections later on).
1362          */
1363         workers_may_exit = 1;
1364
1365         /* Unblock threads blocked on the completion port */
1366         apr_lock(allowed_globals.jobmutex);
1367         while (g_blocked_threads > 0) {
1368             ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1369                          "Child %d: %d threads blocked on the completion port", my_pid, g_blocked_threads);
1370             for (i=g_blocked_threads; i > 0; i--) {
1371                 PostQueuedCompletionStatus(AcceptExCompPort, 0, my_pid, NULL);
1372             }
1373             Sleep(1000);
1374         }
1375         apr_unlock(allowed_globals.jobmutex);
1376
1377         /* Cancel any remaining pending AcceptEx completion contexts */
1378         for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1379             apr_get_os_sock(&nsd,lr->sd);
1380             CancelIo((HANDLE) nsd);
1381         }
1382
1383         /* Drain the canceled contexts off the port */
1384         drain_acceptex_complport(AcceptExCompPort, TRUE);
1385     }
1386
1387     /* Release the start_mutex to let the new process (in the restart
1388      * scenario) a chance to begin servicing requests 
1389      */
1390     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1391                  "Child %d: Releasing the start mutex", my_pid);
1392     apr_unlock(start_mutex);
1393
1394     /* Give busy worker threads a chance to service their connections.
1395      * Kill them off if they take too long
1396      */
1397     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1398                  "Child %d: Waiting for %d threads to die.", my_pid, nthreads);
1399     end_time = time(NULL) + 180;
1400     while (nthreads) {
1401         rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1402         if (rv != WAIT_TIMEOUT) {
1403             rv = rv - WAIT_OBJECT_0;
1404             ap_assert((rv >= 0) && (rv < nthreads));
1405             cleanup_thread(child_handles, &nthreads, rv);
1406             continue;
1407         }
1408         break;
1409     }
1410     for (i = 0; i < nthreads; i++) {
1411         TerminateThread(child_handles[i], 1);
1412         CloseHandle(child_handles[i]);
1413     }
1414     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1415                  "Child %d: All worker threads have ended.", my_pid);
1416
1417     CloseHandle(AcceptExCompPort);
1418     destroy_semaphore(allowed_globals.jobsemaphore);
1419     apr_destroy_lock(allowed_globals.jobmutex);
1420
1421     apr_destroy_pool(pchild);
1422     CloseHandle(exit_event);
1423 }
1424
1425 /*
1426  * Spawn a child Apache process. The child process has the command line arguments from
1427  * argc and argv[], plus a -Z argument giving the name of an event. The child should
1428  * open and poll or wait on this event. When it is signalled, the child should die.
1429  * prefix is a prefix string for the event name.
1430  * 
1431  * The child_num argument on entry contains a serial number for this child (used to create
1432  * a unique event name). On exit, this number will have been incremented by one, ready
1433  * for the next call. 
1434  *
1435  * On exit, the value pointed to be *ev will contain the event created
1436  * to signal the new child process.
1437  *
1438  * The return value is the handle to the child process if successful, else -1. If -1 is
1439  * returned the error will already have been logged by ap_log_error().
1440  */
1441
1442 /**********************************************************************
1443  * master_main - this is the parent (main) process. We create a
1444  * child process to do the work, then sit around waiting for either
1445  * the child to exit, or a restart or exit signal. If the child dies,
1446  * we just respawn a new one. If we have a shutdown or graceful restart,
1447  * tell the child to die when it is ready. If it is a non-graceful
1448  * restart, force the child to die immediately.
1449  **********************************************************************/
1450
1451 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1452
1453 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1454 {
1455     int i;
1456     int handle = 0;
1457
1458     CloseHandle(handles[position]);
1459     CloseHandle(events[position]);
1460
1461     handle = (int)handles[position];
1462
1463     for (i = position; i < (*processes)-1; i++) {
1464         handles[i] = handles[i + 1];
1465         events[i] = events[i + 1];
1466     }
1467     (*processes)--;
1468 }
1469
1470 static int create_process(apr_pool_t *p, HANDLE *handles, HANDLE *events, int *processes)
1471 {
1472     int rv;
1473     char buf[1024];
1474     char *pCommand;
1475     char *pEnvVar;
1476     char *pEnvBlock;
1477     int i;
1478     int iEnvBlockLen;
1479     STARTUPINFO si;           /* Filled in prior to call to CreateProcess */
1480     PROCESS_INFORMATION pi;   /* filled in on call to CreateProcess */
1481
1482     ap_listen_rec *lr;
1483     DWORD BytesWritten;
1484     HANDLE hPipeRead = NULL;
1485     HANDLE hPipeWrite = NULL;
1486     SECURITY_ATTRIBUTES sa = {0};  
1487
1488     HANDLE kill_event;
1489     LPWSAPROTOCOL_INFO  lpWSAProtocolInfo;
1490     HANDLE hDupedCompPort;
1491
1492     sa.nLength = sizeof(sa);
1493     sa.bInheritHandle = TRUE;
1494     sa.lpSecurityDescriptor = NULL;
1495
1496     /* Build the command line. Should look something like this:
1497      * C:/apache/bin/apache.exe -f ap_server_confname 
1498      * First, get the path to the executable...
1499      */
1500     rv = GetModuleFileName(NULL, buf, sizeof(buf));
1501     if (rv == sizeof(buf)) {
1502         ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1503                      "Parent: Path to Apache process too long");
1504         return -1;
1505     } else if (rv == 0) {
1506         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1507                      "Parent: GetModuleFileName() returned NULL for current process.");
1508         return -1;
1509     }
1510
1511     /* Build the command line */
1512     pCommand = apr_psprintf(p, "\"%s\"", buf);  
1513     for (i = 1; i < server_conf->process->argc; i++) {
1514         pCommand = apr_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1515     }
1516
1517     /* Build the environment, since Win9x disrespects the active env */
1518     pEnvVar = apr_psprintf(p, "AP_PARENT_PID=%i", parent_pid);
1519     /*
1520      * Win32's CreateProcess call requires that the environment
1521      * be passed in an environment block, a null terminated block of
1522      * null terminated strings.
1523      */  
1524     i = 0;
1525     iEnvBlockLen = 1;
1526     while (_environ[i]) {
1527         iEnvBlockLen += strlen(_environ[i]) + 1;
1528         i++;
1529     }
1530
1531     pEnvBlock = (char *)apr_pcalloc(p, iEnvBlockLen + strlen(pEnvVar) + 1);
1532     strcpy(pEnvBlock, pEnvVar);
1533     pEnvVar = strchr(pEnvBlock, '\0') + 1;
1534
1535     i = 0;
1536     while (_environ[i]) {
1537         strcpy(pEnvVar, _environ[i]);
1538         pEnvVar = strchr(pEnvVar, '\0') + 1;
1539         i++;
1540     }
1541     pEnvVar = '\0';
1542     /* Create a pipe to send socket info to the child */
1543     if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1544         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1545                      "Parent: Unable to create pipe to child process.");
1546         return -1;
1547     }
1548
1549     /* Give the read end of the pipe (hPipeRead) to the child as stdin. The 
1550      * parent will write the socket data to the child on this pipe.
1551      */
1552     memset(&si, 0, sizeof(si));
1553     memset(&pi, 0, sizeof(pi));
1554     si.cb = sizeof(si);
1555     si.dwFlags     = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1556     si.wShowWindow = SW_HIDE;
1557     si.hStdInput   = hPipeRead;
1558
1559     if (!CreateProcess(NULL, pCommand, NULL, NULL, 
1560                        TRUE,               /* Inherit handles */
1561                        CREATE_SUSPENDED,   /* Creation flags */
1562                        pEnvBlock,          /* Environment block */
1563                        NULL,
1564                        &si, &pi)) {
1565         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1566                      "Parent: Not able to create the child process.");
1567         /*
1568          * We must close the handles to the new process and its main thread
1569          * to prevent handle and memory leaks.
1570          */ 
1571         CloseHandle(pi.hProcess);
1572         CloseHandle(pi.hThread);
1573         return -1;
1574     }
1575     
1576     ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1577                  "Parent: Created child process %d", pi.dwProcessId);
1578
1579     SetEnvironmentVariable("AP_PARENT_PID",NULL);
1580
1581     /* Create the exit_event, apCchild_pid */
1582     sa.nLength = sizeof(sa);
1583     sa.bInheritHandle = TRUE;
1584     sa.lpSecurityDescriptor = NULL;        
1585     kill_event = CreateEvent(&sa, TRUE, FALSE, apr_psprintf(pconf,"apC%d", pi.dwProcessId));
1586     if (!kill_event) {
1587         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1588                      "Parent: Could not create exit event for child process");
1589         CloseHandle(pi.hProcess);
1590         CloseHandle(pi.hThread);
1591         return -1;
1592     }
1593     
1594     /* Assume the child process lives. Update the process and event tables */
1595     handles[*processes] = pi.hProcess;
1596     events[*processes] = kill_event;
1597     (*processes)++;
1598
1599     /* We never store the thread's handle, so close it now. */
1600     ResumeThread(pi.hThread);
1601     CloseHandle(pi.hThread);
1602  
1603     /* Run the chain of open sockets. For each socket, duplicate it 
1604      * for the target process then send the WSAPROTOCOL_INFO 
1605      * (returned by dup socket) to the child */
1606     for (lr = ap_listeners; lr; lr = lr->next) {
1607         int nsd;
1608         lpWSAProtocolInfo = apr_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1609         apr_get_os_sock(&nsd,lr->sd);
1610         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1611                      "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1612         if (WSADuplicateSocket(nsd, pi.dwProcessId,
1613                                lpWSAProtocolInfo) == SOCKET_ERROR) {
1614             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), server_conf,
1615                          "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1616             return -1;
1617         }
1618
1619         if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1620                        &BytesWritten,
1621                        (LPOVERLAPPED) NULL)) {
1622             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1623                          "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1624             return -1;
1625         }
1626         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_DEBUG, APR_SUCCESS, server_conf,
1627                      "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1628     }
1629     if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1630         /* Now, send the AcceptEx completion port to the child */
1631         if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort, 
1632                              pi.hProcess, &hDupedCompPort,  0,
1633                              TRUE, DUPLICATE_SAME_ACCESS)) {
1634             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1635                          "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1636             return -1;
1637         }
1638
1639         WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1640     }
1641     
1642     CloseHandle(hPipeRead);
1643     CloseHandle(hPipeWrite);        
1644
1645     return 0;
1646 }
1647
1648 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1649 {
1650     int remaining_children_to_start = ap_daemons_to_start;
1651     int i;
1652     int rv, cld;
1653     int child_num = 0;
1654     int restart_pending = 0;
1655     int shutdown_pending = 0;
1656     int current_live_processes = 0; /* number of child process we know about */
1657
1658     HANDLE process_handles[MAX_PROCESSES];
1659     HANDLE process_kill_events[MAX_PROCESSES];
1660
1661     setup_listeners(s);
1662     bind_listeners_to_completion_port();
1663
1664     /* Create child process 
1665      * Should only be one in this version of Apache for WIN32 
1666      */
1667     while (remaining_children_to_start--) {
1668         if (create_process(pconf, process_handles, process_kill_events, 
1669                            &current_live_processes) < 0) {
1670             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1671                          "master_main: create child process failed. Exiting.");
1672             shutdown_pending = 1;
1673             goto die_now;
1674         }
1675     }
1676     
1677     restart_pending = shutdown_pending = 0;
1678
1679     if (!strcasecmp(signal_arg, "runservice"))
1680         mpm_service_started();
1681
1682     /* Wait for shutdown or restart events or for child death */
1683     process_handles[current_live_processes] = shutdown_event;
1684     process_handles[current_live_processes+1] = restart_event;
1685
1686     rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles, 
1687                                 FALSE, INFINITE);
1688     cld = rv - WAIT_OBJECT_0;
1689     if (rv == WAIT_FAILED) {
1690         /* Something serious is wrong */
1691         ap_log_error(APLOG_MARK,APLOG_CRIT, apr_get_os_error(), server_conf,
1692                      "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1693         shutdown_pending = 1;
1694     }
1695     else if (rv == WAIT_TIMEOUT) {
1696         /* Hey, this cannot happen */
1697         ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1698                      "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1699         shutdown_pending = 1;
1700     }
1701     else if (cld == current_live_processes) {
1702         /* shutdown_event signalled */
1703         shutdown_pending = 1;
1704         printf("shutdown event signaled\n");
1705         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s, 
1706                      "Parent: SHUTDOWN EVENT SIGNALED -- Shutting down the server.");
1707         if (ResetEvent(shutdown_event) == 0) {
1708             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1709                          "ResetEvent(shutdown_event)");
1710         }
1711
1712     }
1713     else if (cld == current_live_processes+1) {
1714         /* restart_event signalled */
1715         int children_to_kill = current_live_processes;
1716         restart_pending = 1;
1717         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, s, 
1718                      "Parent: RESTART EVENT SIGNALED -- Restarting the server.");
1719         if (ResetEvent(restart_event) == 0) {
1720             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1721                          "master_main: ResetEvent(restart_event) failed.");
1722         }
1723         /* Signal each child process to die 
1724          * We are making a big assumption here that the child process, once signaled,
1725          * will REALLY go away. Since this is a restart, we do not want to hold the 
1726          * new child process up waiting for the old child to die. Remove the old 
1727          * child out of the process_handles apr_table_t and hope for the best...
1728          */
1729         for (i = 0; i < children_to_kill; i++) {
1730             if (SetEvent(process_kill_events[i]) == 0)
1731                 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1732                              "master_main: SetEvent for child process in slot #%d failed", i);
1733             cleanup_process(process_handles, process_kill_events, i, &current_live_processes);
1734         }
1735     } 
1736     else {
1737         /* A child process must have exited because of a fatal error condition (seg fault, etc.). 
1738          * Remove the dead process 
1739          * from the process_handles and process_kill_events apr_table_t and create a new
1740          * child process.
1741          * TODO: Consider restarting the child immediately without looping through http_main
1742          * and without rereading the configuration. Will need this if we ever support multiple 
1743          * children. One option, create a parent thread which waits on child death and restarts it.
1744          * Consider, however, that if the user makes httpd.conf invalid, we want to die before
1745          * our child tries it... otherwise we have a nasty loop.
1746          */
1747         restart_pending = 1;
1748         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf, 
1749                      "Parent: CHILD PROCESS FAILED -- Restarting the child process.");
1750         ap_assert(cld < current_live_processes);
1751         cleanup_process(process_handles, process_kill_events, cld, &current_live_processes);
1752         /* APD2("main_process: child in slot %d died", rv); */
1753         /* restart_child(process_hancles, process_kill_events, cld, &current_live_processes); */
1754
1755         /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead 
1756          * process. */
1757         drain_acceptex_complport(AcceptExCompPort, FALSE);
1758     }
1759
1760 die_now:
1761     if (shutdown_pending) 
1762     {
1763         int tmstart = time(NULL);
1764         
1765         if (strcasecmp(signal_arg, "runservice")) {
1766             mpm_service_stopping();
1767         }
1768         /* Signal each child processes to die */
1769         for (i = 0; i < current_live_processes; i++) {
1770             printf("SetEvent handle = %d\n", process_kill_events[i]);
1771             if (SetEvent(process_kill_events[i]) == 0)
1772                 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
1773                              "master_main: SetEvent for child process in slot #%d failed", i);
1774         }
1775
1776         while (current_live_processes && ((tmstart+60) > time(NULL))) {
1777             rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1778             if (rv == WAIT_TIMEOUT)
1779                 continue;
1780             ap_assert(rv != WAIT_FAILED);
1781             cld = rv - WAIT_OBJECT_0;
1782             ap_assert(rv < current_live_processes);
1783             cleanup_process(process_handles, process_kill_events, cld, &current_live_processes);
1784         }
1785         for (i = 0; i < current_live_processes; i++) {
1786             ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1787                          "Parent: Forcing termination of child #%d (handle %d)", i, process_handles[i]);
1788             TerminateProcess((HANDLE) process_handles[i], 1);
1789         }
1790         return 0;  /* Tell the caller we do not want to restart */
1791     }
1792
1793     return 1;      /* Tell the caller we want a restart */
1794 }
1795
1796
1797 #define SERVICE_UNNAMED (-1)
1798
1799 /* service_nt_main_fn needs to append the StartService() args 
1800  * outside of our call stack and thread as the service starts...
1801  */
1802 apr_array_header_t *mpm_new_argv;
1803
1804 /* Remember service_to_start failures to log and fail in pre_config.
1805  * Remember inst_argc and inst_argv for installing or starting the
1806  * service after we preflight the config.
1807  */
1808
1809 static apr_status_t service_to_start_success;
1810 static int inst_argc;
1811 static const char * const *inst_argv;
1812     
1813 void winnt_rewrite_args(process_rec *process) 
1814 {
1815     /* Handle the following SCM aspects in this phase:
1816      *
1817      *   -k runservice [transition for WinNT, nothing for Win9x]
1818      *   -k (!)install [error out if name is not installed]
1819      *
1820      * We can't leave this phase until we know our identity
1821      * and modify the command arguments appropriately.
1822      */
1823     apr_status_t service_named = SERVICE_UNNAMED;
1824     apr_status_t rv;
1825     char *def_server_root;
1826     char fnbuf[MAX_PATH];
1827     char optbuf[3];
1828     const char *optarg;
1829     int fixed_args;
1830     int pid;
1831     apr_getopt_t *opt;
1832     int running_as_service = 1;
1833
1834     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1835     GetVersionEx(&osver);
1836
1837     /* AP_PARENT_PID is only valid in the child */
1838     pid = ap_exists_config_define("AP_PARENT_PID");
1839     if (pid) 
1840     {
1841         /* This is the child */
1842         my_pid = GetCurrentProcessId();
1843
1844         /* The parent is responsible for providing the
1845          * COMPLETE ARGUMENTS REQUIRED to the child.
1846          *
1847          * No further argument parsing is needed, but
1848          * for good measure we will provide a simple
1849          * signal string for later testing.
1850          */
1851         signal_arg = "runchild";
1852         return;
1853     }
1854     
1855     /* This is the parent, we have a long way to go :-) */
1856     parent_pid = my_pid = GetCurrentProcessId();
1857     
1858     /* Rewrite process->argv[]; 
1859      *
1860      * strip out -k signal into signal_arg
1861      * strip out -n servicename into service_name & display_name
1862      * add default -d serverroot from the path of this executable
1863      * 
1864      * The end result will look like:
1865      *
1866      * The invocation command (%0)
1867      *     The -d serverroot default from the running executable
1868      *         The requested service's (-n) registry ConfigArgs
1869      *             The WinNT SCM's StartService() args
1870      */
1871     if (!GetModuleFileName(NULL, fnbuf, sizeof(fnbuf))) {
1872         rv = apr_get_os_error();
1873         ap_log_error(APLOG_MARK,APLOG_ERR, rv, NULL, 
1874                      "Failed to get the path of Apache.exe");
1875         exit(1);
1876     }
1877     /* WARNING: There is an implict assumption here that the
1878      * executable resides in ServerRoot or ServerRoot\bin
1879      */
1880     def_server_root = (char *) apr_filename_of_pathname(fnbuf);
1881     if (def_server_root > fnbuf) {
1882         *(def_server_root - 1) = '\0';
1883         def_server_root = (char *) apr_filename_of_pathname(fnbuf);
1884         if (!strcasecmp(def_server_root, "bin"))
1885             *(def_server_root - 1) = '\0';
1886     }
1887     def_server_root = ap_os_canonical_filename(process->pool, fnbuf);
1888
1889     /* Use process->pool so that the rewritten argv
1890      * lasts for the lifetime of the server process,
1891      * because pconf will be destroyed after the 
1892      * initial pre-flight of the config parser.
1893      */
1894     mpm_new_argv = apr_make_array(process->pool, process->argc + 2,
1895                                   sizeof(const char *));
1896     *(const char **)apr_push_array(mpm_new_argv) = process->argv[0];
1897     *(const char **)apr_push_array(mpm_new_argv) = "-d";
1898     *(const char **)apr_push_array(mpm_new_argv) = def_server_root;
1899
1900     fixed_args = mpm_new_argv->nelts;
1901
1902     optbuf[0] = '-';
1903     optbuf[2] = '\0';
1904     apr_initopt(&opt, process->pool, process->argc, (char**) process->argv);
1905     while (apr_getopt(opt, "n:k:iu" AP_SERVER_BASEARGS, 
1906                       optbuf + 1, &optarg) == APR_SUCCESS) {
1907         switch (optbuf[1]) {
1908         case 'n':
1909             service_named = mpm_service_set_name(process->pool, optarg);
1910             break;
1911         case 'k':
1912             signal_arg = optarg;
1913             break;
1914         case 'i':
1915             ap_log_error(APLOG_MARK,APLOG_WARNING, 0, NULL,
1916                 "-i is deprecated.  Use -k install.");
1917             signal_arg = "install";
1918             break;
1919         case 'u':
1920             ap_log_error(APLOG_MARK,APLOG_WARNING, 0, NULL,
1921                 "-u is deprecated.  Use -k uninstall.");
1922             signal_arg = "uninstall";
1923             break;
1924         default:
1925             *(const char **)apr_push_array(mpm_new_argv) =
1926                 apr_pstrdup(process->pool, optbuf);
1927
1928             if (optarg) {
1929                 *(const char **)apr_push_array(mpm_new_argv) = optarg;
1930             }
1931             break;
1932         }
1933     }
1934     
1935     /* Track the number of args actually entered by the user */
1936     inst_argc = mpm_new_argv->nelts - fixed_args;
1937
1938     /* Provide a default 'run' -k arg to simplify signal_arg tests */
1939     if (!signal_arg)
1940     {
1941         signal_arg = "run";
1942         running_as_service = 0;
1943     }
1944
1945     if (!strcasecmp(signal_arg, "runservice")) 
1946     {
1947         /* Start the NT Service _NOW_ because the WinNT SCM is 
1948          * expecting us to rapidly assume control of our own 
1949          * process, the SCM will tell us our service name, and
1950          * may have extra StartService() command arguments to
1951          * add for us.
1952          *
1953          * Any other process has a console, so we don't to begin
1954          * a Win9x service until the configuration is parsed and
1955          * any command line errors are reported.
1956          *
1957          * We hold the return value so that we can die in pre_config
1958          * after logging begins, and the failure can land in the log.
1959          */
1960         if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) {
1961             service_to_start_success = mpm_service_to_start();
1962             if (service_to_start_success == APR_SUCCESS)
1963                 service_named = APR_SUCCESS;
1964         }
1965     }
1966
1967     if (service_named == SERVICE_UNNAMED && running_as_service) {
1968         service_named = mpm_service_set_name(process->pool, 
1969                                              DEFAULT_SERVICE_NAME);
1970     }
1971
1972     if (!strcasecmp(signal_arg, "install")) /* -k install */
1973     {
1974         if (service_named == APR_SUCCESS) 
1975         {
1976             ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
1977                  "%s: Service is already installed.", display_name);
1978             exit(1);
1979         }
1980     }
1981     else if (running_as_service)
1982     {
1983         if (service_named == APR_SUCCESS) 
1984         {
1985             rv = mpm_merge_service_args(process->pool, mpm_new_argv, 
1986                                         fixed_args);
1987             if (rv == APR_SUCCESS) {
1988                 ap_log_error(APLOG_MARK,APLOG_NOERRNO|APLOG_INFO, 0, NULL,
1989                              "Using ConfigArgs of the installed service "
1990                              "\"%s\".", display_name);
1991             }
1992             else  {
1993                 ap_log_error(APLOG_MARK,APLOG_INFO, rv, NULL,
1994                              "No installed ConfigArgs for the service "
1995                              "\"%s\", using Apache defaults.", display_name);
1996             }
1997         }
1998         else
1999         {
2000             ap_log_error(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO, 0, NULL,
2001                  "No installed service named \"%s\".", display_name);
2002             exit(1);
2003         }
2004     }
2005     
2006     /* Track the args actually entered by the user.
2007      * These will be used for the -k install parameters, as well as
2008      * for the -k start service override arguments.
2009      */
2010     inst_argv = (const char * const *)mpm_new_argv->elts
2011         + mpm_new_argv->nelts - inst_argc;
2012
2013     process->argc = mpm_new_argv->nelts; 
2014     process->argv = (const char * const *) mpm_new_argv->elts;
2015 }
2016
2017
2018 static void winnt_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp) 
2019 {
2020     /* Handle the following SCM aspects in this phase:
2021      *
2022      *   -k runservice [WinNT errors logged from rewrite_args]
2023      *   -k uninstall
2024      *   -k stop
2025      *
2026      * in these cases we -don't- care if httpd.conf has config errors!
2027      */
2028     apr_status_t rv;
2029
2030     if (ap_exists_config_define("ONE_PROCESS"))
2031         one_process = -1;
2032
2033     if (ap_exists_config_define("ONE_PROCESS"))
2034         one_process = -1;
2035
2036     if (!strcasecmp(signal_arg, "runservice")
2037             && (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
2038             && (service_to_start_success != APR_SUCCESS)) {
2039         ap_log_error(APLOG_MARK,APLOG_ERR, service_to_start_success, NULL, 
2040                      "%s: Unable to start the service manager.",
2041                      display_name);
2042         exit(1);
2043     }
2044
2045     if (!strcasecmp(signal_arg, "uninstall")) {
2046         rv = mpm_service_uninstall();
2047         exit(rv);
2048     }
2049
2050     if (!strcasecmp(signal_arg, "stop")) {
2051         mpm_signal_service(ptemp, 0);
2052         exit(0);
2053     }
2054
2055     ap_listen_pre_config();
2056     ap_daemons_to_start = DEFAULT_NUM_DAEMON;
2057     ap_threads_per_child = DEFAULT_START_THREAD;
2058     ap_pid_fname = DEFAULT_PIDLOG;
2059     max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
2060
2061     apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
2062 }
2063
2064 static void winnt_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec* server)
2065 {
2066     static int restart_num = 0;
2067     apr_status_t rv = 0;
2068
2069     server_conf = server;
2070     
2071     /* Handle the following SCM aspects in this phase:
2072      *
2073      *   -k install
2074      *   -k start
2075      *   -k restart
2076      *   -k runservice [Win95, only once - after we parsed the config]
2077      *
2078      * because all of these signals are useful _only_ if there
2079      * is a valid conf\httpd.conf environment to start.
2080      *
2081      * We reached this phase by avoiding errors that would cause
2082      * these options to fail unexpectedly in another process.
2083      */
2084
2085     if (!strcasecmp(signal_arg, "install")) {
2086         rv = mpm_service_install(ptemp, inst_argc, inst_argv);
2087         exit (rv);
2088     }
2089
2090     if (!strcasecmp(signal_arg, "start")) {
2091         rv = mpm_service_start(ptemp, inst_argc, inst_argv);
2092         exit (rv);
2093     }
2094
2095     if (!strcasecmp(signal_arg, "restart")) {
2096         mpm_signal_service(ptemp, 1);
2097         exit (rv);
2098     }
2099
2100     if (parent_pid == my_pid) 
2101     {
2102         if (restart_num++ == 1) 
2103         {
2104             /* This code should be run once in the parent and not run
2105              * across a restart
2106              */
2107             PSECURITY_ATTRIBUTES sa = GetNullACL();  /* returns NULL if invalid (Win95?) */
2108             setup_signal_names(apr_psprintf(pconf,"ap%d", parent_pid));
2109             if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
2110                 /* Create the AcceptEx IoCompletionPort once in the parent.
2111                  * The completion port persists across restarts. 
2112                  */
2113                 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
2114                                                           NULL,
2115                                                           0,
2116                                                           0); /* CONCURRENT ACTIVE THREADS */
2117                 if (AcceptExCompPort == NULL) {
2118                     ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
2119                                  "Parent: Unable to create the AcceptExCompletionPort -- process will exit");
2120                     exit(1);
2121                 }
2122             }
2123
2124             ap_log_pid(pconf, ap_pid_fname);
2125             
2126             /* Create shutdown event, apPID_shutdown, where PID is the parent 
2127              * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
2128              */
2129             shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
2130             if (!shutdown_event) {
2131                 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
2132                              "Parent: Cannot create shutdown event %s", signal_shutdown_name);
2133                 CleanNullACL((void *)sa);
2134                 exit(1);
2135             }
2136
2137             /* Create restart event, apPID_restart, where PID is the parent 
2138              * Apache process ID. Restart is signaled by 'apache -k restart'.
2139              */
2140             restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
2141             if (!restart_event) {
2142                 CloseHandle(shutdown_event);
2143                 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
2144                              "Parent: Cannot create restart event %s", signal_restart_name);
2145                 CleanNullACL((void *)sa);
2146                 exit(1);
2147             }
2148             CleanNullACL((void *)sa);
2149
2150             /* Now that we are flying at 15000 feet... 
2151              * wipe out the Win95 service console,
2152              * signal the SCM the WinNT service started, or
2153              * if not a service, setup console handlers instead.
2154              */
2155             if (!strcasecmp(signal_arg, "runservice"))
2156             {
2157                 if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT) 
2158                 {
2159                     rv = mpm_service_to_start();
2160                     if (rv != APR_SUCCESS) {
2161                         ap_log_error(APLOG_MARK,APLOG_ERR, rv, server_conf,
2162                                      "%s: Unable to start the service manager.",
2163                                      display_name);
2164                         exit(1);
2165                     }            
2166                 }
2167             }
2168             else /* ! -k runservice */
2169             {
2170                 mpm_start_console_handler();
2171             }
2172
2173             /* Create the start mutex, apPID, where PID is the parent Apache process ID.
2174              * Ths start mutex is used during a restart to prevent more than one 
2175              * child process from entering the accept loop at once.
2176              */
2177             apr_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS, signal_name_prefix,
2178                                server_conf->process->pool);
2179         }
2180     }
2181     else /* parent_pid != my_pid */
2182     {
2183         mpm_start_child_console_handler();
2184     }
2185 }
2186
2187 AP_DECLARE(int) ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s )
2188 {
2189     static int restart = 0;            /* Default is "not a restart" */
2190
2191     pconf = _pconf;
2192     server_conf = s;
2193
2194     if ((parent_pid != my_pid) || one_process) {
2195         /* Running as Child process or in one_process (debug) mode */
2196         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
2197                      "Child %d: Child process is running", my_pid);
2198         child_main();
2199         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
2200                      "Child %d: Child process is exiting", my_pid);        
2201
2202         return 1;
2203     }  /* Child or single process */
2204     else { /* Parent process */
2205         restart = master_main(server_conf, shutdown_event, restart_event);
2206
2207         if (!restart) {
2208             /* Shutting down. Clean up... */
2209             const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
2210
2211             if (pidfile != NULL && unlink(pidfile) == 0) {
2212                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS,
2213                              server_conf, "removed PID file %s (pid=%ld)",
2214                              pidfile, GetCurrentProcessId());
2215             }
2216             apr_destroy_lock(start_mutex);
2217
2218             CloseHandle(restart_event);
2219             CloseHandle(shutdown_event);
2220
2221             return 1;
2222         }
2223     }  /* Parent process */
2224
2225     return 0; /* Restart */
2226 }
2227
2228 static void winnt_hooks(void)
2229 {
2230     ap_hook_pre_config(winnt_pre_config, NULL, NULL, AP_HOOK_MIDDLE);
2231     ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
2232 }
2233
2234 /* 
2235  * Command processors 
2236  */
2237 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg) 
2238 {
2239     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2240     if (err != NULL) {
2241         return err;
2242     }
2243
2244     if (cmd->server->is_virtual) {
2245         return "PidFile directive not allowed in <VirtualHost>";
2246     }
2247     ap_pid_fname = arg;
2248     return NULL;
2249 }
2250
2251 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg) 
2252 {
2253     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2254     if (err != NULL) {
2255         return err;
2256     }
2257
2258     ap_threads_per_child = atoi(arg);
2259     if (ap_threads_per_child > HARD_THREAD_LIMIT) {
2260         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
2261                      "WARNING: ThreadsPerChild of %d exceeds compile time"
2262                      " limit of %d threads,", ap_threads_per_child, 
2263                      HARD_THREAD_LIMIT);
2264         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2265                      " lowering ThreadsPerChild to %d. To increase, please"
2266                      " see the  HARD_THREAD_LIMIT define in %s.", 
2267                      HARD_THREAD_LIMIT, AP_MPM_HARD_LIMITS_FILE);
2268         ap_threads_per_child = HARD_THREAD_LIMIT;
2269     }
2270     else if (ap_threads_per_child < 1) {
2271         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
2272                      "WARNING: Require ThreadsPerChild > 0, setting to 1");
2273         ap_threads_per_child = 1;
2274     }
2275     return NULL;
2276 }
2277
2278
2279 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg) 
2280 {
2281     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2282     if (err != NULL) {
2283         return err;
2284     }
2285
2286     max_requests_per_child = atoi(arg);
2287
2288     return NULL;
2289 }
2290
2291 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg) 
2292 {
2293     apr_finfo_t finfo;
2294     const char *fname;
2295     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2296     if (err != NULL) {
2297         return err;
2298     }
2299
2300     fname = ap_server_root_relative(cmd->pool, arg);
2301     if ((apr_stat(&finfo, fname, cmd->pool) != APR_SUCCESS) || 
2302         (finfo.filetype != APR_DIR)) {
2303         return apr_pstrcat(cmd->pool, "CoreDumpDirectory ", fname, 
2304                           " does not exist or is not a directory", NULL);
2305     }
2306     apr_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
2307     return NULL;
2308 }
2309
2310 /* Stub functions until this MPM supports the connection status API */
2311
2312 AP_DECLARE(void) ap_update_connection_status(long conn_id, const char *key, \
2313                                              const char *value)
2314 {
2315     /* NOP */
2316 }
2317
2318 AP_DECLARE(void) ap_reset_connection_status(long conn_id)
2319 {
2320     /* NOP */
2321 }
2322
2323 AP_DECLARE(apr_array_header_t *) ap_get_status_table(apr_pool_t *p)
2324 {
2325     /* NOP */
2326     return NULL;
2327 }
2328
2329 static const command_rec winnt_cmds[] = {
2330 LISTEN_COMMANDS
2331 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
2332     "A file for logging the server process ID"},
2333 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
2334   "Number of threads each child creates" },
2335 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
2336   "Maximum number of requests a particular child serves before dying." },
2337 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
2338   "The location of the directory Apache changes to before dumping core" },
2339 { NULL }
2340 };
2341
2342 AP_MODULE_DECLARE_DATA module mpm_winnt_module = {
2343     MPM20_MODULE_STUFF,
2344     winnt_rewrite_args,         /* hook to run before apache parses args */
2345     NULL,                       /* create per-directory config structure */
2346     NULL,                       /* merge per-directory config structures */
2347     NULL,                       /* create per-server config structure */
2348     NULL,                       /* merge per-server config structures */
2349     winnt_cmds,                 /* command apr_table_t */
2350     winnt_hooks                 /* register_hooks */
2351 };