1 /* ====================================================================
2 * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in
13 * the documentation and/or other materials provided with the
16 * 3. All advertising materials mentioning features or use of this
17 * software must display the following acknowledgment:
18 * "This product includes software developed by the Apache Group
19 * for use in the Apache HTTP server project (http://www.apache.org/)."
21 * 4. The names "Apache Server" and "Apache Group" must not be used to
22 * endorse or promote products derived from this software without
23 * prior written permission. For written permission, please contact
26 * 5. Products derived from this software may not be called "Apache"
27 * nor may "Apache" appear in their names without prior written
28 * permission of the Apache Group.
30 * 6. Redistributions of any form whatsoever must retain the following
32 * "This product includes software developed by the Apache Group
33 * for use in the Apache HTTP server project (http://www.apache.org/)."
35 * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
36 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46 * OF THE POSSIBILITY OF SUCH DAMAGE.
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Group and was originally based
51 * on public domain software written at the National Center for
52 * Supercomputing Applications, University of Illinois, Urbana-Champaign.
53 * For more information on the Apache Group and the Apache HTTP server
54 * project, please see <http://www.apache.org/>.
59 #include "apr_portable.h"
61 #include "http_main.h"
63 #include "http_config.h" /* for read_config */
64 #include "http_core.h" /* for get_remote_host */
65 #include "http_connection.h"
67 #include "ap_config.h"
68 #include "ap_listen.h"
69 #include "mpm_default.h"
71 #include "iol_socket.h"
76 * Definitions of WINNT MPM specific config globals
79 static char *ap_pid_fname = NULL;
80 static int ap_threads_per_child = 0;
81 static int workers_may_exit = 0;
82 static int max_requests_per_child = 0;
84 static struct fd_set listenfds;
85 static int num_listenfds = 0;
86 static SOCKET listenmaxfd = INVALID_SOCKET;
88 static ap_context_t *pconf; /* Pool for config stuff */
90 static char ap_coredump_dir[MAX_STRING_LEN];
92 static server_rec *server_conf;
93 static HANDLE AcceptExCompPort = NULL;
95 static int one_process = 0;
97 static OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
99 int ap_max_requests_per_child=0;
100 int ap_daemons_to_start=0;
102 static event *exit_event;
103 ap_lock_t *start_mutex;
107 static ap_status_t socket_cleanup(void *sock)
109 struct socket_t *thesocket = sock;
111 if (ap_get_os_sock(&sd, thesocket) == APR_SUCCESS) {
117 /* A bunch or routines from os/win32/multithread.c that need to be merged into APR
118 * or thrown out entirely...
130 return(MULTI_TIMEOUT);
141 typedef void semaphore;
145 create_semaphore(int initial)
147 return(CreateSemaphore(NULL, initial, 1000000, NULL));
150 static int acquire_semaphore(semaphore *semaphore_id)
154 rv = WaitForSingleObject(semaphore_id, INFINITE);
159 static int release_semaphore(semaphore *semaphore_id)
161 return(ReleaseSemaphore(semaphore_id, 1, NULL));
164 static void destroy_semaphore(semaphore *semaphore_id)
166 CloseHandle(semaphore_id);
170 /* To share the semaphores with other processes, we need a NULL ACL
171 * Code from MS KB Q106387
173 static PSECURITY_ATTRIBUTES GetNullACL()
175 PSECURITY_DESCRIPTOR pSD;
176 PSECURITY_ATTRIBUTES sa;
178 sa = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES));
179 pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,
180 SECURITY_DESCRIPTOR_MIN_LENGTH);
181 if (pSD == NULL || sa == NULL) {
184 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
190 if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
196 sa->nLength = sizeof(sa);
197 sa->lpSecurityDescriptor = pSD;
198 sa->bInheritHandle = TRUE;
202 static void CleanNullACL( void *sa ) {
204 LocalFree( ((PSECURITY_ATTRIBUTES)sa)->lpSecurityDescriptor);
210 * The Win32 call WaitForMultipleObjects will only allow you to wait for
211 * a maximum of MAXIMUM_WAIT_OBJECTS (current 64). Since the threading
212 * model in the multithreaded version of apache wants to use this call,
213 * we are restricted to a maximum of 64 threads. This is a simplistic
214 * routine that will increase this size.
216 static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles,
220 DWORD dwRet = WAIT_TIMEOUT;
224 tStopTime = time(NULL) + dwSeconds;
232 for (dwIndex = 0; dwIndex * MAXIMUM_WAIT_OBJECTS < nCount; dwIndex++) {
233 dwRet = WaitForMultipleObjects(
234 min(MAXIMUM_WAIT_OBJECTS, nCount - (dwIndex * MAXIMUM_WAIT_OBJECTS)),
235 lpHandles + (dwIndex * MAXIMUM_WAIT_OBJECTS),
238 if (dwRet != WAIT_TIMEOUT) {
242 } while((time(NULL) < tStopTime) && (dwRet == WAIT_TIMEOUT));
248 * Signalling Apache on NT.
250 * Under Unix, Apache can be told to shutdown or restart by sending various
251 * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
252 * we use "events" instead. The parent apache process goes into a loop
253 * where it waits forever for a set of events. Two of those events are
259 * (where PID is the PID of the apache parent process). When one of these
260 * is signalled, the Apache parent performs the appropriate action. The events
261 * can become signalled through internal Apache methods (e.g. if the child
262 * finds a fatal error and needs to kill its parent), via the service
263 * control manager (the control thread will signal the shutdown event when
264 * requested to stop the Apache service), from the -k Apache command line,
265 * or from any external program which finds the Apache PID from the
268 * The signal_parent() function, below, is used to signal one of these events.
269 * It can be called by any child or parent process, since it does not
270 * rely on global variables.
272 * On entry, type gives the event to signal. 0 means shutdown, 1 means
275 static void signal_parent(int type)
279 extern char signal_shutdown_name[];
280 extern char signal_restart_name[];
282 /* after updating the shutdown_pending or restart flags, we need
283 * to wake up the parent process so it can see the changes. The
284 * parent will normally be waiting for either a child process
285 * to die, or for a signal on the "spache-signal" event. So set the
286 * "apache-signal" event here.
293 case 0: signal_name = signal_shutdown_name; break;
294 case 1: signal_name = signal_restart_name; break;
297 e = OpenEvent(EVENT_ALL_ACCESS, FALSE, signal_name);
299 /* Um, problem, can't signal the parent, which means we can't
300 * signal ourselves to die. Ignore for now...
302 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
303 "OpenEvent on %s event", signal_name);
306 if (SetEvent(e) == 0) {
307 /* Same problem as above */
308 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
309 "SetEvent on %s event", signal_name);
315 static int volatile is_graceful = 0;
316 API_EXPORT(int) ap_graceful_stop_signalled(void)
320 void ap_start_shutdown(void)
325 * Initialise the signal names, in the global variables signal_name_prefix,
326 * signal_restart_name and signal_shutdown_name.
329 #define MAX_SIGNAL_NAME 30 /* Long enough for apPID_shutdown, where PID is an int */
330 char signal_name_prefix[MAX_SIGNAL_NAME];
331 char signal_restart_name[MAX_SIGNAL_NAME];
332 char signal_shutdown_name[MAX_SIGNAL_NAME];
333 static void setup_signal_names(char *prefix)
335 ap_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);
336 ap_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name),
337 "%s_shutdown", signal_name_prefix);
338 ap_snprintf(signal_restart_name, sizeof(signal_restart_name),
339 "%s_restart", signal_name_prefix);
343 * Routines that deal with sockets, some are WIN32 specific...
345 static int s_iInitCount = 0;
346 static int AMCSocketInitialize(void)
348 int iVersionRequested;
352 if (s_iInitCount > 0) {
356 else if (s_iInitCount < 0)
357 return (s_iInitCount);
359 /* s_iInitCount == 0. Do the initailization */
360 iVersionRequested = MAKEWORD(2, 0);
361 err = WSAStartup((WORD) iVersionRequested, &wsaData);
364 return (s_iInitCount);
366 if (LOBYTE(wsaData.wVersion) != 1 ||
367 HIBYTE(wsaData.wVersion) != 1) {
370 return (s_iInitCount);
374 return (s_iInitCount);
377 static void AMCSocketCleanup(void)
379 if (--s_iInitCount == 0)
384 static void sock_disable_nagle(int s)
386 /* The Nagle algorithm says that we should delay sending partial
387 * packets in hopes of getting more data. We don't want to do
388 * this; we are not telnet. There are bad interactions between
389 * persistent connections and Nagle's algorithm that have very severe
390 * performance penalties. (Failing to disable Nagle is not much of a
391 * problem with simple HTTP.)
393 * In spite of these problems, failure here is not a shooting offense.
397 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
399 ap_log_error(APLOG_MARK, APLOG_WARNING, APR_SUCCESS, server_conf,
400 "setsockopt: (TCP_NODELAY)");
405 * Routines to deal with managing the list of listening sockets.
407 static ap_listen_rec *head_listener;
408 static ap_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
413 for (lr = head_listener; lr ; lr = lr->next) {
414 ap_get_os_sock(&nsd, lr->sd);
415 if (FD_ISSET(nsd, main_fds)) {
416 head_listener = lr->next;
417 if (head_listener == NULL)
418 head_listener = ap_listeners;
425 static int setup_listeners(server_rec *s)
428 int num_listeners = 0;
431 /* Setup the listeners */
434 if (ap_listen_open(s->process, s->port)) {
437 for (lr = ap_listeners; lr; lr = lr->next) {
439 if (lr->sd != NULL) {
440 ap_get_os_sock(&nsd, lr->sd);
441 FD_SET(nsd, &listenfds);
442 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
449 head_listener = ap_listeners;
451 return num_listeners;
454 static int setup_inherited_listeners(server_rec *s)
456 WSAPROTOCOL_INFO WSAProtocolInfo;
460 int num_listeners = 0;
463 /* Setup the listeners */
466 /* Set up a default listener if necessary */
468 if (ap_listeners == NULL) {
470 lr = ap_palloc(s->process->pool, sizeof(ap_listen_rec));
474 lr->next = ap_listeners;
478 /* Open the pipe to the parent process to receive the inherited socket
479 * data. The sockets have been set to listening in the parent process.
481 pipe = GetStdHandle(STD_INPUT_HANDLE);
482 for (lr = ap_listeners; lr; lr = lr->next) {
483 if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
484 &BytesRead, (LPOVERLAPPED) NULL)) {
485 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
486 "setup_inherited_listeners: Unable to read socket data from parent");
487 signal_parent(0); /* tell parent to die */
490 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
491 "Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.", my_pid);
492 nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
493 &WSAProtocolInfo, 0, 0);
494 if (nsd == INVALID_SOCKET) {
495 ap_log_error(APLOG_MARK, APLOG_CRIT, WSAGetLastError(), server_conf,
496 "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
497 signal_parent(0); /* tell parent to die */
501 FD_SET(nsd, &listenfds);
502 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
506 // ap_register_cleanup(p, (void *)lr->sd, socket_cleanup, ap_null_cleanup);
507 ap_put_os_sock(&lr->sd, &nsd, pconf);
510 /* Now, read the AcceptExCompPort from the parent */
511 ReadFile(pipe, &AcceptExCompPort, sizeof(AcceptExCompPort), &BytesRead, (LPOVERLAPPED) NULL);
514 for (lr = ap_listeners; lr; lr = lr->next) {
518 head_listener = ap_listeners;
519 return num_listeners;
523 /**********************************************************************
524 * Multithreaded implementation
526 * This code is fairly specific to Win32.
528 * The model used to handle requests is a set of threads. One "main"
529 * thread listens for new requests. When something becomes
530 * available, it does a select and places the newly available socket
531 * onto a list of "jobs" (add_job()). Then any one of a fixed number
532 * of "worker" threads takes the top job off the job list with
533 * remove_job() and handles that connection to completion. After
534 * the connection has finished the thread is free to take another
535 * job from the job list.
537 * In the code, the "main" thread is running within the child_main()
538 * function. The first thing this function does is create the
539 * worker threads, which operate in the child_sub_main() function. The
540 * main thread then goes into a loop within child_main() where they
541 * do a select() on the listening sockets. The select times out once
542 * per second so that the thread can check for an "exit" signal
543 * from the parent process (see below). If this signal is set, the
544 * thread can exit, but only after it has accepted all incoming
545 * connections already in the listen queue (since Win32 appears
546 * to through away listened but unaccepted connections when a
549 * Because the main and worker threads exist within a single process
550 * they are vulnerable to crashes or memory leaks (crashes can also
551 * be caused within modules, of course). There also needs to be a
552 * mechanism to perform restarts and shutdowns. This is done by
553 * creating the main & worker threads within a subprocess. A
554 * main process (the "parent process") creates one (or more)
555 * processes to do the work, then the parent sits around waiting
556 * for the working process to die, in which case it starts a new
557 * one. The parent process also handles restarts (by creating
558 * a new working process then signalling the previous working process
559 * exit ) and shutdowns (by signalling the working process to exit).
560 * The parent process operates within the master_main() function. This
561 * process also handles requests from the service manager (NT only).
563 * Signalling between the parent and working process uses a Win32
564 * event. Each child has a unique name for the event, which is
565 * passed to it with the -Z argument when the child is spawned. The
566 * parent sets (signals) this event to tell the child to die.
567 * At present all children do a graceful die - they finish all
568 * current jobs _and_ empty the listen queue before they exit.
569 * A non-graceful die would need a second event. The -Z argument in
570 * the child is also used to create the shutdown and restart events,
571 * since the prefix (apPID) contains the parent process PID.
573 * The code below starts with functions at the lowest level -
574 * worker threads, and works up to the top level - the main()
575 * function of the parent process.
577 * The scoreboard (in process memory) contains details of the worker
578 * threads (within the active working process). There is no shared
579 * "scoreboard" between processes, since only one is ever active
580 * at once (or at most, two, when one has been told to shutdown but
581 * is processes outstanding requests, and a new one has been started).
582 * This is controlled by a "start_mutex" which ensures only one working
583 * process is active at once.
584 **********************************************************************/
588 * Definition of jobs, shared by main and worker threads.
591 typedef struct joblist_s {
592 struct joblist_s *next;
597 * Globals common to main and worker threads. This structure is not
598 * used by the parent process.
601 typedef struct globals_s {
602 semaphore *jobsemaphore;
609 globals allowed_globals =
610 {NULL, NULL, NULL, NULL, 0};
611 #define MAX_SELECT_ERRORS 100
612 #define PADDED_ADDR_SIZE sizeof(SOCKADDR_IN)+16
614 /* Windows 9x specific code...
615 * Accept processing for on Windows 95/98 uses a producer/consumer queue
616 * model. A single thread accepts connections and queues the accepted socket
617 * to the accept queue for consumption by a pool of worker threads.
619 * win9x_get_connection()
620 * Calls remove_job() to pull a job from the accept queue. All the worker
621 * threads block on remove_job.
622 * accept_and_queue_connections()
623 * The accept threads runs this function, which accepts connections off
624 * the network and calls add_job() to queue jobs to the accept_queue.
625 * add_job()/remove_job()
626 * Add or remove an accepted socket from the list of sockets
627 * connected to clients. allowed_globals.jobmutex protects
628 * against multiple concurrent access to the linked list of jobs.
630 static void add_job(int sock)
634 new_job = (joblist *) malloc(sizeof(joblist));
635 if (new_job == NULL) {
636 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
637 "Ouch! Out of memory in add_job()!");
640 new_job->next = NULL;
641 new_job->sock = sock;
643 ap_lock(allowed_globals.jobmutex);
645 if (allowed_globals.jobtail != NULL)
646 allowed_globals.jobtail->next = new_job;
647 allowed_globals.jobtail = new_job;
648 if (!allowed_globals.jobhead)
649 allowed_globals.jobhead = new_job;
650 allowed_globals.jobcount++;
651 release_semaphore(allowed_globals.jobsemaphore);
653 ap_unlock(allowed_globals.jobmutex);
656 static int remove_job(void)
661 acquire_semaphore(allowed_globals.jobsemaphore);
662 ap_lock(allowed_globals.jobmutex);
664 if (workers_may_exit && !allowed_globals.jobhead) {
665 ap_unlock(allowed_globals.jobmutex);
668 job = allowed_globals.jobhead;
670 allowed_globals.jobhead = job->next;
671 if (allowed_globals.jobhead == NULL)
672 allowed_globals.jobtail = NULL;
673 ap_unlock(allowed_globals.jobmutex);
680 static void accept_and_queue_connections(void * dummy)
682 int requests_this_child = 0;
687 int nsd = INVALID_SOCKET;
688 struct sockaddr_in sa_client;
689 int count_select_errors = 0;
693 while (!workers_may_exit) {
694 if (ap_max_requests_per_child && (requests_this_child > ap_max_requests_per_child)) {
698 tv.tv_sec = wait_time;
700 memcpy(&main_fds, &listenfds, sizeof(fd_set));
702 // rc = ap_select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
703 rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
705 if (rc == 0 || (rc == SOCKET_ERROR && h_errno == WSAEINTR)) {
706 count_select_errors = 0; /* reset count of errors */
709 else if (rc == SOCKET_ERROR) {
710 /* A "real" error occurred, log it and increment the count of
711 * select errors. This count is used to ensure we don't go into
712 * a busy loop of continuous errors.
714 ap_log_error(APLOG_MARK, APLOG_INFO, h_errno, server_conf,
715 "select failed with errno %d", h_errno);
716 count_select_errors++;
717 if (count_select_errors > MAX_SELECT_ERRORS) {
718 workers_may_exit = 1;
719 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
720 "Too many errors in select loop. Child process exiting.");
726 lr = find_ready_listener(&main_fds);
728 /* fetch the native socket descriptor */
729 ap_get_os_sock(&nsd, lr->sd);
734 clen = sizeof(sa_client);
735 csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
736 if (csd == INVALID_SOCKET) {
739 } while (csd < 0 && h_errno == WSAEINTR);
742 if (h_errno != WSAECONNABORTED) {
743 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
744 "accept: (client socket)");
749 requests_this_child++;
752 SetEvent(exit_event);
754 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
758 if (context == NULL) {
759 /* allocate the completion context and the transaction pool */
760 context = ap_pcalloc(pconf, sizeof(COMP_CONTEXT));
762 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
763 "win9x_get_connection: ap_pcalloc() failed. Process will exit.");
766 ap_create_context(&context->ptrans, pconf);
771 ap_clear_pool(context->ptrans);
772 context->accept_socket = remove_job();
773 if (context->accept_socket == -1) {
776 //ap_note_cleanups_for_socket(ptrans, csd);
777 len = sizeof(struct sockaddr);
778 context->sa_server = ap_palloc(context->ptrans, len);
779 if (getsockname(context->accept_socket,
780 context->sa_server, &len)== SOCKET_ERROR) {
781 ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(), server_conf,
782 "getsockname failed");
785 len = sizeof(struct sockaddr);
786 context->sa_client = ap_palloc(context->ptrans, len);
787 if ((getpeername(context->accept_socket,
788 context->sa_client, &len)) == SOCKET_ERROR) {
789 ap_log_error(APLOG_MARK, APLOG_WARNING, h_errno, server_conf,
790 "getpeername failed with error %d\n", WSAGetLastError());
791 memset(&context->sa_client, '\0', sizeof(context->sa_client));
794 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
796 /* do we NEED_DUPPED_CSD ?? */
803 * Windows 2000/NT specific code...
804 * create_acceptex_context()
805 * reset_acceptex_context()
806 * drain_acceptex_complport()
807 * winnt_get_connection()
809 * TODO: Insert a discussion of 'completion contexts' and what these function do here...
811 static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp)
814 PCOMP_CONTEXT context;
822 rc = GetQueuedCompletionStatus(hComplPort, &BytesRead, &CompKey,
825 lastError = GetLastError();
826 if (lastError == ERROR_OPERATION_ABORTED) {
827 ap_log_error(APLOG_MARK,APLOG_INFO,lastError, server_conf,
828 "Child: %d - Draining a packet off the completion port.", my_pid);
833 ap_log_error(APLOG_MARK,APLOG_INFO,APR_SUCCESS, server_conf,
834 "Child: %d - Nuking an active connection. context = %x", my_pid, context);
835 context = (PCOMP_CONTEXT) pol;
836 if (context && bCleanUp) {
837 /* It is only valid to clean-up in the process that initiated the I/O */
838 closesocket(context->accept_socket);
839 CloseHandle(context->Overlapped.hEvent);
843 static int create_acceptex_context(ap_context_t *_pconf, ap_listen_rec *lr)
845 PCOMP_CONTEXT context;
850 /* allocate the completion context */
851 context = ap_pcalloc(_pconf, sizeof(COMP_CONTEXT));
853 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
854 "create_acceptex_context: ap_pcalloc() failed. Process will exit.");
858 /* initialize the completion context */
860 context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
861 if (context->Overlapped.hEvent == NULL) {
862 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
863 "create_acceptex_context: CreateEvent() failed. Process will exit.");
866 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
867 if (context->accept_socket == INVALID_SOCKET) {
868 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
869 "create_acceptex_context: socket() failed. Process will exit.");
872 ap_create_context(&context->ptrans, _pconf);
873 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
874 context->recv_buf = context->conn_io->inbase;
875 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
876 ap_get_os_sock(&nsd, context->lr->sd);
878 /* AcceptEx on the completion context. The completion context will be signaled
879 * when a connection is accepted. */
880 if (!AcceptEx(nsd, context->accept_socket,
882 0, //context->recv_buf_size,
883 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
885 (LPOVERLAPPED) context)) {
886 lasterror = WSAGetLastError();
887 if (lasterror != ERROR_IO_PENDING) {
888 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
889 "create_acceptex_context: AcceptEx failed. Process will exit.");
897 static ap_inline int reset_acceptex_context(PCOMP_CONTEXT context)
903 context->lr->count++;
905 if (context->accept_socket == -1)
906 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
908 if (context->accept_socket == INVALID_SOCKET) {
909 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
910 "reset_acceptex_context: socket() failed. Process will exit.");
914 ap_clear_pool(context->ptrans);
915 context->sock = NULL;
916 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
917 context->recv_buf = context->conn_io->inbase;
918 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
919 ap_get_os_sock(&nsd, context->lr->sd);
921 if (!AcceptEx(nsd, context->accept_socket,
923 0, //context->recv_buf_size,
924 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
925 &BytesRead, (LPOVERLAPPED) context)) {
926 lasterror = WSAGetLastError();
927 if (lasterror != ERROR_IO_PENDING) {
928 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
929 "reset_acceptex_context: AcceptEx failed. Leaving the process running.");
936 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
938 int requests_this_child = 0;
944 if (context != NULL) {
945 /* If child shutdown has been signaled, clean-up the completion context */
946 if (workers_may_exit) {
947 CloseHandle(context->Overlapped.hEvent);
951 context->accept_socket = -1; /* Don't reuse the accept_socket */
952 if (reset_acceptex_context(context) == -1) {
953 if (context->accept_socket != -1)
954 closesocket(context->accept_socket);
955 CloseHandle(context->Overlapped.hEvent);
962 rc = GetQueuedCompletionStatus(AcceptExCompPort,
968 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
969 "Child: %d - GetQueuedCompletionStatus() failed", my_pid);
974 context = (PCOMP_CONTEXT) pol;
975 if (CompKey == 999) {
979 /* Each listener needs at least 1 context available to receive connections on.
980 * Create additional listener contexts if needed.
982 ap_lock(allowed_globals.jobmutex);
983 context->lr->count--;
984 if ((context->lr->count < 2) && !workers_may_exit) {
985 if (create_acceptex_context(pconf, context->lr) == -1) {
986 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
987 "Unable to create an AcceptEx completion context -- process will exit");
992 ap_unlock(allowed_globals.jobmutex);
994 /* Received a connection */
995 context->conn_io->incnt = BytesRead;
996 GetAcceptExSockaddrs(context->recv_buf,
997 0, //context->recv_buf_size,
1000 &context->sa_server,
1001 &context->sa_server_len,
1002 &context->sa_client,
1003 &context->sa_client_len);
1009 * worker_main() - this is the main loop for the worker threads
1012 * Each thread runs within this function. They wait within remove_job()
1013 * for a job to become available, then handle all the requests on that
1014 * connection until it is closed, then return to remove_job().
1016 * The worker thread will exit when it removes a job which contains
1017 * socket number -1. This provides a graceful thread exit, since
1018 * it will never exit during a connection.
1020 * This code in this function is basically equivalent to the child_main()
1021 * from the multi-process (Unix) environment, except that we
1023 * - do not call child_init_modules (child init API phase)
1024 * - block in remove_job, and when unblocked we have an already
1025 * accepted socket, instead of blocking on a mutex or select().
1028 static void worker_main(int child_num)
1030 static BOOLEAN bListenersStarted = FALSE;
1031 PCOMP_CONTEXT context = NULL;
1033 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1034 /* Windows NT/2000: Create AcceptEx completion contexts for each of the
1037 ap_lock(allowed_globals.jobmutex);
1038 if (!bListenersStarted) {
1041 bListenersStarted = TRUE;
1042 for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1043 for(i=0; i<2; i++) {
1045 if (create_acceptex_context(pconf, lr) == -1) {
1046 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1047 "Unable to create an AcceptEx completion context -- process will exit");
1048 signal_parent(0); /* tell parent to die */
1053 ap_unlock(allowed_globals.jobmutex);
1057 conn_rec *current_conn;
1060 /* Grab a connection off the network */
1061 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1062 context = win9x_get_connection(context);
1065 context = winnt_get_connection(context);
1070 sock_disable_nagle(context->accept_socket);
1071 ap_put_os_sock(&context->sock, &context->accept_socket, context->ptrans);
1072 ap_register_cleanup(context->ptrans, context->sock, socket_cleanup, ap_null_cleanup);
1073 iol = win32_attach_socket(context->ptrans, context->sock);
1075 ap_log_error(APLOG_MARK, APLOG_ERR, APR_ENOMEM, server_conf,
1076 "worker_main: attach_socket() failed. Continuing...");
1077 closesocket(context->accept_socket);
1080 ap_bpush_iol(context->conn_io, iol);
1081 current_conn = ap_new_connection(context->ptrans, server_conf, context->conn_io,
1082 (struct sockaddr_in *) context->sa_client,
1083 (struct sockaddr_in *) context->sa_server,
1086 ap_process_connection(current_conn);
1089 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1090 "child_main: Setting exit_event");
1091 SetEvent(exit_event);
1093 /* TODO: Add code to clean-up completion contexts here */
1096 static void cleanup_thread(thread **handles, int *thread_cnt, int thread_to_clean)
1100 free_thread(handles[thread_to_clean]);
1101 for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1102 handles[i] = handles[i + 1];
1109 * child_main() is main loop for the child process. The loop in
1110 * this function becomes the controlling thread for the actually working
1111 * threads (which run in a loop in child_sub_main()).
1113 * exit_event, start_mutex, ap_threads_per_child, server_conf,
1114 * h_errno defined to WSAGetLastError in winsock2.h,
1116 static void child_main()
1118 int nthreads = ap_threads_per_child;
1120 thread **child_handles;
1125 ap_context_t *pchild;
1127 ap_create_context(&pchild, pconf);
1129 // ap_restart_time = time(NULL);
1131 * Wait until we have permission to start accepting connections.
1132 * start_mutex is used to ensure that only one child ever
1133 * goes into the listen/accept loop at once.
1135 status = ap_lock(start_mutex);
1136 if (status != APR_SUCCESS) {
1137 ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
1138 "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1139 signal_parent(0); /* tell parent to die */
1140 ap_destroy_context(pchild);
1143 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, "Child %d: Acquired the start mutex", my_pid);
1145 /* Setup the listening sockets */
1148 setup_listeners(server_conf);
1150 /* Associate the socket with the IO Completion port */
1151 for (lr = ap_listeners; lr; lr = lr->next) {
1153 ap_get_os_sock(&nsd,lr->sd);
1154 CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
1158 setup_inherited_listeners(server_conf);
1160 if (listenmaxfd == INVALID_SOCKET) {
1161 /* No sockets were made, better log something and exit */
1162 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, NULL,
1163 "No sockets were created for listening");
1164 signal_parent(0); /* tell parent to die */
1165 ap_destroy_context(pchild);
1169 allowed_globals.jobsemaphore = create_semaphore(0);
1170 ap_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
1172 /* Create the worker thread pool */
1173 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, "Child %d: Creating %d worker threads",my_pid, nthreads);
1174 child_handles = (thread *) alloca(nthreads * sizeof(int));
1175 for (i = 0; i < nthreads; i++) {
1176 child_handles[i] = create_thread((void (*)(void *)) worker_main, (void *) i);
1179 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1180 /* Win95/98: Create the accept thread */
1181 create_thread((void (*)(void *)) accept_and_queue_connections, (void *) NULL);
1184 /* Wait for the exit event to be signaled by the parent process */
1185 rv = WaitForSingleObject(exit_event, INFINITE);
1187 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1188 "Child %d: Exit event signaled. Child process is ending.", my_pid);
1189 workers_may_exit = 1;
1191 /* Shutdown the worker threads */
1192 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1193 for (i = 0; i < nthreads; i++) {
1197 else { /* Windows NT/2000 */
1198 /* Hack alert... Give the server a couple of seconds to receive
1199 * connections and drain AcceptEx completion contexts. We will
1200 * probably drop a few connections across a graceful restart, but
1201 * hopefully not many. This needs work...*/
1204 /* Tell the worker threads to exit. Any connections accepted on
1205 * the completion port from now will be dropped */
1206 for (i=0; i < nthreads; i++) {
1207 if (!PostQueuedCompletionStatus(AcceptExCompPort, 0, 999, NULL)) {
1208 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1209 "PostQueuedCompletionStatus failed");
1214 /* Wait for the worker threads to die */
1215 end_time = time(NULL) + 180;
1217 rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1218 if (rv != WAIT_TIMEOUT) {
1219 rv = rv - WAIT_OBJECT_0;
1220 ap_assert((rv >= 0) && (rv < nthreads));
1221 cleanup_thread(child_handles, &nthreads, rv);
1226 for (i = 0; i < nthreads; i++) {
1227 kill_thread(child_handles[i]);
1228 free_thread(child_handles[i]);
1230 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1231 "Child %d: All worker threads have ended.", my_pid);
1233 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1234 /* All the worker threads should have exited by now, which will
1235 * cause any outstanding I/O on the completion port to be aborted.
1236 * Drain the completion port of this aborted I/O/
1238 drain_acceptex_complport(AcceptExCompPort, TRUE);
1241 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1242 "Child %d: Releasing the start mutex", my_pid);
1243 ap_unlock(start_mutex);
1245 /* Still need to register cleanups for the sockets */
1246 CloseHandle(AcceptExCompPort);
1247 destroy_semaphore(allowed_globals.jobsemaphore);
1248 ap_destroy_lock(allowed_globals.jobmutex);
1250 ap_destroy_context(pchild);
1254 * Spawn a child Apache process. The child process has the command line arguments from
1255 * argc and argv[], plus a -Z argument giving the name of an event. The child should
1256 * open and poll or wait on this event. When it is signalled, the child should die.
1257 * prefix is a prefix string for the event name.
1259 * The child_num argument on entry contains a serial number for this child (used to create
1260 * a unique event name). On exit, this number will have been incremented by one, ready
1261 * for the next call.
1263 * On exit, the value pointed to be *ev will contain the event created
1264 * to signal the new child process.
1266 * The return value is the handle to the child process if successful, else -1. If -1 is
1267 * returned the error will already have been logged by ap_log_error().
1270 /**********************************************************************
1271 * master_main - this is the parent (main) process. We create a
1272 * child process to do the work, then sit around waiting for either
1273 * the child to exit, or a restart or exit signal. If the child dies,
1274 * we just respawn a new one. If we have a shutdown or graceful restart,
1275 * tell the child to die when it is ready. If it is a non-graceful
1276 * restart, force the child to die immediately.
1277 **********************************************************************/
1279 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1281 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1286 CloseHandle(handles[position]);
1287 CloseHandle(events[position]);
1289 handle = (int)handles[position];
1291 for (i = position; i < (*processes)-1; i++) {
1292 handles[i] = handles[i + 1];
1293 events[i] = events[i + 1];
1298 static int create_process(ap_context_t *p, HANDLE *handles, HANDLE *events, int *processes)
1305 STARTUPINFO si; /* Filled in prior to call to CreateProcess */
1306 PROCESS_INFORMATION pi; /* filled in on call to CreateProces */
1310 HANDLE hPipeRead = NULL;
1311 HANDLE hPipeWrite = NULL;
1312 SECURITY_ATTRIBUTES sa = {0};
1314 sa.nLength = sizeof(sa);
1315 sa.bInheritHandle = TRUE;
1316 sa.lpSecurityDescriptor = NULL;
1318 /* Create the IOCompletionPort */
1319 if (AcceptExCompPort == NULL) {
1320 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1323 0); /* CONCURRENT ACTIVE THREADS */
1324 if (AcceptExCompPort == NULL) {
1325 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1326 "Unable to create the AcceptExCompletionPort -- process will exit");
1331 /* Build the command line. Should look something like this:
1332 * C:/apache/bin/apache.exe -f ap_server_confname
1333 * First, get the path to the executable...
1335 rv = GetModuleFileName(NULL, buf, sizeof(buf));
1336 if (rv == sizeof(buf)) {
1337 ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1338 "Parent: Path to Apache process too long");
1340 } else if (rv == 0) {
1341 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1342 "Parent: GetModuleFileName() returned NULL for current process.");
1346 /* Build the command line */
1347 pCommand = ap_psprintf(p, "\"%s\"", buf);
1348 for (i = 1; i < server_conf->process->argc; i++) {
1349 pCommand = ap_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1352 /* Create a pipe to send socket info to the child */
1353 if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1354 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1355 "Parent: Unable to create pipe to child process.\n");
1359 SetEnvironmentVariable("AP_PARENT_PID",ap_psprintf(p,"%d",parent_pid));
1361 /* Give the read end of the pipe (hPipeRead) to the child as stdin. The
1362 * parent will write the socket data to the child on this pipe.
1364 memset(&si, 0, sizeof(si));
1365 memset(&pi, 0, sizeof(pi));
1367 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1368 si.wShowWindow = SW_HIDE;
1369 si.hStdInput = hPipeRead;
1371 if (!CreateProcess(NULL, pCommand, NULL, NULL,
1372 TRUE, /* Inherit handles */
1373 CREATE_SUSPENDED, /* Creation flags */
1374 NULL, /* Environment block */
1377 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1378 "Parent: Not able to create the child process.");
1380 * We must close the handles to the new process and its main thread
1381 * to prevent handle and memory leaks.
1383 CloseHandle(pi.hProcess);
1384 CloseHandle(pi.hThread);
1389 LPWSAPROTOCOL_INFO lpWSAProtocolInfo;
1390 HANDLE hDupedCompPort;
1392 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1393 "Parent: Created child process %d", pi.dwProcessId);
1395 SetEnvironmentVariable("AP_PARENT_PID",NULL);
1397 /* Create the exit_event, apCchild_pid */
1398 sa.nLength = sizeof(sa);
1399 sa.bInheritHandle = TRUE;
1400 sa.lpSecurityDescriptor = NULL;
1401 kill_event = CreateEvent(&sa, TRUE, FALSE, ap_psprintf(pconf,"apC%d", pi.dwProcessId));
1403 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1404 "Parent: Could not create exit event for child process");
1405 CloseHandle(pi.hProcess);
1406 CloseHandle(pi.hThread);
1410 /* Assume the child process lives. Update the process and event tables */
1411 handles[*processes] = pi.hProcess;
1412 events[*processes] = kill_event;
1415 /* We never store the thread's handle, so close it now. */
1416 ResumeThread(pi.hThread);
1417 CloseHandle(pi.hThread);
1419 /* Run the chain of open sockets. For each socket, duplicate it
1420 * for the target process then send the WSAPROTOCOL_INFO
1421 * (returned by dup socket) to the child */
1422 for (lr = ap_listeners; lr; lr = lr->next) {
1424 lpWSAProtocolInfo = ap_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1425 ap_get_os_sock(&nsd,lr->sd);
1426 /* Associate the socket with the IOcompletion port */
1427 CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
1428 ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_INFO, APR_SUCCESS, server_conf,
1429 "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1430 if (WSADuplicateSocket(nsd, pi.dwProcessId,
1431 lpWSAProtocolInfo) == SOCKET_ERROR) {
1432 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, server_conf,
1433 "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1437 if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1439 (LPOVERLAPPED) NULL)) {
1440 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1441 "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1444 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1445 "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1447 /* Now, send the AcceptEx completion port to the child */
1448 if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort,
1449 pi.hProcess, &hDupedCompPort, 0,
1450 TRUE, DUPLICATE_SAME_ACCESS)) {
1451 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1452 "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1455 WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1458 CloseHandle(hPipeRead);
1459 CloseHandle(hPipeWrite);
1464 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1466 int remaining_children_to_start = ap_daemons_to_start;
1470 int restart_pending = 0;
1471 int shutdown_pending = 0;
1472 int current_live_processes = 0; /* number of child process we know about */
1474 HANDLE process_handles[MAX_PROCESSES];
1475 HANDLE process_kill_events[MAX_PROCESSES];
1479 /* Create child process
1480 * Should only be one in this version of Apache for WIN32
1482 service_set_status(SERVICE_START_PENDING);
1483 while (remaining_children_to_start--) {
1484 if (create_process(pconf, process_handles, process_kill_events,
1485 ¤t_live_processes) < 0) {
1486 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1487 "master_main: create child process failed. Exiting.");
1488 shutdown_pending = 1;
1492 service_set_status(SERVICE_RUNNING);
1494 restart_pending = shutdown_pending = 0;
1496 /* Wait for shutdown or restart events or for child death */
1497 process_handles[current_live_processes] = shutdown_event;
1498 process_handles[current_live_processes+1] = restart_event;
1499 printf("process/shutdown/restart %d %d %d\n", process_handles[0], process_handles[1], process_handles[2]);
1500 rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles,
1502 cld = rv - WAIT_OBJECT_0;
1503 if (rv == WAIT_FAILED) {
1504 /* Something serious is wrong */
1505 ap_log_error(APLOG_MARK,APLOG_CRIT, GetLastError(), server_conf,
1506 "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1507 shutdown_pending = 1;
1509 else if (rv == WAIT_TIMEOUT) {
1510 /* Hey, this cannot happen */
1511 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1512 "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1513 shutdown_pending = 1;
1515 else if (cld == current_live_processes) {
1516 /* shutdown_event signalled */
1517 shutdown_pending = 1;
1518 printf("shutdown event signaled\n");
1519 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1520 "master_main: Shutdown event signaled -- doing server shutdown.");
1521 if (ResetEvent(shutdown_event) == 0) {
1522 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1523 "ResetEvent(shutdown_event)");
1527 else if (cld == current_live_processes+1) {
1528 /* restart_event signalled */
1529 int children_to_kill = current_live_processes;
1530 restart_pending = 1;
1531 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1532 "master_main: Restart event signaled. Doing a graceful restart.");
1533 if (ResetEvent(restart_event) == 0) {
1534 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1535 "master_main: ResetEvent(restart_event) failed.");
1537 /* Signal each child process to die
1538 * We are making a big assumption here that the child process, once signaled,
1539 * will REALLY go away. Since this is a restart, we do not want to hold the
1540 * new child process up waiting for the old child to die. Remove the old
1541 * child out of the process_handles ap_table_t and hope for the best...
1543 for (i = 0; i < children_to_kill; i++) {
1544 printf("SetEvent handle = %d\n", process_kill_events[i]);
1545 if (SetEvent(process_kill_events[i]) == 0)
1546 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1547 "master_main: SetEvent for child process in slot #%d failed", i);
1548 cleanup_process(process_handles, process_kill_events, i, ¤t_live_processes);
1552 /* A child process must have exited because of a fatal error condition (seg fault, etc.).
1553 * Remove the dead process
1554 * from the process_handles and process_kill_events ap_table_t and create a new
1556 * TODO: Consider restarting the child immediately without looping through http_main
1557 * and without rereading the configuration. Will need this if we ever support multiple
1558 * children. One option, create a parent thread which waits on child death and restarts it.
1560 restart_pending = 1;
1561 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1562 "master_main: Child process failed. Restarting the child process.");
1563 ap_assert(cld < current_live_processes);
1564 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1565 /* APD2("main_process: child in slot %d died", rv); */
1566 /* restart_child(process_hancles, process_kill_events, cld, ¤t_live_processes); */
1568 /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead
1570 drain_acceptex_complport(AcceptExCompPort, FALSE);
1574 if (shutdown_pending) {
1575 int tmstart = time(NULL);
1576 /* Signal each child processes to die */
1577 for (i = 0; i < current_live_processes; i++) {
1578 printf("SetEvent handle = %d\n", process_kill_events[i]);
1579 if (SetEvent(process_kill_events[i]) == 0)
1580 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1581 "master_main: SetEvent for child process in slot #%d failed", i);
1584 while (current_live_processes && ((tmstart+60) > time(NULL))) {
1585 rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1586 if (rv == WAIT_TIMEOUT)
1588 ap_assert(rv != WAIT_FAILED);
1589 cld = rv - WAIT_OBJECT_0;
1590 ap_assert(rv < current_live_processes);
1591 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1593 for (i = 0; i < current_live_processes; i++) {
1594 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1595 "forcing termination of child #%d (handle %d)", i, process_handles[i]);
1596 TerminateProcess((HANDLE) process_handles[i], 1);
1598 return (0); /* Tell the caller we are shutting down */
1601 return (1); /* Tell the caller we want a restart */
1605 * winnt_pre_config() hook
1607 static void winnt_pre_config(ap_context_t *pconf, ap_context_t *plog, ap_context_t *ptemp)
1611 one_process = !!getenv("ONE_PROCESS");
1613 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1614 GetVersionEx(&osver);
1616 /* AP_PARENT_PID is only valid in the child */
1617 pid = getenv("AP_PARENT_PID");
1619 /* This is the child */
1620 parent_pid = atoi(pid);
1624 /* This is the parent */
1625 parent_pid = my_pid = getpid();
1629 ap_listen_pre_config();
1630 ap_daemons_to_start = DEFAULT_NUM_DAEMON;
1631 ap_threads_per_child = DEFAULT_START_THREAD;
1632 ap_pid_fname = DEFAULT_PIDLOG;
1633 max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1635 ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1639 static void winnt_post_config(ap_context_t *pconf, ap_context_t *plog, ap_context_t *ptemp, server_rec* server_conf)
1641 server_conf = server_conf;
1644 API_EXPORT(int) ap_mpm_run(ap_context_t *_pconf, ap_context_t *plog, server_rec *s )
1647 char* exit_event_name;
1648 static int restart = 0; /* Default is to not restart */
1650 static HANDLE shutdown_event; /* used to signal shutdown to parent */
1651 static HANDLE restart_event; /* used to signal a restart to parent */
1656 if ((parent_pid != my_pid) || one_process) {
1658 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1659 "Child %d: Child process is running", my_pid);
1660 AMCSocketInitialize();
1661 exit_event_name = ap_psprintf(pconf, "apC%d", my_pid);
1662 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1665 /* Create the IO CompletionPort */
1666 if (AcceptExCompPort == NULL) {
1667 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1669 if (AcceptExCompPort == NULL) {
1670 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1671 "Unable to create the AcceptExCompletionPort -- process will exit");
1675 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1676 exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1679 ap_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1680 exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1681 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1682 "Child %d: exit_event_name = %s", my_pid, exit_event_name);
1684 ap_assert(start_mutex);
1685 ap_assert(exit_event);
1689 CloseHandle(exit_event);
1694 /* Parent process */
1695 PSECURITY_ATTRIBUTES sa = GetNullACL(); /* returns NULL if invalid (Win95?) */
1697 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1699 ap_log_pid(pconf, ap_pid_fname);
1701 service_set_status(SERVICE_START_PENDING);
1702 AMCSocketInitialize();
1703 // setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1705 /* Create shutdown event, apPID_shutdown, where PID is the parent
1706 * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
1708 shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
1709 if (!shutdown_event) {
1710 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), s,
1711 "master_main: Cannot create shutdown event %s", signal_shutdown_name);
1712 CleanNullACL((void *)sa);
1716 /* Create restart event, apPID_restart, where PID is the parent
1717 * Apache process ID. Restart is signaled by 'apache -k restart'.
1719 // restart_event = CreateEvent(sa, TRUE, FALSE, signal_restart_name);
1720 restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
1721 if (!restart_event) {
1722 CloseHandle(shutdown_event);
1723 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), s,
1724 "ap_run_mpm: Cannot create restart event %s", signal_restart_name);
1725 CleanNullACL((void *)sa);
1728 CleanNullACL((void *)sa);
1730 /* Create the start mutex, apPID, where PID is the parent Apache process ID.
1731 * Ths start mutex is used during a restart to prevent more than one
1732 * child process from entering the accept loop at once.
1734 // ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1735 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,s->process->pool);
1736 /* TODO: Add some code to detect failure */
1740 restart = master_main(server_conf, shutdown_event, restart_event);
1743 const char *pidfile = NULL;
1744 /* Shutting down. Clean up... */
1745 pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1746 if ( pidfile != NULL && unlink(pidfile) == 0)
1747 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO,APR_SUCCESS,
1748 server_conf, "removed PID file %s (pid=%ld)",
1749 pidfile, (long)getpid());
1750 ap_destroy_lock(start_mutex);
1752 CloseHandle(restart_event);
1753 CloseHandle(shutdown_event);
1756 service_set_status(SERVICE_STOPPED);
1762 static void winnt_hooks(void)
1766 /* Configuration hooks implemented by http_config.c ... */
1767 ap_hook_pre_config(winnt_pre_config, NULL, NULL, HOOK_MIDDLE);
1771 * Command processors
1773 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg)
1775 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1780 if (cmd->server->is_virtual) {
1781 return "PidFile directive not allowed in <VirtualHost>";
1787 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg)
1789 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1794 ap_threads_per_child = atoi(arg);
1795 if (ap_threads_per_child > HARD_THREAD_LIMIT) {
1796 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1797 "WARNING: ThreadsPerChild of %d exceeds compile time"
1798 " limit of %d threads,", ap_threads_per_child,
1800 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1801 " lowering ThreadsPerChild to %d. To increase, please"
1802 " see the HARD_THREAD_LIMIT define in src/include/httpd.h.",
1805 else if (ap_threads_per_child < 1) {
1806 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1807 "WARNING: Require ThreadsPerChild > 0, setting to 1");
1808 ap_threads_per_child = 1;
1814 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg)
1816 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1821 max_requests_per_child = atoi(arg);
1826 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg)
1830 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1835 fname = ap_server_root_relative(cmd->pool, arg);
1836 if ((stat(fname, &finfo) == -1) || !S_ISDIR(finfo.st_mode)) {
1837 return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
1838 " does not exist or is not a directory", NULL);
1840 ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1844 /* Stub functions until this MPM supports the connection status API */
1846 API_EXPORT(void) ap_update_connection_status(long conn_id, const char *key, \
1852 API_EXPORT(void) ap_reset_connection_status(long conn_id)
1857 static const command_rec winnt_cmds[] = {
1859 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
1860 "A file for logging the server process ID"},
1861 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
1862 "Number of threads each child creates" },
1863 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
1864 "Maximum number of requests a particular child serves before dying." },
1865 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
1866 "The location of the directory Apache changes to before dumping core" },
1870 module MODULE_VAR_EXPORT mpm_winnt_module = {
1871 STANDARD20_MODULE_STUFF,
1872 NULL, /* create per-directory config structure */
1873 NULL, /* merge per-directory config structures */
1874 NULL, /* create per-server config structure */
1875 NULL, /* merge per-server config structures */
1876 winnt_cmds, /* command ap_table_t */
1877 NULL, /* handlers */
1878 winnt_hooks /* register_hooks */