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"
76 typedef HANDLE thread;
79 * Definitions of WINNT MPM specific config globals
81 static int workers_may_exit = 0;
82 static int shutdown_in_progress = 0;
83 static unsigned int g_blocked_threads = 0;
85 static char *ap_pid_fname = NULL;
86 static int ap_threads_per_child = 0;
88 static int max_requests_per_child = 0;
89 static HANDLE shutdown_event; /* used to signal shutdown to parent */
90 static HANDLE restart_event; /* used to signal a restart to parent */
92 #define MAX_SIGNAL_NAME 30 /* Long enough for apPID_shutdown, where PID is an int */
93 char signal_name_prefix[MAX_SIGNAL_NAME];
94 char signal_restart_name[MAX_SIGNAL_NAME];
95 char signal_shutdown_name[MAX_SIGNAL_NAME];
97 static struct fd_set listenfds;
98 static int num_listenfds = 0;
99 static SOCKET listenmaxfd = INVALID_SOCKET;
101 static apr_pool_t *pconf; /* Pool for config stuff */
103 static char ap_coredump_dir[MAX_STRING_LEN];
105 static server_rec *server_conf;
106 static HANDLE AcceptExCompPort = NULL;
108 static int one_process = 0;
109 static char const* signal_arg;
111 OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
113 int ap_max_requests_per_child=0;
114 int ap_daemons_to_start=0;
116 static HANDLE exit_event;
117 static HANDLE maintenance_event;
118 apr_lock_t *start_mutex;
122 /* This is the helper code to resolve late bound entry points
123 * missing from one or more releases of the Win32 API...
124 * but it sure would be nice if we didn't duplicate this code
128 static const char* const lateDllName[DLL_defined] = {
129 "kernel32", "advapi32", "mswsock", "ws2_32" };
130 static HMODULE lateDllHandle[DLL_defined] = {
131 NULL, NULL, NULL, NULL };
133 FARPROC ap_load_dll_func(ap_dlltoken_e fnLib, char* fnName, int ordinal)
135 if (!lateDllHandle[fnLib]) {
136 lateDllHandle[fnLib] = LoadLibrary(lateDllName[fnLib]);
137 if (!lateDllHandle[fnLib])
141 return GetProcAddress(lateDllHandle[fnLib], (char *) ordinal);
143 return GetProcAddress(lateDllHandle[fnLib], fnName);
146 static apr_status_t socket_cleanup(void *sock)
148 apr_socket_t *thesocket = sock;
150 if (apr_get_os_sock(&sd, thesocket) == APR_SUCCESS) {
156 /* A bunch or routines from os/win32/multithread.c that need to be merged into APR
157 * or thrown out entirely...
160 static HANDLE create_semaphore(int initial)
162 return(CreateSemaphore(NULL, initial, 1000000, NULL));
165 static void acquire_semaphore(HANDLE semaphore_id)
169 rv = WaitForSingleObject(semaphore_id, INFINITE);
174 static int release_semaphore(HANDLE semaphore_id)
176 return(ReleaseSemaphore(semaphore_id, 1, NULL));
179 static void destroy_semaphore(HANDLE semaphore_id)
181 CloseHandle(semaphore_id);
185 /* To share the semaphores with other processes, we need a NULL ACL
186 * Code from MS KB Q106387
188 static PSECURITY_ATTRIBUTES GetNullACL()
190 PSECURITY_DESCRIPTOR pSD;
191 PSECURITY_ATTRIBUTES sa;
193 sa = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES));
194 pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,
195 SECURITY_DESCRIPTOR_MIN_LENGTH);
196 if (pSD == NULL || sa == NULL) {
200 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
201 || apr_get_os_error()) {
206 if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
207 || apr_get_os_error()) {
212 sa->nLength = sizeof(sa);
213 sa->lpSecurityDescriptor = pSD;
214 sa->bInheritHandle = TRUE;
218 static void CleanNullACL( void *sa ) {
220 LocalFree( ((PSECURITY_ATTRIBUTES)sa)->lpSecurityDescriptor);
226 * The Win32 call WaitForMultipleObjects will only allow you to wait for
227 * a maximum of MAXIMUM_WAIT_OBJECTS (current 64). Since the threading
228 * model in the multithreaded version of apache wants to use this call,
229 * we are restricted to a maximum of 64 threads. This is a simplistic
230 * routine that will increase this size.
232 static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles,
236 DWORD dwRet = WAIT_TIMEOUT;
240 tStopTime = time(NULL) + dwSeconds;
248 for (dwIndex = 0; dwIndex * MAXIMUM_WAIT_OBJECTS < nCount; dwIndex++) {
249 dwRet = WaitForMultipleObjects(
250 min(MAXIMUM_WAIT_OBJECTS, nCount - (dwIndex * MAXIMUM_WAIT_OBJECTS)),
251 lpHandles + (dwIndex * MAXIMUM_WAIT_OBJECTS),
254 if (dwRet != WAIT_TIMEOUT) {
258 } while((time(NULL) < tStopTime) && (dwRet == WAIT_TIMEOUT));
264 * Signalling Apache on NT.
266 * Under Unix, Apache can be told to shutdown or restart by sending various
267 * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
268 * we use "events" instead. The parent apache process goes into a loop
269 * where it waits forever for a set of events. Two of those events are
275 * (where PID is the PID of the apache parent process). When one of these
276 * is signalled, the Apache parent performs the appropriate action. The events
277 * can become signalled through internal Apache methods (e.g. if the child
278 * finds a fatal error and needs to kill its parent), via the service
279 * control manager (the control thread will signal the shutdown event when
280 * requested to stop the Apache service), from the -k Apache command line,
281 * or from any external program which finds the Apache PID from the
284 * The signal_parent() function, below, is used to signal one of these events.
285 * It can be called by any child or parent process, since it does not
286 * rely on global variables.
288 * On entry, type gives the event to signal. 0 means shutdown, 1 means
291 void signal_parent(int type)
296 /* after updating the shutdown_pending or restart flags, we need
297 * to wake up the parent process so it can see the changes. The
298 * parent will normally be waiting for either a child process
299 * to die, or for a signal on the "spache-signal" event. So set the
300 * "apache-signal" event here.
307 case 0: signal_name = signal_shutdown_name; break;
308 case 1: signal_name = signal_restart_name; break;
311 e = OpenEvent(EVENT_ALL_ACCESS, FALSE, signal_name);
313 /* Um, problem, can't signal the parent, which means we can't
314 * signal ourselves to die. Ignore for now...
316 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
317 "OpenEvent on %s event", signal_name);
320 if (SetEvent(e) == 0) {
321 /* Same problem as above */
322 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
323 "SetEvent on %s event", signal_name);
330 static int volatile is_graceful = 0;
332 AP_DECLARE(int) ap_graceful_stop_signalled(void)
337 AP_DECLARE(void) ap_start_shutdown(void)
342 AP_DECLARE(void) ap_start_restart(int gracefully)
344 is_graceful = gracefully;
349 * Initialise the signal names, in the global variables signal_name_prefix,
350 * signal_restart_name and signal_shutdown_name.
353 void setup_signal_names(char *prefix)
355 apr_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);
356 apr_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name),
357 "%s_shutdown", signal_name_prefix);
358 apr_snprintf(signal_restart_name, sizeof(signal_restart_name),
359 "%s_restart", signal_name_prefix);
363 * Routines that deal with sockets, some are WIN32 specific...
366 static void sock_disable_nagle(int s)
368 /* The Nagle algorithm says that we should delay sending partial
369 * packets in hopes of getting more data. We don't want to do
370 * this; we are not telnet. There are bad interactions between
371 * persistent connections and Nagle's algorithm that have very severe
372 * performance penalties. (Failing to disable Nagle is not much of a
373 * problem with simple HTTP.)
375 * In spite of these problems, failure here is not a shooting offense.
379 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
381 ap_log_error(APLOG_MARK, APLOG_WARNING, APR_SUCCESS, server_conf,
382 "setsockopt: (TCP_NODELAY)");
387 * Routines to deal with managing the list of listening sockets.
389 static ap_listen_rec *head_listener;
391 static apr_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
396 for (lr = head_listener; lr ; lr = lr->next) {
397 apr_get_os_sock(&nsd, lr->sd);
398 if (FD_ISSET(nsd, main_fds)) {
399 head_listener = lr->next;
400 if (head_listener == NULL)
401 head_listener = ap_listeners;
409 static int setup_listeners(server_rec *s)
412 int num_listeners = 0;
415 /* Setup the listeners */
418 if (ap_listen_open(s->process, s->port)) {
421 for (lr = ap_listeners; lr; lr = lr->next) {
423 if (lr->sd != NULL) {
424 apr_get_os_sock(&nsd, lr->sd);
425 FD_SET(nsd, &listenfds);
426 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
433 head_listener = ap_listeners;
435 return num_listeners;
438 static int setup_inherited_listeners(server_rec *s)
440 WSAPROTOCOL_INFO WSAProtocolInfo;
444 int num_listeners = 0;
447 /* Setup the listeners */
450 /* Set up a default listener if necessary */
452 if (ap_listeners == NULL) {
454 lr = apr_palloc(s->process->pool, sizeof(ap_listen_rec));
458 lr->next = ap_listeners;
462 /* Open the pipe to the parent process to receive the inherited socket
463 * data. The sockets have been set to listening in the parent process.
465 pipe = GetStdHandle(STD_INPUT_HANDLE);
466 for (lr = ap_listeners; lr; lr = lr->next) {
467 if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
468 &BytesRead, (LPOVERLAPPED) NULL)) {
469 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
470 "setup_inherited_listeners: Unable to read socket data from parent");
471 signal_parent(0); /* tell parent to die */
474 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
475 "Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.", my_pid);
476 nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
477 &WSAProtocolInfo, 0, 0);
478 if (nsd == INVALID_SOCKET) {
479 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), server_conf,
480 "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
481 signal_parent(0); /* tell parent to die */
485 FD_SET(nsd, &listenfds);
486 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
490 apr_put_os_sock(&lr->sd, &nsd, pconf);
493 /* Now, read the AcceptExCompPort from the parent */
494 ReadFile(pipe, &AcceptExCompPort, sizeof(AcceptExCompPort), &BytesRead, (LPOVERLAPPED) NULL);
497 for (lr = ap_listeners; lr; lr = lr->next) {
501 head_listener = ap_listeners;
502 return num_listeners;
505 static void bind_listeners_to_completion_port()
507 /* Associate the open listeners with the completion port.
508 * Bypass the operation for Windows 95/98
512 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
513 for (lr = ap_listeners; lr; lr = lr->next) {
515 apr_get_os_sock(&nsd,lr->sd);
516 CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
521 /**********************************************************************
522 * Multithreaded implementation
524 * This code is fairly specific to Win32.
526 * The model used to handle requests is a set of threads. One "main"
527 * thread listens for new requests. When something becomes
528 * available, it does a select and places the newly available socket
529 * onto a list of "jobs" (add_job()). Then any one of a fixed number
530 * of "worker" threads takes the top job off the job list with
531 * remove_job() and handles that connection to completion. After
532 * the connection has finished the thread is free to take another
533 * job from the job list.
535 * In the code, the "main" thread is running within the child_main()
536 * function. The first thing this function does is create the
537 * worker threads, which operate in the child_sub_main() function. The
538 * main thread then goes into a loop within child_main() where they
539 * do a select() on the listening sockets. The select times out once
540 * per second so that the thread can check for an "exit" signal
541 * from the parent process (see below). If this signal is set, the
542 * thread can exit, but only after it has accepted all incoming
543 * connections already in the listen queue (since Win32 appears
544 * to through away listened but unaccepted connections when a
547 * Because the main and worker threads exist within a single process
548 * they are vulnerable to crashes or memory leaks (crashes can also
549 * be caused within modules, of course). There also needs to be a
550 * mechanism to perform restarts and shutdowns. This is done by
551 * creating the main & worker threads within a subprocess. A
552 * main process (the "parent process") creates one (or more)
553 * processes to do the work, then the parent sits around waiting
554 * for the working process to die, in which case it starts a new
555 * one. The parent process also handles restarts (by creating
556 * a new working process then signalling the previous working process
557 * exit ) and shutdowns (by signalling the working process to exit).
558 * The parent process operates within the master_main() function. This
559 * process also handles requests from the service manager (NT only).
561 * Signalling between the parent and working process uses a Win32
562 * event. Each child has a unique name for the event, which is
563 * passed to it with the -Z argument when the child is spawned. The
564 * parent sets (signals) this event to tell the child to die.
565 * At present all children do a graceful die - they finish all
566 * current jobs _and_ empty the listen queue before they exit.
567 * A non-graceful die would need a second event. The -Z argument in
568 * the child is also used to create the shutdown and restart events,
569 * since the prefix (apPID) contains the parent process PID.
571 * The code below starts with functions at the lowest level -
572 * worker threads, and works up to the top level - the main()
573 * function of the parent process.
575 * The scoreboard (in process memory) contains details of the worker
576 * threads (within the active working process). There is no shared
577 * "scoreboard" between processes, since only one is ever active
578 * at once (or at most, two, when one has been told to shutdown but
579 * is processes outstanding requests, and a new one has been started).
580 * This is controlled by a "start_mutex" which ensures only one working
581 * process is active at once.
582 **********************************************************************/
586 * Definition of jobs, shared by main and worker threads.
589 typedef struct joblist_s {
590 struct joblist_s *next;
595 * Globals common to main and worker threads. This structure is not
596 * used by the parent process.
599 typedef struct globals_s {
603 apr_lock_t *jobmutex;
608 globals allowed_globals =
609 {NULL, NULL, NULL, NULL, 0};
610 #define MAX_SELECT_ERRORS 100
611 #define PADDED_ADDR_SIZE sizeof(SOCKADDR_IN)+16
613 /* Windows 9x specific code...
614 * Accept processing for on Windows 95/98 uses a producer/consumer queue
615 * model. A single thread accepts connections and queues the accepted socket
616 * to the accept queue for consumption by a pool of worker threads.
618 * win9x_get_connection()
619 * Calls remove_job() to pull a job from the accept queue. All the worker
620 * threads block on remove_job.
621 * accept_and_queue_connections()
622 * The accept threads runs this function, which accepts connections off
623 * the network and calls add_job() to queue jobs to the accept_queue.
624 * add_job()/remove_job()
625 * Add or remove an accepted socket from the list of sockets
626 * connected to clients. allowed_globals.jobmutex protects
627 * against multiple concurrent access to the linked list of jobs.
629 static void add_job(int sock)
633 new_job = (joblist *) malloc(sizeof(joblist));
634 if (new_job == NULL) {
635 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
636 "Ouch! Out of memory in add_job()!");
639 new_job->next = NULL;
640 new_job->sock = sock;
642 apr_lock(allowed_globals.jobmutex);
644 if (allowed_globals.jobtail != NULL)
645 allowed_globals.jobtail->next = new_job;
646 allowed_globals.jobtail = new_job;
647 if (!allowed_globals.jobhead)
648 allowed_globals.jobhead = new_job;
649 allowed_globals.jobcount++;
650 release_semaphore(allowed_globals.jobsemaphore);
652 apr_unlock(allowed_globals.jobmutex);
655 static int remove_job(void)
660 acquire_semaphore(allowed_globals.jobsemaphore);
661 apr_lock(allowed_globals.jobmutex);
663 if (shutdown_in_progress && !allowed_globals.jobhead) {
664 apr_unlock(allowed_globals.jobmutex);
667 job = allowed_globals.jobhead;
669 allowed_globals.jobhead = job->next;
670 if (allowed_globals.jobhead == NULL)
671 allowed_globals.jobtail = NULL;
672 apr_unlock(allowed_globals.jobmutex);
679 static void accept_and_queue_connections(void * dummy)
681 int requests_this_child = 0;
686 int nsd = INVALID_SOCKET;
687 struct sockaddr_in sa_client;
688 int count_select_errors = 0;
692 while (!shutdown_in_progress) {
693 if (ap_max_requests_per_child && (requests_this_child > ap_max_requests_per_child)) {
697 tv.tv_sec = wait_time;
699 memcpy(&main_fds, &listenfds, sizeof(fd_set));
701 rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
703 if (rc == 0 || (rc == SOCKET_ERROR && APR_STATUS_IS_EINTR(apr_get_netos_error()))) {
704 count_select_errors = 0; /* reset count of errors */
707 else if (rc == SOCKET_ERROR) {
708 /* A "real" error occurred, log it and increment the count of
709 * select errors. This count is used to ensure we don't go into
710 * a busy loop of continuous errors.
712 ap_log_error(APLOG_MARK, APLOG_INFO, apr_get_netos_error(), server_conf,
713 "select failed with error %d", apr_get_netos_error());
714 count_select_errors++;
715 if (count_select_errors > MAX_SELECT_ERRORS) {
716 shutdown_in_progress = 1;
717 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), server_conf,
718 "Too many errors in select loop. Child process exiting.");
724 lr = find_ready_listener(&main_fds);
726 /* fetch the native socket descriptor */
727 apr_get_os_sock(&nsd, lr->sd);
732 clen = sizeof(sa_client);
733 csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
734 if (csd == INVALID_SOCKET) {
737 } while (csd < 0 && APR_STATUS_IS_EINTR(apr_get_netos_error()));
740 if (apr_get_netos_error() == APR_FROM_OS_ERROR(WSAECONNABORTED)) {
741 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), server_conf,
742 "accept: (client socket)");
747 requests_this_child++;
750 SetEvent(exit_event);
752 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
756 if (context == NULL) {
757 /* allocate the completion context and the transaction pool */
758 context = apr_pcalloc(pconf, sizeof(COMP_CONTEXT));
760 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
761 "win9x_get_connection: apr_pcalloc() failed. Process will exit.");
764 apr_create_pool(&context->ptrans, pconf);
769 apr_clear_pool(context->ptrans);
770 context->accept_socket = remove_job();
771 if (context->accept_socket == -1) {
774 len = sizeof(struct sockaddr);
775 context->sa_server = apr_palloc(context->ptrans, len);
776 if (getsockname(context->accept_socket,
777 context->sa_server, &len)== SOCKET_ERROR) {
778 ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), server_conf,
779 "getsockname failed");
782 len = sizeof(struct sockaddr);
783 context->sa_client = apr_palloc(context->ptrans, len);
784 if ((getpeername(context->accept_socket,
785 context->sa_client, &len)) == SOCKET_ERROR) {
786 ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), server_conf,
787 "getpeername failed");
788 memset(&context->sa_client, '\0', sizeof(context->sa_client));
791 /* do we NEED_DUPPED_CSD ?? */
798 * Windows 2000/NT specific code...
799 * create_acceptex_context()
800 * reset_acceptex_context()
801 * drain_acceptex_complport()
802 * winnt_get_connection()
804 * TODO: Insert a discussion of 'completion contexts' and what these function do here...
806 static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp)
809 PCOMP_CONTEXT context;
816 rc = GetQueuedCompletionStatus(hComplPort, &BytesRead, &CompKey,
819 rc = apr_get_os_error();
820 if (rc == APR_FROM_OS_ERROR(ERROR_OPERATION_ABORTED)) {
821 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
822 "Child %d: - Draining an ABORTED packet off "
823 "the AcceptEx completion port.", my_pid);
828 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
829 "Child %d: - Draining and discarding an active connection "
830 "off the AcceptEx completion port.", my_pid);
831 context = (PCOMP_CONTEXT) pol;
832 if (context && bCleanUp) {
833 /* It is only valid to clean-up in the process that initiated the I/O */
834 closesocket(context->accept_socket);
835 CloseHandle(context->Overlapped.hEvent);
839 static int create_acceptex_context(apr_pool_t *_pconf, ap_listen_rec *lr)
841 PCOMP_CONTEXT context;
846 /* allocate the completion context */
847 context = apr_pcalloc(_pconf, sizeof(COMP_CONTEXT));
849 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
850 "create_acceptex_context: apr_pcalloc() failed. Process will exit.");
854 /* initialize the completion context */
856 context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
857 if (context->Overlapped.hEvent == NULL) {
858 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
859 "create_acceptex_context: CreateEvent() failed. Process will exit.");
863 /* create and initialize the accept socket */
864 apr_get_os_sock(&nsd, context->lr->sd);
865 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
866 if (context->accept_socket == INVALID_SOCKET) {
867 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_netos_error(), server_conf,
868 "create_acceptex_context: socket() failed. Process will exit.");
872 /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
873 if (setsockopt(context->accept_socket, SOL_SOCKET,
874 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
876 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), server_conf,
877 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
878 /* Not a failure condition. Keep running. */
881 apr_create_pool(&context->ptrans, _pconf);
883 /* recv_buf must be large enough to hold the remote and local
884 * addresses. Note that recv_buf_size is the amount of recv_buf
885 * available for AcceptEx to receive bytes into. Since we
886 * don't want AcceptEx to do a recv, set the size to 0.
888 context->recv_buf = apr_pcalloc(_pconf, 2*PADDED_ADDR_SIZE);
889 context->recv_buf_size = 0;
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 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;
921 /* recreate and initialize the accept socket if it is not being reused */
922 apr_get_os_sock(&nsd, context->lr->sd);
924 /* AcceptEx on the completion context. The completion context will be signaled
925 * when a connection is accepted. Hack Alert: TransmitFile, under certain
926 * circumstances, can 'recycle' accept sockets, saving the overhead of calling
927 * socket(). Occasionally this fails (usually when the client closes his end
928 * of the connection early). When this occurs, AcceptEx will fail with 10022,
929 * Invalid Parameter. When this occurs, just open a fresh accept socket and
932 for (i=0; i<2; i++) {
933 if (context->accept_socket == INVALID_SOCKET) {
934 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
935 if (context->accept_socket == INVALID_SOCKET) {
936 rc = apr_get_netos_error();
937 ap_log_error(APLOG_MARK,APLOG_ERR, rc, server_conf,
938 "reset_acceptex_context: socket() failed. Process will exit.");
942 /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
943 if (setsockopt(context->accept_socket, SOL_SOCKET,
944 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd, sizeof(nsd))) {
945 ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(),
947 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
951 if (!AcceptEx(nsd, context->accept_socket,
953 context->recv_buf_size,
957 (LPOVERLAPPED) context)) {
959 rc = apr_get_netos_error();
960 if (rc != APR_FROM_OS_ERROR(ERROR_IO_PENDING)) {
961 ap_log_error(APLOG_MARK, APLOG_INFO, rc, server_conf,
962 "reset_acceptex_context: AcceptEx failed for "
963 "listening socket: %d and accept socket: %d",
964 nsd, context->accept_socket);
965 closesocket(context->accept_socket);
966 context->accept_socket = INVALID_SOCKET;
973 context->lr->count++;
977 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
979 int requests_this_child = 0;
986 if (context != NULL) {
987 if (shutdown_in_progress) {
988 /* Clean-up the AcceptEx completion context */
989 CloseHandle(context->Overlapped.hEvent);
990 if (context->accept_socket != INVALID_SOCKET)
991 closesocket(context->accept_socket);
994 /* Prepare the completion context for reuse */
995 if ((rc = reset_acceptex_context(context)) != APR_SUCCESS) {
996 ap_log_error(APLOG_MARK, APLOG_CRIT, rc, server_conf,
997 "Child %d: winnt_get_connection: reset_acceptex_context failed.",
999 if (context->accept_socket != INVALID_SOCKET)
1000 closesocket(context->accept_socket);
1001 CloseHandle(context->Overlapped.hEvent);
1002 /* Probably should just die now... */
1007 /* May need to atomize the workers_may_exit check with the
1008 * g_blocked_threads++ */
1009 if (workers_may_exit) {
1012 g_blocked_threads++;
1015 rc = GetQueuedCompletionStatus(AcceptExCompPort, &BytesRead, &CompKey,
1018 rc = apr_get_os_error();
1019 if (rc != APR_FROM_OS_ERROR(ERROR_OPERATION_ABORTED)) {
1020 /* Is this a deadly condition?
1021 * We sometimes get ERROR_NETNAME_DELETED when a client
1022 * disconnects when attempting to reuse sockets. Not sure why
1023 * we see this now and not during AcceptEx(). Reset the
1024 * AcceptEx context and continue...
1026 ap_log_error(APLOG_MARK,APLOG_INFO, rc, server_conf,
1027 "Child %d: - GetQueuedCompletionStatus() failed",
1029 /* Reset the completion context */
1031 context = (PCOMP_CONTEXT) pol;
1032 if (context->accept_socket != INVALID_SOCKET)
1033 closesocket(context->accept_socket);
1034 if ((rc = reset_acceptex_context(context)) != APR_SUCCESS) {
1035 ap_log_error(APLOG_MARK, APLOG_CRIT, rc, server_conf,
1036 "Child %d: winnt_get_connection: reset_acceptex_context failed.",
1038 if (context->accept_socket != INVALID_SOCKET)
1039 closesocket(context->accept_socket);
1040 CloseHandle(context->Overlapped.hEvent);
1041 /* Probably should just die now... */
1046 /* Sometimes we catch ERROR_OPERATION_ABORTED completion packets
1047 * from the old child process (during a restart). Ignore them.
1049 ap_log_error(APLOG_MARK,APLOG_INFO, rc, server_conf,
1050 "Child %d: - Draining ERROR_OPERATION_ABORTED packet off "
1051 "the completion port.", my_pid);
1057 /* CompKey == my_pid means this thread was unblocked by
1058 * the shutdown code (not by io completion).
1060 if (CompKey == my_pid) {
1061 g_blocked_threads--;
1064 /* Sometimes we catch shutdown io completion packets
1065 * posted by the old child process (during a restart). Ignore them.
1070 context = (PCOMP_CONTEXT) pol;
1074 g_blocked_threads--;
1076 /* Check to see if we need to create more completion contexts,
1077 * but only if we are not in the process of shutting down
1079 if (!shutdown_in_progress) {
1080 apr_lock(allowed_globals.jobmutex);
1081 context->lr->count--;
1082 if (context->lr->count < 2) {
1083 SetEvent(maintenance_event);
1085 apr_unlock(allowed_globals.jobmutex);
1088 /* Received a connection */
1089 GetAcceptExSockaddrs(context->recv_buf,
1090 context->recv_buf_size,
1093 &context->sa_server,
1094 &context->sa_server_len,
1095 &context->sa_client,
1096 &context->sa_client_len);
1102 * worker_main() - this is the main loop for the worker threads
1105 * Each thread runs within this function. They wait within remove_job()
1106 * for a job to become available, then handle all the requests on that
1107 * connection until it is closed, then return to remove_job().
1109 * The worker thread will exit when it removes a job which contains
1110 * socket number -1. This provides a graceful thread exit, since
1111 * it will never exit during a connection.
1113 * This code in this function is basically equivalent to the child_main()
1114 * from the multi-process (Unix) environment, except that we
1116 * - do not call child_init_modules (child init API phase)
1117 * - block in remove_job, and when unblocked we have an already
1118 * accepted socket, instead of blocking on a mutex or select().
1121 static void worker_main(int child_num)
1123 PCOMP_CONTEXT context = NULL;
1127 apr_int32_t disconnected;
1129 /* Grab a connection off the network */
1130 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1131 context = win9x_get_connection(context);
1134 context = winnt_get_connection(context);
1139 sock_disable_nagle(context->accept_socket);
1140 apr_put_os_sock(&context->sock, &context->accept_socket, context->ptrans);
1142 c = ap_new_connection(context->ptrans, server_conf, context->sock,
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);
1151 if (!disconnected) {
1152 context->accept_socket = INVALID_SOCKET;
1153 ap_lingering_close(c);
1157 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1158 "Child %d: Thread exiting.", my_pid);
1161 SetEvent(exit_event);
1163 /* TODO: Add code to clean-up completion contexts here */
1166 static void cleanup_thread(thread *handles, int *thread_cnt, int thread_to_clean)
1170 CloseHandle(handles[thread_to_clean]);
1171 for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1172 handles[i] = handles[i + 1];
1176 static void create_listeners()
1178 #define NUM_LISTENERS 5
1180 for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1181 while (lr->count < NUM_LISTENERS) {
1182 if (create_acceptex_context(pconf, lr) == -1) {
1183 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
1184 "Unable to create an AcceptEx completion context -- process will exit");
1185 signal_parent(0); /* tell parent to die */
1191 * child_main() runs the main control thread for the child process.
1193 * The control thread:
1194 * - sets up the worker thread pool
1195 * - starts the accept thread (Win 9x)
1196 * - creates AcceptEx contexts (Win NT)
1197 * - waits for exit_event, maintenance_event or maintenance timeout
1198 * and does the right thing depending on which event is received.
1200 static void child_main()
1202 apr_status_t status;
1203 HANDLE child_events[2];
1204 char* exit_event_name;
1205 int nthreads = ap_threads_per_child;
1207 thread *child_handles;
1215 /* This is the child process or we are running in single process
1218 exit_event_name = apr_psprintf(pconf, "apC%d", my_pid);
1219 setup_signal_names(apr_psprintf(pconf,"ap%d", parent_pid));
1222 /* Single process mode */
1223 apr_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1224 exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1226 setup_listeners(server_conf);
1227 bind_listeners_to_completion_port();
1230 /* Child process mode */
1231 apr_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1232 exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1233 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1234 "Child %d: exit_event_name = %s", my_pid, exit_event_name);
1236 setup_inherited_listeners(server_conf);
1239 /* Initialize the child_events */
1240 maintenance_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1241 child_events[0] = exit_event;
1242 child_events[1] = maintenance_event;
1244 ap_assert(start_mutex);
1245 ap_assert(exit_event);
1246 ap_assert(maintenance_event);
1248 apr_create_pool(&pchild, pconf);
1249 allowed_globals.jobsemaphore = create_semaphore(0);
1250 apr_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
1253 * Wait until we have permission to start accepting connections.
1254 * start_mutex is used to ensure that only one child ever
1255 * goes into the listen/accept loop at once.
1257 status = apr_lock(start_mutex);
1258 if (status != APR_SUCCESS) {
1259 ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
1260 "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1261 signal_parent(0); /* tell parent to die */
1264 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1265 "Child %d: Acquired the start mutex.", my_pid);
1267 /* Create the worker thread pool */
1268 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1269 "Child %d: Starting %d worker threads.", my_pid, nthreads);
1270 child_handles = (thread) alloca(nthreads * sizeof(int));
1271 for (i = 0; i < nthreads; i++) {
1272 child_handles[i] = (thread) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1276 /* Begin accepting connections */
1277 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1278 /* Win95/98: Start the accept thread */
1279 _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) accept_and_queue_connections,
1280 (void *) i, 0, &tid);
1282 /* Windows NT/2000: Create AcceptEx completion contexts */
1286 /* Wait for one of three events:
1288 * The exit_event is signaled by the parent process to notify
1289 * the child that it is time to exit.
1291 * maintenance_event:
1292 * This event is signaled by the worker thread pool to direct
1293 * this thread to create more completion contexts.
1296 * To do periodic maintenance on the server (check for thread exits,
1297 * number of completion contexts, etc.)
1300 rv = WaitForMultipleObjects(2, (HANDLE *) child_events, FALSE, INFINITE);
1301 cld = rv - WAIT_OBJECT_0;
1302 if (rv == WAIT_FAILED) {
1303 /* Something serious is wrong */
1304 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1305 "Child %d: WAIT_FAILED -- shutting down server");
1308 else if (rv == WAIT_TIMEOUT) {
1309 /* Hey, this cannot happen */
1310 ap_log_error(APLOG_MARK, APLOG_CRIT, APR_SUCCESS, server_conf,
1311 "Child %d: WAIT_TIMEOUT -- shutting down server", my_pid);
1314 else if (cld == 0) {
1315 /* Exit event was signaled */
1316 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1317 "Child %d: Exit event signaled. Child process is ending.", my_pid);
1321 /* Child maintenance event signaled */
1322 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1325 ResetEvent(maintenance_event);
1326 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1327 "Child %d: Child maintenance event signaled.", my_pid);
1331 /* Setting is_graceful will close keep-alive connections */
1334 /* Shutdown the worker threads */
1335 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1336 /* workers_may_exit = 1; Not used on Win9x */
1337 shutdown_in_progress = 1;
1338 for (i = 0; i < nthreads; i++) {
1342 else { /* Windows NT/2000 */
1346 * Setting shutdown_in_progress prevents new AcceptEx completion
1347 * contexts from being queued to the port but allows threads to
1348 * continue consuming from the port. This gives the server a
1349 * chance to handle any accepted connections.
1351 shutdown_in_progress = 1;
1354 /* Setting workers_may_exit prevents threads from consumimg from the
1355 * completion port (especially threads that unblock off of keep-alive
1356 * connections later on).
1358 workers_may_exit = 1;
1360 /* Unblock threads blocked on the completion port */
1361 apr_lock(allowed_globals.jobmutex);
1362 while (g_blocked_threads > 0) {
1363 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1364 "Child %d: %d threads blocked on the completion port", my_pid, g_blocked_threads);
1365 for (i=g_blocked_threads; i > 0; i--) {
1366 PostQueuedCompletionStatus(AcceptExCompPort, 0, my_pid, NULL);
1370 apr_unlock(allowed_globals.jobmutex);
1372 /* Cancel any remaining pending AcceptEx completion contexts */
1373 for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1374 apr_get_os_sock(&nsd,lr->sd);
1375 CancelIo((HANDLE) nsd);
1378 /* Drain the canceled contexts off the port */
1379 drain_acceptex_complport(AcceptExCompPort, TRUE);
1382 /* Release the start_mutex to let the new process (in the restart
1383 * scenario) a chance to begin servicing requests
1385 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1386 "Child %d: Releasing the start mutex", my_pid);
1387 apr_unlock(start_mutex);
1389 /* Give busy worker threads a chance to service their connections.
1390 * Kill them off if they take too long
1392 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1393 "Child %d: Waiting for %d threads to die.", my_pid, nthreads);
1394 end_time = time(NULL) + 180;
1396 rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1397 if (rv != WAIT_TIMEOUT) {
1398 rv = rv - WAIT_OBJECT_0;
1399 ap_assert((rv >= 0) && (rv < nthreads));
1400 cleanup_thread(child_handles, &nthreads, rv);
1405 for (i = 0; i < nthreads; i++) {
1406 TerminateThread(child_handles[i], 1);
1407 CloseHandle(child_handles[i]);
1409 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1410 "Child %d: All worker threads have ended.", my_pid);
1412 CloseHandle(AcceptExCompPort);
1413 destroy_semaphore(allowed_globals.jobsemaphore);
1414 apr_destroy_lock(allowed_globals.jobmutex);
1416 apr_destroy_pool(pchild);
1417 CloseHandle(exit_event);
1421 * Spawn a child Apache process. The child process has the command line arguments from
1422 * argc and argv[], plus a -Z argument giving the name of an event. The child should
1423 * open and poll or wait on this event. When it is signalled, the child should die.
1424 * prefix is a prefix string for the event name.
1426 * The child_num argument on entry contains a serial number for this child (used to create
1427 * a unique event name). On exit, this number will have been incremented by one, ready
1428 * for the next call.
1430 * On exit, the value pointed to be *ev will contain the event created
1431 * to signal the new child process.
1433 * The return value is the handle to the child process if successful, else -1. If -1 is
1434 * returned the error will already have been logged by ap_log_error().
1437 /**********************************************************************
1438 * master_main - this is the parent (main) process. We create a
1439 * child process to do the work, then sit around waiting for either
1440 * the child to exit, or a restart or exit signal. If the child dies,
1441 * we just respawn a new one. If we have a shutdown or graceful restart,
1442 * tell the child to die when it is ready. If it is a non-graceful
1443 * restart, force the child to die immediately.
1444 **********************************************************************/
1446 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1448 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1453 CloseHandle(handles[position]);
1454 CloseHandle(events[position]);
1456 handle = (int)handles[position];
1458 for (i = position; i < (*processes)-1; i++) {
1459 handles[i] = handles[i + 1];
1460 events[i] = events[i + 1];
1465 static int create_process(apr_pool_t *p, HANDLE *handles, HANDLE *events, int *processes)
1474 STARTUPINFO si; /* Filled in prior to call to CreateProcess */
1475 PROCESS_INFORMATION pi; /* filled in on call to CreateProcess */
1479 HANDLE hPipeRead = NULL;
1480 HANDLE hPipeWrite = NULL;
1481 SECURITY_ATTRIBUTES sa = {0};
1484 LPWSAPROTOCOL_INFO lpWSAProtocolInfo;
1485 HANDLE hDupedCompPort;
1487 sa.nLength = sizeof(sa);
1488 sa.bInheritHandle = TRUE;
1489 sa.lpSecurityDescriptor = NULL;
1491 /* Build the command line. Should look something like this:
1492 * C:/apache/bin/apache.exe -f ap_server_confname
1493 * First, get the path to the executable...
1495 rv = GetModuleFileName(NULL, buf, sizeof(buf));
1496 if (rv == sizeof(buf)) {
1497 ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1498 "Parent: Path to Apache process too long");
1500 } else if (rv == 0) {
1501 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1502 "Parent: GetModuleFileName() returned NULL for current process.");
1506 /* Build the command line */
1507 pCommand = apr_psprintf(p, "\"%s\"", buf);
1508 for (i = 1; i < server_conf->process->argc; i++) {
1509 pCommand = apr_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1512 /* Build the environment, since Win9x disrespects the active env */
1513 pEnvVar = apr_psprintf(p, "AP_PARENT_PID=%i", parent_pid);
1515 * Win32's CreateProcess call requires that the environment
1516 * be passed in an environment block, a null terminated block of
1517 * null terminated strings.
1521 while (_environ[i]) {
1522 iEnvBlockLen += strlen(_environ[i]) + 1;
1526 pEnvBlock = (char *)apr_pcalloc(p, iEnvBlockLen + strlen(pEnvVar) + 1);
1527 strcpy(pEnvBlock, pEnvVar);
1528 pEnvVar = strchr(pEnvBlock, '\0') + 1;
1531 while (_environ[i]) {
1532 strcpy(pEnvVar, _environ[i]);
1533 pEnvVar = strchr(pEnvVar, '\0') + 1;
1537 /* Create a pipe to send socket info to the child */
1538 if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1539 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1540 "Parent: Unable to create pipe to child process.");
1544 /* Give the read end of the pipe (hPipeRead) to the child as stdin. The
1545 * parent will write the socket data to the child on this pipe.
1547 memset(&si, 0, sizeof(si));
1548 memset(&pi, 0, sizeof(pi));
1550 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1551 si.wShowWindow = SW_HIDE;
1552 si.hStdInput = hPipeRead;
1554 if (!CreateProcess(NULL, pCommand, NULL, NULL,
1555 TRUE, /* Inherit handles */
1556 CREATE_SUSPENDED, /* Creation flags */
1557 pEnvBlock, /* Environment block */
1560 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1561 "Parent: Not able to create the child process.");
1563 * We must close the handles to the new process and its main thread
1564 * to prevent handle and memory leaks.
1566 CloseHandle(pi.hProcess);
1567 CloseHandle(pi.hThread);
1571 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1572 "Parent: Created child process %d", pi.dwProcessId);
1574 SetEnvironmentVariable("AP_PARENT_PID",NULL);
1576 /* Create the exit_event, apCchild_pid */
1577 sa.nLength = sizeof(sa);
1578 sa.bInheritHandle = TRUE;
1579 sa.lpSecurityDescriptor = NULL;
1580 kill_event = CreateEvent(&sa, TRUE, FALSE, apr_psprintf(pconf,"apC%d", pi.dwProcessId));
1582 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1583 "Parent: Could not create exit event for child process");
1584 CloseHandle(pi.hProcess);
1585 CloseHandle(pi.hThread);
1589 /* Assume the child process lives. Update the process and event tables */
1590 handles[*processes] = pi.hProcess;
1591 events[*processes] = kill_event;
1594 /* We never store the thread's handle, so close it now. */
1595 ResumeThread(pi.hThread);
1596 CloseHandle(pi.hThread);
1598 /* Run the chain of open sockets. For each socket, duplicate it
1599 * for the target process then send the WSAPROTOCOL_INFO
1600 * (returned by dup socket) to the child */
1601 for (lr = ap_listeners; lr; lr = lr->next) {
1603 lpWSAProtocolInfo = apr_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1604 apr_get_os_sock(&nsd,lr->sd);
1605 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1606 "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1607 if (WSADuplicateSocket(nsd, pi.dwProcessId,
1608 lpWSAProtocolInfo) == SOCKET_ERROR) {
1609 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), server_conf,
1610 "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1614 if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1616 (LPOVERLAPPED) NULL)) {
1617 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1618 "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1621 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1622 "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1624 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1625 /* Now, send the AcceptEx completion port to the child */
1626 if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort,
1627 pi.hProcess, &hDupedCompPort, 0,
1628 TRUE, DUPLICATE_SAME_ACCESS)) {
1629 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1630 "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1634 WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1637 CloseHandle(hPipeRead);
1638 CloseHandle(hPipeWrite);
1643 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1645 int remaining_children_to_start = ap_daemons_to_start;
1649 int restart_pending = 0;
1650 int shutdown_pending = 0;
1651 int current_live_processes = 0; /* number of child process we know about */
1653 HANDLE process_handles[MAX_PROCESSES];
1654 HANDLE process_kill_events[MAX_PROCESSES];
1657 bind_listeners_to_completion_port();
1659 /* Create child process
1660 * Should only be one in this version of Apache for WIN32
1662 while (remaining_children_to_start--) {
1663 if (create_process(pconf, process_handles, process_kill_events,
1664 ¤t_live_processes) < 0) {
1665 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), server_conf,
1666 "master_main: create child process failed. Exiting.");
1667 shutdown_pending = 1;
1672 restart_pending = shutdown_pending = 0;
1674 if (!strcasecmp(signal_arg, "runservice"))
1675 mpm_service_started();
1677 /* Wait for shutdown or restart events or for child death */
1678 process_handles[current_live_processes] = shutdown_event;
1679 process_handles[current_live_processes+1] = restart_event;
1681 rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles,
1683 cld = rv - WAIT_OBJECT_0;
1684 if (rv == WAIT_FAILED) {
1685 /* Something serious is wrong */
1686 ap_log_error(APLOG_MARK,APLOG_CRIT, apr_get_os_error(), server_conf,
1687 "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1688 shutdown_pending = 1;
1690 else if (rv == WAIT_TIMEOUT) {
1691 /* Hey, this cannot happen */
1692 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1693 "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1694 shutdown_pending = 1;
1696 else if (cld == current_live_processes) {
1697 /* shutdown_event signalled */
1698 shutdown_pending = 1;
1699 printf("shutdown event signaled\n");
1700 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1701 "master_main: Shutdown event signaled -- doing server shutdown.");
1702 if (ResetEvent(shutdown_event) == 0) {
1703 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1704 "ResetEvent(shutdown_event)");
1708 else if (cld == current_live_processes+1) {
1709 /* restart_event signalled */
1710 int children_to_kill = current_live_processes;
1711 restart_pending = 1;
1712 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, s,
1713 "master_main: Restart event signaled. Doing a graceful restart.");
1714 if (ResetEvent(restart_event) == 0) {
1715 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1716 "master_main: ResetEvent(restart_event) failed.");
1718 /* Signal each child process to die
1719 * We are making a big assumption here that the child process, once signaled,
1720 * will REALLY go away. Since this is a restart, we do not want to hold the
1721 * new child process up waiting for the old child to die. Remove the old
1722 * child out of the process_handles apr_table_t and hope for the best...
1724 for (i = 0; i < children_to_kill; i++) {
1725 if (SetEvent(process_kill_events[i]) == 0)
1726 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1727 "master_main: SetEvent for child process in slot #%d failed", i);
1728 cleanup_process(process_handles, process_kill_events, i, ¤t_live_processes);
1732 /* A child process must have exited because of a fatal error condition (seg fault, etc.).
1733 * Remove the dead process
1734 * from the process_handles and process_kill_events apr_table_t and create a new
1736 * TODO: Consider restarting the child immediately without looping through http_main
1737 * and without rereading the configuration. Will need this if we ever support multiple
1738 * children. One option, create a parent thread which waits on child death and restarts it.
1739 * Consider, however, that if the user makes httpd.conf invalid, we want to die before
1740 * our child tries it... otherwise we have a nasty loop.
1742 restart_pending = 1;
1743 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1744 "master_main: Child process failed. Restarting the child process.");
1745 ap_assert(cld < current_live_processes);
1746 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1747 /* APD2("main_process: child in slot %d died", rv); */
1748 /* restart_child(process_hancles, process_kill_events, cld, ¤t_live_processes); */
1750 /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead
1752 drain_acceptex_complport(AcceptExCompPort, FALSE);
1756 if (shutdown_pending)
1758 int tmstart = time(NULL);
1760 if (strcasecmp(signal_arg, "runservice")) {
1761 mpm_service_stopping();
1763 /* Signal each child processes to die */
1764 for (i = 0; i < current_live_processes; i++) {
1765 printf("SetEvent handle = %d\n", process_kill_events[i]);
1766 if (SetEvent(process_kill_events[i]) == 0)
1767 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
1768 "master_main: SetEvent for child process in slot #%d failed", i);
1771 while (current_live_processes && ((tmstart+60) > time(NULL))) {
1772 rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1773 if (rv == WAIT_TIMEOUT)
1775 ap_assert(rv != WAIT_FAILED);
1776 cld = rv - WAIT_OBJECT_0;
1777 ap_assert(rv < current_live_processes);
1778 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1780 for (i = 0; i < current_live_processes; i++) {
1781 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1782 "forcing termination of child #%d (handle %d)", i, process_handles[i]);
1783 TerminateProcess((HANDLE) process_handles[i], 1);
1785 return 0; /* Tell the caller we do not want to restart */
1788 return 1; /* Tell the caller we want a restart */
1792 #define SERVICE_UNNAMED -1
1794 /* service_nt_main_fn needs to append the StartService() args
1795 * outside of our call stack and thread as the service starts...
1797 apr_array_header_t *mpm_new_argv;
1799 /* Remember service_to_start failures to log and fail in pre_config.
1800 * Remember inst_argc and inst_argv for installing or starting the
1801 * service after we preflight the config.
1804 static apr_status_t service_to_start_success;
1805 static int inst_argc;
1806 static char **inst_argv;
1808 void winnt_rewrite_args(process_rec *process)
1810 /* Handle the following SCM aspects in this phase:
1812 * -k runservice [transition for WinNT, nothing for Win9x]
1813 * -k (!)install [error out if name is not installed]
1815 * We can't leave this phase until we know our identity
1816 * and modify the command arguments appropriately.
1818 apr_status_t service_named = SERVICE_UNNAMED;
1820 char *def_server_root;
1821 char fnbuf[MAX_PATH];
1824 const char **new_arg;
1828 int running_as_service = 1;
1830 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1831 GetVersionEx(&osver);
1833 /* AP_PARENT_PID is only valid in the child */
1834 pid = getenv("AP_PARENT_PID");
1837 /* This is the child */
1838 parent_pid = (DWORD) atol(pid);
1839 my_pid = GetCurrentProcessId();
1841 /* The parent is responsible for providing the
1842 * COMPLETE ARGUMENTS REQUIRED to the child.
1844 * No further argument parsing is needed, but
1845 * for good measure we will provide a simple
1846 * signal string for later testing.
1848 signal_arg = "runchild";
1852 /* This is the parent, we have a long way to go :-) */
1853 parent_pid = my_pid = GetCurrentProcessId();
1855 /* Rewrite process->argv[];
1857 * strip out -k signal into signal_arg
1858 * strip out -n servicename into service_name & display_name
1859 * add default -d serverroot from the path of this executable
1861 * The end result will look like:
1863 * The invocation command (%0)
1864 * The -d serverroot default from the running executable
1865 * The requested service's (-n) registry ConfigArgs
1866 * The WinNT SCM's StartService() args
1869 if (!GetModuleFileName(NULL, fnbuf, sizeof(fnbuf))) {
1870 /* WARNING: There is an implict assumption here that the
1871 * executable resides in the ServerRoot!
1873 rv = apr_get_os_error();
1874 ap_log_error(APLOG_MARK,APLOG_ERR, rv, NULL,
1875 "Failed to get the running module's file name");
1878 def_server_root = (char *) apr_filename_of_pathname(fnbuf);
1879 if (def_server_root > fnbuf) {
1880 *(def_server_root - 1) = '\0';
1881 def_server_root = ap_os_canonical_filename(process->pool, fnbuf);
1884 /* Use process->pool so that the rewritten argv
1885 * lasts for the lifetime of the server process,
1886 * because pconf will be destroyed after the
1887 * initial pre-flight of the config parser.
1890 mpm_new_argv = apr_make_array(process->pool, process->argc + 2, sizeof(char *));
1891 new_arg = (char**) apr_push_array(mpm_new_argv);
1892 *new_arg = (char *) process->argv[0];
1894 new_arg = (char**) apr_push_array(mpm_new_argv);
1896 new_arg = (char**) apr_push_array(mpm_new_argv);
1897 *new_arg = def_server_root;
1899 fixed_args = mpm_new_argv->nelts;
1901 optbuf[0] = '-'; optbuf[2] = '\0';
1902 apr_initopt(&opt, process->pool, process->argc, (char**) process->argv);
1903 while (apr_getopt(opt, "n:k:iu" AP_SERVER_BASEARGS,
1904 optbuf + 1, &optarg) == APR_SUCCESS) {
1905 switch (optbuf[1]) {
1907 service_named = mpm_service_set_name(process->pool, optarg);
1910 signal_arg = optarg;
1913 ap_log_error(APLOG_MARK,APLOG_WARNING, 0, NULL,
1914 "-i is deprecated. Use -k install.");
1915 signal_arg = "install";
1918 ap_log_error(APLOG_MARK,APLOG_WARNING, 0, NULL,
1919 "-u is deprecated. Use -k uninstall.");
1920 signal_arg = "uninstall";
1923 new_arg = (char**) apr_push_array(mpm_new_argv);
1924 *new_arg = apr_pstrdup(process->pool, optbuf);
1926 new_arg = (char**) apr_push_array(mpm_new_argv);
1933 /* Track the number of args actually entered by the user */
1934 inst_argc = mpm_new_argv->nelts - fixed_args;
1936 /* Provide a default 'run' -k arg to simplify signal_arg tests */
1940 running_as_service = 0;
1943 if (!strcasecmp(signal_arg, "runservice"))
1945 /* Start the NT Service _NOW_ because the WinNT SCM is
1946 * expecting us to rapidly assume control of our own
1947 * process, the SCM will tell us our service name, and
1948 * may have extra StartService() command arguments to
1951 * Any other process has a console, so we don't to begin
1952 * a Win9x service until the configuration is parsed and
1953 * any command line errors are reported.
1955 * We hold the return value so that we can die in pre_config
1956 * after logging begins, and the failure can land in the log.
1958 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) {
1959 service_to_start_success = mpm_service_to_start();
1960 if (service_to_start_success == APR_SUCCESS)
1961 service_named = APR_SUCCESS;
1965 if (service_named == SERVICE_UNNAMED && running_as_service) {
1966 service_named = mpm_service_set_name(process->pool,
1967 DEFAULT_SERVICE_NAME);
1970 if (!strcasecmp(signal_arg, "install")) /* -k install */
1972 if (service_named == APR_SUCCESS)
1974 ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
1975 "%s: Service is already installed.", display_name);
1979 else if (running_as_service)
1981 if (service_named == APR_SUCCESS)
1983 rv = mpm_merge_service_args(process->pool, mpm_new_argv,
1985 if (rv == APR_SUCCESS) {
1986 ap_log_error(APLOG_MARK,APLOG_NOERRNO|APLOG_INFO, 0, NULL,
1987 "Using ConfigArgs of the installed service "
1988 "\"%s\".", display_name);
1991 ap_log_error(APLOG_MARK,APLOG_INFO, rv, NULL,
1992 "No installed ConfigArgs for the service "
1993 "\"%s\", using Apache defaults.", display_name);
1998 ap_log_error(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO, 0, NULL,
1999 "No installed service named \"%s\".", display_name);
2004 /* Track the args actually entered by the user.
2005 * These will be used for the -k install parameters, as well as
2006 * for the -k start service override arguments.
2008 inst_argv = (char**) mpm_new_argv->elts + mpm_new_argv->nelts - inst_argc;
2010 process->argc = mpm_new_argv->nelts;
2011 process->argv = (char**) mpm_new_argv->elts;
2015 static void winnt_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
2017 /* Handle the following SCM aspects in this phase:
2019 * -k runservice [WinNT errors logged from rewrite_args]
2023 * in these cases we -don't- care if httpd.conf has config errors!
2027 if (getenv("ONE_PROCESS"))
2030 if (ap_exists_config_define("ONE_PROCESS"))
2033 if (!strcasecmp(signal_arg, "runservice")
2034 && (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
2035 && (service_to_start_success != APR_SUCCESS)) {
2036 ap_log_error(APLOG_MARK,APLOG_ERR, service_to_start_success, NULL,
2037 "%s: Unable to start the service manager.",
2042 if (!strcasecmp(signal_arg, "uninstall")) {
2043 rv = mpm_service_uninstall();
2047 if (!strcasecmp(signal_arg, "stop")) {
2048 mpm_signal_service(ptemp, 0);
2052 ap_listen_pre_config();
2053 ap_daemons_to_start = DEFAULT_NUM_DAEMON;
2054 ap_threads_per_child = DEFAULT_START_THREAD;
2055 ap_pid_fname = DEFAULT_PIDLOG;
2056 max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
2058 apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
2061 static void winnt_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec* server)
2063 static int restart_num = 0;
2064 apr_status_t rv = 0;
2066 server_conf = server;
2068 /* Handle the following SCM aspects in this phase:
2073 * -k runservice [Win95, only once - after we parsed the config]
2075 * because all of these signals are useful _only_ if there
2076 * is a valid conf\httpd.conf environment to start.
2078 * We reached this phase by avoiding errors that would cause
2079 * these options to fail unexpectedly in another process.
2082 if (!strcasecmp(signal_arg, "install")) {
2083 rv = mpm_service_install(ptemp, inst_argc, inst_argv);
2087 if (!strcasecmp(signal_arg, "start")) {
2088 rv = mpm_service_start(ptemp, inst_argc, inst_argv);
2092 if (!strcasecmp(signal_arg, "restart")) {
2093 mpm_signal_service(ptemp, 1);
2097 if (parent_pid == my_pid)
2099 if (restart_num++ == 1)
2101 /* This code should be run once in the parent and not run
2104 PSECURITY_ATTRIBUTES sa = GetNullACL(); /* returns NULL if invalid (Win95?) */
2105 setup_signal_names(apr_psprintf(pconf,"ap%d", parent_pid));
2106 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
2107 /* Create the AcceptEx IoCompletionPort once in the parent.
2108 * The completion port persists across restarts.
2110 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
2113 0); /* CONCURRENT ACTIVE THREADS */
2114 if (AcceptExCompPort == NULL) {
2115 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), server_conf,
2116 "Parent: Unable to create the AcceptExCompletionPort -- process will exit");
2121 ap_log_pid(pconf, ap_pid_fname);
2123 /* Create shutdown event, apPID_shutdown, where PID is the parent
2124 * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
2126 shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
2127 if (!shutdown_event) {
2128 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
2129 "Parent: Cannot create shutdown event %s", signal_shutdown_name);
2130 CleanNullACL((void *)sa);
2134 /* Create restart event, apPID_restart, where PID is the parent
2135 * Apache process ID. Restart is signaled by 'apache -k restart'.
2137 restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
2138 if (!restart_event) {
2139 CloseHandle(shutdown_event);
2140 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), server_conf,
2141 "Parent: Cannot create restart event %s", signal_restart_name);
2142 CleanNullACL((void *)sa);
2145 CleanNullACL((void *)sa);
2147 /* Now that we are flying at 15000 feet...
2148 * wipe out the Win95 service console,
2149 * signal the SCM the WinNT service started, or
2150 * if not a service, setup console handlers instead.
2152 if (!strcasecmp(signal_arg, "runservice"))
2154 if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT)
2156 rv = mpm_service_to_start();
2157 if (rv != APR_SUCCESS) {
2158 ap_log_error(APLOG_MARK,APLOG_ERR, rv, server_conf,
2159 "%s: Unable to start the service manager.",
2165 else /* ! -k runservice */
2167 mpm_start_console_handler();
2170 /* Create the start mutex, apPID, where PID is the parent Apache process ID.
2171 * Ths start mutex is used during a restart to prevent more than one
2172 * child process from entering the accept loop at once.
2174 apr_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS, signal_name_prefix,
2175 server_conf->process->pool);
2178 else /* parent_pid != my_pid */
2180 mpm_start_child_console_handler();
2184 AP_DECLARE(int) ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s )
2186 static int restart = 0; /* Default is "not a restart" */
2191 if ((parent_pid != my_pid) || one_process) {
2192 /* Running as Child process or in one_process (debug) mode */
2193 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
2194 "Child %d: Child process is running", my_pid);
2196 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
2197 "Child %d: Child process is exiting", my_pid);
2200 } /* Child or single process */
2201 else { /* Parent process */
2202 restart = master_main(server_conf, shutdown_event, restart_event);
2205 /* Shutting down. Clean up... */
2206 const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
2208 if (pidfile != NULL && unlink(pidfile) == 0) {
2209 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS,
2210 server_conf, "removed PID file %s (pid=%ld)",
2211 pidfile, GetCurrentProcessId());
2213 apr_destroy_lock(start_mutex);
2215 CloseHandle(restart_event);
2216 CloseHandle(shutdown_event);
2220 } /* Parent process */
2222 return 0; /* Restart */
2225 static void winnt_hooks(void)
2227 ap_hook_pre_config(winnt_pre_config, NULL, NULL, AP_HOOK_MIDDLE);
2228 ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
2232 * Command processors
2234 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg)
2236 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2241 if (cmd->server->is_virtual) {
2242 return "PidFile directive not allowed in <VirtualHost>";
2248 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg)
2250 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2255 ap_threads_per_child = atoi(arg);
2256 if (ap_threads_per_child > HARD_THREAD_LIMIT) {
2257 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2258 "WARNING: ThreadsPerChild of %d exceeds compile time"
2259 " limit of %d threads,", ap_threads_per_child,
2261 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2262 " lowering ThreadsPerChild to %d. To increase, please"
2263 " see the HARD_THREAD_LIMIT define in %s.",
2264 HARD_THREAD_LIMIT, AP_MPM_HARD_LIMITS_FILE);
2265 ap_threads_per_child = HARD_THREAD_LIMIT;
2267 else if (ap_threads_per_child < 1) {
2268 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
2269 "WARNING: Require ThreadsPerChild > 0, setting to 1");
2270 ap_threads_per_child = 1;
2276 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg)
2278 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2283 max_requests_per_child = atoi(arg);
2288 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg)
2292 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2297 fname = ap_server_root_relative(cmd->pool, arg);
2298 if ((apr_stat(&finfo, fname, cmd->pool) != APR_SUCCESS) ||
2299 (finfo.filetype != APR_DIR)) {
2300 return apr_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
2301 " does not exist or is not a directory", NULL);
2303 apr_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
2307 /* Stub functions until this MPM supports the connection status API */
2309 AP_DECLARE(void) ap_update_connection_status(long conn_id, const char *key, \
2315 AP_DECLARE(void) ap_reset_connection_status(long conn_id)
2320 AP_DECLARE(apr_array_header_t *) ap_get_status_table(apr_pool_t *p)
2326 static const command_rec winnt_cmds[] = {
2328 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
2329 "A file for logging the server process ID"},
2330 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
2331 "Number of threads each child creates" },
2332 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
2333 "Maximum number of requests a particular child serves before dying." },
2334 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
2335 "The location of the directory Apache changes to before dumping core" },
2339 AP_MODULE_DECLARE_DATA module mpm_winnt_module = {
2341 winnt_rewrite_args, /* hook to run before apache parses args */
2342 NULL, /* create per-directory config structure */
2343 NULL, /* merge per-directory config structures */
2344 NULL, /* create per-server config structure */
2345 NULL, /* merge per-server config structures */
2346 winnt_cmds, /* command apr_table_t */
2347 NULL, /* handlers */
2348 winnt_hooks /* register_hooks */