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"
68 #include "apr_strings.h"
70 #include "ap_config.h"
71 #include "ap_listen.h"
72 #include "mpm_default.h"
73 #include "mpm_winnt.h"
74 #include "mpm_common.h"
77 * Definitions of WINNT MPM specific config globals
79 static int workers_may_exit = 0;
80 static int shutdown_in_progress = 0;
81 static unsigned int g_blocked_threads = 0;
83 static char *ap_pid_fname = NULL;
84 static int ap_threads_per_child = 0;
86 static int max_requests_per_child = 0;
87 static HANDLE shutdown_event; /* used to signal shutdown to parent */
88 static HANDLE restart_event; /* used to signal a restart to parent */
90 #define MAX_SIGNAL_NAME 30 /* Long enough for apPID_shutdown, where PID is an int */
91 char signal_name_prefix[MAX_SIGNAL_NAME];
92 char signal_restart_name[MAX_SIGNAL_NAME];
93 char signal_shutdown_name[MAX_SIGNAL_NAME];
95 static struct fd_set listenfds;
96 static int num_listenfds = 0;
97 static SOCKET listenmaxfd = INVALID_SOCKET;
99 static apr_pool_t *pconf; /* Pool for config stuff */
101 static char ap_coredump_dir[MAX_STRING_LEN];
103 static server_rec *server_conf;
104 static HANDLE AcceptExCompPort = NULL;
106 static int one_process = 0;
107 static char const* signal_arg;
109 OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
111 int ap_max_requests_per_child=0;
112 int ap_daemons_to_start=0;
114 static event *exit_event;
115 HANDLE maintenance_event;
116 apr_lock_t *start_mutex;
120 /* This is the helper code to resolve late bound entry points
121 * missing from one or more releases of the Win32 API...
122 * but it sure would be nice if we didn't duplicate this code
126 static const char* const lateDllName[DLL_defined] = {
127 "kernel32", "advapi32", "mswsock", "ws2_32" };
128 static HMODULE lateDllHandle[DLL_defined] = {
129 NULL, NULL, NULL, NULL };
131 FARPROC ap_load_dll_func(ap_dlltoken_e fnLib, char* fnName, int ordinal)
133 if (!lateDllHandle[fnLib]) {
134 lateDllHandle[fnLib] = LoadLibrary(lateDllName[fnLib]);
135 if (!lateDllHandle[fnLib])
139 return GetProcAddress(lateDllHandle[fnLib], (char *) ordinal);
141 return GetProcAddress(lateDllHandle[fnLib], fnName);
144 static apr_status_t socket_cleanup(void *sock)
146 apr_socket_t *thesocket = sock;
148 if (apr_get_os_sock(&sd, thesocket) == APR_SUCCESS) {
154 /* A bunch or routines from os/win32/multithread.c that need to be merged into APR
155 * or thrown out entirely...
158 typedef void semaphore;
162 create_semaphore(int initial)
164 return(CreateSemaphore(NULL, initial, 1000000, NULL));
167 static void acquire_semaphore(semaphore *semaphore_id)
171 rv = WaitForSingleObject(semaphore_id, INFINITE);
176 static int release_semaphore(semaphore *semaphore_id)
178 return(ReleaseSemaphore(semaphore_id, 1, NULL));
181 static void destroy_semaphore(semaphore *semaphore_id)
183 CloseHandle(semaphore_id);
187 /* To share the semaphores with other processes, we need a NULL ACL
188 * Code from MS KB Q106387
190 static PSECURITY_ATTRIBUTES GetNullACL()
192 PSECURITY_DESCRIPTOR pSD;
193 PSECURITY_ATTRIBUTES sa;
195 sa = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES));
196 pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,
197 SECURITY_DESCRIPTOR_MIN_LENGTH);
198 if (pSD == NULL || sa == NULL) {
202 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
203 || apr_get_os_error()) {
208 if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
209 || apr_get_os_error()) {
214 sa->nLength = sizeof(sa);
215 sa->lpSecurityDescriptor = pSD;
216 sa->bInheritHandle = TRUE;
220 static void CleanNullACL( void *sa ) {
222 LocalFree( ((PSECURITY_ATTRIBUTES)sa)->lpSecurityDescriptor);
228 * The Win32 call WaitForMultipleObjects will only allow you to wait for
229 * a maximum of MAXIMUM_WAIT_OBJECTS (current 64). Since the threading
230 * model in the multithreaded version of apache wants to use this call,
231 * we are restricted to a maximum of 64 threads. This is a simplistic
232 * routine that will increase this size.
234 static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles,
238 DWORD dwRet = WAIT_TIMEOUT;
242 tStopTime = time(NULL) + dwSeconds;
250 for (dwIndex = 0; dwIndex * MAXIMUM_WAIT_OBJECTS < nCount; dwIndex++) {
251 dwRet = WaitForMultipleObjects(
252 min(MAXIMUM_WAIT_OBJECTS, nCount - (dwIndex * MAXIMUM_WAIT_OBJECTS)),
253 lpHandles + (dwIndex * MAXIMUM_WAIT_OBJECTS),
256 if (dwRet != WAIT_TIMEOUT) {
260 } while((time(NULL) < tStopTime) && (dwRet == WAIT_TIMEOUT));
266 * Signalling Apache on NT.
268 * Under Unix, Apache can be told to shutdown or restart by sending various
269 * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
270 * we use "events" instead. The parent apache process goes into a loop
271 * where it waits forever for a set of events. Two of those events are
277 * (where PID is the PID of the apache parent process). When one of these
278 * is signalled, the Apache parent performs the appropriate action. The events
279 * can become signalled through internal Apache methods (e.g. if the child
280 * finds a fatal error and needs to kill its parent), via the service
281 * control manager (the control thread will signal the shutdown event when
282 * requested to stop the Apache service), from the -k Apache command line,
283 * or from any external program which finds the Apache PID from the
286 * The signal_parent() function, below, is used to signal one of these events.
287 * It can be called by any child or parent process, since it does not
288 * rely on global variables.
290 * On entry, type gives the event to signal. 0 means shutdown, 1 means
293 void signal_parent(int type)
298 /* after updating the shutdown_pending or restart flags, we need
299 * to wake up the parent process so it can see the changes. The
300 * parent will normally be waiting for either a child process
301 * to die, or for a signal on the "spache-signal" event. So set the
302 * "apache-signal" event here.
309 case 0: signal_name = signal_shutdown_name; break;
310 case 1: signal_name = signal_restart_name; break;
313 e = OpenEvent(EVENT_ALL_ACCESS, FALSE, signal_name);
315 /* Um, problem, can't signal the parent, which means we can't
316 * signal ourselves to die. Ignore for now...
318 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
319 "OpenEvent on %s event", signal_name);
322 if (SetEvent(e) == 0) {
323 /* Same problem as above */
324 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
325 "SetEvent on %s event", signal_name);
332 static int volatile is_graceful = 0;
334 API_EXPORT(int) ap_graceful_stop_signalled(void)
339 API_EXPORT(void) ap_start_shutdown(void)
344 API_EXPORT(void) ap_start_restart(int gracefully)
346 is_graceful = gracefully;
351 * Initialise the signal names, in the global variables signal_name_prefix,
352 * signal_restart_name and signal_shutdown_name.
355 void setup_signal_names(char *prefix)
357 apr_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);
358 apr_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name),
359 "%s_shutdown", signal_name_prefix);
360 apr_snprintf(signal_restart_name, sizeof(signal_restart_name),
361 "%s_restart", signal_name_prefix);
365 * Routines that deal with sockets, some are WIN32 specific...
368 static void sock_disable_nagle(int s)
370 /* The Nagle algorithm says that we should delay sending partial
371 * packets in hopes of getting more data. We don't want to do
372 * this; we are not telnet. There are bad interactions between
373 * persistent connections and Nagle's algorithm that have very severe
374 * performance penalties. (Failing to disable Nagle is not much of a
375 * problem with simple HTTP.)
377 * In spite of these problems, failure here is not a shooting offense.
381 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
383 ap_log_error(APLOG_MARK, APLOG_WARNING, APR_SUCCESS, server_conf,
384 "setsockopt: (TCP_NODELAY)");
389 * Routines to deal with managing the list of listening sockets.
391 static ap_listen_rec *head_listener;
393 static apr_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
398 for (lr = head_listener; lr ; lr = lr->next) {
399 apr_get_os_sock(&nsd, lr->sd);
400 if (FD_ISSET(nsd, main_fds)) {
401 head_listener = lr->next;
402 if (head_listener == NULL)
403 head_listener = ap_listeners;
411 static int setup_listeners(server_rec *s)
414 int num_listeners = 0;
417 /* Setup the listeners */
420 if (ap_listen_open(s->process, s->port)) {
423 for (lr = ap_listeners; lr; lr = lr->next) {
425 if (lr->sd != NULL) {
426 apr_get_os_sock(&nsd, lr->sd);
427 FD_SET(nsd, &listenfds);
428 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
435 head_listener = ap_listeners;
437 return num_listeners;
440 static int setup_inherited_listeners(server_rec *s)
442 WSAPROTOCOL_INFO WSAProtocolInfo;
446 int num_listeners = 0;
449 /* Setup the listeners */
452 /* Set up a default listener if necessary */
454 if (ap_listeners == NULL) {
456 lr = apr_palloc(s->process->pool, sizeof(ap_listen_rec));
460 lr->next = ap_listeners;
464 /* Open the pipe to the parent process to receive the inherited socket
465 * data. The sockets have been set to listening in the parent process.
467 pipe = GetStdHandle(STD_INPUT_HANDLE);
468 for (lr = ap_listeners; lr; lr = lr->next) {
469 if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
470 &BytesRead, (LPOVERLAPPED) NULL)) {
471 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
472 "setup_inherited_listeners: Unable to read socket data from parent");
473 signal_parent(0); /* tell parent to die */
476 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
477 "Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.", my_pid);
478 nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
479 &WSAProtocolInfo, 0, 0);
480 if (nsd == INVALID_SOCKET) {
481 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), server_conf,
482 "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
483 signal_parent(0); /* tell parent to die */
487 FD_SET(nsd, &listenfds);
488 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
492 apr_put_os_sock(&lr->sd, &nsd, pconf);
495 /* Now, read the AcceptExCompPort from the parent */
496 ReadFile(pipe, &AcceptExCompPort, sizeof(AcceptExCompPort), &BytesRead, (LPOVERLAPPED) NULL);
499 for (lr = ap_listeners; lr; lr = lr->next) {
503 head_listener = ap_listeners;
504 return num_listeners;
507 static void bind_listeners_to_completion_port()
509 /* Associate the open listeners with the completion port.
510 * Bypass the operation for Windows 95/98
514 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
515 for (lr = ap_listeners; lr; lr = lr->next) {
517 apr_get_os_sock(&nsd,lr->sd);
518 CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
523 /**********************************************************************
524 * Multithreaded implementation
526 * This code is fairly specific to Win32.
528 * The model used to handle requests is a set of threads. One "main"
529 * thread listens for new requests. When something becomes
530 * available, it does a select and places the newly available socket
531 * onto a list of "jobs" (add_job()). Then any one of a fixed number
532 * of "worker" threads takes the top job off the job list with
533 * remove_job() and handles that connection to completion. After
534 * the connection has finished the thread is free to take another
535 * job from the job list.
537 * In the code, the "main" thread is running within the child_main()
538 * function. The first thing this function does is create the
539 * worker threads, which operate in the child_sub_main() function. The
540 * main thread then goes into a loop within child_main() where they
541 * do a select() on the listening sockets. The select times out once
542 * per second so that the thread can check for an "exit" signal
543 * from the parent process (see below). If this signal is set, the
544 * thread can exit, but only after it has accepted all incoming
545 * connections already in the listen queue (since Win32 appears
546 * to through away listened but unaccepted connections when a
549 * Because the main and worker threads exist within a single process
550 * they are vulnerable to crashes or memory leaks (crashes can also
551 * be caused within modules, of course). There also needs to be a
552 * mechanism to perform restarts and shutdowns. This is done by
553 * creating the main & worker threads within a subprocess. A
554 * main process (the "parent process") creates one (or more)
555 * processes to do the work, then the parent sits around waiting
556 * for the working process to die, in which case it starts a new
557 * one. The parent process also handles restarts (by creating
558 * a new working process then signalling the previous working process
559 * exit ) and shutdowns (by signalling the working process to exit).
560 * The parent process operates within the master_main() function. This
561 * process also handles requests from the service manager (NT only).
563 * Signalling between the parent and working process uses a Win32
564 * event. Each child has a unique name for the event, which is
565 * passed to it with the -Z argument when the child is spawned. The
566 * parent sets (signals) this event to tell the child to die.
567 * At present all children do a graceful die - they finish all
568 * current jobs _and_ empty the listen queue before they exit.
569 * A non-graceful die would need a second event. The -Z argument in
570 * the child is also used to create the shutdown and restart events,
571 * since the prefix (apPID) contains the parent process PID.
573 * The code below starts with functions at the lowest level -
574 * worker threads, and works up to the top level - the main()
575 * function of the parent process.
577 * The scoreboard (in process memory) contains details of the worker
578 * threads (within the active working process). There is no shared
579 * "scoreboard" between processes, since only one is ever active
580 * at once (or at most, two, when one has been told to shutdown but
581 * is processes outstanding requests, and a new one has been started).
582 * This is controlled by a "start_mutex" which ensures only one working
583 * process is active at once.
584 **********************************************************************/
588 * Definition of jobs, shared by main and worker threads.
591 typedef struct joblist_s {
592 struct joblist_s *next;
597 * Globals common to main and worker threads. This structure is not
598 * used by the parent process.
601 typedef struct globals_s {
602 semaphore *jobsemaphore;
605 apr_lock_t *jobmutex;
610 globals allowed_globals =
611 {NULL, NULL, NULL, NULL, 0};
612 #define MAX_SELECT_ERRORS 100
613 #define PADDED_ADDR_SIZE sizeof(SOCKADDR_IN)+16
615 /* Windows 9x specific code...
616 * Accept processing for on Windows 95/98 uses a producer/consumer queue
617 * model. A single thread accepts connections and queues the accepted socket
618 * to the accept queue for consumption by a pool of worker threads.
620 * win9x_get_connection()
621 * Calls remove_job() to pull a job from the accept queue. All the worker
622 * threads block on remove_job.
623 * accept_and_queue_connections()
624 * The accept threads runs this function, which accepts connections off
625 * the network and calls add_job() to queue jobs to the accept_queue.
626 * add_job()/remove_job()
627 * Add or remove an accepted socket from the list of sockets
628 * connected to clients. allowed_globals.jobmutex protects
629 * against multiple concurrent access to the linked list of jobs.
631 static void add_job(int sock)
635 new_job = (joblist *) malloc(sizeof(joblist));
636 if (new_job == NULL) {
637 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
638 "Ouch! Out of memory in add_job()!");
641 new_job->next = NULL;
642 new_job->sock = sock;
644 apr_lock(allowed_globals.jobmutex);
646 if (allowed_globals.jobtail != NULL)
647 allowed_globals.jobtail->next = new_job;
648 allowed_globals.jobtail = new_job;
649 if (!allowed_globals.jobhead)
650 allowed_globals.jobhead = new_job;
651 allowed_globals.jobcount++;
652 release_semaphore(allowed_globals.jobsemaphore);
654 apr_unlock(allowed_globals.jobmutex);
657 static int remove_job(void)
662 acquire_semaphore(allowed_globals.jobsemaphore);
663 apr_lock(allowed_globals.jobmutex);
665 if (shutdown_in_progress && !allowed_globals.jobhead) {
666 apr_unlock(allowed_globals.jobmutex);
669 job = allowed_globals.jobhead;
671 allowed_globals.jobhead = job->next;
672 if (allowed_globals.jobhead == NULL)
673 allowed_globals.jobtail = NULL;
674 apr_unlock(allowed_globals.jobmutex);
681 static void accept_and_queue_connections(void * dummy)
683 int requests_this_child = 0;
688 int nsd = INVALID_SOCKET;
689 struct sockaddr_in sa_client;
690 int count_select_errors = 0;
694 while (!shutdown_in_progress) {
695 if (ap_max_requests_per_child && (requests_this_child > ap_max_requests_per_child)) {
699 tv.tv_sec = wait_time;
701 memcpy(&main_fds, &listenfds, sizeof(fd_set));
703 rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
705 if (rc == 0 || (rc == SOCKET_ERROR && h_errno == WSAEINTR)) {
706 count_select_errors = 0; /* reset count of errors */
709 else if (rc == SOCKET_ERROR) {
710 /* A "real" error occurred, log it and increment the count of
711 * select errors. This count is used to ensure we don't go into
712 * a busy loop of continuous errors.
714 ap_log_error(APLOG_MARK, APLOG_INFO, h_errno, server_conf,
715 "select failed with errno %d", h_errno);
716 count_select_errors++;
717 if (count_select_errors > MAX_SELECT_ERRORS) {
718 shutdown_in_progress = 1;
719 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
720 "Too many errors in select loop. Child process exiting.");
726 lr = find_ready_listener(&main_fds);
728 /* fetch the native socket descriptor */
729 apr_get_os_sock(&nsd, lr->sd);
734 clen = sizeof(sa_client);
735 csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
736 if (csd == INVALID_SOCKET) {
739 } while (csd < 0 && h_errno == WSAEINTR);
742 if (h_errno != WSAECONNABORTED) {
743 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
744 "accept: (client socket)");
749 requests_this_child++;
752 SetEvent(exit_event);
754 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
758 if (context == NULL) {
759 /* allocate the completion context and the transaction pool */
760 context = apr_pcalloc(pconf, sizeof(COMP_CONTEXT));
762 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
763 "win9x_get_connection: apr_pcalloc() failed. Process will exit.");
766 apr_create_pool(&context->ptrans, pconf);
771 apr_clear_pool(context->ptrans);
772 context->accept_socket = remove_job();
773 if (context->accept_socket == -1) {
776 len = sizeof(struct sockaddr);
777 context->sa_server = apr_palloc(context->ptrans, len);
778 if (getsockname(context->accept_socket,
779 context->sa_server, &len)== SOCKET_ERROR) {
780 ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), server_conf,
781 "getsockname failed");
784 len = sizeof(struct sockaddr);
785 context->sa_client = apr_palloc(context->ptrans, len);
786 if ((getpeername(context->accept_socket,
787 context->sa_client, &len)) == SOCKET_ERROR) {
788 ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), server_conf,
789 "getpeername failed");
790 memset(&context->sa_client, '\0', sizeof(context->sa_client));
793 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
795 /* do we NEED_DUPPED_CSD ?? */
802 * Windows 2000/NT specific code...
803 * create_acceptex_context()
804 * reset_acceptex_context()
805 * drain_acceptex_complport()
806 * winnt_get_connection()
808 * TODO: Insert a discussion of 'completion contexts' and what these function do here...
810 static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp)
813 PCOMP_CONTEXT context;
820 rc = GetQueuedCompletionStatus(hComplPort, &BytesRead, &CompKey,
823 rc = apr_get_os_error();
824 if (rc == APR_FROM_OS_ERROR(ERROR_OPERATION_ABORTED)) {
825 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
826 "Child %d: - Draining an ABORTED packet off "
827 "the AcceptEx completion port.", my_pid);
832 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
833 "Child %d: - Draining and discarding an active connection "
834 "off the AcceptEx completion port.", my_pid);
835 context = (PCOMP_CONTEXT) pol;
836 if (context && bCleanUp) {
837 /* It is only valid to clean-up in the process that initiated the I/O */
838 closesocket(context->accept_socket);
839 CloseHandle(context->Overlapped.hEvent);
843 static int create_acceptex_context(apr_pool_t *_pconf, ap_listen_rec *lr)
845 PCOMP_CONTEXT context;
850 /* allocate the completion context */
851 context = apr_pcalloc(_pconf, sizeof(COMP_CONTEXT));
853 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
854 "create_acceptex_context: apr_pcalloc() failed. Process will exit.");
858 /* initialize the completion context */
860 context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
861 if (context->Overlapped.hEvent == NULL) {
862 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
863 "create_acceptex_context: CreateEvent() failed. Process will exit.");
867 /* create and initialize the accept socket */
868 apr_get_os_sock(&nsd, context->lr->sd);
869 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
870 if (context->accept_socket == INVALID_SOCKET) {
871 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_netos_error(), server_conf,
872 "create_acceptex_context: socket() failed. Process will exit.");
876 /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
877 if (setsockopt(context->accept_socket, SOL_SOCKET,
878 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
880 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), server_conf,
881 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
882 /* Not a failure condition. Keep running. */
885 apr_create_pool(&context->ptrans, _pconf);
886 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
887 context->recv_buf = context->conn_io->inbase;
888 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
891 /* AcceptEx on the completion context. The completion context will be signaled
892 * when a connection is accepted. */
893 if (!AcceptEx(nsd, context->accept_socket,
895 0, //context->recv_buf_size,
896 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
898 (LPOVERLAPPED) context)) {
899 lasterror = apr_get_netos_error();
900 if (lasterror != APR_FROM_OS_ERROR(ERROR_IO_PENDING)) {
901 ap_log_error(APLOG_MARK,APLOG_ERR, lasterror, server_conf,
902 "create_acceptex_context: AcceptEx failed. Process will exit.");
911 static apr_inline apr_status_t reset_acceptex_context(PCOMP_CONTEXT context)
917 /* reset the buffer pools */
918 apr_clear_pool(context->ptrans);
919 context->sock = NULL;
920 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
921 context->recv_buf = context->conn_io->inbase;
922 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
924 /* recreate and initialize the accept socket if it is not being reused */
925 apr_get_os_sock(&nsd, context->lr->sd);
927 /* AcceptEx on the completion context. The completion context will be signaled
928 * when a connection is accepted. Hack Alert: TransmitFile, under certain
929 * circumstances, can 'recycle' accept sockets, saving the overhead of calling
930 * socket(). Occasionally this fails (usually when the client closes his end
931 * of the connection early). When this occurs, AcceptEx will fail with 10022,
932 * Invalid Parameter. When this occurs, just open a fresh accept socket and
935 for (i=0; i<2; i++) {
936 if (context->accept_socket == INVALID_SOCKET) {
937 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
938 if (context->accept_socket == INVALID_SOCKET) {
939 rc = apr_get_netos_error();
940 ap_log_error(APLOG_MARK,APLOG_ERR, rc, server_conf,
941 "reset_acceptex_context: socket() failed. Process will exit.");
945 /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
946 if (setsockopt(context->accept_socket, SOL_SOCKET,
947 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd, sizeof(nsd))) {
948 ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(),
950 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
954 if (!AcceptEx(nsd, context->accept_socket, context->recv_buf, 0,
955 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE, &BytesRead,
956 (LPOVERLAPPED) context)) {
957 rc = apr_get_netos_error();
958 if (rc != APR_FROM_OS_ERROR(ERROR_IO_PENDING)) {
959 ap_log_error(APLOG_MARK, APLOG_INFO, rc, server_conf,
960 "reset_acceptex_context: AcceptEx failed for "
961 "listening socket: %d and accept socket: %d",
962 nsd, context->accept_socket);
963 closesocket(context->accept_socket);
964 context->accept_socket = INVALID_SOCKET;
971 context->lr->count++;
975 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
977 int requests_this_child = 0;
984 if (context != NULL) {
985 if (shutdown_in_progress) {
986 /* Clean-up the AcceptEx completion context */
987 CloseHandle(context->Overlapped.hEvent);
988 if (context->accept_socket != INVALID_SOCKET)
989 closesocket(context->accept_socket);
992 /* Prepare the completion context for reuse */
993 if ((rc = reset_acceptex_context(context)) != APR_SUCCESS) {
994 ap_log_error(APLOG_MARK, APLOG_CRIT, rc, server_conf,
995 "Child %d: winnt_get_connection: reset_acceptex_context failed.",
997 if (context->accept_socket != INVALID_SOCKET)
998 closesocket(context->accept_socket);
999 CloseHandle(context->Overlapped.hEvent);
1000 /* Probably should just die now... */
1005 /* May need to atomize the workers_may_exit check with the
1006 * g_blocked_threads++ */
1007 if (workers_may_exit) {
1010 g_blocked_threads++;
1013 rc = GetQueuedCompletionStatus(AcceptExCompPort, &BytesRead, &CompKey,
1016 rc = apr_get_os_error();
1017 if (rc != APR_FROM_OS_ERROR(ERROR_OPERATION_ABORTED)) {
1018 /* Is this a deadly condition?
1019 * We sometimes get ERROR_NETNAME_DELETED when a client
1020 * disconnects when attempting to reuse sockets. Not sure why
1021 * we see this now and not during AcceptEx(). Reset the
1022 * AcceptEx context and continue...
1024 ap_log_error(APLOG_MARK,APLOG_INFO, rc, server_conf,
1025 "Child %d: - GetQueuedCompletionStatus() failed",
1027 /* Reset the completion context */
1029 context = (PCOMP_CONTEXT) pol;
1030 if (context->accept_socket != INVALID_SOCKET)
1031 closesocket(context->accept_socket);
1032 if ((rc = reset_acceptex_context(context)) != APR_SUCCESS) {
1033 ap_log_error(APLOG_MARK, APLOG_CRIT, rc, server_conf,
1034 "Child %d: winnt_get_connection: reset_acceptex_context failed.",
1036 if (context->accept_socket != INVALID_SOCKET)
1037 closesocket(context->accept_socket);
1038 CloseHandle(context->Overlapped.hEvent);
1039 /* Probably should just die now... */
1044 /* Sometimes we catch ERROR_OPERATION_ABORTED completion packets
1045 * from the old child process (during a restart). Ignore them.
1047 ap_log_error(APLOG_MARK,APLOG_INFO, rc, server_conf,
1048 "Child %d: - Draining ERROR_OPERATION_ABORTED packet off "
1049 "the completion port.", my_pid);
1055 /* CompKey == my_pid means this thread was unblocked by
1056 * the shutdown code (not by io completion).
1058 if (CompKey == my_pid) {
1059 g_blocked_threads--;
1062 /* Sometimes we catch shutdown io completion packets
1063 * posted by the old child process (during a restart). Ignore them.
1068 context = (PCOMP_CONTEXT) pol;
1072 g_blocked_threads--;
1074 /* Check to see if we need to create more completion contexts,
1075 * but only if we are not in the process of shutting down
1077 if (!shutdown_in_progress) {
1078 apr_lock(allowed_globals.jobmutex);
1079 context->lr->count--;
1080 if (context->lr->count < 2) {
1081 SetEvent(maintenance_event);
1083 apr_unlock(allowed_globals.jobmutex);
1086 /* Received a connection */
1087 context->conn_io->incnt = BytesRead;
1088 GetAcceptExSockaddrs(context->recv_buf,
1089 0, //context->recv_buf_size,
1092 &context->sa_server,
1093 &context->sa_server_len,
1094 &context->sa_client,
1095 &context->sa_client_len);
1101 * worker_main() - this is the main loop for the worker threads
1104 * Each thread runs within this function. They wait within remove_job()
1105 * for a job to become available, then handle all the requests on that
1106 * connection until it is closed, then return to remove_job().
1108 * The worker thread will exit when it removes a job which contains
1109 * socket number -1. This provides a graceful thread exit, since
1110 * it will never exit during a connection.
1112 * This code in this function is basically equivalent to the child_main()
1113 * from the multi-process (Unix) environment, except that we
1115 * - do not call child_init_modules (child init API phase)
1116 * - block in remove_job, and when unblocked we have an already
1117 * accepted socket, instead of blocking on a mutex or select().
1120 static void worker_main(int child_num)
1122 PCOMP_CONTEXT context = NULL;
1126 apr_int32_t disconnected;
1128 /* Grab a connection off the network */
1129 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1130 context = win9x_get_connection(context);
1133 context = winnt_get_connection(context);
1138 sock_disable_nagle(context->accept_socket);
1139 apr_put_os_sock(&context->sock, &context->accept_socket, context->ptrans);
1141 ap_bpush_socket(context->conn_io, context->sock);
1142 c = ap_new_connection(context->ptrans, server_conf, context->conn_io,
1143 (struct sockaddr_in *) context->sa_client,
1144 (struct sockaddr_in *) context->sa_server,
1147 ap_process_connection(c);
1150 apr_getsocketopt(context->sock, APR_SO_DISCONNECTED, &disconnected);
1152 /* I have no idea if we should do anything here, so I leave this
1155 /* Kill the clean-up registered by the iol. We want to leave
1156 * the accept socket open because we are about to try to
1161 context->accept_socket = INVALID_SOCKET;
1162 ap_lingering_close(c);
1166 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1167 "Child %d: Thread exiting.", my_pid);
1170 SetEvent(exit_event);
1172 /* TODO: Add code to clean-up completion contexts here */
1175 static void cleanup_thread(thread **handles, int *thread_cnt, int thread_to_clean)
1179 CloseHandle(handles[thread_to_clean]);
1180 for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1181 handles[i] = handles[i + 1];
1185 static void create_listeners()
1187 #define NUM_LISTENERS 5
1189 for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1190 while (lr->count < NUM_LISTENERS) {
1191 if (create_acceptex_context(pconf, lr) == -1) {
1192 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
1193 "Unable to create an AcceptEx completion context -- process will exit");
1194 signal_parent(0); /* tell parent to die */
1200 * child_main() runs the main control thread for the child process.
1202 * The control thread:
1203 * - sets up the worker thread pool
1204 * - starts the accept thread (Win 9x)
1205 * - creates AcceptEx contexts (Win NT)
1206 * - waits for exit_event, maintenance_event or maintenance timeout
1207 * and does the right thing depending on which event is received.
1209 static void child_main()
1211 apr_status_t status;
1212 HANDLE child_events[2];
1213 char* exit_event_name;
1214 int nthreads = ap_threads_per_child;
1216 thread **child_handles;
1224 /* This is the child process or we are running in single process
1227 exit_event_name = apr_psprintf(pconf, "apC%d", my_pid);
1228 setup_signal_names(apr_psprintf(pconf,"ap%d", parent_pid));
1231 /* Single process mode */
1232 apr_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1233 exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1235 setup_listeners(server_conf);
1236 bind_listeners_to_completion_port();
1239 /* Child process mode */
1240 apr_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1241 exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1242 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1243 "Child %d: exit_event_name = %s", my_pid, exit_event_name);
1245 setup_inherited_listeners(server_conf);
1248 /* Initialize the child_events */
1249 maintenance_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1250 child_events[0] = exit_event;
1251 child_events[1] = maintenance_event;
1253 ap_assert(start_mutex);
1254 ap_assert(exit_event);
1255 ap_assert(maintenance_event);
1257 apr_create_pool(&pchild, pconf);
1258 allowed_globals.jobsemaphore = create_semaphore(0);
1259 apr_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
1262 * Wait until we have permission to start accepting connections.
1263 * start_mutex is used to ensure that only one child ever
1264 * goes into the listen/accept loop at once.
1266 status = apr_lock(start_mutex);
1267 if (status != APR_SUCCESS) {
1268 ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
1269 "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1270 signal_parent(0); /* tell parent to die */
1273 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1274 "Child %d: Acquired the start mutex.", my_pid);
1276 /* Create the worker thread pool */
1277 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1278 "Child %d: Starting %d worker threads.", my_pid, nthreads);
1279 child_handles = (thread *) alloca(nthreads * sizeof(int));
1280 for (i = 0; i < nthreads; i++) {
1281 child_handles[i] = (thread *) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1285 /* Begin accepting connections */
1286 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1287 /* Win95/98: Start the accept thread */
1288 _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) accept_and_queue_connections,
1289 (void *) i, 0, &tid);
1291 /* Windows NT/2000: Create AcceptEx completion contexts */
1295 /* Wait for one of three events:
1297 * The exit_event is signaled by the parent process to notify
1298 * the child that it is time to exit.
1300 * maintenance_event:
1301 * This event is signaled by the worker thread pool to direct
1302 * this thread to create more completion contexts.
1305 * To do periodic maintenance on the server (check for thread exits,
1306 * number of completion contexts, etc.)
1309 rv = WaitForMultipleObjects(2, (HANDLE *) child_events, FALSE, INFINITE);
1310 cld = rv - WAIT_OBJECT_0;
1311 if (rv == WAIT_FAILED) {
1312 /* Something serious is wrong */
1313 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1314 "Child %d: WAIT_FAILED -- shutting down server");
1317 else if (rv == WAIT_TIMEOUT) {
1318 /* Hey, this cannot happen */
1319 ap_log_error(APLOG_MARK, APLOG_CRIT, APR_SUCCESS, server_conf,
1320 "Child %d: WAIT_TIMEOUT -- shutting down server", my_pid);
1323 else if (cld == 0) {
1324 /* Exit event was signaled */
1325 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1326 "Child %d: Exit event signaled. Child process is ending.", my_pid);
1330 /* Child maintenance event signaled */
1331 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1334 ResetEvent(maintenance_event);
1335 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1336 "Child %d: Child maintenance event signaled.", my_pid);
1340 /* Setting is_graceful will close keep-alive connections */
1343 /* Shutdown the worker threads */
1344 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1345 /* workers_may_exit = 1; Not used on Win9x */
1346 shutdown_in_progress = 1;
1347 for (i = 0; i < nthreads; i++) {
1351 else { /* Windows NT/2000 */
1355 * Setting shutdown_in_progress prevents new AcceptEx completion
1356 * contexts from being queued to the port but allows threads to
1357 * continue consuming from the port. This gives the server a
1358 * chance to handle any accepted connections.
1360 shutdown_in_progress = 1;
1363 /* Setting workers_may_exit prevents threads from consumimg from the
1364 * completion port (especially threads that unblock off of keep-alive
1365 * connections later on).
1367 workers_may_exit = 1;
1369 /* Unblock threads blocked on the completion port */
1370 apr_lock(allowed_globals.jobmutex);
1371 while (g_blocked_threads > 0) {
1372 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1373 "Child %d: %d threads blocked on the completion port", my_pid, g_blocked_threads);
1374 for (i=g_blocked_threads; i > 0; i--) {
1375 PostQueuedCompletionStatus(AcceptExCompPort, 0, my_pid, NULL);
1379 apr_unlock(allowed_globals.jobmutex);
1381 /* Cancel any remaining pending AcceptEx completion contexts */
1382 for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1383 apr_get_os_sock(&nsd,lr->sd);
1384 CancelIo((HANDLE) nsd);
1387 /* Drain the canceled contexts off the port */
1388 drain_acceptex_complport(AcceptExCompPort, TRUE);
1391 /* Release the start_mutex to let the new process (in the restart
1392 * scenario) a chance to begin servicing requests
1394 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1395 "Child %d: Releasing the start mutex", my_pid);
1396 apr_unlock(start_mutex);
1398 /* Give busy worker threads a chance to service their connections.
1399 * Kill them off if they take too long
1401 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1402 "Child %d: Waiting for %d threads to die.", my_pid, nthreads);
1403 end_time = time(NULL) + 180;
1405 rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1406 if (rv != WAIT_TIMEOUT) {
1407 rv = rv - WAIT_OBJECT_0;
1408 ap_assert((rv >= 0) && (rv < nthreads));
1409 cleanup_thread(child_handles, &nthreads, rv);
1414 for (i = 0; i < nthreads; i++) {
1415 TerminateThread(child_handles[i], 1);
1416 CloseHandle(child_handles[i]);
1418 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1419 "Child %d: All worker threads have ended.", my_pid);
1421 CloseHandle(AcceptExCompPort);
1422 destroy_semaphore(allowed_globals.jobsemaphore);
1423 apr_destroy_lock(allowed_globals.jobmutex);
1425 apr_destroy_pool(pchild);
1426 CloseHandle(exit_event);
1430 * Spawn a child Apache process. The child process has the command line arguments from
1431 * argc and argv[], plus a -Z argument giving the name of an event. The child should
1432 * open and poll or wait on this event. When it is signalled, the child should die.
1433 * prefix is a prefix string for the event name.
1435 * The child_num argument on entry contains a serial number for this child (used to create
1436 * a unique event name). On exit, this number will have been incremented by one, ready
1437 * for the next call.
1439 * On exit, the value pointed to be *ev will contain the event created
1440 * to signal the new child process.
1442 * The return value is the handle to the child process if successful, else -1. If -1 is
1443 * returned the error will already have been logged by ap_log_error().
1446 /**********************************************************************
1447 * master_main - this is the parent (main) process. We create a
1448 * child process to do the work, then sit around waiting for either
1449 * the child to exit, or a restart or exit signal. If the child dies,
1450 * we just respawn a new one. If we have a shutdown or graceful restart,
1451 * tell the child to die when it is ready. If it is a non-graceful
1452 * restart, force the child to die immediately.
1453 **********************************************************************/
1455 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1457 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1462 CloseHandle(handles[position]);
1463 CloseHandle(events[position]);
1465 handle = (int)handles[position];
1467 for (i = position; i < (*processes)-1; i++) {
1468 handles[i] = handles[i + 1];
1469 events[i] = events[i + 1];
1474 static int create_process(apr_pool_t *p, HANDLE *handles, HANDLE *events, int *processes)
1483 STARTUPINFO si; /* Filled in prior to call to CreateProcess */
1484 PROCESS_INFORMATION pi; /* filled in on call to CreateProcess */
1488 HANDLE hPipeRead = NULL;
1489 HANDLE hPipeWrite = NULL;
1490 SECURITY_ATTRIBUTES sa = {0};
1493 LPWSAPROTOCOL_INFO lpWSAProtocolInfo;
1494 HANDLE hDupedCompPort;
1496 sa.nLength = sizeof(sa);
1497 sa.bInheritHandle = TRUE;
1498 sa.lpSecurityDescriptor = NULL;
1500 /* Build the command line. Should look something like this:
1501 * C:/apache/bin/apache.exe -f ap_server_confname
1502 * First, get the path to the executable...
1504 rv = GetModuleFileName(NULL, buf, sizeof(buf));
1505 if (rv == sizeof(buf)) {
1506 ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1507 "Parent: Path to Apache process too long");
1509 } else if (rv == 0) {
1510 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1511 "Parent: GetModuleFileName() returned NULL for current process.");
1515 /* Build the command line */
1516 pCommand = apr_psprintf(p, "\"%s\"", buf);
1517 for (i = 1; i < server_conf->process->argc; i++) {
1518 pCommand = apr_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1521 /* Build the environment, since Win9x disrespects the active env */
1522 pEnvVar = apr_psprintf(p, "AP_PARENT_PID=%i", parent_pid);
1524 * Win32's CreateProcess call requires that the environment
1525 * be passed in an environment block, a null terminated block of
1526 * null terminated strings.
1530 while (_environ[i]) {
1531 iEnvBlockLen += strlen(_environ[i]) + 1;
1535 pEnvBlock = (char *)apr_pcalloc(p, iEnvBlockLen + strlen(pEnvVar) + 1);
1536 strcpy(pEnvBlock, pEnvVar);
1537 pEnvVar = strchr(pEnvBlock, '\0') + 1;
1540 while (_environ[i]) {
1541 strcpy(pEnvVar, _environ[i]);
1542 pEnvVar = strchr(pEnvVar, '\0') + 1;
1546 /* Create a pipe to send socket info to the child */
1547 if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1548 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1549 "Parent: Unable to create pipe to child process.");
1553 /* Give the read end of the pipe (hPipeRead) to the child as stdin. The
1554 * parent will write the socket data to the child on this pipe.
1556 memset(&si, 0, sizeof(si));
1557 memset(&pi, 0, sizeof(pi));
1559 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1560 si.wShowWindow = SW_HIDE;
1561 si.hStdInput = hPipeRead;
1563 if (!CreateProcess(NULL, pCommand, NULL, NULL,
1564 TRUE, /* Inherit handles */
1565 CREATE_SUSPENDED, /* Creation flags */
1566 pEnvBlock, /* Environment block */
1569 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1570 "Parent: Not able to create the child process.");
1572 * We must close the handles to the new process and its main thread
1573 * to prevent handle and memory leaks.
1575 CloseHandle(pi.hProcess);
1576 CloseHandle(pi.hThread);
1580 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1581 "Parent: Created child process %d", pi.dwProcessId);
1583 SetEnvironmentVariable("AP_PARENT_PID",NULL);
1585 /* Create the exit_event, apCchild_pid */
1586 sa.nLength = sizeof(sa);
1587 sa.bInheritHandle = TRUE;
1588 sa.lpSecurityDescriptor = NULL;
1589 kill_event = CreateEvent(&sa, TRUE, FALSE, apr_psprintf(pconf,"apC%d", pi.dwProcessId));
1591 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1592 "Parent: Could not create exit event for child process");
1593 CloseHandle(pi.hProcess);
1594 CloseHandle(pi.hThread);
1598 /* Assume the child process lives. Update the process and event tables */
1599 handles[*processes] = pi.hProcess;
1600 events[*processes] = kill_event;
1603 /* We never store the thread's handle, so close it now. */
1604 ResumeThread(pi.hThread);
1605 CloseHandle(pi.hThread);
1607 /* Run the chain of open sockets. For each socket, duplicate it
1608 * for the target process then send the WSAPROTOCOL_INFO
1609 * (returned by dup socket) to the child */
1610 for (lr = ap_listeners; lr; lr = lr->next) {
1612 lpWSAProtocolInfo = apr_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1613 apr_get_os_sock(&nsd,lr->sd);
1614 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1615 "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1616 if (WSADuplicateSocket(nsd, pi.dwProcessId,
1617 lpWSAProtocolInfo) == SOCKET_ERROR) {
1618 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, server_conf,
1619 "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1623 if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1625 (LPOVERLAPPED) NULL)) {
1626 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1627 "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1630 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1631 "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1633 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1634 /* Now, send the AcceptEx completion port to the child */
1635 if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort,
1636 pi.hProcess, &hDupedCompPort, 0,
1637 TRUE, DUPLICATE_SAME_ACCESS)) {
1638 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1639 "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1643 WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1646 CloseHandle(hPipeRead);
1647 CloseHandle(hPipeWrite);
1652 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1654 int remaining_children_to_start = ap_daemons_to_start;
1658 int restart_pending = 0;
1659 int shutdown_pending = 0;
1660 int current_live_processes = 0; /* number of child process we know about */
1662 HANDLE process_handles[MAX_PROCESSES];
1663 HANDLE process_kill_events[MAX_PROCESSES];
1666 bind_listeners_to_completion_port();
1668 /* Create child process
1669 * Should only be one in this version of Apache for WIN32
1671 while (remaining_children_to_start--) {
1672 if (create_process(pconf, process_handles, process_kill_events,
1673 ¤t_live_processes) < 0) {
1674 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1675 "master_main: create child process failed. Exiting.");
1676 shutdown_pending = 1;
1681 restart_pending = shutdown_pending = 0;
1683 if (!strcasecmp(signal_arg, "runservice"))
1684 mpm_service_started();
1686 /* Wait for shutdown or restart events or for child death */
1687 process_handles[current_live_processes] = shutdown_event;
1688 process_handles[current_live_processes+1] = restart_event;
1690 rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles,
1692 cld = rv - WAIT_OBJECT_0;
1693 if (rv == WAIT_FAILED) {
1694 /* Something serious is wrong */
1695 ap_log_error(APLOG_MARK,APLOG_CRIT, apr_get_os_error(), server_conf,
1696 "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1697 shutdown_pending = 1;
1699 else if (rv == WAIT_TIMEOUT) {
1700 /* Hey, this cannot happen */
1701 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1702 "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1703 shutdown_pending = 1;
1705 else if (cld == current_live_processes) {
1706 /* shutdown_event signalled */
1707 shutdown_pending = 1;
1708 printf("shutdown event signaled\n");
1709 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1710 "master_main: Shutdown event signaled -- doing server shutdown.");
1711 if (ResetEvent(shutdown_event) == 0) {
1712 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1713 "ResetEvent(shutdown_event)");
1717 else if (cld == current_live_processes+1) {
1718 /* restart_event signalled */
1719 int children_to_kill = current_live_processes;
1720 restart_pending = 1;
1721 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, s,
1722 "master_main: Restart event signaled. Doing a graceful restart.");
1723 if (ResetEvent(restart_event) == 0) {
1724 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1725 "master_main: ResetEvent(restart_event) failed.");
1727 /* Signal each child process to die
1728 * We are making a big assumption here that the child process, once signaled,
1729 * will REALLY go away. Since this is a restart, we do not want to hold the
1730 * new child process up waiting for the old child to die. Remove the old
1731 * child out of the process_handles apr_table_t and hope for the best...
1733 for (i = 0; i < children_to_kill; i++) {
1734 if (SetEvent(process_kill_events[i]) == 0)
1735 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1736 "master_main: SetEvent for child process in slot #%d failed", i);
1737 cleanup_process(process_handles, process_kill_events, i, ¤t_live_processes);
1741 /* A child process must have exited because of a fatal error condition (seg fault, etc.).
1742 * Remove the dead process
1743 * from the process_handles and process_kill_events apr_table_t and create a new
1745 * TODO: Consider restarting the child immediately without looping through http_main
1746 * and without rereading the configuration. Will need this if we ever support multiple
1747 * children. One option, create a parent thread which waits on child death and restarts it.
1748 * Consider, however, that if the user makes httpd.conf invalid, we want to die before
1749 * our child tries it... otherwise we have a nasty loop.
1751 restart_pending = 1;
1752 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1753 "master_main: Child process failed. Restarting the child process.");
1754 ap_assert(cld < current_live_processes);
1755 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1756 /* APD2("main_process: child in slot %d died", rv); */
1757 /* restart_child(process_hancles, process_kill_events, cld, ¤t_live_processes); */
1759 /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead
1761 drain_acceptex_complport(AcceptExCompPort, FALSE);
1765 if (shutdown_pending)
1767 int tmstart = time(NULL);
1769 if (strcasecmp(signal_arg, "runservice")) {
1770 mpm_service_stopping();
1772 /* Signal each child processes to die */
1773 for (i = 0; i < current_live_processes; i++) {
1774 printf("SetEvent handle = %d\n", process_kill_events[i]);
1775 if (SetEvent(process_kill_events[i]) == 0)
1776 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
1777 "master_main: SetEvent for child process in slot #%d failed", i);
1780 while (current_live_processes && ((tmstart+60) > time(NULL))) {
1781 rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1782 if (rv == WAIT_TIMEOUT)
1784 ap_assert(rv != WAIT_FAILED);
1785 cld = rv - WAIT_OBJECT_0;
1786 ap_assert(rv < current_live_processes);
1787 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1789 for (i = 0; i < current_live_processes; i++) {
1790 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1791 "forcing termination of child #%d (handle %d)", i, process_handles[i]);
1792 TerminateProcess((HANDLE) process_handles[i], 1);
1794 return 0; /* Tell the caller we do not want to restart */
1797 return 1; /* Tell the caller we want a restart */
1801 #define SERVICE_UNNAMED -1
1803 /* service_nt_main_fn needs to append the StartService() args
1804 * outside of our call stack and thread as the service starts...
1806 apr_array_header_t *mpm_new_argv;
1808 /* Remember service_to_start failures to log and fail in pre_config.
1809 * Remember inst_argc and inst_argv for installing or starting the
1810 * service after we preflight the config.
1813 static apr_status_t service_to_start_success;
1814 static int inst_argc;
1815 static char **inst_argv;
1817 void winnt_rewrite_args(process_rec *process)
1819 /* Handle the following SCM aspects in this phase:
1821 * -k runservice [transition for WinNT, nothing for Win9x]
1822 * -k (!)install [error out if name is not installed]
1824 * We can't leave this phase until we know our identity
1825 * and modify the command arguments appropriately.
1827 apr_status_t service_named = SERVICE_UNNAMED;
1829 char *def_server_root;
1830 char fnbuf[MAX_PATH];
1833 const char **new_arg;
1838 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1839 GetVersionEx(&osver);
1841 /* AP_PARENT_PID is only valid in the child */
1842 pid = getenv("AP_PARENT_PID");
1845 /* This is the child */
1846 parent_pid = (DWORD) atol(pid);
1847 my_pid = GetCurrentProcessId();
1849 /* The parent is responsible for providing the
1850 * COMPLETE ARGUMENTS REQUIRED to the child.
1852 * No further argument parsing is needed, but
1853 * for good measure we will provide a simple
1854 * signal string for later testing.
1856 signal_arg = "runchild";
1860 /* This is the parent, we have a long way to go :-) */
1861 parent_pid = my_pid = GetCurrentProcessId();
1863 /* Rewrite process->argv[];
1865 * strip out -k signal into signal_arg
1866 * strip out -n servicename into service_name & display_name
1867 * add default -d serverroot from the path of this executable
1869 * The end result will look like:
1871 * The invocation command (%0)
1872 * The -d serverroot default from the running executable
1873 * The requested service's (-n) registry ConfigArgs
1874 * The WinNT SCM's StartService() args
1877 if (!GetModuleFileName(NULL, fnbuf, sizeof(fnbuf))) {
1878 /* WARNING: There is an implict assumption here that the
1879 * executable resides in the ServerRoot!
1881 rv = apr_get_os_error();
1882 ap_log_error(APLOG_MARK,APLOG_ERR, rv, NULL,
1883 "Failed to get the running module's file name");
1886 def_server_root = (char *) apr_filename_of_pathname(fnbuf);
1887 if (def_server_root > fnbuf) {
1888 *(def_server_root - 1) = '\0';
1889 def_server_root = ap_os_canonical_filename(process->pool, fnbuf);
1892 /* Use process->pool so that the rewritten argv
1893 * lasts for the lifetime of the server process,
1894 * because pconf will be destroyed after the
1895 * initial pre-flight of the config parser.
1898 mpm_new_argv = apr_make_array(process->pool, process->argc + 2, sizeof(char *));
1899 new_arg = (char**) apr_push_array(mpm_new_argv);
1900 *new_arg = (char *) process->argv[0];
1902 new_arg = (char**) apr_push_array(mpm_new_argv);
1904 new_arg = (char**) apr_push_array(mpm_new_argv);
1905 *new_arg = def_server_root;
1907 fixed_args = mpm_new_argv->nelts;
1909 optbuf[0] = '-'; optbuf[2] = '\0';
1910 apr_initopt(&opt, process->pool, process->argc, (char**) process->argv);
1911 while (apr_getopt(opt, "n:k:iu" AP_SERVER_BASEARGS,
1912 optbuf + 1, &optarg) == APR_SUCCESS) {
1913 switch (optbuf[1]) {
1915 service_named = mpm_service_set_name(process->pool, optarg);
1918 signal_arg = optarg;
1921 /* TODO: warn of depreciated syntax, "use -k install instead" */
1922 signal_arg = "install";
1925 /* TODO: warn of depreciated syntax, "use -k uninstall instead" */
1926 signal_arg = "uninstall";
1932 new_arg = (char**) apr_push_array(mpm_new_argv);
1933 *new_arg = apr_pstrdup(process->pool, optbuf);
1935 new_arg = (char**) apr_push_array(mpm_new_argv);
1942 /* Track the number of args actually entered by the user */
1943 inst_argc = mpm_new_argv->nelts - fixed_args;
1945 /* Provide a default 'run' -k arg to simplify signal_arg tests */
1949 if (!strcasecmp(signal_arg, "runservice"))
1951 /* Start the NT Service _NOW_ because the WinNT SCM is
1952 * expecting us to rapidly assume control of our own
1953 * process, the SCM will tell us our service name, and
1954 * may have extra StartService() command arguments to
1957 * Any other process has a console, so we don't to begin
1958 * a Win9x service until the configuration is parsed and
1959 * any command line errors are reported.
1961 * We hold the return value so that we can die in pre_config
1962 * after logging begins, and the failure can land in the log.
1964 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) {
1965 service_to_start_success = mpm_service_to_start();
1966 if (service_to_start_success == APR_SUCCESS)
1967 service_named = APR_SUCCESS;
1971 if (service_named == SERVICE_UNNAMED) {
1972 service_named = mpm_service_set_name(process->pool,
1973 DEFAULT_SERVICE_NAME);
1976 if (!strcasecmp(signal_arg, "install")) /* -k install */
1978 if (service_named == APR_SUCCESS)
1980 ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
1981 "%s: Service is already installed.", display_name);
1987 if (service_named == APR_SUCCESS)
1989 rv = mpm_merge_service_args(process->pool, mpm_new_argv,
1991 if (rv != APR_SUCCESS) {
1992 ap_log_error(APLOG_MARK,APLOG_ERR, rv, NULL,
1993 "%s: ConfigArgs are missing from the registry.",
1999 ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
2000 "%s: No installed service by that name.", display_name);
2005 /* Track the args actually entered by the user.
2006 * These will be used for the -k install parameters, as well as
2007 * for the -k start service override arguments.
2009 inst_argv = (char**) mpm_new_argv->elts + mpm_new_argv->nelts - inst_argc;
2011 process->argc = mpm_new_argv->nelts;
2012 process->argv = (char**) mpm_new_argv->elts;
2016 static void winnt_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
2018 /* Handle the following SCM aspects in this phase:
2020 * -k runservice [WinNT errors logged from rewrite_args]
2024 * in these cases we -don't- care if httpd.conf has config errors!
2028 if (getenv("ONE_PROCESS"))
2031 if (ap_exists_config_define("ONE_PROCESS"))
2034 if (!strcasecmp(signal_arg, "runservice")
2035 && (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
2036 && (service_to_start_success != APR_SUCCESS)) {
2037 ap_log_error(APLOG_MARK,APLOG_ERR, service_to_start_success, NULL,
2038 "%s: Unable to start the service manager.",
2043 if (!strcasecmp(signal_arg, "uninstall")) {
2044 rv = mpm_service_uninstall();
2048 if (!strcasecmp(signal_arg, "stop")) {
2049 mpm_signal_service(ptemp, 0);
2053 ap_listen_pre_config();
2054 ap_daemons_to_start = DEFAULT_NUM_DAEMON;
2055 ap_threads_per_child = DEFAULT_START_THREAD;
2056 ap_pid_fname = DEFAULT_PIDLOG;
2057 max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
2059 apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
2062 static void winnt_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec* server)
2064 static int restart_num = 0;
2065 apr_status_t rv = 0;
2067 server_conf = server;
2069 /* Handle the following SCM aspects in this phase:
2074 * -k runservice [Win95, only once - after we parsed the config]
2076 * because all of these signals are useful _only_ if there
2077 * is a valid conf\httpd.conf environment to start.
2079 * We reached this phase by avoiding errors that would cause
2080 * these options to fail unexpectedly in another process.
2083 if (!strcasecmp(signal_arg, "install")) {
2084 rv = mpm_service_install(ptemp, inst_argc, inst_argv);
2088 if (!strcasecmp(signal_arg, "start")) {
2089 rv = mpm_service_start(ptemp, inst_argc, inst_argv);
2093 if (!strcasecmp(signal_arg, "restart")) {
2094 mpm_signal_service(ptemp, 1);
2098 if (parent_pid == my_pid)
2100 if (restart_num++ == 1)
2102 /* This code should be run once in the parent and not run
2105 PSECURITY_ATTRIBUTES sa = GetNullACL(); /* returns NULL if invalid (Win95?) */
2106 setup_signal_names(apr_psprintf(pconf,"ap%d", parent_pid));
2107 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
2108 /* Create the AcceptEx IoCompletionPort once in the parent.
2109 * The completion port persists across restarts.
2111 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
2114 0); /* CONCURRENT ACTIVE THREADS */
2115 if (AcceptExCompPort == NULL) {
2116 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
2117 "Parent: Unable to create the AcceptExCompletionPort -- process will exit");
2122 ap_log_pid(pconf, ap_pid_fname);
2124 /* Create shutdown event, apPID_shutdown, where PID is the parent
2125 * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
2127 shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
2128 if (!shutdown_event) {
2129 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
2130 "Parent: Cannot create shutdown event %s", signal_shutdown_name);
2131 CleanNullACL((void *)sa);
2135 /* Create restart event, apPID_restart, where PID is the parent
2136 * Apache process ID. Restart is signaled by 'apache -k restart'.
2138 restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
2139 if (!restart_event) {
2140 CloseHandle(shutdown_event);
2141 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
2142 "Parent: Cannot create restart event %s", signal_restart_name);
2143 CleanNullACL((void *)sa);
2146 CleanNullACL((void *)sa);
2148 /* Now that we are flying at 15000 feet...
2149 * wipe out the Win95 service console,
2150 * signal the SCM the WinNT service started, or
2151 * if not a service, setup console handlers instead.
2153 if (!strcasecmp(signal_arg, "runservice"))
2155 if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT)
2157 rv = mpm_service_to_start();
2158 if (rv != APR_SUCCESS) {
2159 ap_log_error(APLOG_MARK,APLOG_ERR, rv, server_conf,
2160 "%s: Unable to start the service manager.",
2166 else /* ! -k runservice */
2168 mpm_start_console_handler();
2171 /* Create the start mutex, apPID, where PID is the parent Apache process ID.
2172 * Ths start mutex is used during a restart to prevent more than one
2173 * child process from entering the accept loop at once.
2175 apr_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS, signal_name_prefix,
2176 server_conf->process->pool);
2179 else /* parent_pid != my_pid */
2181 mpm_start_child_console_handler();
2185 API_EXPORT(int) ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s )
2187 static int restart = 0; /* Default is "not a restart" */
2192 if ((parent_pid != my_pid) || one_process) {
2193 /* Running as Child process or in one_process (debug) mode */
2194 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
2195 "Child %d: Child process is running", my_pid);
2197 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
2198 "Child %d: Child process is exiting", my_pid);
2201 } /* Child or single process */
2202 else { /* Parent process */
2203 restart = master_main(server_conf, shutdown_event, restart_event);
2206 /* Shutting down. Clean up... */
2207 const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
2209 if (pidfile != NULL && unlink(pidfile) == 0) {
2210 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS,
2211 server_conf, "removed PID file %s (pid=%ld)",
2212 pidfile, GetCurrentProcessId());
2214 apr_destroy_lock(start_mutex);
2216 CloseHandle(restart_event);
2217 CloseHandle(shutdown_event);
2221 } /* Parent process */
2223 return 0; /* Restart */
2226 static void winnt_hooks(void)
2228 ap_hook_pre_config(winnt_pre_config, NULL, NULL, AP_HOOK_MIDDLE);
2229 ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
2233 * Command processors
2235 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg)
2237 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2242 if (cmd->server->is_virtual) {
2243 return "PidFile directive not allowed in <VirtualHost>";
2249 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg)
2251 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2256 ap_threads_per_child = atoi(arg);
2257 if (ap_threads_per_child > HARD_THREAD_LIMIT) {
2258 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2259 "WARNING: ThreadsPerChild of %d exceeds compile time"
2260 " limit of %d threads,", ap_threads_per_child,
2262 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2263 " lowering ThreadsPerChild to %d. To increase, please"
2264 " see the HARD_THREAD_LIMIT define in %s.",
2265 HARD_THREAD_LIMIT, AP_MPM_HARD_LIMITS_FILE);
2266 ap_threads_per_child = HARD_THREAD_LIMIT;
2268 else if (ap_threads_per_child < 1) {
2269 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2270 "WARNING: Require ThreadsPerChild > 0, setting to 1");
2271 ap_threads_per_child = 1;
2277 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg)
2279 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2284 max_requests_per_child = atoi(arg);
2289 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg)
2293 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2298 fname = ap_server_root_relative(cmd->pool, arg);
2299 if ((apr_stat(&finfo, fname, cmd->pool) != APR_SUCCESS) ||
2300 (finfo.filetype != APR_DIR)) {
2301 return apr_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
2302 " does not exist or is not a directory", NULL);
2304 apr_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
2308 /* Stub functions until this MPM supports the connection status API */
2310 API_EXPORT(void) ap_update_connection_status(long conn_id, const char *key, \
2316 API_EXPORT(void) ap_reset_connection_status(long conn_id)
2321 API_EXPORT(apr_array_header_t *) ap_get_status_table(apr_pool_t *p)
2327 static const command_rec winnt_cmds[] = {
2329 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
2330 "A file for logging the server process ID"},
2331 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
2332 "Number of threads each child creates" },
2333 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
2334 "Maximum number of requests a particular child serves before dying." },
2335 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
2336 "The location of the directory Apache changes to before dumping core" },
2340 MODULE_VAR_EXPORT module mpm_winnt_module = {
2342 winnt_rewrite_args, /* hook to run before apache parses args */
2343 NULL, /* create per-directory config structure */
2344 NULL, /* merge per-directory config structures */
2345 NULL, /* create per-server config structure */
2346 NULL, /* merge per-server config structures */
2347 winnt_cmds, /* command apr_table_t */
2348 NULL, /* handlers */
2349 winnt_hooks /* register_hooks */