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