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