xref: /freebsd/usr.sbin/daemon/daemon.c (revision 4f52dfbb)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1999 Berkeley Software Design, Inc. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. Berkeley Software Design Inc's name may not be used to endorse or
15  *    promote products derived from this software without specific prior
16  *    written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  *	From BSDI: daemon.c,v 1.2 1996/08/15 01:11:09 jch Exp
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include <sys/param.h>
37 #include <sys/mman.h>
38 #include <sys/wait.h>
39 
40 #include <fcntl.h>
41 #include <err.h>
42 #include <errno.h>
43 #include <libutil.h>
44 #include <login_cap.h>
45 #include <pwd.h>
46 #include <signal.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <unistd.h>
50 #include <string.h>
51 #include <strings.h>
52 #define SYSLOG_NAMES
53 #include <syslog.h>
54 #include <time.h>
55 #include <assert.h>
56 
57 #define LBUF_SIZE 4096
58 
59 struct log_params {
60 	int dosyslog;
61 	int logpri;
62 	int noclose;
63 	int outfd;
64 };
65 
66 static void restrict_process(const char *);
67 static void handle_term(int);
68 static void handle_chld(int);
69 static int  listen_child(int, struct log_params *);
70 static int  get_log_mapping(const char *, const CODE *);
71 static void open_pid_files(const char *, const char *, struct pidfh **,
72 			   struct pidfh **);
73 static void do_output(const unsigned char *, size_t, struct log_params *);
74 static void daemon_sleep(time_t, long);
75 static void usage(void);
76 
77 static volatile sig_atomic_t terminate = 0, child_gone = 0, pid = 0;
78 
79 int
80 main(int argc, char *argv[])
81 {
82 	const char *pidfile, *ppidfile, *title, *user, *outfn, *logtag;
83 	int ch, nochdir, noclose, restart, dosyslog, child_eof;
84 	sigset_t mask_susp, mask_orig, mask_read, mask_term;
85 	struct log_params logpar;
86 	int pfd[2] = { -1, -1 }, outfd = -1;
87 	int stdmask, logpri, logfac;
88 	struct pidfh *ppfh, *pfh;
89 	char *p;
90 
91 	memset(&logpar, 0, sizeof(logpar));
92 	stdmask = STDOUT_FILENO | STDERR_FILENO;
93 	ppidfile = pidfile = user = NULL;
94 	nochdir = noclose = 1;
95 	logpri = LOG_NOTICE;
96 	logfac = LOG_DAEMON;
97 	logtag = "daemon";
98 	restart = 0;
99 	dosyslog = 0;
100 	outfn = NULL;
101 	title = NULL;
102 	while ((ch = getopt(argc, argv, "cfSp:P:ru:o:s:l:t:l:m:R:T:")) != -1) {
103 		switch (ch) {
104 		case 'c':
105 			nochdir = 0;
106 			break;
107 		case 'f':
108 			noclose = 0;
109 			break;
110 		case 'l':
111 			logfac = get_log_mapping(optarg, facilitynames);
112 			if (logfac == -1)
113 				errx(5, "unrecognized syslog facility");
114 			dosyslog = 1;
115 			break;
116 		case 'm':
117 			stdmask = strtol(optarg, &p, 10);
118 			if (p == optarg || stdmask < 0 || stdmask > 3)
119 				errx(6, "unrecognized listening mask");
120 			break;
121 		case 'o':
122 			outfn = optarg;
123 			break;
124 		case 'p':
125 			pidfile = optarg;
126 			break;
127 		case 'P':
128 			ppidfile = optarg;
129 			break;
130 		case 'r':
131 			restart = 1;
132 			break;
133 		case 'R':
134 			restart = strtol(optarg, &p, 0);
135 			if (p == optarg || restart < 1)
136 				errx(6, "invalid restart delay");
137 			break;
138 		case 's':
139 			logpri = get_log_mapping(optarg, prioritynames);
140 			if (logpri == -1)
141 				errx(4, "unrecognized syslog priority");
142 			dosyslog = 1;
143 			break;
144 		case 'S':
145 			dosyslog = 1;
146 			break;
147 		case 't':
148 			title = optarg;
149 			break;
150 		case 'T':
151 			logtag = optarg;
152 			dosyslog = 1;
153 			break;
154 		case 'u':
155 			user = optarg;
156 			break;
157 		default:
158 			usage();
159 		}
160 	}
161 	argc -= optind;
162 	argv += optind;
163 
164 	if (argc == 0)
165 		usage();
166 
167 	if (!title)
168 		title = argv[0];
169 
170 	if (outfn) {
171 		outfd = open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
172 		if (outfd == -1)
173 			err(7, "open");
174 	}
175 
176 	if (dosyslog)
177 		openlog(logtag, LOG_PID | LOG_NDELAY, logfac);
178 
179 	ppfh = pfh = NULL;
180 	/*
181 	 * Try to open the pidfile before calling daemon(3),
182 	 * to be able to report the error intelligently
183 	 */
184 	open_pid_files(pidfile, ppidfile, &pfh, &ppfh);
185 	if (daemon(nochdir, noclose) == -1) {
186 		warn("daemon");
187 		goto exit;
188 	}
189 	/* Write out parent pidfile if needed. */
190 	pidfile_write(ppfh);
191 	/*
192 	 * If the pidfile or restart option is specified the daemon
193 	 * executes the command in a forked process and wait on child
194 	 * exit to remove the pidfile or restart the command. Normally
195 	 * we don't want the monitoring daemon to be terminated
196 	 * leaving the running process and the stale pidfile, so we
197 	 * catch SIGTERM and forward it to the children expecting to
198 	 * get SIGCHLD eventually. We also must fork() to obtain a
199 	 * readable pipe with the child for writing to a log file
200 	 * and syslog.
201 	 */
202 	pid = -1;
203 	if (pidfile || ppidfile || restart || outfd != -1 || dosyslog) {
204 		struct sigaction act_term, act_chld;
205 
206 		/* Avoid PID racing with SIGCHLD and SIGTERM. */
207 		memset(&act_term, 0, sizeof(act_term));
208 		act_term.sa_handler = handle_term;
209 		sigemptyset(&act_term.sa_mask);
210 		sigaddset(&act_term.sa_mask, SIGCHLD);
211 
212 		memset(&act_chld, 0, sizeof(act_chld));
213 		act_chld.sa_handler = handle_chld;
214 		sigemptyset(&act_chld.sa_mask);
215 		sigaddset(&act_chld.sa_mask, SIGTERM);
216 
217 		/* Block these when avoiding racing before sigsuspend(). */
218 		sigemptyset(&mask_susp);
219 		sigaddset(&mask_susp, SIGTERM);
220 		sigaddset(&mask_susp, SIGCHLD);
221 		/* Block SIGTERM when we lack a valid child PID. */
222 		sigemptyset(&mask_term);
223 		sigaddset(&mask_term, SIGTERM);
224 		/*
225 		 * When reading, we wish to avoid SIGCHLD. SIGTERM
226 		 * has to be caught, otherwise we'll be stuck until
227 		 * the read() returns - if it returns.
228 		 */
229 		sigemptyset(&mask_read);
230 		sigaddset(&mask_read, SIGCHLD);
231 		/* Block SIGTERM to avoid racing until we have forked. */
232 		if (sigprocmask(SIG_BLOCK, &mask_term, &mask_orig)) {
233 			warn("sigprocmask");
234 			goto exit;
235 		}
236 		if (sigaction(SIGTERM, &act_term, NULL) == -1) {
237 			warn("sigaction");
238 			goto exit;
239 		}
240 		if (sigaction(SIGCHLD, &act_chld, NULL) == -1) {
241 			warn("sigaction");
242 			goto exit;
243 		}
244 		/*
245 		 * Try to protect against pageout kill. Ignore the
246 		 * error, madvise(2) will fail only if a process does
247 		 * not have superuser privileges.
248 		 */
249 		(void)madvise(NULL, 0, MADV_PROTECT);
250 		logpar.outfd = outfd;
251 		logpar.dosyslog = dosyslog;
252 		logpar.logpri = logpri;
253 		logpar.noclose = noclose;
254 restart:
255 		if (pipe(pfd))
256 			err(1, "pipe");
257 		/*
258 		 * Spawn a child to exec the command.
259 		 */
260 		child_gone = 0;
261 		pid = fork();
262 		if (pid == -1) {
263 			warn("fork");
264 			goto exit;
265 		} else if (pid > 0) {
266 			/*
267 			 * Unblock SIGTERM after we know we have a valid
268 			 * child PID to signal.
269 			 */
270 			if (sigprocmask(SIG_UNBLOCK, &mask_term, NULL)) {
271 				warn("sigprocmask");
272 				goto exit;
273 			}
274 			close(pfd[1]);
275 			pfd[1] = -1;
276 		}
277 	}
278 	if (pid <= 0) {
279 		/* Now that we are the child, write out the pid. */
280 		pidfile_write(pfh);
281 
282 		if (user != NULL)
283 			restrict_process(user);
284 		/*
285 		 * When forking, the child gets the original sigmask,
286 		 * and dup'd pipes.
287 		 */
288 		if (pid == 0) {
289 			close(pfd[0]);
290 			if (sigprocmask(SIG_SETMASK, &mask_orig, NULL))
291 				err(1, "sigprogmask");
292 			if (stdmask & STDERR_FILENO) {
293 				if (dup2(pfd[1], STDERR_FILENO) == -1)
294 					err(1, "dup2");
295 			}
296 			if (stdmask & STDOUT_FILENO) {
297 				if (dup2(pfd[1], STDOUT_FILENO) == -1)
298 					err(1, "dup2");
299 			}
300 			if (pfd[1] != STDERR_FILENO &&
301 			    pfd[1] != STDOUT_FILENO)
302 				close(pfd[1]);
303 		}
304 		execvp(argv[0], argv);
305 		/*
306 		 * execvp() failed -- report the error. The child is
307 		 * now running, so the exit status doesn't matter.
308 		 */
309 		err(1, "%s", argv[0]);
310 	}
311 	setproctitle("%s[%d]", title, (int)pid);
312 	/*
313 	 * As we have closed the write end of pipe for parent process,
314 	 * we might detect the child's exit by reading EOF. The child
315 	 * might have closed its stdout and stderr, so we must wait for
316 	 * the SIGCHLD to ensure that the process is actually gone.
317 	 */
318 	child_eof = 0;
319 	for (;;) {
320 		/*
321 		 * We block SIGCHLD when listening, but SIGTERM we accept
322 		 * so the read() won't block if we wish to depart.
323 		 *
324 		 * Upon receiving SIGTERM, we have several options after
325 		 * sending the SIGTERM to our child:
326 		 * - read until EOF
327 		 * - read until EOF but only for a while
328 		 * - bail immediately
329 		 *
330 		 * We go for the third, as otherwise we have no guarantee
331 		 * that we won't block indefinitely if the child refuses
332 		 * to depart. To handle the second option, a different
333 		 * approach would be needed (procctl()?)
334 		 */
335 		if (child_gone && child_eof) {
336 			break;
337 		} else if (terminate) {
338 			goto exit;
339 		} else if (!child_eof) {
340 			if (sigprocmask(SIG_BLOCK, &mask_read, NULL)) {
341 				warn("sigprocmask");
342 				goto exit;
343 			}
344 			child_eof = !listen_child(pfd[0], &logpar);
345 			if (sigprocmask(SIG_UNBLOCK, &mask_read, NULL)) {
346 				warn("sigprocmask");
347 				goto exit;
348 			}
349 		} else {
350 			if (sigprocmask(SIG_BLOCK, &mask_susp, NULL)) {
351 				warn("sigprocmask");
352 	 			goto exit;
353 			}
354 			while (!terminate && !child_gone)
355 				sigsuspend(&mask_orig);
356 			if (sigprocmask(SIG_UNBLOCK, &mask_susp, NULL)) {
357 				warn("sigprocmask");
358 				goto exit;
359 			}
360 		}
361 	}
362 	if (sigprocmask(SIG_BLOCK, &mask_term, NULL)) {
363 		warn("sigprocmask");
364 		goto exit;
365 	}
366 	if (restart && !terminate) {
367 		daemon_sleep(restart, 0);
368 		close(pfd[0]);
369 		pfd[0] = -1;
370 		goto restart;
371 	}
372 exit:
373 	close(outfd);
374 	close(pfd[0]);
375 	close(pfd[1]);
376 	if (dosyslog)
377 		closelog();
378 	pidfile_remove(pfh);
379 	pidfile_remove(ppfh);
380 	exit(1); /* If daemon(3) succeeded exit status does not matter. */
381 }
382 
383 static void
384 daemon_sleep(time_t secs, long nsecs)
385 {
386 	struct timespec ts = { secs, nsecs };
387 	while (nanosleep(&ts, &ts) == -1) {
388 		if (errno != EINTR)
389 			err(1, "nanosleep");
390 	}
391 }
392 
393 static void
394 open_pid_files(const char *pidfile, const char *ppidfile,
395 	       struct pidfh **pfh, struct pidfh **ppfh)
396 {
397 	pid_t fpid;
398 	int serrno;
399 
400 	if (pidfile) {
401 		*pfh = pidfile_open(pidfile, 0600, &fpid);
402 		if (*pfh == NULL) {
403 			if (errno == EEXIST) {
404 				errx(3, "process already running, pid: %d",
405 				    fpid);
406 			}
407 			err(2, "pidfile ``%s''", pidfile);
408 		}
409 	}
410 	/* Do the same for the actual daemon process. */
411 	if (ppidfile) {
412 		*ppfh = pidfile_open(ppidfile, 0600, &fpid);
413 		if (*ppfh == NULL) {
414 			serrno = errno;
415 			pidfile_remove(*pfh);
416 			errno = serrno;
417 			if (errno == EEXIST) {
418 				errx(3, "process already running, pid: %d",
419 				     fpid);
420 			}
421 			err(2, "ppidfile ``%s''", ppidfile);
422 		}
423 	}
424 }
425 
426 static int
427 get_log_mapping(const char *str, const CODE *c)
428 {
429 	const CODE *cp;
430 	for (cp = c; cp->c_name; cp++)
431 		if (strcmp(cp->c_name, str) == 0)
432 			return cp->c_val;
433 	return -1;
434 }
435 
436 static void
437 restrict_process(const char *user)
438 {
439 	struct passwd *pw = NULL;
440 
441 	pw = getpwnam(user);
442 	if (pw == NULL)
443 		errx(1, "unknown user: %s", user);
444 
445 	if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0)
446 		errx(1, "failed to set user environment");
447 }
448 
449 /*
450  * We try to collect whole lines terminated by '\n'. Otherwise we collect a
451  * full buffer, and then output it.
452  *
453  * Return value of 0 is assumed to mean EOF or error, and 1 indicates to
454  * continue reading.
455  */
456 static int
457 listen_child(int fd, struct log_params *logpar)
458 {
459 	static unsigned char buf[LBUF_SIZE];
460 	static size_t bytes_read = 0;
461 	int rv;
462 
463 	assert(logpar);
464 	assert(bytes_read < LBUF_SIZE - 1);
465 
466 	rv = read(fd, buf + bytes_read, LBUF_SIZE - bytes_read - 1);
467 	if (rv > 0) {
468 		unsigned char *cp;
469 
470 		bytes_read += rv;
471 		assert(bytes_read <= LBUF_SIZE - 1);
472 		/* Always NUL-terminate just in case. */
473 		buf[LBUF_SIZE - 1] = '\0';
474 		/*
475 		 * Chomp line by line until we run out of buffer.
476 		 * This does not take NUL characters into account.
477 		 */
478 		while ((cp = memchr(buf, '\n', bytes_read)) != NULL) {
479 			size_t bytes_line = cp - buf + 1;
480 			assert(bytes_line <= bytes_read);
481 			do_output(buf, bytes_line, logpar);
482 			bytes_read -= bytes_line;
483 			memmove(buf, cp + 1, bytes_read);
484 		}
485 		/* Wait until the buffer is full. */
486 		if (bytes_read < LBUF_SIZE - 1)
487 			return 1;
488 		do_output(buf, bytes_read, logpar);
489 		bytes_read = 0;
490 		return 1;
491 	} else if (rv == -1) {
492 		/* EINTR should trigger another read. */
493 		if (errno == EINTR) {
494 			return 1;
495 		} else {
496 			warn("read");
497 			return 0;
498 		}
499 	}
500 	/* Upon EOF, we have to flush what's left of the buffer. */
501 	if (bytes_read > 0) {
502 		do_output(buf, bytes_read, logpar);
503 		bytes_read = 0;
504 	}
505 	return 0;
506 }
507 
508 /*
509  * The default behavior is to stay silent if the user wants to redirect
510  * output to a file and/or syslog. If neither are provided, then we bounce
511  * everything back to parent's stdout.
512  */
513 static void
514 do_output(const unsigned char *buf, size_t len, struct log_params *logpar)
515 {
516 	assert(len <= LBUF_SIZE);
517 	assert(logpar);
518 
519 	if (len < 1)
520 		return;
521 	if (logpar->dosyslog)
522 		syslog(logpar->logpri, "%.*s", (int)len, buf);
523 	if (logpar->outfd != -1) {
524 		if (write(logpar->outfd, buf, len) == -1)
525 			warn("write");
526 	}
527 	if (logpar->noclose && !logpar->dosyslog && logpar->outfd == -1)
528 		printf("%.*s", (int)len, buf);
529 }
530 
531 /*
532  * We use the global PID acquired directly from fork. If there is no valid
533  * child pid, the handler should be blocked and/or child_gone == 1.
534  */
535 static void
536 handle_term(int signo)
537 {
538 	if (pid > 0 && !child_gone)
539 		kill(pid, signo);
540 	terminate = 1;
541 }
542 
543 static void
544 handle_chld(int signo)
545 {
546 	(void)signo;
547 	for (;;) {
548 		int rv = waitpid(-1, NULL, WNOHANG);
549 		if (pid == rv) {
550 			child_gone = 1;
551 			break;
552 		} else if (rv == -1 && errno != EINTR) {
553 			warn("waitpid");
554 			return;
555 		}
556 	}
557 }
558 
559 static void
560 usage(void)
561 {
562 	(void)fprintf(stderr,
563 	    "usage: daemon [-cfrS] [-p child_pidfile] [-P supervisor_pidfile]\n"
564 	    "              [-u user] [-o output_file] [-t title]\n"
565 	    "              [-l syslog_facility] [-s syslog_priority]\n"
566 	    "              [-T syslog_tag] [-m output_mask] [-R restart_delay_secs]\n"
567 	    "command arguments ...\n");
568 	exit(1);
569 }
570