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 kqueue_fd;
83 int restart_delay;
84 int stdmask;
85 int syslog_priority;
86 int syslog_facility;
87 int keep_fds_open;
88 int output_fd;
89 bool restart_enabled;
90 bool syslog_enabled;
91 bool log_reopen;
92 };
93
94 static void restrict_process(const char *);
95 static int open_log(const char *);
96 static void reopen_log(struct daemon_state *);
97 static bool listen_child(int, struct daemon_state *);
98 static int get_log_mapping(const char *, const CODE *);
99 static void open_pid_files(struct daemon_state *);
100 static void do_output(const unsigned char *, size_t, struct daemon_state *);
101 static void daemon_sleep(struct daemon_state *);
102 static void daemon_state_init(struct daemon_state *);
103 static void daemon_eventloop(struct daemon_state *);
104 static void daemon_terminate(struct daemon_state *);
105 static void daemon_exec(struct daemon_state *);
106 static bool daemon_is_child_dead(struct daemon_state *);
107 static void daemon_set_child_pipe(struct daemon_state *);
108 static int daemon_setup_kqueue(void);
109
110 static const char shortopts[] = "+cfHSp:P:ru:o:s:l:t:m:R:T:h";
111
112 static const struct option longopts[] = {
113 { "change-dir", no_argument, NULL, 'c' },
114 { "close-fds", no_argument, NULL, 'f' },
115 { "sighup", no_argument, NULL, 'H' },
116 { "syslog", no_argument, NULL, 'S' },
117 { "output-file", required_argument, NULL, 'o' },
118 { "output-mask", required_argument, NULL, 'm' },
119 { "child-pidfile", required_argument, NULL, 'p' },
120 { "supervisor-pidfile", required_argument, NULL, 'P' },
121 { "restart", no_argument, NULL, 'r' },
122 { "restart-delay", required_argument, NULL, 'R' },
123 { "title", required_argument, NULL, 't' },
124 { "user", required_argument, NULL, 'u' },
125 { "syslog-priority", required_argument, NULL, 's' },
126 { "syslog-facility", required_argument, NULL, 'l' },
127 { "syslog-tag", required_argument, NULL, 'T' },
128 { "help", no_argument, NULL, 'h' },
129 { NULL, 0, NULL, 0 }
130 };
131
132 static _Noreturn void
usage(int exitcode)133 usage(int exitcode)
134 {
135 (void)fprintf(stderr,
136 "usage: daemon [-cfHrS] [-p child_pidfile] [-P supervisor_pidfile]\n"
137 " [-u user] [-o output_file] [-t title]\n"
138 " [-l syslog_facility] [-s syslog_priority]\n"
139 " [-T syslog_tag] [-m output_mask] [-R restart_delay_secs]\n"
140 "command arguments ...\n");
141
142 (void)fprintf(stderr,
143 " --change-dir -c Change the current working directory to root\n"
144 " --close-fds -f Set stdin, stdout, stderr to /dev/null\n"
145 " --sighup -H Close and re-open output file on SIGHUP\n"
146 " --syslog -S Send output to syslog\n"
147 " --output-file -o <file> Append output of the child process to file\n"
148 " --output-mask -m <mask> What to send to syslog/file\n"
149 " 1=stdout, 2=stderr, 3=both\n"
150 " --child-pidfile -p <file> Write PID of the child process to file\n"
151 " --supervisor-pidfile -P <file> Write PID of the supervisor process to file\n"
152 " --restart -r Restart child if it terminates (1 sec delay)\n"
153 " --restart-delay -R <N> Restart child if it terminates after N sec\n"
154 " --title -t <title> Set the title of the supervisor process\n"
155 " --user -u <user> Drop privileges, run as given user\n"
156 " --syslog-priority -s <prio> Set syslog priority\n"
157 " --syslog-facility -l <flty> Set syslog facility\n"
158 " --syslog-tag -T <tag> Set syslog tag\n"
159 " --help -h Show this help\n");
160
161 exit(exitcode);
162 }
163
164 int
main(int argc,char * argv[])165 main(int argc, char *argv[])
166 {
167 char *p = NULL;
168 int ch = 0;
169 struct daemon_state state;
170
171 daemon_state_init(&state);
172
173 /* Signals are processed via kqueue */
174 signal(SIGHUP, SIG_IGN);
175 signal(SIGTERM, SIG_IGN);
176
177 /*
178 * Supervision mode is enabled if one of the following options are used:
179 * --child-pidfile -p
180 * --supervisor-pidfile -P
181 * --restart -r / --restart-delay -R
182 * --syslog -S
183 * --syslog-facility -l
184 * --syslog-priority -s
185 * --syslog-tag -T
186 *
187 * In supervision mode daemon executes the command in a forked process
188 * and observes the child by waiting for SIGCHILD. In supervision mode
189 * daemon must never exit before the child, this is necessary to prevent
190 * orphaning the child and leaving a stale pid file.
191 * To achieve this daemon catches SIGTERM and
192 * forwards it to the child, expecting to get SIGCHLD eventually.
193 */
194 while ((ch = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) {
195 switch (ch) {
196 case 'c':
197 state.keep_cur_workdir = 0;
198 break;
199 case 'f':
200 state.keep_fds_open = 0;
201 break;
202 case 'H':
203 state.log_reopen = true;
204 break;
205 case 'l':
206 state.syslog_facility = get_log_mapping(optarg,
207 facilitynames);
208 if (state.syslog_facility == -1) {
209 errx(5, "unrecognized syslog facility");
210 }
211 state.syslog_enabled = true;
212 state.mode = MODE_SUPERVISE;
213 break;
214 case 'm':
215 state.stdmask = strtol(optarg, &p, 10);
216 if (p == optarg || state.stdmask < 0 || state.stdmask > 3) {
217 errx(6, "unrecognized listening mask");
218 }
219 break;
220 case 'o':
221 state.output_filename = optarg;
222 /*
223 * TODO: setting output filename doesn't have to turn
224 * the supervision mode on. For non-supervised mode
225 * daemon could open the specified file and set it's
226 * descriptor as both stderr and stout before execve()
227 */
228 state.mode = MODE_SUPERVISE;
229 break;
230 case 'p':
231 state.child_pidfile = optarg;
232 state.mode = MODE_SUPERVISE;
233 break;
234 case 'P':
235 state.parent_pidfile = optarg;
236 state.mode = MODE_SUPERVISE;
237 break;
238 case 'r':
239 state.restart_enabled = true;
240 state.mode = MODE_SUPERVISE;
241 break;
242 case 'R':
243 state.restart_enabled = true;
244 state.restart_delay = strtol(optarg, &p, 0);
245 if (p == optarg || state.restart_delay < 1) {
246 errx(6, "invalid restart delay");
247 }
248 state.mode = MODE_SUPERVISE;
249 break;
250 case 's':
251 state.syslog_priority = get_log_mapping(optarg,
252 prioritynames);
253 if (state.syslog_priority == -1) {
254 errx(4, "unrecognized syslog priority");
255 }
256 state.syslog_enabled = true;
257 state.mode = MODE_SUPERVISE;
258 break;
259 case 'S':
260 state.syslog_enabled = true;
261 state.mode = MODE_SUPERVISE;
262 break;
263 case 't':
264 state.title = optarg;
265 break;
266 case 'T':
267 state.syslog_tag = optarg;
268 state.syslog_enabled = true;
269 state.mode = MODE_SUPERVISE;
270 break;
271 case 'u':
272 state.user = optarg;
273 break;
274 case 'h':
275 usage(0);
276 __builtin_unreachable();
277 default:
278 usage(1);
279 }
280 }
281 argc -= optind;
282 argv += optind;
283 state.argv = argv;
284
285 if (argc == 0) {
286 usage(1);
287 }
288
289 if (!state.title) {
290 state.title = argv[0];
291 }
292
293 if (state.output_filename) {
294 state.output_fd = open_log(state.output_filename);
295 if (state.output_fd == -1) {
296 err(7, "open");
297 }
298 }
299
300 if (state.syslog_enabled) {
301 openlog(state.syslog_tag, LOG_PID | LOG_NDELAY,
302 state.syslog_facility);
303 }
304
305 /*
306 * Try to open the pidfile before calling daemon(3),
307 * to be able to report the error intelligently
308 */
309 open_pid_files(&state);
310
311 /*
312 * TODO: add feature to avoid backgrounding
313 * i.e. --foreground, -f
314 */
315 if (daemon(state.keep_cur_workdir, state.keep_fds_open) == -1) {
316 warn("daemon");
317 daemon_terminate(&state);
318 }
319
320 if (state.mode == MODE_DAEMON) {
321 daemon_exec(&state);
322 }
323
324 /* Write out parent pidfile if needed. */
325 pidfile_write(state.parent_pidfh);
326
327 state.kqueue_fd = daemon_setup_kqueue();
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
daemon_exec(struct daemon_state * state)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 recieved 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
daemon_eventloop(struct daemon_state * state)367 daemon_eventloop(struct daemon_state *state)
368 {
369 struct kevent event;
370 int kq;
371 int ret;
372
373 /*
374 * Try to protect against pageout kill. Ignore the
375 * error, madvise(2) will fail only if a process does
376 * not have superuser privileges.
377 */
378 (void)madvise(NULL, 0, MADV_PROTECT);
379
380 if (pipe(state->pipe_fd)) {
381 err(1, "pipe");
382 }
383
384 kq = state->kqueue_fd;
385 EV_SET(&event, state->pipe_fd[0], EVFILT_READ, EV_ADD|EV_CLEAR, 0, 0,
386 NULL);
387 if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
388 err(EXIT_FAILURE, "failed to register kevent");
389 }
390
391 memset(&event, 0, sizeof(struct kevent));
392
393 /* Spawn a child to exec the command. */
394 state->pid = fork();
395
396 /* fork failed, this can only happen when supervision is enabled */
397 switch (state->pid) {
398 case -1:
399 warn("fork");
400 state->mode = MODE_NOCHILD;
401 return;
402 /* fork succeeded, this is child's branch */
403 case 0:
404 close(kq);
405 daemon_set_child_pipe(state);
406 daemon_exec(state);
407 break;
408 }
409
410 /* case: pid > 0; fork succeeded */
411 close(state->pipe_fd[1]);
412 state->pipe_fd[1] = -1;
413 setproctitle("%s[%d]", state->title, (int)state->pid);
414 setbuf(stdout, NULL);
415
416 while (state->mode != MODE_NOCHILD) {
417 ret = kevent(kq, NULL, 0, &event, 1, NULL);
418 switch (ret) {
419 case -1:
420 if (errno == EINTR)
421 continue;
422 err(EXIT_FAILURE, "kevent wait");
423 case 0:
424 continue;
425 }
426
427 if (event.flags & EV_ERROR) {
428 errx(EXIT_FAILURE, "Event error: %s",
429 strerror(event.data));
430 }
431
432 switch (event.filter) {
433 case EVFILT_SIGNAL:
434
435 switch (event.ident) {
436 case SIGCHLD:
437 if (daemon_is_child_dead(state)) {
438 /* child is dead, read all until EOF */
439 state->pid = -1;
440 state->mode = MODE_NOCHILD;
441 while (listen_child(state->pipe_fd[0],
442 state))
443 ;
444 }
445 continue;
446 case SIGTERM:
447 if (state->mode != MODE_SUPERVISE) {
448 /* user is impatient */
449 /* TODO: warn about repeated SIGTERM? */
450 continue;
451 }
452
453 state->mode = MODE_TERMINATING;
454 state->restart_enabled = false;
455 if (state->pid > 0) {
456 kill(state->pid, SIGTERM);
457 }
458 /*
459 * TODO set kevent timer to exit
460 * unconditionally after some time
461 */
462 continue;
463 case SIGHUP:
464 if (state->log_reopen && state->output_fd >= 0) {
465 reopen_log(state);
466 }
467 continue;
468 }
469 break;
470
471 case EVFILT_READ:
472 /*
473 * detecting EOF is no longer necessary
474 * if child closes the pipe daemon will stop getting
475 * EVFILT_READ events
476 */
477
478 if (event.data > 0) {
479 (void)listen_child(state->pipe_fd[0], state);
480 }
481 continue;
482 default:
483 assert(0 && "Unexpected kevent filter type");
484 continue;
485 }
486 }
487
488 /* EVFILT_READ kqueue filter goes away here. */
489 close(state->pipe_fd[0]);
490 state->pipe_fd[0] = -1;
491 }
492
493 /*
494 * Note that daemon_sleep() should not be called with anything but the signal
495 * events in the kqueue without further consideration.
496 */
497 static void
daemon_sleep(struct daemon_state * state)498 daemon_sleep(struct daemon_state *state)
499 {
500 struct kevent event = { 0 };
501 int ret;
502
503 assert(state->pipe_fd[0] == -1);
504 assert(state->pipe_fd[1] == -1);
505
506 if (!state->restart_enabled) {
507 return;
508 }
509
510 EV_SET(&event, 0, EVFILT_TIMER, EV_ADD|EV_ONESHOT, NOTE_SECONDS,
511 state->restart_delay, NULL);
512 if (kevent(state->kqueue_fd, &event, 1, NULL, 0, NULL) == -1) {
513 err(1, "failed to register timer");
514 }
515
516 for (;;) {
517 ret = kevent(state->kqueue_fd, NULL, 0, &event, 1, NULL);
518 if (ret == -1) {
519 if (errno != EINTR) {
520 err(1, "kevent");
521 }
522
523 continue;
524 }
525
526 /*
527 * Any other events being raised are indicative of a problem
528 * that we need to investigate. Most likely being that
529 * something was not cleaned up from the eventloop.
530 */
531 assert(event.filter == EVFILT_TIMER ||
532 event.filter == EVFILT_SIGNAL);
533
534 if (event.filter == EVFILT_TIMER) {
535 /* Break's over, back to work. */
536 break;
537 }
538
539 /* Process any pending signals. */
540 switch (event.ident) {
541 case SIGTERM:
542 /*
543 * We could disarm the timer, but we'll be terminating
544 * promptly anyways.
545 */
546 state->restart_enabled = false;
547 return;
548 case SIGHUP:
549 if (state->log_reopen && state->output_fd >= 0) {
550 reopen_log(state);
551 }
552
553 break;
554 case SIGCHLD:
555 default:
556 /* Discard */
557 break;
558 }
559 }
560
561 /* SIGTERM should've returned immediately. */
562 assert(state->restart_enabled);
563 }
564
565 static void
open_pid_files(struct daemon_state * state)566 open_pid_files(struct daemon_state *state)
567 {
568 pid_t fpid;
569 int serrno;
570
571 if (state->child_pidfile) {
572 state->child_pidfh = pidfile_open(state->child_pidfile, 0600, &fpid);
573 if (state->child_pidfh == NULL) {
574 if (errno == EEXIST) {
575 errx(3, "process already running, pid: %d",
576 fpid);
577 }
578 err(2, "pidfile ``%s''", state->child_pidfile);
579 }
580 }
581 /* Do the same for the actual daemon process. */
582 if (state->parent_pidfile) {
583 state->parent_pidfh= pidfile_open(state->parent_pidfile, 0600, &fpid);
584 if (state->parent_pidfh == NULL) {
585 serrno = errno;
586 pidfile_remove(state->child_pidfh);
587 errno = serrno;
588 if (errno == EEXIST) {
589 errx(3, "process already running, pid: %d",
590 fpid);
591 }
592 err(2, "ppidfile ``%s''", state->parent_pidfile);
593 }
594 }
595 }
596
597 static int
get_log_mapping(const char * str,const CODE * c)598 get_log_mapping(const char *str, const CODE *c)
599 {
600 const CODE *cp;
601 for (cp = c; cp->c_name; cp++)
602 if (strcmp(cp->c_name, str) == 0) {
603 return cp->c_val;
604 }
605 return -1;
606 }
607
608 static void
restrict_process(const char * user)609 restrict_process(const char *user)
610 {
611 struct passwd *pw = NULL;
612
613 pw = getpwnam(user);
614 if (pw == NULL) {
615 errx(1, "unknown user: %s", user);
616 }
617
618 if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0) {
619 errx(1, "failed to set user environment");
620 }
621
622 setenv("USER", pw->pw_name, 1);
623 setenv("HOME", pw->pw_dir, 1);
624 setenv("SHELL", *pw->pw_shell ? pw->pw_shell : _PATH_BSHELL, 1);
625 }
626
627 /*
628 * We try to collect whole lines terminated by '\n'. Otherwise we collect a
629 * full buffer, and then output it.
630 *
631 * Return value of false is assumed to mean EOF or error, and true indicates to
632 * continue reading.
633 *
634 * TODO: simplify signature - state contains pipefd
635 */
636 static bool
listen_child(int fd,struct daemon_state * state)637 listen_child(int fd, struct daemon_state *state)
638 {
639 static unsigned char buf[LBUF_SIZE];
640 static size_t bytes_read = 0;
641 int rv;
642
643 assert(state != NULL);
644 assert(bytes_read < LBUF_SIZE - 1);
645
646 rv = read(fd, buf + bytes_read, LBUF_SIZE - bytes_read - 1);
647 if (rv > 0) {
648 unsigned char *cp;
649
650 bytes_read += rv;
651 assert(bytes_read <= LBUF_SIZE - 1);
652 /* Always NUL-terminate just in case. */
653 buf[LBUF_SIZE - 1] = '\0';
654 /*
655 * Chomp line by line until we run out of buffer.
656 * This does not take NUL characters into account.
657 */
658 while ((cp = memchr(buf, '\n', bytes_read)) != NULL) {
659 size_t bytes_line = cp - buf + 1;
660 assert(bytes_line <= bytes_read);
661 do_output(buf, bytes_line, state);
662 bytes_read -= bytes_line;
663 memmove(buf, cp + 1, bytes_read);
664 }
665 /* Wait until the buffer is full. */
666 if (bytes_read < LBUF_SIZE - 1) {
667 return true;
668 }
669 do_output(buf, bytes_read, state);
670 bytes_read = 0;
671 return true;
672 } else if (rv == -1) {
673 /* EINTR should trigger another read. */
674 if (errno == EINTR) {
675 return true;
676 } else {
677 warn("read");
678 return false;
679 }
680 }
681 /* Upon EOF, we have to flush what's left of the buffer. */
682 if (bytes_read > 0) {
683 do_output(buf, bytes_read, state);
684 bytes_read = 0;
685 }
686 return false;
687 }
688
689 /*
690 * The default behavior is to stay silent if the user wants to redirect
691 * output to a file and/or syslog. If neither are provided, then we bounce
692 * everything back to parent's stdout.
693 */
694 static void
do_output(const unsigned char * buf,size_t len,struct daemon_state * state)695 do_output(const unsigned char *buf, size_t len, struct daemon_state *state)
696 {
697 assert(len <= LBUF_SIZE);
698 assert(state != NULL);
699
700 if (len < 1) {
701 return;
702 }
703 if (state->syslog_enabled) {
704 syslog(state->syslog_priority, "%.*s", (int)len, buf);
705 }
706 if (state->output_fd != -1) {
707 if (write(state->output_fd, buf, len) == -1)
708 warn("write");
709 }
710 if (state->keep_fds_open &&
711 !state->syslog_enabled &&
712 state->output_fd == -1) {
713 printf("%.*s", (int)len, buf);
714 }
715 }
716
717 static int
open_log(const char * outfn)718 open_log(const char *outfn)
719 {
720
721 return open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
722 }
723
724 static void
reopen_log(struct daemon_state * state)725 reopen_log(struct daemon_state *state)
726 {
727 int outfd;
728
729 outfd = open_log(state->output_filename);
730 if (state->output_fd >= 0) {
731 close(state->output_fd);
732 }
733 state->output_fd = outfd;
734 }
735
736 static void
daemon_state_init(struct daemon_state * state)737 daemon_state_init(struct daemon_state *state)
738 {
739 *state = (struct daemon_state) {
740 .pipe_fd = { -1, -1 },
741 .argv = NULL,
742 .parent_pidfh = NULL,
743 .child_pidfh = NULL,
744 .child_pidfile = NULL,
745 .parent_pidfile = NULL,
746 .title = NULL,
747 .user = NULL,
748 .mode = MODE_DAEMON,
749 .restart_enabled = false,
750 .pid = 0,
751 .keep_cur_workdir = 1,
752 .kqueue_fd = -1,
753 .restart_delay = 1,
754 .stdmask = STDOUT_FILENO | STDERR_FILENO,
755 .syslog_enabled = false,
756 .log_reopen = false,
757 .syslog_priority = LOG_NOTICE,
758 .syslog_tag = "daemon",
759 .syslog_facility = LOG_DAEMON,
760 .keep_fds_open = 1,
761 .output_fd = -1,
762 .output_filename = NULL,
763 };
764 }
765
766 static _Noreturn void
daemon_terminate(struct daemon_state * state)767 daemon_terminate(struct daemon_state *state)
768 {
769 assert(state != NULL);
770
771 if (state->kqueue_fd >= 0) {
772 close(state->kqueue_fd);
773 }
774 if (state->output_fd >= 0) {
775 close(state->output_fd);
776 }
777 if (state->pipe_fd[0] >= 0) {
778 close(state->pipe_fd[0]);
779 }
780
781 if (state->pipe_fd[1] >= 0) {
782 close(state->pipe_fd[1]);
783 }
784 if (state->syslog_enabled) {
785 closelog();
786 }
787 pidfile_remove(state->child_pidfh);
788 pidfile_remove(state->parent_pidfh);
789
790 /*
791 * Note that the exit value here doesn't matter in the case of a clean
792 * exit; daemon(3) already detached us from the caller, nothing is left
793 * to care about this one.
794 */
795 exit(1);
796 }
797
798 /*
799 * Returns true if SIGCHILD came from state->pid due to its exit.
800 */
801 static bool
daemon_is_child_dead(struct daemon_state * state)802 daemon_is_child_dead(struct daemon_state *state)
803 {
804 int status;
805
806 for (;;) {
807 int who = waitpid(-1, &status, WNOHANG);
808 if (state->pid == who && (WIFEXITED(status) ||
809 WIFSIGNALED(status))) {
810 return true;
811 }
812 if (who == 0) {
813 return false;
814 }
815 if (who == -1 && errno != EINTR) {
816 warn("waitpid");
817 return false;
818 }
819 }
820 }
821
822 static void
daemon_set_child_pipe(struct daemon_state * state)823 daemon_set_child_pipe(struct daemon_state *state)
824 {
825 if (state->stdmask & STDERR_FILENO) {
826 if (dup2(state->pipe_fd[1], STDERR_FILENO) == -1) {
827 err(1, "dup2");
828 }
829 }
830 if (state->stdmask & STDOUT_FILENO) {
831 if (dup2(state->pipe_fd[1], STDOUT_FILENO) == -1) {
832 err(1, "dup2");
833 }
834 }
835 if (state->pipe_fd[1] != STDERR_FILENO &&
836 state->pipe_fd[1] != STDOUT_FILENO) {
837 close(state->pipe_fd[1]);
838 }
839
840 /* The child gets dup'd pipes. */
841 close(state->pipe_fd[0]);
842 }
843
844 static int
daemon_setup_kqueue(void)845 daemon_setup_kqueue(void)
846 {
847 int kq;
848 struct kevent event = { 0 };
849
850 kq = kqueuex(KQUEUE_CLOEXEC);
851 if (kq == -1) {
852 err(EXIT_FAILURE, "kqueue");
853 }
854
855 EV_SET(&event, SIGHUP, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
856 if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
857 err(EXIT_FAILURE, "failed to register kevent");
858 }
859
860 EV_SET(&event, SIGTERM, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
861 if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
862 err(EXIT_FAILURE, "failed to register kevent");
863 }
864
865 EV_SET(&event, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
866 if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
867 err(EXIT_FAILURE, "failed to register kevent");
868 }
869
870 return (kq);
871 }
872