1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
61 #include "http_main.h"
63 #include "http_config.h" /* for read_config */
64 #include "http_core.h" /* for get_remote_host */
65 #include "http_connection.h"
66 #include "apr_portable.h"
67 #include "apr_getopt.h"
69 #include "ap_config.h"
70 #include "ap_listen.h"
71 #include "mpm_default.h"
72 #include "iol_socket.h"
73 #include "mpm_winnt.h"
76 * Definitions of WINNT MPM specific config globals
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 static HANDLE shutdown_event; /* used to signal shutdown to parent */
84 static HANDLE restart_event; /* used to signal a restart to parent */
86 #define MAX_SIGNAL_NAME 30 /* Long enough for apPID_shutdown, where PID is an int */
87 char signal_name_prefix[MAX_SIGNAL_NAME];
88 char signal_restart_name[MAX_SIGNAL_NAME];
89 char signal_shutdown_name[MAX_SIGNAL_NAME];
91 static struct fd_set listenfds;
92 static int num_listenfds = 0;
93 static SOCKET listenmaxfd = INVALID_SOCKET;
95 static ap_pool_t *pconf; /* Pool for config stuff */
97 static char ap_coredump_dir[MAX_STRING_LEN];
99 static server_rec *server_conf;
100 static HANDLE AcceptExCompPort = NULL;
102 static int one_process = 0;
103 static char *signal_arg;
105 OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
107 int ap_max_requests_per_child=0;
108 int ap_daemons_to_start=0;
110 static event *exit_event;
111 HANDLE maintenance_event;
112 ap_lock_t *start_mutex;
116 /* This is the helper code to resolve late bound entry points
117 * missing from one or more releases of the Win32 API...
118 * but it sure would be nice if we didn't duplicate this code
122 static const char* const lateDllName[DLL_defined] = {
123 "kernel32", "advapi32", "mswsock", "ws2_32" };
124 static HMODULE lateDllHandle[DLL_defined] = {
125 NULL, NULL, NULL, NULL };
127 FARPROC ap_load_dll_func(ap_dlltoken_e fnLib, char* fnName, int ordinal)
129 if (!lateDllHandle[fnLib]) {
130 lateDllHandle[fnLib] = LoadLibrary(lateDllName[fnLib]);
131 if (!lateDllHandle[fnLib])
135 return GetProcAddress(lateDllHandle[fnLib], (char *) ordinal);
137 return GetProcAddress(lateDllHandle[fnLib], fnName);
140 static ap_status_t socket_cleanup(void *sock)
142 ap_socket_t *thesocket = sock;
144 if (ap_get_os_sock(&sd, thesocket) == APR_SUCCESS) {
150 /* A bunch or routines from os/win32/multithread.c that need to be merged into APR
151 * or thrown out entirely...
154 typedef void semaphore;
158 create_semaphore(int initial)
160 return(CreateSemaphore(NULL, initial, 1000000, NULL));
163 static void acquire_semaphore(semaphore *semaphore_id)
167 rv = WaitForSingleObject(semaphore_id, INFINITE);
172 static int release_semaphore(semaphore *semaphore_id)
174 return(ReleaseSemaphore(semaphore_id, 1, NULL));
177 static void destroy_semaphore(semaphore *semaphore_id)
179 CloseHandle(semaphore_id);
183 /* To share the semaphores with other processes, we need a NULL ACL
184 * Code from MS KB Q106387
186 static PSECURITY_ATTRIBUTES GetNullACL()
188 PSECURITY_DESCRIPTOR pSD;
189 PSECURITY_ATTRIBUTES sa;
191 sa = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES));
192 pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,
193 SECURITY_DESCRIPTOR_MIN_LENGTH);
194 if (pSD == NULL || sa == NULL) {
197 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
203 if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
209 sa->nLength = sizeof(sa);
210 sa->lpSecurityDescriptor = pSD;
211 sa->bInheritHandle = TRUE;
215 static void CleanNullACL( void *sa ) {
217 LocalFree( ((PSECURITY_ATTRIBUTES)sa)->lpSecurityDescriptor);
223 * The Win32 call WaitForMultipleObjects will only allow you to wait for
224 * a maximum of MAXIMUM_WAIT_OBJECTS (current 64). Since the threading
225 * model in the multithreaded version of apache wants to use this call,
226 * we are restricted to a maximum of 64 threads. This is a simplistic
227 * routine that will increase this size.
229 static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles,
233 DWORD dwRet = WAIT_TIMEOUT;
237 tStopTime = time(NULL) + dwSeconds;
245 for (dwIndex = 0; dwIndex * MAXIMUM_WAIT_OBJECTS < nCount; dwIndex++) {
246 dwRet = WaitForMultipleObjects(
247 min(MAXIMUM_WAIT_OBJECTS, nCount - (dwIndex * MAXIMUM_WAIT_OBJECTS)),
248 lpHandles + (dwIndex * MAXIMUM_WAIT_OBJECTS),
251 if (dwRet != WAIT_TIMEOUT) {
255 } while((time(NULL) < tStopTime) && (dwRet == WAIT_TIMEOUT));
261 * Signalling Apache on NT.
263 * Under Unix, Apache can be told to shutdown or restart by sending various
264 * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
265 * we use "events" instead. The parent apache process goes into a loop
266 * where it waits forever for a set of events. Two of those events are
272 * (where PID is the PID of the apache parent process). When one of these
273 * is signalled, the Apache parent performs the appropriate action. The events
274 * can become signalled through internal Apache methods (e.g. if the child
275 * finds a fatal error and needs to kill its parent), via the service
276 * control manager (the control thread will signal the shutdown event when
277 * requested to stop the Apache service), from the -k Apache command line,
278 * or from any external program which finds the Apache PID from the
281 * The signal_parent() function, below, is used to signal one of these events.
282 * It can be called by any child or parent process, since it does not
283 * rely on global variables.
285 * On entry, type gives the event to signal. 0 means shutdown, 1 means
288 void signal_parent(int type)
293 /* after updating the shutdown_pending or restart flags, we need
294 * to wake up the parent process so it can see the changes. The
295 * parent will normally be waiting for either a child process
296 * to die, or for a signal on the "spache-signal" event. So set the
297 * "apache-signal" event here.
304 case 0: signal_name = signal_shutdown_name; break;
305 case 1: signal_name = signal_restart_name; break;
308 e = OpenEvent(EVENT_ALL_ACCESS, FALSE, signal_name);
310 /* Um, problem, can't signal the parent, which means we can't
311 * signal ourselves to die. Ignore for now...
313 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
314 "OpenEvent on %s event", signal_name);
317 if (SetEvent(e) == 0) {
318 /* Same problem as above */
319 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
320 "SetEvent on %s event", signal_name);
327 static int volatile is_graceful = 0;
329 API_EXPORT(int) ap_graceful_stop_signalled(void)
334 API_EXPORT(void) ap_start_shutdown(void)
340 * Initialise the signal names, in the global variables signal_name_prefix,
341 * signal_restart_name and signal_shutdown_name.
344 void setup_signal_names(char *prefix)
346 ap_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);
347 ap_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name),
348 "%s_shutdown", signal_name_prefix);
349 ap_snprintf(signal_restart_name, sizeof(signal_restart_name),
350 "%s_restart", signal_name_prefix);
354 * Routines that deal with sockets, some are WIN32 specific...
357 static void sock_disable_nagle(int s)
359 /* The Nagle algorithm says that we should delay sending partial
360 * packets in hopes of getting more data. We don't want to do
361 * this; we are not telnet. There are bad interactions between
362 * persistent connections and Nagle's algorithm that have very severe
363 * performance penalties. (Failing to disable Nagle is not much of a
364 * problem with simple HTTP.)
366 * In spite of these problems, failure here is not a shooting offense.
370 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
372 ap_log_error(APLOG_MARK, APLOG_WARNING, APR_SUCCESS, server_conf,
373 "setsockopt: (TCP_NODELAY)");
378 * Routines to deal with managing the list of listening sockets.
380 static ap_listen_rec *head_listener;
382 static ap_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
387 for (lr = head_listener; lr ; lr = lr->next) {
388 ap_get_os_sock(&nsd, lr->sd);
389 if (FD_ISSET(nsd, main_fds)) {
390 head_listener = lr->next;
391 if (head_listener == NULL)
392 head_listener = ap_listeners;
400 static int setup_listeners(server_rec *s)
403 int num_listeners = 0;
406 /* Setup the listeners */
409 if (ap_listen_open(s->process, s->port)) {
412 for (lr = ap_listeners; lr; lr = lr->next) {
414 if (lr->sd != NULL) {
415 ap_get_os_sock(&nsd, lr->sd);
416 FD_SET(nsd, &listenfds);
417 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
424 head_listener = ap_listeners;
426 return num_listeners;
429 static int setup_inherited_listeners(server_rec *s)
431 WSAPROTOCOL_INFO WSAProtocolInfo;
435 int num_listeners = 0;
438 /* Setup the listeners */
441 /* Set up a default listener if necessary */
443 if (ap_listeners == NULL) {
445 lr = ap_palloc(s->process->pool, sizeof(ap_listen_rec));
449 lr->next = ap_listeners;
453 /* Open the pipe to the parent process to receive the inherited socket
454 * data. The sockets have been set to listening in the parent process.
456 pipe = GetStdHandle(STD_INPUT_HANDLE);
457 for (lr = ap_listeners; lr; lr = lr->next) {
458 if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
459 &BytesRead, (LPOVERLAPPED) NULL)) {
460 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
461 "setup_inherited_listeners: Unable to read socket data from parent");
462 signal_parent(0); /* tell parent to die */
465 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
466 "Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.", my_pid);
467 nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
468 &WSAProtocolInfo, 0, 0);
469 if (nsd == INVALID_SOCKET) {
470 ap_log_error(APLOG_MARK, APLOG_CRIT, WSAGetLastError(), server_conf,
471 "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
472 signal_parent(0); /* tell parent to die */
476 FD_SET(nsd, &listenfds);
477 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
481 ap_put_os_sock(&lr->sd, &nsd, pconf);
484 /* Now, read the AcceptExCompPort from the parent */
485 ReadFile(pipe, &AcceptExCompPort, sizeof(AcceptExCompPort), &BytesRead, (LPOVERLAPPED) NULL);
488 for (lr = ap_listeners; lr; lr = lr->next) {
492 head_listener = ap_listeners;
493 return num_listeners;
496 static void bind_listeners_to_completion_port()
498 /* Associate the open listeners with the completion port.
499 * Bypass the operation for Windows 95/98
503 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
504 for (lr = ap_listeners; lr; lr = lr->next) {
506 ap_get_os_sock(&nsd,lr->sd);
507 CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
512 /**********************************************************************
513 * Multithreaded implementation
515 * This code is fairly specific to Win32.
517 * The model used to handle requests is a set of threads. One "main"
518 * thread listens for new requests. When something becomes
519 * available, it does a select and places the newly available socket
520 * onto a list of "jobs" (add_job()). Then any one of a fixed number
521 * of "worker" threads takes the top job off the job list with
522 * remove_job() and handles that connection to completion. After
523 * the connection has finished the thread is free to take another
524 * job from the job list.
526 * In the code, the "main" thread is running within the child_main()
527 * function. The first thing this function does is create the
528 * worker threads, which operate in the child_sub_main() function. The
529 * main thread then goes into a loop within child_main() where they
530 * do a select() on the listening sockets. The select times out once
531 * per second so that the thread can check for an "exit" signal
532 * from the parent process (see below). If this signal is set, the
533 * thread can exit, but only after it has accepted all incoming
534 * connections already in the listen queue (since Win32 appears
535 * to through away listened but unaccepted connections when a
538 * Because the main and worker threads exist within a single process
539 * they are vulnerable to crashes or memory leaks (crashes can also
540 * be caused within modules, of course). There also needs to be a
541 * mechanism to perform restarts and shutdowns. This is done by
542 * creating the main & worker threads within a subprocess. A
543 * main process (the "parent process") creates one (or more)
544 * processes to do the work, then the parent sits around waiting
545 * for the working process to die, in which case it starts a new
546 * one. The parent process also handles restarts (by creating
547 * a new working process then signalling the previous working process
548 * exit ) and shutdowns (by signalling the working process to exit).
549 * The parent process operates within the master_main() function. This
550 * process also handles requests from the service manager (NT only).
552 * Signalling between the parent and working process uses a Win32
553 * event. Each child has a unique name for the event, which is
554 * passed to it with the -Z argument when the child is spawned. The
555 * parent sets (signals) this event to tell the child to die.
556 * At present all children do a graceful die - they finish all
557 * current jobs _and_ empty the listen queue before they exit.
558 * A non-graceful die would need a second event. The -Z argument in
559 * the child is also used to create the shutdown and restart events,
560 * since the prefix (apPID) contains the parent process PID.
562 * The code below starts with functions at the lowest level -
563 * worker threads, and works up to the top level - the main()
564 * function of the parent process.
566 * The scoreboard (in process memory) contains details of the worker
567 * threads (within the active working process). There is no shared
568 * "scoreboard" between processes, since only one is ever active
569 * at once (or at most, two, when one has been told to shutdown but
570 * is processes outstanding requests, and a new one has been started).
571 * This is controlled by a "start_mutex" which ensures only one working
572 * process is active at once.
573 **********************************************************************/
577 * Definition of jobs, shared by main and worker threads.
580 typedef struct joblist_s {
581 struct joblist_s *next;
586 * Globals common to main and worker threads. This structure is not
587 * used by the parent process.
590 typedef struct globals_s {
591 semaphore *jobsemaphore;
598 globals allowed_globals =
599 {NULL, NULL, NULL, NULL, 0};
600 #define MAX_SELECT_ERRORS 100
601 #define PADDED_ADDR_SIZE sizeof(SOCKADDR_IN)+16
603 /* Windows 9x specific code...
604 * Accept processing for on Windows 95/98 uses a producer/consumer queue
605 * model. A single thread accepts connections and queues the accepted socket
606 * to the accept queue for consumption by a pool of worker threads.
608 * win9x_get_connection()
609 * Calls remove_job() to pull a job from the accept queue. All the worker
610 * threads block on remove_job.
611 * accept_and_queue_connections()
612 * The accept threads runs this function, which accepts connections off
613 * the network and calls add_job() to queue jobs to the accept_queue.
614 * add_job()/remove_job()
615 * Add or remove an accepted socket from the list of sockets
616 * connected to clients. allowed_globals.jobmutex protects
617 * against multiple concurrent access to the linked list of jobs.
619 static void add_job(int sock)
623 new_job = (joblist *) malloc(sizeof(joblist));
624 if (new_job == NULL) {
625 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
626 "Ouch! Out of memory in add_job()!");
629 new_job->next = NULL;
630 new_job->sock = sock;
632 ap_lock(allowed_globals.jobmutex);
634 if (allowed_globals.jobtail != NULL)
635 allowed_globals.jobtail->next = new_job;
636 allowed_globals.jobtail = new_job;
637 if (!allowed_globals.jobhead)
638 allowed_globals.jobhead = new_job;
639 allowed_globals.jobcount++;
640 release_semaphore(allowed_globals.jobsemaphore);
642 ap_unlock(allowed_globals.jobmutex);
645 static int remove_job(void)
650 acquire_semaphore(allowed_globals.jobsemaphore);
651 ap_lock(allowed_globals.jobmutex);
653 if (workers_may_exit && !allowed_globals.jobhead) {
654 ap_unlock(allowed_globals.jobmutex);
657 job = allowed_globals.jobhead;
659 allowed_globals.jobhead = job->next;
660 if (allowed_globals.jobhead == NULL)
661 allowed_globals.jobtail = NULL;
662 ap_unlock(allowed_globals.jobmutex);
669 static void accept_and_queue_connections(void * dummy)
671 int requests_this_child = 0;
676 int nsd = INVALID_SOCKET;
677 struct sockaddr_in sa_client;
678 int count_select_errors = 0;
682 while (!workers_may_exit) {
683 if (ap_max_requests_per_child && (requests_this_child > ap_max_requests_per_child)) {
687 tv.tv_sec = wait_time;
689 memcpy(&main_fds, &listenfds, sizeof(fd_set));
691 rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
693 if (rc == 0 || (rc == SOCKET_ERROR && h_errno == WSAEINTR)) {
694 count_select_errors = 0; /* reset count of errors */
697 else if (rc == SOCKET_ERROR) {
698 /* A "real" error occurred, log it and increment the count of
699 * select errors. This count is used to ensure we don't go into
700 * a busy loop of continuous errors.
702 ap_log_error(APLOG_MARK, APLOG_INFO, h_errno, server_conf,
703 "select failed with errno %d", h_errno);
704 count_select_errors++;
705 if (count_select_errors > MAX_SELECT_ERRORS) {
706 workers_may_exit = 1;
707 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
708 "Too many errors in select loop. Child process exiting.");
714 lr = find_ready_listener(&main_fds);
716 /* fetch the native socket descriptor */
717 ap_get_os_sock(&nsd, lr->sd);
722 clen = sizeof(sa_client);
723 csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
724 if (csd == INVALID_SOCKET) {
727 } while (csd < 0 && h_errno == WSAEINTR);
730 if (h_errno != WSAECONNABORTED) {
731 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
732 "accept: (client socket)");
737 requests_this_child++;
740 SetEvent(exit_event);
742 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
746 if (context == NULL) {
747 /* allocate the completion context and the transaction pool */
748 context = ap_pcalloc(pconf, sizeof(COMP_CONTEXT));
750 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
751 "win9x_get_connection: ap_pcalloc() failed. Process will exit.");
754 ap_create_pool(&context->ptrans, pconf);
759 ap_clear_pool(context->ptrans);
760 context->accept_socket = remove_job();
761 if (context->accept_socket == -1) {
764 len = sizeof(struct sockaddr);
765 context->sa_server = ap_palloc(context->ptrans, len);
766 if (getsockname(context->accept_socket,
767 context->sa_server, &len)== SOCKET_ERROR) {
768 ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(), server_conf,
769 "getsockname failed");
772 len = sizeof(struct sockaddr);
773 context->sa_client = ap_palloc(context->ptrans, len);
774 if ((getpeername(context->accept_socket,
775 context->sa_client, &len)) == SOCKET_ERROR) {
776 ap_log_error(APLOG_MARK, APLOG_WARNING, h_errno, server_conf,
777 "getpeername failed with error %d\n", WSAGetLastError());
778 memset(&context->sa_client, '\0', sizeof(context->sa_client));
781 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
783 /* do we NEED_DUPPED_CSD ?? */
790 * Windows 2000/NT specific code...
791 * create_acceptex_context()
792 * reset_acceptex_context()
793 * drain_acceptex_complport()
794 * winnt_get_connection()
796 * TODO: Insert a discussion of 'completion contexts' and what these function do here...
798 static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp)
801 PCOMP_CONTEXT context;
809 rc = GetQueuedCompletionStatus(hComplPort, &BytesRead, &CompKey,
812 lastError = GetLastError();
813 if (lastError == ERROR_OPERATION_ABORTED) {
814 ap_log_error(APLOG_MARK,APLOG_INFO,lastError, server_conf,
815 "Child %d: - Draining a packet off the completion port.", my_pid);
820 ap_log_error(APLOG_MARK,APLOG_INFO,APR_SUCCESS, server_conf,
821 "Child %d: - Nuking an active connection. context = %x", my_pid, context);
822 context = (PCOMP_CONTEXT) pol;
823 if (context && bCleanUp) {
824 /* It is only valid to clean-up in the process that initiated the I/O */
825 closesocket(context->accept_socket);
826 CloseHandle(context->Overlapped.hEvent);
830 static int create_acceptex_context(ap_pool_t *_pconf, ap_listen_rec *lr)
832 PCOMP_CONTEXT context;
837 /* allocate the completion context */
838 context = ap_pcalloc(_pconf, sizeof(COMP_CONTEXT));
840 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
841 "create_acceptex_context: ap_pcalloc() failed. Process will exit.");
845 /* initialize the completion context */
847 context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
848 if (context->Overlapped.hEvent == NULL) {
849 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
850 "create_acceptex_context: CreateEvent() failed. Process will exit.");
854 /* create and initialize the accept socket */
855 ap_get_os_sock(&nsd, context->lr->sd);
856 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
857 if (context->accept_socket == INVALID_SOCKET) {
858 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
859 "create_acceptex_context: socket() failed. Process will exit.");
863 /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
864 if (setsockopt(context->accept_socket, SOL_SOCKET,
865 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
867 ap_log_error(APLOG_MARK, APLOG_ERR, WSAGetLastError(), server_conf,
868 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
869 /* Not a failure condition. Keep running. */
872 ap_create_pool(&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;
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,
882 0, //context->recv_buf_size,
883 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
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.");
898 static ap_inline ap_status_t reset_acceptex_context(PCOMP_CONTEXT context)
904 context->lr->count++;
906 /* recreate and initialize the accept socket if it is not being reused */
907 ap_get_os_sock(&nsd, context->lr->sd);
908 if (context->accept_socket == INVALID_SOCKET) {
909 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
910 if (context->accept_socket == INVALID_SOCKET) {
911 lasterror = WSAGetLastError();
912 ap_log_error(APLOG_MARK,APLOG_ERR, lasterror, server_conf,
913 "reset_acceptex_context: socket() failed. Process will exit.");
917 /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
918 if (setsockopt(context->accept_socket, SOL_SOCKET,
919 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
921 ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(),
923 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
924 /* Not a failure condition. Keep running. */
928 /* reset the completion context */
929 ap_clear_pool(context->ptrans);
930 context->sock = NULL;
931 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
932 context->recv_buf = context->conn_io->inbase;
933 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
935 /* AcceptEx on the completion context. The completion context will be signaled
936 * when a connection is accepted. */
937 if (!AcceptEx(nsd, context->accept_socket, context->recv_buf, 0,
938 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE, &BytesRead,
939 (LPOVERLAPPED) context)) {
940 lasterror = WSAGetLastError();
941 if (lasterror != ERROR_IO_PENDING) {
942 ap_log_error(APLOG_MARK, APLOG_INFO, lasterror, server_conf,
943 "reset_acceptex_context: AcceptEx failed for "
944 "listening socket: %d and accept socket: %d",
945 nsd, context->accept_socket);
946 context->accept_socket = INVALID_SOCKET;
953 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
955 int requests_this_child = 0;
961 if (workers_may_exit) {
962 /* Child shutdown has been signaled */
964 CloseHandle(context->Overlapped.hEvent);
967 if (!workers_may_exit && (context != NULL)) {
968 /* Prepare the completion context for reuse */
969 if (reset_acceptex_context(context) != APR_SUCCESS) {
970 /* Retry once, this time requesting a new socket */
971 if (context->accept_socket != INVALID_SOCKET) {
972 closesocket(context->accept_socket);
973 context->accept_socket = INVALID_SOCKET;
975 if (reset_acceptex_context(context) != APR_SUCCESS) {
976 /* Failed again, so give up, but leave the thread up
977 * Should we signal a shutdown now?
979 if (context->accept_socket != INVALID_SOCKET)
980 closesocket(context->accept_socket);
981 CloseHandle(context->Overlapped.hEvent);
987 rc = GetQueuedCompletionStatus(AcceptExCompPort,
994 /* During a restart, the new child process can catch
995 * ERROR_OPERATION_ABORTED completion packets
996 * posted by the old child process. Just continue...
998 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
999 "Child %d: - GetQueuedCompletionStatus() failed", my_pid);
1003 /* Check the Completion Key.
1004 * == my_pid indicate this process wants to exit
1005 * == 0 implies valid i/o completion
1006 * != 0 implies a posted completion packet by an old
1007 * process. Just ignore it.
1009 if (CompKey == my_pid) {
1016 context = (PCOMP_CONTEXT) pol;
1020 /* Check to see if we need to create more completion contexts,
1021 * but only if we are not in the process of shutting down
1023 if (!workers_may_exit) {
1024 ap_lock(allowed_globals.jobmutex);
1025 context->lr->count--;
1026 if (context->lr->count < 2) {
1027 SetEvent(maintenance_event);
1029 ap_unlock(allowed_globals.jobmutex);
1032 /* Received a connection */
1033 context->conn_io->incnt = BytesRead;
1034 GetAcceptExSockaddrs(context->recv_buf,
1035 0, //context->recv_buf_size,
1038 &context->sa_server,
1039 &context->sa_server_len,
1040 &context->sa_client,
1041 &context->sa_client_len);
1047 * worker_main() - this is the main loop for the worker threads
1050 * Each thread runs within this function. They wait within remove_job()
1051 * for a job to become available, then handle all the requests on that
1052 * connection until it is closed, then return to remove_job().
1054 * The worker thread will exit when it removes a job which contains
1055 * socket number -1. This provides a graceful thread exit, since
1056 * it will never exit during a connection.
1058 * This code in this function is basically equivalent to the child_main()
1059 * from the multi-process (Unix) environment, except that we
1061 * - do not call child_init_modules (child init API phase)
1062 * - block in remove_job, and when unblocked we have an already
1063 * accepted socket, instead of blocking on a mutex or select().
1066 static void worker_main(int child_num)
1068 PCOMP_CONTEXT context = NULL;
1071 conn_rec *current_conn;
1074 /* Grab a connection off the network */
1075 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1076 context = win9x_get_connection(context);
1079 context = winnt_get_connection(context);
1084 sock_disable_nagle(context->accept_socket);
1085 ap_put_os_sock(&context->sock, &context->accept_socket, context->ptrans);
1087 iol = win32_attach_socket(context->ptrans, context->sock);
1089 ap_log_error(APLOG_MARK, APLOG_ERR, APR_ENOMEM, server_conf,
1090 "worker_main: attach_socket() failed. Continuing...");
1091 closesocket(context->accept_socket);
1094 ap_bpush_iol(context->conn_io, iol);
1095 current_conn = ap_new_connection(context->ptrans, server_conf, context->conn_io,
1096 (struct sockaddr_in *) context->sa_client,
1097 (struct sockaddr_in *) context->sa_server,
1100 ap_process_connection(current_conn);
1101 ap_lingering_close(current_conn);
1102 context->accept_socket = INVALID_SOCKET;
1105 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1106 "Child %d: Thread exiting.", my_pid);
1109 SetEvent(exit_event);
1111 /* TODO: Add code to clean-up completion contexts here */
1114 static void cleanup_thread(thread **handles, int *thread_cnt, int thread_to_clean)
1118 CloseHandle(handles[thread_to_clean]);
1119 for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1120 handles[i] = handles[i + 1];
1124 static void create_listeners()
1126 #define NUM_LISTENERS 5
1128 for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1129 while (lr->count < NUM_LISTENERS) {
1130 if (create_acceptex_context(pconf, lr) == -1) {
1131 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1132 "Unable to create an AcceptEx completion context -- process will exit");
1133 signal_parent(0); /* tell parent to die */
1139 * child_main() runs the main control thread for the child process.
1141 * The control thread:
1142 * - sets up the worker thread pool
1143 * - starts the accept thread (Win 9x)
1144 * - creates AcceptEx contexts (Win NT)
1145 * - waits for exit_event, maintenance_event or maintenance timeout
1146 * and does the right thing depending on which event is received.
1148 static void child_main()
1151 HANDLE child_events[2];
1152 char* exit_event_name;
1153 int nthreads = ap_threads_per_child;
1155 thread **child_handles;
1163 /* This is the child process or we are running in single process
1166 exit_event_name = ap_psprintf(pconf, "apC%d", my_pid);
1167 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1170 /* Single process mode */
1171 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1172 exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1174 setup_listeners(server_conf);
1175 bind_listeners_to_completion_port();
1178 /* Child process mode */
1179 ap_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1180 exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1181 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1182 "Child %d: exit_event_name = %s", my_pid, exit_event_name);
1184 setup_inherited_listeners(server_conf);
1187 /* Initialize the child_events */
1188 maintenance_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1189 child_events[0] = exit_event;
1190 child_events[1] = maintenance_event;
1192 ap_assert(start_mutex);
1193 ap_assert(exit_event);
1194 ap_assert(maintenance_event);
1196 ap_create_pool(&pchild, pconf);
1197 allowed_globals.jobsemaphore = create_semaphore(0);
1198 ap_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
1201 * Wait until we have permission to start accepting connections.
1202 * start_mutex is used to ensure that only one child ever
1203 * goes into the listen/accept loop at once.
1205 status = ap_lock(start_mutex);
1206 if (status != APR_SUCCESS) {
1207 ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
1208 "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1209 signal_parent(0); /* tell parent to die */
1212 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1213 "Child %d: Acquired the start mutex.", my_pid);
1215 /* Create the worker thread pool */
1216 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1217 "Child %d: Starting %d worker threads.", my_pid, nthreads);
1218 child_handles = (thread *) alloca(nthreads * sizeof(int));
1219 for (i = 0; i < nthreads; i++) {
1220 child_handles[i] = (thread *) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1221 NULL, 0, &thread_id);
1224 /* Begin accepting connections */
1225 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1226 /* Win95/98: Start the accept thread */
1227 _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) accept_and_queue_connections,
1228 (void *) i, 0, &thread_id);
1230 /* Windows NT/2000: Create AcceptEx completion contexts */
1234 /* Wait for one of three events:
1236 * The exit_event is signaled by the parent process to notify
1237 * the child that it is time to exit.
1239 * maintenance_event:
1240 * This event is signaled by the worker thread pool to direct
1241 * this thread to create more completion contexts.
1244 * To do periodic maintenance on the server (check for thread exits,
1245 * number of completion contexts, etc.)
1247 while (!workers_may_exit) {
1248 rv = WaitForMultipleObjects(2, (HANDLE *) child_events, FALSE, INFINITE);
1249 cld = rv - WAIT_OBJECT_0;
1250 if (rv == WAIT_FAILED) {
1251 /* Something serious is wrong */
1252 workers_may_exit = 1;
1253 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1254 "Child %d: WAIT_FAILED -- shutting down server");
1256 else if (rv == WAIT_TIMEOUT) {
1257 /* Hey, this cannot happen */
1258 workers_may_exit = 1;
1259 ap_log_error(APLOG_MARK, APLOG_CRIT, APR_SUCCESS, server_conf,
1260 "Child %d: WAIT_TIMEOUT -- shutting down server", my_pid);
1262 else if (cld == 0) {
1263 /* Exit event was signaled */
1264 workers_may_exit = 1;
1265 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1266 "Child %d: Exit event signaled. Child process is ending.", my_pid);
1269 /* Child maintenance event signaled */
1270 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1273 ResetEvent(maintenance_event);
1274 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1275 "Child %d: Child maintenance event signaled.", my_pid);
1279 /* Setting is_graceful will close keep-alive connections
1282 /* Shutdown the worker threads */
1283 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1284 for (i = 0; i < nthreads; i++) {
1288 else { /* Windows NT/2000 */
1292 * First thing to do is to drain all the completion contexts off the
1293 * AcceptEx iocp. Give a busy server the chance to drain
1294 * the port by servicing connections (workers_may_exit prevents new
1295 * AcceptEx completion contexts from being queued to the port).
1299 /* Cancel any remaining pending async i/o.
1300 * This will cause io completion packets to be queued to the
1301 * port for any remaining active contexts
1303 for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1304 ap_get_os_sock(&nsd,lr->sd);
1305 CancelIo((HANDLE) nsd);
1308 /* Drain the canceled contexts off the port */
1309 drain_acceptex_complport(AcceptExCompPort, FALSE);
1311 /* Hopefully by now, all the completion contexts should be drained
1312 * off the port. There could still be some cancel io completion packets
1313 * flying around in the kernel... We will cover this possibility later..
1315 * Consider using HasOverlappedIoCompleted()...
1317 * Next task is to unblock all the threads blocked on
1318 * GetQueuedCompletionStatus()
1321 for (i=0; i < nthreads*2; i++) {
1322 PostQueuedCompletionStatus(AcceptExCompPort, 0, my_pid, NULL);
1325 /* Give the worker threads time to realize they've been posted */
1329 /* Release the start_mutex to let the new process (in the restart
1330 * scenario) a chance to begin servicing requests
1332 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1333 "Child %d: Releasing the start mutex", my_pid);
1334 ap_unlock(start_mutex);
1336 /* Give busy worker threads a chance to service their connections.
1337 * Kill them off if they take too long
1339 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1340 "Child %d: Waiting for %d threads to die.", my_pid, nthreads);
1341 end_time = time(NULL) + 180;
1343 rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1344 if (rv != WAIT_TIMEOUT) {
1345 rv = rv - WAIT_OBJECT_0;
1346 ap_assert((rv >= 0) && (rv < nthreads));
1347 cleanup_thread(child_handles, &nthreads, rv);
1352 for (i = 0; i < nthreads; i++) {
1353 TerminateThread(child_handles[i], 1);
1354 CloseHandle(child_handles[i]);
1356 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1357 "Child %d: All worker threads have ended.", my_pid);
1359 CloseHandle(AcceptExCompPort);
1360 destroy_semaphore(allowed_globals.jobsemaphore);
1361 ap_destroy_lock(allowed_globals.jobmutex);
1363 ap_destroy_pool(pchild);
1364 CloseHandle(exit_event);
1368 * Spawn a child Apache process. The child process has the command line arguments from
1369 * argc and argv[], plus a -Z argument giving the name of an event. The child should
1370 * open and poll or wait on this event. When it is signalled, the child should die.
1371 * prefix is a prefix string for the event name.
1373 * The child_num argument on entry contains a serial number for this child (used to create
1374 * a unique event name). On exit, this number will have been incremented by one, ready
1375 * for the next call.
1377 * On exit, the value pointed to be *ev will contain the event created
1378 * to signal the new child process.
1380 * The return value is the handle to the child process if successful, else -1. If -1 is
1381 * returned the error will already have been logged by ap_log_error().
1384 /**********************************************************************
1385 * master_main - this is the parent (main) process. We create a
1386 * child process to do the work, then sit around waiting for either
1387 * the child to exit, or a restart or exit signal. If the child dies,
1388 * we just respawn a new one. If we have a shutdown or graceful restart,
1389 * tell the child to die when it is ready. If it is a non-graceful
1390 * restart, force the child to die immediately.
1391 **********************************************************************/
1393 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1395 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1400 CloseHandle(handles[position]);
1401 CloseHandle(events[position]);
1403 handle = (int)handles[position];
1405 for (i = position; i < (*processes)-1; i++) {
1406 handles[i] = handles[i + 1];
1407 events[i] = events[i + 1];
1412 static int create_process(ap_pool_t *p, HANDLE *handles, HANDLE *events, int *processes)
1421 STARTUPINFO si; /* Filled in prior to call to CreateProcess */
1422 PROCESS_INFORMATION pi; /* filled in on call to CreateProcess */
1426 HANDLE hPipeRead = NULL;
1427 HANDLE hPipeWrite = NULL;
1428 SECURITY_ATTRIBUTES sa = {0};
1431 LPWSAPROTOCOL_INFO lpWSAProtocolInfo;
1432 HANDLE hDupedCompPort;
1434 sa.nLength = sizeof(sa);
1435 sa.bInheritHandle = TRUE;
1436 sa.lpSecurityDescriptor = NULL;
1438 /* Build the command line. Should look something like this:
1439 * C:/apache/bin/apache.exe -f ap_server_confname
1440 * First, get the path to the executable...
1442 rv = GetModuleFileName(NULL, buf, sizeof(buf));
1443 if (rv == sizeof(buf)) {
1444 ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1445 "Parent: Path to Apache process too long");
1447 } else if (rv == 0) {
1448 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1449 "Parent: GetModuleFileName() returned NULL for current process.");
1453 /* Build the command line */
1454 pCommand = ap_psprintf(p, "\"%s\"", buf);
1455 for (i = 1; i < server_conf->process->argc; i++) {
1456 pCommand = ap_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1459 /* Build the environment, since Win9x disrespects the active env */
1460 pEnvVar = ap_psprintf(p, "AP_PARENT_PID=%i", parent_pid);
1462 * Win32's CreateProcess call requires that the environment
1463 * be passed in an environment block, a null terminated block of
1464 * null terminated strings.
1468 while (_environ[i]) {
1469 iEnvBlockLen += strlen(_environ[i]) + 1;
1473 pEnvBlock = (char *)ap_pcalloc(p, iEnvBlockLen + strlen(pEnvVar) + 1);
1474 strcpy(pEnvBlock, pEnvVar);
1475 pEnvVar = strchr(pEnvBlock, '\0') + 1;
1478 while (_environ[i]) {
1479 strcpy(pEnvVar, _environ[i]);
1480 pEnvVar = strchr(pEnvVar, '\0') + 1;
1484 /* Create a pipe to send socket info to the child */
1485 if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1486 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1487 "Parent: Unable to create pipe to child process.\n");
1491 /* Give the read end of the pipe (hPipeRead) to the child as stdin. The
1492 * parent will write the socket data to the child on this pipe.
1494 memset(&si, 0, sizeof(si));
1495 memset(&pi, 0, sizeof(pi));
1497 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1498 si.wShowWindow = SW_HIDE;
1499 si.hStdInput = hPipeRead;
1501 if (!CreateProcess(NULL, pCommand, NULL, NULL,
1502 TRUE, /* Inherit handles */
1503 CREATE_SUSPENDED, /* Creation flags */
1504 pEnvBlock, /* Environment block */
1507 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1508 "Parent: Not able to create the child process.");
1510 * We must close the handles to the new process and its main thread
1511 * to prevent handle and memory leaks.
1513 CloseHandle(pi.hProcess);
1514 CloseHandle(pi.hThread);
1518 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1519 "Parent: Created child process %d", pi.dwProcessId);
1521 SetEnvironmentVariable("AP_PARENT_PID",NULL);
1523 /* Create the exit_event, apCchild_pid */
1524 sa.nLength = sizeof(sa);
1525 sa.bInheritHandle = TRUE;
1526 sa.lpSecurityDescriptor = NULL;
1527 kill_event = CreateEvent(&sa, TRUE, FALSE, ap_psprintf(pconf,"apC%d", pi.dwProcessId));
1529 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1530 "Parent: Could not create exit event for child process");
1531 CloseHandle(pi.hProcess);
1532 CloseHandle(pi.hThread);
1536 /* Assume the child process lives. Update the process and event tables */
1537 handles[*processes] = pi.hProcess;
1538 events[*processes] = kill_event;
1541 /* We never store the thread's handle, so close it now. */
1542 ResumeThread(pi.hThread);
1543 CloseHandle(pi.hThread);
1545 /* Run the chain of open sockets. For each socket, duplicate it
1546 * for the target process then send the WSAPROTOCOL_INFO
1547 * (returned by dup socket) to the child */
1548 for (lr = ap_listeners; lr; lr = lr->next) {
1550 lpWSAProtocolInfo = ap_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1551 ap_get_os_sock(&nsd,lr->sd);
1552 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1553 "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1554 if (WSADuplicateSocket(nsd, pi.dwProcessId,
1555 lpWSAProtocolInfo) == SOCKET_ERROR) {
1556 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, server_conf,
1557 "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1561 if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1563 (LPOVERLAPPED) NULL)) {
1564 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1565 "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1568 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1569 "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1571 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1572 /* Now, send the AcceptEx completion port to the child */
1573 if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort,
1574 pi.hProcess, &hDupedCompPort, 0,
1575 TRUE, DUPLICATE_SAME_ACCESS)) {
1576 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1577 "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1581 WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1584 CloseHandle(hPipeRead);
1585 CloseHandle(hPipeWrite);
1590 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1592 int remaining_children_to_start = ap_daemons_to_start;
1596 int restart_pending = 0;
1597 int shutdown_pending = 0;
1598 int current_live_processes = 0; /* number of child process we know about */
1600 HANDLE process_handles[MAX_PROCESSES];
1601 HANDLE process_kill_events[MAX_PROCESSES];
1604 bind_listeners_to_completion_port();
1606 /* Create child process
1607 * Should only be one in this version of Apache for WIN32
1609 while (remaining_children_to_start--) {
1610 if (create_process(pconf, process_handles, process_kill_events,
1611 ¤t_live_processes) < 0) {
1612 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1613 "master_main: create child process failed. Exiting.");
1614 shutdown_pending = 1;
1619 restart_pending = shutdown_pending = 0;
1621 if (!strcasecmp(signal_arg, "runservice"))
1622 mpm_service_started();
1624 /* Wait for shutdown or restart events or for child death */
1625 process_handles[current_live_processes] = shutdown_event;
1626 process_handles[current_live_processes+1] = restart_event;
1628 rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles,
1630 cld = rv - WAIT_OBJECT_0;
1631 if (rv == WAIT_FAILED) {
1632 /* Something serious is wrong */
1633 ap_log_error(APLOG_MARK,APLOG_CRIT, GetLastError(), server_conf,
1634 "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1635 shutdown_pending = 1;
1637 else if (rv == WAIT_TIMEOUT) {
1638 /* Hey, this cannot happen */
1639 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1640 "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1641 shutdown_pending = 1;
1643 else if (cld == current_live_processes) {
1644 /* shutdown_event signalled */
1645 shutdown_pending = 1;
1646 printf("shutdown event signaled\n");
1647 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1648 "master_main: Shutdown event signaled -- doing server shutdown.");
1649 if (ResetEvent(shutdown_event) == 0) {
1650 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1651 "ResetEvent(shutdown_event)");
1655 else if (cld == current_live_processes+1) {
1656 /* restart_event signalled */
1657 int children_to_kill = current_live_processes;
1658 restart_pending = 1;
1659 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, s,
1660 "master_main: Restart event signaled. Doing a graceful restart.");
1661 if (ResetEvent(restart_event) == 0) {
1662 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1663 "master_main: ResetEvent(restart_event) failed.");
1665 /* Signal each child process to die
1666 * We are making a big assumption here that the child process, once signaled,
1667 * will REALLY go away. Since this is a restart, we do not want to hold the
1668 * new child process up waiting for the old child to die. Remove the old
1669 * child out of the process_handles ap_table_t and hope for the best...
1671 for (i = 0; i < children_to_kill; i++) {
1672 if (SetEvent(process_kill_events[i]) == 0)
1673 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1674 "master_main: SetEvent for child process in slot #%d failed", i);
1675 cleanup_process(process_handles, process_kill_events, i, ¤t_live_processes);
1679 /* A child process must have exited because of a fatal error condition (seg fault, etc.).
1680 * Remove the dead process
1681 * from the process_handles and process_kill_events ap_table_t and create a new
1683 * TODO: Consider restarting the child immediately without looping through http_main
1684 * and without rereading the configuration. Will need this if we ever support multiple
1685 * children. One option, create a parent thread which waits on child death and restarts it.
1686 * Consider, however, that if the user makes httpd.conf invalid, we want to die before
1687 * our child tries it... otherwise we have a nasty loop.
1689 restart_pending = 1;
1690 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1691 "master_main: Child process failed. Restarting the child process.");
1692 ap_assert(cld < current_live_processes);
1693 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1694 /* APD2("main_process: child in slot %d died", rv); */
1695 /* restart_child(process_hancles, process_kill_events, cld, ¤t_live_processes); */
1697 /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead
1699 drain_acceptex_complport(AcceptExCompPort, FALSE);
1703 if (shutdown_pending)
1705 int tmstart = time(NULL);
1707 if (strcasecmp(signal_arg,"runservice")
1708 && (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)) {
1709 mpm_service_nt_stopping();
1711 /* Signal each child processes to die */
1712 for (i = 0; i < current_live_processes; i++) {
1713 printf("SetEvent handle = %d\n", process_kill_events[i]);
1714 if (SetEvent(process_kill_events[i]) == 0)
1715 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1716 "master_main: SetEvent for child process in slot #%d failed", i);
1719 while (current_live_processes && ((tmstart+60) > time(NULL))) {
1720 rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1721 if (rv == WAIT_TIMEOUT)
1723 ap_assert(rv != WAIT_FAILED);
1724 cld = rv - WAIT_OBJECT_0;
1725 ap_assert(rv < current_live_processes);
1726 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1728 for (i = 0; i < current_live_processes; i++) {
1729 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1730 "forcing termination of child #%d (handle %d)", i, process_handles[i]);
1731 TerminateProcess((HANDLE) process_handles[i], 1);
1733 return 0; /* Tell the caller we do not want to restart */
1736 return 1; /* Tell the caller we want a restart */
1740 #define SERVICE_UNNAMED -1
1742 /* service_nt_main_fn needs to append the StartService() args
1743 * outside of our call stack and thread as the service starts...
1745 ap_array_header_t *mpm_new_argv;
1747 /* Remember service_to_start failures to log and fail in pre_config.
1748 * Remember inst_argc and inst_argv for installing or starting the
1749 * service after we preflight the config.
1752 static ap_status_t service_to_start_success;
1753 static int inst_argc;
1754 static char **inst_argv;
1756 void winnt_rewrite_args(process_rec *process)
1758 /* Handle the following SCM aspects in this phase:
1760 * -k runservice [transition for WinNT, nothing for Win9x]
1761 * -k (!)install [error out if name is not installed]
1763 * We can't leave this phase until we know our identity
1764 * and modify the command arguments appropriately.
1766 ap_status_t service_named = SERVICE_UNNAMED;
1768 char *def_server_root;
1769 char fnbuf[MAX_PATH];
1776 one_process = !!getenv("ONE_PROCESS");
1778 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1779 GetVersionEx(&osver);
1781 /* AP_PARENT_PID is only valid in the child */
1782 pid = getenv("AP_PARENT_PID");
1785 /* This is the child */
1786 parent_pid = (DWORD) atol(pid);
1787 my_pid = GetCurrentProcessId();
1789 /* The parent is responsible for providing the
1790 * COMPLETE ARGUMENTS REQUIRED to the child.
1792 * No further argument parsing is needed, but
1793 * for good measure we will provide a simple
1794 * signal string for later testing.
1796 signal_arg = "runchild";
1800 /* This is the parent, we have a long way to go :-) */
1801 parent_pid = my_pid = GetCurrentProcessId();
1803 /* Rewrite process->argv[];
1805 * strip out -k signal into signal_arg
1806 * strip out -n servicename into service_name & display_name
1807 * add default -d serverroot from the path of this executable
1809 * The end result will look like:
1811 * The invocation command ($0)
1812 * The -d serverroot default from the running executable
1813 * The requested service's (-n) registry ConfigArgs
1814 * The command line arguments from this process
1815 * The WinNT SCM's StartService() args
1818 if (!GetModuleFileName(NULL, fnbuf, sizeof(fnbuf))) {
1819 /* WARNING: There is an implict assumption here that the
1820 * executable resides in the ServerRoot!
1822 rv = GetLastError();
1823 ap_log_error(APLOG_MARK,APLOG_ERR, rv, NULL,
1824 "Failed to get the running module's file name");
1827 def_server_root = (char *) ap_filename_of_pathname(fnbuf);
1828 if (def_server_root > fnbuf) {
1829 *(def_server_root - 1) = '\0';
1830 def_server_root = ap_os_canonical_filename(process->pool, fnbuf);
1833 /* Use process->pool so that the rewritten argv
1834 * lasts for the lifetime of the server process,
1835 * because pconf will be destroyed after the
1836 * initial pre-flight of the config parser.
1839 mpm_new_argv = ap_make_array(process->pool, process->argc + 2, sizeof(char *));
1840 new_arg = (char**) ap_push_array(mpm_new_argv);
1841 *new_arg = (char *) process->argv[0];
1843 new_arg = (char**) ap_push_array(mpm_new_argv);
1845 new_arg = (char**) ap_push_array(mpm_new_argv);
1846 *new_arg = def_server_root;
1848 fixed_args = mpm_new_argv->nelts;
1850 optbuf[0] = '-'; optbuf[2] = '\0';
1851 while (ap_getopt(process->argc, (char**) process->argv,
1852 "n:k:iu" AP_SERVER_BASEARGS,
1853 &opt, process->pool) == APR_SUCCESS) {
1856 service_named = mpm_service_set_name(process->pool, ap_optarg);
1859 signal_arg = ap_optarg;
1862 /* TODO: warn of depreciated syntax, "use -k install instead" */
1863 signal_arg = "install";
1866 /* TODO: warn of depreciated syntax, "use -k uninstall instead" */
1867 signal_arg = "uninstall";
1870 optbuf[1] = (char) opt;
1871 new_arg = (char**) ap_push_array(mpm_new_argv);
1872 *new_arg = ap_pstrdup(process->pool, optbuf);
1874 new_arg = (char**) ap_push_array(mpm_new_argv);
1875 *new_arg = ap_optarg;
1880 /* Set optreset and optind to allow ap_getopt to work correctly
1881 * when called from http_main.c
1886 /* Track the number of args actually entered by the user */
1887 inst_argc = mpm_new_argv->nelts - fixed_args;
1889 /* Provide a default 'run' -k arg to simplify signal_arg tests */
1893 if (!strcasecmp(signal_arg, "runservice"))
1895 /* Start the NT Service _NOW_ because the WinNT SCM is
1896 * expecting us to rapidly assume control of our own
1897 * process, the SCM will tell us our service name, and
1898 * may have extra StartService() command arguments to
1901 * Any other process has a console, so we don't to begin
1902 * a Win9x service until the configuration is parsed and
1903 * any command line errors are reported.
1905 * We hold the return value so that we can die in pre_config
1906 * after logging begins, and the failure can land in the log.
1908 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) {
1909 service_to_start_success = mpm_service_to_start();
1910 if (service_to_start_success == APR_SUCCESS)
1911 service_named = APR_SUCCESS;
1915 if (service_named == SERVICE_UNNAMED) {
1916 service_named = mpm_service_set_name(process->pool,
1917 DEFAULT_SERVICE_NAME);
1920 if (strcasecmp(signal_arg, "install")) /* not -k install */
1922 if (service_named == APR_SUCCESS)
1924 rv = mpm_merge_service_args(process->pool, mpm_new_argv,
1926 if (rv != APR_SUCCESS) {
1927 ap_log_error(APLOG_MARK,APLOG_ERR, rv, NULL,
1928 "%s: ConfigArgs are missing from the registry.",
1934 ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
1935 "%s: No installed service by that name.", display_name);
1939 else /* -k install */
1941 if (service_named == APR_SUCCESS)
1943 ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
1944 "%s: Service is already installed.", display_name);
1949 /* Track the args actually entered by the user.
1950 * These will be used for the -k install parameters, as well as
1951 * for the -k start service override arguments.
1953 inst_argv = (char**) mpm_new_argv->elts + mpm_new_argv->nelts - inst_argc;
1955 process->argc = mpm_new_argv->nelts;
1956 process->argv = (char**) mpm_new_argv->elts;
1960 static void winnt_pre_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp)
1962 /* Handle the following SCM aspects in this phase:
1964 * -k runservice [WinNT errors logged from rewrite_args]
1967 * in both cases we -don't- care if httpd.conf is error-free
1971 if (!strcasecmp(signal_arg, "runservice")
1972 && (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
1973 && (service_to_start_success != APR_SUCCESS)) {
1974 ap_log_error(APLOG_MARK,APLOG_ERR, service_to_start_success, NULL,
1975 "%s: Unable to start the service manager.",
1980 if (!strcasecmp(signal_arg, "uninstall")) {
1981 rv = mpm_service_uninstall();
1985 ap_listen_pre_config();
1986 ap_daemons_to_start = DEFAULT_NUM_DAEMON;
1987 ap_threads_per_child = DEFAULT_START_THREAD;
1988 ap_pid_fname = DEFAULT_PIDLOG;
1989 max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1991 ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1994 static void winnt_post_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp, server_rec* server)
1996 static int restart_num = 0;
1999 server_conf = server;
2001 /* Handle the following SCM aspects in this phase:
2007 * -k runservice [Win95, only once - after we parsed the config]
2009 * because all of these signals are useful _only_ if there
2010 * is a valid conf\httpd.conf environment to start.
2012 * We reached this phase by avoiding errors that would cause
2013 * these options to fail unexpectedly in another process.
2016 if (!strcasecmp(signal_arg, "install")) {
2017 rv = mpm_service_install(ptemp, inst_argc, inst_argv);
2021 if (!strcasecmp(signal_arg, "start")) {
2022 rv = mpm_service_start(ptemp, inst_argc, inst_argv);
2026 if (!strcasecmp(signal_arg, "restart")) {
2027 mpm_signal_service(ptemp, ap_pid_fname, 1);
2031 // TODO: This Stinks - but we needed the ap_pid_fname entry from
2032 // the config!?! Find a clean way to get the egg back into
2033 // into the chicken and shove this signal into pre_config
2035 // src/os/win32/main_win32.c had some (possibly buggy) code to
2036 // search for just the PidFile entry, but this sounds like a
2037 // universally useful function that we ought to wrap into the
2038 // main server, not just the Win32 MPM.
2040 if (!strcasecmp(signal_arg, "stop")) {
2041 mpm_signal_service(ptemp, ap_pid_fname, 0);
2045 if (parent_pid == my_pid)
2047 if (restart_num++ == 1)
2049 /* This code should be run once in the parent and not run
2052 PSECURITY_ATTRIBUTES sa = GetNullACL(); /* returns NULL if invalid (Win95?) */
2053 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
2054 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
2055 /* Create the AcceptEx IoCompletionPort once in the parent.
2056 * The completion port persists across restarts.
2058 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
2061 0); /* CONCURRENT ACTIVE THREADS */
2062 if (AcceptExCompPort == NULL) {
2063 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
2064 "Parent: Unable to create the AcceptExCompletionPort -- process will exit");
2069 ap_log_pid(pconf, ap_pid_fname);
2071 /* Create shutdown event, apPID_shutdown, where PID is the parent
2072 * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
2074 shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
2075 if (!shutdown_event) {
2076 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
2077 "Parent: Cannot create shutdown event %s", signal_shutdown_name);
2078 CleanNullACL((void *)sa);
2082 /* Create restart event, apPID_restart, where PID is the parent
2083 * Apache process ID. Restart is signaled by 'apache -k restart'.
2085 restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
2086 if (!restart_event) {
2087 CloseHandle(shutdown_event);
2088 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
2089 "Parent: Cannot create restart event %s", signal_restart_name);
2090 CleanNullACL((void *)sa);
2093 CleanNullACL((void *)sa);
2095 /* Now that we are flying at 15000 feet...
2096 * wipe out the Win95 service console,
2097 * signal the SCM the WinNT service started, or
2098 * if not a service, setup console handlers instead.
2100 if (!strcasecmp(signal_arg, "runservice"))
2102 if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT)
2104 rv = mpm_service_to_start();
2105 if (rv != APR_SUCCESS) {
2106 ap_log_error(APLOG_MARK,APLOG_ERR, rv, server_conf,
2107 "%s: Unable to start the service manager.",
2113 else /* ! -k runservice */
2115 mpm_start_console_handler();
2118 /* Create the start mutex, apPID, where PID is the parent Apache process ID.
2119 * Ths start mutex is used during a restart to prevent more than one
2120 * child process from entering the accept loop at once.
2122 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS, signal_name_prefix,
2123 server_conf->process->pool);
2126 else /* parent_pid != my_pid */
2128 mpm_start_child_console_handler();
2132 API_EXPORT(int) ap_mpm_run(ap_pool_t *_pconf, ap_pool_t *plog, server_rec *s )
2134 static int restart = 0; /* Default is "not a restart" */
2139 if ((parent_pid != my_pid) || one_process) {
2140 /* Running as Child process or in one_process (debug) mode */
2141 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
2142 "Child %d: Child process is running", my_pid);
2144 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
2145 "Child %d: Child process is exiting", my_pid);
2148 } /* Child or single process */
2149 else { /* Parent process */
2150 restart = master_main(server_conf, shutdown_event, restart_event);
2153 /* Shutting down. Clean up... */
2154 const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
2156 if (pidfile != NULL && unlink(pidfile) == 0) {
2157 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS,
2158 server_conf, "removed PID file %s (pid=%ld)",
2159 pidfile, GetCurrentProcessId());
2161 ap_destroy_lock(start_mutex);
2163 CloseHandle(restart_event);
2164 CloseHandle(shutdown_event);
2168 } /* Parent process */
2170 return 0; /* Restart */
2173 static void winnt_hooks(void)
2176 ap_hook_pre_config(winnt_pre_config, NULL, NULL, AP_HOOK_MIDDLE);
2177 ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
2181 * Command processors
2183 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg)
2185 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2190 if (cmd->server->is_virtual) {
2191 return "PidFile directive not allowed in <VirtualHost>";
2197 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg)
2199 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2204 ap_threads_per_child = atoi(arg);
2205 if (ap_threads_per_child > HARD_THREAD_LIMIT) {
2206 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2207 "WARNING: ThreadsPerChild of %d exceeds compile time"
2208 " limit of %d threads,", ap_threads_per_child,
2210 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2211 " lowering ThreadsPerChild to %d. To increase, please"
2212 " see the HARD_THREAD_LIMIT define in src/include/httpd.h.",
2215 else if (ap_threads_per_child < 1) {
2216 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2217 "WARNING: Require ThreadsPerChild > 0, setting to 1");
2218 ap_threads_per_child = 1;
2224 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg)
2226 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2231 max_requests_per_child = atoi(arg);
2236 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg)
2240 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2245 fname = ap_server_root_relative(cmd->pool, arg);
2246 if ((ap_stat(&finfo, fname, cmd->pool) != APR_SUCCESS) ||
2247 (finfo.filetype != APR_DIR)) {
2248 return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
2249 " does not exist or is not a directory", NULL);
2251 ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
2255 /* Stub functions until this MPM supports the connection status API */
2257 API_EXPORT(void) ap_update_connection_status(long conn_id, const char *key, \
2263 API_EXPORT(void) ap_reset_connection_status(long conn_id)
2268 API_EXPORT(ap_array_header_t *) ap_get_status_table(ap_pool_t *p)
2274 static const command_rec winnt_cmds[] = {
2276 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
2277 "A file for logging the server process ID"},
2278 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
2279 "Number of threads each child creates" },
2280 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
2281 "Maximum number of requests a particular child serves before dying." },
2282 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
2283 "The location of the directory Apache changes to before dumping core" },
2287 MODULE_VAR_EXPORT module mpm_winnt_module = {
2289 winnt_rewrite_args, /* hook to run before apache parses args */
2290 NULL, /* create per-directory config structure */
2291 NULL, /* merge per-directory config structures */
2292 NULL, /* create per-server config structure */
2293 NULL, /* merge per-server config structures */
2294 winnt_cmds, /* command ap_table_t */
2295 NULL, /* handlers */
2296 winnt_hooks /* register_hooks */