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