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