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