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)
341 * Initialise the signal names, in the global variables signal_name_prefix,
342 * signal_restart_name and signal_shutdown_name.
345 void setup_signal_names(char *prefix)
347 ap_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);
348 ap_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name),
349 "%s_shutdown", signal_name_prefix);
350 ap_snprintf(signal_restart_name, sizeof(signal_restart_name),
351 "%s_restart", signal_name_prefix);
355 * Routines that deal with sockets, some are WIN32 specific...
358 static void sock_disable_nagle(int s)
360 /* The Nagle algorithm says that we should delay sending partial
361 * packets in hopes of getting more data. We don't want to do
362 * this; we are not telnet. There are bad interactions between
363 * persistent connections and Nagle's algorithm that have very severe
364 * performance penalties. (Failing to disable Nagle is not much of a
365 * problem with simple HTTP.)
367 * In spite of these problems, failure here is not a shooting offense.
371 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
373 ap_log_error(APLOG_MARK, APLOG_WARNING, APR_SUCCESS, server_conf,
374 "setsockopt: (TCP_NODELAY)");
379 * Routines to deal with managing the list of listening sockets.
381 static ap_listen_rec *head_listener;
383 static ap_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
388 for (lr = head_listener; lr ; lr = lr->next) {
389 ap_get_os_sock(&nsd, lr->sd);
390 if (FD_ISSET(nsd, main_fds)) {
391 head_listener = lr->next;
392 if (head_listener == NULL)
393 head_listener = ap_listeners;
401 static int setup_listeners(server_rec *s)
404 int num_listeners = 0;
407 /* Setup the listeners */
410 if (ap_listen_open(s->process, s->port)) {
413 for (lr = ap_listeners; lr; lr = lr->next) {
415 if (lr->sd != NULL) {
416 ap_get_os_sock(&nsd, lr->sd);
417 FD_SET(nsd, &listenfds);
418 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
425 head_listener = ap_listeners;
427 return num_listeners;
430 static int setup_inherited_listeners(server_rec *s)
432 WSAPROTOCOL_INFO WSAProtocolInfo;
436 int num_listeners = 0;
439 /* Setup the listeners */
442 /* Set up a default listener if necessary */
444 if (ap_listeners == NULL) {
446 lr = ap_palloc(s->process->pool, sizeof(ap_listen_rec));
450 lr->next = ap_listeners;
454 /* Open the pipe to the parent process to receive the inherited socket
455 * data. The sockets have been set to listening in the parent process.
457 pipe = GetStdHandle(STD_INPUT_HANDLE);
458 for (lr = ap_listeners; lr; lr = lr->next) {
459 if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
460 &BytesRead, (LPOVERLAPPED) NULL)) {
461 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
462 "setup_inherited_listeners: Unable to read socket data from parent");
463 signal_parent(0); /* tell parent to die */
466 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
467 "Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.", my_pid);
468 nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
469 &WSAProtocolInfo, 0, 0);
470 if (nsd == INVALID_SOCKET) {
471 ap_log_error(APLOG_MARK, APLOG_CRIT, WSAGetLastError(), server_conf,
472 "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
473 signal_parent(0); /* tell parent to die */
477 FD_SET(nsd, &listenfds);
478 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
482 ap_put_os_sock(&lr->sd, &nsd, pconf);
485 /* Now, read the AcceptExCompPort from the parent */
486 ReadFile(pipe, &AcceptExCompPort, sizeof(AcceptExCompPort), &BytesRead, (LPOVERLAPPED) NULL);
489 for (lr = ap_listeners; lr; lr = lr->next) {
493 head_listener = ap_listeners;
494 return num_listeners;
497 static void bind_listeners_to_completion_port()
499 /* Associate the open listeners with the completion port.
500 * Bypass the operation for Windows 95/98
504 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
505 for (lr = ap_listeners; lr; lr = lr->next) {
507 ap_get_os_sock(&nsd,lr->sd);
508 CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
513 /**********************************************************************
514 * Multithreaded implementation
516 * This code is fairly specific to Win32.
518 * The model used to handle requests is a set of threads. One "main"
519 * thread listens for new requests. When something becomes
520 * available, it does a select and places the newly available socket
521 * onto a list of "jobs" (add_job()). Then any one of a fixed number
522 * of "worker" threads takes the top job off the job list with
523 * remove_job() and handles that connection to completion. After
524 * the connection has finished the thread is free to take another
525 * job from the job list.
527 * In the code, the "main" thread is running within the child_main()
528 * function. The first thing this function does is create the
529 * worker threads, which operate in the child_sub_main() function. The
530 * main thread then goes into a loop within child_main() where they
531 * do a select() on the listening sockets. The select times out once
532 * per second so that the thread can check for an "exit" signal
533 * from the parent process (see below). If this signal is set, the
534 * thread can exit, but only after it has accepted all incoming
535 * connections already in the listen queue (since Win32 appears
536 * to through away listened but unaccepted connections when a
539 * Because the main and worker threads exist within a single process
540 * they are vulnerable to crashes or memory leaks (crashes can also
541 * be caused within modules, of course). There also needs to be a
542 * mechanism to perform restarts and shutdowns. This is done by
543 * creating the main & worker threads within a subprocess. A
544 * main process (the "parent process") creates one (or more)
545 * processes to do the work, then the parent sits around waiting
546 * for the working process to die, in which case it starts a new
547 * one. The parent process also handles restarts (by creating
548 * a new working process then signalling the previous working process
549 * exit ) and shutdowns (by signalling the working process to exit).
550 * The parent process operates within the master_main() function. This
551 * process also handles requests from the service manager (NT only).
553 * Signalling between the parent and working process uses a Win32
554 * event. Each child has a unique name for the event, which is
555 * passed to it with the -Z argument when the child is spawned. The
556 * parent sets (signals) this event to tell the child to die.
557 * At present all children do a graceful die - they finish all
558 * current jobs _and_ empty the listen queue before they exit.
559 * A non-graceful die would need a second event. The -Z argument in
560 * the child is also used to create the shutdown and restart events,
561 * since the prefix (apPID) contains the parent process PID.
563 * The code below starts with functions at the lowest level -
564 * worker threads, and works up to the top level - the main()
565 * function of the parent process.
567 * The scoreboard (in process memory) contains details of the worker
568 * threads (within the active working process). There is no shared
569 * "scoreboard" between processes, since only one is ever active
570 * at once (or at most, two, when one has been told to shutdown but
571 * is processes outstanding requests, and a new one has been started).
572 * This is controlled by a "start_mutex" which ensures only one working
573 * process is active at once.
574 **********************************************************************/
578 * Definition of jobs, shared by main and worker threads.
581 typedef struct joblist_s {
582 struct joblist_s *next;
587 * Globals common to main and worker threads. This structure is not
588 * used by the parent process.
591 typedef struct globals_s {
592 semaphore *jobsemaphore;
599 globals allowed_globals =
600 {NULL, NULL, NULL, NULL, 0};
601 #define MAX_SELECT_ERRORS 100
602 #define PADDED_ADDR_SIZE sizeof(SOCKADDR_IN)+16
604 /* Windows 9x specific code...
605 * Accept processing for on Windows 95/98 uses a producer/consumer queue
606 * model. A single thread accepts connections and queues the accepted socket
607 * to the accept queue for consumption by a pool of worker threads.
609 * win9x_get_connection()
610 * Calls remove_job() to pull a job from the accept queue. All the worker
611 * threads block on remove_job.
612 * accept_and_queue_connections()
613 * The accept threads runs this function, which accepts connections off
614 * the network and calls add_job() to queue jobs to the accept_queue.
615 * add_job()/remove_job()
616 * Add or remove an accepted socket from the list of sockets
617 * connected to clients. allowed_globals.jobmutex protects
618 * against multiple concurrent access to the linked list of jobs.
620 static void add_job(int sock)
624 new_job = (joblist *) malloc(sizeof(joblist));
625 if (new_job == NULL) {
626 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
627 "Ouch! Out of memory in add_job()!");
630 new_job->next = NULL;
631 new_job->sock = sock;
633 ap_lock(allowed_globals.jobmutex);
635 if (allowed_globals.jobtail != NULL)
636 allowed_globals.jobtail->next = new_job;
637 allowed_globals.jobtail = new_job;
638 if (!allowed_globals.jobhead)
639 allowed_globals.jobhead = new_job;
640 allowed_globals.jobcount++;
641 release_semaphore(allowed_globals.jobsemaphore);
643 ap_unlock(allowed_globals.jobmutex);
646 static int remove_job(void)
651 acquire_semaphore(allowed_globals.jobsemaphore);
652 ap_lock(allowed_globals.jobmutex);
654 if (workers_may_exit && !allowed_globals.jobhead) {
655 ap_unlock(allowed_globals.jobmutex);
658 job = allowed_globals.jobhead;
660 allowed_globals.jobhead = job->next;
661 if (allowed_globals.jobhead == NULL)
662 allowed_globals.jobtail = NULL;
663 ap_unlock(allowed_globals.jobmutex);
670 static void accept_and_queue_connections(void * dummy)
672 int requests_this_child = 0;
677 int nsd = INVALID_SOCKET;
678 struct sockaddr_in sa_client;
679 int count_select_errors = 0;
683 while (!workers_may_exit) {
684 if (ap_max_requests_per_child && (requests_this_child > ap_max_requests_per_child)) {
688 tv.tv_sec = wait_time;
690 memcpy(&main_fds, &listenfds, sizeof(fd_set));
692 rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
694 if (rc == 0 || (rc == SOCKET_ERROR && h_errno == WSAEINTR)) {
695 count_select_errors = 0; /* reset count of errors */
698 else if (rc == SOCKET_ERROR) {
699 /* A "real" error occurred, log it and increment the count of
700 * select errors. This count is used to ensure we don't go into
701 * a busy loop of continuous errors.
703 ap_log_error(APLOG_MARK, APLOG_INFO, h_errno, server_conf,
704 "select failed with errno %d", h_errno);
705 count_select_errors++;
706 if (count_select_errors > MAX_SELECT_ERRORS) {
707 workers_may_exit = 1;
708 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
709 "Too many errors in select loop. Child process exiting.");
715 lr = find_ready_listener(&main_fds);
717 /* fetch the native socket descriptor */
718 ap_get_os_sock(&nsd, lr->sd);
723 clen = sizeof(sa_client);
724 csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
725 if (csd == INVALID_SOCKET) {
728 } while (csd < 0 && h_errno == WSAEINTR);
731 if (h_errno != WSAECONNABORTED) {
732 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
733 "accept: (client socket)");
738 requests_this_child++;
741 SetEvent(exit_event);
743 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
747 if (context == NULL) {
748 /* allocate the completion context and the transaction pool */
749 context = ap_pcalloc(pconf, sizeof(COMP_CONTEXT));
751 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
752 "win9x_get_connection: ap_pcalloc() failed. Process will exit.");
755 ap_create_pool(&context->ptrans, pconf);
760 ap_clear_pool(context->ptrans);
761 context->accept_socket = remove_job();
762 if (context->accept_socket == -1) {
765 len = sizeof(struct sockaddr);
766 context->sa_server = ap_palloc(context->ptrans, len);
767 if (getsockname(context->accept_socket,
768 context->sa_server, &len)== SOCKET_ERROR) {
769 ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(), server_conf,
770 "getsockname failed");
773 len = sizeof(struct sockaddr);
774 context->sa_client = ap_palloc(context->ptrans, len);
775 if ((getpeername(context->accept_socket,
776 context->sa_client, &len)) == SOCKET_ERROR) {
777 ap_log_error(APLOG_MARK, APLOG_WARNING, h_errno, server_conf,
778 "getpeername failed with error %d\n", WSAGetLastError());
779 memset(&context->sa_client, '\0', sizeof(context->sa_client));
782 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
784 /* do we NEED_DUPPED_CSD ?? */
791 * Windows 2000/NT specific code...
792 * create_acceptex_context()
793 * reset_acceptex_context()
794 * drain_acceptex_complport()
795 * winnt_get_connection()
797 * TODO: Insert a discussion of 'completion contexts' and what these function do here...
799 static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp)
802 PCOMP_CONTEXT context;
810 rc = GetQueuedCompletionStatus(hComplPort, &BytesRead, &CompKey,
813 lastError = GetLastError();
814 if (lastError == ERROR_OPERATION_ABORTED) {
815 ap_log_error(APLOG_MARK,APLOG_INFO,lastError, server_conf,
816 "Child %d: - Draining a packet off the completion port.", my_pid);
821 ap_log_error(APLOG_MARK,APLOG_INFO,APR_SUCCESS, server_conf,
822 "Child %d: - Nuking an active connection. context = %x", my_pid, context);
823 context = (PCOMP_CONTEXT) pol;
824 if (context && bCleanUp) {
825 /* It is only valid to clean-up in the process that initiated the I/O */
826 closesocket(context->accept_socket);
827 CloseHandle(context->Overlapped.hEvent);
831 static int create_acceptex_context(ap_pool_t *_pconf, ap_listen_rec *lr)
833 PCOMP_CONTEXT context;
838 /* allocate the completion context */
839 context = ap_pcalloc(_pconf, sizeof(COMP_CONTEXT));
841 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
842 "create_acceptex_context: ap_pcalloc() failed. Process will exit.");
846 /* initialize the completion context */
848 context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
849 if (context->Overlapped.hEvent == NULL) {
850 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
851 "create_acceptex_context: CreateEvent() failed. Process will exit.");
855 /* create and initialize the accept socket */
856 ap_get_os_sock(&nsd, context->lr->sd);
857 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
858 if (context->accept_socket == INVALID_SOCKET) {
859 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
860 "create_acceptex_context: socket() failed. Process will exit.");
864 /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
865 if (setsockopt(context->accept_socket, SOL_SOCKET,
866 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
868 ap_log_error(APLOG_MARK, APLOG_ERR, WSAGetLastError(), server_conf,
869 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
870 /* Not a failure condition. Keep running. */
873 ap_create_pool(&context->ptrans, _pconf);
874 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
875 context->recv_buf = context->conn_io->inbase;
876 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
879 /* AcceptEx on the completion context. The completion context will be signaled
880 * when a connection is accepted. */
881 if (!AcceptEx(nsd, context->accept_socket,
883 0, //context->recv_buf_size,
884 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
886 (LPOVERLAPPED) context)) {
887 lasterror = WSAGetLastError();
888 if (lasterror != ERROR_IO_PENDING) {
889 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
890 "create_acceptex_context: AcceptEx failed. Process will exit.");
899 static ap_inline ap_status_t reset_acceptex_context(PCOMP_CONTEXT context)
905 context->lr->count++;
907 /* recreate and initialize the accept socket if it is not being reused */
908 ap_get_os_sock(&nsd, context->lr->sd);
909 if (context->accept_socket == INVALID_SOCKET) {
910 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
911 if (context->accept_socket == INVALID_SOCKET) {
912 lasterror = WSAGetLastError();
913 ap_log_error(APLOG_MARK,APLOG_ERR, lasterror, server_conf,
914 "reset_acceptex_context: socket() failed. Process will exit.");
918 /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
919 if (setsockopt(context->accept_socket, SOL_SOCKET,
920 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
922 ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(),
924 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
925 /* Not a failure condition. Keep running. */
929 /* reset the completion context */
930 ap_clear_pool(context->ptrans);
931 context->sock = NULL;
932 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
933 context->recv_buf = context->conn_io->inbase;
934 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
936 /* AcceptEx on the completion context. The completion context will be signaled
937 * when a connection is accepted. */
938 if (!AcceptEx(nsd, context->accept_socket, context->recv_buf, 0,
939 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE, &BytesRead,
940 (LPOVERLAPPED) context)) {
941 lasterror = WSAGetLastError();
942 if (lasterror != ERROR_IO_PENDING) {
943 ap_log_error(APLOG_MARK, APLOG_INFO, lasterror, server_conf,
944 "reset_acceptex_context: AcceptEx failed for "
945 "listening socket: %d and accept socket: %d",
946 nsd, context->accept_socket);
947 context->accept_socket = INVALID_SOCKET;
954 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
956 int requests_this_child = 0;
962 if (workers_may_exit) {
963 /* Child shutdown has been signaled */
965 CloseHandle(context->Overlapped.hEvent);
968 if (!workers_may_exit && (context != NULL)) {
969 /* Prepare the completion context for reuse */
970 if (reset_acceptex_context(context) != APR_SUCCESS) {
971 /* Retry once, this time requesting a new socket */
972 if (context->accept_socket != INVALID_SOCKET) {
973 closesocket(context->accept_socket);
974 context->accept_socket = INVALID_SOCKET;
976 if (reset_acceptex_context(context) != APR_SUCCESS) {
977 /* Failed again, so give up, but leave the thread up
978 * Should we signal a shutdown now?
980 if (context->accept_socket != INVALID_SOCKET)
981 closesocket(context->accept_socket);
982 CloseHandle(context->Overlapped.hEvent);
988 rc = GetQueuedCompletionStatus(AcceptExCompPort,
995 /* During a restart, the new child process can catch
996 * ERROR_OPERATION_ABORTED completion packets
997 * posted by the old child process. Just continue...
999 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1000 "Child %d: - GetQueuedCompletionStatus() failed", my_pid);
1004 /* Check the Completion Key.
1005 * == my_pid indicate this process wants to exit
1006 * == 0 implies valid i/o completion
1007 * != 0 implies a posted completion packet by an old
1008 * process. Just ignore it.
1010 if (CompKey == my_pid) {
1017 context = (PCOMP_CONTEXT) pol;
1021 /* Check to see if we need to create more completion contexts,
1022 * but only if we are not in the process of shutting down
1024 if (!workers_may_exit) {
1025 ap_lock(allowed_globals.jobmutex);
1026 context->lr->count--;
1027 if (context->lr->count < 2) {
1028 SetEvent(maintenance_event);
1030 ap_unlock(allowed_globals.jobmutex);
1033 /* Received a connection */
1034 context->conn_io->incnt = BytesRead;
1035 GetAcceptExSockaddrs(context->recv_buf,
1036 0, //context->recv_buf_size,
1039 &context->sa_server,
1040 &context->sa_server_len,
1041 &context->sa_client,
1042 &context->sa_client_len);
1048 * worker_main() - this is the main loop for the worker threads
1051 * Each thread runs within this function. They wait within remove_job()
1052 * for a job to become available, then handle all the requests on that
1053 * connection until it is closed, then return to remove_job().
1055 * The worker thread will exit when it removes a job which contains
1056 * socket number -1. This provides a graceful thread exit, since
1057 * it will never exit during a connection.
1059 * This code in this function is basically equivalent to the child_main()
1060 * from the multi-process (Unix) environment, except that we
1062 * - do not call child_init_modules (child init API phase)
1063 * - block in remove_job, and when unblocked we have an already
1064 * accepted socket, instead of blocking on a mutex or select().
1067 static void worker_main(int child_num)
1069 PCOMP_CONTEXT context = NULL;
1072 conn_rec *current_conn;
1075 /* Grab a connection off the network */
1076 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1077 context = win9x_get_connection(context);
1080 context = winnt_get_connection(context);
1085 sock_disable_nagle(context->accept_socket);
1086 ap_put_os_sock(&context->sock, &context->accept_socket, context->ptrans);
1088 iol = ap_iol_attach_socket(context->ptrans, context->sock);
1090 ap_log_error(APLOG_MARK, APLOG_ERR, APR_ENOMEM, server_conf,
1091 "worker_main: attach_socket() failed. Continuing...");
1092 closesocket(context->accept_socket);
1095 ap_bpush_iol(context->conn_io, iol);
1096 current_conn = ap_new_connection(context->ptrans, server_conf, context->conn_io,
1097 (struct sockaddr_in *) context->sa_client,
1098 (struct sockaddr_in *) context->sa_server,
1101 ap_process_connection(current_conn);
1102 ap_lingering_close(current_conn);
1103 context->accept_socket = INVALID_SOCKET;
1106 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1107 "Child %d: Thread exiting.", my_pid);
1110 SetEvent(exit_event);
1112 /* TODO: Add code to clean-up completion contexts here */
1115 static void cleanup_thread(thread **handles, int *thread_cnt, int thread_to_clean)
1119 CloseHandle(handles[thread_to_clean]);
1120 for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1121 handles[i] = handles[i + 1];
1125 static void create_listeners()
1127 #define NUM_LISTENERS 5
1129 for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1130 while (lr->count < NUM_LISTENERS) {
1131 if (create_acceptex_context(pconf, lr) == -1) {
1132 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1133 "Unable to create an AcceptEx completion context -- process will exit");
1134 signal_parent(0); /* tell parent to die */
1140 * child_main() runs the main control thread for the child process.
1142 * The control thread:
1143 * - sets up the worker thread pool
1144 * - starts the accept thread (Win 9x)
1145 * - creates AcceptEx contexts (Win NT)
1146 * - waits for exit_event, maintenance_event or maintenance timeout
1147 * and does the right thing depending on which event is received.
1149 static void child_main()
1152 HANDLE child_events[2];
1153 char* exit_event_name;
1154 int nthreads = ap_threads_per_child;
1156 thread **child_handles;
1164 /* This is the child process or we are running in single process
1167 exit_event_name = ap_psprintf(pconf, "apC%d", my_pid);
1168 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1171 /* Single process mode */
1172 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1173 exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1175 setup_listeners(server_conf);
1176 bind_listeners_to_completion_port();
1179 /* Child process mode */
1180 ap_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1181 exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1182 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1183 "Child %d: exit_event_name = %s", my_pid, exit_event_name);
1185 setup_inherited_listeners(server_conf);
1188 /* Initialize the child_events */
1189 maintenance_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1190 child_events[0] = exit_event;
1191 child_events[1] = maintenance_event;
1193 ap_assert(start_mutex);
1194 ap_assert(exit_event);
1195 ap_assert(maintenance_event);
1197 ap_create_pool(&pchild, pconf);
1198 allowed_globals.jobsemaphore = create_semaphore(0);
1199 ap_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
1202 * Wait until we have permission to start accepting connections.
1203 * start_mutex is used to ensure that only one child ever
1204 * goes into the listen/accept loop at once.
1206 status = ap_lock(start_mutex);
1207 if (status != APR_SUCCESS) {
1208 ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
1209 "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1210 signal_parent(0); /* tell parent to die */
1213 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1214 "Child %d: Acquired the start mutex.", my_pid);
1216 /* Create the worker thread pool */
1217 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1218 "Child %d: Starting %d worker threads.", my_pid, nthreads);
1219 child_handles = (thread *) alloca(nthreads * sizeof(int));
1220 for (i = 0; i < nthreads; i++) {
1221 child_handles[i] = (thread *) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1222 NULL, 0, &thread_id);
1225 /* Begin accepting connections */
1226 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1227 /* Win95/98: Start the accept thread */
1228 _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) accept_and_queue_connections,
1229 (void *) i, 0, &thread_id);
1231 /* Windows NT/2000: Create AcceptEx completion contexts */
1235 /* Wait for one of three events:
1237 * The exit_event is signaled by the parent process to notify
1238 * the child that it is time to exit.
1240 * maintenance_event:
1241 * This event is signaled by the worker thread pool to direct
1242 * this thread to create more completion contexts.
1245 * To do periodic maintenance on the server (check for thread exits,
1246 * number of completion contexts, etc.)
1248 while (!workers_may_exit) {
1249 rv = WaitForMultipleObjects(2, (HANDLE *) child_events, FALSE, INFINITE);
1250 cld = rv - WAIT_OBJECT_0;
1251 if (rv == WAIT_FAILED) {
1252 /* Something serious is wrong */
1253 workers_may_exit = 1;
1254 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1255 "Child %d: WAIT_FAILED -- shutting down server");
1257 else if (rv == WAIT_TIMEOUT) {
1258 /* Hey, this cannot happen */
1259 workers_may_exit = 1;
1260 ap_log_error(APLOG_MARK, APLOG_CRIT, APR_SUCCESS, server_conf,
1261 "Child %d: WAIT_TIMEOUT -- shutting down server", my_pid);
1263 else if (cld == 0) {
1264 /* Exit event was signaled */
1265 workers_may_exit = 1;
1266 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1267 "Child %d: Exit event signaled. Child process is ending.", my_pid);
1270 /* Child maintenance event signaled */
1271 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1274 ResetEvent(maintenance_event);
1275 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1276 "Child %d: Child maintenance event signaled.", my_pid);
1280 /* Setting is_graceful will close keep-alive connections
1283 /* Shutdown the worker threads */
1284 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1285 for (i = 0; i < nthreads; i++) {
1289 else { /* Windows NT/2000 */
1293 * First thing to do is to drain all the completion contexts off the
1294 * AcceptEx iocp. Give a busy server the chance to drain
1295 * the port by servicing connections (workers_may_exit prevents new
1296 * AcceptEx completion contexts from being queued to the port).
1300 /* Cancel any remaining pending async i/o.
1301 * This will cause io completion packets to be queued to the
1302 * port for any remaining active contexts
1304 for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1305 ap_get_os_sock(&nsd,lr->sd);
1306 CancelIo((HANDLE) nsd);
1309 /* Drain the canceled contexts off the port */
1310 drain_acceptex_complport(AcceptExCompPort, FALSE);
1312 /* Hopefully by now, all the completion contexts should be drained
1313 * off the port. There could still be some cancel io completion packets
1314 * flying around in the kernel... We will cover this possibility later..
1316 * Consider using HasOverlappedIoCompleted()...
1318 * Next task is to unblock all the threads blocked on
1319 * GetQueuedCompletionStatus()
1322 for (i=0; i < nthreads*2; i++) {
1323 PostQueuedCompletionStatus(AcceptExCompPort, 0, my_pid, NULL);
1326 /* Give the worker threads time to realize they've been posted */
1330 /* Release the start_mutex to let the new process (in the restart
1331 * scenario) a chance to begin servicing requests
1333 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1334 "Child %d: Releasing the start mutex", my_pid);
1335 ap_unlock(start_mutex);
1337 /* Give busy worker threads a chance to service their connections.
1338 * Kill them off if they take too long
1340 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1341 "Child %d: Waiting for %d threads to die.", my_pid, nthreads);
1342 end_time = time(NULL) + 180;
1344 rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1345 if (rv != WAIT_TIMEOUT) {
1346 rv = rv - WAIT_OBJECT_0;
1347 ap_assert((rv >= 0) && (rv < nthreads));
1348 cleanup_thread(child_handles, &nthreads, rv);
1353 for (i = 0; i < nthreads; i++) {
1354 TerminateThread(child_handles[i], 1);
1355 CloseHandle(child_handles[i]);
1357 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1358 "Child %d: All worker threads have ended.", my_pid);
1360 CloseHandle(AcceptExCompPort);
1361 destroy_semaphore(allowed_globals.jobsemaphore);
1362 ap_destroy_lock(allowed_globals.jobmutex);
1364 ap_destroy_pool(pchild);
1365 CloseHandle(exit_event);
1369 * Spawn a child Apache process. The child process has the command line arguments from
1370 * argc and argv[], plus a -Z argument giving the name of an event. The child should
1371 * open and poll or wait on this event. When it is signalled, the child should die.
1372 * prefix is a prefix string for the event name.
1374 * The child_num argument on entry contains a serial number for this child (used to create
1375 * a unique event name). On exit, this number will have been incremented by one, ready
1376 * for the next call.
1378 * On exit, the value pointed to be *ev will contain the event created
1379 * to signal the new child process.
1381 * The return value is the handle to the child process if successful, else -1. If -1 is
1382 * returned the error will already have been logged by ap_log_error().
1385 /**********************************************************************
1386 * master_main - this is the parent (main) process. We create a
1387 * child process to do the work, then sit around waiting for either
1388 * the child to exit, or a restart or exit signal. If the child dies,
1389 * we just respawn a new one. If we have a shutdown or graceful restart,
1390 * tell the child to die when it is ready. If it is a non-graceful
1391 * restart, force the child to die immediately.
1392 **********************************************************************/
1394 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1396 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1401 CloseHandle(handles[position]);
1402 CloseHandle(events[position]);
1404 handle = (int)handles[position];
1406 for (i = position; i < (*processes)-1; i++) {
1407 handles[i] = handles[i + 1];
1408 events[i] = events[i + 1];
1413 static int create_process(ap_pool_t *p, HANDLE *handles, HANDLE *events, int *processes)
1422 STARTUPINFO si; /* Filled in prior to call to CreateProcess */
1423 PROCESS_INFORMATION pi; /* filled in on call to CreateProcess */
1427 HANDLE hPipeRead = NULL;
1428 HANDLE hPipeWrite = NULL;
1429 SECURITY_ATTRIBUTES sa = {0};
1432 LPWSAPROTOCOL_INFO lpWSAProtocolInfo;
1433 HANDLE hDupedCompPort;
1435 sa.nLength = sizeof(sa);
1436 sa.bInheritHandle = TRUE;
1437 sa.lpSecurityDescriptor = NULL;
1439 /* Build the command line. Should look something like this:
1440 * C:/apache/bin/apache.exe -f ap_server_confname
1441 * First, get the path to the executable...
1443 rv = GetModuleFileName(NULL, buf, sizeof(buf));
1444 if (rv == sizeof(buf)) {
1445 ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1446 "Parent: Path to Apache process too long");
1448 } else if (rv == 0) {
1449 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1450 "Parent: GetModuleFileName() returned NULL for current process.");
1454 /* Build the command line */
1455 pCommand = ap_psprintf(p, "\"%s\"", buf);
1456 for (i = 1; i < server_conf->process->argc; i++) {
1457 pCommand = ap_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1460 /* Build the environment, since Win9x disrespects the active env */
1461 pEnvVar = ap_psprintf(p, "AP_PARENT_PID=%i", parent_pid);
1463 * Win32's CreateProcess call requires that the environment
1464 * be passed in an environment block, a null terminated block of
1465 * null terminated strings.
1469 while (_environ[i]) {
1470 iEnvBlockLen += strlen(_environ[i]) + 1;
1474 pEnvBlock = (char *)ap_pcalloc(p, iEnvBlockLen + strlen(pEnvVar) + 1);
1475 strcpy(pEnvBlock, pEnvVar);
1476 pEnvVar = strchr(pEnvBlock, '\0') + 1;
1479 while (_environ[i]) {
1480 strcpy(pEnvVar, _environ[i]);
1481 pEnvVar = strchr(pEnvVar, '\0') + 1;
1485 /* Create a pipe to send socket info to the child */
1486 if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1487 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1488 "Parent: Unable to create pipe to child process.\n");
1492 /* Give the read end of the pipe (hPipeRead) to the child as stdin. The
1493 * parent will write the socket data to the child on this pipe.
1495 memset(&si, 0, sizeof(si));
1496 memset(&pi, 0, sizeof(pi));
1498 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1499 si.wShowWindow = SW_HIDE;
1500 si.hStdInput = hPipeRead;
1502 if (!CreateProcess(NULL, pCommand, NULL, NULL,
1503 TRUE, /* Inherit handles */
1504 CREATE_SUSPENDED, /* Creation flags */
1505 pEnvBlock, /* Environment block */
1508 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1509 "Parent: Not able to create the child process.");
1511 * We must close the handles to the new process and its main thread
1512 * to prevent handle and memory leaks.
1514 CloseHandle(pi.hProcess);
1515 CloseHandle(pi.hThread);
1519 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1520 "Parent: Created child process %d", pi.dwProcessId);
1522 SetEnvironmentVariable("AP_PARENT_PID",NULL);
1524 /* Create the exit_event, apCchild_pid */
1525 sa.nLength = sizeof(sa);
1526 sa.bInheritHandle = TRUE;
1527 sa.lpSecurityDescriptor = NULL;
1528 kill_event = CreateEvent(&sa, TRUE, FALSE, ap_psprintf(pconf,"apC%d", pi.dwProcessId));
1530 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1531 "Parent: Could not create exit event for child process");
1532 CloseHandle(pi.hProcess);
1533 CloseHandle(pi.hThread);
1537 /* Assume the child process lives. Update the process and event tables */
1538 handles[*processes] = pi.hProcess;
1539 events[*processes] = kill_event;
1542 /* We never store the thread's handle, so close it now. */
1543 ResumeThread(pi.hThread);
1544 CloseHandle(pi.hThread);
1546 /* Run the chain of open sockets. For each socket, duplicate it
1547 * for the target process then send the WSAPROTOCOL_INFO
1548 * (returned by dup socket) to the child */
1549 for (lr = ap_listeners; lr; lr = lr->next) {
1551 lpWSAProtocolInfo = ap_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1552 ap_get_os_sock(&nsd,lr->sd);
1553 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1554 "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1555 if (WSADuplicateSocket(nsd, pi.dwProcessId,
1556 lpWSAProtocolInfo) == SOCKET_ERROR) {
1557 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, server_conf,
1558 "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1562 if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1564 (LPOVERLAPPED) NULL)) {
1565 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1566 "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1569 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1570 "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1572 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1573 /* Now, send the AcceptEx completion port to the child */
1574 if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort,
1575 pi.hProcess, &hDupedCompPort, 0,
1576 TRUE, DUPLICATE_SAME_ACCESS)) {
1577 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1578 "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1582 WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1585 CloseHandle(hPipeRead);
1586 CloseHandle(hPipeWrite);
1591 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1593 int remaining_children_to_start = ap_daemons_to_start;
1597 int restart_pending = 0;
1598 int shutdown_pending = 0;
1599 int current_live_processes = 0; /* number of child process we know about */
1601 HANDLE process_handles[MAX_PROCESSES];
1602 HANDLE process_kill_events[MAX_PROCESSES];
1605 bind_listeners_to_completion_port();
1607 /* Create child process
1608 * Should only be one in this version of Apache for WIN32
1610 while (remaining_children_to_start--) {
1611 if (create_process(pconf, process_handles, process_kill_events,
1612 ¤t_live_processes) < 0) {
1613 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1614 "master_main: create child process failed. Exiting.");
1615 shutdown_pending = 1;
1620 restart_pending = shutdown_pending = 0;
1622 if (!strcasecmp(signal_arg, "runservice"))
1623 mpm_service_started();
1625 /* Wait for shutdown or restart events or for child death */
1626 process_handles[current_live_processes] = shutdown_event;
1627 process_handles[current_live_processes+1] = restart_event;
1629 rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles,
1631 cld = rv - WAIT_OBJECT_0;
1632 if (rv == WAIT_FAILED) {
1633 /* Something serious is wrong */
1634 ap_log_error(APLOG_MARK,APLOG_CRIT, GetLastError(), server_conf,
1635 "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1636 shutdown_pending = 1;
1638 else if (rv == WAIT_TIMEOUT) {
1639 /* Hey, this cannot happen */
1640 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1641 "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1642 shutdown_pending = 1;
1644 else if (cld == current_live_processes) {
1645 /* shutdown_event signalled */
1646 shutdown_pending = 1;
1647 printf("shutdown event signaled\n");
1648 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1649 "master_main: Shutdown event signaled -- doing server shutdown.");
1650 if (ResetEvent(shutdown_event) == 0) {
1651 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1652 "ResetEvent(shutdown_event)");
1656 else if (cld == current_live_processes+1) {
1657 /* restart_event signalled */
1658 int children_to_kill = current_live_processes;
1659 restart_pending = 1;
1660 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, s,
1661 "master_main: Restart event signaled. Doing a graceful restart.");
1662 if (ResetEvent(restart_event) == 0) {
1663 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1664 "master_main: ResetEvent(restart_event) failed.");
1666 /* Signal each child process to die
1667 * We are making a big assumption here that the child process, once signaled,
1668 * will REALLY go away. Since this is a restart, we do not want to hold the
1669 * new child process up waiting for the old child to die. Remove the old
1670 * child out of the process_handles ap_table_t and hope for the best...
1672 for (i = 0; i < children_to_kill; i++) {
1673 if (SetEvent(process_kill_events[i]) == 0)
1674 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1675 "master_main: SetEvent for child process in slot #%d failed", i);
1676 cleanup_process(process_handles, process_kill_events, i, ¤t_live_processes);
1680 /* A child process must have exited because of a fatal error condition (seg fault, etc.).
1681 * Remove the dead process
1682 * from the process_handles and process_kill_events ap_table_t and create a new
1684 * TODO: Consider restarting the child immediately without looping through http_main
1685 * and without rereading the configuration. Will need this if we ever support multiple
1686 * children. One option, create a parent thread which waits on child death and restarts it.
1687 * Consider, however, that if the user makes httpd.conf invalid, we want to die before
1688 * our child tries it... otherwise we have a nasty loop.
1690 restart_pending = 1;
1691 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1692 "master_main: Child process failed. Restarting the child process.");
1693 ap_assert(cld < current_live_processes);
1694 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1695 /* APD2("main_process: child in slot %d died", rv); */
1696 /* restart_child(process_hancles, process_kill_events, cld, ¤t_live_processes); */
1698 /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead
1700 drain_acceptex_complport(AcceptExCompPort, FALSE);
1704 if (shutdown_pending)
1706 int tmstart = time(NULL);
1708 if (strcasecmp(signal_arg,"runservice")
1709 && (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)) {
1710 mpm_service_nt_stopping();
1712 /* Signal each child processes to die */
1713 for (i = 0; i < current_live_processes; i++) {
1714 printf("SetEvent handle = %d\n", process_kill_events[i]);
1715 if (SetEvent(process_kill_events[i]) == 0)
1716 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1717 "master_main: SetEvent for child process in slot #%d failed", i);
1720 while (current_live_processes && ((tmstart+60) > time(NULL))) {
1721 rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1722 if (rv == WAIT_TIMEOUT)
1724 ap_assert(rv != WAIT_FAILED);
1725 cld = rv - WAIT_OBJECT_0;
1726 ap_assert(rv < current_live_processes);
1727 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1729 for (i = 0; i < current_live_processes; i++) {
1730 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1731 "forcing termination of child #%d (handle %d)", i, process_handles[i]);
1732 TerminateProcess((HANDLE) process_handles[i], 1);
1734 return 0; /* Tell the caller we do not want to restart */
1737 return 1; /* Tell the caller we want a restart */
1741 #define SERVICE_UNNAMED -1
1743 /* service_nt_main_fn needs to append the StartService() args
1744 * outside of our call stack and thread as the service starts...
1746 ap_array_header_t *mpm_new_argv;
1748 /* Remember service_to_start failures to log and fail in pre_config.
1749 * Remember inst_argc and inst_argv for installing or starting the
1750 * service after we preflight the config.
1753 static ap_status_t service_to_start_success;
1754 static int inst_argc;
1755 static char **inst_argv;
1757 void winnt_rewrite_args(process_rec *process)
1759 /* Handle the following SCM aspects in this phase:
1761 * -k runservice [transition for WinNT, nothing for Win9x]
1762 * -k (!)install [error out if name is not installed]
1764 * We can't leave this phase until we know our identity
1765 * and modify the command arguments appropriately.
1767 ap_status_t service_named = SERVICE_UNNAMED;
1769 char *def_server_root;
1770 char fnbuf[MAX_PATH];
1777 one_process = !!getenv("ONE_PROCESS");
1779 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1780 GetVersionEx(&osver);
1782 /* AP_PARENT_PID is only valid in the child */
1783 pid = getenv("AP_PARENT_PID");
1786 /* This is the child */
1787 parent_pid = (DWORD) atol(pid);
1788 my_pid = GetCurrentProcessId();
1790 /* The parent is responsible for providing the
1791 * COMPLETE ARGUMENTS REQUIRED to the child.
1793 * No further argument parsing is needed, but
1794 * for good measure we will provide a simple
1795 * signal string for later testing.
1797 signal_arg = "runchild";
1801 /* This is the parent, we have a long way to go :-) */
1802 parent_pid = my_pid = GetCurrentProcessId();
1804 /* Rewrite process->argv[];
1806 * strip out -k signal into signal_arg
1807 * strip out -n servicename into service_name & display_name
1808 * add default -d serverroot from the path of this executable
1810 * The end result will look like:
1812 * The invocation command ($0)
1813 * The -d serverroot default from the running executable
1814 * The requested service's (-n) registry ConfigArgs
1815 * The command line arguments from this process
1816 * The WinNT SCM's StartService() args
1819 if (!GetModuleFileName(NULL, fnbuf, sizeof(fnbuf))) {
1820 /* WARNING: There is an implict assumption here that the
1821 * executable resides in the ServerRoot!
1823 rv = GetLastError();
1824 ap_log_error(APLOG_MARK,APLOG_ERR, rv, NULL,
1825 "Failed to get the running module's file name");
1828 def_server_root = (char *) ap_filename_of_pathname(fnbuf);
1829 if (def_server_root > fnbuf) {
1830 *(def_server_root - 1) = '\0';
1831 def_server_root = ap_os_canonical_filename(process->pool, fnbuf);
1834 /* Use process->pool so that the rewritten argv
1835 * lasts for the lifetime of the server process,
1836 * because pconf will be destroyed after the
1837 * initial pre-flight of the config parser.
1840 mpm_new_argv = ap_make_array(process->pool, process->argc + 2, sizeof(char *));
1841 new_arg = (char**) ap_push_array(mpm_new_argv);
1842 *new_arg = (char *) process->argv[0];
1844 new_arg = (char**) ap_push_array(mpm_new_argv);
1846 new_arg = (char**) ap_push_array(mpm_new_argv);
1847 *new_arg = def_server_root;
1849 fixed_args = mpm_new_argv->nelts;
1851 optbuf[0] = '-'; optbuf[2] = '\0';
1852 while (ap_getopt(process->argc, (char**) process->argv,
1853 "n:k:iu" AP_SERVER_BASEARGS,
1854 &opt, process->pool) == APR_SUCCESS) {
1857 service_named = mpm_service_set_name(process->pool, ap_optarg);
1860 signal_arg = ap_optarg;
1863 /* TODO: warn of depreciated syntax, "use -k install instead" */
1864 signal_arg = "install";
1867 /* TODO: warn of depreciated syntax, "use -k uninstall instead" */
1868 signal_arg = "uninstall";
1871 optbuf[1] = (char) opt;
1872 new_arg = (char**) ap_push_array(mpm_new_argv);
1873 *new_arg = ap_pstrdup(process->pool, optbuf);
1875 new_arg = (char**) ap_push_array(mpm_new_argv);
1876 *new_arg = ap_optarg;
1881 /* Set optreset and optind to allow ap_getopt to work correctly
1882 * when called from http_main.c
1887 /* Track the number of args actually entered by the user */
1888 inst_argc = mpm_new_argv->nelts - fixed_args;
1890 /* Provide a default 'run' -k arg to simplify signal_arg tests */
1894 if (!strcasecmp(signal_arg, "runservice"))
1896 /* Start the NT Service _NOW_ because the WinNT SCM is
1897 * expecting us to rapidly assume control of our own
1898 * process, the SCM will tell us our service name, and
1899 * may have extra StartService() command arguments to
1902 * Any other process has a console, so we don't to begin
1903 * a Win9x service until the configuration is parsed and
1904 * any command line errors are reported.
1906 * We hold the return value so that we can die in pre_config
1907 * after logging begins, and the failure can land in the log.
1909 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) {
1910 service_to_start_success = mpm_service_to_start();
1911 if (service_to_start_success == APR_SUCCESS)
1912 service_named = APR_SUCCESS;
1916 if (service_named == SERVICE_UNNAMED) {
1917 service_named = mpm_service_set_name(process->pool,
1918 DEFAULT_SERVICE_NAME);
1921 if (strcasecmp(signal_arg, "install")) /* not -k install */
1923 if (service_named == APR_SUCCESS)
1925 rv = mpm_merge_service_args(process->pool, mpm_new_argv,
1927 if (rv != APR_SUCCESS) {
1928 ap_log_error(APLOG_MARK,APLOG_ERR, rv, NULL,
1929 "%s: ConfigArgs are missing from the registry.",
1935 ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
1936 "%s: No installed service by that name.", display_name);
1940 else /* -k install */
1942 if (service_named == APR_SUCCESS)
1944 ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
1945 "%s: Service is already installed.", display_name);
1950 /* Track the args actually entered by the user.
1951 * These will be used for the -k install parameters, as well as
1952 * for the -k start service override arguments.
1954 inst_argv = (char**) mpm_new_argv->elts + mpm_new_argv->nelts - inst_argc;
1956 process->argc = mpm_new_argv->nelts;
1957 process->argv = (char**) mpm_new_argv->elts;
1961 static void winnt_pre_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp)
1963 /* Handle the following SCM aspects in this phase:
1965 * -k runservice [WinNT errors logged from rewrite_args]
1968 * in both cases we -don't- care if httpd.conf is error-free
1972 if (!strcasecmp(signal_arg, "runservice")
1973 && (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
1974 && (service_to_start_success != APR_SUCCESS)) {
1975 ap_log_error(APLOG_MARK,APLOG_ERR, service_to_start_success, NULL,
1976 "%s: Unable to start the service manager.",
1981 if (!strcasecmp(signal_arg, "uninstall")) {
1982 rv = mpm_service_uninstall();
1986 ap_listen_pre_config();
1987 ap_daemons_to_start = DEFAULT_NUM_DAEMON;
1988 ap_threads_per_child = DEFAULT_START_THREAD;
1989 ap_pid_fname = DEFAULT_PIDLOG;
1990 max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1992 ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1995 static void winnt_post_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp, server_rec* server)
1997 static int restart_num = 0;
2000 server_conf = server;
2002 /* Handle the following SCM aspects in this phase:
2008 * -k runservice [Win95, only once - after we parsed the config]
2010 * because all of these signals are useful _only_ if there
2011 * is a valid conf\httpd.conf environment to start.
2013 * We reached this phase by avoiding errors that would cause
2014 * these options to fail unexpectedly in another process.
2017 if (!strcasecmp(signal_arg, "install")) {
2018 rv = mpm_service_install(ptemp, inst_argc, inst_argv);
2022 if (!strcasecmp(signal_arg, "start")) {
2023 rv = mpm_service_start(ptemp, inst_argc, inst_argv);
2027 if (!strcasecmp(signal_arg, "restart")) {
2028 mpm_signal_service(ptemp, ap_pid_fname, 1);
2032 // TODO: This Stinks - but we needed the ap_pid_fname entry from
2033 // the config!?! Find a clean way to get the egg back into
2034 // into the chicken and shove this signal into pre_config
2036 // src/os/win32/main_win32.c had some (possibly buggy) code to
2037 // search for just the PidFile entry, but this sounds like a
2038 // universally useful function that we ought to wrap into the
2039 // main server, not just the Win32 MPM.
2041 if (!strcasecmp(signal_arg, "stop")) {
2042 mpm_signal_service(ptemp, ap_pid_fname, 0);
2046 if (parent_pid == my_pid)
2048 if (restart_num++ == 1)
2050 /* This code should be run once in the parent and not run
2053 PSECURITY_ATTRIBUTES sa = GetNullACL(); /* returns NULL if invalid (Win95?) */
2054 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
2055 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
2056 /* Create the AcceptEx IoCompletionPort once in the parent.
2057 * The completion port persists across restarts.
2059 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
2062 0); /* CONCURRENT ACTIVE THREADS */
2063 if (AcceptExCompPort == NULL) {
2064 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
2065 "Parent: Unable to create the AcceptExCompletionPort -- process will exit");
2070 ap_log_pid(pconf, ap_pid_fname);
2072 /* Create shutdown event, apPID_shutdown, where PID is the parent
2073 * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
2075 shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
2076 if (!shutdown_event) {
2077 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
2078 "Parent: Cannot create shutdown event %s", signal_shutdown_name);
2079 CleanNullACL((void *)sa);
2083 /* Create restart event, apPID_restart, where PID is the parent
2084 * Apache process ID. Restart is signaled by 'apache -k restart'.
2086 restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
2087 if (!restart_event) {
2088 CloseHandle(shutdown_event);
2089 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
2090 "Parent: Cannot create restart event %s", signal_restart_name);
2091 CleanNullACL((void *)sa);
2094 CleanNullACL((void *)sa);
2096 /* Now that we are flying at 15000 feet...
2097 * wipe out the Win95 service console,
2098 * signal the SCM the WinNT service started, or
2099 * if not a service, setup console handlers instead.
2101 if (!strcasecmp(signal_arg, "runservice"))
2103 if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT)
2105 rv = mpm_service_to_start();
2106 if (rv != APR_SUCCESS) {
2107 ap_log_error(APLOG_MARK,APLOG_ERR, rv, server_conf,
2108 "%s: Unable to start the service manager.",
2114 else /* ! -k runservice */
2116 mpm_start_console_handler();
2119 /* Create the start mutex, apPID, where PID is the parent Apache process ID.
2120 * Ths start mutex is used during a restart to prevent more than one
2121 * child process from entering the accept loop at once.
2123 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS, signal_name_prefix,
2124 server_conf->process->pool);
2127 else /* parent_pid != my_pid */
2129 mpm_start_child_console_handler();
2133 API_EXPORT(int) ap_mpm_run(ap_pool_t *_pconf, ap_pool_t *plog, server_rec *s )
2135 static int restart = 0; /* Default is "not a restart" */
2140 if ((parent_pid != my_pid) || one_process) {
2141 /* Running as Child process or in one_process (debug) mode */
2142 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
2143 "Child %d: Child process is running", my_pid);
2145 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
2146 "Child %d: Child process is exiting", my_pid);
2149 } /* Child or single process */
2150 else { /* Parent process */
2151 restart = master_main(server_conf, shutdown_event, restart_event);
2154 /* Shutting down. Clean up... */
2155 const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
2157 if (pidfile != NULL && unlink(pidfile) == 0) {
2158 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS,
2159 server_conf, "removed PID file %s (pid=%ld)",
2160 pidfile, GetCurrentProcessId());
2162 ap_destroy_lock(start_mutex);
2164 CloseHandle(restart_event);
2165 CloseHandle(shutdown_event);
2169 } /* Parent process */
2171 return 0; /* Restart */
2174 static void winnt_hooks(void)
2177 ap_hook_pre_config(winnt_pre_config, NULL, NULL, AP_HOOK_MIDDLE);
2178 ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
2182 * Command processors
2184 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg)
2186 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2191 if (cmd->server->is_virtual) {
2192 return "PidFile directive not allowed in <VirtualHost>";
2198 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg)
2200 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2205 ap_threads_per_child = atoi(arg);
2206 if (ap_threads_per_child > HARD_THREAD_LIMIT) {
2207 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2208 "WARNING: ThreadsPerChild of %d exceeds compile time"
2209 " limit of %d threads,", ap_threads_per_child,
2211 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2212 " lowering ThreadsPerChild to %d. To increase, please"
2213 " see the HARD_THREAD_LIMIT define in %s.",
2214 HARD_THREAD_LIMIT, AP_MPM_HARD_LIMITS_FILE);
2216 else if (ap_threads_per_child < 1) {
2217 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2218 "WARNING: Require ThreadsPerChild > 0, setting to 1");
2219 ap_threads_per_child = 1;
2225 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg)
2227 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2232 max_requests_per_child = atoi(arg);
2237 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg)
2241 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2246 fname = ap_server_root_relative(cmd->pool, arg);
2247 if ((ap_stat(&finfo, fname, cmd->pool) != APR_SUCCESS) ||
2248 (finfo.filetype != APR_DIR)) {
2249 return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
2250 " does not exist or is not a directory", NULL);
2252 ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
2256 /* Stub functions until this MPM supports the connection status API */
2258 API_EXPORT(void) ap_update_connection_status(long conn_id, const char *key, \
2264 API_EXPORT(void) ap_reset_connection_status(long conn_id)
2269 API_EXPORT(ap_array_header_t *) ap_get_status_table(ap_pool_t *p)
2275 static const command_rec winnt_cmds[] = {
2277 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
2278 "A file for logging the server process ID"},
2279 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
2280 "Number of threads each child creates" },
2281 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
2282 "Maximum number of requests a particular child serves before dying." },
2283 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
2284 "The location of the directory Apache changes to before dumping core" },
2288 MODULE_VAR_EXPORT module mpm_winnt_module = {
2290 winnt_rewrite_args, /* hook to run before apache parses args */
2291 NULL, /* create per-directory config structure */
2292 NULL, /* merge per-directory config structures */
2293 NULL, /* create per-server config structure */
2294 NULL, /* merge per-server config structures */
2295 winnt_cmds, /* command ap_table_t */
2296 NULL, /* handlers */
2297 winnt_hooks /* register_hooks */