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