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()
538 detach_from_terminal(
541 const char *logfilename
546 # if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
555 exit_code = (errno) ? errno : -1;
556 msyslog(LOG_ERR, "fork: %m");
561 exit_code = wait_child_sync_if(pipe_fds[0],
568 * close all open files excepting waitsync_fd_to_close.
569 * msyslog() unreliable until after init_logging().
572 if (syslog_file != NULL) {
577 close_all_except(waitsync_fd_to_close);
578 INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
581 init_logging(progname, 0, TRUE);
582 /* we lost our logfile (if any) daemonizing */
583 setup_logfile(logfilename);
590 proc2_$who_am_i(&puid);
591 proc2_$make_server(&puid, &st);
593 # endif /* SYS_DOMAINOS */
595 if (setsid() == (pid_t)-1)
596 msyslog(LOG_ERR, "setsid(): %m");
597 # elif defined(HAVE_SETPGID)
598 if (setpgid(0, 0) == -1)
599 msyslog(LOG_ERR, "setpgid(): %m");
600 # else /* !HAVE_SETSID && !HAVE_SETPGID follows */
602 fid = open("/dev/tty", 2);
604 ioctl(fid, (u_long)TIOCNOTTY, NULL);
607 # endif /* TIOCNOTTY */
608 ntp_setpgrp(0, getpid());
609 # endif /* !HAVE_SETSID && !HAVE_SETPGID */
611 /* Don't get killed by low-on-memory signal. */
612 sa.sa_handler = catch_danger;
613 sigemptyset(&sa.sa_mask);
614 sa.sa_flags = SA_RESTART;
615 sigaction(SIGDANGER, &sa, NULL);
623 * Map user name/number to user ID
631 if (isdigit((unsigned char)*user)) {
632 sw_uid = (uid_t)strtoul(user, &endp, 0);
636 if ((pw = getpwuid(sw_uid)) != NULL) {
638 user = estrdup(pw->pw_name);
642 msyslog(LOG_ERR, "Cannot find user ID %s", user);
649 if ((pw = getpwnam(user)) != NULL) {
654 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
656 msyslog(LOG_ERR, "Cannot find user `%s'", user);
665 * Map group name/number to group ID
673 if (isdigit((unsigned char)*group)) {
674 sw_gid = (gid_t)strtoul(group, &endp, 0);
679 if ((gr = getgrnam(group)) != NULL) {
683 msyslog(LOG_ERR, "Cannot find group `%s'", group);
692 * Change (effective) user and group IDs, also initialize the supplementary group access list
698 /* If the the user was already mapped, no need to map it again */
699 if ((NULL != user) && (0 == sw_uid)) {
703 /* same applies for the group */
704 if ((NULL != group) && (0 == sw_gid)) {
705 if (0 == map_group())
709 if (user && initgroups(user, sw_gid)) {
710 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
713 if (group && setgid(sw_gid)) {
714 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
717 if (group && setegid(sw_gid)) {
718 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
722 if (0 != setgroups(1, &sw_gid)) {
723 msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
728 if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
729 msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
732 if (user && setuid(sw_uid)) {
733 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
736 if (user && seteuid(sw_uid)) {
737 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
743 #endif /* HAVE_DROPROOT */
747 * Main program. Initialize us, disconnect us from the tty if necessary,
748 * and loop waiting for I/O and/or timer expiries.
758 struct recvbuf *rbuf;
759 const char * logfilename;
763 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
766 # if defined(HAVE_WORKING_FORK)
771 # endif /* HAVE_WORKING_FORK*/
777 # ifdef NEED_PTHREAD_WARMUP
791 initializing = TRUE; /* mark that we are initializing */
792 parse_cmdline_opts(&argc, &argv);
794 debug = OPT_VALUE_SET_DEBUG_LEVEL;
795 # ifdef HAVE_SETLINEBUF
800 if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
804 || HAVE_OPT(SAVECONFIGQUIT))
807 init_logging(progname, NLOG_SYNCMASK, TRUE);
808 /* honor -l/--logfile option to log to a file */
809 if (HAVE_OPT(LOGFILE)) {
810 logfilename = OPT_ARG(LOGFILE);
812 change_logfile(logfilename, FALSE);
817 if (HAVE_OPT(SAVECONFIGQUIT))
820 msyslog(LOG_NOTICE, "%s: Starting", Version);
824 char buf[1024]; /* Secret knowledge of msyslog buf length */
827 /* Note that every arg has an initial space character */
828 snprintf(cp, sizeof(buf), "Command line:");
831 for (i = 0; i < saved_argc ; ++i) {
832 snprintf(cp, sizeof(buf) - (cp - buf),
833 " %s", saved_argv[i]);
836 msyslog(LOG_INFO, "%s", buf);
840 * Install trap handlers to log errors and assertion failures.
841 * Default handlers print to stderr which doesn't work if detached.
843 isc_assertion_setcallback(assertion_failed);
844 isc_error_setfatal(library_fatal_error);
845 isc_error_setunexpected(library_unexpected_error);
847 /* MPE lacks the concept of root */
848 # if defined(HAVE_GETUID) && !defined(MPE)
850 if (uid && !HAVE_OPT( SAVECONFIGQUIT )
851 # if defined(HAVE_TRUSTEDBSD_MAC)
852 /* We can run as non-root if the mac_ntpd policy is enabled. */
853 && mac_is_present("ntpd") != 1
858 "must be run as root, not uid %ld", (long)uid);
864 * Enable the Multi-Media Timer for Windows?
867 if (HAVE_OPT( MODIFYMMTIMER ))
868 set_mm_timer(MM_TIMER_HIRES);
871 #ifdef HAVE_DNSREGISTRATION
873 * Enable mDNS registrations?
875 if (HAVE_OPT( MDNS )) {
878 #endif /* HAVE_DNSREGISTRATION */
880 if (HAVE_OPT( NOVIRTUALIPS ))
881 listen_to_virtual_ips = 0;
884 * --interface, listen on specified interfaces
886 if (HAVE_OPT( INTERFACE )) {
887 int ifacect = STACKCT_OPT( INTERFACE );
888 const char** ifaces = STACKLST_OPT( INTERFACE );
891 while (ifacect-- > 0) {
893 is_ip_address(*ifaces, AF_UNSPEC, &addr)
896 *ifaces, -1, ACTION_LISTEN);
901 if (HAVE_OPT( NICE ))
904 # ifdef HAVE_SCHED_SETSCHEDULER
905 if (HAVE_OPT( PRIORITY )) {
906 config_priority = OPT_VALUE_PRIORITY;
907 config_priority_override = 1;
912 # ifdef HAVE_WORKING_FORK
913 /* make sure the FDs are initialised */
916 do { /* 'loop' once */
917 if (!HAVE_OPT( WAIT_SYNC ))
919 wait_sync = OPT_VALUE_WAIT_SYNC;
920 if (wait_sync <= 0) {
924 /* -w requires a fork() even with debug > 0 */
926 if (pipe(pipe_fds)) {
927 exit_code = (errno) ? errno : -1;
929 "Pipe creation failed for --wait-sync: %m");
932 waitsync_fd_to_close = pipe_fds[1];
933 } while (0); /* 'loop' once */
934 # endif /* HAVE_WORKING_FORK */
939 * Make sure the service is initialized before we do anything else
944 * Start interpolation thread, must occur before first
950 * Initialize random generator and public key pair
954 ntp_srandom((int)(now.l_i * now.l_uf));
957 * Detach us from the terminal. May need an #ifndef GIZMO.
961 # ifdef HAVE_WORKING_FORK
962 detach_from_terminal(pipe_fds, wait_sync, logfilename);
963 # endif /* HAVE_WORKING_FORK */
968 * SCO OpenServer's system clock offers much more precise timekeeping
969 * on the base CPU than the other CPUs (for multiprocessor systems),
970 * so we must lock to the base CPU.
972 fd = open("/dev/at1", O_RDONLY);
975 if (ioctl(fd, ACPU_LOCK, &zero) < 0)
976 msyslog(LOG_ERR, "cannot lock to base CPU: %m");
981 /* Setup stack size in preparation for locking pages in memory. */
982 # if defined(HAVE_MLOCKALL)
983 # ifdef HAVE_SETRLIMIT
984 ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
985 # ifdef RLIMIT_MEMLOCK
987 * The default RLIMIT_MEMLOCK is very low on Linux systems.
988 * Unless we increase this limit malloc calls are likely to
989 * fail if we drop root privilege. To be useful the value
990 * has to be larger than the largest ntpd resident set size.
992 ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
993 # endif /* RLIMIT_MEMLOCK */
994 # endif /* HAVE_SETRLIMIT */
995 # else /* !HAVE_MLOCKALL follows */
1000 * set the stack limit for AIX for plock().
1001 * see get_aix_stack() for more info.
1003 if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
1005 "Cannot adjust stack limit for plock: %m");
1007 # endif /* PROCLOCK */
1008 # endif /* HAVE_PLOCK */
1009 # endif /* !HAVE_MLOCKALL */
1012 * Set up signals we pay attention to locally.
1015 signal_no_reset(SIGDIE1, finish);
1016 signal_no_reset(SIGDIE2, finish);
1017 signal_no_reset(SIGDIE3, finish);
1018 signal_no_reset(SIGDIE4, finish);
1021 signal_no_reset(SIGBUS, finish);
1024 # if !defined(SYS_WINNT) && !defined(VMS)
1026 (void) signal_no_reset(MOREDEBUGSIG, moredebug);
1027 (void) signal_no_reset(LESSDEBUGSIG, lessdebug);
1029 (void) signal_no_reset(MOREDEBUGSIG, no_debug);
1030 (void) signal_no_reset(LESSDEBUGSIG, no_debug);
1032 # endif /* !SYS_WINNT && !VMS */
1035 * Set up signals we should never pay attention to.
1038 signal_no_reset(SIGPIPE, SIG_IGN);
1042 * Call the init_ routines to initialize the data structures.
1044 * Exactly what command-line options are we expecting here?
1058 set_process_priority();
1059 init_proto(); /* Call at high priority */
1062 mon_start(MON_ON); /* monitor on by default now */
1063 /* turn off in config if unwanted */
1066 * Get the configuration. This is done in a separate module
1067 * since this will definitely be different for the gizmo board.
1069 getconfig(argc, argv);
1071 if (-1 == cur_memlock) {
1072 # if defined(HAVE_MLOCKALL)
1074 * lock the process into memory
1076 if ( !HAVE_OPT(SAVECONFIGQUIT)
1077 # ifdef RLIMIT_MEMLOCK
1078 && -1 != DFLT_RLIMIT_MEMLOCK
1080 && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
1081 msyslog(LOG_ERR, "mlockall(): %m");
1082 # else /* !HAVE_MLOCKALL follows */
1086 * lock the process into memory
1088 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
1089 msyslog(LOG_ERR, "plock(PROCLOCK): %m");
1090 # else /* !PROCLOCK follows */
1093 * Lock text into ram
1095 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
1096 msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
1097 # else /* !TXTLOCK follows */
1098 msyslog(LOG_ERR, "plock() - don't know what to lock!");
1099 # endif /* !TXTLOCK */
1100 # endif /* !PROCLOCK */
1101 # endif /* HAVE_PLOCK */
1102 # endif /* !HAVE_MLOCKALL */
1105 loop_config(LOOP_DRIFTINIT, 0);
1106 report_event(EVNT_SYSRESTART, NULL, NULL);
1107 initializing = FALSE;
1109 # ifdef HAVE_DROPROOT
1112 #ifdef NEED_EARLY_FORK
1113 fork_nonchroot_worker();
1116 /* Drop super-user privileges and chroot now if the OS supports this */
1118 # ifdef HAVE_LINUX_CAPABILITIES
1119 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
1120 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
1121 msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
1124 # elif HAVE_SOLARIS_PRIVS
1125 /* Nothing to do here */
1127 /* we need a user to switch to */
1129 msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
1132 # endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
1135 if (0 == map_user())
1138 if (group != NULL) {
1139 if (0 == map_group())
1144 /* make sure cwd is inside the jail: */
1145 if (chdir(chrootdir)) {
1146 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
1149 if (chroot(chrootdir)) {
1150 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
1154 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
1158 # ifdef HAVE_SOLARIS_PRIVS
1159 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
1160 msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
1163 if ((highprivs = priv_allocset()) == NULL) {
1164 msyslog(LOG_ERR, "priv_allocset() failed:%m");
1167 (void) getppriv(PRIV_PERMITTED, highprivs);
1168 (void) priv_intersect(highprivs, lowprivs);
1169 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1170 msyslog(LOG_ERR, "setppriv() failed:%m");
1173 # endif /* HAVE_SOLARIS_PRIVS */
1174 if (0 == set_user_group_ids())
1177 # if defined(HAVE_TRUSTEDBSD_MAC)
1179 * To manipulate system time and (re-)bind to NTP_PORT as needed
1180 * following interface changes, we must either run as uid 0 or
1181 * the mac_ntpd policy module must be enabled.
1183 if (sw_uid != 0 && mac_is_present("ntpd") != 1) {
1184 msyslog(LOG_ERR, "Need MAC 'ntpd' policy enabled to drop root privileges");
1187 # elif !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1189 * for now assume that the privilege to bind to privileged ports
1190 * is associated with running with uid 0 - should be refined on
1191 * ports that allow binding to NTP_PORT with uid != 0
1193 disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */
1194 # endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1196 if (disable_dynamic_updates && interface_interval) {
1197 interface_interval = 0;
1198 msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1201 # ifdef HAVE_LINUX_CAPABILITIES
1204 * We may be running under non-root uid now, but we still hold full root privileges!
1205 * We drop all of them, except for the crucial one or two: cap_sys_time and
1206 * cap_net_bind_service if doing dynamic interface tracking.
1211 captext = (0 != interface_interval)
1212 ? "cap_sys_time,cap_net_bind_service=pe"
1213 : "cap_sys_time=pe";
1214 caps = cap_from_text(captext);
1217 "cap_from_text(%s) failed: %m",
1221 if (-1 == cap_set_proc(caps)) {
1223 "cap_set_proc() failed to drop root privs: %m");
1228 # endif /* HAVE_LINUX_CAPABILITIES */
1229 # ifdef HAVE_SOLARIS_PRIVS
1230 if (priv_delset(lowprivs, "proc_setid") == -1) {
1231 msyslog(LOG_ERR, "priv_delset() failed:%m");
1234 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1235 msyslog(LOG_ERR, "setppriv() failed:%m");
1238 priv_freeset(lowprivs);
1239 priv_freeset(highprivs);
1240 # endif /* HAVE_SOLARIS_PRIVS */
1241 root_dropped = TRUE;
1242 fork_deferred_worker();
1243 } /* if (droproot) */
1244 # endif /* HAVE_DROPROOT */
1246 /* libssecomp sandboxing */
1247 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1248 scmp_filter_ctx ctx;
1250 if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1251 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1253 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1262 SCMP_SYS(clock_gettime),
1263 SCMP_SYS(clock_settime),
1266 SCMP_SYS(exit_group),
1270 SCMP_SYS(getitimer),
1271 SCMP_SYS(getsockname),
1282 SCMP_SYS(rt_sigaction),
1283 SCMP_SYS(rt_sigprocmask),
1284 SCMP_SYS(rt_sigreturn),
1287 SCMP_SYS(setitimer),
1297 SCMP_SYS(_newselect),
1301 SCMP_SYS(clock_gettime),
1302 SCMP_SYS(clock_settime),
1304 SCMP_SYS(exit_group),
1307 SCMP_SYS(getitimer),
1316 SCMP_SYS(rt_sigaction),
1317 SCMP_SYS(rt_sigprocmask),
1319 SCMP_SYS(setitimer),
1321 SCMP_SYS(sigprocmask),
1322 SCMP_SYS(sigreturn),
1323 SCMP_SYS(socketcall),
1332 for (i = 0; i < COUNTOF(scmp_sc); i++) {
1333 if (seccomp_rule_add(ctx,
1334 SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1336 "%s: seccomp_rule_add() failed: %m",
1342 if (seccomp_load(ctx) < 0)
1343 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1346 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1348 #endif /* LIBSECCOMP and KERN_SECCOMP */
1354 # ifdef HAVE_IO_COMPLETION_PORT
1357 #if !defined(SIM) && defined(SIGDIE1)
1361 GetReceivedBuffers();
1362 # else /* normal I/O */
1364 BLOCK_IO_AND_ALARM();
1365 was_alarmed = FALSE;
1368 #if !defined(SIM) && defined(SIGDIE1)
1372 if (alarm_flag) { /* alarmed? */
1377 /* collect async name/addr results */
1379 harvest_blocking_responses();
1381 if (!was_alarmed && !has_full_recv_buffer()) {
1383 * Nothing to do. Wait for something.
1388 if (alarm_flag) { /* alarmed? */
1394 UNBLOCK_IO_AND_ALARM();
1396 * Out here, signals are unblocked. Call timer routine
1397 * to process expiry.
1400 was_alarmed = FALSE;
1401 BLOCK_IO_AND_ALARM();
1404 # endif /* !HAVE_IO_COMPLETION_PORT */
1406 # ifdef DEBUG_TIMING
1415 rbuf = get_full_recv_buffer();
1416 while (rbuf != NULL) {
1421 UNBLOCK_IO_AND_ALARM();
1424 /* avoid timer starvation during lengthy I/O handling */
1426 was_alarmed = FALSE;
1430 * Call the data procedure to handle each received
1433 if (rbuf->receiver != NULL) {
1434 # ifdef DEBUG_TIMING
1437 L_SUB(&dts, &rbuf->recv_time);
1438 DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1439 collect_timing(rbuf, "buffer processing delay", 1, &dts);
1442 (*rbuf->receiver)(rbuf);
1444 msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1448 BLOCK_IO_AND_ALARM();
1450 rbuf = get_full_recv_buffer();
1452 # ifdef DEBUG_TIMING
1456 collect_timing(NULL, "processing", bufcount, &tsb);
1457 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1466 # ifdef HAVE_DNSREGISTRATION
1467 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1468 mdnsreg = current_time;
1469 msyslog(LOG_INFO, "Attempting to register mDNS");
1470 if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1471 htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1473 msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1475 msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1478 msyslog(LOG_INFO, "mDNS service registered.");
1482 # endif /* HAVE_DNSREGISTRATION */
1485 UNBLOCK_IO_AND_ALARM();
1491 #if !defined(SIM) && defined(SIGDIE1)
1493 * finish - exit gracefully
1500 const char *sig_desc;
1503 #ifdef HAVE_STRSIGNAL
1504 sig_desc = strsignal(sig);
1506 if (sig_desc == NULL)
1508 msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1510 /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1511 # ifdef HAVE_DNSREGISTRATION
1513 DNSServiceRefDeallocate(mdns);
1528 #endif /* !SIM && SIGDIE1 */
1533 * wait_child_sync_if - implements parent side of -w/--wait-sync
1535 # ifdef HAVE_WORKING_FORK
1544 time_t wait_end_time;
1548 struct timeval wtimeout;
1553 /* waitsync_fd_to_close used solely by child */
1554 close(waitsync_fd_to_close);
1555 wait_end_time = time(NULL) + wait_sync;
1557 cur_time = time(NULL);
1558 wait_rem = (wait_end_time > cur_time)
1559 ? (wait_end_time - cur_time)
1561 wtimeout.tv_sec = wait_rem;
1562 wtimeout.tv_usec = 0;
1564 FD_SET(pipe_read_fd, &readset);
1565 rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1570 exit_code = (errno) ? errno : -1;
1572 "--wait-sync select failed: %m");
1577 * select() indicated a timeout, but in case
1578 * its timeouts are affected by a step of the
1579 * system clock, select() again with a zero
1580 * timeout to confirm.
1583 FD_SET(pipe_read_fd, &readset);
1584 wtimeout.tv_sec = 0;
1585 wtimeout.tv_usec = 0;
1586 rc = select(pipe_read_fd + 1, &readset, NULL,
1588 if (0 == rc) /* select() timeout */
1592 } else /* readable */
1594 } while (wait_rem > 0);
1596 fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1597 progname, wait_sync);
1600 # endif /* HAVE_WORKING_FORK */
1604 * assertion_failed - Redirect assertion failures to msyslog().
1610 isc_assertiontype_t type,
1614 isc_assertion_setcallback(NULL); /* Avoid recursion */
1616 msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1617 file, line, isc_assertion_typetotext(type), cond);
1618 msyslog(LOG_ERR, "exiting (due to assertion failure)");
1620 #if defined(DEBUG) && defined(SYS_WINNT)
1630 * library_fatal_error - Handle fatal errors from our libraries.
1633 library_fatal_error(
1642 isc_error_setfatal(NULL); /* Avoid recursion */
1644 msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1645 vsnprintf(errbuf, sizeof(errbuf), format, args);
1646 msyslog(LOG_ERR, "%s", errbuf);
1647 msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1649 #if defined(DEBUG) && defined(SYS_WINNT)
1659 * library_unexpected_error - Handle non fatal errors from our libraries.
1661 # define MAX_UNEXPECTED_ERRORS 100
1662 int unexpected_error_cnt = 0;
1664 library_unexpected_error(
1673 if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1674 return; /* avoid clutter in log */
1676 msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1677 vsnprintf(errbuf, sizeof(errbuf), format, args);
1678 msyslog(LOG_ERR, "%s", errbuf);
1680 if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1681 msyslog(LOG_ERR, "Too many errors. Shutting up.");
1686 #if !defined(SIM) && !defined(SYS_WINNT)
1690 * moredebug - increase debugging verbosity
1697 int saved_errno = errno;
1702 msyslog(LOG_DEBUG, "debug raised to %d", debug);
1704 errno = saved_errno;
1709 * lessdebug - decrease debugging verbosity
1716 int saved_errno = errno;
1721 msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1723 errno = saved_errno;
1726 # else /* !DEBUG follows */
1730 * no_debug - We don't do the debug here.
1737 int saved_errno = errno;
1739 msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1740 errno = saved_errno;
1742 # endif /* !DEBUG */
1743 #endif /* !SIM && !SYS_WINNT */