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