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