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