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