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