xref: /freebsd/contrib/unbound/services/listen_dnsport.c (revision 7a789145f88a6aceacc59029a0cafe7de7aeefea)
1 /*
2  * services/listen_dnsport.c - listen on port 53 for incoming DNS queries.
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 has functions to get queries from clients.
40  */
41 #include "config.h"
42 #ifdef HAVE_SYS_TYPES_H
43 #  include <sys/types.h>
44 #endif
45 #include <limits.h>
46 #ifdef USE_TCP_FASTOPEN
47 #include <netinet/tcp.h>
48 #endif
49 #include <ctype.h>
50 #include "services/listen_dnsport.h"
51 #include "services/outside_network.h"
52 #include "util/netevent.h"
53 #include "util/log.h"
54 #include "util/config_file.h"
55 #include "util/net_help.h"
56 #include "sldns/sbuffer.h"
57 #include "sldns/parseutil.h"
58 #include "sldns/wire2str.h"
59 #include "services/mesh.h"
60 #include "util/fptr_wlist.h"
61 #include "util/locks.h"
62 #include "util/timeval_func.h"
63 
64 #ifdef HAVE_NETDB_H
65 #include <netdb.h>
66 #endif
67 #include <fcntl.h>
68 
69 #ifdef HAVE_SYS_UN_H
70 #include <sys/un.h>
71 #endif
72 
73 #ifdef HAVE_SYSTEMD
74 #include <systemd/sd-daemon.h>
75 #endif
76 
77 #ifdef HAVE_IFADDRS_H
78 #include <ifaddrs.h>
79 #endif
80 #ifdef HAVE_NET_IF_H
81 #include <net/if.h>
82 #endif
83 
84 #ifdef HAVE_TIME_H
85 #include <time.h>
86 #endif
87 #include <sys/time.h>
88 
89 #ifdef HAVE_NGTCP2
90 #include <ngtcp2/ngtcp2.h>
91 #include <ngtcp2/ngtcp2_crypto.h>
92 #ifdef HAVE_NGTCP2_NGTCP2_CRYPTO_OSSL_H
93 #include <ngtcp2/ngtcp2_crypto_ossl.h>
94 #elif defined(HAVE_NGTCP2_NGTCP2_CRYPTO_QUICTLS_H)
95 #include <ngtcp2/ngtcp2_crypto_quictls.h>
96 #elif defined(HAVE_NGTCP2_NGTCP2_CRYPTO_OPENSSL_H)
97 #include <ngtcp2/ngtcp2_crypto_openssl.h>
98 #define MAKE_QUIC_METHOD 1
99 #endif
100 #endif
101 
102 #ifdef HAVE_OPENSSL_SSL_H
103 #include <openssl/ssl.h>
104 #endif
105 
106 #ifdef HAVE_LINUX_NET_TSTAMP_H
107 #include <linux/net_tstamp.h>
108 #endif
109 
110 /** number of queued TCP connections for listen() */
111 #define TCP_BACKLOG 256
112 
113 #ifndef THREADS_DISABLED
114 /** lock on the counter of stream buffer memory */
115 static lock_basic_type stream_wait_count_lock;
116 /** lock on the counter of HTTP2 query buffer memory */
117 static lock_basic_type http2_query_buffer_count_lock;
118 /** lock on the counter of HTTP2 response buffer memory */
119 static lock_basic_type http2_response_buffer_count_lock;
120 #endif
121 /** size (in bytes) of stream wait buffers */
122 static size_t stream_wait_count = 0;
123 /** is the lock initialised for stream wait buffers */
124 static int stream_wait_lock_inited = 0;
125 /** size (in bytes) of HTTP2 query buffers */
126 static size_t http2_query_buffer_count = 0;
127 /** is the lock initialised for HTTP2 query buffers */
128 static int http2_query_buffer_lock_inited = 0;
129 /** size (in bytes) of HTTP2 response buffers */
130 static size_t http2_response_buffer_count = 0;
131 /** is the lock initialised for HTTP2 response buffers */
132 static int http2_response_buffer_lock_inited = 0;
133 
134 /**
135  * Debug print of the getaddrinfo returned address.
136  * @param addr: the address returned.
137  * @param additional: additional text that describes the type of socket,
138  * 	or NULL for no text.
139  */
140 static void
verbose_print_addr(struct addrinfo * addr,const char * additional)141 verbose_print_addr(struct addrinfo *addr, const char* additional)
142 {
143 	if(verbosity >= VERB_ALGO) {
144 		char buf[100];
145 		void* sinaddr = &((struct sockaddr_in*)addr->ai_addr)->sin_addr;
146 #ifdef INET6
147 		if(addr->ai_family == AF_INET6)
148 			sinaddr = &((struct sockaddr_in6*)addr->ai_addr)->
149 				sin6_addr;
150 #endif /* INET6 */
151 		if(inet_ntop(addr->ai_family, sinaddr, buf,
152 			(socklen_t)sizeof(buf)) == 0) {
153 			(void)strlcpy(buf, "(null)", sizeof(buf));
154 		}
155 		buf[sizeof(buf)-1] = 0;
156 		verbose(VERB_ALGO, "creating %s%s socket %s %d%s%s",
157 			addr->ai_socktype==SOCK_DGRAM?"udp":
158 			addr->ai_socktype==SOCK_STREAM?"tcp":"otherproto",
159 			addr->ai_family==AF_INET?"4":
160 			addr->ai_family==AF_INET6?"6":
161 			"_otherfam", buf,
162 			ntohs(((struct sockaddr_in*)addr->ai_addr)->sin_port),
163 			(additional?" ":""), (additional?additional:""));
164 	}
165 }
166 
167 void
verbose_print_unbound_socket(struct unbound_socket * ub_sock)168 verbose_print_unbound_socket(struct unbound_socket* ub_sock)
169 {
170 	if(verbosity >= VERB_ALGO) {
171 		char buf[256];
172 		log_info("listing of unbound_socket structure:");
173 		addr_to_str((void*)ub_sock->addr, ub_sock->addrlen, buf,
174 			sizeof(buf));
175 		log_info("%s s is: %d, fam is: %s, acl: %s", buf, ub_sock->s,
176 			ub_sock->fam == AF_INET?"AF_INET":"AF_INET6",
177 			ub_sock->acl?"yes":"no");
178 	}
179 }
180 
181 #ifdef HAVE_SYSTEMD
182 static int
systemd_get_activated(int family,int socktype,int listen,struct sockaddr * addr,socklen_t addrlen,const char * path)183 systemd_get_activated(int family, int socktype, int listen,
184 		      struct sockaddr *addr, socklen_t addrlen,
185 		      const char *path)
186 {
187 	int i = 0;
188 	int r = 0;
189 	int s = -1;
190 	const char* listen_pid, *listen_fds;
191 
192 	/* We should use "listen" option only for stream protocols. For UDP it should be -1 */
193 
194 	if((r = sd_booted()) < 1) {
195 		if(r == 0)
196 			log_warn("systemd is not running");
197 		else
198 			log_err("systemd sd_booted(): %s", strerror(-r));
199 		return -1;
200 	}
201 
202 	listen_pid = getenv("LISTEN_PID");
203 	listen_fds = getenv("LISTEN_FDS");
204 
205 	if (!listen_pid) {
206 		log_warn("Systemd mandatory ENV variable is not defined: LISTEN_PID");
207 		return -1;
208 	}
209 
210 	if (!listen_fds) {
211 		log_warn("Systemd mandatory ENV variable is not defined: LISTEN_FDS");
212 		return -1;
213 	}
214 
215 	if((r = sd_listen_fds(0)) < 1) {
216 		if(r == 0)
217 			log_warn("systemd: did not return socket, check unit configuration");
218 		else
219 			log_err("systemd sd_listen_fds(): %s", strerror(-r));
220 		return -1;
221 	}
222 
223 	for(i = 0; i < r; i++) {
224 		if(sd_is_socket(SD_LISTEN_FDS_START + i, family, socktype, listen)) {
225 			s = SD_LISTEN_FDS_START + i;
226 			break;
227 		}
228 	}
229 	if (s == -1) {
230 		if (addr)
231 			log_err_addr("systemd sd_listen_fds()",
232 				     "no such socket",
233 				     (struct sockaddr_storage *)addr, addrlen);
234 		else
235 			log_err("systemd sd_listen_fds(): %s", path);
236 	}
237 	return s;
238 }
239 #endif
240 
241 int
create_udp_sock(int family,int socktype,struct sockaddr * addr,socklen_t addrlen,int v6only,int * inuse,int * noproto,int rcv,int snd,int listen,int * reuseport,int transparent,int freebind,int use_systemd,int dscp)242 create_udp_sock(int family, int socktype, struct sockaddr* addr,
243         socklen_t addrlen, int v6only, int* inuse, int* noproto,
244 	int rcv, int snd, int listen, int* reuseport, int transparent,
245 	int freebind, int use_systemd, int dscp)
246 {
247 	int s;
248 	char* err;
249 #if defined(SO_REUSEADDR) || defined(SO_REUSEPORT) || defined(IPV6_USE_MIN_MTU)  || defined(IP_TRANSPARENT) || defined(IP_BINDANY) || defined(IP_FREEBIND) || defined (SO_BINDANY)
250 	int on=1;
251 #endif
252 #ifdef IPV6_MTU
253 	int mtu = IPV6_MIN_MTU;
254 #endif
255 #if !defined(SO_RCVBUFFORCE) && !defined(SO_RCVBUF)
256 	(void)rcv;
257 #endif
258 #if !defined(SO_SNDBUFFORCE) && !defined(SO_SNDBUF)
259 	(void)snd;
260 #endif
261 #ifndef IPV6_V6ONLY
262 	(void)v6only;
263 #endif
264 #if !defined(IP_TRANSPARENT) && !defined(IP_BINDANY) && !defined(SO_BINDANY)
265 	(void)transparent;
266 #endif
267 #if !defined(IP_FREEBIND)
268 	(void)freebind;
269 #endif
270 #ifdef HAVE_SYSTEMD
271 	int got_fd_from_systemd = 0;
272 
273 	if (!use_systemd
274 	    || (use_systemd
275 		&& (s = systemd_get_activated(family, socktype, -1, addr,
276 					      addrlen, NULL)) == -1)) {
277 #else
278 	(void)use_systemd;
279 #endif
280 	if((s = socket(family, socktype, 0)) == -1) {
281 		*inuse = 0;
282 #ifndef USE_WINSOCK
283 		if(errno == EAFNOSUPPORT || errno == EPROTONOSUPPORT) {
284 			*noproto = 1;
285 			return -1;
286 		}
287 #else
288 		if(WSAGetLastError() == WSAEAFNOSUPPORT ||
289 			WSAGetLastError() == WSAEPROTONOSUPPORT) {
290 			*noproto = 1;
291 			return -1;
292 		}
293 #endif
294 		log_err("can't create socket: %s", sock_strerror(errno));
295 		*noproto = 0;
296 		return -1;
297 	}
298 #ifdef HAVE_SYSTEMD
299 	} else {
300 		got_fd_from_systemd = 1;
301 	}
302 #endif
303 	if(listen) {
304 #ifdef SO_REUSEADDR
305 		if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&on,
306 			(socklen_t)sizeof(on)) < 0) {
307 			log_err("setsockopt(.. SO_REUSEADDR ..) failed: %s",
308 				sock_strerror(errno));
309 #ifndef USE_WINSOCK
310 			if(errno != ENOSYS) {
311 				close(s);
312 				*noproto = 0;
313 				*inuse = 0;
314 				return -1;
315 			}
316 #else
317 			closesocket(s);
318 			*noproto = 0;
319 			*inuse = 0;
320 			return -1;
321 #endif
322 		}
323 #endif /* SO_REUSEADDR */
324 #ifdef SO_REUSEPORT
325 #  ifdef SO_REUSEPORT_LB
326 		/* on FreeBSD 12 we have SO_REUSEPORT_LB that does loadbalance
327 		 * like SO_REUSEPORT on Linux.  This is what the users want
328 		 * with the config option in unbound.conf; if we actually
329 		 * need local address and port reuse they'll also need to
330 		 * have SO_REUSEPORT set for them, assume it was _LB they want.
331 		 */
332 		if (reuseport && *reuseport &&
333 		    setsockopt(s, SOL_SOCKET, SO_REUSEPORT_LB, (void*)&on,
334 			(socklen_t)sizeof(on)) < 0) {
335 #ifdef ENOPROTOOPT
336 			if(errno != ENOPROTOOPT || verbosity >= 3)
337 				log_warn("setsockopt(.. SO_REUSEPORT_LB ..) failed: %s",
338 					strerror(errno));
339 #endif
340 			/* this option is not essential, we can continue */
341 			*reuseport = 0;
342 		}
343 #  else /* no SO_REUSEPORT_LB */
344 
345 		/* try to set SO_REUSEPORT so that incoming
346 		 * queries are distributed evenly among the receiving threads.
347 		 * Each thread must have its own socket bound to the same port,
348 		 * with SO_REUSEPORT set on each socket.
349 		 */
350 		if (reuseport && *reuseport &&
351 		    setsockopt(s, SOL_SOCKET, SO_REUSEPORT, (void*)&on,
352 			(socklen_t)sizeof(on)) < 0) {
353 #ifdef ENOPROTOOPT
354 			if(errno != ENOPROTOOPT || verbosity >= 3)
355 				log_warn("setsockopt(.. SO_REUSEPORT ..) failed: %s",
356 					strerror(errno));
357 #endif
358 			/* this option is not essential, we can continue */
359 			*reuseport = 0;
360 		}
361 #  endif /* SO_REUSEPORT_LB */
362 #else
363 		(void)reuseport;
364 #endif /* defined(SO_REUSEPORT) */
365 #ifdef IP_TRANSPARENT
366 		if (transparent &&
367 		    setsockopt(s, IPPROTO_IP, IP_TRANSPARENT, (void*)&on,
368 		    (socklen_t)sizeof(on)) < 0) {
369 			log_warn("setsockopt(.. IP_TRANSPARENT ..) failed: %s",
370 			strerror(errno));
371 		}
372 #elif defined(IP_BINDANY)
373 		if (transparent &&
374 		    setsockopt(s, (family==AF_INET6? IPPROTO_IPV6:IPPROTO_IP),
375 		    (family == AF_INET6? IPV6_BINDANY:IP_BINDANY),
376 		    (void*)&on, (socklen_t)sizeof(on)) < 0) {
377 			log_warn("setsockopt(.. IP%s_BINDANY ..) failed: %s",
378 			(family==AF_INET6?"V6":""), strerror(errno));
379 		}
380 #elif defined(SO_BINDANY)
381 		if (transparent &&
382 		    setsockopt(s, SOL_SOCKET, SO_BINDANY, (void*)&on,
383 		    (socklen_t)sizeof(on)) < 0) {
384 			log_warn("setsockopt(.. SO_BINDANY ..) failed: %s",
385 			strerror(errno));
386 		}
387 #endif /* IP_TRANSPARENT || IP_BINDANY || SO_BINDANY */
388 	}
389 #ifdef IP_FREEBIND
390 	if(freebind &&
391 	    setsockopt(s, IPPROTO_IP, IP_FREEBIND, (void*)&on,
392 	    (socklen_t)sizeof(on)) < 0) {
393 		log_warn("setsockopt(.. IP_FREEBIND ..) failed: %s",
394 		strerror(errno));
395 	}
396 #endif /* IP_FREEBIND */
397 	if(rcv) {
398 #ifdef SO_RCVBUF
399 		int got;
400 		socklen_t slen = (socklen_t)sizeof(got);
401 #  ifdef SO_RCVBUFFORCE
402 		/* Linux specific: try to use root permission to override
403 		 * system limits on rcvbuf. The limit is stored in
404 		 * /proc/sys/net/core/rmem_max or sysctl net.core.rmem_max */
405 		if(setsockopt(s, SOL_SOCKET, SO_RCVBUFFORCE, (void*)&rcv,
406 			(socklen_t)sizeof(rcv)) < 0) {
407 			if(errno != EPERM) {
408 				log_err("setsockopt(..., SO_RCVBUFFORCE, "
409 					"...) failed: %s", sock_strerror(errno));
410 				sock_close(s);
411 				*noproto = 0;
412 				*inuse = 0;
413 				return -1;
414 			}
415 #  endif /* SO_RCVBUFFORCE */
416 			if(setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void*)&rcv,
417 				(socklen_t)sizeof(rcv)) < 0) {
418 				log_err("setsockopt(..., SO_RCVBUF, "
419 					"...) failed: %s", sock_strerror(errno));
420 				sock_close(s);
421 				*noproto = 0;
422 				*inuse = 0;
423 				return -1;
424 			}
425 			/* check if we got the right thing or if system
426 			 * reduced to some system max.  Warn if so */
427 			if(getsockopt(s, SOL_SOCKET, SO_RCVBUF, (void*)&got,
428 				&slen) >= 0 && got < rcv/2) {
429 				log_warn("so-rcvbuf %u was not granted. "
430 					"Got %u. To fix: start with "
431 					"root permissions(linux) or sysctl "
432 					"bigger net.core.rmem_max(linux) or "
433 					"kern.ipc.maxsockbuf(bsd) values.",
434 					(unsigned)rcv, (unsigned)got);
435 			}
436 #  ifdef SO_RCVBUFFORCE
437 		}
438 #  endif
439 #endif /* SO_RCVBUF */
440 	}
441 	/* first do RCVBUF as the receive buffer is more important */
442 	if(snd) {
443 #ifdef SO_SNDBUF
444 		int got;
445 		socklen_t slen = (socklen_t)sizeof(got);
446 #  ifdef SO_SNDBUFFORCE
447 		/* Linux specific: try to use root permission to override
448 		 * system limits on sndbuf. The limit is stored in
449 		 * /proc/sys/net/core/wmem_max or sysctl net.core.wmem_max */
450 		if(setsockopt(s, SOL_SOCKET, SO_SNDBUFFORCE, (void*)&snd,
451 			(socklen_t)sizeof(snd)) < 0) {
452 			if(errno != EPERM && errno != ENOBUFS) {
453 				log_err("setsockopt(..., SO_SNDBUFFORCE, "
454 					"...) failed: %s", sock_strerror(errno));
455 				sock_close(s);
456 				*noproto = 0;
457 				*inuse = 0;
458 				return -1;
459 			}
460 			if(errno != EPERM) {
461 				verbose(VERB_ALGO, "setsockopt(..., SO_SNDBUFFORCE, "
462 					"...) was not granted: %s", sock_strerror(errno));
463 			}
464 #  endif /* SO_SNDBUFFORCE */
465 			if(setsockopt(s, SOL_SOCKET, SO_SNDBUF, (void*)&snd,
466 				(socklen_t)sizeof(snd)) < 0) {
467 				if(errno != ENOSYS && errno != ENOBUFS) {
468 					log_err("setsockopt(..., SO_SNDBUF, "
469 						"...) failed: %s", sock_strerror(errno));
470 					sock_close(s);
471 					*noproto = 0;
472 					*inuse = 0;
473 					return -1;
474 				}
475 				log_warn("setsockopt(..., SO_SNDBUF, "
476 					"...) was not granted: %s", sock_strerror(errno));
477 			}
478 			/* check if we got the right thing or if system
479 			 * reduced to some system max.  Warn if so */
480 			if(getsockopt(s, SOL_SOCKET, SO_SNDBUF, (void*)&got,
481 				&slen) >= 0 && got < snd/2) {
482 				log_warn("so-sndbuf %u was not granted. "
483 					"Got %u. To fix: start with "
484 					"root permissions(linux) or sysctl "
485 					"bigger net.core.wmem_max(linux) or "
486 					"kern.ipc.maxsockbuf(bsd) values. or "
487 					"set so-sndbuf: 0 (use system value).",
488 					(unsigned)snd, (unsigned)got);
489 			}
490 #  ifdef SO_SNDBUFFORCE
491 		}
492 #  endif
493 #endif /* SO_SNDBUF */
494 	}
495 	err = set_ip_dscp(s, family, dscp);
496 	if(err != NULL)
497 		log_warn("error setting IP DiffServ codepoint %d on UDP socket: %s", dscp, err);
498 	if(family == AF_INET6) {
499 # if defined(IPV6_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
500 		int omit6_set = 0;
501 		int action;
502 # endif
503 # if defined(IPV6_V6ONLY)
504 		if(v6only
505 #   ifdef HAVE_SYSTEMD
506 			/* Systemd wants to control if the socket is v6 only
507 			 * or both, with BindIPv6Only=default, ipv6-only or
508 			 * both in systemd.socket, so it is not set here. */
509 			&& !got_fd_from_systemd
510 #   endif
511 			) {
512 			int val=(v6only==2)?0:1;
513 			if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
514 				(void*)&val, (socklen_t)sizeof(val)) < 0) {
515 				log_err("setsockopt(..., IPV6_V6ONLY"
516 					", ...) failed: %s", sock_strerror(errno));
517 				sock_close(s);
518 				*noproto = 0;
519 				*inuse = 0;
520 				return -1;
521 			}
522 		}
523 # endif
524 # if defined(IPV6_USE_MIN_MTU)
525 		/*
526 		 * There is no fragmentation of IPv6 datagrams
527 		 * during forwarding in the network. Therefore
528 		 * we do not send UDP datagrams larger than
529 		 * the minimum IPv6 MTU of 1280 octets. The
530 		 * EDNS0 message length can be larger if the
531 		 * network stack supports IPV6_USE_MIN_MTU.
532 		 */
533 		if (setsockopt(s, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
534 			(void*)&on, (socklen_t)sizeof(on)) < 0) {
535 			log_err("setsockopt(..., IPV6_USE_MIN_MTU, "
536 				"...) failed: %s", sock_strerror(errno));
537 			sock_close(s);
538 			*noproto = 0;
539 			*inuse = 0;
540 			return -1;
541 		}
542 # elif defined(IPV6_MTU)
543 #   ifndef USE_WINSOCK
544 		/*
545 		 * On Linux, to send no larger than 1280, the PMTUD is
546 		 * disabled by default for datagrams anyway, so we set
547 		 * the MTU to use.
548 		 */
549 		if (setsockopt(s, IPPROTO_IPV6, IPV6_MTU,
550 			(void*)&mtu, (socklen_t)sizeof(mtu)) < 0) {
551 			log_err("setsockopt(..., IPV6_MTU, ...) failed: %s",
552 				sock_strerror(errno));
553 			sock_close(s);
554 			*noproto = 0;
555 			*inuse = 0;
556 			return -1;
557 		}
558 #   elif defined(IPV6_USER_MTU)
559 		/* As later versions of the mingw crosscompiler define
560 		 * IPV6_MTU, do the same for windows but use IPV6_USER_MTU
561 		 * instead which is writable; IPV6_MTU is readonly there. */
562 		if (setsockopt(s, IPPROTO_IPV6, IPV6_USER_MTU,
563 			(void*)&mtu, (socklen_t)sizeof(mtu)) < 0) {
564 			if (WSAGetLastError() != WSAENOPROTOOPT) {
565 				log_err("setsockopt(..., IPV6_USER_MTU, ...) failed: %s",
566 					wsa_strerror(WSAGetLastError()));
567 				sock_close(s);
568 				*noproto = 0;
569 				*inuse = 0;
570 				return -1;
571 			}
572 		}
573 #   endif /* USE_WINSOCK */
574 # endif /* IPv6 MTU */
575 # if defined(IPV6_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
576 #  if defined(IP_PMTUDISC_OMIT)
577 		action = IP_PMTUDISC_OMIT;
578 		if (setsockopt(s, IPPROTO_IPV6, IPV6_MTU_DISCOVER,
579 			&action, (socklen_t)sizeof(action)) < 0) {
580 
581 			if (errno != EINVAL) {
582 				log_err("setsockopt(..., IPV6_MTU_DISCOVER, IP_PMTUDISC_OMIT...) failed: %s",
583 					strerror(errno));
584 				sock_close(s);
585 				*noproto = 0;
586 				*inuse = 0;
587 				return -1;
588 			}
589 		}
590 		else
591 		{
592 		    omit6_set = 1;
593 		}
594 #  endif
595 		if (omit6_set == 0) {
596 			action = IP_PMTUDISC_DONT;
597 			if (setsockopt(s, IPPROTO_IPV6, IPV6_MTU_DISCOVER,
598 				&action, (socklen_t)sizeof(action)) < 0) {
599 				log_err("setsockopt(..., IPV6_MTU_DISCOVER, IP_PMTUDISC_DONT...) failed: %s",
600 					strerror(errno));
601 				sock_close(s);
602 				*noproto = 0;
603 				*inuse = 0;
604 				return -1;
605 			}
606 		}
607 # endif /* IPV6_MTU_DISCOVER */
608 	} else if(family == AF_INET) {
609 #  if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
610 /* linux 3.15 has IP_PMTUDISC_OMIT, Hannes Frederic Sowa made it so that
611  * PMTU information is not accepted, but fragmentation is allowed
612  * if and only if the packet size exceeds the outgoing interface MTU
613  * (and also uses the interface mtu to determine the size of the packets).
614  * So there won't be any EMSGSIZE error.  Against DNS fragmentation attacks.
615  * FreeBSD already has same semantics without setting the option. */
616 		int omit_set = 0;
617 		int action;
618 #   if defined(IP_PMTUDISC_OMIT)
619 		action = IP_PMTUDISC_OMIT;
620 		if (setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER,
621 			&action, (socklen_t)sizeof(action)) < 0) {
622 
623 			if (errno != EINVAL) {
624 				log_err("setsockopt(..., IP_MTU_DISCOVER, IP_PMTUDISC_OMIT...) failed: %s",
625 					strerror(errno));
626 				sock_close(s);
627 				*noproto = 0;
628 				*inuse = 0;
629 				return -1;
630 			}
631 		}
632 		else
633 		{
634 		    omit_set = 1;
635 		}
636 #   endif
637 		if (omit_set == 0) {
638    			action = IP_PMTUDISC_DONT;
639 			if (setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER,
640 				&action, (socklen_t)sizeof(action)) < 0) {
641 				log_err("setsockopt(..., IP_MTU_DISCOVER, IP_PMTUDISC_DONT...) failed: %s",
642 					strerror(errno));
643 				sock_close(s);
644 				*noproto = 0;
645 				*inuse = 0;
646 				return -1;
647 			}
648 		}
649 #  elif defined(IP_DONTFRAG) && !defined(__APPLE__)
650 		/* the IP_DONTFRAG option if defined in the 11.0 OSX headers,
651 		 * but does not work on that version, so we exclude it */
652 		/* a nonzero value disables fragmentation, according to
653 		 * docs.oracle.com for ip(4). */
654 		int off = 1;
655 		if (setsockopt(s, IPPROTO_IP, IP_DONTFRAG,
656 			&off, (socklen_t)sizeof(off)) < 0) {
657 			log_err("setsockopt(..., IP_DONTFRAG, ...) failed: %s",
658 				strerror(errno));
659 			sock_close(s);
660 			*noproto = 0;
661 			*inuse = 0;
662 			return -1;
663 		}
664 #  endif /* IPv4 MTU */
665 	}
666 	if(
667 #ifdef HAVE_SYSTEMD
668 		!got_fd_from_systemd &&
669 #endif
670 		bind(s, (struct sockaddr*)addr, addrlen) != 0) {
671 		*noproto = 0;
672 		*inuse = 0;
673 #ifndef USE_WINSOCK
674 #ifdef EADDRINUSE
675 		*inuse = (errno == EADDRINUSE);
676 		/* detect freebsd jail with no ipv6 permission */
677 		if(family==AF_INET6 && errno==EINVAL)
678 			*noproto = 1;
679 		else if(errno != EADDRINUSE &&
680 			!(errno == EACCES && verbosity < 4 && !listen)
681 #ifdef EADDRNOTAVAIL
682 			&& !(errno == EADDRNOTAVAIL && verbosity < 4 && !listen)
683 #endif
684 			) {
685 			log_err_addr("can't bind socket", strerror(errno),
686 				(struct sockaddr_storage*)addr, addrlen);
687 		}
688 #endif /* EADDRINUSE */
689 #else /* USE_WINSOCK */
690 		if(WSAGetLastError() != WSAEADDRINUSE &&
691 			WSAGetLastError() != WSAEADDRNOTAVAIL &&
692 			!(WSAGetLastError() == WSAEACCES && verbosity < 4 && !listen)) {
693 			log_err_addr("can't bind socket",
694 				wsa_strerror(WSAGetLastError()),
695 				(struct sockaddr_storage*)addr, addrlen);
696 		}
697 #endif /* USE_WINSOCK */
698 		sock_close(s);
699 		return -1;
700 	}
701 	if(!fd_set_nonblock(s)) {
702 		*noproto = 0;
703 		*inuse = 0;
704 		sock_close(s);
705 		return -1;
706 	}
707 	return s;
708 }
709 
710 int
create_tcp_accept_sock(struct addrinfo * addr,int v6only,int * noproto,int * reuseport,int transparent,int mss,int nodelay,int freebind,int use_systemd,int dscp,const char * additional)711 create_tcp_accept_sock(struct addrinfo *addr, int v6only, int* noproto,
712 	int* reuseport, int transparent, int mss, int nodelay, int freebind,
713 	int use_systemd, int dscp, const char* additional)
714 {
715 	int s = -1;
716 	char* err;
717 #if defined(SO_REUSEADDR) || defined(SO_REUSEPORT)		\
718 	|| defined(IPV6_V6ONLY) || defined(IP_TRANSPARENT)	\
719 	|| defined(IP_BINDANY) || defined(IP_FREEBIND)		\
720 	|| defined(SO_BINDANY) || defined(TCP_NODELAY)
721 	int on = 1;
722 #endif
723 #ifdef HAVE_SYSTEMD
724 	int got_fd_from_systemd = 0;
725 #endif
726 #ifdef USE_TCP_FASTOPEN
727 	int qlen;
728 #endif
729 #if !defined(IP_TRANSPARENT) && !defined(IP_BINDANY) && !defined(SO_BINDANY)
730 	(void)transparent;
731 #endif
732 #if !defined(IP_FREEBIND)
733 	(void)freebind;
734 #endif
735 	verbose_print_addr(addr, additional);
736 	*noproto = 0;
737 #ifdef HAVE_SYSTEMD
738 	if (!use_systemd ||
739 	    (use_systemd
740 	     && (s = systemd_get_activated(addr->ai_family, addr->ai_socktype, 1,
741 					   addr->ai_addr, addr->ai_addrlen,
742 					   NULL)) == -1)) {
743 #else
744 	(void)use_systemd;
745 #endif
746 	if((s = socket(addr->ai_family, addr->ai_socktype, 0)) == -1) {
747 #ifndef USE_WINSOCK
748 		if(errno == EAFNOSUPPORT || errno == EPROTONOSUPPORT) {
749 			*noproto = 1;
750 			return -1;
751 		}
752 #else
753 		if(WSAGetLastError() == WSAEAFNOSUPPORT ||
754 			WSAGetLastError() == WSAEPROTONOSUPPORT) {
755 			*noproto = 1;
756 			return -1;
757 		}
758 #endif
759 		log_err("can't create socket: %s", sock_strerror(errno));
760 		return -1;
761 	}
762 	if(nodelay) {
763 #if defined(IPPROTO_TCP) && defined(TCP_NODELAY)
764 		if(setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void*)&on,
765 			(socklen_t)sizeof(on)) < 0) {
766 			#ifndef USE_WINSOCK
767 			log_err(" setsockopt(.. TCP_NODELAY ..) failed: %s",
768 				strerror(errno));
769 			#else
770 			log_err(" setsockopt(.. TCP_NODELAY ..) failed: %s",
771 				wsa_strerror(WSAGetLastError()));
772 			#endif
773 		}
774 #else
775 		log_warn(" setsockopt(TCP_NODELAY) unsupported");
776 #endif /* defined(IPPROTO_TCP) && defined(TCP_NODELAY) */
777 	}
778 	if (mss > 0) {
779 #if defined(IPPROTO_TCP) && defined(TCP_MAXSEG)
780 		if(setsockopt(s, IPPROTO_TCP, TCP_MAXSEG, (void*)&mss,
781 			(socklen_t)sizeof(mss)) < 0) {
782 			log_err(" setsockopt(.. TCP_MAXSEG ..) failed: %s",
783 				sock_strerror(errno));
784 		} else {
785 			verbose(VERB_ALGO,
786 				" tcp socket mss set to %d", mss);
787 		}
788 #else
789 		log_warn(" setsockopt(TCP_MAXSEG) unsupported");
790 #endif /* defined(IPPROTO_TCP) && defined(TCP_MAXSEG) */
791 	}
792 #ifdef HAVE_SYSTEMD
793 	} else {
794 		got_fd_from_systemd = 1;
795     }
796 #endif
797 #ifdef SO_REUSEADDR
798 	if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&on,
799 		(socklen_t)sizeof(on)) < 0) {
800 		log_err("setsockopt(.. SO_REUSEADDR ..) failed: %s",
801 			sock_strerror(errno));
802 		sock_close(s);
803 		return -1;
804 	}
805 #endif /* SO_REUSEADDR */
806 #ifdef IP_FREEBIND
807 	if (freebind && setsockopt(s, IPPROTO_IP, IP_FREEBIND, (void*)&on,
808 	    (socklen_t)sizeof(on)) < 0) {
809 		log_warn("setsockopt(.. IP_FREEBIND ..) failed: %s",
810 		strerror(errno));
811 	}
812 #endif /* IP_FREEBIND */
813 #ifdef SO_REUSEPORT
814 	/* try to set SO_REUSEPORT so that incoming
815 	 * connections are distributed evenly among the receiving threads.
816 	 * Each thread must have its own socket bound to the same port,
817 	 * with SO_REUSEPORT set on each socket.
818 	 */
819 	if (reuseport && *reuseport &&
820 		setsockopt(s, SOL_SOCKET, SO_REUSEPORT, (void*)&on,
821 		(socklen_t)sizeof(on)) < 0) {
822 #ifdef ENOPROTOOPT
823 		if(errno != ENOPROTOOPT || verbosity >= 3)
824 			log_warn("setsockopt(.. SO_REUSEPORT ..) failed: %s",
825 				strerror(errno));
826 #endif
827 		/* this option is not essential, we can continue */
828 		*reuseport = 0;
829 	}
830 #else
831 	(void)reuseport;
832 #endif /* defined(SO_REUSEPORT) */
833 #if defined(IPV6_V6ONLY)
834 	if(addr->ai_family == AF_INET6 && v6only
835 #  ifdef HAVE_SYSTEMD
836 		/* Systemd wants to control if the socket is v6 only
837 		 * or both, with BindIPv6Only=default, ipv6-only or
838 		 * both in systemd.socket, so it is not set here. */
839 		&& !got_fd_from_systemd
840 #  endif
841 		) {
842 		if(setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
843 			(void*)&on, (socklen_t)sizeof(on)) < 0) {
844 			log_err("setsockopt(..., IPV6_V6ONLY, ...) failed: %s",
845 				sock_strerror(errno));
846 			sock_close(s);
847 			return -1;
848 		}
849 	}
850 #else
851 	(void)v6only;
852 #endif /* IPV6_V6ONLY */
853 #ifdef IP_TRANSPARENT
854 	if (transparent &&
855 	    setsockopt(s, IPPROTO_IP, IP_TRANSPARENT, (void*)&on,
856 	    (socklen_t)sizeof(on)) < 0) {
857 		log_warn("setsockopt(.. IP_TRANSPARENT ..) failed: %s",
858 			strerror(errno));
859 	}
860 #elif defined(IP_BINDANY)
861 	if (transparent &&
862 	    setsockopt(s, (addr->ai_family==AF_INET6? IPPROTO_IPV6:IPPROTO_IP),
863 	    (addr->ai_family == AF_INET6? IPV6_BINDANY:IP_BINDANY),
864 	    (void*)&on, (socklen_t)sizeof(on)) < 0) {
865 		log_warn("setsockopt(.. IP%s_BINDANY ..) failed: %s",
866 		(addr->ai_family==AF_INET6?"V6":""), strerror(errno));
867 	}
868 #elif defined(SO_BINDANY)
869 	if (transparent &&
870 	    setsockopt(s, SOL_SOCKET, SO_BINDANY, (void*)&on, (socklen_t)
871 	    sizeof(on)) < 0) {
872 		log_warn("setsockopt(.. SO_BINDANY ..) failed: %s",
873 		strerror(errno));
874 	}
875 #endif /* IP_TRANSPARENT || IP_BINDANY || SO_BINDANY */
876 	err = set_ip_dscp(s, addr->ai_family, dscp);
877 	if(err != NULL)
878 		log_warn("error setting IP DiffServ codepoint %d on TCP socket: %s", dscp, err);
879 	if(
880 #ifdef HAVE_SYSTEMD
881 		!got_fd_from_systemd &&
882 #endif
883         bind(s, addr->ai_addr, addr->ai_addrlen) != 0) {
884 #ifndef USE_WINSOCK
885 		/* detect freebsd jail with no ipv6 permission */
886 		if(addr->ai_family==AF_INET6 && errno==EINVAL)
887 			*noproto = 1;
888 		else {
889 			log_err_addr("can't bind socket", strerror(errno),
890 				(struct sockaddr_storage*)addr->ai_addr,
891 				addr->ai_addrlen);
892 		}
893 #else
894 		log_err_addr("can't bind socket",
895 			wsa_strerror(WSAGetLastError()),
896 			(struct sockaddr_storage*)addr->ai_addr,
897 			addr->ai_addrlen);
898 #endif
899 		sock_close(s);
900 		return -1;
901 	}
902 	if(!fd_set_nonblock(s)) {
903 		sock_close(s);
904 		return -1;
905 	}
906 	if(listen(s, TCP_BACKLOG) == -1) {
907 		log_err("can't listen: %s", sock_strerror(errno));
908 		sock_close(s);
909 		return -1;
910 	}
911 #ifdef USE_TCP_FASTOPEN
912 	/* qlen specifies how many outstanding TFO requests to allow. Limit is a defense
913 	   against IP spoofing attacks as suggested in RFC7413 */
914 #ifdef __APPLE__
915 	/* OS X implementation only supports qlen of 1 via this call. Actual
916 	   value is configured by the net.inet.tcp.fastopen_backlog kernel param. */
917 	qlen = 1;
918 #else
919 	/* 5 is recommended on linux */
920 	qlen = 5;
921 #endif
922 	if ((setsockopt(s, IPPROTO_TCP, TCP_FASTOPEN, &qlen,
923 		  sizeof(qlen))) == -1 ) {
924 #ifdef ENOPROTOOPT
925 		/* squelch ENOPROTOOPT: freebsd server mode with kernel support
926 		   disabled, except when verbosity enabled for debugging */
927 		if(errno != ENOPROTOOPT || verbosity >= 3) {
928 #endif
929 		  if(errno == EPERM) {
930 		  	log_warn("Setting TCP Fast Open as server failed: %s ; this could likely be because sysctl net.inet.tcp.fastopen.enabled, net.inet.tcp.fastopen.server_enable, or net.ipv4.tcp_fastopen is disabled", strerror(errno));
931 		  } else {
932 		  	log_err("Setting TCP Fast Open as server failed: %s", strerror(errno));
933 		  }
934 #ifdef ENOPROTOOPT
935 		}
936 #endif
937 	}
938 #endif
939 	return s;
940 }
941 
942 char*
set_ip_dscp(int socket,int addrfamily,int dscp)943 set_ip_dscp(int socket, int addrfamily, int dscp)
944 {
945 	int ds;
946 
947 	if(dscp == 0)
948 		return NULL;
949 	ds = dscp << 2;
950 	switch(addrfamily) {
951 	case AF_INET6:
952 	#ifdef IPV6_TCLASS
953 		if(setsockopt(socket, IPPROTO_IPV6, IPV6_TCLASS, (void*)&ds,
954 			sizeof(ds)) < 0)
955 			return sock_strerror(errno);
956 		break;
957 	#else
958 		return "IPV6_TCLASS not defined on this system";
959 	#endif
960 	default:
961 		if(setsockopt(socket, IPPROTO_IP, IP_TOS, (void*)&ds, sizeof(ds)) < 0)
962 			return sock_strerror(errno);
963 		break;
964 	}
965 	return NULL;
966 }
967 
968 int
create_local_accept_sock(const char * path,int * noproto,int use_systemd)969 create_local_accept_sock(const char *path, int* noproto, int use_systemd)
970 {
971 #ifdef HAVE_SYSTEMD
972 	int ret;
973 
974 	if (use_systemd && (ret = systemd_get_activated(AF_LOCAL, SOCK_STREAM, 1, NULL, 0, path)) != -1)
975 		return ret;
976 	else {
977 #endif
978 #ifdef HAVE_SYS_UN_H
979 	int s;
980 	struct sockaddr_un usock;
981 #ifndef HAVE_SYSTEMD
982 	(void)use_systemd;
983 #endif
984 
985 	verbose(VERB_ALGO, "creating unix socket %s", path);
986 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
987 	/* this member exists on BSDs, not Linux */
988 	usock.sun_len = (unsigned)sizeof(usock);
989 #endif
990 	usock.sun_family = AF_LOCAL;
991 	/* length is 92-108, 104 on FreeBSD */
992 	(void)strlcpy(usock.sun_path, path, sizeof(usock.sun_path));
993 
994 	if ((s = socket(AF_LOCAL, SOCK_STREAM, 0)) == -1) {
995 		log_err("Cannot create local socket %s (%s)",
996 			path, strerror(errno));
997 		return -1;
998 	}
999 
1000 	if (unlink(path) && errno != ENOENT) {
1001 		/* The socket already exists and cannot be removed */
1002 		log_err("Cannot remove old local socket %s (%s)",
1003 			path, strerror(errno));
1004 		goto err;
1005 	}
1006 
1007 	if (bind(s, (struct sockaddr *)&usock,
1008 		(socklen_t)sizeof(struct sockaddr_un)) == -1) {
1009 		log_err("Cannot bind local socket %s (%s)",
1010 			path, strerror(errno));
1011 		goto err;
1012 	}
1013 
1014 	if (!fd_set_nonblock(s)) {
1015 		log_err("Cannot set non-blocking mode");
1016 		goto err;
1017 	}
1018 
1019 	if (listen(s, TCP_BACKLOG) == -1) {
1020 		log_err("can't listen: %s", strerror(errno));
1021 		goto err;
1022 	}
1023 
1024 	(void)noproto; /*unused*/
1025 	return s;
1026 
1027 err:
1028 	sock_close(s);
1029 	return -1;
1030 
1031 #ifdef HAVE_SYSTEMD
1032 	}
1033 #endif
1034 #else
1035 	(void)use_systemd;
1036 	(void)path;
1037 	log_err("Local sockets are not supported");
1038 	*noproto = 1;
1039 	return -1;
1040 #endif
1041 }
1042 
1043 
1044 /**
1045  * Create socket from getaddrinfo results
1046  */
1047 static int
make_sock(int stype,const char * ifname,int port,struct addrinfo * hints,int v6only,int * noip6,size_t rcv,size_t snd,int * reuseport,int transparent,int tcp_mss,int nodelay,int freebind,int use_systemd,int dscp,struct unbound_socket * ub_sock,const char * additional)1048 make_sock(int stype, const char* ifname, int port,
1049 	struct addrinfo *hints, int v6only, int* noip6, size_t rcv, size_t snd,
1050 	int* reuseport, int transparent, int tcp_mss, int nodelay, int freebind,
1051 	int use_systemd, int dscp, struct unbound_socket* ub_sock,
1052 	const char* additional)
1053 {
1054 	struct addrinfo *res = NULL;
1055 	int r, s, inuse, noproto;
1056 	char portbuf[32];
1057 	snprintf(portbuf, sizeof(portbuf), "%d", port);
1058 	hints->ai_socktype = stype;
1059 	*noip6 = 0;
1060 	if((r=getaddrinfo(ifname, portbuf, hints, &res)) != 0 || !res) {
1061 #ifdef USE_WINSOCK
1062 		if(r == EAI_NONAME && hints->ai_family == AF_INET6){
1063 			*noip6 = 1; /* 'Host not found' for IP6 on winXP */
1064 			return -1;
1065 		}
1066 #endif
1067 		log_err("node %s:%s getaddrinfo: %s %s",
1068 			ifname?ifname:"default", portbuf, gai_strerror(r),
1069 #ifdef EAI_SYSTEM
1070 			(r==EAI_SYSTEM?(char*)strerror(errno):"")
1071 #else
1072 			""
1073 #endif
1074 		);
1075 		return -1;
1076 	}
1077 	if(stype == SOCK_DGRAM) {
1078 		verbose_print_addr(res, additional);
1079 		s = create_udp_sock(res->ai_family, res->ai_socktype,
1080 			(struct sockaddr*)res->ai_addr, res->ai_addrlen,
1081 			v6only, &inuse, &noproto, (int)rcv, (int)snd, 1,
1082 			reuseport, transparent, freebind, use_systemd, dscp);
1083 		if(s == -1 && inuse) {
1084 			log_err("bind: address already in use");
1085 		} else if(s == -1 && noproto && hints->ai_family == AF_INET6){
1086 			*noip6 = 1;
1087 		}
1088 	} else	{
1089 		s = create_tcp_accept_sock(res, v6only, &noproto, reuseport,
1090 			transparent, tcp_mss, nodelay, freebind, use_systemd,
1091 			dscp, additional);
1092 		if(s == -1 && noproto && hints->ai_family == AF_INET6){
1093 			*noip6 = 1;
1094 		}
1095 	}
1096 
1097 	if(!res->ai_addr) {
1098 		log_err("getaddrinfo returned no address");
1099 		freeaddrinfo(res);
1100 		sock_close(s);
1101 		return -1;
1102 	}
1103 	ub_sock->addr = memdup(res->ai_addr, res->ai_addrlen);
1104 	ub_sock->addrlen = res->ai_addrlen;
1105 	if(!ub_sock->addr) {
1106 		log_err("out of memory: allocate listening address");
1107 		freeaddrinfo(res);
1108 		sock_close(s);
1109 		return -1;
1110 	}
1111 	freeaddrinfo(res);
1112 
1113 	ub_sock->s = s;
1114 	ub_sock->fam = hints->ai_family;
1115 	ub_sock->acl = NULL;
1116 
1117 	return s;
1118 }
1119 
1120 /** make socket and first see if ifname contains port override info */
1121 static int
make_sock_port(int stype,const char * ifname,int port,struct addrinfo * hints,int v6only,int * noip6,size_t rcv,size_t snd,int * reuseport,int transparent,int tcp_mss,int nodelay,int freebind,int use_systemd,int dscp,struct unbound_socket * ub_sock,const char * additional)1122 make_sock_port(int stype, const char* ifname, int port,
1123 	struct addrinfo *hints, int v6only, int* noip6, size_t rcv, size_t snd,
1124 	int* reuseport, int transparent, int tcp_mss, int nodelay, int freebind,
1125 	int use_systemd, int dscp, struct unbound_socket* ub_sock,
1126 	const char* additional)
1127 {
1128 	const char* s = strchr(ifname, '@');
1129 	if(s) {
1130 		/* override port with ifspec@port */
1131 		int port;
1132 		char newif[128];
1133 		if((size_t)(s-ifname) >= sizeof(newif)) {
1134 			log_err("ifname too long: %s", ifname);
1135 			*noip6 = 0;
1136 			return -1;
1137 		}
1138 		port = atoi(s+1);
1139 		if(port < 0 || 0 == port || port > 65535) {
1140 			log_err("invalid portnumber in interface: %s", ifname);
1141 			*noip6 = 0;
1142 			return -1;
1143 		}
1144 		(void)strlcpy(newif, ifname, sizeof(newif));
1145 		newif[s-ifname] = 0;
1146 		return make_sock(stype, newif, port, hints, v6only, noip6, rcv,
1147 			snd, reuseport, transparent, tcp_mss, nodelay, freebind,
1148 			use_systemd, dscp, ub_sock, additional);
1149 	}
1150 	return make_sock(stype, ifname, port, hints, v6only, noip6, rcv, snd,
1151 		reuseport, transparent, tcp_mss, nodelay, freebind, use_systemd,
1152 		dscp, ub_sock, additional);
1153 }
1154 
1155 /**
1156  * Add port to open ports list.
1157  * @param list: list head. changed.
1158  * @param s: fd.
1159  * @param ftype: if fd is UDP.
1160  * @param pp2_enabled: if PROXYv2 is enabled for this port.
1161  * @param ub_sock: socket with address.
1162  * @return false on failure. list in unchanged then.
1163  */
1164 static int
port_insert(struct listen_port ** list,int s,enum listen_type ftype,int pp2_enabled,struct unbound_socket * ub_sock)1165 port_insert(struct listen_port** list, int s, enum listen_type ftype,
1166 	int pp2_enabled, struct unbound_socket* ub_sock)
1167 {
1168 	struct listen_port* item = (struct listen_port*)malloc(
1169 		sizeof(struct listen_port));
1170 	if(!item)
1171 		return 0;
1172 	item->next = *list;
1173 	item->fd = s;
1174 	item->ftype = ftype;
1175 	item->pp2_enabled = pp2_enabled;
1176 	item->socket = ub_sock;
1177 	*list = item;
1178 	return 1;
1179 }
1180 
1181 /** set fd to receive software timestamps */
1182 static int
set_recvtimestamp(int s)1183 set_recvtimestamp(int s)
1184 {
1185 #ifdef HAVE_LINUX_NET_TSTAMP_H
1186 	int opt = SOF_TIMESTAMPING_RX_SOFTWARE | SOF_TIMESTAMPING_SOFTWARE;
1187 	if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMPNS, (void*)&opt, (socklen_t)sizeof(opt)) < 0) {
1188 		log_err("setsockopt(..., SO_TIMESTAMPNS, ...) failed: %s",
1189 			strerror(errno));
1190 		return 0;
1191 	}
1192 	return 1;
1193 #elif defined(SO_TIMESTAMP) && defined(SCM_TIMESTAMP)
1194 	int on = 1;
1195 	/* FreeBSD and also Linux. */
1196 	if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, (void*)&on, (socklen_t)sizeof(on)) < 0) {
1197 		log_err("setsockopt(..., SO_TIMESTAMP, ...) failed: %s",
1198 			strerror(errno));
1199 		return 0;
1200 	}
1201 	return 1;
1202 #else
1203 	log_err("packets timestamping is not supported on this platform");
1204 	(void)s;
1205 	return 0;
1206 #endif
1207 }
1208 
1209 /** set fd to receive source address packet info */
1210 static int
set_recvpktinfo(int s,int family)1211 set_recvpktinfo(int s, int family)
1212 {
1213 #if defined(IPV6_RECVPKTINFO) || defined(IPV6_PKTINFO) || (defined(IP_RECVDSTADDR) && defined(IP_SENDSRCADDR)) || defined(IP_PKTINFO)
1214 	int on = 1;
1215 #else
1216 	(void)s;
1217 #endif
1218 	if(family == AF_INET6) {
1219 #           ifdef IPV6_RECVPKTINFO
1220 		if(setsockopt(s, IPPROTO_IPV6, IPV6_RECVPKTINFO,
1221 			(void*)&on, (socklen_t)sizeof(on)) < 0) {
1222 			log_err("setsockopt(..., IPV6_RECVPKTINFO, ...) failed: %s",
1223 				strerror(errno));
1224 			return 0;
1225 		}
1226 #           elif defined(IPV6_PKTINFO)
1227 		if(setsockopt(s, IPPROTO_IPV6, IPV6_PKTINFO,
1228 			(void*)&on, (socklen_t)sizeof(on)) < 0) {
1229 			log_err("setsockopt(..., IPV6_PKTINFO, ...) failed: %s",
1230 				strerror(errno));
1231 			return 0;
1232 		}
1233 #           else
1234 		log_err("no IPV6_RECVPKTINFO and IPV6_PKTINFO options, please "
1235 			"disable interface-automatic or do-ip6 in config");
1236 		return 0;
1237 #           endif /* defined IPV6_RECVPKTINFO */
1238 
1239 	} else if(family == AF_INET) {
1240 #           ifdef IP_PKTINFO
1241 		if(setsockopt(s, IPPROTO_IP, IP_PKTINFO,
1242 			(void*)&on, (socklen_t)sizeof(on)) < 0) {
1243 			log_err("setsockopt(..., IP_PKTINFO, ...) failed: %s",
1244 				strerror(errno));
1245 			return 0;
1246 		}
1247 #           elif defined(IP_RECVDSTADDR) && defined(IP_SENDSRCADDR)
1248 		if(setsockopt(s, IPPROTO_IP, IP_RECVDSTADDR,
1249 			(void*)&on, (socklen_t)sizeof(on)) < 0) {
1250 			log_err("setsockopt(..., IP_RECVDSTADDR, ...) failed: %s",
1251 				strerror(errno));
1252 			return 0;
1253 		}
1254 #           else
1255 		log_err("no IP_SENDSRCADDR or IP_PKTINFO option, please disable "
1256 			"interface-automatic or do-ip4 in config");
1257 		return 0;
1258 #           endif /* IP_PKTINFO */
1259 
1260 	}
1261 	return 1;
1262 }
1263 
1264 /**
1265  * Helper for ports_open. Creates one interface (or NULL for default).
1266  * @param ifname: The interface ip address.
1267  * @param do_auto: use automatic interface detection.
1268  * 	If enabled, then ifname must be the wildcard name.
1269  * @param do_udp: if udp should be used.
1270  * @param do_tcp: if tcp should be used.
1271  * @param hints: for getaddrinfo. family and flags have to be set by caller.
1272  * @param port: Port number to use.
1273  * @param list: list of open ports, appended to, changed to point to list head.
1274  * @param rcv: receive buffer size for UDP
1275  * @param snd: send buffer size for UDP
1276  * @param ssl_port: ssl service port number
1277  * @param tls_additional_port: list of additional ssl service port numbers.
1278  * @param https_port: DoH service port number
1279  * @param proxy_protocol_port: list of PROXYv2 port numbers.
1280  * @param reuseport: try to set SO_REUSEPORT if nonNULL and true.
1281  * 	set to false on exit if reuseport failed due to no kernel support.
1282  * @param transparent: set IP_TRANSPARENT socket option.
1283  * @param tcp_mss: maximum segment size of tcp socket. default if zero.
1284  * @param freebind: set IP_FREEBIND socket option.
1285  * @param http2_nodelay: set TCP_NODELAY on HTTP/2 connection
1286  * @param use_systemd: if true, fetch sockets from systemd.
1287  * @param dnscrypt_port: dnscrypt service port number
1288  * @param dscp: DSCP to use.
1289  * @param quic_port: dns over quic port number.
1290  * @param http_notls_downstream: if no tls is used for https downstream.
1291  * @param sock_queue_timeout: the sock_queue_timeout from config. Seconds to
1292  * 	wait to discard if UDP packets have waited for long in the socket
1293  * 	buffer.
1294  * @return: returns false on error.
1295  */
1296 static int
ports_create_if(const char * ifname,int do_auto,int do_udp,int do_tcp,struct addrinfo * hints,int port,struct listen_port ** list,size_t rcv,size_t snd,int ssl_port,struct config_strlist * tls_additional_port,int https_port,struct config_strlist * proxy_protocol_port,int * reuseport,int transparent,int tcp_mss,int freebind,int http2_nodelay,int use_systemd,int dnscrypt_port,int dscp,int quic_port,int http_notls_downstream,int sock_queue_timeout)1297 ports_create_if(const char* ifname, int do_auto, int do_udp, int do_tcp,
1298 	struct addrinfo *hints, int port, struct listen_port** list,
1299 	size_t rcv, size_t snd, int ssl_port,
1300 	struct config_strlist* tls_additional_port, int https_port,
1301 	struct config_strlist* proxy_protocol_port,
1302 	int* reuseport, int transparent, int tcp_mss, int freebind,
1303 	int http2_nodelay, int use_systemd, int dnscrypt_port, int dscp,
1304 	int quic_port, int http_notls_downstream, int sock_queue_timeout)
1305 {
1306 	int s, noip6=0;
1307 	int is_ssl = if_is_ssl(ifname, port, ssl_port, tls_additional_port);
1308 	int is_https = if_is_https(ifname, port, https_port);
1309 	int is_dnscrypt = if_is_dnscrypt(ifname, port, dnscrypt_port);
1310 	int is_pp2 = if_is_pp2(ifname, port, proxy_protocol_port);
1311 	int is_doq = if_is_quic(ifname, port, quic_port);
1312 	/* Always set TCP_NODELAY on TLS connection as it speeds up the TLS
1313 	 * handshake. DoH had already such option so we respect it.
1314 	 * Otherwise the server waits before sending more handshake data for
1315 	 * the client ACK (Nagle's algorithm), which is delayed because the
1316 	 * client waits for more data before ACKing (delayed ACK). */
1317 	int nodelay = is_https?http2_nodelay:is_ssl;
1318 	struct unbound_socket* ub_sock;
1319 	const char* add = NULL;
1320 
1321 	if(!do_udp && !do_tcp)
1322 		return 0;
1323 
1324 	if(is_pp2) {
1325 		if(is_dnscrypt) {
1326 			fatal_exit("PROXYv2 and DNSCrypt combination not "
1327 				"supported!");
1328 		} else if(is_https) {
1329 			fatal_exit("PROXYv2 and DoH combination not "
1330 				"supported!");
1331 		} else if(is_doq) {
1332 			fatal_exit("PROXYv2 and DoQ combination not "
1333 				"supported!");
1334 		}
1335 	}
1336 
1337 	/* Check if both UDP and TCP ports should be open.
1338 	 * In the case of encrypted channels, probably an unencrypted channel
1339 	 * at the same port is not desired. */
1340 	if((is_ssl || is_https) && !is_doq) do_udp = do_auto = 0;
1341 	if((is_doq) && !(is_https || is_ssl)) do_tcp = 0;
1342 
1343 	if(do_auto) {
1344 		ub_sock = calloc(1, sizeof(struct unbound_socket));
1345 		if(!ub_sock)
1346 			return 0;
1347 		if((s = make_sock_port(SOCK_DGRAM, ifname, port, hints, 1,
1348 			&noip6, rcv, snd, reuseport, transparent,
1349 			tcp_mss, nodelay, freebind, use_systemd, dscp, ub_sock,
1350 			(is_dnscrypt?"udpancil_dnscrypt":"udpancil"))) == -1) {
1351 			free(ub_sock->addr);
1352 			free(ub_sock);
1353 			if(noip6) {
1354 				log_warn("IPv6 protocol not available");
1355 				return 1;
1356 			}
1357 			return 0;
1358 		}
1359 		/* getting source addr packet info is highly non-portable */
1360 		if(!set_recvpktinfo(s, hints->ai_family)) {
1361 			sock_close(s);
1362 			free(ub_sock->addr);
1363 			free(ub_sock);
1364 			return 0;
1365 		}
1366 		if (sock_queue_timeout && !set_recvtimestamp(s)) {
1367 			log_warn("socket timestamping is not available");
1368 		}
1369 		if(!port_insert(list, s, is_dnscrypt
1370 			?listen_type_udpancil_dnscrypt:listen_type_udpancil,
1371 			is_pp2, ub_sock)) {
1372 			sock_close(s);
1373 			free(ub_sock->addr);
1374 			free(ub_sock);
1375 			return 0;
1376 		}
1377 	} else if(do_udp) {
1378 		enum listen_type udp_port_type;
1379 		ub_sock = calloc(1, sizeof(struct unbound_socket));
1380 		if(!ub_sock)
1381 			return 0;
1382 		if(is_dnscrypt) {
1383 			udp_port_type = listen_type_udp_dnscrypt;
1384 			add = "dnscrypt";
1385 		} else if(is_doq) {
1386 			udp_port_type = listen_type_doq;
1387 			add = "doq";
1388 			if(if_listens_on(ifname, port, 53, NULL)) {
1389 				log_err("DNS over QUIC is strictly not "
1390 					"allowed on port 53 as per RFC 9250. "
1391 					"Port 53 is for DNS datagrams. Error "
1392 					"for interface '%s'.", ifname);
1393 				free(ub_sock->addr);
1394 				free(ub_sock);
1395 				return 0;
1396 			}
1397 		} else {
1398 			udp_port_type = listen_type_udp;
1399 			add = NULL;
1400 		}
1401 		/* regular udp socket */
1402 		if((s = make_sock_port(SOCK_DGRAM, ifname, port, hints, 1,
1403 			&noip6, rcv, snd, reuseport, transparent,
1404 			tcp_mss, nodelay, freebind, use_systemd, dscp, ub_sock,
1405 			add)) == -1) {
1406 			free(ub_sock->addr);
1407 			free(ub_sock);
1408 			if(noip6) {
1409 				log_warn("IPv6 protocol not available");
1410 				return 1;
1411 			}
1412 			return 0;
1413 		}
1414 		if(udp_port_type == listen_type_doq) {
1415 			if(!set_recvpktinfo(s, hints->ai_family)) {
1416 				sock_close(s);
1417 				free(ub_sock->addr);
1418 				free(ub_sock);
1419 				return 0;
1420 			}
1421 		}
1422 		if(udp_port_type == listen_type_udp && sock_queue_timeout)
1423 			udp_port_type = listen_type_udpancil;
1424 		if (sock_queue_timeout) {
1425 			if(!set_recvtimestamp(s)) {
1426 				log_warn("socket timestamping is not available");
1427 			} else {
1428 				if(udp_port_type == listen_type_udp)
1429 					udp_port_type = listen_type_udpancil;
1430 			}
1431 		}
1432 		if(!port_insert(list, s, udp_port_type, is_pp2, ub_sock)) {
1433 			sock_close(s);
1434 			free(ub_sock->addr);
1435 			free(ub_sock);
1436 			return 0;
1437 		}
1438 	}
1439 	if(do_tcp) {
1440 		enum listen_type port_type;
1441 		ub_sock = calloc(1, sizeof(struct unbound_socket));
1442 		if(!ub_sock)
1443 			return 0;
1444 		if(is_ssl) {
1445 			port_type = listen_type_ssl;
1446 			add = "tls";
1447 		} else if(is_https) {
1448 			port_type = listen_type_http;
1449 			add = "https";
1450 			if(http_notls_downstream)
1451 				add = "http";
1452 		} else if(is_dnscrypt) {
1453 			port_type = listen_type_tcp_dnscrypt;
1454 			add = "dnscrypt";
1455 		} else {
1456 			port_type = listen_type_tcp;
1457 			add = NULL;
1458 		}
1459 		if((s = make_sock_port(SOCK_STREAM, ifname, port, hints, 1,
1460 			&noip6, 0, 0, reuseport, transparent, tcp_mss, nodelay,
1461 			freebind, use_systemd, dscp, ub_sock, add)) == -1) {
1462 			free(ub_sock->addr);
1463 			free(ub_sock);
1464 			if(noip6) {
1465 				/*log_warn("IPv6 protocol not available");*/
1466 				return 1;
1467 			}
1468 			return 0;
1469 		}
1470 		if(is_ssl)
1471 			verbose(VERB_ALGO, "setup TCP for SSL service");
1472 		if(!port_insert(list, s, port_type, is_pp2, ub_sock)) {
1473 			sock_close(s);
1474 			free(ub_sock->addr);
1475 			free(ub_sock);
1476 			return 0;
1477 		}
1478 	}
1479 	return 1;
1480 }
1481 
1482 /**
1483  * Add items to commpoint list in front.
1484  * @param c: commpoint to add.
1485  * @param front: listen struct.
1486  * @return: false on failure.
1487  */
1488 static int
listen_cp_insert(struct comm_point * c,struct listen_dnsport * front)1489 listen_cp_insert(struct comm_point* c, struct listen_dnsport* front)
1490 {
1491 	struct listen_list* item = (struct listen_list*)malloc(
1492 		sizeof(struct listen_list));
1493 	if(!item)
1494 		return 0;
1495 	item->com = c;
1496 	item->next = front->cps;
1497 	front->cps = item;
1498 	return 1;
1499 }
1500 
listen_setup_locks(void)1501 void listen_setup_locks(void)
1502 {
1503 	if(!stream_wait_lock_inited) {
1504 		lock_basic_init(&stream_wait_count_lock);
1505 		stream_wait_lock_inited = 1;
1506 	}
1507 	if(!http2_query_buffer_lock_inited) {
1508 		lock_basic_init(&http2_query_buffer_count_lock);
1509 		http2_query_buffer_lock_inited = 1;
1510 	}
1511 	if(!http2_response_buffer_lock_inited) {
1512 		lock_basic_init(&http2_response_buffer_count_lock);
1513 		http2_response_buffer_lock_inited = 1;
1514 	}
1515 }
1516 
listen_desetup_locks(void)1517 void listen_desetup_locks(void)
1518 {
1519 	if(stream_wait_lock_inited) {
1520 		stream_wait_lock_inited = 0;
1521 		lock_basic_destroy(&stream_wait_count_lock);
1522 	}
1523 	if(http2_query_buffer_lock_inited) {
1524 		http2_query_buffer_lock_inited = 0;
1525 		lock_basic_destroy(&http2_query_buffer_count_lock);
1526 	}
1527 	if(http2_response_buffer_lock_inited) {
1528 		http2_response_buffer_lock_inited = 0;
1529 		lock_basic_destroy(&http2_response_buffer_count_lock);
1530 	}
1531 }
1532 
1533 struct listen_dnsport*
listen_create(struct comm_base * base,struct listen_port * ports,size_t bufsize,int tcp_accept_count,int tcp_idle_timeout,int harden_large_queries,uint32_t http_max_streams,char * http_endpoint,int http_notls,struct tcl_list * tcp_conn_limit,void * dot_sslctx,void * doh_sslctx,void * quic_sslctx,struct dt_env * dtenv,struct doq_table * doq_table,struct ub_randstate * rnd,struct config_file * cfg,comm_point_callback_type * cb,void * cb_arg)1534 listen_create(struct comm_base* base, struct listen_port* ports,
1535 	size_t bufsize, int tcp_accept_count, int tcp_idle_timeout,
1536 	int harden_large_queries, uint32_t http_max_streams,
1537 	char* http_endpoint, int http_notls, struct tcl_list* tcp_conn_limit,
1538 	void* dot_sslctx, void* doh_sslctx, void* quic_sslctx,
1539 	struct dt_env* dtenv,
1540 	struct doq_table* doq_table,
1541 	struct ub_randstate* rnd,struct config_file* cfg,
1542 	comm_point_callback_type* cb, void *cb_arg)
1543 {
1544 	struct listen_dnsport* front = (struct listen_dnsport*)
1545 		malloc(sizeof(struct listen_dnsport));
1546 	if(!front)
1547 		return NULL;
1548 	front->cps = NULL;
1549 	front->udp_buff = sldns_buffer_new(bufsize);
1550 #ifdef USE_DNSCRYPT
1551 	front->dnscrypt_udp_buff = NULL;
1552 #endif
1553 	if(!front->udp_buff) {
1554 		free(front);
1555 		return NULL;
1556 	}
1557 
1558 	/* create comm points as needed */
1559 	while(ports) {
1560 		struct comm_point* cp = NULL;
1561 		if(ports->ftype == listen_type_udp ||
1562 		   ports->ftype == listen_type_udp_dnscrypt) {
1563 			cp = comm_point_create_udp(base, ports->fd,
1564 				front->udp_buff, ports->pp2_enabled, cb,
1565 				cb_arg, ports->socket);
1566 		} else if(ports->ftype == listen_type_doq && doq_table) {
1567 #ifndef HAVE_NGTCP2
1568 			log_warn("Unbound is not compiled with "
1569 				"ngtcp2. This is required to use DNS "
1570 				"over QUIC.");
1571 #endif
1572 			cp = comm_point_create_doq(base, ports->fd,
1573 				front->udp_buff, cb, cb_arg, ports->socket,
1574 				doq_table, rnd, quic_sslctx, cfg);
1575 		} else if(ports->ftype == listen_type_tcp ||
1576 				ports->ftype == listen_type_tcp_dnscrypt) {
1577 			cp = comm_point_create_tcp(base, ports->fd,
1578 				tcp_accept_count, tcp_idle_timeout,
1579 				harden_large_queries, 0, NULL,
1580 				tcp_conn_limit, bufsize, front->udp_buff,
1581 				ports->ftype, ports->pp2_enabled, cb, cb_arg,
1582 				ports->socket);
1583 		} else if(ports->ftype == listen_type_ssl ||
1584 			ports->ftype == listen_type_http) {
1585 			cp = comm_point_create_tcp(base, ports->fd,
1586 				tcp_accept_count, tcp_idle_timeout,
1587 				harden_large_queries,
1588 				http_max_streams, http_endpoint,
1589 				tcp_conn_limit, bufsize, front->udp_buff,
1590 				ports->ftype, ports->pp2_enabled, cb, cb_arg,
1591 				ports->socket);
1592 			if(ports->ftype == listen_type_http) {
1593 				if(!doh_sslctx && !http_notls) {
1594 					log_warn("HTTPS port configured, but "
1595 						"no TLS tls-service-key or "
1596 						"tls-service-pem set");
1597 				}
1598 #ifndef HAVE_SSL_CTX_SET_ALPN_SELECT_CB
1599 				if(!http_notls) {
1600 					log_warn("Unbound is not compiled "
1601 						"with an OpenSSL version "
1602 						"supporting ALPN "
1603 						"(OpenSSL >= 1.0.2). This "
1604 						"is required to use "
1605 						"DNS-over-HTTPS");
1606 				}
1607 #endif
1608 #ifndef HAVE_NGHTTP2_NGHTTP2_H
1609 				log_warn("Unbound is not compiled with "
1610 					"nghttp2. This is required to use "
1611 					"DNS-over-HTTPS.");
1612 #endif
1613 			}
1614 		} else if(ports->ftype == listen_type_udpancil ||
1615 				  ports->ftype == listen_type_udpancil_dnscrypt) {
1616 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && defined(HAVE_RECVMSG)
1617 			cp = comm_point_create_udp_ancil(base, ports->fd,
1618 				front->udp_buff, ports->pp2_enabled, cb,
1619 				cb_arg, ports->socket);
1620 #else
1621 			log_warn("This system does not support UDP ancillary data.");
1622 #endif
1623 		}
1624 		if(!cp) {
1625 			log_err("can't create commpoint");
1626 			listen_delete(front);
1627 			return NULL;
1628 		}
1629 		if((http_notls && ports->ftype == listen_type_http) ||
1630 			(ports->ftype == listen_type_tcp) ||
1631 			(ports->ftype == listen_type_udp) ||
1632 			(ports->ftype == listen_type_udpancil) ||
1633 			(ports->ftype == listen_type_tcp_dnscrypt) ||
1634 			(ports->ftype == listen_type_udp_dnscrypt) ||
1635 			(ports->ftype == listen_type_udpancil_dnscrypt)) {
1636 			cp->ssl = NULL;
1637 		} else if(ports->ftype == listen_type_doq) {
1638 			cp->ssl = quic_sslctx;
1639 		} else if(ports->ftype == listen_type_http) {
1640 			cp->ssl = doh_sslctx;
1641 		} else {
1642 			cp->ssl = dot_sslctx;
1643 		}
1644 		cp->dtenv = dtenv;
1645 		cp->do_not_close = 1;
1646 #ifdef USE_DNSCRYPT
1647 		if (ports->ftype == listen_type_udp_dnscrypt ||
1648 			ports->ftype == listen_type_tcp_dnscrypt ||
1649 			ports->ftype == listen_type_udpancil_dnscrypt) {
1650 			cp->dnscrypt = 1;
1651 			cp->dnscrypt_buffer = sldns_buffer_new(bufsize);
1652 			if(!cp->dnscrypt_buffer) {
1653 				log_err("can't alloc dnscrypt_buffer");
1654 				comm_point_delete(cp);
1655 				listen_delete(front);
1656 				return NULL;
1657 			}
1658 			front->dnscrypt_udp_buff = cp->dnscrypt_buffer;
1659 		}
1660 #endif
1661 		if(!listen_cp_insert(cp, front)) {
1662 			log_err("malloc failed");
1663 			comm_point_delete(cp);
1664 			listen_delete(front);
1665 			return NULL;
1666 		}
1667 		ports = ports->next;
1668 	}
1669 	if(!front->cps) {
1670 		log_err("Could not open sockets to accept queries.");
1671 		listen_delete(front);
1672 		return NULL;
1673 	}
1674 
1675 	return front;
1676 }
1677 
1678 void
listen_list_delete(struct listen_list * list)1679 listen_list_delete(struct listen_list* list)
1680 {
1681 	struct listen_list *p = list, *pn;
1682 	while(p) {
1683 		pn = p->next;
1684 		comm_point_delete(p->com);
1685 		free(p);
1686 		p = pn;
1687 	}
1688 }
1689 
1690 void
listen_delete(struct listen_dnsport * front)1691 listen_delete(struct listen_dnsport* front)
1692 {
1693 	if(!front)
1694 		return;
1695 	listen_list_delete(front->cps);
1696 #ifdef USE_DNSCRYPT
1697 	if(front->dnscrypt_udp_buff &&
1698 		front->udp_buff != front->dnscrypt_udp_buff) {
1699 		sldns_buffer_free(front->dnscrypt_udp_buff);
1700 	}
1701 #endif
1702 	sldns_buffer_free(front->udp_buff);
1703 	free(front);
1704 }
1705 
1706 #ifdef HAVE_GETIFADDRS
1707 static int
resolve_ifa_name(struct ifaddrs * ifas,const char * search_ifa,char *** ip_addresses,int * ip_addresses_size)1708 resolve_ifa_name(struct ifaddrs *ifas, const char *search_ifa, char ***ip_addresses, int *ip_addresses_size)
1709 {
1710 	struct ifaddrs *ifa;
1711 	void *tmpbuf;
1712 	int last_ip_addresses_size = *ip_addresses_size;
1713 
1714 	for(ifa = ifas; ifa != NULL; ifa = ifa->ifa_next) {
1715 		sa_family_t family;
1716 		const char* atsign;
1717 #ifdef INET6      /* |   address ip    | % |  ifa name  | @ |  port  | nul */
1718 		char addr_buf[INET6_ADDRSTRLEN + 1 + IF_NAMESIZE + 1 + 16 + 1];
1719 #else
1720 		char addr_buf[INET_ADDRSTRLEN + 1 + 16 + 1];
1721 #endif
1722 
1723 		if((atsign=strrchr(search_ifa, '@')) != NULL) {
1724 			if(strlen(ifa->ifa_name) != (size_t)(atsign-search_ifa)
1725 			   || strncmp(ifa->ifa_name, search_ifa,
1726 			   atsign-search_ifa) != 0)
1727 				continue;
1728 		} else {
1729 			if(strcmp(ifa->ifa_name, search_ifa) != 0)
1730 				continue;
1731 			atsign = "";
1732 		}
1733 
1734 		if(ifa->ifa_addr == NULL)
1735 			continue;
1736 
1737 		family = ifa->ifa_addr->sa_family;
1738 		if(family == AF_INET) {
1739 			char a4[INET_ADDRSTRLEN + 1];
1740 			struct sockaddr_in *in4 = (struct sockaddr_in *)
1741 				ifa->ifa_addr;
1742 			if(!inet_ntop(family, &in4->sin_addr, a4, sizeof(a4))) {
1743 				log_err("inet_ntop failed");
1744 				return 0;
1745 			}
1746 			snprintf(addr_buf, sizeof(addr_buf), "%s%s",
1747 				a4, atsign);
1748 		}
1749 #ifdef INET6
1750 		else if(family == AF_INET6) {
1751 			struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)
1752 				ifa->ifa_addr;
1753 			char a6[INET6_ADDRSTRLEN + 1];
1754 			char if_index_name[IF_NAMESIZE + 1];
1755 			if_index_name[0] = 0;
1756 			if(!inet_ntop(family, &in6->sin6_addr, a6, sizeof(a6))) {
1757 				log_err("inet_ntop failed");
1758 				return 0;
1759 			}
1760 			(void)if_indextoname(in6->sin6_scope_id,
1761 				(char *)if_index_name);
1762 			if (strlen(if_index_name) != 0) {
1763 				snprintf(addr_buf, sizeof(addr_buf),
1764 					"%s%%%s%s", a6, if_index_name, atsign);
1765 			} else {
1766 				snprintf(addr_buf, sizeof(addr_buf), "%s%s",
1767 					a6, atsign);
1768 			}
1769 		}
1770 #endif
1771 		else {
1772 			continue;
1773 		}
1774 		verbose(4, "interface %s has address %s", search_ifa, addr_buf);
1775 
1776 		tmpbuf = realloc(*ip_addresses, sizeof(char *) * (*ip_addresses_size + 1));
1777 		if(!tmpbuf) {
1778 			log_err("realloc failed: out of memory");
1779 			return 0;
1780 		} else {
1781 			*ip_addresses = tmpbuf;
1782 		}
1783 		(*ip_addresses)[*ip_addresses_size] = strdup(addr_buf);
1784 		if(!(*ip_addresses)[*ip_addresses_size]) {
1785 			log_err("strdup failed: out of memory");
1786 			return 0;
1787 		}
1788 		(*ip_addresses_size)++;
1789 	}
1790 
1791 	if (*ip_addresses_size == last_ip_addresses_size) {
1792 		tmpbuf = realloc(*ip_addresses, sizeof(char *) * (*ip_addresses_size + 1));
1793 		if(!tmpbuf) {
1794 			log_err("realloc failed: out of memory");
1795 			return 0;
1796 		} else {
1797 			*ip_addresses = tmpbuf;
1798 		}
1799 		(*ip_addresses)[*ip_addresses_size] = strdup(search_ifa);
1800 		if(!(*ip_addresses)[*ip_addresses_size]) {
1801 			log_err("strdup failed: out of memory");
1802 			return 0;
1803 		}
1804 		(*ip_addresses_size)++;
1805 	}
1806 	return 1;
1807 }
1808 #endif /* HAVE_GETIFADDRS */
1809 
resolve_interface_names(char ** ifs,int num_ifs,struct config_strlist * list,char *** resif,int * num_resif)1810 int resolve_interface_names(char** ifs, int num_ifs,
1811 	struct config_strlist* list, char*** resif, int* num_resif)
1812 {
1813 #ifdef HAVE_GETIFADDRS
1814 	struct ifaddrs *addrs = NULL;
1815 	if(num_ifs == 0 && list == NULL) {
1816 		*resif = NULL;
1817 		*num_resif = 0;
1818 		return 1;
1819 	}
1820 	if(getifaddrs(&addrs) == -1) {
1821 		log_err("failed to list interfaces: getifaddrs: %s",
1822 			strerror(errno));
1823 		freeifaddrs(addrs);
1824 		return 0;
1825 	}
1826 	if(ifs) {
1827 		int i;
1828 		for(i=0; i<num_ifs; i++) {
1829 			if(!resolve_ifa_name(addrs, ifs[i], resif, num_resif)) {
1830 				freeifaddrs(addrs);
1831 				config_del_strarray(*resif, *num_resif);
1832 				*resif = NULL;
1833 				*num_resif = 0;
1834 				return 0;
1835 			}
1836 		}
1837 	}
1838 	if(list) {
1839 		struct config_strlist* p;
1840 		for(p = list; p; p = p->next) {
1841 			if(!resolve_ifa_name(addrs, p->str, resif, num_resif)) {
1842 				freeifaddrs(addrs);
1843 				config_del_strarray(*resif, *num_resif);
1844 				*resif = NULL;
1845 				*num_resif = 0;
1846 				return 0;
1847 			}
1848 }
1849 	}
1850 	freeifaddrs(addrs);
1851 	return 1;
1852 #else
1853 	struct config_strlist* p;
1854 	if(num_ifs == 0 && list == NULL) {
1855 		*resif = NULL;
1856 		*num_resif = 0;
1857 		return 1;
1858 	}
1859 	*num_resif = num_ifs;
1860 	for(p = list; p; p = p->next) {
1861 		(*num_resif)++;
1862 	}
1863 	*resif = calloc(*num_resif, sizeof(**resif));
1864 	if(!*resif) {
1865 		log_err("out of memory");
1866 		return 0;
1867 	}
1868 	if(ifs) {
1869 		int i;
1870 		for(i=0; i<num_ifs; i++) {
1871 			(*resif)[i] = strdup(ifs[i]);
1872 			if(!((*resif)[i])) {
1873 				log_err("out of memory");
1874 				config_del_strarray(*resif, *num_resif);
1875 				*resif = NULL;
1876 				*num_resif = 0;
1877 				return 0;
1878 			}
1879 		}
1880 	}
1881 	if(list) {
1882 		int idx = num_ifs;
1883 		for(p = list; p; p = p->next) {
1884 			(*resif)[idx] = strdup(p->str);
1885 			if(!((*resif)[idx])) {
1886 				log_err("out of memory");
1887 				config_del_strarray(*resif, *num_resif);
1888 				*resif = NULL;
1889 				*num_resif = 0;
1890 				return 0;
1891 			}
1892 			idx++;
1893 		}
1894 	}
1895 	return 1;
1896 #endif /* HAVE_GETIFADDRS */
1897 }
1898 
1899 struct listen_port*
listening_ports_open(struct config_file * cfg,char ** ifs,int num_ifs,int * reuseport)1900 listening_ports_open(struct config_file* cfg, char** ifs, int num_ifs,
1901 	int* reuseport)
1902 {
1903 	struct listen_port* list = NULL;
1904 	struct addrinfo hints;
1905 	int i, do_ip4, do_ip6;
1906 	int do_tcp, do_auto;
1907 	do_ip4 = cfg->do_ip4;
1908 	do_ip6 = cfg->do_ip6;
1909 	do_tcp = cfg->do_tcp;
1910 	do_auto = cfg->if_automatic && cfg->do_udp;
1911 	if(cfg->incoming_num_tcp == 0)
1912 		do_tcp = 0;
1913 
1914 	/* getaddrinfo */
1915 	memset(&hints, 0, sizeof(hints));
1916 	hints.ai_flags = AI_PASSIVE;
1917 	/* no name lookups on our listening ports */
1918 	if(num_ifs > 0)
1919 		hints.ai_flags |= AI_NUMERICHOST;
1920 	hints.ai_family = AF_UNSPEC;
1921 #ifndef INET6
1922 	do_ip6 = 0;
1923 #endif
1924 	if(!do_ip4 && !do_ip6) {
1925 		return NULL;
1926 	}
1927 	/* create ip4 and ip6 ports so that return addresses are nice. */
1928 	if(do_auto || num_ifs == 0) {
1929 		if(do_auto && cfg->if_automatic_ports &&
1930 			cfg->if_automatic_ports[0]!=0) {
1931 			char* now = cfg->if_automatic_ports;
1932 			while(now && *now) {
1933 				char* after;
1934 				int extraport;
1935 				while(isspace((unsigned char)*now))
1936 					now++;
1937 				if(!*now)
1938 					break;
1939 				after = now;
1940 				extraport = (int)strtol(now, &after, 10);
1941 				if(extraport < 0 || extraport > 65535) {
1942 					log_err("interface-automatic-ports port number out of range, at position %d of '%s'", (int)(now-cfg->if_automatic_ports)+1, cfg->if_automatic_ports);
1943 					listening_ports_free(list);
1944 					return NULL;
1945 				}
1946 				if(extraport == 0 && now == after) {
1947 					log_err("interface-automatic-ports could not be parsed, at position %d of '%s'", (int)(now-cfg->if_automatic_ports)+1, cfg->if_automatic_ports);
1948 					listening_ports_free(list);
1949 					return NULL;
1950 				}
1951 				now = after;
1952 				if(do_ip6) {
1953 					hints.ai_family = AF_INET6;
1954 					if(!ports_create_if("::0",
1955 						do_auto, cfg->do_udp, do_tcp,
1956 						&hints, extraport, &list,
1957 						cfg->so_rcvbuf, cfg->so_sndbuf,
1958 						cfg->ssl_port, cfg->tls_additional_port,
1959 						cfg->https_port,
1960 						cfg->proxy_protocol_port,
1961 						reuseport, cfg->ip_transparent,
1962 						cfg->tcp_mss, cfg->ip_freebind,
1963 						cfg->http_nodelay, cfg->use_systemd,
1964 						cfg->dnscrypt_port, cfg->ip_dscp,
1965 						cfg->quic_port, cfg->http_notls_downstream,
1966 						cfg->sock_queue_timeout)) {
1967 						listening_ports_free(list);
1968 						return NULL;
1969 					}
1970 				}
1971 				if(do_ip4) {
1972 					hints.ai_family = AF_INET;
1973 					if(!ports_create_if("0.0.0.0",
1974 						do_auto, cfg->do_udp, do_tcp,
1975 						&hints, extraport, &list,
1976 						cfg->so_rcvbuf, cfg->so_sndbuf,
1977 						cfg->ssl_port, cfg->tls_additional_port,
1978 						cfg->https_port,
1979 						cfg->proxy_protocol_port,
1980 						reuseport, cfg->ip_transparent,
1981 						cfg->tcp_mss, cfg->ip_freebind,
1982 						cfg->http_nodelay, cfg->use_systemd,
1983 						cfg->dnscrypt_port, cfg->ip_dscp,
1984 						cfg->quic_port, cfg->http_notls_downstream,
1985 						cfg->sock_queue_timeout)) {
1986 						listening_ports_free(list);
1987 						return NULL;
1988 					}
1989 				}
1990 			}
1991 			return list;
1992 		}
1993 		if(do_ip6) {
1994 			hints.ai_family = AF_INET6;
1995 			if(!ports_create_if(do_auto?"::0":"::1",
1996 				do_auto, cfg->do_udp, do_tcp,
1997 				&hints, cfg->port, &list,
1998 				cfg->so_rcvbuf, cfg->so_sndbuf,
1999 				cfg->ssl_port, cfg->tls_additional_port,
2000 				cfg->https_port, cfg->proxy_protocol_port,
2001 				reuseport, cfg->ip_transparent,
2002 				cfg->tcp_mss, cfg->ip_freebind,
2003 				cfg->http_nodelay, cfg->use_systemd,
2004 				cfg->dnscrypt_port, cfg->ip_dscp,
2005 				cfg->quic_port, cfg->http_notls_downstream,
2006 				cfg->sock_queue_timeout)) {
2007 				listening_ports_free(list);
2008 				return NULL;
2009 			}
2010 		}
2011 		if(do_ip4) {
2012 			hints.ai_family = AF_INET;
2013 			if(!ports_create_if(do_auto?"0.0.0.0":"127.0.0.1",
2014 				do_auto, cfg->do_udp, do_tcp,
2015 				&hints, cfg->port, &list,
2016 				cfg->so_rcvbuf, cfg->so_sndbuf,
2017 				cfg->ssl_port, cfg->tls_additional_port,
2018 				cfg->https_port, cfg->proxy_protocol_port,
2019 				reuseport, cfg->ip_transparent,
2020 				cfg->tcp_mss, cfg->ip_freebind,
2021 				cfg->http_nodelay, cfg->use_systemd,
2022 				cfg->dnscrypt_port, cfg->ip_dscp,
2023 				cfg->quic_port, cfg->http_notls_downstream,
2024 				cfg->sock_queue_timeout)) {
2025 				listening_ports_free(list);
2026 				return NULL;
2027 			}
2028 		}
2029 	} else for(i = 0; i<num_ifs; i++) {
2030 		if(str_is_ip6(ifs[i])) {
2031 			if(!do_ip6)
2032 				continue;
2033 			hints.ai_family = AF_INET6;
2034 			if(!ports_create_if(ifs[i], 0, cfg->do_udp,
2035 				do_tcp, &hints, cfg->port, &list,
2036 				cfg->so_rcvbuf, cfg->so_sndbuf,
2037 				cfg->ssl_port, cfg->tls_additional_port,
2038 				cfg->https_port, cfg->proxy_protocol_port,
2039 				reuseport, cfg->ip_transparent,
2040 				cfg->tcp_mss, cfg->ip_freebind,
2041 				cfg->http_nodelay, cfg->use_systemd,
2042 				cfg->dnscrypt_port, cfg->ip_dscp,
2043 				cfg->quic_port, cfg->http_notls_downstream,
2044 				cfg->sock_queue_timeout)) {
2045 				listening_ports_free(list);
2046 				return NULL;
2047 			}
2048 		} else {
2049 			if(!do_ip4)
2050 				continue;
2051 			hints.ai_family = AF_INET;
2052 			if(!ports_create_if(ifs[i], 0, cfg->do_udp,
2053 				do_tcp, &hints, cfg->port, &list,
2054 				cfg->so_rcvbuf, cfg->so_sndbuf,
2055 				cfg->ssl_port, cfg->tls_additional_port,
2056 				cfg->https_port, cfg->proxy_protocol_port,
2057 				reuseport, cfg->ip_transparent,
2058 				cfg->tcp_mss, cfg->ip_freebind,
2059 				cfg->http_nodelay, cfg->use_systemd,
2060 				cfg->dnscrypt_port, cfg->ip_dscp,
2061 				cfg->quic_port, cfg->http_notls_downstream,
2062 				cfg->sock_queue_timeout)) {
2063 				listening_ports_free(list);
2064 				return NULL;
2065 			}
2066 		}
2067 	}
2068 
2069 	return list;
2070 }
2071 
listening_ports_free(struct listen_port * list)2072 void listening_ports_free(struct listen_port* list)
2073 {
2074 	struct listen_port* nx;
2075 	while(list) {
2076 		nx = list->next;
2077 		if(list->fd != -1) {
2078 			sock_close(list->fd);
2079 		}
2080 		/* rc_ports don't have ub_socket */
2081 		if(list->socket) {
2082 			free(list->socket->addr);
2083 			free(list->socket);
2084 		}
2085 		free(list);
2086 		list = nx;
2087 	}
2088 }
2089 
listen_get_mem(struct listen_dnsport * listen)2090 size_t listen_get_mem(struct listen_dnsport* listen)
2091 {
2092 	struct listen_list* p;
2093 	size_t s = sizeof(*listen) + sizeof(*listen->base) +
2094 		sizeof(*listen->udp_buff) +
2095 		sldns_buffer_capacity(listen->udp_buff);
2096 #ifdef USE_DNSCRYPT
2097 	s += sizeof(*listen->dnscrypt_udp_buff);
2098 	if(listen->udp_buff != listen->dnscrypt_udp_buff){
2099 		s += sldns_buffer_capacity(listen->dnscrypt_udp_buff);
2100 	}
2101 #endif
2102 	for(p = listen->cps; p; p = p->next) {
2103 		s += sizeof(*p);
2104 		s += comm_point_get_mem(p->com);
2105 	}
2106 	return s;
2107 }
2108 
listen_stop_accept(struct listen_dnsport * listen)2109 void listen_stop_accept(struct listen_dnsport* listen)
2110 {
2111 	/* do not stop the ones that have no tcp_free list
2112 	 * (they have already stopped listening) */
2113 	struct listen_list* p;
2114 	for(p=listen->cps; p; p=p->next) {
2115 		if(p->com->type == comm_tcp_accept &&
2116 			p->com->tcp_free != NULL) {
2117 			comm_point_stop_listening(p->com);
2118 		}
2119 	}
2120 }
2121 
listen_start_accept(struct listen_dnsport * listen)2122 void listen_start_accept(struct listen_dnsport* listen)
2123 {
2124 	/* do not start the ones that have no tcp_free list, it is no
2125 	 * use to listen to them because they have no free tcp handlers */
2126 	struct listen_list* p;
2127 	for(p=listen->cps; p; p=p->next) {
2128 		if(p->com->type == comm_tcp_accept &&
2129 			p->com->tcp_free != NULL) {
2130 			comm_point_start_listening(p->com, -1, -1);
2131 		}
2132 	}
2133 }
2134 
2135 struct tcp_req_info*
tcp_req_info_create(struct sldns_buffer * spoolbuf)2136 tcp_req_info_create(struct sldns_buffer* spoolbuf)
2137 {
2138 	struct tcp_req_info* req = (struct tcp_req_info*)malloc(sizeof(*req));
2139 	if(!req) {
2140 		log_err("malloc failure for new stream outoforder processing structure");
2141 		return NULL;
2142 	}
2143 	memset(req, 0, sizeof(*req));
2144 	req->spool_buffer = spoolbuf;
2145 	return req;
2146 }
2147 
2148 void
tcp_req_info_delete(struct tcp_req_info * req)2149 tcp_req_info_delete(struct tcp_req_info* req)
2150 {
2151 	if(!req) return;
2152 	tcp_req_info_clear(req);
2153 	/* cp is pointer back to commpoint that owns this struct and
2154 	 * called delete on us */
2155 	/* spool_buffer is shared udp buffer, not deleted here */
2156 	free(req);
2157 }
2158 
tcp_req_info_clear(struct tcp_req_info * req)2159 void tcp_req_info_clear(struct tcp_req_info* req)
2160 {
2161 	struct tcp_req_open_item* open, *nopen;
2162 	struct tcp_req_done_item* item, *nitem;
2163 	if(!req) return;
2164 
2165 	/* free outstanding request mesh reply entries */
2166 	open = req->open_req_list;
2167 	while(open) {
2168 		nopen = open->next;
2169 		mesh_state_remove_reply(open->mesh, open->mesh_state, req->cp,
2170 			NULL, NULL);
2171 		free(open);
2172 		open = nopen;
2173 	}
2174 	req->open_req_list = NULL;
2175 	req->num_open_req = 0;
2176 
2177 	/* free pending writable result packets */
2178 	item = req->done_req_list;
2179 	while(item) {
2180 		nitem = item->next;
2181 		lock_basic_lock(&stream_wait_count_lock);
2182 		stream_wait_count -= (sizeof(struct tcp_req_done_item)
2183 			+item->len);
2184 		lock_basic_unlock(&stream_wait_count_lock);
2185 		free(item->buf);
2186 		free(item);
2187 		item = nitem;
2188 	}
2189 	req->done_req_list = NULL;
2190 	req->num_done_req = 0;
2191 	req->read_is_closed = 0;
2192 }
2193 
2194 void
tcp_req_info_remove_mesh_state(struct tcp_req_info * req,struct mesh_state * m)2195 tcp_req_info_remove_mesh_state(struct tcp_req_info* req, struct mesh_state* m)
2196 {
2197 	struct tcp_req_open_item* open, *prev = NULL;
2198 	if(!req || !m) return;
2199 	open = req->open_req_list;
2200 	while(open) {
2201 		if(open->mesh_state == m) {
2202 			struct tcp_req_open_item* next;
2203 			if(prev) prev->next = open->next;
2204 			else req->open_req_list = open->next;
2205 			/* caller has to manage the mesh state reply entry */
2206 			next = open->next;
2207 			free(open);
2208 			req->num_open_req --;
2209 
2210 			/* prev = prev; */
2211 			open = next;
2212 			continue;
2213 		}
2214 		prev = open;
2215 		open = open->next;
2216 	}
2217 }
2218 
2219 /** setup listening for read or write */
2220 static void
tcp_req_info_setup_listen(struct tcp_req_info * req)2221 tcp_req_info_setup_listen(struct tcp_req_info* req)
2222 {
2223 	int wr = 0;
2224 	int rd = 0;
2225 
2226 	if(req->cp->tcp_byte_count != 0) {
2227 		/* cannot change, halfway through */
2228 		return;
2229 	}
2230 
2231 	if(!req->cp->tcp_is_reading)
2232 		wr = 1;
2233 	if(!req->read_is_closed)
2234 		rd = 1;
2235 
2236 	if(wr) {
2237 		req->cp->tcp_is_reading = 0;
2238 		comm_point_stop_listening(req->cp);
2239 		comm_point_start_listening(req->cp, -1,
2240 			adjusted_tcp_timeout(req->cp));
2241 	} else if(rd) {
2242 		req->cp->tcp_is_reading = 1;
2243 		comm_point_stop_listening(req->cp);
2244 		comm_point_start_listening(req->cp, -1,
2245 			adjusted_tcp_timeout(req->cp));
2246 		/* and also read it (from SSL stack buffers), so
2247 		 * no event read event is expected since the remainder of
2248 		 * the TLS frame is sitting in the buffers. */
2249 		req->read_again = 1;
2250 	} else {
2251 		comm_point_stop_listening(req->cp);
2252 		comm_point_start_listening(req->cp, -1,
2253 			adjusted_tcp_timeout(req->cp));
2254 		comm_point_listen_for_rw(req->cp, 0, 0);
2255 	}
2256 }
2257 
2258 /** remove first item from list of pending results */
2259 static struct tcp_req_done_item*
tcp_req_info_pop_done(struct tcp_req_info * req)2260 tcp_req_info_pop_done(struct tcp_req_info* req)
2261 {
2262 	struct tcp_req_done_item* item;
2263 	log_assert(req->num_done_req > 0 && req->done_req_list);
2264 	item = req->done_req_list;
2265 	lock_basic_lock(&stream_wait_count_lock);
2266 	stream_wait_count -= (sizeof(struct tcp_req_done_item)+item->len);
2267 	lock_basic_unlock(&stream_wait_count_lock);
2268 	req->done_req_list = req->done_req_list->next;
2269 	req->num_done_req --;
2270 	return item;
2271 }
2272 
2273 /** Send given buffer and setup to write */
2274 static void
tcp_req_info_start_write_buf(struct tcp_req_info * req,uint8_t * buf,size_t len)2275 tcp_req_info_start_write_buf(struct tcp_req_info* req, uint8_t* buf,
2276 	size_t len)
2277 {
2278 	sldns_buffer_clear(req->cp->buffer);
2279 	sldns_buffer_write(req->cp->buffer, buf, len);
2280 	sldns_buffer_flip(req->cp->buffer);
2281 
2282 	req->cp->tcp_is_reading = 0; /* we are now writing */
2283 }
2284 
2285 /** pick up the next result and start writing it to the channel */
2286 static void
tcp_req_pickup_next_result(struct tcp_req_info * req)2287 tcp_req_pickup_next_result(struct tcp_req_info* req)
2288 {
2289 	if(req->num_done_req > 0) {
2290 		/* unlist the done item from the list of pending results */
2291 		struct tcp_req_done_item* item = tcp_req_info_pop_done(req);
2292 		tcp_req_info_start_write_buf(req, item->buf, item->len);
2293 		free(item->buf);
2294 		free(item);
2295 	}
2296 }
2297 
2298 /** the read channel has closed */
2299 int
tcp_req_info_handle_read_close(struct tcp_req_info * req)2300 tcp_req_info_handle_read_close(struct tcp_req_info* req)
2301 {
2302 	verbose(VERB_ALGO, "tcp channel read side closed %d", req->cp->fd);
2303 	/* RFC 7766 6.2.4 says to drop pending replies when client closes. */
2304 	return 0; /* drop connection */
2305 }
2306 
2307 void
tcp_req_info_handle_writedone(struct tcp_req_info * req)2308 tcp_req_info_handle_writedone(struct tcp_req_info* req)
2309 {
2310 	/* back to reading state, we finished this write event */
2311 	sldns_buffer_clear(req->cp->buffer);
2312 	if(req->num_done_req == 0 && req->read_is_closed) {
2313 		/* no more to write and nothing to read, close it */
2314 		comm_point_drop_reply(&req->cp->repinfo);
2315 		return;
2316 	}
2317 	req->cp->tcp_is_reading = 1;
2318 	/* see if another result needs writing */
2319 	tcp_req_pickup_next_result(req);
2320 
2321 	/* see if there is more to write, if not stop_listening for writing */
2322 	/* see if new requests are allowed, if so, start_listening
2323 	 * for reading */
2324 	tcp_req_info_setup_listen(req);
2325 }
2326 
2327 void
tcp_req_info_handle_readdone(struct tcp_req_info * req)2328 tcp_req_info_handle_readdone(struct tcp_req_info* req)
2329 {
2330 	struct comm_point* c = req->cp;
2331 
2332 	/* we want to read up several requests, unless there are
2333 	 * pending answers */
2334 
2335 	req->is_drop = 0;
2336 	req->is_reply = 0;
2337 	req->in_worker_handle = 1;
2338 	sldns_buffer_set_limit(req->spool_buffer, 0);
2339 	/* handle the current request */
2340 	/* this calls the worker handle request routine that could give
2341 	 * a cache response, or localdata response, or drop the reply,
2342 	 * or schedule a mesh entry for later */
2343 	fptr_ok(fptr_whitelist_comm_point(c->callback));
2344 	if( (*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, &c->repinfo) ) {
2345 		req->in_worker_handle = 0;
2346 		/* there is an answer, put it up.  It is already in the
2347 		 * c->buffer, just send it. */
2348 		/* since we were just reading a query, the channel is
2349 		 * clear to write to */
2350 	send_it:
2351 		c->tcp_is_reading = 0;
2352 		comm_point_stop_listening(c);
2353 		comm_point_start_listening(c, -1, adjusted_tcp_timeout(c));
2354 		return;
2355 	}
2356 	req->in_worker_handle = 0;
2357 	/* it should be waiting in the mesh for recursion.
2358 	 * If mesh failed to add a new entry and called commpoint_drop_reply.
2359 	 * Then the mesh state has been cleared. */
2360 	if(req->is_drop) {
2361 		/* the reply has been dropped, stream has been closed. */
2362 		return;
2363 	}
2364 	/* If mesh failed(mallocfail) and called commpoint_send_reply with
2365 	 * something like servfail then we pick up that reply below. */
2366 	if(req->is_reply) {
2367 		goto send_it;
2368 	}
2369 
2370 	sldns_buffer_clear(c->buffer);
2371 	/* if pending answers, pick up an answer and start sending it */
2372 	tcp_req_pickup_next_result(req);
2373 
2374 	/* if answers pending, start sending answers */
2375 	/* read more requests if we can have more requests */
2376 	tcp_req_info_setup_listen(req);
2377 }
2378 
2379 int
tcp_req_info_add_meshstate(struct tcp_req_info * req,struct mesh_area * mesh,struct mesh_state * m)2380 tcp_req_info_add_meshstate(struct tcp_req_info* req,
2381 	struct mesh_area* mesh, struct mesh_state* m)
2382 {
2383 	struct tcp_req_open_item* item;
2384 	log_assert(req && mesh && m);
2385 	item = (struct tcp_req_open_item*)malloc(sizeof(*item));
2386 	if(!item) return 0;
2387 	item->next = req->open_req_list;
2388 	item->mesh = mesh;
2389 	item->mesh_state = m;
2390 	req->open_req_list = item;
2391 	req->num_open_req++;
2392 	return 1;
2393 }
2394 
2395 /** Add a result to the result list.  At the end. */
2396 static int
tcp_req_info_add_result(struct tcp_req_info * req,uint8_t * buf,size_t len)2397 tcp_req_info_add_result(struct tcp_req_info* req, uint8_t* buf, size_t len)
2398 {
2399 	struct tcp_req_done_item* last = NULL;
2400 	struct tcp_req_done_item* item;
2401 	size_t space;
2402 
2403 	/* see if we have space */
2404 	space = sizeof(struct tcp_req_done_item) + len;
2405 	lock_basic_lock(&stream_wait_count_lock);
2406 	if(stream_wait_count + space > stream_wait_max) {
2407 		lock_basic_unlock(&stream_wait_count_lock);
2408 		verbose(VERB_ALGO, "drop stream reply, no space left, in stream-wait-size");
2409 		return 0;
2410 	}
2411 	stream_wait_count += space;
2412 	lock_basic_unlock(&stream_wait_count_lock);
2413 
2414 	/* find last element */
2415 	last = req->done_req_list;
2416 	while(last && last->next)
2417 		last = last->next;
2418 
2419 	/* create new element */
2420 	item = (struct tcp_req_done_item*)malloc(sizeof(*item));
2421 	if(!item) {
2422 		log_err("malloc failure, for stream result list");
2423 		return 0;
2424 	}
2425 	item->next = NULL;
2426 	item->len = len;
2427 	item->buf = memdup(buf, len);
2428 	if(!item->buf) {
2429 		free(item);
2430 		log_err("malloc failure, adding reply to stream result list");
2431 		return 0;
2432 	}
2433 
2434 	/* link in */
2435 	if(last) last->next = item;
2436 	else req->done_req_list = item;
2437 	req->num_done_req++;
2438 	return 1;
2439 }
2440 
2441 void
tcp_req_info_send_reply(struct tcp_req_info * req)2442 tcp_req_info_send_reply(struct tcp_req_info* req)
2443 {
2444 	if(req->in_worker_handle) {
2445 		/* reply from mesh is in the spool_buffer */
2446 		/* copy now, so that the spool buffer is free for other tasks
2447 		 * before the callback is done */
2448 		sldns_buffer_clear(req->cp->buffer);
2449 		sldns_buffer_write(req->cp->buffer,
2450 			sldns_buffer_begin(req->spool_buffer),
2451 			sldns_buffer_limit(req->spool_buffer));
2452 		sldns_buffer_flip(req->cp->buffer);
2453 		req->is_reply = 1;
2454 		return;
2455 	}
2456 	/* now that the query has been handled, that mesh_reply entry
2457 	 * should be removed, from the tcp_req_info list,
2458 	 * the mesh state cleanup removes then with region_cleanup and
2459 	 * replies_sent true. */
2460 	/* see if we can send it straight away (we are not doing
2461 	 * anything else).  If so, copy to buffer and start */
2462 	if(req->cp->tcp_is_reading && req->cp->tcp_byte_count == 0) {
2463 		/* buffer is free, and was ready to read new query into,
2464 		 * but we are now going to use it to send this answer */
2465 		tcp_req_info_start_write_buf(req,
2466 			sldns_buffer_begin(req->spool_buffer),
2467 			sldns_buffer_limit(req->spool_buffer));
2468 		/* switch to listen to write events */
2469 		comm_point_stop_listening(req->cp);
2470 		comm_point_start_listening(req->cp, -1,
2471 			adjusted_tcp_timeout(req->cp));
2472 		return;
2473 	}
2474 	/* queue up the answer behind the others already pending */
2475 	if(!tcp_req_info_add_result(req, sldns_buffer_begin(req->spool_buffer),
2476 		sldns_buffer_limit(req->spool_buffer))) {
2477 		/* drop the connection, we are out of resources */
2478 		comm_point_drop_reply(&req->cp->repinfo);
2479 	}
2480 }
2481 
tcp_req_info_get_stream_buffer_size(void)2482 size_t tcp_req_info_get_stream_buffer_size(void)
2483 {
2484 	size_t s;
2485 	if(!stream_wait_lock_inited)
2486 		return stream_wait_count;
2487 	lock_basic_lock(&stream_wait_count_lock);
2488 	s = stream_wait_count;
2489 	lock_basic_unlock(&stream_wait_count_lock);
2490 	return s;
2491 }
2492 
http2_get_query_buffer_size(void)2493 size_t http2_get_query_buffer_size(void)
2494 {
2495 	size_t s;
2496 	if(!http2_query_buffer_lock_inited)
2497 		return http2_query_buffer_count;
2498 	lock_basic_lock(&http2_query_buffer_count_lock);
2499 	s = http2_query_buffer_count;
2500 	lock_basic_unlock(&http2_query_buffer_count_lock);
2501 	return s;
2502 }
2503 
http2_get_response_buffer_size(void)2504 size_t http2_get_response_buffer_size(void)
2505 {
2506 	size_t s;
2507 	if(!http2_response_buffer_lock_inited)
2508 		return http2_response_buffer_count;
2509 	lock_basic_lock(&http2_response_buffer_count_lock);
2510 	s = http2_response_buffer_count;
2511 	lock_basic_unlock(&http2_response_buffer_count_lock);
2512 	return s;
2513 }
2514 
2515 #ifdef HAVE_NGHTTP2
2516 /** nghttp2 callback. Used to copy response from rbuffer to nghttp2 session */
http2_submit_response_read_callback(nghttp2_session * ATTR_UNUSED (session),int32_t stream_id,uint8_t * buf,size_t length,uint32_t * data_flags,nghttp2_data_source * source,void * ATTR_UNUSED (cb_arg))2517 static ssize_t http2_submit_response_read_callback(
2518 	nghttp2_session* ATTR_UNUSED(session),
2519 	int32_t stream_id, uint8_t* buf, size_t length, uint32_t* data_flags,
2520 	nghttp2_data_source* source, void* ATTR_UNUSED(cb_arg))
2521 {
2522 	struct http2_stream* h2_stream;
2523 	struct http2_session* h2_session = source->ptr;
2524 	size_t copylen = length;
2525 	if(!(h2_stream = nghttp2_session_get_stream_user_data(
2526 		h2_session->session, stream_id))) {
2527 		verbose(VERB_QUERY, "http2: cannot get stream data, closing "
2528 			"stream");
2529 		return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
2530 	}
2531 	if(!h2_stream->rbuffer ||
2532 		sldns_buffer_remaining(h2_stream->rbuffer) == 0) {
2533 		verbose(VERB_QUERY, "http2: cannot submit buffer. No data "
2534 			"available in rbuffer");
2535 		/* rbuffer will be free'd in frame close cb */
2536 		return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
2537 	}
2538 
2539 	if(copylen > sldns_buffer_remaining(h2_stream->rbuffer))
2540 		copylen = sldns_buffer_remaining(h2_stream->rbuffer);
2541 	if(copylen > SSIZE_MAX)
2542 		copylen = SSIZE_MAX; /* will probably never happen */
2543 
2544 	memcpy(buf, sldns_buffer_current(h2_stream->rbuffer), copylen);
2545 	sldns_buffer_skip(h2_stream->rbuffer, copylen);
2546 
2547 	if(sldns_buffer_remaining(h2_stream->rbuffer) == 0) {
2548 		*data_flags |= NGHTTP2_DATA_FLAG_EOF;
2549 		lock_basic_lock(&http2_response_buffer_count_lock);
2550 		http2_response_buffer_count -=
2551 			sldns_buffer_capacity(h2_stream->rbuffer);
2552 		lock_basic_unlock(&http2_response_buffer_count_lock);
2553 		sldns_buffer_free(h2_stream->rbuffer);
2554 		h2_stream->rbuffer = NULL;
2555 	}
2556 
2557 	return copylen;
2558 }
2559 
2560 /**
2561  * Send RST_STREAM frame for stream.
2562  * @param h2_session: http2 session to submit frame to
2563  * @param h2_stream: http2 stream containing frame ID to use in RST_STREAM
2564  * @return 0 on error, 1 otherwise
2565  */
http2_submit_rst_stream(struct http2_session * h2_session,struct http2_stream * h2_stream)2566 static int http2_submit_rst_stream(struct http2_session* h2_session,
2567 		struct http2_stream* h2_stream)
2568 {
2569 	int ret = nghttp2_submit_rst_stream(h2_session->session,
2570 		NGHTTP2_FLAG_NONE, h2_stream->stream_id,
2571 		NGHTTP2_INTERNAL_ERROR);
2572 	if(ret) {
2573 		verbose(VERB_QUERY, "http2: nghttp2_submit_rst_stream failed, "
2574 			"error: %s", nghttp2_strerror(ret));
2575 		return 0;
2576 	}
2577 	return 1;
2578 }
2579 
2580 /**
2581  * DNS response ready to be submitted to nghttp2, to be prepared for sending
2582  * out. Response is stored in c->buffer. Copy to rbuffer because the c->buffer
2583  * might be used before this will be sent out.
2584  * @param h2_session: http2 session, containing c->buffer which contains answer
2585  * @return 0 on error, 1 otherwise
2586  */
http2_submit_dns_response(struct http2_session * h2_session)2587 int http2_submit_dns_response(struct http2_session* h2_session)
2588 {
2589 	int ret;
2590 	nghttp2_data_provider data_prd;
2591 	char status[4];
2592 	nghttp2_nv headers[3];
2593 	struct http2_stream* h2_stream = h2_session->c->h2_stream;
2594 	size_t rlen;
2595 	char rlen_str[32];
2596 
2597 	if(h2_stream->rbuffer) {
2598 		log_err("http2 submit response error: rbuffer already "
2599 			"exists");
2600 		return 0;
2601 	}
2602 	if(sldns_buffer_remaining(h2_session->c->buffer) == 0) {
2603 		log_err("http2 submit response error: c->buffer not complete");
2604 		return 0;
2605 	}
2606 
2607 	if(snprintf(status, 4, "%d", h2_stream->status) != 3) {
2608 		verbose(VERB_QUERY, "http2: submit response error: "
2609 			"invalid status");
2610 		return 0;
2611 	}
2612 
2613 	rlen = sldns_buffer_remaining(h2_session->c->buffer);
2614 	snprintf(rlen_str, sizeof(rlen_str), "%u", (unsigned)rlen);
2615 
2616 	lock_basic_lock(&http2_response_buffer_count_lock);
2617 	if(http2_response_buffer_count + rlen > http2_response_buffer_max) {
2618 		lock_basic_unlock(&http2_response_buffer_count_lock);
2619 		verbose(VERB_ALGO, "reset HTTP2 stream, no space left, "
2620 			"in https-response-buffer-size");
2621 		return http2_submit_rst_stream(h2_session, h2_stream);
2622 	}
2623 	http2_response_buffer_count += rlen;
2624 	lock_basic_unlock(&http2_response_buffer_count_lock);
2625 
2626 	if(!(h2_stream->rbuffer = sldns_buffer_new(rlen))) {
2627 		lock_basic_lock(&http2_response_buffer_count_lock);
2628 		http2_response_buffer_count -= rlen;
2629 		lock_basic_unlock(&http2_response_buffer_count_lock);
2630 		log_err("http2 submit response error: malloc failure");
2631 		return 0;
2632 	}
2633 
2634 	headers[0].name = (uint8_t*)":status";
2635 	headers[0].namelen = 7;
2636 	headers[0].value = (uint8_t*)status;
2637 	headers[0].valuelen = 3;
2638 	headers[0].flags = NGHTTP2_NV_FLAG_NONE;
2639 
2640 	headers[1].name = (uint8_t*)"content-type";
2641 	headers[1].namelen = 12;
2642 	headers[1].value = (uint8_t*)"application/dns-message";
2643 	headers[1].valuelen = 23;
2644 	headers[1].flags = NGHTTP2_NV_FLAG_NONE;
2645 
2646 	headers[2].name = (uint8_t*)"content-length";
2647 	headers[2].namelen = 14;
2648 	headers[2].value = (uint8_t*)rlen_str;
2649 	headers[2].valuelen = strlen(rlen_str);
2650 	headers[2].flags = NGHTTP2_NV_FLAG_NONE;
2651 
2652 	sldns_buffer_write(h2_stream->rbuffer,
2653 		sldns_buffer_current(h2_session->c->buffer),
2654 		sldns_buffer_remaining(h2_session->c->buffer));
2655 	sldns_buffer_flip(h2_stream->rbuffer);
2656 
2657 	data_prd.source.ptr = h2_session;
2658 	data_prd.read_callback = http2_submit_response_read_callback;
2659 	ret = nghttp2_submit_response(h2_session->session, h2_stream->stream_id,
2660 		headers, 3, &data_prd);
2661 	if(ret) {
2662 		verbose(VERB_QUERY, "http2: set_stream_user_data failed, "
2663 			"error: %s", nghttp2_strerror(ret));
2664 		return 0;
2665 	}
2666 	return 1;
2667 }
2668 #else
http2_submit_dns_response(void * ATTR_UNUSED (v))2669 int http2_submit_dns_response(void* ATTR_UNUSED(v))
2670 {
2671 	return 0;
2672 }
2673 #endif
2674 
2675 #ifdef HAVE_NGHTTP2
2676 /** HTTP status to descriptive string */
http_status_to_str(enum http_status s)2677 static char* http_status_to_str(enum http_status s)
2678 {
2679 	switch(s) {
2680 		case HTTP_STATUS_OK:
2681 			return "OK";
2682 		case HTTP_STATUS_BAD_REQUEST:
2683 			return "Bad Request";
2684 		case HTTP_STATUS_NOT_FOUND:
2685 			return "Not Found";
2686 		case HTTP_STATUS_PAYLOAD_TOO_LARGE:
2687 			return "Payload Too Large";
2688 		case HTTP_STATUS_URI_TOO_LONG:
2689 			return "URI Too Long";
2690 		case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:
2691 			return "Unsupported Media Type";
2692 		case HTTP_STATUS_NOT_IMPLEMENTED:
2693 			return "Not Implemented";
2694 	}
2695 	return "Status Unknown";
2696 }
2697 
2698 /** nghttp2 callback. Used to copy error message to nghttp2 session */
http2_submit_error_read_callback(nghttp2_session * ATTR_UNUSED (session),int32_t stream_id,uint8_t * buf,size_t length,uint32_t * data_flags,nghttp2_data_source * source,void * ATTR_UNUSED (cb_arg))2699 static ssize_t http2_submit_error_read_callback(
2700 	nghttp2_session* ATTR_UNUSED(session),
2701 	int32_t stream_id, uint8_t* buf, size_t length, uint32_t* data_flags,
2702 	nghttp2_data_source* source, void* ATTR_UNUSED(cb_arg))
2703 {
2704 	struct http2_stream* h2_stream;
2705 	struct http2_session* h2_session = source->ptr;
2706 	char* msg;
2707 	if(!(h2_stream = nghttp2_session_get_stream_user_data(
2708 		h2_session->session, stream_id))) {
2709 		verbose(VERB_QUERY, "http2: cannot get stream data, closing "
2710 			"stream");
2711 		return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
2712 	}
2713 	*data_flags |= NGHTTP2_DATA_FLAG_EOF;
2714 	msg = http_status_to_str(h2_stream->status);
2715 	if(length < strlen(msg))
2716 		return 0; /* not worth trying over multiple frames */
2717 	memcpy(buf, msg, strlen(msg));
2718 	return strlen(msg);
2719 
2720 }
2721 
2722 /**
2723  * HTTP error response ready to be submitted to nghttp2, to be prepared for
2724  * sending out. Message body will contain descriptive string for HTTP status.
2725  * @param h2_session: http2 session to submit to
2726  * @param h2_stream: http2 stream containing HTTP status to use for error
2727  * @return 0 on error, 1 otherwise
2728  */
http2_submit_error(struct http2_session * h2_session,struct http2_stream * h2_stream)2729 static int http2_submit_error(struct http2_session* h2_session,
2730 	struct http2_stream* h2_stream)
2731 {
2732 	int ret;
2733 	char status[4];
2734 	nghttp2_data_provider data_prd;
2735 	nghttp2_nv headers[1]; /* will be copied by nghttp */
2736 	if(snprintf(status, 4, "%d", h2_stream->status) != 3) {
2737 		verbose(VERB_QUERY, "http2: submit error failed, "
2738 			"invalid status");
2739 		return 0;
2740 	}
2741 	headers[0].name = (uint8_t*)":status";
2742 	headers[0].namelen = 7;
2743 	headers[0].value = (uint8_t*)status;
2744 	headers[0].valuelen = 3;
2745 	headers[0].flags = NGHTTP2_NV_FLAG_NONE;
2746 
2747 	data_prd.source.ptr = h2_session;
2748 	data_prd.read_callback = http2_submit_error_read_callback;
2749 
2750 	ret = nghttp2_submit_response(h2_session->session, h2_stream->stream_id,
2751 		headers, 1, &data_prd);
2752 	if(ret) {
2753 		verbose(VERB_QUERY, "http2: submit error failed, "
2754 			"error: %s", nghttp2_strerror(ret));
2755 		return 0;
2756 	}
2757 	return 1;
2758 }
2759 
2760 /**
2761  * Start query handling. Query is stored in the stream, and will be free'd here.
2762  * @param h2_session: http2 session, containing comm point
2763  * @param h2_stream: stream containing buffered query
2764  * @return: -1 on error, 1 if answer is stored in c->buffer, 0 if there is no
2765  * reply available (yet).
2766  */
http2_query_read_done(struct http2_session * h2_session,struct http2_stream * h2_stream)2767 static int http2_query_read_done(struct http2_session* h2_session,
2768 	struct http2_stream* h2_stream)
2769 {
2770 	log_assert(h2_stream->qbuffer);
2771 
2772 	if(h2_session->c->h2_stream) {
2773 		verbose(VERB_ALGO, "http2_query_read_done failure: shared "
2774 			"buffer already assigned to stream");
2775 		return -1;
2776 	}
2777 
2778     /* the c->buffer might be used by mesh_send_reply and no be cleard
2779 	 * need to be cleared before use */
2780 	sldns_buffer_clear(h2_session->c->buffer);
2781 	if(sldns_buffer_remaining(h2_session->c->buffer) <
2782 		sldns_buffer_remaining(h2_stream->qbuffer)) {
2783 		/* qbuffer will be free'd in frame close cb */
2784 		sldns_buffer_clear(h2_session->c->buffer);
2785 		verbose(VERB_ALGO, "http2_query_read_done failure: can't fit "
2786 			"qbuffer in c->buffer");
2787 		return -1;
2788 	}
2789 
2790 	sldns_buffer_write(h2_session->c->buffer,
2791 		sldns_buffer_current(h2_stream->qbuffer),
2792 		sldns_buffer_remaining(h2_stream->qbuffer));
2793 
2794 	lock_basic_lock(&http2_query_buffer_count_lock);
2795 	http2_query_buffer_count -= sldns_buffer_capacity(h2_stream->qbuffer);
2796 	lock_basic_unlock(&http2_query_buffer_count_lock);
2797 	sldns_buffer_free(h2_stream->qbuffer);
2798 	h2_stream->qbuffer = NULL;
2799 
2800 	sldns_buffer_flip(h2_session->c->buffer);
2801 	h2_session->c->h2_stream = h2_stream;
2802 	fptr_ok(fptr_whitelist_comm_point(h2_session->c->callback));
2803 	if((*h2_session->c->callback)(h2_session->c, h2_session->c->cb_arg,
2804 		NETEVENT_NOERROR, &h2_session->c->repinfo)) {
2805 		return 1; /* answer in c->buffer */
2806 	}
2807 	sldns_buffer_clear(h2_session->c->buffer);
2808 	h2_session->c->h2_stream = NULL;
2809 	return 0; /* mesh state added, or dropped */
2810 }
2811 
2812 /** nghttp2 callback. Used to check if the received frame indicates the end of a
2813  * stream. Gather collected request data and start query handling. */
http2_req_frame_recv_cb(nghttp2_session * session,const nghttp2_frame * frame,void * cb_arg)2814 static int http2_req_frame_recv_cb(nghttp2_session* session,
2815 	const nghttp2_frame* frame, void* cb_arg)
2816 {
2817 	struct http2_session* h2_session = (struct http2_session*)cb_arg;
2818 	struct http2_stream* h2_stream;
2819 	int query_read_done;
2820 
2821 	if((frame->hd.type != NGHTTP2_DATA &&
2822 		frame->hd.type != NGHTTP2_HEADERS) ||
2823 		!(frame->hd.flags & NGHTTP2_FLAG_END_STREAM)) {
2824 			return 0;
2825 	}
2826 
2827 	if(!(h2_stream = nghttp2_session_get_stream_user_data(
2828 		session, frame->hd.stream_id)))
2829 		return 0;
2830 
2831 	if(h2_stream->invalid_endpoint) {
2832 		h2_stream->status = HTTP_STATUS_NOT_FOUND;
2833 		goto submit_http_error;
2834 	}
2835 
2836 	if(h2_stream->invalid_content_type) {
2837 		h2_stream->status = HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE;
2838 		goto submit_http_error;
2839 	}
2840 
2841 	if(h2_stream->http_method != HTTP_METHOD_GET &&
2842 		h2_stream->http_method != HTTP_METHOD_POST) {
2843 		h2_stream->status = HTTP_STATUS_NOT_IMPLEMENTED;
2844 		goto submit_http_error;
2845 	}
2846 
2847 	if(h2_stream->query_too_large) {
2848 		if(h2_stream->http_method == HTTP_METHOD_POST)
2849 			h2_stream->status = HTTP_STATUS_PAYLOAD_TOO_LARGE;
2850 		else
2851 			h2_stream->status = HTTP_STATUS_URI_TOO_LONG;
2852 		goto submit_http_error;
2853 	}
2854 
2855 	if(!h2_stream->qbuffer) {
2856 		h2_stream->status = HTTP_STATUS_BAD_REQUEST;
2857 		goto submit_http_error;
2858 	}
2859 
2860 	if(h2_stream->status) {
2861 submit_http_error:
2862 		verbose(VERB_QUERY, "http2 request invalid, returning :status="
2863 			"%d", h2_stream->status);
2864 		if(!http2_submit_error(h2_session, h2_stream)) {
2865 			return NGHTTP2_ERR_CALLBACK_FAILURE;
2866 		}
2867 		return 0;
2868 	}
2869 	h2_stream->status = HTTP_STATUS_OK;
2870 
2871 	sldns_buffer_flip(h2_stream->qbuffer);
2872 	h2_session->postpone_drop = 1;
2873 	query_read_done = http2_query_read_done(h2_session, h2_stream);
2874 	h2_session->postpone_drop = 0;
2875 	if(query_read_done < 0)
2876 		return NGHTTP2_ERR_CALLBACK_FAILURE;
2877 	else if(!query_read_done) {
2878 		if(h2_session->is_drop) {
2879 			/* connection needs to be closed. Return failure to make
2880 			 * sure no other action are taken anymore on comm point.
2881 			 * failure will result in reclaiming (and closing)
2882 			 * of comm point. */
2883 			verbose(VERB_QUERY, "http2 query dropped in worker cb");
2884 			return NGHTTP2_ERR_CALLBACK_FAILURE;
2885 		}
2886 		/* nothing to submit right now, query added to mesh. */
2887 		return 0;
2888 	}
2889 	if(!http2_submit_dns_response(h2_session)) {
2890 		sldns_buffer_clear(h2_session->c->buffer);
2891 		h2_session->c->h2_stream = NULL;
2892 		return NGHTTP2_ERR_CALLBACK_FAILURE;
2893 	}
2894 	verbose(VERB_QUERY, "http2 query submitted to session");
2895 	sldns_buffer_clear(h2_session->c->buffer);
2896 	h2_session->c->h2_stream = NULL;
2897 	return 0;
2898 }
2899 
2900 /** nghttp2 callback. Used to detect start of new streams. */
http2_req_begin_headers_cb(nghttp2_session * session,const nghttp2_frame * frame,void * cb_arg)2901 static int http2_req_begin_headers_cb(nghttp2_session* session,
2902 	const nghttp2_frame* frame, void* cb_arg)
2903 {
2904 	struct http2_session* h2_session = (struct http2_session*)cb_arg;
2905 	struct http2_stream* h2_stream;
2906 	int ret;
2907 	if(frame->hd.type != NGHTTP2_HEADERS ||
2908 		frame->headers.cat != NGHTTP2_HCAT_REQUEST) {
2909 		/* only interested in request headers */
2910 		return 0;
2911 	}
2912 	if(!(h2_stream = http2_stream_create(frame->hd.stream_id))) {
2913 		log_err("malloc failure while creating http2 stream");
2914 		return NGHTTP2_ERR_CALLBACK_FAILURE;
2915 	}
2916 	http2_session_add_stream(h2_session, h2_stream);
2917 	ret = nghttp2_session_set_stream_user_data(session,
2918 		frame->hd.stream_id, h2_stream);
2919 	if(ret) {
2920 		/* stream does not exist */
2921 		verbose(VERB_QUERY, "http2: set_stream_user_data failed, "
2922 			"error: %s", nghttp2_strerror(ret));
2923 		return NGHTTP2_ERR_CALLBACK_FAILURE;
2924 	}
2925 
2926 	return 0;
2927 }
2928 
2929 /**
2930  * base64url decode, store in qbuffer
2931  * @param h2_session: http2 session
2932  * @param h2_stream: http2 stream
2933  * @param start: start of the base64 string
2934  * @param length: length of the base64 string
2935  * @return: 0 on error, 1 otherwise. query will be stored in h2_stream->qbuffer,
2936  * buffer will be NULL is unparseble.
2937  */
http2_buffer_uri_query(struct http2_session * h2_session,struct http2_stream * h2_stream,const uint8_t * start,size_t length)2938 static int http2_buffer_uri_query(struct http2_session* h2_session,
2939 	struct http2_stream* h2_stream, const uint8_t* start, size_t length)
2940 {
2941 	size_t expectb64len;
2942 	int b64len;
2943 	if(h2_stream->http_method == HTTP_METHOD_POST)
2944 		return 1;
2945 	if(length == 0)
2946 		return 1;
2947 	if(h2_stream->qbuffer) {
2948 		verbose(VERB_ALGO, "http2_req_header fail, "
2949 			"qbuffer already set");
2950 		return 0;
2951 	}
2952 
2953 	/* calculate size, might be a bit bigger than the real
2954 	 * decoded buffer size */
2955 	expectb64len = sldns_b64_pton_calculate_size(length);
2956 	log_assert(expectb64len > 0);
2957 	if(expectb64len >
2958 		h2_session->c->http2_stream_max_qbuffer_size) {
2959 		h2_stream->query_too_large = 1;
2960 		return 1;
2961 	}
2962 
2963 	lock_basic_lock(&http2_query_buffer_count_lock);
2964 	if(http2_query_buffer_count + expectb64len > http2_query_buffer_max) {
2965 		lock_basic_unlock(&http2_query_buffer_count_lock);
2966 		verbose(VERB_ALGO, "reset HTTP2 stream, no space left, "
2967 			"in http2-query-buffer-size");
2968 		return http2_submit_rst_stream(h2_session, h2_stream);
2969 	}
2970 	http2_query_buffer_count += expectb64len;
2971 	lock_basic_unlock(&http2_query_buffer_count_lock);
2972 	if(!(h2_stream->qbuffer = sldns_buffer_new(expectb64len))) {
2973 		lock_basic_lock(&http2_query_buffer_count_lock);
2974 		http2_query_buffer_count -= expectb64len;
2975 		lock_basic_unlock(&http2_query_buffer_count_lock);
2976 		log_err("http2_req_header fail, qbuffer "
2977 			"malloc failure");
2978 		return 0;
2979 	}
2980 
2981 	if(sldns_b64_contains_nonurl((char const*)start, length)) {
2982 		char buf[65536+4];
2983 		verbose(VERB_ALGO, "HTTP2 stream contains wrong b64 encoding");
2984 		/* copy to the scratch buffer temporarily to terminate the
2985 		 * string with a zero */
2986 		if(length+1 > sizeof(buf)) {
2987 			/* too long */
2988 			lock_basic_lock(&http2_query_buffer_count_lock);
2989 			http2_query_buffer_count -= expectb64len;
2990 			lock_basic_unlock(&http2_query_buffer_count_lock);
2991 			sldns_buffer_free(h2_stream->qbuffer);
2992 			h2_stream->qbuffer = NULL;
2993 			return 1;
2994 		}
2995 		memmove(buf, start, length);
2996 		buf[length] = 0;
2997 		if(!(b64len = sldns_b64_pton(buf, sldns_buffer_current(
2998 			h2_stream->qbuffer), expectb64len)) || b64len < 0) {
2999 			lock_basic_lock(&http2_query_buffer_count_lock);
3000 			http2_query_buffer_count -= expectb64len;
3001 			lock_basic_unlock(&http2_query_buffer_count_lock);
3002 			sldns_buffer_free(h2_stream->qbuffer);
3003 			h2_stream->qbuffer = NULL;
3004 			return 1;
3005 		}
3006 	} else {
3007 		if(!(b64len = sldns_b64url_pton(
3008 			(char const *)start, length,
3009 			sldns_buffer_current(h2_stream->qbuffer),
3010 			expectb64len)) || b64len < 0) {
3011 			lock_basic_lock(&http2_query_buffer_count_lock);
3012 			http2_query_buffer_count -= expectb64len;
3013 			lock_basic_unlock(&http2_query_buffer_count_lock);
3014 			sldns_buffer_free(h2_stream->qbuffer);
3015 			h2_stream->qbuffer = NULL;
3016 			/* return without error, method can be an
3017 			 * unknown POST */
3018 			return 1;
3019 		}
3020 	}
3021 	sldns_buffer_skip(h2_stream->qbuffer, (size_t)b64len);
3022 	return 1;
3023 }
3024 
3025 /** nghttp2 callback. Used to parse headers from HEADER frames. */
http2_req_header_cb(nghttp2_session * session,const nghttp2_frame * frame,const uint8_t * name,size_t namelen,const uint8_t * value,size_t valuelen,uint8_t ATTR_UNUSED (flags),void * cb_arg)3026 static int http2_req_header_cb(nghttp2_session* session,
3027 	const nghttp2_frame* frame, const uint8_t* name, size_t namelen,
3028 	const uint8_t* value, size_t valuelen, uint8_t ATTR_UNUSED(flags),
3029 	void* cb_arg)
3030 {
3031 	struct http2_stream* h2_stream = NULL;
3032 	struct http2_session* h2_session = (struct http2_session*)cb_arg;
3033 	/* nghttp2 deals with CONTINUATION frames and provides them as part of
3034 	 * the HEADER */
3035 	if(frame->hd.type != NGHTTP2_HEADERS ||
3036 		frame->headers.cat != NGHTTP2_HCAT_REQUEST) {
3037 		/* only interested in request headers */
3038 		return 0;
3039 	}
3040 	if(!(h2_stream = nghttp2_session_get_stream_user_data(session,
3041 		frame->hd.stream_id)))
3042 		return 0;
3043 
3044 	/* earlier checks already indicate we can stop handling this query */
3045 	if(h2_stream->http_method == HTTP_METHOD_UNSUPPORTED ||
3046 		h2_stream->invalid_content_type ||
3047 		h2_stream->invalid_endpoint)
3048 		return 0;
3049 
3050 
3051 	/* nghttp2 performs some sanity checks in the headers, including:
3052 	 * name and value are guaranteed to be null terminated
3053 	 * name is guaranteed to be lowercase
3054 	 * content-length value is guaranteed to contain digits
3055 	 */
3056 
3057 	if(!h2_stream->http_method && namelen == 7 &&
3058 		memcmp(":method", name, namelen) == 0) {
3059 		/* Case insensitive check on :method value to be on the safe
3060 		 * side. I failed to find text about case sensitivity in specs.
3061 		 */
3062 		if(valuelen == 3 && strcasecmp("GET", (const char*)value) == 0)
3063 			h2_stream->http_method = HTTP_METHOD_GET;
3064 		else if(valuelen == 4 &&
3065 			strcasecmp("POST", (const char*)value) == 0) {
3066 			h2_stream->http_method = HTTP_METHOD_POST;
3067 			if(h2_stream->qbuffer) {
3068 				/* POST method uses query from DATA frames */
3069 				lock_basic_lock(&http2_query_buffer_count_lock);
3070 				http2_query_buffer_count -=
3071 					sldns_buffer_capacity(h2_stream->qbuffer);
3072 				lock_basic_unlock(&http2_query_buffer_count_lock);
3073 				sldns_buffer_free(h2_stream->qbuffer);
3074 				h2_stream->qbuffer = NULL;
3075 			}
3076 		} else
3077 			h2_stream->http_method = HTTP_METHOD_UNSUPPORTED;
3078 		return 0;
3079 	}
3080 	if(namelen == 5 && memcmp(":path", name, namelen) == 0) {
3081 		/* :path may contain DNS query, depending on method. Method might
3082 		 * not be known yet here, so check after finishing receiving
3083 		 * stream. */
3084 #define	HTTP_QUERY_PARAM "?dns="
3085 		size_t el = strlen(h2_session->c->http_endpoint);
3086 		size_t qpl = strlen(HTTP_QUERY_PARAM);
3087 
3088 		if(valuelen < el || memcmp(h2_session->c->http_endpoint,
3089 			value, el) != 0) {
3090 			h2_stream->invalid_endpoint = 1;
3091 			return 0;
3092 		}
3093 		/* larger than endpoint only allowed if it is for the query
3094 		 * parameter */
3095 		if(valuelen <= el+qpl ||
3096 			memcmp(HTTP_QUERY_PARAM, value+el, qpl) != 0) {
3097 			if(valuelen != el)
3098 				h2_stream->invalid_endpoint = 1;
3099 			return 0;
3100 		}
3101 
3102 		if(!http2_buffer_uri_query(h2_session, h2_stream,
3103 			value+(el+qpl), valuelen-(el+qpl))) {
3104 			return NGHTTP2_ERR_CALLBACK_FAILURE;
3105 		}
3106 		return 0;
3107 	}
3108 	/* Content type is a SHOULD (rfc7231#section-3.1.1.5) when using POST,
3109 	 * and not needed when using GET. Don't enforce.
3110 	 * If set only allow lowercase "application/dns-message".
3111 	 *
3112 	 * Clients SHOULD (rfc8484#section-4.1) set an accept header, but MUST
3113 	 * be able to handle "application/dns-message". Since that is the only
3114 	 * content-type supported we can ignore the accept header.
3115 	 */
3116 	if((namelen == 12 && memcmp("content-type", name, namelen) == 0)) {
3117 		if(valuelen != 23 || memcmp("application/dns-message", value,
3118 			valuelen) != 0) {
3119 			h2_stream->invalid_content_type = 1;
3120 		}
3121 	}
3122 
3123 	/* Only interested in content-lentg for POST (on not yet known) method.
3124 	 */
3125 	if((!h2_stream->http_method ||
3126 		h2_stream->http_method == HTTP_METHOD_POST) &&
3127 		!h2_stream->content_length && namelen  == 14 &&
3128 		memcmp("content-length", name, namelen) == 0) {
3129 		if(valuelen > 5) {
3130 			h2_stream->query_too_large = 1;
3131 			return 0;
3132 		}
3133 		/* guaranteed to only contain digits and be null terminated */
3134 		h2_stream->content_length = atoi((const char*)value);
3135 		if(h2_stream->content_length >
3136 			h2_session->c->http2_stream_max_qbuffer_size) {
3137 			h2_stream->query_too_large = 1;
3138 			return 0;
3139 		}
3140 	}
3141 	return 0;
3142 }
3143 
3144 /** nghttp2 callback. Used to get data from DATA frames, which can contain
3145  * queries in POST requests. */
http2_req_data_chunk_recv_cb(nghttp2_session * ATTR_UNUSED (session),uint8_t ATTR_UNUSED (flags),int32_t stream_id,const uint8_t * data,size_t len,void * cb_arg)3146 static int http2_req_data_chunk_recv_cb(nghttp2_session* ATTR_UNUSED(session),
3147 	uint8_t ATTR_UNUSED(flags), int32_t stream_id, const uint8_t* data,
3148 	size_t len, void* cb_arg)
3149 {
3150 	struct http2_session* h2_session = (struct http2_session*)cb_arg;
3151 	struct http2_stream* h2_stream;
3152 	size_t qlen = 0;
3153 
3154 	if(!(h2_stream = nghttp2_session_get_stream_user_data(
3155 		h2_session->session, stream_id))) {
3156 		return 0;
3157 	}
3158 
3159 	if(h2_stream->query_too_large)
3160 		return 0;
3161 
3162 	if(!h2_stream->qbuffer) {
3163 		if(h2_stream->content_length) {
3164 			if(h2_stream->content_length < len)
3165 				/* getting more data in DATA frame than
3166 				 * advertised in content-length header. */
3167 				return NGHTTP2_ERR_CALLBACK_FAILURE;
3168 			qlen = h2_stream->content_length;
3169 		} else if(len <= h2_session->c->http2_stream_max_qbuffer_size) {
3170 			/* setting this to msg-buffer-size can result in a lot
3171 			 * of memory consumption. Most queries should fit in a
3172 			 * single DATA frame, and most POST queries will
3173 			 * contain content-length which does not impose this
3174 			 * limit. */
3175 			qlen = len;
3176 		}
3177 	}
3178 	if(!h2_stream->qbuffer && qlen) {
3179 		lock_basic_lock(&http2_query_buffer_count_lock);
3180 		if(http2_query_buffer_count + qlen > http2_query_buffer_max) {
3181 			lock_basic_unlock(&http2_query_buffer_count_lock);
3182 			verbose(VERB_ALGO, "reset HTTP2 stream, no space left, "
3183 				"in http2-query-buffer-size");
3184 			return http2_submit_rst_stream(h2_session, h2_stream);
3185 		}
3186 		http2_query_buffer_count += qlen;
3187 		lock_basic_unlock(&http2_query_buffer_count_lock);
3188 		if(!(h2_stream->qbuffer = sldns_buffer_new(qlen))) {
3189 			lock_basic_lock(&http2_query_buffer_count_lock);
3190 			http2_query_buffer_count -= qlen;
3191 			lock_basic_unlock(&http2_query_buffer_count_lock);
3192 		}
3193 	}
3194 
3195 	if(!h2_stream->qbuffer ||
3196 		sldns_buffer_remaining(h2_stream->qbuffer) < len) {
3197 		verbose(VERB_ALGO, "http2 data_chunk_recv failed. Not enough "
3198 			"buffer space for POST query. Can happen on multi "
3199 			"frame requests without content-length header");
3200 		h2_stream->query_too_large = 1;
3201 		return 0;
3202 	}
3203 
3204 	sldns_buffer_write(h2_stream->qbuffer, data, len);
3205 
3206 	return 0;
3207 }
3208 
http2_req_stream_clear(struct http2_stream * h2_stream)3209 void http2_req_stream_clear(struct http2_stream* h2_stream)
3210 {
3211 	if(h2_stream->qbuffer) {
3212 		lock_basic_lock(&http2_query_buffer_count_lock);
3213 		http2_query_buffer_count -=
3214 			sldns_buffer_capacity(h2_stream->qbuffer);
3215 		lock_basic_unlock(&http2_query_buffer_count_lock);
3216 		sldns_buffer_free(h2_stream->qbuffer);
3217 		h2_stream->qbuffer = NULL;
3218 	}
3219 	if(h2_stream->rbuffer) {
3220 		lock_basic_lock(&http2_response_buffer_count_lock);
3221 		http2_response_buffer_count -=
3222 			sldns_buffer_capacity(h2_stream->rbuffer);
3223 		lock_basic_unlock(&http2_response_buffer_count_lock);
3224 		sldns_buffer_free(h2_stream->rbuffer);
3225 		h2_stream->rbuffer = NULL;
3226 	}
3227 }
3228 
http2_req_callbacks_create(void)3229 nghttp2_session_callbacks* http2_req_callbacks_create(void)
3230 {
3231 	nghttp2_session_callbacks *callbacks;
3232 	if(nghttp2_session_callbacks_new(&callbacks) == NGHTTP2_ERR_NOMEM) {
3233 		log_err("failed to initialize nghttp2 callback");
3234 		return NULL;
3235 	}
3236 	/* reception of header block started, used to create h2_stream */
3237 	nghttp2_session_callbacks_set_on_begin_headers_callback(callbacks,
3238 		http2_req_begin_headers_cb);
3239 	/* complete frame received, used to get data from stream if frame
3240 	 * has end stream flag, and start processing query */
3241 	nghttp2_session_callbacks_set_on_frame_recv_callback(callbacks,
3242 		http2_req_frame_recv_cb);
3243 	/* get request info from headers */
3244 	nghttp2_session_callbacks_set_on_header_callback(callbacks,
3245 		http2_req_header_cb);
3246 	/* get data from DATA frames, containing POST query */
3247 	nghttp2_session_callbacks_set_on_data_chunk_recv_callback(callbacks,
3248 		http2_req_data_chunk_recv_cb);
3249 
3250 	/* generic HTTP2 callbacks */
3251 	nghttp2_session_callbacks_set_recv_callback(callbacks, http2_recv_cb);
3252 	nghttp2_session_callbacks_set_send_callback(callbacks, http2_send_cb);
3253 	nghttp2_session_callbacks_set_on_stream_close_callback(callbacks,
3254 		http2_stream_close_cb);
3255 
3256 	return callbacks;
3257 }
3258 #endif /* HAVE_NGHTTP2 */
3259 
3260 #ifdef HAVE_NGTCP2
3261 struct doq_table*
doq_table_create(struct config_file * cfg,struct ub_randstate * rnd)3262 doq_table_create(struct config_file* cfg, struct ub_randstate* rnd)
3263 {
3264 	struct doq_table* table;
3265 
3266 	if (!cfg->quic_port)
3267 		return NULL;
3268 	table = calloc(1, sizeof(*table));
3269 	if(!table)
3270 		return NULL;
3271 #ifdef USE_NGTCP2_CRYPTO_OSSL
3272 	/* Initialize the ossl crypto, it is harmless to call twice,
3273 	 * and this is before use of doq connections. */
3274 	if(ngtcp2_crypto_ossl_init() != 0) {
3275 		log_err("ngtcp2_crypto_ossl_init failed");
3276 		free(table);
3277 		return NULL;
3278 	}
3279 #elif defined(HAVE_NGTCP2_CRYPTO_QUICTLS_INIT)
3280 	if(ngtcp2_crypto_quictls_init() != 0) {
3281 		log_err("ngtcp2_crypto_quictls_init failed");
3282 		free(table);
3283 		return NULL;
3284 	}
3285 #endif
3286 	table->idle_timeout = ((uint64_t)cfg->tcp_idle_timeout)*
3287 		NGTCP2_MILLISECONDS;
3288 	table->sv_scidlen = 16;
3289 	table->static_secret_len = 16;
3290 	table->static_secret = malloc(table->static_secret_len);
3291 	if(!table->static_secret) {
3292 		free(table);
3293 		return NULL;
3294 	}
3295 	doq_fill_rand(rnd, table->static_secret, table->static_secret_len);
3296 	table->conn_tree = rbtree_create(doq_conn_cmp);
3297 	if(!table->conn_tree) {
3298 		free(table->static_secret);
3299 		free(table);
3300 		return NULL;
3301 	}
3302 	table->conid_tree = rbtree_create(doq_conid_cmp);
3303 	if(!table->conid_tree) {
3304 		free(table->static_secret);
3305 		free(table->conn_tree);
3306 		free(table);
3307 		return NULL;
3308 	}
3309 	table->timer_tree = rbtree_create(doq_timer_cmp);
3310 	if(!table->timer_tree) {
3311 		free(table->static_secret);
3312 		free(table->conn_tree);
3313 		free(table->conid_tree);
3314 		free(table);
3315 		return NULL;
3316 	}
3317 	lock_rw_init(&table->lock);
3318 	lock_rw_init(&table->conid_lock);
3319 	lock_basic_init(&table->size_lock);
3320 	lock_protect(&table->lock, &table->static_secret,
3321 		sizeof(table->static_secret));
3322 	lock_protect(&table->lock, &table->static_secret_len,
3323 		sizeof(table->static_secret_len));
3324 	lock_protect(&table->lock, table->static_secret,
3325 		table->static_secret_len);
3326 	lock_protect(&table->lock, &table->sv_scidlen,
3327 		sizeof(table->sv_scidlen));
3328 	lock_protect(&table->lock, &table->idle_timeout,
3329 		sizeof(table->idle_timeout));
3330 	lock_protect(&table->lock, &table->conn_tree, sizeof(table->conn_tree));
3331 	lock_protect(&table->lock, table->conn_tree, sizeof(*table->conn_tree));
3332 	lock_protect(&table->conid_lock, table->conid_tree,
3333 		sizeof(*table->conid_tree));
3334 	lock_protect(&table->lock, table->timer_tree,
3335 		sizeof(*table->timer_tree));
3336 	lock_protect(&table->size_lock, &table->current_size,
3337 		sizeof(table->current_size));
3338 	return table;
3339 }
3340 
3341 /** delete elements from the connection tree */
3342 static void
conn_tree_del(rbnode_type * node,void * arg)3343 conn_tree_del(rbnode_type* node, void* arg)
3344 {
3345 	struct doq_table* table = (struct doq_table*)arg;
3346 	struct doq_conn* conn;
3347 	if(!node || !table)
3348 		return;
3349 	conn = (struct doq_conn*)node->key;
3350 	if(conn->timer.timer_in_list) {
3351 		/* Remove timer from list first, because finding the rbnode
3352 		 * element of the setlist of same timeouts needs tree lookup.
3353 		 * Edit the tree structure after that lookup. */
3354 		doq_timer_list_remove(conn->table, &conn->timer);
3355 	}
3356 	if(conn->timer.timer_in_tree)
3357 		doq_timer_tree_remove(conn->table, &conn->timer);
3358 	doq_table_quic_size_subtract(table, sizeof(*conn)+conn->key.dcidlen);
3359 	doq_conn_delete(conn, table);
3360 }
3361 
3362 /** delete elements from the connection id tree */
3363 static void
conid_tree_del(rbnode_type * node,void * ATTR_UNUSED (arg))3364 conid_tree_del(rbnode_type* node, void* ATTR_UNUSED(arg))
3365 {
3366 	if(!node)
3367 		return;
3368 	doq_conid_delete((struct doq_conid*)node->key);
3369 }
3370 
3371 void
doq_table_delete(struct doq_table * table)3372 doq_table_delete(struct doq_table* table)
3373 {
3374 	if(!table)
3375 		return;
3376 	lock_rw_destroy(&table->lock);
3377 	free(table->static_secret);
3378 	if(table->conn_tree) {
3379 		traverse_postorder(table->conn_tree, conn_tree_del, table);
3380 		free(table->conn_tree);
3381 	}
3382 	lock_rw_destroy(&table->conid_lock);
3383 	if(table->conid_tree) {
3384 		/* The tree should be empty, because the doq_conn_delete calls
3385 		 * above should have also removed their conid elements. */
3386 		traverse_postorder(table->conid_tree, conid_tree_del, NULL);
3387 		free(table->conid_tree);
3388 	}
3389 	lock_basic_destroy(&table->size_lock);
3390 	if(table->timer_tree) {
3391 		/* The tree should be empty, because the conn_tree_del calls
3392 		 * above should also have removed them. Also the doq_timer
3393 		 * is part of the doq_conn struct, so is already freed. */
3394 		free(table->timer_tree);
3395 	}
3396 	table->write_list_first = NULL;
3397 	table->write_list_last = NULL;
3398 	free(table);
3399 }
3400 
3401 struct doq_timer*
doq_timer_find_time(struct doq_table * table,ngtcp2_tstamp ts)3402 doq_timer_find_time(struct doq_table* table, ngtcp2_tstamp ts)
3403 {
3404 	struct doq_timer key;
3405 	struct rbnode_type* node;
3406 	log_assert(table != NULL);
3407 	memset(&key, 0, sizeof(key));
3408 	key.time_mono = ts;
3409 	node = rbtree_search(table->timer_tree, &key);
3410 	if(node)
3411 		return (struct doq_timer*)node->key;
3412 	return NULL;
3413 }
3414 
3415 void
doq_timer_tree_remove(struct doq_table * table,struct doq_timer * timer)3416 doq_timer_tree_remove(struct doq_table* table, struct doq_timer* timer)
3417 {
3418 	if(!timer->timer_in_tree)
3419 		return;
3420 	rbtree_delete(table->timer_tree, timer);
3421 	timer->timer_in_tree = 0;
3422 	/* This item could have more timers in the same set. */
3423 	if(timer->setlist_first) {
3424 		struct doq_timer* rb_timer = timer->setlist_first;
3425 		/* del first element from setlist */
3426 		if(rb_timer->setlist_next)
3427 			rb_timer->setlist_next->setlist_prev = NULL;
3428 		else
3429 			timer->setlist_last = NULL;
3430 		timer->setlist_first = rb_timer->setlist_next;
3431 		rb_timer->setlist_prev = NULL;
3432 		rb_timer->setlist_next = NULL;
3433 		rb_timer->timer_in_list = 0;
3434 		/* insert it into the tree as new rb element */
3435 		memset(&rb_timer->node, 0, sizeof(rb_timer->node));
3436 		rb_timer->node.key = rb_timer;
3437 		rbtree_insert(table->timer_tree, &rb_timer->node);
3438 		rb_timer->timer_in_tree = 1;
3439 		/* the setlist, if any remainder, moves to the rb element */
3440 		rb_timer->setlist_first = timer->setlist_first;
3441 		rb_timer->setlist_last = timer->setlist_last;
3442 		timer->setlist_first = NULL;
3443 		timer->setlist_last = NULL;
3444 		rb_timer->worker_doq_socket = timer->worker_doq_socket;
3445 	}
3446 	timer->worker_doq_socket = NULL;
3447 }
3448 
3449 void
doq_timer_list_remove(struct doq_table * table,struct doq_timer * timer)3450 doq_timer_list_remove(struct doq_table* table, struct doq_timer* timer)
3451 {
3452 	struct doq_timer* rb_timer;
3453 	if(!timer->timer_in_list)
3454 		return;
3455 	/* The item in the rbtree has the list start and end. */
3456 	rb_timer = doq_timer_find_time(table, timer->time_mono);
3457 	if(rb_timer) {
3458 		if(timer->setlist_prev)
3459 			timer->setlist_prev->setlist_next = timer->setlist_next;
3460 		else
3461 			rb_timer->setlist_first = timer->setlist_next;
3462 		if(timer->setlist_next)
3463 			timer->setlist_next->setlist_prev = timer->setlist_prev;
3464 		else
3465 			rb_timer->setlist_last = timer->setlist_prev;
3466 		timer->setlist_prev = NULL;
3467 		timer->setlist_next = NULL;
3468 	}
3469 	timer->timer_in_list = 0;
3470 }
3471 
3472 /** doq append timer to setlist */
3473 static void
doq_timer_list_append(struct doq_timer * rb_timer,struct doq_timer * timer)3474 doq_timer_list_append(struct doq_timer* rb_timer, struct doq_timer* timer)
3475 {
3476 	log_assert(timer->timer_in_list == 0);
3477 	timer->timer_in_list = 1;
3478 	timer->setlist_next = NULL;
3479 	timer->setlist_prev = rb_timer->setlist_last;
3480 	if(rb_timer->setlist_last)
3481 		rb_timer->setlist_last->setlist_next = timer;
3482 	else
3483 		rb_timer->setlist_first = timer;
3484 	rb_timer->setlist_last = timer;
3485 }
3486 
3487 void
doq_timer_unset(struct doq_table * table,struct doq_timer * timer)3488 doq_timer_unset(struct doq_table* table, struct doq_timer* timer)
3489 {
3490 	if(timer->timer_in_list) {
3491 		/* Remove timer from list first, because finding the rbnode
3492 		 * element of the setlist of same timeouts needs tree lookup.
3493 		 * Edit the tree structure after that lookup. */
3494 		doq_timer_list_remove(table, timer);
3495 	}
3496 	if(timer->timer_in_tree)
3497 		doq_timer_tree_remove(table, timer);
3498 	timer->worker_doq_socket = NULL;
3499 }
3500 
doq_timer_set(struct doq_table * table,struct doq_timer * timer,struct doq_server_socket * worker_doq_socket,struct timeval * tv,ngtcp2_tstamp ts)3501 void doq_timer_set(struct doq_table* table, struct doq_timer* timer,
3502 	struct doq_server_socket* worker_doq_socket, struct timeval* tv,
3503 	ngtcp2_tstamp ts)
3504 {
3505 	struct doq_timer* rb_timer;
3506 	if(verbosity >= VERB_ALGO && timer->conn) {
3507 		char a[256];
3508 		struct timeval rel;
3509 		addr_to_str((void*)&timer->conn->key.paddr.addr,
3510 			timer->conn->key.paddr.addrlen, a, sizeof(a));
3511 		timeval_subtract(&rel, tv, worker_doq_socket->now_tv);
3512 		verbose(VERB_ALGO, "doq %s timer set %d.%6.6d in %d.%6.6d",
3513 			a, (int)tv->tv_sec, (int)tv->tv_usec,
3514 			(int)rel.tv_sec, (int)rel.tv_usec);
3515 	}
3516 	if(timer->timer_in_tree || timer->timer_in_list) {
3517 		if(timer->time_mono == ts)
3518 			return; /* already set on that time */
3519 		doq_timer_unset(table, timer);
3520 	}
3521 	timer->time_real.tv_sec = tv->tv_sec;
3522 	timer->time_real.tv_usec = tv->tv_usec;
3523 	timer->time_mono = ts;
3524 	rb_timer = doq_timer_find_time(table, ts);
3525 	if(rb_timer) {
3526 		/* There is a timeout already with this value. Timer is
3527 		 * added to the setlist. */
3528 		doq_timer_list_append(rb_timer, timer);
3529 	} else {
3530 		/* There is no timeout with this value. Make timer a new
3531 		 * tree element. */
3532 		memset(&timer->node, 0, sizeof(timer->node));
3533 		timer->node.key = timer;
3534 		rbtree_insert(table->timer_tree, &timer->node);
3535 		timer->timer_in_tree = 1;
3536 		timer->setlist_first = NULL;
3537 		timer->setlist_last = NULL;
3538 		timer->worker_doq_socket = worker_doq_socket;
3539 	}
3540 }
3541 
3542 struct doq_conn*
doq_conn_create(struct comm_point * c,struct doq_pkt_addr * paddr,const uint8_t * dcid,size_t dcidlen,uint32_t version)3543 doq_conn_create(struct comm_point* c, struct doq_pkt_addr* paddr,
3544 	const uint8_t* dcid, size_t dcidlen, uint32_t version)
3545 {
3546 	struct doq_conn* conn = calloc(1, sizeof(*conn));
3547 	if(!conn)
3548 		return NULL;
3549 	conn->node.key = conn;
3550 	conn->doq_socket = c->doq_socket;
3551 	conn->table = c->doq_socket->table;
3552 	memmove(&conn->key.paddr.addr, &paddr->addr, paddr->addrlen);
3553 	conn->key.paddr.addrlen = paddr->addrlen;
3554 	memmove(&conn->key.paddr.localaddr, &paddr->localaddr,
3555 		paddr->localaddrlen);
3556 	conn->key.paddr.localaddrlen = paddr->localaddrlen;
3557 	conn->key.paddr.ifindex = paddr->ifindex;
3558 	conn->key.dcid = memdup((void*)dcid, dcidlen);
3559 	if(!conn->key.dcid) {
3560 		free(conn);
3561 		return NULL;
3562 	}
3563 	conn->key.dcidlen = dcidlen;
3564 	conn->version = version;
3565 #ifdef HAVE_NGTCP2_CCERR_DEFAULT
3566 	ngtcp2_ccerr_default(&conn->ccerr);
3567 #else
3568 	ngtcp2_connection_close_error_default(&conn->last_error);
3569 #endif
3570 	rbtree_init(&conn->stream_tree, &doq_stream_cmp);
3571 	conn->timer.conn = conn;
3572 	lock_basic_init(&conn->lock);
3573 	lock_protect(&conn->lock, &conn->key, sizeof(conn->key));
3574 	lock_protect(&conn->lock, &conn->doq_socket, sizeof(conn->doq_socket));
3575 	lock_protect(&conn->lock, &conn->table, sizeof(conn->table));
3576 	lock_protect(&conn->lock, &conn->is_deleted, sizeof(conn->is_deleted));
3577 	lock_protect(&conn->lock, &conn->version, sizeof(conn->version));
3578 	lock_protect(&conn->lock, &conn->conn, sizeof(conn->conn));
3579 	lock_protect(&conn->lock, &conn->conid_list, sizeof(conn->conid_list));
3580 #ifdef HAVE_NGTCP2_CCERR_DEFAULT
3581 	lock_protect(&conn->lock, &conn->ccerr, sizeof(conn->ccerr));
3582 #else
3583 	lock_protect(&conn->lock, &conn->last_error, sizeof(conn->last_error));
3584 #endif
3585 	lock_protect(&conn->lock, &conn->tls_alert, sizeof(conn->tls_alert));
3586 	lock_protect(&conn->lock, &conn->ssl, sizeof(conn->ssl));
3587 	lock_protect(&conn->lock, &conn->close_pkt, sizeof(conn->close_pkt));
3588 	lock_protect(&conn->lock, &conn->close_pkt_len, sizeof(conn->close_pkt_len));
3589 	lock_protect(&conn->lock, &conn->close_ecn, sizeof(conn->close_ecn));
3590 	lock_protect(&conn->lock, &conn->stream_tree, sizeof(conn->stream_tree));
3591 	lock_protect(&conn->lock, &conn->stream_write_first, sizeof(conn->stream_write_first));
3592 	lock_protect(&conn->lock, &conn->stream_write_last, sizeof(conn->stream_write_last));
3593 	lock_protect(&conn->lock, &conn->write_interest, sizeof(conn->write_interest));
3594 	lock_protect(&conn->lock, &conn->on_write_list, sizeof(conn->on_write_list));
3595 	lock_protect(&conn->lock, &conn->write_prev, sizeof(conn->write_prev));
3596 	lock_protect(&conn->lock, &conn->write_next, sizeof(conn->write_next));
3597 	return conn;
3598 }
3599 
3600 /** The arguments for doq stream tree del. */
3601 struct doq_stream_tree_del_args {
3602 	/** The doq table. */
3603 	struct doq_table* table;
3604 	/** The doq connection for the stream. */
3605 	struct doq_conn* conn;
3606 };
3607 
3608 /** delete stream tree node */
3609 static void
stream_tree_del(rbnode_type * node,void * arg)3610 stream_tree_del(rbnode_type* node, void* arg)
3611 {
3612 	struct doq_stream_tree_del_args* args = (struct doq_stream_tree_del_args*)arg;
3613 	struct doq_table* table = args->table;
3614 	struct doq_stream* stream;
3615 	if(!node)
3616 		return;
3617 	stream = (struct doq_stream*)node;
3618 	if(stream->mesh_state) {
3619 		mesh_state_remove_reply(stream->mesh, stream->mesh_state,
3620 			args->conn->doq_socket->cp, NULL, stream);
3621 		stream->mesh_state = NULL;
3622 	}
3623 	if(stream->in)
3624 		doq_table_quic_size_subtract(table, stream->inlen);
3625 	if(stream->out)
3626 		doq_table_quic_size_subtract(table, stream->outlen);
3627 	doq_table_quic_size_subtract(table, sizeof(*stream));
3628 	doq_stream_delete(stream);
3629 }
3630 
3631 void
doq_conn_delete(struct doq_conn * conn,struct doq_table * table)3632 doq_conn_delete(struct doq_conn* conn, struct doq_table* table)
3633 {
3634 	if(!conn)
3635 		return;
3636 	lock_basic_destroy(&conn->lock);
3637 	lock_rw_wrlock(&conn->table->conid_lock);
3638 	doq_conn_clear_conids(conn);
3639 	lock_rw_unlock(&conn->table->conid_lock);
3640 	/* Remove the app data from ngtcp2 before SSL_free of conn->ssl,
3641 	 * because the ngtcp2 conn is deleted. */
3642 	if(conn->ssl)
3643 		SSL_set_app_data(conn->ssl, NULL);
3644 	if(conn->stream_tree.count != 0) {
3645 		struct doq_stream_tree_del_args args;
3646 		memset(&args, 0, sizeof(args));
3647 		args.table = table;
3648 		args.conn = conn;
3649 		traverse_postorder(&conn->stream_tree, stream_tree_del, &args);
3650 	}
3651 	free(conn->key.dcid);
3652 	SSL_free(conn->ssl);
3653 #ifdef USE_NGTCP2_CRYPTO_OSSL
3654 	ngtcp2_crypto_ossl_ctx_del(conn->ossl_ctx);
3655 #endif
3656 	ngtcp2_conn_del(conn->conn);
3657 	free(conn->close_pkt);
3658 	free(conn);
3659 }
3660 
3661 int
doq_conn_cmp(const void * key1,const void * key2)3662 doq_conn_cmp(const void* key1, const void* key2)
3663 {
3664 	struct doq_conn* c = (struct doq_conn*)key1;
3665 	struct doq_conn* d = (struct doq_conn*)key2;
3666 	int r;
3667 	/* Compared in the order destination address, then
3668 	 * local address, ifindex and then dcid.
3669 	 * So that for a search for findlessorequal for the destination
3670 	 * address will find connections to that address, with different
3671 	 * dcids.
3672 	 * Also a printout in sorted order prints the connections by IP
3673 	 * address of destination, and then a number of them depending on the
3674 	 * dcids. */
3675 	if(c->key.paddr.addrlen != d->key.paddr.addrlen) {
3676 		if(c->key.paddr.addrlen < d->key.paddr.addrlen)
3677 			return -1;
3678 		return 1;
3679 	}
3680 	if((r=memcmp(&c->key.paddr.addr, &d->key.paddr.addr,
3681 		c->key.paddr.addrlen))!=0)
3682 		return r;
3683 	if(c->key.paddr.localaddrlen != d->key.paddr.localaddrlen) {
3684 		if(c->key.paddr.localaddrlen < d->key.paddr.localaddrlen)
3685 			return -1;
3686 		return 1;
3687 	}
3688 	if((r=memcmp(&c->key.paddr.localaddr, &d->key.paddr.localaddr,
3689 		c->key.paddr.localaddrlen))!=0)
3690 		return r;
3691 	if(c->key.paddr.ifindex != d->key.paddr.ifindex) {
3692 		if(c->key.paddr.ifindex < d->key.paddr.ifindex)
3693 			return -1;
3694 		return 1;
3695 	}
3696 	if(c->key.dcidlen != d->key.dcidlen) {
3697 		if(c->key.dcidlen < d->key.dcidlen)
3698 			return -1;
3699 		return 1;
3700 	}
3701 	if((r=memcmp(c->key.dcid, d->key.dcid, c->key.dcidlen))!=0)
3702 		return r;
3703 	return 0;
3704 }
3705 
doq_conid_cmp(const void * key1,const void * key2)3706 int doq_conid_cmp(const void* key1, const void* key2)
3707 {
3708 	struct doq_conid* c = (struct doq_conid*)key1;
3709 	struct doq_conid* d = (struct doq_conid*)key2;
3710 	if(c->cidlen != d->cidlen) {
3711 		if(c->cidlen < d->cidlen)
3712 			return -1;
3713 		return 1;
3714 	}
3715 	return memcmp(c->cid, d->cid, c->cidlen);
3716 }
3717 
doq_timer_cmp(const void * key1,const void * key2)3718 int doq_timer_cmp(const void* key1, const void* key2)
3719 {
3720 	struct doq_timer* e = (struct doq_timer*)key1;
3721 	struct doq_timer* f = (struct doq_timer*)key2;
3722 	if(e->time_mono < f->time_mono)
3723 		return -1;
3724 	if(e->time_mono > f->time_mono)
3725 		return 1;
3726 	return 0;
3727 }
3728 
doq_stream_cmp(const void * key1,const void * key2)3729 int doq_stream_cmp(const void* key1, const void* key2)
3730 {
3731 	struct doq_stream* c = (struct doq_stream*)key1;
3732 	struct doq_stream* d = (struct doq_stream*)key2;
3733 	if(c->stream_id != d->stream_id) {
3734 		if(c->stream_id < d->stream_id)
3735 			return -1;
3736 		return 1;
3737 	}
3738 	return 0;
3739 }
3740 
3741 /** doq store a local address in repinfo */
3742 static void
doq_repinfo_store_localaddr(struct comm_reply * repinfo,struct doq_addr_storage * localaddr,socklen_t localaddrlen)3743 doq_repinfo_store_localaddr(struct comm_reply* repinfo,
3744 	struct doq_addr_storage* localaddr, socklen_t localaddrlen)
3745 {
3746 	/* use the pktinfo that we have for ancillary udp data otherwise,
3747 	 * this saves space for a sockaddr */
3748 	memset(&repinfo->pktinfo, 0, sizeof(repinfo->pktinfo));
3749 	if(addr_is_ip6((void*)localaddr, localaddrlen)) {
3750 #ifdef IPV6_PKTINFO
3751 		struct sockaddr_in6* sa6 = (struct sockaddr_in6*)localaddr;
3752 		memmove(&repinfo->pktinfo.v6info.ipi6_addr,
3753 			&sa6->sin6_addr, sizeof(struct in6_addr));
3754 		repinfo->doq_srcport = sa6->sin6_port;
3755 #endif
3756 		repinfo->srctype = 6;
3757 	} else {
3758 #ifdef IP_PKTINFO
3759 		struct sockaddr_in* sa = (struct sockaddr_in*)localaddr;
3760 		memmove(&repinfo->pktinfo.v4info.ipi_addr,
3761 			&sa->sin_addr, sizeof(struct in_addr));
3762 		repinfo->doq_srcport = sa->sin_port;
3763 #elif defined(IP_RECVDSTADDR)
3764 		struct sockaddr_in* sa = (struct sockaddr_in*)localaddr;
3765 		memmove(&repinfo->pktinfo.v4addr, &sa->sin_addr,
3766 			sizeof(struct in_addr));
3767 		repinfo->doq_srcport = sa->sin_port;
3768 #endif
3769 		repinfo->srctype = 4;
3770 	}
3771 }
3772 
3773 /** doq retrieve localaddr from repinfo */
3774 static void
doq_repinfo_retrieve_localaddr(struct comm_reply * repinfo,struct doq_addr_storage * localaddr,socklen_t * localaddrlen)3775 doq_repinfo_retrieve_localaddr(struct comm_reply* repinfo,
3776 	struct doq_addr_storage* localaddr, socklen_t* localaddrlen)
3777 {
3778 	if(repinfo->srctype == 6) {
3779 #ifdef IPV6_PKTINFO
3780 		struct sockaddr_in6* sa6 = (struct sockaddr_in6*)localaddr;
3781 		*localaddrlen = (socklen_t)sizeof(struct sockaddr_in6);
3782 		memset(sa6, 0, *localaddrlen);
3783 		sa6->sin6_family = AF_INET6;
3784 		memmove(&sa6->sin6_addr, &repinfo->pktinfo.v6info.ipi6_addr,
3785 			sizeof(struct in6_addr));
3786 		sa6->sin6_port = repinfo->doq_srcport;
3787 #endif
3788 	} else {
3789 #ifdef IP_PKTINFO
3790 		struct sockaddr_in* sa = (struct sockaddr_in*)localaddr;
3791 		*localaddrlen = (socklen_t)sizeof(struct sockaddr_in);
3792 		memset(sa, 0, *localaddrlen);
3793 		sa->sin_family = AF_INET;
3794 		memmove(&sa->sin_addr, &repinfo->pktinfo.v4info.ipi_addr,
3795 			sizeof(struct in_addr));
3796 		sa->sin_port = repinfo->doq_srcport;
3797 #elif defined(IP_RECVDSTADDR)
3798 		struct sockaddr_in* sa = (struct sockaddr_in*)localaddr;
3799 		*localaddrlen = (socklen_t)sizeof(struct sockaddr_in);
3800 		memset(sa, 0, *localaddrlen);
3801 		sa->sin_family = AF_INET;
3802 		memmove(&sa->sin_addr, &repinfo->pktinfo.v4addr,
3803 			sizeof(struct in_addr));
3804 		sa->sin_port = repinfo->doq_srcport;
3805 #endif
3806 	}
3807 }
3808 
3809 /** doq write a connection key into repinfo, false if it does not fit */
3810 static int
doq_conn_key_store_repinfo(struct doq_conn_key * key,struct comm_reply * repinfo)3811 doq_conn_key_store_repinfo(struct doq_conn_key* key,
3812 	struct comm_reply* repinfo)
3813 {
3814 	repinfo->is_proxied = 0;
3815 	repinfo->doq_ifindex = key->paddr.ifindex;
3816 	repinfo->remote_addrlen = key->paddr.addrlen;
3817 	memmove(&repinfo->remote_addr, &key->paddr.addr,
3818 		repinfo->remote_addrlen);
3819 	repinfo->client_addrlen = key->paddr.addrlen;
3820 	memmove(&repinfo->client_addr, &key->paddr.addr,
3821 		repinfo->client_addrlen);
3822 	doq_repinfo_store_localaddr(repinfo, &key->paddr.localaddr,
3823 		key->paddr.localaddrlen);
3824 	if(key->dcidlen > sizeof(repinfo->doq_dcid))
3825 		return 0;
3826 	repinfo->doq_dcidlen = key->dcidlen;
3827 	memmove(repinfo->doq_dcid, key->dcid, key->dcidlen);
3828 	return 1;
3829 }
3830 
3831 void
doq_conn_key_from_repinfo(struct doq_conn_key * key,struct comm_reply * repinfo)3832 doq_conn_key_from_repinfo(struct doq_conn_key* key, struct comm_reply* repinfo)
3833 {
3834 	key->paddr.ifindex = repinfo->doq_ifindex;
3835 	key->paddr.addrlen = repinfo->remote_addrlen;
3836 	memmove(&key->paddr.addr, &repinfo->remote_addr,
3837 		repinfo->remote_addrlen);
3838 	doq_repinfo_retrieve_localaddr(repinfo, &key->paddr.localaddr,
3839 		&key->paddr.localaddrlen);
3840 	key->dcidlen = repinfo->doq_dcidlen;
3841 	key->dcid = repinfo->doq_dcid;
3842 }
3843 
3844 /** doq add a stream to the connection */
3845 static void
doq_conn_add_stream(struct doq_conn * conn,struct doq_stream * stream)3846 doq_conn_add_stream(struct doq_conn* conn, struct doq_stream* stream)
3847 {
3848 	(void)rbtree_insert(&conn->stream_tree, &stream->node);
3849 }
3850 
3851 /** doq delete a stream from the connection */
3852 static void
doq_conn_del_stream(struct doq_conn * conn,struct doq_stream * stream)3853 doq_conn_del_stream(struct doq_conn* conn, struct doq_stream* stream)
3854 {
3855 	(void)rbtree_delete(&conn->stream_tree, &stream->node);
3856 }
3857 
3858 /** doq create new stream */
3859 static struct doq_stream*
doq_stream_create(int64_t stream_id)3860 doq_stream_create(int64_t stream_id)
3861 {
3862 	struct doq_stream* stream = calloc(1, sizeof(*stream));
3863 	if(!stream)
3864 		return NULL;
3865 	stream->node.key = stream;
3866 	stream->stream_id = stream_id;
3867 	return stream;
3868 }
3869 
doq_stream_delete(struct doq_stream * stream)3870 void doq_stream_delete(struct doq_stream* stream)
3871 {
3872 	if(!stream)
3873 		return;
3874 	free(stream->in);
3875 	free(stream->out);
3876 	free(stream);
3877 }
3878 
3879 struct doq_stream*
doq_stream_find(struct doq_conn * conn,int64_t stream_id)3880 doq_stream_find(struct doq_conn* conn, int64_t stream_id)
3881 {
3882 	rbnode_type* node;
3883 	struct doq_stream key;
3884 	key.node.key = &key;
3885 	key.stream_id = stream_id;
3886 	node = rbtree_search(&conn->stream_tree, &key);
3887 	if(node)
3888 		return (struct doq_stream*)node->key;
3889 	return NULL;
3890 }
3891 
3892 /** doq put stream on the conn write list */
3893 static void
doq_stream_on_write_list(struct doq_conn * conn,struct doq_stream * stream)3894 doq_stream_on_write_list(struct doq_conn* conn, struct doq_stream* stream)
3895 {
3896 	if(stream->on_write_list)
3897 		return;
3898 	stream->write_prev = conn->stream_write_last;
3899 	if(conn->stream_write_last)
3900 		conn->stream_write_last->write_next = stream;
3901 	else
3902 		conn->stream_write_first = stream;
3903 	conn->stream_write_last = stream;
3904 	stream->write_next = NULL;
3905 	stream->on_write_list = 1;
3906 }
3907 
3908 /** doq remove stream from the conn write list */
3909 static void
doq_stream_off_write_list(struct doq_conn * conn,struct doq_stream * stream)3910 doq_stream_off_write_list(struct doq_conn* conn, struct doq_stream* stream)
3911 {
3912 	if(!stream->on_write_list)
3913 		return;
3914 	if(stream->write_next)
3915 		stream->write_next->write_prev = stream->write_prev;
3916 	else conn->stream_write_last = stream->write_prev;
3917 	if(stream->write_prev)
3918 		stream->write_prev->write_next = stream->write_next;
3919 	else conn->stream_write_first = stream->write_next;
3920 	stream->write_prev = NULL;
3921 	stream->write_next = NULL;
3922 	stream->on_write_list = 0;
3923 }
3924 
3925 /** doq stream remove in buffer */
3926 static void
doq_stream_remove_in_buffer(struct doq_stream * stream,struct doq_table * table)3927 doq_stream_remove_in_buffer(struct doq_stream* stream, struct doq_table* table)
3928 {
3929 	if(stream->in) {
3930 		doq_table_quic_size_subtract(table, stream->inlen);
3931 		free(stream->in);
3932 		stream->in = NULL;
3933 		stream->inlen = 0;
3934 	}
3935 }
3936 
3937 /** doq stream remove out buffer */
3938 static void
doq_stream_remove_out_buffer(struct doq_stream * stream,struct doq_table * table)3939 doq_stream_remove_out_buffer(struct doq_stream* stream,
3940 	struct doq_table* table)
3941 {
3942 	if(stream->out) {
3943 		doq_table_quic_size_subtract(table, stream->outlen);
3944 		free(stream->out);
3945 		stream->out = NULL;
3946 		stream->outlen = 0;
3947 	}
3948 }
3949 
3950 int
doq_stream_close(struct doq_conn * conn,struct doq_stream * stream,int send_shutdown)3951 doq_stream_close(struct doq_conn* conn, struct doq_stream* stream,
3952 	int send_shutdown)
3953 {
3954 	int ret;
3955 	if(stream->is_closed)
3956 		return 1;
3957 	stream->is_closed = 1;
3958 	if(stream->mesh_state) {
3959 		mesh_state_remove_reply(stream->mesh, stream->mesh_state,
3960 			conn->doq_socket->cp, NULL, stream);
3961 		stream->mesh_state = NULL;
3962 	}
3963 	doq_stream_off_write_list(conn, stream);
3964 	if(send_shutdown) {
3965 		verbose(VERB_ALGO, "doq: shutdown stream_id %d with app_error_code %d",
3966 			(int)stream->stream_id, (int)DOQ_APP_ERROR_CODE);
3967 		ret = ngtcp2_conn_shutdown_stream(conn->conn,
3968 #ifdef HAVE_NGTCP2_CONN_SHUTDOWN_STREAM4
3969 			0,
3970 #endif
3971 			stream->stream_id, DOQ_APP_ERROR_CODE);
3972 		if(ret != 0) {
3973 			log_err("doq ngtcp2_conn_shutdown_stream %d failed: %s",
3974 				(int)stream->stream_id, ngtcp2_strerror(ret));
3975 			return 0;
3976 		}
3977 		doq_conn_write_enable(conn);
3978 	}
3979 	verbose(VERB_ALGO, "doq: conn extend max streams bidi by 1");
3980 	ngtcp2_conn_extend_max_streams_bidi(conn->conn, 1);
3981 	doq_conn_write_enable(conn);
3982 	doq_stream_remove_in_buffer(stream, conn->doq_socket->table);
3983 	doq_stream_remove_out_buffer(stream, conn->doq_socket->table);
3984 	doq_table_quic_size_subtract(conn->doq_socket->table, sizeof(*stream));
3985 	doq_conn_del_stream(conn, stream);
3986 	doq_stream_delete(stream);
3987 	return 1;
3988 }
3989 
3990 /** doq stream pick up answer data from buffer */
3991 static int
doq_stream_pickup_answer(struct doq_conn * conn,struct doq_stream * stream,struct sldns_buffer * buf)3992 doq_stream_pickup_answer(struct doq_conn* conn, struct doq_stream* stream,
3993 	struct sldns_buffer* buf)
3994 {
3995 	stream->is_answer_available = 1;
3996 	if(stream->out) {
3997 		free(stream->out);
3998 		stream->out = NULL;
3999 		stream->outlen = 0;
4000 	}
4001 	stream->nwrite = 0;
4002 	stream->outlen = sldns_buffer_limit(buf);
4003 	if(!doq_table_quic_size_available(conn->doq_socket->table,
4004 		conn->doq_socket->cfg, stream->outlen)) {
4005 		verbose(VERB_ALGO, "doq stream: no space for reply length");
4006 		return 0;
4007 	}
4008 	/* For quic the output bytes have to stay allocated and available,
4009 	 * for potential resends, until the remote end has acknowledged them.
4010 	 * This includes the tcplen start uint16_t, in outlen_wire. */
4011 	stream->outlen_wire = htons(stream->outlen);
4012 	stream->out = memdup(sldns_buffer_begin(buf), sldns_buffer_limit(buf));
4013 	if(!stream->out) {
4014 		log_err("doq could not send answer: out of memory");
4015 		return 0;
4016 	}
4017 	return 1;
4018 }
4019 
4020 int
doq_stream_send_reply(struct doq_conn * conn,struct doq_stream * stream,struct sldns_buffer * buf)4021 doq_stream_send_reply(struct doq_conn* conn, struct doq_stream* stream,
4022 	struct sldns_buffer* buf)
4023 {
4024 	if(verbosity >= VERB_ALGO) {
4025 		char* s = sldns_wire2str_pkt(sldns_buffer_begin(buf),
4026 			sldns_buffer_limit(buf));
4027 		verbose(VERB_ALGO, "doq stream %d response\n%s",
4028 			(int)stream->stream_id, (s?s:"null"));
4029 		free(s);
4030 	}
4031 	if(stream->out)
4032 		doq_table_quic_size_subtract(conn->doq_socket->table,
4033 			stream->outlen);
4034 	if(!doq_stream_pickup_answer(conn, stream, buf))
4035 		return 0;
4036 	doq_table_quic_size_add(conn->doq_socket->table, stream->outlen);
4037 	doq_stream_on_write_list(conn, stream);
4038 	doq_conn_write_enable(conn);
4039 	return 1;
4040 }
4041 #endif /* HAVE_NGTCP2 */
4042 
4043 void
doq_stream_add_meshstate(struct doq_stream * stream,struct mesh_area * mesh,struct mesh_state * m)4044 doq_stream_add_meshstate(struct doq_stream* stream,
4045 	struct mesh_area* mesh, struct mesh_state* m)
4046 {
4047 #ifdef HAVE_NGTCP2
4048 	stream->mesh = mesh;
4049 	stream->mesh_state = m;
4050 #else
4051 	(void)stream; (void)mesh; (void)m;
4052 #endif
4053 }
4054 
4055 void
doq_stream_remove_mesh_state(struct doq_stream * stream)4056 doq_stream_remove_mesh_state(struct doq_stream* stream)
4057 {
4058 #ifdef HAVE_NGTCP2
4059 	if(!stream)
4060 		return;
4061 	stream->mesh_state = NULL;
4062 #else
4063 	(void)stream;
4064 #endif
4065 }
4066 
4067 #ifdef HAVE_NGTCP2
4068 /** doq stream data length has completed, allocations can be done. False on
4069  * allocation failure. */
4070 static int
doq_stream_datalen_complete(struct doq_conn * conn,struct doq_stream * stream,struct doq_table * table)4071 doq_stream_datalen_complete(struct doq_conn* conn, struct doq_stream* stream,
4072 	struct doq_table* table)
4073 {
4074 	if(stream->inlen > 1024*1024) {
4075 		log_err("doq stream in length too large %d",
4076 			(int)stream->inlen);
4077 		return 0;
4078 	}
4079 	if(!doq_table_quic_size_available(table, conn->doq_socket->cfg,
4080 		stream->inlen)) {
4081 		verbose(VERB_ALGO, "doq stream: no space for query length");
4082 		return 0;
4083 	}
4084 	stream->in = calloc(1, stream->inlen);
4085 	if(!stream->in) {
4086 		log_err("doq could not read stream, calloc failed: "
4087 			"out of memory");
4088 		return 0;
4089 	}
4090 	doq_table_quic_size_add(table, stream->inlen);
4091 	return 1;
4092 }
4093 
4094 /** doq stream data is complete, the input data has been received. */
4095 static int
doq_stream_data_complete(struct doq_conn * conn,struct doq_stream * stream)4096 doq_stream_data_complete(struct doq_conn* conn, struct doq_stream* stream)
4097 {
4098 	struct comm_point* c;
4099 	if(verbosity >= VERB_ALGO) {
4100 		char* s = sldns_wire2str_pkt(stream->in, stream->inlen);
4101 		char a[128];
4102 		addr_to_str((void*)&conn->key.paddr.addr,
4103 			conn->key.paddr.addrlen, a, sizeof(a));
4104 		verbose(VERB_ALGO, "doq %s stream %d incoming query\n%s",
4105 			a, (int)stream->stream_id, (s?s:"null"));
4106 		free(s);
4107 	}
4108 	stream->is_query_complete = 1;
4109 	c = conn->doq_socket->cp;
4110 	if(!stream->in) {
4111 		verbose(VERB_ALGO, "doq_stream_data_complete: no in buffer");
4112 		return 0;
4113 	}
4114 	if(stream->inlen > sldns_buffer_capacity(c->buffer)) {
4115 		verbose(VERB_ALGO, "doq_stream_data_complete: query too long");
4116 		return 0;
4117 	}
4118 	sldns_buffer_clear(c->buffer);
4119 	sldns_buffer_write(c->buffer, stream->in, stream->inlen);
4120 	sldns_buffer_flip(c->buffer);
4121 	c->repinfo.c = c;
4122 	if(!doq_conn_key_store_repinfo(&conn->key, &c->repinfo)) {
4123 		verbose(VERB_ALGO, "doq_stream_data_complete: connection "
4124 			"DCID too long");
4125 		return 0;
4126 	}
4127 	c->repinfo.doq_streamid = stream->stream_id;
4128 	c->repinfo.doq_stream = stream;
4129 	conn->doq_socket->current_conn = conn;
4130 	fptr_ok(fptr_whitelist_comm_point(c->callback));
4131 	if( (*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, &c->repinfo)) {
4132 		conn->doq_socket->current_conn = NULL;
4133 		if(!doq_stream_send_reply(conn, stream, c->buffer)) {
4134 			verbose(VERB_ALGO, "doq: failed to send_reply");
4135 			return 0;
4136 		}
4137 		return 1;
4138 	}
4139 	conn->doq_socket->current_conn = NULL;
4140 	return 1;
4141 }
4142 
4143 /** doq receive data for a stream, more bytes of the incoming data */
4144 static int
doq_stream_recv_data(struct doq_conn * conn,struct doq_stream * stream,const uint8_t * data,size_t datalen,int * recv_done,struct doq_table * table)4145 doq_stream_recv_data(struct doq_conn* conn, struct doq_stream* stream,
4146 	const uint8_t* data, size_t datalen, int* recv_done,
4147 	struct doq_table* table)
4148 {
4149 	int got_data = 0;
4150 	/* read the tcplength uint16_t at the start */
4151 	if(stream->nread < 2) {
4152 		uint16_t tcplen = 0;
4153 		size_t todolen = 2 - stream->nread;
4154 
4155 		if(stream->nread > 0) {
4156 			/* put in the already read byte if there is one */
4157 			tcplen = stream->inlen;
4158 		}
4159 		if(datalen < todolen)
4160 			todolen = datalen;
4161 		memmove(((uint8_t*)&tcplen)+stream->nread, data, todolen);
4162 		stream->nread += todolen;
4163 		data += todolen;
4164 		datalen -= todolen;
4165 		if(stream->nread == 2) {
4166 			/* the initial length value is completed */
4167 			stream->inlen = ntohs(tcplen);
4168 			if(!doq_stream_datalen_complete(conn, stream, table))
4169 				return 0;
4170 		} else {
4171 			/* store for later */
4172 			stream->inlen = tcplen;
4173 			return 1;
4174 		}
4175 	}
4176 	/* if there are more data bytes */
4177 	if(datalen > 0) {
4178 		size_t to_write = datalen;
4179 		if(stream->nread-2 > stream->inlen) {
4180 			verbose(VERB_ALGO, "doq stream buffer too small");
4181 			return 0;
4182 		}
4183 		if(datalen > stream->inlen - (stream->nread-2))
4184 			to_write = stream->inlen - (stream->nread-2);
4185 		if(to_write > 0) {
4186 			if(!stream->in) {
4187 				verbose(VERB_ALGO, "doq: stream has "
4188 					"no buffer");
4189 				return 0;
4190 			}
4191 			memmove(stream->in+(stream->nread-2), data, to_write);
4192 			stream->nread += to_write;
4193 			data += to_write;
4194 			datalen -= to_write;
4195 			got_data = 1;
4196 		}
4197 	}
4198 	/* Are there extra bytes received after the end? If so, log them. */
4199 	if(datalen > 0) {
4200 		if(verbosity >= VERB_ALGO)
4201 			log_hex("doq stream has extra bytes received after end",
4202 				(void*)data, datalen);
4203 	}
4204 	/* Is the input data complete? */
4205 	if(got_data && stream->nread >= stream->inlen+2) {
4206 		if(!stream->in) {
4207 			verbose(VERB_ALGO, "doq: completed stream has "
4208 				"no buffer");
4209 			return 0;
4210 		}
4211 		*recv_done = 1;
4212 	}
4213 	return 1;
4214 }
4215 
4216 /** doq receive FIN for a stream. No more bytes are going to arrive. */
4217 static int
doq_stream_recv_fin(struct doq_conn * conn,struct doq_stream * stream,int recv_done)4218 doq_stream_recv_fin(struct doq_conn* conn, struct doq_stream* stream, int
4219 	recv_done)
4220 {
4221 	if(!stream->is_query_complete && !recv_done) {
4222 		verbose(VERB_ALGO, "doq: stream recv FIN, but is "
4223 			"not complete, have %d of %d bytes",
4224 			((int)stream->nread)-2, (int)stream->inlen);
4225 		if(!doq_stream_close(conn, stream, 1))
4226 			return 0;
4227 	}
4228 	return 1;
4229 }
4230 
doq_fill_rand(struct ub_randstate * rnd,uint8_t * buf,size_t len)4231 void doq_fill_rand(struct ub_randstate* rnd, uint8_t* buf, size_t len)
4232 {
4233 	size_t i;
4234 	for(i=0; i<len; i++)
4235 		buf[i] = ub_random(rnd)&0xff;
4236 }
4237 
4238 /** generate new connection id, checks for duplicates.
4239  * caller must hold lock on conid tree. */
4240 static int
doq_conn_generate_new_conid(struct doq_conn * conn,uint8_t * data,size_t datalen)4241 doq_conn_generate_new_conid(struct doq_conn* conn, uint8_t* data,
4242 	size_t datalen)
4243 {
4244 	int max_try = 100;
4245 	int i;
4246 	for(i=0; i<max_try; i++) {
4247 		doq_fill_rand(conn->doq_socket->rnd, data, datalen);
4248 		if(!doq_conid_find(conn->table, data, datalen)) {
4249 			/* Found an unused connection id. */
4250 			return 1;
4251 		}
4252 	}
4253 	verbose(VERB_ALGO, "doq_conn_generate_new_conid failed: could not "
4254 		"generate random unused connection id value in %d attempts.",
4255 		max_try);
4256 	return 0;
4257 }
4258 
4259 /** ngtcp2 rand callback function */
4260 static void
doq_rand_cb(uint8_t * dest,size_t destlen,const ngtcp2_rand_ctx * rand_ctx)4261 doq_rand_cb(uint8_t* dest, size_t destlen, const ngtcp2_rand_ctx* rand_ctx)
4262 {
4263 	struct ub_randstate* rnd = (struct ub_randstate*)
4264 		rand_ctx->native_handle;
4265 	doq_fill_rand(rnd, dest, destlen);
4266 }
4267 
4268 /** ngtcp2 get_new_connection_id callback function */
4269 static int
doq_get_new_connection_id_cb(ngtcp2_conn * ATTR_UNUSED (conn),ngtcp2_cid * cid,uint8_t * token,size_t cidlen,void * user_data)4270 doq_get_new_connection_id_cb(ngtcp2_conn* ATTR_UNUSED(conn), ngtcp2_cid* cid,
4271 	uint8_t* token, size_t cidlen, void* user_data)
4272 {
4273 	struct doq_conn* doq_conn = (struct doq_conn*)user_data;
4274 	/* Lock the conid tree, so we can check for duplicates while
4275 	 * generating the id, and then insert it, whilst keeping the tree
4276 	 * locked against other modifications, guaranteeing uniqueness. */
4277 	lock_rw_wrlock(&doq_conn->table->conid_lock);
4278 	if(!doq_conn_generate_new_conid(doq_conn, cid->data, cidlen)) {
4279 		lock_rw_unlock(&doq_conn->table->conid_lock);
4280 		return NGTCP2_ERR_CALLBACK_FAILURE;
4281 	}
4282 	cid->datalen = cidlen;
4283 	if(ngtcp2_crypto_generate_stateless_reset_token(token,
4284 		doq_conn->doq_socket->static_secret,
4285 		doq_conn->doq_socket->static_secret_len, cid) != 0) {
4286 		lock_rw_unlock(&doq_conn->table->conid_lock);
4287 		return NGTCP2_ERR_CALLBACK_FAILURE;
4288 	}
4289 	if(!doq_conn_associate_conid(doq_conn, cid->data, cid->datalen)) {
4290 		lock_rw_unlock(&doq_conn->table->conid_lock);
4291 		return NGTCP2_ERR_CALLBACK_FAILURE;
4292 	}
4293 	lock_rw_unlock(&doq_conn->table->conid_lock);
4294 	return 0;
4295 }
4296 
4297 /** ngtcp2 remove_connection_id callback function */
4298 static int
doq_remove_connection_id_cb(ngtcp2_conn * ATTR_UNUSED (conn),const ngtcp2_cid * cid,void * user_data)4299 doq_remove_connection_id_cb(ngtcp2_conn* ATTR_UNUSED(conn),
4300 	const ngtcp2_cid* cid, void* user_data)
4301 {
4302 	struct doq_conn* doq_conn = (struct doq_conn*)user_data;
4303 	lock_rw_wrlock(&doq_conn->table->conid_lock);
4304 	doq_conn_dissociate_conid(doq_conn, cid->data, cid->datalen);
4305 	lock_rw_unlock(&doq_conn->table->conid_lock);
4306 	return 0;
4307 }
4308 
4309 /** doq submit a new token */
4310 static int
doq_submit_new_token(struct doq_conn * conn)4311 doq_submit_new_token(struct doq_conn* conn)
4312 {
4313 	uint8_t token[NGTCP2_CRYPTO_MAX_REGULAR_TOKENLEN];
4314 	ngtcp2_ssize tokenlen;
4315 	int ret;
4316 	const ngtcp2_path* path = ngtcp2_conn_get_path(conn->conn);
4317 
4318 	tokenlen = ngtcp2_crypto_generate_regular_token(token,
4319 		conn->doq_socket->static_secret,
4320 		conn->doq_socket->static_secret_len, path->remote.addr,
4321 		path->remote.addrlen, doq_get_timestamp_nanosec());
4322 	if(tokenlen < 0) {
4323 		log_err("doq ngtcp2_crypto_generate_regular_token failed");
4324 		return 1;
4325 	}
4326 
4327 	verbose(VERB_ALGO, "doq submit new token");
4328 	ret = ngtcp2_conn_submit_new_token(conn->conn, token, tokenlen);
4329 	if(ret != 0) {
4330 		log_err("doq ngtcp2_conn_submit_new_token failed: %s",
4331 			ngtcp2_strerror(ret));
4332 		return 0;
4333 	}
4334 	return 1;
4335 }
4336 
4337 /** ngtcp2 handshake_completed callback function */
4338 static int
doq_handshake_completed_cb(ngtcp2_conn * ATTR_UNUSED (conn),void * user_data)4339 doq_handshake_completed_cb(ngtcp2_conn* ATTR_UNUSED(conn), void* user_data)
4340 {
4341 	struct doq_conn* doq_conn = (struct doq_conn*)user_data;
4342 	verbose(VERB_ALGO, "doq handshake_completed callback");
4343 	verbose(VERB_ALGO, "ngtcp2_conn_get_max_data_left is %d",
4344 		(int)ngtcp2_conn_get_max_data_left(doq_conn->conn));
4345 #ifdef HAVE_NGTCP2_CONN_GET_MAX_LOCAL_STREAMS_UNI
4346 	verbose(VERB_ALGO, "ngtcp2_conn_get_max_local_streams_uni is %d",
4347 		(int)ngtcp2_conn_get_max_local_streams_uni(doq_conn->conn));
4348 #endif
4349 	verbose(VERB_ALGO, "ngtcp2_conn_get_streams_uni_left is %d",
4350 		(int)ngtcp2_conn_get_streams_uni_left(doq_conn->conn));
4351 	verbose(VERB_ALGO, "ngtcp2_conn_get_streams_bidi_left is %d",
4352 		(int)ngtcp2_conn_get_streams_bidi_left(doq_conn->conn));
4353 	verbose(VERB_ALGO, "negotiated cipher name is %s",
4354 		SSL_get_cipher_name(doq_conn->ssl));
4355 	if(verbosity > VERB_ALGO) {
4356 		const unsigned char* alpn = NULL;
4357 		unsigned int alpnlen = 0;
4358 		char alpnstr[128];
4359 		SSL_get0_alpn_selected(doq_conn->ssl, &alpn, &alpnlen);
4360 		if(alpnlen > sizeof(alpnstr)-1)
4361 			alpnlen = sizeof(alpnstr)-1;
4362 		memmove(alpnstr, alpn, alpnlen);
4363 		alpnstr[alpnlen]=0;
4364 		verbose(VERB_ALGO, "negotiated ALPN is '%s'", alpnstr);
4365 	}
4366 
4367 	if(!doq_submit_new_token(doq_conn))
4368 		return -1;
4369 	return 0;
4370 }
4371 
4372 /** ngtcp2 stream_open callback function */
4373 static int
doq_stream_open_cb(ngtcp2_conn * ATTR_UNUSED (conn),int64_t stream_id,void * user_data)4374 doq_stream_open_cb(ngtcp2_conn* ATTR_UNUSED(conn), int64_t stream_id,
4375 	void* user_data)
4376 {
4377 	struct doq_conn* doq_conn = (struct doq_conn*)user_data;
4378 	struct doq_stream* stream;
4379 	verbose(VERB_ALGO, "doq new stream %x", (int)stream_id);
4380 	if(doq_stream_find(doq_conn, stream_id)) {
4381 		verbose(VERB_ALGO, "doq: stream with this id already exists");
4382 		return 0;
4383 	}
4384 	if(!doq_table_quic_size_available(doq_conn->doq_socket->table,
4385 		doq_conn->doq_socket->cfg, sizeof(*stream)
4386 		+ 100 /* estimated query in */
4387 		+ 512 /* estimated response out */
4388 		)) {
4389 		int rv;
4390 		verbose(VERB_ALGO, "doq: no mem for new stream");
4391 		rv = ngtcp2_conn_shutdown_stream(doq_conn->conn,
4392 #ifdef HAVE_NGTCP2_CONN_SHUTDOWN_STREAM4
4393 			0,
4394 #endif
4395 			stream_id, NGTCP2_CONNECTION_REFUSED);
4396 		if(rv != 0) {
4397 			log_err("ngtcp2_conn_shutdown_stream failed: %s",
4398 				ngtcp2_strerror(rv));
4399 			return NGTCP2_ERR_CALLBACK_FAILURE;
4400 		}
4401 		return 0;
4402 	}
4403 	stream = doq_stream_create(stream_id);
4404 	if(!stream) {
4405 		log_err("doq: could not doq_stream_create: out of memory");
4406 		return NGTCP2_ERR_CALLBACK_FAILURE;
4407 	}
4408 	doq_table_quic_size_add(doq_conn->doq_socket->table, sizeof(*stream));
4409 	doq_conn_add_stream(doq_conn, stream);
4410 	return 0;
4411 }
4412 
4413 /** ngtcp2 recv_stream_data callback function */
4414 static int
doq_recv_stream_data_cb(ngtcp2_conn * ATTR_UNUSED (conn),uint32_t flags,int64_t stream_id,uint64_t offset,const uint8_t * data,size_t datalen,void * user_data,void * ATTR_UNUSED (stream_user_data))4415 doq_recv_stream_data_cb(ngtcp2_conn* ATTR_UNUSED(conn), uint32_t flags,
4416 	int64_t stream_id, uint64_t offset, const uint8_t* data,
4417 	size_t datalen, void* user_data, void* ATTR_UNUSED(stream_user_data))
4418 {
4419 	int recv_done = 0;
4420 	struct doq_conn* doq_conn = (struct doq_conn*)user_data;
4421 	struct doq_stream* stream;
4422 	verbose(VERB_ALGO, "doq recv stream data stream id %d offset %d "
4423 		"datalen %d%s%s", (int)stream_id, (int)offset, (int)datalen,
4424 		((flags&NGTCP2_STREAM_DATA_FLAG_FIN)!=0?" FIN":""),
4425 #ifdef NGTCP2_STREAM_DATA_FLAG_0RTT
4426 		((flags&NGTCP2_STREAM_DATA_FLAG_0RTT)!=0?" 0RTT":"")
4427 #else
4428 		((flags&NGTCP2_STREAM_DATA_FLAG_EARLY)!=0?" EARLY":"")
4429 #endif
4430 		);
4431 	stream = doq_stream_find(doq_conn, stream_id);
4432 	if(!stream) {
4433 		verbose(VERB_ALGO, "doq: received stream data for "
4434 			"unknown stream %d", (int)stream_id);
4435 		return 0;
4436 	}
4437 	if(stream->is_closed) {
4438 		verbose(VERB_ALGO, "doq: stream is closed, ignore recv data");
4439 		return 0;
4440 	}
4441 	if(datalen != 0) {
4442 		if(!doq_stream_recv_data(doq_conn, stream, data, datalen,
4443 			&recv_done, doq_conn->doq_socket->table))
4444 			return NGTCP2_ERR_CALLBACK_FAILURE;
4445 	}
4446 	if((flags&NGTCP2_STREAM_DATA_FLAG_FIN)!=0) {
4447 		if(!doq_stream_recv_fin(doq_conn, stream, recv_done))
4448 			return NGTCP2_ERR_CALLBACK_FAILURE;
4449 	}
4450 	ngtcp2_conn_extend_max_stream_offset(doq_conn->conn, stream_id,
4451 		datalen);
4452 	ngtcp2_conn_extend_max_offset(doq_conn->conn, datalen);
4453 	if(recv_done) {
4454 		if(!doq_stream_data_complete(doq_conn, stream))
4455 			return NGTCP2_ERR_CALLBACK_FAILURE;
4456 	}
4457 	return 0;
4458 }
4459 
4460 /** ngtcp2 stream_close callback function */
4461 static int
doq_stream_close_cb(ngtcp2_conn * ATTR_UNUSED (conn),uint32_t flags,int64_t stream_id,uint64_t app_error_code,void * user_data,void * ATTR_UNUSED (stream_user_data))4462 doq_stream_close_cb(ngtcp2_conn* ATTR_UNUSED(conn), uint32_t flags,
4463 	int64_t stream_id, uint64_t app_error_code, void* user_data,
4464 	void* ATTR_UNUSED(stream_user_data))
4465 {
4466 	struct doq_conn* doq_conn = (struct doq_conn*)user_data;
4467 	struct doq_stream* stream;
4468 	if((flags&NGTCP2_STREAM_CLOSE_FLAG_APP_ERROR_CODE_SET)!=0)
4469 		verbose(VERB_ALGO, "doq stream close for stream id %d %sapp_error_code %d",
4470 		(int)stream_id,
4471 		(((flags&NGTCP2_STREAM_CLOSE_FLAG_APP_ERROR_CODE_SET)!=0)?
4472 		"APP_ERROR_CODE_SET ":""),
4473 		(int)app_error_code);
4474 	else
4475 		verbose(VERB_ALGO, "doq stream close for stream id %d",
4476 			(int)stream_id);
4477 
4478 	stream = doq_stream_find(doq_conn, stream_id);
4479 	if(!stream) {
4480 		verbose(VERB_ALGO, "doq: stream close for "
4481 			"unknown stream %d", (int)stream_id);
4482 		return 0;
4483 	}
4484 	if(!doq_stream_close(doq_conn, stream, 0))
4485 		return NGTCP2_ERR_CALLBACK_FAILURE;
4486 	return 0;
4487 }
4488 
4489 /** ngtcp2 stream_reset callback function */
4490 static int
doq_stream_reset_cb(ngtcp2_conn * ATTR_UNUSED (conn),int64_t stream_id,uint64_t final_size,uint64_t app_error_code,void * user_data,void * ATTR_UNUSED (stream_user_data))4491 doq_stream_reset_cb(ngtcp2_conn* ATTR_UNUSED(conn), int64_t stream_id,
4492 	uint64_t final_size, uint64_t app_error_code, void* user_data,
4493 	void* ATTR_UNUSED(stream_user_data))
4494 {
4495 	struct doq_conn* doq_conn = (struct doq_conn*)user_data;
4496 	struct doq_stream* stream;
4497 	verbose(VERB_ALGO, "doq stream reset for stream id %d final_size %d "
4498 		"app_error_code %d", (int)stream_id, (int)final_size,
4499 		(int)app_error_code);
4500 
4501 	stream = doq_stream_find(doq_conn, stream_id);
4502 	if(!stream) {
4503 		verbose(VERB_ALGO, "doq: stream reset for "
4504 			"unknown stream %d", (int)stream_id);
4505 		return 0;
4506 	}
4507 	if(!doq_stream_close(doq_conn, stream, 0))
4508 		return NGTCP2_ERR_CALLBACK_FAILURE;
4509 	return 0;
4510 }
4511 
4512 /** ngtcp2 extend_max_stream_data function */
doq_extend_max_stream_data_cb(ngtcp2_conn * ATTR_UNUSED (conn),int64_t stream_id,uint64_t max_data,void * user_data,void * ATTR_UNUSED (stream_user_data))4513 int doq_extend_max_stream_data_cb(ngtcp2_conn* ATTR_UNUSED(conn),
4514 	int64_t stream_id, uint64_t max_data, void* user_data,
4515 	void* ATTR_UNUSED(stream_user_data))
4516 {
4517 	struct doq_conn* doq_conn = (struct doq_conn*)user_data;
4518 	struct doq_stream* stream;
4519 	verbose(VERB_ALGO, "doq extend_max_stream_data stream id %d "
4520 		"max_data %d ", (int)stream_id, (int)max_data);
4521 	if(max_data == 0)
4522 		return 0;
4523 	stream = doq_stream_find(doq_conn, stream_id);
4524 	if(!stream) {
4525 		verbose(VERB_ALGO, "doq: unknown stream %d", (int)stream_id);
4526 		return 0;
4527 	}
4528 	if(!stream->is_answer_available)
4529 		return 0;
4530 	doq_stream_on_write_list(doq_conn, stream);
4531 	doq_conn_write_enable(doq_conn);
4532 	return 0;
4533 }
4534 
4535 /** ngtcp2 acked_stream_data_offset callback function */
4536 static int
doq_acked_stream_data_offset_cb(ngtcp2_conn * ATTR_UNUSED (conn),int64_t stream_id,uint64_t offset,uint64_t datalen,void * user_data,void * ATTR_UNUSED (stream_user_data))4537 doq_acked_stream_data_offset_cb(ngtcp2_conn* ATTR_UNUSED(conn),
4538 	int64_t stream_id, uint64_t offset, uint64_t datalen, void* user_data,
4539 	void* ATTR_UNUSED(stream_user_data))
4540 {
4541 	struct doq_conn* doq_conn = (struct doq_conn*)user_data;
4542 	struct doq_stream* stream;
4543 	verbose(VERB_ALGO, "doq stream acked data for stream id %d offset %d "
4544 		"datalen %d", (int)stream_id, (int)offset, (int)datalen);
4545 
4546 	stream = doq_stream_find(doq_conn, stream_id);
4547 	if(!stream) {
4548 		verbose(VERB_ALGO, "doq: stream acked data for "
4549 			"unknown stream %d", (int)stream_id);
4550 		return 0;
4551 	}
4552 	/* Acked the data from [offset .. offset+datalen). */
4553 	if(stream->is_closed)
4554 		return 0;
4555 	if(offset+datalen >= stream->outlen) {
4556 		doq_stream_remove_in_buffer(stream,
4557 			doq_conn->doq_socket->table);
4558 		doq_stream_remove_out_buffer(stream,
4559 			doq_conn->doq_socket->table);
4560 	}
4561 	return 0;
4562 }
4563 
4564 /** ngtc2p log_printf callback function */
4565 static void
doq_log_printf_cb(void * ATTR_UNUSED (user_data),const char * fmt,...)4566 doq_log_printf_cb(void* ATTR_UNUSED(user_data), const char* fmt, ...)
4567 {
4568 	char buf[1024];
4569 	va_list ap;
4570 	va_start(ap, fmt);
4571 	vsnprintf(buf, sizeof(buf), fmt, ap);
4572 	verbose(VERB_ALGO, "libngtcp2: %s", buf);
4573 	va_end(ap);
4574 }
4575 
4576 #ifdef MAKE_QUIC_METHOD
4577 /** the doq application tx key callback, false on failure */
4578 static int
doq_application_tx_key_cb(struct doq_conn * conn)4579 doq_application_tx_key_cb(struct doq_conn* conn)
4580 {
4581 	verbose(VERB_ALGO, "doq application tx key cb");
4582 	/* The server does not want to open streams to the client,
4583 	 * the client instead initiates by opening bidi streams. */
4584 	verbose(VERB_ALGO, "doq ngtcp2_conn_get_max_data_left is %d",
4585 		(int)ngtcp2_conn_get_max_data_left(conn->conn));
4586 #ifdef HAVE_NGTCP2_CONN_GET_MAX_LOCAL_STREAMS_UNI
4587 	verbose(VERB_ALGO, "doq ngtcp2_conn_get_max_local_streams_uni is %d",
4588 		(int)ngtcp2_conn_get_max_local_streams_uni(conn->conn));
4589 #endif
4590 	verbose(VERB_ALGO, "doq ngtcp2_conn_get_streams_uni_left is %d",
4591 		(int)ngtcp2_conn_get_streams_uni_left(conn->conn));
4592 	verbose(VERB_ALGO, "doq ngtcp2_conn_get_streams_bidi_left is %d",
4593 		(int)ngtcp2_conn_get_streams_bidi_left(conn->conn));
4594 	return 1;
4595 }
4596 
4597 /** quic_method set_encryption_secrets function */
4598 static int
doq_set_encryption_secrets(SSL * ssl,OSSL_ENCRYPTION_LEVEL ossl_level,const uint8_t * read_secret,const uint8_t * write_secret,size_t secret_len)4599 doq_set_encryption_secrets(SSL *ssl, OSSL_ENCRYPTION_LEVEL ossl_level,
4600 	const uint8_t *read_secret, const uint8_t *write_secret,
4601 	size_t secret_len)
4602 {
4603 	struct doq_conn* doq_conn = (struct doq_conn*)SSL_get_app_data(ssl);
4604 #ifdef HAVE_NGTCP2_ENCRYPTION_LEVEL
4605 	ngtcp2_encryption_level
4606 #else
4607 	ngtcp2_crypto_level
4608 #endif
4609 		level =
4610 #ifdef USE_NGTCP2_CRYPTO_OSSL
4611 		ngtcp2_crypto_ossl_from_ossl_encryption_level(ossl_level);
4612 #elif defined(HAVE_NGTCP2_CRYPTO_QUICTLS_FROM_OSSL_ENCRYPTION_LEVEL)
4613 		ngtcp2_crypto_quictls_from_ossl_encryption_level(ossl_level);
4614 #else
4615 		ngtcp2_crypto_openssl_from_ossl_encryption_level(ossl_level);
4616 #endif
4617 
4618 	if(read_secret) {
4619 		verbose(VERB_ALGO, "doq: ngtcp2_crypto_derive_and_install_rx_key for level %d ossl %d", (int)level, (int)ossl_level);
4620 		if(ngtcp2_crypto_derive_and_install_rx_key(doq_conn->conn,
4621 			NULL, NULL, NULL, level, read_secret, secret_len)
4622 			!= 0) {
4623 			log_err("ngtcp2_crypto_derive_and_install_rx_key "
4624 				"failed");
4625 			return 0;
4626 		}
4627 	}
4628 
4629 	if(write_secret) {
4630 		verbose(VERB_ALGO, "doq: ngtcp2_crypto_derive_and_install_tx_key for level %d ossl %d", (int)level, (int)ossl_level);
4631 		if(ngtcp2_crypto_derive_and_install_tx_key(doq_conn->conn,
4632 			NULL, NULL, NULL, level, write_secret, secret_len)
4633 			!= 0) {
4634 			log_err("ngtcp2_crypto_derive_and_install_tx_key "
4635 				"failed");
4636 			return 0;
4637 		}
4638 		if(level == NGTCP2_CRYPTO_LEVEL_APPLICATION) {
4639 			if(!doq_application_tx_key_cb(doq_conn))
4640 				return 0;
4641 		}
4642 	}
4643 	return 1;
4644 }
4645 
4646 /** quic_method add_handshake_data function */
4647 static int
doq_add_handshake_data(SSL * ssl,OSSL_ENCRYPTION_LEVEL ossl_level,const uint8_t * data,size_t len)4648 doq_add_handshake_data(SSL *ssl, OSSL_ENCRYPTION_LEVEL ossl_level,
4649 	const uint8_t *data, size_t len)
4650 {
4651 	struct doq_conn* doq_conn = (struct doq_conn*)SSL_get_app_data(ssl);
4652 #ifdef HAVE_NGTCP2_ENCRYPTION_LEVEL
4653 	ngtcp2_encryption_level
4654 #else
4655 	ngtcp2_crypto_level
4656 #endif
4657 		level =
4658 #ifdef USE_NGTCP2_CRYPTO_OSSL
4659 		ngtcp2_crypto_ossl_from_ossl_encryption_level(ossl_level);
4660 #elif defined(HAVE_NGTCP2_CRYPTO_QUICTLS_FROM_OSSL_ENCRYPTION_LEVEL)
4661 		ngtcp2_crypto_quictls_from_ossl_encryption_level(ossl_level);
4662 #else
4663 		ngtcp2_crypto_openssl_from_ossl_encryption_level(ossl_level);
4664 #endif
4665 	int rv;
4666 
4667 	verbose(VERB_ALGO, "doq_add_handshake_data: "
4668 		"ngtcp2_con_submit_crypto_data level %d", (int)level);
4669 	rv = ngtcp2_conn_submit_crypto_data(doq_conn->conn, level, data, len);
4670 	if(rv != 0) {
4671 		log_err("ngtcp2_conn_submit_crypto_data failed: %s",
4672 			ngtcp2_strerror(rv));
4673 		ngtcp2_conn_set_tls_error(doq_conn->conn, rv);
4674 		return 0;
4675 	}
4676 	return 1;
4677 }
4678 
4679 /** quic_method flush_flight function */
4680 static int
doq_flush_flight(SSL * ATTR_UNUSED (ssl))4681 doq_flush_flight(SSL* ATTR_UNUSED(ssl))
4682 {
4683 	return 1;
4684 }
4685 
4686 /** quic_method send_alert function */
4687 static int
doq_send_alert(SSL * ssl,enum ssl_encryption_level_t ATTR_UNUSED (level),uint8_t alert)4688 doq_send_alert(SSL *ssl, enum ssl_encryption_level_t ATTR_UNUSED(level),
4689 	uint8_t alert)
4690 {
4691 	struct doq_conn* doq_conn = (struct doq_conn*)SSL_get_app_data(ssl);
4692 	doq_conn->tls_alert = alert;
4693 	return 1;
4694 }
4695 #endif /* MAKE_QUIC_METHOD */
4696 
4697 /** ALPN select callback for the doq SSL context */
4698 static int
doq_alpn_select_cb(SSL * ATTR_UNUSED (ssl),const unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * ATTR_UNUSED (arg))4699 doq_alpn_select_cb(SSL* ATTR_UNUSED(ssl), const unsigned char** out,
4700 	unsigned char* outlen, const unsigned char* in, unsigned int inlen,
4701 	void* ATTR_UNUSED(arg))
4702 {
4703 	/* select "doq" */
4704 	int ret = SSL_select_next_proto((void*)out, outlen,
4705 		(const unsigned char*)"\x03""doq", 4, in, inlen);
4706 	if(ret == OPENSSL_NPN_NEGOTIATED)
4707 		return SSL_TLSEXT_ERR_OK;
4708 	verbose(VERB_ALGO, "doq alpn_select_cb: ALPN from client does "
4709 		"not have 'doq'");
4710 	return SSL_TLSEXT_ERR_ALERT_FATAL;
4711 }
4712 
quic_sslctx_create(char * key,char * pem,char * verifypem)4713 void* quic_sslctx_create(char* key, char* pem, char* verifypem)
4714 {
4715 #ifdef HAVE_NGTCP2
4716 	char* sid_ctx = "unbound server";
4717 #ifdef MAKE_QUIC_METHOD
4718 	SSL_QUIC_METHOD* quic_method;
4719 #endif
4720 	SSL_CTX* ctx = SSL_CTX_new(TLS_server_method());
4721 	if(!ctx) {
4722 		log_crypto_err("Could not SSL_CTX_new");
4723 		return NULL;
4724 	}
4725 	if(!key || key[0] == 0) {
4726 		log_err("doq: error, no tls-service-key file specified");
4727 		SSL_CTX_free(ctx);
4728 		return NULL;
4729 	}
4730 	if(!pem || pem[0] == 0) {
4731 		log_err("doq: error, no tls-service-pem file specified");
4732 		SSL_CTX_free(ctx);
4733 		return NULL;
4734 	}
4735 	SSL_CTX_set_options(ctx,
4736 		(SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
4737 		SSL_OP_SINGLE_ECDH_USE |
4738 		SSL_OP_CIPHER_SERVER_PREFERENCE |
4739 		SSL_OP_NO_ANTI_REPLAY);
4740 	SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
4741 	SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
4742 	SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
4743 #ifdef HAVE_SSL_CTX_SET_ALPN_SELECT_CB
4744 	SSL_CTX_set_alpn_select_cb(ctx, doq_alpn_select_cb, NULL);
4745 #endif
4746 	SSL_CTX_set_default_verify_paths(ctx);
4747 	if(!SSL_CTX_use_certificate_chain_file(ctx, pem)) {
4748 		log_err("doq: error for cert file: %s", pem);
4749 		log_crypto_err("doq: error in "
4750 			"SSL_CTX_use_certificate_chain_file");
4751 		SSL_CTX_free(ctx);
4752 		return NULL;
4753 	}
4754 	if(!SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM)) {
4755 		log_err("doq: error for private key file: %s", key);
4756 		log_crypto_err("doq: error in SSL_CTX_use_PrivateKey_file");
4757 		SSL_CTX_free(ctx);
4758 		return NULL;
4759 	}
4760 	if(!SSL_CTX_check_private_key(ctx)) {
4761 		log_err("doq: error for key file: %s", key);
4762 		log_crypto_err("doq: error in SSL_CTX_check_private_key");
4763 		SSL_CTX_free(ctx);
4764 		return NULL;
4765 	}
4766 	SSL_CTX_set_session_id_context(ctx, (void*)sid_ctx, strlen(sid_ctx));
4767 	if(verifypem && verifypem[0]) {
4768 		if(!SSL_CTX_load_verify_locations(ctx, verifypem, NULL)) {
4769 			log_err("doq: error for verify pem file: %s",
4770 				verifypem);
4771 			log_crypto_err("doq: error in "
4772 				"SSL_CTX_load_verify_locations");
4773 			SSL_CTX_free(ctx);
4774 			return NULL;
4775 		}
4776 		SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(
4777 			verifypem));
4778 		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER|
4779 			SSL_VERIFY_CLIENT_ONCE|
4780 			SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
4781 	}
4782 
4783 	SSL_CTX_set_max_early_data(ctx, 0xffffffff);
4784 #ifdef HAVE_NGTCP2_CRYPTO_QUICTLS_CONFIGURE_SERVER_CONTEXT
4785 	if(ngtcp2_crypto_quictls_configure_server_context(ctx) != 0) {
4786 		log_err("ngtcp2_crypto_quictls_configure_server_context failed");
4787 		SSL_CTX_free(ctx);
4788 		return NULL;
4789 	}
4790 #elif defined(MAKE_QUIC_METHOD)
4791 	/* The quic_method needs to remain valid during the SSL_CTX
4792 	 * lifetime, so we allocate it. It is freed with the
4793 	 * doq_server_socket. */
4794 	quic_method = calloc(1, sizeof(SSL_QUIC_METHOD));
4795 	if(!quic_method) {
4796 		log_err("calloc failed: out of memory");
4797 		SSL_CTX_free(ctx);
4798 		return NULL;
4799 	}
4800 	doq_socket->quic_method = quic_method;
4801 	quic_method->set_encryption_secrets = doq_set_encryption_secrets;
4802 	quic_method->add_handshake_data = doq_add_handshake_data;
4803 	quic_method->flush_flight = doq_flush_flight;
4804 	quic_method->send_alert = doq_send_alert;
4805 	SSL_CTX_set_quic_method(ctx, doq_socket->quic_method);
4806 #endif
4807 	return ctx;
4808 #else /* HAVE_NGTCP2 */
4809 	(void)key; (void)pem; (void)verifypem;
4810 	return NULL;
4811 #endif /* HAVE_NGTCP2 */
4812 }
4813 
4814 /** Get the ngtcp2_conn from ssl userdata of type ngtcp2_conn_ref */
doq_conn_ref_get_conn(ngtcp2_crypto_conn_ref * conn_ref)4815 static ngtcp2_conn* doq_conn_ref_get_conn(ngtcp2_crypto_conn_ref* conn_ref)
4816 {
4817 	struct doq_conn* conn = (struct doq_conn*)conn_ref->user_data;
4818 	return conn->conn;
4819 }
4820 
4821 /** create new SSL session for server connection */
4822 static SSL*
doq_ssl_server_setup(SSL_CTX * ctx,struct doq_conn * conn)4823 doq_ssl_server_setup(SSL_CTX* ctx, struct doq_conn* conn)
4824 {
4825 #ifdef USE_NGTCP2_CRYPTO_OSSL
4826 	int ret;
4827 #endif
4828 	SSL* ssl = SSL_new(ctx);
4829 	if(!ssl) {
4830 		log_crypto_err("doq: SSL_new failed");
4831 		return NULL;
4832 	}
4833 #ifdef USE_NGTCP2_CRYPTO_OSSL
4834 	if((ret=ngtcp2_crypto_ossl_ctx_new(&conn->ossl_ctx, NULL)) != 0) {
4835 		log_err("doq: ngtcp2_crypto_ossl_ctx_new failed: %s",
4836 			ngtcp2_strerror(ret));
4837 		SSL_free(ssl);
4838 		return NULL;
4839 	}
4840 	ngtcp2_crypto_ossl_ctx_set_ssl(conn->ossl_ctx, ssl);
4841 	if(ngtcp2_crypto_ossl_configure_server_session(ssl) != 0) {
4842 		log_err("doq: ngtcp2_crypto_ossl_configure_server_session failed");
4843 		SSL_free(ssl);
4844 		return NULL;
4845 	}
4846 #endif
4847 #if defined(USE_NGTCP2_CRYPTO_OSSL) || defined(HAVE_NGTCP2_CRYPTO_QUICTLS_CONFIGURE_SERVER_CONTEXT)
4848 	conn->conn_ref.get_conn = &doq_conn_ref_get_conn;
4849 	conn->conn_ref.user_data = conn;
4850 	SSL_set_app_data(ssl, &conn->conn_ref);
4851 #else
4852 	SSL_set_app_data(ssl, conn);
4853 #endif
4854 	SSL_set_accept_state(ssl);
4855 #ifdef HAVE_SSL_SET_QUIC_TLS_EARLY_DATA_ENABLED
4856 	SSL_set_quic_tls_early_data_enabled(ssl, 1);
4857 #else
4858 	SSL_set_quic_early_data_enabled(ssl, 1);
4859 #endif
4860 	return ssl;
4861 }
4862 
4863 int
doq_conn_setup(struct doq_conn * conn,uint8_t * scid,size_t scidlen,uint8_t * ocid,size_t ocidlen,const uint8_t * token,size_t tokenlen)4864 doq_conn_setup(struct doq_conn* conn, uint8_t* scid, size_t scidlen,
4865 	uint8_t* ocid, size_t ocidlen, const uint8_t* token, size_t tokenlen)
4866 {
4867 	int rv;
4868 	struct ngtcp2_cid dcid, sv_scid, scid_cid;
4869 	struct ngtcp2_path path;
4870 	struct ngtcp2_callbacks callbacks;
4871 	struct ngtcp2_settings settings;
4872 	struct ngtcp2_transport_params params;
4873 	memset(&dcid, 0, sizeof(dcid));
4874 	memset(&sv_scid, 0, sizeof(sv_scid));
4875 	memset(&scid_cid, 0, sizeof(scid_cid));
4876 	memset(&path, 0, sizeof(path));
4877 	memset(&callbacks, 0, sizeof(callbacks));
4878 	memset(&settings, 0, sizeof(settings));
4879 	memset(&params, 0, sizeof(params));
4880 
4881 	ngtcp2_cid_init(&scid_cid, scid, scidlen);
4882 	ngtcp2_cid_init(&dcid, conn->key.dcid, conn->key.dcidlen);
4883 
4884 	path.remote.addr = (struct sockaddr*)&conn->key.paddr.addr;
4885 	path.remote.addrlen = conn->key.paddr.addrlen;
4886 	path.local.addr = (struct sockaddr*)&conn->key.paddr.localaddr;
4887 	path.local.addrlen = conn->key.paddr.localaddrlen;
4888 
4889 	callbacks.recv_client_initial = ngtcp2_crypto_recv_client_initial_cb;
4890 	callbacks.recv_crypto_data = ngtcp2_crypto_recv_crypto_data_cb;
4891 	callbacks.encrypt = ngtcp2_crypto_encrypt_cb;
4892 	callbacks.decrypt = ngtcp2_crypto_decrypt_cb;
4893 	callbacks.hp_mask = ngtcp2_crypto_hp_mask;
4894 	callbacks.update_key = ngtcp2_crypto_update_key_cb;
4895 	callbacks.delete_crypto_aead_ctx =
4896 		ngtcp2_crypto_delete_crypto_aead_ctx_cb;
4897 	callbacks.delete_crypto_cipher_ctx =
4898 		ngtcp2_crypto_delete_crypto_cipher_ctx_cb;
4899 	callbacks.get_path_challenge_data =
4900 		ngtcp2_crypto_get_path_challenge_data_cb;
4901 	callbacks.version_negotiation = ngtcp2_crypto_version_negotiation_cb;
4902 	callbacks.rand = doq_rand_cb;
4903 	callbacks.get_new_connection_id = doq_get_new_connection_id_cb;
4904 	callbacks.remove_connection_id = doq_remove_connection_id_cb;
4905 	callbacks.handshake_completed = doq_handshake_completed_cb;
4906 	callbacks.stream_open = doq_stream_open_cb;
4907 	callbacks.stream_close = doq_stream_close_cb;
4908 	callbacks.stream_reset = doq_stream_reset_cb;
4909 	callbacks.extend_max_stream_data = doq_extend_max_stream_data_cb;
4910 	callbacks.acked_stream_data_offset = doq_acked_stream_data_offset_cb;
4911 	callbacks.recv_stream_data = doq_recv_stream_data_cb;
4912 
4913 	ngtcp2_settings_default(&settings);
4914 	if(verbosity >= VERB_ALGO) {
4915 		settings.log_printf = doq_log_printf_cb;
4916 	}
4917 	settings.rand_ctx.native_handle = conn->doq_socket->rnd;
4918 	settings.initial_ts = doq_get_timestamp_nanosec();
4919 	settings.max_stream_window = 6*1024*1024;
4920 	settings.max_window = 6*1024*1024;
4921 #ifdef HAVE_STRUCT_NGTCP2_SETTINGS_TOKENLEN
4922 	settings.token = (void*)token;
4923 	settings.tokenlen = tokenlen;
4924 #else
4925 	settings.token.base = (void*)token;
4926 	settings.token.len = tokenlen;
4927 #endif
4928 
4929 	ngtcp2_transport_params_default(&params);
4930 	params.max_idle_timeout = conn->doq_socket->idle_timeout;
4931 	params.active_connection_id_limit = 7;
4932 	params.initial_max_stream_data_bidi_local = 256*1024;
4933 	params.initial_max_stream_data_bidi_remote = 256*1024;
4934 	params.initial_max_data = 1024*1024;
4935 	/* DoQ uses bidi streams, so we allow 0 uni streams. */
4936 	params.initial_max_streams_uni = 0;
4937 	/* Initial max on number of bidi streams the remote end can open.
4938 	 * That is the number of queries it can make, at first. */
4939 	params.initial_max_streams_bidi = 10;
4940 	if(ocid) {
4941 		ngtcp2_cid_init(&params.original_dcid, ocid, ocidlen);
4942 		ngtcp2_cid_init(&params.retry_scid, conn->key.dcid,
4943 			conn->key.dcidlen);
4944 		params.retry_scid_present = 1;
4945 	} else {
4946 		ngtcp2_cid_init(&params.original_dcid, conn->key.dcid,
4947 			conn->key.dcidlen);
4948 	}
4949 #ifdef HAVE_STRUCT_NGTCP2_TRANSPORT_PARAMS_ORIGINAL_DCID_PRESENT
4950 	params.original_dcid_present = 1;
4951 #endif
4952 	doq_fill_rand(conn->doq_socket->rnd, params.stateless_reset_token,
4953 		sizeof(params.stateless_reset_token));
4954 	sv_scid.datalen = conn->doq_socket->sv_scidlen;
4955 	lock_rw_wrlock(&conn->table->conid_lock);
4956 	if(!doq_conn_generate_new_conid(conn, sv_scid.data, sv_scid.datalen)) {
4957 		lock_rw_unlock(&conn->table->conid_lock);
4958 		return 0;
4959 	}
4960 
4961 	rv = ngtcp2_conn_server_new(&conn->conn, &scid_cid, &sv_scid, &path,
4962 		conn->version, &callbacks, &settings, &params, NULL, conn);
4963 	if(rv != 0) {
4964 		conn->conn = NULL;
4965 		lock_rw_unlock(&conn->table->conid_lock);
4966 		log_err("ngtcp2_conn_server_new failed: %s",
4967 			ngtcp2_strerror(rv));
4968 		return 0;
4969 	}
4970 	if(!doq_conn_setup_conids(conn)) {
4971 		lock_rw_unlock(&conn->table->conid_lock);
4972 		log_err("doq_conn_setup_conids failed: out of memory");
4973 		return 0;
4974 	}
4975 	lock_rw_unlock(&conn->table->conid_lock);
4976 	conn->ssl = doq_ssl_server_setup((SSL_CTX*)conn->doq_socket->ctx,
4977 		conn);
4978 	if(!conn->ssl) {
4979 		log_err("doq_ssl_server_setup failed");
4980 		return 0;
4981 	}
4982 #ifdef USE_NGTCP2_CRYPTO_OSSL
4983 	ngtcp2_conn_set_tls_native_handle(conn->conn, conn->ossl_ctx);
4984 #else
4985 	ngtcp2_conn_set_tls_native_handle(conn->conn, conn->ssl);
4986 #endif
4987 	doq_conn_write_enable(conn);
4988 	return 1;
4989 }
4990 
4991 struct doq_conid*
doq_conid_find(struct doq_table * table,const uint8_t * data,size_t datalen)4992 doq_conid_find(struct doq_table* table, const uint8_t* data, size_t datalen)
4993 {
4994 	struct rbnode_type* node;
4995 	struct doq_conid key;
4996 	key.node.key = &key;
4997 	key.cid = (void*)data;
4998 	key.cidlen = datalen;
4999 	log_assert(table != NULL);
5000 	node = rbtree_search(table->conid_tree, &key);
5001 	if(node)
5002 		return (struct doq_conid*)node->key;
5003 	return NULL;
5004 }
5005 
5006 /** insert conid in the conid list */
5007 static void
doq_conid_list_insert(struct doq_conn * conn,struct doq_conid * conid)5008 doq_conid_list_insert(struct doq_conn* conn, struct doq_conid* conid)
5009 {
5010 	conid->prev = NULL;
5011 	conid->next = conn->conid_list;
5012 	if(conn->conid_list)
5013 		conn->conid_list->prev = conid;
5014 	conn->conid_list = conid;
5015 }
5016 
5017 /** remove conid from the conid list */
5018 static void
doq_conid_list_remove(struct doq_conn * conn,struct doq_conid * conid)5019 doq_conid_list_remove(struct doq_conn* conn, struct doq_conid* conid)
5020 {
5021 	if(conid->prev)
5022 		conid->prev->next = conid->next;
5023 	else	conn->conid_list = conid->next;
5024 	if(conid->next)
5025 		conid->next->prev = conid->prev;
5026 }
5027 
5028 /** create a doq_conid */
5029 static struct doq_conid*
doq_conid_create(uint8_t * data,size_t datalen,struct doq_conn_key * key)5030 doq_conid_create(uint8_t* data, size_t datalen, struct doq_conn_key* key)
5031 {
5032 	struct doq_conid* conid;
5033 	conid = calloc(1, sizeof(*conid));
5034 	if(!conid)
5035 		return NULL;
5036 	conid->cid = memdup(data, datalen);
5037 	if(!conid->cid) {
5038 		free(conid);
5039 		return NULL;
5040 	}
5041 	conid->cidlen = datalen;
5042 	conid->node.key = conid;
5043 	conid->key = *key;
5044 	conid->key.dcid = memdup(key->dcid, key->dcidlen);
5045 	if(!conid->key.dcid) {
5046 		free(conid->cid);
5047 		free(conid);
5048 		return NULL;
5049 	}
5050 	return conid;
5051 }
5052 
5053 void
doq_conid_delete(struct doq_conid * conid)5054 doq_conid_delete(struct doq_conid* conid)
5055 {
5056 	if(!conid)
5057 		return;
5058 	free(conid->key.dcid);
5059 	free(conid->cid);
5060 	free(conid);
5061 }
5062 
5063 /** return true if the conid is for the conn. */
5064 static int
conid_is_for_conn(struct doq_conn * conn,struct doq_conid * conid)5065 conid_is_for_conn(struct doq_conn* conn, struct doq_conid* conid)
5066 {
5067 	if(conid->key.dcidlen == conn->key.dcidlen &&
5068 		memcmp(conid->key.dcid, conn->key.dcid, conid->key.dcidlen)==0
5069 		&& conid->key.paddr.addrlen == conn->key.paddr.addrlen &&
5070 		memcmp(&conid->key.paddr.addr, &conn->key.paddr.addr,
5071 			conid->key.paddr.addrlen) == 0 &&
5072 		conid->key.paddr.localaddrlen == conn->key.paddr.localaddrlen &&
5073 		memcmp(&conid->key.paddr.localaddr, &conn->key.paddr.localaddr,
5074 			conid->key.paddr.localaddrlen) == 0 &&
5075 		conid->key.paddr.ifindex == conn->key.paddr.ifindex)
5076 		return 1;
5077 	return 0;
5078 }
5079 
5080 int
doq_conn_associate_conid(struct doq_conn * conn,uint8_t * data,size_t datalen)5081 doq_conn_associate_conid(struct doq_conn* conn, uint8_t* data, size_t datalen)
5082 {
5083 	struct doq_conid* conid;
5084 	conid = doq_conid_find(conn->table, data, datalen);
5085 	if(conid && !conid_is_for_conn(conn, conid)) {
5086 		verbose(VERB_ALGO, "doq connection id already exists for "
5087 			"another doq_conn. Ignoring second connection id.");
5088 		/* Already exists to another conn, ignore it.
5089 		 * This works, in that the conid is listed in the doq_conn
5090 		 * conid_list element, and removed from there. So our conid
5091 		 * tree and list are fine, when created and removed.
5092 		 * The tree now does not have the lookup element pointing
5093 		 * to this connection. */
5094 		return 1;
5095 	}
5096 	if(conid)
5097 		return 1; /* already inserted */
5098 	conid = doq_conid_create(data, datalen, &conn->key);
5099 	if(!conid)
5100 		return 0;
5101 	doq_conid_list_insert(conn, conid);
5102 	(void)rbtree_insert(conn->table->conid_tree, &conid->node);
5103 	return 1;
5104 }
5105 
5106 void
doq_conn_dissociate_conid(struct doq_conn * conn,const uint8_t * data,size_t datalen)5107 doq_conn_dissociate_conid(struct doq_conn* conn, const uint8_t* data,
5108 	size_t datalen)
5109 {
5110 	struct doq_conid* conid;
5111 	conid = doq_conid_find(conn->table, data, datalen);
5112 	if(conid && !conid_is_for_conn(conn, conid))
5113 		return;
5114 	if(conid) {
5115 		(void)rbtree_delete(conn->table->conid_tree,
5116 			conid->node.key);
5117 		doq_conid_list_remove(conn, conid);
5118 		doq_conid_delete(conid);
5119 	}
5120 }
5121 
5122 /** associate the scid array and also the dcid.
5123  * caller must hold the locks on conn and doq_table.conid_lock. */
5124 static int
doq_conn_setup_id_array_and_dcid(struct doq_conn * conn,struct ngtcp2_cid * scids,size_t num_scid)5125 doq_conn_setup_id_array_and_dcid(struct doq_conn* conn,
5126 	struct ngtcp2_cid* scids, size_t num_scid)
5127 {
5128 	size_t i;
5129 	for(i=0; i<num_scid; i++) {
5130 		if(!doq_conn_associate_conid(conn, scids[i].data,
5131 			scids[i].datalen))
5132 			return 0;
5133 	}
5134 	if(!doq_conn_associate_conid(conn, conn->key.dcid, conn->key.dcidlen))
5135 		return 0;
5136 	return 1;
5137 }
5138 
5139 int
doq_conn_setup_conids(struct doq_conn * conn)5140 doq_conn_setup_conids(struct doq_conn* conn)
5141 {
5142 	size_t num_scid =
5143 #ifndef HAVE_NGTCP2_CONN_GET_NUM_SCID
5144 		ngtcp2_conn_get_scid(conn->conn, NULL);
5145 #else
5146 		ngtcp2_conn_get_num_scid(conn->conn);
5147 #endif
5148 	if(num_scid <= 4) {
5149 		struct ngtcp2_cid ids[4];
5150 		/* Usually there are not that many scids when just accepted,
5151 		 * like only 2. */
5152 		ngtcp2_conn_get_scid(conn->conn, ids);
5153 		return doq_conn_setup_id_array_and_dcid(conn, ids, num_scid);
5154 	} else {
5155 		struct ngtcp2_cid *scids = calloc(num_scid,
5156 			sizeof(struct ngtcp2_cid));
5157 		if(!scids)
5158 			return 0;
5159 		ngtcp2_conn_get_scid(conn->conn, scids);
5160 		if(!doq_conn_setup_id_array_and_dcid(conn, scids, num_scid)) {
5161 			free(scids);
5162 			return 0;
5163 		}
5164 		free(scids);
5165 	}
5166 	return 1;
5167 }
5168 
5169 void
doq_conn_clear_conids(struct doq_conn * conn)5170 doq_conn_clear_conids(struct doq_conn* conn)
5171 {
5172 	struct doq_conid* p, *next;
5173 	if(!conn)
5174 		return;
5175 	p = conn->conid_list;
5176 	while(p) {
5177 		next = p->next;
5178 		(void)rbtree_delete(conn->table->conid_tree, p->node.key);
5179 		doq_conid_delete(p);
5180 		p = next;
5181 	}
5182 	conn->conid_list = NULL;
5183 }
5184 
doq_get_timestamp_nanosec(void)5185 ngtcp2_tstamp doq_get_timestamp_nanosec(void)
5186 {
5187 	struct timespec tp;
5188 	memset(&tp, 0, sizeof(tp));
5189 #ifdef CLOCK_BOOTTIME
5190 	if(clock_gettime(CLOCK_BOOTTIME, &tp) == -1) {
5191 #endif
5192 		if(clock_gettime(CLOCK_MONOTONIC, &tp) == -1) {
5193 			log_err("clock_gettime failed: %s", strerror(errno));
5194 		}
5195 #ifdef CLOCK_BOOTTIME
5196 	}
5197 #endif
5198 	return ((uint64_t)tp.tv_sec)*((uint64_t)1000000000) +
5199 		((uint64_t)tp.tv_nsec);
5200 }
5201 
doq_get_timevalue(void)5202 static struct timeval doq_get_timevalue(void)
5203 {
5204 	struct timeval tv;
5205 	memset(&tv, 0, sizeof(tv));
5206 	if(gettimeofday(&tv, NULL) < 0) {
5207 		log_err("gettimeofday failed: %s", strerror(errno));
5208 		memset(&tv, 0, sizeof(tv));
5209 	}
5210 	return tv;
5211 }
5212 
5213 /** doq start the closing period for the connection. */
5214 static int
doq_conn_start_closing_period(struct comm_point * c,struct doq_conn * conn)5215 doq_conn_start_closing_period(struct comm_point* c, struct doq_conn* conn)
5216 {
5217 	struct ngtcp2_path_storage ps;
5218 	struct ngtcp2_pkt_info pi;
5219 	ngtcp2_ssize ret;
5220 	if(!conn)
5221 		return 1;
5222 	if(
5223 #ifdef HAVE_NGTCP2_CONN_IN_CLOSING_PERIOD
5224 		ngtcp2_conn_in_closing_period(conn->conn)
5225 #else
5226 		ngtcp2_conn_is_in_closing_period(conn->conn)
5227 #endif
5228 		)
5229 		return 1;
5230 	if(
5231 #ifdef HAVE_NGTCP2_CONN_IN_DRAINING_PERIOD
5232 		ngtcp2_conn_in_draining_period(conn->conn)
5233 #else
5234 		ngtcp2_conn_is_in_draining_period(conn->conn)
5235 #endif
5236 		) {
5237 		doq_conn_write_disable(conn);
5238 		return 1;
5239 	}
5240 	ngtcp2_path_storage_zero(&ps);
5241 	sldns_buffer_clear(c->doq_socket->pkt_buf);
5242 	/* the call to ngtcp2_conn_write_connection_close causes the
5243 	 * conn to be closed. It is now in the closing period. */
5244 	ret = ngtcp2_conn_write_connection_close(conn->conn, &ps.path,
5245 		&pi, sldns_buffer_begin(c->doq_socket->pkt_buf),
5246 		sldns_buffer_remaining(c->doq_socket->pkt_buf),
5247 #ifdef HAVE_NGTCP2_CCERR_DEFAULT
5248 		&conn->ccerr
5249 #else
5250 		&conn->last_error
5251 #endif
5252 		, doq_get_timestamp_nanosec());
5253 	if(ret < 0) {
5254 		log_err("doq ngtcp2_conn_write_connection_close failed: %s",
5255 			ngtcp2_strerror(ret));
5256 		return 0;
5257 	}
5258 	if(ret == 0) {
5259 		return 0;
5260 	}
5261 	sldns_buffer_set_position(c->doq_socket->pkt_buf, ret);
5262 	sldns_buffer_flip(c->doq_socket->pkt_buf);
5263 
5264 	/* The close packet is allocated, because it may have to be repeated.
5265 	 * When incoming packets have this connection dcid. */
5266 	conn->close_pkt = memdup(sldns_buffer_begin(c->doq_socket->pkt_buf),
5267 		sldns_buffer_limit(c->doq_socket->pkt_buf));
5268 	if(!conn->close_pkt) {
5269 		log_err("doq: could not allocate close packet: out of memory");
5270 		return 0;
5271 	}
5272 	conn->close_pkt_len = sldns_buffer_limit(c->doq_socket->pkt_buf);
5273 	conn->close_ecn = pi.ecn;
5274 	return 1;
5275 }
5276 
5277 /** doq send the close packet for the connection, perhaps again. */
5278 int
doq_conn_send_close(struct comm_point * c,struct doq_conn * conn)5279 doq_conn_send_close(struct comm_point* c, struct doq_conn* conn)
5280 {
5281 	if(!conn)
5282 		return 0;
5283 	if(!conn->close_pkt)
5284 		return 0;
5285 	if(conn->close_pkt_len > sldns_buffer_capacity(c->doq_socket->pkt_buf))
5286 		return 0;
5287 	sldns_buffer_clear(c->doq_socket->pkt_buf);
5288 	sldns_buffer_write(c->doq_socket->pkt_buf, conn->close_pkt, conn->close_pkt_len);
5289 	sldns_buffer_flip(c->doq_socket->pkt_buf);
5290 	verbose(VERB_ALGO, "doq send connection close");
5291 	doq_send_pkt(c, &conn->key.paddr, conn->close_ecn);
5292 	doq_conn_write_disable(conn);
5293 	return 1;
5294 }
5295 
5296 /** doq close the connection on error. If it returns a failure, it
5297  * does not wait to send a close, and the connection can be dropped. */
5298 static int
doq_conn_close_error(struct comm_point * c,struct doq_conn * conn)5299 doq_conn_close_error(struct comm_point* c, struct doq_conn* conn)
5300 {
5301 #ifdef HAVE_NGTCP2_CCERR_DEFAULT
5302 	if(conn->ccerr.type == NGTCP2_CCERR_TYPE_IDLE_CLOSE)
5303 		return 0;
5304 #else
5305 	if(conn->last_error.type ==
5306 		NGTCP2_CONNECTION_CLOSE_ERROR_CODE_TYPE_TRANSPORT_IDLE_CLOSE)
5307 		return 0;
5308 #endif
5309 	if(!doq_conn_start_closing_period(c, conn))
5310 		return 0;
5311 	if(
5312 #ifdef HAVE_NGTCP2_CONN_IN_DRAINING_PERIOD
5313 		ngtcp2_conn_in_draining_period(conn->conn)
5314 #else
5315 		ngtcp2_conn_is_in_draining_period(conn->conn)
5316 #endif
5317 		) {
5318 		doq_conn_write_disable(conn);
5319 		return 1;
5320 	}
5321 	doq_conn_write_enable(conn);
5322 	if(!doq_conn_send_close(c, conn))
5323 		return 0;
5324 	return 1;
5325 }
5326 
5327 int
doq_conn_recv(struct comm_point * c,struct doq_pkt_addr * paddr,struct doq_conn * conn,struct ngtcp2_pkt_info * pi,int * err_retry,int * err_drop)5328 doq_conn_recv(struct comm_point* c, struct doq_pkt_addr* paddr,
5329 	struct doq_conn* conn, struct ngtcp2_pkt_info* pi, int* err_retry,
5330 	int* err_drop)
5331 {
5332 	int ret;
5333 	struct ngtcp2_path path;
5334 	memset(&path, 0, sizeof(path));
5335 	path.remote.addr = (struct sockaddr*)&paddr->addr;
5336 	path.remote.addrlen = paddr->addrlen;
5337 	path.local.addr = (struct sockaddr*)&paddr->localaddr;
5338 	path.local.addrlen = paddr->localaddrlen;
5339 
5340 	ret = ngtcp2_conn_read_pkt(conn->conn, &path, pi,
5341 		sldns_buffer_begin(c->doq_socket->pkt_buf),
5342 		sldns_buffer_limit(c->doq_socket->pkt_buf),
5343 		doq_get_timestamp_nanosec());
5344 	if(ret != 0) {
5345 		if(err_retry)
5346 			*err_retry = 0;
5347 		if(err_drop)
5348 			*err_drop = 0;
5349 		if(ret == NGTCP2_ERR_DRAINING) {
5350 			verbose(VERB_ALGO, "ngtcp2_conn_read_pkt returned %s",
5351 				ngtcp2_strerror(ret));
5352 			doq_conn_write_disable(conn);
5353 			return 0;
5354 		} else if(ret == NGTCP2_ERR_DROP_CONN) {
5355 			verbose(VERB_ALGO, "ngtcp2_conn_read_pkt returned %s",
5356 				ngtcp2_strerror(ret));
5357 			if(err_drop)
5358 				*err_drop = 1;
5359 			return 0;
5360 		} else if(ret == NGTCP2_ERR_RETRY) {
5361 			verbose(VERB_ALGO, "ngtcp2_conn_read_pkt returned %s",
5362 				ngtcp2_strerror(ret));
5363 			if(err_retry)
5364 				*err_retry = 1;
5365 			if(err_drop)
5366 				*err_drop = 1;
5367 			return 0;
5368 		} else if(ret == NGTCP2_ERR_CRYPTO) {
5369 			if(
5370 #ifdef HAVE_NGTCP2_CCERR_DEFAULT
5371 				!conn->ccerr.error_code
5372 #else
5373 				!conn->last_error.error_code
5374 #endif
5375 				) {
5376 				/* in picotls the tls alert may need to be
5377 				 * copied, but this is with openssl. And there
5378 				 * is conn->tls_alert. */
5379 #ifdef HAVE_NGTCP2_CCERR_DEFAULT
5380 				ngtcp2_ccerr_set_tls_alert(&conn->ccerr,
5381 					conn->tls_alert, NULL, 0);
5382 #else
5383 				ngtcp2_connection_close_error_set_transport_error_tls_alert(
5384 					&conn->last_error, conn->tls_alert,
5385 					NULL, 0);
5386 #endif
5387 			}
5388 		} else {
5389 			if(
5390 #ifdef HAVE_NGTCP2_CCERR_DEFAULT
5391 				!conn->ccerr.error_code
5392 #else
5393 				!conn->last_error.error_code
5394 #endif
5395 				) {
5396 #ifdef HAVE_NGTCP2_CCERR_DEFAULT
5397 				ngtcp2_ccerr_set_liberr(&conn->ccerr, ret,
5398 					NULL, 0);
5399 #else
5400 				ngtcp2_connection_close_error_set_transport_error_liberr(
5401 					&conn->last_error, ret, NULL, 0);
5402 #endif
5403 			}
5404 		}
5405 		log_err("ngtcp2_conn_read_pkt failed: %s",
5406 			ngtcp2_strerror(ret));
5407 		if(!doq_conn_close_error(c, conn)) {
5408 			if(err_drop)
5409 				*err_drop = 1;
5410 		}
5411 		return 0;
5412 	}
5413 	doq_conn_write_enable(conn);
5414 	return 1;
5415 }
5416 
5417 /** doq stream write is done */
5418 static void
doq_stream_write_is_done(struct doq_conn * conn,struct doq_stream * stream)5419 doq_stream_write_is_done(struct doq_conn* conn, struct doq_stream* stream)
5420 {
5421 	/* Cannot deallocate, the buffer may be needed for resends. */
5422 	doq_stream_off_write_list(conn, stream);
5423 }
5424 
5425 int
doq_conn_write_streams(struct comm_point * c,struct doq_conn * conn,int * err_drop)5426 doq_conn_write_streams(struct comm_point* c, struct doq_conn* conn,
5427 	int* err_drop)
5428 {
5429 	struct doq_stream* stream = conn->stream_write_first;
5430 	ngtcp2_path_storage ps;
5431 	size_t num_packets = 0, max_packets = 65535;
5432 	ngtcp2_path_storage_zero(&ps);
5433 
5434 	for(;;) {
5435 		int64_t stream_id;
5436 		uint32_t flags = 0;
5437 		ngtcp2_pkt_info pi;
5438 		ngtcp2_vec datav[2];
5439 		size_t datav_count = 0;
5440 		ngtcp2_ssize ret, ndatalen = 0;
5441 		int fin;
5442 
5443 		if(stream) {
5444 			/* data to send */
5445 			verbose(VERB_ALGO, "doq: doq_conn write stream %d",
5446 				(int)stream->stream_id);
5447 			stream_id = stream->stream_id;
5448 			fin = 1;
5449 			if(stream->nwrite < 2) {
5450 				datav[0].base = ((uint8_t*)&stream->
5451 					outlen_wire) + stream->nwrite;
5452 				datav[0].len = 2 - stream->nwrite;
5453 				datav[1].base = stream->out;
5454 				datav[1].len = stream->outlen;
5455 				datav_count = 2;
5456 			} else {
5457 				datav[0].base = stream->out +
5458 					(stream->nwrite-2);
5459 				datav[0].len = stream->outlen -
5460 					(stream->nwrite-2);
5461 				datav_count = 1;
5462 			}
5463 		} else {
5464 			/* no data to send */
5465 			verbose(VERB_ALGO, "doq: doq_conn write stream -1");
5466 			stream_id = -1;
5467 			fin = 0;
5468 			datav[0].base = NULL;
5469 			datav[0].len = 0;
5470 			datav_count = 1;
5471 		}
5472 
5473 		/* if more streams, set it to write more */
5474 		if(stream && stream->write_next)
5475 			flags |= NGTCP2_WRITE_STREAM_FLAG_MORE;
5476 		if(fin)
5477 			flags |= NGTCP2_WRITE_STREAM_FLAG_FIN;
5478 
5479 		sldns_buffer_clear(c->doq_socket->pkt_buf);
5480 		ret = ngtcp2_conn_writev_stream(conn->conn, &ps.path, &pi,
5481 			sldns_buffer_begin(c->doq_socket->pkt_buf),
5482 			sldns_buffer_remaining(c->doq_socket->pkt_buf),
5483 			&ndatalen, flags, stream_id, datav, datav_count,
5484 			doq_get_timestamp_nanosec());
5485 		if(ret < 0) {
5486 			if(ret == NGTCP2_ERR_WRITE_MORE) {
5487 				verbose(VERB_ALGO, "doq: write more, ndatalen %d", (int)ndatalen);
5488 				if(stream) {
5489 					if(ndatalen >= 0)
5490 						stream->nwrite += ndatalen;
5491 					if(stream->nwrite >= stream->outlen+2)
5492 						doq_stream_write_is_done(
5493 							conn, stream);
5494 					stream = stream->write_next;
5495 				}
5496 				continue;
5497 			} else if(ret == NGTCP2_ERR_STREAM_DATA_BLOCKED) {
5498 				verbose(VERB_ALGO, "doq: ngtcp2_conn_writev_stream returned NGTCP2_ERR_STREAM_DATA_BLOCKED");
5499 				if(stream) {
5500 					doq_stream_off_write_list(conn, stream);
5501 					stream = stream->write_next;
5502 					continue;
5503 				} else {
5504 					break;
5505 				}
5506 			} else if(ret == NGTCP2_ERR_STREAM_SHUT_WR) {
5507 				verbose(VERB_ALGO, "doq: ngtcp2_conn_writev_stream returned NGTCP2_ERR_STREAM_SHUT_WR");
5508 #ifdef HAVE_NGTCP2_CCERR_DEFAULT
5509 				ngtcp2_ccerr_set_application_error(
5510 					&conn->ccerr, DOQ_APP_ERROR_CODE, NULL, 0);
5511 #else
5512 				ngtcp2_connection_close_error_set_application_error(&conn->last_error, DOQ_APP_ERROR_CODE, NULL, 0);
5513 #endif
5514 				if(err_drop)
5515 					*err_drop = 0;
5516 				if(!doq_conn_close_error(c, conn)) {
5517 					if(err_drop)
5518 						*err_drop = 1;
5519 				}
5520 				return 0;
5521 			}
5522 
5523 			log_err("doq: ngtcp2_conn_writev_stream failed: %s",
5524 				ngtcp2_strerror(ret));
5525 #ifdef HAVE_NGTCP2_CCERR_DEFAULT
5526 			ngtcp2_ccerr_set_liberr(&conn->ccerr, ret, NULL, 0);
5527 #else
5528 			ngtcp2_connection_close_error_set_transport_error_liberr(
5529 				&conn->last_error, ret, NULL, 0);
5530 #endif
5531 			if(err_drop)
5532 				*err_drop = 0;
5533 			if(!doq_conn_close_error(c, conn)) {
5534 				if(err_drop)
5535 					*err_drop = 1;
5536 			}
5537 			return 0;
5538 		}
5539 		verbose(VERB_ALGO, "doq: writev_stream pkt size %d ndatawritten %d",
5540 			(int)ret, (int)ndatalen);
5541 
5542 		if(ndatalen >= 0 && stream) {
5543 			stream->nwrite += ndatalen;
5544 			if(stream->nwrite >= stream->outlen+2)
5545 				doq_stream_write_is_done(conn, stream);
5546 		}
5547 		if(ret == 0) {
5548 			/* congestion limited */
5549 			doq_conn_write_disable(conn);
5550 			ngtcp2_conn_update_pkt_tx_time(conn->conn,
5551 				doq_get_timestamp_nanosec());
5552 			return 1;
5553 		}
5554 		sldns_buffer_set_position(c->doq_socket->pkt_buf, ret);
5555 		sldns_buffer_flip(c->doq_socket->pkt_buf);
5556 		doq_send_pkt(c, &conn->key.paddr, pi.ecn);
5557 
5558 		if(c->doq_socket->have_blocked_pkt)
5559 			break;
5560 		if(++num_packets == max_packets)
5561 			break;
5562 		if(stream)
5563 			stream = stream->write_next;
5564 	}
5565 	ngtcp2_conn_update_pkt_tx_time(conn->conn, doq_get_timestamp_nanosec());
5566 	return 1;
5567 }
5568 
5569 void
doq_conn_write_enable(struct doq_conn * conn)5570 doq_conn_write_enable(struct doq_conn* conn)
5571 {
5572 	conn->write_interest = 1;
5573 }
5574 
5575 void
doq_conn_write_disable(struct doq_conn * conn)5576 doq_conn_write_disable(struct doq_conn* conn)
5577 {
5578 	conn->write_interest = 0;
5579 }
5580 
5581 /** doq append the connection to the write list */
5582 static void
doq_conn_write_list_append(struct doq_table * table,struct doq_conn * conn)5583 doq_conn_write_list_append(struct doq_table* table, struct doq_conn* conn)
5584 {
5585 	if(conn->on_write_list)
5586 		return;
5587 	conn->write_prev = table->write_list_last;
5588 	if(table->write_list_last)
5589 		table->write_list_last->write_next = conn;
5590 	else table->write_list_first = conn;
5591 	conn->write_next = NULL;
5592 	table->write_list_last = conn;
5593 	conn->on_write_list = 1;
5594 }
5595 
5596 void
doq_conn_write_list_remove(struct doq_table * table,struct doq_conn * conn)5597 doq_conn_write_list_remove(struct doq_table* table, struct doq_conn* conn)
5598 {
5599 	if(!conn->on_write_list)
5600 		return;
5601 	if(conn->write_next)
5602 		conn->write_next->write_prev = conn->write_prev;
5603 	else table->write_list_last = conn->write_prev;
5604 	if(conn->write_prev)
5605 		conn->write_prev->write_next = conn->write_next;
5606 	else table->write_list_first = conn->write_next;
5607 	conn->write_prev = NULL;
5608 	conn->write_next = NULL;
5609 	conn->on_write_list = 0;
5610 }
5611 
5612 void
doq_conn_set_write_list(struct doq_table * table,struct doq_conn * conn)5613 doq_conn_set_write_list(struct doq_table* table, struct doq_conn* conn)
5614 {
5615 	if(conn->write_interest && conn->on_write_list)
5616 		return;
5617 	if(!conn->write_interest && !conn->on_write_list)
5618 		return;
5619 	if(conn->write_interest)
5620 		doq_conn_write_list_append(table, conn);
5621 	else doq_conn_write_list_remove(table, conn);
5622 }
5623 
5624 struct doq_conn*
doq_table_pop_first(struct doq_table * table)5625 doq_table_pop_first(struct doq_table* table)
5626 {
5627 	struct doq_conn* conn = table->write_list_first;
5628 	if(!conn)
5629 		return NULL;
5630 	lock_basic_lock(&conn->lock);
5631 	table->write_list_first = conn->write_next;
5632 	if(conn->write_next)
5633 		conn->write_next->write_prev = NULL;
5634 	else table->write_list_last = NULL;
5635 	conn->write_next = NULL;
5636 	conn->write_prev = NULL;
5637 	conn->on_write_list = 0;
5638 	return conn;
5639 }
5640 
5641 int
doq_conn_check_timer(struct doq_conn * conn,struct timeval * tv,ngtcp2_tstamp * ts)5642 doq_conn_check_timer(struct doq_conn* conn, struct timeval* tv, ngtcp2_tstamp* ts)
5643 {
5644 	ngtcp2_tstamp doq_expiry = ngtcp2_conn_get_expiry(conn->conn);
5645 	ngtcp2_tstamp doq_now = doq_get_timestamp_nanosec();
5646 	ngtcp2_tstamp t;
5647 	struct timeval now = doq_get_timevalue();
5648 
5649 	if(doq_expiry <= doq_now || doq_expiry == UINT64_MAX) {
5650 		/* UINT64_MAX means there is no next expiry. */
5651 		/* The timer has already expired, add with zero timeout.
5652 		 * This should call the callback straight away. Calling it
5653 		 * from the event callbacks is cleaner than calling it here,
5654 		 * because then it is always called with the same locks and
5655 		 * so on. This routine only has the conn.lock. */
5656 		t = doq_now;
5657 		memcpy(tv, &now, sizeof(*tv));
5658 	} else {
5659 		t = doq_expiry;
5660 		memset(tv, 0, sizeof(*tv));
5661 		tv->tv_sec = (doq_expiry - doq_now) / NGTCP2_SECONDS;
5662 		tv->tv_usec = ((doq_expiry - doq_now) / NGTCP2_MICROSECONDS)%1000000;
5663 		timeval_add(tv, &now);
5664 	}
5665 
5666 	*ts = t;
5667 
5668 	/* If we already have a timer, is it the right value? */
5669 	if(conn->timer.timer_in_tree || conn->timer.timer_in_list) {
5670 		if(conn->timer.time_mono == *ts)
5671 			return 0;
5672 	}
5673 	return 1;
5674 }
5675 
5676 /* doq print connection log */
5677 static void
doq_conn_log_line(struct doq_conn * conn,char * s)5678 doq_conn_log_line(struct doq_conn* conn, char* s)
5679 {
5680 	char remotestr[256], localstr[256];
5681 	addr_to_str((void*)&conn->key.paddr.addr, conn->key.paddr.addrlen,
5682 		remotestr, sizeof(remotestr));
5683 	addr_to_str((void*)&conn->key.paddr.localaddr,
5684 		conn->key.paddr.localaddrlen, localstr, sizeof(localstr));
5685 	log_info("doq conn %s %s %s", remotestr, localstr, s);
5686 }
5687 
5688 int
doq_conn_handle_timeout(struct doq_conn * conn)5689 doq_conn_handle_timeout(struct doq_conn* conn)
5690 {
5691 	int rv;
5692 
5693 	if(verbosity >= VERB_ALGO)
5694 		doq_conn_log_line(conn, "timeout");
5695 
5696 	rv = ngtcp2_conn_handle_expiry(conn->conn, doq_get_timestamp_nanosec());
5697 	if(rv != 0) {
5698 		verbose(VERB_ALGO, "ngtcp2_conn_handle_expiry failed: %s",
5699 			ngtcp2_strerror(rv));
5700 #ifdef HAVE_NGTCP2_CCERR_DEFAULT
5701 		ngtcp2_ccerr_set_liberr(&conn->ccerr, rv, NULL, 0);
5702 #else
5703 		ngtcp2_connection_close_error_set_transport_error_liberr(
5704 			&conn->last_error, rv, NULL, 0);
5705 #endif
5706 		if(!doq_conn_close_error(conn->doq_socket->cp, conn)) {
5707 			/* failed, return for deletion */
5708 			return 0;
5709 		}
5710 		return 1;
5711 	}
5712 	doq_conn_write_enable(conn);
5713 	if(!doq_conn_write_streams(conn->doq_socket->cp, conn, NULL)) {
5714 		/* failed, return for deletion. */
5715 		return 0;
5716 	}
5717 	return 1;
5718 }
5719 
5720 void
doq_table_quic_size_add(struct doq_table * table,size_t add)5721 doq_table_quic_size_add(struct doq_table* table, size_t add)
5722 {
5723 	lock_basic_lock(&table->size_lock);
5724 	table->current_size += add;
5725 	lock_basic_unlock(&table->size_lock);
5726 }
5727 
5728 void
doq_table_quic_size_subtract(struct doq_table * table,size_t subtract)5729 doq_table_quic_size_subtract(struct doq_table* table, size_t subtract)
5730 {
5731 	lock_basic_lock(&table->size_lock);
5732 	if(table->current_size < subtract)
5733 		table->current_size = 0;
5734 	else	table->current_size -= subtract;
5735 	lock_basic_unlock(&table->size_lock);
5736 }
5737 
5738 int
doq_table_quic_size_available(struct doq_table * table,struct config_file * cfg,size_t mem)5739 doq_table_quic_size_available(struct doq_table* table,
5740 	struct config_file* cfg, size_t mem)
5741 {
5742 	size_t cur;
5743 	if (!table)
5744 		return 0;
5745 	lock_basic_lock(&table->size_lock);
5746 	cur = table->current_size;
5747 	lock_basic_unlock(&table->size_lock);
5748 
5749 	if(cur + mem > cfg->quic_size)
5750 		return 0;
5751 	return 1;
5752 }
5753 
doq_table_quic_size_get(struct doq_table * table)5754 size_t doq_table_quic_size_get(struct doq_table* table)
5755 {
5756 	size_t sz;
5757 	if(!table)
5758 		return 0;
5759 	lock_basic_lock(&table->size_lock);
5760 	sz = table->current_size;
5761 	lock_basic_unlock(&table->size_lock);
5762 	return sz;
5763 }
5764 #endif /* HAVE_NGTCP2 */
5765