xref: /freebsd/usr.sbin/daemon/daemon.c (revision ecf4106237505fa9459ae871793b754334989c17)
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 			break;
252 		case 's':
253 			state.syslog_priority = get_log_mapping(optarg,
254 			    prioritynames);
255 			if (state.syslog_priority == -1) {
256 				errx(4, "unrecognized syslog priority");
257 			}
258 			state.syslog_enabled = true;
259 			state.mode = MODE_SUPERVISE;
260 			break;
261 		case 'S':
262 			state.syslog_enabled = true;
263 			state.mode = MODE_SUPERVISE;
264 			break;
265 		case 't':
266 			state.title = optarg;
267 			break;
268 		case 'T':
269 			state.syslog_tag = optarg;
270 			state.syslog_enabled = true;
271 			state.mode = MODE_SUPERVISE;
272 			break;
273 		case 'u':
274 			state.user = optarg;
275 			break;
276 		case 'h':
277 			usage(0);
278 			__builtin_unreachable();
279 		default:
280 			usage(1);
281 		}
282 	}
283 	argc -= optind;
284 	argv += optind;
285 	state.argv = argv;
286 
287 	if (argc == 0) {
288 		usage(1);
289 	}
290 
291 	if (!state.title) {
292 		state.title = argv[0];
293 	}
294 
295 	if (state.output_filename) {
296 		state.output_fd = open_log(state.output_filename);
297 		if (state.output_fd == -1) {
298 			err(7, "open");
299 		}
300 	}
301 
302 	if (state.syslog_enabled) {
303 		openlog(state.syslog_tag, LOG_PID | LOG_NDELAY,
304 		    state.syslog_facility);
305 	}
306 
307 	/*
308 	 * Try to open the pidfile before calling daemon(3),
309 	 * to be able to report the error intelligently
310 	 */
311 	open_pid_files(&state);
312 
313 	/*
314 	 * TODO: add feature to avoid backgrounding
315 	 * i.e. --foreground, -f
316 	 */
317 	if (daemon(state.keep_cur_workdir, state.keep_fds_open) == -1) {
318 		warn("daemon");
319 		daemon_terminate(&state);
320 	}
321 
322 	if (state.mode == MODE_DAEMON) {
323 		daemon_exec(&state);
324 	}
325 
326 	/* Write out parent pidfile if needed. */
327 	pidfile_write(state.parent_pidfh);
328 
329 	do {
330 		state.mode = MODE_SUPERVISE;
331 		daemon_eventloop(&state);
332 		daemon_sleep(&state);
333 	} while (state.restart_enabled);
334 
335 	daemon_terminate(&state);
336 }
337 
338 static void
339 daemon_exec(struct daemon_state *state)
340 {
341 	pidfile_write(state->child_pidfh);
342 
343 	if (state->user != NULL) {
344 		restrict_process(state->user);
345 	}
346 
347 	/* Ignored signals remain ignored after execve, unignore them */
348 	signal(SIGHUP, SIG_DFL);
349 	signal(SIGTERM, SIG_DFL);
350 	execvp(state->argv[0], state->argv);
351 	/* execvp() failed - report error and exit this process */
352 	err(1, "%s", state->argv[0]);
353 }
354 
355 /* Main event loop: fork the child and watch for events.
356  * After SIGTERM is received and propagated to the child there are
357  * several options on what to do next:
358  * - read until EOF
359  * - read until EOF but only for a while
360  * - bail immediately
361  * Currently the third option is used, because otherwise there is no
362  * guarantee that read() won't block indefinitely if the child refuses
363  * to depart. To handle the second option, a different approach
364  * would be needed (procctl()?).
365  */
366 static void
367 daemon_eventloop(struct daemon_state *state)
368 {
369 	struct kevent event;
370 	int kq;
371 	int ret;
372 	int pipe_fd[2];
373 
374 	/*
375 	 * Try to protect against pageout kill. Ignore the
376 	 * error, madvise(2) will fail only if a process does
377 	 * not have superuser privileges.
378 	 */
379 	(void)madvise(NULL, 0, MADV_PROTECT);
380 
381 	if (pipe(pipe_fd)) {
382 		err(1, "pipe");
383 	}
384 	state->pipe_rd = pipe_fd[0];
385 	state->pipe_wr = pipe_fd[1];
386 
387 	kq = kqueuex(KQUEUE_CLOEXEC);
388 	EV_SET(&event, state->pipe_rd, EVFILT_READ, EV_ADD|EV_CLEAR, 0, 0,
389 	    NULL);
390 	if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
391 		err(EXIT_FAILURE, "failed to register kevent");
392 	}
393 
394 	EV_SET(&event, SIGHUP,  EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
395 	if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
396 		err(EXIT_FAILURE, "failed to register kevent");
397 	}
398 
399 	EV_SET(&event, SIGTERM, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
400 	if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
401 		err(EXIT_FAILURE, "failed to register kevent");
402 	}
403 
404 	EV_SET(&event, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
405 	if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
406 		err(EXIT_FAILURE, "failed to register kevent");
407 	}
408 	memset(&event, 0, sizeof(struct kevent));
409 
410 	/* Spawn a child to exec the command. */
411 	state->pid = fork();
412 
413 	/* fork failed, this can only happen when supervision is enabled */
414 	switch (state->pid) {
415 	case -1:
416 		warn("fork");
417 		state->mode = MODE_NOCHILD;
418 		return;
419 	/* fork succeeded, this is child's branch */
420 	case 0:
421 		close(kq);
422 		daemon_set_child_pipe(state);
423 		daemon_exec(state);
424 		break;
425 	}
426 
427 	/* case: pid > 0; fork succeeded */
428 	close(state->pipe_wr);
429 	state->pipe_wr = -1;
430 	setproctitle("%s[%d]", state->title, (int)state->pid);
431 	setbuf(stdout, NULL);
432 
433 	while (state->mode != MODE_NOCHILD) {
434 		ret = kevent(kq, NULL, 0, &event, 1, NULL);
435 		switch (ret) {
436 		case -1:
437 			if (errno == EINTR)
438 				continue;
439 			err(EXIT_FAILURE, "kevent wait");
440 		case 0:
441 			continue;
442 		}
443 
444 		if (event.flags & EV_ERROR) {
445 			errx(EXIT_FAILURE, "Event error: %s",
446 			    strerror((int)event.data));
447 		}
448 
449 		switch (event.filter) {
450 		case EVFILT_SIGNAL:
451 
452 			switch (event.ident) {
453 			case SIGCHLD:
454 				if (daemon_is_child_dead(state)) {
455 					/* child is dead, read all until EOF */
456 					state->pid = -1;
457 					state->mode = MODE_NOCHILD;
458 					while (listen_child(state)) {
459 						continue;
460 					}
461 				}
462 				continue;
463 			case SIGTERM:
464 				if (state->mode != MODE_SUPERVISE) {
465 					/* user is impatient */
466 					/* TODO: warn about repeated SIGTERM? */
467 					continue;
468 				}
469 
470 				state->mode = MODE_TERMINATING;
471 				state->restart_enabled = false;
472 				if (state->pid > 0) {
473 					kill(state->pid, SIGTERM);
474 				}
475 				/*
476 				 * TODO set kevent timer to exit
477 				 * unconditionally after some time
478 				 */
479 				continue;
480 			case SIGHUP:
481 				if (state->log_reopen && state->output_fd >= 0) {
482 					reopen_log(state);
483 				}
484 				continue;
485 			}
486 			break;
487 
488 		case EVFILT_READ:
489 			/*
490 			 * detecting EOF is no longer necessary
491 			 * if child closes the pipe daemon will stop getting
492 			 * EVFILT_READ events
493 			 */
494 
495 			if (event.data > 0) {
496 				(void)listen_child(state);
497 			}
498 			continue;
499 		default:
500 			continue;
501 		}
502 	}
503 
504 	close(kq);
505 	close(state->pipe_rd);
506 	state->pipe_rd = -1;
507 }
508 
509 static void
510 daemon_sleep(struct daemon_state *state)
511 {
512 	struct timespec ts = { state->restart_delay, 0 };
513 
514 	if (!state->restart_enabled) {
515 		return;
516 	}
517 	while (nanosleep(&ts, &ts) == -1) {
518 		if (errno != EINTR) {
519 			err(1, "nanosleep");
520 		}
521 	}
522 }
523 
524 static void
525 open_pid_files(struct daemon_state *state)
526 {
527 	pid_t fpid;
528 	int serrno;
529 
530 	if (state->child_pidfile) {
531 		state->child_pidfh = pidfile_open(state->child_pidfile, 0600, &fpid);
532 		if (state->child_pidfh == NULL) {
533 			if (errno == EEXIST) {
534 				errx(3, "process already running, pid: %d",
535 				    fpid);
536 			}
537 			err(2, "pidfile ``%s''", state->child_pidfile);
538 		}
539 	}
540 	/* Do the same for the actual daemon process. */
541 	if (state->parent_pidfile) {
542 		state->parent_pidfh= pidfile_open(state->parent_pidfile, 0600, &fpid);
543 		if (state->parent_pidfh == NULL) {
544 			serrno = errno;
545 			pidfile_remove(state->child_pidfh);
546 			errno = serrno;
547 			if (errno == EEXIST) {
548 				errx(3, "process already running, pid: %d",
549 				     fpid);
550 			}
551 			err(2, "ppidfile ``%s''", state->parent_pidfile);
552 		}
553 	}
554 }
555 
556 static int
557 get_log_mapping(const char *str, const CODE *c)
558 {
559 	const CODE *cp;
560 	for (cp = c; cp->c_name; cp++)
561 		if (strcmp(cp->c_name, str) == 0) {
562 			return cp->c_val;
563 		}
564 	return -1;
565 }
566 
567 static void
568 restrict_process(const char *user)
569 {
570 	struct passwd *pw = NULL;
571 
572 	pw = getpwnam(user);
573 	if (pw == NULL) {
574 		errx(1, "unknown user: %s", user);
575 	}
576 
577 	if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0) {
578 		errx(1, "failed to set user environment");
579 	}
580 
581 	setenv("USER", pw->pw_name, 1);
582 	setenv("HOME", pw->pw_dir, 1);
583 	setenv("SHELL", *pw->pw_shell ? pw->pw_shell : _PATH_BSHELL, 1);
584 }
585 
586 /*
587  * We try to collect whole lines terminated by '\n'. Otherwise we collect a
588  * full buffer, and then output it.
589  *
590  * Return value of false is assumed to mean EOF or error, and true indicates to
591  * continue reading.
592  */
593 static bool
594 listen_child(struct daemon_state *state)
595 {
596 	ssize_t rv;
597 	unsigned char *cp;
598 
599 	assert(state != NULL);
600 	assert(state->pos < LBUF_SIZE - 1);
601 
602 	rv = read(state->pipe_rd, state->buf + state->pos,
603 	    LBUF_SIZE - state->pos - 1);
604 	if (rv > 0) {
605 		state->pos += rv;
606 		assert(state->pos <= LBUF_SIZE - 1);
607 		/* Always NUL-terminate just in case. */
608 		state->buf[LBUF_SIZE - 1] = '\0';
609 
610 		/*
611 		 * Find position of the last newline in the buffer.
612 		 * The buffer is guaranteed to have one or more complete lines
613 		 * if at least one newline was found when searching in reverse.
614 		 * All complete lines are flushed.
615 		 * This does not take NUL characters into account.
616 		 */
617 		cp = memrchr(state->buf, '\n', state->pos);
618 		if (cp != NULL) {
619 			size_t bytes_line = cp - state->buf + 1;
620 			assert(bytes_line <= state->pos);
621 			do_output(state->buf, bytes_line, state);
622 			state->pos -= bytes_line;
623 			memmove(state->buf, cp + 1, state->pos);
624 		}
625 		/* Wait until the buffer is full. */
626 		if (state->pos < LBUF_SIZE - 1) {
627 			return true;
628 		}
629 		do_output(state->buf, state->pos, state);
630 		state->pos = 0;
631 		return true;
632 	} else if (rv == -1) {
633 		/* EINTR should trigger another read. */
634 		if (errno == EINTR) {
635 			return true;
636 		} else {
637 			warn("read");
638 			return false;
639 		}
640 	}
641 	/* Upon EOF, we have to flush what's left of the buffer. */
642 	if (state->pos > 0) {
643 		do_output(state->buf, state->pos, state);
644 		state->pos = 0;
645 	}
646 	return false;
647 }
648 
649 /*
650  * The default behavior is to stay silent if the user wants to redirect
651  * output to a file and/or syslog. If neither are provided, then we bounce
652  * everything back to parent's stdout.
653  */
654 static void
655 do_output(const unsigned char *buf, size_t len, struct daemon_state *state)
656 {
657 	assert(len <= LBUF_SIZE);
658 	assert(state != NULL);
659 
660 	if (len < 1) {
661 		return;
662 	}
663 	if (state->syslog_enabled) {
664 		syslog(state->syslog_priority, "%.*s", (int)len, buf);
665 	}
666 	if (state->output_fd != -1) {
667 		if (write(state->output_fd, buf, len) == -1)
668 			warn("write");
669 	}
670 	if (state->keep_fds_open &&
671 	    !state->syslog_enabled &&
672 	    state->output_fd == -1) {
673 		printf("%.*s", (int)len, buf);
674 	}
675 }
676 
677 static int
678 open_log(const char *outfn)
679 {
680 
681 	return open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
682 }
683 
684 static void
685 reopen_log(struct daemon_state *state)
686 {
687 	int outfd;
688 
689 	outfd = open_log(state->output_filename);
690 	if (state->output_fd >= 0) {
691 		close(state->output_fd);
692 	}
693 	state->output_fd = outfd;
694 }
695 
696 static void
697 daemon_state_init(struct daemon_state *state)
698 {
699 	*state = (struct daemon_state) {
700 		.buf = {0},
701 		.pos = 0,
702 		.argv = NULL,
703 		.parent_pidfh = NULL,
704 		.child_pidfh = NULL,
705 		.child_pidfile = NULL,
706 		.parent_pidfile = NULL,
707 		.title = NULL,
708 		.user = NULL,
709 		.mode = MODE_DAEMON,
710 		.restart_enabled = false,
711 		.pid = 0,
712 		.pipe_rd = -1,
713 		.pipe_wr = -1,
714 		.keep_cur_workdir = 1,
715 		.restart_delay = 1,
716 		.stdmask = STDOUT_FILENO | STDERR_FILENO,
717 		.syslog_enabled = false,
718 		.log_reopen = false,
719 		.syslog_priority = LOG_NOTICE,
720 		.syslog_tag = "daemon",
721 		.syslog_facility = LOG_DAEMON,
722 		.keep_fds_open = 1,
723 		.output_fd = -1,
724 		.output_filename = NULL,
725 	};
726 }
727 
728 static _Noreturn void
729 daemon_terminate(struct daemon_state *state)
730 {
731 	assert(state != NULL);
732 
733 	if (state->output_fd >= 0) {
734 		close(state->output_fd);
735 	}
736 	if (state->pipe_rd >= 0) {
737 		close(state->pipe_rd);
738 	}
739 
740 	if (state->pipe_wr >= 0) {
741 		close(state->pipe_wr);
742 	}
743 	if (state->syslog_enabled) {
744 		closelog();
745 	}
746 	pidfile_remove(state->child_pidfh);
747 	pidfile_remove(state->parent_pidfh);
748 
749 	/*
750 	 * Note that the exit value here doesn't matter in the case of a clean
751 	 * exit; daemon(3) already detached us from the caller, nothing is left
752 	 * to care about this one.
753 	 */
754 	exit(1);
755 }
756 
757 /*
758  * Returns true if SIGCHILD came from state->pid
759  * This function could hang if SIGCHILD was emittied for a reason other than
760  * child dying (e.g., ptrace attach).
761  */
762 static bool
763 daemon_is_child_dead(struct daemon_state *state)
764 {
765 	for (;;) {
766 		int who = waitpid(-1, NULL, WNOHANG);
767 		if (state->pid == who) {
768 			return true;
769 		}
770 		if (who == -1 && errno != EINTR) {
771 			warn("waitpid");
772 			return false;
773 		}
774 	}
775 }
776 
777 static void
778 daemon_set_child_pipe(struct daemon_state *state)
779 {
780 	if (state->stdmask & STDERR_FILENO) {
781 		if (dup2(state->pipe_wr, STDERR_FILENO) == -1) {
782 			err(1, "dup2");
783 		}
784 	}
785 	if (state->stdmask & STDOUT_FILENO) {
786 		if (dup2(state->pipe_wr, STDOUT_FILENO) == -1) {
787 			err(1, "dup2");
788 		}
789 	}
790 	if (state->pipe_wr != STDERR_FILENO &&
791 	    state->pipe_wr != STDOUT_FILENO) {
792 		close(state->pipe_wr);
793 	}
794 
795 	/* The child gets dup'd pipes. */
796 	close(state->pipe_rd);
797 }
798