1 /* $NetBSD: ntpd.c,v 1.14 2017/04/13 20:17:42 christos Exp $ */ 2 3 /* 4 * ntpd.c - main program for the fixed point NTP daemon 5 */ 6 7 #ifdef HAVE_CONFIG_H 8 # include <config.h> 9 #endif 10 11 #include "ntp_machine.h" 12 #include "ntpd.h" 13 #include "ntp_io.h" 14 #include "ntp_stdlib.h" 15 #include <ntp_random.h> 16 17 #include "ntp_config.h" 18 #include "ntp_syslog.h" 19 #include "ntp_assert.h" 20 #include "isc/error.h" 21 #include "isc/strerror.h" 22 #include "isc/formatcheck.h" 23 #include "iosignal.h" 24 25 #ifdef SIM 26 # include "ntpsim.h" 27 #endif 28 29 #include "ntp_libopts.h" 30 #include "ntpd-opts.h" 31 32 /* there's a short treatise below what the thread stuff is for. 33 * [Bug 2954] enable the threading warm-up only for Linux. 34 */ 35 #if defined(HAVE_PTHREADS) && HAVE_PTHREADS && !defined(NO_THREADS) 36 # ifdef HAVE_PTHREAD_H 37 # include <pthread.h> 38 # endif 39 # if defined(linux) 40 # define NEED_PTHREAD_WARMUP 41 # endif 42 #endif 43 44 #ifdef HAVE_UNISTD_H 45 # include <unistd.h> 46 #endif 47 #ifdef HAVE_SYS_STAT_H 48 # include <sys/stat.h> 49 #endif 50 #include <stdio.h> 51 #ifdef HAVE_SYS_PARAM_H 52 # include <sys/param.h> 53 #endif 54 #ifdef HAVE_SYS_SIGNAL_H 55 # include <sys/signal.h> 56 #else 57 # include <signal.h> 58 #endif 59 #ifdef HAVE_SYS_IOCTL_H 60 # include <sys/ioctl.h> 61 #endif /* HAVE_SYS_IOCTL_H */ 62 #if defined(HAVE_RTPRIO) 63 # ifdef HAVE_SYS_LOCK_H 64 # include <sys/lock.h> 65 # endif 66 # include <sys/rtprio.h> 67 #else 68 # ifdef HAVE_PLOCK 69 # ifdef HAVE_SYS_LOCK_H 70 # include <sys/lock.h> 71 # endif 72 # endif 73 #endif 74 #if defined(HAVE_SCHED_SETSCHEDULER) 75 # ifdef HAVE_SCHED_H 76 # include <sched.h> 77 # else 78 # ifdef HAVE_SYS_SCHED_H 79 # include <sys/sched.h> 80 # endif 81 # endif 82 #endif 83 #if defined(HAVE_SYS_MMAN_H) 84 # include <sys/mman.h> 85 #endif 86 87 #ifdef HAVE_TERMIOS_H 88 # include <termios.h> 89 #endif 90 91 #ifdef SYS_DOMAINOS 92 # include <apollo/base.h> 93 #endif /* SYS_DOMAINOS */ 94 95 96 #include "recvbuff.h" 97 #include "ntp_cmdargs.h" 98 99 #if 0 /* HMS: I don't think we need this. 961223 */ 100 #ifdef LOCK_PROCESS 101 # ifdef SYS_SOLARIS 102 # include <sys/mman.h> 103 # else 104 # include <sys/lock.h> 105 # endif 106 #endif 107 #endif 108 109 #ifdef _AIX 110 # include <ulimit.h> 111 #endif /* _AIX */ 112 113 #ifdef SCO5_CLOCK 114 # include <sys/ci/ciioctl.h> 115 #endif 116 117 #ifdef HAVE_DROPROOT 118 # include <ctype.h> 119 # include <grp.h> 120 # include <pwd.h> 121 #ifdef HAVE_LINUX_CAPABILITIES 122 # include <sys/capability.h> 123 # include <sys/prctl.h> 124 #endif /* HAVE_LINUX_CAPABILITIES */ 125 #if defined(HAVE_PRIV_H) && defined(HAVE_SOLARIS_PRIVS) 126 # include <priv.h> 127 #endif /* HAVE_PRIV_H */ 128 #endif /* HAVE_DROPROOT */ 129 130 #if defined (LIBSECCOMP) && (KERN_SECCOMP) 131 /* # include <sys/types.h> */ 132 # include <sys/resource.h> 133 # include <seccomp.h> 134 #endif /* LIBSECCOMP and KERN_SECCOMP */ 135 136 #ifdef HAVE_DNSREGISTRATION 137 # include <dns_sd.h> 138 DNSServiceRef mdns; 139 #endif 140 141 #ifdef HAVE_SETPGRP_0 142 # define ntp_setpgrp(x, y) setpgrp() 143 #else 144 # define ntp_setpgrp(x, y) setpgrp(x, y) 145 #endif 146 147 #ifdef HAVE_SOLARIS_PRIVS 148 # define LOWPRIVS "basic,sys_time,net_privaddr,proc_setid,!proc_info,!proc_session,!proc_exec" 149 static priv_set_t *lowprivs = NULL; 150 static priv_set_t *highprivs = NULL; 151 #endif /* HAVE_SOLARIS_PRIVS */ 152 /* 153 * Scheduling priority we run at 154 */ 155 #define NTPD_PRIO (-12) 156 157 int priority_done = 2; /* 0 - Set priority */ 158 /* 1 - priority is OK where it is */ 159 /* 2 - Don't set priority */ 160 /* 1 and 2 are pretty much the same */ 161 162 int listen_to_virtual_ips = TRUE; 163 164 /* 165 * No-fork flag. If set, we do not become a background daemon. 166 */ 167 int nofork; /* Fork by default */ 168 169 #ifdef HAVE_DNSREGISTRATION 170 /* 171 * mDNS registration flag. If set, we attempt to register with the mDNS system, but only 172 * after we have synched the first time. If the attempt fails, then try again once per 173 * minute for up to 5 times. After all, we may be starting before mDNS. 174 */ 175 int mdnsreg = FALSE; 176 int mdnstries = 5; 177 #endif /* HAVE_DNSREGISTRATION */ 178 179 #ifdef HAVE_DROPROOT 180 int droproot; 181 int root_dropped; 182 char *user; /* User to switch to */ 183 char *group; /* group to switch to */ 184 const char *chrootdir; /* directory to chroot to */ 185 uid_t sw_uid; 186 gid_t sw_gid; 187 char *endp; 188 struct group *gr; 189 struct passwd *pw; 190 #endif /* HAVE_DROPROOT */ 191 192 #ifdef HAVE_WORKING_FORK 193 int waitsync_fd_to_close = -1; /* -w/--wait-sync */ 194 #endif 195 196 /* 197 * Version declaration 198 */ 199 extern const char *Version; 200 201 char const *progname; 202 203 int was_alarmed; 204 205 #ifdef DECL_SYSCALL 206 /* 207 * We put this here, since the argument profile is syscall-specific 208 */ 209 extern int syscall (int, ...); 210 #endif /* DECL_SYSCALL */ 211 212 213 #if !defined(SIM) && defined(SIGDIE1) 214 static volatile int signalled = 0; 215 static volatile int signo = 0; 216 217 /* In an ideal world, 'finish_safe()' would declared as noreturn... */ 218 static void finish_safe (int); 219 static RETSIGTYPE finish (int); 220 #endif 221 222 #if !defined(SIM) && defined(HAVE_WORKING_FORK) 223 static int wait_child_sync_if (int, long); 224 #endif 225 226 #if !defined(SIM) && !defined(SYS_WINNT) 227 # ifdef DEBUG 228 static RETSIGTYPE moredebug (int); 229 static RETSIGTYPE lessdebug (int); 230 # else /* !DEBUG follows */ 231 static RETSIGTYPE no_debug (int); 232 # endif /* !DEBUG */ 233 #endif /* !SIM && !SYS_WINNT */ 234 235 #ifndef WORK_FORK 236 int saved_argc; 237 char ** saved_argv; 238 #endif 239 240 #ifndef SIM 241 int ntpdmain (int, char **); 242 static void set_process_priority (void); 243 static void assertion_failed (const char *, int, 244 isc_assertiontype_t, 245 const char *) 246 __attribute__ ((__noreturn__)); 247 static void library_fatal_error (const char *, int, 248 const char *, va_list) 249 ISC_FORMAT_PRINTF(3, 0); 250 static void library_unexpected_error(const char *, int, 251 const char *, va_list) 252 ISC_FORMAT_PRINTF(3, 0); 253 #endif /* !SIM */ 254 255 256 /* Bug2332 unearthed a problem in the interaction of reduced user 257 * privileges, the limits on memory usage and some versions of the 258 * pthread library on Linux systems. The 'pthread_cancel()' function and 259 * likely some others need to track the stack of the thread involved, 260 * and uses a function that comes from GCC (--> libgcc_s.so) to do 261 * this. Unfortunately the developers of glibc decided to load the 262 * library on demand, which speeds up program start but can cause 263 * trouble here: Due to all the things NTPD does to limit its resource 264 * usage, this deferred load of libgcc_s does not always work once the 265 * restrictions are in effect. 266 * 267 * One way out of this was attempting a forced link against libgcc_s 268 * when possible because it makes the library available immediately 269 * without deferred load. (The symbol resolution would still be dynamic 270 * and on demand, but the code would already be in the process image.) 271 * 272 * This is a tricky thing to do, since it's not necessary everywhere, 273 * not possible everywhere, has shown to break the build of other 274 * programs in the NTP suite and is now generally frowned upon. 275 * 276 * So we take a different approach here: We creat a worker thread that does 277 * actually nothing except waiting for cancellation and cancel it. If 278 * this is done before all the limitations are put in place, the 279 * machinery is pre-heated and all the runtime stuff should be in place 280 * and useable when needed. 281 * 282 * This uses only the standard pthread API and should work with all 283 * implementations of pthreads. It is not necessary everywhere, but it's 284 * cheap enough to go on nearly unnoticed. 285 * 286 * Addendum: Bug 2954 showed that the assumption that this should work 287 * with all OS is wrong -- at least FreeBSD bombs heavily. 288 */ 289 #ifdef NEED_PTHREAD_WARMUP 290 291 /* simple thread function: sleep until cancelled, just to exercise 292 * thread cancellation. 293 */ 294 static void* 295 my_pthread_warmup_worker( 296 void *thread_args) 297 { 298 (void)thread_args; 299 for (;;) 300 sleep(10); 301 return NULL; 302 } 303 304 /* pre-heat threading: create a thread and cancel it, just to exercise 305 * thread cancellation. 306 */ 307 static void 308 my_pthread_warmup(void) 309 { 310 pthread_t thread; 311 pthread_attr_t thr_attr; 312 int rc; 313 314 pthread_attr_init(&thr_attr); 315 #if defined(HAVE_PTHREAD_ATTR_GETSTACKSIZE) && \ 316 defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && \ 317 defined(PTHREAD_STACK_MIN) 318 rc = pthread_attr_setstacksize(&thr_attr, PTHREAD_STACK_MIN); 319 if (0 != rc) 320 msyslog(LOG_ERR, 321 "my_pthread_warmup: pthread_attr_setstacksize() -> %s", 322 strerror(rc)); 323 #endif 324 rc = pthread_create( 325 &thread, &thr_attr, my_pthread_warmup_worker, NULL); 326 pthread_attr_destroy(&thr_attr); 327 if (0 != rc) { 328 msyslog(LOG_ERR, 329 "my_pthread_warmup: pthread_create() -> %s", 330 strerror(rc)); 331 } else { 332 pthread_cancel(thread); 333 pthread_join(thread, NULL); 334 } 335 } 336 337 #endif /*defined(NEED_PTHREAD_WARMUP)*/ 338 339 #ifdef NEED_EARLY_FORK 340 static void 341 dummy_callback(void) { return; } 342 343 static void 344 fork_nonchroot_worker(void) { 345 getaddrinfo_sometime("localhost", "ntp", NULL, INITIAL_DNS_RETRY, 346 (gai_sometime_callback)&dummy_callback, NULL); 347 } 348 #endif /* NEED_EARLY_FORK */ 349 350 void 351 parse_cmdline_opts( 352 int * pargc, 353 char ***pargv 354 ) 355 { 356 static int parsed; 357 static int optct; 358 359 if (!parsed) 360 optct = ntpOptionProcess(&ntpdOptions, *pargc, *pargv); 361 362 parsed = 1; 363 364 *pargc -= optct; 365 *pargv += optct; 366 } 367 368 369 #ifdef SIM 370 int 371 main( 372 int argc, 373 char *argv[] 374 ) 375 { 376 progname = argv[0]; 377 parse_cmdline_opts(&argc, &argv); 378 #ifdef DEBUG 379 debug = OPT_VALUE_SET_DEBUG_LEVEL; 380 DPRINTF(1, ("%s\n", Version)); 381 #endif 382 383 return ntpsim(argc, argv); 384 } 385 #else /* !SIM follows */ 386 #ifdef NO_MAIN_ALLOWED 387 CALL(ntpd,"ntpd",ntpdmain); 388 #else /* !NO_MAIN_ALLOWED follows */ 389 #ifndef SYS_WINNT 390 int 391 main( 392 int argc, 393 char *argv[] 394 ) 395 { 396 return ntpdmain(argc, argv); 397 } 398 #endif /* !SYS_WINNT */ 399 #endif /* !NO_MAIN_ALLOWED */ 400 #endif /* !SIM */ 401 402 #ifdef _AIX 403 /* 404 * OK. AIX is different than solaris in how it implements plock(). 405 * If you do NOT adjust the stack limit, you will get the MAXIMUM 406 * stack size allocated and PINNED with you program. To check the 407 * value, use ulimit -a. 408 * 409 * To fix this, we create an automatic variable and set our stack limit 410 * to that PLUS 32KB of extra space (we need some headroom). 411 * 412 * This subroutine gets the stack address. 413 * 414 * Grover Davidson and Matt Ladendorf 415 * 416 */ 417 static char * 418 get_aix_stack(void) 419 { 420 char ch; 421 return (&ch); 422 } 423 424 /* 425 * Signal handler for SIGDANGER. 426 */ 427 static void 428 catch_danger(int signo) 429 { 430 msyslog(LOG_INFO, "ntpd: setpgid(): %m"); 431 /* Make the system believe we'll free something, but don't do it! */ 432 return; 433 } 434 #endif /* _AIX */ 435 436 /* 437 * Set the process priority 438 */ 439 #ifndef SIM 440 static void 441 set_process_priority(void) 442 { 443 444 # ifdef DEBUG 445 if (debug > 1) 446 msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>", 447 ((priority_done) 448 ? "Leave priority alone" 449 : "Attempt to set priority" 450 ), 451 priority_done); 452 # endif /* DEBUG */ 453 454 # if defined(HAVE_SCHED_SETSCHEDULER) 455 if (!priority_done) { 456 extern int config_priority_override, config_priority; 457 int pmax, pmin; 458 struct sched_param sched; 459 460 pmax = sched_get_priority_max(SCHED_FIFO); 461 sched.sched_priority = pmax; 462 if ( config_priority_override ) { 463 pmin = sched_get_priority_min(SCHED_FIFO); 464 if ( config_priority > pmax ) 465 sched.sched_priority = pmax; 466 else if ( config_priority < pmin ) 467 sched.sched_priority = pmin; 468 else 469 sched.sched_priority = config_priority; 470 } 471 if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 ) 472 msyslog(LOG_ERR, "sched_setscheduler(): %m"); 473 else 474 ++priority_done; 475 } 476 # endif /* HAVE_SCHED_SETSCHEDULER */ 477 # ifdef HAVE_RTPRIO 478 # ifdef RTP_SET 479 if (!priority_done) { 480 struct rtprio srtp; 481 482 srtp.type = RTP_PRIO_REALTIME; /* was: RTP_PRIO_NORMAL */ 483 srtp.prio = 0; /* 0 (hi) -> RTP_PRIO_MAX (31,lo) */ 484 485 if (rtprio(RTP_SET, getpid(), &srtp) < 0) 486 msyslog(LOG_ERR, "rtprio() error: %m"); 487 else 488 ++priority_done; 489 } 490 # else /* !RTP_SET follows */ 491 if (!priority_done) { 492 if (rtprio(0, 120) < 0) 493 msyslog(LOG_ERR, "rtprio() error: %m"); 494 else 495 ++priority_done; 496 } 497 # endif /* !RTP_SET */ 498 # endif /* HAVE_RTPRIO */ 499 # if defined(NTPD_PRIO) && NTPD_PRIO != 0 500 # ifdef HAVE_ATT_NICE 501 if (!priority_done) { 502 errno = 0; 503 if (-1 == nice (NTPD_PRIO) && errno != 0) 504 msyslog(LOG_ERR, "nice() error: %m"); 505 else 506 ++priority_done; 507 } 508 # endif /* HAVE_ATT_NICE */ 509 # ifdef HAVE_BSD_NICE 510 if (!priority_done) { 511 if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO)) 512 msyslog(LOG_ERR, "setpriority() error: %m"); 513 else 514 ++priority_done; 515 } 516 # endif /* HAVE_BSD_NICE */ 517 # endif /* NTPD_PRIO && NTPD_PRIO != 0 */ 518 if (!priority_done) 519 msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority"); 520 } 521 #endif /* !SIM */ 522 523 524 /* 525 * Main program. Initialize us, disconnect us from the tty if necessary, 526 * and loop waiting for I/O and/or timer expiries. 527 */ 528 #ifndef SIM 529 int 530 ntpdmain( 531 int argc, 532 char *argv[] 533 ) 534 { 535 l_fp now; 536 struct recvbuf *rbuf; 537 const char * logfilename; 538 # ifdef HAVE_UMASK 539 mode_t uv; 540 # endif 541 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */ 542 uid_t uid; 543 # endif 544 # if defined(HAVE_WORKING_FORK) 545 long wait_sync = 0; 546 int pipe_fds[2]; 547 int rc; 548 int exit_code; 549 # ifdef _AIX 550 struct sigaction sa; 551 # endif 552 # if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY) 553 int fid; 554 # endif 555 # endif /* HAVE_WORKING_FORK*/ 556 # ifdef SCO5_CLOCK 557 int fd; 558 int zero; 559 # endif 560 561 # ifdef NEED_PTHREAD_WARMUP 562 my_pthread_warmup(); 563 # endif 564 565 # ifdef HAVE_UMASK 566 uv = umask(0); 567 if (uv) 568 umask(uv); 569 else 570 umask(022); 571 # endif 572 saved_argc = argc; 573 saved_argv = argv; 574 progname = argv[0]; 575 initializing = TRUE; /* mark that we are initializing */ 576 parse_cmdline_opts(&argc, &argv); 577 # ifdef DEBUG 578 debug = OPT_VALUE_SET_DEBUG_LEVEL; 579 # ifdef HAVE_SETLINEBUF 580 setlinebuf(stdout); 581 # endif 582 # endif 583 584 if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT) 585 # ifdef DEBUG 586 || debug 587 # endif 588 || HAVE_OPT(SAVECONFIGQUIT)) 589 nofork = TRUE; 590 591 init_logging(progname, NLOG_SYNCMASK, TRUE); 592 /* honor -l/--logfile option to log to a file */ 593 if (HAVE_OPT(LOGFILE)) { 594 logfilename = OPT_ARG(LOGFILE); 595 syslogit = FALSE; 596 change_logfile(logfilename, FALSE); 597 } else { 598 logfilename = NULL; 599 if (nofork) 600 msyslog_term = TRUE; 601 if (HAVE_OPT(SAVECONFIGQUIT)) 602 syslogit = FALSE; 603 } 604 msyslog(LOG_NOTICE, "%s: Starting", Version); 605 606 { 607 int i; 608 char buf[1024]; /* Secret knowledge of msyslog buf length */ 609 char *cp = buf; 610 611 /* Note that every arg has an initial space character */ 612 snprintf(cp, sizeof(buf), "Command line:"); 613 cp += strlen(cp); 614 615 for (i = 0; i < saved_argc ; ++i) { 616 snprintf(cp, sizeof(buf) - (cp - buf), 617 " %s", saved_argv[i]); 618 cp += strlen(cp); 619 } 620 msyslog(LOG_INFO, "%s", buf); 621 } 622 623 /* 624 * Install trap handlers to log errors and assertion failures. 625 * Default handlers print to stderr which doesn't work if detached. 626 */ 627 isc_assertion_setcallback(assertion_failed); 628 isc_error_setfatal(library_fatal_error); 629 isc_error_setunexpected(library_unexpected_error); 630 631 /* MPE lacks the concept of root */ 632 # if defined(HAVE_GETUID) && !defined(MPE) 633 uid = getuid(); 634 if (uid && !HAVE_OPT( SAVECONFIGQUIT )) { 635 msyslog_term = TRUE; 636 msyslog(LOG_ERR, 637 "must be run as root, not uid %ld", (long)uid); 638 exit(1); 639 } 640 # endif 641 642 /* 643 * Enable the Multi-Media Timer for Windows? 644 */ 645 # ifdef SYS_WINNT 646 if (HAVE_OPT( MODIFYMMTIMER )) 647 set_mm_timer(MM_TIMER_HIRES); 648 # endif 649 650 #ifdef HAVE_DNSREGISTRATION 651 /* 652 * Enable mDNS registrations? 653 */ 654 if (HAVE_OPT( MDNS )) { 655 mdnsreg = TRUE; 656 } 657 #endif /* HAVE_DNSREGISTRATION */ 658 659 if (HAVE_OPT( NOVIRTUALIPS )) 660 listen_to_virtual_ips = 0; 661 662 /* 663 * --interface, listen on specified interfaces 664 */ 665 if (HAVE_OPT( INTERFACE )) { 666 int ifacect = STACKCT_OPT( INTERFACE ); 667 const char** ifaces = STACKLST_OPT( INTERFACE ); 668 sockaddr_u addr; 669 670 while (ifacect-- > 0) { 671 add_nic_rule( 672 is_ip_address(*ifaces, AF_UNSPEC, &addr) 673 ? MATCH_IFADDR 674 : MATCH_IFNAME, 675 *ifaces, -1, ACTION_LISTEN); 676 ifaces++; 677 } 678 } 679 680 if (HAVE_OPT( NICE )) 681 priority_done = 0; 682 683 # ifdef HAVE_SCHED_SETSCHEDULER 684 if (HAVE_OPT( PRIORITY )) { 685 config_priority = OPT_VALUE_PRIORITY; 686 config_priority_override = 1; 687 priority_done = 0; 688 } 689 # endif 690 691 # ifdef HAVE_WORKING_FORK 692 /* make sure the FDs are initialised */ 693 pipe_fds[0] = -1; 694 pipe_fds[1] = -1; 695 do { /* 'loop' once */ 696 if (!HAVE_OPT( WAIT_SYNC )) 697 break; 698 wait_sync = OPT_VALUE_WAIT_SYNC; 699 if (wait_sync <= 0) { 700 wait_sync = 0; 701 break; 702 } 703 /* -w requires a fork() even with debug > 0 */ 704 nofork = FALSE; 705 if (pipe(pipe_fds)) { 706 exit_code = (errno) ? errno : -1; 707 msyslog(LOG_ERR, 708 "Pipe creation failed for --wait-sync: %m"); 709 exit(exit_code); 710 } 711 waitsync_fd_to_close = pipe_fds[1]; 712 } while (0); /* 'loop' once */ 713 # endif /* HAVE_WORKING_FORK */ 714 715 init_lib(); 716 # ifdef SYS_WINNT 717 /* 718 * Start interpolation thread, must occur before first 719 * get_systime() 720 */ 721 init_winnt_time(); 722 # endif 723 /* 724 * Initialize random generator and public key pair 725 */ 726 get_systime(&now); 727 728 ntp_srandom((int)(now.l_i * now.l_uf)); 729 730 /* 731 * Detach us from the terminal. May need an #ifndef GIZMO. 732 */ 733 if (!nofork) { 734 735 # ifdef HAVE_WORKING_FORK 736 rc = fork(); 737 if (-1 == rc) { 738 exit_code = (errno) ? errno : -1; 739 msyslog(LOG_ERR, "fork: %m"); 740 exit(exit_code); 741 } 742 if (rc > 0) { 743 /* parent */ 744 exit_code = wait_child_sync_if(pipe_fds[0], 745 wait_sync); 746 exit(exit_code); 747 } 748 749 /* 750 * child/daemon 751 * close all open files excepting waitsync_fd_to_close. 752 * msyslog() unreliable until after init_logging(). 753 */ 754 closelog(); 755 if (syslog_file != NULL) { 756 fclose(syslog_file); 757 syslog_file = NULL; 758 syslogit = TRUE; 759 } 760 close_all_except(waitsync_fd_to_close); 761 INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \ 762 && 2 == dup2(0, 2)); 763 764 init_logging(progname, 0, TRUE); 765 /* we lost our logfile (if any) daemonizing */ 766 setup_logfile(logfilename); 767 768 # ifdef SYS_DOMAINOS 769 { 770 uid_$t puid; 771 status_$t st; 772 773 proc2_$who_am_i(&puid); 774 proc2_$make_server(&puid, &st); 775 } 776 # endif /* SYS_DOMAINOS */ 777 # ifdef HAVE_SETSID 778 if (setsid() == (pid_t)-1) 779 msyslog(LOG_ERR, "setsid(): %m"); 780 # elif defined(HAVE_SETPGID) 781 if (setpgid(0, 0) == -1) 782 msyslog(LOG_ERR, "setpgid(): %m"); 783 # else /* !HAVE_SETSID && !HAVE_SETPGID follows */ 784 # ifdef TIOCNOTTY 785 fid = open("/dev/tty", 2); 786 if (fid >= 0) { 787 ioctl(fid, (u_long)TIOCNOTTY, NULL); 788 close(fid); 789 } 790 # endif /* TIOCNOTTY */ 791 ntp_setpgrp(0, getpid()); 792 # endif /* !HAVE_SETSID && !HAVE_SETPGID */ 793 # ifdef _AIX 794 /* Don't get killed by low-on-memory signal. */ 795 sa.sa_handler = catch_danger; 796 sigemptyset(&sa.sa_mask); 797 sa.sa_flags = SA_RESTART; 798 sigaction(SIGDANGER, &sa, NULL); 799 # endif /* _AIX */ 800 # endif /* HAVE_WORKING_FORK */ 801 } 802 803 # ifdef SCO5_CLOCK 804 /* 805 * SCO OpenServer's system clock offers much more precise timekeeping 806 * on the base CPU than the other CPUs (for multiprocessor systems), 807 * so we must lock to the base CPU. 808 */ 809 fd = open("/dev/at1", O_RDONLY); 810 if (fd >= 0) { 811 zero = 0; 812 if (ioctl(fd, ACPU_LOCK, &zero) < 0) 813 msyslog(LOG_ERR, "cannot lock to base CPU: %m"); 814 close(fd); 815 } 816 # endif 817 818 /* Setup stack size in preparation for locking pages in memory. */ 819 # if defined(HAVE_MLOCKALL) 820 # ifdef HAVE_SETRLIMIT 821 ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k"); 822 # ifdef RLIMIT_MEMLOCK 823 /* 824 * The default RLIMIT_MEMLOCK is very low on Linux systems. 825 * Unless we increase this limit malloc calls are likely to 826 * fail if we drop root privilege. To be useful the value 827 * has to be larger than the largest ntpd resident set size. 828 */ 829 ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB"); 830 # endif /* RLIMIT_MEMLOCK */ 831 # endif /* HAVE_SETRLIMIT */ 832 # else /* !HAVE_MLOCKALL follows */ 833 # ifdef HAVE_PLOCK 834 # ifdef PROCLOCK 835 # ifdef _AIX 836 /* 837 * set the stack limit for AIX for plock(). 838 * see get_aix_stack() for more info. 839 */ 840 if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0) 841 msyslog(LOG_ERR, 842 "Cannot adjust stack limit for plock: %m"); 843 # endif /* _AIX */ 844 # endif /* PROCLOCK */ 845 # endif /* HAVE_PLOCK */ 846 # endif /* !HAVE_MLOCKALL */ 847 848 /* 849 * Set up signals we pay attention to locally. 850 */ 851 # ifdef SIGDIE1 852 signal_no_reset(SIGDIE1, finish); 853 signal_no_reset(SIGDIE2, finish); 854 signal_no_reset(SIGDIE3, finish); 855 signal_no_reset(SIGDIE4, finish); 856 # endif 857 # ifdef SIGBUS 858 signal_no_reset(SIGBUS, finish); 859 # endif 860 861 # if !defined(SYS_WINNT) && !defined(VMS) 862 # ifdef DEBUG 863 (void) signal_no_reset(MOREDEBUGSIG, moredebug); 864 (void) signal_no_reset(LESSDEBUGSIG, lessdebug); 865 # else 866 (void) signal_no_reset(MOREDEBUGSIG, no_debug); 867 (void) signal_no_reset(LESSDEBUGSIG, no_debug); 868 # endif /* DEBUG */ 869 # endif /* !SYS_WINNT && !VMS */ 870 871 /* 872 * Set up signals we should never pay attention to. 873 */ 874 # ifdef SIGPIPE 875 signal_no_reset(SIGPIPE, SIG_IGN); 876 # endif 877 878 /* 879 * Call the init_ routines to initialize the data structures. 880 * 881 * Exactly what command-line options are we expecting here? 882 */ 883 INIT_SSL(); 884 init_auth(); 885 init_util(); 886 init_restrict(); 887 init_mon(); 888 init_timer(); 889 init_request(); 890 init_control(); 891 init_peer(); 892 # ifdef REFCLOCK 893 init_refclock(); 894 # endif 895 set_process_priority(); 896 init_proto(); /* Call at high priority */ 897 init_io(); 898 init_loopfilter(); 899 mon_start(MON_ON); /* monitor on by default now */ 900 /* turn off in config if unwanted */ 901 902 /* 903 * Get the configuration. This is done in a separate module 904 * since this will definitely be different for the gizmo board. 905 */ 906 getconfig(argc, argv); 907 908 if (-1 == cur_memlock) { 909 # if defined(HAVE_MLOCKALL) 910 /* 911 * lock the process into memory 912 */ 913 if ( !HAVE_OPT(SAVECONFIGQUIT) 914 # ifdef RLIMIT_MEMLOCK 915 && -1 != DFLT_RLIMIT_MEMLOCK 916 # endif 917 && 0 != mlockall(MCL_CURRENT|MCL_FUTURE)) 918 msyslog(LOG_ERR, "mlockall(): %m"); 919 # else /* !HAVE_MLOCKALL follows */ 920 # ifdef HAVE_PLOCK 921 # ifdef PROCLOCK 922 /* 923 * lock the process into memory 924 */ 925 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK)) 926 msyslog(LOG_ERR, "plock(PROCLOCK): %m"); 927 # else /* !PROCLOCK follows */ 928 # ifdef TXTLOCK 929 /* 930 * Lock text into ram 931 */ 932 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK)) 933 msyslog(LOG_ERR, "plock(TXTLOCK) error: %m"); 934 # else /* !TXTLOCK follows */ 935 msyslog(LOG_ERR, "plock() - don't know what to lock!"); 936 # endif /* !TXTLOCK */ 937 # endif /* !PROCLOCK */ 938 # endif /* HAVE_PLOCK */ 939 # endif /* !HAVE_MLOCKALL */ 940 } 941 942 loop_config(LOOP_DRIFTINIT, 0); 943 report_event(EVNT_SYSRESTART, NULL, NULL); 944 initializing = FALSE; 945 946 # ifdef HAVE_DROPROOT 947 if (droproot) { 948 949 #ifdef NEED_EARLY_FORK 950 fork_nonchroot_worker(); 951 #endif 952 953 /* Drop super-user privileges and chroot now if the OS supports this */ 954 955 # ifdef HAVE_LINUX_CAPABILITIES 956 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */ 957 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) { 958 msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" ); 959 exit(-1); 960 } 961 # elif HAVE_SOLARIS_PRIVS 962 /* Nothing to do here */ 963 # else 964 /* we need a user to switch to */ 965 if (user == NULL) { 966 msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" ); 967 exit(-1); 968 } 969 # endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */ 970 971 if (user != NULL) { 972 if (isdigit((unsigned char)*user)) { 973 sw_uid = (uid_t)strtoul(user, &endp, 0); 974 if (*endp != '\0') 975 goto getuser; 976 977 if ((pw = getpwuid(sw_uid)) != NULL) { 978 free(user); 979 user = estrdup(pw->pw_name); 980 sw_gid = pw->pw_gid; 981 } else { 982 errno = 0; 983 msyslog(LOG_ERR, "Cannot find user ID %s", user); 984 exit (-1); 985 } 986 987 } else { 988 getuser: 989 errno = 0; 990 if ((pw = getpwnam(user)) != NULL) { 991 sw_uid = pw->pw_uid; 992 sw_gid = pw->pw_gid; 993 } else { 994 if (errno) 995 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user); 996 else 997 msyslog(LOG_ERR, "Cannot find user `%s'", user); 998 exit (-1); 999 } 1000 } 1001 } 1002 if (group != NULL) { 1003 if (isdigit((unsigned char)*group)) { 1004 sw_gid = (gid_t)strtoul(group, &endp, 0); 1005 if (*endp != '\0') 1006 goto getgroup; 1007 } else { 1008 getgroup: 1009 if ((gr = getgrnam(group)) != NULL) { 1010 sw_gid = gr->gr_gid; 1011 } else { 1012 errno = 0; 1013 msyslog(LOG_ERR, "Cannot find group `%s'", group); 1014 exit (-1); 1015 } 1016 } 1017 } 1018 1019 if (chrootdir ) { 1020 /* make sure cwd is inside the jail: */ 1021 if (chdir(chrootdir)) { 1022 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir); 1023 exit (-1); 1024 } 1025 if (chroot(chrootdir)) { 1026 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir); 1027 exit (-1); 1028 } 1029 if (chdir("/")) { 1030 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m"); 1031 exit (-1); 1032 } 1033 } 1034 # ifdef HAVE_SOLARIS_PRIVS 1035 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) { 1036 msyslog(LOG_ERR, "priv_str_to_set() failed:%m"); 1037 exit(-1); 1038 } 1039 if ((highprivs = priv_allocset()) == NULL) { 1040 msyslog(LOG_ERR, "priv_allocset() failed:%m"); 1041 exit(-1); 1042 } 1043 (void) getppriv(PRIV_PERMITTED, highprivs); 1044 (void) priv_intersect(highprivs, lowprivs); 1045 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) { 1046 msyslog(LOG_ERR, "setppriv() failed:%m"); 1047 exit(-1); 1048 } 1049 # endif /* HAVE_SOLARIS_PRIVS */ 1050 if (user && initgroups(user, sw_gid)) { 1051 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user); 1052 exit (-1); 1053 } 1054 if (group && setgid(sw_gid)) { 1055 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group); 1056 exit (-1); 1057 } 1058 if (group && setegid(sw_gid)) { 1059 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group); 1060 exit (-1); 1061 } 1062 if (group) { 1063 if (0 != setgroups(1, &sw_gid)) { 1064 msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid); 1065 exit (-1); 1066 } 1067 } 1068 else if (pw) 1069 if (0 != initgroups(pw->pw_name, pw->pw_gid)) { 1070 msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid); 1071 exit (-1); 1072 } 1073 if (user && setuid(sw_uid)) { 1074 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user); 1075 exit (-1); 1076 } 1077 if (user && seteuid(sw_uid)) { 1078 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user); 1079 exit (-1); 1080 } 1081 1082 # if !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS) 1083 /* 1084 * for now assume that the privilege to bind to privileged ports 1085 * is associated with running with uid 0 - should be refined on 1086 * ports that allow binding to NTP_PORT with uid != 0 1087 */ 1088 disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */ 1089 # endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */ 1090 1091 if (disable_dynamic_updates && interface_interval) { 1092 interface_interval = 0; 1093 msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking"); 1094 } 1095 1096 # ifdef HAVE_LINUX_CAPABILITIES 1097 { 1098 /* 1099 * We may be running under non-root uid now, but we still hold full root privileges! 1100 * We drop all of them, except for the crucial one or two: cap_sys_time and 1101 * cap_net_bind_service if doing dynamic interface tracking. 1102 */ 1103 cap_t caps; 1104 char *captext; 1105 1106 captext = (0 != interface_interval) 1107 ? "cap_sys_time,cap_net_bind_service=pe" 1108 : "cap_sys_time=pe"; 1109 caps = cap_from_text(captext); 1110 if (!caps) { 1111 msyslog(LOG_ERR, 1112 "cap_from_text(%s) failed: %m", 1113 captext); 1114 exit(-1); 1115 } 1116 if (-1 == cap_set_proc(caps)) { 1117 msyslog(LOG_ERR, 1118 "cap_set_proc() failed to drop root privs: %m"); 1119 exit(-1); 1120 } 1121 cap_free(caps); 1122 } 1123 # endif /* HAVE_LINUX_CAPABILITIES */ 1124 # ifdef HAVE_SOLARIS_PRIVS 1125 if (priv_delset(lowprivs, "proc_setid") == -1) { 1126 msyslog(LOG_ERR, "priv_delset() failed:%m"); 1127 exit(-1); 1128 } 1129 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) { 1130 msyslog(LOG_ERR, "setppriv() failed:%m"); 1131 exit(-1); 1132 } 1133 priv_freeset(lowprivs); 1134 priv_freeset(highprivs); 1135 # endif /* HAVE_SOLARIS_PRIVS */ 1136 root_dropped = TRUE; 1137 fork_deferred_worker(); 1138 } /* if (droproot) */ 1139 # endif /* HAVE_DROPROOT */ 1140 1141 /* libssecomp sandboxing */ 1142 #if defined (LIBSECCOMP) && (KERN_SECCOMP) 1143 scmp_filter_ctx ctx; 1144 1145 if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0) 1146 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__); 1147 else { 1148 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__); 1149 } 1150 1151 #ifdef __x86_64__ 1152 int scmp_sc[] = { 1153 SCMP_SYS(adjtimex), 1154 SCMP_SYS(bind), 1155 SCMP_SYS(brk), 1156 SCMP_SYS(chdir), 1157 SCMP_SYS(clock_gettime), 1158 SCMP_SYS(clock_settime), 1159 SCMP_SYS(close), 1160 SCMP_SYS(connect), 1161 SCMP_SYS(exit_group), 1162 SCMP_SYS(fstat), 1163 SCMP_SYS(fsync), 1164 SCMP_SYS(futex), 1165 SCMP_SYS(getitimer), 1166 SCMP_SYS(getsockname), 1167 SCMP_SYS(ioctl), 1168 SCMP_SYS(lseek), 1169 SCMP_SYS(madvise), 1170 SCMP_SYS(mmap), 1171 SCMP_SYS(munmap), 1172 SCMP_SYS(open), 1173 SCMP_SYS(poll), 1174 SCMP_SYS(read), 1175 SCMP_SYS(recvmsg), 1176 SCMP_SYS(rename), 1177 SCMP_SYS(rt_sigaction), 1178 SCMP_SYS(rt_sigprocmask), 1179 SCMP_SYS(rt_sigreturn), 1180 SCMP_SYS(select), 1181 SCMP_SYS(sendto), 1182 SCMP_SYS(setitimer), 1183 SCMP_SYS(setsid), 1184 SCMP_SYS(socket), 1185 SCMP_SYS(stat), 1186 SCMP_SYS(time), 1187 SCMP_SYS(write), 1188 }; 1189 #endif 1190 #ifdef __i386__ 1191 int scmp_sc[] = { 1192 SCMP_SYS(_newselect), 1193 SCMP_SYS(adjtimex), 1194 SCMP_SYS(brk), 1195 SCMP_SYS(chdir), 1196 SCMP_SYS(clock_gettime), 1197 SCMP_SYS(clock_settime), 1198 SCMP_SYS(close), 1199 SCMP_SYS(exit_group), 1200 SCMP_SYS(fsync), 1201 SCMP_SYS(futex), 1202 SCMP_SYS(getitimer), 1203 SCMP_SYS(madvise), 1204 SCMP_SYS(mmap), 1205 SCMP_SYS(mmap2), 1206 SCMP_SYS(munmap), 1207 SCMP_SYS(open), 1208 SCMP_SYS(poll), 1209 SCMP_SYS(read), 1210 SCMP_SYS(rename), 1211 SCMP_SYS(rt_sigaction), 1212 SCMP_SYS(rt_sigprocmask), 1213 SCMP_SYS(select), 1214 SCMP_SYS(setitimer), 1215 SCMP_SYS(setsid), 1216 SCMP_SYS(sigprocmask), 1217 SCMP_SYS(sigreturn), 1218 SCMP_SYS(socketcall), 1219 SCMP_SYS(stat64), 1220 SCMP_SYS(time), 1221 SCMP_SYS(write), 1222 }; 1223 #endif 1224 { 1225 int i; 1226 1227 for (i = 0; i < COUNTOF(scmp_sc); i++) { 1228 if (seccomp_rule_add(ctx, 1229 SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) { 1230 msyslog(LOG_ERR, 1231 "%s: seccomp_rule_add() failed: %m", 1232 __func__); 1233 } 1234 } 1235 } 1236 1237 if (seccomp_load(ctx) < 0) 1238 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m", 1239 __func__); 1240 else { 1241 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__); 1242 } 1243 #endif /* LIBSECCOMP and KERN_SECCOMP */ 1244 1245 # ifdef HAVE_IO_COMPLETION_PORT 1246 1247 for (;;) { 1248 #if !defined(SIM) && defined(SIGDIE1) 1249 if (signalled) 1250 finish_safe(signo); 1251 #endif 1252 GetReceivedBuffers(); 1253 # else /* normal I/O */ 1254 1255 BLOCK_IO_AND_ALARM(); 1256 was_alarmed = FALSE; 1257 1258 for (;;) { 1259 #if !defined(SIM) && defined(SIGDIE1) 1260 if (signalled) 1261 finish_safe(signo); 1262 #endif 1263 if (alarm_flag) { /* alarmed? */ 1264 was_alarmed = TRUE; 1265 alarm_flag = FALSE; 1266 } 1267 1268 /* collect async name/addr results */ 1269 if (!was_alarmed) 1270 harvest_blocking_responses(); 1271 1272 if (!was_alarmed && !has_full_recv_buffer()) { 1273 /* 1274 * Nothing to do. Wait for something. 1275 */ 1276 io_handler(); 1277 } 1278 1279 if (alarm_flag) { /* alarmed? */ 1280 was_alarmed = TRUE; 1281 alarm_flag = FALSE; 1282 } 1283 1284 if (was_alarmed) { 1285 UNBLOCK_IO_AND_ALARM(); 1286 /* 1287 * Out here, signals are unblocked. Call timer routine 1288 * to process expiry. 1289 */ 1290 timer(); 1291 was_alarmed = FALSE; 1292 BLOCK_IO_AND_ALARM(); 1293 } 1294 1295 # endif /* !HAVE_IO_COMPLETION_PORT */ 1296 1297 # ifdef DEBUG_TIMING 1298 { 1299 l_fp pts; 1300 l_fp tsa, tsb; 1301 int bufcount = 0; 1302 1303 get_systime(&pts); 1304 tsa = pts; 1305 # endif 1306 rbuf = get_full_recv_buffer(); 1307 while (rbuf != NULL) { 1308 if (alarm_flag) { 1309 was_alarmed = TRUE; 1310 alarm_flag = FALSE; 1311 } 1312 UNBLOCK_IO_AND_ALARM(); 1313 1314 if (was_alarmed) { 1315 /* avoid timer starvation during lengthy I/O handling */ 1316 timer(); 1317 was_alarmed = FALSE; 1318 } 1319 1320 /* 1321 * Call the data procedure to handle each received 1322 * packet. 1323 */ 1324 if (rbuf->receiver != NULL) { 1325 # ifdef DEBUG_TIMING 1326 l_fp dts = pts; 1327 1328 L_SUB(&dts, &rbuf->recv_time); 1329 DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9))); 1330 collect_timing(rbuf, "buffer processing delay", 1, &dts); 1331 bufcount++; 1332 # endif 1333 (*rbuf->receiver)(rbuf); 1334 } else { 1335 msyslog(LOG_ERR, "fatal: receive buffer callback NULL"); 1336 abort(); 1337 } 1338 1339 BLOCK_IO_AND_ALARM(); 1340 freerecvbuf(rbuf); 1341 rbuf = get_full_recv_buffer(); 1342 } 1343 # ifdef DEBUG_TIMING 1344 get_systime(&tsb); 1345 L_SUB(&tsb, &tsa); 1346 if (bufcount) { 1347 collect_timing(NULL, "processing", bufcount, &tsb); 1348 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9))); 1349 } 1350 } 1351 # endif 1352 1353 /* 1354 * Go around again 1355 */ 1356 1357 # ifdef HAVE_DNSREGISTRATION 1358 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) { 1359 mdnsreg = current_time; 1360 msyslog(LOG_INFO, "Attempting to register mDNS"); 1361 if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL, 1362 htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) { 1363 if (!--mdnstries) { 1364 msyslog(LOG_ERR, "Unable to register mDNS, giving up."); 1365 } else { 1366 msyslog(LOG_INFO, "Unable to register mDNS, will try later."); 1367 } 1368 } else { 1369 msyslog(LOG_INFO, "mDNS service registered."); 1370 mdnsreg = FALSE; 1371 } 1372 } 1373 # endif /* HAVE_DNSREGISTRATION */ 1374 1375 } 1376 UNBLOCK_IO_AND_ALARM(); 1377 return 1; 1378 } 1379 #endif /* !SIM */ 1380 1381 1382 #if !defined(SIM) && defined(SIGDIE1) 1383 /* 1384 * finish - exit gracefully 1385 */ 1386 static void 1387 finish_safe( 1388 int sig 1389 ) 1390 { 1391 const char *sig_desc; 1392 1393 sig_desc = NULL; 1394 #ifdef HAVE_STRSIGNAL 1395 sig_desc = strsignal(sig); 1396 #endif 1397 if (sig_desc == NULL) 1398 sig_desc = ""; 1399 msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname, 1400 sig, sig_desc); 1401 /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */ 1402 # ifdef HAVE_DNSREGISTRATION 1403 if (mdns != NULL) 1404 DNSServiceRefDeallocate(mdns); 1405 # endif 1406 peer_cleanup(); 1407 exit(0); 1408 } 1409 1410 static RETSIGTYPE 1411 finish( 1412 int sig 1413 ) 1414 { 1415 signalled = 1; 1416 signo = sig; 1417 } 1418 1419 #endif /* !SIM && SIGDIE1 */ 1420 1421 1422 #ifndef SIM 1423 /* 1424 * wait_child_sync_if - implements parent side of -w/--wait-sync 1425 */ 1426 # ifdef HAVE_WORKING_FORK 1427 static int 1428 wait_child_sync_if( 1429 int pipe_read_fd, 1430 long wait_sync 1431 ) 1432 { 1433 int rc; 1434 int exit_code; 1435 time_t wait_end_time; 1436 time_t cur_time; 1437 time_t wait_rem; 1438 fd_set readset; 1439 struct timeval wtimeout; 1440 1441 if (0 == wait_sync) 1442 return 0; 1443 1444 /* waitsync_fd_to_close used solely by child */ 1445 close(waitsync_fd_to_close); 1446 wait_end_time = time(NULL) + wait_sync; 1447 do { 1448 cur_time = time(NULL); 1449 wait_rem = (wait_end_time > cur_time) 1450 ? (wait_end_time - cur_time) 1451 : 0; 1452 wtimeout.tv_sec = wait_rem; 1453 wtimeout.tv_usec = 0; 1454 FD_ZERO(&readset); 1455 FD_SET(pipe_read_fd, &readset); 1456 rc = select(pipe_read_fd + 1, &readset, NULL, NULL, 1457 &wtimeout); 1458 if (-1 == rc) { 1459 if (EINTR == errno) 1460 continue; 1461 exit_code = (errno) ? errno : -1; 1462 msyslog(LOG_ERR, 1463 "--wait-sync select failed: %m"); 1464 return exit_code; 1465 } 1466 if (0 == rc) { 1467 /* 1468 * select() indicated a timeout, but in case 1469 * its timeouts are affected by a step of the 1470 * system clock, select() again with a zero 1471 * timeout to confirm. 1472 */ 1473 FD_ZERO(&readset); 1474 FD_SET(pipe_read_fd, &readset); 1475 wtimeout.tv_sec = 0; 1476 wtimeout.tv_usec = 0; 1477 rc = select(pipe_read_fd + 1, &readset, NULL, 1478 NULL, &wtimeout); 1479 if (0 == rc) /* select() timeout */ 1480 break; 1481 else /* readable */ 1482 return 0; 1483 } else /* readable */ 1484 return 0; 1485 } while (wait_rem > 0); 1486 1487 fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n", 1488 progname, wait_sync); 1489 return ETIMEDOUT; 1490 } 1491 # endif /* HAVE_WORKING_FORK */ 1492 1493 1494 /* 1495 * assertion_failed - Redirect assertion failures to msyslog(). 1496 */ 1497 static void 1498 assertion_failed( 1499 const char *file, 1500 int line, 1501 isc_assertiontype_t type, 1502 const char *cond 1503 ) 1504 { 1505 isc_assertion_setcallback(NULL); /* Avoid recursion */ 1506 1507 msyslog(LOG_ERR, "%s:%d: %s(%s) failed", 1508 file, line, isc_assertion_typetotext(type), cond); 1509 msyslog(LOG_ERR, "exiting (due to assertion failure)"); 1510 1511 #if defined(DEBUG) && defined(SYS_WINNT) 1512 if (debug) 1513 DebugBreak(); 1514 #endif 1515 1516 abort(); 1517 } 1518 1519 1520 /* 1521 * library_fatal_error - Handle fatal errors from our libraries. 1522 */ 1523 static void 1524 library_fatal_error( 1525 const char *file, 1526 int line, 1527 const char *format, 1528 va_list args 1529 ) 1530 { 1531 char errbuf[256]; 1532 1533 isc_error_setfatal(NULL); /* Avoid recursion */ 1534 1535 msyslog(LOG_ERR, "%s:%d: fatal error:", file, line); 1536 vsnprintf(errbuf, sizeof(errbuf), format, args); 1537 msyslog(LOG_ERR, "%s", errbuf); 1538 msyslog(LOG_ERR, "exiting (due to fatal error in library)"); 1539 1540 #if defined(DEBUG) && defined(SYS_WINNT) 1541 if (debug) 1542 DebugBreak(); 1543 #endif 1544 1545 abort(); 1546 } 1547 1548 1549 /* 1550 * library_unexpected_error - Handle non fatal errors from our libraries. 1551 */ 1552 # define MAX_UNEXPECTED_ERRORS 100 1553 int unexpected_error_cnt = 0; 1554 static void 1555 library_unexpected_error( 1556 const char *file, 1557 int line, 1558 const char *format, 1559 va_list args 1560 ) 1561 { 1562 char errbuf[256]; 1563 1564 if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS) 1565 return; /* avoid clutter in log */ 1566 1567 msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line); 1568 vsnprintf(errbuf, sizeof(errbuf), format, args); 1569 msyslog(LOG_ERR, "%s", errbuf); 1570 1571 if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS) 1572 msyslog(LOG_ERR, "Too many errors. Shutting up."); 1573 1574 } 1575 #endif /* !SIM */ 1576 1577 #if !defined(SIM) && !defined(SYS_WINNT) 1578 # ifdef DEBUG 1579 1580 /* 1581 * moredebug - increase debugging verbosity 1582 */ 1583 static RETSIGTYPE 1584 moredebug( 1585 int sig 1586 ) 1587 { 1588 int saved_errno = errno; 1589 1590 if (debug < 255) 1591 { 1592 debug++; 1593 msyslog(LOG_DEBUG, "debug raised to %d", debug); 1594 } 1595 errno = saved_errno; 1596 } 1597 1598 1599 /* 1600 * lessdebug - decrease debugging verbosity 1601 */ 1602 static RETSIGTYPE 1603 lessdebug( 1604 int sig 1605 ) 1606 { 1607 int saved_errno = errno; 1608 1609 if (debug > 0) 1610 { 1611 debug--; 1612 msyslog(LOG_DEBUG, "debug lowered to %d", debug); 1613 } 1614 errno = saved_errno; 1615 } 1616 1617 # else /* !DEBUG follows */ 1618 1619 1620 /* 1621 * no_debug - We don't do the debug here. 1622 */ 1623 static RETSIGTYPE 1624 no_debug( 1625 int sig 1626 ) 1627 { 1628 int saved_errno = errno; 1629 1630 msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig); 1631 errno = saved_errno; 1632 } 1633 # endif /* !DEBUG */ 1634 #endif /* !SIM && !SYS_WINNT */ 1635