xref: /freebsd/contrib/unbound/util/netevent.c (revision 7a789145f88a6aceacc59029a0cafe7de7aeefea)
1 /*
2  * util/netevent.c - event notification
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains event notification functions.
40  */
41 #include "config.h"
42 #include "util/netevent.h"
43 #include "util/ub_event.h"
44 #include "util/log.h"
45 #include "util/net_help.h"
46 #include "util/tcp_conn_limit.h"
47 #include "util/fptr_wlist.h"
48 #include "util/proxy_protocol.h"
49 #include "util/timeval_func.h"
50 #include "sldns/pkthdr.h"
51 #include "sldns/sbuffer.h"
52 #include "sldns/str2wire.h"
53 #include "dnstap/dnstap.h"
54 #include "dnscrypt/dnscrypt.h"
55 #include "services/listen_dnsport.h"
56 #include "util/random.h"
57 #ifdef HAVE_SYS_TYPES_H
58 #include <sys/types.h>
59 #endif
60 #ifdef HAVE_SYS_SOCKET_H
61 #include <sys/socket.h>
62 #endif
63 #ifdef HAVE_NETDB_H
64 #include <netdb.h>
65 #endif
66 #ifdef HAVE_POLL_H
67 #include <poll.h>
68 #endif
69 
70 #ifdef HAVE_OPENSSL_SSL_H
71 #include <openssl/ssl.h>
72 #endif
73 #ifdef HAVE_OPENSSL_ERR_H
74 #include <openssl/err.h>
75 #endif
76 
77 #ifdef HAVE_NGTCP2
78 #include <ngtcp2/ngtcp2.h>
79 #include <ngtcp2/ngtcp2_crypto.h>
80 #endif
81 
82 #ifdef HAVE_LINUX_NET_TSTAMP_H
83 #include <linux/net_tstamp.h>
84 #endif
85 
86 /* -------- Start of local definitions -------- */
87 /** if CMSG_ALIGN is not defined on this platform, a workaround */
88 #ifndef CMSG_ALIGN
89 #  ifdef __CMSG_ALIGN
90 #    define CMSG_ALIGN(n) __CMSG_ALIGN(n)
91 #  elif defined(CMSG_DATA_ALIGN)
92 #    define CMSG_ALIGN _CMSG_DATA_ALIGN
93 #  else
94 #    define CMSG_ALIGN(len) (((len)+sizeof(long)-1) & ~(sizeof(long)-1))
95 #  endif
96 #endif
97 
98 /** if CMSG_LEN is not defined on this platform, a workaround */
99 #ifndef CMSG_LEN
100 #  define CMSG_LEN(len) (CMSG_ALIGN(sizeof(struct cmsghdr))+(len))
101 #endif
102 
103 /** if CMSG_SPACE is not defined on this platform, a workaround */
104 #ifndef CMSG_SPACE
105 #  ifdef _CMSG_HDR_ALIGN
106 #    define CMSG_SPACE(l) (CMSG_ALIGN(l)+_CMSG_HDR_ALIGN(sizeof(struct cmsghdr)))
107 #  else
108 #    define CMSG_SPACE(l) (CMSG_ALIGN(l)+CMSG_ALIGN(sizeof(struct cmsghdr)))
109 #  endif
110 #endif
111 
112 /** The TCP writing query timeout in milliseconds */
113 #define TCP_QUERY_TIMEOUT 120000
114 /** The minimum actual TCP timeout to use, regardless of what we advertise,
115  * in msec */
116 #define TCP_QUERY_TIMEOUT_MINIMUM 200
117 
118 #ifndef NONBLOCKING_IS_BROKEN
119 /** number of UDP reads to perform per read indication from select */
120 #define NUM_UDP_PER_SELECT 100
121 #else
122 #define NUM_UDP_PER_SELECT 1
123 #endif
124 
125 /** timeout in millisec to wait for write to unblock, packets dropped after.*/
126 #define SEND_BLOCKED_WAIT_TIMEOUT 200
127 /** max number of times to wait for write to unblock, packets dropped after.*/
128 #define SEND_BLOCKED_MAX_RETRY 5
129 
130 /** Let's make timestamping code cleaner and redefine SO_TIMESTAMP* */
131 #ifndef SO_TIMESTAMP
132 #define SO_TIMESTAMP 29
133 #endif
134 #ifndef SO_TIMESTAMPNS
135 #define SO_TIMESTAMPNS 35
136 #endif
137 #ifndef SO_TIMESTAMPING
138 #define SO_TIMESTAMPING 37
139 #endif
140 /**
141  * The internal event structure for keeping ub_event info for the event.
142  * Possibly other structures (list, tree) this is part of.
143  */
144 struct internal_event {
145 	/** the comm base */
146 	struct comm_base* base;
147 	/** ub_event event type */
148 	struct ub_event* ev;
149 };
150 
151 /**
152  * Internal base structure, so that every thread has its own events.
153  */
154 struct internal_base {
155 	/** ub_event event_base type. */
156 	struct ub_event_base* base;
157 	/** seconds time pointer points here */
158 	time_t secs;
159 	/** timeval with current time */
160 	struct timeval now;
161 	/** the event used for slow_accept timeouts */
162 	struct ub_event* slow_accept;
163 	/** true if slow_accept is enabled */
164 	int slow_accept_enabled;
165 	/** last log time for slow logging of file descriptor errors */
166 	time_t last_slow_log;
167 	/** last log time for slow logging of write wait failures */
168 	time_t last_writewait_log;
169 };
170 
171 /**
172  * Internal timer structure, to store timer event in.
173  */
174 struct internal_timer {
175 	/** the super struct from which derived */
176 	struct comm_timer super;
177 	/** the comm base */
178 	struct comm_base* base;
179 	/** ub_event event type */
180 	struct ub_event* ev;
181 	/** is timer enabled */
182 	uint8_t enabled;
183 };
184 
185 /**
186  * Internal signal structure, to store signal event in.
187  */
188 struct internal_signal {
189 	/** ub_event event type */
190 	struct ub_event* ev;
191 	/** next in signal list */
192 	struct internal_signal* next;
193 };
194 
195 /** create a tcp handler with a parent */
196 static struct comm_point* comm_point_create_tcp_handler(
197 	struct comm_base *base, struct comm_point* parent, size_t bufsize,
198 	struct sldns_buffer* spoolbuf, comm_point_callback_type* callback,
199 	void* callback_arg, struct unbound_socket* socket);
200 
201 /* -------- End of local definitions -------- */
202 
203 struct comm_base*
comm_base_create(int sigs)204 comm_base_create(int sigs)
205 {
206 	struct comm_base* b = (struct comm_base*)calloc(1,
207 		sizeof(struct comm_base));
208 	const char *evnm="event", *evsys="", *evmethod="";
209 
210 	if(!b)
211 		return NULL;
212 	b->eb = (struct internal_base*)calloc(1, sizeof(struct internal_base));
213 	if(!b->eb) {
214 		free(b);
215 		return NULL;
216 	}
217 	b->eb->base = ub_default_event_base(sigs, &b->eb->secs, &b->eb->now);
218 	if(!b->eb->base) {
219 		free(b->eb);
220 		free(b);
221 		return NULL;
222 	}
223 	ub_comm_base_now(b);
224 	ub_get_event_sys(b->eb->base, &evnm, &evsys, &evmethod);
225 	verbose(VERB_ALGO, "%s %s uses %s method.", evnm, evsys, evmethod);
226 	return b;
227 }
228 
229 struct comm_base*
comm_base_create_event(struct ub_event_base * base)230 comm_base_create_event(struct ub_event_base* base)
231 {
232 	struct comm_base* b = (struct comm_base*)calloc(1,
233 		sizeof(struct comm_base));
234 	if(!b)
235 		return NULL;
236 	b->eb = (struct internal_base*)calloc(1, sizeof(struct internal_base));
237 	if(!b->eb) {
238 		free(b);
239 		return NULL;
240 	}
241 	b->eb->base = base;
242 	ub_comm_base_now(b);
243 	return b;
244 }
245 
246 void
comm_base_delete(struct comm_base * b)247 comm_base_delete(struct comm_base* b)
248 {
249 	if(!b)
250 		return;
251 	if(b->eb->slow_accept_enabled) {
252 		if(ub_event_del(b->eb->slow_accept) != 0) {
253 			log_err("could not event_del slow_accept");
254 		}
255 		ub_event_free(b->eb->slow_accept);
256 	}
257 	ub_event_base_free(b->eb->base);
258 	b->eb->base = NULL;
259 	free(b->eb);
260 	free(b);
261 }
262 
263 void
comm_base_delete_no_base(struct comm_base * b)264 comm_base_delete_no_base(struct comm_base* b)
265 {
266 	if(!b)
267 		return;
268 	if(b->eb->slow_accept_enabled) {
269 		if(ub_event_del(b->eb->slow_accept) != 0) {
270 			log_err("could not event_del slow_accept");
271 		}
272 		ub_event_free(b->eb->slow_accept);
273 	}
274 	b->eb->base = NULL;
275 	free(b->eb);
276 	free(b);
277 }
278 
279 void
comm_base_timept(struct comm_base * b,time_t ** tt,struct timeval ** tv)280 comm_base_timept(struct comm_base* b, time_t** tt, struct timeval** tv)
281 {
282 	*tt = &b->eb->secs;
283 	*tv = &b->eb->now;
284 }
285 
286 void
comm_base_dispatch(struct comm_base * b)287 comm_base_dispatch(struct comm_base* b)
288 {
289 	int retval;
290 	retval = ub_event_base_dispatch(b->eb->base);
291 	if(retval < 0) {
292 		fatal_exit("event_dispatch returned error %d, "
293 			"errno is %s", retval, strerror(errno));
294 	}
295 }
296 
comm_base_exit(struct comm_base * b)297 void comm_base_exit(struct comm_base* b)
298 {
299 	if(ub_event_base_loopexit(b->eb->base) != 0) {
300 		log_err("Could not loopexit");
301 	}
302 }
303 
comm_base_set_slow_accept_handlers(struct comm_base * b,void (* stop_acc)(void *),void (* start_acc)(void *),void * arg)304 void comm_base_set_slow_accept_handlers(struct comm_base* b,
305 	void (*stop_acc)(void*), void (*start_acc)(void*), void* arg)
306 {
307 	b->stop_accept = stop_acc;
308 	b->start_accept = start_acc;
309 	b->cb_arg = arg;
310 }
311 
comm_base_internal(struct comm_base * b)312 struct ub_event_base* comm_base_internal(struct comm_base* b)
313 {
314 	return b->eb->base;
315 }
316 
comm_point_internal(struct comm_point * c)317 struct ub_event* comm_point_internal(struct comm_point* c)
318 {
319 	return c->ev->ev;
320 }
321 
322 /** see if errno for udp has to be logged or not uses globals */
323 static int
udp_send_errno_needs_log(struct sockaddr * addr,socklen_t addrlen)324 udp_send_errno_needs_log(struct sockaddr* addr, socklen_t addrlen)
325 {
326 	/* do not log transient errors (unless high verbosity) */
327 #if defined(ENETUNREACH) || defined(EHOSTDOWN) || defined(EHOSTUNREACH) || defined(ENETDOWN)
328 	switch(errno) {
329 #  ifdef ENETUNREACH
330 		case ENETUNREACH:
331 #  endif
332 #  ifdef EHOSTDOWN
333 		case EHOSTDOWN:
334 #  endif
335 #  ifdef EHOSTUNREACH
336 		case EHOSTUNREACH:
337 #  endif
338 #  ifdef ENETDOWN
339 		case ENETDOWN:
340 #  endif
341 		case EPERM:
342 		case EACCES:
343 			if(verbosity < VERB_ALGO)
344 				return 0;
345 			break;
346 		default:
347 			break;
348 	}
349 #endif
350 	/* permission denied is gotten for every send if the
351 	 * network is disconnected (on some OS), squelch it */
352 	if( ((errno == EPERM)
353 #  ifdef EADDRNOTAVAIL
354 		/* 'Cannot assign requested address' also when disconnected */
355 		|| (errno == EADDRNOTAVAIL)
356 #  endif
357 		) && verbosity < VERB_ALGO)
358 		return 0;
359 #  ifdef EADDRINUSE
360 	/* If SO_REUSEADDR is set, we could try to connect to the same server
361 	 * from the same source port twice. */
362 	if(errno == EADDRINUSE && verbosity < VERB_DETAIL)
363 		return 0;
364 #  endif
365 	/* squelch errors where people deploy AAAA ::ffff:bla for
366 	 * authority servers, which we try for intranets. */
367 	if(errno == EINVAL && addr_is_ip4mapped(
368 		(struct sockaddr_storage*)addr, addrlen) &&
369 		verbosity < VERB_DETAIL)
370 		return 0;
371 	/* SO_BROADCAST sockopt can give access to 255.255.255.255,
372 	 * but a dns cache does not need it. */
373 	if(errno == EACCES && addr_is_broadcast(
374 		(struct sockaddr_storage*)addr, addrlen) &&
375 		verbosity < VERB_DETAIL)
376 		return 0;
377 #  ifdef ENOTCONN
378 	/* For 0.0.0.0, ::0 targets it can return that socket is not connected.
379 	 * This can be ignored, and the address skipped. It remains
380 	 * possible to send there for completeness in configuration. */
381 	if(errno == ENOTCONN && addr_is_any(
382 		(struct sockaddr_storage*)addr, addrlen) &&
383 		verbosity < VERB_DETAIL)
384 		return 0;
385 #  endif
386 	return 1;
387 }
388 
tcp_connect_errno_needs_log(struct sockaddr * addr,socklen_t addrlen)389 int tcp_connect_errno_needs_log(struct sockaddr* addr, socklen_t addrlen)
390 {
391 	return udp_send_errno_needs_log(addr, addrlen);
392 }
393 
394 /* send a UDP reply */
395 int
comm_point_send_udp_msg(struct comm_point * c,sldns_buffer * packet,struct sockaddr * addr,socklen_t addrlen,int is_connected)396 comm_point_send_udp_msg(struct comm_point *c, sldns_buffer* packet,
397 	struct sockaddr* addr, socklen_t addrlen, int is_connected)
398 {
399 	ssize_t sent;
400 	log_assert(c->fd != -1);
401 #ifdef UNBOUND_DEBUG
402 	if(sldns_buffer_remaining(packet) == 0)
403 		log_err("error: send empty UDP packet");
404 #endif
405 	log_assert(addr && addrlen > 0);
406 	if(!is_connected) {
407 		sent = sendto(c->fd, (void*)sldns_buffer_begin(packet),
408 			sldns_buffer_remaining(packet), 0,
409 			addr, addrlen);
410 	} else {
411 		sent = send(c->fd, (void*)sldns_buffer_begin(packet),
412 			sldns_buffer_remaining(packet), 0);
413 	}
414 	if(sent == -1) {
415 		/* try again and block, waiting for IO to complete,
416 		 * we want to send the answer, and we will wait for
417 		 * the ethernet interface buffer to have space. */
418 #ifndef USE_WINSOCK
419 		if(errno == EAGAIN || errno == EINTR ||
420 #  ifdef EWOULDBLOCK
421 			errno == EWOULDBLOCK ||
422 #  endif
423 			errno == ENOBUFS) {
424 #else
425 		if(WSAGetLastError() == WSAEINPROGRESS ||
426 			WSAGetLastError() == WSAEINTR ||
427 			WSAGetLastError() == WSAENOBUFS ||
428 			WSAGetLastError() == WSAEWOULDBLOCK) {
429 #endif
430 			int retries = 0;
431 			/* if we set the fd blocking, other threads suddenly
432 			 * have a blocking fd that they operate on */
433 			while(sent == -1 && retries < SEND_BLOCKED_MAX_RETRY && (
434 #ifndef USE_WINSOCK
435 				errno == EAGAIN || errno == EINTR ||
436 #  ifdef EWOULDBLOCK
437 				errno == EWOULDBLOCK ||
438 #  endif
439 				errno == ENOBUFS
440 #else
441 				WSAGetLastError() == WSAEINPROGRESS ||
442 				WSAGetLastError() == WSAEINTR ||
443 				WSAGetLastError() == WSAENOBUFS ||
444 				WSAGetLastError() == WSAEWOULDBLOCK
445 #endif
446 			)) {
447 #if defined(HAVE_POLL) || defined(USE_WINSOCK)
448 				int send_nobufs = (
449 #ifndef USE_WINSOCK
450 					errno == ENOBUFS
451 #else
452 					WSAGetLastError() == WSAENOBUFS
453 #endif
454 				);
455 				struct pollfd p;
456 				int pret;
457 				memset(&p, 0, sizeof(p));
458 				p.fd = c->fd;
459 				p.events = POLLOUT
460 #ifndef USE_WINSOCK
461 					| POLLERR | POLLHUP
462 #endif
463 					;
464 #  ifndef USE_WINSOCK
465 				pret = poll(&p, 1, SEND_BLOCKED_WAIT_TIMEOUT);
466 #  else
467 				pret = WSAPoll(&p, 1,
468 					SEND_BLOCKED_WAIT_TIMEOUT);
469 #  endif
470 				if(pret == 0) {
471 					/* timer expired */
472 					struct comm_base* b = c->ev->base;
473 					if(b->eb->last_writewait_log+SLOW_LOG_TIME <=
474 						b->eb->secs) {
475 						b->eb->last_writewait_log = b->eb->secs;
476 						verbose(VERB_OPS, "send udp blocked "
477 							"for long, dropping packet.");
478 					}
479 					return 0;
480 				} else if(pret < 0 &&
481 #ifndef USE_WINSOCK
482 					errno != EAGAIN && errno != EINTR &&
483 #  ifdef EWOULDBLOCK
484 					errno != EWOULDBLOCK &&
485 #  endif
486 					errno != ENOMEM && errno != ENOBUFS
487 #else
488 					WSAGetLastError() != WSAEINPROGRESS &&
489 					WSAGetLastError() != WSAEINTR &&
490 					WSAGetLastError() != WSAENOBUFS &&
491 					WSAGetLastError() != WSAEWOULDBLOCK
492 #endif
493 					) {
494 					log_err("poll udp out failed: %s",
495 						sock_strerror(errno));
496 					return 0;
497 				} else if((pret < 0 &&
498 #ifndef USE_WINSOCK
499 					( errno == ENOBUFS  /* Maybe some systems */
500 					|| errno == ENOMEM  /* Linux */
501 					|| errno == EAGAIN)  /* Macos, solaris, openbsd */
502 #else
503 					WSAGetLastError() == WSAENOBUFS
504 #endif
505 					) || (send_nobufs && retries > 0)) {
506 					/* ENOBUFS/ENOMEM/EAGAIN, and poll
507 					 * returned without
508 					 * a timeout. Or the retried send call
509 					 * returned ENOBUFS/ENOMEM/EAGAIN.
510 					 * It is good to wait a bit for the
511 					 * error to clear. */
512 					/* The timeout is 20*(2^(retries+1)),
513 					 * it increases exponentially, starting
514 					 * at 40 msec. After 5 tries, 1240 msec
515 					 * have passed in total, when poll
516 					 * returned the error, and 1200 msec
517 					 * when send returned the errors. */
518 #ifndef USE_WINSOCK
519 					pret = poll(NULL, 0, (SEND_BLOCKED_WAIT_TIMEOUT/10)<<(retries+1));
520 #else
521 					Sleep((SEND_BLOCKED_WAIT_TIMEOUT/10)<<(retries+1));
522 					pret = 0;
523 #endif
524 					if(pret < 0
525 #ifndef USE_WINSOCK
526 						&& errno != EAGAIN && errno != EINTR &&
527 #  ifdef EWOULDBLOCK
528 						errno != EWOULDBLOCK &&
529 #  endif
530 						errno != ENOMEM && errno != ENOBUFS
531 #else
532 						/* Sleep does not error */
533 #endif
534 					) {
535 						log_err("poll udp out timer failed: %s",
536 							sock_strerror(errno));
537 					}
538 				}
539 #endif /* defined(HAVE_POLL) || defined(USE_WINSOCK) */
540 				retries++;
541 				if (!is_connected) {
542 					sent = sendto(c->fd, (void*)sldns_buffer_begin(packet),
543 						sldns_buffer_remaining(packet), 0,
544 						addr, addrlen);
545 				} else {
546 					sent = send(c->fd, (void*)sldns_buffer_begin(packet),
547 						sldns_buffer_remaining(packet), 0);
548 				}
549 			}
550 		}
551 	}
552 	if(sent == -1) {
553 		if(!udp_send_errno_needs_log(addr, addrlen))
554 			return 0;
555 		if (!is_connected) {
556 			verbose(VERB_OPS, "sendto failed: %s", sock_strerror(errno));
557 		} else {
558 			verbose(VERB_OPS, "send failed: %s", sock_strerror(errno));
559 		}
560 		if(addr)
561 			log_addr(VERB_OPS, "remote address is",
562 				(struct sockaddr_storage*)addr, addrlen);
563 		return 0;
564 	} else if((size_t)sent != sldns_buffer_remaining(packet)) {
565 		log_err("sent %d in place of %d bytes",
566 			(int)sent, (int)sldns_buffer_remaining(packet));
567 		return 0;
568 	}
569 	return 1;
570 }
571 
572 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && (defined(HAVE_RECVMSG) || defined(HAVE_SENDMSG))
573 /** print debug ancillary info */
574 static void p_ancil(const char* str, struct comm_reply* r)
575 {
576 	if(r->srctype != 4 && r->srctype != 6) {
577 		log_info("%s: unknown srctype %d", str, r->srctype);
578 		return;
579 	}
580 
581 	if(r->srctype == 6) {
582 #ifdef IPV6_PKTINFO
583 		char buf[1024];
584 		if(inet_ntop(AF_INET6, &r->pktinfo.v6info.ipi6_addr,
585 			buf, (socklen_t)sizeof(buf)) == 0) {
586 			(void)strlcpy(buf, "(inet_ntop error)", sizeof(buf));
587 		}
588 		buf[sizeof(buf)-1]=0;
589 		log_info("%s: %s %d", str, buf, r->pktinfo.v6info.ipi6_ifindex);
590 #endif
591 	} else if(r->srctype == 4) {
592 #ifdef IP_PKTINFO
593 		char buf1[1024], buf2[1024];
594 		if(inet_ntop(AF_INET, &r->pktinfo.v4info.ipi_addr,
595 			buf1, (socklen_t)sizeof(buf1)) == 0) {
596 			(void)strlcpy(buf1, "(inet_ntop error)", sizeof(buf1));
597 		}
598 		buf1[sizeof(buf1)-1]=0;
599 #ifdef HAVE_STRUCT_IN_PKTINFO_IPI_SPEC_DST
600 		if(inet_ntop(AF_INET, &r->pktinfo.v4info.ipi_spec_dst,
601 			buf2, (socklen_t)sizeof(buf2)) == 0) {
602 			(void)strlcpy(buf2, "(inet_ntop error)", sizeof(buf2));
603 		}
604 		buf2[sizeof(buf2)-1]=0;
605 #else
606 		buf2[0]=0;
607 #endif
608 		log_info("%s: %d %s %s", str, r->pktinfo.v4info.ipi_ifindex,
609 			buf1, buf2);
610 #elif defined(IP_RECVDSTADDR)
611 		char buf1[1024];
612 		if(inet_ntop(AF_INET, &r->pktinfo.v4addr,
613 			buf1, (socklen_t)sizeof(buf1)) == 0) {
614 			(void)strlcpy(buf1, "(inet_ntop error)", sizeof(buf1));
615 		}
616 		buf1[sizeof(buf1)-1]=0;
617 		log_info("%s: %s", str, buf1);
618 #endif /* IP_PKTINFO or PI_RECVDSTDADDR */
619 	}
620 }
621 #endif /* AF_INET6 && IPV6_PKTINFO && HAVE_RECVMSG||HAVE_SENDMSG */
622 
623 /** send a UDP reply over specified interface*/
624 static int
625 comm_point_send_udp_msg_if(struct comm_point *c, sldns_buffer* packet,
626 	struct sockaddr* addr, socklen_t addrlen, struct comm_reply* r)
627 {
628 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && defined(HAVE_SENDMSG)
629 	ssize_t sent;
630 	struct msghdr msg;
631 	struct iovec iov[1];
632 	union {
633 		struct cmsghdr hdr;
634 		char buf[256];
635 	} control;
636 #ifndef S_SPLINT_S
637 	struct cmsghdr *cmsg;
638 #endif /* S_SPLINT_S */
639 
640 	log_assert(c->fd != -1);
641 #ifdef UNBOUND_DEBUG
642 	if(sldns_buffer_remaining(packet) == 0)
643 		log_err("error: send empty UDP packet");
644 #endif
645 	log_assert(addr && addrlen > 0);
646 
647 	msg.msg_name = addr;
648 	msg.msg_namelen = addrlen;
649 	iov[0].iov_base = sldns_buffer_begin(packet);
650 	iov[0].iov_len = sldns_buffer_remaining(packet);
651 	msg.msg_iov = iov;
652 	msg.msg_iovlen = 1;
653 	msg.msg_control = control.buf;
654 #ifndef S_SPLINT_S
655 	msg.msg_controllen = sizeof(control.buf);
656 #endif /* S_SPLINT_S */
657 	msg.msg_flags = 0;
658 
659 #ifndef S_SPLINT_S
660 	cmsg = CMSG_FIRSTHDR(&msg);
661 	if(r->srctype == 4) {
662 #ifdef IP_PKTINFO
663 		void* cmsg_data;
664 		msg.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
665 		log_assert(msg.msg_controllen <= sizeof(control.buf));
666 		cmsg->cmsg_level = IPPROTO_IP;
667 		cmsg->cmsg_type = IP_PKTINFO;
668 		memmove(CMSG_DATA(cmsg), &r->pktinfo.v4info,
669 			sizeof(struct in_pktinfo));
670 		/* unset the ifindex to not bypass the routing tables */
671 		cmsg_data = CMSG_DATA(cmsg);
672 		((struct in_pktinfo *) cmsg_data)->ipi_ifindex = 0;
673 		cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
674 		/* zero the padding bytes inserted by the CMSG_LEN */
675 		if(sizeof(struct in_pktinfo) < cmsg->cmsg_len)
676 			memset(((uint8_t*)(CMSG_DATA(cmsg))) +
677 				sizeof(struct in_pktinfo), 0, cmsg->cmsg_len
678 				- sizeof(struct in_pktinfo));
679 #elif defined(IP_SENDSRCADDR)
680 		msg.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
681 		log_assert(msg.msg_controllen <= sizeof(control.buf));
682 		cmsg->cmsg_level = IPPROTO_IP;
683 		cmsg->cmsg_type = IP_SENDSRCADDR;
684 		memmove(CMSG_DATA(cmsg), &r->pktinfo.v4addr,
685 			sizeof(struct in_addr));
686 		cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
687 		/* zero the padding bytes inserted by the CMSG_LEN */
688 		if(sizeof(struct in_addr) < cmsg->cmsg_len)
689 			memset(((uint8_t*)(CMSG_DATA(cmsg))) +
690 				sizeof(struct in_addr), 0, cmsg->cmsg_len
691 				- sizeof(struct in_addr));
692 #else
693 		verbose(VERB_ALGO, "no IP_PKTINFO or IP_SENDSRCADDR");
694 		msg.msg_control = NULL;
695 #endif /* IP_PKTINFO or IP_SENDSRCADDR */
696 	} else if(r->srctype == 6) {
697 		void* cmsg_data;
698 		msg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
699 		log_assert(msg.msg_controllen <= sizeof(control.buf));
700 		cmsg->cmsg_level = IPPROTO_IPV6;
701 		cmsg->cmsg_type = IPV6_PKTINFO;
702 		memmove(CMSG_DATA(cmsg), &r->pktinfo.v6info,
703 			sizeof(struct in6_pktinfo));
704 		/* unset the ifindex to not bypass the routing tables */
705 		cmsg_data = CMSG_DATA(cmsg);
706 		((struct in6_pktinfo *) cmsg_data)->ipi6_ifindex = 0;
707 		cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
708 		/* zero the padding bytes inserted by the CMSG_LEN */
709 		if(sizeof(struct in6_pktinfo) < cmsg->cmsg_len)
710 			memset(((uint8_t*)(CMSG_DATA(cmsg))) +
711 				sizeof(struct in6_pktinfo), 0, cmsg->cmsg_len
712 				- sizeof(struct in6_pktinfo));
713 	} else {
714 		/* try to pass all 0 to use default route */
715 		msg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
716 		log_assert(msg.msg_controllen <= sizeof(control.buf));
717 		cmsg->cmsg_level = IPPROTO_IPV6;
718 		cmsg->cmsg_type = IPV6_PKTINFO;
719 		memset(CMSG_DATA(cmsg), 0, sizeof(struct in6_pktinfo));
720 		cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
721 		/* zero the padding bytes inserted by the CMSG_LEN */
722 		if(sizeof(struct in6_pktinfo) < cmsg->cmsg_len)
723 			memset(((uint8_t*)(CMSG_DATA(cmsg))) +
724 				sizeof(struct in6_pktinfo), 0, cmsg->cmsg_len
725 				- sizeof(struct in6_pktinfo));
726 	}
727 #endif /* S_SPLINT_S */
728 	if(verbosity >= VERB_ALGO && r->srctype != 0)
729 		p_ancil("send_udp over interface", r);
730 	sent = sendmsg(c->fd, &msg, 0);
731 	if(sent == -1) {
732 		/* try again and block, waiting for IO to complete,
733 		 * we want to send the answer, and we will wait for
734 		 * the ethernet interface buffer to have space. */
735 #ifndef USE_WINSOCK
736 		if(errno == EAGAIN || errno == EINTR ||
737 #  ifdef EWOULDBLOCK
738 			errno == EWOULDBLOCK ||
739 #  endif
740 			errno == ENOBUFS) {
741 #else
742 		if(WSAGetLastError() == WSAEINPROGRESS ||
743 			WSAGetLastError() == WSAEINTR ||
744 			WSAGetLastError() == WSAENOBUFS ||
745 			WSAGetLastError() == WSAEWOULDBLOCK) {
746 #endif
747 			int retries = 0;
748 			while(sent == -1 && retries < SEND_BLOCKED_MAX_RETRY && (
749 #ifndef USE_WINSOCK
750 				errno == EAGAIN || errno == EINTR ||
751 #  ifdef EWOULDBLOCK
752 				errno == EWOULDBLOCK ||
753 #  endif
754 				errno == ENOBUFS
755 #else
756 				WSAGetLastError() == WSAEINPROGRESS ||
757 				WSAGetLastError() == WSAEINTR ||
758 				WSAGetLastError() == WSAENOBUFS ||
759 				WSAGetLastError() == WSAEWOULDBLOCK
760 #endif
761 			)) {
762 #if defined(HAVE_POLL) || defined(USE_WINSOCK)
763 				int send_nobufs = (
764 #ifndef USE_WINSOCK
765 					errno == ENOBUFS
766 #else
767 					WSAGetLastError() == WSAENOBUFS
768 #endif
769 				);
770 				struct pollfd p;
771 				int pret;
772 				memset(&p, 0, sizeof(p));
773 				p.fd = c->fd;
774 				p.events = POLLOUT
775 #ifndef USE_WINSOCK
776 					| POLLERR | POLLHUP
777 #endif
778 					;
779 #  ifndef USE_WINSOCK
780 				pret = poll(&p, 1, SEND_BLOCKED_WAIT_TIMEOUT);
781 #  else
782 				pret = WSAPoll(&p, 1,
783 					SEND_BLOCKED_WAIT_TIMEOUT);
784 #  endif
785 				if(pret == 0) {
786 					/* timer expired */
787 					struct comm_base* b = c->ev->base;
788 					if(b->eb->last_writewait_log+SLOW_LOG_TIME <=
789 						b->eb->secs) {
790 						b->eb->last_writewait_log = b->eb->secs;
791 						verbose(VERB_OPS, "send udp blocked "
792 							"for long, dropping packet.");
793 					}
794 					return 0;
795 				} else if(pret < 0 &&
796 #ifndef USE_WINSOCK
797 					errno != EAGAIN && errno != EINTR &&
798 #  ifdef EWOULDBLOCK
799 					errno != EWOULDBLOCK &&
800 #  endif
801 					errno != ENOMEM && errno != ENOBUFS
802 #else
803 					WSAGetLastError() != WSAEINPROGRESS &&
804 					WSAGetLastError() != WSAEINTR &&
805 					WSAGetLastError() != WSAENOBUFS &&
806 					WSAGetLastError() != WSAEWOULDBLOCK
807 #endif
808 					) {
809 					log_err("poll udp out failed: %s",
810 						sock_strerror(errno));
811 					return 0;
812 				} else if((pret < 0 &&
813 #ifndef USE_WINSOCK
814 					( errno == ENOBUFS  /* Maybe some systems */
815 					|| errno == ENOMEM  /* Linux */
816 					|| errno == EAGAIN)  /* Macos, solaris, openbsd */
817 #else
818 					WSAGetLastError() == WSAENOBUFS
819 #endif
820 					) || (send_nobufs && retries > 0)) {
821 					/* ENOBUFS/ENOMEM/EAGAIN, and poll
822 					 * returned without
823 					 * a timeout. Or the retried send call
824 					 * returned ENOBUFS/ENOMEM/EAGAIN.
825 					 * It is good to wait a bit for the
826 					 * error to clear. */
827 					/* The timeout is 20*(2^(retries+1)),
828 					 * it increases exponentially, starting
829 					 * at 40 msec. After 5 tries, 1240 msec
830 					 * have passed in total, when poll
831 					 * returned the error, and 1200 msec
832 					 * when send returned the errors. */
833 #ifndef USE_WINSOCK
834 					pret = poll(NULL, 0, (SEND_BLOCKED_WAIT_TIMEOUT/10)<<(retries+1));
835 #else
836 					Sleep((SEND_BLOCKED_WAIT_TIMEOUT/10)<<(retries+1));
837 					pret = 0;
838 #endif
839 					if(pret < 0
840 #ifndef USE_WINSOCK
841 						&& errno != EAGAIN && errno != EINTR &&
842 #  ifdef EWOULDBLOCK
843 						errno != EWOULDBLOCK &&
844 #  endif
845 						errno != ENOMEM && errno != ENOBUFS
846 #else  /* USE_WINSOCK */
847 						/* Sleep does not error */
848 #endif
849 					) {
850 						log_err("poll udp out timer failed: %s",
851 							sock_strerror(errno));
852 					}
853 				}
854 #endif /* defined(HAVE_POLL) || defined(USE_WINSOCK) */
855 				retries++;
856 				sent = sendmsg(c->fd, &msg, 0);
857 			}
858 		}
859 	}
860 	if(sent == -1) {
861 		if(!udp_send_errno_needs_log(addr, addrlen))
862 			return 0;
863 		verbose(VERB_OPS, "sendmsg failed: %s", strerror(errno));
864 		log_addr(VERB_OPS, "remote address is",
865 			(struct sockaddr_storage*)addr, addrlen);
866 #ifdef __NetBSD__
867 		/* netbsd 7 has IP_PKTINFO for recv but not send */
868 		if(errno == EINVAL && r->srctype == 4)
869 			log_err("sendmsg: No support for sendmsg(IP_PKTINFO). "
870 				"Please disable interface-automatic");
871 #endif
872 		return 0;
873 	} else if((size_t)sent != sldns_buffer_remaining(packet)) {
874 		log_err("sent %d in place of %d bytes",
875 			(int)sent, (int)sldns_buffer_remaining(packet));
876 		return 0;
877 	}
878 	return 1;
879 #else
880 	(void)c;
881 	(void)packet;
882 	(void)addr;
883 	(void)addrlen;
884 	(void)r;
885 	log_err("sendmsg: IPV6_PKTINFO not supported");
886 	return 0;
887 #endif /* AF_INET6 && IPV6_PKTINFO && HAVE_SENDMSG */
888 }
889 
890 /** return true is UDP receive error needs to be logged */
891 static int udp_recv_needs_log(int err)
892 {
893 	switch(err) {
894 	case EACCES: /* some hosts send ICMP 'Permission Denied' */
895 #ifndef USE_WINSOCK
896 	case ECONNREFUSED:
897 #  ifdef ENETUNREACH
898 	case ENETUNREACH:
899 #  endif
900 #  ifdef EHOSTDOWN
901 	case EHOSTDOWN:
902 #  endif
903 #  ifdef EHOSTUNREACH
904 	case EHOSTUNREACH:
905 #  endif
906 #  ifdef ENETDOWN
907 	case ENETDOWN:
908 #  endif
909 #else /* USE_WINSOCK */
910 	case WSAECONNREFUSED:
911 	case WSAENETUNREACH:
912 	case WSAEHOSTDOWN:
913 	case WSAEHOSTUNREACH:
914 	case WSAENETDOWN:
915 #endif
916 		if(verbosity >= VERB_ALGO)
917 			return 1;
918 		return 0;
919 	default:
920 		break;
921 	}
922 	return 1;
923 }
924 
925 /** Parses the PROXYv2 header from buf and updates the comm_reply struct.
926  *  Returns 1 on success, 0 on failure. */
927 static int consume_pp2_header(struct sldns_buffer* buf, struct comm_reply* rep,
928 	int stream) {
929 	size_t size;
930 	struct pp2_header *header;
931 	int err = pp2_read_header(sldns_buffer_begin(buf),
932 		sldns_buffer_remaining(buf));
933 	if(err) return 0;
934 	header = (struct pp2_header*)sldns_buffer_begin(buf);
935 	size = PP2_HEADER_SIZE + ntohs(header->len);
936 	if((header->ver_cmd & 0xF) == PP2_CMD_LOCAL) {
937 		/* A connection from the proxy itself.
938 		 * No need to do anything with addresses. */
939 		goto done;
940 	}
941 	if(header->fam_prot == PP2_UNSPEC_UNSPEC) {
942 		/* Unspecified family and protocol. This could be used for
943 		 * health checks by proxies.
944 		 * No need to do anything with addresses. */
945 		goto done;
946 	}
947 	/* Read the proxied address */
948 	switch(header->fam_prot) {
949 		case PP2_INET_STREAM:
950 		case PP2_INET_DGRAM:
951 			{
952 			struct sockaddr_in* addr =
953 				(struct sockaddr_in*)&rep->client_addr;
954 			if(ntohs(header->len) < PP2_HEADER_LEN_INET) {
955 				verbose(VERB_OPS, "proxy_protocol: header too short for IPv4 address");
956 				return 0;
957 			}
958 			addr->sin_family = AF_INET;
959 			addr->sin_addr.s_addr = header->addr.addr4.src_addr;
960 			addr->sin_port = header->addr.addr4.src_port;
961 			rep->client_addrlen = (socklen_t)sizeof(struct sockaddr_in);
962 			}
963 			/* Ignore the destination address; it should be us. */
964 			break;
965 		case PP2_INET6_STREAM:
966 		case PP2_INET6_DGRAM:
967 			{
968 			struct sockaddr_in6* addr =
969 				(struct sockaddr_in6*)&rep->client_addr;
970 			if(ntohs(header->len) < PP2_HEADER_LEN_INET6) {
971 				verbose(VERB_OPS, "proxy_protocol: header too short for IPv6 address");
972 				return 0;
973 			}
974 			memset(addr, 0, sizeof(*addr));
975 			addr->sin6_family = AF_INET6;
976 			memcpy(&addr->sin6_addr,
977 				header->addr.addr6.src_addr, 16);
978 			addr->sin6_port = header->addr.addr6.src_port;
979 			rep->client_addrlen = (socklen_t)sizeof(struct sockaddr_in6);
980 			}
981 			/* Ignore the destination address; it should be us. */
982 			break;
983 		default:
984 			log_err("proxy_protocol: unsupported family and "
985 				"protocol 0x%x", (int)header->fam_prot);
986 			return 0;
987 	}
988 	rep->is_proxied = 1;
989 done:
990 	if(!stream) {
991 		/* We are reading a whole packet;
992 		 * Move the rest of the data to overwrite the PROXYv2 header */
993 		/* XXX can we do better to avoid memmove? */
994 		memmove(header, ((char*)header)+size,
995 			sldns_buffer_limit(buf)-size);
996 		sldns_buffer_set_limit(buf, sldns_buffer_limit(buf)-size);
997 	}
998 	return 1;
999 }
1000 
1001 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && defined(HAVE_RECVMSG)
1002 void
1003 comm_point_udp_ancil_callback(int fd, short event, void* arg)
1004 {
1005 	struct comm_reply rep;
1006 	struct msghdr msg;
1007 	struct iovec iov[1];
1008 	ssize_t rcv;
1009 	union {
1010 		struct cmsghdr hdr;
1011 		char buf[256];
1012 	} ancil;
1013 	int i;
1014 #ifndef S_SPLINT_S
1015 	struct cmsghdr* cmsg;
1016 #endif /* S_SPLINT_S */
1017 #ifdef HAVE_LINUX_NET_TSTAMP_H
1018 	struct timespec *ts;
1019 #endif /* HAVE_LINUX_NET_TSTAMP_H */
1020 
1021 	rep.c = (struct comm_point*)arg;
1022 	log_assert(rep.c->type == comm_udp);
1023 
1024 	if(!(event&UB_EV_READ))
1025 		return;
1026 	log_assert(rep.c && rep.c->buffer && rep.c->fd == fd);
1027 	ub_comm_base_now(rep.c->ev->base);
1028 	for(i=0; i<NUM_UDP_PER_SELECT; i++) {
1029 		sldns_buffer_clear(rep.c->buffer);
1030 		timeval_clear(&rep.c->recv_tv);
1031 		rep.remote_addrlen = (socklen_t)sizeof(rep.remote_addr);
1032 		log_assert(fd != -1);
1033 		log_assert(sldns_buffer_remaining(rep.c->buffer) > 0);
1034 		msg.msg_name = &rep.remote_addr;
1035 		msg.msg_namelen = (socklen_t)sizeof(rep.remote_addr);
1036 		iov[0].iov_base = sldns_buffer_begin(rep.c->buffer);
1037 		iov[0].iov_len = sldns_buffer_remaining(rep.c->buffer);
1038 		msg.msg_iov = iov;
1039 		msg.msg_iovlen = 1;
1040 		msg.msg_control = ancil.buf;
1041 #ifndef S_SPLINT_S
1042 		msg.msg_controllen = sizeof(ancil.buf);
1043 #endif /* S_SPLINT_S */
1044 		msg.msg_flags = 0;
1045 		rcv = recvmsg(fd, &msg, MSG_DONTWAIT);
1046 		if(rcv == -1) {
1047 			if(errno != EAGAIN && errno != EINTR
1048 				&& udp_recv_needs_log(errno)) {
1049 				log_err("recvmsg failed: %s", strerror(errno));
1050 			}
1051 			return;
1052 		}
1053 		rep.remote_addrlen = msg.msg_namelen;
1054 		sldns_buffer_skip(rep.c->buffer, rcv);
1055 		sldns_buffer_flip(rep.c->buffer);
1056 		rep.srctype = 0;
1057 		rep.is_proxied = 0;
1058 #ifndef S_SPLINT_S
1059 		for(cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
1060 			cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1061 			if( cmsg->cmsg_level == IPPROTO_IPV6 &&
1062 				cmsg->cmsg_type == IPV6_PKTINFO) {
1063 				rep.srctype = 6;
1064 				memmove(&rep.pktinfo.v6info, CMSG_DATA(cmsg),
1065 					sizeof(struct in6_pktinfo));
1066 				break;
1067 #ifdef IP_PKTINFO
1068 			} else if( cmsg->cmsg_level == IPPROTO_IP &&
1069 				cmsg->cmsg_type == IP_PKTINFO) {
1070 				rep.srctype = 4;
1071 				memmove(&rep.pktinfo.v4info, CMSG_DATA(cmsg),
1072 					sizeof(struct in_pktinfo));
1073 				break;
1074 #elif defined(IP_RECVDSTADDR)
1075 			} else if( cmsg->cmsg_level == IPPROTO_IP &&
1076 				cmsg->cmsg_type == IP_RECVDSTADDR) {
1077 				rep.srctype = 4;
1078 				memmove(&rep.pktinfo.v4addr, CMSG_DATA(cmsg),
1079 					sizeof(struct in_addr));
1080 				break;
1081 #endif /* IP_PKTINFO or IP_RECVDSTADDR */
1082 #ifdef HAVE_LINUX_NET_TSTAMP_H
1083 			} else if( cmsg->cmsg_level == SOL_SOCKET &&
1084 				cmsg->cmsg_type == SO_TIMESTAMPNS) {
1085 				ts = (struct timespec *)CMSG_DATA(cmsg);
1086 				TIMESPEC_TO_TIMEVAL(&rep.c->recv_tv, ts);
1087 			} else if( cmsg->cmsg_level == SOL_SOCKET &&
1088 				cmsg->cmsg_type == SO_TIMESTAMPING) {
1089 				ts = (struct timespec *)CMSG_DATA(cmsg);
1090 				TIMESPEC_TO_TIMEVAL(&rep.c->recv_tv, ts);
1091 			} else if( cmsg->cmsg_level == SOL_SOCKET &&
1092 				cmsg->cmsg_type == SO_TIMESTAMP) {
1093 				memmove(&rep.c->recv_tv, CMSG_DATA(cmsg), sizeof(struct timeval));
1094 #elif defined(SO_TIMESTAMP) && defined(SCM_TIMESTAMP)
1095 			} else if( cmsg->cmsg_level == SOL_SOCKET &&
1096 				cmsg->cmsg_type == SCM_TIMESTAMP) {
1097 				/* FreeBSD and also Linux. */
1098 				memmove(&rep.c->recv_tv, CMSG_DATA(cmsg), sizeof(struct timeval));
1099 #endif /* HAVE_LINUX_NET_TSTAMP_H */
1100 			}
1101 		}
1102 
1103 		if(verbosity >= VERB_ALGO && rep.srctype != 0)
1104 			p_ancil("receive_udp on interface", &rep);
1105 #endif /* S_SPLINT_S */
1106 
1107 		if(rep.c->pp2_enabled && !consume_pp2_header(rep.c->buffer,
1108 			&rep, 0)) {
1109 			log_err("proxy_protocol: could not consume PROXYv2 header");
1110 			return;
1111 		}
1112 		if(!rep.is_proxied) {
1113 			rep.client_addrlen = rep.remote_addrlen;
1114 			memmove(&rep.client_addr, &rep.remote_addr,
1115 				rep.remote_addrlen);
1116 		}
1117 
1118 		fptr_ok(fptr_whitelist_comm_point(rep.c->callback));
1119 		if((*rep.c->callback)(rep.c, rep.c->cb_arg, NETEVENT_NOERROR, &rep)) {
1120 			/* send back immediate reply */
1121 			struct sldns_buffer *buffer;
1122 #ifdef USE_DNSCRYPT
1123 			buffer = rep.c->dnscrypt_buffer;
1124 #else
1125 			buffer = rep.c->buffer;
1126 #endif
1127 			(void)comm_point_send_udp_msg_if(rep.c, buffer,
1128 				(struct sockaddr*)&rep.remote_addr,
1129 				rep.remote_addrlen, &rep);
1130 		}
1131 		if(!rep.c || rep.c->fd == -1) /* commpoint closed */
1132 			break;
1133 	}
1134 }
1135 #endif /* AF_INET6 && IPV6_PKTINFO && HAVE_RECVMSG */
1136 
1137 void
1138 comm_point_udp_callback(int fd, short event, void* arg)
1139 {
1140 	struct comm_reply rep;
1141 	ssize_t rcv;
1142 	int i;
1143 	struct sldns_buffer *buffer;
1144 
1145 	rep.c = (struct comm_point*)arg;
1146 	log_assert(rep.c->type == comm_udp);
1147 
1148 	if(!(event&UB_EV_READ))
1149 		return;
1150 	log_assert(rep.c && rep.c->buffer && rep.c->fd == fd);
1151 	ub_comm_base_now(rep.c->ev->base);
1152 	for(i=0; i<NUM_UDP_PER_SELECT; i++) {
1153 		sldns_buffer_clear(rep.c->buffer);
1154 		rep.remote_addrlen = (socklen_t)sizeof(rep.remote_addr);
1155 		log_assert(fd != -1);
1156 		log_assert(sldns_buffer_remaining(rep.c->buffer) > 0);
1157 		rcv = recvfrom(fd, (void*)sldns_buffer_begin(rep.c->buffer),
1158 			sldns_buffer_remaining(rep.c->buffer), MSG_DONTWAIT,
1159 			(struct sockaddr*)&rep.remote_addr, &rep.remote_addrlen);
1160 		if(rcv == -1) {
1161 #ifndef USE_WINSOCK
1162 			if(errno != EAGAIN && errno != EINTR
1163 				&& udp_recv_needs_log(errno))
1164 				log_err("recvfrom %d failed: %s",
1165 					fd, strerror(errno));
1166 #else
1167 			if(WSAGetLastError() != WSAEINPROGRESS &&
1168 				WSAGetLastError() != WSAECONNRESET &&
1169 				WSAGetLastError()!= WSAEWOULDBLOCK &&
1170 				udp_recv_needs_log(WSAGetLastError()))
1171 				log_err("recvfrom failed: %s",
1172 					wsa_strerror(WSAGetLastError()));
1173 #endif
1174 			return;
1175 		}
1176 		sldns_buffer_skip(rep.c->buffer, rcv);
1177 		sldns_buffer_flip(rep.c->buffer);
1178 		rep.srctype = 0;
1179 		rep.is_proxied = 0;
1180 
1181 		if(rep.c->pp2_enabled && !consume_pp2_header(rep.c->buffer,
1182 			&rep, 0)) {
1183 			log_err("proxy_protocol: could not consume PROXYv2 header");
1184 			return;
1185 		}
1186 		if(!rep.is_proxied) {
1187 			rep.client_addrlen = rep.remote_addrlen;
1188 			memmove(&rep.client_addr, &rep.remote_addr,
1189 				rep.remote_addrlen);
1190 		}
1191 
1192 		fptr_ok(fptr_whitelist_comm_point(rep.c->callback));
1193 		if((*rep.c->callback)(rep.c, rep.c->cb_arg, NETEVENT_NOERROR, &rep)) {
1194 			/* send back immediate reply */
1195 #ifdef USE_DNSCRYPT
1196 			buffer = rep.c->dnscrypt_buffer;
1197 #else
1198 			buffer = rep.c->buffer;
1199 #endif
1200 			(void)comm_point_send_udp_msg(rep.c, buffer,
1201 				(struct sockaddr*)&rep.remote_addr,
1202 				rep.remote_addrlen, 0);
1203 		}
1204 		if(!rep.c || rep.c->fd != fd) /* commpoint closed to -1 or reused for
1205 		another UDP port. Note rep.c cannot be reused with TCP fd. */
1206 			break;
1207 	}
1208 }
1209 
1210 #ifdef HAVE_NGTCP2
1211 void
1212 doq_pkt_addr_init(struct doq_pkt_addr* paddr)
1213 {
1214 	paddr->addrlen = (socklen_t)sizeof(paddr->addr);
1215 	paddr->localaddrlen = (socklen_t)sizeof(paddr->localaddr);
1216 	paddr->ifindex = 0;
1217 }
1218 
1219 /** set the ecn on the transmission */
1220 static void
1221 doq_set_ecn(int fd, int family, uint32_t ecn)
1222 {
1223 	unsigned int val = ecn;
1224 	if(family == AF_INET6) {
1225 		if(setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, &val,
1226 			(socklen_t)sizeof(val)) == -1) {
1227 			log_err("setsockopt(.. IPV6_TCLASS ..): %s",
1228 				strerror(errno));
1229 		}
1230 		return;
1231 	}
1232 	if(setsockopt(fd, IPPROTO_IP, IP_TOS, &val,
1233 		(socklen_t)sizeof(val)) == -1) {
1234 		log_err("setsockopt(.. IP_TOS ..): %s",
1235 			strerror(errno));
1236 	}
1237 }
1238 
1239 /** set the local address in the control ancillary data */
1240 static void
1241 doq_set_localaddr_cmsg(struct msghdr* msg, size_t control_size,
1242 	struct doq_addr_storage* localaddr, socklen_t localaddrlen,
1243 	int ifindex)
1244 {
1245 #ifndef S_SPLINT_S
1246 	struct cmsghdr* cmsg;
1247 #endif /* S_SPLINT_S */
1248 #ifndef S_SPLINT_S
1249 	cmsg = CMSG_FIRSTHDR(msg);
1250 	if(localaddr->sockaddr.in.sin_family == AF_INET) {
1251 #ifdef IP_PKTINFO
1252 		struct sockaddr_in* sa = (struct sockaddr_in*)localaddr;
1253 		struct in_pktinfo v4info;
1254 		log_assert(localaddrlen >= sizeof(struct sockaddr_in));
1255 		msg->msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
1256 		memset(msg->msg_control, 0, msg->msg_controllen);
1257 		log_assert(msg->msg_controllen <= control_size);
1258 		cmsg->cmsg_level = IPPROTO_IP;
1259 		cmsg->cmsg_type = IP_PKTINFO;
1260 		memset(&v4info, 0, sizeof(v4info));
1261 #  ifdef HAVE_STRUCT_IN_PKTINFO_IPI_SPEC_DST
1262 		memmove(&v4info.ipi_spec_dst, &sa->sin_addr,
1263 			sizeof(struct in_addr));
1264 #  else
1265 		memmove(&v4info.ipi_addr, &sa->sin_addr,
1266 			sizeof(struct in_addr));
1267 #  endif
1268 		v4info.ipi_ifindex = ifindex;
1269 		memmove(CMSG_DATA(cmsg), &v4info, sizeof(struct in_pktinfo));
1270 		cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
1271 #elif defined(IP_SENDSRCADDR)
1272 		struct sockaddr_in* sa= (struct sockaddr_in*)localaddr;
1273 		log_assert(localaddrlen >= sizeof(struct sockaddr_in));
1274 		msg->msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
1275 		memset(msg->msg_control, 0, msg->msg_controllen);
1276 		log_assert(msg->msg_controllen <= control_size);
1277 		cmsg->cmsg_level = IPPROTO_IP;
1278 		cmsg->cmsg_type = IP_SENDSRCADDR;
1279 		memmove(CMSG_DATA(cmsg),  &sa->sin_addr,
1280 			sizeof(struct in_addr));
1281 		cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
1282 #endif
1283 	} else {
1284 		struct sockaddr_in6* sa6 = (struct sockaddr_in6*)localaddr;
1285 		struct in6_pktinfo v6info;
1286 		log_assert(localaddrlen >= sizeof(struct sockaddr_in6));
1287 		msg->msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
1288 		memset(msg->msg_control, 0, msg->msg_controllen);
1289 		log_assert(msg->msg_controllen <= control_size);
1290 		cmsg->cmsg_level = IPPROTO_IPV6;
1291 		cmsg->cmsg_type = IPV6_PKTINFO;
1292 		memset(&v6info, 0, sizeof(v6info));
1293 		memmove(&v6info.ipi6_addr, &sa6->sin6_addr,
1294 			sizeof(struct in6_addr));
1295 		v6info.ipi6_ifindex = ifindex;
1296 		memmove(CMSG_DATA(cmsg), &v6info, sizeof(struct in6_pktinfo));
1297 		cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
1298 	}
1299 #endif /* S_SPLINT_S */
1300 	/* Ignore unused variables, if no assertions are compiled. */
1301 	(void)localaddrlen;
1302 	(void)control_size;
1303 }
1304 
1305 /** write address and port into strings */
1306 static int
1307 doq_print_addr_port(struct doq_addr_storage* addr, socklen_t addrlen,
1308 	char* host, size_t hostlen, char* port, size_t portlen)
1309 {
1310 	if(addr->sockaddr.in.sin_family == AF_INET) {
1311 		struct sockaddr_in* sa = (struct sockaddr_in*)addr;
1312 		log_assert(addrlen >= sizeof(*sa));
1313 		if(inet_ntop(sa->sin_family, &sa->sin_addr, host,
1314 			(socklen_t)hostlen) == 0) {
1315 			log_hex("inet_ntop error: address", &sa->sin_addr,
1316 				sizeof(sa->sin_addr));
1317 			return 0;
1318 		}
1319 		snprintf(port, portlen, "%u", (unsigned)ntohs(sa->sin_port));
1320 	} else if(addr->sockaddr.in.sin_family == AF_INET6) {
1321 		struct sockaddr_in6* sa6 = (struct sockaddr_in6*)addr;
1322 		log_assert(addrlen >= sizeof(*sa6));
1323 		if(inet_ntop(sa6->sin6_family, &sa6->sin6_addr, host,
1324 			(socklen_t)hostlen) == 0) {
1325 			log_hex("inet_ntop error: address", &sa6->sin6_addr,
1326 				sizeof(sa6->sin6_addr));
1327 			return 0;
1328 		}
1329 		snprintf(port, portlen, "%u", (unsigned)ntohs(sa6->sin6_port));
1330 	}
1331 	return 1;
1332 }
1333 
1334 /** doq store the blocked packet when write has blocked */
1335 static void
1336 doq_store_blocked_pkt(struct comm_point* c, struct doq_pkt_addr* paddr,
1337 	uint32_t ecn)
1338 {
1339 	if(c->doq_socket->have_blocked_pkt)
1340 		return; /* should not happen that we write when there is
1341 		already a blocked write, but if so, drop it. */
1342 	if(sldns_buffer_limit(c->doq_socket->pkt_buf) >
1343 		sldns_buffer_capacity(c->doq_socket->blocked_pkt))
1344 		return; /* impossibly large, drop packet. impossible because
1345 		pkt_buf and blocked_pkt are the same size. */
1346 	c->doq_socket->have_blocked_pkt = 1;
1347 	c->doq_socket->blocked_pkt_pi.ecn = ecn;
1348 	memcpy(c->doq_socket->blocked_paddr, paddr,
1349 		sizeof(*c->doq_socket->blocked_paddr));
1350 	sldns_buffer_clear(c->doq_socket->blocked_pkt);
1351 	sldns_buffer_write(c->doq_socket->blocked_pkt,
1352 		sldns_buffer_begin(c->doq_socket->pkt_buf),
1353 		sldns_buffer_limit(c->doq_socket->pkt_buf));
1354 	sldns_buffer_flip(c->doq_socket->blocked_pkt);
1355 }
1356 
1357 void
1358 doq_send_pkt(struct comm_point* c, struct doq_pkt_addr* paddr, uint32_t ecn)
1359 {
1360 	struct msghdr msg;
1361 	struct iovec iov[1];
1362 	union {
1363 		struct cmsghdr hdr;
1364 		char buf[256];
1365 	} control;
1366 	ssize_t ret;
1367 	iov[0].iov_base = sldns_buffer_begin(c->doq_socket->pkt_buf);
1368 	iov[0].iov_len = sldns_buffer_limit(c->doq_socket->pkt_buf);
1369 	memset(&msg, 0, sizeof(msg));
1370 	msg.msg_name = (void*)&paddr->addr;
1371 	msg.msg_namelen = paddr->addrlen;
1372 	msg.msg_iov = iov;
1373 	msg.msg_iovlen = 1;
1374 	msg.msg_control = control.buf;
1375 #ifndef S_SPLINT_S
1376 	msg.msg_controllen = sizeof(control.buf);
1377 #endif /* S_SPLINT_S */
1378 	msg.msg_flags = 0;
1379 
1380 	doq_set_localaddr_cmsg(&msg, sizeof(control.buf), &paddr->localaddr,
1381 		paddr->localaddrlen, paddr->ifindex);
1382 	doq_set_ecn(c->fd, paddr->addr.sockaddr.in.sin_family, ecn);
1383 
1384 	for(;;) {
1385 		ret = sendmsg(c->fd, &msg, MSG_DONTWAIT);
1386 		if(ret == -1 && errno == EINTR)
1387 			continue;
1388 		break;
1389 	}
1390 	if(ret == -1) {
1391 #ifndef USE_WINSOCK
1392 		if(errno == EAGAIN ||
1393 #  ifdef EWOULDBLOCK
1394 			errno == EWOULDBLOCK ||
1395 #  endif
1396 			errno == ENOBUFS)
1397 #else
1398 		if(WSAGetLastError() == WSAEINPROGRESS ||
1399 			WSAGetLastError() == WSAENOBUFS ||
1400 			WSAGetLastError() == WSAEWOULDBLOCK)
1401 #endif
1402 		{
1403 			/* udp send has blocked */
1404 			doq_store_blocked_pkt(c, paddr, ecn);
1405 			return;
1406 		}
1407 		if(!udp_send_errno_needs_log((void*)&paddr->addr,
1408 			paddr->addrlen))
1409 			return;
1410 		if(verbosity >= VERB_OPS) {
1411 			char host[256], port[32];
1412 			if(doq_print_addr_port(&paddr->addr, paddr->addrlen,
1413 				host, sizeof(host), port, sizeof(port))) {
1414 				verbose(VERB_OPS, "doq sendmsg to %s %s "
1415 					"failed: %s", host, port,
1416 					strerror(errno));
1417 			} else {
1418 				verbose(VERB_OPS, "doq sendmsg failed: %s",
1419 					strerror(errno));
1420 			}
1421 		}
1422 		return;
1423 	} else if(ret != (ssize_t)sldns_buffer_limit(c->doq_socket->pkt_buf)) {
1424 		char host[256], port[32];
1425 		if(doq_print_addr_port(&paddr->addr, paddr->addrlen, host,
1426 			sizeof(host), port, sizeof(port))) {
1427 			log_err("doq sendmsg to %s %s failed: "
1428 				"sent %d in place of %d bytes",
1429 				host, port, (int)ret,
1430 				(int)sldns_buffer_limit(c->doq_socket->pkt_buf));
1431 		} else {
1432 			log_err("doq sendmsg failed: "
1433 				"sent %d in place of %d bytes",
1434 				(int)ret, (int)sldns_buffer_limit(c->doq_socket->pkt_buf));
1435 		}
1436 		return;
1437 	}
1438 }
1439 
1440 /** fetch port number */
1441 static int
1442 doq_sockaddr_get_port(struct doq_addr_storage* addr)
1443 {
1444 	if(addr->sockaddr.in.sin_family == AF_INET) {
1445 		struct sockaddr_in* sa = (struct sockaddr_in*)addr;
1446 		return ntohs(sa->sin_port);
1447 	} else if(addr->sockaddr.in.sin_family == AF_INET6) {
1448 		struct sockaddr_in6* sa6 = (struct sockaddr_in6*)addr;
1449 		return ntohs(sa6->sin6_port);
1450 	}
1451 	return 0;
1452 }
1453 
1454 /** get local address from ancillary data headers */
1455 static int
1456 doq_get_localaddr_cmsg(struct comm_point* c, struct doq_pkt_addr* paddr,
1457 	int* pkt_continue, struct msghdr* msg)
1458 {
1459 #ifndef S_SPLINT_S
1460 	struct cmsghdr* cmsg;
1461 #endif /* S_SPLINT_S */
1462 
1463 	memset(&paddr->localaddr, 0, sizeof(paddr->localaddr));
1464 #ifndef S_SPLINT_S
1465 	for(cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL;
1466 		cmsg = CMSG_NXTHDR(msg, cmsg)) {
1467 		if( cmsg->cmsg_level == IPPROTO_IPV6 &&
1468 			cmsg->cmsg_type == IPV6_PKTINFO) {
1469 			struct in6_pktinfo* v6info =
1470 				(struct in6_pktinfo*)CMSG_DATA(cmsg);
1471 			struct sockaddr_in6* sa= (struct sockaddr_in6*)
1472 				&paddr->localaddr;
1473 			struct sockaddr_in6* rema = (struct sockaddr_in6*)
1474 				&paddr->addr;
1475 			if(rema->sin6_family != AF_INET6) {
1476 				log_err("doq cmsg family mismatch cmsg is ip6");
1477 				*pkt_continue = 1;
1478 				return 0;
1479 			}
1480 			sa->sin6_family = AF_INET6;
1481 			sa->sin6_port = htons(doq_sockaddr_get_port(
1482 				(void*)c->socket->addr));
1483 			paddr->ifindex = v6info->ipi6_ifindex;
1484 			memmove(&sa->sin6_addr, &v6info->ipi6_addr,
1485 				sizeof(struct in6_addr));
1486 			paddr->localaddrlen = sizeof(struct sockaddr_in6);
1487 			break;
1488 #ifdef IP_PKTINFO
1489 		} else if( cmsg->cmsg_level == IPPROTO_IP &&
1490 			cmsg->cmsg_type == IP_PKTINFO) {
1491 			struct in_pktinfo* v4info =
1492 				(struct in_pktinfo*)CMSG_DATA(cmsg);
1493 			struct sockaddr_in* sa= (struct sockaddr_in*)
1494 				&paddr->localaddr;
1495 			struct sockaddr_in* rema = (struct sockaddr_in*)
1496 				&paddr->addr;
1497 			if(rema->sin_family != AF_INET) {
1498 				log_err("doq cmsg family mismatch cmsg is ip4");
1499 				*pkt_continue = 1;
1500 				return 0;
1501 			}
1502 			sa->sin_family = AF_INET;
1503 			sa->sin_port = htons(doq_sockaddr_get_port(
1504 				(void*)c->socket->addr));
1505 			paddr->ifindex = v4info->ipi_ifindex;
1506 			memmove(&sa->sin_addr, &v4info->ipi_addr,
1507 				sizeof(struct in_addr));
1508 			paddr->localaddrlen = sizeof(struct sockaddr_in);
1509 			break;
1510 #elif defined(IP_RECVDSTADDR)
1511 		} else if( cmsg->cmsg_level == IPPROTO_IP &&
1512 			cmsg->cmsg_type == IP_RECVDSTADDR) {
1513 			struct sockaddr_in* sa= (struct sockaddr_in*)
1514 				&paddr->localaddr;
1515 			struct sockaddr_in* rema = (struct sockaddr_in*)
1516 				&paddr->addr;
1517 			if(rema->sin_family != AF_INET) {
1518 				log_err("doq cmsg family mismatch cmsg is ip4");
1519 				*pkt_continue = 1;
1520 				return 0;
1521 			}
1522 			sa->sin_family = AF_INET;
1523 			sa->sin_port = htons(doq_sockaddr_get_port(
1524 				(void*)c->socket->addr));
1525 			paddr->ifindex = 0;
1526 			memmove(&sa.sin_addr, CMSG_DATA(cmsg),
1527 				sizeof(struct in_addr));
1528 			paddr->localaddrlen = sizeof(struct sockaddr_in);
1529 			break;
1530 #endif /* IP_PKTINFO or IP_RECVDSTADDR */
1531 		}
1532 	}
1533 #endif /* S_SPLINT_S */
1534 
1535 return 1;
1536 }
1537 
1538 /** get packet ecn information */
1539 static uint32_t
1540 msghdr_get_ecn(struct msghdr* msg, int family)
1541 {
1542 #ifndef S_SPLINT_S
1543 	struct cmsghdr* cmsg;
1544 	if(family == AF_INET6) {
1545 		for(cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL;
1546 			cmsg = CMSG_NXTHDR(msg, cmsg)) {
1547 			if(cmsg->cmsg_level == IPPROTO_IPV6 &&
1548 				cmsg->cmsg_type == IPV6_TCLASS &&
1549 				cmsg->cmsg_len != 0) {
1550 				uint8_t* ecn = (uint8_t*)CMSG_DATA(cmsg);
1551 				return *ecn;
1552 			}
1553 		}
1554 		return 0;
1555 	}
1556 	for(cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL;
1557 		cmsg = CMSG_NXTHDR(msg, cmsg)) {
1558 		if(cmsg->cmsg_level == IPPROTO_IP &&
1559 			cmsg->cmsg_type == IP_TOS &&
1560 			cmsg->cmsg_len != 0) {
1561 			uint8_t* ecn = (uint8_t*)CMSG_DATA(cmsg);
1562 			return *ecn;
1563 		}
1564 	}
1565 #endif /* S_SPLINT_S */
1566 	return 0;
1567 }
1568 
1569 /** receive packet for DoQ on UDP. get ancillary data for addresses,
1570  * return false if failed and the callback can stop receiving UDP packets
1571  * if pkt_continue is false. */
1572 static int
1573 doq_recv(struct comm_point* c, struct doq_pkt_addr* paddr, int* pkt_continue,
1574 	struct ngtcp2_pkt_info* pi)
1575 {
1576 	struct msghdr msg;
1577 	struct iovec iov[1];
1578 	ssize_t rcv;
1579 	union {
1580 		struct cmsghdr hdr;
1581 		char buf[256];
1582 	} ancil;
1583 
1584 	msg.msg_name = &paddr->addr;
1585 	msg.msg_namelen = (socklen_t)sizeof(paddr->addr);
1586 	iov[0].iov_base = sldns_buffer_begin(c->doq_socket->pkt_buf);
1587 	iov[0].iov_len = sldns_buffer_remaining(c->doq_socket->pkt_buf);
1588 	msg.msg_iov = iov;
1589 	msg.msg_iovlen = 1;
1590 	msg.msg_control = ancil.buf;
1591 #ifndef S_SPLINT_S
1592 	msg.msg_controllen = sizeof(ancil.buf);
1593 #endif /* S_SPLINT_S */
1594 	msg.msg_flags = 0;
1595 
1596 	rcv = recvmsg(c->fd, &msg, MSG_DONTWAIT);
1597 	if(rcv == -1) {
1598 		if(errno != EAGAIN && errno != EINTR
1599 			&& udp_recv_needs_log(errno)) {
1600 			log_err("recvmsg failed for doq: %s", strerror(errno));
1601 		}
1602 		*pkt_continue = 0;
1603 		return 0;
1604 	}
1605 
1606 	paddr->addrlen = msg.msg_namelen;
1607 	sldns_buffer_skip(c->doq_socket->pkt_buf, rcv);
1608 	sldns_buffer_flip(c->doq_socket->pkt_buf);
1609 	if(!doq_get_localaddr_cmsg(c, paddr, pkt_continue, &msg))
1610 		return 0;
1611 	pi->ecn = msghdr_get_ecn(&msg, paddr->addr.sockaddr.in.sin_family);
1612 	return 1;
1613 }
1614 
1615 /** send the version negotiation for doq. scid and dcid are flipped around
1616  * to send back to the client. */
1617 static void
1618 doq_send_version_negotiation(struct comm_point* c, struct doq_pkt_addr* paddr,
1619 	const uint8_t* dcid, size_t dcidlen, const uint8_t* scid,
1620 	size_t scidlen)
1621 {
1622 	uint32_t versions[2];
1623 	size_t versions_len = 0;
1624 	ngtcp2_ssize ret;
1625 	uint8_t unused_random;
1626 
1627 	/* fill the array with supported versions */
1628 	versions[0] = NGTCP2_PROTO_VER_V1;
1629 	versions_len = 1;
1630 	unused_random = ub_random_max(c->doq_socket->rnd, 256);
1631 	sldns_buffer_clear(c->doq_socket->pkt_buf);
1632 	ret = ngtcp2_pkt_write_version_negotiation(
1633 		sldns_buffer_begin(c->doq_socket->pkt_buf),
1634 		sldns_buffer_capacity(c->doq_socket->pkt_buf), unused_random,
1635 		dcid, dcidlen, scid, scidlen, versions, versions_len);
1636 	if(ret < 0) {
1637 		log_err("ngtcp2_pkt_write_version_negotiation failed: %s",
1638 			ngtcp2_strerror(ret));
1639 		return;
1640 	}
1641 	sldns_buffer_set_position(c->doq_socket->pkt_buf, ret);
1642 	sldns_buffer_flip(c->doq_socket->pkt_buf);
1643 	doq_send_pkt(c, paddr, 0);
1644 }
1645 
1646 /** Find the doq_conn object by remote address and dcid */
1647 static struct doq_conn*
1648 doq_conn_find(struct doq_table* table, struct doq_addr_storage* addr,
1649 	socklen_t addrlen, struct doq_addr_storage* localaddr,
1650 	socklen_t localaddrlen, int ifindex, const uint8_t* dcid,
1651 	size_t dcidlen)
1652 {
1653 	struct rbnode_type* node;
1654 	struct doq_conn key;
1655 	memset(&key.node, 0, sizeof(key.node));
1656 	key.node.key = &key;
1657 	memmove(&key.key.paddr.addr, addr, addrlen);
1658 	key.key.paddr.addrlen = addrlen;
1659 	memmove(&key.key.paddr.localaddr, localaddr, localaddrlen);
1660 	key.key.paddr.localaddrlen = localaddrlen;
1661 	key.key.paddr.ifindex = ifindex;
1662 	key.key.dcid = (void*)dcid;
1663 	key.key.dcidlen = dcidlen;
1664 	node = rbtree_search(table->conn_tree, &key);
1665 	if(node)
1666 		return (struct doq_conn*)node->key;
1667 	return NULL;
1668 }
1669 
1670 /** find the doq_con by the connection id */
1671 static struct doq_conn*
1672 doq_conn_find_by_id(struct doq_table* table, const uint8_t* dcid,
1673 	size_t dcidlen)
1674 {
1675 	struct doq_conid* conid;
1676 	lock_rw_rdlock(&table->conid_lock);
1677 	conid = doq_conid_find(table, dcid, dcidlen);
1678 	if(conid) {
1679 		/* make a copy of the key */
1680 		struct doq_conn* conn;
1681 		struct doq_conn_key key = conid->key;
1682 		uint8_t cid[NGTCP2_MAX_CIDLEN];
1683 		log_assert(conid->key.dcidlen <= NGTCP2_MAX_CIDLEN);
1684 		memcpy(cid, conid->key.dcid, conid->key.dcidlen);
1685 		key.dcid = cid;
1686 		lock_rw_unlock(&table->conid_lock);
1687 
1688 		/* now that the conid lock is released, look up the conn */
1689 		lock_rw_rdlock(&table->lock);
1690 		conn = doq_conn_find(table, &key.paddr.addr,
1691 			key.paddr.addrlen, &key.paddr.localaddr,
1692 			key.paddr.localaddrlen, key.paddr.ifindex, key.dcid,
1693 			key.dcidlen);
1694 		if(!conn) {
1695 			/* The connection got deleted between the conid lookup
1696 			 * and the connection lock grab, it no longer exists,
1697 			 * so return null. */
1698 			lock_rw_unlock(&table->lock);
1699 			return NULL;
1700 		}
1701 		lock_basic_lock(&conn->lock);
1702 		if(conn->is_deleted) {
1703 			lock_rw_unlock(&table->lock);
1704 			lock_basic_unlock(&conn->lock);
1705 			return NULL;
1706 		}
1707 		lock_rw_unlock(&table->lock);
1708 		return conn;
1709 	}
1710 	lock_rw_unlock(&table->conid_lock);
1711 	return NULL;
1712 }
1713 
1714 /** Find the doq_conn, by addr or by connection id */
1715 static struct doq_conn*
1716 doq_conn_find_by_addr_or_cid(struct doq_table* table,
1717 	struct doq_pkt_addr* paddr, const uint8_t* dcid, size_t dcidlen)
1718 {
1719 	struct doq_conn* conn;
1720 	lock_rw_rdlock(&table->lock);
1721 	conn = doq_conn_find(table, &paddr->addr, paddr->addrlen,
1722 		&paddr->localaddr, paddr->localaddrlen, paddr->ifindex,
1723 		dcid, dcidlen);
1724 	if(conn && conn->is_deleted) {
1725 		conn = NULL;
1726 	}
1727 	if(conn) {
1728 		lock_basic_lock(&conn->lock);
1729 		lock_rw_unlock(&table->lock);
1730 		verbose(VERB_ALGO, "doq: found connection by address, dcid");
1731 	} else {
1732 		lock_rw_unlock(&table->lock);
1733 		conn = doq_conn_find_by_id(table, dcid, dcidlen);
1734 		if(conn) {
1735 			verbose(VERB_ALGO, "doq: found connection by dcid");
1736 		}
1737 	}
1738 	return conn;
1739 }
1740 
1741 /** decode doq packet header, false on handled or failure, true to continue
1742  * to process the packet */
1743 static int
1744 doq_decode_pkt_header_negotiate(struct comm_point* c,
1745 	struct doq_pkt_addr* paddr, struct doq_conn** conn)
1746 {
1747 #ifdef HAVE_STRUCT_NGTCP2_VERSION_CID
1748 	struct ngtcp2_version_cid vc;
1749 #else
1750 	uint32_t version;
1751 	const uint8_t *dcid, *scid;
1752 	size_t dcidlen, scidlen;
1753 #endif
1754 	int rv;
1755 
1756 #ifdef HAVE_STRUCT_NGTCP2_VERSION_CID
1757 	rv = ngtcp2_pkt_decode_version_cid(&vc,
1758 		sldns_buffer_begin(c->doq_socket->pkt_buf),
1759 		sldns_buffer_limit(c->doq_socket->pkt_buf),
1760 		c->doq_socket->sv_scidlen);
1761 #else
1762 	rv = ngtcp2_pkt_decode_version_cid(&version, &dcid, &dcidlen,
1763 		&scid, &scidlen, sldns_buffer_begin(c->doq_socket->pkt_buf),
1764 		sldns_buffer_limit(c->doq_socket->pkt_buf), c->doq_socket->sv_scidlen);
1765 #endif
1766 	if(rv != 0) {
1767 		if(rv == NGTCP2_ERR_VERSION_NEGOTIATION) {
1768 			/* send the version negotiation */
1769 			doq_send_version_negotiation(c, paddr,
1770 #ifdef HAVE_STRUCT_NGTCP2_VERSION_CID
1771 			vc.scid, vc.scidlen, vc.dcid, vc.dcidlen
1772 #else
1773 			scid, scidlen, dcid, dcidlen
1774 #endif
1775 			);
1776 			return 0;
1777 		}
1778 		verbose(VERB_ALGO, "doq: could not decode version "
1779 			"and CID from QUIC packet header: %s",
1780 			ngtcp2_strerror(rv));
1781 		return 0;
1782 	}
1783 
1784 	if(verbosity >= VERB_ALGO) {
1785 		verbose(VERB_ALGO, "ngtcp2_pkt_decode_version_cid packet has "
1786 			"QUIC protocol version %u", (unsigned)
1787 #ifdef HAVE_STRUCT_NGTCP2_VERSION_CID
1788 			vc.
1789 #endif
1790 			version
1791 			);
1792 		log_hex("dcid",
1793 #ifdef HAVE_STRUCT_NGTCP2_VERSION_CID
1794 			(void*)vc.dcid, vc.dcidlen
1795 #else
1796 			(void*)dcid, dcidlen
1797 #endif
1798 			);
1799 		log_hex("scid",
1800 #ifdef HAVE_STRUCT_NGTCP2_VERSION_CID
1801 			(void*)vc.scid, vc.scidlen
1802 #else
1803 			(void*)scid, scidlen
1804 #endif
1805 			);
1806 	}
1807 	*conn = doq_conn_find_by_addr_or_cid(c->doq_socket->table, paddr,
1808 #ifdef HAVE_STRUCT_NGTCP2_VERSION_CID
1809 		vc.dcid, vc.dcidlen
1810 #else
1811 		dcid, dcidlen
1812 #endif
1813 		);
1814 	if(*conn)
1815 		(*conn)->doq_socket = c->doq_socket;
1816 	return 1;
1817 }
1818 
1819 /** fill cid structure with random data */
1820 static void doq_cid_randfill(struct ngtcp2_cid* cid, size_t datalen,
1821 	struct ub_randstate* rnd)
1822 {
1823 	uint8_t buf[32];
1824 	if(datalen > sizeof(buf))
1825 		datalen = sizeof(buf);
1826 	doq_fill_rand(rnd, buf, datalen);
1827 	ngtcp2_cid_init(cid, buf, datalen);
1828 }
1829 
1830 /** send retry packet for doq connection. */
1831 static void
1832 doq_send_retry(struct comm_point* c, struct doq_pkt_addr* paddr,
1833 	struct ngtcp2_pkt_hd* hd)
1834 {
1835 	char host[256], port[32];
1836 	struct ngtcp2_cid scid;
1837 	uint8_t token[NGTCP2_CRYPTO_MAX_RETRY_TOKENLEN];
1838 	ngtcp2_ssize tokenlen, ret;
1839 
1840 	if(!doq_print_addr_port(&paddr->addr, paddr->addrlen, host,
1841 		sizeof(host), port, sizeof(port))) {
1842 		log_err("doq_send_retry failed");
1843 		return;
1844 	}
1845 	verbose(VERB_ALGO, "doq: sending retry packet to %s %s", host, port);
1846 
1847 	/* the server chosen source connection ID */
1848 	scid.datalen = c->doq_socket->sv_scidlen;
1849 	doq_cid_randfill(&scid, scid.datalen, c->doq_socket->rnd);
1850 
1851 	tokenlen = ngtcp2_crypto_generate_retry_token(token,
1852 		c->doq_socket->static_secret, c->doq_socket->static_secret_len,
1853 		hd->version, (void*)&paddr->addr, paddr->addrlen, &scid,
1854 		&hd->dcid, doq_get_timestamp_nanosec());
1855 	if(tokenlen < 0) {
1856 		log_err("ngtcp2_crypto_generate_retry_token failed: %s",
1857 			ngtcp2_strerror(tokenlen));
1858 		return;
1859 	}
1860 
1861 	sldns_buffer_clear(c->doq_socket->pkt_buf);
1862 	ret = ngtcp2_crypto_write_retry(sldns_buffer_begin(c->doq_socket->pkt_buf),
1863 		sldns_buffer_capacity(c->doq_socket->pkt_buf), hd->version,
1864 		&hd->scid, &scid, &hd->dcid, token, tokenlen);
1865 	if(ret < 0) {
1866 		log_err("ngtcp2_crypto_write_retry failed: %s",
1867 			ngtcp2_strerror(ret));
1868 		return;
1869 	}
1870 	sldns_buffer_set_position(c->doq_socket->pkt_buf, ret);
1871 	sldns_buffer_flip(c->doq_socket->pkt_buf);
1872 	doq_send_pkt(c, paddr, 0);
1873 }
1874 
1875 /** doq send stateless connection close */
1876 static void
1877 doq_send_stateless_connection_close(struct comm_point* c,
1878 	struct doq_pkt_addr* paddr, struct ngtcp2_pkt_hd* hd,
1879 	uint64_t error_code)
1880 {
1881 	ngtcp2_ssize ret;
1882 	sldns_buffer_clear(c->doq_socket->pkt_buf);
1883 	ret = ngtcp2_crypto_write_connection_close(
1884 		sldns_buffer_begin(c->doq_socket->pkt_buf),
1885 		sldns_buffer_capacity(c->doq_socket->pkt_buf), hd->version, &hd->scid,
1886 		&hd->dcid, error_code, NULL, 0);
1887 	if(ret < 0) {
1888 		log_err("ngtcp2_crypto_write_connection_close failed: %s",
1889 			ngtcp2_strerror(ret));
1890 		return;
1891 	}
1892 	sldns_buffer_set_position(c->doq_socket->pkt_buf, ret);
1893 	sldns_buffer_flip(c->doq_socket->pkt_buf);
1894 	doq_send_pkt(c, paddr, 0);
1895 }
1896 
1897 /** doq verify retry token, false on failure */
1898 static int
1899 doq_verify_retry_token(struct comm_point* c, struct doq_pkt_addr* paddr,
1900 	struct ngtcp2_cid* ocid, struct ngtcp2_pkt_hd* hd)
1901 {
1902 	char host[256], port[32];
1903 	if(!doq_print_addr_port(&paddr->addr, paddr->addrlen, host,
1904 		sizeof(host), port, sizeof(port))) {
1905 		log_err("doq_verify_retry_token failed");
1906 		return 0;
1907 	}
1908 	verbose(VERB_ALGO, "doq: verifying retry token from %s %s", host,
1909 		port);
1910 	if(ngtcp2_crypto_verify_retry_token(ocid,
1911 #ifdef HAVE_STRUCT_NGTCP2_PKT_HD_TOKENLEN
1912 		hd->token, hd->tokenlen,
1913 #else
1914 		hd->token.base, hd->token.len,
1915 #endif
1916 		c->doq_socket->static_secret,
1917 		c->doq_socket->static_secret_len, hd->version,
1918 		(void*)&paddr->addr, paddr->addrlen, &hd->dcid,
1919 		10*NGTCP2_SECONDS, doq_get_timestamp_nanosec()) != 0) {
1920 		verbose(VERB_ALGO, "doq: could not verify retry token "
1921 			"from %s %s", host, port);
1922 		return 0;
1923 	}
1924 	verbose(VERB_ALGO, "doq: verified retry token from %s %s", host, port);
1925 	return 1;
1926 }
1927 
1928 /** doq verify token, false on failure */
1929 static int
1930 doq_verify_token(struct comm_point* c, struct doq_pkt_addr* paddr,
1931 	struct ngtcp2_pkt_hd* hd)
1932 {
1933 	char host[256], port[32];
1934 	if(!doq_print_addr_port(&paddr->addr, paddr->addrlen, host,
1935 		sizeof(host), port, sizeof(port))) {
1936 		log_err("doq_verify_token failed");
1937 		return 0;
1938 	}
1939 	verbose(VERB_ALGO, "doq: verifying token from %s %s", host, port);
1940 	if(ngtcp2_crypto_verify_regular_token(
1941 #ifdef HAVE_STRUCT_NGTCP2_PKT_HD_TOKENLEN
1942 		hd->token, hd->tokenlen,
1943 #else
1944 		hd->token.base, hd->token.len,
1945 #endif
1946 		c->doq_socket->static_secret, c->doq_socket->static_secret_len,
1947 		(void*)&paddr->addr, paddr->addrlen, 3600*NGTCP2_SECONDS,
1948 		doq_get_timestamp_nanosec()) != 0) {
1949 		verbose(VERB_ALGO, "doq: could not verify token from %s %s",
1950 			host, port);
1951 		return 0;
1952 	}
1953 	verbose(VERB_ALGO, "doq: verified token from %s %s", host, port);
1954 	return 1;
1955 }
1956 
1957 /** delete and remove from the lookup tree the doq_conn connection */
1958 static void
1959 doq_delete_connection(struct comm_point* c, struct doq_conn* conn)
1960 {
1961 	struct doq_conn copy;
1962 	uint8_t cid[NGTCP2_MAX_CIDLEN];
1963 	rbnode_type* node;
1964 	if(!conn)
1965 		return;
1966 	/* Copy the key and set it deleted. */
1967 	conn->is_deleted = 1;
1968 	doq_conn_write_disable(conn);
1969 	copy.key = conn->key;
1970 	log_assert(conn->key.dcidlen <= NGTCP2_MAX_CIDLEN);
1971 	memcpy(cid, conn->key.dcid, conn->key.dcidlen);
1972 	copy.key.dcid = cid;
1973 	copy.node.key = &copy;
1974 	lock_basic_unlock(&conn->lock);
1975 
1976 	/* Now get the table lock to delete it from the tree */
1977 	lock_rw_wrlock(&c->doq_socket->table->lock);
1978 	node = rbtree_delete(c->doq_socket->table->conn_tree, copy.node.key);
1979 	if(node) {
1980 		conn = (struct doq_conn*)node->key;
1981 		lock_basic_lock(&conn->lock);
1982 		doq_conn_write_list_remove(c->doq_socket->table, conn);
1983 		if(conn->timer.timer_in_list) {
1984 			/* Remove timer from list first, because finding the
1985 			 * rbnode element of the setlist of same timeouts
1986 			 * needs tree lookup. Edit the tree structure after
1987 			 * that lookup. */
1988 			doq_timer_list_remove(c->doq_socket->table,
1989 				&conn->timer);
1990 		}
1991 		if(conn->timer.timer_in_tree)
1992 			doq_timer_tree_remove(c->doq_socket->table,
1993 				&conn->timer);
1994 	}
1995 	lock_rw_unlock(&c->doq_socket->table->lock);
1996 	if(node) {
1997 		lock_basic_unlock(&conn->lock);
1998 		doq_table_quic_size_subtract(c->doq_socket->table,
1999 			sizeof(*conn)+conn->key.dcidlen);
2000 		doq_conn_delete(conn, c->doq_socket->table);
2001 	}
2002 }
2003 
2004 /** create and setup a new doq connection, to a new destination, or with
2005  * a new dcid. It has a new set of streams. It is inserted in the lookup tree.
2006  * Returns NULL on failure. */
2007 static struct doq_conn*
2008 doq_setup_new_conn(struct comm_point* c, struct doq_pkt_addr* paddr,
2009 	struct ngtcp2_pkt_hd* hd, struct ngtcp2_cid* ocid)
2010 {
2011 	struct doq_conn* conn;
2012 	if(!doq_table_quic_size_available(c->doq_socket->table,
2013 		c->doq_socket->cfg, sizeof(*conn)+hd->dcid.datalen
2014 		+ sizeof(struct doq_stream)
2015 		+ 100 /* estimated input query */
2016 		+ 1200 /* estimated output query */)) {
2017 		verbose(VERB_ALGO, "doq: no mem available for new connection");
2018 		doq_send_stateless_connection_close(c, paddr, hd,
2019 			NGTCP2_CONNECTION_REFUSED);
2020 		return NULL;
2021 	}
2022 	conn = doq_conn_create(c, paddr, hd->dcid.data, hd->dcid.datalen,
2023 		hd->version);
2024 	if(!conn) {
2025 		log_err("doq: could not allocate doq_conn");
2026 		return NULL;
2027 	}
2028 	lock_rw_wrlock(&c->doq_socket->table->lock);
2029 	lock_basic_lock(&conn->lock);
2030 	if(!rbtree_insert(c->doq_socket->table->conn_tree, &conn->node)) {
2031 		lock_rw_unlock(&c->doq_socket->table->lock);
2032 		log_err("doq: duplicate connection");
2033 		/* conn has no entry in writelist, and no timer yet. */
2034 		lock_basic_unlock(&conn->lock);
2035 		doq_conn_delete(conn, c->doq_socket->table);
2036 		return NULL;
2037 	}
2038 	lock_rw_unlock(&c->doq_socket->table->lock);
2039 	doq_table_quic_size_add(c->doq_socket->table,
2040 		sizeof(*conn)+conn->key.dcidlen);
2041 	verbose(VERB_ALGO, "doq: created new connection");
2042 
2043 	/* the scid and dcid switch meaning from the accepted client
2044 	 * connection to the server connection. The 'source' and 'destination'
2045 	 * meaning is reversed. */
2046 	if(!doq_conn_setup(conn, hd->scid.data, hd->scid.datalen,
2047 		(ocid?ocid->data:NULL), (ocid?ocid->datalen:0),
2048 #ifdef HAVE_STRUCT_NGTCP2_PKT_HD_TOKENLEN
2049 		hd->token, hd->tokenlen
2050 #else
2051 		hd->token.base, hd->token.len
2052 #endif
2053 		)) {
2054 		log_err("doq: could not set up connection");
2055 		doq_delete_connection(c, conn);
2056 		return NULL;
2057 	}
2058 	return conn;
2059 }
2060 
2061 /** perform doq address validation */
2062 static int
2063 doq_address_validation(struct comm_point* c, struct doq_pkt_addr* paddr,
2064 	struct ngtcp2_pkt_hd* hd, struct ngtcp2_cid* ocid,
2065 	struct ngtcp2_cid** pocid)
2066 {
2067 #ifdef HAVE_STRUCT_NGTCP2_PKT_HD_TOKENLEN
2068 	const uint8_t* token = hd->token;
2069 	size_t tokenlen = hd->tokenlen;
2070 #else
2071 	const uint8_t* token = hd->token.base;
2072 	size_t tokenlen = hd->token.len;
2073 #endif
2074 	verbose(VERB_ALGO, "doq stateless address validation");
2075 
2076 	if(tokenlen == 0 || token == NULL) {
2077 		doq_send_retry(c, paddr, hd);
2078 		return 0;
2079 	}
2080 	if(token[0] != NGTCP2_CRYPTO_TOKEN_MAGIC_RETRY &&
2081 		hd->dcid.datalen < NGTCP2_MIN_INITIAL_DCIDLEN) {
2082 		doq_send_stateless_connection_close(c, paddr, hd,
2083 			NGTCP2_INVALID_TOKEN);
2084 		return 0;
2085 	}
2086 	if(token[0] == NGTCP2_CRYPTO_TOKEN_MAGIC_RETRY) {
2087 		if(!doq_verify_retry_token(c, paddr, ocid, hd)) {
2088 			doq_send_stateless_connection_close(c, paddr, hd,
2089 				NGTCP2_INVALID_TOKEN);
2090 			return 0;
2091 		}
2092 		*pocid = ocid;
2093 	} else if(token[0] == NGTCP2_CRYPTO_TOKEN_MAGIC_REGULAR) {
2094 		if(!doq_verify_token(c, paddr, hd)) {
2095 			doq_send_retry(c, paddr, hd);
2096 			return 0;
2097 		}
2098 #ifdef HAVE_STRUCT_NGTCP2_PKT_HD_TOKENLEN
2099 		hd->token = NULL;
2100 		hd->tokenlen = 0;
2101 #else
2102 		hd->token.base = NULL;
2103 		hd->token.len = 0;
2104 #endif
2105 	} else {
2106 		verbose(VERB_ALGO, "doq address validation: unrecognised "
2107 			"token in hd.token.base with magic byte 0x%2.2x",
2108 			(int)token[0]);
2109 		if(c->doq_socket->validate_addr) {
2110 			doq_send_retry(c, paddr, hd);
2111 			return 0;
2112 		}
2113 #ifdef HAVE_STRUCT_NGTCP2_PKT_HD_TOKENLEN
2114 		hd->token = NULL;
2115 		hd->tokenlen = 0;
2116 #else
2117 		hd->token.base = NULL;
2118 		hd->token.len = 0;
2119 #endif
2120 	}
2121 	return 1;
2122 }
2123 
2124 /** the doq accept, returns false if no further processing of content */
2125 static int
2126 doq_accept(struct comm_point* c, struct doq_pkt_addr* paddr,
2127 	struct doq_conn** conn, struct ngtcp2_pkt_info* pi)
2128 {
2129 	int rv;
2130 	struct ngtcp2_pkt_hd hd;
2131 	struct ngtcp2_cid ocid, *pocid=NULL;
2132 	int err_retry;
2133 	memset(&hd, 0, sizeof(hd));
2134 	rv = ngtcp2_accept(&hd, sldns_buffer_begin(c->doq_socket->pkt_buf),
2135 		sldns_buffer_limit(c->doq_socket->pkt_buf));
2136 	if(rv != 0) {
2137 		if(rv == NGTCP2_ERR_RETRY) {
2138 			doq_send_retry(c, paddr, &hd);
2139 			return 0;
2140 		}
2141 		log_err("doq: initial packet failed, ngtcp2_accept failed: %s",
2142 			ngtcp2_strerror(rv));
2143 		return 0;
2144 	}
2145 	if(c->doq_socket->validate_addr ||
2146 #ifdef HAVE_STRUCT_NGTCP2_PKT_HD_TOKENLEN
2147 		hd.tokenlen
2148 #else
2149 		hd.token.len
2150 #endif
2151 		) {
2152 		if(!doq_address_validation(c, paddr, &hd, &ocid, &pocid))
2153 			return 0;
2154 	}
2155 	*conn = doq_setup_new_conn(c, paddr, &hd, pocid);
2156 	if(!*conn)
2157 		return 0;
2158 	(*conn)->doq_socket = c->doq_socket;
2159 	if(!doq_conn_recv(c, paddr, *conn, pi, &err_retry, NULL)) {
2160 		if(err_retry)
2161 			doq_send_retry(c, paddr, &hd);
2162 		doq_delete_connection(c, *conn);
2163 		*conn = NULL;
2164 		return 0;
2165 	}
2166 	return 1;
2167 }
2168 
2169 /** doq pickup a timer to wait for for the worker. If any timer exists. */
2170 static void
2171 doq_pickup_timer(struct comm_point* c)
2172 {
2173 	struct doq_timer* t;
2174 	struct timeval tv;
2175 	ngtcp2_tstamp ts = 0;
2176 	int have_time = 0;
2177 	memset(&tv, 0, sizeof(tv));
2178 
2179 	lock_rw_wrlock(&c->doq_socket->table->lock);
2180 	RBTREE_FOR(t, struct doq_timer*, c->doq_socket->table->timer_tree) {
2181 		if(t->worker_doq_socket == NULL ||
2182 			t->worker_doq_socket == c->doq_socket) {
2183 			/* pick up this element */
2184 			t->worker_doq_socket = c->doq_socket;
2185 			memcpy(&tv, &t->time_real, sizeof(tv));
2186 			ts = t->time_mono;
2187 			have_time = 1;
2188 			break;
2189 		}
2190 	}
2191 	lock_rw_unlock(&c->doq_socket->table->lock);
2192 	c->doq_socket->marked_time = ts;
2193 	if(have_time) {
2194 		struct timeval rel;
2195 		timeval_subtract(&rel, &tv, c->doq_socket->now_tv);
2196 		comm_timer_set(c->doq_socket->timer, &rel);
2197 		verbose(VERB_ALGO, "doq pickup timer at %d.%6.6d in %d.%6.6d",
2198 			(int)tv.tv_sec, (int)tv.tv_usec, (int)rel.tv_sec,
2199 			(int)rel.tv_usec);
2200 	} else {
2201 		if(comm_timer_is_set(c->doq_socket->timer))
2202 			comm_timer_disable(c->doq_socket->timer);
2203 		verbose(VERB_ALGO, "doq timer disabled");
2204 	}
2205 }
2206 
2207 /** doq done with connection, release locks and setup timer and write */
2208 static void
2209 doq_done_setup_timer_and_write(struct comm_point* c, struct doq_conn* conn)
2210 {
2211 	struct doq_conn copy;
2212 	uint8_t cid[NGTCP2_MAX_CIDLEN];
2213 	rbnode_type* node;
2214 	struct timeval new_tv;
2215 	ngtcp2_tstamp new_ts;
2216 	int write_change = 0, timer_change = 0;
2217 
2218 	/* No longer in callbacks, so the pointer to doq_socket is back
2219 	 * to NULL. */
2220 	conn->doq_socket = NULL;
2221 
2222 	if(doq_conn_check_timer(conn, &new_tv, &new_ts))
2223 		timer_change = 1;
2224 	if( (conn->write_interest && !conn->on_write_list) ||
2225 		(!conn->write_interest && conn->on_write_list))
2226 		write_change = 1;
2227 
2228 	if(!timer_change && !write_change) {
2229 		/* Nothing to do. */
2230 		lock_basic_unlock(&conn->lock);
2231 		return;
2232 	}
2233 
2234 	/* The table lock is needed to change the write list and timer tree.
2235 	 * So the connection lock is release and then the connection is
2236 	 * looked up again. */
2237 	copy.key = conn->key;
2238 	log_assert(conn->key.dcidlen <= NGTCP2_MAX_CIDLEN);
2239 	memcpy(cid, conn->key.dcid, conn->key.dcidlen);
2240 	copy.key.dcid = cid;
2241 	copy.node.key = &copy;
2242 	lock_basic_unlock(&conn->lock);
2243 
2244 	lock_rw_wrlock(&c->doq_socket->table->lock);
2245 	node = rbtree_search(c->doq_socket->table->conn_tree, copy.node.key);
2246 	if(!node) {
2247 		lock_rw_unlock(&c->doq_socket->table->lock);
2248 		/* Must have been deleted in the mean time. */
2249 		return;
2250 	}
2251 	conn = (struct doq_conn*)node->key;
2252 	lock_basic_lock(&conn->lock);
2253 	if(conn->is_deleted) {
2254 		/* It is deleted now. */
2255 		lock_rw_unlock(&c->doq_socket->table->lock);
2256 		lock_basic_unlock(&conn->lock);
2257 		return;
2258 	}
2259 
2260 	if(write_change) {
2261 		/* Edit the write lists, we are holding the table.lock and can
2262 		 * edit the list first,last and also prev,next and on_list
2263 		 * elements in the doq_conn structures. */
2264 		doq_conn_set_write_list(c->doq_socket->table, conn);
2265 	}
2266 	if(timer_change) {
2267 		doq_timer_set(c->doq_socket->table, &conn->timer,
2268 			c->doq_socket, &new_tv, new_ts);
2269 	}
2270 	lock_rw_unlock(&c->doq_socket->table->lock);
2271 	lock_basic_unlock(&conn->lock);
2272 }
2273 
2274 /** doq done with connection callbacks, release locks and setup write */
2275 static void
2276 doq_done_with_conn_cb(struct comm_point* c, struct doq_conn* conn)
2277 {
2278 	struct doq_conn copy;
2279 	uint8_t cid[NGTCP2_MAX_CIDLEN];
2280 	rbnode_type* node;
2281 
2282 	/* no longer in callbacks, so the pointer to doq_socket is back
2283 	 * to NULL. */
2284 	conn->doq_socket = NULL;
2285 
2286 	if( (conn->write_interest && conn->on_write_list) ||
2287 		(!conn->write_interest && !conn->on_write_list)) {
2288 		/* The connection already has the required write list
2289 		 * status. */
2290 		lock_basic_unlock(&conn->lock);
2291 		return;
2292 	}
2293 
2294 	/* To edit the write list of connections we have to hold the table
2295 	 * lock, so we release the connection and then look it up again. */
2296 	copy.key = conn->key;
2297 	log_assert(conn->key.dcidlen <= NGTCP2_MAX_CIDLEN);
2298 	memcpy(cid, conn->key.dcid, conn->key.dcidlen);
2299 	copy.key.dcid = cid;
2300 	copy.node.key = &copy;
2301 	lock_basic_unlock(&conn->lock);
2302 
2303 	lock_rw_wrlock(&c->doq_socket->table->lock);
2304 	node = rbtree_search(c->doq_socket->table->conn_tree, copy.node.key);
2305 	if(!node) {
2306 		lock_rw_unlock(&c->doq_socket->table->lock);
2307 		/* must have been deleted in the mean time */
2308 		return;
2309 	}
2310 	conn = (struct doq_conn*)node->key;
2311 	lock_basic_lock(&conn->lock);
2312 	if(conn->is_deleted) {
2313 		/* it is deleted now. */
2314 		lock_rw_unlock(&c->doq_socket->table->lock);
2315 		lock_basic_unlock(&conn->lock);
2316 		return;
2317 	}
2318 
2319 	/* edit the write lists, we are holding the table.lock and can
2320 	 * edit the list first,last and also prev,next and on_list elements
2321 	 * in the doq_conn structures. */
2322 	doq_conn_set_write_list(c->doq_socket->table, conn);
2323 	lock_rw_unlock(&c->doq_socket->table->lock);
2324 	lock_basic_unlock(&conn->lock);
2325 }
2326 
2327 /** doq count the length of the write list */
2328 static size_t
2329 doq_write_list_length(struct comm_point* c)
2330 {
2331 	size_t count = 0;
2332 	struct doq_conn* conn;
2333 	lock_rw_rdlock(&c->doq_socket->table->lock);
2334 	conn = c->doq_socket->table->write_list_first;
2335 	while(conn) {
2336 		count++;
2337 		conn = conn->write_next;
2338 	}
2339 	lock_rw_unlock(&c->doq_socket->table->lock);
2340 	return count;
2341 }
2342 
2343 /** doq pop the first element from the write list to have write events */
2344 static struct doq_conn*
2345 doq_pop_write_conn(struct comm_point* c)
2346 {
2347 	struct doq_conn* conn;
2348 	lock_rw_wrlock(&c->doq_socket->table->lock);
2349 	conn = doq_table_pop_first(c->doq_socket->table);
2350 	while(conn && conn->is_deleted) {
2351 		lock_basic_unlock(&conn->lock);
2352 		conn = doq_table_pop_first(c->doq_socket->table);
2353 	}
2354 	lock_rw_unlock(&c->doq_socket->table->lock);
2355 	if(conn)
2356 		conn->doq_socket = c->doq_socket;
2357 	return conn;
2358 }
2359 
2360 /** doq the connection is done with write callbacks, release it. */
2361 static void
2362 doq_done_with_write_cb(struct comm_point* c, struct doq_conn* conn,
2363 	int delete_it)
2364 {
2365 	if(delete_it) {
2366 		doq_delete_connection(c, conn);
2367 		return;
2368 	}
2369 	doq_done_setup_timer_and_write(c, conn);
2370 }
2371 
2372 /** see if the doq socket wants to write packets */
2373 static int
2374 doq_socket_want_write(struct comm_point* c)
2375 {
2376 	int want_write = 0;
2377 	if(c->doq_socket->have_blocked_pkt)
2378 		return 1;
2379 	lock_rw_rdlock(&c->doq_socket->table->lock);
2380 	if(c->doq_socket->table->write_list_first)
2381 		want_write = 1;
2382 	lock_rw_unlock(&c->doq_socket->table->lock);
2383 	return want_write;
2384 }
2385 
2386 /** enable write event for the doq server socket fd */
2387 static void
2388 doq_socket_write_enable(struct comm_point* c)
2389 {
2390 	verbose(VERB_ALGO, "doq socket want write");
2391 	if(c->doq_socket->event_has_write)
2392 		return;
2393 	comm_point_listen_for_rw(c, 1, 1);
2394 	c->doq_socket->event_has_write = 1;
2395 }
2396 
2397 /** disable write event for the doq server socket fd */
2398 static void
2399 doq_socket_write_disable(struct comm_point* c)
2400 {
2401 	verbose(VERB_ALGO, "doq socket want no write");
2402 	if(!c->doq_socket->event_has_write)
2403 		return;
2404 	comm_point_listen_for_rw(c, 1, 0);
2405 	c->doq_socket->event_has_write = 0;
2406 }
2407 
2408 /** write blocked packet, if possible. returns false if failed, again. */
2409 static int
2410 doq_write_blocked_pkt(struct comm_point* c)
2411 {
2412 	struct doq_pkt_addr paddr;
2413 	if(!c->doq_socket->have_blocked_pkt)
2414 		return 1;
2415 	c->doq_socket->have_blocked_pkt = 0;
2416 	if(sldns_buffer_limit(c->doq_socket->blocked_pkt) >
2417 		sldns_buffer_remaining(c->doq_socket->pkt_buf))
2418 		return 1; /* impossibly large, drop it.
2419 		impossible since pkt_buf is same size as blocked_pkt buf. */
2420 	sldns_buffer_clear(c->doq_socket->pkt_buf);
2421 	sldns_buffer_write(c->doq_socket->pkt_buf,
2422 		sldns_buffer_begin(c->doq_socket->blocked_pkt),
2423 		sldns_buffer_limit(c->doq_socket->blocked_pkt));
2424 	sldns_buffer_flip(c->doq_socket->pkt_buf);
2425 	memcpy(&paddr, c->doq_socket->blocked_paddr, sizeof(paddr));
2426 	doq_send_pkt(c, &paddr, c->doq_socket->blocked_pkt_pi.ecn);
2427 	if(c->doq_socket->have_blocked_pkt)
2428 		return 0;
2429 	return 1;
2430 }
2431 
2432 /** doq find a timer that timed out and return the conn, locked. */
2433 static struct doq_conn*
2434 doq_timer_timeout_conn(struct doq_server_socket* doq_socket)
2435 {
2436 	struct doq_conn* conn = NULL;
2437 	struct rbnode_type* node;
2438 	lock_rw_wrlock(&doq_socket->table->lock);
2439 	node = rbtree_first(doq_socket->table->timer_tree);
2440 	if(node && node != RBTREE_NULL) {
2441 		struct doq_timer* t = (struct doq_timer*)node;
2442 		conn = t->conn;
2443 
2444 		/* If now < timer then no further timeouts in tree. */
2445 		if(timeval_smaller(doq_socket->now_tv, &t->time_real)) {
2446 			lock_rw_unlock(&doq_socket->table->lock);
2447 			return NULL;
2448 		}
2449 
2450 		lock_basic_lock(&conn->lock);
2451 		conn->doq_socket = doq_socket;
2452 
2453 		/* Now that the timer is fired, remove it. */
2454 		doq_timer_unset(doq_socket->table, t);
2455 		lock_rw_unlock(&doq_socket->table->lock);
2456 		return conn;
2457 	}
2458 	lock_rw_unlock(&doq_socket->table->lock);
2459 	return NULL;
2460 }
2461 
2462 /** doq timer erase the marker that said which timer the worker uses. */
2463 static void
2464 doq_timer_erase_marker(struct doq_server_socket* doq_socket)
2465 {
2466 	struct doq_timer* t;
2467 	lock_rw_wrlock(&doq_socket->table->lock);
2468 	t = doq_timer_find_time(doq_socket->table, doq_socket->marked_time);
2469 	if(t && t->worker_doq_socket == doq_socket)
2470 		t->worker_doq_socket = NULL;
2471 	lock_rw_unlock(&doq_socket->table->lock);
2472 	doq_socket->marked_time = 0;
2473 }
2474 
2475 void
2476 doq_timer_cb(void* arg)
2477 {
2478 	struct doq_server_socket* doq_socket = (struct doq_server_socket*)arg;
2479 	struct doq_conn* conn;
2480 	verbose(VERB_ALGO, "doq timer callback");
2481 
2482 	doq_timer_erase_marker(doq_socket);
2483 
2484 	while((conn = doq_timer_timeout_conn(doq_socket)) != NULL) {
2485 		if(conn->is_deleted ||
2486 #ifdef HAVE_NGTCP2_CONN_IN_CLOSING_PERIOD
2487 			ngtcp2_conn_in_closing_period(conn->conn) ||
2488 #else
2489 			ngtcp2_conn_is_in_closing_period(conn->conn) ||
2490 #endif
2491 #ifdef HAVE_NGTCP2_CONN_IN_DRAINING_PERIOD
2492 			ngtcp2_conn_in_draining_period(conn->conn)
2493 #else
2494 			ngtcp2_conn_is_in_draining_period(conn->conn)
2495 #endif
2496 			) {
2497 			if(verbosity >= VERB_ALGO) {
2498 				char remotestr[256];
2499 				addr_to_str((void*)&conn->key.paddr.addr,
2500 					conn->key.paddr.addrlen, remotestr,
2501 					sizeof(remotestr));
2502 				verbose(VERB_ALGO, "doq conn %s is deleted "
2503 					"after timeout", remotestr);
2504 			}
2505 			doq_delete_connection(doq_socket->cp, conn);
2506 			continue;
2507 		}
2508 		if(!doq_conn_handle_timeout(conn))
2509 			doq_delete_connection(doq_socket->cp, conn);
2510 		else doq_done_setup_timer_and_write(doq_socket->cp, conn);
2511 	}
2512 
2513 	if(doq_socket_want_write(doq_socket->cp))
2514 		doq_socket_write_enable(doq_socket->cp);
2515 	else doq_socket_write_disable(doq_socket->cp);
2516 	doq_pickup_timer(doq_socket->cp);
2517 }
2518 
2519 void
2520 comm_point_doq_callback(int fd, short event, void* arg)
2521 {
2522 	struct comm_point* c;
2523 	struct doq_pkt_addr paddr;
2524 	int i, pkt_continue, err_drop;
2525 	struct doq_conn* conn;
2526 	struct ngtcp2_pkt_info pi;
2527 	size_t count, num_len;
2528 
2529 	c = (struct comm_point*)arg;
2530 	log_assert(c->type == comm_doq);
2531 
2532 	log_assert(c && c->doq_socket->pkt_buf && c->fd == fd);
2533 	ub_comm_base_now(c->ev->base);
2534 
2535 	/* see if there is a blocked packet, and send that if possible.
2536 	 * do not attempt to read yet, even if possible, that would just
2537 	 * push more answers in reply to those read packets onto the list
2538 	 * of written replies. First attempt to clear the write content out.
2539 	 * That keeps the memory usage from bloating up. */
2540 	if(c->doq_socket->have_blocked_pkt) {
2541 		if(!doq_write_blocked_pkt(c)) {
2542 			/* this write has also blocked, attempt to write
2543 			 * later. Make sure the event listens to write
2544 			 * events. */
2545 			if(!c->doq_socket->event_has_write)
2546 				doq_socket_write_enable(c);
2547 			doq_pickup_timer(c);
2548 			return;
2549 		}
2550 	}
2551 
2552 	/* see if there is write interest */
2553 	count = 0;
2554 	num_len = doq_write_list_length(c);
2555 	while((conn = doq_pop_write_conn(c)) != NULL) {
2556 		if(conn->is_deleted ||
2557 #ifdef HAVE_NGTCP2_CONN_IN_CLOSING_PERIOD
2558 			ngtcp2_conn_in_closing_period(conn->conn) ||
2559 #else
2560 			ngtcp2_conn_is_in_closing_period(conn->conn) ||
2561 #endif
2562 #ifdef HAVE_NGTCP2_CONN_IN_DRAINING_PERIOD
2563 			ngtcp2_conn_in_draining_period(conn->conn)
2564 #else
2565 			ngtcp2_conn_is_in_draining_period(conn->conn)
2566 #endif
2567 			) {
2568 			conn->doq_socket = NULL;
2569 			lock_basic_unlock(&conn->lock);
2570 			if(c->doq_socket->have_blocked_pkt) {
2571 				if(!c->doq_socket->event_has_write)
2572 					doq_socket_write_enable(c);
2573 				doq_pickup_timer(c);
2574 				return;
2575 			}
2576 			if(++count > num_len*2)
2577 				break;
2578 			continue;
2579 		}
2580 		if(verbosity >= VERB_ALGO) {
2581 			char remotestr[256];
2582 			addr_to_str((void*)&conn->key.paddr.addr,
2583 				conn->key.paddr.addrlen, remotestr,
2584 				sizeof(remotestr));
2585 			verbose(VERB_ALGO, "doq write connection %s %d",
2586 				remotestr, doq_sockaddr_get_port(
2587 				&conn->key.paddr.addr));
2588 		}
2589 		if(doq_conn_write_streams(c, conn, &err_drop))
2590 			err_drop = 0;
2591 		doq_done_with_write_cb(c, conn, err_drop);
2592 		if(c->doq_socket->have_blocked_pkt) {
2593 			if(!c->doq_socket->event_has_write)
2594 				doq_socket_write_enable(c);
2595 			doq_pickup_timer(c);
2596 			return;
2597 		}
2598 		/* Stop overly long write lists that are created
2599 		 * while we are processing. Do those next time there
2600 		 * is a write callback. Stops long loops, and keeps
2601 		 * fair for other events. */
2602 		if(++count > num_len*2)
2603 			break;
2604 	}
2605 
2606 	/* check for data to read */
2607 	if((event&UB_EV_READ)!=0)
2608 	  for(i=0; i<NUM_UDP_PER_SELECT; i++) {
2609 		/* there may be a blocked write packet and if so, stop
2610 		 * reading because the reply cannot get written. The
2611 		 * blocked packet could be written during the conn_recv
2612 		 * handling of replies, or for a connection close. */
2613 		if(c->doq_socket->have_blocked_pkt) {
2614 			if(!c->doq_socket->event_has_write)
2615 				doq_socket_write_enable(c);
2616 			doq_pickup_timer(c);
2617 			return;
2618 		}
2619 		sldns_buffer_clear(c->doq_socket->pkt_buf);
2620 		doq_pkt_addr_init(&paddr);
2621 		log_assert(fd != -1);
2622 		log_assert(sldns_buffer_remaining(c->doq_socket->pkt_buf) > 0);
2623 		if(!doq_recv(c, &paddr, &pkt_continue, &pi)) {
2624 			if(pkt_continue)
2625 				continue;
2626 			break;
2627 		}
2628 
2629 		/* handle incoming packet from remote addr to localaddr */
2630 		if(verbosity >= VERB_ALGO) {
2631 			char remotestr[256], localstr[256];
2632 			addr_to_str((void*)&paddr.addr, paddr.addrlen,
2633 				remotestr, sizeof(remotestr));
2634 			addr_to_str((void*)&paddr.localaddr,
2635 				paddr.localaddrlen, localstr,
2636 				sizeof(localstr));
2637 			log_info("incoming doq packet from %s port %d on "
2638 				"%s port %d ifindex %d",
2639 				remotestr, doq_sockaddr_get_port(&paddr.addr),
2640 				localstr,
2641 				doq_sockaddr_get_port(&paddr.localaddr),
2642 				paddr.ifindex);
2643 			log_info("doq_recv length %d ecn 0x%x",
2644 				(int)sldns_buffer_limit(c->doq_socket->pkt_buf),
2645 				(int)pi.ecn);
2646 		}
2647 
2648 		if(sldns_buffer_limit(c->doq_socket->pkt_buf) == 0)
2649 			continue;
2650 
2651 		conn = NULL;
2652 		if(!doq_decode_pkt_header_negotiate(c, &paddr, &conn))
2653 			continue;
2654 		if(!conn) {
2655 			if(!doq_accept(c, &paddr, &conn, &pi))
2656 				continue;
2657 			if(!doq_conn_write_streams(c, conn, NULL)) {
2658 				doq_delete_connection(c, conn);
2659 				continue;
2660 			}
2661 			doq_done_setup_timer_and_write(c, conn);
2662 			continue;
2663 		}
2664 		if(
2665 #ifdef HAVE_NGTCP2_CONN_IN_CLOSING_PERIOD
2666 			ngtcp2_conn_in_closing_period(conn->conn)
2667 #else
2668 			ngtcp2_conn_is_in_closing_period(conn->conn)
2669 #endif
2670 			) {
2671 			if(!doq_conn_send_close(c, conn)) {
2672 				doq_delete_connection(c, conn);
2673 			} else {
2674 				doq_done_setup_timer_and_write(c, conn);
2675 			}
2676 			continue;
2677 		}
2678 		if(
2679 #ifdef HAVE_NGTCP2_CONN_IN_DRAINING_PERIOD
2680 			ngtcp2_conn_in_draining_period(conn->conn)
2681 #else
2682 			ngtcp2_conn_is_in_draining_period(conn->conn)
2683 #endif
2684 			) {
2685 			doq_done_setup_timer_and_write(c, conn);
2686 			continue;
2687 		}
2688 		if(!doq_conn_recv(c, &paddr, conn, &pi, NULL, &err_drop)) {
2689 			/* The receive failed, and if it also failed to send
2690 			 * a close, drop the connection. That means it is not
2691 			 * in the closing period. */
2692 			if(err_drop) {
2693 				doq_delete_connection(c, conn);
2694 			} else {
2695 				doq_done_setup_timer_and_write(c, conn);
2696 			}
2697 			continue;
2698 		}
2699 		if(!doq_conn_write_streams(c, conn, &err_drop)) {
2700 			if(err_drop) {
2701 				doq_delete_connection(c, conn);
2702 			} else {
2703 				doq_done_setup_timer_and_write(c, conn);
2704 			}
2705 			continue;
2706 		}
2707 		doq_done_setup_timer_and_write(c, conn);
2708 	}
2709 
2710 	/* see if we want to have more write events */
2711 	verbose(VERB_ALGO, "doq check write enable");
2712 	if(doq_socket_want_write(c))
2713 		doq_socket_write_enable(c);
2714 	else doq_socket_write_disable(c);
2715 	doq_pickup_timer(c);
2716 }
2717 
2718 /** create new doq server socket structure */
2719 static struct doq_server_socket*
2720 doq_server_socket_create(struct doq_table* table, struct ub_randstate* rnd,
2721 	const void* quic_sslctx, struct comm_point* c, struct comm_base* base,
2722 	struct config_file* cfg)
2723 {
2724 	size_t doq_buffer_size = 4096; /* bytes buffer size, for one packet. */
2725 	struct doq_server_socket* doq_socket;
2726 	log_assert(table != NULL);
2727 	doq_socket = calloc(1, sizeof(*doq_socket));
2728 	if(!doq_socket) {
2729 		return NULL;
2730 	}
2731 	doq_socket->table = table;
2732 	doq_socket->rnd = rnd;
2733 	doq_socket->validate_addr = 1;
2734 	/* the doq_socket has its own copy of the static secret, as
2735 	 * well as other config values, so that they do not need table.lock */
2736 	doq_socket->static_secret_len = table->static_secret_len;
2737 	doq_socket->static_secret = memdup(table->static_secret,
2738 		table->static_secret_len);
2739 	if(!doq_socket->static_secret) {
2740 		free(doq_socket);
2741 		return NULL;
2742 	}
2743 	doq_socket->ctx = (SSL_CTX*)quic_sslctx;
2744 	doq_socket->idle_timeout = table->idle_timeout;
2745 	doq_socket->sv_scidlen = table->sv_scidlen;
2746 	doq_socket->cp = c;
2747 	doq_socket->pkt_buf = sldns_buffer_new(doq_buffer_size);
2748 	if(!doq_socket->pkt_buf) {
2749 		free(doq_socket->static_secret);
2750 		free(doq_socket);
2751 		return NULL;
2752 	}
2753 	doq_socket->blocked_pkt = sldns_buffer_new(
2754 		sldns_buffer_capacity(doq_socket->pkt_buf));
2755 	if(!doq_socket->pkt_buf) {
2756 		free(doq_socket->static_secret);
2757 		sldns_buffer_free(doq_socket->pkt_buf);
2758 		free(doq_socket);
2759 		return NULL;
2760 	}
2761 	doq_socket->blocked_paddr = calloc(1,
2762 		sizeof(*doq_socket->blocked_paddr));
2763 	if(!doq_socket->blocked_paddr) {
2764 		free(doq_socket->static_secret);
2765 		sldns_buffer_free(doq_socket->pkt_buf);
2766 		sldns_buffer_free(doq_socket->blocked_pkt);
2767 		free(doq_socket);
2768 		return NULL;
2769 	}
2770 	doq_socket->timer = comm_timer_create(base, doq_timer_cb, doq_socket);
2771 	if(!doq_socket->timer) {
2772 		free(doq_socket->static_secret);
2773 		sldns_buffer_free(doq_socket->pkt_buf);
2774 		sldns_buffer_free(doq_socket->blocked_pkt);
2775 		free(doq_socket->blocked_paddr);
2776 		free(doq_socket);
2777 		return NULL;
2778 	}
2779 	doq_socket->marked_time = 0;
2780 	comm_base_timept(base, &doq_socket->now_tt, &doq_socket->now_tv);
2781 	doq_socket->cfg = cfg;
2782 	return doq_socket;
2783 }
2784 
2785 /** delete doq server socket structure */
2786 static void
2787 doq_server_socket_delete(struct doq_server_socket* doq_socket)
2788 {
2789 	if(!doq_socket)
2790 		return;
2791 	free(doq_socket->static_secret);
2792 #ifndef HAVE_NGTCP2_CRYPTO_QUICTLS_CONFIGURE_SERVER_CONTEXT
2793 	free(doq_socket->quic_method);
2794 #endif
2795 	sldns_buffer_free(doq_socket->pkt_buf);
2796 	sldns_buffer_free(doq_socket->blocked_pkt);
2797 	free(doq_socket->blocked_paddr);
2798 	comm_timer_delete(doq_socket->timer);
2799 	free(doq_socket);
2800 }
2801 
2802 /** find repinfo in the doq table */
2803 static struct doq_conn*
2804 doq_lookup_repinfo(struct doq_table* table, struct comm_reply* repinfo)
2805 {
2806 	struct doq_conn* conn;
2807 	struct doq_conn_key key;
2808 	log_assert(table != NULL);
2809 	doq_conn_key_from_repinfo(&key, repinfo);
2810 	lock_rw_rdlock(&table->lock);
2811 	conn = doq_conn_find(table, &key.paddr.addr,
2812 		key.paddr.addrlen, &key.paddr.localaddr,
2813 		key.paddr.localaddrlen, key.paddr.ifindex, key.dcid,
2814 		key.dcidlen);
2815 	if(conn) {
2816 		lock_basic_lock(&conn->lock);
2817 		lock_rw_unlock(&table->lock);
2818 		return conn;
2819 	}
2820 	lock_rw_unlock(&table->lock);
2821 	return NULL;
2822 }
2823 
2824 /** doq find connection and stream. From inside callbacks from worker. */
2825 static int
2826 doq_lookup_conn_stream(struct comm_reply* repinfo, struct comm_point* c,
2827 	struct doq_conn** conn, struct doq_stream** stream)
2828 {
2829 	log_assert(c->doq_socket);
2830 	if(c->doq_socket->current_conn) {
2831 		*conn = c->doq_socket->current_conn;
2832 	} else {
2833 		*conn = doq_lookup_repinfo(c->doq_socket->table, repinfo);
2834 		if((*conn) && (*conn)->is_deleted) {
2835 			lock_basic_unlock(&(*conn)->lock);
2836 			*conn = NULL;
2837 		}
2838 		if(*conn) {
2839 			(*conn)->doq_socket = c->doq_socket;
2840 		}
2841 	}
2842 	if(!*conn) {
2843 		*stream = NULL;
2844 		return 0;
2845 	}
2846 	*stream = doq_stream_find(*conn, repinfo->doq_streamid);
2847 	if(!*stream) {
2848 		if(!c->doq_socket->current_conn) {
2849 			/* Not inside callbacks, we have our own lock on conn.
2850 			 * Release it. */
2851 			lock_basic_unlock(&(*conn)->lock);
2852 		}
2853 		return 0;
2854 	}
2855 	if((*stream)->is_closed) {
2856 		/* stream is closed, ignore reply or drop */
2857 		if(!c->doq_socket->current_conn) {
2858 			/* Not inside callbacks, we have our own lock on conn.
2859 			 * Release it. */
2860 			lock_basic_unlock(&(*conn)->lock);
2861 		}
2862 		return 0;
2863 	}
2864 	return 1;
2865 }
2866 
2867 /** doq send a reply from a comm reply */
2868 static void
2869 doq_socket_send_reply(struct comm_reply* repinfo)
2870 {
2871 	struct doq_conn* conn;
2872 	struct doq_stream* stream;
2873 	log_assert(repinfo->c->type == comm_doq);
2874 	if(!doq_lookup_conn_stream(repinfo, repinfo->c, &conn, &stream)) {
2875 		verbose(VERB_ALGO, "doq: send_reply but %s is gone",
2876 			(conn?"stream":"connection"));
2877 		/* No stream, it may have been closed. */
2878 		/* Drop the reply, it cannot be sent. */
2879 		return;
2880 	}
2881 	if(!doq_stream_send_reply(conn, stream, repinfo->c->buffer))
2882 		doq_stream_close(conn, stream, 1);
2883 	if(!repinfo->c->doq_socket->current_conn) {
2884 		/* Not inside callbacks, we have our own lock on conn.
2885 		 * Release it. */
2886 		doq_done_with_conn_cb(repinfo->c, conn);
2887 		/* since we sent a reply, or closed it, the assumption is
2888 		 * that there is something to write, so enable write event.
2889 		 * It waits until the write event happens to write the
2890 		 * streams with answers, this allows some answers to be
2891 		 * answered before the event loop reaches the doq fd, in
2892 		 * repinfo->c->fd, and that collates answers. That would
2893 		 * not happen if we write doq packets right now. */
2894 		doq_socket_write_enable(repinfo->c);
2895 	}
2896 }
2897 
2898 /** doq drop a reply from a comm reply */
2899 static void
2900 doq_socket_drop_reply(struct comm_reply* repinfo)
2901 {
2902 	struct doq_conn* conn;
2903 	struct doq_stream* stream;
2904 	log_assert(repinfo->c->type == comm_doq);
2905 	if(!doq_lookup_conn_stream(repinfo, repinfo->c, &conn, &stream)) {
2906 		verbose(VERB_ALGO, "doq: drop_reply but %s is gone",
2907 			(conn?"stream":"connection"));
2908 		/* The connection or stream is already gone. */
2909 		return;
2910 	}
2911 	doq_stream_close(conn, stream, 1);
2912 	if(!repinfo->c->doq_socket->current_conn) {
2913 		/* Not inside callbacks, we have our own lock on conn.
2914 		 * Release it. */
2915 		doq_done_with_conn_cb(repinfo->c, conn);
2916 		doq_socket_write_enable(repinfo->c);
2917 	}
2918 }
2919 #endif /* HAVE_NGTCP2 */
2920 
2921 int adjusted_tcp_timeout(struct comm_point* c)
2922 {
2923 	if(c->tcp_timeout_msec < TCP_QUERY_TIMEOUT_MINIMUM)
2924 		return TCP_QUERY_TIMEOUT_MINIMUM;
2925 	return c->tcp_timeout_msec;
2926 }
2927 
2928 /** Use a new tcp handler for new query fd, set to read query */
2929 static void
2930 setup_tcp_handler(struct comm_point* c, int fd, int cur, int max)
2931 {
2932 	int handler_usage;
2933 	log_assert(c->type == comm_tcp || c->type == comm_http);
2934 	log_assert(c->fd == -1);
2935 	sldns_buffer_clear(c->buffer);
2936 #ifdef USE_DNSCRYPT
2937 	if (c->dnscrypt)
2938 		sldns_buffer_clear(c->dnscrypt_buffer);
2939 #endif
2940 	c->tcp_is_reading = 1;
2941 	c->tcp_byte_count = 0;
2942 	c->tcp_keepalive = 0;
2943 	/* reset to configured value before applying load-based reduction */
2944 	c->tcp_timeout_msec = c->tcp_parent->tcp_timeout_msec;
2945 	/* if more than half the tcp handlers are in use, use a shorter
2946 	 * timeout for this TCP connection, we need to make space for
2947 	 * other connections to be able to get attention */
2948 	/* If > 50% TCP handler structures in use, set timeout to 1/100th
2949 	 * 	configured value.
2950 	 * If > 65%TCP handler structures in use, set to 1/500th configured
2951 	 * 	value.
2952 	 * If > 80% TCP handler structures in use, set to 0.
2953 	 *
2954 	 * If the timeout to use falls below 200 milliseconds, an actual
2955 	 * timeout of 200ms is used.
2956 	 */
2957 	handler_usage = (cur * 100) / max;
2958 	if(handler_usage > 50 && handler_usage <= 65)
2959 		c->tcp_timeout_msec /= 100;
2960 	else if (handler_usage > 65 && handler_usage <= 80)
2961 		c->tcp_timeout_msec /= 500;
2962 	else if (handler_usage > 80)
2963 		c->tcp_timeout_msec = 0;
2964 	comm_point_start_listening(c, fd, adjusted_tcp_timeout(c));
2965 }
2966 
2967 void comm_base_handle_slow_accept(int ATTR_UNUSED(fd),
2968 	short ATTR_UNUSED(event), void* arg)
2969 {
2970 	struct comm_base* b = (struct comm_base*)arg;
2971 	/* timeout for the slow accept, re-enable accepts again */
2972 	if(b->start_accept) {
2973 		verbose(VERB_ALGO, "wait is over, slow accept disabled");
2974 		fptr_ok(fptr_whitelist_start_accept(b->start_accept));
2975 		(*b->start_accept)(b->cb_arg);
2976 		b->eb->slow_accept_enabled = 0;
2977 	}
2978 }
2979 
2980 /** out of resources in the accept path: pause all listening for
2981  * NETEVENT_SLOW_ACCEPT_TIME and re-arm via comm_base_handle_slow_accept.
2982  *
2983  * If the routine fails, the socket is accepted and then closed, draining it
2984  * from the waiting list of connections to be accepted.
2985  * @param c: the comm point that is a listening socket.
2986  * @param msec: if 0: uses the slow accept time. Otherwise, sets the time
2987  *		to wait.
2988  */
2989 static void
2990 comm_point_slow_accept(struct comm_point* c, int msec)
2991 {
2992 	struct comm_base* b = c->ev->base;
2993 	struct timeval tv;
2994 	struct ub_event* slowev;
2995 	if(!b->stop_accept)
2996 		return;
2997 	if(b->eb->slow_accept_enabled)
2998 		return;
2999 	/* Allocate the event */
3000 	slowev = ub_event_new(b->eb->base, -1, UB_EV_TIMEOUT,
3001 		comm_base_handle_slow_accept, b);
3002 	if(!slowev) {
3003 		/* The slow accept was not enabled yet, to handle
3004 		 * the allocation failure, instead drain the incoming
3005 		 * connection. */
3006 		int new_fd = accept(c->fd, NULL, NULL);
3007 		if(new_fd != -1) {
3008 			verbose(VERB_ALGO, "slow accept: event_new failed, "
3009 				"drop connection");
3010 			sock_close(new_fd);
3011 		}
3012 		return;
3013 	}
3014 	ub_comm_base_now(b);
3015 	if(b->eb->last_slow_log+SLOW_LOG_TIME <= b->eb->secs) {
3016 		b->eb->last_slow_log = b->eb->secs;
3017 		verbose(VERB_OPS, "out of resources on accept, "
3018 			"slow down accept for %d msec",
3019 			NETEVENT_SLOW_ACCEPT_TIME);
3020 	}
3021 	b->eb->slow_accept_enabled = 1;
3022 	fptr_ok(fptr_whitelist_stop_accept(b->stop_accept));
3023 	(*b->stop_accept)(b->cb_arg);
3024 	/* set timeout, no mallocs */
3025 	if(msec == 0)
3026 		msec = NETEVENT_SLOW_ACCEPT_TIME;
3027 	tv.tv_sec = msec/1000;
3028 	tv.tv_usec = (msec%1000)*1000;
3029 	b->eb->slow_accept = slowev;
3030 	if(ub_event_add(b->eb->slow_accept, &tv) != 0) {
3031 		/* we do not want to log here,
3032 		 * error: "event_add failed." */
3033 	}
3034 }
3035 
3036 int comm_point_perform_accept(struct comm_point* c,
3037 	struct sockaddr_storage* addr, socklen_t* addrlen)
3038 {
3039 	int new_fd;
3040 	*addrlen = (socklen_t)sizeof(*addr);
3041 #ifndef HAVE_ACCEPT4
3042 	new_fd = accept(c->fd, (struct sockaddr*)addr, addrlen);
3043 #else
3044 	/* SOCK_NONBLOCK saves extra calls to fcntl for the same result */
3045 	new_fd = accept4(c->fd, (struct sockaddr*)addr, addrlen, SOCK_NONBLOCK);
3046 #endif
3047 	if(new_fd == -1) {
3048 #ifndef USE_WINSOCK
3049 		/* EINTR is signal interrupt. others are closed connection. */
3050 		if(	errno == EINTR || errno == EAGAIN
3051 #ifdef EWOULDBLOCK
3052 			|| errno == EWOULDBLOCK
3053 #endif
3054 #ifdef ECONNABORTED
3055 			|| errno == ECONNABORTED
3056 #endif
3057 #ifdef EPROTO
3058 			|| errno == EPROTO
3059 #endif /* EPROTO */
3060 			)
3061 			return -1;
3062 #if defined(ENFILE) && defined(EMFILE)
3063 		if(errno == ENFILE || errno == EMFILE) {
3064 			/* out of file descriptors, likely outside of our
3065 			 * control. stop accept() calls for some time */
3066 			if(c->ev->base->stop_accept) {
3067 				struct comm_base* b = c->ev->base;
3068 				struct timeval tv;
3069 				struct ub_event* slowev = ub_event_new(
3070 					b->eb->base, -1, UB_EV_TIMEOUT,
3071 					comm_base_handle_slow_accept, b);
3072 				if(!slowev) {
3073 					verbose(VERB_ALGO, "slow accept: "
3074 						"event_new failed");
3075 					return -1;
3076 				}
3077 				verbose(VERB_ALGO, "out of file descriptors: "
3078 					"slow accept");
3079 				ub_comm_base_now(b);
3080 				if(b->eb->last_slow_log+SLOW_LOG_TIME <=
3081 					b->eb->secs) {
3082 					b->eb->last_slow_log = b->eb->secs;
3083 					verbose(VERB_OPS, "accept failed, "
3084 						"slow down accept for %d "
3085 						"msec: %s",
3086 						NETEVENT_SLOW_ACCEPT_TIME,
3087 						sock_strerror(errno));
3088 				}
3089 				b->eb->slow_accept_enabled = 1;
3090 				fptr_ok(fptr_whitelist_stop_accept(
3091 					b->stop_accept));
3092 				(*b->stop_accept)(b->cb_arg);
3093 				/* set timeout, no mallocs */
3094 				tv.tv_sec = NETEVENT_SLOW_ACCEPT_TIME/1000;
3095 				tv.tv_usec = (NETEVENT_SLOW_ACCEPT_TIME%1000)*1000;
3096 				b->eb->slow_accept = slowev;
3097 				if(ub_event_add(b->eb->slow_accept, &tv)
3098 					!= 0) {
3099 					/* we do not want to log here,
3100 					 * error: "event_add failed." */
3101 				}
3102 			} else {
3103 				log_err("accept, with no slow down, "
3104 					"failed: %s", sock_strerror(errno));
3105 			}
3106 			return -1;
3107 		}
3108 #endif
3109 #else /* USE_WINSOCK */
3110 		if(WSAGetLastError() == WSAEINPROGRESS ||
3111 			WSAGetLastError() == WSAECONNRESET)
3112 			return -1;
3113 		if(WSAGetLastError() == WSAEWOULDBLOCK) {
3114 			ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
3115 			return -1;
3116 		}
3117 #endif
3118 		log_err_addr("accept failed", sock_strerror(errno), addr,
3119 			*addrlen);
3120 		return -1;
3121 	}
3122 	if(c->tcp_conn_limit && c->type == comm_tcp_accept) {
3123 		c->tcl_addr = tcl_addr_lookup(c->tcp_conn_limit, addr, *addrlen);
3124 		if(!tcl_new_connection(c->tcl_addr)) {
3125 			if(verbosity >= 3)
3126 				log_err_addr("accept rejected",
3127 				"connection limit exceeded", addr, *addrlen);
3128 			sock_close(new_fd);
3129 			return -1;
3130 		}
3131 	}
3132 #ifndef HAVE_ACCEPT4
3133 	fd_set_nonblock(new_fd);
3134 #endif
3135 	return new_fd;
3136 }
3137 
3138 #ifdef USE_WINSOCK
3139 static long win_bio_cb(BIO *b, int oper, const char* ATTR_UNUSED(argp),
3140 #ifdef HAVE_BIO_SET_CALLBACK_EX
3141 	size_t ATTR_UNUSED(len),
3142 #endif
3143         int ATTR_UNUSED(argi), long argl,
3144 #ifndef HAVE_BIO_SET_CALLBACK_EX
3145 	long retvalue
3146 #else
3147 	int retvalue, size_t* ATTR_UNUSED(processed)
3148 #endif
3149 	)
3150 {
3151 	int wsa_err = WSAGetLastError(); /* store errcode before it is gone */
3152 	verbose(VERB_ALGO, "bio_cb %d, %s %s %s", oper,
3153 		(oper&BIO_CB_RETURN)?"return":"before",
3154 		(oper&BIO_CB_READ)?"read":((oper&BIO_CB_WRITE)?"write":"other"),
3155 		wsa_err==WSAEWOULDBLOCK?"wsawb":"");
3156 	/* on windows, check if previous operation caused EWOULDBLOCK */
3157 	if( (oper == (BIO_CB_READ|BIO_CB_RETURN) && argl == 0) ||
3158 		(oper == (BIO_CB_GETS|BIO_CB_RETURN) && argl == 0)) {
3159 		if(wsa_err == WSAEWOULDBLOCK)
3160 			ub_winsock_tcp_wouldblock((struct ub_event*)
3161 				BIO_get_callback_arg(b), UB_EV_READ);
3162 	}
3163 	if( (oper == (BIO_CB_WRITE|BIO_CB_RETURN) && argl == 0) ||
3164 		(oper == (BIO_CB_PUTS|BIO_CB_RETURN) && argl == 0)) {
3165 		if(wsa_err == WSAEWOULDBLOCK)
3166 			ub_winsock_tcp_wouldblock((struct ub_event*)
3167 				BIO_get_callback_arg(b), UB_EV_WRITE);
3168 	}
3169 	/* return original return value */
3170 	return retvalue;
3171 }
3172 
3173 /** set win bio callbacks for nonblocking operations */
3174 void
3175 comm_point_tcp_win_bio_cb(struct comm_point* c, void* thessl)
3176 {
3177 	SSL* ssl = (SSL*)thessl;
3178 	/* set them both just in case, but usually they are the same BIO */
3179 #ifdef HAVE_BIO_SET_CALLBACK_EX
3180 	BIO_set_callback_ex(SSL_get_rbio(ssl), &win_bio_cb);
3181 #else
3182 	BIO_set_callback(SSL_get_rbio(ssl), &win_bio_cb);
3183 #endif
3184 	BIO_set_callback_arg(SSL_get_rbio(ssl), (char*)c->ev->ev);
3185 #ifdef HAVE_BIO_SET_CALLBACK_EX
3186 	BIO_set_callback_ex(SSL_get_wbio(ssl), &win_bio_cb);
3187 #else
3188 	BIO_set_callback(SSL_get_wbio(ssl), &win_bio_cb);
3189 #endif
3190 	BIO_set_callback_arg(SSL_get_wbio(ssl), (char*)c->ev->ev);
3191 }
3192 #endif
3193 
3194 #ifdef HAVE_NGHTTP2
3195 /** Create http2 session server.  Per connection, after TCP accepted.*/
3196 static int http2_session_server_create(struct http2_session* h2_session)
3197 {
3198 	log_assert(h2_session->callbacks);
3199 	h2_session->is_drop = 0;
3200 	if(nghttp2_session_server_new(&h2_session->session,
3201 			h2_session->callbacks,
3202 		h2_session) == NGHTTP2_ERR_NOMEM) {
3203 		log_err("failed to create nghttp2 session server");
3204 		return 0;
3205 	}
3206 
3207 	return 1;
3208 }
3209 
3210 /** Submit http2 setting to session. Once per session. */
3211 static int http2_submit_settings(struct http2_session* h2_session)
3212 {
3213 	int ret;
3214 	nghttp2_settings_entry settings[1] = {
3215 		{NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS,
3216 		 h2_session->c->http2_max_streams}};
3217 
3218 	ret = nghttp2_submit_settings(h2_session->session, NGHTTP2_FLAG_NONE,
3219 		settings, 1);
3220 	if(ret) {
3221 		verbose(VERB_QUERY, "http2: submit_settings failed, "
3222 			"error: %s", nghttp2_strerror(ret));
3223 		return 0;
3224 	}
3225 	return 1;
3226 }
3227 #endif /* HAVE_NGHTTP2 */
3228 
3229 #ifdef HAVE_NGHTTP2
3230 /** Delete http2 stream. After session delete or stream close callback */
3231 static void http2_stream_delete(struct http2_session* h2_session,
3232 	struct http2_stream* h2_stream)
3233 {
3234 	if(h2_stream->mesh_state) {
3235 		mesh_state_remove_reply(h2_stream->mesh, h2_stream->mesh_state,
3236 			h2_session->c, h2_stream, NULL);
3237 		h2_stream->mesh_state = NULL;
3238 	}
3239 	http2_req_stream_clear(h2_stream);
3240 	free(h2_stream);
3241 }
3242 #endif /* HAVE_NGHTTP2 */
3243 
3244 /** delete http2 session server. After closing connection. */
3245 static void http2_session_server_delete(struct http2_session* h2_session)
3246 {
3247 #ifdef HAVE_NGHTTP2
3248 	struct http2_stream* h2_stream, *next;
3249 	nghttp2_session_del(h2_session->session); /* NULL input is fine */
3250 	h2_session->session = NULL;
3251 	for(h2_stream = h2_session->first_stream; h2_stream;) {
3252 		next = h2_stream->next;
3253 		http2_stream_delete(h2_session, h2_stream);
3254 		h2_stream = next;
3255 	}
3256 	h2_session->first_stream = NULL;
3257 	h2_session->is_drop = 0;
3258 	h2_session->postpone_drop = 0;
3259 	h2_session->c->h2_stream = NULL;
3260 #endif
3261 	(void)h2_session;
3262 }
3263 
3264 void
3265 comm_point_tcp_accept_callback(int fd, short event, void* arg)
3266 {
3267 	struct comm_point* c = (struct comm_point*)arg, *c_hdl;
3268 	int new_fd;
3269 	log_assert(c->type == comm_tcp_accept);
3270 	if(!(event & UB_EV_READ)) {
3271 		log_info("ignoring tcp accept event %d", (int)event);
3272 		return;
3273 	}
3274 	ub_comm_base_now(c->ev->base);
3275 	/* find free tcp handler. */
3276 	if(!c->tcp_free) {
3277 		log_warn("accepted too many tcp, connections full");
3278 		/* Wait for a short moment (say 50msec) so that other
3279 		 * TCP connections can complete. Or timeout, at the busy
3280 		 * timeout of about 200msec. That stops this routine from
3281 		 * spinning endlessly, and gives time to complete the other
3282 		 * requests. But it is not as slow as the 2000msec wait
3283 		 * time for when the kernel is out of buffers. */
3284 		comm_point_slow_accept(c, NETEVENT_SLOW_ACCEPT_QUEUE_TIME);
3285 		return;
3286 	}
3287 	/* accept incoming connection. */
3288 	c_hdl = c->tcp_free;
3289 	/* Should not happen: inconsistent tcp_free state in
3290 	 * accept_callback. */
3291 	log_assert(c_hdl->is_in_tcp_free);
3292 	/* clear leftover flags from previous use, and then set the
3293 	 * correct event base for the event structure for libevent */
3294 	ub_event_free(c_hdl->ev->ev);
3295 	c_hdl->ev->ev = NULL;
3296 	if((c_hdl->type == comm_tcp && c_hdl->tcp_req_info) ||
3297 		c_hdl->type == comm_local || c_hdl->type == comm_raw)
3298 		c_hdl->tcp_do_toggle_rw = 0;
3299 	else	c_hdl->tcp_do_toggle_rw = 1;
3300 
3301 	if(c_hdl->type == comm_http) {
3302 #ifdef HAVE_NGHTTP2
3303 		if(!c_hdl->h2_session ||
3304 			!http2_session_server_create(c_hdl->h2_session)) {
3305 			log_warn("failed to create nghttp2");
3306 			comm_point_slow_accept(c, 0);
3307 			return;
3308 		}
3309 		if(!c_hdl->h2_session ||
3310 			!http2_submit_settings(c_hdl->h2_session)) {
3311 			log_warn("failed to submit http2 settings");
3312 			if(c_hdl->h2_session)
3313 				http2_session_server_delete(c_hdl->h2_session);
3314 			comm_point_slow_accept(c, 0);
3315 			return;
3316 		}
3317 		if(!c->ssl) {
3318 			c_hdl->tcp_do_toggle_rw = 0;
3319 			c_hdl->use_h2 = 1;
3320 		}
3321 #endif
3322 		c_hdl->ev->ev = ub_event_new(c_hdl->ev->base->eb->base, -1,
3323 			UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT,
3324 			comm_point_http_handle_callback, c_hdl);
3325 	} else {
3326 		c_hdl->ev->ev = ub_event_new(c_hdl->ev->base->eb->base, -1,
3327 			UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT,
3328 			comm_point_tcp_handle_callback, c_hdl);
3329 	}
3330 	if(!c_hdl->ev->ev) {
3331 		log_warn("could not ub_event_new, for new tcp");
3332 #ifdef HAVE_NGHTTP2
3333 		if(c_hdl->type == comm_http && c_hdl->h2_session)
3334 			http2_session_server_delete(c_hdl->h2_session);
3335 #endif
3336 		comm_point_slow_accept(c, 0);
3337 		return;
3338 	}
3339 	log_assert(fd != -1);
3340 	(void)fd;
3341 	new_fd = comm_point_perform_accept(c, &c_hdl->repinfo.remote_addr,
3342 		&c_hdl->repinfo.remote_addrlen);
3343 	if(new_fd == -1) {
3344 #ifdef HAVE_NGHTTP2
3345 		if(c_hdl->type == comm_http && c_hdl->h2_session)
3346 			http2_session_server_delete(c_hdl->h2_session);
3347 #endif
3348 		return;
3349 	}
3350 	/* move per-netblock TCP-connection-limit handle to the handler so that
3351 	 * comm_point_close() on the handler decrements the count on close */
3352 	c_hdl->tcl_addr = c->tcl_addr;
3353 	c->tcl_addr = NULL;
3354 	/* Copy remote_address to client_address.
3355 	 * Simplest way/time for streams to do that. */
3356 	c_hdl->repinfo.client_addrlen = c_hdl->repinfo.remote_addrlen;
3357 	memmove(&c_hdl->repinfo.client_addr,
3358 		&c_hdl->repinfo.remote_addr,
3359 		c_hdl->repinfo.remote_addrlen);
3360 	if(c->ssl) {
3361 		c_hdl->ssl = incoming_ssl_fd(c->ssl, new_fd);
3362 		if(!c_hdl->ssl) {
3363 			c_hdl->fd = new_fd;
3364 			comm_point_close(c_hdl);
3365 			return;
3366 		}
3367 		c_hdl->ssl_shake_state = comm_ssl_shake_read;
3368 #ifdef USE_WINSOCK
3369 		comm_point_tcp_win_bio_cb(c_hdl, c_hdl->ssl);
3370 #endif
3371 	}
3372 
3373 	/* Paranoia: Check that the state has not changed from above: */
3374 	/* Should not happen: tcp_free state changed within accept_callback. */
3375 	log_assert(c_hdl == c->tcp_free);
3376 	log_assert(c_hdl->is_in_tcp_free);
3377 	/* grab the tcp handler buffers */
3378 	c->cur_tcp_count++;
3379 	c->tcp_free = c_hdl->tcp_free;
3380 	c_hdl->tcp_free = NULL;
3381 	c_hdl->is_in_tcp_free = 0;
3382 	if(!c->tcp_free) {
3383 		/* stop accepting incoming queries for now. */
3384 		comm_point_stop_listening(c);
3385 	}
3386 	setup_tcp_handler(c_hdl, new_fd, c->cur_tcp_count, c->max_tcp_count);
3387 }
3388 
3389 /** Make tcp handler free for next assignment */
3390 static void
3391 reclaim_tcp_handler(struct comm_point* c)
3392 {
3393 	log_assert(c->type == comm_tcp);
3394 	if(c->ssl) {
3395 #ifdef HAVE_SSL
3396 		SSL_shutdown(c->ssl);
3397 		SSL_free(c->ssl);
3398 		c->ssl = NULL;
3399 #endif
3400 	}
3401 	comm_point_close(c);
3402 	if(c->tcp_parent && !c->is_in_tcp_free) {
3403 		/* Should not happen: bad tcp_free state in reclaim_tcp. */
3404 		log_assert(c->tcp_free == NULL);
3405 		log_assert(c->tcp_parent->cur_tcp_count > 0);
3406 		c->tcp_parent->cur_tcp_count--;
3407 		c->tcp_free = c->tcp_parent->tcp_free;
3408 		c->tcp_parent->tcp_free = c;
3409 		c->is_in_tcp_free = 1;
3410 		if(!c->tcp_free) {
3411 			/* re-enable listening on accept socket */
3412 			comm_point_start_listening(c->tcp_parent, -1, -1);
3413 		}
3414 	}
3415 	c->tcp_more_read_again = NULL;
3416 	c->tcp_more_write_again = NULL;
3417 	c->tcp_byte_count = 0;
3418 	c->pp2_header_state = pp2_header_none;
3419 	sldns_buffer_clear(c->buffer);
3420 }
3421 
3422 /** do the callback when writing is done */
3423 static void
3424 tcp_callback_writer(struct comm_point* c)
3425 {
3426 	log_assert(c->type == comm_tcp);
3427 	if(!c->tcp_write_and_read) {
3428 		sldns_buffer_clear(c->buffer);
3429 		c->tcp_byte_count = 0;
3430 	}
3431 	if(c->tcp_do_toggle_rw)
3432 		c->tcp_is_reading = 1;
3433 	/* switch from listening(write) to listening(read) */
3434 	if(c->tcp_req_info) {
3435 		tcp_req_info_handle_writedone(c->tcp_req_info);
3436 	} else {
3437 		comm_point_stop_listening(c);
3438 		if(c->tcp_write_and_read) {
3439 			fptr_ok(fptr_whitelist_comm_point(c->callback));
3440 			if( (*c->callback)(c, c->cb_arg, NETEVENT_PKT_WRITTEN,
3441 				&c->repinfo) ) {
3442 				comm_point_start_listening(c, -1,
3443 					adjusted_tcp_timeout(c));
3444 			}
3445 		} else {
3446 			comm_point_start_listening(c, -1,
3447 					adjusted_tcp_timeout(c));
3448 		}
3449 	}
3450 }
3451 
3452 /** do the callback when reading is done */
3453 static void
3454 tcp_callback_reader(struct comm_point* c)
3455 {
3456 	log_assert(c->type == comm_tcp || c->type == comm_local);
3457 	sldns_buffer_flip(c->buffer);
3458 	if(c->tcp_do_toggle_rw)
3459 		c->tcp_is_reading = 0;
3460 	c->tcp_byte_count = 0;
3461 	if(c->tcp_req_info) {
3462 		tcp_req_info_handle_readdone(c->tcp_req_info);
3463 	} else {
3464 		if(c->type == comm_tcp)
3465 			comm_point_stop_listening(c);
3466 		fptr_ok(fptr_whitelist_comm_point(c->callback));
3467 		if( (*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, &c->repinfo) ) {
3468 			comm_point_start_listening(c, -1,
3469 					adjusted_tcp_timeout(c));
3470 		}
3471 	}
3472 }
3473 
3474 #ifdef HAVE_SSL
3475 /** true if the ssl handshake error has to be squelched from the logs */
3476 int
3477 squelch_err_ssl_handshake(unsigned long err)
3478 {
3479 	if(verbosity >= VERB_QUERY)
3480 		return 0; /* only squelch on low verbosity */
3481 	if(ERR_GET_LIB(err) == ERR_LIB_SSL &&
3482 		(ERR_GET_REASON(err) == SSL_R_HTTPS_PROXY_REQUEST ||
3483 		 ERR_GET_REASON(err) == SSL_R_HTTP_REQUEST ||
3484 		 ERR_GET_REASON(err) == SSL_R_WRONG_VERSION_NUMBER ||
3485 		 ERR_GET_REASON(err) == SSL_R_SSLV3_ALERT_BAD_CERTIFICATE
3486 #ifdef SSL_F_TLS_POST_PROCESS_CLIENT_HELLO
3487 		 || ERR_GET_REASON(err) == SSL_R_NO_SHARED_CIPHER
3488 #endif
3489 #ifdef SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO
3490 		 || ERR_GET_REASON(err) == SSL_R_UNKNOWN_PROTOCOL
3491 		 || ERR_GET_REASON(err) == SSL_R_UNSUPPORTED_PROTOCOL
3492 #  ifdef SSL_R_VERSION_TOO_LOW
3493 		 || ERR_GET_REASON(err) == SSL_R_VERSION_TOO_LOW
3494 #  endif
3495 #endif
3496 		))
3497 		return 1;
3498 	return 0;
3499 }
3500 #endif /* HAVE_SSL */
3501 
3502 /** continue ssl handshake */
3503 #ifdef HAVE_SSL
3504 static int
3505 ssl_handshake(struct comm_point* c)
3506 {
3507 	int r;
3508 	if(c->ssl_shake_state == comm_ssl_shake_hs_read) {
3509 		/* read condition satisfied back to writing */
3510 		comm_point_listen_for_rw(c, 0, 1);
3511 		c->ssl_shake_state = comm_ssl_shake_none;
3512 		return 1;
3513 	}
3514 	if(c->ssl_shake_state == comm_ssl_shake_hs_write) {
3515 		/* write condition satisfied, back to reading */
3516 		comm_point_listen_for_rw(c, 1, 0);
3517 		c->ssl_shake_state = comm_ssl_shake_none;
3518 		return 1;
3519 	}
3520 
3521 	ERR_clear_error();
3522 	r = SSL_do_handshake(c->ssl);
3523 	if(r != 1) {
3524 		int want = SSL_get_error(c->ssl, r);
3525 		if(want == SSL_ERROR_WANT_READ) {
3526 			if(c->ssl_shake_state == comm_ssl_shake_read)
3527 				return 1;
3528 			c->ssl_shake_state = comm_ssl_shake_read;
3529 			comm_point_listen_for_rw(c, 1, 0);
3530 			return 1;
3531 		} else if(want == SSL_ERROR_WANT_WRITE) {
3532 			if(c->ssl_shake_state == comm_ssl_shake_write)
3533 				return 1;
3534 			c->ssl_shake_state = comm_ssl_shake_write;
3535 			comm_point_listen_for_rw(c, 0, 1);
3536 			return 1;
3537 		} else if(r == 0) {
3538 			return 0; /* closed */
3539 		} else if(want == SSL_ERROR_SYSCALL) {
3540 			/* SYSCALL and errno==0 means closed uncleanly */
3541 #ifdef EPIPE
3542 			if(errno == EPIPE && verbosity < 2)
3543 				return 0; /* silence 'broken pipe' */
3544 #endif
3545 #ifdef ECONNRESET
3546 			if(errno == ECONNRESET && verbosity < 2)
3547 				return 0; /* silence reset by peer */
3548 #endif
3549 			if(!tcp_connect_errno_needs_log(
3550 				(struct sockaddr*)&c->repinfo.remote_addr,
3551 				c->repinfo.remote_addrlen))
3552 				return 0; /* silence connect failures that
3553 				show up because after connect this is the
3554 				first system call that accesses the socket */
3555 			if(errno != 0)
3556 				log_err("SSL_handshake syscall: %s",
3557 					strerror(errno));
3558 			return 0;
3559 		} else {
3560 			unsigned long err = ERR_get_error();
3561 			if(!squelch_err_ssl_handshake(err)) {
3562 				long vr;
3563 				log_crypto_err_io_code("ssl handshake failed",
3564 					want, err);
3565 				if((vr=SSL_get_verify_result(c->ssl)) != 0)
3566 					log_err("ssl handshake cert error: %s",
3567 						X509_verify_cert_error_string(
3568 						vr));
3569 				log_addr(VERB_OPS, "ssl handshake failed",
3570 					&c->repinfo.remote_addr,
3571 					c->repinfo.remote_addrlen);
3572 			}
3573 			return 0;
3574 		}
3575 	}
3576 	/* this is where peer verification could take place */
3577 	if((SSL_get_verify_mode(c->ssl)&SSL_VERIFY_PEER)) {
3578 		/* verification */
3579 		if(SSL_get_verify_result(c->ssl) == X509_V_OK) {
3580 #ifdef HAVE_SSL_GET1_PEER_CERTIFICATE
3581 			X509* x = SSL_get1_peer_certificate(c->ssl);
3582 #else
3583 			X509* x = SSL_get_peer_certificate(c->ssl);
3584 #endif
3585 			if(!x) {
3586 				log_addr(VERB_ALGO, "SSL connection failed: "
3587 					"no certificate",
3588 					&c->repinfo.remote_addr,
3589 					c->repinfo.remote_addrlen);
3590 				return 0;
3591 			}
3592 			log_cert(VERB_ALGO, "peer certificate", x);
3593 #ifdef HAVE_SSL_GET0_PEERNAME
3594 			if(SSL_get0_peername(c->ssl)) {
3595 				char buf[255];
3596 				snprintf(buf, sizeof(buf), "SSL connection "
3597 					"to %s authenticated",
3598 					SSL_get0_peername(c->ssl));
3599 				log_addr(VERB_ALGO, buf, &c->repinfo.remote_addr,
3600 					c->repinfo.remote_addrlen);
3601 			} else {
3602 #endif
3603 				log_addr(VERB_ALGO, "SSL connection "
3604 					"authenticated", &c->repinfo.remote_addr,
3605 					c->repinfo.remote_addrlen);
3606 #ifdef HAVE_SSL_GET0_PEERNAME
3607 			}
3608 #endif
3609 			X509_free(x);
3610 		} else {
3611 #ifdef HAVE_SSL_GET1_PEER_CERTIFICATE
3612 			X509* x = SSL_get1_peer_certificate(c->ssl);
3613 #else
3614 			X509* x = SSL_get_peer_certificate(c->ssl);
3615 #endif
3616 			if(x) {
3617 				log_cert(VERB_ALGO, "peer certificate", x);
3618 				X509_free(x);
3619 			}
3620 			log_addr(VERB_ALGO, "SSL connection failed: "
3621 				"failed to authenticate",
3622 				&c->repinfo.remote_addr,
3623 				c->repinfo.remote_addrlen);
3624 			return 0;
3625 		}
3626 	} else {
3627 		/* unauthenticated, the verify peer flag was not set
3628 		 * in c->ssl when the ssl object was created from ssl_ctx */
3629 		log_addr(VERB_ALGO, "SSL connection", &c->repinfo.remote_addr,
3630 			c->repinfo.remote_addrlen);
3631 	}
3632 
3633 #ifdef HAVE_SSL_GET0_ALPN_SELECTED
3634 	/* check if http2 use is negotiated */
3635 	if(c->type == comm_http && c->h2_session) {
3636 		const unsigned char *alpn;
3637 		unsigned int alpnlen = 0;
3638 		SSL_get0_alpn_selected(c->ssl, &alpn, &alpnlen);
3639 		if(alpnlen == 2 && memcmp("h2", alpn, 2) == 0) {
3640 			/* connection upgraded to HTTP2 */
3641 			c->tcp_do_toggle_rw = 0;
3642 			c->use_h2 = 1;
3643 		} else {
3644 			verbose(VERB_ALGO, "client doesn't support HTTP/2");
3645 			return 0;
3646 		}
3647 	}
3648 #endif
3649 
3650 	/* setup listen rw correctly */
3651 	if(c->tcp_is_reading) {
3652 		if(c->ssl_shake_state != comm_ssl_shake_read)
3653 			comm_point_listen_for_rw(c, 1, 0);
3654 	} else {
3655 		comm_point_listen_for_rw(c, 0, 1);
3656 	}
3657 	c->ssl_shake_state = comm_ssl_shake_none;
3658 	return 1;
3659 }
3660 #endif /* HAVE_SSL */
3661 
3662 /** ssl read callback on TCP */
3663 static int
3664 ssl_handle_read(struct comm_point* c)
3665 {
3666 #ifdef HAVE_SSL
3667 	int r;
3668 	if(c->ssl_shake_state != comm_ssl_shake_none) {
3669 		if(!ssl_handshake(c))
3670 			return 0;
3671 		if(c->ssl_shake_state != comm_ssl_shake_none)
3672 			return 1;
3673 	}
3674 	if(c->pp2_enabled && c->pp2_header_state != pp2_header_done) {
3675 		struct pp2_header* header = NULL;
3676 		size_t want_read_size = 0;
3677 		size_t current_read_size = 0;
3678 		if(c->pp2_header_state == pp2_header_none) {
3679 			want_read_size = PP2_HEADER_SIZE;
3680 			if(sldns_buffer_remaining(c->buffer)<want_read_size) {
3681 				log_err_addr("proxy_protocol: not enough "
3682 					"buffer size to read PROXYv2 header", "",
3683 					&c->repinfo.remote_addr,
3684 					c->repinfo.remote_addrlen);
3685 				return 0;
3686 			}
3687 			verbose(VERB_ALGO, "proxy_protocol: reading fixed "
3688 				"part of PROXYv2 header (len %lu)",
3689 				(unsigned long)want_read_size);
3690 			current_read_size = want_read_size;
3691 			if(c->tcp_byte_count < current_read_size) {
3692 				ERR_clear_error();
3693 				if((r=SSL_read(c->ssl, (void*)sldns_buffer_at(
3694 					c->buffer, c->tcp_byte_count),
3695 					current_read_size -
3696 					c->tcp_byte_count)) <= 0) {
3697 					int want = SSL_get_error(c->ssl, r);
3698 					if(want == SSL_ERROR_ZERO_RETURN) {
3699 						if(c->tcp_req_info)
3700 							return tcp_req_info_handle_read_close(c->tcp_req_info);
3701 						return 0; /* shutdown, closed */
3702 					} else if(want == SSL_ERROR_WANT_READ) {
3703 #ifdef USE_WINSOCK
3704 						ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
3705 #endif
3706 						return 1; /* read more later */
3707 					} else if(want == SSL_ERROR_WANT_WRITE) {
3708 						c->ssl_shake_state = comm_ssl_shake_hs_write;
3709 						comm_point_listen_for_rw(c, 0, 1);
3710 						return 1;
3711 					} else if(want == SSL_ERROR_SYSCALL) {
3712 #ifdef ECONNRESET
3713 						if(errno == ECONNRESET && verbosity < 2)
3714 							return 0; /* silence reset by peer */
3715 #endif
3716 						if(errno != 0)
3717 							log_err("SSL_read syscall: %s",
3718 								strerror(errno));
3719 						return 0;
3720 					}
3721 					log_crypto_err_io("could not SSL_read",
3722 						want);
3723 					return 0;
3724 				}
3725 				c->tcp_byte_count += r;
3726 				sldns_buffer_skip(c->buffer, r);
3727 				if(c->tcp_byte_count != current_read_size) return 1;
3728 				c->pp2_header_state = pp2_header_init;
3729 			}
3730 		}
3731 		if(c->pp2_header_state == pp2_header_init) {
3732 			int err;
3733 			err = pp2_read_header(
3734 				sldns_buffer_begin(c->buffer),
3735 				sldns_buffer_limit(c->buffer));
3736 			if(err) {
3737 				log_err("proxy_protocol: could not parse "
3738 					"PROXYv2 header (%s)",
3739 					pp_lookup_error(err));
3740 				return 0;
3741 			}
3742 			header = (struct pp2_header*)sldns_buffer_begin(c->buffer);
3743 			want_read_size = ntohs(header->len);
3744 			if(sldns_buffer_limit(c->buffer) <
3745 				PP2_HEADER_SIZE + want_read_size) {
3746 				log_err_addr("proxy_protocol: not enough "
3747 					"buffer size to read PROXYv2 header", "",
3748 					&c->repinfo.remote_addr,
3749 					c->repinfo.remote_addrlen);
3750 				return 0;
3751 			}
3752 			verbose(VERB_ALGO, "proxy_protocol: reading variable "
3753 				"part of PROXYv2 header (len %lu)",
3754 				(unsigned long)want_read_size);
3755 			current_read_size = PP2_HEADER_SIZE + want_read_size;
3756 			if(want_read_size == 0) {
3757 				/* nothing more to read; header is complete */
3758 				c->pp2_header_state = pp2_header_done;
3759 			} else if(c->tcp_byte_count < current_read_size) {
3760 				ERR_clear_error();
3761 				if((r=SSL_read(c->ssl, (void*)sldns_buffer_at(
3762 					c->buffer, c->tcp_byte_count),
3763 					current_read_size -
3764 					c->tcp_byte_count)) <= 0) {
3765 					int want = SSL_get_error(c->ssl, r);
3766 					if(want == SSL_ERROR_ZERO_RETURN) {
3767 						if(c->tcp_req_info)
3768 							return tcp_req_info_handle_read_close(c->tcp_req_info);
3769 						return 0; /* shutdown, closed */
3770 					} else if(want == SSL_ERROR_WANT_READ) {
3771 #ifdef USE_WINSOCK
3772 						ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
3773 #endif
3774 						return 1; /* read more later */
3775 					} else if(want == SSL_ERROR_WANT_WRITE) {
3776 						c->ssl_shake_state = comm_ssl_shake_hs_write;
3777 						comm_point_listen_for_rw(c, 0, 1);
3778 						return 1;
3779 					} else if(want == SSL_ERROR_SYSCALL) {
3780 #ifdef ECONNRESET
3781 						if(errno == ECONNRESET && verbosity < 2)
3782 							return 0; /* silence reset by peer */
3783 #endif
3784 						if(errno != 0)
3785 							log_err("SSL_read syscall: %s",
3786 								strerror(errno));
3787 						return 0;
3788 					}
3789 					log_crypto_err_io("could not SSL_read",
3790 						want);
3791 					return 0;
3792 				}
3793 				c->tcp_byte_count += r;
3794 				sldns_buffer_skip(c->buffer, r);
3795 				if(c->tcp_byte_count != current_read_size) return 1;
3796 				c->pp2_header_state = pp2_header_done;
3797 			}
3798 		}
3799 		if(c->pp2_header_state != pp2_header_done || !header) {
3800 			log_err_addr("proxy_protocol: wrong state for the "
3801 				"PROXYv2 header", "", &c->repinfo.remote_addr,
3802 				c->repinfo.remote_addrlen);
3803 			return 0;
3804 		}
3805 		sldns_buffer_flip(c->buffer);
3806 		if(!consume_pp2_header(c->buffer, &c->repinfo, 1)) {
3807 			log_err_addr("proxy_protocol: could not consume "
3808 				"PROXYv2 header", "", &c->repinfo.remote_addr,
3809 				c->repinfo.remote_addrlen);
3810 			return 0;
3811 		}
3812 		verbose(VERB_ALGO, "proxy_protocol: successful read of "
3813 			"PROXYv2 header");
3814 		/* Clear and reset the buffer to read the following
3815 		 * DNS packet(s). */
3816 		sldns_buffer_clear(c->buffer);
3817 		c->tcp_byte_count = 0;
3818 		return 1;
3819 	}
3820 	if(c->tcp_byte_count < sizeof(uint16_t)) {
3821 		/* read length bytes */
3822 		ERR_clear_error();
3823 		if((r=SSL_read(c->ssl, (void*)sldns_buffer_at(c->buffer,
3824 			c->tcp_byte_count), (int)(sizeof(uint16_t) -
3825 			c->tcp_byte_count))) <= 0) {
3826 			int want = SSL_get_error(c->ssl, r);
3827 			if(want == SSL_ERROR_ZERO_RETURN) {
3828 				if(c->tcp_req_info)
3829 					return tcp_req_info_handle_read_close(c->tcp_req_info);
3830 				return 0; /* shutdown, closed */
3831 			} else if(want == SSL_ERROR_WANT_READ) {
3832 #ifdef USE_WINSOCK
3833 				ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
3834 #endif
3835 				return 1; /* read more later */
3836 			} else if(want == SSL_ERROR_WANT_WRITE) {
3837 				c->ssl_shake_state = comm_ssl_shake_hs_write;
3838 				comm_point_listen_for_rw(c, 0, 1);
3839 				return 1;
3840 			} else if(want == SSL_ERROR_SYSCALL) {
3841 #ifdef ECONNRESET
3842 				if(errno == ECONNRESET && verbosity < 2)
3843 					return 0; /* silence reset by peer */
3844 #endif
3845 				if(errno != 0)
3846 					log_err("SSL_read syscall: %s",
3847 						strerror(errno));
3848 				return 0;
3849 			}
3850 			log_crypto_err_io("could not SSL_read", want);
3851 			return 0;
3852 		}
3853 		c->tcp_byte_count += r;
3854 		if(c->tcp_byte_count < sizeof(uint16_t))
3855 			return 1;
3856 		if(sldns_buffer_read_u16_at(c->buffer, 0) >
3857 			sldns_buffer_capacity(c->buffer)) {
3858 			verbose(VERB_QUERY, "ssl: dropped larger than buffer");
3859 			return 0;
3860 		}
3861 		sldns_buffer_set_limit(c->buffer,
3862 			sldns_buffer_read_u16_at(c->buffer, 0));
3863 		if(sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
3864 			verbose(VERB_QUERY, "ssl: dropped bogus too short.");
3865 			return 0;
3866 		}
3867 		sldns_buffer_skip(c->buffer, (ssize_t)(c->tcp_byte_count-sizeof(uint16_t)));
3868 		verbose(VERB_ALGO, "Reading ssl tcp query of length %d",
3869 			(int)sldns_buffer_limit(c->buffer));
3870 	}
3871 	if(sldns_buffer_remaining(c->buffer) > 0) {
3872 		ERR_clear_error();
3873 		r = SSL_read(c->ssl, (void*)sldns_buffer_current(c->buffer),
3874 			(int)sldns_buffer_remaining(c->buffer));
3875 		if(r <= 0) {
3876 			int want = SSL_get_error(c->ssl, r);
3877 			if(want == SSL_ERROR_ZERO_RETURN) {
3878 				if(c->tcp_req_info)
3879 					return tcp_req_info_handle_read_close(c->tcp_req_info);
3880 				return 0; /* shutdown, closed */
3881 			} else if(want == SSL_ERROR_WANT_READ) {
3882 #ifdef USE_WINSOCK
3883 				ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
3884 #endif
3885 				return 1; /* read more later */
3886 			} else if(want == SSL_ERROR_WANT_WRITE) {
3887 				c->ssl_shake_state = comm_ssl_shake_hs_write;
3888 				comm_point_listen_for_rw(c, 0, 1);
3889 				return 1;
3890 			} else if(want == SSL_ERROR_SYSCALL) {
3891 #ifdef ECONNRESET
3892 				if(errno == ECONNRESET && verbosity < 2)
3893 					return 0; /* silence reset by peer */
3894 #endif
3895 				if(errno != 0)
3896 					log_err("SSL_read syscall: %s",
3897 						strerror(errno));
3898 				return 0;
3899 			}
3900 			log_crypto_err_io("could not SSL_read", want);
3901 			return 0;
3902 		}
3903 		sldns_buffer_skip(c->buffer, (ssize_t)r);
3904 	}
3905 	if(sldns_buffer_remaining(c->buffer) <= 0) {
3906 		tcp_callback_reader(c);
3907 	}
3908 	return 1;
3909 #else
3910 	(void)c;
3911 	return 0;
3912 #endif /* HAVE_SSL */
3913 }
3914 
3915 /** ssl write callback on TCP */
3916 static int
3917 ssl_handle_write(struct comm_point* c)
3918 {
3919 #ifdef HAVE_SSL
3920 	int r;
3921 	if(c->ssl_shake_state != comm_ssl_shake_none) {
3922 		if(!ssl_handshake(c))
3923 			return 0;
3924 		if(c->ssl_shake_state != comm_ssl_shake_none)
3925 			return 1;
3926 	}
3927 	/* ignore return, if fails we may simply block */
3928 	(void)SSL_set_mode(c->ssl, (long)SSL_MODE_ENABLE_PARTIAL_WRITE);
3929 	if((c->tcp_write_and_read?c->tcp_write_byte_count:c->tcp_byte_count) < sizeof(uint16_t)) {
3930 		uint16_t len = htons(c->tcp_write_and_read?c->tcp_write_pkt_len:sldns_buffer_limit(c->buffer));
3931 		ERR_clear_error();
3932 		if(c->tcp_write_and_read) {
3933 			if(c->tcp_write_pkt_len + 2 < LDNS_RR_BUF_SIZE) {
3934 				/* combine the tcp length and the query for
3935 				 * write, this emulates writev */
3936 				uint8_t buf[LDNS_RR_BUF_SIZE];
3937 				memmove(buf, &len, sizeof(uint16_t));
3938 				memmove(buf+sizeof(uint16_t),
3939 					c->tcp_write_pkt,
3940 					c->tcp_write_pkt_len);
3941 				r = SSL_write(c->ssl,
3942 					(void*)(buf+c->tcp_write_byte_count),
3943 					c->tcp_write_pkt_len + 2 -
3944 					c->tcp_write_byte_count);
3945 			} else {
3946 				r = SSL_write(c->ssl,
3947 					(void*)(((uint8_t*)&len)+c->tcp_write_byte_count),
3948 					(int)(sizeof(uint16_t)-c->tcp_write_byte_count));
3949 			}
3950 		} else if(sizeof(uint16_t)+sldns_buffer_remaining(c->buffer) <
3951 			LDNS_RR_BUF_SIZE) {
3952 			/* combine the tcp length and the query for write,
3953 			 * this emulates writev */
3954 			uint8_t buf[LDNS_RR_BUF_SIZE];
3955 			memmove(buf, &len, sizeof(uint16_t));
3956 			memmove(buf+sizeof(uint16_t),
3957 				sldns_buffer_current(c->buffer),
3958 				sldns_buffer_remaining(c->buffer));
3959 			r = SSL_write(c->ssl, (void*)(buf+c->tcp_byte_count),
3960 				(int)(sizeof(uint16_t)+
3961 				sldns_buffer_remaining(c->buffer)
3962 				- c->tcp_byte_count));
3963 		} else {
3964 			r = SSL_write(c->ssl,
3965 				(void*)(((uint8_t*)&len)+c->tcp_byte_count),
3966 				(int)(sizeof(uint16_t)-c->tcp_byte_count));
3967 		}
3968 		if(r <= 0) {
3969 			int want = SSL_get_error(c->ssl, r);
3970 			if(want == SSL_ERROR_ZERO_RETURN) {
3971 				return 0; /* closed */
3972 			} else if(want == SSL_ERROR_WANT_READ) {
3973 				c->ssl_shake_state = comm_ssl_shake_hs_read;
3974 				comm_point_listen_for_rw(c, 1, 0);
3975 				return 1; /* wait for read condition */
3976 			} else if(want == SSL_ERROR_WANT_WRITE) {
3977 #ifdef USE_WINSOCK
3978 				ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
3979 #endif
3980 				return 1; /* write more later */
3981 			} else if(want == SSL_ERROR_SYSCALL) {
3982 #ifdef EPIPE
3983 				if(errno == EPIPE && verbosity < 2)
3984 					return 0; /* silence 'broken pipe' */
3985 #endif
3986 				if(errno != 0)
3987 					log_err("SSL_write syscall: %s",
3988 						strerror(errno));
3989 				return 0;
3990 			}
3991 			log_crypto_err_io("could not SSL_write", want);
3992 			return 0;
3993 		}
3994 		if(c->tcp_write_and_read) {
3995 			c->tcp_write_byte_count += r;
3996 			if(c->tcp_write_byte_count < sizeof(uint16_t))
3997 				return 1;
3998 		} else {
3999 			c->tcp_byte_count += r;
4000 			if(c->tcp_byte_count < sizeof(uint16_t))
4001 				return 1;
4002 			sldns_buffer_set_position(c->buffer, c->tcp_byte_count -
4003 				sizeof(uint16_t));
4004 		}
4005 		if((!c->tcp_write_and_read && sldns_buffer_remaining(c->buffer) == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == c->tcp_write_pkt_len + 2)) {
4006 			tcp_callback_writer(c);
4007 			return 1;
4008 		}
4009 	}
4010 	log_assert(c->tcp_write_and_read || sldns_buffer_remaining(c->buffer) > 0);
4011 	log_assert(!c->tcp_write_and_read || c->tcp_write_byte_count < c->tcp_write_pkt_len + 2);
4012 	ERR_clear_error();
4013 	if(c->tcp_write_and_read) {
4014 		r = SSL_write(c->ssl, (void*)(c->tcp_write_pkt + c->tcp_write_byte_count - 2),
4015 			(int)(c->tcp_write_pkt_len + 2 - c->tcp_write_byte_count));
4016 	} else {
4017 		r = SSL_write(c->ssl, (void*)sldns_buffer_current(c->buffer),
4018 			(int)sldns_buffer_remaining(c->buffer));
4019 	}
4020 	if(r <= 0) {
4021 		int want = SSL_get_error(c->ssl, r);
4022 		if(want == SSL_ERROR_ZERO_RETURN) {
4023 			return 0; /* closed */
4024 		} else if(want == SSL_ERROR_WANT_READ) {
4025 			c->ssl_shake_state = comm_ssl_shake_hs_read;
4026 			comm_point_listen_for_rw(c, 1, 0);
4027 			return 1; /* wait for read condition */
4028 		} else if(want == SSL_ERROR_WANT_WRITE) {
4029 #ifdef USE_WINSOCK
4030 			ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
4031 #endif
4032 			return 1; /* write more later */
4033 		} else if(want == SSL_ERROR_SYSCALL) {
4034 #ifdef EPIPE
4035 			if(errno == EPIPE && verbosity < 2)
4036 				return 0; /* silence 'broken pipe' */
4037 #endif
4038 			if(errno != 0)
4039 				log_err("SSL_write syscall: %s",
4040 					strerror(errno));
4041 			return 0;
4042 		}
4043 		log_crypto_err_io("could not SSL_write", want);
4044 		return 0;
4045 	}
4046 	if(c->tcp_write_and_read) {
4047 		c->tcp_write_byte_count += r;
4048 	} else {
4049 		sldns_buffer_skip(c->buffer, (ssize_t)r);
4050 	}
4051 
4052 	if((!c->tcp_write_and_read && sldns_buffer_remaining(c->buffer) == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == c->tcp_write_pkt_len + 2)) {
4053 		tcp_callback_writer(c);
4054 	}
4055 	return 1;
4056 #else
4057 	(void)c;
4058 	return 0;
4059 #endif /* HAVE_SSL */
4060 }
4061 
4062 /** handle ssl tcp connection with dns contents */
4063 static int
4064 ssl_handle_it(struct comm_point* c, int is_write)
4065 {
4066 	/* handle case where renegotiation wants read during write call
4067 	 * or write during read calls */
4068 	if(is_write && c->ssl_shake_state == comm_ssl_shake_hs_write)
4069 		return ssl_handle_read(c);
4070 	else if(!is_write && c->ssl_shake_state == comm_ssl_shake_hs_read)
4071 		return ssl_handle_write(c);
4072 	/* handle read events for read operation and write events for a
4073 	 * write operation */
4074 	else if(!is_write)
4075 		return ssl_handle_read(c);
4076 	return ssl_handle_write(c);
4077 }
4078 
4079 /**
4080  * Handle tcp reading callback.
4081  * @param fd: file descriptor of socket.
4082  * @param c: comm point to read from into buffer.
4083  * @param short_ok: if true, very short packets are OK (for comm_local).
4084  * @return: 0 on error
4085  */
4086 static int
4087 comm_point_tcp_handle_read(int fd, struct comm_point* c, int short_ok)
4088 {
4089 	ssize_t r;
4090 	int recv_initial = 0;
4091 	log_assert(c->type == comm_tcp || c->type == comm_local);
4092 	if(c->ssl)
4093 		return ssl_handle_it(c, 0);
4094 	if(!c->tcp_is_reading && !c->tcp_write_and_read)
4095 		return 0;
4096 
4097 	log_assert(fd != -1);
4098 	if(c->pp2_enabled && c->pp2_header_state != pp2_header_done) {
4099 		struct pp2_header* header = NULL;
4100 		size_t want_read_size = 0;
4101 		size_t current_read_size = 0;
4102 		if(c->pp2_header_state == pp2_header_none) {
4103 			want_read_size = PP2_HEADER_SIZE;
4104 			if(sldns_buffer_remaining(c->buffer)<want_read_size) {
4105 				log_err_addr("proxy_protocol: not enough "
4106 					"buffer size to read PROXYv2 header", "",
4107 					&c->repinfo.remote_addr,
4108 					c->repinfo.remote_addrlen);
4109 				return 0;
4110 			}
4111 			verbose(VERB_ALGO, "proxy_protocol: reading fixed "
4112 				"part of PROXYv2 header (len %lu)",
4113 				(unsigned long)want_read_size);
4114 			current_read_size = want_read_size;
4115 			if(c->tcp_byte_count < current_read_size) {
4116 				r = recv(fd, (void*)sldns_buffer_at(c->buffer,
4117 					c->tcp_byte_count),
4118 					current_read_size-c->tcp_byte_count, MSG_DONTWAIT);
4119 				if(r == 0) {
4120 					if(c->tcp_req_info)
4121 						return tcp_req_info_handle_read_close(c->tcp_req_info);
4122 					return 0;
4123 				} else if(r == -1) {
4124 					goto recv_error_initial;
4125 				}
4126 				c->tcp_byte_count += r;
4127 				sldns_buffer_skip(c->buffer, r);
4128 				if(c->tcp_byte_count != current_read_size) return 1;
4129 				c->pp2_header_state = pp2_header_init;
4130 			}
4131 		}
4132 		if(c->pp2_header_state == pp2_header_init) {
4133 			int err;
4134 			err = pp2_read_header(
4135 				sldns_buffer_begin(c->buffer),
4136 				sldns_buffer_limit(c->buffer));
4137 			if(err) {
4138 				log_err("proxy_protocol: could not parse "
4139 					"PROXYv2 header (%s)",
4140 					pp_lookup_error(err));
4141 				return 0;
4142 			}
4143 			header = (struct pp2_header*)sldns_buffer_begin(c->buffer);
4144 			want_read_size = ntohs(header->len);
4145 			if(sldns_buffer_limit(c->buffer) <
4146 				PP2_HEADER_SIZE + want_read_size) {
4147 				log_err_addr("proxy_protocol: not enough "
4148 					"buffer size to read PROXYv2 header", "",
4149 					&c->repinfo.remote_addr,
4150 					c->repinfo.remote_addrlen);
4151 				return 0;
4152 			}
4153 			verbose(VERB_ALGO, "proxy_protocol: reading variable "
4154 				"part of PROXYv2 header (len %lu)",
4155 				(unsigned long)want_read_size);
4156 			current_read_size = PP2_HEADER_SIZE + want_read_size;
4157 			if(want_read_size == 0) {
4158 				/* nothing more to read; header is complete */
4159 				c->pp2_header_state = pp2_header_done;
4160 			} else if(c->tcp_byte_count < current_read_size) {
4161 				r = recv(fd, (void*)sldns_buffer_at(c->buffer,
4162 					c->tcp_byte_count),
4163 					current_read_size-c->tcp_byte_count, MSG_DONTWAIT);
4164 				if(r == 0) {
4165 					if(c->tcp_req_info)
4166 						return tcp_req_info_handle_read_close(c->tcp_req_info);
4167 					return 0;
4168 				} else if(r == -1) {
4169 					goto recv_error;
4170 				}
4171 				c->tcp_byte_count += r;
4172 				sldns_buffer_skip(c->buffer, r);
4173 				if(c->tcp_byte_count != current_read_size) return 1;
4174 				c->pp2_header_state = pp2_header_done;
4175 			}
4176 		}
4177 		if(c->pp2_header_state != pp2_header_done || !header) {
4178 			log_err_addr("proxy_protocol: wrong state for the "
4179 				"PROXYv2 header", "", &c->repinfo.remote_addr,
4180 				c->repinfo.remote_addrlen);
4181 			return 0;
4182 		}
4183 		sldns_buffer_flip(c->buffer);
4184 		if(!consume_pp2_header(c->buffer, &c->repinfo, 1)) {
4185 			log_err_addr("proxy_protocol: could not consume "
4186 				"PROXYv2 header", "", &c->repinfo.remote_addr,
4187 				c->repinfo.remote_addrlen);
4188 			return 0;
4189 		}
4190 		verbose(VERB_ALGO, "proxy_protocol: successful read of "
4191 			"PROXYv2 header");
4192 		/* Clear and reset the buffer to read the following
4193 		    * DNS packet(s). */
4194 		sldns_buffer_clear(c->buffer);
4195 		c->tcp_byte_count = 0;
4196 		return 1;
4197 	}
4198 
4199 	if(c->tcp_byte_count < sizeof(uint16_t)) {
4200 		/* read length bytes */
4201 		r = recv(fd,(void*)sldns_buffer_at(c->buffer,c->tcp_byte_count),
4202 			sizeof(uint16_t)-c->tcp_byte_count, MSG_DONTWAIT);
4203 		if(r == 0) {
4204 			if(c->tcp_req_info)
4205 				return tcp_req_info_handle_read_close(c->tcp_req_info);
4206 			return 0;
4207 		} else if(r == -1) {
4208 			if(c->pp2_enabled) goto recv_error;
4209 			goto recv_error_initial;
4210 		}
4211 		c->tcp_byte_count += r;
4212 		if(c->tcp_byte_count != sizeof(uint16_t))
4213 			return 1;
4214 		if(sldns_buffer_read_u16_at(c->buffer, 0) >
4215 			sldns_buffer_capacity(c->buffer)) {
4216 			verbose(VERB_QUERY, "tcp: dropped larger than buffer");
4217 			return 0;
4218 		}
4219 		sldns_buffer_set_limit(c->buffer,
4220 			sldns_buffer_read_u16_at(c->buffer, 0));
4221 		if(!short_ok &&
4222 			sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
4223 			verbose(VERB_QUERY, "tcp: dropped bogus too short.");
4224 			return 0;
4225 		}
4226 		verbose(VERB_ALGO, "Reading tcp query of length %d",
4227 			(int)sldns_buffer_limit(c->buffer));
4228 	}
4229 
4230 	if(sldns_buffer_remaining(c->buffer) == 0)
4231 		log_err("in comm_point_tcp_handle_read buffer_remaining is "
4232 			"not > 0 as expected, continuing with (harmless) 0 "
4233 			"length recv");
4234 	r = recv(fd, (void*)sldns_buffer_current(c->buffer),
4235 		sldns_buffer_remaining(c->buffer), MSG_DONTWAIT);
4236 	if(r == 0) {
4237 		if(c->tcp_req_info)
4238 			return tcp_req_info_handle_read_close(c->tcp_req_info);
4239 		return 0;
4240 	} else if(r == -1) {
4241 		goto recv_error;
4242 	}
4243 	sldns_buffer_skip(c->buffer, r);
4244 	if(sldns_buffer_remaining(c->buffer) <= 0) {
4245 		tcp_callback_reader(c);
4246 	}
4247 	return 1;
4248 
4249 recv_error_initial:
4250 	recv_initial = 1;
4251 recv_error:
4252 #ifndef USE_WINSOCK
4253 	if(errno == EINTR || errno == EAGAIN)
4254 		return 1;
4255 #ifdef ECONNRESET
4256 	if(errno == ECONNRESET && verbosity < 2)
4257 		return 0; /* silence reset by peer */
4258 #endif
4259 	if(recv_initial) {
4260 #ifdef ECONNREFUSED
4261 		if(errno == ECONNREFUSED && verbosity < 2)
4262 			return 0; /* silence reset by peer */
4263 #endif
4264 #ifdef ENETUNREACH
4265 		if(errno == ENETUNREACH && verbosity < 2)
4266 			return 0; /* silence it */
4267 #endif
4268 #ifdef EHOSTDOWN
4269 		if(errno == EHOSTDOWN && verbosity < 2)
4270 			return 0; /* silence it */
4271 #endif
4272 #ifdef EHOSTUNREACH
4273 		if(errno == EHOSTUNREACH && verbosity < 2)
4274 			return 0; /* silence it */
4275 #endif
4276 #ifdef ENETDOWN
4277 		if(errno == ENETDOWN && verbosity < 2)
4278 			return 0; /* silence it */
4279 #endif
4280 #ifdef EACCES
4281 		if(errno == EACCES && verbosity < 2)
4282 			return 0; /* silence it */
4283 #endif
4284 #ifdef ENOTCONN
4285 		if(errno == ENOTCONN) {
4286 			log_err_addr("read (in tcp initial) failed and this "
4287 				"could be because TCP Fast Open is "
4288 				"enabled [--disable-tfo-client "
4289 				"--disable-tfo-server] but does not "
4290 				"work", sock_strerror(errno),
4291 				&c->repinfo.remote_addr,
4292 				c->repinfo.remote_addrlen);
4293 			return 0;
4294 		}
4295 #endif
4296 	}
4297 #else /* USE_WINSOCK */
4298 	if(recv_initial) {
4299 		if(WSAGetLastError() == WSAECONNREFUSED && verbosity < 2)
4300 			return 0;
4301 		if(WSAGetLastError() == WSAEHOSTDOWN && verbosity < 2)
4302 			return 0;
4303 		if(WSAGetLastError() == WSAEHOSTUNREACH && verbosity < 2)
4304 			return 0;
4305 		if(WSAGetLastError() == WSAENETDOWN && verbosity < 2)
4306 			return 0;
4307 		if(WSAGetLastError() == WSAENETUNREACH && verbosity < 2)
4308 			return 0;
4309 	}
4310 	if(WSAGetLastError() == WSAECONNRESET)
4311 		return 0;
4312 	if(WSAGetLastError() == WSAEINPROGRESS)
4313 		return 1;
4314 	if(WSAGetLastError() == WSAEWOULDBLOCK) {
4315 		ub_winsock_tcp_wouldblock(c->ev->ev,
4316 			UB_EV_READ);
4317 		return 1;
4318 	}
4319 #endif
4320 	log_err_addr((recv_initial?"read (in tcp initial)":"read (in tcp)"),
4321 		sock_strerror(errno), &c->repinfo.remote_addr,
4322 		c->repinfo.remote_addrlen);
4323 	return 0;
4324 }
4325 
4326 /**
4327  * Handle tcp writing callback.
4328  * @param fd: file descriptor of socket.
4329  * @param c: comm point to write buffer out of.
4330  * @return: 0 on error
4331  */
4332 static int
4333 comm_point_tcp_handle_write(int fd, struct comm_point* c)
4334 {
4335 	ssize_t r;
4336 	struct sldns_buffer *buffer;
4337 	log_assert(c->type == comm_tcp);
4338 #ifdef USE_DNSCRYPT
4339 	buffer = c->dnscrypt_buffer;
4340 #else
4341 	buffer = c->buffer;
4342 #endif
4343 	if(c->tcp_is_reading && !c->ssl && !c->tcp_write_and_read)
4344 		return 0;
4345 	log_assert(fd != -1);
4346 	if(((!c->tcp_write_and_read && c->tcp_byte_count == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == 0)) && c->tcp_check_nb_connect) {
4347 		/* check for pending error from nonblocking connect */
4348 		/* from Stevens, unix network programming, vol1, 3rd ed, p450*/
4349 		int error = 0;
4350 		socklen_t len = (socklen_t)sizeof(error);
4351 		if(getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&error,
4352 			&len) < 0){
4353 #ifndef USE_WINSOCK
4354 			error = errno; /* on solaris errno is error */
4355 #else /* USE_WINSOCK */
4356 			error = WSAGetLastError();
4357 #endif
4358 		}
4359 #ifndef USE_WINSOCK
4360 #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
4361 		if(error == EINPROGRESS || error == EWOULDBLOCK)
4362 			return 1; /* try again later */
4363 		else
4364 #endif
4365 		if(error != 0 && verbosity < 2)
4366 			return 0; /* silence lots of chatter in the logs */
4367                 else if(error != 0) {
4368 			log_err_addr("tcp connect", strerror(error),
4369 				&c->repinfo.remote_addr,
4370 				c->repinfo.remote_addrlen);
4371 #else /* USE_WINSOCK */
4372 		/* examine error */
4373 		if(error == WSAEINPROGRESS)
4374 			return 1;
4375 		else if(error == WSAEWOULDBLOCK) {
4376 			ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
4377 			return 1;
4378 		} else if(error != 0 && verbosity < 2)
4379 			return 0;
4380 		else if(error != 0) {
4381 			log_err_addr("tcp connect", wsa_strerror(error),
4382 				&c->repinfo.remote_addr,
4383 				c->repinfo.remote_addrlen);
4384 #endif /* USE_WINSOCK */
4385 			return 0;
4386 		}
4387 	}
4388 	if(c->ssl)
4389 		return ssl_handle_it(c, 1);
4390 
4391 #ifdef USE_MSG_FASTOPEN
4392 	/* Only try this on first use of a connection that uses tfo,
4393 	   otherwise fall through to normal write */
4394 	/* Also, TFO support on WINDOWS not implemented at the moment */
4395 	if(c->tcp_do_fastopen == 1) {
4396 		/* this form of sendmsg() does both a connect() and send() so need to
4397 		   look for various flavours of error*/
4398 		uint16_t len = htons(c->tcp_write_and_read?c->tcp_write_pkt_len:sldns_buffer_limit(buffer));
4399 		struct msghdr msg;
4400 		struct iovec iov[2];
4401 		c->tcp_do_fastopen = 0;
4402 		memset(&msg, 0, sizeof(msg));
4403 		if(c->tcp_write_and_read) {
4404 			iov[0].iov_base = (uint8_t*)&len + c->tcp_write_byte_count;
4405 			iov[0].iov_len = sizeof(uint16_t) - c->tcp_write_byte_count;
4406 			iov[1].iov_base = c->tcp_write_pkt;
4407 			iov[1].iov_len = c->tcp_write_pkt_len;
4408 		} else {
4409 			iov[0].iov_base = (uint8_t*)&len + c->tcp_byte_count;
4410 			iov[0].iov_len = sizeof(uint16_t) - c->tcp_byte_count;
4411 			iov[1].iov_base = sldns_buffer_begin(buffer);
4412 			iov[1].iov_len = sldns_buffer_limit(buffer);
4413 		}
4414 		log_assert(iov[0].iov_len > 0);
4415 		msg.msg_name = &c->repinfo.remote_addr;
4416 		msg.msg_namelen = c->repinfo.remote_addrlen;
4417 		msg.msg_iov = iov;
4418 		msg.msg_iovlen = 2;
4419 		r = sendmsg(fd, &msg, MSG_FASTOPEN);
4420 		if (r == -1) {
4421 #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
4422 			/* Handshake is underway, maybe because no TFO cookie available.
4423 			   Come back to write the message*/
4424 			if(errno == EINPROGRESS || errno == EWOULDBLOCK)
4425 				return 1;
4426 #endif
4427 			if(errno == EINTR || errno == EAGAIN)
4428 				return 1;
4429 			/* Not handling EISCONN here as shouldn't ever hit that case.*/
4430 			if(errno != EPIPE
4431 #ifdef EOPNOTSUPP
4432 				/* if /proc/sys/net/ipv4/tcp_fastopen is
4433 				 * disabled on Linux, sendmsg may return
4434 				 * 'Operation not supported', if so
4435 				 * fallthrough to ordinary connect. */
4436 				&& errno != EOPNOTSUPP
4437 #endif
4438 				&& errno != 0) {
4439 				if(verbosity < 2)
4440 					return 0; /* silence lots of chatter in the logs */
4441 				log_err_addr("tcp sendmsg", strerror(errno),
4442 					&c->repinfo.remote_addr,
4443 					c->repinfo.remote_addrlen);
4444 				return 0;
4445 			}
4446 			verbose(VERB_ALGO, "tcp sendmsg for fastopen failed (with %s), try normal connect", strerror(errno));
4447 			/* fallthrough to nonFASTOPEN
4448 			 * (MSG_FASTOPEN on Linux 3 produces EPIPE)
4449 			 * we need to perform connect() */
4450 			if(connect(fd, (struct sockaddr *)&c->repinfo.remote_addr,
4451 				c->repinfo.remote_addrlen) == -1) {
4452 #ifdef EINPROGRESS
4453 				if(errno == EINPROGRESS)
4454 					return 1; /* wait until connect done*/
4455 #endif
4456 #ifdef USE_WINSOCK
4457 				if(WSAGetLastError() == WSAEINPROGRESS ||
4458 					WSAGetLastError() == WSAEWOULDBLOCK)
4459 					return 1; /* wait until connect done*/
4460 #endif
4461 				if(tcp_connect_errno_needs_log(
4462 					(struct sockaddr *)&c->repinfo.remote_addr,
4463 					c->repinfo.remote_addrlen)) {
4464 					log_err_addr("outgoing tcp: connect after EPIPE for fastopen",
4465 						strerror(errno),
4466 						&c->repinfo.remote_addr,
4467 						c->repinfo.remote_addrlen);
4468 				}
4469 				return 0;
4470 			}
4471 
4472 		} else {
4473 			if(c->tcp_write_and_read) {
4474 				c->tcp_write_byte_count += r;
4475 				if(c->tcp_write_byte_count < sizeof(uint16_t))
4476 					return 1;
4477 			} else {
4478 				c->tcp_byte_count += r;
4479 				if(c->tcp_byte_count < sizeof(uint16_t))
4480 					return 1;
4481 				sldns_buffer_set_position(buffer, c->tcp_byte_count -
4482 					sizeof(uint16_t));
4483 			}
4484 			if((!c->tcp_write_and_read && sldns_buffer_remaining(buffer) == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == c->tcp_write_pkt_len + 2)) {
4485 				tcp_callback_writer(c);
4486 				return 1;
4487 			}
4488 		}
4489 	}
4490 #endif /* USE_MSG_FASTOPEN */
4491 
4492 	if((c->tcp_write_and_read?c->tcp_write_byte_count:c->tcp_byte_count) < sizeof(uint16_t)) {
4493 		uint16_t len = htons(c->tcp_write_and_read?c->tcp_write_pkt_len:sldns_buffer_limit(buffer));
4494 #ifdef HAVE_WRITEV
4495 		struct iovec iov[2];
4496 		if(c->tcp_write_and_read) {
4497 			iov[0].iov_base = (uint8_t*)&len + c->tcp_write_byte_count;
4498 			iov[0].iov_len = sizeof(uint16_t) - c->tcp_write_byte_count;
4499 			iov[1].iov_base = c->tcp_write_pkt;
4500 			iov[1].iov_len = c->tcp_write_pkt_len;
4501 		} else {
4502 			iov[0].iov_base = (uint8_t*)&len + c->tcp_byte_count;
4503 			iov[0].iov_len = sizeof(uint16_t) - c->tcp_byte_count;
4504 			iov[1].iov_base = sldns_buffer_begin(buffer);
4505 			iov[1].iov_len = sldns_buffer_limit(buffer);
4506 		}
4507 		log_assert(iov[0].iov_len > 0);
4508 		r = writev(fd, iov, 2);
4509 #else /* HAVE_WRITEV */
4510 		if(c->tcp_write_and_read) {
4511 			r = send(fd, (void*)(((uint8_t*)&len)+c->tcp_write_byte_count),
4512 				sizeof(uint16_t)-c->tcp_write_byte_count, 0);
4513 		} else {
4514 			r = send(fd, (void*)(((uint8_t*)&len)+c->tcp_byte_count),
4515 				sizeof(uint16_t)-c->tcp_byte_count, 0);
4516 		}
4517 #endif /* HAVE_WRITEV */
4518 		if(r == -1) {
4519 #ifndef USE_WINSOCK
4520 #  ifdef EPIPE
4521                 	if(errno == EPIPE && verbosity < 2)
4522                         	return 0; /* silence 'broken pipe' */
4523   #endif
4524 			if(errno == EINTR || errno == EAGAIN)
4525 				return 1;
4526 #ifdef ECONNRESET
4527 			if(errno == ECONNRESET && verbosity < 2)
4528 				return 0; /* silence reset by peer */
4529 #endif
4530 #  ifdef HAVE_WRITEV
4531 			log_err_addr("tcp writev", strerror(errno),
4532 				&c->repinfo.remote_addr,
4533 				c->repinfo.remote_addrlen);
4534 #  else /* HAVE_WRITEV */
4535 			log_err_addr("tcp send s", strerror(errno),
4536 				&c->repinfo.remote_addr,
4537 				c->repinfo.remote_addrlen);
4538 #  endif /* HAVE_WRITEV */
4539 #else
4540 			if(WSAGetLastError() == WSAENOTCONN)
4541 				return 1;
4542 			if(WSAGetLastError() == WSAEINPROGRESS)
4543 				return 1;
4544 			if(WSAGetLastError() == WSAEWOULDBLOCK) {
4545 				ub_winsock_tcp_wouldblock(c->ev->ev,
4546 					UB_EV_WRITE);
4547 				return 1;
4548 			}
4549 			if(WSAGetLastError() == WSAECONNRESET && verbosity < 2)
4550 				return 0; /* silence reset by peer */
4551 			log_err_addr("tcp send s",
4552 				wsa_strerror(WSAGetLastError()),
4553 				&c->repinfo.remote_addr,
4554 				c->repinfo.remote_addrlen);
4555 #endif
4556 			return 0;
4557 		}
4558 		if(c->tcp_write_and_read) {
4559 			c->tcp_write_byte_count += r;
4560 			if(c->tcp_write_byte_count < sizeof(uint16_t))
4561 				return 1;
4562 		} else {
4563 			c->tcp_byte_count += r;
4564 			if(c->tcp_byte_count < sizeof(uint16_t))
4565 				return 1;
4566 			sldns_buffer_set_position(buffer, c->tcp_byte_count -
4567 				sizeof(uint16_t));
4568 		}
4569 		if((!c->tcp_write_and_read && sldns_buffer_remaining(buffer) == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == c->tcp_write_pkt_len + 2)) {
4570 			tcp_callback_writer(c);
4571 			return 1;
4572 		}
4573 	}
4574 	log_assert(c->tcp_write_and_read || sldns_buffer_remaining(buffer) > 0);
4575 	log_assert(!c->tcp_write_and_read || c->tcp_write_byte_count < c->tcp_write_pkt_len + 2);
4576 	if(c->tcp_write_and_read) {
4577 		r = send(fd, (void*)(c->tcp_write_pkt + c->tcp_write_byte_count - 2),
4578 			c->tcp_write_pkt_len + 2 - c->tcp_write_byte_count, 0);
4579 	} else {
4580 		r = send(fd, (void*)sldns_buffer_current(buffer),
4581 			sldns_buffer_remaining(buffer), 0);
4582 	}
4583 	if(r == -1) {
4584 #ifndef USE_WINSOCK
4585 		if(errno == EINTR || errno == EAGAIN)
4586 			return 1;
4587 #ifdef ECONNRESET
4588 		if(errno == ECONNRESET && verbosity < 2)
4589 			return 0; /* silence reset by peer */
4590 #endif
4591 #else
4592 		if(WSAGetLastError() == WSAEINPROGRESS)
4593 			return 1;
4594 		if(WSAGetLastError() == WSAEWOULDBLOCK) {
4595 			ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
4596 			return 1;
4597 		}
4598 		if(WSAGetLastError() == WSAECONNRESET && verbosity < 2)
4599 			return 0; /* silence reset by peer */
4600 #endif
4601 		log_err_addr("tcp send r", sock_strerror(errno),
4602 			&c->repinfo.remote_addr,
4603 			c->repinfo.remote_addrlen);
4604 		return 0;
4605 	}
4606 	if(c->tcp_write_and_read) {
4607 		c->tcp_write_byte_count += r;
4608 	} else {
4609 		sldns_buffer_skip(buffer, r);
4610 	}
4611 
4612 	if((!c->tcp_write_and_read && sldns_buffer_remaining(buffer) == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == c->tcp_write_pkt_len + 2)) {
4613 		tcp_callback_writer(c);
4614 	}
4615 
4616 	return 1;
4617 }
4618 
4619 /** read again to drain buffers when there could be more to read, returns 0
4620  * on failure which means the comm point is closed. */
4621 static int
4622 tcp_req_info_read_again(int fd, struct comm_point* c)
4623 {
4624 	while(c->tcp_req_info->read_again) {
4625 		int r;
4626 		c->tcp_req_info->read_again = 0;
4627 		if(c->tcp_is_reading)
4628 			r = comm_point_tcp_handle_read(fd, c, 0);
4629 		else 	r = comm_point_tcp_handle_write(fd, c);
4630 		if(!r) {
4631 			reclaim_tcp_handler(c);
4632 			if(!c->tcp_do_close) {
4633 				fptr_ok(fptr_whitelist_comm_point(
4634 					c->callback));
4635 				(void)(*c->callback)(c, c->cb_arg,
4636 					NETEVENT_CLOSED, NULL);
4637 			}
4638 			return 0;
4639 		}
4640 	}
4641 	return 1;
4642 }
4643 
4644 /** read again to drain buffers when there could be more to read */
4645 static void
4646 tcp_more_read_again(int fd, struct comm_point* c)
4647 {
4648 	/* if the packet is done, but another one could be waiting on
4649 	 * the connection, the callback signals this, and we try again */
4650 	/* this continues until the read routines get EAGAIN or so,
4651 	 * and thus does not call the callback, and the bool is 0 */
4652 	int* moreread = c->tcp_more_read_again;
4653 	while(moreread && *moreread) {
4654 		*moreread = 0;
4655 		if(!comm_point_tcp_handle_read(fd, c, 0)) {
4656 			reclaim_tcp_handler(c);
4657 			if(!c->tcp_do_close) {
4658 				fptr_ok(fptr_whitelist_comm_point(
4659 					c->callback));
4660 				(void)(*c->callback)(c, c->cb_arg,
4661 					NETEVENT_CLOSED, NULL);
4662 			}
4663 			return;
4664 		}
4665 	}
4666 }
4667 
4668 /** write again to fill up when there could be more to write */
4669 static void
4670 tcp_more_write_again(int fd, struct comm_point* c)
4671 {
4672 	/* if the packet is done, but another is waiting to be written,
4673 	 * the callback signals it and we try again. */
4674 	/* this continues until the write routines get EAGAIN or so,
4675 	 * and thus does not call the callback, and the bool is 0 */
4676 	int* morewrite = c->tcp_more_write_again;
4677 	while(morewrite && *morewrite) {
4678 		*morewrite = 0;
4679 		if(!comm_point_tcp_handle_write(fd, c)) {
4680 			reclaim_tcp_handler(c);
4681 			if(!c->tcp_do_close) {
4682 				fptr_ok(fptr_whitelist_comm_point(
4683 					c->callback));
4684 				(void)(*c->callback)(c, c->cb_arg,
4685 					NETEVENT_CLOSED, NULL);
4686 			}
4687 			return;
4688 		}
4689 	}
4690 }
4691 
4692 void
4693 comm_point_tcp_handle_callback(int fd, short event, void* arg)
4694 {
4695 	struct comm_point* c = (struct comm_point*)arg;
4696 	log_assert(c->type == comm_tcp);
4697 	ub_comm_base_now(c->ev->base);
4698 
4699 	if(c->fd == -1 || c->fd != fd)
4700 		return; /* duplicate event, but commpoint closed. */
4701 
4702 #ifdef USE_DNSCRYPT
4703 	/* Initialize if this is a dnscrypt socket */
4704 	if(c->tcp_parent) {
4705 		c->dnscrypt = c->tcp_parent->dnscrypt;
4706 	}
4707 	if(c->dnscrypt && c->dnscrypt_buffer == c->buffer) {
4708 		c->dnscrypt_buffer = sldns_buffer_new(sldns_buffer_capacity(c->buffer));
4709 		if(!c->dnscrypt_buffer) {
4710 			log_err("Could not allocate dnscrypt buffer");
4711 			reclaim_tcp_handler(c);
4712 			if(!c->tcp_do_close) {
4713 				fptr_ok(fptr_whitelist_comm_point(
4714 					c->callback));
4715 				(void)(*c->callback)(c, c->cb_arg,
4716 					NETEVENT_CLOSED, NULL);
4717 			}
4718 			return;
4719 		}
4720 	}
4721 #endif
4722 
4723 	if((event&UB_EV_TIMEOUT)) {
4724 		verbose(VERB_QUERY, "tcp took too long, dropped");
4725 		reclaim_tcp_handler(c);
4726 		if(!c->tcp_do_close) {
4727 			fptr_ok(fptr_whitelist_comm_point(c->callback));
4728 			(void)(*c->callback)(c, c->cb_arg,
4729 				NETEVENT_TIMEOUT, NULL);
4730 		}
4731 		return;
4732 	}
4733 	if((event&UB_EV_READ)
4734 #ifdef USE_MSG_FASTOPEN
4735 		&& !(c->tcp_do_fastopen && (event&UB_EV_WRITE))
4736 #endif
4737 		) {
4738 		int has_tcpq = (c->tcp_req_info != NULL);
4739 		int* moreread = c->tcp_more_read_again;
4740 		if(!comm_point_tcp_handle_read(fd, c, 0)) {
4741 			reclaim_tcp_handler(c);
4742 			if(!c->tcp_do_close) {
4743 				fptr_ok(fptr_whitelist_comm_point(
4744 					c->callback));
4745 				(void)(*c->callback)(c, c->cb_arg,
4746 					NETEVENT_CLOSED, NULL);
4747 			}
4748 			return;
4749 		}
4750 		if(has_tcpq && c->tcp_req_info && c->tcp_req_info->read_again) {
4751 			if(!tcp_req_info_read_again(fd, c))
4752 				return;
4753 		}
4754 		if(moreread && *moreread)
4755 			tcp_more_read_again(fd, c);
4756 		return;
4757 	}
4758 	if((event&UB_EV_WRITE)) {
4759 		int has_tcpq = (c->tcp_req_info != NULL);
4760 		int* morewrite = c->tcp_more_write_again;
4761 		if(!comm_point_tcp_handle_write(fd, c)) {
4762 			reclaim_tcp_handler(c);
4763 			if(!c->tcp_do_close) {
4764 				fptr_ok(fptr_whitelist_comm_point(
4765 					c->callback));
4766 				(void)(*c->callback)(c, c->cb_arg,
4767 					NETEVENT_CLOSED, NULL);
4768 			}
4769 			return;
4770 		}
4771 		if(has_tcpq && c->tcp_req_info && c->tcp_req_info->read_again) {
4772 			if(!tcp_req_info_read_again(fd, c))
4773 				return;
4774 		}
4775 		if(morewrite && *morewrite)
4776 			tcp_more_write_again(fd, c);
4777 		return;
4778 	}
4779 	log_err("Ignored event %d for tcphdl.", event);
4780 }
4781 
4782 /** Make http handler free for next assignment */
4783 static void
4784 reclaim_http_handler(struct comm_point* c)
4785 {
4786 	log_assert(c->type == comm_http);
4787 	if(c->ssl) {
4788 #ifdef HAVE_SSL
4789 		SSL_shutdown(c->ssl);
4790 		SSL_free(c->ssl);
4791 		c->ssl = NULL;
4792 #endif
4793 	}
4794 	comm_point_close(c);
4795 	if(c->tcp_parent && !c->is_in_tcp_free) {
4796 		/* Should not happen: bad tcp_free state in reclaim_http. */
4797 		log_assert(c->tcp_free == NULL);
4798 		log_assert(c->tcp_parent->cur_tcp_count > 0);
4799 		c->tcp_parent->cur_tcp_count--;
4800 		c->tcp_free = c->tcp_parent->tcp_free;
4801 		c->tcp_parent->tcp_free = c;
4802 		c->is_in_tcp_free = 1;
4803 		if(!c->tcp_free) {
4804 			/* re-enable listening on accept socket */
4805 			comm_point_start_listening(c->tcp_parent, -1, -1);
4806 		}
4807 	}
4808 }
4809 
4810 /** read more data for http (with ssl) */
4811 static int
4812 ssl_http_read_more(struct comm_point* c)
4813 {
4814 #ifdef HAVE_SSL
4815 	int r;
4816 	log_assert(sldns_buffer_remaining(c->buffer) > 0);
4817 	ERR_clear_error();
4818 	r = SSL_read(c->ssl, (void*)sldns_buffer_current(c->buffer),
4819 		(int)sldns_buffer_remaining(c->buffer));
4820 	if(r <= 0) {
4821 		int want = SSL_get_error(c->ssl, r);
4822 		if(want == SSL_ERROR_ZERO_RETURN) {
4823 			return 0; /* shutdown, closed */
4824 		} else if(want == SSL_ERROR_WANT_READ) {
4825 			return 1; /* read more later */
4826 		} else if(want == SSL_ERROR_WANT_WRITE) {
4827 			c->ssl_shake_state = comm_ssl_shake_hs_write;
4828 			comm_point_listen_for_rw(c, 0, 1);
4829 			return 1;
4830 		} else if(want == SSL_ERROR_SYSCALL) {
4831 #ifdef ECONNRESET
4832 			if(errno == ECONNRESET && verbosity < 2)
4833 				return 0; /* silence reset by peer */
4834 #endif
4835 			if(errno != 0)
4836 				log_err("SSL_read syscall: %s",
4837 					strerror(errno));
4838 			return 0;
4839 		}
4840 		log_crypto_err_io("could not SSL_read", want);
4841 		return 0;
4842 	}
4843 	verbose(VERB_ALGO, "ssl http read more skip to %d + %d",
4844 		(int)sldns_buffer_position(c->buffer), (int)r);
4845 	sldns_buffer_skip(c->buffer, (ssize_t)r);
4846 	return 1;
4847 #else
4848 	(void)c;
4849 	return 0;
4850 #endif /* HAVE_SSL */
4851 }
4852 
4853 /** read more data for http */
4854 static int
4855 http_read_more(int fd, struct comm_point* c)
4856 {
4857 	ssize_t r;
4858 	log_assert(sldns_buffer_remaining(c->buffer) > 0);
4859 	r = recv(fd, (void*)sldns_buffer_current(c->buffer),
4860 		sldns_buffer_remaining(c->buffer), MSG_DONTWAIT);
4861 	if(r == 0) {
4862 		return 0;
4863 	} else if(r == -1) {
4864 #ifndef USE_WINSOCK
4865 		if(errno == EINTR || errno == EAGAIN)
4866 			return 1;
4867 #else /* USE_WINSOCK */
4868 		if(WSAGetLastError() == WSAECONNRESET)
4869 			return 0;
4870 		if(WSAGetLastError() == WSAEINPROGRESS)
4871 			return 1;
4872 		if(WSAGetLastError() == WSAEWOULDBLOCK) {
4873 			ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
4874 			return 1;
4875 		}
4876 #endif
4877 		log_err_addr("read (in http r)", sock_strerror(errno),
4878 			&c->repinfo.remote_addr, c->repinfo.remote_addrlen);
4879 		return 0;
4880 	}
4881 	verbose(VERB_ALGO, "http read more skip to %d + %d",
4882 		(int)sldns_buffer_position(c->buffer), (int)r);
4883 	sldns_buffer_skip(c->buffer, r);
4884 	return 1;
4885 }
4886 
4887 /** return true if http header has been read (one line complete) */
4888 static int
4889 http_header_done(sldns_buffer* buf)
4890 {
4891 	size_t i;
4892 	for(i=sldns_buffer_position(buf); i<sldns_buffer_limit(buf); i++) {
4893 		/* there was a \r before the \n, but we ignore that */
4894 		if((char)sldns_buffer_read_u8_at(buf, i) == '\n')
4895 			return 1;
4896 	}
4897 	return 0;
4898 }
4899 
4900 /** return character string into buffer for header line, moves buffer
4901  * past that line and puts zero terminator into linefeed-newline */
4902 static char*
4903 http_header_line(sldns_buffer* buf)
4904 {
4905 	char* result = (char*)sldns_buffer_current(buf);
4906 	size_t i;
4907 	for(i=sldns_buffer_position(buf); i<sldns_buffer_limit(buf); i++) {
4908 		/* terminate the string on the \r */
4909 		if((char)sldns_buffer_read_u8_at(buf, i) == '\r')
4910 			sldns_buffer_write_u8_at(buf, i, 0);
4911 		/* terminate on the \n and skip past the it and done */
4912 		if((char)sldns_buffer_read_u8_at(buf, i) == '\n') {
4913 			sldns_buffer_write_u8_at(buf, i, 0);
4914 			sldns_buffer_set_position(buf, i+1);
4915 			return result;
4916 		}
4917 	}
4918 	return NULL;
4919 }
4920 
4921 /** move unread buffer to start and clear rest for putting the rest into it */
4922 static void
4923 http_moveover_buffer(sldns_buffer* buf)
4924 {
4925 	size_t pos = sldns_buffer_position(buf);
4926 	size_t len = sldns_buffer_remaining(buf);
4927 	sldns_buffer_clear(buf);
4928 	memmove(sldns_buffer_begin(buf), sldns_buffer_at(buf, pos), len);
4929 	sldns_buffer_set_position(buf, len);
4930 }
4931 
4932 /** a http header is complete, process it */
4933 static int
4934 http_process_initial_header(struct comm_point* c)
4935 {
4936 	char* line = http_header_line(c->buffer);
4937 	if(!line) return 1;
4938 	verbose(VERB_ALGO, "http header: %s", line);
4939 	if(strncasecmp(line, "HTTP/1.1 ", 9) == 0) {
4940 		/* check returncode */
4941 		if(line[9] != '2') {
4942 			verbose(VERB_ALGO, "http bad status %s", line+9);
4943 			return 0;
4944 		}
4945 	} else if(strncasecmp(line, "Content-Length: ", 16) == 0) {
4946 		if(!c->http_is_chunked) {
4947 			char* end = NULL;
4948 			long long cl;
4949 			errno = 0;
4950 			cl = strtoll(line+16, &end, 10);
4951 			if(end == line+16 || errno != 0 || cl < 0) {
4952 				verbose(VERB_ALGO, "http invalid Content-Length: " ARG_LL "d", cl);
4953 				return 0; /* reject */
4954 			}
4955 			c->tcp_byte_count = (size_t)cl;
4956 		}
4957 	} else if(strncasecmp(line, "Transfer-Encoding: chunked", 19+7) == 0) {
4958 		c->tcp_byte_count = 0;
4959 		c->http_is_chunked = 1;
4960 	} else if(line[0] == 0) {
4961 		/* end of initial headers */
4962 		c->http_in_headers = 0;
4963 		if(c->http_is_chunked)
4964 			c->http_in_chunk_headers = 1;
4965 		/* remove header text from front of buffer
4966 		 * the buffer is going to be used to return the data segment
4967 		 * itself and we don't want the header to get returned
4968 		 * prepended with it */
4969 		http_moveover_buffer(c->buffer);
4970 		sldns_buffer_flip(c->buffer);
4971 		return 1;
4972 	}
4973 	/* ignore other headers */
4974 	return 1;
4975 }
4976 
4977 /** a chunk header is complete, process it, return 0=fail, 1=continue next
4978  * header line, 2=done with chunked transfer*/
4979 static int
4980 http_process_chunk_header(struct comm_point* c)
4981 {
4982 	char* line = http_header_line(c->buffer);
4983 	if(!line) return 1;
4984 	if(c->http_in_chunk_headers == 3) {
4985 		verbose(VERB_ALGO, "http chunk trailer: %s", line);
4986 		/* are we done ? */
4987 		if(line[0] == 0 && c->tcp_byte_count == 0) {
4988 			/* callback of http reader when NETEVENT_DONE,
4989 			 * end of data, with no data in buffer */
4990 			sldns_buffer_set_position(c->buffer, 0);
4991 			sldns_buffer_set_limit(c->buffer, 0);
4992 			fptr_ok(fptr_whitelist_comm_point(c->callback));
4993 			(void)(*c->callback)(c, c->cb_arg, NETEVENT_DONE, NULL);
4994 			/* return that we are done */
4995 			return 2;
4996 		}
4997 		if(line[0] == 0) {
4998 			/* continue with header of the next chunk */
4999 			c->http_in_chunk_headers = 1;
5000 			/* remove header text from front of buffer */
5001 			http_moveover_buffer(c->buffer);
5002 			sldns_buffer_flip(c->buffer);
5003 			return 1;
5004 		}
5005 		/* ignore further trail headers */
5006 		return 1;
5007 	}
5008 	verbose(VERB_ALGO, "http chunk header: %s", line);
5009 	if(c->http_in_chunk_headers == 1) {
5010 		/* read chunked start line */
5011 		char* end = NULL;
5012 		long chunk_sz;
5013 		errno = 0;
5014 		chunk_sz = strtol(line, &end, 16);
5015 		if(end == line || errno != 0 || chunk_sz < 0) {
5016 			verbose(VERB_ALGO, "http invalid chunk size: %ld",
5017 				chunk_sz);
5018 			return 0;
5019 		}
5020 		c->tcp_byte_count = (size_t)chunk_sz;
5021 		c->http_in_chunk_headers = 0;
5022 		/* remove header text from front of buffer */
5023 		http_moveover_buffer(c->buffer);
5024 		sldns_buffer_flip(c->buffer);
5025 		if(c->tcp_byte_count == 0) {
5026 			/* done with chunks, process chunk_trailer lines */
5027 			c->http_in_chunk_headers = 3;
5028 		}
5029 		return 1;
5030 	}
5031 	/* ignore other headers */
5032 	return 1;
5033 }
5034 
5035 /** handle nonchunked data segment, 0=fail, 1=wait */
5036 static int
5037 http_nonchunk_segment(struct comm_point* c)
5038 {
5039 	/* c->buffer at position..limit has new data we read in.
5040 	 * the buffer itself is full of nonchunked data.
5041 	 * we are looking to read tcp_byte_count more data
5042 	 * and then the transfer is done. */
5043 	size_t remainbufferlen;
5044 	size_t got_now = sldns_buffer_limit(c->buffer);
5045 	if(c->tcp_byte_count <= got_now) {
5046 		/* done, this is the last data fragment */
5047 		c->http_stored = 0;
5048 		sldns_buffer_set_position(c->buffer, 0);
5049 		fptr_ok(fptr_whitelist_comm_point(c->callback));
5050 		(void)(*c->callback)(c, c->cb_arg, NETEVENT_DONE, NULL);
5051 		return 1;
5052 	}
5053 	/* if we have the buffer space,
5054 	 * read more data collected into the buffer */
5055 	remainbufferlen = sldns_buffer_capacity(c->buffer) -
5056 		sldns_buffer_limit(c->buffer);
5057 	if(remainbufferlen+got_now >= c->tcp_byte_count ||
5058 		remainbufferlen >= (size_t)(c->ssl?16384:2048)) {
5059 		size_t total = sldns_buffer_limit(c->buffer);
5060 		sldns_buffer_clear(c->buffer);
5061 		sldns_buffer_set_position(c->buffer, total);
5062 		c->http_stored = total;
5063 		/* return and wait to read more */
5064 		return 1;
5065 	}
5066 	/* call callback with this data amount, then
5067 	 * wait for more */
5068 	c->tcp_byte_count -= got_now;
5069 	c->http_stored = 0;
5070 	sldns_buffer_set_position(c->buffer, 0);
5071 	fptr_ok(fptr_whitelist_comm_point(c->callback));
5072 	(void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, NULL);
5073 	/* c->callback has to buffer_clear(c->buffer). */
5074 	/* return and wait to read more */
5075 	return 1;
5076 }
5077 
5078 /** handle chunked data segment, return 0=fail, 1=wait, 2=process more */
5079 static int
5080 http_chunked_segment(struct comm_point* c)
5081 {
5082 	/* the c->buffer has from position..limit new data we read. */
5083 	/* the current chunk has length tcp_byte_count.
5084 	 * once we read that read more chunk headers.
5085 	 */
5086 	size_t remainbufferlen;
5087 	size_t got_now = sldns_buffer_limit(c->buffer) - c->http_stored;
5088 	verbose(VERB_ALGO, "http_chunked_segment: got now %d, tcpbytcount %d, http_stored %d, buffer pos %d, buffer limit %d", (int)got_now, (int)c->tcp_byte_count, (int)c->http_stored, (int)sldns_buffer_position(c->buffer), (int)sldns_buffer_limit(c->buffer));
5089 	if(c->tcp_byte_count <= got_now) {
5090 		/* the chunk has completed (with perhaps some extra data
5091 		 * from next chunk header and next chunk) */
5092 		/* save too much info into temp buffer */
5093 		size_t fraglen;
5094 		struct comm_reply repinfo;
5095 		c->http_stored = 0;
5096 		sldns_buffer_skip(c->buffer, (ssize_t)c->tcp_byte_count);
5097 		sldns_buffer_clear(c->http_temp);
5098 		if(sldns_buffer_remaining(c->buffer) >
5099 			sldns_buffer_capacity(c->http_temp)) {
5100 			verbose(VERB_OPS, "http chunked: surplus %d exceeds "
5101 				"temp buffer %d", (int)sldns_buffer_remaining(
5102 				c->buffer), (int)sldns_buffer_capacity(
5103 				c->http_temp));
5104 			return 0;
5105 		}
5106 		sldns_buffer_write(c->http_temp,
5107 			sldns_buffer_current(c->buffer),
5108 			sldns_buffer_remaining(c->buffer));
5109 		sldns_buffer_flip(c->http_temp);
5110 
5111 		/* callback with this fragment */
5112 		fraglen = sldns_buffer_position(c->buffer);
5113 		sldns_buffer_set_position(c->buffer, 0);
5114 		sldns_buffer_set_limit(c->buffer, fraglen);
5115 		repinfo = c->repinfo;
5116 		fptr_ok(fptr_whitelist_comm_point(c->callback));
5117 		(void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, &repinfo);
5118 		/* c->callback has to buffer_clear(). */
5119 
5120 		/* is commpoint deleted? */
5121 		if(!repinfo.c) {
5122 			return 1;
5123 		}
5124 		/* copy waiting info */
5125 		sldns_buffer_clear(c->buffer);
5126 		sldns_buffer_write(c->buffer,
5127 			sldns_buffer_begin(c->http_temp),
5128 			sldns_buffer_remaining(c->http_temp));
5129 		sldns_buffer_flip(c->buffer);
5130 		/* process end of chunk trailer header lines, until
5131 		 * an empty line */
5132 		c->http_in_chunk_headers = 3;
5133 		/* process more data in buffer (if any) */
5134 		return 2;
5135 	}
5136 	c->tcp_byte_count -= got_now;
5137 
5138 	/* if we have the buffer space,
5139 	 * read more data collected into the buffer */
5140 	remainbufferlen = sldns_buffer_capacity(c->buffer) -
5141 		sldns_buffer_limit(c->buffer);
5142 	if(remainbufferlen >= c->tcp_byte_count ||
5143 		remainbufferlen >= 2048) {
5144 		size_t total = sldns_buffer_limit(c->buffer);
5145 		sldns_buffer_clear(c->buffer);
5146 		sldns_buffer_set_position(c->buffer, total);
5147 		c->http_stored = total;
5148 		/* return and wait to read more */
5149 		return 1;
5150 	}
5151 
5152 	/* callback of http reader for a new part of the data */
5153 	c->http_stored = 0;
5154 	sldns_buffer_set_position(c->buffer, 0);
5155 	fptr_ok(fptr_whitelist_comm_point(c->callback));
5156 	(void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, NULL);
5157 	/* c->callback has to buffer_clear(c->buffer). */
5158 	/* return and wait to read more */
5159 	return 1;
5160 }
5161 
5162 #ifdef HAVE_NGHTTP2
5163 /** Create new http2 session. Called when creating handling comm point. */
5164 static struct http2_session* http2_session_create(struct comm_point* c)
5165 {
5166 	struct http2_session* session = calloc(1, sizeof(*session));
5167 	if(!session) {
5168 		log_err("malloc failure while creating http2 session");
5169 		return NULL;
5170 	}
5171 	session->c = c;
5172 
5173 	return session;
5174 }
5175 #endif
5176 
5177 /** Delete http2 session. After closing connection or on error */
5178 static void http2_session_delete(struct http2_session* h2_session)
5179 {
5180 #ifdef HAVE_NGHTTP2
5181 	if(h2_session->callbacks)
5182 		nghttp2_session_callbacks_del(h2_session->callbacks);
5183 	free(h2_session);
5184 #else
5185 	(void)h2_session;
5186 #endif
5187 }
5188 
5189 #ifdef HAVE_NGHTTP2
5190 struct http2_stream* http2_stream_create(int32_t stream_id)
5191 {
5192 	struct http2_stream* h2_stream = calloc(1, sizeof(*h2_stream));
5193 	if(!h2_stream) {
5194 		log_err("malloc failure while creating http2 stream");
5195 		return NULL;
5196 	}
5197 	h2_stream->stream_id = stream_id;
5198 	return h2_stream;
5199 }
5200 #endif
5201 
5202 void http2_stream_add_meshstate(struct http2_stream* h2_stream,
5203 	struct mesh_area* mesh, struct mesh_state* m)
5204 {
5205 	h2_stream->mesh = mesh;
5206 	h2_stream->mesh_state = m;
5207 }
5208 
5209 void http2_stream_remove_mesh_state(struct http2_stream* h2_stream)
5210 {
5211 	if(!h2_stream)
5212 		return;
5213 	h2_stream->mesh_state = NULL;
5214 }
5215 
5216 #ifdef HAVE_NGHTTP2
5217 void http2_session_add_stream(struct http2_session* h2_session,
5218 	struct http2_stream* h2_stream)
5219 {
5220 	if(h2_session->first_stream)
5221 		h2_session->first_stream->prev = h2_stream;
5222 	h2_stream->next = h2_session->first_stream;
5223 	h2_session->first_stream = h2_stream;
5224 }
5225 
5226 /** remove stream from session linked list. After stream close callback or
5227  * closing connection */
5228 static void http2_session_remove_stream(struct http2_session* h2_session,
5229 	struct http2_stream* h2_stream)
5230 {
5231 	if(h2_stream->prev)
5232 		h2_stream->prev->next = h2_stream->next;
5233 	else
5234 		h2_session->first_stream = h2_stream->next;
5235 	if(h2_stream->next)
5236 		h2_stream->next->prev = h2_stream->prev;
5237 
5238 }
5239 
5240 int http2_stream_close_cb(nghttp2_session* ATTR_UNUSED(session),
5241 	int32_t stream_id, uint32_t ATTR_UNUSED(error_code), void* cb_arg)
5242 {
5243 	struct http2_stream* h2_stream;
5244 	struct http2_session* h2_session = (struct http2_session*)cb_arg;
5245 	if(!(h2_stream = nghttp2_session_get_stream_user_data(
5246 		h2_session->session, stream_id))) {
5247 		return 0;
5248 	}
5249 	http2_session_remove_stream(h2_session, h2_stream);
5250 	http2_stream_delete(h2_session, h2_stream);
5251 	return 0;
5252 }
5253 
5254 ssize_t http2_recv_cb(nghttp2_session* ATTR_UNUSED(session), uint8_t* buf,
5255 	size_t len, int ATTR_UNUSED(flags), void* cb_arg)
5256 {
5257 	struct http2_session* h2_session = (struct http2_session*)cb_arg;
5258 	ssize_t ret;
5259 
5260 	log_assert(h2_session->c->type == comm_http);
5261 	log_assert(h2_session->c->h2_session);
5262 	if(++h2_session->reads_count > h2_session->c->http2_max_streams) {
5263 		/* We are somewhat arbitrarily capping the amount of
5264 		 * consecutive reads on the HTTP2 session to the number of max
5265 		 * allowed streams.
5266 		 * When we reach the cap, error out with NGHTTP2_ERR_WOULDBLOCK
5267 		 * to signal nghttp2_session_recv() to stop reading for now. */
5268 		h2_session->reads_count = 0;
5269 		return NGHTTP2_ERR_WOULDBLOCK;
5270 	}
5271 
5272 #ifdef HAVE_SSL
5273 	if(h2_session->c->ssl) {
5274 		int r;
5275 		ERR_clear_error();
5276 		r = SSL_read(h2_session->c->ssl, buf, len);
5277 		if(r <= 0) {
5278 			int want = SSL_get_error(h2_session->c->ssl, r);
5279 			if(want == SSL_ERROR_ZERO_RETURN) {
5280 				return NGHTTP2_ERR_EOF;
5281 			} else if(want == SSL_ERROR_WANT_READ) {
5282 				return NGHTTP2_ERR_WOULDBLOCK;
5283 			} else if(want == SSL_ERROR_WANT_WRITE) {
5284 				h2_session->c->ssl_shake_state = comm_ssl_shake_hs_write;
5285 				comm_point_listen_for_rw(h2_session->c, 0, 1);
5286 				return NGHTTP2_ERR_WOULDBLOCK;
5287 			} else if(want == SSL_ERROR_SYSCALL) {
5288 #ifdef ECONNRESET
5289 				if(errno == ECONNRESET && verbosity < 2)
5290 					return NGHTTP2_ERR_CALLBACK_FAILURE;
5291 #endif
5292 				if(errno != 0)
5293 					log_err("SSL_read syscall: %s",
5294 						strerror(errno));
5295 				return NGHTTP2_ERR_CALLBACK_FAILURE;
5296 			}
5297 			log_crypto_err_io("could not SSL_read", want);
5298 			return NGHTTP2_ERR_CALLBACK_FAILURE;
5299 		}
5300 		return r;
5301 	}
5302 #endif /* HAVE_SSL */
5303 
5304 	ret = recv(h2_session->c->fd, (void*)buf, len, MSG_DONTWAIT);
5305 	if(ret == 0) {
5306 		return NGHTTP2_ERR_EOF;
5307 	} else if(ret < 0) {
5308 #ifndef USE_WINSOCK
5309 		if(errno == EINTR || errno == EAGAIN)
5310 			return NGHTTP2_ERR_WOULDBLOCK;
5311 #ifdef ECONNRESET
5312 		if(errno == ECONNRESET && verbosity < 2)
5313 			return NGHTTP2_ERR_CALLBACK_FAILURE;
5314 #endif
5315 		log_err_addr("could not http2 recv: %s", strerror(errno),
5316 			&h2_session->c->repinfo.remote_addr,
5317 			h2_session->c->repinfo.remote_addrlen);
5318 #else /* USE_WINSOCK */
5319 		if(WSAGetLastError() == WSAECONNRESET)
5320 			return NGHTTP2_ERR_CALLBACK_FAILURE;
5321 		if(WSAGetLastError() == WSAEINPROGRESS)
5322 			return NGHTTP2_ERR_WOULDBLOCK;
5323 		if(WSAGetLastError() == WSAEWOULDBLOCK) {
5324 			ub_winsock_tcp_wouldblock(h2_session->c->ev->ev,
5325 				UB_EV_READ);
5326 			return NGHTTP2_ERR_WOULDBLOCK;
5327 		}
5328 		log_err_addr("could not http2 recv: %s",
5329 			wsa_strerror(WSAGetLastError()),
5330 			&h2_session->c->repinfo.remote_addr,
5331 			h2_session->c->repinfo.remote_addrlen);
5332 #endif
5333 		return NGHTTP2_ERR_CALLBACK_FAILURE;
5334 	}
5335 	return ret;
5336 }
5337 #endif /* HAVE_NGHTTP2 */
5338 
5339 /** Handle http2 read */
5340 static int
5341 comm_point_http2_handle_read(int ATTR_UNUSED(fd), struct comm_point* c)
5342 {
5343 #ifdef HAVE_NGHTTP2
5344 	int ret;
5345 	log_assert(c->h2_session);
5346 
5347 	/* reading until recv cb returns NGHTTP2_ERR_WOULDBLOCK */
5348 	ret = nghttp2_session_recv(c->h2_session->session);
5349 	if(ret) {
5350 		if(ret != NGHTTP2_ERR_EOF &&
5351 			ret != NGHTTP2_ERR_CALLBACK_FAILURE) {
5352 			char a[256];
5353 			addr_to_str(&c->repinfo.remote_addr,
5354 				c->repinfo.remote_addrlen, a, sizeof(a));
5355 			verbose(VERB_QUERY, "http2: session_recv from %s failed, "
5356 				"error: %s", a, nghttp2_strerror(ret));
5357 		}
5358 		return 0;
5359 	}
5360 	if(nghttp2_session_want_write(c->h2_session->session)) {
5361 		c->tcp_is_reading = 0;
5362 		comm_point_stop_listening(c);
5363 		comm_point_start_listening(c, -1, adjusted_tcp_timeout(c));
5364 	} else if(!nghttp2_session_want_read(c->h2_session->session))
5365 		return 0; /* connection can be closed */
5366 	return 1;
5367 #else
5368 	(void)c;
5369 	return 0;
5370 #endif
5371 }
5372 
5373 /**
5374  * Handle http reading callback.
5375  * @param fd: file descriptor of socket.
5376  * @param c: comm point to read from into buffer.
5377  * @return: 0 on error
5378  */
5379 static int
5380 comm_point_http_handle_read(int fd, struct comm_point* c)
5381 {
5382 	log_assert(c->type == comm_http);
5383 	log_assert(fd != -1);
5384 
5385 	/* if we are in ssl handshake, handle SSL handshake */
5386 #ifdef HAVE_SSL
5387 	if(c->ssl && c->ssl_shake_state != comm_ssl_shake_none) {
5388 		if(!ssl_handshake(c))
5389 			return 0;
5390 		if(c->ssl_shake_state != comm_ssl_shake_none)
5391 			return 1;
5392 	}
5393 #endif /* HAVE_SSL */
5394 
5395 	if(!c->tcp_is_reading)
5396 		return 1;
5397 
5398 	if(c->use_h2) {
5399 		return comm_point_http2_handle_read(fd, c);
5400 	}
5401 
5402 	/* http version is <= http/1.1 */
5403 
5404 	if(c->http_min_version >= http_version_2) {
5405 		/* HTTP/2 failed, not allowed to use lower version. */
5406 		return 0;
5407 	}
5408 
5409 	/* read more data */
5410 	if(c->ssl) {
5411 		if(!ssl_http_read_more(c))
5412 			return 0;
5413 	} else {
5414 		if(!http_read_more(fd, c))
5415 			return 0;
5416 	}
5417 
5418 	if(c->http_stored >= sldns_buffer_position(c->buffer)) {
5419 		/* read did not work but we wanted more data, there is
5420 		 * no bytes to process now. */
5421 		return 1;
5422 	}
5423 	sldns_buffer_flip(c->buffer);
5424 	/* if we are partway in a segment of data, position us at the point
5425 	 * where we left off previously */
5426 	if(c->http_stored < sldns_buffer_limit(c->buffer))
5427 		sldns_buffer_set_position(c->buffer, c->http_stored);
5428 	else	sldns_buffer_set_position(c->buffer, sldns_buffer_limit(c->buffer));
5429 
5430 	while(sldns_buffer_remaining(c->buffer) > 0) {
5431 		/* Handle HTTP/1.x data */
5432 		/* if we are reading headers, read more headers */
5433 		if(c->http_in_headers || c->http_in_chunk_headers) {
5434 			/* if header is done, process the header */
5435 			if(!http_header_done(c->buffer)) {
5436 				if(sldns_buffer_limit(c->buffer) ==
5437 					sldns_buffer_capacity(c->buffer)) {
5438 					verbose(VERB_OPS, "http header line "
5439 						"exceeds %d bytes, transfer "
5440 						"failed", (int)sldns_buffer_capacity(c->buffer));
5441 					return 0;
5442 				}
5443 				/* copy remaining data to front of buffer
5444 				 * and set rest for writing into it */
5445 				http_moveover_buffer(c->buffer);
5446 				/* return and wait to read more */
5447 				return 1;
5448 			}
5449 			if(!c->http_in_chunk_headers) {
5450 				/* process initial headers */
5451 				if(!http_process_initial_header(c))
5452 					return 0;
5453 			} else {
5454 				/* process chunk headers */
5455 				int r = http_process_chunk_header(c);
5456 				if(r == 0) return 0;
5457 				if(r == 2) return 1; /* done */
5458 				/* r == 1, continue */
5459 			}
5460 			/* see if we have more to process */
5461 			continue;
5462 		}
5463 
5464 		if(!c->http_is_chunked) {
5465 			/* if we are reading nonchunks, process that*/
5466 			return http_nonchunk_segment(c);
5467 		} else {
5468 			/* if we are reading chunks, read the chunk */
5469 			int r = http_chunked_segment(c);
5470 			if(r == 0) return 0;
5471 			if(r == 1) return 1;
5472 			continue;
5473 		}
5474 	}
5475 	/* broke out of the loop; could not process header instead need
5476 	 * to read more */
5477 	/* moveover any remaining data and read more data */
5478 	http_moveover_buffer(c->buffer);
5479 	/* return and wait to read more */
5480 	return 1;
5481 }
5482 
5483 /** check pending connect for http */
5484 static int
5485 http_check_connect(int fd, struct comm_point* c)
5486 {
5487 	/* check for pending error from nonblocking connect */
5488 	/* from Stevens, unix network programming, vol1, 3rd ed, p450*/
5489 	int error = 0;
5490 	socklen_t len = (socklen_t)sizeof(error);
5491 	if(getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&error,
5492 		&len) < 0){
5493 #ifndef USE_WINSOCK
5494 		error = errno; /* on solaris errno is error */
5495 #else /* USE_WINSOCK */
5496 		error = WSAGetLastError();
5497 #endif
5498 	}
5499 #ifndef USE_WINSOCK
5500 #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
5501 	if(error == EINPROGRESS || error == EWOULDBLOCK)
5502 		return 1; /* try again later */
5503 	else
5504 #endif
5505 	if(error != 0 && verbosity < 2)
5506 		return 0; /* silence lots of chatter in the logs */
5507 	else if(error != 0) {
5508 		log_err_addr("http connect", strerror(error),
5509 			&c->repinfo.remote_addr, c->repinfo.remote_addrlen);
5510 #else /* USE_WINSOCK */
5511 	/* examine error */
5512 	if(error == WSAEINPROGRESS)
5513 		return 1;
5514 	else if(error == WSAEWOULDBLOCK) {
5515 		ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
5516 		return 1;
5517 	} else if(error != 0 && verbosity < 2)
5518 		return 0;
5519 	else if(error != 0) {
5520 		log_err_addr("http connect", wsa_strerror(error),
5521 			&c->repinfo.remote_addr, c->repinfo.remote_addrlen);
5522 #endif /* USE_WINSOCK */
5523 		return 0;
5524 	}
5525 	/* keep on processing this socket */
5526 	return 2;
5527 }
5528 
5529 /** write more data for http (with ssl) */
5530 static int
5531 ssl_http_write_more(struct comm_point* c)
5532 {
5533 #ifdef HAVE_SSL
5534 	int r;
5535 	log_assert(sldns_buffer_remaining(c->buffer) > 0);
5536 	ERR_clear_error();
5537 	r = SSL_write(c->ssl, (void*)sldns_buffer_current(c->buffer),
5538 		(int)sldns_buffer_remaining(c->buffer));
5539 	if(r <= 0) {
5540 		int want = SSL_get_error(c->ssl, r);
5541 		if(want == SSL_ERROR_ZERO_RETURN) {
5542 			return 0; /* closed */
5543 		} else if(want == SSL_ERROR_WANT_READ) {
5544 			c->ssl_shake_state = comm_ssl_shake_hs_read;
5545 			comm_point_listen_for_rw(c, 1, 0);
5546 			return 1; /* wait for read condition */
5547 		} else if(want == SSL_ERROR_WANT_WRITE) {
5548 			return 1; /* write more later */
5549 		} else if(want == SSL_ERROR_SYSCALL) {
5550 #ifdef EPIPE
5551 			if(errno == EPIPE && verbosity < 2)
5552 				return 0; /* silence 'broken pipe' */
5553 #endif
5554 			if(errno != 0)
5555 				log_err("SSL_write syscall: %s",
5556 					strerror(errno));
5557 			return 0;
5558 		}
5559 		log_crypto_err_io("could not SSL_write", want);
5560 		return 0;
5561 	}
5562 	sldns_buffer_skip(c->buffer, (ssize_t)r);
5563 	return 1;
5564 #else
5565 	(void)c;
5566 	return 0;
5567 #endif /* HAVE_SSL */
5568 }
5569 
5570 /** write more data for http */
5571 static int
5572 http_write_more(int fd, struct comm_point* c)
5573 {
5574 	ssize_t r;
5575 	log_assert(sldns_buffer_remaining(c->buffer) > 0);
5576 	r = send(fd, (void*)sldns_buffer_current(c->buffer),
5577 		sldns_buffer_remaining(c->buffer), 0);
5578 	if(r == -1) {
5579 #ifndef USE_WINSOCK
5580 		if(errno == EINTR || errno == EAGAIN)
5581 			return 1;
5582 #else
5583 		if(WSAGetLastError() == WSAEINPROGRESS)
5584 			return 1;
5585 		if(WSAGetLastError() == WSAEWOULDBLOCK) {
5586 			ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
5587 			return 1;
5588 		}
5589 #endif
5590 		log_err_addr("http send r", sock_strerror(errno),
5591 			&c->repinfo.remote_addr, c->repinfo.remote_addrlen);
5592 		return 0;
5593 	}
5594 	sldns_buffer_skip(c->buffer, r);
5595 	return 1;
5596 }
5597 
5598 #ifdef HAVE_NGHTTP2
5599 ssize_t http2_send_cb(nghttp2_session* ATTR_UNUSED(session), const uint8_t* buf,
5600 	size_t len, int ATTR_UNUSED(flags), void* cb_arg)
5601 {
5602 	ssize_t ret;
5603 	struct http2_session* h2_session = (struct http2_session*)cb_arg;
5604 	log_assert(h2_session->c->type == comm_http);
5605 	log_assert(h2_session->c->h2_session);
5606 
5607 #ifdef HAVE_SSL
5608 	if(h2_session->c->ssl) {
5609 		int r;
5610 		ERR_clear_error();
5611 		r = SSL_write(h2_session->c->ssl, buf, len);
5612 		if(r <= 0) {
5613 			int want = SSL_get_error(h2_session->c->ssl, r);
5614 			if(want == SSL_ERROR_ZERO_RETURN) {
5615 				return NGHTTP2_ERR_CALLBACK_FAILURE;
5616 			} else if(want == SSL_ERROR_WANT_READ) {
5617 				h2_session->c->ssl_shake_state = comm_ssl_shake_hs_read;
5618 				comm_point_listen_for_rw(h2_session->c, 1, 0);
5619 				return NGHTTP2_ERR_WOULDBLOCK;
5620 			} else if(want == SSL_ERROR_WANT_WRITE) {
5621 				return NGHTTP2_ERR_WOULDBLOCK;
5622 			} else if(want == SSL_ERROR_SYSCALL) {
5623 #ifdef EPIPE
5624 				if(errno == EPIPE && verbosity < 2)
5625 					return NGHTTP2_ERR_CALLBACK_FAILURE;
5626 #endif
5627 				if(errno != 0)
5628 					log_err("SSL_write syscall: %s",
5629 						strerror(errno));
5630 				return NGHTTP2_ERR_CALLBACK_FAILURE;
5631 			}
5632 			log_crypto_err_io("could not SSL_write", want);
5633 			return NGHTTP2_ERR_CALLBACK_FAILURE;
5634 		}
5635 		return r;
5636 	}
5637 #endif /* HAVE_SSL */
5638 
5639 	ret = send(h2_session->c->fd, (void*)buf, len, 0);
5640 	if(ret == 0) {
5641 		return NGHTTP2_ERR_CALLBACK_FAILURE;
5642 	} else if(ret < 0) {
5643 #ifndef USE_WINSOCK
5644 		if(errno == EINTR || errno == EAGAIN)
5645 			return NGHTTP2_ERR_WOULDBLOCK;
5646 #ifdef EPIPE
5647 		if(errno == EPIPE && verbosity < 2)
5648 			return NGHTTP2_ERR_CALLBACK_FAILURE;
5649 #endif
5650 #ifdef ECONNRESET
5651 		if(errno == ECONNRESET && verbosity < 2)
5652 			return NGHTTP2_ERR_CALLBACK_FAILURE;
5653 #endif
5654 		log_err_addr("could not http2 write: %s", strerror(errno),
5655 			&h2_session->c->repinfo.remote_addr,
5656 			h2_session->c->repinfo.remote_addrlen);
5657 #else /* USE_WINSOCK */
5658 		if(WSAGetLastError() == WSAENOTCONN)
5659 			return NGHTTP2_ERR_WOULDBLOCK;
5660 		if(WSAGetLastError() == WSAEINPROGRESS)
5661 			return NGHTTP2_ERR_WOULDBLOCK;
5662 		if(WSAGetLastError() == WSAEWOULDBLOCK) {
5663 			ub_winsock_tcp_wouldblock(h2_session->c->ev->ev,
5664 				UB_EV_WRITE);
5665 			return NGHTTP2_ERR_WOULDBLOCK;
5666 		}
5667 		if(WSAGetLastError() == WSAECONNRESET && verbosity < 2)
5668 			return NGHTTP2_ERR_CALLBACK_FAILURE;
5669 		log_err_addr("could not http2 write: %s",
5670 			wsa_strerror(WSAGetLastError()),
5671 			&h2_session->c->repinfo.remote_addr,
5672 			h2_session->c->repinfo.remote_addrlen);
5673 #endif
5674 		return NGHTTP2_ERR_CALLBACK_FAILURE;
5675 	}
5676 	return ret;
5677 }
5678 #endif /* HAVE_NGHTTP2 */
5679 
5680 /** Handle http2 writing */
5681 static int
5682 comm_point_http2_handle_write(int ATTR_UNUSED(fd), struct comm_point* c)
5683 {
5684 #ifdef HAVE_NGHTTP2
5685 	int ret;
5686 	log_assert(c->h2_session);
5687 
5688 	ret = nghttp2_session_send(c->h2_session->session);
5689 	if(ret) {
5690 		verbose(VERB_QUERY, "http2: session_send failed, "
5691 			"error: %s", nghttp2_strerror(ret));
5692 		return 0;
5693 	}
5694 
5695 	if(nghttp2_session_want_read(c->h2_session->session)) {
5696 		c->tcp_is_reading = 1;
5697 		comm_point_stop_listening(c);
5698 		comm_point_start_listening(c, -1, adjusted_tcp_timeout(c));
5699 	} else if(!nghttp2_session_want_write(c->h2_session->session))
5700 		return 0; /* connection can be closed */
5701 	return 1;
5702 #else
5703 	(void)c;
5704 	return 0;
5705 #endif
5706 }
5707 
5708 /**
5709  * Handle http writing callback.
5710  * @param fd: file descriptor of socket.
5711  * @param c: comm point to write buffer out of.
5712  * @return: 0 on error
5713  */
5714 static int
5715 comm_point_http_handle_write(int fd, struct comm_point* c)
5716 {
5717 	log_assert(c->type == comm_http);
5718 	log_assert(fd != -1);
5719 
5720 	/* check pending connect errors, if that fails, we wait for more,
5721 	 * or we can continue to write contents */
5722 	if(c->tcp_check_nb_connect) {
5723 		int r = http_check_connect(fd, c);
5724 		if(r == 0) return 0;
5725 		if(r == 1) return 1;
5726 		c->tcp_check_nb_connect = 0;
5727 	}
5728 	/* if we are in ssl handshake, handle SSL handshake */
5729 #ifdef HAVE_SSL
5730 	if(c->ssl && c->ssl_shake_state != comm_ssl_shake_none) {
5731 		if(!ssl_handshake(c))
5732 			return 0;
5733 		if(c->ssl_shake_state != comm_ssl_shake_none)
5734 			return 1;
5735 	}
5736 #endif /* HAVE_SSL */
5737 	if(c->tcp_is_reading)
5738 		return 1;
5739 
5740 	if(c->use_h2) {
5741 		return comm_point_http2_handle_write(fd, c);
5742 	}
5743 
5744 	/* http version is <= http/1.1 */
5745 
5746 	if(c->http_min_version >= http_version_2) {
5747 		/* HTTP/2 failed, not allowed to use lower version. */
5748 		return 0;
5749 	}
5750 
5751 	/* if we are writing, write more */
5752 	if(c->ssl) {
5753 		if(!ssl_http_write_more(c))
5754 			return 0;
5755 	} else {
5756 		if(!http_write_more(fd, c))
5757 			return 0;
5758 	}
5759 
5760 	/* we write a single buffer contents, that can contain
5761 	 * the http request, and then flip to read the results */
5762 	/* see if write is done */
5763 	if(sldns_buffer_remaining(c->buffer) == 0) {
5764 		sldns_buffer_clear(c->buffer);
5765 		if(c->tcp_do_toggle_rw)
5766 			c->tcp_is_reading = 1;
5767 		c->tcp_byte_count = 0;
5768 		/* switch from listening(write) to listening(read) */
5769 		comm_point_stop_listening(c);
5770 		comm_point_start_listening(c, -1, -1);
5771 	}
5772 	return 1;
5773 }
5774 
5775 void
5776 comm_point_http_handle_callback(int fd, short event, void* arg)
5777 {
5778 	struct comm_point* c = (struct comm_point*)arg;
5779 	log_assert(c->type == comm_http);
5780 	ub_comm_base_now(c->ev->base);
5781 
5782 	if((event&UB_EV_TIMEOUT)) {
5783 		verbose(VERB_QUERY, "http took too long, dropped");
5784 		reclaim_http_handler(c);
5785 		if(!c->tcp_do_close) {
5786 			fptr_ok(fptr_whitelist_comm_point(c->callback));
5787 			(void)(*c->callback)(c, c->cb_arg,
5788 				NETEVENT_TIMEOUT, NULL);
5789 		}
5790 		return;
5791 	}
5792 	if((event&UB_EV_READ)) {
5793 		if(!comm_point_http_handle_read(fd, c)) {
5794 			reclaim_http_handler(c);
5795 			if(!c->tcp_do_close) {
5796 				fptr_ok(fptr_whitelist_comm_point(
5797 					c->callback));
5798 				(void)(*c->callback)(c, c->cb_arg,
5799 					NETEVENT_CLOSED, NULL);
5800 			}
5801 		}
5802 		return;
5803 	}
5804 	if((event&UB_EV_WRITE)) {
5805 		if(!comm_point_http_handle_write(fd, c)) {
5806 			reclaim_http_handler(c);
5807 			if(!c->tcp_do_close) {
5808 				fptr_ok(fptr_whitelist_comm_point(
5809 					c->callback));
5810 				(void)(*c->callback)(c, c->cb_arg,
5811 					NETEVENT_CLOSED, NULL);
5812 			}
5813 		}
5814 		return;
5815 	}
5816 	log_err("Ignored event %d for httphdl.", event);
5817 }
5818 
5819 void comm_point_local_handle_callback(int fd, short event, void* arg)
5820 {
5821 	struct comm_point* c = (struct comm_point*)arg;
5822 	log_assert(c->type == comm_local);
5823 	ub_comm_base_now(c->ev->base);
5824 
5825 	if((event&UB_EV_READ)) {
5826 		if(!comm_point_tcp_handle_read(fd, c, 1)) {
5827 			fptr_ok(fptr_whitelist_comm_point(c->callback));
5828 			(void)(*c->callback)(c, c->cb_arg, NETEVENT_CLOSED,
5829 				NULL);
5830 		}
5831 		return;
5832 	}
5833 	log_err("Ignored event %d for localhdl.", event);
5834 }
5835 
5836 void comm_point_raw_handle_callback(int ATTR_UNUSED(fd),
5837 	short event, void* arg)
5838 {
5839 	struct comm_point* c = (struct comm_point*)arg;
5840 	int err = NETEVENT_NOERROR;
5841 	log_assert(c->type == comm_raw);
5842 	ub_comm_base_now(c->ev->base);
5843 
5844 	if((event&UB_EV_TIMEOUT))
5845 		err = NETEVENT_TIMEOUT;
5846 	fptr_ok(fptr_whitelist_comm_point_raw(c->callback));
5847 	(void)(*c->callback)(c, c->cb_arg, err, NULL);
5848 }
5849 
5850 struct comm_point*
5851 comm_point_create_udp(struct comm_base *base, int fd, sldns_buffer* buffer,
5852 	int pp2_enabled, comm_point_callback_type* callback,
5853 	void* callback_arg, struct unbound_socket* socket)
5854 {
5855 	struct comm_point* c = (struct comm_point*)calloc(1,
5856 		sizeof(struct comm_point));
5857 	short evbits;
5858 	if(!c)
5859 		return NULL;
5860 	c->ev = (struct internal_event*)calloc(1,
5861 		sizeof(struct internal_event));
5862 	if(!c->ev) {
5863 		free(c);
5864 		return NULL;
5865 	}
5866 	c->ev->base = base;
5867 	c->fd = fd;
5868 	c->buffer = buffer;
5869 	c->timeout = NULL;
5870 	c->tcp_is_reading = 0;
5871 	c->tcp_byte_count = 0;
5872 	c->tcp_parent = NULL;
5873 	c->max_tcp_count = 0;
5874 	c->cur_tcp_count = 0;
5875 	c->tcp_handlers = NULL;
5876 	c->tcp_free = NULL;
5877 	c->is_in_tcp_free = 0;
5878 	c->type = comm_udp;
5879 	c->tcp_do_close = 0;
5880 	c->do_not_close = 0;
5881 	c->tcp_do_toggle_rw = 0;
5882 	c->tcp_check_nb_connect = 0;
5883 #ifdef USE_MSG_FASTOPEN
5884 	c->tcp_do_fastopen = 0;
5885 #endif
5886 #ifdef USE_DNSCRYPT
5887 	c->dnscrypt = 0;
5888 	c->dnscrypt_buffer = buffer;
5889 #endif
5890 	c->inuse = 0;
5891 	c->callback = callback;
5892 	c->cb_arg = callback_arg;
5893 	c->socket = socket;
5894 	c->pp2_enabled = pp2_enabled;
5895 	c->pp2_header_state = pp2_header_none;
5896 	evbits = UB_EV_READ | UB_EV_PERSIST;
5897 	/* ub_event stuff */
5898 	c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
5899 		comm_point_udp_callback, c);
5900 	if(c->ev->ev == NULL) {
5901 		log_err("could not baseset udp event");
5902 		comm_point_delete(c);
5903 		return NULL;
5904 	}
5905 	if(fd!=-1 && ub_event_add(c->ev->ev, c->timeout) != 0 ) {
5906 		log_err("could not add udp event");
5907 		comm_point_delete(c);
5908 		return NULL;
5909 	}
5910 	c->event_added = 1;
5911 	return c;
5912 }
5913 
5914 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && defined(HAVE_RECVMSG)
5915 struct comm_point*
5916 comm_point_create_udp_ancil(struct comm_base *base, int fd,
5917 	sldns_buffer* buffer, int pp2_enabled,
5918 	comm_point_callback_type* callback, void* callback_arg, struct unbound_socket* socket)
5919 {
5920 	struct comm_point* c = (struct comm_point*)calloc(1,
5921 		sizeof(struct comm_point));
5922 	short evbits;
5923 	if(!c)
5924 		return NULL;
5925 	c->ev = (struct internal_event*)calloc(1,
5926 		sizeof(struct internal_event));
5927 	if(!c->ev) {
5928 		free(c);
5929 		return NULL;
5930 	}
5931 	c->ev->base = base;
5932 	c->fd = fd;
5933 	c->buffer = buffer;
5934 	c->timeout = NULL;
5935 	c->tcp_is_reading = 0;
5936 	c->tcp_byte_count = 0;
5937 	c->tcp_parent = NULL;
5938 	c->max_tcp_count = 0;
5939 	c->cur_tcp_count = 0;
5940 	c->tcp_handlers = NULL;
5941 	c->tcp_free = NULL;
5942 	c->is_in_tcp_free = 0;
5943 	c->type = comm_udp;
5944 	c->tcp_do_close = 0;
5945 	c->do_not_close = 0;
5946 #ifdef USE_DNSCRYPT
5947 	c->dnscrypt = 0;
5948 	c->dnscrypt_buffer = buffer;
5949 #endif
5950 	c->inuse = 0;
5951 	c->tcp_do_toggle_rw = 0;
5952 	c->tcp_check_nb_connect = 0;
5953 #ifdef USE_MSG_FASTOPEN
5954 	c->tcp_do_fastopen = 0;
5955 #endif
5956 	c->callback = callback;
5957 	c->cb_arg = callback_arg;
5958 	c->socket = socket;
5959 	c->pp2_enabled = pp2_enabled;
5960 	c->pp2_header_state = pp2_header_none;
5961 	evbits = UB_EV_READ | UB_EV_PERSIST;
5962 	/* ub_event stuff */
5963 	c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
5964 		comm_point_udp_ancil_callback, c);
5965 	if(c->ev->ev == NULL) {
5966 		log_err("could not baseset udp event");
5967 		comm_point_delete(c);
5968 		return NULL;
5969 	}
5970 	if(fd!=-1 && ub_event_add(c->ev->ev, c->timeout) != 0 ) {
5971 		log_err("could not add udp event");
5972 		comm_point_delete(c);
5973 		return NULL;
5974 	}
5975 	c->event_added = 1;
5976 	return c;
5977 }
5978 #endif
5979 
5980 struct comm_point*
5981 comm_point_create_doq(struct comm_base *base, int fd, sldns_buffer* buffer,
5982 	comm_point_callback_type* callback, void* callback_arg,
5983 	struct unbound_socket* socket, struct doq_table* table,
5984 	struct ub_randstate* rnd, const void* quic_sslctx,
5985 	struct config_file* cfg)
5986 {
5987 #ifdef HAVE_NGTCP2
5988 	struct comm_point* c = (struct comm_point*)calloc(1,
5989 		sizeof(struct comm_point));
5990 	short evbits;
5991 	log_assert(table != NULL);
5992 	if(!c)
5993 		return NULL;
5994 	c->ev = (struct internal_event*)calloc(1,
5995 		sizeof(struct internal_event));
5996 	if(!c->ev) {
5997 		free(c);
5998 		return NULL;
5999 	}
6000 	c->ev->base = base;
6001 	c->fd = fd;
6002 	c->buffer = buffer;
6003 	c->timeout = NULL;
6004 	c->tcp_is_reading = 0;
6005 	c->tcp_byte_count = 0;
6006 	c->tcp_parent = NULL;
6007 	c->max_tcp_count = 0;
6008 	c->cur_tcp_count = 0;
6009 	c->tcp_handlers = NULL;
6010 	c->tcp_free = NULL;
6011 	c->is_in_tcp_free = 0;
6012 	c->type = comm_doq;
6013 	c->tcp_do_close = 0;
6014 	c->do_not_close = 0;
6015 	c->tcp_do_toggle_rw = 0;
6016 	c->tcp_check_nb_connect = 0;
6017 #ifdef USE_MSG_FASTOPEN
6018 	c->tcp_do_fastopen = 0;
6019 #endif
6020 #ifdef USE_DNSCRYPT
6021 	c->dnscrypt = 0;
6022 	c->dnscrypt_buffer = NULL;
6023 #endif
6024 	c->doq_socket = doq_server_socket_create(table, rnd, quic_sslctx, c,
6025 		base, cfg);
6026 	if(!c->doq_socket) {
6027 		log_err("could not create doq comm_point");
6028 		comm_point_delete(c);
6029 		return NULL;
6030 	}
6031 	c->inuse = 0;
6032 	c->callback = callback;
6033 	c->cb_arg = callback_arg;
6034 	c->socket = socket;
6035 	c->pp2_enabled = 0;
6036 	c->pp2_header_state = pp2_header_none;
6037 	evbits = UB_EV_READ | UB_EV_PERSIST;
6038 	/* ub_event stuff */
6039 	c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
6040 		comm_point_doq_callback, c);
6041 	if(c->ev->ev == NULL) {
6042 		log_err("could not baseset udp event");
6043 		comm_point_delete(c);
6044 		return NULL;
6045 	}
6046 	if(fd!=-1 && ub_event_add(c->ev->ev, c->timeout) != 0 ) {
6047 		log_err("could not add udp event");
6048 		comm_point_delete(c);
6049 		return NULL;
6050 	}
6051 	c->event_added = 1;
6052 	return c;
6053 #else
6054 	/* no libngtcp2, so no QUIC support */
6055 	(void)base;
6056 	(void)buffer;
6057 	(void)callback;
6058 	(void)callback_arg;
6059 	(void)socket;
6060 	(void)rnd;
6061 	(void)table;
6062 	(void)quic_sslctx;
6063 	(void)cfg;
6064 	sock_close(fd);
6065 	return NULL;
6066 #endif /* HAVE_NGTCP2 */
6067 }
6068 
6069 static struct comm_point*
6070 comm_point_create_tcp_handler(struct comm_base *base,
6071 	struct comm_point* parent, size_t bufsize,
6072 	struct sldns_buffer* spoolbuf, comm_point_callback_type* callback,
6073 	void* callback_arg, struct unbound_socket* socket)
6074 {
6075 	struct comm_point* c = (struct comm_point*)calloc(1,
6076 		sizeof(struct comm_point));
6077 	short evbits;
6078 	if(!c)
6079 		return NULL;
6080 	c->ev = (struct internal_event*)calloc(1,
6081 		sizeof(struct internal_event));
6082 	if(!c->ev) {
6083 		free(c);
6084 		return NULL;
6085 	}
6086 	c->ev->base = base;
6087 	c->fd = -1;
6088 	c->buffer = sldns_buffer_new(bufsize);
6089 	if(!c->buffer) {
6090 		free(c->ev);
6091 		free(c);
6092 		return NULL;
6093 	}
6094 	c->timeout = (struct timeval*)malloc(sizeof(struct timeval));
6095 	if(!c->timeout) {
6096 		sldns_buffer_free(c->buffer);
6097 		free(c->ev);
6098 		free(c);
6099 		return NULL;
6100 	}
6101 	c->tcp_is_reading = 0;
6102 	c->tcp_byte_count = 0;
6103 	c->tcp_parent = parent;
6104 	c->tcp_timeout_msec = parent->tcp_timeout_msec;
6105 	c->tcp_conn_limit = parent->tcp_conn_limit;
6106 	c->tcl_addr = NULL;
6107 	c->tcp_keepalive = 0;
6108 	c->max_tcp_count = 0;
6109 	c->cur_tcp_count = 0;
6110 	c->tcp_handlers = NULL;
6111 	c->tcp_free = NULL;
6112 	c->is_in_tcp_free = 0;
6113 	c->type = comm_tcp;
6114 	c->tcp_do_close = 0;
6115 	c->do_not_close = 0;
6116 	c->tcp_do_toggle_rw = 1;
6117 	c->tcp_check_nb_connect = 0;
6118 #ifdef USE_MSG_FASTOPEN
6119 	c->tcp_do_fastopen = 0;
6120 #endif
6121 #ifdef USE_DNSCRYPT
6122 	c->dnscrypt = 0;
6123 	/* We don't know just yet if this is a dnscrypt channel. Allocation
6124 	 * will be done when handling the callback. */
6125 	c->dnscrypt_buffer = c->buffer;
6126 #endif
6127 	c->repinfo.c = c;
6128 	c->callback = callback;
6129 	c->cb_arg = callback_arg;
6130 	c->socket = socket;
6131 	c->pp2_enabled = parent->pp2_enabled;
6132 	c->pp2_header_state = pp2_header_none;
6133 	if(spoolbuf) {
6134 		c->tcp_req_info = tcp_req_info_create(spoolbuf);
6135 		if(!c->tcp_req_info) {
6136 			log_err("could not create tcp commpoint");
6137 			sldns_buffer_free(c->buffer);
6138 			free(c->timeout);
6139 			free(c->ev);
6140 			free(c);
6141 			return NULL;
6142 		}
6143 		c->tcp_req_info->cp = c;
6144 		c->tcp_do_close = 1;
6145 		c->tcp_do_toggle_rw = 0;
6146 	}
6147 	/* add to parent free list */
6148 	c->tcp_free = parent->tcp_free;
6149 	parent->tcp_free = c;
6150 	c->is_in_tcp_free = 1;
6151 	/* ub_event stuff */
6152 	evbits = UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT;
6153 	c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
6154 		comm_point_tcp_handle_callback, c);
6155 	if(c->ev->ev == NULL)
6156 	{
6157 		log_err("could not basetset tcphdl event");
6158 		parent->tcp_free = c->tcp_free;
6159 		tcp_req_info_delete(c->tcp_req_info);
6160 		sldns_buffer_free(c->buffer);
6161 		free(c->timeout);
6162 		free(c->ev);
6163 		free(c);
6164 		return NULL;
6165 	}
6166 	return c;
6167 }
6168 
6169 static struct comm_point*
6170 comm_point_create_http_handler(struct comm_base *base,
6171 	struct comm_point* parent, size_t bufsize, int harden_large_queries,
6172 	uint32_t http_max_streams, char* http_endpoint,
6173 	comm_point_callback_type* callback, void* callback_arg,
6174 	struct unbound_socket* socket)
6175 {
6176 	struct comm_point* c = (struct comm_point*)calloc(1,
6177 		sizeof(struct comm_point));
6178 	short evbits;
6179 	if(!c)
6180 		return NULL;
6181 	c->ev = (struct internal_event*)calloc(1,
6182 		sizeof(struct internal_event));
6183 	if(!c->ev) {
6184 		free(c);
6185 		return NULL;
6186 	}
6187 	c->ev->base = base;
6188 	c->fd = -1;
6189 	c->buffer = sldns_buffer_new(bufsize);
6190 	if(!c->buffer) {
6191 		free(c->ev);
6192 		free(c);
6193 		return NULL;
6194 	}
6195 	c->timeout = (struct timeval*)malloc(sizeof(struct timeval));
6196 	if(!c->timeout) {
6197 		sldns_buffer_free(c->buffer);
6198 		free(c->ev);
6199 		free(c);
6200 		return NULL;
6201 	}
6202 	c->tcp_is_reading = 0;
6203 	c->tcp_byte_count = 0;
6204 	c->tcp_parent = parent;
6205 	c->tcp_timeout_msec = parent->tcp_timeout_msec;
6206 	c->tcp_conn_limit = parent->tcp_conn_limit;
6207 	c->tcl_addr = NULL;
6208 	c->tcp_keepalive = 0;
6209 	c->max_tcp_count = 0;
6210 	c->cur_tcp_count = 0;
6211 	c->tcp_handlers = NULL;
6212 	c->tcp_free = NULL;
6213 	c->is_in_tcp_free = 0;
6214 	c->type = comm_http;
6215 	c->tcp_do_close = 1;
6216 	c->do_not_close = 0;
6217 	c->tcp_do_toggle_rw = 1; /* will be set to 0 after http2 upgrade */
6218 	c->tcp_check_nb_connect = 0;
6219 #ifdef USE_MSG_FASTOPEN
6220 	c->tcp_do_fastopen = 0;
6221 #endif
6222 #ifdef USE_DNSCRYPT
6223 	c->dnscrypt = 0;
6224 	c->dnscrypt_buffer = NULL;
6225 #endif
6226 	c->repinfo.c = c;
6227 	c->callback = callback;
6228 	c->cb_arg = callback_arg;
6229 	c->socket = socket;
6230 	c->pp2_enabled = 0;
6231 	c->pp2_header_state = pp2_header_none;
6232 
6233 	c->http_min_version = http_version_2;
6234 	c->http2_stream_max_qbuffer_size = bufsize;
6235 	if(harden_large_queries && bufsize > 512)
6236 		c->http2_stream_max_qbuffer_size = 512;
6237 	c->http2_max_streams = http_max_streams;
6238 	if(!(c->http_endpoint = strdup(http_endpoint))) {
6239 		log_err("could not strdup http_endpoint");
6240 		sldns_buffer_free(c->buffer);
6241 		free(c->timeout);
6242 		free(c->ev);
6243 		free(c);
6244 		return NULL;
6245 	}
6246 	c->use_h2 = 0;
6247 #ifdef HAVE_NGHTTP2
6248 	if(!(c->h2_session = http2_session_create(c))) {
6249 		log_err("could not create http2 session");
6250 		free(c->http_endpoint);
6251 		sldns_buffer_free(c->buffer);
6252 		free(c->timeout);
6253 		free(c->ev);
6254 		free(c);
6255 		return NULL;
6256 	}
6257 	if(!(c->h2_session->callbacks = http2_req_callbacks_create())) {
6258 		log_err("could not create http2 callbacks");
6259 		http2_session_delete(c->h2_session);
6260 		free(c->http_endpoint);
6261 		sldns_buffer_free(c->buffer);
6262 		free(c->timeout);
6263 		free(c->ev);
6264 		free(c);
6265 		return NULL;
6266 	}
6267 #endif
6268 
6269 	/* add to parent free list */
6270 	c->tcp_free = parent->tcp_free;
6271 	parent->tcp_free = c;
6272 	c->is_in_tcp_free = 1;
6273 	/* ub_event stuff */
6274 	evbits = UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT;
6275 	c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
6276 		comm_point_http_handle_callback, c);
6277 	if(c->ev->ev == NULL)
6278 	{
6279 		log_err("could not set http handler event");
6280 		parent->tcp_free = c->tcp_free;
6281 		http2_session_delete(c->h2_session);
6282 		sldns_buffer_free(c->buffer);
6283 		free(c->timeout);
6284 		free(c->ev);
6285 		free(c);
6286 		return NULL;
6287 	}
6288 	return c;
6289 }
6290 
6291 struct comm_point*
6292 comm_point_create_tcp(struct comm_base *base, int fd, int num,
6293 	int idle_timeout, int harden_large_queries,
6294 	uint32_t http_max_streams, char* http_endpoint,
6295 	struct tcl_list* tcp_conn_limit, size_t bufsize,
6296 	struct sldns_buffer* spoolbuf, enum listen_type port_type,
6297 	int pp2_enabled, comm_point_callback_type* callback,
6298 	void* callback_arg, struct unbound_socket* socket)
6299 {
6300 	struct comm_point* c = (struct comm_point*)calloc(1,
6301 		sizeof(struct comm_point));
6302 	short evbits;
6303 	int i;
6304 	/* first allocate the TCP accept listener */
6305 	if(!c)
6306 		return NULL;
6307 	c->ev = (struct internal_event*)calloc(1,
6308 		sizeof(struct internal_event));
6309 	if(!c->ev) {
6310 		free(c);
6311 		return NULL;
6312 	}
6313 	c->ev->base = base;
6314 	c->fd = fd;
6315 	c->buffer = NULL;
6316 	c->timeout = NULL;
6317 	c->tcp_is_reading = 0;
6318 	c->tcp_byte_count = 0;
6319 	c->tcp_timeout_msec = idle_timeout;
6320 	c->tcp_conn_limit = tcp_conn_limit;
6321 	c->tcl_addr = NULL;
6322 	c->tcp_keepalive = 0;
6323 	c->tcp_parent = NULL;
6324 	c->max_tcp_count = num;
6325 	c->cur_tcp_count = 0;
6326 	c->tcp_handlers = (struct comm_point**)calloc((size_t)num,
6327 		sizeof(struct comm_point*));
6328 	if(!c->tcp_handlers) {
6329 		free(c->ev);
6330 		free(c);
6331 		return NULL;
6332 	}
6333 	c->tcp_free = NULL;
6334 	c->is_in_tcp_free = 0;
6335 	c->type = comm_tcp_accept;
6336 	c->tcp_do_close = 0;
6337 	c->do_not_close = 0;
6338 	c->tcp_do_toggle_rw = 0;
6339 	c->tcp_check_nb_connect = 0;
6340 #ifdef USE_MSG_FASTOPEN
6341 	c->tcp_do_fastopen = 0;
6342 #endif
6343 #ifdef USE_DNSCRYPT
6344 	c->dnscrypt = 0;
6345 	c->dnscrypt_buffer = NULL;
6346 #endif
6347 	c->callback = NULL;
6348 	c->cb_arg = NULL;
6349 	c->socket = socket;
6350 	c->pp2_enabled = (port_type==listen_type_http?0:pp2_enabled);
6351 	c->pp2_header_state = pp2_header_none;
6352 	evbits = UB_EV_READ | UB_EV_PERSIST;
6353 	/* ub_event stuff */
6354 	c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
6355 		comm_point_tcp_accept_callback, c);
6356 	if(c->ev->ev == NULL) {
6357 		log_err("could not baseset tcpacc event");
6358 		comm_point_delete(c);
6359 		return NULL;
6360 	}
6361 	if (ub_event_add(c->ev->ev, c->timeout) != 0) {
6362 		log_err("could not add tcpacc event");
6363 		comm_point_delete(c);
6364 		return NULL;
6365 	}
6366 	c->event_added = 1;
6367 	/* now prealloc the handlers */
6368 	for(i=0; i<num; i++) {
6369 		if(port_type == listen_type_tcp ||
6370 			port_type == listen_type_ssl ||
6371 			port_type == listen_type_tcp_dnscrypt) {
6372 			c->tcp_handlers[i] = comm_point_create_tcp_handler(base,
6373 				c, bufsize, spoolbuf, callback, callback_arg, socket);
6374 		} else if(port_type == listen_type_http) {
6375 			c->tcp_handlers[i] = comm_point_create_http_handler(
6376 				base, c, bufsize, harden_large_queries,
6377 				http_max_streams, http_endpoint,
6378 				callback, callback_arg, socket);
6379 		}
6380 		else {
6381 			log_err("could not create tcp handler, unknown listen "
6382 				"type");
6383 			return NULL;
6384 		}
6385 		if(!c->tcp_handlers[i]) {
6386 			comm_point_delete(c);
6387 			return NULL;
6388 		}
6389 	}
6390 
6391 	return c;
6392 }
6393 
6394 struct comm_point*
6395 comm_point_create_tcp_out(struct comm_base *base, size_t bufsize,
6396         comm_point_callback_type* callback, void* callback_arg)
6397 {
6398 	struct comm_point* c = (struct comm_point*)calloc(1,
6399 		sizeof(struct comm_point));
6400 	short evbits;
6401 	if(!c)
6402 		return NULL;
6403 	c->ev = (struct internal_event*)calloc(1,
6404 		sizeof(struct internal_event));
6405 	if(!c->ev) {
6406 		free(c);
6407 		return NULL;
6408 	}
6409 	c->ev->base = base;
6410 	c->fd = -1;
6411 	c->buffer = sldns_buffer_new(bufsize);
6412 	if(!c->buffer) {
6413 		free(c->ev);
6414 		free(c);
6415 		return NULL;
6416 	}
6417 	c->timeout = NULL;
6418 	c->tcp_is_reading = 0;
6419 	c->tcp_byte_count = 0;
6420 	c->tcp_timeout_msec = TCP_QUERY_TIMEOUT;
6421 	c->tcp_conn_limit = NULL;
6422 	c->tcl_addr = NULL;
6423 	c->tcp_keepalive = 0;
6424 	c->tcp_parent = NULL;
6425 	c->max_tcp_count = 0;
6426 	c->cur_tcp_count = 0;
6427 	c->tcp_handlers = NULL;
6428 	c->tcp_free = NULL;
6429 	c->is_in_tcp_free = 0;
6430 	c->type = comm_tcp;
6431 	c->tcp_do_close = 0;
6432 	c->do_not_close = 0;
6433 	c->tcp_do_toggle_rw = 1;
6434 	c->tcp_check_nb_connect = 1;
6435 #ifdef USE_MSG_FASTOPEN
6436 	c->tcp_do_fastopen = 1;
6437 #endif
6438 #ifdef USE_DNSCRYPT
6439 	c->dnscrypt = 0;
6440 	c->dnscrypt_buffer = c->buffer;
6441 #endif
6442 	c->repinfo.c = c;
6443 	c->callback = callback;
6444 	c->cb_arg = callback_arg;
6445 	c->pp2_enabled = 0;
6446 	c->pp2_header_state = pp2_header_none;
6447 	evbits = UB_EV_PERSIST | UB_EV_WRITE;
6448 	c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
6449 		comm_point_tcp_handle_callback, c);
6450 	if(c->ev->ev == NULL)
6451 	{
6452 		log_err("could not baseset tcpout event");
6453 		sldns_buffer_free(c->buffer);
6454 		free(c->ev);
6455 		free(c);
6456 		return NULL;
6457 	}
6458 
6459 	return c;
6460 }
6461 
6462 struct comm_point*
6463 comm_point_create_http_out(struct comm_base *base, size_t bufsize,
6464         comm_point_callback_type* callback, void* callback_arg,
6465 	sldns_buffer* temp)
6466 {
6467 	struct comm_point* c = (struct comm_point*)calloc(1,
6468 		sizeof(struct comm_point));
6469 	short evbits;
6470 	if(!c)
6471 		return NULL;
6472 	c->ev = (struct internal_event*)calloc(1,
6473 		sizeof(struct internal_event));
6474 	if(!c->ev) {
6475 		free(c);
6476 		return NULL;
6477 	}
6478 	c->ev->base = base;
6479 	c->fd = -1;
6480 	c->buffer = sldns_buffer_new(bufsize);
6481 	if(!c->buffer) {
6482 		free(c->ev);
6483 		free(c);
6484 		return NULL;
6485 	}
6486 	c->timeout = NULL;
6487 	c->tcp_is_reading = 0;
6488 	c->tcp_byte_count = 0;
6489 	c->tcp_parent = NULL;
6490 	c->max_tcp_count = 0;
6491 	c->cur_tcp_count = 0;
6492 	c->tcp_handlers = NULL;
6493 	c->tcp_free = NULL;
6494 	c->is_in_tcp_free = 0;
6495 	c->type = comm_http;
6496 	c->tcp_do_close = 0;
6497 	c->do_not_close = 0;
6498 	c->tcp_do_toggle_rw = 1;
6499 	c->tcp_check_nb_connect = 1;
6500 	c->http_in_headers = 1;
6501 	c->http_in_chunk_headers = 0;
6502 	c->http_is_chunked = 0;
6503 	c->http_temp = temp;
6504 #ifdef USE_MSG_FASTOPEN
6505 	c->tcp_do_fastopen = 1;
6506 #endif
6507 #ifdef USE_DNSCRYPT
6508 	c->dnscrypt = 0;
6509 	c->dnscrypt_buffer = c->buffer;
6510 #endif
6511 	c->repinfo.c = c;
6512 	c->callback = callback;
6513 	c->cb_arg = callback_arg;
6514 	c->pp2_enabled = 0;
6515 	c->pp2_header_state = pp2_header_none;
6516 	evbits = UB_EV_PERSIST | UB_EV_WRITE;
6517 	c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
6518 		comm_point_http_handle_callback, c);
6519 	if(c->ev->ev == NULL)
6520 	{
6521 		log_err("could not baseset tcpout event");
6522 #ifdef HAVE_SSL
6523 		SSL_free(c->ssl);
6524 #endif
6525 		sldns_buffer_free(c->buffer);
6526 		free(c->ev);
6527 		free(c);
6528 		return NULL;
6529 	}
6530 
6531 	return c;
6532 }
6533 
6534 struct comm_point*
6535 comm_point_create_local(struct comm_base *base, int fd, size_t bufsize,
6536         comm_point_callback_type* callback, void* callback_arg)
6537 {
6538 	struct comm_point* c = (struct comm_point*)calloc(1,
6539 		sizeof(struct comm_point));
6540 	short evbits;
6541 	if(!c)
6542 		return NULL;
6543 	c->ev = (struct internal_event*)calloc(1,
6544 		sizeof(struct internal_event));
6545 	if(!c->ev) {
6546 		free(c);
6547 		return NULL;
6548 	}
6549 	c->ev->base = base;
6550 	c->fd = fd;
6551 	c->buffer = sldns_buffer_new(bufsize);
6552 	if(!c->buffer) {
6553 		free(c->ev);
6554 		free(c);
6555 		return NULL;
6556 	}
6557 	c->timeout = NULL;
6558 	c->tcp_is_reading = 1;
6559 	c->tcp_byte_count = 0;
6560 	c->tcp_parent = NULL;
6561 	c->max_tcp_count = 0;
6562 	c->cur_tcp_count = 0;
6563 	c->tcp_handlers = NULL;
6564 	c->tcp_free = NULL;
6565 	c->is_in_tcp_free = 0;
6566 	c->type = comm_local;
6567 	c->tcp_do_close = 0;
6568 	c->do_not_close = 1;
6569 	c->tcp_do_toggle_rw = 0;
6570 	c->tcp_check_nb_connect = 0;
6571 #ifdef USE_MSG_FASTOPEN
6572 	c->tcp_do_fastopen = 0;
6573 #endif
6574 #ifdef USE_DNSCRYPT
6575 	c->dnscrypt = 0;
6576 	c->dnscrypt_buffer = c->buffer;
6577 #endif
6578 	c->callback = callback;
6579 	c->cb_arg = callback_arg;
6580 	c->pp2_enabled = 0;
6581 	c->pp2_header_state = pp2_header_none;
6582 	/* ub_event stuff */
6583 	evbits = UB_EV_PERSIST | UB_EV_READ;
6584 	c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
6585 		comm_point_local_handle_callback, c);
6586 	if(c->ev->ev == NULL) {
6587 		log_err("could not baseset localhdl event");
6588 		free(c->ev);
6589 		free(c);
6590 		return NULL;
6591 	}
6592 	if (ub_event_add(c->ev->ev, c->timeout) != 0) {
6593 		log_err("could not add localhdl event");
6594 		ub_event_free(c->ev->ev);
6595 		free(c->ev);
6596 		free(c);
6597 		return NULL;
6598 	}
6599 	c->event_added = 1;
6600 	return c;
6601 }
6602 
6603 struct comm_point*
6604 comm_point_create_raw(struct comm_base* base, int fd, int writing,
6605 	comm_point_callback_type* callback, void* callback_arg)
6606 {
6607 	struct comm_point* c = (struct comm_point*)calloc(1,
6608 		sizeof(struct comm_point));
6609 	short evbits;
6610 	if(!c)
6611 		return NULL;
6612 	c->ev = (struct internal_event*)calloc(1,
6613 		sizeof(struct internal_event));
6614 	if(!c->ev) {
6615 		free(c);
6616 		return NULL;
6617 	}
6618 	c->ev->base = base;
6619 	c->fd = fd;
6620 	c->buffer = NULL;
6621 	c->timeout = NULL;
6622 	c->tcp_is_reading = 0;
6623 	c->tcp_byte_count = 0;
6624 	c->tcp_parent = NULL;
6625 	c->max_tcp_count = 0;
6626 	c->cur_tcp_count = 0;
6627 	c->tcp_handlers = NULL;
6628 	c->tcp_free = NULL;
6629 	c->is_in_tcp_free = 0;
6630 	c->type = comm_raw;
6631 	c->tcp_do_close = 0;
6632 	c->do_not_close = 1;
6633 	c->tcp_do_toggle_rw = 0;
6634 	c->tcp_check_nb_connect = 0;
6635 #ifdef USE_MSG_FASTOPEN
6636 	c->tcp_do_fastopen = 0;
6637 #endif
6638 #ifdef USE_DNSCRYPT
6639 	c->dnscrypt = 0;
6640 	c->dnscrypt_buffer = c->buffer;
6641 #endif
6642 	c->callback = callback;
6643 	c->cb_arg = callback_arg;
6644 	c->pp2_enabled = 0;
6645 	c->pp2_header_state = pp2_header_none;
6646 	/* ub_event stuff */
6647 	if(writing)
6648 		evbits = UB_EV_PERSIST | UB_EV_WRITE;
6649 	else 	evbits = UB_EV_PERSIST | UB_EV_READ;
6650 	c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
6651 		comm_point_raw_handle_callback, c);
6652 	if(c->ev->ev == NULL) {
6653 		log_err("could not baseset rawhdl event");
6654 		free(c->ev);
6655 		free(c);
6656 		return NULL;
6657 	}
6658 	if (ub_event_add(c->ev->ev, c->timeout) != 0) {
6659 		log_err("could not add rawhdl event");
6660 		ub_event_free(c->ev->ev);
6661 		free(c->ev);
6662 		free(c);
6663 		return NULL;
6664 	}
6665 	c->event_added = 1;
6666 	return c;
6667 }
6668 
6669 void
6670 comm_point_close(struct comm_point* c)
6671 {
6672 	if(!c)
6673 		return;
6674 	if(c->fd != -1) {
6675 		verbose(5, "comm_point_close of %d: event_del", c->fd);
6676 		if(c->event_added) {
6677 			if(ub_event_del(c->ev->ev) != 0) {
6678 				log_err("could not event_del on close");
6679 			}
6680 			c->event_added = 0;
6681 		}
6682 	}
6683 	if(c->tcl_addr) {
6684 		tcl_close_connection(c->tcl_addr);
6685 		c->tcl_addr = NULL;
6686 	}
6687 	if(c->tcp_req_info)
6688 		tcp_req_info_clear(c->tcp_req_info);
6689 	if(c->h2_session)
6690 		http2_session_server_delete(c->h2_session);
6691 	/* stop the comm point from reading or writing after it is closed. */
6692 	if(c->tcp_more_read_again && *c->tcp_more_read_again)
6693 		*c->tcp_more_read_again = 0;
6694 	if(c->tcp_more_write_again && *c->tcp_more_write_again)
6695 		*c->tcp_more_write_again = 0;
6696 
6697 	/* close fd after removing from event lists, or epoll.. is messed up */
6698 	if(c->fd != -1 && !c->do_not_close) {
6699 #ifdef USE_WINSOCK
6700 		if(c->type == comm_tcp || c->type == comm_http) {
6701 			/* delete sticky events for the fd, it gets closed */
6702 			ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
6703 			ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
6704 		}
6705 #endif
6706 		verbose(VERB_ALGO, "close fd %d", c->fd);
6707 		sock_close(c->fd);
6708 	}
6709 	c->fd = -1;
6710 }
6711 
6712 void
6713 comm_point_delete(struct comm_point* c)
6714 {
6715 	if(!c)
6716 		return;
6717 	if((c->type == comm_tcp || c->type == comm_http) && c->ssl) {
6718 #ifdef HAVE_SSL
6719 		SSL_shutdown(c->ssl);
6720 		SSL_free(c->ssl);
6721 #endif
6722 	}
6723 	if(c->type == comm_http && c->http_endpoint) {
6724 		free(c->http_endpoint);
6725 		c->http_endpoint = NULL;
6726 	}
6727 	comm_point_close(c);
6728 	if(c->tcp_handlers) {
6729 		int i;
6730 		for(i=0; i<c->max_tcp_count; i++)
6731 			comm_point_delete(c->tcp_handlers[i]);
6732 		free(c->tcp_handlers);
6733 	}
6734 	free(c->timeout);
6735 	if(c->type == comm_tcp || c->type == comm_local || c->type == comm_http) {
6736 		sldns_buffer_free(c->buffer);
6737 #ifdef USE_DNSCRYPT
6738 		if(c->dnscrypt && c->dnscrypt_buffer != c->buffer) {
6739 			sldns_buffer_free(c->dnscrypt_buffer);
6740 		}
6741 #endif
6742 		if(c->tcp_req_info) {
6743 			tcp_req_info_delete(c->tcp_req_info);
6744 		}
6745 		if(c->h2_session) {
6746 			http2_session_delete(c->h2_session);
6747 		}
6748 	}
6749 #ifdef HAVE_NGTCP2
6750 	if(c->doq_socket)
6751 		doq_server_socket_delete(c->doq_socket);
6752 #endif
6753 	ub_event_free(c->ev->ev);
6754 	free(c->ev);
6755 	free(c);
6756 }
6757 
6758 #ifdef USE_DNSTAP
6759 static void
6760 send_reply_dnstap(struct dt_env* dtenv,
6761 	struct sockaddr* addr, socklen_t addrlen,
6762 	struct sockaddr_storage* client_addr, socklen_t client_addrlen,
6763 	enum comm_point_type type, void* ssl, sldns_buffer* buffer)
6764 {
6765 	log_addr(VERB_ALGO, "from local addr", (void*)addr, addrlen);
6766 	log_addr(VERB_ALGO, "response to client", client_addr, client_addrlen);
6767 	dt_msg_send_client_response(dtenv, client_addr,
6768 		(struct sockaddr_storage*)addr, type, ssl, buffer);
6769 }
6770 #endif
6771 
6772 void
6773 comm_point_send_reply(struct comm_reply *repinfo)
6774 {
6775 	struct sldns_buffer* buffer;
6776 	log_assert(repinfo && repinfo->c);
6777 #ifdef USE_DNSCRYPT
6778 	buffer = repinfo->c->dnscrypt_buffer;
6779 	if(!dnsc_handle_uncurved_request(repinfo,
6780 		repinfo->c->tcp_req_info?
6781 		repinfo->c->tcp_req_info->spool_buffer:repinfo->c->buffer)) {
6782 		return;
6783 	}
6784 #else
6785 	buffer = repinfo->c->buffer;
6786 #endif
6787 	if(repinfo->c->type == comm_udp) {
6788 		if(repinfo->srctype)
6789 			comm_point_send_udp_msg_if(repinfo->c, buffer,
6790 				(struct sockaddr*)&repinfo->remote_addr,
6791 				repinfo->remote_addrlen, repinfo);
6792 		else
6793 			comm_point_send_udp_msg(repinfo->c, buffer,
6794 				(struct sockaddr*)&repinfo->remote_addr,
6795 				repinfo->remote_addrlen, 0);
6796 #ifdef USE_DNSTAP
6797 		/*
6798 		 * sending src (client)/dst (local service) addresses over
6799 		 * DNSTAP from udp callback
6800 		 */
6801 		if(repinfo->c->dtenv != NULL && repinfo->c->dtenv->log_client_response_messages) {
6802 			send_reply_dnstap(repinfo->c->dtenv,
6803 				repinfo->c->socket->addr,
6804 				repinfo->c->socket->addrlen,
6805 				&repinfo->client_addr, repinfo->client_addrlen,
6806 				repinfo->c->type, repinfo->c->ssl,
6807 				repinfo->c->buffer);
6808 		}
6809 #endif
6810 	} else {
6811 #ifdef USE_DNSTAP
6812 		struct dt_env* dtenv =
6813 #ifdef HAVE_NGTCP2
6814 			repinfo->c->doq_socket
6815 			?repinfo->c->dtenv:
6816 #endif
6817 			repinfo->c->tcp_parent->dtenv;
6818 		struct sldns_buffer* dtbuffer = repinfo->c->tcp_req_info
6819 			?repinfo->c->tcp_req_info->spool_buffer
6820 			:repinfo->c->buffer;
6821 #ifdef USE_DNSCRYPT
6822 		if(repinfo->c->dnscrypt && repinfo->is_dnscrypted)
6823 			dtbuffer = repinfo->c->buffer;
6824 #endif
6825 		/*
6826 		 * sending src (client)/dst (local service) addresses over
6827 		 * DNSTAP from other callbacks
6828 		 */
6829 		if(dtenv != NULL && dtenv->log_client_response_messages) {
6830 			send_reply_dnstap(dtenv,
6831 				repinfo->c->socket->addr,
6832 				repinfo->c->socket->addrlen,
6833 				&repinfo->client_addr, repinfo->client_addrlen,
6834 				repinfo->c->type, repinfo->c->ssl,
6835 				dtbuffer);
6836 		}
6837 #endif
6838 		if(repinfo->c->tcp_req_info) {
6839 			tcp_req_info_send_reply(repinfo->c->tcp_req_info);
6840 		} else if(repinfo->c->use_h2) {
6841 			if(!http2_submit_dns_response(repinfo->c->h2_session)) {
6842 				return;
6843 			}
6844 			repinfo->c->h2_stream = NULL;
6845 			repinfo->c->tcp_is_reading = 0;
6846 			comm_point_stop_listening(repinfo->c);
6847 			comm_point_start_listening(repinfo->c, -1,
6848 				adjusted_tcp_timeout(repinfo->c));
6849 			return;
6850 #ifdef HAVE_NGTCP2
6851 		} else if(repinfo->c->doq_socket) {
6852 			doq_socket_send_reply(repinfo);
6853 #endif
6854 		} else {
6855 			comm_point_start_listening(repinfo->c, -1,
6856 				adjusted_tcp_timeout(repinfo->c));
6857 		}
6858 	}
6859 }
6860 
6861 void
6862 comm_point_drop_reply(struct comm_reply* repinfo)
6863 {
6864 	if(!repinfo)
6865 		return;
6866 	log_assert(repinfo->c);
6867 	log_assert(repinfo->c->type != comm_tcp_accept);
6868 	if(repinfo->c->type == comm_udp)
6869 		return;
6870 	if(repinfo->c->tcp_req_info)
6871 		repinfo->c->tcp_req_info->is_drop = 1;
6872 	if(repinfo->c->type == comm_http) {
6873 		if(repinfo->c->h2_session) {
6874 			repinfo->c->h2_session->is_drop = 1;
6875 			if(!repinfo->c->h2_session->postpone_drop)
6876 				reclaim_http_handler(repinfo->c);
6877 			return;
6878 		}
6879 		reclaim_http_handler(repinfo->c);
6880 		return;
6881 #ifdef HAVE_NGTCP2
6882 	} else if(repinfo->c->doq_socket) {
6883 		doq_socket_drop_reply(repinfo);
6884 		return;
6885 #endif
6886 	}
6887 	reclaim_tcp_handler(repinfo->c);
6888 }
6889 
6890 void
6891 comm_point_stop_listening(struct comm_point* c)
6892 {
6893 	verbose(VERB_ALGO, "comm point stop listening %d", c->fd);
6894 	if(c->event_added) {
6895 		if(ub_event_del(c->ev->ev) != 0) {
6896 			log_err("event_del error to stoplisten");
6897 		}
6898 		c->event_added = 0;
6899 	}
6900 }
6901 
6902 void
6903 comm_point_start_listening(struct comm_point* c, int newfd, int msec)
6904 {
6905 	verbose(VERB_ALGO, "comm point start listening %d (%d msec)",
6906 		c->fd==-1?newfd:c->fd, msec);
6907 	if(c->type == comm_tcp_accept && !c->tcp_free) {
6908 		/* no use to start listening no free slots. */
6909 		return;
6910 	}
6911 	if(c->event_added) {
6912 		if(ub_event_del(c->ev->ev) != 0) {
6913 			log_err("event_del error to startlisten");
6914 		}
6915 		c->event_added = 0;
6916 	}
6917 	if(msec != -1 && msec != 0) {
6918 		if(!c->timeout) {
6919 			c->timeout = (struct timeval*)malloc(sizeof(
6920 				struct timeval));
6921 			if(!c->timeout) {
6922 				log_err("cpsl: malloc failed. No net read.");
6923 				return;
6924 			}
6925 		}
6926 		ub_event_add_bits(c->ev->ev, UB_EV_TIMEOUT);
6927 #ifndef S_SPLINT_S /* splint fails on struct timeval. */
6928 		c->timeout->tv_sec = msec/1000;
6929 		c->timeout->tv_usec = (msec%1000)*1000;
6930 #endif /* S_SPLINT_S */
6931 	} else {
6932 		if(msec == 0 || !c->timeout) {
6933 			ub_event_del_bits(c->ev->ev, UB_EV_TIMEOUT);
6934 		}
6935 	}
6936 	if(c->type == comm_tcp || c->type == comm_http) {
6937 		ub_event_del_bits(c->ev->ev, UB_EV_READ|UB_EV_WRITE);
6938 		if(c->tcp_write_and_read) {
6939 			verbose(5, "startlistening %d mode rw", (newfd==-1?c->fd:newfd));
6940 			ub_event_add_bits(c->ev->ev, UB_EV_READ|UB_EV_WRITE);
6941 		} else if(c->tcp_is_reading) {
6942 			verbose(5, "startlistening %d mode r", (newfd==-1?c->fd:newfd));
6943 			ub_event_add_bits(c->ev->ev, UB_EV_READ);
6944 		} else	{
6945 			verbose(5, "startlistening %d mode w", (newfd==-1?c->fd:newfd));
6946 			ub_event_add_bits(c->ev->ev, UB_EV_WRITE);
6947 		}
6948 	}
6949 	if(newfd != -1) {
6950 		if(c->fd != -1 && c->fd != newfd) {
6951 			verbose(5, "cpsl close of fd %d for %d", c->fd, newfd);
6952 			sock_close(c->fd);
6953 		}
6954 		c->fd = newfd;
6955 		ub_event_set_fd(c->ev->ev, c->fd);
6956 	}
6957 	if(ub_event_add(c->ev->ev, msec==0?NULL:c->timeout) != 0) {
6958 		log_err("event_add failed. in cpsl.");
6959 		return;
6960 	}
6961 	c->event_added = 1;
6962 }
6963 
6964 void comm_point_listen_for_rw(struct comm_point* c, int rd, int wr)
6965 {
6966 	verbose(VERB_ALGO, "comm point listen_for_rw %d %d", c->fd, wr);
6967 	if(c->event_added) {
6968 		if(ub_event_del(c->ev->ev) != 0) {
6969 			log_err("event_del error to cplf");
6970 		}
6971 		c->event_added = 0;
6972 	}
6973 	if(!c->timeout) {
6974 		ub_event_del_bits(c->ev->ev, UB_EV_TIMEOUT);
6975 	}
6976 	ub_event_del_bits(c->ev->ev, UB_EV_READ|UB_EV_WRITE);
6977 	if(rd) ub_event_add_bits(c->ev->ev, UB_EV_READ);
6978 	if(wr) ub_event_add_bits(c->ev->ev, UB_EV_WRITE);
6979 	if(ub_event_add(c->ev->ev, c->timeout) != 0) {
6980 		log_err("event_add failed. in cplf.");
6981 		return;
6982 	}
6983 	c->event_added = 1;
6984 }
6985 
6986 size_t comm_point_get_mem(struct comm_point* c)
6987 {
6988 	size_t s;
6989 	if(!c)
6990 		return 0;
6991 	s = sizeof(*c) + sizeof(*c->ev);
6992 	if(c->timeout)
6993 		s += sizeof(*c->timeout);
6994 	if(c->type == comm_tcp || c->type == comm_local) {
6995 		s += sizeof(*c->buffer) + sldns_buffer_capacity(c->buffer);
6996 #ifdef USE_DNSCRYPT
6997 		s += sizeof(*c->dnscrypt_buffer);
6998 		if(c->buffer != c->dnscrypt_buffer) {
6999 			s += sldns_buffer_capacity(c->dnscrypt_buffer);
7000 		}
7001 #endif
7002 	}
7003 	if(c->type == comm_tcp_accept) {
7004 		int i;
7005 		for(i=0; i<c->max_tcp_count; i++)
7006 			s += comm_point_get_mem(c->tcp_handlers[i]);
7007 	}
7008 	return s;
7009 }
7010 
7011 struct comm_timer*
7012 comm_timer_create(struct comm_base* base, void (*cb)(void*), void* cb_arg)
7013 {
7014 	struct internal_timer *tm = (struct internal_timer*)calloc(1,
7015 		sizeof(struct internal_timer));
7016 	if(!tm) {
7017 		log_err("malloc failed");
7018 		return NULL;
7019 	}
7020 	tm->super.ev_timer = tm;
7021 	tm->base = base;
7022 	tm->super.callback = cb;
7023 	tm->super.cb_arg = cb_arg;
7024 	tm->ev = ub_event_new(base->eb->base, -1, UB_EV_TIMEOUT,
7025 		comm_timer_callback, &tm->super);
7026 	if(tm->ev == NULL) {
7027 		log_err("timer_create: event_base_set failed.");
7028 		free(tm);
7029 		return NULL;
7030 	}
7031 	return &tm->super;
7032 }
7033 
7034 void
7035 comm_timer_disable(struct comm_timer* timer)
7036 {
7037 	if(!timer)
7038 		return;
7039 	ub_timer_del(timer->ev_timer->ev);
7040 	timer->ev_timer->enabled = 0;
7041 }
7042 
7043 void
7044 comm_timer_set(struct comm_timer* timer, struct timeval* tv)
7045 {
7046 	log_assert(tv);
7047 	if(timer->ev_timer->enabled)
7048 		comm_timer_disable(timer);
7049 	if(ub_timer_add(timer->ev_timer->ev, timer->ev_timer->base->eb->base,
7050 		comm_timer_callback, timer, tv) != 0)
7051 		log_err("comm_timer_set: evtimer_add failed.");
7052 	timer->ev_timer->enabled = 1;
7053 }
7054 
7055 void
7056 comm_timer_delete(struct comm_timer* timer)
7057 {
7058 	if(!timer)
7059 		return;
7060 	comm_timer_disable(timer);
7061 	/* Free the sub struct timer->ev_timer derived from the super struct timer.
7062 	 * i.e. assert(timer == timer->ev_timer)
7063 	 */
7064 	ub_event_free(timer->ev_timer->ev);
7065 	free(timer->ev_timer);
7066 }
7067 
7068 void
7069 comm_timer_callback(int ATTR_UNUSED(fd), short event, void* arg)
7070 {
7071 	struct comm_timer* tm = (struct comm_timer*)arg;
7072 	if(!(event&UB_EV_TIMEOUT))
7073 		return;
7074 	ub_comm_base_now(tm->ev_timer->base);
7075 	tm->ev_timer->enabled = 0;
7076 	fptr_ok(fptr_whitelist_comm_timer(tm->callback));
7077 	(*tm->callback)(tm->cb_arg);
7078 }
7079 
7080 int
7081 comm_timer_is_set(struct comm_timer* timer)
7082 {
7083 	return (int)timer->ev_timer->enabled;
7084 }
7085 
7086 size_t
7087 comm_timer_get_mem(struct comm_timer* timer)
7088 {
7089 	if(!timer) return 0;
7090 	return sizeof(struct internal_timer);
7091 }
7092 
7093 struct comm_signal*
7094 comm_signal_create(struct comm_base* base,
7095         void (*callback)(int, void*), void* cb_arg)
7096 {
7097 	struct comm_signal* com = (struct comm_signal*)malloc(
7098 		sizeof(struct comm_signal));
7099 	if(!com) {
7100 		log_err("malloc failed");
7101 		return NULL;
7102 	}
7103 	com->base = base;
7104 	com->callback = callback;
7105 	com->cb_arg = cb_arg;
7106 	com->ev_signal = NULL;
7107 	return com;
7108 }
7109 
7110 void
7111 comm_signal_callback(int sig, short event, void* arg)
7112 {
7113 	struct comm_signal* comsig = (struct comm_signal*)arg;
7114 	if(!(event & UB_EV_SIGNAL))
7115 		return;
7116 	ub_comm_base_now(comsig->base);
7117 	fptr_ok(fptr_whitelist_comm_signal(comsig->callback));
7118 	(*comsig->callback)(sig, comsig->cb_arg);
7119 }
7120 
7121 int
7122 comm_signal_bind(struct comm_signal* comsig, int sig)
7123 {
7124 	struct internal_signal* entry = (struct internal_signal*)calloc(1,
7125 		sizeof(struct internal_signal));
7126 	if(!entry) {
7127 		log_err("malloc failed");
7128 		return 0;
7129 	}
7130 	log_assert(comsig);
7131 	/* add signal event */
7132 	entry->ev = ub_signal_new(comsig->base->eb->base, sig,
7133 		comm_signal_callback, comsig);
7134 	if(entry->ev == NULL) {
7135 		log_err("Could not create signal event");
7136 		free(entry);
7137 		return 0;
7138 	}
7139 	if(ub_signal_add(entry->ev, NULL) != 0) {
7140 		log_err("Could not add signal handler");
7141 		ub_event_free(entry->ev);
7142 		free(entry);
7143 		return 0;
7144 	}
7145 	/* link into list */
7146 	entry->next = comsig->ev_signal;
7147 	comsig->ev_signal = entry;
7148 	return 1;
7149 }
7150 
7151 void
7152 comm_signal_delete(struct comm_signal* comsig)
7153 {
7154 	struct internal_signal* p, *np;
7155 	if(!comsig)
7156 		return;
7157 	p=comsig->ev_signal;
7158 	while(p) {
7159 		np = p->next;
7160 		ub_signal_del(p->ev);
7161 		ub_event_free(p->ev);
7162 		free(p);
7163 		p = np;
7164 	}
7165 	free(comsig);
7166 }
7167