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
64 const char *child_pidfile;
65 const char *parent_pidfile;
66 const char *output_filename;
67 const char *syslog_tag;
70 struct pidfh *parent_pidfh;
71 struct pidfh *child_pidfh;
79 bool supervision_enabled;
86 static void restrict_process(const char *);
87 static void handle_term(int);
88 static void handle_chld(int);
89 static void handle_hup(int);
90 static int open_log(const char *);
91 static void reopen_log(struct daemon_state *);
92 static bool listen_child(int, struct daemon_state *);
93 static int get_log_mapping(const char *, const CODE *);
94 static void open_pid_files(struct daemon_state *);
95 static void do_output(const unsigned char *, size_t, struct daemon_state *);
96 static void daemon_sleep(time_t, long);
97 static void daemon_state_init(struct daemon_state *);
98 static void daemon_terminate(struct daemon_state *);
100 static volatile sig_atomic_t terminate = 0;
101 static volatile sig_atomic_t child_gone = 0;
102 static volatile sig_atomic_t pid = 0;
103 static volatile sig_atomic_t do_log_reopen = 0;
105 static const char shortopts[] = "+cfHSp:P:ru:o:s:l:t:m:R:T:h";
107 static const struct option longopts[] = {
108 { "change-dir", no_argument, NULL, 'c' },
109 { "close-fds", no_argument, NULL, 'f' },
110 { "sighup", no_argument, NULL, 'H' },
111 { "syslog", no_argument, NULL, 'S' },
112 { "output-file", required_argument, NULL, 'o' },
113 { "output-mask", required_argument, NULL, 'm' },
114 { "child-pidfile", required_argument, NULL, 'p' },
115 { "supervisor-pidfile", required_argument, NULL, 'P' },
116 { "restart", no_argument, NULL, 'r' },
117 { "restart-delay", required_argument, NULL, 'R' },
118 { "title", required_argument, NULL, 't' },
119 { "user", required_argument, NULL, 'u' },
120 { "syslog-priority", required_argument, NULL, 's' },
121 { "syslog-facility", required_argument, NULL, 'l' },
122 { "syslog-tag", required_argument, NULL, 'T' },
123 { "help", no_argument, NULL, 'h' },
127 static _Noreturn void
130 (void)fprintf(stderr,
131 "usage: daemon [-cfHrS] [-p child_pidfile] [-P supervisor_pidfile]\n"
132 " [-u user] [-o output_file] [-t title]\n"
133 " [-l syslog_facility] [-s syslog_priority]\n"
134 " [-T syslog_tag] [-m output_mask] [-R restart_delay_secs]\n"
135 "command arguments ...\n");
137 (void)fprintf(stderr,
138 " --change-dir -c Change the current working directory to root\n"
139 " --close-fds -f Set stdin, stdout, stderr to /dev/null\n"
140 " --sighup -H Close and re-open output file on SIGHUP\n"
141 " --syslog -S Send output to syslog\n"
142 " --output-file -o <file> Append output of the child process to file\n"
143 " --output-mask -m <mask> What to send to syslog/file\n"
144 " 1=stdout, 2=stderr, 3=both\n"
145 " --child-pidfile -p <file> Write PID of the child process to file\n"
146 " --supervisor-pidfile -P <file> Write PID of the supervisor process to file\n"
147 " --restart -r Restart child if it terminates (1 sec delay)\n"
148 " --restart-delay -R <N> Restart child if it terminates after N sec\n"
149 " --title -t <title> Set the title of the supervisor process\n"
150 " --user -u <user> Drop privileges, run as given user\n"
151 " --syslog-priority -s <prio> Set syslog priority\n"
152 " --syslog-facility -l <flty> Set syslog facility\n"
153 " --syslog-tag -T <tag> Set syslog tag\n"
154 " --help -h Show this help\n");
160 main(int argc, char *argv[])
164 struct daemon_state state;
170 daemon_state_init(&state);
171 sigemptyset(&mask_susp);
172 sigemptyset(&mask_read);
173 sigemptyset(&mask_term);
174 sigemptyset(&mask_orig);
177 * Supervision mode is enabled if one of the following options are used:
179 * --supervisor-pidfile -P
180 * --restart -r / --restart-delay -R
182 * --syslog-facility -l
183 * --syslog-priority -s
186 * In supervision mode daemon executes the command in a forked process
187 * and observes the child by waiting for SIGCHILD. In supervision mode
188 * daemon must never exit before the child, this is necessary to prevent
189 * orphaning the child and leaving a stale pid file.
190 * To achieve this daemon catches SIGTERM and
191 * forwards it to the child, expecting to get SIGCHLD eventually.
193 while ((ch = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) {
196 state.keep_cur_workdir = 0;
199 state.keep_fds_open = 0;
202 state.log_reopen = true;
205 state.syslog_facility = get_log_mapping(optarg,
207 if (state.syslog_facility == -1) {
208 errx(5, "unrecognized syslog facility");
210 state.syslog_enabled = true;
211 state.supervision_enabled = true;
214 state.stdmask = strtol(optarg, &p, 10);
215 if (p == optarg || state.stdmask < 0 || state.stdmask > 3) {
216 errx(6, "unrecognized listening mask");
220 state.output_filename = optarg;
222 * TODO: setting output filename doesn't have to turn
223 * the supervision mode on. For non-supervised mode
224 * daemon could open the specified file and set it's
225 * descriptor as both stderr and stout before execve()
227 state.supervision_enabled = true;
230 state.child_pidfile = optarg;
231 state.supervision_enabled = true;
234 state.parent_pidfile = optarg;
235 state.supervision_enabled = true;
238 state.restart_enabled = true;
239 state.supervision_enabled = true;
242 state.restart_enabled = true;
243 state.restart_delay = strtol(optarg, &p, 0);
244 if (p == optarg || state.restart_delay < 1) {
245 errx(6, "invalid restart delay");
249 state.syslog_priority = get_log_mapping(optarg,
251 if (state.syslog_priority == -1) {
252 errx(4, "unrecognized syslog priority");
254 state.syslog_enabled = true;
255 state.supervision_enabled = true;
258 state.syslog_enabled = true;
259 state.supervision_enabled = true;
262 state.title = optarg;
265 state.syslog_tag = optarg;
266 state.syslog_enabled = true;
267 state.supervision_enabled = true;
274 __builtin_unreachable();
287 state.title = argv[0];
290 if (state.output_filename) {
291 state.output_fd = open_log(state.output_filename);
292 if (state.output_fd == -1) {
297 if (state.syslog_enabled) {
298 openlog(state.syslog_tag, LOG_PID | LOG_NDELAY,
299 state.syslog_facility);
303 * Try to open the pidfile before calling daemon(3),
304 * to be able to report the error intelligently
306 open_pid_files(&state);
307 if (daemon(state.keep_cur_workdir, state.keep_fds_open) == -1) {
309 daemon_terminate(&state);
311 /* Write out parent pidfile if needed. */
312 pidfile_write(state.parent_pidfh);
314 if (state.supervision_enabled) {
315 struct sigaction act_term = { 0 };
316 struct sigaction act_chld = { 0 };
317 struct sigaction act_hup = { 0 };
319 /* Avoid PID racing with SIGCHLD and SIGTERM. */
320 act_term.sa_handler = handle_term;
321 sigemptyset(&act_term.sa_mask);
322 sigaddset(&act_term.sa_mask, SIGCHLD);
324 act_chld.sa_handler = handle_chld;
325 sigemptyset(&act_chld.sa_mask);
326 sigaddset(&act_chld.sa_mask, SIGTERM);
328 act_hup.sa_handler = handle_hup;
329 sigemptyset(&act_hup.sa_mask);
331 /* Block these when avoiding racing before sigsuspend(). */
332 sigaddset(&mask_susp, SIGTERM);
333 sigaddset(&mask_susp, SIGCHLD);
334 /* Block SIGTERM when we lack a valid child PID. */
335 sigaddset(&mask_term, SIGTERM);
337 * When reading, we wish to avoid SIGCHLD. SIGTERM
338 * has to be caught, otherwise we'll be stuck until
339 * the read() returns - if it returns.
341 sigaddset(&mask_read, SIGCHLD);
342 /* Block SIGTERM to avoid racing until we have forked. */
343 if (sigprocmask(SIG_BLOCK, &mask_term, &mask_orig)) {
345 daemon_terminate(&state);
347 if (sigaction(SIGTERM, &act_term, NULL) == -1) {
349 daemon_terminate(&state);
351 if (sigaction(SIGCHLD, &act_chld, NULL) == -1) {
353 daemon_terminate(&state);
356 * Try to protect against pageout kill. Ignore the
357 * error, madvise(2) will fail only if a process does
358 * not have superuser privileges.
360 (void)madvise(NULL, 0, MADV_PROTECT);
361 if (state.log_reopen && state.output_fd >= 0 &&
362 sigaction(SIGHUP, &act_hup, NULL) == -1) {
364 daemon_terminate(&state);
367 if (pipe(state.pipe_fd)) {
371 * Spawn a child to exec the command.
377 /* fork failed, this can only happen when supervision is enabled */
380 daemon_terminate(&state);
383 /* fork succeeded, this is child's branch or supervision is disabled */
385 pidfile_write(state.child_pidfh);
387 if (state.user != NULL) {
388 restrict_process(state.user);
391 * In supervision mode, the child gets the original sigmask,
394 if (state.supervision_enabled) {
395 close(state.pipe_fd[0]);
396 if (sigprocmask(SIG_SETMASK, &mask_orig, NULL)) {
397 err(1, "sigprogmask");
399 if (state.stdmask & STDERR_FILENO) {
400 if (dup2(state.pipe_fd[1], STDERR_FILENO) == -1) {
404 if (state.stdmask & STDOUT_FILENO) {
405 if (dup2(state.pipe_fd[1], STDOUT_FILENO) == -1) {
409 if (state.pipe_fd[1] != STDERR_FILENO &&
410 state.pipe_fd[1] != STDOUT_FILENO) {
411 close(state.pipe_fd[1]);
414 execvp(argv[0], argv);
415 /* execvp() failed - report error and exit this process */
416 err(1, "%s", argv[0]);
421 * fork succeeded, this is the parent branch, this can only happen when
422 * supervision is enabled
424 * Unblock SIGTERM after we know we have a valid child PID to signal.
426 if (sigprocmask(SIG_UNBLOCK, &mask_term, NULL)) {
428 daemon_terminate(&state);
430 close(state.pipe_fd[1]);
431 state.pipe_fd[1] = -1;
433 setproctitle("%s[%d]", state.title, (int)pid);
435 * As we have closed the write end of pipe for parent process,
436 * we might detect the child's exit by reading EOF. The child
437 * might have closed its stdout and stderr, so we must wait for
438 * the SIGCHLD to ensure that the process is actually gone.
442 * We block SIGCHLD when listening, but SIGTERM we accept
443 * so the read() won't block if we wish to depart.
445 * Upon receiving SIGTERM, we have several options after
446 * sending the SIGTERM to our child:
448 * - read until EOF but only for a while
451 * We go for the third, as otherwise we have no guarantee
452 * that we won't block indefinitely if the child refuses
453 * to depart. To handle the second option, a different
454 * approach would be needed (procctl()?)
456 if (child_gone && state.child_eof) {
461 daemon_terminate(&state);
464 if (state.child_eof) {
465 if (sigprocmask(SIG_BLOCK, &mask_susp, NULL)) {
467 daemon_terminate(&state);
469 while (!terminate && !child_gone) {
470 sigsuspend(&mask_orig);
472 if (sigprocmask(SIG_UNBLOCK, &mask_susp, NULL)) {
474 daemon_terminate(&state);
479 if (sigprocmask(SIG_BLOCK, &mask_read, NULL)) {
481 daemon_terminate(&state);
484 state.child_eof = !listen_child(state.pipe_fd[0], &state);
486 if (sigprocmask(SIG_UNBLOCK, &mask_read, NULL)) {
488 daemon_terminate(&state);
492 if (state.restart_enabled && !terminate) {
493 daemon_sleep(state.restart_delay, 0);
495 if (sigprocmask(SIG_BLOCK, &mask_term, NULL)) {
497 daemon_terminate(&state);
499 if (state.restart_enabled && !terminate) {
500 close(state.pipe_fd[0]);
501 state.pipe_fd[0] = -1;
504 daemon_terminate(&state);
508 daemon_sleep(time_t secs, long nsecs)
510 struct timespec ts = { secs, nsecs };
512 while (!terminate && nanosleep(&ts, &ts) == -1) {
513 if (errno != EINTR) {
520 open_pid_files(struct daemon_state *state)
525 if (state->child_pidfile) {
526 state->child_pidfh = pidfile_open(state->child_pidfile, 0600, &fpid);
527 if (state->child_pidfh == NULL) {
528 if (errno == EEXIST) {
529 errx(3, "process already running, pid: %d",
532 err(2, "pidfile ``%s''", state->child_pidfile);
535 /* Do the same for the actual daemon process. */
536 if (state->parent_pidfile) {
537 state->parent_pidfh= pidfile_open(state->parent_pidfile, 0600, &fpid);
538 if (state->parent_pidfh == NULL) {
540 pidfile_remove(state->child_pidfh);
542 if (errno == EEXIST) {
543 errx(3, "process already running, pid: %d",
546 err(2, "ppidfile ``%s''", state->parent_pidfile);
552 get_log_mapping(const char *str, const CODE *c)
555 for (cp = c; cp->c_name; cp++)
556 if (strcmp(cp->c_name, str) == 0) {
563 restrict_process(const char *user)
565 struct passwd *pw = NULL;
569 errx(1, "unknown user: %s", user);
572 if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0) {
573 errx(1, "failed to set user environment");
576 setenv("USER", pw->pw_name, 1);
577 setenv("HOME", pw->pw_dir, 1);
578 setenv("SHELL", *pw->pw_shell ? pw->pw_shell : _PATH_BSHELL, 1);
582 * We try to collect whole lines terminated by '\n'. Otherwise we collect a
583 * full buffer, and then output it.
585 * Return value of false is assumed to mean EOF or error, and true indicates to
589 listen_child(int fd, struct daemon_state *state)
591 static unsigned char buf[LBUF_SIZE];
592 static size_t bytes_read = 0;
595 assert(state != NULL);
596 assert(bytes_read < LBUF_SIZE - 1);
601 rv = read(fd, buf + bytes_read, LBUF_SIZE - bytes_read - 1);
606 assert(bytes_read <= LBUF_SIZE - 1);
607 /* Always NUL-terminate just in case. */
608 buf[LBUF_SIZE - 1] = '\0';
610 * Chomp line by line until we run out of buffer.
611 * This does not take NUL characters into account.
613 while ((cp = memchr(buf, '\n', bytes_read)) != NULL) {
614 size_t bytes_line = cp - buf + 1;
615 assert(bytes_line <= bytes_read);
616 do_output(buf, bytes_line, state);
617 bytes_read -= bytes_line;
618 memmove(buf, cp + 1, bytes_read);
620 /* Wait until the buffer is full. */
621 if (bytes_read < LBUF_SIZE - 1) {
624 do_output(buf, bytes_read, state);
627 } else if (rv == -1) {
628 /* EINTR should trigger another read. */
629 if (errno == EINTR) {
636 /* Upon EOF, we have to flush what's left of the buffer. */
637 if (bytes_read > 0) {
638 do_output(buf, bytes_read, state);
645 * The default behavior is to stay silent if the user wants to redirect
646 * output to a file and/or syslog. If neither are provided, then we bounce
647 * everything back to parent's stdout.
650 do_output(const unsigned char *buf, size_t len, struct daemon_state *state)
652 assert(len <= LBUF_SIZE);
653 assert(state != NULL);
658 if (state->syslog_enabled) {
659 syslog(state->syslog_priority, "%.*s", (int)len, buf);
661 if (state->output_fd != -1) {
662 if (write(state->output_fd, buf, len) == -1)
665 if (state->keep_fds_open &&
666 !state->syslog_enabled &&
667 state->output_fd == -1) {
668 printf("%.*s", (int)len, buf);
673 * We use the global PID acquired directly from fork. If there is no valid
674 * child pid, the handler should be blocked and/or child_gone == 1.
677 handle_term(int signo)
679 if (pid > 0 && !child_gone) {
686 handle_chld(int signo __unused)
690 int rv = waitpid(-1, NULL, WNOHANG);
694 } else if (rv == -1 && errno != EINTR) {
702 handle_hup(int signo __unused)
709 open_log(const char *outfn)
712 return open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
716 reopen_log(struct daemon_state *state)
721 outfd = open_log(state->output_filename);
722 if (state->output_fd >= 0) {
723 close(state->output_fd);
725 state->output_fd = outfd;
729 daemon_state_init(struct daemon_state *state)
731 *state = (struct daemon_state) {
732 .pipe_fd = { -1, -1 },
733 .parent_pidfh = NULL,
735 .child_pidfile = NULL,
736 .parent_pidfile = NULL,
739 .supervision_enabled = false,
741 .restart_enabled = false,
742 .keep_cur_workdir = 1,
744 .stdmask = STDOUT_FILENO | STDERR_FILENO,
745 .syslog_enabled = false,
747 .syslog_priority = LOG_NOTICE,
748 .syslog_tag = "daemon",
749 .syslog_facility = LOG_DAEMON,
752 .output_filename = NULL,
756 static _Noreturn void
757 daemon_terminate(struct daemon_state *state)
759 assert(state != NULL);
760 close(state->output_fd);
761 close(state->pipe_fd[0]);
762 close(state->pipe_fd[1]);
763 if (state->syslog_enabled) {
766 pidfile_remove(state->child_pidfh);
767 pidfile_remove(state->parent_pidfh);
770 * Note that the exit value here doesn't matter in the case of a clean
771 * exit; daemon(3) already detached us from the caller, nothing is left
772 * to care about this one.