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/event.h>
42 #include <login_cap.h>
56 /* 1 year in seconds */
57 #define MAX_RESTART_DELAY 60*60*24*365
59 #define LBUF_SIZE 4096
62 MODE_DAEMON = 0, /* simply daemonize, no supervision */
63 MODE_SUPERVISE, /* initial supervision state */
64 MODE_TERMINATING, /* user requested termination */
65 MODE_NOCHILD, /* child is terminated, final state of the event loop */
70 unsigned char buf[LBUF_SIZE];
73 const char *child_pidfile;
74 const char *parent_pidfile;
75 const char *output_filename;
76 const char *syslog_tag;
79 struct pidfh *parent_pidfh;
80 struct pidfh *child_pidfh;
81 enum daemon_mode mode;
97 static void restrict_process(const char *);
98 static int open_log(const char *);
99 static void reopen_log(struct daemon_state *);
100 static bool listen_child(struct daemon_state *);
101 static int get_log_mapping(const char *, const CODE *);
102 static void open_pid_files(struct daemon_state *);
103 static void do_output(const unsigned char *, size_t, struct daemon_state *);
104 static void daemon_sleep(struct daemon_state *);
105 static void daemon_state_init(struct daemon_state *);
106 static void daemon_eventloop(struct daemon_state *);
107 static void daemon_terminate(struct daemon_state *);
108 static void daemon_exec(struct daemon_state *);
109 static bool daemon_is_child_dead(struct daemon_state *);
110 static void daemon_set_child_pipe(struct daemon_state *);
112 static const char shortopts[] = "+cfHSp:P:ru:o:s:l:t:m:R:T:h";
114 static const struct option longopts[] = {
115 { "change-dir", no_argument, NULL, 'c' },
116 { "close-fds", no_argument, NULL, 'f' },
117 { "sighup", no_argument, NULL, 'H' },
118 { "syslog", no_argument, NULL, 'S' },
119 { "output-file", required_argument, NULL, 'o' },
120 { "output-mask", required_argument, NULL, 'm' },
121 { "child-pidfile", required_argument, NULL, 'p' },
122 { "supervisor-pidfile", required_argument, NULL, 'P' },
123 { "restart", no_argument, NULL, 'r' },
124 { "restart-delay", required_argument, NULL, 'R' },
125 { "title", required_argument, NULL, 't' },
126 { "user", required_argument, NULL, 'u' },
127 { "syslog-priority", required_argument, NULL, 's' },
128 { "syslog-facility", required_argument, NULL, 'l' },
129 { "syslog-tag", required_argument, NULL, 'T' },
130 { "help", no_argument, NULL, 'h' },
134 static _Noreturn void
137 (void)fprintf(stderr,
138 "usage: daemon [-cfHrS] [-p child_pidfile] [-P supervisor_pidfile]\n"
139 " [-u user] [-o output_file] [-t title]\n"
140 " [-l syslog_facility] [-s syslog_priority]\n"
141 " [-T syslog_tag] [-m output_mask] [-R restart_delay_secs]\n"
142 "command arguments ...\n");
144 (void)fprintf(stderr,
145 " --change-dir -c Change the current working directory to root\n"
146 " --close-fds -f Set stdin, stdout, stderr to /dev/null\n"
147 " --sighup -H Close and re-open output file on SIGHUP\n"
148 " --syslog -S Send output to syslog\n"
149 " --output-file -o <file> Append output of the child process to file\n"
150 " --output-mask -m <mask> What to send to syslog/file\n"
151 " 1=stdout, 2=stderr, 3=both\n"
152 " --child-pidfile -p <file> Write PID of the child process to file\n"
153 " --supervisor-pidfile -P <file> Write PID of the supervisor process to file\n"
154 " --restart -r Restart child if it terminates (1 sec delay)\n"
155 " --restart-delay -R <N> Restart child if it terminates after N sec\n"
156 " --title -t <title> Set the title of the supervisor process\n"
157 " --user -u <user> Drop privileges, run as given user\n"
158 " --syslog-priority -s <prio> Set syslog priority\n"
159 " --syslog-facility -l <flty> Set syslog facility\n"
160 " --syslog-tag -T <tag> Set syslog tag\n"
161 " --help -h Show this help\n");
167 main(int argc, char *argv[])
169 const char *e = NULL;
171 struct daemon_state state;
173 daemon_state_init(&state);
175 /* Signals are processed via kqueue */
176 signal(SIGHUP, SIG_IGN);
177 signal(SIGTERM, SIG_IGN);
180 * Supervision mode is enabled if one of the following options are used:
182 * --supervisor-pidfile -P
183 * --restart -r / --restart-delay -R
185 * --syslog-facility -l
186 * --syslog-priority -s
189 * In supervision mode daemon executes the command in a forked process
190 * and observes the child by waiting for SIGCHILD. In supervision mode
191 * daemon must never exit before the child, this is necessary to prevent
192 * orphaning the child and leaving a stale pid file.
193 * To achieve this daemon catches SIGTERM and
194 * forwards it to the child, expecting to get SIGCHLD eventually.
196 while ((ch = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) {
199 state.keep_cur_workdir = 0;
202 state.keep_fds_open = 0;
205 state.log_reopen = true;
208 state.syslog_facility = get_log_mapping(optarg,
210 if (state.syslog_facility == -1) {
211 errx(5, "unrecognized syslog facility");
213 state.syslog_enabled = true;
214 state.mode = MODE_SUPERVISE;
217 state.stdmask = (int)strtonum(optarg, 0, 3, &e);
219 errx(6, "unrecognized listening mask: %s", e);
223 state.output_filename = optarg;
225 * TODO: setting output filename doesn't have to turn
226 * the supervision mode on. For non-supervised mode
227 * daemon could open the specified file and set it's
228 * descriptor as both stderr and stout before execve()
230 state.mode = MODE_SUPERVISE;
233 state.child_pidfile = optarg;
234 state.mode = MODE_SUPERVISE;
237 state.parent_pidfile = optarg;
238 state.mode = MODE_SUPERVISE;
241 state.restart_enabled = true;
242 state.mode = MODE_SUPERVISE;
245 state.restart_enabled = true;
246 state.restart_delay = (int)strtonum(optarg, 1,
247 MAX_RESTART_DELAY, &e);
249 errx(6, "invalid restart delay: %s", e);
253 state.syslog_priority = get_log_mapping(optarg,
255 if (state.syslog_priority == -1) {
256 errx(4, "unrecognized syslog priority");
258 state.syslog_enabled = true;
259 state.mode = MODE_SUPERVISE;
262 state.syslog_enabled = true;
263 state.mode = MODE_SUPERVISE;
266 state.title = optarg;
269 state.syslog_tag = optarg;
270 state.syslog_enabled = true;
271 state.mode = MODE_SUPERVISE;
278 __builtin_unreachable();
292 state.title = argv[0];
295 if (state.output_filename) {
296 state.output_fd = open_log(state.output_filename);
297 if (state.output_fd == -1) {
302 if (state.syslog_enabled) {
303 openlog(state.syslog_tag, LOG_PID | LOG_NDELAY,
304 state.syslog_facility);
308 * Try to open the pidfile before calling daemon(3),
309 * to be able to report the error intelligently
311 open_pid_files(&state);
314 * TODO: add feature to avoid backgrounding
315 * i.e. --foreground, -f
317 if (daemon(state.keep_cur_workdir, state.keep_fds_open) == -1) {
319 daemon_terminate(&state);
322 if (state.mode == MODE_DAEMON) {
326 /* Write out parent pidfile if needed. */
327 pidfile_write(state.parent_pidfh);
330 state.mode = MODE_SUPERVISE;
331 daemon_eventloop(&state);
332 daemon_sleep(&state);
333 } while (state.restart_enabled);
335 daemon_terminate(&state);
339 daemon_exec(struct daemon_state *state)
341 pidfile_write(state->child_pidfh);
343 if (state->user != NULL) {
344 restrict_process(state->user);
347 /* Ignored signals remain ignored after execve, unignore them */
348 signal(SIGHUP, SIG_DFL);
349 signal(SIGTERM, SIG_DFL);
350 execvp(state->argv[0], state->argv);
351 /* execvp() failed - report error and exit this process */
352 err(1, "%s", state->argv[0]);
355 /* Main event loop: fork the child and watch for events.
356 * After SIGTERM is received and propagated to the child there are
357 * several options on what to do next:
359 * - read until EOF but only for a while
361 * Currently the third option is used, because otherwise there is no
362 * guarantee that read() won't block indefinitely if the child refuses
363 * to depart. To handle the second option, a different approach
364 * would be needed (procctl()?).
367 daemon_eventloop(struct daemon_state *state)
375 * Try to protect against pageout kill. Ignore the
376 * error, madvise(2) will fail only if a process does
377 * not have superuser privileges.
379 (void)madvise(NULL, 0, MADV_PROTECT);
384 state->pipe_rd = pipe_fd[0];
385 state->pipe_wr = pipe_fd[1];
387 kq = kqueuex(KQUEUE_CLOEXEC);
388 EV_SET(&event, state->pipe_rd, EVFILT_READ, EV_ADD|EV_CLEAR, 0, 0,
390 if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
391 err(EXIT_FAILURE, "failed to register kevent");
394 EV_SET(&event, SIGHUP, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
395 if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
396 err(EXIT_FAILURE, "failed to register kevent");
399 EV_SET(&event, SIGTERM, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
400 if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
401 err(EXIT_FAILURE, "failed to register kevent");
404 EV_SET(&event, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
405 if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
406 err(EXIT_FAILURE, "failed to register kevent");
408 memset(&event, 0, sizeof(struct kevent));
410 /* Spawn a child to exec the command. */
413 /* fork failed, this can only happen when supervision is enabled */
414 switch (state->pid) {
417 state->mode = MODE_NOCHILD;
419 /* fork succeeded, this is child's branch */
422 daemon_set_child_pipe(state);
427 /* case: pid > 0; fork succeeded */
428 close(state->pipe_wr);
430 setproctitle("%s[%d]", state->title, (int)state->pid);
431 setbuf(stdout, NULL);
433 while (state->mode != MODE_NOCHILD) {
434 ret = kevent(kq, NULL, 0, &event, 1, NULL);
439 err(EXIT_FAILURE, "kevent wait");
444 if (event.flags & EV_ERROR) {
445 errx(EXIT_FAILURE, "Event error: %s",
446 strerror((int)event.data));
449 switch (event.filter) {
452 switch (event.ident) {
454 if (daemon_is_child_dead(state)) {
455 /* child is dead, read all until EOF */
457 state->mode = MODE_NOCHILD;
458 while (listen_child(state)) {
464 if (state->mode != MODE_SUPERVISE) {
465 /* user is impatient */
466 /* TODO: warn about repeated SIGTERM? */
470 state->mode = MODE_TERMINATING;
471 state->restart_enabled = false;
472 if (state->pid > 0) {
473 kill(state->pid, SIGTERM);
476 * TODO set kevent timer to exit
477 * unconditionally after some time
481 if (state->log_reopen && state->output_fd >= 0) {
490 * detecting EOF is no longer necessary
491 * if child closes the pipe daemon will stop getting
495 if (event.data > 0) {
496 (void)listen_child(state);
505 close(state->pipe_rd);
510 daemon_sleep(struct daemon_state *state)
512 struct timespec ts = { state->restart_delay, 0 };
514 if (!state->restart_enabled) {
517 while (nanosleep(&ts, &ts) == -1) {
518 if (errno != EINTR) {
525 open_pid_files(struct daemon_state *state)
530 if (state->child_pidfile) {
531 state->child_pidfh = pidfile_open(state->child_pidfile, 0600, &fpid);
532 if (state->child_pidfh == NULL) {
533 if (errno == EEXIST) {
534 errx(3, "process already running, pid: %d",
537 err(2, "pidfile ``%s''", state->child_pidfile);
540 /* Do the same for the actual daemon process. */
541 if (state->parent_pidfile) {
542 state->parent_pidfh= pidfile_open(state->parent_pidfile, 0600, &fpid);
543 if (state->parent_pidfh == NULL) {
545 pidfile_remove(state->child_pidfh);
547 if (errno == EEXIST) {
548 errx(3, "process already running, pid: %d",
551 err(2, "ppidfile ``%s''", state->parent_pidfile);
557 get_log_mapping(const char *str, const CODE *c)
560 for (cp = c; cp->c_name; cp++)
561 if (strcmp(cp->c_name, str) == 0) {
568 restrict_process(const char *user)
570 struct passwd *pw = NULL;
574 errx(1, "unknown user: %s", user);
577 if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0) {
578 errx(1, "failed to set user environment");
581 setenv("USER", pw->pw_name, 1);
582 setenv("HOME", pw->pw_dir, 1);
583 setenv("SHELL", *pw->pw_shell ? pw->pw_shell : _PATH_BSHELL, 1);
587 * We try to collect whole lines terminated by '\n'. Otherwise we collect a
588 * full buffer, and then output it.
590 * Return value of false is assumed to mean EOF or error, and true indicates to
594 listen_child(struct daemon_state *state)
599 assert(state != NULL);
600 assert(state->pos < LBUF_SIZE - 1);
602 rv = read(state->pipe_rd, state->buf + state->pos,
603 LBUF_SIZE - state->pos - 1);
606 assert(state->pos <= LBUF_SIZE - 1);
607 /* Always NUL-terminate just in case. */
608 state->buf[LBUF_SIZE - 1] = '\0';
611 * Find position of the last newline in the buffer.
612 * The buffer is guaranteed to have one or more complete lines
613 * if at least one newline was found when searching in reverse.
614 * All complete lines are flushed.
615 * This does not take NUL characters into account.
617 cp = memrchr(state->buf, '\n', state->pos);
619 size_t bytes_line = cp - state->buf + 1;
620 assert(bytes_line <= state->pos);
621 do_output(state->buf, bytes_line, state);
622 state->pos -= bytes_line;
623 memmove(state->buf, cp + 1, state->pos);
625 /* Wait until the buffer is full. */
626 if (state->pos < LBUF_SIZE - 1) {
629 do_output(state->buf, state->pos, state);
632 } else if (rv == -1) {
633 /* EINTR should trigger another read. */
634 if (errno == EINTR) {
641 /* Upon EOF, we have to flush what's left of the buffer. */
642 if (state->pos > 0) {
643 do_output(state->buf, state->pos, state);
650 * The default behavior is to stay silent if the user wants to redirect
651 * output to a file and/or syslog. If neither are provided, then we bounce
652 * everything back to parent's stdout.
655 do_output(const unsigned char *buf, size_t len, struct daemon_state *state)
657 assert(len <= LBUF_SIZE);
658 assert(state != NULL);
663 if (state->syslog_enabled) {
664 syslog(state->syslog_priority, "%.*s", (int)len, buf);
666 if (state->output_fd != -1) {
667 if (write(state->output_fd, buf, len) == -1)
670 if (state->keep_fds_open &&
671 !state->syslog_enabled &&
672 state->output_fd == -1) {
673 printf("%.*s", (int)len, buf);
678 open_log(const char *outfn)
681 return open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
685 reopen_log(struct daemon_state *state)
689 outfd = open_log(state->output_filename);
690 if (state->output_fd >= 0) {
691 close(state->output_fd);
693 state->output_fd = outfd;
697 daemon_state_init(struct daemon_state *state)
699 *state = (struct daemon_state) {
703 .parent_pidfh = NULL,
705 .child_pidfile = NULL,
706 .parent_pidfile = NULL,
710 .restart_enabled = false,
714 .keep_cur_workdir = 1,
716 .stdmask = STDOUT_FILENO | STDERR_FILENO,
717 .syslog_enabled = false,
719 .syslog_priority = LOG_NOTICE,
720 .syslog_tag = "daemon",
721 .syslog_facility = LOG_DAEMON,
724 .output_filename = NULL,
728 static _Noreturn void
729 daemon_terminate(struct daemon_state *state)
731 assert(state != NULL);
733 if (state->output_fd >= 0) {
734 close(state->output_fd);
736 if (state->pipe_rd >= 0) {
737 close(state->pipe_rd);
740 if (state->pipe_wr >= 0) {
741 close(state->pipe_wr);
743 if (state->syslog_enabled) {
746 pidfile_remove(state->child_pidfh);
747 pidfile_remove(state->parent_pidfh);
750 * Note that the exit value here doesn't matter in the case of a clean
751 * exit; daemon(3) already detached us from the caller, nothing is left
752 * to care about this one.
758 * Returns true if SIGCHILD came from state->pid
759 * This function could hang if SIGCHILD was emittied for a reason other than
760 * child dying (e.g., ptrace attach).
763 daemon_is_child_dead(struct daemon_state *state)
766 int who = waitpid(-1, NULL, WNOHANG);
767 if (state->pid == who) {
770 if (who == -1 && errno != EINTR) {
778 daemon_set_child_pipe(struct daemon_state *state)
780 if (state->stdmask & STDERR_FILENO) {
781 if (dup2(state->pipe_wr, STDERR_FILENO) == -1) {
785 if (state->stdmask & STDOUT_FILENO) {
786 if (dup2(state->pipe_wr, STDOUT_FILENO) == -1) {
790 if (state->pipe_wr != STDERR_FILENO &&
791 state->pipe_wr != STDOUT_FILENO) {
792 close(state->pipe_wr);
795 /* The child gets dup'd pipes. */
796 close(state->pipe_rd);