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