]> granicus.if.org Git - apache/blob - server/mpm/winnt/mpm_winnt.c
this security API needs some loving, a warning at least for SYSTEM/LocalSystem
[apache] / server / mpm / winnt / mpm_winnt.c
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #ifdef WIN32
18
19 #include "httpd.h"
20 #include "http_main.h"
21 #include "http_log.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"
29 #include "apr_lib.h"
30 #include "apr_shm.h"
31 #include "apr_thread_mutex.h"
32 #include "ap_mpm.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"
38 #include <malloc.h>
39 #include "apr_atomic.h"
40
41
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.
44  */
45 extern apr_shm_t *ap_scoreboard_shm;
46
47 /* ap_my_generation are used by the scoreboard code */
48 ap_generation_t volatile ap_my_generation=0;
49
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 */
53
54 static char ap_coredump_dir[MAX_STRING_LEN];
55
56 static int one_process = 0;
57 static char const* signal_arg = NULL;
58
59 OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
60
61 /* set by child_main to STACK_SIZE_PARAM_IS_A_RESERVATION for NT >= 5.1 (XP/2003) */
62 DWORD stack_res_flag;
63
64 static DWORD parent_pid;
65 DWORD my_pid;
66
67 /* used by parent to signal the child to start and exit */
68 apr_proc_mutex_t *start_mutex;
69 HANDLE exit_event;
70
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;
75
76 /* shared by service.c as global, although
77  * perhaps it should be private.
78  */
79 apr_pool_t *pconf;
80
81 /* on several occasions we don't have the global server context
82  * although it's needed for logging, etc.
83  */
84 server_rec *ap_server_conf;
85
86 /* definitions from child.c */
87 void child_main(apr_pool_t *pconf);
88
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.
93  */
94 static HANDLE pipe;
95
96 /* Stub functions until this MPM supports the connection status API */
97
98 AP_DECLARE(void) ap_update_connection_status(long conn_id, const char *key, \
99                                              const char *value)
100 {
101     /* NOP */
102 }
103
104 AP_DECLARE(void) ap_reset_connection_status(long conn_id)
105 {
106     /* NOP */
107 }
108
109 AP_DECLARE(apr_array_header_t *) ap_get_status_table(apr_pool_t *p)
110 {
111     /* NOP */
112     return NULL;
113 }
114
115 /*
116  * Command processors
117  */
118
119 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg)
120 {
121     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
122     if (err != NULL) {
123         return err;
124     }
125
126     ap_threads_per_child = atoi(arg);
127     return NULL;
128 }
129 static const char *set_thread_limit (cmd_parms *cmd, void *dummy, const char *arg)
130 {
131     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
132     if (err != NULL) {
133         return err;
134     }
135
136     thread_limit = atoi(arg);
137     return NULL;
138 }
139
140 static const command_rec winnt_cmds[] = {
141 LISTEN_COMMANDS,
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"),
146 { NULL }
147 };
148
149
150 /*
151  * Signalling Apache on NT.
152  *
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
157  * called
158  *
159  *    apPID_shutdown
160  *    apPID_restart
161  *
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
169  * httpd.pid file.
170  *
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.
174  *
175  * On entry, type gives the event to signal. 0 means shutdown, 1 means
176  * graceful restart.
177  */
178 /*
179  * Initialise the signal names, in the global variables signal_name_prefix,
180  * signal_restart_name and signal_shutdown_name.
181  */
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)
187 {
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);
193 }
194
195 AP_DECLARE(void) ap_signal_parent(ap_signal_parent_e type)
196 {
197     HANDLE e;
198     char *signal_name;
199
200     if (parent_pid == my_pid) {
201         switch(type) {
202            case SIGNAL_PARENT_SHUTDOWN:
203            {
204                SetEvent(shutdown_event);
205                break;
206            }
207            /* This MPM supports only graceful restarts right now */
208            case SIGNAL_PARENT_RESTART:
209            case SIGNAL_PARENT_RESTART_GRACEFUL:
210            {
211                SetEvent(restart_event);
212                break;
213            }
214         }
215         return;
216     }
217
218     switch(type) {
219        case SIGNAL_PARENT_SHUTDOWN:
220        {
221            signal_name = signal_shutdown_name;
222            break;
223        }
224        /* This MPM supports only graceful restarts right now */
225        case SIGNAL_PARENT_RESTART:
226        case SIGNAL_PARENT_RESTART_GRACEFUL:
227        {
228            signal_name = signal_restart_name;
229            break;
230        }
231        default:
232            return;
233     }
234
235     e = OpenEvent(EVENT_MODIFY_STATE, FALSE, signal_name);
236     if (!e) {
237         /* Um, problem, can't signal the parent, which means we can't
238          * signal ourselves to die. Ignore for now...
239          */
240         ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf,
241                      "OpenEvent on %s event", signal_name);
242         return;
243     }
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);
248         CloseHandle(e);
249         return;
250     }
251     CloseHandle(e);
252 }
253
254
255 /*
256  * Passed the following handles [in sync with send_handles_to_child()]
257  *
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]
262  */
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)
266 {
267     HANDLE hScore;
268     HANDLE ready_event;
269     HANDLE os_start;
270     DWORD BytesRead;
271     void *sb_shared;
272     apr_status_t rv;
273
274     /* *** We now do this was back in winnt_rewrite_args
275      * pipe = GetStdHandle(STD_INPUT_HANDLE);
276      */
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);
283     }
284
285     SetEvent(ready_event);
286     CloseHandle(ready_event);
287
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);
294     }
295
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);
302     }
303     *child_start_mutex = NULL;
304     if ((rv = apr_os_proc_mutex_put(child_start_mutex, &os_start, s->process->pool))
305             != APR_SUCCESS) {
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);
309     }
310
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);
317     }
318     *scoreboard_shm = NULL;
319     if ((rv = apr_os_shm_put(scoreboard_shm, &hScore, s->process->pool))
320             != APR_SUCCESS) {
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);
324     }
325
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);
331     }
332     /* We must 'initialize' the scoreboard to relink all the
333      * process-local pointer arrays into the shared memory block.
334      */
335     ap_init_scoreboard(sb_shared);
336
337     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
338                  "Child %d: Retrieved our scoreboard from the parent.", my_pid);
339 }
340
341
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,
347                                  HANDLE hProcess,
348                                  apr_file_t *child_in)
349 {
350     apr_status_t rv;
351     HANDLE hCurrentProcess = GetCurrentProcess();
352     HANDLE hDup;
353     HANDLE os_start;
354     HANDLE hScore;
355     apr_size_t BytesWritten;
356
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");
361         return -1;
362     }
363     if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
364             != APR_SUCCESS) {
365         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
366                      "Parent: Unable to send the exit event handle to the child");
367         return -1;
368     }
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");
373         return -1;
374     }
375     if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
376             != APR_SUCCESS) {
377         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
378                      "Parent: Unable to send the exit event handle to the child");
379         return -1;
380     }
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");
384         return -1;
385     }
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");
390         return -1;
391     }
392     if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
393             != APR_SUCCESS) {
394         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
395                      "Parent: Unable to send the start mutex to the child");
396         return -1;
397     }
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");
401         return -1;
402     }
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");
407         return -1;
408     }
409     if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
410             != APR_SUCCESS) {
411         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
412                      "Parent: Unable to send the scoreboard handle to the child");
413         return -1;
414     }
415
416     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
417                  "Parent: Sent the scoreboard to the child");
418     return 0;
419 }
420
421
422 /*
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.
427  */
428 void get_listeners_from_parent(server_rec *s)
429 {
430     WSAPROTOCOL_INFO WSAProtocolInfo;
431     ap_listen_rec *lr;
432     DWORD BytesRead;
433     int lcnt = 0;
434     SOCKET nsd;
435     HANDLE hProcess = GetCurrentProcess();
436     HANDLE dup;
437
438     /* Set up a default listener if necessary */
439     if (ap_listeners == NULL) {
440         ap_listen_rec *lr;
441         lr = apr_palloc(s->process->pool, sizeof(ap_listen_rec));
442         lr->sd = NULL;
443         lr->next = ap_listeners;
444         ap_listeners = lr;
445     }
446
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.
449      *
450      * *** We now do this was back in winnt_rewrite_args
451      * pipe = GetStdHandle(STD_INPUT_HANDLE);
452      */
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);
459         }
460
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);
467         }
468
469         if (DuplicateHandle(hProcess, (HANDLE) nsd, hProcess, &dup,
470                             0, FALSE, DUPLICATE_SAME_ACCESS)) {
471             closesocket(nsd);
472             nsd = (SOCKET) dup;
473         }
474
475         apr_os_sock_put(&lr->sd, &nsd, s->process->pool);
476     }
477
478     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
479                  "Child %d: retrieved %d listeners from parent", my_pid, lcnt);
480 }
481
482
483 static int send_listeners_to_child(apr_pool_t *p, DWORD dwProcessId,
484                                    apr_file_t *child_in)
485 {
486     apr_status_t rv;
487     int lcnt = 0;
488     ap_listen_rec *lr;
489     LPWSAPROTOCOL_INFO  lpWSAProtocolInfo;
490     apr_size_t BytesWritten;
491
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.
495      */
496     for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) {
497         apr_os_sock_t nsd;
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",
502                      nsd, dwProcessId);
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 );
507             return -1;
508         }
509
510         if ((rv = apr_file_write_full(child_in, lpWSAProtocolInfo,
511                                       sizeof(WSAPROTOCOL_INFO), &BytesWritten))
512                 != APR_SUCCESS) {
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 );
515             return -1;
516         }
517     }
518
519     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
520                  "Parent: Sent %d listeners to child %d", lcnt, dwProcessId);
521     return 0;
522 }
523
524 enum waitlist_e {
525     waitlist_ready = 0,
526     waitlist_term = 1
527 };
528
529 static int create_process(apr_pool_t *p, HANDLE *child_proc, HANDLE *child_exit_event,
530                           DWORD *child_pid)
531 {
532     /* These NEVER change for the lifetime of this parent
533      */
534     static char **args = NULL;
535     static char pidbuf[28];
536
537     apr_status_t rv;
538     apr_pool_t *ptemp;
539     apr_procattr_t *attr;
540     apr_proc_t new_child;
541     HANDLE hExitEvent;
542     HANDLE waitlist[2];  /* see waitlist_e */
543     char *cmd;
544     char *cwd;
545     char **env;
546     int envc;
547
548     apr_pool_create_ex(&ptemp, p, NULL, NULL);
549
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...
553      */
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");
561     }
562
563     if (!args) {
564         /* Build the args array, only once since it won't change
565          * for the lifetime of this parent process.
566          */
567         if ((rv = ap_os_proc_filepath(&cmd, ptemp))
568                 != APR_SUCCESS) {
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);
573             return -1;
574         }
575
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;
582     }
583     else {
584         cmd = args[0];
585     }
586
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);
593         return -1;
594     }
595
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);
602         return -1;
603     }
604
605     /* Create the child_exit_event */
606     hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
607     if (!hExitEvent) {
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]);
612         return -1;
613     }
614
615     /* Build the env array */
616     for (envc = 0; _environ[envc]; ++envc) {
617         ;
618     }
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);
622     env[envc] = pidbuf;
623     env[envc + 1] = NULL;
624
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);
633         return -1;
634     }
635
636     ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
637                  "Parent: Created child process %d", new_child.pid);
638
639     if (send_handles_to_child(ptemp, waitlist[waitlist_ready], hExitEvent,
640                               start_mutex, ap_scoreboard_shm,
641                               new_child.hproc, new_child.in)) {
642         /*
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.
646          */
647         SetEvent(hExitEvent);
648         apr_pool_destroy(ptemp);
649         CloseHandle(hExitEvent);
650         CloseHandle(waitlist[waitlist_ready]);
651         CloseHandle(new_child.hproc);
652         return -1;
653     }
654
655     /* Important:
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.
660      */
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) {
665         /*
666          * Outch... that isn't a ready signal. It's dead, Jim!
667          */
668         SetEvent(hExitEvent);
669         apr_pool_destroy(ptemp);
670         CloseHandle(hExitEvent);
671         CloseHandle(new_child.hproc);
672         return -1;
673     }
674
675     if (send_listeners_to_child(ptemp, new_child.pid, new_child.in)) {
676         /*
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.
680          */
681         SetEvent(hExitEvent);
682         apr_pool_destroy(ptemp);
683         CloseHandle(hExitEvent);
684         CloseHandle(new_child.hproc);
685         return -1;
686     }
687
688     apr_file_close(new_child.in);
689
690     *child_exit_event = hExitEvent;
691     *child_proc = new_child.hproc;
692     *child_pid = new_child.pid;
693
694     return 0;
695 }
696
697 /***********************************************************************
698  * master_main()
699  * master_main() runs in the parent process.  It creates the child
700  * process which handles HTTP requests then waits on one of three
701  * events:
702  *
703  * restart_event
704  * -------------
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.
714  *
715  * shutdown_event
716  * --------------
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.
724  *
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
732  * condtion.
733  *
734  * master_main uses the child_exit_event to signal the child process
735  * to exit.
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)
742 {
743     int rv, cld;
744     int restart_pending;
745     int shutdown_pending;
746     HANDLE child_exit_event;
747     HANDLE event_handles[NUM_WAIT_HANDLES];
748     DWORD child_pid;
749
750     restart_pending = shutdown_pending = 0;
751
752     event_handles[SHUTDOWN_HANDLE] = shutdown_event;
753     event_handles[RESTART_HANDLE] = restart_event;
754
755     /* Create a single child process */
756     rv = create_process(pconf, &event_handles[CHILD_HANDLE],
757                         &child_exit_event, &child_pid);
758     if (rv < 0)
759     {
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;
763         goto die_now;
764     }
765     if (!strcasecmp(signal_arg, "runservice")) {
766         mpm_service_started();
767     }
768
769     /* Update the scoreboard. Note that there is only a single active
770      * child at once.
771      */
772     ap_scoreboard_image->parent[0].quiescing = 0;
773     ap_scoreboard_image->parent[0].pid = child_pid;
774
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;
784     }
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;
790     }
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)");
799         }
800     }
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.
804          */
805         restart_pending = 1;
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.");
811         }
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]);
816         }
817         /* Don't wait to verify that the child process really exits,
818          * just move on with the restart.
819          */
820         CloseHandle(event_handles[CHILD_HANDLE]);
821         event_handles[CHILD_HANDLE] = NULL;
822     }
823     else {
824         /* The child process exited prematurely due to a fatal error. */
825         DWORD exitcode;
826         if (!GetExitCodeProcess(event_handles[CHILD_HANDLE], &exitcode)) {
827             /* HUH? We did exit, didn't we? */
828             exitcode = APEXIT_CHILDFATAL;
829         }
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;
836         }
837         else {
838             int i;
839             restart_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);
844             }
845         }
846         CloseHandle(event_handles[CHILD_HANDLE]);
847         event_handles[CHILD_HANDLE] = NULL;
848     }
849     if (restart_pending) {
850         ++ap_my_generation;
851         ap_scoreboard_image->global->running_generation = ap_my_generation;
852     }
853 die_now:
854     if (shutdown_pending)
855     {
856         int timeout = 30000;  /* Timeout is milliseconds */
857         winnt_mpm_state = AP_MPMQ_STOPPING;
858
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.
862          */
863         if (!strcasecmp(signal_arg, "runservice")) {
864             mpm_service_stopping();
865         }
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]);
870         }
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;
878             }
879             else {
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;
885             }
886         }
887         CloseHandle(child_exit_event);
888         return 0;  /* Tell the caller we do not want to restart */
889     }
890     winnt_mpm_state = AP_MPMQ_STARTING;
891     CloseHandle(child_exit_event);
892     return 1;      /* Tell the caller we want a restart */
893 }
894
895 /* service_nt_main_fn needs to append the StartService() args
896  * outside of our call stack and thread as the service starts...
897  */
898 apr_array_header_t *mpm_new_argv;
899
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.
903  */
904
905 AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
906 {
907     switch(query_code){
908         case AP_MPMQ_MAX_DAEMON_USED:
909             *result = MAXIMUM_WAIT_OBJECTS;
910             return APR_SUCCESS;
911         case AP_MPMQ_IS_THREADED:
912             *result = AP_MPMQ_STATIC;
913             return APR_SUCCESS;
914         case AP_MPMQ_IS_FORKED:
915             *result = AP_MPMQ_NOT_SUPPORTED;
916             return APR_SUCCESS;
917         case AP_MPMQ_HARD_LIMIT_DAEMONS:
918             *result = HARD_SERVER_LIMIT;
919             return APR_SUCCESS;
920         case AP_MPMQ_HARD_LIMIT_THREADS:
921             *result = thread_limit;
922             return APR_SUCCESS;
923         case AP_MPMQ_MAX_THREADS:
924             *result = ap_threads_per_child;
925             return APR_SUCCESS;
926         case AP_MPMQ_MIN_SPARE_DAEMONS:
927             *result = 0;
928             return APR_SUCCESS;
929         case AP_MPMQ_MIN_SPARE_THREADS:
930             *result = 0;
931             return APR_SUCCESS;
932         case AP_MPMQ_MAX_SPARE_DAEMONS:
933             *result = 0;
934             return APR_SUCCESS;
935         case AP_MPMQ_MAX_SPARE_THREADS:
936             *result = 0;
937             return APR_SUCCESS;
938         case AP_MPMQ_MAX_REQUESTS_DAEMON:
939             *result = ap_max_requests_per_child;
940             return APR_SUCCESS;
941         case AP_MPMQ_MAX_DAEMONS:
942             *result = 0;
943             return APR_SUCCESS;
944         case AP_MPMQ_MPM_STATE:
945             *result = winnt_mpm_state;
946             return APR_SUCCESS;
947     }
948     return APR_ENOTIMPL;
949 }
950
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;
957
958 void winnt_rewrite_args(process_rec *process)
959 {
960     /* Handle the following SCM aspects in this phase:
961      *
962      *   -k runservice [transition in service context only]
963      *   -k install
964      *   -k config
965      *   -k uninstall
966      *   -k stop
967      *   -k shutdown (same as -k stop). Maintained for backward compatability.
968      *
969      * We can't leave this phase until we know our identity
970      * and modify the command arguments appropriately.
971      *
972      * We do not care if the .conf file exists or is parsable when
973      * attempting to stop or uninstall a service.
974      */
975     apr_status_t rv;
976     char *def_server_root;
977     char *binpath;
978     char optbuf[3];
979     const char *optarg;
980     int fixed_args;
981     char *pid;
982     apr_getopt_t *opt;
983     int running_as_service = 1;
984     int errout = 0;
985     apr_file_t *nullfile;
986
987     pconf = process->pconf;
988
989     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
990     GetVersionEx(&osver);
991
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
994      */
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;
999     }
1000
1001     /* AP_PARENT_PID is only valid in the child */
1002     pid = getenv("AP_PARENT_PID");
1003     if (pid)
1004     {
1005         HANDLE filehand;
1006         HANDLE hproc = GetCurrentProcess();
1007
1008         /* This is the child */
1009         my_pid = GetCurrentProcessId();
1010         parent_pid = (DWORD) atol(pid);
1011
1012         /* Prevent holding open the (nonexistant) console */
1013         ap_real_exit_code = 0;
1014
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()
1019          */
1020         pipe = GetStdHandle(STD_INPUT_HANDLE);
1021         if (DuplicateHandle(hproc, pipe,
1022                             hproc, &filehand, 0, FALSE,
1023                             DUPLICATE_SAME_ACCESS)) {
1024             pipe = filehand;
1025         }
1026
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!
1032          */
1033         {
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);
1038         }
1039
1040         /* This child needs the existing stderr opened for logging,
1041          * already 
1042          */
1043
1044
1045         /* The parent is responsible for providing the
1046          * COMPLETE ARGUMENTS REQUIRED to the child.
1047          *
1048          * No further argument parsing is needed, but
1049          * for good measure we will provide a simple
1050          * signal string for later testing.
1051          */
1052         signal_arg = "runchild";
1053         return;
1054     }
1055
1056     /* This is the parent, we have a long way to go :-) */
1057     parent_pid = my_pid = GetCurrentProcessId();
1058
1059     /* This behavior is voided by setting real_exit_code to 0 */
1060     atexit(hold_console_open_on_error);
1061
1062     /* Rewrite process->argv[];
1063      *
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
1067      *
1068      * The end result will look like:
1069      *
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
1074      */
1075     if ((rv = ap_os_proc_filepath(&binpath, process->pconf))
1076             != APR_SUCCESS) {
1077         ap_log_error(APLOG_MARK,APLOG_CRIT, rv, NULL,
1078                      "Failed to get the full path of %s", process->argv[0]);
1079         exit(APEXIT_INIT);
1080     }
1081     /* WARNING: There is an implict assumption here that the
1082      * executable resides in ServerRoot or ServerRoot\bin
1083      */
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';
1090     }
1091     apr_filepath_merge(&def_server_root, NULL, binpath,
1092                        APR_FILEPATH_TRUENAME, process->pool);
1093
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.
1098      */
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;
1104
1105     fixed_args = mpm_new_argv->nelts;
1106
1107     optbuf[0] = '-';
1108     optbuf[2] = '\0';
1109     apr_getopt_init(&opt, process->pool, process->argc, (char**) process->argv);
1110     opt->errfn = NULL;
1111     while ((rv = apr_getopt(opt, "wn:k:" AP_SERVER_BASEARGS,
1112                             optbuf + 1, &optarg)) == APR_SUCCESS) {
1113         switch (optbuf[1]) {
1114
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!
1117          */
1118         case 'w':
1119             if (ap_real_exit_code)
1120                 ap_real_exit_code = 2;
1121             break;
1122
1123         case 'n':
1124             service_set = mpm_service_set_name(process->pool, &service_name,
1125                                                optarg);
1126             break;
1127
1128         case 'k':
1129             signal_arg = optarg;
1130             break;
1131
1132         case 'E':
1133             errout = 1;
1134             /* Fall through so the Apache main() handles the 'E' arg */
1135         default:
1136             *(const char **)apr_array_push(mpm_new_argv) =
1137                 apr_pstrdup(process->pool, optbuf);
1138
1139             if (optarg) {
1140                 *(const char **)apr_array_push(mpm_new_argv) = optarg;
1141             }
1142             break;
1143         }
1144     }
1145
1146     /* back up to capture the bad argument */
1147     if (rv == APR_BADCH || rv == APR_BADARG) {
1148         opt->ind--;
1149     }
1150
1151     while (opt->ind < opt->argc) {
1152         *(const char **)apr_array_push(mpm_new_argv) =
1153             apr_pstrdup(process->pool, opt->argv[opt->ind++]);
1154     }
1155
1156     /* Track the number of args actually entered by the user */
1157     inst_argc = mpm_new_argv->nelts - fixed_args;
1158
1159     /* Provide a default 'run' -k arg to simplify signal_arg tests */
1160     if (!signal_arg)
1161     {
1162         signal_arg = "run";
1163         running_as_service = 0;
1164     }
1165
1166     if (!strcasecmp(signal_arg, "runservice"))
1167     {
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
1172          * add for us.
1173          *
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.
1179          */
1180         apr_filepath_set(def_server_root, process->pool);
1181
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.
1185          *
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.
1188          */
1189         if (!errout) {
1190             mpm_nt_eventlog_stderr_open(service_name, process->pool);
1191         }
1192         service_to_start_success = mpm_service_to_start(&service_name,
1193                                                         process->pool);
1194         if (service_to_start_success == APR_SUCCESS) {
1195             service_set = APR_SUCCESS;
1196         }
1197
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()
1202          */
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)
1208                     == APR_SUCCESS)
1209                 apr_file_dup2(nullstdout, nullfile, process->pool);
1210             apr_file_close(nullfile);
1211         }
1212     }
1213
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);
1218     }
1219
1220     if (!strcasecmp(signal_arg, "install")) /* -k install */
1221     {
1222         if (service_set == APR_SUCCESS)
1223         {
1224             ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
1225                  "%s: Service is already installed.", service_name);
1226             exit(APEXIT_INIT);
1227         }
1228     }
1229     else if (running_as_service)
1230     {
1231         if (service_set == APR_SUCCESS)
1232         {
1233             /* Attempt to Uninstall, or stop, before
1234              * we can read the arguments or .conf files
1235              */
1236             if (!strcasecmp(signal_arg, "uninstall")) {
1237                 rv = mpm_service_uninstall();
1238                 exit(rv);
1239             }
1240
1241             if ((!strcasecmp(signal_arg, "stop")) ||
1242                 (!strcasecmp(signal_arg, "shutdown"))) {
1243                 mpm_signal_service(process->pool, 0);
1244                 exit(0);
1245             }
1246
1247             rv = mpm_merge_service_args(process->pool, mpm_new_argv,
1248                                         fixed_args);
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);
1253             }
1254             else  {
1255                 ap_log_error(APLOG_MARK,APLOG_WARNING, rv, NULL,
1256                              "No installed ConfigArgs for the service "
1257                              "\"%s\", using Apache defaults.", service_name);
1258             }
1259         }
1260         else
1261         {
1262             ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL,
1263                  "No installed service named \"%s\".", service_name);
1264             exit(APEXIT_INIT);
1265         }
1266     }
1267     if (strcasecmp(signal_arg, "install") && service_set && service_set != SERVICE_UNSET)
1268     {
1269         ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL,
1270              "No installed service named \"%s\".", service_name);
1271         exit(APEXIT_INIT);
1272     }
1273
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.
1277      */
1278     inst_argv = (const char * const *)mpm_new_argv->elts
1279         + mpm_new_argv->nelts - inst_argc;
1280
1281     /* Now, do service install or reconfigure then proceed to
1282      * post_config to test the installed configuration.
1283      */
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) {
1288             exit(rv);
1289         }
1290
1291         fprintf(stderr,"Testing httpd.conf....\n");
1292         fprintf(stderr,"Errors reported here must be corrected before the "
1293                 "service can be started.\n");
1294     }
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) {
1299             exit(rv);
1300         }
1301
1302         fprintf(stderr,"Testing httpd.conf....\n");
1303         fprintf(stderr,"Errors reported here must be corrected before the "
1304                 "service can be started.\n");
1305     }
1306
1307     process->argc = mpm_new_argv->nelts;
1308     process->argv = (const char * const *) mpm_new_argv->elts;
1309 }
1310
1311
1312 static int winnt_pre_config(apr_pool_t *pconf_, apr_pool_t *plog, apr_pool_t *ptemp)
1313 {
1314     /* Handle the following SCM aspects in this phase:
1315      *
1316      *   -k runservice [WinNT errors logged from rewrite_args]
1317      */
1318
1319     /* Initialize shared static objects.
1320      * TODO: Put config related statics into an sconf structure.
1321      */
1322     pconf = pconf_;
1323
1324     if (ap_exists_config_define("ONE_PROCESS") ||
1325         ap_exists_config_define("DEBUG"))
1326         one_process = -1;
1327
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.
1331      */
1332     ap_sys_privileges_handlers(1);
1333
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.",
1338                      service_name);
1339         exit(APEXIT_INIT);
1340     }
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.
1346          */
1347         apr_file_t *nullfile;
1348         apr_status_t rv;
1349         apr_pool_t *pproc = apr_pool_parent_get(pconf);
1350
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)
1356                     == APR_SUCCESS)
1357                 apr_file_dup2(nullstdout, nullfile, pproc);
1358             apr_file_close(nullfile);
1359         }
1360     }
1361
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;
1368
1369     apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1370
1371     return OK;
1372 }
1373
1374 static int winnt_check_config(apr_pool_t *pconf, apr_pool_t *plog,
1375                               apr_pool_t *ptemp, server_rec* s)
1376 {
1377     int is_parent;
1378     static int restart_num = 0;
1379     int startup = 0;
1380
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) {
1384         startup = 1;
1385     }
1386
1387     if (thread_limit > MAX_THREAD_LIMIT) {
1388         if (startup) {
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);
1400         }
1401         thread_limit = MAX_THREAD_LIMIT;
1402     }
1403     else if (thread_limit < 1) {
1404         if (startup) {
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",
1411                          thread_limit);
1412         }
1413         thread_limit = 1;
1414     }
1415
1416     /* You cannot change ThreadLimit across a restart; ignore
1417      * any such attempts.
1418      */
1419     if (!first_thread_limit) {
1420         first_thread_limit = thread_limit;
1421     }
1422     else if (thread_limit != first_thread_limit) {
1423         /* Don't need a startup console version here */
1424         if (is_parent) {
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);
1429         }
1430         thread_limit = first_thread_limit;
1431     }
1432
1433     if (ap_threads_per_child > thread_limit) {
1434         if (startup) {
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 "
1443                          "directive.");
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);
1449         }
1450         ap_threads_per_child = thread_limit;
1451     }
1452     else if (ap_threads_per_child < 1) {
1453         if (startup) {
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);
1461         }
1462         ap_threads_per_child = 1;
1463     }
1464
1465     return OK;
1466 }
1467
1468 static int winnt_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec* s)
1469 {
1470     static int restart_num = 0;
1471     apr_status_t rv = 0;
1472
1473     /* Handle the following SCM aspects in this phase:
1474      *
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)
1477      *   -k start
1478      *   -k restart
1479      *   -k runservice [Win95, only once - after we parsed the config]
1480      *
1481      * because all of these signals are useful _only_ if there
1482      * is a valid conf\httpd.conf environment to start.
1483      *
1484      * We reached this phase by avoiding errors that would cause
1485      * these options to fail unexpectedly in another process.
1486      */
1487
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.
1492          */
1493         apr_pool_destroy(s->process->pool);
1494         apr_terminate();
1495         exit(0);
1496     }
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.
1501          */
1502         apr_pool_destroy(s->process->pool);
1503         apr_terminate();
1504         exit(0);
1505     }
1506
1507     if (!strcasecmp(signal_arg, "start")) {
1508         ap_listen_rec *lr;
1509
1510         /* Close the listening sockets. */
1511         for (lr = ap_listeners; lr; lr = lr->next) {
1512             apr_socket_close(lr->sd);
1513             lr->active = 0;
1514         }
1515         rv = mpm_service_start(ptemp, inst_argc, inst_argv);
1516         apr_pool_destroy(s->process->pool);
1517         apr_terminate();
1518         exit (rv);
1519     }
1520
1521     if (!strcasecmp(signal_arg, "restart")) {
1522         mpm_signal_service(ptemp, 1);
1523         apr_pool_destroy(s->process->pool);
1524         apr_terminate();
1525         exit (rv);
1526     }
1527
1528     if (parent_pid == my_pid)
1529     {
1530         if (restart_num++ == 1)
1531         {
1532             /* This code should be run once in the parent and not run
1533              * across a restart
1534              */
1535             PSECURITY_ATTRIBUTES sa = GetNullACL();  /* returns NULL if invalid (Win95?) */
1536             setup_signal_names(apr_psprintf(pconf,"ap%d", parent_pid));
1537
1538             ap_log_pid(pconf, ap_pid_fname);
1539
1540             /* Create shutdown event, apPID_shutdown, where PID is the parent
1541              * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
1542              */
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;
1549             }
1550
1551             /* Create restart event, apPID_restart, where PID is the parent
1552              * Apache process ID. Restart is signaled by 'apache -k restart'.
1553              */
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;
1561             }
1562             CleanNullACL((void *)sa);
1563
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.
1567              */
1568             rv =  apr_proc_mutex_create(&start_mutex, NULL,
1569                                         APR_LOCK_DEFAULT,
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.",
1574                              service_name);
1575                 return HTTP_INTERNAL_SERVER_ERROR;
1576             }
1577         }
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.
1581         */
1582         if (strcasecmp(signal_arg, "runservice"))
1583             mpm_start_console_handler();
1584     }
1585     else /* parent_pid != my_pid */
1586     {
1587         mpm_start_child_console_handler();
1588     }
1589     return OK;
1590 }
1591
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.
1594  */
1595 static int winnt_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
1596 {
1597     /* Initialize shared static objects.
1598      */
1599     ap_server_conf = s;
1600
1601     if (parent_pid != my_pid) {
1602         return OK;
1603     }
1604
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.)
1609      */
1610     if (!strcasecmp(signal_arg, "restart")
1611             || !strcasecmp(signal_arg, "config")) {
1612         return OK;
1613     }
1614
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");
1618         return DONE;
1619     }
1620
1621     return OK;
1622 }
1623
1624 static void winnt_child_init(apr_pool_t *pchild, struct server_rec *s)
1625 {
1626     apr_status_t rv;
1627
1628     setup_signal_names(apr_psprintf(pchild,"ap%d", parent_pid));
1629
1630     /* This is a child process, not in single process mode */
1631     if (!one_process) {
1632         /* Set up events and the scoreboard */
1633         get_handles_from_parent(s, &exit_event, &start_mutex,
1634                                 &ap_scoreboard_shm);
1635
1636         /* Set up the listeners */
1637         get_listeners_from_parent(s);
1638
1639         /* Done reading from the parent, close that channel */
1640         CloseHandle(pipe);
1641
1642         ap_my_generation = ap_scoreboard_image->global->running_generation;
1643     }
1644     else {
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);
1653         }
1654
1655         /* Borrow the shutdown_even as our _child_ loop exit event */
1656         exit_event = shutdown_event;
1657     }
1658 }
1659
1660
1661 AP_DECLARE(int) ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s )
1662 {
1663     static int restart = 0;            /* Default is "not a restart" */
1664
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.
1669      */
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) {
1673             return 1;
1674         }
1675     }
1676
1677     if ((parent_pid != my_pid) || one_process)
1678     {
1679         /* The child process or in one_process (debug) mode
1680          */
1681         ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
1682                      "Child %d: Child process is running", my_pid);
1683
1684         child_main(pconf);
1685
1686         ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
1687                      "Child %d: Child process is exiting", my_pid);
1688         return 1;
1689     }
1690     else
1691     {
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());
1698
1699         restart = master_main(ap_server_conf, shutdown_event, restart_event);
1700
1701         if (!restart)
1702         {
1703             /* Shutting down. Clean up... */
1704             const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1705
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());
1710             }
1711             apr_proc_mutex_destroy(start_mutex);
1712
1713             CloseHandle(restart_event);
1714             CloseHandle(shutdown_event);
1715
1716             return 1;
1717         }
1718     }
1719
1720     return 0; /* Restart */
1721 }
1722
1723 static void winnt_hooks(apr_pool_t *p)
1724 {
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
1727      * console.
1728      */
1729     static const char *const aszSucc[] = {"core.c", NULL};
1730
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);
1736 }
1737
1738 AP_MODULE_DECLARE_DATA module mpm_winnt_module = {
1739     MPM20_MODULE_STUFF,
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 */
1747 };
1748
1749 #endif /* def WIN32 */