]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/daemon/daemon.c
zfs: merge openzfs/zfs@797f55ef1
[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 #include <sys/param.h>
35 #include <sys/event.h>
36 #include <sys/mman.h>
37 #include <sys/wait.h>
38
39 #include <fcntl.h>
40 #include <err.h>
41 #include <errno.h>
42 #include <getopt.h>
43 #include <libutil.h>
44 #include <login_cap.h>
45 #include <paths.h>
46 #include <pwd.h>
47 #include <signal.h>
48 #include <stdio.h>
49 #include <stdbool.h>
50 #include <stdlib.h>
51 #include <unistd.h>
52 #include <string.h>
53 #include <strings.h>
54 #define SYSLOG_NAMES
55 #include <syslog.h>
56 #include <time.h>
57 #include <assert.h>
58
59 #define LBUF_SIZE 4096
60
61 enum daemon_mode {
62         MODE_DAEMON = 0,   /* simply daemonize, no supervision */
63         MODE_SUPERVISE,    /* initial supervision state */
64         MODE_TERMINATING,  /* user requested termination */
65         MODE_NOCHILD,      /* child is terminated, final state of the event loop */
66 };
67
68 struct daemon_state {
69         int pipe_fd[2];
70         char **argv;
71         const char *child_pidfile;
72         const char *parent_pidfile;
73         const char *output_filename;
74         const char *syslog_tag;
75         const char *title;
76         const char *user;
77         struct pidfh *parent_pidfh;
78         struct pidfh *child_pidfh;
79         enum daemon_mode mode;
80         int pid;
81         int keep_cur_workdir;
82         int restart_delay;
83         int stdmask;
84         int syslog_priority;
85         int syslog_facility;
86         int keep_fds_open;
87         int output_fd;
88         bool restart_enabled;
89         bool syslog_enabled;
90         bool log_reopen;
91 };
92
93 static void restrict_process(const char *);
94 static int  open_log(const char *);
95 static void reopen_log(struct daemon_state *);
96 static bool listen_child(int, struct daemon_state *);
97 static int  get_log_mapping(const char *, const CODE *);
98 static void open_pid_files(struct daemon_state *);
99 static void do_output(const unsigned char *, size_t, struct daemon_state *);
100 static void daemon_sleep(struct daemon_state *);
101 static void daemon_state_init(struct daemon_state *);
102 static void daemon_eventloop(struct daemon_state *);
103 static void daemon_terminate(struct daemon_state *);
104 static void daemon_exec(struct daemon_state *);
105 static bool daemon_is_child_dead(struct daemon_state *);
106 static void daemon_set_child_pipe(struct daemon_state *);
107
108 static const char shortopts[] = "+cfHSp:P:ru:o:s:l:t:m:R:T:h";
109
110 static const struct option longopts[] = {
111         { "change-dir",         no_argument,            NULL,           'c' },
112         { "close-fds",          no_argument,            NULL,           'f' },
113         { "sighup",             no_argument,            NULL,           'H' },
114         { "syslog",             no_argument,            NULL,           'S' },
115         { "output-file",        required_argument,      NULL,           'o' },
116         { "output-mask",        required_argument,      NULL,           'm' },
117         { "child-pidfile",      required_argument,      NULL,           'p' },
118         { "supervisor-pidfile", required_argument,      NULL,           'P' },
119         { "restart",            no_argument,            NULL,           'r' },
120         { "restart-delay",      required_argument,      NULL,           'R' },
121         { "title",              required_argument,      NULL,           't' },
122         { "user",               required_argument,      NULL,           'u' },
123         { "syslog-priority",    required_argument,      NULL,           's' },
124         { "syslog-facility",    required_argument,      NULL,           'l' },
125         { "syslog-tag",         required_argument,      NULL,           'T' },
126         { "help",               no_argument,            NULL,           'h' },
127         { NULL,                 0,                      NULL,            0  }
128 };
129
130 static _Noreturn void
131 usage(int exitcode)
132 {
133         (void)fprintf(stderr,
134             "usage: daemon [-cfHrS] [-p child_pidfile] [-P supervisor_pidfile]\n"
135             "              [-u user] [-o output_file] [-t title]\n"
136             "              [-l syslog_facility] [-s syslog_priority]\n"
137             "              [-T syslog_tag] [-m output_mask] [-R restart_delay_secs]\n"
138             "command arguments ...\n");
139
140         (void)fprintf(stderr,
141             "  --change-dir         -c         Change the current working directory to root\n"
142             "  --close-fds          -f         Set stdin, stdout, stderr to /dev/null\n"
143             "  --sighup             -H         Close and re-open output file on SIGHUP\n"
144             "  --syslog             -S         Send output to syslog\n"
145             "  --output-file        -o <file>  Append output of the child process to file\n"
146             "  --output-mask        -m <mask>  What to send to syslog/file\n"
147             "                                  1=stdout, 2=stderr, 3=both\n"
148             "  --child-pidfile      -p <file>  Write PID of the child process to file\n"
149             "  --supervisor-pidfile -P <file>  Write PID of the supervisor process to file\n"
150             "  --restart            -r         Restart child if it terminates (1 sec delay)\n"
151             "  --restart-delay      -R <N>     Restart child if it terminates after N sec\n"
152             "  --title              -t <title> Set the title of the supervisor process\n"
153             "  --user               -u <user>  Drop privileges, run as given user\n"
154             "  --syslog-priority    -s <prio>  Set syslog priority\n"
155             "  --syslog-facility    -l <flty>  Set syslog facility\n"
156             "  --syslog-tag         -T <tag>   Set syslog tag\n"
157             "  --help               -h         Show this help\n");
158
159         exit(exitcode);
160 }
161
162 int
163 main(int argc, char *argv[])
164 {
165         char *p = NULL;
166         int ch = 0;
167         struct daemon_state state;
168
169         daemon_state_init(&state);
170
171         /* Signals are processed via kqueue */
172         signal(SIGHUP, SIG_IGN);
173         signal(SIGTERM, SIG_IGN);
174
175         /*
176          * Supervision mode is enabled if one of the following options are used:
177          * --child-pidfile -p
178          * --supervisor-pidfile -P
179          * --restart -r / --restart-delay -R
180          * --syslog -S
181          * --syslog-facility -l
182          * --syslog-priority -s
183          * --syslog-tag -T
184          *
185          * In supervision mode daemon executes the command in a forked process
186          * and observes the child by waiting for SIGCHILD. In supervision mode
187          * daemon must never exit before the child, this is necessary  to prevent
188          * orphaning the child and leaving a stale pid file.
189          * To achieve this daemon catches SIGTERM and
190          * forwards it to the child, expecting to get SIGCHLD eventually.
191          */
192         while ((ch = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) {
193                 switch (ch) {
194                 case 'c':
195                         state.keep_cur_workdir = 0;
196                         break;
197                 case 'f':
198                         state.keep_fds_open = 0;
199                         break;
200                 case 'H':
201                         state.log_reopen = true;
202                         break;
203                 case 'l':
204                         state.syslog_facility = get_log_mapping(optarg,
205                             facilitynames);
206                         if (state.syslog_facility == -1) {
207                                 errx(5, "unrecognized syslog facility");
208                         }
209                         state.syslog_enabled = true;
210                         state.mode = MODE_SUPERVISE;
211                         break;
212                 case 'm':
213                         state.stdmask = strtol(optarg, &p, 10);
214                         if (p == optarg || state.stdmask < 0 || state.stdmask > 3) {
215                                 errx(6, "unrecognized listening mask");
216                         }
217                         break;
218                 case 'o':
219                         state.output_filename = optarg;
220                         /*
221                          * TODO: setting output filename doesn't have to turn
222                          * the supervision mode on. For non-supervised mode
223                          * daemon could open the specified file and set it's
224                          * descriptor as both stderr and stout before execve()
225                          */
226                         state.mode = MODE_SUPERVISE;
227                         break;
228                 case 'p':
229                         state.child_pidfile = optarg;
230                         state.mode = MODE_SUPERVISE;
231                         break;
232                 case 'P':
233                         state.parent_pidfile = optarg;
234                         state.mode = MODE_SUPERVISE;
235                         break;
236                 case 'r':
237                         state.restart_enabled = true;
238                         state.mode = MODE_SUPERVISE;
239                         break;
240                 case 'R':
241                         state.restart_enabled = true;
242                         state.restart_delay = strtol(optarg, &p, 0);
243                         if (p == optarg || state.restart_delay < 1) {
244                                 errx(6, "invalid restart delay");
245                         }
246                         break;
247                 case 's':
248                         state.syslog_priority = get_log_mapping(optarg,
249                             prioritynames);
250                         if (state.syslog_priority == -1) {
251                                 errx(4, "unrecognized syslog priority");
252                         }
253                         state.syslog_enabled = true;
254                         state.mode = MODE_SUPERVISE;
255                         break;
256                 case 'S':
257                         state.syslog_enabled = true;
258                         state.mode = MODE_SUPERVISE;
259                         break;
260                 case 't':
261                         state.title = optarg;
262                         break;
263                 case 'T':
264                         state.syslog_tag = optarg;
265                         state.syslog_enabled = true;
266                         state.mode = MODE_SUPERVISE;
267                         break;
268                 case 'u':
269                         state.user = optarg;
270                         break;
271                 case 'h':
272                         usage(0);
273                         __builtin_unreachable();
274                 default:
275                         usage(1);
276                 }
277         }
278         argc -= optind;
279         argv += optind;
280         state.argv = argv;
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
308         /*
309          * TODO: add feature to avoid backgrounding
310          * i.e. --foreground, -f
311          */
312         if (daemon(state.keep_cur_workdir, state.keep_fds_open) == -1) {
313                 warn("daemon");
314                 daemon_terminate(&state);
315         }
316
317         if (state.mode == MODE_DAEMON) {
318                 daemon_exec(&state);
319         }
320
321         /* Write out parent pidfile if needed. */
322         pidfile_write(state.parent_pidfh);
323
324         do {
325                 state.mode = MODE_SUPERVISE;
326                 daemon_eventloop(&state);
327                 daemon_sleep(&state);
328         } while (state.restart_enabled);
329
330         daemon_terminate(&state);
331 }
332
333 static void
334 daemon_exec(struct daemon_state *state)
335 {
336         pidfile_write(state->child_pidfh);
337
338         if (state->user != NULL) {
339                 restrict_process(state->user);
340         }
341
342         /* Ignored signals remain ignored after execve, unignore them */
343         signal(SIGHUP, SIG_DFL);
344         signal(SIGTERM, SIG_DFL);
345         execvp(state->argv[0], state->argv);
346         /* execvp() failed - report error and exit this process */
347         err(1, "%s", state->argv[0]);
348 }
349
350 /* Main event loop: fork the child and watch for events.
351  * After SIGTERM is recieved and propagated to the child there are
352  * several options on what to do next:
353  * - read until EOF
354  * - read until EOF but only for a while
355  * - bail immediately
356  * Currently the third option is used, because otherwise there is no
357  * guarantee that read() won't block indefinitely if the child refuses
358  * to depart. To handle the second option, a different approach
359  * would be needed (procctl()?).
360  */
361 static void
362 daemon_eventloop(struct daemon_state *state)
363 {
364         struct kevent event;
365         int kq;
366         int ret;
367
368         /*
369          * Try to protect against pageout kill. Ignore the
370          * error, madvise(2) will fail only if a process does
371          * not have superuser privileges.
372          */
373         (void)madvise(NULL, 0, MADV_PROTECT);
374
375         if (pipe(state->pipe_fd)) {
376                 err(1, "pipe");
377         }
378
379         kq = kqueuex(KQUEUE_CLOEXEC);
380         EV_SET(&event, state->pipe_fd[0], EVFILT_READ, EV_ADD|EV_CLEAR, 0, 0,
381             NULL);
382         if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
383                 err(EXIT_FAILURE, "failed to register kevent");
384         }
385
386         EV_SET(&event, SIGHUP,  EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
387         if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
388                 err(EXIT_FAILURE, "failed to register kevent");
389         }
390
391         EV_SET(&event, SIGTERM, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
392         if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
393                 err(EXIT_FAILURE, "failed to register kevent");
394         }
395
396         EV_SET(&event, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
397         if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
398                 err(EXIT_FAILURE, "failed to register kevent");
399         }
400         memset(&event, 0, sizeof(struct kevent));
401
402         /* Spawn a child to exec the command. */
403         state->pid = fork();
404
405         /* fork failed, this can only happen when supervision is enabled */
406         switch (state->pid) {
407         case -1:
408                 warn("fork");
409                 state->mode = MODE_NOCHILD;
410                 return;
411         /* fork succeeded, this is child's branch */
412         case 0:
413                 close(kq);
414                 daemon_set_child_pipe(state);
415                 daemon_exec(state);
416                 break;
417         }
418
419         /* case: pid > 0; fork succeeded */
420         close(state->pipe_fd[1]);
421         state->pipe_fd[1] = -1;
422         setproctitle("%s[%d]", state->title, (int)state->pid);
423         setbuf(stdout, NULL);
424
425         while (state->mode != MODE_NOCHILD) {
426                 ret = kevent(kq, NULL, 0, &event, 1, NULL);
427                 switch (ret) {
428                 case -1:
429                         if (errno == EINTR)
430                                 continue;
431                         err(EXIT_FAILURE, "kevent wait");
432                 case 0:
433                         continue;
434                 }
435
436                 if (event.flags & EV_ERROR) {
437                         errx(EXIT_FAILURE, "Event error: %s",
438                             strerror(event.data));
439                 }
440
441                 switch (event.filter) {
442                 case EVFILT_SIGNAL:
443
444                         switch (event.ident) {
445                         case SIGCHLD:
446                                 if (daemon_is_child_dead(state)) {
447                                         /* child is dead, read all until EOF */
448                                         state->pid = -1;
449                                         state->mode = MODE_NOCHILD;
450                                         while (listen_child(state->pipe_fd[0],
451                                             state))
452                                                 ;
453                                 }
454                                 continue;
455                         case SIGTERM:
456                                 if (state->mode != MODE_SUPERVISE) {
457                                         /* user is impatient */
458                                         /* TODO: warn about repeated SIGTERM? */
459                                         continue;
460                                 }
461
462                                 state->mode = MODE_TERMINATING;
463                                 state->restart_enabled = false;
464                                 if (state->pid > 0) {
465                                         kill(state->pid, SIGTERM);
466                                 }
467                                 /*
468                                  * TODO set kevent timer to exit
469                                  * unconditionally after some time
470                                  */
471                                 continue;
472                         case SIGHUP:
473                                 if (state->log_reopen && state->output_fd >= 0) {
474                                         reopen_log(state);
475                                 }
476                                 continue;
477                         }
478                         break;
479
480                 case EVFILT_READ:
481                         /*
482                          * detecting EOF is no longer necessary
483                          * if child closes the pipe daemon will stop getting
484                          * EVFILT_READ events
485                          */
486
487                         if (event.data > 0) {
488                                 (void)listen_child(state->pipe_fd[0], state);
489                         }
490                         continue;
491                 default:
492                         continue;
493                 }
494         }
495
496         close(kq);
497         close(state->pipe_fd[0]);
498         state->pipe_fd[0] = -1;
499 }
500
501 static void
502 daemon_sleep(struct daemon_state *state)
503 {
504         struct timespec ts = { state->restart_delay, 0 };
505
506         if (!state->restart_enabled) {
507                 return;
508         }
509         while (nanosleep(&ts, &ts) == -1) {
510                 if (errno != EINTR) {
511                         err(1, "nanosleep");
512                 }
513         }
514 }
515
516 static void
517 open_pid_files(struct daemon_state *state)
518 {
519         pid_t fpid;
520         int serrno;
521
522         if (state->child_pidfile) {
523                 state->child_pidfh = pidfile_open(state->child_pidfile, 0600, &fpid);
524                 if (state->child_pidfh == NULL) {
525                         if (errno == EEXIST) {
526                                 errx(3, "process already running, pid: %d",
527                                     fpid);
528                         }
529                         err(2, "pidfile ``%s''", state->child_pidfile);
530                 }
531         }
532         /* Do the same for the actual daemon process. */
533         if (state->parent_pidfile) {
534                 state->parent_pidfh= pidfile_open(state->parent_pidfile, 0600, &fpid);
535                 if (state->parent_pidfh == NULL) {
536                         serrno = errno;
537                         pidfile_remove(state->child_pidfh);
538                         errno = serrno;
539                         if (errno == EEXIST) {
540                                 errx(3, "process already running, pid: %d",
541                                      fpid);
542                         }
543                         err(2, "ppidfile ``%s''", state->parent_pidfile);
544                 }
545         }
546 }
547
548 static int
549 get_log_mapping(const char *str, const CODE *c)
550 {
551         const CODE *cp;
552         for (cp = c; cp->c_name; cp++)
553                 if (strcmp(cp->c_name, str) == 0) {
554                         return cp->c_val;
555                 }
556         return -1;
557 }
558
559 static void
560 restrict_process(const char *user)
561 {
562         struct passwd *pw = NULL;
563
564         pw = getpwnam(user);
565         if (pw == NULL) {
566                 errx(1, "unknown user: %s", user);
567         }
568
569         if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0) {
570                 errx(1, "failed to set user environment");
571         }
572
573         setenv("USER", pw->pw_name, 1);
574         setenv("HOME", pw->pw_dir, 1);
575         setenv("SHELL", *pw->pw_shell ? pw->pw_shell : _PATH_BSHELL, 1);
576 }
577
578 /*
579  * We try to collect whole lines terminated by '\n'. Otherwise we collect a
580  * full buffer, and then output it.
581  *
582  * Return value of false is assumed to mean EOF or error, and true indicates to
583  * continue reading.
584  *
585  * TODO: simplify signature - state contains pipefd
586  */
587 static bool
588 listen_child(int fd, struct daemon_state *state)
589 {
590         static unsigned char buf[LBUF_SIZE];
591         static size_t bytes_read = 0;
592         int rv;
593
594         assert(state != NULL);
595         assert(bytes_read < LBUF_SIZE - 1);
596
597         rv = read(fd, buf + bytes_read, LBUF_SIZE - bytes_read - 1);
598         if (rv > 0) {
599                 unsigned char *cp;
600
601                 bytes_read += rv;
602                 assert(bytes_read <= LBUF_SIZE - 1);
603                 /* Always NUL-terminate just in case. */
604                 buf[LBUF_SIZE - 1] = '\0';
605                 /*
606                  * Chomp line by line until we run out of buffer.
607                  * This does not take NUL characters into account.
608                  */
609                 while ((cp = memchr(buf, '\n', bytes_read)) != NULL) {
610                         size_t bytes_line = cp - buf + 1;
611                         assert(bytes_line <= bytes_read);
612                         do_output(buf, bytes_line, state);
613                         bytes_read -= bytes_line;
614                         memmove(buf, cp + 1, bytes_read);
615                 }
616                 /* Wait until the buffer is full. */
617                 if (bytes_read < LBUF_SIZE - 1) {
618                         return true;
619                 }
620                 do_output(buf, bytes_read, state);
621                 bytes_read = 0;
622                 return true;
623         } else if (rv == -1) {
624                 /* EINTR should trigger another read. */
625                 if (errno == EINTR) {
626                         return true;
627                 } else {
628                         warn("read");
629                         return false;
630                 }
631         }
632         /* Upon EOF, we have to flush what's left of the buffer. */
633         if (bytes_read > 0) {
634                 do_output(buf, bytes_read, state);
635                 bytes_read = 0;
636         }
637         return false;
638 }
639
640 /*
641  * The default behavior is to stay silent if the user wants to redirect
642  * output to a file and/or syslog. If neither are provided, then we bounce
643  * everything back to parent's stdout.
644  */
645 static void
646 do_output(const unsigned char *buf, size_t len, struct daemon_state *state)
647 {
648         assert(len <= LBUF_SIZE);
649         assert(state != NULL);
650
651         if (len < 1) {
652                 return;
653         }
654         if (state->syslog_enabled) {
655                 syslog(state->syslog_priority, "%.*s", (int)len, buf);
656         }
657         if (state->output_fd != -1) {
658                 if (write(state->output_fd, buf, len) == -1)
659                         warn("write");
660         }
661         if (state->keep_fds_open &&
662             !state->syslog_enabled &&
663             state->output_fd == -1) {
664                 printf("%.*s", (int)len, buf);
665         }
666 }
667
668 static int
669 open_log(const char *outfn)
670 {
671
672         return open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
673 }
674
675 static void
676 reopen_log(struct daemon_state *state)
677 {
678         int outfd;
679
680         outfd = open_log(state->output_filename);
681         if (state->output_fd >= 0) {
682                 close(state->output_fd);
683         }
684         state->output_fd = outfd;
685 }
686
687 static void
688 daemon_state_init(struct daemon_state *state)
689 {
690         *state = (struct daemon_state) {
691                 .pipe_fd = { -1, -1 },
692                 .argv = NULL,
693                 .parent_pidfh = NULL,
694                 .child_pidfh = NULL,
695                 .child_pidfile = NULL,
696                 .parent_pidfile = NULL,
697                 .title = NULL,
698                 .user = NULL,
699                 .mode = MODE_DAEMON,
700                 .restart_enabled = false,
701                 .pid = 0,
702                 .keep_cur_workdir = 1,
703                 .restart_delay = 1,
704                 .stdmask = STDOUT_FILENO | STDERR_FILENO,
705                 .syslog_enabled = false,
706                 .log_reopen = false,
707                 .syslog_priority = LOG_NOTICE,
708                 .syslog_tag = "daemon",
709                 .syslog_facility = LOG_DAEMON,
710                 .keep_fds_open = 1,
711                 .output_fd = -1,
712                 .output_filename = NULL,
713         };
714 }
715
716 static _Noreturn void
717 daemon_terminate(struct daemon_state *state)
718 {
719         assert(state != NULL);
720
721         if (state->output_fd >= 0) {
722                 close(state->output_fd);
723         }
724         if (state->pipe_fd[0] >= 0) {
725                 close(state->pipe_fd[0]);
726         }
727
728         if (state->pipe_fd[1] >= 0) {
729                 close(state->pipe_fd[1]);
730         }
731         if (state->syslog_enabled) {
732                 closelog();
733         }
734         pidfile_remove(state->child_pidfh);
735         pidfile_remove(state->parent_pidfh);
736
737         /*
738          * Note that the exit value here doesn't matter in the case of a clean
739          * exit; daemon(3) already detached us from the caller, nothing is left
740          * to care about this one.
741          */
742         exit(1);
743 }
744
745 /*
746  * Returns true if SIGCHILD came from state->pid
747  * This function could hang if SIGCHILD was emittied for a reason other than
748  * child dying (e.g., ptrace attach).
749  */
750 static bool
751 daemon_is_child_dead(struct daemon_state *state)
752 {
753         for (;;) {
754                 int who = waitpid(-1, NULL, WNOHANG);
755                 if (state->pid == who) {
756                         return true;
757                 }
758                 if (who == -1 && errno != EINTR) {
759                         warn("waitpid");
760                         return false;
761                 }
762         }
763 }
764
765 static void
766 daemon_set_child_pipe(struct daemon_state *state)
767 {
768         if (state->stdmask & STDERR_FILENO) {
769                 if (dup2(state->pipe_fd[1], STDERR_FILENO) == -1) {
770                         err(1, "dup2");
771                 }
772         }
773         if (state->stdmask & STDOUT_FILENO) {
774                 if (dup2(state->pipe_fd[1], STDOUT_FILENO) == -1) {
775                         err(1, "dup2");
776                 }
777         }
778         if (state->pipe_fd[1] != STDERR_FILENO &&
779             state->pipe_fd[1] != STDOUT_FILENO) {
780                 close(state->pipe_fd[1]);
781         }
782
783         /* The child gets dup'd pipes. */
784         close(state->pipe_fd[0]);
785 }