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