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