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 RETSIGTYPE finish (int);
215 #if !defined(SIM) && defined(HAVE_WORKING_FORK)
216 static int wait_child_sync_if (int, long);
219 #if !defined(SIM) && !defined(SYS_WINNT)
221 static RETSIGTYPE moredebug (int);
222 static RETSIGTYPE lessdebug (int);
223 # else /* !DEBUG follows */
224 static RETSIGTYPE no_debug (int);
226 #endif /* !SIM && !SYS_WINNT */
232 int ntpdmain (int, char **);
233 static void set_process_priority (void);
234 static void assertion_failed (const char *, int,
237 __attribute__ ((__noreturn__));
238 static void library_fatal_error (const char *, int,
239 const char *, va_list)
240 ISC_FORMAT_PRINTF(3, 0);
241 static void library_unexpected_error(const char *, int,
242 const char *, va_list)
243 ISC_FORMAT_PRINTF(3, 0);
247 /* Bug2332 unearthed a problem in the interaction of reduced user
248 * privileges, the limits on memory usage and some versions of the
249 * pthread library on Linux systems. The 'pthread_cancel()' function and
250 * likely some others need to track the stack of the thread involved,
251 * and uses a function that comes from GCC (--> libgcc_s.so) to do
252 * this. Unfortunately the developers of glibc decided to load the
253 * library on demand, which speeds up program start but can cause
254 * trouble here: Due to all the things NTPD does to limit its resource
255 * usage, this deferred load of libgcc_s does not always work once the
256 * restrictions are in effect.
258 * One way out of this was attempting a forced link against libgcc_s
259 * when possible because it makes the library available immediately
260 * without deferred load. (The symbol resolution would still be dynamic
261 * and on demand, but the code would already be in the process image.)
263 * This is a tricky thing to do, since it's not necessary everywhere,
264 * not possible everywhere, has shown to break the build of other
265 * programs in the NTP suite and is now generally frowned upon.
267 * So we take a different approach here: We creat a worker thread that does
268 * actually nothing except waiting for cancellation and cancel it. If
269 * this is done before all the limitations are put in place, the
270 * machinery is pre-heated and all the runtime stuff should be in place
271 * and useable when needed.
273 * This uses only the standard pthread API and should work with all
274 * implementations of pthreads. It is not necessary everywhere, but it's
275 * cheap enough to go on nearly unnoticed.
277 * Addendum: Bug 2954 showed that the assumption that this should work
278 * with all OS is wrong -- at least FreeBSD bombs heavily.
280 #ifdef NEED_PTHREAD_WARMUP
282 /* simple thread function: sleep until cancelled, just to exercise
283 * thread cancellation.
286 my_pthread_warmup_worker(
295 /* pre-heat threading: create a thread and cancel it, just to exercise
296 * thread cancellation.
299 my_pthread_warmup(void)
304 &thread, NULL, my_pthread_warmup_worker, NULL);
306 pthread_cancel(thread);
307 pthread_join(thread, NULL);
311 #endif /*defined(NEED_PTHREAD_WARMUP)*/
324 optct = ntpOptionProcess(&ntpdOptions, *pargc, *pargv);
341 parse_cmdline_opts(&argc, &argv);
343 debug = OPT_VALUE_SET_DEBUG_LEVEL;
344 DPRINTF(1, ("%s\n", Version));
347 return ntpsim(argc, argv);
349 #else /* !SIM follows */
350 #ifdef NO_MAIN_ALLOWED
351 CALL(ntpd,"ntpd",ntpdmain);
352 #else /* !NO_MAIN_ALLOWED follows */
360 return ntpdmain(argc, argv);
362 #endif /* !SYS_WINNT */
363 #endif /* !NO_MAIN_ALLOWED */
368 * OK. AIX is different than solaris in how it implements plock().
369 * If you do NOT adjust the stack limit, you will get the MAXIMUM
370 * stack size allocated and PINNED with you program. To check the
371 * value, use ulimit -a.
373 * To fix this, we create an automatic variable and set our stack limit
374 * to that PLUS 32KB of extra space (we need some headroom).
376 * This subroutine gets the stack address.
378 * Grover Davidson and Matt Ladendorf
389 * Signal handler for SIGDANGER.
392 catch_danger(int signo)
394 msyslog(LOG_INFO, "ntpd: setpgid(): %m");
395 /* Make the system believe we'll free something, but don't do it! */
401 * Set the process priority
405 set_process_priority(void)
410 msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>",
412 ? "Leave priority alone"
413 : "Attempt to set priority"
418 # if defined(HAVE_SCHED_SETSCHEDULER)
419 if (!priority_done) {
420 extern int config_priority_override, config_priority;
422 struct sched_param sched;
424 pmax = sched_get_priority_max(SCHED_FIFO);
425 sched.sched_priority = pmax;
426 if ( config_priority_override ) {
427 pmin = sched_get_priority_min(SCHED_FIFO);
428 if ( config_priority > pmax )
429 sched.sched_priority = pmax;
430 else if ( config_priority < pmin )
431 sched.sched_priority = pmin;
433 sched.sched_priority = config_priority;
435 if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 )
436 msyslog(LOG_ERR, "sched_setscheduler(): %m");
440 # endif /* HAVE_SCHED_SETSCHEDULER */
443 if (!priority_done) {
446 srtp.type = RTP_PRIO_REALTIME; /* was: RTP_PRIO_NORMAL */
447 srtp.prio = 0; /* 0 (hi) -> RTP_PRIO_MAX (31,lo) */
449 if (rtprio(RTP_SET, getpid(), &srtp) < 0)
450 msyslog(LOG_ERR, "rtprio() error: %m");
454 # else /* !RTP_SET follows */
455 if (!priority_done) {
456 if (rtprio(0, 120) < 0)
457 msyslog(LOG_ERR, "rtprio() error: %m");
461 # endif /* !RTP_SET */
462 # endif /* HAVE_RTPRIO */
463 # if defined(NTPD_PRIO) && NTPD_PRIO != 0
464 # ifdef HAVE_ATT_NICE
465 if (!priority_done) {
467 if (-1 == nice (NTPD_PRIO) && errno != 0)
468 msyslog(LOG_ERR, "nice() error: %m");
472 # endif /* HAVE_ATT_NICE */
473 # ifdef HAVE_BSD_NICE
474 if (!priority_done) {
475 if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO))
476 msyslog(LOG_ERR, "setpriority() error: %m");
480 # endif /* HAVE_BSD_NICE */
481 # endif /* NTPD_PRIO && NTPD_PRIO != 0 */
483 msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority");
489 * Main program. Initialize us, disconnect us from the tty if necessary,
490 * and loop waiting for I/O and/or timer expiries.
500 struct recvbuf *rbuf;
501 const char * logfilename;
505 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
508 # if defined(HAVE_WORKING_FORK)
516 # if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
519 # endif /* HAVE_WORKING_FORK*/
525 # ifdef NEED_PTHREAD_WARMUP
539 initializing = TRUE; /* mark that we are initializing */
540 parse_cmdline_opts(&argc, &argv);
542 debug = OPT_VALUE_SET_DEBUG_LEVEL;
543 # ifdef HAVE_SETLINEBUF
548 if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
552 || HAVE_OPT(SAVECONFIGQUIT))
555 init_logging(progname, NLOG_SYNCMASK, TRUE);
556 /* honor -l/--logfile option to log to a file */
557 if (HAVE_OPT(LOGFILE)) {
558 logfilename = OPT_ARG(LOGFILE);
560 change_logfile(logfilename, FALSE);
565 if (HAVE_OPT(SAVECONFIGQUIT))
568 msyslog(LOG_NOTICE, "%s: Starting", Version);
572 char buf[1024]; /* Secret knowledge of msyslog buf length */
575 /* Note that every arg has an initial space character */
576 snprintf(cp, sizeof(buf), "Command line:");
579 for (i = 0; i < saved_argc ; ++i) {
580 snprintf(cp, sizeof(buf) - (cp - buf),
581 " %s", saved_argv[i]);
584 msyslog(LOG_INFO, "%s", buf);
588 * Install trap handlers to log errors and assertion failures.
589 * Default handlers print to stderr which doesn't work if detached.
591 isc_assertion_setcallback(assertion_failed);
592 isc_error_setfatal(library_fatal_error);
593 isc_error_setunexpected(library_unexpected_error);
595 /* MPE lacks the concept of root */
596 # if defined(HAVE_GETUID) && !defined(MPE)
598 if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
601 "must be run as root, not uid %ld", (long)uid);
607 * Enable the Multi-Media Timer for Windows?
610 if (HAVE_OPT( MODIFYMMTIMER ))
611 set_mm_timer(MM_TIMER_HIRES);
614 #ifdef HAVE_DNSREGISTRATION
616 * Enable mDNS registrations?
618 if (HAVE_OPT( MDNS )) {
621 #endif /* HAVE_DNSREGISTRATION */
623 if (HAVE_OPT( NOVIRTUALIPS ))
624 listen_to_virtual_ips = 0;
627 * --interface, listen on specified interfaces
629 if (HAVE_OPT( INTERFACE )) {
630 int ifacect = STACKCT_OPT( INTERFACE );
631 const char** ifaces = STACKLST_OPT( INTERFACE );
634 while (ifacect-- > 0) {
636 is_ip_address(*ifaces, AF_UNSPEC, &addr)
639 *ifaces, -1, ACTION_LISTEN);
644 if (HAVE_OPT( NICE ))
647 # ifdef HAVE_SCHED_SETSCHEDULER
648 if (HAVE_OPT( PRIORITY )) {
649 config_priority = OPT_VALUE_PRIORITY;
650 config_priority_override = 1;
655 # ifdef HAVE_WORKING_FORK
656 /* make sure the FDs are initialised */
659 do { /* 'loop' once */
660 if (!HAVE_OPT( WAIT_SYNC ))
662 wait_sync = OPT_VALUE_WAIT_SYNC;
663 if (wait_sync <= 0) {
667 /* -w requires a fork() even with debug > 0 */
669 if (pipe(pipe_fds)) {
670 exit_code = (errno) ? errno : -1;
672 "Pipe creation failed for --wait-sync: %m");
675 waitsync_fd_to_close = pipe_fds[1];
676 } while (0); /* 'loop' once */
677 # endif /* HAVE_WORKING_FORK */
682 * Start interpolation thread, must occur before first
688 * Initialize random generator and public key pair
692 ntp_srandom((int)(now.l_i * now.l_uf));
695 * Detach us from the terminal. May need an #ifndef GIZMO.
699 # ifdef HAVE_WORKING_FORK
702 exit_code = (errno) ? errno : -1;
703 msyslog(LOG_ERR, "fork: %m");
708 exit_code = wait_child_sync_if(pipe_fds[0],
715 * close all open files excepting waitsync_fd_to_close.
716 * msyslog() unreliable until after init_logging().
719 if (syslog_file != NULL) {
724 close_all_except(waitsync_fd_to_close);
725 INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
728 init_logging(progname, 0, TRUE);
729 /* we lost our logfile (if any) daemonizing */
730 setup_logfile(logfilename);
737 proc2_$who_am_i(&puid);
738 proc2_$make_server(&puid, &st);
740 # endif /* SYS_DOMAINOS */
742 if (setsid() == (pid_t)-1)
743 msyslog(LOG_ERR, "setsid(): %m");
744 # elif defined(HAVE_SETPGID)
745 if (setpgid(0, 0) == -1)
746 msyslog(LOG_ERR, "setpgid(): %m");
747 # else /* !HAVE_SETSID && !HAVE_SETPGID follows */
749 fid = open("/dev/tty", 2);
751 ioctl(fid, (u_long)TIOCNOTTY, NULL);
754 # endif /* TIOCNOTTY */
755 ntp_setpgrp(0, getpid());
756 # endif /* !HAVE_SETSID && !HAVE_SETPGID */
758 /* Don't get killed by low-on-memory signal. */
759 sa.sa_handler = catch_danger;
760 sigemptyset(&sa.sa_mask);
761 sa.sa_flags = SA_RESTART;
762 sigaction(SIGDANGER, &sa, NULL);
764 # endif /* HAVE_WORKING_FORK */
769 * SCO OpenServer's system clock offers much more precise timekeeping
770 * on the base CPU than the other CPUs (for multiprocessor systems),
771 * so we must lock to the base CPU.
773 fd = open("/dev/at1", O_RDONLY);
776 if (ioctl(fd, ACPU_LOCK, &zero) < 0)
777 msyslog(LOG_ERR, "cannot lock to base CPU: %m");
782 /* Setup stack size in preparation for locking pages in memory. */
783 # if defined(HAVE_MLOCKALL)
784 # ifdef HAVE_SETRLIMIT
785 ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
786 # ifdef RLIMIT_MEMLOCK
788 * The default RLIMIT_MEMLOCK is very low on Linux systems.
789 * Unless we increase this limit malloc calls are likely to
790 * fail if we drop root privilege. To be useful the value
791 * has to be larger than the largest ntpd resident set size.
793 ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
794 # endif /* RLIMIT_MEMLOCK */
795 # endif /* HAVE_SETRLIMIT */
796 # else /* !HAVE_MLOCKALL follows */
801 * set the stack limit for AIX for plock().
802 * see get_aix_stack() for more info.
804 if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
806 "Cannot adjust stack limit for plock: %m");
808 # endif /* PROCLOCK */
809 # endif /* HAVE_PLOCK */
810 # endif /* !HAVE_MLOCKALL */
813 * Set up signals we pay attention to locally.
816 signal_no_reset(SIGDIE1, finish);
817 signal_no_reset(SIGDIE2, finish);
818 signal_no_reset(SIGDIE3, finish);
819 signal_no_reset(SIGDIE4, finish);
822 signal_no_reset(SIGBUS, finish);
825 # if !defined(SYS_WINNT) && !defined(VMS)
827 (void) signal_no_reset(MOREDEBUGSIG, moredebug);
828 (void) signal_no_reset(LESSDEBUGSIG, lessdebug);
830 (void) signal_no_reset(MOREDEBUGSIG, no_debug);
831 (void) signal_no_reset(LESSDEBUGSIG, no_debug);
833 # endif /* !SYS_WINNT && !VMS */
836 * Set up signals we should never pay attention to.
839 signal_no_reset(SIGPIPE, SIG_IGN);
843 * Call the init_ routines to initialize the data structures.
845 * Exactly what command-line options are we expecting here?
859 set_process_priority();
860 init_proto(); /* Call at high priority */
863 mon_start(MON_ON); /* monitor on by default now */
864 /* turn off in config if unwanted */
867 * Get the configuration. This is done in a separate module
868 * since this will definitely be different for the gizmo board.
870 getconfig(argc, argv);
872 if (-1 == cur_memlock) {
873 # if defined(HAVE_MLOCKALL)
875 * lock the process into memory
877 if ( !HAVE_OPT(SAVECONFIGQUIT)
878 # ifdef RLIMIT_MEMLOCK
879 && -1 != DFLT_RLIMIT_MEMLOCK
881 && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
882 msyslog(LOG_ERR, "mlockall(): %m");
883 # else /* !HAVE_MLOCKALL follows */
887 * lock the process into memory
889 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
890 msyslog(LOG_ERR, "plock(PROCLOCK): %m");
891 # else /* !PROCLOCK follows */
896 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
897 msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
898 # else /* !TXTLOCK follows */
899 msyslog(LOG_ERR, "plock() - don't know what to lock!");
900 # endif /* !TXTLOCK */
901 # endif /* !PROCLOCK */
902 # endif /* HAVE_PLOCK */
903 # endif /* !HAVE_MLOCKALL */
906 loop_config(LOOP_DRIFTINIT, 0);
907 report_event(EVNT_SYSRESTART, NULL, NULL);
908 initializing = FALSE;
910 # ifdef HAVE_DROPROOT
912 /* Drop super-user privileges and chroot now if the OS supports this */
914 # ifdef HAVE_LINUX_CAPABILITIES
915 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
916 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
917 msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
920 # elif HAVE_SOLARIS_PRIVS
921 /* Nothing to do here */
923 /* we need a user to switch to */
925 msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
928 # endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
931 if (isdigit((unsigned char)*user)) {
932 sw_uid = (uid_t)strtoul(user, &endp, 0);
936 if ((pw = getpwuid(sw_uid)) != NULL) {
938 user = estrdup(pw->pw_name);
942 msyslog(LOG_ERR, "Cannot find user ID %s", user);
949 if ((pw = getpwnam(user)) != NULL) {
954 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
956 msyslog(LOG_ERR, "Cannot find user `%s'", user);
962 if (isdigit((unsigned char)*group)) {
963 sw_gid = (gid_t)strtoul(group, &endp, 0);
968 if ((gr = getgrnam(group)) != NULL) {
972 msyslog(LOG_ERR, "Cannot find group `%s'", group);
979 /* make sure cwd is inside the jail: */
980 if (chdir(chrootdir)) {
981 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
984 if (chroot(chrootdir)) {
985 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
989 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
993 # ifdef HAVE_SOLARIS_PRIVS
994 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
995 msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
998 if ((highprivs = priv_allocset()) == NULL) {
999 msyslog(LOG_ERR, "priv_allocset() failed:%m");
1002 (void) getppriv(PRIV_PERMITTED, highprivs);
1003 (void) priv_intersect(highprivs, lowprivs);
1004 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1005 msyslog(LOG_ERR, "setppriv() failed:%m");
1008 # endif /* HAVE_SOLARIS_PRIVS */
1009 if (user && initgroups(user, sw_gid)) {
1010 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
1013 if (group && setgid(sw_gid)) {
1014 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
1017 if (group && setegid(sw_gid)) {
1018 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
1022 if (0 != setgroups(1, &sw_gid)) {
1023 msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
1028 if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
1029 msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
1032 if (user && setuid(sw_uid)) {
1033 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
1036 if (user && seteuid(sw_uid)) {
1037 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
1041 # if !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1043 * for now assume that the privilege to bind to privileged ports
1044 * is associated with running with uid 0 - should be refined on
1045 * ports that allow binding to NTP_PORT with uid != 0
1047 disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */
1048 # endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1050 if (disable_dynamic_updates && interface_interval) {
1051 interface_interval = 0;
1052 msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1055 # ifdef HAVE_LINUX_CAPABILITIES
1058 * We may be running under non-root uid now, but we still hold full root privileges!
1059 * We drop all of them, except for the crucial one or two: cap_sys_time and
1060 * cap_net_bind_service if doing dynamic interface tracking.
1065 captext = (0 != interface_interval)
1066 ? "cap_sys_time,cap_net_bind_service=pe"
1067 : "cap_sys_time=pe";
1068 caps = cap_from_text(captext);
1071 "cap_from_text(%s) failed: %m",
1075 if (-1 == cap_set_proc(caps)) {
1077 "cap_set_proc() failed to drop root privs: %m");
1082 # endif /* HAVE_LINUX_CAPABILITIES */
1083 # ifdef HAVE_SOLARIS_PRIVS
1084 if (priv_delset(lowprivs, "proc_setid") == -1) {
1085 msyslog(LOG_ERR, "priv_delset() failed:%m");
1088 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1089 msyslog(LOG_ERR, "setppriv() failed:%m");
1092 priv_freeset(lowprivs);
1093 priv_freeset(highprivs);
1094 # endif /* HAVE_SOLARIS_PRIVS */
1095 root_dropped = TRUE;
1096 fork_deferred_worker();
1097 } /* if (droproot) */
1098 # endif /* HAVE_DROPROOT */
1100 /* libssecomp sandboxing */
1101 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1102 scmp_filter_ctx ctx;
1104 if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1105 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1107 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1116 SCMP_SYS(clock_gettime),
1117 SCMP_SYS(clock_settime),
1120 SCMP_SYS(exit_group),
1124 SCMP_SYS(getitimer),
1125 SCMP_SYS(getsockname),
1136 SCMP_SYS(rt_sigaction),
1137 SCMP_SYS(rt_sigprocmask),
1138 SCMP_SYS(rt_sigreturn),
1141 SCMP_SYS(setitimer),
1151 SCMP_SYS(_newselect),
1155 SCMP_SYS(clock_gettime),
1156 SCMP_SYS(clock_settime),
1158 SCMP_SYS(exit_group),
1161 SCMP_SYS(getitimer),
1170 SCMP_SYS(rt_sigaction),
1171 SCMP_SYS(rt_sigprocmask),
1173 SCMP_SYS(setitimer),
1175 SCMP_SYS(sigprocmask),
1176 SCMP_SYS(sigreturn),
1177 SCMP_SYS(socketcall),
1186 for (i = 0; i < COUNTOF(scmp_sc); i++) {
1187 if (seccomp_rule_add(ctx,
1188 SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1190 "%s: seccomp_rule_add() failed: %m",
1196 if (seccomp_load(ctx) < 0)
1197 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1200 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1202 #endif /* LIBSECCOMP and KERN_SECCOMP */
1204 # ifdef HAVE_IO_COMPLETION_PORT
1207 GetReceivedBuffers();
1208 # else /* normal I/O */
1210 BLOCK_IO_AND_ALARM();
1211 was_alarmed = FALSE;
1214 if (alarm_flag) { /* alarmed? */
1219 if (!was_alarmed && !has_full_recv_buffer()) {
1221 * Nothing to do. Wait for something.
1226 if (alarm_flag) { /* alarmed? */
1232 UNBLOCK_IO_AND_ALARM();
1234 * Out here, signals are unblocked. Call timer routine
1235 * to process expiry.
1238 was_alarmed = FALSE;
1239 BLOCK_IO_AND_ALARM();
1242 # endif /* !HAVE_IO_COMPLETION_PORT */
1244 # ifdef DEBUG_TIMING
1253 rbuf = get_full_recv_buffer();
1254 while (rbuf != NULL) {
1259 UNBLOCK_IO_AND_ALARM();
1262 /* avoid timer starvation during lengthy I/O handling */
1264 was_alarmed = FALSE;
1268 * Call the data procedure to handle each received
1271 if (rbuf->receiver != NULL) {
1272 # ifdef DEBUG_TIMING
1275 L_SUB(&dts, &rbuf->recv_time);
1276 DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1277 collect_timing(rbuf, "buffer processing delay", 1, &dts);
1280 (*rbuf->receiver)(rbuf);
1282 msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1286 BLOCK_IO_AND_ALARM();
1288 rbuf = get_full_recv_buffer();
1290 # ifdef DEBUG_TIMING
1294 collect_timing(NULL, "processing", bufcount, &tsb);
1295 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1304 # ifdef HAVE_DNSREGISTRATION
1305 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1306 mdnsreg = current_time;
1307 msyslog(LOG_INFO, "Attempting to register mDNS");
1308 if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1309 htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1311 msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1313 msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1316 msyslog(LOG_INFO, "mDNS service registered.");
1320 # endif /* HAVE_DNSREGISTRATION */
1323 UNBLOCK_IO_AND_ALARM();
1329 #if !defined(SIM) && defined(SIGDIE1)
1331 * finish - exit gracefully
1338 const char *sig_desc;
1341 #ifdef HAVE_STRSIGNAL
1342 sig_desc = strsignal(sig);
1344 if (sig_desc == NULL)
1346 msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1348 /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1349 # ifdef HAVE_DNSREGISTRATION
1351 DNSServiceRefDeallocate(mdns);
1356 #endif /* !SIM && SIGDIE1 */
1361 * wait_child_sync_if - implements parent side of -w/--wait-sync
1363 # ifdef HAVE_WORKING_FORK
1372 time_t wait_end_time;
1376 struct timeval wtimeout;
1381 /* waitsync_fd_to_close used solely by child */
1382 close(waitsync_fd_to_close);
1383 wait_end_time = time(NULL) + wait_sync;
1385 cur_time = time(NULL);
1386 wait_rem = (wait_end_time > cur_time)
1387 ? (wait_end_time - cur_time)
1389 wtimeout.tv_sec = wait_rem;
1390 wtimeout.tv_usec = 0;
1392 FD_SET(pipe_read_fd, &readset);
1393 rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1398 exit_code = (errno) ? errno : -1;
1400 "--wait-sync select failed: %m");
1405 * select() indicated a timeout, but in case
1406 * its timeouts are affected by a step of the
1407 * system clock, select() again with a zero
1408 * timeout to confirm.
1411 FD_SET(pipe_read_fd, &readset);
1412 wtimeout.tv_sec = 0;
1413 wtimeout.tv_usec = 0;
1414 rc = select(pipe_read_fd + 1, &readset, NULL,
1416 if (0 == rc) /* select() timeout */
1420 } else /* readable */
1422 } while (wait_rem > 0);
1424 fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1425 progname, wait_sync);
1428 # endif /* HAVE_WORKING_FORK */
1432 * assertion_failed - Redirect assertion failures to msyslog().
1438 isc_assertiontype_t type,
1442 isc_assertion_setcallback(NULL); /* Avoid recursion */
1444 msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1445 file, line, isc_assertion_typetotext(type), cond);
1446 msyslog(LOG_ERR, "exiting (due to assertion failure)");
1448 #if defined(DEBUG) && defined(SYS_WINNT)
1458 * library_fatal_error - Handle fatal errors from our libraries.
1461 library_fatal_error(
1470 isc_error_setfatal(NULL); /* Avoid recursion */
1472 msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1473 vsnprintf(errbuf, sizeof(errbuf), format, args);
1474 msyslog(LOG_ERR, "%s", errbuf);
1475 msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1477 #if defined(DEBUG) && defined(SYS_WINNT)
1487 * library_unexpected_error - Handle non fatal errors from our libraries.
1489 # define MAX_UNEXPECTED_ERRORS 100
1490 int unexpected_error_cnt = 0;
1492 library_unexpected_error(
1501 if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1502 return; /* avoid clutter in log */
1504 msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1505 vsnprintf(errbuf, sizeof(errbuf), format, args);
1506 msyslog(LOG_ERR, "%s", errbuf);
1508 if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1509 msyslog(LOG_ERR, "Too many errors. Shutting up.");
1514 #if !defined(SIM) && !defined(SYS_WINNT)
1518 * moredebug - increase debugging verbosity
1525 int saved_errno = errno;
1530 msyslog(LOG_DEBUG, "debug raised to %d", debug);
1532 errno = saved_errno;
1537 * lessdebug - decrease debugging verbosity
1544 int saved_errno = errno;
1549 msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1551 errno = saved_errno;
1554 # else /* !DEBUG follows */
1558 * no_debug - We don't do the debug here.
1565 int saved_errno = errno;
1567 msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1568 errno = saved_errno;
1570 # endif /* !DEBUG */
1571 #endif /* !SIM && !SYS_WINNT */