ntpd.c revision 293896
1/*
2 * ntpd.c - main program for the fixed point NTP daemon
3 */
4
5#ifdef HAVE_CONFIG_H
6# include <config.h>
7#endif
8
9#include "ntp_machine.h"
10#include "ntpd.h"
11#include "ntp_io.h"
12#include "ntp_stdlib.h"
13#include <ntp_random.h>
14
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"
21#include "iosignal.h"
22
23#ifdef SIM
24# include "ntpsim.h"
25#endif
26
27#include "ntp_libopts.h"
28#include "ntpd-opts.h"
29
30/* there's a short treatise below what the thread stuff is for.
31 * [Bug 2954] enable the threading warm-up only for Linux.
32 */
33#if defined(HAVE_PTHREADS) && HAVE_PTHREADS && !defined(NO_THREADS)
34# ifdef HAVE_PTHREAD_H
35#  include <pthread.h>
36# endif
37# if defined(linux)
38#  define NEED_PTHREAD_WARMUP
39# endif
40#endif
41
42#ifdef HAVE_UNISTD_H
43# include <unistd.h>
44#endif
45#ifdef HAVE_SYS_STAT_H
46# include <sys/stat.h>
47#endif
48#include <stdio.h>
49#ifdef HAVE_SYS_PARAM_H
50# include <sys/param.h>
51#endif
52#ifdef HAVE_SYS_SIGNAL_H
53# include <sys/signal.h>
54#else
55# include <signal.h>
56#endif
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>
63# endif
64# include <sys/rtprio.h>
65#else
66# ifdef HAVE_PLOCK
67#  ifdef HAVE_SYS_LOCK_H
68#	include <sys/lock.h>
69#  endif
70# endif
71#endif
72#if defined(HAVE_SCHED_SETSCHEDULER)
73# ifdef HAVE_SCHED_H
74#  include <sched.h>
75# else
76#  ifdef HAVE_SYS_SCHED_H
77#   include <sys/sched.h>
78#  endif
79# endif
80#endif
81#if defined(HAVE_SYS_MMAN_H)
82# include <sys/mman.h>
83#endif
84
85#ifdef HAVE_TERMIOS_H
86# include <termios.h>
87#endif
88
89#ifdef SYS_DOMAINOS
90# include <apollo/base.h>
91#endif /* SYS_DOMAINOS */
92
93
94#include "recvbuff.h"
95#include "ntp_cmdargs.h"
96
97#if 0				/* HMS: I don't think we need this. 961223 */
98#ifdef LOCK_PROCESS
99# ifdef SYS_SOLARIS
100#  include <sys/mman.h>
101# else
102#  include <sys/lock.h>
103# endif
104#endif
105#endif
106
107#ifdef _AIX
108# include <ulimit.h>
109#endif /* _AIX */
110
111#ifdef SCO5_CLOCK
112# include <sys/ci/ciioctl.h>
113#endif
114
115#ifdef HAVE_DROPROOT
116# include <ctype.h>
117# include <grp.h>
118# include <pwd.h>
119#ifdef HAVE_LINUX_CAPABILITIES
120# include <sys/capability.h>
121# include <sys/prctl.h>
122#endif /* HAVE_LINUX_CAPABILITIES */
123#if defined(HAVE_PRIV_H) && defined(HAVE_SOLARIS_PRIVS)
124# include <priv.h>
125#endif /* HAVE_PRIV_H */
126#endif /* HAVE_DROPROOT */
127
128#if defined (LIBSECCOMP) && (KERN_SECCOMP)
129/* # include <sys/types.h> */
130# include <sys/resource.h>
131# include <seccomp.h>
132#endif /* LIBSECCOMP and KERN_SECCOMP */
133
134#ifdef HAVE_DNSREGISTRATION
135# include <dns_sd.h>
136DNSServiceRef mdns;
137#endif
138
139#ifdef HAVE_SETPGRP_0
140# define ntp_setpgrp(x, y)	setpgrp()
141#else
142# define ntp_setpgrp(x, y)	setpgrp(x, y)
143#endif
144
145#ifdef HAVE_SOLARIS_PRIVS
146# define LOWPRIVS "basic,sys_time,net_privaddr,proc_setid,!proc_info,!proc_session,!proc_exec"
147static priv_set_t *lowprivs = NULL;
148static priv_set_t *highprivs = NULL;
149#endif /* HAVE_SOLARIS_PRIVS */
150/*
151 * Scheduling priority we run at
152 */
153#define NTPD_PRIO	(-12)
154
155int priority_done = 2;		/* 0 - Set priority */
156				/* 1 - priority is OK where it is */
157				/* 2 - Don't set priority */
158				/* 1 and 2 are pretty much the same */
159
160int listen_to_virtual_ips = TRUE;
161
162/*
163 * No-fork flag.  If set, we do not become a background daemon.
164 */
165int nofork;			/* Fork by default */
166
167#ifdef HAVE_DNSREGISTRATION
168/*
169 * mDNS registration flag. If set, we attempt to register with the mDNS system, but only
170 * after we have synched the first time. If the attempt fails, then try again once per
171 * minute for up to 5 times. After all, we may be starting before mDNS.
172 */
173int mdnsreg = FALSE;
174int mdnstries = 5;
175#endif  /* HAVE_DNSREGISTRATION */
176
177#ifdef HAVE_DROPROOT
178int droproot;
179int root_dropped;
180char *user;		/* User to switch to */
181char *group;		/* group to switch to */
182const char *chrootdir;	/* directory to chroot to */
183uid_t sw_uid;
184gid_t sw_gid;
185char *endp;
186struct group *gr;
187struct passwd *pw;
188#endif /* HAVE_DROPROOT */
189
190#ifdef HAVE_WORKING_FORK
191int	waitsync_fd_to_close = -1;	/* -w/--wait-sync */
192#endif
193
194/*
195 * Version declaration
196 */
197extern const char *Version;
198
199char const *progname;
200
201int was_alarmed;
202
203#ifdef DECL_SYSCALL
204/*
205 * We put this here, since the argument profile is syscall-specific
206 */
207extern int syscall	(int, ...);
208#endif /* DECL_SYSCALL */
209
210
211#if !defined(SIM) && defined(SIGDIE1)
212static	RETSIGTYPE	finish		(int);
213#endif
214
215#if !defined(SIM) && defined(HAVE_WORKING_FORK)
216static int	wait_child_sync_if	(int, long);
217#endif
218
219#if !defined(SIM) && !defined(SYS_WINNT)
220# ifdef	DEBUG
221static	RETSIGTYPE	moredebug	(int);
222static	RETSIGTYPE	lessdebug	(int);
223# else	/* !DEBUG follows */
224static	RETSIGTYPE	no_debug	(int);
225# endif	/* !DEBUG */
226#endif	/* !SIM && !SYS_WINNT */
227
228int	saved_argc;
229char **	saved_argv;
230
231#ifndef SIM
232int		ntpdmain		(int, char **);
233static void	set_process_priority	(void);
234static void	assertion_failed	(const char *, int,
235					 isc_assertiontype_t,
236					 const char *)
237			__attribute__	((__noreturn__));
238static void	library_fatal_error	(const char *, int,
239					 const char *, va_list)
240					ISC_FORMAT_PRINTF(3, 0);
241static void	library_unexpected_error(const char *, int,
242					 const char *, va_list)
243					ISC_FORMAT_PRINTF(3, 0);
244#endif	/* !SIM */
245
246
247/* Bug2332 unearthed a problem in the interaction of reduced user
248 * privileges, the limits on memory usage and some versions of the
249 * pthread library on Linux systems. The 'pthread_cancel()' function and
250 * likely some others need to track the stack of the thread involved,
251 * and uses a function that comes from GCC (--> libgcc_s.so) to do
252 * this. Unfortunately the developers of glibc decided to load the
253 * library on demand, which speeds up program start but can cause
254 * trouble here: Due to all the things NTPD does to limit its resource
255 * usage, this deferred load of libgcc_s does not always work once the
256 * restrictions are in effect.
257 *
258 * One way out of this was attempting a forced link against libgcc_s
259 * when possible because it makes the library available immediately
260 * without deferred load. (The symbol resolution would still be dynamic
261 * and on demand, but the code would already be in the process image.)
262 *
263 * This is a tricky thing to do, since it's not necessary everywhere,
264 * not possible everywhere, has shown to break the build of other
265 * programs in the NTP suite and is now generally frowned upon.
266 *
267 * So we take a different approach here: We creat a worker thread that does
268 * actually nothing except waiting for cancellation and cancel it. If
269 * this is done before all the limitations are put in place, the
270 * machinery is pre-heated and all the runtime stuff should be in place
271 * and useable when needed.
272 *
273 * This uses only the standard pthread API and should work with all
274 * implementations of pthreads. It is not necessary everywhere, but it's
275 * cheap enough to go on nearly unnoticed.
276 *
277 * Addendum: Bug 2954 showed that the assumption that this should work
278 * with all OS is wrong -- at least FreeBSD bombs heavily.
279 */
280#ifdef NEED_PTHREAD_WARMUP
281
282/* simple thread function: sleep until cancelled, just to exercise
283 * thread cancellation.
284 */
285static void*
286my_pthread_warmup_worker(
287	void *thread_args)
288{
289	(void)thread_args;
290	for (;;)
291		sleep(10);
292	return NULL;
293}
294
295/* pre-heat threading: create a thread and cancel it, just to exercise
296 * thread cancellation.
297 */
298static void
299my_pthread_warmup(void)
300{
301	pthread_t thread;
302	int       rc;
303	rc = pthread_create(
304		&thread, NULL, my_pthread_warmup_worker, NULL);
305	if (0 == rc) {
306		pthread_cancel(thread);
307		pthread_join(thread, NULL);
308	}
309}
310
311#endif /*defined(NEED_PTHREAD_WARMUP)*/
312
313
314void
315parse_cmdline_opts(
316	int *	pargc,
317	char ***pargv
318	)
319{
320	static int	parsed;
321	static int	optct;
322
323	if (!parsed)
324		optct = ntpOptionProcess(&ntpdOptions, *pargc, *pargv);
325
326	parsed = 1;
327
328	*pargc -= optct;
329	*pargv += optct;
330}
331
332
333#ifdef SIM
334int
335main(
336	int argc,
337	char *argv[]
338	)
339{
340	progname = argv[0];
341	parse_cmdline_opts(&argc, &argv);
342#ifdef DEBUG
343	debug = OPT_VALUE_SET_DEBUG_LEVEL;
344	DPRINTF(1, ("%s\n", Version));
345#endif
346
347	return ntpsim(argc, argv);
348}
349#else	/* !SIM follows */
350#ifdef NO_MAIN_ALLOWED
351CALL(ntpd,"ntpd",ntpdmain);
352#else	/* !NO_MAIN_ALLOWED follows */
353#ifndef SYS_WINNT
354int
355main(
356	int argc,
357	char *argv[]
358	)
359{
360	return ntpdmain(argc, argv);
361}
362#endif /* !SYS_WINNT */
363#endif /* !NO_MAIN_ALLOWED */
364#endif /* !SIM */
365
366#ifdef _AIX
367/*
368 * OK. AIX is different than solaris in how it implements plock().
369 * If you do NOT adjust the stack limit, you will get the MAXIMUM
370 * stack size allocated and PINNED with you program. To check the
371 * value, use ulimit -a.
372 *
373 * To fix this, we create an automatic variable and set our stack limit
374 * to that PLUS 32KB of extra space (we need some headroom).
375 *
376 * This subroutine gets the stack address.
377 *
378 * Grover Davidson and Matt Ladendorf
379 *
380 */
381static char *
382get_aix_stack(void)
383{
384	char ch;
385	return (&ch);
386}
387
388/*
389 * Signal handler for SIGDANGER.
390 */
391static void
392catch_danger(int signo)
393{
394	msyslog(LOG_INFO, "ntpd: setpgid(): %m");
395	/* Make the system believe we'll free something, but don't do it! */
396	return;
397}
398#endif /* _AIX */
399
400/*
401 * Set the process priority
402 */
403#ifndef SIM
404static void
405set_process_priority(void)
406{
407
408# ifdef DEBUG
409	if (debug > 1)
410		msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>",
411			((priority_done)
412			 ? "Leave priority alone"
413			 : "Attempt to set priority"
414				),
415			priority_done);
416# endif /* DEBUG */
417
418# if defined(HAVE_SCHED_SETSCHEDULER)
419	if (!priority_done) {
420		extern int config_priority_override, config_priority;
421		int pmax, pmin;
422		struct sched_param sched;
423
424		pmax = sched_get_priority_max(SCHED_FIFO);
425		sched.sched_priority = pmax;
426		if ( config_priority_override ) {
427			pmin = sched_get_priority_min(SCHED_FIFO);
428			if ( config_priority > pmax )
429				sched.sched_priority = pmax;
430			else if ( config_priority < pmin )
431				sched.sched_priority = pmin;
432			else
433				sched.sched_priority = config_priority;
434		}
435		if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 )
436			msyslog(LOG_ERR, "sched_setscheduler(): %m");
437		else
438			++priority_done;
439	}
440# endif /* HAVE_SCHED_SETSCHEDULER */
441# ifdef HAVE_RTPRIO
442#  ifdef RTP_SET
443	if (!priority_done) {
444		struct rtprio srtp;
445
446		srtp.type = RTP_PRIO_REALTIME;	/* was: RTP_PRIO_NORMAL */
447		srtp.prio = 0;		/* 0 (hi) -> RTP_PRIO_MAX (31,lo) */
448
449		if (rtprio(RTP_SET, getpid(), &srtp) < 0)
450			msyslog(LOG_ERR, "rtprio() error: %m");
451		else
452			++priority_done;
453	}
454#  else	/* !RTP_SET follows */
455	if (!priority_done) {
456		if (rtprio(0, 120) < 0)
457			msyslog(LOG_ERR, "rtprio() error: %m");
458		else
459			++priority_done;
460	}
461#  endif	/* !RTP_SET */
462# endif	/* HAVE_RTPRIO */
463# if defined(NTPD_PRIO) && NTPD_PRIO != 0
464#  ifdef HAVE_ATT_NICE
465	if (!priority_done) {
466		errno = 0;
467		if (-1 == nice (NTPD_PRIO) && errno != 0)
468			msyslog(LOG_ERR, "nice() error: %m");
469		else
470			++priority_done;
471	}
472#  endif	/* HAVE_ATT_NICE */
473#  ifdef HAVE_BSD_NICE
474	if (!priority_done) {
475		if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO))
476			msyslog(LOG_ERR, "setpriority() error: %m");
477		else
478			++priority_done;
479	}
480#  endif	/* HAVE_BSD_NICE */
481# endif	/* NTPD_PRIO && NTPD_PRIO != 0 */
482	if (!priority_done)
483		msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority");
484}
485#endif	/* !SIM */
486
487
488/*
489 * Main program.  Initialize us, disconnect us from the tty if necessary,
490 * and loop waiting for I/O and/or timer expiries.
491 */
492#ifndef SIM
493int
494ntpdmain(
495	int argc,
496	char *argv[]
497	)
498{
499	l_fp		now;
500	struct recvbuf *rbuf;
501	const char *	logfilename;
502# ifdef HAVE_UMASK
503	mode_t		uv;
504# endif
505# if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
506	uid_t		uid;
507# endif
508# if defined(HAVE_WORKING_FORK)
509	long		wait_sync = 0;
510	int		pipe_fds[2];
511	int		rc;
512	int		exit_code;
513#  ifdef _AIX
514	struct sigaction sa;
515#  endif
516#  if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
517	int		fid;
518#  endif
519# endif	/* HAVE_WORKING_FORK*/
520# ifdef SCO5_CLOCK
521	int		fd;
522	int		zero;
523# endif
524
525# ifdef NEED_PTHREAD_WARMUP
526	my_pthread_warmup();
527# endif
528
529# ifdef HAVE_UMASK
530	uv = umask(0);
531	if (uv)
532		umask(uv);
533	else
534		umask(022);
535# endif
536	saved_argc = argc;
537	saved_argv = argv;
538	progname = argv[0];
539	initializing = TRUE;		/* mark that we are initializing */
540	parse_cmdline_opts(&argc, &argv);
541# ifdef DEBUG
542	debug = OPT_VALUE_SET_DEBUG_LEVEL;
543#  ifdef HAVE_SETLINEBUF
544	setlinebuf(stdout);
545#  endif
546# endif
547
548	if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
549# ifdef DEBUG
550	    || debug
551# endif
552	    || HAVE_OPT(SAVECONFIGQUIT))
553		nofork = TRUE;
554
555	init_logging(progname, NLOG_SYNCMASK, TRUE);
556	/* honor -l/--logfile option to log to a file */
557	if (HAVE_OPT(LOGFILE)) {
558		logfilename = OPT_ARG(LOGFILE);
559		syslogit = FALSE;
560		change_logfile(logfilename, FALSE);
561	} else {
562		logfilename = NULL;
563		if (nofork)
564			msyslog_term = TRUE;
565		if (HAVE_OPT(SAVECONFIGQUIT))
566			syslogit = FALSE;
567	}
568	msyslog(LOG_NOTICE, "%s: Starting", Version);
569
570	{
571		int i;
572		char buf[1024];	/* Secret knowledge of msyslog buf length */
573		char *cp = buf;
574
575		/* Note that every arg has an initial space character */
576		snprintf(cp, sizeof(buf), "Command line:");
577		cp += strlen(cp);
578
579		for (i = 0; i < saved_argc ; ++i) {
580			snprintf(cp, sizeof(buf) - (cp - buf),
581				" %s", saved_argv[i]);
582			cp += strlen(cp);
583		}
584		msyslog(LOG_INFO, "%s", buf);
585	}
586
587	/*
588	 * Install trap handlers to log errors and assertion failures.
589	 * Default handlers print to stderr which doesn't work if detached.
590	 */
591	isc_assertion_setcallback(assertion_failed);
592	isc_error_setfatal(library_fatal_error);
593	isc_error_setunexpected(library_unexpected_error);
594
595	/* MPE lacks the concept of root */
596# if defined(HAVE_GETUID) && !defined(MPE)
597	uid = getuid();
598	if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
599		msyslog_term = TRUE;
600		msyslog(LOG_ERR,
601			"must be run as root, not uid %ld", (long)uid);
602		exit(1);
603	}
604# endif
605
606/*
607 * Enable the Multi-Media Timer for Windows?
608 */
609# ifdef SYS_WINNT
610	if (HAVE_OPT( MODIFYMMTIMER ))
611		set_mm_timer(MM_TIMER_HIRES);
612# endif
613
614#ifdef HAVE_DNSREGISTRATION
615/*
616 * Enable mDNS registrations?
617 */
618	if (HAVE_OPT( MDNS )) {
619		mdnsreg = TRUE;
620	}
621#endif  /* HAVE_DNSREGISTRATION */
622
623	if (HAVE_OPT( NOVIRTUALIPS ))
624		listen_to_virtual_ips = 0;
625
626	/*
627	 * --interface, listen on specified interfaces
628	 */
629	if (HAVE_OPT( INTERFACE )) {
630		int		ifacect = STACKCT_OPT( INTERFACE );
631		const char**	ifaces  = STACKLST_OPT( INTERFACE );
632		sockaddr_u	addr;
633
634		while (ifacect-- > 0) {
635			add_nic_rule(
636				is_ip_address(*ifaces, AF_UNSPEC, &addr)
637					? MATCH_IFADDR
638					: MATCH_IFNAME,
639				*ifaces, -1, ACTION_LISTEN);
640			ifaces++;
641		}
642	}
643
644	if (HAVE_OPT( NICE ))
645		priority_done = 0;
646
647# ifdef HAVE_SCHED_SETSCHEDULER
648	if (HAVE_OPT( PRIORITY )) {
649		config_priority = OPT_VALUE_PRIORITY;
650		config_priority_override = 1;
651		priority_done = 0;
652	}
653# endif
654
655# ifdef HAVE_WORKING_FORK
656	/* make sure the FDs are initialised */
657	pipe_fds[0] = -1;
658	pipe_fds[1] = -1;
659	do {					/* 'loop' once */
660		if (!HAVE_OPT( WAIT_SYNC ))
661			break;
662		wait_sync = OPT_VALUE_WAIT_SYNC;
663		if (wait_sync <= 0) {
664			wait_sync = 0;
665			break;
666		}
667		/* -w requires a fork() even with debug > 0 */
668		nofork = FALSE;
669		if (pipe(pipe_fds)) {
670			exit_code = (errno) ? errno : -1;
671			msyslog(LOG_ERR,
672				"Pipe creation failed for --wait-sync: %m");
673			exit(exit_code);
674		}
675		waitsync_fd_to_close = pipe_fds[1];
676	} while (0);				/* 'loop' once */
677# endif	/* HAVE_WORKING_FORK */
678
679	init_lib();
680# ifdef SYS_WINNT
681	/*
682	 * Start interpolation thread, must occur before first
683	 * get_systime()
684	 */
685	init_winnt_time();
686# endif
687	/*
688	 * Initialize random generator and public key pair
689	 */
690	get_systime(&now);
691
692	ntp_srandom((int)(now.l_i * now.l_uf));
693
694	/*
695	 * Detach us from the terminal.  May need an #ifndef GIZMO.
696	 */
697	if (!nofork) {
698
699# ifdef HAVE_WORKING_FORK
700		rc = fork();
701		if (-1 == rc) {
702			exit_code = (errno) ? errno : -1;
703			msyslog(LOG_ERR, "fork: %m");
704			exit(exit_code);
705		}
706		if (rc > 0) {
707			/* parent */
708			exit_code = wait_child_sync_if(pipe_fds[0],
709						       wait_sync);
710			exit(exit_code);
711		}
712
713		/*
714		 * child/daemon
715		 * close all open files excepting waitsync_fd_to_close.
716		 * msyslog() unreliable until after init_logging().
717		 */
718		closelog();
719		if (syslog_file != NULL) {
720			fclose(syslog_file);
721			syslog_file = NULL;
722			syslogit = TRUE;
723		}
724		close_all_except(waitsync_fd_to_close);
725		INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
726			&& 2 == dup2(0, 2));
727
728		init_logging(progname, 0, TRUE);
729		/* we lost our logfile (if any) daemonizing */
730		setup_logfile(logfilename);
731
732#  ifdef SYS_DOMAINOS
733		{
734			uid_$t puid;
735			status_$t st;
736
737			proc2_$who_am_i(&puid);
738			proc2_$make_server(&puid, &st);
739		}
740#  endif	/* SYS_DOMAINOS */
741#  ifdef HAVE_SETSID
742		if (setsid() == (pid_t)-1)
743			msyslog(LOG_ERR, "setsid(): %m");
744#  elif defined(HAVE_SETPGID)
745		if (setpgid(0, 0) == -1)
746			msyslog(LOG_ERR, "setpgid(): %m");
747#  else		/* !HAVE_SETSID && !HAVE_SETPGID follows */
748#   ifdef TIOCNOTTY
749		fid = open("/dev/tty", 2);
750		if (fid >= 0) {
751			ioctl(fid, (u_long)TIOCNOTTY, NULL);
752			close(fid);
753		}
754#   endif	/* TIOCNOTTY */
755		ntp_setpgrp(0, getpid());
756#  endif	/* !HAVE_SETSID && !HAVE_SETPGID */
757#  ifdef _AIX
758		/* Don't get killed by low-on-memory signal. */
759		sa.sa_handler = catch_danger;
760		sigemptyset(&sa.sa_mask);
761		sa.sa_flags = SA_RESTART;
762		sigaction(SIGDANGER, &sa, NULL);
763#  endif	/* _AIX */
764# endif		/* HAVE_WORKING_FORK */
765	}
766
767# ifdef SCO5_CLOCK
768	/*
769	 * SCO OpenServer's system clock offers much more precise timekeeping
770	 * on the base CPU than the other CPUs (for multiprocessor systems),
771	 * so we must lock to the base CPU.
772	 */
773	fd = open("/dev/at1", O_RDONLY);
774	if (fd >= 0) {
775		zero = 0;
776		if (ioctl(fd, ACPU_LOCK, &zero) < 0)
777			msyslog(LOG_ERR, "cannot lock to base CPU: %m");
778		close(fd);
779	}
780# endif
781
782	/* Setup stack size in preparation for locking pages in memory. */
783# if defined(HAVE_MLOCKALL)
784#  ifdef HAVE_SETRLIMIT
785	ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
786#   ifdef RLIMIT_MEMLOCK
787	/*
788	 * The default RLIMIT_MEMLOCK is very low on Linux systems.
789	 * Unless we increase this limit malloc calls are likely to
790	 * fail if we drop root privilege.  To be useful the value
791	 * has to be larger than the largest ntpd resident set size.
792	 */
793	ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
794#   endif	/* RLIMIT_MEMLOCK */
795#  endif	/* HAVE_SETRLIMIT */
796# else	/* !HAVE_MLOCKALL follows */
797#  ifdef HAVE_PLOCK
798#   ifdef PROCLOCK
799#    ifdef _AIX
800	/*
801	 * set the stack limit for AIX for plock().
802	 * see get_aix_stack() for more info.
803	 */
804	if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
805		msyslog(LOG_ERR,
806			"Cannot adjust stack limit for plock: %m");
807#    endif	/* _AIX */
808#   endif	/* PROCLOCK */
809#  endif	/* HAVE_PLOCK */
810# endif	/* !HAVE_MLOCKALL */
811
812	/*
813	 * Set up signals we pay attention to locally.
814	 */
815# ifdef SIGDIE1
816	signal_no_reset(SIGDIE1, finish);
817	signal_no_reset(SIGDIE2, finish);
818	signal_no_reset(SIGDIE3, finish);
819	signal_no_reset(SIGDIE4, finish);
820# endif
821# ifdef SIGBUS
822	signal_no_reset(SIGBUS, finish);
823# endif
824
825# if !defined(SYS_WINNT) && !defined(VMS)
826#  ifdef DEBUG
827	(void) signal_no_reset(MOREDEBUGSIG, moredebug);
828	(void) signal_no_reset(LESSDEBUGSIG, lessdebug);
829#  else
830	(void) signal_no_reset(MOREDEBUGSIG, no_debug);
831	(void) signal_no_reset(LESSDEBUGSIG, no_debug);
832#  endif	/* DEBUG */
833# endif	/* !SYS_WINNT && !VMS */
834
835	/*
836	 * Set up signals we should never pay attention to.
837	 */
838# ifdef SIGPIPE
839	signal_no_reset(SIGPIPE, SIG_IGN);
840# endif
841
842	/*
843	 * Call the init_ routines to initialize the data structures.
844	 *
845	 * Exactly what command-line options are we expecting here?
846	 */
847	INIT_SSL();
848	init_auth();
849	init_util();
850	init_restrict();
851	init_mon();
852	init_timer();
853	init_request();
854	init_control();
855	init_peer();
856# ifdef REFCLOCK
857	init_refclock();
858# endif
859	set_process_priority();
860	init_proto();		/* Call at high priority */
861	init_io();
862	init_loopfilter();
863	mon_start(MON_ON);	/* monitor on by default now	  */
864				/* turn off in config if unwanted */
865
866	/*
867	 * Get the configuration.  This is done in a separate module
868	 * since this will definitely be different for the gizmo board.
869	 */
870	getconfig(argc, argv);
871
872	if (-1 == cur_memlock) {
873# if defined(HAVE_MLOCKALL)
874		/*
875		 * lock the process into memory
876		 */
877		if (   !HAVE_OPT(SAVECONFIGQUIT)
878#  ifdef RLIMIT_MEMLOCK
879		    && -1 != DFLT_RLIMIT_MEMLOCK
880#  endif
881		    && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
882			msyslog(LOG_ERR, "mlockall(): %m");
883# else	/* !HAVE_MLOCKALL follows */
884#  ifdef HAVE_PLOCK
885#   ifdef PROCLOCK
886		/*
887		 * lock the process into memory
888		 */
889		if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
890			msyslog(LOG_ERR, "plock(PROCLOCK): %m");
891#   else	/* !PROCLOCK follows  */
892#    ifdef TXTLOCK
893		/*
894		 * Lock text into ram
895		 */
896		if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
897			msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
898#    else	/* !TXTLOCK follows */
899		msyslog(LOG_ERR, "plock() - don't know what to lock!");
900#    endif	/* !TXTLOCK */
901#   endif	/* !PROCLOCK */
902#  endif	/* HAVE_PLOCK */
903# endif	/* !HAVE_MLOCKALL */
904	}
905
906	loop_config(LOOP_DRIFTINIT, 0);
907	report_event(EVNT_SYSRESTART, NULL, NULL);
908	initializing = FALSE;
909
910# ifdef HAVE_DROPROOT
911	if (droproot) {
912		/* Drop super-user privileges and chroot now if the OS supports this */
913
914#  ifdef HAVE_LINUX_CAPABILITIES
915		/* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
916		if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
917			msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
918			exit(-1);
919		}
920#  elif HAVE_SOLARIS_PRIVS
921		/* Nothing to do here */
922#  else
923		/* we need a user to switch to */
924		if (user == NULL) {
925			msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
926			exit(-1);
927		}
928#  endif	/* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
929
930		if (user != NULL) {
931			if (isdigit((unsigned char)*user)) {
932				sw_uid = (uid_t)strtoul(user, &endp, 0);
933				if (*endp != '\0')
934					goto getuser;
935
936				if ((pw = getpwuid(sw_uid)) != NULL) {
937					free(user);
938					user = estrdup(pw->pw_name);
939					sw_gid = pw->pw_gid;
940				} else {
941					errno = 0;
942					msyslog(LOG_ERR, "Cannot find user ID %s", user);
943					exit (-1);
944				}
945
946			} else {
947getuser:
948				errno = 0;
949				if ((pw = getpwnam(user)) != NULL) {
950					sw_uid = pw->pw_uid;
951					sw_gid = pw->pw_gid;
952				} else {
953					if (errno)
954						msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
955					else
956						msyslog(LOG_ERR, "Cannot find user `%s'", user);
957					exit (-1);
958				}
959			}
960		}
961		if (group != NULL) {
962			if (isdigit((unsigned char)*group)) {
963				sw_gid = (gid_t)strtoul(group, &endp, 0);
964				if (*endp != '\0')
965					goto getgroup;
966			} else {
967getgroup:
968				if ((gr = getgrnam(group)) != NULL) {
969					sw_gid = gr->gr_gid;
970				} else {
971					errno = 0;
972					msyslog(LOG_ERR, "Cannot find group `%s'", group);
973					exit (-1);
974				}
975			}
976		}
977
978		if (chrootdir ) {
979			/* make sure cwd is inside the jail: */
980			if (chdir(chrootdir)) {
981				msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
982				exit (-1);
983			}
984			if (chroot(chrootdir)) {
985				msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
986				exit (-1);
987			}
988			if (chdir("/")) {
989				msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
990				exit (-1);
991			}
992		}
993#  ifdef HAVE_SOLARIS_PRIVS
994		if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
995			msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
996			exit(-1);
997		}
998		if ((highprivs = priv_allocset()) == NULL) {
999			msyslog(LOG_ERR, "priv_allocset() failed:%m");
1000			exit(-1);
1001		}
1002		(void) getppriv(PRIV_PERMITTED, highprivs);
1003		(void) priv_intersect(highprivs, lowprivs);
1004		if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1005			msyslog(LOG_ERR, "setppriv() failed:%m");
1006			exit(-1);
1007		}
1008#  endif /* HAVE_SOLARIS_PRIVS */
1009		if (user && initgroups(user, sw_gid)) {
1010			msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
1011			exit (-1);
1012		}
1013		if (group && setgid(sw_gid)) {
1014			msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
1015			exit (-1);
1016		}
1017		if (group && setegid(sw_gid)) {
1018			msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
1019			exit (-1);
1020		}
1021		if (group) {
1022			if (0 != setgroups(1, &sw_gid)) {
1023				msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
1024				exit (-1);
1025			}
1026		}
1027		else if (pw)
1028			if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
1029				msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
1030				exit (-1);
1031			}
1032		if (user && setuid(sw_uid)) {
1033			msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
1034			exit (-1);
1035		}
1036		if (user && seteuid(sw_uid)) {
1037			msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
1038			exit (-1);
1039		}
1040
1041#  if !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1042		/*
1043		 * for now assume that the privilege to bind to privileged ports
1044		 * is associated with running with uid 0 - should be refined on
1045		 * ports that allow binding to NTP_PORT with uid != 0
1046		 */
1047		disable_dynamic_updates |= (sw_uid != 0);  /* also notifies routing message listener */
1048#  endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1049
1050		if (disable_dynamic_updates && interface_interval) {
1051			interface_interval = 0;
1052			msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1053		}
1054
1055#  ifdef HAVE_LINUX_CAPABILITIES
1056		{
1057			/*
1058			 *  We may be running under non-root uid now, but we still hold full root privileges!
1059			 *  We drop all of them, except for the crucial one or two: cap_sys_time and
1060			 *  cap_net_bind_service if doing dynamic interface tracking.
1061			 */
1062			cap_t caps;
1063			char *captext;
1064
1065			captext = (0 != interface_interval)
1066				      ? "cap_sys_time,cap_net_bind_service=pe"
1067				      : "cap_sys_time=pe";
1068			caps = cap_from_text(captext);
1069			if (!caps) {
1070				msyslog(LOG_ERR,
1071					"cap_from_text(%s) failed: %m",
1072					captext);
1073				exit(-1);
1074			}
1075			if (-1 == cap_set_proc(caps)) {
1076				msyslog(LOG_ERR,
1077					"cap_set_proc() failed to drop root privs: %m");
1078				exit(-1);
1079			}
1080			cap_free(caps);
1081		}
1082#  endif	/* HAVE_LINUX_CAPABILITIES */
1083#  ifdef HAVE_SOLARIS_PRIVS
1084		if (priv_delset(lowprivs, "proc_setid") == -1) {
1085			msyslog(LOG_ERR, "priv_delset() failed:%m");
1086			exit(-1);
1087		}
1088		if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1089			msyslog(LOG_ERR, "setppriv() failed:%m");
1090			exit(-1);
1091		}
1092		priv_freeset(lowprivs);
1093		priv_freeset(highprivs);
1094#  endif /* HAVE_SOLARIS_PRIVS */
1095		root_dropped = TRUE;
1096		fork_deferred_worker();
1097	}	/* if (droproot) */
1098# endif	/* HAVE_DROPROOT */
1099
1100/* libssecomp sandboxing */
1101#if defined (LIBSECCOMP) && (KERN_SECCOMP)
1102	scmp_filter_ctx ctx;
1103
1104	if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1105		msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1106	else {
1107		msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1108	}
1109
1110#ifdef __x86_64__
1111int scmp_sc[] = {
1112	SCMP_SYS(adjtimex),
1113	SCMP_SYS(bind),
1114	SCMP_SYS(brk),
1115	SCMP_SYS(chdir),
1116	SCMP_SYS(clock_gettime),
1117	SCMP_SYS(clock_settime),
1118	SCMP_SYS(close),
1119	SCMP_SYS(connect),
1120	SCMP_SYS(exit_group),
1121	SCMP_SYS(fstat),
1122	SCMP_SYS(fsync),
1123	SCMP_SYS(futex),
1124	SCMP_SYS(getitimer),
1125	SCMP_SYS(getsockname),
1126	SCMP_SYS(ioctl),
1127	SCMP_SYS(lseek),
1128	SCMP_SYS(madvise),
1129	SCMP_SYS(mmap),
1130	SCMP_SYS(munmap),
1131	SCMP_SYS(open),
1132	SCMP_SYS(poll),
1133	SCMP_SYS(read),
1134	SCMP_SYS(recvmsg),
1135	SCMP_SYS(rename),
1136	SCMP_SYS(rt_sigaction),
1137	SCMP_SYS(rt_sigprocmask),
1138	SCMP_SYS(rt_sigreturn),
1139	SCMP_SYS(select),
1140	SCMP_SYS(sendto),
1141	SCMP_SYS(setitimer),
1142	SCMP_SYS(setsid),
1143	SCMP_SYS(socket),
1144	SCMP_SYS(stat),
1145	SCMP_SYS(time),
1146	SCMP_SYS(write),
1147};
1148#endif
1149#ifdef __i386__
1150int scmp_sc[] = {
1151	SCMP_SYS(_newselect),
1152	SCMP_SYS(adjtimex),
1153	SCMP_SYS(brk),
1154	SCMP_SYS(chdir),
1155	SCMP_SYS(clock_gettime),
1156	SCMP_SYS(clock_settime),
1157	SCMP_SYS(close),
1158	SCMP_SYS(exit_group),
1159	SCMP_SYS(fsync),
1160	SCMP_SYS(futex),
1161	SCMP_SYS(getitimer),
1162	SCMP_SYS(madvise),
1163	SCMP_SYS(mmap),
1164	SCMP_SYS(mmap2),
1165	SCMP_SYS(munmap),
1166	SCMP_SYS(open),
1167	SCMP_SYS(poll),
1168	SCMP_SYS(read),
1169	SCMP_SYS(rename),
1170	SCMP_SYS(rt_sigaction),
1171	SCMP_SYS(rt_sigprocmask),
1172	SCMP_SYS(select),
1173	SCMP_SYS(setitimer),
1174	SCMP_SYS(setsid),
1175	SCMP_SYS(sigprocmask),
1176	SCMP_SYS(sigreturn),
1177	SCMP_SYS(socketcall),
1178	SCMP_SYS(stat64),
1179	SCMP_SYS(time),
1180	SCMP_SYS(write),
1181};
1182#endif
1183	{
1184		int i;
1185
1186		for (i = 0; i < COUNTOF(scmp_sc); i++) {
1187			if (seccomp_rule_add(ctx,
1188			    SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1189				msyslog(LOG_ERR,
1190				    "%s: seccomp_rule_add() failed: %m",
1191				    __func__);
1192			}
1193		}
1194	}
1195
1196	if (seccomp_load(ctx) < 0)
1197		msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1198		    __func__);
1199	else {
1200		msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1201	}
1202#endif /* LIBSECCOMP and KERN_SECCOMP */
1203
1204# ifdef HAVE_IO_COMPLETION_PORT
1205
1206	for (;;) {
1207		GetReceivedBuffers();
1208# else /* normal I/O */
1209
1210	BLOCK_IO_AND_ALARM();
1211	was_alarmed = FALSE;
1212
1213	for (;;) {
1214		if (alarm_flag) {	/* alarmed? */
1215			was_alarmed = TRUE;
1216			alarm_flag = FALSE;
1217		}
1218
1219		if (!was_alarmed && !has_full_recv_buffer()) {
1220			/*
1221			 * Nothing to do.  Wait for something.
1222			 */
1223			io_handler();
1224		}
1225
1226		if (alarm_flag) {	/* alarmed? */
1227			was_alarmed = TRUE;
1228			alarm_flag = FALSE;
1229		}
1230
1231		if (was_alarmed) {
1232			UNBLOCK_IO_AND_ALARM();
1233			/*
1234			 * Out here, signals are unblocked.  Call timer routine
1235			 * to process expiry.
1236			 */
1237			timer();
1238			was_alarmed = FALSE;
1239			BLOCK_IO_AND_ALARM();
1240		}
1241
1242# endif		/* !HAVE_IO_COMPLETION_PORT */
1243
1244# ifdef DEBUG_TIMING
1245		{
1246			l_fp pts;
1247			l_fp tsa, tsb;
1248			int bufcount = 0;
1249
1250			get_systime(&pts);
1251			tsa = pts;
1252# endif
1253			rbuf = get_full_recv_buffer();
1254			while (rbuf != NULL) {
1255				if (alarm_flag) {
1256					was_alarmed = TRUE;
1257					alarm_flag = FALSE;
1258				}
1259				UNBLOCK_IO_AND_ALARM();
1260
1261				if (was_alarmed) {
1262					/* avoid timer starvation during lengthy I/O handling */
1263					timer();
1264					was_alarmed = FALSE;
1265				}
1266
1267				/*
1268				 * Call the data procedure to handle each received
1269				 * packet.
1270				 */
1271				if (rbuf->receiver != NULL) {
1272# ifdef DEBUG_TIMING
1273					l_fp dts = pts;
1274
1275					L_SUB(&dts, &rbuf->recv_time);
1276					DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1277					collect_timing(rbuf, "buffer processing delay", 1, &dts);
1278					bufcount++;
1279# endif
1280					(*rbuf->receiver)(rbuf);
1281				} else {
1282					msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1283					abort();
1284				}
1285
1286				BLOCK_IO_AND_ALARM();
1287				freerecvbuf(rbuf);
1288				rbuf = get_full_recv_buffer();
1289			}
1290# ifdef DEBUG_TIMING
1291			get_systime(&tsb);
1292			L_SUB(&tsb, &tsa);
1293			if (bufcount) {
1294				collect_timing(NULL, "processing", bufcount, &tsb);
1295				DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1296			}
1297		}
1298# endif
1299
1300		/*
1301		 * Go around again
1302		 */
1303
1304# ifdef HAVE_DNSREGISTRATION
1305		if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1306			mdnsreg = current_time;
1307			msyslog(LOG_INFO, "Attempting to register mDNS");
1308			if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1309			    htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1310				if (!--mdnstries) {
1311					msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1312				} else {
1313					msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1314				}
1315			} else {
1316				msyslog(LOG_INFO, "mDNS service registered.");
1317				mdnsreg = FALSE;
1318			}
1319		}
1320# endif /* HAVE_DNSREGISTRATION */
1321
1322	}
1323	UNBLOCK_IO_AND_ALARM();
1324	return 1;
1325}
1326#endif	/* !SIM */
1327
1328
1329#if !defined(SIM) && defined(SIGDIE1)
1330/*
1331 * finish - exit gracefully
1332 */
1333static RETSIGTYPE
1334finish(
1335	int sig
1336	)
1337{
1338	const char *sig_desc;
1339
1340	sig_desc = NULL;
1341#ifdef HAVE_STRSIGNAL
1342	sig_desc = strsignal(sig);
1343#endif
1344	if (sig_desc == NULL)
1345		sig_desc = "";
1346	msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1347		sig, sig_desc);
1348	/* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1349# ifdef HAVE_DNSREGISTRATION
1350	if (mdns != NULL)
1351		DNSServiceRefDeallocate(mdns);
1352# endif
1353	peer_cleanup();
1354	exit(0);
1355}
1356#endif	/* !SIM && SIGDIE1 */
1357
1358
1359#ifndef SIM
1360/*
1361 * wait_child_sync_if - implements parent side of -w/--wait-sync
1362 */
1363# ifdef HAVE_WORKING_FORK
1364static int
1365wait_child_sync_if(
1366	int	pipe_read_fd,
1367	long	wait_sync
1368	)
1369{
1370	int	rc;
1371	int	exit_code;
1372	time_t	wait_end_time;
1373	time_t	cur_time;
1374	time_t	wait_rem;
1375	fd_set	readset;
1376	struct timeval wtimeout;
1377
1378	if (0 == wait_sync)
1379		return 0;
1380
1381	/* waitsync_fd_to_close used solely by child */
1382	close(waitsync_fd_to_close);
1383	wait_end_time = time(NULL) + wait_sync;
1384	do {
1385		cur_time = time(NULL);
1386		wait_rem = (wait_end_time > cur_time)
1387				? (wait_end_time - cur_time)
1388				: 0;
1389		wtimeout.tv_sec = wait_rem;
1390		wtimeout.tv_usec = 0;
1391		FD_ZERO(&readset);
1392		FD_SET(pipe_read_fd, &readset);
1393		rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1394			    &wtimeout);
1395		if (-1 == rc) {
1396			if (EINTR == errno)
1397				continue;
1398			exit_code = (errno) ? errno : -1;
1399			msyslog(LOG_ERR,
1400				"--wait-sync select failed: %m");
1401			return exit_code;
1402		}
1403		if (0 == rc) {
1404			/*
1405			 * select() indicated a timeout, but in case
1406			 * its timeouts are affected by a step of the
1407			 * system clock, select() again with a zero
1408			 * timeout to confirm.
1409			 */
1410			FD_ZERO(&readset);
1411			FD_SET(pipe_read_fd, &readset);
1412			wtimeout.tv_sec = 0;
1413			wtimeout.tv_usec = 0;
1414			rc = select(pipe_read_fd + 1, &readset, NULL,
1415				    NULL, &wtimeout);
1416			if (0 == rc)	/* select() timeout */
1417				break;
1418			else		/* readable */
1419				return 0;
1420		} else			/* readable */
1421			return 0;
1422	} while (wait_rem > 0);
1423
1424	fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1425		progname, wait_sync);
1426	return ETIMEDOUT;
1427}
1428# endif	/* HAVE_WORKING_FORK */
1429
1430
1431/*
1432 * assertion_failed - Redirect assertion failures to msyslog().
1433 */
1434static void
1435assertion_failed(
1436	const char *file,
1437	int line,
1438	isc_assertiontype_t type,
1439	const char *cond
1440	)
1441{
1442	isc_assertion_setcallback(NULL);    /* Avoid recursion */
1443
1444	msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1445		file, line, isc_assertion_typetotext(type), cond);
1446	msyslog(LOG_ERR, "exiting (due to assertion failure)");
1447
1448#if defined(DEBUG) && defined(SYS_WINNT)
1449	if (debug)
1450		DebugBreak();
1451#endif
1452
1453	abort();
1454}
1455
1456
1457/*
1458 * library_fatal_error - Handle fatal errors from our libraries.
1459 */
1460static void
1461library_fatal_error(
1462	const char *file,
1463	int line,
1464	const char *format,
1465	va_list args
1466	)
1467{
1468	char errbuf[256];
1469
1470	isc_error_setfatal(NULL);  /* Avoid recursion */
1471
1472	msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1473	vsnprintf(errbuf, sizeof(errbuf), format, args);
1474	msyslog(LOG_ERR, "%s", errbuf);
1475	msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1476
1477#if defined(DEBUG) && defined(SYS_WINNT)
1478	if (debug)
1479		DebugBreak();
1480#endif
1481
1482	abort();
1483}
1484
1485
1486/*
1487 * library_unexpected_error - Handle non fatal errors from our libraries.
1488 */
1489# define MAX_UNEXPECTED_ERRORS 100
1490int unexpected_error_cnt = 0;
1491static void
1492library_unexpected_error(
1493	const char *file,
1494	int line,
1495	const char *format,
1496	va_list args
1497	)
1498{
1499	char errbuf[256];
1500
1501	if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1502		return;	/* avoid clutter in log */
1503
1504	msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1505	vsnprintf(errbuf, sizeof(errbuf), format, args);
1506	msyslog(LOG_ERR, "%s", errbuf);
1507
1508	if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1509		msyslog(LOG_ERR, "Too many errors.  Shutting up.");
1510
1511}
1512#endif	/* !SIM */
1513
1514#if !defined(SIM) && !defined(SYS_WINNT)
1515# ifdef DEBUG
1516
1517/*
1518 * moredebug - increase debugging verbosity
1519 */
1520static RETSIGTYPE
1521moredebug(
1522	int sig
1523	)
1524{
1525	int saved_errno = errno;
1526
1527	if (debug < 255)
1528	{
1529		debug++;
1530		msyslog(LOG_DEBUG, "debug raised to %d", debug);
1531	}
1532	errno = saved_errno;
1533}
1534
1535
1536/*
1537 * lessdebug - decrease debugging verbosity
1538 */
1539static RETSIGTYPE
1540lessdebug(
1541	int sig
1542	)
1543{
1544	int saved_errno = errno;
1545
1546	if (debug > 0)
1547	{
1548		debug--;
1549		msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1550	}
1551	errno = saved_errno;
1552}
1553
1554# else	/* !DEBUG follows */
1555
1556
1557/*
1558 * no_debug - We don't do the debug here.
1559 */
1560static RETSIGTYPE
1561no_debug(
1562	int sig
1563	)
1564{
1565	int saved_errno = errno;
1566
1567	msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1568	errno = saved_errno;
1569}
1570# endif	/* !DEBUG */
1571#endif	/* !SIM && !SYS_WINNT */
1572