]> granicus.if.org Git - apache/blob - server/mpm/winnt/mpm_winnt.c
Eliminate os.c and ApacheOS.dsp, ApacheOS.mak, et. al. Update the winnt
[apache] / server / mpm / winnt / mpm_winnt.c
1 /* ====================================================================
2  * Copyright (c) 1995-2000 The Apache Software Foundation.  All rights reserved.
3  * 
4  * Redistribution and use in source and binary forms, with or without 
5  * modification, are permitted provided that the following conditions 
6  * are met: 
7  * 
8  * 1. Redistributions of source code must retain the above copyright 
9  *    notice, this list of conditions and the following disclaimer.  
10  * 
11  * 2. Redistributions in binary form must reproduce the above copyright 
12  *    notice, this list of conditions and the following disclaimer in 
13  *    the documentation and/or other materials provided with the 
14  *    distribution. 
15  * 
16  * 3. All advertising materials mentioning features or use of this 
17  *    software must display the following acknowledgment: 
18  *    "This product includes software developed by the Apache Software Foundation 
19  *    for use in the Apache HTTP server project (http://www.apache.org/)." 
20  * 
21  * 4. The names "Apache Server" and "Apache Software Foundation" must not be used to 
22  *    endorse or promote products derived from this software without 
23  *    prior written permission. For written permission, please contact 
24  *    apache@apache.org. 
25  * 
26  * 5. Products derived from this software may not be called "Apache" 
27  *    nor may "Apache" appear in their names without prior written 
28  *    permission of the Apache Software Foundation. 
29  * 
30  * 6. Redistributions of any form whatsoever must retain the following 
31  *    acknowledgment: 
32  *    "This product includes software developed by the Apache Software Foundation 
33  *    for use in the Apache HTTP server project (http://www.apache.org/)." 
34  * 
35  * THIS SOFTWARE IS PROVIDED BY THE Apache Software Foundation ``AS IS'' AND ANY 
36  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
38  * PURPOSE ARE 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 
41  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
42  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
43  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
44  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
45  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
46  * OF THE POSSIBILITY OF SUCH DAMAGE. 
47  * ==================================================================== 
48  * 
49  * This software consists of voluntary contributions made by many 
50  * individuals on behalf of the Apache Software Foundation and was originally based 
51  * on public domain software written at the National Center for 
52  * Supercomputing Applications, University of Illinois, Urbana-Champaign. 
53  * For more information on the Apache Software Foundation and the Apache HTTP server 
54  * project, please see <http://www.apache.org/>. 
55  * 
56  */ 
57  
58 #define CORE_PRIVATE 
59 #include "apr_portable.h"
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 "ap_mpm.h"
67 #include "ap_config.h"
68 #include "ap_listen.h"
69 #include "mpm_default.h"
70 #include "service.h"
71 #include "iol_socket.h"
72 #include "winnt.h"
73
74
75 /*
76  * Definitions of WINNT MPM specific config globals
77  */
78
79 static char *ap_pid_fname = NULL;
80 static int ap_threads_per_child = 0;
81 static int workers_may_exit = 0;
82 static int max_requests_per_child = 0;
83
84 static struct fd_set listenfds;
85 static int num_listenfds = 0;
86 static SOCKET listenmaxfd = INVALID_SOCKET;
87
88 static ap_context_t *pconf;             /* Pool for config stuff */
89
90 static char ap_coredump_dir[MAX_STRING_LEN];
91
92 static server_rec *server_conf;
93 static HANDLE AcceptExCompPort = NULL;
94
95 static int one_process = 0;
96
97 static OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
98
99 int ap_max_requests_per_child=0;
100 int ap_daemons_to_start=0;
101
102 static event *exit_event;
103 ap_lock_t *start_mutex;
104 int my_pid;
105 int parent_pid;
106
107 static ap_status_t socket_cleanup(void *sock)
108 {
109     struct socket_t *thesocket = sock;
110     SOCKET sd;
111     if (ap_get_os_sock(&sd, thesocket) == APR_SUCCESS) {
112         closesocket(sd);
113     }
114     return APR_SUCCESS;
115 }
116
117 /* A bunch or routines from os/win32/multithread.c that need to be merged into APR
118  * or thrown out entirely...
119  */
120
121 static int
122 map_rv(int rv)
123 {
124     switch(rv)
125     {
126     case WAIT_OBJECT_0:
127     case WAIT_ABANDONED:
128         return(MULTI_OK);
129     case WAIT_TIMEOUT:
130         return(MULTI_TIMEOUT);
131     case WAIT_FAILED:
132         return(MULTI_ERR);
133     default:
134         ap_assert(0);
135     }
136
137     ap_assert(0);
138     return(0);
139 }
140
141 typedef void semaphore;
142 typedef void event;
143
144 static semaphore *
145 create_semaphore(int initial)
146 {
147     return(CreateSemaphore(NULL, initial, 1000000, NULL));
148 }
149
150 static int acquire_semaphore(semaphore *semaphore_id)
151 {
152     int rv;
153     
154     rv = WaitForSingleObject(semaphore_id, INFINITE);
155     
156     return(map_rv(rv));
157 }
158
159 static int release_semaphore(semaphore *semaphore_id)
160 {
161     return(ReleaseSemaphore(semaphore_id, 1, NULL));
162 }
163
164 static void destroy_semaphore(semaphore *semaphore_id)
165 {
166     CloseHandle(semaphore_id);
167 }
168
169
170 /* To share the semaphores with other processes, we need a NULL ACL
171  * Code from MS KB Q106387
172  */
173 static PSECURITY_ATTRIBUTES GetNullACL()
174 {
175     PSECURITY_DESCRIPTOR pSD;
176     PSECURITY_ATTRIBUTES sa;
177
178     sa  = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES));
179     pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,
180                                             SECURITY_DESCRIPTOR_MIN_LENGTH);
181     if (pSD == NULL || sa == NULL) {
182         return NULL;
183     }
184     if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
185         || GetLastError()) {
186         LocalFree( pSD );
187         LocalFree( sa );
188         return NULL;
189     }
190     if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
191         || GetLastError()) {
192         LocalFree( pSD );
193         LocalFree( sa );
194         return NULL;
195     }
196     sa->nLength = sizeof(sa);
197     sa->lpSecurityDescriptor = pSD;
198     sa->bInheritHandle = TRUE;
199     return sa;
200 }
201
202 static void CleanNullACL( void *sa ) {
203     if( sa ) {
204         LocalFree( ((PSECURITY_ATTRIBUTES)sa)->lpSecurityDescriptor);
205         LocalFree( sa );
206     }
207 }
208
209 /*
210  * The Win32 call WaitForMultipleObjects will only allow you to wait for 
211  * a maximum of MAXIMUM_WAIT_OBJECTS (current 64).  Since the threading 
212  * model in the multithreaded version of apache wants to use this call, 
213  * we are restricted to a maximum of 64 threads.  This is a simplistic 
214  * routine that will increase this size.
215  */
216 static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles, 
217                                    DWORD dwSeconds)
218 {
219     time_t tStopTime;
220     DWORD dwRet = WAIT_TIMEOUT;
221     DWORD dwIndex=0;
222     BOOL bFirst = TRUE;
223   
224     tStopTime = time(NULL) + dwSeconds;
225   
226     do {
227         if (!bFirst)
228             Sleep(1000);
229         else
230             bFirst = FALSE;
231           
232         for (dwIndex = 0; dwIndex * MAXIMUM_WAIT_OBJECTS < nCount; dwIndex++) {
233             dwRet = WaitForMultipleObjects( 
234                 min(MAXIMUM_WAIT_OBJECTS, nCount - (dwIndex * MAXIMUM_WAIT_OBJECTS)),
235                 lpHandles + (dwIndex * MAXIMUM_WAIT_OBJECTS), 
236                 0, 0);
237                                            
238             if (dwRet != WAIT_TIMEOUT) {                                          
239               break;
240             }
241         }
242     } while((time(NULL) < tStopTime) && (dwRet == WAIT_TIMEOUT));
243     
244     return dwRet;
245 }
246
247 /*
248  * Signalling Apache on NT.
249  *
250  * Under Unix, Apache can be told to shutdown or restart by sending various
251  * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
252  * we use "events" instead. The parent apache process goes into a loop
253  * where it waits forever for a set of events. Two of those events are
254  * called
255  *
256  *    apPID_shutdown
257  *    apPID_restart
258  *
259  * (where PID is the PID of the apache parent process). When one of these
260  * is signalled, the Apache parent performs the appropriate action. The events
261  * can become signalled through internal Apache methods (e.g. if the child
262  * finds a fatal error and needs to kill its parent), via the service
263  * control manager (the control thread will signal the shutdown event when
264  * requested to stop the Apache service), from the -k Apache command line,
265  * or from any external program which finds the Apache PID from the
266  * httpd.pid file.
267  *
268  * The signal_parent() function, below, is used to signal one of these events.
269  * It can be called by any child or parent process, since it does not
270  * rely on global variables.
271  *
272  * On entry, type gives the event to signal. 0 means shutdown, 1 means 
273  * graceful restart.
274  */
275 static void signal_parent(int type)
276 {
277     HANDLE e;
278     char *signal_name;
279     extern char signal_shutdown_name[];
280     extern char signal_restart_name[];
281
282     /* after updating the shutdown_pending or restart flags, we need
283      * to wake up the parent process so it can see the changes. The
284      * parent will normally be waiting for either a child process
285      * to die, or for a signal on the "spache-signal" event. So set the
286      * "apache-signal" event here.
287      */
288     if (one_process) {
289         return;
290     }
291
292     switch(type) {
293     case 0: signal_name = signal_shutdown_name; break;
294     case 1: signal_name = signal_restart_name; break;
295     default: return;
296     }
297     e = OpenEvent(EVENT_ALL_ACCESS, FALSE, signal_name);
298     if (!e) {
299         /* Um, problem, can't signal the parent, which means we can't
300          * signal ourselves to die. Ignore for now...
301          */
302         ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
303                      "OpenEvent on %s event", signal_name);
304         return;
305     }
306     if (SetEvent(e) == 0) {
307         /* Same problem as above */
308         ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
309                      "SetEvent on %s event", signal_name);
310         CloseHandle(e);
311         return;
312     }
313     CloseHandle(e);
314 }
315 static int volatile is_graceful = 0;
316 API_EXPORT(int) ap_graceful_stop_signalled(void)
317 {
318     return is_graceful;
319 }
320 void ap_start_shutdown(void)
321 {
322     signal_parent(0);
323 }
324 /*
325  * Initialise the signal names, in the global variables signal_name_prefix, 
326  * signal_restart_name and signal_shutdown_name.
327  */
328
329 #define MAX_SIGNAL_NAME 30  /* Long enough for apPID_shutdown, where PID is an int */
330 char signal_name_prefix[MAX_SIGNAL_NAME];
331 char signal_restart_name[MAX_SIGNAL_NAME]; 
332 char signal_shutdown_name[MAX_SIGNAL_NAME];
333 static void setup_signal_names(char *prefix)
334 {
335     ap_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);    
336     ap_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name), 
337         "%s_shutdown", signal_name_prefix);    
338     ap_snprintf(signal_restart_name, sizeof(signal_restart_name), 
339         "%s_restart", signal_name_prefix);    
340 }
341
342 /*
343  * Routines that deal with sockets, some are WIN32 specific...
344  */
345 static int s_iInitCount = 0;
346 static int AMCSocketInitialize(void)
347 {
348     int iVersionRequested;
349     WSADATA wsaData;
350     int err;
351
352     if (s_iInitCount > 0) {
353         s_iInitCount++;
354         return (0);
355     }
356     else if (s_iInitCount < 0)
357         return (s_iInitCount);
358
359     /* s_iInitCount == 0. Do the initailization */
360     iVersionRequested = MAKEWORD(2, 0);
361     err = WSAStartup((WORD) iVersionRequested, &wsaData);
362     if (err) {
363         s_iInitCount = -1;
364         return (s_iInitCount);
365     }
366     if (LOBYTE(wsaData.wVersion) != 1 ||
367         HIBYTE(wsaData.wVersion) != 1) {
368         s_iInitCount = -2;
369         WSACleanup();
370         return (s_iInitCount);
371     }
372
373     s_iInitCount++;
374     return (s_iInitCount);
375
376 }
377 static void AMCSocketCleanup(void)
378 {
379     if (--s_iInitCount == 0)
380         WSACleanup();
381     return;
382 }
383
384 static void sock_disable_nagle(int s) 
385 {
386     /* The Nagle algorithm says that we should delay sending partial
387      * packets in hopes of getting more data.  We don't want to do
388      * this; we are not telnet.  There are bad interactions between
389      * persistent connections and Nagle's algorithm that have very severe
390      * performance penalties.  (Failing to disable Nagle is not much of a
391      * problem with simple HTTP.)
392      *
393      * In spite of these problems, failure here is not a shooting offense.
394      */
395     int just_say_no = 1;
396
397     if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
398                    sizeof(int)) < 0) {
399         ap_log_error(APLOG_MARK, APLOG_WARNING, APR_SUCCESS, server_conf,
400                     "setsockopt: (TCP_NODELAY)");
401     }
402 }
403
404 /*
405  * Routines to deal with managing the list of listening sockets.
406  */
407 static ap_listen_rec *head_listener;
408 static ap_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
409 {
410     ap_listen_rec *lr;
411     SOCKET nsd;
412
413     for (lr = head_listener; lr ; lr = lr->next) {
414         ap_get_os_sock(&nsd, lr->sd);
415         if (FD_ISSET(nsd, main_fds)) {
416             head_listener = lr->next;
417             if (head_listener == NULL)
418                 head_listener = ap_listeners;
419
420             return (lr);
421         }
422     }
423     return NULL;
424 }
425 static int setup_listeners(server_rec *s)
426 {
427     ap_listen_rec *lr;
428     int num_listeners = 0;
429     SOCKET nsd;
430
431     /* Setup the listeners */
432     FD_ZERO(&listenfds);
433
434     if (ap_listen_open(s->process, s->port)) {
435        return 0;
436     }
437     for (lr = ap_listeners; lr; lr = lr->next) {
438         num_listeners++;
439         if (lr->sd != NULL) {
440             ap_get_os_sock(&nsd, lr->sd);
441             FD_SET(nsd, &listenfds);
442             if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
443                 listenmaxfd = nsd;
444             }
445         }
446         lr->count = 0;
447     }
448
449     head_listener = ap_listeners;
450
451     return num_listeners;
452 }
453
454 static int setup_inherited_listeners(server_rec *s)
455 {
456     WSAPROTOCOL_INFO WSAProtocolInfo;
457     HANDLE pipe;
458     ap_listen_rec *lr;
459     DWORD BytesRead;
460     int num_listeners = 0;
461     SOCKET nsd;
462
463     /* Setup the listeners */
464     FD_ZERO(&listenfds);
465
466     /* Set up a default listener if necessary */
467
468     if (ap_listeners == NULL) {
469         ap_listen_rec *lr;
470         lr = ap_palloc(s->process->pool, sizeof(ap_listen_rec));
471         if (!lr)
472             return 0;
473         lr->sd = NULL;
474         lr->next = ap_listeners;
475         ap_listeners = lr;
476     }
477
478     /* Open the pipe to the parent process to receive the inherited socket
479      * data. The sockets have been set to listening in the parent process.
480      */
481     pipe = GetStdHandle(STD_INPUT_HANDLE);
482     for (lr = ap_listeners; lr; lr = lr->next) {
483         if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO), 
484                       &BytesRead, (LPOVERLAPPED) NULL)) {
485             ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
486                          "setup_inherited_listeners: Unable to read socket data from parent");
487             signal_parent(0);   /* tell parent to die */
488             exit(1);
489         }
490         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
491                      "Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.", my_pid);
492         nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
493                         &WSAProtocolInfo, 0, 0);
494         if (nsd == INVALID_SOCKET) {
495             ap_log_error(APLOG_MARK, APLOG_CRIT, WSAGetLastError(), server_conf,
496                          "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
497             signal_parent(0);   /* tell parent to die */
498             exit(1);
499         }
500         if (nsd >= 0) {
501             FD_SET(nsd, &listenfds);
502             if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
503                 listenmaxfd = nsd;
504             }
505         }
506 //        ap_register_cleanup(p, (void *)lr->sd, socket_cleanup, ap_null_cleanup);
507         ap_put_os_sock(&lr->sd, &nsd, pconf);
508         lr->count = 0;
509     }
510     /* Now, read the AcceptExCompPort from the parent */
511     ReadFile(pipe, &AcceptExCompPort, sizeof(AcceptExCompPort), &BytesRead, (LPOVERLAPPED) NULL);
512     CloseHandle(pipe);
513
514     for (lr = ap_listeners; lr; lr = lr->next) {
515         num_listeners++;
516     }
517
518     head_listener = ap_listeners;
519     return num_listeners;
520 }
521
522
523 /**********************************************************************
524  * Multithreaded implementation
525  *
526  * This code is fairly specific to Win32.
527  *
528  * The model used to handle requests is a set of threads. One "main"
529  * thread listens for new requests. When something becomes
530  * available, it does a select and places the newly available socket
531  * onto a list of "jobs" (add_job()). Then any one of a fixed number
532  * of "worker" threads takes the top job off the job list with
533  * remove_job() and handles that connection to completion. After
534  * the connection has finished the thread is free to take another
535  * job from the job list.
536  *
537  * In the code, the "main" thread is running within the child_main()
538  * function. The first thing this function does is create the
539  * worker threads, which operate in the child_sub_main() function. The
540  * main thread then goes into a loop within child_main() where they
541  * do a select() on the listening sockets. The select times out once
542  * per second so that the thread can check for an "exit" signal
543  * from the parent process (see below). If this signal is set, the 
544  * thread can exit, but only after it has accepted all incoming
545  * connections already in the listen queue (since Win32 appears
546  * to through away listened but unaccepted connections when a 
547  * process dies).
548  *
549  * Because the main and worker threads exist within a single process
550  * they are vulnerable to crashes or memory leaks (crashes can also
551  * be caused within modules, of course). There also needs to be a 
552  * mechanism to perform restarts and shutdowns. This is done by
553  * creating the main & worker threads within a subprocess. A
554  * main process (the "parent process") creates one (or more) 
555  * processes to do the work, then the parent sits around waiting
556  * for the working process to die, in which case it starts a new
557  * one. The parent process also handles restarts (by creating
558  * a new working process then signalling the previous working process 
559  * exit ) and shutdowns (by signalling the working process to exit).
560  * The parent process operates within the master_main() function. This
561  * process also handles requests from the service manager (NT only).
562  *
563  * Signalling between the parent and working process uses a Win32
564  * event. Each child has a unique name for the event, which is
565  * passed to it with the -Z argument when the child is spawned. The
566  * parent sets (signals) this event to tell the child to die.
567  * At present all children do a graceful die - they finish all
568  * current jobs _and_ empty the listen queue before they exit.
569  * A non-graceful die would need a second event. The -Z argument in
570  * the child is also used to create the shutdown and restart events,
571  * since the prefix (apPID) contains the parent process PID.
572  *
573  * The code below starts with functions at the lowest level -
574  * worker threads, and works up to the top level - the main()
575  * function of the parent process.
576  *
577  * The scoreboard (in process memory) contains details of the worker
578  * threads (within the active working process). There is no shared
579  * "scoreboard" between processes, since only one is ever active
580  * at once (or at most, two, when one has been told to shutdown but
581  * is processes outstanding requests, and a new one has been started).
582  * This is controlled by a "start_mutex" which ensures only one working
583  * process is active at once.
584  **********************************************************************/
585
586
587 /*
588  * Definition of jobs, shared by main and worker threads.
589  */
590
591 typedef struct joblist_s {
592     struct joblist_s *next;
593     int sock;
594 } joblist;
595
596 /*
597  * Globals common to main and worker threads. This structure is not
598  * used by the parent process.
599  */
600
601 typedef struct globals_s {
602     semaphore *jobsemaphore;
603     joblist *jobhead;
604     joblist *jobtail;
605     ap_lock_t *jobmutex;
606     int jobcount;
607 } globals;
608
609 globals allowed_globals =
610 {NULL, NULL, NULL, NULL, 0};
611 #define MAX_SELECT_ERRORS 100
612 #define PADDED_ADDR_SIZE sizeof(SOCKADDR_IN)+16
613
614 /* Windows 9x specific code...
615  * Accept processing for on Windows 95/98 uses a producer/consumer queue 
616  * model. A single thread accepts connections and queues the accepted socket 
617  * to the accept queue for consumption by a pool of worker threads.
618  *
619  * win9x_get_connection()
620  *    Calls remove_job() to pull a job from the accept queue. All the worker 
621  *    threads block on remove_job.
622  * accept_and_queue_connections()
623  *    The accept threads runs this function, which accepts connections off 
624  *    the network and calls add_job() to queue jobs to the accept_queue.
625  * add_job()/remove_job()
626  *    Add or remove an accepted socket from the list of sockets 
627  *    connected to clients. allowed_globals.jobmutex protects
628  *    against multiple concurrent access to the linked list of jobs.
629  */
630 static void add_job(int sock)
631 {
632     joblist *new_job;
633
634     new_job = (joblist *) malloc(sizeof(joblist));
635     if (new_job == NULL) {
636         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
637                      "Ouch!  Out of memory in add_job()!");
638         return;
639     }
640     new_job->next = NULL;
641     new_job->sock = sock;
642
643     ap_lock(allowed_globals.jobmutex);
644
645     if (allowed_globals.jobtail != NULL)
646         allowed_globals.jobtail->next = new_job;
647     allowed_globals.jobtail = new_job;
648     if (!allowed_globals.jobhead)
649         allowed_globals.jobhead = new_job;
650     allowed_globals.jobcount++;
651     release_semaphore(allowed_globals.jobsemaphore);
652
653     ap_unlock(allowed_globals.jobmutex);
654 }
655
656 static int remove_job(void)
657 {
658     joblist *job;
659     int sock;
660
661     acquire_semaphore(allowed_globals.jobsemaphore);
662     ap_lock(allowed_globals.jobmutex);
663
664     if (workers_may_exit && !allowed_globals.jobhead) {
665         ap_unlock(allowed_globals.jobmutex);
666         return (-1);
667     }
668     job = allowed_globals.jobhead;
669     ap_assert(job);
670     allowed_globals.jobhead = job->next;
671     if (allowed_globals.jobhead == NULL)
672         allowed_globals.jobtail = NULL;
673     ap_unlock(allowed_globals.jobmutex);
674     sock = job->sock;
675     free(job);
676
677     return (sock);
678 }
679
680 static void accept_and_queue_connections(void * dummy)
681 {
682     int requests_this_child = 0;
683     struct timeval tv;
684     fd_set main_fds;
685     int wait_time = 1;
686     int csd;
687     int nsd = INVALID_SOCKET;
688     struct sockaddr_in sa_client;
689     int count_select_errors = 0;
690     int rc;
691     int clen;
692
693     while (!workers_may_exit) {
694         if (ap_max_requests_per_child && (requests_this_child > ap_max_requests_per_child)) {
695             break;
696         }
697
698         tv.tv_sec = wait_time;
699         tv.tv_usec = 0;
700         memcpy(&main_fds, &listenfds, sizeof(fd_set));
701
702 //      rc = ap_select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
703         rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
704
705         if (rc == 0 || (rc == SOCKET_ERROR && h_errno == WSAEINTR)) {
706             count_select_errors = 0;    /* reset count of errors */            
707             continue;
708         }
709         else if (rc == SOCKET_ERROR) {
710             /* A "real" error occurred, log it and increment the count of
711              * select errors. This count is used to ensure we don't go into
712              * a busy loop of continuous errors.
713              */
714             ap_log_error(APLOG_MARK, APLOG_INFO, h_errno, server_conf, 
715                          "select failed with errno %d", h_errno);
716             count_select_errors++;
717             if (count_select_errors > MAX_SELECT_ERRORS) {
718                 workers_may_exit = 1;
719                 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
720                              "Too many errors in select loop. Child process exiting.");
721                 break;
722             }
723         } else {
724             ap_listen_rec *lr;
725
726             lr = find_ready_listener(&main_fds);
727             if (lr != NULL) {
728                 /* fetch the native socket descriptor */
729                 ap_get_os_sock(&nsd, lr->sd);
730             }
731         }
732
733         do {
734             clen = sizeof(sa_client);
735             csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
736             if (csd == INVALID_SOCKET) {
737                 csd = -1;
738             }
739         } while (csd < 0 && h_errno == WSAEINTR);
740
741         if (csd < 0) {
742             if (h_errno != WSAECONNABORTED) {
743                 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
744                             "accept: (client socket)");
745             }
746         }
747         else {
748             add_job(csd);
749             requests_this_child++;
750         }
751     }
752     SetEvent(exit_event);
753 }
754 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
755 {
756     int len;
757
758     if (context == NULL) {
759         /* allocate the completion context and the transaction pool */
760         context = ap_pcalloc(pconf, sizeof(COMP_CONTEXT));
761         if (!context) {
762             ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
763                          "win9x_get_connection: ap_pcalloc() failed. Process will exit.");
764             return NULL;
765         }
766         ap_create_context(&context->ptrans, pconf);
767     }
768     
769
770     while (1) {
771         ap_clear_pool(context->ptrans);        
772         context->accept_socket = remove_job();
773         if (context->accept_socket == -1) {
774             return NULL;
775         }
776         //ap_note_cleanups_for_socket(ptrans, csd);
777         len = sizeof(struct sockaddr);
778         context->sa_server = ap_palloc(context->ptrans, len);
779         if (getsockname(context->accept_socket, 
780                         context->sa_server, &len)== SOCKET_ERROR) {
781             ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(), server_conf, 
782                          "getsockname failed");
783             continue;
784         }
785         len = sizeof(struct sockaddr);
786         context->sa_client = ap_palloc(context->ptrans, len);
787         if ((getpeername(context->accept_socket,
788                          context->sa_client, &len)) == SOCKET_ERROR) {
789             ap_log_error(APLOG_MARK, APLOG_WARNING, h_errno, server_conf, 
790                          "getpeername failed with error %d\n", WSAGetLastError());
791             memset(&context->sa_client, '\0', sizeof(context->sa_client));
792         }
793
794         context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
795
796         /* do we NEED_DUPPED_CSD ?? */
797         
798         return context;
799     }
800 }
801
802 /* 
803  * Windows 2000/NT specific code...
804  * create_acceptex_context()
805  * reset_acceptex_context()
806  * drain_acceptex_complport()
807  * winnt_get_connection()
808  *
809  * TODO: Insert a discussion of 'completion contexts' and what these function do here...
810  */
811 static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp) 
812 {
813     LPOVERLAPPED pol;
814     PCOMP_CONTEXT context;
815     int rc;
816     DWORD BytesRead;
817     DWORD CompKey;
818     int lastError;
819
820     while (1) {
821         context = NULL;
822         rc = GetQueuedCompletionStatus(hComplPort, &BytesRead, &CompKey,
823                                        &pol, 1000);
824         if (!rc) {
825             lastError = GetLastError();
826             if (lastError == ERROR_OPERATION_ABORTED) {
827                 ap_log_error(APLOG_MARK,APLOG_INFO,lastError, server_conf,
828                              "Child: %d - Draining a packet off the completion port.", my_pid);
829                 continue;
830             }
831             break;
832         }
833         ap_log_error(APLOG_MARK,APLOG_INFO,APR_SUCCESS, server_conf,
834                      "Child: %d - Nuking an active connection. context = %x", my_pid, context);
835         context = (PCOMP_CONTEXT) pol;
836         if (context && bCleanUp) {
837             /* It is only valid to clean-up in the process that initiated the I/O */
838             closesocket(context->accept_socket);
839             CloseHandle(context->Overlapped.hEvent);
840         }
841     }
842 }
843 static int create_acceptex_context(ap_context_t *_pconf, ap_listen_rec *lr) 
844 {
845     PCOMP_CONTEXT context;
846     DWORD BytesRead;
847     SOCKET nsd;
848     int lasterror;
849     
850     /* allocate the completion context */
851     context = ap_pcalloc(_pconf, sizeof(COMP_CONTEXT));
852     if (!context) {
853         ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
854                      "create_acceptex_context: ap_pcalloc() failed. Process will exit.");
855         return -1;
856     }
857
858     /* initialize the completion context */
859     context->lr = lr;
860     context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); 
861     if (context->Overlapped.hEvent == NULL) {
862         ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
863                      "create_acceptex_context: CreateEvent() failed. Process will exit.");
864         return -1;
865     }
866     context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
867     if (context->accept_socket == INVALID_SOCKET) {
868         ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
869                      "create_acceptex_context: socket() failed. Process will exit.");
870         return -1;
871     }
872     ap_create_context(&context->ptrans, _pconf);
873     context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
874     context->recv_buf = context->conn_io->inbase;
875     context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
876     ap_get_os_sock(&nsd, context->lr->sd);
877
878     /* AcceptEx on the completion context. The completion context will be signaled
879      * when a connection is accepted. */
880     if (!AcceptEx(nsd, context->accept_socket,
881                   context->recv_buf, 
882                   0, //context->recv_buf_size,
883                   PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
884                   &BytesRead,
885                   (LPOVERLAPPED) context)) {
886         lasterror = WSAGetLastError();
887         if (lasterror != ERROR_IO_PENDING) {
888             ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
889                          "create_acceptex_context: AcceptEx failed. Process will exit.");
890             return -1;
891         }
892     }
893     lr->count++;
894
895     return 0;
896 }
897 static ap_inline int reset_acceptex_context(PCOMP_CONTEXT context) 
898 {
899     DWORD BytesRead;
900     SOCKET nsd;
901     int lasterror;
902
903     context->lr->count++;
904
905     if (context->accept_socket == -1)
906         context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
907
908     if (context->accept_socket == INVALID_SOCKET) {
909         ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
910                      "reset_acceptex_context: socket() failed. Process will exit.");
911         return -1;
912     }
913
914     ap_clear_pool(context->ptrans);
915     context->sock = NULL;
916     context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
917     context->recv_buf = context->conn_io->inbase;
918     context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
919     ap_get_os_sock(&nsd, context->lr->sd);
920
921     if (!AcceptEx(nsd, context->accept_socket, 
922                   context->recv_buf, 
923                   0, //context->recv_buf_size,
924                   PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
925                   &BytesRead, (LPOVERLAPPED) context)) {
926         lasterror = WSAGetLastError();
927         if (lasterror != ERROR_IO_PENDING) {
928             ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
929                          "reset_acceptex_context: AcceptEx failed. Leaving the process running.");
930             return -1;
931         }
932     }
933
934     return 0;
935 }
936 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
937 {
938     int requests_this_child = 0;
939     int rc;
940     LPOVERLAPPED pol;
941     DWORD CompKey;
942     DWORD BytesRead;
943
944     if (context != NULL) {
945         /* If child shutdown has been signaled, clean-up the completion context */
946         if (workers_may_exit) {
947             CloseHandle(context->Overlapped.hEvent);
948             /* destroy pool */
949         }
950         else {
951             context->accept_socket = -1; /* Don't reuse the accept_socket */
952             if (reset_acceptex_context(context) == -1) {
953                 if (context->accept_socket != -1)
954                     closesocket(context->accept_socket);
955                 CloseHandle(context->Overlapped.hEvent);
956                 return NULL;
957             }
958         }
959     }
960
961     while (1) {
962         rc = GetQueuedCompletionStatus(AcceptExCompPort,
963                                        &BytesRead,
964                                        &CompKey,
965                                        &pol,
966                                        INFINITE);
967         if (!rc) {
968             ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
969                          "Child: %d - GetQueuedCompletionStatus() failed", my_pid);
970             continue;
971         }
972         break;
973     }
974     context = (PCOMP_CONTEXT) pol;
975     if (CompKey == 999) {
976         return NULL;
977     }
978
979     /* Each listener needs at least 1 context available to receive connections on.
980      * Create additional listener contexts if needed. 
981      */
982     ap_lock(allowed_globals.jobmutex);
983     context->lr->count--;
984     if ((context->lr->count < 2) && !workers_may_exit) {
985         if (create_acceptex_context(pconf, context->lr) == -1) {
986             ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
987                          "Unable to create an AcceptEx completion context -- process will exit");
988             signal_parent(0);
989             return NULL;
990         }
991     }
992     ap_unlock(allowed_globals.jobmutex);
993
994     /* Received a connection */
995     context->conn_io->incnt = BytesRead;
996     GetAcceptExSockaddrs(context->recv_buf, 
997                          0, //context->recv_buf_size,
998                          PADDED_ADDR_SIZE,
999                          PADDED_ADDR_SIZE,
1000                          &context->sa_server,
1001                          &context->sa_server_len,
1002                          &context->sa_client,
1003                          &context->sa_client_len);
1004
1005     return context;
1006
1007 }
1008 /*
1009  * worker_main() - this is the main loop for the worker threads
1010  *
1011  * Windows 95/98
1012  * Each thread runs within this function. They wait within remove_job()
1013  * for a job to become available, then handle all the requests on that
1014  * connection until it is closed, then return to remove_job().
1015  *
1016  * The worker thread will exit when it removes a job which contains
1017  * socket number -1. This provides a graceful thread exit, since
1018  * it will never exit during a connection.
1019  *
1020  * This code in this function is basically equivalent to the child_main()
1021  * from the multi-process (Unix) environment, except that we
1022  *
1023  *  - do not call child_init_modules (child init API phase)
1024  *  - block in remove_job, and when unblocked we have an already
1025  *    accepted socket, instead of blocking on a mutex or select().
1026  */
1027
1028 static void worker_main(int child_num)
1029 {
1030     static BOOLEAN bListenersStarted = FALSE;
1031     PCOMP_CONTEXT context = NULL;
1032
1033     if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1034         /* Windows NT/2000: Create AcceptEx completion contexts for each of the
1035          * listeners
1036          */
1037         ap_lock(allowed_globals.jobmutex);
1038         if (!bListenersStarted) {
1039             ap_listen_rec *lr;
1040             int i;
1041             bListenersStarted = TRUE;
1042             for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1043                 for(i=0; i<2; i++) {
1044                     if (lr->count < 2)
1045                         if (create_acceptex_context(pconf, lr) == -1) {
1046                             ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1047                                          "Unable to create an AcceptEx completion context -- process will exit");
1048                             signal_parent(0);   /* tell parent to die */
1049                         }
1050                 }
1051             }
1052         }
1053         ap_unlock(allowed_globals.jobmutex);
1054     }
1055
1056     while (1) {
1057         conn_rec *current_conn;
1058         ap_iol *iol;
1059
1060         /* Grab a connection off the network */
1061         if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1062             context = win9x_get_connection(context);
1063         }
1064         else {
1065             context = winnt_get_connection(context);
1066         }
1067
1068         if (!context)
1069             break;
1070         sock_disable_nagle(context->accept_socket);
1071         ap_put_os_sock(&context->sock, &context->accept_socket, context->ptrans);
1072         ap_register_cleanup(context->ptrans, context->sock, socket_cleanup, ap_null_cleanup);
1073         iol = win32_attach_socket(context->ptrans, context->sock);
1074         if (iol == NULL) {
1075             ap_log_error(APLOG_MARK, APLOG_ERR, APR_ENOMEM, server_conf,
1076                          "worker_main: attach_socket() failed. Continuing...");
1077             closesocket(context->accept_socket);
1078             continue;
1079         }
1080         ap_bpush_iol(context->conn_io, iol);
1081         current_conn = ap_new_connection(context->ptrans, server_conf, context->conn_io,
1082                                          (struct sockaddr_in *) context->sa_client,
1083                                          (struct sockaddr_in *) context->sa_server,
1084                                          child_num);
1085
1086         ap_process_connection(current_conn);
1087     }
1088 #if 0
1089     ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1090                  "child_main: Setting exit_event");
1091     SetEvent(exit_event);
1092 #endif
1093     /* TODO: Add code to clean-up completion contexts here */
1094 }
1095
1096 static void cleanup_thread(thread **handles, int *thread_cnt, int thread_to_clean)
1097 {
1098     int i;
1099
1100     CloseHandle(handles[thread_to_clean]);
1101     for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1102         handles[i] = handles[i + 1];
1103     (*thread_cnt)--;
1104 }
1105
1106
1107
1108 /*
1109  * child_main() is main loop for the child process. The loop in
1110  * this function becomes the controlling thread for the actually working
1111  * threads (which run in a loop in child_sub_main()).
1112  * Globals Used:
1113  *  exit_event, start_mutex, ap_threads_per_child, server_conf,
1114  *  h_errno defined to WSAGetLastError in winsock2.h,
1115  */
1116 static void child_main()
1117 {
1118     int nthreads = ap_threads_per_child;
1119     int thread_id;
1120     thread **child_handles;
1121     int rv;
1122     ap_status_t status;
1123     time_t end_time;
1124     int i;
1125     ap_context_t *pchild;
1126
1127     ap_create_context(&pchild, pconf);
1128
1129 //    ap_restart_time = time(NULL);
1130     /*
1131      * Wait until we have permission to start accepting connections.
1132      * start_mutex is used to ensure that only one child ever
1133      * goes into the listen/accept loop at once.
1134      */
1135     status = ap_lock(start_mutex);
1136     if (status != APR_SUCCESS) {
1137         ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
1138                      "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1139         signal_parent(0);       /* tell parent to die */
1140         ap_destroy_context(pchild);
1141         exit(0);
1142     }
1143     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, "Child %d: Acquired the start mutex", my_pid);
1144
1145     /* Setup the listening sockets */
1146     if (one_process) {
1147         ap_listen_rec *lr;
1148         setup_listeners(server_conf);
1149
1150         /* Associate the socket with the IO Completion port */
1151         for (lr = ap_listeners; lr; lr = lr->next) {
1152             int nsd;
1153             ap_get_os_sock(&nsd,lr->sd);
1154             CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
1155         }
1156   
1157     } else {
1158         setup_inherited_listeners(server_conf);
1159     }
1160     if (listenmaxfd == INVALID_SOCKET) {
1161         /* No sockets were made, better log something and exit */
1162         ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, NULL,
1163                      "No sockets were created for listening");
1164         signal_parent(0);       /* tell parent to die */
1165         ap_destroy_context(pchild);
1166         exit(0);
1167     }
1168
1169     allowed_globals.jobsemaphore = create_semaphore(0);
1170     ap_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
1171
1172     /* Create the worker thread pool */
1173     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, "Child %d: Creating %d worker threads",my_pid, nthreads);
1174     child_handles = (thread *) alloca(nthreads * sizeof(int));
1175     for (i = 0; i < nthreads; i++) {
1176         child_handles[i] = (thread *) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1177                                                      NULL, 0, &thread_id);
1178     }
1179
1180     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1181         /* Win95/98: Create the accept thread */
1182         _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) accept_and_queue_connections,
1183                        (void *) i, 0, &thread_id);
1184     }
1185
1186     /* Wait for the exit event to be signaled by the parent process */
1187     rv = WaitForSingleObject(exit_event, INFINITE);
1188
1189     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1190                  "Child %d: Exit event signaled. Child process is ending.", my_pid);
1191     workers_may_exit = 1;      
1192
1193     /* Shutdown the worker threads */
1194     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1195         for (i = 0; i < nthreads; i++) {
1196             add_job(-1);
1197         }
1198     }
1199     else { /* Windows NT/2000 */
1200         /* Hack alert... Give the server a couple of seconds to receive 
1201          * connections and drain AcceptEx completion contexts. We will
1202          * probably drop a few connections across a graceful restart, but
1203          * hopefully not many. This needs work...*/
1204         Sleep(2000);
1205
1206         /* Tell the worker threads to exit. Any connections accepted on 
1207          * the completion port from now will be dropped */
1208         for (i=0; i < nthreads; i++) {
1209             if (!PostQueuedCompletionStatus(AcceptExCompPort, 0, 999, NULL)) {
1210                 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1211                              "PostQueuedCompletionStatus failed");
1212             }
1213         }
1214     }
1215
1216     /* Wait for the worker threads to die */
1217     end_time = time(NULL) + 180;
1218     while (nthreads) {
1219         rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1220         if (rv != WAIT_TIMEOUT) {
1221             rv = rv - WAIT_OBJECT_0;
1222             ap_assert((rv >= 0) && (rv < nthreads));
1223             cleanup_thread(child_handles, &nthreads, rv);
1224             continue;
1225         }
1226         break;
1227     }
1228     for (i = 0; i < nthreads; i++) {
1229         TerminateThread(child_handles[i], 1);
1230         CloseHandle(child_handles[i]);
1231     }
1232     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1233                  "Child %d: All worker threads have ended.", my_pid);
1234
1235     if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {    
1236         /* All the worker threads should have exited by now, which will
1237          * cause any outstanding I/O on the completion port to be aborted.
1238          * Drain the completion port of this aborted I/O/
1239          */
1240         drain_acceptex_complport(AcceptExCompPort, TRUE);
1241     }
1242
1243     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1244                  "Child %d: Releasing the start mutex", my_pid);
1245     ap_unlock(start_mutex);
1246
1247     /* Still need to register cleanups for the sockets */
1248     CloseHandle(AcceptExCompPort);
1249     destroy_semaphore(allowed_globals.jobsemaphore);
1250     ap_destroy_lock(allowed_globals.jobmutex);
1251
1252     ap_destroy_context(pchild);
1253 }
1254
1255 /*
1256  * Spawn a child Apache process. The child process has the command line arguments from
1257  * argc and argv[], plus a -Z argument giving the name of an event. The child should
1258  * open and poll or wait on this event. When it is signalled, the child should die.
1259  * prefix is a prefix string for the event name.
1260  * 
1261  * The child_num argument on entry contains a serial number for this child (used to create
1262  * a unique event name). On exit, this number will have been incremented by one, ready
1263  * for the next call. 
1264  *
1265  * On exit, the value pointed to be *ev will contain the event created
1266  * to signal the new child process.
1267  *
1268  * The return value is the handle to the child process if successful, else -1. If -1 is
1269  * returned the error will already have been logged by ap_log_error().
1270  */
1271
1272 /**********************************************************************
1273  * master_main - this is the parent (main) process. We create a
1274  * child process to do the work, then sit around waiting for either
1275  * the child to exit, or a restart or exit signal. If the child dies,
1276  * we just respawn a new one. If we have a shutdown or graceful restart,
1277  * tell the child to die when it is ready. If it is a non-graceful
1278  * restart, force the child to die immediately.
1279  **********************************************************************/
1280
1281 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1282
1283 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1284 {
1285     int i;
1286     int handle = 0;
1287
1288     CloseHandle(handles[position]);
1289     CloseHandle(events[position]);
1290
1291     handle = (int)handles[position];
1292
1293     for (i = position; i < (*processes)-1; i++) {
1294         handles[i] = handles[i + 1];
1295         events[i] = events[i + 1];
1296     }
1297     (*processes)--;
1298 }
1299
1300 static int create_process(ap_context_t *p, HANDLE *handles, HANDLE *events, int *processes)
1301 {
1302
1303     int rv;
1304     char buf[1024];
1305     char *pCommand;
1306     int i;
1307     STARTUPINFO si;           /* Filled in prior to call to CreateProcess */
1308     PROCESS_INFORMATION pi;   /* filled in on call to CreateProces */
1309
1310     ap_listen_rec *lr;
1311     DWORD BytesWritten;
1312     HANDLE hPipeRead = NULL;
1313     HANDLE hPipeWrite = NULL;
1314     SECURITY_ATTRIBUTES sa = {0};  
1315
1316     sa.nLength = sizeof(sa);
1317     sa.bInheritHandle = TRUE;
1318     sa.lpSecurityDescriptor = NULL;
1319
1320     /* Create the IOCompletionPort */
1321     if (AcceptExCompPort == NULL) {
1322         AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1323                                                   NULL,
1324                                                   0,
1325                                                   0); /* CONCURRENT ACTIVE THREADS */
1326         if (AcceptExCompPort == NULL) {
1327             ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1328                          "Unable to create the AcceptExCompletionPort -- process will exit");
1329             return -1;
1330         }
1331     }
1332
1333     /* Build the command line. Should look something like this:
1334      * C:/apache/bin/apache.exe -f ap_server_confname 
1335      * First, get the path to the executable...
1336      */
1337     rv = GetModuleFileName(NULL, buf, sizeof(buf));
1338     if (rv == sizeof(buf)) {
1339         ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1340                      "Parent: Path to Apache process too long");
1341         return -1;
1342     } else if (rv == 0) {
1343         ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1344                      "Parent: GetModuleFileName() returned NULL for current process.");
1345         return -1;
1346     }
1347
1348     /* Build the command line */
1349     pCommand = ap_psprintf(p, "\"%s\"", buf);  
1350     for (i = 1; i < server_conf->process->argc; i++) {
1351         pCommand = ap_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1352     }
1353
1354     /* Create a pipe to send socket info to the child */
1355     if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1356         ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1357                      "Parent: Unable to create pipe to child process.\n");
1358         return -1;
1359     }
1360
1361     SetEnvironmentVariable("AP_PARENT_PID",ap_psprintf(p,"%d",parent_pid));
1362
1363     /* Give the read end of the pipe (hPipeRead) to the child as stdin. The 
1364      * parent will write the socket data to the child on this pipe.
1365      */
1366     memset(&si, 0, sizeof(si));
1367     memset(&pi, 0, sizeof(pi));
1368     si.cb = sizeof(si);
1369     si.dwFlags     = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1370     si.wShowWindow = SW_HIDE;
1371     si.hStdInput   = hPipeRead;
1372
1373     if (!CreateProcess(NULL, pCommand, NULL, NULL, 
1374                        TRUE,               /* Inherit handles */
1375                        CREATE_SUSPENDED,   /* Creation flags */
1376                        NULL,               /* Environment block */
1377                        NULL,
1378                        &si, &pi)) {
1379         ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1380                      "Parent: Not able to create the child process.");
1381         /*
1382          * We must close the handles to the new process and its main thread
1383          * to prevent handle and memory leaks.
1384          */ 
1385         CloseHandle(pi.hProcess);
1386         CloseHandle(pi.hThread);
1387         return -1;
1388     }
1389     else {
1390         HANDLE kill_event;
1391         LPWSAPROTOCOL_INFO  lpWSAProtocolInfo;
1392         HANDLE hDupedCompPort;
1393
1394         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1395                      "Parent: Created child process %d", pi.dwProcessId);
1396
1397         SetEnvironmentVariable("AP_PARENT_PID",NULL);
1398
1399         /* Create the exit_event, apCchild_pid */
1400         sa.nLength = sizeof(sa);
1401         sa.bInheritHandle = TRUE;
1402         sa.lpSecurityDescriptor = NULL;        
1403         kill_event = CreateEvent(&sa, TRUE, FALSE, ap_psprintf(pconf,"apC%d", pi.dwProcessId));
1404         if (!kill_event) {
1405             ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1406                          "Parent: Could not create exit event for child process");
1407             CloseHandle(pi.hProcess);
1408             CloseHandle(pi.hThread);
1409             return -1;
1410         }
1411         
1412         /* Assume the child process lives. Update the process and event tables */
1413         handles[*processes] = pi.hProcess;
1414         events[*processes] = kill_event;
1415         (*processes)++;
1416
1417         /* We never store the thread's handle, so close it now. */
1418         ResumeThread(pi.hThread);
1419         CloseHandle(pi.hThread);
1420
1421         /* Run the chain of open sockets. For each socket, duplicate it 
1422          * for the target process then send the WSAPROTOCOL_INFO 
1423          * (returned by dup socket) to the child */
1424         for (lr = ap_listeners; lr; lr = lr->next) {
1425             int nsd;
1426             lpWSAProtocolInfo = ap_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1427             ap_get_os_sock(&nsd,lr->sd);
1428             /* Associate the socket with the IOcompletion port */
1429             CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
1430             ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_INFO, APR_SUCCESS, server_conf,
1431                          "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1432             if (WSADuplicateSocket(nsd, pi.dwProcessId,
1433                                    lpWSAProtocolInfo) == SOCKET_ERROR) {
1434                 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, server_conf,
1435                              "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1436                 return -1;
1437             }
1438
1439             if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1440                            &BytesWritten,
1441                            (LPOVERLAPPED) NULL)) {
1442                 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1443                              "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1444                 return -1;
1445             }
1446             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1447                          "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1448         }
1449         /* Now, send the AcceptEx completion port to the child */
1450         if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort, 
1451                              pi.hProcess, &hDupedCompPort,  0,
1452                              TRUE, DUPLICATE_SAME_ACCESS)) {
1453             ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1454                          "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1455             return -1;
1456         }
1457         WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1458     }
1459
1460     CloseHandle(hPipeRead);
1461     CloseHandle(hPipeWrite);        
1462
1463     return 0;
1464 }
1465
1466 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1467 {
1468     int remaining_children_to_start = ap_daemons_to_start;
1469     int i;
1470     int rv, cld;
1471     int child_num = 0;
1472     int restart_pending = 0;
1473     int shutdown_pending = 0;
1474     int current_live_processes = 0; /* number of child process we know about */
1475
1476     HANDLE process_handles[MAX_PROCESSES];
1477     HANDLE process_kill_events[MAX_PROCESSES];
1478
1479     setup_listeners(s);
1480
1481     /* Create child process 
1482      * Should only be one in this version of Apache for WIN32 
1483      */
1484     service_set_status(SERVICE_START_PENDING);
1485     while (remaining_children_to_start--) {
1486         if (create_process(pconf, process_handles, process_kill_events, 
1487                            &current_live_processes) < 0) {
1488             ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1489                          "master_main: create child process failed. Exiting.");
1490             shutdown_pending = 1;
1491             goto die_now;
1492         }
1493     }
1494     service_set_status(SERVICE_RUNNING);
1495
1496     restart_pending = shutdown_pending = 0;
1497     
1498     /* Wait for shutdown or restart events or for child death */
1499     process_handles[current_live_processes] = shutdown_event;
1500     process_handles[current_live_processes+1] = restart_event;
1501     printf("process/shutdown/restart %d %d %d\n", process_handles[0], process_handles[1], process_handles[2]);
1502     rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles, 
1503                                 FALSE, INFINITE);
1504     cld = rv - WAIT_OBJECT_0;
1505     if (rv == WAIT_FAILED) {
1506         /* Something serious is wrong */
1507         ap_log_error(APLOG_MARK,APLOG_CRIT, GetLastError(), server_conf,
1508                      "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1509         shutdown_pending = 1;
1510     }
1511     else if (rv == WAIT_TIMEOUT) {
1512         /* Hey, this cannot happen */
1513         ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1514                      "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1515         shutdown_pending = 1;
1516     }
1517     else if (cld == current_live_processes) {
1518         /* shutdown_event signalled */
1519         shutdown_pending = 1;
1520         printf("shutdown event signaled\n");
1521         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s, 
1522                      "master_main: Shutdown event signaled -- doing server shutdown.");
1523         if (ResetEvent(shutdown_event) == 0) {
1524             ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1525                          "ResetEvent(shutdown_event)");
1526         }
1527
1528     }
1529     else if (cld == current_live_processes+1) {
1530         /* restart_event signalled */
1531         int children_to_kill = current_live_processes;
1532         restart_pending = 1;
1533         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s, 
1534                      "master_main: Restart event signaled. Doing a graceful restart.");
1535         if (ResetEvent(restart_event) == 0) {
1536             ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1537                          "master_main: ResetEvent(restart_event) failed.");
1538         }
1539         /* Signal each child process to die 
1540          * We are making a big assumption here that the child process, once signaled,
1541          * will REALLY go away. Since this is a restart, we do not want to hold the 
1542          * new child process up waiting for the old child to die. Remove the old 
1543          * child out of the process_handles ap_table_t and hope for the best...
1544          */
1545         for (i = 0; i < children_to_kill; i++) {
1546             printf("SetEvent handle = %d\n", process_kill_events[i]);
1547             if (SetEvent(process_kill_events[i]) == 0)
1548                 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1549                              "master_main: SetEvent for child process in slot #%d failed", i);
1550             cleanup_process(process_handles, process_kill_events, i, &current_live_processes);
1551         }
1552     } 
1553     else {
1554         /* A child process must have exited because of a fatal error condition (seg fault, etc.). 
1555          * Remove the dead process 
1556          * from the process_handles and process_kill_events ap_table_t and create a new
1557          * child process.
1558          * TODO: Consider restarting the child immediately without looping through http_main
1559          * and without rereading the configuration. Will need this if we ever support multiple 
1560          * children. One option, create a parent thread which waits on child death and restarts it.
1561          */
1562         restart_pending = 1;
1563         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf, 
1564                      "master_main: Child process failed. Restarting the child process.");
1565         ap_assert(cld < current_live_processes);
1566         cleanup_process(process_handles, process_kill_events, cld, &current_live_processes);
1567         /* APD2("main_process: child in slot %d died", rv); */
1568         /* restart_child(process_hancles, process_kill_events, cld, &current_live_processes); */
1569
1570         /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead 
1571          * process. */
1572         drain_acceptex_complport(AcceptExCompPort, FALSE);
1573     }
1574
1575 die_now:
1576     if (shutdown_pending) {
1577         int tmstart = time(NULL);
1578         /* Signal each child processes to die */
1579         for (i = 0; i < current_live_processes; i++) {
1580             printf("SetEvent handle = %d\n", process_kill_events[i]);
1581             if (SetEvent(process_kill_events[i]) == 0)
1582                 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1583                              "master_main: SetEvent for child process in slot #%d failed", i);
1584         }
1585
1586         while (current_live_processes && ((tmstart+60) > time(NULL))) {
1587             rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1588             if (rv == WAIT_TIMEOUT)
1589                 continue;
1590             ap_assert(rv != WAIT_FAILED);
1591             cld = rv - WAIT_OBJECT_0;
1592             ap_assert(rv < current_live_processes);
1593             cleanup_process(process_handles, process_kill_events, cld, &current_live_processes);
1594         }
1595         for (i = 0; i < current_live_processes; i++) {
1596             ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1597                          "forcing termination of child #%d (handle %d)", i, process_handles[i]);
1598             TerminateProcess((HANDLE) process_handles[i], 1);
1599         }
1600         return (0); /* Tell the caller we are shutting down */
1601     }
1602
1603     return (1); /* Tell the caller we want a restart */
1604 }
1605
1606 /* 
1607  * winnt_pre_config() hook
1608  */
1609 static void winnt_pre_config(ap_context_t *pconf, ap_context_t *plog, ap_context_t *ptemp) 
1610 {
1611     char *pid;
1612
1613     one_process = !!getenv("ONE_PROCESS");
1614
1615     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1616     GetVersionEx(&osver);
1617
1618     /* AP_PARENT_PID is only valid in the child */
1619     pid = getenv("AP_PARENT_PID");
1620     if (pid) {
1621         /* This is the child */
1622         parent_pid = atoi(pid);
1623         my_pid = getpid();
1624     }
1625     else {
1626         /* This is the parent */
1627         parent_pid = my_pid = getpid();
1628
1629     }
1630
1631     ap_listen_pre_config();
1632     ap_daemons_to_start = DEFAULT_NUM_DAEMON;
1633     ap_threads_per_child = DEFAULT_START_THREAD;
1634     ap_pid_fname = DEFAULT_PIDLOG;
1635     max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1636
1637     ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1638
1639 }
1640
1641 static void winnt_post_config(ap_context_t *pconf, ap_context_t *plog, ap_context_t *ptemp, server_rec* server_conf)
1642 {
1643     server_conf = server_conf;
1644 }
1645
1646 API_EXPORT(int) ap_mpm_run(ap_context_t *_pconf, ap_context_t *plog, server_rec *s )
1647 {
1648
1649     char* exit_event_name;
1650     static int restart = 0;             /* Default is to not restart */
1651 //    time_t tmstart;
1652     static HANDLE shutdown_event;       /* used to signal shutdown to parent */
1653     static HANDLE restart_event;        /* used to signal a restart to parent */
1654
1655     pconf = _pconf;
1656     server_conf = s;
1657
1658     if ((parent_pid != my_pid) || one_process) {
1659         /* Child process */
1660         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1661                      "Child %d: Child process is running", my_pid);        
1662         AMCSocketInitialize();
1663         exit_event_name = ap_psprintf(pconf, "apC%d", my_pid);
1664         setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1665
1666         if (one_process) {
1667             /* Create the IO CompletionPort */
1668             if (AcceptExCompPort == NULL) {
1669                 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1670                                                           NULL, 0, 0); 
1671                 if (AcceptExCompPort == NULL) {
1672                     ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1673                                  "Unable to create the AcceptExCompletionPort -- process will exit");
1674                     return -1;
1675                 }
1676             }
1677             ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1678             exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1679         }
1680         else {
1681             ap_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1682             exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1683             ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1684                          "Child %d: exit_event_name = %s", my_pid, exit_event_name);        
1685         }
1686         ap_assert(start_mutex);
1687         ap_assert(exit_event);
1688
1689         child_main();
1690
1691         CloseHandle(exit_event);
1692         AMCSocketCleanup();
1693         restart = 0;
1694     }
1695     else {
1696         /* Parent process */
1697         PSECURITY_ATTRIBUTES sa = GetNullACL();  /* returns NULL if invalid (Win95?) */
1698
1699         setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1700         if (!restart) {
1701             ap_log_pid(pconf, ap_pid_fname);
1702
1703             service_set_status(SERVICE_START_PENDING);
1704             AMCSocketInitialize();
1705 //            setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1706         
1707             /* Create shutdown event, apPID_shutdown, where PID is the parent 
1708              * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
1709              */
1710             shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
1711             if (!shutdown_event) {
1712                 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), s,
1713                              "master_main: Cannot create shutdown event %s", signal_shutdown_name);
1714                 CleanNullACL((void *)sa);
1715                 exit(1);
1716             }
1717
1718             /* Create restart event, apPID_restart, where PID is the parent 
1719              * Apache process ID. Restart is signaled by 'apache -k restart'.
1720              */
1721 //            restart_event = CreateEvent(sa, TRUE, FALSE, signal_restart_name);
1722             restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
1723             if (!restart_event) {
1724                 CloseHandle(shutdown_event);
1725                 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), s,
1726                              "ap_run_mpm: Cannot create restart event %s", signal_restart_name);
1727                 CleanNullACL((void *)sa);
1728                 exit(1);
1729             }
1730             CleanNullACL((void *)sa);
1731             
1732             /* Create the start mutex, apPID, where PID is the parent Apache process ID.
1733              * Ths start mutex is used during a restart to prevent more than one 
1734              * child process from entering the accept loop at once.
1735              */
1736 //            ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1737             ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,s->process->pool);
1738             /* TODO: Add some code to detect failure */
1739         }
1740
1741         /* Go to work... */
1742         restart = master_main(server_conf, shutdown_event, restart_event);
1743
1744         if (!restart) {
1745             const char *pidfile = NULL;
1746             /* Shutting down. Clean up... */
1747             pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1748             if ( pidfile != NULL && unlink(pidfile) == 0)
1749                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO,APR_SUCCESS,
1750                              server_conf, "removed PID file %s (pid=%ld)",
1751                              pidfile, (long)getpid());
1752             ap_destroy_lock(start_mutex);
1753
1754             CloseHandle(restart_event);
1755             CloseHandle(shutdown_event);
1756             AMCSocketCleanup();
1757
1758             service_set_status(SERVICE_STOPPED);
1759         }
1760     }
1761     return !restart;
1762 }
1763
1764 static void winnt_hooks(void)
1765 {
1766 //    INIT_SIGLIST()
1767     one_process = 0;
1768     /* Configuration hooks implemented by http_config.c ... */
1769     ap_hook_pre_config(winnt_pre_config, NULL, NULL, HOOK_MIDDLE);
1770 }
1771
1772 /* 
1773  * Command processors 
1774  */
1775 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg) 
1776 {
1777     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1778     if (err != NULL) {
1779         return err;
1780     }
1781
1782     if (cmd->server->is_virtual) {
1783         return "PidFile directive not allowed in <VirtualHost>";
1784     }
1785     ap_pid_fname = arg;
1786     return NULL;
1787 }
1788
1789 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg) 
1790 {
1791     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1792     if (err != NULL) {
1793         return err;
1794     }
1795
1796     ap_threads_per_child = atoi(arg);
1797     if (ap_threads_per_child > HARD_THREAD_LIMIT) {
1798         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1799                      "WARNING: ThreadsPerChild of %d exceeds compile time"
1800                      " limit of %d threads,", ap_threads_per_child, 
1801                      HARD_THREAD_LIMIT);
1802         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1803                      " lowering ThreadsPerChild to %d. To increase, please"
1804                      " see the  HARD_THREAD_LIMIT define in src/include/httpd.h.", 
1805                      HARD_THREAD_LIMIT);
1806     }
1807     else if (ap_threads_per_child < 1) {
1808         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1809                      "WARNING: Require ThreadsPerChild > 0, setting to 1");
1810         ap_threads_per_child = 1;
1811     }
1812     return NULL;
1813 }
1814
1815
1816 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg) 
1817 {
1818     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1819     if (err != NULL) {
1820         return err;
1821     }
1822
1823     max_requests_per_child = atoi(arg);
1824
1825     return NULL;
1826 }
1827
1828 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg) 
1829 {
1830     struct stat finfo;
1831     const char *fname;
1832     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1833     if (err != NULL) {
1834         return err;
1835     }
1836
1837     fname = ap_server_root_relative(cmd->pool, arg);
1838     if ((stat(fname, &finfo) == -1) || !S_ISDIR(finfo.st_mode)) {
1839         return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname, 
1840                           " does not exist or is not a directory", NULL);
1841     }
1842     ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1843     return NULL;
1844 }
1845
1846 /* Stub functions until this MPM supports the connection status API */
1847
1848 API_EXPORT(void) ap_update_connection_status(long conn_id, const char *key, \
1849                                              const char *value)
1850 {
1851     /* NOP */
1852 }
1853
1854 API_EXPORT(void) ap_reset_connection_status(long conn_id)
1855 {
1856     /* NOP */
1857 }
1858
1859 static const command_rec winnt_cmds[] = {
1860 LISTEN_COMMANDS
1861 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
1862     "A file for logging the server process ID"},
1863 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
1864   "Number of threads each child creates" },
1865 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
1866   "Maximum number of requests a particular child serves before dying." },
1867 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
1868   "The location of the directory Apache changes to before dumping core" },
1869 { NULL }
1870 };
1871
1872 module MODULE_VAR_EXPORT mpm_winnt_module = {
1873     STANDARD20_MODULE_STUFF,
1874     NULL,                       /* create per-directory config structure */
1875     NULL,                       /* merge per-directory config structures */
1876     NULL,                       /* create per-server config structure */
1877     NULL,                       /* merge per-server config structures */
1878     winnt_cmds,                 /* command ap_table_t */
1879     NULL,                       /* handlers */
1880     winnt_hooks                 /* register_hooks */
1881 };