xref: /freebsd/usr.sbin/daemon/daemon.c (revision 298a392ec31819c8440974eeb47dfed48568fd5e)
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 
3354ede02dSPhilippe Charnier #include <sys/cdefs.h>
3454ede02dSPhilippe Charnier __FBSDID("$FreeBSD$");
3554ede02dSPhilippe Charnier 
36c6262cb6SPawel Jakub Dawidek #include <sys/param.h>
3753c49998SMikolaj Golub #include <sys/mman.h>
382ad43027SMikolaj Golub #include <sys/wait.h>
39bd06a3ecSMike Barcroft 
4053d49b37SJilles Tjoelker #include <fcntl.h>
41bd06a3ecSMike Barcroft #include <err.h>
42846be7bdSPoul-Henning Kamp #include <errno.h>
430a402ad2SIhor Antonov #include <getopt.h>
44c6262cb6SPawel Jakub Dawidek #include <libutil.h>
45e6d4b388STom Rhodes #include <login_cap.h>
466b3ad1d7SMaxim Sobolev #include <paths.h>
47195fc497SMikolaj Golub #include <pwd.h>
48195fc497SMikolaj Golub #include <signal.h>
49bd06a3ecSMike Barcroft #include <stdio.h>
50203df05bSIhor Antonov #include <stdbool.h>
51bd06a3ecSMike Barcroft #include <stdlib.h>
52bd06a3ecSMike Barcroft #include <unistd.h>
5353d49b37SJilles Tjoelker #include <string.h>
5453d49b37SJilles Tjoelker #include <strings.h>
5553d49b37SJilles Tjoelker #define SYSLOG_NAMES
5653d49b37SJilles Tjoelker #include <syslog.h>
5753d49b37SJilles Tjoelker #include <time.h>
5853d49b37SJilles Tjoelker #include <assert.h>
59bd06a3ecSMike Barcroft 
6053d49b37SJilles Tjoelker #define LBUF_SIZE 4096
6153d49b37SJilles Tjoelker 
62*298a392eSIhor Antonov struct daemon_state {
63*298a392eSIhor Antonov 	int pipe_fd[2];
64*298a392eSIhor Antonov 	const char *child_pidfile;
65*298a392eSIhor Antonov 	const char *parent_pidfile;
66e70444c6SIhor Antonov 	const char *output_filename;
676f063672SIhor Antonov 	const char *syslog_tag;
68*298a392eSIhor Antonov 	const char *title;
69*298a392eSIhor Antonov 	const char *user;
70*298a392eSIhor Antonov 	struct pidfh *parent_pidfh;
71*298a392eSIhor Antonov 	struct pidfh *child_pidfh;
72*298a392eSIhor Antonov 	int keep_cur_workdir;
73*298a392eSIhor Antonov 	int restart_delay;
74*298a392eSIhor Antonov 	int stdmask;
75e70444c6SIhor Antonov 	int syslog_priority;
766f063672SIhor Antonov 	int syslog_facility;
77129ec8f4SIhor Antonov 	int keep_fds_open;
78e70444c6SIhor Antonov 	int output_fd;
79*298a392eSIhor Antonov 	bool supervision_enabled;
80*298a392eSIhor Antonov 	bool child_eof;
81*298a392eSIhor Antonov 	bool restart_enabled;
82f2f9d31dSIhor Antonov 	bool syslog_enabled;
83*298a392eSIhor Antonov 	bool log_reopen;
8453d49b37SJilles Tjoelker };
8553d49b37SJilles Tjoelker 
86e6d4b388STom Rhodes static void restrict_process(const char *);
8753d49b37SJilles Tjoelker static void handle_term(int);
8853d49b37SJilles Tjoelker static void handle_chld(int);
894cd407ecSMaxim Sobolev static void handle_hup(int);
904cd407ecSMaxim Sobolev static int  open_log(const char *);
91*298a392eSIhor Antonov static void reopen_log(struct daemon_state *);
92*298a392eSIhor Antonov static bool listen_child(int, struct daemon_state *);
9353d49b37SJilles Tjoelker static int  get_log_mapping(const char *, const CODE *);
94*298a392eSIhor Antonov static void open_pid_files(struct daemon_state *);
95*298a392eSIhor Antonov static void do_output(const unsigned char *, size_t, struct daemon_state *);
9653d49b37SJilles Tjoelker static void daemon_sleep(time_t, long);
97*298a392eSIhor Antonov static void daemon_state_init(struct daemon_state *);
98bd06a3ecSMike Barcroft 
99e745dc22SIhor Antonov static volatile sig_atomic_t terminate = 0;
100e745dc22SIhor Antonov static volatile sig_atomic_t child_gone = 0;
10175f61ca9SIhor Antonov static volatile sig_atomic_t pid = 0;
102e745dc22SIhor Antonov static volatile sig_atomic_t do_log_reopen = 0;
10353d49b37SJilles Tjoelker 
1040a402ad2SIhor Antonov static const char shortopts[] = "+cfHSp:P:ru:o:s:l:t:m:R:T:h";
1050a402ad2SIhor Antonov 
1060a402ad2SIhor Antonov static const struct option longopts[] = {
1070a402ad2SIhor Antonov         { "change-dir",         no_argument,            NULL,           'c' },
1080a402ad2SIhor Antonov         { "close-fds",          no_argument,            NULL,           'f' },
1090a402ad2SIhor Antonov         { "sighup",             no_argument,            NULL,           'H' },
1100a402ad2SIhor Antonov         { "syslog",             no_argument,            NULL,           'S' },
1110a402ad2SIhor Antonov         { "output-file",        required_argument,      NULL,           'o' },
1120a402ad2SIhor Antonov         { "output-mask",        required_argument,      NULL,           'm' },
1130a402ad2SIhor Antonov         { "child-pidfile",      required_argument,      NULL,           'p' },
1140a402ad2SIhor Antonov         { "supervisor-pidfile", required_argument,      NULL,           'P' },
1150a402ad2SIhor Antonov         { "restart",            no_argument,            NULL,           'r' },
1160a402ad2SIhor Antonov         { "restart-delay",      required_argument,      NULL,           'R' },
1170a402ad2SIhor Antonov         { "title",              required_argument,      NULL,           't' },
1180a402ad2SIhor Antonov         { "user",               required_argument,      NULL,           'u' },
1190a402ad2SIhor Antonov         { "syslog-priority",    required_argument,      NULL,           's' },
1200a402ad2SIhor Antonov         { "syslog-facility",    required_argument,      NULL,           'l' },
1210a402ad2SIhor Antonov         { "syslog-tag",         required_argument,      NULL,           'T' },
1220a402ad2SIhor Antonov         { "help",               no_argument,            NULL,           'h' },
1230a402ad2SIhor Antonov         { NULL,                 0,                      NULL,            0  }
1240a402ad2SIhor Antonov };
1250a402ad2SIhor Antonov 
1260a402ad2SIhor Antonov static _Noreturn void
1270a402ad2SIhor Antonov usage(int exitcode)
1280a402ad2SIhor Antonov {
1290a402ad2SIhor Antonov 	(void)fprintf(stderr,
1300a402ad2SIhor Antonov 	    "usage: daemon [-cfHrS] [-p child_pidfile] [-P supervisor_pidfile]\n"
1310a402ad2SIhor Antonov 	    "              [-u user] [-o output_file] [-t title]\n"
1320a402ad2SIhor Antonov 	    "              [-l syslog_facility] [-s syslog_priority]\n"
1330a402ad2SIhor Antonov 	    "              [-T syslog_tag] [-m output_mask] [-R restart_delay_secs]\n"
1340a402ad2SIhor Antonov 	    "command arguments ...\n");
1350a402ad2SIhor Antonov 
1360a402ad2SIhor Antonov 	(void)fprintf(stderr,
1370a402ad2SIhor Antonov 	    "  --change-dir         -c         Change the current working directory to root\n"
1380a402ad2SIhor Antonov 	    "  --close-fds          -f         Set stdin, stdout, stderr to /dev/null\n"
1390a402ad2SIhor Antonov 	    "  --sighup             -H         Close and re-open output file on SIGHUP\n"
1400a402ad2SIhor Antonov 	    "  --syslog             -S         Send output to syslog\n"
1410a402ad2SIhor Antonov 	    "  --output-file        -o <file>  Append output of the child process to file\n"
1420a402ad2SIhor Antonov 	    "  --output-mask        -m <mask>  What to send to syslog/file\n"
1430a402ad2SIhor Antonov 	    "                                  1=stdout, 2=stderr, 3=both\n"
1440a402ad2SIhor Antonov 	    "  --child-pidfile      -p <file>  Write PID of the child process to file\n"
1450a402ad2SIhor Antonov 	    "  --supervisor-pidfile -P <file>  Write PID of the supervisor process to file\n"
1460a402ad2SIhor Antonov 	    "  --restart            -r         Restart child if it terminates (1 sec delay)\n"
1470a402ad2SIhor Antonov 	    "  --restart-delay      -R <N>     Restart child if it terminates after N sec\n"
1480a402ad2SIhor Antonov 	    "  --title              -t <title> Set the title of the supervisor process\n"
1490a402ad2SIhor Antonov 	    "  --user               -u <user>  Drop privileges, run as given user\n"
1500a402ad2SIhor Antonov 	    "  --syslog-priority    -s <prio>  Set syslog priority\n"
1510a402ad2SIhor Antonov 	    "  --syslog-facility    -l <flty>  Set syslog facility\n"
1520a402ad2SIhor Antonov 	    "  --syslog-tag         -T <tag>   Set syslog tag\n"
1530a402ad2SIhor Antonov 	    "  --help               -h         Show this help\n");
1540a402ad2SIhor Antonov 
1550a402ad2SIhor Antonov 	exit(exitcode);
1560a402ad2SIhor Antonov }
1570a402ad2SIhor Antonov 
158bd06a3ecSMike Barcroft int
159bd06a3ecSMike Barcroft main(int argc, char *argv[])
160bd06a3ecSMike Barcroft {
161e745dc22SIhor Antonov 	char *p = NULL;
162e745dc22SIhor Antonov 	int ch = 0;
163*298a392eSIhor Antonov 	struct daemon_state state;
164e745dc22SIhor Antonov 	sigset_t mask_orig;
165e745dc22SIhor Antonov 	sigset_t mask_read;
166e745dc22SIhor Antonov 	sigset_t mask_term;
167e745dc22SIhor Antonov 	sigset_t mask_susp;
168bd06a3ecSMike Barcroft 
169*298a392eSIhor Antonov 	daemon_state_init(&state);
170e745dc22SIhor Antonov 	sigemptyset(&mask_susp);
171e745dc22SIhor Antonov 	sigemptyset(&mask_read);
172e745dc22SIhor Antonov 	sigemptyset(&mask_term);
17384866cefSIhor Antonov 	sigemptyset(&mask_orig);
174e745dc22SIhor Antonov 
175f907027bSIhor Antonov 	/*
176f907027bSIhor Antonov 	 * Supervision mode is enabled if one of the following options are used:
177f907027bSIhor Antonov 	 * --child-pidfile -p
178f907027bSIhor Antonov 	 * --supervisor-pidfile -P
179f907027bSIhor Antonov 	 * --restart -r / --restart-delay -R
180f907027bSIhor Antonov 	 * --syslog -S
181f907027bSIhor Antonov 	 * --syslog-facility -l
182f907027bSIhor Antonov 	 * --syslog-priority -s
183f907027bSIhor Antonov 	 * --syslog-tag -T
184f907027bSIhor Antonov 	 *
185f907027bSIhor Antonov 	 * In supervision mode daemon executes the command in a forked process
186f907027bSIhor Antonov 	 * and observes the child by waiting for SIGCHILD. In supervision mode
187f907027bSIhor Antonov 	 * daemon must never exit before the child, this is necessary  to prevent
188f907027bSIhor Antonov 	 * orphaning the child and leaving a stale pid file.
189f907027bSIhor Antonov 	 * To achieve this daemon catches SIGTERM and
190f907027bSIhor Antonov 	 * forwards it to the child, expecting to get SIGCHLD eventually.
191f907027bSIhor Antonov 	 */
1920a402ad2SIhor Antonov 	while ((ch = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) {
193bd06a3ecSMike Barcroft 		switch (ch) {
194bd06a3ecSMike Barcroft 		case 'c':
195*298a392eSIhor Antonov 			state.keep_cur_workdir = 0;
196bd06a3ecSMike Barcroft 			break;
197bd06a3ecSMike Barcroft 		case 'f':
198*298a392eSIhor Antonov 			state.keep_fds_open = 0;
199bd06a3ecSMike Barcroft 			break;
2004cd407ecSMaxim Sobolev 		case 'H':
201*298a392eSIhor Antonov 			state.log_reopen = true;
2024cd407ecSMaxim Sobolev 			break;
20353d49b37SJilles Tjoelker 		case 'l':
204*298a392eSIhor Antonov 			state.syslog_facility = get_log_mapping(optarg,
20539ea4280SIhor Antonov 			    facilitynames);
206*298a392eSIhor Antonov 			if (state.syslog_facility == -1) {
20753d49b37SJilles Tjoelker 				errx(5, "unrecognized syslog facility");
2086b4ef4b1SIhor Antonov 			}
209*298a392eSIhor Antonov 			state.syslog_enabled = true;
210*298a392eSIhor Antonov 			state.supervision_enabled = true;
21153d49b37SJilles Tjoelker 			break;
21253d49b37SJilles Tjoelker 		case 'm':
213*298a392eSIhor Antonov 			state.stdmask = strtol(optarg, &p, 10);
214*298a392eSIhor Antonov 			if (p == optarg || state.stdmask < 0 || state.stdmask > 3) {
21553d49b37SJilles Tjoelker 				errx(6, "unrecognized listening mask");
2166b4ef4b1SIhor Antonov 			}
21753d49b37SJilles Tjoelker 			break;
21853d49b37SJilles Tjoelker 		case 'o':
219*298a392eSIhor Antonov 			state.output_filename = optarg;
220f907027bSIhor Antonov 			/*
221f907027bSIhor Antonov 			 * TODO: setting output filename doesn't have to turn
222f907027bSIhor Antonov 			 * the supervision mode on. For non-supervised mode
223f907027bSIhor Antonov 			 * daemon could open the specified file and set it's
224f907027bSIhor Antonov 			 * descriptor as both stderr and stout before execve()
225f907027bSIhor Antonov 			 */
226*298a392eSIhor Antonov 			state.supervision_enabled = true;
22753d49b37SJilles Tjoelker 			break;
228846be7bdSPoul-Henning Kamp 		case 'p':
229*298a392eSIhor Antonov 			state.child_pidfile = optarg;
230*298a392eSIhor Antonov 			state.supervision_enabled = true;
231846be7bdSPoul-Henning Kamp 			break;
23232b17786SJohn-Mark Gurney 		case 'P':
233*298a392eSIhor Antonov 			state.parent_pidfile = optarg;
234*298a392eSIhor Antonov 			state.supervision_enabled = true;
23532b17786SJohn-Mark Gurney 			break;
236b6193c24SMikolaj Golub 		case 'r':
237*298a392eSIhor Antonov 			state.restart_enabled = true;
238*298a392eSIhor Antonov 			state.supervision_enabled = true;
239b6193c24SMikolaj Golub 			break;
24037820b87SIan Lepore 		case 'R':
241*298a392eSIhor Antonov 			state.restart_enabled = true;
242*298a392eSIhor Antonov 			state.restart_delay = strtol(optarg, &p, 0);
243*298a392eSIhor Antonov 			if (p == optarg || state.restart_delay < 1) {
24437820b87SIan Lepore 				errx(6, "invalid restart delay");
2456b4ef4b1SIhor Antonov 			}
24637820b87SIan Lepore 			break;
24753d49b37SJilles Tjoelker 		case 's':
248*298a392eSIhor Antonov 			state.syslog_priority = get_log_mapping(optarg,
24939ea4280SIhor Antonov 			    prioritynames);
250*298a392eSIhor Antonov 			if (state.syslog_priority == -1) {
25153d49b37SJilles Tjoelker 				errx(4, "unrecognized syslog priority");
2526b4ef4b1SIhor Antonov 			}
253*298a392eSIhor Antonov 			state.syslog_enabled = true;
254*298a392eSIhor Antonov 			state.supervision_enabled = true;
25553d49b37SJilles Tjoelker 			break;
25653d49b37SJilles Tjoelker 		case 'S':
257*298a392eSIhor Antonov 			state.syslog_enabled = true;
258*298a392eSIhor Antonov 			state.supervision_enabled = true;
25953d49b37SJilles Tjoelker 			break;
260112bfcf5SConrad Meyer 		case 't':
261*298a392eSIhor Antonov 			state.title = optarg;
262112bfcf5SConrad Meyer 			break;
26353d49b37SJilles Tjoelker 		case 'T':
264*298a392eSIhor Antonov 			state.syslog_tag = optarg;
265*298a392eSIhor Antonov 			state.syslog_enabled = true;
266*298a392eSIhor Antonov 			state.supervision_enabled = true;
26753d49b37SJilles Tjoelker 			break;
268e6d4b388STom Rhodes 		case 'u':
269*298a392eSIhor Antonov 			state.user = optarg;
270e6d4b388STom Rhodes 			break;
2710a402ad2SIhor Antonov 		case 'h':
2720a402ad2SIhor Antonov 			usage(0);
2730a402ad2SIhor Antonov 			__builtin_unreachable();
274bd06a3ecSMike Barcroft 		default:
2750a402ad2SIhor Antonov 			usage(1);
276bd06a3ecSMike Barcroft 		}
277bd06a3ecSMike Barcroft 	}
278bd06a3ecSMike Barcroft 	argc -= optind;
279bd06a3ecSMike Barcroft 	argv += optind;
280bd06a3ecSMike Barcroft 
2816b4ef4b1SIhor Antonov 	if (argc == 0) {
2820a402ad2SIhor Antonov 		usage(1);
2836b4ef4b1SIhor Antonov 	}
28412d7249eSTom Rhodes 
285*298a392eSIhor Antonov 	if (!state.title) {
286*298a392eSIhor Antonov 		state.title = argv[0];
2876b4ef4b1SIhor Antonov 	}
28853d49b37SJilles Tjoelker 
289*298a392eSIhor Antonov 	if (state.output_filename) {
290*298a392eSIhor Antonov 		state.output_fd = open_log(state.output_filename);
291*298a392eSIhor Antonov 		if (state.output_fd == -1) {
29253d49b37SJilles Tjoelker 			err(7, "open");
29353d49b37SJilles Tjoelker 		}
2946b4ef4b1SIhor Antonov 	}
29553d49b37SJilles Tjoelker 
296*298a392eSIhor Antonov 	if (state.syslog_enabled) {
297*298a392eSIhor Antonov 		openlog(state.syslog_tag, LOG_PID | LOG_NDELAY,
298*298a392eSIhor Antonov 		    state.syslog_facility);
2996b4ef4b1SIhor Antonov 	}
30053d49b37SJilles Tjoelker 
301846be7bdSPoul-Henning Kamp 	/*
302846be7bdSPoul-Henning Kamp 	 * Try to open the pidfile before calling daemon(3),
303846be7bdSPoul-Henning Kamp 	 * to be able to report the error intelligently
304846be7bdSPoul-Henning Kamp 	 */
305*298a392eSIhor Antonov 	open_pid_files(&state);
306*298a392eSIhor Antonov 	if (daemon(state.keep_cur_workdir, state.keep_fds_open) == -1) {
3079da0ef13SMikolaj Golub 		warn("daemon");
3089da0ef13SMikolaj Golub 		goto exit;
3099da0ef13SMikolaj Golub 	}
3109da0ef13SMikolaj Golub 	/* Write out parent pidfile if needed. */
311*298a392eSIhor Antonov 	pidfile_write(state.parent_pidfh);
312203df05bSIhor Antonov 
313*298a392eSIhor Antonov 	if (state.supervision_enabled) {
314259ed21dSIhor Antonov 		struct sigaction act_term = { 0 };
315259ed21dSIhor Antonov 		struct sigaction act_chld = { 0 };
316259ed21dSIhor Antonov 		struct sigaction act_hup = { 0 };
31753d49b37SJilles Tjoelker 
31853d49b37SJilles Tjoelker 		/* Avoid PID racing with SIGCHLD and SIGTERM. */
31953d49b37SJilles Tjoelker 		act_term.sa_handler = handle_term;
32053d49b37SJilles Tjoelker 		sigemptyset(&act_term.sa_mask);
32153d49b37SJilles Tjoelker 		sigaddset(&act_term.sa_mask, SIGCHLD);
32253d49b37SJilles Tjoelker 
32353d49b37SJilles Tjoelker 		act_chld.sa_handler = handle_chld;
32453d49b37SJilles Tjoelker 		sigemptyset(&act_chld.sa_mask);
32553d49b37SJilles Tjoelker 		sigaddset(&act_chld.sa_mask, SIGTERM);
32653d49b37SJilles Tjoelker 
3274cd407ecSMaxim Sobolev 		act_hup.sa_handler = handle_hup;
3284cd407ecSMaxim Sobolev 		sigemptyset(&act_hup.sa_mask);
3294cd407ecSMaxim Sobolev 
33053d49b37SJilles Tjoelker 		/* Block these when avoiding racing before sigsuspend(). */
33153d49b37SJilles Tjoelker 		sigaddset(&mask_susp, SIGTERM);
33253d49b37SJilles Tjoelker 		sigaddset(&mask_susp, SIGCHLD);
33353d49b37SJilles Tjoelker 		/* Block SIGTERM when we lack a valid child PID. */
33453d49b37SJilles Tjoelker 		sigaddset(&mask_term, SIGTERM);
3352ad43027SMikolaj Golub 		/*
33653d49b37SJilles Tjoelker 		 * When reading, we wish to avoid SIGCHLD. SIGTERM
33753d49b37SJilles Tjoelker 		 * has to be caught, otherwise we'll be stuck until
33853d49b37SJilles Tjoelker 		 * the read() returns - if it returns.
339195fc497SMikolaj Golub 		 */
34053d49b37SJilles Tjoelker 		sigaddset(&mask_read, SIGCHLD);
34153d49b37SJilles Tjoelker 		/* Block SIGTERM to avoid racing until we have forked. */
34253d49b37SJilles Tjoelker 		if (sigprocmask(SIG_BLOCK, &mask_term, &mask_orig)) {
3439da0ef13SMikolaj Golub 			warn("sigprocmask");
3449da0ef13SMikolaj Golub 			goto exit;
3459da0ef13SMikolaj Golub 		}
34653d49b37SJilles Tjoelker 		if (sigaction(SIGTERM, &act_term, NULL) == -1) {
34753d49b37SJilles Tjoelker 			warn("sigaction");
34853d49b37SJilles Tjoelker 			goto exit;
34953d49b37SJilles Tjoelker 		}
35053d49b37SJilles Tjoelker 		if (sigaction(SIGCHLD, &act_chld, NULL) == -1) {
35153d49b37SJilles Tjoelker 			warn("sigaction");
35253d49b37SJilles Tjoelker 			goto exit;
35353d49b37SJilles Tjoelker 		}
35453c49998SMikolaj Golub 		/*
35553c49998SMikolaj Golub 		 * Try to protect against pageout kill. Ignore the
35653c49998SMikolaj Golub 		 * error, madvise(2) will fail only if a process does
35753c49998SMikolaj Golub 		 * not have superuser privileges.
35853c49998SMikolaj Golub 		 */
35953c49998SMikolaj Golub 		(void)madvise(NULL, 0, MADV_PROTECT);
360*298a392eSIhor Antonov 		if (state.log_reopen && state.output_fd >= 0 &&
3614cd407ecSMaxim Sobolev 		    sigaction(SIGHUP, &act_hup, NULL) == -1) {
3624cd407ecSMaxim Sobolev 			warn("sigaction");
3634cd407ecSMaxim Sobolev 			goto exit;
3644cd407ecSMaxim Sobolev 		}
365b6193c24SMikolaj Golub restart:
366*298a392eSIhor Antonov 		if (pipe(state.pipe_fd)) {
36753d49b37SJilles Tjoelker 			err(1, "pipe");
3686b4ef4b1SIhor Antonov 		}
369195fc497SMikolaj Golub 		/*
37053d49b37SJilles Tjoelker 		 * Spawn a child to exec the command.
3712ad43027SMikolaj Golub 		 */
37253d49b37SJilles Tjoelker 		child_gone = 0;
3732ad43027SMikolaj Golub 		pid = fork();
37475f61ca9SIhor Antonov 	}
37575f61ca9SIhor Antonov 
37675f61ca9SIhor Antonov 	/* fork failed, this can only happen when supervision is enabled */
3772ad43027SMikolaj Golub 	if (pid == -1) {
3789da0ef13SMikolaj Golub 		warn("fork");
3799da0ef13SMikolaj Golub 		goto exit;
38053d49b37SJilles Tjoelker 	}
38175f61ca9SIhor Antonov 
38275f61ca9SIhor Antonov 
38375f61ca9SIhor Antonov 	/* fork succeeded, this is child's branch or supervision is disabled */
38475f61ca9SIhor Antonov 	if (pid == 0) {
385*298a392eSIhor Antonov 		pidfile_write(state.child_pidfh);
386846be7bdSPoul-Henning Kamp 
387*298a392eSIhor Antonov 		if (state.user != NULL) {
388*298a392eSIhor Antonov 			restrict_process(state.user);
3896b4ef4b1SIhor Antonov 		}
39053d49b37SJilles Tjoelker 		/*
39175f61ca9SIhor Antonov 		 * In supervision mode, the child gets the original sigmask,
39253d49b37SJilles Tjoelker 		 * and dup'd pipes.
39353d49b37SJilles Tjoelker 		 */
394*298a392eSIhor Antonov 		if (state.supervision_enabled) {
395*298a392eSIhor Antonov 			close(state.pipe_fd[0]);
3966b4ef4b1SIhor Antonov 			if (sigprocmask(SIG_SETMASK, &mask_orig, NULL)) {
39753d49b37SJilles Tjoelker 				err(1, "sigprogmask");
3986b4ef4b1SIhor Antonov 			}
399*298a392eSIhor Antonov 			if (state.stdmask & STDERR_FILENO) {
400*298a392eSIhor Antonov 				if (dup2(state.pipe_fd[1], STDERR_FILENO) == -1) {
40153d49b37SJilles Tjoelker 					err(1, "dup2");
40253d49b37SJilles Tjoelker 				}
4036b4ef4b1SIhor Antonov 			}
404*298a392eSIhor Antonov 			if (state.stdmask & STDOUT_FILENO) {
405*298a392eSIhor Antonov 				if (dup2(state.pipe_fd[1], STDOUT_FILENO) == -1) {
40653d49b37SJilles Tjoelker 					err(1, "dup2");
40753d49b37SJilles Tjoelker 				}
4086b4ef4b1SIhor Antonov 			}
409*298a392eSIhor Antonov 			if (state.pipe_fd[1] != STDERR_FILENO &&
410*298a392eSIhor Antonov 			    state.pipe_fd[1] != STDOUT_FILENO) {
411*298a392eSIhor Antonov 				close(state.pipe_fd[1]);
41253d49b37SJilles Tjoelker 			}
4136b4ef4b1SIhor Antonov 		}
414bd06a3ecSMike Barcroft 		execvp(argv[0], argv);
41575f61ca9SIhor Antonov 		/* execvp() failed - report error and exit this process */
4162ad43027SMikolaj Golub 		err(1, "%s", argv[0]);
4172ad43027SMikolaj Golub 	}
41875f61ca9SIhor Antonov 
41975f61ca9SIhor Antonov 	/*
42075f61ca9SIhor Antonov 	 * else: pid > 0
42175f61ca9SIhor Antonov 	 * fork succeeded, this is the parent branch, this can only happen when
42275f61ca9SIhor Antonov 	 * supervision is enabled
42375f61ca9SIhor Antonov 	 *
42475f61ca9SIhor Antonov 	 * Unblock SIGTERM after we know we have a valid child PID to signal.
42575f61ca9SIhor Antonov 	 */
42675f61ca9SIhor Antonov 	if (sigprocmask(SIG_UNBLOCK, &mask_term, NULL)) {
42775f61ca9SIhor Antonov 		warn("sigprocmask");
42875f61ca9SIhor Antonov 		goto exit;
42975f61ca9SIhor Antonov 	}
430*298a392eSIhor Antonov 	close(state.pipe_fd[1]);
431*298a392eSIhor Antonov 	state.pipe_fd[1] = -1;
43275f61ca9SIhor Antonov 
433*298a392eSIhor Antonov 	setproctitle("%s[%d]", state.title, (int)pid);
43453d49b37SJilles Tjoelker 	/*
43553d49b37SJilles Tjoelker 	 * As we have closed the write end of pipe for parent process,
43653d49b37SJilles Tjoelker 	 * we might detect the child's exit by reading EOF. The child
43753d49b37SJilles Tjoelker 	 * might have closed its stdout and stderr, so we must wait for
43853d49b37SJilles Tjoelker 	 * the SIGCHLD to ensure that the process is actually gone.
43953d49b37SJilles Tjoelker 	 */
44053d49b37SJilles Tjoelker 	for (;;) {
44153d49b37SJilles Tjoelker 		/*
44253d49b37SJilles Tjoelker 		 * We block SIGCHLD when listening, but SIGTERM we accept
44353d49b37SJilles Tjoelker 		 * so the read() won't block if we wish to depart.
44453d49b37SJilles Tjoelker 		 *
44553d49b37SJilles Tjoelker 		 * Upon receiving SIGTERM, we have several options after
44653d49b37SJilles Tjoelker 		 * sending the SIGTERM to our child:
44753d49b37SJilles Tjoelker 		 * - read until EOF
44853d49b37SJilles Tjoelker 		 * - read until EOF but only for a while
44953d49b37SJilles Tjoelker 		 * - bail immediately
45053d49b37SJilles Tjoelker 		 *
45153d49b37SJilles Tjoelker 		 * We go for the third, as otherwise we have no guarantee
45253d49b37SJilles Tjoelker 		 * that we won't block indefinitely if the child refuses
45353d49b37SJilles Tjoelker 		 * to depart. To handle the second option, a different
45453d49b37SJilles Tjoelker 		 * approach would be needed (procctl()?)
45553d49b37SJilles Tjoelker 		 */
456*298a392eSIhor Antonov 		if (child_gone && state.child_eof) {
45753d49b37SJilles Tjoelker 			break;
458cd1e6e70SIhor Antonov 		}
459cd1e6e70SIhor Antonov 
460cd1e6e70SIhor Antonov 		if (terminate) {
46153d49b37SJilles Tjoelker 			goto exit;
46253d49b37SJilles Tjoelker 		}
463cd1e6e70SIhor Antonov 
464*298a392eSIhor Antonov 		if (state.child_eof) {
46553d49b37SJilles Tjoelker 			if (sigprocmask(SIG_BLOCK, &mask_susp, NULL)) {
46653d49b37SJilles Tjoelker 				warn("sigprocmask");
46753d49b37SJilles Tjoelker 				goto exit;
46853d49b37SJilles Tjoelker 			}
469d6c398d8SIhor Antonov 			while (!terminate && !child_gone) {
47053d49b37SJilles Tjoelker 				sigsuspend(&mask_orig);
471d6c398d8SIhor Antonov 			}
47253d49b37SJilles Tjoelker 			if (sigprocmask(SIG_UNBLOCK, &mask_susp, NULL)) {
47353d49b37SJilles Tjoelker 				warn("sigprocmask");
47453d49b37SJilles Tjoelker 				goto exit;
47553d49b37SJilles Tjoelker 			}
476cd1e6e70SIhor Antonov 			continue;
47753d49b37SJilles Tjoelker 		}
478cd1e6e70SIhor Antonov 
479cd1e6e70SIhor Antonov 		if (sigprocmask(SIG_BLOCK, &mask_read, NULL)) {
480cd1e6e70SIhor Antonov 			warn("sigprocmask");
481cd1e6e70SIhor Antonov 			goto exit;
482cd1e6e70SIhor Antonov 		}
483cd1e6e70SIhor Antonov 
484*298a392eSIhor Antonov 		state.child_eof = !listen_child(state.pipe_fd[0], &state);
485cd1e6e70SIhor Antonov 
486cd1e6e70SIhor Antonov 		if (sigprocmask(SIG_UNBLOCK, &mask_read, NULL)) {
487cd1e6e70SIhor Antonov 			warn("sigprocmask");
488cd1e6e70SIhor Antonov 			goto exit;
489cd1e6e70SIhor Antonov 		}
490cd1e6e70SIhor Antonov 
49153d49b37SJilles Tjoelker 	}
492*298a392eSIhor Antonov 	if (state.restart_enabled && !terminate) {
493*298a392eSIhor Antonov 		daemon_sleep(state.restart_delay, 0);
4946b4ef4b1SIhor Antonov 	}
49553d49b37SJilles Tjoelker 	if (sigprocmask(SIG_BLOCK, &mask_term, NULL)) {
49653d49b37SJilles Tjoelker 		warn("sigprocmask");
49753d49b37SJilles Tjoelker 		goto exit;
49853d49b37SJilles Tjoelker 	}
499*298a392eSIhor Antonov 	if (state.restart_enabled && !terminate) {
500*298a392eSIhor Antonov 		close(state.pipe_fd[0]);
501*298a392eSIhor Antonov 		state.pipe_fd[0] = -1;
502b6193c24SMikolaj Golub 		goto restart;
503b6193c24SMikolaj Golub 	}
5049da0ef13SMikolaj Golub exit:
505*298a392eSIhor Antonov 	close(state.output_fd);
506*298a392eSIhor Antonov 	close(state.pipe_fd[0]);
507*298a392eSIhor Antonov 	close(state.pipe_fd[1]);
508*298a392eSIhor Antonov 	if (state.syslog_enabled) {
50953d49b37SJilles Tjoelker 		closelog();
5106b4ef4b1SIhor Antonov 	}
511*298a392eSIhor Antonov 	pidfile_remove(state.child_pidfh);
512*298a392eSIhor Antonov 	pidfile_remove(state.parent_pidfh);
5139da0ef13SMikolaj Golub 	exit(1); /* If daemon(3) succeeded exit status does not matter. */
514bd06a3ecSMike Barcroft }
515bd06a3ecSMike Barcroft 
516bd06a3ecSMike Barcroft static void
51753d49b37SJilles Tjoelker daemon_sleep(time_t secs, long nsecs)
518195fc497SMikolaj Golub {
51953d49b37SJilles Tjoelker 	struct timespec ts = { secs, nsecs };
52009a3675dSConrad Meyer 
52109a3675dSConrad Meyer 	while (!terminate && nanosleep(&ts, &ts) == -1) {
5226b4ef4b1SIhor Antonov 		if (errno != EINTR) {
52353d49b37SJilles Tjoelker 			err(1, "nanosleep");
52453d49b37SJilles Tjoelker 		}
52553d49b37SJilles Tjoelker 	}
5266b4ef4b1SIhor Antonov }
52753d49b37SJilles Tjoelker 
52853d49b37SJilles Tjoelker static void
529*298a392eSIhor Antonov open_pid_files(struct daemon_state *state)
53053d49b37SJilles Tjoelker {
53153d49b37SJilles Tjoelker 	pid_t fpid;
53253d49b37SJilles Tjoelker 	int serrno;
53353d49b37SJilles Tjoelker 
534*298a392eSIhor Antonov 	if (state->child_pidfile) {
535*298a392eSIhor Antonov 		state->child_pidfh = pidfile_open(state->child_pidfile, 0600, &fpid);
536*298a392eSIhor Antonov 		if (state->child_pidfh == NULL) {
53753d49b37SJilles Tjoelker 			if (errno == EEXIST) {
53853d49b37SJilles Tjoelker 				errx(3, "process already running, pid: %d",
53953d49b37SJilles Tjoelker 				    fpid);
54053d49b37SJilles Tjoelker 			}
541*298a392eSIhor Antonov 			err(2, "pidfile ``%s''", state->child_pidfile);
54253d49b37SJilles Tjoelker 		}
54353d49b37SJilles Tjoelker 	}
54453d49b37SJilles Tjoelker 	/* Do the same for the actual daemon process. */
545*298a392eSIhor Antonov 	if (state->parent_pidfile) {
546*298a392eSIhor Antonov 		state->parent_pidfh= pidfile_open(state->parent_pidfile, 0600, &fpid);
547*298a392eSIhor Antonov 		if (state->parent_pidfh == NULL) {
54853d49b37SJilles Tjoelker 			serrno = errno;
549*298a392eSIhor Antonov 			pidfile_remove(state->child_pidfh);
55053d49b37SJilles Tjoelker 			errno = serrno;
55153d49b37SJilles Tjoelker 			if (errno == EEXIST) {
55253d49b37SJilles Tjoelker 				errx(3, "process already running, pid: %d",
55353d49b37SJilles Tjoelker 				     fpid);
55453d49b37SJilles Tjoelker 			}
555*298a392eSIhor Antonov 			err(2, "ppidfile ``%s''", state->parent_pidfile);
55653d49b37SJilles Tjoelker 		}
55753d49b37SJilles Tjoelker 	}
55853d49b37SJilles Tjoelker }
55953d49b37SJilles Tjoelker 
56053d49b37SJilles Tjoelker static int
56153d49b37SJilles Tjoelker get_log_mapping(const char *str, const CODE *c)
56253d49b37SJilles Tjoelker {
56353d49b37SJilles Tjoelker 	const CODE *cp;
56453d49b37SJilles Tjoelker 	for (cp = c; cp->c_name; cp++)
5656b4ef4b1SIhor Antonov 		if (strcmp(cp->c_name, str) == 0) {
56653d49b37SJilles Tjoelker 			return cp->c_val;
5676b4ef4b1SIhor Antonov 		}
56853d49b37SJilles Tjoelker 	return -1;
569195fc497SMikolaj Golub }
570195fc497SMikolaj Golub 
571195fc497SMikolaj Golub static void
572e6d4b388STom Rhodes restrict_process(const char *user)
57312d7249eSTom Rhodes {
57412d7249eSTom Rhodes 	struct passwd *pw = NULL;
57512d7249eSTom Rhodes 
576e6d4b388STom Rhodes 	pw = getpwnam(user);
5776b4ef4b1SIhor Antonov 	if (pw == NULL) {
578e6d4b388STom Rhodes 		errx(1, "unknown user: %s", user);
5796b4ef4b1SIhor Antonov 	}
58012d7249eSTom Rhodes 
5816b4ef4b1SIhor Antonov 	if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0) {
582e6d4b388STom Rhodes 		errx(1, "failed to set user environment");
5836b4ef4b1SIhor Antonov 	}
5846b3ad1d7SMaxim Sobolev 
5856b3ad1d7SMaxim Sobolev 	setenv("USER", pw->pw_name, 1);
5866b3ad1d7SMaxim Sobolev 	setenv("HOME", pw->pw_dir, 1);
5876b3ad1d7SMaxim Sobolev 	setenv("SHELL", *pw->pw_shell ? pw->pw_shell : _PATH_BSHELL, 1);
58812d7249eSTom Rhodes }
58912d7249eSTom Rhodes 
59053d49b37SJilles Tjoelker /*
59153d49b37SJilles Tjoelker  * We try to collect whole lines terminated by '\n'. Otherwise we collect a
59253d49b37SJilles Tjoelker  * full buffer, and then output it.
59353d49b37SJilles Tjoelker  *
594bc43a9a7SIhor Antonov  * Return value of false is assumed to mean EOF or error, and true indicates to
59553d49b37SJilles Tjoelker  * continue reading.
59653d49b37SJilles Tjoelker  */
597bc43a9a7SIhor Antonov static bool
598*298a392eSIhor Antonov listen_child(int fd, struct daemon_state *state)
5992ad43027SMikolaj Golub {
60053d49b37SJilles Tjoelker 	static unsigned char buf[LBUF_SIZE];
60153d49b37SJilles Tjoelker 	static size_t bytes_read = 0;
60253d49b37SJilles Tjoelker 	int rv;
6032ad43027SMikolaj Golub 
604*298a392eSIhor Antonov 	assert(state);
60553d49b37SJilles Tjoelker 	assert(bytes_read < LBUF_SIZE - 1);
60653d49b37SJilles Tjoelker 
6076b4ef4b1SIhor Antonov 	if (do_log_reopen) {
608*298a392eSIhor Antonov 		reopen_log(state);
6096b4ef4b1SIhor Antonov 	}
61053d49b37SJilles Tjoelker 	rv = read(fd, buf + bytes_read, LBUF_SIZE - bytes_read - 1);
61153d49b37SJilles Tjoelker 	if (rv > 0) {
61253d49b37SJilles Tjoelker 		unsigned char *cp;
61353d49b37SJilles Tjoelker 
61453d49b37SJilles Tjoelker 		bytes_read += rv;
61553d49b37SJilles Tjoelker 		assert(bytes_read <= LBUF_SIZE - 1);
61653d49b37SJilles Tjoelker 		/* Always NUL-terminate just in case. */
61753d49b37SJilles Tjoelker 		buf[LBUF_SIZE - 1] = '\0';
61853d49b37SJilles Tjoelker 		/*
61953d49b37SJilles Tjoelker 		 * Chomp line by line until we run out of buffer.
62053d49b37SJilles Tjoelker 		 * This does not take NUL characters into account.
62153d49b37SJilles Tjoelker 		 */
62253d49b37SJilles Tjoelker 		while ((cp = memchr(buf, '\n', bytes_read)) != NULL) {
62353d49b37SJilles Tjoelker 			size_t bytes_line = cp - buf + 1;
62453d49b37SJilles Tjoelker 			assert(bytes_line <= bytes_read);
625*298a392eSIhor Antonov 			do_output(buf, bytes_line, state);
62653d49b37SJilles Tjoelker 			bytes_read -= bytes_line;
62753d49b37SJilles Tjoelker 			memmove(buf, cp + 1, bytes_read);
628195fc497SMikolaj Golub 		}
62953d49b37SJilles Tjoelker 		/* Wait until the buffer is full. */
6306b4ef4b1SIhor Antonov 		if (bytes_read < LBUF_SIZE - 1) {
631bc43a9a7SIhor Antonov 			return true;
6326b4ef4b1SIhor Antonov 		}
633*298a392eSIhor Antonov 		do_output(buf, bytes_read, state);
63453d49b37SJilles Tjoelker 		bytes_read = 0;
635bc43a9a7SIhor Antonov 		return true;
63653d49b37SJilles Tjoelker 	} else if (rv == -1) {
63753d49b37SJilles Tjoelker 		/* EINTR should trigger another read. */
63853d49b37SJilles Tjoelker 		if (errno == EINTR) {
639bc43a9a7SIhor Antonov 			return true;
64053d49b37SJilles Tjoelker 		} else {
64153d49b37SJilles Tjoelker 			warn("read");
642bc43a9a7SIhor Antonov 			return false;
643c60d51f9SMikolaj Golub 		}
64453d49b37SJilles Tjoelker 	}
64553d49b37SJilles Tjoelker 	/* Upon EOF, we have to flush what's left of the buffer. */
64653d49b37SJilles Tjoelker 	if (bytes_read > 0) {
647*298a392eSIhor Antonov 		do_output(buf, bytes_read, state);
64853d49b37SJilles Tjoelker 		bytes_read = 0;
64953d49b37SJilles Tjoelker 	}
650bc43a9a7SIhor Antonov 	return false;
65153d49b37SJilles Tjoelker }
65253d49b37SJilles Tjoelker 
65353d49b37SJilles Tjoelker /*
65453d49b37SJilles Tjoelker  * The default behavior is to stay silent if the user wants to redirect
65553d49b37SJilles Tjoelker  * output to a file and/or syslog. If neither are provided, then we bounce
65653d49b37SJilles Tjoelker  * everything back to parent's stdout.
65753d49b37SJilles Tjoelker  */
65853d49b37SJilles Tjoelker static void
659*298a392eSIhor Antonov do_output(const unsigned char *buf, size_t len, struct daemon_state *state)
66053d49b37SJilles Tjoelker {
66153d49b37SJilles Tjoelker 	assert(len <= LBUF_SIZE);
662*298a392eSIhor Antonov 	assert(state);
66353d49b37SJilles Tjoelker 
6646b4ef4b1SIhor Antonov 	if (len < 1) {
66553d49b37SJilles Tjoelker 		return;
6666b4ef4b1SIhor Antonov 	}
667*298a392eSIhor Antonov 	if (state->syslog_enabled) {
668*298a392eSIhor Antonov 		syslog(state->syslog_priority, "%.*s", (int)len, buf);
6696b4ef4b1SIhor Antonov 	}
670*298a392eSIhor Antonov 	if (state->output_fd != -1) {
671*298a392eSIhor Antonov 		if (write(state->output_fd, buf, len) == -1)
67253d49b37SJilles Tjoelker 			warn("write");
67353d49b37SJilles Tjoelker 	}
674*298a392eSIhor Antonov 	if (state->keep_fds_open &&
675*298a392eSIhor Antonov 	    !state->syslog_enabled &&
676*298a392eSIhor Antonov 	    state->output_fd == -1) {
67753d49b37SJilles Tjoelker 		printf("%.*s", (int)len, buf);
67853d49b37SJilles Tjoelker 	}
6796b4ef4b1SIhor Antonov }
68053d49b37SJilles Tjoelker 
68153d49b37SJilles Tjoelker /*
68253d49b37SJilles Tjoelker  * We use the global PID acquired directly from fork. If there is no valid
68353d49b37SJilles Tjoelker  * child pid, the handler should be blocked and/or child_gone == 1.
68453d49b37SJilles Tjoelker  */
68553d49b37SJilles Tjoelker static void
68653d49b37SJilles Tjoelker handle_term(int signo)
68753d49b37SJilles Tjoelker {
6886b4ef4b1SIhor Antonov 	if (pid > 0 && !child_gone) {
68953d49b37SJilles Tjoelker 		kill(pid, signo);
6906b4ef4b1SIhor Antonov 	}
691b6193c24SMikolaj Golub 	terminate = 1;
692195fc497SMikolaj Golub }
69353d49b37SJilles Tjoelker 
69453d49b37SJilles Tjoelker static void
6954cd407ecSMaxim Sobolev handle_chld(int signo __unused)
69653d49b37SJilles Tjoelker {
6974cd407ecSMaxim Sobolev 
69853d49b37SJilles Tjoelker 	for (;;) {
69953d49b37SJilles Tjoelker 		int rv = waitpid(-1, NULL, WNOHANG);
70053d49b37SJilles Tjoelker 		if (pid == rv) {
70153d49b37SJilles Tjoelker 			child_gone = 1;
70253d49b37SJilles Tjoelker 			break;
70353d49b37SJilles Tjoelker 		} else if (rv == -1 && errno != EINTR) {
70453d49b37SJilles Tjoelker 			warn("waitpid");
70553d49b37SJilles Tjoelker 			return;
7062ad43027SMikolaj Golub 		}
7072ad43027SMikolaj Golub 	}
7082ad43027SMikolaj Golub }
7092ad43027SMikolaj Golub 
7102ad43027SMikolaj Golub static void
7114cd407ecSMaxim Sobolev handle_hup(int signo __unused)
7124cd407ecSMaxim Sobolev {
7134cd407ecSMaxim Sobolev 
7144cd407ecSMaxim Sobolev 	do_log_reopen = 1;
7154cd407ecSMaxim Sobolev }
7164cd407ecSMaxim Sobolev 
7174cd407ecSMaxim Sobolev static int
7184cd407ecSMaxim Sobolev open_log(const char *outfn)
7194cd407ecSMaxim Sobolev {
7204cd407ecSMaxim Sobolev 
7214cd407ecSMaxim Sobolev 	return open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
7224cd407ecSMaxim Sobolev }
7234cd407ecSMaxim Sobolev 
7244cd407ecSMaxim Sobolev static void
725*298a392eSIhor Antonov reopen_log(struct daemon_state *state)
7264cd407ecSMaxim Sobolev {
7274cd407ecSMaxim Sobolev 	int outfd;
7284cd407ecSMaxim Sobolev 
7294cd407ecSMaxim Sobolev 	do_log_reopen = 0;
730*298a392eSIhor Antonov 	outfd = open_log(state->output_filename);
731*298a392eSIhor Antonov 	if (state->output_fd >= 0) {
732*298a392eSIhor Antonov 		close(state->output_fd);
7336b4ef4b1SIhor Antonov 	}
734*298a392eSIhor Antonov 	state->output_fd = outfd;
7354cd407ecSMaxim Sobolev }
7364cd407ecSMaxim Sobolev 
737*298a392eSIhor Antonov static void
738*298a392eSIhor Antonov daemon_state_init(struct daemon_state *state)
739*298a392eSIhor Antonov {
740*298a392eSIhor Antonov 	memset(state, 0, sizeof(struct daemon_state));
741*298a392eSIhor Antonov 	*state = (struct daemon_state) {
742*298a392eSIhor Antonov 		.pipe_fd = { -1, -1 },
743*298a392eSIhor Antonov 		.parent_pidfh = NULL,
744*298a392eSIhor Antonov 		.child_pidfh = NULL,
745*298a392eSIhor Antonov 		.child_pidfile = NULL,
746*298a392eSIhor Antonov 		.parent_pidfile = NULL,
747*298a392eSIhor Antonov 		.title = NULL,
748*298a392eSIhor Antonov 		.user = NULL,
749*298a392eSIhor Antonov 		.supervision_enabled = false,
750*298a392eSIhor Antonov 		.child_eof = false,
751*298a392eSIhor Antonov 		.restart_enabled = false,
752*298a392eSIhor Antonov 		.keep_cur_workdir = 1,
753*298a392eSIhor Antonov 		.restart_delay = 1,
754*298a392eSIhor Antonov 		.stdmask = STDOUT_FILENO | STDERR_FILENO,
755*298a392eSIhor Antonov 		.syslog_enabled = false,
756*298a392eSIhor Antonov 		.log_reopen = false,
757*298a392eSIhor Antonov 		.syslog_priority = LOG_NOTICE,
758*298a392eSIhor Antonov 		.syslog_tag = "daemon",
759*298a392eSIhor Antonov 		.syslog_facility = LOG_DAEMON,
760*298a392eSIhor Antonov 		.keep_fds_open = 1,
761*298a392eSIhor Antonov 		.output_fd = -1,
762*298a392eSIhor Antonov 		.output_filename = NULL,
763*298a392eSIhor Antonov 	};
764*298a392eSIhor Antonov }
765