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