]> granicus.if.org Git - apache/blob - server/mpm/prefork/prefork.c
fixing compile errors due to if assignment warnings
[apache] / server / mpm / prefork / prefork.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 #include "apr.h"
18 #include "apr_portable.h"
19 #include "apr_strings.h"
20 #include "apr_thread_proc.h"
21 #include "apr_signal.h"
22
23 #define APR_WANT_STDIO
24 #define APR_WANT_STRFUNC
25 #include "apr_want.h"
26
27 #if APR_HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #if APR_HAVE_SYS_TYPES_H
31 #include <sys/types.h>
32 #endif
33
34 #include "ap_config.h"
35 #include "httpd.h"
36 #include "mpm_default.h"
37 #include "http_main.h"
38 #include "http_log.h"
39 #include "http_config.h"
40 #include "http_core.h"          /* for get_remote_host */
41 #include "http_connection.h"
42 #include "scoreboard.h"
43 #include "ap_mpm.h"
44 #include "util_mutex.h"
45 #include "unixd.h"
46 #include "mpm_common.h"
47 #include "ap_listen.h"
48 #include "ap_mmn.h"
49 #include "apr_poll.h"
50 #include "util_time.h"
51
52 #include <stdlib.h>
53
54 #ifdef HAVE_TIME_H
55 #include <time.h>
56 #endif
57 #ifdef HAVE_SYS_PROCESSOR_H
58 #include <sys/processor.h> /* for bindprocessor() */
59 #endif
60
61 #include <signal.h>
62 #include <sys/times.h>
63
64 /* Limit on the total --- clients will be locked out if more servers than
65  * this are needed.  It is intended solely to keep the server from crashing
66  * when things get out of hand.
67  *
68  * We keep a hard maximum number of servers, for two reasons --- first off,
69  * in case something goes seriously wrong, we want to stop the fork bomb
70  * short of actually crashing the machine we're running on by filling some
71  * kernel table.  Secondly, it keeps the size of the scoreboard file small
72  * enough that we can read the whole thing without worrying too much about
73  * the overhead.
74  */
75 #ifndef DEFAULT_SERVER_LIMIT
76 #define DEFAULT_SERVER_LIMIT 256
77 #endif
78
79 /* Admin can't tune ServerLimit beyond MAX_SERVER_LIMIT.  We want
80  * some sort of compile-time limit to help catch typos.
81  */
82 #ifndef MAX_SERVER_LIMIT
83 #define MAX_SERVER_LIMIT 200000
84 #endif
85
86 #ifndef HARD_THREAD_LIMIT
87 #define HARD_THREAD_LIMIT 1
88 #endif
89
90 /* config globals */
91
92 static int ap_daemons_to_start=0;
93 static int ap_daemons_min_free=0;
94 static int ap_daemons_max_free=0;
95 static int ap_daemons_limit=0;      /* MaxRequestWorkers */
96 static int server_limit = 0;
97 static int mpm_state = AP_MPMQ_STARTING;
98
99 /* data retained by prefork across load/unload of the module
100  * allocated on first call to pre-config hook; located on
101  * subsequent calls to pre-config hook
102  */
103 typedef struct prefork_retained_data {
104     int first_server_limit;
105     int module_loads;
106     ap_generation_t my_generation;
107     int volatile is_graceful; /* set from signal handler */
108     int maxclients_reported;
109     /*
110      * The max child slot ever assigned, preserved across restarts.  Necessary
111      * to deal with MaxRequestWorkers changes across AP_SIG_GRACEFUL restarts.  We
112      * use this value to optimize routines that have to scan the entire scoreboard.
113      */
114     int max_daemons_limit;
115     /*
116      * idle_spawn_rate is the number of children that will be spawned on the
117      * next maintenance cycle if there aren't enough idle servers.  It is
118      * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
119      * without the need to spawn.
120      */
121     int idle_spawn_rate;
122 #ifndef MAX_SPAWN_RATE
123 #define MAX_SPAWN_RATE  (32)
124 #endif
125     int hold_off_on_exponential_spawning;
126 } prefork_retained_data;
127 static prefork_retained_data *retained;
128
129 typedef struct prefork_child_bucket {
130     ap_pod_t *pod;
131     ap_listen_rec *listeners;
132     apr_proc_mutex_t *mutex;
133 } prefork_child_bucket;
134 static int                   num_buckets; /* Number of listeners buckets */
135 static prefork_child_bucket *all_buckets, /* All listeners buckets */
136                             *my_bucket;   /* Current child bucket */
137
138 #define MPM_CHILD_PID(i) (ap_scoreboard_image->parent[i].pid)
139
140 /* one_process --- debugging mode variable; can be set from the command line
141  * with the -X flag.  If set, this gets you the child_main loop running
142  * in the process which originally started up (no detach, no make_child),
143  * which is a pretty nice debugging environment.  (You'll get a SIGHUP
144  * early in standalone_main; just continue through.  This is the server
145  * trying to kill off any child processes which it might have lying
146  * around --- Apache doesn't keep track of their pids, it just sends
147  * SIGHUP to the process group, ignoring it in the root process.
148  * Continue through and you'll be fine.).
149  */
150
151 static int one_process = 0;
152
153 static apr_pool_t *pconf;               /* Pool for config stuff */
154 static apr_pool_t *pchild;              /* Pool for httpd child stuff */
155
156 static pid_t ap_my_pid; /* it seems silly to call getpid all the time */
157 static pid_t parent_pid;
158 static int my_child_num;
159
160 #ifdef GPROF
161 /*
162  * change directory for gprof to plop the gmon.out file
163  * configure in httpd.conf:
164  * GprofDir $RuntimeDir/   -> $ServerRoot/$RuntimeDir/gmon.out
165  * GprofDir $RuntimeDir/%  -> $ServerRoot/$RuntimeDir/gprof.$pid/gmon.out
166  */
167 static void chdir_for_gprof(void)
168 {
169     core_server_config *sconf =
170         ap_get_core_module_config(ap_server_conf->module_config);
171     char *dir = sconf->gprof_dir;
172     const char *use_dir;
173
174     if(dir) {
175         apr_status_t res;
176         char *buf = NULL ;
177         int len = strlen(sconf->gprof_dir) - 1;
178         if(*(dir + len) == '%') {
179             dir[len] = '\0';
180             buf = ap_append_pid(pconf, dir, "gprof.");
181         }
182         use_dir = ap_server_root_relative(pconf, buf ? buf : dir);
183         res = apr_dir_make(use_dir,
184                            APR_UREAD | APR_UWRITE | APR_UEXECUTE |
185                            APR_GREAD | APR_GEXECUTE |
186                            APR_WREAD | APR_WEXECUTE, pconf);
187         if(res != APR_SUCCESS && !APR_STATUS_IS_EEXIST(res)) {
188             ap_log_error(APLOG_MARK, APLOG_ERR, res, ap_server_conf, APLOGNO(00142)
189                          "gprof: error creating directory %s", dir);
190         }
191     }
192     else {
193         use_dir = ap_runtime_dir_relative(pconf, "");
194     }
195
196     chdir(use_dir);
197 }
198 #else
199 #define chdir_for_gprof()
200 #endif
201
202 static void prefork_note_child_killed(int childnum, pid_t pid,
203                                       ap_generation_t gen)
204 {
205     AP_DEBUG_ASSERT(childnum != -1); /* no scoreboard squatting with this MPM */
206     ap_run_child_status(ap_server_conf,
207                         ap_scoreboard_image->parent[childnum].pid,
208                         ap_scoreboard_image->parent[childnum].generation,
209                         childnum, MPM_CHILD_EXITED);
210     ap_scoreboard_image->parent[childnum].pid = 0;
211 }
212
213 static void prefork_note_child_started(int slot, pid_t pid)
214 {
215     ap_scoreboard_image->parent[slot].pid = pid;
216     ap_run_child_status(ap_server_conf,
217                         ap_scoreboard_image->parent[slot].pid,
218                         retained->my_generation, slot, MPM_CHILD_STARTED);
219 }
220
221 /* a clean exit from a child with proper cleanup */
222 static void clean_child_exit(int code) __attribute__ ((noreturn));
223 static void clean_child_exit(int code)
224 {
225     mpm_state = AP_MPMQ_STOPPING;
226
227     apr_signal(SIGHUP, SIG_IGN);
228     apr_signal(SIGTERM, SIG_IGN);
229
230     if (pchild) {
231         apr_pool_destroy(pchild);
232     }
233
234     if (one_process) {
235         prefork_note_child_killed(/* slot */ 0, 0, 0);
236     }
237
238     ap_mpm_pod_close(my_bucket->pod);
239     chdir_for_gprof();
240     exit(code);
241 }
242
243 static apr_status_t accept_mutex_on(void)
244 {
245     apr_status_t rv = apr_proc_mutex_lock(my_bucket->mutex);
246     if (rv != APR_SUCCESS) {
247         const char *msg = "couldn't grab the accept mutex";
248
249         if (retained->my_generation !=
250             ap_scoreboard_image->global->running_generation) {
251             ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, ap_server_conf, APLOGNO(00143) "%s", msg);
252             clean_child_exit(0);
253         }
254         else {
255             ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, APLOGNO(00144) "%s", msg);
256             exit(APEXIT_CHILDFATAL);
257         }
258     }
259     return APR_SUCCESS;
260 }
261
262 static apr_status_t accept_mutex_off(void)
263 {
264     apr_status_t rv = apr_proc_mutex_unlock(my_bucket->mutex);
265     if (rv != APR_SUCCESS) {
266         const char *msg = "couldn't release the accept mutex";
267
268         if (retained->my_generation !=
269             ap_scoreboard_image->global->running_generation) {
270             ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, ap_server_conf, APLOGNO(00145) "%s", msg);
271             /* don't exit here... we have a connection to
272              * process, after which point we'll see that the
273              * generation changed and we'll exit cleanly
274              */
275         }
276         else {
277             ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, APLOGNO(00146) "%s", msg);
278             exit(APEXIT_CHILDFATAL);
279         }
280     }
281     return APR_SUCCESS;
282 }
283
284 /* On some architectures it's safe to do unserialized accept()s in the single
285  * Listen case.  But it's never safe to do it in the case where there's
286  * multiple Listen statements.  Define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
287  * when it's safe in the single Listen case.
288  */
289 #ifdef SINGLE_LISTEN_UNSERIALIZED_ACCEPT
290 #define SAFE_ACCEPT(stmt) (ap_listeners->next ? (stmt) : APR_SUCCESS)
291 #else
292 #define SAFE_ACCEPT(stmt) (stmt)
293 #endif
294
295 static int prefork_query(int query_code, int *result, apr_status_t *rv)
296 {
297     *rv = APR_SUCCESS;
298     switch(query_code){
299     case AP_MPMQ_MAX_DAEMON_USED:
300         *result = ap_daemons_limit;
301         break;
302     case AP_MPMQ_IS_THREADED:
303         *result = AP_MPMQ_NOT_SUPPORTED;
304         break;
305     case AP_MPMQ_IS_FORKED:
306         *result = AP_MPMQ_DYNAMIC;
307         break;
308     case AP_MPMQ_HARD_LIMIT_DAEMONS:
309         *result = server_limit;
310         break;
311     case AP_MPMQ_HARD_LIMIT_THREADS:
312         *result = HARD_THREAD_LIMIT;
313         break;
314     case AP_MPMQ_MAX_THREADS:
315         *result = 1;
316         break;
317     case AP_MPMQ_MIN_SPARE_DAEMONS:
318         *result = ap_daemons_min_free;
319         break;
320     case AP_MPMQ_MIN_SPARE_THREADS:
321         *result = 0;
322         break;
323     case AP_MPMQ_MAX_SPARE_DAEMONS:
324         *result = ap_daemons_max_free;
325         break;
326     case AP_MPMQ_MAX_SPARE_THREADS:
327         *result = 0;
328         break;
329     case AP_MPMQ_MAX_REQUESTS_DAEMON:
330         *result = ap_max_requests_per_child;
331         break;
332     case AP_MPMQ_MAX_DAEMONS:
333         *result = ap_daemons_limit;
334         break;
335     case AP_MPMQ_MPM_STATE:
336         *result = mpm_state;
337         break;
338     case AP_MPMQ_GENERATION:
339         *result = retained->my_generation;
340         break;
341     default:
342         *rv = APR_ENOTIMPL;
343         break;
344     }
345     return OK;
346 }
347
348 static const char *prefork_get_name(void)
349 {
350     return "prefork";
351 }
352
353 /*****************************************************************
354  * Connection structures and accounting...
355  */
356
357 static void just_die(int sig)
358 {
359     clean_child_exit(0);
360 }
361
362 /* volatile because they're updated from a signal handler */
363 static int volatile shutdown_pending;
364 static int volatile restart_pending;
365 static int volatile die_now = 0;
366
367 static void stop_listening(int sig)
368 {
369     mpm_state = AP_MPMQ_STOPPING;
370     ap_close_listeners_ex(my_bucket->listeners);
371
372     /* For a graceful stop, we want the child to exit when done */
373     die_now = 1;
374 }
375
376 static void sig_term(int sig)
377 {
378     if (shutdown_pending == 1) {
379         /* Um, is this _probably_ not an error, if the user has
380          * tried to do a shutdown twice quickly, so we won't
381          * worry about reporting it.
382          */
383         return;
384     }
385     mpm_state = AP_MPMQ_STOPPING;
386     shutdown_pending = 1;
387     retained->is_graceful = (sig == AP_SIG_GRACEFUL_STOP);
388 }
389
390 /* restart() is the signal handler for SIGHUP and AP_SIG_GRACEFUL
391  * in the parent process, unless running in ONE_PROCESS mode
392  */
393 static void restart(int sig)
394 {
395     if (restart_pending == 1) {
396         /* Probably not an error - don't bother reporting it */
397         return;
398     }
399     mpm_state = AP_MPMQ_STOPPING;
400     restart_pending = 1;
401     retained->is_graceful = (sig == AP_SIG_GRACEFUL);
402 }
403
404 static void set_signals(void)
405 {
406 #ifndef NO_USE_SIGACTION
407     struct sigaction sa;
408 #endif
409
410     if (!one_process) {
411         ap_fatal_signal_setup(ap_server_conf, pconf);
412     }
413
414 #ifndef NO_USE_SIGACTION
415     sigemptyset(&sa.sa_mask);
416     sa.sa_flags = 0;
417
418     sa.sa_handler = sig_term;
419     if (sigaction(SIGTERM, &sa, NULL) < 0)
420         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(00147) "sigaction(SIGTERM)");
421 #ifdef AP_SIG_GRACEFUL_STOP
422     if (sigaction(AP_SIG_GRACEFUL_STOP, &sa, NULL) < 0)
423         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(00148)
424                      "sigaction(" AP_SIG_GRACEFUL_STOP_STRING ")");
425 #endif
426 #ifdef SIGINT
427     if (sigaction(SIGINT, &sa, NULL) < 0)
428         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(00149) "sigaction(SIGINT)");
429 #endif
430 #ifdef SIGXCPU
431     sa.sa_handler = SIG_DFL;
432     if (sigaction(SIGXCPU, &sa, NULL) < 0)
433         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(00150) "sigaction(SIGXCPU)");
434 #endif
435 #ifdef SIGXFSZ
436     /* For systems following the LFS standard, ignoring SIGXFSZ allows
437      * a write() beyond the 2GB limit to fail gracefully with E2BIG
438      * rather than terminate the process. */
439     sa.sa_handler = SIG_IGN;
440     if (sigaction(SIGXFSZ, &sa, NULL) < 0)
441         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(00151) "sigaction(SIGXFSZ)");
442 #endif
443 #ifdef SIGPIPE
444     sa.sa_handler = SIG_IGN;
445     if (sigaction(SIGPIPE, &sa, NULL) < 0)
446         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(00152) "sigaction(SIGPIPE)");
447 #endif
448
449     /* we want to ignore HUPs and AP_SIG_GRACEFUL while we're busy
450      * processing one
451      */
452     sigaddset(&sa.sa_mask, SIGHUP);
453     sigaddset(&sa.sa_mask, AP_SIG_GRACEFUL);
454     sa.sa_handler = restart;
455     if (sigaction(SIGHUP, &sa, NULL) < 0)
456         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(00153) "sigaction(SIGHUP)");
457     if (sigaction(AP_SIG_GRACEFUL, &sa, NULL) < 0)
458         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(00154) "sigaction(" AP_SIG_GRACEFUL_STRING ")");
459 #else
460     if (!one_process) {
461 #ifdef SIGXCPU
462         apr_signal(SIGXCPU, SIG_DFL);
463 #endif /* SIGXCPU */
464 #ifdef SIGXFSZ
465         apr_signal(SIGXFSZ, SIG_IGN);
466 #endif /* SIGXFSZ */
467     }
468
469     apr_signal(SIGTERM, sig_term);
470 #ifdef SIGHUP
471     apr_signal(SIGHUP, restart);
472 #endif /* SIGHUP */
473 #ifdef AP_SIG_GRACEFUL
474     apr_signal(AP_SIG_GRACEFUL, restart);
475 #endif /* AP_SIG_GRACEFUL */
476 #ifdef AP_SIG_GRACEFUL_STOP
477     apr_signal(AP_SIG_GRACEFUL_STOP, sig_term);
478 #endif /* AP_SIG_GRACEFUL */
479 #ifdef SIGPIPE
480     apr_signal(SIGPIPE, SIG_IGN);
481 #endif /* SIGPIPE */
482
483 #endif
484 }
485
486 /*****************************************************************
487  * Child process main loop.
488  * The following vars are static to avoid getting clobbered by longjmp();
489  * they are really private to child_main.
490  */
491
492 static int requests_this_child;
493 static int num_listensocks = 0;
494
495 static void child_main(int child_num_arg, int child_bucket)
496 {
497 #if APR_HAS_THREADS
498     apr_thread_t *thd = NULL;
499     apr_os_thread_t osthd;
500 #endif
501     apr_pool_t *ptrans;
502     apr_allocator_t *allocator;
503     apr_status_t status;
504     int i;
505     ap_listen_rec *lr;
506     apr_pollset_t *pollset;
507     ap_sb_handle_t *sbh;
508     apr_bucket_alloc_t *bucket_alloc;
509     int last_poll_idx = 0;
510     const char *lockfile;
511
512     mpm_state = AP_MPMQ_STARTING; /* for benefit of any hooks that run as this
513                                    * child initializes
514                                    */
515
516     my_child_num = child_num_arg;
517     ap_my_pid = getpid();
518     requests_this_child = 0;
519
520     ap_fatal_signal_child_setup(ap_server_conf);
521
522     /* Get a sub context for global allocations in this child, so that
523      * we can have cleanups occur when the child exits.
524      */
525     apr_allocator_create(&allocator);
526     apr_allocator_max_free_set(allocator, ap_max_mem_free);
527     apr_pool_create_ex(&pchild, pconf, NULL, allocator);
528     apr_allocator_owner_set(allocator, pchild);
529     apr_pool_tag(pchild, "pchild");
530
531 #if APR_HAS_THREADS
532     osthd = apr_os_thread_current();
533     apr_os_thread_put(&thd, &osthd, pchild);
534 #endif
535
536     apr_pool_create(&ptrans, pchild);
537     apr_pool_tag(ptrans, "transaction");
538
539     /* close unused listeners and pods */
540     for (i = 0; i < num_buckets; i++) {
541         if (i != child_bucket) {
542             ap_close_listeners_ex(all_buckets[i].listeners);
543             ap_mpm_pod_close(all_buckets[i].pod);
544         }
545     }
546
547     /* needs to be done before we switch UIDs so we have permissions */
548     ap_reopen_scoreboard(pchild, NULL, 0);
549     status = SAFE_ACCEPT(apr_proc_mutex_child_init(&my_bucket->mutex,
550                                     apr_proc_mutex_lockfile(my_bucket->mutex),
551                                     pchild));
552     if (status != APR_SUCCESS) {
553         lockfile = apr_proc_mutex_lockfile(my_bucket->mutex);
554         ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf, APLOGNO(00155)
555                      "Couldn't initialize cross-process lock in child "
556                      "(%s) (%s)",
557                      lockfile ? lockfile : "none",
558                      apr_proc_mutex_name(my_bucket->mutex));
559         clean_child_exit(APEXIT_CHILDFATAL);
560     }
561
562     if (ap_run_drop_privileges(pchild, ap_server_conf)) {
563         clean_child_exit(APEXIT_CHILDFATAL);
564     }
565
566     ap_run_child_init(pchild, ap_server_conf);
567
568     ap_create_sb_handle(&sbh, pchild, my_child_num, 0);
569
570     (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
571
572     /* Set up the pollfd array */
573     status = apr_pollset_create(&pollset, num_listensocks, pchild,
574                                 APR_POLLSET_NOCOPY);
575     if (status != APR_SUCCESS) {
576         ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf, APLOGNO(00156)
577                      "Couldn't create pollset in child; check system or user limits");
578         clean_child_exit(APEXIT_CHILDSICK); /* assume temporary resource issue */
579     }
580
581     for (lr = my_bucket->listeners, i = num_listensocks; i--; lr = lr->next) {
582         apr_pollfd_t *pfd = apr_pcalloc(pchild, sizeof *pfd);
583
584         pfd->desc_type = APR_POLL_SOCKET;
585         pfd->desc.s = lr->sd;
586         pfd->reqevents = APR_POLLIN;
587         pfd->client_data = lr;
588
589         status = apr_pollset_add(pollset, pfd);
590         if (status != APR_SUCCESS) {
591             /* If the child processed a SIGWINCH before setting up the
592              * pollset, this error path is expected and harmless,
593              * since the listener fd was already closed; so don't
594              * pollute the logs in that case. */
595             if (!die_now) {
596                 ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf, APLOGNO(00157)
597                              "Couldn't add listener to pollset; check system or user limits");
598                 clean_child_exit(APEXIT_CHILDSICK);
599             }
600             clean_child_exit(0);
601         }
602
603         lr->accept_func = ap_unixd_accept;
604     }
605
606     mpm_state = AP_MPMQ_RUNNING;
607
608     bucket_alloc = apr_bucket_alloc_create(pchild);
609
610     /* die_now is set when AP_SIG_GRACEFUL is received in the child;
611      * shutdown_pending is set when SIGTERM is received when running
612      * in single process mode.  */
613     while (!die_now && !shutdown_pending) {
614         conn_rec *current_conn;
615         void *csd;
616
617         /*
618          * (Re)initialize this child to a pre-connection state.
619          */
620
621         apr_pool_clear(ptrans);
622
623         if ((ap_max_requests_per_child > 0
624              && requests_this_child++ >= ap_max_requests_per_child)) {
625             clean_child_exit(0);
626         }
627
628         (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
629
630         /*
631          * Wait for an acceptable connection to arrive.
632          */
633
634         /* Lock around "accept", if necessary */
635         SAFE_ACCEPT(accept_mutex_on());
636
637         if (num_listensocks == 1) {
638             /* There is only one listener record, so refer to that one. */
639             lr = my_bucket->listeners;
640         }
641         else {
642             /* multiple listening sockets - need to poll */
643             for (;;) {
644                 apr_int32_t numdesc;
645                 const apr_pollfd_t *pdesc;
646
647                 /* check for termination first so we don't sleep for a while in
648                  * poll if already signalled
649                  */
650                 if (die_now         /* in graceful stop/restart */
651                     || (one_process && shutdown_pending)) {
652                     SAFE_ACCEPT(accept_mutex_off());
653                     clean_child_exit(0);
654                 }
655
656                 /* timeout == 10 seconds to avoid a hang at graceful restart/stop
657                  * caused by the closing of sockets by the signal handler
658                  */
659                 status = apr_pollset_poll(pollset, apr_time_from_sec(10),
660                                           &numdesc, &pdesc);
661                 if (status != APR_SUCCESS) {
662                     if (APR_STATUS_IS_TIMEUP(status) ||
663                         APR_STATUS_IS_EINTR(status)) {
664                         continue;
665                     }
666                     /* Single Unix documents select as returning errnos
667                      * EBADF, EINTR, and EINVAL... and in none of those
668                      * cases does it make sense to continue.  In fact
669                      * on Linux 2.0.x we seem to end up with EFAULT
670                      * occasionally, and we'd loop forever due to it.
671                      */
672                     ap_log_error(APLOG_MARK, APLOG_ERR, status,
673                                  ap_server_conf, APLOGNO(00158) "apr_pollset_poll: (listen)");
674                     SAFE_ACCEPT(accept_mutex_off());
675                     clean_child_exit(APEXIT_CHILDSICK);
676                 }
677
678                 /* We can always use pdesc[0], but sockets at position N
679                  * could end up completely starved of attention in a very
680                  * busy server. Therefore, we round-robin across the
681                  * returned set of descriptors. While it is possible that
682                  * the returned set of descriptors might flip around and
683                  * continue to starve some sockets, we happen to know the
684                  * internal pollset implementation retains ordering
685                  * stability of the sockets. Thus, the round-robin should
686                  * ensure that a socket will eventually be serviced.
687                  */
688                 if (last_poll_idx >= numdesc)
689                     last_poll_idx = 0;
690
691                 /* Grab a listener record from the client_data of the poll
692                  * descriptor, and advance our saved index to round-robin
693                  * the next fetch.
694                  *
695                  * ### hmm... this descriptor might have POLLERR rather
696                  * ### than POLLIN
697                  */
698                 lr = pdesc[last_poll_idx++].client_data;
699                 goto got_fd;
700             }
701         }
702     got_fd:
703         /* if we accept() something we don't want to die, so we have to
704          * defer the exit
705          */
706         status = lr->accept_func(&csd, lr, ptrans);
707
708         SAFE_ACCEPT(accept_mutex_off());      /* unlock after "accept" */
709
710         if (status == APR_EGENERAL) {
711             /* resource shortage or should-not-occur occured */
712             clean_child_exit(APEXIT_CHILDSICK);
713         }
714         else if (status != APR_SUCCESS) {
715             continue;
716         }
717
718         /*
719          * We now have a connection, so set it up with the appropriate
720          * socket options, file descriptors, and read/write buffers.
721          */
722
723         current_conn = ap_run_create_connection(ptrans, ap_server_conf, csd, my_child_num, sbh, bucket_alloc);
724         if (current_conn) {
725 #if APR_HAS_THREADS
726             current_conn->current_thread = thd;
727 #endif
728             ap_process_connection(current_conn, csd);
729             ap_lingering_close(current_conn);
730         }
731
732         /* Check the pod and the generation number after processing a
733          * connection so that we'll go away if a graceful restart occurred
734          * while we were processing the connection or we are the lucky
735          * idle server process that gets to die.
736          */
737         if (ap_mpm_pod_check(my_bucket->pod) == APR_SUCCESS) { /* selected as idle? */
738             die_now = 1;
739         }
740         else if (retained->my_generation !=
741                  ap_scoreboard_image->global->running_generation) { /* restart? */
742             /* yeah, this could be non-graceful restart, in which case the
743              * parent will kill us soon enough, but why bother checking?
744              */
745             die_now = 1;
746         }
747     }
748     apr_pool_clear(ptrans); /* kludge to avoid crash in APR reslist cleanup code */
749     clean_child_exit(0);
750 }
751
752
753 static int make_child(server_rec *s, int slot, int bucket)
754 {
755     int pid;
756
757     if (slot + 1 > retained->max_daemons_limit) {
758         retained->max_daemons_limit = slot + 1;
759     }
760
761     if (one_process) {
762         my_bucket = &all_buckets[0];
763
764         apr_signal(SIGHUP, sig_term);
765         /* Don't catch AP_SIG_GRACEFUL in ONE_PROCESS mode :) */
766         apr_signal(SIGINT, sig_term);
767 #ifdef SIGQUIT
768         apr_signal(SIGQUIT, SIG_DFL);
769 #endif
770         apr_signal(SIGTERM, sig_term);
771         prefork_note_child_started(slot, getpid());
772         child_main(slot, 0);
773         /* NOTREACHED */
774         ap_assert(0);
775         return -1;
776     }
777
778     (void) ap_update_child_status_from_indexes(slot, 0, SERVER_STARTING,
779                                                (request_rec *) NULL);
780
781 #ifdef _OSD_POSIX
782     /* BS2000 requires a "special" version of fork() before a setuid() call */
783     if ((pid = os_fork(ap_unixd_config.user_name)) == -1) {
784 #else
785     if ((pid = fork()) == -1) {
786 #endif
787         ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, APLOGNO(00159) "fork: Unable to fork new process");
788
789         /* fork didn't succeed. Fix the scoreboard or else
790          * it will say SERVER_STARTING forever and ever
791          */
792         (void) ap_update_child_status_from_indexes(slot, 0, SERVER_DEAD,
793                                                    (request_rec *) NULL);
794
795         /* In case system resources are maxxed out, we don't want
796          * Apache running away with the CPU trying to fork over and
797          * over and over again.
798          */
799         sleep(10);
800
801         return -1;
802     }
803
804     if (!pid) {
805         my_bucket = &all_buckets[bucket];
806
807 #ifdef HAVE_BINDPROCESSOR
808         /* by default AIX binds to a single processor
809          * this bit unbinds children which will then bind to another cpu
810          */
811         int status = bindprocessor(BINDPROCESS, (int)getpid(),
812                                    PROCESSOR_CLASS_ANY);
813         if (status != OK) {
814             ap_log_error(APLOG_MARK, APLOG_DEBUG, errno,
815                          ap_server_conf, APLOGNO(00160) "processor unbind failed");
816         }
817 #endif
818         RAISE_SIGSTOP(MAKE_CHILD);
819         AP_MONCONTROL(1);
820         /* Disable the parent's signal handlers and set up proper handling in
821          * the child.
822          */
823         apr_signal(SIGHUP, just_die);
824         apr_signal(SIGTERM, just_die);
825         /* Ignore SIGINT in child. This fixes race-condition in signals
826          * handling when httpd is runnning on foreground and user hits ctrl+c.
827          * In this case, SIGINT is sent to all children followed by SIGTERM
828          * from the main process, which interrupts the SIGINT handler and
829          * leads to inconsistency.
830          */
831         apr_signal(SIGINT, SIG_IGN);
832         /* The child process just closes listeners on AP_SIG_GRACEFUL.
833          * The pod is used for signalling the graceful restart.
834          */
835         apr_signal(AP_SIG_GRACEFUL, stop_listening);
836         child_main(slot, bucket);
837     }
838
839     ap_scoreboard_image->parent[slot].bucket = bucket;
840     prefork_note_child_started(slot, pid);
841
842     return 0;
843 }
844
845
846 /* start up a bunch of children */
847 static void startup_children(int number_to_start)
848 {
849     int i;
850
851     for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
852         if (ap_scoreboard_image->servers[i][0].status != SERVER_DEAD) {
853             continue;
854         }
855         if (make_child(ap_server_conf, i, i % num_buckets) < 0) {
856             break;
857         }
858         --number_to_start;
859     }
860 }
861
862 static void perform_idle_server_maintenance(apr_pool_t *p)
863 {
864     static int bucket_make_child_record = -1;
865     static int bucket_kill_child_record = -1;
866     int i;
867     int idle_count;
868     worker_score *ws;
869     int free_length;
870     int free_slots[MAX_SPAWN_RATE];
871     int last_non_dead;
872     int total_non_dead;
873
874     /* initialize the free_list */
875     free_length = 0;
876
877     idle_count = 0;
878     last_non_dead = -1;
879     total_non_dead = 0;
880
881     for (i = 0; i < ap_daemons_limit; ++i) {
882         int status;
883
884         if (i >= retained->max_daemons_limit && free_length == retained->idle_spawn_rate)
885             break;
886         ws = &ap_scoreboard_image->servers[i][0];
887         status = ws->status;
888         if (status == SERVER_DEAD) {
889             /* try to keep children numbers as low as possible */
890             if (free_length < retained->idle_spawn_rate) {
891                 free_slots[free_length] = i;
892                 ++free_length;
893             }
894         }
895         else {
896             /* We consider a starting server as idle because we started it
897              * at least a cycle ago, and if it still hasn't finished starting
898              * then we're just going to swamp things worse by forking more.
899              * So we hopefully won't need to fork more if we count it.
900              * This depends on the ordering of SERVER_READY and SERVER_STARTING.
901              */
902             if (status <= SERVER_READY) {
903                 ++ idle_count;
904             }
905
906             ++total_non_dead;
907             last_non_dead = i;
908         }
909     }
910     retained->max_daemons_limit = last_non_dead + 1;
911     if (idle_count > ap_daemons_max_free) {
912         /* kill off one child... we use the pod because that'll cause it to
913          * shut down gracefully, in case it happened to pick up a request
914          * while we were counting
915          */
916         bucket_kill_child_record = (bucket_kill_child_record + 1) % num_buckets;
917         ap_mpm_pod_signal(all_buckets[bucket_kill_child_record].pod);
918         retained->idle_spawn_rate = 1;
919     }
920     else if (idle_count < ap_daemons_min_free) {
921         /* terminate the free list */
922         if (free_length == 0) {
923             /* only report this condition once */
924             if (!retained->maxclients_reported) {
925                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(00161)
926                             "server reached MaxRequestWorkers setting, consider"
927                             " raising the MaxRequestWorkers setting");
928                 retained->maxclients_reported = 1;
929             }
930             retained->idle_spawn_rate = 1;
931         }
932         else {
933             if (retained->idle_spawn_rate >= 8) {
934                 ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, APLOGNO(00162)
935                     "server seems busy, (you may need "
936                     "to increase StartServers, or Min/MaxSpareServers), "
937                     "spawning %d children, there are %d idle, and "
938                     "%d total children", retained->idle_spawn_rate,
939                     idle_count, total_non_dead);
940             }
941             for (i = 0; i < free_length; ++i) {
942                 bucket_make_child_record++;
943                 bucket_make_child_record %= num_buckets;
944                 make_child(ap_server_conf, free_slots[i],
945                            bucket_make_child_record);
946             }
947             /* the next time around we want to spawn twice as many if this
948              * wasn't good enough, but not if we've just done a graceful
949              */
950             if (retained->hold_off_on_exponential_spawning) {
951                 --retained->hold_off_on_exponential_spawning;
952             }
953             else if (retained->idle_spawn_rate < MAX_SPAWN_RATE) {
954                 retained->idle_spawn_rate *= 2;
955             }
956         }
957     }
958     else {
959         retained->idle_spawn_rate = 1;
960     }
961 }
962
963 /*****************************************************************
964  * Executive routines.
965  */
966
967 static int prefork_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
968 {
969     int index;
970     int remaining_children_to_start;
971     int i;
972
973     ap_log_pid(pconf, ap_pid_fname);
974
975     if (!retained->is_graceful) {
976         if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
977             mpm_state = AP_MPMQ_STOPPING;
978             return !OK;
979         }
980         /* fix the generation number in the global score; we just got a new,
981          * cleared scoreboard
982          */
983         ap_scoreboard_image->global->running_generation = retained->my_generation;
984     }
985
986     restart_pending = shutdown_pending = 0;
987     set_signals();
988
989     if (one_process) {
990         AP_MONCONTROL(1);
991         make_child(ap_server_conf, 0, 0);
992         /* NOTREACHED */
993         ap_assert(0);
994         return !OK;
995     }
996
997     /* Don't thrash since num_buckets depends on the
998      * system and the number of online CPU cores...
999      */
1000     if (ap_daemons_limit < num_buckets)
1001         ap_daemons_limit = num_buckets;
1002     if (ap_daemons_to_start < num_buckets)
1003         ap_daemons_to_start = num_buckets;
1004     if (ap_daemons_min_free < num_buckets)
1005         ap_daemons_min_free = num_buckets;
1006     if (ap_daemons_max_free < ap_daemons_min_free + num_buckets)
1007         ap_daemons_max_free = ap_daemons_min_free + num_buckets;
1008
1009     /* If we're doing a graceful_restart then we're going to see a lot
1010      * of children exiting immediately when we get into the main loop
1011      * below (because we just sent them AP_SIG_GRACEFUL).  This happens pretty
1012      * rapidly... and for each one that exits we'll start a new one until
1013      * we reach at least daemons_min_free.  But we may be permitted to
1014      * start more than that, so we'll just keep track of how many we're
1015      * supposed to start up without the 1 second penalty between each fork.
1016      */
1017     remaining_children_to_start = ap_daemons_to_start;
1018     if (remaining_children_to_start > ap_daemons_limit) {
1019         remaining_children_to_start = ap_daemons_limit;
1020     }
1021     if (!retained->is_graceful) {
1022         startup_children(remaining_children_to_start);
1023         remaining_children_to_start = 0;
1024     }
1025     else {
1026         /* give the system some time to recover before kicking into
1027          * exponential mode
1028          */
1029         retained->hold_off_on_exponential_spawning = 10;
1030     }
1031
1032     ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00163)
1033                 "%s configured -- resuming normal operations",
1034                 ap_get_server_description());
1035     ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, APLOGNO(00164)
1036                 "Server built: %s", ap_get_server_built());
1037     ap_log_command_line(plog, s);
1038     ap_log_mpm_common(s);
1039     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(00165)
1040                 "Accept mutex: %s (default: %s)",
1041                 (all_buckets[0].mutex)
1042                     ? apr_proc_mutex_name(all_buckets[0].mutex)
1043                     : "none",
1044                 apr_proc_mutex_defname());
1045
1046     mpm_state = AP_MPMQ_RUNNING;
1047
1048     while (!restart_pending && !shutdown_pending) {
1049         int child_slot;
1050         apr_exit_why_e exitwhy;
1051         int status, processed_status;
1052         /* this is a memory leak, but I'll fix it later. */
1053         apr_proc_t pid;
1054
1055         ap_wait_or_timeout(&exitwhy, &status, &pid, pconf, ap_server_conf);
1056
1057         /* XXX: if it takes longer than 1 second for all our children
1058          * to start up and get into IDLE state then we may spawn an
1059          * extra child
1060          */
1061         if (pid.pid != -1) {
1062             processed_status = ap_process_child_status(&pid, exitwhy, status);
1063             child_slot = ap_find_child_by_pid(&pid);
1064             if (processed_status == APEXIT_CHILDFATAL) {
1065                 /* fix race condition found in PR 39311
1066                  * A child created at the same time as a graceful happens 
1067                  * can find the lock missing and create a fatal error.
1068                  * It is not fatal for the last generation to be in this state.
1069                  */
1070                 if (child_slot < 0
1071                     || ap_get_scoreboard_process(child_slot)->generation
1072                        == retained->my_generation) {
1073                     mpm_state = AP_MPMQ_STOPPING;
1074                     return !OK;
1075                 }
1076                 else {
1077                     ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, APLOGNO(00166)
1078                                  "Ignoring fatal error in child of previous "
1079                                  "generation (pid %ld).",
1080                                  (long)pid.pid);
1081                 }
1082             }
1083
1084             /* non-fatal death... note that it's gone in the scoreboard. */
1085             if (child_slot >= 0) {
1086                 (void) ap_update_child_status_from_indexes(child_slot, 0, SERVER_DEAD,
1087                                                            (request_rec *) NULL);
1088                 prefork_note_child_killed(child_slot, 0, 0);
1089                 if (processed_status == APEXIT_CHILDSICK) {
1090                     /* child detected a resource shortage (E[NM]FILE, ENOBUFS, etc)
1091                      * cut the fork rate to the minimum
1092                      */
1093                     retained->idle_spawn_rate = 1;
1094                 }
1095                 else if (remaining_children_to_start
1096                     && child_slot < ap_daemons_limit) {
1097                     /* we're still doing a 1-for-1 replacement of dead
1098                      * children with new children
1099                      */
1100                     make_child(ap_server_conf, child_slot,
1101                                ap_get_scoreboard_process(child_slot)->bucket);
1102                     --remaining_children_to_start;
1103                 }
1104 #if APR_HAS_OTHER_CHILD
1105             }
1106             else if (apr_proc_other_child_alert(&pid, APR_OC_REASON_DEATH, status) == APR_SUCCESS) {
1107                 /* handled */
1108 #endif
1109             }
1110             else if (retained->is_graceful) {
1111                 /* Great, we've probably just lost a slot in the
1112                  * scoreboard.  Somehow we don't know about this
1113                  * child.
1114                  */
1115                 ap_log_error(APLOG_MARK, APLOG_WARNING,
1116                             0, ap_server_conf, APLOGNO(00167)
1117                             "long lost child came home! (pid %ld)", (long)pid.pid);
1118             }
1119             /* Don't perform idle maintenance when a child dies,
1120              * only do it when there's a timeout.  Remember only a
1121              * finite number of children can die, and it's pretty
1122              * pathological for a lot to die suddenly.
1123              */
1124             continue;
1125         }
1126         else if (remaining_children_to_start) {
1127             /* we hit a 1 second timeout in which none of the previous
1128              * generation of children needed to be reaped... so assume
1129              * they're all done, and pick up the slack if any is left.
1130              */
1131             startup_children(remaining_children_to_start);
1132             remaining_children_to_start = 0;
1133             /* In any event we really shouldn't do the code below because
1134              * few of the servers we just started are in the IDLE state
1135              * yet, so we'd mistakenly create an extra server.
1136              */
1137             continue;
1138         }
1139
1140         perform_idle_server_maintenance(pconf);
1141     }
1142
1143     mpm_state = AP_MPMQ_STOPPING;
1144
1145     if (shutdown_pending && !retained->is_graceful) {
1146         /* Time to shut down:
1147          * Kill child processes, tell them to call child_exit, etc...
1148          */
1149         if (ap_unixd_killpg(getpgrp(), SIGTERM) < 0) {
1150             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(00168) "killpg SIGTERM");
1151         }
1152         ap_reclaim_child_processes(1, /* Start with SIGTERM */
1153                                    prefork_note_child_killed);
1154
1155         /* cleanup pid file on normal shutdown */
1156         ap_remove_pid(pconf, ap_pid_fname);
1157         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00169)
1158                     "caught SIGTERM, shutting down");
1159
1160         return DONE;
1161     } else if (shutdown_pending) {
1162         /* Time to perform a graceful shut down:
1163          * Reap the inactive children, and ask the active ones
1164          * to close their listeners, then wait until they are
1165          * all done to exit.
1166          */
1167         int active_children;
1168         apr_time_t cutoff = 0;
1169
1170         /* Stop listening */
1171         ap_close_listeners();
1172
1173         /* kill off the idle ones */
1174         for (i = 0; i < num_buckets; i++) {
1175             ap_mpm_pod_killpg(all_buckets[i].pod, retained->max_daemons_limit);
1176         }
1177
1178         /* Send SIGUSR1 to the active children */
1179         active_children = 0;
1180         for (index = 0; index < ap_daemons_limit; ++index) {
1181             if (ap_scoreboard_image->servers[index][0].status != SERVER_DEAD) {
1182                 /* Ask each child to close its listeners. */
1183                 ap_mpm_safe_kill(MPM_CHILD_PID(index), AP_SIG_GRACEFUL);
1184                 active_children++;
1185             }
1186         }
1187
1188         /* Allow each child which actually finished to exit */
1189         ap_relieve_child_processes(prefork_note_child_killed);
1190
1191         /* cleanup pid file */
1192         ap_remove_pid(pconf, ap_pid_fname);
1193         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00170)
1194            "caught " AP_SIG_GRACEFUL_STOP_STRING ", shutting down gracefully");
1195
1196         if (ap_graceful_shutdown_timeout) {
1197             cutoff = apr_time_now() +
1198                      apr_time_from_sec(ap_graceful_shutdown_timeout);
1199         }
1200
1201         /* Don't really exit until each child has finished */
1202         shutdown_pending = 0;
1203         do {
1204             /* Pause for a second */
1205             sleep(1);
1206
1207             /* Relieve any children which have now exited */
1208             ap_relieve_child_processes(prefork_note_child_killed);
1209
1210             active_children = 0;
1211             for (index = 0; index < ap_daemons_limit; ++index) {
1212                 if (ap_mpm_safe_kill(MPM_CHILD_PID(index), 0) == APR_SUCCESS) {
1213                     active_children = 1;
1214                     /* Having just one child is enough to stay around */
1215                     break;
1216                 }
1217             }
1218         } while (!shutdown_pending && active_children &&
1219                  (!ap_graceful_shutdown_timeout || apr_time_now() < cutoff));
1220
1221         /* We might be here because we received SIGTERM, either
1222          * way, try and make sure that all of our processes are
1223          * really dead.
1224          */
1225         ap_unixd_killpg(getpgrp(), SIGTERM);
1226
1227         return DONE;
1228     }
1229
1230     /* we've been told to restart */
1231     apr_signal(SIGHUP, SIG_IGN);
1232     apr_signal(AP_SIG_GRACEFUL, SIG_IGN);
1233     if (one_process) {
1234         /* not worth thinking about */
1235         return DONE;
1236     }
1237
1238     /* advance to the next generation */
1239     /* XXX: we really need to make sure this new generation number isn't in
1240      * use by any of the children.
1241      */
1242     ++retained->my_generation;
1243     ap_scoreboard_image->global->running_generation = retained->my_generation;
1244
1245     if (retained->is_graceful) {
1246         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00171)
1247                     "Graceful restart requested, doing restart");
1248
1249         /* kill off the idle ones */
1250         for (i = 0; i < num_buckets; i++) {
1251             ap_mpm_pod_killpg(all_buckets[i].pod, retained->max_daemons_limit);
1252         }
1253
1254         /* This is mostly for debugging... so that we know what is still
1255          * gracefully dealing with existing request.  This will break
1256          * in a very nasty way if we ever have the scoreboard totally
1257          * file-based (no shared memory)
1258          */
1259         for (index = 0; index < ap_daemons_limit; ++index) {
1260             if (ap_scoreboard_image->servers[index][0].status != SERVER_DEAD) {
1261                 ap_scoreboard_image->servers[index][0].status = SERVER_GRACEFUL;
1262                 /* Ask each child to close its listeners.
1263                  *
1264                  * NOTE: we use the scoreboard, because if we send SIGUSR1
1265                  * to every process in the group, this may include CGI's,
1266                  * piped loggers, etc. They almost certainly won't handle
1267                  * it gracefully.
1268                  */
1269                 ap_mpm_safe_kill(ap_scoreboard_image->parent[index].pid, AP_SIG_GRACEFUL);
1270             }
1271         }
1272     }
1273     else {
1274         /* Kill 'em off */
1275         if (ap_unixd_killpg(getpgrp(), SIGHUP) < 0) {
1276             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(00172) "killpg SIGHUP");
1277         }
1278         ap_reclaim_child_processes(0, /* Not when just starting up */
1279                                    prefork_note_child_killed);
1280         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00173)
1281                     "SIGHUP received.  Attempting to restart");
1282     }
1283
1284     return OK;
1285 }
1286
1287 /* This really should be a post_config hook, but the error log is already
1288  * redirected by that point, so we need to do this in the open_logs phase.
1289  */
1290 static int prefork_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
1291 {
1292     int startup = 0;
1293     int level_flags = 0;
1294     ap_listen_rec **listen_buckets;
1295     apr_status_t rv;
1296     char id[16];
1297     int i;
1298
1299     pconf = p;
1300
1301     /* the reverse of pre_config, we want this only the first time around */
1302     if (retained->module_loads == 1) {
1303         startup = 1;
1304         level_flags |= APLOG_STARTUP;
1305     }
1306
1307     if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
1308         ap_log_error(APLOG_MARK, APLOG_ALERT | level_flags, 0,
1309                      (startup ? NULL : s),
1310                      "no listening sockets available, shutting down");
1311         return DONE;
1312     }
1313
1314     if (one_process) {
1315         num_buckets = 1;
1316     }
1317     else if (!retained->is_graceful) { /* Preserve the number of buckets
1318                                           on graceful restarts. */
1319         num_buckets = 0;
1320     }
1321     if ((rv = ap_duplicate_listeners(pconf, ap_server_conf,
1322                                      &listen_buckets, &num_buckets))) {
1323         ap_log_error(APLOG_MARK, APLOG_CRIT | level_flags, rv,
1324                      (startup ? NULL : s),
1325                      "could not duplicate listeners");
1326         return DONE;
1327     }
1328     all_buckets = apr_pcalloc(pconf, num_buckets *
1329                                      sizeof(prefork_child_bucket));
1330     for (i = 0; i < num_buckets; i++) {
1331         if ((rv = ap_mpm_pod_open(pconf, &all_buckets[i].pod))) {
1332             ap_log_error(APLOG_MARK, APLOG_CRIT | level_flags, rv,
1333                          (startup ? NULL : s),
1334                          "could not open pipe-of-death");
1335             return DONE;
1336         }
1337         /* Initialize cross-process accept lock (safe accept needed only) */
1338         if ((rv = SAFE_ACCEPT((apr_snprintf(id, sizeof id, "%i", i),
1339                                ap_proc_mutex_create(&all_buckets[i].mutex,
1340                                                     NULL, AP_ACCEPT_MUTEX_TYPE,
1341                                                     id, s, pconf, 0))))) {
1342             ap_log_error(APLOG_MARK, APLOG_CRIT | level_flags, rv,
1343                          (startup ? NULL : s),
1344                          "could not create accept mutex");
1345             return DONE;
1346         }
1347         all_buckets[i].listeners = listen_buckets[i];
1348     }
1349
1350     return OK;
1351 }
1352
1353 static int prefork_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp)
1354 {
1355     int no_detach, debug, foreground;
1356     apr_status_t rv;
1357     const char *userdata_key = "mpm_prefork_module";
1358
1359     mpm_state = AP_MPMQ_STARTING;
1360
1361     debug = ap_exists_config_define("DEBUG");
1362
1363     if (debug) {
1364         foreground = one_process = 1;
1365         no_detach = 0;
1366     }
1367     else
1368     {
1369         no_detach = ap_exists_config_define("NO_DETACH");
1370         one_process = ap_exists_config_define("ONE_PROCESS");
1371         foreground = ap_exists_config_define("FOREGROUND");
1372     }
1373
1374     ap_mutex_register(p, AP_ACCEPT_MUTEX_TYPE, NULL, APR_LOCK_DEFAULT, 0);
1375
1376     /* sigh, want this only the second time around */
1377     retained = ap_retained_data_get(userdata_key);
1378     if (!retained) {
1379         retained = ap_retained_data_create(userdata_key, sizeof(*retained));
1380         retained->max_daemons_limit = -1;
1381         retained->idle_spawn_rate = 1;
1382     }
1383     ++retained->module_loads;
1384     if (retained->module_loads == 2) {
1385         if (!one_process && !foreground) {
1386             /* before we detach, setup crash handlers to log to errorlog */
1387             ap_fatal_signal_setup(ap_server_conf, pconf);
1388             rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
1389                                            : APR_PROC_DETACH_DAEMONIZE);
1390             if (rv != APR_SUCCESS) {
1391                 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(00174)
1392                              "apr_proc_detach failed");
1393                 return HTTP_INTERNAL_SERVER_ERROR;
1394             }
1395         }
1396     }
1397
1398     parent_pid = ap_my_pid = getpid();
1399
1400     ap_listen_pre_config();
1401     ap_daemons_to_start = DEFAULT_START_DAEMON;
1402     ap_daemons_min_free = DEFAULT_MIN_FREE_DAEMON;
1403     ap_daemons_max_free = DEFAULT_MAX_FREE_DAEMON;
1404     server_limit = DEFAULT_SERVER_LIMIT;
1405     ap_daemons_limit = server_limit;
1406     ap_extended_status = 0;
1407
1408     return OK;
1409 }
1410
1411 static int prefork_check_config(apr_pool_t *p, apr_pool_t *plog,
1412                                 apr_pool_t *ptemp, server_rec *s)
1413 {
1414     int startup = 0;
1415
1416     /* the reverse of pre_config, we want this only the first time around */
1417     if (retained->module_loads == 1) {
1418         startup = 1;
1419     }
1420
1421     if (server_limit > MAX_SERVER_LIMIT) {
1422         if (startup) {
1423             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00175)
1424                          "WARNING: ServerLimit of %d exceeds compile-time "
1425                          "limit of", server_limit);
1426             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1427                          " %d servers, decreasing to %d.",
1428                          MAX_SERVER_LIMIT, MAX_SERVER_LIMIT);
1429         } else {
1430             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00176)
1431                          "ServerLimit of %d exceeds compile-time limit "
1432                          "of %d, decreasing to match",
1433                          server_limit, MAX_SERVER_LIMIT);
1434         }
1435         server_limit = MAX_SERVER_LIMIT;
1436     }
1437     else if (server_limit < 1) {
1438         if (startup) {
1439             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00177)
1440                          "WARNING: ServerLimit of %d not allowed, "
1441                          "increasing to 1.", server_limit);
1442         } else {
1443             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00178)
1444                          "ServerLimit of %d not allowed, increasing to 1",
1445                          server_limit);
1446         }
1447         server_limit = 1;
1448     }
1449
1450     /* you cannot change ServerLimit across a restart; ignore
1451      * any such attempts
1452      */
1453     if (!retained->first_server_limit) {
1454         retained->first_server_limit = server_limit;
1455     }
1456     else if (server_limit != retained->first_server_limit) {
1457         /* don't need a startup console version here */
1458         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00179)
1459                      "changing ServerLimit to %d from original value of %d "
1460                      "not allowed during restart",
1461                      server_limit, retained->first_server_limit);
1462         server_limit = retained->first_server_limit;
1463     }
1464
1465     if (ap_daemons_limit > server_limit) {
1466         if (startup) {
1467             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00180)
1468                          "WARNING: MaxRequestWorkers of %d exceeds ServerLimit "
1469                          "value of", ap_daemons_limit);
1470             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1471                          " %d servers, decreasing MaxRequestWorkers to %d.",
1472                          server_limit, server_limit);
1473             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1474                          " To increase, please see the ServerLimit "
1475                          "directive.");
1476         } else {
1477             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00181)
1478                          "MaxRequestWorkers of %d exceeds ServerLimit value "
1479                          "of %d, decreasing to match",
1480                          ap_daemons_limit, server_limit);
1481         }
1482         ap_daemons_limit = server_limit;
1483     }
1484     else if (ap_daemons_limit < 1) {
1485         if (startup) {
1486             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00182)
1487                          "WARNING: MaxRequestWorkers of %d not allowed, "
1488                          "increasing to 1.", ap_daemons_limit);
1489         } else {
1490             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00183)
1491                          "MaxRequestWorkers of %d not allowed, increasing to 1",
1492                          ap_daemons_limit);
1493         }
1494         ap_daemons_limit = 1;
1495     }
1496
1497     /* ap_daemons_to_start > ap_daemons_limit checked in prefork_run() */
1498     if (ap_daemons_to_start < 1) {
1499         if (startup) {
1500             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00184)
1501                          "WARNING: StartServers of %d not allowed, "
1502                          "increasing to 1.", ap_daemons_to_start);
1503         } else {
1504             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00185)
1505                          "StartServers of %d not allowed, increasing to 1",
1506                          ap_daemons_to_start);
1507         }
1508         ap_daemons_to_start = 1;
1509     }
1510
1511     if (ap_daemons_min_free < 1) {
1512         if (startup) {
1513             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00186)
1514                          "WARNING: MinSpareServers of %d not allowed, "
1515                          "increasing to 1", ap_daemons_min_free);
1516             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1517                          " to avoid almost certain server failure.");
1518             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1519                          " Please read the documentation.");
1520         } else {
1521             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00187)
1522                          "MinSpareServers of %d not allowed, increasing to 1",
1523                          ap_daemons_min_free);
1524         }
1525         ap_daemons_min_free = 1;
1526     }
1527
1528     /* ap_daemons_max_free < ap_daemons_min_free + 1 checked in prefork_run() */
1529
1530     return OK;
1531 }
1532
1533 static void prefork_hooks(apr_pool_t *p)
1534 {
1535     /* Our open_logs hook function must run before the core's, or stderr
1536      * will be redirected to a file, and the messages won't print to the
1537      * console.
1538      */
1539     static const char *const aszSucc[] = {"core.c", NULL};
1540     ap_force_set_tz(p);
1541
1542     ap_hook_open_logs(prefork_open_logs, NULL, aszSucc, APR_HOOK_REALLY_FIRST);
1543     /* we need to set the MPM state before other pre-config hooks use MPM query
1544      * to retrieve it, so register as REALLY_FIRST
1545      */
1546     ap_hook_pre_config(prefork_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
1547     ap_hook_check_config(prefork_check_config, NULL, NULL, APR_HOOK_MIDDLE);
1548     ap_hook_mpm(prefork_run, NULL, NULL, APR_HOOK_MIDDLE);
1549     ap_hook_mpm_query(prefork_query, NULL, NULL, APR_HOOK_MIDDLE);
1550     ap_hook_mpm_get_name(prefork_get_name, NULL, NULL, APR_HOOK_MIDDLE);
1551 }
1552
1553 static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, const char *arg)
1554 {
1555     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1556     if (err != NULL) {
1557         return err;
1558     }
1559
1560     ap_daemons_to_start = atoi(arg);
1561     return NULL;
1562 }
1563
1564 static const char *set_min_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
1565 {
1566     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1567     if (err != NULL) {
1568         return err;
1569     }
1570
1571     ap_daemons_min_free = atoi(arg);
1572     return NULL;
1573 }
1574
1575 static const char *set_max_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
1576 {
1577     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1578     if (err != NULL) {
1579         return err;
1580     }
1581
1582     ap_daemons_max_free = atoi(arg);
1583     return NULL;
1584 }
1585
1586 static const char *set_max_clients (cmd_parms *cmd, void *dummy, const char *arg)
1587 {
1588     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1589     if (err != NULL) {
1590         return err;
1591     }
1592     if (!strcasecmp(cmd->cmd->name, "MaxClients")) {
1593         ap_log_error(APLOG_MARK, APLOG_INFO, 0, NULL, APLOGNO(00188)
1594                      "MaxClients is deprecated, use MaxRequestWorkers "
1595                      "instead.");
1596     }
1597     ap_daemons_limit = atoi(arg);
1598     return NULL;
1599 }
1600
1601 static const char *set_server_limit (cmd_parms *cmd, void *dummy, const char *arg)
1602 {
1603     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1604     if (err != NULL) {
1605         return err;
1606     }
1607
1608     server_limit = atoi(arg);
1609     return NULL;
1610 }
1611
1612 static const command_rec prefork_cmds[] = {
1613 LISTEN_COMMANDS,
1614 AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
1615               "Number of child processes launched at server startup"),
1616 AP_INIT_TAKE1("MinSpareServers", set_min_free_servers, NULL, RSRC_CONF,
1617               "Minimum number of idle children, to handle request spikes"),
1618 AP_INIT_TAKE1("MaxSpareServers", set_max_free_servers, NULL, RSRC_CONF,
1619               "Maximum number of idle children"),
1620 AP_INIT_TAKE1("MaxClients", set_max_clients, NULL, RSRC_CONF,
1621               "Deprecated name of MaxRequestWorkers"),
1622 AP_INIT_TAKE1("MaxRequestWorkers", set_max_clients, NULL, RSRC_CONF,
1623               "Maximum number of children alive at the same time"),
1624 AP_INIT_TAKE1("ServerLimit", set_server_limit, NULL, RSRC_CONF,
1625               "Maximum value of MaxRequestWorkers for this run of Apache"),
1626 AP_GRACEFUL_SHUTDOWN_TIMEOUT_COMMAND,
1627 { NULL }
1628 };
1629
1630 AP_DECLARE_MODULE(mpm_prefork) = {
1631     MPM20_MODULE_STUFF,
1632     NULL,                       /* hook to run before apache parses args */
1633     NULL,                       /* create per-directory config structure */
1634     NULL,                       /* merge per-directory config structures */
1635     NULL,                       /* create per-server config structure */
1636     NULL,                       /* merge per-server config structures */
1637     prefork_cmds,               /* command apr_table_t */
1638     prefork_hooks,              /* register hooks */
1639 };