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>
108 # include "ntservice.h"
116 # include <sys/ci/ciioctl.h>
123 #ifdef HAVE_LINUX_CAPABILITIES
124 # include <sys/capability.h>
125 # include <sys/prctl.h>
126 #endif /* HAVE_LINUX_CAPABILITIES */
127 #if defined(HAVE_PRIV_H) && defined(HAVE_SOLARIS_PRIVS)
129 #endif /* HAVE_PRIV_H */
130 #if defined(HAVE_TRUSTEDBSD_MAC)
131 # include <sys/mac.h>
132 #endif /* HAVE_TRUSTEDBSD_MAC */
133 #endif /* HAVE_DROPROOT */
135 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
136 /* # include <sys/types.h> */
137 # include <sys/resource.h>
138 # include <seccomp.h>
139 #endif /* LIBSECCOMP and KERN_SECCOMP */
141 #ifdef HAVE_DNSREGISTRATION
146 #ifdef HAVE_SETPGRP_0
147 # define ntp_setpgrp(x, y) setpgrp()
149 # define ntp_setpgrp(x, y) setpgrp(x, y)
152 #ifdef HAVE_SOLARIS_PRIVS
153 # define LOWPRIVS "basic,sys_time,net_privaddr,proc_setid,!proc_info,!proc_session,!proc_exec"
154 static priv_set_t *lowprivs = NULL;
155 static priv_set_t *highprivs = NULL;
156 #endif /* HAVE_SOLARIS_PRIVS */
158 * Scheduling priority we run at
160 #define NTPD_PRIO (-12)
162 int priority_done = 2; /* 0 - Set priority */
163 /* 1 - priority is OK where it is */
164 /* 2 - Don't set priority */
165 /* 1 and 2 are pretty much the same */
167 int listen_to_virtual_ips = TRUE;
170 * No-fork flag. If set, we do not become a background daemon.
172 int nofork; /* Fork by default */
174 #ifdef HAVE_DNSREGISTRATION
176 * mDNS registration flag. If set, we attempt to register with the mDNS system, but only
177 * after we have synched the first time. If the attempt fails, then try again once per
178 * minute for up to 5 times. After all, we may be starting before mDNS.
182 #endif /* HAVE_DNSREGISTRATION */
187 char *user; /* User to switch to */
188 char *group; /* group to switch to */
189 const char *chrootdir; /* directory to chroot to */
194 #endif /* HAVE_DROPROOT */
196 #ifdef HAVE_WORKING_FORK
197 int waitsync_fd_to_close = -1; /* -w/--wait-sync */
201 * Version declaration
203 extern const char *Version;
205 char const *progname;
211 * We put this here, since the argument profile is syscall-specific
213 extern int syscall (int, ...);
214 #endif /* DECL_SYSCALL */
217 #if !defined(SIM) && defined(SIGDIE1)
218 static volatile int signalled = 0;
219 static volatile int signo = 0;
221 /* In an ideal world, 'finish_safe()' would declared as noreturn... */
222 static void finish_safe (int);
223 static RETSIGTYPE finish (int);
226 #if !defined(SIM) && defined(HAVE_WORKING_FORK)
227 static int wait_child_sync_if (int, long);
230 #if !defined(SIM) && !defined(SYS_WINNT)
232 static RETSIGTYPE moredebug (int);
233 static RETSIGTYPE lessdebug (int);
234 # else /* !DEBUG follows */
235 static RETSIGTYPE no_debug (int);
237 #endif /* !SIM && !SYS_WINNT */
245 int ntpdmain (int, char **);
246 static void set_process_priority (void);
247 static void assertion_failed (const char *, int,
250 __attribute__ ((__noreturn__));
251 static void library_fatal_error (const char *, int,
252 const char *, va_list)
253 ISC_FORMAT_PRINTF(3, 0);
254 static void library_unexpected_error(const char *, int,
255 const char *, va_list)
256 ISC_FORMAT_PRINTF(3, 0);
260 /* Bug2332 unearthed a problem in the interaction of reduced user
261 * privileges, the limits on memory usage and some versions of the
262 * pthread library on Linux systems. The 'pthread_cancel()' function and
263 * likely some others need to track the stack of the thread involved,
264 * and uses a function that comes from GCC (--> libgcc_s.so) to do
265 * this. Unfortunately the developers of glibc decided to load the
266 * library on demand, which speeds up program start but can cause
267 * trouble here: Due to all the things NTPD does to limit its resource
268 * usage, this deferred load of libgcc_s does not always work once the
269 * restrictions are in effect.
271 * One way out of this was attempting a forced link against libgcc_s
272 * when possible because it makes the library available immediately
273 * without deferred load. (The symbol resolution would still be dynamic
274 * and on demand, but the code would already be in the process image.)
276 * This is a tricky thing to do, since it's not necessary everywhere,
277 * not possible everywhere, has shown to break the build of other
278 * programs in the NTP suite and is now generally frowned upon.
280 * So we take a different approach here: We creat a worker thread that does
281 * actually nothing except waiting for cancellation and cancel it. If
282 * this is done before all the limitations are put in place, the
283 * machinery is pre-heated and all the runtime stuff should be in place
284 * and useable when needed.
286 * This uses only the standard pthread API and should work with all
287 * implementations of pthreads. It is not necessary everywhere, but it's
288 * cheap enough to go on nearly unnoticed.
290 * Addendum: Bug 2954 showed that the assumption that this should work
291 * with all OS is wrong -- at least FreeBSD bombs heavily.
293 #ifdef NEED_PTHREAD_WARMUP
295 /* simple thread function: sleep until cancelled, just to exercise
296 * thread cancellation.
299 my_pthread_warmup_worker(
308 /* pre-heat threading: create a thread and cancel it, just to exercise
309 * thread cancellation.
312 my_pthread_warmup(void)
315 pthread_attr_t thr_attr;
318 pthread_attr_init(&thr_attr);
319 #if defined(HAVE_PTHREAD_ATTR_GETSTACKSIZE) && \
320 defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && \
321 defined(PTHREAD_STACK_MIN)
323 size_t ssmin = 32*1024; /* 32kB should be minimum */
324 if (ssmin < PTHREAD_STACK_MIN)
325 ssmin = PTHREAD_STACK_MIN;
326 rc = pthread_attr_setstacksize(&thr_attr, ssmin);
329 "my_pthread_warmup: pthread_attr_setstacksize() -> %s",
334 &thread, &thr_attr, my_pthread_warmup_worker, NULL);
335 pthread_attr_destroy(&thr_attr);
338 "my_pthread_warmup: pthread_create() -> %s",
341 pthread_cancel(thread);
342 pthread_join(thread, NULL);
346 #endif /*defined(NEED_PTHREAD_WARMUP)*/
348 #ifdef NEED_EARLY_FORK
350 dummy_callback(void) { return; }
353 fork_nonchroot_worker(void) {
354 getaddrinfo_sometime("localhost", "ntp", NULL, INITIAL_DNS_RETRY,
355 (gai_sometime_callback)&dummy_callback, NULL);
357 #endif /* NEED_EARLY_FORK */
369 optct = ntpOptionProcess(&ntpdOptions, *pargc, *pargv);
386 parse_cmdline_opts(&argc, &argv);
388 debug = OPT_VALUE_SET_DEBUG_LEVEL;
389 DPRINTF(1, ("%s\n", Version));
392 return ntpsim(argc, argv);
394 #else /* !SIM follows */
395 #ifdef NO_MAIN_ALLOWED
396 CALL(ntpd,"ntpd",ntpdmain);
397 #else /* !NO_MAIN_ALLOWED follows */
405 return ntpdmain(argc, argv);
407 #endif /* !SYS_WINNT */
408 #endif /* !NO_MAIN_ALLOWED */
413 * OK. AIX is different than solaris in how it implements plock().
414 * If you do NOT adjust the stack limit, you will get the MAXIMUM
415 * stack size allocated and PINNED with you program. To check the
416 * value, use ulimit -a.
418 * To fix this, we create an automatic variable and set our stack limit
419 * to that PLUS 32KB of extra space (we need some headroom).
421 * This subroutine gets the stack address.
423 * Grover Davidson and Matt Ladendorf
434 * Signal handler for SIGDANGER.
437 catch_danger(int signo)
439 msyslog(LOG_INFO, "ntpd: setpgid(): %m");
440 /* Make the system believe we'll free something, but don't do it! */
446 * Set the process priority
450 set_process_priority(void)
455 msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>",
457 ? "Leave priority alone"
458 : "Attempt to set priority"
463 # if defined(HAVE_SCHED_SETSCHEDULER)
464 if (!priority_done) {
465 extern int config_priority_override, config_priority;
467 struct sched_param sched;
469 pmax = sched_get_priority_max(SCHED_FIFO);
470 sched.sched_priority = pmax;
471 if ( config_priority_override ) {
472 pmin = sched_get_priority_min(SCHED_FIFO);
473 if ( config_priority > pmax )
474 sched.sched_priority = pmax;
475 else if ( config_priority < pmin )
476 sched.sched_priority = pmin;
478 sched.sched_priority = config_priority;
480 if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 )
481 msyslog(LOG_ERR, "sched_setscheduler(): %m");
485 # endif /* HAVE_SCHED_SETSCHEDULER */
488 if (!priority_done) {
491 srtp.type = RTP_PRIO_REALTIME; /* was: RTP_PRIO_NORMAL */
492 srtp.prio = 0; /* 0 (hi) -> RTP_PRIO_MAX (31,lo) */
494 if (rtprio(RTP_SET, getpid(), &srtp) < 0)
495 msyslog(LOG_ERR, "rtprio() error: %m");
499 # else /* !RTP_SET follows */
500 if (!priority_done) {
501 if (rtprio(0, 120) < 0)
502 msyslog(LOG_ERR, "rtprio() error: %m");
506 # endif /* !RTP_SET */
507 # endif /* HAVE_RTPRIO */
508 # if defined(NTPD_PRIO) && NTPD_PRIO != 0
509 # ifdef HAVE_ATT_NICE
510 if (!priority_done) {
512 if (-1 == nice (NTPD_PRIO) && errno != 0)
513 msyslog(LOG_ERR, "nice() error: %m");
517 # endif /* HAVE_ATT_NICE */
518 # ifdef HAVE_BSD_NICE
519 if (!priority_done) {
520 if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO))
521 msyslog(LOG_ERR, "setpriority() error: %m");
525 # endif /* HAVE_BSD_NICE */
526 # endif /* NTPD_PRIO && NTPD_PRIO != 0 */
528 msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority");
532 #if !defined(SIM) && !defined(SYS_WINNT)
534 * Detach from terminal (much like daemon())
535 * Nothe that this function calls exit()
537 # ifdef HAVE_WORKING_FORK
539 detach_from_terminal(
542 const char *logfilename
547 # if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
556 exit_code = (errno) ? errno : -1;
557 msyslog(LOG_ERR, "fork: %m");
562 exit_code = wait_child_sync_if(pipe_fds[0],
569 * close all open files excepting waitsync_fd_to_close.
570 * msyslog() unreliable until after init_logging().
573 if (syslog_file != NULL) {
578 close_all_except(waitsync_fd_to_close);
579 INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
582 init_logging(progname, 0, TRUE);
583 /* we lost our logfile (if any) daemonizing */
584 setup_logfile(logfilename);
591 proc2_$who_am_i(&puid);
592 proc2_$make_server(&puid, &st);
594 # endif /* SYS_DOMAINOS */
596 if (setsid() == (pid_t)-1)
597 msyslog(LOG_ERR, "setsid(): %m");
598 # elif defined(HAVE_SETPGID)
599 if (setpgid(0, 0) == -1)
600 msyslog(LOG_ERR, "setpgid(): %m");
601 # else /* !HAVE_SETSID && !HAVE_SETPGID follows */
603 fid = open("/dev/tty", 2);
605 ioctl(fid, (u_long)TIOCNOTTY, NULL);
608 # endif /* TIOCNOTTY */
609 ntp_setpgrp(0, getpid());
610 # endif /* !HAVE_SETSID && !HAVE_SETPGID */
612 /* Don't get killed by low-on-memory signal. */
613 sa.sa_handler = catch_danger;
614 sigemptyset(&sa.sa_mask);
615 sa.sa_flags = SA_RESTART;
616 sigaction(SIGDANGER, &sa, NULL);
621 # endif /* HAVE_WORKING_FORK */
625 * Map user name/number to user ID
633 if (isdigit((unsigned char)*user)) {
634 sw_uid = (uid_t)strtoul(user, &endp, 0);
638 if ((pw = getpwuid(sw_uid)) != NULL) {
640 user = estrdup(pw->pw_name);
644 msyslog(LOG_ERR, "Cannot find user ID %s", user);
651 if ((pw = getpwnam(user)) != NULL) {
656 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
658 msyslog(LOG_ERR, "Cannot find user `%s'", user);
667 * Map group name/number to group ID
674 if (isdigit((unsigned char)*group)) {
675 sw_gid = (gid_t)strtoul(group, &endp, 0);
680 if ((gr = getgrnam(group)) != NULL) {
684 msyslog(LOG_ERR, "Cannot find group `%s'", group);
695 if (user && initgroups(user, sw_gid)) {
696 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
699 if (group && setgid(sw_gid)) {
700 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
703 if (group && setegid(sw_gid)) {
704 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
708 if (0 != setgroups(1, &sw_gid)) {
709 msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
714 if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
715 msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
724 if (user && setuid(sw_uid)) {
725 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
728 if (user && seteuid(sw_uid)) {
729 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
736 * Change (effective) user and group IDs, also initialize the supplementary group access list
738 int set_user_group_ids(void);
740 set_user_group_ids(void)
742 /* If the the user was already mapped, no need to map it again */
743 if ((NULL != user) && (0 == sw_uid)) {
747 /* same applies for the group */
748 if ((NULL != group) && (0 == sw_gid)) {
749 if (0 == map_group())
753 if (getegid() != sw_gid && 0 == set_group_ids())
755 if (geteuid() != sw_uid && 0 == set_user_ids())
760 #endif /* HAVE_DROPROOT */
764 * Main program. Initialize us, disconnect us from the tty if necessary,
765 * and loop waiting for I/O and/or timer expiries.
775 struct recvbuf *rbuf;
776 const char * logfilename;
780 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
783 # if defined(HAVE_WORKING_FORK)
788 # endif /* HAVE_WORKING_FORK*/
794 # ifdef NEED_PTHREAD_WARMUP
808 initializing = TRUE; /* mark that we are initializing */
809 parse_cmdline_opts(&argc, &argv);
811 debug = OPT_VALUE_SET_DEBUG_LEVEL;
812 # ifdef HAVE_SETLINEBUF
817 if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
821 || HAVE_OPT(SAVECONFIGQUIT))
824 init_logging(progname, NLOG_SYNCMASK, TRUE);
825 /* honor -l/--logfile option to log to a file */
826 if (HAVE_OPT(LOGFILE)) {
827 logfilename = OPT_ARG(LOGFILE);
829 change_logfile(logfilename, FALSE);
834 if (HAVE_OPT(SAVECONFIGQUIT))
837 msyslog(LOG_NOTICE, "%s: Starting", Version);
841 char buf[1024]; /* Secret knowledge of msyslog buf length */
844 /* Note that every arg has an initial space character */
845 snprintf(cp, sizeof(buf), "Command line:");
848 for (i = 0; i < saved_argc ; ++i) {
849 snprintf(cp, sizeof(buf) - (cp - buf),
850 " %s", saved_argv[i]);
853 msyslog(LOG_INFO, "%s", buf);
857 * Install trap handlers to log errors and assertion failures.
858 * Default handlers print to stderr which doesn't work if detached.
860 isc_assertion_setcallback(assertion_failed);
861 isc_error_setfatal(library_fatal_error);
862 isc_error_setunexpected(library_unexpected_error);
864 /* MPE lacks the concept of root */
865 # if defined(HAVE_GETUID) && !defined(MPE)
867 if (uid && !HAVE_OPT( SAVECONFIGQUIT )
868 # if defined(HAVE_TRUSTEDBSD_MAC)
869 /* We can run as non-root if the mac_ntpd policy is enabled. */
870 && mac_is_present("ntpd") != 1
875 "must be run as root, not uid %ld", (long)uid);
881 * Enable the Multi-Media Timer for Windows?
884 if (HAVE_OPT( MODIFYMMTIMER ))
885 set_mm_timer(MM_TIMER_HIRES);
888 #ifdef HAVE_DNSREGISTRATION
890 * Enable mDNS registrations?
892 if (HAVE_OPT( MDNS )) {
895 #endif /* HAVE_DNSREGISTRATION */
897 if (HAVE_OPT( NOVIRTUALIPS ))
898 listen_to_virtual_ips = 0;
901 * --interface, listen on specified interfaces
903 if (HAVE_OPT( INTERFACE )) {
904 int ifacect = STACKCT_OPT( INTERFACE );
905 const char** ifaces = STACKLST_OPT( INTERFACE );
908 while (ifacect-- > 0) {
910 is_ip_address(*ifaces, AF_UNSPEC, &addr)
913 *ifaces, -1, ACTION_LISTEN);
918 if (HAVE_OPT( NICE ))
921 # ifdef HAVE_SCHED_SETSCHEDULER
922 if (HAVE_OPT( PRIORITY )) {
923 config_priority = OPT_VALUE_PRIORITY;
924 config_priority_override = 1;
929 # ifdef HAVE_WORKING_FORK
930 /* make sure the FDs are initialised */
933 do { /* 'loop' once */
934 if (!HAVE_OPT( WAIT_SYNC ))
936 wait_sync = OPT_VALUE_WAIT_SYNC;
937 if (wait_sync <= 0) {
941 /* -w requires a fork() even with debug > 0 */
943 if (pipe(pipe_fds)) {
944 exit_code = (errno) ? errno : -1;
946 "Pipe creation failed for --wait-sync: %m");
949 waitsync_fd_to_close = pipe_fds[1];
950 } while (0); /* 'loop' once */
951 # endif /* HAVE_WORKING_FORK */
956 * Make sure the service is initialized before we do anything else
961 * Start interpolation thread, must occur before first
967 * Initialize random generator and public key pair
971 ntp_srandom((int)(now.l_i * now.l_uf));
974 * Detach us from the terminal. May need an #ifndef GIZMO.
978 # ifdef HAVE_WORKING_FORK
979 detach_from_terminal(pipe_fds, wait_sync, logfilename);
980 # endif /* HAVE_WORKING_FORK */
985 * SCO OpenServer's system clock offers much more precise timekeeping
986 * on the base CPU than the other CPUs (for multiprocessor systems),
987 * so we must lock to the base CPU.
989 fd = open("/dev/at1", O_RDONLY);
992 if (ioctl(fd, ACPU_LOCK, &zero) < 0)
993 msyslog(LOG_ERR, "cannot lock to base CPU: %m");
998 /* Setup stack size in preparation for locking pages in memory. */
999 # if defined(HAVE_MLOCKALL)
1000 # ifdef HAVE_SETRLIMIT
1001 ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
1002 # if defined(RLIMIT_MEMLOCK) && defined(DFLT_RLIMIT_MEMLOCK) && DFLT_RLIMIT_MEMLOCK != -1
1004 * The default RLIMIT_MEMLOCK is very low on Linux systems.
1005 * Unless we increase this limit malloc calls are likely to
1006 * fail if we drop root privilege. To be useful the value
1007 * has to be larger than the largest ntpd resident set size.
1009 ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
1010 # endif /* RLIMIT_MEMLOCK */
1011 # endif /* HAVE_SETRLIMIT */
1012 # else /* !HAVE_MLOCKALL follows */
1017 * set the stack limit for AIX for plock().
1018 * see get_aix_stack() for more info.
1020 if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
1022 "Cannot adjust stack limit for plock: %m");
1024 # endif /* PROCLOCK */
1025 # endif /* HAVE_PLOCK */
1026 # endif /* !HAVE_MLOCKALL */
1029 * Set up signals we pay attention to locally.
1032 signal_no_reset(SIGDIE1, finish);
1033 signal_no_reset(SIGDIE2, finish);
1034 signal_no_reset(SIGDIE3, finish);
1035 signal_no_reset(SIGDIE4, finish);
1038 signal_no_reset(SIGBUS, finish);
1041 # if !defined(SYS_WINNT) && !defined(VMS)
1043 (void) signal_no_reset(MOREDEBUGSIG, moredebug);
1044 (void) signal_no_reset(LESSDEBUGSIG, lessdebug);
1046 (void) signal_no_reset(MOREDEBUGSIG, no_debug);
1047 (void) signal_no_reset(LESSDEBUGSIG, no_debug);
1049 # endif /* !SYS_WINNT && !VMS */
1052 * Set up signals we should never pay attention to.
1055 signal_no_reset(SIGPIPE, SIG_IGN);
1059 * Call the init_ routines to initialize the data structures.
1061 * Exactly what command-line options are we expecting here?
1075 set_process_priority();
1076 init_proto(); /* Call at high priority */
1079 mon_start(MON_ON); /* monitor on by default now */
1080 /* turn off in config if unwanted */
1083 * Get the configuration. This is done in a separate module
1084 * since this will definitely be different for the gizmo board.
1086 getconfig(argc, argv);
1088 if (-1 == cur_memlock) {
1089 # if defined(HAVE_MLOCKALL)
1091 * lock the process into memory
1093 if ( !HAVE_OPT(SAVECONFIGQUIT)
1094 # ifdef RLIMIT_MEMLOCK
1095 && -1 != DFLT_RLIMIT_MEMLOCK
1097 && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
1098 msyslog(LOG_ERR, "mlockall(): %m");
1099 # else /* !HAVE_MLOCKALL follows */
1103 * lock the process into memory
1105 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
1106 msyslog(LOG_ERR, "plock(PROCLOCK): %m");
1107 # else /* !PROCLOCK follows */
1110 * Lock text into ram
1112 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
1113 msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
1114 # else /* !TXTLOCK follows */
1115 msyslog(LOG_ERR, "plock() - don't know what to lock!");
1116 # endif /* !TXTLOCK */
1117 # endif /* !PROCLOCK */
1118 # endif /* HAVE_PLOCK */
1119 # endif /* !HAVE_MLOCKALL */
1122 loop_config(LOOP_DRIFTINIT, 0);
1123 report_event(EVNT_SYSRESTART, NULL, NULL);
1124 initializing = FALSE;
1126 # ifdef HAVE_DROPROOT
1129 #ifdef NEED_EARLY_FORK
1130 fork_nonchroot_worker();
1133 /* Drop super-user privileges and chroot now if the OS supports this */
1135 # ifdef HAVE_LINUX_CAPABILITIES
1136 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
1137 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
1138 msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
1141 # elif HAVE_SOLARIS_PRIVS
1142 /* Nothing to do here */
1144 /* we need a user to switch to */
1146 msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
1149 # endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
1152 if (0 == map_user())
1155 if (group != NULL) {
1156 if (0 == map_group())
1161 /* make sure cwd is inside the jail: */
1162 if (chdir(chrootdir)) {
1163 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
1166 if (chroot(chrootdir)) {
1167 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
1171 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
1175 # ifdef HAVE_SOLARIS_PRIVS
1176 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
1177 msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
1180 if ((highprivs = priv_allocset()) == NULL) {
1181 msyslog(LOG_ERR, "priv_allocset() failed:%m");
1184 (void) getppriv(PRIV_PERMITTED, highprivs);
1185 (void) priv_intersect(highprivs, lowprivs);
1186 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1187 msyslog(LOG_ERR, "setppriv() failed:%m");
1190 # endif /* HAVE_SOLARIS_PRIVS */
1191 if (0 == set_user_group_ids())
1194 # if defined(HAVE_TRUSTEDBSD_MAC)
1196 * To manipulate system time and (re-)bind to NTP_PORT as needed
1197 * following interface changes, we must either run as uid 0 or
1198 * the mac_ntpd policy module must be enabled.
1200 if (sw_uid != 0 && mac_is_present("ntpd") != 1) {
1201 msyslog(LOG_ERR, "Need MAC 'ntpd' policy enabled to drop root privileges");
1204 # elif !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1206 * for now assume that the privilege to bind to privileged ports
1207 * is associated with running with uid 0 - should be refined on
1208 * ports that allow binding to NTP_PORT with uid != 0
1210 disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */
1211 # endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1213 if (disable_dynamic_updates && interface_interval) {
1214 interface_interval = 0;
1215 msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1218 # ifdef HAVE_LINUX_CAPABILITIES
1221 * We may be running under non-root uid now, but we still hold full root privileges!
1222 * We drop all of them, except for the crucial one or two: cap_sys_time and
1223 * cap_net_bind_service if doing dynamic interface tracking.
1228 captext = (0 != interface_interval)
1229 ? "cap_sys_time,cap_net_bind_service=pe"
1230 : "cap_sys_time=pe";
1231 caps = cap_from_text(captext);
1234 "cap_from_text(%s) failed: %m",
1238 if (-1 == cap_set_proc(caps)) {
1240 "cap_set_proc() failed to drop root privs: %m");
1245 # endif /* HAVE_LINUX_CAPABILITIES */
1246 # ifdef HAVE_SOLARIS_PRIVS
1247 if (priv_delset(lowprivs, "proc_setid") == -1) {
1248 msyslog(LOG_ERR, "priv_delset() failed:%m");
1251 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1252 msyslog(LOG_ERR, "setppriv() failed:%m");
1255 priv_freeset(lowprivs);
1256 priv_freeset(highprivs);
1257 # endif /* HAVE_SOLARIS_PRIVS */
1258 root_dropped = TRUE;
1259 fork_deferred_worker();
1260 } /* if (droproot) */
1261 # endif /* HAVE_DROPROOT */
1263 /* libssecomp sandboxing */
1264 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1265 scmp_filter_ctx ctx;
1267 if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1268 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1270 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1279 SCMP_SYS(clock_gettime),
1280 SCMP_SYS(clock_settime),
1283 SCMP_SYS(exit_group),
1287 SCMP_SYS(getitimer),
1288 SCMP_SYS(getsockname),
1299 SCMP_SYS(rt_sigaction),
1300 SCMP_SYS(rt_sigprocmask),
1301 SCMP_SYS(rt_sigreturn),
1304 SCMP_SYS(setitimer),
1314 SCMP_SYS(_newselect),
1318 SCMP_SYS(clock_gettime),
1319 SCMP_SYS(clock_settime),
1321 SCMP_SYS(exit_group),
1324 SCMP_SYS(getitimer),
1333 SCMP_SYS(rt_sigaction),
1334 SCMP_SYS(rt_sigprocmask),
1336 SCMP_SYS(setitimer),
1338 SCMP_SYS(sigprocmask),
1339 SCMP_SYS(sigreturn),
1340 SCMP_SYS(socketcall),
1349 for (i = 0; i < COUNTOF(scmp_sc); i++) {
1350 if (seccomp_rule_add(ctx,
1351 SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1353 "%s: seccomp_rule_add() failed: %m",
1359 if (seccomp_load(ctx) < 0)
1360 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1363 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1365 #endif /* LIBSECCOMP and KERN_SECCOMP */
1371 # ifdef HAVE_IO_COMPLETION_PORT
1374 #if !defined(SIM) && defined(SIGDIE1)
1378 GetReceivedBuffers();
1379 # else /* normal I/O */
1381 BLOCK_IO_AND_ALARM();
1382 was_alarmed = FALSE;
1385 #if !defined(SIM) && defined(SIGDIE1)
1389 if (alarm_flag) { /* alarmed? */
1394 /* collect async name/addr results */
1396 harvest_blocking_responses();
1398 if (!was_alarmed && !has_full_recv_buffer()) {
1400 * Nothing to do. Wait for something.
1405 if (alarm_flag) { /* alarmed? */
1411 UNBLOCK_IO_AND_ALARM();
1413 * Out here, signals are unblocked. Call timer routine
1414 * to process expiry.
1417 was_alarmed = FALSE;
1418 BLOCK_IO_AND_ALARM();
1421 # endif /* !HAVE_IO_COMPLETION_PORT */
1423 # ifdef DEBUG_TIMING
1432 rbuf = get_full_recv_buffer();
1433 while (rbuf != NULL) {
1438 UNBLOCK_IO_AND_ALARM();
1441 /* avoid timer starvation during lengthy I/O handling */
1443 was_alarmed = FALSE;
1447 * Call the data procedure to handle each received
1450 if (rbuf->receiver != NULL) {
1451 # ifdef DEBUG_TIMING
1454 L_SUB(&dts, &rbuf->recv_time);
1455 DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1456 collect_timing(rbuf, "buffer processing delay", 1, &dts);
1459 (*rbuf->receiver)(rbuf);
1461 msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1465 BLOCK_IO_AND_ALARM();
1467 rbuf = get_full_recv_buffer();
1469 # ifdef DEBUG_TIMING
1473 collect_timing(NULL, "processing", bufcount, &tsb);
1474 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1483 # ifdef HAVE_DNSREGISTRATION
1484 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1485 mdnsreg = current_time;
1486 msyslog(LOG_INFO, "Attempting to register mDNS");
1487 if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1488 htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1490 msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1492 msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1495 msyslog(LOG_INFO, "mDNS service registered.");
1499 # endif /* HAVE_DNSREGISTRATION */
1502 UNBLOCK_IO_AND_ALARM();
1508 #if !defined(SIM) && defined(SIGDIE1)
1510 * finish - exit gracefully
1517 const char *sig_desc;
1520 #ifdef HAVE_STRSIGNAL
1521 sig_desc = strsignal(sig);
1523 if (sig_desc == NULL)
1525 msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1527 /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1528 # ifdef HAVE_DNSREGISTRATION
1530 DNSServiceRefDeallocate(mdns);
1545 #endif /* !SIM && SIGDIE1 */
1550 * wait_child_sync_if - implements parent side of -w/--wait-sync
1552 # ifdef HAVE_WORKING_FORK
1561 time_t wait_end_time;
1565 struct timeval wtimeout;
1570 /* waitsync_fd_to_close used solely by child */
1571 close(waitsync_fd_to_close);
1572 wait_end_time = time(NULL) + wait_sync;
1574 cur_time = time(NULL);
1575 wait_rem = (wait_end_time > cur_time)
1576 ? (wait_end_time - cur_time)
1578 wtimeout.tv_sec = wait_rem;
1579 wtimeout.tv_usec = 0;
1581 FD_SET(pipe_read_fd, &readset);
1582 rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1587 exit_code = (errno) ? errno : -1;
1589 "--wait-sync select failed: %m");
1594 * select() indicated a timeout, but in case
1595 * its timeouts are affected by a step of the
1596 * system clock, select() again with a zero
1597 * timeout to confirm.
1600 FD_SET(pipe_read_fd, &readset);
1601 wtimeout.tv_sec = 0;
1602 wtimeout.tv_usec = 0;
1603 rc = select(pipe_read_fd + 1, &readset, NULL,
1605 if (0 == rc) /* select() timeout */
1609 } else /* readable */
1611 } while (wait_rem > 0);
1613 fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1614 progname, wait_sync);
1617 # endif /* HAVE_WORKING_FORK */
1621 * assertion_failed - Redirect assertion failures to msyslog().
1627 isc_assertiontype_t type,
1631 isc_assertion_setcallback(NULL); /* Avoid recursion */
1633 msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1634 file, line, isc_assertion_typetotext(type), cond);
1635 msyslog(LOG_ERR, "exiting (due to assertion failure)");
1637 #if defined(DEBUG) && defined(SYS_WINNT)
1647 * library_fatal_error - Handle fatal errors from our libraries.
1650 library_fatal_error(
1659 isc_error_setfatal(NULL); /* Avoid recursion */
1661 msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1662 vsnprintf(errbuf, sizeof(errbuf), format, args);
1663 msyslog(LOG_ERR, "%s", errbuf);
1664 msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1666 #if defined(DEBUG) && defined(SYS_WINNT)
1676 * library_unexpected_error - Handle non fatal errors from our libraries.
1678 # define MAX_UNEXPECTED_ERRORS 100
1679 int unexpected_error_cnt = 0;
1681 library_unexpected_error(
1690 if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1691 return; /* avoid clutter in log */
1693 msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1694 vsnprintf(errbuf, sizeof(errbuf), format, args);
1695 msyslog(LOG_ERR, "%s", errbuf);
1697 if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1698 msyslog(LOG_ERR, "Too many errors. Shutting up.");
1703 #if !defined(SIM) && !defined(SYS_WINNT)
1707 * moredebug - increase debugging verbosity
1714 int saved_errno = errno;
1719 msyslog(LOG_DEBUG, "debug raised to %d", debug);
1721 errno = saved_errno;
1726 * lessdebug - decrease debugging verbosity
1733 int saved_errno = errno;
1738 msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1740 errno = saved_errno;
1743 # else /* !DEBUG follows */
1747 * no_debug - We don't do the debug here.
1754 int saved_errno = errno;
1756 msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1757 errno = saved_errno;
1759 # endif /* !DEBUG */
1760 #endif /* !SIM && !SYS_WINNT */