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"
74 #include "mpm_common.h"
77 * Definitions of WINNT MPM specific config globals
80 static char *ap_pid_fname = NULL;
81 static int ap_threads_per_child = 0;
82 static int workers_may_exit = 0;
83 static int max_requests_per_child = 0;
84 static HANDLE shutdown_event; /* used to signal shutdown to parent */
85 static HANDLE restart_event; /* used to signal a restart to parent */
87 #define MAX_SIGNAL_NAME 30 /* Long enough for apPID_shutdown, where PID is an int */
88 char signal_name_prefix[MAX_SIGNAL_NAME];
89 char signal_restart_name[MAX_SIGNAL_NAME];
90 char signal_shutdown_name[MAX_SIGNAL_NAME];
92 static struct fd_set listenfds;
93 static int num_listenfds = 0;
94 static SOCKET listenmaxfd = INVALID_SOCKET;
96 static ap_pool_t *pconf; /* Pool for config stuff */
98 static char ap_coredump_dir[MAX_STRING_LEN];
100 static server_rec *server_conf;
101 static HANDLE AcceptExCompPort = NULL;
103 static int one_process = 0;
104 static char *signal_arg;
106 OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
108 int ap_max_requests_per_child=0;
109 int ap_daemons_to_start=0;
111 static event *exit_event;
112 HANDLE maintenance_event;
113 ap_lock_t *start_mutex;
117 /* This is the helper code to resolve late bound entry points
118 * missing from one or more releases of the Win32 API...
119 * but it sure would be nice if we didn't duplicate this code
123 static const char* const lateDllName[DLL_defined] = {
124 "kernel32", "advapi32", "mswsock", "ws2_32" };
125 static HMODULE lateDllHandle[DLL_defined] = {
126 NULL, NULL, NULL, NULL };
128 FARPROC ap_load_dll_func(ap_dlltoken_e fnLib, char* fnName, int ordinal)
130 if (!lateDllHandle[fnLib]) {
131 lateDllHandle[fnLib] = LoadLibrary(lateDllName[fnLib]);
132 if (!lateDllHandle[fnLib])
136 return GetProcAddress(lateDllHandle[fnLib], (char *) ordinal);
138 return GetProcAddress(lateDllHandle[fnLib], fnName);
141 static ap_status_t socket_cleanup(void *sock)
143 ap_socket_t *thesocket = sock;
145 if (ap_get_os_sock(&sd, thesocket) == APR_SUCCESS) {
151 /* A bunch or routines from os/win32/multithread.c that need to be merged into APR
152 * or thrown out entirely...
155 typedef void semaphore;
159 create_semaphore(int initial)
161 return(CreateSemaphore(NULL, initial, 1000000, NULL));
164 static void acquire_semaphore(semaphore *semaphore_id)
168 rv = WaitForSingleObject(semaphore_id, INFINITE);
173 static int release_semaphore(semaphore *semaphore_id)
175 return(ReleaseSemaphore(semaphore_id, 1, NULL));
178 static void destroy_semaphore(semaphore *semaphore_id)
180 CloseHandle(semaphore_id);
184 /* To share the semaphores with other processes, we need a NULL ACL
185 * Code from MS KB Q106387
187 static PSECURITY_ATTRIBUTES GetNullACL()
189 PSECURITY_DESCRIPTOR pSD;
190 PSECURITY_ATTRIBUTES sa;
192 sa = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES));
193 pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,
194 SECURITY_DESCRIPTOR_MIN_LENGTH);
195 if (pSD == NULL || sa == NULL) {
198 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
204 if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
210 sa->nLength = sizeof(sa);
211 sa->lpSecurityDescriptor = pSD;
212 sa->bInheritHandle = TRUE;
216 static void CleanNullACL( void *sa ) {
218 LocalFree( ((PSECURITY_ATTRIBUTES)sa)->lpSecurityDescriptor);
224 * The Win32 call WaitForMultipleObjects will only allow you to wait for
225 * a maximum of MAXIMUM_WAIT_OBJECTS (current 64). Since the threading
226 * model in the multithreaded version of apache wants to use this call,
227 * we are restricted to a maximum of 64 threads. This is a simplistic
228 * routine that will increase this size.
230 static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles,
234 DWORD dwRet = WAIT_TIMEOUT;
238 tStopTime = time(NULL) + dwSeconds;
246 for (dwIndex = 0; dwIndex * MAXIMUM_WAIT_OBJECTS < nCount; dwIndex++) {
247 dwRet = WaitForMultipleObjects(
248 min(MAXIMUM_WAIT_OBJECTS, nCount - (dwIndex * MAXIMUM_WAIT_OBJECTS)),
249 lpHandles + (dwIndex * MAXIMUM_WAIT_OBJECTS),
252 if (dwRet != WAIT_TIMEOUT) {
256 } while((time(NULL) < tStopTime) && (dwRet == WAIT_TIMEOUT));
262 * Signalling Apache on NT.
264 * Under Unix, Apache can be told to shutdown or restart by sending various
265 * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
266 * we use "events" instead. The parent apache process goes into a loop
267 * where it waits forever for a set of events. Two of those events are
273 * (where PID is the PID of the apache parent process). When one of these
274 * is signalled, the Apache parent performs the appropriate action. The events
275 * can become signalled through internal Apache methods (e.g. if the child
276 * finds a fatal error and needs to kill its parent), via the service
277 * control manager (the control thread will signal the shutdown event when
278 * requested to stop the Apache service), from the -k Apache command line,
279 * or from any external program which finds the Apache PID from the
282 * The signal_parent() function, below, is used to signal one of these events.
283 * It can be called by any child or parent process, since it does not
284 * rely on global variables.
286 * On entry, type gives the event to signal. 0 means shutdown, 1 means
289 void signal_parent(int type)
294 /* after updating the shutdown_pending or restart flags, we need
295 * to wake up the parent process so it can see the changes. The
296 * parent will normally be waiting for either a child process
297 * to die, or for a signal on the "spache-signal" event. So set the
298 * "apache-signal" event here.
305 case 0: signal_name = signal_shutdown_name; break;
306 case 1: signal_name = signal_restart_name; break;
309 e = OpenEvent(EVENT_ALL_ACCESS, FALSE, signal_name);
311 /* Um, problem, can't signal the parent, which means we can't
312 * signal ourselves to die. Ignore for now...
314 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
315 "OpenEvent on %s event", signal_name);
318 if (SetEvent(e) == 0) {
319 /* Same problem as above */
320 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
321 "SetEvent on %s event", signal_name);
328 static int volatile is_graceful = 0;
330 API_EXPORT(int) ap_graceful_stop_signalled(void)
335 API_EXPORT(void) ap_start_shutdown(void)
340 API_EXPORT(void) ap_start_restart(int gracefully)
342 is_graceful = gracefully;
347 * Initialise the signal names, in the global variables signal_name_prefix,
348 * signal_restart_name and signal_shutdown_name.
351 void setup_signal_names(char *prefix)
353 ap_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);
354 ap_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name),
355 "%s_shutdown", signal_name_prefix);
356 ap_snprintf(signal_restart_name, sizeof(signal_restart_name),
357 "%s_restart", signal_name_prefix);
361 * Routines that deal with sockets, some are WIN32 specific...
364 static void sock_disable_nagle(int s)
366 /* The Nagle algorithm says that we should delay sending partial
367 * packets in hopes of getting more data. We don't want to do
368 * this; we are not telnet. There are bad interactions between
369 * persistent connections and Nagle's algorithm that have very severe
370 * performance penalties. (Failing to disable Nagle is not much of a
371 * problem with simple HTTP.)
373 * In spite of these problems, failure here is not a shooting offense.
377 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
379 ap_log_error(APLOG_MARK, APLOG_WARNING, APR_SUCCESS, server_conf,
380 "setsockopt: (TCP_NODELAY)");
385 * Routines to deal with managing the list of listening sockets.
387 static ap_listen_rec *head_listener;
389 static ap_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
394 for (lr = head_listener; lr ; lr = lr->next) {
395 ap_get_os_sock(&nsd, lr->sd);
396 if (FD_ISSET(nsd, main_fds)) {
397 head_listener = lr->next;
398 if (head_listener == NULL)
399 head_listener = ap_listeners;
407 static int setup_listeners(server_rec *s)
410 int num_listeners = 0;
413 /* Setup the listeners */
416 if (ap_listen_open(s->process, s->port)) {
419 for (lr = ap_listeners; lr; lr = lr->next) {
421 if (lr->sd != NULL) {
422 ap_get_os_sock(&nsd, lr->sd);
423 FD_SET(nsd, &listenfds);
424 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
431 head_listener = ap_listeners;
433 return num_listeners;
436 static int setup_inherited_listeners(server_rec *s)
438 WSAPROTOCOL_INFO WSAProtocolInfo;
442 int num_listeners = 0;
445 /* Setup the listeners */
448 /* Set up a default listener if necessary */
450 if (ap_listeners == NULL) {
452 lr = ap_palloc(s->process->pool, sizeof(ap_listen_rec));
456 lr->next = ap_listeners;
460 /* Open the pipe to the parent process to receive the inherited socket
461 * data. The sockets have been set to listening in the parent process.
463 pipe = GetStdHandle(STD_INPUT_HANDLE);
464 for (lr = ap_listeners; lr; lr = lr->next) {
465 if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
466 &BytesRead, (LPOVERLAPPED) NULL)) {
467 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
468 "setup_inherited_listeners: Unable to read socket data from parent");
469 signal_parent(0); /* tell parent to die */
472 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
473 "Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.", my_pid);
474 nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
475 &WSAProtocolInfo, 0, 0);
476 if (nsd == INVALID_SOCKET) {
477 ap_log_error(APLOG_MARK, APLOG_CRIT, WSAGetLastError(), server_conf,
478 "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
479 signal_parent(0); /* tell parent to die */
483 FD_SET(nsd, &listenfds);
484 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
488 ap_put_os_sock(&lr->sd, &nsd, pconf);
491 /* Now, read the AcceptExCompPort from the parent */
492 ReadFile(pipe, &AcceptExCompPort, sizeof(AcceptExCompPort), &BytesRead, (LPOVERLAPPED) NULL);
495 for (lr = ap_listeners; lr; lr = lr->next) {
499 head_listener = ap_listeners;
500 return num_listeners;
503 static void bind_listeners_to_completion_port()
505 /* Associate the open listeners with the completion port.
506 * Bypass the operation for Windows 95/98
510 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
511 for (lr = ap_listeners; lr; lr = lr->next) {
513 ap_get_os_sock(&nsd,lr->sd);
514 CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
519 /**********************************************************************
520 * Multithreaded implementation
522 * This code is fairly specific to Win32.
524 * The model used to handle requests is a set of threads. One "main"
525 * thread listens for new requests. When something becomes
526 * available, it does a select and places the newly available socket
527 * onto a list of "jobs" (add_job()). Then any one of a fixed number
528 * of "worker" threads takes the top job off the job list with
529 * remove_job() and handles that connection to completion. After
530 * the connection has finished the thread is free to take another
531 * job from the job list.
533 * In the code, the "main" thread is running within the child_main()
534 * function. The first thing this function does is create the
535 * worker threads, which operate in the child_sub_main() function. The
536 * main thread then goes into a loop within child_main() where they
537 * do a select() on the listening sockets. The select times out once
538 * per second so that the thread can check for an "exit" signal
539 * from the parent process (see below). If this signal is set, the
540 * thread can exit, but only after it has accepted all incoming
541 * connections already in the listen queue (since Win32 appears
542 * to through away listened but unaccepted connections when a
545 * Because the main and worker threads exist within a single process
546 * they are vulnerable to crashes or memory leaks (crashes can also
547 * be caused within modules, of course). There also needs to be a
548 * mechanism to perform restarts and shutdowns. This is done by
549 * creating the main & worker threads within a subprocess. A
550 * main process (the "parent process") creates one (or more)
551 * processes to do the work, then the parent sits around waiting
552 * for the working process to die, in which case it starts a new
553 * one. The parent process also handles restarts (by creating
554 * a new working process then signalling the previous working process
555 * exit ) and shutdowns (by signalling the working process to exit).
556 * The parent process operates within the master_main() function. This
557 * process also handles requests from the service manager (NT only).
559 * Signalling between the parent and working process uses a Win32
560 * event. Each child has a unique name for the event, which is
561 * passed to it with the -Z argument when the child is spawned. The
562 * parent sets (signals) this event to tell the child to die.
563 * At present all children do a graceful die - they finish all
564 * current jobs _and_ empty the listen queue before they exit.
565 * A non-graceful die would need a second event. The -Z argument in
566 * the child is also used to create the shutdown and restart events,
567 * since the prefix (apPID) contains the parent process PID.
569 * The code below starts with functions at the lowest level -
570 * worker threads, and works up to the top level - the main()
571 * function of the parent process.
573 * The scoreboard (in process memory) contains details of the worker
574 * threads (within the active working process). There is no shared
575 * "scoreboard" between processes, since only one is ever active
576 * at once (or at most, two, when one has been told to shutdown but
577 * is processes outstanding requests, and a new one has been started).
578 * This is controlled by a "start_mutex" which ensures only one working
579 * process is active at once.
580 **********************************************************************/
584 * Definition of jobs, shared by main and worker threads.
587 typedef struct joblist_s {
588 struct joblist_s *next;
593 * Globals common to main and worker threads. This structure is not
594 * used by the parent process.
597 typedef struct globals_s {
598 semaphore *jobsemaphore;
605 globals allowed_globals =
606 {NULL, NULL, NULL, NULL, 0};
607 #define MAX_SELECT_ERRORS 100
608 #define PADDED_ADDR_SIZE sizeof(SOCKADDR_IN)+16
610 /* Windows 9x specific code...
611 * Accept processing for on Windows 95/98 uses a producer/consumer queue
612 * model. A single thread accepts connections and queues the accepted socket
613 * to the accept queue for consumption by a pool of worker threads.
615 * win9x_get_connection()
616 * Calls remove_job() to pull a job from the accept queue. All the worker
617 * threads block on remove_job.
618 * accept_and_queue_connections()
619 * The accept threads runs this function, which accepts connections off
620 * the network and calls add_job() to queue jobs to the accept_queue.
621 * add_job()/remove_job()
622 * Add or remove an accepted socket from the list of sockets
623 * connected to clients. allowed_globals.jobmutex protects
624 * against multiple concurrent access to the linked list of jobs.
626 static void add_job(int sock)
630 new_job = (joblist *) malloc(sizeof(joblist));
631 if (new_job == NULL) {
632 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
633 "Ouch! Out of memory in add_job()!");
636 new_job->next = NULL;
637 new_job->sock = sock;
639 ap_lock(allowed_globals.jobmutex);
641 if (allowed_globals.jobtail != NULL)
642 allowed_globals.jobtail->next = new_job;
643 allowed_globals.jobtail = new_job;
644 if (!allowed_globals.jobhead)
645 allowed_globals.jobhead = new_job;
646 allowed_globals.jobcount++;
647 release_semaphore(allowed_globals.jobsemaphore);
649 ap_unlock(allowed_globals.jobmutex);
652 static int remove_job(void)
657 acquire_semaphore(allowed_globals.jobsemaphore);
658 ap_lock(allowed_globals.jobmutex);
660 if (workers_may_exit && !allowed_globals.jobhead) {
661 ap_unlock(allowed_globals.jobmutex);
664 job = allowed_globals.jobhead;
666 allowed_globals.jobhead = job->next;
667 if (allowed_globals.jobhead == NULL)
668 allowed_globals.jobtail = NULL;
669 ap_unlock(allowed_globals.jobmutex);
676 static void accept_and_queue_connections(void * dummy)
678 int requests_this_child = 0;
683 int nsd = INVALID_SOCKET;
684 struct sockaddr_in sa_client;
685 int count_select_errors = 0;
689 while (!workers_may_exit) {
690 if (ap_max_requests_per_child && (requests_this_child > ap_max_requests_per_child)) {
694 tv.tv_sec = wait_time;
696 memcpy(&main_fds, &listenfds, sizeof(fd_set));
698 rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
700 if (rc == 0 || (rc == SOCKET_ERROR && h_errno == WSAEINTR)) {
701 count_select_errors = 0; /* reset count of errors */
704 else if (rc == SOCKET_ERROR) {
705 /* A "real" error occurred, log it and increment the count of
706 * select errors. This count is used to ensure we don't go into
707 * a busy loop of continuous errors.
709 ap_log_error(APLOG_MARK, APLOG_INFO, h_errno, server_conf,
710 "select failed with errno %d", h_errno);
711 count_select_errors++;
712 if (count_select_errors > MAX_SELECT_ERRORS) {
713 workers_may_exit = 1;
714 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
715 "Too many errors in select loop. Child process exiting.");
721 lr = find_ready_listener(&main_fds);
723 /* fetch the native socket descriptor */
724 ap_get_os_sock(&nsd, lr->sd);
729 clen = sizeof(sa_client);
730 csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
731 if (csd == INVALID_SOCKET) {
734 } while (csd < 0 && h_errno == WSAEINTR);
737 if (h_errno != WSAECONNABORTED) {
738 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
739 "accept: (client socket)");
744 requests_this_child++;
747 SetEvent(exit_event);
749 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
753 if (context == NULL) {
754 /* allocate the completion context and the transaction pool */
755 context = ap_pcalloc(pconf, sizeof(COMP_CONTEXT));
757 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
758 "win9x_get_connection: ap_pcalloc() failed. Process will exit.");
761 ap_create_pool(&context->ptrans, pconf);
766 ap_clear_pool(context->ptrans);
767 context->accept_socket = remove_job();
768 if (context->accept_socket == -1) {
771 len = sizeof(struct sockaddr);
772 context->sa_server = ap_palloc(context->ptrans, len);
773 if (getsockname(context->accept_socket,
774 context->sa_server, &len)== SOCKET_ERROR) {
775 ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(), server_conf,
776 "getsockname failed");
779 len = sizeof(struct sockaddr);
780 context->sa_client = ap_palloc(context->ptrans, len);
781 if ((getpeername(context->accept_socket,
782 context->sa_client, &len)) == SOCKET_ERROR) {
783 ap_log_error(APLOG_MARK, APLOG_WARNING, h_errno, server_conf,
784 "getpeername failed with error %d\n", WSAGetLastError());
785 memset(&context->sa_client, '\0', sizeof(context->sa_client));
788 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
790 /* do we NEED_DUPPED_CSD ?? */
797 * Windows 2000/NT specific code...
798 * create_acceptex_context()
799 * reset_acceptex_context()
800 * drain_acceptex_complport()
801 * winnt_get_connection()
803 * TODO: Insert a discussion of 'completion contexts' and what these function do here...
805 static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp)
808 PCOMP_CONTEXT context;
816 rc = GetQueuedCompletionStatus(hComplPort, &BytesRead, &CompKey,
819 lastError = GetLastError();
820 if (lastError == ERROR_OPERATION_ABORTED) {
821 ap_log_error(APLOG_MARK,APLOG_INFO,lastError, server_conf,
822 "Child %d: - Draining a packet off the completion port.", my_pid);
827 ap_log_error(APLOG_MARK,APLOG_INFO,APR_SUCCESS, server_conf,
828 "Child %d: - Nuking an active connection. context = %x", my_pid, context);
829 context = (PCOMP_CONTEXT) pol;
830 if (context && bCleanUp) {
831 /* It is only valid to clean-up in the process that initiated the I/O */
832 closesocket(context->accept_socket);
833 CloseHandle(context->Overlapped.hEvent);
837 static int create_acceptex_context(ap_pool_t *_pconf, ap_listen_rec *lr)
839 PCOMP_CONTEXT context;
844 /* allocate the completion context */
845 context = ap_pcalloc(_pconf, sizeof(COMP_CONTEXT));
847 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
848 "create_acceptex_context: ap_pcalloc() failed. Process will exit.");
852 /* initialize the completion context */
854 context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
855 if (context->Overlapped.hEvent == NULL) {
856 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
857 "create_acceptex_context: CreateEvent() failed. Process will exit.");
861 /* create and initialize the accept socket */
862 ap_get_os_sock(&nsd, context->lr->sd);
863 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
864 if (context->accept_socket == INVALID_SOCKET) {
865 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
866 "create_acceptex_context: socket() failed. Process will exit.");
870 /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
871 if (setsockopt(context->accept_socket, SOL_SOCKET,
872 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
874 ap_log_error(APLOG_MARK, APLOG_ERR, WSAGetLastError(), server_conf,
875 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
876 /* Not a failure condition. Keep running. */
879 ap_create_pool(&context->ptrans, _pconf);
880 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
881 context->recv_buf = context->conn_io->inbase;
882 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
885 /* AcceptEx on the completion context. The completion context will be signaled
886 * when a connection is accepted. */
887 if (!AcceptEx(nsd, context->accept_socket,
889 0, //context->recv_buf_size,
890 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
892 (LPOVERLAPPED) context)) {
893 lasterror = WSAGetLastError();
894 if (lasterror != ERROR_IO_PENDING) {
895 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
896 "create_acceptex_context: AcceptEx failed. Process will exit.");
905 static ap_inline ap_status_t reset_acceptex_context(PCOMP_CONTEXT context)
911 context->lr->count++;
913 /* recreate and initialize the accept socket if it is not being reused */
914 ap_get_os_sock(&nsd, context->lr->sd);
915 if (context->accept_socket == INVALID_SOCKET) {
916 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
917 if (context->accept_socket == INVALID_SOCKET) {
918 lasterror = WSAGetLastError();
919 ap_log_error(APLOG_MARK,APLOG_ERR, lasterror, server_conf,
920 "reset_acceptex_context: socket() failed. Process will exit.");
924 /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
925 if (setsockopt(context->accept_socket, SOL_SOCKET,
926 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
928 ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(),
930 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
931 /* Not a failure condition. Keep running. */
935 /* reset the completion context */
936 ap_clear_pool(context->ptrans);
937 context->sock = NULL;
938 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
939 context->recv_buf = context->conn_io->inbase;
940 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
942 /* AcceptEx on the completion context. The completion context will be signaled
943 * when a connection is accepted. */
944 if (!AcceptEx(nsd, context->accept_socket, context->recv_buf, 0,
945 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE, &BytesRead,
946 (LPOVERLAPPED) context)) {
947 lasterror = WSAGetLastError();
948 if (lasterror != ERROR_IO_PENDING) {
949 ap_log_error(APLOG_MARK, APLOG_INFO, lasterror, server_conf,
950 "reset_acceptex_context: AcceptEx failed for "
951 "listening socket: %d and accept socket: %d",
952 nsd, context->accept_socket);
959 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
961 int requests_this_child = 0;
967 if (workers_may_exit) {
968 /* Child shutdown has been signaled */
970 CloseHandle(context->Overlapped.hEvent);
973 if (!workers_may_exit && (context != NULL)) {
974 /* Prepare the completion context for reuse */
975 if (reset_acceptex_context(context) != APR_SUCCESS) {
976 /* Retry once, this time requesting a new socket */
977 if (context->accept_socket != INVALID_SOCKET) {
978 closesocket(context->accept_socket);
979 context->accept_socket = INVALID_SOCKET;
981 if (reset_acceptex_context(context) != APR_SUCCESS) {
982 /* Failed again, so give up, but leave the thread up
983 * Should we signal a shutdown now?
985 if (context->accept_socket != INVALID_SOCKET)
986 closesocket(context->accept_socket);
987 CloseHandle(context->Overlapped.hEvent);
993 rc = GetQueuedCompletionStatus(AcceptExCompPort,
1000 /* During a restart, the new child process can catch
1001 * ERROR_OPERATION_ABORTED completion packets
1002 * posted by the old child process. Just continue...
1004 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1005 "Child %d: - GetQueuedCompletionStatus() failed", my_pid);
1009 /* Check the Completion Key.
1010 * == my_pid indicate this process wants to exit
1011 * == 0 implies valid i/o completion
1012 * != 0 implies a posted completion packet by an old
1013 * process. Just ignore it.
1015 if (CompKey == my_pid) {
1022 context = (PCOMP_CONTEXT) pol;
1026 /* Check to see if we need to create more completion contexts,
1027 * but only if we are not in the process of shutting down
1029 if (!workers_may_exit) {
1030 ap_lock(allowed_globals.jobmutex);
1031 context->lr->count--;
1032 if (context->lr->count < 2) {
1033 SetEvent(maintenance_event);
1035 ap_unlock(allowed_globals.jobmutex);
1038 /* Received a connection */
1039 context->conn_io->incnt = BytesRead;
1040 GetAcceptExSockaddrs(context->recv_buf,
1041 0, //context->recv_buf_size,
1044 &context->sa_server,
1045 &context->sa_server_len,
1046 &context->sa_client,
1047 &context->sa_client_len);
1053 * worker_main() - this is the main loop for the worker threads
1056 * Each thread runs within this function. They wait within remove_job()
1057 * for a job to become available, then handle all the requests on that
1058 * connection until it is closed, then return to remove_job().
1060 * The worker thread will exit when it removes a job which contains
1061 * socket number -1. This provides a graceful thread exit, since
1062 * it will never exit during a connection.
1064 * This code in this function is basically equivalent to the child_main()
1065 * from the multi-process (Unix) environment, except that we
1067 * - do not call child_init_modules (child init API phase)
1068 * - block in remove_job, and when unblocked we have an already
1069 * accepted socket, instead of blocking on a mutex or select().
1072 static void worker_main(int child_num)
1074 PCOMP_CONTEXT context = NULL;
1079 ap_int32_t disconnected;
1081 /* Grab a connection off the network */
1082 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1083 context = win9x_get_connection(context);
1086 context = winnt_get_connection(context);
1091 sock_disable_nagle(context->accept_socket);
1092 ap_put_os_sock(&context->sock, &context->accept_socket, context->ptrans);
1094 iol = ap_iol_attach_socket(context->ptrans, context->sock);
1096 ap_log_error(APLOG_MARK, APLOG_ERR, APR_ENOMEM, server_conf,
1097 "worker_main: attach_socket() failed. Continuing...");
1098 closesocket(context->accept_socket);
1101 ap_bpush_iol(context->conn_io, iol);
1102 c = ap_new_connection(context->ptrans, server_conf, context->conn_io,
1103 (struct sockaddr_in *) context->sa_client,
1104 (struct sockaddr_in *) context->sa_server,
1107 ap_process_connection(c);
1110 ap_getsocketopt(context->sock, APR_SO_DISCONNECTED, &disconnected);
1112 /* Kill the clean-up registered by the iol. We want to leave
1113 * the accept socket open because we are about to try to
1116 ap_bpop_iol(&iol, context->conn_io);
1119 context->accept_socket = INVALID_SOCKET;
1120 /* Disable lingering close for the moment to fix a seg fault.
1121 * All the sendfile code needs some serious work to return
1122 * proper error values, handle updating bytes_sent, etc.
1123 * I'll enable lingering close after I've fixed the sendfile
1125 * ap_lingering_close(c);
1127 ap_bclose(c->client);
1131 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1132 "Child %d: Thread exiting.", my_pid);
1135 SetEvent(exit_event);
1137 /* TODO: Add code to clean-up completion contexts here */
1140 static void cleanup_thread(thread **handles, int *thread_cnt, int thread_to_clean)
1144 CloseHandle(handles[thread_to_clean]);
1145 for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1146 handles[i] = handles[i + 1];
1150 static void create_listeners()
1152 #define NUM_LISTENERS 5
1154 for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1155 while (lr->count < NUM_LISTENERS) {
1156 if (create_acceptex_context(pconf, lr) == -1) {
1157 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1158 "Unable to create an AcceptEx completion context -- process will exit");
1159 signal_parent(0); /* tell parent to die */
1165 * child_main() runs the main control thread for the child process.
1167 * The control thread:
1168 * - sets up the worker thread pool
1169 * - starts the accept thread (Win 9x)
1170 * - creates AcceptEx contexts (Win NT)
1171 * - waits for exit_event, maintenance_event or maintenance timeout
1172 * and does the right thing depending on which event is received.
1174 static void child_main()
1177 HANDLE child_events[2];
1178 char* exit_event_name;
1179 int nthreads = ap_threads_per_child;
1181 thread **child_handles;
1189 /* This is the child process or we are running in single process
1192 exit_event_name = ap_psprintf(pconf, "apC%d", my_pid);
1193 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1196 /* Single process mode */
1197 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1198 exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1200 setup_listeners(server_conf);
1201 bind_listeners_to_completion_port();
1204 /* Child process mode */
1205 ap_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1206 exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1207 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1208 "Child %d: exit_event_name = %s", my_pid, exit_event_name);
1210 setup_inherited_listeners(server_conf);
1213 /* Initialize the child_events */
1214 maintenance_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1215 child_events[0] = exit_event;
1216 child_events[1] = maintenance_event;
1218 ap_assert(start_mutex);
1219 ap_assert(exit_event);
1220 ap_assert(maintenance_event);
1222 ap_create_pool(&pchild, pconf);
1223 allowed_globals.jobsemaphore = create_semaphore(0);
1224 ap_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
1227 * Wait until we have permission to start accepting connections.
1228 * start_mutex is used to ensure that only one child ever
1229 * goes into the listen/accept loop at once.
1231 status = ap_lock(start_mutex);
1232 if (status != APR_SUCCESS) {
1233 ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
1234 "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1235 signal_parent(0); /* tell parent to die */
1238 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1239 "Child %d: Acquired the start mutex.", my_pid);
1241 /* Create the worker thread pool */
1242 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1243 "Child %d: Starting %d worker threads.", my_pid, nthreads);
1244 child_handles = (thread *) alloca(nthreads * sizeof(int));
1245 for (i = 0; i < nthreads; i++) {
1246 child_handles[i] = (thread *) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1250 /* Begin accepting connections */
1251 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1252 /* Win95/98: Start the accept thread */
1253 _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) accept_and_queue_connections,
1254 (void *) i, 0, &tid);
1256 /* Windows NT/2000: Create AcceptEx completion contexts */
1260 /* Wait for one of three events:
1262 * The exit_event is signaled by the parent process to notify
1263 * the child that it is time to exit.
1265 * maintenance_event:
1266 * This event is signaled by the worker thread pool to direct
1267 * this thread to create more completion contexts.
1270 * To do periodic maintenance on the server (check for thread exits,
1271 * number of completion contexts, etc.)
1273 while (!workers_may_exit) {
1274 rv = WaitForMultipleObjects(2, (HANDLE *) child_events, FALSE, INFINITE);
1275 cld = rv - WAIT_OBJECT_0;
1276 if (rv == WAIT_FAILED) {
1277 /* Something serious is wrong */
1278 workers_may_exit = 1;
1279 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1280 "Child %d: WAIT_FAILED -- shutting down server");
1282 else if (rv == WAIT_TIMEOUT) {
1283 /* Hey, this cannot happen */
1284 workers_may_exit = 1;
1285 ap_log_error(APLOG_MARK, APLOG_CRIT, APR_SUCCESS, server_conf,
1286 "Child %d: WAIT_TIMEOUT -- shutting down server", my_pid);
1288 else if (cld == 0) {
1289 /* Exit event was signaled */
1290 workers_may_exit = 1;
1291 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1292 "Child %d: Exit event signaled. Child process is ending.", my_pid);
1295 /* Child maintenance event signaled */
1296 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1299 ResetEvent(maintenance_event);
1300 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1301 "Child %d: Child maintenance event signaled.", my_pid);
1305 /* Setting is_graceful will close keep-alive connections */
1308 /* Shutdown the worker threads */
1309 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1310 for (i = 0; i < nthreads; i++) {
1314 else { /* Windows NT/2000 */
1318 * First thing to do is to drain all the completion contexts off the
1319 * AcceptEx iocp. Give a busy server the chance to drain
1320 * the port by servicing connections (workers_may_exit prevents new
1321 * AcceptEx completion contexts from being queued to the port).
1325 /* Cancel any remaining pending async i/o.
1326 * This will cause io completion packets to be queued to the
1327 * port for any remaining active contexts
1329 for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1330 ap_get_os_sock(&nsd,lr->sd);
1331 CancelIo((HANDLE) nsd);
1334 /* Drain the canceled contexts off the port */
1335 drain_acceptex_complport(AcceptExCompPort, FALSE);
1337 /* Hopefully by now, all the completion contexts should be drained
1338 * off the port. There could still be some cancel io completion packets
1339 * flying around in the kernel... We will cover this possibility later..
1341 * Consider using HasOverlappedIoCompleted()...
1343 * Next task is to unblock all the threads blocked on
1344 * GetQueuedCompletionStatus()
1347 for (i=0; i < nthreads*2; i++) {
1348 PostQueuedCompletionStatus(AcceptExCompPort, 0, my_pid, NULL);
1351 /* Give the worker threads time to realize they've been posted */
1355 /* Release the start_mutex to let the new process (in the restart
1356 * scenario) a chance to begin servicing requests
1358 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1359 "Child %d: Releasing the start mutex", my_pid);
1360 ap_unlock(start_mutex);
1362 /* Give busy worker threads a chance to service their connections.
1363 * Kill them off if they take too long
1365 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1366 "Child %d: Waiting for %d threads to die.", my_pid, nthreads);
1367 end_time = time(NULL) + 180;
1369 rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1370 if (rv != WAIT_TIMEOUT) {
1371 rv = rv - WAIT_OBJECT_0;
1372 ap_assert((rv >= 0) && (rv < nthreads));
1373 cleanup_thread(child_handles, &nthreads, rv);
1378 for (i = 0; i < nthreads; i++) {
1379 TerminateThread(child_handles[i], 1);
1380 CloseHandle(child_handles[i]);
1382 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1383 "Child %d: All worker threads have ended.", my_pid);
1385 CloseHandle(AcceptExCompPort);
1386 destroy_semaphore(allowed_globals.jobsemaphore);
1387 ap_destroy_lock(allowed_globals.jobmutex);
1389 ap_destroy_pool(pchild);
1390 CloseHandle(exit_event);
1394 * Spawn a child Apache process. The child process has the command line arguments from
1395 * argc and argv[], plus a -Z argument giving the name of an event. The child should
1396 * open and poll or wait on this event. When it is signalled, the child should die.
1397 * prefix is a prefix string for the event name.
1399 * The child_num argument on entry contains a serial number for this child (used to create
1400 * a unique event name). On exit, this number will have been incremented by one, ready
1401 * for the next call.
1403 * On exit, the value pointed to be *ev will contain the event created
1404 * to signal the new child process.
1406 * The return value is the handle to the child process if successful, else -1. If -1 is
1407 * returned the error will already have been logged by ap_log_error().
1410 /**********************************************************************
1411 * master_main - this is the parent (main) process. We create a
1412 * child process to do the work, then sit around waiting for either
1413 * the child to exit, or a restart or exit signal. If the child dies,
1414 * we just respawn a new one. If we have a shutdown or graceful restart,
1415 * tell the child to die when it is ready. If it is a non-graceful
1416 * restart, force the child to die immediately.
1417 **********************************************************************/
1419 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1421 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1426 CloseHandle(handles[position]);
1427 CloseHandle(events[position]);
1429 handle = (int)handles[position];
1431 for (i = position; i < (*processes)-1; i++) {
1432 handles[i] = handles[i + 1];
1433 events[i] = events[i + 1];
1438 static int create_process(ap_pool_t *p, HANDLE *handles, HANDLE *events, int *processes)
1447 STARTUPINFO si; /* Filled in prior to call to CreateProcess */
1448 PROCESS_INFORMATION pi; /* filled in on call to CreateProcess */
1452 HANDLE hPipeRead = NULL;
1453 HANDLE hPipeWrite = NULL;
1454 SECURITY_ATTRIBUTES sa = {0};
1457 LPWSAPROTOCOL_INFO lpWSAProtocolInfo;
1458 HANDLE hDupedCompPort;
1460 sa.nLength = sizeof(sa);
1461 sa.bInheritHandle = TRUE;
1462 sa.lpSecurityDescriptor = NULL;
1464 /* Build the command line. Should look something like this:
1465 * C:/apache/bin/apache.exe -f ap_server_confname
1466 * First, get the path to the executable...
1468 rv = GetModuleFileName(NULL, buf, sizeof(buf));
1469 if (rv == sizeof(buf)) {
1470 ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1471 "Parent: Path to Apache process too long");
1473 } else if (rv == 0) {
1474 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1475 "Parent: GetModuleFileName() returned NULL for current process.");
1479 /* Build the command line */
1480 pCommand = ap_psprintf(p, "\"%s\"", buf);
1481 for (i = 1; i < server_conf->process->argc; i++) {
1482 pCommand = ap_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1485 /* Build the environment, since Win9x disrespects the active env */
1486 pEnvVar = ap_psprintf(p, "AP_PARENT_PID=%i", parent_pid);
1488 * Win32's CreateProcess call requires that the environment
1489 * be passed in an environment block, a null terminated block of
1490 * null terminated strings.
1494 while (_environ[i]) {
1495 iEnvBlockLen += strlen(_environ[i]) + 1;
1499 pEnvBlock = (char *)ap_pcalloc(p, iEnvBlockLen + strlen(pEnvVar) + 1);
1500 strcpy(pEnvBlock, pEnvVar);
1501 pEnvVar = strchr(pEnvBlock, '\0') + 1;
1504 while (_environ[i]) {
1505 strcpy(pEnvVar, _environ[i]);
1506 pEnvVar = strchr(pEnvVar, '\0') + 1;
1510 /* Create a pipe to send socket info to the child */
1511 if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1512 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1513 "Parent: Unable to create pipe to child process.\n");
1517 /* Give the read end of the pipe (hPipeRead) to the child as stdin. The
1518 * parent will write the socket data to the child on this pipe.
1520 memset(&si, 0, sizeof(si));
1521 memset(&pi, 0, sizeof(pi));
1523 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1524 si.wShowWindow = SW_HIDE;
1525 si.hStdInput = hPipeRead;
1527 if (!CreateProcess(NULL, pCommand, NULL, NULL,
1528 TRUE, /* Inherit handles */
1529 CREATE_SUSPENDED, /* Creation flags */
1530 pEnvBlock, /* Environment block */
1533 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1534 "Parent: Not able to create the child process.");
1536 * We must close the handles to the new process and its main thread
1537 * to prevent handle and memory leaks.
1539 CloseHandle(pi.hProcess);
1540 CloseHandle(pi.hThread);
1544 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1545 "Parent: Created child process %d", pi.dwProcessId);
1547 SetEnvironmentVariable("AP_PARENT_PID",NULL);
1549 /* Create the exit_event, apCchild_pid */
1550 sa.nLength = sizeof(sa);
1551 sa.bInheritHandle = TRUE;
1552 sa.lpSecurityDescriptor = NULL;
1553 kill_event = CreateEvent(&sa, TRUE, FALSE, ap_psprintf(pconf,"apC%d", pi.dwProcessId));
1555 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1556 "Parent: Could not create exit event for child process");
1557 CloseHandle(pi.hProcess);
1558 CloseHandle(pi.hThread);
1562 /* Assume the child process lives. Update the process and event tables */
1563 handles[*processes] = pi.hProcess;
1564 events[*processes] = kill_event;
1567 /* We never store the thread's handle, so close it now. */
1568 ResumeThread(pi.hThread);
1569 CloseHandle(pi.hThread);
1571 /* Run the chain of open sockets. For each socket, duplicate it
1572 * for the target process then send the WSAPROTOCOL_INFO
1573 * (returned by dup socket) to the child */
1574 for (lr = ap_listeners; lr; lr = lr->next) {
1576 lpWSAProtocolInfo = ap_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1577 ap_get_os_sock(&nsd,lr->sd);
1578 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1579 "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1580 if (WSADuplicateSocket(nsd, pi.dwProcessId,
1581 lpWSAProtocolInfo) == SOCKET_ERROR) {
1582 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, server_conf,
1583 "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1587 if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1589 (LPOVERLAPPED) NULL)) {
1590 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1591 "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1594 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1595 "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1597 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1598 /* Now, send the AcceptEx completion port to the child */
1599 if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort,
1600 pi.hProcess, &hDupedCompPort, 0,
1601 TRUE, DUPLICATE_SAME_ACCESS)) {
1602 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1603 "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1607 WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1610 CloseHandle(hPipeRead);
1611 CloseHandle(hPipeWrite);
1616 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1618 int remaining_children_to_start = ap_daemons_to_start;
1622 int restart_pending = 0;
1623 int shutdown_pending = 0;
1624 int current_live_processes = 0; /* number of child process we know about */
1626 HANDLE process_handles[MAX_PROCESSES];
1627 HANDLE process_kill_events[MAX_PROCESSES];
1630 bind_listeners_to_completion_port();
1632 /* Create child process
1633 * Should only be one in this version of Apache for WIN32
1635 while (remaining_children_to_start--) {
1636 if (create_process(pconf, process_handles, process_kill_events,
1637 ¤t_live_processes) < 0) {
1638 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1639 "master_main: create child process failed. Exiting.");
1640 shutdown_pending = 1;
1645 restart_pending = shutdown_pending = 0;
1647 if (!strcasecmp(signal_arg, "runservice"))
1648 mpm_service_started();
1650 /* Wait for shutdown or restart events or for child death */
1651 process_handles[current_live_processes] = shutdown_event;
1652 process_handles[current_live_processes+1] = restart_event;
1654 rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles,
1656 cld = rv - WAIT_OBJECT_0;
1657 if (rv == WAIT_FAILED) {
1658 /* Something serious is wrong */
1659 ap_log_error(APLOG_MARK,APLOG_CRIT, GetLastError(), server_conf,
1660 "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1661 shutdown_pending = 1;
1663 else if (rv == WAIT_TIMEOUT) {
1664 /* Hey, this cannot happen */
1665 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1666 "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1667 shutdown_pending = 1;
1669 else if (cld == current_live_processes) {
1670 /* shutdown_event signalled */
1671 shutdown_pending = 1;
1672 printf("shutdown event signaled\n");
1673 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1674 "master_main: Shutdown event signaled -- doing server shutdown.");
1675 if (ResetEvent(shutdown_event) == 0) {
1676 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1677 "ResetEvent(shutdown_event)");
1681 else if (cld == current_live_processes+1) {
1682 /* restart_event signalled */
1683 int children_to_kill = current_live_processes;
1684 restart_pending = 1;
1685 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, s,
1686 "master_main: Restart event signaled. Doing a graceful restart.");
1687 if (ResetEvent(restart_event) == 0) {
1688 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1689 "master_main: ResetEvent(restart_event) failed.");
1691 /* Signal each child process to die
1692 * We are making a big assumption here that the child process, once signaled,
1693 * will REALLY go away. Since this is a restart, we do not want to hold the
1694 * new child process up waiting for the old child to die. Remove the old
1695 * child out of the process_handles ap_table_t and hope for the best...
1697 for (i = 0; i < children_to_kill; i++) {
1698 if (SetEvent(process_kill_events[i]) == 0)
1699 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1700 "master_main: SetEvent for child process in slot #%d failed", i);
1701 cleanup_process(process_handles, process_kill_events, i, ¤t_live_processes);
1705 /* A child process must have exited because of a fatal error condition (seg fault, etc.).
1706 * Remove the dead process
1707 * from the process_handles and process_kill_events ap_table_t and create a new
1709 * TODO: Consider restarting the child immediately without looping through http_main
1710 * and without rereading the configuration. Will need this if we ever support multiple
1711 * children. One option, create a parent thread which waits on child death and restarts it.
1712 * Consider, however, that if the user makes httpd.conf invalid, we want to die before
1713 * our child tries it... otherwise we have a nasty loop.
1715 restart_pending = 1;
1716 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1717 "master_main: Child process failed. Restarting the child process.");
1718 ap_assert(cld < current_live_processes);
1719 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1720 /* APD2("main_process: child in slot %d died", rv); */
1721 /* restart_child(process_hancles, process_kill_events, cld, ¤t_live_processes); */
1723 /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead
1725 drain_acceptex_complport(AcceptExCompPort, FALSE);
1729 if (shutdown_pending)
1731 int tmstart = time(NULL);
1733 if (strcasecmp(signal_arg, "runservice")) {
1734 mpm_service_stopping();
1736 /* Signal each child processes to die */
1737 for (i = 0; i < current_live_processes; i++) {
1738 printf("SetEvent handle = %d\n", process_kill_events[i]);
1739 if (SetEvent(process_kill_events[i]) == 0)
1740 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1741 "master_main: SetEvent for child process in slot #%d failed", i);
1744 while (current_live_processes && ((tmstart+60) > time(NULL))) {
1745 rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1746 if (rv == WAIT_TIMEOUT)
1748 ap_assert(rv != WAIT_FAILED);
1749 cld = rv - WAIT_OBJECT_0;
1750 ap_assert(rv < current_live_processes);
1751 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1753 for (i = 0; i < current_live_processes; i++) {
1754 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1755 "forcing termination of child #%d (handle %d)", i, process_handles[i]);
1756 TerminateProcess((HANDLE) process_handles[i], 1);
1758 return 0; /* Tell the caller we do not want to restart */
1761 return 1; /* Tell the caller we want a restart */
1765 #define SERVICE_UNNAMED -1
1767 /* service_nt_main_fn needs to append the StartService() args
1768 * outside of our call stack and thread as the service starts...
1770 ap_array_header_t *mpm_new_argv;
1772 /* Remember service_to_start failures to log and fail in pre_config.
1773 * Remember inst_argc and inst_argv for installing or starting the
1774 * service after we preflight the config.
1777 static ap_status_t service_to_start_success;
1778 static int inst_argc;
1779 static char **inst_argv;
1781 void winnt_rewrite_args(process_rec *process)
1783 /* Handle the following SCM aspects in this phase:
1785 * -k runservice [transition for WinNT, nothing for Win9x]
1786 * -k (!)install [error out if name is not installed]
1788 * We can't leave this phase until we know our identity
1789 * and modify the command arguments appropriately.
1791 ap_status_t service_named = SERVICE_UNNAMED;
1793 char *def_server_root;
1794 char fnbuf[MAX_PATH];
1801 one_process = !!getenv("ONE_PROCESS");
1803 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1804 GetVersionEx(&osver);
1806 /* AP_PARENT_PID is only valid in the child */
1807 pid = getenv("AP_PARENT_PID");
1810 /* This is the child */
1811 parent_pid = (DWORD) atol(pid);
1812 my_pid = GetCurrentProcessId();
1814 /* The parent is responsible for providing the
1815 * COMPLETE ARGUMENTS REQUIRED to the child.
1817 * No further argument parsing is needed, but
1818 * for good measure we will provide a simple
1819 * signal string for later testing.
1821 signal_arg = "runchild";
1825 /* This is the parent, we have a long way to go :-) */
1826 parent_pid = my_pid = GetCurrentProcessId();
1828 /* Rewrite process->argv[];
1830 * strip out -k signal into signal_arg
1831 * strip out -n servicename into service_name & display_name
1832 * add default -d serverroot from the path of this executable
1834 * The end result will look like:
1836 * The invocation command (%0)
1837 * The -d serverroot default from the running executable
1838 * The requested service's (-n) registry ConfigArgs
1839 * The WinNT SCM's StartService() args
1842 if (!GetModuleFileName(NULL, fnbuf, sizeof(fnbuf))) {
1843 /* WARNING: There is an implict assumption here that the
1844 * executable resides in the ServerRoot!
1846 rv = GetLastError();
1847 ap_log_error(APLOG_MARK,APLOG_ERR, rv, NULL,
1848 "Failed to get the running module's file name");
1851 def_server_root = (char *) ap_filename_of_pathname(fnbuf);
1852 if (def_server_root > fnbuf) {
1853 *(def_server_root - 1) = '\0';
1854 def_server_root = ap_os_canonical_filename(process->pool, fnbuf);
1857 /* Use process->pool so that the rewritten argv
1858 * lasts for the lifetime of the server process,
1859 * because pconf will be destroyed after the
1860 * initial pre-flight of the config parser.
1863 mpm_new_argv = ap_make_array(process->pool, process->argc + 2, sizeof(char *));
1864 new_arg = (char**) ap_push_array(mpm_new_argv);
1865 *new_arg = (char *) process->argv[0];
1867 new_arg = (char**) ap_push_array(mpm_new_argv);
1869 new_arg = (char**) ap_push_array(mpm_new_argv);
1870 *new_arg = def_server_root;
1872 fixed_args = mpm_new_argv->nelts;
1874 optbuf[0] = '-'; optbuf[2] = '\0';
1875 while (ap_getopt(process->argc, (char**) process->argv,
1876 "n:k:iu" AP_SERVER_BASEARGS,
1877 &opt, process->pool) == APR_SUCCESS) {
1880 service_named = mpm_service_set_name(process->pool, ap_optarg);
1883 signal_arg = ap_optarg;
1886 /* TODO: warn of depreciated syntax, "use -k install instead" */
1887 signal_arg = "install";
1890 /* TODO: warn of depreciated syntax, "use -k uninstall instead" */
1891 signal_arg = "uninstall";
1894 optbuf[1] = (char) opt;
1895 new_arg = (char**) ap_push_array(mpm_new_argv);
1896 *new_arg = ap_pstrdup(process->pool, optbuf);
1898 new_arg = (char**) ap_push_array(mpm_new_argv);
1899 *new_arg = ap_optarg;
1904 /* Set optreset and optind to allow ap_getopt to work correctly
1905 * when called from http_main.c
1910 /* Track the number of args actually entered by the user */
1911 inst_argc = mpm_new_argv->nelts - fixed_args;
1913 /* Provide a default 'run' -k arg to simplify signal_arg tests */
1917 if (!strcasecmp(signal_arg, "runservice"))
1919 /* Start the NT Service _NOW_ because the WinNT SCM is
1920 * expecting us to rapidly assume control of our own
1921 * process, the SCM will tell us our service name, and
1922 * may have extra StartService() command arguments to
1925 * Any other process has a console, so we don't to begin
1926 * a Win9x service until the configuration is parsed and
1927 * any command line errors are reported.
1929 * We hold the return value so that we can die in pre_config
1930 * after logging begins, and the failure can land in the log.
1932 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) {
1933 service_to_start_success = mpm_service_to_start();
1934 if (service_to_start_success == APR_SUCCESS)
1935 service_named = APR_SUCCESS;
1939 if (service_named == SERVICE_UNNAMED) {
1940 service_named = mpm_service_set_name(process->pool,
1941 DEFAULT_SERVICE_NAME);
1944 if (!strcasecmp(signal_arg, "install")) /* -k install */
1946 if (service_named == APR_SUCCESS)
1948 ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
1949 "%s: Service is already installed.", display_name);
1955 if (service_named == APR_SUCCESS)
1957 rv = mpm_merge_service_args(process->pool, mpm_new_argv,
1959 if (rv != APR_SUCCESS) {
1960 ap_log_error(APLOG_MARK,APLOG_ERR, rv, NULL,
1961 "%s: ConfigArgs are missing from the registry.",
1967 ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
1968 "%s: No installed service by that name.", display_name);
1973 /* Track the args actually entered by the user.
1974 * These will be used for the -k install parameters, as well as
1975 * for the -k start service override arguments.
1977 inst_argv = (char**) mpm_new_argv->elts + mpm_new_argv->nelts - inst_argc;
1979 process->argc = mpm_new_argv->nelts;
1980 process->argv = (char**) mpm_new_argv->elts;
1984 static void winnt_pre_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp)
1986 /* Handle the following SCM aspects in this phase:
1988 * -k runservice [WinNT errors logged from rewrite_args]
1992 * in these cases we -don't- care if httpd.conf has config errors!
1996 if (!strcasecmp(signal_arg, "runservice")
1997 && (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
1998 && (service_to_start_success != APR_SUCCESS)) {
1999 ap_log_error(APLOG_MARK,APLOG_ERR, service_to_start_success, NULL,
2000 "%s: Unable to start the service manager.",
2005 if (!strcasecmp(signal_arg, "uninstall")) {
2006 rv = mpm_service_uninstall();
2010 if (!strcasecmp(signal_arg, "stop")) {
2011 mpm_signal_service(ptemp, 0);
2015 ap_listen_pre_config();
2016 ap_daemons_to_start = DEFAULT_NUM_DAEMON;
2017 ap_threads_per_child = DEFAULT_START_THREAD;
2018 ap_pid_fname = DEFAULT_PIDLOG;
2019 max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
2021 ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
2024 static void winnt_post_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp, server_rec* server)
2026 static int restart_num = 0;
2029 server_conf = server;
2031 /* Handle the following SCM aspects in this phase:
2036 * -k runservice [Win95, only once - after we parsed the config]
2038 * because all of these signals are useful _only_ if there
2039 * is a valid conf\httpd.conf environment to start.
2041 * We reached this phase by avoiding errors that would cause
2042 * these options to fail unexpectedly in another process.
2045 if (!strcasecmp(signal_arg, "install")) {
2046 rv = mpm_service_install(ptemp, inst_argc, inst_argv);
2050 if (!strcasecmp(signal_arg, "start")) {
2051 rv = mpm_service_start(ptemp, inst_argc, inst_argv);
2055 if (!strcasecmp(signal_arg, "restart")) {
2056 mpm_signal_service(ptemp, 1);
2060 if (parent_pid == my_pid)
2062 if (restart_num++ == 1)
2064 /* This code should be run once in the parent and not run
2067 PSECURITY_ATTRIBUTES sa = GetNullACL(); /* returns NULL if invalid (Win95?) */
2068 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
2069 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
2070 /* Create the AcceptEx IoCompletionPort once in the parent.
2071 * The completion port persists across restarts.
2073 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
2076 0); /* CONCURRENT ACTIVE THREADS */
2077 if (AcceptExCompPort == NULL) {
2078 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
2079 "Parent: Unable to create the AcceptExCompletionPort -- process will exit");
2084 ap_log_pid(pconf, ap_pid_fname);
2086 /* Create shutdown event, apPID_shutdown, where PID is the parent
2087 * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
2089 shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
2090 if (!shutdown_event) {
2091 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
2092 "Parent: Cannot create shutdown event %s", signal_shutdown_name);
2093 CleanNullACL((void *)sa);
2097 /* Create restart event, apPID_restart, where PID is the parent
2098 * Apache process ID. Restart is signaled by 'apache -k restart'.
2100 restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
2101 if (!restart_event) {
2102 CloseHandle(shutdown_event);
2103 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
2104 "Parent: Cannot create restart event %s", signal_restart_name);
2105 CleanNullACL((void *)sa);
2108 CleanNullACL((void *)sa);
2110 /* Now that we are flying at 15000 feet...
2111 * wipe out the Win95 service console,
2112 * signal the SCM the WinNT service started, or
2113 * if not a service, setup console handlers instead.
2115 if (!strcasecmp(signal_arg, "runservice"))
2117 if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT)
2119 rv = mpm_service_to_start();
2120 if (rv != APR_SUCCESS) {
2121 ap_log_error(APLOG_MARK,APLOG_ERR, rv, server_conf,
2122 "%s: Unable to start the service manager.",
2128 else /* ! -k runservice */
2130 mpm_start_console_handler();
2133 /* Create the start mutex, apPID, where PID is the parent Apache process ID.
2134 * Ths start mutex is used during a restart to prevent more than one
2135 * child process from entering the accept loop at once.
2137 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS, signal_name_prefix,
2138 server_conf->process->pool);
2141 else /* parent_pid != my_pid */
2143 mpm_start_child_console_handler();
2147 API_EXPORT(int) ap_mpm_run(ap_pool_t *_pconf, ap_pool_t *plog, server_rec *s )
2149 static int restart = 0; /* Default is "not a restart" */
2154 if ((parent_pid != my_pid) || one_process) {
2155 /* Running as Child process or in one_process (debug) mode */
2156 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
2157 "Child %d: Child process is running", my_pid);
2159 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
2160 "Child %d: Child process is exiting", my_pid);
2163 } /* Child or single process */
2164 else { /* Parent process */
2165 restart = master_main(server_conf, shutdown_event, restart_event);
2168 /* Shutting down. Clean up... */
2169 const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
2171 if (pidfile != NULL && unlink(pidfile) == 0) {
2172 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS,
2173 server_conf, "removed PID file %s (pid=%ld)",
2174 pidfile, GetCurrentProcessId());
2176 ap_destroy_lock(start_mutex);
2178 CloseHandle(restart_event);
2179 CloseHandle(shutdown_event);
2183 } /* Parent process */
2185 return 0; /* Restart */
2188 static void winnt_hooks(void)
2191 ap_hook_pre_config(winnt_pre_config, NULL, NULL, AP_HOOK_MIDDLE);
2192 ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
2196 * Command processors
2198 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg)
2200 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2205 if (cmd->server->is_virtual) {
2206 return "PidFile directive not allowed in <VirtualHost>";
2212 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg)
2214 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2219 ap_threads_per_child = atoi(arg);
2220 if (ap_threads_per_child > HARD_THREAD_LIMIT) {
2221 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2222 "WARNING: ThreadsPerChild of %d exceeds compile time"
2223 " limit of %d threads,", ap_threads_per_child,
2225 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2226 " lowering ThreadsPerChild to %d. To increase, please"
2227 " see the HARD_THREAD_LIMIT define in %s.",
2228 HARD_THREAD_LIMIT, AP_MPM_HARD_LIMITS_FILE);
2230 else if (ap_threads_per_child < 1) {
2231 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2232 "WARNING: Require ThreadsPerChild > 0, setting to 1");
2233 ap_threads_per_child = 1;
2239 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg)
2241 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2246 max_requests_per_child = atoi(arg);
2251 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg)
2255 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2260 fname = ap_server_root_relative(cmd->pool, arg);
2261 if ((ap_stat(&finfo, fname, cmd->pool) != APR_SUCCESS) ||
2262 (finfo.filetype != APR_DIR)) {
2263 return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
2264 " does not exist or is not a directory", NULL);
2266 ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
2270 /* Stub functions until this MPM supports the connection status API */
2272 API_EXPORT(void) ap_update_connection_status(long conn_id, const char *key, \
2278 API_EXPORT(void) ap_reset_connection_status(long conn_id)
2283 API_EXPORT(ap_array_header_t *) ap_get_status_table(ap_pool_t *p)
2289 static const command_rec winnt_cmds[] = {
2291 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
2292 "A file for logging the server process ID"},
2293 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
2294 "Number of threads each child creates" },
2295 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
2296 "Maximum number of requests a particular child serves before dying." },
2297 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
2298 "The location of the directory Apache changes to before dumping core" },
2302 MODULE_VAR_EXPORT module mpm_winnt_module = {
2304 winnt_rewrite_args, /* hook to run before apache parses args */
2305 NULL, /* create per-directory config structure */
2306 NULL, /* merge per-directory config structures */
2307 NULL, /* create per-server config structure */
2308 NULL, /* merge per-server config structures */
2309 winnt_cmds, /* command ap_table_t */
2310 NULL, /* handlers */
2311 winnt_hooks /* register_hooks */