2 * ntpd.c - main program for the fixed point NTP daemon
9 #include "ntp_machine.h"
12 #include "ntp_stdlib.h"
13 #include <ntp_random.h>
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"
27 #include "ntp_libopts.h"
28 #include "ntpd-opts.h"
30 /* there's a short treatise below what the thread stuff is for.
31 * [Bug 2954] enable the threading warm-up only for Linux.
33 #if defined(HAVE_PTHREADS) && HAVE_PTHREADS && !defined(NO_THREADS)
34 # ifdef HAVE_PTHREAD_H
38 # define NEED_PTHREAD_WARMUP
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
49 #ifdef HAVE_SYS_PARAM_H
50 # include <sys/param.h>
52 #ifdef HAVE_SYS_SIGNAL_H
53 # include <sys/signal.h>
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>
64 # include <sys/rtprio.h>
67 # ifdef HAVE_SYS_LOCK_H
68 # include <sys/lock.h>
72 #if defined(HAVE_SCHED_SETSCHEDULER)
76 # ifdef HAVE_SYS_SCHED_H
77 # include <sys/sched.h>
81 #if defined(HAVE_SYS_MMAN_H)
82 # include <sys/mman.h>
90 # include <apollo/base.h>
91 #endif /* SYS_DOMAINOS */
95 #include "ntp_cmdargs.h"
97 #if 0 /* HMS: I don't think we need this. 961223 */
100 # include <sys/mman.h>
102 # include <sys/lock.h>
112 # include <sys/ci/ciioctl.h>
119 #ifdef HAVE_LINUX_CAPABILITIES
120 # include <sys/capability.h>
121 # include <sys/prctl.h>
122 #endif /* HAVE_LINUX_CAPABILITIES */
123 #if defined(HAVE_PRIV_H) && defined(HAVE_SOLARIS_PRIVS)
125 #endif /* HAVE_PRIV_H */
126 #endif /* HAVE_DROPROOT */
128 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
129 /* # include <sys/types.h> */
130 # include <sys/resource.h>
131 # include <seccomp.h>
132 #endif /* LIBSECCOMP and KERN_SECCOMP */
134 #ifdef HAVE_DNSREGISTRATION
139 #ifdef HAVE_SETPGRP_0
140 # define ntp_setpgrp(x, y) setpgrp()
142 # define ntp_setpgrp(x, y) setpgrp(x, y)
145 #ifdef HAVE_SOLARIS_PRIVS
146 # define LOWPRIVS "basic,sys_time,net_privaddr,proc_setid,!proc_info,!proc_session,!proc_exec"
147 static priv_set_t *lowprivs = NULL;
148 static priv_set_t *highprivs = NULL;
149 #endif /* HAVE_SOLARIS_PRIVS */
151 * Scheduling priority we run at
153 #define NTPD_PRIO (-12)
155 int priority_done = 2; /* 0 - Set priority */
156 /* 1 - priority is OK where it is */
157 /* 2 - Don't set priority */
158 /* 1 and 2 are pretty much the same */
160 int listen_to_virtual_ips = TRUE;
163 * No-fork flag. If set, we do not become a background daemon.
165 int nofork; /* Fork by default */
167 #ifdef HAVE_DNSREGISTRATION
169 * mDNS registration flag. If set, we attempt to register with the mDNS system, but only
170 * after we have synched the first time. If the attempt fails, then try again once per
171 * minute for up to 5 times. After all, we may be starting before mDNS.
175 #endif /* HAVE_DNSREGISTRATION */
180 char *user; /* User to switch to */
181 char *group; /* group to switch to */
182 const char *chrootdir; /* directory to chroot to */
188 #endif /* HAVE_DROPROOT */
190 #ifdef HAVE_WORKING_FORK
191 int waitsync_fd_to_close = -1; /* -w/--wait-sync */
195 * Version declaration
197 extern const char *Version;
199 char const *progname;
205 * We put this here, since the argument profile is syscall-specific
207 extern int syscall (int, ...);
208 #endif /* DECL_SYSCALL */
211 #if !defined(SIM) && defined(SIGDIE1)
212 static volatile int signalled = 0;
213 static volatile int signo = 0;
215 /* In an ideal world, 'finish_safe()' would declared as noreturn... */
216 static void finish_safe (int);
217 static RETSIGTYPE finish (int);
220 #if !defined(SIM) && defined(HAVE_WORKING_FORK)
221 static int wait_child_sync_if (int, long);
224 #if !defined(SIM) && !defined(SYS_WINNT)
226 static RETSIGTYPE moredebug (int);
227 static RETSIGTYPE lessdebug (int);
228 # else /* !DEBUG follows */
229 static RETSIGTYPE no_debug (int);
231 #endif /* !SIM && !SYS_WINNT */
239 int ntpdmain (int, char **);
240 static void set_process_priority (void);
241 static void assertion_failed (const char *, int,
244 __attribute__ ((__noreturn__));
245 static void library_fatal_error (const char *, int,
246 const char *, va_list)
247 ISC_FORMAT_PRINTF(3, 0);
248 static void library_unexpected_error(const char *, int,
249 const char *, va_list)
250 ISC_FORMAT_PRINTF(3, 0);
254 /* Bug2332 unearthed a problem in the interaction of reduced user
255 * privileges, the limits on memory usage and some versions of the
256 * pthread library on Linux systems. The 'pthread_cancel()' function and
257 * likely some others need to track the stack of the thread involved,
258 * and uses a function that comes from GCC (--> libgcc_s.so) to do
259 * this. Unfortunately the developers of glibc decided to load the
260 * library on demand, which speeds up program start but can cause
261 * trouble here: Due to all the things NTPD does to limit its resource
262 * usage, this deferred load of libgcc_s does not always work once the
263 * restrictions are in effect.
265 * One way out of this was attempting a forced link against libgcc_s
266 * when possible because it makes the library available immediately
267 * without deferred load. (The symbol resolution would still be dynamic
268 * and on demand, but the code would already be in the process image.)
270 * This is a tricky thing to do, since it's not necessary everywhere,
271 * not possible everywhere, has shown to break the build of other
272 * programs in the NTP suite and is now generally frowned upon.
274 * So we take a different approach here: We creat a worker thread that does
275 * actually nothing except waiting for cancellation and cancel it. If
276 * this is done before all the limitations are put in place, the
277 * machinery is pre-heated and all the runtime stuff should be in place
278 * and useable when needed.
280 * This uses only the standard pthread API and should work with all
281 * implementations of pthreads. It is not necessary everywhere, but it's
282 * cheap enough to go on nearly unnoticed.
284 * Addendum: Bug 2954 showed that the assumption that this should work
285 * with all OS is wrong -- at least FreeBSD bombs heavily.
287 #ifdef NEED_PTHREAD_WARMUP
289 /* simple thread function: sleep until cancelled, just to exercise
290 * thread cancellation.
293 my_pthread_warmup_worker(
302 /* pre-heat threading: create a thread and cancel it, just to exercise
303 * thread cancellation.
306 my_pthread_warmup(void)
309 pthread_attr_t thr_attr;
312 pthread_attr_init(&thr_attr);
313 #if defined(HAVE_PTHREAD_ATTR_GETSTACKSIZE) && \
314 defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && \
315 defined(PTHREAD_STACK_MIN)
317 size_t ssmin = 32*1024; /* 32kB should be minimum */
318 if (ssmin < PTHREAD_STACK_MIN)
319 ssmin = PTHREAD_STACK_MIN;
320 rc = pthread_attr_setstacksize(&thr_attr, ssmin);
323 "my_pthread_warmup: pthread_attr_setstacksize() -> %s",
328 &thread, &thr_attr, my_pthread_warmup_worker, NULL);
329 pthread_attr_destroy(&thr_attr);
332 "my_pthread_warmup: pthread_create() -> %s",
335 pthread_cancel(thread);
336 pthread_join(thread, NULL);
340 #endif /*defined(NEED_PTHREAD_WARMUP)*/
342 #ifdef NEED_EARLY_FORK
344 dummy_callback(void) { return; }
347 fork_nonchroot_worker(void) {
348 getaddrinfo_sometime("localhost", "ntp", NULL, INITIAL_DNS_RETRY,
349 (gai_sometime_callback)&dummy_callback, NULL);
351 #endif /* NEED_EARLY_FORK */
363 optct = ntpOptionProcess(&ntpdOptions, *pargc, *pargv);
380 parse_cmdline_opts(&argc, &argv);
382 debug = OPT_VALUE_SET_DEBUG_LEVEL;
383 DPRINTF(1, ("%s\n", Version));
386 return ntpsim(argc, argv);
388 #else /* !SIM follows */
389 #ifdef NO_MAIN_ALLOWED
390 CALL(ntpd,"ntpd",ntpdmain);
391 #else /* !NO_MAIN_ALLOWED follows */
399 return ntpdmain(argc, argv);
401 #endif /* !SYS_WINNT */
402 #endif /* !NO_MAIN_ALLOWED */
407 * OK. AIX is different than solaris in how it implements plock().
408 * If you do NOT adjust the stack limit, you will get the MAXIMUM
409 * stack size allocated and PINNED with you program. To check the
410 * value, use ulimit -a.
412 * To fix this, we create an automatic variable and set our stack limit
413 * to that PLUS 32KB of extra space (we need some headroom).
415 * This subroutine gets the stack address.
417 * Grover Davidson and Matt Ladendorf
428 * Signal handler for SIGDANGER.
431 catch_danger(int signo)
433 msyslog(LOG_INFO, "ntpd: setpgid(): %m");
434 /* Make the system believe we'll free something, but don't do it! */
440 * Set the process priority
444 set_process_priority(void)
449 msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>",
451 ? "Leave priority alone"
452 : "Attempt to set priority"
457 # if defined(HAVE_SCHED_SETSCHEDULER)
458 if (!priority_done) {
459 extern int config_priority_override, config_priority;
461 struct sched_param sched;
463 pmax = sched_get_priority_max(SCHED_FIFO);
464 sched.sched_priority = pmax;
465 if ( config_priority_override ) {
466 pmin = sched_get_priority_min(SCHED_FIFO);
467 if ( config_priority > pmax )
468 sched.sched_priority = pmax;
469 else if ( config_priority < pmin )
470 sched.sched_priority = pmin;
472 sched.sched_priority = config_priority;
474 if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 )
475 msyslog(LOG_ERR, "sched_setscheduler(): %m");
479 # endif /* HAVE_SCHED_SETSCHEDULER */
482 if (!priority_done) {
485 srtp.type = RTP_PRIO_REALTIME; /* was: RTP_PRIO_NORMAL */
486 srtp.prio = 0; /* 0 (hi) -> RTP_PRIO_MAX (31,lo) */
488 if (rtprio(RTP_SET, getpid(), &srtp) < 0)
489 msyslog(LOG_ERR, "rtprio() error: %m");
493 # else /* !RTP_SET follows */
494 if (!priority_done) {
495 if (rtprio(0, 120) < 0)
496 msyslog(LOG_ERR, "rtprio() error: %m");
500 # endif /* !RTP_SET */
501 # endif /* HAVE_RTPRIO */
502 # if defined(NTPD_PRIO) && NTPD_PRIO != 0
503 # ifdef HAVE_ATT_NICE
504 if (!priority_done) {
506 if (-1 == nice (NTPD_PRIO) && errno != 0)
507 msyslog(LOG_ERR, "nice() error: %m");
511 # endif /* HAVE_ATT_NICE */
512 # ifdef HAVE_BSD_NICE
513 if (!priority_done) {
514 if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO))
515 msyslog(LOG_ERR, "setpriority() error: %m");
519 # endif /* HAVE_BSD_NICE */
520 # endif /* NTPD_PRIO && NTPD_PRIO != 0 */
522 msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority");
528 * Main program. Initialize us, disconnect us from the tty if necessary,
529 * and loop waiting for I/O and/or timer expiries.
539 struct recvbuf *rbuf;
540 const char * logfilename;
544 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
547 # if defined(HAVE_WORKING_FORK)
555 # if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
558 # endif /* HAVE_WORKING_FORK*/
564 # ifdef NEED_PTHREAD_WARMUP
578 initializing = TRUE; /* mark that we are initializing */
579 parse_cmdline_opts(&argc, &argv);
581 debug = OPT_VALUE_SET_DEBUG_LEVEL;
582 # ifdef HAVE_SETLINEBUF
587 if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
591 || HAVE_OPT(SAVECONFIGQUIT))
594 init_logging(progname, NLOG_SYNCMASK, TRUE);
595 /* honor -l/--logfile option to log to a file */
596 if (HAVE_OPT(LOGFILE)) {
597 logfilename = OPT_ARG(LOGFILE);
599 change_logfile(logfilename, FALSE);
604 if (HAVE_OPT(SAVECONFIGQUIT))
607 msyslog(LOG_NOTICE, "%s: Starting", Version);
611 char buf[1024]; /* Secret knowledge of msyslog buf length */
614 /* Note that every arg has an initial space character */
615 snprintf(cp, sizeof(buf), "Command line:");
618 for (i = 0; i < saved_argc ; ++i) {
619 snprintf(cp, sizeof(buf) - (cp - buf),
620 " %s", saved_argv[i]);
623 msyslog(LOG_INFO, "%s", buf);
627 * Install trap handlers to log errors and assertion failures.
628 * Default handlers print to stderr which doesn't work if detached.
630 isc_assertion_setcallback(assertion_failed);
631 isc_error_setfatal(library_fatal_error);
632 isc_error_setunexpected(library_unexpected_error);
634 /* MPE lacks the concept of root */
635 # if defined(HAVE_GETUID) && !defined(MPE)
637 if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
640 "must be run as root, not uid %ld", (long)uid);
646 * Enable the Multi-Media Timer for Windows?
649 if (HAVE_OPT( MODIFYMMTIMER ))
650 set_mm_timer(MM_TIMER_HIRES);
653 #ifdef HAVE_DNSREGISTRATION
655 * Enable mDNS registrations?
657 if (HAVE_OPT( MDNS )) {
660 #endif /* HAVE_DNSREGISTRATION */
662 if (HAVE_OPT( NOVIRTUALIPS ))
663 listen_to_virtual_ips = 0;
666 * --interface, listen on specified interfaces
668 if (HAVE_OPT( INTERFACE )) {
669 int ifacect = STACKCT_OPT( INTERFACE );
670 const char** ifaces = STACKLST_OPT( INTERFACE );
673 while (ifacect-- > 0) {
675 is_ip_address(*ifaces, AF_UNSPEC, &addr)
678 *ifaces, -1, ACTION_LISTEN);
683 if (HAVE_OPT( NICE ))
686 # ifdef HAVE_SCHED_SETSCHEDULER
687 if (HAVE_OPT( PRIORITY )) {
688 config_priority = OPT_VALUE_PRIORITY;
689 config_priority_override = 1;
694 # ifdef HAVE_WORKING_FORK
695 /* make sure the FDs are initialised */
698 do { /* 'loop' once */
699 if (!HAVE_OPT( WAIT_SYNC ))
701 wait_sync = OPT_VALUE_WAIT_SYNC;
702 if (wait_sync <= 0) {
706 /* -w requires a fork() even with debug > 0 */
708 if (pipe(pipe_fds)) {
709 exit_code = (errno) ? errno : -1;
711 "Pipe creation failed for --wait-sync: %m");
714 waitsync_fd_to_close = pipe_fds[1];
715 } while (0); /* 'loop' once */
716 # endif /* HAVE_WORKING_FORK */
721 * Start interpolation thread, must occur before first
727 * Initialize random generator and public key pair
731 ntp_srandom((int)(now.l_i * now.l_uf));
734 * Detach us from the terminal. May need an #ifndef GIZMO.
738 # ifdef HAVE_WORKING_FORK
741 exit_code = (errno) ? errno : -1;
742 msyslog(LOG_ERR, "fork: %m");
747 exit_code = wait_child_sync_if(pipe_fds[0],
754 * close all open files excepting waitsync_fd_to_close.
755 * msyslog() unreliable until after init_logging().
758 if (syslog_file != NULL) {
763 close_all_except(waitsync_fd_to_close);
764 INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
767 init_logging(progname, 0, TRUE);
768 /* we lost our logfile (if any) daemonizing */
769 setup_logfile(logfilename);
776 proc2_$who_am_i(&puid);
777 proc2_$make_server(&puid, &st);
779 # endif /* SYS_DOMAINOS */
781 if (setsid() == (pid_t)-1)
782 msyslog(LOG_ERR, "setsid(): %m");
783 # elif defined(HAVE_SETPGID)
784 if (setpgid(0, 0) == -1)
785 msyslog(LOG_ERR, "setpgid(): %m");
786 # else /* !HAVE_SETSID && !HAVE_SETPGID follows */
788 fid = open("/dev/tty", 2);
790 ioctl(fid, (u_long)TIOCNOTTY, NULL);
793 # endif /* TIOCNOTTY */
794 ntp_setpgrp(0, getpid());
795 # endif /* !HAVE_SETSID && !HAVE_SETPGID */
797 /* Don't get killed by low-on-memory signal. */
798 sa.sa_handler = catch_danger;
799 sigemptyset(&sa.sa_mask);
800 sa.sa_flags = SA_RESTART;
801 sigaction(SIGDANGER, &sa, NULL);
803 # endif /* HAVE_WORKING_FORK */
808 * SCO OpenServer's system clock offers much more precise timekeeping
809 * on the base CPU than the other CPUs (for multiprocessor systems),
810 * so we must lock to the base CPU.
812 fd = open("/dev/at1", O_RDONLY);
815 if (ioctl(fd, ACPU_LOCK, &zero) < 0)
816 msyslog(LOG_ERR, "cannot lock to base CPU: %m");
821 /* Setup stack size in preparation for locking pages in memory. */
822 # if defined(HAVE_MLOCKALL)
823 # ifdef HAVE_SETRLIMIT
824 ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
825 # ifdef RLIMIT_MEMLOCK
827 * The default RLIMIT_MEMLOCK is very low on Linux systems.
828 * Unless we increase this limit malloc calls are likely to
829 * fail if we drop root privilege. To be useful the value
830 * has to be larger than the largest ntpd resident set size.
832 ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
833 # endif /* RLIMIT_MEMLOCK */
834 # endif /* HAVE_SETRLIMIT */
835 # else /* !HAVE_MLOCKALL follows */
840 * set the stack limit for AIX for plock().
841 * see get_aix_stack() for more info.
843 if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
845 "Cannot adjust stack limit for plock: %m");
847 # endif /* PROCLOCK */
848 # endif /* HAVE_PLOCK */
849 # endif /* !HAVE_MLOCKALL */
852 * Set up signals we pay attention to locally.
855 signal_no_reset(SIGDIE1, finish);
856 signal_no_reset(SIGDIE2, finish);
857 signal_no_reset(SIGDIE3, finish);
858 signal_no_reset(SIGDIE4, finish);
861 signal_no_reset(SIGBUS, finish);
864 # if !defined(SYS_WINNT) && !defined(VMS)
866 (void) signal_no_reset(MOREDEBUGSIG, moredebug);
867 (void) signal_no_reset(LESSDEBUGSIG, lessdebug);
869 (void) signal_no_reset(MOREDEBUGSIG, no_debug);
870 (void) signal_no_reset(LESSDEBUGSIG, no_debug);
872 # endif /* !SYS_WINNT && !VMS */
875 * Set up signals we should never pay attention to.
878 signal_no_reset(SIGPIPE, SIG_IGN);
882 * Call the init_ routines to initialize the data structures.
884 * Exactly what command-line options are we expecting here?
898 set_process_priority();
899 init_proto(); /* Call at high priority */
902 mon_start(MON_ON); /* monitor on by default now */
903 /* turn off in config if unwanted */
906 * Get the configuration. This is done in a separate module
907 * since this will definitely be different for the gizmo board.
909 getconfig(argc, argv);
911 if (-1 == cur_memlock) {
912 # if defined(HAVE_MLOCKALL)
914 * lock the process into memory
916 if ( !HAVE_OPT(SAVECONFIGQUIT)
917 # ifdef RLIMIT_MEMLOCK
918 && -1 != DFLT_RLIMIT_MEMLOCK
920 && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
921 msyslog(LOG_ERR, "mlockall(): %m");
922 # else /* !HAVE_MLOCKALL follows */
926 * lock the process into memory
928 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
929 msyslog(LOG_ERR, "plock(PROCLOCK): %m");
930 # else /* !PROCLOCK follows */
935 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
936 msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
937 # else /* !TXTLOCK follows */
938 msyslog(LOG_ERR, "plock() - don't know what to lock!");
939 # endif /* !TXTLOCK */
940 # endif /* !PROCLOCK */
941 # endif /* HAVE_PLOCK */
942 # endif /* !HAVE_MLOCKALL */
945 loop_config(LOOP_DRIFTINIT, 0);
946 report_event(EVNT_SYSRESTART, NULL, NULL);
947 initializing = FALSE;
949 # ifdef HAVE_DROPROOT
952 #ifdef NEED_EARLY_FORK
953 fork_nonchroot_worker();
956 /* Drop super-user privileges and chroot now if the OS supports this */
958 # ifdef HAVE_LINUX_CAPABILITIES
959 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
960 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
961 msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
964 # elif HAVE_SOLARIS_PRIVS
965 /* Nothing to do here */
967 /* we need a user to switch to */
969 msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
972 # endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
975 if (isdigit((unsigned char)*user)) {
976 sw_uid = (uid_t)strtoul(user, &endp, 0);
980 if ((pw = getpwuid(sw_uid)) != NULL) {
982 user = estrdup(pw->pw_name);
986 msyslog(LOG_ERR, "Cannot find user ID %s", user);
993 if ((pw = getpwnam(user)) != NULL) {
998 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
1000 msyslog(LOG_ERR, "Cannot find user `%s'", user);
1005 if (group != NULL) {
1006 if (isdigit((unsigned char)*group)) {
1007 sw_gid = (gid_t)strtoul(group, &endp, 0);
1012 if ((gr = getgrnam(group)) != NULL) {
1013 sw_gid = gr->gr_gid;
1016 msyslog(LOG_ERR, "Cannot find group `%s'", group);
1023 /* make sure cwd is inside the jail: */
1024 if (chdir(chrootdir)) {
1025 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
1028 if (chroot(chrootdir)) {
1029 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
1033 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
1037 # ifdef HAVE_SOLARIS_PRIVS
1038 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
1039 msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
1042 if ((highprivs = priv_allocset()) == NULL) {
1043 msyslog(LOG_ERR, "priv_allocset() failed:%m");
1046 (void) getppriv(PRIV_PERMITTED, highprivs);
1047 (void) priv_intersect(highprivs, lowprivs);
1048 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1049 msyslog(LOG_ERR, "setppriv() failed:%m");
1052 # endif /* HAVE_SOLARIS_PRIVS */
1053 if (user && initgroups(user, sw_gid)) {
1054 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
1057 if (group && setgid(sw_gid)) {
1058 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
1061 if (group && setegid(sw_gid)) {
1062 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
1066 if (0 != setgroups(1, &sw_gid)) {
1067 msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
1072 if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
1073 msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
1076 if (user && setuid(sw_uid)) {
1077 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
1080 if (user && seteuid(sw_uid)) {
1081 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
1085 # if !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1087 * for now assume that the privilege to bind to privileged ports
1088 * is associated with running with uid 0 - should be refined on
1089 * ports that allow binding to NTP_PORT with uid != 0
1091 disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */
1092 # endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1094 if (disable_dynamic_updates && interface_interval) {
1095 interface_interval = 0;
1096 msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1099 # ifdef HAVE_LINUX_CAPABILITIES
1102 * We may be running under non-root uid now, but we still hold full root privileges!
1103 * We drop all of them, except for the crucial one or two: cap_sys_time and
1104 * cap_net_bind_service if doing dynamic interface tracking.
1109 captext = (0 != interface_interval)
1110 ? "cap_sys_time,cap_net_bind_service=pe"
1111 : "cap_sys_time=pe";
1112 caps = cap_from_text(captext);
1115 "cap_from_text(%s) failed: %m",
1119 if (-1 == cap_set_proc(caps)) {
1121 "cap_set_proc() failed to drop root privs: %m");
1126 # endif /* HAVE_LINUX_CAPABILITIES */
1127 # ifdef HAVE_SOLARIS_PRIVS
1128 if (priv_delset(lowprivs, "proc_setid") == -1) {
1129 msyslog(LOG_ERR, "priv_delset() failed:%m");
1132 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1133 msyslog(LOG_ERR, "setppriv() failed:%m");
1136 priv_freeset(lowprivs);
1137 priv_freeset(highprivs);
1138 # endif /* HAVE_SOLARIS_PRIVS */
1139 root_dropped = TRUE;
1140 fork_deferred_worker();
1141 } /* if (droproot) */
1142 # endif /* HAVE_DROPROOT */
1144 /* libssecomp sandboxing */
1145 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1146 scmp_filter_ctx ctx;
1148 if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1149 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1151 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1160 SCMP_SYS(clock_gettime),
1161 SCMP_SYS(clock_settime),
1164 SCMP_SYS(exit_group),
1168 SCMP_SYS(getitimer),
1169 SCMP_SYS(getsockname),
1180 SCMP_SYS(rt_sigaction),
1181 SCMP_SYS(rt_sigprocmask),
1182 SCMP_SYS(rt_sigreturn),
1185 SCMP_SYS(setitimer),
1195 SCMP_SYS(_newselect),
1199 SCMP_SYS(clock_gettime),
1200 SCMP_SYS(clock_settime),
1202 SCMP_SYS(exit_group),
1205 SCMP_SYS(getitimer),
1214 SCMP_SYS(rt_sigaction),
1215 SCMP_SYS(rt_sigprocmask),
1217 SCMP_SYS(setitimer),
1219 SCMP_SYS(sigprocmask),
1220 SCMP_SYS(sigreturn),
1221 SCMP_SYS(socketcall),
1230 for (i = 0; i < COUNTOF(scmp_sc); i++) {
1231 if (seccomp_rule_add(ctx,
1232 SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1234 "%s: seccomp_rule_add() failed: %m",
1240 if (seccomp_load(ctx) < 0)
1241 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1244 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1246 #endif /* LIBSECCOMP and KERN_SECCOMP */
1248 # ifdef HAVE_IO_COMPLETION_PORT
1251 #if !defined(SIM) && defined(SIGDIE1)
1255 GetReceivedBuffers();
1256 # else /* normal I/O */
1258 BLOCK_IO_AND_ALARM();
1259 was_alarmed = FALSE;
1262 #if !defined(SIM) && defined(SIGDIE1)
1266 if (alarm_flag) { /* alarmed? */
1271 /* collect async name/addr results */
1273 harvest_blocking_responses();
1275 if (!was_alarmed && !has_full_recv_buffer()) {
1277 * Nothing to do. Wait for something.
1282 if (alarm_flag) { /* alarmed? */
1288 UNBLOCK_IO_AND_ALARM();
1290 * Out here, signals are unblocked. Call timer routine
1291 * to process expiry.
1294 was_alarmed = FALSE;
1295 BLOCK_IO_AND_ALARM();
1298 # endif /* !HAVE_IO_COMPLETION_PORT */
1300 # ifdef DEBUG_TIMING
1309 rbuf = get_full_recv_buffer();
1310 while (rbuf != NULL) {
1315 UNBLOCK_IO_AND_ALARM();
1318 /* avoid timer starvation during lengthy I/O handling */
1320 was_alarmed = FALSE;
1324 * Call the data procedure to handle each received
1327 if (rbuf->receiver != NULL) {
1328 # ifdef DEBUG_TIMING
1331 L_SUB(&dts, &rbuf->recv_time);
1332 DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1333 collect_timing(rbuf, "buffer processing delay", 1, &dts);
1336 (*rbuf->receiver)(rbuf);
1338 msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1342 BLOCK_IO_AND_ALARM();
1344 rbuf = get_full_recv_buffer();
1346 # ifdef DEBUG_TIMING
1350 collect_timing(NULL, "processing", bufcount, &tsb);
1351 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1360 # ifdef HAVE_DNSREGISTRATION
1361 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1362 mdnsreg = current_time;
1363 msyslog(LOG_INFO, "Attempting to register mDNS");
1364 if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1365 htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1367 msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1369 msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1372 msyslog(LOG_INFO, "mDNS service registered.");
1376 # endif /* HAVE_DNSREGISTRATION */
1379 UNBLOCK_IO_AND_ALARM();
1385 #if !defined(SIM) && defined(SIGDIE1)
1387 * finish - exit gracefully
1394 const char *sig_desc;
1397 #ifdef HAVE_STRSIGNAL
1398 sig_desc = strsignal(sig);
1400 if (sig_desc == NULL)
1402 msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1404 /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1405 # ifdef HAVE_DNSREGISTRATION
1407 DNSServiceRefDeallocate(mdns);
1422 #endif /* !SIM && SIGDIE1 */
1427 * wait_child_sync_if - implements parent side of -w/--wait-sync
1429 # ifdef HAVE_WORKING_FORK
1438 time_t wait_end_time;
1442 struct timeval wtimeout;
1447 /* waitsync_fd_to_close used solely by child */
1448 close(waitsync_fd_to_close);
1449 wait_end_time = time(NULL) + wait_sync;
1451 cur_time = time(NULL);
1452 wait_rem = (wait_end_time > cur_time)
1453 ? (wait_end_time - cur_time)
1455 wtimeout.tv_sec = wait_rem;
1456 wtimeout.tv_usec = 0;
1458 FD_SET(pipe_read_fd, &readset);
1459 rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1464 exit_code = (errno) ? errno : -1;
1466 "--wait-sync select failed: %m");
1471 * select() indicated a timeout, but in case
1472 * its timeouts are affected by a step of the
1473 * system clock, select() again with a zero
1474 * timeout to confirm.
1477 FD_SET(pipe_read_fd, &readset);
1478 wtimeout.tv_sec = 0;
1479 wtimeout.tv_usec = 0;
1480 rc = select(pipe_read_fd + 1, &readset, NULL,
1482 if (0 == rc) /* select() timeout */
1486 } else /* readable */
1488 } while (wait_rem > 0);
1490 fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1491 progname, wait_sync);
1494 # endif /* HAVE_WORKING_FORK */
1498 * assertion_failed - Redirect assertion failures to msyslog().
1504 isc_assertiontype_t type,
1508 isc_assertion_setcallback(NULL); /* Avoid recursion */
1510 msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1511 file, line, isc_assertion_typetotext(type), cond);
1512 msyslog(LOG_ERR, "exiting (due to assertion failure)");
1514 #if defined(DEBUG) && defined(SYS_WINNT)
1524 * library_fatal_error - Handle fatal errors from our libraries.
1527 library_fatal_error(
1536 isc_error_setfatal(NULL); /* Avoid recursion */
1538 msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1539 vsnprintf(errbuf, sizeof(errbuf), format, args);
1540 msyslog(LOG_ERR, "%s", errbuf);
1541 msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1543 #if defined(DEBUG) && defined(SYS_WINNT)
1553 * library_unexpected_error - Handle non fatal errors from our libraries.
1555 # define MAX_UNEXPECTED_ERRORS 100
1556 int unexpected_error_cnt = 0;
1558 library_unexpected_error(
1567 if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1568 return; /* avoid clutter in log */
1570 msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1571 vsnprintf(errbuf, sizeof(errbuf), format, args);
1572 msyslog(LOG_ERR, "%s", errbuf);
1574 if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1575 msyslog(LOG_ERR, "Too many errors. Shutting up.");
1580 #if !defined(SIM) && !defined(SYS_WINNT)
1584 * moredebug - increase debugging verbosity
1591 int saved_errno = errno;
1596 msyslog(LOG_DEBUG, "debug raised to %d", debug);
1598 errno = saved_errno;
1603 * lessdebug - decrease debugging verbosity
1610 int saved_errno = errno;
1615 msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1617 errno = saved_errno;
1620 # else /* !DEBUG follows */
1624 * no_debug - We don't do the debug here.
1631 int saved_errno = errno;
1633 msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1634 errno = saved_errno;
1636 # endif /* !DEBUG */
1637 #endif /* !SIM && !SYS_WINNT */