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