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