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.
60 #include "apr_portable.h"
62 #include "http_main.h"
64 #include "http_config.h" /* for read_config */
65 #include "http_core.h" /* for get_remote_host */
66 #include "http_connection.h"
68 #include "ap_config.h"
69 #include "ap_listen.h"
70 #include "mpm_default.h"
72 #include "iol_socket.h"
77 * Definitions of WINNT MPM specific config globals
80 static char *ap_pid_fname = NULL;
81 static int ap_threads_per_child = 0;
82 static int workers_may_exit = 0;
83 static int max_requests_per_child = 0;
84 static HANDLE shutdown_event; /* used to signal shutdown to parent */
85 static HANDLE restart_event; /* used to signal a restart to parent */
87 static struct fd_set listenfds;
88 static int num_listenfds = 0;
89 static SOCKET listenmaxfd = INVALID_SOCKET;
91 static ap_pool_t *pconf; /* Pool for config stuff */
93 static char ap_coredump_dir[MAX_STRING_LEN];
95 static server_rec *server_conf;
96 static HANDLE AcceptExCompPort = NULL;
98 static int one_process = 0;
100 static OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
102 int ap_max_requests_per_child=0;
103 int ap_daemons_to_start=0;
105 static event *exit_event;
106 HANDLE maintenance_event;
107 ap_lock_t *start_mutex;
111 static ap_status_t socket_cleanup(void *sock)
113 ap_socket_t *thesocket = sock;
115 if (ap_get_os_sock(&sd, thesocket) == APR_SUCCESS) {
121 /* A bunch or routines from os/win32/multithread.c that need to be merged into APR
122 * or thrown out entirely...
126 typedef void semaphore;
130 create_semaphore(int initial)
132 return(CreateSemaphore(NULL, initial, 1000000, NULL));
135 static void acquire_semaphore(semaphore *semaphore_id)
139 rv = WaitForSingleObject(semaphore_id, INFINITE);
144 static int release_semaphore(semaphore *semaphore_id)
146 return(ReleaseSemaphore(semaphore_id, 1, NULL));
149 static void destroy_semaphore(semaphore *semaphore_id)
151 CloseHandle(semaphore_id);
155 /* To share the semaphores with other processes, we need a NULL ACL
156 * Code from MS KB Q106387
158 static PSECURITY_ATTRIBUTES GetNullACL()
160 PSECURITY_DESCRIPTOR pSD;
161 PSECURITY_ATTRIBUTES sa;
163 sa = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES));
164 pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,
165 SECURITY_DESCRIPTOR_MIN_LENGTH);
166 if (pSD == NULL || sa == NULL) {
169 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
175 if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
181 sa->nLength = sizeof(sa);
182 sa->lpSecurityDescriptor = pSD;
183 sa->bInheritHandle = TRUE;
187 static void CleanNullACL( void *sa ) {
189 LocalFree( ((PSECURITY_ATTRIBUTES)sa)->lpSecurityDescriptor);
195 * The Win32 call WaitForMultipleObjects will only allow you to wait for
196 * a maximum of MAXIMUM_WAIT_OBJECTS (current 64). Since the threading
197 * model in the multithreaded version of apache wants to use this call,
198 * we are restricted to a maximum of 64 threads. This is a simplistic
199 * routine that will increase this size.
201 static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles,
205 DWORD dwRet = WAIT_TIMEOUT;
209 tStopTime = time(NULL) + dwSeconds;
217 for (dwIndex = 0; dwIndex * MAXIMUM_WAIT_OBJECTS < nCount; dwIndex++) {
218 dwRet = WaitForMultipleObjects(
219 min(MAXIMUM_WAIT_OBJECTS, nCount - (dwIndex * MAXIMUM_WAIT_OBJECTS)),
220 lpHandles + (dwIndex * MAXIMUM_WAIT_OBJECTS),
223 if (dwRet != WAIT_TIMEOUT) {
227 } while((time(NULL) < tStopTime) && (dwRet == WAIT_TIMEOUT));
233 * Signalling Apache on NT.
235 * Under Unix, Apache can be told to shutdown or restart by sending various
236 * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
237 * we use "events" instead. The parent apache process goes into a loop
238 * where it waits forever for a set of events. Two of those events are
244 * (where PID is the PID of the apache parent process). When one of these
245 * is signalled, the Apache parent performs the appropriate action. The events
246 * can become signalled through internal Apache methods (e.g. if the child
247 * finds a fatal error and needs to kill its parent), via the service
248 * control manager (the control thread will signal the shutdown event when
249 * requested to stop the Apache service), from the -k Apache command line,
250 * or from any external program which finds the Apache PID from the
253 * The signal_parent() function, below, is used to signal one of these events.
254 * It can be called by any child or parent process, since it does not
255 * rely on global variables.
257 * On entry, type gives the event to signal. 0 means shutdown, 1 means
260 static void signal_parent(int type)
264 extern char signal_shutdown_name[];
265 extern char signal_restart_name[];
267 /* after updating the shutdown_pending or restart flags, we need
268 * to wake up the parent process so it can see the changes. The
269 * parent will normally be waiting for either a child process
270 * to die, or for a signal on the "spache-signal" event. So set the
271 * "apache-signal" event here.
278 case 0: signal_name = signal_shutdown_name; break;
279 case 1: signal_name = signal_restart_name; break;
282 e = OpenEvent(EVENT_ALL_ACCESS, FALSE, signal_name);
284 /* Um, problem, can't signal the parent, which means we can't
285 * signal ourselves to die. Ignore for now...
287 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
288 "OpenEvent on %s event", signal_name);
291 if (SetEvent(e) == 0) {
292 /* Same problem as above */
293 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
294 "SetEvent on %s event", signal_name);
300 static int volatile is_graceful = 0;
301 API_EXPORT(int) ap_graceful_stop_signalled(void)
305 void ap_start_shutdown(void)
310 * Initialise the signal names, in the global variables signal_name_prefix,
311 * signal_restart_name and signal_shutdown_name.
314 #define MAX_SIGNAL_NAME 30 /* Long enough for apPID_shutdown, where PID is an int */
315 char signal_name_prefix[MAX_SIGNAL_NAME];
316 char signal_restart_name[MAX_SIGNAL_NAME];
317 char signal_shutdown_name[MAX_SIGNAL_NAME];
318 static void setup_signal_names(char *prefix)
320 ap_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);
321 ap_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name),
322 "%s_shutdown", signal_name_prefix);
323 ap_snprintf(signal_restart_name, sizeof(signal_restart_name),
324 "%s_restart", signal_name_prefix);
328 * Routines that deal with sockets, some are WIN32 specific...
331 static void sock_disable_nagle(int s)
333 /* The Nagle algorithm says that we should delay sending partial
334 * packets in hopes of getting more data. We don't want to do
335 * this; we are not telnet. There are bad interactions between
336 * persistent connections and Nagle's algorithm that have very severe
337 * performance penalties. (Failing to disable Nagle is not much of a
338 * problem with simple HTTP.)
340 * In spite of these problems, failure here is not a shooting offense.
344 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
346 ap_log_error(APLOG_MARK, APLOG_WARNING, APR_SUCCESS, server_conf,
347 "setsockopt: (TCP_NODELAY)");
352 * Routines to deal with managing the list of listening sockets.
354 static ap_listen_rec *head_listener;
355 static ap_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
360 for (lr = head_listener; lr ; lr = lr->next) {
361 ap_get_os_sock(&nsd, lr->sd);
362 if (FD_ISSET(nsd, main_fds)) {
363 head_listener = lr->next;
364 if (head_listener == NULL)
365 head_listener = ap_listeners;
372 static int setup_listeners(server_rec *s)
375 int num_listeners = 0;
378 /* Setup the listeners */
381 if (ap_listen_open(s->process, s->port)) {
384 for (lr = ap_listeners; lr; lr = lr->next) {
386 if (lr->sd != NULL) {
387 ap_get_os_sock(&nsd, lr->sd);
388 FD_SET(nsd, &listenfds);
389 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
396 head_listener = ap_listeners;
398 return num_listeners;
401 static int setup_inherited_listeners(server_rec *s)
403 WSAPROTOCOL_INFO WSAProtocolInfo;
407 int num_listeners = 0;
410 /* Setup the listeners */
413 /* Set up a default listener if necessary */
415 if (ap_listeners == NULL) {
417 lr = ap_palloc(s->process->pool, sizeof(ap_listen_rec));
421 lr->next = ap_listeners;
425 /* Open the pipe to the parent process to receive the inherited socket
426 * data. The sockets have been set to listening in the parent process.
428 pipe = GetStdHandle(STD_INPUT_HANDLE);
429 for (lr = ap_listeners; lr; lr = lr->next) {
430 if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
431 &BytesRead, (LPOVERLAPPED) NULL)) {
432 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
433 "setup_inherited_listeners: Unable to read socket data from parent");
434 signal_parent(0); /* tell parent to die */
437 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
438 "Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.", my_pid);
439 nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
440 &WSAProtocolInfo, 0, 0);
441 if (nsd == INVALID_SOCKET) {
442 ap_log_error(APLOG_MARK, APLOG_CRIT, WSAGetLastError(), server_conf,
443 "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
444 signal_parent(0); /* tell parent to die */
448 FD_SET(nsd, &listenfds);
449 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
453 // ap_register_cleanup(p, (void *)lr->sd, socket_cleanup, ap_null_cleanup);
454 ap_put_os_sock(&lr->sd, &nsd, pconf);
457 /* Now, read the AcceptExCompPort from the parent */
458 ReadFile(pipe, &AcceptExCompPort, sizeof(AcceptExCompPort), &BytesRead, (LPOVERLAPPED) NULL);
461 for (lr = ap_listeners; lr; lr = lr->next) {
465 head_listener = ap_listeners;
466 return num_listeners;
469 static void bind_listeners_to_completion_port()
471 /* Associate the open listeners with the completion port.
472 * Bypass the operation for Windows 95/98
476 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
477 for (lr = ap_listeners; lr; lr = lr->next) {
479 ap_get_os_sock(&nsd,lr->sd);
480 CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
485 /**********************************************************************
486 * Multithreaded implementation
488 * This code is fairly specific to Win32.
490 * The model used to handle requests is a set of threads. One "main"
491 * thread listens for new requests. When something becomes
492 * available, it does a select and places the newly available socket
493 * onto a list of "jobs" (add_job()). Then any one of a fixed number
494 * of "worker" threads takes the top job off the job list with
495 * remove_job() and handles that connection to completion. After
496 * the connection has finished the thread is free to take another
497 * job from the job list.
499 * In the code, the "main" thread is running within the child_main()
500 * function. The first thing this function does is create the
501 * worker threads, which operate in the child_sub_main() function. The
502 * main thread then goes into a loop within child_main() where they
503 * do a select() on the listening sockets. The select times out once
504 * per second so that the thread can check for an "exit" signal
505 * from the parent process (see below). If this signal is set, the
506 * thread can exit, but only after it has accepted all incoming
507 * connections already in the listen queue (since Win32 appears
508 * to through away listened but unaccepted connections when a
511 * Because the main and worker threads exist within a single process
512 * they are vulnerable to crashes or memory leaks (crashes can also
513 * be caused within modules, of course). There also needs to be a
514 * mechanism to perform restarts and shutdowns. This is done by
515 * creating the main & worker threads within a subprocess. A
516 * main process (the "parent process") creates one (or more)
517 * processes to do the work, then the parent sits around waiting
518 * for the working process to die, in which case it starts a new
519 * one. The parent process also handles restarts (by creating
520 * a new working process then signalling the previous working process
521 * exit ) and shutdowns (by signalling the working process to exit).
522 * The parent process operates within the master_main() function. This
523 * process also handles requests from the service manager (NT only).
525 * Signalling between the parent and working process uses a Win32
526 * event. Each child has a unique name for the event, which is
527 * passed to it with the -Z argument when the child is spawned. The
528 * parent sets (signals) this event to tell the child to die.
529 * At present all children do a graceful die - they finish all
530 * current jobs _and_ empty the listen queue before they exit.
531 * A non-graceful die would need a second event. The -Z argument in
532 * the child is also used to create the shutdown and restart events,
533 * since the prefix (apPID) contains the parent process PID.
535 * The code below starts with functions at the lowest level -
536 * worker threads, and works up to the top level - the main()
537 * function of the parent process.
539 * The scoreboard (in process memory) contains details of the worker
540 * threads (within the active working process). There is no shared
541 * "scoreboard" between processes, since only one is ever active
542 * at once (or at most, two, when one has been told to shutdown but
543 * is processes outstanding requests, and a new one has been started).
544 * This is controlled by a "start_mutex" which ensures only one working
545 * process is active at once.
546 **********************************************************************/
550 * Definition of jobs, shared by main and worker threads.
553 typedef struct joblist_s {
554 struct joblist_s *next;
559 * Globals common to main and worker threads. This structure is not
560 * used by the parent process.
563 typedef struct globals_s {
564 semaphore *jobsemaphore;
571 globals allowed_globals =
572 {NULL, NULL, NULL, NULL, 0};
573 #define MAX_SELECT_ERRORS 100
574 #define PADDED_ADDR_SIZE sizeof(SOCKADDR_IN)+16
576 /* Windows 9x specific code...
577 * Accept processing for on Windows 95/98 uses a producer/consumer queue
578 * model. A single thread accepts connections and queues the accepted socket
579 * to the accept queue for consumption by a pool of worker threads.
581 * win9x_get_connection()
582 * Calls remove_job() to pull a job from the accept queue. All the worker
583 * threads block on remove_job.
584 * accept_and_queue_connections()
585 * The accept threads runs this function, which accepts connections off
586 * the network and calls add_job() to queue jobs to the accept_queue.
587 * add_job()/remove_job()
588 * Add or remove an accepted socket from the list of sockets
589 * connected to clients. allowed_globals.jobmutex protects
590 * against multiple concurrent access to the linked list of jobs.
592 static void add_job(int sock)
596 new_job = (joblist *) malloc(sizeof(joblist));
597 if (new_job == NULL) {
598 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
599 "Ouch! Out of memory in add_job()!");
602 new_job->next = NULL;
603 new_job->sock = sock;
605 ap_lock(allowed_globals.jobmutex);
607 if (allowed_globals.jobtail != NULL)
608 allowed_globals.jobtail->next = new_job;
609 allowed_globals.jobtail = new_job;
610 if (!allowed_globals.jobhead)
611 allowed_globals.jobhead = new_job;
612 allowed_globals.jobcount++;
613 release_semaphore(allowed_globals.jobsemaphore);
615 ap_unlock(allowed_globals.jobmutex);
618 static int remove_job(void)
623 acquire_semaphore(allowed_globals.jobsemaphore);
624 ap_lock(allowed_globals.jobmutex);
626 if (workers_may_exit && !allowed_globals.jobhead) {
627 ap_unlock(allowed_globals.jobmutex);
630 job = allowed_globals.jobhead;
632 allowed_globals.jobhead = job->next;
633 if (allowed_globals.jobhead == NULL)
634 allowed_globals.jobtail = NULL;
635 ap_unlock(allowed_globals.jobmutex);
642 static void accept_and_queue_connections(void * dummy)
644 int requests_this_child = 0;
649 int nsd = INVALID_SOCKET;
650 struct sockaddr_in sa_client;
651 int count_select_errors = 0;
655 while (!workers_may_exit) {
656 if (ap_max_requests_per_child && (requests_this_child > ap_max_requests_per_child)) {
660 tv.tv_sec = wait_time;
662 memcpy(&main_fds, &listenfds, sizeof(fd_set));
664 // rc = ap_select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
665 rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
667 if (rc == 0 || (rc == SOCKET_ERROR && h_errno == WSAEINTR)) {
668 count_select_errors = 0; /* reset count of errors */
671 else if (rc == SOCKET_ERROR) {
672 /* A "real" error occurred, log it and increment the count of
673 * select errors. This count is used to ensure we don't go into
674 * a busy loop of continuous errors.
676 ap_log_error(APLOG_MARK, APLOG_INFO, h_errno, server_conf,
677 "select failed with errno %d", h_errno);
678 count_select_errors++;
679 if (count_select_errors > MAX_SELECT_ERRORS) {
680 workers_may_exit = 1;
681 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
682 "Too many errors in select loop. Child process exiting.");
688 lr = find_ready_listener(&main_fds);
690 /* fetch the native socket descriptor */
691 ap_get_os_sock(&nsd, lr->sd);
696 clen = sizeof(sa_client);
697 csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
698 if (csd == INVALID_SOCKET) {
701 } while (csd < 0 && h_errno == WSAEINTR);
704 if (h_errno != WSAECONNABORTED) {
705 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
706 "accept: (client socket)");
711 requests_this_child++;
714 SetEvent(exit_event);
716 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
720 if (context == NULL) {
721 /* allocate the completion context and the transaction pool */
722 context = ap_pcalloc(pconf, sizeof(COMP_CONTEXT));
724 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
725 "win9x_get_connection: ap_pcalloc() failed. Process will exit.");
728 ap_create_pool(&context->ptrans, pconf);
733 ap_clear_pool(context->ptrans);
734 context->accept_socket = remove_job();
735 if (context->accept_socket == -1) {
738 //ap_note_cleanups_for_socket(ptrans, csd);
739 len = sizeof(struct sockaddr);
740 context->sa_server = ap_palloc(context->ptrans, len);
741 if (getsockname(context->accept_socket,
742 context->sa_server, &len)== SOCKET_ERROR) {
743 ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(), server_conf,
744 "getsockname failed");
747 len = sizeof(struct sockaddr);
748 context->sa_client = ap_palloc(context->ptrans, len);
749 if ((getpeername(context->accept_socket,
750 context->sa_client, &len)) == SOCKET_ERROR) {
751 ap_log_error(APLOG_MARK, APLOG_WARNING, h_errno, server_conf,
752 "getpeername failed with error %d\n", WSAGetLastError());
753 memset(&context->sa_client, '\0', sizeof(context->sa_client));
756 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
758 /* do we NEED_DUPPED_CSD ?? */
765 * Windows 2000/NT specific code...
766 * create_acceptex_context()
767 * reset_acceptex_context()
768 * drain_acceptex_complport()
769 * winnt_get_connection()
771 * TODO: Insert a discussion of 'completion contexts' and what these function do here...
773 static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp)
776 PCOMP_CONTEXT context;
784 rc = GetQueuedCompletionStatus(hComplPort, &BytesRead, &CompKey,
787 lastError = GetLastError();
788 if (lastError == ERROR_OPERATION_ABORTED) {
789 ap_log_error(APLOG_MARK,APLOG_INFO,lastError, server_conf,
790 "Child %d: - Draining a packet off the completion port.", my_pid);
795 ap_log_error(APLOG_MARK,APLOG_INFO,APR_SUCCESS, server_conf,
796 "Child %d: - Nuking an active connection. context = %x", my_pid, context);
797 context = (PCOMP_CONTEXT) pol;
798 if (context && bCleanUp) {
799 /* It is only valid to clean-up in the process that initiated the I/O */
800 closesocket(context->accept_socket);
801 CloseHandle(context->Overlapped.hEvent);
805 static int create_acceptex_context(ap_pool_t *_pconf, ap_listen_rec *lr)
807 PCOMP_CONTEXT context;
812 /* allocate the completion context */
813 context = ap_pcalloc(_pconf, sizeof(COMP_CONTEXT));
815 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
816 "create_acceptex_context: ap_pcalloc() failed. Process will exit.");
820 /* initialize the completion context */
822 context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
823 if (context->Overlapped.hEvent == NULL) {
824 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
825 "create_acceptex_context: CreateEvent() failed. Process will exit.");
829 /* create and initialize the accept socket */
830 ap_get_os_sock(&nsd, context->lr->sd);
831 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
832 if (context->accept_socket == INVALID_SOCKET) {
833 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
834 "create_acceptex_context: socket() failed. Process will exit.");
838 /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
839 if (setsockopt(context->accept_socket, SOL_SOCKET,
840 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
842 ap_log_error(APLOG_MARK, APLOG_ERR, WSAGetLastError(), server_conf,
843 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
844 /* Not a failure condition. Keep running. */
847 ap_create_pool(&context->ptrans, _pconf);
848 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
849 context->recv_buf = context->conn_io->inbase;
850 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
853 /* AcceptEx on the completion context. The completion context will be signaled
854 * when a connection is accepted. */
855 if (!AcceptEx(nsd, context->accept_socket,
857 0, //context->recv_buf_size,
858 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
860 (LPOVERLAPPED) context)) {
861 lasterror = WSAGetLastError();
862 if (lasterror != ERROR_IO_PENDING) {
863 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
864 "create_acceptex_context: AcceptEx failed. Process will exit.");
873 static ap_inline int reset_acceptex_context(PCOMP_CONTEXT context)
879 context->lr->count++;
881 /* recreate and initialize the accept socket if it is not being reused */
882 ap_get_os_sock(&nsd, context->lr->sd);
883 if (context->accept_socket == INVALID_SOCKET) {
884 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
885 if (context->accept_socket == INVALID_SOCKET) {
886 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
887 "reset_acceptex_context: socket() failed. Process will exit.");
891 /* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
892 if (setsockopt(context->accept_socket, SOL_SOCKET,
893 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
895 ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(),
897 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
898 /* Not a failure condition. Keep running. */
902 /* reset the completion context */
903 ap_clear_pool(context->ptrans);
904 context->sock = NULL;
905 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
906 context->recv_buf = context->conn_io->inbase;
907 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
909 /* AcceptEx on the completion context. The completion context will be signaled
910 * when a connection is accepted. */
911 if (!AcceptEx(nsd, context->accept_socket,
913 0, //context->recv_buf_size,
914 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
915 &BytesRead, (LPOVERLAPPED) context)) {
916 lasterror = WSAGetLastError();
917 if (lasterror != ERROR_IO_PENDING) {
918 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
919 "reset_acceptex_context: AcceptEx failed. Leaving the process running.");
926 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
928 int requests_this_child = 0;
934 if (context != NULL) {
935 /* If child shutdown has been signaled, clean-up the completion context */
936 if (workers_may_exit) {
937 CloseHandle(context->Overlapped.hEvent);
941 context->accept_socket = INVALID_SOCKET; /* Don't reuse the accept_socket */
942 if (reset_acceptex_context(context) == -1) {
943 if (context->accept_socket != -1)
944 closesocket(context->accept_socket);
945 CloseHandle(context->Overlapped.hEvent);
952 rc = GetQueuedCompletionStatus(AcceptExCompPort,
958 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
959 "Child %d: - GetQueuedCompletionStatus() failed", my_pid);
960 /* During a restart, the new child process can catch
961 * ERROR_OPERATION_ABORTED completion packets
962 * posted by the old child process. Just continue...
967 /* Check the Completion Key.
968 * == my_pid indicate this process wants to exit
969 * == 0 implies valid i/o completion
970 * != 0 implies a posted completion packet by an old
971 * process. Just ignore it.
973 if (CompKey == my_pid) {
979 context = (PCOMP_CONTEXT) pol;
983 /* Check to see if we need to create more completion contexts,
984 * but only if we are not in the process of shutting down
986 if (!workers_may_exit) {
987 ap_lock(allowed_globals.jobmutex);
988 context->lr->count--;
989 if (context->lr->count < 2) {
990 SetEvent(maintenance_event);
992 ap_unlock(allowed_globals.jobmutex);
995 /* Received a connection */
996 context->conn_io->incnt = BytesRead;
997 GetAcceptExSockaddrs(context->recv_buf,
998 0, //context->recv_buf_size,
1001 &context->sa_server,
1002 &context->sa_server_len,
1003 &context->sa_client,
1004 &context->sa_client_len);
1010 * worker_main() - this is the main loop for the worker threads
1013 * Each thread runs within this function. They wait within remove_job()
1014 * for a job to become available, then handle all the requests on that
1015 * connection until it is closed, then return to remove_job().
1017 * The worker thread will exit when it removes a job which contains
1018 * socket number -1. This provides a graceful thread exit, since
1019 * it will never exit during a connection.
1021 * This code in this function is basically equivalent to the child_main()
1022 * from the multi-process (Unix) environment, except that we
1024 * - do not call child_init_modules (child init API phase)
1025 * - block in remove_job, and when unblocked we have an already
1026 * accepted socket, instead of blocking on a mutex or select().
1029 static void worker_main(int child_num)
1031 PCOMP_CONTEXT context = NULL;
1034 conn_rec *current_conn;
1037 /* Grab a connection off the network */
1038 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1039 context = win9x_get_connection(context);
1042 context = winnt_get_connection(context);
1047 sock_disable_nagle(context->accept_socket);
1048 ap_put_os_sock(&context->sock, &context->accept_socket, context->ptrans);
1049 // ap_register_cleanup(context->ptrans, context->sock, socket_cleanup, ap_null_cleanup);
1050 iol = win32_attach_socket(context->ptrans, context->sock);
1052 ap_log_error(APLOG_MARK, APLOG_ERR, APR_ENOMEM, server_conf,
1053 "worker_main: attach_socket() failed. Continuing...");
1054 closesocket(context->accept_socket);
1057 ap_bpush_iol(context->conn_io, iol);
1058 current_conn = ap_new_connection(context->ptrans, server_conf, context->conn_io,
1059 (struct sockaddr_in *) context->sa_client,
1060 (struct sockaddr_in *) context->sa_server,
1063 ap_process_connection(current_conn);
1066 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1067 "Child %d: Thread exiting.", my_pid);
1070 SetEvent(exit_event);
1072 /* TODO: Add code to clean-up completion contexts here */
1075 static void cleanup_thread(thread **handles, int *thread_cnt, int thread_to_clean)
1079 CloseHandle(handles[thread_to_clean]);
1080 for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1081 handles[i] = handles[i + 1];
1085 static void create_listeners()
1087 #define NUM_LISTENERS 5
1089 for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1090 while (lr->count < NUM_LISTENERS) {
1091 if (create_acceptex_context(pconf, lr) == -1) {
1092 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1093 "Unable to create an AcceptEx completion context -- process will exit");
1094 signal_parent(0); /* tell parent to die */
1100 * child_main() runs the main control thread for the child process.
1102 * The control thread:
1103 * - sets up the worker thread pool
1104 * - starts the accept thread (Win 9x)
1105 * - creates AcceptEx contexts (Win NT)
1106 * - waits for exit_event, maintenance_event or maintenance timeout
1107 * and does the right thing depending on which event is received.
1109 static void child_main()
1112 HANDLE child_events[2];
1113 char* exit_event_name;
1114 int nthreads = ap_threads_per_child;
1116 thread **child_handles;
1124 /* This is the child process or we are running in single process
1127 exit_event_name = ap_psprintf(pconf, "apC%d", my_pid);
1128 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1131 /* Single process mode */
1132 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1133 exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1135 setup_listeners(server_conf);
1136 bind_listeners_to_completion_port();
1139 /* Child process mode */
1140 ap_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1141 exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1142 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1143 "Child %d: exit_event_name = %s", my_pid, exit_event_name);
1145 setup_inherited_listeners(server_conf);
1148 /* Initialize the child_events */
1149 maintenance_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1150 child_events[0] = exit_event;
1151 child_events[1] = maintenance_event;
1153 ap_assert(start_mutex);
1154 ap_assert(exit_event);
1155 ap_assert(maintenance_event);
1157 ap_create_pool(&pchild, pconf);
1158 allowed_globals.jobsemaphore = create_semaphore(0);
1159 ap_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
1162 * Wait until we have permission to start accepting connections.
1163 * start_mutex is used to ensure that only one child ever
1164 * goes into the listen/accept loop at once.
1166 status = ap_lock(start_mutex);
1167 if (status != APR_SUCCESS) {
1168 ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
1169 "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1170 signal_parent(0); /* tell parent to die */
1173 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1174 "Child %d: Acquired the start mutex.", my_pid);
1176 /* Create the worker thread pool */
1177 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1178 "Child %d: Starting %d worker threads.", my_pid, nthreads);
1179 child_handles = (thread *) alloca(nthreads * sizeof(int));
1180 for (i = 0; i < nthreads; i++) {
1181 child_handles[i] = (thread *) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1182 NULL, 0, &thread_id);
1185 /* Begin accepting connections */
1186 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1187 /* Win95/98: Start the accept thread */
1188 _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) accept_and_queue_connections,
1189 (void *) i, 0, &thread_id);
1191 /* Windows NT/2000: Create AcceptEx completion contexts */
1195 /* Wait for one of three events:
1197 * The exit_event is signaled by the parent process to notify
1198 * the child that it is time to exit.
1200 * maintenance_event:
1201 * This event is signaled by the worker thread pool to direct
1202 * this thread to create more completion contexts.
1205 * To do periodic maintenance on the server (check for thread exits,
1206 * number of completion contexts, etc.)
1208 while (!workers_may_exit) {
1209 rv = WaitForMultipleObjects(2, (HANDLE *) child_events, FALSE, INFINITE);
1210 cld = rv - WAIT_OBJECT_0;
1211 if (rv == WAIT_FAILED) {
1212 /* Something serious is wrong */
1213 workers_may_exit = 1;
1214 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1215 "Child %d: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1216 /* Give a busy server the chance to drain AcceptEx completion contexts
1217 * by servicing connections. Note that the setting of workers_may_exit
1218 * prevents new AcceptEx completion contexts from being created.
1222 /* Drain any remaining contexts. May loose a few connections here. */
1223 drain_acceptex_complport(AcceptExCompPort, FALSE);
1225 else if (rv == WAIT_TIMEOUT) {
1226 /* Hey, this cannot happen */
1227 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1228 "Child %d: Server maintenance...", my_pid);
1230 else if (cld == 0) {
1231 /* Exit event was signaled */
1232 workers_may_exit = 1;
1233 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1234 "Child %d: Exit event signaled. Child process is ending.", my_pid);
1237 /* Child maintenance event signaled */
1238 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1241 ResetEvent(maintenance_event);
1242 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1243 "Child %d: Child maintenance event signaled...", my_pid);
1247 /* Shutdown the worker threads */
1248 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1249 for (i = 0; i < nthreads; i++) {
1253 else { /* Windows NT/2000 */
1254 /* Sometimes posted completion contexts intended for this process
1255 * are consumed by the new process (during restart). Send a few
1256 * extra to compensate. At worst, this process may hang around
1257 * for several minutes because a thread is not exiting because
1258 * it is blocked on GetQueuedCompletionStatus.
1260 for (i=0; i < 2*nthreads; i++) {
1261 if (!PostQueuedCompletionStatus(AcceptExCompPort, 0, my_pid, NULL)) {
1262 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1263 "PostQueuedCompletionStatus failed");
1268 /* Release the start_mutex to let the new process (in the restart
1269 * scenario) a chance to begin servicing requests
1271 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1272 "Child %d: Releasing the start mutex", my_pid);
1273 ap_unlock(start_mutex);
1275 /* Give busy worker threads a chance to service their connections.
1276 * Kill them off if they take too long
1278 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1279 "Child %d: Waiting for %d threads to die.", my_pid, nthreads);
1280 end_time = time(NULL) + 180;
1282 rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1283 if (rv != WAIT_TIMEOUT) {
1284 rv = rv - WAIT_OBJECT_0;
1285 ap_assert((rv >= 0) && (rv < nthreads));
1286 cleanup_thread(child_handles, &nthreads, rv);
1291 for (i = 0; i < nthreads; i++) {
1292 TerminateThread(child_handles[i], 1);
1293 CloseHandle(child_handles[i]);
1295 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1296 "Child %d: All worker threads have ended.", my_pid);
1298 CloseHandle(AcceptExCompPort);
1299 destroy_semaphore(allowed_globals.jobsemaphore);
1300 ap_destroy_lock(allowed_globals.jobmutex);
1302 ap_destroy_pool(pchild);
1303 CloseHandle(exit_event);
1307 * Spawn a child Apache process. The child process has the command line arguments from
1308 * argc and argv[], plus a -Z argument giving the name of an event. The child should
1309 * open and poll or wait on this event. When it is signalled, the child should die.
1310 * prefix is a prefix string for the event name.
1312 * The child_num argument on entry contains a serial number for this child (used to create
1313 * a unique event name). On exit, this number will have been incremented by one, ready
1314 * for the next call.
1316 * On exit, the value pointed to be *ev will contain the event created
1317 * to signal the new child process.
1319 * The return value is the handle to the child process if successful, else -1. If -1 is
1320 * returned the error will already have been logged by ap_log_error().
1323 /**********************************************************************
1324 * master_main - this is the parent (main) process. We create a
1325 * child process to do the work, then sit around waiting for either
1326 * the child to exit, or a restart or exit signal. If the child dies,
1327 * we just respawn a new one. If we have a shutdown or graceful restart,
1328 * tell the child to die when it is ready. If it is a non-graceful
1329 * restart, force the child to die immediately.
1330 **********************************************************************/
1332 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1334 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1339 CloseHandle(handles[position]);
1340 CloseHandle(events[position]);
1342 handle = (int)handles[position];
1344 for (i = position; i < (*processes)-1; i++) {
1345 handles[i] = handles[i + 1];
1346 events[i] = events[i + 1];
1351 static int create_process(ap_pool_t *p, HANDLE *handles, HANDLE *events, int *processes)
1358 STARTUPINFO si; /* Filled in prior to call to CreateProcess */
1359 PROCESS_INFORMATION pi; /* filled in on call to CreateProces */
1363 HANDLE hPipeRead = NULL;
1364 HANDLE hPipeWrite = NULL;
1365 SECURITY_ATTRIBUTES sa = {0};
1367 sa.nLength = sizeof(sa);
1368 sa.bInheritHandle = TRUE;
1369 sa.lpSecurityDescriptor = NULL;
1371 /* Build the command line. Should look something like this:
1372 * C:/apache/bin/apache.exe -f ap_server_confname
1373 * First, get the path to the executable...
1375 rv = GetModuleFileName(NULL, buf, sizeof(buf));
1376 if (rv == sizeof(buf)) {
1377 ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1378 "Parent: Path to Apache process too long");
1380 } else if (rv == 0) {
1381 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1382 "Parent: GetModuleFileName() returned NULL for current process.");
1386 /* Build the command line */
1387 pCommand = ap_psprintf(p, "\"%s\"", buf);
1388 for (i = 1; i < server_conf->process->argc; i++) {
1389 pCommand = ap_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1392 /* Create a pipe to send socket info to the child */
1393 if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1394 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1395 "Parent: Unable to create pipe to child process.\n");
1399 SetEnvironmentVariable("AP_PARENT_PID",ap_psprintf(p,"%d",parent_pid));
1401 /* Give the read end of the pipe (hPipeRead) to the child as stdin. The
1402 * parent will write the socket data to the child on this pipe.
1404 memset(&si, 0, sizeof(si));
1405 memset(&pi, 0, sizeof(pi));
1407 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1408 si.wShowWindow = SW_HIDE;
1409 si.hStdInput = hPipeRead;
1411 if (!CreateProcess(NULL, pCommand, NULL, NULL,
1412 TRUE, /* Inherit handles */
1413 CREATE_SUSPENDED, /* Creation flags */
1414 NULL, /* Environment block */
1417 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1418 "Parent: Not able to create the child process.");
1420 * We must close the handles to the new process and its main thread
1421 * to prevent handle and memory leaks.
1423 CloseHandle(pi.hProcess);
1424 CloseHandle(pi.hThread);
1429 LPWSAPROTOCOL_INFO lpWSAProtocolInfo;
1430 HANDLE hDupedCompPort;
1432 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1433 "Parent: Created child process %d", pi.dwProcessId);
1435 SetEnvironmentVariable("AP_PARENT_PID",NULL);
1437 /* Create the exit_event, apCchild_pid */
1438 sa.nLength = sizeof(sa);
1439 sa.bInheritHandle = TRUE;
1440 sa.lpSecurityDescriptor = NULL;
1441 kill_event = CreateEvent(&sa, TRUE, FALSE, ap_psprintf(pconf,"apC%d", pi.dwProcessId));
1443 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1444 "Parent: Could not create exit event for child process");
1445 CloseHandle(pi.hProcess);
1446 CloseHandle(pi.hThread);
1450 /* Assume the child process lives. Update the process and event tables */
1451 handles[*processes] = pi.hProcess;
1452 events[*processes] = kill_event;
1455 /* We never store the thread's handle, so close it now. */
1456 ResumeThread(pi.hThread);
1457 CloseHandle(pi.hThread);
1459 /* Run the chain of open sockets. For each socket, duplicate it
1460 * for the target process then send the WSAPROTOCOL_INFO
1461 * (returned by dup socket) to the child */
1462 for (lr = ap_listeners; lr; lr = lr->next) {
1464 lpWSAProtocolInfo = ap_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1465 ap_get_os_sock(&nsd,lr->sd);
1466 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1467 "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1468 if (WSADuplicateSocket(nsd, pi.dwProcessId,
1469 lpWSAProtocolInfo) == SOCKET_ERROR) {
1470 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, server_conf,
1471 "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1475 if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1477 (LPOVERLAPPED) NULL)) {
1478 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1479 "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1482 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1483 "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1485 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1486 /* Now, send the AcceptEx completion port to the child */
1487 if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort,
1488 pi.hProcess, &hDupedCompPort, 0,
1489 TRUE, DUPLICATE_SAME_ACCESS)) {
1490 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1491 "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1495 WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1499 CloseHandle(hPipeRead);
1500 CloseHandle(hPipeWrite);
1505 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1507 int remaining_children_to_start = ap_daemons_to_start;
1511 int restart_pending = 0;
1512 int shutdown_pending = 0;
1513 int current_live_processes = 0; /* number of child process we know about */
1515 HANDLE process_handles[MAX_PROCESSES];
1516 HANDLE process_kill_events[MAX_PROCESSES];
1519 bind_listeners_to_completion_port();
1521 /* Create child process
1522 * Should only be one in this version of Apache for WIN32
1524 service_set_status(SERVICE_START_PENDING);
1525 while (remaining_children_to_start--) {
1526 if (create_process(pconf, process_handles, process_kill_events,
1527 ¤t_live_processes) < 0) {
1528 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1529 "master_main: create child process failed. Exiting.");
1530 shutdown_pending = 1;
1534 service_set_status(SERVICE_RUNNING);
1536 restart_pending = shutdown_pending = 0;
1538 /* Wait for shutdown or restart events or for child death */
1539 process_handles[current_live_processes] = shutdown_event;
1540 process_handles[current_live_processes+1] = restart_event;
1542 rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles,
1544 cld = rv - WAIT_OBJECT_0;
1545 if (rv == WAIT_FAILED) {
1546 /* Something serious is wrong */
1547 ap_log_error(APLOG_MARK,APLOG_CRIT, GetLastError(), server_conf,
1548 "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1549 shutdown_pending = 1;
1551 else if (rv == WAIT_TIMEOUT) {
1552 /* Hey, this cannot happen */
1553 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1554 "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1555 shutdown_pending = 1;
1557 else if (cld == current_live_processes) {
1558 /* shutdown_event signalled */
1559 shutdown_pending = 1;
1560 printf("shutdown event signaled\n");
1561 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1562 "master_main: Shutdown event signaled -- doing server shutdown.");
1563 if (ResetEvent(shutdown_event) == 0) {
1564 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1565 "ResetEvent(shutdown_event)");
1569 else if (cld == current_live_processes+1) {
1570 /* restart_event signalled */
1571 int children_to_kill = current_live_processes;
1572 restart_pending = 1;
1573 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, s,
1574 "master_main: Restart event signaled. Doing a graceful restart.");
1575 if (ResetEvent(restart_event) == 0) {
1576 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1577 "master_main: ResetEvent(restart_event) failed.");
1579 /* Signal each child process to die
1580 * We are making a big assumption here that the child process, once signaled,
1581 * will REALLY go away. Since this is a restart, we do not want to hold the
1582 * new child process up waiting for the old child to die. Remove the old
1583 * child out of the process_handles ap_table_t and hope for the best...
1585 for (i = 0; i < children_to_kill; i++) {
1586 if (SetEvent(process_kill_events[i]) == 0)
1587 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1588 "master_main: SetEvent for child process in slot #%d failed", i);
1589 cleanup_process(process_handles, process_kill_events, i, ¤t_live_processes);
1593 /* A child process must have exited because of a fatal error condition (seg fault, etc.).
1594 * Remove the dead process
1595 * from the process_handles and process_kill_events ap_table_t and create a new
1597 * TODO: Consider restarting the child immediately without looping through http_main
1598 * and without rereading the configuration. Will need this if we ever support multiple
1599 * children. One option, create a parent thread which waits on child death and restarts it.
1601 restart_pending = 1;
1602 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1603 "master_main: Child process failed. Restarting the child process.");
1604 ap_assert(cld < current_live_processes);
1605 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1606 /* APD2("main_process: child in slot %d died", rv); */
1607 /* restart_child(process_hancles, process_kill_events, cld, ¤t_live_processes); */
1609 /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead
1611 drain_acceptex_complport(AcceptExCompPort, FALSE);
1615 if (shutdown_pending) {
1616 int tmstart = time(NULL);
1617 /* Signal each child processes to die */
1618 for (i = 0; i < current_live_processes; i++) {
1619 printf("SetEvent handle = %d\n", process_kill_events[i]);
1620 if (SetEvent(process_kill_events[i]) == 0)
1621 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1622 "master_main: SetEvent for child process in slot #%d failed", i);
1625 while (current_live_processes && ((tmstart+60) > time(NULL))) {
1626 rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1627 if (rv == WAIT_TIMEOUT)
1629 ap_assert(rv != WAIT_FAILED);
1630 cld = rv - WAIT_OBJECT_0;
1631 ap_assert(rv < current_live_processes);
1632 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1634 for (i = 0; i < current_live_processes; i++) {
1635 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1636 "forcing termination of child #%d (handle %d)", i, process_handles[i]);
1637 TerminateProcess((HANDLE) process_handles[i], 1);
1639 return 0; /* Tell the caller we do not want to restart */
1642 return 1; /* Tell the caller we want a restart */
1646 * winnt_pre_config() hook
1648 static void winnt_pre_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp)
1652 one_process = !!getenv("ONE_PROCESS");
1654 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1655 GetVersionEx(&osver);
1657 /* AP_PARENT_PID is only valid in the child */
1658 pid = getenv("AP_PARENT_PID");
1660 /* This is the child */
1661 parent_pid = atoi(pid);
1665 /* This is the parent */
1666 parent_pid = my_pid = getpid();
1669 ap_listen_pre_config();
1670 ap_daemons_to_start = DEFAULT_NUM_DAEMON;
1671 ap_threads_per_child = DEFAULT_START_THREAD;
1672 ap_pid_fname = DEFAULT_PIDLOG;
1673 max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1675 ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1679 static void winnt_post_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp, server_rec* server_conf)
1681 static int restart_num = 0;
1682 server_conf = server_conf;
1684 if (parent_pid == my_pid) {
1685 if (restart_num++ == 1) {
1686 /* This code should be run once in the parent and not run
1689 PSECURITY_ATTRIBUTES sa = GetNullACL(); /* returns NULL if invalid (Win95?) */
1690 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1691 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1692 /* Create the AcceptEx IoCompletionPort once in the parent.
1693 * The completion port persists across restarts.
1695 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1698 0); /* CONCURRENT ACTIVE THREADS */
1699 if (AcceptExCompPort == NULL) {
1700 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1701 "Parent: Unable to create the AcceptExCompletionPort -- process will exit");
1706 ap_log_pid(pconf, ap_pid_fname);
1707 service_set_status(SERVICE_START_PENDING);
1709 /* Create shutdown event, apPID_shutdown, where PID is the parent
1710 * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
1712 shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
1713 if (!shutdown_event) {
1714 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
1715 "Parent: Cannot create shutdown event %s", signal_shutdown_name);
1716 CleanNullACL((void *)sa);
1720 /* Create restart event, apPID_restart, where PID is the parent
1721 * Apache process ID. Restart is signaled by 'apache -k restart'.
1723 restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
1724 if (!restart_event) {
1725 CloseHandle(shutdown_event);
1726 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
1727 "Parent: Cannot create restart event %s", signal_restart_name);
1728 CleanNullACL((void *)sa);
1731 CleanNullACL((void *)sa);
1733 /* Create the start mutex, apPID, where PID is the parent Apache process ID.
1734 * Ths start mutex is used during a restart to prevent more than one
1735 * child process from entering the accept loop at once.
1737 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS, signal_name_prefix,
1738 server_conf->process->pool);
1743 API_EXPORT(int) ap_mpm_run(ap_pool_t *_pconf, ap_pool_t *plog, server_rec *s )
1745 static int restart = 0; /* Default is "not a restart" */
1750 if ((parent_pid != my_pid) || one_process) {
1751 /* Running as Child process or in one_process (debug) mode */
1752 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1753 "Child %d: Child process is running", my_pid);
1755 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1756 "Child %d: Child process is exiting", my_pid);
1759 } /* Child or single process */
1760 else { /* Parent process */
1761 restart = master_main(server_conf, shutdown_event, restart_event);
1764 /* Shutting down. Clean up... */
1765 const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1767 if (pidfile != NULL && unlink(pidfile) == 0) {
1768 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO,APR_SUCCESS,
1769 server_conf, "removed PID file %s (pid=%ld)",
1770 pidfile, (long)getpid());
1772 ap_destroy_lock(start_mutex);
1774 CloseHandle(restart_event);
1775 CloseHandle(shutdown_event);
1777 service_set_status(SERVICE_STOPPED);
1781 } /* Parent process */
1783 return 0; /* Restart */
1786 static void winnt_hooks(void)
1789 ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
1793 * Command processors
1795 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg)
1797 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1802 if (cmd->server->is_virtual) {
1803 return "PidFile directive not allowed in <VirtualHost>";
1809 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg)
1811 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1816 ap_threads_per_child = atoi(arg);
1817 if (ap_threads_per_child > HARD_THREAD_LIMIT) {
1818 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1819 "WARNING: ThreadsPerChild of %d exceeds compile time"
1820 " limit of %d threads,", ap_threads_per_child,
1822 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1823 " lowering ThreadsPerChild to %d. To increase, please"
1824 " see the HARD_THREAD_LIMIT define in src/include/httpd.h.",
1827 else if (ap_threads_per_child < 1) {
1828 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1829 "WARNING: Require ThreadsPerChild > 0, setting to 1");
1830 ap_threads_per_child = 1;
1836 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg)
1838 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1843 max_requests_per_child = atoi(arg);
1848 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg)
1852 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1857 fname = ap_server_root_relative(cmd->pool, arg);
1858 if ((stat(fname, &finfo) == -1) || !S_ISDIR(finfo.st_mode)) {
1859 return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
1860 " does not exist or is not a directory", NULL);
1862 ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1866 /* Stub functions until this MPM supports the connection status API */
1868 API_EXPORT(void) ap_update_connection_status(long conn_id, const char *key, \
1874 API_EXPORT(void) ap_reset_connection_status(long conn_id)
1879 API_EXPORT(ap_array_header_t *) ap_get_status_table(ap_pool_t *p)
1885 static const command_rec winnt_cmds[] = {
1887 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
1888 "A file for logging the server process ID"},
1889 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
1890 "Number of threads each child creates" },
1891 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
1892 "Maximum number of requests a particular child serves before dying." },
1893 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
1894 "The location of the directory Apache changes to before dumping core" },
1898 module MODULE_VAR_EXPORT mpm_winnt_module = {
1900 winnt_pre_config, /* hook run before configuration is read */
1901 NULL, /* create per-directory config structure */
1902 NULL, /* merge per-directory config structures */
1903 NULL, /* create per-server config structure */
1904 NULL, /* merge per-server config structures */
1905 winnt_cmds, /* command ap_table_t */
1906 NULL, /* handlers */
1907 winnt_hooks /* register_hooks */