1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2002 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.
61 #include "http_main.h"
63 #include "http_config.h" /* for read_config */
64 #include "http_core.h" /* for get_remote_host */
65 #include "http_connection.h"
66 #include "apr_portable.h"
67 #include "apr_getopt.h"
68 #include "apr_strings.h"
71 #include "apr_thread_mutex.h"
73 #include "ap_config.h"
74 #include "ap_listen.h"
75 #include "mpm_default.h"
76 #include "mpm_winnt.h"
77 #include "mpm_common.h"
80 /* Limit on the threads per process. Clients will be locked out if more than
81 * this * HARD_SERVER_LIMIT are needed.
83 * We keep this for one reason it keeps the size of the scoreboard file small
84 * enough that we can read the whole thing without worrying too much about
87 #ifndef HARD_THREAD_LIMIT
88 #define HARD_THREAD_LIMIT 1920
91 /* Limit on the total --- clients will be locked out if more servers than
92 * this are needed. It is intended solely to keep the server from crashing
93 * when things get out of hand.
95 * We keep a hard maximum number of servers, for two reasons --- first off,
96 * in case something goes seriously wrong, we want to stop the fork bomb
97 * short of actually crashing the machine we're running on by filling some
98 * kernel table. Secondly, it keeps the size of the scoreboard file small
99 * enough that we can read the whole thing without worrying too much about
102 #define HARD_SERVER_LIMIT 1
104 /* scoreboard.c does the heavy lifting; all we do is create the child
105 * score by moving a handle down the pipe into the child's stdin.
107 extern apr_shm_t *ap_scoreboard_shm;
108 server_rec *ap_server_conf;
109 typedef HANDLE thread;
111 /* Definitions of WINNT MPM specific config globals */
112 static apr_pool_t *pconf;
113 static apr_pool_t *pchild = NULL;
114 static int workers_may_exit = 0;
115 static int shutdown_in_progress = 0;
116 static unsigned int g_blocked_threads = 0;
118 static HANDLE shutdown_event; /* used to signal the parent to shutdown */
119 static HANDLE restart_event; /* used to signal the parent to restart */
120 static HANDLE exit_event; /* used by parent to signal the child to exit */
121 static HANDLE max_requests_per_child_event;
123 static char ap_coredump_dir[MAX_STRING_LEN];
125 static int one_process = 0;
126 static char const* signal_arg = NULL;
128 OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
130 apr_proc_mutex_t *start_mutex;
132 static DWORD parent_pid;
134 int ap_threads_per_child = 0;
136 /* ap_my_generation are used by the scoreboard code */
137 ap_generation_t volatile ap_my_generation=0;
139 /* Queue for managing the passing of COMP_CONTEXTs between
140 * the accept and worker threads.
142 static apr_thread_mutex_t *qlock;
143 static PCOMP_CONTEXT qhead = NULL;
144 static PCOMP_CONTEXT qtail = NULL;
145 static int num_completion_contexts = 0;
146 static HANDLE ThreadDispatchIOCP = NULL;
148 /* Stub functions until this MPM supports the connection status API */
150 AP_DECLARE(void) ap_update_connection_status(long conn_id, const char *key, \
156 AP_DECLARE(void) ap_reset_connection_status(long conn_id)
161 AP_DECLARE(apr_array_header_t *) ap_get_status_table(apr_pool_t *p)
171 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg)
173 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
178 ap_threads_per_child = atoi(arg);
179 if (ap_threads_per_child > HARD_THREAD_LIMIT) {
180 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
181 "WARNING: ThreadsPerChild of %d exceeds compile time"
182 " limit of %d threads,", ap_threads_per_child,
184 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
185 " lowering ThreadsPerChild to %d. To increase, please"
186 " see the HARD_THREAD_LIMIT define in %s.",
187 HARD_THREAD_LIMIT, AP_MPM_HARD_LIMITS_FILE);
188 ap_threads_per_child = HARD_THREAD_LIMIT;
190 else if (ap_threads_per_child < 1) {
191 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
192 "WARNING: Require ThreadsPerChild > 0, setting to 1");
193 ap_threads_per_child = 1;
198 static const command_rec winnt_cmds[] = {
200 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
201 "Number of threads each child creates" },
206 AP_DECLARE(void) mpm_recycle_completion_context(PCOMP_CONTEXT pCompContext)
208 /* Recycle the completion context.
209 * - destroy the ptrans pool
210 * - put the context on the queue to be consumed by the accept thread
212 * pCompContext->accept_socket may be in a disconnected but reusable
213 * state so -don't- close it.
216 apr_pool_clear(pCompContext->ptrans);
217 apr_pool_destroy(pCompContext->ptrans);
218 pCompContext->ptrans = NULL;
219 pCompContext->next = NULL;
220 apr_thread_mutex_lock(qlock);
222 qtail->next = pCompContext;
224 qhead = pCompContext;
225 qtail = pCompContext;
226 apr_thread_mutex_unlock(qlock);
230 AP_DECLARE(PCOMP_CONTEXT) mpm_get_completion_context(void)
232 PCOMP_CONTEXT pCompContext = NULL;
234 /* Grab a context off the queue */
235 apr_thread_mutex_lock(qlock);
237 pCompContext = qhead;
242 apr_thread_mutex_unlock(qlock);
244 /* If we failed to grab a context off the queue, alloc one out of
245 * the child pool. There may be up to ap_threads_per_child contexts
246 * in the system at once.
249 if (num_completion_contexts >= ap_threads_per_child) {
250 static int reported = 0;
252 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, ap_server_conf,
253 "Server ran out of threads to serve requests. Consider "
254 "raising the ThreadsPerChild setting");
259 pCompContext = (PCOMP_CONTEXT) apr_pcalloc(pchild, sizeof(COMP_CONTEXT));
261 pCompContext->Overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
262 if (pCompContext->Overlapped.hEvent == NULL) {
263 /* Hopefully this is a temporary condition ... */
264 ap_log_error(APLOG_MARK,APLOG_WARNING, apr_get_os_error(), ap_server_conf,
265 "mpm_get_completion_context: CreateEvent failed.");
268 pCompContext->accept_socket = INVALID_SOCKET;
269 num_completion_contexts++;
274 AP_DECLARE(apr_status_t) mpm_post_completion_context(PCOMP_CONTEXT pCompContext,
277 LPOVERLAPPED pOverlapped;
279 pOverlapped = &pCompContext->Overlapped;
283 PostQueuedCompletionStatus(ThreadDispatchIOCP, 0, state, pOverlapped);
287 /* This is the helper code to resolve late bound entry points
288 * missing from one or more releases of the Win32 API...
289 * but it sure would be nice if we didn't duplicate this code
292 static const char* const lateDllName[DLL_defined] = {
293 "kernel32", "advapi32", "mswsock", "ws2_32" };
294 static HMODULE lateDllHandle[DLL_defined] = {
295 NULL, NULL, NULL, NULL };
297 FARPROC ap_load_dll_func(ap_dlltoken_e fnLib, char* fnName, int ordinal)
299 if (!lateDllHandle[fnLib]) {
300 lateDllHandle[fnLib] = LoadLibrary(lateDllName[fnLib]);
301 if (!lateDllHandle[fnLib])
305 return GetProcAddress(lateDllHandle[fnLib], (char *) ordinal);
307 return GetProcAddress(lateDllHandle[fnLib], fnName);
310 /* To share the semaphores with other processes, we need a NULL ACL
311 * Code from MS KB Q106387
313 static PSECURITY_ATTRIBUTES GetNullACL()
315 PSECURITY_DESCRIPTOR pSD;
316 PSECURITY_ATTRIBUTES sa;
318 sa = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES));
319 sa->nLength = sizeof(sizeof(SECURITY_ATTRIBUTES));
321 pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
322 sa->lpSecurityDescriptor = pSD;
324 if (pSD == NULL || sa == NULL) {
328 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
329 || apr_get_os_error()) {
334 if (!SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)
335 || apr_get_os_error()) {
341 sa->bInheritHandle = TRUE;
345 static void CleanNullACL( void *sa ) {
347 LocalFree( ((PSECURITY_ATTRIBUTES)sa)->lpSecurityDescriptor);
353 * The Win32 call WaitForMultipleObjects will only allow you to wait for
354 * a maximum of MAXIMUM_WAIT_OBJECTS (current 64). Since the threading
355 * model in the multithreaded version of apache wants to use this call,
356 * we are restricted to a maximum of 64 threads. This is a simplistic
357 * routine that will increase this size.
359 static DWORD wait_for_many_objects(DWORD nCount, CONST HANDLE *lpHandles,
363 DWORD dwRet = WAIT_TIMEOUT;
367 tStopTime = time(NULL) + dwSeconds;
375 for (dwIndex = 0; dwIndex * MAXIMUM_WAIT_OBJECTS < nCount; dwIndex++) {
376 dwRet = WaitForMultipleObjects(
377 min(MAXIMUM_WAIT_OBJECTS, nCount - (dwIndex * MAXIMUM_WAIT_OBJECTS)),
378 lpHandles + (dwIndex * MAXIMUM_WAIT_OBJECTS),
381 if (dwRet != WAIT_TIMEOUT) {
385 } while((time(NULL) < tStopTime) && (dwRet == WAIT_TIMEOUT));
391 * Signalling Apache on NT.
393 * Under Unix, Apache can be told to shutdown or restart by sending various
394 * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
395 * we use "events" instead. The parent apache process goes into a loop
396 * where it waits forever for a set of events. Two of those events are
402 * (where PID is the PID of the apache parent process). When one of these
403 * is signalled, the Apache parent performs the appropriate action. The events
404 * can become signalled through internal Apache methods (e.g. if the child
405 * finds a fatal error and needs to kill its parent), via the service
406 * control manager (the control thread will signal the shutdown event when
407 * requested to stop the Apache service), from the -k Apache command line,
408 * or from any external program which finds the Apache PID from the
411 * The signal_parent() function, below, is used to signal one of these events.
412 * It can be called by any child or parent process, since it does not
413 * rely on global variables.
415 * On entry, type gives the event to signal. 0 means shutdown, 1 means
419 * Initialise the signal names, in the global variables signal_name_prefix,
420 * signal_restart_name and signal_shutdown_name.
422 #define MAX_SIGNAL_NAME 30 /* Long enough for apPID_shutdown, where PID is an int */
423 char signal_name_prefix[MAX_SIGNAL_NAME];
424 char signal_restart_name[MAX_SIGNAL_NAME];
425 char signal_shutdown_name[MAX_SIGNAL_NAME];
426 void setup_signal_names(char *prefix)
428 apr_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);
429 apr_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name),
430 "%s_shutdown", signal_name_prefix);
431 apr_snprintf(signal_restart_name, sizeof(signal_restart_name),
432 "%s_restart", signal_name_prefix);
435 static int volatile is_graceful = 0;
436 AP_DECLARE(int) ap_graceful_stop_signalled(void)
441 AP_DECLARE(void) ap_signal_parent(ap_signal_parent_e type)
446 if (parent_pid == my_pid) {
448 case SIGNAL_PARENT_SHUTDOWN:
450 SetEvent(shutdown_event);
453 /* This MPM supports only graceful restarts right now */
454 case SIGNAL_PARENT_RESTART:
455 case SIGNAL_PARENT_RESTART_GRACEFUL:
458 SetEvent(restart_event);
466 case SIGNAL_PARENT_SHUTDOWN:
468 signal_name = signal_shutdown_name;
471 /* This MPM supports only graceful restarts right now */
472 case SIGNAL_PARENT_RESTART:
473 case SIGNAL_PARENT_RESTART_GRACEFUL:
475 signal_name = signal_restart_name;
483 e = OpenEvent(EVENT_MODIFY_STATE, FALSE, signal_name);
485 /* Um, problem, can't signal the parent, which means we can't
486 * signal ourselves to die. Ignore for now...
488 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf,
489 "OpenEvent on %s event", signal_name);
492 if (SetEvent(e) == 0) {
493 /* Same problem as above */
494 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf,
495 "SetEvent on %s event", signal_name);
502 /* set_listeners_noninheritable()
503 * Make the listening socket handles noninheritable by processes
504 * started out of this process.
506 static int set_listeners_noninheritable(apr_pool_t *p)
511 HANDLE hProcess = GetCurrentProcess();
513 for (lr = ap_listeners; lr; lr = lr->next) {
514 apr_os_sock_get(&nsd,lr->sd);
515 if (!DuplicateHandle(hProcess, (HANDLE) nsd, hProcess, &dup,
516 0, FALSE, DUPLICATE_SAME_ACCESS)) {
517 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), ap_server_conf,
518 "set_listeners_noninheritable: DuplicateHandle failed.");
523 apr_os_sock_put(&lr->sd, &nsd, p);
527 if (my_pid == parent_pid) {
528 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
529 "Parent: Marked listeners as not inheritable.");
531 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
532 "Child %d: Marked listeners as not inheritable.", my_pid);
538 * find_ready_listener()
539 * Only used by Win9* and should go away when the win9*_accept() function is
540 * reimplemented using apr_poll().
542 static ap_listen_rec *head_listener;
543 static APR_INLINE ap_listen_rec *find_ready_listener(fd_set * main_fds)
548 for (lr = head_listener; lr ; lr = lr->next) {
549 apr_os_sock_get(&nsd, lr->sd);
550 if (FD_ISSET(nsd, main_fds)) {
551 head_listener = lr->next;
552 if (head_listener == NULL)
553 head_listener = ap_listeners;
564 void get_handles_from_parent(server_rec *s)
572 pipe = GetStdHandle(STD_INPUT_HANDLE);
573 if (!ReadFile(pipe, &exit_event, sizeof(HANDLE),
574 &BytesRead, (LPOVERLAPPED) NULL)
575 || (BytesRead != sizeof(HANDLE))) {
576 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
577 "Child %d: Unable to retrieve the exit event from the parent", my_pid);
578 exit(APEXIT_CHILDINIT);
581 if (!ReadFile(pipe, &hScore, sizeof(hScore),
582 &BytesRead, (LPOVERLAPPED) NULL)
583 || (BytesRead != sizeof(hScore))) {
584 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
585 "Child %d: Unable to retrieve the scoreboard from the parent", my_pid);
586 exit(APEXIT_CHILDINIT);
589 if ((rv = apr_os_shm_put(&ap_scoreboard_shm, &hScore, s->process->pool))
591 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
592 "Child %d: Unable to access the scoreboard from the parent", my_pid);
593 exit(APEXIT_CHILDINIT);
596 rv = ap_reopen_scoreboard(s->process->pool, &ap_scoreboard_shm, 1);
597 if (rv || !(sb_shared = apr_shm_baseaddr_get(ap_scoreboard_shm))) {
598 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
599 "Child %d: Unable to reopen the scoreboard from the parent", my_pid);
600 exit(APEXIT_CHILDINIT);
602 /* We must 'initialize' the scoreboard to relink all the
603 * process-local pointer arrays into the shared memory block.
605 ap_init_scoreboard(sb_shared);
607 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
608 "Child %d: Retrieved our scoreboard from the parent.", my_pid);
612 * get_listeners_from_parent()
613 * The listen sockets are opened in the parent. This function, which runs
614 * exclusively in the child process, receives them from the parent and
615 * makes them availeble in the child.
617 void get_listeners_from_parent(server_rec *s)
619 WSAPROTOCOL_INFO WSAProtocolInfo;
626 /* Set up a default listener if necessary */
627 if (ap_listeners == NULL) {
629 lr = apr_palloc(s->process->pool, sizeof(ap_listen_rec));
631 lr->next = ap_listeners;
635 /* Open the pipe to the parent process to receive the inherited socket
636 * data. The sockets have been set to listening in the parent process.
638 pipe = GetStdHandle(STD_INPUT_HANDLE);
640 for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) {
641 if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
642 &BytesRead, (LPOVERLAPPED) NULL)) {
643 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
644 "setup_inherited_listeners: Unable to read socket data from parent");
645 exit(APEXIT_CHILDINIT);
647 nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
648 &WSAProtocolInfo, 0, 0);
649 if (nsd == INVALID_SOCKET) {
650 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf,
651 "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
652 exit(APEXIT_CHILDINIT);
654 apr_os_sock_put(&lr->sd, &nsd, s->process->pool);
657 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
658 "Child %d: retrieved %d listeners from parent", my_pid, lcnt);
660 if (!set_listeners_noninheritable(s->process->pool)) {
661 exit(APEXIT_CHILDINIT);
666 /* Windows 9x specific code...
667 * Accept processing for on Windows 95/98 uses a producer/consumer queue
668 * model. A single thread accepts connections and queues the accepted socket
669 * to the accept queue for consumption by a pool of worker threads.
672 * The accept threads runs this function, which accepts connections off
673 * the network and calls add_job() to queue jobs to the accept_queue.
674 * add_job()/remove_job()
675 * Add or remove an accepted socket from the list of sockets
676 * connected to clients. allowed_globals.jobmutex protects
677 * against multiple concurrent access to the linked list of jobs.
678 * win9x_get_connection()
679 * Calls remove_job() to pull a job from the accept queue. All the worker
680 * threads block on remove_job.
683 typedef struct joblist_s {
684 struct joblist_s *next;
688 typedef struct globals_s {
692 apr_thread_mutex_t *jobmutex;
696 globals allowed_globals = {NULL, NULL, NULL, NULL, 0};
697 #define MAX_SELECT_ERRORS 100
699 static void add_job(int sock)
703 new_job = (joblist *) malloc(sizeof(joblist));
704 if (new_job == NULL) {
705 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
706 "Ouch! Out of memory in add_job()!");
709 new_job->next = NULL;
710 new_job->sock = sock;
712 apr_thread_mutex_lock(allowed_globals.jobmutex);
714 if (allowed_globals.jobtail != NULL)
715 allowed_globals.jobtail->next = new_job;
716 allowed_globals.jobtail = new_job;
717 if (!allowed_globals.jobhead)
718 allowed_globals.jobhead = new_job;
719 allowed_globals.jobcount++;
720 ReleaseSemaphore(allowed_globals.jobsemaphore, 1, NULL);
722 apr_thread_mutex_unlock(allowed_globals.jobmutex);
725 static int remove_job(void)
730 WaitForSingleObject(allowed_globals.jobsemaphore, INFINITE);
731 apr_thread_mutex_lock(allowed_globals.jobmutex);
733 if (shutdown_in_progress && !allowed_globals.jobhead) {
734 apr_thread_mutex_unlock(allowed_globals.jobmutex);
737 job = allowed_globals.jobhead;
739 allowed_globals.jobhead = job->next;
740 if (allowed_globals.jobhead == NULL)
741 allowed_globals.jobtail = NULL;
742 apr_thread_mutex_unlock(allowed_globals.jobmutex);
749 static void win9x_accept(void * dummy)
755 SOCKET nsd = INVALID_SOCKET;
756 struct sockaddr_in sa_client;
757 int count_select_errors = 0;
761 struct fd_set listenfds;
762 SOCKET listenmaxfd = INVALID_SOCKET;
764 /* Setup the listeners
765 * ToDo: Use apr_poll()
768 for (lr = ap_listeners; lr; lr = lr->next) {
769 if (lr->sd != NULL) {
770 apr_os_sock_get(&nsd, lr->sd);
771 FD_SET(nsd, &listenfds);
772 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
777 head_listener = ap_listeners;
779 while (!shutdown_in_progress) {
780 tv.tv_sec = wait_time;
782 memcpy(&main_fds, &listenfds, sizeof(fd_set));
784 rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
786 if (rc == 0 || (rc == SOCKET_ERROR && APR_STATUS_IS_EINTR(apr_get_netos_error()))) {
787 count_select_errors = 0; /* reset count of errors */
790 else if (rc == SOCKET_ERROR) {
791 /* A "real" error occurred, log it and increment the count of
792 * select errors. This count is used to ensure we don't go into
793 * a busy loop of continuous errors.
795 ap_log_error(APLOG_MARK, APLOG_INFO, apr_get_netos_error(), ap_server_conf,
796 "select failed with error %d", apr_get_netos_error());
797 count_select_errors++;
798 if (count_select_errors > MAX_SELECT_ERRORS) {
799 shutdown_in_progress = 1;
800 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), ap_server_conf,
801 "Too many errors in select loop. Child process exiting.");
807 lr = find_ready_listener(&main_fds);
809 /* fetch the native socket descriptor */
810 apr_os_sock_get(&nsd, lr->sd);
815 clen = sizeof(sa_client);
816 csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
817 if (csd == INVALID_SOCKET) {
820 } while (csd < 0 && APR_STATUS_IS_EINTR(apr_get_netos_error()));
823 if (APR_STATUS_IS_ECONNABORTED(apr_get_netos_error())) {
824 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), ap_server_conf,
825 "accept: (client socket)");
832 SetEvent(exit_event);
835 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
839 if (context == NULL) {
840 /* allocate the completion context and the transaction pool */
841 context = apr_pcalloc(pconf, sizeof(COMP_CONTEXT));
842 apr_pool_create(&context->ptrans, pconf);
843 apr_pool_tag(context->ptrans, "ptrans");
848 apr_pool_clear(context->ptrans);
849 context->accept_socket = remove_job();
850 if (context->accept_socket == -1) {
853 len = sizeof(struct sockaddr);
854 context->sa_server = apr_palloc(context->ptrans, len);
855 if (getsockname(context->accept_socket,
856 context->sa_server, &len)== SOCKET_ERROR) {
857 ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), ap_server_conf,
858 "getsockname failed");
861 len = sizeof(struct sockaddr);
862 context->sa_client = apr_palloc(context->ptrans, len);
863 if ((getpeername(context->accept_socket,
864 context->sa_client, &len)) == SOCKET_ERROR) {
865 ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), ap_server_conf,
866 "getpeername failed");
867 memset(&context->sa_client, '\0', sizeof(context->sa_client));
870 /* do we NEED_DUPPED_CSD ?? */
875 /* Windows NT/2000 specific code...
876 * Accept processing for on Windows NT uses a producer/consumer queue
877 * model. An accept thread accepts connections off the network then issues
878 * PostQueuedCompletionStatus() to awake a thread blocked on the ThreadDispatch
882 * One or more accept threads run in this function, each of which accepts
883 * connections off the network and calls PostQueuedCompletionStatus() to
884 * queue an io completion packet to the ThreadDispatch IOCompletionPort.
885 * winnt_get_connection()
886 * Worker threads block on the ThreadDispatch IOCompletionPort awaiting
887 * connections to service.
889 static void winnt_accept(void *listen_socket)
892 PCOMP_CONTEXT pCompContext;
897 nlsd = (SOCKET) listen_socket;
899 while (!shutdown_in_progress) {
900 pCompContext = mpm_get_completion_context();
902 /* Hopefully whatever is preventing us from getting a
903 * completion context is a temporary resource constraint.
910 /* Create and initialize the accept socket */
911 if (pCompContext->accept_socket == INVALID_SOCKET) {
912 pCompContext->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
913 if (pCompContext->accept_socket == INVALID_SOCKET) {
914 /* Hopefully another temporary condition. Be graceful. */
915 ap_log_error(APLOG_MARK,APLOG_WARNING, apr_get_netos_error(), ap_server_conf,
916 "winnt_accept: Failed to allocate an accept socket. "
917 "Temporary resource constraint? Try again.");
923 /* AcceptEx on the completion context. The completion context will be
924 * signaled when a connection is accepted.
926 if (!AcceptEx(nlsd, pCompContext->accept_socket,
932 &pCompContext->Overlapped)) {
933 lasterror = apr_get_netos_error();
934 if (lasterror == APR_FROM_OS_ERROR(WSAEINVAL)) {
935 /* Hack alert. Occasionally, TransmitFile will not recycle the
936 * accept socket (usually when the client disconnects early).
937 * Get a new socket and try the call again.
939 closesocket(pCompContext->accept_socket);
940 pCompContext->accept_socket = INVALID_SOCKET;
941 ap_log_error(APLOG_MARK, APLOG_DEBUG, lasterror, ap_server_conf,
942 "winnt_accept: AcceptEx failed due to early client "
943 "disconnect. Reallocate the accept socket and try again.");
944 if (shutdown_in_progress)
949 else if (lasterror != APR_FROM_OS_ERROR(ERROR_IO_PENDING)) {
950 ap_log_error(APLOG_MARK,APLOG_ERR, lasterror, ap_server_conf,
951 "winnt_accept: AcceptEx failed. Attempting to recover.");
952 closesocket(pCompContext->accept_socket);
953 pCompContext->accept_socket = INVALID_SOCKET;
958 /* Wait for pending i/o */
959 WaitForSingleObject(pCompContext->Overlapped.hEvent, INFINITE);
962 /* Inherit the listen socket settings. Required for
965 if (setsockopt(pCompContext->accept_socket, SOL_SOCKET,
966 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nlsd,
968 ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), ap_server_conf,
969 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
970 /* Not a failure condition. Keep running. */
973 /* Get the local & remote address */
974 GetAcceptExSockaddrs(pCompContext->buff,
978 &pCompContext->sa_server,
979 &pCompContext->sa_server_len,
980 &pCompContext->sa_client,
981 &pCompContext->sa_client_len);
983 /* When a connection is received, send an io completion notification to
984 * the ThreadDispatchIOCP. This function could be replaced by
985 * mpm_post_completion_context(), but why do an extra function call...
987 PostQueuedCompletionStatus(ThreadDispatchIOCP, 0, IOCP_CONNECTION_ACCEPTED,
988 &pCompContext->Overlapped);
991 if (!shutdown_in_progress) {
992 /* Yow, hit an irrecoverable error! Tell the child to die. */
993 SetEvent(exit_event);
996 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT pCompContext)
1003 mpm_recycle_completion_context(pCompContext);
1005 g_blocked_threads++;
1007 if (workers_may_exit) {
1008 g_blocked_threads--;
1011 rc = GetQueuedCompletionStatus(ThreadDispatchIOCP, &BytesRead, &CompKey,
1014 rc = apr_get_os_error();
1015 ap_log_error(APLOG_MARK,APLOG_DEBUG, rc, ap_server_conf,
1016 "Child %d: GetQueuedComplationStatus returned %d", my_pid, rc);
1021 case IOCP_CONNECTION_ACCEPTED:
1022 pCompContext = CONTAINING_RECORD(pol, COMP_CONTEXT, Overlapped);
1025 g_blocked_threads--;
1028 g_blocked_threads--;
1034 g_blocked_threads--;
1036 if ((rc = apr_pool_create(&pCompContext->ptrans, pconf)) != APR_SUCCESS) {
1037 ap_log_error(APLOG_MARK,APLOG_DEBUG, rc, ap_server_conf,
1038 "Child %d: apr_pool_create failed with rc %d", my_pid, rc);
1040 apr_pool_tag(pCompContext->ptrans, "ptrans");
1043 return pCompContext;
1048 * Main entry point for the worker threads. Worker threads block in
1049 * win*_get_connection() awaiting a connection to service.
1051 static void worker_main(long thread_num)
1053 static int requests_this_child = 0;
1054 PCOMP_CONTEXT context = NULL;
1055 apr_os_sock_info_t sockinfo;
1056 ap_sb_handle_t *sbh;
1060 apr_int32_t disconnected;
1062 ap_update_child_status_from_indexes(0, thread_num, SERVER_READY,
1063 (request_rec *) NULL);
1066 /* Grab a connection off the network */
1067 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1068 context = win9x_get_connection(context);
1071 context = winnt_get_connection(context);
1074 /* Time for the thread to exit */
1078 /* Have we hit MaxRequestPerChild connections? */
1079 if (ap_max_requests_per_child) {
1080 requests_this_child++;
1081 if (requests_this_child > ap_max_requests_per_child) {
1082 SetEvent(max_requests_per_child_event);
1086 sockinfo.os_sock = &context->accept_socket;
1087 sockinfo.local = context->sa_server;
1088 sockinfo.remote = context->sa_client;
1089 sockinfo.family = APR_INET;
1090 sockinfo.type = SOCK_STREAM;
1091 /* ### is this correct? Shouldn't be inheritable (at this point) */
1092 apr_os_sock_make(&context->sock, &sockinfo, context->ptrans);
1094 ap_create_sb_handle(&sbh, context->ptrans, 0, thread_num);
1095 c = ap_run_create_connection(context->ptrans, ap_server_conf, context->sock,
1099 ap_process_connection(c, context->sock);
1100 apr_getsocketopt(context->sock, APR_SO_DISCONNECTED, &disconnected);
1101 if (!disconnected) {
1102 context->accept_socket = INVALID_SOCKET;
1103 ap_lingering_close(c);
1107 /* ap_run_create_connection closes the socket on failure */
1108 context->accept_socket = INVALID_SOCKET;
1112 ap_update_child_status_from_indexes(0, thread_num, SERVER_DEAD,
1113 (request_rec *) NULL);
1115 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
1116 "Child %d: Thread exiting.", my_pid);
1119 static void cleanup_thread(thread *handles, int *thread_cnt, int thread_to_clean)
1123 CloseHandle(handles[thread_to_clean]);
1124 for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1125 handles[i] = handles[i + 1];
1131 * Entry point for the main control thread for the child process.
1132 * This thread creates the accept thread, worker threads and
1133 * monitors the child process for maintenance and shutdown
1136 static void child_main()
1138 apr_status_t status;
1140 HANDLE child_events[2];
1141 int nthreads = ap_threads_per_child;
1143 thread *child_handles;
1149 apr_pool_create(&pchild, pconf);
1150 apr_pool_tag(pchild, "pchild");
1152 ap_run_child_init(pchild, ap_server_conf);
1154 /* Initialize the child_events */
1155 max_requests_per_child_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1156 if (!max_requests_per_child_event) {
1157 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1158 "Child %d: Failed to create a max_requests event.", my_pid);
1159 exit(APEXIT_CHILDINIT);
1161 child_events[0] = exit_event;
1162 child_events[1] = max_requests_per_child_event;
1164 allowed_globals.jobsemaphore = CreateSemaphore(NULL, 0, 1000000, NULL);
1165 apr_thread_mutex_create(&allowed_globals.jobmutex,
1166 APR_THREAD_MUTEX_DEFAULT, pchild);
1169 * Wait until we have permission to start accepting connections.
1170 * start_mutex is used to ensure that only one child ever
1171 * goes into the listen/accept loop at once.
1173 status = apr_proc_mutex_lock(start_mutex);
1174 if (status != APR_SUCCESS) {
1175 ap_log_error(APLOG_MARK,APLOG_ERR, status, ap_server_conf,
1176 "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1177 exit(APEXIT_CHILDINIT);
1179 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, ap_server_conf,
1180 "Child %d: Acquired the start mutex.", my_pid);
1183 * Create the worker thread dispatch IOCompletionPort
1184 * on Windows NT/2000
1186 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1187 /* Create the worker thread dispatch IOCP */
1188 ThreadDispatchIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1191 0); /* CONCURRENT ACTIVE THREADS */
1192 apr_thread_mutex_create(&qlock, APR_THREAD_MUTEX_DEFAULT, pchild);
1196 * Create the pool of worker threads
1198 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, ap_server_conf,
1199 "Child %d: Starting %d worker threads.", my_pid, nthreads);
1200 child_handles = (thread) alloca(nthreads * sizeof(int));
1201 for (i = 0; i < nthreads; i++) {
1202 ap_update_child_status_from_indexes(0, i, SERVER_STARTING,
1203 (request_rec *) NULL);
1204 child_handles[i] = (thread) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1205 (void *) i, 0, &tid);
1209 * Start the accept thread
1211 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1212 _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) win9x_accept,
1213 (void *) i, 0, &tid);
1215 /* Start an accept thread per listener */
1216 SOCKET nlsd; /* native listening sock descriptor */
1218 for (lr = ap_listeners; lr; lr = lr->next) {
1219 if (lr->sd != NULL) {
1220 apr_os_sock_get(&nlsd, lr->sd);
1221 _beginthreadex(NULL, 1000, (LPTHREAD_START_ROUTINE) winnt_accept,
1222 (void *) nlsd, 0, &tid);
1227 /* Wait for one of three events:
1229 * The exit_event is signaled by the parent process to notify
1230 * the child that it is time to exit.
1232 * max_requests_per_child_event:
1233 * This event is signaled by the worker threads to indicate that
1234 * the process has handled MaxRequestsPerChild connections.
1237 * To do periodic maintenance on the server (check for thread exits,
1238 * number of completion contexts, etc.)
1241 rv = WaitForMultipleObjects(2, (HANDLE *) child_events, FALSE, 1000);
1242 cld = rv - WAIT_OBJECT_0;
1243 if (rv == WAIT_FAILED) {
1244 /* Something serious is wrong */
1245 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1246 "Child %d: WAIT_FAILED -- shutting down server");
1249 else if (rv == WAIT_TIMEOUT) {
1250 apr_proc_other_child_check();
1252 else if (cld == 0) {
1253 /* Exit event was signaled */
1254 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
1255 "Child %d: Exit event signaled. Child process is ending.", my_pid);
1259 /* MaxRequestsPerChild event set by the worker threads.
1260 * Signal the parent to restart
1262 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
1263 "Child %d: Process exiting because it reached "
1264 "MaxRequestsPerChild. Signaling the parent to "
1265 "restart a new child process.", my_pid);
1266 ap_signal_parent(SIGNAL_PARENT_RESTART);
1271 /* Setting is_graceful will cause keep-alive connections to be closed
1272 * rather than block on the next network read.
1276 /* Setting shutdown_in_progress prevents new connections from
1277 * being accepted but allows the worker threads to continue
1278 * handling connections that have already been accepted.
1280 shutdown_in_progress = 1;
1282 /* Close the listening sockets. */
1283 for (lr = ap_listeners; lr ; lr = lr->next) {
1284 apr_socket_close(lr->sd);
1288 /* Release the start_mutex to let the new process (in the restart
1289 * scenario) a chance to begin accepting and servicing requests
1291 rv = apr_proc_mutex_unlock(start_mutex);
1292 if (rv == APR_SUCCESS) {
1293 ap_log_error(APLOG_MARK,APLOG_INFO | APLOG_NOERRNO, rv, ap_server_conf,
1294 "Child %d: Released the start mutex", my_pid);
1297 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
1298 "Child %d: Failure releasing the start mutex", my_pid);
1301 /* Tell the worker threads they may exit when done handling
1304 workers_may_exit = 1;
1306 /* Shutdown the worker threads */
1307 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1308 for (i = 0; i < nthreads; i++) {
1312 else { /* Windows NT/2000 */
1313 /* Post worker threads blocked on the ThreadDispatch IOCompletion port */
1314 while (g_blocked_threads > 0) {
1315 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, ap_server_conf,
1316 "Child %d: %d threads blocked on the completion port", my_pid, g_blocked_threads);
1317 for (i=g_blocked_threads; i > 0; i--) {
1318 PostQueuedCompletionStatus(ThreadDispatchIOCP, 0, IOCP_SHUTDOWN, NULL);
1322 /* Empty the accept queue of completion contexts */
1323 apr_thread_mutex_lock(qlock);
1325 CloseHandle(qhead->Overlapped.hEvent);
1326 closesocket(qhead->accept_socket);
1327 qhead = qhead->next;
1329 apr_thread_mutex_unlock(qlock);
1332 /* Give busy worker threads a chance to service their connections */
1333 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, ap_server_conf,
1334 "Child %d: Waiting for %d threads to die.", my_pid, nthreads);
1335 end_time = time(NULL) + 180;
1337 rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1338 if (rv != WAIT_TIMEOUT) {
1339 rv = rv - WAIT_OBJECT_0;
1340 ap_assert((rv >= 0) && (rv < nthreads));
1341 cleanup_thread(child_handles, &nthreads, rv);
1347 /* Kill remaining threads off the hard way */
1348 for (i = 0; i < nthreads; i++) {
1349 TerminateThread(child_handles[i], 1);
1350 CloseHandle(child_handles[i]);
1352 ap_log_error(APLOG_MARK,APLOG_DEBUG, APR_SUCCESS, ap_server_conf,
1353 "Child %d: All worker threads have ended.", my_pid);
1355 CloseHandle(allowed_globals.jobsemaphore);
1356 apr_thread_mutex_destroy(allowed_globals.jobmutex);
1357 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS)
1358 apr_thread_mutex_destroy(qlock);
1360 apr_pool_destroy(pchild);
1361 CloseHandle(exit_event);
1364 static int send_handles_to_child(apr_pool_t *p, HANDLE child_exit_event, HANDLE hProcess, HANDLE hPipeWrite)
1369 HANDLE hCurrentProcess = GetCurrentProcess();
1372 if (!DuplicateHandle(hCurrentProcess, child_exit_event, hProcess, &hDup,
1373 EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, 0)) {
1374 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1375 "Parent: Unable to duplicate the exit event handle for the child");
1378 if (!WriteFile(hPipeWrite, &hDup, sizeof(hDup),
1379 &BytesWritten, (LPOVERLAPPED) NULL)
1380 || (BytesWritten != sizeof(hDup))) {
1381 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1382 "Parent: Unable to send the exit event handle to the child");
1386 if ((rv = apr_os_shm_get(&hScore, ap_scoreboard_shm)) != APR_SUCCESS) {
1387 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
1388 "Parent: Unable to retrieve the scoreboard handle for the child");
1391 if (!DuplicateHandle(hCurrentProcess, hScore, hProcess, &hDup,
1392 FILE_MAP_READ | FILE_MAP_WRITE, FALSE, 0)) {
1393 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1394 "Parent: Unable to duplicate the scoreboard handle to the child");
1397 if (!WriteFile(hPipeWrite, &hDup, sizeof(hDup),
1398 &BytesWritten, (LPOVERLAPPED) NULL)
1399 || (BytesWritten != sizeof(hDup))) {
1400 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1401 "Parent: Unable to send the scoreboard handle to the child");
1405 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
1406 "Parent: Sent the scoreboard to the child");
1410 static int send_listeners_to_child(apr_pool_t *p, DWORD dwProcessId, HANDLE hPipeWrite)
1414 LPWSAPROTOCOL_INFO lpWSAProtocolInfo;
1417 /* Run the chain of open sockets. For each socket, duplicate it
1418 * for the target process then send the WSAPROTOCOL_INFO
1419 * (returned by dup socket) to the child.
1421 for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) {
1423 lpWSAProtocolInfo = apr_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1424 apr_os_sock_get(&nsd,lr->sd);
1425 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
1426 "Parent: Duplicating socket %d and sending it to child process %d",
1428 if (WSADuplicateSocket(nsd, dwProcessId,
1429 lpWSAProtocolInfo) == SOCKET_ERROR) {
1430 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf,
1431 "Parent: WSADuplicateSocket failed for socket %d. Check the FAQ.", lr->sd );
1435 if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1437 (LPOVERLAPPED) NULL)
1438 || BytesWritten != sizeof(WSAPROTOCOL_INFO)) {
1439 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1440 "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1445 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
1446 "Parent: Sent %d listeners to child %d", lcnt, dwProcessId);
1450 static int create_process(apr_pool_t *p, HANDLE *child_proc, HANDLE *child_exit_event)
1459 STARTUPINFO si; /* Filled in prior to call to CreateProcess */
1460 PROCESS_INFORMATION pi; /* filled in on call to CreateProcess */
1467 HANDLE hCurrentProcess = GetCurrentProcess();
1468 SECURITY_ATTRIBUTES sa;
1470 sa.nLength = sizeof(sa);
1471 sa.bInheritHandle = TRUE;
1472 sa.lpSecurityDescriptor = NULL;
1474 /* Build the command line. Should look something like this:
1475 * C:/apache/bin/apache.exe -f ap_server_confname
1476 * First, get the path to the executable...
1478 rv = GetModuleFileName(NULL, buf, sizeof(buf));
1479 if (rv == sizeof(buf)) {
1480 ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, ap_server_conf,
1481 "Parent: Path to Apache process too long");
1483 } else if (rv == 0) {
1484 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1485 "Parent: GetModuleFileName() returned NULL for current process.");
1489 /* Build the command line */
1490 pCommand = apr_psprintf(p, "\"%s\"", buf);
1491 for (i = 1; i < ap_server_conf->process->argc; i++) {
1492 pCommand = apr_pstrcat(p, pCommand, " \"", ap_server_conf->process->argv[i], "\"", NULL);
1495 /* Create a pipe to send socket info to the child */
1496 if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1497 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1498 "Parent: Unable to create pipe to child process.");
1502 /* Make our end of the handle non-inherited */
1503 if (DuplicateHandle(hCurrentProcess, hPipeWrite, hCurrentProcess,
1504 &hDup, 0, FALSE, DUPLICATE_SAME_ACCESS)) {
1505 CloseHandle(hPipeWrite);
1509 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1510 "Parent: Unable to duplicate pipe to child.\n");
1511 CloseHandle(hPipeWrite);
1512 CloseHandle(hPipeRead);
1516 /* Open a null handle to soak info from the child */
1517 hNullOutput = CreateFile("nul", GENERIC_READ | GENERIC_WRITE,
1518 FILE_SHARE_READ | FILE_SHARE_WRITE,
1519 &sa, OPEN_EXISTING, 0, NULL);
1520 if (hNullOutput == INVALID_HANDLE_VALUE) {
1521 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1522 "Parent: Unable to create null output pipe for child process.\n");
1523 CloseHandle(hPipeWrite);
1524 CloseHandle(hPipeRead);
1528 /* Child's initial stderr -> our main server error log (or, failing that, stderr) */
1529 if (ap_server_conf->error_log) { /* Is this check really necessary?*/
1530 rv = apr_os_file_get(&hShareError, ap_server_conf->error_log);
1531 if (rv == APR_SUCCESS && hShareError != INVALID_HANDLE_VALUE) {
1532 if (DuplicateHandle(hCurrentProcess, hShareError,
1533 hCurrentProcess, &hDup,
1534 GENERIC_WRITE, TRUE, 0)) {
1538 rv = apr_get_os_error();
1541 if (rv != APR_SUCCESS) {
1542 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
1543 "Parent: Unable to share error log with child.\n");
1544 CloseHandle(hPipeWrite);
1545 CloseHandle(hPipeRead);
1546 CloseHandle(hNullOutput);
1549 else if (hShareError == INVALID_HANDLE_VALUE) {
1550 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_CRIT, 0, ap_server_conf,
1551 "Parent: Failed to share error log with child.\n");
1552 CloseHandle(hPipeWrite);
1553 CloseHandle(hPipeRead);
1554 CloseHandle(hNullOutput);
1559 hShareError = GetStdHandle(STD_ERROR_HANDLE);
1562 /* Create the child_exit_event */
1563 hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1565 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1566 "Parent: Could not create exit event for child process");
1567 CloseHandle(hPipeWrite);
1568 CloseHandle(hPipeRead);
1569 CloseHandle(hNullOutput);
1570 if (GetStdHandle(STD_ERROR_HANDLE) != hShareError) {
1571 CloseHandle(hShareError);
1577 * Build the environment
1578 * Win32's CreateProcess call requires that the environment
1579 * be passed in an environment block, a null terminated block of
1580 * null terminated strings.
1582 _putenv(apr_psprintf(p,"AP_PARENT_PID=%i", parent_pid));
1583 _putenv(apr_psprintf(p,"AP_MY_GENERATION=%i", ap_my_generation));
1587 while (_environ[i]) {
1588 iEnvBlockLen += strlen(_environ[i]) + 1;
1591 pEnvBlock = (char *)apr_pcalloc(p, iEnvBlockLen);
1592 pEnvVar = pEnvBlock;
1594 while (_environ[i]) {
1595 strcpy(pEnvVar, _environ[i]);
1596 pEnvVar = strchr(pEnvVar, '\0') + 1;
1601 /* Give the read end of the pipe (hPipeRead) to the child as stdin. The
1602 * parent will write the socket data to the child on this pipe.
1604 memset(&si, 0, sizeof(si));
1605 memset(&pi, 0, sizeof(pi));
1607 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1608 si.wShowWindow = SW_HIDE;
1609 si.hStdInput = hPipeRead;
1610 si.hStdOutput = hNullOutput;
1611 si.hStdError = hShareError;
1613 rv = CreateProcess(NULL, pCommand, NULL, NULL,
1614 TRUE, /* Inherit handles */
1615 0, /* Creation flags */
1616 pEnvBlock, /* Environment block */
1620 /* Undo everything created for the child alone
1622 CloseHandle(pi.hThread);
1623 CloseHandle(hPipeRead);
1624 CloseHandle(hNullOutput);
1625 if (GetStdHandle(STD_ERROR_HANDLE) != hShareError) {
1626 /* Handles opened with GetStdHandle are psuedo handles
1627 * and should not be closed else bad things will happen.
1629 CloseHandle(hShareError);
1631 _putenv("AP_PARENT_PID=");
1632 _putenv("AP_MY_GENERATION=");
1635 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1636 "Parent: Failed to create the child process.");
1637 CloseHandle(hExitEvent);
1638 CloseHandle(hPipeWrite);
1639 CloseHandle(pi.hProcess);
1643 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
1644 "Parent: Created child process %d", pi.dwProcessId);
1646 if (send_handles_to_child(p, hExitEvent, pi.hProcess, hPipeWrite)) {
1648 * This error is fatal, mop up the child and move on
1649 * We toggle the child's exit event to cause this child
1650 * to quit even as it is attempting to start.
1652 SetEvent(hExitEvent);
1653 CloseHandle(hExitEvent);
1654 CloseHandle(hPipeWrite);
1655 CloseHandle(pi.hProcess);
1660 * Give the child process a chance to run before dup'ing the sockets.
1661 * We have already set the listening sockets noninheritable, but if
1662 * WSADuplicateSocket runs before the child process initializes
1663 * the listeners will be inherited anyway.
1665 * XXX: This is badness; needs some mutex interlocking
1669 if (send_listeners_to_child(p, pi.dwProcessId, hPipeWrite)) {
1671 * This error is fatal, mop up the child and move on
1672 * We toggle the child's exit event to cause this child
1673 * to quit even as it is attempting to start.
1675 SetEvent(hExitEvent);
1676 CloseHandle(hExitEvent);
1677 CloseHandle(hPipeWrite);
1678 CloseHandle(pi.hProcess);
1682 CloseHandle(hPipeWrite);
1684 *child_proc = pi.hProcess;
1685 *child_exit_event = hExitEvent;
1690 /***********************************************************************
1692 * master_main() runs in the parent process. It creates the child
1693 * process which handles HTTP requests then waits on one of three
1698 * The restart event causes master_main to start a new child process and
1699 * tells the old child process to exit (by setting the child_exit_event).
1700 * The restart event is set as a result of one of the following:
1701 * 1. An apache -k restart command on the command line
1702 * 2. A command received from Windows service manager which gets
1703 * translated into an ap_signal_parent(SIGNAL_PARENT_RESTART)
1704 * call by code in service.c.
1705 * 3. The child process calling ap_signal_parent(SIGNAL_PARENT_RESTART)
1706 * as a result of hitting MaxRequestsPerChild.
1710 * The shutdown event causes master_main to tell the child process to
1711 * exit and that the server is shutting down. The shutdown event is
1712 * set as a result of one of the following:
1713 * 1. An apache -k shutdown command on the command line
1714 * 2. A command received from Windows service manager which gets
1715 * translated into an ap_signal_parent(SIGNAL_PARENT_SHUTDOWN)
1716 * call by code in service.c.
1718 * child process handle
1719 * --------------------
1720 * The child process handle will be signaled if the child process
1721 * exits for any reason. In a normal running server, the signaling
1722 * of this event means that the child process has exited prematurely
1723 * due to a seg fault or other irrecoverable error. For server
1724 * robustness, master_main will restart the child process under this
1727 * master_main uses the child_exit_event to signal the child process
1729 **********************************************************************/
1730 #define NUM_WAIT_HANDLES 3
1731 #define CHILD_HANDLE 0
1732 #define SHUTDOWN_HANDLE 1
1733 #define RESTART_HANDLE 2
1734 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1737 int restart_pending;
1738 int shutdown_pending;
1739 HANDLE child_exit_event;
1740 HANDLE event_handles[NUM_WAIT_HANDLES];
1742 restart_pending = shutdown_pending = 0;
1744 event_handles[SHUTDOWN_HANDLE] = shutdown_event;
1745 event_handles[RESTART_HANDLE] = restart_event;
1747 /* Create a single child process */
1748 rv = create_process(pconf, &event_handles[CHILD_HANDLE],
1752 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1753 "master_main: create child process failed. Exiting.");
1754 shutdown_pending = 1;
1758 if (!strcasecmp(signal_arg, "runservice")) {
1759 mpm_service_started();
1762 /* Wait for shutdown or restart events or for child death */
1763 rv = WaitForMultipleObjects(NUM_WAIT_HANDLES, (HANDLE *) event_handles, FALSE, INFINITE);
1764 cld = rv - WAIT_OBJECT_0;
1765 if (rv == WAIT_FAILED) {
1766 /* Something serious is wrong */
1767 ap_log_error(APLOG_MARK,APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1768 "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1769 shutdown_pending = 1;
1771 else if (rv == WAIT_TIMEOUT) {
1772 /* Hey, this cannot happen */
1773 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1774 "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1775 shutdown_pending = 1;
1777 else if (cld == SHUTDOWN_HANDLE) {
1778 /* shutdown_event signalled */
1779 shutdown_pending = 1;
1780 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1781 "Parent: Received shutdown signal -- Shutting down the server.");
1782 if (ResetEvent(shutdown_event) == 0) {
1783 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1784 "ResetEvent(shutdown_event)");
1788 else if (cld == RESTART_HANDLE) {
1789 /* Received a restart event. Prepare the restart_event to be reused
1790 * then signal the child process to exit.
1792 restart_pending = 1;
1793 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, s,
1794 "Parent: Received restart signal -- Restarting the server.");
1795 if (ResetEvent(restart_event) == 0) {
1796 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1797 "Parent: ResetEvent(restart_event) failed.");
1799 if (SetEvent(child_exit_event) == 0) {
1800 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1801 "Parent: SetEvent for child process %d failed.",
1802 event_handles[CHILD_HANDLE]);
1804 /* Don't wait to verify that the child process really exits,
1805 * just move on with the restart.
1807 CloseHandle(event_handles[CHILD_HANDLE]);
1808 event_handles[CHILD_HANDLE] = NULL;
1812 /* The child process exited prematurely due to a fatal error. */
1814 if (!GetExitCodeProcess(event_handles[CHILD_HANDLE], &exitcode)) {
1815 /* HUH? We did exit, didn't we? */
1816 exitcode = APEXIT_CHILDFATAL;
1818 if ( exitcode == APEXIT_CHILDFATAL
1819 || exitcode == APEXIT_CHILDINIT
1820 || exitcode == APEXIT_INIT) {
1821 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, ap_server_conf,
1822 "Parent: child process exited with status %u -- Aborting.", exitcode);
1825 restart_pending = 1;
1826 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, ap_server_conf,
1827 "Parent: child process exited with status %u -- Restarting.", exitcode);
1829 CloseHandle(event_handles[CHILD_HANDLE]);
1830 event_handles[CHILD_HANDLE] = NULL;
1835 if (shutdown_pending)
1837 int timeout = 30000; /* Timeout is milliseconds */
1839 /* This shutdown is only marginally graceful. We will give the
1840 * child a bit of time to exit gracefully. If the time expires,
1841 * the child will be wacked.
1843 if (strcasecmp(signal_arg, "runservice")) {
1844 mpm_service_stopping();
1846 /* Signal the child processes to exit */
1847 if (SetEvent(child_exit_event) == 0) {
1848 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), ap_server_conf,
1849 "Parent: SetEvent for child process %d failed", event_handles[CHILD_HANDLE]);
1851 if (event_handles[CHILD_HANDLE]) {
1852 rv = WaitForSingleObject(event_handles[CHILD_HANDLE], timeout);
1853 if (rv == WAIT_OBJECT_0) {
1854 ap_log_error(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO, APR_SUCCESS, ap_server_conf,
1855 "Parent: Child process %d exited successfully.", event_handles[CHILD_HANDLE]);
1856 CloseHandle(event_handles[CHILD_HANDLE]);
1857 event_handles[CHILD_HANDLE] = NULL;
1860 ap_log_error(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO, APR_SUCCESS, ap_server_conf,
1861 "Parent: Forcing termination of child process %d ", event_handles[CHILD_HANDLE]);
1862 TerminateProcess(event_handles[CHILD_HANDLE], 1);
1863 CloseHandle(event_handles[CHILD_HANDLE]);
1864 event_handles[CHILD_HANDLE] = NULL;
1867 return 0; /* Tell the caller we do not want to restart */
1870 return 1; /* Tell the caller we want a restart */
1873 /* service_nt_main_fn needs to append the StartService() args
1874 * outside of our call stack and thread as the service starts...
1876 apr_array_header_t *mpm_new_argv;
1878 /* Remember service_to_start failures to log and fail in pre_config.
1879 * Remember inst_argc and inst_argv for installing or starting the
1880 * service after we preflight the config.
1883 AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
1886 case AP_MPMQ_MAX_DAEMON_USED:
1887 *result = MAXIMUM_WAIT_OBJECTS;
1889 case AP_MPMQ_IS_THREADED:
1890 *result = AP_MPMQ_STATIC;
1892 case AP_MPMQ_IS_FORKED:
1893 *result = AP_MPMQ_NOT_SUPPORTED;
1895 case AP_MPMQ_HARD_LIMIT_DAEMONS:
1896 *result = HARD_SERVER_LIMIT;
1898 case AP_MPMQ_HARD_LIMIT_THREADS:
1899 *result = HARD_THREAD_LIMIT;
1901 case AP_MPMQ_MAX_THREADS:
1902 *result = ap_threads_per_child;
1904 case AP_MPMQ_MIN_SPARE_DAEMONS:
1907 case AP_MPMQ_MIN_SPARE_THREADS:
1910 case AP_MPMQ_MAX_SPARE_DAEMONS:
1913 case AP_MPMQ_MAX_SPARE_THREADS:
1916 case AP_MPMQ_MAX_REQUESTS_DAEMON:
1917 *result = ap_max_requests_per_child;
1919 case AP_MPMQ_MAX_DAEMONS:
1923 return APR_ENOTIMPL;
1926 #define SERVICE_UNSET (-1)
1927 static apr_status_t service_set = SERVICE_UNSET;
1928 static apr_status_t service_to_start_success;
1929 static int inst_argc;
1930 static const char * const *inst_argv;
1931 static char *service_name = NULL;
1933 void winnt_rewrite_args(process_rec *process)
1935 /* Handle the following SCM aspects in this phase:
1937 * -k runservice [transition for WinNT, nothing for Win9x]
1938 * -k (!)install [error out if name is not installed]
1940 * We can't leave this phase until we know our identity
1941 * and modify the command arguments appropriately.
1944 char *def_server_root;
1945 char fnbuf[MAX_PATH];
1951 int running_as_service = 1;
1953 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1954 GetVersionEx(&osver);
1956 /* AP_PARENT_PID is only valid in the child */
1957 pid = getenv("AP_PARENT_PID");
1960 /* This is the child */
1961 my_pid = GetCurrentProcessId();
1962 parent_pid = (DWORD) atol(pid);
1964 /* The parent is responsible for providing the
1965 * COMPLETE ARGUMENTS REQUIRED to the child.
1967 * No further argument parsing is needed, but
1968 * for good measure we will provide a simple
1969 * signal string for later testing.
1971 signal_arg = "runchild";
1975 /* This is the parent, we have a long way to go :-) */
1976 parent_pid = my_pid = GetCurrentProcessId();
1978 /* Rewrite process->argv[];
1980 * strip out -k signal into signal_arg
1981 * strip out -n servicename and set the names
1982 * add default -d serverroot from the path of this executable
1984 * The end result will look like:
1986 * The invocation command (%0)
1987 * The -d serverroot default from the running executable
1988 * The requested service's (-n) registry ConfigArgs
1989 * The WinNT SCM's StartService() args
1991 if (!GetModuleFileName(NULL, fnbuf, sizeof(fnbuf))) {
1992 rv = apr_get_os_error();
1993 ap_log_error(APLOG_MARK,APLOG_CRIT, rv, NULL,
1994 "Failed to get the path of Apache.exe");
1997 /* WARNING: There is an implict assumption here that the
1998 * executable resides in ServerRoot or ServerRoot\bin
2000 def_server_root = (char *) apr_filename_of_pathname(fnbuf);
2001 if (def_server_root > fnbuf) {
2002 *(def_server_root - 1) = '\0';
2003 def_server_root = (char *) apr_filename_of_pathname(fnbuf);
2004 if (!strcasecmp(def_server_root, "bin"))
2005 *(def_server_root - 1) = '\0';
2007 apr_filepath_merge(&def_server_root, NULL, fnbuf,
2008 APR_FILEPATH_TRUENAME, process->pool);
2010 /* Use process->pool so that the rewritten argv
2011 * lasts for the lifetime of the server process,
2012 * because pconf will be destroyed after the
2013 * initial pre-flight of the config parser.
2015 mpm_new_argv = apr_array_make(process->pool, process->argc + 2,
2016 sizeof(const char *));
2017 *(const char **)apr_array_push(mpm_new_argv) = process->argv[0];
2018 *(const char **)apr_array_push(mpm_new_argv) = "-d";
2019 *(const char **)apr_array_push(mpm_new_argv) = def_server_root;
2021 fixed_args = mpm_new_argv->nelts;
2025 apr_getopt_init(&opt, process->pool, process->argc, (char**) process->argv);
2027 while ((rv = apr_getopt(opt, "n:k:iu" AP_SERVER_BASEARGS,
2028 optbuf + 1, &optarg)) == APR_SUCCESS) {
2029 switch (optbuf[1]) {
2031 service_set = mpm_service_set_name(process->pool, &service_name,
2035 signal_arg = optarg;
2038 *(const char **)apr_array_push(mpm_new_argv) =
2039 apr_pstrdup(process->pool, optbuf);
2042 *(const char **)apr_array_push(mpm_new_argv) = optarg;
2048 /* back up to capture the bad argument */
2049 if (rv == APR_BADCH || rv == APR_BADARG) {
2053 while (opt->ind < opt->argc) {
2054 *(const char **)apr_array_push(mpm_new_argv) =
2055 apr_pstrdup(process->pool, opt->argv[opt->ind++]);
2058 /* Track the number of args actually entered by the user */
2059 inst_argc = mpm_new_argv->nelts - fixed_args;
2061 /* Provide a default 'run' -k arg to simplify signal_arg tests */
2065 running_as_service = 0;
2068 if (!strcasecmp(signal_arg, "runservice"))
2070 /* Start the NT Service _NOW_ because the WinNT SCM is
2071 * expecting us to rapidly assume control of our own
2072 * process, the SCM will tell us our service name, and
2073 * may have extra StartService() command arguments to
2076 * Any other process has a console, so we don't to begin
2077 * a Win9x service until the configuration is parsed and
2078 * any command line errors are reported.
2080 * We hold the return value so that we can die in pre_config
2081 * after logging begins, and the failure can land in the log.
2083 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) {
2084 service_to_start_success = mpm_service_to_start(&service_name,
2086 if (service_to_start_success == APR_SUCCESS) {
2087 service_set = APR_SUCCESS;
2092 /* Get the default for any -k option, except run */
2093 if (service_set == SERVICE_UNSET && strcasecmp(signal_arg, "run")) {
2094 service_set = mpm_service_set_name(process->pool, &service_name,
2095 AP_DEFAULT_SERVICE_NAME);
2098 if (!strcasecmp(signal_arg, "install")) /* -k install */
2100 if (service_set == APR_SUCCESS)
2102 ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
2103 "%s: Service is already installed.", service_name);
2107 else if (running_as_service)
2109 if (service_set == APR_SUCCESS)
2111 rv = mpm_merge_service_args(process->pool, mpm_new_argv,
2113 if (rv == APR_SUCCESS) {
2114 ap_log_error(APLOG_MARK,APLOG_NOERRNO|APLOG_INFO, 0, NULL,
2115 "Using ConfigArgs of the installed service "
2116 "\"%s\".", service_name);
2119 ap_log_error(APLOG_MARK,APLOG_WARNING, rv, NULL,
2120 "No installed ConfigArgs for the service "
2121 "\"%s\", using Apache defaults.", service_name);
2126 ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL,
2127 "No installed service named \"%s\".", service_name);
2131 if (strcasecmp(signal_arg, "install") && service_set && service_set != SERVICE_UNSET)
2133 ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL,
2134 "No installed service named \"%s\".", service_name);
2138 /* Track the args actually entered by the user.
2139 * These will be used for the -k install parameters, as well as
2140 * for the -k start service override arguments.
2142 inst_argv = (const char * const *)mpm_new_argv->elts
2143 + mpm_new_argv->nelts - inst_argc;
2145 process->argc = mpm_new_argv->nelts;
2146 process->argv = (const char * const *) mpm_new_argv->elts;
2150 static int winnt_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
2152 /* Handle the following SCM aspects in this phase:
2154 * -k runservice [WinNT errors logged from rewrite_args]
2157 * -k shutdown (same as -k stop). Maintained for backward compatability.
2159 * in these cases we -don't- care if httpd.conf has config errors!
2163 if (ap_exists_config_define("ONE_PROCESS") ||
2164 ap_exists_config_define("DEBUG"))
2167 if (!strcasecmp(signal_arg, "runservice")
2168 && (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
2169 && (service_to_start_success != APR_SUCCESS)) {
2170 ap_log_error(APLOG_MARK,APLOG_CRIT, service_to_start_success, NULL,
2171 "%s: Unable to start the service manager.",
2176 if (!strcasecmp(signal_arg, "uninstall")) {
2177 rv = mpm_service_uninstall();
2181 if ((!strcasecmp(signal_arg, "stop")) ||
2182 (!strcasecmp(signal_arg, "shutdown"))) {
2183 mpm_signal_service(ptemp, 0);
2187 ap_listen_pre_config();
2188 ap_threads_per_child = DEFAULT_START_THREAD;
2189 ap_pid_fname = DEFAULT_PIDLOG;
2190 ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
2192 apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
2197 static int winnt_post_config(apr_pool_t *pconf_, apr_pool_t *plog, apr_pool_t *ptemp, server_rec* s)
2199 static int restart_num = 0;
2200 apr_status_t rv = 0;
2202 /* Initialize shared static objects.
2207 /* Handle the following SCM aspects in this phase:
2213 * -k runservice [Win95, only once - after we parsed the config]
2215 * because all of these signals are useful _only_ if there
2216 * is a valid conf\httpd.conf environment to start.
2218 * We reached this phase by avoiding errors that would cause
2219 * these options to fail unexpectedly in another process.
2222 if (!strcasecmp(signal_arg, "install")) {
2223 rv = mpm_service_install(ptemp, inst_argc, inst_argv, 0);
2226 if (!strcasecmp(signal_arg, "config")) {
2227 rv = mpm_service_install(ptemp, inst_argc, inst_argv, 1);
2231 if (!strcasecmp(signal_arg, "start")) {
2234 /* Close the listening sockets. */
2235 for (lr = ap_listeners; lr; lr = lr->next) {
2236 apr_socket_close(lr->sd);
2239 rv = mpm_service_start(ptemp, inst_argc, inst_argv);
2243 if (!strcasecmp(signal_arg, "restart")) {
2244 mpm_signal_service(ptemp, 1);
2248 if (parent_pid == my_pid)
2250 if (restart_num++ == 1)
2252 /* This code should be run once in the parent and not run
2255 PSECURITY_ATTRIBUTES sa = GetNullACL(); /* returns NULL if invalid (Win95?) */
2256 setup_signal_names(apr_psprintf(pconf,"ap%d", parent_pid));
2258 ap_log_pid(pconf, ap_pid_fname);
2260 /* Create shutdown event, apPID_shutdown, where PID is the parent
2261 * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
2263 shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
2264 if (!shutdown_event) {
2265 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
2266 "Parent: Cannot create shutdown event %s", signal_shutdown_name);
2267 CleanNullACL((void *)sa);
2268 return HTTP_INTERNAL_SERVER_ERROR;
2271 /* Create restart event, apPID_restart, where PID is the parent
2272 * Apache process ID. Restart is signaled by 'apache -k restart'.
2274 restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
2275 if (!restart_event) {
2276 CloseHandle(shutdown_event);
2277 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
2278 "Parent: Cannot create restart event %s", signal_restart_name);
2279 CleanNullACL((void *)sa);
2280 return HTTP_INTERNAL_SERVER_ERROR;
2282 CleanNullACL((void *)sa);
2284 /* Now that we are flying at 15000 feet...
2285 * wipe out the Win95 service console,
2286 * signal the SCM the WinNT service started, or
2287 * if not a service, setup console handlers instead.
2289 if (!strcasecmp(signal_arg, "runservice"))
2291 if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT)
2293 rv = mpm_service_to_start(&service_name,
2295 if (rv != APR_SUCCESS) {
2296 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
2297 "%s: Unable to start the service manager.",
2299 return HTTP_INTERNAL_SERVER_ERROR;
2303 else /* ! -k runservice */
2305 mpm_start_console_handler();
2308 /* Create the start mutex, apPID, where PID is the parent Apache process ID.
2309 * Ths start mutex is used during a restart to prevent more than one
2310 * child process from entering the accept loop at once.
2312 rv = apr_proc_mutex_create(&start_mutex,
2315 ap_server_conf->process->pool);
2316 if (rv != APR_SUCCESS) {
2317 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
2318 "%s: Unable to create the start_mutex.",
2320 return HTTP_INTERNAL_SERVER_ERROR;
2324 else /* parent_pid != my_pid */
2326 mpm_start_child_console_handler();
2331 /* This really should be a post_config hook, but the error log is already
2332 * redirected by that point, so we need to do this in the open_logs phase.
2334 static int winnt_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
2336 if (parent_pid != my_pid) {
2340 /* We cannot initialize our listeners if we are restarting
2341 * (the parent process already has glomed on to them)
2342 * nor should we do so for service reconfiguration
2343 * (since the service may already be running.)
2345 if (!strcasecmp(signal_arg, "restart")
2346 || !strcasecmp(signal_arg, "config")) {
2350 if (ap_setup_listeners(s) < 1) {
2351 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT|APLOG_STARTUP, 0,
2352 NULL, "no listening sockets available, shutting down");
2356 if (!set_listeners_noninheritable(s->process->pool)) {
2363 static void winnt_child_init(apr_pool_t *pchild, struct server_rec *s)
2367 setup_signal_names(apr_psprintf(pchild,"ap%d", parent_pid));
2369 /* This is a child process, not in single process mode */
2371 /* Set up events and the scoreboard */
2372 get_handles_from_parent(s);
2374 /* Set up the listeners */
2375 get_listeners_from_parent(s);
2377 ap_my_generation = atoi(getenv("AP_MY_GENERATION"));
2379 rv = apr_proc_mutex_child_init(&start_mutex, signal_name_prefix,
2383 /* Single process mode - this lock doesn't even need to exist */
2384 rv = apr_proc_mutex_create(&start_mutex, signal_name_prefix,
2385 APR_LOCK_DEFAULT, s->process->pool);
2387 /* Borrow the shutdown_even as our _child_ loop exit event */
2388 exit_event = shutdown_event;
2390 if (rv != APR_SUCCESS) {
2391 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
2392 "%s child %d: Unable to init the start_mutex.",
2393 service_name, my_pid);
2394 exit(APEXIT_CHILDINIT);
2399 AP_DECLARE(int) ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s )
2401 static int restart = 0; /* Default is "not a restart" */
2403 /* ### If non-graceful restarts are ever introduced - we need to rerun
2404 * the pre_mpm hook on subsequent non-graceful restarts. But Win32
2405 * has only graceful style restarts - and we need this hook to act
2406 * the same on Win32 as on Unix.
2408 if (!restart && ((parent_pid == my_pid) || one_process)) {
2409 /* Set up the scoreboard. */
2410 if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
2415 if ((parent_pid != my_pid) || one_process)
2417 /* The child process or in one_process (debug) mode
2419 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
2420 "Child %d: Child process is running", my_pid);
2424 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
2425 "Child %d: Child process is exiting", my_pid);
2430 /* A real-honest to goodness parent */
2432 restart = master_main(ap_server_conf, shutdown_event, restart_event);
2436 /* Shutting down. Clean up... */
2437 const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
2439 if (pidfile != NULL && unlink(pidfile) == 0) {
2440 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS,
2441 ap_server_conf, "removed PID file %s (pid=%ld)",
2442 pidfile, GetCurrentProcessId());
2444 apr_proc_mutex_destroy(start_mutex);
2446 CloseHandle(restart_event);
2447 CloseHandle(shutdown_event);
2453 return 0; /* Restart */
2456 static void winnt_hooks(apr_pool_t *p)
2458 /* The prefork open_logs phase must run before the core's, or stderr
2459 * will be redirected to a file, and the messages won't print to the
2462 static const char *const aszSucc[] = {"core.c", NULL};
2464 ap_hook_pre_config(winnt_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2465 ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
2466 ap_hook_child_init(winnt_child_init, NULL, NULL, APR_HOOK_MIDDLE);
2467 ap_hook_open_logs(winnt_open_logs, NULL, aszSucc, APR_HOOK_MIDDLE);
2470 AP_MODULE_DECLARE_DATA module mpm_winnt_module = {
2472 winnt_rewrite_args, /* hook to run before apache parses args */
2473 NULL, /* create per-directory config structure */
2474 NULL, /* merge per-directory config structures */
2475 NULL, /* create per-server config structure */
2476 NULL, /* merge per-server config structures */
2477 winnt_cmds, /* command apr_table_t */
2478 winnt_hooks /* register_hooks */