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)*/
335 #ifdef NEED_EARLY_FORK
337 dummy_callback(void) { return; }
340 fork_nonchroot_worker(void) {
341 getaddrinfo_sometime("localhost", "ntp", NULL, INITIAL_DNS_RETRY,
342 (gai_sometime_callback)&dummy_callback, NULL);
344 #endif /* NEED_EARLY_FORK */
356 optct = ntpOptionProcess(&ntpdOptions, *pargc, *pargv);
373 parse_cmdline_opts(&argc, &argv);
375 debug = OPT_VALUE_SET_DEBUG_LEVEL;
376 DPRINTF(1, ("%s\n", Version));
379 return ntpsim(argc, argv);
381 #else /* !SIM follows */
382 #ifdef NO_MAIN_ALLOWED
383 CALL(ntpd,"ntpd",ntpdmain);
384 #else /* !NO_MAIN_ALLOWED follows */
392 return ntpdmain(argc, argv);
394 #endif /* !SYS_WINNT */
395 #endif /* !NO_MAIN_ALLOWED */
400 * OK. AIX is different than solaris in how it implements plock().
401 * If you do NOT adjust the stack limit, you will get the MAXIMUM
402 * stack size allocated and PINNED with you program. To check the
403 * value, use ulimit -a.
405 * To fix this, we create an automatic variable and set our stack limit
406 * to that PLUS 32KB of extra space (we need some headroom).
408 * This subroutine gets the stack address.
410 * Grover Davidson and Matt Ladendorf
421 * Signal handler for SIGDANGER.
424 catch_danger(int signo)
426 msyslog(LOG_INFO, "ntpd: setpgid(): %m");
427 /* Make the system believe we'll free something, but don't do it! */
433 * Set the process priority
437 set_process_priority(void)
442 msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>",
444 ? "Leave priority alone"
445 : "Attempt to set priority"
450 # if defined(HAVE_SCHED_SETSCHEDULER)
451 if (!priority_done) {
452 extern int config_priority_override, config_priority;
454 struct sched_param sched;
456 pmax = sched_get_priority_max(SCHED_FIFO);
457 sched.sched_priority = pmax;
458 if ( config_priority_override ) {
459 pmin = sched_get_priority_min(SCHED_FIFO);
460 if ( config_priority > pmax )
461 sched.sched_priority = pmax;
462 else if ( config_priority < pmin )
463 sched.sched_priority = pmin;
465 sched.sched_priority = config_priority;
467 if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 )
468 msyslog(LOG_ERR, "sched_setscheduler(): %m");
472 # endif /* HAVE_SCHED_SETSCHEDULER */
475 if (!priority_done) {
478 srtp.type = RTP_PRIO_REALTIME; /* was: RTP_PRIO_NORMAL */
479 srtp.prio = 0; /* 0 (hi) -> RTP_PRIO_MAX (31,lo) */
481 if (rtprio(RTP_SET, getpid(), &srtp) < 0)
482 msyslog(LOG_ERR, "rtprio() error: %m");
486 # else /* !RTP_SET follows */
487 if (!priority_done) {
488 if (rtprio(0, 120) < 0)
489 msyslog(LOG_ERR, "rtprio() error: %m");
493 # endif /* !RTP_SET */
494 # endif /* HAVE_RTPRIO */
495 # if defined(NTPD_PRIO) && NTPD_PRIO != 0
496 # ifdef HAVE_ATT_NICE
497 if (!priority_done) {
499 if (-1 == nice (NTPD_PRIO) && errno != 0)
500 msyslog(LOG_ERR, "nice() error: %m");
504 # endif /* HAVE_ATT_NICE */
505 # ifdef HAVE_BSD_NICE
506 if (!priority_done) {
507 if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO))
508 msyslog(LOG_ERR, "setpriority() error: %m");
512 # endif /* HAVE_BSD_NICE */
513 # endif /* NTPD_PRIO && NTPD_PRIO != 0 */
515 msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority");
521 * Main program. Initialize us, disconnect us from the tty if necessary,
522 * and loop waiting for I/O and/or timer expiries.
532 struct recvbuf *rbuf;
533 const char * logfilename;
537 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
540 # if defined(HAVE_WORKING_FORK)
548 # if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
551 # endif /* HAVE_WORKING_FORK*/
557 # ifdef NEED_PTHREAD_WARMUP
571 initializing = TRUE; /* mark that we are initializing */
572 parse_cmdline_opts(&argc, &argv);
574 debug = OPT_VALUE_SET_DEBUG_LEVEL;
575 # ifdef HAVE_SETLINEBUF
580 if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
584 || HAVE_OPT(SAVECONFIGQUIT))
587 init_logging(progname, NLOG_SYNCMASK, TRUE);
588 /* honor -l/--logfile option to log to a file */
589 if (HAVE_OPT(LOGFILE)) {
590 logfilename = OPT_ARG(LOGFILE);
592 change_logfile(logfilename, FALSE);
597 if (HAVE_OPT(SAVECONFIGQUIT))
600 msyslog(LOG_NOTICE, "%s: Starting", Version);
604 char buf[1024]; /* Secret knowledge of msyslog buf length */
607 /* Note that every arg has an initial space character */
608 snprintf(cp, sizeof(buf), "Command line:");
611 for (i = 0; i < saved_argc ; ++i) {
612 snprintf(cp, sizeof(buf) - (cp - buf),
613 " %s", saved_argv[i]);
616 msyslog(LOG_INFO, "%s", buf);
620 * Install trap handlers to log errors and assertion failures.
621 * Default handlers print to stderr which doesn't work if detached.
623 isc_assertion_setcallback(assertion_failed);
624 isc_error_setfatal(library_fatal_error);
625 isc_error_setunexpected(library_unexpected_error);
627 /* MPE lacks the concept of root */
628 # if defined(HAVE_GETUID) && !defined(MPE)
630 if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
633 "must be run as root, not uid %ld", (long)uid);
639 * Enable the Multi-Media Timer for Windows?
642 if (HAVE_OPT( MODIFYMMTIMER ))
643 set_mm_timer(MM_TIMER_HIRES);
646 #ifdef HAVE_DNSREGISTRATION
648 * Enable mDNS registrations?
650 if (HAVE_OPT( MDNS )) {
653 #endif /* HAVE_DNSREGISTRATION */
655 if (HAVE_OPT( NOVIRTUALIPS ))
656 listen_to_virtual_ips = 0;
659 * --interface, listen on specified interfaces
661 if (HAVE_OPT( INTERFACE )) {
662 int ifacect = STACKCT_OPT( INTERFACE );
663 const char** ifaces = STACKLST_OPT( INTERFACE );
666 while (ifacect-- > 0) {
668 is_ip_address(*ifaces, AF_UNSPEC, &addr)
671 *ifaces, -1, ACTION_LISTEN);
676 if (HAVE_OPT( NICE ))
679 # ifdef HAVE_SCHED_SETSCHEDULER
680 if (HAVE_OPT( PRIORITY )) {
681 config_priority = OPT_VALUE_PRIORITY;
682 config_priority_override = 1;
687 # ifdef HAVE_WORKING_FORK
688 /* make sure the FDs are initialised */
691 do { /* 'loop' once */
692 if (!HAVE_OPT( WAIT_SYNC ))
694 wait_sync = OPT_VALUE_WAIT_SYNC;
695 if (wait_sync <= 0) {
699 /* -w requires a fork() even with debug > 0 */
701 if (pipe(pipe_fds)) {
702 exit_code = (errno) ? errno : -1;
704 "Pipe creation failed for --wait-sync: %m");
707 waitsync_fd_to_close = pipe_fds[1];
708 } while (0); /* 'loop' once */
709 # endif /* HAVE_WORKING_FORK */
714 * Start interpolation thread, must occur before first
720 * Initialize random generator and public key pair
724 ntp_srandom((int)(now.l_i * now.l_uf));
727 * Detach us from the terminal. May need an #ifndef GIZMO.
731 # ifdef HAVE_WORKING_FORK
734 exit_code = (errno) ? errno : -1;
735 msyslog(LOG_ERR, "fork: %m");
740 exit_code = wait_child_sync_if(pipe_fds[0],
747 * close all open files excepting waitsync_fd_to_close.
748 * msyslog() unreliable until after init_logging().
751 if (syslog_file != NULL) {
756 close_all_except(waitsync_fd_to_close);
757 INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
760 init_logging(progname, 0, TRUE);
761 /* we lost our logfile (if any) daemonizing */
762 setup_logfile(logfilename);
769 proc2_$who_am_i(&puid);
770 proc2_$make_server(&puid, &st);
772 # endif /* SYS_DOMAINOS */
774 if (setsid() == (pid_t)-1)
775 msyslog(LOG_ERR, "setsid(): %m");
776 # elif defined(HAVE_SETPGID)
777 if (setpgid(0, 0) == -1)
778 msyslog(LOG_ERR, "setpgid(): %m");
779 # else /* !HAVE_SETSID && !HAVE_SETPGID follows */
781 fid = open("/dev/tty", 2);
783 ioctl(fid, (u_long)TIOCNOTTY, NULL);
786 # endif /* TIOCNOTTY */
787 ntp_setpgrp(0, getpid());
788 # endif /* !HAVE_SETSID && !HAVE_SETPGID */
790 /* Don't get killed by low-on-memory signal. */
791 sa.sa_handler = catch_danger;
792 sigemptyset(&sa.sa_mask);
793 sa.sa_flags = SA_RESTART;
794 sigaction(SIGDANGER, &sa, NULL);
796 # endif /* HAVE_WORKING_FORK */
801 * SCO OpenServer's system clock offers much more precise timekeeping
802 * on the base CPU than the other CPUs (for multiprocessor systems),
803 * so we must lock to the base CPU.
805 fd = open("/dev/at1", O_RDONLY);
808 if (ioctl(fd, ACPU_LOCK, &zero) < 0)
809 msyslog(LOG_ERR, "cannot lock to base CPU: %m");
814 /* Setup stack size in preparation for locking pages in memory. */
815 # if defined(HAVE_MLOCKALL)
816 # ifdef HAVE_SETRLIMIT
817 ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
818 # ifdef RLIMIT_MEMLOCK
820 * The default RLIMIT_MEMLOCK is very low on Linux systems.
821 * Unless we increase this limit malloc calls are likely to
822 * fail if we drop root privilege. To be useful the value
823 * has to be larger than the largest ntpd resident set size.
825 ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
826 # endif /* RLIMIT_MEMLOCK */
827 # endif /* HAVE_SETRLIMIT */
828 # else /* !HAVE_MLOCKALL follows */
833 * set the stack limit for AIX for plock().
834 * see get_aix_stack() for more info.
836 if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
838 "Cannot adjust stack limit for plock: %m");
840 # endif /* PROCLOCK */
841 # endif /* HAVE_PLOCK */
842 # endif /* !HAVE_MLOCKALL */
845 * Set up signals we pay attention to locally.
848 signal_no_reset(SIGDIE1, finish);
849 signal_no_reset(SIGDIE2, finish);
850 signal_no_reset(SIGDIE3, finish);
851 signal_no_reset(SIGDIE4, finish);
854 signal_no_reset(SIGBUS, finish);
857 # if !defined(SYS_WINNT) && !defined(VMS)
859 (void) signal_no_reset(MOREDEBUGSIG, moredebug);
860 (void) signal_no_reset(LESSDEBUGSIG, lessdebug);
862 (void) signal_no_reset(MOREDEBUGSIG, no_debug);
863 (void) signal_no_reset(LESSDEBUGSIG, no_debug);
865 # endif /* !SYS_WINNT && !VMS */
868 * Set up signals we should never pay attention to.
871 signal_no_reset(SIGPIPE, SIG_IGN);
875 * Call the init_ routines to initialize the data structures.
877 * Exactly what command-line options are we expecting here?
891 set_process_priority();
892 init_proto(); /* Call at high priority */
895 mon_start(MON_ON); /* monitor on by default now */
896 /* turn off in config if unwanted */
899 * Get the configuration. This is done in a separate module
900 * since this will definitely be different for the gizmo board.
902 getconfig(argc, argv);
904 if (-1 == cur_memlock) {
905 # if defined(HAVE_MLOCKALL)
907 * lock the process into memory
909 if ( !HAVE_OPT(SAVECONFIGQUIT)
910 # ifdef RLIMIT_MEMLOCK
911 && -1 != DFLT_RLIMIT_MEMLOCK
913 && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
914 msyslog(LOG_ERR, "mlockall(): %m");
915 # else /* !HAVE_MLOCKALL follows */
919 * lock the process into memory
921 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
922 msyslog(LOG_ERR, "plock(PROCLOCK): %m");
923 # else /* !PROCLOCK follows */
928 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
929 msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
930 # else /* !TXTLOCK follows */
931 msyslog(LOG_ERR, "plock() - don't know what to lock!");
932 # endif /* !TXTLOCK */
933 # endif /* !PROCLOCK */
934 # endif /* HAVE_PLOCK */
935 # endif /* !HAVE_MLOCKALL */
938 loop_config(LOOP_DRIFTINIT, 0);
939 report_event(EVNT_SYSRESTART, NULL, NULL);
940 initializing = FALSE;
942 # ifdef HAVE_DROPROOT
945 #ifdef NEED_EARLY_FORK
946 fork_nonchroot_worker();
949 /* Drop super-user privileges and chroot now if the OS supports this */
951 # ifdef HAVE_LINUX_CAPABILITIES
952 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
953 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
954 msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
957 # elif HAVE_SOLARIS_PRIVS
958 /* Nothing to do here */
960 /* we need a user to switch to */
962 msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
965 # endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
968 if (isdigit((unsigned char)*user)) {
969 sw_uid = (uid_t)strtoul(user, &endp, 0);
973 if ((pw = getpwuid(sw_uid)) != NULL) {
975 user = estrdup(pw->pw_name);
979 msyslog(LOG_ERR, "Cannot find user ID %s", user);
986 if ((pw = getpwnam(user)) != NULL) {
991 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
993 msyslog(LOG_ERR, "Cannot find user `%s'", user);
999 if (isdigit((unsigned char)*group)) {
1000 sw_gid = (gid_t)strtoul(group, &endp, 0);
1005 if ((gr = getgrnam(group)) != NULL) {
1006 sw_gid = gr->gr_gid;
1009 msyslog(LOG_ERR, "Cannot find group `%s'", group);
1016 /* make sure cwd is inside the jail: */
1017 if (chdir(chrootdir)) {
1018 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
1021 if (chroot(chrootdir)) {
1022 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
1026 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
1030 # ifdef HAVE_SOLARIS_PRIVS
1031 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
1032 msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
1035 if ((highprivs = priv_allocset()) == NULL) {
1036 msyslog(LOG_ERR, "priv_allocset() failed:%m");
1039 (void) getppriv(PRIV_PERMITTED, highprivs);
1040 (void) priv_intersect(highprivs, lowprivs);
1041 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1042 msyslog(LOG_ERR, "setppriv() failed:%m");
1045 # endif /* HAVE_SOLARIS_PRIVS */
1046 if (user && initgroups(user, sw_gid)) {
1047 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
1050 if (group && setgid(sw_gid)) {
1051 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
1054 if (group && setegid(sw_gid)) {
1055 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
1059 if (0 != setgroups(1, &sw_gid)) {
1060 msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
1065 if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
1066 msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
1069 if (user && setuid(sw_uid)) {
1070 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
1073 if (user && seteuid(sw_uid)) {
1074 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
1078 # if !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1080 * for now assume that the privilege to bind to privileged ports
1081 * is associated with running with uid 0 - should be refined on
1082 * ports that allow binding to NTP_PORT with uid != 0
1084 disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */
1085 # endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1087 if (disable_dynamic_updates && interface_interval) {
1088 interface_interval = 0;
1089 msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1092 # ifdef HAVE_LINUX_CAPABILITIES
1095 * We may be running under non-root uid now, but we still hold full root privileges!
1096 * We drop all of them, except for the crucial one or two: cap_sys_time and
1097 * cap_net_bind_service if doing dynamic interface tracking.
1102 captext = (0 != interface_interval)
1103 ? "cap_sys_time,cap_net_bind_service=pe"
1104 : "cap_sys_time=pe";
1105 caps = cap_from_text(captext);
1108 "cap_from_text(%s) failed: %m",
1112 if (-1 == cap_set_proc(caps)) {
1114 "cap_set_proc() failed to drop root privs: %m");
1119 # endif /* HAVE_LINUX_CAPABILITIES */
1120 # ifdef HAVE_SOLARIS_PRIVS
1121 if (priv_delset(lowprivs, "proc_setid") == -1) {
1122 msyslog(LOG_ERR, "priv_delset() failed:%m");
1125 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1126 msyslog(LOG_ERR, "setppriv() failed:%m");
1129 priv_freeset(lowprivs);
1130 priv_freeset(highprivs);
1131 # endif /* HAVE_SOLARIS_PRIVS */
1132 root_dropped = TRUE;
1133 fork_deferred_worker();
1134 } /* if (droproot) */
1135 # endif /* HAVE_DROPROOT */
1137 /* libssecomp sandboxing */
1138 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1139 scmp_filter_ctx ctx;
1141 if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1142 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1144 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1153 SCMP_SYS(clock_gettime),
1154 SCMP_SYS(clock_settime),
1157 SCMP_SYS(exit_group),
1161 SCMP_SYS(getitimer),
1162 SCMP_SYS(getsockname),
1173 SCMP_SYS(rt_sigaction),
1174 SCMP_SYS(rt_sigprocmask),
1175 SCMP_SYS(rt_sigreturn),
1178 SCMP_SYS(setitimer),
1188 SCMP_SYS(_newselect),
1192 SCMP_SYS(clock_gettime),
1193 SCMP_SYS(clock_settime),
1195 SCMP_SYS(exit_group),
1198 SCMP_SYS(getitimer),
1207 SCMP_SYS(rt_sigaction),
1208 SCMP_SYS(rt_sigprocmask),
1210 SCMP_SYS(setitimer),
1212 SCMP_SYS(sigprocmask),
1213 SCMP_SYS(sigreturn),
1214 SCMP_SYS(socketcall),
1223 for (i = 0; i < COUNTOF(scmp_sc); i++) {
1224 if (seccomp_rule_add(ctx,
1225 SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1227 "%s: seccomp_rule_add() failed: %m",
1233 if (seccomp_load(ctx) < 0)
1234 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1237 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1239 #endif /* LIBSECCOMP and KERN_SECCOMP */
1241 # ifdef HAVE_IO_COMPLETION_PORT
1244 #if !defined(SIM) && defined(SIGDIE1)
1248 GetReceivedBuffers();
1249 # else /* normal I/O */
1251 BLOCK_IO_AND_ALARM();
1252 was_alarmed = FALSE;
1255 #if !defined(SIM) && defined(SIGDIE1)
1259 if (alarm_flag) { /* alarmed? */
1264 /* collect async name/addr results */
1266 harvest_blocking_responses();
1268 if (!was_alarmed && !has_full_recv_buffer()) {
1270 * Nothing to do. Wait for something.
1275 if (alarm_flag) { /* alarmed? */
1281 UNBLOCK_IO_AND_ALARM();
1283 * Out here, signals are unblocked. Call timer routine
1284 * to process expiry.
1287 was_alarmed = FALSE;
1288 BLOCK_IO_AND_ALARM();
1291 # endif /* !HAVE_IO_COMPLETION_PORT */
1293 # ifdef DEBUG_TIMING
1302 rbuf = get_full_recv_buffer();
1303 while (rbuf != NULL) {
1308 UNBLOCK_IO_AND_ALARM();
1311 /* avoid timer starvation during lengthy I/O handling */
1313 was_alarmed = FALSE;
1317 * Call the data procedure to handle each received
1320 if (rbuf->receiver != NULL) {
1321 # ifdef DEBUG_TIMING
1324 L_SUB(&dts, &rbuf->recv_time);
1325 DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1326 collect_timing(rbuf, "buffer processing delay", 1, &dts);
1329 (*rbuf->receiver)(rbuf);
1331 msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1335 BLOCK_IO_AND_ALARM();
1337 rbuf = get_full_recv_buffer();
1339 # ifdef DEBUG_TIMING
1343 collect_timing(NULL, "processing", bufcount, &tsb);
1344 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1353 # ifdef HAVE_DNSREGISTRATION
1354 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1355 mdnsreg = current_time;
1356 msyslog(LOG_INFO, "Attempting to register mDNS");
1357 if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1358 htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1360 msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1362 msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1365 msyslog(LOG_INFO, "mDNS service registered.");
1369 # endif /* HAVE_DNSREGISTRATION */
1372 UNBLOCK_IO_AND_ALARM();
1378 #if !defined(SIM) && defined(SIGDIE1)
1380 * finish - exit gracefully
1387 const char *sig_desc;
1390 #ifdef HAVE_STRSIGNAL
1391 sig_desc = strsignal(sig);
1393 if (sig_desc == NULL)
1395 msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1397 /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1398 # ifdef HAVE_DNSREGISTRATION
1400 DNSServiceRefDeallocate(mdns);
1415 #endif /* !SIM && SIGDIE1 */
1420 * wait_child_sync_if - implements parent side of -w/--wait-sync
1422 # ifdef HAVE_WORKING_FORK
1431 time_t wait_end_time;
1435 struct timeval wtimeout;
1440 /* waitsync_fd_to_close used solely by child */
1441 close(waitsync_fd_to_close);
1442 wait_end_time = time(NULL) + wait_sync;
1444 cur_time = time(NULL);
1445 wait_rem = (wait_end_time > cur_time)
1446 ? (wait_end_time - cur_time)
1448 wtimeout.tv_sec = wait_rem;
1449 wtimeout.tv_usec = 0;
1451 FD_SET(pipe_read_fd, &readset);
1452 rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1457 exit_code = (errno) ? errno : -1;
1459 "--wait-sync select failed: %m");
1464 * select() indicated a timeout, but in case
1465 * its timeouts are affected by a step of the
1466 * system clock, select() again with a zero
1467 * timeout to confirm.
1470 FD_SET(pipe_read_fd, &readset);
1471 wtimeout.tv_sec = 0;
1472 wtimeout.tv_usec = 0;
1473 rc = select(pipe_read_fd + 1, &readset, NULL,
1475 if (0 == rc) /* select() timeout */
1479 } else /* readable */
1481 } while (wait_rem > 0);
1483 fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1484 progname, wait_sync);
1487 # endif /* HAVE_WORKING_FORK */
1491 * assertion_failed - Redirect assertion failures to msyslog().
1497 isc_assertiontype_t type,
1501 isc_assertion_setcallback(NULL); /* Avoid recursion */
1503 msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1504 file, line, isc_assertion_typetotext(type), cond);
1505 msyslog(LOG_ERR, "exiting (due to assertion failure)");
1507 #if defined(DEBUG) && defined(SYS_WINNT)
1517 * library_fatal_error - Handle fatal errors from our libraries.
1520 library_fatal_error(
1529 isc_error_setfatal(NULL); /* Avoid recursion */
1531 msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1532 vsnprintf(errbuf, sizeof(errbuf), format, args);
1533 msyslog(LOG_ERR, "%s", errbuf);
1534 msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1536 #if defined(DEBUG) && defined(SYS_WINNT)
1546 * library_unexpected_error - Handle non fatal errors from our libraries.
1548 # define MAX_UNEXPECTED_ERRORS 100
1549 int unexpected_error_cnt = 0;
1551 library_unexpected_error(
1560 if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1561 return; /* avoid clutter in log */
1563 msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1564 vsnprintf(errbuf, sizeof(errbuf), format, args);
1565 msyslog(LOG_ERR, "%s", errbuf);
1567 if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1568 msyslog(LOG_ERR, "Too many errors. Shutting up.");
1573 #if !defined(SIM) && !defined(SYS_WINNT)
1577 * moredebug - increase debugging verbosity
1584 int saved_errno = errno;
1589 msyslog(LOG_DEBUG, "debug raised to %d", debug);
1591 errno = saved_errno;
1596 * lessdebug - decrease debugging verbosity
1603 int saved_errno = errno;
1608 msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1610 errno = saved_errno;
1613 # else /* !DEBUG follows */
1617 * no_debug - We don't do the debug here.
1624 int saved_errno = errno;
1626 msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1627 errno = saved_errno;
1629 # endif /* !DEBUG */
1630 #endif /* !SIM && !SYS_WINNT */