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