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