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/event.h> 34 #include <sys/mman.h> 35 #include <sys/wait.h> 36 37 #include <fcntl.h> 38 #include <err.h> 39 #include <errno.h> 40 #include <getopt.h> 41 #include <libutil.h> 42 #include <login_cap.h> 43 #include <paths.h> 44 #include <pwd.h> 45 #include <signal.h> 46 #include <stdio.h> 47 #include <stdbool.h> 48 #include <stdlib.h> 49 #include <unistd.h> 50 #include <string.h> 51 #define SYSLOG_NAMES 52 #include <syslog.h> 53 #include <time.h> 54 #include <assert.h> 55 56 /* 1 year in seconds */ 57 #define MAX_RESTART_DELAY 60*60*24*365 58 59 /* Maximum number of restarts */ 60 #define MAX_RESTART_COUNT 128 61 62 #define LBUF_SIZE 4096 63 64 enum daemon_mode { 65 MODE_DAEMON = 0, /* simply daemonize, no supervision */ 66 MODE_SUPERVISE, /* initial supervision state */ 67 MODE_TERMINATING, /* user requested termination */ 68 MODE_NOCHILD, /* child is terminated, final state of the event loop */ 69 }; 70 71 72 struct daemon_state { 73 unsigned char buf[LBUF_SIZE]; 74 size_t pos; 75 char **argv; 76 const char *child_pidfile; 77 const char *parent_pidfile; 78 const char *output_filename; 79 const char *syslog_tag; 80 const char *title; 81 const char *user; 82 struct pidfh *parent_pidfh; 83 struct pidfh *child_pidfh; 84 enum daemon_mode mode; 85 int pid; 86 int pipe_rd; 87 int pipe_wr; 88 int keep_cur_workdir; 89 int kqueue_fd; 90 int restart_delay; 91 int stdmask; 92 int syslog_priority; 93 int syslog_facility; 94 int keep_fds_open; 95 int output_fd; 96 mode_t output_file_mode; 97 bool restart_enabled; 98 bool syslog_enabled; 99 bool log_reopen; 100 int restart_count; 101 int restarted_count; 102 }; 103 104 static void restrict_process(const char *); 105 static int open_log(const char *, mode_t); 106 static void reopen_log(struct daemon_state *); 107 static bool listen_child(struct daemon_state *); 108 static int get_log_mapping(const char *, const CODE *); 109 static void open_pid_files(struct daemon_state *); 110 static void do_output(const unsigned char *, size_t, struct daemon_state *); 111 static void daemon_sleep(struct daemon_state *); 112 static void daemon_state_init(struct daemon_state *); 113 static void daemon_eventloop(struct daemon_state *); 114 static void daemon_terminate(struct daemon_state *); 115 static void daemon_exec(struct daemon_state *); 116 static bool daemon_is_child_dead(struct daemon_state *); 117 static void daemon_set_child_pipe(struct daemon_state *); 118 static int daemon_setup_kqueue(void); 119 120 static int pidfile_truncate(struct pidfh *); 121 122 static const char shortopts[] = "+cfHSp:P:ru:o:M:s:l:t:m:R:T:C:h"; 123 124 static const struct option longopts[] = { 125 { "change-dir", no_argument, NULL, 'c' }, 126 { "close-fds", no_argument, NULL, 'f' }, 127 { "sighup", no_argument, NULL, 'H' }, 128 { "syslog", no_argument, NULL, 'S' }, 129 { "output-file", required_argument, NULL, 'o' }, 130 { "output-file-mode", required_argument, NULL, 'M' }, 131 { "output-mask", required_argument, NULL, 'm' }, 132 { "child-pidfile", required_argument, NULL, 'p' }, 133 { "supervisor-pidfile", required_argument, NULL, 'P' }, 134 { "restart", no_argument, NULL, 'r' }, 135 { "restart-count", required_argument, NULL, 'C' }, 136 { "restart-delay", required_argument, NULL, 'R' }, 137 { "title", required_argument, NULL, 't' }, 138 { "user", required_argument, NULL, 'u' }, 139 { "syslog-priority", required_argument, NULL, 's' }, 140 { "syslog-facility", required_argument, NULL, 'l' }, 141 { "syslog-tag", required_argument, NULL, 'T' }, 142 { "help", no_argument, NULL, 'h' }, 143 { NULL, 0, NULL, 0 } 144 }; 145 146 static _Noreturn void 147 usage(int exitcode) 148 { 149 (void)fprintf(stderr, 150 "usage: daemon [-cfHrS] [-p child_pidfile] [-P supervisor_pidfile]\n" 151 " [-u user] [-o output_file] [-M output_file_mode] [-t title]\n" 152 " [-l syslog_facility] [-s syslog_priority]\n" 153 " [-T syslog_tag] [-m output_mask] [-R restart_delay_secs]\n" 154 " [-C restart_count]\n" 155 "command arguments ...\n"); 156 157 (void)fprintf(stderr, 158 " --change-dir -c Change the current working directory to root\n" 159 " --close-fds -f Set stdin, stdout, stderr to /dev/null\n" 160 " --sighup -H Close and re-open output file on SIGHUP\n" 161 " --syslog -S Send output to syslog\n" 162 " --output-file -o <file> Append output of the child process to file\n" 163 " --output-file-mode -M <mode> Output file mode of the child process\n" 164 " --output-mask -m <mask> What to send to syslog/file\n" 165 " 1=stdout, 2=stderr, 3=both\n" 166 " --child-pidfile -p <file> Write PID of the child process to file\n" 167 " --supervisor-pidfile -P <file> Write PID of the supervisor process to file\n" 168 " --restart -r Restart child if it terminates (1 sec delay)\n" 169 " --restart-count -C <N> Restart child at most N times, then exit\n" 170 " --restart-delay -R <N> Restart child if it terminates after N sec\n" 171 " --title -t <title> Set the title of the supervisor process\n" 172 " --user -u <user> Drop privileges, run as given user\n" 173 " --syslog-priority -s <prio> Set syslog priority\n" 174 " --syslog-facility -l <flty> Set syslog facility\n" 175 " --syslog-tag -T <tag> Set syslog tag\n" 176 " --help -h Show this help\n"); 177 178 exit(exitcode); 179 } 180 181 int 182 main(int argc, char *argv[]) 183 { 184 const char *e = NULL; 185 int ch = 0; 186 mode_t *set = NULL; 187 struct daemon_state state; 188 189 daemon_state_init(&state); 190 191 /* Signals are processed via kqueue */ 192 signal(SIGHUP, SIG_IGN); 193 signal(SIGTERM, SIG_IGN); 194 195 /* 196 * Supervision mode is enabled if one of the following options are used: 197 * --child-pidfile -p 198 * --supervisor-pidfile -P 199 * --restart -r / --restart-delay -R 200 * --syslog -S 201 * --syslog-facility -l 202 * --syslog-priority -s 203 * --syslog-tag -T 204 * 205 * In supervision mode daemon executes the command in a forked process 206 * and observes the child by waiting for SIGCHILD. In supervision mode 207 * daemon must never exit before the child, this is necessary to prevent 208 * orphaning the child and leaving a stale pid file. 209 * To achieve this daemon catches SIGTERM and 210 * forwards it to the child, expecting to get SIGCHLD eventually. 211 */ 212 while ((ch = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) { 213 switch (ch) { 214 case 'c': 215 state.keep_cur_workdir = 0; 216 break; 217 case 'C': 218 state.restart_count = (int)strtonum(optarg, 0, 219 MAX_RESTART_COUNT, &e); 220 if (e != NULL) { 221 errx(6, "invalid restart count: %s", e); 222 } 223 break; 224 case 'f': 225 state.keep_fds_open = 0; 226 break; 227 case 'H': 228 state.log_reopen = true; 229 break; 230 case 'l': 231 state.syslog_facility = get_log_mapping(optarg, 232 facilitynames); 233 if (state.syslog_facility == -1) { 234 errx(5, "unrecognized syslog facility"); 235 } 236 state.syslog_enabled = true; 237 state.mode = MODE_SUPERVISE; 238 break; 239 case 'm': 240 state.stdmask = (int)strtonum(optarg, 0, 3, &e); 241 if (e != NULL) { 242 errx(6, "unrecognized listening mask: %s", e); 243 } 244 break; 245 case 'o': 246 state.output_filename = optarg; 247 /* 248 * TODO: setting output filename doesn't have to turn 249 * the supervision mode on. For non-supervised mode 250 * daemon could open the specified file and set it's 251 * descriptor as both stderr and stout before execve() 252 */ 253 state.mode = MODE_SUPERVISE; 254 break; 255 case 'M': 256 if ((set = setmode(optarg)) == NULL) { 257 errx(6, "unrecognized output file mode: %s", optarg); 258 } else { 259 state.output_file_mode = getmode(set, 0); 260 } 261 free(set); 262 set = NULL; 263 break; 264 case 'p': 265 state.child_pidfile = optarg; 266 state.mode = MODE_SUPERVISE; 267 break; 268 case 'P': 269 state.parent_pidfile = optarg; 270 state.mode = MODE_SUPERVISE; 271 break; 272 case 'r': 273 state.restart_enabled = true; 274 state.mode = MODE_SUPERVISE; 275 break; 276 case 'R': 277 state.restart_enabled = true; 278 state.restart_delay = (int)strtonum(optarg, 1, 279 MAX_RESTART_DELAY, &e); 280 if (e != NULL) { 281 errx(6, "invalid restart delay: %s", e); 282 } 283 state.mode = MODE_SUPERVISE; 284 break; 285 case 's': 286 state.syslog_priority = get_log_mapping(optarg, 287 prioritynames); 288 if (state.syslog_priority == -1) { 289 errx(4, "unrecognized syslog priority"); 290 } 291 state.syslog_enabled = true; 292 state.mode = MODE_SUPERVISE; 293 break; 294 case 'S': 295 state.syslog_enabled = true; 296 state.mode = MODE_SUPERVISE; 297 break; 298 case 't': 299 state.title = optarg; 300 break; 301 case 'T': 302 state.syslog_tag = optarg; 303 state.syslog_enabled = true; 304 state.mode = MODE_SUPERVISE; 305 break; 306 case 'u': 307 state.user = optarg; 308 break; 309 case 'h': 310 usage(0); 311 __unreachable(); 312 default: 313 usage(1); 314 } 315 } 316 argc -= optind; 317 argv += optind; 318 state.argv = argv; 319 320 if (argc == 0) { 321 usage(1); 322 } 323 324 if (!state.title) { 325 state.title = argv[0]; 326 } 327 328 if (state.output_filename) { 329 state.output_fd = open_log(state.output_filename, state.output_file_mode); 330 if (state.output_fd == -1) { 331 err(7, "open"); 332 } 333 } 334 335 if (state.syslog_enabled) { 336 openlog(state.syslog_tag, LOG_PID | LOG_NDELAY, 337 state.syslog_facility); 338 } 339 340 /* 341 * Try to open the pidfile before calling daemon(3), 342 * to be able to report the error intelligently 343 */ 344 open_pid_files(&state); 345 346 /* 347 * TODO: add feature to avoid backgrounding 348 * i.e. --foreground, -f 349 */ 350 if (daemon(state.keep_cur_workdir, state.keep_fds_open) == -1) { 351 warn("daemon"); 352 daemon_terminate(&state); 353 } 354 355 if (state.mode == MODE_DAEMON) { 356 daemon_exec(&state); 357 } 358 359 /* Write out parent pidfile if needed. */ 360 pidfile_write(state.parent_pidfh); 361 362 state.kqueue_fd = daemon_setup_kqueue(); 363 364 do { 365 state.mode = MODE_SUPERVISE; 366 daemon_eventloop(&state); 367 daemon_sleep(&state); 368 if (state.restart_enabled && state.restart_count > -1) { 369 if (state.restarted_count >= state.restart_count) { 370 state.restart_enabled = false; 371 } 372 state.restarted_count++; 373 } 374 } while (state.restart_enabled); 375 376 daemon_terminate(&state); 377 } 378 379 static void 380 daemon_exec(struct daemon_state *state) 381 { 382 pidfile_write(state->child_pidfh); 383 384 if (state->user != NULL) { 385 restrict_process(state->user); 386 } 387 388 /* Ignored signals remain ignored after execve, unignore them */ 389 signal(SIGHUP, SIG_DFL); 390 signal(SIGTERM, SIG_DFL); 391 execvp(state->argv[0], state->argv); 392 /* execvp() failed - report error and exit this process */ 393 err(1, "%s", state->argv[0]); 394 } 395 396 /* Main event loop: fork the child and watch for events. 397 * After SIGTERM is received and propagated to the child there are 398 * several options on what to do next: 399 * - read until EOF 400 * - read until EOF but only for a while 401 * - bail immediately 402 * Currently the third option is used, because otherwise there is no 403 * guarantee that read() won't block indefinitely if the child refuses 404 * to depart. To handle the second option, a different approach 405 * would be needed (procctl()?). 406 */ 407 static void 408 daemon_eventloop(struct daemon_state *state) 409 { 410 struct kevent event; 411 int kq; 412 int ret; 413 int pipe_fd[2]; 414 415 /* 416 * Try to protect against pageout kill. Ignore the 417 * error, madvise(2) will fail only if a process does 418 * not have superuser privileges. 419 */ 420 (void)madvise(NULL, 0, MADV_PROTECT); 421 422 if (pipe(pipe_fd)) { 423 err(1, "pipe"); 424 } 425 state->pipe_rd = pipe_fd[0]; 426 state->pipe_wr = pipe_fd[1]; 427 428 kq = state->kqueue_fd; 429 EV_SET(&event, state->pipe_rd, EVFILT_READ, EV_ADD|EV_CLEAR, 0, 0, 430 NULL); 431 if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) { 432 err(EXIT_FAILURE, "failed to register kevent"); 433 } 434 435 memset(&event, 0, sizeof(struct kevent)); 436 437 /* Spawn a child to exec the command. */ 438 state->pid = fork(); 439 440 /* fork failed, this can only happen when supervision is enabled */ 441 switch (state->pid) { 442 case -1: 443 warn("fork"); 444 state->mode = MODE_NOCHILD; 445 return; 446 /* fork succeeded, this is child's branch */ 447 case 0: 448 close(kq); 449 daemon_set_child_pipe(state); 450 daemon_exec(state); 451 break; 452 } 453 454 /* case: pid > 0; fork succeeded */ 455 close(state->pipe_wr); 456 state->pipe_wr = -1; 457 setproctitle("%s[%d]", state->title, (int)state->pid); 458 setbuf(stdout, NULL); 459 460 while (state->mode != MODE_NOCHILD) { 461 ret = kevent(kq, NULL, 0, &event, 1, NULL); 462 switch (ret) { 463 case -1: 464 if (errno == EINTR) 465 continue; 466 err(EXIT_FAILURE, "kevent wait"); 467 case 0: 468 continue; 469 } 470 471 if (event.flags & EV_ERROR) { 472 errx(EXIT_FAILURE, "Event error: %s", 473 strerror((int)event.data)); 474 } 475 476 switch (event.filter) { 477 case EVFILT_SIGNAL: 478 479 switch (event.ident) { 480 case SIGCHLD: 481 if (daemon_is_child_dead(state)) { 482 /* child is dead, read all until EOF */ 483 state->pid = -1; 484 state->mode = MODE_NOCHILD; 485 while (listen_child(state)) { 486 continue; 487 } 488 } 489 continue; 490 case SIGTERM: 491 if (state->mode != MODE_SUPERVISE) { 492 /* user is impatient */ 493 /* TODO: warn about repeated SIGTERM? */ 494 continue; 495 } 496 497 state->mode = MODE_TERMINATING; 498 state->restart_enabled = false; 499 if (state->pid > 0) { 500 kill(state->pid, SIGTERM); 501 } 502 /* 503 * TODO set kevent timer to exit 504 * unconditionally after some time 505 */ 506 continue; 507 case SIGHUP: 508 if (state->log_reopen && state->output_fd >= 0) { 509 reopen_log(state); 510 } 511 continue; 512 } 513 break; 514 515 case EVFILT_READ: 516 /* 517 * detecting EOF is no longer necessary 518 * if child closes the pipe daemon will stop getting 519 * EVFILT_READ events 520 */ 521 522 if (event.data > 0) { 523 (void)listen_child(state); 524 } 525 continue; 526 default: 527 assert(0 && "Unexpected kevent filter type"); 528 continue; 529 } 530 } 531 532 /* EVFILT_READ kqueue filter goes away here. */ 533 close(state->pipe_rd); 534 state->pipe_rd = -1; 535 536 /* 537 * We don't have to truncate the pidfile, but it's easier to test 538 * daemon(8) behavior in some respects if we do. We won't bother if 539 * the child won't be restarted. 540 */ 541 if (state->child_pidfh != NULL && state->restart_enabled) { 542 pidfile_truncate(state->child_pidfh); 543 } 544 } 545 546 /* 547 * Note that daemon_sleep() should not be called with anything but the signal 548 * events in the kqueue without further consideration. 549 */ 550 static void 551 daemon_sleep(struct daemon_state *state) 552 { 553 struct kevent event = { 0 }; 554 int ret; 555 556 assert(state->pipe_rd == -1); 557 assert(state->pipe_wr == -1); 558 559 if (!state->restart_enabled) { 560 return; 561 } 562 563 EV_SET(&event, 0, EVFILT_TIMER, EV_ADD|EV_ONESHOT, NOTE_SECONDS, 564 state->restart_delay, NULL); 565 if (kevent(state->kqueue_fd, &event, 1, NULL, 0, NULL) == -1) { 566 err(1, "failed to register timer"); 567 } 568 569 for (;;) { 570 ret = kevent(state->kqueue_fd, NULL, 0, &event, 1, NULL); 571 if (ret == -1) { 572 if (errno != EINTR) { 573 err(1, "kevent"); 574 } 575 576 continue; 577 } 578 579 /* 580 * Any other events being raised are indicative of a problem 581 * that we need to investigate. Most likely being that 582 * something was not cleaned up from the eventloop. 583 */ 584 assert(event.filter == EVFILT_TIMER || 585 event.filter == EVFILT_SIGNAL); 586 587 if (event.filter == EVFILT_TIMER) { 588 /* Break's over, back to work. */ 589 break; 590 } 591 592 /* Process any pending signals. */ 593 switch (event.ident) { 594 case SIGTERM: 595 /* 596 * We could disarm the timer, but we'll be terminating 597 * promptly anyways. 598 */ 599 state->restart_enabled = false; 600 return; 601 case SIGHUP: 602 if (state->log_reopen && state->output_fd >= 0) { 603 reopen_log(state); 604 } 605 606 break; 607 case SIGCHLD: 608 default: 609 /* Discard */ 610 break; 611 } 612 } 613 614 /* SIGTERM should've returned immediately. */ 615 assert(state->restart_enabled); 616 } 617 618 static void 619 open_pid_files(struct daemon_state *state) 620 { 621 pid_t fpid; 622 int serrno; 623 624 if (state->child_pidfile) { 625 state->child_pidfh = pidfile_open(state->child_pidfile, 0600, &fpid); 626 if (state->child_pidfh == NULL) { 627 if (errno == EEXIST) { 628 errx(3, "process already running, pid: %d", 629 fpid); 630 } 631 err(2, "pidfile ``%s''", state->child_pidfile); 632 } 633 } 634 /* Do the same for the actual daemon process. */ 635 if (state->parent_pidfile) { 636 state->parent_pidfh= pidfile_open(state->parent_pidfile, 0600, &fpid); 637 if (state->parent_pidfh == NULL) { 638 serrno = errno; 639 pidfile_remove(state->child_pidfh); 640 errno = serrno; 641 if (errno == EEXIST) { 642 errx(3, "process already running, pid: %d", 643 fpid); 644 } 645 err(2, "ppidfile ``%s''", state->parent_pidfile); 646 } 647 } 648 } 649 650 static int 651 get_log_mapping(const char *str, const CODE *c) 652 { 653 const CODE *cp; 654 for (cp = c; cp->c_name; cp++) 655 if (strcmp(cp->c_name, str) == 0) { 656 return cp->c_val; 657 } 658 return -1; 659 } 660 661 static void 662 restrict_process(const char *user) 663 { 664 struct passwd *pw = NULL; 665 666 pw = getpwnam(user); 667 if (pw == NULL) { 668 errx(1, "unknown user: %s", user); 669 } 670 671 if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0) { 672 errx(1, "failed to set user environment"); 673 } 674 675 setenv("USER", pw->pw_name, 1); 676 setenv("HOME", pw->pw_dir, 1); 677 setenv("SHELL", *pw->pw_shell ? pw->pw_shell : _PATH_BSHELL, 1); 678 } 679 680 /* 681 * We try to collect whole lines terminated by '\n'. Otherwise we collect a 682 * full buffer, and then output it. 683 * 684 * Return value of false is assumed to mean EOF or error, and true indicates to 685 * continue reading. 686 */ 687 static bool 688 listen_child(struct daemon_state *state) 689 { 690 ssize_t rv; 691 unsigned char *cp; 692 693 assert(state != NULL); 694 assert(state->pos < LBUF_SIZE - 1); 695 696 rv = read(state->pipe_rd, state->buf + state->pos, 697 LBUF_SIZE - state->pos - 1); 698 if (rv > 0) { 699 state->pos += rv; 700 assert(state->pos <= LBUF_SIZE - 1); 701 /* Always NUL-terminate just in case. */ 702 state->buf[LBUF_SIZE - 1] = '\0'; 703 704 /* 705 * Find position of the last newline in the buffer. 706 * The buffer is guaranteed to have one or more complete lines 707 * if at least one newline was found when searching in reverse. 708 * All complete lines are flushed. 709 * This does not take NUL characters into account. 710 */ 711 cp = memrchr(state->buf, '\n', state->pos); 712 if (cp != NULL) { 713 size_t bytes_line = cp - state->buf + 1; 714 assert(bytes_line <= state->pos); 715 do_output(state->buf, bytes_line, state); 716 state->pos -= bytes_line; 717 memmove(state->buf, cp + 1, state->pos); 718 } 719 /* Wait until the buffer is full. */ 720 if (state->pos < LBUF_SIZE - 1) { 721 return true; 722 } 723 do_output(state->buf, state->pos, state); 724 state->pos = 0; 725 return true; 726 } else if (rv == -1) { 727 /* EINTR should trigger another read. */ 728 if (errno == EINTR) { 729 return true; 730 } else { 731 warn("read"); 732 return false; 733 } 734 } 735 /* Upon EOF, we have to flush what's left of the buffer. */ 736 if (state->pos > 0) { 737 do_output(state->buf, state->pos, state); 738 state->pos = 0; 739 } 740 return false; 741 } 742 743 /* 744 * The default behavior is to stay silent if the user wants to redirect 745 * output to a file and/or syslog. If neither are provided, then we bounce 746 * everything back to parent's stdout. 747 */ 748 static void 749 do_output(const unsigned char *buf, size_t len, struct daemon_state *state) 750 { 751 assert(len <= LBUF_SIZE); 752 assert(state != NULL); 753 754 if (len < 1) { 755 return; 756 } 757 if (state->syslog_enabled) { 758 syslog(state->syslog_priority, "%.*s", (int)len, buf); 759 } 760 if (state->output_fd != -1) { 761 if (write(state->output_fd, buf, len) == -1) 762 warn("write"); 763 } 764 if (state->keep_fds_open && 765 !state->syslog_enabled && 766 state->output_fd == -1) { 767 printf("%.*s", (int)len, buf); 768 } 769 } 770 771 static int 772 open_log(const char *outfn, mode_t outfm) 773 { 774 775 return open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, outfm); 776 } 777 778 static void 779 reopen_log(struct daemon_state *state) 780 { 781 int outfd; 782 783 outfd = open_log(state->output_filename, state->output_file_mode); 784 if (state->output_fd >= 0) { 785 close(state->output_fd); 786 } 787 state->output_fd = outfd; 788 } 789 790 static void 791 daemon_state_init(struct daemon_state *state) 792 { 793 *state = (struct daemon_state) { 794 .buf = {0}, 795 .pos = 0, 796 .argv = NULL, 797 .parent_pidfh = NULL, 798 .child_pidfh = NULL, 799 .child_pidfile = NULL, 800 .parent_pidfile = NULL, 801 .title = NULL, 802 .user = NULL, 803 .mode = MODE_DAEMON, 804 .restart_enabled = false, 805 .pid = 0, 806 .pipe_rd = -1, 807 .pipe_wr = -1, 808 .keep_cur_workdir = 1, 809 .kqueue_fd = -1, 810 .restart_delay = 1, 811 .stdmask = STDOUT_FILENO | STDERR_FILENO, 812 .syslog_enabled = false, 813 .log_reopen = false, 814 .syslog_priority = LOG_NOTICE, 815 .syslog_tag = "daemon", 816 .syslog_facility = LOG_DAEMON, 817 .keep_fds_open = 1, 818 .output_fd = -1, 819 .output_filename = NULL, 820 .output_file_mode = 0600, 821 .restart_count = -1, 822 .restarted_count = 0 823 }; 824 } 825 826 static _Noreturn void 827 daemon_terminate(struct daemon_state *state) 828 { 829 assert(state != NULL); 830 831 if (state->kqueue_fd >= 0) { 832 close(state->kqueue_fd); 833 } 834 if (state->output_fd >= 0) { 835 close(state->output_fd); 836 } 837 if (state->pipe_rd >= 0) { 838 close(state->pipe_rd); 839 } 840 841 if (state->pipe_wr >= 0) { 842 close(state->pipe_wr); 843 } 844 if (state->syslog_enabled) { 845 closelog(); 846 } 847 pidfile_remove(state->child_pidfh); 848 pidfile_remove(state->parent_pidfh); 849 850 /* 851 * Note that the exit value here doesn't matter in the case of a clean 852 * exit; daemon(3) already detached us from the caller, nothing is left 853 * to care about this one. 854 */ 855 exit(1); 856 } 857 858 /* 859 * Returns true if SIGCHILD came from state->pid due to its exit. 860 */ 861 static bool 862 daemon_is_child_dead(struct daemon_state *state) 863 { 864 int status; 865 866 for (;;) { 867 int who = waitpid(-1, &status, WNOHANG); 868 if (state->pid == who && (WIFEXITED(status) || 869 WIFSIGNALED(status))) { 870 return true; 871 } 872 if (who == 0) { 873 return false; 874 } 875 if (who == -1 && errno != EINTR) { 876 warn("waitpid"); 877 return false; 878 } 879 } 880 } 881 882 static void 883 daemon_set_child_pipe(struct daemon_state *state) 884 { 885 if (state->stdmask & STDERR_FILENO) { 886 if (dup2(state->pipe_wr, STDERR_FILENO) == -1) { 887 err(1, "dup2"); 888 } 889 } 890 if (state->stdmask & STDOUT_FILENO) { 891 if (dup2(state->pipe_wr, STDOUT_FILENO) == -1) { 892 err(1, "dup2"); 893 } 894 } 895 if (state->pipe_wr != STDERR_FILENO && 896 state->pipe_wr != STDOUT_FILENO) { 897 close(state->pipe_wr); 898 } 899 900 /* The child gets dup'd pipes. */ 901 close(state->pipe_rd); 902 } 903 904 static int 905 daemon_setup_kqueue(void) 906 { 907 int kq; 908 struct kevent event = { 0 }; 909 910 kq = kqueuex(KQUEUE_CLOEXEC); 911 if (kq == -1) { 912 err(EXIT_FAILURE, "kqueue"); 913 } 914 915 EV_SET(&event, SIGHUP, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL); 916 if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) { 917 err(EXIT_FAILURE, "failed to register kevent"); 918 } 919 920 EV_SET(&event, SIGTERM, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL); 921 if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) { 922 err(EXIT_FAILURE, "failed to register kevent"); 923 } 924 925 EV_SET(&event, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL); 926 if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) { 927 err(EXIT_FAILURE, "failed to register kevent"); 928 } 929 930 return (kq); 931 } 932 933 static int 934 pidfile_truncate(struct pidfh *pfh) 935 { 936 int pfd = pidfile_fileno(pfh); 937 938 assert(pfd >= 0); 939 940 if (ftruncate(pfd, 0) == -1) 941 return (-1); 942 943 /* 944 * pidfile_write(3) will always pwrite(..., 0) today, but let's assume 945 * it may not always and do a best-effort reset of the position just to 946 * set a good example. 947 */ 948 (void)lseek(pfd, 0, SEEK_SET); 949 return (0); 950 } 951