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