2 * ntpd.c - main program for the fixed point NTP daemon
9 #include "ntp_machine.h"
12 #include "ntp_stdlib.h"
13 #include <ntp_random.h>
15 #include "ntp_config.h"
16 #include "ntp_syslog.h"
17 #include "ntp_assert.h"
18 #include "isc/error.h"
19 #include "isc/strerror.h"
20 #include "isc/formatcheck.h"
27 #include "ntp_libopts.h"
28 #include "ntpd-opts.h"
30 /* there's a short treatise below what the thread stuff is for.
31 * [Bug 2954] enable the threading warm-up only for Linux.
33 #if defined(HAVE_PTHREADS) && HAVE_PTHREADS && !defined(NO_THREADS)
34 # ifdef HAVE_PTHREAD_H
38 # define NEED_PTHREAD_WARMUP
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
49 #ifdef HAVE_SYS_PARAM_H
50 # include <sys/param.h>
52 #ifdef HAVE_SYS_SIGNAL_H
53 # include <sys/signal.h>
57 #ifdef HAVE_SYS_IOCTL_H
58 # include <sys/ioctl.h>
59 #endif /* HAVE_SYS_IOCTL_H */
60 #if defined(HAVE_RTPRIO)
61 # ifdef HAVE_SYS_LOCK_H
62 # include <sys/lock.h>
64 # include <sys/rtprio.h>
67 # ifdef HAVE_SYS_LOCK_H
68 # include <sys/lock.h>
72 #if defined(HAVE_SCHED_SETSCHEDULER)
76 # ifdef HAVE_SYS_SCHED_H
77 # include <sys/sched.h>
81 #if defined(HAVE_SYS_MMAN_H)
82 # include <sys/mman.h>
90 # include <apollo/base.h>
91 #endif /* SYS_DOMAINOS */
95 #include "ntp_cmdargs.h"
97 #if 0 /* HMS: I don't think we need this. 961223 */
100 # include <sys/mman.h>
102 # include <sys/lock.h>
112 # include <sys/ci/ciioctl.h>
119 #ifdef HAVE_LINUX_CAPABILITIES
120 # include <sys/capability.h>
121 # include <sys/prctl.h>
122 #endif /* HAVE_LINUX_CAPABILITIES */
123 #if defined(HAVE_PRIV_H) && defined(HAVE_SOLARIS_PRIVS)
125 #endif /* HAVE_PRIV_H */
126 #if defined(HAVE_TRUSTEDBSD_MAC)
127 # include <sys/mac.h>
128 #endif /* HAVE_TRUSTEDBSD_MAC */
129 #endif /* HAVE_DROPROOT */
131 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
132 /* # include <sys/types.h> */
133 # include <sys/resource.h>
134 # include <seccomp.h>
135 #endif /* LIBSECCOMP and KERN_SECCOMP */
137 #ifdef HAVE_DNSREGISTRATION
142 #ifdef HAVE_SETPGRP_0
143 # define ntp_setpgrp(x, y) setpgrp()
145 # define ntp_setpgrp(x, y) setpgrp(x, y)
148 #ifdef HAVE_SOLARIS_PRIVS
149 # define LOWPRIVS "basic,sys_time,net_privaddr,proc_setid,!proc_info,!proc_session,!proc_exec"
150 static priv_set_t *lowprivs = NULL;
151 static priv_set_t *highprivs = NULL;
152 #endif /* HAVE_SOLARIS_PRIVS */
154 * Scheduling priority we run at
156 #define NTPD_PRIO (-12)
158 int priority_done = 2; /* 0 - Set priority */
159 /* 1 - priority is OK where it is */
160 /* 2 - Don't set priority */
161 /* 1 and 2 are pretty much the same */
163 int listen_to_virtual_ips = TRUE;
166 * No-fork flag. If set, we do not become a background daemon.
168 int nofork; /* Fork by default */
170 #ifdef HAVE_DNSREGISTRATION
172 * mDNS registration flag. If set, we attempt to register with the mDNS system, but only
173 * after we have synched the first time. If the attempt fails, then try again once per
174 * minute for up to 5 times. After all, we may be starting before mDNS.
178 #endif /* HAVE_DNSREGISTRATION */
183 char *user; /* User to switch to */
184 char *group; /* group to switch to */
185 const char *chrootdir; /* directory to chroot to */
191 #endif /* HAVE_DROPROOT */
193 #ifdef HAVE_WORKING_FORK
194 int waitsync_fd_to_close = -1; /* -w/--wait-sync */
198 * Version declaration
200 extern const char *Version;
202 char const *progname;
208 * We put this here, since the argument profile is syscall-specific
210 extern int syscall (int, ...);
211 #endif /* DECL_SYSCALL */
214 #if !defined(SIM) && defined(SIGDIE1)
215 static volatile int signalled = 0;
216 static volatile int signo = 0;
218 /* In an ideal world, 'finish_safe()' would declared as noreturn... */
219 static void finish_safe (int);
220 static RETSIGTYPE finish (int);
223 #if !defined(SIM) && defined(HAVE_WORKING_FORK)
224 static int wait_child_sync_if (int, long);
227 #if !defined(SIM) && !defined(SYS_WINNT)
229 static RETSIGTYPE moredebug (int);
230 static RETSIGTYPE lessdebug (int);
231 # else /* !DEBUG follows */
232 static RETSIGTYPE no_debug (int);
234 #endif /* !SIM && !SYS_WINNT */
242 int ntpdmain (int, char **);
243 static void set_process_priority (void);
244 static void assertion_failed (const char *, int,
247 __attribute__ ((__noreturn__));
248 static void library_fatal_error (const char *, int,
249 const char *, va_list)
250 ISC_FORMAT_PRINTF(3, 0);
251 static void library_unexpected_error(const char *, int,
252 const char *, va_list)
253 ISC_FORMAT_PRINTF(3, 0);
257 /* Bug2332 unearthed a problem in the interaction of reduced user
258 * privileges, the limits on memory usage and some versions of the
259 * pthread library on Linux systems. The 'pthread_cancel()' function and
260 * likely some others need to track the stack of the thread involved,
261 * and uses a function that comes from GCC (--> libgcc_s.so) to do
262 * this. Unfortunately the developers of glibc decided to load the
263 * library on demand, which speeds up program start but can cause
264 * trouble here: Due to all the things NTPD does to limit its resource
265 * usage, this deferred load of libgcc_s does not always work once the
266 * restrictions are in effect.
268 * One way out of this was attempting a forced link against libgcc_s
269 * when possible because it makes the library available immediately
270 * without deferred load. (The symbol resolution would still be dynamic
271 * and on demand, but the code would already be in the process image.)
273 * This is a tricky thing to do, since it's not necessary everywhere,
274 * not possible everywhere, has shown to break the build of other
275 * programs in the NTP suite and is now generally frowned upon.
277 * So we take a different approach here: We creat a worker thread that does
278 * actually nothing except waiting for cancellation and cancel it. If
279 * this is done before all the limitations are put in place, the
280 * machinery is pre-heated and all the runtime stuff should be in place
281 * and useable when needed.
283 * This uses only the standard pthread API and should work with all
284 * implementations of pthreads. It is not necessary everywhere, but it's
285 * cheap enough to go on nearly unnoticed.
287 * Addendum: Bug 2954 showed that the assumption that this should work
288 * with all OS is wrong -- at least FreeBSD bombs heavily.
290 #ifdef NEED_PTHREAD_WARMUP
292 /* simple thread function: sleep until cancelled, just to exercise
293 * thread cancellation.
296 my_pthread_warmup_worker(
305 /* pre-heat threading: create a thread and cancel it, just to exercise
306 * thread cancellation.
309 my_pthread_warmup(void)
312 pthread_attr_t thr_attr;
315 pthread_attr_init(&thr_attr);
316 #if defined(HAVE_PTHREAD_ATTR_GETSTACKSIZE) && \
317 defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && \
318 defined(PTHREAD_STACK_MIN)
320 size_t ssmin = 32*1024; /* 32kB should be minimum */
321 if (ssmin < PTHREAD_STACK_MIN)
322 ssmin = PTHREAD_STACK_MIN;
323 rc = pthread_attr_setstacksize(&thr_attr, ssmin);
326 "my_pthread_warmup: pthread_attr_setstacksize() -> %s",
331 &thread, &thr_attr, my_pthread_warmup_worker, NULL);
332 pthread_attr_destroy(&thr_attr);
335 "my_pthread_warmup: pthread_create() -> %s",
338 pthread_cancel(thread);
339 pthread_join(thread, NULL);
343 #endif /*defined(NEED_PTHREAD_WARMUP)*/
345 #ifdef NEED_EARLY_FORK
347 dummy_callback(void) { return; }
350 fork_nonchroot_worker(void) {
351 getaddrinfo_sometime("localhost", "ntp", NULL, INITIAL_DNS_RETRY,
352 (gai_sometime_callback)&dummy_callback, NULL);
354 #endif /* NEED_EARLY_FORK */
366 optct = ntpOptionProcess(&ntpdOptions, *pargc, *pargv);
383 parse_cmdline_opts(&argc, &argv);
385 debug = OPT_VALUE_SET_DEBUG_LEVEL;
386 DPRINTF(1, ("%s\n", Version));
389 return ntpsim(argc, argv);
391 #else /* !SIM follows */
392 #ifdef NO_MAIN_ALLOWED
393 CALL(ntpd,"ntpd",ntpdmain);
394 #else /* !NO_MAIN_ALLOWED follows */
402 return ntpdmain(argc, argv);
404 #endif /* !SYS_WINNT */
405 #endif /* !NO_MAIN_ALLOWED */
410 * OK. AIX is different than solaris in how it implements plock().
411 * If you do NOT adjust the stack limit, you will get the MAXIMUM
412 * stack size allocated and PINNED with you program. To check the
413 * value, use ulimit -a.
415 * To fix this, we create an automatic variable and set our stack limit
416 * to that PLUS 32KB of extra space (we need some headroom).
418 * This subroutine gets the stack address.
420 * Grover Davidson and Matt Ladendorf
431 * Signal handler for SIGDANGER.
434 catch_danger(int signo)
436 msyslog(LOG_INFO, "ntpd: setpgid(): %m");
437 /* Make the system believe we'll free something, but don't do it! */
443 * Set the process priority
447 set_process_priority(void)
452 msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>",
454 ? "Leave priority alone"
455 : "Attempt to set priority"
460 # if defined(HAVE_SCHED_SETSCHEDULER)
461 if (!priority_done) {
462 extern int config_priority_override, config_priority;
464 struct sched_param sched;
466 pmax = sched_get_priority_max(SCHED_FIFO);
467 sched.sched_priority = pmax;
468 if ( config_priority_override ) {
469 pmin = sched_get_priority_min(SCHED_FIFO);
470 if ( config_priority > pmax )
471 sched.sched_priority = pmax;
472 else if ( config_priority < pmin )
473 sched.sched_priority = pmin;
475 sched.sched_priority = config_priority;
477 if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 )
478 msyslog(LOG_ERR, "sched_setscheduler(): %m");
482 # endif /* HAVE_SCHED_SETSCHEDULER */
485 if (!priority_done) {
488 srtp.type = RTP_PRIO_REALTIME; /* was: RTP_PRIO_NORMAL */
489 srtp.prio = 0; /* 0 (hi) -> RTP_PRIO_MAX (31,lo) */
491 if (rtprio(RTP_SET, getpid(), &srtp) < 0)
492 msyslog(LOG_ERR, "rtprio() error: %m");
496 # else /* !RTP_SET follows */
497 if (!priority_done) {
498 if (rtprio(0, 120) < 0)
499 msyslog(LOG_ERR, "rtprio() error: %m");
503 # endif /* !RTP_SET */
504 # endif /* HAVE_RTPRIO */
505 # if defined(NTPD_PRIO) && NTPD_PRIO != 0
506 # ifdef HAVE_ATT_NICE
507 if (!priority_done) {
509 if (-1 == nice (NTPD_PRIO) && errno != 0)
510 msyslog(LOG_ERR, "nice() error: %m");
514 # endif /* HAVE_ATT_NICE */
515 # ifdef HAVE_BSD_NICE
516 if (!priority_done) {
517 if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO))
518 msyslog(LOG_ERR, "setpriority() error: %m");
522 # endif /* HAVE_BSD_NICE */
523 # endif /* NTPD_PRIO && NTPD_PRIO != 0 */
525 msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority");
531 * Main program. Initialize us, disconnect us from the tty if necessary,
532 * and loop waiting for I/O and/or timer expiries.
542 struct recvbuf *rbuf;
543 const char * logfilename;
547 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
550 # if defined(HAVE_WORKING_FORK)
558 # if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
561 # endif /* HAVE_WORKING_FORK*/
567 # ifdef NEED_PTHREAD_WARMUP
581 initializing = TRUE; /* mark that we are initializing */
582 parse_cmdline_opts(&argc, &argv);
584 debug = OPT_VALUE_SET_DEBUG_LEVEL;
585 # ifdef HAVE_SETLINEBUF
590 if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
594 || HAVE_OPT(SAVECONFIGQUIT))
597 init_logging(progname, NLOG_SYNCMASK, TRUE);
598 /* honor -l/--logfile option to log to a file */
599 if (HAVE_OPT(LOGFILE)) {
600 logfilename = OPT_ARG(LOGFILE);
602 change_logfile(logfilename, FALSE);
607 if (HAVE_OPT(SAVECONFIGQUIT))
610 msyslog(LOG_NOTICE, "%s: Starting", Version);
614 char buf[1024]; /* Secret knowledge of msyslog buf length */
617 /* Note that every arg has an initial space character */
618 snprintf(cp, sizeof(buf), "Command line:");
621 for (i = 0; i < saved_argc ; ++i) {
622 snprintf(cp, sizeof(buf) - (cp - buf),
623 " %s", saved_argv[i]);
626 msyslog(LOG_INFO, "%s", buf);
630 * Install trap handlers to log errors and assertion failures.
631 * Default handlers print to stderr which doesn't work if detached.
633 isc_assertion_setcallback(assertion_failed);
634 isc_error_setfatal(library_fatal_error);
635 isc_error_setunexpected(library_unexpected_error);
637 /* MPE lacks the concept of root */
638 # if defined(HAVE_GETUID) && !defined(MPE)
640 if (uid && !HAVE_OPT( SAVECONFIGQUIT )
641 # if defined(HAVE_TRUSTEDBSD_MAC)
642 /* We can run as non-root if the mac_ntpd policy is enabled. */
643 && mac_is_present("ntpd") != 1
648 "must be run as root, not uid %ld", (long)uid);
654 * Enable the Multi-Media Timer for Windows?
657 if (HAVE_OPT( MODIFYMMTIMER ))
658 set_mm_timer(MM_TIMER_HIRES);
661 #ifdef HAVE_DNSREGISTRATION
663 * Enable mDNS registrations?
665 if (HAVE_OPT( MDNS )) {
668 #endif /* HAVE_DNSREGISTRATION */
670 if (HAVE_OPT( NOVIRTUALIPS ))
671 listen_to_virtual_ips = 0;
674 * --interface, listen on specified interfaces
676 if (HAVE_OPT( INTERFACE )) {
677 int ifacect = STACKCT_OPT( INTERFACE );
678 const char** ifaces = STACKLST_OPT( INTERFACE );
681 while (ifacect-- > 0) {
683 is_ip_address(*ifaces, AF_UNSPEC, &addr)
686 *ifaces, -1, ACTION_LISTEN);
691 if (HAVE_OPT( NICE ))
694 # ifdef HAVE_SCHED_SETSCHEDULER
695 if (HAVE_OPT( PRIORITY )) {
696 config_priority = OPT_VALUE_PRIORITY;
697 config_priority_override = 1;
702 # ifdef HAVE_WORKING_FORK
703 /* make sure the FDs are initialised */
706 do { /* 'loop' once */
707 if (!HAVE_OPT( WAIT_SYNC ))
709 wait_sync = OPT_VALUE_WAIT_SYNC;
710 if (wait_sync <= 0) {
714 /* -w requires a fork() even with debug > 0 */
716 if (pipe(pipe_fds)) {
717 exit_code = (errno) ? errno : -1;
719 "Pipe creation failed for --wait-sync: %m");
722 waitsync_fd_to_close = pipe_fds[1];
723 } while (0); /* 'loop' once */
724 # endif /* HAVE_WORKING_FORK */
729 * Start interpolation thread, must occur before first
735 * Initialize random generator and public key pair
739 ntp_srandom((int)(now.l_i * now.l_uf));
742 * Detach us from the terminal. May need an #ifndef GIZMO.
746 # ifdef HAVE_WORKING_FORK
749 exit_code = (errno) ? errno : -1;
750 msyslog(LOG_ERR, "fork: %m");
755 exit_code = wait_child_sync_if(pipe_fds[0],
762 * close all open files excepting waitsync_fd_to_close.
763 * msyslog() unreliable until after init_logging().
766 if (syslog_file != NULL) {
771 close_all_except(waitsync_fd_to_close);
772 INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
775 init_logging(progname, 0, TRUE);
776 /* we lost our logfile (if any) daemonizing */
777 setup_logfile(logfilename);
784 proc2_$who_am_i(&puid);
785 proc2_$make_server(&puid, &st);
787 # endif /* SYS_DOMAINOS */
789 if (setsid() == (pid_t)-1)
790 msyslog(LOG_ERR, "setsid(): %m");
791 # elif defined(HAVE_SETPGID)
792 if (setpgid(0, 0) == -1)
793 msyslog(LOG_ERR, "setpgid(): %m");
794 # else /* !HAVE_SETSID && !HAVE_SETPGID follows */
796 fid = open("/dev/tty", 2);
798 ioctl(fid, (u_long)TIOCNOTTY, NULL);
801 # endif /* TIOCNOTTY */
802 ntp_setpgrp(0, getpid());
803 # endif /* !HAVE_SETSID && !HAVE_SETPGID */
805 /* Don't get killed by low-on-memory signal. */
806 sa.sa_handler = catch_danger;
807 sigemptyset(&sa.sa_mask);
808 sa.sa_flags = SA_RESTART;
809 sigaction(SIGDANGER, &sa, NULL);
811 # endif /* HAVE_WORKING_FORK */
816 * SCO OpenServer's system clock offers much more precise timekeeping
817 * on the base CPU than the other CPUs (for multiprocessor systems),
818 * so we must lock to the base CPU.
820 fd = open("/dev/at1", O_RDONLY);
823 if (ioctl(fd, ACPU_LOCK, &zero) < 0)
824 msyslog(LOG_ERR, "cannot lock to base CPU: %m");
829 /* Setup stack size in preparation for locking pages in memory. */
830 # if defined(HAVE_MLOCKALL)
831 # ifdef HAVE_SETRLIMIT
832 ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
833 # ifdef RLIMIT_MEMLOCK
835 * The default RLIMIT_MEMLOCK is very low on Linux systems.
836 * Unless we increase this limit malloc calls are likely to
837 * fail if we drop root privilege. To be useful the value
838 * has to be larger than the largest ntpd resident set size.
840 ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
841 # endif /* RLIMIT_MEMLOCK */
842 # endif /* HAVE_SETRLIMIT */
843 # else /* !HAVE_MLOCKALL follows */
848 * set the stack limit for AIX for plock().
849 * see get_aix_stack() for more info.
851 if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
853 "Cannot adjust stack limit for plock: %m");
855 # endif /* PROCLOCK */
856 # endif /* HAVE_PLOCK */
857 # endif /* !HAVE_MLOCKALL */
860 * Set up signals we pay attention to locally.
863 signal_no_reset(SIGDIE1, finish);
864 signal_no_reset(SIGDIE2, finish);
865 signal_no_reset(SIGDIE3, finish);
866 signal_no_reset(SIGDIE4, finish);
869 signal_no_reset(SIGBUS, finish);
872 # if !defined(SYS_WINNT) && !defined(VMS)
874 (void) signal_no_reset(MOREDEBUGSIG, moredebug);
875 (void) signal_no_reset(LESSDEBUGSIG, lessdebug);
877 (void) signal_no_reset(MOREDEBUGSIG, no_debug);
878 (void) signal_no_reset(LESSDEBUGSIG, no_debug);
880 # endif /* !SYS_WINNT && !VMS */
883 * Set up signals we should never pay attention to.
886 signal_no_reset(SIGPIPE, SIG_IGN);
890 * Call the init_ routines to initialize the data structures.
892 * Exactly what command-line options are we expecting here?
906 set_process_priority();
907 init_proto(); /* Call at high priority */
910 mon_start(MON_ON); /* monitor on by default now */
911 /* turn off in config if unwanted */
914 * Get the configuration. This is done in a separate module
915 * since this will definitely be different for the gizmo board.
917 getconfig(argc, argv);
919 if (-1 == cur_memlock) {
920 # if defined(HAVE_MLOCKALL)
922 * lock the process into memory
924 if ( !HAVE_OPT(SAVECONFIGQUIT)
925 # ifdef RLIMIT_MEMLOCK
926 && -1 != DFLT_RLIMIT_MEMLOCK
928 && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
929 msyslog(LOG_ERR, "mlockall(): %m");
930 # else /* !HAVE_MLOCKALL follows */
934 * lock the process into memory
936 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
937 msyslog(LOG_ERR, "plock(PROCLOCK): %m");
938 # else /* !PROCLOCK follows */
943 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
944 msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
945 # else /* !TXTLOCK follows */
946 msyslog(LOG_ERR, "plock() - don't know what to lock!");
947 # endif /* !TXTLOCK */
948 # endif /* !PROCLOCK */
949 # endif /* HAVE_PLOCK */
950 # endif /* !HAVE_MLOCKALL */
953 loop_config(LOOP_DRIFTINIT, 0);
954 report_event(EVNT_SYSRESTART, NULL, NULL);
955 initializing = FALSE;
957 # ifdef HAVE_DROPROOT
960 #ifdef NEED_EARLY_FORK
961 fork_nonchroot_worker();
964 /* Drop super-user privileges and chroot now if the OS supports this */
966 # ifdef HAVE_LINUX_CAPABILITIES
967 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
968 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
969 msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
972 # elif HAVE_SOLARIS_PRIVS
973 /* Nothing to do here */
975 /* we need a user to switch to */
977 msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
980 # endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
983 if (isdigit((unsigned char)*user)) {
984 sw_uid = (uid_t)strtoul(user, &endp, 0);
988 if ((pw = getpwuid(sw_uid)) != NULL) {
990 user = estrdup(pw->pw_name);
994 msyslog(LOG_ERR, "Cannot find user ID %s", user);
1001 if ((pw = getpwnam(user)) != NULL) {
1002 sw_uid = pw->pw_uid;
1003 sw_gid = pw->pw_gid;
1006 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
1008 msyslog(LOG_ERR, "Cannot find user `%s'", user);
1013 if (group != NULL) {
1014 if (isdigit((unsigned char)*group)) {
1015 sw_gid = (gid_t)strtoul(group, &endp, 0);
1020 if ((gr = getgrnam(group)) != NULL) {
1021 sw_gid = gr->gr_gid;
1024 msyslog(LOG_ERR, "Cannot find group `%s'", group);
1031 /* make sure cwd is inside the jail: */
1032 if (chdir(chrootdir)) {
1033 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
1036 if (chroot(chrootdir)) {
1037 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
1041 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
1045 # ifdef HAVE_SOLARIS_PRIVS
1046 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
1047 msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
1050 if ((highprivs = priv_allocset()) == NULL) {
1051 msyslog(LOG_ERR, "priv_allocset() failed:%m");
1054 (void) getppriv(PRIV_PERMITTED, highprivs);
1055 (void) priv_intersect(highprivs, lowprivs);
1056 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1057 msyslog(LOG_ERR, "setppriv() failed:%m");
1060 # endif /* HAVE_SOLARIS_PRIVS */
1061 if (user && initgroups(user, sw_gid)) {
1062 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
1065 if (group && setgid(sw_gid)) {
1066 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
1069 if (group && setegid(sw_gid)) {
1070 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
1074 if (0 != setgroups(1, &sw_gid)) {
1075 msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
1080 if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
1081 msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
1084 if (user && setuid(sw_uid)) {
1085 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
1088 if (user && seteuid(sw_uid)) {
1089 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
1093 # if defined(HAVE_TRUSTEDBSD_MAC)
1095 * To manipulate system time and (re-)bind to NTP_PORT as needed
1096 * following interface changes, we must either run as uid 0 or
1097 * the mac_ntpd policy module must be enabled.
1099 if (sw_uid != 0 && mac_is_present("ntpd") != 1) {
1100 msyslog(LOG_ERR, "Need MAC 'ntpd' policy enabled to drop root privileges");
1103 # elif !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1105 * for now assume that the privilege to bind to privileged ports
1106 * is associated with running with uid 0 - should be refined on
1107 * ports that allow binding to NTP_PORT with uid != 0
1109 disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */
1110 # endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1112 if (disable_dynamic_updates && interface_interval) {
1113 interface_interval = 0;
1114 msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1117 # ifdef HAVE_LINUX_CAPABILITIES
1120 * We may be running under non-root uid now, but we still hold full root privileges!
1121 * We drop all of them, except for the crucial one or two: cap_sys_time and
1122 * cap_net_bind_service if doing dynamic interface tracking.
1127 captext = (0 != interface_interval)
1128 ? "cap_sys_time,cap_net_bind_service=pe"
1129 : "cap_sys_time=pe";
1130 caps = cap_from_text(captext);
1133 "cap_from_text(%s) failed: %m",
1137 if (-1 == cap_set_proc(caps)) {
1139 "cap_set_proc() failed to drop root privs: %m");
1144 # endif /* HAVE_LINUX_CAPABILITIES */
1145 # ifdef HAVE_SOLARIS_PRIVS
1146 if (priv_delset(lowprivs, "proc_setid") == -1) {
1147 msyslog(LOG_ERR, "priv_delset() failed:%m");
1150 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1151 msyslog(LOG_ERR, "setppriv() failed:%m");
1154 priv_freeset(lowprivs);
1155 priv_freeset(highprivs);
1156 # endif /* HAVE_SOLARIS_PRIVS */
1157 root_dropped = TRUE;
1158 fork_deferred_worker();
1159 } /* if (droproot) */
1160 # endif /* HAVE_DROPROOT */
1162 /* libssecomp sandboxing */
1163 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1164 scmp_filter_ctx ctx;
1166 if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1167 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1169 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1178 SCMP_SYS(clock_gettime),
1179 SCMP_SYS(clock_settime),
1182 SCMP_SYS(exit_group),
1186 SCMP_SYS(getitimer),
1187 SCMP_SYS(getsockname),
1198 SCMP_SYS(rt_sigaction),
1199 SCMP_SYS(rt_sigprocmask),
1200 SCMP_SYS(rt_sigreturn),
1203 SCMP_SYS(setitimer),
1213 SCMP_SYS(_newselect),
1217 SCMP_SYS(clock_gettime),
1218 SCMP_SYS(clock_settime),
1220 SCMP_SYS(exit_group),
1223 SCMP_SYS(getitimer),
1232 SCMP_SYS(rt_sigaction),
1233 SCMP_SYS(rt_sigprocmask),
1235 SCMP_SYS(setitimer),
1237 SCMP_SYS(sigprocmask),
1238 SCMP_SYS(sigreturn),
1239 SCMP_SYS(socketcall),
1248 for (i = 0; i < COUNTOF(scmp_sc); i++) {
1249 if (seccomp_rule_add(ctx,
1250 SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1252 "%s: seccomp_rule_add() failed: %m",
1258 if (seccomp_load(ctx) < 0)
1259 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1262 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1264 #endif /* LIBSECCOMP and KERN_SECCOMP */
1266 # ifdef HAVE_IO_COMPLETION_PORT
1269 #if !defined(SIM) && defined(SIGDIE1)
1273 GetReceivedBuffers();
1274 # else /* normal I/O */
1276 BLOCK_IO_AND_ALARM();
1277 was_alarmed = FALSE;
1280 #if !defined(SIM) && defined(SIGDIE1)
1284 if (alarm_flag) { /* alarmed? */
1289 /* collect async name/addr results */
1291 harvest_blocking_responses();
1293 if (!was_alarmed && !has_full_recv_buffer()) {
1295 * Nothing to do. Wait for something.
1300 if (alarm_flag) { /* alarmed? */
1306 UNBLOCK_IO_AND_ALARM();
1308 * Out here, signals are unblocked. Call timer routine
1309 * to process expiry.
1312 was_alarmed = FALSE;
1313 BLOCK_IO_AND_ALARM();
1316 # endif /* !HAVE_IO_COMPLETION_PORT */
1318 # ifdef DEBUG_TIMING
1327 rbuf = get_full_recv_buffer();
1328 while (rbuf != NULL) {
1333 UNBLOCK_IO_AND_ALARM();
1336 /* avoid timer starvation during lengthy I/O handling */
1338 was_alarmed = FALSE;
1342 * Call the data procedure to handle each received
1345 if (rbuf->receiver != NULL) {
1346 # ifdef DEBUG_TIMING
1349 L_SUB(&dts, &rbuf->recv_time);
1350 DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1351 collect_timing(rbuf, "buffer processing delay", 1, &dts);
1354 (*rbuf->receiver)(rbuf);
1356 msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1360 BLOCK_IO_AND_ALARM();
1362 rbuf = get_full_recv_buffer();
1364 # ifdef DEBUG_TIMING
1368 collect_timing(NULL, "processing", bufcount, &tsb);
1369 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1378 # ifdef HAVE_DNSREGISTRATION
1379 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1380 mdnsreg = current_time;
1381 msyslog(LOG_INFO, "Attempting to register mDNS");
1382 if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1383 htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1385 msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1387 msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1390 msyslog(LOG_INFO, "mDNS service registered.");
1394 # endif /* HAVE_DNSREGISTRATION */
1397 UNBLOCK_IO_AND_ALARM();
1403 #if !defined(SIM) && defined(SIGDIE1)
1405 * finish - exit gracefully
1412 const char *sig_desc;
1415 #ifdef HAVE_STRSIGNAL
1416 sig_desc = strsignal(sig);
1418 if (sig_desc == NULL)
1420 msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1422 /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1423 # ifdef HAVE_DNSREGISTRATION
1425 DNSServiceRefDeallocate(mdns);
1440 #endif /* !SIM && SIGDIE1 */
1445 * wait_child_sync_if - implements parent side of -w/--wait-sync
1447 # ifdef HAVE_WORKING_FORK
1456 time_t wait_end_time;
1460 struct timeval wtimeout;
1465 /* waitsync_fd_to_close used solely by child */
1466 close(waitsync_fd_to_close);
1467 wait_end_time = time(NULL) + wait_sync;
1469 cur_time = time(NULL);
1470 wait_rem = (wait_end_time > cur_time)
1471 ? (wait_end_time - cur_time)
1473 wtimeout.tv_sec = wait_rem;
1474 wtimeout.tv_usec = 0;
1476 FD_SET(pipe_read_fd, &readset);
1477 rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1482 exit_code = (errno) ? errno : -1;
1484 "--wait-sync select failed: %m");
1489 * select() indicated a timeout, but in case
1490 * its timeouts are affected by a step of the
1491 * system clock, select() again with a zero
1492 * timeout to confirm.
1495 FD_SET(pipe_read_fd, &readset);
1496 wtimeout.tv_sec = 0;
1497 wtimeout.tv_usec = 0;
1498 rc = select(pipe_read_fd + 1, &readset, NULL,
1500 if (0 == rc) /* select() timeout */
1504 } else /* readable */
1506 } while (wait_rem > 0);
1508 fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1509 progname, wait_sync);
1512 # endif /* HAVE_WORKING_FORK */
1516 * assertion_failed - Redirect assertion failures to msyslog().
1522 isc_assertiontype_t type,
1526 isc_assertion_setcallback(NULL); /* Avoid recursion */
1528 msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1529 file, line, isc_assertion_typetotext(type), cond);
1530 msyslog(LOG_ERR, "exiting (due to assertion failure)");
1532 #if defined(DEBUG) && defined(SYS_WINNT)
1542 * library_fatal_error - Handle fatal errors from our libraries.
1545 library_fatal_error(
1554 isc_error_setfatal(NULL); /* Avoid recursion */
1556 msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1557 vsnprintf(errbuf, sizeof(errbuf), format, args);
1558 msyslog(LOG_ERR, "%s", errbuf);
1559 msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1561 #if defined(DEBUG) && defined(SYS_WINNT)
1571 * library_unexpected_error - Handle non fatal errors from our libraries.
1573 # define MAX_UNEXPECTED_ERRORS 100
1574 int unexpected_error_cnt = 0;
1576 library_unexpected_error(
1585 if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1586 return; /* avoid clutter in log */
1588 msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1589 vsnprintf(errbuf, sizeof(errbuf), format, args);
1590 msyslog(LOG_ERR, "%s", errbuf);
1592 if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1593 msyslog(LOG_ERR, "Too many errors. Shutting up.");
1598 #if !defined(SIM) && !defined(SYS_WINNT)
1602 * moredebug - increase debugging verbosity
1609 int saved_errno = errno;
1614 msyslog(LOG_DEBUG, "debug raised to %d", debug);
1616 errno = saved_errno;
1621 * lessdebug - decrease debugging verbosity
1628 int saved_errno = errno;
1633 msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1635 errno = saved_errno;
1638 # else /* !DEBUG follows */
1642 * no_debug - We don't do the debug here.
1649 int saved_errno = errno;
1651 msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1652 errno = saved_errno;
1654 # endif /* !DEBUG */
1655 #endif /* !SIM && !SYS_WINNT */