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