]> granicus.if.org Git - apache/blob - server/mpm/winnt/mpm_winnt.c
fix some typos in comments
[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 "apr_general.h"
34 #include "ap_config.h"
35 #include "ap_listen.h"
36 #include "mpm_default.h"
37 #include "mpm_winnt.h"
38 #include "mpm_common.h"
39 #include <malloc.h>
40 #include "apr_atomic.h"
41 #include "scoreboard.h"
42
43 #ifdef __WATCOMC__
44 #define _environ environ
45 #endif
46
47 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION /* missing on MinGW */
48 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
49 #endif
50
51 /* Because ap_setup_listeners() is skipped in the child, any merging
52  * of [::]:80 and 0.0.0.0:80 for AP_ENABLE_V4_MAPPED in the parent
53  * won't have taken place in the child, so the child will expect to
54  * read two sockets for "Listen 80" but the parent will send only
55  * one.
56  */
57 #ifdef AP_ENABLE_V4_MAPPED
58 #error The WinNT MPM does not currently support AP_ENABLE_V4_MAPPED
59 #endif
60
61 /* scoreboard.c does the heavy lifting; all we do is create the child
62  * score by moving a handle down the pipe into the child's stdin.
63  */
64 extern apr_shm_t *ap_scoreboard_shm;
65
66 /* my_generation is returned to the scoreboard code */
67 static volatile ap_generation_t my_generation=0;
68
69 /* Definitions of WINNT MPM specific config globals */
70 static HANDLE shutdown_event;  /* used to signal the parent to shutdown */
71 static HANDLE restart_event;   /* used to signal the parent to restart */
72
73 static int one_process = 0;
74 static char const* signal_arg = NULL;
75
76 OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */
77
78 /* set by child_main to STACK_SIZE_PARAM_IS_A_RESERVATION for NT >= 5.1 (XP/2003) */
79 DWORD stack_res_flag;
80
81 static DWORD parent_pid;
82 DWORD my_pid;
83
84 /* used by parent to signal the child to start and exit */
85 apr_proc_mutex_t *start_mutex;
86 HANDLE exit_event;
87
88 int ap_threads_per_child = 0;
89 static int thread_limit = 0;
90 static int first_thread_limit = 0;
91 int winnt_mpm_state = AP_MPMQ_STARTING;
92
93 /* shared by service.c as global, although
94  * perhaps it should be private.
95  */
96 apr_pool_t *pconf;
97
98 /* definitions from child.c */
99 void child_main(apr_pool_t *pconf);
100
101 /* Only one of these, the pipe from our parent, meant only for
102  * one child worker's consumption (not to be inherited!)
103  * XXX: decorate this name for the trunk branch, was left simplified
104  *      only to make the 2.2 patch trivial to read.
105  */
106 static HANDLE pipe;
107
108 /*
109  * Command processors
110  */
111
112 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, const char *arg)
113 {
114     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
115     if (err != NULL) {
116         return err;
117     }
118
119     ap_threads_per_child = atoi(arg);
120     return NULL;
121 }
122 static const char *set_thread_limit (cmd_parms *cmd, void *dummy, const char *arg)
123 {
124     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
125     if (err != NULL) {
126         return err;
127     }
128
129     thread_limit = atoi(arg);
130     return NULL;
131 }
132
133 static const command_rec winnt_cmds[] = {
134 LISTEN_COMMANDS,
135 AP_INIT_TAKE1("ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF,
136   "Number of threads each child creates" ),
137 AP_INIT_TAKE1("ThreadLimit", set_thread_limit, NULL, RSRC_CONF,
138   "Maximum worker threads in a server for this run of Apache"),
139 { NULL }
140 };
141
142 static void winnt_note_child_started(int slot, pid_t pid)
143 {
144     ap_scoreboard_image->parent[slot].pid = pid;
145     ap_run_child_status(ap_server_conf,
146                         ap_scoreboard_image->parent[slot].pid,
147                         my_generation, slot, MPM_CHILD_STARTED);
148 }
149
150 static void winnt_note_child_killed(int slot)
151 {
152     ap_run_child_status(ap_server_conf,
153                         ap_scoreboard_image->parent[slot].pid,
154                         ap_scoreboard_image->parent[slot].generation,
155                         slot, MPM_CHILD_EXITED);
156     ap_scoreboard_image->parent[slot].pid = 0;
157 }
158
159 /*
160  * Signalling Apache on NT.
161  *
162  * Under Unix, Apache can be told to shutdown or restart by sending various
163  * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
164  * we use "events" instead. The parent apache process goes into a loop
165  * where it waits forever for a set of events. Two of those events are
166  * called
167  *
168  *    apPID_shutdown
169  *    apPID_restart
170  *
171  * (where PID is the PID of the apache parent process). When one of these
172  * is signalled, the Apache parent performs the appropriate action. The events
173  * can become signalled through internal Apache methods (e.g. if the child
174  * finds a fatal error and needs to kill its parent), via the service
175  * control manager (the control thread will signal the shutdown event when
176  * requested to stop the Apache service), from the -k Apache command line,
177  * or from any external program which finds the Apache PID from the
178  * httpd.pid file.
179  *
180  * The signal_parent() function, below, is used to signal one of these events.
181  * It can be called by any child or parent process, since it does not
182  * rely on global variables.
183  *
184  * On entry, type gives the event to signal. 0 means shutdown, 1 means
185  * graceful restart.
186  */
187 /*
188  * Initialise the signal names, in the global variables signal_name_prefix,
189  * signal_restart_name and signal_shutdown_name.
190  */
191 #define MAX_SIGNAL_NAME 30  /* Long enough for apPID_shutdown, where PID is an int */
192 char signal_name_prefix[MAX_SIGNAL_NAME];
193 char signal_restart_name[MAX_SIGNAL_NAME];
194 char signal_shutdown_name[MAX_SIGNAL_NAME];
195 void setup_signal_names(char *prefix)
196 {
197     apr_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);
198     apr_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name),
199         "%s_shutdown", signal_name_prefix);
200     apr_snprintf(signal_restart_name, sizeof(signal_restart_name),
201         "%s_restart", signal_name_prefix);
202 }
203
204 AP_DECLARE(void) ap_signal_parent(ap_signal_parent_e type)
205 {
206     HANDLE e;
207     char *signal_name;
208
209     if (parent_pid == my_pid) {
210         switch(type) {
211            case SIGNAL_PARENT_SHUTDOWN:
212            {
213                SetEvent(shutdown_event);
214                break;
215            }
216            /* This MPM supports only graceful restarts right now */
217            case SIGNAL_PARENT_RESTART:
218            case SIGNAL_PARENT_RESTART_GRACEFUL:
219            {
220                SetEvent(restart_event);
221                break;
222            }
223         }
224         return;
225     }
226
227     switch(type) {
228        case SIGNAL_PARENT_SHUTDOWN:
229        {
230            signal_name = signal_shutdown_name;
231            break;
232        }
233        /* This MPM supports only graceful restarts right now */
234        case SIGNAL_PARENT_RESTART:
235        case SIGNAL_PARENT_RESTART_GRACEFUL:
236        {
237            signal_name = signal_restart_name;
238            break;
239        }
240        default:
241            return;
242     }
243
244     e = OpenEvent(EVENT_MODIFY_STATE, FALSE, signal_name);
245     if (!e) {
246         /* Um, problem, can't signal the parent, which means we can't
247          * signal ourselves to die. Ignore for now...
248          */
249         ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf,
250                      "OpenEvent on %s event", signal_name);
251         return;
252     }
253     if (SetEvent(e) == 0) {
254         /* Same problem as above */
255         ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf,
256                      "SetEvent on %s event", signal_name);
257         CloseHandle(e);
258         return;
259     }
260     CloseHandle(e);
261 }
262
263
264 /*
265  * Passed the following handles [in sync with send_handles_to_child()]
266  *
267  *   ready event [signal the parent immediately, then close]
268  *   exit event  [save to poll later]
269  *   start mutex [signal from the parent to begin accept()]
270  *   scoreboard shm handle [to recreate the ap_scoreboard]
271  */
272 static void get_handles_from_parent(server_rec *s, HANDLE *child_exit_event,
273                                     apr_proc_mutex_t **child_start_mutex,
274                                     apr_shm_t **scoreboard_shm)
275 {
276     HANDLE hScore;
277     HANDLE ready_event;
278     HANDLE os_start;
279     DWORD BytesRead;
280     void *sb_shared;
281     apr_status_t rv;
282
283     /* *** We now do this was back in winnt_rewrite_args
284      * pipe = GetStdHandle(STD_INPUT_HANDLE);
285      */
286     if (!ReadFile(pipe, &ready_event, sizeof(HANDLE),
287                   &BytesRead, (LPOVERLAPPED) NULL)
288         || (BytesRead != sizeof(HANDLE))) {
289         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
290                      "Child: Unable to retrieve the ready event from the parent");
291         exit(APEXIT_CHILDINIT);
292     }
293
294     SetEvent(ready_event);
295     CloseHandle(ready_event);
296
297     if (!ReadFile(pipe, child_exit_event, sizeof(HANDLE),
298                   &BytesRead, (LPOVERLAPPED) NULL)
299         || (BytesRead != sizeof(HANDLE))) {
300         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
301                      "Child: Unable to retrieve the exit event from the parent");
302         exit(APEXIT_CHILDINIT);
303     }
304
305     if (!ReadFile(pipe, &os_start, sizeof(os_start),
306                   &BytesRead, (LPOVERLAPPED) NULL)
307         || (BytesRead != sizeof(os_start))) {
308         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
309                      "Child: Unable to retrieve the start_mutex from the parent");
310         exit(APEXIT_CHILDINIT);
311     }
312     *child_start_mutex = NULL;
313     if ((rv = apr_os_proc_mutex_put(child_start_mutex, &os_start, s->process->pool))
314             != APR_SUCCESS) {
315         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
316                      "Child: Unable to access the start_mutex from the parent");
317         exit(APEXIT_CHILDINIT);
318     }
319
320     if (!ReadFile(pipe, &hScore, sizeof(hScore),
321                   &BytesRead, (LPOVERLAPPED) NULL)
322         || (BytesRead != sizeof(hScore))) {
323         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
324                      "Child: Unable to retrieve the scoreboard from the parent");
325         exit(APEXIT_CHILDINIT);
326     }
327     *scoreboard_shm = NULL;
328     if ((rv = apr_os_shm_put(scoreboard_shm, &hScore, s->process->pool))
329             != APR_SUCCESS) {
330         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
331                      "Child: Unable to access the scoreboard from the parent");
332         exit(APEXIT_CHILDINIT);
333     }
334
335     rv = ap_reopen_scoreboard(s->process->pool, scoreboard_shm, 1);
336     if (rv || !(sb_shared = apr_shm_baseaddr_get(*scoreboard_shm))) {
337         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
338                      "Child: Unable to reopen the scoreboard from the parent");
339         exit(APEXIT_CHILDINIT);
340     }
341     /* We must 'initialize' the scoreboard to relink all the
342      * process-local pointer arrays into the shared memory block.
343      */
344     ap_init_scoreboard(sb_shared);
345
346     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
347                  "Child: Retrieved our scoreboard from the parent.");
348 }
349
350
351 static int send_handles_to_child(apr_pool_t *p,
352                                  HANDLE child_ready_event,
353                                  HANDLE child_exit_event,
354                                  apr_proc_mutex_t *child_start_mutex,
355                                  apr_shm_t *scoreboard_shm,
356                                  HANDLE hProcess,
357                                  apr_file_t *child_in)
358 {
359     apr_status_t rv;
360     HANDLE hCurrentProcess = GetCurrentProcess();
361     HANDLE hDup;
362     HANDLE os_start;
363     HANDLE hScore;
364     apr_size_t BytesWritten;
365
366     if (!DuplicateHandle(hCurrentProcess, child_ready_event, hProcess, &hDup,
367         EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, 0)) {
368         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
369                      "Parent: Unable to duplicate the ready event handle for the child");
370         return -1;
371     }
372     if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
373             != APR_SUCCESS) {
374         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
375                      "Parent: Unable to send the exit event handle to the child");
376         return -1;
377     }
378     if (!DuplicateHandle(hCurrentProcess, child_exit_event, hProcess, &hDup,
379                          EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, 0)) {
380         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
381                      "Parent: Unable to duplicate the exit event handle for the child");
382         return -1;
383     }
384     if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
385             != APR_SUCCESS) {
386         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
387                      "Parent: Unable to send the exit event handle to the child");
388         return -1;
389     }
390     if ((rv = apr_os_proc_mutex_get(&os_start, child_start_mutex)) != APR_SUCCESS) {
391         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
392                      "Parent: Unable to retrieve the start mutex for the child");
393         return -1;
394     }
395     if (!DuplicateHandle(hCurrentProcess, os_start, hProcess, &hDup,
396                          SYNCHRONIZE, FALSE, 0)) {
397         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
398                      "Parent: Unable to duplicate the start mutex to the child");
399         return -1;
400     }
401     if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
402             != APR_SUCCESS) {
403         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
404                      "Parent: Unable to send the start mutex to the child");
405         return -1;
406     }
407     if ((rv = apr_os_shm_get(&hScore, scoreboard_shm)) != APR_SUCCESS) {
408         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
409                      "Parent: Unable to retrieve the scoreboard handle for the child");
410         return -1;
411     }
412     if (!DuplicateHandle(hCurrentProcess, hScore, hProcess, &hDup,
413                          FILE_MAP_READ | FILE_MAP_WRITE, FALSE, 0)) {
414         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
415                      "Parent: Unable to duplicate the scoreboard handle to the child");
416         return -1;
417     }
418     if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
419             != APR_SUCCESS) {
420         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
421                      "Parent: Unable to send the scoreboard handle to the child");
422         return -1;
423     }
424
425     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
426                  "Parent: Sent the scoreboard to the child");
427     return 0;
428 }
429
430
431 /*
432  * get_listeners_from_parent()
433  * The listen sockets are opened in the parent. This function, which runs
434  * exclusively in the child process, receives them from the parent and
435  * makes them availeble in the child.
436  */
437 static void get_listeners_from_parent(server_rec *s)
438 {
439     WSAPROTOCOL_INFO WSAProtocolInfo;
440     ap_listen_rec *lr;
441     DWORD BytesRead;
442     int lcnt = 0;
443     SOCKET nsd;
444
445     /* Set up a default listener if necessary */
446     if (ap_listeners == NULL) {
447         ap_listen_rec *lr;
448         lr = apr_palloc(s->process->pool, sizeof(ap_listen_rec));
449         lr->sd = NULL;
450         lr->next = ap_listeners;
451         ap_listeners = lr;
452     }
453
454     /* Open the pipe to the parent process to receive the inherited socket
455      * data. The sockets have been set to listening in the parent process.
456      *
457      * *** We now do this was back in winnt_rewrite_args
458      * pipe = GetStdHandle(STD_INPUT_HANDLE);
459      */
460     for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) {
461         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
462                      "Child: Waiting for data for listening socket %pI",
463                      lr->bind_addr);
464         if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
465                       &BytesRead, (LPOVERLAPPED) NULL)) {
466             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
467                          "Child: Unable to read socket data from parent");
468             exit(APEXIT_CHILDINIT);
469         }
470
471         nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
472                         &WSAProtocolInfo, 0, 0);
473         if (nsd == INVALID_SOCKET) {
474             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf,
475                          "Child: WSASocket failed to open the inherited socket");
476             exit(APEXIT_CHILDINIT);
477         }
478
479         if (!SetHandleInformation((HANDLE)nsd, HANDLE_FLAG_INHERIT, 0)) {
480             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), ap_server_conf,
481                          "Child: SetHandleInformation failed");
482         }
483         apr_os_sock_put(&lr->sd, &nsd, s->process->pool);
484     }
485
486     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
487                  "Child: retrieved %d listeners from parent", lcnt);
488 }
489
490
491 static int send_listeners_to_child(apr_pool_t *p, DWORD dwProcessId,
492                                    apr_file_t *child_in)
493 {
494     apr_status_t rv;
495     int lcnt = 0;
496     ap_listen_rec *lr;
497     LPWSAPROTOCOL_INFO  lpWSAProtocolInfo;
498     apr_size_t BytesWritten;
499
500     /* Run the chain of open sockets. For each socket, duplicate it
501      * for the target process then send the WSAPROTOCOL_INFO
502      * (returned by dup socket) to the child.
503      */
504     for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) {
505         apr_os_sock_t nsd;
506         lpWSAProtocolInfo = apr_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
507         apr_os_sock_get(&nsd, lr->sd);
508         ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf,
509                      "Parent: Duplicating socket %d (%pI) and sending it to child process %lu",
510                      nsd, lr->bind_addr, dwProcessId);
511         if (WSADuplicateSocket(nsd, dwProcessId,
512                                lpWSAProtocolInfo) == SOCKET_ERROR) {
513             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf,
514                          "Parent: WSADuplicateSocket failed for socket %d. Check the FAQ.", nsd);
515             return -1;
516         }
517
518         if ((rv = apr_file_write_full(child_in, lpWSAProtocolInfo,
519                                       sizeof(WSAPROTOCOL_INFO), &BytesWritten))
520                 != APR_SUCCESS) {
521             ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
522                          "Parent: Unable to write duplicated socket %d to the child.", nsd);
523             return -1;
524         }
525     }
526
527     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
528                  "Parent: Sent %d listeners to child %lu", lcnt, dwProcessId);
529     return 0;
530 }
531
532 enum waitlist_e {
533     waitlist_ready = 0,
534     waitlist_term = 1
535 };
536
537 static int create_process(apr_pool_t *p, HANDLE *child_proc, HANDLE *child_exit_event,
538                           DWORD *child_pid)
539 {
540     /* These NEVER change for the lifetime of this parent
541      */
542     static char **args = NULL;
543     static char pidbuf[28];
544
545     apr_status_t rv;
546     apr_pool_t *ptemp;
547     apr_procattr_t *attr;
548     apr_proc_t new_child;
549     HANDLE hExitEvent;
550     HANDLE waitlist[2];  /* see waitlist_e */
551     char *cmd;
552     char *cwd;
553     char **env;
554     int envc;
555
556     apr_pool_create_ex(&ptemp, p, NULL, NULL);
557
558     /* Build the command line. Should look something like this:
559      * C:/apache/bin/httpd.exe -f ap_server_confname
560      * First, get the path to the executable...
561      */
562     apr_procattr_create(&attr, ptemp);
563     apr_procattr_cmdtype_set(attr, APR_PROGRAM);
564     apr_procattr_detach_set(attr, 1);
565     if (((rv = apr_filepath_get(&cwd, 0, ptemp)) != APR_SUCCESS)
566            || ((rv = apr_procattr_dir_set(attr, cwd)) != APR_SUCCESS)) {
567         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
568                      "Parent: Failed to get the current path");
569     }
570
571     if (!args) {
572         /* Build the args array, only once since it won't change
573          * for the lifetime of this parent process.
574          */
575         if ((rv = ap_os_proc_filepath(&cmd, ptemp))
576                 != APR_SUCCESS) {
577             ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, ap_server_conf,
578                          "Parent: Failed to get full path of %s",
579                          ap_server_conf->process->argv[0]);
580             apr_pool_destroy(ptemp);
581             return -1;
582         }
583
584         args = malloc((ap_server_conf->process->argc + 1) * sizeof (char*));
585         memcpy(args + 1, ap_server_conf->process->argv + 1,
586                (ap_server_conf->process->argc - 1) * sizeof (char*));
587         args[0] = malloc(strlen(cmd) + 1);
588         strcpy(args[0], cmd);
589         args[ap_server_conf->process->argc] = NULL;
590     }
591     else {
592         cmd = args[0];
593     }
594
595     /* Create a pipe to send handles to the child */
596     if ((rv = apr_procattr_io_set(attr, APR_FULL_BLOCK,
597                                   APR_NO_PIPE, APR_NO_PIPE)) != APR_SUCCESS) {
598         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
599                         "Parent: Unable to create child stdin pipe.");
600         apr_pool_destroy(ptemp);
601         return -1;
602     }
603
604     /* Create the child_ready_event */
605     waitlist[waitlist_ready] = CreateEvent(NULL, TRUE, FALSE, NULL);
606     if (!waitlist[waitlist_ready]) {
607         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
608                      "Parent: Could not create ready event for child process");
609         apr_pool_destroy (ptemp);
610         return -1;
611     }
612
613     /* Create the child_exit_event */
614     hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
615     if (!hExitEvent) {
616         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
617                      "Parent: Could not create exit event for child process");
618         apr_pool_destroy(ptemp);
619         CloseHandle(waitlist[waitlist_ready]);
620         return -1;
621     }
622
623     /* Build the env array */
624     for (envc = 0; _environ[envc]; ++envc) {
625         ;
626     }
627     env = apr_palloc(ptemp, (envc + 2) * sizeof (char*));  
628     memcpy(env, _environ, envc * sizeof (char*));
629     apr_snprintf(pidbuf, sizeof(pidbuf), "AP_PARENT_PID=%lu", parent_pid);
630     env[envc] = pidbuf;
631     env[envc + 1] = NULL;
632
633     rv = apr_proc_create(&new_child, cmd, (const char * const *)args,
634                          (const char * const *)env, attr, ptemp);
635     if (rv != APR_SUCCESS) {
636         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
637                      "Parent: Failed to create the child process.");
638         apr_pool_destroy(ptemp);
639         CloseHandle(hExitEvent);
640         CloseHandle(waitlist[waitlist_ready]);
641         CloseHandle(new_child.hproc);
642         return -1;
643     }
644
645     ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
646                  "Parent: Created child process %d", new_child.pid);
647
648     if (send_handles_to_child(ptemp, waitlist[waitlist_ready], hExitEvent,
649                               start_mutex, ap_scoreboard_shm,
650                               new_child.hproc, new_child.in)) {
651         /*
652          * This error is fatal, mop up the child and move on
653          * We toggle the child's exit event to cause this child
654          * to quit even as it is attempting to start.
655          */
656         SetEvent(hExitEvent);
657         apr_pool_destroy(ptemp);
658         CloseHandle(hExitEvent);
659         CloseHandle(waitlist[waitlist_ready]);
660         CloseHandle(new_child.hproc);
661         return -1;
662     }
663
664     /* Important:
665      * Give the child process a chance to run before dup'ing the sockets.
666      * We have already set the listening sockets noninheritable, but if
667      * WSADuplicateSocket runs before the child process initializes
668      * the listeners will be inherited anyway.
669      */
670     waitlist[waitlist_term] = new_child.hproc;
671     rv = WaitForMultipleObjects(2, waitlist, FALSE, INFINITE);
672     CloseHandle(waitlist[waitlist_ready]);
673     if (rv != WAIT_OBJECT_0) {
674         /*
675          * Outch... that isn't a ready signal. It's dead, Jim!
676          */
677         SetEvent(hExitEvent);
678         apr_pool_destroy(ptemp);
679         CloseHandle(hExitEvent);
680         CloseHandle(new_child.hproc);
681         return -1;
682     }
683
684     if (send_listeners_to_child(ptemp, new_child.pid, new_child.in)) {
685         /*
686          * This error is fatal, mop up the child and move on
687          * We toggle the child's exit event to cause this child
688          * to quit even as it is attempting to start.
689          */
690         SetEvent(hExitEvent);
691         apr_pool_destroy(ptemp);
692         CloseHandle(hExitEvent);
693         CloseHandle(new_child.hproc);
694         return -1;
695     }
696
697     apr_file_close(new_child.in);
698
699     *child_exit_event = hExitEvent;
700     *child_proc = new_child.hproc;
701     *child_pid = new_child.pid;
702
703     return 0;
704 }
705
706 /***********************************************************************
707  * master_main()
708  * master_main() runs in the parent process.  It creates the child
709  * process which handles HTTP requests then waits on one of three
710  * events:
711  *
712  * restart_event
713  * -------------
714  * The restart event causes master_main to start a new child process and
715  * tells the old child process to exit (by setting the child_exit_event).
716  * The restart event is set as a result of one of the following:
717  * 1. An apache -k restart command on the command line
718  * 2. A command received from Windows service manager which gets
719  *    translated into an ap_signal_parent(SIGNAL_PARENT_RESTART)
720  *    call by code in service.c.
721  * 3. The child process calling ap_signal_parent(SIGNAL_PARENT_RESTART)
722  *    as a result of hitting MaxConnectionsPerChild.
723  *
724  * shutdown_event
725  * --------------
726  * The shutdown event causes master_main to tell the child process to
727  * exit and that the server is shutting down. The shutdown event is
728  * set as a result of one of the following:
729  * 1. An apache -k shutdown command on the command line
730  * 2. A command received from Windows service manager which gets
731  *    translated into an ap_signal_parent(SIGNAL_PARENT_SHUTDOWN)
732  *    call by code in service.c.
733  *
734  * child process handle
735  * --------------------
736  * The child process handle will be signaled if the child process
737  * exits for any reason. In a normal running server, the signaling
738  * of this event means that the child process has exited prematurely
739  * due to a seg fault or other irrecoverable error. For server
740  * robustness, master_main will restart the child process under this
741  * condtion.
742  *
743  * master_main uses the child_exit_event to signal the child process
744  * to exit.
745  **********************************************************************/
746 #define NUM_WAIT_HANDLES 3
747 #define CHILD_HANDLE     0
748 #define SHUTDOWN_HANDLE  1
749 #define RESTART_HANDLE   2
750 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
751 {
752     int rv, cld;
753     int child_created;
754     int restart_pending;
755     int shutdown_pending;
756     HANDLE child_exit_event;
757     HANDLE event_handles[NUM_WAIT_HANDLES];
758     DWORD child_pid;
759
760     child_created = restart_pending = shutdown_pending = 0;
761
762     event_handles[SHUTDOWN_HANDLE] = shutdown_event;
763     event_handles[RESTART_HANDLE] = restart_event;
764
765     /* Create a single child process */
766     rv = create_process(pconf, &event_handles[CHILD_HANDLE],
767                         &child_exit_event, &child_pid);
768     if (rv < 0)
769     {
770         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
771                      "master_main: create child process failed. Exiting.");
772         shutdown_pending = 1;
773         goto die_now;
774     }
775
776     child_created = 1;
777
778     if (!strcasecmp(signal_arg, "runservice")) {
779         mpm_service_started();
780     }
781
782     /* Update the scoreboard. Note that there is only a single active
783      * child at once.
784      */
785     ap_scoreboard_image->parent[0].quiescing = 0;
786     winnt_note_child_started(/* slot */ 0, child_pid);
787
788     /* Wait for shutdown or restart events or for child death */
789     winnt_mpm_state = AP_MPMQ_RUNNING;
790     rv = WaitForMultipleObjects(NUM_WAIT_HANDLES, (HANDLE *) event_handles, FALSE, INFINITE);
791     cld = rv - WAIT_OBJECT_0;
792     if (rv == WAIT_FAILED) {
793         /* Something serious is wrong */
794         ap_log_error(APLOG_MARK,APLOG_CRIT, apr_get_os_error(), ap_server_conf,
795                      "master_main: WaitForMultipleObjects WAIT_FAILED -- doing server shutdown");
796         shutdown_pending = 1;
797     }
798     else if (rv == WAIT_TIMEOUT) {
799         /* Hey, this cannot happen */
800         ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
801                      "master_main: WaitForMultipleObjects with INFINITE wait exited with WAIT_TIMEOUT");
802         shutdown_pending = 1;
803     }
804     else if (cld == SHUTDOWN_HANDLE) {
805         /* shutdown_event signalled */
806         shutdown_pending = 1;
807         ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, s,
808                      "Parent: Received shutdown signal -- Shutting down the server.");
809         if (ResetEvent(shutdown_event) == 0) {
810             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
811                          "ResetEvent(shutdown_event)");
812         }
813     }
814     else if (cld == RESTART_HANDLE) {
815         /* Received a restart event. Prepare the restart_event to be reused
816          * then signal the child process to exit.
817          */
818         restart_pending = 1;
819         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
820                      "Parent: Received restart signal -- Restarting the server.");
821         if (ResetEvent(restart_event) == 0) {
822             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
823                          "Parent: ResetEvent(restart_event) failed.");
824         }
825         if (SetEvent(child_exit_event) == 0) {
826             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s,
827                          "Parent: SetEvent for child process %pp failed.",
828                          event_handles[CHILD_HANDLE]);
829         }
830         /* Don't wait to verify that the child process really exits,
831          * just move on with the restart.
832          */
833         CloseHandle(event_handles[CHILD_HANDLE]);
834         event_handles[CHILD_HANDLE] = NULL;
835     }
836     else {
837         /* The child process exited prematurely due to a fatal error. */
838         DWORD exitcode;
839         if (!GetExitCodeProcess(event_handles[CHILD_HANDLE], &exitcode)) {
840             /* HUH? We did exit, didn't we? */
841             exitcode = APEXIT_CHILDFATAL;
842         }
843         if (   exitcode == APEXIT_CHILDFATAL
844             || exitcode == APEXIT_CHILDINIT
845             || exitcode == APEXIT_INIT) {
846             ap_log_error(APLOG_MARK, APLOG_CRIT, 0, ap_server_conf,
847                          "Parent: child process exited with status %lu -- Aborting.", exitcode);
848             shutdown_pending = 1;
849         }
850         else {
851             int i;
852             restart_pending = 1;
853             ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
854                          "Parent: child process exited with status %lu -- Restarting.", exitcode);
855             for (i = 0; i < ap_threads_per_child; i++) {
856                 ap_update_child_status_from_indexes(0, i, SERVER_DEAD, NULL);
857             }
858         }
859         CloseHandle(event_handles[CHILD_HANDLE]);
860         event_handles[CHILD_HANDLE] = NULL;
861     }
862
863     winnt_note_child_killed(/* slot */ 0);
864
865     if (restart_pending) {
866         ++my_generation;
867         ap_scoreboard_image->global->running_generation = my_generation;
868     }
869 die_now:
870     if (shutdown_pending)
871     {
872         int timeout = 30000;  /* Timeout is milliseconds */
873         winnt_mpm_state = AP_MPMQ_STOPPING;
874
875         if (!child_created) {
876             return 0;  /* Tell the caller we do not want to restart */
877         }
878
879         /* This shutdown is only marginally graceful. We will give the
880          * child a bit of time to exit gracefully. If the time expires,
881          * the child will be wacked.
882          */
883         if (!strcasecmp(signal_arg, "runservice")) {
884             mpm_service_stopping();
885         }
886         /* Signal the child processes to exit */
887         if (SetEvent(child_exit_event) == 0) {
888                 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), ap_server_conf,
889                              "Parent: SetEvent for child process %pp failed",
890                              event_handles[CHILD_HANDLE]);
891         }
892         if (event_handles[CHILD_HANDLE]) {
893             rv = WaitForSingleObject(event_handles[CHILD_HANDLE], timeout);
894             if (rv == WAIT_OBJECT_0) {
895                 ap_log_error(APLOG_MARK,APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
896                              "Parent: Child process exited successfully.");
897                 CloseHandle(event_handles[CHILD_HANDLE]);
898                 event_handles[CHILD_HANDLE] = NULL;
899             }
900             else {
901                 ap_log_error(APLOG_MARK,APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
902                              "Parent: Forcing termination of child process %pp",
903                              event_handles[CHILD_HANDLE]);
904                 TerminateProcess(event_handles[CHILD_HANDLE], 1);
905                 CloseHandle(event_handles[CHILD_HANDLE]);
906                 event_handles[CHILD_HANDLE] = NULL;
907             }
908         }
909         CloseHandle(child_exit_event);
910         return 0;  /* Tell the caller we do not want to restart */
911     }
912     winnt_mpm_state = AP_MPMQ_STARTING;
913     CloseHandle(child_exit_event);
914     return 1;      /* Tell the caller we want a restart */
915 }
916
917 /* service_nt_main_fn needs to append the StartService() args
918  * outside of our call stack and thread as the service starts...
919  */
920 apr_array_header_t *mpm_new_argv;
921
922 /* Remember service_to_start failures to log and fail in pre_config.
923  * Remember inst_argc and inst_argv for installing or starting the
924  * service after we preflight the config.
925  */
926
927 static int winnt_query(int query_code, int *result, apr_status_t *rv)
928 {
929     *rv = APR_SUCCESS;
930     switch (query_code) {
931         case AP_MPMQ_MAX_DAEMON_USED:
932             *result = MAXIMUM_WAIT_OBJECTS;
933             break;
934         case AP_MPMQ_IS_THREADED:
935             *result = AP_MPMQ_STATIC;
936             break;
937         case AP_MPMQ_IS_FORKED:
938             *result = AP_MPMQ_NOT_SUPPORTED;
939             break;
940         case AP_MPMQ_HARD_LIMIT_DAEMONS:
941             *result = HARD_SERVER_LIMIT;
942             break;
943         case AP_MPMQ_HARD_LIMIT_THREADS:
944             *result = thread_limit;
945             break;
946         case AP_MPMQ_MAX_THREADS:
947             *result = ap_threads_per_child;
948             break;
949         case AP_MPMQ_MIN_SPARE_DAEMONS:
950             *result = 0;
951             break;
952         case AP_MPMQ_MIN_SPARE_THREADS:
953             *result = 0;
954             break;
955         case AP_MPMQ_MAX_SPARE_DAEMONS:
956             *result = 0;
957             break;
958         case AP_MPMQ_MAX_SPARE_THREADS:
959             *result = 0;
960             break;
961         case AP_MPMQ_MAX_REQUESTS_DAEMON:
962             *result = ap_max_requests_per_child;
963             break;
964         case AP_MPMQ_MAX_DAEMONS:
965             *result = 1;
966             break;
967         case AP_MPMQ_MPM_STATE:
968             *result = winnt_mpm_state;
969             break;
970         case AP_MPMQ_GENERATION:
971             *result = my_generation;
972             break;
973         default:
974             *rv = APR_ENOTIMPL;
975             break;
976     }
977     return OK;
978 }
979
980 static const char *winnt_get_name(void)
981 {
982     return "WinNT";
983 }
984
985 #define SERVICE_UNSET (-1)
986 static apr_status_t service_set = SERVICE_UNSET;
987 static apr_status_t service_to_start_success;
988 static int inst_argc;
989 static const char * const *inst_argv;
990 static const char *service_name = NULL;
991
992 static void winnt_rewrite_args(process_rec *process)
993 {
994     /* Handle the following SCM aspects in this phase:
995      *
996      *   -k runservice [transition in service context only]
997      *   -k install
998      *   -k config
999      *   -k uninstall
1000      *   -k stop
1001      *   -k shutdown (same as -k stop). Maintained for backward compatability.
1002      *
1003      * We can't leave this phase until we know our identity
1004      * and modify the command arguments appropriately.
1005      *
1006      * We do not care if the .conf file exists or is parsable when
1007      * attempting to stop or uninstall a service.
1008      */
1009     apr_status_t rv;
1010     char *def_server_root;
1011     char *binpath;
1012     char optbuf[3];
1013     const char *opt_arg;
1014     int fixed_args;
1015     char *pid;
1016     apr_getopt_t *opt;
1017     int running_as_service = 1;
1018     int errout = 0;
1019     apr_file_t *nullfile;
1020
1021     pconf = process->pconf;
1022
1023     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1024     GetVersionEx(&osver);
1025
1026     /* We wish this was *always* a reservation, but sadly it wasn't so and
1027      * we couldn't break a hard limit prior to NT Kernel 5.1
1028      */
1029     if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT 
1030         && ((osver.dwMajorVersion > 5)
1031          || ((osver.dwMajorVersion == 5) && (osver.dwMinorVersion > 0)))) {
1032         stack_res_flag = STACK_SIZE_PARAM_IS_A_RESERVATION;
1033     }
1034
1035     /* AP_PARENT_PID is only valid in the child */
1036     pid = getenv("AP_PARENT_PID");
1037     if (pid)
1038     {
1039         HANDLE filehand;
1040         HANDLE hproc = GetCurrentProcess();
1041
1042         /* This is the child */
1043         my_pid = GetCurrentProcessId();
1044         parent_pid = (DWORD) atol(pid);
1045
1046         /* Prevent holding open the (nonexistant) console */
1047         ap_real_exit_code = 0;
1048
1049         /* The parent gave us stdin, we need to remember this
1050          * handle, and no longer inherit it at our children
1051          * (we can't slurp it up now, we just aren't ready yet).
1052          * The original handle is closed below, at apr_file_dup2()
1053          */
1054         pipe = GetStdHandle(STD_INPUT_HANDLE);
1055         if (DuplicateHandle(hproc, pipe,
1056                             hproc, &filehand, 0, FALSE,
1057                             DUPLICATE_SAME_ACCESS)) {
1058             pipe = filehand;
1059         }
1060
1061         /* The parent gave us stdout of the NUL device,
1062          * and expects us to suck up stdin of all of our
1063          * shared handles and data from the parent.
1064          * Don't infect child processes with our stdin
1065          * handle, use another handle to NUL!
1066          */
1067         {
1068             apr_file_t *infile, *outfile;
1069             if ((apr_file_open_stdout(&outfile, process->pool) == APR_SUCCESS)
1070              && (apr_file_open_stdin(&infile, process->pool) == APR_SUCCESS))
1071                 apr_file_dup2(infile, outfile, process->pool);
1072         }
1073
1074         /* This child needs the existing stderr opened for logging,
1075          * already 
1076          */
1077
1078
1079         /* The parent is responsible for providing the
1080          * COMPLETE ARGUMENTS REQUIRED to the child.
1081          *
1082          * No further argument parsing is needed, but
1083          * for good measure we will provide a simple
1084          * signal string for later testing.
1085          */
1086         signal_arg = "runchild";
1087         return;
1088     }
1089
1090     /* This is the parent, we have a long way to go :-) */
1091     parent_pid = my_pid = GetCurrentProcessId();
1092
1093     /* This behavior is voided by setting real_exit_code to 0 */
1094     atexit(hold_console_open_on_error);
1095
1096     /* Rewrite process->argv[];
1097      *
1098      * strip out -k signal into signal_arg
1099      * strip out -n servicename and set the names
1100      * add default -d serverroot from the path of this executable
1101      *
1102      * The end result will look like:
1103      *
1104      * The invocation command (%0)
1105      *     The -d serverroot default from the running executable
1106      *         The requested service's (-n) registry ConfigArgs
1107      *             The WinNT SCM's StartService() args
1108      */
1109     if ((rv = ap_os_proc_filepath(&binpath, process->pconf))
1110             != APR_SUCCESS) {
1111         ap_log_error(APLOG_MARK,APLOG_CRIT, rv, NULL,
1112                      "Failed to get the full path of %s", process->argv[0]);
1113         exit(APEXIT_INIT);
1114     }
1115     /* WARNING: There is an implict assumption here that the
1116      * executable resides in ServerRoot or ServerRoot\bin
1117      */
1118     def_server_root = (char *) apr_filepath_name_get(binpath);
1119     if (def_server_root > binpath) {
1120         *(def_server_root - 1) = '\0';
1121         def_server_root = (char *) apr_filepath_name_get(binpath);
1122         if (!strcasecmp(def_server_root, "bin"))
1123             *(def_server_root - 1) = '\0';
1124     }
1125     apr_filepath_merge(&def_server_root, NULL, binpath,
1126                        APR_FILEPATH_TRUENAME, process->pool);
1127
1128     /* Use process->pool so that the rewritten argv
1129      * lasts for the lifetime of the server process,
1130      * because pconf will be destroyed after the
1131      * initial pre-flight of the config parser.
1132      */
1133     mpm_new_argv = apr_array_make(process->pool, process->argc + 2,
1134                                   sizeof(const char *));
1135     *(const char **)apr_array_push(mpm_new_argv) = process->argv[0];
1136     *(const char **)apr_array_push(mpm_new_argv) = "-d";
1137     *(const char **)apr_array_push(mpm_new_argv) = def_server_root;
1138
1139     fixed_args = mpm_new_argv->nelts;
1140
1141     optbuf[0] = '-';
1142     optbuf[2] = '\0';
1143     apr_getopt_init(&opt, process->pool, process->argc, process->argv);
1144     opt->errfn = NULL;
1145     while ((rv = apr_getopt(opt, "wn:k:" AP_SERVER_BASEARGS,
1146                             optbuf + 1, &opt_arg)) == APR_SUCCESS) {
1147         switch (optbuf[1]) {
1148
1149         /* Shortcuts; include the -w option to hold the window open on error.
1150          * This must not be toggled once we reset ap_real_exit_code to 0!
1151          */
1152         case 'w':
1153             if (ap_real_exit_code)
1154                 ap_real_exit_code = 2;
1155             break;
1156
1157         case 'n':
1158             service_set = mpm_service_set_name(process->pool, &service_name,
1159                                                opt_arg);
1160             break;
1161
1162         case 'k':
1163             signal_arg = opt_arg;
1164             break;
1165
1166         case 'E':
1167             errout = 1;
1168             /* Fall through so the Apache main() handles the 'E' arg */
1169         default:
1170             *(const char **)apr_array_push(mpm_new_argv) =
1171                 apr_pstrdup(process->pool, optbuf);
1172
1173             if (opt_arg) {
1174                 *(const char **)apr_array_push(mpm_new_argv) = opt_arg;
1175             }
1176             break;
1177         }
1178     }
1179
1180     /* back up to capture the bad argument */
1181     if (rv == APR_BADCH || rv == APR_BADARG) {
1182         opt->ind--;
1183     }
1184
1185     while (opt->ind < opt->argc) {
1186         *(const char **)apr_array_push(mpm_new_argv) =
1187             apr_pstrdup(process->pool, opt->argv[opt->ind++]);
1188     }
1189
1190     /* Track the number of args actually entered by the user */
1191     inst_argc = mpm_new_argv->nelts - fixed_args;
1192
1193     /* Provide a default 'run' -k arg to simplify signal_arg tests */
1194     if (!signal_arg)
1195     {
1196         signal_arg = "run";
1197         running_as_service = 0;
1198     }
1199
1200     if (!strcasecmp(signal_arg, "runservice"))
1201     {
1202         /* Start the NT Service _NOW_ because the WinNT SCM is
1203          * expecting us to rapidly assume control of our own
1204          * process, the SCM will tell us our service name, and
1205          * may have extra StartService() command arguments to
1206          * add for us.
1207          *
1208          * The SCM will generally invoke the executable with
1209          * the c:\win\system32 default directory.  This is very
1210          * lethal if folks use ServerRoot /foopath on windows
1211          * without a drive letter.  Change to the default root
1212          * (path to apache root, above /bin) for safety.
1213          */
1214         apr_filepath_set(def_server_root, process->pool);
1215
1216         /* Any other process has a console, so we don't to begin
1217          * a Win9x service until the configuration is parsed and
1218          * any command line errors are reported.
1219          *
1220          * We hold the return value so that we can die in pre_config
1221          * after logging begins, and the failure can land in the log.
1222          */
1223         if (!errout) {
1224             mpm_nt_eventlog_stderr_open(service_name, process->pool);
1225         }
1226         service_to_start_success = mpm_service_to_start(&service_name,
1227                                                         process->pool);
1228         if (service_to_start_success == APR_SUCCESS) {
1229             service_set = APR_SUCCESS;
1230         }
1231
1232         /* Open a null handle to soak stdout in this process.
1233          * Windows service processes are missing any file handle
1234          * usable for stdin/out/err.  This was the cause of later 
1235          * trouble with invocations of apr_file_open_stdout()
1236          */
1237         if ((rv = apr_file_open(&nullfile, "NUL",
1238                                 APR_READ | APR_WRITE, APR_OS_DEFAULT,
1239                                 process->pool)) == APR_SUCCESS) {
1240             apr_file_t *nullstdout;
1241             if (apr_file_open_stdout(&nullstdout, process->pool)
1242                     == APR_SUCCESS)
1243                 apr_file_dup2(nullstdout, nullfile, process->pool);
1244             apr_file_close(nullfile);
1245         }
1246     }
1247
1248     /* Get the default for any -k option, except run */
1249     if (service_set == SERVICE_UNSET && strcasecmp(signal_arg, "run")) {
1250         service_set = mpm_service_set_name(process->pool, &service_name,
1251                                            AP_DEFAULT_SERVICE_NAME);
1252     }
1253
1254     if (!strcasecmp(signal_arg, "install")) /* -k install */
1255     {
1256         if (service_set == APR_SUCCESS)
1257         {
1258             ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL,
1259                  "%s: Service is already installed.", service_name);
1260             exit(APEXIT_INIT);
1261         }
1262     }
1263     else if (running_as_service)
1264     {
1265         if (service_set == APR_SUCCESS)
1266         {
1267             /* Attempt to Uninstall, or stop, before
1268              * we can read the arguments or .conf files
1269              */
1270             if (!strcasecmp(signal_arg, "uninstall")) {
1271                 rv = mpm_service_uninstall();
1272                 exit(rv);
1273             }
1274
1275             if ((!strcasecmp(signal_arg, "stop")) ||
1276                 (!strcasecmp(signal_arg, "shutdown"))) {
1277                 mpm_signal_service(process->pool, 0);
1278                 exit(0);
1279             }
1280
1281             rv = mpm_merge_service_args(process->pool, mpm_new_argv,
1282                                         fixed_args);
1283             if (rv == APR_SUCCESS) {
1284                 ap_log_error(APLOG_MARK,APLOG_INFO, 0, NULL,
1285                              "Using ConfigArgs of the installed service "
1286                              "\"%s\".", service_name);
1287             }
1288             else  {
1289                 ap_log_error(APLOG_MARK,APLOG_WARNING, rv, NULL,
1290                              "No installed ConfigArgs for the service "
1291                              "\"%s\", using Apache defaults.", service_name);
1292             }
1293         }
1294         else
1295         {
1296             ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL,
1297                  "No installed service named \"%s\".", service_name);
1298             exit(APEXIT_INIT);
1299         }
1300     }
1301     if (strcasecmp(signal_arg, "install") && service_set && service_set != SERVICE_UNSET)
1302     {
1303         ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL,
1304              "No installed service named \"%s\".", service_name);
1305         exit(APEXIT_INIT);
1306     }
1307
1308     /* Track the args actually entered by the user.
1309      * These will be used for the -k install parameters, as well as
1310      * for the -k start service override arguments.
1311      */
1312     inst_argv = (const char * const *)mpm_new_argv->elts
1313         + mpm_new_argv->nelts - inst_argc;
1314
1315     /* Now, do service install or reconfigure then proceed to
1316      * post_config to test the installed configuration.
1317      */
1318     if (!strcasecmp(signal_arg, "config")) { /* -k config */
1319         /* Reconfigure the service */
1320         rv = mpm_service_install(process->pool, inst_argc, inst_argv, 1);
1321         if (rv != APR_SUCCESS) {
1322             exit(rv);
1323         }
1324
1325         fprintf(stderr,"Testing httpd.conf....\n");
1326         fprintf(stderr,"Errors reported here must be corrected before the "
1327                 "service can be started.\n");
1328     }
1329     else if (!strcasecmp(signal_arg, "install")) { /* -k install */
1330         /* Install the service */
1331         rv = mpm_service_install(process->pool, inst_argc, inst_argv, 0);
1332         if (rv != APR_SUCCESS) {
1333             exit(rv);
1334         }
1335
1336         fprintf(stderr,"Testing httpd.conf....\n");
1337         fprintf(stderr,"Errors reported here must be corrected before the "
1338                 "service can be started.\n");
1339     }
1340
1341     process->argc = mpm_new_argv->nelts;
1342     process->argv = (const char * const *) mpm_new_argv->elts;
1343 }
1344
1345
1346 static int winnt_pre_config(apr_pool_t *pconf_, apr_pool_t *plog, apr_pool_t *ptemp)
1347 {
1348     /* Handle the following SCM aspects in this phase:
1349      *
1350      *   -k runservice [WinNT errors logged from rewrite_args]
1351      */
1352
1353     /* Initialize shared static objects.
1354      * TODO: Put config related statics into an sconf structure.
1355      */
1356     pconf = pconf_;
1357
1358     if (ap_exists_config_define("ONE_PROCESS") ||
1359         ap_exists_config_define("DEBUG"))
1360         one_process = -1;
1361
1362     /* XXX: presume proper privilages; one nice thing would be
1363      * a loud emit if running as "LocalSystem"/"SYSTEM" to indicate
1364      * they should change to a user with write access to logs/ alone.
1365      */
1366     ap_sys_privileges_handlers(1);
1367
1368     if (!strcasecmp(signal_arg, "runservice")
1369             && (service_to_start_success != APR_SUCCESS)) {
1370         ap_log_error(APLOG_MARK,APLOG_CRIT, service_to_start_success, NULL,
1371                      "%s: Unable to start the service manager.",
1372                      service_name);
1373         exit(APEXIT_INIT);
1374     }
1375     else if (!one_process && !my_generation) {
1376         /* Open a null handle to soak stdout in this process.
1377          * We need to emulate apr_proc_detach, unix performs this
1378          * same check in the pre_config hook (although it is
1379          * arguably premature).  Services already fixed this.
1380          */
1381         apr_file_t *nullfile;
1382         apr_status_t rv;
1383         apr_pool_t *pproc = apr_pool_parent_get(pconf);
1384
1385         if ((rv = apr_file_open(&nullfile, "NUL",
1386                                 APR_READ | APR_WRITE, APR_OS_DEFAULT,
1387                                 pproc)) == APR_SUCCESS) {
1388             apr_file_t *nullstdout;
1389             if (apr_file_open_stdout(&nullstdout, pproc)
1390                     == APR_SUCCESS)
1391                 apr_file_dup2(nullstdout, nullfile, pproc);
1392             apr_file_close(nullfile);
1393         }
1394     }
1395
1396     ap_listen_pre_config();
1397     thread_limit = DEFAULT_THREAD_LIMIT;
1398     ap_threads_per_child = DEFAULT_THREADS_PER_CHILD;
1399
1400     return OK;
1401 }
1402
1403 static int winnt_check_config(apr_pool_t *pconf, apr_pool_t *plog,
1404                               apr_pool_t *ptemp, server_rec* s)
1405 {
1406     int is_parent;
1407     static int restart_num = 0;
1408     int startup = 0;
1409
1410     /* We want this only in the parent and only the first time around */
1411     is_parent = (parent_pid == my_pid);
1412     if (is_parent && restart_num++ == 0) {
1413         startup = 1;
1414     }
1415
1416     if (thread_limit > MAX_THREAD_LIMIT) {
1417         if (startup) {
1418             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1419                          "WARNING: ThreadLimit of %d exceeds compile-time "
1420                          "limit of", thread_limit);
1421             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1422                          " %d threads, decreasing to %d.",
1423                          MAX_THREAD_LIMIT, MAX_THREAD_LIMIT);
1424         } else if (is_parent) {
1425             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1426                          "ThreadLimit of %d exceeds compile-time limit "
1427                          "of %d, decreasing to match",
1428                          thread_limit, MAX_THREAD_LIMIT);
1429         }
1430         thread_limit = MAX_THREAD_LIMIT;
1431     }
1432     else if (thread_limit < 1) {
1433         if (startup) {
1434             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1435                          "WARNING: ThreadLimit of %d not allowed, "
1436                          "increasing to 1.", thread_limit);
1437         } else if (is_parent) {
1438             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1439                          "ThreadLimit of %d not allowed, increasing to 1",
1440                          thread_limit);
1441         }
1442         thread_limit = 1;
1443     }
1444
1445     /* You cannot change ThreadLimit across a restart; ignore
1446      * any such attempts.
1447      */
1448     if (!first_thread_limit) {
1449         first_thread_limit = thread_limit;
1450     }
1451     else if (thread_limit != first_thread_limit) {
1452         /* Don't need a startup console version here */
1453         if (is_parent) {
1454             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1455                          "changing ThreadLimit to %d from original value "
1456                          "of %d not allowed during restart",
1457                          thread_limit, first_thread_limit);
1458         }
1459         thread_limit = first_thread_limit;
1460     }
1461
1462     if (ap_threads_per_child > thread_limit) {
1463         if (startup) {
1464             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1465                          "WARNING: ThreadsPerChild of %d exceeds ThreadLimit "
1466                          "of", ap_threads_per_child);
1467             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1468                          " %d threads, decreasing to %d.",
1469                          thread_limit, thread_limit);
1470             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1471                          " To increase, please see the ThreadLimit "
1472                          "directive.");
1473         } else if (is_parent) {
1474             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1475                          "ThreadsPerChild of %d exceeds ThreadLimit "
1476                          "of %d, decreasing to match",
1477                          ap_threads_per_child, thread_limit);
1478         }
1479         ap_threads_per_child = thread_limit;
1480     }
1481     else if (ap_threads_per_child < 1) {
1482         if (startup) {
1483             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1484                          "WARNING: ThreadsPerChild of %d not allowed, "
1485                          "increasing to 1.", ap_threads_per_child);
1486         } else if (is_parent) {
1487             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1488                          "ThreadsPerChild of %d not allowed, increasing to 1",
1489                          ap_threads_per_child);
1490         }
1491         ap_threads_per_child = 1;
1492     }
1493
1494     return OK;
1495 }
1496
1497 static int winnt_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec* s)
1498 {
1499     static int restart_num = 0;
1500     apr_status_t rv = 0;
1501
1502     /* Handle the following SCM aspects in this phase:
1503      *
1504      *   -k install (catch and exit as install was handled in rewrite_args)
1505      *   -k config  (catch and exit as config was handled in rewrite_args)
1506      *   -k start
1507      *   -k restart
1508      *   -k runservice [Win95, only once - after we parsed the config]
1509      *
1510      * because all of these signals are useful _only_ if there
1511      * is a valid conf\httpd.conf environment to start.
1512      *
1513      * We reached this phase by avoiding errors that would cause
1514      * these options to fail unexpectedly in another process.
1515      */
1516
1517     if (!strcasecmp(signal_arg, "install")) {
1518         /* Service install happens in the rewrite_args hooks. If we
1519          * made it this far, the server configuration is clean and the
1520          * service will successfully start.
1521          */
1522         apr_pool_destroy(s->process->pool);
1523         apr_terminate();
1524         exit(0);
1525     }
1526     if (!strcasecmp(signal_arg, "config")) {
1527         /* Service reconfiguration happens in the rewrite_args hooks. If we
1528          * made it this far, the server configuration is clean and the
1529          * service will successfully start.
1530          */
1531         apr_pool_destroy(s->process->pool);
1532         apr_terminate();
1533         exit(0);
1534     }
1535
1536     if (!strcasecmp(signal_arg, "start")) {
1537         ap_listen_rec *lr;
1538
1539         /* Close the listening sockets. */
1540         for (lr = ap_listeners; lr; lr = lr->next) {
1541             apr_socket_close(lr->sd);
1542             lr->active = 0;
1543         }
1544         rv = mpm_service_start(ptemp, inst_argc, inst_argv);
1545         apr_pool_destroy(s->process->pool);
1546         apr_terminate();
1547         exit (rv);
1548     }
1549
1550     if (!strcasecmp(signal_arg, "restart")) {
1551         mpm_signal_service(ptemp, 1);
1552         apr_pool_destroy(s->process->pool);
1553         apr_terminate();
1554         exit (rv);
1555     }
1556
1557     if (parent_pid == my_pid)
1558     {
1559         if (restart_num++ == 1)
1560         {
1561             /* This code should be run once in the parent and not run
1562              * across a restart
1563              */
1564             PSECURITY_ATTRIBUTES sa = GetNullACL();  /* returns NULL if invalid (Win95?) */
1565             setup_signal_names(apr_psprintf(pconf, "ap%lu", parent_pid));
1566
1567             ap_log_pid(pconf, ap_pid_fname);
1568
1569             /* Create shutdown event, apPID_shutdown, where PID is the parent
1570              * Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
1571              */
1572             shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name);
1573             if (!shutdown_event) {
1574                 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1575                              "Parent: Cannot create shutdown event %s", signal_shutdown_name);
1576                 CleanNullACL((void *)sa);
1577                 return HTTP_INTERNAL_SERVER_ERROR;
1578             }
1579
1580             /* Create restart event, apPID_restart, where PID is the parent
1581              * Apache process ID. Restart is signaled by 'apache -k restart'.
1582              */
1583             restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name);
1584             if (!restart_event) {
1585                 CloseHandle(shutdown_event);
1586                 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
1587                              "Parent: Cannot create restart event %s", signal_restart_name);
1588                 CleanNullACL((void *)sa);
1589                 return HTTP_INTERNAL_SERVER_ERROR;
1590             }
1591             CleanNullACL((void *)sa);
1592
1593             /* Create the start mutex, as an unnamed object for security.
1594              * Ths start mutex is used during a restart to prevent more than
1595              * one child process from entering the accept loop at once.
1596              */
1597             rv =  apr_proc_mutex_create(&start_mutex, NULL,
1598                                         APR_LOCK_DEFAULT,
1599                                         ap_server_conf->process->pool);
1600             if (rv != APR_SUCCESS) {
1601                 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
1602                              "%s: Unable to create the start_mutex.",
1603                              service_name);
1604                 return HTTP_INTERNAL_SERVER_ERROR;
1605             }
1606         }
1607         /* Always reset our console handler to be the first, even on a restart
1608         *  because some modules (e.g. mod_perl) might have set a console 
1609         *  handler to terminate the process.
1610         */
1611         if (strcasecmp(signal_arg, "runservice"))
1612             mpm_start_console_handler();
1613     }
1614     else /* parent_pid != my_pid */
1615     {
1616         mpm_start_child_console_handler();
1617     }
1618     return OK;
1619 }
1620
1621 /* This really should be a post_config hook, but the error log is already
1622  * redirected by that point, so we need to do this in the open_logs phase.
1623  */
1624 static int winnt_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
1625 {
1626     /* Initialize shared static objects.
1627      */
1628     if (parent_pid != my_pid) {
1629         return OK;
1630     }
1631
1632     /* We cannot initialize our listeners if we are restarting
1633      * (the parent process already has glomed on to them)
1634      * nor should we do so for service reconfiguration
1635      * (since the service may already be running.)
1636      */
1637     if (!strcasecmp(signal_arg, "restart")
1638             || !strcasecmp(signal_arg, "config")) {
1639         return OK;
1640     }
1641
1642     if (ap_setup_listeners(s) < 1) {
1643         ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_STARTUP, 0,
1644                      NULL, "no listening sockets available, shutting down");
1645         return DONE;
1646     }
1647
1648     return OK;
1649 }
1650
1651 static void winnt_child_init(apr_pool_t *pchild, struct server_rec *s)
1652 {
1653     apr_status_t rv;
1654
1655     setup_signal_names(apr_psprintf(pchild, "ap%lu", parent_pid));
1656
1657     /* This is a child process, not in single process mode */
1658     if (!one_process) {
1659         /* Set up events and the scoreboard */
1660         get_handles_from_parent(s, &exit_event, &start_mutex,
1661                                 &ap_scoreboard_shm);
1662
1663         /* Set up the listeners */
1664         get_listeners_from_parent(s);
1665
1666         /* Done reading from the parent, close that channel */
1667         CloseHandle(pipe);
1668
1669         my_generation = ap_scoreboard_image->global->running_generation;
1670     }
1671     else {
1672         /* Single process mode - this lock doesn't even need to exist */
1673         rv = apr_proc_mutex_create(&start_mutex, signal_name_prefix,
1674                                    APR_LOCK_DEFAULT, s->process->pool);
1675         if (rv != APR_SUCCESS) {
1676             ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
1677                          "%s child: Unable to init the start_mutex.",
1678                          service_name);
1679             exit(APEXIT_CHILDINIT);
1680         }
1681
1682         /* Borrow the shutdown_even as our _child_ loop exit event */
1683         exit_event = shutdown_event;
1684     }
1685 }
1686
1687
1688 static int winnt_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s )
1689 {
1690     static int restart = 0;            /* Default is "not a restart" */
1691
1692     /* ### If non-graceful restarts are ever introduced - we need to rerun
1693      * the pre_mpm hook on subsequent non-graceful restarts.  But Win32
1694      * has only graceful style restarts - and we need this hook to act
1695      * the same on Win32 as on Unix.
1696      */
1697     if (!restart && ((parent_pid == my_pid) || one_process)) {
1698         /* Set up the scoreboard. */
1699         if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
1700             return DONE;
1701         }
1702     }
1703
1704     if ((parent_pid != my_pid) || one_process)
1705     {
1706         /* The child process or in one_process (debug) mode
1707          */
1708         ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
1709                      "Child process is running");
1710
1711         child_main(pconf);
1712
1713         ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf,
1714                      "Child process is exiting");
1715         return DONE;
1716     }
1717     else
1718     {
1719         /* A real-honest to goodness parent */
1720         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1721                      "%s configured -- resuming normal operations",
1722                      ap_get_server_description());
1723         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1724                      "Server built: %s", ap_get_server_built());
1725         ap_log_command_line(plog, s);
1726
1727         restart = master_main(ap_server_conf, shutdown_event, restart_event);
1728
1729         if (!restart)
1730         {
1731             /* Shutting down. Clean up... */
1732             ap_remove_pid(pconf, ap_pid_fname);
1733             apr_proc_mutex_destroy(start_mutex);
1734
1735             CloseHandle(restart_event);
1736             CloseHandle(shutdown_event);
1737
1738             return DONE;
1739         }
1740     }
1741
1742     return OK; /* Restart */
1743 }
1744
1745 static void winnt_hooks(apr_pool_t *p)
1746 {
1747     /* Our open_logs hook function must run before the core's, or stderr
1748      * will be redirected to a file, and the messages won't print to the
1749      * console.
1750      */
1751     static const char *const aszSucc[] = {"core.c", NULL};
1752
1753     ap_hook_pre_config(winnt_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1754     ap_hook_check_config(winnt_check_config, NULL, NULL, APR_HOOK_MIDDLE);
1755     ap_hook_post_config(winnt_post_config, NULL, NULL, 0);
1756     ap_hook_child_init(winnt_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1757     ap_hook_open_logs(winnt_open_logs, NULL, aszSucc, APR_HOOK_REALLY_FIRST);
1758     ap_hook_mpm(winnt_run, NULL, NULL, APR_HOOK_MIDDLE);
1759     ap_hook_mpm_query(winnt_query, NULL, NULL, APR_HOOK_MIDDLE);
1760     ap_hook_mpm_get_name(winnt_get_name, NULL, NULL, APR_HOOK_MIDDLE);
1761 }
1762
1763 AP_DECLARE_MODULE(mpm_winnt) = {
1764     MPM20_MODULE_STUFF,
1765     winnt_rewrite_args,    /* hook to run before apache parses args */
1766     NULL,                  /* create per-directory config structure */
1767     NULL,                  /* merge per-directory config structures */
1768     NULL,                  /* create per-server config structure */
1769     NULL,                  /* merge per-server config structures */
1770     winnt_cmds,            /* command apr_table_t */
1771     winnt_hooks            /* register_hooks */
1772 };
1773
1774 #endif /* def WIN32 */