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