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