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>
48 #ifdef HAVE_SYS_WAIT_H
49 # include <sys/wait.h>
52 #ifdef HAVE_SYS_PARAM_H
53 # include <sys/param.h>
55 #ifdef HAVE_SYS_SIGNAL_H
56 # include <sys/signal.h>
60 #ifdef HAVE_SYS_IOCTL_H
61 # include <sys/ioctl.h>
62 #endif /* HAVE_SYS_IOCTL_H */
63 #if defined(HAVE_RTPRIO)
64 # ifdef HAVE_SYS_LOCK_H
65 # include <sys/lock.h>
67 # include <sys/rtprio.h>
70 # ifdef HAVE_SYS_LOCK_H
71 # include <sys/lock.h>
75 #if defined(HAVE_SCHED_SETSCHEDULER)
79 # ifdef HAVE_SYS_SCHED_H
80 # include <sys/sched.h>
84 #if defined(HAVE_SYS_MMAN_H)
85 # include <sys/mman.h>
88 #ifdef HAVE_SYSEXITS_H
89 # include <sysexits.h>
97 # include <apollo/base.h>
98 #endif /* SYS_DOMAINOS */
101 #include "recvbuff.h"
102 #include "ntp_cmdargs.h"
104 #if 0 /* HMS: I don't think we need this. 961223 */
107 # include <sys/mman.h>
109 # include <sys/lock.h>
115 # include "ntservice.h"
123 # include <sys/ci/ciioctl.h>
130 #ifdef HAVE_LINUX_CAPABILITIES
131 # include <sys/capability.h>
132 # include <sys/prctl.h>
133 #endif /* HAVE_LINUX_CAPABILITIES */
134 #if defined(HAVE_PRIV_H) && defined(HAVE_SOLARIS_PRIVS)
136 #endif /* HAVE_PRIV_H */
137 #endif /* HAVE_DROPROOT */
139 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
140 /* # include <sys/types.h> */
141 # include <sys/resource.h>
142 # include <seccomp.h>
143 #endif /* LIBSECCOMP and KERN_SECCOMP */
145 #ifdef HAVE_DNSREGISTRATION
150 /* In case 'sysexits.h' is unavailable, define some exit codes here: */
152 # define EX_SOFTWARE 70
161 #define EX_PROTOCOL 76
165 #ifdef HAVE_SETPGRP_0
166 # define ntp_setpgrp(x, y) setpgrp()
168 # define ntp_setpgrp(x, y) setpgrp(x, y)
171 #ifdef HAVE_SOLARIS_PRIVS
172 # define LOWPRIVS "basic,sys_time,net_privaddr,proc_setid,!proc_info,!proc_session,!proc_exec"
173 static priv_set_t *lowprivs = NULL;
174 static priv_set_t *highprivs = NULL;
175 #endif /* HAVE_SOLARIS_PRIVS */
177 * Scheduling priority we run at
179 #define NTPD_PRIO (-12)
181 int priority_done = 2; /* 0 - Set priority */
182 /* 1 - priority is OK where it is */
183 /* 2 - Don't set priority */
184 /* 1 and 2 are pretty much the same */
186 int listen_to_virtual_ips = TRUE;
189 * No-fork flag. If set, we do not become a background daemon.
191 int nofork; /* Fork by default */
193 #ifdef HAVE_DNSREGISTRATION
195 * mDNS registration flag. If set, we attempt to register with the mDNS system, but only
196 * after we have synched the first time. If the attempt fails, then try again once per
197 * minute for up to 5 times. After all, we may be starting before mDNS.
201 #endif /* HAVE_DNSREGISTRATION */
203 #ifdef HAVE_LINUX_CAPABILITIES
204 int have_caps; /* runtime check whether capabilities work */
205 #endif /* HAVE_LINUX_CAPABILITIES */
210 char *user; /* User to switch to */
211 char *group; /* group to switch to */
212 const char *chrootdir; /* directory to chroot to */
217 #endif /* HAVE_DROPROOT */
219 #ifdef HAVE_WORKING_FORK
220 int daemon_pipe[2] = { -1, -1 };
224 * Version declaration
226 extern const char *Version;
228 char const *progname;
234 * We put this here, since the argument profile is syscall-specific
236 extern int syscall (int, ...);
237 #endif /* DECL_SYSCALL */
240 #if !defined(SIM) && defined(SIGDIE1)
241 static volatile int signalled = 0;
242 static volatile int signo = 0;
244 /* In an ideal world, 'finish_safe()' would declared as noreturn... */
245 static void finish_safe (int);
246 static RETSIGTYPE finish (int);
249 #if !defined(SIM) && defined(HAVE_WORKING_FORK)
250 static int wait_child_sync_if (int, unsigned long);
251 static int wait_child_exit_if (pid_t, int);
254 #if !defined(SIM) && !defined(SYS_WINNT)
256 static RETSIGTYPE moredebug (int);
257 static RETSIGTYPE lessdebug (int);
258 # else /* !DEBUG follows */
259 static RETSIGTYPE no_debug (int);
261 #endif /* !SIM && !SYS_WINNT */
269 int ntpdmain (int, char **);
270 static void set_process_priority (void);
271 static void assertion_failed (const char *, int,
274 __attribute__ ((__noreturn__));
275 static void library_fatal_error (const char *, int,
276 const char *, va_list)
277 ISC_FORMAT_PRINTF(3, 0);
278 static void library_unexpected_error(const char *, int,
279 const char *, va_list)
280 ISC_FORMAT_PRINTF(3, 0);
284 /* Bug2332 unearthed a problem in the interaction of reduced user
285 * privileges, the limits on memory usage and some versions of the
286 * pthread library on Linux systems. The 'pthread_cancel()' function and
287 * likely some others need to track the stack of the thread involved,
288 * and uses a function that comes from GCC (--> libgcc_s.so) to do
289 * this. Unfortunately the developers of glibc decided to load the
290 * library on demand, which speeds up program start but can cause
291 * trouble here: Due to all the things NTPD does to limit its resource
292 * usage, this deferred load of libgcc_s does not always work once the
293 * restrictions are in effect.
295 * One way out of this was attempting a forced link against libgcc_s
296 * when possible because it makes the library available immediately
297 * without deferred load. (The symbol resolution would still be dynamic
298 * and on demand, but the code would already be in the process image.)
300 * This is a tricky thing to do, since it's not necessary everywhere,
301 * not possible everywhere, has shown to break the build of other
302 * programs in the NTP suite and is now generally frowned upon.
304 * So we take a different approach here: We creat a worker thread that does
305 * actually nothing except waiting for cancellation and cancel it. If
306 * this is done before all the limitations are put in place, the
307 * machinery is pre-heated and all the runtime stuff should be in place
308 * and useable when needed.
310 * This uses only the standard pthread API and should work with all
311 * implementations of pthreads. It is not necessary everywhere, but it's
312 * cheap enough to go on nearly unnoticed.
314 * Addendum: Bug 2954 showed that the assumption that this should work
315 * with all OS is wrong -- at least FreeBSD bombs heavily.
317 #ifdef NEED_PTHREAD_WARMUP
319 /* simple thread function: sleep until cancelled, just to exercise
320 * thread cancellation.
323 my_pthread_warmup_worker(
332 /* pre-heat threading: create a thread and cancel it, just to exercise
333 * thread cancellation.
336 my_pthread_warmup(void)
339 pthread_attr_t thr_attr;
342 pthread_attr_init(&thr_attr);
343 #if defined(HAVE_PTHREAD_ATTR_GETSTACKSIZE) && \
344 defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && \
345 defined(PTHREAD_STACK_MIN)
347 size_t ssmin = 32*1024; /* 32kB should be minimum */
348 if (ssmin < PTHREAD_STACK_MIN)
349 ssmin = PTHREAD_STACK_MIN;
350 rc = pthread_attr_setstacksize(&thr_attr, ssmin);
353 "my_pthread_warmup: pthread_attr_setstacksize() -> %s",
358 &thread, &thr_attr, my_pthread_warmup_worker, NULL);
359 pthread_attr_destroy(&thr_attr);
362 "my_pthread_warmup: pthread_create() -> %s",
365 pthread_cancel(thread);
366 pthread_join(thread, NULL);
370 #endif /*defined(NEED_PTHREAD_WARMUP)*/
372 #ifdef NEED_EARLY_FORK
374 dummy_callback(void) { return; }
377 fork_nonchroot_worker(void) {
378 getaddrinfo_sometime("localhost", "ntp", NULL, INITIAL_DNS_RETRY,
379 (gai_sometime_callback)&dummy_callback, NULL);
381 #endif /* NEED_EARLY_FORK */
393 optct = ntpOptionProcess(&ntpdOptions, *pargc, *pargv);
410 parse_cmdline_opts(&argc, &argv);
412 debug = OPT_VALUE_SET_DEBUG_LEVEL;
413 DPRINTF(1, ("%s\n", Version));
416 return ntpsim(argc, argv);
418 #elif defined(NO_MAIN_ALLOWED)
419 CALL(ntpd,"ntpd",ntpdmain);
420 #elif !defined(SYS_WINNT)
427 return ntpdmain(argc, argv);
429 #endif /* !SYS_WINNT */
433 * OK. AIX is different than solaris in how it implements plock().
434 * If you do NOT adjust the stack limit, you will get the MAXIMUM
435 * stack size allocated and PINNED with you program. To check the
436 * value, use ulimit -a.
438 * To fix this, we create an automatic variable and set our stack limit
439 * to that PLUS 32KB of extra space (we need some headroom).
441 * This subroutine gets the stack address.
443 * Grover Davidson and Matt Ladendorf
454 * Signal handler for SIGDANGER.
457 catch_danger(int signo)
459 msyslog(LOG_INFO, "ntpd: setpgid(): %m");
460 /* Make the system believe we'll free something, but don't do it! */
466 * Set the process priority
470 set_process_priority(void)
475 msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>",
477 ? "Leave priority alone"
478 : "Attempt to set priority"
483 # if defined(HAVE_SCHED_SETSCHEDULER)
484 if (!priority_done) {
485 extern int config_priority_override, config_priority;
487 struct sched_param sched;
489 pmax = sched_get_priority_max(SCHED_FIFO);
490 sched.sched_priority = pmax;
491 if ( config_priority_override ) {
492 pmin = sched_get_priority_min(SCHED_FIFO);
493 if ( config_priority > pmax )
494 sched.sched_priority = pmax;
495 else if ( config_priority < pmin )
496 sched.sched_priority = pmin;
498 sched.sched_priority = config_priority;
500 if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 )
501 msyslog(LOG_ERR, "sched_setscheduler(): %m");
505 # endif /* HAVE_SCHED_SETSCHEDULER */
508 if (!priority_done) {
511 srtp.type = RTP_PRIO_REALTIME; /* was: RTP_PRIO_NORMAL */
512 srtp.prio = 0; /* 0 (hi) -> RTP_PRIO_MAX (31,lo) */
514 if (rtprio(RTP_SET, getpid(), &srtp) < 0)
515 msyslog(LOG_ERR, "rtprio() error: %m");
519 # else /* !RTP_SET follows */
520 if (!priority_done) {
521 if (rtprio(0, 120) < 0)
522 msyslog(LOG_ERR, "rtprio() error: %m");
526 # endif /* !RTP_SET */
527 # endif /* HAVE_RTPRIO */
528 # if defined(NTPD_PRIO) && NTPD_PRIO != 0
529 # ifdef HAVE_ATT_NICE
530 if (!priority_done) {
532 if (-1 == nice (NTPD_PRIO) && errno != 0)
533 msyslog(LOG_ERR, "nice() error: %m");
537 # endif /* HAVE_ATT_NICE */
538 # ifdef HAVE_BSD_NICE
539 if (!priority_done) {
540 if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO))
541 msyslog(LOG_ERR, "setpriority() error: %m");
545 # endif /* HAVE_BSD_NICE */
546 # endif /* NTPD_PRIO && NTPD_PRIO != 0 */
548 msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority");
552 #if !defined(SIM) && !defined(SYS_WINNT)
554 * Detach from terminal (much like daemon())
555 * Nothe that this function calls exit()
557 # ifdef HAVE_WORKING_FORK
559 detach_from_terminal(
562 const char *logfilename
567 # if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
578 msyslog(LOG_ERR, "fork: %m");
579 exit_code = EX_OSERR;
583 exit_code = wait_child_sync_if(
585 DPRINTF(1, ("sync_if: rc=%d\n", exit_code));
586 if (exit_code <= 0) {
587 /* probe daemon exit code -- wait for
588 * child process if we have an unexpected
589 * EOF on the monitor pipe.
591 exit_code = wait_child_exit_if(
592 cpid, (exit_code < 0));
593 DPRINTF(1, ("exit_if: rc=%d\n", exit_code));
601 * close all open files excepting waitsync_fd_to_close.
602 * msyslog() unreliable until after init_logging().
605 if (syslog_file != NULL) {
610 close_all_except(pipe[1]);
612 INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
615 init_logging(progname, 0, TRUE);
616 /* we lost our logfile (if any) daemonizing */
617 setup_logfile(logfilename);
624 proc2_$who_am_i(&puid);
625 proc2_$make_server(&puid, &st);
627 # endif /* SYS_DOMAINOS */
629 if (setsid() == (pid_t)-1)
630 msyslog(LOG_ERR, "setsid(): %m");
631 # elif defined(HAVE_SETPGID)
632 if (setpgid(0, 0) == -1)
633 msyslog(LOG_ERR, "setpgid(): %m");
634 # else /* !HAVE_SETSID && !HAVE_SETPGID follows */
636 fid = open("/dev/tty", 2);
638 ioctl(fid, (u_long)TIOCNOTTY, NULL);
641 # endif /* TIOCNOTTY */
642 ntp_setpgrp(0, getpid());
643 # endif /* !HAVE_SETSID && !HAVE_SETPGID */
645 /* Don't get killed by low-on-memory signal. */
646 sa.sa_handler = catch_danger;
647 sigemptyset(&sa.sa_mask);
648 sa.sa_flags = SA_RESTART;
649 sigaction(SIGDANGER, &sa, NULL);
654 # endif /* HAVE_WORKING_FORK */
658 * Map user name/number to user ID
666 if (isdigit((unsigned char)*user)) {
667 sw_uid = (uid_t)strtoul(user, &endp, 0);
671 if ((pw = getpwuid(sw_uid)) != NULL) {
673 user = estrdup(pw->pw_name);
677 msyslog(LOG_ERR, "Cannot find user ID %s", user);
684 if ((pw = getpwnam(user)) != NULL) {
689 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
691 msyslog(LOG_ERR, "Cannot find user `%s'", user);
700 * Map group name/number to group ID
707 if (isdigit((unsigned char)*group)) {
708 sw_gid = (gid_t)strtoul(group, &endp, 0);
713 if ((gr = getgrnam(group)) != NULL) {
717 msyslog(LOG_ERR, "Cannot find group `%s'", group);
728 if (user && initgroups(user, sw_gid)) {
729 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
732 if (group && setgid(sw_gid)) {
733 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
736 if (group && setegid(sw_gid)) {
737 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
741 if (0 != setgroups(1, &sw_gid)) {
742 msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
747 if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
748 msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
757 if (user && setuid(sw_uid)) {
758 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
761 if (user && seteuid(sw_uid)) {
762 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
769 * Change (effective) user and group IDs, also initialize the supplementary group access list
771 int set_user_group_ids(void);
773 set_user_group_ids(void)
775 /* If the the user was already mapped, no need to map it again */
776 if ((NULL != user) && (0 == sw_uid)) {
780 /* same applies for the group */
781 if ((NULL != group) && (0 == sw_gid)) {
782 if (0 == map_group())
786 if (getegid() != sw_gid && 0 == set_group_ids())
788 if (geteuid() != sw_uid && 0 == set_user_ids())
793 #endif /* HAVE_DROPROOT */
797 * Main program. Initialize us, disconnect us from the tty if necessary,
798 * and loop waiting for I/O and/or timer expiries.
808 struct recvbuf *rbuf;
809 const char * logfilename;
813 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
816 # if defined(HAVE_WORKING_FORK)
818 # endif /* HAVE_WORKING_FORK*/
824 # ifdef NEED_PTHREAD_WARMUP
838 initializing = TRUE; /* mark that we are initializing */
839 parse_cmdline_opts(&argc, &argv);
841 debug = OPT_VALUE_SET_DEBUG_LEVEL;
842 # ifdef HAVE_SETLINEBUF
847 if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
851 || HAVE_OPT(SAVECONFIGQUIT))
854 init_logging(progname, NLOG_SYNCMASK, TRUE);
855 /* honor -l/--logfile option to log to a file */
856 if (HAVE_OPT(LOGFILE)) {
857 logfilename = OPT_ARG(LOGFILE);
859 change_logfile(logfilename, FALSE);
864 if (HAVE_OPT(SAVECONFIGQUIT))
867 msyslog(LOG_NOTICE, "%s: Starting", Version);
871 char buf[1024]; /* Secret knowledge of msyslog buf length */
874 /* Note that every arg has an initial space character */
875 snprintf(cp, sizeof(buf), "Command line:");
878 for (i = 0; i < saved_argc ; ++i) {
879 snprintf(cp, sizeof(buf) - (cp - buf),
880 " %s", saved_argv[i]);
883 msyslog(LOG_NOTICE, "%s", buf);
886 msyslog(LOG_NOTICE, "----------------------------------------------------");
887 msyslog(LOG_NOTICE, "ntp-4 is maintained by Network Time Foundation,");
888 msyslog(LOG_NOTICE, "Inc. (NTF), a non-profit 501(c)(3) public-benefit");
889 msyslog(LOG_NOTICE, "corporation. Support and training for ntp-4 are");
890 msyslog(LOG_NOTICE, "available at https://www.nwtime.org/support");
891 msyslog(LOG_NOTICE, "----------------------------------------------------");
894 * Install trap handlers to log errors and assertion failures.
895 * Default handlers print to stderr which doesn't work if detached.
897 isc_assertion_setcallback(assertion_failed);
898 isc_error_setfatal(library_fatal_error);
899 isc_error_setunexpected(library_unexpected_error);
901 /* MPE lacks the concept of root */
902 # if defined(HAVE_GETUID) && !defined(MPE)
904 if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
907 "must be run as root, not uid %ld", (long)uid);
913 * Enable the Multi-Media Timer for Windows?
916 if (HAVE_OPT( MODIFYMMTIMER ))
917 set_mm_timer(MM_TIMER_HIRES);
920 #ifdef HAVE_DNSREGISTRATION
922 * Enable mDNS registrations?
924 if (HAVE_OPT( MDNS )) {
927 #endif /* HAVE_DNSREGISTRATION */
929 if (HAVE_OPT( NOVIRTUALIPS ))
930 listen_to_virtual_ips = 0;
933 * --interface, listen on specified interfaces
935 if (HAVE_OPT( INTERFACE )) {
936 int ifacect = STACKCT_OPT( INTERFACE );
937 const char** ifaces = STACKLST_OPT( INTERFACE );
940 while (ifacect-- > 0) {
942 is_ip_address(*ifaces, AF_UNSPEC, &addr)
945 *ifaces, -1, ACTION_LISTEN);
950 if (HAVE_OPT( NICE ))
953 # ifdef HAVE_SCHED_SETSCHEDULER
954 if (HAVE_OPT( PRIORITY )) {
955 config_priority = OPT_VALUE_PRIORITY;
956 config_priority_override = 1;
961 # ifdef HAVE_WORKING_FORK
962 /* make sure the FDs are initialised
964 * note: if WAIT_SYNC is requested, we *have* to fork. This will
965 * overide any '-n' (nofork) or '-d' (debug) option presented on
968 if (HAVE_OPT(WAIT_SYNC)) {
969 wait_sync = OPT_VALUE_WAIT_SYNC;
975 if ( !nofork && pipe(daemon_pipe)) {
977 "Pipe creation failed for --wait-sync/daemon: %m");
980 # endif /* HAVE_WORKING_FORK */
985 * Make sure the service is initialized before we do anything else
990 * Start interpolation thread, must occur before first
996 * Initialize random generator and public key pair
1000 ntp_srandom((int)(now.l_i * now.l_uf));
1003 * Detach us from the terminal. May need an #ifndef GIZMO.
1005 # ifdef HAVE_WORKING_FORK
1007 detach_from_terminal(daemon_pipe, wait_sync, logfilename);
1009 # endif /* HAVE_WORKING_FORK */
1013 * SCO OpenServer's system clock offers much more precise timekeeping
1014 * on the base CPU than the other CPUs (for multiprocessor systems),
1015 * so we must lock to the base CPU.
1017 fd = open("/dev/at1", O_RDONLY);
1020 if (ioctl(fd, ACPU_LOCK, &zero) < 0)
1021 msyslog(LOG_ERR, "cannot lock to base CPU: %m");
1026 /* Setup stack size in preparation for locking pages in memory. */
1027 # if defined(HAVE_MLOCKALL)
1028 # ifdef HAVE_SETRLIMIT
1029 ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
1030 # ifdef RLIMIT_MEMLOCK
1032 * The default RLIMIT_MEMLOCK is very low on Linux systems.
1033 * Unless we increase this limit malloc calls are likely to
1034 * fail if we drop root privilege. To be useful the value
1035 * has to be larger than the largest ntpd resident set size.
1037 ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
1038 # endif /* RLIMIT_MEMLOCK */
1039 # endif /* HAVE_SETRLIMIT */
1040 # else /* !HAVE_MLOCKALL follows */
1045 * set the stack limit for AIX for plock().
1046 * see get_aix_stack() for more info.
1048 if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
1050 "Cannot adjust stack limit for plock: %m");
1052 # endif /* PROCLOCK */
1053 # endif /* HAVE_PLOCK */
1054 # endif /* !HAVE_MLOCKALL */
1057 * Set up signals we pay attention to locally.
1060 signal_no_reset(SIGDIE1, finish);
1061 signal_no_reset(SIGDIE2, finish);
1062 signal_no_reset(SIGDIE3, finish);
1063 signal_no_reset(SIGDIE4, finish);
1066 signal_no_reset(SIGBUS, finish);
1069 # if !defined(SYS_WINNT) && !defined(VMS)
1071 (void) signal_no_reset(MOREDEBUGSIG, moredebug);
1072 (void) signal_no_reset(LESSDEBUGSIG, lessdebug);
1074 (void) signal_no_reset(MOREDEBUGSIG, no_debug);
1075 (void) signal_no_reset(LESSDEBUGSIG, no_debug);
1077 # endif /* !SYS_WINNT && !VMS */
1080 * Set up signals we should never pay attention to.
1083 signal_no_reset(SIGPIPE, SIG_IGN);
1087 * Call the init_ routines to initialize the data structures.
1089 * Exactly what command-line options are we expecting here?
1103 set_process_priority();
1104 init_proto(); /* Call at high priority */
1107 mon_start(MON_ON); /* monitor on by default now */
1108 /* turn off in config if unwanted */
1111 * Get the configuration. This is done in a separate module
1112 * since this will definitely be different for the gizmo board.
1114 getconfig(argc, argv);
1116 if (-1 == cur_memlock) {
1117 # if defined(HAVE_MLOCKALL)
1119 * lock the process into memory
1121 if ( !HAVE_OPT(SAVECONFIGQUIT)
1122 # ifdef RLIMIT_MEMLOCK
1123 && -1 != DFLT_RLIMIT_MEMLOCK
1125 && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
1126 msyslog(LOG_ERR, "mlockall(): %m");
1127 # else /* !HAVE_MLOCKALL follows */
1131 * lock the process into memory
1133 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
1134 msyslog(LOG_ERR, "plock(PROCLOCK): %m");
1135 # else /* !PROCLOCK follows */
1138 * Lock text into ram
1140 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
1141 msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
1142 # else /* !TXTLOCK follows */
1143 msyslog(LOG_ERR, "plock() - don't know what to lock!");
1144 # endif /* !TXTLOCK */
1145 # endif /* !PROCLOCK */
1146 # endif /* HAVE_PLOCK */
1147 # endif /* !HAVE_MLOCKALL */
1150 loop_config(LOOP_DRIFTINIT, 0);
1151 report_event(EVNT_SYSRESTART, NULL, NULL);
1152 initializing = FALSE;
1154 # ifdef HAVE_LINUX_CAPABILITIES
1156 /* Check that setting capabilities actually works; we might be
1157 * run on a kernel with disabled capabilities. We must not
1158 * drop privileges in this case.
1161 caps = cap_from_text("cap_sys_time,cap_setuid,cap_setgid,cap_sys_chroot,cap_net_bind_service=pe");
1163 msyslog( LOG_ERR, "cap_from_text() failed: %m" );
1166 have_caps = (cap_set_proc(caps) == 0);
1167 cap_free(caps); /* caps not NULL here! */
1169 # endif /* HAVE_LINUX_CAPABILITIES */
1171 # ifdef HAVE_DROPROOT
1172 # ifdef HAVE_LINUX_CAPABILITIES
1173 if (droproot && have_caps) {
1176 # endif /*HAVE_LINUX_CAPABILITIES*/
1178 # ifdef NEED_EARLY_FORK
1179 fork_nonchroot_worker();
1182 /* Drop super-user privileges and chroot now if the OS supports this */
1184 # ifdef HAVE_LINUX_CAPABILITIES
1185 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
1186 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
1187 msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
1190 # elif HAVE_SOLARIS_PRIVS
1191 /* Nothing to do here */
1193 /* we need a user to switch to */
1195 msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
1198 # endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
1201 if (0 == map_user())
1204 if (group != NULL) {
1205 if (0 == map_group())
1210 /* make sure cwd is inside the jail: */
1211 if (chdir(chrootdir)) {
1212 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
1215 if (chroot(chrootdir)) {
1216 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
1220 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
1224 # ifdef HAVE_SOLARIS_PRIVS
1225 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
1226 msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
1229 if ((highprivs = priv_allocset()) == NULL) {
1230 msyslog(LOG_ERR, "priv_allocset() failed:%m");
1233 (void) getppriv(PRIV_PERMITTED, highprivs);
1234 (void) priv_intersect(highprivs, lowprivs);
1235 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1236 msyslog(LOG_ERR, "setppriv() failed:%m");
1239 # endif /* HAVE_SOLARIS_PRIVS */
1240 if (0 == set_user_group_ids())
1243 # if !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1245 * for now assume that the privilege to bind to privileged ports
1246 * is associated with running with uid 0 - should be refined on
1247 * ports that allow binding to NTP_PORT with uid != 0
1249 disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */
1250 # endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1252 if (disable_dynamic_updates && interface_interval) {
1253 interface_interval = 0;
1254 msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1257 # ifdef HAVE_LINUX_CAPABILITIES
1260 * We may be running under non-root uid now, but we still hold full root privileges!
1261 * We drop all of them, except for the crucial one or two: cap_sys_time and
1262 * cap_net_bind_service if doing dynamic interface tracking.
1267 captext = (0 != interface_interval)
1268 ? "cap_sys_time,cap_net_bind_service=pe"
1269 : "cap_sys_time=pe";
1270 caps = cap_from_text(captext);
1273 "cap_from_text(%s) failed: %m",
1277 if (-1 == cap_set_proc(caps)) {
1279 "cap_set_proc() failed to drop root privs: %m");
1284 # endif /* HAVE_LINUX_CAPABILITIES */
1285 # ifdef HAVE_SOLARIS_PRIVS
1286 if (priv_delset(lowprivs, "proc_setid") == -1) {
1287 msyslog(LOG_ERR, "priv_delset() failed:%m");
1290 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1291 msyslog(LOG_ERR, "setppriv() failed:%m");
1294 priv_freeset(lowprivs);
1295 priv_freeset(highprivs);
1296 # endif /* HAVE_SOLARIS_PRIVS */
1297 root_dropped = TRUE;
1298 fork_deferred_worker();
1299 } /* if (droproot) */
1300 # endif /* HAVE_DROPROOT */
1302 /* libssecomp sandboxing */
1303 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1304 scmp_filter_ctx ctx;
1306 if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1307 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1309 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1318 SCMP_SYS(clock_gettime),
1319 SCMP_SYS(clock_settime),
1322 SCMP_SYS(exit_group),
1326 SCMP_SYS(getitimer),
1327 SCMP_SYS(getsockname),
1338 SCMP_SYS(rt_sigaction),
1339 SCMP_SYS(rt_sigprocmask),
1340 SCMP_SYS(rt_sigreturn),
1343 SCMP_SYS(setitimer),
1353 SCMP_SYS(_newselect),
1357 SCMP_SYS(clock_gettime),
1358 SCMP_SYS(clock_settime),
1360 SCMP_SYS(exit_group),
1363 SCMP_SYS(getitimer),
1372 SCMP_SYS(rt_sigaction),
1373 SCMP_SYS(rt_sigprocmask),
1375 SCMP_SYS(setitimer),
1377 SCMP_SYS(sigprocmask),
1378 SCMP_SYS(sigreturn),
1379 SCMP_SYS(socketcall),
1388 for (i = 0; i < COUNTOF(scmp_sc); i++) {
1389 if (seccomp_rule_add(ctx,
1390 SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1392 "%s: seccomp_rule_add() failed: %m",
1398 if (seccomp_load(ctx) < 0)
1399 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1402 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1404 #endif /* LIBSECCOMP and KERN_SECCOMP */
1406 #if defined(SYS_WINNT)
1408 #elif defined(HAVE_WORKING_FORK)
1409 if (daemon_pipe[1] != -1) {
1410 write(daemon_pipe[1], "R\n", 2);
1412 #endif /* HAVE_WORKING_FORK */
1414 # ifndef HAVE_IO_COMPLETION_PORT
1415 BLOCK_IO_AND_ALARM();
1416 was_alarmed = FALSE;
1420 #if !defined(SIM) && defined(SIGDIE1)
1424 # ifdef HAVE_IO_COMPLETION_PORT
1425 GetReceivedBuffers();
1427 # else /* normal I/O */
1428 if (alarm_flag) { /* alarmed? */
1433 /* collect async name/addr results */
1435 harvest_blocking_responses();
1437 if (!was_alarmed && !has_full_recv_buffer()) {
1439 * Nothing to do. Wait for something.
1444 if (alarm_flag) { /* alarmed? */
1450 UNBLOCK_IO_AND_ALARM();
1452 * Out here, signals are unblocked. Call timer routine
1453 * to process expiry.
1456 was_alarmed = FALSE;
1457 BLOCK_IO_AND_ALARM();
1460 # endif /* !HAVE_IO_COMPLETION_PORT */
1462 # ifdef DEBUG_TIMING
1471 rbuf = get_full_recv_buffer();
1472 while (rbuf != NULL) {
1477 UNBLOCK_IO_AND_ALARM();
1480 /* avoid timer starvation during lengthy I/O handling */
1482 was_alarmed = FALSE;
1486 * Call the data procedure to handle each received
1489 if (rbuf->receiver != NULL) {
1490 # ifdef DEBUG_TIMING
1493 L_SUB(&dts, &rbuf->recv_time);
1494 DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1495 collect_timing(rbuf, "buffer processing delay", 1, &dts);
1498 (*rbuf->receiver)(rbuf);
1500 msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1504 BLOCK_IO_AND_ALARM();
1506 rbuf = get_full_recv_buffer();
1508 # ifdef DEBUG_TIMING
1512 collect_timing(NULL, "processing", bufcount, &tsb);
1513 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1522 # ifdef HAVE_DNSREGISTRATION
1523 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1524 mdnsreg = current_time;
1525 msyslog(LOG_INFO, "Attempting to register mDNS");
1526 if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1527 htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1529 msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1531 msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1534 msyslog(LOG_INFO, "mDNS service registered.");
1538 # endif /* HAVE_DNSREGISTRATION */
1541 UNBLOCK_IO_AND_ALARM();
1547 #if !defined(SIM) && defined(SIGDIE1)
1549 * finish - exit gracefully
1556 const char *sig_desc;
1559 #ifdef HAVE_STRSIGNAL
1560 sig_desc = strsignal(sig);
1562 if (sig_desc == NULL)
1564 msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1566 /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1567 # ifdef HAVE_DNSREGISTRATION
1569 DNSServiceRefDeallocate(mdns);
1584 #endif /* !SIM && SIGDIE1 */
1589 * wait_child_sync_if - implements parent side of -w/--wait-sync
1591 # ifdef HAVE_WORKING_FORK
1596 unsigned long wait_sync
1601 time_t wait_end_time;
1605 struct timeval wtimeout;
1607 /* we wait a bit for the child in *any* case, because on failure
1608 * of the child we have to get and inspect the exit code!
1610 wait_end_time = time(NULL);
1612 wait_end_time += wait_sync;
1614 wait_end_time += 30;
1617 cur_time = time(NULL);
1618 wait_rem = (wait_end_time > cur_time)
1619 ? (wait_end_time - cur_time)
1621 wtimeout.tv_sec = wait_rem;
1622 wtimeout.tv_usec = 0;
1624 FD_SET(pipe_read_fd, &readset);
1625 rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1631 "daemon startup: select failed: %m");
1636 * select() indicated a timeout, but in case
1637 * its timeouts are affected by a step of the
1638 * system clock, select() again with a zero
1639 * timeout to confirm.
1642 FD_SET(pipe_read_fd, &readset);
1643 wtimeout.tv_sec = 0;
1644 wtimeout.tv_usec = 0;
1645 rc = select(pipe_read_fd + 1, &readset, NULL,
1647 if (0 == rc) /* select() timeout */
1650 rc = read(pipe_read_fd, &ch, 1);
1652 DPRINTF(2, ("daemon control: got EOF\n"));
1653 return -1; /* unexpected EOF, check daemon */
1654 } else if (rc == 1) {
1655 DPRINTF(2, ("daemon control: got '%c'\n",
1656 (ch >= ' ' ? ch : '.')));
1657 if (ch == 'R' && !wait_sync)
1659 if (ch == 'S' && wait_sync)
1662 DPRINTF(2, ("daemon control: read 1 char failed: %s\n",
1666 } while (wait_rem > 0);
1669 fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1670 progname, wait_sync);
1673 fprintf(stderr, "%s: daemon startup monitoring timed out.\n",
1686 # ifdef HAVE_WAITPID
1689 if (cpid == waitpid(cpid, &wstatus, (blocking ? 0 : WNOHANG))) {
1690 DPRINTF(1, ("child (pid=%d) dead now\n", cpid));
1691 if (WIFEXITED(wstatus)) {
1692 rc = WEXITSTATUS(wstatus);
1693 msyslog(LOG_ERR, "daemon child exited with code %d",
1695 } else if (WIFSIGNALED(wstatus)) {
1697 msyslog(LOG_ERR, "daemon child died with signal %d",
1701 msyslog(LOG_ERR, "daemon child died with unknown cause");
1704 DPRINTF(1, ("child (pid=%d) still alive\n", cpid));
1713 # endif /* HAVE_WORKING_FORK */
1717 * assertion_failed - Redirect assertion failures to msyslog().
1723 isc_assertiontype_t type,
1727 isc_assertion_setcallback(NULL); /* Avoid recursion */
1729 msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1730 file, line, isc_assertion_typetotext(type), cond);
1731 msyslog(LOG_ERR, "exiting (due to assertion failure)");
1733 #if defined(DEBUG) && defined(SYS_WINNT)
1743 * library_fatal_error - Handle fatal errors from our libraries.
1746 library_fatal_error(
1755 isc_error_setfatal(NULL); /* Avoid recursion */
1757 msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1758 vsnprintf(errbuf, sizeof(errbuf), format, args);
1759 msyslog(LOG_ERR, "%s", errbuf);
1760 msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1762 #if defined(DEBUG) && defined(SYS_WINNT)
1772 * library_unexpected_error - Handle non fatal errors from our libraries.
1774 # define MAX_UNEXPECTED_ERRORS 100
1775 int unexpected_error_cnt = 0;
1777 library_unexpected_error(
1786 if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1787 return; /* avoid clutter in log */
1789 msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1790 vsnprintf(errbuf, sizeof(errbuf), format, args);
1791 msyslog(LOG_ERR, "%s", errbuf);
1793 if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1794 msyslog(LOG_ERR, "Too many errors. Shutting up.");
1799 #if !defined(SIM) && !defined(SYS_WINNT)
1803 * moredebug - increase debugging verbosity
1810 int saved_errno = errno;
1815 msyslog(LOG_DEBUG, "debug raised to %d", debug);
1817 errno = saved_errno;
1822 * lessdebug - decrease debugging verbosity
1829 int saved_errno = errno;
1834 msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1836 errno = saved_errno;
1839 # else /* !DEBUG follows */
1843 * no_debug - We don't do the debug here.
1850 int saved_errno = errno;
1852 msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1853 errno = saved_errno;
1855 # endif /* !DEBUG */
1856 #endif /* !SIM && !SYS_WINNT */