1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
60 #include "apr_portable.h"
62 #include "http_main.h"
64 #include "http_config.h" /* for read_config */
65 #include "http_core.h" /* for get_remote_host */
66 #include "http_connection.h"
68 #include "ap_config.h"
69 #include "ap_listen.h"
70 #include "mpm_default.h"
72 #include "iol_socket.h"
77 * Definitions of WINNT MPM specific config globals
80 static char *ap_pid_fname = NULL;
81 static int ap_threads_per_child = 0;
82 static int workers_may_exit = 0;
83 static int max_requests_per_child = 0;
84 static HANDLE shutdown_event; /* used to signal shutdown to parent */
85 static HANDLE restart_event; /* used to signal a restart to parent */
87 static struct fd_set listenfds;
88 static int num_listenfds = 0;
89 static SOCKET listenmaxfd = INVALID_SOCKET;
91 static ap_pool_t *pconf; /* Pool for config stuff */
93 static char ap_coredump_dir[MAX_STRING_LEN];
95 static server_rec *server_conf;
96 static HANDLE AcceptExCompPort = NULL;
98 static int one_process = 0;
100 static OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
102 int ap_max_requests_per_child=0;
103 int ap_daemons_to_start=0;
105 static event *exit_event;
106 ap_lock_t *start_mutex;
110 static ap_status_t socket_cleanup(void *sock)
112 ap_socket_t *thesocket = sock;
114 if (ap_get_os_sock(&sd, thesocket) == APR_SUCCESS) {
120 /* A bunch or routines from os/win32/multithread.c that need to be merged into APR
121 * or thrown out entirely...
125 typedef void semaphore;
129 create_semaphore(int initial)
131 return(CreateSemaphore(NULL, initial, 1000000, NULL));
134 static void acquire_semaphore(semaphore *semaphore_id)
138 rv = WaitForSingleObject(semaphore_id, INFINITE);
143 static int release_semaphore(semaphore *semaphore_id)
145 return(ReleaseSemaphore(semaphore_id, 1, NULL));
148 static void destroy_semaphore(semaphore *semaphore_id)
150 CloseHandle(semaphore_id);
154 /* To share the semaphores with other processes, we need a NULL ACL
155 * Code from MS KB Q106387
157 static PSECURITY_ATTRIBUTES GetNullACL()
159 PSECURITY_DESCRIPTOR pSD;
160 PSECURITY_ATTRIBUTES sa;
162 sa = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES));
163 pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,
164 SECURITY_DESCRIPTOR_MIN_LENGTH);
165 if (pSD == NULL || sa == NULL) {
168 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
174 if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
180 sa->nLength = sizeof(sa);
181 sa->lpSecurityDescriptor = pSD;
182 sa->bInheritHandle = TRUE;
186 static void CleanNullACL( void *sa ) {
188 LocalFree( ((PSECURITY_ATTRIBUTES)sa)->lpSecurityDescriptor);
194 * The Win32 call WaitForMultipleObjects will only allow you to wait for
195 * a maximum of MAXIMUM_WAIT_OBJECTS (current 64). Since the threading
196 * model in the multithreaded version of apache wants to use this call,
197 * we are restricted to a maximum of 64 threads. This is a simplistic
198 * routine that will increase this size.
200 static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles,
204 DWORD dwRet = WAIT_TIMEOUT;
208 tStopTime = time(NULL) + dwSeconds;
216 for (dwIndex = 0; dwIndex * MAXIMUM_WAIT_OBJECTS < nCount; dwIndex++) {
217 dwRet = WaitForMultipleObjects(
218 min(MAXIMUM_WAIT_OBJECTS, nCount - (dwIndex * MAXIMUM_WAIT_OBJECTS)),
219 lpHandles + (dwIndex * MAXIMUM_WAIT_OBJECTS),
222 if (dwRet != WAIT_TIMEOUT) {
226 } while((time(NULL) < tStopTime) && (dwRet == WAIT_TIMEOUT));
232 * Signalling Apache on NT.
234 * Under Unix, Apache can be told to shutdown or restart by sending various
235 * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
236 * we use "events" instead. The parent apache process goes into a loop
237 * where it waits forever for a set of events. Two of those events are
243 * (where PID is the PID of the apache parent process). When one of these
244 * is signalled, the Apache parent performs the appropriate action. The events
245 * can become signalled through internal Apache methods (e.g. if the child
246 * finds a fatal error and needs to kill its parent), via the service
247 * control manager (the control thread will signal the shutdown event when
248 * requested to stop the Apache service), from the -k Apache command line,
249 * or from any external program which finds the Apache PID from the
252 * The signal_parent() function, below, is used to signal one of these events.
253 * It can be called by any child or parent process, since it does not
254 * rely on global variables.
256 * On entry, type gives the event to signal. 0 means shutdown, 1 means
259 static void signal_parent(int type)
263 extern char signal_shutdown_name[];
264 extern char signal_restart_name[];
266 /* after updating the shutdown_pending or restart flags, we need
267 * to wake up the parent process so it can see the changes. The
268 * parent will normally be waiting for either a child process
269 * to die, or for a signal on the "spache-signal" event. So set the
270 * "apache-signal" event here.
277 case 0: signal_name = signal_shutdown_name; break;
278 case 1: signal_name = signal_restart_name; break;
281 e = OpenEvent(EVENT_ALL_ACCESS, FALSE, signal_name);
283 /* Um, problem, can't signal the parent, which means we can't
284 * signal ourselves to die. Ignore for now...
286 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
287 "OpenEvent on %s event", signal_name);
290 if (SetEvent(e) == 0) {
291 /* Same problem as above */
292 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
293 "SetEvent on %s event", signal_name);
299 static int volatile is_graceful = 0;
300 API_EXPORT(int) ap_graceful_stop_signalled(void)
304 void ap_start_shutdown(void)
309 * Initialise the signal names, in the global variables signal_name_prefix,
310 * signal_restart_name and signal_shutdown_name.
313 #define MAX_SIGNAL_NAME 30 /* Long enough for apPID_shutdown, where PID is an int */
314 char signal_name_prefix[MAX_SIGNAL_NAME];
315 char signal_restart_name[MAX_SIGNAL_NAME];
316 char signal_shutdown_name[MAX_SIGNAL_NAME];
317 static void setup_signal_names(char *prefix)
319 ap_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);
320 ap_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name),
321 "%s_shutdown", signal_name_prefix);
322 ap_snprintf(signal_restart_name, sizeof(signal_restart_name),
323 "%s_restart", signal_name_prefix);
327 * Routines that deal with sockets, some are WIN32 specific...
329 static int s_iInitCount = 0;
330 static int AMCSocketInitialize(void)
332 int iVersionRequested;
336 if (s_iInitCount > 0) {
340 else if (s_iInitCount < 0)
341 return (s_iInitCount);
343 /* s_iInitCount == 0. Do the initailization */
344 iVersionRequested = MAKEWORD(2, 0);
345 err = WSAStartup((WORD) iVersionRequested, &wsaData);
348 return (s_iInitCount);
350 if (LOBYTE(wsaData.wVersion) != 1 ||
351 HIBYTE(wsaData.wVersion) != 1) {
354 return (s_iInitCount);
358 return (s_iInitCount);
361 static void AMCSocketCleanup(void)
363 if (--s_iInitCount == 0)
368 static void sock_disable_nagle(int s)
370 /* The Nagle algorithm says that we should delay sending partial
371 * packets in hopes of getting more data. We don't want to do
372 * this; we are not telnet. There are bad interactions between
373 * persistent connections and Nagle's algorithm that have very severe
374 * performance penalties. (Failing to disable Nagle is not much of a
375 * problem with simple HTTP.)
377 * In spite of these problems, failure here is not a shooting offense.
381 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
383 ap_log_error(APLOG_MARK, APLOG_WARNING, APR_SUCCESS, server_conf,
384 "setsockopt: (TCP_NODELAY)");
389 * Routines to deal with managing the list of listening sockets.
391 static ap_listen_rec *head_listener;
392 static ap_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
397 for (lr = head_listener; lr ; lr = lr->next) {
398 ap_get_os_sock(&nsd, lr->sd);
399 if (FD_ISSET(nsd, main_fds)) {
400 head_listener = lr->next;
401 if (head_listener == NULL)
402 head_listener = ap_listeners;
409 static int setup_listeners(server_rec *s)
412 int num_listeners = 0;
415 /* Setup the listeners */
418 if (ap_listen_open(s->process, s->port)) {
421 for (lr = ap_listeners; lr; lr = lr->next) {
423 if (lr->sd != NULL) {
424 ap_get_os_sock(&nsd, lr->sd);
425 FD_SET(nsd, &listenfds);
426 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
433 head_listener = ap_listeners;
435 return num_listeners;
438 static int setup_inherited_listeners(server_rec *s)
440 WSAPROTOCOL_INFO WSAProtocolInfo;
444 int num_listeners = 0;
447 /* Setup the listeners */
450 /* Set up a default listener if necessary */
452 if (ap_listeners == NULL) {
454 lr = ap_palloc(s->process->pool, sizeof(ap_listen_rec));
458 lr->next = ap_listeners;
462 /* Open the pipe to the parent process to receive the inherited socket
463 * data. The sockets have been set to listening in the parent process.
465 pipe = GetStdHandle(STD_INPUT_HANDLE);
466 for (lr = ap_listeners; lr; lr = lr->next) {
467 if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
468 &BytesRead, (LPOVERLAPPED) NULL)) {
469 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
470 "setup_inherited_listeners: Unable to read socket data from parent");
471 signal_parent(0); /* tell parent to die */
474 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
475 "Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.", my_pid);
476 nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
477 &WSAProtocolInfo, 0, 0);
478 if (nsd == INVALID_SOCKET) {
479 ap_log_error(APLOG_MARK, APLOG_CRIT, WSAGetLastError(), server_conf,
480 "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
481 signal_parent(0); /* tell parent to die */
485 FD_SET(nsd, &listenfds);
486 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
490 // ap_register_cleanup(p, (void *)lr->sd, socket_cleanup, ap_null_cleanup);
491 ap_put_os_sock(&lr->sd, &nsd, pconf);
494 /* Now, read the AcceptExCompPort from the parent */
495 ReadFile(pipe, &AcceptExCompPort, sizeof(AcceptExCompPort), &BytesRead, (LPOVERLAPPED) NULL);
498 for (lr = ap_listeners; lr; lr = lr->next) {
502 head_listener = ap_listeners;
503 return num_listeners;
506 static void bind_listeners_to_completion_port()
508 /* Associate the open listeners with the completion port.
509 * Bypass the operation for Windows 95/98
513 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
514 for (lr = ap_listeners; lr; lr = lr->next) {
516 ap_get_os_sock(&nsd,lr->sd);
517 CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
522 /**********************************************************************
523 * Multithreaded implementation
525 * This code is fairly specific to Win32.
527 * The model used to handle requests is a set of threads. One "main"
528 * thread listens for new requests. When something becomes
529 * available, it does a select and places the newly available socket
530 * onto a list of "jobs" (add_job()). Then any one of a fixed number
531 * of "worker" threads takes the top job off the job list with
532 * remove_job() and handles that connection to completion. After
533 * the connection has finished the thread is free to take another
534 * job from the job list.
536 * In the code, the "main" thread is running within the child_main()
537 * function. The first thing this function does is create the
538 * worker threads, which operate in the child_sub_main() function. The
539 * main thread then goes into a loop within child_main() where they
540 * do a select() on the listening sockets. The select times out once
541 * per second so that the thread can check for an "exit" signal
542 * from the parent process (see below). If this signal is set, the
543 * thread can exit, but only after it has accepted all incoming
544 * connections already in the listen queue (since Win32 appears
545 * to through away listened but unaccepted connections when a
548 * Because the main and worker threads exist within a single process
549 * they are vulnerable to crashes or memory leaks (crashes can also
550 * be caused within modules, of course). There also needs to be a
551 * mechanism to perform restarts and shutdowns. This is done by
552 * creating the main & worker threads within a subprocess. A
553 * main process (the "parent process") creates one (or more)
554 * processes to do the work, then the parent sits around waiting
555 * for the working process to die, in which case it starts a new
556 * one. The parent process also handles restarts (by creating
557 * a new working process then signalling the previous working process
558 * exit ) and shutdowns (by signalling the working process to exit).
559 * The parent process operates within the master_main() function. This
560 * process also handles requests from the service manager (NT only).
562 * Signalling between the parent and working process uses a Win32
563 * event. Each child has a unique name for the event, which is
564 * passed to it with the -Z argument when the child is spawned. The
565 * parent sets (signals) this event to tell the child to die.
566 * At present all children do a graceful die - they finish all
567 * current jobs _and_ empty the listen queue before they exit.
568 * A non-graceful die would need a second event. The -Z argument in
569 * the child is also used to create the shutdown and restart events,
570 * since the prefix (apPID) contains the parent process PID.
572 * The code below starts with functions at the lowest level -
573 * worker threads, and works up to the top level - the main()
574 * function of the parent process.
576 * The scoreboard (in process memory) contains details of the worker
577 * threads (within the active working process). There is no shared
578 * "scoreboard" between processes, since only one is ever active
579 * at once (or at most, two, when one has been told to shutdown but
580 * is processes outstanding requests, and a new one has been started).
581 * This is controlled by a "start_mutex" which ensures only one working
582 * process is active at once.
583 **********************************************************************/
587 * Definition of jobs, shared by main and worker threads.
590 typedef struct joblist_s {
591 struct joblist_s *next;
596 * Globals common to main and worker threads. This structure is not
597 * used by the parent process.
600 typedef struct globals_s {
601 semaphore *jobsemaphore;
608 globals allowed_globals =
609 {NULL, NULL, NULL, NULL, 0};
610 #define MAX_SELECT_ERRORS 100
611 #define PADDED_ADDR_SIZE sizeof(SOCKADDR_IN)+16
613 /* Windows 9x specific code...
614 * Accept processing for on Windows 95/98 uses a producer/consumer queue
615 * model. A single thread accepts connections and queues the accepted socket
616 * to the accept queue for consumption by a pool of worker threads.
618 * win9x_get_connection()
619 * Calls remove_job() to pull a job from the accept queue. All the worker
620 * threads block on remove_job.
621 * accept_and_queue_connections()
622 * The accept threads runs this function, which accepts connections off
623 * the network and calls add_job() to queue jobs to the accept_queue.
624 * add_job()/remove_job()
625 * Add or remove an accepted socket from the list of sockets
626 * connected to clients. allowed_globals.jobmutex protects
627 * against multiple concurrent access to the linked list of jobs.
629 static void add_job(int sock)
633 new_job = (joblist *) malloc(sizeof(joblist));
634 if (new_job == NULL) {
635 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
636 "Ouch! Out of memory in add_job()!");
639 new_job->next = NULL;
640 new_job->sock = sock;
642 ap_lock(allowed_globals.jobmutex);
644 if (allowed_globals.jobtail != NULL)
645 allowed_globals.jobtail->next = new_job;
646 allowed_globals.jobtail = new_job;
647 if (!allowed_globals.jobhead)
648 allowed_globals.jobhead = new_job;
649 allowed_globals.jobcount++;
650 release_semaphore(allowed_globals.jobsemaphore);
652 ap_unlock(allowed_globals.jobmutex);
655 static int remove_job(void)
660 acquire_semaphore(allowed_globals.jobsemaphore);
661 ap_lock(allowed_globals.jobmutex);
663 if (workers_may_exit && !allowed_globals.jobhead) {
664 ap_unlock(allowed_globals.jobmutex);
667 job = allowed_globals.jobhead;
669 allowed_globals.jobhead = job->next;
670 if (allowed_globals.jobhead == NULL)
671 allowed_globals.jobtail = NULL;
672 ap_unlock(allowed_globals.jobmutex);
679 static void accept_and_queue_connections(void * dummy)
681 int requests_this_child = 0;
686 int nsd = INVALID_SOCKET;
687 struct sockaddr_in sa_client;
688 int count_select_errors = 0;
692 while (!workers_may_exit) {
693 if (ap_max_requests_per_child && (requests_this_child > ap_max_requests_per_child)) {
697 tv.tv_sec = wait_time;
699 memcpy(&main_fds, &listenfds, sizeof(fd_set));
701 // rc = ap_select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
702 rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
704 if (rc == 0 || (rc == SOCKET_ERROR && h_errno == WSAEINTR)) {
705 count_select_errors = 0; /* reset count of errors */
708 else if (rc == SOCKET_ERROR) {
709 /* A "real" error occurred, log it and increment the count of
710 * select errors. This count is used to ensure we don't go into
711 * a busy loop of continuous errors.
713 ap_log_error(APLOG_MARK, APLOG_INFO, h_errno, server_conf,
714 "select failed with errno %d", h_errno);
715 count_select_errors++;
716 if (count_select_errors > MAX_SELECT_ERRORS) {
717 workers_may_exit = 1;
718 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
719 "Too many errors in select loop. Child process exiting.");
725 lr = find_ready_listener(&main_fds);
727 /* fetch the native socket descriptor */
728 ap_get_os_sock(&nsd, lr->sd);
733 clen = sizeof(sa_client);
734 csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
735 if (csd == INVALID_SOCKET) {
738 } while (csd < 0 && h_errno == WSAEINTR);
741 if (h_errno != WSAECONNABORTED) {
742 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
743 "accept: (client socket)");
748 requests_this_child++;
751 SetEvent(exit_event);
753 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
757 if (context == NULL) {
758 /* allocate the completion context and the transaction pool */
759 context = ap_pcalloc(pconf, sizeof(COMP_CONTEXT));
761 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
762 "win9x_get_connection: ap_pcalloc() failed. Process will exit.");
765 ap_create_pool(&context->ptrans, pconf);
770 ap_clear_pool(context->ptrans);
771 context->accept_socket = remove_job();
772 if (context->accept_socket == -1) {
775 //ap_note_cleanups_for_socket(ptrans, csd);
776 len = sizeof(struct sockaddr);
777 context->sa_server = ap_palloc(context->ptrans, len);
778 if (getsockname(context->accept_socket,
779 context->sa_server, &len)== SOCKET_ERROR) {
780 ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(), server_conf,
781 "getsockname failed");
784 len = sizeof(struct sockaddr);
785 context->sa_client = ap_palloc(context->ptrans, len);
786 if ((getpeername(context->accept_socket,
787 context->sa_client, &len)) == SOCKET_ERROR) {
788 ap_log_error(APLOG_MARK, APLOG_WARNING, h_errno, server_conf,
789 "getpeername failed with error %d\n", WSAGetLastError());
790 memset(&context->sa_client, '\0', sizeof(context->sa_client));
793 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
795 /* do we NEED_DUPPED_CSD ?? */
802 * Windows 2000/NT specific code...
803 * create_acceptex_context()
804 * reset_acceptex_context()
805 * drain_acceptex_complport()
806 * winnt_get_connection()
808 * TODO: Insert a discussion of 'completion contexts' and what these function do here...
810 static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp)
813 PCOMP_CONTEXT context;
821 rc = GetQueuedCompletionStatus(hComplPort, &BytesRead, &CompKey,
824 lastError = GetLastError();
825 if (lastError == ERROR_OPERATION_ABORTED) {
826 ap_log_error(APLOG_MARK,APLOG_INFO,lastError, server_conf,
827 "Child: %d - Draining a packet off the completion port.", my_pid);
832 ap_log_error(APLOG_MARK,APLOG_INFO,APR_SUCCESS, server_conf,
833 "Child: %d - Nuking an active connection. context = %x", my_pid, context);
834 context = (PCOMP_CONTEXT) pol;
835 if (context && bCleanUp) {
836 /* It is only valid to clean-up in the process that initiated the I/O */
837 closesocket(context->accept_socket);
838 CloseHandle(context->Overlapped.hEvent);
842 static int create_acceptex_context(ap_pool_t *_pconf, ap_listen_rec *lr)
844 PCOMP_CONTEXT context;
849 /* allocate the completion context */
850 context = ap_pcalloc(_pconf, sizeof(COMP_CONTEXT));
852 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
853 "create_acceptex_context: ap_pcalloc() failed. Process will exit.");
857 /* initialize the completion context */
859 context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
860 if (context->Overlapped.hEvent == NULL) {
861 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
862 "create_acceptex_context: CreateEvent() failed. Process will exit.");
865 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
866 if (context->accept_socket == INVALID_SOCKET) {
867 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
868 "create_acceptex_context: socket() failed. Process will exit.");
871 ap_create_pool(&context->ptrans, _pconf);
872 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
873 context->recv_buf = context->conn_io->inbase;
874 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
875 ap_get_os_sock(&nsd, context->lr->sd);
877 /* AcceptEx on the completion context. The completion context will be signaled
878 * when a connection is accepted. */
879 if (!AcceptEx(nsd, context->accept_socket,
881 0, //context->recv_buf_size,
882 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
884 (LPOVERLAPPED) context)) {
885 lasterror = WSAGetLastError();
886 if (lasterror != ERROR_IO_PENDING) {
887 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
888 "create_acceptex_context: AcceptEx failed. Process will exit.");
892 /* SO_UPDATE_ACCEPT_CONTEXT is a Microsoft-ism which is required
893 * if you want to use more than several key socket calls on a
894 * socket initialized via AcceptEx(). In particular, it is
895 * required for shutdown() to work.
898 if (setsockopt(context->accept_socket, SOL_SOCKET,
899 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
901 ap_log_error(APLOG_MARK, APLOG_ERR, WSAGetLastError(), server_conf,
902 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
910 static ap_inline int reset_acceptex_context(PCOMP_CONTEXT context)
916 context->lr->count++;
918 if (context->accept_socket == -1)
919 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
921 if (context->accept_socket == INVALID_SOCKET) {
922 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
923 "reset_acceptex_context: socket() failed. Process will exit.");
927 ap_clear_pool(context->ptrans);
928 context->sock = NULL;
929 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
930 context->recv_buf = context->conn_io->inbase;
931 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
932 ap_get_os_sock(&nsd, context->lr->sd);
934 if (!AcceptEx(nsd, context->accept_socket,
936 0, //context->recv_buf_size,
937 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
938 &BytesRead, (LPOVERLAPPED) context)) {
939 lasterror = WSAGetLastError();
940 if (lasterror != ERROR_IO_PENDING) {
941 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
942 "reset_acceptex_context: AcceptEx failed. Leaving the process running.");
946 /* SO_UPDATE_ACCEPT_CONTEXT is a Microsoft-ism which is required
947 * if you want to use more than several key socket calls on a
948 * socket initialized via AcceptEx(). In particular, it is
949 * required for shutdown() to work.
952 if (setsockopt(context->accept_socket, SOL_SOCKET,
953 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
955 ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(),
957 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
963 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
965 int requests_this_child = 0;
971 if (context != NULL) {
972 /* If child shutdown has been signaled, clean-up the completion context */
973 if (workers_may_exit) {
974 CloseHandle(context->Overlapped.hEvent);
978 context->accept_socket = -1; /* Don't reuse the accept_socket */
979 if (reset_acceptex_context(context) == -1) {
980 if (context->accept_socket != -1)
981 closesocket(context->accept_socket);
982 CloseHandle(context->Overlapped.hEvent);
989 rc = GetQueuedCompletionStatus(AcceptExCompPort,
995 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
996 "Child: %d - GetQueuedCompletionStatus() failed", my_pid);
1001 context = (PCOMP_CONTEXT) pol;
1002 if (CompKey == 999) {
1006 /* Each listener needs at least 1 context available to receive connections on.
1007 * Create additional listener contexts if needed.
1009 ap_lock(allowed_globals.jobmutex);
1010 context->lr->count--;
1011 if ((context->lr->count < 2) && !workers_may_exit) {
1012 if (create_acceptex_context(pconf, context->lr) == -1) {
1013 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1014 "Unable to create an AcceptEx completion context -- process will exit");
1019 ap_unlock(allowed_globals.jobmutex);
1021 /* Received a connection */
1022 context->conn_io->incnt = BytesRead;
1023 GetAcceptExSockaddrs(context->recv_buf,
1024 0, //context->recv_buf_size,
1027 &context->sa_server,
1028 &context->sa_server_len,
1029 &context->sa_client,
1030 &context->sa_client_len);
1036 * worker_main() - this is the main loop for the worker threads
1039 * Each thread runs within this function. They wait within remove_job()
1040 * for a job to become available, then handle all the requests on that
1041 * connection until it is closed, then return to remove_job().
1043 * The worker thread will exit when it removes a job which contains
1044 * socket number -1. This provides a graceful thread exit, since
1045 * it will never exit during a connection.
1047 * This code in this function is basically equivalent to the child_main()
1048 * from the multi-process (Unix) environment, except that we
1050 * - do not call child_init_modules (child init API phase)
1051 * - block in remove_job, and when unblocked we have an already
1052 * accepted socket, instead of blocking on a mutex or select().
1055 static void worker_main(int child_num)
1057 static BOOLEAN bListenersStarted = FALSE;
1058 PCOMP_CONTEXT context = NULL;
1060 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1061 /* Windows NT/2000: Create AcceptEx completion contexts for each of the
1064 ap_lock(allowed_globals.jobmutex);
1065 if (!bListenersStarted) {
1068 bListenersStarted = TRUE;
1069 for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1070 for(i=0; i<2; i++) {
1072 if (create_acceptex_context(pconf, lr) == -1) {
1073 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1074 "Unable to create an AcceptEx completion context -- process will exit");
1075 signal_parent(0); /* tell parent to die */
1080 ap_unlock(allowed_globals.jobmutex);
1084 conn_rec *current_conn;
1087 /* Grab a connection off the network */
1088 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1089 context = win9x_get_connection(context);
1092 context = winnt_get_connection(context);
1097 sock_disable_nagle(context->accept_socket);
1098 ap_put_os_sock(&context->sock, &context->accept_socket, context->ptrans);
1099 ap_register_cleanup(context->ptrans, context->sock, socket_cleanup, ap_null_cleanup);
1100 iol = win32_attach_socket(context->ptrans, context->sock);
1102 ap_log_error(APLOG_MARK, APLOG_ERR, APR_ENOMEM, server_conf,
1103 "worker_main: attach_socket() failed. Continuing...");
1104 closesocket(context->accept_socket);
1107 ap_bpush_iol(context->conn_io, iol);
1108 current_conn = ap_new_connection(context->ptrans, server_conf, context->conn_io,
1109 (struct sockaddr_in *) context->sa_client,
1110 (struct sockaddr_in *) context->sa_server,
1113 ap_process_connection(current_conn);
1116 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1117 "child_main: Setting exit_event");
1118 SetEvent(exit_event);
1120 /* TODO: Add code to clean-up completion contexts here */
1123 static void cleanup_thread(thread **handles, int *thread_cnt, int thread_to_clean)
1127 CloseHandle(handles[thread_to_clean]);
1128 for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1129 handles[i] = handles[i + 1];
1136 * child_main() is main loop for the child process. The loop in
1137 * this function becomes the controlling thread for the actually working
1138 * threads (which run in a loop in child_sub_main()).
1140 * exit_event, start_mutex, ap_threads_per_child, server_conf,
1141 * h_errno defined to WSAGetLastError in winsock2.h,
1143 static void child_main()
1145 char* exit_event_name;
1146 int nthreads = ap_threads_per_child;
1148 thread **child_handles;
1155 /* This is the child process or we are running in single process
1159 exit_event_name = ap_psprintf(pconf, "apC%d", my_pid);
1160 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1163 /* Single process mode */
1164 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1165 exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1167 setup_listeners(server_conf);
1168 bind_listeners_to_completion_port();
1171 /* Child process mode */
1172 ap_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1173 exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1174 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1175 "Child %d: exit_event_name = %s", my_pid, exit_event_name);
1177 setup_inherited_listeners(server_conf);
1179 ap_assert(start_mutex);
1180 ap_assert(exit_event);
1182 ap_create_pool(&pchild, pconf);
1185 if (listenmaxfd == INVALID_SOCKET) {
1186 /* No sockets were made, better log something and exit */
1187 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, NULL,
1188 "No sockets were created for listening");
1189 signal_parent(0); /* tell parent to die */
1190 ap_destroy_pool(pchild);
1194 allowed_globals.jobsemaphore = create_semaphore(0);
1195 ap_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
1198 * Wait until we have permission to start accepting connections.
1199 * start_mutex is used to ensure that only one child ever
1200 * goes into the listen/accept loop at once.
1202 status = ap_lock(start_mutex);
1203 if (status != APR_SUCCESS) {
1204 ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
1205 "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1206 signal_parent(0); /* tell parent to die */
1207 ap_destroy_pool(pchild);
1210 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, "Child %d: Acquired the start mutex", my_pid);
1212 /* Create the worker thread pool */
1213 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, "Child %d: Creating %d worker threads",my_pid, nthreads);
1214 child_handles = (thread *) alloca(nthreads * sizeof(int));
1215 for (i = 0; i < nthreads; i++) {
1216 child_handles[i] = (thread *) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1217 NULL, 0, &thread_id);
1220 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1221 /* Win95/98: Create the accept thread */
1222 _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) accept_and_queue_connections,
1223 (void *) i, 0, &thread_id);
1226 /* Wait for the exit event to be signaled by the parent process */
1227 rv = WaitForSingleObject(exit_event, INFINITE);
1229 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1230 "Child %d: Exit event signaled. Child process is ending.", my_pid);
1231 workers_may_exit = 1;
1233 /* Shutdown the worker threads */
1234 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1235 for (i = 0; i < nthreads; i++) {
1239 else { /* Windows NT/2000 */
1240 /* Tell the worker threads to exit. */
1241 for (i=0; i < nthreads; i++) {
1242 if (!PostQueuedCompletionStatus(AcceptExCompPort, 0, 999, NULL)) {
1243 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1244 "PostQueuedCompletionStatus failed");
1249 /* Wait for the worker threads to die */
1250 end_time = time(NULL) + 180;
1252 rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1253 if (rv != WAIT_TIMEOUT) {
1254 rv = rv - WAIT_OBJECT_0;
1255 ap_assert((rv >= 0) && (rv < nthreads));
1256 cleanup_thread(child_handles, &nthreads, rv);
1261 for (i = 0; i < nthreads; i++) {
1262 TerminateThread(child_handles[i], 1);
1263 CloseHandle(child_handles[i]);
1265 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1266 "Child %d: All worker threads have ended.", my_pid);
1268 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1269 /* All the worker threads should have exited by now, which will
1270 * cause any outstanding I/O on the completion port to be aborted.
1271 * Drain the completion port of this aborted I/O/
1273 drain_acceptex_complport(AcceptExCompPort, TRUE);
1276 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1277 "Child %d: Releasing the start mutex", my_pid);
1278 ap_unlock(start_mutex);
1280 /* Still need to register cleanups for the sockets */
1281 CloseHandle(AcceptExCompPort);
1282 destroy_semaphore(allowed_globals.jobsemaphore);
1283 ap_destroy_lock(allowed_globals.jobmutex);
1285 ap_destroy_pool(pchild);
1286 CloseHandle(exit_event);
1290 * Spawn a child Apache process. The child process has the command line arguments from
1291 * argc and argv[], plus a -Z argument giving the name of an event. The child should
1292 * open and poll or wait on this event. When it is signalled, the child should die.
1293 * prefix is a prefix string for the event name.
1295 * The child_num argument on entry contains a serial number for this child (used to create
1296 * a unique event name). On exit, this number will have been incremented by one, ready
1297 * for the next call.
1299 * On exit, the value pointed to be *ev will contain the event created
1300 * to signal the new child process.
1302 * The return value is the handle to the child process if successful, else -1. If -1 is
1303 * returned the error will already have been logged by ap_log_error().
1306 /**********************************************************************
1307 * master_main - this is the parent (main) process. We create a
1308 * child process to do the work, then sit around waiting for either
1309 * the child to exit, or a restart or exit signal. If the child dies,
1310 * we just respawn a new one. If we have a shutdown or graceful restart,
1311 * tell the child to die when it is ready. If it is a non-graceful
1312 * restart, force the child to die immediately.
1313 **********************************************************************/
1315 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1317 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1322 CloseHandle(handles[position]);
1323 CloseHandle(events[position]);
1325 handle = (int)handles[position];
1327 for (i = position; i < (*processes)-1; i++) {
1328 handles[i] = handles[i + 1];
1329 events[i] = events[i + 1];
1334 static int create_process(ap_pool_t *p, HANDLE *handles, HANDLE *events, int *processes)
1341 STARTUPINFO si; /* Filled in prior to call to CreateProcess */
1342 PROCESS_INFORMATION pi; /* filled in on call to CreateProces */
1346 HANDLE hPipeRead = NULL;
1347 HANDLE hPipeWrite = NULL;
1348 SECURITY_ATTRIBUTES sa = {0};
1350 sa.nLength = sizeof(sa);
1351 sa.bInheritHandle = TRUE;
1352 sa.lpSecurityDescriptor = NULL;
1354 /* Build the command line. Should look something like this:
1355 * C:/apache/bin/apache.exe -f ap_server_confname
1356 * First, get the path to the executable...
1358 rv = GetModuleFileName(NULL, buf, sizeof(buf));
1359 if (rv == sizeof(buf)) {
1360 ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1361 "Parent: Path to Apache process too long");
1363 } else if (rv == 0) {
1364 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1365 "Parent: GetModuleFileName() returned NULL for current process.");
1369 /* Build the command line */
1370 pCommand = ap_psprintf(p, "\"%s\"", buf);
1371 for (i = 1; i < server_conf->process->argc; i++) {
1372 pCommand = ap_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1375 /* Create a pipe to send socket info to the child */
1376 if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1377 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1378 "Parent: Unable to create pipe to child process.\n");
1382 SetEnvironmentVariable("AP_PARENT_PID",ap_psprintf(p,"%d",parent_pid));
1384 /* Give the read end of the pipe (hPipeRead) to the child as stdin. The
1385 * parent will write the socket data to the child on this pipe.
1387 memset(&si, 0, sizeof(si));
1388 memset(&pi, 0, sizeof(pi));
1390 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1391 si.wShowWindow = SW_HIDE;
1392 si.hStdInput = hPipeRead;
1394 if (!CreateProcess(NULL, pCommand, NULL, NULL,
1395 TRUE, /* Inherit handles */
1396 CREATE_SUSPENDED, /* Creation flags */
1397 NULL, /* Environment block */
1400 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1401 "Parent: Not able to create the child process.");
1403 * We must close the handles to the new process and its main thread
1404 * to prevent handle and memory leaks.
1406 CloseHandle(pi.hProcess);
1407 CloseHandle(pi.hThread);
1412 LPWSAPROTOCOL_INFO lpWSAProtocolInfo;
1413 HANDLE hDupedCompPort;
1415 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1416 "Parent: Created child process %d", pi.dwProcessId);
1418 SetEnvironmentVariable("AP_PARENT_PID",NULL);
1420 /* Create the exit_event, apCchild_pid */
1421 sa.nLength = sizeof(sa);
1422 sa.bInheritHandle = TRUE;
1423 sa.lpSecurityDescriptor = NULL;
1424 kill_event = CreateEvent(&sa, TRUE, FALSE, ap_psprintf(pconf,"apC%d", pi.dwProcessId));
1426 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1427 "Parent: Could not create exit event for child process");
1428 CloseHandle(pi.hProcess);
1429 CloseHandle(pi.hThread);
1433 /* Assume the child process lives. Update the process and event tables */
1434 handles[*processes] = pi.hProcess;
1435 events[*processes] = kill_event;
1438 /* We never store the thread's handle, so close it now. */
1439 ResumeThread(pi.hThread);
1440 CloseHandle(pi.hThread);
1442 /* Run the chain of open sockets. For each socket, duplicate it
1443 * for the target process then send the WSAPROTOCOL_INFO
1444 * (returned by dup socket) to the child */
1445 for (lr = ap_listeners; lr; lr = lr->next) {
1447 lpWSAProtocolInfo = ap_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1448 ap_get_os_sock(&nsd,lr->sd);
1449 ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_INFO, APR_SUCCESS, server_conf,
1450 "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1451 if (WSADuplicateSocket(nsd, pi.dwProcessId,
1452 lpWSAProtocolInfo) == SOCKET_ERROR) {
1453 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, server_conf,
1454 "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1458 if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1460 (LPOVERLAPPED) NULL)) {
1461 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1462 "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1465 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1466 "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1468 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1469 /* Now, send the AcceptEx completion port to the child */
1470 if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort,
1471 pi.hProcess, &hDupedCompPort, 0,
1472 TRUE, DUPLICATE_SAME_ACCESS)) {
1473 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1474 "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1478 WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1482 CloseHandle(hPipeRead);
1483 CloseHandle(hPipeWrite);
1488 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1490 int remaining_children_to_start = ap_daemons_to_start;
1494 int restart_pending = 0;
1495 int shutdown_pending = 0;
1496 int current_live_processes = 0; /* number of child process we know about */
1498 HANDLE process_handles[MAX_PROCESSES];
1499 HANDLE process_kill_events[MAX_PROCESSES];
1502 bind_listeners_to_completion_port();
1504 /* Create child process
1505 * Should only be one in this version of Apache for WIN32
1507 service_set_status(SERVICE_START_PENDING);
1508 while (remaining_children_to_start--) {
1509 if (create_process(pconf, process_handles, process_kill_events,
1510 ¤t_live_processes) < 0) {
1511 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1512 "master_main: create child process failed. Exiting.");
1513 shutdown_pending = 1;
1517 service_set_status(SERVICE_RUNNING);
1519 restart_pending = shutdown_pending = 0;
1521 /* Wait for shutdown or restart events or for child death */
1522 process_handles[current_live_processes] = shutdown_event;
1523 process_handles[current_live_processes+1] = restart_event;
1525 rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles,
1527 cld = rv - WAIT_OBJECT_0;
1528 if (rv == WAIT_FAILED) {
1529 /* Something serious is wrong */
1530 ap_log_error(APLOG_MARK,APLOG_CRIT, GetLastError(), server_conf,
1531 "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1532 shutdown_pending = 1;
1534 else if (rv == WAIT_TIMEOUT) {
1535 /* Hey, this cannot happen */
1536 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1537 "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1538 shutdown_pending = 1;
1540 else if (cld == current_live_processes) {
1541 /* shutdown_event signalled */
1542 shutdown_pending = 1;
1543 printf("shutdown event signaled\n");
1544 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1545 "master_main: Shutdown event signaled -- doing server shutdown.");
1546 if (ResetEvent(shutdown_event) == 0) {
1547 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1548 "ResetEvent(shutdown_event)");
1552 else if (cld == current_live_processes+1) {
1553 /* restart_event signalled */
1554 int children_to_kill = current_live_processes;
1555 restart_pending = 1;
1556 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1557 "master_main: Restart event signaled. Doing a graceful restart.");
1558 if (ResetEvent(restart_event) == 0) {
1559 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1560 "master_main: ResetEvent(restart_event) failed.");
1562 /* Signal each child process to die
1563 * We are making a big assumption here that the child process, once signaled,
1564 * will REALLY go away. Since this is a restart, we do not want to hold the
1565 * new child process up waiting for the old child to die. Remove the old
1566 * child out of the process_handles ap_table_t and hope for the best...
1568 for (i = 0; i < children_to_kill; i++) {
1569 printf("SetEvent handle = %d\n", process_kill_events[i]);
1570 if (SetEvent(process_kill_events[i]) == 0)
1571 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1572 "master_main: SetEvent for child process in slot #%d failed", i);
1573 cleanup_process(process_handles, process_kill_events, i, ¤t_live_processes);
1577 /* A child process must have exited because of a fatal error condition (seg fault, etc.).
1578 * Remove the dead process
1579 * from the process_handles and process_kill_events ap_table_t and create a new
1581 * TODO: Consider restarting the child immediately without looping through http_main
1582 * and without rereading the configuration. Will need this if we ever support multiple
1583 * children. One option, create a parent thread which waits on child death and restarts it.
1585 restart_pending = 1;
1586 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1587 "master_main: Child process failed. Restarting the child process.");
1588 ap_assert(cld < current_live_processes);
1589 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1590 /* APD2("main_process: child in slot %d died", rv); */
1591 /* restart_child(process_hancles, process_kill_events, cld, ¤t_live_processes); */
1593 /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead
1595 drain_acceptex_complport(AcceptExCompPort, FALSE);
1599 if (shutdown_pending) {
1600 int tmstart = time(NULL);
1601 /* Signal each child processes to die */
1602 for (i = 0; i < current_live_processes; i++) {
1603 printf("SetEvent handle = %d\n", process_kill_events[i]);
1604 if (SetEvent(process_kill_events[i]) == 0)
1605 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1606 "master_main: SetEvent for child process in slot #%d failed", i);
1609 while (current_live_processes && ((tmstart+60) > time(NULL))) {
1610 rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1611 if (rv == WAIT_TIMEOUT)
1613 ap_assert(rv != WAIT_FAILED);
1614 cld = rv - WAIT_OBJECT_0;
1615 ap_assert(rv < current_live_processes);
1616 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1618 for (i = 0; i < current_live_processes; i++) {
1619 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1620 "forcing termination of child #%d (handle %d)", i, process_handles[i]);
1621 TerminateProcess((HANDLE) process_handles[i], 1);
1623 return 0; /* Tell the caller we do not want to restart */
1626 return 1; /* Tell the caller we want a restart */
1630 * winnt_pre_config() hook
1632 static void winnt_pre_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp)
1636 one_process = !!getenv("ONE_PROCESS");
1638 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1639 GetVersionEx(&osver);
1641 /* AP_PARENT_PID is only valid in the child */
1642 pid = getenv("AP_PARENT_PID");
1644 /* This is the child */
1645 parent_pid = atoi(pid);
1649 /* This is the parent */
1650 parent_pid = my_pid = getpid();
1653 ap_listen_pre_config();
1654 ap_daemons_to_start = DEFAULT_NUM_DAEMON;
1655 ap_threads_per_child = DEFAULT_START_THREAD;
1656 ap_pid_fname = DEFAULT_PIDLOG;
1657 max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1659 ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1663 static void winnt_post_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp, server_rec* server_conf)
1665 static int restart_num = 0;
1666 server_conf = server_conf;
1668 if (parent_pid == my_pid) {
1669 if (restart_num++ == 1) {
1670 /* This code should be run once in the parent and not run
1673 PSECURITY_ATTRIBUTES sa = GetNullACL(); /* returns NULL if invalid (Win95?) */
1674 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1675 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1676 /* Create the AcceptEx IoCompletionPort once in the parent.
1677 * The completion port persists across restarts.
1679 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1682 0); /* CONCURRENT ACTIVE THREADS */
1683 if (AcceptExCompPort == NULL) {
1684 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1685 "Parent: Unable to create the AcceptExCompletionPort -- process will exit");
1690 ap_log_pid(pconf, ap_pid_fname);
1691 service_set_status(SERVICE_START_PENDING);
1693 AMCSocketInitialize();
1695 /* Create shutdown event, apPID_shutdown, where PID is the parent
1696 * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
1698 shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
1699 if (!shutdown_event) {
1700 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
1701 "Parent: Cannot create shutdown event %s", signal_shutdown_name);
1702 CleanNullACL((void *)sa);
1706 /* Create restart event, apPID_restart, where PID is the parent
1707 * Apache process ID. Restart is signaled by 'apache -k restart'.
1709 restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
1710 if (!restart_event) {
1711 CloseHandle(shutdown_event);
1712 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
1713 "Parent: Cannot create restart event %s", signal_restart_name);
1714 CleanNullACL((void *)sa);
1717 CleanNullACL((void *)sa);
1719 /* Create the start mutex, apPID, where PID is the parent Apache process ID.
1720 * Ths start mutex is used during a restart to prevent more than one
1721 * child process from entering the accept loop at once.
1723 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS, signal_name_prefix,
1724 server_conf->process->pool);
1729 API_EXPORT(int) ap_mpm_run(ap_pool_t *_pconf, ap_pool_t *plog, server_rec *s )
1731 static int restart = 0; /* Default is "not a restart" */
1736 if ((parent_pid != my_pid) || one_process) {
1737 /* Running as Child process or in one_process (debug) mode */
1738 ap_log_error(APLOG_MARK, APLOG_ERR, APR_SUCCESS, server_conf,
1739 "Child %d: Child process is running", my_pid);
1740 AMCSocketInitialize();
1743 ap_log_error(APLOG_MARK, APLOG_ERR, APR_SUCCESS, server_conf,
1744 "Child %d: Child process is exiting", my_pid);
1747 } /* Child or single process */
1748 else { /* Parent process */
1749 restart = master_main(server_conf, shutdown_event, restart_event);
1752 /* Shutting down. Clean up... */
1753 const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1755 if (pidfile != NULL && unlink(pidfile) == 0) {
1756 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO,APR_SUCCESS,
1757 server_conf, "removed PID file %s (pid=%ld)",
1758 pidfile, (long)getpid());
1760 ap_destroy_lock(start_mutex);
1762 CloseHandle(restart_event);
1763 CloseHandle(shutdown_event);
1766 service_set_status(SERVICE_STOPPED);
1770 } /* Parent process */
1772 return 0; /* Restart */
1775 static void winnt_hooks(void)
1778 ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
1782 * Command processors
1784 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg)
1786 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1791 if (cmd->server->is_virtual) {
1792 return "PidFile directive not allowed in <VirtualHost>";
1798 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg)
1800 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1805 ap_threads_per_child = atoi(arg);
1806 if (ap_threads_per_child > HARD_THREAD_LIMIT) {
1807 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1808 "WARNING: ThreadsPerChild of %d exceeds compile time"
1809 " limit of %d threads,", ap_threads_per_child,
1811 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1812 " lowering ThreadsPerChild to %d. To increase, please"
1813 " see the HARD_THREAD_LIMIT define in src/include/httpd.h.",
1816 else if (ap_threads_per_child < 1) {
1817 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1818 "WARNING: Require ThreadsPerChild > 0, setting to 1");
1819 ap_threads_per_child = 1;
1825 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg)
1827 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1832 max_requests_per_child = atoi(arg);
1837 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg)
1841 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1846 fname = ap_server_root_relative(cmd->pool, arg);
1847 if ((stat(fname, &finfo) == -1) || !S_ISDIR(finfo.st_mode)) {
1848 return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
1849 " does not exist or is not a directory", NULL);
1851 ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1855 /* Stub functions until this MPM supports the connection status API */
1857 API_EXPORT(void) ap_update_connection_status(long conn_id, const char *key, \
1863 API_EXPORT(void) ap_reset_connection_status(long conn_id)
1868 API_EXPORT(ap_array_header_t *) ap_get_status_table(ap_pool_t *p)
1874 static const command_rec winnt_cmds[] = {
1876 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
1877 "A file for logging the server process ID"},
1878 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
1879 "Number of threads each child creates" },
1880 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
1881 "Maximum number of requests a particular child serves before dying." },
1882 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
1883 "The location of the directory Apache changes to before dumping core" },
1887 module MODULE_VAR_EXPORT mpm_winnt_module = {
1889 winnt_pre_config, /* hook run before configuration is read */
1890 NULL, /* create per-directory config structure */
1891 NULL, /* merge per-directory config structures */
1892 NULL, /* create per-server config structure */
1893 NULL, /* merge per-server config structures */
1894 winnt_cmds, /* command ap_table_t */
1895 NULL, /* handlers */
1896 winnt_hooks /* register_hooks */