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 #if defined(HAVE_TRUSTEDBSD_MAC)
131 # include <sys/mac.h>
132 #endif /* HAVE_TRUSTEDBSD_MAC */
133 #endif /* HAVE_DROPROOT */
135 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
136 /* # include <sys/types.h> */
137 # include <sys/resource.h>
138 # include <seccomp.h>
139 #endif /* LIBSECCOMP and KERN_SECCOMP */
142 #include <sys/procctl.h>
143 #ifndef PROC_STACKGAP_CTL
145 * Even if we compile on an older system we can still run on a newer one.
147 #define PROC_STACKGAP_CTL 17
148 #define PROC_STACKGAP_DISABLE 0x0002
152 #ifdef HAVE_DNSREGISTRATION
157 #ifdef HAVE_SETPGRP_0
158 # define ntp_setpgrp(x, y) setpgrp()
160 # define ntp_setpgrp(x, y) setpgrp(x, y)
163 #ifdef HAVE_SOLARIS_PRIVS
164 # define LOWPRIVS "basic,sys_time,net_privaddr,proc_setid,!proc_info,!proc_session,!proc_exec"
165 static priv_set_t *lowprivs = NULL;
166 static priv_set_t *highprivs = NULL;
167 #endif /* HAVE_SOLARIS_PRIVS */
169 * Scheduling priority we run at
171 #define NTPD_PRIO (-12)
173 int priority_done = 2; /* 0 - Set priority */
174 /* 1 - priority is OK where it is */
175 /* 2 - Don't set priority */
176 /* 1 and 2 are pretty much the same */
178 int listen_to_virtual_ips = TRUE;
181 * No-fork flag. If set, we do not become a background daemon.
183 int nofork; /* Fork by default */
185 #ifdef HAVE_DNSREGISTRATION
187 * mDNS registration flag. If set, we attempt to register with the mDNS system, but only
188 * after we have synched the first time. If the attempt fails, then try again once per
189 * minute for up to 5 times. After all, we may be starting before mDNS.
193 #endif /* HAVE_DNSREGISTRATION */
198 char *user; /* User to switch to */
199 char *group; /* group to switch to */
200 const char *chrootdir; /* directory to chroot to */
205 #endif /* HAVE_DROPROOT */
207 #ifdef HAVE_WORKING_FORK
208 int waitsync_fd_to_close = -1; /* -w/--wait-sync */
212 * Version declaration
214 extern const char *Version;
216 char const *progname;
222 * We put this here, since the argument profile is syscall-specific
224 extern int syscall (int, ...);
225 #endif /* DECL_SYSCALL */
228 #if !defined(SIM) && defined(SIGDIE1)
229 static volatile int signalled = 0;
230 static volatile int signo = 0;
232 /* In an ideal world, 'finish_safe()' would declared as noreturn... */
233 static void finish_safe (int);
234 static RETSIGTYPE finish (int);
237 #if !defined(SIM) && defined(HAVE_WORKING_FORK)
238 static int wait_child_sync_if (int, long);
241 #if !defined(SIM) && !defined(SYS_WINNT)
243 static RETSIGTYPE moredebug (int);
244 static RETSIGTYPE lessdebug (int);
245 # else /* !DEBUG follows */
246 static RETSIGTYPE no_debug (int);
248 #endif /* !SIM && !SYS_WINNT */
256 int ntpdmain (int, char **);
257 static void set_process_priority (void);
258 static void assertion_failed (const char *, int,
261 __attribute__ ((__noreturn__));
262 static void library_fatal_error (const char *, int,
263 const char *, va_list)
264 ISC_FORMAT_PRINTF(3, 0);
265 static void library_unexpected_error(const char *, int,
266 const char *, va_list)
267 ISC_FORMAT_PRINTF(3, 0);
271 /* Bug2332 unearthed a problem in the interaction of reduced user
272 * privileges, the limits on memory usage and some versions of the
273 * pthread library on Linux systems. The 'pthread_cancel()' function and
274 * likely some others need to track the stack of the thread involved,
275 * and uses a function that comes from GCC (--> libgcc_s.so) to do
276 * this. Unfortunately the developers of glibc decided to load the
277 * library on demand, which speeds up program start but can cause
278 * trouble here: Due to all the things NTPD does to limit its resource
279 * usage, this deferred load of libgcc_s does not always work once the
280 * restrictions are in effect.
282 * One way out of this was attempting a forced link against libgcc_s
283 * when possible because it makes the library available immediately
284 * without deferred load. (The symbol resolution would still be dynamic
285 * and on demand, but the code would already be in the process image.)
287 * This is a tricky thing to do, since it's not necessary everywhere,
288 * not possible everywhere, has shown to break the build of other
289 * programs in the NTP suite and is now generally frowned upon.
291 * So we take a different approach here: We creat a worker thread that does
292 * actually nothing except waiting for cancellation and cancel it. If
293 * this is done before all the limitations are put in place, the
294 * machinery is pre-heated and all the runtime stuff should be in place
295 * and useable when needed.
297 * This uses only the standard pthread API and should work with all
298 * implementations of pthreads. It is not necessary everywhere, but it's
299 * cheap enough to go on nearly unnoticed.
301 * Addendum: Bug 2954 showed that the assumption that this should work
302 * with all OS is wrong -- at least FreeBSD bombs heavily.
304 #ifdef NEED_PTHREAD_WARMUP
306 /* simple thread function: sleep until cancelled, just to exercise
307 * thread cancellation.
310 my_pthread_warmup_worker(
319 /* pre-heat threading: create a thread and cancel it, just to exercise
320 * thread cancellation.
323 my_pthread_warmup(void)
326 pthread_attr_t thr_attr;
329 pthread_attr_init(&thr_attr);
330 #if defined(HAVE_PTHREAD_ATTR_GETSTACKSIZE) && \
331 defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && \
332 defined(PTHREAD_STACK_MIN)
334 size_t ssmin = 32*1024; /* 32kB should be minimum */
335 if (ssmin < PTHREAD_STACK_MIN)
336 ssmin = PTHREAD_STACK_MIN;
337 rc = pthread_attr_setstacksize(&thr_attr, ssmin);
340 "my_pthread_warmup: pthread_attr_setstacksize() -> %s",
345 &thread, &thr_attr, my_pthread_warmup_worker, NULL);
346 pthread_attr_destroy(&thr_attr);
349 "my_pthread_warmup: pthread_create() -> %s",
352 pthread_cancel(thread);
353 pthread_join(thread, NULL);
357 #endif /*defined(NEED_PTHREAD_WARMUP)*/
359 #ifdef NEED_EARLY_FORK
361 dummy_callback(void) { return; }
364 fork_nonchroot_worker(void) {
365 getaddrinfo_sometime("localhost", "ntp", NULL, INITIAL_DNS_RETRY,
366 (gai_sometime_callback)&dummy_callback, NULL);
368 #endif /* NEED_EARLY_FORK */
380 optct = ntpOptionProcess(&ntpdOptions, *pargc, *pargv);
397 parse_cmdline_opts(&argc, &argv);
399 debug = OPT_VALUE_SET_DEBUG_LEVEL;
400 DPRINTF(1, ("%s\n", Version));
403 return ntpsim(argc, argv);
405 #else /* !SIM follows */
406 #ifdef NO_MAIN_ALLOWED
407 CALL(ntpd,"ntpd",ntpdmain);
408 #else /* !NO_MAIN_ALLOWED follows */
419 * We Must disable ASLR stack gap on FreeBSD to avoid a
420 * segfault. See PR/241421 and PR/241960.
422 int aslr_var = PROC_STACKGAP_DISABLE;
424 pid_t my_pid = getpid();
425 procctl(P_PID, my_pid, PROC_STACKGAP_CTL, &aslr_var);
428 return ntpdmain(argc, argv);
430 #endif /* !SYS_WINNT */
431 #endif /* !NO_MAIN_ALLOWED */
436 * OK. AIX is different than solaris in how it implements plock().
437 * If you do NOT adjust the stack limit, you will get the MAXIMUM
438 * stack size allocated and PINNED with you program. To check the
439 * value, use ulimit -a.
441 * To fix this, we create an automatic variable and set our stack limit
442 * to that PLUS 32KB of extra space (we need some headroom).
444 * This subroutine gets the stack address.
446 * Grover Davidson and Matt Ladendorf
457 * Signal handler for SIGDANGER.
460 catch_danger(int signo)
462 msyslog(LOG_INFO, "ntpd: setpgid(): %m");
463 /* Make the system believe we'll free something, but don't do it! */
469 * Set the process priority
473 set_process_priority(void)
478 msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>",
480 ? "Leave priority alone"
481 : "Attempt to set priority"
486 # if defined(HAVE_SCHED_SETSCHEDULER)
487 if (!priority_done) {
488 extern int config_priority_override, config_priority;
490 struct sched_param sched;
492 pmax = sched_get_priority_max(SCHED_FIFO);
493 sched.sched_priority = pmax;
494 if ( config_priority_override ) {
495 pmin = sched_get_priority_min(SCHED_FIFO);
496 if ( config_priority > pmax )
497 sched.sched_priority = pmax;
498 else if ( config_priority < pmin )
499 sched.sched_priority = pmin;
501 sched.sched_priority = config_priority;
503 if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 )
504 msyslog(LOG_ERR, "sched_setscheduler(): %m");
508 # endif /* HAVE_SCHED_SETSCHEDULER */
511 if (!priority_done) {
514 srtp.type = RTP_PRIO_REALTIME; /* was: RTP_PRIO_NORMAL */
515 srtp.prio = 0; /* 0 (hi) -> RTP_PRIO_MAX (31,lo) */
517 if (rtprio(RTP_SET, getpid(), &srtp) < 0)
518 msyslog(LOG_ERR, "rtprio() error: %m");
522 # else /* !RTP_SET follows */
523 if (!priority_done) {
524 if (rtprio(0, 120) < 0)
525 msyslog(LOG_ERR, "rtprio() error: %m");
529 # endif /* !RTP_SET */
530 # endif /* HAVE_RTPRIO */
531 # if defined(NTPD_PRIO) && NTPD_PRIO != 0
532 # ifdef HAVE_ATT_NICE
533 if (!priority_done) {
535 if (-1 == nice (NTPD_PRIO) && errno != 0)
536 msyslog(LOG_ERR, "nice() error: %m");
540 # endif /* HAVE_ATT_NICE */
541 # ifdef HAVE_BSD_NICE
542 if (!priority_done) {
543 if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO))
544 msyslog(LOG_ERR, "setpriority() error: %m");
548 # endif /* HAVE_BSD_NICE */
549 # endif /* NTPD_PRIO && NTPD_PRIO != 0 */
551 msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority");
555 #if !defined(SIM) && !defined(SYS_WINNT)
557 * Detach from terminal (much like daemon())
558 * Nothe that this function calls exit()
560 # ifdef HAVE_WORKING_FORK
562 detach_from_terminal(
565 const char *logfilename
570 # if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
579 exit_code = (errno) ? errno : -1;
580 msyslog(LOG_ERR, "fork: %m");
585 exit_code = wait_child_sync_if(pipe_fds[0],
592 * close all open files excepting waitsync_fd_to_close.
593 * msyslog() unreliable until after init_logging().
596 if (syslog_file != NULL) {
601 close_all_except(waitsync_fd_to_close);
602 INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
605 init_logging(progname, 0, TRUE);
606 /* we lost our logfile (if any) daemonizing */
607 setup_logfile(logfilename);
614 proc2_$who_am_i(&puid);
615 proc2_$make_server(&puid, &st);
617 # endif /* SYS_DOMAINOS */
619 if (setsid() == (pid_t)-1)
620 msyslog(LOG_ERR, "setsid(): %m");
621 # elif defined(HAVE_SETPGID)
622 if (setpgid(0, 0) == -1)
623 msyslog(LOG_ERR, "setpgid(): %m");
624 # else /* !HAVE_SETSID && !HAVE_SETPGID follows */
626 fid = open("/dev/tty", 2);
628 ioctl(fid, (u_long)TIOCNOTTY, NULL);
631 # endif /* TIOCNOTTY */
632 ntp_setpgrp(0, getpid());
633 # endif /* !HAVE_SETSID && !HAVE_SETPGID */
635 /* Don't get killed by low-on-memory signal. */
636 sa.sa_handler = catch_danger;
637 sigemptyset(&sa.sa_mask);
638 sa.sa_flags = SA_RESTART;
639 sigaction(SIGDANGER, &sa, NULL);
644 # endif /* HAVE_WORKING_FORK */
648 * Map user name/number to user ID
656 if (isdigit((unsigned char)*user)) {
657 sw_uid = (uid_t)strtoul(user, &endp, 0);
661 if ((pw = getpwuid(sw_uid)) != NULL) {
663 user = estrdup(pw->pw_name);
667 msyslog(LOG_ERR, "Cannot find user ID %s", user);
674 if ((pw = getpwnam(user)) != NULL) {
679 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
681 msyslog(LOG_ERR, "Cannot find user `%s'", user);
690 * Map group name/number to group ID
697 if (isdigit((unsigned char)*group)) {
698 sw_gid = (gid_t)strtoul(group, &endp, 0);
703 if ((gr = getgrnam(group)) != NULL) {
707 msyslog(LOG_ERR, "Cannot find group `%s'", group);
718 if (user && initgroups(user, sw_gid)) {
719 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
722 if (group && setgid(sw_gid)) {
723 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
726 if (group && setegid(sw_gid)) {
727 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
731 if (0 != setgroups(1, &sw_gid)) {
732 msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
737 if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
738 msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
747 if (user && setuid(sw_uid)) {
748 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
751 if (user && seteuid(sw_uid)) {
752 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
759 * Change (effective) user and group IDs, also initialize the supplementary group access list
761 int set_user_group_ids(void);
763 set_user_group_ids(void)
765 /* If the the user was already mapped, no need to map it again */
766 if ((NULL != user) && (0 == sw_uid)) {
770 /* same applies for the group */
771 if ((NULL != group) && (0 == sw_gid)) {
772 if (0 == map_group())
776 if (getegid() != sw_gid && 0 == set_group_ids())
778 if (geteuid() != sw_uid && 0 == set_user_ids())
783 #endif /* HAVE_DROPROOT */
787 * Main program. Initialize us, disconnect us from the tty if necessary,
788 * and loop waiting for I/O and/or timer expiries.
798 struct recvbuf *rbuf;
799 const char * logfilename;
803 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
806 # if defined(HAVE_WORKING_FORK)
811 # endif /* HAVE_WORKING_FORK*/
817 # ifdef NEED_PTHREAD_WARMUP
831 initializing = TRUE; /* mark that we are initializing */
832 parse_cmdline_opts(&argc, &argv);
834 debug = OPT_VALUE_SET_DEBUG_LEVEL;
835 # ifdef HAVE_SETLINEBUF
840 if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
844 || HAVE_OPT(SAVECONFIGQUIT))
847 init_logging(progname, NLOG_SYNCMASK, TRUE);
848 /* honor -l/--logfile option to log to a file */
849 if (HAVE_OPT(LOGFILE)) {
850 logfilename = OPT_ARG(LOGFILE);
852 change_logfile(logfilename, FALSE);
857 if (HAVE_OPT(SAVECONFIGQUIT))
860 msyslog(LOG_NOTICE, "%s: Starting", Version);
864 char buf[1024]; /* Secret knowledge of msyslog buf length */
867 /* Note that every arg has an initial space character */
868 snprintf(cp, sizeof(buf), "Command line:");
871 for (i = 0; i < saved_argc ; ++i) {
872 snprintf(cp, sizeof(buf) - (cp - buf),
873 " %s", saved_argv[i]);
876 msyslog(LOG_INFO, "%s", buf);
880 * Install trap handlers to log errors and assertion failures.
881 * Default handlers print to stderr which doesn't work if detached.
883 isc_assertion_setcallback(assertion_failed);
884 isc_error_setfatal(library_fatal_error);
885 isc_error_setunexpected(library_unexpected_error);
887 /* MPE lacks the concept of root */
888 # if defined(HAVE_GETUID) && !defined(MPE)
890 if (uid && !HAVE_OPT( SAVECONFIGQUIT )
891 # if defined(HAVE_TRUSTEDBSD_MAC)
892 /* We can run as non-root if the mac_ntpd policy is enabled. */
893 && mac_is_present("ntpd") != 1
898 "must be run as root, not uid %ld", (long)uid);
904 * Enable the Multi-Media Timer for Windows?
907 if (HAVE_OPT( MODIFYMMTIMER ))
908 set_mm_timer(MM_TIMER_HIRES);
911 #ifdef HAVE_DNSREGISTRATION
913 * Enable mDNS registrations?
915 if (HAVE_OPT( MDNS )) {
918 #endif /* HAVE_DNSREGISTRATION */
920 if (HAVE_OPT( NOVIRTUALIPS ))
921 listen_to_virtual_ips = 0;
924 * --interface, listen on specified interfaces
926 if (HAVE_OPT( INTERFACE )) {
927 int ifacect = STACKCT_OPT( INTERFACE );
928 const char** ifaces = STACKLST_OPT( INTERFACE );
931 while (ifacect-- > 0) {
933 is_ip_address(*ifaces, AF_UNSPEC, &addr)
936 *ifaces, -1, ACTION_LISTEN);
941 if (HAVE_OPT( NICE ))
944 # ifdef HAVE_SCHED_SETSCHEDULER
945 if (HAVE_OPT( PRIORITY )) {
946 config_priority = OPT_VALUE_PRIORITY;
947 config_priority_override = 1;
952 # ifdef HAVE_WORKING_FORK
953 /* make sure the FDs are initialised */
956 do { /* 'loop' once */
957 if (!HAVE_OPT( WAIT_SYNC ))
959 wait_sync = OPT_VALUE_WAIT_SYNC;
960 if (wait_sync <= 0) {
964 /* -w requires a fork() even with debug > 0 */
966 if (pipe(pipe_fds)) {
967 exit_code = (errno) ? errno : -1;
969 "Pipe creation failed for --wait-sync: %m");
972 waitsync_fd_to_close = pipe_fds[1];
973 } while (0); /* 'loop' once */
974 # endif /* HAVE_WORKING_FORK */
979 * Make sure the service is initialized before we do anything else
984 * Start interpolation thread, must occur before first
990 * Initialize random generator and public key pair
994 ntp_srandom((int)(now.l_i * now.l_uf));
997 * Detach us from the terminal. May need an #ifndef GIZMO.
1001 # ifdef HAVE_WORKING_FORK
1002 detach_from_terminal(pipe_fds, wait_sync, logfilename);
1003 # endif /* HAVE_WORKING_FORK */
1008 * SCO OpenServer's system clock offers much more precise timekeeping
1009 * on the base CPU than the other CPUs (for multiprocessor systems),
1010 * so we must lock to the base CPU.
1012 fd = open("/dev/at1", O_RDONLY);
1015 if (ioctl(fd, ACPU_LOCK, &zero) < 0)
1016 msyslog(LOG_ERR, "cannot lock to base CPU: %m");
1021 /* Setup stack size in preparation for locking pages in memory. */
1022 # if defined(HAVE_MLOCKALL)
1023 # ifdef HAVE_SETRLIMIT
1024 ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
1025 # if defined(RLIMIT_MEMLOCK) && defined(DFLT_RLIMIT_MEMLOCK) && DFLT_RLIMIT_MEMLOCK != -1
1027 * The default RLIMIT_MEMLOCK is very low on Linux systems.
1028 * Unless we increase this limit malloc calls are likely to
1029 * fail if we drop root privilege. To be useful the value
1030 * has to be larger than the largest ntpd resident set size.
1032 ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
1033 # endif /* RLIMIT_MEMLOCK */
1034 # endif /* HAVE_SETRLIMIT */
1035 # else /* !HAVE_MLOCKALL follows */
1040 * set the stack limit for AIX for plock().
1041 * see get_aix_stack() for more info.
1043 if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
1045 "Cannot adjust stack limit for plock: %m");
1047 # endif /* PROCLOCK */
1048 # endif /* HAVE_PLOCK */
1049 # endif /* !HAVE_MLOCKALL */
1052 * Set up signals we pay attention to locally.
1055 signal_no_reset(SIGDIE1, finish);
1056 signal_no_reset(SIGDIE2, finish);
1057 signal_no_reset(SIGDIE3, finish);
1058 signal_no_reset(SIGDIE4, finish);
1061 signal_no_reset(SIGBUS, finish);
1064 # if !defined(SYS_WINNT) && !defined(VMS)
1066 (void) signal_no_reset(MOREDEBUGSIG, moredebug);
1067 (void) signal_no_reset(LESSDEBUGSIG, lessdebug);
1069 (void) signal_no_reset(MOREDEBUGSIG, no_debug);
1070 (void) signal_no_reset(LESSDEBUGSIG, no_debug);
1072 # endif /* !SYS_WINNT && !VMS */
1075 * Set up signals we should never pay attention to.
1078 signal_no_reset(SIGPIPE, SIG_IGN);
1082 * Call the init_ routines to initialize the data structures.
1084 * Exactly what command-line options are we expecting here?
1098 set_process_priority();
1099 init_proto(); /* Call at high priority */
1102 mon_start(MON_ON); /* monitor on by default now */
1103 /* turn off in config if unwanted */
1106 * Get the configuration. This is done in a separate module
1107 * since this will definitely be different for the gizmo board.
1109 getconfig(argc, argv);
1111 if (-1 == cur_memlock) {
1112 # if defined(HAVE_MLOCKALL)
1114 * lock the process into memory
1116 if ( !HAVE_OPT(SAVECONFIGQUIT)
1117 # ifdef RLIMIT_MEMLOCK
1118 && -1 != DFLT_RLIMIT_MEMLOCK
1120 && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
1121 msyslog(LOG_ERR, "mlockall(): %m");
1122 # else /* !HAVE_MLOCKALL follows */
1126 * lock the process into memory
1128 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
1129 msyslog(LOG_ERR, "plock(PROCLOCK): %m");
1130 # else /* !PROCLOCK follows */
1133 * Lock text into ram
1135 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
1136 msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
1137 # else /* !TXTLOCK follows */
1138 msyslog(LOG_ERR, "plock() - don't know what to lock!");
1139 # endif /* !TXTLOCK */
1140 # endif /* !PROCLOCK */
1141 # endif /* HAVE_PLOCK */
1142 # endif /* !HAVE_MLOCKALL */
1145 loop_config(LOOP_DRIFTINIT, 0);
1146 report_event(EVNT_SYSRESTART, NULL, NULL);
1147 initializing = FALSE;
1149 # ifdef HAVE_DROPROOT
1152 #ifdef NEED_EARLY_FORK
1153 fork_nonchroot_worker();
1156 /* Drop super-user privileges and chroot now if the OS supports this */
1158 # ifdef HAVE_LINUX_CAPABILITIES
1159 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
1160 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
1161 msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
1164 # elif HAVE_SOLARIS_PRIVS
1165 /* Nothing to do here */
1167 /* we need a user to switch to */
1169 msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
1172 # endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
1175 if (0 == map_user())
1178 if (group != NULL) {
1179 if (0 == map_group())
1184 /* make sure cwd is inside the jail: */
1185 if (chdir(chrootdir)) {
1186 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
1189 if (chroot(chrootdir)) {
1190 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
1194 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
1198 # ifdef HAVE_SOLARIS_PRIVS
1199 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
1200 msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
1203 if ((highprivs = priv_allocset()) == NULL) {
1204 msyslog(LOG_ERR, "priv_allocset() failed:%m");
1207 (void) getppriv(PRIV_PERMITTED, highprivs);
1208 (void) priv_intersect(highprivs, lowprivs);
1209 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1210 msyslog(LOG_ERR, "setppriv() failed:%m");
1213 # endif /* HAVE_SOLARIS_PRIVS */
1214 if (0 == set_user_group_ids())
1217 # if defined(HAVE_TRUSTEDBSD_MAC)
1219 * To manipulate system time and (re-)bind to NTP_PORT as needed
1220 * following interface changes, we must either run as uid 0 or
1221 * the mac_ntpd policy module must be enabled.
1223 if (sw_uid != 0 && mac_is_present("ntpd") != 1) {
1224 msyslog(LOG_ERR, "Need MAC 'ntpd' policy enabled to drop root privileges");
1227 # elif !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1229 * for now assume that the privilege to bind to privileged ports
1230 * is associated with running with uid 0 - should be refined on
1231 * ports that allow binding to NTP_PORT with uid != 0
1233 disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */
1234 # endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1236 if (disable_dynamic_updates && interface_interval) {
1237 interface_interval = 0;
1238 msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1241 # ifdef HAVE_LINUX_CAPABILITIES
1244 * We may be running under non-root uid now, but we still hold full root privileges!
1245 * We drop all of them, except for the crucial one or two: cap_sys_time and
1246 * cap_net_bind_service if doing dynamic interface tracking.
1251 captext = (0 != interface_interval)
1252 ? "cap_sys_time,cap_net_bind_service=pe"
1253 : "cap_sys_time=pe";
1254 caps = cap_from_text(captext);
1257 "cap_from_text(%s) failed: %m",
1261 if (-1 == cap_set_proc(caps)) {
1263 "cap_set_proc() failed to drop root privs: %m");
1268 # endif /* HAVE_LINUX_CAPABILITIES */
1269 # ifdef HAVE_SOLARIS_PRIVS
1270 if (priv_delset(lowprivs, "proc_setid") == -1) {
1271 msyslog(LOG_ERR, "priv_delset() failed:%m");
1274 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1275 msyslog(LOG_ERR, "setppriv() failed:%m");
1278 priv_freeset(lowprivs);
1279 priv_freeset(highprivs);
1280 # endif /* HAVE_SOLARIS_PRIVS */
1281 root_dropped = TRUE;
1282 fork_deferred_worker();
1283 } /* if (droproot) */
1284 # endif /* HAVE_DROPROOT */
1286 /* libssecomp sandboxing */
1287 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1288 scmp_filter_ctx ctx;
1290 if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1291 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1293 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1302 SCMP_SYS(clock_gettime),
1303 SCMP_SYS(clock_settime),
1306 SCMP_SYS(exit_group),
1310 SCMP_SYS(getitimer),
1311 SCMP_SYS(getsockname),
1322 SCMP_SYS(rt_sigaction),
1323 SCMP_SYS(rt_sigprocmask),
1324 SCMP_SYS(rt_sigreturn),
1327 SCMP_SYS(setitimer),
1337 SCMP_SYS(_newselect),
1341 SCMP_SYS(clock_gettime),
1342 SCMP_SYS(clock_settime),
1344 SCMP_SYS(exit_group),
1347 SCMP_SYS(getitimer),
1356 SCMP_SYS(rt_sigaction),
1357 SCMP_SYS(rt_sigprocmask),
1359 SCMP_SYS(setitimer),
1361 SCMP_SYS(sigprocmask),
1362 SCMP_SYS(sigreturn),
1363 SCMP_SYS(socketcall),
1372 for (i = 0; i < COUNTOF(scmp_sc); i++) {
1373 if (seccomp_rule_add(ctx,
1374 SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1376 "%s: seccomp_rule_add() failed: %m",
1382 if (seccomp_load(ctx) < 0)
1383 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1386 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1388 #endif /* LIBSECCOMP and KERN_SECCOMP */
1394 # ifdef HAVE_IO_COMPLETION_PORT
1397 #if !defined(SIM) && defined(SIGDIE1)
1401 GetReceivedBuffers();
1402 # else /* normal I/O */
1404 BLOCK_IO_AND_ALARM();
1405 was_alarmed = FALSE;
1408 #if !defined(SIM) && defined(SIGDIE1)
1412 if (alarm_flag) { /* alarmed? */
1417 /* collect async name/addr results */
1419 harvest_blocking_responses();
1421 if (!was_alarmed && !has_full_recv_buffer()) {
1423 * Nothing to do. Wait for something.
1428 if (alarm_flag) { /* alarmed? */
1434 UNBLOCK_IO_AND_ALARM();
1436 * Out here, signals are unblocked. Call timer routine
1437 * to process expiry.
1440 was_alarmed = FALSE;
1441 BLOCK_IO_AND_ALARM();
1444 # endif /* !HAVE_IO_COMPLETION_PORT */
1446 # ifdef DEBUG_TIMING
1455 rbuf = get_full_recv_buffer();
1456 while (rbuf != NULL) {
1461 UNBLOCK_IO_AND_ALARM();
1464 /* avoid timer starvation during lengthy I/O handling */
1466 was_alarmed = FALSE;
1470 * Call the data procedure to handle each received
1473 if (rbuf->receiver != NULL) {
1474 # ifdef DEBUG_TIMING
1477 L_SUB(&dts, &rbuf->recv_time);
1478 DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1479 collect_timing(rbuf, "buffer processing delay", 1, &dts);
1482 (*rbuf->receiver)(rbuf);
1484 msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1488 BLOCK_IO_AND_ALARM();
1490 rbuf = get_full_recv_buffer();
1492 # ifdef DEBUG_TIMING
1496 collect_timing(NULL, "processing", bufcount, &tsb);
1497 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1506 # ifdef HAVE_DNSREGISTRATION
1507 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1508 mdnsreg = current_time;
1509 msyslog(LOG_INFO, "Attempting to register mDNS");
1510 if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1511 htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1513 msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1515 msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1518 msyslog(LOG_INFO, "mDNS service registered.");
1522 # endif /* HAVE_DNSREGISTRATION */
1525 UNBLOCK_IO_AND_ALARM();
1531 #if !defined(SIM) && defined(SIGDIE1)
1533 * finish - exit gracefully
1540 const char *sig_desc;
1543 #ifdef HAVE_STRSIGNAL
1544 sig_desc = strsignal(sig);
1546 if (sig_desc == NULL)
1548 msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1550 /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1551 # ifdef HAVE_DNSREGISTRATION
1553 DNSServiceRefDeallocate(mdns);
1568 #endif /* !SIM && SIGDIE1 */
1573 * wait_child_sync_if - implements parent side of -w/--wait-sync
1575 # ifdef HAVE_WORKING_FORK
1584 time_t wait_end_time;
1588 struct timeval wtimeout;
1593 /* waitsync_fd_to_close used solely by child */
1594 close(waitsync_fd_to_close);
1595 wait_end_time = time(NULL) + wait_sync;
1597 cur_time = time(NULL);
1598 wait_rem = (wait_end_time > cur_time)
1599 ? (wait_end_time - cur_time)
1601 wtimeout.tv_sec = wait_rem;
1602 wtimeout.tv_usec = 0;
1604 FD_SET(pipe_read_fd, &readset);
1605 rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1610 exit_code = (errno) ? errno : -1;
1612 "--wait-sync select failed: %m");
1617 * select() indicated a timeout, but in case
1618 * its timeouts are affected by a step of the
1619 * system clock, select() again with a zero
1620 * timeout to confirm.
1623 FD_SET(pipe_read_fd, &readset);
1624 wtimeout.tv_sec = 0;
1625 wtimeout.tv_usec = 0;
1626 rc = select(pipe_read_fd + 1, &readset, NULL,
1628 if (0 == rc) /* select() timeout */
1632 } else /* readable */
1634 } while (wait_rem > 0);
1636 fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1637 progname, wait_sync);
1640 # endif /* HAVE_WORKING_FORK */
1644 * assertion_failed - Redirect assertion failures to msyslog().
1650 isc_assertiontype_t type,
1654 isc_assertion_setcallback(NULL); /* Avoid recursion */
1656 msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1657 file, line, isc_assertion_typetotext(type), cond);
1658 msyslog(LOG_ERR, "exiting (due to assertion failure)");
1660 #if defined(DEBUG) && defined(SYS_WINNT)
1670 * library_fatal_error - Handle fatal errors from our libraries.
1673 library_fatal_error(
1682 isc_error_setfatal(NULL); /* Avoid recursion */
1684 msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1685 vsnprintf(errbuf, sizeof(errbuf), format, args);
1686 msyslog(LOG_ERR, "%s", errbuf);
1687 msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1689 #if defined(DEBUG) && defined(SYS_WINNT)
1699 * library_unexpected_error - Handle non fatal errors from our libraries.
1701 # define MAX_UNEXPECTED_ERRORS 100
1702 int unexpected_error_cnt = 0;
1704 library_unexpected_error(
1713 if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1714 return; /* avoid clutter in log */
1716 msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1717 vsnprintf(errbuf, sizeof(errbuf), format, args);
1718 msyslog(LOG_ERR, "%s", errbuf);
1720 if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1721 msyslog(LOG_ERR, "Too many errors. Shutting up.");
1726 #if !defined(SIM) && !defined(SYS_WINNT)
1730 * moredebug - increase debugging verbosity
1737 int saved_errno = errno;
1742 msyslog(LOG_DEBUG, "debug raised to %d", debug);
1744 errno = saved_errno;
1749 * lessdebug - decrease debugging verbosity
1756 int saved_errno = errno;
1761 msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1763 errno = saved_errno;
1766 # else /* !DEBUG follows */
1770 * no_debug - We don't do the debug here.
1777 int saved_errno = errno;
1779 msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1780 errno = saved_errno;
1782 # endif /* !DEBUG */
1783 #endif /* !SIM && !SYS_WINNT */