2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1999 Berkeley Software Design, Inc. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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
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
30 * From BSDI: daemon.c,v 1.2 1996/08/15 01:11:09 jch Exp
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
36 #include <sys/param.h>
45 #include <login_cap.h>
60 #define LBUF_SIZE 4096
70 static void restrict_process(const char *);
71 static void handle_term(int);
72 static void handle_chld(int);
73 static void handle_hup(int);
74 static int open_log(const char *);
75 static void reopen_log(struct log_params *);
76 static int listen_child(int, struct log_params *);
77 static int get_log_mapping(const char *, const CODE *);
78 static void open_pid_files(const char *, const char *, struct pidfh **,
80 static void do_output(const unsigned char *, size_t, struct log_params *);
81 static void daemon_sleep(time_t, long);
83 static volatile sig_atomic_t terminate = 0;
84 static volatile sig_atomic_t child_gone = 0;
85 static volatile sig_atomic_t pid = -1;
86 static volatile sig_atomic_t do_log_reopen = 0;
88 static const char shortopts[] = "+cfHSp:P:ru:o:s:l:t:m:R:T:h";
90 static const struct option longopts[] = {
91 { "change-dir", no_argument, NULL, 'c' },
92 { "close-fds", no_argument, NULL, 'f' },
93 { "sighup", no_argument, NULL, 'H' },
94 { "syslog", no_argument, NULL, 'S' },
95 { "output-file", required_argument, NULL, 'o' },
96 { "output-mask", required_argument, NULL, 'm' },
97 { "child-pidfile", required_argument, NULL, 'p' },
98 { "supervisor-pidfile", required_argument, NULL, 'P' },
99 { "restart", no_argument, NULL, 'r' },
100 { "restart-delay", required_argument, NULL, 'R' },
101 { "title", required_argument, NULL, 't' },
102 { "user", required_argument, NULL, 'u' },
103 { "syslog-priority", required_argument, NULL, 's' },
104 { "syslog-facility", required_argument, NULL, 'l' },
105 { "syslog-tag", required_argument, NULL, 'T' },
106 { "help", no_argument, NULL, 'h' },
110 static _Noreturn void
113 (void)fprintf(stderr,
114 "usage: daemon [-cfHrS] [-p child_pidfile] [-P supervisor_pidfile]\n"
115 " [-u user] [-o output_file] [-t title]\n"
116 " [-l syslog_facility] [-s syslog_priority]\n"
117 " [-T syslog_tag] [-m output_mask] [-R restart_delay_secs]\n"
118 "command arguments ...\n");
120 (void)fprintf(stderr,
121 " --change-dir -c Change the current working directory to root\n"
122 " --close-fds -f Set stdin, stdout, stderr to /dev/null\n"
123 " --sighup -H Close and re-open output file on SIGHUP\n"
124 " --syslog -S Send output to syslog\n"
125 " --output-file -o <file> Append output of the child process to file\n"
126 " --output-mask -m <mask> What to send to syslog/file\n"
127 " 1=stdout, 2=stderr, 3=both\n"
128 " --child-pidfile -p <file> Write PID of the child process to file\n"
129 " --supervisor-pidfile -P <file> Write PID of the supervisor process to file\n"
130 " --restart -r Restart child if it terminates (1 sec delay)\n"
131 " --restart-delay -R <N> Restart child if it terminates after N sec\n"
132 " --title -t <title> Set the title of the supervisor process\n"
133 " --user -u <user> Drop privileges, run as given user\n"
134 " --syslog-priority -s <prio> Set syslog priority\n"
135 " --syslog-facility -l <flty> Set syslog facility\n"
136 " --syslog-tag -T <tag> Set syslog tag\n"
137 " --help -h Show this help\n");
143 main(int argc, char *argv[])
145 bool supervision_enabled = false;
146 bool syslog_enabled = false;
147 bool log_reopen = false;
149 const char *pidfile = NULL;
150 const char *logtag = "daemon";
151 const char *outfn = NULL;
152 const char *ppidfile = NULL;
153 const char *title = NULL;
154 const char *user = NULL;
157 int logfac = LOG_DAEMON;
158 int logpri = LOG_NOTICE;
162 int pfd[2] = { -1, -1 };
164 int stdmask = STDOUT_FILENO | STDERR_FILENO;
165 struct log_params logpar = { 0 };
166 struct pidfh *ppfh = NULL;
167 struct pidfh *pfh = NULL;
173 sigemptyset(&mask_susp);
174 sigemptyset(&mask_read);
175 sigemptyset(&mask_term);
176 sigemptyset(&mask_orig);
178 while ((ch = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) {
190 logfac = get_log_mapping(optarg, facilitynames);
192 errx(5, "unrecognized syslog facility");
194 syslog_enabled = true;
197 stdmask = strtol(optarg, &p, 10);
198 if (p == optarg || stdmask < 0 || stdmask > 3) {
199 errx(6, "unrecognized listening mask");
215 restart = strtol(optarg, &p, 0);
216 if (p == optarg || restart < 1) {
217 errx(6, "invalid restart delay");
221 logpri = get_log_mapping(optarg, prioritynames);
223 errx(4, "unrecognized syslog priority");
225 syslog_enabled = true;
228 syslog_enabled = true;
235 syslog_enabled = true;
242 __builtin_unreachable();
259 outfd = open_log(outfn);
265 if (syslog_enabled) {
266 openlog(logtag, LOG_PID | LOG_NDELAY, logfac);
270 * Try to open the pidfile before calling daemon(3),
271 * to be able to report the error intelligently
273 open_pid_files(pidfile, ppidfile, &pfh, &ppfh);
274 if (daemon(nochdir, noclose) == -1) {
278 /* Write out parent pidfile if needed. */
282 * Supervision mode is enabled if one of the following options are used:
284 * --supervisor-pidfile -P
285 * --restart -r / --restart-delay -R
287 * --syslog-facility -l
288 * --syslog-priority -s
291 * In supervision mode daemon executes the command in a forked process
292 * and observes the child by waiting for SIGCHILD. In supervision mode
293 * daemon must never exit before the child, this is necessary to prevent
294 * orphaning the child and leaving a stale pid file.
295 * To achieve this daemon catches SIGTERM and
296 * forwards it to the child, expecting to get SIGCHLD eventually.
298 supervision_enabled = pidfile != NULL ||
302 syslog_enabled == true;
304 if (supervision_enabled) {
305 struct sigaction act_term = { 0 };
306 struct sigaction act_chld = { 0 };
307 struct sigaction act_hup = { 0 };
309 /* Avoid PID racing with SIGCHLD and SIGTERM. */
310 act_term.sa_handler = handle_term;
311 sigemptyset(&act_term.sa_mask);
312 sigaddset(&act_term.sa_mask, SIGCHLD);
314 act_chld.sa_handler = handle_chld;
315 sigemptyset(&act_chld.sa_mask);
316 sigaddset(&act_chld.sa_mask, SIGTERM);
318 act_hup.sa_handler = handle_hup;
319 sigemptyset(&act_hup.sa_mask);
321 /* Block these when avoiding racing before sigsuspend(). */
322 sigaddset(&mask_susp, SIGTERM);
323 sigaddset(&mask_susp, SIGCHLD);
324 /* Block SIGTERM when we lack a valid child PID. */
325 sigaddset(&mask_term, SIGTERM);
327 * When reading, we wish to avoid SIGCHLD. SIGTERM
328 * has to be caught, otherwise we'll be stuck until
329 * the read() returns - if it returns.
331 sigaddset(&mask_read, SIGCHLD);
332 /* Block SIGTERM to avoid racing until we have forked. */
333 if (sigprocmask(SIG_BLOCK, &mask_term, &mask_orig)) {
337 if (sigaction(SIGTERM, &act_term, NULL) == -1) {
341 if (sigaction(SIGCHLD, &act_chld, NULL) == -1) {
346 * Try to protect against pageout kill. Ignore the
347 * error, madvise(2) will fail only if a process does
348 * not have superuser privileges.
350 (void)madvise(NULL, 0, MADV_PROTECT);
351 logpar.outfd = outfd;
352 logpar.syslog_enabled = syslog_enabled;
353 logpar.logpri = logpri;
354 logpar.noclose = noclose;
355 logpar.outfn = outfn;
356 if (log_reopen && outfd >= 0 &&
357 sigaction(SIGHUP, &act_hup, NULL) == -1) {
366 * Spawn a child to exec the command.
373 } else if (pid > 0) {
375 * Unblock SIGTERM after we know we have a valid
376 * child PID to signal.
378 if (sigprocmask(SIG_UNBLOCK, &mask_term, NULL)) {
387 /* Now that we are the child, write out the pid. */
391 restrict_process(user);
394 * When forking, the child gets the original sigmask,
399 if (sigprocmask(SIG_SETMASK, &mask_orig, NULL)) {
400 err(1, "sigprogmask");
402 if (stdmask & STDERR_FILENO) {
403 if (dup2(pfd[1], STDERR_FILENO) == -1) {
407 if (stdmask & STDOUT_FILENO) {
408 if (dup2(pfd[1], STDOUT_FILENO) == -1) {
412 if (pfd[1] != STDERR_FILENO &&
413 pfd[1] != STDOUT_FILENO) {
417 execvp(argv[0], argv);
419 * execvp() failed -- report the error. The child is
420 * now running, so the exit status doesn't matter.
422 err(1, "%s", argv[0]);
424 setproctitle("%s[%d]", title, (int)pid);
426 * As we have closed the write end of pipe for parent process,
427 * we might detect the child's exit by reading EOF. The child
428 * might have closed its stdout and stderr, so we must wait for
429 * the SIGCHLD to ensure that the process is actually gone.
433 * We block SIGCHLD when listening, but SIGTERM we accept
434 * so the read() won't block if we wish to depart.
436 * Upon receiving SIGTERM, we have several options after
437 * sending the SIGTERM to our child:
439 * - read until EOF but only for a while
442 * We go for the third, as otherwise we have no guarantee
443 * that we won't block indefinitely if the child refuses
444 * to depart. To handle the second option, a different
445 * approach would be needed (procctl()?)
447 if (child_gone && child_eof) {
449 } else if (terminate) {
451 } else if (!child_eof) {
452 if (sigprocmask(SIG_BLOCK, &mask_read, NULL)) {
456 child_eof = !listen_child(pfd[0], &logpar);
457 if (sigprocmask(SIG_UNBLOCK, &mask_read, NULL)) {
462 if (sigprocmask(SIG_BLOCK, &mask_susp, NULL)) {
466 while (!terminate && !child_gone)
467 sigsuspend(&mask_orig);
468 if (sigprocmask(SIG_UNBLOCK, &mask_susp, NULL)) {
474 if (restart && !terminate) {
475 daemon_sleep(restart, 0);
477 if (sigprocmask(SIG_BLOCK, &mask_term, NULL)) {
481 if (restart && !terminate) {
490 if (syslog_enabled) {
494 pidfile_remove(ppfh);
495 exit(1); /* If daemon(3) succeeded exit status does not matter. */
499 daemon_sleep(time_t secs, long nsecs)
501 struct timespec ts = { secs, nsecs };
503 while (!terminate && nanosleep(&ts, &ts) == -1) {
504 if (errno != EINTR) {
511 open_pid_files(const char *pidfile, const char *ppidfile,
512 struct pidfh **pfh, struct pidfh **ppfh)
518 *pfh = pidfile_open(pidfile, 0600, &fpid);
520 if (errno == EEXIST) {
521 errx(3, "process already running, pid: %d",
524 err(2, "pidfile ``%s''", pidfile);
527 /* Do the same for the actual daemon process. */
529 *ppfh = pidfile_open(ppidfile, 0600, &fpid);
532 pidfile_remove(*pfh);
534 if (errno == EEXIST) {
535 errx(3, "process already running, pid: %d",
538 err(2, "ppidfile ``%s''", ppidfile);
544 get_log_mapping(const char *str, const CODE *c)
547 for (cp = c; cp->c_name; cp++)
548 if (strcmp(cp->c_name, str) == 0) {
555 restrict_process(const char *user)
557 struct passwd *pw = NULL;
561 errx(1, "unknown user: %s", user);
564 if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0) {
565 errx(1, "failed to set user environment");
568 setenv("USER", pw->pw_name, 1);
569 setenv("HOME", pw->pw_dir, 1);
570 setenv("SHELL", *pw->pw_shell ? pw->pw_shell : _PATH_BSHELL, 1);
574 * We try to collect whole lines terminated by '\n'. Otherwise we collect a
575 * full buffer, and then output it.
577 * Return value of 0 is assumed to mean EOF or error, and 1 indicates to
581 listen_child(int fd, struct log_params *logpar)
583 static unsigned char buf[LBUF_SIZE];
584 static size_t bytes_read = 0;
588 assert(bytes_read < LBUF_SIZE - 1);
593 rv = read(fd, buf + bytes_read, LBUF_SIZE - bytes_read - 1);
598 assert(bytes_read <= LBUF_SIZE - 1);
599 /* Always NUL-terminate just in case. */
600 buf[LBUF_SIZE - 1] = '\0';
602 * Chomp line by line until we run out of buffer.
603 * This does not take NUL characters into account.
605 while ((cp = memchr(buf, '\n', bytes_read)) != NULL) {
606 size_t bytes_line = cp - buf + 1;
607 assert(bytes_line <= bytes_read);
608 do_output(buf, bytes_line, logpar);
609 bytes_read -= bytes_line;
610 memmove(buf, cp + 1, bytes_read);
612 /* Wait until the buffer is full. */
613 if (bytes_read < LBUF_SIZE - 1) {
616 do_output(buf, bytes_read, logpar);
619 } else if (rv == -1) {
620 /* EINTR should trigger another read. */
621 if (errno == EINTR) {
628 /* Upon EOF, we have to flush what's left of the buffer. */
629 if (bytes_read > 0) {
630 do_output(buf, bytes_read, logpar);
637 * The default behavior is to stay silent if the user wants to redirect
638 * output to a file and/or syslog. If neither are provided, then we bounce
639 * everything back to parent's stdout.
642 do_output(const unsigned char *buf, size_t len, struct log_params *logpar)
644 assert(len <= LBUF_SIZE);
650 if (logpar->syslog_enabled) {
651 syslog(logpar->logpri, "%.*s", (int)len, buf);
653 if (logpar->outfd != -1) {
654 if (write(logpar->outfd, buf, len) == -1)
657 if (logpar->noclose && !logpar->syslog_enabled && logpar->outfd == -1) {
658 printf("%.*s", (int)len, buf);
663 * We use the global PID acquired directly from fork. If there is no valid
664 * child pid, the handler should be blocked and/or child_gone == 1.
667 handle_term(int signo)
669 if (pid > 0 && !child_gone) {
676 handle_chld(int signo __unused)
680 int rv = waitpid(-1, NULL, WNOHANG);
684 } else if (rv == -1 && errno != EINTR) {
692 handle_hup(int signo __unused)
699 open_log(const char *outfn)
702 return open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
706 reopen_log(struct log_params *lpp)
711 outfd = open_log(lpp->outfn);
712 if (lpp->outfd >= 0) {