xref: /openbsd/sbin/unwind/frontend.c (revision 3538560b)
1 /*	$OpenBSD: frontend.c,v 1.63 2021/01/19 16:52:12 florian Exp $	*/
2 
3 /*
4  * Copyright (c) 2018 Florian Obser <florian@openbsd.org>
5  * Copyright (c) 2005 Claudio Jeker <claudio@openbsd.org>
6  * Copyright (c) 2004 Esben Norby <norby@openbsd.org>
7  * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
8  *
9  * Permission to use, copy, modify, and distribute this software for any
10  * purpose with or without fee is hereby granted, provided that the above
11  * copyright notice and this permission notice appear in all copies.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20  */
21 
22 #include <sys/types.h>
23 #include <sys/queue.h>
24 #include <sys/socket.h>
25 #include <sys/syslog.h>
26 #include <sys/tree.h>
27 #include <sys/uio.h>
28 
29 #include <netinet/in.h>
30 #include <net/if.h>
31 #include <net/route.h>
32 
33 #include <errno.h>
34 #include <event.h>
35 #include <imsg.h>
36 #include <netdb.h>
37 #include <pwd.h>
38 #include <signal.h>
39 #include <stdint.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <time.h>
44 #include <unistd.h>
45 
46 #include "libunbound/config.h"
47 #include "libunbound/sldns/pkthdr.h"
48 #include "libunbound/sldns/sbuffer.h"
49 #include "libunbound/sldns/str2wire.h"
50 #include "libunbound/sldns/wire2str.h"
51 #include "libunbound/util/alloc.h"
52 #include "libunbound/util/net_help.h"
53 #include "libunbound/util/regional.h"
54 #include "libunbound/util/data/dname.h"
55 #include "libunbound/util/data/msgencode.h"
56 #include "libunbound/util/data/msgparse.h"
57 #include "libunbound/util/data/msgreply.h"
58 
59 #include "log.h"
60 #include "unwind.h"
61 #include "frontend.h"
62 #include "control.h"
63 
64 #define	ROUTE_SOCKET_BUF_SIZE   16384
65 
66 /*
67  * size of a resource record with name a two octed pointer to qname
68  * 2 octets pointer to qname
69  * 2 octets TYPE
70  * 2 octets CLASS
71  * 4 octets TTL
72  * 2 octets RDLENGTH
73  */
74 #define COMPRESSED_RR_SIZE	12
75 #define MINIMIZE_ANSWER		1
76 
77 #define FD_RESERVE		5
78 #define TCP_TIMEOUT		15
79 #define DEFAULT_TCP_SIZE	512
80 
81 struct udp_ev {
82 	struct event		 ev;
83 	uint8_t			 query[65536];
84 	struct msghdr		 rcvmhdr;
85 	struct iovec		 rcviov[1];
86 	struct sockaddr_storage	 from;
87 } udp4ev, udp6ev;
88 
89 struct tcp_accept_ev {
90 	struct event		 ev;
91 	struct event		 pause;
92 } tcp4ev, tcp6ev;
93 
94 struct pending_query {
95 	TAILQ_ENTRY(pending_query)	 entry;
96 	struct sockaddr_storage		 from;
97 	struct sldns_buffer		*qbuf;
98 	struct sldns_buffer		*abuf;
99 	struct regional			*region;
100 	struct query_info		 qinfo;
101 	struct msg_parse		*qmsg;
102 	struct edns_data		 edns;
103 	struct event			 ev;		/* for tcp */
104 	struct event			 resp_ev;	/* for tcp */
105 	struct event			 tmo_ev;	/* for tcp */
106 	uint64_t			 imsg_id;
107 	int				 fd;
108 	int				 tcp;
109 };
110 
111 TAILQ_HEAD(, pending_query)	 pending_queries;
112 
113 struct bl_node {
114 	RB_ENTRY(bl_node)	 entry;
115 	char			*domain;
116 };
117 
118 __dead void		 frontend_shutdown(void);
119 void			 frontend_sig_handler(int, short, void *);
120 void			 frontend_startup(void);
121 void			 udp_receive(int, short, void *);
122 void			 handle_query(struct pending_query *);
123 void			 free_pending_query(struct pending_query *);
124 void			 tcp_accept(int, short, void *);
125 int			 accept_reserve(int, struct sockaddr *, socklen_t *);
126 void			 accept_paused(int, short, void *);
127 void			 tcp_request(int, short, void *);
128 void			 tcp_response(int, short, void *);
129 void			 tcp_timeout(int, short, void *);
130 int			 check_query(sldns_buffer*);
131 void			 noerror_answer(struct pending_query *);
132 void			 chaos_answer(struct pending_query *);
133 void			 error_answer(struct pending_query *, int rcode);
134 void			 send_answer(struct pending_query *);
135 void			 route_receive(int, short, void *);
136 void			 handle_route_message(struct rt_msghdr *,
137 			     struct sockaddr **);
138 void			 get_rtaddrs(int, struct sockaddr *,
139 			     struct sockaddr **);
140 void			 rtmget_default(void);
141 struct pending_query	*find_pending_query(uint64_t);
142 void			 parse_trust_anchor(struct trust_anchor_head *, int);
143 void			 send_trust_anchors(struct trust_anchor_head *);
144 void			 write_trust_anchors(struct trust_anchor_head *, int);
145 void			 parse_blocklist(int);
146 int			 bl_cmp(struct bl_node *, struct bl_node *);
147 void			 free_bl(void);
148 int			 pending_query_cnt(void);
149 
150 struct uw_conf		*frontend_conf;
151 struct imsgev		*iev_main;
152 struct imsgev		*iev_resolver;
153 struct event		 ev_route;
154 int			 udp4sock = -1, udp6sock = -1;
155 int			 tcp4sock = -1, tcp6sock = -1;
156 int			 ta_fd = -1;
157 
158 static struct trust_anchor_head	 trust_anchors, new_trust_anchors;
159 
160 RB_HEAD(bl_tree, bl_node)	 bl_head = RB_INITIALIZER(&bl_head);
161 RB_PROTOTYPE(bl_tree, bl_node, entry, bl_cmp)
162 RB_GENERATE(bl_tree, bl_node, entry, bl_cmp)
163 
164 void
165 frontend_sig_handler(int sig, short event, void *bula)
166 {
167 	/*
168 	 * Normal signal handler rules don't apply because libevent
169 	 * decouples for us.
170 	 */
171 
172 	switch (sig) {
173 	case SIGINT:
174 	case SIGTERM:
175 		frontend_shutdown();
176 	default:
177 		fatalx("unexpected signal");
178 	}
179 }
180 
181 void
182 frontend(int debug, int verbose)
183 {
184 	struct event	 ev_sigint, ev_sigterm;
185 	struct passwd	*pw;
186 
187 	frontend_conf = config_new_empty();
188 
189 	log_init(debug, LOG_DAEMON);
190 	log_setverbose(verbose);
191 
192 	if ((pw = getpwnam(UNWIND_USER)) == NULL)
193 		fatal("getpwnam");
194 
195 	if (chroot(pw->pw_dir) == -1)
196 		fatal("chroot");
197 	if (chdir("/") == -1)
198 		fatal("chdir(\"/\")");
199 
200 	setproctitle("%s", "frontend");
201 	log_procinit("frontend");
202 
203 	if (setgroups(1, &pw->pw_gid) ||
204 	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
205 	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
206 		fatal("can't drop privileges");
207 
208 	if (pledge("stdio unix recvfd", NULL) == -1)
209 		fatal("pledge");
210 
211 	event_init();
212 
213 	/* Setup signal handler. */
214 	signal_set(&ev_sigint, SIGINT, frontend_sig_handler, NULL);
215 	signal_set(&ev_sigterm, SIGTERM, frontend_sig_handler, NULL);
216 	signal_add(&ev_sigint, NULL);
217 	signal_add(&ev_sigterm, NULL);
218 	signal(SIGPIPE, SIG_IGN);
219 	signal(SIGHUP, SIG_IGN);
220 
221 	/* Setup pipe and event handler to the parent process. */
222 	if (iev_main != NULL)
223 		fatal("iev_main");
224 	if ((iev_main = malloc(sizeof(struct imsgev))) == NULL)
225 		fatal(NULL);
226 	imsg_init(&iev_main->ibuf, 3);
227 	iev_main->handler = frontend_dispatch_main;
228 	iev_main->events = EV_READ;
229 	event_set(&iev_main->ev, iev_main->ibuf.fd, iev_main->events,
230 	    iev_main->handler, iev_main);
231 	event_add(&iev_main->ev, NULL);
232 
233 	udp4ev.rcviov[0].iov_base = (caddr_t)udp4ev.query;
234 	udp4ev.rcviov[0].iov_len = sizeof(udp4ev.query);
235 	udp4ev.rcvmhdr.msg_name = (caddr_t)&udp4ev.from;
236 	udp4ev.rcvmhdr.msg_namelen = sizeof(udp4ev.from);
237 	udp4ev.rcvmhdr.msg_iov = udp4ev.rcviov;
238 	udp4ev.rcvmhdr.msg_iovlen = 1;
239 
240 	udp6ev.rcviov[0].iov_base = (caddr_t)udp6ev.query;
241 	udp6ev.rcviov[0].iov_len = sizeof(udp6ev.query);
242 	udp6ev.rcvmhdr.msg_name = (caddr_t)&udp6ev.from;
243 	udp6ev.rcvmhdr.msg_namelen = sizeof(udp6ev.from);
244 	udp6ev.rcvmhdr.msg_iov = udp6ev.rcviov;
245 	udp6ev.rcvmhdr.msg_iovlen = 1;
246 
247 	TAILQ_INIT(&pending_queries);
248 
249 	TAILQ_INIT(&trust_anchors);
250 	TAILQ_INIT(&new_trust_anchors);
251 
252 	add_new_ta(&trust_anchors, KSK2017);
253 
254 	event_dispatch();
255 
256 	frontend_shutdown();
257 }
258 
259 __dead void
260 frontend_shutdown(void)
261 {
262 	/* Close pipes. */
263 	msgbuf_write(&iev_resolver->ibuf.w);
264 	msgbuf_clear(&iev_resolver->ibuf.w);
265 	close(iev_resolver->ibuf.fd);
266 	msgbuf_write(&iev_main->ibuf.w);
267 	msgbuf_clear(&iev_main->ibuf.w);
268 	close(iev_main->ibuf.fd);
269 
270 	config_clear(frontend_conf);
271 
272 	free(iev_resolver);
273 	free(iev_main);
274 
275 	log_info("frontend exiting");
276 	exit(0);
277 }
278 
279 int
280 frontend_imsg_compose_main(int type, pid_t pid, void *data, uint16_t datalen)
281 {
282 	return (imsg_compose_event(iev_main, type, 0, pid, -1, data, datalen));
283 }
284 
285 int
286 frontend_imsg_compose_resolver(int type, pid_t pid, void *data,
287     uint16_t datalen)
288 {
289 	return (imsg_compose_event(iev_resolver, type, 0, pid, -1, data,
290 	    datalen));
291 }
292 
293 void
294 frontend_dispatch_main(int fd, short event, void *bula)
295 {
296 	static struct uw_conf	*nconf;
297 	struct imsg		 imsg;
298 	struct imsgev		*iev = bula;
299 	struct imsgbuf		*ibuf = &iev->ibuf;
300 	int			 n, shut = 0;
301 
302 	if (event & EV_READ) {
303 		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
304 			fatal("imsg_read error");
305 		if (n == 0)	/* Connection closed. */
306 			shut = 1;
307 	}
308 	if (event & EV_WRITE) {
309 		if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
310 			fatal("msgbuf_write");
311 		if (n == 0)	/* Connection closed. */
312 			shut = 1;
313 	}
314 
315 	for (;;) {
316 		if ((n = imsg_get(ibuf, &imsg)) == -1)
317 			fatal("%s: imsg_get error", __func__);
318 		if (n == 0)	/* No more messages. */
319 			break;
320 
321 		switch (imsg.hdr.type) {
322 		case IMSG_SOCKET_IPC_RESOLVER:
323 			/*
324 			 * Setup pipe and event handler to the resolver
325 			 * process.
326 			 */
327 			if (iev_resolver) {
328 				fatalx("%s: received unexpected imsg fd "
329 				    "to frontend", __func__);
330 				break;
331 			}
332 			if ((fd = imsg.fd) == -1) {
333 				fatalx("%s: expected to receive imsg fd to "
334 				   "frontend but didn't receive any",
335 				   __func__);
336 				break;
337 			}
338 
339 			if (iev_resolver != NULL)
340 				fatal("iev_resolver");
341 			iev_resolver = malloc(sizeof(struct imsgev));
342 			if (iev_resolver == NULL)
343 				fatal(NULL);
344 
345 			imsg_init(&iev_resolver->ibuf, fd);
346 			iev_resolver->handler = frontend_dispatch_resolver;
347 			iev_resolver->events = EV_READ;
348 
349 			event_set(&iev_resolver->ev, iev_resolver->ibuf.fd,
350 			    iev_resolver->events, iev_resolver->handler,
351 			    iev_resolver);
352 			event_add(&iev_resolver->ev, NULL);
353 			break;
354 		case IMSG_RECONF_CONF:
355 		case IMSG_RECONF_BLOCKLIST_FILE:
356 		case IMSG_RECONF_FORWARDER:
357 		case IMSG_RECONF_DOT_FORWARDER:
358 		case IMSG_RECONF_FORCE:
359 			imsg_receive_config(&imsg, &nconf);
360 			break;
361 		case IMSG_RECONF_END:
362 			if (nconf == NULL)
363 				fatalx("%s: IMSG_RECONF_END without "
364 				    "IMSG_RECONF_CONF", __func__);
365 			merge_config(frontend_conf, nconf);
366 			if (frontend_conf->blocklist_file == NULL)
367 				free_bl();
368 			nconf = NULL;
369 			break;
370 		case IMSG_UDP6SOCK:
371 			if (udp6sock != -1)
372 				fatalx("%s: received unexpected udp6sock",
373 				    __func__);
374 			if ((udp6sock = imsg.fd) == -1)
375 				fatalx("%s: expected to receive imsg "
376 				    "UDP6 fd but didn't receive any", __func__);
377 			event_set(&udp6ev.ev, udp6sock, EV_READ | EV_PERSIST,
378 			    udp_receive, &udp6ev);
379 			event_add(&udp6ev.ev, NULL);
380 			break;
381 		case IMSG_UDP4SOCK:
382 			if (udp4sock != -1)
383 				fatalx("%s: received unexpected udp4sock",
384 				    __func__);
385 			if ((udp4sock = imsg.fd) == -1)
386 				fatalx("%s: expected to receive imsg "
387 				    "UDP4 fd but didn't receive any", __func__);
388 			event_set(&udp4ev.ev, udp4sock, EV_READ | EV_PERSIST,
389 			    udp_receive, &udp4ev);
390 			event_add(&udp4ev.ev, NULL);
391 			break;
392 		case IMSG_TCP4SOCK:
393 			if (tcp4sock != -1)
394 				fatalx("%s: received unexpected tcp4sock",
395 				    __func__);
396 			if ((tcp4sock = imsg.fd) == -1)
397 				fatalx("%s: expected to receive imsg "
398 				    "TCP4 fd but didn't receive any", __func__);
399 			event_set(&tcp4ev.ev, tcp4sock, EV_READ | EV_PERSIST,
400 			    tcp_accept, &tcp4ev);
401 			event_add(&tcp4ev.ev, NULL);
402 			evtimer_set(&tcp4ev.pause, accept_paused, &tcp4ev);
403 			break;
404 		case IMSG_TCP6SOCK:
405 			if (tcp6sock != -1)
406 				fatalx("%s: received unexpected tcp6sock",
407 				    __func__);
408 			if ((tcp6sock = imsg.fd) == -1)
409 				fatalx("%s: expected to receive imsg "
410 				    "TCP6 fd but didn't receive any", __func__);
411 			event_set(&tcp6ev.ev, tcp6sock, EV_READ | EV_PERSIST,
412 			    tcp_accept, &tcp6ev);
413 			event_add(&tcp6ev.ev, NULL);
414 			evtimer_set(&tcp6ev.pause, accept_paused, &tcp6ev);
415 			break;
416 		case IMSG_ROUTESOCK: {
417 			static int	 routesock = -1;
418 
419 			if (routesock != -1)
420 				fatalx("%s: received unexpected routesock",
421 				    __func__);
422 			if ((fd = imsg.fd) == -1)
423 				fatalx("%s: expected to receive imsg "
424 				    "routesocket fd but didn't receive any",
425 				    __func__);
426 			routesock = fd;
427 			event_set(&ev_route, fd, EV_READ | EV_PERSIST,
428 			    route_receive, NULL);
429 			break;
430 		}
431 		case IMSG_STARTUP:
432 			frontend_startup();
433 			break;
434 		case IMSG_CONTROLFD:
435 			if ((fd = imsg.fd) == -1)
436 				fatalx("%s: expected to receive imsg control "
437 				    "fd but didn't receive any", __func__);
438 			/* Listen on control socket. */
439 			control_listen(fd);
440 			break;
441 		case IMSG_TAFD:
442 			if ((ta_fd = imsg.fd) != -1)
443 				parse_trust_anchor(&trust_anchors, ta_fd);
444 			if (!TAILQ_EMPTY(&trust_anchors))
445 				send_trust_anchors(&trust_anchors);
446 			break;
447 		case IMSG_BLFD:
448 			if ((fd = imsg.fd) == -1)
449 				fatalx("%s: expected to receive imsg block "
450 				   "list fd but didn't receive any", __func__);
451 			parse_blocklist(fd);
452 			break;
453 		default:
454 			log_debug("%s: error handling imsg %d", __func__,
455 			    imsg.hdr.type);
456 			break;
457 		}
458 		imsg_free(&imsg);
459 	}
460 	if (!shut)
461 		imsg_event_add(iev);
462 	else {
463 		/* This pipe is dead. Remove its event handler. */
464 		event_del(&iev->ev);
465 		event_loopexit(NULL);
466 	}
467 }
468 
469 void
470 frontend_dispatch_resolver(int fd, short event, void *bula)
471 {
472 	struct pending_query		*pq;
473 	struct imsgev			*iev = bula;
474 	struct imsgbuf			*ibuf = &iev->ibuf;
475 	struct imsg			 imsg;
476 	int				 n, shut = 0, chg;
477 
478 	if (event & EV_READ) {
479 		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
480 			fatal("imsg_read error");
481 		if (n == 0)	/* Connection closed. */
482 			shut = 1;
483 	}
484 	if (event & EV_WRITE) {
485 		if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
486 			fatal("msgbuf_write");
487 		if (n == 0)	/* Connection closed. */
488 			shut = 1;
489 	}
490 
491 	for (;;) {
492 		if ((n = imsg_get(ibuf, &imsg)) == -1)
493 			fatal("%s: imsg_get error", __func__);
494 		if (n == 0)	/* No more messages. */
495 			break;
496 
497 		switch (imsg.hdr.type) {
498 		case IMSG_ANSWER: {
499 			struct answer_header	*answer_header;
500 			int			 data_len;
501 			uint8_t			*data;
502 
503 			if (IMSG_DATA_SIZE(imsg) < sizeof(*answer_header))
504 				fatalx("%s: IMSG_ANSWER wrong length: "
505 				    "%lu", __func__, IMSG_DATA_SIZE(imsg));
506 			answer_header = (struct answer_header *)imsg.data;
507 			data = (uint8_t *)imsg.data + sizeof(*answer_header);
508 			if (answer_header->answer_len > UINT16_MAX)
509 				fatalx("%s: IMSG_ANSWER answer too big: %d",
510 				    __func__, answer_header->answer_len);
511 			data_len = IMSG_DATA_SIZE(imsg) -
512 			    sizeof(*answer_header);
513 
514 			if ((pq = find_pending_query(answer_header->id)) ==
515 			    NULL) {
516 				log_warnx("%s: cannot find pending query %llu",
517 				    __func__, answer_header->id);
518 				break;
519 			}
520 
521 			if (answer_header->srvfail) {
522 				error_answer(pq, LDNS_RCODE_SERVFAIL);
523 				send_answer(pq);
524 				break;
525 			}
526 
527 			if (answer_header->bogus && !(pq->qmsg->flags &
528 			    BIT_CD)) {
529 				error_answer(pq, LDNS_RCODE_SERVFAIL);
530 				send_answer(pq);
531 				break;
532 			}
533 
534 			if (sldns_buffer_position(pq->abuf) == 0 &&
535 			    !sldns_buffer_set_capacity(pq->abuf,
536 			    answer_header->answer_len)) {
537 				error_answer(pq, LDNS_RCODE_SERVFAIL);
538 				send_answer(pq);
539 				break;
540 			}
541 
542 			if (sldns_buffer_position(pq->abuf) + data_len >
543 			    sldns_buffer_capacity(pq->abuf))
544 				fatalx("%s: IMSG_ANSWER answer too big: %d",
545 				    __func__, data_len);
546 			sldns_buffer_write(pq->abuf, data, data_len);
547 
548 			if (sldns_buffer_position(pq->abuf) ==
549 			    sldns_buffer_capacity(pq->abuf)) {
550 				sldns_buffer_flip(pq->abuf);
551 				noerror_answer(pq);
552 				send_answer(pq);
553 			}
554 			break;
555 		}
556 		case IMSG_CTL_RESOLVER_INFO:
557 		case IMSG_CTL_AUTOCONF_RESOLVER_INFO:
558 		case IMSG_CTL_MEM_INFO:
559 		case IMSG_CTL_END:
560 			control_imsg_relay(&imsg);
561 			break;
562 		case IMSG_NEW_TA:
563 			/* make sure this is a string */
564 			((char *)imsg.data)[IMSG_DATA_SIZE(imsg) - 1] = '\0';
565 			add_new_ta(&new_trust_anchors, imsg.data);
566 			break;
567 		case IMSG_NEW_TAS_ABORT:
568 			free_tas(&new_trust_anchors);
569 			break;
570 		case IMSG_NEW_TAS_DONE:
571 			chg = merge_tas(&new_trust_anchors, &trust_anchors);
572 			if (chg)
573 				send_trust_anchors(&trust_anchors);
574 
575 			/*
576 			 * always write trust anchors, the modify date on
577 			 * the file is an indication when we made progress
578 			 */
579 			if (ta_fd != -1)
580 				write_trust_anchors(&trust_anchors, ta_fd);
581 			break;
582 		default:
583 			log_debug("%s: error handling imsg %d", __func__,
584 			    imsg.hdr.type);
585 			break;
586 		}
587 		imsg_free(&imsg);
588 	}
589 	if (!shut)
590 		imsg_event_add(iev);
591 	else {
592 		/* This pipe is dead. Remove its event handler. */
593 		event_del(&iev->ev);
594 		event_loopexit(NULL);
595 	}
596 }
597 
598 void
599 frontend_startup(void)
600 {
601 	if (!event_initialized(&ev_route))
602 		fatalx("%s: did not receive a route socket from the main "
603 		    "process", __func__);
604 
605 	event_add(&ev_route, NULL);
606 
607 	frontend_imsg_compose_main(IMSG_STARTUP_DONE, 0, NULL, 0);
608 }
609 
610 void
611 free_pending_query(struct pending_query *pq)
612 {
613 	if (!pq)
614 		return;
615 
616 	TAILQ_REMOVE(&pending_queries, pq, entry);
617 	regional_destroy(pq->region);
618 	sldns_buffer_free(pq->qbuf);
619 	sldns_buffer_free(pq->abuf);
620 	if (pq->tcp) {
621 		if (event_initialized(&pq->ev))
622 			event_del(&pq->ev);
623 		if (event_initialized(&pq->resp_ev))
624 			event_del(&pq->resp_ev);
625 		if (event_initialized(&pq->tmo_ev))
626 			event_del(&pq->tmo_ev);
627 		if (pq->fd != -1)
628 			close(pq->fd);
629 	}
630 	free(pq);
631 }
632 
633 void
634 udp_receive(int fd, short events, void *arg)
635 {
636 	struct udp_ev		*udpev = (struct udp_ev *)arg;
637 	struct pending_query	*pq = NULL;
638 	ssize_t			 len;
639 
640 	if ((len = recvmsg(fd, &udpev->rcvmhdr, 0)) == -1) {
641 		log_warn("recvmsg");
642 		return;
643 	}
644 
645 	if ((pq = calloc(1, sizeof(*pq))) == NULL) {
646 		log_warn(NULL);
647 		return;
648 	}
649 
650 	do {
651 		arc4random_buf(&pq->imsg_id, sizeof(pq->imsg_id));
652 	} while(find_pending_query(pq->imsg_id) != NULL);
653 
654 	TAILQ_INSERT_TAIL(&pending_queries, pq, entry);
655 
656 	pq->from = udpev->from;
657 	pq->fd = fd;
658 	pq->qbuf = sldns_buffer_new(len);
659 	pq->abuf = sldns_buffer_new(len); /* make sure we can send errors */
660 	pq->region = regional_create();
661 	pq->qmsg = regional_alloc(pq->region, sizeof(*pq->qmsg));
662 
663 	if (!pq->qbuf || !pq->abuf || !pq->region || !pq->qmsg) {
664 		log_warnx("out of memory");
665 		free_pending_query(pq);
666 		return;
667 	}
668 
669 	memset(pq->qmsg, 0, sizeof(*pq->qmsg));
670 	sldns_buffer_write(pq->qbuf, udpev->query, len);
671 	sldns_buffer_flip(pq->qbuf);
672 	handle_query(pq);
673 }
674 
675 void
676 handle_query(struct pending_query *pq)
677 {
678 	struct query_imsg	 query_imsg;
679 	struct bl_node		 find;
680 	int			 rcode;
681 	char			*str;
682 	char			 dname[LDNS_MAX_DOMAINLEN + 1];
683 	char			 qclass_buf[16];
684 	char			 qtype_buf[16];
685 
686 	if (log_getverbose() & OPT_VERBOSE2 && (str =
687 	    sldns_wire2str_pkt(sldns_buffer_begin(pq->qbuf),
688 	    sldns_buffer_limit(pq->qbuf))) != NULL) {
689 		log_debug("from: %s\n%s", ip_port((struct sockaddr *)
690 		    &pq->from), str);
691 		free(str);
692 	}
693 
694 	if (!query_info_parse(&pq->qinfo, pq->qbuf)) {
695 		log_warnx("query_info_parse failed");
696 		goto drop;
697 	}
698 
699 	sldns_buffer_rewind(pq->qbuf);
700 
701 	if (parse_packet(pq->qbuf, pq->qmsg, pq->region) !=
702 	    LDNS_RCODE_NOERROR) {
703 		log_warnx("parse_packet failed");
704 		goto drop;
705 	}
706 
707 	rcode = check_query(pq->qbuf);
708 	switch (rcode) {
709 	case LDNS_RCODE_NOERROR:
710 		break;
711 	case -1:
712 		goto drop;
713 	default:
714 		error_answer(pq, rcode);
715 		goto send_answer;
716 	}
717 
718 	rcode = parse_extract_edns(pq->qmsg, &pq->edns, pq->region);
719 	if (rcode != LDNS_RCODE_NOERROR) {
720 		error_answer(pq, rcode);
721 		goto send_answer;
722 	}
723 
724 	if (!dname_valid(pq->qinfo.qname, pq->qinfo.qname_len)) {
725 		error_answer(pq, LDNS_RCODE_FORMERR);
726 		goto send_answer;
727 	}
728 	dname_str(pq->qinfo.qname, dname);
729 
730 	sldns_wire2str_class_buf(pq->qinfo.qclass, qclass_buf,
731 	    sizeof(qclass_buf));
732 	sldns_wire2str_type_buf(pq->qinfo.qtype, qtype_buf, sizeof(qtype_buf));
733 	log_debug("%s: %s %s %s ?", ip_port((struct sockaddr *)&pq->from),
734 	    dname, qclass_buf, qtype_buf);
735 
736 	find.domain = dname;
737 	if (RB_FIND(bl_tree, &bl_head, &find) != NULL) {
738 		if (frontend_conf->blocklist_log)
739 			log_info("blocking %s", dname);
740 		error_answer(pq, LDNS_RCODE_REFUSED);
741 		goto send_answer;
742 	}
743 
744 	if (pq->qinfo.qtype == LDNS_RR_TYPE_AXFR || pq->qinfo.qtype ==
745 	    LDNS_RR_TYPE_IXFR) {
746 		error_answer(pq, LDNS_RCODE_REFUSED);
747 		goto send_answer;
748 	}
749 
750 	if(pq->qinfo.qtype == LDNS_RR_TYPE_OPT ||
751 	    pq->qinfo.qtype == LDNS_RR_TYPE_TSIG ||
752 	    pq->qinfo.qtype == LDNS_RR_TYPE_TKEY ||
753 	    pq->qinfo.qtype == LDNS_RR_TYPE_MAILA ||
754 	    pq->qinfo.qtype == LDNS_RR_TYPE_MAILB ||
755 	    (pq->qinfo.qtype >= 128 && pq->qinfo.qtype <= 248)) {
756 		error_answer(pq, LDNS_RCODE_FORMERR);
757 		goto send_answer;
758 	}
759 
760 	if (pq->qinfo.qclass == LDNS_RR_CLASS_CH) {
761 		if (strcasecmp(dname, "version.server.") == 0 ||
762 		    strcasecmp(dname, "version.bind.") == 0) {
763 			chaos_answer(pq);
764 		} else
765 			error_answer(pq, LDNS_RCODE_REFUSED);
766 		goto send_answer;
767 	}
768 
769 	if (strlcpy(query_imsg.qname, dname, sizeof(query_imsg.qname)) >=
770 	    sizeof(query_imsg.qname)) {
771 		log_warnx("qname too long");
772 		error_answer(pq, LDNS_RCODE_FORMERR);
773 		goto send_answer;
774 	}
775 	query_imsg.id = pq->imsg_id;
776 	query_imsg.t = pq->qinfo.qtype;
777 	query_imsg.c = pq->qinfo.qclass;
778 
779 	if (frontend_imsg_compose_resolver(IMSG_QUERY, 0, &query_imsg,
780 	    sizeof(query_imsg)) == -1) {
781 		error_answer(pq, LDNS_RCODE_SERVFAIL);
782 		goto send_answer;
783 	}
784 	return;
785 
786  send_answer:
787 	send_answer(pq);
788 	return;
789 
790  drop:
791 	free_pending_query(pq);
792 }
793 
794 void
795 noerror_answer(struct pending_query *pq)
796 {
797 	struct query_info	 skip, qinfo;
798 	struct reply_info	*rinfo = NULL;
799 	struct alloc_cache	 alloc;
800 	struct edns_data	 edns;
801 
802 	alloc_init(&alloc, NULL, 0);
803 	memset(&qinfo, 0, sizeof(qinfo));
804 	/* read past query section, no memory is allocated */
805 	if (!query_info_parse(&skip, pq->abuf))
806 		goto srvfail;
807 
808 	if (reply_info_parse(pq->abuf, &alloc, &qinfo, &rinfo, pq->region,
809 	    &edns) != 0)
810 		goto srvfail;
811 	/* reply_info_parse() allocates memory */
812 	query_info_clear(&qinfo);
813 
814 	sldns_buffer_clear(pq->abuf);
815 	if (reply_info_encode(&pq->qinfo, rinfo, pq->qmsg->id, rinfo->flags,
816 	    pq->abuf, 0, pq->region, pq->tcp ? UINT16_MAX : pq->edns.udp_size,
817 	    pq->edns.bits & EDNS_DO, MINIMIZE_ANSWER) == 0)
818 		goto srvfail;
819 
820 	reply_info_parsedelete(rinfo, &alloc);
821 	alloc_clear(&alloc);
822 	return;
823 
824  srvfail:
825 	reply_info_parsedelete(rinfo, &alloc);
826 	alloc_clear(&alloc);
827 	error_answer(pq, LDNS_RCODE_SERVFAIL);
828 }
829 
830 void
831 chaos_answer(struct pending_query *pq)
832 {
833 	size_t		 len;
834 	const char	*name = "unwind";
835 
836 	len = strlen(name);
837 	if (!sldns_buffer_set_capacity(pq->abuf,
838 	    sldns_buffer_capacity(pq->qbuf) + COMPRESSED_RR_SIZE + 1 + len)) {
839 		error_answer(pq, LDNS_RCODE_SERVFAIL);
840 		return;
841 	}
842 
843 	sldns_buffer_copy(pq->abuf, pq->qbuf);
844 
845 	sldns_buffer_clear(pq->abuf);
846 
847 	sldns_buffer_skip(pq->abuf, sizeof(uint16_t));	/* skip id */
848 	sldns_buffer_write_u16(pq->abuf, 0);		/* clear flags */
849 	LDNS_QR_SET(sldns_buffer_begin(pq->abuf));
850 	LDNS_RA_SET(sldns_buffer_begin(pq->abuf));
851 	if (LDNS_RD_WIRE(sldns_buffer_begin(pq->qbuf)))
852 		LDNS_RD_SET(sldns_buffer_begin(pq->abuf));
853 	if (LDNS_CD_WIRE(sldns_buffer_begin(pq->qbuf)))
854 		LDNS_CD_SET(sldns_buffer_begin(pq->abuf));
855 	LDNS_RCODE_SET(sldns_buffer_begin(pq->abuf), LDNS_RCODE_NOERROR);
856 	sldns_buffer_write_u16(pq->abuf, 1);		/* qdcount */
857 	sldns_buffer_write_u16(pq->abuf, 1);		/* ancount */
858 	sldns_buffer_write_u16(pq->abuf, 0);		/* nscount */
859 	sldns_buffer_write_u16(pq->abuf, 0);		/* arcount */
860 	(void)query_dname_len(pq->abuf);		/* skip qname */
861 	sldns_buffer_skip(pq->abuf, sizeof(uint16_t));	/* skip qtype */
862 	sldns_buffer_skip(pq->abuf, sizeof(uint16_t));	/* skip qclass */
863 
864 	sldns_buffer_write_u16(pq->abuf, 0xc00c);	/* ptr to query */
865 	sldns_buffer_write_u16(pq->abuf, LDNS_RR_TYPE_TXT);
866 	sldns_buffer_write_u16(pq->abuf, LDNS_RR_CLASS_CH);
867 	sldns_buffer_write_u32(pq->abuf, 0);		/* TTL */
868 	sldns_buffer_write_u16(pq->abuf, 1 + len);	/* RDLENGTH */
869 	sldns_buffer_write_u8(pq->abuf, len);		/* length octed */
870 	sldns_buffer_write(pq->abuf, name, len);
871 	sldns_buffer_flip(pq->abuf);
872 }
873 
874 void
875 error_answer(struct pending_query *pq, int rcode)
876 {
877 	sldns_buffer_clear(pq->abuf);
878 	error_encode(pq->abuf, rcode, &pq->qinfo, pq->qmsg->id,
879 	    pq->qmsg->flags, pq->edns.edns_present ? &pq->edns : NULL);
880 }
881 
882 int
883 check_query(sldns_buffer* pkt)
884 {
885 	if(sldns_buffer_limit(pkt) < LDNS_HEADER_SIZE) {
886 		log_warnx("bad query: too short, dropped");
887 		return -1;
888 	}
889 	if(LDNS_QR_WIRE(sldns_buffer_begin(pkt))) {
890 		log_warnx("bad query: QR set, dropped");
891 		return -1;
892 	}
893 	if(LDNS_TC_WIRE(sldns_buffer_begin(pkt))) {
894 		LDNS_TC_CLR(sldns_buffer_begin(pkt));
895 		log_warnx("bad query: TC set");
896 		return (LDNS_RCODE_FORMERR);
897 	}
898 	if(!(LDNS_RD_WIRE(sldns_buffer_begin(pkt)))) {
899 		log_warnx("bad query: RD not set");
900 		return (LDNS_RCODE_REFUSED);
901 	}
902 	if(LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_QUERY) {
903 		log_warnx("bad query: unknown opcode %d",
904 		    LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)));
905 		return (LDNS_RCODE_NOTIMPL);
906 	}
907 
908 	if (LDNS_QDCOUNT(sldns_buffer_begin(pkt)) != 1 &&
909 	    LDNS_ANCOUNT(sldns_buffer_begin(pkt))!= 0 &&
910 	    LDNS_NSCOUNT(sldns_buffer_begin(pkt))!= 0 &&
911 	    LDNS_ARCOUNT(sldns_buffer_begin(pkt)) > 1) {
912 		log_warnx("bad query: qdcount: %d, ancount: %d "
913 		    "nscount: %d, arcount: %d",
914 		    LDNS_QDCOUNT(sldns_buffer_begin(pkt)),
915 		    LDNS_ANCOUNT(sldns_buffer_begin(pkt)),
916 		    LDNS_NSCOUNT(sldns_buffer_begin(pkt)),
917 		    LDNS_ARCOUNT(sldns_buffer_begin(pkt)));
918 		return (LDNS_RCODE_FORMERR);
919 	}
920 	return 0;
921 }
922 
923 void
924 send_answer(struct pending_query *pq)
925 {
926 	char	*str;
927 
928 	if (log_getverbose() & OPT_VERBOSE2 && (str =
929 	    sldns_wire2str_pkt(sldns_buffer_begin(pq->abuf),
930 	    sldns_buffer_limit(pq->abuf))) != NULL) {
931 		log_debug("from: %s\n%s", ip_port((struct sockaddr *)
932 		    &pq->from), str);
933 		free(str);
934 	}
935 
936 	if (!pq->tcp) {
937 		if(sendto(pq->fd, sldns_buffer_current(pq->abuf),
938 		    sldns_buffer_remaining(pq->abuf), 0,
939 		    (struct sockaddr *)&pq->from, pq->from.ss_len) == -1)
940 			log_warn("sendto");
941 		free_pending_query(pq);
942 	} else {
943 		struct sldns_buffer	*tmp;
944 
945 		tmp = sldns_buffer_new(sldns_buffer_limit(pq->abuf) + 2);
946 
947 		if (!tmp) {
948 			free_pending_query(pq);
949 			return;
950 		}
951 
952 		sldns_buffer_write_u16(tmp, sldns_buffer_limit(pq->abuf));
953 		sldns_buffer_write(tmp, sldns_buffer_current(pq->abuf),
954 		    sldns_buffer_remaining(pq->abuf));
955 		sldns_buffer_flip(tmp);
956 		sldns_buffer_free(pq->abuf);
957 		pq->abuf = tmp;
958 		event_add(&pq->resp_ev, NULL);
959 	}
960 }
961 
962 char*
963 ip_port(struct sockaddr *sa)
964 {
965 	static char	 hbuf[NI_MAXHOST], buf[NI_MAXHOST];
966 
967 	if (getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), NULL, 0,
968 	    NI_NUMERICHOST) != 0) {
969 		snprintf(buf, sizeof(buf), "%s", "(unknown)");
970 		return buf;
971 	}
972 
973 	if (sa->sa_family == AF_INET6)
974 		snprintf(buf, sizeof(buf), "[%s]:%d", hbuf, ntohs(
975 		    ((struct sockaddr_in6 *)sa)->sin6_port));
976 	if (sa->sa_family == AF_INET)
977 		snprintf(buf, sizeof(buf), "[%s]:%d", hbuf, ntohs(
978 		    ((struct sockaddr_in *)sa)->sin_port));
979 
980 	return buf;
981 }
982 
983 struct pending_query*
984 find_pending_query(uint64_t id)
985 {
986 	struct pending_query	*pq;
987 
988 	TAILQ_FOREACH(pq, &pending_queries, entry)
989 		if (pq->imsg_id == id)
990 			return pq;
991 	return NULL;
992 }
993 
994 void
995 route_receive(int fd, short events, void *arg)
996 {
997 	static uint8_t		*buf;
998 
999 	struct rt_msghdr	*rtm;
1000 	struct sockaddr		*sa, *rti_info[RTAX_MAX];
1001 	ssize_t			 n;
1002 
1003 	if (buf == NULL) {
1004 		buf = malloc(ROUTE_SOCKET_BUF_SIZE);
1005 		if (buf == NULL)
1006 			fatal("malloc");
1007 	}
1008 	rtm = (struct rt_msghdr *)buf;
1009 	if ((n = read(fd, buf, ROUTE_SOCKET_BUF_SIZE)) == -1) {
1010 		if (errno == EAGAIN || errno == EINTR)
1011 			return;
1012 		log_warn("dispatch_rtmsg: read error");
1013 		return;
1014 	}
1015 
1016 	if (n == 0)
1017 		fatal("routing socket closed");
1018 
1019 	if (n < (ssize_t)sizeof(rtm->rtm_msglen) || n < rtm->rtm_msglen) {
1020 		log_warnx("partial rtm of %zd in buffer", n);
1021 		return;
1022 	}
1023 
1024 	if (rtm->rtm_version != RTM_VERSION)
1025 		return;
1026 
1027 	sa = (struct sockaddr *)(buf + rtm->rtm_hdrlen);
1028 	get_rtaddrs(rtm->rtm_addrs, sa, rti_info);
1029 
1030 	handle_route_message(rtm, rti_info);
1031 }
1032 
1033 #define ROUNDUP(a) \
1034 	((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
1035 
1036 void
1037 get_rtaddrs(int addrs, struct sockaddr *sa, struct sockaddr **rti_info)
1038 {
1039 	int	i;
1040 
1041 	for (i = 0; i < RTAX_MAX; i++) {
1042 		if (addrs & (1 << i)) {
1043 			rti_info[i] = sa;
1044 			sa = (struct sockaddr *)((char *)(sa) +
1045 			    ROUNDUP(sa->sa_len));
1046 		} else
1047 			rti_info[i] = NULL;
1048 	}
1049 }
1050 
1051 void
1052 handle_route_message(struct rt_msghdr *rtm, struct sockaddr **rti_info)
1053 {
1054 	struct imsg_rdns_proposal	 rdns_proposal;
1055 	struct sockaddr_rtdns		*rtdns;
1056 	struct if_announcemsghdr	*ifan;
1057 
1058 	switch (rtm->rtm_type) {
1059 	case RTM_IFANNOUNCE:
1060 		ifan = (struct if_announcemsghdr *)rtm;
1061 		if (ifan->ifan_what == IFAN_ARRIVAL)
1062 			break;
1063 		rdns_proposal.if_index = ifan->ifan_index;
1064 		rdns_proposal.src = 0;
1065 		rdns_proposal.rtdns.sr_family = AF_INET;
1066 		rdns_proposal.rtdns.sr_len = offsetof(struct sockaddr_rtdns,
1067 		    sr_dns);
1068 		frontend_imsg_compose_resolver(IMSG_REPLACE_DNS, 0,
1069 		    &rdns_proposal, sizeof(rdns_proposal));
1070 		break;
1071 	case RTM_IFINFO:
1072 		frontend_imsg_compose_resolver(IMSG_NETWORK_CHANGED, 0, NULL,
1073 		    0);
1074 		break;
1075 	case RTM_PROPOSAL:
1076 		if (!(rtm->rtm_addrs & RTA_DNS))
1077 			break;
1078 
1079 		rtdns = (struct sockaddr_rtdns*)rti_info[RTAX_DNS];
1080 		switch (rtdns->sr_family) {
1081 		case AF_INET:
1082 			if ((rtdns->sr_len - 2) % sizeof(struct in_addr) != 0) {
1083 				log_warnx("ignoring invalid RTM_PROPOSAL");
1084 				return;
1085 			}
1086 			break;
1087 		case AF_INET6:
1088 			if ((rtdns->sr_len - 2) % sizeof(struct in6_addr) != 0) {
1089 				log_warnx("ignoring invalid RTM_PROPOSAL");
1090 				return;
1091 			}
1092 			break;
1093 		default:
1094 			log_warnx("ignoring invalid RTM_PROPOSAL");
1095 			return;
1096 		}
1097 		rdns_proposal.if_index = rtm->rtm_index;
1098 		rdns_proposal.src = rtm->rtm_priority;
1099 		memcpy(&rdns_proposal.rtdns, rtdns, sizeof(rdns_proposal.rtdns));
1100 		frontend_imsg_compose_resolver(IMSG_REPLACE_DNS, 0,
1101 		    &rdns_proposal, sizeof(rdns_proposal));
1102 		break;
1103 	default:
1104 		break;
1105 	}
1106 }
1107 
1108 void
1109 add_new_ta(struct trust_anchor_head *tah, char *val)
1110 {
1111 	struct trust_anchor	*ta, *i;
1112 	int			 cmp;
1113 
1114 	if ((ta = malloc(sizeof(*ta))) == NULL)
1115 		fatal("%s", __func__);
1116 	if ((ta->ta = strdup(val)) == NULL)
1117 		fatal("%s", __func__);
1118 
1119 	/* keep the list sorted to prevent churn if the order changes in DNS */
1120 	TAILQ_FOREACH(i, tah, entry) {
1121 		cmp = strcmp(i->ta, ta->ta);
1122 		if ( cmp == 0) {
1123 			/* duplicate */
1124 			free(ta->ta);
1125 			free(ta);
1126 			return;
1127 		} else if (cmp > 0) {
1128 			TAILQ_INSERT_BEFORE(i, ta, entry);
1129 			return;
1130 		}
1131 	}
1132 	TAILQ_INSERT_TAIL(tah, ta, entry);
1133 }
1134 
1135 void
1136 free_tas(struct trust_anchor_head *tah)
1137 {
1138 	struct trust_anchor	*ta;
1139 
1140 	while ((ta = TAILQ_FIRST(tah))) {
1141 		TAILQ_REMOVE(tah, ta, entry);
1142 		free(ta->ta);
1143 		free(ta);
1144 	}
1145 }
1146 
1147 int
1148 merge_tas(struct trust_anchor_head *newh, struct trust_anchor_head *oldh)
1149 {
1150 	struct trust_anchor	*i, *j;
1151 	int			 chg = 0;
1152 
1153 	j = TAILQ_FIRST(oldh);
1154 
1155 	TAILQ_FOREACH(i, newh, entry) {
1156 		if (j == NULL || strcmp(i->ta, j->ta) != 0) {
1157 			chg = 1;
1158 			break;
1159 		}
1160 		j = TAILQ_NEXT(j, entry);
1161 	}
1162 	if (j != NULL)
1163 		chg = 1;
1164 
1165 	if (chg) {
1166 		free_tas(oldh);
1167 		TAILQ_CONCAT(oldh, newh, entry);
1168 	} else {
1169 		free_tas(newh);
1170 	}
1171 	return (chg);
1172 }
1173 
1174 void
1175 parse_trust_anchor(struct trust_anchor_head *tah, int fd)
1176 {
1177 	size_t	 len, dname_len;
1178 	ssize_t	 n, sz;
1179 	uint8_t	 rr[LDNS_RR_BUF_SIZE];
1180 	char	*str, *p, buf[512], *line;
1181 
1182 	sz = 0;
1183 	str = NULL;
1184 
1185 	while ((n = read(fd, buf, sizeof(buf))) > 0) {
1186 		p = recallocarray(str, sz, sz + n, 1);
1187 		if (p == NULL) {
1188 			log_warn("%s", __func__);
1189 			goto out;
1190 		}
1191 		str = p;
1192 		memcpy(str + sz, buf, n);
1193 		sz += n;
1194 	}
1195 
1196 	if (n == -1) {
1197 		log_warn("%s", __func__);
1198 		goto out;
1199 	}
1200 
1201 	/* make it a string */
1202 	p = recallocarray(str, sz, sz + 1, 1);
1203 	if (p == NULL) {
1204 		log_warn("%s", __func__);
1205 		goto out;
1206 	}
1207 	str = p;
1208 	sz++;
1209 
1210 	len = sizeof(rr);
1211 
1212 	while ((line = strsep(&p, "\n")) != NULL) {
1213 		if (sldns_str2wire_rr_buf(line, rr, &len, &dname_len,
1214 		    ROOT_DNSKEY_TTL, NULL, 0, NULL, 0) != 0)
1215 			continue;
1216 		if (sldns_wirerr_get_type(rr, len, dname_len) ==
1217 		    LDNS_RR_TYPE_DNSKEY)
1218 			add_new_ta(tah, line);
1219 	}
1220 
1221 out:
1222 	free(str);
1223 	return;
1224 }
1225 
1226 void
1227 send_trust_anchors(struct trust_anchor_head *tah)
1228 {
1229 	struct trust_anchor	*ta;
1230 
1231 	TAILQ_FOREACH(ta, tah, entry)
1232 		frontend_imsg_compose_resolver(IMSG_NEW_TA, 0, ta->ta,
1233 		    strlen(ta->ta) + 1);
1234 	frontend_imsg_compose_resolver(IMSG_NEW_TAS_DONE, 0, NULL, 0);
1235 }
1236 
1237 void
1238 write_trust_anchors(struct trust_anchor_head *tah, int fd)
1239 {
1240 	struct trust_anchor	*ta;
1241 	size_t			 len = 0;
1242 	ssize_t			 n;
1243 	char			*str;
1244 
1245 	if (lseek(fd, 0, SEEK_SET) == -1) {
1246 		log_warn("%s", __func__);
1247 		goto out;
1248 	}
1249 
1250 	TAILQ_FOREACH(ta, tah, entry) {
1251 		if ((n = asprintf(&str, "%s\n", ta->ta)) == -1) {
1252 			log_warn("%s", __func__);
1253 			len = 0;
1254 			goto out;
1255 		}
1256 		len += n;
1257 		if (write(fd, str, n) != n) {
1258 			log_warn("%s", __func__);
1259 			free(str);
1260 			len = 0;
1261 			goto out;
1262 		}
1263 		free(str);
1264 	}
1265 out:
1266 	ftruncate(fd, len);
1267 	fsync(fd);
1268 }
1269 
1270 void
1271 parse_blocklist(int fd)
1272 {
1273 	FILE		 *f;
1274 	struct bl_node	*bl_node;
1275 	char		 *line = NULL;
1276 	size_t		  linesize = 0;
1277 	ssize_t		  linelen;
1278 
1279 	if((f = fdopen(fd, "r")) == NULL) {
1280 		log_warn("cannot read block list");
1281 		close(fd);
1282 		return;
1283 	}
1284 
1285 	free_bl();
1286 
1287 	while ((linelen = getline(&line, &linesize, f)) != -1) {
1288 		if (line[linelen - 1] == '\n') {
1289 			if (linelen >= 2 && line[linelen - 2] != '.')
1290 				line[linelen - 1] = '.';
1291 			else
1292 				line[linelen - 1] = '\0';
1293 		}
1294 
1295 		bl_node = malloc(sizeof *bl_node);
1296 		if (bl_node == NULL)
1297 			fatal("%s: malloc", __func__);
1298 		if ((bl_node->domain = strdup(line)) == NULL)
1299 			fatal("%s: strdup", __func__);
1300 		if (RB_INSERT(bl_tree, &bl_head, bl_node) != NULL) {
1301 			log_warnx("duplicate blocked domain \"%s\"", line);
1302 			free(bl_node->domain);
1303 			free(bl_node);
1304 		}
1305 	}
1306 	free(line);
1307 	if (ferror(f))
1308 		log_warn("getline");
1309 	fclose(f);
1310 }
1311 
1312 int
1313 bl_cmp(struct bl_node *e1, struct bl_node *e2) {
1314 	return (strcasecmp(e1->domain, e2->domain));
1315 }
1316 
1317 void
1318 free_bl(void)
1319 {
1320 	struct bl_node	*n, *nxt;
1321 
1322 	RB_FOREACH_SAFE(n, bl_tree, &bl_head, nxt) {
1323 		RB_REMOVE(bl_tree, &bl_head, n);
1324 		free(n->domain);
1325 		free(n);
1326 	}
1327 }
1328 
1329 int
1330 pending_query_cnt(void)
1331 {
1332 	struct pending_query	*e;
1333 	int			 cnt = 0;
1334 
1335 	TAILQ_FOREACH(e, &pending_queries, entry)
1336 		cnt++;
1337 	return cnt;
1338 }
1339 
1340 void
1341 accept_paused(int fd, short events, void *arg)
1342 {
1343 	struct tcp_accept_ev	*tcpev = arg;
1344 	event_add(&tcpev->ev, NULL);
1345 }
1346 
1347 int
1348 accept_reserve(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
1349 {
1350 	if (getdtablecount() + FD_RESERVE >= getdtablesize()) {
1351 		log_debug("%s: inflight fds exceeded", __func__);
1352 		errno = EMFILE;
1353 		return -1;
1354 	}
1355 	return accept4(sockfd, addr, addrlen, SOCK_NONBLOCK | SOCK_CLOEXEC);
1356 }
1357 
1358 void
1359 tcp_accept(int fd, short events, void *arg)
1360 {
1361 	static struct timeval	 timeout = {TCP_TIMEOUT, 0};
1362 	static struct timeval	 backoff = {1, 0};
1363 	struct pending_query	*pq;
1364 	struct tcp_accept_ev	*tcpev;
1365 	struct sockaddr_storage	 ss;
1366 	socklen_t		 len;
1367 	int			 s;
1368 
1369 	tcpev = arg;
1370 	len = sizeof(ss);
1371 
1372 	if ((s = accept_reserve(fd, (struct sockaddr *)&ss, &len)) == -1) {
1373 		switch (errno) {
1374 		case EINTR:
1375 		case EWOULDBLOCK:
1376 		case ECONNABORTED:
1377 			return;
1378 		case EMFILE:
1379 		case ENFILE:
1380 			event_del(&tcpev->ev);
1381 			evtimer_add(&tcpev->pause, &backoff);
1382 			return;
1383 		default:
1384 			fatal("accept");
1385 		}
1386 	}
1387 
1388 	if ((pq = calloc(1, sizeof(*pq))) == NULL) {
1389 		log_warn(NULL);
1390 		close(s);
1391 		return;
1392 	}
1393 
1394 	do {
1395 		arc4random_buf(&pq->imsg_id, sizeof(pq->imsg_id));
1396 	} while(find_pending_query(pq->imsg_id) != NULL);
1397 
1398 	TAILQ_INSERT_TAIL(&pending_queries, pq, entry);
1399 
1400 	pq->from = ss;
1401 	pq->fd = s;
1402 	pq->tcp = 1;
1403 	pq->qbuf = sldns_buffer_new(DEFAULT_TCP_SIZE);
1404 	pq->region = regional_create();
1405 	pq->qmsg = regional_alloc(pq->region, sizeof(*pq->qmsg));
1406 
1407 	if (!pq->qbuf || !pq->region || !pq->qmsg) {
1408 		free_pending_query(pq);
1409 		return;
1410 	}
1411 
1412 	memset(pq->qmsg, 0, sizeof(*pq->qmsg));
1413 
1414 	event_set(&pq->ev, s, EV_READ | EV_PERSIST, tcp_request, pq);
1415 	event_add(&pq->ev, NULL);
1416 	event_set(&pq->resp_ev, s, EV_WRITE | EV_PERSIST, tcp_response, pq);
1417 
1418 	evtimer_set(&pq->tmo_ev, tcp_timeout, pq);
1419 	evtimer_add(&pq->tmo_ev, &timeout);
1420 }
1421 
1422 void
1423 tcp_request(int fd, short events, void *arg)
1424 {
1425 	struct pending_query	*pq;
1426 	ssize_t			 n;
1427 
1428 	pq = arg;
1429 
1430 	n = read(fd, sldns_buffer_current(pq->qbuf),
1431 	    sldns_buffer_remaining(pq->qbuf));
1432 
1433 	switch (n) {
1434 	case -1:
1435 		switch (errno) {
1436 		case EINTR:
1437 		case EAGAIN:
1438 			return;
1439 		default:
1440 			goto fail;
1441 		}
1442 		break;
1443 	case 0:
1444 		log_debug("closed connection");
1445 		goto fail;
1446 	default:
1447 		break;
1448 	}
1449 
1450 	sldns_buffer_skip(pq->qbuf, n);
1451 
1452 	if (sldns_buffer_position(pq->qbuf) >= 2 && !pq->abuf) {
1453 		struct sldns_buffer	*tmp;
1454 		uint16_t		 len;
1455 
1456 		sldns_buffer_flip(pq->qbuf);
1457 		len = sldns_buffer_read_u16(pq->qbuf);
1458 		tmp = sldns_buffer_new(len);
1459 		pq->abuf = sldns_buffer_new(len);
1460 
1461 		if (!tmp || !pq->abuf)
1462 			goto fail;
1463 
1464 		sldns_buffer_write(tmp, sldns_buffer_current(pq->qbuf),
1465 		    sldns_buffer_remaining(pq->qbuf));
1466 		sldns_buffer_free(pq->qbuf);
1467 		pq->qbuf = tmp;
1468 	}
1469 	if (sldns_buffer_remaining(pq->qbuf) == 0) {
1470 		sldns_buffer_flip(pq->qbuf);
1471 		shutdown(fd, SHUT_RD);
1472 		event_del(&pq->ev);
1473 		handle_query(pq);
1474 	}
1475 	return;
1476 fail:
1477 	free_pending_query(pq);
1478 }
1479 
1480 void
1481 tcp_response(int fd, short events, void *arg)
1482 {
1483 	struct pending_query	*pq;
1484 	ssize_t			 n;
1485 
1486 	pq = arg;
1487 
1488 	n = write(fd, sldns_buffer_current(pq->abuf),
1489 	    sldns_buffer_remaining(pq->abuf));
1490 
1491 	if (n == -1) {
1492 		if (errno == EAGAIN || errno == EINTR)
1493 			return;
1494 		free_pending_query(pq);
1495 	}
1496 	sldns_buffer_skip(pq->abuf, n);
1497 	if (sldns_buffer_remaining(pq->abuf) == 0)
1498 		free_pending_query(pq);
1499 }
1500 
1501 void
1502 tcp_timeout(int fd, short events, void *arg)
1503 {
1504 	free_pending_query(arg);
1505 }
1506