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>
48 #ifdef HAVE_SYS_WAIT_H
49 # include <sys/wait.h>
52 #ifdef HAVE_SYS_PARAM_H
53 # include <sys/param.h>
55 #ifdef HAVE_SYS_SIGNAL_H
56 # include <sys/signal.h>
60 #ifdef HAVE_SYS_IOCTL_H
61 # include <sys/ioctl.h>
62 #endif /* HAVE_SYS_IOCTL_H */
63 #if defined(HAVE_RTPRIO)
64 # ifdef HAVE_SYS_LOCK_H
65 # include <sys/lock.h>
67 # include <sys/rtprio.h>
70 # ifdef HAVE_SYS_LOCK_H
71 # include <sys/lock.h>
75 #if defined(HAVE_SCHED_SETSCHEDULER)
79 # ifdef HAVE_SYS_SCHED_H
80 # include <sys/sched.h>
84 #if defined(HAVE_SYS_MMAN_H)
85 # include <sys/mman.h>
88 #ifdef HAVE_SYSEXITS_H
89 # include <sysexits.h>
97 # include <apollo/base.h>
98 #endif /* SYS_DOMAINOS */
101 #include "recvbuff.h"
102 #include "ntp_cmdargs.h"
104 #if 0 /* HMS: I don't think we need this. 961223 */
107 # include <sys/mman.h>
109 # include <sys/lock.h>
115 # include "ntservice.h"
123 # include <sys/ci/ciioctl.h>
130 #ifdef HAVE_LINUX_CAPABILITIES
131 # include <sys/capability.h>
132 # include <sys/prctl.h>
133 #endif /* HAVE_LINUX_CAPABILITIES */
134 #if defined(HAVE_PRIV_H) && defined(HAVE_SOLARIS_PRIVS)
136 #endif /* HAVE_PRIV_H */
137 #if defined(HAVE_TRUSTEDBSD_MAC)
138 # include <sys/mac.h>
139 #endif /* HAVE_TRUSTEDBSD_MAC */
140 #endif /* HAVE_DROPROOT */
142 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
143 /* # include <sys/types.h> */
144 # include <sys/resource.h>
145 # include <seccomp.h>
146 #endif /* LIBSECCOMP and KERN_SECCOMP */
149 #include <sys/procctl.h>
150 #ifndef PROC_STACKGAP_CTL
152 * Even if we compile on an older system we can still run on a newer one.
154 #define PROC_STACKGAP_CTL 17
155 #define PROC_STACKGAP_DISABLE 0x0002
159 #ifdef HAVE_DNSREGISTRATION
164 /* In case 'sysexits.h' is unavailable, define some exit codes here: */
166 # define EX_SOFTWARE 70
175 #define EX_PROTOCOL 76
179 #ifdef HAVE_SETPGRP_0
180 # define ntp_setpgrp(x, y) setpgrp()
182 # define ntp_setpgrp(x, y) setpgrp(x, y)
185 #ifdef HAVE_SOLARIS_PRIVS
186 # define LOWPRIVS "basic,sys_time,net_privaddr,proc_setid,!proc_info,!proc_session,!proc_exec"
187 static priv_set_t *lowprivs = NULL;
188 static priv_set_t *highprivs = NULL;
189 #endif /* HAVE_SOLARIS_PRIVS */
191 * Scheduling priority we run at
193 #define NTPD_PRIO (-12)
195 int priority_done = 2; /* 0 - Set priority */
196 /* 1 - priority is OK where it is */
197 /* 2 - Don't set priority */
198 /* 1 and 2 are pretty much the same */
200 int listen_to_virtual_ips = TRUE;
203 * No-fork flag. If set, we do not become a background daemon.
205 int nofork; /* Fork by default */
207 #ifdef HAVE_DNSREGISTRATION
209 * mDNS registration flag. If set, we attempt to register with the mDNS system, but only
210 * after we have synched the first time. If the attempt fails, then try again once per
211 * minute for up to 5 times. After all, we may be starting before mDNS.
215 #endif /* HAVE_DNSREGISTRATION */
217 #ifdef HAVE_LINUX_CAPABILITIES
218 int have_caps; /* runtime check whether capabilities work */
219 #endif /* HAVE_LINUX_CAPABILITIES */
224 char *user; /* User to switch to */
225 char *group; /* group to switch to */
226 const char *chrootdir; /* directory to chroot to */
231 #endif /* HAVE_DROPROOT */
233 #ifdef HAVE_WORKING_FORK
234 int daemon_pipe[2] = { -1, -1 };
238 * Version declaration
240 extern const char *Version;
242 char const *progname;
248 * We put this here, since the argument profile is syscall-specific
250 extern int syscall (int, ...);
251 #endif /* DECL_SYSCALL */
254 #if !defined(SIM) && defined(SIGDIE1)
255 static volatile int signalled = 0;
256 static volatile int signo = 0;
258 /* In an ideal world, 'finish_safe()' would declared as noreturn... */
259 static void finish_safe (int);
260 static RETSIGTYPE finish (int);
263 #if !defined(SIM) && defined(HAVE_WORKING_FORK)
264 static int wait_child_sync_if (int, unsigned long);
265 static int wait_child_exit_if (pid_t, int);
268 #if !defined(SIM) && !defined(SYS_WINNT)
270 static RETSIGTYPE moredebug (int);
271 static RETSIGTYPE lessdebug (int);
272 # else /* !DEBUG follows */
273 static RETSIGTYPE no_debug (int);
275 #endif /* !SIM && !SYS_WINNT */
283 int ntpdmain (int, char **);
284 static void set_process_priority (void);
285 static void assertion_failed (const char *, int,
288 __attribute__ ((__noreturn__));
289 static void library_fatal_error (const char *, int,
290 const char *, va_list)
291 ISC_FORMAT_PRINTF(3, 0);
292 static void library_unexpected_error(const char *, int,
293 const char *, va_list)
294 ISC_FORMAT_PRINTF(3, 0);
298 /* Bug2332 unearthed a problem in the interaction of reduced user
299 * privileges, the limits on memory usage and some versions of the
300 * pthread library on Linux systems. The 'pthread_cancel()' function and
301 * likely some others need to track the stack of the thread involved,
302 * and uses a function that comes from GCC (--> libgcc_s.so) to do
303 * this. Unfortunately the developers of glibc decided to load the
304 * library on demand, which speeds up program start but can cause
305 * trouble here: Due to all the things NTPD does to limit its resource
306 * usage, this deferred load of libgcc_s does not always work once the
307 * restrictions are in effect.
309 * One way out of this was attempting a forced link against libgcc_s
310 * when possible because it makes the library available immediately
311 * without deferred load. (The symbol resolution would still be dynamic
312 * and on demand, but the code would already be in the process image.)
314 * This is a tricky thing to do, since it's not necessary everywhere,
315 * not possible everywhere, has shown to break the build of other
316 * programs in the NTP suite and is now generally frowned upon.
318 * So we take a different approach here: We creat a worker thread that does
319 * actually nothing except waiting for cancellation and cancel it. If
320 * this is done before all the limitations are put in place, the
321 * machinery is pre-heated and all the runtime stuff should be in place
322 * and useable when needed.
324 * This uses only the standard pthread API and should work with all
325 * implementations of pthreads. It is not necessary everywhere, but it's
326 * cheap enough to go on nearly unnoticed.
328 * Addendum: Bug 2954 showed that the assumption that this should work
329 * with all OS is wrong -- at least FreeBSD bombs heavily.
331 #ifdef NEED_PTHREAD_WARMUP
333 /* simple thread function: sleep until cancelled, just to exercise
334 * thread cancellation.
337 my_pthread_warmup_worker(
346 /* pre-heat threading: create a thread and cancel it, just to exercise
347 * thread cancellation.
350 my_pthread_warmup(void)
353 pthread_attr_t thr_attr;
356 pthread_attr_init(&thr_attr);
357 #if defined(HAVE_PTHREAD_ATTR_GETSTACKSIZE) && \
358 defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && \
359 defined(PTHREAD_STACK_MIN)
361 size_t ssmin = 32*1024; /* 32kB should be minimum */
362 if (ssmin < PTHREAD_STACK_MIN)
363 ssmin = PTHREAD_STACK_MIN;
364 rc = pthread_attr_setstacksize(&thr_attr, ssmin);
367 "my_pthread_warmup: pthread_attr_setstacksize() -> %s",
372 &thread, &thr_attr, my_pthread_warmup_worker, NULL);
373 pthread_attr_destroy(&thr_attr);
376 "my_pthread_warmup: pthread_create() -> %s",
379 pthread_cancel(thread);
380 pthread_join(thread, NULL);
384 #endif /*defined(NEED_PTHREAD_WARMUP)*/
386 #ifdef NEED_EARLY_FORK
388 dummy_callback(void) { return; }
391 fork_nonchroot_worker(void) {
392 getaddrinfo_sometime("localhost", "ntp", NULL, INITIAL_DNS_RETRY,
393 (gai_sometime_callback)&dummy_callback, NULL);
395 #endif /* NEED_EARLY_FORK */
407 optct = ntpOptionProcess(&ntpdOptions, *pargc, *pargv);
424 parse_cmdline_opts(&argc, &argv);
426 debug = OPT_VALUE_SET_DEBUG_LEVEL;
427 DPRINTF(1, ("%s\n", Version));
430 return ntpsim(argc, argv);
432 #elif defined(NO_MAIN_ALLOWED)
433 CALL(ntpd,"ntpd",ntpdmain);
434 #elif !defined(SYS_WINNT)
444 * We Must disable ASLR stack gap on FreeBSD to avoid a
445 * segfault. See PR/241421 and PR/241960.
447 int aslr_var = PROC_STACKGAP_DISABLE;
449 pid_t my_pid = getpid();
450 procctl(P_PID, my_pid, PROC_STACKGAP_CTL, &aslr_var);
453 return ntpdmain(argc, argv);
455 #endif /* !SYS_WINNT */
459 * OK. AIX is different than solaris in how it implements plock().
460 * If you do NOT adjust the stack limit, you will get the MAXIMUM
461 * stack size allocated and PINNED with you program. To check the
462 * value, use ulimit -a.
464 * To fix this, we create an automatic variable and set our stack limit
465 * to that PLUS 32KB of extra space (we need some headroom).
467 * This subroutine gets the stack address.
469 * Grover Davidson and Matt Ladendorf
480 * Signal handler for SIGDANGER.
483 catch_danger(int signo)
485 msyslog(LOG_INFO, "ntpd: setpgid(): %m");
486 /* Make the system believe we'll free something, but don't do it! */
492 * Set the process priority
496 set_process_priority(void)
501 msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>",
503 ? "Leave priority alone"
504 : "Attempt to set priority"
509 # if defined(HAVE_SCHED_SETSCHEDULER)
510 if (!priority_done) {
511 extern int config_priority_override, config_priority;
513 struct sched_param sched;
515 pmax = sched_get_priority_max(SCHED_FIFO);
516 sched.sched_priority = pmax;
517 if ( config_priority_override ) {
518 pmin = sched_get_priority_min(SCHED_FIFO);
519 if ( config_priority > pmax )
520 sched.sched_priority = pmax;
521 else if ( config_priority < pmin )
522 sched.sched_priority = pmin;
524 sched.sched_priority = config_priority;
526 if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 )
527 msyslog(LOG_ERR, "sched_setscheduler(): %m");
531 # endif /* HAVE_SCHED_SETSCHEDULER */
534 if (!priority_done) {
537 srtp.type = RTP_PRIO_REALTIME; /* was: RTP_PRIO_NORMAL */
538 srtp.prio = 0; /* 0 (hi) -> RTP_PRIO_MAX (31,lo) */
540 if (rtprio(RTP_SET, getpid(), &srtp) < 0)
541 msyslog(LOG_ERR, "rtprio() error: %m");
545 # else /* !RTP_SET follows */
546 if (!priority_done) {
547 if (rtprio(0, 120) < 0)
548 msyslog(LOG_ERR, "rtprio() error: %m");
552 # endif /* !RTP_SET */
553 # endif /* HAVE_RTPRIO */
554 # if defined(NTPD_PRIO) && NTPD_PRIO != 0
555 # ifdef HAVE_ATT_NICE
556 if (!priority_done) {
558 if (-1 == nice (NTPD_PRIO) && errno != 0)
559 msyslog(LOG_ERR, "nice() error: %m");
563 # endif /* HAVE_ATT_NICE */
564 # ifdef HAVE_BSD_NICE
565 if (!priority_done) {
566 if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO))
567 msyslog(LOG_ERR, "setpriority() error: %m");
571 # endif /* HAVE_BSD_NICE */
572 # endif /* NTPD_PRIO && NTPD_PRIO != 0 */
574 msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority");
578 #if !defined(SIM) && !defined(SYS_WINNT)
580 * Detach from terminal (much like daemon())
581 * Nothe that this function calls exit()
583 # ifdef HAVE_WORKING_FORK
585 detach_from_terminal(
588 const char *logfilename
593 # if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
604 msyslog(LOG_ERR, "fork: %m");
605 exit_code = EX_OSERR;
609 exit_code = wait_child_sync_if(
611 DPRINTF(1, ("sync_if: rc=%d\n", exit_code));
612 if (exit_code <= 0) {
613 /* probe daemon exit code -- wait for
614 * child process if we have an unexpected
615 * EOF on the monitor pipe.
617 exit_code = wait_child_exit_if(
618 cpid, (exit_code < 0));
619 DPRINTF(1, ("exit_if: rc=%d\n", exit_code));
627 * close all open files excepting waitsync_fd_to_close.
628 * msyslog() unreliable until after init_logging().
631 if (syslog_file != NULL) {
636 close_all_except(pipe[1]);
638 INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
641 init_logging(progname, 0, TRUE);
642 /* we lost our logfile (if any) daemonizing */
643 setup_logfile(logfilename);
650 proc2_$who_am_i(&puid);
651 proc2_$make_server(&puid, &st);
653 # endif /* SYS_DOMAINOS */
655 if (setsid() == (pid_t)-1)
656 msyslog(LOG_ERR, "setsid(): %m");
657 # elif defined(HAVE_SETPGID)
658 if (setpgid(0, 0) == -1)
659 msyslog(LOG_ERR, "setpgid(): %m");
660 # else /* !HAVE_SETSID && !HAVE_SETPGID follows */
662 fid = open("/dev/tty", 2);
664 ioctl(fid, (u_long)TIOCNOTTY, NULL);
667 # endif /* TIOCNOTTY */
668 ntp_setpgrp(0, getpid());
669 # endif /* !HAVE_SETSID && !HAVE_SETPGID */
671 /* Don't get killed by low-on-memory signal. */
672 sa.sa_handler = catch_danger;
673 sigemptyset(&sa.sa_mask);
674 sa.sa_flags = SA_RESTART;
675 sigaction(SIGDANGER, &sa, NULL);
680 # endif /* HAVE_WORKING_FORK */
684 * Map user name/number to user ID
692 if (isdigit((unsigned char)*user)) {
693 sw_uid = (uid_t)strtoul(user, &endp, 0);
697 if ((pw = getpwuid(sw_uid)) != NULL) {
699 user = estrdup(pw->pw_name);
703 msyslog(LOG_ERR, "Cannot find user ID %s", user);
710 if ((pw = getpwnam(user)) != NULL) {
715 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
717 msyslog(LOG_ERR, "Cannot find user `%s'", user);
726 * Map group name/number to group ID
733 if (isdigit((unsigned char)*group)) {
734 sw_gid = (gid_t)strtoul(group, &endp, 0);
739 if ((gr = getgrnam(group)) != NULL) {
743 msyslog(LOG_ERR, "Cannot find group `%s'", group);
754 if (user && initgroups(user, sw_gid)) {
755 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
758 if (group && setgid(sw_gid)) {
759 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
762 if (group && setegid(sw_gid)) {
763 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
767 if (0 != setgroups(1, &sw_gid)) {
768 msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
773 if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
774 msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
783 if (user && setuid(sw_uid)) {
784 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
787 if (user && seteuid(sw_uid)) {
788 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
795 * Change (effective) user and group IDs, also initialize the supplementary group access list
797 int set_user_group_ids(void);
799 set_user_group_ids(void)
801 /* If the the user was already mapped, no need to map it again */
802 if ((NULL != user) && (0 == sw_uid)) {
806 /* same applies for the group */
807 if ((NULL != group) && (0 == sw_gid)) {
808 if (0 == map_group())
812 if (getegid() != sw_gid && 0 == set_group_ids())
814 if (geteuid() != sw_uid && 0 == set_user_ids())
819 #endif /* HAVE_DROPROOT */
823 * Main program. Initialize us, disconnect us from the tty if necessary,
824 * and loop waiting for I/O and/or timer expiries.
834 struct recvbuf *rbuf;
835 const char * logfilename;
839 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
842 # if defined(HAVE_WORKING_FORK)
844 # endif /* HAVE_WORKING_FORK*/
850 # ifdef NEED_PTHREAD_WARMUP
864 initializing = TRUE; /* mark that we are initializing */
865 parse_cmdline_opts(&argc, &argv);
867 debug = OPT_VALUE_SET_DEBUG_LEVEL;
868 # ifdef HAVE_SETLINEBUF
873 if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
877 || HAVE_OPT(SAVECONFIGQUIT))
880 init_logging(progname, NLOG_SYNCMASK, TRUE);
881 /* honor -l/--logfile option to log to a file */
882 if (HAVE_OPT(LOGFILE)) {
883 logfilename = OPT_ARG(LOGFILE);
885 change_logfile(logfilename, FALSE);
890 if (HAVE_OPT(SAVECONFIGQUIT))
893 msyslog(LOG_NOTICE, "%s: Starting", Version);
897 char buf[1024]; /* Secret knowledge of msyslog buf length */
900 /* Note that every arg has an initial space character */
901 snprintf(cp, sizeof(buf), "Command line:");
904 for (i = 0; i < saved_argc ; ++i) {
905 snprintf(cp, sizeof(buf) - (cp - buf),
906 " %s", saved_argv[i]);
909 msyslog(LOG_NOTICE, "%s", buf);
912 msyslog(LOG_NOTICE, "----------------------------------------------------");
913 msyslog(LOG_NOTICE, "ntp-4 is maintained by Network Time Foundation,");
914 msyslog(LOG_NOTICE, "Inc. (NTF), a non-profit 501(c)(3) public-benefit");
915 msyslog(LOG_NOTICE, "corporation. Support and training for ntp-4 are");
916 msyslog(LOG_NOTICE, "available at https://www.nwtime.org/support");
917 msyslog(LOG_NOTICE, "----------------------------------------------------");
920 * Install trap handlers to log errors and assertion failures.
921 * Default handlers print to stderr which doesn't work if detached.
923 isc_assertion_setcallback(assertion_failed);
924 isc_error_setfatal(library_fatal_error);
925 isc_error_setunexpected(library_unexpected_error);
927 /* MPE lacks the concept of root */
928 # if defined(HAVE_GETUID) && !defined(MPE)
930 if (uid && !HAVE_OPT( SAVECONFIGQUIT )
931 # if defined(HAVE_TRUSTEDBSD_MAC)
932 /* We can run as non-root if the mac_ntpd policy is enabled. */
933 && mac_is_present("ntpd") != 1
938 "must be run as root, not uid %ld", (long)uid);
944 * Enable the Multi-Media Timer for Windows?
947 if (HAVE_OPT( MODIFYMMTIMER ))
948 set_mm_timer(MM_TIMER_HIRES);
951 #ifdef HAVE_DNSREGISTRATION
953 * Enable mDNS registrations?
955 if (HAVE_OPT( MDNS )) {
958 #endif /* HAVE_DNSREGISTRATION */
960 if (HAVE_OPT( NOVIRTUALIPS ))
961 listen_to_virtual_ips = 0;
964 * --interface, listen on specified interfaces
966 if (HAVE_OPT( INTERFACE )) {
967 int ifacect = STACKCT_OPT( INTERFACE );
968 const char** ifaces = STACKLST_OPT( INTERFACE );
971 while (ifacect-- > 0) {
973 is_ip_address(*ifaces, AF_UNSPEC, &addr)
976 *ifaces, -1, ACTION_LISTEN);
981 if (HAVE_OPT( NICE ))
984 # ifdef HAVE_SCHED_SETSCHEDULER
985 if (HAVE_OPT( PRIORITY )) {
986 config_priority = OPT_VALUE_PRIORITY;
987 config_priority_override = 1;
992 # ifdef HAVE_WORKING_FORK
993 /* make sure the FDs are initialised
995 * note: if WAIT_SYNC is requested, we *have* to fork. This will
996 * overide any '-n' (nofork) or '-d' (debug) option presented on
999 if (HAVE_OPT(WAIT_SYNC)) {
1000 wait_sync = OPT_VALUE_WAIT_SYNC;
1006 if ( !nofork && pipe(daemon_pipe)) {
1008 "Pipe creation failed for --wait-sync/daemon: %m");
1011 # endif /* HAVE_WORKING_FORK */
1016 * Make sure the service is initialized before we do anything else
1021 * Start interpolation thread, must occur before first
1027 * Initialize random generator and public key pair
1031 ntp_srandom((int)(now.l_i * now.l_uf));
1034 * Detach us from the terminal. May need an #ifndef GIZMO.
1036 # ifdef HAVE_WORKING_FORK
1038 detach_from_terminal(daemon_pipe, wait_sync, logfilename);
1040 # endif /* HAVE_WORKING_FORK */
1044 * SCO OpenServer's system clock offers much more precise timekeeping
1045 * on the base CPU than the other CPUs (for multiprocessor systems),
1046 * so we must lock to the base CPU.
1048 fd = open("/dev/at1", O_RDONLY);
1051 if (ioctl(fd, ACPU_LOCK, &zero) < 0)
1052 msyslog(LOG_ERR, "cannot lock to base CPU: %m");
1057 /* Setup stack size in preparation for locking pages in memory. */
1058 # if defined(HAVE_MLOCKALL)
1059 # ifdef HAVE_SETRLIMIT
1060 ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
1061 # ifdef RLIMIT_MEMLOCK
1063 * The default RLIMIT_MEMLOCK is very low on Linux systems.
1064 * Unless we increase this limit malloc calls are likely to
1065 * fail if we drop root privilege. To be useful the value
1066 * has to be larger than the largest ntpd resident set size.
1068 ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
1069 # endif /* RLIMIT_MEMLOCK */
1070 # endif /* HAVE_SETRLIMIT */
1071 # else /* !HAVE_MLOCKALL follows */
1076 * set the stack limit for AIX for plock().
1077 * see get_aix_stack() for more info.
1079 if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
1081 "Cannot adjust stack limit for plock: %m");
1083 # endif /* PROCLOCK */
1084 # endif /* HAVE_PLOCK */
1085 # endif /* !HAVE_MLOCKALL */
1088 * Set up signals we pay attention to locally.
1091 signal_no_reset(SIGDIE1, finish);
1092 signal_no_reset(SIGDIE2, finish);
1093 signal_no_reset(SIGDIE3, finish);
1094 signal_no_reset(SIGDIE4, finish);
1097 signal_no_reset(SIGBUS, finish);
1100 # if !defined(SYS_WINNT) && !defined(VMS)
1102 (void) signal_no_reset(MOREDEBUGSIG, moredebug);
1103 (void) signal_no_reset(LESSDEBUGSIG, lessdebug);
1105 (void) signal_no_reset(MOREDEBUGSIG, no_debug);
1106 (void) signal_no_reset(LESSDEBUGSIG, no_debug);
1108 # endif /* !SYS_WINNT && !VMS */
1111 * Set up signals we should never pay attention to.
1114 signal_no_reset(SIGPIPE, SIG_IGN);
1118 * Call the init_ routines to initialize the data structures.
1120 * Exactly what command-line options are we expecting here?
1134 set_process_priority();
1135 init_proto(); /* Call at high priority */
1138 mon_start(MON_ON); /* monitor on by default now */
1139 /* turn off in config if unwanted */
1142 * Get the configuration. This is done in a separate module
1143 * since this will definitely be different for the gizmo board.
1145 getconfig(argc, argv);
1147 if (-1 == cur_memlock) {
1148 # if defined(HAVE_MLOCKALL)
1150 * lock the process into memory
1152 if ( !HAVE_OPT(SAVECONFIGQUIT)
1153 # ifdef RLIMIT_MEMLOCK
1154 && -1 != DFLT_RLIMIT_MEMLOCK
1156 && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
1157 msyslog(LOG_ERR, "mlockall(): %m");
1158 # else /* !HAVE_MLOCKALL follows */
1162 * lock the process into memory
1164 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
1165 msyslog(LOG_ERR, "plock(PROCLOCK): %m");
1166 # else /* !PROCLOCK follows */
1169 * Lock text into ram
1171 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
1172 msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
1173 # else /* !TXTLOCK follows */
1174 msyslog(LOG_ERR, "plock() - don't know what to lock!");
1175 # endif /* !TXTLOCK */
1176 # endif /* !PROCLOCK */
1177 # endif /* HAVE_PLOCK */
1178 # endif /* !HAVE_MLOCKALL */
1181 loop_config(LOOP_DRIFTINIT, 0);
1182 report_event(EVNT_SYSRESTART, NULL, NULL);
1183 initializing = FALSE;
1185 # ifdef HAVE_LINUX_CAPABILITIES
1187 /* Check that setting capabilities actually works; we might be
1188 * run on a kernel with disabled capabilities. We must not
1189 * drop privileges in this case.
1192 caps = cap_from_text("cap_sys_time,cap_setuid,cap_setgid,cap_sys_chroot,cap_net_bind_service=pe");
1194 msyslog( LOG_ERR, "cap_from_text() failed: %m" );
1197 have_caps = (cap_set_proc(caps) == 0);
1198 cap_free(caps); /* caps not NULL here! */
1200 # endif /* HAVE_LINUX_CAPABILITIES */
1202 # ifdef HAVE_DROPROOT
1203 # ifdef HAVE_LINUX_CAPABILITIES
1204 if (droproot && have_caps) {
1207 # endif /*HAVE_LINUX_CAPABILITIES*/
1209 # ifdef NEED_EARLY_FORK
1210 fork_nonchroot_worker();
1213 /* Drop super-user privileges and chroot now if the OS supports this */
1215 # ifdef HAVE_LINUX_CAPABILITIES
1216 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
1217 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
1218 msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
1221 # elif HAVE_SOLARIS_PRIVS
1222 /* Nothing to do here */
1224 /* we need a user to switch to */
1226 msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
1229 # endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
1232 if (0 == map_user())
1235 if (group != NULL) {
1236 if (0 == map_group())
1241 /* make sure cwd is inside the jail: */
1242 if (chdir(chrootdir)) {
1243 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
1246 if (chroot(chrootdir)) {
1247 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
1251 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
1255 # ifdef HAVE_SOLARIS_PRIVS
1256 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
1257 msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
1260 if ((highprivs = priv_allocset()) == NULL) {
1261 msyslog(LOG_ERR, "priv_allocset() failed:%m");
1264 (void) getppriv(PRIV_PERMITTED, highprivs);
1265 (void) priv_intersect(highprivs, lowprivs);
1266 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1267 msyslog(LOG_ERR, "setppriv() failed:%m");
1270 # endif /* HAVE_SOLARIS_PRIVS */
1271 if (0 == set_user_group_ids())
1274 # if defined(HAVE_TRUSTEDBSD_MAC)
1276 * To manipulate system time and (re-)bind to NTP_PORT as needed
1277 * following interface changes, we must either run as uid 0 or
1278 * the mac_ntpd policy module must be enabled.
1280 if (sw_uid != 0 && mac_is_present("ntpd") != 1) {
1281 msyslog(LOG_ERR, "Need MAC 'ntpd' policy enabled to drop root privileges");
1284 # elif !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1286 * for now assume that the privilege to bind to privileged ports
1287 * is associated with running with uid 0 - should be refined on
1288 * ports that allow binding to NTP_PORT with uid != 0
1290 disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */
1291 # endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1293 if (disable_dynamic_updates && interface_interval) {
1294 interface_interval = 0;
1295 msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1298 # ifdef HAVE_LINUX_CAPABILITIES
1301 * We may be running under non-root uid now, but we still hold full root privileges!
1302 * We drop all of them, except for the crucial one or two: cap_sys_time and
1303 * cap_net_bind_service if doing dynamic interface tracking.
1308 captext = (0 != interface_interval)
1309 ? "cap_sys_time,cap_net_bind_service=pe"
1310 : "cap_sys_time=pe";
1311 caps = cap_from_text(captext);
1314 "cap_from_text(%s) failed: %m",
1318 if (-1 == cap_set_proc(caps)) {
1320 "cap_set_proc() failed to drop root privs: %m");
1325 # endif /* HAVE_LINUX_CAPABILITIES */
1326 # ifdef HAVE_SOLARIS_PRIVS
1327 if (priv_delset(lowprivs, "proc_setid") == -1) {
1328 msyslog(LOG_ERR, "priv_delset() failed:%m");
1331 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1332 msyslog(LOG_ERR, "setppriv() failed:%m");
1335 priv_freeset(lowprivs);
1336 priv_freeset(highprivs);
1337 # endif /* HAVE_SOLARIS_PRIVS */
1338 root_dropped = TRUE;
1339 fork_deferred_worker();
1340 } /* if (droproot) */
1341 # endif /* HAVE_DROPROOT */
1343 /* libssecomp sandboxing */
1344 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1345 scmp_filter_ctx ctx;
1347 if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1348 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1350 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1359 SCMP_SYS(clock_gettime),
1360 SCMP_SYS(clock_settime),
1363 SCMP_SYS(exit_group),
1367 SCMP_SYS(getitimer),
1368 SCMP_SYS(getsockname),
1379 SCMP_SYS(rt_sigaction),
1380 SCMP_SYS(rt_sigprocmask),
1381 SCMP_SYS(rt_sigreturn),
1384 SCMP_SYS(setitimer),
1394 SCMP_SYS(_newselect),
1398 SCMP_SYS(clock_gettime),
1399 SCMP_SYS(clock_settime),
1401 SCMP_SYS(exit_group),
1404 SCMP_SYS(getitimer),
1413 SCMP_SYS(rt_sigaction),
1414 SCMP_SYS(rt_sigprocmask),
1416 SCMP_SYS(setitimer),
1418 SCMP_SYS(sigprocmask),
1419 SCMP_SYS(sigreturn),
1420 SCMP_SYS(socketcall),
1429 for (i = 0; i < COUNTOF(scmp_sc); i++) {
1430 if (seccomp_rule_add(ctx,
1431 SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1433 "%s: seccomp_rule_add() failed: %m",
1439 if (seccomp_load(ctx) < 0)
1440 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1443 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1445 #endif /* LIBSECCOMP and KERN_SECCOMP */
1447 #if defined(SYS_WINNT)
1449 #elif defined(HAVE_WORKING_FORK)
1450 if (daemon_pipe[1] != -1) {
1451 write(daemon_pipe[1], "R\n", 2);
1453 #endif /* HAVE_WORKING_FORK */
1455 # ifndef HAVE_IO_COMPLETION_PORT
1456 BLOCK_IO_AND_ALARM();
1457 was_alarmed = FALSE;
1461 #if !defined(SIM) && defined(SIGDIE1)
1465 # ifdef HAVE_IO_COMPLETION_PORT
1466 GetReceivedBuffers();
1468 # else /* normal I/O */
1469 if (alarm_flag) { /* alarmed? */
1474 /* collect async name/addr results */
1476 harvest_blocking_responses();
1478 if (!was_alarmed && !has_full_recv_buffer()) {
1480 * Nothing to do. Wait for something.
1485 if (alarm_flag) { /* alarmed? */
1491 UNBLOCK_IO_AND_ALARM();
1493 * Out here, signals are unblocked. Call timer routine
1494 * to process expiry.
1497 was_alarmed = FALSE;
1498 BLOCK_IO_AND_ALARM();
1501 # endif /* !HAVE_IO_COMPLETION_PORT */
1503 # ifdef DEBUG_TIMING
1512 rbuf = get_full_recv_buffer();
1513 while (rbuf != NULL) {
1518 UNBLOCK_IO_AND_ALARM();
1521 /* avoid timer starvation during lengthy I/O handling */
1523 was_alarmed = FALSE;
1527 * Call the data procedure to handle each received
1530 if (rbuf->receiver != NULL) {
1531 # ifdef DEBUG_TIMING
1534 L_SUB(&dts, &rbuf->recv_time);
1535 DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1536 collect_timing(rbuf, "buffer processing delay", 1, &dts);
1539 (*rbuf->receiver)(rbuf);
1541 msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1545 BLOCK_IO_AND_ALARM();
1547 rbuf = get_full_recv_buffer();
1549 # ifdef DEBUG_TIMING
1553 collect_timing(NULL, "processing", bufcount, &tsb);
1554 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1563 # ifdef HAVE_DNSREGISTRATION
1564 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1565 mdnsreg = current_time;
1566 msyslog(LOG_INFO, "Attempting to register mDNS");
1567 if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1568 htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1570 msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1572 msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1575 msyslog(LOG_INFO, "mDNS service registered.");
1579 # endif /* HAVE_DNSREGISTRATION */
1582 UNBLOCK_IO_AND_ALARM();
1588 #if !defined(SIM) && defined(SIGDIE1)
1590 * finish - exit gracefully
1597 const char *sig_desc;
1600 #ifdef HAVE_STRSIGNAL
1601 sig_desc = strsignal(sig);
1603 if (sig_desc == NULL)
1605 msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1607 /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1608 # ifdef HAVE_DNSREGISTRATION
1610 DNSServiceRefDeallocate(mdns);
1625 #endif /* !SIM && SIGDIE1 */
1630 * wait_child_sync_if - implements parent side of -w/--wait-sync
1632 # ifdef HAVE_WORKING_FORK
1637 unsigned long wait_sync
1642 time_t wait_end_time;
1646 struct timeval wtimeout;
1648 /* we wait a bit for the child in *any* case, because on failure
1649 * of the child we have to get and inspect the exit code!
1651 wait_end_time = time(NULL);
1653 wait_end_time += wait_sync;
1655 wait_end_time += 30;
1658 cur_time = time(NULL);
1659 wait_rem = (wait_end_time > cur_time)
1660 ? (wait_end_time - cur_time)
1662 wtimeout.tv_sec = wait_rem;
1663 wtimeout.tv_usec = 0;
1665 FD_SET(pipe_read_fd, &readset);
1666 rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1672 "daemon startup: select failed: %m");
1677 * select() indicated a timeout, but in case
1678 * its timeouts are affected by a step of the
1679 * system clock, select() again with a zero
1680 * timeout to confirm.
1683 FD_SET(pipe_read_fd, &readset);
1684 wtimeout.tv_sec = 0;
1685 wtimeout.tv_usec = 0;
1686 rc = select(pipe_read_fd + 1, &readset, NULL,
1688 if (0 == rc) /* select() timeout */
1691 rc = read(pipe_read_fd, &ch, 1);
1693 DPRINTF(2, ("daemon control: got EOF\n"));
1694 return -1; /* unexpected EOF, check daemon */
1695 } else if (rc == 1) {
1696 DPRINTF(2, ("daemon control: got '%c'\n",
1697 (ch >= ' ' ? ch : '.')));
1698 if (ch == 'R' && !wait_sync)
1700 if (ch == 'S' && wait_sync)
1703 DPRINTF(2, ("daemon control: read 1 char failed: %s\n",
1707 } while (wait_rem > 0);
1710 fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1711 progname, wait_sync);
1714 fprintf(stderr, "%s: daemon startup monitoring timed out.\n",
1727 # ifdef HAVE_WAITPID
1730 if (cpid == waitpid(cpid, &wstatus, (blocking ? 0 : WNOHANG))) {
1731 DPRINTF(1, ("child (pid=%d) dead now\n", cpid));
1732 if (WIFEXITED(wstatus)) {
1733 rc = WEXITSTATUS(wstatus);
1734 msyslog(LOG_ERR, "daemon child exited with code %d",
1736 } else if (WIFSIGNALED(wstatus)) {
1738 msyslog(LOG_ERR, "daemon child died with signal %d",
1742 msyslog(LOG_ERR, "daemon child died with unknown cause");
1745 DPRINTF(1, ("child (pid=%d) still alive\n", cpid));
1754 # endif /* HAVE_WORKING_FORK */
1758 * assertion_failed - Redirect assertion failures to msyslog().
1764 isc_assertiontype_t type,
1768 isc_assertion_setcallback(NULL); /* Avoid recursion */
1770 msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1771 file, line, isc_assertion_typetotext(type), cond);
1772 msyslog(LOG_ERR, "exiting (due to assertion failure)");
1774 #if defined(DEBUG) && defined(SYS_WINNT)
1784 * library_fatal_error - Handle fatal errors from our libraries.
1787 library_fatal_error(
1796 isc_error_setfatal(NULL); /* Avoid recursion */
1798 msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1799 vsnprintf(errbuf, sizeof(errbuf), format, args);
1800 msyslog(LOG_ERR, "%s", errbuf);
1801 msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1803 #if defined(DEBUG) && defined(SYS_WINNT)
1813 * library_unexpected_error - Handle non fatal errors from our libraries.
1815 # define MAX_UNEXPECTED_ERRORS 100
1816 int unexpected_error_cnt = 0;
1818 library_unexpected_error(
1827 if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1828 return; /* avoid clutter in log */
1830 msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1831 vsnprintf(errbuf, sizeof(errbuf), format, args);
1832 msyslog(LOG_ERR, "%s", errbuf);
1834 if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1835 msyslog(LOG_ERR, "Too many errors. Shutting up.");
1840 #if !defined(SIM) && !defined(SYS_WINNT)
1844 * moredebug - increase debugging verbosity
1851 int saved_errno = errno;
1856 msyslog(LOG_DEBUG, "debug raised to %d", debug);
1858 errno = saved_errno;
1863 * lessdebug - decrease debugging verbosity
1870 int saved_errno = errno;
1875 msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1877 errno = saved_errno;
1880 # else /* !DEBUG follows */
1884 * no_debug - We don't do the debug here.
1891 int saved_errno = errno;
1893 msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1894 errno = saved_errno;
1896 # endif /* !DEBUG */
1897 #endif /* !SIM && !SYS_WINNT */