2 * Copyright (c) 1999 Berkeley Software Design, Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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
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
28 * From BSDI: daemon.c,v 1.2 1996/08/15 01:11:09 jch Exp
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
34 #include <sys/param.h>
42 #include <login_cap.h>
55 #define LBUF_SIZE 4096
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 **,
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);
75 static volatile sig_atomic_t terminate = 0, child_gone = 0, pid = 0;
78 main(int argc, char *argv[])
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;
89 memset(&logpar, 0, sizeof(logpar));
90 stdmask = STDOUT_FILENO | STDERR_FILENO;
91 ppidfile = pidfile = user = NULL;
92 nochdir = noclose = 1;
100 while ((ch = getopt(argc, argv, "cfSp:P:ru:o:s:l:t:l:m:T:")) != -1) {
109 logfac = get_log_mapping(optarg, facilitynames);
111 errx(5, "unrecognized syslog facility");
115 stdmask = strtol(optarg, &p, 10);
116 if (p == optarg || stdmask < 0 || stdmask > 3)
117 errx(6, "unrecognized listening mask");
132 logpri = get_log_mapping(optarg, prioritynames);
134 errx(4, "unrecognized syslog priority");
164 outfd = open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
170 openlog(logtag, LOG_PID | LOG_NDELAY, logfac);
174 * Try to open the pidfile before calling daemon(3),
175 * to be able to report the error intelligently
177 open_pid_files(pidfile, ppidfile, &pfh, &ppfh);
178 if (daemon(nochdir, noclose) == -1) {
182 /* Write out parent pidfile if needed. */
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
196 if (pidfile || ppidfile || restart || outfd != -1 || dosyslog) {
197 struct sigaction act_term, act_chld;
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);
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);
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);
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.
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)) {
229 if (sigaction(SIGTERM, &act_term, NULL) == -1) {
233 if (sigaction(SIGCHLD, &act_chld, NULL) == -1) {
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.
242 (void)madvise(NULL, 0, MADV_PROTECT);
243 logpar.outfd = outfd;
244 logpar.dosyslog = dosyslog;
245 logpar.logpri = logpri;
246 logpar.noclose = noclose;
251 * Spawn a child to exec the command.
258 } else if (pid > 0) {
260 * Unblock SIGTERM after we know we have a valid
261 * child PID to signal.
263 if (sigprocmask(SIG_UNBLOCK, &mask_term, NULL)) {
272 /* Now that we are the child, write out the pid. */
276 restrict_process(user);
278 * When forking, the child gets the original sigmask,
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)
289 if (stdmask & STDOUT_FILENO) {
290 if (dup2(pfd[1], STDOUT_FILENO) == -1)
293 if (pfd[1] != STDERR_FILENO &&
294 pfd[1] != STDOUT_FILENO)
297 execvp(argv[0], argv);
299 * execvp() failed -- report the error. The child is
300 * now running, so the exit status doesn't matter.
302 err(1, "%s", argv[0]);
304 setproctitle("%s[%d]", title, (int)pid);
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.
314 * We block SIGCHLD when listening, but SIGTERM we accept
315 * so the read() won't block if we wish to depart.
317 * Upon receiving SIGTERM, we have several options after
318 * sending the SIGTERM to our child:
320 * - read until EOF but only for a while
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()?)
328 if (child_gone && child_eof) {
330 } else if (terminate) {
332 } else if (!child_eof) {
333 if (sigprocmask(SIG_BLOCK, &mask_read, NULL)) {
337 child_eof = !listen_child(pfd[0], &logpar);
338 if (sigprocmask(SIG_UNBLOCK, &mask_read, NULL)) {
343 if (sigprocmask(SIG_BLOCK, &mask_susp, NULL)) {
347 while (!terminate && !child_gone)
348 sigsuspend(&mask_orig);
349 if (sigprocmask(SIG_UNBLOCK, &mask_susp, NULL)) {
355 if (sigprocmask(SIG_BLOCK, &mask_term, NULL)) {
359 if (restart && !terminate) {
372 pidfile_remove(ppfh);
373 exit(1); /* If daemon(3) succeeded exit status does not matter. */
377 daemon_sleep(time_t secs, long nsecs)
379 struct timespec ts = { secs, nsecs };
380 while (nanosleep(&ts, &ts) == -1) {
387 open_pid_files(const char *pidfile, const char *ppidfile,
388 struct pidfh **pfh, struct pidfh **ppfh)
394 *pfh = pidfile_open(pidfile, 0600, &fpid);
396 if (errno == EEXIST) {
397 errx(3, "process already running, pid: %d",
400 err(2, "pidfile ``%s''", pidfile);
403 /* Do the same for the actual daemon process. */
405 *ppfh = pidfile_open(ppidfile, 0600, &fpid);
408 pidfile_remove(*pfh);
410 if (errno == EEXIST) {
411 errx(3, "process already running, pid: %d",
414 err(2, "ppidfile ``%s''", ppidfile);
420 get_log_mapping(const char *str, const CODE *c)
423 for (cp = c; cp->c_name; cp++)
424 if (strcmp(cp->c_name, str) == 0)
430 restrict_process(const char *user)
432 struct passwd *pw = NULL;
436 errx(1, "unknown user: %s", user);
438 if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0)
439 errx(1, "failed to set user environment");
443 * We try to collect whole lines terminated by '\n'. Otherwise we collect a
444 * full buffer, and then output it.
446 * Return value of 0 is assumed to mean EOF or error, and 1 indicates to
450 listen_child(int fd, struct log_params *logpar)
452 static unsigned char buf[LBUF_SIZE];
453 static size_t bytes_read = 0;
457 assert(bytes_read < LBUF_SIZE - 1);
459 rv = read(fd, buf + bytes_read, LBUF_SIZE - bytes_read - 1);
464 assert(bytes_read <= LBUF_SIZE - 1);
465 /* Always NUL-terminate just in case. */
466 buf[LBUF_SIZE - 1] = '\0';
468 * Chomp line by line until we run out of buffer.
469 * This does not take NUL characters into account.
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);
478 /* Wait until the buffer is full. */
479 if (bytes_read < LBUF_SIZE - 1)
481 do_output(buf, bytes_read, logpar);
484 } else if (rv == -1) {
485 /* EINTR should trigger another read. */
486 if (errno == EINTR) {
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);
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.
507 do_output(const unsigned char *buf, size_t len, struct log_params *logpar)
509 assert(len <= LBUF_SIZE);
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)
520 if (logpar->noclose && !logpar->dosyslog && logpar->outfd == -1)
521 printf("%.*s", (int)len, buf);
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.
529 handle_term(int signo)
531 if (pid > 0 && !child_gone)
537 handle_chld(int signo)
541 int rv = waitpid(-1, NULL, WNOHANG);
545 } else if (rv == -1 && errno != EINTR) {
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");