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 #if defined(HAVE_PTHREADS) && HAVE_PTHREADS && !defined(NO_THREADS)
32 # ifdef HAVE_PTHREAD_H
35 # define NEED_PTHREAD_WARMUP
41 #ifdef HAVE_SYS_STAT_H
42 # include <sys/stat.h>
45 #ifdef HAVE_SYS_PARAM_H
46 # include <sys/param.h>
48 #ifdef HAVE_SYS_SIGNAL_H
49 # include <sys/signal.h>
53 #ifdef HAVE_SYS_IOCTL_H
54 # include <sys/ioctl.h>
55 #endif /* HAVE_SYS_IOCTL_H */
56 #if defined(HAVE_RTPRIO)
57 # ifdef HAVE_SYS_LOCK_H
58 # include <sys/lock.h>
60 # include <sys/rtprio.h>
63 # ifdef HAVE_SYS_LOCK_H
64 # include <sys/lock.h>
68 #if defined(HAVE_SCHED_SETSCHEDULER)
72 # ifdef HAVE_SYS_SCHED_H
73 # include <sys/sched.h>
77 #if defined(HAVE_SYS_MMAN_H)
78 # include <sys/mman.h>
86 # include <apollo/base.h>
87 #endif /* SYS_DOMAINOS */
91 #include "ntp_cmdargs.h"
93 #if 0 /* HMS: I don't think we need this. 961223 */
96 # include <sys/mman.h>
98 # include <sys/lock.h>
108 # include <sys/ci/ciioctl.h>
115 #ifdef HAVE_LINUX_CAPABILITIES
116 # include <sys/capability.h>
117 # include <sys/prctl.h>
118 #endif /* HAVE_LINUX_CAPABILITIES */
119 #if defined(HAVE_PRIV_H) && defined(HAVE_SOLARIS_PRIVS)
121 #endif /* HAVE_PRIV_H */
122 #endif /* HAVE_DROPROOT */
124 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
125 /* # include <sys/types.h> */
126 # include <sys/resource.h>
127 # include <seccomp.h>
128 #endif /* LIBSECCOMP and KERN_SECCOMP */
130 #ifdef HAVE_DNSREGISTRATION
135 #ifdef HAVE_SETPGRP_0
136 # define ntp_setpgrp(x, y) setpgrp()
138 # define ntp_setpgrp(x, y) setpgrp(x, y)
141 #ifdef HAVE_SOLARIS_PRIVS
142 # define LOWPRIVS "basic,sys_time,net_privaddr,proc_setid,!proc_info,!proc_session,!proc_exec"
143 static priv_set_t *lowprivs = NULL;
144 static priv_set_t *highprivs = NULL;
145 #endif /* HAVE_SOLARIS_PRIVS */
147 * Scheduling priority we run at
149 #define NTPD_PRIO (-12)
151 int priority_done = 2; /* 0 - Set priority */
152 /* 1 - priority is OK where it is */
153 /* 2 - Don't set priority */
154 /* 1 and 2 are pretty much the same */
156 int listen_to_virtual_ips = TRUE;
159 * No-fork flag. If set, we do not become a background daemon.
161 int nofork; /* Fork by default */
163 #ifdef HAVE_DNSREGISTRATION
165 * mDNS registration flag. If set, we attempt to register with the mDNS system, but only
166 * after we have synched the first time. If the attempt fails, then try again once per
167 * minute for up to 5 times. After all, we may be starting before mDNS.
171 #endif /* HAVE_DNSREGISTRATION */
176 char *user; /* User to switch to */
177 char *group; /* group to switch to */
178 const char *chrootdir; /* directory to chroot to */
184 #endif /* HAVE_DROPROOT */
186 #ifdef HAVE_WORKING_FORK
187 int waitsync_fd_to_close = -1; /* -w/--wait-sync */
191 * Version declaration
193 extern const char *Version;
195 char const *progname;
201 * We put this here, since the argument profile is syscall-specific
203 extern int syscall (int, ...);
204 #endif /* DECL_SYSCALL */
207 #if !defined(SIM) && defined(SIGDIE1)
208 static RETSIGTYPE finish (int);
211 #if !defined(SIM) && defined(HAVE_WORKING_FORK)
212 static int wait_child_sync_if (int, long);
215 #if !defined(SIM) && !defined(SYS_WINNT)
217 static RETSIGTYPE moredebug (int);
218 static RETSIGTYPE lessdebug (int);
219 # else /* !DEBUG follows */
220 static RETSIGTYPE no_debug (int);
222 #endif /* !SIM && !SYS_WINNT */
228 int ntpdmain (int, char **);
229 static void set_process_priority (void);
230 static void assertion_failed (const char *, int,
233 __attribute__ ((__noreturn__));
234 static void library_fatal_error (const char *, int,
235 const char *, va_list)
236 ISC_FORMAT_PRINTF(3, 0);
237 static void library_unexpected_error(const char *, int,
238 const char *, va_list)
239 ISC_FORMAT_PRINTF(3, 0);
243 /* Bug2332 unearthed a problem in the interaction of reduced user
244 * privileges, the limits on memory usage and some versions of the
245 * pthread library on Linux systems. The 'pthread_cancel()' function and
246 * likely some others need to track the stack of the thread involved,
247 * and uses a function that comes from GCC (--> libgcc_s.so) to do
248 * this. Unfortunately the developers of glibc decided to load the
249 * library on demand, which speeds up program start but can cause
250 * trouble here: Due to all the things NTPD does to limit its resource
251 * usage, this deferred load of libgcc_s does not always work once the
252 * restrictions are in effect.
254 * One way out of this was attempting a forced link against libgcc_s
255 * when possible because it makes the library available immediately
256 * without deferred load. (The symbol resolution would still be dynamic
257 * and on demand, but the code would already be in the process image.)
259 * This is a tricky thing to do, since it's not necessary everywhere,
260 * not possible everywhere, has shown to break the build of other
261 * programs in the NTP suite and is now generally frowned upon.
263 * So we take a different approach here: We creat a worker thread that does
264 * actually nothing except waiting for cancellation and cancel it. If
265 * this is done before all the limitations are put in place, the
266 * machinery is pre-heated and all the runtime stuff should be in place
267 * and useable when needed.
269 * This uses only the standard pthread API and should work with all
270 * implementations of pthreads. It is not necessary everywhere, but it's
271 * cheap enough to go on nearly unnoticed.
273 #ifdef NEED_PTHREAD_WARMUP
275 /* simple thread function: sleep until cancelled, just to exercise
276 * thread cancellation.
279 my_pthread_warmup_worker(
288 /* pre-heat threading: create a thread and cancel it, just to exercise
289 * thread cancellation.
292 my_pthread_warmup(void)
297 &thread, NULL, my_pthread_warmup_worker, NULL);
299 pthread_cancel(thread);
300 pthread_join(thread, NULL);
304 #endif /*defined(NEED_PTHREAD_WARMUP)*/
317 optct = ntpOptionProcess(&ntpdOptions, *pargc, *pargv);
334 parse_cmdline_opts(&argc, &argv);
336 debug = OPT_VALUE_SET_DEBUG_LEVEL;
337 DPRINTF(1, ("%s\n", Version));
340 return ntpsim(argc, argv);
342 #else /* !SIM follows */
343 #ifdef NO_MAIN_ALLOWED
344 CALL(ntpd,"ntpd",ntpdmain);
345 #else /* !NO_MAIN_ALLOWED follows */
353 return ntpdmain(argc, argv);
355 #endif /* !SYS_WINNT */
356 #endif /* !NO_MAIN_ALLOWED */
361 * OK. AIX is different than solaris in how it implements plock().
362 * If you do NOT adjust the stack limit, you will get the MAXIMUM
363 * stack size allocated and PINNED with you program. To check the
364 * value, use ulimit -a.
366 * To fix this, we create an automatic variable and set our stack limit
367 * to that PLUS 32KB of extra space (we need some headroom).
369 * This subroutine gets the stack address.
371 * Grover Davidson and Matt Ladendorf
382 * Signal handler for SIGDANGER.
385 catch_danger(int signo)
387 msyslog(LOG_INFO, "ntpd: setpgid(): %m");
388 /* Make the system believe we'll free something, but don't do it! */
394 * Set the process priority
398 set_process_priority(void)
403 msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>",
405 ? "Leave priority alone"
406 : "Attempt to set priority"
411 # if defined(HAVE_SCHED_SETSCHEDULER)
412 if (!priority_done) {
413 extern int config_priority_override, config_priority;
415 struct sched_param sched;
417 pmax = sched_get_priority_max(SCHED_FIFO);
418 sched.sched_priority = pmax;
419 if ( config_priority_override ) {
420 pmin = sched_get_priority_min(SCHED_FIFO);
421 if ( config_priority > pmax )
422 sched.sched_priority = pmax;
423 else if ( config_priority < pmin )
424 sched.sched_priority = pmin;
426 sched.sched_priority = config_priority;
428 if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 )
429 msyslog(LOG_ERR, "sched_setscheduler(): %m");
433 # endif /* HAVE_SCHED_SETSCHEDULER */
436 if (!priority_done) {
439 srtp.type = RTP_PRIO_REALTIME; /* was: RTP_PRIO_NORMAL */
440 srtp.prio = 0; /* 0 (hi) -> RTP_PRIO_MAX (31,lo) */
442 if (rtprio(RTP_SET, getpid(), &srtp) < 0)
443 msyslog(LOG_ERR, "rtprio() error: %m");
447 # else /* !RTP_SET follows */
448 if (!priority_done) {
449 if (rtprio(0, 120) < 0)
450 msyslog(LOG_ERR, "rtprio() error: %m");
454 # endif /* !RTP_SET */
455 # endif /* HAVE_RTPRIO */
456 # if defined(NTPD_PRIO) && NTPD_PRIO != 0
457 # ifdef HAVE_ATT_NICE
458 if (!priority_done) {
460 if (-1 == nice (NTPD_PRIO) && errno != 0)
461 msyslog(LOG_ERR, "nice() error: %m");
465 # endif /* HAVE_ATT_NICE */
466 # ifdef HAVE_BSD_NICE
467 if (!priority_done) {
468 if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO))
469 msyslog(LOG_ERR, "setpriority() error: %m");
473 # endif /* HAVE_BSD_NICE */
474 # endif /* NTPD_PRIO && NTPD_PRIO != 0 */
476 msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority");
482 * Main program. Initialize us, disconnect us from the tty if necessary,
483 * and loop waiting for I/O and/or timer expiries.
493 struct recvbuf *rbuf;
494 const char * logfilename;
498 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
501 # if defined(HAVE_WORKING_FORK)
509 # if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
512 # endif /* HAVE_WORKING_FORK*/
518 # ifdef NEED_PTHREAD_WARMUP
532 initializing = TRUE; /* mark that we are initializing */
533 parse_cmdline_opts(&argc, &argv);
535 debug = OPT_VALUE_SET_DEBUG_LEVEL;
536 # ifdef HAVE_SETLINEBUF
541 if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
545 || HAVE_OPT(SAVECONFIGQUIT))
548 init_logging(progname, NLOG_SYNCMASK, TRUE);
549 /* honor -l/--logfile option to log to a file */
550 if (HAVE_OPT(LOGFILE)) {
551 logfilename = OPT_ARG(LOGFILE);
553 change_logfile(logfilename, FALSE);
558 if (HAVE_OPT(SAVECONFIGQUIT))
561 msyslog(LOG_NOTICE, "%s: Starting", Version);
565 char buf[1024]; /* Secret knowledge of msyslog buf length */
568 /* Note that every arg has an initial space character */
569 snprintf(cp, sizeof(buf), "Command line:");
572 for (i = 0; i < saved_argc ; ++i) {
573 snprintf(cp, sizeof(buf) - (cp - buf),
574 " %s", saved_argv[i]);
577 msyslog(LOG_INFO, "%s", buf);
581 * Install trap handlers to log errors and assertion failures.
582 * Default handlers print to stderr which doesn't work if detached.
584 isc_assertion_setcallback(assertion_failed);
585 isc_error_setfatal(library_fatal_error);
586 isc_error_setunexpected(library_unexpected_error);
588 /* MPE lacks the concept of root */
589 # if defined(HAVE_GETUID) && !defined(MPE)
591 if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
594 "must be run as root, not uid %ld", (long)uid);
600 * Enable the Multi-Media Timer for Windows?
603 if (HAVE_OPT( MODIFYMMTIMER ))
604 set_mm_timer(MM_TIMER_HIRES);
607 #ifdef HAVE_DNSREGISTRATION
609 * Enable mDNS registrations?
611 if (HAVE_OPT( MDNS )) {
614 #endif /* HAVE_DNSREGISTRATION */
616 if (HAVE_OPT( NOVIRTUALIPS ))
617 listen_to_virtual_ips = 0;
620 * --interface, listen on specified interfaces
622 if (HAVE_OPT( INTERFACE )) {
623 int ifacect = STACKCT_OPT( INTERFACE );
624 const char** ifaces = STACKLST_OPT( INTERFACE );
627 while (ifacect-- > 0) {
629 is_ip_address(*ifaces, AF_UNSPEC, &addr)
632 *ifaces, -1, ACTION_LISTEN);
637 if (HAVE_OPT( NICE ))
640 # ifdef HAVE_SCHED_SETSCHEDULER
641 if (HAVE_OPT( PRIORITY )) {
642 config_priority = OPT_VALUE_PRIORITY;
643 config_priority_override = 1;
648 # ifdef HAVE_WORKING_FORK
649 do { /* 'loop' once */
650 if (!HAVE_OPT( WAIT_SYNC ))
652 wait_sync = OPT_VALUE_WAIT_SYNC;
653 if (wait_sync <= 0) {
657 /* -w requires a fork() even with debug > 0 */
659 if (pipe(pipe_fds)) {
660 exit_code = (errno) ? errno : -1;
662 "Pipe creation failed for --wait-sync: %m");
665 waitsync_fd_to_close = pipe_fds[1];
666 } while (0); /* 'loop' once */
667 # endif /* HAVE_WORKING_FORK */
672 * Start interpolation thread, must occur before first
678 * Initialize random generator and public key pair
682 ntp_srandom((int)(now.l_i * now.l_uf));
685 * Detach us from the terminal. May need an #ifndef GIZMO.
689 # ifdef HAVE_WORKING_FORK
692 exit_code = (errno) ? errno : -1;
693 msyslog(LOG_ERR, "fork: %m");
698 exit_code = wait_child_sync_if(pipe_fds[0],
705 * close all open files excepting waitsync_fd_to_close.
706 * msyslog() unreliable until after init_logging().
709 if (syslog_file != NULL) {
714 close_all_except(waitsync_fd_to_close);
715 INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
718 init_logging(progname, 0, TRUE);
719 /* we lost our logfile (if any) daemonizing */
720 setup_logfile(logfilename);
727 proc2_$who_am_i(&puid);
728 proc2_$make_server(&puid, &st);
730 # endif /* SYS_DOMAINOS */
732 if (setsid() == (pid_t)-1)
733 msyslog(LOG_ERR, "setsid(): %m");
734 # elif defined(HAVE_SETPGID)
735 if (setpgid(0, 0) == -1)
736 msyslog(LOG_ERR, "setpgid(): %m");
737 # else /* !HAVE_SETSID && !HAVE_SETPGID follows */
739 fid = open("/dev/tty", 2);
741 ioctl(fid, (u_long)TIOCNOTTY, NULL);
744 # endif /* TIOCNOTTY */
745 ntp_setpgrp(0, getpid());
746 # endif /* !HAVE_SETSID && !HAVE_SETPGID */
748 /* Don't get killed by low-on-memory signal. */
749 sa.sa_handler = catch_danger;
750 sigemptyset(&sa.sa_mask);
751 sa.sa_flags = SA_RESTART;
752 sigaction(SIGDANGER, &sa, NULL);
754 # endif /* HAVE_WORKING_FORK */
759 * SCO OpenServer's system clock offers much more precise timekeeping
760 * on the base CPU than the other CPUs (for multiprocessor systems),
761 * so we must lock to the base CPU.
763 fd = open("/dev/at1", O_RDONLY);
766 if (ioctl(fd, ACPU_LOCK, &zero) < 0)
767 msyslog(LOG_ERR, "cannot lock to base CPU: %m");
772 /* Setup stack size in preparation for locking pages in memory. */
773 # if defined(HAVE_MLOCKALL)
774 # ifdef HAVE_SETRLIMIT
775 ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
776 # ifdef RLIMIT_MEMLOCK
778 * The default RLIMIT_MEMLOCK is very low on Linux systems.
779 * Unless we increase this limit malloc calls are likely to
780 * fail if we drop root privilege. To be useful the value
781 * has to be larger than the largest ntpd resident set size.
783 ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
784 # endif /* RLIMIT_MEMLOCK */
785 # endif /* HAVE_SETRLIMIT */
786 # else /* !HAVE_MLOCKALL follows */
791 * set the stack limit for AIX for plock().
792 * see get_aix_stack() for more info.
794 if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
796 "Cannot adjust stack limit for plock: %m");
798 # endif /* PROCLOCK */
799 # endif /* HAVE_PLOCK */
800 # endif /* !HAVE_MLOCKALL */
803 * Set up signals we pay attention to locally.
806 signal_no_reset(SIGDIE1, finish);
807 signal_no_reset(SIGDIE2, finish);
808 signal_no_reset(SIGDIE3, finish);
809 signal_no_reset(SIGDIE4, finish);
812 signal_no_reset(SIGBUS, finish);
815 # if !defined(SYS_WINNT) && !defined(VMS)
817 (void) signal_no_reset(MOREDEBUGSIG, moredebug);
818 (void) signal_no_reset(LESSDEBUGSIG, lessdebug);
820 (void) signal_no_reset(MOREDEBUGSIG, no_debug);
821 (void) signal_no_reset(LESSDEBUGSIG, no_debug);
823 # endif /* !SYS_WINNT && !VMS */
826 * Set up signals we should never pay attention to.
829 signal_no_reset(SIGPIPE, SIG_IGN);
833 * Call the init_ routines to initialize the data structures.
835 * Exactly what command-line options are we expecting here?
849 set_process_priority();
850 init_proto(); /* Call at high priority */
853 mon_start(MON_ON); /* monitor on by default now */
854 /* turn off in config if unwanted */
857 * Get the configuration. This is done in a separate module
858 * since this will definitely be different for the gizmo board.
860 getconfig(argc, argv);
862 if (-1 == cur_memlock) {
863 # if defined(HAVE_MLOCKALL)
865 * lock the process into memory
867 if ( !HAVE_OPT(SAVECONFIGQUIT)
868 # ifdef RLIMIT_MEMLOCK
869 && -1 != DFLT_RLIMIT_MEMLOCK
871 && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
872 msyslog(LOG_ERR, "mlockall(): %m");
873 # else /* !HAVE_MLOCKALL follows */
877 * lock the process into memory
879 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
880 msyslog(LOG_ERR, "plock(PROCLOCK): %m");
881 # else /* !PROCLOCK follows */
886 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
887 msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
888 # else /* !TXTLOCK follows */
889 msyslog(LOG_ERR, "plock() - don't know what to lock!");
890 # endif /* !TXTLOCK */
891 # endif /* !PROCLOCK */
892 # endif /* HAVE_PLOCK */
893 # endif /* !HAVE_MLOCKALL */
896 loop_config(LOOP_DRIFTINIT, 0);
897 report_event(EVNT_SYSRESTART, NULL, NULL);
898 initializing = FALSE;
900 # ifdef HAVE_DROPROOT
902 /* Drop super-user privileges and chroot now if the OS supports this */
904 # ifdef HAVE_LINUX_CAPABILITIES
905 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
906 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
907 msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
910 # elif HAVE_SOLARIS_PRIVS
911 /* Nothing to do here */
913 /* we need a user to switch to */
915 msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
918 # endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
921 if (isdigit((unsigned char)*user)) {
922 sw_uid = (uid_t)strtoul(user, &endp, 0);
926 if ((pw = getpwuid(sw_uid)) != NULL) {
928 user = estrdup(pw->pw_name);
932 msyslog(LOG_ERR, "Cannot find user ID %s", user);
939 if ((pw = getpwnam(user)) != NULL) {
944 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
946 msyslog(LOG_ERR, "Cannot find user `%s'", user);
952 if (isdigit((unsigned char)*group)) {
953 sw_gid = (gid_t)strtoul(group, &endp, 0);
958 if ((gr = getgrnam(group)) != NULL) {
962 msyslog(LOG_ERR, "Cannot find group `%s'", group);
969 /* make sure cwd is inside the jail: */
970 if (chdir(chrootdir)) {
971 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
974 if (chroot(chrootdir)) {
975 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
979 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
983 # ifdef HAVE_SOLARIS_PRIVS
984 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
985 msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
988 if ((highprivs = priv_allocset()) == NULL) {
989 msyslog(LOG_ERR, "priv_allocset() failed:%m");
992 (void) getppriv(PRIV_PERMITTED, highprivs);
993 (void) priv_intersect(highprivs, lowprivs);
994 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
995 msyslog(LOG_ERR, "setppriv() failed:%m");
998 # endif /* HAVE_SOLARIS_PRIVS */
999 if (user && initgroups(user, sw_gid)) {
1000 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
1003 if (group && setgid(sw_gid)) {
1004 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
1007 if (group && setegid(sw_gid)) {
1008 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
1012 if (0 != setgroups(1, &sw_gid)) {
1013 msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
1018 if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
1019 msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
1022 if (user && setuid(sw_uid)) {
1023 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
1026 if (user && seteuid(sw_uid)) {
1027 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
1031 # if !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1033 * for now assume that the privilege to bind to privileged ports
1034 * is associated with running with uid 0 - should be refined on
1035 * ports that allow binding to NTP_PORT with uid != 0
1037 disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */
1038 # endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1040 if (disable_dynamic_updates && interface_interval) {
1041 interface_interval = 0;
1042 msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1045 # ifdef HAVE_LINUX_CAPABILITIES
1048 * We may be running under non-root uid now, but we still hold full root privileges!
1049 * We drop all of them, except for the crucial one or two: cap_sys_time and
1050 * cap_net_bind_service if doing dynamic interface tracking.
1055 captext = (0 != interface_interval)
1056 ? "cap_sys_time,cap_net_bind_service=pe"
1057 : "cap_sys_time=pe";
1058 caps = cap_from_text(captext);
1061 "cap_from_text(%s) failed: %m",
1065 if (-1 == cap_set_proc(caps)) {
1067 "cap_set_proc() failed to drop root privs: %m");
1072 # endif /* HAVE_LINUX_CAPABILITIES */
1073 # ifdef HAVE_SOLARIS_PRIVS
1074 if (priv_delset(lowprivs, "proc_setid") == -1) {
1075 msyslog(LOG_ERR, "priv_delset() failed:%m");
1078 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1079 msyslog(LOG_ERR, "setppriv() failed:%m");
1082 priv_freeset(lowprivs);
1083 priv_freeset(highprivs);
1084 # endif /* HAVE_SOLARIS_PRIVS */
1085 root_dropped = TRUE;
1086 fork_deferred_worker();
1087 } /* if (droproot) */
1088 # endif /* HAVE_DROPROOT */
1090 /* libssecomp sandboxing */
1091 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1092 scmp_filter_ctx ctx;
1094 if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1095 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1097 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1106 SCMP_SYS(clock_gettime),
1107 SCMP_SYS(clock_settime),
1110 SCMP_SYS(exit_group),
1114 SCMP_SYS(getitimer),
1115 SCMP_SYS(getsockname),
1126 SCMP_SYS(rt_sigaction),
1127 SCMP_SYS(rt_sigprocmask),
1128 SCMP_SYS(rt_sigreturn),
1131 SCMP_SYS(setitimer),
1141 SCMP_SYS(_newselect),
1145 SCMP_SYS(clock_gettime),
1146 SCMP_SYS(clock_settime),
1148 SCMP_SYS(exit_group),
1151 SCMP_SYS(getitimer),
1160 SCMP_SYS(rt_sigaction),
1161 SCMP_SYS(rt_sigprocmask),
1163 SCMP_SYS(setitimer),
1165 SCMP_SYS(sigprocmask),
1166 SCMP_SYS(sigreturn),
1167 SCMP_SYS(socketcall),
1176 for (i = 0; i < COUNTOF(scmp_sc); i++) {
1177 if (seccomp_rule_add(ctx,
1178 SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1180 "%s: seccomp_rule_add() failed: %m",
1186 if (seccomp_load(ctx) < 0)
1187 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1190 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1192 #endif /* LIBSECCOMP and KERN_SECCOMP */
1194 # ifdef HAVE_IO_COMPLETION_PORT
1197 GetReceivedBuffers();
1198 # else /* normal I/O */
1200 BLOCK_IO_AND_ALARM();
1201 was_alarmed = FALSE;
1204 if (alarm_flag) { /* alarmed? */
1209 if (!was_alarmed && !has_full_recv_buffer()) {
1211 * Nothing to do. Wait for something.
1216 if (alarm_flag) { /* alarmed? */
1222 UNBLOCK_IO_AND_ALARM();
1224 * Out here, signals are unblocked. Call timer routine
1225 * to process expiry.
1228 was_alarmed = FALSE;
1229 BLOCK_IO_AND_ALARM();
1232 # endif /* !HAVE_IO_COMPLETION_PORT */
1234 # ifdef DEBUG_TIMING
1243 rbuf = get_full_recv_buffer();
1244 while (rbuf != NULL) {
1249 UNBLOCK_IO_AND_ALARM();
1252 /* avoid timer starvation during lengthy I/O handling */
1254 was_alarmed = FALSE;
1258 * Call the data procedure to handle each received
1261 if (rbuf->receiver != NULL) {
1262 # ifdef DEBUG_TIMING
1265 L_SUB(&dts, &rbuf->recv_time);
1266 DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1267 collect_timing(rbuf, "buffer processing delay", 1, &dts);
1270 (*rbuf->receiver)(rbuf);
1272 msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1276 BLOCK_IO_AND_ALARM();
1278 rbuf = get_full_recv_buffer();
1280 # ifdef DEBUG_TIMING
1284 collect_timing(NULL, "processing", bufcount, &tsb);
1285 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1294 # ifdef HAVE_DNSREGISTRATION
1295 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1296 mdnsreg = current_time;
1297 msyslog(LOG_INFO, "Attempting to register mDNS");
1298 if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1299 htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1301 msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1303 msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1306 msyslog(LOG_INFO, "mDNS service registered.");
1310 # endif /* HAVE_DNSREGISTRATION */
1313 UNBLOCK_IO_AND_ALARM();
1319 #if !defined(SIM) && defined(SIGDIE1)
1321 * finish - exit gracefully
1328 const char *sig_desc;
1331 #ifdef HAVE_STRSIGNAL
1332 sig_desc = strsignal(sig);
1334 if (sig_desc == NULL)
1336 msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1338 /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1339 # ifdef HAVE_DNSREGISTRATION
1341 DNSServiceRefDeallocate(mdns);
1346 #endif /* !SIM && SIGDIE1 */
1351 * wait_child_sync_if - implements parent side of -w/--wait-sync
1353 # ifdef HAVE_WORKING_FORK
1362 time_t wait_end_time;
1366 struct timeval wtimeout;
1371 /* waitsync_fd_to_close used solely by child */
1372 close(waitsync_fd_to_close);
1373 wait_end_time = time(NULL) + wait_sync;
1375 cur_time = time(NULL);
1376 wait_rem = (wait_end_time > cur_time)
1377 ? (wait_end_time - cur_time)
1379 wtimeout.tv_sec = wait_rem;
1380 wtimeout.tv_usec = 0;
1382 FD_SET(pipe_read_fd, &readset);
1383 rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1388 exit_code = (errno) ? errno : -1;
1390 "--wait-sync select failed: %m");
1395 * select() indicated a timeout, but in case
1396 * its timeouts are affected by a step of the
1397 * system clock, select() again with a zero
1398 * timeout to confirm.
1401 FD_SET(pipe_read_fd, &readset);
1402 wtimeout.tv_sec = 0;
1403 wtimeout.tv_usec = 0;
1404 rc = select(pipe_read_fd + 1, &readset, NULL,
1406 if (0 == rc) /* select() timeout */
1410 } else /* readable */
1412 } while (wait_rem > 0);
1414 fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1415 progname, wait_sync);
1418 # endif /* HAVE_WORKING_FORK */
1422 * assertion_failed - Redirect assertion failures to msyslog().
1428 isc_assertiontype_t type,
1432 isc_assertion_setcallback(NULL); /* Avoid recursion */
1434 msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1435 file, line, isc_assertion_typetotext(type), cond);
1436 msyslog(LOG_ERR, "exiting (due to assertion failure)");
1438 #if defined(DEBUG) && defined(SYS_WINNT)
1448 * library_fatal_error - Handle fatal errors from our libraries.
1451 library_fatal_error(
1460 isc_error_setfatal(NULL); /* Avoid recursion */
1462 msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1463 vsnprintf(errbuf, sizeof(errbuf), format, args);
1464 msyslog(LOG_ERR, "%s", errbuf);
1465 msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1467 #if defined(DEBUG) && defined(SYS_WINNT)
1477 * library_unexpected_error - Handle non fatal errors from our libraries.
1479 # define MAX_UNEXPECTED_ERRORS 100
1480 int unexpected_error_cnt = 0;
1482 library_unexpected_error(
1491 if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1492 return; /* avoid clutter in log */
1494 msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1495 vsnprintf(errbuf, sizeof(errbuf), format, args);
1496 msyslog(LOG_ERR, "%s", errbuf);
1498 if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1499 msyslog(LOG_ERR, "Too many errors. Shutting up.");
1504 #if !defined(SIM) && !defined(SYS_WINNT)
1508 * moredebug - increase debugging verbosity
1515 int saved_errno = errno;
1520 msyslog(LOG_DEBUG, "debug raised to %d", debug);
1522 errno = saved_errno;
1527 * lessdebug - decrease debugging verbosity
1534 int saved_errno = errno;
1539 msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1541 errno = saved_errno;
1544 # else /* !DEBUG follows */
1548 * no_debug - We don't do the debug here.
1555 int saved_errno = errno;
1557 msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1558 errno = saved_errno;
1560 # endif /* !DEBUG */
1561 #endif /* !SIM && !SYS_WINNT */