xref: /openbsd/usr.sbin/ntpd/constraint.c (revision 3b54e53f)
1 /*	$OpenBSD: constraint.c,v 1.34 2016/10/18 22:05:47 rzalamena Exp $	*/
2 
3 /*
4  * Copyright (c) 2015 Reyk Floeter <reyk@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/queue.h>
20 #include <sys/socket.h>
21 #include <sys/time.h>
22 #include <sys/types.h>
23 #include <sys/wait.h>
24 #include <sys/resource.h>
25 #include <sys/uio.h>
26 
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
29 
30 #include <errno.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <fcntl.h>
34 #include <imsg.h>
35 #include <netdb.h>
36 #include <poll.h>
37 #include <signal.h>
38 #include <string.h>
39 #include <unistd.h>
40 #include <time.h>
41 #include <ctype.h>
42 #include <tls.h>
43 #include <pwd.h>
44 
45 #include "ntpd.h"
46 
47 int	 constraint_addr_init(struct constraint *);
48 struct constraint *
49 	 constraint_byid(u_int32_t);
50 struct constraint *
51 	 constraint_byfd(int);
52 struct constraint *
53 	 constraint_bypid(pid_t);
54 int	 constraint_close(u_int32_t);
55 void	 constraint_update(void);
56 void	 constraint_reset(void);
57 int	 constraint_cmp(const void *, const void *);
58 
59 void	 priv_constraint_close(int, int);
60 void	 priv_constraint_readquery(struct constraint *, struct ntp_addr_msg *,
61 	    uint8_t **);
62 
63 struct httpsdate *
64 	 httpsdate_init(const char *, const char *, const char *,
65 	    const char *, const u_int8_t *, size_t);
66 void	 httpsdate_free(void *);
67 int	 httpsdate_request(struct httpsdate *, struct timeval *);
68 void	*httpsdate_query(const char *, const char *, const char *,
69 	    const char *, const u_int8_t *, size_t,
70 	    struct timeval *, struct timeval *);
71 
72 char	*tls_readline(struct tls *, size_t *, size_t *, struct timeval *);
73 
74 u_int constraint_cnt;
75 extern u_int peer_cnt;
76 extern struct imsgbuf *ibuf;		/* priv */
77 extern struct imsgbuf *ibuf_main;	/* chld */
78 
79 struct httpsdate {
80 	char			*tls_addr;
81 	char			*tls_port;
82 	char			*tls_hostname;
83 	char			*tls_path;
84 	char			*tls_request;
85 	struct tls_config	*tls_config;
86 	struct tls		*tls_ctx;
87 	struct tm		 tls_tm;
88 };
89 
90 int
91 constraint_init(struct constraint *cstr)
92 {
93 	cstr->state = STATE_NONE;
94 	cstr->fd = -1;
95 	cstr->last = getmonotime();
96 	cstr->constraint = 0;
97 	cstr->senderrors = 0;
98 
99 	return (constraint_addr_init(cstr));
100 }
101 
102 int
103 constraint_addr_init(struct constraint *cstr)
104 {
105 	struct sockaddr_in	*sa_in;
106 	struct sockaddr_in6	*sa_in6;
107 	struct ntp_addr		*h;
108 
109 	if (cstr->state == STATE_DNS_INPROGRESS)
110 		return (0);
111 
112 	if (cstr->addr_head.a == NULL) {
113 		priv_dns(IMSG_CONSTRAINT_DNS, cstr->addr_head.name, cstr->id);
114 		cstr->state = STATE_DNS_INPROGRESS;
115 		return (0);
116 	}
117 
118 	h = cstr->addr;
119 	switch (h->ss.ss_family) {
120 	case AF_INET:
121 		sa_in = (struct sockaddr_in *)&h->ss;
122 		if (ntohs(sa_in->sin_port) == 0)
123 			sa_in->sin_port = htons(443);
124 		cstr->state = STATE_DNS_DONE;
125 		break;
126 	case AF_INET6:
127 		sa_in6 = (struct sockaddr_in6 *)&h->ss;
128 		if (ntohs(sa_in6->sin6_port) == 0)
129 			sa_in6->sin6_port = htons(443);
130 		cstr->state = STATE_DNS_DONE;
131 		break;
132 	default:
133 		/* XXX king bula sez it? */
134 		fatalx("wrong AF in constraint_addr_init");
135 		/* NOTREACHED */
136 	}
137 
138 	return (1);
139 }
140 
141 int
142 constraint_query(struct constraint *cstr)
143 {
144 	time_t			 now;
145 	struct ntp_addr_msg	 am;
146 	struct iovec		 iov[3];
147 	int			 iov_cnt = 0;
148 
149 	now = getmonotime();
150 
151 	switch (cstr->state) {
152 	case STATE_DNS_DONE:
153 		/* Proceed and query the time */
154 		break;
155 	case STATE_DNS_TEMPFAIL:
156 		/* Retry resolving the address */
157 		constraint_init(cstr);
158 		return (-1);
159 	case STATE_QUERY_SENT:
160 		if (cstr->last + CONSTRAINT_SCAN_TIMEOUT > now) {
161 			/* The caller should expect a reply */
162 			return (0);
163 		}
164 
165 		/* Timeout, just kill the process to reset it. */
166 		imsg_compose(ibuf_main, IMSG_CONSTRAINT_KILL,
167 		    cstr->id, 0, -1, NULL, 0);
168 
169 		cstr->state = STATE_TIMEOUT;
170 		return (-1);
171 	case STATE_INVALID:
172 		if (cstr->last + CONSTRAINT_SCAN_INTERVAL > now) {
173 			/* Nothing to do */
174 			return (-1);
175 		}
176 
177 		/* Reset and retry */
178 		cstr->senderrors = 0;
179 		constraint_close(cstr->id);
180 		break;
181 	case STATE_REPLY_RECEIVED:
182 	default:
183 		/* Nothing to do */
184 		return (-1);
185 	}
186 
187 	cstr->last = now;
188 	cstr->state = STATE_QUERY_SENT;
189 
190 	memset(&am, 0, sizeof(am));
191 	memcpy(&am.a, cstr->addr, sizeof(am.a));
192 
193 	iov[iov_cnt].iov_base = &am;
194 	iov[iov_cnt++].iov_len = sizeof(am);
195 	if (cstr->addr_head.name) {
196 		am.namelen = strlen(cstr->addr_head.name) + 1;
197 		iov[iov_cnt].iov_base = cstr->addr_head.name;
198 		iov[iov_cnt++].iov_len = am.namelen;
199 	}
200 	if (cstr->addr_head.path) {
201 		am.pathlen = strlen(cstr->addr_head.path) + 1;
202 		iov[iov_cnt].iov_base = cstr->addr_head.path;
203 		iov[iov_cnt++].iov_len = am.pathlen;
204 	}
205 
206 	imsg_composev(ibuf_main, IMSG_CONSTRAINT_QUERY,
207 	    cstr->id, 0, -1, iov, iov_cnt);
208 
209 	return (0);
210 }
211 
212 void
213 priv_constraint_msg(u_int32_t id, u_int8_t *data, size_t len, int argc,
214     char **argv)
215 {
216 	struct ntp_addr_msg	 am;
217 	struct ntp_addr		*h;
218 	struct constraint	*cstr;
219 	int			 pipes[2];
220 	int			 rv;
221 
222 	if ((cstr = constraint_byid(id)) != NULL) {
223 		log_warnx("IMSG_CONSTRAINT_QUERY repeated for id %d", id);
224 		return;
225 	}
226 
227 	if (len < sizeof(am)) {
228 		log_warnx("invalid IMSG_CONSTRAINT_QUERY received");
229 		return;
230 	}
231 	memcpy(&am, data, sizeof(am));
232 	if (len != (sizeof(am) + am.namelen + am.pathlen)) {
233 		log_warnx("invalid IMSG_CONSTRAINT_QUERY received");
234 		return;
235 	}
236 	/* Additional imsg data is obtained in the unpriv child */
237 
238 	if ((h = calloc(1, sizeof(*h))) == NULL)
239 		fatal("calloc ntp_addr");
240 	memcpy(h, &am.a, sizeof(*h));
241 	h->next = NULL;
242 
243 	cstr = new_constraint();
244 	cstr->id = id;
245 	cstr->addr = h;
246 	cstr->addr_head.a = h;
247 	constraint_add(cstr);
248 	constraint_cnt++;
249 
250 	if (socketpair(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, AF_UNSPEC,
251 	    pipes) == -1)
252 		fatal("%s pipes", __func__);
253 
254 	/* Prepare and send constraint data to child. */
255 	cstr->fd = pipes[0];
256 	imsg_init(&cstr->ibuf, cstr->fd);
257 	if (imsg_compose(&cstr->ibuf, IMSG_CONSTRAINT_QUERY, id, 0, -1,
258 	    data, len) == -1)
259 		fatal("%s: imsg_compose", __func__);
260 	do {
261 		rv = imsg_flush(&cstr->ibuf);
262 	} while (rv == -1 && errno == EAGAIN);
263 	if (rv == -1)
264 		fatal("imsg_flush");
265 
266 	/*
267 	 * Fork child handlers and make sure to do any sensitive work in the
268 	 * the (unprivileged) child.  The parent should not do any parsing,
269 	 * certificate loading etc.
270 	 */
271 	cstr->pid = start_child(CONSTRAINT_PROC_NAME, pipes[1], argc, argv);
272 }
273 
274 void
275 priv_constraint_readquery(struct constraint *cstr, struct ntp_addr_msg *am,
276     uint8_t **data)
277 {
278 	struct ntp_addr		*h;
279 	uint8_t			*dptr;
280 	int			 n;
281 	struct imsg		 imsg;
282 	size_t			 mlen;
283 
284 	/* Read the message our parent left us. */
285 	if (((n = imsg_read(&cstr->ibuf)) == -1 && errno != EAGAIN) || n == 0)
286 		fatal("%s: imsg_read", __func__);
287 	if (((n = imsg_get(&cstr->ibuf, &imsg)) == -1) || n == 0)
288 		fatal("%s: imsg_get", __func__);
289 	if (imsg.hdr.type != IMSG_CONSTRAINT_QUERY)
290 		fatalx("%s: invalid message type", __func__);
291 
292 	/*
293 	 * Copy the message contents just like our father:
294 	 * priv_constraint_msg().
295 	 */
296 	mlen = imsg.hdr.len - IMSG_HEADER_SIZE;
297 	if (mlen < sizeof(*am))
298 		fatalx("%s: mlen < sizeof(*am)", __func__);
299 
300 	memcpy(am, imsg.data, sizeof(*am));
301 	if (mlen != (sizeof(*am) + am->namelen + am->pathlen))
302 		fatalx("%s: mlen < sizeof(*am) + am->namelen + am->pathlen",
303 		    __func__);
304 
305 	if ((h = calloc(1, sizeof(*h))) == NULL ||
306 	    (*data = calloc(1, mlen)) == NULL)
307 		fatal("%s: calloc", __func__);
308 
309 	memcpy(h, &am->a, sizeof(*h));
310 	h->next = NULL;
311 
312 	cstr->id = imsg.hdr.peerid;
313 	cstr->addr = h;
314 	cstr->addr_head.a = h;
315 
316 	dptr = imsg.data;
317 	memcpy(*data, dptr + sizeof(*am), mlen - sizeof(*am));
318 	imsg_free(&imsg);
319 }
320 
321 void
322 priv_constraint_child(const char *pw_dir, uid_t pw_uid, gid_t pw_gid)
323 {
324 	struct constraint	*cstr;
325 	struct ntp_addr_msg	*am;
326 	uint8_t			*data;
327 	static char		 addr[NI_MAXHOST];
328 	struct timeval		 rectv, xmttv;
329 	struct sigaction	 sa;
330 	void			*ctx;
331 	struct iovec		 iov[2];
332 	int			 i, rv;
333 
334 	log_procinit("constraint");
335 
336 	if (setpriority(PRIO_PROCESS, 0, 0) == -1)
337 		log_warn("could not set priority");
338 
339 	if ((cstr = calloc(1, sizeof(*cstr))) == NULL ||
340 	    (am = calloc(1, sizeof(*am))) == NULL)
341 		fatal("%s: calloc", __func__);
342 
343 	/* Init TLS and load CA certs before chroot() */
344 	if (tls_init() == -1)
345 		fatalx("tls_init");
346 	if ((conf->ca = tls_load_file(CONSTRAINT_CA,
347 	    &conf->ca_len, NULL)) == NULL)
348 		fatalx("failed to load constraint ca");
349 
350 	if (chroot(pw_dir) == -1)
351 		fatal("chroot");
352 	if (chdir("/") == -1)
353 		fatal("chdir(\"/\")");
354 
355 	if (setgroups(1, &pw_gid) ||
356 	    setresgid(pw_gid, pw_gid, pw_gid) ||
357 	    setresuid(pw_uid, pw_uid, pw_uid))
358 		fatal("can't drop privileges");
359 
360 	/* Reset all signal handlers */
361 	memset(&sa, 0, sizeof(sa));
362 	sigemptyset(&sa.sa_mask);
363 	sa.sa_flags = SA_RESTART;
364 	sa.sa_handler = SIG_DFL;
365 	for (i = 1; i < _NSIG; i++)
366 		sigaction(i, &sa, NULL);
367 
368 	if (pledge("stdio inet", NULL) == -1)
369 		fatal("pledge");
370 
371 	cstr->fd = CONSTRAINT_PASSFD;
372 	imsg_init(&cstr->ibuf, cstr->fd);
373 	priv_constraint_readquery(cstr, am, &data);
374 
375 	/*
376 	 * Get the IP address as name and set the process title accordingly.
377 	 * This only converts an address into a string and does not trigger
378 	 * any DNS operation, so it is safe to be called without the dns
379 	 * pledge.
380 	 */
381 	if (getnameinfo((struct sockaddr *)&cstr->addr->ss,
382 	    SA_LEN((struct sockaddr *)&cstr->addr->ss),
383 	    addr, sizeof(addr), NULL, 0,
384 	    NI_NUMERICHOST) != 0)
385 		fatalx("%s getnameinfo", __func__);
386 
387 	log_debug("constraint request to %s", addr);
388 	setproctitle("constraint from %s", addr);
389 	(void)closefrom(CONSTRAINT_PASSFD + 1);
390 
391 	/*
392 	 * Set the close-on-exec flag to prevent leaking the communication
393 	 * channel to any exec'ed child.  In theory this could never happen,
394 	 * constraints don't exec children and pledge() prevents it,
395 	 * but we keep it as a safety belt; especially for portability.
396 	 */
397 	if (fcntl(CONSTRAINT_PASSFD, F_SETFD, FD_CLOEXEC) == -1)
398 		fatal("%s fcntl F_SETFD", __func__);
399 
400 	/* Get remaining data from imsg in the unpriv child */
401 	if (am->namelen) {
402 		if ((cstr->addr_head.name =
403 		    get_string(data, am->namelen)) == NULL)
404 			fatalx("invalid IMSG_CONSTRAINT_QUERY name");
405 		data += am->namelen;
406 	}
407 	if (am->pathlen) {
408 		if ((cstr->addr_head.path =
409 		    get_string(data, am->pathlen)) == NULL)
410 			fatalx("invalid IMSG_CONSTRAINT_QUERY path");
411 	}
412 
413 	/* Run! */
414 	if ((ctx = httpsdate_query(addr,
415 	    CONSTRAINT_PORT, cstr->addr_head.name, cstr->addr_head.path,
416 	    conf->ca, conf->ca_len, &rectv, &xmttv)) == NULL) {
417 		/* Abort with failure but without warning */
418 		exit(1);
419 	}
420 
421 	iov[0].iov_base = &rectv;
422 	iov[0].iov_len = sizeof(rectv);
423 	iov[1].iov_base = &xmttv;
424 	iov[1].iov_len = sizeof(xmttv);
425 	imsg_composev(&cstr->ibuf,
426 	    IMSG_CONSTRAINT_RESULT, 0, 0, -1, iov, 2);
427 	do {
428 		rv = imsg_flush(&cstr->ibuf);
429 	} while (rv == -1 && errno == EAGAIN);
430 
431 	/* Tear down the TLS connection after sending the result */
432 	httpsdate_free(ctx);
433 
434 	exit(0);
435 }
436 
437 void
438 priv_constraint_check_child(pid_t pid, int status)
439 {
440 	struct constraint	*cstr;
441 	int			 fail, sig;
442 	char			*signame;
443 
444 	fail = sig = 0;
445 	if (WIFSIGNALED(status)) {
446 		sig = WTERMSIG(status);
447 	} else if (WIFEXITED(status)) {
448 		if (WEXITSTATUS(status) != 0)
449 			fail = 1;
450 	} else
451 		fatalx("unexpected cause of SIGCHLD");
452 
453 	if ((cstr = constraint_bypid(pid)) != NULL) {
454 		if (sig) {
455 			if (sig != SIGTERM) {
456 				signame = strsignal(sig) ?
457 				    strsignal(sig) : "unknown";
458 				log_warnx("constraint %s; "
459 				    "terminated with signal %d (%s)",
460 				    log_sockaddr((struct sockaddr *)
461 				    &cstr->addr->ss), sig, signame);
462 			}
463 			fail = 1;
464 		}
465 
466 		priv_constraint_close(cstr->fd, fail);
467 	}
468 }
469 
470 void
471 priv_constraint_kill(u_int32_t id)
472 {
473 	struct constraint	*cstr;
474 
475 	if ((cstr = constraint_byid(id)) == NULL) {
476 		log_warnx("IMSG_CONSTRAINT_KILL for invalid id %d", id);
477 		return;
478 	}
479 
480 	kill(cstr->pid, SIGTERM);
481 }
482 
483 struct constraint *
484 constraint_byid(u_int32_t id)
485 {
486 	struct constraint	*cstr;
487 
488 	TAILQ_FOREACH(cstr, &conf->constraints, entry) {
489 		if (cstr->id == id)
490 			return (cstr);
491 	}
492 
493 	return (NULL);
494 }
495 
496 struct constraint *
497 constraint_byfd(int fd)
498 {
499 	struct constraint	*cstr;
500 
501 	TAILQ_FOREACH(cstr, &conf->constraints, entry) {
502 		if (cstr->fd == fd)
503 			return (cstr);
504 	}
505 
506 	return (NULL);
507 }
508 
509 struct constraint *
510 constraint_bypid(pid_t pid)
511 {
512 	struct constraint	*cstr;
513 
514 	TAILQ_FOREACH(cstr, &conf->constraints, entry) {
515 		if (cstr->pid == pid)
516 			return (cstr);
517 	}
518 
519 	return (NULL);
520 }
521 
522 int
523 constraint_close(u_int32_t id)
524 {
525 	struct constraint	*cstr;
526 
527 	if ((cstr = constraint_byid(id)) == NULL) {
528 		log_warn("%s: id %d: not found", __func__, id);
529 		return (0);
530 	}
531 
532 	cstr->last = getmonotime();
533 
534 	if (cstr->addr == NULL || (cstr->addr = cstr->addr->next) == NULL) {
535 		/* Either a pool or all addresses have been tried */
536 		cstr->addr = cstr->addr_head.a;
537 		if (cstr->senderrors)
538 			cstr->state = STATE_INVALID;
539 		else if (cstr->state >= STATE_QUERY_SENT)
540 			cstr->state = STATE_DNS_DONE;
541 
542 		return (1);
543 	}
544 
545 	/* Go on and try the next resolved address for this constraint */
546 	return (constraint_init(cstr));
547 }
548 
549 void
550 priv_constraint_close(int fd, int fail)
551 {
552 	struct constraint	*cstr;
553 	u_int32_t		 id;
554 
555 	if ((cstr = constraint_byfd(fd)) == NULL) {
556 		log_warn("%s: fd %d: not found", __func__, fd);
557 		return;
558 	}
559 
560 	id = cstr->id;
561 	constraint_remove(cstr);
562 	constraint_cnt--;
563 
564 	imsg_compose(ibuf, IMSG_CONSTRAINT_CLOSE, id, 0, -1,
565 	    &fail, sizeof(fail));
566 }
567 
568 void
569 constraint_add(struct constraint *cstr)
570 {
571 	TAILQ_INSERT_TAIL(&conf->constraints, cstr, entry);
572 }
573 
574 void
575 constraint_remove(struct constraint *cstr)
576 {
577 	TAILQ_REMOVE(&conf->constraints, cstr, entry);
578 
579 	msgbuf_clear(&cstr->ibuf.w);
580 	if (cstr->fd != -1)
581 		close(cstr->fd);
582 	free(cstr->addr_head.name);
583 	free(cstr->addr_head.path);
584 	free(cstr->addr);
585 	free(cstr);
586 }
587 
588 void
589 constraint_purge(void)
590 {
591 	struct constraint	*cstr, *ncstr;
592 
593 	TAILQ_FOREACH_SAFE(cstr, &conf->constraints, entry, ncstr)
594 		constraint_remove(cstr);
595 }
596 
597 int
598 priv_constraint_dispatch(struct pollfd *pfd)
599 {
600 	struct imsg		 imsg;
601 	struct constraint	*cstr;
602 	ssize_t			 n;
603 	struct timeval		 tv[2];
604 
605 	if ((cstr = constraint_byfd(pfd->fd)) == NULL)
606 		return (0);
607 
608 	if (!(pfd->revents & POLLIN))
609 		return (0);
610 
611 	if (((n = imsg_read(&cstr->ibuf)) == -1 && errno != EAGAIN) || n == 0) {
612 		priv_constraint_close(pfd->fd, 1);
613 		return (1);
614 	}
615 
616 	for (;;) {
617 		if ((n = imsg_get(&cstr->ibuf, &imsg)) == -1) {
618 			priv_constraint_close(pfd->fd, 1);
619 			return (1);
620 		}
621 		if (n == 0)
622 			break;
623 
624 		switch (imsg.hdr.type) {
625 		case IMSG_CONSTRAINT_RESULT:
626 			 if (imsg.hdr.len != IMSG_HEADER_SIZE + sizeof(tv))
627 				fatalx("invalid IMSG_CONSTRAINT received");
628 
629 			/* forward imsg to ntp child, don't parse it here */
630 			imsg_compose(ibuf, imsg.hdr.type,
631 			    cstr->id, 0, -1, imsg.data, sizeof(tv));
632 			break;
633 		default:
634 			break;
635 		}
636 		imsg_free(&imsg);
637 	}
638 
639 	return (0);
640 }
641 
642 void
643 constraint_msg_result(u_int32_t id, u_int8_t *data, size_t len)
644 {
645 	struct constraint	*cstr;
646 	struct timeval		 tv[2];
647 	double			 offset;
648 
649 	if ((cstr = constraint_byid(id)) == NULL) {
650 		log_warnx("IMSG_CONSTRAINT_CLOSE with invalid constraint id");
651 		return;
652 	}
653 
654 	if (len != sizeof(tv)) {
655 		log_warnx("invalid IMSG_CONSTRAINT received");
656 		return;
657 	}
658 
659 	memcpy(tv, data, len);
660 
661 	offset = gettime_from_timeval(&tv[0]) -
662 	    gettime_from_timeval(&tv[1]);
663 
664 	log_info("constraint reply from %s: offset %f",
665 	    log_sockaddr((struct sockaddr *)&cstr->addr->ss),
666 	    offset);
667 
668 	cstr->state = STATE_REPLY_RECEIVED;
669 	cstr->last = getmonotime();
670 	cstr->constraint = tv[0].tv_sec;
671 
672 	constraint_update();
673 }
674 
675 void
676 constraint_msg_close(u_int32_t id, u_int8_t *data, size_t len)
677 {
678 	struct constraint	*cstr;
679 	int			 fail;
680 
681 	if ((cstr = constraint_byid(id)) == NULL) {
682 		log_warnx("IMSG_CONSTRAINT_CLOSE with invalid constraint id");
683 		return;
684 	}
685 
686 	if (len != sizeof(int)) {
687 		log_warnx("invalid IMSG_CONSTRAINT_CLOSE received");
688 		return;
689 	}
690 
691 	memcpy(&fail, data, len);
692 
693 	if (fail) {
694 		log_debug("no constraint reply from %s"
695 		    " received in time, next query %ds",
696 		    log_sockaddr((struct sockaddr *)
697 		    &cstr->addr->ss), CONSTRAINT_SCAN_INTERVAL);
698 	}
699 
700 	if (fail || cstr->state < STATE_QUERY_SENT) {
701 		cstr->senderrors++;
702 		constraint_close(cstr->id);
703 	}
704 }
705 
706 void
707 constraint_msg_dns(u_int32_t id, u_int8_t *data, size_t len)
708 {
709 	struct constraint	*cstr, *ncstr = NULL;
710 	u_int8_t		*p;
711 	struct ntp_addr		*h;
712 
713 	if ((cstr = constraint_byid(id)) == NULL) {
714 		log_warnx("IMSG_CONSTRAINT_DNS with invalid constraint id");
715 		return;
716 	}
717 	if (cstr->addr != NULL) {
718 		log_warnx("IMSG_CONSTRAINT_DNS but addr != NULL!");
719 		return;
720 	}
721 	if (len == 0) {
722 		log_debug("%s FAILED", __func__);
723 		cstr->state = STATE_DNS_TEMPFAIL;
724 		return;
725 	}
726 
727 	if ((len % sizeof(struct sockaddr_storage)) != 0)
728 		fatalx("IMSG_CONSTRAINT_DNS len");
729 
730 	p = data;
731 	do {
732 		if ((h = calloc(1, sizeof(*h))) == NULL)
733 			fatal("calloc ntp_addr");
734 		memcpy(&h->ss, p, sizeof(h->ss));
735 		p += sizeof(h->ss);
736 		len -= sizeof(h->ss);
737 
738 		if (ncstr == NULL || cstr->addr_head.pool) {
739 			ncstr = new_constraint();
740 			ncstr->addr = h;
741 			ncstr->addr_head.a = h;
742 			ncstr->addr_head.name = strdup(cstr->addr_head.name);
743 			ncstr->addr_head.path = strdup(cstr->addr_head.path);
744 			if (ncstr->addr_head.name == NULL ||
745 			    ncstr->addr_head.path == NULL)
746 				fatal("calloc name");
747 			ncstr->addr_head.pool = cstr->addr_head.pool;
748 			ncstr->state = STATE_DNS_DONE;
749 			constraint_add(ncstr);
750 			constraint_cnt += constraint_init(ncstr);
751 		} else {
752 			h->next = ncstr->addr;
753 			ncstr->addr = h;
754 			ncstr->addr_head.a = h;
755 		}
756 	} while (len);
757 
758 	constraint_remove(cstr);
759 }
760 
761 int
762 constraint_cmp(const void *a, const void *b)
763 {
764 	return (*(const time_t *)a - *(const time_t *)b);
765 }
766 
767 void
768 constraint_update(void)
769 {
770 	struct constraint *cstr;
771 	int	 cnt, i;
772 	time_t	*sum;
773 	time_t	 now;
774 
775 	now = getmonotime();
776 
777 	cnt = 0;
778 	TAILQ_FOREACH(cstr, &conf->constraints, entry) {
779 		if (cstr->state != STATE_REPLY_RECEIVED)
780 			continue;
781 		cnt++;
782 	}
783 
784 	if ((sum = calloc(cnt, sizeof(time_t))) == NULL)
785 		fatal("calloc");
786 
787 	i = 0;
788 	TAILQ_FOREACH(cstr, &conf->constraints, entry) {
789 		if (cstr->state != STATE_REPLY_RECEIVED)
790 			continue;
791 		sum[i++] = cstr->constraint + (now - cstr->last);
792 	}
793 
794 	qsort(sum, cnt, sizeof(time_t), constraint_cmp);
795 
796 	/* calculate median */
797 	i = cnt / 2;
798 	if (cnt % 2 == 0)
799 		if (sum[i - 1] < sum[i])
800 			i -= 1;
801 
802 	conf->constraint_last = now;
803 	conf->constraint_median = sum[i];
804 
805 	free(sum);
806 }
807 
808 void
809 constraint_reset(void)
810 {
811 	struct constraint *cstr;
812 
813 	TAILQ_FOREACH(cstr, &conf->constraints, entry) {
814 		if (cstr->state == STATE_QUERY_SENT)
815 			continue;
816 		constraint_close(cstr->id);
817 	}
818 	conf->constraint_errors = 0;
819 }
820 
821 int
822 constraint_check(double val)
823 {
824 	struct timeval	tv;
825 	double		constraint;
826 	time_t		now;
827 
828 	if (conf->constraint_median == 0)
829 		return (0);
830 
831 	/* Calculate the constraint with the current offset */
832 	now = getmonotime();
833 	tv.tv_sec = conf->constraint_median + (now - conf->constraint_last);
834 	tv.tv_usec = 0;
835 	constraint = gettime_from_timeval(&tv);
836 
837 	if (((val - constraint) > CONSTRAINT_MARGIN) ||
838 	    ((constraint - val) > CONSTRAINT_MARGIN)) {
839 		/* XXX get new constraint if too many errors happened */
840 		if (conf->constraint_errors++ >
841 		    (CONSTRAINT_ERROR_MARGIN * peer_cnt)) {
842 			constraint_reset();
843 		}
844 
845 		return (-1);
846 	}
847 
848 	return (0);
849 }
850 
851 struct httpsdate *
852 httpsdate_init(const char *addr, const char *port, const char *hostname,
853     const char *path, const u_int8_t *ca, size_t ca_len)
854 {
855 	struct httpsdate	*httpsdate = NULL;
856 
857 	if ((httpsdate = calloc(1, sizeof(*httpsdate))) == NULL)
858 		goto fail;
859 
860 	if (hostname == NULL)
861 		hostname = addr;
862 
863 	if ((httpsdate->tls_addr = strdup(addr)) == NULL ||
864 	    (httpsdate->tls_port = strdup(port)) == NULL ||
865 	    (httpsdate->tls_hostname = strdup(hostname)) == NULL ||
866 	    (httpsdate->tls_path = strdup(path)) == NULL)
867 		goto fail;
868 
869 	if (asprintf(&httpsdate->tls_request,
870 	    "HEAD %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n",
871 	    httpsdate->tls_path, httpsdate->tls_hostname) == -1)
872 		goto fail;
873 
874 	if ((httpsdate->tls_config = tls_config_new()) == NULL)
875 		goto fail;
876 
877 	if (tls_config_set_ciphers(httpsdate->tls_config, "all") != 0)
878 		goto fail;
879 
880 	if (ca == NULL || ca_len == 0)
881 		tls_config_insecure_noverifycert(httpsdate->tls_config);
882 	else
883 		tls_config_set_ca_mem(httpsdate->tls_config, ca, ca_len);
884 
885 	return (httpsdate);
886 
887  fail:
888 	httpsdate_free(httpsdate);
889 	return (NULL);
890 }
891 
892 void
893 httpsdate_free(void *arg)
894 {
895 	struct httpsdate *httpsdate = arg;
896 	if (httpsdate == NULL)
897 		return;
898 	if (httpsdate->tls_ctx)
899 		tls_close(httpsdate->tls_ctx);
900 	tls_free(httpsdate->tls_ctx);
901 	tls_config_free(httpsdate->tls_config);
902 	free(httpsdate->tls_addr);
903 	free(httpsdate->tls_port);
904 	free(httpsdate->tls_hostname);
905 	free(httpsdate->tls_path);
906 	free(httpsdate->tls_request);
907 	free(httpsdate);
908 }
909 
910 int
911 httpsdate_request(struct httpsdate *httpsdate, struct timeval *when)
912 {
913 	size_t	 outlen = 0, maxlength = CONSTRAINT_MAXHEADERLENGTH, len;
914 	char	*line, *p, *buf;
915 	ssize_t	 ret;
916 
917 	if ((httpsdate->tls_ctx = tls_client()) == NULL)
918 		goto fail;
919 
920 	if (tls_configure(httpsdate->tls_ctx, httpsdate->tls_config) == -1)
921 		goto fail;
922 
923 	/*
924 	 * libtls expects an address string, which can also be a DNS name,
925 	 * but we pass a pre-resolved IP address string in tls_addr so it
926 	 * does not trigger any DNS operation and is safe to be called
927 	 * without the dns pledge.
928 	 */
929 	if (tls_connect_servername(httpsdate->tls_ctx, httpsdate->tls_addr,
930 	    httpsdate->tls_port, httpsdate->tls_hostname) == -1) {
931 		log_debug("tls connect failed: %s (%s): %s",
932 		    httpsdate->tls_addr, httpsdate->tls_hostname,
933 		    tls_error(httpsdate->tls_ctx));
934 		goto fail;
935 	}
936 
937 	buf = httpsdate->tls_request;
938 	len = strlen(httpsdate->tls_request);
939 	while (len > 0) {
940 		ret = tls_write(httpsdate->tls_ctx, buf, len);
941 		if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT)
942 			continue;
943 		if (ret < 0) {
944 			log_warnx("tls write failed: %s (%s): %s",
945 			    httpsdate->tls_addr, httpsdate->tls_hostname,
946 			    tls_error(httpsdate->tls_ctx));
947 			goto fail;
948 		}
949 		buf += ret;
950 		len -= ret;
951 	}
952 
953 	while ((line = tls_readline(httpsdate->tls_ctx, &outlen,
954 	    &maxlength, when)) != NULL) {
955 		line[strcspn(line, "\r\n")] = '\0';
956 
957 		if ((p = strchr(line, ' ')) == NULL || *p == '\0')
958 			goto next;
959 		*p++ = '\0';
960 		if (strcasecmp("Date:", line) != 0)
961 			goto next;
962 
963 		/*
964 		 * Expect the date/time format as IMF-fixdate which is
965 		 * mandated by HTTP/1.1 in the new RFC 7231 and was
966 		 * preferred by RFC 2616.  Other formats would be RFC 850
967 		 * or ANSI C's asctime() - the latter doesn't include
968 		 * the timezone which is required here.
969 		 */
970 		if (strptime(p, "%a, %d %h %Y %T GMT",
971 		    &httpsdate->tls_tm) == NULL) {
972 			log_warnx("unsupported date format");
973 			free(line);
974 			return (-1);
975 		}
976 
977 		free(line);
978 		break;
979  next:
980 		free(line);
981 	}
982 
983 	return (0);
984 
985  fail:
986 	httpsdate_free(httpsdate);
987 	return (-1);
988 }
989 
990 void *
991 httpsdate_query(const char *addr, const char *port, const char *hostname,
992     const char *path, const u_int8_t *ca, size_t ca_len,
993     struct timeval *rectv, struct timeval *xmttv)
994 {
995 	struct httpsdate	*httpsdate;
996 	struct timeval		 when;
997 	time_t			 t;
998 
999 	if ((httpsdate = httpsdate_init(addr, port, hostname, path,
1000 	    ca, ca_len)) == NULL)
1001 		return (NULL);
1002 
1003 	if (httpsdate_request(httpsdate, &when) == -1)
1004 		return (NULL);
1005 
1006 	/* Return parsed date as local time */
1007 	t = timegm(&httpsdate->tls_tm);
1008 
1009 	/* Report parsed Date: as "received time" */
1010 	rectv->tv_sec = t;
1011 	rectv->tv_usec = 0;
1012 
1013 	/* And add delay as "transmit time" */
1014 	xmttv->tv_sec = when.tv_sec;
1015 	xmttv->tv_usec = when.tv_usec;
1016 
1017 	return (httpsdate);
1018 }
1019 
1020 /* Based on SSL_readline in ftp/fetch.c */
1021 char *
1022 tls_readline(struct tls *tls, size_t *lenp, size_t *maxlength,
1023     struct timeval *when)
1024 {
1025 	size_t i, len;
1026 	char *buf, *q, c;
1027 	ssize_t ret;
1028 
1029 	len = 128;
1030 	if ((buf = malloc(len)) == NULL)
1031 		fatal("Can't allocate memory for transfer buffer");
1032 	for (i = 0; ; i++) {
1033 		if (i >= len - 1) {
1034 			if ((q = reallocarray(buf, len, 2)) == NULL)
1035 				fatal("Can't expand transfer buffer");
1036 			buf = q;
1037 			len *= 2;
1038 		}
1039  again:
1040 		ret = tls_read(tls, &c, 1);
1041 		if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT)
1042 			goto again;
1043 		if (ret < 0) {
1044 			/* SSL read error, ignore */
1045 			free(buf);
1046 			return (NULL);
1047 		}
1048 
1049 		if (maxlength != NULL && (*maxlength)-- == 0) {
1050 			log_warnx("maximum length exceeded");
1051 			free(buf);
1052 			return (NULL);
1053 		}
1054 
1055 		buf[i] = c;
1056 		if (c == '\n')
1057 			break;
1058 	}
1059 	*lenp = i;
1060 	if (gettimeofday(when, NULL) == -1)
1061 		fatal("gettimeofday");
1062 	return (buf);
1063 }
1064 
1065 char *
1066 get_string(u_int8_t *ptr, size_t len)
1067 {
1068 	size_t	 i;
1069 
1070 	for (i = 0; i < len; i++)
1071 		if (!(isprint(ptr[i]) || isspace(ptr[i])))
1072 			break;
1073 
1074 	return strndup(ptr, i);
1075 }
1076