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
89static apr_proc_mutex_t *accept_mutex;
90static int ap_daemons_to_start=0;
91static int ap_daemons_min_free=0;
92static int ap_daemons_max_free=0;
93static int ap_daemons_limit=0;      /* MaxRequestWorkers */
94static int server_limit = 0;
95static int mpm_state = AP_MPMQ_STARTING;
96static 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 */
102typedef 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;
126static 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
141static int one_process = 0;
142
143static apr_pool_t *pconf;               /* Pool for config stuff */
144static apr_pool_t *pchild;              /* Pool for httpd child stuff */
145
146static pid_t ap_my_pid; /* it seems silly to call getpid all the time */
147static pid_t parent_pid;
148static 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 */
157static 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, APLOGNO(00142)
179                         "gprof: error creating directory %s", dir);
180        }
181    }
182    else {
183        use_dir = ap_runtime_dir_relative(pconf, "");
184    }
185
186    chdir(use_dir);
187}
188#else
189#define chdir_for_gprof()
190#endif
191
192static 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
203static 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 */
212static void clean_child_exit(int code) __attribute__ ((noreturn));
213static 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
230static 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, APLOGNO(00143) "%s", msg);
239            clean_child_exit(0);
240        }
241        else {
242            ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, APLOGNO(00144) "%s", msg);
243            exit(APEXIT_CHILDFATAL);
244        }
245    }
246}
247
248static 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, APLOGNO(00145) "%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, APLOGNO(00146) "%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
280static 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
333static const char *prefork_get_name(void)
334{
335    return "prefork";
336}
337
338/*****************************************************************
339 * Connection structures and accounting...
340 */
341
342static void just_die(int sig)
343{
344    clean_child_exit(0);
345}
346
347/* volatile because they're updated from a signal handler */
348static int volatile shutdown_pending;
349static int volatile restart_pending;
350static int volatile die_now = 0;
351
352static 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
361static 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 */
378static 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
389static 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, APLOGNO(00147) "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, APLOGNO(00148)
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, APLOGNO(00149) "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, APLOGNO(00150) "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, APLOGNO(00151) "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, APLOGNO(00152) "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, APLOGNO(00153) "sigaction(SIGHUP)");
442    if (sigaction(AP_SIG_GRACEFUL, &sa, NULL) < 0)
443        ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(00154) "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
477static int requests_this_child;
478static int num_listensocks = 0;
479
480static 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, APLOGNO(00155)
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, APLOGNO(00156)
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            /* If the child processed a SIGWINCH before setting up the
568             * pollset, this error path is expected and harmless,
569             * since the listener fd was already closed; so don't
570             * pollute the logs in that case. */
571            if (!die_now) {
572                ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf, APLOGNO(00157)
573                             "Couldn't add listener to pollset; check system or user limits");
574                clean_child_exit(APEXIT_CHILDSICK);
575            }
576            clean_child_exit(0);
577        }
578
579        lr->accept_func = ap_unixd_accept;
580    }
581
582    mpm_state = AP_MPMQ_RUNNING;
583
584    bucket_alloc = apr_bucket_alloc_create(pchild);
585
586    /* die_now is set when AP_SIG_GRACEFUL is received in the child;
587     * shutdown_pending is set when SIGTERM is received when running
588     * in single process mode.  */
589    while (!die_now && !shutdown_pending) {
590        conn_rec *current_conn;
591        void *csd;
592
593        /*
594         * (Re)initialize this child to a pre-connection state.
595         */
596
597        apr_pool_clear(ptrans);
598
599        if ((ap_max_requests_per_child > 0
600             && requests_this_child++ >= ap_max_requests_per_child)) {
601            clean_child_exit(0);
602        }
603
604        (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
605
606        /*
607         * Wait for an acceptable connection to arrive.
608         */
609
610        /* Lock around "accept", if necessary */
611        SAFE_ACCEPT(accept_mutex_on());
612
613        if (num_listensocks == 1) {
614            /* There is only one listener record, so refer to that one. */
615            lr = ap_listeners;
616        }
617        else {
618            /* multiple listening sockets - need to poll */
619            for (;;) {
620                apr_int32_t numdesc;
621                const apr_pollfd_t *pdesc;
622
623                /* check for termination first so we don't sleep for a while in
624                 * poll if already signalled
625                 */
626                if (die_now         /* in graceful stop/restart */
627                    || (one_process && shutdown_pending)) {
628                    SAFE_ACCEPT(accept_mutex_off());
629                    clean_child_exit(0);
630                }
631
632                /* timeout == 10 seconds to avoid a hang at graceful restart/stop
633                 * caused by the closing of sockets by the signal handler
634                 */
635                status = apr_pollset_poll(pollset, apr_time_from_sec(10),
636                                          &numdesc, &pdesc);
637                if (status != APR_SUCCESS) {
638                    if (APR_STATUS_IS_TIMEUP(status) ||
639                        APR_STATUS_IS_EINTR(status)) {
640                        continue;
641                    }
642                    /* Single Unix documents select as returning errnos
643                     * EBADF, EINTR, and EINVAL... and in none of those
644                     * cases does it make sense to continue.  In fact
645                     * on Linux 2.0.x we seem to end up with EFAULT
646                     * occasionally, and we'd loop forever due to it.
647                     */
648                    ap_log_error(APLOG_MARK, APLOG_ERR, status,
649                                 ap_server_conf, APLOGNO(00158) "apr_pollset_poll: (listen)");
650                    SAFE_ACCEPT(accept_mutex_off());
651                    clean_child_exit(APEXIT_CHILDSICK);
652                }
653
654                /* We can always use pdesc[0], but sockets at position N
655                 * could end up completely starved of attention in a very
656                 * busy server. Therefore, we round-robin across the
657                 * returned set of descriptors. While it is possible that
658                 * the returned set of descriptors might flip around and
659                 * continue to starve some sockets, we happen to know the
660                 * internal pollset implementation retains ordering
661                 * stability of the sockets. Thus, the round-robin should
662                 * ensure that a socket will eventually be serviced.
663                 */
664                if (last_poll_idx >= numdesc)
665                    last_poll_idx = 0;
666
667                /* Grab a listener record from the client_data of the poll
668                 * descriptor, and advance our saved index to round-robin
669                 * the next fetch.
670                 *
671                 * ### hmm... this descriptor might have POLLERR rather
672                 * ### than POLLIN
673                 */
674                lr = pdesc[last_poll_idx++].client_data;
675                goto got_fd;
676            }
677        }
678    got_fd:
679        /* if we accept() something we don't want to die, so we have to
680         * defer the exit
681         */
682        status = lr->accept_func(&csd, lr, ptrans);
683
684        SAFE_ACCEPT(accept_mutex_off());      /* unlock after "accept" */
685
686        if (status == APR_EGENERAL) {
687            /* resource shortage or should-not-occur occured */
688            clean_child_exit(APEXIT_CHILDSICK);
689        }
690        else if (status != APR_SUCCESS) {
691            continue;
692        }
693
694        /*
695         * We now have a connection, so set it up with the appropriate
696         * socket options, file descriptors, and read/write buffers.
697         */
698
699        current_conn = ap_run_create_connection(ptrans, ap_server_conf, csd, my_child_num, sbh, bucket_alloc);
700        if (current_conn) {
701#if APR_HAS_THREADS
702            current_conn->current_thread = thd;
703#endif
704            ap_process_connection(current_conn, csd);
705            ap_lingering_close(current_conn);
706        }
707
708        /* Check the pod and the generation number after processing a
709         * connection so that we'll go away if a graceful restart occurred
710         * while we were processing the connection or we are the lucky
711         * idle server process that gets to die.
712         */
713        if (ap_mpm_pod_check(pod) == APR_SUCCESS) { /* selected as idle? */
714            die_now = 1;
715        }
716        else if (retained->my_generation !=
717                 ap_scoreboard_image->global->running_generation) { /* restart? */
718            /* yeah, this could be non-graceful restart, in which case the
719             * parent will kill us soon enough, but why bother checking?
720             */
721            die_now = 1;
722        }
723    }
724    apr_pool_clear(ptrans); /* kludge to avoid crash in APR reslist cleanup code */
725    clean_child_exit(0);
726}
727
728
729static int make_child(server_rec *s, int slot)
730{
731    int pid;
732
733    if (slot + 1 > retained->max_daemons_limit) {
734        retained->max_daemons_limit = slot + 1;
735    }
736
737    if (one_process) {
738        apr_signal(SIGHUP, sig_term);
739        /* Don't catch AP_SIG_GRACEFUL in ONE_PROCESS mode :) */
740        apr_signal(SIGINT, sig_term);
741#ifdef SIGQUIT
742        apr_signal(SIGQUIT, SIG_DFL);
743#endif
744        apr_signal(SIGTERM, sig_term);
745        prefork_note_child_started(slot, getpid());
746        child_main(slot);
747        /* NOTREACHED */
748    }
749
750    (void) ap_update_child_status_from_indexes(slot, 0, SERVER_STARTING,
751                                               (request_rec *) NULL);
752
753
754#ifdef _OSD_POSIX
755    /* BS2000 requires a "special" version of fork() before a setuid() call */
756    if ((pid = os_fork(ap_unixd_config.user_name)) == -1) {
757#else
758    if ((pid = fork()) == -1) {
759#endif
760        ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, APLOGNO(00159) "fork: Unable to fork new process");
761
762        /* fork didn't succeed. Fix the scoreboard or else
763         * it will say SERVER_STARTING forever and ever
764         */
765        (void) ap_update_child_status_from_indexes(slot, 0, SERVER_DEAD,
766                                                   (request_rec *) NULL);
767
768        /* In case system resources are maxxed out, we don't want
769         * Apache running away with the CPU trying to fork over and
770         * over and over again.
771         */
772        sleep(10);
773
774        return -1;
775    }
776
777    if (!pid) {
778#ifdef HAVE_BINDPROCESSOR
779        /* by default AIX binds to a single processor
780         * this bit unbinds children which will then bind to another cpu
781         */
782        int status = bindprocessor(BINDPROCESS, (int)getpid(),
783                                   PROCESSOR_CLASS_ANY);
784        if (status != OK) {
785            ap_log_error(APLOG_MARK, APLOG_DEBUG, errno,
786                         ap_server_conf, APLOGNO(00160) "processor unbind failed");
787        }
788#endif
789        RAISE_SIGSTOP(MAKE_CHILD);
790        AP_MONCONTROL(1);
791        /* Disable the parent's signal handlers and set up proper handling in
792         * the child.
793         */
794        apr_signal(SIGHUP, just_die);
795        apr_signal(SIGTERM, just_die);
796        /* The child process just closes listeners on AP_SIG_GRACEFUL.
797         * The pod is used for signalling the graceful restart.
798         */
799        apr_signal(AP_SIG_GRACEFUL, stop_listening);
800        child_main(slot);
801    }
802
803    prefork_note_child_started(slot, pid);
804
805    return 0;
806}
807
808
809/* start up a bunch of children */
810static void startup_children(int number_to_start)
811{
812    int i;
813
814    for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
815        if (ap_scoreboard_image->servers[i][0].status != SERVER_DEAD) {
816            continue;
817        }
818        if (make_child(ap_server_conf, i) < 0) {
819            break;
820        }
821        --number_to_start;
822    }
823}
824
825static void perform_idle_server_maintenance(apr_pool_t *p)
826{
827    int i;
828    int idle_count;
829    worker_score *ws;
830    int free_length;
831    int free_slots[MAX_SPAWN_RATE];
832    int last_non_dead;
833    int total_non_dead;
834
835    /* initialize the free_list */
836    free_length = 0;
837
838    idle_count = 0;
839    last_non_dead = -1;
840    total_non_dead = 0;
841
842    for (i = 0; i < ap_daemons_limit; ++i) {
843        int status;
844
845        if (i >= retained->max_daemons_limit && free_length == retained->idle_spawn_rate)
846            break;
847        ws = &ap_scoreboard_image->servers[i][0];
848        status = ws->status;
849        if (status == SERVER_DEAD) {
850            /* try to keep children numbers as low as possible */
851            if (free_length < retained->idle_spawn_rate) {
852                free_slots[free_length] = i;
853                ++free_length;
854            }
855        }
856        else {
857            /* We consider a starting server as idle because we started it
858             * at least a cycle ago, and if it still hasn't finished starting
859             * then we're just going to swamp things worse by forking more.
860             * So we hopefully won't need to fork more if we count it.
861             * This depends on the ordering of SERVER_READY and SERVER_STARTING.
862             */
863            if (status <= SERVER_READY) {
864                ++ idle_count;
865            }
866
867            ++total_non_dead;
868            last_non_dead = i;
869        }
870    }
871    retained->max_daemons_limit = last_non_dead + 1;
872    if (idle_count > ap_daemons_max_free) {
873        /* kill off one child... we use the pod because that'll cause it to
874         * shut down gracefully, in case it happened to pick up a request
875         * while we were counting
876         */
877        ap_mpm_pod_signal(pod);
878        retained->idle_spawn_rate = 1;
879    }
880    else if (idle_count < ap_daemons_min_free) {
881        /* terminate the free list */
882        if (free_length == 0) {
883            /* only report this condition once */
884            if (!retained->maxclients_reported) {
885                ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(00161)
886                            "server reached MaxRequestWorkers setting, consider"
887                            " raising the MaxRequestWorkers setting");
888                retained->maxclients_reported = 1;
889            }
890            retained->idle_spawn_rate = 1;
891        }
892        else {
893            if (retained->idle_spawn_rate >= 8) {
894                ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, APLOGNO(00162)
895                    "server seems busy, (you may need "
896                    "to increase StartServers, or Min/MaxSpareServers), "
897                    "spawning %d children, there are %d idle, and "
898                    "%d total children", retained->idle_spawn_rate,
899                    idle_count, total_non_dead);
900            }
901            for (i = 0; i < free_length; ++i) {
902                make_child(ap_server_conf, free_slots[i]);
903            }
904            /* the next time around we want to spawn twice as many if this
905             * wasn't good enough, but not if we've just done a graceful
906             */
907            if (retained->hold_off_on_exponential_spawning) {
908                --retained->hold_off_on_exponential_spawning;
909            }
910            else if (retained->idle_spawn_rate < MAX_SPAWN_RATE) {
911                retained->idle_spawn_rate *= 2;
912            }
913        }
914    }
915    else {
916        retained->idle_spawn_rate = 1;
917    }
918}
919
920/*****************************************************************
921 * Executive routines.
922 */
923
924static int prefork_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
925{
926    int index;
927    int remaining_children_to_start;
928    apr_status_t rv;
929
930    ap_log_pid(pconf, ap_pid_fname);
931
932    /* Initialize cross-process accept lock */
933    rv = ap_proc_mutex_create(&accept_mutex, NULL, AP_ACCEPT_MUTEX_TYPE, NULL,
934                              s, _pconf, 0);
935    if (rv != APR_SUCCESS) {
936        mpm_state = AP_MPMQ_STOPPING;
937        return DONE;
938    }
939
940    if (!retained->is_graceful) {
941        if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
942            mpm_state = AP_MPMQ_STOPPING;
943            return DONE;
944        }
945        /* fix the generation number in the global score; we just got a new,
946         * cleared scoreboard
947         */
948        ap_scoreboard_image->global->running_generation = retained->my_generation;
949    }
950
951    restart_pending = shutdown_pending = 0;
952    set_signals();
953
954    if (one_process) {
955        AP_MONCONTROL(1);
956        make_child(ap_server_conf, 0);
957        /* NOTREACHED */
958    }
959    else {
960    if (ap_daemons_max_free < ap_daemons_min_free + 1)  /* Don't thrash... */
961        ap_daemons_max_free = ap_daemons_min_free + 1;
962
963    /* If we're doing a graceful_restart then we're going to see a lot
964     * of children exiting immediately when we get into the main loop
965     * below (because we just sent them AP_SIG_GRACEFUL).  This happens pretty
966     * rapidly... and for each one that exits we'll start a new one until
967     * we reach at least daemons_min_free.  But we may be permitted to
968     * start more than that, so we'll just keep track of how many we're
969     * supposed to start up without the 1 second penalty between each fork.
970     */
971    remaining_children_to_start = ap_daemons_to_start;
972    if (remaining_children_to_start > ap_daemons_limit) {
973        remaining_children_to_start = ap_daemons_limit;
974    }
975    if (!retained->is_graceful) {
976        startup_children(remaining_children_to_start);
977        remaining_children_to_start = 0;
978    }
979    else {
980        /* give the system some time to recover before kicking into
981         * exponential mode
982         */
983        retained->hold_off_on_exponential_spawning = 10;
984    }
985
986    ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00163)
987                "%s configured -- resuming normal operations",
988                ap_get_server_description());
989    ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, APLOGNO(00164)
990                "Server built: %s", ap_get_server_built());
991    ap_log_command_line(plog, s);
992    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(00165)
993                "Accept mutex: %s (default: %s)",
994                apr_proc_mutex_name(accept_mutex),
995                apr_proc_mutex_defname());
996
997    mpm_state = AP_MPMQ_RUNNING;
998
999    while (!restart_pending && !shutdown_pending) {
1000        int child_slot;
1001        apr_exit_why_e exitwhy;
1002        int status, processed_status;
1003        /* this is a memory leak, but I'll fix it later. */
1004        apr_proc_t pid;
1005
1006        ap_wait_or_timeout(&exitwhy, &status, &pid, pconf, ap_server_conf);
1007
1008        /* XXX: if it takes longer than 1 second for all our children
1009         * to start up and get into IDLE state then we may spawn an
1010         * extra child
1011         */
1012        if (pid.pid != -1) {
1013            processed_status = ap_process_child_status(&pid, exitwhy, status);
1014            child_slot = ap_find_child_by_pid(&pid);
1015            if (processed_status == APEXIT_CHILDFATAL) {
1016                /* fix race condition found in PR 39311
1017                 * A child created at the same time as a graceful happens
1018                 * can find the lock missing and create a fatal error.
1019                 * It is not fatal for the last generation to be in this state.
1020                 */
1021                if (child_slot < 0
1022                    || ap_get_scoreboard_process(child_slot)->generation
1023                       == retained->my_generation) {
1024                    mpm_state = AP_MPMQ_STOPPING;
1025                    return DONE;
1026                }
1027                else {
1028                    ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, APLOGNO(00166)
1029                                 "Ignoring fatal error in child of previous "
1030                                 "generation (pid %ld).",
1031                                 (long)pid.pid);
1032                }
1033            }
1034
1035            /* non-fatal death... note that it's gone in the scoreboard. */
1036            if (child_slot >= 0) {
1037                (void) ap_update_child_status_from_indexes(child_slot, 0, SERVER_DEAD,
1038                                                           (request_rec *) NULL);
1039                prefork_note_child_killed(child_slot, 0, 0);
1040                if (processed_status == APEXIT_CHILDSICK) {
1041                    /* child detected a resource shortage (E[NM]FILE, ENOBUFS, etc)
1042                     * cut the fork rate to the minimum
1043                     */
1044                    retained->idle_spawn_rate = 1;
1045                }
1046                else if (remaining_children_to_start
1047                    && child_slot < ap_daemons_limit) {
1048                    /* we're still doing a 1-for-1 replacement of dead
1049                     * children with new children
1050                     */
1051                    make_child(ap_server_conf, child_slot);
1052                    --remaining_children_to_start;
1053                }
1054#if APR_HAS_OTHER_CHILD
1055            }
1056            else if (apr_proc_other_child_alert(&pid, APR_OC_REASON_DEATH, status) == APR_SUCCESS) {
1057                /* handled */
1058#endif
1059            }
1060            else if (retained->is_graceful) {
1061                /* Great, we've probably just lost a slot in the
1062                 * scoreboard.  Somehow we don't know about this
1063                 * child.
1064                 */
1065                ap_log_error(APLOG_MARK, APLOG_WARNING,
1066                            0, ap_server_conf, APLOGNO(00167)
1067                            "long lost child came home! (pid %ld)", (long)pid.pid);
1068            }
1069            /* Don't perform idle maintenance when a child dies,
1070             * only do it when there's a timeout.  Remember only a
1071             * finite number of children can die, and it's pretty
1072             * pathological for a lot to die suddenly.
1073             */
1074            continue;
1075        }
1076        else if (remaining_children_to_start) {
1077            /* we hit a 1 second timeout in which none of the previous
1078             * generation of children needed to be reaped... so assume
1079             * they're all done, and pick up the slack if any is left.
1080             */
1081            startup_children(remaining_children_to_start);
1082            remaining_children_to_start = 0;
1083            /* In any event we really shouldn't do the code below because
1084             * few of the servers we just started are in the IDLE state
1085             * yet, so we'd mistakenly create an extra server.
1086             */
1087            continue;
1088        }
1089
1090        perform_idle_server_maintenance(pconf);
1091    }
1092    } /* one_process */
1093
1094    mpm_state = AP_MPMQ_STOPPING;
1095
1096    if (shutdown_pending && !retained->is_graceful) {
1097        /* Time to shut down:
1098         * Kill child processes, tell them to call child_exit, etc...
1099         */
1100        if (ap_unixd_killpg(getpgrp(), SIGTERM) < 0) {
1101            ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(00168) "killpg SIGTERM");
1102        }
1103        ap_reclaim_child_processes(1, /* Start with SIGTERM */
1104                                   prefork_note_child_killed);
1105
1106        /* cleanup pid file on normal shutdown */
1107        ap_remove_pid(pconf, ap_pid_fname);
1108        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00169)
1109                    "caught SIGTERM, shutting down");
1110
1111        return DONE;
1112    } else if (shutdown_pending) {
1113        /* Time to perform a graceful shut down:
1114         * Reap the inactive children, and ask the active ones
1115         * to close their listeners, then wait until they are
1116         * all done to exit.
1117         */
1118        int active_children;
1119        apr_time_t cutoff = 0;
1120
1121        /* Stop listening */
1122        ap_close_listeners();
1123
1124        /* kill off the idle ones */
1125        ap_mpm_pod_killpg(pod, retained->max_daemons_limit);
1126
1127        /* Send SIGUSR1 to the active children */
1128        active_children = 0;
1129        for (index = 0; index < ap_daemons_limit; ++index) {
1130            if (ap_scoreboard_image->servers[index][0].status != SERVER_DEAD) {
1131                /* Ask each child to close its listeners. */
1132                ap_mpm_safe_kill(MPM_CHILD_PID(index), AP_SIG_GRACEFUL);
1133                active_children++;
1134            }
1135        }
1136
1137        /* Allow each child which actually finished to exit */
1138        ap_relieve_child_processes(prefork_note_child_killed);
1139
1140        /* cleanup pid file */
1141        ap_remove_pid(pconf, ap_pid_fname);
1142        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00170)
1143           "caught " AP_SIG_GRACEFUL_STOP_STRING ", shutting down gracefully");
1144
1145        if (ap_graceful_shutdown_timeout) {
1146            cutoff = apr_time_now() +
1147                     apr_time_from_sec(ap_graceful_shutdown_timeout);
1148        }
1149
1150        /* Don't really exit until each child has finished */
1151        shutdown_pending = 0;
1152        do {
1153            /* Pause for a second */
1154            sleep(1);
1155
1156            /* Relieve any children which have now exited */
1157            ap_relieve_child_processes(prefork_note_child_killed);
1158
1159            active_children = 0;
1160            for (index = 0; index < ap_daemons_limit; ++index) {
1161                if (ap_mpm_safe_kill(MPM_CHILD_PID(index), 0) == APR_SUCCESS) {
1162                    active_children = 1;
1163                    /* Having just one child is enough to stay around */
1164                    break;
1165                }
1166            }
1167        } while (!shutdown_pending && active_children &&
1168                 (!ap_graceful_shutdown_timeout || apr_time_now() < cutoff));
1169
1170        /* We might be here because we received SIGTERM, either
1171         * way, try and make sure that all of our processes are
1172         * really dead.
1173         */
1174        ap_unixd_killpg(getpgrp(), SIGTERM);
1175
1176        return DONE;
1177    }
1178
1179    /* we've been told to restart */
1180    apr_signal(SIGHUP, SIG_IGN);
1181    apr_signal(AP_SIG_GRACEFUL, SIG_IGN);
1182    if (one_process) {
1183        /* not worth thinking about */
1184        return DONE;
1185    }
1186
1187    /* advance to the next generation */
1188    /* XXX: we really need to make sure this new generation number isn't in
1189     * use by any of the children.
1190     */
1191    ++retained->my_generation;
1192    ap_scoreboard_image->global->running_generation = retained->my_generation;
1193
1194    if (retained->is_graceful) {
1195        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00171)
1196                    "Graceful restart requested, doing restart");
1197
1198        /* kill off the idle ones */
1199        ap_mpm_pod_killpg(pod, retained->max_daemons_limit);
1200
1201        /* This is mostly for debugging... so that we know what is still
1202         * gracefully dealing with existing request.  This will break
1203         * in a very nasty way if we ever have the scoreboard totally
1204         * file-based (no shared memory)
1205         */
1206        for (index = 0; index < ap_daemons_limit; ++index) {
1207            if (ap_scoreboard_image->servers[index][0].status != SERVER_DEAD) {
1208                ap_scoreboard_image->servers[index][0].status = SERVER_GRACEFUL;
1209                /* Ask each child to close its listeners.
1210                 *
1211                 * NOTE: we use the scoreboard, because if we send SIGUSR1
1212                 * to every process in the group, this may include CGI's,
1213                 * piped loggers, etc. They almost certainly won't handle
1214                 * it gracefully.
1215                 */
1216                ap_mpm_safe_kill(ap_scoreboard_image->parent[index].pid, AP_SIG_GRACEFUL);
1217            }
1218        }
1219    }
1220    else {
1221        /* Kill 'em off */
1222        if (ap_unixd_killpg(getpgrp(), SIGHUP) < 0) {
1223            ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(00172) "killpg SIGHUP");
1224        }
1225        ap_reclaim_child_processes(0, /* Not when just starting up */
1226                                   prefork_note_child_killed);
1227        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00173)
1228                    "SIGHUP received.  Attempting to restart");
1229    }
1230
1231    return OK;
1232}
1233
1234/* This really should be a post_config hook, but the error log is already
1235 * redirected by that point, so we need to do this in the open_logs phase.
1236 */
1237static int prefork_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
1238{
1239    int startup = 0;
1240    int level_flags = 0;
1241    apr_status_t rv;
1242
1243    pconf = p;
1244
1245    /* the reverse of pre_config, we want this only the first time around */
1246    if (retained->module_loads == 1) {
1247        startup = 1;
1248        level_flags |= APLOG_STARTUP;
1249    }
1250
1251    if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
1252        ap_log_error(APLOG_MARK, APLOG_ALERT | level_flags, 0,
1253                     (startup ? NULL : s),
1254                     "no listening sockets available, shutting down");
1255        return DONE;
1256    }
1257
1258    if ((rv = ap_mpm_pod_open(pconf, &pod))) {
1259        ap_log_error(APLOG_MARK, APLOG_CRIT | level_flags, rv,
1260                     (startup ? NULL : s),
1261                     "could not open pipe-of-death");
1262        return DONE;
1263    }
1264    return OK;
1265}
1266
1267static int prefork_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp)
1268{
1269    int no_detach, debug, foreground;
1270    apr_status_t rv;
1271    const char *userdata_key = "mpm_prefork_module";
1272
1273    mpm_state = AP_MPMQ_STARTING;
1274
1275    debug = ap_exists_config_define("DEBUG");
1276
1277    if (debug) {
1278        foreground = one_process = 1;
1279        no_detach = 0;
1280    }
1281    else
1282    {
1283        no_detach = ap_exists_config_define("NO_DETACH");
1284        one_process = ap_exists_config_define("ONE_PROCESS");
1285        foreground = ap_exists_config_define("FOREGROUND");
1286    }
1287
1288    ap_mutex_register(p, AP_ACCEPT_MUTEX_TYPE, NULL, APR_LOCK_DEFAULT, 0);
1289
1290    /* sigh, want this only the second time around */
1291    retained = ap_retained_data_get(userdata_key);
1292    if (!retained) {
1293        retained = ap_retained_data_create(userdata_key, sizeof(*retained));
1294        retained->max_daemons_limit = -1;
1295        retained->idle_spawn_rate = 1;
1296    }
1297    ++retained->module_loads;
1298    if (retained->module_loads == 2) {
1299        if (!one_process && !foreground) {
1300            /* before we detach, setup crash handlers to log to errorlog */
1301            ap_fatal_signal_setup(ap_server_conf, pconf);
1302            rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
1303                                           : APR_PROC_DETACH_DAEMONIZE);
1304            if (rv != APR_SUCCESS) {
1305                ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(00174)
1306                             "apr_proc_detach failed");
1307                return HTTP_INTERNAL_SERVER_ERROR;
1308            }
1309        }
1310    }
1311
1312    parent_pid = ap_my_pid = getpid();
1313
1314    ap_listen_pre_config();
1315    ap_daemons_to_start = DEFAULT_START_DAEMON;
1316    ap_daemons_min_free = DEFAULT_MIN_FREE_DAEMON;
1317    ap_daemons_max_free = DEFAULT_MAX_FREE_DAEMON;
1318    server_limit = DEFAULT_SERVER_LIMIT;
1319    ap_daemons_limit = server_limit;
1320    ap_extended_status = 0;
1321
1322    return OK;
1323}
1324
1325static int prefork_check_config(apr_pool_t *p, apr_pool_t *plog,
1326                                apr_pool_t *ptemp, server_rec *s)
1327{
1328    int startup = 0;
1329
1330    /* the reverse of pre_config, we want this only the first time around */
1331    if (retained->module_loads == 1) {
1332        startup = 1;
1333    }
1334
1335    if (server_limit > MAX_SERVER_LIMIT) {
1336        if (startup) {
1337            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00175)
1338                         "WARNING: ServerLimit of %d exceeds compile-time "
1339                         "limit of", server_limit);
1340            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1341                         " %d servers, decreasing to %d.",
1342                         MAX_SERVER_LIMIT, MAX_SERVER_LIMIT);
1343        } else {
1344            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00176)
1345                         "ServerLimit of %d exceeds compile-time limit "
1346                         "of %d, decreasing to match",
1347                         server_limit, MAX_SERVER_LIMIT);
1348        }
1349        server_limit = MAX_SERVER_LIMIT;
1350    }
1351    else if (server_limit < 1) {
1352        if (startup) {
1353            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00177)
1354                         "WARNING: ServerLimit of %d not allowed, "
1355                         "increasing to 1.", server_limit);
1356        } else {
1357            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00178)
1358                         "ServerLimit of %d not allowed, increasing to 1",
1359                         server_limit);
1360        }
1361        server_limit = 1;
1362    }
1363
1364    /* you cannot change ServerLimit across a restart; ignore
1365     * any such attempts
1366     */
1367    if (!retained->first_server_limit) {
1368        retained->first_server_limit = server_limit;
1369    }
1370    else if (server_limit != retained->first_server_limit) {
1371        /* don't need a startup console version here */
1372        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00179)
1373                     "changing ServerLimit to %d from original value of %d "
1374                     "not allowed during restart",
1375                     server_limit, retained->first_server_limit);
1376        server_limit = retained->first_server_limit;
1377    }
1378
1379    if (ap_daemons_limit > server_limit) {
1380        if (startup) {
1381            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00180)
1382                         "WARNING: MaxRequestWorkers of %d exceeds ServerLimit "
1383                         "value of", ap_daemons_limit);
1384            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1385                         " %d servers, decreasing MaxRequestWorkers to %d.",
1386                         server_limit, server_limit);
1387            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1388                         " To increase, please see the ServerLimit "
1389                         "directive.");
1390        } else {
1391            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00181)
1392                         "MaxRequestWorkers of %d exceeds ServerLimit value "
1393                         "of %d, decreasing to match",
1394                         ap_daemons_limit, server_limit);
1395        }
1396        ap_daemons_limit = server_limit;
1397    }
1398    else if (ap_daemons_limit < 1) {
1399        if (startup) {
1400            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00182)
1401                         "WARNING: MaxRequestWorkers of %d not allowed, "
1402                         "increasing to 1.", ap_daemons_limit);
1403        } else {
1404            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00183)
1405                         "MaxRequestWorkers of %d not allowed, increasing to 1",
1406                         ap_daemons_limit);
1407        }
1408        ap_daemons_limit = 1;
1409    }
1410
1411    /* ap_daemons_to_start > ap_daemons_limit checked in prefork_run() */
1412    if (ap_daemons_to_start < 0) {
1413        if (startup) {
1414            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00184)
1415                         "WARNING: StartServers of %d not allowed, "
1416                         "increasing to 1.", ap_daemons_to_start);
1417        } else {
1418            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00185)
1419                         "StartServers of %d not allowed, increasing to 1",
1420                         ap_daemons_to_start);
1421        }
1422        ap_daemons_to_start = 1;
1423    }
1424
1425    if (ap_daemons_min_free < 1) {
1426        if (startup) {
1427            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00186)
1428                         "WARNING: MinSpareServers of %d not allowed, "
1429                         "increasing to 1", ap_daemons_min_free);
1430            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1431                         " to avoid almost certain server failure.");
1432            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1433                         " Please read the documentation.");
1434        } else {
1435            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00187)
1436                         "MinSpareServers of %d not allowed, increasing to 1",
1437                         ap_daemons_min_free);
1438        }
1439        ap_daemons_min_free = 1;
1440    }
1441
1442    /* ap_daemons_max_free < ap_daemons_min_free + 1 checked in prefork_run() */
1443
1444    return OK;
1445}
1446
1447static void prefork_hooks(apr_pool_t *p)
1448{
1449    /* Our open_logs hook function must run before the core's, or stderr
1450     * will be redirected to a file, and the messages won't print to the
1451     * console.
1452     */
1453    static const char *const aszSucc[] = {"core.c", NULL};
1454
1455    ap_hook_open_logs(prefork_open_logs, NULL, aszSucc, APR_HOOK_REALLY_FIRST);
1456    /* we need to set the MPM state before other pre-config hooks use MPM query
1457     * to retrieve it, so register as REALLY_FIRST
1458     */
1459    ap_hook_pre_config(prefork_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
1460    ap_hook_check_config(prefork_check_config, NULL, NULL, APR_HOOK_MIDDLE);
1461    ap_hook_mpm(prefork_run, NULL, NULL, APR_HOOK_MIDDLE);
1462    ap_hook_mpm_query(prefork_query, NULL, NULL, APR_HOOK_MIDDLE);
1463    ap_hook_mpm_get_name(prefork_get_name, NULL, NULL, APR_HOOK_MIDDLE);
1464}
1465
1466static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, const char *arg)
1467{
1468    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1469    if (err != NULL) {
1470        return err;
1471    }
1472
1473    ap_daemons_to_start = atoi(arg);
1474    return NULL;
1475}
1476
1477static const char *set_min_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
1478{
1479    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1480    if (err != NULL) {
1481        return err;
1482    }
1483
1484    ap_daemons_min_free = atoi(arg);
1485    return NULL;
1486}
1487
1488static const char *set_max_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
1489{
1490    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1491    if (err != NULL) {
1492        return err;
1493    }
1494
1495    ap_daemons_max_free = atoi(arg);
1496    return NULL;
1497}
1498
1499static const char *set_max_clients (cmd_parms *cmd, void *dummy, const char *arg)
1500{
1501    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1502    if (err != NULL) {
1503        return err;
1504    }
1505    if (!strcasecmp(cmd->cmd->name, "MaxClients")) {
1506        ap_log_error(APLOG_MARK, APLOG_INFO, 0, NULL, APLOGNO(00188)
1507                     "MaxClients is deprecated, use MaxRequestWorkers "
1508                     "instead.");
1509    }
1510    ap_daemons_limit = atoi(arg);
1511    return NULL;
1512}
1513
1514static const char *set_server_limit (cmd_parms *cmd, void *dummy, const char *arg)
1515{
1516    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1517    if (err != NULL) {
1518        return err;
1519    }
1520
1521    server_limit = atoi(arg);
1522    return NULL;
1523}
1524
1525static const command_rec prefork_cmds[] = {
1526LISTEN_COMMANDS,
1527AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
1528              "Number of child processes launched at server startup"),
1529AP_INIT_TAKE1("MinSpareServers", set_min_free_servers, NULL, RSRC_CONF,
1530              "Minimum number of idle children, to handle request spikes"),
1531AP_INIT_TAKE1("MaxSpareServers", set_max_free_servers, NULL, RSRC_CONF,
1532              "Maximum number of idle children"),
1533AP_INIT_TAKE1("MaxClients", set_max_clients, NULL, RSRC_CONF,
1534              "Deprecated name of MaxRequestWorkers"),
1535AP_INIT_TAKE1("MaxRequestWorkers", set_max_clients, NULL, RSRC_CONF,
1536              "Maximum number of children alive at the same time"),
1537AP_INIT_TAKE1("ServerLimit", set_server_limit, NULL, RSRC_CONF,
1538              "Maximum value of MaxRequestWorkers for this run of Apache"),
1539AP_GRACEFUL_SHUTDOWN_TIMEOUT_COMMAND,
1540{ NULL }
1541};
1542
1543AP_DECLARE_MODULE(mpm_prefork) = {
1544    MPM20_MODULE_STUFF,
1545    NULL,                       /* hook to run before apache parses args */
1546    NULL,                       /* create per-directory config structure */
1547    NULL,                       /* merge per-directory config structures */
1548    NULL,                       /* create per-server config structure */
1549    NULL,                       /* merge per-server config structures */
1550    prefork_cmds,               /* command apr_table_t */
1551    prefork_hooks,              /* register hooks */
1552};
1553