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