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