xref: /freebsd/contrib/ntp/ntpd/ntpd.c (revision 42249ef2)
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 # ifdef HAVE_WORKING_FORK
538 static void
539 detach_from_terminal(
540 	int pipe_fds[2],
541 	long wait_sync,
542 	const char *logfilename
543 	)
544 {
545 	int rc;
546 	int exit_code;
547 #  if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
548 	int		fid;
549 #  endif
550 #  ifdef _AIX
551 	struct sigaction sa;
552 #  endif
553 
554 	rc = fork();
555 	if (-1 == rc) {
556 		exit_code = (errno) ? errno : -1;
557 		msyslog(LOG_ERR, "fork: %m");
558 		exit(exit_code);
559 	}
560 	if (rc > 0) {
561 		/* parent */
562 		exit_code = wait_child_sync_if(pipe_fds[0],
563 					       wait_sync);
564 		exit(exit_code);
565 	}
566 
567 	/*
568 	 * child/daemon
569 	 * close all open files excepting waitsync_fd_to_close.
570 	 * msyslog() unreliable until after init_logging().
571 	 */
572 	closelog();
573 	if (syslog_file != NULL) {
574 		fclose(syslog_file);
575 		syslog_file = NULL;
576 		syslogit = TRUE;
577 	}
578 	close_all_except(waitsync_fd_to_close);
579 	INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
580 		&& 2 == dup2(0, 2));
581 
582 	init_logging(progname, 0, TRUE);
583 	/* we lost our logfile (if any) daemonizing */
584 	setup_logfile(logfilename);
585 
586 #  ifdef SYS_DOMAINOS
587 	{
588 		uid_$t puid;
589 		status_$t st;
590 
591 		proc2_$who_am_i(&puid);
592 		proc2_$make_server(&puid, &st);
593 	}
594 #  endif	/* SYS_DOMAINOS */
595 #  ifdef HAVE_SETSID
596 	if (setsid() == (pid_t)-1)
597 		msyslog(LOG_ERR, "setsid(): %m");
598 #  elif defined(HAVE_SETPGID)
599 	if (setpgid(0, 0) == -1)
600 		msyslog(LOG_ERR, "setpgid(): %m");
601 #  else		/* !HAVE_SETSID && !HAVE_SETPGID follows */
602 #   ifdef TIOCNOTTY
603 	fid = open("/dev/tty", 2);
604 	if (fid >= 0) {
605 		ioctl(fid, (u_long)TIOCNOTTY, NULL);
606 		close(fid);
607 	}
608 #   endif	/* TIOCNOTTY */
609 	ntp_setpgrp(0, getpid());
610 #  endif	/* !HAVE_SETSID && !HAVE_SETPGID */
611 #  ifdef _AIX
612 	/* Don't get killed by low-on-memory signal. */
613 	sa.sa_handler = catch_danger;
614 	sigemptyset(&sa.sa_mask);
615 	sa.sa_flags = SA_RESTART;
616 	sigaction(SIGDANGER, &sa, NULL);
617 #  endif	/* _AIX */
618 
619 	return;
620 }
621 # endif /* HAVE_WORKING_FORK */
622 
623 #ifdef HAVE_DROPROOT
624 /*
625  * Map user name/number to user ID
626 */
627 static int
628 map_user(
629 	)
630 {
631 	char *endp;
632 
633 	if (isdigit((unsigned char)*user)) {
634 		sw_uid = (uid_t)strtoul(user, &endp, 0);
635 		if (*endp != '\0')
636 			goto getuser;
637 
638 		if ((pw = getpwuid(sw_uid)) != NULL) {
639 			free(user);
640 			user = estrdup(pw->pw_name);
641 			sw_gid = pw->pw_gid;
642 		} else {
643 			errno = 0;
644 			msyslog(LOG_ERR, "Cannot find user ID %s", user);
645 			return 0;
646 		}
647 
648 	} else {
649 getuser:
650 		errno = 0;
651 		if ((pw = getpwnam(user)) != NULL) {
652 			sw_uid = pw->pw_uid;
653 			sw_gid = pw->pw_gid;
654 		} else {
655 			if (errno)
656 				msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
657 			else
658 				msyslog(LOG_ERR, "Cannot find user `%s'", user);
659 			return 0;
660 		}
661 	}
662 
663 	return 1;
664 }
665 
666 /*
667  * Map group name/number to group ID
668 */
669 static int
670 map_group(void)
671 {
672 	char *endp;
673 
674 	if (isdigit((unsigned char)*group)) {
675 		sw_gid = (gid_t)strtoul(group, &endp, 0);
676 		if (*endp != '\0')
677 			goto getgroup;
678 	} else {
679 getgroup:
680 		if ((gr = getgrnam(group)) != NULL) {
681 			sw_gid = gr->gr_gid;
682 		} else {
683 			errno = 0;
684 			msyslog(LOG_ERR, "Cannot find group `%s'", group);
685 			return 0;
686 		}
687 	}
688 
689 	return 1;
690 }
691 
692 static int
693 set_group_ids(void)
694 {
695 	if (user && initgroups(user, sw_gid)) {
696 		msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
697 		return 0;
698 	}
699 	if (group && setgid(sw_gid)) {
700 		msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
701 		return 0;
702 	}
703 	if (group && setegid(sw_gid)) {
704 		msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
705 		return 0;
706 	}
707 	if (group) {
708 		if (0 != setgroups(1, &sw_gid)) {
709 			msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
710 			return 0;
711 		}
712 	}
713 	else if (pw)
714 		if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
715 			msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
716 			return 0;
717 		}
718 	return 1;
719 }
720 
721 static int
722 set_user_ids(void)
723 {
724 	if (user && setuid(sw_uid)) {
725 		msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
726 		return 0;
727 	}
728 	if (user && seteuid(sw_uid)) {
729 		msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
730 		return 0;
731 	}
732 	return 1;
733 }
734 
735 /*
736  * Change (effective) user and group IDs, also initialize the supplementary group access list
737  */
738 int set_user_group_ids(void);
739 int
740 set_user_group_ids(void)
741 {
742 	/* If the the user was already mapped, no need to map it again */
743 	if ((NULL != user) && (0 == sw_uid)) {
744 		if (0 == map_user())
745 			exit (-1);
746 	}
747 	/* same applies for the group */
748 	if ((NULL != group) && (0 == sw_gid)) {
749 		if (0 == map_group())
750 			exit (-1);
751 	}
752 
753 	if (getegid() != sw_gid && 0 == set_group_ids())
754 		return 0;
755 	if (geteuid() != sw_uid && 0 == set_user_ids())
756 		return 0;
757 
758 	return 1;
759 }
760 #endif /* HAVE_DROPROOT */
761 #endif /* !SIM */
762 
763 /*
764  * Main program.  Initialize us, disconnect us from the tty if necessary,
765  * and loop waiting for I/O and/or timer expiries.
766  */
767 #ifndef SIM
768 int
769 ntpdmain(
770 	int argc,
771 	char *argv[]
772 	)
773 {
774 	l_fp		now;
775 	struct recvbuf *rbuf;
776 	const char *	logfilename;
777 # ifdef HAVE_UMASK
778 	mode_t		uv;
779 # endif
780 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
781 	uid_t		uid;
782 # endif
783 # if defined(HAVE_WORKING_FORK)
784 	long		wait_sync = 0;
785 	int		pipe_fds[2];
786 	int		rc;
787 	int		exit_code;
788 # endif	/* HAVE_WORKING_FORK*/
789 # ifdef SCO5_CLOCK
790 	int		fd;
791 	int		zero;
792 # endif
793 
794 # ifdef NEED_PTHREAD_WARMUP
795 	my_pthread_warmup();
796 # endif
797 
798 # ifdef HAVE_UMASK
799 	uv = umask(0);
800 	if (uv)
801 		umask(uv);
802 	else
803 		umask(022);
804 # endif
805 	saved_argc = argc;
806 	saved_argv = argv;
807 	progname = argv[0];
808 	initializing = TRUE;		/* mark that we are initializing */
809 	parse_cmdline_opts(&argc, &argv);
810 # ifdef DEBUG
811 	debug = OPT_VALUE_SET_DEBUG_LEVEL;
812 #  ifdef HAVE_SETLINEBUF
813 	setlinebuf(stdout);
814 #  endif
815 # endif
816 
817 	if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
818 # ifdef DEBUG
819 	    || debug
820 # endif
821 	    || HAVE_OPT(SAVECONFIGQUIT))
822 		nofork = TRUE;
823 
824 	init_logging(progname, NLOG_SYNCMASK, TRUE);
825 	/* honor -l/--logfile option to log to a file */
826 	if (HAVE_OPT(LOGFILE)) {
827 		logfilename = OPT_ARG(LOGFILE);
828 		syslogit = FALSE;
829 		change_logfile(logfilename, FALSE);
830 	} else {
831 		logfilename = NULL;
832 		if (nofork)
833 			msyslog_term = TRUE;
834 		if (HAVE_OPT(SAVECONFIGQUIT))
835 			syslogit = FALSE;
836 	}
837 	msyslog(LOG_NOTICE, "%s: Starting", Version);
838 
839 	{
840 		int i;
841 		char buf[1024];	/* Secret knowledge of msyslog buf length */
842 		char *cp = buf;
843 
844 		/* Note that every arg has an initial space character */
845 		snprintf(cp, sizeof(buf), "Command line:");
846 		cp += strlen(cp);
847 
848 		for (i = 0; i < saved_argc ; ++i) {
849 			snprintf(cp, sizeof(buf) - (cp - buf),
850 				" %s", saved_argv[i]);
851 			cp += strlen(cp);
852 		}
853 		msyslog(LOG_INFO, "%s", buf);
854 	}
855 
856 	/*
857 	 * Install trap handlers to log errors and assertion failures.
858 	 * Default handlers print to stderr which doesn't work if detached.
859 	 */
860 	isc_assertion_setcallback(assertion_failed);
861 	isc_error_setfatal(library_fatal_error);
862 	isc_error_setunexpected(library_unexpected_error);
863 
864 	/* MPE lacks the concept of root */
865 # if defined(HAVE_GETUID) && !defined(MPE)
866 	uid = getuid();
867 	if (uid && !HAVE_OPT( SAVECONFIGQUIT )
868 #  if defined(HAVE_TRUSTEDBSD_MAC)
869 	    /* We can run as non-root if the mac_ntpd policy is enabled. */
870 	    && mac_is_present("ntpd") != 1
871 #  endif
872 	    ) {
873 		msyslog_term = TRUE;
874 		msyslog(LOG_ERR,
875 			"must be run as root, not uid %ld", (long)uid);
876 		exit(1);
877 	}
878 # endif
879 
880 /*
881  * Enable the Multi-Media Timer for Windows?
882  */
883 # ifdef SYS_WINNT
884 	if (HAVE_OPT( MODIFYMMTIMER ))
885 		set_mm_timer(MM_TIMER_HIRES);
886 # endif
887 
888 #ifdef HAVE_DNSREGISTRATION
889 /*
890  * Enable mDNS registrations?
891  */
892 	if (HAVE_OPT( MDNS )) {
893 		mdnsreg = TRUE;
894 	}
895 #endif  /* HAVE_DNSREGISTRATION */
896 
897 	if (HAVE_OPT( NOVIRTUALIPS ))
898 		listen_to_virtual_ips = 0;
899 
900 	/*
901 	 * --interface, listen on specified interfaces
902 	 */
903 	if (HAVE_OPT( INTERFACE )) {
904 		int		ifacect = STACKCT_OPT( INTERFACE );
905 		const char**	ifaces  = STACKLST_OPT( INTERFACE );
906 		sockaddr_u	addr;
907 
908 		while (ifacect-- > 0) {
909 			add_nic_rule(
910 				is_ip_address(*ifaces, AF_UNSPEC, &addr)
911 					? MATCH_IFADDR
912 					: MATCH_IFNAME,
913 				*ifaces, -1, ACTION_LISTEN);
914 			ifaces++;
915 		}
916 	}
917 
918 	if (HAVE_OPT( NICE ))
919 		priority_done = 0;
920 
921 # ifdef HAVE_SCHED_SETSCHEDULER
922 	if (HAVE_OPT( PRIORITY )) {
923 		config_priority = OPT_VALUE_PRIORITY;
924 		config_priority_override = 1;
925 		priority_done = 0;
926 	}
927 # endif
928 
929 # ifdef HAVE_WORKING_FORK
930 	/* make sure the FDs are initialised */
931 	pipe_fds[0] = -1;
932 	pipe_fds[1] = -1;
933 	do {					/* 'loop' once */
934 		if (!HAVE_OPT( WAIT_SYNC ))
935 			break;
936 		wait_sync = OPT_VALUE_WAIT_SYNC;
937 		if (wait_sync <= 0) {
938 			wait_sync = 0;
939 			break;
940 		}
941 		/* -w requires a fork() even with debug > 0 */
942 		nofork = FALSE;
943 		if (pipe(pipe_fds)) {
944 			exit_code = (errno) ? errno : -1;
945 			msyslog(LOG_ERR,
946 				"Pipe creation failed for --wait-sync: %m");
947 			exit(exit_code);
948 		}
949 		waitsync_fd_to_close = pipe_fds[1];
950 	} while (0);				/* 'loop' once */
951 # endif	/* HAVE_WORKING_FORK */
952 
953 	init_lib();
954 # ifdef SYS_WINNT
955 	/*
956 	 * Make sure the service is initialized before we do anything else
957 	 */
958 	ntservice_init();
959 
960 	/*
961 	 * Start interpolation thread, must occur before first
962 	 * get_systime()
963 	 */
964 	init_winnt_time();
965 # endif
966 	/*
967 	 * Initialize random generator and public key pair
968 	 */
969 	get_systime(&now);
970 
971 	ntp_srandom((int)(now.l_i * now.l_uf));
972 
973 	/*
974 	 * Detach us from the terminal.  May need an #ifndef GIZMO.
975 	 */
976 	if (!nofork) {
977 
978 # ifdef HAVE_WORKING_FORK
979 		detach_from_terminal(pipe_fds, wait_sync, logfilename);
980 # endif		/* HAVE_WORKING_FORK */
981 	}
982 
983 # ifdef SCO5_CLOCK
984 	/*
985 	 * SCO OpenServer's system clock offers much more precise timekeeping
986 	 * on the base CPU than the other CPUs (for multiprocessor systems),
987 	 * so we must lock to the base CPU.
988 	 */
989 	fd = open("/dev/at1", O_RDONLY);
990 	if (fd >= 0) {
991 		zero = 0;
992 		if (ioctl(fd, ACPU_LOCK, &zero) < 0)
993 			msyslog(LOG_ERR, "cannot lock to base CPU: %m");
994 		close(fd);
995 	}
996 # endif
997 
998 	/* Setup stack size in preparation for locking pages in memory. */
999 # if defined(HAVE_MLOCKALL)
1000 #  ifdef HAVE_SETRLIMIT
1001 	ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
1002 #   ifdef RLIMIT_MEMLOCK
1003 	/*
1004 	 * The default RLIMIT_MEMLOCK is very low on Linux systems.
1005 	 * Unless we increase this limit malloc calls are likely to
1006 	 * fail if we drop root privilege.  To be useful the value
1007 	 * has to be larger than the largest ntpd resident set size.
1008 	 */
1009 	ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
1010 #   endif	/* RLIMIT_MEMLOCK */
1011 #  endif	/* HAVE_SETRLIMIT */
1012 # else	/* !HAVE_MLOCKALL follows */
1013 #  ifdef HAVE_PLOCK
1014 #   ifdef PROCLOCK
1015 #    ifdef _AIX
1016 	/*
1017 	 * set the stack limit for AIX for plock().
1018 	 * see get_aix_stack() for more info.
1019 	 */
1020 	if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
1021 		msyslog(LOG_ERR,
1022 			"Cannot adjust stack limit for plock: %m");
1023 #    endif	/* _AIX */
1024 #   endif	/* PROCLOCK */
1025 #  endif	/* HAVE_PLOCK */
1026 # endif	/* !HAVE_MLOCKALL */
1027 
1028 	/*
1029 	 * Set up signals we pay attention to locally.
1030 	 */
1031 # ifdef SIGDIE1
1032 	signal_no_reset(SIGDIE1, finish);
1033 	signal_no_reset(SIGDIE2, finish);
1034 	signal_no_reset(SIGDIE3, finish);
1035 	signal_no_reset(SIGDIE4, finish);
1036 # endif
1037 # ifdef SIGBUS
1038 	signal_no_reset(SIGBUS, finish);
1039 # endif
1040 
1041 # if !defined(SYS_WINNT) && !defined(VMS)
1042 #  ifdef DEBUG
1043 	(void) signal_no_reset(MOREDEBUGSIG, moredebug);
1044 	(void) signal_no_reset(LESSDEBUGSIG, lessdebug);
1045 #  else
1046 	(void) signal_no_reset(MOREDEBUGSIG, no_debug);
1047 	(void) signal_no_reset(LESSDEBUGSIG, no_debug);
1048 #  endif	/* DEBUG */
1049 # endif	/* !SYS_WINNT && !VMS */
1050 
1051 	/*
1052 	 * Set up signals we should never pay attention to.
1053 	 */
1054 # ifdef SIGPIPE
1055 	signal_no_reset(SIGPIPE, SIG_IGN);
1056 # endif
1057 
1058 	/*
1059 	 * Call the init_ routines to initialize the data structures.
1060 	 *
1061 	 * Exactly what command-line options are we expecting here?
1062 	 */
1063 	INIT_SSL();
1064 	init_auth();
1065 	init_util();
1066 	init_restrict();
1067 	init_mon();
1068 	init_timer();
1069 	init_request();
1070 	init_control();
1071 	init_peer();
1072 # ifdef REFCLOCK
1073 	init_refclock();
1074 # endif
1075 	set_process_priority();
1076 	init_proto();		/* Call at high priority */
1077 	init_io();
1078 	init_loopfilter();
1079 	mon_start(MON_ON);	/* monitor on by default now	  */
1080 				/* turn off in config if unwanted */
1081 
1082 	/*
1083 	 * Get the configuration.  This is done in a separate module
1084 	 * since this will definitely be different for the gizmo board.
1085 	 */
1086 	getconfig(argc, argv);
1087 
1088 	if (-1 == cur_memlock) {
1089 # if defined(HAVE_MLOCKALL)
1090 		/*
1091 		 * lock the process into memory
1092 		 */
1093 		if (   !HAVE_OPT(SAVECONFIGQUIT)
1094 #  ifdef RLIMIT_MEMLOCK
1095 		    && -1 != DFLT_RLIMIT_MEMLOCK
1096 #  endif
1097 		    && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
1098 			msyslog(LOG_ERR, "mlockall(): %m");
1099 # else	/* !HAVE_MLOCKALL follows */
1100 #  ifdef HAVE_PLOCK
1101 #   ifdef PROCLOCK
1102 		/*
1103 		 * lock the process into memory
1104 		 */
1105 		if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
1106 			msyslog(LOG_ERR, "plock(PROCLOCK): %m");
1107 #   else	/* !PROCLOCK follows  */
1108 #    ifdef TXTLOCK
1109 		/*
1110 		 * Lock text into ram
1111 		 */
1112 		if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
1113 			msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
1114 #    else	/* !TXTLOCK follows */
1115 		msyslog(LOG_ERR, "plock() - don't know what to lock!");
1116 #    endif	/* !TXTLOCK */
1117 #   endif	/* !PROCLOCK */
1118 #  endif	/* HAVE_PLOCK */
1119 # endif	/* !HAVE_MLOCKALL */
1120 	}
1121 
1122 	loop_config(LOOP_DRIFTINIT, 0);
1123 	report_event(EVNT_SYSRESTART, NULL, NULL);
1124 	initializing = FALSE;
1125 
1126 # ifdef HAVE_DROPROOT
1127 	if (droproot) {
1128 
1129 #ifdef NEED_EARLY_FORK
1130 		fork_nonchroot_worker();
1131 #endif
1132 
1133 		/* Drop super-user privileges and chroot now if the OS supports this */
1134 
1135 #  ifdef HAVE_LINUX_CAPABILITIES
1136 		/* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
1137 		if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
1138 			msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
1139 			exit(-1);
1140 		}
1141 #  elif HAVE_SOLARIS_PRIVS
1142 		/* Nothing to do here */
1143 #  else
1144 		/* we need a user to switch to */
1145 		if (user == NULL) {
1146 			msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
1147 			exit(-1);
1148 		}
1149 #  endif	/* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
1150 
1151 		if (user != NULL) {
1152 			if (0 == map_user())
1153 				exit (-1);
1154 		}
1155 		if (group != NULL) {
1156 			if (0 == map_group())
1157 				exit (-1);
1158 		}
1159 
1160 		if (chrootdir ) {
1161 			/* make sure cwd is inside the jail: */
1162 			if (chdir(chrootdir)) {
1163 				msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
1164 				exit (-1);
1165 			}
1166 			if (chroot(chrootdir)) {
1167 				msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
1168 				exit (-1);
1169 			}
1170 			if (chdir("/")) {
1171 				msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
1172 				exit (-1);
1173 			}
1174 		}
1175 #  ifdef HAVE_SOLARIS_PRIVS
1176 		if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
1177 			msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
1178 			exit(-1);
1179 		}
1180 		if ((highprivs = priv_allocset()) == NULL) {
1181 			msyslog(LOG_ERR, "priv_allocset() failed:%m");
1182 			exit(-1);
1183 		}
1184 		(void) getppriv(PRIV_PERMITTED, highprivs);
1185 		(void) priv_intersect(highprivs, lowprivs);
1186 		if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1187 			msyslog(LOG_ERR, "setppriv() failed:%m");
1188 			exit(-1);
1189 		}
1190 #  endif /* HAVE_SOLARIS_PRIVS */
1191 		if (0 == set_user_group_ids())
1192 			exit(-1);
1193 
1194 #  if defined(HAVE_TRUSTEDBSD_MAC)
1195 		/*
1196 		 * To manipulate system time and (re-)bind to NTP_PORT as needed
1197 		 * following interface changes, we must either run as uid 0 or
1198 		 * the mac_ntpd policy module must be enabled.
1199 		 */
1200 		if (sw_uid != 0 && mac_is_present("ntpd") != 1) {
1201 			msyslog(LOG_ERR, "Need MAC 'ntpd' policy enabled to drop root privileges");
1202 			exit (-1);
1203 		}
1204 #  elif !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1205 		/*
1206 		 * for now assume that the privilege to bind to privileged ports
1207 		 * is associated with running with uid 0 - should be refined on
1208 		 * ports that allow binding to NTP_PORT with uid != 0
1209 		 */
1210 		disable_dynamic_updates |= (sw_uid != 0);  /* also notifies routing message listener */
1211 #  endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1212 
1213 		if (disable_dynamic_updates && interface_interval) {
1214 			interface_interval = 0;
1215 			msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1216 		}
1217 
1218 #  ifdef HAVE_LINUX_CAPABILITIES
1219 		{
1220 			/*
1221 			 *  We may be running under non-root uid now, but we still hold full root privileges!
1222 			 *  We drop all of them, except for the crucial one or two: cap_sys_time and
1223 			 *  cap_net_bind_service if doing dynamic interface tracking.
1224 			 */
1225 			cap_t caps;
1226 			char *captext;
1227 
1228 			captext = (0 != interface_interval)
1229 				      ? "cap_sys_time,cap_net_bind_service=pe"
1230 				      : "cap_sys_time=pe";
1231 			caps = cap_from_text(captext);
1232 			if (!caps) {
1233 				msyslog(LOG_ERR,
1234 					"cap_from_text(%s) failed: %m",
1235 					captext);
1236 				exit(-1);
1237 			}
1238 			if (-1 == cap_set_proc(caps)) {
1239 				msyslog(LOG_ERR,
1240 					"cap_set_proc() failed to drop root privs: %m");
1241 				exit(-1);
1242 			}
1243 			cap_free(caps);
1244 		}
1245 #  endif	/* HAVE_LINUX_CAPABILITIES */
1246 #  ifdef HAVE_SOLARIS_PRIVS
1247 		if (priv_delset(lowprivs, "proc_setid") == -1) {
1248 			msyslog(LOG_ERR, "priv_delset() failed:%m");
1249 			exit(-1);
1250 		}
1251 		if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1252 			msyslog(LOG_ERR, "setppriv() failed:%m");
1253 			exit(-1);
1254 		}
1255 		priv_freeset(lowprivs);
1256 		priv_freeset(highprivs);
1257 #  endif /* HAVE_SOLARIS_PRIVS */
1258 		root_dropped = TRUE;
1259 		fork_deferred_worker();
1260 	}	/* if (droproot) */
1261 # endif	/* HAVE_DROPROOT */
1262 
1263 /* libssecomp sandboxing */
1264 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1265 	scmp_filter_ctx ctx;
1266 
1267 	if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1268 		msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1269 	else {
1270 		msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1271 	}
1272 
1273 #ifdef __x86_64__
1274 int scmp_sc[] = {
1275 	SCMP_SYS(adjtimex),
1276 	SCMP_SYS(bind),
1277 	SCMP_SYS(brk),
1278 	SCMP_SYS(chdir),
1279 	SCMP_SYS(clock_gettime),
1280 	SCMP_SYS(clock_settime),
1281 	SCMP_SYS(close),
1282 	SCMP_SYS(connect),
1283 	SCMP_SYS(exit_group),
1284 	SCMP_SYS(fstat),
1285 	SCMP_SYS(fsync),
1286 	SCMP_SYS(futex),
1287 	SCMP_SYS(getitimer),
1288 	SCMP_SYS(getsockname),
1289 	SCMP_SYS(ioctl),
1290 	SCMP_SYS(lseek),
1291 	SCMP_SYS(madvise),
1292 	SCMP_SYS(mmap),
1293 	SCMP_SYS(munmap),
1294 	SCMP_SYS(open),
1295 	SCMP_SYS(poll),
1296 	SCMP_SYS(read),
1297 	SCMP_SYS(recvmsg),
1298 	SCMP_SYS(rename),
1299 	SCMP_SYS(rt_sigaction),
1300 	SCMP_SYS(rt_sigprocmask),
1301 	SCMP_SYS(rt_sigreturn),
1302 	SCMP_SYS(select),
1303 	SCMP_SYS(sendto),
1304 	SCMP_SYS(setitimer),
1305 	SCMP_SYS(setsid),
1306 	SCMP_SYS(socket),
1307 	SCMP_SYS(stat),
1308 	SCMP_SYS(time),
1309 	SCMP_SYS(write),
1310 };
1311 #endif
1312 #ifdef __i386__
1313 int scmp_sc[] = {
1314 	SCMP_SYS(_newselect),
1315 	SCMP_SYS(adjtimex),
1316 	SCMP_SYS(brk),
1317 	SCMP_SYS(chdir),
1318 	SCMP_SYS(clock_gettime),
1319 	SCMP_SYS(clock_settime),
1320 	SCMP_SYS(close),
1321 	SCMP_SYS(exit_group),
1322 	SCMP_SYS(fsync),
1323 	SCMP_SYS(futex),
1324 	SCMP_SYS(getitimer),
1325 	SCMP_SYS(madvise),
1326 	SCMP_SYS(mmap),
1327 	SCMP_SYS(mmap2),
1328 	SCMP_SYS(munmap),
1329 	SCMP_SYS(open),
1330 	SCMP_SYS(poll),
1331 	SCMP_SYS(read),
1332 	SCMP_SYS(rename),
1333 	SCMP_SYS(rt_sigaction),
1334 	SCMP_SYS(rt_sigprocmask),
1335 	SCMP_SYS(select),
1336 	SCMP_SYS(setitimer),
1337 	SCMP_SYS(setsid),
1338 	SCMP_SYS(sigprocmask),
1339 	SCMP_SYS(sigreturn),
1340 	SCMP_SYS(socketcall),
1341 	SCMP_SYS(stat64),
1342 	SCMP_SYS(time),
1343 	SCMP_SYS(write),
1344 };
1345 #endif
1346 	{
1347 		int i;
1348 
1349 		for (i = 0; i < COUNTOF(scmp_sc); i++) {
1350 			if (seccomp_rule_add(ctx,
1351 			    SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1352 				msyslog(LOG_ERR,
1353 				    "%s: seccomp_rule_add() failed: %m",
1354 				    __func__);
1355 			}
1356 		}
1357 	}
1358 
1359 	if (seccomp_load(ctx) < 0)
1360 		msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1361 		    __func__);
1362 	else {
1363 		msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1364 	}
1365 #endif /* LIBSECCOMP and KERN_SECCOMP */
1366 
1367 #ifdef SYS_WINNT
1368 	ntservice_isup();
1369 #endif
1370 
1371 # ifdef HAVE_IO_COMPLETION_PORT
1372 
1373 	for (;;) {
1374 #if !defined(SIM) && defined(SIGDIE1)
1375 		if (signalled)
1376 			finish_safe(signo);
1377 #endif
1378 		GetReceivedBuffers();
1379 # else /* normal I/O */
1380 
1381 	BLOCK_IO_AND_ALARM();
1382 	was_alarmed = FALSE;
1383 
1384 	for (;;) {
1385 #if !defined(SIM) && defined(SIGDIE1)
1386 		if (signalled)
1387 			finish_safe(signo);
1388 #endif
1389 		if (alarm_flag) {	/* alarmed? */
1390 			was_alarmed = TRUE;
1391 			alarm_flag = FALSE;
1392 		}
1393 
1394 		/* collect async name/addr results */
1395 		if (!was_alarmed)
1396 		    harvest_blocking_responses();
1397 
1398 		if (!was_alarmed && !has_full_recv_buffer()) {
1399 			/*
1400 			 * Nothing to do.  Wait for something.
1401 			 */
1402 			io_handler();
1403 		}
1404 
1405 		if (alarm_flag) {	/* alarmed? */
1406 			was_alarmed = TRUE;
1407 			alarm_flag = FALSE;
1408 		}
1409 
1410 		if (was_alarmed) {
1411 			UNBLOCK_IO_AND_ALARM();
1412 			/*
1413 			 * Out here, signals are unblocked.  Call timer routine
1414 			 * to process expiry.
1415 			 */
1416 			timer();
1417 			was_alarmed = FALSE;
1418 			BLOCK_IO_AND_ALARM();
1419 		}
1420 
1421 # endif		/* !HAVE_IO_COMPLETION_PORT */
1422 
1423 # ifdef DEBUG_TIMING
1424 		{
1425 			l_fp pts;
1426 			l_fp tsa, tsb;
1427 			int bufcount = 0;
1428 
1429 			get_systime(&pts);
1430 			tsa = pts;
1431 # endif
1432 			rbuf = get_full_recv_buffer();
1433 			while (rbuf != NULL) {
1434 				if (alarm_flag) {
1435 					was_alarmed = TRUE;
1436 					alarm_flag = FALSE;
1437 				}
1438 				UNBLOCK_IO_AND_ALARM();
1439 
1440 				if (was_alarmed) {
1441 					/* avoid timer starvation during lengthy I/O handling */
1442 					timer();
1443 					was_alarmed = FALSE;
1444 				}
1445 
1446 				/*
1447 				 * Call the data procedure to handle each received
1448 				 * packet.
1449 				 */
1450 				if (rbuf->receiver != NULL) {
1451 # ifdef DEBUG_TIMING
1452 					l_fp dts = pts;
1453 
1454 					L_SUB(&dts, &rbuf->recv_time);
1455 					DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1456 					collect_timing(rbuf, "buffer processing delay", 1, &dts);
1457 					bufcount++;
1458 # endif
1459 					(*rbuf->receiver)(rbuf);
1460 				} else {
1461 					msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1462 					abort();
1463 				}
1464 
1465 				BLOCK_IO_AND_ALARM();
1466 				freerecvbuf(rbuf);
1467 				rbuf = get_full_recv_buffer();
1468 			}
1469 # ifdef DEBUG_TIMING
1470 			get_systime(&tsb);
1471 			L_SUB(&tsb, &tsa);
1472 			if (bufcount) {
1473 				collect_timing(NULL, "processing", bufcount, &tsb);
1474 				DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1475 			}
1476 		}
1477 # endif
1478 
1479 		/*
1480 		 * Go around again
1481 		 */
1482 
1483 # ifdef HAVE_DNSREGISTRATION
1484 		if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1485 			mdnsreg = current_time;
1486 			msyslog(LOG_INFO, "Attempting to register mDNS");
1487 			if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
1488 			    htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1489 				if (!--mdnstries) {
1490 					msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1491 				} else {
1492 					msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1493 				}
1494 			} else {
1495 				msyslog(LOG_INFO, "mDNS service registered.");
1496 				mdnsreg = FALSE;
1497 			}
1498 		}
1499 # endif /* HAVE_DNSREGISTRATION */
1500 
1501 	}
1502 	UNBLOCK_IO_AND_ALARM();
1503 	return 1;
1504 }
1505 #endif	/* !SIM */
1506 
1507 
1508 #if !defined(SIM) && defined(SIGDIE1)
1509 /*
1510  * finish - exit gracefully
1511  */
1512 static void
1513 finish_safe(
1514 	int	sig
1515 	)
1516 {
1517 	const char *sig_desc;
1518 
1519 	sig_desc = NULL;
1520 #ifdef HAVE_STRSIGNAL
1521 	sig_desc = strsignal(sig);
1522 #endif
1523 	if (sig_desc == NULL)
1524 		sig_desc = "";
1525 	msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1526 		sig, sig_desc);
1527 	/* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1528 # ifdef HAVE_DNSREGISTRATION
1529 	if (mdns != NULL)
1530 		DNSServiceRefDeallocate(mdns);
1531 # endif
1532 	peer_cleanup();
1533 	exit(0);
1534 }
1535 
1536 static RETSIGTYPE
1537 finish(
1538 	int	sig
1539 	)
1540 {
1541 	signalled = 1;
1542 	signo = sig;
1543 }
1544 
1545 #endif	/* !SIM && SIGDIE1 */
1546 
1547 
1548 #ifndef SIM
1549 /*
1550  * wait_child_sync_if - implements parent side of -w/--wait-sync
1551  */
1552 # ifdef HAVE_WORKING_FORK
1553 static int
1554 wait_child_sync_if(
1555 	int	pipe_read_fd,
1556 	long	wait_sync
1557 	)
1558 {
1559 	int	rc;
1560 	int	exit_code;
1561 	time_t	wait_end_time;
1562 	time_t	cur_time;
1563 	time_t	wait_rem;
1564 	fd_set	readset;
1565 	struct timeval wtimeout;
1566 
1567 	if (0 == wait_sync)
1568 		return 0;
1569 
1570 	/* waitsync_fd_to_close used solely by child */
1571 	close(waitsync_fd_to_close);
1572 	wait_end_time = time(NULL) + wait_sync;
1573 	do {
1574 		cur_time = time(NULL);
1575 		wait_rem = (wait_end_time > cur_time)
1576 				? (wait_end_time - cur_time)
1577 				: 0;
1578 		wtimeout.tv_sec = wait_rem;
1579 		wtimeout.tv_usec = 0;
1580 		FD_ZERO(&readset);
1581 		FD_SET(pipe_read_fd, &readset);
1582 		rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1583 			    &wtimeout);
1584 		if (-1 == rc) {
1585 			if (EINTR == errno)
1586 				continue;
1587 			exit_code = (errno) ? errno : -1;
1588 			msyslog(LOG_ERR,
1589 				"--wait-sync select failed: %m");
1590 			return exit_code;
1591 		}
1592 		if (0 == rc) {
1593 			/*
1594 			 * select() indicated a timeout, but in case
1595 			 * its timeouts are affected by a step of the
1596 			 * system clock, select() again with a zero
1597 			 * timeout to confirm.
1598 			 */
1599 			FD_ZERO(&readset);
1600 			FD_SET(pipe_read_fd, &readset);
1601 			wtimeout.tv_sec = 0;
1602 			wtimeout.tv_usec = 0;
1603 			rc = select(pipe_read_fd + 1, &readset, NULL,
1604 				    NULL, &wtimeout);
1605 			if (0 == rc)	/* select() timeout */
1606 				break;
1607 			else		/* readable */
1608 				return 0;
1609 		} else			/* readable */
1610 			return 0;
1611 	} while (wait_rem > 0);
1612 
1613 	fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1614 		progname, wait_sync);
1615 	return ETIMEDOUT;
1616 }
1617 # endif	/* HAVE_WORKING_FORK */
1618 
1619 
1620 /*
1621  * assertion_failed - Redirect assertion failures to msyslog().
1622  */
1623 static void
1624 assertion_failed(
1625 	const char *file,
1626 	int line,
1627 	isc_assertiontype_t type,
1628 	const char *cond
1629 	)
1630 {
1631 	isc_assertion_setcallback(NULL);    /* Avoid recursion */
1632 
1633 	msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1634 		file, line, isc_assertion_typetotext(type), cond);
1635 	msyslog(LOG_ERR, "exiting (due to assertion failure)");
1636 
1637 #if defined(DEBUG) && defined(SYS_WINNT)
1638 	if (debug)
1639 		DebugBreak();
1640 #endif
1641 
1642 	abort();
1643 }
1644 
1645 
1646 /*
1647  * library_fatal_error - Handle fatal errors from our libraries.
1648  */
1649 static void
1650 library_fatal_error(
1651 	const char *file,
1652 	int line,
1653 	const char *format,
1654 	va_list args
1655 	)
1656 {
1657 	char errbuf[256];
1658 
1659 	isc_error_setfatal(NULL);  /* Avoid recursion */
1660 
1661 	msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1662 	vsnprintf(errbuf, sizeof(errbuf), format, args);
1663 	msyslog(LOG_ERR, "%s", errbuf);
1664 	msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1665 
1666 #if defined(DEBUG) && defined(SYS_WINNT)
1667 	if (debug)
1668 		DebugBreak();
1669 #endif
1670 
1671 	abort();
1672 }
1673 
1674 
1675 /*
1676  * library_unexpected_error - Handle non fatal errors from our libraries.
1677  */
1678 # define MAX_UNEXPECTED_ERRORS 100
1679 int unexpected_error_cnt = 0;
1680 static void
1681 library_unexpected_error(
1682 	const char *file,
1683 	int line,
1684 	const char *format,
1685 	va_list args
1686 	)
1687 {
1688 	char errbuf[256];
1689 
1690 	if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1691 		return;	/* avoid clutter in log */
1692 
1693 	msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1694 	vsnprintf(errbuf, sizeof(errbuf), format, args);
1695 	msyslog(LOG_ERR, "%s", errbuf);
1696 
1697 	if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1698 		msyslog(LOG_ERR, "Too many errors.  Shutting up.");
1699 
1700 }
1701 #endif	/* !SIM */
1702 
1703 #if !defined(SIM) && !defined(SYS_WINNT)
1704 # ifdef DEBUG
1705 
1706 /*
1707  * moredebug - increase debugging verbosity
1708  */
1709 static RETSIGTYPE
1710 moredebug(
1711 	int sig
1712 	)
1713 {
1714 	int saved_errno = errno;
1715 
1716 	if (debug < 255)
1717 	{
1718 		debug++;
1719 		msyslog(LOG_DEBUG, "debug raised to %d", debug);
1720 	}
1721 	errno = saved_errno;
1722 }
1723 
1724 
1725 /*
1726  * lessdebug - decrease debugging verbosity
1727  */
1728 static RETSIGTYPE
1729 lessdebug(
1730 	int sig
1731 	)
1732 {
1733 	int saved_errno = errno;
1734 
1735 	if (debug > 0)
1736 	{
1737 		debug--;
1738 		msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1739 	}
1740 	errno = saved_errno;
1741 }
1742 
1743 # else	/* !DEBUG follows */
1744 
1745 
1746 /*
1747  * no_debug - We don't do the debug here.
1748  */
1749 static RETSIGTYPE
1750 no_debug(
1751 	int sig
1752 	)
1753 {
1754 	int saved_errno = errno;
1755 
1756 	msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1757 	errno = saved_errno;
1758 }
1759 # endif	/* !DEBUG */
1760 #endif	/* !SIM && !SYS_WINNT */
1761