1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
20 #include "http_main.h"
22 #include "http_config.h" /* for read_config */
23 #include "http_core.h" /* for get_remote_host */
24 #include "http_connection.h"
25 #include "apr_portable.h"
26 #include "apr_thread_proc.h"
27 #include "apr_getopt.h"
28 #include "apr_strings.h"
31 #include "apr_thread_mutex.h"
33 #include "apr_general.h"
34 #include "ap_config.h"
35 #include "ap_listen.h"
36 #include "mpm_default.h"
37 #include "mpm_winnt.h"
38 #include "mpm_common.h"
40 #include "apr_atomic.h"
41 #include "scoreboard.h"
44 #define _environ environ
47 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION /* missing on MinGW */
48 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
51 /* Because ap_setup_listeners() is skipped in the child, any merging
52 * of [::]:80 and 0.0.0.0:80 for AP_ENABLE_V4_MAPPED in the parent
53 * won't have taken place in the child, so the child will expect to
54 * read two sockets for "Listen 80" but the parent will send only
57 #ifdef AP_ENABLE_V4_MAPPED
58 #error The WinNT MPM does not currently support AP_ENABLE_V4_MAPPED
61 /* scoreboard.c does the heavy lifting; all we do is create the child
62 * score by moving a handle down the pipe into the child's stdin.
64 extern apr_shm_t *ap_scoreboard_shm;
66 /* my_generation is returned to the scoreboard code */
67 static volatile ap_generation_t my_generation=0;
69 /* Definitions of WINNT MPM specific config globals */
70 static HANDLE shutdown_event; /* used to signal the parent to shutdown */
71 static HANDLE restart_event; /* used to signal the parent to restart */
73 static int one_process = 0;
74 static char const* signal_arg = NULL;
76 OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
78 /* set by child_main to STACK_SIZE_PARAM_IS_A_RESERVATION for NT >= 5.1 (XP/2003) */
81 static DWORD parent_pid;
84 /* used by parent to signal the child to start and exit */
85 apr_proc_mutex_t *start_mutex;
88 int ap_threads_per_child = 0;
89 static int thread_limit = 0;
90 static int first_thread_limit = 0;
91 int winnt_mpm_state = AP_MPMQ_STARTING;
93 /* shared by service.c as global, although
94 * perhaps it should be private.
98 /* definitions from child.c */
99 void child_main(apr_pool_t *pconf);
101 /* Only one of these, the pipe from our parent, meant only for
102 * one child worker's consumption (not to be inherited!)
103 * XXX: decorate this name for the trunk branch, was left simplified
104 * only to make the 2.2 patch trivial to read.
112 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, const char *arg)
114 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
119 ap_threads_per_child = atoi(arg);
122 static const char *set_thread_limit (cmd_parms *cmd, void *dummy, const char *arg)
124 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
129 thread_limit = atoi(arg);
133 static const command_rec winnt_cmds[] = {
135 AP_INIT_TAKE1("ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF,
136 "Number of threads each child creates" ),
137 AP_INIT_TAKE1("ThreadLimit", set_thread_limit, NULL, RSRC_CONF,
138 "Maximum worker threads in a server for this run of Apache"),
142 static void winnt_note_child_started(int slot, pid_t pid)
144 ap_scoreboard_image->parent[slot].pid = pid;
145 ap_run_child_status(ap_server_conf,
146 ap_scoreboard_image->parent[slot].pid,
147 my_generation, slot, MPM_CHILD_STARTED);
150 static void winnt_note_child_killed(int slot)
152 ap_run_child_status(ap_server_conf,
153 ap_scoreboard_image->parent[slot].pid,
154 ap_scoreboard_image->parent[slot].generation,
155 slot, MPM_CHILD_EXITED);
156 ap_scoreboard_image->parent[slot].pid = 0;
160 * Signalling Apache on NT.
162 * Under Unix, Apache can be told to shutdown or restart by sending various
163 * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
164 * we use "events" instead. The parent apache process goes into a loop
165 * where it waits forever for a set of events. Two of those events are
171 * (where PID is the PID of the apache parent process). When one of these
172 * is signalled, the Apache parent performs the appropriate action. The events
173 * can become signalled through internal Apache methods (e.g. if the child
174 * finds a fatal error and needs to kill its parent), via the service
175 * control manager (the control thread will signal the shutdown event when
176 * requested to stop the Apache service), from the -k Apache command line,
177 * or from any external program which finds the Apache PID from the
180 * The signal_parent() function, below, is used to signal one of these events.
181 * It can be called by any child or parent process, since it does not
182 * rely on global variables.
184 * On entry, type gives the event to signal. 0 means shutdown, 1 means
188 * Initialise the signal names, in the global variables signal_name_prefix,
189 * signal_restart_name and signal_shutdown_name.
191 #define MAX_SIGNAL_NAME 30 /* Long enough for apPID_shutdown, where PID is an int */
192 char signal_name_prefix[MAX_SIGNAL_NAME];
193 char signal_restart_name[MAX_SIGNAL_NAME];
194 char signal_shutdown_name[MAX_SIGNAL_NAME];
195 void setup_signal_names(char *prefix)
197 apr_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);
198 apr_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name),
199 "%s_shutdown", signal_name_prefix);
200 apr_snprintf(signal_restart_name, sizeof(signal_restart_name),
201 "%s_restart", signal_name_prefix);
204 AP_DECLARE(void) ap_signal_parent(ap_signal_parent_e type)
209 if (parent_pid == my_pid) {
211 case SIGNAL_PARENT_SHUTDOWN:
213 SetEvent(shutdown_event);
216 /* This MPM supports only graceful restarts right now */
217 case SIGNAL_PARENT_RESTART:
218 case SIGNAL_PARENT_RESTART_GRACEFUL:
220 SetEvent(restart_event);
228 case SIGNAL_PARENT_SHUTDOWN:
230 signal_name = signal_shutdown_name;
233 /* This MPM supports only graceful restarts right now */
234 case SIGNAL_PARENT_RESTART:
235 case SIGNAL_PARENT_RESTART_GRACEFUL:
237 signal_name = signal_restart_name;
244 e = OpenEvent(EVENT_MODIFY_STATE, FALSE, signal_name);
246 /* Um, problem, can't signal the parent, which means we can't
247 * signal ourselves to die. Ignore for now...
249 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf,
250 "OpenEvent on %s event", signal_name);
253 if (SetEvent(e) == 0) {
254 /* Same problem as above */
255 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf,
256 "SetEvent on %s event", signal_name);
265 * Passed the following handles [in sync with send_handles_to_child()]
267 * ready event [signal the parent immediately, then close]
268 * exit event [save to poll later]
269 * start mutex [signal from the parent to begin accept()]
270 * scoreboard shm handle [to recreate the ap_scoreboard]
272 static void get_handles_from_parent(server_rec *s, HANDLE *child_exit_event,
273 apr_proc_mutex_t **child_start_mutex,
274 apr_shm_t **scoreboard_shm)
283 /* *** We now do this was back in winnt_rewrite_args
284 * pipe = GetStdHandle(STD_INPUT_HANDLE);
286 if (!ReadFile(pipe, &ready_event, sizeof(HANDLE),
287 &BytesRead, (LPOVERLAPPED) NULL)
288 || (BytesRead != sizeof(HANDLE))) {
289 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
290 "Child: Unable to retrieve the ready event from the parent");
291 exit(APEXIT_CHILDINIT);
294 SetEvent(ready_event);
295 CloseHandle(ready_event);
297 if (!ReadFile(pipe, child_exit_event, sizeof(HANDLE),
298 &BytesRead, (LPOVERLAPPED) NULL)
299 || (BytesRead != sizeof(HANDLE))) {
300 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
301 "Child: Unable to retrieve the exit event from the parent");
302 exit(APEXIT_CHILDINIT);
305 if (!ReadFile(pipe, &os_start, sizeof(os_start),
306 &BytesRead, (LPOVERLAPPED) NULL)
307 || (BytesRead != sizeof(os_start))) {
308 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
309 "Child: Unable to retrieve the start_mutex from the parent");
310 exit(APEXIT_CHILDINIT);
312 *child_start_mutex = NULL;
313 if ((rv = apr_os_proc_mutex_put(child_start_mutex, &os_start, s->process->pool))
315 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
316 "Child: Unable to access the start_mutex from the parent");
317 exit(APEXIT_CHILDINIT);
320 if (!ReadFile(pipe, &hScore, sizeof(hScore),
321 &BytesRead, (LPOVERLAPPED) NULL)
322 || (BytesRead != sizeof(hScore))) {
323 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
324 "Child: Unable to retrieve the scoreboard from the parent");
325 exit(APEXIT_CHILDINIT);
327 *scoreboard_shm = NULL;
328 if ((rv = apr_os_shm_put(scoreboard_shm, &hScore, s->process->pool))
330 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
331 "Child: Unable to access the scoreboard from the parent");
332 exit(APEXIT_CHILDINIT);
335 rv = ap_reopen_scoreboard(s->process->pool, scoreboard_shm, 1);
336 if (rv || !(sb_shared = apr_shm_baseaddr_get(*scoreboard_shm))) {
337 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
338 "Child: Unable to reopen the scoreboard from the parent");
339 exit(APEXIT_CHILDINIT);
341 /* We must 'initialize' the scoreboard to relink all the
342 * process-local pointer arrays into the shared memory block.
344 ap_init_scoreboard(sb_shared);
346 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
347 "Child: Retrieved our scoreboard from the parent.");
351 static int send_handles_to_child(apr_pool_t *p,
352 HANDLE child_ready_event,
353 HANDLE child_exit_event,
354 apr_proc_mutex_t *child_start_mutex,
355 apr_shm_t *scoreboard_shm,
357 apr_file_t *child_in)
360 HANDLE hCurrentProcess = GetCurrentProcess();
364 apr_size_t BytesWritten;
366 if (!DuplicateHandle(hCurrentProcess, child_ready_event, hProcess, &hDup,
367 EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, 0)) {
368 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
369 "Parent: Unable to duplicate the ready event handle for the child");
372 if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
374 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
375 "Parent: Unable to send the exit event handle to the child");
378 if (!DuplicateHandle(hCurrentProcess, child_exit_event, hProcess, &hDup,
379 EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, 0)) {
380 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
381 "Parent: Unable to duplicate the exit event handle for the child");
384 if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
386 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
387 "Parent: Unable to send the exit event handle to the child");
390 if ((rv = apr_os_proc_mutex_get(&os_start, child_start_mutex)) != APR_SUCCESS) {
391 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
392 "Parent: Unable to retrieve the start mutex for the child");
395 if (!DuplicateHandle(hCurrentProcess, os_start, hProcess, &hDup,
396 SYNCHRONIZE, FALSE, 0)) {
397 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
398 "Parent: Unable to duplicate the start mutex to the child");
401 if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
403 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
404 "Parent: Unable to send the start mutex to the child");
407 if ((rv = apr_os_shm_get(&hScore, scoreboard_shm)) != APR_SUCCESS) {
408 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
409 "Parent: Unable to retrieve the scoreboard handle for the child");
412 if (!DuplicateHandle(hCurrentProcess, hScore, hProcess, &hDup,
413 FILE_MAP_READ | FILE_MAP_WRITE, FALSE, 0)) {
414 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
415 "Parent: Unable to duplicate the scoreboard handle to the child");
418 if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
420 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
421 "Parent: Unable to send the scoreboard handle to the child");
425 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
426 "Parent: Sent the scoreboard to the child");
432 * get_listeners_from_parent()
433 * The listen sockets are opened in the parent. This function, which runs
434 * exclusively in the child process, receives them from the parent and
435 * makes them availeble in the child.
437 static void get_listeners_from_parent(server_rec *s)
439 WSAPROTOCOL_INFO WSAProtocolInfo;
445 /* Set up a default listener if necessary */
446 if (ap_listeners == NULL) {
448 lr = apr_palloc(s->process->pool, sizeof(ap_listen_rec));
450 lr->next = ap_listeners;
454 /* Open the pipe to the parent process to receive the inherited socket
455 * data. The sockets have been set to listening in the parent process.
457 * *** We now do this was back in winnt_rewrite_args
458 * pipe = GetStdHandle(STD_INPUT_HANDLE);
460 for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) {
461 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
462 "Child: Waiting for data for listening socket %pI",
464 if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
465 &BytesRead, (LPOVERLAPPED) NULL)) {
466 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
467 "Child: Unable to read socket data from parent");
468 exit(APEXIT_CHILDINIT);
471 nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
472 &WSAProtocolInfo, 0, 0);
473 if (nsd == INVALID_SOCKET) {
474 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf,
475 "Child: WSASocket failed to open the inherited socket");
476 exit(APEXIT_CHILDINIT);
479 if (!SetHandleInformation((HANDLE)nsd, HANDLE_FLAG_INHERIT, 0)) {
480 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), ap_server_conf,
481 "Child: SetHandleInformation failed");
483 apr_os_sock_put(&lr->sd, &nsd, s->process->pool);
486 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
487 "Child: retrieved %d listeners from parent", lcnt);
491 static int send_listeners_to_child(apr_pool_t *p, DWORD dwProcessId,
492 apr_file_t *child_in)
497 LPWSAPROTOCOL_INFO lpWSAProtocolInfo;
498 apr_size_t BytesWritten;
500 /* Run the chain of open sockets. For each socket, duplicate it
501 * for the target process then send the WSAPROTOCOL_INFO
502 * (returned by dup socket) to the child.
504 for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) {
506 lpWSAProtocolInfo = apr_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
507 apr_os_sock_get(&nsd, lr->sd);
508 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
509 "Parent: Duplicating socket %d (%pI) and sending it to child process %lu",
510 nsd, lr->bind_addr, dwProcessId);
511 if (WSADuplicateSocket(nsd, dwProcessId,
512 lpWSAProtocolInfo) == SOCKET_ERROR) {
513 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf,
514 "Parent: WSADuplicateSocket failed for socket %d. Check the FAQ.", nsd);
518 if ((rv = apr_file_write_full(child_in, lpWSAProtocolInfo,
519 sizeof(WSAPROTOCOL_INFO), &BytesWritten))
521 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
522 "Parent: Unable to write duplicated socket %d to the child.", nsd);
527 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
528 "Parent: Sent %d listeners to child %lu", lcnt, dwProcessId);
537 static int create_process(apr_pool_t *p, HANDLE *child_proc, HANDLE *child_exit_event,
540 /* These NEVER change for the lifetime of this parent
542 static char **args = NULL;
543 static char pidbuf[28];
547 apr_procattr_t *attr;
548 apr_proc_t new_child;
550 HANDLE waitlist[2]; /* see waitlist_e */
556 apr_pool_create_ex(&ptemp, p, NULL, NULL);
558 /* Build the command line. Should look something like this:
559 * C:/apache/bin/httpd.exe -f ap_server_confname
560 * First, get the path to the executable...
562 apr_procattr_create(&attr, ptemp);
563 apr_procattr_cmdtype_set(attr, APR_PROGRAM);
564 apr_procattr_detach_set(attr, 1);
565 if (((rv = apr_filepath_get(&cwd, 0, ptemp)) != APR_SUCCESS)
566 || ((rv = apr_procattr_dir_set(attr, cwd)) != APR_SUCCESS)) {
567 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
568 "Parent: Failed to get the current path");
572 /* Build the args array, only once since it won't change
573 * for the lifetime of this parent process.
575 if ((rv = ap_os_proc_filepath(&cmd, ptemp))
577 ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, ap_server_conf,
578 "Parent: Failed to get full path of %s",
579 ap_server_conf->process->argv[0]);
580 apr_pool_destroy(ptemp);
584 args = malloc((ap_server_conf->process->argc + 1) * sizeof (char*));
585 memcpy(args + 1, ap_server_conf->process->argv + 1,
586 (ap_server_conf->process->argc - 1) * sizeof (char*));
587 args[0] = malloc(strlen(cmd) + 1);
588 strcpy(args[0], cmd);
589 args[ap_server_conf->process->argc] = NULL;
595 /* Create a pipe to send handles to the child */
596 if ((rv = apr_procattr_io_set(attr, APR_FULL_BLOCK,
597 APR_NO_PIPE, APR_NO_PIPE)) != APR_SUCCESS) {
598 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
599 "Parent: Unable to create child stdin pipe.");
600 apr_pool_destroy(ptemp);
604 /* Create the child_ready_event */
605 waitlist[waitlist_ready] = CreateEvent(NULL, TRUE, FALSE, NULL);
606 if (!waitlist[waitlist_ready]) {
607 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
608 "Parent: Could not create ready event for child process");
609 apr_pool_destroy (ptemp);
613 /* Create the child_exit_event */
614 hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
616 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
617 "Parent: Could not create exit event for child process");
618 apr_pool_destroy(ptemp);
619 CloseHandle(waitlist[waitlist_ready]);
623 /* Build the env array */
624 for (envc = 0; _environ[envc]; ++envc) {
627 env = apr_palloc(ptemp, (envc + 2) * sizeof (char*));
628 memcpy(env, _environ, envc * sizeof (char*));
629 apr_snprintf(pidbuf, sizeof(pidbuf), "AP_PARENT_PID=%lu", parent_pid);
631 env[envc + 1] = NULL;
633 rv = apr_proc_create(&new_child, cmd, (const char * const *)args,
634 (const char * const *)env, attr, ptemp);
635 if (rv != APR_SUCCESS) {
636 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
637 "Parent: Failed to create the child process.");
638 apr_pool_destroy(ptemp);
639 CloseHandle(hExitEvent);
640 CloseHandle(waitlist[waitlist_ready]);
641 CloseHandle(new_child.hproc);
645 ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
646 "Parent: Created child process %d", new_child.pid);
648 if (send_handles_to_child(ptemp, waitlist[waitlist_ready], hExitEvent,
649 start_mutex, ap_scoreboard_shm,
650 new_child.hproc, new_child.in)) {
652 * This error is fatal, mop up the child and move on
653 * We toggle the child's exit event to cause this child
654 * to quit even as it is attempting to start.
656 SetEvent(hExitEvent);
657 apr_pool_destroy(ptemp);
658 CloseHandle(hExitEvent);
659 CloseHandle(waitlist[waitlist_ready]);
660 CloseHandle(new_child.hproc);
665 * Give the child process a chance to run before dup'ing the sockets.
666 * We have already set the listening sockets noninheritable, but if
667 * WSADuplicateSocket runs before the child process initializes
668 * the listeners will be inherited anyway.
670 waitlist[waitlist_term] = new_child.hproc;
671 rv = WaitForMultipleObjects(2, waitlist, FALSE, INFINITE);
672 CloseHandle(waitlist[waitlist_ready]);
673 if (rv != WAIT_OBJECT_0) {
675 * Outch... that isn't a ready signal. It's dead, Jim!
677 SetEvent(hExitEvent);
678 apr_pool_destroy(ptemp);
679 CloseHandle(hExitEvent);
680 CloseHandle(new_child.hproc);
684 if (send_listeners_to_child(ptemp, new_child.pid, new_child.in)) {
686 * This error is fatal, mop up the child and move on
687 * We toggle the child's exit event to cause this child
688 * to quit even as it is attempting to start.
690 SetEvent(hExitEvent);
691 apr_pool_destroy(ptemp);
692 CloseHandle(hExitEvent);
693 CloseHandle(new_child.hproc);
697 apr_file_close(new_child.in);
699 *child_exit_event = hExitEvent;
700 *child_proc = new_child.hproc;
701 *child_pid = new_child.pid;
706 /***********************************************************************
708 * master_main() runs in the parent process. It creates the child
709 * process which handles HTTP requests then waits on one of three
714 * The restart event causes master_main to start a new child process and
715 * tells the old child process to exit (by setting the child_exit_event).
716 * The restart event is set as a result of one of the following:
717 * 1. An apache -k restart command on the command line
718 * 2. A command received from Windows service manager which gets
719 * translated into an ap_signal_parent(SIGNAL_PARENT_RESTART)
720 * call by code in service.c.
721 * 3. The child process calling ap_signal_parent(SIGNAL_PARENT_RESTART)
722 * as a result of hitting MaxConnectionsPerChild.
726 * The shutdown event causes master_main to tell the child process to
727 * exit and that the server is shutting down. The shutdown event is
728 * set as a result of one of the following:
729 * 1. An apache -k shutdown command on the command line
730 * 2. A command received from Windows service manager which gets
731 * translated into an ap_signal_parent(SIGNAL_PARENT_SHUTDOWN)
732 * call by code in service.c.
734 * child process handle
735 * --------------------
736 * The child process handle will be signaled if the child process
737 * exits for any reason. In a normal running server, the signaling
738 * of this event means that the child process has exited prematurely
739 * due to a seg fault or other irrecoverable error. For server
740 * robustness, master_main will restart the child process under this
743 * master_main uses the child_exit_event to signal the child process
745 **********************************************************************/
746 #define NUM_WAIT_HANDLES 3
747 #define CHILD_HANDLE 0
748 #define SHUTDOWN_HANDLE 1
749 #define RESTART_HANDLE 2
750 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
755 int shutdown_pending;
756 HANDLE child_exit_event;
757 HANDLE event_handles[NUM_WAIT_HANDLES];
760 child_created = restart_pending = shutdown_pending = 0;
762 event_handles[SHUTDOWN_HANDLE] = shutdown_event;
763 event_handles[RESTART_HANDLE] = restart_event;
765 /* Create a single child process */
766 rv = create_process(pconf, &event_handles[CHILD_HANDLE],
767 &child_exit_event, &child_pid);
770 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
771 "master_main: create child process failed. Exiting.");
772 shutdown_pending = 1;
778 if (!strcasecmp(signal_arg, "runservice")) {
779 mpm_service_started();
782 /* Update the scoreboard. Note that there is only a single active
785 ap_scoreboard_image->parent[0].quiescing = 0;
786 winnt_note_child_started(/* slot */ 0, child_pid);
788 /* Wait for shutdown or restart events or for child death */
789 winnt_mpm_state = AP_MPMQ_RUNNING;
790 rv = WaitForMultipleObjects(NUM_WAIT_HANDLES, (HANDLE *) event_handles, FALSE, INFINITE);
791 cld = rv - WAIT_OBJECT_0;
792 if (rv == WAIT_FAILED) {
793 /* Something serious is wrong */
794 ap_log_error(APLOG_MARK,APLOG_CRIT, apr_get_os_error(), ap_server_conf,
795 "master_main: WaitForMultipleObjects WAIT_FAILED -- doing server shutdown");
796 shutdown_pending = 1;
798 else if (rv == WAIT_TIMEOUT) {
799 /* Hey, this cannot happen */
800 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
801 "master_main: WaitForMultipleObjects with INFINITE wait exited with WAIT_TIMEOUT");
802 shutdown_pending = 1;
804 else if (cld == SHUTDOWN_HANDLE) {
805 /* shutdown_event signalled */
806 shutdown_pending = 1;
807 ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, s,
808 "Parent: Received shutdown signal -- Shutting down the server.");
809 if (ResetEvent(shutdown_event) == 0) {
810 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
811 "ResetEvent(shutdown_event)");
814 else if (cld == RESTART_HANDLE) {
815 /* Received a restart event. Prepare the restart_event to be reused
816 * then signal the child process to exit.
819 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
820 "Parent: Received restart signal -- Restarting the server.");
821 if (ResetEvent(restart_event) == 0) {
822 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
823 "Parent: ResetEvent(restart_event) failed.");
825 if (SetEvent(child_exit_event) == 0) {
826 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
827 "Parent: SetEvent for child process %pp failed.",
828 event_handles[CHILD_HANDLE]);
830 /* Don't wait to verify that the child process really exits,
831 * just move on with the restart.
833 CloseHandle(event_handles[CHILD_HANDLE]);
834 event_handles[CHILD_HANDLE] = NULL;
837 /* The child process exited prematurely due to a fatal error. */
839 if (!GetExitCodeProcess(event_handles[CHILD_HANDLE], &exitcode)) {
840 /* HUH? We did exit, didn't we? */
841 exitcode = APEXIT_CHILDFATAL;
843 if ( exitcode == APEXIT_CHILDFATAL
844 || exitcode == APEXIT_CHILDINIT
845 || exitcode == APEXIT_INIT) {
846 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, ap_server_conf,
847 "Parent: child process exited with status %lu -- Aborting.", exitcode);
848 shutdown_pending = 1;
853 ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
854 "Parent: child process exited with status %lu -- Restarting.", exitcode);
855 for (i = 0; i < ap_threads_per_child; i++) {
856 ap_update_child_status_from_indexes(0, i, SERVER_DEAD, NULL);
859 CloseHandle(event_handles[CHILD_HANDLE]);
860 event_handles[CHILD_HANDLE] = NULL;
863 winnt_note_child_killed(/* slot */ 0);
865 if (restart_pending) {
867 ap_scoreboard_image->global->running_generation = my_generation;
870 if (shutdown_pending)
872 int timeout = 30000; /* Timeout is milliseconds */
873 winnt_mpm_state = AP_MPMQ_STOPPING;
875 if (!child_created) {
876 return 0; /* Tell the caller we do not want to restart */
879 /* This shutdown is only marginally graceful. We will give the
880 * child a bit of time to exit gracefully. If the time expires,
881 * the child will be wacked.
883 if (!strcasecmp(signal_arg, "runservice")) {
884 mpm_service_stopping();
886 /* Signal the child processes to exit */
887 if (SetEvent(child_exit_event) == 0) {
888 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), ap_server_conf,
889 "Parent: SetEvent for child process %pp failed",
890 event_handles[CHILD_HANDLE]);
892 if (event_handles[CHILD_HANDLE]) {
893 rv = WaitForSingleObject(event_handles[CHILD_HANDLE], timeout);
894 if (rv == WAIT_OBJECT_0) {
895 ap_log_error(APLOG_MARK,APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
896 "Parent: Child process exited successfully.");
897 CloseHandle(event_handles[CHILD_HANDLE]);
898 event_handles[CHILD_HANDLE] = NULL;
901 ap_log_error(APLOG_MARK,APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
902 "Parent: Forcing termination of child process %pp",
903 event_handles[CHILD_HANDLE]);
904 TerminateProcess(event_handles[CHILD_HANDLE], 1);
905 CloseHandle(event_handles[CHILD_HANDLE]);
906 event_handles[CHILD_HANDLE] = NULL;
909 CloseHandle(child_exit_event);
910 return 0; /* Tell the caller we do not want to restart */
912 winnt_mpm_state = AP_MPMQ_STARTING;
913 CloseHandle(child_exit_event);
914 return 1; /* Tell the caller we want a restart */
917 /* service_nt_main_fn needs to append the StartService() args
918 * outside of our call stack and thread as the service starts...
920 apr_array_header_t *mpm_new_argv;
922 /* Remember service_to_start failures to log and fail in pre_config.
923 * Remember inst_argc and inst_argv for installing or starting the
924 * service after we preflight the config.
927 static int winnt_query(int query_code, int *result, apr_status_t *rv)
930 switch (query_code) {
931 case AP_MPMQ_MAX_DAEMON_USED:
932 *result = MAXIMUM_WAIT_OBJECTS;
934 case AP_MPMQ_IS_THREADED:
935 *result = AP_MPMQ_STATIC;
937 case AP_MPMQ_IS_FORKED:
938 *result = AP_MPMQ_NOT_SUPPORTED;
940 case AP_MPMQ_HARD_LIMIT_DAEMONS:
941 *result = HARD_SERVER_LIMIT;
943 case AP_MPMQ_HARD_LIMIT_THREADS:
944 *result = thread_limit;
946 case AP_MPMQ_MAX_THREADS:
947 *result = ap_threads_per_child;
949 case AP_MPMQ_MIN_SPARE_DAEMONS:
952 case AP_MPMQ_MIN_SPARE_THREADS:
955 case AP_MPMQ_MAX_SPARE_DAEMONS:
958 case AP_MPMQ_MAX_SPARE_THREADS:
961 case AP_MPMQ_MAX_REQUESTS_DAEMON:
962 *result = ap_max_requests_per_child;
964 case AP_MPMQ_MAX_DAEMONS:
967 case AP_MPMQ_MPM_STATE:
968 *result = winnt_mpm_state;
970 case AP_MPMQ_GENERATION:
971 *result = my_generation;
980 static const char *winnt_get_name(void)
985 #define SERVICE_UNSET (-1)
986 static apr_status_t service_set = SERVICE_UNSET;
987 static apr_status_t service_to_start_success;
988 static int inst_argc;
989 static const char * const *inst_argv;
990 static const char *service_name = NULL;
992 static void winnt_rewrite_args(process_rec *process)
994 /* Handle the following SCM aspects in this phase:
996 * -k runservice [transition in service context only]
1001 * -k shutdown (same as -k stop). Maintained for backward compatability.
1003 * We can't leave this phase until we know our identity
1004 * and modify the command arguments appropriately.
1006 * We do not care if the .conf file exists or is parsable when
1007 * attempting to stop or uninstall a service.
1010 char *def_server_root;
1013 const char *opt_arg;
1017 int running_as_service = 1;
1019 apr_file_t *nullfile;
1021 pconf = process->pconf;
1023 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1024 GetVersionEx(&osver);
1026 /* We wish this was *always* a reservation, but sadly it wasn't so and
1027 * we couldn't break a hard limit prior to NT Kernel 5.1
1029 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1030 && ((osver.dwMajorVersion > 5)
1031 || ((osver.dwMajorVersion == 5) && (osver.dwMinorVersion > 0)))) {
1032 stack_res_flag = STACK_SIZE_PARAM_IS_A_RESERVATION;
1035 /* AP_PARENT_PID is only valid in the child */
1036 pid = getenv("AP_PARENT_PID");
1040 HANDLE hproc = GetCurrentProcess();
1042 /* This is the child */
1043 my_pid = GetCurrentProcessId();
1044 parent_pid = (DWORD) atol(pid);
1046 /* Prevent holding open the (nonexistant) console */
1047 ap_real_exit_code = 0;
1049 /* The parent gave us stdin, we need to remember this
1050 * handle, and no longer inherit it at our children
1051 * (we can't slurp it up now, we just aren't ready yet).
1052 * The original handle is closed below, at apr_file_dup2()
1054 pipe = GetStdHandle(STD_INPUT_HANDLE);
1055 if (DuplicateHandle(hproc, pipe,
1056 hproc, &filehand, 0, FALSE,
1057 DUPLICATE_SAME_ACCESS)) {
1061 /* The parent gave us stdout of the NUL device,
1062 * and expects us to suck up stdin of all of our
1063 * shared handles and data from the parent.
1064 * Don't infect child processes with our stdin
1065 * handle, use another handle to NUL!
1068 apr_file_t *infile, *outfile;
1069 if ((apr_file_open_stdout(&outfile, process->pool) == APR_SUCCESS)
1070 && (apr_file_open_stdin(&infile, process->pool) == APR_SUCCESS))
1071 apr_file_dup2(infile, outfile, process->pool);
1074 /* This child needs the existing stderr opened for logging,
1079 /* The parent is responsible for providing the
1080 * COMPLETE ARGUMENTS REQUIRED to the child.
1082 * No further argument parsing is needed, but
1083 * for good measure we will provide a simple
1084 * signal string for later testing.
1086 signal_arg = "runchild";
1090 /* This is the parent, we have a long way to go :-) */
1091 parent_pid = my_pid = GetCurrentProcessId();
1093 /* This behavior is voided by setting real_exit_code to 0 */
1094 atexit(hold_console_open_on_error);
1096 /* Rewrite process->argv[];
1098 * strip out -k signal into signal_arg
1099 * strip out -n servicename and set the names
1100 * add default -d serverroot from the path of this executable
1102 * The end result will look like:
1104 * The invocation command (%0)
1105 * The -d serverroot default from the running executable
1106 * The requested service's (-n) registry ConfigArgs
1107 * The WinNT SCM's StartService() args
1109 if ((rv = ap_os_proc_filepath(&binpath, process->pconf))
1111 ap_log_error(APLOG_MARK,APLOG_CRIT, rv, NULL,
1112 "Failed to get the full path of %s", process->argv[0]);
1115 /* WARNING: There is an implict assumption here that the
1116 * executable resides in ServerRoot or ServerRoot\bin
1118 def_server_root = (char *) apr_filepath_name_get(binpath);
1119 if (def_server_root > binpath) {
1120 *(def_server_root - 1) = '\0';
1121 def_server_root = (char *) apr_filepath_name_get(binpath);
1122 if (!strcasecmp(def_server_root, "bin"))
1123 *(def_server_root - 1) = '\0';
1125 apr_filepath_merge(&def_server_root, NULL, binpath,
1126 APR_FILEPATH_TRUENAME, process->pool);
1128 /* Use process->pool so that the rewritten argv
1129 * lasts for the lifetime of the server process,
1130 * because pconf will be destroyed after the
1131 * initial pre-flight of the config parser.
1133 mpm_new_argv = apr_array_make(process->pool, process->argc + 2,
1134 sizeof(const char *));
1135 *(const char **)apr_array_push(mpm_new_argv) = process->argv[0];
1136 *(const char **)apr_array_push(mpm_new_argv) = "-d";
1137 *(const char **)apr_array_push(mpm_new_argv) = def_server_root;
1139 fixed_args = mpm_new_argv->nelts;
1143 apr_getopt_init(&opt, process->pool, process->argc, process->argv);
1145 while ((rv = apr_getopt(opt, "wn:k:" AP_SERVER_BASEARGS,
1146 optbuf + 1, &opt_arg)) == APR_SUCCESS) {
1147 switch (optbuf[1]) {
1149 /* Shortcuts; include the -w option to hold the window open on error.
1150 * This must not be toggled once we reset ap_real_exit_code to 0!
1153 if (ap_real_exit_code)
1154 ap_real_exit_code = 2;
1158 service_set = mpm_service_set_name(process->pool, &service_name,
1163 signal_arg = opt_arg;
1168 /* Fall through so the Apache main() handles the 'E' arg */
1170 *(const char **)apr_array_push(mpm_new_argv) =
1171 apr_pstrdup(process->pool, optbuf);
1174 *(const char **)apr_array_push(mpm_new_argv) = opt_arg;
1180 /* back up to capture the bad argument */
1181 if (rv == APR_BADCH || rv == APR_BADARG) {
1185 while (opt->ind < opt->argc) {
1186 *(const char **)apr_array_push(mpm_new_argv) =
1187 apr_pstrdup(process->pool, opt->argv[opt->ind++]);
1190 /* Track the number of args actually entered by the user */
1191 inst_argc = mpm_new_argv->nelts - fixed_args;
1193 /* Provide a default 'run' -k arg to simplify signal_arg tests */
1197 running_as_service = 0;
1200 if (!strcasecmp(signal_arg, "runservice"))
1202 /* Start the NT Service _NOW_ because the WinNT SCM is
1203 * expecting us to rapidly assume control of our own
1204 * process, the SCM will tell us our service name, and
1205 * may have extra StartService() command arguments to
1208 * The SCM will generally invoke the executable with
1209 * the c:\win\system32 default directory. This is very
1210 * lethal if folks use ServerRoot /foopath on windows
1211 * without a drive letter. Change to the default root
1212 * (path to apache root, above /bin) for safety.
1214 apr_filepath_set(def_server_root, process->pool);
1216 /* Any other process has a console, so we don't to begin
1217 * a Win9x service until the configuration is parsed and
1218 * any command line errors are reported.
1220 * We hold the return value so that we can die in pre_config
1221 * after logging begins, and the failure can land in the log.
1224 mpm_nt_eventlog_stderr_open(service_name, process->pool);
1226 service_to_start_success = mpm_service_to_start(&service_name,
1228 if (service_to_start_success == APR_SUCCESS) {
1229 service_set = APR_SUCCESS;
1232 /* Open a null handle to soak stdout in this process.
1233 * Windows service processes are missing any file handle
1234 * usable for stdin/out/err. This was the cause of later
1235 * trouble with invocations of apr_file_open_stdout()
1237 if ((rv = apr_file_open(&nullfile, "NUL",
1238 APR_READ | APR_WRITE, APR_OS_DEFAULT,
1239 process->pool)) == APR_SUCCESS) {
1240 apr_file_t *nullstdout;
1241 if (apr_file_open_stdout(&nullstdout, process->pool)
1243 apr_file_dup2(nullstdout, nullfile, process->pool);
1244 apr_file_close(nullfile);
1248 /* Get the default for any -k option, except run */
1249 if (service_set == SERVICE_UNSET && strcasecmp(signal_arg, "run")) {
1250 service_set = mpm_service_set_name(process->pool, &service_name,
1251 AP_DEFAULT_SERVICE_NAME);
1254 if (!strcasecmp(signal_arg, "install")) /* -k install */
1256 if (service_set == APR_SUCCESS)
1258 ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
1259 "%s: Service is already installed.", service_name);
1263 else if (running_as_service)
1265 if (service_set == APR_SUCCESS)
1267 /* Attempt to Uninstall, or stop, before
1268 * we can read the arguments or .conf files
1270 if (!strcasecmp(signal_arg, "uninstall")) {
1271 rv = mpm_service_uninstall();
1275 if ((!strcasecmp(signal_arg, "stop")) ||
1276 (!strcasecmp(signal_arg, "shutdown"))) {
1277 mpm_signal_service(process->pool, 0);
1281 rv = mpm_merge_service_args(process->pool, mpm_new_argv,
1283 if (rv == APR_SUCCESS) {
1284 ap_log_error(APLOG_MARK,APLOG_INFO, 0, NULL,
1285 "Using ConfigArgs of the installed service "
1286 "\"%s\".", service_name);
1289 ap_log_error(APLOG_MARK,APLOG_WARNING, rv, NULL,
1290 "No installed ConfigArgs for the service "
1291 "\"%s\", using Apache defaults.", service_name);
1296 ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL,
1297 "No installed service named \"%s\".", service_name);
1301 if (strcasecmp(signal_arg, "install") && service_set && service_set != SERVICE_UNSET)
1303 ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL,
1304 "No installed service named \"%s\".", service_name);
1308 /* Track the args actually entered by the user.
1309 * These will be used for the -k install parameters, as well as
1310 * for the -k start service override arguments.
1312 inst_argv = (const char * const *)mpm_new_argv->elts
1313 + mpm_new_argv->nelts - inst_argc;
1315 /* Now, do service install or reconfigure then proceed to
1316 * post_config to test the installed configuration.
1318 if (!strcasecmp(signal_arg, "config")) { /* -k config */
1319 /* Reconfigure the service */
1320 rv = mpm_service_install(process->pool, inst_argc, inst_argv, 1);
1321 if (rv != APR_SUCCESS) {
1325 fprintf(stderr,"Testing httpd.conf....\n");
1326 fprintf(stderr,"Errors reported here must be corrected before the "
1327 "service can be started.\n");
1329 else if (!strcasecmp(signal_arg, "install")) { /* -k install */
1330 /* Install the service */
1331 rv = mpm_service_install(process->pool, inst_argc, inst_argv, 0);
1332 if (rv != APR_SUCCESS) {
1336 fprintf(stderr,"Testing httpd.conf....\n");
1337 fprintf(stderr,"Errors reported here must be corrected before the "
1338 "service can be started.\n");
1341 process->argc = mpm_new_argv->nelts;
1342 process->argv = (const char * const *) mpm_new_argv->elts;
1346 static int winnt_pre_config(apr_pool_t *pconf_, apr_pool_t *plog, apr_pool_t *ptemp)
1348 /* Handle the following SCM aspects in this phase:
1350 * -k runservice [WinNT errors logged from rewrite_args]
1353 /* Initialize shared static objects.
1354 * TODO: Put config related statics into an sconf structure.
1358 if (ap_exists_config_define("ONE_PROCESS") ||
1359 ap_exists_config_define("DEBUG"))
1362 /* XXX: presume proper privilages; one nice thing would be
1363 * a loud emit if running as "LocalSystem"/"SYSTEM" to indicate
1364 * they should change to a user with write access to logs/ alone.
1366 ap_sys_privileges_handlers(1);
1368 if (!strcasecmp(signal_arg, "runservice")
1369 && (service_to_start_success != APR_SUCCESS)) {
1370 ap_log_error(APLOG_MARK,APLOG_CRIT, service_to_start_success, NULL,
1371 "%s: Unable to start the service manager.",
1375 else if (!one_process && !my_generation) {
1376 /* Open a null handle to soak stdout in this process.
1377 * We need to emulate apr_proc_detach, unix performs this
1378 * same check in the pre_config hook (although it is
1379 * arguably premature). Services already fixed this.
1381 apr_file_t *nullfile;
1383 apr_pool_t *pproc = apr_pool_parent_get(pconf);
1385 if ((rv = apr_file_open(&nullfile, "NUL",
1386 APR_READ | APR_WRITE, APR_OS_DEFAULT,
1387 pproc)) == APR_SUCCESS) {
1388 apr_file_t *nullstdout;
1389 if (apr_file_open_stdout(&nullstdout, pproc)
1391 apr_file_dup2(nullstdout, nullfile, pproc);
1392 apr_file_close(nullfile);
1396 ap_listen_pre_config();
1397 thread_limit = DEFAULT_THREAD_LIMIT;
1398 ap_threads_per_child = DEFAULT_THREADS_PER_CHILD;
1403 static int winnt_check_config(apr_pool_t *pconf, apr_pool_t *plog,
1404 apr_pool_t *ptemp, server_rec* s)
1407 static int restart_num = 0;
1410 /* We want this only in the parent and only the first time around */
1411 is_parent = (parent_pid == my_pid);
1412 if (is_parent && restart_num++ == 0) {
1416 if (thread_limit > MAX_THREAD_LIMIT) {
1418 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1419 "WARNING: ThreadLimit of %d exceeds compile-time "
1420 "limit of", thread_limit);
1421 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1422 " %d threads, decreasing to %d.",
1423 MAX_THREAD_LIMIT, MAX_THREAD_LIMIT);
1424 } else if (is_parent) {
1425 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1426 "ThreadLimit of %d exceeds compile-time limit "
1427 "of %d, decreasing to match",
1428 thread_limit, MAX_THREAD_LIMIT);
1430 thread_limit = MAX_THREAD_LIMIT;
1432 else if (thread_limit < 1) {
1434 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1435 "WARNING: ThreadLimit of %d not allowed, "
1436 "increasing to 1.", thread_limit);
1437 } else if (is_parent) {
1438 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1439 "ThreadLimit of %d not allowed, increasing to 1",
1445 /* You cannot change ThreadLimit across a restart; ignore
1446 * any such attempts.
1448 if (!first_thread_limit) {
1449 first_thread_limit = thread_limit;
1451 else if (thread_limit != first_thread_limit) {
1452 /* Don't need a startup console version here */
1454 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1455 "changing ThreadLimit to %d from original value "
1456 "of %d not allowed during restart",
1457 thread_limit, first_thread_limit);
1459 thread_limit = first_thread_limit;
1462 if (ap_threads_per_child > thread_limit) {
1464 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1465 "WARNING: ThreadsPerChild of %d exceeds ThreadLimit "
1466 "of", ap_threads_per_child);
1467 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1468 " %d threads, decreasing to %d.",
1469 thread_limit, thread_limit);
1470 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1471 " To increase, please see the ThreadLimit "
1473 } else if (is_parent) {
1474 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1475 "ThreadsPerChild of %d exceeds ThreadLimit "
1476 "of %d, decreasing to match",
1477 ap_threads_per_child, thread_limit);
1479 ap_threads_per_child = thread_limit;
1481 else if (ap_threads_per_child < 1) {
1483 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1484 "WARNING: ThreadsPerChild of %d not allowed, "
1485 "increasing to 1.", ap_threads_per_child);
1486 } else if (is_parent) {
1487 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1488 "ThreadsPerChild of %d not allowed, increasing to 1",
1489 ap_threads_per_child);
1491 ap_threads_per_child = 1;
1497 static int winnt_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec* s)
1499 static int restart_num = 0;
1500 apr_status_t rv = 0;
1502 /* Handle the following SCM aspects in this phase:
1504 * -k install (catch and exit as install was handled in rewrite_args)
1505 * -k config (catch and exit as config was handled in rewrite_args)
1508 * -k runservice [Win95, only once - after we parsed the config]
1510 * because all of these signals are useful _only_ if there
1511 * is a valid conf\httpd.conf environment to start.
1513 * We reached this phase by avoiding errors that would cause
1514 * these options to fail unexpectedly in another process.
1517 if (!strcasecmp(signal_arg, "install")) {
1518 /* Service install happens in the rewrite_args hooks. If we
1519 * made it this far, the server configuration is clean and the
1520 * service will successfully start.
1522 apr_pool_destroy(s->process->pool);
1526 if (!strcasecmp(signal_arg, "config")) {
1527 /* Service reconfiguration happens in the rewrite_args hooks. If we
1528 * made it this far, the server configuration is clean and the
1529 * service will successfully start.
1531 apr_pool_destroy(s->process->pool);
1536 if (!strcasecmp(signal_arg, "start")) {
1539 /* Close the listening sockets. */
1540 for (lr = ap_listeners; lr; lr = lr->next) {
1541 apr_socket_close(lr->sd);
1544 rv = mpm_service_start(ptemp, inst_argc, inst_argv);
1545 apr_pool_destroy(s->process->pool);
1550 if (!strcasecmp(signal_arg, "restart")) {
1551 mpm_signal_service(ptemp, 1);
1552 apr_pool_destroy(s->process->pool);
1557 if (parent_pid == my_pid)
1559 if (restart_num++ == 1)
1561 /* This code should be run once in the parent and not run
1564 PSECURITY_ATTRIBUTES sa = GetNullACL(); /* returns NULL if invalid (Win95?) */
1565 setup_signal_names(apr_psprintf(pconf, "ap%lu", parent_pid));
1567 ap_log_pid(pconf, ap_pid_fname);
1569 /* Create shutdown event, apPID_shutdown, where PID is the parent
1570 * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
1572 shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
1573 if (!shutdown_event) {
1574 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1575 "Parent: Cannot create shutdown event %s", signal_shutdown_name);
1576 CleanNullACL((void *)sa);
1577 return HTTP_INTERNAL_SERVER_ERROR;
1580 /* Create restart event, apPID_restart, where PID is the parent
1581 * Apache process ID. Restart is signaled by 'apache -k restart'.
1583 restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
1584 if (!restart_event) {
1585 CloseHandle(shutdown_event);
1586 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1587 "Parent: Cannot create restart event %s", signal_restart_name);
1588 CleanNullACL((void *)sa);
1589 return HTTP_INTERNAL_SERVER_ERROR;
1591 CleanNullACL((void *)sa);
1593 /* Create the start mutex, as an unnamed object for security.
1594 * Ths start mutex is used during a restart to prevent more than
1595 * one child process from entering the accept loop at once.
1597 rv = apr_proc_mutex_create(&start_mutex, NULL,
1599 ap_server_conf->process->pool);
1600 if (rv != APR_SUCCESS) {
1601 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
1602 "%s: Unable to create the start_mutex.",
1604 return HTTP_INTERNAL_SERVER_ERROR;
1607 /* Always reset our console handler to be the first, even on a restart
1608 * because some modules (e.g. mod_perl) might have set a console
1609 * handler to terminate the process.
1611 if (strcasecmp(signal_arg, "runservice"))
1612 mpm_start_console_handler();
1614 else /* parent_pid != my_pid */
1616 mpm_start_child_console_handler();
1621 /* This really should be a post_config hook, but the error log is already
1622 * redirected by that point, so we need to do this in the open_logs phase.
1624 static int winnt_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
1626 /* Initialize shared static objects.
1628 if (parent_pid != my_pid) {
1632 /* We cannot initialize our listeners if we are restarting
1633 * (the parent process already has glomed on to them)
1634 * nor should we do so for service reconfiguration
1635 * (since the service may already be running.)
1637 if (!strcasecmp(signal_arg, "restart")
1638 || !strcasecmp(signal_arg, "config")) {
1642 if (ap_setup_listeners(s) < 1) {
1643 ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_STARTUP, 0,
1644 NULL, "no listening sockets available, shutting down");
1651 static void winnt_child_init(apr_pool_t *pchild, struct server_rec *s)
1655 setup_signal_names(apr_psprintf(pchild, "ap%lu", parent_pid));
1657 /* This is a child process, not in single process mode */
1659 /* Set up events and the scoreboard */
1660 get_handles_from_parent(s, &exit_event, &start_mutex,
1661 &ap_scoreboard_shm);
1663 /* Set up the listeners */
1664 get_listeners_from_parent(s);
1666 /* Done reading from the parent, close that channel */
1669 my_generation = ap_scoreboard_image->global->running_generation;
1672 /* Single process mode - this lock doesn't even need to exist */
1673 rv = apr_proc_mutex_create(&start_mutex, signal_name_prefix,
1674 APR_LOCK_DEFAULT, s->process->pool);
1675 if (rv != APR_SUCCESS) {
1676 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
1677 "%s child: Unable to init the start_mutex.",
1679 exit(APEXIT_CHILDINIT);
1682 /* Borrow the shutdown_even as our _child_ loop exit event */
1683 exit_event = shutdown_event;
1688 static int winnt_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s )
1690 static int restart = 0; /* Default is "not a restart" */
1692 /* ### If non-graceful restarts are ever introduced - we need to rerun
1693 * the pre_mpm hook on subsequent non-graceful restarts. But Win32
1694 * has only graceful style restarts - and we need this hook to act
1695 * the same on Win32 as on Unix.
1697 if (!restart && ((parent_pid == my_pid) || one_process)) {
1698 /* Set up the scoreboard. */
1699 if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
1704 if ((parent_pid != my_pid) || one_process)
1706 /* The child process or in one_process (debug) mode
1708 ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
1709 "Child process is running");
1713 ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
1714 "Child process is exiting");
1719 /* A real-honest to goodness parent */
1720 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1721 "%s configured -- resuming normal operations",
1722 ap_get_server_description());
1723 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1724 "Server built: %s", ap_get_server_built());
1725 ap_log_command_line(plog, s);
1727 restart = master_main(ap_server_conf, shutdown_event, restart_event);
1731 /* Shutting down. Clean up... */
1732 ap_remove_pid(pconf, ap_pid_fname);
1733 apr_proc_mutex_destroy(start_mutex);
1735 CloseHandle(restart_event);
1736 CloseHandle(shutdown_event);
1742 return OK; /* Restart */
1745 static void winnt_hooks(apr_pool_t *p)
1747 /* Our open_logs hook function must run before the core's, or stderr
1748 * will be redirected to a file, and the messages won't print to the
1751 static const char *const aszSucc[] = {"core.c", NULL};
1753 ap_hook_pre_config(winnt_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1754 ap_hook_check_config(winnt_check_config, NULL, NULL, APR_HOOK_MIDDLE);
1755 ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
1756 ap_hook_child_init(winnt_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1757 ap_hook_open_logs(winnt_open_logs, NULL, aszSucc, APR_HOOK_REALLY_FIRST);
1758 ap_hook_mpm(winnt_run, NULL, NULL, APR_HOOK_MIDDLE);
1759 ap_hook_mpm_query(winnt_query, NULL, NULL, APR_HOOK_MIDDLE);
1760 ap_hook_mpm_get_name(winnt_get_name, NULL, NULL, APR_HOOK_MIDDLE);
1763 AP_DECLARE_MODULE(mpm_winnt) = {
1765 winnt_rewrite_args, /* hook to run before apache parses args */
1766 NULL, /* create per-directory config structure */
1767 NULL, /* merge per-directory config structures */
1768 NULL, /* create per-server config structure */
1769 NULL, /* merge per-server config structures */
1770 winnt_cmds, /* command apr_table_t */
1771 winnt_hooks /* register_hooks */
1774 #endif /* def WIN32 */