]> granicus.if.org Git - apache/blob - server/mpm/winnt/mpm_winnt.c
Logs have already been opened by http_main.c. Don't need to do it here again.
[apache] / server / mpm / winnt / mpm_winnt.c
1 /* ====================================================================
2  * Copyright (c) 1995-1999 The Apache Group.  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 Group 
19  *    for use in the Apache HTTP server project (http://www.apache.org/)." 
20  * 
21  * 4. The names "Apache Server" and "Apache Group" 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 Group. 
29  * 
30  * 6. Redistributions of any form whatsoever must retain the following 
31  *    acknowledgment: 
32  *    "This product includes software developed by the Apache Group 
33  *    for use in the Apache HTTP server project (http://www.apache.org/)." 
34  * 
35  * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``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 GROUP 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 Group 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 Group 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     free_thread(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
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] = create_thread((void (*)(void *)) worker_main, (void *) i);
1177     }
1178
1179     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1180         /* Win95/98: Create the accept thread */
1181         create_thread((void (*)(void *)) accept_and_queue_connections, (void *) NULL);
1182     }
1183
1184     /* Wait for the exit event to be signaled by the parent process */
1185     rv = WaitForSingleObject(exit_event, INFINITE);
1186
1187     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1188                  "Child %d: Exit event signaled. Child process is ending.", my_pid);
1189     workers_may_exit = 1;      
1190
1191     /* Shutdown the worker threads */
1192     if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1193         for (i = 0; i < nthreads; i++) {
1194             add_job(-1);
1195         }
1196     }
1197     else { /* Windows NT/2000 */
1198         /* Hack alert... Give the server a couple of seconds to receive 
1199          * connections and drain AcceptEx completion contexts. We will
1200          * probably drop a few connections across a graceful restart, but
1201          * hopefully not many. This needs work...*/
1202         Sleep(2000);
1203
1204         /* Tell the worker threads to exit. Any connections accepted on 
1205          * the completion port from now will be dropped */
1206         for (i=0; i < nthreads; i++) {
1207             if (!PostQueuedCompletionStatus(AcceptExCompPort, 0, 999, NULL)) {
1208                 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1209                              "PostQueuedCompletionStatus failed");
1210             }
1211         }
1212     }
1213
1214     /* Wait for the worker threads to die */
1215     end_time = time(NULL) + 180;
1216     while (nthreads) {
1217         rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1218         if (rv != WAIT_TIMEOUT) {
1219             rv = rv - WAIT_OBJECT_0;
1220             ap_assert((rv >= 0) && (rv < nthreads));
1221             cleanup_thread(child_handles, &nthreads, rv);
1222             continue;
1223         }
1224         break;
1225     }
1226     for (i = 0; i < nthreads; i++) {
1227         kill_thread(child_handles[i]);
1228         free_thread(child_handles[i]);
1229     }
1230     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1231                  "Child %d: All worker threads have ended.", my_pid);
1232
1233     if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {    
1234         /* All the worker threads should have exited by now, which will
1235          * cause any outstanding I/O on the completion port to be aborted.
1236          * Drain the completion port of this aborted I/O/
1237          */
1238         drain_acceptex_complport(AcceptExCompPort, TRUE);
1239     }
1240
1241     ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, 
1242                  "Child %d: Releasing the start mutex", my_pid);
1243     ap_unlock(start_mutex);
1244
1245     /* Still need to register cleanups for the sockets */
1246     CloseHandle(AcceptExCompPort);
1247     destroy_semaphore(allowed_globals.jobsemaphore);
1248     ap_destroy_lock(allowed_globals.jobmutex);
1249
1250     ap_destroy_context(pchild);
1251 }
1252
1253 /*
1254  * Spawn a child Apache process. The child process has the command line arguments from
1255  * argc and argv[], plus a -Z argument giving the name of an event. The child should
1256  * open and poll or wait on this event. When it is signalled, the child should die.
1257  * prefix is a prefix string for the event name.
1258  * 
1259  * The child_num argument on entry contains a serial number for this child (used to create
1260  * a unique event name). On exit, this number will have been incremented by one, ready
1261  * for the next call. 
1262  *
1263  * On exit, the value pointed to be *ev will contain the event created
1264  * to signal the new child process.
1265  *
1266  * The return value is the handle to the child process if successful, else -1. If -1 is
1267  * returned the error will already have been logged by ap_log_error().
1268  */
1269
1270 /**********************************************************************
1271  * master_main - this is the parent (main) process. We create a
1272  * child process to do the work, then sit around waiting for either
1273  * the child to exit, or a restart or exit signal. If the child dies,
1274  * we just respawn a new one. If we have a shutdown or graceful restart,
1275  * tell the child to die when it is ready. If it is a non-graceful
1276  * restart, force the child to die immediately.
1277  **********************************************************************/
1278
1279 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1280
1281 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1282 {
1283     int i;
1284     int handle = 0;
1285
1286     CloseHandle(handles[position]);
1287     CloseHandle(events[position]);
1288
1289     handle = (int)handles[position];
1290
1291     for (i = position; i < (*processes)-1; i++) {
1292         handles[i] = handles[i + 1];
1293         events[i] = events[i + 1];
1294     }
1295     (*processes)--;
1296 }
1297
1298 static int create_process(ap_context_t *p, HANDLE *handles, HANDLE *events, int *processes)
1299 {
1300
1301     int rv;
1302     char buf[1024];
1303     char *pCommand;
1304     int i;
1305     STARTUPINFO si;           /* Filled in prior to call to CreateProcess */
1306     PROCESS_INFORMATION pi;   /* filled in on call to CreateProces */
1307
1308     ap_listen_rec *lr;
1309     DWORD BytesWritten;
1310     HANDLE hPipeRead = NULL;
1311     HANDLE hPipeWrite = NULL;
1312     SECURITY_ATTRIBUTES sa = {0};  
1313
1314     sa.nLength = sizeof(sa);
1315     sa.bInheritHandle = TRUE;
1316     sa.lpSecurityDescriptor = NULL;
1317
1318     /* Create the IOCompletionPort */
1319     if (AcceptExCompPort == NULL) {
1320         AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1321                                                   NULL,
1322                                                   0,
1323                                                   0); /* CONCURRENT ACTIVE THREADS */
1324         if (AcceptExCompPort == NULL) {
1325             ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1326                          "Unable to create the AcceptExCompletionPort -- process will exit");
1327             return -1;
1328         }
1329     }
1330
1331     /* Build the command line. Should look something like this:
1332      * C:/apache/bin/apache.exe -f ap_server_confname 
1333      * First, get the path to the executable...
1334      */
1335     rv = GetModuleFileName(NULL, buf, sizeof(buf));
1336     if (rv == sizeof(buf)) {
1337         ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1338                      "Parent: Path to Apache process too long");
1339         return -1;
1340     } else if (rv == 0) {
1341         ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1342                      "Parent: GetModuleFileName() returned NULL for current process.");
1343         return -1;
1344     }
1345
1346     /* Build the command line */
1347     pCommand = ap_psprintf(p, "\"%s\"", buf);  
1348     for (i = 1; i < server_conf->process->argc; i++) {
1349         pCommand = ap_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1350     }
1351
1352     /* Create a pipe to send socket info to the child */
1353     if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1354         ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1355                      "Parent: Unable to create pipe to child process.\n");
1356         return -1;
1357     }
1358
1359     SetEnvironmentVariable("AP_PARENT_PID",ap_psprintf(p,"%d",parent_pid));
1360
1361     /* Give the read end of the pipe (hPipeRead) to the child as stdin. The 
1362      * parent will write the socket data to the child on this pipe.
1363      */
1364     memset(&si, 0, sizeof(si));
1365     memset(&pi, 0, sizeof(pi));
1366     si.cb = sizeof(si);
1367     si.dwFlags     = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1368     si.wShowWindow = SW_HIDE;
1369     si.hStdInput   = hPipeRead;
1370
1371     if (!CreateProcess(NULL, pCommand, NULL, NULL, 
1372                        TRUE,               /* Inherit handles */
1373                        CREATE_SUSPENDED,   /* Creation flags */
1374                        NULL,               /* Environment block */
1375                        NULL,
1376                        &si, &pi)) {
1377         ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1378                      "Parent: Not able to create the child process.");
1379         /*
1380          * We must close the handles to the new process and its main thread
1381          * to prevent handle and memory leaks.
1382          */ 
1383         CloseHandle(pi.hProcess);
1384         CloseHandle(pi.hThread);
1385         return -1;
1386     }
1387     else {
1388         HANDLE kill_event;
1389         LPWSAPROTOCOL_INFO  lpWSAProtocolInfo;
1390         HANDLE hDupedCompPort;
1391
1392         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1393                      "Parent: Created child process %d", pi.dwProcessId);
1394
1395         SetEnvironmentVariable("AP_PARENT_PID",NULL);
1396
1397         /* Create the exit_event, apCchild_pid */
1398         sa.nLength = sizeof(sa);
1399         sa.bInheritHandle = TRUE;
1400         sa.lpSecurityDescriptor = NULL;        
1401         kill_event = CreateEvent(&sa, TRUE, FALSE, ap_psprintf(pconf,"apC%d", pi.dwProcessId));
1402         if (!kill_event) {
1403             ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1404                          "Parent: Could not create exit event for child process");
1405             CloseHandle(pi.hProcess);
1406             CloseHandle(pi.hThread);
1407             return -1;
1408         }
1409         
1410         /* Assume the child process lives. Update the process and event tables */
1411         handles[*processes] = pi.hProcess;
1412         events[*processes] = kill_event;
1413         (*processes)++;
1414
1415         /* We never store the thread's handle, so close it now. */
1416         ResumeThread(pi.hThread);
1417         CloseHandle(pi.hThread);
1418
1419         /* Run the chain of open sockets. For each socket, duplicate it 
1420          * for the target process then send the WSAPROTOCOL_INFO 
1421          * (returned by dup socket) to the child */
1422         for (lr = ap_listeners; lr; lr = lr->next) {
1423             int nsd;
1424             lpWSAProtocolInfo = ap_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1425             ap_get_os_sock(&nsd,lr->sd);
1426             /* Associate the socket with the IOcompletion port */
1427             CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
1428             ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_INFO, APR_SUCCESS, server_conf,
1429                          "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1430             if (WSADuplicateSocket(nsd, pi.dwProcessId,
1431                                    lpWSAProtocolInfo) == SOCKET_ERROR) {
1432                 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, server_conf,
1433                              "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1434                 return -1;
1435             }
1436
1437             if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1438                            &BytesWritten,
1439                            (LPOVERLAPPED) NULL)) {
1440                 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1441                              "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1442                 return -1;
1443             }
1444             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1445                          "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1446         }
1447         /* Now, send the AcceptEx completion port to the child */
1448         if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort, 
1449                              pi.hProcess, &hDupedCompPort,  0,
1450                              TRUE, DUPLICATE_SAME_ACCESS)) {
1451             ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1452                          "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1453             return -1;
1454         }
1455         WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1456     }
1457
1458     CloseHandle(hPipeRead);
1459     CloseHandle(hPipeWrite);        
1460
1461     return 0;
1462 }
1463
1464 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1465 {
1466     int remaining_children_to_start = ap_daemons_to_start;
1467     int i;
1468     int rv, cld;
1469     int child_num = 0;
1470     int restart_pending = 0;
1471     int shutdown_pending = 0;
1472     int current_live_processes = 0; /* number of child process we know about */
1473
1474     HANDLE process_handles[MAX_PROCESSES];
1475     HANDLE process_kill_events[MAX_PROCESSES];
1476
1477     setup_listeners(s);
1478
1479     /* Create child process 
1480      * Should only be one in this version of Apache for WIN32 
1481      */
1482     service_set_status(SERVICE_START_PENDING);
1483     while (remaining_children_to_start--) {
1484         if (create_process(pconf, process_handles, process_kill_events, 
1485                            &current_live_processes) < 0) {
1486             ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1487                          "master_main: create child process failed. Exiting.");
1488             shutdown_pending = 1;
1489             goto die_now;
1490         }
1491     }
1492     service_set_status(SERVICE_RUNNING);
1493
1494     restart_pending = shutdown_pending = 0;
1495     
1496     /* Wait for shutdown or restart events or for child death */
1497     process_handles[current_live_processes] = shutdown_event;
1498     process_handles[current_live_processes+1] = restart_event;
1499     printf("process/shutdown/restart %d %d %d\n", process_handles[0], process_handles[1], process_handles[2]);
1500     rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles, 
1501                                 FALSE, INFINITE);
1502     cld = rv - WAIT_OBJECT_0;
1503     if (rv == WAIT_FAILED) {
1504         /* Something serious is wrong */
1505         ap_log_error(APLOG_MARK,APLOG_CRIT, GetLastError(), server_conf,
1506                      "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1507         shutdown_pending = 1;
1508     }
1509     else if (rv == WAIT_TIMEOUT) {
1510         /* Hey, this cannot happen */
1511         ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1512                      "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1513         shutdown_pending = 1;
1514     }
1515     else if (cld == current_live_processes) {
1516         /* shutdown_event signalled */
1517         shutdown_pending = 1;
1518         printf("shutdown event signaled\n");
1519         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s, 
1520                      "master_main: Shutdown event signaled -- doing server shutdown.");
1521         if (ResetEvent(shutdown_event) == 0) {
1522             ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1523                          "ResetEvent(shutdown_event)");
1524         }
1525
1526     }
1527     else if (cld == current_live_processes+1) {
1528         /* restart_event signalled */
1529         int children_to_kill = current_live_processes;
1530         restart_pending = 1;
1531         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s, 
1532                      "master_main: Restart event signaled. Doing a graceful restart.");
1533         if (ResetEvent(restart_event) == 0) {
1534             ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1535                          "master_main: ResetEvent(restart_event) failed.");
1536         }
1537         /* Signal each child process to die 
1538          * We are making a big assumption here that the child process, once signaled,
1539          * will REALLY go away. Since this is a restart, we do not want to hold the 
1540          * new child process up waiting for the old child to die. Remove the old 
1541          * child out of the process_handles ap_table_t and hope for the best...
1542          */
1543         for (i = 0; i < children_to_kill; i++) {
1544             printf("SetEvent handle = %d\n", process_kill_events[i]);
1545             if (SetEvent(process_kill_events[i]) == 0)
1546                 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1547                              "master_main: SetEvent for child process in slot #%d failed", i);
1548             cleanup_process(process_handles, process_kill_events, i, &current_live_processes);
1549         }
1550     } 
1551     else {
1552         /* A child process must have exited because of a fatal error condition (seg fault, etc.). 
1553          * Remove the dead process 
1554          * from the process_handles and process_kill_events ap_table_t and create a new
1555          * child process.
1556          * TODO: Consider restarting the child immediately without looping through http_main
1557          * and without rereading the configuration. Will need this if we ever support multiple 
1558          * children. One option, create a parent thread which waits on child death and restarts it.
1559          */
1560         restart_pending = 1;
1561         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf, 
1562                      "master_main: Child process failed. Restarting the child process.");
1563         ap_assert(cld < current_live_processes);
1564         cleanup_process(process_handles, process_kill_events, cld, &current_live_processes);
1565         /* APD2("main_process: child in slot %d died", rv); */
1566         /* restart_child(process_hancles, process_kill_events, cld, &current_live_processes); */
1567
1568         /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead 
1569          * process. */
1570         drain_acceptex_complport(AcceptExCompPort, FALSE);
1571     }
1572
1573 die_now:
1574     if (shutdown_pending) {
1575         int tmstart = time(NULL);
1576         /* Signal each child processes to die */
1577         for (i = 0; i < current_live_processes; i++) {
1578             printf("SetEvent handle = %d\n", process_kill_events[i]);
1579             if (SetEvent(process_kill_events[i]) == 0)
1580                 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1581                              "master_main: SetEvent for child process in slot #%d failed", i);
1582         }
1583
1584         while (current_live_processes && ((tmstart+60) > time(NULL))) {
1585             rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1586             if (rv == WAIT_TIMEOUT)
1587                 continue;
1588             ap_assert(rv != WAIT_FAILED);
1589             cld = rv - WAIT_OBJECT_0;
1590             ap_assert(rv < current_live_processes);
1591             cleanup_process(process_handles, process_kill_events, cld, &current_live_processes);
1592         }
1593         for (i = 0; i < current_live_processes; i++) {
1594             ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1595                          "forcing termination of child #%d (handle %d)", i, process_handles[i]);
1596             TerminateProcess((HANDLE) process_handles[i], 1);
1597         }
1598         return (0); /* Tell the caller we are shutting down */
1599     }
1600
1601     return (1); /* Tell the caller we want a restart */
1602 }
1603
1604 /* 
1605  * winnt_pre_config() hook
1606  */
1607 static void winnt_pre_config(ap_context_t *pconf, ap_context_t *plog, ap_context_t *ptemp) 
1608 {
1609     char *pid;
1610
1611     one_process = !!getenv("ONE_PROCESS");
1612
1613     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1614     GetVersionEx(&osver);
1615
1616     /* AP_PARENT_PID is only valid in the child */
1617     pid = getenv("AP_PARENT_PID");
1618     if (pid) {
1619         /* This is the child */
1620         parent_pid = atoi(pid);
1621         my_pid = getpid();
1622     }
1623     else {
1624         /* This is the parent */
1625         parent_pid = my_pid = getpid();
1626
1627     }
1628
1629     ap_listen_pre_config();
1630     ap_daemons_to_start = DEFAULT_NUM_DAEMON;
1631     ap_threads_per_child = DEFAULT_START_THREAD;
1632     ap_pid_fname = DEFAULT_PIDLOG;
1633     max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1634
1635     ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1636
1637 }
1638
1639 static void winnt_post_config(ap_context_t *pconf, ap_context_t *plog, ap_context_t *ptemp, server_rec* server_conf)
1640 {
1641     server_conf = server_conf;
1642 }
1643
1644 API_EXPORT(int) ap_mpm_run(ap_context_t *_pconf, ap_context_t *plog, server_rec *s )
1645 {
1646
1647     char* exit_event_name;
1648     static int restart = 0;             /* Default is to not restart */
1649 //    time_t tmstart;
1650     static HANDLE shutdown_event;       /* used to signal shutdown to parent */
1651     static HANDLE restart_event;        /* used to signal a restart to parent */
1652
1653     pconf = _pconf;
1654     server_conf = s;
1655
1656     if ((parent_pid != my_pid) || one_process) {
1657         /* Child process */
1658         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1659                      "Child %d: Child process is running", my_pid);        
1660         AMCSocketInitialize();
1661         exit_event_name = ap_psprintf(pconf, "apC%d", my_pid);
1662         setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1663
1664         if (one_process) {
1665             /* Create the IO CompletionPort */
1666             if (AcceptExCompPort == NULL) {
1667                 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1668                                                           NULL, 0, 0); 
1669                 if (AcceptExCompPort == NULL) {
1670                     ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1671                                  "Unable to create the AcceptExCompletionPort -- process will exit");
1672                     return -1;
1673                 }
1674             }
1675             ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1676             exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1677         }
1678         else {
1679             ap_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1680             exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1681             ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1682                          "Child %d: exit_event_name = %s", my_pid, exit_event_name);        
1683         }
1684         ap_assert(start_mutex);
1685         ap_assert(exit_event);
1686
1687         child_main();
1688
1689         CloseHandle(exit_event);
1690         AMCSocketCleanup();
1691         restart = 0;
1692     }
1693     else {
1694         /* Parent process */
1695         PSECURITY_ATTRIBUTES sa = GetNullACL();  /* returns NULL if invalid (Win95?) */
1696
1697         setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1698         if (!restart) {
1699             ap_log_pid(pconf, ap_pid_fname);
1700
1701             service_set_status(SERVICE_START_PENDING);
1702             AMCSocketInitialize();
1703 //            setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1704         
1705             /* Create shutdown event, apPID_shutdown, where PID is the parent 
1706              * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
1707              */
1708             shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
1709             if (!shutdown_event) {
1710                 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), s,
1711                              "master_main: Cannot create shutdown event %s", signal_shutdown_name);
1712                 CleanNullACL((void *)sa);
1713                 exit(1);
1714             }
1715
1716             /* Create restart event, apPID_restart, where PID is the parent 
1717              * Apache process ID. Restart is signaled by 'apache -k restart'.
1718              */
1719 //            restart_event = CreateEvent(sa, TRUE, FALSE, signal_restart_name);
1720             restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
1721             if (!restart_event) {
1722                 CloseHandle(shutdown_event);
1723                 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), s,
1724                              "ap_run_mpm: Cannot create restart event %s", signal_restart_name);
1725                 CleanNullACL((void *)sa);
1726                 exit(1);
1727             }
1728             CleanNullACL((void *)sa);
1729             
1730             /* Create the start mutex, apPID, where PID is the parent Apache process ID.
1731              * Ths start mutex is used during a restart to prevent more than one 
1732              * child process from entering the accept loop at once.
1733              */
1734 //            ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1735             ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,s->process->pool);
1736             /* TODO: Add some code to detect failure */
1737         }
1738
1739         /* Go to work... */
1740         restart = master_main(server_conf, shutdown_event, restart_event);
1741
1742         if (!restart) {
1743             const char *pidfile = NULL;
1744             /* Shutting down. Clean up... */
1745             pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1746             if ( pidfile != NULL && unlink(pidfile) == 0)
1747                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO,APR_SUCCESS,
1748                              server_conf, "removed PID file %s (pid=%ld)",
1749                              pidfile, (long)getpid());
1750             ap_destroy_lock(start_mutex);
1751
1752             CloseHandle(restart_event);
1753             CloseHandle(shutdown_event);
1754             AMCSocketCleanup();
1755
1756             service_set_status(SERVICE_STOPPED);
1757         }
1758     }
1759     return !restart;
1760 }
1761
1762 static void winnt_hooks(void)
1763 {
1764 //    INIT_SIGLIST()
1765     one_process = 0;
1766     /* Configuration hooks implemented by http_config.c ... */
1767     ap_hook_pre_config(winnt_pre_config, NULL, NULL, HOOK_MIDDLE);
1768 }
1769
1770 /* 
1771  * Command processors 
1772  */
1773 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg) 
1774 {
1775     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1776     if (err != NULL) {
1777         return err;
1778     }
1779
1780     if (cmd->server->is_virtual) {
1781         return "PidFile directive not allowed in <VirtualHost>";
1782     }
1783     ap_pid_fname = arg;
1784     return NULL;
1785 }
1786
1787 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg) 
1788 {
1789     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1790     if (err != NULL) {
1791         return err;
1792     }
1793
1794     ap_threads_per_child = atoi(arg);
1795     if (ap_threads_per_child > HARD_THREAD_LIMIT) {
1796         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1797                      "WARNING: ThreadsPerChild of %d exceeds compile time"
1798                      " limit of %d threads,", ap_threads_per_child, 
1799                      HARD_THREAD_LIMIT);
1800         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1801                      " lowering ThreadsPerChild to %d. To increase, please"
1802                      " see the  HARD_THREAD_LIMIT define in src/include/httpd.h.", 
1803                      HARD_THREAD_LIMIT);
1804     }
1805     else if (ap_threads_per_child < 1) {
1806         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1807                      "WARNING: Require ThreadsPerChild > 0, setting to 1");
1808         ap_threads_per_child = 1;
1809     }
1810     return NULL;
1811 }
1812
1813
1814 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg) 
1815 {
1816     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1817     if (err != NULL) {
1818         return err;
1819     }
1820
1821     max_requests_per_child = atoi(arg);
1822
1823     return NULL;
1824 }
1825
1826 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg) 
1827 {
1828     struct stat finfo;
1829     const char *fname;
1830     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1831     if (err != NULL) {
1832         return err;
1833     }
1834
1835     fname = ap_server_root_relative(cmd->pool, arg);
1836     if ((stat(fname, &finfo) == -1) || !S_ISDIR(finfo.st_mode)) {
1837         return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname, 
1838                           " does not exist or is not a directory", NULL);
1839     }
1840     ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1841     return NULL;
1842 }
1843
1844 /* Stub functions until this MPM supports the connection status API */
1845
1846 API_EXPORT(void) ap_update_connection_status(long conn_id, const char *key, \
1847                                              const char *value)
1848 {
1849     /* NOP */
1850 }
1851
1852 API_EXPORT(void) ap_reset_connection_status(long conn_id)
1853 {
1854     /* NOP */
1855 }
1856
1857 static const command_rec winnt_cmds[] = {
1858 LISTEN_COMMANDS
1859 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
1860     "A file for logging the server process ID"},
1861 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
1862   "Number of threads each child creates" },
1863 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
1864   "Maximum number of requests a particular child serves before dying." },
1865 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
1866   "The location of the directory Apache changes to before dumping core" },
1867 { NULL }
1868 };
1869
1870 module MODULE_VAR_EXPORT mpm_winnt_module = {
1871     STANDARD20_MODULE_STUFF,
1872     NULL,                       /* create per-directory config structure */
1873     NULL,                       /* merge per-directory config structures */
1874     NULL,                       /* create per-server config structure */
1875     NULL,                       /* merge per-server config structures */
1876     winnt_cmds,                 /* command ap_table_t */
1877     NULL,                       /* handlers */
1878     winnt_hooks                 /* register_hooks */
1879 };