xref: /freebsd/usr.sbin/daemon/daemon.c (revision 81ad6265)
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 <paths.h>
46 #include <pwd.h>
47 #include <signal.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <unistd.h>
51 #include <string.h>
52 #include <strings.h>
53 #define SYSLOG_NAMES
54 #include <syslog.h>
55 #include <time.h>
56 #include <assert.h>
57 
58 #define LBUF_SIZE 4096
59 
60 struct log_params {
61 	int dosyslog;
62 	int logpri;
63 	int noclose;
64 	int outfd;
65 	const char *outfn;
66 };
67 
68 static void restrict_process(const char *);
69 static void handle_term(int);
70 static void handle_chld(int);
71 static void handle_hup(int);
72 static int open_log(const char *);
73 static void reopen_log(struct log_params *);
74 static int  listen_child(int, struct log_params *);
75 static int  get_log_mapping(const char *, const CODE *);
76 static void open_pid_files(const char *, const char *, struct pidfh **,
77 			   struct pidfh **);
78 static void do_output(const unsigned char *, size_t, struct log_params *);
79 static void daemon_sleep(time_t, long);
80 static void usage(void);
81 
82 static volatile sig_atomic_t terminate = 0, child_gone = 0, pid = 0,
83   do_log_reopen = 0;
84 
85 int
86 main(int argc, char *argv[])
87 {
88 	const char *pidfile, *ppidfile, *title, *user, *outfn, *logtag;
89 	int ch, nochdir, noclose, restart, dosyslog, child_eof;
90 	sigset_t mask_susp, mask_orig, mask_read, mask_term;
91 	struct log_params logpar;
92 	int pfd[2] = { -1, -1 }, outfd = -1;
93 	int stdmask, logpri, logfac, log_reopen;
94 	struct pidfh *ppfh, *pfh;
95 	char *p;
96 
97 	memset(&logpar, 0, sizeof(logpar));
98 	stdmask = STDOUT_FILENO | STDERR_FILENO;
99 	ppidfile = pidfile = user = NULL;
100 	nochdir = noclose = 1;
101 	logpri = LOG_NOTICE;
102 	logfac = LOG_DAEMON;
103 	logtag = "daemon";
104 	restart = 0;
105 	dosyslog = 0;
106 	log_reopen = 0;
107 	outfn = NULL;
108 	title = NULL;
109 	while ((ch = getopt(argc, argv, "cfHSp:P:ru:o:s:l:t:l:m:R:T:")) != -1) {
110 		switch (ch) {
111 		case 'c':
112 			nochdir = 0;
113 			break;
114 		case 'f':
115 			noclose = 0;
116 			break;
117 		case 'H':
118 			log_reopen = 1;
119 			break;
120 		case 'l':
121 			logfac = get_log_mapping(optarg, facilitynames);
122 			if (logfac == -1)
123 				errx(5, "unrecognized syslog facility");
124 			dosyslog = 1;
125 			break;
126 		case 'm':
127 			stdmask = strtol(optarg, &p, 10);
128 			if (p == optarg || stdmask < 0 || stdmask > 3)
129 				errx(6, "unrecognized listening mask");
130 			break;
131 		case 'o':
132 			outfn = optarg;
133 			break;
134 		case 'p':
135 			pidfile = optarg;
136 			break;
137 		case 'P':
138 			ppidfile = optarg;
139 			break;
140 		case 'r':
141 			restart = 1;
142 			break;
143 		case 'R':
144 			restart = strtol(optarg, &p, 0);
145 			if (p == optarg || restart < 1)
146 				errx(6, "invalid restart delay");
147 			break;
148 		case 's':
149 			logpri = get_log_mapping(optarg, prioritynames);
150 			if (logpri == -1)
151 				errx(4, "unrecognized syslog priority");
152 			dosyslog = 1;
153 			break;
154 		case 'S':
155 			dosyslog = 1;
156 			break;
157 		case 't':
158 			title = optarg;
159 			break;
160 		case 'T':
161 			logtag = optarg;
162 			dosyslog = 1;
163 			break;
164 		case 'u':
165 			user = optarg;
166 			break;
167 		default:
168 			usage();
169 		}
170 	}
171 	argc -= optind;
172 	argv += optind;
173 
174 	if (argc == 0)
175 		usage();
176 
177 	if (!title)
178 		title = argv[0];
179 
180 	if (outfn) {
181 		outfd = open_log(outfn);
182 		if (outfd == -1)
183 			err(7, "open");
184 	}
185 
186 	if (dosyslog)
187 		openlog(logtag, LOG_PID | LOG_NDELAY, logfac);
188 
189 	ppfh = pfh = NULL;
190 	/*
191 	 * Try to open the pidfile before calling daemon(3),
192 	 * to be able to report the error intelligently
193 	 */
194 	open_pid_files(pidfile, ppidfile, &pfh, &ppfh);
195 	if (daemon(nochdir, noclose) == -1) {
196 		warn("daemon");
197 		goto exit;
198 	}
199 	/* Write out parent pidfile if needed. */
200 	pidfile_write(ppfh);
201 	/*
202 	 * If the pidfile or restart option is specified the daemon
203 	 * executes the command in a forked process and wait on child
204 	 * exit to remove the pidfile or restart the command. Normally
205 	 * we don't want the monitoring daemon to be terminated
206 	 * leaving the running process and the stale pidfile, so we
207 	 * catch SIGTERM and forward it to the children expecting to
208 	 * get SIGCHLD eventually. We also must fork() to obtain a
209 	 * readable pipe with the child for writing to a log file
210 	 * and syslog.
211 	 */
212 	pid = -1;
213 	if (pidfile || ppidfile || restart || outfd != -1 || dosyslog) {
214 		struct sigaction act_term, act_chld, act_hup;
215 
216 		/* Avoid PID racing with SIGCHLD and SIGTERM. */
217 		memset(&act_term, 0, sizeof(act_term));
218 		act_term.sa_handler = handle_term;
219 		sigemptyset(&act_term.sa_mask);
220 		sigaddset(&act_term.sa_mask, SIGCHLD);
221 
222 		memset(&act_chld, 0, sizeof(act_chld));
223 		act_chld.sa_handler = handle_chld;
224 		sigemptyset(&act_chld.sa_mask);
225 		sigaddset(&act_chld.sa_mask, SIGTERM);
226 
227 		memset(&act_hup, 0, sizeof(act_hup));
228 		act_hup.sa_handler = handle_hup;
229 		sigemptyset(&act_hup.sa_mask);
230 
231 		/* Block these when avoiding racing before sigsuspend(). */
232 		sigemptyset(&mask_susp);
233 		sigaddset(&mask_susp, SIGTERM);
234 		sigaddset(&mask_susp, SIGCHLD);
235 		/* Block SIGTERM when we lack a valid child PID. */
236 		sigemptyset(&mask_term);
237 		sigaddset(&mask_term, SIGTERM);
238 		/*
239 		 * When reading, we wish to avoid SIGCHLD. SIGTERM
240 		 * has to be caught, otherwise we'll be stuck until
241 		 * the read() returns - if it returns.
242 		 */
243 		sigemptyset(&mask_read);
244 		sigaddset(&mask_read, SIGCHLD);
245 		/* Block SIGTERM to avoid racing until we have forked. */
246 		if (sigprocmask(SIG_BLOCK, &mask_term, &mask_orig)) {
247 			warn("sigprocmask");
248 			goto exit;
249 		}
250 		if (sigaction(SIGTERM, &act_term, NULL) == -1) {
251 			warn("sigaction");
252 			goto exit;
253 		}
254 		if (sigaction(SIGCHLD, &act_chld, NULL) == -1) {
255 			warn("sigaction");
256 			goto exit;
257 		}
258 		/*
259 		 * Try to protect against pageout kill. Ignore the
260 		 * error, madvise(2) will fail only if a process does
261 		 * not have superuser privileges.
262 		 */
263 		(void)madvise(NULL, 0, MADV_PROTECT);
264 		logpar.outfd = outfd;
265 		logpar.dosyslog = dosyslog;
266 		logpar.logpri = logpri;
267 		logpar.noclose = noclose;
268 		logpar.outfn = outfn;
269 		if (log_reopen && outfd >= 0 &&
270 		    sigaction(SIGHUP, &act_hup, NULL) == -1) {
271 			warn("sigaction");
272 			goto exit;
273 		}
274 restart:
275 		if (pipe(pfd))
276 			err(1, "pipe");
277 		/*
278 		 * Spawn a child to exec the command.
279 		 */
280 		child_gone = 0;
281 		pid = fork();
282 		if (pid == -1) {
283 			warn("fork");
284 			goto exit;
285 		} else if (pid > 0) {
286 			/*
287 			 * Unblock SIGTERM after we know we have a valid
288 			 * child PID to signal.
289 			 */
290 			if (sigprocmask(SIG_UNBLOCK, &mask_term, NULL)) {
291 				warn("sigprocmask");
292 				goto exit;
293 			}
294 			close(pfd[1]);
295 			pfd[1] = -1;
296 		}
297 	}
298 	if (pid <= 0) {
299 		/* Now that we are the child, write out the pid. */
300 		pidfile_write(pfh);
301 
302 		if (user != NULL)
303 			restrict_process(user);
304 		/*
305 		 * When forking, the child gets the original sigmask,
306 		 * and dup'd pipes.
307 		 */
308 		if (pid == 0) {
309 			close(pfd[0]);
310 			if (sigprocmask(SIG_SETMASK, &mask_orig, NULL))
311 				err(1, "sigprogmask");
312 			if (stdmask & STDERR_FILENO) {
313 				if (dup2(pfd[1], STDERR_FILENO) == -1)
314 					err(1, "dup2");
315 			}
316 			if (stdmask & STDOUT_FILENO) {
317 				if (dup2(pfd[1], STDOUT_FILENO) == -1)
318 					err(1, "dup2");
319 			}
320 			if (pfd[1] != STDERR_FILENO &&
321 			    pfd[1] != STDOUT_FILENO)
322 				close(pfd[1]);
323 		}
324 		execvp(argv[0], argv);
325 		/*
326 		 * execvp() failed -- report the error. The child is
327 		 * now running, so the exit status doesn't matter.
328 		 */
329 		err(1, "%s", argv[0]);
330 	}
331 	setproctitle("%s[%d]", title, (int)pid);
332 	/*
333 	 * As we have closed the write end of pipe for parent process,
334 	 * we might detect the child's exit by reading EOF. The child
335 	 * might have closed its stdout and stderr, so we must wait for
336 	 * the SIGCHLD to ensure that the process is actually gone.
337 	 */
338 	child_eof = 0;
339 	for (;;) {
340 		/*
341 		 * We block SIGCHLD when listening, but SIGTERM we accept
342 		 * so the read() won't block if we wish to depart.
343 		 *
344 		 * Upon receiving SIGTERM, we have several options after
345 		 * sending the SIGTERM to our child:
346 		 * - read until EOF
347 		 * - read until EOF but only for a while
348 		 * - bail immediately
349 		 *
350 		 * We go for the third, as otherwise we have no guarantee
351 		 * that we won't block indefinitely if the child refuses
352 		 * to depart. To handle the second option, a different
353 		 * approach would be needed (procctl()?)
354 		 */
355 		if (child_gone && child_eof) {
356 			break;
357 		} else if (terminate) {
358 			goto exit;
359 		} else if (!child_eof) {
360 			if (sigprocmask(SIG_BLOCK, &mask_read, NULL)) {
361 				warn("sigprocmask");
362 				goto exit;
363 			}
364 			child_eof = !listen_child(pfd[0], &logpar);
365 			if (sigprocmask(SIG_UNBLOCK, &mask_read, NULL)) {
366 				warn("sigprocmask");
367 				goto exit;
368 			}
369 		} else {
370 			if (sigprocmask(SIG_BLOCK, &mask_susp, NULL)) {
371 				warn("sigprocmask");
372 	 			goto exit;
373 			}
374 			while (!terminate && !child_gone)
375 				sigsuspend(&mask_orig);
376 			if (sigprocmask(SIG_UNBLOCK, &mask_susp, NULL)) {
377 				warn("sigprocmask");
378 				goto exit;
379 			}
380 		}
381 	}
382 	if (restart && !terminate)
383 		daemon_sleep(restart, 0);
384 	if (sigprocmask(SIG_BLOCK, &mask_term, NULL)) {
385 		warn("sigprocmask");
386 		goto exit;
387 	}
388 	if (restart && !terminate) {
389 		close(pfd[0]);
390 		pfd[0] = -1;
391 		goto restart;
392 	}
393 exit:
394 	close(outfd);
395 	close(pfd[0]);
396 	close(pfd[1]);
397 	if (dosyslog)
398 		closelog();
399 	pidfile_remove(pfh);
400 	pidfile_remove(ppfh);
401 	exit(1); /* If daemon(3) succeeded exit status does not matter. */
402 }
403 
404 static void
405 daemon_sleep(time_t secs, long nsecs)
406 {
407 	struct timespec ts = { secs, nsecs };
408 
409 	while (!terminate && nanosleep(&ts, &ts) == -1) {
410 		if (errno != EINTR)
411 			err(1, "nanosleep");
412 	}
413 }
414 
415 static void
416 open_pid_files(const char *pidfile, const char *ppidfile,
417 	       struct pidfh **pfh, struct pidfh **ppfh)
418 {
419 	pid_t fpid;
420 	int serrno;
421 
422 	if (pidfile) {
423 		*pfh = pidfile_open(pidfile, 0600, &fpid);
424 		if (*pfh == NULL) {
425 			if (errno == EEXIST) {
426 				errx(3, "process already running, pid: %d",
427 				    fpid);
428 			}
429 			err(2, "pidfile ``%s''", pidfile);
430 		}
431 	}
432 	/* Do the same for the actual daemon process. */
433 	if (ppidfile) {
434 		*ppfh = pidfile_open(ppidfile, 0600, &fpid);
435 		if (*ppfh == NULL) {
436 			serrno = errno;
437 			pidfile_remove(*pfh);
438 			errno = serrno;
439 			if (errno == EEXIST) {
440 				errx(3, "process already running, pid: %d",
441 				     fpid);
442 			}
443 			err(2, "ppidfile ``%s''", ppidfile);
444 		}
445 	}
446 }
447 
448 static int
449 get_log_mapping(const char *str, const CODE *c)
450 {
451 	const CODE *cp;
452 	for (cp = c; cp->c_name; cp++)
453 		if (strcmp(cp->c_name, str) == 0)
454 			return cp->c_val;
455 	return -1;
456 }
457 
458 static void
459 restrict_process(const char *user)
460 {
461 	struct passwd *pw = NULL;
462 
463 	pw = getpwnam(user);
464 	if (pw == NULL)
465 		errx(1, "unknown user: %s", user);
466 
467 	if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0)
468 		errx(1, "failed to set user environment");
469 
470 	setenv("USER", pw->pw_name, 1);
471 	setenv("HOME", pw->pw_dir, 1);
472 	setenv("SHELL", *pw->pw_shell ? pw->pw_shell : _PATH_BSHELL, 1);
473 }
474 
475 /*
476  * We try to collect whole lines terminated by '\n'. Otherwise we collect a
477  * full buffer, and then output it.
478  *
479  * Return value of 0 is assumed to mean EOF or error, and 1 indicates to
480  * continue reading.
481  */
482 static int
483 listen_child(int fd, struct log_params *logpar)
484 {
485 	static unsigned char buf[LBUF_SIZE];
486 	static size_t bytes_read = 0;
487 	int rv;
488 
489 	assert(logpar);
490 	assert(bytes_read < LBUF_SIZE - 1);
491 
492 	if (do_log_reopen)
493 		reopen_log(logpar);
494 	rv = read(fd, buf + bytes_read, LBUF_SIZE - bytes_read - 1);
495 	if (rv > 0) {
496 		unsigned char *cp;
497 
498 		bytes_read += rv;
499 		assert(bytes_read <= LBUF_SIZE - 1);
500 		/* Always NUL-terminate just in case. */
501 		buf[LBUF_SIZE - 1] = '\0';
502 		/*
503 		 * Chomp line by line until we run out of buffer.
504 		 * This does not take NUL characters into account.
505 		 */
506 		while ((cp = memchr(buf, '\n', bytes_read)) != NULL) {
507 			size_t bytes_line = cp - buf + 1;
508 			assert(bytes_line <= bytes_read);
509 			do_output(buf, bytes_line, logpar);
510 			bytes_read -= bytes_line;
511 			memmove(buf, cp + 1, bytes_read);
512 		}
513 		/* Wait until the buffer is full. */
514 		if (bytes_read < LBUF_SIZE - 1)
515 			return 1;
516 		do_output(buf, bytes_read, logpar);
517 		bytes_read = 0;
518 		return 1;
519 	} else if (rv == -1) {
520 		/* EINTR should trigger another read. */
521 		if (errno == EINTR) {
522 			return 1;
523 		} else {
524 			warn("read");
525 			return 0;
526 		}
527 	}
528 	/* Upon EOF, we have to flush what's left of the buffer. */
529 	if (bytes_read > 0) {
530 		do_output(buf, bytes_read, logpar);
531 		bytes_read = 0;
532 	}
533 	return 0;
534 }
535 
536 /*
537  * The default behavior is to stay silent if the user wants to redirect
538  * output to a file and/or syslog. If neither are provided, then we bounce
539  * everything back to parent's stdout.
540  */
541 static void
542 do_output(const unsigned char *buf, size_t len, struct log_params *logpar)
543 {
544 	assert(len <= LBUF_SIZE);
545 	assert(logpar);
546 
547 	if (len < 1)
548 		return;
549 	if (logpar->dosyslog)
550 		syslog(logpar->logpri, "%.*s", (int)len, buf);
551 	if (logpar->outfd != -1) {
552 		if (write(logpar->outfd, buf, len) == -1)
553 			warn("write");
554 	}
555 	if (logpar->noclose && !logpar->dosyslog && logpar->outfd == -1)
556 		printf("%.*s", (int)len, buf);
557 }
558 
559 /*
560  * We use the global PID acquired directly from fork. If there is no valid
561  * child pid, the handler should be blocked and/or child_gone == 1.
562  */
563 static void
564 handle_term(int signo)
565 {
566 	if (pid > 0 && !child_gone)
567 		kill(pid, signo);
568 	terminate = 1;
569 }
570 
571 static void
572 handle_chld(int signo __unused)
573 {
574 
575 	for (;;) {
576 		int rv = waitpid(-1, NULL, WNOHANG);
577 		if (pid == rv) {
578 			child_gone = 1;
579 			break;
580 		} else if (rv == -1 && errno != EINTR) {
581 			warn("waitpid");
582 			return;
583 		}
584 	}
585 }
586 
587 static void
588 handle_hup(int signo __unused)
589 {
590 
591 	do_log_reopen = 1;
592 }
593 
594 static int
595 open_log(const char *outfn)
596 {
597 
598 	return open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
599 }
600 
601 static void
602 reopen_log(struct log_params *lpp)
603 {
604 	int outfd;
605 
606 	do_log_reopen = 0;
607 	outfd = open_log(lpp->outfn);
608 	if (lpp->outfd >= 0)
609 		close(lpp->outfd);
610 	lpp->outfd = outfd;
611 }
612 
613 static void
614 usage(void)
615 {
616 	(void)fprintf(stderr,
617 	    "usage: daemon [-cfHrS] [-p child_pidfile] [-P supervisor_pidfile]\n"
618 	    "              [-u user] [-o output_file] [-t title]\n"
619 	    "              [-l syslog_facility] [-s syslog_priority]\n"
620 	    "              [-T syslog_tag] [-m output_mask] [-R restart_delay_secs]\n"
621 	    "command arguments ...\n");
622 	exit(1);
623 }
624