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