1 /*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 1999 Berkeley Software Design, Inc. All rights reserved. 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions 8 * are met: 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 16 * written permission. 17 * 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 28 * SUCH DAMAGE. 29 * 30 * From BSDI: daemon.c,v 1.2 1996/08/15 01:11:09 jch Exp 31 */ 32 33 #include <sys/cdefs.h> 34 __FBSDID("$FreeBSD$"); 35 36 #include <sys/param.h> 37 #include <sys/mman.h> 38 #include <sys/wait.h> 39 40 #include <fcntl.h> 41 #include <err.h> 42 #include <errno.h> 43 #include <getopt.h> 44 #include <libutil.h> 45 #include <login_cap.h> 46 #include <paths.h> 47 #include <pwd.h> 48 #include <signal.h> 49 #include <stdio.h> 50 #include <stdlib.h> 51 #include <unistd.h> 52 #include <string.h> 53 #include <strings.h> 54 #define SYSLOG_NAMES 55 #include <syslog.h> 56 #include <time.h> 57 #include <assert.h> 58 59 #define LBUF_SIZE 4096 60 61 struct log_params { 62 int dosyslog; 63 int logpri; 64 int noclose; 65 int outfd; 66 const char *outfn; 67 }; 68 69 static void restrict_process(const char *); 70 static void handle_term(int); 71 static void handle_chld(int); 72 static void handle_hup(int); 73 static int open_log(const char *); 74 static void reopen_log(struct log_params *); 75 static int listen_child(int, struct log_params *); 76 static int get_log_mapping(const char *, const CODE *); 77 static void open_pid_files(const char *, const char *, struct pidfh **, 78 struct pidfh **); 79 static void do_output(const unsigned char *, size_t, struct log_params *); 80 static void daemon_sleep(time_t, long); 81 82 static volatile sig_atomic_t terminate = 0, child_gone = 0, pid = 0, 83 do_log_reopen = 0; 84 85 static const char shortopts[] = "+cfHSp:P:ru:o:s:l:t:m:R:T:h"; 86 87 static const struct option longopts[] = { 88 { "change-dir", no_argument, NULL, 'c' }, 89 { "close-fds", no_argument, NULL, 'f' }, 90 { "sighup", no_argument, NULL, 'H' }, 91 { "syslog", no_argument, NULL, 'S' }, 92 { "output-file", required_argument, NULL, 'o' }, 93 { "output-mask", required_argument, NULL, 'm' }, 94 { "child-pidfile", required_argument, NULL, 'p' }, 95 { "supervisor-pidfile", required_argument, NULL, 'P' }, 96 { "restart", no_argument, NULL, 'r' }, 97 { "restart-delay", required_argument, NULL, 'R' }, 98 { "title", required_argument, NULL, 't' }, 99 { "user", required_argument, NULL, 'u' }, 100 { "syslog-priority", required_argument, NULL, 's' }, 101 { "syslog-facility", required_argument, NULL, 'l' }, 102 { "syslog-tag", required_argument, NULL, 'T' }, 103 { "help", no_argument, NULL, 'h' }, 104 { NULL, 0, NULL, 0 } 105 }; 106 107 static _Noreturn void 108 usage(int exitcode) 109 { 110 (void)fprintf(stderr, 111 "usage: daemon [-cfHrS] [-p child_pidfile] [-P supervisor_pidfile]\n" 112 " [-u user] [-o output_file] [-t title]\n" 113 " [-l syslog_facility] [-s syslog_priority]\n" 114 " [-T syslog_tag] [-m output_mask] [-R restart_delay_secs]\n" 115 "command arguments ...\n"); 116 117 (void)fprintf(stderr, 118 " --change-dir -c Change the current working directory to root\n" 119 " --close-fds -f Set stdin, stdout, stderr to /dev/null\n" 120 " --sighup -H Close and re-open output file on SIGHUP\n" 121 " --syslog -S Send output to syslog\n" 122 " --output-file -o <file> Append output of the child process to file\n" 123 " --output-mask -m <mask> What to send to syslog/file\n" 124 " 1=stdout, 2=stderr, 3=both\n" 125 " --child-pidfile -p <file> Write PID of the child process to file\n" 126 " --supervisor-pidfile -P <file> Write PID of the supervisor process to file\n" 127 " --restart -r Restart child if it terminates (1 sec delay)\n" 128 " --restart-delay -R <N> Restart child if it terminates after N sec\n" 129 " --title -t <title> Set the title of the supervisor process\n" 130 " --user -u <user> Drop privileges, run as given user\n" 131 " --syslog-priority -s <prio> Set syslog priority\n" 132 " --syslog-facility -l <flty> Set syslog facility\n" 133 " --syslog-tag -T <tag> Set syslog tag\n" 134 " --help -h Show this help\n"); 135 136 exit(exitcode); 137 } 138 139 int 140 main(int argc, char *argv[]) 141 { 142 const char *pidfile, *ppidfile, *title, *user, *outfn, *logtag; 143 int ch, nochdir, noclose, restart, dosyslog, child_eof; 144 sigset_t mask_susp, mask_orig, mask_read, mask_term; 145 struct log_params logpar; 146 int pfd[2] = { -1, -1 }, outfd = -1; 147 int stdmask, logpri, logfac, log_reopen; 148 struct pidfh *ppfh, *pfh; 149 char *p; 150 151 memset(&logpar, 0, sizeof(logpar)); 152 stdmask = STDOUT_FILENO | STDERR_FILENO; 153 ppidfile = pidfile = user = NULL; 154 nochdir = noclose = 1; 155 logpri = LOG_NOTICE; 156 logfac = LOG_DAEMON; 157 logtag = "daemon"; 158 restart = 0; 159 dosyslog = 0; 160 log_reopen = 0; 161 outfn = NULL; 162 title = NULL; 163 while ((ch = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) { 164 switch (ch) { 165 case 'c': 166 nochdir = 0; 167 break; 168 case 'f': 169 noclose = 0; 170 break; 171 case 'H': 172 log_reopen = 1; 173 break; 174 case 'l': 175 logfac = get_log_mapping(optarg, facilitynames); 176 if (logfac == -1) 177 errx(5, "unrecognized syslog facility"); 178 dosyslog = 1; 179 break; 180 case 'm': 181 stdmask = strtol(optarg, &p, 10); 182 if (p == optarg || stdmask < 0 || stdmask > 3) 183 errx(6, "unrecognized listening mask"); 184 break; 185 case 'o': 186 outfn = optarg; 187 break; 188 case 'p': 189 pidfile = optarg; 190 break; 191 case 'P': 192 ppidfile = optarg; 193 break; 194 case 'r': 195 restart = 1; 196 break; 197 case 'R': 198 restart = strtol(optarg, &p, 0); 199 if (p == optarg || restart < 1) 200 errx(6, "invalid restart delay"); 201 break; 202 case 's': 203 logpri = get_log_mapping(optarg, prioritynames); 204 if (logpri == -1) 205 errx(4, "unrecognized syslog priority"); 206 dosyslog = 1; 207 break; 208 case 'S': 209 dosyslog = 1; 210 break; 211 case 't': 212 title = optarg; 213 break; 214 case 'T': 215 logtag = optarg; 216 dosyslog = 1; 217 break; 218 case 'u': 219 user = optarg; 220 break; 221 case 'h': 222 usage(0); 223 __builtin_unreachable(); 224 default: 225 usage(1); 226 } 227 } 228 argc -= optind; 229 argv += optind; 230 231 if (argc == 0) 232 usage(1); 233 234 if (!title) 235 title = argv[0]; 236 237 if (outfn) { 238 outfd = open_log(outfn); 239 if (outfd == -1) 240 err(7, "open"); 241 } 242 243 if (dosyslog) 244 openlog(logtag, LOG_PID | LOG_NDELAY, logfac); 245 246 ppfh = pfh = NULL; 247 /* 248 * Try to open the pidfile before calling daemon(3), 249 * to be able to report the error intelligently 250 */ 251 open_pid_files(pidfile, ppidfile, &pfh, &ppfh); 252 if (daemon(nochdir, noclose) == -1) { 253 warn("daemon"); 254 goto exit; 255 } 256 /* Write out parent pidfile if needed. */ 257 pidfile_write(ppfh); 258 /* 259 * If the pidfile or restart option is specified the daemon 260 * executes the command in a forked process and wait on child 261 * exit to remove the pidfile or restart the command. Normally 262 * we don't want the monitoring daemon to be terminated 263 * leaving the running process and the stale pidfile, so we 264 * catch SIGTERM and forward it to the children expecting to 265 * get SIGCHLD eventually. We also must fork() to obtain a 266 * readable pipe with the child for writing to a log file 267 * and syslog. 268 */ 269 pid = -1; 270 if (pidfile || ppidfile || restart || outfd != -1 || dosyslog) { 271 struct sigaction act_term, act_chld, act_hup; 272 273 /* Avoid PID racing with SIGCHLD and SIGTERM. */ 274 memset(&act_term, 0, sizeof(act_term)); 275 act_term.sa_handler = handle_term; 276 sigemptyset(&act_term.sa_mask); 277 sigaddset(&act_term.sa_mask, SIGCHLD); 278 279 memset(&act_chld, 0, sizeof(act_chld)); 280 act_chld.sa_handler = handle_chld; 281 sigemptyset(&act_chld.sa_mask); 282 sigaddset(&act_chld.sa_mask, SIGTERM); 283 284 memset(&act_hup, 0, sizeof(act_hup)); 285 act_hup.sa_handler = handle_hup; 286 sigemptyset(&act_hup.sa_mask); 287 288 /* Block these when avoiding racing before sigsuspend(). */ 289 sigemptyset(&mask_susp); 290 sigaddset(&mask_susp, SIGTERM); 291 sigaddset(&mask_susp, SIGCHLD); 292 /* Block SIGTERM when we lack a valid child PID. */ 293 sigemptyset(&mask_term); 294 sigaddset(&mask_term, SIGTERM); 295 /* 296 * When reading, we wish to avoid SIGCHLD. SIGTERM 297 * has to be caught, otherwise we'll be stuck until 298 * the read() returns - if it returns. 299 */ 300 sigemptyset(&mask_read); 301 sigaddset(&mask_read, SIGCHLD); 302 /* Block SIGTERM to avoid racing until we have forked. */ 303 if (sigprocmask(SIG_BLOCK, &mask_term, &mask_orig)) { 304 warn("sigprocmask"); 305 goto exit; 306 } 307 if (sigaction(SIGTERM, &act_term, NULL) == -1) { 308 warn("sigaction"); 309 goto exit; 310 } 311 if (sigaction(SIGCHLD, &act_chld, NULL) == -1) { 312 warn("sigaction"); 313 goto exit; 314 } 315 /* 316 * Try to protect against pageout kill. Ignore the 317 * error, madvise(2) will fail only if a process does 318 * not have superuser privileges. 319 */ 320 (void)madvise(NULL, 0, MADV_PROTECT); 321 logpar.outfd = outfd; 322 logpar.dosyslog = dosyslog; 323 logpar.logpri = logpri; 324 logpar.noclose = noclose; 325 logpar.outfn = outfn; 326 if (log_reopen && outfd >= 0 && 327 sigaction(SIGHUP, &act_hup, NULL) == -1) { 328 warn("sigaction"); 329 goto exit; 330 } 331 restart: 332 if (pipe(pfd)) 333 err(1, "pipe"); 334 /* 335 * Spawn a child to exec the command. 336 */ 337 child_gone = 0; 338 pid = fork(); 339 if (pid == -1) { 340 warn("fork"); 341 goto exit; 342 } else if (pid > 0) { 343 /* 344 * Unblock SIGTERM after we know we have a valid 345 * child PID to signal. 346 */ 347 if (sigprocmask(SIG_UNBLOCK, &mask_term, NULL)) { 348 warn("sigprocmask"); 349 goto exit; 350 } 351 close(pfd[1]); 352 pfd[1] = -1; 353 } 354 } 355 if (pid <= 0) { 356 /* Now that we are the child, write out the pid. */ 357 pidfile_write(pfh); 358 359 if (user != NULL) 360 restrict_process(user); 361 /* 362 * When forking, the child gets the original sigmask, 363 * and dup'd pipes. 364 */ 365 if (pid == 0) { 366 close(pfd[0]); 367 if (sigprocmask(SIG_SETMASK, &mask_orig, NULL)) 368 err(1, "sigprogmask"); 369 if (stdmask & STDERR_FILENO) { 370 if (dup2(pfd[1], STDERR_FILENO) == -1) 371 err(1, "dup2"); 372 } 373 if (stdmask & STDOUT_FILENO) { 374 if (dup2(pfd[1], STDOUT_FILENO) == -1) 375 err(1, "dup2"); 376 } 377 if (pfd[1] != STDERR_FILENO && 378 pfd[1] != STDOUT_FILENO) 379 close(pfd[1]); 380 } 381 execvp(argv[0], argv); 382 /* 383 * execvp() failed -- report the error. The child is 384 * now running, so the exit status doesn't matter. 385 */ 386 err(1, "%s", argv[0]); 387 } 388 setproctitle("%s[%d]", title, (int)pid); 389 /* 390 * As we have closed the write end of pipe for parent process, 391 * we might detect the child's exit by reading EOF. The child 392 * might have closed its stdout and stderr, so we must wait for 393 * the SIGCHLD to ensure that the process is actually gone. 394 */ 395 child_eof = 0; 396 for (;;) { 397 /* 398 * We block SIGCHLD when listening, but SIGTERM we accept 399 * so the read() won't block if we wish to depart. 400 * 401 * Upon receiving SIGTERM, we have several options after 402 * sending the SIGTERM to our child: 403 * - read until EOF 404 * - read until EOF but only for a while 405 * - bail immediately 406 * 407 * We go for the third, as otherwise we have no guarantee 408 * that we won't block indefinitely if the child refuses 409 * to depart. To handle the second option, a different 410 * approach would be needed (procctl()?) 411 */ 412 if (child_gone && child_eof) { 413 break; 414 } else if (terminate) { 415 goto exit; 416 } else if (!child_eof) { 417 if (sigprocmask(SIG_BLOCK, &mask_read, NULL)) { 418 warn("sigprocmask"); 419 goto exit; 420 } 421 child_eof = !listen_child(pfd[0], &logpar); 422 if (sigprocmask(SIG_UNBLOCK, &mask_read, NULL)) { 423 warn("sigprocmask"); 424 goto exit; 425 } 426 } else { 427 if (sigprocmask(SIG_BLOCK, &mask_susp, NULL)) { 428 warn("sigprocmask"); 429 goto exit; 430 } 431 while (!terminate && !child_gone) 432 sigsuspend(&mask_orig); 433 if (sigprocmask(SIG_UNBLOCK, &mask_susp, NULL)) { 434 warn("sigprocmask"); 435 goto exit; 436 } 437 } 438 } 439 if (restart && !terminate) 440 daemon_sleep(restart, 0); 441 if (sigprocmask(SIG_BLOCK, &mask_term, NULL)) { 442 warn("sigprocmask"); 443 goto exit; 444 } 445 if (restart && !terminate) { 446 close(pfd[0]); 447 pfd[0] = -1; 448 goto restart; 449 } 450 exit: 451 close(outfd); 452 close(pfd[0]); 453 close(pfd[1]); 454 if (dosyslog) 455 closelog(); 456 pidfile_remove(pfh); 457 pidfile_remove(ppfh); 458 exit(1); /* If daemon(3) succeeded exit status does not matter. */ 459 } 460 461 static void 462 daemon_sleep(time_t secs, long nsecs) 463 { 464 struct timespec ts = { secs, nsecs }; 465 466 while (!terminate && nanosleep(&ts, &ts) == -1) { 467 if (errno != EINTR) 468 err(1, "nanosleep"); 469 } 470 } 471 472 static void 473 open_pid_files(const char *pidfile, const char *ppidfile, 474 struct pidfh **pfh, struct pidfh **ppfh) 475 { 476 pid_t fpid; 477 int serrno; 478 479 if (pidfile) { 480 *pfh = pidfile_open(pidfile, 0600, &fpid); 481 if (*pfh == NULL) { 482 if (errno == EEXIST) { 483 errx(3, "process already running, pid: %d", 484 fpid); 485 } 486 err(2, "pidfile ``%s''", pidfile); 487 } 488 } 489 /* Do the same for the actual daemon process. */ 490 if (ppidfile) { 491 *ppfh = pidfile_open(ppidfile, 0600, &fpid); 492 if (*ppfh == NULL) { 493 serrno = errno; 494 pidfile_remove(*pfh); 495 errno = serrno; 496 if (errno == EEXIST) { 497 errx(3, "process already running, pid: %d", 498 fpid); 499 } 500 err(2, "ppidfile ``%s''", ppidfile); 501 } 502 } 503 } 504 505 static int 506 get_log_mapping(const char *str, const CODE *c) 507 { 508 const CODE *cp; 509 for (cp = c; cp->c_name; cp++) 510 if (strcmp(cp->c_name, str) == 0) 511 return cp->c_val; 512 return -1; 513 } 514 515 static void 516 restrict_process(const char *user) 517 { 518 struct passwd *pw = NULL; 519 520 pw = getpwnam(user); 521 if (pw == NULL) 522 errx(1, "unknown user: %s", user); 523 524 if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0) 525 errx(1, "failed to set user environment"); 526 527 setenv("USER", pw->pw_name, 1); 528 setenv("HOME", pw->pw_dir, 1); 529 setenv("SHELL", *pw->pw_shell ? pw->pw_shell : _PATH_BSHELL, 1); 530 } 531 532 /* 533 * We try to collect whole lines terminated by '\n'. Otherwise we collect a 534 * full buffer, and then output it. 535 * 536 * Return value of 0 is assumed to mean EOF or error, and 1 indicates to 537 * continue reading. 538 */ 539 static int 540 listen_child(int fd, struct log_params *logpar) 541 { 542 static unsigned char buf[LBUF_SIZE]; 543 static size_t bytes_read = 0; 544 int rv; 545 546 assert(logpar); 547 assert(bytes_read < LBUF_SIZE - 1); 548 549 if (do_log_reopen) 550 reopen_log(logpar); 551 rv = read(fd, buf + bytes_read, LBUF_SIZE - bytes_read - 1); 552 if (rv > 0) { 553 unsigned char *cp; 554 555 bytes_read += rv; 556 assert(bytes_read <= LBUF_SIZE - 1); 557 /* Always NUL-terminate just in case. */ 558 buf[LBUF_SIZE - 1] = '\0'; 559 /* 560 * Chomp line by line until we run out of buffer. 561 * This does not take NUL characters into account. 562 */ 563 while ((cp = memchr(buf, '\n', bytes_read)) != NULL) { 564 size_t bytes_line = cp - buf + 1; 565 assert(bytes_line <= bytes_read); 566 do_output(buf, bytes_line, logpar); 567 bytes_read -= bytes_line; 568 memmove(buf, cp + 1, bytes_read); 569 } 570 /* Wait until the buffer is full. */ 571 if (bytes_read < LBUF_SIZE - 1) 572 return 1; 573 do_output(buf, bytes_read, logpar); 574 bytes_read = 0; 575 return 1; 576 } else if (rv == -1) { 577 /* EINTR should trigger another read. */ 578 if (errno == EINTR) { 579 return 1; 580 } else { 581 warn("read"); 582 return 0; 583 } 584 } 585 /* Upon EOF, we have to flush what's left of the buffer. */ 586 if (bytes_read > 0) { 587 do_output(buf, bytes_read, logpar); 588 bytes_read = 0; 589 } 590 return 0; 591 } 592 593 /* 594 * The default behavior is to stay silent if the user wants to redirect 595 * output to a file and/or syslog. If neither are provided, then we bounce 596 * everything back to parent's stdout. 597 */ 598 static void 599 do_output(const unsigned char *buf, size_t len, struct log_params *logpar) 600 { 601 assert(len <= LBUF_SIZE); 602 assert(logpar); 603 604 if (len < 1) 605 return; 606 if (logpar->dosyslog) 607 syslog(logpar->logpri, "%.*s", (int)len, buf); 608 if (logpar->outfd != -1) { 609 if (write(logpar->outfd, buf, len) == -1) 610 warn("write"); 611 } 612 if (logpar->noclose && !logpar->dosyslog && logpar->outfd == -1) 613 printf("%.*s", (int)len, buf); 614 } 615 616 /* 617 * We use the global PID acquired directly from fork. If there is no valid 618 * child pid, the handler should be blocked and/or child_gone == 1. 619 */ 620 static void 621 handle_term(int signo) 622 { 623 if (pid > 0 && !child_gone) 624 kill(pid, signo); 625 terminate = 1; 626 } 627 628 static void 629 handle_chld(int signo __unused) 630 { 631 632 for (;;) { 633 int rv = waitpid(-1, NULL, WNOHANG); 634 if (pid == rv) { 635 child_gone = 1; 636 break; 637 } else if (rv == -1 && errno != EINTR) { 638 warn("waitpid"); 639 return; 640 } 641 } 642 } 643 644 static void 645 handle_hup(int signo __unused) 646 { 647 648 do_log_reopen = 1; 649 } 650 651 static int 652 open_log(const char *outfn) 653 { 654 655 return open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600); 656 } 657 658 static void 659 reopen_log(struct log_params *lpp) 660 { 661 int outfd; 662 663 do_log_reopen = 0; 664 outfd = open_log(lpp->outfn); 665 if (lpp->outfd >= 0) 666 close(lpp->outfd); 667 lpp->outfd = outfd; 668 } 669 670