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