1 /* ====================================================================
2 * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in
13 * the documentation and/or other materials provided with the
16 * 3. All advertising materials mentioning features or use of this
17 * software must display the following acknowledgment:
18 * "This product includes software developed by the Apache Group
19 * for use in the Apache HTTP server project (http://www.apache.org/)."
21 * 4. The names "Apache Server" and "Apache Group" must not be used to
22 * endorse or promote products derived from this software without
23 * prior written permission. For written permission, please contact
26 * 5. Products derived from this software may not be called "Apache"
27 * nor may "Apache" appear in their names without prior written
28 * permission of the Apache Group.
30 * 6. Redistributions of any form whatsoever must retain the following
32 * "This product includes software developed by the Apache Group
33 * for use in the Apache HTTP server project (http://www.apache.org/)."
35 * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
36 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46 * OF THE POSSIBILITY OF SUCH DAMAGE.
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Group and was originally based
51 * on public domain software written at the National Center for
52 * Supercomputing Applications, University of Illinois, Urbana-Champaign.
53 * For more information on the Apache Group and the Apache HTTP server
54 * project, please see <http://www.apache.org/>.
59 * httpd.c: simple http daemon for answering WWW file requests
62 * 03-21-93 Rob McCool wrote original code (up to NCSA HTTPd 1.3)
65 * changed server number for child-alone processes to 0 and changed name
69 * Added numerous speed hacks proposed by Robert S. Thau (rst@ai.mit.edu)
70 * including set group before fork, and call gettime before to fork
71 * to set up libraries.
74 * Brandon's code snarfed from NCSA 1.4, but tinkered to work with the
75 * Apache server, and also to have child processes do accept() directly.
78 * Extensive rework for Apache.
81 /* TODO: this is a cobbled together prefork MPM example... it should mostly
82 * TODO: behave like apache-1.3... here's a short list of things I think
83 * TODO: need cleaning up still:
84 * TODO: - use ralf's mm stuff for the shared mem and mutexes
85 * TODO: - clean up scoreboard stuff when we figure out how to do it in 2.0
91 #include "http_main.h"
93 #include "http_config.h"
94 #include "http_core.h" /* for get_remote_host */
95 #include "http_connection.h"
96 #include "scoreboard_prefork.h"
99 #include "iol_socket.h"
100 #include "ap_listen.h"
101 #ifdef USE_SHMGET_SCOREBOARD
102 #include <sys/types.h>
107 #ifdef HAVE_BSTRING_H
108 #include <bstring.h> /* for IRIX, FD_SET calls bzero() */
113 static int ap_max_requests_per_child=0;
114 static char *ap_pid_fname=NULL;
115 static char *ap_scoreboard_fname=NULL;
116 static char *ap_lock_fname;
117 static char *ap_server_argv0=NULL;
118 static int ap_daemons_to_start=0;
119 static int ap_daemons_min_free=0;
120 static int ap_daemons_max_free=0;
121 static int ap_daemons_limit=0;
122 static time_t ap_restart_time=0;
123 static int ap_extended_status = 0;
126 * The max child slot ever assigned, preserved across restarts. Necessary
127 * to deal with MaxClients changes across SIGUSR1 restarts. We use this
128 * value to optimize routines that have to scan the entire scoreboard.
130 static int max_daemons_limit = -1;
132 static char ap_coredump_dir[MAX_STRING_LEN];
134 /* *Non*-shared http_main globals... */
136 static server_rec *server_conf;
138 static fd_set listenfds;
139 static int listenmaxfd;
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.).
152 static int one_process = 0;
154 #ifdef HAS_OTHER_CHILD
155 /* used to maintain list of children which aren't part of the scoreboard */
156 typedef struct other_child_rec other_child_rec;
157 struct other_child_rec {
158 other_child_rec *next;
160 void (*maintenance) (int, void *, ap_wait_t);
164 static other_child_rec *other_children;
167 static pool *pconf; /* Pool for config stuff */
168 static pool *pchild; /* Pool for httpd child stuff */
170 static int my_pid; /* it seems silly to call getpid all the time */
172 static int my_child_num;
177 char tpf_server_name[INETD_SERVNAME_LENGTH+1];
180 static scoreboard *ap_scoreboard_image = NULL;
182 static int volatile exit_after_unblock = 0;
186 * change directory for gprof to plop the gmon.out file
187 * configure in httpd.conf:
188 * GprofDir logs/ -> $ServerRoot/logs/gmon.out
189 * GprofDir logs/% -> $ServerRoot/logs/gprof.$pid/gmon.out
191 static void chdir_for_gprof(void)
193 core_server_config *sconf =
194 ap_get_module_config(server_conf->module_config, &core_module);
195 char *dir = sconf->gprof_dir;
199 int len = strlen(sconf->gprof_dir) - 1;
200 if(*(dir + len) == '%') {
202 ap_snprintf(buf, sizeof(buf), "%sgprof.%d", dir, (int)getpid());
204 dir = ap_server_root_relative(pconf, buf[0] ? buf : dir);
205 if(mkdir(dir, 0755) < 0 && errno != EEXIST) {
206 ap_log_error(APLOG_MARK, APLOG_ERR, server_conf,
207 "gprof: error creating directory %s", dir);
211 dir = ap_server_root_relative(pconf, "logs");
217 #define chdir_for_gprof()
220 /* a clean exit from a child with proper cleanup */
221 static void clean_child_exit(int code) __attribute__ ((noreturn));
222 static void clean_child_exit(int code)
225 ap_destroy_pool(pchild);
231 #if defined(USE_FCNTL_SERIALIZED_ACCEPT) || defined(USE_FLOCK_SERIALIZED_ACCEPT)
232 static void expand_lock_fname(pool *p)
234 /* XXXX possibly bogus cast */
235 ap_lock_fname = ap_psprintf(p, "%s.%lu",
236 ap_server_root_relative(p, ap_lock_fname), (unsigned long)getpid());
240 #if defined (USE_USLOCK_SERIALIZED_ACCEPT)
244 static ulock_t uslock = NULL;
246 #define accept_mutex_child_init(x)
248 static void accept_mutex_init(pool *p)
254 /* default is 8, allocate enough for all the children plus the parent */
255 if ((old = usconfig(CONF_INITUSERS, HARD_SERVER_LIMIT + 1)) == -1) {
256 perror("usconfig(CONF_INITUSERS)");
260 if ((old = usconfig(CONF_LOCKTYPE, US_NODEBUG)) == -1) {
261 perror("usconfig(CONF_LOCKTYPE)");
264 if ((old = usconfig(CONF_ARENATYPE, US_SHAREDONLY)) == -1) {
265 perror("usconfig(CONF_ARENATYPE)");
268 if ((us = usinit("/dev/zero")) == NULL) {
273 if ((uslock = usnewlock(us)) == NULL) {
279 static void accept_mutex_on(void)
281 switch (ussetlock(uslock)) {
286 fprintf(stderr, "didn't get lock\n");
287 clean_child_exit(APEXIT_CHILDFATAL);
290 clean_child_exit(APEXIT_CHILDFATAL);
294 static void accept_mutex_off(void)
296 if (usunsetlock(uslock) == -1) {
297 perror("usunsetlock");
298 clean_child_exit(APEXIT_CHILDFATAL);
302 #elif defined (USE_PTHREAD_SERIALIZED_ACCEPT)
304 /* This code probably only works on Solaris ... but it works really fast
305 * on Solaris. Note that pthread mutexes are *NOT* released when a task
306 * dies ... the task has to free it itself. So we block signals and
307 * try to be nice about releasing the mutex.
312 static pthread_mutex_t *accept_mutex = (void *)(caddr_t) -1;
313 static int have_accept_mutex;
314 static sigset_t accept_block_mask;
315 static sigset_t accept_previous_mask;
317 static void accept_mutex_child_cleanup(void *foo)
319 if (accept_mutex != (void *)(caddr_t)-1
320 && have_accept_mutex) {
321 pthread_mutex_unlock(accept_mutex);
325 static void accept_mutex_child_init(pool *p)
327 ap_register_cleanup(p, NULL, accept_mutex_child_cleanup, ap_null_cleanup);
330 static void accept_mutex_cleanup(void *foo)
332 if (accept_mutex != (void *)(caddr_t)-1
333 && munmap((caddr_t) accept_mutex, sizeof(*accept_mutex))) {
336 accept_mutex = (void *)(caddr_t)-1;
339 static void accept_mutex_init(pool *p)
341 pthread_mutexattr_t mattr;
344 fd = open("/dev/zero", O_RDWR);
346 perror("open(/dev/zero)");
349 accept_mutex = (pthread_mutex_t *) mmap((caddr_t) 0, sizeof(*accept_mutex),
350 PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
351 if (accept_mutex == (void *) (caddr_t) - 1) {
356 if ((errno = pthread_mutexattr_init(&mattr))) {
357 perror("pthread_mutexattr_init");
360 if ((errno = pthread_mutexattr_setpshared(&mattr,
361 PTHREAD_PROCESS_SHARED))) {
362 perror("pthread_mutexattr_setpshared");
365 if ((errno = pthread_mutex_init(accept_mutex, &mattr))) {
366 perror("pthread_mutex_init");
369 sigfillset(&accept_block_mask);
370 sigdelset(&accept_block_mask, SIGHUP);
371 sigdelset(&accept_block_mask, SIGTERM);
372 sigdelset(&accept_block_mask, SIGUSR1);
373 ap_register_cleanup(p, NULL, accept_mutex_cleanup, ap_null_cleanup);
376 static void accept_mutex_on(void)
380 if (sigprocmask(SIG_BLOCK, &accept_block_mask, &accept_previous_mask)) {
381 perror("sigprocmask(SIG_BLOCK)");
382 clean_child_exit(APEXIT_CHILDFATAL);
384 if ((err = pthread_mutex_lock(accept_mutex))) {
386 perror("pthread_mutex_lock");
387 clean_child_exit(APEXIT_CHILDFATAL);
389 have_accept_mutex = 1;
392 static void accept_mutex_off(void)
396 if ((err = pthread_mutex_unlock(accept_mutex))) {
398 perror("pthread_mutex_unlock");
399 clean_child_exit(APEXIT_CHILDFATAL);
401 /* There is a slight race condition right here... if we were to die right
402 * now, we'd do another pthread_mutex_unlock. Now, doing that would let
403 * another process into the mutex. pthread mutexes are designed to be
404 * fast, as such they don't have protection for things like testing if the
405 * thread owning a mutex is actually unlocking it (or even any way of
406 * testing who owns the mutex).
408 * If we were to unset have_accept_mutex prior to releasing the mutex
409 * then the race could result in the server unable to serve hits. Doing
410 * it this way means that the server can continue, but an additional
411 * child might be in the critical section ... at least it's still serving
414 have_accept_mutex = 0;
415 if (sigprocmask(SIG_SETMASK, &accept_previous_mask, NULL)) {
416 perror("sigprocmask(SIG_SETMASK)");
421 #elif defined (USE_SYSVSEM_SERIALIZED_ACCEPT)
423 #include <sys/types.h>
427 #ifdef NEED_UNION_SEMUN
428 /* it makes no sense, but this isn't defined on solaris */
431 struct semid_ds *buf;
437 static int sem_id = -1;
438 static struct sembuf op_on;
439 static struct sembuf op_off;
441 /* We get a random semaphore ... the lame sysv semaphore interface
442 * means we have to be sure to clean this up or else we'll leak
445 static void accept_mutex_cleanup(void *foo)
451 /* this is ignored anyhow */
453 semctl(sem_id, 0, IPC_RMID, ick);
456 #define accept_mutex_child_init(x)
458 static void accept_mutex_init(pool *p)
463 /* acquire the semaphore */
464 sem_id = semget(IPC_PRIVATE, 1, IPC_CREAT | 0600);
470 if (semctl(sem_id, 0, SETVAL, ick) < 0) {
471 perror("semctl(SETVAL)");
475 /* restrict it to use only by the appropriate user_id ... not that this
476 * stops CGIs from acquiring it and dinking around with it.
478 buf.sem_perm.uid = unixd_config.user_id;
479 buf.sem_perm.gid = unixd_config.group_id;
480 buf.sem_perm.mode = 0600;
482 if (semctl(sem_id, 0, IPC_SET, ick) < 0) {
483 perror("semctl(IPC_SET)");
487 ap_register_cleanup(p, NULL, accept_mutex_cleanup, ap_null_cleanup);
489 /* pre-initialize these */
492 op_on.sem_flg = SEM_UNDO;
495 op_off.sem_flg = SEM_UNDO;
498 static void accept_mutex_on(void)
500 while (semop(sem_id, &op_on, 1) < 0) {
501 if (errno != EINTR) {
502 perror("accept_mutex_on");
503 clean_child_exit(APEXIT_CHILDFATAL);
508 static void accept_mutex_off(void)
510 while (semop(sem_id, &op_off, 1) < 0) {
511 if (errno != EINTR) {
512 perror("accept_mutex_off");
513 clean_child_exit(APEXIT_CHILDFATAL);
518 #elif defined(USE_FCNTL_SERIALIZED_ACCEPT)
519 static struct flock lock_it;
520 static struct flock unlock_it;
522 static int lock_fd = -1;
524 #define accept_mutex_child_init(x)
527 * Initialize mutex lock.
528 * Must be safe to call this on a restart.
530 static void accept_mutex_init(pool *p)
533 lock_it.l_whence = SEEK_SET; /* from current point */
534 lock_it.l_start = 0; /* -"- */
535 lock_it.l_len = 0; /* until end of file */
536 lock_it.l_type = F_WRLCK; /* set exclusive/write lock */
537 lock_it.l_pid = 0; /* pid not actually interesting */
538 unlock_it.l_whence = SEEK_SET; /* from current point */
539 unlock_it.l_start = 0; /* -"- */
540 unlock_it.l_len = 0; /* until end of file */
541 unlock_it.l_type = F_UNLCK; /* set exclusive/write lock */
542 unlock_it.l_pid = 0; /* pid not actually interesting */
544 expand_lock_fname(p);
545 lock_fd = ap_popenf(p, ap_lock_fname, O_CREAT | O_WRONLY | O_EXCL, 0644);
548 fprintf(stderr, "Cannot open lock file: %s\n", ap_lock_fname);
551 unlink(ap_lock_fname);
554 static void accept_mutex_on(void)
558 while ((ret = fcntl(lock_fd, F_SETLKW, &lock_it)) < 0 && errno == EINTR) {
563 ap_log_error(APLOG_MARK, APLOG_EMERG, server_conf,
564 "fcntl: F_SETLKW: Error getting accept lock, exiting! "
565 "Perhaps you need to use the LockFile directive to place "
566 "your lock file on a local disk!");
567 clean_child_exit(APEXIT_CHILDFATAL);
571 static void accept_mutex_off(void)
575 while ((ret = fcntl(lock_fd, F_SETLKW, &unlock_it)) < 0 && errno == EINTR) {
579 ap_log_error(APLOG_MARK, APLOG_EMERG, server_conf,
580 "fcntl: F_SETLKW: Error freeing accept lock, exiting! "
581 "Perhaps you need to use the LockFile directive to place "
582 "your lock file on a local disk!");
583 clean_child_exit(APEXIT_CHILDFATAL);
587 #elif defined(USE_FLOCK_SERIALIZED_ACCEPT)
589 static int lock_fd = -1;
591 static void accept_mutex_cleanup(void *foo)
593 unlink(ap_lock_fname);
597 * Initialize mutex lock.
598 * Done by each child at it's birth
600 static void accept_mutex_child_init(pool *p)
603 lock_fd = ap_popenf(p, ap_lock_fname, O_WRONLY, 0600);
605 ap_log_error(APLOG_MARK, APLOG_EMERG, server_conf,
606 "Child cannot open lock file: %s", ap_lock_fname);
607 clean_child_exit(APEXIT_CHILDINIT);
612 * Initialize mutex lock.
613 * Must be safe to call this on a restart.
615 static void accept_mutex_init(pool *p)
617 expand_lock_fname(p);
618 unlink(ap_lock_fname);
619 lock_fd = ap_popenf(p, ap_lock_fname, O_CREAT | O_WRONLY | O_EXCL, 0600);
621 ap_log_error(APLOG_MARK, APLOG_EMERG, server_conf,
622 "Parent cannot open lock file: %s", ap_lock_fname);
625 ap_register_cleanup(p, NULL, accept_mutex_cleanup, ap_null_cleanup);
628 static void accept_mutex_on(void)
632 while ((ret = flock(lock_fd, LOCK_EX)) < 0 && errno == EINTR)
636 ap_log_error(APLOG_MARK, APLOG_EMERG, server_conf,
637 "flock: LOCK_EX: Error getting accept lock. Exiting!");
638 clean_child_exit(APEXIT_CHILDFATAL);
642 static void accept_mutex_off(void)
644 if (flock(lock_fd, LOCK_UN) < 0) {
645 ap_log_error(APLOG_MARK, APLOG_EMERG, server_conf,
646 "flock: LOCK_UN: Error freeing accept lock. Exiting!");
647 clean_child_exit(APEXIT_CHILDFATAL);
651 #elif defined(USE_OS2SEM_SERIALIZED_ACCEPT)
653 static HMTX lock_sem = -1;
655 static void accept_mutex_cleanup(void *foo)
657 DosReleaseMutexSem(lock_sem);
658 DosCloseMutexSem(lock_sem);
662 * Initialize mutex lock.
663 * Done by each child at it's birth
665 static void accept_mutex_child_init(pool *p)
667 int rc = DosOpenMutexSem(NULL, &lock_sem);
670 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_EMERG, server_conf,
671 "Child cannot open lock semaphore, rc=%d", rc);
672 clean_child_exit(APEXIT_CHILDINIT);
677 * Initialize mutex lock.
678 * Must be safe to call this on a restart.
680 static void accept_mutex_init(pool *p)
682 int rc = DosCreateMutexSem(NULL, &lock_sem, DC_SEM_SHARED, FALSE);
685 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_EMERG, server_conf,
686 "Parent cannot create lock semaphore, rc=%d", rc);
690 ap_register_cleanup(p, NULL, accept_mutex_cleanup, ap_null_cleanup);
693 static void accept_mutex_on(void)
695 int rc = DosRequestMutexSem(lock_sem, SEM_INDEFINITE_WAIT);
698 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_EMERG, server_conf,
699 "OS2SEM: Error %d getting accept lock. Exiting!", rc);
700 clean_child_exit(APEXIT_CHILDFATAL);
704 static void accept_mutex_off(void)
706 int rc = DosReleaseMutexSem(lock_sem);
709 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_EMERG, server_conf,
710 "OS2SEM: Error %d freeing accept lock. Exiting!", rc);
711 clean_child_exit(APEXIT_CHILDFATAL);
715 #elif defined(USE_TPF_CORE_SERIALIZED_ACCEPT)
717 static int tpf_core_held;
719 static void accept_mutex_cleanup(void *foo)
725 #define accept_mutex_init(x)
727 static void accept_mutex_child_init(pool *p)
729 ap_register_cleanup(p, NULL, accept_mutex_cleanup, ap_null_cleanup);
733 static void accept_mutex_on(void)
740 static void accept_mutex_off(void)
748 /* Default --- no serialization. Other methods *could* go here,
751 #if !defined(MULTITHREAD)
752 /* Multithreaded systems don't complete between processes for
754 #define NO_SERIALIZED_ACCEPT
755 #define accept_mutex_child_init(x)
756 #define accept_mutex_init(x)
757 #define accept_mutex_on()
758 #define accept_mutex_off()
762 /* On some architectures it's safe to do unserialized accept()s in the single
763 * Listen case. But it's never safe to do it in the case where there's
764 * multiple Listen statements. Define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
765 * when it's safe in the single Listen case.
767 #ifdef SINGLE_LISTEN_UNSERIALIZED_ACCEPT
768 #define SAFE_ACCEPT(stmt) do {if (ap_listeners->next) {stmt;}} while(0)
770 #define SAFE_ACCEPT(stmt) do {stmt;} while(0)
774 /*****************************************************************
775 * dealing with other children
778 #ifdef HAS_OTHER_CHILD
779 API_EXPORT(void) ap_register_other_child(int pid,
780 void (*maintenance) (int reason, void *, ap_wait_t status),
781 void *data, int write_fd)
783 other_child_rec *ocr;
785 ocr = ap_palloc(pconf, sizeof(*ocr));
787 ocr->maintenance = maintenance;
789 ocr->write_fd = write_fd;
790 ocr->next = other_children;
791 other_children = ocr;
794 /* note that since this can be called by a maintenance function while we're
795 * scanning the other_children list, all scanners should protect themself
796 * by loading ocr->next before calling any maintenance function.
798 API_EXPORT(void) ap_unregister_other_child(void *data)
800 other_child_rec **pocr, *nocr;
802 for (pocr = &other_children; *pocr; pocr = &(*pocr)->next) {
803 if ((*pocr)->data == data) {
804 nocr = (*pocr)->next;
805 (*(*pocr)->maintenance) (OC_REASON_UNREGISTER, (*pocr)->data, -1);
807 /* XXX: um, well we've just wasted some space in pconf ? */
813 /* test to ensure that the write_fds are all still writable, otherwise
814 * invoke the maintenance functions as appropriate */
815 static void probe_writable_fds(void)
819 other_child_rec *ocr, *nocr;
823 if (other_children == NULL)
827 FD_ZERO(&writable_fds);
829 for (ocr = other_children; ocr; ocr = ocr->next) {
830 if (ocr->write_fd == -1)
832 FD_SET(ocr->write_fd, &writable_fds);
833 if (ocr->write_fd > fd_max) {
834 fd_max = ocr->write_fd;
842 rc = ap_select(fd_max + 1, NULL, &writable_fds, NULL, &tv);
843 } while (rc == -1 && errno == EINTR);
846 /* XXX: uhh this could be really bad, we could have a bad file
847 * descriptor due to a bug in one of the maintenance routines */
848 ap_log_unixerr("probe_writable_fds", "select",
849 "could not probe writable fds", server_conf);
855 for (ocr = other_children; ocr; ocr = nocr) {
857 if (ocr->write_fd == -1)
859 if (FD_ISSET(ocr->write_fd, &writable_fds))
861 (*ocr->maintenance) (OC_REASON_UNWRITABLE, ocr->data, -1);
865 /* possibly reap an other_child, return 0 if yes, -1 if not */
866 static int reap_other_child(int pid, ap_wait_t status)
868 other_child_rec *ocr, *nocr;
870 for (ocr = other_children; ocr; ocr = nocr) {
875 (*ocr->maintenance) (OC_REASON_DEATH, ocr->data, status);
882 /*****************************************************************
884 * Dealing with the scoreboard... a lot of these variables are global
885 * only to avoid getting clobbered by the longjmp() that happens when
886 * a hard timeout expires...
888 * We begin with routines which deal with the file itself...
891 #if defined(USE_OS2_SCOREBOARD)
893 /* The next two routines are used to access shared memory under OS/2. */
894 /* This requires EMX v09c to be installed. */
896 caddr_t create_shared_heap(const char *name, size_t size)
902 rc = DosAllocSharedMem(&mem, name, size,
903 PAG_COMMIT | PAG_READ | PAG_WRITE);
906 h = _ucreate(mem, size, !_BLOCK_CLEAN, _HEAP_REGULAR | _HEAP_SHARED,
913 caddr_t get_shared_heap(const char *Name)
916 PVOID BaseAddress; /* Pointer to the base address of
917 the shared memory object */
918 ULONG AttributeFlags; /* Flags describing characteristics
919 of the shared memory object */
920 APIRET rc; /* Return code */
922 /* Request read and write access to */
923 /* the shared memory object */
924 AttributeFlags = PAG_WRITE | PAG_READ;
926 rc = DosGetNamedSharedMem(&BaseAddress, Name, AttributeFlags);
929 printf("DosGetNamedSharedMem error: return code = %ld", rc);
936 static void setup_shared_mem(pool *p)
942 m = (caddr_t) create_shared_heap("\\SHAREMEM\\SCOREBOARD", SCOREBOARD_SIZE);
944 fprintf(stderr, "%s: Could not create OS/2 Shared memory pool.\n",
949 rc = _uopen((Heap_t) m);
952 "%s: Could not uopen() newly created OS/2 Shared memory pool.\n",
955 ap_scoreboard_image = (scoreboard *) m;
956 ap_scoreboard_image->global.running_generation = 0;
959 static void reopen_scoreboard(pool *p)
964 m = (caddr_t) get_shared_heap("\\SHAREMEM\\SCOREBOARD");
966 fprintf(stderr, "%s: Could not find existing OS/2 Shared memory pool.\n",
971 rc = _uopen((Heap_t) m);
972 ap_scoreboard_image = (scoreboard *) m;
975 #elif defined(USE_POSIX_SCOREBOARD)
976 #include <sys/mman.h>
981 * As of version 4.23A, shared memory in QNX must reside under /dev/shmem,
982 * where no subdirectories allowed.
984 * POSIX shm_open() and shm_unlink() will take care about this issue,
985 * but to avoid confusion, I suggest to redefine scoreboard file name
986 * in httpd.conf to cut "logs/" from it. With default setup actual name
987 * will be "/dev/shmem/logs.apache_status".
989 * If something went wrong and Apache did not unlinked this object upon
990 * exit, you can remove it manually, using "rm -f" command.
993 * <sys/mman.h> in QNX defines MAP_ANON, but current implementation
994 * does NOT support BSD style anonymous mapping. So, the order of
995 * conditional compilation is important:
996 * this #ifdef section must be ABOVE the next one (BSD style).
998 * I tested this stuff and it works fine for me, but if it provides
999 * trouble for you, just comment out USE_MMAP_SCOREBOARD in QNX section
1003 * Igor N. Kovalenko -- infoh@mail.wplus.net
1006 static void cleanup_shared_mem(void *d)
1008 shm_unlink(ap_scoreboard_fname);
1011 static void setup_shared_mem(pool *p)
1017 fd = shm_open(ap_scoreboard_fname, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
1019 ap_snprintf(buf, sizeof(buf), "%s: could not open(create) scoreboard",
1024 if (ltrunc(fd, (off_t) SCOREBOARD_SIZE, SEEK_SET) == -1) {
1025 ap_snprintf(buf, sizeof(buf), "%s: could not ltrunc scoreboard",
1028 shm_unlink(ap_scoreboard_fname);
1031 if ((m = (caddr_t) mmap((caddr_t) 0,
1032 (size_t) SCOREBOARD_SIZE, PROT_READ | PROT_WRITE,
1033 MAP_SHARED, fd, (off_t) 0)) == (caddr_t) - 1) {
1034 ap_snprintf(buf, sizeof(buf), "%s: cannot mmap scoreboard",
1037 shm_unlink(ap_scoreboard_fname);
1041 ap_register_cleanup(p, NULL, cleanup_shared_mem, ap_null_cleanup);
1042 ap_scoreboard_image = (scoreboard *) m;
1043 ap_scoreboard_image->global.running_generation = 0;
1046 static void reopen_scoreboard(pool *p)
1050 #elif defined(USE_MMAP_SCOREBOARD)
1052 static void setup_shared_mem(pool *p)
1056 #if defined(MAP_ANON)
1060 * 9-Aug-97 - Jeff Venters (venters@convex.hp.com)
1061 * ConvexOS maps address space as follows:
1062 * 0x00000000 - 0x7fffffff : Kernel
1063 * 0x80000000 - 0xffffffff : User
1064 * Start mmapped area 1GB above start of text.
1066 * Also, the length requires a pointer as the actual length is
1067 * returned (rounded up to a page boundary).
1070 unsigned len = SCOREBOARD_SIZE;
1072 m = mmap((caddr_t) 0xC0000000, &len,
1073 PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, NOFD, 0);
1075 #elif defined(MAP_TMPFILE)
1077 char mfile[] = "/tmp/apache_shmem_XXXX";
1078 int fd = mkstemp(mfile);
1081 fprintf(stderr, "%s: Could not open %s\n", ap_server_argv0, mfile);
1084 m = mmap((caddr_t) 0, SCOREBOARD_SIZE,
1085 PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
1086 if (m == (caddr_t) - 1) {
1088 fprintf(stderr, "%s: Could not mmap %s\n", ap_server_argv0, mfile);
1095 m = mmap((caddr_t) 0, SCOREBOARD_SIZE,
1096 PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0);
1098 if (m == (caddr_t) - 1) {
1100 fprintf(stderr, "%s: Could not mmap memory\n", ap_server_argv0);
1107 fd = open("/dev/zero", O_RDWR);
1110 fprintf(stderr, "%s: Could not open /dev/zero\n", ap_server_argv0);
1113 m = mmap((caddr_t) 0, SCOREBOARD_SIZE,
1114 PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
1115 if (m == (caddr_t) - 1) {
1117 fprintf(stderr, "%s: Could not mmap /dev/zero\n", ap_server_argv0);
1122 ap_scoreboard_image = (scoreboard *) m;
1123 ap_scoreboard_image->global.running_generation = 0;
1126 static void reopen_scoreboard(pool *p)
1130 #elif defined(USE_SHMGET_SCOREBOARD)
1131 static key_t shmkey = IPC_PRIVATE;
1132 static int shmid = -1;
1134 static void setup_shared_mem(pool *p)
1136 struct shmid_ds shmbuf;
1141 if ((shmid = shmget(shmkey, SCOREBOARD_SIZE, IPC_CREAT | SHM_R | SHM_W)) == -1) {
1143 if (errno == ENOSYS) {
1144 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_EMERG, server_conf,
1145 "Your kernel was built without CONFIG_SYSVIPC\n"
1146 "%s: Please consult the Apache FAQ for details",
1150 ap_log_error(APLOG_MARK, APLOG_EMERG, server_conf,
1151 "could not call shmget");
1155 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, server_conf,
1156 "created shared memory segment #%d", shmid);
1160 * Some SysV systems place the shared segment WAY too close
1161 * to the dynamic memory break point (sbrk(0)). This severely
1162 * limits the use of malloc/sbrk in the program since sbrk will
1163 * refuse to move past that point.
1165 * To get around this, we move the break point "way up there",
1166 * attach the segment and then move break back down. Ugly
1168 if ((obrk = sbrk(MOVEBREAK)) == (char *) -1) {
1169 ap_log_error(APLOG_MARK, APLOG_ERR, server_conf,
1170 "sbrk() could not move break");
1174 #define BADSHMAT ((scoreboard *)(-1))
1175 if ((ap_scoreboard_image = (scoreboard *) shmat(shmid, 0, 0)) == BADSHMAT) {
1176 ap_log_error(APLOG_MARK, APLOG_EMERG, server_conf, "shmat error");
1178 * We exit below, after we try to remove the segment
1181 else { /* only worry about permissions if we attached the segment */
1182 if (shmctl(shmid, IPC_STAT, &shmbuf) != 0) {
1183 ap_log_error(APLOG_MARK, APLOG_ERR, server_conf,
1184 "shmctl() could not stat segment #%d", shmid);
1187 shmbuf.shm_perm.uid = unixd_config.user_id;
1188 shmbuf.shm_perm.gid = unixd_config.group_id;
1189 if (shmctl(shmid, IPC_SET, &shmbuf) != 0) {
1190 ap_log_error(APLOG_MARK, APLOG_ERR, server_conf,
1191 "shmctl() could not set segment #%d", shmid);
1196 * We must avoid leaving segments in the kernel's
1199 if (shmctl(shmid, IPC_RMID, NULL) != 0) {
1200 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf,
1201 "shmctl: IPC_RMID: could not remove shared memory segment #%d",
1204 if (ap_scoreboard_image == BADSHMAT) /* now bailout */
1208 if (obrk == (char *) -1)
1209 return; /* nothing else to do */
1210 if (sbrk(-(MOVEBREAK)) == (char *) -1) {
1211 ap_log_error(APLOG_MARK, APLOG_ERR, server_conf,
1212 "sbrk() could not move break back");
1215 ap_scoreboard_image->global.running_generation = 0;
1218 static void reopen_scoreboard(pool *p)
1222 #elif defined(USE_TPF_SCOREBOARD)
1224 static void cleanup_scoreboard_heap()
1227 rv = rsysc(ap_scoreboard_image, SCOREBOARD_FRAMES, SCOREBOARD_NAME);
1228 if(rv == RSYSC_ERROR) {
1229 ap_log_error(APLOG_MARK, APLOG_ERR, server_conf,
1230 "rsysc() could not release scoreboard system heap");
1234 static void setup_shared_mem(pool *p)
1236 cinfc(CINFC_WRITE, CINFC_CMMCTK2);
1237 ap_scoreboard_image = (scoreboard *) gsysc(SCOREBOARD_FRAMES, SCOREBOARD_NAME);
1239 if (!ap_scoreboard_image) {
1240 fprintf(stderr, "httpd: Could not create scoreboard system heap storage.\n");
1244 ap_register_cleanup(p, NULL, cleanup_scoreboard_heap, ap_null_cleanup);
1245 ap_scoreboard_image->global.running_generation = 0;
1248 static void reopen_scoreboard(pool *p)
1250 cinfc(CINFC_WRITE, CINFC_CMMCTK2);
1254 #define SCOREBOARD_FILE
1255 static scoreboard _scoreboard_image;
1256 static int scoreboard_fd = -1;
1258 /* XXX: things are seriously screwed if we ever have to do a partial
1259 * read or write ... we could get a corrupted scoreboard
1261 static int force_write(int fd, void *buffer, int bufsz)
1263 int rv, orig_sz = bufsz;
1266 rv = write(fd, buffer, bufsz);
1268 buffer = (char *) buffer + rv;
1271 } while ((rv > 0 && bufsz > 0) || (rv == -1 && errno == EINTR));
1273 return rv < 0 ? rv : orig_sz - bufsz;
1276 static int force_read(int fd, void *buffer, int bufsz)
1278 int rv, orig_sz = bufsz;
1281 rv = read(fd, buffer, bufsz);
1283 buffer = (char *) buffer + rv;
1286 } while ((rv > 0 && bufsz > 0) || (rv == -1 && errno == EINTR));
1288 return rv < 0 ? rv : orig_sz - bufsz;
1291 static void cleanup_scoreboard_file(void *foo)
1293 unlink(ap_scoreboard_fname);
1296 void reopen_scoreboard(pool *p)
1298 if (scoreboard_fd != -1)
1299 ap_pclosef(p, scoreboard_fd);
1302 ap_scoreboard_fname = ap_server_root_relative(p, ap_scoreboard_fname);
1304 scoreboard_fd = ap_popenf(p, ap_scoreboard_fname, O_CREAT | O_BINARY | O_RDWR, 0666);
1305 if (scoreboard_fd == -1) {
1306 perror(ap_scoreboard_fname);
1307 fprintf(stderr, "Cannot open scoreboard file:\n");
1308 clean_child_exit(1);
1313 /* Called by parent process */
1314 static void reinit_scoreboard(pool *p)
1316 int running_gen = 0;
1317 if (ap_scoreboard_image)
1318 running_gen = ap_scoreboard_image->global.running_generation;
1320 #ifndef SCOREBOARD_FILE
1321 if (ap_scoreboard_image == NULL) {
1322 setup_shared_mem(p);
1324 memset(ap_scoreboard_image, 0, SCOREBOARD_SIZE);
1325 ap_scoreboard_image->global.running_generation = running_gen;
1327 ap_scoreboard_image = &_scoreboard_image;
1328 ap_scoreboard_fname = ap_server_root_relative(p, ap_scoreboard_fname);
1330 scoreboard_fd = ap_popenf(p, ap_scoreboard_fname, O_CREAT | O_BINARY | O_RDWR, 0644);
1331 if (scoreboard_fd == -1) {
1332 perror(ap_scoreboard_fname);
1333 fprintf(stderr, "Cannot open scoreboard file:\n");
1336 ap_register_cleanup(p, NULL, cleanup_scoreboard_file, ap_null_cleanup);
1338 memset((char *) ap_scoreboard_image, 0, sizeof(*ap_scoreboard_image));
1339 ap_scoreboard_image->global.running_generation = running_gen;
1340 force_write(scoreboard_fd, ap_scoreboard_image, sizeof(*ap_scoreboard_image));
1344 /* Routines called to deal with the scoreboard image
1345 * --- note that we do *not* need write locks, since update_child_status
1346 * only updates a *single* record in place, and only one process writes to
1347 * a given scoreboard slot at a time (either the child process owning that
1348 * slot, or the parent, noting that the child has died).
1350 * As a final note --- setting the score entry to getpid() is always safe,
1351 * since when the parent is writing an entry, it's only noting SERVER_DEAD
1355 ap_inline void ap_sync_scoreboard_image(void)
1357 #ifdef SCOREBOARD_FILE
1358 lseek(scoreboard_fd, 0L, 0);
1359 force_read(scoreboard_fd, ap_scoreboard_image, sizeof(*ap_scoreboard_image));
1363 API_EXPORT(int) ap_exists_scoreboard_image(void)
1365 return (ap_scoreboard_image ? 1 : 0);
1368 static ap_inline void put_scoreboard_info(int child_num,
1369 short_score *new_score_rec)
1371 #ifdef SCOREBOARD_FILE
1372 lseek(scoreboard_fd, (long) child_num * sizeof(short_score), 0);
1373 force_write(scoreboard_fd, new_score_rec, sizeof(short_score));
1377 int ap_update_child_status(int child_num, int status, request_rec *r)
1387 ap_sync_scoreboard_image();
1388 ss = &ap_scoreboard_image->servers[child_num];
1389 old_status = ss->status;
1390 ss->status = status;
1392 if (ap_extended_status) {
1393 if (status == SERVER_READY || status == SERVER_DEAD) {
1395 * Reset individual counters
1397 if (status == SERVER_DEAD) {
1398 ss->my_access_count = 0L;
1399 ss->my_bytes_served = 0L;
1401 ss->conn_count = (unsigned short) 0;
1402 ss->conn_bytes = (unsigned long) 0;
1405 conn_rec *c = r->connection;
1406 ap_cpystrn(ss->client, ap_get_remote_host(c, r->per_dir_config,
1407 REMOTE_NOLOOKUP), sizeof(ss->client));
1408 if (r->the_request == NULL) {
1409 ap_cpystrn(ss->request, "NULL", sizeof(ss->request));
1410 } else if (r->parsed_uri.password == NULL) {
1411 ap_cpystrn(ss->request, r->the_request, sizeof(ss->request));
1413 /* Don't reveal the password in the server-status view */
1414 ap_cpystrn(ss->request, ap_pstrcat(r->pool, r->method, " ",
1415 ap_unparse_uri_components(r->pool, &r->parsed_uri, UNP_OMITPASSWORD),
1416 r->assbackwards ? NULL : " ", r->protocol, NULL),
1417 sizeof(ss->request));
1419 ss->vhostrec = r->server;
1422 if (status == SERVER_STARTING && r == NULL) {
1423 /* clean up the slot's vhostrec pointer (maybe re-used)
1424 * and mark the slot as belonging to a new generation.
1426 ss->vhostrec = NULL;
1427 ap_scoreboard_image->parent[child_num].generation = ap_my_generation;
1428 #ifdef SCOREBOARD_FILE
1429 lseek(scoreboard_fd, XtOffsetOf(scoreboard, parent[child_num]), 0);
1430 force_write(scoreboard_fd, &ap_scoreboard_image->parent[child_num],
1431 sizeof(parent_score));
1434 put_scoreboard_info(child_num, ss);
1439 static void update_scoreboard_global(void)
1441 #ifdef SCOREBOARD_FILE
1442 lseek(scoreboard_fd,
1443 (char *) &ap_scoreboard_image->global -(char *) ap_scoreboard_image, 0);
1444 force_write(scoreboard_fd, &ap_scoreboard_image->global,
1445 sizeof ap_scoreboard_image->global);
1449 void ap_time_process_request(int child_num, int status)
1452 #if defined(NO_GETTIMEOFDAY) && !defined(NO_TIMES)
1459 ap_sync_scoreboard_image();
1460 ss = &ap_scoreboard_image->servers[child_num];
1462 if (status == START_PREQUEST) {
1463 #if defined(NO_GETTIMEOFDAY)
1465 if ((ss->start_time = times(&tms_blk)) == -1)
1466 #endif /* NO_TIMES */
1467 ss->start_time = (clock_t) 0;
1469 if (gettimeofday(&ss->start_time, (struct timezone *) 0) < 0)
1470 ss->start_time.tv_sec =
1471 ss->start_time.tv_usec = 0L;
1474 else if (status == STOP_PREQUEST) {
1475 #if defined(NO_GETTIMEOFDAY)
1477 if ((ss->stop_time = times(&tms_blk)) == -1)
1479 ss->stop_time = ss->start_time = (clock_t) 0;
1481 if (gettimeofday(&ss->stop_time, (struct timezone *) 0) < 0)
1482 ss->stop_time.tv_sec =
1483 ss->stop_time.tv_usec =
1484 ss->start_time.tv_sec =
1485 ss->start_time.tv_usec = 0L;
1490 put_scoreboard_info(child_num, ss);
1493 static void increment_counts(int child_num, request_rec *r)
1498 ap_sync_scoreboard_image();
1499 ss = &ap_scoreboard_image->servers[child_num];
1502 ap_bgetopt(r->connection->client, BO_BYTECT, &bs);
1508 ss->my_access_count++;
1510 ss->bytes_served += (unsigned long) bs;
1511 ss->my_bytes_served += (unsigned long) bs;
1512 ss->conn_bytes += (unsigned long) bs;
1514 put_scoreboard_info(child_num, ss);
1517 static int find_child_by_pid(int pid)
1521 for (i = 0; i < max_daemons_limit; ++i)
1522 if (ap_scoreboard_image->parent[i].pid == pid)
1528 static void reclaim_child_processes(int terminate)
1532 long int waittime = 1024 * 16; /* in usecs */
1536 #ifdef HAS_OTHER_CHILD
1537 other_child_rec *ocr, *nocr;
1540 ap_sync_scoreboard_image();
1542 for (tries = terminate ? 4 : 1; tries <= 9; ++tries) {
1543 /* don't want to hold up progress any more than
1544 * necessary, but we need to allow children a few moments to exit.
1545 * Set delay with an exponential backoff.
1547 tv.tv_sec = waittime / 1000000;
1548 tv.tv_usec = waittime % 1000000;
1549 waittime = waittime * 4;
1550 ap_select(0, NULL, NULL, NULL, &tv);
1552 /* now see who is done */
1554 for (i = 0; i < max_daemons_limit; ++i) {
1555 int pid = ap_scoreboard_image->parent[i].pid;
1557 if (pid == my_pid || pid == 0)
1560 waitret = waitpid(pid, &status, WNOHANG);
1561 if (waitret == pid || waitret == -1) {
1562 ap_scoreboard_image->parent[i].pid = 0;
1571 /* perhaps it missed the SIGHUP, lets try again */
1572 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING,
1574 "child process %d did not exit, sending another SIGHUP",
1577 waittime = 1024 * 16;
1583 case 7: /* 1.4sec */
1584 /* ok, now it's being annoying */
1585 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING,
1587 "child process %d still did not exit, sending a SIGTERM",
1592 /* die child scum */
1593 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, server_conf,
1594 "child process %d still did not exit, sending a SIGKILL",
1598 case 9: /* 14 sec */
1599 /* gave it our best shot, but alas... If this really
1600 * is a child we are trying to kill and it really hasn't
1601 * exited, we will likely fail to bind to the port
1602 * after the restart.
1604 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, server_conf,
1605 "could not make child process %d exit, "
1606 "attempting to continue anyway", pid);
1610 #ifdef HAS_OTHER_CHILD
1611 for (ocr = other_children; ocr; ocr = nocr) {
1616 waitret = waitpid(ocr->pid, &status, WNOHANG);
1617 if (waitret == ocr->pid) {
1619 (*ocr->maintenance) (OC_REASON_DEATH, ocr->data, status);
1621 else if (waitret == 0) {
1622 (*ocr->maintenance) (OC_REASON_RESTART, ocr->data, -1);
1625 else if (waitret == -1) {
1626 /* uh what the heck? they didn't call unregister? */
1628 (*ocr->maintenance) (OC_REASON_LOST, ocr->data, -1);
1632 if (!not_dead_yet) {
1633 /* nothing left to wait for */
1637 #endif /* ndef MULTITHREAD */
1641 #if defined(NEED_WAITPID)
1643 Systems without a real waitpid sometimes lose a child's exit while waiting
1644 for another. Search through the scoreboard for missing children.
1646 int reap_children(ap_wait_t *status)
1650 for (n = 0; n < max_daemons_limit; ++n) {
1651 ap_sync_scoreboard_image();
1652 if (ap_scoreboard_image->servers[n].status != SERVER_DEAD &&
1653 kill((pid = ap_scoreboard_image->parent[n].pid), 0) == -1) {
1654 ap_update_child_status(n, SERVER_DEAD, NULL);
1655 /* just mark it as having a successful exit status */
1656 bzero((char *) status, sizeof(ap_wait_t));
1664 /* Finally, this routine is used by the caretaker process to wait for
1668 /* number of calls to wait_or_timeout between writable probes */
1669 #ifndef INTERVAL_OF_WRITABLE_PROBES
1670 #define INTERVAL_OF_WRITABLE_PROBES 10
1672 static int wait_or_timeout_counter;
1674 static int wait_or_timeout(ap_wait_t *status)
1679 ++wait_or_timeout_counter;
1680 if (wait_or_timeout_counter == INTERVAL_OF_WRITABLE_PROBES) {
1681 wait_or_timeout_counter = 0;
1682 #ifdef HAS_OTHER_CHILD
1683 probe_writable_fds();
1686 ret = waitpid(-1, status, WNOHANG);
1687 if (ret == -1 && errno == EINTR) {
1694 if ((ret = reap_children(status)) > 0) {
1698 tv.tv_sec = SCOREBOARD_MAINTENANCE_INTERVAL / 1000000;
1699 tv.tv_usec = SCOREBOARD_MAINTENANCE_INTERVAL % 1000000;
1700 ap_select(0, NULL, NULL, NULL, &tv);
1707 #elif defined(_NSIG)
1708 #define NumSIG _NSIG
1709 #elif defined(__NSIG)
1710 #define NumSIG __NSIG
1712 #define NumSIG 32 /* for 1998's unixes, this is still a good assumption */
1715 #ifdef SYS_SIGLIST /* platform has sys_siglist[] */
1716 #define INIT_SIGLIST() /*nothing*/
1717 #else /* platform has no sys_siglist[], define our own */
1718 #define SYS_SIGLIST ap_sys_siglist
1719 #define INIT_SIGLIST() siglist_init();
1721 const char *ap_sys_siglist[NumSIG];
1723 static void siglist_init(void)
1727 ap_sys_siglist[0] = "Signal 0";
1729 ap_sys_siglist[SIGHUP] = "Hangup";
1732 ap_sys_siglist[SIGINT] = "Interrupt";
1735 ap_sys_siglist[SIGQUIT] = "Quit";
1738 ap_sys_siglist[SIGILL] = "Illegal instruction";
1741 ap_sys_siglist[SIGTRAP] = "Trace/BPT trap";
1744 ap_sys_siglist[SIGIOT] = "IOT instruction";
1747 ap_sys_siglist[SIGABRT] = "Abort";
1750 ap_sys_siglist[SIGEMT] = "Emulator trap";
1753 ap_sys_siglist[SIGFPE] = "Arithmetic exception";
1756 ap_sys_siglist[SIGKILL] = "Killed";
1759 ap_sys_siglist[SIGBUS] = "Bus error";
1762 ap_sys_siglist[SIGSEGV] = "Segmentation fault";
1765 ap_sys_siglist[SIGSYS] = "Bad system call";
1768 ap_sys_siglist[SIGPIPE] = "Broken pipe";
1771 ap_sys_siglist[SIGALRM] = "Alarm clock";
1774 ap_sys_siglist[SIGTERM] = "Terminated";
1777 ap_sys_siglist[SIGUSR1] = "User defined signal 1";
1780 ap_sys_siglist[SIGUSR2] = "User defined signal 2";
1783 ap_sys_siglist[SIGCLD] = "Child status change";
1786 ap_sys_siglist[SIGCHLD] = "Child status change";
1789 ap_sys_siglist[SIGPWR] = "Power-fail restart";
1792 ap_sys_siglist[SIGWINCH] = "Window changed";
1795 ap_sys_siglist[SIGURG] = "urgent socket condition";
1798 ap_sys_siglist[SIGPOLL] = "Pollable event occurred";
1801 ap_sys_siglist[SIGIO] = "socket I/O possible";
1804 ap_sys_siglist[SIGSTOP] = "Stopped (signal)";
1807 ap_sys_siglist[SIGTSTP] = "Stopped";
1810 ap_sys_siglist[SIGCONT] = "Continued";
1813 ap_sys_siglist[SIGTTIN] = "Stopped (tty input)";
1816 ap_sys_siglist[SIGTTOU] = "Stopped (tty output)";
1819 ap_sys_siglist[SIGVTALRM] = "virtual timer expired";
1822 ap_sys_siglist[SIGPROF] = "profiling timer expired";
1825 ap_sys_siglist[SIGXCPU] = "exceeded cpu limit";
1828 ap_sys_siglist[SIGXFSZ] = "exceeded file size limit";
1830 for (sig=0; sig < sizeof(ap_sys_siglist)/sizeof(ap_sys_siglist[0]); ++sig)
1831 if (ap_sys_siglist[sig] == NULL)
1832 ap_sys_siglist[sig] = "";
1834 #endif /* platform has sys_siglist[] */
1837 /* handle all varieties of core dumping signals */
1838 static void sig_coredump(int sig)
1840 chdir(ap_coredump_dir);
1841 signal(sig, SIG_DFL);
1842 kill(getpid(), sig);
1843 /* At this point we've got sig blocked, because we're still inside
1844 * the signal handler. When we leave the signal handler it will
1845 * be unblocked, and we'll take the signal... and coredump or whatever
1846 * is appropriate for this particular Unix. In addition the parent
1847 * will see the real signal we received -- whereas if we called
1848 * abort() here, the parent would only see SIGABRT.
1852 /*****************************************************************
1853 * Connection structures and accounting...
1856 static void just_die(int sig)
1858 clean_child_exit(0);
1861 static int volatile deferred_die;
1862 static int volatile usr1_just_die;
1864 static void usr1_handler(int sig)
1866 if (usr1_just_die) {
1872 /* volatile just in case */
1873 static int volatile shutdown_pending;
1874 static int volatile restart_pending;
1875 static int volatile is_graceful;
1876 ap_generation_t volatile ap_my_generation=0;
1878 static void sig_term(int sig)
1880 if (shutdown_pending == 1) {
1881 /* Um, is this _probably_ not an error, if the user has
1882 * tried to do a shutdown twice quickly, so we won't
1883 * worry about reporting it.
1887 shutdown_pending = 1;
1890 static void restart(int sig)
1892 if (restart_pending == 1) {
1893 /* Probably not an error - don't bother reporting it */
1896 restart_pending = 1;
1897 is_graceful = sig == SIGUSR1;
1900 static void set_signals(void)
1902 #ifndef NO_USE_SIGACTION
1903 struct sigaction sa;
1905 sigemptyset(&sa.sa_mask);
1909 sa.sa_handler = sig_coredump;
1910 #if defined(SA_ONESHOT)
1911 sa.sa_flags = SA_ONESHOT;
1912 #elif defined(SA_RESETHAND)
1913 sa.sa_flags = SA_RESETHAND;
1915 if (sigaction(SIGSEGV, &sa, NULL) < 0)
1916 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf, "sigaction(SIGSEGV)");
1918 if (sigaction(SIGBUS, &sa, NULL) < 0)
1919 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf, "sigaction(SIGBUS)");
1922 if (sigaction(SIGABORT, &sa, NULL) < 0)
1923 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf, "sigaction(SIGABORT)");
1926 if (sigaction(SIGABRT, &sa, NULL) < 0)
1927 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf, "sigaction(SIGABRT)");
1930 if (sigaction(SIGILL, &sa, NULL) < 0)
1931 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf, "sigaction(SIGILL)");
1935 sa.sa_handler = sig_term;
1936 if (sigaction(SIGTERM, &sa, NULL) < 0)
1937 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf, "sigaction(SIGTERM)");
1939 if (sigaction(SIGINT, &sa, NULL) < 0)
1940 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf, "sigaction(SIGINT)");
1943 sa.sa_handler = SIG_DFL;
1944 if (sigaction(SIGXCPU, &sa, NULL) < 0)
1945 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf, "sigaction(SIGXCPU)");
1948 sa.sa_handler = SIG_DFL;
1949 if (sigaction(SIGXFSZ, &sa, NULL) < 0)
1950 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf, "sigaction(SIGXFSZ)");
1953 sa.sa_handler = SIG_IGN;
1954 if (sigaction(SIGPIPE, &sa, NULL) < 0)
1955 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf, "sigaction(SIGPIPE)");
1958 /* we want to ignore HUPs and USR1 while we're busy processing one */
1959 sigaddset(&sa.sa_mask, SIGHUP);
1960 sigaddset(&sa.sa_mask, SIGUSR1);
1961 sa.sa_handler = restart;
1962 if (sigaction(SIGHUP, &sa, NULL) < 0)
1963 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf, "sigaction(SIGHUP)");
1964 if (sigaction(SIGUSR1, &sa, NULL) < 0)
1965 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf, "sigaction(SIGUSR1)");
1968 signal(SIGSEGV, sig_coredump);
1970 signal(SIGBUS, sig_coredump);
1973 signal(SIGABORT, sig_coredump);
1974 #endif /* SIGABORT */
1976 signal(SIGABRT, sig_coredump);
1977 #endif /* SIGABRT */
1979 signal(SIGILL, sig_coredump);
1982 signal(SIGXCPU, SIG_DFL);
1983 #endif /* SIGXCPU */
1985 signal(SIGXFSZ, SIG_DFL);
1986 #endif /* SIGXFSZ */
1989 signal(SIGTERM, sig_term);
1991 signal(SIGHUP, restart);
1994 signal(SIGUSR1, restart);
1995 #endif /* SIGUSR1 */
1997 signal(SIGPIPE, SIG_IGN);
1998 #endif /* SIGPIPE */
2003 /*****************************************************************
2004 * Connection structures and accounting...
2008 static conn_rec *new_connection(pool *p, server_rec *server, BUFF *inout,
2009 const struct sockaddr_in *remaddr,
2010 const struct sockaddr_in *saddr,
2013 conn_rec *conn = (conn_rec *) ap_pcalloc(p, sizeof(conn_rec));
2015 /* Got a connection structure, so initialize what fields we can
2016 * (the rest are zeroed out by pcalloc).
2019 conn->child_num = child_num;
2022 conn->local_addr = *saddr;
2023 conn->base_server = server;
2024 conn->client = inout;
2026 conn->remote_addr = *remaddr;
2027 conn->remote_ip = ap_pstrdup(conn->pool,
2028 inet_ntoa(conn->remote_addr.sin_addr));
2033 #if defined(TCP_NODELAY) && !defined(MPE) && !defined(TPF)
2034 static void sock_disable_nagle(int s)
2036 /* The Nagle algorithm says that we should delay sending partial
2037 * packets in hopes of getting more data. We don't want to do
2038 * this; we are not telnet. There are bad interactions between
2039 * persistent connections and Nagle's algorithm that have very severe
2040 * performance penalties. (Failing to disable Nagle is not much of a
2041 * problem with simple HTTP.)
2043 * In spite of these problems, failure here is not a shooting offense.
2045 int just_say_no = 1;
2047 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
2049 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf,
2050 "setsockopt: (TCP_NODELAY)");
2055 #define sock_disable_nagle(s) /* NOOP */
2059 /*****************************************************************
2060 * Child process main loop.
2061 * The following vars are static to avoid getting clobbered by longjmp();
2062 * they are really private to child_main.
2067 static int requests_this_child;
2068 static fd_set main_fds;
2070 API_EXPORT(void) ap_child_terminate(request_rec *r)
2072 r->connection->keepalive = 0;
2073 requests_this_child = ap_max_requests_per_child = 1;
2076 int ap_graceful_stop_signalled(void)
2078 ap_sync_scoreboard_image();
2080 ap_scoreboard_image->global.running_generation != ap_my_generation) {
2086 static void child_main(int child_num_arg)
2089 struct sockaddr sa_server;
2090 struct sockaddr sa_client;
2092 ap_listen_rec *last_lr;
2094 conn_rec *current_conn;
2099 my_child_num = child_num_arg;
2100 requests_this_child = 0;
2103 /* Get a sub pool for global allocations in this child, so that
2104 * we can have cleanups occur when the child exits.
2106 pchild = ap_make_sub_pool(pconf);
2108 ptrans = ap_make_sub_pool(pchild);
2110 /* needs to be done before we switch UIDs so we have permissions */
2111 reopen_scoreboard(pchild);
2112 SAFE_ACCEPT(accept_mutex_child_init(pchild));
2114 if (unixd_setup_child()) {
2115 clean_child_exit(APEXIT_CHILDFATAL);
2118 ap_child_init_hook(pchild, server_conf);
2120 (void) ap_update_child_status(my_child_num, SERVER_READY, (request_rec *) NULL);
2122 signal(SIGHUP, just_die);
2123 signal(SIGTERM, just_die);
2126 /* Stop Ctrl-C/Ctrl-Break signals going to child processes */
2128 unsigned long ulTimes;
2129 DosSetSignalExceptionFocus(0, &ulTimes);
2133 while (!ap_graceful_stop_signalled()) {
2136 /* Prepare to receive a SIGUSR1 due to graceful restart so that
2137 * we can exit cleanly.
2140 signal(SIGUSR1, usr1_handler);
2143 * (Re)initialize this child to a pre-connection state.
2146 current_conn = NULL;
2148 ap_clear_pool(ptrans);
2150 if ((ap_max_requests_per_child > 0
2151 && requests_this_child++ >= ap_max_requests_per_child)) {
2152 clean_child_exit(0);
2155 (void) ap_update_child_status(my_child_num, SERVER_READY, (request_rec *) NULL);
2158 * Wait for an acceptable connection to arrive.
2161 /* Lock around "accept", if necessary */
2162 SAFE_ACCEPT(accept_mutex_on());
2165 if (ap_listeners->next) {
2166 /* more than one socket */
2167 memcpy(&main_fds, &listenfds, sizeof(fd_set));
2168 srv = ap_select(listenmaxfd + 1, &main_fds, NULL, NULL, NULL);
2170 if (srv < 0 && errno != EINTR) {
2171 /* Single Unix documents select as returning errnos
2172 * EBADF, EINTR, and EINVAL... and in none of those
2173 * cases does it make sense to continue. In fact
2174 * on Linux 2.0.x we seem to end up with EFAULT
2175 * occasionally, and we'd loop forever due to it.
2177 ap_log_error(APLOG_MARK, APLOG_ERR, server_conf, "select: (listen)");
2178 clean_child_exit(1);
2184 /* we remember the last_lr we searched last time around so that
2185 we don't end up starving any particular listening socket */
2186 if (last_lr == NULL) {
2192 while (lr != last_lr) {
2196 if (FD_ISSET(lr->fd, &main_fds)) break;
2199 if (lr == last_lr) {
2206 /* only one socket, just pretend we did the other stuff */
2207 sd = ap_listeners->fd;
2210 /* if we accept() something we don't want to die, so we have to
2216 /* we didn't get a socket, and we were told to die */
2217 clean_child_exit(0);
2219 clen = sizeof(sa_client);
2220 csd = ap_accept(sd, &sa_client, &clen);
2221 if (csd >= 0 || errno != EINTR)
2226 break; /* We have a socket ready for reading */
2229 /* Our old behaviour here was to continue after accept()
2230 * errors. But this leads us into lots of troubles
2231 * because most of the errors are quite fatal. For
2232 * example, EMFILE can be caused by slow descriptor
2233 * leaks (say in a 3rd party module, or libc). It's
2234 * foolish for us to continue after an EMFILE. We also
2235 * seem to tickle kernel bugs on some platforms which
2236 * lead to never-ending loops here. So it seems best
2237 * to just exit in most cases.
2241 /* EPROTO on certain older kernels really means
2242 * ECONNABORTED, so we need to ignore it for them.
2243 * See discussion in new-httpd archives nh.9701
2244 * search for EPROTO.
2246 * Also see nh.9603, search for EPROTO:
2247 * There is potentially a bug in Solaris 2.x x<6,
2248 * and other boxes that implement tcp sockets in
2249 * userland (i.e. on top of STREAMS). On these
2250 * systems, EPROTO can actually result in a fatal
2251 * loop. See PR#981 for example. It's hard to
2252 * handle both uses of EPROTO.
2259 /* Linux generates the rest of these, other tcp
2260 * stacks (i.e. bsd) tend to hide them behind
2261 * getsockopt() interfaces. They occur when
2262 * the net goes sour or the client disconnects
2263 * after the three-way handshake has been done
2264 * in the kernel but before userland has picked
2282 ap_log_error(APLOG_MARK, APLOG_EMERG, server_conf,
2283 "offload device inactive");
2284 clean_child_exit(APEXIT_CHILDFATAL);
2287 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, server_conf,
2288 "select/accept error (%u)", errno);
2289 clean_child_exit(APEXIT_CHILDFATAL);
2292 ap_log_error(APLOG_MARK, APLOG_ERR, server_conf,
2293 "accept: (client socket)");
2294 clean_child_exit(1);
2299 if (ap_graceful_stop_signalled()) {
2300 clean_child_exit(0);
2305 SAFE_ACCEPT(accept_mutex_off()); /* unlock after "accept" */
2308 if (csd == 0) /* 0 is invalid socket for TPF */
2312 /* We've got a socket, let's at least process one request off the
2313 * socket before we accept a graceful restart request. We set
2314 * the signal to ignore because we don't want to disturb any
2317 signal(SIGUSR1, SIG_IGN);
2320 * We now have a connection, so set it up with the appropriate
2321 * socket options, file descriptors, and read/write buffers.
2324 clen = sizeof(sa_server);
2325 if (getsockname(csd, &sa_server, &clen) < 0) {
2326 ap_log_error(APLOG_MARK, APLOG_ERR, server_conf, "getsockname");
2331 sock_disable_nagle(csd);
2333 iol = unix_attach_socket(csd);
2335 if (errno == EBADF) {
2336 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, NULL,
2337 "filedescriptor (%u) larger than FD_SETSIZE (%u) "
2338 "found, you probably need to rebuild Apache with a "
2339 "larger FD_SETSIZE", csd, FD_SETSIZE);
2342 ap_log_error(APLOG_MARK, APLOG_WARNING, NULL,
2343 "error attaching to socket");
2349 (void) ap_update_child_status(my_child_num, SERVER_BUSY_READ,
2350 (request_rec *) NULL);
2352 conn_io = ap_bcreate(ptrans, B_RDWR);
2354 ap_bpush_iol(conn_io, iol);
2356 current_conn = new_connection(ptrans, server_conf, conn_io,
2357 (struct sockaddr_in *) &sa_client,
2358 (struct sockaddr_in *) &sa_server,
2361 ap_process_connection(current_conn);
2366 static int make_child(server_rec *s, int slot, time_t now)
2370 if (slot + 1 > max_daemons_limit) {
2371 max_daemons_limit = slot + 1;
2375 signal(SIGHUP, just_die);
2376 signal(SIGINT, just_die);
2378 signal(SIGQUIT, SIG_DFL);
2380 signal(SIGTERM, just_die);
2384 (void) ap_update_child_status(slot, SERVER_STARTING, (request_rec *) NULL);
2388 /* BS2000 requires a "special" version of fork() before a setuid() call */
2389 if ((pid = os_fork(unixd_config.user_name)) == -1) {
2391 if ((pid = os_fork(s, slot)) == -1) {
2393 if ((pid = fork()) == -1) {
2395 ap_log_error(APLOG_MARK, APLOG_ERR, s, "fork: Unable to fork new process");
2397 /* fork didn't succeed. Fix the scoreboard or else
2398 * it will say SERVER_STARTING forever and ever
2400 (void) ap_update_child_status(slot, SERVER_DEAD, (request_rec *) NULL);
2402 /* In case system resources are maxxed out, we don't want
2403 Apache running away with the CPU trying to fork over and
2404 over and over again. */
2411 #ifdef AIX_BIND_PROCESSOR
2412 /* by default AIX binds to a single processor
2413 * this bit unbinds children which will then bind to another cpu
2415 #include <sys/processor.h>
2416 int status = bindprocessor(BINDPROCESS, (int)getpid(),
2417 PROCESSOR_CLASS_ANY);
2419 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, server_conf,
2420 "processor unbind failed %d", status);
2423 RAISE_SIGSTOP(MAKE_CHILD);
2424 /* Disable the restart signal handlers and enable the just_die stuff.
2425 * Note that since restart() just notes that a restart has been
2426 * requested there's no race condition here.
2428 signal(SIGHUP, just_die);
2429 signal(SIGUSR1, just_die);
2430 signal(SIGTERM, just_die);
2434 ap_scoreboard_image->parent[slot].pid = pid;
2435 #ifdef SCOREBOARD_FILE
2436 lseek(scoreboard_fd, XtOffsetOf(scoreboard, parent[slot]), 0);
2437 force_write(scoreboard_fd, &ap_scoreboard_image->parent[slot],
2438 sizeof(parent_score));
2445 /* start up a bunch of children */
2446 static void startup_children(int number_to_start)
2449 time_t now = time(0);
2451 for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
2452 if (ap_scoreboard_image->servers[i].status != SERVER_DEAD) {
2455 if (make_child(server_conf, i, now) < 0) {
2464 * idle_spawn_rate is the number of children that will be spawned on the
2465 * next maintenance cycle if there aren't enough idle servers. It is
2466 * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
2467 * without the need to spawn.
2469 static int idle_spawn_rate = 1;
2470 #ifndef MAX_SPAWN_RATE
2471 #define MAX_SPAWN_RATE (32)
2473 static int hold_off_on_exponential_spawning;
2475 static void perform_idle_server_maintenance(void)
2481 time_t now = time(0);
2483 int free_slots[MAX_SPAWN_RATE];
2487 /* initialize the free_list */
2495 ap_sync_scoreboard_image();
2496 for (i = 0; i < ap_daemons_limit; ++i) {
2499 if (i >= max_daemons_limit && free_length == idle_spawn_rate)
2501 ss = &ap_scoreboard_image->servers[i];
2502 status = ss->status;
2503 if (status == SERVER_DEAD) {
2504 /* try to keep children numbers as low as possible */
2505 if (free_length < idle_spawn_rate) {
2506 free_slots[free_length] = i;
2511 /* We consider a starting server as idle because we started it
2512 * at least a cycle ago, and if it still hasn't finished starting
2513 * then we're just going to swamp things worse by forking more.
2514 * So we hopefully won't need to fork more if we count it.
2515 * This depends on the ordering of SERVER_READY and SERVER_STARTING.
2517 if (status <= SERVER_READY) {
2519 /* always kill the highest numbered child if we have to...
2520 * no really well thought out reason ... other than observing
2521 * the server behaviour under linux where lower numbered children
2522 * tend to service more hits (and hence are more likely to have
2523 * their data in cpu caches).
2532 max_daemons_limit = last_non_dead + 1;
2533 if (idle_count > ap_daemons_max_free) {
2534 /* kill off one child... we use SIGUSR1 because that'll cause it to
2535 * shut down gracefully, in case it happened to pick up a request
2536 * while we were counting
2538 kill(ap_scoreboard_image->parent[to_kill].pid, SIGUSR1);
2539 idle_spawn_rate = 1;
2541 else if (idle_count < ap_daemons_min_free) {
2542 /* terminate the free list */
2543 if (free_length == 0) {
2544 /* only report this condition once */
2545 static int reported = 0;
2548 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, server_conf,
2549 "server reached MaxClients setting, consider"
2550 " raising the MaxClients setting");
2553 idle_spawn_rate = 1;
2556 if (idle_spawn_rate >= 8) {
2557 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, server_conf,
2558 "server seems busy, (you may need "
2559 "to increase StartServers, or Min/MaxSpareServers), "
2560 "spawning %d children, there are %d idle, and "
2561 "%d total children", idle_spawn_rate,
2562 idle_count, total_non_dead);
2564 for (i = 0; i < free_length; ++i) {
2566 if(make_child(server_conf, free_slots[i], now) == -1) {
2567 if(free_length == 1) {
2568 shutdown_pending = 1;
2569 ap_log_error(APLOG_MARK, APLOG_EMERG, server_conf,
2570 "No active child processes: shutting down");
2574 make_child(server_conf, free_slots[i], now);
2577 /* the next time around we want to spawn twice as many if this
2578 * wasn't good enough, but not if we've just done a graceful
2580 if (hold_off_on_exponential_spawning) {
2581 --hold_off_on_exponential_spawning;
2583 else if (idle_spawn_rate < MAX_SPAWN_RATE) {
2584 idle_spawn_rate *= 2;
2589 idle_spawn_rate = 1;
2594 static void process_child_status(int pid, ap_wait_t status)
2596 /* Child died... if it died due to a fatal error,
2597 * we should simply bail out.
2599 if ((WIFEXITED(status)) &&
2600 WEXITSTATUS(status) == APEXIT_CHILDFATAL) {
2601 ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_NOERRNO, server_conf,
2602 "Child %d returned a Fatal error... \n"
2603 "Apache is exiting!",
2605 exit(APEXIT_CHILDFATAL);
2607 if (WIFSIGNALED(status)) {
2608 switch (WTERMSIG(status)) {
2617 if (WCOREDUMP(status)) {
2618 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
2620 "child pid %d exit signal %s (%d), "
2621 "possible coredump in %s",
2622 pid, (WTERMSIG(status) >= NumSIG) ? "" :
2623 SYS_SIGLIST[WTERMSIG(status)], WTERMSIG(status),
2628 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
2630 "child pid %d exit signal %s (%d)", pid,
2631 SYS_SIGLIST[WTERMSIG(status)], WTERMSIG(status));
2636 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
2638 "child pid %d exit signal %d",
2639 pid, WTERMSIG(status));
2646 static int setup_listeners(pool *pconf, server_rec *s)
2650 if (ap_listen_open(pconf, s->port)) {
2651 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT, s,
2652 "no listening sockets available, shutting down");
2657 FD_ZERO(&listenfds);
2658 for (lr = ap_listeners; lr; lr = lr->next) {
2659 FD_SET(lr->fd, &listenfds);
2660 if (lr->fd > listenmaxfd) {
2661 listenmaxfd = lr->fd;
2668 /*****************************************************************
2669 * Executive routines.
2672 int ap_mpm_run(pool *_pconf, pool *plog, server_rec *s)
2674 int remaining_children_to_start;
2680 ap_log_pid(pconf, ap_pid_fname);
2682 if (setup_listeners(pconf, s)) {
2683 /* XXX: hey, what's the right way for the mpm to indicate a fatal error? */
2687 SAFE_ACCEPT(accept_mutex_init(pconf));
2689 reinit_scoreboard(pconf);
2691 #ifdef SCOREBOARD_FILE
2693 ap_scoreboard_fname = ap_server_root_relative(pconf, ap_scoreboard_fname);
2694 ap_note_cleanups_for_fd(pconf, scoreboard_fd);
2700 if (ap_daemons_max_free < ap_daemons_min_free + 1) /* Don't thrash... */
2701 ap_daemons_max_free = ap_daemons_min_free + 1;
2703 /* If we're doing a graceful_restart then we're going to see a lot
2704 * of children exiting immediately when we get into the main loop
2705 * below (because we just sent them SIGUSR1). This happens pretty
2706 * rapidly... and for each one that exits we'll start a new one until
2707 * we reach at least daemons_min_free. But we may be permitted to
2708 * start more than that, so we'll just keep track of how many we're
2709 * supposed to start up without the 1 second penalty between each fork.
2711 remaining_children_to_start = ap_daemons_to_start;
2712 if (remaining_children_to_start > ap_daemons_limit) {
2713 remaining_children_to_start = ap_daemons_limit;
2716 startup_children(remaining_children_to_start);
2717 remaining_children_to_start = 0;
2720 /* give the system some time to recover before kicking into
2721 * exponential mode */
2722 hold_off_on_exponential_spawning = 10;
2725 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, server_conf,
2726 "%s configured -- resuming normal operations",
2727 ap_get_server_version());
2728 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, server_conf,
2729 "Server built: %s", ap_get_server_built());
2730 restart_pending = shutdown_pending = 0;
2732 while (!restart_pending && !shutdown_pending) {
2735 int pid = wait_or_timeout(&status);
2737 /* XXX: if it takes longer than 1 second for all our children
2738 * to start up and get into IDLE state then we may spawn an
2742 process_child_status(pid, status);
2743 /* non-fatal death... note that it's gone in the scoreboard. */
2744 ap_sync_scoreboard_image();
2745 child_slot = find_child_by_pid(pid);
2746 if (child_slot >= 0) {
2747 (void) ap_update_child_status(child_slot, SERVER_DEAD,
2748 (request_rec *) NULL);
2749 if (remaining_children_to_start
2750 && child_slot < ap_daemons_limit) {
2751 /* we're still doing a 1-for-1 replacement of dead
2752 * children with new children
2754 make_child(server_conf, child_slot, time(0));
2755 --remaining_children_to_start;
2757 #ifdef HAS_OTHER_CHILD
2759 else if (reap_other_child(pid, status) == 0) {
2763 else if (is_graceful) {
2764 /* Great, we've probably just lost a slot in the
2765 * scoreboard. Somehow we don't know about this
2768 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, server_conf,
2769 "long lost child came home! (pid %d)", pid);
2771 /* Don't perform idle maintenance when a child dies,
2772 * only do it when there's a timeout. Remember only a
2773 * finite number of children can die, and it's pretty
2774 * pathological for a lot to die suddenly.
2778 else if (remaining_children_to_start) {
2779 /* we hit a 1 second timeout in which none of the previous
2780 * generation of children needed to be reaped... so assume
2781 * they're all done, and pick up the slack if any is left.
2783 startup_children(remaining_children_to_start);
2784 remaining_children_to_start = 0;
2785 /* In any event we really shouldn't do the code below because
2786 * few of the servers we just started are in the IDLE state
2787 * yet, so we'd mistakenly create an extra server.
2792 perform_idle_server_maintenance();
2794 shutdown_pending = os_check_server(tpf_server_name);
2800 if (shutdown_pending) {
2801 /* Time to gracefully shut down:
2802 * Kill child processes, tell them to call child_exit, etc...
2804 if (ap_killpg(getpgrp(), SIGTERM) < 0) {
2805 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf, "killpg SIGTERM");
2807 reclaim_child_processes(1); /* Start with SIGTERM */
2809 /* cleanup pid file on normal shutdown */
2811 const char *pidfile = NULL;
2812 pidfile = ap_server_root_relative (pconf, ap_pid_fname);
2813 if ( pidfile != NULL && unlink(pidfile) == 0)
2814 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO,
2816 "removed PID file %s (pid=%ld)",
2817 pidfile, (long)getpid());
2820 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, server_conf,
2821 "caught SIGTERM, shutting down");
2825 /* we've been told to restart */
2826 signal(SIGHUP, SIG_IGN);
2827 signal(SIGUSR1, SIG_IGN);
2830 /* not worth thinking about */
2834 /* advance to the next generation */
2835 /* XXX: we really need to make sure this new generation number isn't in
2836 * use by any of the children.
2839 ap_scoreboard_image->global.running_generation = ap_my_generation;
2840 update_scoreboard_global();
2843 #ifndef SCOREBOARD_FILE
2846 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, server_conf,
2847 "SIGUSR1 received. Doing graceful restart");
2849 /* kill off the idle ones */
2850 if (ap_killpg(getpgrp(), SIGUSR1) < 0) {
2851 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf, "killpg SIGUSR1");
2853 #ifndef SCOREBOARD_FILE
2854 /* This is mostly for debugging... so that we know what is still
2855 * gracefully dealing with existing request. But we can't really
2856 * do it if we're in a SCOREBOARD_FILE because it'll cause
2857 * corruption too easily.
2859 ap_sync_scoreboard_image();
2860 for (i = 0; i < ap_daemons_limit; ++i) {
2861 if (ap_scoreboard_image->servers[i].status != SERVER_DEAD) {
2862 ap_scoreboard_image->servers[i].status = SERVER_GRACEFUL;
2869 if (ap_killpg(getpgrp(), SIGHUP) < 0) {
2870 ap_log_error(APLOG_MARK, APLOG_WARNING, server_conf, "killpg SIGHUP");
2872 reclaim_child_processes(0); /* Not when just starting up */
2873 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, server_conf,
2874 "SIGHUP received. Attempting to restart");
2878 ap_restart_time = time(NULL);
2884 static void prefork_pre_command_line(pool *pcommands)
2890 /* TODO: set one_process properly */ one_process = 0;
2893 static void prefork_pre_config(pool *pconf, pool *plog, pool *ptemp)
2895 static int restart_num = 0;
2897 one_process = ap_exists_config_define("ONE_PROCESS");
2899 /* sigh, want this only the second time around */
2900 if (restart_num++ == 1) {
2911 ap_listen_pre_config();
2912 ap_daemons_to_start = DEFAULT_START_DAEMON;
2913 ap_daemons_min_free = DEFAULT_MIN_FREE_DAEMON;
2914 ap_daemons_max_free = DEFAULT_MAX_FREE_DAEMON;
2915 ap_daemons_limit = HARD_SERVER_LIMIT;
2916 ap_pid_fname = DEFAULT_PIDLOG;
2917 ap_scoreboard_fname = DEFAULT_SCOREBOARD;
2918 ap_lock_fname = DEFAULT_LOCKFILE;
2919 ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
2920 ap_extended_status = 0;
2922 ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
2925 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg)
2927 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2932 if (cmd->server->is_virtual) {
2933 return "PidFile directive not allowed in <VirtualHost>";
2939 static const char *set_scoreboard(cmd_parms *cmd, void *dummy, char *arg)
2941 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2946 ap_scoreboard_fname = arg;
2950 static const char *set_lockfile(cmd_parms *cmd, void *dummy, char *arg)
2952 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2957 ap_lock_fname = arg;
2961 static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, char *arg)
2963 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2968 ap_daemons_to_start = atoi(arg);
2972 static const char *set_min_free_servers(cmd_parms *cmd, void *dummy, char *arg)
2974 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2979 ap_daemons_min_free = atoi(arg);
2980 if (ap_daemons_min_free <= 0) {
2981 fprintf(stderr, "WARNING: detected MinSpareServers set to non-positive.\n");
2982 fprintf(stderr, "Resetting to 1 to avoid almost certain Apache failure.\n");
2983 fprintf(stderr, "Please read the documentation.\n");
2984 ap_daemons_min_free = 1;
2990 static const char *set_max_free_servers(cmd_parms *cmd, void *dummy, char *arg)
2992 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2997 ap_daemons_max_free = atoi(arg);
3001 static const char *set_server_limit (cmd_parms *cmd, void *dummy, char *arg)
3003 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
3008 ap_daemons_limit = atoi(arg);
3009 if (ap_daemons_limit > HARD_SERVER_LIMIT) {
3010 fprintf(stderr, "WARNING: MaxClients of %d exceeds compile time limit "
3011 "of %d servers,\n", ap_daemons_limit, HARD_SERVER_LIMIT);
3012 fprintf(stderr, " lowering MaxClients to %d. To increase, please "
3013 "see the\n", HARD_SERVER_LIMIT);
3014 fprintf(stderr, " HARD_SERVER_LIMIT define in src/include/httpd.h.\n");
3015 ap_daemons_limit = HARD_SERVER_LIMIT;
3017 else if (ap_daemons_limit < 1) {
3018 fprintf(stderr, "WARNING: Require MaxClients > 0, setting to 1\n");
3019 ap_daemons_limit = 1;
3024 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg)
3026 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
3031 ap_max_requests_per_child = atoi(arg);
3036 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg)
3040 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
3045 fname = ap_server_root_relative(cmd->pool, arg);
3046 /* ZZZ change this to the AP func FileInfo*/
3047 if ((stat(fname, &finfo) == -1) || !S_ISDIR(finfo.st_mode)) {
3048 return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
3049 " does not exist or is not a directory", NULL);
3051 ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
3055 /* there are no threads in the prefork model, so the mutexes are
3057 /* TODO: make these #defines to eliminate the function call */
3059 struct ap_thread_mutex {
3063 API_EXPORT(ap_thread_mutex *) ap_thread_mutex_new(void)
3065 return malloc(sizeof(ap_thread_mutex));
3068 API_EXPORT(void) ap_thread_mutex_lock(ap_thread_mutex *mtx)
3072 API_EXPORT(void) ap_thread_mutex_unlock(ap_thread_mutex *mtx)
3076 API_EXPORT(void) ap_thread_mutex_destroy(ap_thread_mutex *mtx)
3082 static const command_rec prefork_cmds[] = {
3083 UNIX_DAEMON_COMMANDS
3085 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
3086 "A file for logging the server process ID"},
3087 { "ScoreBoardFile", set_scoreboard, NULL, RSRC_CONF, TAKE1,
3088 "A file for Apache to maintain runtime process management information"},
3089 { "LockFile", set_lockfile, NULL, RSRC_CONF, TAKE1,
3090 "The lockfile used when Apache needs to lock the accept() call"},
3091 { "StartServers", set_daemons_to_start, NULL, RSRC_CONF, TAKE1,
3092 "Number of child processes launched at server startup" },
3093 { "MinSpareServers", set_min_free_servers, NULL, RSRC_CONF, TAKE1,
3094 "Minimum number of idle children, to handle request spikes" },
3095 { "MaxSpareServers", set_max_free_servers, NULL, RSRC_CONF, TAKE1,
3096 "Maximum number of idle children" },
3097 { "MaxClients", set_server_limit, NULL, RSRC_CONF, TAKE1,
3098 "Maximum number of children alive at the same time" },
3099 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
3100 "Maximum number of requests a particular child serves before dying." },
3101 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
3102 "The location of the directory Apache changes to before dumping core" },
3106 module MODULE_VAR_EXPORT mpm_prefork_module = {
3107 STANDARD20_MODULE_STUFF,
3108 prefork_pre_command_line, /* pre_command_line */
3109 prefork_pre_config, /* pre_config */
3110 NULL, /* post_config */
3111 NULL, /* open_logs */
3112 NULL, /* child_init */
3113 NULL, /* create per-directory config structure */
3114 NULL, /* merge per-directory config structures */
3115 NULL, /* create per-server config structure */
3116 NULL, /* merge per-server config structures */
3117 prefork_cmds, /* command table */
3118 NULL, /* handlers */
3119 NULL, /* translate_handler */
3120 NULL, /* check_user_id */
3121 NULL, /* check auth */
3122 NULL, /* check access */
3123 NULL, /* type_checker */
3124 NULL, /* pre-run fixups */
3126 NULL, /* header parser */
3127 NULL /* post_read_request */