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