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