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