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)
451 case SIGNAL_PARENT_SHUTDOWN:
453 signal_name = signal_shutdown_name;
456 /* This MPM supports only graceful restarts right now */
457 case SIGNAL_PARENT_RESTART:
458 case SIGNAL_PARENT_RESTART_GRACEFUL:
460 signal_name = signal_restart_name;
468 e = OpenEvent(EVENT_MODIFY_STATE, FALSE, signal_name);
470 /* Um, problem, can't signal the parent, which means we can't
471 * signal ourselves to die. Ignore for now...
473 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf,
474 "OpenEvent on %s event", signal_name);
477 if (SetEvent(e) == 0) {
478 /* Same problem as above */
479 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf,
480 "SetEvent on %s event", signal_name);
487 /* set_listeners_noninheritable()
488 * Make the listening socket handles noninheritable by processes
489 * started out of this process.
491 static int set_listeners_noninheritable(apr_pool_t *p)
496 HANDLE hProcess = GetCurrentProcess();
498 for (lr = ap_listeners; lr; lr = lr->next) {
499 apr_os_sock_get(&nsd,lr->sd);
500 if (!DuplicateHandle(hProcess, (HANDLE) nsd, hProcess, &dup,
501 0, FALSE, DUPLICATE_SAME_ACCESS)) {
502 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), ap_server_conf,
503 "set_listeners_noninheritable: DuplicateHandle failed.");
508 apr_os_sock_put(&lr->sd, &nsd, p);
512 if (my_pid == parent_pid) {
513 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
514 "Parent: Marked listeners as not inheritable.");
516 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
517 "Child %d: Marked listeners as not inheritable.", my_pid);
523 * find_ready_listener()
524 * Only used by Win9* and should go away when the win9*_accept() function is
525 * reimplemented using apr_poll().
527 static ap_listen_rec *head_listener;
528 static APR_INLINE ap_listen_rec *find_ready_listener(fd_set * main_fds)
533 for (lr = head_listener; lr ; lr = lr->next) {
534 apr_os_sock_get(&nsd, lr->sd);
535 if (FD_ISSET(nsd, main_fds)) {
536 head_listener = lr->next;
537 if (head_listener == NULL)
538 head_listener = ap_listeners;
549 void get_handles_from_parent(server_rec *s)
557 pipe = GetStdHandle(STD_INPUT_HANDLE);
558 if (!ReadFile(pipe, &exit_event, sizeof(HANDLE),
559 &BytesRead, (LPOVERLAPPED) NULL)
560 || (BytesRead != sizeof(HANDLE))) {
561 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
562 "Child %d: Unable to retrieve the exit event from the parent", my_pid);
563 exit(APEXIT_CHILDINIT);
566 if (!ReadFile(pipe, &hScore, sizeof(hScore),
567 &BytesRead, (LPOVERLAPPED) NULL)
568 || (BytesRead != sizeof(hScore))) {
569 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
570 "Child %d: Unable to retrieve the scoreboard from the parent", my_pid);
571 exit(APEXIT_CHILDINIT);
574 if ((rv = apr_os_shm_put(&ap_scoreboard_shm, &hScore, s->process->pool))
576 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
577 "Child %d: Unable to access the scoreboard from the parent", my_pid);
578 exit(APEXIT_CHILDINIT);
581 rv = ap_reopen_scoreboard(pchild, &ap_scoreboard_shm, 1);
582 if (rv || !(sb_shared = apr_shm_baseaddr_get(ap_scoreboard_shm))) {
583 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
584 "Child %d: Unable to reopen the scoreboard from the parent", my_pid);
585 exit(APEXIT_CHILDINIT);
587 ap_init_scoreboard(sb_shared);
589 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
590 "Child %d: Retrieved our scoreboard from the parent.", my_pid);
594 * get_listeners_from_parent()
595 * The listen sockets are opened in the parent. This function, which runs
596 * exclusively in the child process, receives them from the parent and
597 * makes them availeble in the child.
599 void get_listeners_from_parent(server_rec *s)
601 WSAPROTOCOL_INFO WSAProtocolInfo;
608 /* Set up a default listener if necessary */
609 if (ap_listeners == NULL) {
611 lr = apr_palloc(s->process->pool, sizeof(ap_listen_rec));
613 lr->next = ap_listeners;
617 /* Open the pipe to the parent process to receive the inherited socket
618 * data. The sockets have been set to listening in the parent process.
620 pipe = GetStdHandle(STD_INPUT_HANDLE);
622 for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) {
623 if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
624 &BytesRead, (LPOVERLAPPED) NULL)) {
625 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
626 "setup_inherited_listeners: Unable to read socket data from parent");
627 exit(APEXIT_CHILDINIT);
629 nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
630 &WSAProtocolInfo, 0, 0);
631 if (nsd == INVALID_SOCKET) {
632 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf,
633 "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
634 exit(APEXIT_CHILDINIT);
636 apr_os_sock_put(&lr->sd, &nsd, pconf);
639 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
640 "Child %d: retrieved %d listeners from parent", my_pid, lcnt);
642 if (!set_listeners_noninheritable(pconf)) {
643 exit(APEXIT_CHILDINIT);
648 /* Windows 9x specific code...
649 * Accept processing for on Windows 95/98 uses a producer/consumer queue
650 * model. A single thread accepts connections and queues the accepted socket
651 * to the accept queue for consumption by a pool of worker threads.
654 * The accept threads runs this function, which accepts connections off
655 * the network and calls add_job() to queue jobs to the accept_queue.
656 * add_job()/remove_job()
657 * Add or remove an accepted socket from the list of sockets
658 * connected to clients. allowed_globals.jobmutex protects
659 * against multiple concurrent access to the linked list of jobs.
660 * win9x_get_connection()
661 * Calls remove_job() to pull a job from the accept queue. All the worker
662 * threads block on remove_job.
665 typedef struct joblist_s {
666 struct joblist_s *next;
670 typedef struct globals_s {
674 apr_thread_mutex_t *jobmutex;
678 globals allowed_globals = {NULL, NULL, NULL, NULL, 0};
679 #define MAX_SELECT_ERRORS 100
681 static void add_job(int sock)
685 new_job = (joblist *) malloc(sizeof(joblist));
686 if (new_job == NULL) {
687 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
688 "Ouch! Out of memory in add_job()!");
691 new_job->next = NULL;
692 new_job->sock = sock;
694 apr_thread_mutex_lock(allowed_globals.jobmutex);
696 if (allowed_globals.jobtail != NULL)
697 allowed_globals.jobtail->next = new_job;
698 allowed_globals.jobtail = new_job;
699 if (!allowed_globals.jobhead)
700 allowed_globals.jobhead = new_job;
701 allowed_globals.jobcount++;
702 ReleaseSemaphore(allowed_globals.jobsemaphore, 1, NULL);
704 apr_thread_mutex_unlock(allowed_globals.jobmutex);
707 static int remove_job(void)
712 WaitForSingleObject(allowed_globals.jobsemaphore, INFINITE);
713 apr_thread_mutex_lock(allowed_globals.jobmutex);
715 if (shutdown_in_progress && !allowed_globals.jobhead) {
716 apr_thread_mutex_unlock(allowed_globals.jobmutex);
719 job = allowed_globals.jobhead;
721 allowed_globals.jobhead = job->next;
722 if (allowed_globals.jobhead == NULL)
723 allowed_globals.jobtail = NULL;
724 apr_thread_mutex_unlock(allowed_globals.jobmutex);
731 static void win9x_accept(void * dummy)
737 SOCKET nsd = INVALID_SOCKET;
738 struct sockaddr_in sa_client;
739 int count_select_errors = 0;
743 struct fd_set listenfds;
744 SOCKET listenmaxfd = INVALID_SOCKET;
746 /* Setup the listeners
747 * ToDo: Use apr_poll()
750 for (lr = ap_listeners; lr; lr = lr->next) {
751 if (lr->sd != NULL) {
752 apr_os_sock_get(&nsd, lr->sd);
753 FD_SET(nsd, &listenfds);
754 if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
759 head_listener = ap_listeners;
761 while (!shutdown_in_progress) {
762 tv.tv_sec = wait_time;
764 memcpy(&main_fds, &listenfds, sizeof(fd_set));
766 rc = select(listenmaxfd + 1, &main_fds, NULL, NULL, &tv);
768 if (rc == 0 || (rc == SOCKET_ERROR && APR_STATUS_IS_EINTR(apr_get_netos_error()))) {
769 count_select_errors = 0; /* reset count of errors */
772 else if (rc == SOCKET_ERROR) {
773 /* A "real" error occurred, log it and increment the count of
774 * select errors. This count is used to ensure we don't go into
775 * a busy loop of continuous errors.
777 ap_log_error(APLOG_MARK, APLOG_INFO, apr_get_netos_error(), ap_server_conf,
778 "select failed with error %d", apr_get_netos_error());
779 count_select_errors++;
780 if (count_select_errors > MAX_SELECT_ERRORS) {
781 shutdown_in_progress = 1;
782 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), ap_server_conf,
783 "Too many errors in select loop. Child process exiting.");
789 lr = find_ready_listener(&main_fds);
791 /* fetch the native socket descriptor */
792 apr_os_sock_get(&nsd, lr->sd);
797 clen = sizeof(sa_client);
798 csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
799 if (csd == INVALID_SOCKET) {
802 } while (csd < 0 && APR_STATUS_IS_EINTR(apr_get_netos_error()));
805 if (APR_STATUS_IS_ECONNABORTED(apr_get_netos_error())) {
806 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_netos_error(), ap_server_conf,
807 "accept: (client socket)");
814 SetEvent(exit_event);
817 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
821 if (context == NULL) {
822 /* allocate the completion context and the transaction pool */
823 context = apr_pcalloc(pconf, sizeof(COMP_CONTEXT));
824 apr_pool_create(&context->ptrans, pconf);
829 apr_pool_clear(context->ptrans);
830 context->accept_socket = remove_job();
831 if (context->accept_socket == -1) {
834 len = sizeof(struct sockaddr);
835 context->sa_server = apr_palloc(context->ptrans, len);
836 if (getsockname(context->accept_socket,
837 context->sa_server, &len)== SOCKET_ERROR) {
838 ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), ap_server_conf,
839 "getsockname failed");
842 len = sizeof(struct sockaddr);
843 context->sa_client = apr_palloc(context->ptrans, len);
844 if ((getpeername(context->accept_socket,
845 context->sa_client, &len)) == SOCKET_ERROR) {
846 ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), ap_server_conf,
847 "getpeername failed");
848 memset(&context->sa_client, '\0', sizeof(context->sa_client));
851 /* do we NEED_DUPPED_CSD ?? */
856 /* Windows NT/2000 specific code...
857 * Accept processing for on Windows NT uses a producer/consumer queue
858 * model. An accept thread accepts connections off the network then issues
859 * PostQueuedCompletionStatus() to awake a thread blocked on the ThreadDispatch
863 * One or more accept threads run in this function, each of which accepts
864 * connections off the network and calls PostQueuedCompletionStatus() to
865 * queue an io completion packet to the ThreadDispatch IOCompletionPort.
866 * winnt_get_connection()
867 * Worker threads block on the ThreadDispatch IOCompletionPort awaiting
868 * connections to service.
870 static void winnt_accept(void *listen_socket)
873 PCOMP_CONTEXT pCompContext;
878 nlsd = (SOCKET) listen_socket;
880 while (!shutdown_in_progress) {
881 pCompContext = mpm_get_completion_context();
883 /* Hopefully whatever is preventing us from getting a
884 * completion context is a temporary resource constraint.
891 /* Create and initialize the accept socket */
892 if (pCompContext->accept_socket == INVALID_SOCKET) {
893 pCompContext->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
894 if (pCompContext->accept_socket == INVALID_SOCKET) {
895 /* Hopefully another temporary condition. Be graceful. */
896 ap_log_error(APLOG_MARK,APLOG_WARNING, apr_get_netos_error(), ap_server_conf,
897 "winnt_accept: Failed to allocate an accept socket. "
898 "Temporary resource constraint? Try again.");
904 /* AcceptEx on the completion context. The completion context will be
905 * signaled when a connection is accepted.
907 if (!AcceptEx(nlsd, pCompContext->accept_socket,
913 &pCompContext->Overlapped)) {
914 lasterror = apr_get_netos_error();
915 if (lasterror == APR_FROM_OS_ERROR(WSAEINVAL)) {
916 /* Hack alert. Occasionally, TransmitFile will not recycle the
917 * accept socket (usually when the client disconnects early).
918 * Get a new socket and try the call again.
920 closesocket(pCompContext->accept_socket);
921 pCompContext->accept_socket = INVALID_SOCKET;
922 ap_log_error(APLOG_MARK, APLOG_DEBUG, lasterror, ap_server_conf,
923 "winnt_accept: AcceptEx failed due to early client "
924 "disconnect. Reallocate the accept socket and try again.");
925 if (shutdown_in_progress)
930 else if (lasterror != APR_FROM_OS_ERROR(ERROR_IO_PENDING)) {
931 ap_log_error(APLOG_MARK,APLOG_ERR, lasterror, ap_server_conf,
932 "winnt_accept: AcceptEx failed. Attempting to recover.");
933 closesocket(pCompContext->accept_socket);
934 pCompContext->accept_socket = INVALID_SOCKET;
939 /* Wait for pending i/o */
940 WaitForSingleObject(pCompContext->Overlapped.hEvent, INFINITE);
943 /* Inherit the listen socket settings. Required for
946 if (setsockopt(pCompContext->accept_socket, SOL_SOCKET,
947 SO_UPDATE_ACCEPT_CONTEXT, (char *)&nlsd,
949 ap_log_error(APLOG_MARK, APLOG_WARNING, apr_get_netos_error(), ap_server_conf,
950 "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
951 /* Not a failure condition. Keep running. */
954 /* Get the local & remote address */
955 GetAcceptExSockaddrs(pCompContext->buff,
959 &pCompContext->sa_server,
960 &pCompContext->sa_server_len,
961 &pCompContext->sa_client,
962 &pCompContext->sa_client_len);
964 /* When a connection is received, send an io completion notification to
965 * the ThreadDispatchIOCP. This function could be replaced by
966 * mpm_post_completion_context(), but why do an extra function call...
968 PostQueuedCompletionStatus(ThreadDispatchIOCP, 0, IOCP_CONNECTION_ACCEPTED,
969 &pCompContext->Overlapped);
972 if (!shutdown_in_progress) {
973 /* Yow, hit an irrecoverable error! Tell the child to die. */
974 SetEvent(exit_event);
977 static PCOMP_CONTEXT winnt_get_connection(PCOMP_CONTEXT pCompContext)
984 mpm_recycle_completion_context(pCompContext);
988 if (workers_may_exit) {
992 rc = GetQueuedCompletionStatus(ThreadDispatchIOCP, &BytesRead, &CompKey,
995 rc = apr_get_os_error();
996 ap_log_error(APLOG_MARK,APLOG_DEBUG, rc, ap_server_conf,
997 "Child %d: GetQueuedComplationStatus returned %d", my_pid, rc);
1002 case IOCP_CONNECTION_ACCEPTED:
1003 pCompContext = CONTAINING_RECORD(pol, COMP_CONTEXT, Overlapped);
1006 g_blocked_threads--;
1009 g_blocked_threads--;
1015 g_blocked_threads--;
1017 if ((rc = apr_pool_create(&pCompContext->ptrans, pconf)) != APR_SUCCESS) {
1018 ap_log_error(APLOG_MARK,APLOG_DEBUG, rc, ap_server_conf,
1019 "Child %d: apr_pool_create failed with rc %d", my_pid, rc);
1022 return pCompContext;
1027 * Main entry point for the worker threads. Worker threads block in
1028 * win*_get_connection() awaiting a connection to service.
1030 static void worker_main(long thread_num)
1032 static int requests_this_child = 0;
1033 PCOMP_CONTEXT context = NULL;
1034 apr_os_sock_info_t sockinfo;
1035 ap_sb_handle_t *sbh;
1039 apr_int32_t disconnected;
1041 ap_update_child_status_from_indexes(0, thread_num, SERVER_READY,
1042 (request_rec *) NULL);
1045 /* Grab a connection off the network */
1046 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1047 context = win9x_get_connection(context);
1050 context = winnt_get_connection(context);
1053 /* Time for the thread to exit */
1057 /* Have we hit MaxRequestPerChild connections? */
1058 if (ap_max_requests_per_child) {
1059 requests_this_child++;
1060 if (requests_this_child > ap_max_requests_per_child) {
1061 SetEvent(max_requests_per_child_event);
1065 sockinfo.os_sock = &context->accept_socket;
1066 sockinfo.local = context->sa_server;
1067 sockinfo.remote = context->sa_client;
1068 sockinfo.family = APR_INET;
1069 sockinfo.type = SOCK_STREAM;
1070 /* ### is this correct? Shouldn't be inheritable (at this point) */
1071 apr_os_sock_make(&context->sock, &sockinfo, context->ptrans);
1073 ap_create_sb_handle(&sbh, context->ptrans, 0, thread_num);
1074 c = ap_run_create_connection(context->ptrans, ap_server_conf, context->sock,
1078 ap_process_connection(c, context->sock);
1079 apr_getsocketopt(context->sock, APR_SO_DISCONNECTED, &disconnected);
1080 if (!disconnected) {
1081 context->accept_socket = INVALID_SOCKET;
1082 ap_lingering_close(c);
1086 /* ap_run_create_connection closes the socket on failure */
1087 context->accept_socket = INVALID_SOCKET;
1091 ap_update_child_status_from_indexes(0, thread_num, SERVER_DEAD,
1092 (request_rec *) NULL);
1094 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
1095 "Child %d: Thread exiting.", my_pid);
1098 static void cleanup_thread(thread *handles, int *thread_cnt, int thread_to_clean)
1102 CloseHandle(handles[thread_to_clean]);
1103 for (i = thread_to_clean; i < ((*thread_cnt) - 1); i++)
1104 handles[i] = handles[i + 1];
1110 * Entry point for the main control thread for the child process.
1111 * This thread creates the accept thread, worker threads and
1112 * monitors the child process for maintenance and shutdown
1115 static void child_main()
1117 apr_status_t status;
1119 HANDLE child_events[2];
1120 int nthreads = ap_threads_per_child;
1122 thread *child_handles;
1128 apr_pool_create(&pchild, pconf);
1130 ap_run_child_init(pchild, ap_server_conf);
1132 /* Initialize the child_events */
1133 max_requests_per_child_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1134 if (!max_requests_per_child_event) {
1135 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1136 "Child %d: Failed to create a max_requests event.", my_pid);
1137 exit(APEXIT_CHILDINIT);
1139 child_events[0] = exit_event;
1140 child_events[1] = max_requests_per_child_event;
1142 allowed_globals.jobsemaphore = CreateSemaphore(NULL, 0, 1000000, NULL);
1143 apr_thread_mutex_create(&allowed_globals.jobmutex,
1144 APR_THREAD_MUTEX_DEFAULT, pchild);
1147 * Wait until we have permission to start accepting connections.
1148 * start_mutex is used to ensure that only one child ever
1149 * goes into the listen/accept loop at once.
1151 status = apr_proc_mutex_lock(start_mutex);
1152 if (status != APR_SUCCESS) {
1153 ap_log_error(APLOG_MARK,APLOG_ERR, status, ap_server_conf,
1154 "Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
1155 exit(APEXIT_CHILDINIT);
1157 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, ap_server_conf,
1158 "Child %d: Acquired the start mutex.", my_pid);
1161 * Create the worker thread dispatch IOCompletionPort
1162 * on Windows NT/2000
1164 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
1165 /* Create the worker thread dispatch IOCP */
1166 ThreadDispatchIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
1169 0); /* CONCURRENT ACTIVE THREADS */
1170 apr_thread_mutex_create(&qlock, APR_THREAD_MUTEX_DEFAULT, pchild);
1174 * Create the pool of worker threads
1176 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, ap_server_conf,
1177 "Child %d: Starting %d worker threads.", my_pid, nthreads);
1178 child_handles = (thread) alloca(nthreads * sizeof(int));
1179 for (i = 0; i < nthreads; i++) {
1180 ap_update_child_status_from_indexes(0, i, SERVER_STARTING,
1181 (request_rec *) NULL);
1182 child_handles[i] = (thread) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
1183 (void *) i, 0, &tid);
1187 * Start the accept thread
1189 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1190 _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) win9x_accept,
1191 (void *) i, 0, &tid);
1193 /* Start an accept thread per listener */
1194 SOCKET nlsd; /* native listening sock descriptor */
1196 for (lr = ap_listeners; lr; lr = lr->next) {
1197 if (lr->sd != NULL) {
1198 apr_os_sock_get(&nlsd, lr->sd);
1199 _beginthreadex(NULL, 1000, (LPTHREAD_START_ROUTINE) winnt_accept,
1200 (void *) nlsd, 0, &tid);
1205 /* Wait for one of three events:
1207 * The exit_event is signaled by the parent process to notify
1208 * the child that it is time to exit.
1210 * max_requests_per_child_event:
1211 * This event is signaled by the worker threads to indicate that
1212 * the process has handled MaxRequestsPerChild connections.
1215 * To do periodic maintenance on the server (check for thread exits,
1216 * number of completion contexts, etc.)
1219 rv = WaitForMultipleObjects(2, (HANDLE *) child_events, FALSE, 1000);
1220 cld = rv - WAIT_OBJECT_0;
1221 if (rv == WAIT_FAILED) {
1222 /* Something serious is wrong */
1223 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1224 "Child %d: WAIT_FAILED -- shutting down server");
1227 else if (rv == WAIT_TIMEOUT) {
1228 apr_proc_other_child_check();
1230 else if (cld == 0) {
1231 /* Exit event was signaled */
1232 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
1233 "Child %d: Exit event signaled. Child process is ending.", my_pid);
1237 /* MaxRequestsPerChild event set by the worker threads.
1238 * Signal the parent to restart
1240 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
1241 "Child %d: Process exiting because it reached "
1242 "MaxRequestsPerChild. Signaling the parent to "
1243 "restart a new child process.", my_pid);
1244 ap_signal_parent(SIGNAL_PARENT_RESTART);
1249 /* Setting is_graceful will cause keep-alive connections to be closed
1250 * rather than block on the next network read.
1254 /* Setting shutdown_in_progress prevents new connections from
1255 * being accepted but allows the worker threads to continue
1256 * handling connections that have already been accepted.
1258 shutdown_in_progress = 1;
1260 /* Close the listening sockets. */
1261 for (lr = ap_listeners; lr ; lr = lr->next) {
1262 apr_socket_close(lr->sd);
1266 /* Release the start_mutex to let the new process (in the restart
1267 * scenario) a chance to begin accepting and servicing requests
1269 rv = apr_proc_mutex_unlock(start_mutex);
1270 if (rv == APR_SUCCESS) {
1271 ap_log_error(APLOG_MARK,APLOG_INFO | APLOG_NOERRNO, rv, ap_server_conf,
1272 "Child %d: Released the start mutex", my_pid);
1275 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
1276 "Child %d: Failure releasing the start mutex", my_pid);
1279 /* Tell the worker threads they may exit when done handling
1282 workers_may_exit = 1;
1284 /* Shutdown the worker threads */
1285 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1286 for (i = 0; i < nthreads; i++) {
1290 else { /* Windows NT/2000 */
1291 /* Post worker threads blocked on the ThreadDispatch IOCompletion port */
1292 while (g_blocked_threads > 0) {
1293 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, ap_server_conf,
1294 "Child %d: %d threads blocked on the completion port", my_pid, g_blocked_threads);
1295 for (i=g_blocked_threads; i > 0; i--) {
1296 PostQueuedCompletionStatus(ThreadDispatchIOCP, 0, IOCP_SHUTDOWN, NULL);
1300 /* Empty the accept queue of completion contexts */
1301 apr_thread_mutex_lock(qlock);
1303 CloseHandle(qhead->Overlapped.hEvent);
1304 closesocket(qhead->accept_socket);
1305 qhead = qhead->next;
1307 apr_thread_mutex_unlock(qlock);
1310 /* Give busy worker threads a chance to service their connections */
1311 ap_log_error(APLOG_MARK,APLOG_INFO, APR_SUCCESS, ap_server_conf,
1312 "Child %d: Waiting for %d threads to die.", my_pid, nthreads);
1313 end_time = time(NULL) + 180;
1315 rv = wait_for_many_objects(nthreads, child_handles, end_time - time(NULL));
1316 if (rv != WAIT_TIMEOUT) {
1317 rv = rv - WAIT_OBJECT_0;
1318 ap_assert((rv >= 0) && (rv < nthreads));
1319 cleanup_thread(child_handles, &nthreads, rv);
1325 /* Kill remaining threads off the hard way */
1326 for (i = 0; i < nthreads; i++) {
1327 TerminateThread(child_handles[i], 1);
1328 CloseHandle(child_handles[i]);
1330 ap_log_error(APLOG_MARK,APLOG_DEBUG, APR_SUCCESS, ap_server_conf,
1331 "Child %d: All worker threads have ended.", my_pid);
1333 CloseHandle(allowed_globals.jobsemaphore);
1334 apr_thread_mutex_destroy(allowed_globals.jobmutex);
1335 if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS)
1336 apr_thread_mutex_destroy(qlock);
1338 apr_pool_destroy(pchild);
1339 CloseHandle(exit_event);
1342 static int send_handles_to_child(apr_pool_t *p, HANDLE child_exit_event, HANDLE hProcess, HANDLE hPipeWrite)
1347 HANDLE hCurrentProcess = GetCurrentProcess();
1350 if (!DuplicateHandle(hCurrentProcess, child_exit_event, hProcess, &hDup,
1351 EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, 0)) {
1352 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1353 "Parent: Unable to duplicate the exit event handle for the child");
1356 if (!WriteFile(hPipeWrite, &hDup, sizeof(hDup),
1357 &BytesWritten, (LPOVERLAPPED) NULL)
1358 || (BytesWritten != sizeof(hDup))) {
1359 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1360 "Parent: Unable to send the exit event handle to the child");
1364 if ((rv = apr_os_shm_get(&hScore, ap_scoreboard_shm)) != APR_SUCCESS) {
1365 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
1366 "Parent: Unable to retrieve the scoreboard handle for the child");
1369 if (!DuplicateHandle(hCurrentProcess, hScore, hProcess, &hDup,
1370 FILE_MAP_READ | FILE_MAP_WRITE, FALSE, 0)) {
1371 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1372 "Parent: Unable to duplicate the scoreboard handle to the child");
1375 if (!WriteFile(hPipeWrite, &hDup, sizeof(hDup),
1376 &BytesWritten, (LPOVERLAPPED) NULL)
1377 || (BytesWritten != sizeof(hDup))) {
1378 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1379 "Parent: Unable to send the scoreboard handle to the child");
1383 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
1384 "Parent: Sent the scoreboard to the child");
1388 static int send_listeners_to_child(apr_pool_t *p, DWORD dwProcessId, HANDLE hPipeWrite)
1392 LPWSAPROTOCOL_INFO lpWSAProtocolInfo;
1395 /* Run the chain of open sockets. For each socket, duplicate it
1396 * for the target process then send the WSAPROTOCOL_INFO
1397 * (returned by dup socket) to the child.
1399 for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) {
1401 lpWSAProtocolInfo = apr_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
1402 apr_os_sock_get(&nsd,lr->sd);
1403 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
1404 "Parent: Duplicating socket %d and sending it to child process %d",
1406 if (WSADuplicateSocket(nsd, dwProcessId,
1407 lpWSAProtocolInfo) == SOCKET_ERROR) {
1408 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf,
1409 "Parent: WSADuplicateSocket failed for socket %d. Check the FAQ.", lr->sd );
1413 if (!WriteFile(hPipeWrite, lpWSAProtocolInfo, (DWORD) sizeof(WSAPROTOCOL_INFO),
1415 (LPOVERLAPPED) NULL)
1416 || BytesWritten != sizeof(WSAPROTOCOL_INFO)) {
1417 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1418 "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
1423 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, ap_server_conf,
1424 "Parent: Sent %d listeners to child %d", lcnt, dwProcessId);
1428 static int create_process(apr_pool_t *p, HANDLE *child_proc, HANDLE *child_exit_event)
1437 STARTUPINFO si; /* Filled in prior to call to CreateProcess */
1438 PROCESS_INFORMATION pi; /* filled in on call to CreateProcess */
1445 HANDLE hCurrentProcess = GetCurrentProcess();
1446 SECURITY_ATTRIBUTES sa;
1448 sa.nLength = sizeof(sa);
1449 sa.bInheritHandle = TRUE;
1450 sa.lpSecurityDescriptor = NULL;
1452 /* Build the command line. Should look something like this:
1453 * C:/apache/bin/apache.exe -f ap_server_confname
1454 * First, get the path to the executable...
1456 rv = GetModuleFileName(NULL, buf, sizeof(buf));
1457 if (rv == sizeof(buf)) {
1458 ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, ap_server_conf,
1459 "Parent: Path to Apache process too long");
1461 } else if (rv == 0) {
1462 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1463 "Parent: GetModuleFileName() returned NULL for current process.");
1467 /* Build the command line */
1468 pCommand = apr_psprintf(p, "\"%s\"", buf);
1469 for (i = 1; i < ap_server_conf->process->argc; i++) {
1470 pCommand = apr_pstrcat(p, pCommand, " \"", ap_server_conf->process->argv[i], "\"", NULL);
1473 /* Create a pipe to send socket info to the child */
1474 if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) {
1475 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1476 "Parent: Unable to create pipe to child process.");
1480 /* Make our end of the handle non-inherited */
1481 if (DuplicateHandle(hCurrentProcess, hPipeWrite, hCurrentProcess,
1482 &hDup, 0, FALSE, DUPLICATE_SAME_ACCESS)) {
1483 CloseHandle(hPipeWrite);
1487 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1488 "Parent: Unable to duplicate pipe to child.\n");
1489 CloseHandle(hPipeWrite);
1490 CloseHandle(hPipeRead);
1494 /* Open a null handle to soak info from the child */
1495 hNullOutput = CreateFile("nul", GENERIC_READ | GENERIC_WRITE,
1496 FILE_SHARE_READ | FILE_SHARE_WRITE,
1497 &sa, OPEN_EXISTING, 0, NULL);
1498 if (hNullOutput == INVALID_HANDLE_VALUE) {
1499 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1500 "Parent: Unable to create null output pipe for child process.\n");
1501 CloseHandle(hPipeWrite);
1502 CloseHandle(hPipeRead);
1506 /* Child's initial stderr -> our main server error log (or, failing that, stderr) */
1507 if (ap_server_conf->error_log) { /* Is this check really necessary?*/
1508 rv = apr_os_file_get(&hShareError, ap_server_conf->error_log);
1509 if (rv == APR_SUCCESS && hShareError != INVALID_HANDLE_VALUE) {
1510 if (DuplicateHandle(hCurrentProcess, hShareError,
1511 hCurrentProcess, &hDup,
1512 GENERIC_WRITE, TRUE, 0)) {
1516 rv = apr_get_os_error();
1519 if (rv != APR_SUCCESS) {
1520 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
1521 "Parent: Unable to share error log with child.\n");
1522 CloseHandle(hPipeWrite);
1523 CloseHandle(hPipeRead);
1524 CloseHandle(hNullOutput);
1527 else if (hShareError == INVALID_HANDLE_VALUE) {
1528 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_CRIT, 0, ap_server_conf,
1529 "Parent: Failed to share error log with child.\n");
1530 CloseHandle(hPipeWrite);
1531 CloseHandle(hPipeRead);
1532 CloseHandle(hNullOutput);
1537 hShareError = GetStdHandle(STD_ERROR_HANDLE);
1540 /* Create the child_exit_event */
1541 hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1543 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1544 "Parent: Could not create exit event for child process");
1545 CloseHandle(hPipeWrite);
1546 CloseHandle(hPipeRead);
1547 CloseHandle(hNullOutput);
1548 if (GetStdHandle(STD_ERROR_HANDLE) != hShareError) {
1549 CloseHandle(hShareError);
1555 * Build the environment
1556 * Win32's CreateProcess call requires that the environment
1557 * be passed in an environment block, a null terminated block of
1558 * null terminated strings.
1560 _putenv(apr_psprintf(p,"AP_PARENT_PID=%i", parent_pid));
1561 _putenv(apr_psprintf(p,"AP_MY_GENERATION=%i", ap_my_generation));
1565 while (_environ[i]) {
1566 iEnvBlockLen += strlen(_environ[i]) + 1;
1569 pEnvBlock = (char *)apr_pcalloc(p, iEnvBlockLen);
1570 pEnvVar = pEnvBlock;
1572 while (_environ[i]) {
1573 strcpy(pEnvVar, _environ[i]);
1574 pEnvVar = strchr(pEnvVar, '\0') + 1;
1579 /* Give the read end of the pipe (hPipeRead) to the child as stdin. The
1580 * parent will write the socket data to the child on this pipe.
1582 memset(&si, 0, sizeof(si));
1583 memset(&pi, 0, sizeof(pi));
1585 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
1586 si.wShowWindow = SW_HIDE;
1587 si.hStdInput = hPipeRead;
1588 si.hStdOutput = hNullOutput;
1589 si.hStdError = hShareError;
1591 rv = CreateProcess(NULL, pCommand, NULL, NULL,
1592 TRUE, /* Inherit handles */
1593 0, /* Creation flags */
1594 pEnvBlock, /* Environment block */
1598 /* Undo everything created for the child alone
1600 CloseHandle(pi.hThread);
1601 CloseHandle(hPipeRead);
1602 CloseHandle(hNullOutput);
1603 if (GetStdHandle(STD_ERROR_HANDLE) != hShareError) {
1604 /* Handles opened with GetStdHandle are psuedo handles
1605 * and should not be closed else bad things will happen.
1607 CloseHandle(hShareError);
1609 _putenv("AP_PARENT_PID=");
1610 _putenv("AP_MY_GENERATION=");
1613 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1614 "Parent: Failed to create the child process.");
1615 CloseHandle(hExitEvent);
1616 CloseHandle(hPipeWrite);
1617 CloseHandle(pi.hProcess);
1621 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
1622 "Parent: Created child process %d", pi.dwProcessId);
1624 if (send_handles_to_child(p, hExitEvent, pi.hProcess, hPipeWrite)) {
1626 * This error is fatal, mop up the child and move on
1627 * We toggle the child's exit event to cause this child
1628 * to quit even as it is attempting to start.
1630 SetEvent(hExitEvent);
1631 CloseHandle(hExitEvent);
1632 CloseHandle(hPipeWrite);
1633 CloseHandle(pi.hProcess);
1638 * Give the child process a chance to run before dup'ing the sockets.
1639 * We have already set the listening sockets noninheritable, but if
1640 * WSADuplicateSocket runs before the child process initializes
1641 * the listeners will be inherited anyway.
1643 * XXX: This is badness; needs some mutex interlocking
1647 if (send_listeners_to_child(p, pi.dwProcessId, hPipeWrite)) {
1649 * This error is fatal, mop up the child and move on
1650 * We toggle the child's exit event to cause this child
1651 * to quit even as it is attempting to start.
1653 SetEvent(hExitEvent);
1654 CloseHandle(hExitEvent);
1655 CloseHandle(hPipeWrite);
1656 CloseHandle(pi.hProcess);
1660 CloseHandle(hPipeWrite);
1662 *child_proc = pi.hProcess;
1663 *child_exit_event = hExitEvent;
1668 /***********************************************************************
1670 * master_main() runs in the parent process. It creates the child
1671 * process which handles HTTP requests then waits on one of three
1676 * The restart event causes master_main to start a new child process and
1677 * tells the old child process to exit (by setting the child_exit_event).
1678 * The restart event is set as a result of one of the following:
1679 * 1. An apache -k restart command on the command line
1680 * 2. A command received from Windows service manager which gets
1681 * translated into an ap_signal_parent(SIGNAL_PARENT_RESTART)
1682 * call by code in service.c.
1683 * 3. The child process calling ap_signal_parent(SIGNAL_PARENT_RESTART)
1684 * as a result of hitting MaxRequestsPerChild.
1688 * The shutdown event causes master_main to tell the child process to
1689 * exit and that the server is shutting down. The shutdown event is
1690 * set as a result of one of the following:
1691 * 1. An apache -k shutdown command on the command line
1692 * 2. A command received from Windows service manager which gets
1693 * translated into an ap_signal_parent(SIGNAL_PARENT_SHUTDOWN)
1694 * call by code in service.c.
1696 * child process handle
1697 * --------------------
1698 * The child process handle will be signaled if the child process
1699 * exits for any reason. In a normal running server, the signaling
1700 * of this event means that the child process has exited prematurely
1701 * due to a seg fault or other irrecoverable error. For server
1702 * robustness, master_main will restart the child process under this
1705 * master_main uses the child_exit_event to signal the child process
1707 **********************************************************************/
1708 #define NUM_WAIT_HANDLES 3
1709 #define CHILD_HANDLE 0
1710 #define SHUTDOWN_HANDLE 1
1711 #define RESTART_HANDLE 2
1712 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
1715 int restart_pending;
1716 int shutdown_pending;
1717 HANDLE child_exit_event;
1718 HANDLE event_handles[NUM_WAIT_HANDLES];
1720 restart_pending = shutdown_pending = 0;
1722 event_handles[SHUTDOWN_HANDLE] = shutdown_event;
1723 event_handles[RESTART_HANDLE] = restart_event;
1725 /* Create a single child process */
1726 rv = create_process(pconf, &event_handles[CHILD_HANDLE],
1730 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1731 "master_main: create child process failed. Exiting.");
1732 shutdown_pending = 1;
1736 if (!strcasecmp(signal_arg, "runservice")) {
1737 mpm_service_started();
1740 /* Wait for shutdown or restart events or for child death */
1741 rv = WaitForMultipleObjects(NUM_WAIT_HANDLES, (HANDLE *) event_handles, FALSE, INFINITE);
1742 cld = rv - WAIT_OBJECT_0;
1743 if (rv == WAIT_FAILED) {
1744 /* Something serious is wrong */
1745 ap_log_error(APLOG_MARK,APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1746 "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
1747 shutdown_pending = 1;
1749 else if (rv == WAIT_TIMEOUT) {
1750 /* Hey, this cannot happen */
1751 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1752 "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
1753 shutdown_pending = 1;
1755 else if (cld == SHUTDOWN_HANDLE) {
1756 /* shutdown_event signalled */
1757 shutdown_pending = 1;
1758 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, s,
1759 "Parent: Received shutdown signal -- Shutting down the server.");
1760 if (ResetEvent(shutdown_event) == 0) {
1761 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1762 "ResetEvent(shutdown_event)");
1766 else if (cld == RESTART_HANDLE) {
1767 /* Received a restart event. Prepare the restart_event to be reused
1768 * then signal the child process to exit.
1770 restart_pending = 1;
1771 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, s,
1772 "Parent: Received restart signal -- Restarting the server.");
1773 if (ResetEvent(restart_event) == 0) {
1774 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1775 "Parent: ResetEvent(restart_event) failed.");
1777 if (SetEvent(child_exit_event) == 0) {
1778 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
1779 "Parent: SetEvent for child process %d failed.",
1780 event_handles[CHILD_HANDLE]);
1782 /* Don't wait to verify that the child process really exits,
1783 * just move on with the restart.
1785 CloseHandle(event_handles[CHILD_HANDLE]);
1786 event_handles[CHILD_HANDLE] = NULL;
1790 /* The child process exited prematurely due to a fatal error. */
1792 if (!GetExitCodeProcess(event_handles[CHILD_HANDLE], &exitcode)) {
1793 /* HUH? We did exit, didn't we? */
1794 exitcode = APEXIT_CHILDFATAL;
1796 if ( exitcode == APEXIT_CHILDFATAL
1797 || exitcode == APEXIT_CHILDINIT
1798 || exitcode == APEXIT_INIT) {
1799 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, ap_server_conf,
1800 "Parent: child process exited with status %u -- Aborting.", exitcode);
1803 restart_pending = 1;
1804 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS, ap_server_conf,
1805 "Parent: child process exited with status %u -- Restarting.", exitcode);
1807 CloseHandle(event_handles[CHILD_HANDLE]);
1808 event_handles[CHILD_HANDLE] = NULL;
1813 if (shutdown_pending)
1815 int timeout = 30000; /* Timeout is milliseconds */
1817 /* This shutdown is only marginally graceful. We will give the
1818 * child a bit of time to exit gracefully. If the time expires,
1819 * the child will be wacked.
1821 if (strcasecmp(signal_arg, "runservice")) {
1822 mpm_service_stopping();
1824 /* Signal the child processes to exit */
1825 if (SetEvent(child_exit_event) == 0) {
1826 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), ap_server_conf,
1827 "Parent: SetEvent for child process %d failed", event_handles[CHILD_HANDLE]);
1829 if (event_handles[CHILD_HANDLE]) {
1830 rv = WaitForSingleObject(event_handles[CHILD_HANDLE], timeout);
1831 if (rv == WAIT_OBJECT_0) {
1832 ap_log_error(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO, APR_SUCCESS, ap_server_conf,
1833 "Parent: Child process %d exited successfully.", event_handles[CHILD_HANDLE]);
1834 CloseHandle(event_handles[CHILD_HANDLE]);
1835 event_handles[CHILD_HANDLE] = NULL;
1838 ap_log_error(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO, APR_SUCCESS, ap_server_conf,
1839 "Parent: Forcing termination of child process %d ", event_handles[CHILD_HANDLE]);
1840 TerminateProcess(event_handles[CHILD_HANDLE], 1);
1841 CloseHandle(event_handles[CHILD_HANDLE]);
1842 event_handles[CHILD_HANDLE] = NULL;
1845 return 0; /* Tell the caller we do not want to restart */
1848 return 1; /* Tell the caller we want a restart */
1851 /* service_nt_main_fn needs to append the StartService() args
1852 * outside of our call stack and thread as the service starts...
1854 apr_array_header_t *mpm_new_argv;
1856 /* Remember service_to_start failures to log and fail in pre_config.
1857 * Remember inst_argc and inst_argv for installing or starting the
1858 * service after we preflight the config.
1861 AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
1864 case AP_MPMQ_MAX_DAEMON_USED:
1865 *result = MAXIMUM_WAIT_OBJECTS;
1867 case AP_MPMQ_IS_THREADED:
1868 *result = AP_MPMQ_STATIC;
1870 case AP_MPMQ_IS_FORKED:
1871 *result = AP_MPMQ_NOT_SUPPORTED;
1873 case AP_MPMQ_HARD_LIMIT_DAEMONS:
1874 *result = HARD_SERVER_LIMIT;
1876 case AP_MPMQ_HARD_LIMIT_THREADS:
1877 *result = HARD_THREAD_LIMIT;
1879 case AP_MPMQ_MAX_THREADS:
1880 *result = ap_threads_per_child;
1882 case AP_MPMQ_MIN_SPARE_DAEMONS:
1885 case AP_MPMQ_MIN_SPARE_THREADS:
1888 case AP_MPMQ_MAX_SPARE_DAEMONS:
1891 case AP_MPMQ_MAX_SPARE_THREADS:
1894 case AP_MPMQ_MAX_REQUESTS_DAEMON:
1895 *result = ap_max_requests_per_child;
1897 case AP_MPMQ_MAX_DAEMONS:
1901 return APR_ENOTIMPL;
1904 #define SERVICE_UNSET (-1)
1905 static apr_status_t service_set = SERVICE_UNSET;
1906 static apr_status_t service_to_start_success;
1907 static int inst_argc;
1908 static const char * const *inst_argv;
1909 static char *service_name = NULL;
1911 void winnt_rewrite_args(process_rec *process)
1913 /* Handle the following SCM aspects in this phase:
1915 * -k runservice [transition for WinNT, nothing for Win9x]
1916 * -k (!)install [error out if name is not installed]
1918 * We can't leave this phase until we know our identity
1919 * and modify the command arguments appropriately.
1922 char *def_server_root;
1923 char fnbuf[MAX_PATH];
1929 int running_as_service = 1;
1931 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1932 GetVersionEx(&osver);
1934 /* AP_PARENT_PID is only valid in the child */
1935 pid = getenv("AP_PARENT_PID");
1938 /* This is the child */
1939 my_pid = GetCurrentProcessId();
1940 parent_pid = (DWORD) atol(pid);
1942 /* The parent is responsible for providing the
1943 * COMPLETE ARGUMENTS REQUIRED to the child.
1945 * No further argument parsing is needed, but
1946 * for good measure we will provide a simple
1947 * signal string for later testing.
1949 signal_arg = "runchild";
1953 /* This is the parent, we have a long way to go :-) */
1954 parent_pid = my_pid = GetCurrentProcessId();
1956 /* Rewrite process->argv[];
1958 * strip out -k signal into signal_arg
1959 * strip out -n servicename and set the names
1960 * add default -d serverroot from the path of this executable
1962 * The end result will look like:
1964 * The invocation command (%0)
1965 * The -d serverroot default from the running executable
1966 * The requested service's (-n) registry ConfigArgs
1967 * The WinNT SCM's StartService() args
1969 if (!GetModuleFileName(NULL, fnbuf, sizeof(fnbuf))) {
1970 rv = apr_get_os_error();
1971 ap_log_error(APLOG_MARK,APLOG_CRIT, rv, NULL,
1972 "Failed to get the path of Apache.exe");
1975 /* WARNING: There is an implict assumption here that the
1976 * executable resides in ServerRoot or ServerRoot\bin
1978 def_server_root = (char *) apr_filename_of_pathname(fnbuf);
1979 if (def_server_root > fnbuf) {
1980 *(def_server_root - 1) = '\0';
1981 def_server_root = (char *) apr_filename_of_pathname(fnbuf);
1982 if (!strcasecmp(def_server_root, "bin"))
1983 *(def_server_root - 1) = '\0';
1985 apr_filepath_merge(&def_server_root, NULL, fnbuf,
1986 APR_FILEPATH_TRUENAME, process->pool);
1988 /* Use process->pool so that the rewritten argv
1989 * lasts for the lifetime of the server process,
1990 * because pconf will be destroyed after the
1991 * initial pre-flight of the config parser.
1993 mpm_new_argv = apr_array_make(process->pool, process->argc + 2,
1994 sizeof(const char *));
1995 *(const char **)apr_array_push(mpm_new_argv) = process->argv[0];
1996 *(const char **)apr_array_push(mpm_new_argv) = "-d";
1997 *(const char **)apr_array_push(mpm_new_argv) = def_server_root;
1999 fixed_args = mpm_new_argv->nelts;
2003 apr_getopt_init(&opt, process->pool, process->argc, (char**) process->argv);
2005 while ((rv = apr_getopt(opt, "n:k:iu" AP_SERVER_BASEARGS,
2006 optbuf + 1, &optarg)) == APR_SUCCESS) {
2007 switch (optbuf[1]) {
2009 service_set = mpm_service_set_name(process->pool, &service_name,
2013 signal_arg = optarg;
2016 ap_log_error(APLOG_MARK,APLOG_WARNING, 0, NULL,
2017 "-i is deprecated. Use -k install.");
2018 signal_arg = "install";
2021 ap_log_error(APLOG_MARK,APLOG_WARNING, 0, NULL,
2022 "-u is deprecated. Use -k uninstall.");
2023 signal_arg = "uninstall";
2026 *(const char **)apr_array_push(mpm_new_argv) =
2027 apr_pstrdup(process->pool, optbuf);
2030 *(const char **)apr_array_push(mpm_new_argv) = optarg;
2036 /* back up to capture the bad argument */
2037 if (rv == APR_BADCH || rv == APR_BADARG) {
2041 while (opt->ind < opt->argc) {
2042 *(const char **)apr_array_push(mpm_new_argv) =
2043 apr_pstrdup(process->pool, opt->argv[opt->ind++]);
2046 /* Track the number of args actually entered by the user */
2047 inst_argc = mpm_new_argv->nelts - fixed_args;
2049 /* Provide a default 'run' -k arg to simplify signal_arg tests */
2053 running_as_service = 0;
2056 if (!strcasecmp(signal_arg, "runservice"))
2058 /* Start the NT Service _NOW_ because the WinNT SCM is
2059 * expecting us to rapidly assume control of our own
2060 * process, the SCM will tell us our service name, and
2061 * may have extra StartService() command arguments to
2064 * Any other process has a console, so we don't to begin
2065 * a Win9x service until the configuration is parsed and
2066 * any command line errors are reported.
2068 * We hold the return value so that we can die in pre_config
2069 * after logging begins, and the failure can land in the log.
2071 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) {
2072 service_to_start_success = mpm_service_to_start(&service_name,
2074 if (service_to_start_success == APR_SUCCESS) {
2075 service_set = APR_SUCCESS;
2080 /* Get the default for any -k option, except run */
2081 if (service_set == SERVICE_UNSET && strcasecmp(signal_arg, "run")) {
2082 service_set = mpm_service_set_name(process->pool, &service_name,
2083 AP_DEFAULT_SERVICE_NAME);
2086 if (!strcasecmp(signal_arg, "install")) /* -k install */
2088 if (service_set == APR_SUCCESS)
2090 ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
2091 "%s: Service is already installed.", service_name);
2095 else if (running_as_service)
2097 if (service_set == APR_SUCCESS)
2099 rv = mpm_merge_service_args(process->pool, mpm_new_argv,
2101 if (rv == APR_SUCCESS) {
2102 ap_log_error(APLOG_MARK,APLOG_NOERRNO|APLOG_INFO, 0, NULL,
2103 "Using ConfigArgs of the installed service "
2104 "\"%s\".", service_name);
2107 ap_log_error(APLOG_MARK,APLOG_WARNING, rv, NULL,
2108 "No installed ConfigArgs for the service "
2109 "\"%s\", using Apache defaults.", service_name);
2114 ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL,
2115 "No installed service named \"%s\".", service_name);
2119 if (strcasecmp(signal_arg, "install") && service_set && service_set != SERVICE_UNSET)
2121 ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL,
2122 "No installed service named \"%s\".", service_name);
2126 /* Track the args actually entered by the user.
2127 * These will be used for the -k install parameters, as well as
2128 * for the -k start service override arguments.
2130 inst_argv = (const char * const *)mpm_new_argv->elts
2131 + mpm_new_argv->nelts - inst_argc;
2133 process->argc = mpm_new_argv->nelts;
2134 process->argv = (const char * const *) mpm_new_argv->elts;
2138 static int winnt_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
2140 /* Handle the following SCM aspects in this phase:
2142 * -k runservice [WinNT errors logged from rewrite_args]
2145 * -k shutdown (same as -k stop). Maintained for backward compatability.
2147 * in these cases we -don't- care if httpd.conf has config errors!
2151 if (ap_exists_config_define("ONE_PROCESS") ||
2152 ap_exists_config_define("DEBUG"))
2155 if (!strcasecmp(signal_arg, "runservice")
2156 && (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
2157 && (service_to_start_success != APR_SUCCESS)) {
2158 ap_log_error(APLOG_MARK,APLOG_CRIT, service_to_start_success, NULL,
2159 "%s: Unable to start the service manager.",
2164 if (!strcasecmp(signal_arg, "uninstall")) {
2165 rv = mpm_service_uninstall();
2169 if ((!strcasecmp(signal_arg, "stop")) ||
2170 (!strcasecmp(signal_arg, "shutdown"))) {
2171 mpm_signal_service(ptemp, 0);
2175 ap_listen_pre_config();
2176 ap_threads_per_child = DEFAULT_START_THREAD;
2177 ap_pid_fname = DEFAULT_PIDLOG;
2178 ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
2180 apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
2185 static int winnt_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec* server)
2187 static int restart_num = 0;
2188 apr_status_t rv = 0;
2190 ap_server_conf = server;
2192 /* Handle the following SCM aspects in this phase:
2197 * -k runservice [Win95, only once - after we parsed the config]
2199 * because all of these signals are useful _only_ if there
2200 * is a valid conf\httpd.conf environment to start.
2202 * We reached this phase by avoiding errors that would cause
2203 * these options to fail unexpectedly in another process.
2206 if (!strcasecmp(signal_arg, "install")) {
2207 rv = mpm_service_install(ptemp, inst_argc, inst_argv);
2211 if (!strcasecmp(signal_arg, "start")) {
2214 /* Close the listening sockets. */
2215 for (lr = ap_listeners; lr; lr = lr->next) {
2216 apr_socket_close(lr->sd);
2219 rv = mpm_service_start(ptemp, inst_argc, inst_argv);
2223 if (!strcasecmp(signal_arg, "restart")) {
2224 mpm_signal_service(ptemp, 1);
2228 if (parent_pid == my_pid)
2230 if (restart_num++ == 1)
2232 /* This code should be run once in the parent and not run
2235 PSECURITY_ATTRIBUTES sa = GetNullACL(); /* returns NULL if invalid (Win95?) */
2236 setup_signal_names(apr_psprintf(pconf,"ap%d", parent_pid));
2238 ap_log_pid(pconf, ap_pid_fname);
2240 /* Create shutdown event, apPID_shutdown, where PID is the parent
2241 * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
2243 shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
2244 if (!shutdown_event) {
2245 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
2246 "Parent: Cannot create shutdown event %s", signal_shutdown_name);
2247 CleanNullACL((void *)sa);
2248 return HTTP_INTERNAL_SERVER_ERROR;
2251 /* Create restart event, apPID_restart, where PID is the parent
2252 * Apache process ID. Restart is signaled by 'apache -k restart'.
2254 restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
2255 if (!restart_event) {
2256 CloseHandle(shutdown_event);
2257 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
2258 "Parent: Cannot create restart event %s", signal_restart_name);
2259 CleanNullACL((void *)sa);
2260 return HTTP_INTERNAL_SERVER_ERROR;
2262 CleanNullACL((void *)sa);
2264 /* Now that we are flying at 15000 feet...
2265 * wipe out the Win95 service console,
2266 * signal the SCM the WinNT service started, or
2267 * if not a service, setup console handlers instead.
2269 if (!strcasecmp(signal_arg, "runservice"))
2271 if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT)
2273 rv = mpm_service_to_start(&service_name,
2274 server->process->pool);
2275 if (rv != APR_SUCCESS) {
2276 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
2277 "%s: Unable to start the service manager.",
2279 return HTTP_INTERNAL_SERVER_ERROR;
2283 else /* ! -k runservice */
2285 mpm_start_console_handler();
2288 /* Create the start mutex, apPID, where PID is the parent Apache process ID.
2289 * Ths start mutex is used during a restart to prevent more than one
2290 * child process from entering the accept loop at once.
2292 rv = apr_proc_mutex_create(&start_mutex,
2295 ap_server_conf->process->pool);
2296 if (rv != APR_SUCCESS) {
2297 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
2298 "%s: Unable to create the start_mutex.",
2300 return HTTP_INTERNAL_SERVER_ERROR;
2304 else /* parent_pid != my_pid */
2306 mpm_start_child_console_handler();
2311 /* This really should be a post_config hook, but the error log is already
2312 * redirected by that point, so we need to do this in the open_logs phase.
2314 static int winnt_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
2319 if (parent_pid != my_pid) {
2323 /* We cannot initialize our listeners if we are restarting
2324 * (the parent process already has glomed on to them)
2325 * nor should we do so for service reconfiguration
2326 * (since the service may already be running.)
2328 if (!strcasecmp(signal_arg, "restart")
2329 || !strcasecmp(signal_arg, "config")) {
2333 if (ap_setup_listeners(ap_server_conf) < 1) {
2334 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT|APLOG_STARTUP, 0,
2335 NULL, "no listening sockets available, shutting down");
2339 if (!set_listeners_noninheritable(pconf)) {
2346 static void winnt_child_init(apr_pool_t *pchild, struct server_rec *ap_server_conf)
2350 setup_signal_names(apr_psprintf(pchild,"ap%d", parent_pid));
2352 /* This is a child process, not in single process mode */
2354 /* Set up events and the scoreboard */
2355 get_handles_from_parent(ap_server_conf);
2357 /* Set up the listeners */
2358 get_listeners_from_parent(ap_server_conf);
2360 ap_my_generation = atoi(getenv("AP_MY_GENERATION"));
2362 rv = apr_proc_mutex_child_init(&start_mutex, signal_name_prefix, pconf);
2365 /* Single process mode - this lock doesn't even need to exist */
2366 rv = apr_proc_mutex_create(&start_mutex, signal_name_prefix,
2367 APR_LOCK_DEFAULT, pconf);
2369 /* Borrow the shutdown_even as our _child_ loop exit event */
2370 exit_event = shutdown_event;
2372 if (rv != APR_SUCCESS) {
2373 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
2374 "%s child %d: Unable to init the start_mutex.",
2375 service_name, my_pid);
2376 exit(APEXIT_CHILDINIT);
2381 AP_DECLARE(int) ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s )
2383 static int restart = 0; /* Default is "not a restart" */
2385 /* ### If non-graceful restarts are ever introduced - we need to rerun
2386 * the pre_mpm hook on subsequent non-graceful restarts. But Win32
2387 * has only graceful style restarts - and we need this hook to act
2388 * the same on Win32 as on Unix.
2390 if (!restart && ((parent_pid == my_pid) || one_process)) {
2391 /* Set up the scoreboard. */
2392 if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
2397 if ((parent_pid != my_pid) || one_process)
2399 /* The child process or in one_process (debug) mode
2401 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
2402 "Child %d: Child process is running", my_pid);
2406 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
2407 "Child %d: Child process is exiting", my_pid);
2412 /* A real-honest to goodness parent */
2414 restart = master_main(ap_server_conf, shutdown_event, restart_event);
2418 /* Shutting down. Clean up... */
2419 const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
2421 if (pidfile != NULL && unlink(pidfile) == 0) {
2422 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, APR_SUCCESS,
2423 ap_server_conf, "removed PID file %s (pid=%ld)",
2424 pidfile, GetCurrentProcessId());
2426 apr_proc_mutex_destroy(start_mutex);
2428 CloseHandle(restart_event);
2429 CloseHandle(shutdown_event);
2435 return 0; /* Restart */
2438 static void winnt_hooks(apr_pool_t *p)
2440 /* The prefork open_logs phase must run before the core's, or stderr
2441 * will be redirected to a file, and the messages won't print to the
2444 static const char *const aszSucc[] = {"core.c", NULL};
2446 ap_hook_pre_config(winnt_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2447 ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
2448 ap_hook_child_init(winnt_child_init, NULL, NULL, APR_HOOK_MIDDLE);
2449 ap_hook_open_logs(winnt_open_logs, NULL, aszSucc, APR_HOOK_MIDDLE);
2452 AP_MODULE_DECLARE_DATA module mpm_winnt_module = {
2454 winnt_rewrite_args, /* hook to run before apache parses args */
2455 NULL, /* create per-directory config structure */
2456 NULL, /* merge per-directory config structures */
2457 NULL, /* create per-server config structure */
2458 NULL, /* merge per-server config structures */
2459 winnt_cmds, /* command apr_table_t */
2460 winnt_hooks /* register_hooks */