xref: /openbsd-src/usr.sbin/ntpd/ntp.c (revision 4c1e55dc91edd6e69ccc60ce855900fbc12cf34f)
1 /*	$OpenBSD: ntp.c,v 1.117 2011/09/21 15:41:30 phessler Exp $ */
2 
3 /*
4  * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
5  * Copyright (c) 2004 Alexander Guy <alexander.guy@andern.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
16  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
17  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/param.h>
21 #include <sys/time.h>
22 #include <sys/stat.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <paths.h>
26 #include <poll.h>
27 #include <pwd.h>
28 #include <signal.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <time.h>
32 #include <unistd.h>
33 
34 #include "ntpd.h"
35 
36 #define	PFD_PIPE_MAIN	0
37 #define	PFD_HOTPLUG	1
38 #define	PFD_PIPE_DNS	2
39 #define	PFD_MAX		3
40 
41 volatile sig_atomic_t	 ntp_quit = 0;
42 volatile sig_atomic_t	 ntp_report = 0;
43 struct imsgbuf		*ibuf_main;
44 struct imsgbuf		*ibuf_dns;
45 struct ntpd_conf	*conf;
46 u_int			 peer_cnt;
47 u_int			 sensors_cnt;
48 time_t			 lastreport;
49 
50 void	ntp_sighdlr(int);
51 int	ntp_dispatch_imsg(void);
52 int	ntp_dispatch_imsg_dns(void);
53 void	peer_add(struct ntp_peer *);
54 void	peer_remove(struct ntp_peer *);
55 void	report_peers(int);
56 
57 void
58 ntp_sighdlr(int sig)
59 {
60 	switch (sig) {
61 	case SIGINT:
62 	case SIGTERM:
63 		ntp_quit = 1;
64 		break;
65 	case SIGINFO:
66 		ntp_report = 1;
67 		break;
68 	}
69 }
70 
71 pid_t
72 ntp_main(int pipe_prnt[2], struct ntpd_conf *nconf, struct passwd *pw)
73 {
74 	int			 a, b, nfds, i, j, idx_peers, timeout;
75 	int			 hotplugfd, nullfd, pipe_dns[2];
76 	u_int			 pfd_elms = 0, idx2peer_elms = 0;
77 	u_int			 listener_cnt, new_cnt, sent_cnt, trial_cnt;
78 	pid_t			 pid, dns_pid;
79 	struct pollfd		*pfd = NULL;
80 	struct servent		*se;
81 	struct listen_addr	*la;
82 	struct ntp_peer		*p;
83 	struct ntp_peer		**idx2peer = NULL;
84 	struct ntp_sensor	*s, *next_s;
85 	struct timespec		 tp;
86 	struct stat		 stb;
87 	time_t			 nextaction, last_sensor_scan = 0;
88 	void			*newp;
89 
90 	switch (pid = fork()) {
91 	case -1:
92 		fatal("cannot fork");
93 		break;
94 	case 0:
95 		break;
96 	default:
97 		return (pid);
98 	}
99 
100 	/* in this case the parent didn't init logging and didn't daemonize */
101 	if (nconf->settime && !nconf->debug) {
102 		log_init(nconf->debug);
103 		if (setsid() == -1)
104 			fatal("setsid");
105 	}
106 	if ((se = getservbyname("ntp", "udp")) == NULL)
107 		fatal("getservbyname");
108 
109 	if ((nullfd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1)
110 		fatal(NULL);
111 	hotplugfd = sensor_hotplugfd();
112 
113 	close(pipe_prnt[0]);
114 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe_dns) == -1)
115 		fatal("socketpair");
116 	dns_pid = ntp_dns(pipe_dns, nconf, pw);
117 	close(pipe_dns[1]);
118 
119 	if (stat(pw->pw_dir, &stb) == -1)
120 		fatal("stat");
121 	if (stb.st_uid != 0 || (stb.st_mode & (S_IWGRP|S_IWOTH)) != 0)
122 		fatalx("bad privsep dir permissions");
123 	if (chroot(pw->pw_dir) == -1)
124 		fatal("chroot");
125 	if (chdir("/") == -1)
126 		fatal("chdir(\"/\")");
127 
128 	if (!nconf->debug) {
129 		dup2(nullfd, STDIN_FILENO);
130 		dup2(nullfd, STDOUT_FILENO);
131 		dup2(nullfd, STDERR_FILENO);
132 	}
133 	close(nullfd);
134 
135 	setproctitle("ntp engine");
136 
137 	conf = nconf;
138 	setup_listeners(se, conf, &listener_cnt);
139 
140 	if (setgroups(1, &pw->pw_gid) ||
141 	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
142 	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
143 		fatal("can't drop privileges");
144 
145 	endservent();
146 
147 	signal(SIGTERM, ntp_sighdlr);
148 	signal(SIGINT, ntp_sighdlr);
149 	signal(SIGINFO, ntp_sighdlr);
150 	signal(SIGPIPE, SIG_IGN);
151 	signal(SIGHUP, SIG_IGN);
152 	signal(SIGCHLD, SIG_DFL);
153 
154 	if ((ibuf_main = malloc(sizeof(struct imsgbuf))) == NULL)
155 		fatal(NULL);
156 	imsg_init(ibuf_main, pipe_prnt[1]);
157 	if ((ibuf_dns = malloc(sizeof(struct imsgbuf))) == NULL)
158 		fatal(NULL);
159 	imsg_init(ibuf_dns, pipe_dns[0]);
160 
161 	TAILQ_FOREACH(p, &conf->ntp_peers, entry)
162 		client_peer_init(p);
163 
164 	bzero(&conf->status, sizeof(conf->status));
165 
166 	conf->freq.num = 0;
167 	conf->freq.samples = 0;
168 	conf->freq.x = 0.0;
169 	conf->freq.xx = 0.0;
170 	conf->freq.xy = 0.0;
171 	conf->freq.y = 0.0;
172 	conf->freq.overall_offset = 0.0;
173 
174 	conf->status.synced = 0;
175 	clock_getres(CLOCK_REALTIME, &tp);
176 	b = 1000000000 / tp.tv_nsec;	/* convert to Hz */
177 	for (a = 0; b > 1; a--, b >>= 1)
178 		;
179 	conf->status.precision = a;
180 	conf->scale = 1;
181 
182 	sensor_init();
183 
184 	log_info("ntp engine ready");
185 
186 	peer_cnt = 0;
187 	TAILQ_FOREACH(p, &conf->ntp_peers, entry)
188 		peer_cnt++;
189 
190 	/* wait 5 min before reporting first status to let things settle down */
191 	lastreport = getmonotime() + (5 * 60) - REPORT_INTERVAL;
192 
193 	while (ntp_quit == 0) {
194 		if (peer_cnt > idx2peer_elms) {
195 			if ((newp = realloc(idx2peer, sizeof(void *) *
196 			    peer_cnt)) == NULL) {
197 				/* panic for now */
198 				log_warn("could not resize idx2peer from %u -> "
199 				    "%u entries", idx2peer_elms, peer_cnt);
200 				fatalx("exiting");
201 			}
202 			idx2peer = newp;
203 			idx2peer_elms = peer_cnt;
204 		}
205 
206 		new_cnt = PFD_MAX + peer_cnt + listener_cnt;
207 		if (new_cnt > pfd_elms) {
208 			if ((newp = realloc(pfd, sizeof(struct pollfd) *
209 			    new_cnt)) == NULL) {
210 				/* panic for now */
211 				log_warn("could not resize pfd from %u -> "
212 				    "%u entries", pfd_elms, new_cnt);
213 				fatalx("exiting");
214 			}
215 			pfd = newp;
216 			pfd_elms = new_cnt;
217 		}
218 
219 		bzero(pfd, sizeof(struct pollfd) * pfd_elms);
220 		bzero(idx2peer, sizeof(void *) * idx2peer_elms);
221 		nextaction = getmonotime() + 3600;
222 		pfd[PFD_PIPE_MAIN].fd = ibuf_main->fd;
223 		pfd[PFD_PIPE_MAIN].events = POLLIN;
224 		pfd[PFD_HOTPLUG].fd = hotplugfd;
225 		pfd[PFD_HOTPLUG].events = POLLIN;
226 		pfd[PFD_PIPE_DNS].fd = ibuf_dns->fd;
227 		pfd[PFD_PIPE_DNS].events = POLLIN;
228 
229 		i = PFD_MAX;
230 		TAILQ_FOREACH(la, &conf->listen_addrs, entry) {
231 			pfd[i].fd = la->fd;
232 			pfd[i].events = POLLIN;
233 			i++;
234 		}
235 
236 		idx_peers = i;
237 		sent_cnt = trial_cnt = 0;
238 		TAILQ_FOREACH(p, &conf->ntp_peers, entry) {
239 			if (p->next > 0 && p->next <= getmonotime()) {
240 				if (p->state > STATE_DNS_INPROGRESS)
241 					trial_cnt++;
242 				if (client_query(p) == 0)
243 					sent_cnt++;
244 			}
245 			if (p->deadline > 0 && p->deadline <= getmonotime()) {
246 				timeout = 300;
247 				log_debug("no reply from %s received in time, "
248 				    "next query %ds %s", log_sockaddr(
249 				    (struct sockaddr *)&p->addr->ss), timeout,
250 				    print_rtable(p->rtable));
251 				if (p->trustlevel >= TRUSTLEVEL_BADPEER &&
252 				    (p->trustlevel /= 2) < TRUSTLEVEL_BADPEER)
253 					log_info("peer %s now invalid",
254 					    log_sockaddr(
255 					    (struct sockaddr *)&p->addr->ss));
256 				client_nextaddr(p);
257 				set_next(p, timeout);
258 			}
259 			if (p->senderrors > MAX_SEND_ERRORS) {
260 				log_debug("failed to send query to %s, "
261 				    "next query %ds", log_sockaddr(
262 				    (struct sockaddr *)&p->addr->ss),
263 				    INTERVAL_QUERY_PATHETIC);
264 				p->senderrors = 0;
265 				client_nextaddr(p);
266 				set_next(p, INTERVAL_QUERY_PATHETIC);
267 			}
268 			if (p->next > 0 && p->next < nextaction)
269 				nextaction = p->next;
270 			if (p->deadline > 0 && p->deadline < nextaction)
271 				nextaction = p->deadline;
272 
273 			if (p->state == STATE_QUERY_SENT &&
274 			    p->query->fd != -1) {
275 				pfd[i].fd = p->query->fd;
276 				pfd[i].events = POLLIN;
277 				idx2peer[i - idx_peers] = p;
278 				i++;
279 			}
280 		}
281 
282 		if (last_sensor_scan == 0 ||
283 		    last_sensor_scan + SENSOR_SCAN_INTERVAL < getmonotime()) {
284 			sensors_cnt = sensor_scan();
285 			last_sensor_scan = getmonotime();
286 		}
287 		if (!TAILQ_EMPTY(&conf->ntp_conf_sensors) && sensors_cnt == 0 &&
288 		    nextaction > last_sensor_scan + SENSOR_SCAN_INTERVAL)
289 			nextaction = last_sensor_scan + SENSOR_SCAN_INTERVAL;
290 		sensors_cnt = 0;
291 		TAILQ_FOREACH(s, &conf->ntp_sensors, entry) {
292 			if (conf->settime && s->offsets[0].offset)
293 				priv_settime(s->offsets[0].offset);
294 			sensors_cnt++;
295 			if (s->next > 0 && s->next < nextaction)
296 				nextaction = s->next;
297 		}
298 
299 		if (conf->settime &&
300 		    ((trial_cnt > 0 && sent_cnt == 0) ||
301 		    (peer_cnt == 0 && sensors_cnt == 0)))
302 			priv_settime(0);	/* no good peers, don't wait */
303 
304 		if (ibuf_main->w.queued > 0)
305 			pfd[PFD_PIPE_MAIN].events |= POLLOUT;
306 		if (ibuf_dns->w.queued > 0)
307 			pfd[PFD_PIPE_DNS].events |= POLLOUT;
308 
309 		timeout = nextaction - getmonotime();
310 		if (timeout < 0)
311 			timeout = 0;
312 
313 		if ((nfds = poll(pfd, i, timeout * 1000)) == -1)
314 			if (errno != EINTR) {
315 				log_warn("poll error");
316 				ntp_quit = 1;
317 			}
318 
319 		if (nfds > 0 && (pfd[PFD_PIPE_MAIN].revents & POLLOUT))
320 			if (msgbuf_write(&ibuf_main->w) < 0) {
321 				log_warn("pipe write error (to parent)");
322 				ntp_quit = 1;
323 			}
324 
325 		if (nfds > 0 && pfd[PFD_PIPE_MAIN].revents & (POLLIN|POLLERR)) {
326 			nfds--;
327 			if (ntp_dispatch_imsg() == -1)
328 				ntp_quit = 1;
329 		}
330 
331 		if (nfds > 0 && (pfd[PFD_PIPE_DNS].revents & POLLOUT))
332 			if (msgbuf_write(&ibuf_dns->w) < 0) {
333 				log_warn("pipe write error (to dns engine)");
334 				ntp_quit = 1;
335 			}
336 
337 		if (nfds > 0 && pfd[PFD_PIPE_DNS].revents & (POLLIN|POLLERR)) {
338 			nfds--;
339 			if (ntp_dispatch_imsg_dns() == -1)
340 				ntp_quit = 1;
341 		}
342 
343 		if (nfds > 0 && pfd[PFD_HOTPLUG].revents & (POLLIN|POLLERR)) {
344 			nfds--;
345 			sensor_hotplugevent(hotplugfd);
346 		}
347 
348 		for (j = PFD_MAX; nfds > 0 && j < idx_peers; j++)
349 			if (pfd[j].revents & (POLLIN|POLLERR)) {
350 				nfds--;
351 				if (server_dispatch(pfd[j].fd, conf) == -1)
352 					ntp_quit = 1;
353 			}
354 
355 		for (; nfds > 0 && j < i; j++)
356 			if (pfd[j].revents & (POLLIN|POLLERR)) {
357 				nfds--;
358 				if (client_dispatch(idx2peer[j - idx_peers],
359 				    conf->settime) == -1)
360 					ntp_quit = 1;
361 			}
362 
363 		for (s = TAILQ_FIRST(&conf->ntp_sensors); s != NULL;
364 		    s = next_s) {
365 			next_s = TAILQ_NEXT(s, entry);
366 			if (s->next <= getmonotime())
367 				sensor_query(s);
368 		}
369 		report_peers(ntp_report);
370 		ntp_report = 0;
371 	}
372 
373 	msgbuf_write(&ibuf_main->w);
374 	msgbuf_clear(&ibuf_main->w);
375 	free(ibuf_main);
376 	msgbuf_write(&ibuf_dns->w);
377 	msgbuf_clear(&ibuf_dns->w);
378 	free(ibuf_dns);
379 
380 	log_info("ntp engine exiting");
381 	_exit(0);
382 }
383 
384 int
385 ntp_dispatch_imsg(void)
386 {
387 	struct imsg		 imsg;
388 	int			 n;
389 
390 	if ((n = imsg_read(ibuf_main)) == -1)
391 		return (-1);
392 
393 	if (n == 0) {	/* connection closed */
394 		log_warnx("ntp_dispatch_imsg in ntp engine: pipe closed");
395 		return (-1);
396 	}
397 
398 	for (;;) {
399 		if ((n = imsg_get(ibuf_main, &imsg)) == -1)
400 			return (-1);
401 
402 		if (n == 0)
403 			break;
404 
405 		switch (imsg.hdr.type) {
406 		case IMSG_ADJTIME:
407 			memcpy(&n, imsg.data, sizeof(n));
408 			if (n == 1 && !conf->status.synced) {
409 				log_info("clock is now synced");
410 				conf->status.synced = 1;
411 			} else if (n == 0 && conf->status.synced) {
412 				log_info("clock is now unsynced");
413 				conf->status.synced = 0;
414 			}
415 			break;
416 		default:
417 			break;
418 		}
419 		imsg_free(&imsg);
420 	}
421 	return (0);
422 }
423 
424 int
425 ntp_dispatch_imsg_dns(void)
426 {
427 	struct imsg		 imsg;
428 	struct ntp_peer		*peer, *npeer;
429 	u_int16_t		 dlen;
430 	u_char			*p;
431 	struct ntp_addr		*h;
432 	int			 n;
433 
434 	if ((n = imsg_read(ibuf_dns)) == -1)
435 		return (-1);
436 
437 	if (n == 0) {	/* connection closed */
438 		log_warnx("ntp_dispatch_imsg_dns in ntp engine: pipe closed");
439 		return (-1);
440 	}
441 
442 	for (;;) {
443 		if ((n = imsg_get(ibuf_dns, &imsg)) == -1)
444 			return (-1);
445 
446 		if (n == 0)
447 			break;
448 
449 		switch (imsg.hdr.type) {
450 		case IMSG_HOST_DNS:
451 			TAILQ_FOREACH(peer, &conf->ntp_peers, entry)
452 				if (peer->id == imsg.hdr.peerid)
453 					break;
454 			if (peer == NULL) {
455 				log_warnx("IMSG_HOST_DNS with invalid peerID");
456 				break;
457 			}
458 			if (peer->addr != NULL) {
459 				log_warnx("IMSG_HOST_DNS but addr != NULL!");
460 				break;
461 			}
462 
463 			dlen = imsg.hdr.len - IMSG_HEADER_SIZE;
464 			if (dlen == 0) {	/* no data -> temp error */
465 				peer->state = STATE_DNS_TEMPFAIL;
466 				break;
467 			}
468 
469 			p = (u_char *)imsg.data;
470 			while (dlen >= sizeof(struct sockaddr_storage)) {
471 				if ((h = calloc(1, sizeof(struct ntp_addr))) ==
472 				    NULL)
473 					fatal(NULL);
474 				memcpy(&h->ss, p, sizeof(h->ss));
475 				p += sizeof(h->ss);
476 				dlen -= sizeof(h->ss);
477 				if (peer->addr_head.pool) {
478 					npeer = new_peer();
479 					npeer->weight = peer->weight;
480 					h->next = NULL;
481 					npeer->addr = h;
482 					npeer->addr_head.a = h;
483 					npeer->addr_head.name =
484 					    peer->addr_head.name;
485 					npeer->addr_head.pool = 1;
486 					npeer->rtable = peer->rtable;
487 					client_peer_init(npeer);
488 					npeer->state = STATE_DNS_DONE;
489 					peer_add(npeer);
490 				} else {
491 					h->next = peer->addr;
492 					peer->addr = h;
493 					peer->addr_head.a = peer->addr;
494 					peer->state = STATE_DNS_DONE;
495 				}
496 			}
497 			if (dlen != 0)
498 				fatalx("IMSG_HOST_DNS: dlen != 0");
499 			if (peer->addr_head.pool)
500 				peer_remove(peer);
501 			else
502 				client_addr_init(peer);
503 			break;
504 		default:
505 			break;
506 		}
507 		imsg_free(&imsg);
508 	}
509 	return (0);
510 }
511 
512 void
513 peer_add(struct ntp_peer *p)
514 {
515 	TAILQ_INSERT_TAIL(&conf->ntp_peers, p, entry);
516 	peer_cnt++;
517 }
518 
519 void
520 peer_remove(struct ntp_peer *p)
521 {
522 	TAILQ_REMOVE(&conf->ntp_peers, p, entry);
523 	free(p);
524 	peer_cnt--;
525 }
526 
527 static void
528 priv_adjfreq(double offset)
529 {
530 	double curtime, freq;
531 
532 	if (!conf->status.synced){
533 		conf->freq.samples = 0;
534 		return;
535 	}
536 
537 	conf->freq.samples++;
538 
539 	if (conf->freq.samples <= 0)
540 		return;
541 
542 	conf->freq.overall_offset += offset;
543 	offset = conf->freq.overall_offset;
544 
545 	curtime = gettime_corrected();
546 	conf->freq.xy += offset * curtime;
547 	conf->freq.x += curtime;
548 	conf->freq.y += offset;
549 	conf->freq.xx += curtime * curtime;
550 
551 	if (conf->freq.samples % FREQUENCY_SAMPLES != 0)
552 		return;
553 
554 	freq =
555 	    (conf->freq.xy - conf->freq.x * conf->freq.y / conf->freq.samples)
556 	    /
557 	    (conf->freq.xx - conf->freq.x * conf->freq.x / conf->freq.samples);
558 
559 	if (freq > MAX_FREQUENCY_ADJUST)
560 		freq = MAX_FREQUENCY_ADJUST;
561 	else if (freq < -MAX_FREQUENCY_ADJUST)
562 		freq = -MAX_FREQUENCY_ADJUST;
563 
564 	imsg_compose(ibuf_main, IMSG_ADJFREQ, 0, 0, -1, &freq, sizeof(freq));
565 	conf->filters |= FILTER_ADJFREQ;
566 	conf->freq.xy = 0.0;
567 	conf->freq.x = 0.0;
568 	conf->freq.y = 0.0;
569 	conf->freq.xx = 0.0;
570 	conf->freq.samples = 0;
571 	conf->freq.overall_offset = 0.0;
572 	conf->freq.num++;
573 }
574 
575 int
576 priv_adjtime(void)
577 {
578 	struct ntp_peer		 *p;
579 	struct ntp_sensor	 *s;
580 	int			  offset_cnt = 0, i = 0, j;
581 	struct ntp_offset	**offsets;
582 	double			  offset_median;
583 
584 	TAILQ_FOREACH(p, &conf->ntp_peers, entry) {
585 		if (p->trustlevel < TRUSTLEVEL_BADPEER)
586 			continue;
587 		if (!p->update.good)
588 			return (1);
589 		offset_cnt += p->weight;
590 	}
591 
592 	TAILQ_FOREACH(s, &conf->ntp_sensors, entry) {
593 		if (!s->update.good)
594 			continue;
595 		offset_cnt += s->weight;
596 	}
597 
598 	if (offset_cnt == 0)
599 		return (1);
600 
601 	if ((offsets = calloc(offset_cnt, sizeof(struct ntp_offset *))) == NULL)
602 		fatal("calloc priv_adjtime");
603 
604 	TAILQ_FOREACH(p, &conf->ntp_peers, entry) {
605 		if (p->trustlevel < TRUSTLEVEL_BADPEER)
606 			continue;
607 		for (j = 0; j < p->weight; j++)
608 			offsets[i++] = &p->update;
609 	}
610 
611 	TAILQ_FOREACH(s, &conf->ntp_sensors, entry) {
612 		if (!s->update.good)
613 			continue;
614 		for (j = 0; j < s->weight; j++)
615 			offsets[i++] = &s->update;
616 	}
617 
618 	qsort(offsets, offset_cnt, sizeof(struct ntp_offset *), offset_compare);
619 
620 	i = offset_cnt / 2;
621 	if (offset_cnt % 2 == 0) {
622 		offset_median =
623 		    (offsets[i - 1]->offset + offsets[i]->offset) / 2;
624 		conf->status.rootdelay =
625 		    (offsets[i - 1]->delay + offsets[i]->delay) / 2;
626 		conf->status.stratum = MAX(
627 		    offsets[i - 1]->status.stratum, offsets[i]->status.stratum);
628 	} else {
629 		offset_median = offsets[i]->offset;
630 		conf->status.rootdelay = offsets[i]->delay;
631 		conf->status.stratum = offsets[i]->status.stratum;
632 	}
633 	conf->status.leap = offsets[i]->status.leap;
634 
635 	imsg_compose(ibuf_main, IMSG_ADJTIME, 0, 0, -1,
636 	    &offset_median, sizeof(offset_median));
637 
638 	priv_adjfreq(offset_median);
639 
640 	conf->status.reftime = gettime();
641 	conf->status.stratum++;	/* one more than selected peer */
642 	if (conf->status.stratum > NTP_MAXSTRATUM)
643 		conf->status.stratum = NTP_MAXSTRATUM;
644 	update_scale(offset_median);
645 
646 	conf->status.refid = offsets[i]->status.send_refid;
647 
648 	free(offsets);
649 
650 	TAILQ_FOREACH(p, &conf->ntp_peers, entry) {
651 		for (i = 0; i < OFFSET_ARRAY_SIZE; i++)
652 			p->reply[i].offset -= offset_median;
653 		p->update.good = 0;
654 	}
655 	TAILQ_FOREACH(s, &conf->ntp_sensors, entry) {
656 		for (i = 0; i < SENSOR_OFFSETS; i++)
657 			s->offsets[i].offset -= offset_median;
658 		s->update.offset -= offset_median;
659 	}
660 
661 	return (0);
662 }
663 
664 int
665 offset_compare(const void *aa, const void *bb)
666 {
667 	const struct ntp_offset * const *a;
668 	const struct ntp_offset * const *b;
669 
670 	a = aa;
671 	b = bb;
672 
673 	if ((*a)->offset < (*b)->offset)
674 		return (-1);
675 	else if ((*a)->offset > (*b)->offset)
676 		return (1);
677 	else
678 		return (0);
679 }
680 
681 void
682 priv_settime(double offset)
683 {
684 	imsg_compose(ibuf_main, IMSG_SETTIME, 0, 0, -1,
685 	    &offset, sizeof(offset));
686 	conf->settime = 0;
687 }
688 
689 void
690 priv_host_dns(char *name, u_int32_t peerid)
691 {
692 	u_int16_t	dlen;
693 
694 	dlen = strlen(name) + 1;
695 	imsg_compose(ibuf_dns, IMSG_HOST_DNS, peerid, 0, -1, name, dlen);
696 }
697 
698 void
699 update_scale(double offset)
700 {
701 	offset += getoffset();
702 	if (offset < 0)
703 		offset = -offset;
704 
705 	if (offset > QSCALE_OFF_MAX || !conf->status.synced ||
706 	    conf->freq.num < 3)
707 		conf->scale = 1;
708 	else if (offset < QSCALE_OFF_MIN)
709 		conf->scale = QSCALE_OFF_MAX / QSCALE_OFF_MIN;
710 	else
711 		conf->scale = QSCALE_OFF_MAX / offset;
712 }
713 
714 time_t
715 scale_interval(time_t requested)
716 {
717 	time_t interval, r;
718 
719 	interval = requested * conf->scale;
720 	r = arc4random_uniform(MAX(5, interval / 10));
721 	return (interval + r);
722 }
723 
724 time_t
725 error_interval(void)
726 {
727 	time_t interval, r;
728 
729 	interval = INTERVAL_QUERY_PATHETIC * QSCALE_OFF_MAX / QSCALE_OFF_MIN;
730 	r = arc4random_uniform(interval / 10);
731 	return (interval + r);
732 }
733 
734 void
735 report_peers(int always)
736 {
737 	time_t now;
738 	u_int badpeers = 0;
739 	u_int badsensors = 0;
740 	struct ntp_peer *p;
741 	struct ntp_sensor *s;
742 
743 	TAILQ_FOREACH(p, &conf->ntp_peers, entry) {
744 		if (p->trustlevel < TRUSTLEVEL_BADPEER)
745 			badpeers++;
746 	}
747 	TAILQ_FOREACH(s, &conf->ntp_sensors, entry) {
748 		if (!s->update.good)
749 			badsensors++;
750 	}
751 
752 	now = getmonotime();
753 	if (!always) {
754 		if ((peer_cnt == 0 || badpeers == 0 || badpeers < peer_cnt / 2)
755 		    && (sensors_cnt == 0 || badsensors == 0 ||
756 		    badsensors < sensors_cnt / 2))
757 			return;
758 
759 		if (lastreport + REPORT_INTERVAL > now)
760 			return;
761 	}
762 	lastreport = now;
763 	if (peer_cnt > 0) {
764 		log_warnx("%u out of %u peers valid", peer_cnt - badpeers,
765 		    peer_cnt);
766 		TAILQ_FOREACH(p, &conf->ntp_peers, entry) {
767 			if (p->trustlevel < TRUSTLEVEL_BADPEER) {
768 				const char *a = "not resolved";
769 				const char *pool = "";
770 				if (p->addr)
771 					a = log_sockaddr(
772 					    (struct sockaddr *)&p->addr->ss);
773 				if (p->addr_head.pool)
774 					pool = "from pool ";
775 				log_warnx("bad peer %s%s (%s) %s",
776 				    pool, p->addr_head.name, a,
777 				    print_rtable(p->rtable));
778 			}
779 		}
780 	}
781 	if (sensors_cnt > 0) {
782 		log_warnx("%u out of %u sensors valid",
783 		    sensors_cnt - badsensors, sensors_cnt);
784 		TAILQ_FOREACH(s, &conf->ntp_sensors, entry) {
785 			if (!s->update.good)
786 				log_warnx("bad sensor %s", s->device);
787 		}
788 	}
789 }
790