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()
535 detach_from_terminal(
538 const char *logfilename
543 # if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
552 exit_code = (errno) ? errno : -1;
553 msyslog(LOG_ERR, "fork: %m");
558 exit_code = wait_child_sync_if(pipe_fds[0],
565 * close all open files excepting waitsync_fd_to_close.
566 * msyslog() unreliable until after init_logging().
569 if (syslog_file != NULL) {
574 close_all_except(waitsync_fd_to_close);
575 INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
578 init_logging(progname, 0, TRUE);
579 /* we lost our logfile (if any) daemonizing */
580 setup_logfile(logfilename);
587 proc2_$who_am_i(&puid);
588 proc2_$make_server(&puid, &st);
590 # endif /* SYS_DOMAINOS */
592 if (setsid() == (pid_t)-1)
593 msyslog(LOG_ERR, "setsid(): %m");
594 # elif defined(HAVE_SETPGID)
595 if (setpgid(0, 0) == -1)
596 msyslog(LOG_ERR, "setpgid(): %m");
597 # else /* !HAVE_SETSID && !HAVE_SETPGID follows */
599 fid = open("/dev/tty", 2);
601 ioctl(fid, (u_long)TIOCNOTTY, NULL);
604 # endif /* TIOCNOTTY */
605 ntp_setpgrp(0, getpid());
606 # endif /* !HAVE_SETSID && !HAVE_SETPGID */
608 /* Don't get killed by low-on-memory signal. */
609 sa.sa_handler = catch_danger;
610 sigemptyset(&sa.sa_mask);
611 sa.sa_flags = SA_RESTART;
612 sigaction(SIGDANGER, &sa, NULL);
620 * Map user name/number to user ID
628 if (isdigit((unsigned char)*user)) {
629 sw_uid = (uid_t)strtoul(user, &endp, 0);
633 if ((pw = getpwuid(sw_uid)) != NULL) {
635 user = estrdup(pw->pw_name);
639 msyslog(LOG_ERR, "Cannot find user ID %s", user);
646 if ((pw = getpwnam(user)) != NULL) {
651 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
653 msyslog(LOG_ERR, "Cannot find user `%s'", user);
662 * Map group name/number to group ID
670 if (isdigit((unsigned char)*group)) {
671 sw_gid = (gid_t)strtoul(group, &endp, 0);
676 if ((gr = getgrnam(group)) != NULL) {
680 msyslog(LOG_ERR, "Cannot find group `%s'", group);
689 * Change (effective) user and group IDs, also initialize the supplementary group access list
695 /* If the the user was already mapped, no need to map it again */
696 if ((NULL != user) && (0 == sw_uid)) {
700 /* same applies for the group */
701 if ((NULL != group) && (0 == sw_gid)) {
702 if (0 == map_group())
706 if (user && initgroups(user, sw_gid)) {
707 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
710 if (group && setgid(sw_gid)) {
711 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
714 if (group && setegid(sw_gid)) {
715 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
719 if (0 != setgroups(1, &sw_gid)) {
720 msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
725 if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
726 msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
729 if (user && setuid(sw_uid)) {
730 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
733 if (user && seteuid(sw_uid)) {
734 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
740 #endif /* HAVE_DROPROOT */
744 * Main program. Initialize us, disconnect us from the tty if necessary,
745 * and loop waiting for I/O and/or timer expiries.
755 struct recvbuf *rbuf;
756 const char * logfilename;
760 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
763 # if defined(HAVE_WORKING_FORK)
768 # endif /* HAVE_WORKING_FORK*/
774 # ifdef NEED_PTHREAD_WARMUP
788 initializing = TRUE; /* mark that we are initializing */
789 parse_cmdline_opts(&argc, &argv);
791 debug = OPT_VALUE_SET_DEBUG_LEVEL;
792 # ifdef HAVE_SETLINEBUF
797 if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
801 || HAVE_OPT(SAVECONFIGQUIT))
804 init_logging(progname, NLOG_SYNCMASK, TRUE);
805 /* honor -l/--logfile option to log to a file */
806 if (HAVE_OPT(LOGFILE)) {
807 logfilename = OPT_ARG(LOGFILE);
809 change_logfile(logfilename, FALSE);
814 if (HAVE_OPT(SAVECONFIGQUIT))
817 msyslog(LOG_NOTICE, "%s: Starting", Version);
821 char buf[1024]; /* Secret knowledge of msyslog buf length */
824 /* Note that every arg has an initial space character */
825 snprintf(cp, sizeof(buf), "Command line:");
828 for (i = 0; i < saved_argc ; ++i) {
829 snprintf(cp, sizeof(buf) - (cp - buf),
830 " %s", saved_argv[i]);
833 msyslog(LOG_INFO, "%s", buf);
837 * Install trap handlers to log errors and assertion failures.
838 * Default handlers print to stderr which doesn't work if detached.
840 isc_assertion_setcallback(assertion_failed);
841 isc_error_setfatal(library_fatal_error);
842 isc_error_setunexpected(library_unexpected_error);
844 /* MPE lacks the concept of root */
845 # if defined(HAVE_GETUID) && !defined(MPE)
847 if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
850 "must be run as root, not uid %ld", (long)uid);
856 * Enable the Multi-Media Timer for Windows?
859 if (HAVE_OPT( MODIFYMMTIMER ))
860 set_mm_timer(MM_TIMER_HIRES);
863 #ifdef HAVE_DNSREGISTRATION
865 * Enable mDNS registrations?
867 if (HAVE_OPT( MDNS )) {
870 #endif /* HAVE_DNSREGISTRATION */
872 if (HAVE_OPT( NOVIRTUALIPS ))
873 listen_to_virtual_ips = 0;
876 * --interface, listen on specified interfaces
878 if (HAVE_OPT( INTERFACE )) {
879 int ifacect = STACKCT_OPT( INTERFACE );
880 const char** ifaces = STACKLST_OPT( INTERFACE );
883 while (ifacect-- > 0) {
885 is_ip_address(*ifaces, AF_UNSPEC, &addr)
888 *ifaces, -1, ACTION_LISTEN);
893 if (HAVE_OPT( NICE ))
896 # ifdef HAVE_SCHED_SETSCHEDULER
897 if (HAVE_OPT( PRIORITY )) {
898 config_priority = OPT_VALUE_PRIORITY;
899 config_priority_override = 1;
904 # ifdef HAVE_WORKING_FORK
905 /* make sure the FDs are initialised */
908 do { /* 'loop' once */
909 if (!HAVE_OPT( WAIT_SYNC ))
911 wait_sync = OPT_VALUE_WAIT_SYNC;
912 if (wait_sync <= 0) {
916 /* -w requires a fork() even with debug > 0 */
918 if (pipe(pipe_fds)) {
919 exit_code = (errno) ? errno : -1;
921 "Pipe creation failed for --wait-sync: %m");
924 waitsync_fd_to_close = pipe_fds[1];
925 } while (0); /* 'loop' once */
926 # endif /* HAVE_WORKING_FORK */
931 * Make sure the service is initialized before we do anything else
936 * Start interpolation thread, must occur before first
942 * Initialize random generator and public key pair
946 ntp_srandom((int)(now.l_i * now.l_uf));
949 * Detach us from the terminal. May need an #ifndef GIZMO.
953 # ifdef HAVE_WORKING_FORK
954 detach_from_terminal(pipe_fds, wait_sync, logfilename);
955 # endif /* HAVE_WORKING_FORK */
960 * SCO OpenServer's system clock offers much more precise timekeeping
961 * on the base CPU than the other CPUs (for multiprocessor systems),
962 * so we must lock to the base CPU.
964 fd = open("/dev/at1", O_RDONLY);
967 if (ioctl(fd, ACPU_LOCK, &zero) < 0)
968 msyslog(LOG_ERR, "cannot lock to base CPU: %m");
973 /* Setup stack size in preparation for locking pages in memory. */
974 # if defined(HAVE_MLOCKALL)
975 # ifdef HAVE_SETRLIMIT
976 ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
977 # ifdef RLIMIT_MEMLOCK
979 * The default RLIMIT_MEMLOCK is very low on Linux systems.
980 * Unless we increase this limit malloc calls are likely to
981 * fail if we drop root privilege. To be useful the value
982 * has to be larger than the largest ntpd resident set size.
984 ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
985 # endif /* RLIMIT_MEMLOCK */
986 # endif /* HAVE_SETRLIMIT */
987 # else /* !HAVE_MLOCKALL follows */
992 * set the stack limit for AIX for plock().
993 * see get_aix_stack() for more info.
995 if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
997 "Cannot adjust stack limit for plock: %m");
999 # endif /* PROCLOCK */
1000 # endif /* HAVE_PLOCK */
1001 # endif /* !HAVE_MLOCKALL */
1004 * Set up signals we pay attention to locally.
1007 signal_no_reset(SIGDIE1, finish);
1008 signal_no_reset(SIGDIE2, finish);
1009 signal_no_reset(SIGDIE3, finish);
1010 signal_no_reset(SIGDIE4, finish);
1013 signal_no_reset(SIGBUS, finish);
1016 # if !defined(SYS_WINNT) && !defined(VMS)
1018 (void) signal_no_reset(MOREDEBUGSIG, moredebug);
1019 (void) signal_no_reset(LESSDEBUGSIG, lessdebug);
1021 (void) signal_no_reset(MOREDEBUGSIG, no_debug);
1022 (void) signal_no_reset(LESSDEBUGSIG, no_debug);
1024 # endif /* !SYS_WINNT && !VMS */
1027 * Set up signals we should never pay attention to.
1030 signal_no_reset(SIGPIPE, SIG_IGN);
1034 * Call the init_ routines to initialize the data structures.
1036 * Exactly what command-line options are we expecting here?
1050 set_process_priority();
1051 init_proto(); /* Call at high priority */
1054 mon_start(MON_ON); /* monitor on by default now */
1055 /* turn off in config if unwanted */
1058 * Get the configuration. This is done in a separate module
1059 * since this will definitely be different for the gizmo board.
1061 getconfig(argc, argv);
1063 if (-1 == cur_memlock) {
1064 # if defined(HAVE_MLOCKALL)
1066 * lock the process into memory
1068 if ( !HAVE_OPT(SAVECONFIGQUIT)
1069 # ifdef RLIMIT_MEMLOCK
1070 && -1 != DFLT_RLIMIT_MEMLOCK
1072 && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
1073 msyslog(LOG_ERR, "mlockall(): %m");
1074 # else /* !HAVE_MLOCKALL follows */
1078 * lock the process into memory
1080 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
1081 msyslog(LOG_ERR, "plock(PROCLOCK): %m");
1082 # else /* !PROCLOCK follows */
1085 * Lock text into ram
1087 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
1088 msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
1089 # else /* !TXTLOCK follows */
1090 msyslog(LOG_ERR, "plock() - don't know what to lock!");
1091 # endif /* !TXTLOCK */
1092 # endif /* !PROCLOCK */
1093 # endif /* HAVE_PLOCK */
1094 # endif /* !HAVE_MLOCKALL */
1097 loop_config(LOOP_DRIFTINIT, 0);
1098 report_event(EVNT_SYSRESTART, NULL, NULL);
1099 initializing = FALSE;
1101 # ifdef HAVE_DROPROOT
1104 #ifdef NEED_EARLY_FORK
1105 fork_nonchroot_worker();
1108 /* Drop super-user privileges and chroot now if the OS supports this */
1110 # ifdef HAVE_LINUX_CAPABILITIES
1111 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
1112 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
1113 msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
1116 # elif HAVE_SOLARIS_PRIVS
1117 /* Nothing to do here */
1119 /* we need a user to switch to */
1121 msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
1124 # endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
1127 if (0 == map_user())
1130 if (group != NULL) {
1131 if (0 == map_group())
1136 /* make sure cwd is inside the jail: */
1137 if (chdir(chrootdir)) {
1138 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
1141 if (chroot(chrootdir)) {
1142 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
1146 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
1150 # ifdef HAVE_SOLARIS_PRIVS
1151 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
1152 msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
1155 if ((highprivs = priv_allocset()) == NULL) {
1156 msyslog(LOG_ERR, "priv_allocset() failed:%m");
1159 (void) getppriv(PRIV_PERMITTED, highprivs);
1160 (void) priv_intersect(highprivs, lowprivs);
1161 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1162 msyslog(LOG_ERR, "setppriv() failed:%m");
1165 # endif /* HAVE_SOLARIS_PRIVS */
1166 if (0 == set_user_group_ids())
1169 # if !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1171 * for now assume that the privilege to bind to privileged ports
1172 * is associated with running with uid 0 - should be refined on
1173 * ports that allow binding to NTP_PORT with uid != 0
1175 disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */
1176 # endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1178 if (disable_dynamic_updates && interface_interval) {
1179 interface_interval = 0;
1180 msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1183 # ifdef HAVE_LINUX_CAPABILITIES
1186 * We may be running under non-root uid now, but we still hold full root privileges!
1187 * We drop all of them, except for the crucial one or two: cap_sys_time and
1188 * cap_net_bind_service if doing dynamic interface tracking.
1193 captext = (0 != interface_interval)
1194 ? "cap_sys_time,cap_net_bind_service=pe"
1195 : "cap_sys_time=pe";
1196 caps = cap_from_text(captext);
1199 "cap_from_text(%s) failed: %m",
1203 if (-1 == cap_set_proc(caps)) {
1205 "cap_set_proc() failed to drop root privs: %m");
1210 # endif /* HAVE_LINUX_CAPABILITIES */
1211 # ifdef HAVE_SOLARIS_PRIVS
1212 if (priv_delset(lowprivs, "proc_setid") == -1) {
1213 msyslog(LOG_ERR, "priv_delset() failed:%m");
1216 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1217 msyslog(LOG_ERR, "setppriv() failed:%m");
1220 priv_freeset(lowprivs);
1221 priv_freeset(highprivs);
1222 # endif /* HAVE_SOLARIS_PRIVS */
1223 root_dropped = TRUE;
1224 fork_deferred_worker();
1225 } /* if (droproot) */
1226 # endif /* HAVE_DROPROOT */
1228 /* libssecomp sandboxing */
1229 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1230 scmp_filter_ctx ctx;
1232 if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1233 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1235 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1244 SCMP_SYS(clock_gettime),
1245 SCMP_SYS(clock_settime),
1248 SCMP_SYS(exit_group),
1252 SCMP_SYS(getitimer),
1253 SCMP_SYS(getsockname),
1264 SCMP_SYS(rt_sigaction),
1265 SCMP_SYS(rt_sigprocmask),
1266 SCMP_SYS(rt_sigreturn),
1269 SCMP_SYS(setitimer),
1279 SCMP_SYS(_newselect),
1283 SCMP_SYS(clock_gettime),
1284 SCMP_SYS(clock_settime),
1286 SCMP_SYS(exit_group),
1289 SCMP_SYS(getitimer),
1298 SCMP_SYS(rt_sigaction),
1299 SCMP_SYS(rt_sigprocmask),
1301 SCMP_SYS(setitimer),
1303 SCMP_SYS(sigprocmask),
1304 SCMP_SYS(sigreturn),
1305 SCMP_SYS(socketcall),
1314 for (i = 0; i < COUNTOF(scmp_sc); i++) {
1315 if (seccomp_rule_add(ctx,
1316 SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1318 "%s: seccomp_rule_add() failed: %m",
1324 if (seccomp_load(ctx) < 0)
1325 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1328 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1330 #endif /* LIBSECCOMP and KERN_SECCOMP */
1336 # ifdef HAVE_IO_COMPLETION_PORT
1339 #if !defined(SIM) && defined(SIGDIE1)
1343 GetReceivedBuffers();
1344 # else /* normal I/O */
1346 BLOCK_IO_AND_ALARM();
1347 was_alarmed = FALSE;
1350 #if !defined(SIM) && defined(SIGDIE1)
1354 if (alarm_flag) { /* alarmed? */
1359 /* collect async name/addr results */
1361 harvest_blocking_responses();
1363 if (!was_alarmed && !has_full_recv_buffer()) {
1365 * Nothing to do. Wait for something.
1370 if (alarm_flag) { /* alarmed? */
1376 UNBLOCK_IO_AND_ALARM();
1378 * Out here, signals are unblocked. Call timer routine
1379 * to process expiry.
1382 was_alarmed = FALSE;
1383 BLOCK_IO_AND_ALARM();
1386 # endif /* !HAVE_IO_COMPLETION_PORT */
1388 # ifdef DEBUG_TIMING
1397 rbuf = get_full_recv_buffer();
1398 while (rbuf != NULL) {
1403 UNBLOCK_IO_AND_ALARM();
1406 /* avoid timer starvation during lengthy I/O handling */
1408 was_alarmed = FALSE;
1412 * Call the data procedure to handle each received
1415 if (rbuf->receiver != NULL) {
1416 # ifdef DEBUG_TIMING
1419 L_SUB(&dts, &rbuf->recv_time);
1420 DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1421 collect_timing(rbuf, "buffer processing delay", 1, &dts);
1424 (*rbuf->receiver)(rbuf);
1426 msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1430 BLOCK_IO_AND_ALARM();
1432 rbuf = get_full_recv_buffer();
1434 # ifdef DEBUG_TIMING
1438 collect_timing(NULL, "processing", bufcount, &tsb);
1439 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1448 # ifdef HAVE_DNSREGISTRATION
1449 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1450 mdnsreg = current_time;
1451 msyslog(LOG_INFO, "Attempting to register mDNS");
1452 if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1453 htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1455 msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1457 msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1460 msyslog(LOG_INFO, "mDNS service registered.");
1464 # endif /* HAVE_DNSREGISTRATION */
1467 UNBLOCK_IO_AND_ALARM();
1473 #if !defined(SIM) && defined(SIGDIE1)
1475 * finish - exit gracefully
1482 const char *sig_desc;
1485 #ifdef HAVE_STRSIGNAL
1486 sig_desc = strsignal(sig);
1488 if (sig_desc == NULL)
1490 msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1492 /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1493 # ifdef HAVE_DNSREGISTRATION
1495 DNSServiceRefDeallocate(mdns);
1510 #endif /* !SIM && SIGDIE1 */
1515 * wait_child_sync_if - implements parent side of -w/--wait-sync
1517 # ifdef HAVE_WORKING_FORK
1526 time_t wait_end_time;
1530 struct timeval wtimeout;
1535 /* waitsync_fd_to_close used solely by child */
1536 close(waitsync_fd_to_close);
1537 wait_end_time = time(NULL) + wait_sync;
1539 cur_time = time(NULL);
1540 wait_rem = (wait_end_time > cur_time)
1541 ? (wait_end_time - cur_time)
1543 wtimeout.tv_sec = wait_rem;
1544 wtimeout.tv_usec = 0;
1546 FD_SET(pipe_read_fd, &readset);
1547 rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1552 exit_code = (errno) ? errno : -1;
1554 "--wait-sync select failed: %m");
1559 * select() indicated a timeout, but in case
1560 * its timeouts are affected by a step of the
1561 * system clock, select() again with a zero
1562 * timeout to confirm.
1565 FD_SET(pipe_read_fd, &readset);
1566 wtimeout.tv_sec = 0;
1567 wtimeout.tv_usec = 0;
1568 rc = select(pipe_read_fd + 1, &readset, NULL,
1570 if (0 == rc) /* select() timeout */
1574 } else /* readable */
1576 } while (wait_rem > 0);
1578 fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1579 progname, wait_sync);
1582 # endif /* HAVE_WORKING_FORK */
1586 * assertion_failed - Redirect assertion failures to msyslog().
1592 isc_assertiontype_t type,
1596 isc_assertion_setcallback(NULL); /* Avoid recursion */
1598 msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1599 file, line, isc_assertion_typetotext(type), cond);
1600 msyslog(LOG_ERR, "exiting (due to assertion failure)");
1602 #if defined(DEBUG) && defined(SYS_WINNT)
1612 * library_fatal_error - Handle fatal errors from our libraries.
1615 library_fatal_error(
1624 isc_error_setfatal(NULL); /* Avoid recursion */
1626 msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1627 vsnprintf(errbuf, sizeof(errbuf), format, args);
1628 msyslog(LOG_ERR, "%s", errbuf);
1629 msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1631 #if defined(DEBUG) && defined(SYS_WINNT)
1641 * library_unexpected_error - Handle non fatal errors from our libraries.
1643 # define MAX_UNEXPECTED_ERRORS 100
1644 int unexpected_error_cnt = 0;
1646 library_unexpected_error(
1655 if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1656 return; /* avoid clutter in log */
1658 msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1659 vsnprintf(errbuf, sizeof(errbuf), format, args);
1660 msyslog(LOG_ERR, "%s", errbuf);
1662 if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1663 msyslog(LOG_ERR, "Too many errors. Shutting up.");
1668 #if !defined(SIM) && !defined(SYS_WINNT)
1672 * moredebug - increase debugging verbosity
1679 int saved_errno = errno;
1684 msyslog(LOG_DEBUG, "debug raised to %d", debug);
1686 errno = saved_errno;
1691 * lessdebug - decrease debugging verbosity
1698 int saved_errno = errno;
1703 msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1705 errno = saved_errno;
1708 # else /* !DEBUG follows */
1712 * no_debug - We don't do the debug here.
1719 int saved_errno = errno;
1721 msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1722 errno = saved_errno;
1724 # endif /* !DEBUG */
1725 #endif /* !SIM && !SYS_WINNT */