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