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