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