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