]> granicus.if.org Git - apache/blob - server/mpm/perchild/perchild.c
convert some -1 back to errno.
[apache] / server / mpm / perchild / perchild.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000 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 #define CORE_PRIVATE 
60  
61 #include "ap_config.h"
62 #include "apr_hash.h"
63 #include "apr_strings.h"
64 #include "apr_portable.h"
65 #include "apr_file_io.h"
66 #include "httpd.h" 
67 #include "http_main.h" 
68 #include "http_log.h" 
69 #include "http_config.h"        /* for read_config */ 
70 #include "http_core.h"          /* for get_remote_host */ 
71 #include "http_protocol.h"
72 #include "http_connection.h"
73 #include "ap_mpm.h"
74 #include "unixd.h"
75 #include "mpm_common.h"
76 #include "iol_socket.h"
77 #include "ap_listen.h"
78 #include "mpm_default.h"
79 #include "mpm.h"
80 #include "scoreboard.h"
81
82 #ifdef HAVE_UNISTD_H
83 #include <unistd.h>
84 #endif
85 #include <poll.h>
86 #ifdef HAVE_SYS_SOCKET_H
87 #include <sys/socket.h>
88 #endif
89 #ifdef HAVE_NETINET_TCP_H
90 #include <netinet/tcp.h>
91 #endif
92 #include <grp.h>
93 #include <pwd.h>
94 #include <pthread.h>
95 #include <sys/stat.h>
96 #include <signal.h>
97 #include <sys/un.h>
98
99 /*
100  * Actual definitions of config globals
101  */
102
103 static int threads_to_start = 0;         /* Worker threads per child */
104 static int min_spare_threads = 0;
105 static int max_spare_threads = 0;
106 static int max_threads = 0;
107 static int max_requests_per_child = 0;
108 static const char *ap_pid_fname=NULL;
109 API_VAR_EXPORT const char *ap_scoreboard_fname=NULL;
110 static int num_daemons=0;
111 static int workers_may_exit = 0;
112 static int requests_this_child;
113 static int num_listenfds = 0;
114 static ap_socket_t **listenfds;
115
116 struct child_info_t {
117     uid_t uid;
118     gid_t gid;
119 };
120
121 struct socket_info_t {
122     const char *sname;   /* The servername */
123     int        cnum;     /* The child number */
124 };
125
126 typedef struct {
127     const char *sockname;
128 } perchild_server_conf;
129
130 typedef struct child_info_t child_info_t;
131 typedef struct socket_info_t socket_info_t;
132
133 /* Tables used to determine the user and group each child process should
134  * run as.  The hash table is used to correlate a server name with a child
135  * process.
136  */
137 static child_info_t child_info_table[HARD_SERVER_LIMIT];
138 static ap_hash_t    *socket_info_table;
139
140
141 struct ap_ctable    ap_child_table[HARD_SERVER_LIMIT];
142
143 /*
144  * The max child slot ever assigned, preserved across restarts.  Necessary
145  * to deal with NumServers changes across SIGWINCH restarts.  We use this
146  * value to optimize routines that have to scan the entire child table.
147  *
148  * XXX - It might not be worth keeping this code in. There aren't very
149  * many child processes in this MPM.
150  */
151 int ap_max_daemons_limit = -1;
152
153 char ap_coredump_dir[MAX_STRING_LEN];
154
155 module MODULE_VAR_EXPORT mpm_perchild_module;
156
157 static ap_file_t *pipe_of_death_in = NULL;
158 static ap_file_t *pipe_of_death_out = NULL;
159 static pthread_mutex_t pipe_of_death_mutex;
160
161 /* *Non*-shared http_main globals... */
162
163 server_rec *ap_server_conf;
164
165 /* one_process --- debugging mode variable; can be set from the command line
166  * with the -X flag.  If set, this gets you the child_main loop running
167  * in the process which originally started up (no detach, no make_child),
168  * which is a pretty nice debugging environment.  (You'll get a SIGHUP
169  * early in standalone_main; just continue through.  This is the server
170  * trying to kill off any child processes which it might have lying
171  * around --- Apache doesn't keep track of their pids, it just sends
172  * SIGHUP to the process group, ignoring it in the root process.
173  * Continue through and you'll be fine.).
174  */
175
176 static int one_process = 0;
177
178 #ifdef DEBUG_SIGSTOP
179 int raise_sigstop_flags;
180 #endif
181
182 static ap_pool_t *pconf;                /* Pool for config stuff */
183 static ap_pool_t *pchild;               /* Pool for httpd child stuff */
184 static ap_pool_t *thread_pool_parent; /* Parent of per-thread pools */
185 static pthread_mutex_t thread_pool_parent_mutex;
186
187 static int child_num;
188 static unsigned int my_pid; /* Linux getpid() doesn't work except in 
189                       main thread. Use this instead */
190 /* Keep track of the number of worker threads currently active */
191 static int worker_thread_count;
192 static pthread_mutex_t worker_thread_count_mutex;
193 static int worker_thread_free_ids[HARD_THREAD_LIMIT];
194 static pthread_attr_t worker_thread_attr;
195
196 /* Keep track of the number of idle worker threads */
197 static int idle_thread_count;
198 static pthread_mutex_t idle_thread_count_mutex;
199
200 /* Locks for accept serialization */
201 #ifdef NO_SERIALIZED_ACCEPT
202 #define SAFE_ACCEPT(stmt) APR_SUCCESS
203 #else
204 #define SAFE_ACCEPT(stmt) (stmt)
205 static ap_lock_t *process_accept_mutex;
206 #endif /* NO_SERIALIZED_ACCEPT */
207 static const char *lock_fname;
208 static pthread_mutex_t thread_accept_mutex = PTHREAD_MUTEX_INITIALIZER;
209
210 API_EXPORT(int) ap_get_max_daemons(void)
211 {
212     return ap_max_daemons_limit;
213 }
214
215 /* a clean exit from a child with proper cleanup */
216 static void clean_child_exit(int code)
217 {
218     if (pchild) {
219         ap_destroy_pool(pchild);
220     }
221     exit(code);
222 }
223
224 /* handle all varieties of core dumping signals */
225 static void sig_coredump(int sig)
226 {
227     chdir(ap_coredump_dir);
228     ap_signal(sig, SIG_DFL);
229     kill(getpid(), sig);
230     /* At this point we've got sig blocked, because we're still inside
231      * the signal handler.  When we leave the signal handler it will
232      * be unblocked, and we'll take the signal... and coredump or whatever
233      * is appropriate for this particular Unix.  In addition the parent
234      * will see the real signal we received -- whereas if we called
235      * abort() here, the parent would only see SIGABRT.
236      */
237 }
238
239 static void just_die(int sig)
240 {
241     clean_child_exit(0);
242 }
243
244 /*****************************************************************
245  * Connection structures and accounting...
246  */
247
248 /* volatile just in case */
249 static int volatile shutdown_pending;
250 static int volatile restart_pending;
251 static int volatile is_graceful;
252
253 /*
254  * ap_start_shutdown() and ap_start_restart(), below, are a first stab at
255  * functions to initiate shutdown or restart without relying on signals. 
256  * Previously this was initiated in sig_term() and restart() signal handlers, 
257  * but we want to be able to start a shutdown/restart from other sources --
258  * e.g. on Win32, from the service manager. Now the service manager can
259  * call ap_start_shutdown() or ap_start_restart() as appropiate.  Note that
260  * these functions can also be called by the child processes, since global
261  * variables are no longer used to pass on the required action to the parent.
262  *
263  * These should only be called from the parent process itself, since the
264  * parent process will use the shutdown_pending and restart_pending variables
265  * to determine whether to shutdown or restart. The child process should
266  * call signal_parent() directly to tell the parent to die -- this will
267  * cause neither of those variable to be set, which the parent will
268  * assume means something serious is wrong (which it will be, for the
269  * child to force an exit) and so do an exit anyway.
270  */
271
272 void ap_start_shutdown(void)
273 {
274     if (shutdown_pending == 1) {
275         /* Um, is this _probably_ not an error, if the user has
276          * tried to do a shutdown twice quickly, so we won't
277          * worry about reporting it.
278          */
279         return;
280     }
281     shutdown_pending = 1;
282 }
283
284 /* do a graceful restart if graceful == 1 */
285 void ap_start_restart(int graceful)
286 {
287
288     if (restart_pending == 1) {
289         /* Probably not an error - don't bother reporting it */
290         return;
291     }
292     restart_pending = 1;
293     is_graceful = graceful;
294 }
295
296 static void sig_term(int sig)
297 {
298     ap_start_shutdown();
299 }
300
301 static void restart(int sig)
302 {
303 #ifndef WIN32
304     ap_start_restart(sig == SIGWINCH);
305 #else
306     ap_start_restart(1);
307 #endif
308 }
309
310 static void set_signals(void)
311 {
312 #ifndef NO_USE_SIGACTION
313     struct sigaction sa;
314
315     sigemptyset(&sa.sa_mask);
316     sa.sa_flags = 0;
317
318     if (!one_process) {
319         sa.sa_handler = sig_coredump;
320 #if defined(SA_ONESHOT)
321         sa.sa_flags = SA_ONESHOT;
322 #elif defined(SA_RESETHAND)
323         sa.sa_flags = SA_RESETHAND;
324 #endif
325         if (sigaction(SIGSEGV, &sa, NULL) < 0)
326             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGSEGV)");
327 #ifdef SIGBUS
328         if (sigaction(SIGBUS, &sa, NULL) < 0)
329             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGBUS)");
330 #endif
331 #ifdef SIGABORT
332         if (sigaction(SIGABORT, &sa, NULL) < 0)
333             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABORT)");
334 #endif
335 #ifdef SIGABRT
336         if (sigaction(SIGABRT, &sa, NULL) < 0)
337             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABRT)");
338 #endif
339 #ifdef SIGILL
340         if (sigaction(SIGILL, &sa, NULL) < 0)
341             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGILL)");
342 #endif
343         sa.sa_flags = 0;
344     }
345     sa.sa_handler = sig_term;
346     if (sigaction(SIGTERM, &sa, NULL) < 0)
347         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
348 #ifdef SIGINT
349     if (sigaction(SIGINT, &sa, NULL) < 0)
350         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
351 #endif
352 #ifdef SIGXCPU
353     sa.sa_handler = SIG_DFL;
354     if (sigaction(SIGXCPU, &sa, NULL) < 0)
355         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXCPU)");
356 #endif
357 #ifdef SIGXFSZ
358     sa.sa_handler = SIG_DFL;
359     if (sigaction(SIGXFSZ, &sa, NULL) < 0)
360         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXFSZ)");
361 #endif
362 #ifdef SIGPIPE
363     sa.sa_handler = SIG_IGN;
364     if (sigaction(SIGPIPE, &sa, NULL) < 0)
365         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
366 #endif
367
368     /* we want to ignore HUPs and WINCH while we're busy processing one */
369     sigaddset(&sa.sa_mask, SIGHUP);
370     sigaddset(&sa.sa_mask, SIGWINCH);
371     sa.sa_handler = restart;
372     if (sigaction(SIGHUP, &sa, NULL) < 0)
373         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
374     if (sigaction(SIGWINCH, &sa, NULL) < 0)
375         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGWINCH)");
376 #else
377     if (!one_process) {
378         ap_signal(SIGSEGV, sig_coredump);
379 #ifdef SIGBUS
380         ap_signal(SIGBUS, sig_coredump);
381 #endif /* SIGBUS */
382 #ifdef SIGABORT
383         ap_signal(SIGABORT, sig_coredump);
384 #endif /* SIGABORT */
385 #ifdef SIGABRT
386         ap_signal(SIGABRT, sig_coredump);
387 #endif /* SIGABRT */
388 #ifdef SIGILL
389         ap_signal(SIGILL, sig_coredump);
390 #endif /* SIGILL */
391 #ifdef SIGXCPU
392         ap_signal(SIGXCPU, SIG_DFL);
393 #endif /* SIGXCPU */
394 #ifdef SIGXFSZ
395         ap_signal(SIGXFSZ, SIG_DFL);
396 #endif /* SIGXFSZ */
397     }
398
399     ap_signal(SIGTERM, sig_term);
400 #ifdef SIGHUP
401     ap_signal(SIGHUP, restart);
402 #endif /* SIGHUP */
403 #ifdef SIGWINCH
404     ap_signal(SIGWINCH, restart);
405 #endif /* SIGWINCH */
406 #ifdef SIGPIPE
407     ap_signal(SIGPIPE, SIG_IGN);
408 #endif /* SIGPIPE */
409
410 #endif
411 }
412
413 /*****************************************************************
414  * Here follows a long bunch of generic server bookkeeping stuff...
415  */
416
417 int ap_graceful_stop_signalled(void)
418 {
419     /* XXX - Does this really work? - Manoj */
420     return is_graceful;
421 }
422
423 /*****************************************************************
424  * Child process main loop.
425  */
426
427 static void process_socket(ap_pool_t *p, ap_socket_t *sock, long conn_id)
428 {
429     BUFF *conn_io;
430     conn_rec *current_conn;
431     ap_iol *iol;
432     int csd;
433     ap_status_t rv;
434
435     if ((rv = ap_get_os_sock(&csd, sock)) != APR_SUCCESS) {
436         ap_log_error(APLOG_MARK, APLOG_ERR, rv, NULL, "ap_get_os_sock");
437     }
438
439     if (csd >= FD_SETSIZE) {
440         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, NULL,
441                      "new file descriptor %d is too large; you probably need "
442                      "to rebuild Apache with a larger FD_SETSIZE "
443                      "(currently %d)", 
444                      csd, FD_SETSIZE);
445         ap_close_socket(sock);
446         return;
447     }
448
449     ap_sock_disable_nagle(csd);
450     iol = ap_iol_attach_socket(p, sock);
451     conn_io = ap_bcreate(p, B_RDWR);
452     ap_bpush_iol(conn_io, iol);
453
454     current_conn = ap_new_apr_connection(p, ap_server_conf, conn_io, sock,
455                                          conn_id);
456
457     ap_process_connection(current_conn);
458     ap_lingering_close(current_conn);
459 }
460
461 static void *worker_thread(void *);
462
463 /* Starts a thread as long as we're below max_threads */
464 static int start_thread(void)
465 {
466     pthread_t thread;
467
468     pthread_mutex_lock(&worker_thread_count_mutex);
469     if (worker_thread_count < max_threads) {
470         if (pthread_create(&thread, &worker_thread_attr, worker_thread,
471           &worker_thread_free_ids[worker_thread_count])) {
472             ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
473                          "pthread_create: unable to create worker thread");
474             /* In case system resources are maxxed out, we don't want
475                Apache running away with the CPU trying to fork over and
476                over and over again if we exit. */
477             sleep(10);
478             workers_may_exit = 1;
479             pthread_mutex_unlock(&worker_thread_count_mutex);
480             return 0;
481         }
482         else {
483             worker_thread_count++;
484         }
485     }
486     else {
487         static int reported = 0;
488         
489         if (!reported) {
490             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, ap_server_conf,
491                          "server reached MaxThreadsPerChild setting, consider raising the"
492                          " MaxThreadsPerChild or NumServers settings");
493             reported = 1;
494         }
495         pthread_mutex_unlock(&worker_thread_count_mutex);
496         return 0;
497     }
498     pthread_mutex_unlock(&worker_thread_count_mutex);
499     return 1;
500
501 }
502 /* Sets workers_may_exit if we received a character on the pipe_of_death */
503 static void check_pipe_of_death(void)
504 {
505     pthread_mutex_lock(&pipe_of_death_mutex);
506     if (!workers_may_exit) {
507         int ret;
508         char pipe_read_char;
509         ap_ssize_t n = 1;
510
511         ret = ap_recv(listenfds[0], &pipe_read_char, &n);
512         if (ap_canonical_error(ret) == APR_EAGAIN) {
513             /* It lost the lottery. It must continue to suffer
514              * through a life of servitude. */
515         }
516         else {
517             /* It won the lottery (or something else is very
518              * wrong). Embrace death with open arms. */
519             workers_may_exit = 1;
520         }
521     }
522     pthread_mutex_unlock(&pipe_of_death_mutex);
523 }
524
525 /* idle_thread_count should be incremented before starting a worker_thread */
526
527 static void *worker_thread(void *arg)
528 {
529     ap_socket_t *csd = NULL;
530     ap_pool_t *tpool;           /* Pool for this thread           */
531     ap_pool_t *ptrans;          /* Pool for per-transaction stuff */
532     ap_socket_t *sd = NULL;
533     int srv;
534     int curr_pollfd, last_pollfd = 0;
535     int thread_just_started = 1;
536     int thread_num = *((int *) arg);
537     long conn_id = child_num * HARD_THREAD_LIMIT + thread_num;
538     ap_pollfd_t *pollset;
539     int n;
540     ap_status_t rv;
541
542     pthread_mutex_lock(&thread_pool_parent_mutex);
543     ap_create_pool(&tpool, thread_pool_parent);
544     pthread_mutex_unlock(&thread_pool_parent_mutex);
545     ap_create_pool(&ptrans, tpool);
546
547     ap_setup_poll(&pollset, num_listenfds+1, tpool);
548     for(n=0 ; n <= num_listenfds ; ++n)
549         ap_add_poll_socket(pollset, listenfds[n], APR_POLLIN);
550
551     while (!workers_may_exit) {
552         workers_may_exit |= (max_requests_per_child != 0) && (requests_this_child <= 0);
553         if (workers_may_exit) break;
554         if (!thread_just_started) {
555             pthread_mutex_lock(&idle_thread_count_mutex);
556             if (idle_thread_count < max_spare_threads) {
557                 idle_thread_count++;
558                 pthread_mutex_unlock(&idle_thread_count_mutex);
559             }
560             else {
561                 pthread_mutex_unlock(&idle_thread_count_mutex);
562                 break;
563             }
564         }
565         else {
566             thread_just_started = 0;
567         }
568         pthread_mutex_lock(&thread_accept_mutex);
569         if (workers_may_exit) {
570             pthread_mutex_unlock(&thread_accept_mutex);
571             break;
572         }
573         if ((rv = SAFE_ACCEPT(ap_lock(process_accept_mutex)))
574             != APR_SUCCESS) {
575             ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
576                          "ap_lock failed. Attempting to shutdown "
577                          "process gracefully.");
578             workers_may_exit = 1;
579         }
580
581         while (!workers_may_exit) {
582             ap_int16_t event;
583             srv = ap_poll(pollset, &n, -1);
584
585             if (srv != APR_SUCCESS) {
586                 if (ap_canonical_error(srv) == APR_EINTR) {
587                     continue;
588                 }
589
590                 /* ap_poll() will only return errors in catastrophic
591                  * circumstances. Let's try exiting gracefully, for now. */
592                 ap_log_error(APLOG_MARK, APLOG_ERR, srv, (const server_rec *)
593                              ap_server_conf, "ap_poll: (listen)");
594                 workers_may_exit = 1;
595             }
596             if (workers_may_exit) break;
597
598             ap_get_revents(&event, listenfds[0], pollset);
599             if (event & APR_POLLIN) {
600                 /* A process got a signal on the shutdown pipe. Check if we're
601                  * the lucky process to die. */
602                 check_pipe_of_death();
603                 continue;
604             }
605
606             if (num_listenfds == 1) {
607                 sd = ap_listeners->sd;
608                 goto got_fd;
609             }
610             else {
611                 /* find a listener */
612                 curr_pollfd = last_pollfd;
613                 do {
614                     curr_pollfd++;
615                     if (curr_pollfd > num_listenfds) {
616                         curr_pollfd = 1;
617                     }
618                     /* XXX: Should we check for POLLERR? */
619                     ap_get_revents(&event, listenfds[curr_pollfd], pollset);
620                     if (event & APR_POLLIN) {
621                         last_pollfd = curr_pollfd;
622                         sd = listenfds[curr_pollfd];
623                         goto got_fd;
624                     }
625                 } while (curr_pollfd != last_pollfd);
626             }
627         }
628     got_fd:
629         if (!workers_may_exit) {
630             if ((rv = ap_accept(&csd, sd, ptrans)) != APR_SUCCESS) {
631                 ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, "ap_accept");
632             }
633             if ((rv = SAFE_ACCEPT(ap_unlock(process_accept_mutex)))
634                 != APR_SUCCESS) {
635                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
636                              "ap_unlock failed. Attempting to shutdown "
637                              "process gracefully.");
638                 workers_may_exit = 1;
639             }
640             pthread_mutex_unlock(&thread_accept_mutex);
641             pthread_mutex_lock(&idle_thread_count_mutex);
642             if (idle_thread_count > min_spare_threads) {
643                 idle_thread_count--;
644             }
645             else {
646                 if (!start_thread()) {
647                     idle_thread_count--;
648                 }
649             }
650             pthread_mutex_unlock(&idle_thread_count_mutex);
651             process_socket(ptrans, csd, conn_id);
652             requests_this_child--;
653         } else {
654             if ((rv = SAFE_ACCEPT(ap_unlock(process_accept_mutex)))
655                 != APR_SUCCESS) {
656                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
657                              "ap_unlock failed. Attempting to shutdown "
658                              "process gracefully.");
659                 workers_may_exit = 1;
660             }
661             pthread_mutex_unlock(&thread_accept_mutex);
662             pthread_mutex_lock(&idle_thread_count_mutex);
663             idle_thread_count--;
664             pthread_mutex_unlock(&idle_thread_count_mutex);
665             break;
666         }
667         ap_clear_pool(ptrans);
668     }
669
670     pthread_mutex_lock(&thread_pool_parent_mutex);
671     ap_destroy_pool(tpool);
672     pthread_mutex_unlock(&thread_pool_parent_mutex);
673     pthread_mutex_lock(&worker_thread_count_mutex);
674     worker_thread_count--;
675     worker_thread_free_ids[worker_thread_count] = thread_num;
676     if (worker_thread_count == 0) {
677         /* All the threads have exited, now finish the shutdown process
678          * by signalling the sigwait thread */
679         kill(my_pid, SIGTERM);
680     }
681     pthread_mutex_unlock(&worker_thread_count_mutex);
682
683     return NULL;
684 }
685
686 /* Set group privileges.
687  *
688  * Note that we use the username as set in the config files, rather than
689  * the lookup of to uid --- the same uid may have multiple passwd entries,
690  * with different sets of groups for each.
691  */
692
693 static int set_group_privs(uid_t uid, gid_t gid)
694 {
695     if (!geteuid()) {
696         const char *name;
697
698         /* Get username if passed as a uid */
699
700         struct passwd *ent;
701
702         if ((ent = getpwuid(uid)) == NULL) {
703             ap_log_error(APLOG_MARK, APLOG_ALERT, errno, NULL,
704                      "getpwuid: couldn't determine user name from uid %u, "
705                      "you probably need to modify the User directive",
706                      (unsigned)uid);
707             return -1;
708         }
709
710         name = ent->pw_name;
711
712         /*
713          * Set the GID before initgroups(), since on some platforms
714          * setgid() is known to zap the group list.
715          */
716         if (setgid(gid) == -1) {
717             ap_log_error(APLOG_MARK, APLOG_ALERT, errno, NULL,
718                         "setgid: unable to set group id to Group %u",
719                         (unsigned)gid);
720             return -1;
721         }
722
723         /* Reset `groups' attributes. */
724
725         if (initgroups(name, gid) == -1) {
726             ap_log_error(APLOG_MARK, APLOG_ALERT, errno, NULL,
727                         "initgroups: unable to set groups for User %s "
728                         "and Group %u", name, (unsigned)gid);
729             return -1;
730         }
731     }
732     return 0;
733 }
734
735
736 static int perchild_setup_child(int childnum)
737 {
738     child_info_t *ug = &child_info_table[childnum];
739
740     if (ug->uid == -1 && ug->gid == -1) {
741         return unixd_setup_child();
742     }
743     if (set_group_privs(ug->uid, ug->gid)) {
744         return -1;
745     }
746     /* Only try to switch if we're running as root */
747     if (!geteuid() && (
748 #ifdef _OSD_POSIX
749         os_init_job_environment(server_conf, unixd_config.user_name, one_process) != 0 ||
750 #endif
751         setuid(ug->uid) == -1)) {
752         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, NULL,
753                     "setuid: unable to change to uid: %ld",
754                     (long) ug->uid);
755         return -1;
756     }
757     return 0;
758 }
759
760 static int create_child_socket(int child_num, ap_pool_t *p)
761 {
762     struct sockaddr_un unix_addr;
763     mode_t omask;
764     int rc;
765     int sd;
766     perchild_server_conf *sconf = (perchild_server_conf *)
767               ap_get_module_config(ap_server_conf->module_config, &mpm_perchild_module);
768     char *socket_name = ap_palloc(p, strlen(sconf->sockname) + 6);
769
770     ap_snprintf(socket_name, strlen(socket_name), "%s.%d", sconf->sockname, child_num);
771     if (unlink(socket_name) < 0 &&
772         errno != ENOENT) {
773         ap_log_error(APLOG_MARK, APLOG_ERR, errno, ap_server_conf,
774                      "Couldn't unlink unix domain socket %s",
775                      socket_name);
776         /* Just a warning; don't bail out */
777     }
778
779     if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
780         ap_log_error(APLOG_MARK, APLOG_ERR, errno, ap_server_conf,
781                      "Couldn't create unix domain socket");
782         return -1;
783     }
784
785     memset(&unix_addr, 0, sizeof(unix_addr));
786     unix_addr.sun_family = AF_UNIX;
787     strcpy(unix_addr.sun_path, socket_name);
788
789     omask = umask(0077); /* so that only Apache can use socket */
790     rc = bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
791     umask(omask); /* can't fail, so can't clobber errno */
792     if (rc < 0) {
793         ap_log_error(APLOG_MARK, APLOG_ERR, errno, ap_server_conf,
794                      "Couldn't bind unix domain socket %s",
795                      socket_name);
796         return -1;
797     }
798
799     if (listen(sd, DEFAULT_PERCHILD_LISTENBACKLOG) < 0) {
800         ap_log_error(APLOG_MARK, APLOG_ERR, errno, ap_server_conf,
801                      "Couldn't listen on unix domain socket");
802         return -1;
803     }
804
805     if (!geteuid()) {
806         if (chown(socket_name, unixd_config.user_id, -1) < 0) {
807             ap_log_error(APLOG_MARK, APLOG_ERR, errno, ap_server_conf,
808                          "Couldn't change owner of unix domain socket %s",
809                          socket_name);
810             return -1;
811         }
812     }
813     return sd;
814 }
815
816 static void child_main(int child_num_arg)
817 {
818     sigset_t sig_mask;
819     int signal_received;
820     int i;
821     ap_listen_rec *lr;
822     ap_status_t rv;
823     int sd;
824
825     my_pid = getpid();
826     child_num = child_num_arg;
827     ap_create_pool(&pchild, pconf);
828
829     /*stuff to do before we switch id's, so we have permissions.*/
830
831     rv = SAFE_ACCEPT(ap_child_init_lock(&process_accept_mutex, lock_fname,
832                                         pchild));
833     if (rv != APR_SUCCESS) {
834         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
835                      "Couldn't initialize cross-process lock in child");
836         clean_child_exit(APEXIT_CHILDFATAL);
837     }
838
839     /* Add the sockets for this child process's virtual hosts */
840     sd = create_child_socket(child_num, pchild);
841
842     if (perchild_setup_child(child_num)) {
843         clean_child_exit(APEXIT_CHILDFATAL);
844     }
845
846     ap_child_init_hook(pchild, ap_server_conf);
847
848     /*done with init critical section */
849
850     /* All threads should mask signals out, accoring to sigwait(2) man page */
851     sigfillset(&sig_mask);
852
853 #ifdef SIGPROCMASK_SETS_THREAD_MASK
854     if (sigprocmask(SIG_SETMASK, &sig_mask, NULL) != 0) {
855         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf, "sigprocmask");
856     }
857 #else
858     if (pthread_sigmask(SIG_SETMASK, &sig_mask, NULL) != 0) {
859         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
860                      "pthread_sigmask");
861     }
862 #endif
863
864     requests_this_child = max_requests_per_child;
865     
866     /* Set up the pollfd array, num_listenfds + 1 for the pipe and 1 for
867      * the child socket.
868      */
869     listenfds = ap_pcalloc(pchild, sizeof(*listenfds) * (num_listenfds + 2));
870 #if APR_FILES_AS_SOCKETS
871     ap_socket_from_file(&listenfds[0], pipe_of_death_in);
872 #endif
873     for (lr = ap_listeners, i = 1; i <= num_listenfds; lr = lr->next, ++i)
874         listenfds[i]=lr->sd;
875
876     /* Setup worker threads */
877
878     if (threads_to_start > max_threads) {
879         threads_to_start = max_threads;
880     }
881     idle_thread_count = threads_to_start;
882     worker_thread_count = 0;
883     for (i = 0; i < max_threads; i++) {
884         worker_thread_free_ids[i] = i;
885     }
886     ap_create_pool(&thread_pool_parent, pchild);
887     pthread_mutex_init(&thread_pool_parent_mutex, NULL);
888     pthread_mutex_init(&idle_thread_count_mutex, NULL);
889     pthread_mutex_init(&worker_thread_count_mutex, NULL);
890     pthread_mutex_init(&pipe_of_death_mutex, NULL);
891     pthread_attr_init(&worker_thread_attr);
892 #ifdef PTHREAD_ATTR_SETDETACHSTATE_ARG2_ADDR
893     {
894         int on = 1;
895
896         pthread_attr_setdetachstate(&worker_thread_attr, &on);
897     }
898 #else
899     pthread_attr_setdetachstate(&worker_thread_attr, PTHREAD_CREATE_DETACHED);
900 #endif
901
902     /* We are creating worker threads right now */
903     for (i=0; i < threads_to_start; i++) {
904         /* start_thread shouldn't fail here */
905         if (!start_thread()) {
906             break;
907         }
908     }
909
910     /* This thread will be the one responsible for handling signals */
911     sigemptyset(&sig_mask);
912     sigaddset(&sig_mask, SIGTERM);
913     sigaddset(&sig_mask, SIGINT);
914     ap_sigwait(&sig_mask, &signal_received);
915     switch (signal_received) {
916         case SIGTERM:
917         case SIGINT:
918             just_die(signal_received);
919             break;
920         default:
921             ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
922             "received impossible signal: %d", signal_received);
923             just_die(SIGTERM);
924     }
925 }
926
927 static int make_child(server_rec *s, int slot, time_t now)
928 {
929     int pid;
930
931     if (slot + 1 > ap_max_daemons_limit) {
932         ap_max_daemons_limit = slot + 1;
933     }
934
935     if (one_process) {
936         set_signals();
937         ap_child_table[slot].pid = getpid();
938         ap_child_table[slot].status = SERVER_ALIVE;
939         child_main(slot);
940     }
941
942     if ((pid = fork()) == -1) {
943         ap_log_error(APLOG_MARK, APLOG_ERR, errno, s,
944                      "fork: Unable to fork new process");
945         /* In case system resources are maxxed out, we don't want
946            Apache running away with the CPU trying to fork over and
947            over and over again. */
948         sleep(10);
949
950         return -1;
951     }
952
953     if (!pid) {
954 #ifdef AIX_BIND_PROCESSOR
955       /* By default, AIX binds to a single processor.  This bit unbinds
956          children which will then bind to another CPU.
957       */
958 #include <sys/processor.h>
959         int status = bindprocessor(BINDPROCESS, (int)getpid(),
960                                PROCESSOR_CLASS_ANY);
961         if (status != OK)
962             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, errno, 
963                          ap_server_conf, "processor unbind failed %d", status);
964 #endif
965
966         RAISE_SIGSTOP(MAKE_CHILD);
967
968         /* XXX - For an unthreaded server, a signal handler will be necessary
969         ap_signal(SIGTERM, just_die);
970         */
971         child_main(slot);
972
973         return 0;
974     }
975     /* else */
976     ap_child_table[slot].pid = pid;
977     ap_child_table[slot].status = SERVER_ALIVE;
978
979     return 0;
980 }
981
982 /* start up a bunch of children */
983 static int startup_children(int number_to_start)
984 {
985     int i;
986
987     for (i = 0; number_to_start && i < num_daemons; ++i) {
988         if (ap_child_table[i].status != SERVER_DEAD) {
989             continue;
990         }
991         if (make_child(ap_server_conf, i, 0) < 0) {
992             break;
993         }
994         --number_to_start;
995     }
996     return number_to_start;
997 }
998
999
1000 /*
1001  * spawn_rate is the number of children that will be spawned on the
1002  * next maintenance cycle if there aren't enough servers.  It is
1003  * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
1004  * without the need to spawn.
1005  */
1006 static int spawn_rate = 1;
1007 #ifndef MAX_SPAWN_RATE
1008 #define MAX_SPAWN_RATE  (32)
1009 #endif
1010 static int hold_off_on_exponential_spawning;
1011
1012 static void perform_child_maintenance(void)
1013 {
1014     int i;
1015     time_t now = 0;
1016     int free_length;
1017     int free_slots[MAX_SPAWN_RATE];
1018     int last_non_dead = -1;
1019
1020     /* initialize the free_list */
1021     free_length = 0;
1022     
1023     for (i = 0; i < num_daemons; ++i) {
1024         if (ap_child_table[i].status == SERVER_DEAD) {
1025             if (free_length < spawn_rate) {
1026                 free_slots[free_length] = i;
1027                 ++free_length;
1028             }
1029         }
1030         else {
1031             last_non_dead = i;
1032         }
1033
1034         if (i >= ap_max_daemons_limit && free_length >= spawn_rate) {
1035             break;
1036         }
1037     }
1038     ap_max_daemons_limit = last_non_dead + 1;
1039
1040     if (free_length > 0) {
1041         for (i = 0; i < free_length; ++i) {
1042             make_child(ap_server_conf, free_slots[i], now);
1043         }
1044         /* the next time around we want to spawn twice as many if this
1045          * wasn't good enough, but not if we've just done a graceful
1046          */
1047         if (hold_off_on_exponential_spawning) {
1048             --hold_off_on_exponential_spawning;
1049         }
1050         else if (spawn_rate < MAX_SPAWN_RATE) {
1051             spawn_rate *= 2;
1052         }
1053     }
1054     else {
1055         spawn_rate = 1;
1056     }
1057 }
1058
1059 static void server_main_loop(int remaining_children_to_start)
1060 {
1061     int child_slot;
1062     ap_wait_t status;
1063     ap_proc_t pid;
1064     int i;
1065
1066     while (!restart_pending && !shutdown_pending) {
1067         ap_wait_or_timeout(&status, &pid, pconf);
1068         
1069         if (pid.pid != -1) {
1070             ap_process_child_status(&pid, status);
1071             /* non-fatal death... note that it's gone in the child table and
1072              * clean out the status table. */
1073             child_slot = -1;
1074             for (i = 0; i < ap_max_daemons_limit; ++i) {
1075                 if (ap_child_table[i].pid == pid.pid) {
1076                     int j;
1077
1078                     child_slot = i;
1079                     for (j = 0; j < HARD_THREAD_LIMIT; j++) {
1080                         ap_perchild_force_reset_connection_status(i * HARD_THREAD_LIMIT + j);
1081                     }
1082                     break;
1083                 }
1084             }
1085             if (child_slot >= 0) {
1086                 ap_child_table[child_slot].status = SERVER_DEAD;
1087                 
1088                 if (remaining_children_to_start
1089                     && child_slot < num_daemons) {
1090                     /* we're still doing a 1-for-1 replacement of dead
1091                      * children with new children
1092                      */
1093                     make_child(ap_server_conf, child_slot, time(NULL));
1094                     --remaining_children_to_start;
1095                 }
1096 #if APR_HAS_OTHER_CHILD
1097             }
1098             else if (ap_reap_other_child(&pid, status) == 0) {
1099                 /* handled */
1100 #endif
1101             }
1102             else if (is_graceful) {
1103                 /* Great, we've probably just lost a slot in the
1104                  * child table.  Somehow we don't know about this
1105                  * child.
1106                  */
1107                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, 
1108                              ap_server_conf,
1109                             "long lost child came home! (pid %ld)", 
1110                              (long)pid.pid);
1111             }
1112             /* Don't perform idle maintenance when a child dies,
1113              * only do it when there's a timeout.  Remember only a
1114              * finite number of children can die, and it's pretty
1115              * pathological for a lot to die suddenly.
1116              */
1117             continue;
1118         }
1119         else if (remaining_children_to_start) {
1120             /* we hit a 1 second timeout in which none of the previous
1121              * generation of children needed to be reaped... so assume
1122              * they're all done, and pick up the slack if any is left.
1123              */
1124             remaining_children_to_start = \
1125                 startup_children(remaining_children_to_start);
1126             /* In any event we really shouldn't do the code below because
1127              * few of the servers we just started are in the IDLE state
1128              * yet, so we'd mistakenly create an extra server.
1129              */
1130             continue;
1131         }
1132
1133         perform_child_maintenance();
1134     }
1135 }
1136
1137 int ap_mpm_run(ap_pool_t *_pconf, ap_pool_t *plog, server_rec *s)
1138 {
1139     int remaining_children_to_start;
1140     int i;
1141     ap_status_t rv;
1142     ap_ssize_t one = 1;
1143
1144     pconf = _pconf;
1145     ap_server_conf = s;
1146     if ((rv = ap_create_pipe(&pipe_of_death_in, &pipe_of_death_out, pconf)) 
1147         != APR_SUCCESS) {
1148         ap_log_error(APLOG_MARK, APLOG_ERR, rv,
1149                      (const server_rec*) ap_server_conf,
1150                      "ap_create_pipe (pipe_of_death)");
1151         exit(1);
1152     }
1153     if ((rv = ap_set_pipe_timeout(pipe_of_death_in, 0)) != APR_SUCCESS) {
1154         ap_log_error(APLOG_MARK, APLOG_ERR, rv,
1155                      (const server_rec*) ap_server_conf,
1156                      "ap_set_pipe_timeout (pipe_of_death)");
1157         exit(1);
1158     }
1159     ap_server_conf = s;
1160     if ((num_listenfds = ap_setup_listeners(ap_server_conf)) < 1) {
1161         /* XXX: hey, what's the right way for the mpm to indicate a fatal error? */
1162         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT, 0, s,
1163             "no listening sockets available, shutting down");
1164         return 1;
1165     }
1166     ap_log_pid(pconf, ap_pid_fname);
1167
1168     /* Initialize cross-process accept lock */
1169     lock_fname = ap_psprintf(_pconf, "%s.%u",
1170                              ap_server_root_relative(_pconf, lock_fname),
1171                              my_pid);
1172     rv = SAFE_ACCEPT(ap_create_lock(&process_accept_mutex, APR_MUTEX,
1173                                     APR_CROSS_PROCESS, lock_fname, _pconf));
1174     if (rv != APR_SUCCESS) {
1175         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
1176                      "Couldn't create cross-process lock");
1177         return 1;
1178     }
1179
1180     if (!is_graceful) {
1181         reinit_scoreboard(pconf);
1182     }
1183     /* Initialize the child table */
1184     if (!is_graceful) {
1185         for (i = 0; i < HARD_SERVER_LIMIT; i++) {
1186             ap_child_table[i].status = SERVER_DEAD;
1187         }
1188     }
1189
1190     set_signals();
1191
1192     /* If we're doing a graceful_restart then we're going to see a lot
1193      * of children exiting immediately when we get into the main loop
1194      * below (because we just sent them SIGWINCH).  This happens pretty
1195      * rapidly... and for each one that exits we'll start a new one until
1196      * we reach at least daemons_min_free.  But we may be permitted to
1197      * start more than that, so we'll just keep track of how many we're
1198      * supposed to start up without the 1 second penalty between each fork.
1199      */
1200     remaining_children_to_start = num_daemons;
1201     if (!is_graceful) {
1202         remaining_children_to_start = \
1203             startup_children(remaining_children_to_start);
1204     }
1205     else {
1206         /* give the system some time to recover before kicking into
1207             * exponential mode */
1208         hold_off_on_exponential_spawning = 10;
1209     }
1210
1211     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1212                 "%s configured -- resuming normal operations",
1213                 ap_get_server_version());
1214     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
1215                 "Server built: %s", ap_get_server_built());
1216     restart_pending = shutdown_pending = 0;
1217
1218     server_main_loop(remaining_children_to_start);
1219
1220     if (shutdown_pending) {
1221         /* Time to gracefully shut down:
1222          * Kill child processes, tell them to call child_exit, etc...
1223          */
1224         if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1225             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf,
1226                          "killpg SIGTERM");
1227         }
1228         ap_reclaim_child_processes(1);          /* Start with SIGTERM */
1229     
1230         /* cleanup pid file on normal shutdown */
1231         {
1232             const char *pidfile = NULL;
1233             pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1234             if ( pidfile != NULL && unlink(pidfile) == 0)
1235                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0,
1236                          ap_server_conf,
1237                          "removed PID file %s (pid=%ld)",
1238                          pidfile, (long)getpid());
1239         }
1240     
1241         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0,
1242                      ap_server_conf, "caught SIGTERM, shutting down");
1243     
1244         return 1;
1245     }
1246
1247     /* we've been told to restart */
1248     ap_signal(SIGHUP, SIG_IGN);
1249
1250     if (one_process) {
1251         /* not worth thinking about */
1252         return 1;
1253     }
1254
1255     if (is_graceful) {
1256         char char_of_death = '!';
1257
1258         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1259                     "SIGWINCH received.  Doing graceful restart");
1260
1261         /* This is mostly for debugging... so that we know what is still
1262          * gracefully dealing with existing request.
1263          */
1264         
1265         for (i = 0; i < num_daemons; ++i) {
1266             if (ap_child_table[i].status != SERVER_DEAD) {
1267                 ap_child_table[i].status = SERVER_DYING;
1268             } 
1269         }
1270         /* give the children the signal to die */
1271         for (i = 0; i < num_daemons;) {
1272             if ((rv = ap_write(pipe_of_death_out, &char_of_death, &one)) != APR_SUCCESS) {
1273                 if (ap_canonical_error(rv) == APR_EINTR) continue;
1274                 ap_log_error(APLOG_MARK, APLOG_WARNING, rv, ap_server_conf,
1275                              "write pipe_of_death");
1276             }
1277             i++;
1278         }
1279     }
1280     else {
1281       /* Kill 'em all.  Since the child acts the same on the parents SIGTERM 
1282        * and a SIGHUP, we may as well use the same signal, because some user
1283        * pthreads are stealing signals from us left and right.
1284        */
1285         if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1286             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf,
1287                          "killpg SIGTERM");
1288         }
1289         ap_reclaim_child_processes(1);          /* Start with SIGTERM */
1290         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0,
1291                      ap_server_conf, "SIGHUP received.  Attempting to restart");
1292     }
1293     return 0;
1294 }
1295
1296 static void perchild_pre_config(ap_pool_t *p, ap_pool_t *plog, ap_pool_t *ptemp)
1297 {
1298     static int restart_num = 0;
1299     int i;
1300
1301     one_process = !!getenv("ONE_PROCESS");
1302
1303     /* sigh, want this only the second time around */
1304     if (restart_num++ == 1) {
1305         is_graceful = 0;
1306
1307         if (!one_process) {
1308             ap_detach();
1309         }
1310
1311         my_pid = getpid();
1312     }
1313
1314     unixd_pre_config();
1315     ap_listen_pre_config();
1316     num_daemons = DEFAULT_NUM_DAEMON;
1317     threads_to_start = DEFAULT_START_THREAD;
1318     min_spare_threads = DEFAULT_MIN_SPARE_THREAD;
1319     max_spare_threads = DEFAULT_MAX_SPARE_THREAD;
1320     max_threads = HARD_THREAD_LIMIT;
1321     ap_pid_fname = DEFAULT_PIDLOG;
1322     ap_scoreboard_fname = DEFAULT_SCOREBOARD;
1323     lock_fname = DEFAULT_LOCKFILE;
1324     max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1325     ap_perchild_set_maintain_connection_status(1);
1326     socket_info_table = ap_make_hash(p);
1327
1328     ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1329
1330     for (i = 0; i < HARD_SERVER_LIMIT; i++) {
1331         child_info_table[i].uid = -1;
1332         child_info_table[i].gid = -1;
1333     }
1334 }
1335
1336 static int perchild_post_read(request_rec *r)
1337 {
1338     const char *hostname = ap_table_get(r->headers_in, "Host");
1339     char *process_num;
1340     int num;
1341
1342     process_num = ap_hash_get(socket_info_table, hostname, 0);
1343     num = atoi(process_num);
1344
1345     if (num != child_num) {
1346         /* package the request and send it to another child */
1347         return DECLINED;
1348     }
1349     return OK;
1350 }
1351
1352 static void perchild_hooks(void)
1353 {
1354     INIT_SIGLIST()
1355     one_process = 0;
1356
1357     ap_hook_pre_config(perchild_pre_config, NULL, NULL, AP_HOOK_MIDDLE); 
1358     /* This must be run absolutely first.  If this request isn't for this
1359      * server then we need to forward it to the proper child.  No sense
1360      * tying up this server running more post_read request hooks if it is
1361      * just going to be forwarded along.
1362      */
1363     ap_hook_post_read_request(perchild_post_read, NULL, NULL, AP_HOOK_REALLY_FIRST);
1364 }
1365
1366 static const char *set_pidfile(cmd_parms *cmd, void *dummy, const char *arg) 
1367 {
1368     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1369     if (err != NULL) {
1370         return err;
1371     }
1372
1373     if (cmd->server->is_virtual) {
1374         return "PidFile directive not allowed in <VirtualHost>";
1375     }
1376     ap_pid_fname = arg;
1377     return NULL;
1378 }
1379
1380 static const char *set_scoreboard(cmd_parms *cmd, void *dummy, const char *arg)
1381 {
1382     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1383     if (err != NULL) {
1384         return err;
1385     }
1386
1387     ap_scoreboard_fname = arg;
1388     return NULL;
1389 }
1390
1391 static const char *set_lockfile(cmd_parms *cmd, void *dummy, const char *arg) 
1392 {
1393     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1394     if (err != NULL) {
1395         return err;
1396     }
1397
1398     lock_fname = arg;
1399     return NULL;
1400 }
1401 static const char *set_num_daemons (cmd_parms *cmd, void *dummy, const char *arg) 
1402 {
1403     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1404     if (err != NULL) {
1405         return err;
1406     }
1407
1408     num_daemons = atoi(arg);
1409     if (num_daemons > HARD_SERVER_LIMIT) {
1410        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1411                     "WARNING: NumServers of %d exceeds compile time limit "
1412                     "of %d servers,", num_daemons, HARD_SERVER_LIMIT);
1413        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1414                     " lowering NumServers to %d.  To increase, please "
1415                     "see the", HARD_SERVER_LIMIT);
1416        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1417                     " HARD_SERVER_LIMIT define in %s.",
1418                     AP_MPM_HARD_LIMITS_FILE);
1419        num_daemons = HARD_SERVER_LIMIT;
1420     } 
1421     else if (num_daemons < 1) {
1422         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1423                      "WARNING: Require NumServers > 0, setting to 1");
1424         num_daemons = 1;
1425     }
1426     return NULL;
1427 }
1428
1429 static const char *set_threads_to_start (cmd_parms *cmd, void *dummy, const char *arg) 
1430 {
1431     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1432     if (err != NULL) {
1433         return err;
1434     }
1435
1436     threads_to_start = atoi(arg);
1437     if (threads_to_start > HARD_THREAD_LIMIT) {
1438         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1439                      "WARNING: StartThreads of %d exceeds compile time"
1440                      " limit of %d threads,", threads_to_start,
1441                      HARD_THREAD_LIMIT);
1442         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1443                      " lowering StartThreads to %d. To increase, please"
1444                      " see the", HARD_THREAD_LIMIT);
1445         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1446                      " HARD_THREAD_LIMIT define in %s.",
1447                      AP_MPM_HARD_LIMITS_FILE);
1448     }
1449     else if (threads_to_start < 1) {
1450         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1451                      "WARNING: Require StartThreads > 0, setting to 1");
1452         threads_to_start = 1;
1453     }
1454     return NULL;
1455 }
1456
1457 static const char *set_min_spare_threads(cmd_parms *cmd, void *dummy, const char *arg)
1458 {
1459     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1460     if (err != NULL) {
1461         return err;
1462     }
1463
1464     min_spare_threads = atoi(arg);
1465     if (min_spare_threads <= 0) {
1466        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1467                     "WARNING: detected MinSpareThreads set to non-positive.");
1468        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1469                     "Resetting to 1 to avoid almost certain Apache failure.");
1470        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1471                     "Please read the documentation.");
1472        min_spare_threads = 1;
1473     }
1474        
1475     return NULL;
1476 }
1477
1478 static const char *set_max_spare_threads(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     max_spare_threads = atoi(arg);
1486     if (max_spare_threads >= HARD_THREAD_LIMIT) {
1487        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1488                     "WARNING: detected MinSpareThreads set higher than");
1489        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1490                     "HARD_THREAD_LIMIT. Resetting to %d", HARD_THREAD_LIMIT);
1491        max_spare_threads = HARD_THREAD_LIMIT;
1492     }
1493     return NULL;
1494 }
1495
1496 static const char *set_max_threads(cmd_parms *cmd, void *dummy, const char *arg)
1497 {
1498     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1499     if (err != NULL) {
1500         return err;
1501     }
1502
1503     max_threads = atoi(arg);
1504     if (max_threads > HARD_THREAD_LIMIT) {
1505        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1506                     "WARNING: detected MaxThreadsPerChild set higher than");
1507        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1508                     "HARD_THREAD_LIMIT. Resetting to %d", HARD_THREAD_LIMIT);
1509        max_threads = HARD_THREAD_LIMIT;
1510     }
1511     return NULL;
1512 }
1513
1514 static const char *set_max_requests(cmd_parms *cmd, void *dummy, const char *arg) 
1515 {
1516     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1517     if (err != NULL) {
1518         return err;
1519     }
1520
1521     max_requests_per_child = atoi(arg);
1522
1523     return NULL;
1524 }
1525
1526 static const char *set_maintain_connection_status(cmd_parms *cmd,
1527                                                   void *dummy, int arg) 
1528 {
1529     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1530     if (err != NULL) {
1531         return err;
1532     }
1533
1534     ap_perchild_set_maintain_connection_status(arg != 0);
1535     return NULL;
1536 }
1537
1538 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, const char *arg) 
1539 {
1540     ap_finfo_t finfo;
1541     const char *fname;
1542     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1543     if (err != NULL) {
1544         return err;
1545     }
1546
1547     fname = ap_server_root_relative(cmd->pool, arg);
1548     if ((ap_stat(&finfo, fname, cmd->pool) != APR_SUCCESS) || 
1549         (finfo.filetype != APR_DIR)) {
1550         return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname, 
1551                           " does not exist or is not a directory", NULL);
1552     }
1553     ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1554     return NULL;
1555 }
1556
1557 static const char *set_childprocess(cmd_parms *cmd, void *dummy, const char *p,
1558                                     const char *u, const char *g) 
1559 {
1560     int curr_child_num = atoi(p);
1561     child_info_t *ug = &child_info_table[curr_child_num - 1];
1562
1563     if (curr_child_num > num_daemons) {
1564         return "Trying to use more child ID's than NumServers.  Increase "
1565                "NumServers in your config file.";
1566     }
1567    
1568     ug->uid = atoi(u);
1569     ug->gid = atoi(g); 
1570
1571     return NULL;
1572 }
1573
1574 static const char *set_socket_name(cmd_parms *cmd, void *dummy, const char *arg)
1575 {
1576     server_rec *s = cmd->server;
1577     perchild_server_conf *conf = (perchild_server_conf *) 
1578                   ap_get_module_config(s->module_config, &mpm_perchild_module);
1579
1580     conf->sockname = ap_server_root_relative(cmd->pool, arg);
1581     return NULL;
1582 }
1583     
1584 static const char *assign_childprocess(cmd_parms *cmd, void *dummy, const char *p)
1585 {
1586     ap_hash_set(socket_info_table, cmd->server->server_hostname, 0, p);
1587     return NULL;
1588 }
1589
1590
1591 static const command_rec perchild_cmds[] = {
1592 UNIX_DAEMON_COMMANDS
1593 LISTEN_COMMANDS
1594 AP_INIT_TAKE1("PidFile", set_pidfile, NULL, RSRC_CONF,
1595               "A file for logging the server process ID"),
1596 AP_INIT_TAKE1("ScoreBoardFile", set_scoreboard, NULL, RSRC_CONF,
1597               "A file for Apache to maintain runtime process management information"),
1598 AP_INIT_TAKE1("LockFile", set_lockfile, NULL, RSRC_CONF,
1599               "The lockfile used when Apache needs to lock the accept() call"),
1600 AP_INIT_TAKE1("NumServers", set_num_daemons, NULL, RSRC_CONF,
1601               "Number of children alive at the same time"),
1602 AP_INIT_TAKE1("StartThreads", set_threads_to_start, NULL, RSRC_CONF,
1603               "Number of threads each child creates"),
1604 AP_INIT_TAKE1("MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF,
1605               "Minimum number of idle threads per child, to handle request spikes"),
1606 AP_INIT_TAKE1("MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF,
1607               "Maximum number of idle threads per child"),
1608 AP_INIT_TAKE1("MaxThreadsPerChild", set_max_threads, NULL, RSRC_CONF,
1609               "Maximum number of threads per child"),
1610 AP_INIT_TAKE1("MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF,
1611               "Maximum number of requests a particular child serves before dying."),
1612 AP_INIT_FLAG("ConnectionStatus", set_maintain_connection_status, NULL, RSRC_CONF,
1613              "Whether or not to maintain status information on current connections"),
1614 AP_INIT_TAKE1("CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF,
1615               "The location of the directory Apache changes to before dumping core"),
1616 AP_INIT_TAKE3("ChildProcess", set_childprocess, NULL, RSRC_CONF,
1617               "Specify a User and Group for a specific child process."),
1618 AP_INIT_TAKE1("AssignChild", assign_childprocess, NULL, RSRC_CONF,
1619               "Tie a virtual host to a specific child process."),
1620 AP_INIT_TAKE1("ChildSockName", set_socket_name, NULL, RSRC_CONF,
1621               "the base name of the socket to use for communication between "
1622               "child processes.  The actual socket will be "
1623               "basename.childnum"),
1624 { NULL }
1625 };
1626
1627 static void *perchild_create_config(ap_pool_t *p, server_rec *s)
1628 {
1629     perchild_server_conf *c =
1630     (perchild_server_conf *) ap_pcalloc(p, sizeof(perchild_server_conf));
1631
1632     c->sockname = ap_server_root_relative(p, DEFAULT_PERCHILD_SOCKET);
1633     return c;
1634 }
1635
1636 module MODULE_VAR_EXPORT mpm_perchild_module = {
1637     MPM20_MODULE_STUFF,
1638     NULL,                       /* hook to run before apache parses args */
1639     NULL,                       /* create per-directory config structure */
1640     NULL,                       /* merge per-directory config structures */
1641     perchild_create_config,     /* create per-server config structure */
1642     NULL,                       /* merge per-server config structures */
1643     perchild_cmds,              /* command ap_table_t */
1644     NULL,                       /* handlers */
1645     perchild_hooks              /* register_hooks */
1646 };
1647