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