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