xref: /freebsd/usr.sbin/daemon/daemon.c (revision bc1dfc316a2bba97773a14b96f5e976a52524be4)
1bd06a3ecSMike Barcroft /*-
21de7b4b8SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
31de7b4b8SPedro F. Giffuni  *
4bd06a3ecSMike Barcroft  * Copyright (c) 1999 Berkeley Software Design, Inc. All rights reserved.
5bd06a3ecSMike Barcroft  *
6bd06a3ecSMike Barcroft  * Redistribution and use in source and binary forms, with or without
7bd06a3ecSMike Barcroft  * modification, are permitted provided that the following conditions
8bd06a3ecSMike Barcroft  * are met:
9bd06a3ecSMike Barcroft  * 1. Redistributions of source code must retain the above copyright
10bd06a3ecSMike Barcroft  *    notice, this list of conditions and the following disclaimer.
11bd06a3ecSMike Barcroft  * 2. Redistributions in binary form must reproduce the above copyright
12bd06a3ecSMike Barcroft  *    notice, this list of conditions and the following disclaimer in the
13bd06a3ecSMike Barcroft  *    documentation and/or other materials provided with the distribution.
14bd06a3ecSMike Barcroft  * 3. Berkeley Software Design Inc's name may not be used to endorse or
15bd06a3ecSMike Barcroft  *    promote products derived from this software without specific prior
16bd06a3ecSMike Barcroft  *    written permission.
17bd06a3ecSMike Barcroft  *
18bd06a3ecSMike Barcroft  * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
19bd06a3ecSMike Barcroft  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20bd06a3ecSMike Barcroft  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21bd06a3ecSMike Barcroft  * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
22bd06a3ecSMike Barcroft  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23bd06a3ecSMike Barcroft  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24bd06a3ecSMike Barcroft  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25bd06a3ecSMike Barcroft  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26bd06a3ecSMike Barcroft  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27bd06a3ecSMike Barcroft  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28bd06a3ecSMike Barcroft  * SUCH DAMAGE.
29bd06a3ecSMike Barcroft  *
30bd06a3ecSMike Barcroft  *	From BSDI: daemon.c,v 1.2 1996/08/15 01:11:09 jch Exp
31bd06a3ecSMike Barcroft  */
32bd06a3ecSMike Barcroft 
338935a399SIhor Antonov #include <sys/event.h>
3453c49998SMikolaj Golub #include <sys/mman.h>
352ad43027SMikolaj Golub #include <sys/wait.h>
36bd06a3ecSMike Barcroft 
3753d49b37SJilles Tjoelker #include <fcntl.h>
38bd06a3ecSMike Barcroft #include <err.h>
39846be7bdSPoul-Henning Kamp #include <errno.h>
400a402ad2SIhor Antonov #include <getopt.h>
41c6262cb6SPawel Jakub Dawidek #include <libutil.h>
42e6d4b388STom Rhodes #include <login_cap.h>
436b3ad1d7SMaxim Sobolev #include <paths.h>
44195fc497SMikolaj Golub #include <pwd.h>
45195fc497SMikolaj Golub #include <signal.h>
46bd06a3ecSMike Barcroft #include <stdio.h>
47203df05bSIhor Antonov #include <stdbool.h>
48bd06a3ecSMike Barcroft #include <stdlib.h>
49bd06a3ecSMike Barcroft #include <unistd.h>
5053d49b37SJilles Tjoelker #include <string.h>
5153d49b37SJilles Tjoelker #define SYSLOG_NAMES
5253d49b37SJilles Tjoelker #include <syslog.h>
5353d49b37SJilles Tjoelker #include <time.h>
5453d49b37SJilles Tjoelker #include <assert.h>
55bd06a3ecSMike Barcroft 
56a6f795ccSIhor Antonov /* 1 year in seconds */
57a6f795ccSIhor Antonov #define MAX_RESTART_DELAY 60*60*24*365
58a6f795ccSIhor Antonov 
597618c9e1SJuraj Lutter /* Maximum number of restarts */
607618c9e1SJuraj Lutter #define MAX_RESTART_COUNT 128
617618c9e1SJuraj Lutter 
6253d49b37SJilles Tjoelker #define LBUF_SIZE 4096
6353d49b37SJilles Tjoelker 
648935a399SIhor Antonov enum daemon_mode {
658935a399SIhor Antonov 	MODE_DAEMON = 0,   /* simply daemonize, no supervision */
668935a399SIhor Antonov 	MODE_SUPERVISE,    /* initial supervision state */
678935a399SIhor Antonov 	MODE_TERMINATING,  /* user requested termination */
688935a399SIhor Antonov 	MODE_NOCHILD,      /* child is terminated, final state of the event loop */
698935a399SIhor Antonov };
708935a399SIhor Antonov 
71407e3790SIhor Antonov 
72298a392eSIhor Antonov struct daemon_state {
7324fd3e96SIhor Antonov 	unsigned char buf[LBUF_SIZE];
7424fd3e96SIhor Antonov 	size_t pos;
754c41f4a0SIhor Antonov 	char **argv;
76298a392eSIhor Antonov 	const char *child_pidfile;
77298a392eSIhor Antonov 	const char *parent_pidfile;
78e70444c6SIhor Antonov 	const char *output_filename;
796f063672SIhor Antonov 	const char *syslog_tag;
80298a392eSIhor Antonov 	const char *title;
81298a392eSIhor Antonov 	const char *user;
82298a392eSIhor Antonov 	struct pidfh *parent_pidfh;
83298a392eSIhor Antonov 	struct pidfh *child_pidfh;
848935a399SIhor Antonov 	enum daemon_mode mode;
858935a399SIhor Antonov 	int pid;
86407e3790SIhor Antonov 	int pipe_rd;
87407e3790SIhor Antonov 	int pipe_wr;
88298a392eSIhor Antonov 	int keep_cur_workdir;
89*bc1dfc31SKyle Evans 	int kqueue_fd;
90298a392eSIhor Antonov 	int restart_delay;
91298a392eSIhor Antonov 	int stdmask;
92e70444c6SIhor Antonov 	int syslog_priority;
936f063672SIhor Antonov 	int syslog_facility;
94129ec8f4SIhor Antonov 	int keep_fds_open;
95e70444c6SIhor Antonov 	int output_fd;
96298a392eSIhor Antonov 	bool restart_enabled;
97f2f9d31dSIhor Antonov 	bool syslog_enabled;
98298a392eSIhor Antonov 	bool log_reopen;
997618c9e1SJuraj Lutter 	int restart_count;
1007618c9e1SJuraj Lutter 	int restarted_count;
10153d49b37SJilles Tjoelker };
10253d49b37SJilles Tjoelker 
103e6d4b388STom Rhodes static void restrict_process(const char *);
1044cd407ecSMaxim Sobolev static int  open_log(const char *);
105298a392eSIhor Antonov static void reopen_log(struct daemon_state *);
1066ac7c9f0SIhor Antonov static bool listen_child(struct daemon_state *);
10753d49b37SJilles Tjoelker static int  get_log_mapping(const char *, const CODE *);
108298a392eSIhor Antonov static void open_pid_files(struct daemon_state *);
109298a392eSIhor Antonov static void do_output(const unsigned char *, size_t, struct daemon_state *);
1108935a399SIhor Antonov static void daemon_sleep(struct daemon_state *);
111298a392eSIhor Antonov static void daemon_state_init(struct daemon_state *);
1124c41f4a0SIhor Antonov static void daemon_eventloop(struct daemon_state *);
113cf6356fdSIhor Antonov static void daemon_terminate(struct daemon_state *);
1148935a399SIhor Antonov static void daemon_exec(struct daemon_state *);
1158935a399SIhor Antonov static bool daemon_is_child_dead(struct daemon_state *);
1168935a399SIhor Antonov static void daemon_set_child_pipe(struct daemon_state *);
117*bc1dfc31SKyle Evans static int daemon_setup_kqueue(void);
11853d49b37SJilles Tjoelker 
119aa8722ccSKyle Evans static int pidfile_truncate(struct pidfh *);
120aa8722ccSKyle Evans 
1217618c9e1SJuraj Lutter static const char shortopts[] = "+cfHSp:P:ru:o:s:l:t:m:R:T:C:h";
1220a402ad2SIhor Antonov 
1230a402ad2SIhor Antonov static const struct option longopts[] = {
1240a402ad2SIhor Antonov 	{ "change-dir",         no_argument,            NULL,           'c' },
1250a402ad2SIhor Antonov 	{ "close-fds",          no_argument,            NULL,           'f' },
1260a402ad2SIhor Antonov 	{ "sighup",             no_argument,            NULL,           'H' },
1270a402ad2SIhor Antonov 	{ "syslog",             no_argument,            NULL,           'S' },
1280a402ad2SIhor Antonov 	{ "output-file",        required_argument,      NULL,           'o' },
1290a402ad2SIhor Antonov 	{ "output-mask",        required_argument,      NULL,           'm' },
1300a402ad2SIhor Antonov 	{ "child-pidfile",      required_argument,      NULL,           'p' },
1310a402ad2SIhor Antonov 	{ "supervisor-pidfile", required_argument,      NULL,           'P' },
1320a402ad2SIhor Antonov 	{ "restart",            no_argument,            NULL,           'r' },
1337618c9e1SJuraj Lutter 	{ "restart-count",      required_argument,      NULL,           'C' },
1340a402ad2SIhor Antonov 	{ "restart-delay",      required_argument,      NULL,           'R' },
1350a402ad2SIhor Antonov 	{ "title",              required_argument,      NULL,           't' },
1360a402ad2SIhor Antonov 	{ "user",               required_argument,      NULL,           'u' },
1370a402ad2SIhor Antonov 	{ "syslog-priority",    required_argument,      NULL,           's' },
1380a402ad2SIhor Antonov 	{ "syslog-facility",    required_argument,      NULL,           'l' },
1390a402ad2SIhor Antonov 	{ "syslog-tag",         required_argument,      NULL,           'T' },
1400a402ad2SIhor Antonov 	{ "help",               no_argument,            NULL,           'h' },
1410a402ad2SIhor Antonov 	{ NULL,                 0,                      NULL,            0  }
1420a402ad2SIhor Antonov };
1430a402ad2SIhor Antonov 
1440a402ad2SIhor Antonov static _Noreturn void
usage(int exitcode)1450a402ad2SIhor Antonov usage(int exitcode)
1460a402ad2SIhor Antonov {
1470a402ad2SIhor Antonov 	(void)fprintf(stderr,
1480a402ad2SIhor Antonov 	    "usage: daemon [-cfHrS] [-p child_pidfile] [-P supervisor_pidfile]\n"
1490a402ad2SIhor Antonov 	    "              [-u user] [-o output_file] [-t title]\n"
1500a402ad2SIhor Antonov 	    "              [-l syslog_facility] [-s syslog_priority]\n"
1510a402ad2SIhor Antonov 	    "              [-T syslog_tag] [-m output_mask] [-R restart_delay_secs]\n"
1527618c9e1SJuraj Lutter 	    "              [-C restart_count]\n"
1530a402ad2SIhor Antonov 	    "command arguments ...\n");
1540a402ad2SIhor Antonov 
1550a402ad2SIhor Antonov 	(void)fprintf(stderr,
1560a402ad2SIhor Antonov 	    "  --change-dir         -c         Change the current working directory to root\n"
1570a402ad2SIhor Antonov 	    "  --close-fds          -f         Set stdin, stdout, stderr to /dev/null\n"
1580a402ad2SIhor Antonov 	    "  --sighup             -H         Close and re-open output file on SIGHUP\n"
1590a402ad2SIhor Antonov 	    "  --syslog             -S         Send output to syslog\n"
1600a402ad2SIhor Antonov 	    "  --output-file        -o <file>  Append output of the child process to file\n"
1610a402ad2SIhor Antonov 	    "  --output-mask        -m <mask>  What to send to syslog/file\n"
1620a402ad2SIhor Antonov 	    "                                  1=stdout, 2=stderr, 3=both\n"
1630a402ad2SIhor Antonov 	    "  --child-pidfile      -p <file>  Write PID of the child process to file\n"
1640a402ad2SIhor Antonov 	    "  --supervisor-pidfile -P <file>  Write PID of the supervisor process to file\n"
1650a402ad2SIhor Antonov 	    "  --restart            -r         Restart child if it terminates (1 sec delay)\n"
1667618c9e1SJuraj Lutter 	    "  --restart-count      -C <N>     Restart child at most N times, then exit\n"
1670a402ad2SIhor Antonov 	    "  --restart-delay      -R <N>     Restart child if it terminates after N sec\n"
1680a402ad2SIhor Antonov 	    "  --title              -t <title> Set the title of the supervisor process\n"
1690a402ad2SIhor Antonov 	    "  --user               -u <user>  Drop privileges, run as given user\n"
1700a402ad2SIhor Antonov 	    "  --syslog-priority    -s <prio>  Set syslog priority\n"
1710a402ad2SIhor Antonov 	    "  --syslog-facility    -l <flty>  Set syslog facility\n"
1720a402ad2SIhor Antonov 	    "  --syslog-tag         -T <tag>   Set syslog tag\n"
1730a402ad2SIhor Antonov 	    "  --help               -h         Show this help\n");
1740a402ad2SIhor Antonov 
1750a402ad2SIhor Antonov 	exit(exitcode);
1760a402ad2SIhor Antonov }
1770a402ad2SIhor Antonov 
178bd06a3ecSMike Barcroft int
main(int argc,char * argv[])179bd06a3ecSMike Barcroft main(int argc, char *argv[])
180bd06a3ecSMike Barcroft {
181a6f795ccSIhor Antonov 	const char *e = NULL;
182e745dc22SIhor Antonov 	int ch = 0;
183298a392eSIhor Antonov 	struct daemon_state state;
184bd06a3ecSMike Barcroft 
185298a392eSIhor Antonov 	daemon_state_init(&state);
1869ee1faeeSIhor Antonov 
1878935a399SIhor Antonov 	/* Signals are processed via kqueue */
1888935a399SIhor Antonov 	signal(SIGHUP, SIG_IGN);
1898935a399SIhor Antonov 	signal(SIGTERM, SIG_IGN);
1908935a399SIhor Antonov 
1919ee1faeeSIhor Antonov 	/*
192f907027bSIhor Antonov 	 * Supervision mode is enabled if one of the following options are used:
193f907027bSIhor Antonov 	 * --child-pidfile -p
194f907027bSIhor Antonov 	 * --supervisor-pidfile -P
195f907027bSIhor Antonov 	 * --restart -r / --restart-delay -R
196f907027bSIhor Antonov 	 * --syslog -S
197f907027bSIhor Antonov 	 * --syslog-facility -l
198f907027bSIhor Antonov 	 * --syslog-priority -s
199f907027bSIhor Antonov 	 * --syslog-tag -T
200f907027bSIhor Antonov 	 *
201f907027bSIhor Antonov 	 * In supervision mode daemon executes the command in a forked process
202f907027bSIhor Antonov 	 * and observes the child by waiting for SIGCHILD. In supervision mode
203f907027bSIhor Antonov 	 * daemon must never exit before the child, this is necessary  to prevent
204f907027bSIhor Antonov 	 * orphaning the child and leaving a stale pid file.
205f907027bSIhor Antonov 	 * To achieve this daemon catches SIGTERM and
206f907027bSIhor Antonov 	 * forwards it to the child, expecting to get SIGCHLD eventually.
207f907027bSIhor Antonov 	 */
2080a402ad2SIhor Antonov 	while ((ch = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) {
209bd06a3ecSMike Barcroft 		switch (ch) {
210bd06a3ecSMike Barcroft 		case 'c':
211298a392eSIhor Antonov 			state.keep_cur_workdir = 0;
212bd06a3ecSMike Barcroft 			break;
2137618c9e1SJuraj Lutter 		case 'C':
2147618c9e1SJuraj Lutter 			state.restart_count = (int)strtonum(optarg, 0,
2157618c9e1SJuraj Lutter 			    MAX_RESTART_COUNT, &e);
2167618c9e1SJuraj Lutter 			if (e != NULL) {
2177618c9e1SJuraj Lutter 				errx(6, "invalid restart count: %s", e);
2187618c9e1SJuraj Lutter 			}
2197618c9e1SJuraj Lutter 			break;
220bd06a3ecSMike Barcroft 		case 'f':
221298a392eSIhor Antonov 			state.keep_fds_open = 0;
222bd06a3ecSMike Barcroft 			break;
2234cd407ecSMaxim Sobolev 		case 'H':
224298a392eSIhor Antonov 			state.log_reopen = true;
2254cd407ecSMaxim Sobolev 			break;
22653d49b37SJilles Tjoelker 		case 'l':
227298a392eSIhor Antonov 			state.syslog_facility = get_log_mapping(optarg,
22839ea4280SIhor Antonov 			    facilitynames);
229298a392eSIhor Antonov 			if (state.syslog_facility == -1) {
23053d49b37SJilles Tjoelker 				errx(5, "unrecognized syslog facility");
2316b4ef4b1SIhor Antonov 			}
232298a392eSIhor Antonov 			state.syslog_enabled = true;
2338935a399SIhor Antonov 			state.mode = MODE_SUPERVISE;
23453d49b37SJilles Tjoelker 			break;
23553d49b37SJilles Tjoelker 		case 'm':
236a6f795ccSIhor Antonov 			state.stdmask = (int)strtonum(optarg, 0, 3, &e);
237a6f795ccSIhor Antonov 			if (e != NULL) {
238a6f795ccSIhor Antonov 				errx(6, "unrecognized listening mask: %s", e);
2396b4ef4b1SIhor Antonov 			}
24053d49b37SJilles Tjoelker 			break;
24153d49b37SJilles Tjoelker 		case 'o':
242298a392eSIhor Antonov 			state.output_filename = optarg;
243f907027bSIhor Antonov 			/*
244f907027bSIhor Antonov 			 * TODO: setting output filename doesn't have to turn
245f907027bSIhor Antonov 			 * the supervision mode on. For non-supervised mode
246f907027bSIhor Antonov 			 * daemon could open the specified file and set it's
247f907027bSIhor Antonov 			 * descriptor as both stderr and stout before execve()
248f907027bSIhor Antonov 			 */
2498935a399SIhor Antonov 			state.mode = MODE_SUPERVISE;
25053d49b37SJilles Tjoelker 			break;
251846be7bdSPoul-Henning Kamp 		case 'p':
252298a392eSIhor Antonov 			state.child_pidfile = optarg;
2538935a399SIhor Antonov 			state.mode = MODE_SUPERVISE;
254846be7bdSPoul-Henning Kamp 			break;
25532b17786SJohn-Mark Gurney 		case 'P':
256298a392eSIhor Antonov 			state.parent_pidfile = optarg;
2578935a399SIhor Antonov 			state.mode = MODE_SUPERVISE;
25832b17786SJohn-Mark Gurney 			break;
259b6193c24SMikolaj Golub 		case 'r':
260298a392eSIhor Antonov 			state.restart_enabled = true;
2618935a399SIhor Antonov 			state.mode = MODE_SUPERVISE;
262b6193c24SMikolaj Golub 			break;
26337820b87SIan Lepore 		case 'R':
264298a392eSIhor Antonov 			state.restart_enabled = true;
265a6f795ccSIhor Antonov 			state.restart_delay = (int)strtonum(optarg, 1,
266a6f795ccSIhor Antonov 			    MAX_RESTART_DELAY, &e);
267a6f795ccSIhor Antonov 			if (e != NULL) {
268a6f795ccSIhor Antonov 				errx(6, "invalid restart delay: %s", e);
2696b4ef4b1SIhor Antonov 			}
270bbc6e6c5SMathieu 			state.mode = MODE_SUPERVISE;
27137820b87SIan Lepore 			break;
27253d49b37SJilles Tjoelker 		case 's':
273298a392eSIhor Antonov 			state.syslog_priority = get_log_mapping(optarg,
27439ea4280SIhor Antonov 			    prioritynames);
275298a392eSIhor Antonov 			if (state.syslog_priority == -1) {
27653d49b37SJilles Tjoelker 				errx(4, "unrecognized syslog priority");
2776b4ef4b1SIhor Antonov 			}
278298a392eSIhor Antonov 			state.syslog_enabled = true;
2798935a399SIhor Antonov 			state.mode = MODE_SUPERVISE;
28053d49b37SJilles Tjoelker 			break;
28153d49b37SJilles Tjoelker 		case 'S':
282298a392eSIhor Antonov 			state.syslog_enabled = true;
2838935a399SIhor Antonov 			state.mode = MODE_SUPERVISE;
28453d49b37SJilles Tjoelker 			break;
285112bfcf5SConrad Meyer 		case 't':
286298a392eSIhor Antonov 			state.title = optarg;
287112bfcf5SConrad Meyer 			break;
28853d49b37SJilles Tjoelker 		case 'T':
289298a392eSIhor Antonov 			state.syslog_tag = optarg;
290298a392eSIhor Antonov 			state.syslog_enabled = true;
2918935a399SIhor Antonov 			state.mode = MODE_SUPERVISE;
29253d49b37SJilles Tjoelker 			break;
293e6d4b388STom Rhodes 		case 'u':
294298a392eSIhor Antonov 			state.user = optarg;
295e6d4b388STom Rhodes 			break;
2960a402ad2SIhor Antonov 		case 'h':
2970a402ad2SIhor Antonov 			usage(0);
298f7a10a77SCollin Funk 			__unreachable();
299bd06a3ecSMike Barcroft 		default:
3000a402ad2SIhor Antonov 			usage(1);
301bd06a3ecSMike Barcroft 		}
302bd06a3ecSMike Barcroft 	}
303bd06a3ecSMike Barcroft 	argc -= optind;
304bd06a3ecSMike Barcroft 	argv += optind;
3054c41f4a0SIhor Antonov 	state.argv = argv;
306bd06a3ecSMike Barcroft 
3076b4ef4b1SIhor Antonov 	if (argc == 0) {
3080a402ad2SIhor Antonov 		usage(1);
3096b4ef4b1SIhor Antonov 	}
31012d7249eSTom Rhodes 
311298a392eSIhor Antonov 	if (!state.title) {
312298a392eSIhor Antonov 		state.title = argv[0];
3136b4ef4b1SIhor Antonov 	}
31453d49b37SJilles Tjoelker 
315298a392eSIhor Antonov 	if (state.output_filename) {
316298a392eSIhor Antonov 		state.output_fd = open_log(state.output_filename);
317298a392eSIhor Antonov 		if (state.output_fd == -1) {
31853d49b37SJilles Tjoelker 			err(7, "open");
31953d49b37SJilles Tjoelker 		}
3206b4ef4b1SIhor Antonov 	}
32153d49b37SJilles Tjoelker 
322298a392eSIhor Antonov 	if (state.syslog_enabled) {
323298a392eSIhor Antonov 		openlog(state.syslog_tag, LOG_PID | LOG_NDELAY,
324298a392eSIhor Antonov 		    state.syslog_facility);
3256b4ef4b1SIhor Antonov 	}
32653d49b37SJilles Tjoelker 
327846be7bdSPoul-Henning Kamp 	/*
328846be7bdSPoul-Henning Kamp 	 * Try to open the pidfile before calling daemon(3),
329846be7bdSPoul-Henning Kamp 	 * to be able to report the error intelligently
330846be7bdSPoul-Henning Kamp 	 */
331298a392eSIhor Antonov 	open_pid_files(&state);
3328935a399SIhor Antonov 
3338935a399SIhor Antonov 	/*
3348935a399SIhor Antonov 	 * TODO: add feature to avoid backgrounding
3358935a399SIhor Antonov 	 * i.e. --foreground, -f
3368935a399SIhor Antonov 	 */
337298a392eSIhor Antonov 	if (daemon(state.keep_cur_workdir, state.keep_fds_open) == -1) {
3389da0ef13SMikolaj Golub 		warn("daemon");
339cf6356fdSIhor Antonov 		daemon_terminate(&state);
3409da0ef13SMikolaj Golub 	}
3418935a399SIhor Antonov 
3428935a399SIhor Antonov 	if (state.mode == MODE_DAEMON) {
3438935a399SIhor Antonov 		daemon_exec(&state);
3448935a399SIhor Antonov 	}
3458935a399SIhor Antonov 
3469da0ef13SMikolaj Golub 	/* Write out parent pidfile if needed. */
347298a392eSIhor Antonov 	pidfile_write(state.parent_pidfh);
348203df05bSIhor Antonov 
349*bc1dfc31SKyle Evans 	state.kqueue_fd = daemon_setup_kqueue();
350*bc1dfc31SKyle Evans 
3514c41f4a0SIhor Antonov 	do {
3528935a399SIhor Antonov 		state.mode = MODE_SUPERVISE;
3534c41f4a0SIhor Antonov 		daemon_eventloop(&state);
3548935a399SIhor Antonov 		daemon_sleep(&state);
3557618c9e1SJuraj Lutter 		if (state.restart_enabled && state.restart_count > -1) {
3567618c9e1SJuraj Lutter 			if (state.restarted_count >= state.restart_count) {
3577618c9e1SJuraj Lutter 				state.restart_enabled = false;
3587618c9e1SJuraj Lutter 			}
3597618c9e1SJuraj Lutter 			state.restarted_count++;
3607618c9e1SJuraj Lutter 		}
3618935a399SIhor Antonov 	} while (state.restart_enabled);
3624c41f4a0SIhor Antonov 
3634c41f4a0SIhor Antonov 	daemon_terminate(&state);
3644c41f4a0SIhor Antonov }
3654c41f4a0SIhor Antonov 
3668935a399SIhor Antonov static void
daemon_exec(struct daemon_state * state)3678935a399SIhor Antonov daemon_exec(struct daemon_state *state)
3688935a399SIhor Antonov {
3698935a399SIhor Antonov 	pidfile_write(state->child_pidfh);
3704c41f4a0SIhor Antonov 
3718935a399SIhor Antonov 	if (state->user != NULL) {
3728935a399SIhor Antonov 		restrict_process(state->user);
3738935a399SIhor Antonov 	}
3748935a399SIhor Antonov 
3758935a399SIhor Antonov 	/* Ignored signals remain ignored after execve, unignore them */
3768935a399SIhor Antonov 	signal(SIGHUP, SIG_DFL);
3778935a399SIhor Antonov 	signal(SIGTERM, SIG_DFL);
3788935a399SIhor Antonov 	execvp(state->argv[0], state->argv);
3798935a399SIhor Antonov 	/* execvp() failed - report error and exit this process */
3808935a399SIhor Antonov 	err(1, "%s", state->argv[0]);
3818935a399SIhor Antonov }
3828935a399SIhor Antonov 
3838935a399SIhor Antonov /* Main event loop: fork the child and watch for events.
384a6f795ccSIhor Antonov  * After SIGTERM is received and propagated to the child there are
3854c41f4a0SIhor Antonov  * several options on what to do next:
3864c41f4a0SIhor Antonov  * - read until EOF
3874c41f4a0SIhor Antonov  * - read until EOF but only for a while
3884c41f4a0SIhor Antonov  * - bail immediately
3894c41f4a0SIhor Antonov  * Currently the third option is used, because otherwise there is no
3904c41f4a0SIhor Antonov  * guarantee that read() won't block indefinitely if the child refuses
3914c41f4a0SIhor Antonov  * to depart. To handle the second option, a different approach
3924c41f4a0SIhor Antonov  * would be needed (procctl()?).
3934c41f4a0SIhor Antonov  */
3944c41f4a0SIhor Antonov static void
daemon_eventloop(struct daemon_state * state)3954c41f4a0SIhor Antonov daemon_eventloop(struct daemon_state *state)
3964c41f4a0SIhor Antonov {
3978935a399SIhor Antonov 	struct kevent event;
3988935a399SIhor Antonov 	int kq;
3998935a399SIhor Antonov 	int ret;
400407e3790SIhor Antonov 	int pipe_fd[2];
4018935a399SIhor Antonov 
4028935a399SIhor Antonov 	/*
4038935a399SIhor Antonov 	 * Try to protect against pageout kill. Ignore the
4048935a399SIhor Antonov 	 * error, madvise(2) will fail only if a process does
4058935a399SIhor Antonov 	 * not have superuser privileges.
4068935a399SIhor Antonov 	 */
4078935a399SIhor Antonov 	(void)madvise(NULL, 0, MADV_PROTECT);
4088935a399SIhor Antonov 
409407e3790SIhor Antonov 	if (pipe(pipe_fd)) {
41053d49b37SJilles Tjoelker 		err(1, "pipe");
4116b4ef4b1SIhor Antonov 	}
412407e3790SIhor Antonov 	state->pipe_rd = pipe_fd[0];
413407e3790SIhor Antonov 	state->pipe_wr = pipe_fd[1];
4148935a399SIhor Antonov 
415*bc1dfc31SKyle Evans 	kq = state->kqueue_fd;
416407e3790SIhor Antonov 	EV_SET(&event, state->pipe_rd, EVFILT_READ, EV_ADD|EV_CLEAR, 0, 0,
4178935a399SIhor Antonov 	    NULL);
4188935a399SIhor Antonov 	if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
4198935a399SIhor Antonov 		err(EXIT_FAILURE, "failed to register kevent");
42075f61ca9SIhor Antonov 	}
42175f61ca9SIhor Antonov 
4228935a399SIhor Antonov 	memset(&event, 0, sizeof(struct kevent));
4238935a399SIhor Antonov 
4248935a399SIhor Antonov 	/* Spawn a child to exec the command. */
4258935a399SIhor Antonov 	state->pid = fork();
4268935a399SIhor Antonov 
42775f61ca9SIhor Antonov 	/* fork failed, this can only happen when supervision is enabled */
4288935a399SIhor Antonov 	switch (state->pid) {
4298935a399SIhor Antonov 	case -1:
4309da0ef13SMikolaj Golub 		warn("fork");
4318935a399SIhor Antonov 		state->mode = MODE_NOCHILD;
4328935a399SIhor Antonov 		return;
4338935a399SIhor Antonov 	/* fork succeeded, this is child's branch */
4348935a399SIhor Antonov 	case 0:
4358935a399SIhor Antonov 		close(kq);
4368935a399SIhor Antonov 		daemon_set_child_pipe(state);
4378935a399SIhor Antonov 		daemon_exec(state);
43853d49b37SJilles Tjoelker 		break;
439cd1e6e70SIhor Antonov 	}
440cd1e6e70SIhor Antonov 
4418935a399SIhor Antonov 	/* case: pid > 0; fork succeeded */
442407e3790SIhor Antonov 	close(state->pipe_wr);
443407e3790SIhor Antonov 	state->pipe_wr = -1;
4448935a399SIhor Antonov 	setproctitle("%s[%d]", state->title, (int)state->pid);
445cec8e6baSDag-Erling Smørgrav 	setbuf(stdout, NULL);
446cd1e6e70SIhor Antonov 
4478935a399SIhor Antonov 	while (state->mode != MODE_NOCHILD) {
4488935a399SIhor Antonov 		ret = kevent(kq, NULL, 0, &event, 1, NULL);
4498935a399SIhor Antonov 		switch (ret) {
4508935a399SIhor Antonov 		case -1:
451494e7dfdSKyle Evans 			if (errno == EINTR)
452494e7dfdSKyle Evans 				continue;
4538935a399SIhor Antonov 			err(EXIT_FAILURE, "kevent wait");
4548935a399SIhor Antonov 		case 0:
455cd1e6e70SIhor Antonov 			continue;
45653d49b37SJilles Tjoelker 		}
457cd1e6e70SIhor Antonov 
4588935a399SIhor Antonov 		if (event.flags & EV_ERROR) {
4598935a399SIhor Antonov 			errx(EXIT_FAILURE, "Event error: %s",
460a6f795ccSIhor Antonov 			    strerror((int)event.data));
461cd1e6e70SIhor Antonov 		}
462cd1e6e70SIhor Antonov 
4638935a399SIhor Antonov 		switch (event.filter) {
4648935a399SIhor Antonov 		case EVFILT_SIGNAL:
465cd1e6e70SIhor Antonov 
4668935a399SIhor Antonov 			switch (event.ident) {
4678935a399SIhor Antonov 			case SIGCHLD:
4688935a399SIhor Antonov 				if (daemon_is_child_dead(state)) {
4698935a399SIhor Antonov 					/* child is dead, read all until EOF */
4708935a399SIhor Antonov 					state->pid = -1;
4718935a399SIhor Antonov 					state->mode = MODE_NOCHILD;
472e0645579SKyle Evans 					while (listen_child(state)) {
473e0645579SKyle Evans 						continue;
474e0645579SKyle Evans 					}
4758935a399SIhor Antonov 				}
4768935a399SIhor Antonov 				continue;
4778935a399SIhor Antonov 			case SIGTERM:
4788935a399SIhor Antonov 				if (state->mode != MODE_SUPERVISE) {
4798935a399SIhor Antonov 					/* user is impatient */
4808935a399SIhor Antonov 					/* TODO: warn about repeated SIGTERM? */
4818935a399SIhor Antonov 					continue;
482cd1e6e70SIhor Antonov 				}
483cd1e6e70SIhor Antonov 
4848935a399SIhor Antonov 				state->mode = MODE_TERMINATING;
4858935a399SIhor Antonov 				state->restart_enabled = false;
4868935a399SIhor Antonov 				if (state->pid > 0) {
4878935a399SIhor Antonov 					kill(state->pid, SIGTERM);
48853d49b37SJilles Tjoelker 				}
4894c41f4a0SIhor Antonov 				/*
4908935a399SIhor Antonov 				 * TODO set kevent timer to exit
4918935a399SIhor Antonov 				 * unconditionally after some time
4924c41f4a0SIhor Antonov 				 */
4938935a399SIhor Antonov 				continue;
4948935a399SIhor Antonov 			case SIGHUP:
4958935a399SIhor Antonov 				if (state->log_reopen && state->output_fd >= 0) {
4968935a399SIhor Antonov 					reopen_log(state);
4978935a399SIhor Antonov 				}
4988935a399SIhor Antonov 				continue;
4998935a399SIhor Antonov 			}
5008935a399SIhor Antonov 			break;
5018935a399SIhor Antonov 
5028935a399SIhor Antonov 		case EVFILT_READ:
5038935a399SIhor Antonov 			/*
5048935a399SIhor Antonov 			 * detecting EOF is no longer necessary
5058935a399SIhor Antonov 			 * if child closes the pipe daemon will stop getting
5068935a399SIhor Antonov 			 * EVFILT_READ events
5078935a399SIhor Antonov 			 */
5088935a399SIhor Antonov 
5098935a399SIhor Antonov 			if (event.data > 0) {
5106ac7c9f0SIhor Antonov 				(void)listen_child(state);
5118935a399SIhor Antonov 			}
5128935a399SIhor Antonov 			continue;
5138935a399SIhor Antonov 		default:
514*bc1dfc31SKyle Evans 			assert(0 && "Unexpected kevent filter type");
5158935a399SIhor Antonov 			continue;
5168935a399SIhor Antonov 		}
51753d49b37SJilles Tjoelker 	}
5184c41f4a0SIhor Antonov 
519*bc1dfc31SKyle Evans 	/* EVFILT_READ kqueue filter goes away here. */
520407e3790SIhor Antonov 	close(state->pipe_rd);
521407e3790SIhor Antonov 	state->pipe_rd = -1;
522aa8722ccSKyle Evans 
523aa8722ccSKyle Evans 	/*
524aa8722ccSKyle Evans 	 * We don't have to truncate the pidfile, but it's easier to test
525aa8722ccSKyle Evans 	 * daemon(8) behavior in some respects if we do.  We won't bother if
526aa8722ccSKyle Evans 	 * the child won't be restarted.
527aa8722ccSKyle Evans 	 */
528aa8722ccSKyle Evans 	if (state->child_pidfh != NULL && state->restart_enabled) {
529aa8722ccSKyle Evans 		pidfile_truncate(state->child_pidfh);
530aa8722ccSKyle Evans 	}
531bd06a3ecSMike Barcroft }
532bd06a3ecSMike Barcroft 
533*bc1dfc31SKyle Evans /*
534*bc1dfc31SKyle Evans  * Note that daemon_sleep() should not be called with anything but the signal
535*bc1dfc31SKyle Evans  * events in the kqueue without further consideration.
536*bc1dfc31SKyle Evans  */
537bd06a3ecSMike Barcroft static void
daemon_sleep(struct daemon_state * state)5388935a399SIhor Antonov daemon_sleep(struct daemon_state *state)
539195fc497SMikolaj Golub {
540*bc1dfc31SKyle Evans 	struct kevent event = { 0 };
541*bc1dfc31SKyle Evans 	int ret;
542*bc1dfc31SKyle Evans 
543*bc1dfc31SKyle Evans 	assert(state->pipe_rd == -1);
544*bc1dfc31SKyle Evans 	assert(state->pipe_wr == -1);
54509a3675dSConrad Meyer 
5468935a399SIhor Antonov 	if (!state->restart_enabled) {
5478935a399SIhor Antonov 		return;
5488935a399SIhor Antonov 	}
549*bc1dfc31SKyle Evans 
550*bc1dfc31SKyle Evans 	EV_SET(&event, 0, EVFILT_TIMER, EV_ADD|EV_ONESHOT, NOTE_SECONDS,
551*bc1dfc31SKyle Evans 	    state->restart_delay, NULL);
552*bc1dfc31SKyle Evans 	if (kevent(state->kqueue_fd, &event, 1, NULL, 0, NULL) == -1) {
553*bc1dfc31SKyle Evans 		err(1, "failed to register timer");
554*bc1dfc31SKyle Evans 	}
555*bc1dfc31SKyle Evans 
556*bc1dfc31SKyle Evans 	for (;;) {
557*bc1dfc31SKyle Evans 		ret = kevent(state->kqueue_fd, NULL, 0, &event, 1, NULL);
558*bc1dfc31SKyle Evans 		if (ret == -1) {
5596b4ef4b1SIhor Antonov 			if (errno != EINTR) {
560*bc1dfc31SKyle Evans 				err(1, "kevent");
561*bc1dfc31SKyle Evans 			}
562*bc1dfc31SKyle Evans 
563*bc1dfc31SKyle Evans 			continue;
564*bc1dfc31SKyle Evans 		}
565*bc1dfc31SKyle Evans 
566*bc1dfc31SKyle Evans 		/*
567*bc1dfc31SKyle Evans 		 * Any other events being raised are indicative of a problem
568*bc1dfc31SKyle Evans 		 * that we need to investigate.  Most likely being that
569*bc1dfc31SKyle Evans 		 * something was not cleaned up from the eventloop.
570*bc1dfc31SKyle Evans 		 */
571*bc1dfc31SKyle Evans 		assert(event.filter == EVFILT_TIMER ||
572*bc1dfc31SKyle Evans 		    event.filter == EVFILT_SIGNAL);
573*bc1dfc31SKyle Evans 
574*bc1dfc31SKyle Evans 		if (event.filter == EVFILT_TIMER) {
575*bc1dfc31SKyle Evans 			/* Break's over, back to work. */
576*bc1dfc31SKyle Evans 			break;
577*bc1dfc31SKyle Evans 		}
578*bc1dfc31SKyle Evans 
579*bc1dfc31SKyle Evans 		/* Process any pending signals. */
580*bc1dfc31SKyle Evans 		switch (event.ident) {
581*bc1dfc31SKyle Evans 		case SIGTERM:
582*bc1dfc31SKyle Evans 			/*
583*bc1dfc31SKyle Evans 			 * We could disarm the timer, but we'll be terminating
584*bc1dfc31SKyle Evans 			 * promptly anyways.
585*bc1dfc31SKyle Evans 			 */
586*bc1dfc31SKyle Evans 			state->restart_enabled = false;
587*bc1dfc31SKyle Evans 			return;
588*bc1dfc31SKyle Evans 		case SIGHUP:
589*bc1dfc31SKyle Evans 			if (state->log_reopen && state->output_fd >= 0) {
590*bc1dfc31SKyle Evans 				reopen_log(state);
591*bc1dfc31SKyle Evans 			}
592*bc1dfc31SKyle Evans 
593*bc1dfc31SKyle Evans 			break;
594*bc1dfc31SKyle Evans 		case SIGCHLD:
595*bc1dfc31SKyle Evans 		default:
596*bc1dfc31SKyle Evans 			/* Discard */
597*bc1dfc31SKyle Evans 			break;
59853d49b37SJilles Tjoelker 		}
59953d49b37SJilles Tjoelker 	}
600*bc1dfc31SKyle Evans 
601*bc1dfc31SKyle Evans 	/* SIGTERM should've returned immediately. */
602*bc1dfc31SKyle Evans 	assert(state->restart_enabled);
6036b4ef4b1SIhor Antonov }
60453d49b37SJilles Tjoelker 
60553d49b37SJilles Tjoelker static void
open_pid_files(struct daemon_state * state)606298a392eSIhor Antonov open_pid_files(struct daemon_state *state)
60753d49b37SJilles Tjoelker {
60853d49b37SJilles Tjoelker 	pid_t fpid;
60953d49b37SJilles Tjoelker 	int serrno;
61053d49b37SJilles Tjoelker 
611298a392eSIhor Antonov 	if (state->child_pidfile) {
612298a392eSIhor Antonov 		state->child_pidfh = pidfile_open(state->child_pidfile, 0600, &fpid);
613298a392eSIhor Antonov 		if (state->child_pidfh == NULL) {
61453d49b37SJilles Tjoelker 			if (errno == EEXIST) {
61553d49b37SJilles Tjoelker 				errx(3, "process already running, pid: %d",
61653d49b37SJilles Tjoelker 				    fpid);
61753d49b37SJilles Tjoelker 			}
618298a392eSIhor Antonov 			err(2, "pidfile ``%s''", state->child_pidfile);
61953d49b37SJilles Tjoelker 		}
62053d49b37SJilles Tjoelker 	}
62153d49b37SJilles Tjoelker 	/* Do the same for the actual daemon process. */
622298a392eSIhor Antonov 	if (state->parent_pidfile) {
623298a392eSIhor Antonov 		state->parent_pidfh= pidfile_open(state->parent_pidfile, 0600, &fpid);
624298a392eSIhor Antonov 		if (state->parent_pidfh == NULL) {
62553d49b37SJilles Tjoelker 			serrno = errno;
626298a392eSIhor Antonov 			pidfile_remove(state->child_pidfh);
62753d49b37SJilles Tjoelker 			errno = serrno;
62853d49b37SJilles Tjoelker 			if (errno == EEXIST) {
62953d49b37SJilles Tjoelker 				errx(3, "process already running, pid: %d",
63053d49b37SJilles Tjoelker 				     fpid);
63153d49b37SJilles Tjoelker 			}
632298a392eSIhor Antonov 			err(2, "ppidfile ``%s''", state->parent_pidfile);
63353d49b37SJilles Tjoelker 		}
63453d49b37SJilles Tjoelker 	}
63553d49b37SJilles Tjoelker }
63653d49b37SJilles Tjoelker 
63753d49b37SJilles Tjoelker static int
get_log_mapping(const char * str,const CODE * c)63853d49b37SJilles Tjoelker get_log_mapping(const char *str, const CODE *c)
63953d49b37SJilles Tjoelker {
64053d49b37SJilles Tjoelker 	const CODE *cp;
64153d49b37SJilles Tjoelker 	for (cp = c; cp->c_name; cp++)
6426b4ef4b1SIhor Antonov 		if (strcmp(cp->c_name, str) == 0) {
64353d49b37SJilles Tjoelker 			return cp->c_val;
6446b4ef4b1SIhor Antonov 		}
64553d49b37SJilles Tjoelker 	return -1;
646195fc497SMikolaj Golub }
647195fc497SMikolaj Golub 
648195fc497SMikolaj Golub static void
restrict_process(const char * user)649e6d4b388STom Rhodes restrict_process(const char *user)
65012d7249eSTom Rhodes {
65112d7249eSTom Rhodes 	struct passwd *pw = NULL;
65212d7249eSTom Rhodes 
653e6d4b388STom Rhodes 	pw = getpwnam(user);
6546b4ef4b1SIhor Antonov 	if (pw == NULL) {
655e6d4b388STom Rhodes 		errx(1, "unknown user: %s", user);
6566b4ef4b1SIhor Antonov 	}
65712d7249eSTom Rhodes 
6586b4ef4b1SIhor Antonov 	if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0) {
659e6d4b388STom Rhodes 		errx(1, "failed to set user environment");
6606b4ef4b1SIhor Antonov 	}
6616b3ad1d7SMaxim Sobolev 
6626b3ad1d7SMaxim Sobolev 	setenv("USER", pw->pw_name, 1);
6636b3ad1d7SMaxim Sobolev 	setenv("HOME", pw->pw_dir, 1);
6646b3ad1d7SMaxim Sobolev 	setenv("SHELL", *pw->pw_shell ? pw->pw_shell : _PATH_BSHELL, 1);
66512d7249eSTom Rhodes }
66612d7249eSTom Rhodes 
66753d49b37SJilles Tjoelker /*
66853d49b37SJilles Tjoelker  * We try to collect whole lines terminated by '\n'. Otherwise we collect a
66953d49b37SJilles Tjoelker  * full buffer, and then output it.
67053d49b37SJilles Tjoelker  *
671bc43a9a7SIhor Antonov  * Return value of false is assumed to mean EOF or error, and true indicates to
67253d49b37SJilles Tjoelker  * continue reading.
67353d49b37SJilles Tjoelker  */
674bc43a9a7SIhor Antonov static bool
listen_child(struct daemon_state * state)6756ac7c9f0SIhor Antonov listen_child(struct daemon_state *state)
6762ad43027SMikolaj Golub {
677a6f795ccSIhor Antonov 	ssize_t rv;
6785745a584SIhor Antonov 	unsigned char *cp;
6792ad43027SMikolaj Golub 
680cf6356fdSIhor Antonov 	assert(state != NULL);
68124fd3e96SIhor Antonov 	assert(state->pos < LBUF_SIZE - 1);
68253d49b37SJilles Tjoelker 
683e0645579SKyle Evans 	rv = read(state->pipe_rd, state->buf + state->pos,
684e0645579SKyle Evans 	    LBUF_SIZE - state->pos - 1);
68553d49b37SJilles Tjoelker 	if (rv > 0) {
68624fd3e96SIhor Antonov 		state->pos += rv;
68724fd3e96SIhor Antonov 		assert(state->pos <= LBUF_SIZE - 1);
68853d49b37SJilles Tjoelker 		/* Always NUL-terminate just in case. */
68924fd3e96SIhor Antonov 		state->buf[LBUF_SIZE - 1] = '\0';
6905745a584SIhor Antonov 
69153d49b37SJilles Tjoelker 		/*
6925745a584SIhor Antonov 		 * Find position of the last newline in the buffer.
6935745a584SIhor Antonov 		 * The buffer is guaranteed to have one or more complete lines
6945745a584SIhor Antonov 		 * if at least one newline was found when searching in reverse.
6955745a584SIhor Antonov 		 * All complete lines are flushed.
69653d49b37SJilles Tjoelker 		 * This does not take NUL characters into account.
69753d49b37SJilles Tjoelker 		 */
6985745a584SIhor Antonov 		cp = memrchr(state->buf, '\n', state->pos);
6995745a584SIhor Antonov 		if (cp != NULL) {
70024fd3e96SIhor Antonov 			size_t bytes_line = cp - state->buf + 1;
70124fd3e96SIhor Antonov 			assert(bytes_line <= state->pos);
70224fd3e96SIhor Antonov 			do_output(state->buf, bytes_line, state);
70324fd3e96SIhor Antonov 			state->pos -= bytes_line;
70424fd3e96SIhor Antonov 			memmove(state->buf, cp + 1, state->pos);
705195fc497SMikolaj Golub 		}
70653d49b37SJilles Tjoelker 		/* Wait until the buffer is full. */
70724fd3e96SIhor Antonov 		if (state->pos < LBUF_SIZE - 1) {
708bc43a9a7SIhor Antonov 			return true;
7096b4ef4b1SIhor Antonov 		}
71024fd3e96SIhor Antonov 		do_output(state->buf, state->pos, state);
71124fd3e96SIhor Antonov 		state->pos = 0;
712bc43a9a7SIhor Antonov 		return true;
71353d49b37SJilles Tjoelker 	} else if (rv == -1) {
71453d49b37SJilles Tjoelker 		/* EINTR should trigger another read. */
71553d49b37SJilles Tjoelker 		if (errno == EINTR) {
716bc43a9a7SIhor Antonov 			return true;
71753d49b37SJilles Tjoelker 		} else {
71853d49b37SJilles Tjoelker 			warn("read");
719bc43a9a7SIhor Antonov 			return false;
720c60d51f9SMikolaj Golub 		}
72153d49b37SJilles Tjoelker 	}
72253d49b37SJilles Tjoelker 	/* Upon EOF, we have to flush what's left of the buffer. */
72324fd3e96SIhor Antonov 	if (state->pos > 0) {
72424fd3e96SIhor Antonov 		do_output(state->buf, state->pos, state);
72524fd3e96SIhor Antonov 		state->pos = 0;
72653d49b37SJilles Tjoelker 	}
727bc43a9a7SIhor Antonov 	return false;
72853d49b37SJilles Tjoelker }
72953d49b37SJilles Tjoelker 
73053d49b37SJilles Tjoelker /*
73153d49b37SJilles Tjoelker  * The default behavior is to stay silent if the user wants to redirect
73253d49b37SJilles Tjoelker  * output to a file and/or syslog. If neither are provided, then we bounce
73353d49b37SJilles Tjoelker  * everything back to parent's stdout.
73453d49b37SJilles Tjoelker  */
73553d49b37SJilles Tjoelker static void
do_output(const unsigned char * buf,size_t len,struct daemon_state * state)736298a392eSIhor Antonov do_output(const unsigned char *buf, size_t len, struct daemon_state *state)
73753d49b37SJilles Tjoelker {
73853d49b37SJilles Tjoelker 	assert(len <= LBUF_SIZE);
739cf6356fdSIhor Antonov 	assert(state != NULL);
74053d49b37SJilles Tjoelker 
7416b4ef4b1SIhor Antonov 	if (len < 1) {
74253d49b37SJilles Tjoelker 		return;
7436b4ef4b1SIhor Antonov 	}
744298a392eSIhor Antonov 	if (state->syslog_enabled) {
745298a392eSIhor Antonov 		syslog(state->syslog_priority, "%.*s", (int)len, buf);
7466b4ef4b1SIhor Antonov 	}
747298a392eSIhor Antonov 	if (state->output_fd != -1) {
748298a392eSIhor Antonov 		if (write(state->output_fd, buf, len) == -1)
74953d49b37SJilles Tjoelker 			warn("write");
75053d49b37SJilles Tjoelker 	}
751298a392eSIhor Antonov 	if (state->keep_fds_open &&
752298a392eSIhor Antonov 	    !state->syslog_enabled &&
753298a392eSIhor Antonov 	    state->output_fd == -1) {
75453d49b37SJilles Tjoelker 		printf("%.*s", (int)len, buf);
75553d49b37SJilles Tjoelker 	}
7566b4ef4b1SIhor Antonov }
75753d49b37SJilles Tjoelker 
7584cd407ecSMaxim Sobolev static int
open_log(const char * outfn)7594cd407ecSMaxim Sobolev open_log(const char *outfn)
7604cd407ecSMaxim Sobolev {
7614cd407ecSMaxim Sobolev 
7624cd407ecSMaxim Sobolev 	return open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
7634cd407ecSMaxim Sobolev }
7644cd407ecSMaxim Sobolev 
7654cd407ecSMaxim Sobolev static void
reopen_log(struct daemon_state * state)766298a392eSIhor Antonov reopen_log(struct daemon_state *state)
7674cd407ecSMaxim Sobolev {
7684cd407ecSMaxim Sobolev 	int outfd;
7694cd407ecSMaxim Sobolev 
770298a392eSIhor Antonov 	outfd = open_log(state->output_filename);
771298a392eSIhor Antonov 	if (state->output_fd >= 0) {
772298a392eSIhor Antonov 		close(state->output_fd);
7736b4ef4b1SIhor Antonov 	}
774298a392eSIhor Antonov 	state->output_fd = outfd;
7754cd407ecSMaxim Sobolev }
7764cd407ecSMaxim Sobolev 
777298a392eSIhor Antonov static void
daemon_state_init(struct daemon_state * state)778298a392eSIhor Antonov daemon_state_init(struct daemon_state *state)
779298a392eSIhor Antonov {
780298a392eSIhor Antonov 	*state = (struct daemon_state) {
78124fd3e96SIhor Antonov 		.buf = {0},
78224fd3e96SIhor Antonov 		.pos = 0,
7834c41f4a0SIhor Antonov 		.argv = NULL,
784298a392eSIhor Antonov 		.parent_pidfh = NULL,
785298a392eSIhor Antonov 		.child_pidfh = NULL,
786298a392eSIhor Antonov 		.child_pidfile = NULL,
787298a392eSIhor Antonov 		.parent_pidfile = NULL,
788298a392eSIhor Antonov 		.title = NULL,
789298a392eSIhor Antonov 		.user = NULL,
7908935a399SIhor Antonov 		.mode = MODE_DAEMON,
791298a392eSIhor Antonov 		.restart_enabled = false,
7928935a399SIhor Antonov 		.pid = 0,
793407e3790SIhor Antonov 		.pipe_rd = -1,
794407e3790SIhor Antonov 		.pipe_wr = -1,
795298a392eSIhor Antonov 		.keep_cur_workdir = 1,
796*bc1dfc31SKyle Evans 		.kqueue_fd = -1,
797298a392eSIhor Antonov 		.restart_delay = 1,
798298a392eSIhor Antonov 		.stdmask = STDOUT_FILENO | STDERR_FILENO,
799298a392eSIhor Antonov 		.syslog_enabled = false,
800298a392eSIhor Antonov 		.log_reopen = false,
801298a392eSIhor Antonov 		.syslog_priority = LOG_NOTICE,
802298a392eSIhor Antonov 		.syslog_tag = "daemon",
803298a392eSIhor Antonov 		.syslog_facility = LOG_DAEMON,
804298a392eSIhor Antonov 		.keep_fds_open = 1,
805298a392eSIhor Antonov 		.output_fd = -1,
806298a392eSIhor Antonov 		.output_filename = NULL,
8077618c9e1SJuraj Lutter 		.restart_count = -1,
8087618c9e1SJuraj Lutter 		.restarted_count = 0
809298a392eSIhor Antonov 	};
810298a392eSIhor Antonov }
811cf6356fdSIhor Antonov 
812cf6356fdSIhor Antonov static _Noreturn void
daemon_terminate(struct daemon_state * state)813cf6356fdSIhor Antonov daemon_terminate(struct daemon_state *state)
814cf6356fdSIhor Antonov {
815cf6356fdSIhor Antonov 	assert(state != NULL);
8168935a399SIhor Antonov 
817*bc1dfc31SKyle Evans 	if (state->kqueue_fd >= 0) {
818*bc1dfc31SKyle Evans 		close(state->kqueue_fd);
819*bc1dfc31SKyle Evans 	}
8208935a399SIhor Antonov 	if (state->output_fd >= 0) {
821cf6356fdSIhor Antonov 		close(state->output_fd);
8228935a399SIhor Antonov 	}
823407e3790SIhor Antonov 	if (state->pipe_rd >= 0) {
824407e3790SIhor Antonov 		close(state->pipe_rd);
8258935a399SIhor Antonov 	}
8268935a399SIhor Antonov 
827407e3790SIhor Antonov 	if (state->pipe_wr >= 0) {
828407e3790SIhor Antonov 		close(state->pipe_wr);
8298935a399SIhor Antonov 	}
830cf6356fdSIhor Antonov 	if (state->syslog_enabled) {
831cf6356fdSIhor Antonov 		closelog();
832cf6356fdSIhor Antonov 	}
833cf6356fdSIhor Antonov 	pidfile_remove(state->child_pidfh);
834cf6356fdSIhor Antonov 	pidfile_remove(state->parent_pidfh);
835cf6356fdSIhor Antonov 
836cf6356fdSIhor Antonov 	/*
837cf6356fdSIhor Antonov 	 * Note that the exit value here doesn't matter in the case of a clean
838cf6356fdSIhor Antonov 	 * exit; daemon(3) already detached us from the caller, nothing is left
839cf6356fdSIhor Antonov 	 * to care about this one.
840cf6356fdSIhor Antonov 	 */
841cf6356fdSIhor Antonov 	exit(1);
842cf6356fdSIhor Antonov }
8438935a399SIhor Antonov 
8448935a399SIhor Antonov /*
8458eaa6be8SKonstantin Belousov  * Returns true if SIGCHILD came from state->pid due to its exit.
8468935a399SIhor Antonov  */
8478935a399SIhor Antonov static bool
daemon_is_child_dead(struct daemon_state * state)8488935a399SIhor Antonov daemon_is_child_dead(struct daemon_state *state)
8498935a399SIhor Antonov {
8508eaa6be8SKonstantin Belousov 	int status;
8518eaa6be8SKonstantin Belousov 
8528935a399SIhor Antonov 	for (;;) {
8538eaa6be8SKonstantin Belousov 		int who = waitpid(-1, &status, WNOHANG);
8548eaa6be8SKonstantin Belousov 		if (state->pid == who && (WIFEXITED(status) ||
8558eaa6be8SKonstantin Belousov 		    WIFSIGNALED(status))) {
8568935a399SIhor Antonov 			return true;
8578935a399SIhor Antonov 		}
8588eaa6be8SKonstantin Belousov 		if (who == 0) {
8598eaa6be8SKonstantin Belousov 			return false;
8608eaa6be8SKonstantin Belousov 		}
8618935a399SIhor Antonov 		if (who == -1 && errno != EINTR) {
8628935a399SIhor Antonov 			warn("waitpid");
8638935a399SIhor Antonov 			return false;
8648935a399SIhor Antonov 		}
8658935a399SIhor Antonov 	}
8668935a399SIhor Antonov }
8678935a399SIhor Antonov 
8688935a399SIhor Antonov static void
daemon_set_child_pipe(struct daemon_state * state)8698935a399SIhor Antonov daemon_set_child_pipe(struct daemon_state *state)
8708935a399SIhor Antonov {
8718935a399SIhor Antonov 	if (state->stdmask & STDERR_FILENO) {
872407e3790SIhor Antonov 		if (dup2(state->pipe_wr, STDERR_FILENO) == -1) {
8738935a399SIhor Antonov 			err(1, "dup2");
8748935a399SIhor Antonov 		}
8758935a399SIhor Antonov 	}
8768935a399SIhor Antonov 	if (state->stdmask & STDOUT_FILENO) {
877407e3790SIhor Antonov 		if (dup2(state->pipe_wr, STDOUT_FILENO) == -1) {
8788935a399SIhor Antonov 			err(1, "dup2");
8798935a399SIhor Antonov 		}
8808935a399SIhor Antonov 	}
881407e3790SIhor Antonov 	if (state->pipe_wr != STDERR_FILENO &&
882407e3790SIhor Antonov 	    state->pipe_wr != STDOUT_FILENO) {
883407e3790SIhor Antonov 		close(state->pipe_wr);
8848935a399SIhor Antonov 	}
8858935a399SIhor Antonov 
8868935a399SIhor Antonov 	/* The child gets dup'd pipes. */
887407e3790SIhor Antonov 	close(state->pipe_rd);
8888935a399SIhor Antonov }
889aa8722ccSKyle Evans 
890aa8722ccSKyle Evans static int
daemon_setup_kqueue(void)891*bc1dfc31SKyle Evans daemon_setup_kqueue(void)
892*bc1dfc31SKyle Evans {
893*bc1dfc31SKyle Evans 	int kq;
894*bc1dfc31SKyle Evans 	struct kevent event = { 0 };
895*bc1dfc31SKyle Evans 
896*bc1dfc31SKyle Evans 	kq = kqueuex(KQUEUE_CLOEXEC);
897*bc1dfc31SKyle Evans 	if (kq == -1) {
898*bc1dfc31SKyle Evans 		err(EXIT_FAILURE, "kqueue");
899*bc1dfc31SKyle Evans 	}
900*bc1dfc31SKyle Evans 
901*bc1dfc31SKyle Evans 	EV_SET(&event, SIGHUP,  EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
902*bc1dfc31SKyle Evans 	if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
903*bc1dfc31SKyle Evans 		err(EXIT_FAILURE, "failed to register kevent");
904*bc1dfc31SKyle Evans 	}
905*bc1dfc31SKyle Evans 
906*bc1dfc31SKyle Evans 	EV_SET(&event, SIGTERM, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
907*bc1dfc31SKyle Evans 	if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
908*bc1dfc31SKyle Evans 		err(EXIT_FAILURE, "failed to register kevent");
909*bc1dfc31SKyle Evans 	}
910*bc1dfc31SKyle Evans 
911*bc1dfc31SKyle Evans 	EV_SET(&event, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
912*bc1dfc31SKyle Evans 	if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
913*bc1dfc31SKyle Evans 		err(EXIT_FAILURE, "failed to register kevent");
914*bc1dfc31SKyle Evans 	}
915*bc1dfc31SKyle Evans 
916*bc1dfc31SKyle Evans 	return (kq);
917*bc1dfc31SKyle Evans }
918*bc1dfc31SKyle Evans 
919*bc1dfc31SKyle Evans static int
pidfile_truncate(struct pidfh * pfh)920aa8722ccSKyle Evans pidfile_truncate(struct pidfh *pfh)
921aa8722ccSKyle Evans {
922aa8722ccSKyle Evans 	int pfd = pidfile_fileno(pfh);
923aa8722ccSKyle Evans 
924aa8722ccSKyle Evans 	assert(pfd >= 0);
925aa8722ccSKyle Evans 
926aa8722ccSKyle Evans 	if (ftruncate(pfd, 0) == -1)
927aa8722ccSKyle Evans 		return (-1);
928aa8722ccSKyle Evans 
929aa8722ccSKyle Evans 	/*
930aa8722ccSKyle Evans 	 * pidfile_write(3) will always pwrite(..., 0) today, but let's assume
931aa8722ccSKyle Evans 	 * it may not always and do a best-effort reset of the position just to
932aa8722ccSKyle Evans 	 * set a good example.
933aa8722ccSKyle Evans 	 */
934aa8722ccSKyle Evans 	(void)lseek(pfd, 0, SEEK_SET);
935aa8722ccSKyle Evans 	return (0);
936aa8722ccSKyle Evans }
937