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