2 * ntpd.c - main program for the fixed point NTP daemon
9 #include "ntp_machine.h"
12 #include "ntp_stdlib.h"
13 #include <ntp_random.h>
15 #include "ntp_config.h"
16 #include "ntp_syslog.h"
17 #include "ntp_assert.h"
18 #include "isc/error.h"
19 #include "isc/strerror.h"
20 #include "isc/formatcheck.h"
27 #include "ntp_libopts.h"
28 #include "ntpd-opts.h"
30 /* there's a short treatise below what the thread stuff is for.
31 * [Bug 2954] enable the threading warm-up only for Linux.
33 #if defined(HAVE_PTHREADS) && HAVE_PTHREADS && !defined(NO_THREADS)
34 # ifdef HAVE_PTHREAD_H
38 # define NEED_PTHREAD_WARMUP
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
49 #ifdef HAVE_SYS_PARAM_H
50 # include <sys/param.h>
52 #ifdef HAVE_SYS_SIGNAL_H
53 # include <sys/signal.h>
57 #ifdef HAVE_SYS_IOCTL_H
58 # include <sys/ioctl.h>
59 #endif /* HAVE_SYS_IOCTL_H */
60 #if defined(HAVE_RTPRIO)
61 # ifdef HAVE_SYS_LOCK_H
62 # include <sys/lock.h>
64 # include <sys/rtprio.h>
67 # ifdef HAVE_SYS_LOCK_H
68 # include <sys/lock.h>
72 #if defined(HAVE_SCHED_SETSCHEDULER)
76 # ifdef HAVE_SYS_SCHED_H
77 # include <sys/sched.h>
81 #if defined(HAVE_SYS_MMAN_H)
82 # include <sys/mman.h>
90 # include <apollo/base.h>
91 #endif /* SYS_DOMAINOS */
95 #include "ntp_cmdargs.h"
97 #if 0 /* HMS: I don't think we need this. 961223 */
100 # include <sys/mman.h>
102 # include <sys/lock.h>
108 # include "ntservice.h"
116 # include <sys/ci/ciioctl.h>
123 #ifdef HAVE_LINUX_CAPABILITIES
124 # include <sys/capability.h>
125 # include <sys/prctl.h>
126 #endif /* HAVE_LINUX_CAPABILITIES */
127 #if defined(HAVE_PRIV_H) && defined(HAVE_SOLARIS_PRIVS)
129 #endif /* HAVE_PRIV_H */
130 #endif /* HAVE_DROPROOT */
132 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
133 /* # include <sys/types.h> */
134 # include <sys/resource.h>
135 # include <seccomp.h>
136 #endif /* LIBSECCOMP and KERN_SECCOMP */
138 #ifdef HAVE_DNSREGISTRATION
143 #ifdef HAVE_SETPGRP_0
144 # define ntp_setpgrp(x, y) setpgrp()
146 # define ntp_setpgrp(x, y) setpgrp(x, y)
149 #ifdef HAVE_SOLARIS_PRIVS
150 # define LOWPRIVS "basic,sys_time,net_privaddr,proc_setid,!proc_info,!proc_session,!proc_exec"
151 static priv_set_t *lowprivs = NULL;
152 static priv_set_t *highprivs = NULL;
153 #endif /* HAVE_SOLARIS_PRIVS */
155 * Scheduling priority we run at
157 #define NTPD_PRIO (-12)
159 int priority_done = 2; /* 0 - Set priority */
160 /* 1 - priority is OK where it is */
161 /* 2 - Don't set priority */
162 /* 1 and 2 are pretty much the same */
164 int listen_to_virtual_ips = TRUE;
167 * No-fork flag. If set, we do not become a background daemon.
169 int nofork; /* Fork by default */
171 #ifdef HAVE_DNSREGISTRATION
173 * mDNS registration flag. If set, we attempt to register with the mDNS system, but only
174 * after we have synched the first time. If the attempt fails, then try again once per
175 * minute for up to 5 times. After all, we may be starting before mDNS.
179 #endif /* HAVE_DNSREGISTRATION */
184 char *user; /* User to switch to */
185 char *group; /* group to switch to */
186 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");
529 #if !defined(SIM) && !defined(SYS_WINNT)
531 * Detach from terminal (much like daemon())
532 * Nothe that this function calls exit()
534 # ifdef HAVE_WORKING_FORK
536 detach_from_terminal(
539 const char *logfilename
544 # if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
553 exit_code = (errno) ? errno : -1;
554 msyslog(LOG_ERR, "fork: %m");
559 exit_code = wait_child_sync_if(pipe_fds[0],
566 * close all open files excepting waitsync_fd_to_close.
567 * msyslog() unreliable until after init_logging().
570 if (syslog_file != NULL) {
575 close_all_except(waitsync_fd_to_close);
576 INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
579 init_logging(progname, 0, TRUE);
580 /* we lost our logfile (if any) daemonizing */
581 setup_logfile(logfilename);
588 proc2_$who_am_i(&puid);
589 proc2_$make_server(&puid, &st);
591 # endif /* SYS_DOMAINOS */
593 if (setsid() == (pid_t)-1)
594 msyslog(LOG_ERR, "setsid(): %m");
595 # elif defined(HAVE_SETPGID)
596 if (setpgid(0, 0) == -1)
597 msyslog(LOG_ERR, "setpgid(): %m");
598 # else /* !HAVE_SETSID && !HAVE_SETPGID follows */
600 fid = open("/dev/tty", 2);
602 ioctl(fid, (u_long)TIOCNOTTY, NULL);
605 # endif /* TIOCNOTTY */
606 ntp_setpgrp(0, getpid());
607 # endif /* !HAVE_SETSID && !HAVE_SETPGID */
609 /* Don't get killed by low-on-memory signal. */
610 sa.sa_handler = catch_danger;
611 sigemptyset(&sa.sa_mask);
612 sa.sa_flags = SA_RESTART;
613 sigaction(SIGDANGER, &sa, NULL);
618 # endif /* HAVE_WORKING_FORK */
622 * Map user name/number to user ID
630 if (isdigit((unsigned char)*user)) {
631 sw_uid = (uid_t)strtoul(user, &endp, 0);
635 if ((pw = getpwuid(sw_uid)) != NULL) {
637 user = estrdup(pw->pw_name);
641 msyslog(LOG_ERR, "Cannot find user ID %s", user);
648 if ((pw = getpwnam(user)) != NULL) {
653 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
655 msyslog(LOG_ERR, "Cannot find user `%s'", user);
664 * Map group name/number to group ID
671 if (isdigit((unsigned char)*group)) {
672 sw_gid = (gid_t)strtoul(group, &endp, 0);
677 if ((gr = getgrnam(group)) != NULL) {
681 msyslog(LOG_ERR, "Cannot find group `%s'", group);
692 if (user && initgroups(user, sw_gid)) {
693 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
696 if (group && setgid(sw_gid)) {
697 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
700 if (group && setegid(sw_gid)) {
701 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
705 if (0 != setgroups(1, &sw_gid)) {
706 msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
711 if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
712 msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
721 if (user && setuid(sw_uid)) {
722 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
725 if (user && seteuid(sw_uid)) {
726 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
733 * Change (effective) user and group IDs, also initialize the supplementary group access list
735 int set_user_group_ids(void);
737 set_user_group_ids(void)
739 /* If the the user was already mapped, no need to map it again */
740 if ((NULL != user) && (0 == sw_uid)) {
744 /* same applies for the group */
745 if ((NULL != group) && (0 == sw_gid)) {
746 if (0 == map_group())
750 if (getegid() != sw_gid && 0 == set_group_ids())
752 if (geteuid() != sw_uid && 0 == set_user_ids())
757 #endif /* HAVE_DROPROOT */
761 * Main program. Initialize us, disconnect us from the tty if necessary,
762 * and loop waiting for I/O and/or timer expiries.
772 struct recvbuf *rbuf;
773 const char * logfilename;
777 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
780 # if defined(HAVE_WORKING_FORK)
785 # endif /* HAVE_WORKING_FORK*/
791 # ifdef NEED_PTHREAD_WARMUP
805 initializing = TRUE; /* mark that we are initializing */
806 parse_cmdline_opts(&argc, &argv);
808 debug = OPT_VALUE_SET_DEBUG_LEVEL;
809 # ifdef HAVE_SETLINEBUF
814 if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
818 || HAVE_OPT(SAVECONFIGQUIT))
821 init_logging(progname, NLOG_SYNCMASK, TRUE);
822 /* honor -l/--logfile option to log to a file */
823 if (HAVE_OPT(LOGFILE)) {
824 logfilename = OPT_ARG(LOGFILE);
826 change_logfile(logfilename, FALSE);
831 if (HAVE_OPT(SAVECONFIGQUIT))
834 msyslog(LOG_NOTICE, "%s: Starting", Version);
838 char buf[1024]; /* Secret knowledge of msyslog buf length */
841 /* Note that every arg has an initial space character */
842 snprintf(cp, sizeof(buf), "Command line:");
845 for (i = 0; i < saved_argc ; ++i) {
846 snprintf(cp, sizeof(buf) - (cp - buf),
847 " %s", saved_argv[i]);
850 msyslog(LOG_INFO, "%s", buf);
854 * Install trap handlers to log errors and assertion failures.
855 * Default handlers print to stderr which doesn't work if detached.
857 isc_assertion_setcallback(assertion_failed);
858 isc_error_setfatal(library_fatal_error);
859 isc_error_setunexpected(library_unexpected_error);
861 /* MPE lacks the concept of root */
862 # if defined(HAVE_GETUID) && !defined(MPE)
864 if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
867 "must be run as root, not uid %ld", (long)uid);
873 * Enable the Multi-Media Timer for Windows?
876 if (HAVE_OPT( MODIFYMMTIMER ))
877 set_mm_timer(MM_TIMER_HIRES);
880 #ifdef HAVE_DNSREGISTRATION
882 * Enable mDNS registrations?
884 if (HAVE_OPT( MDNS )) {
887 #endif /* HAVE_DNSREGISTRATION */
889 if (HAVE_OPT( NOVIRTUALIPS ))
890 listen_to_virtual_ips = 0;
893 * --interface, listen on specified interfaces
895 if (HAVE_OPT( INTERFACE )) {
896 int ifacect = STACKCT_OPT( INTERFACE );
897 const char** ifaces = STACKLST_OPT( INTERFACE );
900 while (ifacect-- > 0) {
902 is_ip_address(*ifaces, AF_UNSPEC, &addr)
905 *ifaces, -1, ACTION_LISTEN);
910 if (HAVE_OPT( NICE ))
913 # ifdef HAVE_SCHED_SETSCHEDULER
914 if (HAVE_OPT( PRIORITY )) {
915 config_priority = OPT_VALUE_PRIORITY;
916 config_priority_override = 1;
921 # ifdef HAVE_WORKING_FORK
922 /* make sure the FDs are initialised */
925 do { /* 'loop' once */
926 if (!HAVE_OPT( WAIT_SYNC ))
928 wait_sync = OPT_VALUE_WAIT_SYNC;
929 if (wait_sync <= 0) {
933 /* -w requires a fork() even with debug > 0 */
935 if (pipe(pipe_fds)) {
936 exit_code = (errno) ? errno : -1;
938 "Pipe creation failed for --wait-sync: %m");
941 waitsync_fd_to_close = pipe_fds[1];
942 } while (0); /* 'loop' once */
943 # endif /* HAVE_WORKING_FORK */
948 * Make sure the service is initialized before we do anything else
953 * Start interpolation thread, must occur before first
959 * Initialize random generator and public key pair
963 ntp_srandom((int)(now.l_i * now.l_uf));
966 * Detach us from the terminal. May need an #ifndef GIZMO.
970 # ifdef HAVE_WORKING_FORK
971 detach_from_terminal(pipe_fds, wait_sync, logfilename);
972 # endif /* HAVE_WORKING_FORK */
977 * SCO OpenServer's system clock offers much more precise timekeeping
978 * on the base CPU than the other CPUs (for multiprocessor systems),
979 * so we must lock to the base CPU.
981 fd = open("/dev/at1", O_RDONLY);
984 if (ioctl(fd, ACPU_LOCK, &zero) < 0)
985 msyslog(LOG_ERR, "cannot lock to base CPU: %m");
990 /* Setup stack size in preparation for locking pages in memory. */
991 # if defined(HAVE_MLOCKALL)
992 # ifdef HAVE_SETRLIMIT
993 ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
994 # ifdef RLIMIT_MEMLOCK
996 * The default RLIMIT_MEMLOCK is very low on Linux systems.
997 * Unless we increase this limit malloc calls are likely to
998 * fail if we drop root privilege. To be useful the value
999 * has to be larger than the largest ntpd resident set size.
1001 ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
1002 # endif /* RLIMIT_MEMLOCK */
1003 # endif /* HAVE_SETRLIMIT */
1004 # else /* !HAVE_MLOCKALL follows */
1009 * set the stack limit for AIX for plock().
1010 * see get_aix_stack() for more info.
1012 if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
1014 "Cannot adjust stack limit for plock: %m");
1016 # endif /* PROCLOCK */
1017 # endif /* HAVE_PLOCK */
1018 # endif /* !HAVE_MLOCKALL */
1021 * Set up signals we pay attention to locally.
1024 signal_no_reset(SIGDIE1, finish);
1025 signal_no_reset(SIGDIE2, finish);
1026 signal_no_reset(SIGDIE3, finish);
1027 signal_no_reset(SIGDIE4, finish);
1030 signal_no_reset(SIGBUS, finish);
1033 # if !defined(SYS_WINNT) && !defined(VMS)
1035 (void) signal_no_reset(MOREDEBUGSIG, moredebug);
1036 (void) signal_no_reset(LESSDEBUGSIG, lessdebug);
1038 (void) signal_no_reset(MOREDEBUGSIG, no_debug);
1039 (void) signal_no_reset(LESSDEBUGSIG, no_debug);
1041 # endif /* !SYS_WINNT && !VMS */
1044 * Set up signals we should never pay attention to.
1047 signal_no_reset(SIGPIPE, SIG_IGN);
1051 * Call the init_ routines to initialize the data structures.
1053 * Exactly what command-line options are we expecting here?
1067 set_process_priority();
1068 init_proto(); /* Call at high priority */
1071 mon_start(MON_ON); /* monitor on by default now */
1072 /* turn off in config if unwanted */
1075 * Get the configuration. This is done in a separate module
1076 * since this will definitely be different for the gizmo board.
1078 getconfig(argc, argv);
1080 if (-1 == cur_memlock) {
1081 # if defined(HAVE_MLOCKALL)
1083 * lock the process into memory
1085 if ( !HAVE_OPT(SAVECONFIGQUIT)
1086 # ifdef RLIMIT_MEMLOCK
1087 && -1 != DFLT_RLIMIT_MEMLOCK
1089 && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
1090 msyslog(LOG_ERR, "mlockall(): %m");
1091 # else /* !HAVE_MLOCKALL follows */
1095 * lock the process into memory
1097 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
1098 msyslog(LOG_ERR, "plock(PROCLOCK): %m");
1099 # else /* !PROCLOCK follows */
1102 * Lock text into ram
1104 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
1105 msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
1106 # else /* !TXTLOCK follows */
1107 msyslog(LOG_ERR, "plock() - don't know what to lock!");
1108 # endif /* !TXTLOCK */
1109 # endif /* !PROCLOCK */
1110 # endif /* HAVE_PLOCK */
1111 # endif /* !HAVE_MLOCKALL */
1114 loop_config(LOOP_DRIFTINIT, 0);
1115 report_event(EVNT_SYSRESTART, NULL, NULL);
1116 initializing = FALSE;
1118 # ifdef HAVE_DROPROOT
1121 #ifdef NEED_EARLY_FORK
1122 fork_nonchroot_worker();
1125 /* Drop super-user privileges and chroot now if the OS supports this */
1127 # ifdef HAVE_LINUX_CAPABILITIES
1128 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
1129 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
1130 msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
1133 # elif HAVE_SOLARIS_PRIVS
1134 /* Nothing to do here */
1136 /* we need a user to switch to */
1138 msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
1141 # endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
1144 if (0 == map_user())
1147 if (group != NULL) {
1148 if (0 == map_group())
1153 /* make sure cwd is inside the jail: */
1154 if (chdir(chrootdir)) {
1155 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
1158 if (chroot(chrootdir)) {
1159 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
1163 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
1167 # ifdef HAVE_SOLARIS_PRIVS
1168 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
1169 msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
1172 if ((highprivs = priv_allocset()) == NULL) {
1173 msyslog(LOG_ERR, "priv_allocset() failed:%m");
1176 (void) getppriv(PRIV_PERMITTED, highprivs);
1177 (void) priv_intersect(highprivs, lowprivs);
1178 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1179 msyslog(LOG_ERR, "setppriv() failed:%m");
1182 # endif /* HAVE_SOLARIS_PRIVS */
1183 if (0 == set_user_group_ids())
1186 # if !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1188 * for now assume that the privilege to bind to privileged ports
1189 * is associated with running with uid 0 - should be refined on
1190 * ports that allow binding to NTP_PORT with uid != 0
1192 disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */
1193 # endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1195 if (disable_dynamic_updates && interface_interval) {
1196 interface_interval = 0;
1197 msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1200 # ifdef HAVE_LINUX_CAPABILITIES
1203 * We may be running under non-root uid now, but we still hold full root privileges!
1204 * We drop all of them, except for the crucial one or two: cap_sys_time and
1205 * cap_net_bind_service if doing dynamic interface tracking.
1210 captext = (0 != interface_interval)
1211 ? "cap_sys_time,cap_net_bind_service=pe"
1212 : "cap_sys_time=pe";
1213 caps = cap_from_text(captext);
1216 "cap_from_text(%s) failed: %m",
1220 if (-1 == cap_set_proc(caps)) {
1222 "cap_set_proc() failed to drop root privs: %m");
1227 # endif /* HAVE_LINUX_CAPABILITIES */
1228 # ifdef HAVE_SOLARIS_PRIVS
1229 if (priv_delset(lowprivs, "proc_setid") == -1) {
1230 msyslog(LOG_ERR, "priv_delset() failed:%m");
1233 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1234 msyslog(LOG_ERR, "setppriv() failed:%m");
1237 priv_freeset(lowprivs);
1238 priv_freeset(highprivs);
1239 # endif /* HAVE_SOLARIS_PRIVS */
1240 root_dropped = TRUE;
1241 fork_deferred_worker();
1242 } /* if (droproot) */
1243 # endif /* HAVE_DROPROOT */
1245 /* libssecomp sandboxing */
1246 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1247 scmp_filter_ctx ctx;
1249 if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1250 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1252 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1261 SCMP_SYS(clock_gettime),
1262 SCMP_SYS(clock_settime),
1265 SCMP_SYS(exit_group),
1269 SCMP_SYS(getitimer),
1270 SCMP_SYS(getsockname),
1281 SCMP_SYS(rt_sigaction),
1282 SCMP_SYS(rt_sigprocmask),
1283 SCMP_SYS(rt_sigreturn),
1286 SCMP_SYS(setitimer),
1296 SCMP_SYS(_newselect),
1300 SCMP_SYS(clock_gettime),
1301 SCMP_SYS(clock_settime),
1303 SCMP_SYS(exit_group),
1306 SCMP_SYS(getitimer),
1315 SCMP_SYS(rt_sigaction),
1316 SCMP_SYS(rt_sigprocmask),
1318 SCMP_SYS(setitimer),
1320 SCMP_SYS(sigprocmask),
1321 SCMP_SYS(sigreturn),
1322 SCMP_SYS(socketcall),
1331 for (i = 0; i < COUNTOF(scmp_sc); i++) {
1332 if (seccomp_rule_add(ctx,
1333 SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1335 "%s: seccomp_rule_add() failed: %m",
1341 if (seccomp_load(ctx) < 0)
1342 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1345 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1347 #endif /* LIBSECCOMP and KERN_SECCOMP */
1353 # ifdef HAVE_IO_COMPLETION_PORT
1356 #if !defined(SIM) && defined(SIGDIE1)
1360 GetReceivedBuffers();
1361 # else /* normal I/O */
1363 BLOCK_IO_AND_ALARM();
1364 was_alarmed = FALSE;
1367 #if !defined(SIM) && defined(SIGDIE1)
1371 if (alarm_flag) { /* alarmed? */
1376 /* collect async name/addr results */
1378 harvest_blocking_responses();
1380 if (!was_alarmed && !has_full_recv_buffer()) {
1382 * Nothing to do. Wait for something.
1387 if (alarm_flag) { /* alarmed? */
1393 UNBLOCK_IO_AND_ALARM();
1395 * Out here, signals are unblocked. Call timer routine
1396 * to process expiry.
1399 was_alarmed = FALSE;
1400 BLOCK_IO_AND_ALARM();
1403 # endif /* !HAVE_IO_COMPLETION_PORT */
1405 # ifdef DEBUG_TIMING
1414 rbuf = get_full_recv_buffer();
1415 while (rbuf != NULL) {
1420 UNBLOCK_IO_AND_ALARM();
1423 /* avoid timer starvation during lengthy I/O handling */
1425 was_alarmed = FALSE;
1429 * Call the data procedure to handle each received
1432 if (rbuf->receiver != NULL) {
1433 # ifdef DEBUG_TIMING
1436 L_SUB(&dts, &rbuf->recv_time);
1437 DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1438 collect_timing(rbuf, "buffer processing delay", 1, &dts);
1441 (*rbuf->receiver)(rbuf);
1443 msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1447 BLOCK_IO_AND_ALARM();
1449 rbuf = get_full_recv_buffer();
1451 # ifdef DEBUG_TIMING
1455 collect_timing(NULL, "processing", bufcount, &tsb);
1456 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1465 # ifdef HAVE_DNSREGISTRATION
1466 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1467 mdnsreg = current_time;
1468 msyslog(LOG_INFO, "Attempting to register mDNS");
1469 if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1470 htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1472 msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1474 msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1477 msyslog(LOG_INFO, "mDNS service registered.");
1481 # endif /* HAVE_DNSREGISTRATION */
1484 UNBLOCK_IO_AND_ALARM();
1490 #if !defined(SIM) && defined(SIGDIE1)
1492 * finish - exit gracefully
1499 const char *sig_desc;
1502 #ifdef HAVE_STRSIGNAL
1503 sig_desc = strsignal(sig);
1505 if (sig_desc == NULL)
1507 msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1509 /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1510 # ifdef HAVE_DNSREGISTRATION
1512 DNSServiceRefDeallocate(mdns);
1527 #endif /* !SIM && SIGDIE1 */
1532 * wait_child_sync_if - implements parent side of -w/--wait-sync
1534 # ifdef HAVE_WORKING_FORK
1543 time_t wait_end_time;
1547 struct timeval wtimeout;
1552 /* waitsync_fd_to_close used solely by child */
1553 close(waitsync_fd_to_close);
1554 wait_end_time = time(NULL) + wait_sync;
1556 cur_time = time(NULL);
1557 wait_rem = (wait_end_time > cur_time)
1558 ? (wait_end_time - cur_time)
1560 wtimeout.tv_sec = wait_rem;
1561 wtimeout.tv_usec = 0;
1563 FD_SET(pipe_read_fd, &readset);
1564 rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1569 exit_code = (errno) ? errno : -1;
1571 "--wait-sync select failed: %m");
1576 * select() indicated a timeout, but in case
1577 * its timeouts are affected by a step of the
1578 * system clock, select() again with a zero
1579 * timeout to confirm.
1582 FD_SET(pipe_read_fd, &readset);
1583 wtimeout.tv_sec = 0;
1584 wtimeout.tv_usec = 0;
1585 rc = select(pipe_read_fd + 1, &readset, NULL,
1587 if (0 == rc) /* select() timeout */
1591 } else /* readable */
1593 } while (wait_rem > 0);
1595 fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1596 progname, wait_sync);
1599 # endif /* HAVE_WORKING_FORK */
1603 * assertion_failed - Redirect assertion failures to msyslog().
1609 isc_assertiontype_t type,
1613 isc_assertion_setcallback(NULL); /* Avoid recursion */
1615 msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1616 file, line, isc_assertion_typetotext(type), cond);
1617 msyslog(LOG_ERR, "exiting (due to assertion failure)");
1619 #if defined(DEBUG) && defined(SYS_WINNT)
1629 * library_fatal_error - Handle fatal errors from our libraries.
1632 library_fatal_error(
1641 isc_error_setfatal(NULL); /* Avoid recursion */
1643 msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1644 vsnprintf(errbuf, sizeof(errbuf), format, args);
1645 msyslog(LOG_ERR, "%s", errbuf);
1646 msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1648 #if defined(DEBUG) && defined(SYS_WINNT)
1658 * library_unexpected_error - Handle non fatal errors from our libraries.
1660 # define MAX_UNEXPECTED_ERRORS 100
1661 int unexpected_error_cnt = 0;
1663 library_unexpected_error(
1672 if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1673 return; /* avoid clutter in log */
1675 msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1676 vsnprintf(errbuf, sizeof(errbuf), format, args);
1677 msyslog(LOG_ERR, "%s", errbuf);
1679 if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1680 msyslog(LOG_ERR, "Too many errors. Shutting up.");
1685 #if !defined(SIM) && !defined(SYS_WINNT)
1689 * moredebug - increase debugging verbosity
1696 int saved_errno = errno;
1701 msyslog(LOG_DEBUG, "debug raised to %d", debug);
1703 errno = saved_errno;
1708 * lessdebug - decrease debugging verbosity
1715 int saved_errno = errno;
1720 msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1722 errno = saved_errno;
1725 # else /* !DEBUG follows */
1729 * no_debug - We don't do the debug here.
1736 int saved_errno = errno;
1738 msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1739 errno = saved_errno;
1741 # endif /* !DEBUG */
1742 #endif /* !SIM && !SYS_WINNT */