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