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 "ap_config.h"
34 #include "ap_listen.h"
35 #include "mpm_default.h"
36 #include "mpm_winnt.h"
37 #include "mpm_common.h"
39 #include "apr_atomic.h"
42 /* scoreboard.c does the heavy lifting; all we do is create the child
43 * score by moving a handle down the pipe into the child's stdin.
45 extern apr_shm_t *ap_scoreboard_shm;
47 /* ap_my_generation are used by the scoreboard code */
48 ap_generation_t volatile ap_my_generation=0;
50 /* Definitions of WINNT MPM specific config globals */
51 static HANDLE shutdown_event; /* used to signal the parent to shutdown */
52 static HANDLE restart_event; /* used to signal the parent to restart */
54 static char ap_coredump_dir[MAX_STRING_LEN];
56 static int one_process = 0;
57 static char const* signal_arg = NULL;
59 OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
61 /* set by child_main to STACK_SIZE_PARAM_IS_A_RESERVATION for NT >= 5.1 (XP/2003) */
64 static DWORD parent_pid;
67 /* used by parent to signal the child to start and exit */
68 apr_proc_mutex_t *start_mutex;
71 int ap_threads_per_child = 0;
72 static int thread_limit = 0;
73 static int first_thread_limit = 0;
74 int winnt_mpm_state = AP_MPMQ_STARTING;
76 /* shared by service.c as global, although
77 * perhaps it should be private.
81 /* on several occasions we don't have the global server context
82 * although it's needed for logging, etc.
84 server_rec *ap_server_conf;
86 /* definitions from child.c */
87 void child_main(apr_pool_t *pconf);
89 /* Only one of these, the pipe from our parent, ment only for
90 * one child worker's consumption (not to be inherited!)
91 * XXX: decorate this name for the trunk branch, was left simplified
92 * only to make the 2.2 patch trivial to read.
96 /* Stub functions until this MPM supports the connection status API */
98 AP_DECLARE(void) ap_update_connection_status(long conn_id, const char *key, \
104 AP_DECLARE(void) ap_reset_connection_status(long conn_id)
109 AP_DECLARE(apr_array_header_t *) ap_get_status_table(apr_pool_t *p)
119 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg)
121 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
126 ap_threads_per_child = atoi(arg);
129 static const char *set_thread_limit (cmd_parms *cmd, void *dummy, const char *arg)
131 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
136 thread_limit = atoi(arg);
140 static const command_rec winnt_cmds[] = {
142 AP_INIT_TAKE1("ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF,
143 "Number of threads each child creates" ),
144 AP_INIT_TAKE1("ThreadLimit", set_thread_limit, NULL, RSRC_CONF,
145 "Maximum worker threads in a server for this run of Apache"),
151 * Signalling Apache on NT.
153 * Under Unix, Apache can be told to shutdown or restart by sending various
154 * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
155 * we use "events" instead. The parent apache process goes into a loop
156 * where it waits forever for a set of events. Two of those events are
162 * (where PID is the PID of the apache parent process). When one of these
163 * is signalled, the Apache parent performs the appropriate action. The events
164 * can become signalled through internal Apache methods (e.g. if the child
165 * finds a fatal error and needs to kill its parent), via the service
166 * control manager (the control thread will signal the shutdown event when
167 * requested to stop the Apache service), from the -k Apache command line,
168 * or from any external program which finds the Apache PID from the
171 * The signal_parent() function, below, is used to signal one of these events.
172 * It can be called by any child or parent process, since it does not
173 * rely on global variables.
175 * On entry, type gives the event to signal. 0 means shutdown, 1 means
179 * Initialise the signal names, in the global variables signal_name_prefix,
180 * signal_restart_name and signal_shutdown_name.
182 #define MAX_SIGNAL_NAME 30 /* Long enough for apPID_shutdown, where PID is an int */
183 char signal_name_prefix[MAX_SIGNAL_NAME];
184 char signal_restart_name[MAX_SIGNAL_NAME];
185 char signal_shutdown_name[MAX_SIGNAL_NAME];
186 void setup_signal_names(char *prefix)
188 apr_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);
189 apr_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name),
190 "%s_shutdown", signal_name_prefix);
191 apr_snprintf(signal_restart_name, sizeof(signal_restart_name),
192 "%s_restart", signal_name_prefix);
195 AP_DECLARE(void) ap_signal_parent(ap_signal_parent_e type)
200 if (parent_pid == my_pid) {
202 case SIGNAL_PARENT_SHUTDOWN:
204 SetEvent(shutdown_event);
207 /* This MPM supports only graceful restarts right now */
208 case SIGNAL_PARENT_RESTART:
209 case SIGNAL_PARENT_RESTART_GRACEFUL:
211 SetEvent(restart_event);
219 case SIGNAL_PARENT_SHUTDOWN:
221 signal_name = signal_shutdown_name;
224 /* This MPM supports only graceful restarts right now */
225 case SIGNAL_PARENT_RESTART:
226 case SIGNAL_PARENT_RESTART_GRACEFUL:
228 signal_name = signal_restart_name;
235 e = OpenEvent(EVENT_MODIFY_STATE, FALSE, signal_name);
237 /* Um, problem, can't signal the parent, which means we can't
238 * signal ourselves to die. Ignore for now...
240 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf,
241 "OpenEvent on %s event", signal_name);
244 if (SetEvent(e) == 0) {
245 /* Same problem as above */
246 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf,
247 "SetEvent on %s event", signal_name);
256 * Passed the following handles [in sync with send_handles_to_child()]
258 * ready event [signal the parent immediately, then close]
259 * exit event [save to poll later]
260 * start mutex [signal from the parent to begin accept()]
261 * scoreboard shm handle [to recreate the ap_scoreboard]
263 void get_handles_from_parent(server_rec *s, HANDLE *child_exit_event,
264 apr_proc_mutex_t **child_start_mutex,
265 apr_shm_t **scoreboard_shm)
274 /* *** We now do this was back in winnt_rewrite_args
275 * pipe = GetStdHandle(STD_INPUT_HANDLE);
277 if (!ReadFile(pipe, &ready_event, sizeof(HANDLE),
278 &BytesRead, (LPOVERLAPPED) NULL)
279 || (BytesRead != sizeof(HANDLE))) {
280 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
281 "Child %d: Unable to retrieve the ready event from the parent", my_pid);
282 exit(APEXIT_CHILDINIT);
285 SetEvent(ready_event);
286 CloseHandle(ready_event);
288 if (!ReadFile(pipe, child_exit_event, sizeof(HANDLE),
289 &BytesRead, (LPOVERLAPPED) NULL)
290 || (BytesRead != sizeof(HANDLE))) {
291 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
292 "Child %d: Unable to retrieve the exit event from the parent", my_pid);
293 exit(APEXIT_CHILDINIT);
296 if (!ReadFile(pipe, &os_start, sizeof(os_start),
297 &BytesRead, (LPOVERLAPPED) NULL)
298 || (BytesRead != sizeof(os_start))) {
299 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
300 "Child %d: Unable to retrieve the start_mutex from the parent", my_pid);
301 exit(APEXIT_CHILDINIT);
303 *child_start_mutex = NULL;
304 if ((rv = apr_os_proc_mutex_put(child_start_mutex, &os_start, s->process->pool))
306 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
307 "Child %d: Unable to access the start_mutex from the parent", my_pid);
308 exit(APEXIT_CHILDINIT);
311 if (!ReadFile(pipe, &hScore, sizeof(hScore),
312 &BytesRead, (LPOVERLAPPED) NULL)
313 || (BytesRead != sizeof(hScore))) {
314 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
315 "Child %d: Unable to retrieve the scoreboard from the parent", my_pid);
316 exit(APEXIT_CHILDINIT);
318 *scoreboard_shm = NULL;
319 if ((rv = apr_os_shm_put(scoreboard_shm, &hScore, s->process->pool))
321 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
322 "Child %d: Unable to access the scoreboard from the parent", my_pid);
323 exit(APEXIT_CHILDINIT);
326 rv = ap_reopen_scoreboard(s->process->pool, scoreboard_shm, 1);
327 if (rv || !(sb_shared = apr_shm_baseaddr_get(*scoreboard_shm))) {
328 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
329 "Child %d: Unable to reopen the scoreboard from the parent", my_pid);
330 exit(APEXIT_CHILDINIT);
332 /* We must 'initialize' the scoreboard to relink all the
333 * process-local pointer arrays into the shared memory block.
335 ap_init_scoreboard(sb_shared);
337 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
338 "Child %d: Retrieved our scoreboard from the parent.", my_pid);
342 static int send_handles_to_child(apr_pool_t *p,
343 HANDLE child_ready_event,
344 HANDLE child_exit_event,
345 apr_proc_mutex_t *child_start_mutex,
346 apr_shm_t *scoreboard_shm,
348 apr_file_t *child_in)
351 HANDLE hCurrentProcess = GetCurrentProcess();
355 apr_size_t BytesWritten;
357 if (!DuplicateHandle(hCurrentProcess, child_ready_event, hProcess, &hDup,
358 EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, 0)) {
359 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
360 "Parent: Unable to duplicate the ready event handle for the child");
363 if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
365 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
366 "Parent: Unable to send the exit event handle to the child");
369 if (!DuplicateHandle(hCurrentProcess, child_exit_event, hProcess, &hDup,
370 EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, 0)) {
371 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
372 "Parent: Unable to duplicate the exit event handle for the child");
375 if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
377 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
378 "Parent: Unable to send the exit event handle to the child");
381 if ((rv = apr_os_proc_mutex_get(&os_start, child_start_mutex)) != APR_SUCCESS) {
382 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
383 "Parent: Unable to retrieve the start mutex for the child");
386 if (!DuplicateHandle(hCurrentProcess, os_start, hProcess, &hDup,
387 SYNCHRONIZE, FALSE, 0)) {
388 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
389 "Parent: Unable to duplicate the start mutex to the child");
392 if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
394 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
395 "Parent: Unable to send the start mutex to the child");
398 if ((rv = apr_os_shm_get(&hScore, scoreboard_shm)) != APR_SUCCESS) {
399 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
400 "Parent: Unable to retrieve the scoreboard handle for the child");
403 if (!DuplicateHandle(hCurrentProcess, hScore, hProcess, &hDup,
404 FILE_MAP_READ | FILE_MAP_WRITE, FALSE, 0)) {
405 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
406 "Parent: Unable to duplicate the scoreboard handle to the child");
409 if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
411 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
412 "Parent: Unable to send the scoreboard handle to the child");
416 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
417 "Parent: Sent the scoreboard to the child");
423 * get_listeners_from_parent()
424 * The listen sockets are opened in the parent. This function, which runs
425 * exclusively in the child process, receives them from the parent and
426 * makes them availeble in the child.
428 void get_listeners_from_parent(server_rec *s)
430 WSAPROTOCOL_INFO WSAProtocolInfo;
435 HANDLE hProcess = GetCurrentProcess();
438 /* Set up a default listener if necessary */
439 if (ap_listeners == NULL) {
441 lr = apr_palloc(s->process->pool, sizeof(ap_listen_rec));
443 lr->next = ap_listeners;
447 /* Open the pipe to the parent process to receive the inherited socket
448 * data. The sockets have been set to listening in the parent process.
450 * *** We now do this was back in winnt_rewrite_args
451 * pipe = GetStdHandle(STD_INPUT_HANDLE);
453 for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) {
454 if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
455 &BytesRead, (LPOVERLAPPED) NULL)) {
456 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
457 "setup_inherited_listeners: Unable to read socket data from parent");
458 exit(APEXIT_CHILDINIT);
461 nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
462 &WSAProtocolInfo, 0, 0);
463 if (nsd == INVALID_SOCKET) {
464 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf,
465 "Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
466 exit(APEXIT_CHILDINIT);
469 if (DuplicateHandle(hProcess, (HANDLE) nsd, hProcess, &dup,
470 0, FALSE, DUPLICATE_SAME_ACCESS)) {
475 apr_os_sock_put(&lr->sd, &nsd, s->process->pool);
478 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
479 "Child %d: retrieved %d listeners from parent", my_pid, lcnt);
483 static int send_listeners_to_child(apr_pool_t *p, DWORD dwProcessId,
484 apr_file_t *child_in)
489 LPWSAPROTOCOL_INFO lpWSAProtocolInfo;
490 apr_size_t BytesWritten;
492 /* Run the chain of open sockets. For each socket, duplicate it
493 * for the target process then send the WSAPROTOCOL_INFO
494 * (returned by dup socket) to the child.
496 for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) {
498 lpWSAProtocolInfo = apr_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
499 apr_os_sock_get(&nsd,lr->sd);
500 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
501 "Parent: Duplicating socket %d and sending it to child process %d",
503 if (WSADuplicateSocket(nsd, dwProcessId,
504 lpWSAProtocolInfo) == SOCKET_ERROR) {
505 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf,
506 "Parent: WSADuplicateSocket failed for socket %d. Check the FAQ.", lr->sd );
510 if ((rv = apr_file_write_full(child_in, lpWSAProtocolInfo,
511 sizeof(WSAPROTOCOL_INFO), &BytesWritten))
513 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
514 "Parent: Unable to write duplicated socket %d to the child.", lr->sd );
519 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
520 "Parent: Sent %d listeners to child %d", lcnt, dwProcessId);
529 static int create_process(apr_pool_t *p, HANDLE *child_proc, HANDLE *child_exit_event,
532 /* These NEVER change for the lifetime of this parent
534 static char **args = NULL;
535 static char pidbuf[28];
539 apr_procattr_t *attr;
540 apr_proc_t new_child;
542 HANDLE waitlist[2]; /* see waitlist_e */
548 apr_pool_create_ex(&ptemp, p, NULL, NULL);
550 /* Build the command line. Should look something like this:
551 * C:/apache/bin/httpd.exe -f ap_server_confname
552 * First, get the path to the executable...
554 apr_procattr_create(&attr, ptemp);
555 apr_procattr_cmdtype_set(attr, APR_PROGRAM);
556 apr_procattr_detach_set(attr, 1);
557 if (((rv = apr_filepath_get(&cwd, 0, ptemp)) != APR_SUCCESS)
558 || ((rv = apr_procattr_dir_set(attr, cwd)) != APR_SUCCESS)) {
559 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
560 "Parent: Failed to get the current path");
564 /* Build the args array, only once since it won't change
565 * for the lifetime of this parent process.
567 if ((rv = ap_os_proc_filepath(&cmd, ptemp))
569 ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, ap_server_conf,
570 "Parent: Failed to get full path of %s",
571 ap_server_conf->process->argv[0]);
572 apr_pool_destroy(ptemp);
576 args = malloc((ap_server_conf->process->argc + 1) * sizeof (char*));
577 memcpy(args + 1, ap_server_conf->process->argv + 1,
578 (ap_server_conf->process->argc - 1) * sizeof (char*));
579 args[0] = malloc(strlen(cmd) + 1);
580 strcpy(args[0], cmd);
581 args[ap_server_conf->process->argc] = NULL;
587 /* Create a pipe to send handles to the child */
588 if ((rv = apr_procattr_io_set(attr, APR_FULL_BLOCK,
589 APR_NO_PIPE, APR_NO_PIPE)) != APR_SUCCESS) {
590 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
591 "Parent: Unable to create child stdin pipe.");
592 apr_pool_destroy(ptemp);
596 /* Create the child_ready_event */
597 waitlist[waitlist_ready] = CreateEvent(NULL, TRUE, FALSE, NULL);
598 if (!waitlist[waitlist_ready]) {
599 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
600 "Parent: Could not create ready event for child process");
601 apr_pool_destroy (ptemp);
605 /* Create the child_exit_event */
606 hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
608 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
609 "Parent: Could not create exit event for child process");
610 apr_pool_destroy(ptemp);
611 CloseHandle(waitlist[waitlist_ready]);
615 /* Build the env array */
616 for (envc = 0; _environ[envc]; ++envc) {
619 env = apr_palloc(ptemp, (envc + 2) * sizeof (char*));
620 memcpy(env, _environ, envc * sizeof (char*));
621 apr_snprintf(pidbuf, sizeof(pidbuf), "AP_PARENT_PID=%i", parent_pid);
623 env[envc + 1] = NULL;
625 rv = apr_proc_create(&new_child, cmd, args, env, attr, ptemp);
626 if (rv != APR_SUCCESS) {
627 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
628 "Parent: Failed to create the child process.");
629 apr_pool_destroy(ptemp);
630 CloseHandle(hExitEvent);
631 CloseHandle(waitlist[waitlist_ready]);
632 CloseHandle(new_child.hproc);
636 ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
637 "Parent: Created child process %d", new_child.pid);
639 if (send_handles_to_child(ptemp, waitlist[waitlist_ready], hExitEvent,
640 start_mutex, ap_scoreboard_shm,
641 new_child.hproc, new_child.in)) {
643 * This error is fatal, mop up the child and move on
644 * We toggle the child's exit event to cause this child
645 * to quit even as it is attempting to start.
647 SetEvent(hExitEvent);
648 apr_pool_destroy(ptemp);
649 CloseHandle(hExitEvent);
650 CloseHandle(waitlist[waitlist_ready]);
651 CloseHandle(new_child.hproc);
656 * Give the child process a chance to run before dup'ing the sockets.
657 * We have already set the listening sockets noninheritable, but if
658 * WSADuplicateSocket runs before the child process initializes
659 * the listeners will be inherited anyway.
661 waitlist[waitlist_term] = new_child.hproc;
662 rv = WaitForMultipleObjects(2, waitlist, FALSE, INFINITE);
663 CloseHandle(waitlist[waitlist_ready]);
664 if (rv != WAIT_OBJECT_0) {
666 * Outch... that isn't a ready signal. It's dead, Jim!
668 SetEvent(hExitEvent);
669 apr_pool_destroy(ptemp);
670 CloseHandle(hExitEvent);
671 CloseHandle(new_child.hproc);
675 if (send_listeners_to_child(ptemp, new_child.pid, new_child.in)) {
677 * This error is fatal, mop up the child and move on
678 * We toggle the child's exit event to cause this child
679 * to quit even as it is attempting to start.
681 SetEvent(hExitEvent);
682 apr_pool_destroy(ptemp);
683 CloseHandle(hExitEvent);
684 CloseHandle(new_child.hproc);
688 apr_file_close(new_child.in);
690 *child_exit_event = hExitEvent;
691 *child_proc = new_child.hproc;
692 *child_pid = new_child.pid;
697 /***********************************************************************
699 * master_main() runs in the parent process. It creates the child
700 * process which handles HTTP requests then waits on one of three
705 * The restart event causes master_main to start a new child process and
706 * tells the old child process to exit (by setting the child_exit_event).
707 * The restart event is set as a result of one of the following:
708 * 1. An apache -k restart command on the command line
709 * 2. A command received from Windows service manager which gets
710 * translated into an ap_signal_parent(SIGNAL_PARENT_RESTART)
711 * call by code in service.c.
712 * 3. The child process calling ap_signal_parent(SIGNAL_PARENT_RESTART)
713 * as a result of hitting MaxRequestsPerChild.
717 * The shutdown event causes master_main to tell the child process to
718 * exit and that the server is shutting down. The shutdown event is
719 * set as a result of one of the following:
720 * 1. An apache -k shutdown command on the command line
721 * 2. A command received from Windows service manager which gets
722 * translated into an ap_signal_parent(SIGNAL_PARENT_SHUTDOWN)
723 * call by code in service.c.
725 * child process handle
726 * --------------------
727 * The child process handle will be signaled if the child process
728 * exits for any reason. In a normal running server, the signaling
729 * of this event means that the child process has exited prematurely
730 * due to a seg fault or other irrecoverable error. For server
731 * robustness, master_main will restart the child process under this
734 * master_main uses the child_exit_event to signal the child process
736 **********************************************************************/
737 #define NUM_WAIT_HANDLES 3
738 #define CHILD_HANDLE 0
739 #define SHUTDOWN_HANDLE 1
740 #define RESTART_HANDLE 2
741 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
745 int shutdown_pending;
746 HANDLE child_exit_event;
747 HANDLE event_handles[NUM_WAIT_HANDLES];
750 restart_pending = shutdown_pending = 0;
752 event_handles[SHUTDOWN_HANDLE] = shutdown_event;
753 event_handles[RESTART_HANDLE] = restart_event;
755 /* Create a single child process */
756 rv = create_process(pconf, &event_handles[CHILD_HANDLE],
757 &child_exit_event, &child_pid);
760 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
761 "master_main: create child process failed. Exiting.");
762 shutdown_pending = 1;
765 if (!strcasecmp(signal_arg, "runservice")) {
766 mpm_service_started();
769 /* Update the scoreboard. Note that there is only a single active
772 ap_scoreboard_image->parent[0].quiescing = 0;
773 ap_scoreboard_image->parent[0].pid = child_pid;
775 /* Wait for shutdown or restart events or for child death */
776 winnt_mpm_state = AP_MPMQ_RUNNING;
777 rv = WaitForMultipleObjects(NUM_WAIT_HANDLES, (HANDLE *) event_handles, FALSE, INFINITE);
778 cld = rv - WAIT_OBJECT_0;
779 if (rv == WAIT_FAILED) {
780 /* Something serious is wrong */
781 ap_log_error(APLOG_MARK,APLOG_CRIT, apr_get_os_error(), ap_server_conf,
782 "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
783 shutdown_pending = 1;
785 else if (rv == WAIT_TIMEOUT) {
786 /* Hey, this cannot happen */
787 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
788 "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
789 shutdown_pending = 1;
791 else if (cld == SHUTDOWN_HANDLE) {
792 /* shutdown_event signalled */
793 shutdown_pending = 1;
794 ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, s,
795 "Parent: Received shutdown signal -- Shutting down the server.");
796 if (ResetEvent(shutdown_event) == 0) {
797 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
798 "ResetEvent(shutdown_event)");
801 else if (cld == RESTART_HANDLE) {
802 /* Received a restart event. Prepare the restart_event to be reused
803 * then signal the child process to exit.
806 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
807 "Parent: Received restart signal -- Restarting the server.");
808 if (ResetEvent(restart_event) == 0) {
809 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
810 "Parent: ResetEvent(restart_event) failed.");
812 if (SetEvent(child_exit_event) == 0) {
813 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
814 "Parent: SetEvent for child process %d failed.",
815 event_handles[CHILD_HANDLE]);
817 /* Don't wait to verify that the child process really exits,
818 * just move on with the restart.
820 CloseHandle(event_handles[CHILD_HANDLE]);
821 event_handles[CHILD_HANDLE] = NULL;
824 /* The child process exited prematurely due to a fatal error. */
826 if (!GetExitCodeProcess(event_handles[CHILD_HANDLE], &exitcode)) {
827 /* HUH? We did exit, didn't we? */
828 exitcode = APEXIT_CHILDFATAL;
830 if ( exitcode == APEXIT_CHILDFATAL
831 || exitcode == APEXIT_CHILDINIT
832 || exitcode == APEXIT_INIT) {
833 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, ap_server_conf,
834 "Parent: child process exited with status %u -- Aborting.", exitcode);
835 shutdown_pending = 1;
840 ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
841 "Parent: child process exited with status %u -- Restarting.", exitcode);
842 for (i = 0; i < ap_threads_per_child; i++) {
843 ap_update_child_status_from_indexes(0, i, SERVER_DEAD, NULL);
846 CloseHandle(event_handles[CHILD_HANDLE]);
847 event_handles[CHILD_HANDLE] = NULL;
849 if (restart_pending) {
851 ap_scoreboard_image->global->running_generation = ap_my_generation;
854 if (shutdown_pending)
856 int timeout = 30000; /* Timeout is milliseconds */
857 winnt_mpm_state = AP_MPMQ_STOPPING;
859 /* This shutdown is only marginally graceful. We will give the
860 * child a bit of time to exit gracefully. If the time expires,
861 * the child will be wacked.
863 if (!strcasecmp(signal_arg, "runservice")) {
864 mpm_service_stopping();
866 /* Signal the child processes to exit */
867 if (SetEvent(child_exit_event) == 0) {
868 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), ap_server_conf,
869 "Parent: SetEvent for child process %d failed", event_handles[CHILD_HANDLE]);
871 if (event_handles[CHILD_HANDLE]) {
872 rv = WaitForSingleObject(event_handles[CHILD_HANDLE], timeout);
873 if (rv == WAIT_OBJECT_0) {
874 ap_log_error(APLOG_MARK,APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
875 "Parent: Child process exited successfully.");
876 CloseHandle(event_handles[CHILD_HANDLE]);
877 event_handles[CHILD_HANDLE] = NULL;
880 ap_log_error(APLOG_MARK,APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
881 "Parent: Forcing termination of child process %d ", event_handles[CHILD_HANDLE]);
882 TerminateProcess(event_handles[CHILD_HANDLE], 1);
883 CloseHandle(event_handles[CHILD_HANDLE]);
884 event_handles[CHILD_HANDLE] = NULL;
887 CloseHandle(child_exit_event);
888 return 0; /* Tell the caller we do not want to restart */
890 winnt_mpm_state = AP_MPMQ_STARTING;
891 CloseHandle(child_exit_event);
892 return 1; /* Tell the caller we want a restart */
895 /* service_nt_main_fn needs to append the StartService() args
896 * outside of our call stack and thread as the service starts...
898 apr_array_header_t *mpm_new_argv;
900 /* Remember service_to_start failures to log and fail in pre_config.
901 * Remember inst_argc and inst_argv for installing or starting the
902 * service after we preflight the config.
905 AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
908 case AP_MPMQ_MAX_DAEMON_USED:
909 *result = MAXIMUM_WAIT_OBJECTS;
911 case AP_MPMQ_IS_THREADED:
912 *result = AP_MPMQ_STATIC;
914 case AP_MPMQ_IS_FORKED:
915 *result = AP_MPMQ_NOT_SUPPORTED;
917 case AP_MPMQ_HARD_LIMIT_DAEMONS:
918 *result = HARD_SERVER_LIMIT;
920 case AP_MPMQ_HARD_LIMIT_THREADS:
921 *result = thread_limit;
923 case AP_MPMQ_MAX_THREADS:
924 *result = ap_threads_per_child;
926 case AP_MPMQ_MIN_SPARE_DAEMONS:
929 case AP_MPMQ_MIN_SPARE_THREADS:
932 case AP_MPMQ_MAX_SPARE_DAEMONS:
935 case AP_MPMQ_MAX_SPARE_THREADS:
938 case AP_MPMQ_MAX_REQUESTS_DAEMON:
939 *result = ap_max_requests_per_child;
941 case AP_MPMQ_MAX_DAEMONS:
944 case AP_MPMQ_MPM_STATE:
945 *result = winnt_mpm_state;
951 #define SERVICE_UNSET (-1)
952 static apr_status_t service_set = SERVICE_UNSET;
953 static apr_status_t service_to_start_success;
954 static int inst_argc;
955 static const char * const *inst_argv;
956 static char *service_name = NULL;
958 void winnt_rewrite_args(process_rec *process)
960 /* Handle the following SCM aspects in this phase:
962 * -k runservice [transition in service context only]
967 * -k shutdown (same as -k stop). Maintained for backward compatability.
969 * We can't leave this phase until we know our identity
970 * and modify the command arguments appropriately.
972 * We do not care if the .conf file exists or is parsable when
973 * attempting to stop or uninstall a service.
976 char *def_server_root;
983 int running_as_service = 1;
985 apr_file_t *nullfile;
987 pconf = process->pconf;
989 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
990 GetVersionEx(&osver);
992 /* We wish this was *always* a reservation, but sadly it wasn't so and
993 * we couldn't break a hard limit prior to NT Kernel 5.1
995 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT
996 && ((osver.dwMajorVersion > 5)
997 || ((osver.dwMajorVersion == 5) && (osver.dwMinorVersion > 0)))) {
998 stack_res_flag = STACK_SIZE_PARAM_IS_A_RESERVATION;
1001 /* AP_PARENT_PID is only valid in the child */
1002 pid = getenv("AP_PARENT_PID");
1006 HANDLE hproc = GetCurrentProcess();
1008 /* This is the child */
1009 my_pid = GetCurrentProcessId();
1010 parent_pid = (DWORD) atol(pid);
1012 /* Prevent holding open the (nonexistant) console */
1013 ap_real_exit_code = 0;
1015 /* The parent gave us stdin, we need to remember this
1016 * handle, and no longer inherit it at our children
1017 * (we can't slurp it up now, we just aren't ready yet).
1018 * The original handle is closed below, at apr_file_dup2()
1020 pipe = GetStdHandle(STD_INPUT_HANDLE);
1021 if (DuplicateHandle(hproc, pipe,
1022 hproc, &filehand, 0, FALSE,
1023 DUPLICATE_SAME_ACCESS)) {
1027 /* The parent gave us stdout of the NUL device,
1028 * and expects us to suck up stdin of all of our
1029 * shared handles and data from the parent.
1030 * Don't infect child processes with our stdin
1031 * handle, use another handle to NUL!
1034 apr_file_t *infile, *outfile;
1035 if ((apr_file_open_stdout(&outfile, process->pool) == APR_SUCCESS)
1036 && (apr_file_open_stdin(&infile, process->pool) == APR_SUCCESS))
1037 apr_file_dup2(infile, outfile, process->pool);
1040 /* This child needs the existing stderr opened for logging,
1045 /* The parent is responsible for providing the
1046 * COMPLETE ARGUMENTS REQUIRED to the child.
1048 * No further argument parsing is needed, but
1049 * for good measure we will provide a simple
1050 * signal string for later testing.
1052 signal_arg = "runchild";
1056 /* This is the parent, we have a long way to go :-) */
1057 parent_pid = my_pid = GetCurrentProcessId();
1059 /* This behavior is voided by setting real_exit_code to 0 */
1060 atexit(hold_console_open_on_error);
1062 /* Rewrite process->argv[];
1064 * strip out -k signal into signal_arg
1065 * strip out -n servicename and set the names
1066 * add default -d serverroot from the path of this executable
1068 * The end result will look like:
1070 * The invocation command (%0)
1071 * The -d serverroot default from the running executable
1072 * The requested service's (-n) registry ConfigArgs
1073 * The WinNT SCM's StartService() args
1075 if ((rv = ap_os_proc_filepath(&binpath, process->pconf))
1077 ap_log_error(APLOG_MARK,APLOG_CRIT, rv, NULL,
1078 "Failed to get the full path of %s", process->argv[0]);
1081 /* WARNING: There is an implict assumption here that the
1082 * executable resides in ServerRoot or ServerRoot\bin
1084 def_server_root = (char *) apr_filepath_name_get(binpath);
1085 if (def_server_root > binpath) {
1086 *(def_server_root - 1) = '\0';
1087 def_server_root = (char *) apr_filepath_name_get(binpath);
1088 if (!strcasecmp(def_server_root, "bin"))
1089 *(def_server_root - 1) = '\0';
1091 apr_filepath_merge(&def_server_root, NULL, binpath,
1092 APR_FILEPATH_TRUENAME, process->pool);
1094 /* Use process->pool so that the rewritten argv
1095 * lasts for the lifetime of the server process,
1096 * because pconf will be destroyed after the
1097 * initial pre-flight of the config parser.
1099 mpm_new_argv = apr_array_make(process->pool, process->argc + 2,
1100 sizeof(const char *));
1101 *(const char **)apr_array_push(mpm_new_argv) = process->argv[0];
1102 *(const char **)apr_array_push(mpm_new_argv) = "-d";
1103 *(const char **)apr_array_push(mpm_new_argv) = def_server_root;
1105 fixed_args = mpm_new_argv->nelts;
1109 apr_getopt_init(&opt, process->pool, process->argc, (char**) process->argv);
1111 while ((rv = apr_getopt(opt, "wn:k:" AP_SERVER_BASEARGS,
1112 optbuf + 1, &optarg)) == APR_SUCCESS) {
1113 switch (optbuf[1]) {
1115 /* Shortcuts; include the -w option to hold the window open on error.
1116 * This must not be toggled once we reset ap_real_exit_code to 0!
1119 if (ap_real_exit_code)
1120 ap_real_exit_code = 2;
1124 service_set = mpm_service_set_name(process->pool, &service_name,
1129 signal_arg = optarg;
1134 /* Fall through so the Apache main() handles the 'E' arg */
1136 *(const char **)apr_array_push(mpm_new_argv) =
1137 apr_pstrdup(process->pool, optbuf);
1140 *(const char **)apr_array_push(mpm_new_argv) = optarg;
1146 /* back up to capture the bad argument */
1147 if (rv == APR_BADCH || rv == APR_BADARG) {
1151 while (opt->ind < opt->argc) {
1152 *(const char **)apr_array_push(mpm_new_argv) =
1153 apr_pstrdup(process->pool, opt->argv[opt->ind++]);
1156 /* Track the number of args actually entered by the user */
1157 inst_argc = mpm_new_argv->nelts - fixed_args;
1159 /* Provide a default 'run' -k arg to simplify signal_arg tests */
1163 running_as_service = 0;
1166 if (!strcasecmp(signal_arg, "runservice"))
1168 /* Start the NT Service _NOW_ because the WinNT SCM is
1169 * expecting us to rapidly assume control of our own
1170 * process, the SCM will tell us our service name, and
1171 * may have extra StartService() command arguments to
1174 * The SCM will generally invoke the executable with
1175 * the c:\win\system32 default directory. This is very
1176 * lethal if folks use ServerRoot /foopath on windows
1177 * without a drive letter. Change to the default root
1178 * (path to apache root, above /bin) for safety.
1180 apr_filepath_set(def_server_root, process->pool);
1182 /* Any other process has a console, so we don't to begin
1183 * a Win9x service until the configuration is parsed and
1184 * any command line errors are reported.
1186 * We hold the return value so that we can die in pre_config
1187 * after logging begins, and the failure can land in the log.
1190 mpm_nt_eventlog_stderr_open(service_name, process->pool);
1192 service_to_start_success = mpm_service_to_start(&service_name,
1194 if (service_to_start_success == APR_SUCCESS) {
1195 service_set = APR_SUCCESS;
1198 /* Open a null handle to soak stdout in this process.
1199 * Windows service processes are missing any file handle
1200 * usable for stdin/out/err. This was the cause of later
1201 * trouble with invocations of apr_file_open_stdout()
1203 if ((rv = apr_file_open(&nullfile, "NUL",
1204 APR_READ | APR_WRITE, APR_OS_DEFAULT,
1205 process->pool)) == APR_SUCCESS) {
1206 apr_file_t *nullstdout;
1207 if (apr_file_open_stdout(&nullstdout, process->pool)
1209 apr_file_dup2(nullstdout, nullfile, process->pool);
1210 apr_file_close(nullfile);
1214 /* Get the default for any -k option, except run */
1215 if (service_set == SERVICE_UNSET && strcasecmp(signal_arg, "run")) {
1216 service_set = mpm_service_set_name(process->pool, &service_name,
1217 AP_DEFAULT_SERVICE_NAME);
1220 if (!strcasecmp(signal_arg, "install")) /* -k install */
1222 if (service_set == APR_SUCCESS)
1224 ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
1225 "%s: Service is already installed.", service_name);
1229 else if (running_as_service)
1231 if (service_set == APR_SUCCESS)
1233 /* Attempt to Uninstall, or stop, before
1234 * we can read the arguments or .conf files
1236 if (!strcasecmp(signal_arg, "uninstall")) {
1237 rv = mpm_service_uninstall();
1241 if ((!strcasecmp(signal_arg, "stop")) ||
1242 (!strcasecmp(signal_arg, "shutdown"))) {
1243 mpm_signal_service(process->pool, 0);
1247 rv = mpm_merge_service_args(process->pool, mpm_new_argv,
1249 if (rv == APR_SUCCESS) {
1250 ap_log_error(APLOG_MARK,APLOG_INFO, 0, NULL,
1251 "Using ConfigArgs of the installed service "
1252 "\"%s\".", service_name);
1255 ap_log_error(APLOG_MARK,APLOG_WARNING, rv, NULL,
1256 "No installed ConfigArgs for the service "
1257 "\"%s\", using Apache defaults.", service_name);
1262 ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL,
1263 "No installed service named \"%s\".", service_name);
1267 if (strcasecmp(signal_arg, "install") && service_set && service_set != SERVICE_UNSET)
1269 ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL,
1270 "No installed service named \"%s\".", service_name);
1274 /* Track the args actually entered by the user.
1275 * These will be used for the -k install parameters, as well as
1276 * for the -k start service override arguments.
1278 inst_argv = (const char * const *)mpm_new_argv->elts
1279 + mpm_new_argv->nelts - inst_argc;
1281 /* Now, do service install or reconfigure then proceed to
1282 * post_config to test the installed configuration.
1284 if (!strcasecmp(signal_arg, "config")) { /* -k config */
1285 /* Reconfigure the service */
1286 rv = mpm_service_install(process->pool, inst_argc, inst_argv, 1);
1287 if (rv != APR_SUCCESS) {
1291 fprintf(stderr,"Testing httpd.conf....\n");
1292 fprintf(stderr,"Errors reported here must be corrected before the "
1293 "service can be started.\n");
1295 else if (!strcasecmp(signal_arg, "install")) { /* -k install */
1296 /* Install the service */
1297 rv = mpm_service_install(process->pool, inst_argc, inst_argv, 0);
1298 if (rv != APR_SUCCESS) {
1302 fprintf(stderr,"Testing httpd.conf....\n");
1303 fprintf(stderr,"Errors reported here must be corrected before the "
1304 "service can be started.\n");
1307 process->argc = mpm_new_argv->nelts;
1308 process->argv = (const char * const *) mpm_new_argv->elts;
1312 static int winnt_pre_config(apr_pool_t *pconf_, apr_pool_t *plog, apr_pool_t *ptemp)
1314 /* Handle the following SCM aspects in this phase:
1316 * -k runservice [WinNT errors logged from rewrite_args]
1319 /* Initialize shared static objects.
1320 * TODO: Put config related statics into an sconf structure.
1324 if (ap_exists_config_define("ONE_PROCESS") ||
1325 ap_exists_config_define("DEBUG"))
1328 /* XXX: presume proper privilages; one nice thing would be
1329 * a loud emit if running as "LocalSystem"/"SYSTEM" to indicate
1330 * they should change to a user with write access to logs/ alone.
1332 ap_sys_privileges_handlers(1);
1334 if (!strcasecmp(signal_arg, "runservice")
1335 && (service_to_start_success != APR_SUCCESS)) {
1336 ap_log_error(APLOG_MARK,APLOG_CRIT, service_to_start_success, NULL,
1337 "%s: Unable to start the service manager.",
1341 else if (!one_process && !ap_my_generation) {
1342 /* Open a null handle to soak stdout in this process.
1343 * We need to emulate apr_proc_detach, unix performs this
1344 * same check in the pre_config hook (although it is
1345 * arguably premature). Services already fixed this.
1347 apr_file_t *nullfile;
1349 apr_pool_t *pproc = apr_pool_parent_get(pconf);
1351 if ((rv = apr_file_open(&nullfile, "NUL",
1352 APR_READ | APR_WRITE, APR_OS_DEFAULT,
1353 pproc)) == APR_SUCCESS) {
1354 apr_file_t *nullstdout;
1355 if (apr_file_open_stdout(&nullstdout, pproc)
1357 apr_file_dup2(nullstdout, nullfile, pproc);
1358 apr_file_close(nullfile);
1362 ap_listen_pre_config();
1363 thread_limit = DEFAULT_THREAD_LIMIT;
1364 ap_threads_per_child = DEFAULT_THREADS_PER_CHILD;
1365 ap_pid_fname = DEFAULT_PIDLOG;
1366 ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1367 ap_max_mem_free = APR_ALLOCATOR_MAX_FREE_UNLIMITED;
1369 apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1374 static int winnt_check_config(apr_pool_t *pconf, apr_pool_t *plog,
1375 apr_pool_t *ptemp, server_rec* s)
1378 static int restart_num = 0;
1381 /* We want this only in the parent and only the first time around */
1382 is_parent = (parent_pid == my_pid);
1383 if (is_parent && restart_num++ == 0) {
1387 if (thread_limit > MAX_THREAD_LIMIT) {
1389 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1390 "WARNING: ThreadLimit of %d exceeds compile-time "
1391 "limit of", thread_limit);
1392 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1393 " %d threads, decreasing to %d.",
1394 MAX_THREAD_LIMIT, MAX_THREAD_LIMIT);
1395 } else if (is_parent) {
1396 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1397 "ThreadLimit of %d exceeds compile-time limit "
1398 "of %d, decreasing to match",
1399 thread_limit, MAX_THREAD_LIMIT);
1401 thread_limit = MAX_THREAD_LIMIT;
1403 else if (thread_limit < 1) {
1405 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1406 "WARNING: ThreadLimit of %d not allowed, "
1407 "increasing to 1.", thread_limit);
1408 } else if (is_parent) {
1409 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1410 "ThreadLimit of %d not allowed, increasing to 1",
1416 /* You cannot change ThreadLimit across a restart; ignore
1417 * any such attempts.
1419 if (!first_thread_limit) {
1420 first_thread_limit = thread_limit;
1422 else if (thread_limit != first_thread_limit) {
1423 /* Don't need a startup console version here */
1425 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1426 "changing ThreadLimit to %d from original value "
1427 "of %d not allowed during restart",
1428 thread_limit, first_thread_limit);
1430 thread_limit = first_thread_limit;
1433 if (ap_threads_per_child > thread_limit) {
1435 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1436 "WARNING: ThreadsPerChild of %d exceeds ThreadLimit "
1437 "of", ap_threads_per_child);
1438 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1439 " %d threads, decreasing to %d.",
1440 thread_limit, thread_limit);
1441 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1442 " To increase, please see the ThreadLimit "
1444 } else if (is_parent) {
1445 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1446 "ThreadsPerChild of %d exceeds ThreadLimit "
1447 "of %d, decreasing to match",
1448 ap_threads_per_child, thread_limit);
1450 ap_threads_per_child = thread_limit;
1452 else if (ap_threads_per_child < 1) {
1454 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1455 "WARNING: ThreadsPerChild of %d not allowed, "
1456 "increasing to 1.", ap_threads_per_child);
1457 } else if (is_parent) {
1458 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1459 "ThreadsPerChild of %d not allowed, increasing to 1",
1460 ap_threads_per_child);
1462 ap_threads_per_child = 1;
1468 static int winnt_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec* s)
1470 static int restart_num = 0;
1471 apr_status_t rv = 0;
1473 /* Handle the following SCM aspects in this phase:
1475 * -k install (catch and exit as install was handled in rewrite_args)
1476 * -k config (catch and exit as config was handled in rewrite_args)
1479 * -k runservice [Win95, only once - after we parsed the config]
1481 * because all of these signals are useful _only_ if there
1482 * is a valid conf\httpd.conf environment to start.
1484 * We reached this phase by avoiding errors that would cause
1485 * these options to fail unexpectedly in another process.
1488 if (!strcasecmp(signal_arg, "install")) {
1489 /* Service install happens in the rewrite_args hooks. If we
1490 * made it this far, the server configuration is clean and the
1491 * service will successfully start.
1493 apr_pool_destroy(s->process->pool);
1497 if (!strcasecmp(signal_arg, "config")) {
1498 /* Service reconfiguration happens in the rewrite_args hooks. If we
1499 * made it this far, the server configuration is clean and the
1500 * service will successfully start.
1502 apr_pool_destroy(s->process->pool);
1507 if (!strcasecmp(signal_arg, "start")) {
1510 /* Close the listening sockets. */
1511 for (lr = ap_listeners; lr; lr = lr->next) {
1512 apr_socket_close(lr->sd);
1515 rv = mpm_service_start(ptemp, inst_argc, inst_argv);
1516 apr_pool_destroy(s->process->pool);
1521 if (!strcasecmp(signal_arg, "restart")) {
1522 mpm_signal_service(ptemp, 1);
1523 apr_pool_destroy(s->process->pool);
1528 if (parent_pid == my_pid)
1530 if (restart_num++ == 1)
1532 /* This code should be run once in the parent and not run
1535 PSECURITY_ATTRIBUTES sa = GetNullACL(); /* returns NULL if invalid (Win95?) */
1536 setup_signal_names(apr_psprintf(pconf,"ap%d", parent_pid));
1538 ap_log_pid(pconf, ap_pid_fname);
1540 /* Create shutdown event, apPID_shutdown, where PID is the parent
1541 * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
1543 shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
1544 if (!shutdown_event) {
1545 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1546 "Parent: Cannot create shutdown event %s", signal_shutdown_name);
1547 CleanNullACL((void *)sa);
1548 return HTTP_INTERNAL_SERVER_ERROR;
1551 /* Create restart event, apPID_restart, where PID is the parent
1552 * Apache process ID. Restart is signaled by 'apache -k restart'.
1554 restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
1555 if (!restart_event) {
1556 CloseHandle(shutdown_event);
1557 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1558 "Parent: Cannot create restart event %s", signal_restart_name);
1559 CleanNullACL((void *)sa);
1560 return HTTP_INTERNAL_SERVER_ERROR;
1562 CleanNullACL((void *)sa);
1564 /* Create the start mutex, as an unnamed object for security.
1565 * Ths start mutex is used during a restart to prevent more than
1566 * one child process from entering the accept loop at once.
1568 rv = apr_proc_mutex_create(&start_mutex, NULL,
1570 ap_server_conf->process->pool);
1571 if (rv != APR_SUCCESS) {
1572 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
1573 "%s: Unable to create the start_mutex.",
1575 return HTTP_INTERNAL_SERVER_ERROR;
1578 /* Always reset our console handler to be the first, even on a restart
1579 * because some modules (e.g. mod_perl) might have set a console
1580 * handler to terminate the process.
1582 if (strcasecmp(signal_arg, "runservice"))
1583 mpm_start_console_handler();
1585 else /* parent_pid != my_pid */
1587 mpm_start_child_console_handler();
1592 /* This really should be a post_config hook, but the error log is already
1593 * redirected by that point, so we need to do this in the open_logs phase.
1595 static int winnt_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
1597 /* Initialize shared static objects.
1601 if (parent_pid != my_pid) {
1605 /* We cannot initialize our listeners if we are restarting
1606 * (the parent process already has glomed on to them)
1607 * nor should we do so for service reconfiguration
1608 * (since the service may already be running.)
1610 if (!strcasecmp(signal_arg, "restart")
1611 || !strcasecmp(signal_arg, "config")) {
1615 if (ap_setup_listeners(s) < 1) {
1616 ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_STARTUP, 0,
1617 NULL, "no listening sockets available, shutting down");
1624 static void winnt_child_init(apr_pool_t *pchild, struct server_rec *s)
1628 setup_signal_names(apr_psprintf(pchild,"ap%d", parent_pid));
1630 /* This is a child process, not in single process mode */
1632 /* Set up events and the scoreboard */
1633 get_handles_from_parent(s, &exit_event, &start_mutex,
1634 &ap_scoreboard_shm);
1636 /* Set up the listeners */
1637 get_listeners_from_parent(s);
1639 /* Done reading from the parent, close that channel */
1642 ap_my_generation = ap_scoreboard_image->global->running_generation;
1645 /* Single process mode - this lock doesn't even need to exist */
1646 rv = apr_proc_mutex_create(&start_mutex, signal_name_prefix,
1647 APR_LOCK_DEFAULT, s->process->pool);
1648 if (rv != APR_SUCCESS) {
1649 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
1650 "%s child %d: Unable to init the start_mutex.",
1651 service_name, my_pid);
1652 exit(APEXIT_CHILDINIT);
1655 /* Borrow the shutdown_even as our _child_ loop exit event */
1656 exit_event = shutdown_event;
1661 AP_DECLARE(int) ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s )
1663 static int restart = 0; /* Default is "not a restart" */
1665 /* ### If non-graceful restarts are ever introduced - we need to rerun
1666 * the pre_mpm hook on subsequent non-graceful restarts. But Win32
1667 * has only graceful style restarts - and we need this hook to act
1668 * the same on Win32 as on Unix.
1670 if (!restart && ((parent_pid == my_pid) || one_process)) {
1671 /* Set up the scoreboard. */
1672 if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
1677 if ((parent_pid != my_pid) || one_process)
1679 /* The child process or in one_process (debug) mode
1681 ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
1682 "Child %d: Child process is running", my_pid);
1686 ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
1687 "Child %d: Child process is exiting", my_pid);
1692 /* A real-honest to goodness parent */
1693 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1694 "%s configured -- resuming normal operations",
1695 ap_get_server_description());
1696 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1697 "Server built: %s", ap_get_server_built());
1699 restart = master_main(ap_server_conf, shutdown_event, restart_event);
1703 /* Shutting down. Clean up... */
1704 const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1706 if (pidfile != NULL && unlink(pidfile) == 0) {
1707 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS,
1708 ap_server_conf, "removed PID file %s (pid=%ld)",
1709 pidfile, GetCurrentProcessId());
1711 apr_proc_mutex_destroy(start_mutex);
1713 CloseHandle(restart_event);
1714 CloseHandle(shutdown_event);
1720 return 0; /* Restart */
1723 static void winnt_hooks(apr_pool_t *p)
1725 /* Our open_logs hook function must run before the core's, or stderr
1726 * will be redirected to a file, and the messages won't print to the
1729 static const char *const aszSucc[] = {"core.c", NULL};
1731 ap_hook_pre_config(winnt_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1732 ap_hook_check_config(winnt_check_config, NULL, NULL, APR_HOOK_MIDDLE);
1733 ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
1734 ap_hook_child_init(winnt_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1735 ap_hook_open_logs(winnt_open_logs, NULL, aszSucc, APR_HOOK_REALLY_FIRST);
1738 AP_MODULE_DECLARE_DATA module mpm_winnt_module = {
1740 winnt_rewrite_args, /* hook to run before apache parses args */
1741 NULL, /* create per-directory config structure */
1742 NULL, /* merge per-directory config structures */
1743 NULL, /* create per-server config structure */
1744 NULL, /* merge per-server config structures */
1745 winnt_cmds, /* command apr_table_t */
1746 winnt_hooks /* register_hooks */
1749 #endif /* def WIN32 */