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