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