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