1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
60 #include "apr_portable.h"
62 #include "http_main.h"
64 #include "http_config.h" /* for read_config */
65 #include "http_core.h" /* for get_remote_host */
66 #include "http_connection.h"
68 #include "ap_config.h"
69 #include "ap_listen.h"
70 #include "mpm_default.h"
72 #include "iol_socket.h"
77 * Definitions of WINNT MPM specific config globals
80 static char *ap_pid_fname = NULL;
81 static int ap_threads_per_child = 0;
82 static int workers_may_exit = 0;
83 static int max_requests_per_child = 0;
85 static struct fd_set listenfds;
86 static int num_listenfds = 0;
87 static SOCKET listenmaxfd = INVALID_SOCKET;
89 static ap_context_t *pconf; /* Pool for config stuff */
91 static char ap_coredump_dir[MAX_STRING_LEN];
93 static server_rec *server_conf;
94 static HANDLE AcceptExCompPort = NULL;
96 static int one_process = 0;
98 static OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
100 int ap_max_requests_per_child=0;
101 int ap_daemons_to_start=0;
103 static event *exit_event;
104 ap_lock_t *start_mutex;
108 static ap_status_t socket_cleanup(void *sock)
110 ap_socket_t *thesocket = sock;
112 if (ap_get_os_sock(&sd, thesocket) == APR_SUCCESS) {
118 /* A bunch or routines from os/win32/multithread.c that need to be merged into APR
119 * or thrown out entirely...
123 typedef void semaphore;
127 create_semaphore(int initial)
129 return(CreateSemaphore(NULL, initial, 1000000, NULL));
132 static void acquire_semaphore(semaphore *semaphore_id)
136 rv = WaitForSingleObject(semaphore_id, INFINITE);
141 static int release_semaphore(semaphore *semaphore_id)
143 return(ReleaseSemaphore(semaphore_id, 1, NULL));
146 static void destroy_semaphore(semaphore *semaphore_id)
148 CloseHandle(semaphore_id);
152 /* To share the semaphores with other processes, we need a NULL ACL
153 * Code from MS KB Q106387
155 static PSECURITY_ATTRIBUTES GetNullACL()
157 PSECURITY_DESCRIPTOR pSD;
158 PSECURITY_ATTRIBUTES sa;
160 sa = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES));
161 pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,
162 SECURITY_DESCRIPTOR_MIN_LENGTH);
163 if (pSD == NULL || sa == NULL) {
166 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
172 if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
178 sa->nLength = sizeof(sa);
179 sa->lpSecurityDescriptor = pSD;
180 sa->bInheritHandle = TRUE;
184 static void CleanNullACL( void *sa ) {
186 LocalFree( ((PSECURITY_ATTRIBUTES)sa)->lpSecurityDescriptor);
192 * The Win32 call WaitForMultipleObjects will only allow you to wait for
193 * a maximum of MAXIMUM_WAIT_OBJECTS (current 64). Since the threading
194 * model in the multithreaded version of apache wants to use this call,
195 * we are restricted to a maximum of 64 threads. This is a simplistic
196 * routine that will increase this size.
198 static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles,
202 DWORD dwRet = WAIT_TIMEOUT;
206 tStopTime = time(NULL) + dwSeconds;
214 for (dwIndex = 0; dwIndex * MAXIMUM_WAIT_OBJECTS < nCount; dwIndex++) {
215 dwRet = WaitForMultipleObjects(
216 min(MAXIMUM_WAIT_OBJECTS, nCount - (dwIndex * MAXIMUM_WAIT_OBJECTS)),
217 lpHandles + (dwIndex * MAXIMUM_WAIT_OBJECTS),
220 if (dwRet != WAIT_TIMEOUT) {
224 } while((time(NULL) < tStopTime) && (dwRet == WAIT_TIMEOUT));
230 * Signalling Apache on NT.
232 * Under Unix, Apache can be told to shutdown or restart by sending various
233 * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
234 * we use "events" instead. The parent apache process goes into a loop
235 * where it waits forever for a set of events. Two of those events are
241 * (where PID is the PID of the apache parent process). When one of these
242 * is signalled, the Apache parent performs the appropriate action. The events
243 * can become signalled through internal Apache methods (e.g. if the child
244 * finds a fatal error and needs to kill its parent), via the service
245 * control manager (the control thread will signal the shutdown event when
246 * requested to stop the Apache service), from the -k Apache command line,
247 * or from any external program which finds the Apache PID from the
250 * The signal_parent() function, below, is used to signal one of these events.
251 * It can be called by any child or parent process, since it does not
252 * rely on global variables.
254 * On entry, type gives the event to signal. 0 means shutdown, 1 means
257 static void signal_parent(int type)
261 extern char signal_shutdown_name[];
262 extern char signal_restart_name[];
264 /* after updating the shutdown_pending or restart flags, we need
265 * to wake up the parent process so it can see the changes. The
266 * parent will normally be waiting for either a child process
267 * to die, or for a signal on the "spache-signal" event. So set the
268 * "apache-signal" event here.
275 case 0: signal_name = signal_shutdown_name; break;
276 case 1: signal_name = signal_restart_name; break;
279 e = OpenEvent(EVENT_ALL_ACCESS, FALSE, signal_name);
281 /* Um, problem, can't signal the parent, which means we can't
282 * signal ourselves to die. Ignore for now...
284 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
285 "OpenEvent on %s event", signal_name);
288 if (SetEvent(e) == 0) {
289 /* Same problem as above */
290 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), server_conf,
291 "SetEvent on %s event", signal_name);
297 static int volatile is_graceful = 0;
298 API_EXPORT(int) ap_graceful_stop_signalled(void)
302 void ap_start_shutdown(void)
307 * Initialise the signal names, in the global variables signal_name_prefix,
308 * signal_restart_name and signal_shutdown_name.
311 #define MAX_SIGNAL_NAME 30 /* Long enough for apPID_shutdown, where PID is an int */
312 char signal_name_prefix[MAX_SIGNAL_NAME];
313 char signal_restart_name[MAX_SIGNAL_NAME];
314 char signal_shutdown_name[MAX_SIGNAL_NAME];
315 static void setup_signal_names(char *prefix)
317 ap_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);
318 ap_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name),
319 "%s_shutdown", signal_name_prefix);
320 ap_snprintf(signal_restart_name, sizeof(signal_restart_name),
321 "%s_restart", signal_name_prefix);
325 * Routines that deal with sockets, some are WIN32 specific...
327 static int s_iInitCount = 0;
328 static int AMCSocketInitialize(void)
330 int iVersionRequested;
334 if (s_iInitCount > 0) {
338 else if (s_iInitCount < 0)
339 return (s_iInitCount);
341 /* s_iInitCount == 0. Do the initailization */
342 iVersionRequested = MAKEWORD(2, 0);
343 err = WSAStartup((WORD) iVersionRequested, &wsaData);
346 return (s_iInitCount);
348 if (LOBYTE(wsaData.wVersion) != 1 ||
349 HIBYTE(wsaData.wVersion) != 1) {
352 return (s_iInitCount);
356 return (s_iInitCount);
359 static void AMCSocketCleanup(void)
361 if (--s_iInitCount == 0)
366 static void sock_disable_nagle(int s)
368 /* The Nagle algorithm says that we should delay sending partial
369 * packets in hopes of getting more data. We don't want to do
370 * this; we are not telnet. There are bad interactions between
371 * persistent connections and Nagle's algorithm that have very severe
372 * performance penalties. (Failing to disable Nagle is not much of a
373 * problem with simple HTTP.)
375 * In spite of these problems, failure here is not a shooting offense.
379 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
381 ap_log_error(APLOG_MARK, APLOG_WARNING, APR_SUCCESS, server_conf,
382 "setsockopt: (TCP_NODELAY)");
387 * Routines to deal with managing the list of listening sockets.
389 static ap_listen_rec *head_listener;
390 static ap_inline ap_listen_rec *find_ready_listener(fd_set * main_fds)
395 for (lr = head_listener; lr ; lr = lr->next) {
396 ap_get_os_sock(&nsd, lr->sd);
397 if (FD_ISSET(nsd, main_fds)) {
398 head_listener = lr->next;
399 if (head_listener == NULL)
400 head_listener = ap_listeners;
407 static int setup_listeners(server_rec *s)
410 int num_listeners = 0;
413 /* Setup the listeners */
416 if (ap_listen_open(s->process, s->port)) {
419 for (lr = ap_listeners; lr; lr = lr->next) {
421 if (lr->sd != NULL) {
422 ap_get_os_sock(&nsd, lr->sd);
423 FD_SET(nsd, &listenfds);
424 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
431 head_listener = ap_listeners;
433 return num_listeners;
436 static int setup_inherited_listeners(server_rec *s)
438 WSAPROTOCOL_INFO WSAProtocolInfo;
442 int num_listeners = 0;
445 /* Setup the listeners */
448 /* Set up a default listener if necessary */
450 if (ap_listeners == NULL) {
452 lr = ap_palloc(s->process->pool, sizeof(ap_listen_rec));
456 lr->next = ap_listeners;
460 /* Open the pipe to the parent process to receive the inherited socket
461 * data. The sockets have been set to listening in the parent process.
463 pipe = GetStdHandle(STD_INPUT_HANDLE);
464 for (lr = ap_listeners; lr; lr = lr->next) {
465 if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
466 &BytesRead, (LPOVERLAPPED) NULL)) {
467 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
468 "setup_inherited_listeners: Unable to read socket data from parent");
469 signal_parent(0); /* tell parent to die */
472 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
473 "Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.", my_pid);
474 nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
475 &WSAProtocolInfo, 0, 0);
476 if (nsd == INVALID_SOCKET) {
477 ap_log_error(APLOG_MARK, APLOG_CRIT, WSAGetLastError(), server_conf,
478 "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
479 signal_parent(0); /* tell parent to die */
483 FD_SET(nsd, &listenfds);
484 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
488 // ap_register_cleanup(p, (void *)lr->sd, socket_cleanup, ap_null_cleanup);
489 ap_put_os_sock(&lr->sd, &nsd, pconf);
492 /* Now, read the AcceptExCompPort from the parent */
493 ReadFile(pipe, &AcceptExCompPort, sizeof(AcceptExCompPort), &BytesRead, (LPOVERLAPPED) NULL);
496 for (lr = ap_listeners; lr; lr = lr->next) {
500 head_listener = ap_listeners;
501 return num_listeners;
505 /**********************************************************************
506 * Multithreaded implementation
508 * This code is fairly specific to Win32.
510 * The model used to handle requests is a set of threads. One "main"
511 * thread listens for new requests. When something becomes
512 * available, it does a select and places the newly available socket
513 * onto a list of "jobs" (add_job()). Then any one of a fixed number
514 * of "worker" threads takes the top job off the job list with
515 * remove_job() and handles that connection to completion. After
516 * the connection has finished the thread is free to take another
517 * job from the job list.
519 * In the code, the "main" thread is running within the child_main()
520 * function. The first thing this function does is create the
521 * worker threads, which operate in the child_sub_main() function. The
522 * main thread then goes into a loop within child_main() where they
523 * do a select() on the listening sockets. The select times out once
524 * per second so that the thread can check for an "exit" signal
525 * from the parent process (see below). If this signal is set, the
526 * thread can exit, but only after it has accepted all incoming
527 * connections already in the listen queue (since Win32 appears
528 * to through away listened but unaccepted connections when a
531 * Because the main and worker threads exist within a single process
532 * they are vulnerable to crashes or memory leaks (crashes can also
533 * be caused within modules, of course). There also needs to be a
534 * mechanism to perform restarts and shutdowns. This is done by
535 * creating the main & worker threads within a subprocess. A
536 * main process (the "parent process") creates one (or more)
537 * processes to do the work, then the parent sits around waiting
538 * for the working process to die, in which case it starts a new
539 * one. The parent process also handles restarts (by creating
540 * a new working process then signalling the previous working process
541 * exit ) and shutdowns (by signalling the working process to exit).
542 * The parent process operates within the master_main() function. This
543 * process also handles requests from the service manager (NT only).
545 * Signalling between the parent and working process uses a Win32
546 * event. Each child has a unique name for the event, which is
547 * passed to it with the -Z argument when the child is spawned. The
548 * parent sets (signals) this event to tell the child to die.
549 * At present all children do a graceful die - they finish all
550 * current jobs _and_ empty the listen queue before they exit.
551 * A non-graceful die would need a second event. The -Z argument in
552 * the child is also used to create the shutdown and restart events,
553 * since the prefix (apPID) contains the parent process PID.
555 * The code below starts with functions at the lowest level -
556 * worker threads, and works up to the top level - the main()
557 * function of the parent process.
559 * The scoreboard (in process memory) contains details of the worker
560 * threads (within the active working process). There is no shared
561 * "scoreboard" between processes, since only one is ever active
562 * at once (or at most, two, when one has been told to shutdown but
563 * is processes outstanding requests, and a new one has been started).
564 * This is controlled by a "start_mutex" which ensures only one working
565 * process is active at once.
566 **********************************************************************/
570 * Definition of jobs, shared by main and worker threads.
573 typedef struct joblist_s {
574 struct joblist_s *next;
579 * Globals common to main and worker threads. This structure is not
580 * used by the parent process.
583 typedef struct globals_s {
584 semaphore *jobsemaphore;
591 globals allowed_globals =
592 {NULL, NULL, NULL, NULL, 0};
593 #define MAX_SELECT_ERRORS 100
594 #define PADDED_ADDR_SIZE sizeof(SOCKADDR_IN)+16
596 /* Windows 9x specific code...
597 * Accept processing for on Windows 95/98 uses a producer/consumer queue
598 * model. A single thread accepts connections and queues the accepted socket
599 * to the accept queue for consumption by a pool of worker threads.
601 * win9x_get_connection()
602 * Calls remove_job() to pull a job from the accept queue. All the worker
603 * threads block on remove_job.
604 * accept_and_queue_connections()
605 * The accept threads runs this function, which accepts connections off
606 * the network and calls add_job() to queue jobs to the accept_queue.
607 * add_job()/remove_job()
608 * Add or remove an accepted socket from the list of sockets
609 * connected to clients. allowed_globals.jobmutex protects
610 * against multiple concurrent access to the linked list of jobs.
612 static void add_job(int sock)
616 new_job = (joblist *) malloc(sizeof(joblist));
617 if (new_job == NULL) {
618 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
619 "Ouch! Out of memory in add_job()!");
622 new_job->next = NULL;
623 new_job->sock = sock;
625 ap_lock(allowed_globals.jobmutex);
627 if (allowed_globals.jobtail != NULL)
628 allowed_globals.jobtail->next = new_job;
629 allowed_globals.jobtail = new_job;
630 if (!allowed_globals.jobhead)
631 allowed_globals.jobhead = new_job;
632 allowed_globals.jobcount++;
633 release_semaphore(allowed_globals.jobsemaphore);
635 ap_unlock(allowed_globals.jobmutex);
638 static int remove_job(void)
643 acquire_semaphore(allowed_globals.jobsemaphore);
644 ap_lock(allowed_globals.jobmutex);
646 if (workers_may_exit && !allowed_globals.jobhead) {
647 ap_unlock(allowed_globals.jobmutex);
650 job = allowed_globals.jobhead;
652 allowed_globals.jobhead = job->next;
653 if (allowed_globals.jobhead == NULL)
654 allowed_globals.jobtail = NULL;
655 ap_unlock(allowed_globals.jobmutex);
662 static void accept_and_queue_connections(void * dummy)
664 int requests_this_child = 0;
669 int nsd = INVALID_SOCKET;
670 struct sockaddr_in sa_client;
671 int count_select_errors = 0;
675 while (!workers_may_exit) {
676 if (ap_max_requests_per_child && (requests_this_child > ap_max_requests_per_child)) {
680 tv.tv_sec = wait_time;
682 memcpy(&main_fds, &listenfds, sizeof(fd_set));
684 // rc = ap_select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
685 rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
687 if (rc == 0 || (rc == SOCKET_ERROR && h_errno == WSAEINTR)) {
688 count_select_errors = 0; /* reset count of errors */
691 else if (rc == SOCKET_ERROR) {
692 /* A "real" error occurred, log it and increment the count of
693 * select errors. This count is used to ensure we don't go into
694 * a busy loop of continuous errors.
696 ap_log_error(APLOG_MARK, APLOG_INFO, h_errno, server_conf,
697 "select failed with errno %d", h_errno);
698 count_select_errors++;
699 if (count_select_errors > MAX_SELECT_ERRORS) {
700 workers_may_exit = 1;
701 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
702 "Too many errors in select loop. Child process exiting.");
708 lr = find_ready_listener(&main_fds);
710 /* fetch the native socket descriptor */
711 ap_get_os_sock(&nsd, lr->sd);
716 clen = sizeof(sa_client);
717 csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
718 if (csd == INVALID_SOCKET) {
721 } while (csd < 0 && h_errno == WSAEINTR);
724 if (h_errno != WSAECONNABORTED) {
725 ap_log_error(APLOG_MARK, APLOG_ERR, h_errno, server_conf,
726 "accept: (client socket)");
731 requests_this_child++;
734 SetEvent(exit_event);
736 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
740 if (context == NULL) {
741 /* allocate the completion context and the transaction pool */
742 context = ap_pcalloc(pconf, sizeof(COMP_CONTEXT));
744 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
745 "win9x_get_connection: ap_pcalloc() failed. Process will exit.");
748 ap_create_context(&context->ptrans, pconf);
753 ap_clear_pool(context->ptrans);
754 context->accept_socket = remove_job();
755 if (context->accept_socket == -1) {
758 //ap_note_cleanups_for_socket(ptrans, csd);
759 len = sizeof(struct sockaddr);
760 context->sa_server = ap_palloc(context->ptrans, len);
761 if (getsockname(context->accept_socket,
762 context->sa_server, &len)== SOCKET_ERROR) {
763 ap_log_error(APLOG_MARK, APLOG_WARNING, WSAGetLastError(), server_conf,
764 "getsockname failed");
767 len = sizeof(struct sockaddr);
768 context->sa_client = ap_palloc(context->ptrans, len);
769 if ((getpeername(context->accept_socket,
770 context->sa_client, &len)) == SOCKET_ERROR) {
771 ap_log_error(APLOG_MARK, APLOG_WARNING, h_errno, server_conf,
772 "getpeername failed with error %d\n", WSAGetLastError());
773 memset(&context->sa_client, '\0', sizeof(context->sa_client));
776 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
778 /* do we NEED_DUPPED_CSD ?? */
785 * Windows 2000/NT specific code...
786 * create_acceptex_context()
787 * reset_acceptex_context()
788 * drain_acceptex_complport()
789 * winnt_get_connection()
791 * TODO: Insert a discussion of 'completion contexts' and what these function do here...
793 static void drain_acceptex_complport(HANDLE hComplPort, BOOLEAN bCleanUp)
796 PCOMP_CONTEXT context;
804 rc = GetQueuedCompletionStatus(hComplPort, &BytesRead, &CompKey,
807 lastError = GetLastError();
808 if (lastError == ERROR_OPERATION_ABORTED) {
809 ap_log_error(APLOG_MARK,APLOG_INFO,lastError, server_conf,
810 "Child: %d - Draining a packet off the completion port.", my_pid);
815 ap_log_error(APLOG_MARK,APLOG_INFO,APR_SUCCESS, server_conf,
816 "Child: %d - Nuking an active connection. context = %x", my_pid, context);
817 context = (PCOMP_CONTEXT) pol;
818 if (context && bCleanUp) {
819 /* It is only valid to clean-up in the process that initiated the I/O */
820 closesocket(context->accept_socket);
821 CloseHandle(context->Overlapped.hEvent);
825 static int create_acceptex_context(ap_context_t *_pconf, ap_listen_rec *lr)
827 PCOMP_CONTEXT context;
832 /* allocate the completion context */
833 context = ap_pcalloc(_pconf, sizeof(COMP_CONTEXT));
835 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
836 "create_acceptex_context: ap_pcalloc() failed. Process will exit.");
840 /* initialize the completion context */
842 context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
843 if (context->Overlapped.hEvent == NULL) {
844 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
845 "create_acceptex_context: CreateEvent() failed. Process will exit.");
848 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
849 if (context->accept_socket == INVALID_SOCKET) {
850 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
851 "create_acceptex_context: socket() failed. Process will exit.");
854 ap_create_context(&context->ptrans, _pconf);
855 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
856 context->recv_buf = context->conn_io->inbase;
857 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
858 ap_get_os_sock(&nsd, context->lr->sd);
860 /* AcceptEx on the completion context. The completion context will be signaled
861 * when a connection is accepted. */
862 if (!AcceptEx(nsd, context->accept_socket,
864 0, //context->recv_buf_size,
865 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
867 (LPOVERLAPPED) context)) {
868 lasterror = WSAGetLastError();
869 if (lasterror != ERROR_IO_PENDING) {
870 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
871 "create_acceptex_context: AcceptEx failed. Process will exit.");
879 static ap_inline int reset_acceptex_context(PCOMP_CONTEXT context)
885 context->lr->count++;
887 if (context->accept_socket == -1)
888 context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
890 if (context->accept_socket == INVALID_SOCKET) {
891 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
892 "reset_acceptex_context: socket() failed. Process will exit.");
896 ap_clear_pool(context->ptrans);
897 context->sock = NULL;
898 context->conn_io = ap_bcreate(context->ptrans, B_RDWR);
899 context->recv_buf = context->conn_io->inbase;
900 context->recv_buf_size = context->conn_io->bufsiz - 2*PADDED_ADDR_SIZE;
901 ap_get_os_sock(&nsd, context->lr->sd);
903 if (!AcceptEx(nsd, context->accept_socket,
905 0, //context->recv_buf_size,
906 PADDED_ADDR_SIZE, PADDED_ADDR_SIZE,
907 &BytesRead, (LPOVERLAPPED) context)) {
908 lasterror = WSAGetLastError();
909 if (lasterror != ERROR_IO_PENDING) {
910 ap_log_error(APLOG_MARK,APLOG_ERR, WSAGetLastError(), server_conf,
911 "reset_acceptex_context: AcceptEx failed. Leaving the process running.");
918 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT context)
920 int requests_this_child = 0;
926 if (context != NULL) {
927 /* If child shutdown has been signaled, clean-up the completion context */
928 if (workers_may_exit) {
929 CloseHandle(context->Overlapped.hEvent);
933 context->accept_socket = -1; /* Don't reuse the accept_socket */
934 if (reset_acceptex_context(context) == -1) {
935 if (context->accept_socket != -1)
936 closesocket(context->accept_socket);
937 CloseHandle(context->Overlapped.hEvent);
944 rc = GetQueuedCompletionStatus(AcceptExCompPort,
950 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
951 "Child: %d - GetQueuedCompletionStatus() failed", my_pid);
956 context = (PCOMP_CONTEXT) pol;
957 if (CompKey == 999) {
961 /* Each listener needs at least 1 context available to receive connections on.
962 * Create additional listener contexts if needed.
964 ap_lock(allowed_globals.jobmutex);
965 context->lr->count--;
966 if ((context->lr->count < 2) && !workers_may_exit) {
967 if (create_acceptex_context(pconf, context->lr) == -1) {
968 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
969 "Unable to create an AcceptEx completion context -- process will exit");
974 ap_unlock(allowed_globals.jobmutex);
976 /* Received a connection */
977 context->conn_io->incnt = BytesRead;
978 GetAcceptExSockaddrs(context->recv_buf,
979 0, //context->recv_buf_size,
983 &context->sa_server_len,
985 &context->sa_client_len);
991 * worker_main() - this is the main loop for the worker threads
994 * Each thread runs within this function. They wait within remove_job()
995 * for a job to become available, then handle all the requests on that
996 * connection until it is closed, then return to remove_job().
998 * The worker thread will exit when it removes a job which contains
999 * socket number -1. This provides a graceful thread exit, since
1000 * it will never exit during a connection.
1002 * This code in this function is basically equivalent to the child_main()
1003 * from the multi-process (Unix) environment, except that we
1005 * - do not call child_init_modules (child init API phase)
1006 * - block in remove_job, and when unblocked we have an already
1007 * accepted socket, instead of blocking on a mutex or select().
1010 static void worker_main(int child_num)
1012 static BOOLEAN bListenersStarted = FALSE;
1013 PCOMP_CONTEXT context = NULL;
1015 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1016 /* Windows NT/2000: Create AcceptEx completion contexts for each of the
1019 ap_lock(allowed_globals.jobmutex);
1020 if (!bListenersStarted) {
1023 bListenersStarted = TRUE;
1024 for (lr = ap_listeners; lr != NULL; lr = lr->next) {
1025 for(i=0; i<2; i++) {
1027 if (create_acceptex_context(pconf, lr) == -1) {
1028 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1029 "Unable to create an AcceptEx completion context -- process will exit");
1030 signal_parent(0); /* tell parent to die */
1035 ap_unlock(allowed_globals.jobmutex);
1039 conn_rec *current_conn;
1042 /* Grab a connection off the network */
1043 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1044 context = win9x_get_connection(context);
1047 context = winnt_get_connection(context);
1052 sock_disable_nagle(context->accept_socket);
1053 ap_put_os_sock(&context->sock, &context->accept_socket, context->ptrans);
1054 ap_register_cleanup(context->ptrans, context->sock, socket_cleanup, ap_null_cleanup);
1055 iol = win32_attach_socket(context->ptrans, context->sock);
1057 ap_log_error(APLOG_MARK, APLOG_ERR, APR_ENOMEM, server_conf,
1058 "worker_main: attach_socket() failed. Continuing...");
1059 closesocket(context->accept_socket);
1062 ap_bpush_iol(context->conn_io, iol);
1063 current_conn = ap_new_connection(context->ptrans, server_conf, context->conn_io,
1064 (struct sockaddr_in *) context->sa_client,
1065 (struct sockaddr_in *) context->sa_server,
1068 ap_process_connection(current_conn);
1071 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1072 "child_main: Setting exit_event");
1073 SetEvent(exit_event);
1075 /* TODO: Add code to clean-up completion contexts here */
1078 static void cleanup_thread(thread **handles, int *thread_cnt, int thread_to_clean)
1082 CloseHandle(handles[thread_to_clean]);
1083 for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1084 handles[i] = handles[i + 1];
1091 * child_main() is main loop for the child process. The loop in
1092 * this function becomes the controlling thread for the actually working
1093 * threads (which run in a loop in child_sub_main()).
1095 * exit_event, start_mutex, ap_threads_per_child, server_conf,
1096 * h_errno defined to WSAGetLastError in winsock2.h,
1098 static void child_main()
1100 int nthreads = ap_threads_per_child;
1102 thread **child_handles;
1107 ap_context_t *pchild;
1109 ap_create_context(&pchild, pconf);
1111 // ap_restart_time = time(NULL);
1113 * Wait until we have permission to start accepting connections.
1114 * start_mutex is used to ensure that only one child ever
1115 * goes into the listen/accept loop at once.
1117 status = ap_lock(start_mutex);
1118 if (status != APR_SUCCESS) {
1119 ap_log_error(APLOG_MARK,APLOG_ERR, status, server_conf,
1120 "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1121 signal_parent(0); /* tell parent to die */
1122 ap_destroy_context(pchild);
1125 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, "Child %d: Acquired the start mutex", my_pid);
1127 /* Setup the listening sockets */
1130 setup_listeners(server_conf);
1132 /* Associate the socket with the IO Completion port */
1133 for (lr = ap_listeners; lr; lr = lr->next) {
1135 ap_get_os_sock(&nsd,lr->sd);
1136 CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
1140 setup_inherited_listeners(server_conf);
1142 if (listenmaxfd == INVALID_SOCKET) {
1143 /* No sockets were made, better log something and exit */
1144 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, NULL,
1145 "No sockets were created for listening");
1146 signal_parent(0); /* tell parent to die */
1147 ap_destroy_context(pchild);
1151 allowed_globals.jobsemaphore = create_semaphore(0);
1152 ap_create_lock(&allowed_globals.jobmutex, APR_MUTEX, APR_INTRAPROCESS, NULL, pchild);
1154 /* Create the worker thread pool */
1155 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf, "Child %d: Creating %d worker threads",my_pid, nthreads);
1156 child_handles = (thread *) alloca(nthreads * sizeof(int));
1157 for (i = 0; i < nthreads; i++) {
1158 child_handles[i] = (thread *) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1159 NULL, 0, &thread_id);
1162 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1163 /* Win95/98: Create the accept thread */
1164 _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) accept_and_queue_connections,
1165 (void *) i, 0, &thread_id);
1168 /* Wait for the exit event to be signaled by the parent process */
1169 rv = WaitForSingleObject(exit_event, INFINITE);
1171 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1172 "Child %d: Exit event signaled. Child process is ending.", my_pid);
1173 workers_may_exit = 1;
1175 /* Shutdown the worker threads */
1176 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1177 for (i = 0; i < nthreads; i++) {
1181 else { /* Windows NT/2000 */
1182 /* Hack alert... Give the server a couple of seconds to receive
1183 * connections and drain AcceptEx completion contexts. We will
1184 * probably drop a few connections across a graceful restart, but
1185 * hopefully not many. This needs work...*/
1188 /* Tell the worker threads to exit. Any connections accepted on
1189 * the completion port from now will be dropped */
1190 for (i=0; i < nthreads; i++) {
1191 if (!PostQueuedCompletionStatus(AcceptExCompPort, 0, 999, NULL)) {
1192 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1193 "PostQueuedCompletionStatus failed");
1198 /* Wait for the worker threads to die */
1199 end_time = time(NULL) + 180;
1201 rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1202 if (rv != WAIT_TIMEOUT) {
1203 rv = rv - WAIT_OBJECT_0;
1204 ap_assert((rv >= 0) && (rv < nthreads));
1205 cleanup_thread(child_handles, &nthreads, rv);
1210 for (i = 0; i < nthreads; i++) {
1211 TerminateThread(child_handles[i], 1);
1212 CloseHandle(child_handles[i]);
1214 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1215 "Child %d: All worker threads have ended.", my_pid);
1217 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1218 /* All the worker threads should have exited by now, which will
1219 * cause any outstanding I/O on the completion port to be aborted.
1220 * Drain the completion port of this aborted I/O/
1222 drain_acceptex_complport(AcceptExCompPort, TRUE);
1225 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, server_conf,
1226 "Child %d: Releasing the start mutex", my_pid);
1227 ap_unlock(start_mutex);
1229 /* Still need to register cleanups for the sockets */
1230 CloseHandle(AcceptExCompPort);
1231 destroy_semaphore(allowed_globals.jobsemaphore);
1232 ap_destroy_lock(allowed_globals.jobmutex);
1234 ap_destroy_context(pchild);
1238 * Spawn a child Apache process. The child process has the command line arguments from
1239 * argc and argv[], plus a -Z argument giving the name of an event. The child should
1240 * open and poll or wait on this event. When it is signalled, the child should die.
1241 * prefix is a prefix string for the event name.
1243 * The child_num argument on entry contains a serial number for this child (used to create
1244 * a unique event name). On exit, this number will have been incremented by one, ready
1245 * for the next call.
1247 * On exit, the value pointed to be *ev will contain the event created
1248 * to signal the new child process.
1250 * The return value is the handle to the child process if successful, else -1. If -1 is
1251 * returned the error will already have been logged by ap_log_error().
1254 /**********************************************************************
1255 * master_main - this is the parent (main) process. We create a
1256 * child process to do the work, then sit around waiting for either
1257 * the child to exit, or a restart or exit signal. If the child dies,
1258 * we just respawn a new one. If we have a shutdown or graceful restart,
1259 * tell the child to die when it is ready. If it is a non-graceful
1260 * restart, force the child to die immediately.
1261 **********************************************************************/
1263 #define MAX_PROCESSES 50 /* must be < MAX_WAIT_OBJECTS-1 */
1265 static void cleanup_process(HANDLE *handles, HANDLE *events, int position, int *processes)
1270 CloseHandle(handles[position]);
1271 CloseHandle(events[position]);
1273 handle = (int)handles[position];
1275 for (i = position; i < (*processes)-1; i++) {
1276 handles[i] = handles[i + 1];
1277 events[i] = events[i + 1];
1282 static int create_process(ap_context_t *p, HANDLE *handles, HANDLE *events, int *processes)
1289 STARTUPINFO si; /* Filled in prior to call to CreateProcess */
1290 PROCESS_INFORMATION pi; /* filled in on call to CreateProces */
1294 HANDLE hPipeRead = NULL;
1295 HANDLE hPipeWrite = NULL;
1296 SECURITY_ATTRIBUTES sa = {0};
1298 sa.nLength = sizeof(sa);
1299 sa.bInheritHandle = TRUE;
1300 sa.lpSecurityDescriptor = NULL;
1302 /* Create the IOCompletionPort */
1303 if (AcceptExCompPort == NULL) {
1304 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1307 0); /* CONCURRENT ACTIVE THREADS */
1308 if (AcceptExCompPort == NULL) {
1309 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1310 "Unable to create the AcceptExCompletionPort -- process will exit");
1315 /* Build the command line. Should look something like this:
1316 * C:/apache/bin/apache.exe -f ap_server_confname
1317 * First, get the path to the executable...
1319 rv = GetModuleFileName(NULL, buf, sizeof(buf));
1320 if (rv == sizeof(buf)) {
1321 ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, server_conf,
1322 "Parent: Path to Apache process too long");
1324 } else if (rv == 0) {
1325 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1326 "Parent: GetModuleFileName() returned NULL for current process.");
1330 /* Build the command line */
1331 pCommand = ap_psprintf(p, "\"%s\"", buf);
1332 for (i = 1; i < server_conf->process->argc; i++) {
1333 pCommand = ap_pstrcat(p, pCommand, " \"", server_conf->process->argv[i], "\"", NULL);
1336 /* Create a pipe to send socket info to the child */
1337 if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1338 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1339 "Parent: Unable to create pipe to child process.\n");
1343 SetEnvironmentVariable("AP_PARENT_PID",ap_psprintf(p,"%d",parent_pid));
1345 /* Give the read end of the pipe (hPipeRead) to the child as stdin. The
1346 * parent will write the socket data to the child on this pipe.
1348 memset(&si, 0, sizeof(si));
1349 memset(&pi, 0, sizeof(pi));
1351 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1352 si.wShowWindow = SW_HIDE;
1353 si.hStdInput = hPipeRead;
1355 if (!CreateProcess(NULL, pCommand, NULL, NULL,
1356 TRUE, /* Inherit handles */
1357 CREATE_SUSPENDED, /* Creation flags */
1358 NULL, /* Environment block */
1361 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1362 "Parent: Not able to create the child process.");
1364 * We must close the handles to the new process and its main thread
1365 * to prevent handle and memory leaks.
1367 CloseHandle(pi.hProcess);
1368 CloseHandle(pi.hThread);
1373 LPWSAPROTOCOL_INFO lpWSAProtocolInfo;
1374 HANDLE hDupedCompPort;
1376 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1377 "Parent: Created child process %d", pi.dwProcessId);
1379 SetEnvironmentVariable("AP_PARENT_PID",NULL);
1381 /* Create the exit_event, apCchild_pid */
1382 sa.nLength = sizeof(sa);
1383 sa.bInheritHandle = TRUE;
1384 sa.lpSecurityDescriptor = NULL;
1385 kill_event = CreateEvent(&sa, TRUE, FALSE, ap_psprintf(pconf,"apC%d", pi.dwProcessId));
1387 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1388 "Parent: Could not create exit event for child process");
1389 CloseHandle(pi.hProcess);
1390 CloseHandle(pi.hThread);
1394 /* Assume the child process lives. Update the process and event tables */
1395 handles[*processes] = pi.hProcess;
1396 events[*processes] = kill_event;
1399 /* We never store the thread's handle, so close it now. */
1400 ResumeThread(pi.hThread);
1401 CloseHandle(pi.hThread);
1403 /* Run the chain of open sockets. For each socket, duplicate it
1404 * for the target process then send the WSAPROTOCOL_INFO
1405 * (returned by dup socket) to the child */
1406 for (lr = ap_listeners; lr; lr = lr->next) {
1408 lpWSAProtocolInfo = ap_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1409 ap_get_os_sock(&nsd,lr->sd);
1410 /* Associate the socket with the IOcompletion port */
1411 CreateIoCompletionPort((HANDLE) nsd, AcceptExCompPort, 0, 0);
1412 ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_INFO, APR_SUCCESS, server_conf,
1413 "Parent: Duplicating socket %d and sending it to child process %d", nsd, pi.dwProcessId);
1414 if (WSADuplicateSocket(nsd, pi.dwProcessId,
1415 lpWSAProtocolInfo) == SOCKET_ERROR) {
1416 ap_log_error(APLOG_MARK, APLOG_CRIT, h_errno, server_conf,
1417 "Parent: WSADuplicateSocket failed for socket %d.", lr->sd );
1421 if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1423 (LPOVERLAPPED) NULL)) {
1424 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1425 "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1428 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1429 "Parent: BytesWritten = %d WSAProtocolInfo = %x20", BytesWritten, *lpWSAProtocolInfo);
1431 /* Now, send the AcceptEx completion port to the child */
1432 if (!DuplicateHandle(GetCurrentProcess(), AcceptExCompPort,
1433 pi.hProcess, &hDupedCompPort, 0,
1434 TRUE, DUPLICATE_SAME_ACCESS)) {
1435 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1436 "Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
1439 WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
1442 CloseHandle(hPipeRead);
1443 CloseHandle(hPipeWrite);
1448 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1450 int remaining_children_to_start = ap_daemons_to_start;
1454 int restart_pending = 0;
1455 int shutdown_pending = 0;
1456 int current_live_processes = 0; /* number of child process we know about */
1458 HANDLE process_handles[MAX_PROCESSES];
1459 HANDLE process_kill_events[MAX_PROCESSES];
1463 /* Create child process
1464 * Should only be one in this version of Apache for WIN32
1466 service_set_status(SERVICE_START_PENDING);
1467 while (remaining_children_to_start--) {
1468 if (create_process(pconf, process_handles, process_kill_events,
1469 ¤t_live_processes) < 0) {
1470 ap_log_error(APLOG_MARK, APLOG_CRIT, GetLastError(), server_conf,
1471 "master_main: create child process failed. Exiting.");
1472 shutdown_pending = 1;
1476 service_set_status(SERVICE_RUNNING);
1478 restart_pending = shutdown_pending = 0;
1480 /* Wait for shutdown or restart events or for child death */
1481 process_handles[current_live_processes] = shutdown_event;
1482 process_handles[current_live_processes+1] = restart_event;
1483 printf("process/shutdown/restart %d %d %d\n", process_handles[0], process_handles[1], process_handles[2]);
1484 rv = WaitForMultipleObjects(current_live_processes+2, (HANDLE *)process_handles,
1486 cld = rv - WAIT_OBJECT_0;
1487 if (rv == WAIT_FAILED) {
1488 /* Something serious is wrong */
1489 ap_log_error(APLOG_MARK,APLOG_CRIT, GetLastError(), server_conf,
1490 "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1491 shutdown_pending = 1;
1493 else if (rv == WAIT_TIMEOUT) {
1494 /* Hey, this cannot happen */
1495 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1496 "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1497 shutdown_pending = 1;
1499 else if (cld == current_live_processes) {
1500 /* shutdown_event signalled */
1501 shutdown_pending = 1;
1502 printf("shutdown event signaled\n");
1503 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1504 "master_main: Shutdown event signaled -- doing server shutdown.");
1505 if (ResetEvent(shutdown_event) == 0) {
1506 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1507 "ResetEvent(shutdown_event)");
1511 else if (cld == current_live_processes+1) {
1512 /* restart_event signalled */
1513 int children_to_kill = current_live_processes;
1514 restart_pending = 1;
1515 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1516 "master_main: Restart event signaled. Doing a graceful restart.");
1517 if (ResetEvent(restart_event) == 0) {
1518 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1519 "master_main: ResetEvent(restart_event) failed.");
1521 /* Signal each child process to die
1522 * We are making a big assumption here that the child process, once signaled,
1523 * will REALLY go away. Since this is a restart, we do not want to hold the
1524 * new child process up waiting for the old child to die. Remove the old
1525 * child out of the process_handles ap_table_t and hope for the best...
1527 for (i = 0; i < children_to_kill; i++) {
1528 printf("SetEvent handle = %d\n", process_kill_events[i]);
1529 if (SetEvent(process_kill_events[i]) == 0)
1530 ap_log_error(APLOG_MARK, APLOG_ERR, GetLastError(), s,
1531 "master_main: SetEvent for child process in slot #%d failed", i);
1532 cleanup_process(process_handles, process_kill_events, i, ¤t_live_processes);
1536 /* A child process must have exited because of a fatal error condition (seg fault, etc.).
1537 * Remove the dead process
1538 * from the process_handles and process_kill_events ap_table_t and create a new
1540 * TODO: Consider restarting the child immediately without looping through http_main
1541 * and without rereading the configuration. Will need this if we ever support multiple
1542 * children. One option, create a parent thread which waits on child death and restarts it.
1544 restart_pending = 1;
1545 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, server_conf,
1546 "master_main: Child process failed. Restarting the child process.");
1547 ap_assert(cld < current_live_processes);
1548 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1549 /* APD2("main_process: child in slot %d died", rv); */
1550 /* restart_child(process_hancles, process_kill_events, cld, ¤t_live_processes); */
1552 /* Drain the AcceptEx completion port of any outstanding I/O pending for the dead
1554 drain_acceptex_complport(AcceptExCompPort, FALSE);
1558 if (shutdown_pending) {
1559 int tmstart = time(NULL);
1560 /* Signal each child processes to die */
1561 for (i = 0; i < current_live_processes; i++) {
1562 printf("SetEvent handle = %d\n", process_kill_events[i]);
1563 if (SetEvent(process_kill_events[i]) == 0)
1564 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1565 "master_main: SetEvent for child process in slot #%d failed", i);
1568 while (current_live_processes && ((tmstart+60) > time(NULL))) {
1569 rv = WaitForMultipleObjects(current_live_processes, (HANDLE *)process_handles, FALSE, 2000);
1570 if (rv == WAIT_TIMEOUT)
1572 ap_assert(rv != WAIT_FAILED);
1573 cld = rv - WAIT_OBJECT_0;
1574 ap_assert(rv < current_live_processes);
1575 cleanup_process(process_handles, process_kill_events, cld, ¤t_live_processes);
1577 for (i = 0; i < current_live_processes; i++) {
1578 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO, APR_SUCCESS, server_conf,
1579 "forcing termination of child #%d (handle %d)", i, process_handles[i]);
1580 TerminateProcess((HANDLE) process_handles[i], 1);
1582 return (0); /* Tell the caller we are shutting down */
1585 return (1); /* Tell the caller we want a restart */
1589 * winnt_pre_config() hook
1591 static void winnt_pre_config(ap_context_t *pconf, ap_context_t *plog, ap_context_t *ptemp)
1595 one_process = !!getenv("ONE_PROCESS");
1597 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1598 GetVersionEx(&osver);
1600 /* AP_PARENT_PID is only valid in the child */
1601 pid = getenv("AP_PARENT_PID");
1603 /* This is the child */
1604 parent_pid = atoi(pid);
1608 /* This is the parent */
1609 parent_pid = my_pid = getpid();
1613 ap_listen_pre_config();
1614 ap_daemons_to_start = DEFAULT_NUM_DAEMON;
1615 ap_threads_per_child = DEFAULT_START_THREAD;
1616 ap_pid_fname = DEFAULT_PIDLOG;
1617 max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1619 ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1623 static void winnt_post_config(ap_context_t *pconf, ap_context_t *plog, ap_context_t *ptemp, server_rec* server_conf)
1625 server_conf = server_conf;
1628 API_EXPORT(int) ap_mpm_run(ap_context_t *_pconf, ap_context_t *plog, server_rec *s )
1631 char* exit_event_name;
1632 static int restart = 0; /* Default is to not restart */
1634 static HANDLE shutdown_event; /* used to signal shutdown to parent */
1635 static HANDLE restart_event; /* used to signal a restart to parent */
1640 if ((parent_pid != my_pid) || one_process) {
1642 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1643 "Child %d: Child process is running", my_pid);
1644 AMCSocketInitialize();
1645 exit_event_name = ap_psprintf(pconf, "apC%d", my_pid);
1646 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1649 /* Create the IO CompletionPort */
1650 if (AcceptExCompPort == NULL) {
1651 AcceptExCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1653 if (AcceptExCompPort == NULL) {
1654 ap_log_error(APLOG_MARK,APLOG_ERR, GetLastError(), server_conf,
1655 "Unable to create the AcceptExCompletionPort -- process will exit");
1659 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1660 exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name);
1663 ap_child_init_lock(&start_mutex, signal_name_prefix, pconf);
1664 exit_event = OpenEvent(EVENT_ALL_ACCESS, FALSE, exit_event_name);
1665 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, server_conf,
1666 "Child %d: exit_event_name = %s", my_pid, exit_event_name);
1668 ap_assert(start_mutex);
1669 ap_assert(exit_event);
1673 CloseHandle(exit_event);
1678 /* Parent process */
1679 PSECURITY_ATTRIBUTES sa = GetNullACL(); /* returns NULL if invalid (Win95?) */
1681 setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1683 ap_log_pid(pconf, ap_pid_fname);
1685 service_set_status(SERVICE_START_PENDING);
1686 AMCSocketInitialize();
1687 // setup_signal_names(ap_psprintf(pconf,"ap%d", parent_pid));
1689 /* Create shutdown event, apPID_shutdown, where PID is the parent
1690 * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
1692 shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
1693 if (!shutdown_event) {
1694 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), s,
1695 "master_main: Cannot create shutdown event %s", signal_shutdown_name);
1696 CleanNullACL((void *)sa);
1700 /* Create restart event, apPID_restart, where PID is the parent
1701 * Apache process ID. Restart is signaled by 'apache -k restart'.
1703 // restart_event = CreateEvent(sa, TRUE, FALSE, signal_restart_name);
1704 restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
1705 if (!restart_event) {
1706 CloseHandle(shutdown_event);
1707 ap_log_error(APLOG_MARK, APLOG_EMERG, GetLastError(), s,
1708 "ap_run_mpm: Cannot create restart event %s", signal_restart_name);
1709 CleanNullACL((void *)sa);
1712 CleanNullACL((void *)sa);
1714 /* Create the start mutex, apPID, where PID is the parent Apache process ID.
1715 * Ths start mutex is used during a restart to prevent more than one
1716 * child process from entering the accept loop at once.
1718 // ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,pconf);
1719 ap_create_lock(&start_mutex,APR_MUTEX, APR_CROSS_PROCESS,signal_name_prefix,s->process->pool);
1720 /* TODO: Add some code to detect failure */
1724 restart = master_main(server_conf, shutdown_event, restart_event);
1727 const char *pidfile = NULL;
1728 /* Shutting down. Clean up... */
1729 pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1730 if ( pidfile != NULL && unlink(pidfile) == 0)
1731 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO,APR_SUCCESS,
1732 server_conf, "removed PID file %s (pid=%ld)",
1733 pidfile, (long)getpid());
1734 ap_destroy_lock(start_mutex);
1736 CloseHandle(restart_event);
1737 CloseHandle(shutdown_event);
1740 service_set_status(SERVICE_STOPPED);
1746 static void winnt_hooks(void)
1750 /* Configuration hooks implemented by http_config.c ... */
1754 * Command processors
1756 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg)
1758 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1763 if (cmd->server->is_virtual) {
1764 return "PidFile directive not allowed in <VirtualHost>";
1770 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg)
1772 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1777 ap_threads_per_child = atoi(arg);
1778 if (ap_threads_per_child > HARD_THREAD_LIMIT) {
1779 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1780 "WARNING: ThreadsPerChild of %d exceeds compile time"
1781 " limit of %d threads,", ap_threads_per_child,
1783 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1784 " lowering ThreadsPerChild to %d. To increase, please"
1785 " see the HARD_THREAD_LIMIT define in src/include/httpd.h.",
1788 else if (ap_threads_per_child < 1) {
1789 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1790 "WARNING: Require ThreadsPerChild > 0, setting to 1");
1791 ap_threads_per_child = 1;
1797 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg)
1799 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1804 max_requests_per_child = atoi(arg);
1809 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg)
1813 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1818 fname = ap_server_root_relative(cmd->pool, arg);
1819 if ((stat(fname, &finfo) == -1) || !S_ISDIR(finfo.st_mode)) {
1820 return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
1821 " does not exist or is not a directory", NULL);
1823 ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1827 /* Stub functions until this MPM supports the connection status API */
1829 API_EXPORT(void) ap_update_connection_status(long conn_id, const char *key, \
1835 API_EXPORT(void) ap_reset_connection_status(long conn_id)
1840 API_EXPORT(ap_array_header_t *) ap_get_status_table(ap_context_t *p)
1846 static const command_rec winnt_cmds[] = {
1848 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
1849 "A file for logging the server process ID"},
1850 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
1851 "Number of threads each child creates" },
1852 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
1853 "Maximum number of requests a particular child serves before dying." },
1854 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
1855 "The location of the directory Apache changes to before dumping core" },
1859 module MODULE_VAR_EXPORT mpm_winnt_module = {
1861 winnt_pre_config, /* hook run before configuration is read */
1862 NULL, /* create per-directory config structure */
1863 NULL, /* merge per-directory config structures */
1864 NULL, /* create per-server config structure */
1865 NULL, /* merge per-server config structures */
1866 winnt_cmds, /* command ap_table_t */
1867 NULL, /* handlers */
1868 winnt_hooks /* register_hooks */