]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/daemon/daemon.c
MFV: xz 5.4.2.
[FreeBSD/FreeBSD.git] / usr.sbin / daemon / daemon.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1999 Berkeley Software Design, Inc. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. Berkeley Software Design Inc's name may not be used to endorse or
15  *    promote products derived from this software without specific prior
16  *    written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  *      From BSDI: daemon.c,v 1.2 1996/08/15 01:11:09 jch Exp
31  */
32
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35
36 #include <sys/param.h>
37 #include <sys/mman.h>
38 #include <sys/wait.h>
39
40 #include <fcntl.h>
41 #include <err.h>
42 #include <errno.h>
43 #include <getopt.h>
44 #include <libutil.h>
45 #include <login_cap.h>
46 #include <paths.h>
47 #include <pwd.h>
48 #include <signal.h>
49 #include <stdio.h>
50 #include <stdbool.h>
51 #include <stdlib.h>
52 #include <unistd.h>
53 #include <string.h>
54 #include <strings.h>
55 #define SYSLOG_NAMES
56 #include <syslog.h>
57 #include <time.h>
58 #include <assert.h>
59
60 #define LBUF_SIZE 4096
61
62 struct daemon_state {
63         int pipe_fd[2];
64         const char *child_pidfile;
65         const char *parent_pidfile;
66         const char *output_filename;
67         const char *syslog_tag;
68         const char *title;
69         const char *user;
70         struct pidfh *parent_pidfh;
71         struct pidfh *child_pidfh;
72         int keep_cur_workdir;
73         int restart_delay;
74         int stdmask;
75         int syslog_priority;
76         int syslog_facility;
77         int keep_fds_open;
78         int output_fd;
79         bool supervision_enabled;
80         bool child_eof;
81         bool restart_enabled;
82         bool syslog_enabled;
83         bool log_reopen;
84 };
85
86 static void restrict_process(const char *);
87 static void handle_term(int);
88 static void handle_chld(int);
89 static void handle_hup(int);
90 static int  open_log(const char *);
91 static void reopen_log(struct daemon_state *);
92 static bool listen_child(int, struct daemon_state *);
93 static int  get_log_mapping(const char *, const CODE *);
94 static void open_pid_files(struct daemon_state *);
95 static void do_output(const unsigned char *, size_t, struct daemon_state *);
96 static void daemon_sleep(time_t, long);
97 static void daemon_state_init(struct daemon_state *);
98 static void daemon_terminate(struct daemon_state *);
99
100 static volatile sig_atomic_t terminate = 0;
101 static volatile sig_atomic_t child_gone = 0;
102 static volatile sig_atomic_t pid = 0;
103 static volatile sig_atomic_t do_log_reopen = 0;
104
105 static const char shortopts[] = "+cfHSp:P:ru:o:s:l:t:m:R:T:h";
106
107 static const struct option longopts[] = {
108         { "change-dir",         no_argument,            NULL,           'c' },
109         { "close-fds",          no_argument,            NULL,           'f' },
110         { "sighup",             no_argument,            NULL,           'H' },
111         { "syslog",             no_argument,            NULL,           'S' },
112         { "output-file",        required_argument,      NULL,           'o' },
113         { "output-mask",        required_argument,      NULL,           'm' },
114         { "child-pidfile",      required_argument,      NULL,           'p' },
115         { "supervisor-pidfile", required_argument,      NULL,           'P' },
116         { "restart",            no_argument,            NULL,           'r' },
117         { "restart-delay",      required_argument,      NULL,           'R' },
118         { "title",              required_argument,      NULL,           't' },
119         { "user",               required_argument,      NULL,           'u' },
120         { "syslog-priority",    required_argument,      NULL,           's' },
121         { "syslog-facility",    required_argument,      NULL,           'l' },
122         { "syslog-tag",         required_argument,      NULL,           'T' },
123         { "help",               no_argument,            NULL,           'h' },
124         { NULL,                 0,                      NULL,            0  }
125 };
126
127 static _Noreturn void
128 usage(int exitcode)
129 {
130         (void)fprintf(stderr,
131             "usage: daemon [-cfHrS] [-p child_pidfile] [-P supervisor_pidfile]\n"
132             "              [-u user] [-o output_file] [-t title]\n"
133             "              [-l syslog_facility] [-s syslog_priority]\n"
134             "              [-T syslog_tag] [-m output_mask] [-R restart_delay_secs]\n"
135             "command arguments ...\n");
136
137         (void)fprintf(stderr,
138             "  --change-dir         -c         Change the current working directory to root\n"
139             "  --close-fds          -f         Set stdin, stdout, stderr to /dev/null\n"
140             "  --sighup             -H         Close and re-open output file on SIGHUP\n"
141             "  --syslog             -S         Send output to syslog\n"
142             "  --output-file        -o <file>  Append output of the child process to file\n"
143             "  --output-mask        -m <mask>  What to send to syslog/file\n"
144             "                                  1=stdout, 2=stderr, 3=both\n"
145             "  --child-pidfile      -p <file>  Write PID of the child process to file\n"
146             "  --supervisor-pidfile -P <file>  Write PID of the supervisor process to file\n"
147             "  --restart            -r         Restart child if it terminates (1 sec delay)\n"
148             "  --restart-delay      -R <N>     Restart child if it terminates after N sec\n"
149             "  --title              -t <title> Set the title of the supervisor process\n"
150             "  --user               -u <user>  Drop privileges, run as given user\n"
151             "  --syslog-priority    -s <prio>  Set syslog priority\n"
152             "  --syslog-facility    -l <flty>  Set syslog facility\n"
153             "  --syslog-tag         -T <tag>   Set syslog tag\n"
154             "  --help               -h         Show this help\n");
155
156         exit(exitcode);
157 }
158
159 int
160 main(int argc, char *argv[])
161 {
162         char *p = NULL;
163         int ch = 0;
164         struct daemon_state state;
165         sigset_t mask_orig;
166         sigset_t mask_read;
167         sigset_t mask_term;
168         sigset_t mask_susp;
169
170         daemon_state_init(&state);
171         sigemptyset(&mask_susp);
172         sigemptyset(&mask_read);
173         sigemptyset(&mask_term);
174         sigemptyset(&mask_orig);
175
176         /*
177          * Supervision mode is enabled if one of the following options are used:
178          * --child-pidfile -p
179          * --supervisor-pidfile -P
180          * --restart -r / --restart-delay -R
181          * --syslog -S
182          * --syslog-facility -l
183          * --syslog-priority -s
184          * --syslog-tag -T
185          *
186          * In supervision mode daemon executes the command in a forked process
187          * and observes the child by waiting for SIGCHILD. In supervision mode
188          * daemon must never exit before the child, this is necessary  to prevent
189          * orphaning the child and leaving a stale pid file.
190          * To achieve this daemon catches SIGTERM and
191          * forwards it to the child, expecting to get SIGCHLD eventually.
192          */
193         while ((ch = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) {
194                 switch (ch) {
195                 case 'c':
196                         state.keep_cur_workdir = 0;
197                         break;
198                 case 'f':
199                         state.keep_fds_open = 0;
200                         break;
201                 case 'H':
202                         state.log_reopen = true;
203                         break;
204                 case 'l':
205                         state.syslog_facility = get_log_mapping(optarg,
206                             facilitynames);
207                         if (state.syslog_facility == -1) {
208                                 errx(5, "unrecognized syslog facility");
209                         }
210                         state.syslog_enabled = true;
211                         state.supervision_enabled = true;
212                         break;
213                 case 'm':
214                         state.stdmask = strtol(optarg, &p, 10);
215                         if (p == optarg || state.stdmask < 0 || state.stdmask > 3) {
216                                 errx(6, "unrecognized listening mask");
217                         }
218                         break;
219                 case 'o':
220                         state.output_filename = optarg;
221                         /*
222                          * TODO: setting output filename doesn't have to turn
223                          * the supervision mode on. For non-supervised mode
224                          * daemon could open the specified file and set it's
225                          * descriptor as both stderr and stout before execve()
226                          */
227                         state.supervision_enabled = true;
228                         break;
229                 case 'p':
230                         state.child_pidfile = optarg;
231                         state.supervision_enabled = true;
232                         break;
233                 case 'P':
234                         state.parent_pidfile = optarg;
235                         state.supervision_enabled = true;
236                         break;
237                 case 'r':
238                         state.restart_enabled = true;
239                         state.supervision_enabled = true;
240                         break;
241                 case 'R':
242                         state.restart_enabled = true;
243                         state.restart_delay = strtol(optarg, &p, 0);
244                         if (p == optarg || state.restart_delay < 1) {
245                                 errx(6, "invalid restart delay");
246                         }
247                         break;
248                 case 's':
249                         state.syslog_priority = get_log_mapping(optarg,
250                             prioritynames);
251                         if (state.syslog_priority == -1) {
252                                 errx(4, "unrecognized syslog priority");
253                         }
254                         state.syslog_enabled = true;
255                         state.supervision_enabled = true;
256                         break;
257                 case 'S':
258                         state.syslog_enabled = true;
259                         state.supervision_enabled = true;
260                         break;
261                 case 't':
262                         state.title = optarg;
263                         break;
264                 case 'T':
265                         state.syslog_tag = optarg;
266                         state.syslog_enabled = true;
267                         state.supervision_enabled = true;
268                         break;
269                 case 'u':
270                         state.user = optarg;
271                         break;
272                 case 'h':
273                         usage(0);
274                         __builtin_unreachable();
275                 default:
276                         usage(1);
277                 }
278         }
279         argc -= optind;
280         argv += optind;
281
282         if (argc == 0) {
283                 usage(1);
284         }
285
286         if (!state.title) {
287                 state.title = argv[0];
288         }
289
290         if (state.output_filename) {
291                 state.output_fd = open_log(state.output_filename);
292                 if (state.output_fd == -1) {
293                         err(7, "open");
294                 }
295         }
296
297         if (state.syslog_enabled) {
298                 openlog(state.syslog_tag, LOG_PID | LOG_NDELAY,
299                     state.syslog_facility);
300         }
301
302         /*
303          * Try to open the pidfile before calling daemon(3),
304          * to be able to report the error intelligently
305          */
306         open_pid_files(&state);
307         if (daemon(state.keep_cur_workdir, state.keep_fds_open) == -1) {
308                 warn("daemon");
309                 daemon_terminate(&state);
310         }
311         /* Write out parent pidfile if needed. */
312         pidfile_write(state.parent_pidfh);
313
314         if (state.supervision_enabled) {
315                 struct sigaction act_term = { 0 };
316                 struct sigaction act_chld = { 0 };
317                 struct sigaction act_hup = { 0 };
318
319                 /* Avoid PID racing with SIGCHLD and SIGTERM. */
320                 act_term.sa_handler = handle_term;
321                 sigemptyset(&act_term.sa_mask);
322                 sigaddset(&act_term.sa_mask, SIGCHLD);
323
324                 act_chld.sa_handler = handle_chld;
325                 sigemptyset(&act_chld.sa_mask);
326                 sigaddset(&act_chld.sa_mask, SIGTERM);
327
328                 act_hup.sa_handler = handle_hup;
329                 sigemptyset(&act_hup.sa_mask);
330
331                 /* Block these when avoiding racing before sigsuspend(). */
332                 sigaddset(&mask_susp, SIGTERM);
333                 sigaddset(&mask_susp, SIGCHLD);
334                 /* Block SIGTERM when we lack a valid child PID. */
335                 sigaddset(&mask_term, SIGTERM);
336                 /*
337                  * When reading, we wish to avoid SIGCHLD. SIGTERM
338                  * has to be caught, otherwise we'll be stuck until
339                  * the read() returns - if it returns.
340                  */
341                 sigaddset(&mask_read, SIGCHLD);
342                 /* Block SIGTERM to avoid racing until we have forked. */
343                 if (sigprocmask(SIG_BLOCK, &mask_term, &mask_orig)) {
344                         warn("sigprocmask");
345                         daemon_terminate(&state);
346                 }
347                 if (sigaction(SIGTERM, &act_term, NULL) == -1) {
348                         warn("sigaction");
349                         daemon_terminate(&state);
350                 }
351                 if (sigaction(SIGCHLD, &act_chld, NULL) == -1) {
352                         warn("sigaction");
353                         daemon_terminate(&state);
354                 }
355                 /*
356                  * Try to protect against pageout kill. Ignore the
357                  * error, madvise(2) will fail only if a process does
358                  * not have superuser privileges.
359                  */
360                 (void)madvise(NULL, 0, MADV_PROTECT);
361                 if (state.log_reopen && state.output_fd >= 0 &&
362                     sigaction(SIGHUP, &act_hup, NULL) == -1) {
363                         warn("sigaction");
364                         daemon_terminate(&state);
365                 }
366 restart:
367                 if (pipe(state.pipe_fd)) {
368                         err(1, "pipe");
369                 }
370                 /*
371                  * Spawn a child to exec the command.
372                  */
373                 child_gone = 0;
374                 pid = fork();
375         }
376
377         /* fork failed, this can only happen when supervision is enabled */
378         if (pid == -1) {
379                 warn("fork");
380                 daemon_terminate(&state);
381         }
382
383         /* fork succeeded, this is child's branch or supervision is disabled */
384         if (pid == 0) {
385                 pidfile_write(state.child_pidfh);
386
387                 if (state.user != NULL) {
388                         restrict_process(state.user);
389                 }
390                 /*
391                  * In supervision mode, the child gets the original sigmask,
392                  * and dup'd pipes.
393                  */
394                 if (state.supervision_enabled) {
395                         close(state.pipe_fd[0]);
396                         if (sigprocmask(SIG_SETMASK, &mask_orig, NULL)) {
397                                 err(1, "sigprogmask");
398                         }
399                         if (state.stdmask & STDERR_FILENO) {
400                                 if (dup2(state.pipe_fd[1], STDERR_FILENO) == -1) {
401                                         err(1, "dup2");
402                                 }
403                         }
404                         if (state.stdmask & STDOUT_FILENO) {
405                                 if (dup2(state.pipe_fd[1], STDOUT_FILENO) == -1) {
406                                         err(1, "dup2");
407                                 }
408                         }
409                         if (state.pipe_fd[1] != STDERR_FILENO &&
410                             state.pipe_fd[1] != STDOUT_FILENO) {
411                                 close(state.pipe_fd[1]);
412                         }
413                 }
414                 execvp(argv[0], argv);
415                 /* execvp() failed - report error and exit this process */
416                 err(1, "%s", argv[0]);
417         }
418
419         /*
420          * else: pid > 0
421          * fork succeeded, this is the parent branch, this can only happen when
422          * supervision is enabled
423          *
424          * Unblock SIGTERM after we know we have a valid child PID to signal.
425          */
426         if (sigprocmask(SIG_UNBLOCK, &mask_term, NULL)) {
427                 warn("sigprocmask");
428                 daemon_terminate(&state);
429         }
430         close(state.pipe_fd[1]);
431         state.pipe_fd[1] = -1;
432
433         setproctitle("%s[%d]", state.title, (int)pid);
434         /*
435          * As we have closed the write end of pipe for parent process,
436          * we might detect the child's exit by reading EOF. The child
437          * might have closed its stdout and stderr, so we must wait for
438          * the SIGCHLD to ensure that the process is actually gone.
439          */
440         for (;;) {
441                 /*
442                  * We block SIGCHLD when listening, but SIGTERM we accept
443                  * so the read() won't block if we wish to depart.
444                  *
445                  * Upon receiving SIGTERM, we have several options after
446                  * sending the SIGTERM to our child:
447                  * - read until EOF
448                  * - read until EOF but only for a while
449                  * - bail immediately
450                  *
451                  * We go for the third, as otherwise we have no guarantee
452                  * that we won't block indefinitely if the child refuses
453                  * to depart. To handle the second option, a different
454                  * approach would be needed (procctl()?)
455                  */
456                 if (child_gone && state.child_eof) {
457                         break;
458                 }
459
460                 if (terminate) {
461                         daemon_terminate(&state);
462                 }
463
464                 if (state.child_eof) {
465                         if (sigprocmask(SIG_BLOCK, &mask_susp, NULL)) {
466                                 warn("sigprocmask");
467                                 daemon_terminate(&state);
468                         }
469                         while (!terminate && !child_gone) {
470                                 sigsuspend(&mask_orig);
471                         }
472                         if (sigprocmask(SIG_UNBLOCK, &mask_susp, NULL)) {
473                                 warn("sigprocmask");
474                                 daemon_terminate(&state);
475                         }
476                         continue;
477                 }
478
479                 if (sigprocmask(SIG_BLOCK, &mask_read, NULL)) {
480                         warn("sigprocmask");
481                         daemon_terminate(&state);
482                 }
483
484                 state.child_eof = !listen_child(state.pipe_fd[0], &state);
485
486                 if (sigprocmask(SIG_UNBLOCK, &mask_read, NULL)) {
487                         warn("sigprocmask");
488                         daemon_terminate(&state);
489                 }
490
491         }
492         if (state.restart_enabled && !terminate) {
493                 daemon_sleep(state.restart_delay, 0);
494         }
495         if (sigprocmask(SIG_BLOCK, &mask_term, NULL)) {
496                 warn("sigprocmask");
497                 daemon_terminate(&state);
498         }
499         if (state.restart_enabled && !terminate) {
500                 close(state.pipe_fd[0]);
501                 state.pipe_fd[0] = -1;
502                 goto restart;
503         }
504         daemon_terminate(&state);
505 }
506
507 static void
508 daemon_sleep(time_t secs, long nsecs)
509 {
510         struct timespec ts = { secs, nsecs };
511
512         while (!terminate && nanosleep(&ts, &ts) == -1) {
513                 if (errno != EINTR) {
514                         err(1, "nanosleep");
515                 }
516         }
517 }
518
519 static void
520 open_pid_files(struct daemon_state *state)
521 {
522         pid_t fpid;
523         int serrno;
524
525         if (state->child_pidfile) {
526                 state->child_pidfh = pidfile_open(state->child_pidfile, 0600, &fpid);
527                 if (state->child_pidfh == NULL) {
528                         if (errno == EEXIST) {
529                                 errx(3, "process already running, pid: %d",
530                                     fpid);
531                         }
532                         err(2, "pidfile ``%s''", state->child_pidfile);
533                 }
534         }
535         /* Do the same for the actual daemon process. */
536         if (state->parent_pidfile) {
537                 state->parent_pidfh= pidfile_open(state->parent_pidfile, 0600, &fpid);
538                 if (state->parent_pidfh == NULL) {
539                         serrno = errno;
540                         pidfile_remove(state->child_pidfh);
541                         errno = serrno;
542                         if (errno == EEXIST) {
543                                 errx(3, "process already running, pid: %d",
544                                      fpid);
545                         }
546                         err(2, "ppidfile ``%s''", state->parent_pidfile);
547                 }
548         }
549 }
550
551 static int
552 get_log_mapping(const char *str, const CODE *c)
553 {
554         const CODE *cp;
555         for (cp = c; cp->c_name; cp++)
556                 if (strcmp(cp->c_name, str) == 0) {
557                         return cp->c_val;
558                 }
559         return -1;
560 }
561
562 static void
563 restrict_process(const char *user)
564 {
565         struct passwd *pw = NULL;
566
567         pw = getpwnam(user);
568         if (pw == NULL) {
569                 errx(1, "unknown user: %s", user);
570         }
571
572         if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0) {
573                 errx(1, "failed to set user environment");
574         }
575
576         setenv("USER", pw->pw_name, 1);
577         setenv("HOME", pw->pw_dir, 1);
578         setenv("SHELL", *pw->pw_shell ? pw->pw_shell : _PATH_BSHELL, 1);
579 }
580
581 /*
582  * We try to collect whole lines terminated by '\n'. Otherwise we collect a
583  * full buffer, and then output it.
584  *
585  * Return value of false is assumed to mean EOF or error, and true indicates to
586  * continue reading.
587  */
588 static bool
589 listen_child(int fd, struct daemon_state *state)
590 {
591         static unsigned char buf[LBUF_SIZE];
592         static size_t bytes_read = 0;
593         int rv;
594
595         assert(state != NULL);
596         assert(bytes_read < LBUF_SIZE - 1);
597
598         if (do_log_reopen) {
599                 reopen_log(state);
600         }
601         rv = read(fd, buf + bytes_read, LBUF_SIZE - bytes_read - 1);
602         if (rv > 0) {
603                 unsigned char *cp;
604
605                 bytes_read += rv;
606                 assert(bytes_read <= LBUF_SIZE - 1);
607                 /* Always NUL-terminate just in case. */
608                 buf[LBUF_SIZE - 1] = '\0';
609                 /*
610                  * Chomp line by line until we run out of buffer.
611                  * This does not take NUL characters into account.
612                  */
613                 while ((cp = memchr(buf, '\n', bytes_read)) != NULL) {
614                         size_t bytes_line = cp - buf + 1;
615                         assert(bytes_line <= bytes_read);
616                         do_output(buf, bytes_line, state);
617                         bytes_read -= bytes_line;
618                         memmove(buf, cp + 1, bytes_read);
619                 }
620                 /* Wait until the buffer is full. */
621                 if (bytes_read < LBUF_SIZE - 1) {
622                         return true;
623                 }
624                 do_output(buf, bytes_read, state);
625                 bytes_read = 0;
626                 return true;
627         } else if (rv == -1) {
628                 /* EINTR should trigger another read. */
629                 if (errno == EINTR) {
630                         return true;
631                 } else {
632                         warn("read");
633                         return false;
634                 }
635         }
636         /* Upon EOF, we have to flush what's left of the buffer. */
637         if (bytes_read > 0) {
638                 do_output(buf, bytes_read, state);
639                 bytes_read = 0;
640         }
641         return false;
642 }
643
644 /*
645  * The default behavior is to stay silent if the user wants to redirect
646  * output to a file and/or syslog. If neither are provided, then we bounce
647  * everything back to parent's stdout.
648  */
649 static void
650 do_output(const unsigned char *buf, size_t len, struct daemon_state *state)
651 {
652         assert(len <= LBUF_SIZE);
653         assert(state != NULL);
654
655         if (len < 1) {
656                 return;
657         }
658         if (state->syslog_enabled) {
659                 syslog(state->syslog_priority, "%.*s", (int)len, buf);
660         }
661         if (state->output_fd != -1) {
662                 if (write(state->output_fd, buf, len) == -1)
663                         warn("write");
664         }
665         if (state->keep_fds_open &&
666             !state->syslog_enabled &&
667             state->output_fd == -1) {
668                 printf("%.*s", (int)len, buf);
669         }
670 }
671
672 /*
673  * We use the global PID acquired directly from fork. If there is no valid
674  * child pid, the handler should be blocked and/or child_gone == 1.
675  */
676 static void
677 handle_term(int signo)
678 {
679         if (pid > 0 && !child_gone) {
680                 kill(pid, signo);
681         }
682         terminate = 1;
683 }
684
685 static void
686 handle_chld(int signo __unused)
687 {
688
689         for (;;) {
690                 int rv = waitpid(-1, NULL, WNOHANG);
691                 if (pid == rv) {
692                         child_gone = 1;
693                         break;
694                 } else if (rv == -1 && errno != EINTR) {
695                         warn("waitpid");
696                         return;
697                 }
698         }
699 }
700
701 static void
702 handle_hup(int signo __unused)
703 {
704
705         do_log_reopen = 1;
706 }
707
708 static int
709 open_log(const char *outfn)
710 {
711
712         return open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
713 }
714
715 static void
716 reopen_log(struct daemon_state *state)
717 {
718         int outfd;
719
720         do_log_reopen = 0;
721         outfd = open_log(state->output_filename);
722         if (state->output_fd >= 0) {
723                 close(state->output_fd);
724         }
725         state->output_fd = outfd;
726 }
727
728 static void
729 daemon_state_init(struct daemon_state *state)
730 {
731         *state = (struct daemon_state) {
732                 .pipe_fd = { -1, -1 },
733                 .parent_pidfh = NULL,
734                 .child_pidfh = NULL,
735                 .child_pidfile = NULL,
736                 .parent_pidfile = NULL,
737                 .title = NULL,
738                 .user = NULL,
739                 .supervision_enabled = false,
740                 .child_eof = false,
741                 .restart_enabled = false,
742                 .keep_cur_workdir = 1,
743                 .restart_delay = 1,
744                 .stdmask = STDOUT_FILENO | STDERR_FILENO,
745                 .syslog_enabled = false,
746                 .log_reopen = false,
747                 .syslog_priority = LOG_NOTICE,
748                 .syslog_tag = "daemon",
749                 .syslog_facility = LOG_DAEMON,
750                 .keep_fds_open = 1,
751                 .output_fd = -1,
752                 .output_filename = NULL,
753         };
754 }
755
756 static _Noreturn void
757 daemon_terminate(struct daemon_state *state)
758 {
759         assert(state != NULL);
760         close(state->output_fd);
761         close(state->pipe_fd[0]);
762         close(state->pipe_fd[1]);
763         if (state->syslog_enabled) {
764                 closelog();
765         }
766         pidfile_remove(state->child_pidfh);
767         pidfile_remove(state->parent_pidfh);
768
769         /*
770          * Note that the exit value here doesn't matter in the case of a clean
771          * exit; daemon(3) already detached us from the caller, nothing is left
772          * to care about this one.
773          */
774         exit(1);
775 }