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)
316 rc = pthread_attr_setstacksize(&thr_attr, PTHREAD_STACK_MIN);
319 "my_pthread_warmup: pthread_attr_setstacksize() -> %s",
323 &thread, &thr_attr, my_pthread_warmup_worker, NULL);
324 pthread_attr_destroy(&thr_attr);
327 "my_pthread_warmup: pthread_create() -> %s",
330 pthread_cancel(thread);
331 pthread_join(thread, NULL);
335 #endif /*defined(NEED_PTHREAD_WARMUP)*/
337 #ifdef NEED_EARLY_FORK
339 dummy_callback(void) { return; }
342 fork_nonchroot_worker(void) {
343 getaddrinfo_sometime("localhost", "ntp", NULL, INITIAL_DNS_RETRY,
344 (gai_sometime_callback)&dummy_callback, NULL);
346 #endif /* NEED_EARLY_FORK */
358 optct = ntpOptionProcess(&ntpdOptions, *pargc, *pargv);
375 parse_cmdline_opts(&argc, &argv);
377 debug = OPT_VALUE_SET_DEBUG_LEVEL;
378 DPRINTF(1, ("%s\n", Version));
381 return ntpsim(argc, argv);
383 #else /* !SIM follows */
384 #ifdef NO_MAIN_ALLOWED
385 CALL(ntpd,"ntpd",ntpdmain);
386 #else /* !NO_MAIN_ALLOWED follows */
394 return ntpdmain(argc, argv);
396 #endif /* !SYS_WINNT */
397 #endif /* !NO_MAIN_ALLOWED */
402 * OK. AIX is different than solaris in how it implements plock().
403 * If you do NOT adjust the stack limit, you will get the MAXIMUM
404 * stack size allocated and PINNED with you program. To check the
405 * value, use ulimit -a.
407 * To fix this, we create an automatic variable and set our stack limit
408 * to that PLUS 32KB of extra space (we need some headroom).
410 * This subroutine gets the stack address.
412 * Grover Davidson and Matt Ladendorf
423 * Signal handler for SIGDANGER.
426 catch_danger(int signo)
428 msyslog(LOG_INFO, "ntpd: setpgid(): %m");
429 /* Make the system believe we'll free something, but don't do it! */
435 * Set the process priority
439 set_process_priority(void)
444 msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>",
446 ? "Leave priority alone"
447 : "Attempt to set priority"
452 # if defined(HAVE_SCHED_SETSCHEDULER)
453 if (!priority_done) {
454 extern int config_priority_override, config_priority;
456 struct sched_param sched;
458 pmax = sched_get_priority_max(SCHED_FIFO);
459 sched.sched_priority = pmax;
460 if ( config_priority_override ) {
461 pmin = sched_get_priority_min(SCHED_FIFO);
462 if ( config_priority > pmax )
463 sched.sched_priority = pmax;
464 else if ( config_priority < pmin )
465 sched.sched_priority = pmin;
467 sched.sched_priority = config_priority;
469 if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 )
470 msyslog(LOG_ERR, "sched_setscheduler(): %m");
474 # endif /* HAVE_SCHED_SETSCHEDULER */
477 if (!priority_done) {
480 srtp.type = RTP_PRIO_REALTIME; /* was: RTP_PRIO_NORMAL */
481 srtp.prio = 0; /* 0 (hi) -> RTP_PRIO_MAX (31,lo) */
483 if (rtprio(RTP_SET, getpid(), &srtp) < 0)
484 msyslog(LOG_ERR, "rtprio() error: %m");
488 # else /* !RTP_SET follows */
489 if (!priority_done) {
490 if (rtprio(0, 120) < 0)
491 msyslog(LOG_ERR, "rtprio() error: %m");
495 # endif /* !RTP_SET */
496 # endif /* HAVE_RTPRIO */
497 # if defined(NTPD_PRIO) && NTPD_PRIO != 0
498 # ifdef HAVE_ATT_NICE
499 if (!priority_done) {
501 if (-1 == nice (NTPD_PRIO) && errno != 0)
502 msyslog(LOG_ERR, "nice() error: %m");
506 # endif /* HAVE_ATT_NICE */
507 # ifdef HAVE_BSD_NICE
508 if (!priority_done) {
509 if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO))
510 msyslog(LOG_ERR, "setpriority() error: %m");
514 # endif /* HAVE_BSD_NICE */
515 # endif /* NTPD_PRIO && NTPD_PRIO != 0 */
517 msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority");
523 * Main program. Initialize us, disconnect us from the tty if necessary,
524 * and loop waiting for I/O and/or timer expiries.
534 struct recvbuf *rbuf;
535 const char * logfilename;
539 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
542 # if defined(HAVE_WORKING_FORK)
550 # if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
553 # endif /* HAVE_WORKING_FORK*/
559 # ifdef NEED_PTHREAD_WARMUP
573 initializing = TRUE; /* mark that we are initializing */
574 parse_cmdline_opts(&argc, &argv);
576 debug = OPT_VALUE_SET_DEBUG_LEVEL;
577 # ifdef HAVE_SETLINEBUF
582 if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
586 || HAVE_OPT(SAVECONFIGQUIT))
589 init_logging(progname, NLOG_SYNCMASK, TRUE);
590 /* honor -l/--logfile option to log to a file */
591 if (HAVE_OPT(LOGFILE)) {
592 logfilename = OPT_ARG(LOGFILE);
594 change_logfile(logfilename, FALSE);
599 if (HAVE_OPT(SAVECONFIGQUIT))
602 msyslog(LOG_NOTICE, "%s: Starting", Version);
606 char buf[1024]; /* Secret knowledge of msyslog buf length */
609 /* Note that every arg has an initial space character */
610 snprintf(cp, sizeof(buf), "Command line:");
613 for (i = 0; i < saved_argc ; ++i) {
614 snprintf(cp, sizeof(buf) - (cp - buf),
615 " %s", saved_argv[i]);
618 msyslog(LOG_INFO, "%s", buf);
622 * Install trap handlers to log errors and assertion failures.
623 * Default handlers print to stderr which doesn't work if detached.
625 isc_assertion_setcallback(assertion_failed);
626 isc_error_setfatal(library_fatal_error);
627 isc_error_setunexpected(library_unexpected_error);
629 /* MPE lacks the concept of root */
630 # if defined(HAVE_GETUID) && !defined(MPE)
632 if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
635 "must be run as root, not uid %ld", (long)uid);
641 * Enable the Multi-Media Timer for Windows?
644 if (HAVE_OPT( MODIFYMMTIMER ))
645 set_mm_timer(MM_TIMER_HIRES);
648 #ifdef HAVE_DNSREGISTRATION
650 * Enable mDNS registrations?
652 if (HAVE_OPT( MDNS )) {
655 #endif /* HAVE_DNSREGISTRATION */
657 if (HAVE_OPT( NOVIRTUALIPS ))
658 listen_to_virtual_ips = 0;
661 * --interface, listen on specified interfaces
663 if (HAVE_OPT( INTERFACE )) {
664 int ifacect = STACKCT_OPT( INTERFACE );
665 const char** ifaces = STACKLST_OPT( INTERFACE );
668 while (ifacect-- > 0) {
670 is_ip_address(*ifaces, AF_UNSPEC, &addr)
673 *ifaces, -1, ACTION_LISTEN);
678 if (HAVE_OPT( NICE ))
681 # ifdef HAVE_SCHED_SETSCHEDULER
682 if (HAVE_OPT( PRIORITY )) {
683 config_priority = OPT_VALUE_PRIORITY;
684 config_priority_override = 1;
689 # ifdef HAVE_WORKING_FORK
690 /* make sure the FDs are initialised */
693 do { /* 'loop' once */
694 if (!HAVE_OPT( WAIT_SYNC ))
696 wait_sync = OPT_VALUE_WAIT_SYNC;
697 if (wait_sync <= 0) {
701 /* -w requires a fork() even with debug > 0 */
703 if (pipe(pipe_fds)) {
704 exit_code = (errno) ? errno : -1;
706 "Pipe creation failed for --wait-sync: %m");
709 waitsync_fd_to_close = pipe_fds[1];
710 } while (0); /* 'loop' once */
711 # endif /* HAVE_WORKING_FORK */
716 * Start interpolation thread, must occur before first
722 * Initialize random generator and public key pair
726 ntp_srandom((int)(now.l_i * now.l_uf));
729 * Detach us from the terminal. May need an #ifndef GIZMO.
733 # ifdef HAVE_WORKING_FORK
736 exit_code = (errno) ? errno : -1;
737 msyslog(LOG_ERR, "fork: %m");
742 exit_code = wait_child_sync_if(pipe_fds[0],
749 * close all open files excepting waitsync_fd_to_close.
750 * msyslog() unreliable until after init_logging().
753 if (syslog_file != NULL) {
758 close_all_except(waitsync_fd_to_close);
759 INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
762 init_logging(progname, 0, TRUE);
763 /* we lost our logfile (if any) daemonizing */
764 setup_logfile(logfilename);
771 proc2_$who_am_i(&puid);
772 proc2_$make_server(&puid, &st);
774 # endif /* SYS_DOMAINOS */
776 if (setsid() == (pid_t)-1)
777 msyslog(LOG_ERR, "setsid(): %m");
778 # elif defined(HAVE_SETPGID)
779 if (setpgid(0, 0) == -1)
780 msyslog(LOG_ERR, "setpgid(): %m");
781 # else /* !HAVE_SETSID && !HAVE_SETPGID follows */
783 fid = open("/dev/tty", 2);
785 ioctl(fid, (u_long)TIOCNOTTY, NULL);
788 # endif /* TIOCNOTTY */
789 ntp_setpgrp(0, getpid());
790 # endif /* !HAVE_SETSID && !HAVE_SETPGID */
792 /* Don't get killed by low-on-memory signal. */
793 sa.sa_handler = catch_danger;
794 sigemptyset(&sa.sa_mask);
795 sa.sa_flags = SA_RESTART;
796 sigaction(SIGDANGER, &sa, NULL);
798 # endif /* HAVE_WORKING_FORK */
803 * SCO OpenServer's system clock offers much more precise timekeeping
804 * on the base CPU than the other CPUs (for multiprocessor systems),
805 * so we must lock to the base CPU.
807 fd = open("/dev/at1", O_RDONLY);
810 if (ioctl(fd, ACPU_LOCK, &zero) < 0)
811 msyslog(LOG_ERR, "cannot lock to base CPU: %m");
816 /* Setup stack size in preparation for locking pages in memory. */
817 # if defined(HAVE_MLOCKALL)
818 # ifdef HAVE_SETRLIMIT
819 ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
820 # ifdef RLIMIT_MEMLOCK
822 * The default RLIMIT_MEMLOCK is very low on Linux systems.
823 * Unless we increase this limit malloc calls are likely to
824 * fail if we drop root privilege. To be useful the value
825 * has to be larger than the largest ntpd resident set size.
827 ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
828 # endif /* RLIMIT_MEMLOCK */
829 # endif /* HAVE_SETRLIMIT */
830 # else /* !HAVE_MLOCKALL follows */
835 * set the stack limit for AIX for plock().
836 * see get_aix_stack() for more info.
838 if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
840 "Cannot adjust stack limit for plock: %m");
842 # endif /* PROCLOCK */
843 # endif /* HAVE_PLOCK */
844 # endif /* !HAVE_MLOCKALL */
847 * Set up signals we pay attention to locally.
850 signal_no_reset(SIGDIE1, finish);
851 signal_no_reset(SIGDIE2, finish);
852 signal_no_reset(SIGDIE3, finish);
853 signal_no_reset(SIGDIE4, finish);
856 signal_no_reset(SIGBUS, finish);
859 # if !defined(SYS_WINNT) && !defined(VMS)
861 (void) signal_no_reset(MOREDEBUGSIG, moredebug);
862 (void) signal_no_reset(LESSDEBUGSIG, lessdebug);
864 (void) signal_no_reset(MOREDEBUGSIG, no_debug);
865 (void) signal_no_reset(LESSDEBUGSIG, no_debug);
867 # endif /* !SYS_WINNT && !VMS */
870 * Set up signals we should never pay attention to.
873 signal_no_reset(SIGPIPE, SIG_IGN);
877 * Call the init_ routines to initialize the data structures.
879 * Exactly what command-line options are we expecting here?
893 set_process_priority();
894 init_proto(); /* Call at high priority */
897 mon_start(MON_ON); /* monitor on by default now */
898 /* turn off in config if unwanted */
901 * Get the configuration. This is done in a separate module
902 * since this will definitely be different for the gizmo board.
904 getconfig(argc, argv);
906 if (-1 == cur_memlock) {
907 # if defined(HAVE_MLOCKALL)
909 * lock the process into memory
911 if ( !HAVE_OPT(SAVECONFIGQUIT)
912 # ifdef RLIMIT_MEMLOCK
913 && -1 != DFLT_RLIMIT_MEMLOCK
915 && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
916 msyslog(LOG_ERR, "mlockall(): %m");
917 # else /* !HAVE_MLOCKALL follows */
921 * lock the process into memory
923 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
924 msyslog(LOG_ERR, "plock(PROCLOCK): %m");
925 # else /* !PROCLOCK follows */
930 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
931 msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
932 # else /* !TXTLOCK follows */
933 msyslog(LOG_ERR, "plock() - don't know what to lock!");
934 # endif /* !TXTLOCK */
935 # endif /* !PROCLOCK */
936 # endif /* HAVE_PLOCK */
937 # endif /* !HAVE_MLOCKALL */
940 loop_config(LOOP_DRIFTINIT, 0);
941 report_event(EVNT_SYSRESTART, NULL, NULL);
942 initializing = FALSE;
944 # ifdef HAVE_DROPROOT
947 #ifdef NEED_EARLY_FORK
948 fork_nonchroot_worker();
951 /* Drop super-user privileges and chroot now if the OS supports this */
953 # ifdef HAVE_LINUX_CAPABILITIES
954 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
955 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
956 msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
959 # elif HAVE_SOLARIS_PRIVS
960 /* Nothing to do here */
962 /* we need a user to switch to */
964 msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
967 # endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
970 if (isdigit((unsigned char)*user)) {
971 sw_uid = (uid_t)strtoul(user, &endp, 0);
975 if ((pw = getpwuid(sw_uid)) != NULL) {
977 user = estrdup(pw->pw_name);
981 msyslog(LOG_ERR, "Cannot find user ID %s", user);
988 if ((pw = getpwnam(user)) != NULL) {
993 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
995 msyslog(LOG_ERR, "Cannot find user `%s'", user);
1000 if (group != NULL) {
1001 if (isdigit((unsigned char)*group)) {
1002 sw_gid = (gid_t)strtoul(group, &endp, 0);
1007 if ((gr = getgrnam(group)) != NULL) {
1008 sw_gid = gr->gr_gid;
1011 msyslog(LOG_ERR, "Cannot find group `%s'", group);
1018 /* make sure cwd is inside the jail: */
1019 if (chdir(chrootdir)) {
1020 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
1023 if (chroot(chrootdir)) {
1024 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
1028 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
1032 # ifdef HAVE_SOLARIS_PRIVS
1033 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
1034 msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
1037 if ((highprivs = priv_allocset()) == NULL) {
1038 msyslog(LOG_ERR, "priv_allocset() failed:%m");
1041 (void) getppriv(PRIV_PERMITTED, highprivs);
1042 (void) priv_intersect(highprivs, lowprivs);
1043 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1044 msyslog(LOG_ERR, "setppriv() failed:%m");
1047 # endif /* HAVE_SOLARIS_PRIVS */
1048 if (user && initgroups(user, sw_gid)) {
1049 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
1052 if (group && setgid(sw_gid)) {
1053 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
1056 if (group && setegid(sw_gid)) {
1057 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
1061 if (0 != setgroups(1, &sw_gid)) {
1062 msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
1067 if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
1068 msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
1071 if (user && setuid(sw_uid)) {
1072 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
1075 if (user && seteuid(sw_uid)) {
1076 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
1080 # if !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1082 * for now assume that the privilege to bind to privileged ports
1083 * is associated with running with uid 0 - should be refined on
1084 * ports that allow binding to NTP_PORT with uid != 0
1086 disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */
1087 # endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1089 if (disable_dynamic_updates && interface_interval) {
1090 interface_interval = 0;
1091 msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1094 # ifdef HAVE_LINUX_CAPABILITIES
1097 * We may be running under non-root uid now, but we still hold full root privileges!
1098 * We drop all of them, except for the crucial one or two: cap_sys_time and
1099 * cap_net_bind_service if doing dynamic interface tracking.
1104 captext = (0 != interface_interval)
1105 ? "cap_sys_time,cap_net_bind_service=pe"
1106 : "cap_sys_time=pe";
1107 caps = cap_from_text(captext);
1110 "cap_from_text(%s) failed: %m",
1114 if (-1 == cap_set_proc(caps)) {
1116 "cap_set_proc() failed to drop root privs: %m");
1121 # endif /* HAVE_LINUX_CAPABILITIES */
1122 # ifdef HAVE_SOLARIS_PRIVS
1123 if (priv_delset(lowprivs, "proc_setid") == -1) {
1124 msyslog(LOG_ERR, "priv_delset() failed:%m");
1127 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1128 msyslog(LOG_ERR, "setppriv() failed:%m");
1131 priv_freeset(lowprivs);
1132 priv_freeset(highprivs);
1133 # endif /* HAVE_SOLARIS_PRIVS */
1134 root_dropped = TRUE;
1135 fork_deferred_worker();
1136 } /* if (droproot) */
1137 # endif /* HAVE_DROPROOT */
1139 /* libssecomp sandboxing */
1140 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1141 scmp_filter_ctx ctx;
1143 if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1144 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1146 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1155 SCMP_SYS(clock_gettime),
1156 SCMP_SYS(clock_settime),
1159 SCMP_SYS(exit_group),
1163 SCMP_SYS(getitimer),
1164 SCMP_SYS(getsockname),
1175 SCMP_SYS(rt_sigaction),
1176 SCMP_SYS(rt_sigprocmask),
1177 SCMP_SYS(rt_sigreturn),
1180 SCMP_SYS(setitimer),
1190 SCMP_SYS(_newselect),
1194 SCMP_SYS(clock_gettime),
1195 SCMP_SYS(clock_settime),
1197 SCMP_SYS(exit_group),
1200 SCMP_SYS(getitimer),
1209 SCMP_SYS(rt_sigaction),
1210 SCMP_SYS(rt_sigprocmask),
1212 SCMP_SYS(setitimer),
1214 SCMP_SYS(sigprocmask),
1215 SCMP_SYS(sigreturn),
1216 SCMP_SYS(socketcall),
1225 for (i = 0; i < COUNTOF(scmp_sc); i++) {
1226 if (seccomp_rule_add(ctx,
1227 SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1229 "%s: seccomp_rule_add() failed: %m",
1235 if (seccomp_load(ctx) < 0)
1236 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1239 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1241 #endif /* LIBSECCOMP and KERN_SECCOMP */
1243 # ifdef HAVE_IO_COMPLETION_PORT
1246 #if !defined(SIM) && defined(SIGDIE1)
1250 GetReceivedBuffers();
1251 # else /* normal I/O */
1253 BLOCK_IO_AND_ALARM();
1254 was_alarmed = FALSE;
1257 #if !defined(SIM) && defined(SIGDIE1)
1261 if (alarm_flag) { /* alarmed? */
1266 /* collect async name/addr results */
1268 harvest_blocking_responses();
1270 if (!was_alarmed && !has_full_recv_buffer()) {
1272 * Nothing to do. Wait for something.
1277 if (alarm_flag) { /* alarmed? */
1283 UNBLOCK_IO_AND_ALARM();
1285 * Out here, signals are unblocked. Call timer routine
1286 * to process expiry.
1289 was_alarmed = FALSE;
1290 BLOCK_IO_AND_ALARM();
1293 # endif /* !HAVE_IO_COMPLETION_PORT */
1295 # ifdef DEBUG_TIMING
1304 rbuf = get_full_recv_buffer();
1305 while (rbuf != NULL) {
1310 UNBLOCK_IO_AND_ALARM();
1313 /* avoid timer starvation during lengthy I/O handling */
1315 was_alarmed = FALSE;
1319 * Call the data procedure to handle each received
1322 if (rbuf->receiver != NULL) {
1323 # ifdef DEBUG_TIMING
1326 L_SUB(&dts, &rbuf->recv_time);
1327 DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1328 collect_timing(rbuf, "buffer processing delay", 1, &dts);
1331 (*rbuf->receiver)(rbuf);
1333 msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1337 BLOCK_IO_AND_ALARM();
1339 rbuf = get_full_recv_buffer();
1341 # ifdef DEBUG_TIMING
1345 collect_timing(NULL, "processing", bufcount, &tsb);
1346 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1355 # ifdef HAVE_DNSREGISTRATION
1356 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1357 mdnsreg = current_time;
1358 msyslog(LOG_INFO, "Attempting to register mDNS");
1359 if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1360 htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1362 msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1364 msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1367 msyslog(LOG_INFO, "mDNS service registered.");
1371 # endif /* HAVE_DNSREGISTRATION */
1374 UNBLOCK_IO_AND_ALARM();
1380 #if !defined(SIM) && defined(SIGDIE1)
1382 * finish - exit gracefully
1389 const char *sig_desc;
1392 #ifdef HAVE_STRSIGNAL
1393 sig_desc = strsignal(sig);
1395 if (sig_desc == NULL)
1397 msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1399 /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1400 # ifdef HAVE_DNSREGISTRATION
1402 DNSServiceRefDeallocate(mdns);
1417 #endif /* !SIM && SIGDIE1 */
1422 * wait_child_sync_if - implements parent side of -w/--wait-sync
1424 # ifdef HAVE_WORKING_FORK
1433 time_t wait_end_time;
1437 struct timeval wtimeout;
1442 /* waitsync_fd_to_close used solely by child */
1443 close(waitsync_fd_to_close);
1444 wait_end_time = time(NULL) + wait_sync;
1446 cur_time = time(NULL);
1447 wait_rem = (wait_end_time > cur_time)
1448 ? (wait_end_time - cur_time)
1450 wtimeout.tv_sec = wait_rem;
1451 wtimeout.tv_usec = 0;
1453 FD_SET(pipe_read_fd, &readset);
1454 rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1459 exit_code = (errno) ? errno : -1;
1461 "--wait-sync select failed: %m");
1466 * select() indicated a timeout, but in case
1467 * its timeouts are affected by a step of the
1468 * system clock, select() again with a zero
1469 * timeout to confirm.
1472 FD_SET(pipe_read_fd, &readset);
1473 wtimeout.tv_sec = 0;
1474 wtimeout.tv_usec = 0;
1475 rc = select(pipe_read_fd + 1, &readset, NULL,
1477 if (0 == rc) /* select() timeout */
1481 } else /* readable */
1483 } while (wait_rem > 0);
1485 fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1486 progname, wait_sync);
1489 # endif /* HAVE_WORKING_FORK */
1493 * assertion_failed - Redirect assertion failures to msyslog().
1499 isc_assertiontype_t type,
1503 isc_assertion_setcallback(NULL); /* Avoid recursion */
1505 msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1506 file, line, isc_assertion_typetotext(type), cond);
1507 msyslog(LOG_ERR, "exiting (due to assertion failure)");
1509 #if defined(DEBUG) && defined(SYS_WINNT)
1519 * library_fatal_error - Handle fatal errors from our libraries.
1522 library_fatal_error(
1531 isc_error_setfatal(NULL); /* Avoid recursion */
1533 msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1534 vsnprintf(errbuf, sizeof(errbuf), format, args);
1535 msyslog(LOG_ERR, "%s", errbuf);
1536 msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1538 #if defined(DEBUG) && defined(SYS_WINNT)
1548 * library_unexpected_error - Handle non fatal errors from our libraries.
1550 # define MAX_UNEXPECTED_ERRORS 100
1551 int unexpected_error_cnt = 0;
1553 library_unexpected_error(
1562 if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1563 return; /* avoid clutter in log */
1565 msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1566 vsnprintf(errbuf, sizeof(errbuf), format, args);
1567 msyslog(LOG_ERR, "%s", errbuf);
1569 if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1570 msyslog(LOG_ERR, "Too many errors. Shutting up.");
1575 #if !defined(SIM) && !defined(SYS_WINNT)
1579 * moredebug - increase debugging verbosity
1586 int saved_errno = errno;
1591 msyslog(LOG_DEBUG, "debug raised to %d", debug);
1593 errno = saved_errno;
1598 * lessdebug - decrease debugging verbosity
1605 int saved_errno = errno;
1610 msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1612 errno = saved_errno;
1615 # else /* !DEBUG follows */
1619 * no_debug - We don't do the debug here.
1626 int saved_errno = errno;
1628 msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1629 errno = saved_errno;
1631 # endif /* !DEBUG */
1632 #endif /* !SIM && !SYS_WINNT */