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>
44 #include <login_cap.h>
57 #define LBUF_SIZE 4096
66 static void restrict_process(const char *);
67 static void handle_term(int);
68 static void handle_chld(int);
69 static int listen_child(int, struct log_params *);
70 static int get_log_mapping(const char *, const CODE *);
71 static void open_pid_files(const char *, const char *, struct pidfh **,
73 static void do_output(const unsigned char *, size_t, struct log_params *);
74 static void daemon_sleep(time_t, long);
75 static void usage(void);
77 static volatile sig_atomic_t terminate = 0, child_gone = 0, pid = 0;
80 main(int argc, char *argv[])
82 const char *pidfile, *ppidfile, *title, *user, *outfn, *logtag;
83 int ch, nochdir, noclose, restart, dosyslog, child_eof;
84 sigset_t mask_susp, mask_orig, mask_read, mask_term;
85 struct log_params logpar;
86 int pfd[2] = { -1, -1 }, outfd = -1;
87 int stdmask, logpri, logfac;
88 struct pidfh *ppfh, *pfh;
91 memset(&logpar, 0, sizeof(logpar));
92 stdmask = STDOUT_FILENO | STDERR_FILENO;
93 ppidfile = pidfile = user = NULL;
94 nochdir = noclose = 1;
102 while ((ch = getopt(argc, argv, "cfSp:P:ru:o:s:l:t:l:m:R:T:")) != -1) {
111 logfac = get_log_mapping(optarg, facilitynames);
113 errx(5, "unrecognized syslog facility");
117 stdmask = strtol(optarg, &p, 10);
118 if (p == optarg || stdmask < 0 || stdmask > 3)
119 errx(6, "unrecognized listening mask");
134 restart = strtol(optarg, &p, 0);
135 if (p == optarg || restart < 1)
136 errx(6, "invalid restart delay");
139 logpri = get_log_mapping(optarg, prioritynames);
141 errx(4, "unrecognized syslog priority");
171 outfd = open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
177 openlog(logtag, LOG_PID | LOG_NDELAY, logfac);
181 * Try to open the pidfile before calling daemon(3),
182 * to be able to report the error intelligently
184 open_pid_files(pidfile, ppidfile, &pfh, &ppfh);
185 if (daemon(nochdir, noclose) == -1) {
189 /* Write out parent pidfile if needed. */
192 * If the pidfile or restart option is specified the daemon
193 * executes the command in a forked process and wait on child
194 * exit to remove the pidfile or restart the command. Normally
195 * we don't want the monitoring daemon to be terminated
196 * leaving the running process and the stale pidfile, so we
197 * catch SIGTERM and forward it to the children expecting to
198 * get SIGCHLD eventually. We also must fork() to obtain a
199 * readable pipe with the child for writing to a log file
203 if (pidfile || ppidfile || restart || outfd != -1 || dosyslog) {
204 struct sigaction act_term, act_chld;
206 /* Avoid PID racing with SIGCHLD and SIGTERM. */
207 memset(&act_term, 0, sizeof(act_term));
208 act_term.sa_handler = handle_term;
209 sigemptyset(&act_term.sa_mask);
210 sigaddset(&act_term.sa_mask, SIGCHLD);
212 memset(&act_chld, 0, sizeof(act_chld));
213 act_chld.sa_handler = handle_chld;
214 sigemptyset(&act_chld.sa_mask);
215 sigaddset(&act_chld.sa_mask, SIGTERM);
217 /* Block these when avoiding racing before sigsuspend(). */
218 sigemptyset(&mask_susp);
219 sigaddset(&mask_susp, SIGTERM);
220 sigaddset(&mask_susp, SIGCHLD);
221 /* Block SIGTERM when we lack a valid child PID. */
222 sigemptyset(&mask_term);
223 sigaddset(&mask_term, SIGTERM);
225 * When reading, we wish to avoid SIGCHLD. SIGTERM
226 * has to be caught, otherwise we'll be stuck until
227 * the read() returns - if it returns.
229 sigemptyset(&mask_read);
230 sigaddset(&mask_read, SIGCHLD);
231 /* Block SIGTERM to avoid racing until we have forked. */
232 if (sigprocmask(SIG_BLOCK, &mask_term, &mask_orig)) {
236 if (sigaction(SIGTERM, &act_term, NULL) == -1) {
240 if (sigaction(SIGCHLD, &act_chld, NULL) == -1) {
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.
249 (void)madvise(NULL, 0, MADV_PROTECT);
250 logpar.outfd = outfd;
251 logpar.dosyslog = dosyslog;
252 logpar.logpri = logpri;
253 logpar.noclose = noclose;
258 * Spawn a child to exec the command.
265 } else if (pid > 0) {
267 * Unblock SIGTERM after we know we have a valid
268 * child PID to signal.
270 if (sigprocmask(SIG_UNBLOCK, &mask_term, NULL)) {
279 /* Now that we are the child, write out the pid. */
283 restrict_process(user);
285 * When forking, the child gets the original sigmask,
290 if (sigprocmask(SIG_SETMASK, &mask_orig, NULL))
291 err(1, "sigprogmask");
292 if (stdmask & STDERR_FILENO) {
293 if (dup2(pfd[1], STDERR_FILENO) == -1)
296 if (stdmask & STDOUT_FILENO) {
297 if (dup2(pfd[1], STDOUT_FILENO) == -1)
300 if (pfd[1] != STDERR_FILENO &&
301 pfd[1] != STDOUT_FILENO)
304 execvp(argv[0], argv);
306 * execvp() failed -- report the error. The child is
307 * now running, so the exit status doesn't matter.
309 err(1, "%s", argv[0]);
311 setproctitle("%s[%d]", title, (int)pid);
313 * As we have closed the write end of pipe for parent process,
314 * we might detect the child's exit by reading EOF. The child
315 * might have closed its stdout and stderr, so we must wait for
316 * the SIGCHLD to ensure that the process is actually gone.
321 * We block SIGCHLD when listening, but SIGTERM we accept
322 * so the read() won't block if we wish to depart.
324 * Upon receiving SIGTERM, we have several options after
325 * sending the SIGTERM to our child:
327 * - read until EOF but only for a while
330 * We go for the third, as otherwise we have no guarantee
331 * that we won't block indefinitely if the child refuses
332 * to depart. To handle the second option, a different
333 * approach would be needed (procctl()?)
335 if (child_gone && child_eof) {
337 } else if (terminate) {
339 } else if (!child_eof) {
340 if (sigprocmask(SIG_BLOCK, &mask_read, NULL)) {
344 child_eof = !listen_child(pfd[0], &logpar);
345 if (sigprocmask(SIG_UNBLOCK, &mask_read, NULL)) {
350 if (sigprocmask(SIG_BLOCK, &mask_susp, NULL)) {
354 while (!terminate && !child_gone)
355 sigsuspend(&mask_orig);
356 if (sigprocmask(SIG_UNBLOCK, &mask_susp, NULL)) {
362 if (restart && !terminate)
363 daemon_sleep(restart, 0);
364 if (sigprocmask(SIG_BLOCK, &mask_term, NULL)) {
368 if (restart && !terminate) {
380 pidfile_remove(ppfh);
381 exit(1); /* If daemon(3) succeeded exit status does not matter. */
385 daemon_sleep(time_t secs, long nsecs)
387 struct timespec ts = { secs, nsecs };
389 while (!terminate && nanosleep(&ts, &ts) == -1) {
396 open_pid_files(const char *pidfile, const char *ppidfile,
397 struct pidfh **pfh, struct pidfh **ppfh)
403 *pfh = pidfile_open(pidfile, 0600, &fpid);
405 if (errno == EEXIST) {
406 errx(3, "process already running, pid: %d",
409 err(2, "pidfile ``%s''", pidfile);
412 /* Do the same for the actual daemon process. */
414 *ppfh = pidfile_open(ppidfile, 0600, &fpid);
417 pidfile_remove(*pfh);
419 if (errno == EEXIST) {
420 errx(3, "process already running, pid: %d",
423 err(2, "ppidfile ``%s''", ppidfile);
429 get_log_mapping(const char *str, const CODE *c)
432 for (cp = c; cp->c_name; cp++)
433 if (strcmp(cp->c_name, str) == 0)
439 restrict_process(const char *user)
441 struct passwd *pw = NULL;
445 errx(1, "unknown user: %s", user);
447 if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0)
448 errx(1, "failed to set user environment");
452 * We try to collect whole lines terminated by '\n'. Otherwise we collect a
453 * full buffer, and then output it.
455 * Return value of 0 is assumed to mean EOF or error, and 1 indicates to
459 listen_child(int fd, struct log_params *logpar)
461 static unsigned char buf[LBUF_SIZE];
462 static size_t bytes_read = 0;
466 assert(bytes_read < LBUF_SIZE - 1);
468 rv = read(fd, buf + bytes_read, LBUF_SIZE - bytes_read - 1);
473 assert(bytes_read <= LBUF_SIZE - 1);
474 /* Always NUL-terminate just in case. */
475 buf[LBUF_SIZE - 1] = '\0';
477 * Chomp line by line until we run out of buffer.
478 * This does not take NUL characters into account.
480 while ((cp = memchr(buf, '\n', bytes_read)) != NULL) {
481 size_t bytes_line = cp - buf + 1;
482 assert(bytes_line <= bytes_read);
483 do_output(buf, bytes_line, logpar);
484 bytes_read -= bytes_line;
485 memmove(buf, cp + 1, bytes_read);
487 /* Wait until the buffer is full. */
488 if (bytes_read < LBUF_SIZE - 1)
490 do_output(buf, bytes_read, logpar);
493 } else if (rv == -1) {
494 /* EINTR should trigger another read. */
495 if (errno == EINTR) {
502 /* Upon EOF, we have to flush what's left of the buffer. */
503 if (bytes_read > 0) {
504 do_output(buf, bytes_read, logpar);
511 * The default behavior is to stay silent if the user wants to redirect
512 * output to a file and/or syslog. If neither are provided, then we bounce
513 * everything back to parent's stdout.
516 do_output(const unsigned char *buf, size_t len, struct log_params *logpar)
518 assert(len <= LBUF_SIZE);
523 if (logpar->dosyslog)
524 syslog(logpar->logpri, "%.*s", (int)len, buf);
525 if (logpar->outfd != -1) {
526 if (write(logpar->outfd, buf, len) == -1)
529 if (logpar->noclose && !logpar->dosyslog && logpar->outfd == -1)
530 printf("%.*s", (int)len, buf);
534 * We use the global PID acquired directly from fork. If there is no valid
535 * child pid, the handler should be blocked and/or child_gone == 1.
538 handle_term(int signo)
540 if (pid > 0 && !child_gone)
546 handle_chld(int signo)
550 int rv = waitpid(-1, NULL, WNOHANG);
554 } else if (rv == -1 && errno != EINTR) {
564 (void)fprintf(stderr,
565 "usage: daemon [-cfrS] [-p child_pidfile] [-P supervisor_pidfile]\n"
566 " [-u user] [-o output_file] [-t title]\n"
567 " [-l syslog_facility] [-s syslog_priority]\n"
568 " [-T syslog_tag] [-m output_mask] [-R restart_delay_secs]\n"
569 "command arguments ...\n");