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