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 /* Only one of these, the pipe from our parent, meant only for
99  * one child worker's consumption (not to be inherited!)
100  * XXX: decorate this name for the trunk branch, was left simplified
101  *      only to make the 2.2 patch trivial to read.
102  */
103 static HANDLE pipe;
104 
105 /*
106  * Command processors
107  */
108 
set_threads_per_child(cmd_parms * cmd,void * dummy,const char * arg)109 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, const char *arg)
110 {
111     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
112     if (err != NULL) {
113         return err;
114     }
115 
116     ap_threads_per_child = atoi(arg);
117     return NULL;
118 }
set_thread_limit(cmd_parms * cmd,void * dummy,const char * arg)119 static const char *set_thread_limit (cmd_parms *cmd, void *dummy, const char *arg)
120 {
121     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
122     if (err != NULL) {
123         return err;
124     }
125 
126     thread_limit = atoi(arg);
127     return NULL;
128 }
129 
130 static const command_rec winnt_cmds[] = {
131 LISTEN_COMMANDS,
132 AP_INIT_TAKE1("ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF,
133   "Number of threads each child creates" ),
134 AP_INIT_TAKE1("ThreadLimit", set_thread_limit, NULL, RSRC_CONF,
135   "Maximum worker threads in a server for this run of Apache"),
136 { NULL }
137 };
138 
winnt_note_child_started(int slot,pid_t pid)139 static void winnt_note_child_started(int slot, pid_t pid)
140 {
141     ap_scoreboard_image->parent[slot].pid = pid;
142     ap_run_child_status(ap_server_conf,
143                         ap_scoreboard_image->parent[slot].pid,
144                         my_generation, slot, MPM_CHILD_STARTED);
145 }
146 
winnt_note_child_killed(int slot)147 static void winnt_note_child_killed(int slot)
148 {
149     ap_run_child_status(ap_server_conf,
150                         ap_scoreboard_image->parent[slot].pid,
151                         ap_scoreboard_image->parent[slot].generation,
152                         slot, MPM_CHILD_EXITED);
153     ap_scoreboard_image->parent[slot].pid = 0;
154 }
155 
156 /*
157  * Signalling Apache on NT.
158  *
159  * Under Unix, Apache can be told to shutdown or restart by sending various
160  * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
161  * we use "events" instead. The parent apache process goes into a loop
162  * where it waits forever for a set of events. Two of those events are
163  * called
164  *
165  *    apPID_shutdown
166  *    apPID_restart
167  *
168  * (where PID is the PID of the apache parent process). When one of these
169  * is signalled, the Apache parent performs the appropriate action. The events
170  * can become signalled through internal Apache methods (e.g. if the child
171  * finds a fatal error and needs to kill its parent), via the service
172  * control manager (the control thread will signal the shutdown event when
173  * requested to stop the Apache service), from the -k Apache command line,
174  * or from any external program which finds the Apache PID from the
175  * httpd.pid file.
176  *
177  * The signal_parent() function, below, is used to signal one of these events.
178  * It can be called by any child or parent process, since it does not
179  * rely on global variables.
180  *
181  * On entry, type gives the event to signal. 0 means shutdown, 1 means
182  * graceful restart.
183  */
184 /*
185  * Initialise the signal names, in the global variables signal_name_prefix,
186  * signal_restart_name and signal_shutdown_name.
187  */
188 #define MAX_SIGNAL_NAME 30  /* Long enough for apPID_shutdown, where PID is an int */
189 static char signal_name_prefix[MAX_SIGNAL_NAME];
190 static char signal_restart_name[MAX_SIGNAL_NAME];
191 static char signal_shutdown_name[MAX_SIGNAL_NAME];
setup_signal_names(char * prefix)192 static void setup_signal_names(char *prefix)
193 {
194     apr_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix);
195     apr_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name),
196         "%s_shutdown", signal_name_prefix);
197     apr_snprintf(signal_restart_name, sizeof(signal_restart_name),
198         "%s_restart", signal_name_prefix);
199 }
200 
ap_signal_parent(ap_signal_parent_e type)201 AP_DECLARE(void) ap_signal_parent(ap_signal_parent_e type)
202 {
203     HANDLE e;
204     char *signal_name;
205 
206     if (parent_pid == my_pid) {
207         switch(type) {
208            case SIGNAL_PARENT_SHUTDOWN:
209            {
210                SetEvent(shutdown_event);
211                break;
212            }
213            /* This MPM supports only graceful restarts right now */
214            case SIGNAL_PARENT_RESTART:
215            case SIGNAL_PARENT_RESTART_GRACEFUL:
216            {
217                SetEvent(restart_event);
218                break;
219            }
220         }
221         return;
222     }
223 
224     switch(type) {
225        case SIGNAL_PARENT_SHUTDOWN:
226        {
227            signal_name = signal_shutdown_name;
228            break;
229        }
230        /* This MPM supports only graceful restarts right now */
231        case SIGNAL_PARENT_RESTART:
232        case SIGNAL_PARENT_RESTART_GRACEFUL:
233        {
234            signal_name = signal_restart_name;
235            break;
236        }
237        default:
238            return;
239     }
240 
241     e = OpenEvent(EVENT_MODIFY_STATE, FALSE, signal_name);
242     if (!e) {
243         /* Um, problem, can't signal the parent, which means we can't
244          * signal ourselves to die. Ignore for now...
245          */
246         ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf, APLOGNO(00382)
247                      "OpenEvent on %s event", signal_name);
248         return;
249     }
250     if (SetEvent(e) == 0) {
251         /* Same problem as above */
252         ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf, APLOGNO(00383)
253                      "SetEvent on %s event", signal_name);
254         CloseHandle(e);
255         return;
256     }
257     CloseHandle(e);
258 }
259 
260 
261 /*
262  * Passed the following handles [in sync with send_handles_to_child()]
263  *
264  *   ready event [signal the parent immediately, then close]
265  *   exit event  [save to poll later]
266  *   start mutex [signal from the parent to begin accept()]
267  *   scoreboard shm handle [to recreate the ap_scoreboard]
268  */
get_handles_from_parent(server_rec * s,HANDLE * child_exit_event,apr_proc_mutex_t ** child_start_mutex,apr_shm_t ** scoreboard_shm)269 static void get_handles_from_parent(server_rec *s, HANDLE *child_exit_event,
270                                     apr_proc_mutex_t **child_start_mutex,
271                                     apr_shm_t **scoreboard_shm)
272 {
273     HANDLE hScore;
274     HANDLE ready_event;
275     HANDLE os_start;
276     DWORD BytesRead;
277     void *sb_shared;
278     apr_status_t rv;
279 
280     /* *** We now do this way back in winnt_rewrite_args
281      * pipe = GetStdHandle(STD_INPUT_HANDLE);
282      */
283     if (!ReadFile(pipe, &ready_event, sizeof(HANDLE),
284                   &BytesRead, (LPOVERLAPPED) NULL)
285         || (BytesRead != sizeof(HANDLE))) {
286         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, APLOGNO(00384)
287                      "Child: Unable to retrieve the ready event from the parent");
288         exit(APEXIT_CHILDINIT);
289     }
290 
291     SetEvent(ready_event);
292     CloseHandle(ready_event);
293 
294     if (!ReadFile(pipe, child_exit_event, sizeof(HANDLE),
295                   &BytesRead, (LPOVERLAPPED) NULL)
296         || (BytesRead != sizeof(HANDLE))) {
297         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, APLOGNO(00385)
298                      "Child: Unable to retrieve the exit event from the parent");
299         exit(APEXIT_CHILDINIT);
300     }
301 
302     if (!ReadFile(pipe, &os_start, sizeof(os_start),
303                   &BytesRead, (LPOVERLAPPED) NULL)
304         || (BytesRead != sizeof(os_start))) {
305         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, APLOGNO(00386)
306                      "Child: Unable to retrieve the start_mutex from the parent");
307         exit(APEXIT_CHILDINIT);
308     }
309     *child_start_mutex = NULL;
310     if ((rv = apr_os_proc_mutex_put(child_start_mutex, &os_start, s->process->pool))
311             != APR_SUCCESS) {
312         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00387)
313                      "Child: Unable to access the start_mutex from the parent");
314         exit(APEXIT_CHILDINIT);
315     }
316 
317     if (!ReadFile(pipe, &hScore, sizeof(hScore),
318                   &BytesRead, (LPOVERLAPPED) NULL)
319         || (BytesRead != sizeof(hScore))) {
320         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, APLOGNO(00388)
321                      "Child: Unable to retrieve the scoreboard from the parent");
322         exit(APEXIT_CHILDINIT);
323     }
324     *scoreboard_shm = NULL;
325     if ((rv = apr_os_shm_put(scoreboard_shm, &hScore, s->process->pool))
326             != APR_SUCCESS) {
327         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00389)
328                      "Child: Unable to access the scoreboard from the parent");
329         exit(APEXIT_CHILDINIT);
330     }
331 
332     rv = ap_reopen_scoreboard(s->process->pool, scoreboard_shm, 1);
333     if (rv || !(sb_shared = apr_shm_baseaddr_get(*scoreboard_shm))) {
334         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00390)
335                      "Child: Unable to reopen the scoreboard from the parent");
336         exit(APEXIT_CHILDINIT);
337     }
338     /* We must 'initialize' the scoreboard to relink all the
339      * process-local pointer arrays into the shared memory block.
340      */
341     ap_init_scoreboard(sb_shared);
342 
343     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(00391)
344                  "Child: Retrieved our scoreboard from the parent.");
345 }
346 
347 
send_handles_to_child(apr_pool_t * p,HANDLE child_ready_event,HANDLE child_exit_event,apr_proc_mutex_t * child_start_mutex,apr_shm_t * scoreboard_shm,HANDLE hProcess,apr_file_t * child_in)348 static int send_handles_to_child(apr_pool_t *p,
349                                  HANDLE child_ready_event,
350                                  HANDLE child_exit_event,
351                                  apr_proc_mutex_t *child_start_mutex,
352                                  apr_shm_t *scoreboard_shm,
353                                  HANDLE hProcess,
354                                  apr_file_t *child_in)
355 {
356     apr_status_t rv;
357     HANDLE hCurrentProcess = GetCurrentProcess();
358     HANDLE hDup;
359     HANDLE os_start;
360     HANDLE hScore;
361     apr_size_t BytesWritten;
362 
363     if (!DuplicateHandle(hCurrentProcess, child_ready_event, hProcess, &hDup,
364         EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, 0)) {
365         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, APLOGNO(00392)
366                      "Parent: Unable to duplicate the ready event handle for the child");
367         return -1;
368     }
369     if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
370             != APR_SUCCESS) {
371         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00393)
372                      "Parent: Unable to send the exit event handle to the child");
373         return -1;
374     }
375     if (!DuplicateHandle(hCurrentProcess, child_exit_event, hProcess, &hDup,
376                          EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, 0)) {
377         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, APLOGNO(00394)
378                      "Parent: Unable to duplicate the exit event handle for the child");
379         return -1;
380     }
381     if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
382             != APR_SUCCESS) {
383         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00395)
384                      "Parent: Unable to send the exit event handle to the child");
385         return -1;
386     }
387     if ((rv = apr_os_proc_mutex_get(&os_start, child_start_mutex)) != APR_SUCCESS) {
388         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00396)
389                      "Parent: Unable to retrieve the start mutex for the child");
390         return -1;
391     }
392     if (!DuplicateHandle(hCurrentProcess, os_start, hProcess, &hDup,
393                          SYNCHRONIZE, FALSE, 0)) {
394         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, APLOGNO(00397)
395                      "Parent: Unable to duplicate the start mutex to the child");
396         return -1;
397     }
398     if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
399             != APR_SUCCESS) {
400         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00398)
401                      "Parent: Unable to send the start mutex to the child");
402         return -1;
403     }
404     if ((rv = apr_os_shm_get(&hScore, scoreboard_shm)) != APR_SUCCESS) {
405         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00399)
406                      "Parent: Unable to retrieve the scoreboard handle for the child");
407         return -1;
408     }
409     if (!DuplicateHandle(hCurrentProcess, hScore, hProcess, &hDup,
410                          FILE_MAP_READ | FILE_MAP_WRITE, FALSE, 0)) {
411         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, APLOGNO(00400)
412                      "Parent: Unable to duplicate the scoreboard handle to the child");
413         return -1;
414     }
415     if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten))
416             != APR_SUCCESS) {
417         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00401)
418                      "Parent: Unable to send the scoreboard handle to the child");
419         return -1;
420     }
421 
422     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(00402)
423                  "Parent: Sent the scoreboard to the child");
424     return 0;
425 }
426 
427 
428 /*
429  * get_listeners_from_parent()
430  * The listen sockets are opened in the parent. This function, which runs
431  * exclusively in the child process, receives them from the parent and
432  * makes them availeble in the child.
433  */
get_listeners_from_parent(server_rec * s)434 static void get_listeners_from_parent(server_rec *s)
435 {
436     WSAPROTOCOL_INFO WSAProtocolInfo;
437     ap_listen_rec *lr;
438     DWORD BytesRead;
439     int lcnt = 0;
440     SOCKET nsd;
441 
442     /* Set up a default listener if necessary */
443     if (ap_listeners == NULL) {
444         ap_listen_rec *lr;
445         lr = apr_palloc(s->process->pool, sizeof(ap_listen_rec));
446         lr->sd = NULL;
447         lr->next = ap_listeners;
448         ap_listeners = lr;
449     }
450 
451     /* Open the pipe to the parent process to receive the inherited socket
452      * data. The sockets have been set to listening in the parent process.
453      *
454      * *** We now do this way back in winnt_rewrite_args
455      * pipe = GetStdHandle(STD_INPUT_HANDLE);
456      */
457     for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) {
458         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(00403)
459                      "Child: Waiting for data for listening socket %pI",
460                      lr->bind_addr);
461         if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO),
462                       &BytesRead, (LPOVERLAPPED) NULL)) {
463             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, APLOGNO(00404)
464                          "Child: Unable to read socket data from parent");
465             exit(APEXIT_CHILDINIT);
466         }
467 
468         nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
469                         &WSAProtocolInfo, 0, 0);
470         if (nsd == INVALID_SOCKET) {
471             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf, APLOGNO(00405)
472                          "Child: WSASocket failed to open the inherited socket");
473             exit(APEXIT_CHILDINIT);
474         }
475 
476         if (!SetHandleInformation((HANDLE)nsd, HANDLE_FLAG_INHERIT, 0)) {
477             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), ap_server_conf, APLOGNO(00406)
478                          "Child: SetHandleInformation failed");
479         }
480         apr_os_sock_put(&lr->sd, &nsd, s->process->pool);
481     }
482 
483     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(00407)
484                  "Child: retrieved %d listeners from parent", lcnt);
485 }
486 
487 
send_listeners_to_child(apr_pool_t * p,DWORD dwProcessId,apr_file_t * child_in)488 static int send_listeners_to_child(apr_pool_t *p, DWORD dwProcessId,
489                                    apr_file_t *child_in)
490 {
491     apr_status_t rv;
492     int lcnt = 0;
493     ap_listen_rec *lr;
494     LPWSAPROTOCOL_INFO  lpWSAProtocolInfo;
495     apr_size_t BytesWritten;
496 
497     /* Run the chain of open sockets. For each socket, duplicate it
498      * for the target process then send the WSAPROTOCOL_INFO
499      * (returned by dup socket) to the child.
500      */
501     for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) {
502         apr_os_sock_t nsd;
503         lpWSAProtocolInfo = apr_pcalloc(p, sizeof(WSAPROTOCOL_INFO));
504         apr_os_sock_get(&nsd, lr->sd);
505         ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, ap_server_conf, APLOGNO(00408)
506                      "Parent: Duplicating socket %d (%pI) and sending it to child process %lu",
507                      nsd, lr->bind_addr, dwProcessId);
508         if (WSADuplicateSocket(nsd, dwProcessId,
509                                lpWSAProtocolInfo) == SOCKET_ERROR) {
510             ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf, APLOGNO(00409)
511                          "Parent: WSADuplicateSocket failed for socket %d. Check the FAQ.", nsd);
512             return -1;
513         }
514 
515         if ((rv = apr_file_write_full(child_in, lpWSAProtocolInfo,
516                                       sizeof(WSAPROTOCOL_INFO), &BytesWritten))
517                 != APR_SUCCESS) {
518             ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00410)
519                          "Parent: Unable to write duplicated socket %d to the child.", nsd);
520             return -1;
521         }
522     }
523 
524     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(00411)
525                  "Parent: Sent %d listeners to child %lu", lcnt, dwProcessId);
526     return 0;
527 }
528 
529 enum waitlist_e {
530     waitlist_ready = 0,
531     waitlist_term = 1
532 };
533 
create_process(apr_pool_t * p,HANDLE * child_proc,HANDLE * child_exit_event,DWORD * child_pid)534 static int create_process(apr_pool_t *p, HANDLE *child_proc, HANDLE *child_exit_event,
535                           DWORD *child_pid)
536 {
537     /* These NEVER change for the lifetime of this parent
538      */
539     static char **args = NULL;
540     static char pidbuf[28];
541 
542     apr_status_t rv;
543     apr_pool_t *ptemp;
544     apr_procattr_t *attr;
545     apr_proc_t new_child;
546     HANDLE hExitEvent;
547     HANDLE waitlist[2];  /* see waitlist_e */
548     char *cmd;
549     char *cwd;
550     char **env;
551     int envc;
552 
553     apr_pool_create_ex(&ptemp, p, NULL, NULL);
554 
555     /* Build the command line. Should look something like this:
556      * C:/apache/bin/httpd.exe -f ap_server_confname
557      * First, get the path to the executable...
558      */
559     apr_procattr_create(&attr, ptemp);
560     apr_procattr_cmdtype_set(attr, APR_PROGRAM);
561     apr_procattr_detach_set(attr, 1);
562     if (((rv = apr_filepath_get(&cwd, 0, ptemp)) != APR_SUCCESS)
563            || ((rv = apr_procattr_dir_set(attr, cwd)) != APR_SUCCESS)) {
564         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00412)
565                      "Parent: Failed to get the current path");
566     }
567 
568     if (!args) {
569         /* Build the args array, only once since it won't change
570          * for the lifetime of this parent process.
571          */
572         if ((rv = ap_os_proc_filepath(&cmd, ptemp))
573                 != APR_SUCCESS) {
574             ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, ap_server_conf, APLOGNO(00413)
575                          "Parent: Failed to get full path of %s",
576                          ap_server_conf->process->argv[0]);
577             apr_pool_destroy(ptemp);
578             return -1;
579         }
580 
581         args = malloc((ap_server_conf->process->argc + 1) * sizeof (char*));
582         memcpy(args + 1, ap_server_conf->process->argv + 1,
583                (ap_server_conf->process->argc - 1) * sizeof (char*));
584         args[0] = malloc(strlen(cmd) + 1);
585         strcpy(args[0], cmd);
586         args[ap_server_conf->process->argc] = NULL;
587     }
588     else {
589         cmd = args[0];
590     }
591 
592     /* Create a pipe to send handles to the child */
593     if ((rv = apr_procattr_io_set(attr, APR_FULL_BLOCK,
594                                   APR_NO_PIPE, APR_NO_PIPE)) != APR_SUCCESS) {
595         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00414)
596                         "Parent: Unable to create child stdin pipe.");
597         apr_pool_destroy(ptemp);
598         return -1;
599     }
600 
601     /* Create the child_ready_event */
602     waitlist[waitlist_ready] = CreateEvent(NULL, TRUE, FALSE, NULL);
603     if (!waitlist[waitlist_ready]) {
604         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, APLOGNO(00415)
605                      "Parent: Could not create ready event for child process");
606         apr_pool_destroy (ptemp);
607         return -1;
608     }
609 
610     /* Create the child_exit_event */
611     hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
612     if (!hExitEvent) {
613         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, APLOGNO(00416)
614                      "Parent: Could not create exit event for child process");
615         apr_pool_destroy(ptemp);
616         CloseHandle(waitlist[waitlist_ready]);
617         return -1;
618     }
619 
620     /* Build the env array */
621     for (envc = 0; _environ[envc]; ++envc) {
622         ;
623     }
624     env = apr_palloc(ptemp, (envc + 2) * sizeof (char*));
625     memcpy(env, _environ, envc * sizeof (char*));
626     apr_snprintf(pidbuf, sizeof(pidbuf), "AP_PARENT_PID=%lu", parent_pid);
627     env[envc] = pidbuf;
628     env[envc + 1] = NULL;
629 
630     rv = apr_proc_create(&new_child, cmd, (const char * const *)args,
631                          (const char * const *)env, attr, ptemp);
632     if (rv != APR_SUCCESS) {
633         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00417)
634                      "Parent: Failed to create the child process.");
635         apr_pool_destroy(ptemp);
636         CloseHandle(hExitEvent);
637         CloseHandle(waitlist[waitlist_ready]);
638         CloseHandle(new_child.hproc);
639         return -1;
640     }
641 
642     ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf, APLOGNO(00418)
643                  "Parent: Created child process %d", new_child.pid);
644 
645     if (send_handles_to_child(ptemp, waitlist[waitlist_ready], hExitEvent,
646                               start_mutex, ap_scoreboard_shm,
647                               new_child.hproc, new_child.in)) {
648         /*
649          * This error is fatal, mop up the child and move on
650          * We toggle the child's exit event to cause this child
651          * to quit even as it is attempting to start.
652          */
653         SetEvent(hExitEvent);
654         apr_pool_destroy(ptemp);
655         CloseHandle(hExitEvent);
656         CloseHandle(waitlist[waitlist_ready]);
657         CloseHandle(new_child.hproc);
658         return -1;
659     }
660 
661     /* Important:
662      * Give the child process a chance to run before dup'ing the sockets.
663      * We have already set the listening sockets noninheritable, but if
664      * WSADuplicateSocket runs before the child process initializes
665      * the listeners will be inherited anyway.
666      */
667     waitlist[waitlist_term] = new_child.hproc;
668     rv = WaitForMultipleObjects(2, waitlist, FALSE, INFINITE);
669     CloseHandle(waitlist[waitlist_ready]);
670     if (rv != WAIT_OBJECT_0) {
671         /*
672          * Outch... that isn't a ready signal. It's dead, Jim!
673          */
674         SetEvent(hExitEvent);
675         apr_pool_destroy(ptemp);
676         CloseHandle(hExitEvent);
677         CloseHandle(new_child.hproc);
678         return -1;
679     }
680 
681     if (send_listeners_to_child(ptemp, new_child.pid, new_child.in)) {
682         /*
683          * This error is fatal, mop up the child and move on
684          * We toggle the child's exit event to cause this child
685          * to quit even as it is attempting to start.
686          */
687         SetEvent(hExitEvent);
688         apr_pool_destroy(ptemp);
689         CloseHandle(hExitEvent);
690         CloseHandle(new_child.hproc);
691         return -1;
692     }
693 
694     apr_file_close(new_child.in);
695 
696     *child_exit_event = hExitEvent;
697     *child_proc = new_child.hproc;
698     *child_pid = new_child.pid;
699 
700     return 0;
701 }
702 
703 /***********************************************************************
704  * master_main()
705  * master_main() runs in the parent process.  It creates the child
706  * process which handles HTTP requests then waits on one of three
707  * events:
708  *
709  * restart_event
710  * -------------
711  * The restart event causes master_main to start a new child process and
712  * tells the old child process to exit (by setting the child_exit_event).
713  * The restart event is set as a result of one of the following:
714  * 1. An apache -k restart command on the command line
715  * 2. A command received from Windows service manager which gets
716  *    translated into an ap_signal_parent(SIGNAL_PARENT_RESTART)
717  *    call by code in service.c.
718  * 3. The child process calling ap_signal_parent(SIGNAL_PARENT_RESTART)
719  *    as a result of hitting MaxConnectionsPerChild.
720  *
721  * shutdown_event
722  * --------------
723  * The shutdown event causes master_main to tell the child process to
724  * exit and that the server is shutting down. The shutdown event is
725  * set as a result of one of the following:
726  * 1. An apache -k shutdown command on the command line
727  * 2. A command received from Windows service manager which gets
728  *    translated into an ap_signal_parent(SIGNAL_PARENT_SHUTDOWN)
729  *    call by code in service.c.
730  *
731  * child process handle
732  * --------------------
733  * The child process handle will be signaled if the child process
734  * exits for any reason. In a normal running server, the signaling
735  * of this event means that the child process has exited prematurely
736  * due to a seg fault or other irrecoverable error. For server
737  * robustness, master_main will restart the child process under this
738  * condtion.
739  *
740  * master_main uses the child_exit_event to signal the child process
741  * to exit.
742  **********************************************************************/
743 #define NUM_WAIT_HANDLES 3
744 #define CHILD_HANDLE     0
745 #define SHUTDOWN_HANDLE  1
746 #define RESTART_HANDLE   2
master_main(server_rec * s,HANDLE shutdown_event,HANDLE restart_event)747 static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event)
748 {
749     int rv, cld;
750     int child_created;
751     int restart_pending;
752     int shutdown_pending;
753     HANDLE child_exit_event;
754     HANDLE event_handles[NUM_WAIT_HANDLES];
755     DWORD child_pid;
756 
757     child_created = restart_pending = shutdown_pending = 0;
758 
759     event_handles[SHUTDOWN_HANDLE] = shutdown_event;
760     event_handles[RESTART_HANDLE] = restart_event;
761 
762     /* Create a single child process */
763     rv = create_process(pconf, &event_handles[CHILD_HANDLE],
764                         &child_exit_event, &child_pid);
765     if (rv < 0)
766     {
767         ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, APLOGNO(00419)
768                      "master_main: create child process failed. Exiting.");
769         shutdown_pending = 1;
770         goto die_now;
771     }
772 
773     child_created = 1;
774 
775     if (!strcasecmp(signal_arg, "runservice")) {
776         mpm_service_started();
777     }
778 
779     /* Update the scoreboard. Note that there is only a single active
780      * child at once.
781      */
782     ap_scoreboard_image->parent[0].quiescing = 0;
783     winnt_note_child_started(/* slot */ 0, child_pid);
784 
785     /* Wait for shutdown or restart events or for child death */
786     winnt_mpm_state = AP_MPMQ_RUNNING;
787     rv = WaitForMultipleObjects(NUM_WAIT_HANDLES, (HANDLE *) event_handles, FALSE, INFINITE);
788     cld = rv - WAIT_OBJECT_0;
789     if (rv == WAIT_FAILED) {
790         /* Something serious is wrong */
791         ap_log_error(APLOG_MARK,APLOG_CRIT, apr_get_os_error(), ap_server_conf, APLOGNO(00420)
792                      "master_main: WaitForMultipleObjects WAIT_FAILED -- doing server shutdown");
793         shutdown_pending = 1;
794     }
795     else if (rv == WAIT_TIMEOUT) {
796         /* Hey, this cannot happen */
797         ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s, APLOGNO(00421)
798                      "master_main: WaitForMultipleObjects with INFINITE wait exited with WAIT_TIMEOUT");
799         shutdown_pending = 1;
800     }
801     else if (cld == SHUTDOWN_HANDLE) {
802         /* shutdown_event signalled */
803         shutdown_pending = 1;
804         ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, s, APLOGNO(00422)
805                      "Parent: Received shutdown signal -- Shutting down the server.");
806         if (ResetEvent(shutdown_event) == 0) {
807             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s, APLOGNO(00423)
808                          "ResetEvent(shutdown_event)");
809         }
810     }
811     else if (cld == RESTART_HANDLE) {
812         /* Received a restart event. Prepare the restart_event to be reused
813          * then signal the child process to exit.
814          */
815         restart_pending = 1;
816         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s, APLOGNO(00424)
817                      "Parent: Received restart signal -- Restarting the server.");
818         if (ResetEvent(restart_event) == 0) {
819             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s, APLOGNO(00425)
820                          "Parent: ResetEvent(restart_event) failed.");
821         }
822         if (SetEvent(child_exit_event) == 0) {
823             ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s, APLOGNO(00426)
824                          "Parent: SetEvent for child process event %pp failed.",
825                          event_handles[CHILD_HANDLE]);
826         }
827         /* Don't wait to verify that the child process really exits,
828          * just move on with the restart.
829          */
830         CloseHandle(event_handles[CHILD_HANDLE]);
831         event_handles[CHILD_HANDLE] = NULL;
832     }
833     else {
834         /* The child process exited prematurely due to a fatal error. */
835         DWORD exitcode;
836         if (!GetExitCodeProcess(event_handles[CHILD_HANDLE], &exitcode)) {
837             /* HUH? We did exit, didn't we? */
838             exitcode = APEXIT_CHILDFATAL;
839         }
840         if (   exitcode == APEXIT_CHILDFATAL
841             || exitcode == APEXIT_CHILDINIT
842             || exitcode == APEXIT_INIT) {
843             ap_log_error(APLOG_MARK, APLOG_CRIT, 0, ap_server_conf, APLOGNO(00427)
844                          "Parent: child process %lu exited with status %lu -- Aborting.",
845                          child_pid, exitcode);
846             shutdown_pending = 1;
847         }
848         else {
849             int i;
850             restart_pending = 1;
851             ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf, APLOGNO(00428)
852                          "Parent: child process %lu exited with status %lu -- Restarting.",
853                          child_pid, exitcode);
854             for (i = 0; i < ap_threads_per_child; i++) {
855                 ap_update_child_status_from_indexes(0, i, SERVER_DEAD, NULL);
856             }
857         }
858         CloseHandle(event_handles[CHILD_HANDLE]);
859         event_handles[CHILD_HANDLE] = NULL;
860     }
861 
862     winnt_note_child_killed(/* slot */ 0);
863 
864     if (restart_pending) {
865         ++my_generation;
866         ap_scoreboard_image->global->running_generation = my_generation;
867     }
868 die_now:
869     if (shutdown_pending)
870     {
871         int timeout = 30000;  /* Timeout is milliseconds */
872         winnt_mpm_state = AP_MPMQ_STOPPING;
873 
874         if (!child_created) {
875             return 0;  /* Tell the caller we do not want to restart */
876         }
877 
878         /* This shutdown is only marginally graceful. We will give the
879          * child a bit of time to exit gracefully. If the time expires,
880          * the child will be wacked.
881          */
882         if (!strcasecmp(signal_arg, "runservice")) {
883             mpm_service_stopping();
884         }
885         /* Signal the child processes to exit */
886         if (SetEvent(child_exit_event) == 0) {
887                 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), ap_server_conf, APLOGNO(00429)
888                              "Parent: SetEvent for child process event %pp failed",
889                              event_handles[CHILD_HANDLE]);
890         }
891         if (event_handles[CHILD_HANDLE]) {
892             rv = WaitForSingleObject(event_handles[CHILD_HANDLE], timeout);
893             if (rv == WAIT_OBJECT_0) {
894                 ap_log_error(APLOG_MARK,APLOG_NOTICE, APR_SUCCESS, ap_server_conf, APLOGNO(00430)
895                              "Parent: Child process %lu exited successfully.", child_pid);
896                 CloseHandle(event_handles[CHILD_HANDLE]);
897                 event_handles[CHILD_HANDLE] = NULL;
898             }
899             else {
900                 ap_log_error(APLOG_MARK,APLOG_NOTICE, APR_SUCCESS, ap_server_conf, APLOGNO(00431)
901                              "Parent: Forcing termination of child process %lu",
902                              child_pid);
903                 TerminateProcess(event_handles[CHILD_HANDLE], 1);
904                 CloseHandle(event_handles[CHILD_HANDLE]);
905                 event_handles[CHILD_HANDLE] = NULL;
906             }
907         }
908         CloseHandle(child_exit_event);
909         return 0;  /* Tell the caller we do not want to restart */
910     }
911     winnt_mpm_state = AP_MPMQ_STARTING;
912     CloseHandle(child_exit_event);
913     return 1;      /* Tell the caller we want a restart */
914 }
915 
916 /* service_nt_main_fn needs to append the StartService() args
917  * outside of our call stack and thread as the service starts...
918  */
919 apr_array_header_t *mpm_new_argv;
920 
921 /* Remember service_to_start failures to log and fail in pre_config.
922  * Remember inst_argc and inst_argv for installing or starting the
923  * service after we preflight the config.
924  */
925 
winnt_query(int query_code,int * result,apr_status_t * rv)926 static int winnt_query(int query_code, int *result, apr_status_t *rv)
927 {
928     *rv = APR_SUCCESS;
929     switch (query_code) {
930         case AP_MPMQ_MAX_DAEMON_USED:
931             *result = MAXIMUM_WAIT_OBJECTS;
932             break;
933         case AP_MPMQ_IS_THREADED:
934             *result = AP_MPMQ_STATIC;
935             break;
936         case AP_MPMQ_IS_FORKED:
937             *result = AP_MPMQ_NOT_SUPPORTED;
938             break;
939         case AP_MPMQ_HARD_LIMIT_DAEMONS:
940             *result = HARD_SERVER_LIMIT;
941             break;
942         case AP_MPMQ_HARD_LIMIT_THREADS:
943             *result = thread_limit;
944             break;
945         case AP_MPMQ_MAX_THREADS:
946             *result = ap_threads_per_child;
947             break;
948         case AP_MPMQ_MIN_SPARE_DAEMONS:
949             *result = 0;
950             break;
951         case AP_MPMQ_MIN_SPARE_THREADS:
952             *result = 0;
953             break;
954         case AP_MPMQ_MAX_SPARE_DAEMONS:
955             *result = 0;
956             break;
957         case AP_MPMQ_MAX_SPARE_THREADS:
958             *result = 0;
959             break;
960         case AP_MPMQ_MAX_REQUESTS_DAEMON:
961             *result = ap_max_requests_per_child;
962             break;
963         case AP_MPMQ_MAX_DAEMONS:
964             *result = 1;
965             break;
966         case AP_MPMQ_MPM_STATE:
967             *result = winnt_mpm_state;
968             break;
969         case AP_MPMQ_GENERATION:
970             *result = my_generation;
971             break;
972         default:
973             *rv = APR_ENOTIMPL;
974             break;
975     }
976     return OK;
977 }
978 
winnt_get_name(void)979 static const char *winnt_get_name(void)
980 {
981     return "WinNT";
982 }
983 
984 #define SERVICE_UNSET (-1)
985 static apr_status_t service_set = SERVICE_UNSET;
986 static apr_status_t service_to_start_success;
987 static int inst_argc;
988 static const char * const *inst_argv;
989 static const char *service_name = NULL;
990 
winnt_rewrite_args(process_rec * process)991 static void winnt_rewrite_args(process_rec *process)
992 {
993     /* Handle the following SCM aspects in this phase:
994      *
995      *   -k runservice [transition in service context only]
996      *   -k install
997      *   -k config
998      *   -k uninstall
999      *   -k stop
1000      *   -k shutdown (same as -k stop). Maintained for backward compatability.
1001      *
1002      * We can't leave this phase until we know our identity
1003      * and modify the command arguments appropriately.
1004      *
1005      * We do not care if the .conf file exists or is parsable when
1006      * attempting to stop or uninstall a service.
1007      */
1008     apr_status_t rv;
1009     char *def_server_root;
1010     char *binpath;
1011     char optbuf[3];
1012     const char *opt_arg;
1013     int fixed_args;
1014     char *pid;
1015     apr_getopt_t *opt;
1016     int running_as_service = 1;
1017     int errout = 0;
1018     apr_file_t *nullfile;
1019 
1020     pconf = process->pconf;
1021 
1022     osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1023     GetVersionEx(&osver);
1024 
1025     /* We wish this was *always* a reservation, but sadly it wasn't so and
1026      * we couldn't break a hard limit prior to NT Kernel 5.1
1027      */
1028     if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT
1029         && ((osver.dwMajorVersion > 5)
1030          || ((osver.dwMajorVersion == 5) && (osver.dwMinorVersion > 0)))) {
1031         stack_res_flag = STACK_SIZE_PARAM_IS_A_RESERVATION;
1032     }
1033 
1034     /* AP_PARENT_PID is only valid in the child */
1035     pid = getenv("AP_PARENT_PID");
1036     if (pid)
1037     {
1038         HANDLE filehand;
1039         HANDLE hproc = GetCurrentProcess();
1040 
1041         /* This is the child */
1042         my_pid = GetCurrentProcessId();
1043         parent_pid = (DWORD) atol(pid);
1044 
1045         /* Prevent holding open the (nonexistant) console */
1046         ap_real_exit_code = 0;
1047 
1048         /* The parent gave us stdin, we need to remember this
1049          * handle, and no longer inherit it at our children
1050          * (we can't slurp it up now, we just aren't ready yet).
1051          * The original handle is closed below, at apr_file_dup2()
1052          */
1053         pipe = GetStdHandle(STD_INPUT_HANDLE);
1054         if (DuplicateHandle(hproc, pipe,
1055                             hproc, &filehand, 0, FALSE,
1056                             DUPLICATE_SAME_ACCESS)) {
1057             pipe = filehand;
1058         }
1059 
1060         /* The parent gave us stdout of the NUL device,
1061          * and expects us to suck up stdin of all of our
1062          * shared handles and data from the parent.
1063          * Don't infect child processes with our stdin
1064          * handle, use another handle to NUL!
1065          */
1066         {
1067             apr_file_t *infile, *outfile;
1068             if ((apr_file_open_stdout(&outfile, process->pool) == APR_SUCCESS)
1069              && (apr_file_open_stdin(&infile, process->pool) == APR_SUCCESS))
1070                 apr_file_dup2(infile, outfile, process->pool);
1071         }
1072 
1073         /* This child needs the existing stderr opened for logging,
1074          * already
1075          */
1076 
1077 
1078         /* The parent is responsible for providing the
1079          * COMPLETE ARGUMENTS REQUIRED to the child.
1080          *
1081          * No further argument parsing is needed, but
1082          * for good measure we will provide a simple
1083          * signal string for later testing.
1084          */
1085         signal_arg = "runchild";
1086         return;
1087     }
1088 
1089     /* This is the parent, we have a long way to go :-) */
1090     parent_pid = my_pid = GetCurrentProcessId();
1091 
1092     /* This behavior is voided by setting real_exit_code to 0 */
1093     atexit(hold_console_open_on_error);
1094 
1095     /* Rewrite process->argv[];
1096      *
1097      * strip out -k signal into signal_arg
1098      * strip out -n servicename and set the names
1099      * add default -d serverroot from the path of this executable
1100      *
1101      * The end result will look like:
1102      *
1103      * The invocation command (%0)
1104      *     The -d serverroot default from the running executable
1105      *         The requested service's (-n) registry ConfigArgs
1106      *             The WinNT SCM's StartService() args
1107      */
1108     if ((rv = ap_os_proc_filepath(&binpath, process->pconf))
1109             != APR_SUCCESS) {
1110         ap_log_error(APLOG_MARK,APLOG_CRIT, rv, NULL, APLOGNO(00432)
1111                      "Failed to get the full path of %s", process->argv[0]);
1112         exit(APEXIT_INIT);
1113     }
1114     /* WARNING: There is an implict assumption here that the
1115      * executable resides in ServerRoot or ServerRoot\bin
1116      */
1117     def_server_root = (char *) apr_filepath_name_get(binpath);
1118     if (def_server_root > binpath) {
1119         *(def_server_root - 1) = '\0';
1120         def_server_root = (char *) apr_filepath_name_get(binpath);
1121         if (!strcasecmp(def_server_root, "bin"))
1122             *(def_server_root - 1) = '\0';
1123     }
1124     apr_filepath_merge(&def_server_root, NULL, binpath,
1125                        APR_FILEPATH_TRUENAME, process->pool);
1126 
1127     /* Use process->pool so that the rewritten argv
1128      * lasts for the lifetime of the server process,
1129      * because pconf will be destroyed after the
1130      * initial pre-flight of the config parser.
1131      */
1132     mpm_new_argv = apr_array_make(process->pool, process->argc + 2,
1133                                   sizeof(const char *));
1134     *(const char **)apr_array_push(mpm_new_argv) = process->argv[0];
1135     *(const char **)apr_array_push(mpm_new_argv) = "-d";
1136     *(const char **)apr_array_push(mpm_new_argv) = def_server_root;
1137 
1138     fixed_args = mpm_new_argv->nelts;
1139 
1140     optbuf[0] = '-';
1141     optbuf[2] = '\0';
1142     apr_getopt_init(&opt, process->pool, process->argc, process->argv);
1143     opt->errfn = NULL;
1144     while ((rv = apr_getopt(opt, "wn:k:" AP_SERVER_BASEARGS,
1145                             optbuf + 1, &opt_arg)) == APR_SUCCESS) {
1146         switch (optbuf[1]) {
1147 
1148         /* Shortcuts; include the -w option to hold the window open on error.
1149          * This must not be toggled once we reset ap_real_exit_code to 0!
1150          */
1151         case 'w':
1152             if (ap_real_exit_code)
1153                 ap_real_exit_code = 2;
1154             break;
1155 
1156         case 'n':
1157             service_set = mpm_service_set_name(process->pool, &service_name,
1158                                                opt_arg);
1159             break;
1160 
1161         case 'k':
1162             signal_arg = opt_arg;
1163             break;
1164 
1165         case 'E':
1166             errout = 1;
1167             /* Fall through so the Apache main() handles the 'E' arg */
1168         default:
1169             *(const char **)apr_array_push(mpm_new_argv) =
1170                 apr_pstrdup(process->pool, optbuf);
1171 
1172             if (opt_arg) {
1173                 *(const char **)apr_array_push(mpm_new_argv) = opt_arg;
1174             }
1175             break;
1176         }
1177     }
1178 
1179     /* back up to capture the bad argument */
1180     if (rv == APR_BADCH || rv == APR_BADARG) {
1181         opt->ind--;
1182     }
1183 
1184     while (opt->ind < opt->argc) {
1185         *(const char **)apr_array_push(mpm_new_argv) =
1186             apr_pstrdup(process->pool, opt->argv[opt->ind++]);
1187     }
1188 
1189     /* Track the number of args actually entered by the user */
1190     inst_argc = mpm_new_argv->nelts - fixed_args;
1191 
1192     /* Provide a default 'run' -k arg to simplify signal_arg tests */
1193     if (!signal_arg)
1194     {
1195         signal_arg = "run";
1196         running_as_service = 0;
1197     }
1198 
1199     if (!strcasecmp(signal_arg, "runservice"))
1200     {
1201         /* Start the NT Service _NOW_ because the WinNT SCM is
1202          * expecting us to rapidly assume control of our own
1203          * process, the SCM will tell us our service name, and
1204          * may have extra StartService() command arguments to
1205          * add for us.
1206          *
1207          * The SCM will generally invoke the executable with
1208          * the c:\win\system32 default directory.  This is very
1209          * lethal if folks use ServerRoot /foopath on windows
1210          * without a drive letter.  Change to the default root
1211          * (path to apache root, above /bin) for safety.
1212          */
1213         apr_filepath_set(def_server_root, process->pool);
1214 
1215         /* Any other process has a console, so we don't to begin
1216          * a Win9x service until the configuration is parsed and
1217          * any command line errors are reported.
1218          *
1219          * We hold the return value so that we can die in pre_config
1220          * after logging begins, and the failure can land in the log.
1221          */
1222         if (!errout) {
1223             mpm_nt_eventlog_stderr_open(service_name, process->pool);
1224         }
1225         service_to_start_success = mpm_service_to_start(&service_name,
1226                                                         process->pool);
1227         if (service_to_start_success == APR_SUCCESS) {
1228             service_set = APR_SUCCESS;
1229         }
1230 
1231         /* Open a null handle to soak stdout in this process.
1232          * Windows service processes are missing any file handle
1233          * usable for stdin/out/err.  This was the cause of later
1234          * trouble with invocations of apr_file_open_stdout()
1235          */
1236         if ((rv = apr_file_open(&nullfile, "NUL",
1237                                 APR_READ | APR_WRITE, APR_OS_DEFAULT,
1238                                 process->pool)) == APR_SUCCESS) {
1239             apr_file_t *nullstdout;
1240             if (apr_file_open_stdout(&nullstdout, process->pool)
1241                     == APR_SUCCESS)
1242                 apr_file_dup2(nullstdout, nullfile, process->pool);
1243             apr_file_close(nullfile);
1244         }
1245     }
1246 
1247     /* Get the default for any -k option, except run */
1248     if (service_set == SERVICE_UNSET && strcasecmp(signal_arg, "run")) {
1249         service_set = mpm_service_set_name(process->pool, &service_name,
1250                                            AP_DEFAULT_SERVICE_NAME);
1251     }
1252 
1253     if (!strcasecmp(signal_arg, "install")) /* -k install */
1254     {
1255         if (service_set == APR_SUCCESS)
1256         {
1257             ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL, APLOGNO(00433)
1258                  "%s: Service is already installed.", service_name);
1259             exit(APEXIT_INIT);
1260         }
1261     }
1262     else if (running_as_service)
1263     {
1264         if (service_set == APR_SUCCESS)
1265         {
1266             /* Attempt to Uninstall, or stop, before
1267              * we can read the arguments or .conf files
1268              */
1269             if (!strcasecmp(signal_arg, "uninstall")) {
1270                 rv = mpm_service_uninstall();
1271                 exit(rv);
1272             }
1273 
1274             if ((!strcasecmp(signal_arg, "stop")) ||
1275                 (!strcasecmp(signal_arg, "shutdown"))) {
1276                 mpm_signal_service(process->pool, 0);
1277                 exit(0);
1278             }
1279 
1280             rv = mpm_merge_service_args(process->pool, mpm_new_argv,
1281                                         fixed_args);
1282             if (rv == APR_SUCCESS) {
1283                 ap_log_error(APLOG_MARK,APLOG_INFO, 0, NULL, APLOGNO(00434)
1284                              "Using ConfigArgs of the installed service "
1285                              "\"%s\".", service_name);
1286             }
1287             else  {
1288                 ap_log_error(APLOG_MARK,APLOG_WARNING, rv, NULL, APLOGNO(00435)
1289                              "No installed ConfigArgs for the service "
1290                              "\"%s\", using Apache defaults.", service_name);
1291             }
1292         }
1293         else
1294         {
1295             ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL, APLOGNO(00436)
1296                  "No installed service named \"%s\".", service_name);
1297             exit(APEXIT_INIT);
1298         }
1299     }
1300     if (strcasecmp(signal_arg, "install") && service_set && service_set != SERVICE_UNSET)
1301     {
1302         ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL, APLOGNO(00437)
1303              "No installed service named \"%s\".", service_name);
1304         exit(APEXIT_INIT);
1305     }
1306 
1307     /* Track the args actually entered by the user.
1308      * These will be used for the -k install parameters, as well as
1309      * for the -k start service override arguments.
1310      */
1311     inst_argv = (const char * const *)mpm_new_argv->elts
1312         + mpm_new_argv->nelts - inst_argc;
1313 
1314     /* Now, do service install or reconfigure then proceed to
1315      * post_config to test the installed configuration.
1316      */
1317     if (!strcasecmp(signal_arg, "config")) { /* -k config */
1318         /* Reconfigure the service */
1319         rv = mpm_service_install(process->pool, inst_argc, inst_argv, 1);
1320         if (rv != APR_SUCCESS) {
1321             exit(rv);
1322         }
1323 
1324         fprintf(stderr,"Testing httpd.conf....\n");
1325         fprintf(stderr,"Errors reported here must be corrected before the "
1326                 "service can be started.\n");
1327     }
1328     else if (!strcasecmp(signal_arg, "install")) { /* -k install */
1329         /* Install the service */
1330         rv = mpm_service_install(process->pool, inst_argc, inst_argv, 0);
1331         if (rv != APR_SUCCESS) {
1332             exit(rv);
1333         }
1334 
1335         fprintf(stderr,"Testing httpd.conf....\n");
1336         fprintf(stderr,"Errors reported here must be corrected before the "
1337                 "service can be started.\n");
1338     }
1339 
1340     process->argc = mpm_new_argv->nelts;
1341     process->argv = (const char * const *) mpm_new_argv->elts;
1342 }
1343 
1344 
winnt_pre_config(apr_pool_t * pconf_,apr_pool_t * plog,apr_pool_t * ptemp)1345 static int winnt_pre_config(apr_pool_t *pconf_, apr_pool_t *plog, apr_pool_t *ptemp)
1346 {
1347     /* Handle the following SCM aspects in this phase:
1348      *
1349      *   -k runservice [WinNT errors logged from rewrite_args]
1350      */
1351 
1352     /* Initialize shared static objects.
1353      * TODO: Put config related statics into an sconf structure.
1354      */
1355     pconf = pconf_;
1356 
1357     if (ap_exists_config_define("ONE_PROCESS") ||
1358         ap_exists_config_define("DEBUG"))
1359         one_process = -1;
1360 
1361     /* XXX: presume proper privilages; one nice thing would be
1362      * a loud emit if running as "LocalSystem"/"SYSTEM" to indicate
1363      * they should change to a user with write access to logs/ alone.
1364      */
1365     ap_sys_privileges_handlers(1);
1366 
1367     if (!strcasecmp(signal_arg, "runservice")
1368             && (service_to_start_success != APR_SUCCESS)) {
1369         ap_log_error(APLOG_MARK,APLOG_CRIT, service_to_start_success, NULL, APLOGNO(00438)
1370                      "%s: Unable to start the service manager.",
1371                      service_name);
1372         exit(APEXIT_INIT);
1373     }
1374     else if (ap_state_query(AP_SQ_RUN_MODE) == AP_SQ_RM_NORMAL
1375              && !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 
winnt_check_config(apr_pool_t * pconf,apr_pool_t * plog,apr_pool_t * ptemp,server_rec * s)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     int startup = 0;
1408 
1409     /* We want this only in the parent and only the first time around */
1410     is_parent = (parent_pid == my_pid);
1411     if (is_parent &&
1412         ap_state_query(AP_SQ_MAIN_STATE) == AP_SQ_MS_CREATE_PRE_CONFIG) {
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, APLOGNO(00439)
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, APLOGNO(00440)
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, APLOGNO(00441)
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, APLOGNO(00442)
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, APLOGNO(00443)
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, APLOGNO(00444)
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, APLOGNO(00445)
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, APLOGNO(00446)
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, APLOGNO(00447)
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 
winnt_post_config(apr_pool_t * pconf,apr_pool_t * plog,apr_pool_t * ptemp,server_rec * s)1497 static int winnt_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec* s)
1498 {
1499     apr_status_t rv = 0;
1500 
1501     /* Handle the following SCM aspects in this phase:
1502      *
1503      *   -k install (catch and exit as install was handled in rewrite_args)
1504      *   -k config  (catch and exit as config was handled in rewrite_args)
1505      *   -k start
1506      *   -k restart
1507      *   -k runservice [Win95, only once - after we parsed the config]
1508      *
1509      * because all of these signals are useful _only_ if there
1510      * is a valid conf\httpd.conf environment to start.
1511      *
1512      * We reached this phase by avoiding errors that would cause
1513      * these options to fail unexpectedly in another process.
1514      */
1515 
1516     if (!strcasecmp(signal_arg, "install")) {
1517         /* Service install happens in the rewrite_args hooks. If we
1518          * made it this far, the server configuration is clean and the
1519          * service will successfully start.
1520          */
1521         apr_pool_destroy(s->process->pool);
1522         apr_terminate();
1523         exit(0);
1524     }
1525     if (!strcasecmp(signal_arg, "config")) {
1526         /* Service reconfiguration happens in the rewrite_args hooks. If we
1527          * made it this far, the server configuration is clean and the
1528          * service will successfully start.
1529          */
1530         apr_pool_destroy(s->process->pool);
1531         apr_terminate();
1532         exit(0);
1533     }
1534 
1535     if (!strcasecmp(signal_arg, "start")) {
1536         ap_listen_rec *lr;
1537 
1538         /* Close the listening sockets. */
1539         for (lr = ap_listeners; lr; lr = lr->next) {
1540             apr_socket_close(lr->sd);
1541             lr->active = 0;
1542         }
1543         rv = mpm_service_start(ptemp, inst_argc, inst_argv);
1544         apr_pool_destroy(s->process->pool);
1545         apr_terminate();
1546         exit (rv);
1547     }
1548 
1549     if (!strcasecmp(signal_arg, "restart")) {
1550         mpm_signal_service(ptemp, 1);
1551         apr_pool_destroy(s->process->pool);
1552         apr_terminate();
1553         exit (rv);
1554     }
1555 
1556     if (parent_pid == my_pid)
1557     {
1558         if (ap_state_query(AP_SQ_MAIN_STATE) != AP_SQ_MS_CREATE_PRE_CONFIG
1559             && ap_state_query(AP_SQ_CONFIG_GEN) == 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, APLOGNO(00448)
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, APLOGNO(00449)
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, APLOGNO(00450)
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  */
winnt_open_logs(apr_pool_t * p,apr_pool_t * plog,apr_pool_t * ptemp,server_rec * s)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, APLOGNO(00451) "no listening sockets available, shutting down");
1645         return DONE;
1646     }
1647 
1648     return OK;
1649 }
1650 
winnt_child_init(apr_pool_t * pchild,struct server_rec * s)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, APLOGNO(00452)
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 
winnt_run(apr_pool_t * _pconf,apr_pool_t * plog,server_rec * s)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_DEBUG, APR_SUCCESS, ap_server_conf, APLOGNO(00453)
1709                      "Child process is running");
1710 
1711         child_main(pconf);
1712 
1713         ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, ap_server_conf, APLOGNO(00454)
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, APLOGNO(00455)
1721                      "%s configured -- resuming normal operations",
1722                      ap_get_server_description());
1723         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00456)
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 
winnt_hooks(apr_pool_t * p)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     ap_hook_insert_network_bucket(winnt_insert_network_bucket, NULL, NULL,
1762                                   APR_HOOK_MIDDLE);
1763 }
1764 
1765 AP_DECLARE_MODULE(mpm_winnt) = {
1766     MPM20_MODULE_STUFF,
1767     winnt_rewrite_args,    /* hook to run before apache parses args */
1768     NULL,                  /* create per-directory config structure */
1769     NULL,                  /* merge per-directory config structures */
1770     NULL,                  /* create per-server config structure */
1771     NULL,                  /* merge per-server config structures */
1772     winnt_cmds,            /* command apr_table_t */
1773     winnt_hooks            /* register_hooks */
1774 };
1775 
1776 #endif /* def WIN32 */
1777