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;
85 static struct fd_set listenfds;
86 static int num_listenfds = 0;
87 static SOCKET listenmaxfd = INVALID_SOCKET;
89 static ap_context_t *pconf; /* Pool for config stuff */
91 static char ap_coredump_dir[MAX_STRING_LEN];
93 static server_rec *server_conf;
94 static HANDLE AcceptExCompPort = NULL;
96 static int one_process = 0;
98 static OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
100 int ap_max_requests_per_child=0;
101 int ap_daemons_to_start=0;
103 static event *exit_event;
104 ap_lock_t *start_mutex;
108 static ap_status_t socket_cleanup(void *sock)
110 ap_socket_t *thesocket = sock;
112 if (ap_get_os_sock(&sd, thesocket) == APR_SUCCESS) {
118 /* A bunch or routines from os/win32/multithread.c that need to be merged into APR
119 * or thrown out entirely...
123 typedef void semaphore;
127 create_semaphore(int initial)
129 return(CreateSemaphore(NULL, initial, 1000000, NULL));
132 static void acquire_semaphore(semaphore *semaphore_id)
136 rv = WaitForSingleObject(semaphore_id, INFINITE);
141 static int release_semaphore(semaphore *semaphore_id)
143 return(ReleaseSemaphore(semaphore_id, 1, NULL));
146 static void destroy_semaphore(semaphore *semaphore_id)
148 CloseHandle(semaphore_id);
152 /* To share the semaphores with other processes, we need a NULL ACL
153 * Code from MS KB Q106387
155 static PSECURITY_ATTRIBUTES GetNullACL()
157 PSECURITY_DESCRIPTOR pSD;
158 PSECURITY_ATTRIBUTES sa;
160 sa = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES));
161 pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,
162 SECURITY_DESCRIPTOR_MIN_LENGTH);
163 if (pSD == NULL || sa == NULL) {
166 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
172 if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
178 sa->nLength = sizeof(sa);
179 sa->lpSecurityDescriptor = pSD;
180 sa->bInheritHandle = TRUE;
184 static void CleanNullACL( void *sa ) {
186 LocalFree( ((PSECURITY_ATTRIBUTES)sa)->lpSecurityDescriptor);
192 * The Win32 call WaitForMultipleObjects will only allow you to wait for
193 * a maximum of MAXIMUM_WAIT_OBJECTS (current 64). Since the threading
194 * model in the multithreaded version of apache wants to use this call,
195 * we are restricted to a maximum of 64 threads. This is a simplistic
196 * routine that will increase this size.
198 static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles,
202 DWORD dwRet = WAIT_TIMEOUT;
206 tStopTime = time(NULL) + dwSeconds;
214 for (dwIndex = 0; dwIndex * MAXIMUM_WAIT_OBJECTS < nCount; dwIndex++) {
215 dwRet = WaitForMultipleObjects(
216 min(MAXIMUM_WAIT_OBJECTS, nCount - (dwIndex * MAXIMUM_WAIT_OBJECTS)),
217 lpHandles + (dwIndex * MAXIMUM_WAIT_OBJECTS),
220 if (dwRet != WAIT_TIMEOUT) {
224 } while((time(NULL) < tStopTime) && (dwRet == WAIT_TIMEOUT));
230 * Signalling Apache on NT.
232 * Under Unix, Apache can be told to shutdown or restart by sending various
233 * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
234 * we use "events" instead. The parent apache process goes into a loop
235 * where it waits forever for a set of events. Two of those events are
241 * (where PID is the PID of the apache parent process). When one of these
242 * is signalled, the Apache parent performs the appropriate action. The events
243 * can become signalled through internal Apache methods (e.g. if the child
244 * finds a fatal error and needs to kill its parent), via the service
245 * control manager (the control thread will signal the shutdown event when
246 * requested to stop the Apache service), from the -k Apache command line,
247 * or from any external program which finds the Apache PID from the
250 * The signal_parent() function, below, is used to signal one of these events.
251 * It can be called by any child or parent process, since it does not
252 * rely on global variables.
254 * On entry, type gives the event to signal. 0 means shutdown, 1 means
257 static void signal_parent(int type)
261 extern char signal_shutdown_name[];
262 extern char signal_restart_name[];
264 /* after updating the shutdown_pending or restart flags, we need
265 * to wake up the parent process so it can see the changes. The
266 * parent will normally be waiting for either a child process
267 * to die, or for a signal on the "spache-signal" event. So set the
268 * "apache-signal" event here.
275 case 0: signal_name = signal_shutdown_name; break;
276 case 1: signal_name = signal_restart_name; break;
279 e = OpenEvent(EVENT_ALL_ACCESS, FALSE, signal_name);
281 /* Um, problem, can't signal the parent, which means we can't
282 * signal ourselves to die. Ignore for now...
284 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
285 "OpenEvent on %s event", signal_name);
288 if (SetEvent(e) == 0) {
289 /* Same problem as above */
290 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
291 "SetEvent on %s event", signal_name);
297 static int volatile is_graceful = 0;
298 API_EXPORT(int) ap_graceful_stop_signalled(void)
302 void ap_start_shutdown(void)
307 * Initialise the signal names, in the global variables signal_name_prefix,
308 * signal_restart_name and signal_shutdown_name.
311 #define MAX_SIGNAL_NAME 30 /* Long enough for apPID_shutdown, where PID is an int */
312 char signal_name_prefix[MAX_SIGNAL_NAME];
313 char signal_restart_name[MAX_SIGNAL_NAME];
314 char signal_shutdown_name[MAX_SIGNAL_NAME];
315 static void setup_signal_names(char *prefix)
317 ap_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);
318 ap_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name),
319 "%s_shutdown", signal_name_prefix);
320 ap_snprintf(signal_restart_name, sizeof(signal_restart_name),
321 "%s_restart", signal_name_prefix);
325 * Routines that deal with sockets, some are WIN32 specific...
327 static int s_iInitCount = 0;
328 static int AMCSocketInitialize(void)
330 int iVersionRequested;
334 if (s_iInitCount > 0) {
338 else if (s_iInitCount < 0)
339 return (s_iInitCount);
341 /* s_iInitCount == 0. Do the initailization */
342 iVersionRequested = MAKEWORD(2, 0);
343 err = WSAStartup((WORD) iVersionRequested, &wsaData);
346 return (s_iInitCount);
348 if (LOBYTE(wsaData.wVersion) != 1 ||
349 HIBYTE(wsaData.wVersion) != 1) {
352 return (s_iInitCount);
356 return (s_iInitCount);
359 static void AMCSocketCleanup(void)
361 if (--s_iInitCount == 0)
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;
390 static ap_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
395 for (lr = head_listener; lr ; lr = lr->next) {
396 ap_get_os_sock(&nsd, lr->sd);
397 if (FD_ISSET(nsd, main_fds)) {
398 head_listener = lr->next;
399 if (head_listener == NULL)
400 head_listener = ap_listeners;
407 static int setup_listeners(server_rec *s)
410 int num_listeners = 0;
413 /* Setup the listeners */
416 if (ap_listen_open(s->process, s->port)) {
419 for (lr = ap_listeners; lr; lr = lr->next) {
421 if (lr->sd != NULL) {
422 ap_get_os_sock(&nsd, lr->sd);
423 FD_SET(nsd, &listenfds);
424 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
431 head_listener = ap_listeners;
433 return num_listeners;
436 static int setup_inherited_listeners(server_rec *s)
438 WSAPROTOCOL_INFO WSAProtocolInfo;
442 int num_listeners = 0;
445 /* Setup the listeners */
448 /* Set up a default listener if necessary */
450 if (ap_listeners == NULL) {
452 lr = ap_palloc(s->process->pool, sizeof(ap_listen_rec));
456 lr->next = ap_listeners;
460 /* Open the pipe to the parent process to receive the inherited socket
461 * data. The sockets have been set to listening in the parent process.
463 pipe = GetStdHandle(STD_INPUT_HANDLE);
464 for (lr = ap_listeners; lr; lr = lr->next) {
465 if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
466 &BytesRead, (LPOVERLAPPED) NULL)) {
467 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
468 "setup_inherited_listeners: Unable to read socket data from parent");
469 signal_parent(0); /* tell parent to die */
472 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
473 "Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.", my_pid);
474 nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
475 &WSAProtocolInfo, 0, 0);
476 if (nsd == INVALID_SOCKET) {
477 ap_log_error(APLOG_MARK, APLOG_CRIT, WSAGetLastError(), server_conf,
478 "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
479 signal_parent(0); /* tell parent to die */
483 FD_SET(nsd, &listenfds);
484 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
488 // ap_register_cleanup(p, (void *)lr->sd, socket_cleanup, ap_null_cleanup);
489 ap_put_os_sock(&lr->sd, &nsd, pconf);
492 /* Now, read the AcceptExCompPort from the parent */
493 ReadFile(pipe, &AcceptExCompPort, sizeof(AcceptExCompPort), &BytesRead, (LPOVERLAPPED) NULL);
496 for (lr = ap_listeners; lr; lr = lr->next) {
500 head_listener = ap_listeners;
501 return num_listeners;
504 static void bind_listeners_to_completion_port()
506 /* Associate the open listeners with the completion port.
507 * Bypass the operation for Windows 95/98
511 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
512 for (lr = ap_listeners; lr; lr = lr->next) {
514 ap_get_os_sock(&nsd,lr->sd);
515 CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
520 /**********************************************************************
521 * Multithreaded implementation
523 * This code is fairly specific to Win32.
525 * The model used to handle requests is a set of threads. One "main"
526 * thread listens for new requests. When something becomes
527 * available, it does a select and places the newly available socket
528 * onto a list of "jobs" (add_job()). Then any one of a fixed number
529 * of "worker" threads takes the top job off the job list with
530 * remove_job() and handles that connection to completion. After
531 * the connection has finished the thread is free to take another
532 * job from the job list.
534 * In the code, the "main" thread is running within the child_main()
535 * function. The first thing this function does is create the
536 * worker threads, which operate in the child_sub_main() function. The
537 * main thread then goes into a loop within child_main() where they
538 * do a select() on the listening sockets. The select times out once
539 * per second so that the thread can check for an "exit" signal
540 * from the parent process (see below). If this signal is set, the
541 * thread can exit, but only after it has accepted all incoming
542 * connections already in the listen queue (since Win32 appears
543 * to through away listened but unaccepted connections when a
546 * Because the main and worker threads exist within a single process
547 * they are vulnerable to crashes or memory leaks (crashes can also
548 * be caused within modules, of course). There also needs to be a
549 * mechanism to perform restarts and shutdowns. This is done by
550 * creating the main & worker threads within a subprocess. A
551 * main process (the "parent process") creates one (or more)
552 * processes to do the work, then the parent sits around waiting
553 * for the working process to die, in which case it starts a new
554 * one. The parent process also handles restarts (by creating
555 * a new working process then signalling the previous working process
556 * exit ) and shutdowns (by signalling the working process to exit).
557 * The parent process operates within the master_main() function. This
558 * process also handles requests from the service manager (NT only).
560 * Signalling between the parent and working process uses a Win32
561 * event. Each child has a unique name for the event, which is
562 * passed to it with the -Z argument when the child is spawned. The
563 * parent sets (signals) this event to tell the child to die.
564 * At present all children do a graceful die - they finish all
565 * current jobs _and_ empty the listen queue before they exit.
566 * A non-graceful die would need a second event. The -Z argument in
567 * the child is also used to create the shutdown and restart events,
568 * since the prefix (apPID) contains the parent process PID.
570 * The code below starts with functions at the lowest level -
571 * worker threads, and works up to the top level - the main()
572 * function of the parent process.
574 * The scoreboard (in process memory) contains details of the worker
575 * threads (within the active working process). There is no shared
576 * "scoreboard" between processes, since only one is ever active
577 * at once (or at most, two, when one has been told to shutdown but
578 * is processes outstanding requests, and a new one has been started).
579 * This is controlled by a "start_mutex" which ensures only one working
580 * process is active at once.
581 **********************************************************************/
585 * Definition of jobs, shared by main and worker threads.
588 typedef struct joblist_s {
589 struct joblist_s *next;
594 * Globals common to main and worker threads. This structure is not
595 * used by the parent process.
598 typedef struct globals_s {
599 semaphore *jobsemaphore;
606 globals allowed_globals =
607 {NULL, NULL, NULL, NULL, 0};
608 #define MAX_SELECT_ERRORS 100
609 #define PADDED_ADDR_SIZE sizeof(SOCKADDR_IN)+16
611 /* Windows 9x specific code...
612 * Accept processing for on Windows 95/98 uses a producer/consumer queue
613 * model. A single thread accepts connections and queues the accepted socket
614 * to the accept queue for consumption by a pool of worker threads.
616 * win9x_get_connection()
617 * Calls remove_job() to pull a job from the accept queue. All the worker
618 * threads block on remove_job.
619 * accept_and_queue_connections()
620 * The accept threads runs this function, which accepts connections off
621 * the network and calls add_job() to queue jobs to the accept_queue.
622 * add_job()/remove_job()
623 * Add or remove an accepted socket from the list of sockets
624 * connected to clients. allowed_globals.jobmutex protects
625 * against multiple concurrent access to the linked list of jobs.
627 static void add_job(int sock)
631 new_job = (joblist *) malloc(sizeof(joblist));
632 if (new_job == NULL) {
633 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
634 "Ouch! Out of memory in add_job()!");
637 new_job->next = NULL;
638 new_job->sock = sock;
640 ap_lock(allowed_globals.jobmutex);
642 if (allowed_globals.jobtail != NULL)
643 allowed_globals.jobtail->next = new_job;
644 allowed_globals.jobtail = new_job;
645 if (!allowed_globals.jobhead)
646 allowed_globals.jobhead = new_job;
647 allowed_globals.jobcount++;
648 release_semaphore(allowed_globals.jobsemaphore);
650 ap_unlock(allowed_globals.jobmutex);
653 static int remove_job(void)
658 acquire_semaphore(allowed_globals.jobsemaphore);
659 ap_lock(allowed_globals.jobmutex);
661 if (workers_may_exit && !allowed_globals.jobhead) {
662 ap_unlock(allowed_globals.jobmutex);
665 job = allowed_globals.jobhead;
667 allowed_globals.jobhead = job->next;
668 if (allowed_globals.jobhead == NULL)
669 allowed_globals.jobtail = NULL;
670 ap_unlock(allowed_globals.jobmutex);
677 static void accept_and_queue_connections(void * dummy)
679 int requests_this_child = 0;
684 int nsd = INVALID_SOCKET;
685 struct sockaddr_in sa_client;
686 int count_select_errors = 0;
690 while (!workers_may_exit) {
691 if (ap_max_requests_per_child && (requests_this_child > ap_max_requests_per_child)) {
695 tv.tv_sec = wait_time;
697 memcpy(&main_fds, &listenfds, sizeof(fd_set));
699 // rc = ap_select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
700 rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
702 if (rc == 0 || (rc == SOCKET_ERROR && h_errno == WSAEINTR)) {
703 count_select_errors = 0; /* reset count of errors */
706 else if (rc == SOCKET_ERROR) {
707 /* A "real" error occurred, log it and increment the count of
708 * select errors. This count is used to ensure we don't go into
709 * a busy loop of continuous errors.
711 ap_log_error(APLOG_MARK, APLOG_INFO, h_errno, server_conf,
712 "select failed with errno %d", h_errno);
713 count_select_errors++;
714 if (count_select_errors > MAX_SELECT_ERRORS) {
715 workers_may_exit = 1;
716 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
717 "Too many errors in select loop. Child process exiting.");
723 lr = find_ready_listener(&main_fds);
725 /* fetch the native socket descriptor */
726 ap_get_os_sock(&nsd, lr->sd);
731 clen = sizeof(sa_client);
732 csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
733 if (csd == INVALID_SOCKET) {
736 } while (csd < 0 && h_errno == WSAEINTR);
739 if (h_errno != WSAECONNABORTED) {
740 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
741 "accept: (client socket)");
746 requests_this_child++;
749 SetEvent(exit_event);
751 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
755 if (context == NULL) {
756 /* allocate the completion context and the transaction pool */
757 context = ap_pcalloc(pconf, sizeof(COMP_CONTEXT));
759 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
760 "win9x_get_connection: ap_pcalloc() failed. Process will exit.");
763 ap_create_context(&context->ptrans, pconf);
768 ap_clear_pool(context->ptrans);
769 context->accept_socket = remove_job();
770 if (context->accept_socket == -1) {
773 //ap_note_cleanups_for_socket(ptrans, csd);
774 len = sizeof(struct sockaddr);
775 context->sa_server = ap_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, WSAGetLastError(), server_conf,
779 "getsockname failed");
782 len = sizeof(struct sockaddr);
783 context->sa_client = ap_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, h_errno, server_conf,
787 "getpeername failed with error %d\n", WSAGetLastError());
788 memset(&context->sa_client, '\0', sizeof(context->sa_client));
791 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
793 /* do we NEED_DUPPED_CSD ?? */
800 * Windows 2000/NT specific code...
801 * create_acceptex_context()
802 * reset_acceptex_context()
803 * drain_acceptex_complport()
804 * winnt_get_connection()
806 * TODO: Insert a discussion of 'completion contexts' and what these function do here...
808 static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp)
811 PCOMP_CONTEXT context;
819 rc = GetQueuedCompletionStatus(hComplPort, &BytesRead, &CompKey,
822 lastError = GetLastError();
823 if (lastError == ERROR_OPERATION_ABORTED) {
824 ap_log_error(APLOG_MARK,APLOG_INFO,lastError, server_conf,
825 "Child: %d - Draining a packet off the completion port.", my_pid);
830 ap_log_error(APLOG_MARK,APLOG_INFO,APR_SUCCESS, server_conf,
831 "Child: %d - Nuking an active connection. context = %x", my_pid, context);
832 context = (PCOMP_CONTEXT) pol;
833 if (context && bCleanUp) {
834 /* It is only valid to clean-up in the process that initiated the I/O */
835 closesocket(context->accept_socket);
836 CloseHandle(context->Overlapped.hEvent);
840 static int create_acceptex_context(ap_context_t *_pconf, ap_listen_rec *lr)
842 PCOMP_CONTEXT context;
847 /* allocate the completion context */
848 context = ap_pcalloc(_pconf, sizeof(COMP_CONTEXT));
850 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
851 "create_acceptex_context: ap_pcalloc() failed. Process will exit.");
855 /* initialize the completion context */
857 context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
858 if (context->Overlapped.hEvent == NULL) {
859 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
860 "create_acceptex_context: CreateEvent() failed. Process will exit.");
863 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
864 if (context->accept_socket == INVALID_SOCKET) {
865 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
866 "create_acceptex_context: socket() failed. Process will exit.");
869 ap_create_context(&context->ptrans, _pconf);
870 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
871 context->recv_buf = context->conn_io->inbase;
872 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
873 ap_get_os_sock(&nsd, context->lr->sd);
875 /* AcceptEx on the completion context. The completion context will be signaled
876 * when a connection is accepted. */
877 if (!AcceptEx(nsd, context->accept_socket,
879 0, //context->recv_buf_size,
880 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
882 (LPOVERLAPPED) context)) {
883 lasterror = WSAGetLastError();
884 if (lasterror != ERROR_IO_PENDING) {
885 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
886 "create_acceptex_context: AcceptEx failed. Process will exit.");
890 /* SO_UPDATE_ACCEPT_CONTEXT is a Microsoft-ism which is required
891 * if you want to use more than several key socket calls on a
892 * socket initialized via AcceptEx(). In particular, it is
893 * required for shutdown() to work.
896 if (setsockopt(context->accept_socket, SOL_SOCKET,
897 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
899 ap_log_error(APLOG_MARK, APLOG_ERR, WSAGetLastError(), server_conf,
900 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
908 static ap_inline int reset_acceptex_context(PCOMP_CONTEXT context)
914 context->lr->count++;
916 if (context->accept_socket == -1)
917 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
919 if (context->accept_socket == INVALID_SOCKET) {
920 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
921 "reset_acceptex_context: socket() failed. Process will exit.");
925 ap_clear_pool(context->ptrans);
926 context->sock = NULL;
927 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
928 context->recv_buf = context->conn_io->inbase;
929 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
930 ap_get_os_sock(&nsd, context->lr->sd);
932 if (!AcceptEx(nsd, context->accept_socket,
934 0, //context->recv_buf_size,
935 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
936 &BytesRead, (LPOVERLAPPED) context)) {
937 lasterror = WSAGetLastError();
938 if (lasterror != ERROR_IO_PENDING) {
939 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
940 "reset_acceptex_context: AcceptEx failed. Leaving the process running.");
944 /* SO_UPDATE_ACCEPT_CONTEXT is a Microsoft-ism which is required
945 * if you want to use more than several key socket calls on a
946 * socket initialized via AcceptEx(). In particular, it is
947 * required for shutdown() to work.
950 if (setsockopt(context->accept_socket, SOL_SOCKET,
951 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
953 ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(),
955 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
961 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
963 int requests_this_child = 0;
969 if (context != NULL) {
970 /* If child shutdown has been signaled, clean-up the completion context */
971 if (workers_may_exit) {
972 CloseHandle(context->Overlapped.hEvent);
976 context->accept_socket = -1; /* Don't reuse the accept_socket */
977 if (reset_acceptex_context(context) == -1) {
978 if (context->accept_socket != -1)
979 closesocket(context->accept_socket);
980 CloseHandle(context->Overlapped.hEvent);
987 rc = GetQueuedCompletionStatus(AcceptExCompPort,
993 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
994 "Child: %d - GetQueuedCompletionStatus() failed", my_pid);
999 context = (PCOMP_CONTEXT) pol;
1000 if (CompKey == 999) {
1004 /* Each listener needs at least 1 context available to receive connections on.
1005 * Create additional listener contexts if needed.
1007 ap_lock(allowed_globals.jobmutex);
1008 context->lr->count--;
1009 if ((context->lr->count < 2) && !workers_may_exit) {
1010 if (create_acceptex_context(pconf, context->lr) == -1) {
1011 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1012 "Unable to create an AcceptEx completion context -- process will exit");
1017 ap_unlock(allowed_globals.jobmutex);
1019 /* Received a connection */
1020 context->conn_io->incnt = BytesRead;
1021 GetAcceptExSockaddrs(context->recv_buf,
1022 0, //context->recv_buf_size,
1025 &context->sa_server,
1026 &context->sa_server_len,
1027 &context->sa_client,
1028 &context->sa_client_len);
1034 * worker_main() - this is the main loop for the worker threads
1037 * Each thread runs within this function. They wait within remove_job()
1038 * for a job to become available, then handle all the requests on that
1039 * connection until it is closed, then return to remove_job().
1041 * The worker thread will exit when it removes a job which contains
1042 * socket number -1. This provides a graceful thread exit, since
1043 * it will never exit during a connection.
1045 * This code in this function is basically equivalent to the child_main()
1046 * from the multi-process (Unix) environment, except that we
1048 * - do not call child_init_modules (child init API phase)
1049 * - block in remove_job, and when unblocked we have an already
1050 * accepted socket, instead of blocking on a mutex or select().
1053 static void worker_main(int child_num)
1055 static BOOLEAN bListenersStarted = FALSE;
1056 PCOMP_CONTEXT context = NULL;
1058 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1059 /* Windows NT/2000: Create AcceptEx completion contexts for each of the
1062 ap_lock(allowed_globals.jobmutex);
1063 if (!bListenersStarted) {
1066 bListenersStarted = TRUE;
1067 for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1068 for(i=0; i<2; i++) {
1070 if (create_acceptex_context(pconf, lr) == -1) {
1071 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1072 "Unable to create an AcceptEx completion context -- process will exit");
1073 signal_parent(0); /* tell parent to die */
1078 ap_unlock(allowed_globals.jobmutex);
1082 conn_rec *current_conn;
1085 /* Grab a connection off the network */
1086 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1087 context = win9x_get_connection(context);
1090 context = winnt_get_connection(context);
1095 sock_disable_nagle(context->accept_socket);
1096 ap_put_os_sock(&context->sock, &context->accept_socket, context->ptrans);
1097 ap_register_cleanup(context->ptrans, context->sock, socket_cleanup, ap_null_cleanup);
1098 iol = win32_attach_socket(context->ptrans, context->sock);
1100 ap_log_error(APLOG_MARK, APLOG_ERR, APR_ENOMEM, server_conf,
1101 "worker_main: attach_socket() failed. Continuing...");
1102 closesocket(context->accept_socket);
1105 ap_bpush_iol(context->conn_io, iol);
1106 current_conn = ap_new_connection(context->ptrans, server_conf, context->conn_io,
1107 (struct sockaddr_in *) context->sa_client,
1108 (struct sockaddr_in *) context->sa_server,
1111 ap_process_connection(current_conn);
1114 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1115 "child_main: Setting exit_event");
1116 SetEvent(exit_event);
1118 /* TODO: Add code to clean-up completion contexts here */
1121 static void cleanup_thread(thread **handles, int *thread_cnt, int thread_to_clean)
1125 CloseHandle(handles[thread_to_clean]);
1126 for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1127 handles[i] = handles[i + 1];
1134 * child_main() is main loop for the child process. The loop in
1135 * this function becomes the controlling thread for the actually working
1136 * threads (which run in a loop in child_sub_main()).
1138 * exit_event, start_mutex, ap_threads_per_child, server_conf,
1139 * h_errno defined to WSAGetLastError in winsock2.h,
1141 static void child_main()
1143 char* exit_event_name;
1144 int nthreads = ap_threads_per_child;
1146 thread **child_handles;
1151 ap_context_t *pchild;
1153 /* This is the child process or we are running in single process
1157 exit_event_name = ap_psprintf(pconf, "apC%d", my_pid);
1158 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1161 /* Single process mode */
1162 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1163 exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1165 setup_listeners(server_conf);
1166 bind_listeners_to_completion_port();
1169 /* Child process mode */
1170 ap_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1171 exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1172 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1173 "Child %d: exit_event_name = %s", my_pid, exit_event_name);
1175 setup_inherited_listeners(server_conf);
1177 ap_assert(start_mutex);
1178 ap_assert(exit_event);
1180 ap_create_context(&pchild, pconf);
1183 if (listenmaxfd == INVALID_SOCKET) {
1184 /* No sockets were made, better log something and exit */
1185 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, NULL,
1186 "No sockets were created for listening");
1187 signal_parent(0); /* tell parent to die */
1188 ap_destroy_context(pchild);
1192 allowed_globals.jobsemaphore = create_semaphore(0);
1193 ap_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
1196 * Wait until we have permission to start accepting connections.
1197 * start_mutex is used to ensure that only one child ever
1198 * goes into the listen/accept loop at once.
1200 status = ap_lock(start_mutex);
1201 if (status != APR_SUCCESS) {
1202 ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
1203 "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1204 signal_parent(0); /* tell parent to die */
1205 ap_destroy_context(pchild);
1208 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, "Child %d: Acquired the start mutex", my_pid);
1210 /* Create the worker thread pool */
1211 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, "Child %d: Creating %d worker threads",my_pid, nthreads);
1212 child_handles = (thread *) alloca(nthreads * sizeof(int));
1213 for (i = 0; i < nthreads; i++) {
1214 child_handles[i] = (thread *) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1215 NULL, 0, &thread_id);
1218 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1219 /* Win95/98: Create the accept thread */
1220 _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) accept_and_queue_connections,
1221 (void *) i, 0, &thread_id);
1224 /* Wait for the exit event to be signaled by the parent process */
1225 rv = WaitForSingleObject(exit_event, INFINITE);
1227 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1228 "Child %d: Exit event signaled. Child process is ending.", my_pid);
1229 workers_may_exit = 1;
1231 /* Shutdown the worker threads */
1232 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1233 for (i = 0; i < nthreads; i++) {
1237 else { /* Windows NT/2000 */
1238 /* Hack alert... Give the server a couple of seconds to receive
1239 * connections and drain AcceptEx completion contexts. We will
1240 * probably drop a few connections across a graceful restart, but
1241 * hopefully not many. This needs work...*/
1244 /* Tell the worker threads to exit. Any connections accepted on
1245 * the completion port from now will be dropped */
1246 for (i=0; i < nthreads; i++) {
1247 if (!PostQueuedCompletionStatus(AcceptExCompPort, 0, 999, NULL)) {
1248 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1249 "PostQueuedCompletionStatus failed");
1254 /* Wait for the worker threads to die */
1255 end_time = time(NULL) + 180;
1257 rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1258 if (rv != WAIT_TIMEOUT) {
1259 rv = rv - WAIT_OBJECT_0;
1260 ap_assert((rv >= 0) && (rv < nthreads));
1261 cleanup_thread(child_handles, &nthreads, rv);
1266 for (i = 0; i < nthreads; i++) {
1267 TerminateThread(child_handles[i], 1);
1268 CloseHandle(child_handles[i]);
1270 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1271 "Child %d: All worker threads have ended.", my_pid);
1273 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1274 /* All the worker threads should have exited by now, which will
1275 * cause any outstanding I/O on the completion port to be aborted.
1276 * Drain the completion port of this aborted I/O/
1278 drain_acceptex_complport(AcceptExCompPort, TRUE);
1281 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1282 "Child %d: Releasing the start mutex", my_pid);
1283 ap_unlock(start_mutex);
1285 /* Still need to register cleanups for the sockets */
1286 CloseHandle(AcceptExCompPort);
1287 destroy_semaphore(allowed_globals.jobsemaphore);
1288 ap_destroy_lock(allowed_globals.jobmutex);
1290 ap_destroy_context(pchild);
1291 CloseHandle(exit_event);
1295 * Spawn a child Apache process. The child process has the command line arguments from
1296 * argc and argv[], plus a -Z argument giving the name of an event. The child should
1297 * open and poll or wait on this event. When it is signalled, the child should die.
1298 * prefix is a prefix string for the event name.
1300 * The child_num argument on entry contains a serial number for this child (used to create
1301 * a unique event name). On exit, this number will have been incremented by one, ready
1302 * for the next call.
1304 * On exit, the value pointed to be *ev will contain the event created
1305 * to signal the new child process.
1307 * The return value is the handle to the child process if successful, else -1. If -1 is
1308 * returned the error will already have been logged by ap_log_error().
1311 /**********************************************************************
1312 * master_main - this is the parent (main) process. We create a
1313 * child process to do the work, then sit around waiting for either
1314 * the child to exit, or a restart or exit signal. If the child dies,
1315 * we just respawn a new one. If we have a shutdown or graceful restart,
1316 * tell the child to die when it is ready. If it is a non-graceful
1317 * restart, force the child to die immediately.
1318 **********************************************************************/
1320 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1322 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1327 CloseHandle(handles[position]);
1328 CloseHandle(events[position]);
1330 handle = (int)handles[position];
1332 for (i = position; i < (*processes)-1; i++) {
1333 handles[i] = handles[i + 1];
1334 events[i] = events[i + 1];
1339 static int create_process(ap_context_t *p, HANDLE *handles, HANDLE *events, int *processes)
1346 STARTUPINFO si; /* Filled in prior to call to CreateProcess */
1347 PROCESS_INFORMATION pi; /* filled in on call to CreateProces */
1351 HANDLE hPipeRead = NULL;
1352 HANDLE hPipeWrite = NULL;
1353 SECURITY_ATTRIBUTES sa = {0};
1355 sa.nLength = sizeof(sa);
1356 sa.bInheritHandle = TRUE;
1357 sa.lpSecurityDescriptor = NULL;
1359 /* Build the command line. Should look something like this:
1360 * C:/apache/bin/apache.exe -f ap_server_confname
1361 * First, get the path to the executable...
1363 rv = GetModuleFileName(NULL, buf, sizeof(buf));
1364 if (rv == sizeof(buf)) {
1365 ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1366 "Parent: Path to Apache process too long");
1368 } else if (rv == 0) {
1369 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1370 "Parent: GetModuleFileName() returned NULL for current process.");
1374 /* Build the command line */
1375 pCommand = ap_psprintf(p, "\"%s\"", buf);
1376 for (i = 1; i < server_conf->process->argc; i++) {
1377 pCommand = ap_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1380 /* Create a pipe to send socket info to the child */
1381 if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1382 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1383 "Parent: Unable to create pipe to child process.\n");
1387 SetEnvironmentVariable("AP_PARENT_PID",ap_psprintf(p,"%d",parent_pid));
1389 /* Give the read end of the pipe (hPipeRead) to the child as stdin. The
1390 * parent will write the socket data to the child on this pipe.
1392 memset(&si, 0, sizeof(si));
1393 memset(&pi, 0, sizeof(pi));
1395 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1396 si.wShowWindow = SW_HIDE;
1397 si.hStdInput = hPipeRead;
1399 if (!CreateProcess(NULL, pCommand, NULL, NULL,
1400 TRUE, /* Inherit handles */
1401 CREATE_SUSPENDED, /* Creation flags */
1402 NULL, /* Environment block */
1405 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1406 "Parent: Not able to create the child process.");
1408 * We must close the handles to the new process and its main thread
1409 * to prevent handle and memory leaks.
1411 CloseHandle(pi.hProcess);
1412 CloseHandle(pi.hThread);
1417 LPWSAPROTOCOL_INFO lpWSAProtocolInfo;
1418 HANDLE hDupedCompPort;
1420 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1421 "Parent: Created child process %d", pi.dwProcessId);
1423 SetEnvironmentVariable("AP_PARENT_PID",NULL);
1425 /* Create the exit_event, apCchild_pid */
1426 sa.nLength = sizeof(sa);
1427 sa.bInheritHandle = TRUE;
1428 sa.lpSecurityDescriptor = NULL;
1429 kill_event = CreateEvent(&sa, TRUE, FALSE, ap_psprintf(pconf,"apC%d", pi.dwProcessId));
1431 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1432 "Parent: Could not create exit event for child process");
1433 CloseHandle(pi.hProcess);
1434 CloseHandle(pi.hThread);
1438 /* Assume the child process lives. Update the process and event tables */
1439 handles[*processes] = pi.hProcess;
1440 events[*processes] = kill_event;
1443 /* We never store the thread's handle, so close it now. */
1444 ResumeThread(pi.hThread);
1445 CloseHandle(pi.hThread);
1447 /* Run the chain of open sockets. For each socket, duplicate it
1448 * for the target process then send the WSAPROTOCOL_INFO
1449 * (returned by dup socket) to the child */
1450 for (lr = ap_listeners; lr; lr = lr->next) {
1452 lpWSAProtocolInfo = ap_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1453 ap_get_os_sock(&nsd,lr->sd);
1454 ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_INFO, APR_SUCCESS, server_conf,
1455 "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1456 if (WSADuplicateSocket(nsd, pi.dwProcessId,
1457 lpWSAProtocolInfo) == SOCKET_ERROR) {
1458 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, server_conf,
1459 "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1463 if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1465 (LPOVERLAPPED) NULL)) {
1466 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1467 "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1470 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1471 "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1473 /* Now, send the AcceptEx completion port to the child */
1474 if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort,
1475 pi.hProcess, &hDupedCompPort, 0,
1476 TRUE, DUPLICATE_SAME_ACCESS)) {
1477 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1478 "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1481 WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1484 CloseHandle(hPipeRead);
1485 CloseHandle(hPipeWrite);
1490 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1492 int remaining_children_to_start = ap_daemons_to_start;
1496 int restart_pending = 0;
1497 int shutdown_pending = 0;
1498 int current_live_processes = 0; /* number of child process we know about */
1500 HANDLE process_handles[MAX_PROCESSES];
1501 HANDLE process_kill_events[MAX_PROCESSES];
1504 bind_listeners_to_completion_port();
1506 /* Create child process
1507 * Should only be one in this version of Apache for WIN32
1509 service_set_status(SERVICE_START_PENDING);
1510 while (remaining_children_to_start--) {
1511 if (create_process(pconf, process_handles, process_kill_events,
1512 ¤t_live_processes) < 0) {
1513 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1514 "master_main: create child process failed. Exiting.");
1515 shutdown_pending = 1;
1519 service_set_status(SERVICE_RUNNING);
1521 restart_pending = shutdown_pending = 0;
1523 /* Wait for shutdown or restart events or for child death */
1524 process_handles[current_live_processes] = shutdown_event;
1525 process_handles[current_live_processes+1] = restart_event;
1526 printf("process/shutdown/restart %d %d %d\n", process_handles[0], process_handles[1], process_handles[2]);
1527 rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles,
1529 cld = rv - WAIT_OBJECT_0;
1530 if (rv == WAIT_FAILED) {
1531 /* Something serious is wrong */
1532 ap_log_error(APLOG_MARK,APLOG_CRIT, GetLastError(), server_conf,
1533 "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1534 shutdown_pending = 1;
1536 else if (rv == WAIT_TIMEOUT) {
1537 /* Hey, this cannot happen */
1538 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1539 "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1540 shutdown_pending = 1;
1542 else if (cld == current_live_processes) {
1543 /* shutdown_event signalled */
1544 shutdown_pending = 1;
1545 printf("shutdown event signaled\n");
1546 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1547 "master_main: Shutdown event signaled -- doing server shutdown.");
1548 if (ResetEvent(shutdown_event) == 0) {
1549 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1550 "ResetEvent(shutdown_event)");
1554 else if (cld == current_live_processes+1) {
1555 /* restart_event signalled */
1556 int children_to_kill = current_live_processes;
1557 restart_pending = 1;
1558 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1559 "master_main: Restart event signaled. Doing a graceful restart.");
1560 if (ResetEvent(restart_event) == 0) {
1561 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1562 "master_main: ResetEvent(restart_event) failed.");
1564 /* Signal each child process to die
1565 * We are making a big assumption here that the child process, once signaled,
1566 * will REALLY go away. Since this is a restart, we do not want to hold the
1567 * new child process up waiting for the old child to die. Remove the old
1568 * child out of the process_handles ap_table_t and hope for the best...
1570 for (i = 0; i < children_to_kill; i++) {
1571 printf("SetEvent handle = %d\n", process_kill_events[i]);
1572 if (SetEvent(process_kill_events[i]) == 0)
1573 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1574 "master_main: SetEvent for child process in slot #%d failed", i);
1575 cleanup_process(process_handles, process_kill_events, i, ¤t_live_processes);
1579 /* A child process must have exited because of a fatal error condition (seg fault, etc.).
1580 * Remove the dead process
1581 * from the process_handles and process_kill_events ap_table_t and create a new
1583 * TODO: Consider restarting the child immediately without looping through http_main
1584 * and without rereading the configuration. Will need this if we ever support multiple
1585 * children. One option, create a parent thread which waits on child death and restarts it.
1587 restart_pending = 1;
1588 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1589 "master_main: Child process failed. Restarting the child process.");
1590 ap_assert(cld < current_live_processes);
1591 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1592 /* APD2("main_process: child in slot %d died", rv); */
1593 /* restart_child(process_hancles, process_kill_events, cld, ¤t_live_processes); */
1595 /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead
1597 drain_acceptex_complport(AcceptExCompPort, FALSE);
1601 if (shutdown_pending) {
1602 int tmstart = time(NULL);
1603 /* Signal each child processes to die */
1604 for (i = 0; i < current_live_processes; i++) {
1605 printf("SetEvent handle = %d\n", process_kill_events[i]);
1606 if (SetEvent(process_kill_events[i]) == 0)
1607 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1608 "master_main: SetEvent for child process in slot #%d failed", i);
1611 while (current_live_processes && ((tmstart+60) > time(NULL))) {
1612 rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1613 if (rv == WAIT_TIMEOUT)
1615 ap_assert(rv != WAIT_FAILED);
1616 cld = rv - WAIT_OBJECT_0;
1617 ap_assert(rv < current_live_processes);
1618 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1620 for (i = 0; i < current_live_processes; i++) {
1621 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1622 "forcing termination of child #%d (handle %d)", i, process_handles[i]);
1623 TerminateProcess((HANDLE) process_handles[i], 1);
1625 return 0; /* Tell the caller we do not want to restart */
1628 return 1; /* Tell the caller we want a restart */
1632 * winnt_pre_config() hook
1634 static void winnt_pre_config(ap_context_t *pconf, ap_context_t *plog, ap_context_t *ptemp)
1638 one_process = !!getenv("ONE_PROCESS");
1640 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1641 GetVersionEx(&osver);
1643 /* AP_PARENT_PID is only valid in the child */
1644 pid = getenv("AP_PARENT_PID");
1646 /* This is the child */
1647 parent_pid = atoi(pid);
1651 /* This is the parent */
1652 parent_pid = my_pid = getpid();
1656 ap_listen_pre_config();
1657 ap_daemons_to_start = DEFAULT_NUM_DAEMON;
1658 ap_threads_per_child = DEFAULT_START_THREAD;
1659 ap_pid_fname = DEFAULT_PIDLOG;
1660 max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1662 ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1666 static void winnt_post_config(ap_context_t *pconf, ap_context_t *plog, ap_context_t *ptemp, server_rec* server_conf)
1668 server_conf = server_conf;
1671 API_EXPORT(int) ap_mpm_run(ap_context_t *_pconf, ap_context_t *plog, server_rec *s )
1673 static int restart = 0; /* Default is "not a restart" */
1675 static HANDLE shutdown_event; /* used to signal shutdown to parent */
1676 static HANDLE restart_event; /* used to signal a restart to parent */
1681 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1682 /* Create the the IoCompletionPort in the parent */
1683 if ((parent_pid == my_pid) || one_process) {
1684 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1687 0); /* CONCURRENT ACTIVE THREADS */
1688 if (AcceptExCompPort == NULL) {
1689 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1690 "Unable to create the AcceptExCompletionPort -- process will exit");
1696 if ((parent_pid != my_pid) || one_process) {
1697 /* Running as Child process or in one_process (debug) mode */
1698 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1699 "Child %d: Child process is running", my_pid);
1700 AMCSocketInitialize();
1703 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1704 "Child %d: Child process is exiting", my_pid);
1706 return 1; /* Shutdown */
1709 /* Parent process */
1710 PSECURITY_ATTRIBUTES sa = GetNullACL(); /* returns NULL if invalid (Win95?) */
1712 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1714 /* This code only needs to be run once in the parent and
1715 * should not be run across a restart
1717 ap_log_pid(pconf, ap_pid_fname);
1719 service_set_status(SERVICE_START_PENDING);
1720 AMCSocketInitialize();
1721 // setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1723 /* Create shutdown event, apPID_shutdown, where PID is the parent
1724 * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
1726 shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
1727 if (!shutdown_event) {
1728 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), s,
1729 "master_main: Cannot create shutdown event %s", signal_shutdown_name);
1730 CleanNullACL((void *)sa);
1731 return 1; /* Shutdown */
1734 /* Create restart event, apPID_restart, where PID is the parent
1735 * Apache process ID. Restart is signaled by 'apache -k restart'.
1737 // restart_event = CreateEvent(sa, TRUE, FALSE, signal_restart_name);
1738 restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
1739 if (!restart_event) {
1740 CloseHandle(shutdown_event);
1741 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), s,
1742 "ap_run_mpm: Cannot create restart event %s", signal_restart_name);
1743 CleanNullACL((void *)sa);
1744 return 1; /* Shutdown */
1746 CleanNullACL((void *)sa);
1748 /* Create the start mutex, apPID, where PID is the parent Apache process ID.
1749 * Ths start mutex is used during a restart to prevent more than one
1750 * child process from entering the accept loop at once.
1752 // ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1753 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,s->process->pool);
1754 /* TODO: Add some code to detect failure */
1758 restart = master_main(server_conf, shutdown_event, restart_event);
1761 /* Shutting down. Clean up... */
1762 const char *pidfile = NULL;
1764 pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1765 if ( pidfile != NULL && unlink(pidfile) == 0) {
1766 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO,APR_SUCCESS,
1767 server_conf, "removed PID file %s (pid=%ld)",
1768 pidfile, (long)getpid());
1770 ap_destroy_lock(start_mutex);
1772 CloseHandle(restart_event);
1773 CloseHandle(shutdown_event);
1776 service_set_status(SERVICE_STOPPED);
1778 return 1; /* Shutdown */
1782 return 0; /* Restart */
1785 static void winnt_hooks(void)
1789 /* Configuration hooks implemented by http_config.c ... */
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_context_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 */