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