upload http
[bottlenecks.git] / rubbos / app / httpd-2.0.64 / server / mpm_common.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /* The purpose of this file is to store the code that MOST mpm's will need
18  * this does not mean a function only goes into this file if every MPM needs
19  * it.  It means that if a function is needed by more than one MPM, and
20  * future maintenance would be served by making the code common, then the
21  * function belongs here.
22  *
23  * This is going in src/main because it is not platform specific, it is
24  * specific to multi-process servers, but NOT to Unix.  Which is why it
25  * does not belong in src/os/unix
26  */
27
28 #include "apr.h"
29 #include "apr_thread_proc.h"
30 #include "apr_signal.h"
31 #include "apr_strings.h"
32 #define APR_WANT_STRFUNC
33 #include "apr_want.h"
34 #include "apr_getopt.h"
35 #include "apr_optional.h"
36 #include "apr_allocator.h"
37
38 #include "httpd.h"
39 #include "http_config.h"
40 #include "http_log.h"
41 #include "http_main.h"
42 #include "mpm.h"
43 #include "mpm_common.h"
44 #include "ap_mpm.h"
45 #include "ap_listen.h"
46 #include "mpm_default.h"
47
48 #ifdef AP_MPM_WANT_SET_SCOREBOARD
49 #include "scoreboard.h"
50 #endif
51
52 #ifdef HAVE_PWD_H
53 #include <pwd.h>
54 #endif
55 #ifdef HAVE_GRP_H
56 #include <grp.h>
57 #endif
58 #if APR_HAVE_UNISTD_H
59 #include <unistd.h>
60 #endif
61
62 #ifdef AP_MPM_WANT_RECLAIM_CHILD_PROCESSES
63
64 typedef enum {DO_NOTHING, SEND_SIGTERM, SEND_SIGKILL, GIVEUP} action_t;
65
66 typedef struct extra_process_t {
67     struct extra_process_t *next;
68     pid_t pid;
69 } extra_process_t;
70
71 static extra_process_t *extras;
72
73 void ap_register_extra_mpm_process(pid_t pid)
74 {
75     extra_process_t *p = (extra_process_t *)malloc(sizeof(extra_process_t));
76
77     p->next = extras;
78     p->pid = pid;
79     extras = p;
80 }
81
82 int ap_unregister_extra_mpm_process(pid_t pid)
83 {
84     extra_process_t *cur = extras;
85     extra_process_t *prev = NULL;
86
87     while (cur && cur->pid != pid) {
88         prev = cur;
89         cur = cur->next;
90     }
91
92     if (cur) {
93         if (prev) {
94             prev->next = cur->next;
95         }
96         else {
97             extras = cur->next;
98         }
99         free(cur);
100         return 1; /* found */
101     }
102     else {
103         /* we don't know about any such process */
104         return 0;
105     }
106 }
107
108 static int reclaim_one_pid(pid_t pid, action_t action)
109 {
110     apr_proc_t proc;
111     apr_status_t waitret;
112
113     /* Ensure pid sanity. */
114     if (pid < 1) {
115         return 1;
116     }        
117
118     proc.pid = pid;
119     waitret = apr_proc_wait(&proc, NULL, NULL, APR_NOWAIT);
120     if (waitret != APR_CHILD_NOTDONE) {
121         return 1;
122     }
123
124     switch(action) {
125     case DO_NOTHING:
126         break;
127         
128     case SEND_SIGTERM:
129         /* ok, now it's being annoying */
130         ap_log_error(APLOG_MARK, APLOG_WARNING,
131                      0, ap_server_conf,
132                      "child process %" APR_PID_T_FMT
133                      " still did not exit, "
134                      "sending a SIGTERM",
135                      pid);
136         kill(pid, SIGTERM);
137         break;
138         
139     case SEND_SIGKILL:
140         ap_log_error(APLOG_MARK, APLOG_ERR,
141                      0, ap_server_conf,
142                      "child process %" APR_PID_T_FMT
143                      " still did not exit, "
144                      "sending a SIGKILL",
145                      pid);
146 #ifndef BEOS
147         kill(pid, SIGKILL);
148 #else
149         /* sending a SIGKILL kills the entire team on BeOS, and as
150          * httpd thread is part of that team it removes any chance
151          * of ever doing a restart.  To counter this I'm changing to
152          * use a kinder, gentler way of killing a specific thread
153          * that is just as effective.
154          */
155         kill_thread(pid);
156 #endif
157         break;
158                 
159     case GIVEUP:
160         /* gave it our best shot, but alas...  If this really
161          * is a child we are trying to kill and it really hasn't
162          * exited, we will likely fail to bind to the port
163          * after the restart.
164          */
165         ap_log_error(APLOG_MARK, APLOG_ERR,
166                      0, ap_server_conf,
167                      "could not make child process %" APR_PID_T_FMT
168                      " exit, "
169                      "attempting to continue anyway",
170                      pid);
171         break;
172     }
173     
174     return 0;
175 }
176
177 void ap_reclaim_child_processes(int terminate)
178 {
179     apr_time_t waittime = 1024 * 16;
180     int i;
181     extra_process_t *cur_extra;
182     int not_dead_yet;
183     int max_daemons;
184     apr_time_t starttime = apr_time_now();
185     /* this table of actions and elapsed times tells what action is taken
186      * at which elapsed time from starting the reclaim
187      */
188     struct {
189         action_t action;
190         apr_time_t action_time;
191     } action_table[] = {
192         {DO_NOTHING, 0}, /* dummy entry for iterations where we reap
193                           * children but take no action against
194                           * stragglers
195                           */
196         {SEND_SIGTERM, apr_time_from_sec(3)},
197         {SEND_SIGTERM, apr_time_from_sec(5)},
198         {SEND_SIGTERM, apr_time_from_sec(7)},
199         {SEND_SIGKILL, apr_time_from_sec(9)},
200         {GIVEUP,       apr_time_from_sec(10)}
201     };
202     int cur_action;      /* index of action we decided to take this
203                           * iteration
204                           */
205     int next_action = 1; /* index of first real action */
206
207     ap_mpm_query(AP_MPMQ_MAX_DAEMON_USED, &max_daemons);
208
209     do {
210         apr_sleep(waittime);
211         /* don't let waittime get longer than 1 second; otherwise, we don't
212          * react quickly to the last child exiting, and taking action can
213          * be delayed
214          */
215         waittime = waittime * 4;
216         if (waittime > apr_time_from_sec(1)) {
217             waittime = apr_time_from_sec(1);
218         }
219
220         /* see what action to take, if any */
221         if (action_table[next_action].action_time <= apr_time_now() - starttime) {
222             cur_action = next_action;
223             ++next_action;
224         }
225         else {
226             cur_action = 0; /* nothing to do */
227         }
228
229         /* now see who is done */
230         not_dead_yet = 0;
231         for (i = 0; i < max_daemons; ++i) {
232             pid_t pid = MPM_CHILD_PID(i);
233
234             if (pid == 0) {
235                 continue; /* not every scoreboard entry is in use */
236             }
237
238             if (reclaim_one_pid(pid, action_table[cur_action].action)) {
239                 MPM_NOTE_CHILD_KILLED(i);
240             }
241             else {
242                 ++not_dead_yet;
243             }
244         }
245  
246         cur_extra = extras;
247         while (cur_extra) {
248             extra_process_t *next = cur_extra->next;
249
250             if (reclaim_one_pid(cur_extra->pid, action_table[cur_action].action)) {
251                 AP_DEBUG_ASSERT(1 == ap_unregister_extra_mpm_process(cur_extra->pid));
252             }
253             else {
254                 ++not_dead_yet;
255             }
256             cur_extra = next;
257         }
258
259 #if APR_HAS_OTHER_CHILD
260         apr_proc_other_child_check();
261 #endif
262
263     } while (not_dead_yet > 0 &&
264              action_table[cur_action].action != GIVEUP);
265 }
266 #endif /* AP_MPM_WANT_RECLAIM_CHILD_PROCESSES */
267
268 #ifdef AP_MPM_WANT_WAIT_OR_TIMEOUT
269
270 /* number of calls to wait_or_timeout between writable probes */
271 #ifndef INTERVAL_OF_WRITABLE_PROBES
272 #define INTERVAL_OF_WRITABLE_PROBES 10
273 #endif
274 static int wait_or_timeout_counter;
275
276 void ap_wait_or_timeout(apr_exit_why_e *status, int *exitcode, apr_proc_t *ret,
277                         apr_pool_t *p)
278 {
279     apr_status_t rv;
280
281     ++wait_or_timeout_counter;
282     if (wait_or_timeout_counter == INTERVAL_OF_WRITABLE_PROBES) {
283         wait_or_timeout_counter = 0;
284     }
285
286     rv = apr_proc_wait_all_procs(ret, exitcode, status, APR_NOWAIT, p);
287     if (APR_STATUS_IS_EINTR(rv)) {
288         ret->pid = -1;
289         return;
290     }
291
292     if (APR_STATUS_IS_CHILD_DONE(rv)) {
293         return;
294     }
295
296 #ifdef NEED_WAITPID
297     if ((ret = reap_children(exitcode, status)) > 0) {
298         return;
299     }
300 #endif
301
302     apr_sleep(SCOREBOARD_MAINTENANCE_INTERVAL);
303     ret->pid = -1;
304     return;
305 }
306 #endif /* AP_MPM_WANT_WAIT_OR_TIMEOUT */
307
308 #ifdef AP_MPM_WANT_PROCESS_CHILD_STATUS
309 int ap_process_child_status(apr_proc_t *pid, apr_exit_why_e why, int status)
310 {
311     int signum = status;
312     const char *sigdesc = apr_signal_description_get(signum);
313
314     /* Child died... if it died due to a fatal error,
315      * we should simply bail out.  The caller needs to
316      * check for bad rc from us and exit, running any
317      * appropriate cleanups.
318      *
319      * If the child died due to a resource shortage, 
320      * the parent should limit the rate of forking
321      */
322     if (APR_PROC_CHECK_EXIT(why)) {
323         if (status == APEXIT_CHILDSICK) {
324             return status;
325         }
326
327         if (status == APEXIT_CHILDFATAL) {
328             ap_log_error(APLOG_MARK, APLOG_ALERT,
329                          0, ap_server_conf,
330                          "Child %" APR_PID_T_FMT
331                          " returned a Fatal error... Apache is exiting!",
332                          pid->pid);
333             return APEXIT_CHILDFATAL;
334         }
335
336         return 0;
337     }
338
339     if (APR_PROC_CHECK_SIGNALED(why)) {
340         switch (signum) {
341         case SIGTERM:
342         case SIGHUP:
343         case AP_SIG_GRACEFUL:
344         case SIGKILL:
345             break;
346
347         default:
348             if (APR_PROC_CHECK_CORE_DUMP(why)) {
349                 ap_log_error(APLOG_MARK, APLOG_NOTICE,
350                              0, ap_server_conf,
351                              "child pid %ld exit signal %s (%d), "
352                              "possible coredump in %s",
353                              (long)pid->pid, sigdesc, signum,
354                              ap_coredump_dir);
355             }
356             else {
357                 ap_log_error(APLOG_MARK, APLOG_NOTICE,
358                              0, ap_server_conf,
359                              "child pid %ld exit signal %s (%d)",
360                              (long)pid->pid, sigdesc, signum);
361             }
362         }
363     }
364     return 0;
365 }
366 #endif /* AP_MPM_WANT_PROCESS_CHILD_STATUS */
367
368 #if defined(TCP_NODELAY) && !defined(MPE) && !defined(TPF)
369 void ap_sock_disable_nagle(apr_socket_t *s)
370 {
371     /* The Nagle algorithm says that we should delay sending partial
372      * packets in hopes of getting more data.  We don't want to do
373      * this; we are not telnet.  There are bad interactions between
374      * persistent connections and Nagle's algorithm that have very severe
375      * performance penalties.  (Failing to disable Nagle is not much of a
376      * problem with simple HTTP.)
377      *
378      * In spite of these problems, failure here is not a shooting offense.
379      */
380     apr_status_t status = apr_socket_opt_set(s, APR_TCP_NODELAY, 1);
381
382     if (status != APR_SUCCESS) {
383         ap_log_error(APLOG_MARK, APLOG_WARNING, status, ap_server_conf,
384                      "apr_socket_opt_set: (TCP_NODELAY)");
385     }
386 }
387 #endif
388
389 #ifdef HAVE_GETPWNAM
390 AP_DECLARE(uid_t) ap_uname2id(const char *name)
391 {
392     struct passwd *ent;
393
394     if (name[0] == '#')
395         return (atoi(&name[1]));
396
397     if (!(ent = getpwnam(name))) {
398         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
399                      "%s: bad user name %s", ap_server_argv0, name);
400         exit(1);
401     }
402
403     return (ent->pw_uid);
404 }
405 #endif
406
407 #ifdef HAVE_GETGRNAM
408 AP_DECLARE(gid_t) ap_gname2id(const char *name)
409 {
410     struct group *ent;
411
412     if (name[0] == '#')
413         return (atoi(&name[1]));
414
415     if (!(ent = getgrnam(name))) {
416         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
417                      "%s: bad group name %s", ap_server_argv0, name);
418         exit(1);
419     }
420
421     return (ent->gr_gid);
422 }
423 #endif
424
425 #ifndef HAVE_INITGROUPS
426 int initgroups(const char *name, gid_t basegid)
427 {
428 #if defined(QNX) || defined(MPE) || defined(BEOS) || defined(_OSD_POSIX) || defined(TPF) || defined(__TANDEM) || defined(OS2) || defined(WIN32) || defined(NETWARE)
429 /* QNX, MPE and BeOS do not appear to support supplementary groups. */
430     return 0;
431 #else /* ndef QNX */
432     gid_t groups[NGROUPS_MAX];
433     struct group *g;
434     int index = 0;
435
436     setgrent();
437
438     groups[index++] = basegid;
439
440     while (index < NGROUPS_MAX && ((g = getgrent()) != NULL)) {
441         if (g->gr_gid != basegid) {
442             char **names;
443
444             for (names = g->gr_mem; *names != NULL; ++names) {
445                 if (!strcmp(*names, name))
446                     groups[index++] = g->gr_gid;
447             }
448         }
449     }
450
451     endgrent();
452
453     return setgroups(index, groups);
454 #endif /* def QNX */
455 }
456 #endif /* def NEED_INITGROUPS */
457
458 #ifdef AP_MPM_USES_POD
459
460 AP_DECLARE(apr_status_t) ap_mpm_pod_open(apr_pool_t *p, ap_pod_t **pod)
461 {
462     apr_status_t rv;
463
464     *pod = apr_palloc(p, sizeof(**pod));
465     rv = apr_file_pipe_create(&((*pod)->pod_in), &((*pod)->pod_out), p);
466     if (rv != APR_SUCCESS) {
467         return rv;
468     }
469
470     apr_file_pipe_timeout_set((*pod)->pod_in, 0);
471     (*pod)->p = p;
472
473     /* close these before exec. */
474     apr_file_unset_inherit((*pod)->pod_in);
475     apr_file_unset_inherit((*pod)->pod_out);
476
477     return APR_SUCCESS;
478 }
479
480 AP_DECLARE(apr_status_t) ap_mpm_pod_check(ap_pod_t *pod)
481 {
482     char c;
483     apr_size_t len = 1;
484     apr_status_t rv;
485
486     rv = apr_file_read(pod->pod_in, &c, &len);
487
488     if ((rv == APR_SUCCESS) && (len == 1)) {
489         return APR_SUCCESS;
490     }
491
492     if (rv != APR_SUCCESS) {
493         return rv;
494     }
495
496     return AP_NORESTART;
497 }
498
499 AP_DECLARE(apr_status_t) ap_mpm_pod_close(ap_pod_t *pod)
500 {
501     apr_status_t rv;
502
503     rv = apr_file_close(pod->pod_out);
504     if (rv != APR_SUCCESS) {
505         return rv;
506     }
507
508     rv = apr_file_close(pod->pod_in);
509     if (rv != APR_SUCCESS) {
510         return rv;
511     }
512
513     return APR_SUCCESS;
514 }
515
516 static apr_status_t pod_signal_internal(ap_pod_t *pod)
517 {
518     apr_status_t rv;
519     char char_of_death = '!';
520     apr_size_t one = 1;
521
522     rv = apr_file_write(pod->pod_out, &char_of_death, &one);
523     if (rv != APR_SUCCESS) {
524         ap_log_error(APLOG_MARK, APLOG_WARNING, rv, ap_server_conf,
525                      "write pipe_of_death");
526     }
527
528     return rv;
529 }
530
531 /* This function connects to the server, then immediately closes the connection.
532  * This permits the MPM to skip the poll when there is only one listening
533  * socket, because it provides a alternate way to unblock an accept() when
534  * the pod is used.
535  */
536 static apr_status_t dummy_connection(ap_pod_t *pod)
537 {
538     apr_status_t rv;
539     apr_socket_t *sock;
540     apr_pool_t *p;
541
542     /* create a temporary pool for the socket.  pconf stays around too long */
543     rv = apr_pool_create(&p, pod->p);
544     if (rv != APR_SUCCESS) {
545         return rv;
546     }
547
548     rv = apr_socket_create(&sock, ap_listeners->bind_addr->family, SOCK_STREAM, p);
549     if (rv != APR_SUCCESS) {
550         ap_log_error(APLOG_MARK, APLOG_WARNING, rv, ap_server_conf,
551                      "get socket to connect to listener");
552         return rv;
553     }
554
555     /* on some platforms (e.g., FreeBSD), the kernel won't accept many
556      * queued connections before it starts blocking local connects...
557      * we need to keep from blocking too long and instead return an error,
558      * because the MPM won't want to hold up a graceful restart for a
559      * long time
560      */
561     rv = apr_socket_timeout_set(sock, apr_time_from_sec(3));
562     if (rv != APR_SUCCESS) {
563         ap_log_error(APLOG_MARK, APLOG_WARNING, rv, ap_server_conf,
564                      "set timeout on socket to connect to listener");
565         apr_socket_close(sock);
566         return rv;
567     }
568
569     rv = apr_connect(sock, ap_listeners->bind_addr);
570     if (rv != APR_SUCCESS) {
571         int log_level = APLOG_WARNING;
572
573         if (APR_STATUS_IS_TIMEUP(rv)) {
574             /* probably some server processes bailed out already and there
575              * is nobody around to call accept and clear out the kernel
576              * connection queue; usually this is not worth logging
577              */
578             log_level = APLOG_DEBUG;
579         }
580
581         ap_log_error(APLOG_MARK, log_level, rv, ap_server_conf,
582                      "connect to listener on %pI", ap_listeners->bind_addr);
583     }
584
585     apr_socket_close(sock);
586     apr_pool_destroy(p);
587
588     return rv;
589 }
590
591 AP_DECLARE(apr_status_t) ap_mpm_pod_signal(ap_pod_t *pod)
592 {
593     apr_status_t rv;
594
595     rv = pod_signal_internal(pod);
596     if (rv != APR_SUCCESS) {
597         return rv;
598     }
599
600     return dummy_connection(pod);
601 }
602
603 void ap_mpm_pod_killpg(ap_pod_t *pod, int num)
604 {
605     int i;
606     apr_status_t rv = APR_SUCCESS;
607
608     /* we don't write anything to the pod here...  we assume
609      * that the would-be reader of the pod has another way to
610      * see that it is time to die once we wake it up
611      *
612      * writing lots of things to the pod at once is very
613      * problematic... we can fill the kernel pipe buffer and
614      * be blocked until somebody consumes some bytes or
615      * we hit a timeout...  if we hit a timeout we can't just
616      * keep trying because maybe we'll never successfully
617      * write again...  but then maybe we'll leave would-be
618      * readers stranded (a number of them could be tied up for
619      * a while serving time-consuming requests)
620      */
621     for (i = 0; i < num && rv == APR_SUCCESS; i++) {
622         rv = dummy_connection(pod);
623     }
624 }
625 #endif /* #ifdef AP_MPM_USES_POD */
626
627 /* standard mpm configuration handling */
628 #ifdef AP_MPM_WANT_SET_PIDFILE
629 const char *ap_pid_fname = NULL;
630
631 const char *ap_mpm_set_pidfile(cmd_parms *cmd, void *dummy,
632                                const char *arg)
633 {
634     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
635     if (err != NULL) {
636         return err;
637     }
638
639     if (cmd->server->is_virtual) {
640         return "PidFile directive not allowed in <VirtualHost>";
641     }
642
643     ap_pid_fname = arg;
644     return NULL;
645 }
646 #endif
647
648 #ifdef AP_MPM_WANT_SET_SCOREBOARD
649 const char * ap_mpm_set_scoreboard(cmd_parms *cmd, void *dummy,
650                                    const char *arg)
651 {
652     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
653     if (err != NULL) {
654         return err;
655     }
656
657     ap_scoreboard_fname = arg;
658     return NULL;
659 }
660 #endif
661
662 #ifdef AP_MPM_WANT_SET_LOCKFILE
663 const char *ap_lock_fname = NULL;
664
665 const char *ap_mpm_set_lockfile(cmd_parms *cmd, void *dummy,
666                                 const char *arg)
667 {
668     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
669     if (err != NULL) {
670         return err;
671     }
672
673     ap_lock_fname = arg;
674     return NULL;
675 }
676 #endif
677
678 #ifdef AP_MPM_WANT_SET_MAX_REQUESTS
679 int ap_max_requests_per_child = 0;
680
681 const char *ap_mpm_set_max_requests(cmd_parms *cmd, void *dummy,
682                                     const char *arg)
683 {
684     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
685     if (err != NULL) {
686         return err;
687     }
688
689     ap_max_requests_per_child = atoi(arg);
690
691     return NULL;
692 }
693 #endif
694
695 #ifdef AP_MPM_WANT_SET_COREDUMPDIR
696 char ap_coredump_dir[MAX_STRING_LEN];
697 int ap_coredumpdir_configured;
698
699 const char *ap_mpm_set_coredumpdir(cmd_parms *cmd, void *dummy,
700                                    const char *arg)
701 {
702     apr_status_t rv;
703     apr_finfo_t finfo;
704     const char *fname;
705     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
706     if (err != NULL) {
707         return err;
708     }
709
710     fname = ap_server_root_relative(cmd->pool, arg);
711     if (!fname) {
712         return apr_pstrcat(cmd->pool, "Invalid CoreDumpDirectory path ", 
713                            arg, NULL);
714     }
715     if ((rv = apr_stat(&finfo, fname, APR_FINFO_TYPE, cmd->pool)) != APR_SUCCESS) {
716         return apr_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
717                            " does not exist", NULL);
718     }
719     if (finfo.filetype != APR_DIR) {
720         return apr_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
721                            " is not a directory", NULL);
722     }
723     apr_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
724     ap_coredumpdir_configured = 1;
725     return NULL;
726 }
727 #endif
728
729 #ifdef AP_MPM_WANT_SET_ACCEPT_LOCK_MECH
730 apr_lockmech_e ap_accept_lock_mech = APR_LOCK_DEFAULT;
731
732 const char ap_valid_accept_mutex_string[] =
733     "Valid accept mutexes for this platform and MPM are: default"
734 #if APR_HAS_FLOCK_SERIALIZE
735     ", flock"
736 #endif
737 #if APR_HAS_FCNTL_SERIALIZE
738     ", fcntl"
739 #endif
740 #if APR_HAS_SYSVSEM_SERIALIZE && !defined(PERCHILD_MPM)
741     ", sysvsem"
742 #endif
743 #if APR_HAS_POSIXSEM_SERIALIZE
744     ", posixsem"
745 #endif
746 #if APR_HAS_PROC_PTHREAD_SERIALIZE
747     ", pthread"
748 #endif
749     ".";
750
751 AP_DECLARE(const char *) ap_mpm_set_accept_lock_mech(cmd_parms *cmd,
752                                                      void *dummy,
753                                                      const char *arg)
754 {
755     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
756     if (err != NULL) {
757         return err;
758     }
759
760     if (!strcasecmp(arg, "default")) {
761         ap_accept_lock_mech = APR_LOCK_DEFAULT;
762     }
763 #if APR_HAS_FLOCK_SERIALIZE
764     else if (!strcasecmp(arg, "flock")) {
765         ap_accept_lock_mech = APR_LOCK_FLOCK;
766     }
767 #endif
768 #if APR_HAS_FCNTL_SERIALIZE
769     else if (!strcasecmp(arg, "fcntl")) {
770         ap_accept_lock_mech = APR_LOCK_FCNTL;
771     }
772 #endif
773
774     /* perchild can't use SysV sems because the permissions on the accept
775      * mutex can't be set to allow all processes to use the mutex and
776      * at the same time keep all users from being able to dink with the
777      * mutex
778      */
779 #if APR_HAS_SYSVSEM_SERIALIZE && !defined(PERCHILD_MPM)
780     else if (!strcasecmp(arg, "sysvsem")) {
781         ap_accept_lock_mech = APR_LOCK_SYSVSEM;
782     }
783 #endif
784 #if APR_HAS_POSIXSEM_SERIALIZE
785     else if (!strcasecmp(arg, "posixsem")) {
786         ap_accept_lock_mech = APR_LOCK_POSIXSEM;
787     }
788 #endif
789 #if APR_HAS_PROC_PTHREAD_SERIALIZE
790     else if (!strcasecmp(arg, "pthread")) {
791         ap_accept_lock_mech = APR_LOCK_PROC_PTHREAD;
792     }
793 #endif
794     else {
795         return apr_pstrcat(cmd->pool, arg, " is an invalid mutex mechanism; ",
796                            ap_valid_accept_mutex_string, NULL);
797     }
798     return NULL;
799 }
800
801 #endif
802
803 #ifdef AP_MPM_WANT_SIGNAL_SERVER
804
805 static const char *dash_k_arg;
806
807 static int send_signal(pid_t pid, int sig)
808 {
809     if (kill(pid, sig) < 0) {
810         ap_log_error(APLOG_MARK, APLOG_STARTUP, errno, NULL,
811                      "sending signal to server");
812         return 1;
813     }
814     return 0;
815 }
816
817 int ap_signal_server(int *exit_status, apr_pool_t *pconf)
818 {
819     apr_status_t rv;
820     pid_t otherpid;
821     int running = 0;
822     int have_pid_file = 0;
823     const char *status;
824     
825     *exit_status = 0;
826
827     rv = ap_read_pid(pconf, ap_pid_fname, &otherpid);
828     if (rv != APR_SUCCESS) {
829         if (rv != APR_ENOENT) {
830             ap_log_error(APLOG_MARK, APLOG_STARTUP, rv, NULL,
831                          "Error retrieving pid file %s", ap_pid_fname);
832             *exit_status = 1;
833             return 1;
834         }
835         status = "httpd (no pid file) not running";
836     }
837     else {
838         have_pid_file = 1;
839         if (kill(otherpid, 0) == 0) {
840             running = 1;
841             status = apr_psprintf(pconf, 
842                                   "httpd (pid %" APR_PID_T_FMT ") already "
843                                   "running", otherpid);
844         }
845         else {
846             status = apr_psprintf(pconf,
847                                   "httpd (pid %" APR_PID_T_FMT "?) not running",
848                                   otherpid);
849         }
850     }
851
852     if (!strcmp(dash_k_arg, "start")) {
853         if (running) {
854             printf("%s\n", status);
855             return 1;
856         }
857     }
858
859     if (!strcmp(dash_k_arg, "stop")) {
860         if (!running) {
861             printf("%s\n", status);
862         }
863         else {
864             send_signal(otherpid, SIGTERM);
865         }
866         return 1;
867     }
868
869     if (!strcmp(dash_k_arg, "restart")) {
870         if (!running) {
871             printf("httpd not running, trying to start\n");
872         }
873         else {
874             *exit_status = send_signal(otherpid, SIGHUP);
875             return 1;
876         }
877     }
878
879     if (!strcmp(dash_k_arg, "graceful")) {
880         if (!running) {
881             printf("httpd not running, trying to start\n");
882         }
883         else {
884             *exit_status = send_signal(otherpid, SIGUSR1);
885             return 1;
886         }
887     }
888
889     return 0;
890 }
891
892 void ap_mpm_rewrite_args(process_rec *process)
893 {
894     apr_array_header_t *mpm_new_argv;
895     apr_status_t rv;
896     apr_getopt_t *opt;
897     char optbuf[3];
898     const char *optarg;
899     int fixed_args;
900
901     mpm_new_argv = apr_array_make(process->pool, process->argc,
902                                   sizeof(const char **));
903     *(const char **)apr_array_push(mpm_new_argv) = process->argv[0];
904     fixed_args = mpm_new_argv->nelts;
905     apr_getopt_init(&opt, process->pool, process->argc, process->argv);
906     opt->errfn = NULL;
907     optbuf[0] = '-';
908     /* option char returned by apr_getopt() will be stored in optbuf[1] */
909     optbuf[2] = '\0';
910     while ((rv = apr_getopt(opt, "k:" AP_SERVER_BASEARGS,
911                             optbuf + 1, &optarg)) == APR_SUCCESS) {
912         switch(optbuf[1]) {
913         case 'k':
914             if (!dash_k_arg) {
915                 if (!strcmp(optarg, "start") || !strcmp(optarg, "stop") ||
916                     !strcmp(optarg, "restart") || !strcmp(optarg, "graceful")) {
917                     dash_k_arg = optarg;
918                     break;
919                 }
920             }
921         default:
922             *(const char **)apr_array_push(mpm_new_argv) =
923                 apr_pstrdup(process->pool, optbuf);
924             if (optarg) {
925                 *(const char **)apr_array_push(mpm_new_argv) = optarg;
926             }
927         }
928     }
929
930     /* back up to capture the bad argument */
931     if (rv == APR_BADCH || rv == APR_BADARG) {
932         opt->ind--;
933     }
934
935     while (opt->ind < opt->argc) {
936         *(const char **)apr_array_push(mpm_new_argv) =
937             apr_pstrdup(process->pool, opt->argv[opt->ind++]);
938     }
939
940     process->argc = mpm_new_argv->nelts;
941     process->argv = (const char * const *)mpm_new_argv->elts;
942
943     if (dash_k_arg) {
944         APR_REGISTER_OPTIONAL_FN(ap_signal_server);
945     }
946 }
947
948 #endif /* AP_MPM_WANT_SIGNAL_SERVER */
949
950 #ifdef AP_MPM_WANT_SET_MAX_MEM_FREE
951 apr_uint32_t ap_max_mem_free = APR_ALLOCATOR_MAX_FREE_UNLIMITED;
952
953 const char *ap_mpm_set_max_mem_free(cmd_parms *cmd, void *dummy,
954                                     const char *arg)
955 {
956     long value;
957     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
958     if (err != NULL) {
959         return err;
960     }
961     
962     value = strtol(arg, NULL, 0);
963     if (value < 0 || errno == ERANGE)
964         return apr_pstrcat(cmd->pool, "Invalid MaxMemFree value: ", 
965                            arg, NULL);
966
967     ap_max_mem_free = (apr_uint32_t)value * 1024;
968
969     return NULL;
970 }
971
972 #endif /* AP_MPM_WANT_SET_MAX_MEM_FREE */
973
974 #ifdef AP_MPM_WANT_FATAL_SIGNAL_HANDLER
975
976 static pid_t parent_pid, my_pid;
977 apr_pool_t *pconf;
978
979 #if AP_ENABLE_EXCEPTION_HOOK
980
981 static int exception_hook_enabled;
982
983 const char *ap_mpm_set_exception_hook(cmd_parms *cmd, void *dummy,
984                                       const char *arg)
985 {
986     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
987     if (err != NULL) {
988         return err;
989     }
990
991     if (cmd->server->is_virtual) {
992         return "EnableExceptionHook directive not allowed in <VirtualHost>";
993     }
994
995     if (strcasecmp(arg, "on") == 0) {
996         exception_hook_enabled = 1;
997     }
998     else if (strcasecmp(arg, "off") == 0) {
999         exception_hook_enabled = 0;
1000     }
1001     else {
1002         return "parameter must be 'on' or 'off'";
1003     }
1004
1005     return NULL;
1006 }
1007
1008 APR_HOOK_STRUCT(
1009     APR_HOOK_LINK(fatal_exception)
1010 )
1011
1012 AP_IMPLEMENT_HOOK_RUN_ALL(int, fatal_exception,
1013                           (ap_exception_info_t *ei), (ei), OK, DECLINED)
1014
1015 static void run_fatal_exception_hook(int sig)
1016 {
1017     ap_exception_info_t ei = {0};
1018
1019     if (exception_hook_enabled &&
1020         geteuid() != 0 && 
1021         my_pid != parent_pid) {
1022         ei.sig = sig;
1023         ei.pid = my_pid;
1024         ap_run_fatal_exception(&ei);
1025     }
1026 }
1027 #endif /* AP_ENABLE_EXCEPTION_HOOK */
1028
1029 /* handle all varieties of core dumping signals */
1030 static void sig_coredump(int sig)
1031 {
1032     apr_filepath_set(ap_coredump_dir, pconf);
1033     apr_signal(sig, SIG_DFL);
1034 #if AP_ENABLE_EXCEPTION_HOOK
1035     run_fatal_exception_hook(sig);
1036 #endif
1037     /* linuxthreads issue calling getpid() here:
1038      *   This comparison won't match if the crashing thread is
1039      *   some module's thread that runs in the parent process.
1040      *   The fallout, which is limited to linuxthreads:
1041      *   The special log message won't be written when such a
1042      *   thread in the parent causes the parent to crash.
1043      */
1044     if (getpid() == parent_pid) {
1045         ap_log_error(APLOG_MARK, APLOG_NOTICE,
1046                      0, ap_server_conf,
1047                      "seg fault or similar nasty error detected "
1048                      "in the parent process");
1049         /* XXX we can probably add some rudimentary cleanup code here,
1050          * like getting rid of the pid file.  If any additional bad stuff
1051          * happens, we are protected from recursive errors taking down the
1052          * system since this function is no longer the signal handler   GLA
1053          */
1054     }
1055     kill(getpid(), sig);
1056     /* At this point we've got sig blocked, because we're still inside
1057      * the signal handler.  When we leave the signal handler it will
1058      * be unblocked, and we'll take the signal... and coredump or whatever
1059      * is appropriate for this particular Unix.  In addition the parent
1060      * will see the real signal we received -- whereas if we called
1061      * abort() here, the parent would only see SIGABRT.
1062      */
1063 }
1064
1065 apr_status_t ap_fatal_signal_child_setup(server_rec *s)
1066 {
1067     my_pid = getpid();
1068     return APR_SUCCESS;
1069 }
1070
1071 apr_status_t ap_fatal_signal_setup(server_rec *s, apr_pool_t *in_pconf)
1072 {
1073 #ifndef NO_USE_SIGACTION
1074     struct sigaction sa;
1075
1076     sigemptyset(&sa.sa_mask);
1077     
1078 #if defined(SA_ONESHOT)
1079     sa.sa_flags = SA_ONESHOT;
1080 #elif defined(SA_RESETHAND)
1081     sa.sa_flags = SA_RESETHAND;
1082 #else
1083     sa.sa_flags = 0;
1084 #endif
1085
1086     sa.sa_handler = sig_coredump;
1087     if (sigaction(SIGSEGV, &sa, NULL) < 0)
1088         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, s, "sigaction(SIGSEGV)");
1089 #ifdef SIGBUS
1090     if (sigaction(SIGBUS, &sa, NULL) < 0)
1091         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, s, "sigaction(SIGBUS)");
1092 #endif
1093 #ifdef SIGABORT
1094     if (sigaction(SIGABORT, &sa, NULL) < 0)
1095         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, s, "sigaction(SIGABORT)");
1096 #endif
1097 #ifdef SIGABRT
1098     if (sigaction(SIGABRT, &sa, NULL) < 0)
1099         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, s, "sigaction(SIGABRT)");
1100 #endif
1101 #ifdef SIGILL
1102     if (sigaction(SIGILL, &sa, NULL) < 0)
1103         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, s, "sigaction(SIGILL)");
1104 #endif
1105
1106 #else /* NO_USE_SIGACTION */
1107     
1108     apr_signal(SIGSEGV, sig_coredump);
1109 #ifdef SIGBUS
1110     apr_signal(SIGBUS, sig_coredump);
1111 #endif /* SIGBUS */
1112 #ifdef SIGABORT
1113     apr_signal(SIGABORT, sig_coredump);
1114 #endif /* SIGABORT */
1115 #ifdef SIGABRT
1116     apr_signal(SIGABRT, sig_coredump);
1117 #endif /* SIGABRT */
1118 #ifdef SIGILL
1119     apr_signal(SIGILL, sig_coredump);
1120 #endif /* SIGILL */
1121
1122 #endif /* NO_USE_SIGACTION */
1123
1124     pconf = in_pconf;
1125     parent_pid = my_pid = getpid();
1126
1127     return APR_SUCCESS;
1128 }
1129
1130 #endif /* AP_MPM_WANT_FATAL_SIGNAL_HANDLER */