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 */
237 int ntpdmain (int, char **);
238 static void set_process_priority (void);
239 static void assertion_failed (const char *, int,
242 __attribute__ ((__noreturn__));
243 static void library_fatal_error (const char *, int,
244 const char *, va_list)
245 ISC_FORMAT_PRINTF(3, 0);
246 static void library_unexpected_error(const char *, int,
247 const char *, va_list)
248 ISC_FORMAT_PRINTF(3, 0);
252 /* Bug2332 unearthed a problem in the interaction of reduced user
253 * privileges, the limits on memory usage and some versions of the
254 * pthread library on Linux systems. The 'pthread_cancel()' function and
255 * likely some others need to track the stack of the thread involved,
256 * and uses a function that comes from GCC (--> libgcc_s.so) to do
257 * this. Unfortunately the developers of glibc decided to load the
258 * library on demand, which speeds up program start but can cause
259 * trouble here: Due to all the things NTPD does to limit its resource
260 * usage, this deferred load of libgcc_s does not always work once the
261 * restrictions are in effect.
263 * One way out of this was attempting a forced link against libgcc_s
264 * when possible because it makes the library available immediately
265 * without deferred load. (The symbol resolution would still be dynamic
266 * and on demand, but the code would already be in the process image.)
268 * This is a tricky thing to do, since it's not necessary everywhere,
269 * not possible everywhere, has shown to break the build of other
270 * programs in the NTP suite and is now generally frowned upon.
272 * So we take a different approach here: We creat a worker thread that does
273 * actually nothing except waiting for cancellation and cancel it. If
274 * this is done before all the limitations are put in place, the
275 * machinery is pre-heated and all the runtime stuff should be in place
276 * and useable when needed.
278 * This uses only the standard pthread API and should work with all
279 * implementations of pthreads. It is not necessary everywhere, but it's
280 * cheap enough to go on nearly unnoticed.
282 * Addendum: Bug 2954 showed that the assumption that this should work
283 * with all OS is wrong -- at least FreeBSD bombs heavily.
285 #ifdef NEED_PTHREAD_WARMUP
287 /* simple thread function: sleep until cancelled, just to exercise
288 * thread cancellation.
291 my_pthread_warmup_worker(
300 /* pre-heat threading: create a thread and cancel it, just to exercise
301 * thread cancellation.
304 my_pthread_warmup(void)
307 pthread_attr_t thr_attr;
310 pthread_attr_init(&thr_attr);
311 #if defined(HAVE_PTHREAD_ATTR_GETSTACKSIZE) && \
312 defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && \
313 defined(PTHREAD_STACK_MIN)
314 rc = pthread_attr_setstacksize(&thr_attr, PTHREAD_STACK_MIN);
317 "my_pthread_warmup: pthread_attr_setstacksize() -> %s",
321 &thread, &thr_attr, my_pthread_warmup_worker, NULL);
322 pthread_attr_destroy(&thr_attr);
325 "my_pthread_warmup: pthread_create() -> %s",
328 pthread_cancel(thread);
329 pthread_join(thread, NULL);
333 #endif /*defined(NEED_PTHREAD_WARMUP)*/
346 optct = ntpOptionProcess(&ntpdOptions, *pargc, *pargv);
363 parse_cmdline_opts(&argc, &argv);
365 debug = OPT_VALUE_SET_DEBUG_LEVEL;
366 DPRINTF(1, ("%s\n", Version));
369 return ntpsim(argc, argv);
371 #else /* !SIM follows */
372 #ifdef NO_MAIN_ALLOWED
373 CALL(ntpd,"ntpd",ntpdmain);
374 #else /* !NO_MAIN_ALLOWED follows */
382 return ntpdmain(argc, argv);
384 #endif /* !SYS_WINNT */
385 #endif /* !NO_MAIN_ALLOWED */
390 * OK. AIX is different than solaris in how it implements plock().
391 * If you do NOT adjust the stack limit, you will get the MAXIMUM
392 * stack size allocated and PINNED with you program. To check the
393 * value, use ulimit -a.
395 * To fix this, we create an automatic variable and set our stack limit
396 * to that PLUS 32KB of extra space (we need some headroom).
398 * This subroutine gets the stack address.
400 * Grover Davidson and Matt Ladendorf
411 * Signal handler for SIGDANGER.
414 catch_danger(int signo)
416 msyslog(LOG_INFO, "ntpd: setpgid(): %m");
417 /* Make the system believe we'll free something, but don't do it! */
423 * Set the process priority
427 set_process_priority(void)
432 msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>",
434 ? "Leave priority alone"
435 : "Attempt to set priority"
440 # if defined(HAVE_SCHED_SETSCHEDULER)
441 if (!priority_done) {
442 extern int config_priority_override, config_priority;
444 struct sched_param sched;
446 pmax = sched_get_priority_max(SCHED_FIFO);
447 sched.sched_priority = pmax;
448 if ( config_priority_override ) {
449 pmin = sched_get_priority_min(SCHED_FIFO);
450 if ( config_priority > pmax )
451 sched.sched_priority = pmax;
452 else if ( config_priority < pmin )
453 sched.sched_priority = pmin;
455 sched.sched_priority = config_priority;
457 if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 )
458 msyslog(LOG_ERR, "sched_setscheduler(): %m");
462 # endif /* HAVE_SCHED_SETSCHEDULER */
465 if (!priority_done) {
468 srtp.type = RTP_PRIO_REALTIME; /* was: RTP_PRIO_NORMAL */
469 srtp.prio = 0; /* 0 (hi) -> RTP_PRIO_MAX (31,lo) */
471 if (rtprio(RTP_SET, getpid(), &srtp) < 0)
472 msyslog(LOG_ERR, "rtprio() error: %m");
476 # else /* !RTP_SET follows */
477 if (!priority_done) {
478 if (rtprio(0, 120) < 0)
479 msyslog(LOG_ERR, "rtprio() error: %m");
483 # endif /* !RTP_SET */
484 # endif /* HAVE_RTPRIO */
485 # if defined(NTPD_PRIO) && NTPD_PRIO != 0
486 # ifdef HAVE_ATT_NICE
487 if (!priority_done) {
489 if (-1 == nice (NTPD_PRIO) && errno != 0)
490 msyslog(LOG_ERR, "nice() error: %m");
494 # endif /* HAVE_ATT_NICE */
495 # ifdef HAVE_BSD_NICE
496 if (!priority_done) {
497 if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO))
498 msyslog(LOG_ERR, "setpriority() error: %m");
502 # endif /* HAVE_BSD_NICE */
503 # endif /* NTPD_PRIO && NTPD_PRIO != 0 */
505 msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority");
511 * Main program. Initialize us, disconnect us from the tty if necessary,
512 * and loop waiting for I/O and/or timer expiries.
522 struct recvbuf *rbuf;
523 const char * logfilename;
527 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
530 # if defined(HAVE_WORKING_FORK)
538 # if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
541 # endif /* HAVE_WORKING_FORK*/
547 # ifdef NEED_PTHREAD_WARMUP
561 initializing = TRUE; /* mark that we are initializing */
562 parse_cmdline_opts(&argc, &argv);
564 debug = OPT_VALUE_SET_DEBUG_LEVEL;
565 # ifdef HAVE_SETLINEBUF
570 if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
574 || HAVE_OPT(SAVECONFIGQUIT))
577 init_logging(progname, NLOG_SYNCMASK, TRUE);
578 /* honor -l/--logfile option to log to a file */
579 if (HAVE_OPT(LOGFILE)) {
580 logfilename = OPT_ARG(LOGFILE);
582 change_logfile(logfilename, FALSE);
587 if (HAVE_OPT(SAVECONFIGQUIT))
590 msyslog(LOG_NOTICE, "%s: Starting", Version);
594 char buf[1024]; /* Secret knowledge of msyslog buf length */
597 /* Note that every arg has an initial space character */
598 snprintf(cp, sizeof(buf), "Command line:");
601 for (i = 0; i < saved_argc ; ++i) {
602 snprintf(cp, sizeof(buf) - (cp - buf),
603 " %s", saved_argv[i]);
606 msyslog(LOG_INFO, "%s", buf);
610 * Install trap handlers to log errors and assertion failures.
611 * Default handlers print to stderr which doesn't work if detached.
613 isc_assertion_setcallback(assertion_failed);
614 isc_error_setfatal(library_fatal_error);
615 isc_error_setunexpected(library_unexpected_error);
617 /* MPE lacks the concept of root */
618 # if defined(HAVE_GETUID) && !defined(MPE)
620 if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
623 "must be run as root, not uid %ld", (long)uid);
629 * Enable the Multi-Media Timer for Windows?
632 if (HAVE_OPT( MODIFYMMTIMER ))
633 set_mm_timer(MM_TIMER_HIRES);
636 #ifdef HAVE_DNSREGISTRATION
638 * Enable mDNS registrations?
640 if (HAVE_OPT( MDNS )) {
643 #endif /* HAVE_DNSREGISTRATION */
645 if (HAVE_OPT( NOVIRTUALIPS ))
646 listen_to_virtual_ips = 0;
649 * --interface, listen on specified interfaces
651 if (HAVE_OPT( INTERFACE )) {
652 int ifacect = STACKCT_OPT( INTERFACE );
653 const char** ifaces = STACKLST_OPT( INTERFACE );
656 while (ifacect-- > 0) {
658 is_ip_address(*ifaces, AF_UNSPEC, &addr)
661 *ifaces, -1, ACTION_LISTEN);
666 if (HAVE_OPT( NICE ))
669 # ifdef HAVE_SCHED_SETSCHEDULER
670 if (HAVE_OPT( PRIORITY )) {
671 config_priority = OPT_VALUE_PRIORITY;
672 config_priority_override = 1;
677 # ifdef HAVE_WORKING_FORK
678 /* make sure the FDs are initialised */
681 do { /* 'loop' once */
682 if (!HAVE_OPT( WAIT_SYNC ))
684 wait_sync = OPT_VALUE_WAIT_SYNC;
685 if (wait_sync <= 0) {
689 /* -w requires a fork() even with debug > 0 */
691 if (pipe(pipe_fds)) {
692 exit_code = (errno) ? errno : -1;
694 "Pipe creation failed for --wait-sync: %m");
697 waitsync_fd_to_close = pipe_fds[1];
698 } while (0); /* 'loop' once */
699 # endif /* HAVE_WORKING_FORK */
704 * Start interpolation thread, must occur before first
710 * Initialize random generator and public key pair
714 ntp_srandom((int)(now.l_i * now.l_uf));
717 * Detach us from the terminal. May need an #ifndef GIZMO.
721 # ifdef HAVE_WORKING_FORK
724 exit_code = (errno) ? errno : -1;
725 msyslog(LOG_ERR, "fork: %m");
730 exit_code = wait_child_sync_if(pipe_fds[0],
737 * close all open files excepting waitsync_fd_to_close.
738 * msyslog() unreliable until after init_logging().
741 if (syslog_file != NULL) {
746 close_all_except(waitsync_fd_to_close);
747 INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
750 init_logging(progname, 0, TRUE);
751 /* we lost our logfile (if any) daemonizing */
752 setup_logfile(logfilename);
759 proc2_$who_am_i(&puid);
760 proc2_$make_server(&puid, &st);
762 # endif /* SYS_DOMAINOS */
764 if (setsid() == (pid_t)-1)
765 msyslog(LOG_ERR, "setsid(): %m");
766 # elif defined(HAVE_SETPGID)
767 if (setpgid(0, 0) == -1)
768 msyslog(LOG_ERR, "setpgid(): %m");
769 # else /* !HAVE_SETSID && !HAVE_SETPGID follows */
771 fid = open("/dev/tty", 2);
773 ioctl(fid, (u_long)TIOCNOTTY, NULL);
776 # endif /* TIOCNOTTY */
777 ntp_setpgrp(0, getpid());
778 # endif /* !HAVE_SETSID && !HAVE_SETPGID */
780 /* Don't get killed by low-on-memory signal. */
781 sa.sa_handler = catch_danger;
782 sigemptyset(&sa.sa_mask);
783 sa.sa_flags = SA_RESTART;
784 sigaction(SIGDANGER, &sa, NULL);
786 # endif /* HAVE_WORKING_FORK */
791 * SCO OpenServer's system clock offers much more precise timekeeping
792 * on the base CPU than the other CPUs (for multiprocessor systems),
793 * so we must lock to the base CPU.
795 fd = open("/dev/at1", O_RDONLY);
798 if (ioctl(fd, ACPU_LOCK, &zero) < 0)
799 msyslog(LOG_ERR, "cannot lock to base CPU: %m");
804 /* Setup stack size in preparation for locking pages in memory. */
805 # if defined(HAVE_MLOCKALL)
806 # ifdef HAVE_SETRLIMIT
807 ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
808 # ifdef RLIMIT_MEMLOCK
810 * The default RLIMIT_MEMLOCK is very low on Linux systems.
811 * Unless we increase this limit malloc calls are likely to
812 * fail if we drop root privilege. To be useful the value
813 * has to be larger than the largest ntpd resident set size.
815 ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
816 # endif /* RLIMIT_MEMLOCK */
817 # endif /* HAVE_SETRLIMIT */
818 # else /* !HAVE_MLOCKALL follows */
823 * set the stack limit for AIX for plock().
824 * see get_aix_stack() for more info.
826 if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
828 "Cannot adjust stack limit for plock: %m");
830 # endif /* PROCLOCK */
831 # endif /* HAVE_PLOCK */
832 # endif /* !HAVE_MLOCKALL */
835 * Set up signals we pay attention to locally.
838 signal_no_reset(SIGDIE1, finish);
839 signal_no_reset(SIGDIE2, finish);
840 signal_no_reset(SIGDIE3, finish);
841 signal_no_reset(SIGDIE4, finish);
844 signal_no_reset(SIGBUS, finish);
847 # if !defined(SYS_WINNT) && !defined(VMS)
849 (void) signal_no_reset(MOREDEBUGSIG, moredebug);
850 (void) signal_no_reset(LESSDEBUGSIG, lessdebug);
852 (void) signal_no_reset(MOREDEBUGSIG, no_debug);
853 (void) signal_no_reset(LESSDEBUGSIG, no_debug);
855 # endif /* !SYS_WINNT && !VMS */
858 * Set up signals we should never pay attention to.
861 signal_no_reset(SIGPIPE, SIG_IGN);
865 * Call the init_ routines to initialize the data structures.
867 * Exactly what command-line options are we expecting here?
881 set_process_priority();
882 init_proto(); /* Call at high priority */
885 mon_start(MON_ON); /* monitor on by default now */
886 /* turn off in config if unwanted */
889 * Get the configuration. This is done in a separate module
890 * since this will definitely be different for the gizmo board.
892 getconfig(argc, argv);
894 if (-1 == cur_memlock) {
895 # if defined(HAVE_MLOCKALL)
897 * lock the process into memory
899 if ( !HAVE_OPT(SAVECONFIGQUIT)
900 # ifdef RLIMIT_MEMLOCK
901 && -1 != DFLT_RLIMIT_MEMLOCK
903 && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
904 msyslog(LOG_ERR, "mlockall(): %m");
905 # else /* !HAVE_MLOCKALL follows */
909 * lock the process into memory
911 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
912 msyslog(LOG_ERR, "plock(PROCLOCK): %m");
913 # else /* !PROCLOCK follows */
918 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
919 msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
920 # else /* !TXTLOCK follows */
921 msyslog(LOG_ERR, "plock() - don't know what to lock!");
922 # endif /* !TXTLOCK */
923 # endif /* !PROCLOCK */
924 # endif /* HAVE_PLOCK */
925 # endif /* !HAVE_MLOCKALL */
928 loop_config(LOOP_DRIFTINIT, 0);
929 report_event(EVNT_SYSRESTART, NULL, NULL);
930 initializing = FALSE;
932 # ifdef HAVE_DROPROOT
934 /* Drop super-user privileges and chroot now if the OS supports this */
936 # ifdef HAVE_LINUX_CAPABILITIES
937 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
938 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
939 msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
942 # elif HAVE_SOLARIS_PRIVS
943 /* Nothing to do here */
945 /* we need a user to switch to */
947 msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
950 # endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
953 if (isdigit((unsigned char)*user)) {
954 sw_uid = (uid_t)strtoul(user, &endp, 0);
958 if ((pw = getpwuid(sw_uid)) != NULL) {
960 user = estrdup(pw->pw_name);
964 msyslog(LOG_ERR, "Cannot find user ID %s", user);
971 if ((pw = getpwnam(user)) != NULL) {
976 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
978 msyslog(LOG_ERR, "Cannot find user `%s'", user);
984 if (isdigit((unsigned char)*group)) {
985 sw_gid = (gid_t)strtoul(group, &endp, 0);
990 if ((gr = getgrnam(group)) != NULL) {
994 msyslog(LOG_ERR, "Cannot find group `%s'", group);
1001 /* make sure cwd is inside the jail: */
1002 if (chdir(chrootdir)) {
1003 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
1006 if (chroot(chrootdir)) {
1007 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
1011 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
1015 # ifdef HAVE_SOLARIS_PRIVS
1016 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
1017 msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
1020 if ((highprivs = priv_allocset()) == NULL) {
1021 msyslog(LOG_ERR, "priv_allocset() failed:%m");
1024 (void) getppriv(PRIV_PERMITTED, highprivs);
1025 (void) priv_intersect(highprivs, lowprivs);
1026 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1027 msyslog(LOG_ERR, "setppriv() failed:%m");
1030 # endif /* HAVE_SOLARIS_PRIVS */
1031 if (user && initgroups(user, sw_gid)) {
1032 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
1035 if (group && setgid(sw_gid)) {
1036 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
1039 if (group && setegid(sw_gid)) {
1040 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
1044 if (0 != setgroups(1, &sw_gid)) {
1045 msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
1050 if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
1051 msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
1054 if (user && setuid(sw_uid)) {
1055 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
1058 if (user && seteuid(sw_uid)) {
1059 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
1063 # if !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1065 * for now assume that the privilege to bind to privileged ports
1066 * is associated with running with uid 0 - should be refined on
1067 * ports that allow binding to NTP_PORT with uid != 0
1069 disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */
1070 # endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1072 if (disable_dynamic_updates && interface_interval) {
1073 interface_interval = 0;
1074 msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1077 # ifdef HAVE_LINUX_CAPABILITIES
1080 * We may be running under non-root uid now, but we still hold full root privileges!
1081 * We drop all of them, except for the crucial one or two: cap_sys_time and
1082 * cap_net_bind_service if doing dynamic interface tracking.
1087 captext = (0 != interface_interval)
1088 ? "cap_sys_time,cap_net_bind_service=pe"
1089 : "cap_sys_time=pe";
1090 caps = cap_from_text(captext);
1093 "cap_from_text(%s) failed: %m",
1097 if (-1 == cap_set_proc(caps)) {
1099 "cap_set_proc() failed to drop root privs: %m");
1104 # endif /* HAVE_LINUX_CAPABILITIES */
1105 # ifdef HAVE_SOLARIS_PRIVS
1106 if (priv_delset(lowprivs, "proc_setid") == -1) {
1107 msyslog(LOG_ERR, "priv_delset() failed:%m");
1110 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1111 msyslog(LOG_ERR, "setppriv() failed:%m");
1114 priv_freeset(lowprivs);
1115 priv_freeset(highprivs);
1116 # endif /* HAVE_SOLARIS_PRIVS */
1117 root_dropped = TRUE;
1118 fork_deferred_worker();
1119 } /* if (droproot) */
1120 # endif /* HAVE_DROPROOT */
1122 /* libssecomp sandboxing */
1123 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1124 scmp_filter_ctx ctx;
1126 if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1127 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1129 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1138 SCMP_SYS(clock_gettime),
1139 SCMP_SYS(clock_settime),
1142 SCMP_SYS(exit_group),
1146 SCMP_SYS(getitimer),
1147 SCMP_SYS(getsockname),
1158 SCMP_SYS(rt_sigaction),
1159 SCMP_SYS(rt_sigprocmask),
1160 SCMP_SYS(rt_sigreturn),
1163 SCMP_SYS(setitimer),
1173 SCMP_SYS(_newselect),
1177 SCMP_SYS(clock_gettime),
1178 SCMP_SYS(clock_settime),
1180 SCMP_SYS(exit_group),
1183 SCMP_SYS(getitimer),
1192 SCMP_SYS(rt_sigaction),
1193 SCMP_SYS(rt_sigprocmask),
1195 SCMP_SYS(setitimer),
1197 SCMP_SYS(sigprocmask),
1198 SCMP_SYS(sigreturn),
1199 SCMP_SYS(socketcall),
1208 for (i = 0; i < COUNTOF(scmp_sc); i++) {
1209 if (seccomp_rule_add(ctx,
1210 SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1212 "%s: seccomp_rule_add() failed: %m",
1218 if (seccomp_load(ctx) < 0)
1219 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1222 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1224 #endif /* LIBSECCOMP and KERN_SECCOMP */
1226 # ifdef HAVE_IO_COMPLETION_PORT
1229 #if !defined(SIM) && defined(SIGDIE1)
1233 GetReceivedBuffers();
1234 # else /* normal I/O */
1236 BLOCK_IO_AND_ALARM();
1237 was_alarmed = FALSE;
1240 #if !defined(SIM) && defined(SIGDIE1)
1244 if (alarm_flag) { /* alarmed? */
1249 /* collect async name/addr results */
1251 harvest_blocking_responses();
1253 if (!was_alarmed && !has_full_recv_buffer()) {
1255 * Nothing to do. Wait for something.
1260 if (alarm_flag) { /* alarmed? */
1266 UNBLOCK_IO_AND_ALARM();
1268 * Out here, signals are unblocked. Call timer routine
1269 * to process expiry.
1272 was_alarmed = FALSE;
1273 BLOCK_IO_AND_ALARM();
1276 # endif /* !HAVE_IO_COMPLETION_PORT */
1278 # ifdef DEBUG_TIMING
1287 rbuf = get_full_recv_buffer();
1288 while (rbuf != NULL) {
1293 UNBLOCK_IO_AND_ALARM();
1296 /* avoid timer starvation during lengthy I/O handling */
1298 was_alarmed = FALSE;
1302 * Call the data procedure to handle each received
1305 if (rbuf->receiver != NULL) {
1306 # ifdef DEBUG_TIMING
1309 L_SUB(&dts, &rbuf->recv_time);
1310 DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1311 collect_timing(rbuf, "buffer processing delay", 1, &dts);
1314 (*rbuf->receiver)(rbuf);
1316 msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1320 BLOCK_IO_AND_ALARM();
1322 rbuf = get_full_recv_buffer();
1324 # ifdef DEBUG_TIMING
1328 collect_timing(NULL, "processing", bufcount, &tsb);
1329 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1338 # ifdef HAVE_DNSREGISTRATION
1339 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1340 mdnsreg = current_time;
1341 msyslog(LOG_INFO, "Attempting to register mDNS");
1342 if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1343 htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1345 msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1347 msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1350 msyslog(LOG_INFO, "mDNS service registered.");
1354 # endif /* HAVE_DNSREGISTRATION */
1357 UNBLOCK_IO_AND_ALARM();
1363 #if !defined(SIM) && defined(SIGDIE1)
1365 * finish - exit gracefully
1372 const char *sig_desc;
1375 #ifdef HAVE_STRSIGNAL
1376 sig_desc = strsignal(sig);
1378 if (sig_desc == NULL)
1380 msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1382 /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1383 # ifdef HAVE_DNSREGISTRATION
1385 DNSServiceRefDeallocate(mdns);
1400 #endif /* !SIM && SIGDIE1 */
1405 * wait_child_sync_if - implements parent side of -w/--wait-sync
1407 # ifdef HAVE_WORKING_FORK
1416 time_t wait_end_time;
1420 struct timeval wtimeout;
1425 /* waitsync_fd_to_close used solely by child */
1426 close(waitsync_fd_to_close);
1427 wait_end_time = time(NULL) + wait_sync;
1429 cur_time = time(NULL);
1430 wait_rem = (wait_end_time > cur_time)
1431 ? (wait_end_time - cur_time)
1433 wtimeout.tv_sec = wait_rem;
1434 wtimeout.tv_usec = 0;
1436 FD_SET(pipe_read_fd, &readset);
1437 rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1442 exit_code = (errno) ? errno : -1;
1444 "--wait-sync select failed: %m");
1449 * select() indicated a timeout, but in case
1450 * its timeouts are affected by a step of the
1451 * system clock, select() again with a zero
1452 * timeout to confirm.
1455 FD_SET(pipe_read_fd, &readset);
1456 wtimeout.tv_sec = 0;
1457 wtimeout.tv_usec = 0;
1458 rc = select(pipe_read_fd + 1, &readset, NULL,
1460 if (0 == rc) /* select() timeout */
1464 } else /* readable */
1466 } while (wait_rem > 0);
1468 fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1469 progname, wait_sync);
1472 # endif /* HAVE_WORKING_FORK */
1476 * assertion_failed - Redirect assertion failures to msyslog().
1482 isc_assertiontype_t type,
1486 isc_assertion_setcallback(NULL); /* Avoid recursion */
1488 msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1489 file, line, isc_assertion_typetotext(type), cond);
1490 msyslog(LOG_ERR, "exiting (due to assertion failure)");
1492 #if defined(DEBUG) && defined(SYS_WINNT)
1502 * library_fatal_error - Handle fatal errors from our libraries.
1505 library_fatal_error(
1514 isc_error_setfatal(NULL); /* Avoid recursion */
1516 msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1517 vsnprintf(errbuf, sizeof(errbuf), format, args);
1518 msyslog(LOG_ERR, "%s", errbuf);
1519 msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1521 #if defined(DEBUG) && defined(SYS_WINNT)
1531 * library_unexpected_error - Handle non fatal errors from our libraries.
1533 # define MAX_UNEXPECTED_ERRORS 100
1534 int unexpected_error_cnt = 0;
1536 library_unexpected_error(
1545 if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1546 return; /* avoid clutter in log */
1548 msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1549 vsnprintf(errbuf, sizeof(errbuf), format, args);
1550 msyslog(LOG_ERR, "%s", errbuf);
1552 if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1553 msyslog(LOG_ERR, "Too many errors. Shutting up.");
1558 #if !defined(SIM) && !defined(SYS_WINNT)
1562 * moredebug - increase debugging verbosity
1569 int saved_errno = errno;
1574 msyslog(LOG_DEBUG, "debug raised to %d", debug);
1576 errno = saved_errno;
1581 * lessdebug - decrease debugging verbosity
1588 int saved_errno = errno;
1593 msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1595 errno = saved_errno;
1598 # else /* !DEBUG follows */
1602 * no_debug - We don't do the debug here.
1609 int saved_errno = errno;
1611 msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1612 errno = saved_errno;
1614 # endif /* !DEBUG */
1615 #endif /* !SIM && !SYS_WINNT */