xref: /freebsd/contrib/unbound/util/net_help.c (revision d3d381b2b194b4d24853e92eecef55f262688d1a)
1 /*
2  * util/net_help.c - implementation of the network helper code
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  * \file
37  * Implementation of net_help.h.
38  */
39 
40 #include "config.h"
41 #include "util/net_help.h"
42 #include "util/log.h"
43 #include "util/data/dname.h"
44 #include "util/module.h"
45 #include "util/regional.h"
46 #include "sldns/parseutil.h"
47 #include "sldns/wire2str.h"
48 #include <fcntl.h>
49 #ifdef HAVE_OPENSSL_SSL_H
50 #include <openssl/ssl.h>
51 #endif
52 #ifdef HAVE_OPENSSL_ERR_H
53 #include <openssl/err.h>
54 #endif
55 
56 /** max length of an IP address (the address portion) that we allow */
57 #define MAX_ADDR_STRLEN 128 /* characters */
58 /** default value for EDNS ADVERTISED size */
59 uint16_t EDNS_ADVERTISED_SIZE = 4096;
60 
61 /** minimal responses when positive answer: default is no */
62 int MINIMAL_RESPONSES = 0;
63 
64 /** rrset order roundrobin: default is no */
65 int RRSET_ROUNDROBIN = 0;
66 
67 /* returns true is string addr is an ip6 specced address */
68 int
69 str_is_ip6(const char* str)
70 {
71 	if(strchr(str, ':'))
72 		return 1;
73 	else    return 0;
74 }
75 
76 int
77 fd_set_nonblock(int s)
78 {
79 #ifdef HAVE_FCNTL
80 	int flag;
81 	if((flag = fcntl(s, F_GETFL)) == -1) {
82 		log_err("can't fcntl F_GETFL: %s", strerror(errno));
83 		flag = 0;
84 	}
85 	flag |= O_NONBLOCK;
86 	if(fcntl(s, F_SETFL, flag) == -1) {
87 		log_err("can't fcntl F_SETFL: %s", strerror(errno));
88 		return 0;
89 	}
90 #elif defined(HAVE_IOCTLSOCKET)
91 	unsigned long on = 1;
92 	if(ioctlsocket(s, FIONBIO, &on) != 0) {
93 		log_err("can't ioctlsocket FIONBIO on: %s",
94 			wsa_strerror(WSAGetLastError()));
95 	}
96 #endif
97 	return 1;
98 }
99 
100 int
101 fd_set_block(int s)
102 {
103 #ifdef HAVE_FCNTL
104 	int flag;
105 	if((flag = fcntl(s, F_GETFL)) == -1) {
106 		log_err("cannot fcntl F_GETFL: %s", strerror(errno));
107 		flag = 0;
108 	}
109 	flag &= ~O_NONBLOCK;
110 	if(fcntl(s, F_SETFL, flag) == -1) {
111 		log_err("cannot fcntl F_SETFL: %s", strerror(errno));
112 		return 0;
113 	}
114 #elif defined(HAVE_IOCTLSOCKET)
115 	unsigned long off = 0;
116 	if(ioctlsocket(s, FIONBIO, &off) != 0) {
117 		if(WSAGetLastError() != WSAEINVAL || verbosity >= 4)
118 			log_err("can't ioctlsocket FIONBIO off: %s",
119 				wsa_strerror(WSAGetLastError()));
120 	}
121 #endif
122 	return 1;
123 }
124 
125 int
126 is_pow2(size_t num)
127 {
128 	if(num == 0) return 1;
129 	return (num & (num-1)) == 0;
130 }
131 
132 void*
133 memdup(void* data, size_t len)
134 {
135 	void* d;
136 	if(!data) return NULL;
137 	if(len == 0) return NULL;
138 	d = malloc(len);
139 	if(!d) return NULL;
140 	memcpy(d, data, len);
141 	return d;
142 }
143 
144 void
145 log_addr(enum verbosity_value v, const char* str,
146 	struct sockaddr_storage* addr, socklen_t addrlen)
147 {
148 	uint16_t port;
149 	const char* family = "unknown";
150 	char dest[100];
151 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
152 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
153 	if(verbosity < v)
154 		return;
155 	switch(af) {
156 		case AF_INET: family="ip4"; break;
157 		case AF_INET6: family="ip6";
158 			sinaddr = &((struct sockaddr_in6*)addr)->sin6_addr;
159 			break;
160 		case AF_LOCAL:
161 			dest[0]=0;
162 			(void)inet_ntop(af, sinaddr, dest,
163 				(socklen_t)sizeof(dest));
164 			verbose(v, "%s local %s", str, dest);
165 			return; /* do not continue and try to get port */
166 		default: break;
167 	}
168 	if(inet_ntop(af, sinaddr, dest, (socklen_t)sizeof(dest)) == 0) {
169 		(void)strlcpy(dest, "(inet_ntop error)", sizeof(dest));
170 	}
171 	dest[sizeof(dest)-1] = 0;
172 	port = ntohs(((struct sockaddr_in*)addr)->sin_port);
173 	if(verbosity >= 4)
174 		verbose(v, "%s %s %s port %d (len %d)", str, family, dest,
175 			(int)port, (int)addrlen);
176 	else	verbose(v, "%s %s port %d", str, dest, (int)port);
177 }
178 
179 int
180 extstrtoaddr(const char* str, struct sockaddr_storage* addr,
181 	socklen_t* addrlen)
182 {
183 	char* s;
184 	int port = UNBOUND_DNS_PORT;
185 	if((s=strchr(str, '@'))) {
186 		char buf[MAX_ADDR_STRLEN];
187 		if(s-str >= MAX_ADDR_STRLEN) {
188 			return 0;
189 		}
190 		(void)strlcpy(buf, str, sizeof(buf));
191 		buf[s-str] = 0;
192 		port = atoi(s+1);
193 		if(port == 0 && strcmp(s+1,"0")!=0) {
194 			return 0;
195 		}
196 		return ipstrtoaddr(buf, port, addr, addrlen);
197 	}
198 	return ipstrtoaddr(str, port, addr, addrlen);
199 }
200 
201 
202 int
203 ipstrtoaddr(const char* ip, int port, struct sockaddr_storage* addr,
204 	socklen_t* addrlen)
205 {
206 	uint16_t p;
207 	if(!ip) return 0;
208 	p = (uint16_t) port;
209 	if(str_is_ip6(ip)) {
210 		char buf[MAX_ADDR_STRLEN];
211 		char* s;
212 		struct sockaddr_in6* sa = (struct sockaddr_in6*)addr;
213 		*addrlen = (socklen_t)sizeof(struct sockaddr_in6);
214 		memset(sa, 0, *addrlen);
215 		sa->sin6_family = AF_INET6;
216 		sa->sin6_port = (in_port_t)htons(p);
217 		if((s=strchr(ip, '%'))) { /* ip6%interface, rfc 4007 */
218 			if(s-ip >= MAX_ADDR_STRLEN)
219 				return 0;
220 			(void)strlcpy(buf, ip, sizeof(buf));
221 			buf[s-ip]=0;
222 			sa->sin6_scope_id = (uint32_t)atoi(s+1);
223 			ip = buf;
224 		}
225 		if(inet_pton((int)sa->sin6_family, ip, &sa->sin6_addr) <= 0) {
226 			return 0;
227 		}
228 	} else { /* ip4 */
229 		struct sockaddr_in* sa = (struct sockaddr_in*)addr;
230 		*addrlen = (socklen_t)sizeof(struct sockaddr_in);
231 		memset(sa, 0, *addrlen);
232 		sa->sin_family = AF_INET;
233 		sa->sin_port = (in_port_t)htons(p);
234 		if(inet_pton((int)sa->sin_family, ip, &sa->sin_addr) <= 0) {
235 			return 0;
236 		}
237 	}
238 	return 1;
239 }
240 
241 int netblockstrtoaddr(const char* str, int port, struct sockaddr_storage* addr,
242         socklen_t* addrlen, int* net)
243 {
244 	char buf[64];
245 	char* s;
246 	*net = (str_is_ip6(str)?128:32);
247 	if((s=strchr(str, '/'))) {
248 		if(atoi(s+1) > *net) {
249 			log_err("netblock too large: %s", str);
250 			return 0;
251 		}
252 		*net = atoi(s+1);
253 		if(*net == 0 && strcmp(s+1, "0") != 0) {
254 			log_err("cannot parse netblock: '%s'", str);
255 			return 0;
256 		}
257 		strlcpy(buf, str, sizeof(buf));
258 		s = strchr(buf, '/');
259 		if(s) *s = 0;
260 		s = buf;
261 	}
262 	if(!ipstrtoaddr(s?s:str, port, addr, addrlen)) {
263 		log_err("cannot parse ip address: '%s'", str);
264 		return 0;
265 	}
266 	if(s) {
267 		addr_mask(addr, *addrlen, *net);
268 	}
269 	return 1;
270 }
271 
272 int authextstrtoaddr(char* str, struct sockaddr_storage* addr,
273 	socklen_t* addrlen, char** auth_name)
274 {
275 	char* s;
276 	int port = UNBOUND_DNS_PORT;
277 	if((s=strchr(str, '@'))) {
278 		char buf[MAX_ADDR_STRLEN];
279 		size_t len = (size_t)(s-str);
280 		char* hash = strchr(s+1, '#');
281 		if(hash) {
282 			*auth_name = hash+1;
283 		} else {
284 			*auth_name = NULL;
285 		}
286 		if(len >= MAX_ADDR_STRLEN) {
287 			return 0;
288 		}
289 		(void)strlcpy(buf, str, sizeof(buf));
290 		buf[len] = 0;
291 		port = atoi(s+1);
292 		if(port == 0) {
293 			if(!hash && strcmp(s+1,"0")!=0)
294 				return 0;
295 			if(hash && strncmp(s+1,"0#",2)!=0)
296 				return 0;
297 		}
298 		return ipstrtoaddr(buf, port, addr, addrlen);
299 	}
300 	if((s=strchr(str, '#'))) {
301 		char buf[MAX_ADDR_STRLEN];
302 		size_t len = (size_t)(s-str);
303 		if(len >= MAX_ADDR_STRLEN) {
304 			return 0;
305 		}
306 		(void)strlcpy(buf, str, sizeof(buf));
307 		buf[len] = 0;
308 		port = UNBOUND_DNS_OVER_TLS_PORT;
309 		*auth_name = s+1;
310 		return ipstrtoaddr(buf, port, addr, addrlen);
311 	}
312 	*auth_name = NULL;
313 	return ipstrtoaddr(str, port, addr, addrlen);
314 }
315 
316 /** store port number into sockaddr structure */
317 void
318 sockaddr_store_port(struct sockaddr_storage* addr, socklen_t addrlen, int port)
319 {
320 	if(addr_is_ip6(addr, addrlen)) {
321 		struct sockaddr_in6* sa = (struct sockaddr_in6*)addr;
322 		sa->sin6_port = (in_port_t)htons((uint16_t)port);
323 	} else {
324 		struct sockaddr_in* sa = (struct sockaddr_in*)addr;
325 		sa->sin_port = (in_port_t)htons((uint16_t)port);
326 	}
327 }
328 
329 void
330 log_nametypeclass(enum verbosity_value v, const char* str, uint8_t* name,
331 	uint16_t type, uint16_t dclass)
332 {
333 	char buf[LDNS_MAX_DOMAINLEN+1];
334 	char t[12], c[12];
335 	const char *ts, *cs;
336 	if(verbosity < v)
337 		return;
338 	dname_str(name, buf);
339 	if(type == LDNS_RR_TYPE_TSIG) ts = "TSIG";
340 	else if(type == LDNS_RR_TYPE_IXFR) ts = "IXFR";
341 	else if(type == LDNS_RR_TYPE_AXFR) ts = "AXFR";
342 	else if(type == LDNS_RR_TYPE_MAILB) ts = "MAILB";
343 	else if(type == LDNS_RR_TYPE_MAILA) ts = "MAILA";
344 	else if(type == LDNS_RR_TYPE_ANY) ts = "ANY";
345 	else if(sldns_rr_descript(type) && sldns_rr_descript(type)->_name)
346 		ts = sldns_rr_descript(type)->_name;
347 	else {
348 		snprintf(t, sizeof(t), "TYPE%d", (int)type);
349 		ts = t;
350 	}
351 	if(sldns_lookup_by_id(sldns_rr_classes, (int)dclass) &&
352 		sldns_lookup_by_id(sldns_rr_classes, (int)dclass)->name)
353 		cs = sldns_lookup_by_id(sldns_rr_classes, (int)dclass)->name;
354 	else {
355 		snprintf(c, sizeof(c), "CLASS%d", (int)dclass);
356 		cs = c;
357 	}
358 	log_info("%s %s %s %s", str, buf, ts, cs);
359 }
360 
361 void log_name_addr(enum verbosity_value v, const char* str, uint8_t* zone,
362 	struct sockaddr_storage* addr, socklen_t addrlen)
363 {
364 	uint16_t port;
365 	const char* family = "unknown_family ";
366 	char namebuf[LDNS_MAX_DOMAINLEN+1];
367 	char dest[100];
368 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
369 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
370 	if(verbosity < v)
371 		return;
372 	switch(af) {
373 		case AF_INET: family=""; break;
374 		case AF_INET6: family="";
375 			sinaddr = &((struct sockaddr_in6*)addr)->sin6_addr;
376 			break;
377 		case AF_LOCAL: family="local "; break;
378 		default: break;
379 	}
380 	if(inet_ntop(af, sinaddr, dest, (socklen_t)sizeof(dest)) == 0) {
381 		(void)strlcpy(dest, "(inet_ntop error)", sizeof(dest));
382 	}
383 	dest[sizeof(dest)-1] = 0;
384 	port = ntohs(((struct sockaddr_in*)addr)->sin_port);
385 	dname_str(zone, namebuf);
386 	if(af != AF_INET && af != AF_INET6)
387 		verbose(v, "%s <%s> %s%s#%d (addrlen %d)",
388 			str, namebuf, family, dest, (int)port, (int)addrlen);
389 	else	verbose(v, "%s <%s> %s%s#%d",
390 			str, namebuf, family, dest, (int)port);
391 }
392 
393 void log_err_addr(const char* str, const char* err,
394 	struct sockaddr_storage* addr, socklen_t addrlen)
395 {
396 	uint16_t port;
397 	char dest[100];
398 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
399 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
400 	if(af == AF_INET6)
401 		sinaddr = &((struct sockaddr_in6*)addr)->sin6_addr;
402 	if(inet_ntop(af, sinaddr, dest, (socklen_t)sizeof(dest)) == 0) {
403 		(void)strlcpy(dest, "(inet_ntop error)", sizeof(dest));
404 	}
405 	dest[sizeof(dest)-1] = 0;
406 	port = ntohs(((struct sockaddr_in*)addr)->sin_port);
407 	if(verbosity >= 4)
408 		log_err("%s: %s for %s port %d (len %d)", str, err, dest,
409 			(int)port, (int)addrlen);
410 	else	log_err("%s: %s for %s", str, err, dest);
411 }
412 
413 int
414 sockaddr_cmp(struct sockaddr_storage* addr1, socklen_t len1,
415 	struct sockaddr_storage* addr2, socklen_t len2)
416 {
417 	struct sockaddr_in* p1_in = (struct sockaddr_in*)addr1;
418 	struct sockaddr_in* p2_in = (struct sockaddr_in*)addr2;
419 	struct sockaddr_in6* p1_in6 = (struct sockaddr_in6*)addr1;
420 	struct sockaddr_in6* p2_in6 = (struct sockaddr_in6*)addr2;
421 	if(len1 < len2)
422 		return -1;
423 	if(len1 > len2)
424 		return 1;
425 	log_assert(len1 == len2);
426 	if( p1_in->sin_family < p2_in->sin_family)
427 		return -1;
428 	if( p1_in->sin_family > p2_in->sin_family)
429 		return 1;
430 	log_assert( p1_in->sin_family == p2_in->sin_family );
431 	/* compare ip4 */
432 	if( p1_in->sin_family == AF_INET ) {
433 		/* just order it, ntohs not required */
434 		if(p1_in->sin_port < p2_in->sin_port)
435 			return -1;
436 		if(p1_in->sin_port > p2_in->sin_port)
437 			return 1;
438 		log_assert(p1_in->sin_port == p2_in->sin_port);
439 		return memcmp(&p1_in->sin_addr, &p2_in->sin_addr, INET_SIZE);
440 	} else if (p1_in6->sin6_family == AF_INET6) {
441 		/* just order it, ntohs not required */
442 		if(p1_in6->sin6_port < p2_in6->sin6_port)
443 			return -1;
444 		if(p1_in6->sin6_port > p2_in6->sin6_port)
445 			return 1;
446 		log_assert(p1_in6->sin6_port == p2_in6->sin6_port);
447 		return memcmp(&p1_in6->sin6_addr, &p2_in6->sin6_addr,
448 			INET6_SIZE);
449 	} else {
450 		/* eek unknown type, perform this comparison for sanity. */
451 		return memcmp(addr1, addr2, len1);
452 	}
453 }
454 
455 int
456 sockaddr_cmp_addr(struct sockaddr_storage* addr1, socklen_t len1,
457 	struct sockaddr_storage* addr2, socklen_t len2)
458 {
459 	struct sockaddr_in* p1_in = (struct sockaddr_in*)addr1;
460 	struct sockaddr_in* p2_in = (struct sockaddr_in*)addr2;
461 	struct sockaddr_in6* p1_in6 = (struct sockaddr_in6*)addr1;
462 	struct sockaddr_in6* p2_in6 = (struct sockaddr_in6*)addr2;
463 	if(len1 < len2)
464 		return -1;
465 	if(len1 > len2)
466 		return 1;
467 	log_assert(len1 == len2);
468 	if( p1_in->sin_family < p2_in->sin_family)
469 		return -1;
470 	if( p1_in->sin_family > p2_in->sin_family)
471 		return 1;
472 	log_assert( p1_in->sin_family == p2_in->sin_family );
473 	/* compare ip4 */
474 	if( p1_in->sin_family == AF_INET ) {
475 		return memcmp(&p1_in->sin_addr, &p2_in->sin_addr, INET_SIZE);
476 	} else if (p1_in6->sin6_family == AF_INET6) {
477 		return memcmp(&p1_in6->sin6_addr, &p2_in6->sin6_addr,
478 			INET6_SIZE);
479 	} else {
480 		/* eek unknown type, perform this comparison for sanity. */
481 		return memcmp(addr1, addr2, len1);
482 	}
483 }
484 
485 int
486 addr_is_ip6(struct sockaddr_storage* addr, socklen_t len)
487 {
488 	if(len == (socklen_t)sizeof(struct sockaddr_in6) &&
489 		((struct sockaddr_in6*)addr)->sin6_family == AF_INET6)
490 		return 1;
491 	else    return 0;
492 }
493 
494 void
495 addr_mask(struct sockaddr_storage* addr, socklen_t len, int net)
496 {
497 	uint8_t mask[8] = {0x0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe};
498 	int i, max;
499 	uint8_t* s;
500 	if(addr_is_ip6(addr, len)) {
501 		s = (uint8_t*)&((struct sockaddr_in6*)addr)->sin6_addr;
502 		max = 128;
503 	} else {
504 		s = (uint8_t*)&((struct sockaddr_in*)addr)->sin_addr;
505 		max = 32;
506 	}
507 	if(net >= max)
508 		return;
509 	for(i=net/8+1; i<max/8; i++) {
510 		s[i] = 0;
511 	}
512 	s[net/8] &= mask[net&0x7];
513 }
514 
515 int
516 addr_in_common(struct sockaddr_storage* addr1, int net1,
517 	struct sockaddr_storage* addr2, int net2, socklen_t addrlen)
518 {
519 	int min = (net1<net2)?net1:net2;
520 	int i, to;
521 	int match = 0;
522 	uint8_t* s1, *s2;
523 	if(addr_is_ip6(addr1, addrlen)) {
524 		s1 = (uint8_t*)&((struct sockaddr_in6*)addr1)->sin6_addr;
525 		s2 = (uint8_t*)&((struct sockaddr_in6*)addr2)->sin6_addr;
526 		to = 16;
527 	} else {
528 		s1 = (uint8_t*)&((struct sockaddr_in*)addr1)->sin_addr;
529 		s2 = (uint8_t*)&((struct sockaddr_in*)addr2)->sin_addr;
530 		to = 4;
531 	}
532 	/* match = bits_in_common(s1, s2, to); */
533 	for(i=0; i<to; i++) {
534 		if(s1[i] == s2[i]) {
535 			match += 8;
536 		} else {
537 			uint8_t z = s1[i]^s2[i];
538 			log_assert(z);
539 			while(!(z&0x80)) {
540 				match++;
541 				z<<=1;
542 			}
543 			break;
544 		}
545 	}
546 	if(match > min) match = min;
547 	return match;
548 }
549 
550 void
551 addr_to_str(struct sockaddr_storage* addr, socklen_t addrlen,
552 	char* buf, size_t len)
553 {
554 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
555 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
556 	if(addr_is_ip6(addr, addrlen))
557 		sinaddr = &((struct sockaddr_in6*)addr)->sin6_addr;
558 	if(inet_ntop(af, sinaddr, buf, (socklen_t)len) == 0) {
559 		snprintf(buf, len, "(inet_ntop_error)");
560 	}
561 }
562 
563 int
564 addr_is_ip4mapped(struct sockaddr_storage* addr, socklen_t addrlen)
565 {
566 	/* prefix for ipv4 into ipv6 mapping is ::ffff:x.x.x.x */
567 	const uint8_t map_prefix[16] =
568 		{0,0,0,0,  0,0,0,0, 0,0,0xff,0xff, 0,0,0,0};
569 	uint8_t* s;
570 	if(!addr_is_ip6(addr, addrlen))
571 		return 0;
572 	/* s is 16 octet ipv6 address string */
573 	s = (uint8_t*)&((struct sockaddr_in6*)addr)->sin6_addr;
574 	return (memcmp(s, map_prefix, 12) == 0);
575 }
576 
577 int addr_is_broadcast(struct sockaddr_storage* addr, socklen_t addrlen)
578 {
579 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
580 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
581 	return af == AF_INET && addrlen>=(socklen_t)sizeof(struct sockaddr_in)
582 		&& memcmp(sinaddr, "\377\377\377\377", 4) == 0;
583 }
584 
585 int addr_is_any(struct sockaddr_storage* addr, socklen_t addrlen)
586 {
587 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
588 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
589 	void* sin6addr = &((struct sockaddr_in6*)addr)->sin6_addr;
590 	if(af == AF_INET && addrlen>=(socklen_t)sizeof(struct sockaddr_in)
591 		&& memcmp(sinaddr, "\000\000\000\000", 4) == 0)
592 		return 1;
593 	else if(af==AF_INET6 && addrlen>=(socklen_t)sizeof(struct sockaddr_in6)
594 		&& memcmp(sin6addr, "\000\000\000\000\000\000\000\000"
595 		"\000\000\000\000\000\000\000\000", 16) == 0)
596 		return 1;
597 	return 0;
598 }
599 
600 void sock_list_insert(struct sock_list** list, struct sockaddr_storage* addr,
601 	socklen_t len, struct regional* region)
602 {
603 	struct sock_list* add = (struct sock_list*)regional_alloc(region,
604 		sizeof(*add) - sizeof(add->addr) + (size_t)len);
605 	if(!add) {
606 		log_err("out of memory in socketlist insert");
607 		return;
608 	}
609 	log_assert(list);
610 	add->next = *list;
611 	add->len = len;
612 	*list = add;
613 	if(len) memmove(&add->addr, addr, len);
614 }
615 
616 void sock_list_prepend(struct sock_list** list, struct sock_list* add)
617 {
618 	struct sock_list* last = add;
619 	if(!last)
620 		return;
621 	while(last->next)
622 		last = last->next;
623 	last->next = *list;
624 	*list = add;
625 }
626 
627 int sock_list_find(struct sock_list* list, struct sockaddr_storage* addr,
628         socklen_t len)
629 {
630 	while(list) {
631 		if(len == list->len) {
632 			if(len == 0 || sockaddr_cmp_addr(addr, len,
633 				&list->addr, list->len) == 0)
634 				return 1;
635 		}
636 		list = list->next;
637 	}
638 	return 0;
639 }
640 
641 void sock_list_merge(struct sock_list** list, struct regional* region,
642 	struct sock_list* add)
643 {
644 	struct sock_list* p;
645 	for(p=add; p; p=p->next) {
646 		if(!sock_list_find(*list, &p->addr, p->len))
647 			sock_list_insert(list, &p->addr, p->len, region);
648 	}
649 }
650 
651 void
652 log_crypto_err(const char* str)
653 {
654 #ifdef HAVE_SSL
655 	/* error:[error code]:[library name]:[function name]:[reason string] */
656 	char buf[128];
657 	unsigned long e;
658 	ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
659 	log_err("%s crypto %s", str, buf);
660 	while( (e=ERR_get_error()) ) {
661 		ERR_error_string_n(e, buf, sizeof(buf));
662 		log_err("and additionally crypto %s", buf);
663 	}
664 #else
665 	(void)str;
666 #endif /* HAVE_SSL */
667 }
668 
669 int
670 listen_sslctx_setup(void* ctxt)
671 {
672 #ifdef HAVE_SSL
673 	SSL_CTX* ctx = (SSL_CTX*)ctxt;
674 	/* no SSLv2, SSLv3 because has defects */
675 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)
676 		!= SSL_OP_NO_SSLv2){
677 		log_crypto_err("could not set SSL_OP_NO_SSLv2");
678 		return 0;
679 	}
680 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)
681 		!= SSL_OP_NO_SSLv3){
682 		log_crypto_err("could not set SSL_OP_NO_SSLv3");
683 		return 0;
684 	}
685 #if defined(SSL_OP_NO_TLSv1) && defined(SSL_OP_NO_TLSv1_1)
686 	/* if we have tls 1.1 disable 1.0 */
687 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1) & SSL_OP_NO_TLSv1)
688 		!= SSL_OP_NO_TLSv1){
689 		log_crypto_err("could not set SSL_OP_NO_TLSv1");
690 		return 0;
691 	}
692 #endif
693 #if defined(SSL_OP_NO_TLSv1_1) && defined(SSL_OP_NO_TLSv1_2)
694 	/* if we have tls 1.2 disable 1.1 */
695 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1_1) & SSL_OP_NO_TLSv1_1)
696 		!= SSL_OP_NO_TLSv1_1){
697 		log_crypto_err("could not set SSL_OP_NO_TLSv1_1");
698 		return 0;
699 	}
700 #endif
701 #if defined(SHA256_DIGEST_LENGTH) && defined(USE_ECDSA)
702 	/* if we have sha256, set the cipher list to have no known vulns */
703 	if(!SSL_CTX_set_cipher_list(ctx, "TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-256-GCM-SHA384:TLS13-AES-128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256"))
704 		log_crypto_err("could not set cipher list with SSL_CTX_set_cipher_list");
705 #endif
706 
707 	if((SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE) &
708 		SSL_OP_CIPHER_SERVER_PREFERENCE) !=
709 		SSL_OP_CIPHER_SERVER_PREFERENCE) {
710 		log_crypto_err("could not set SSL_OP_CIPHER_SERVER_PREFERENCE");
711 		return 0;
712 	}
713 
714 #ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL
715 	SSL_CTX_set_security_level(ctx, 0);
716 #endif
717 #else
718 	(void)ctxt;
719 #endif /* HAVE_SSL */
720 	return 1;
721 }
722 
723 void
724 listen_sslctx_setup_2(void* ctxt)
725 {
726 #ifdef HAVE_SSL
727 	SSL_CTX* ctx = (SSL_CTX*)ctxt;
728 	(void)ctx;
729 #if HAVE_DECL_SSL_CTX_SET_ECDH_AUTO
730 	if(!SSL_CTX_set_ecdh_auto(ctx,1)) {
731 		log_crypto_err("Error in SSL_CTX_ecdh_auto, not enabling ECDHE");
732 	}
733 #elif defined(USE_ECDSA)
734 	if(1) {
735 		EC_KEY *ecdh = EC_KEY_new_by_curve_name (NID_X9_62_prime256v1);
736 		if (!ecdh) {
737 			log_crypto_err("could not find p256, not enabling ECDHE");
738 		} else {
739 			if (1 != SSL_CTX_set_tmp_ecdh (ctx, ecdh)) {
740 				log_crypto_err("Error in SSL_CTX_set_tmp_ecdh, not enabling ECDHE");
741 			}
742 			EC_KEY_free (ecdh);
743 		}
744 	}
745 #endif
746 #else
747 	(void)ctxt;
748 #endif /* HAVE_SSL */
749 }
750 
751 void* listen_sslctx_create(char* key, char* pem, char* verifypem)
752 {
753 #ifdef HAVE_SSL
754 	SSL_CTX* ctx = SSL_CTX_new(SSLv23_server_method());
755 	if(!ctx) {
756 		log_crypto_err("could not SSL_CTX_new");
757 		return NULL;
758 	}
759 	if(!listen_sslctx_setup(ctx)) {
760 		SSL_CTX_free(ctx);
761 		return NULL;
762 	}
763 	if(!SSL_CTX_use_certificate_chain_file(ctx, pem)) {
764 		log_err("error for cert file: %s", pem);
765 		log_crypto_err("error in SSL_CTX use_certificate_chain_file");
766 		SSL_CTX_free(ctx);
767 		return NULL;
768 	}
769 	if(!SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM)) {
770 		log_err("error for private key file: %s", key);
771 		log_crypto_err("Error in SSL_CTX use_PrivateKey_file");
772 		SSL_CTX_free(ctx);
773 		return NULL;
774 	}
775 	if(!SSL_CTX_check_private_key(ctx)) {
776 		log_err("error for key file: %s", key);
777 		log_crypto_err("Error in SSL_CTX check_private_key");
778 		SSL_CTX_free(ctx);
779 		return NULL;
780 	}
781 	listen_sslctx_setup_2(ctx);
782 	if(verifypem && verifypem[0]) {
783 		if(!SSL_CTX_load_verify_locations(ctx, verifypem, NULL)) {
784 			log_crypto_err("Error in SSL_CTX verify locations");
785 			SSL_CTX_free(ctx);
786 			return NULL;
787 		}
788 		SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(
789 			verifypem));
790 		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
791 	}
792 	return ctx;
793 #else
794 	(void)key; (void)pem; (void)verifypem;
795 	return NULL;
796 #endif
797 }
798 
799 void* connect_sslctx_create(char* key, char* pem, char* verifypem)
800 {
801 #ifdef HAVE_SSL
802 	SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
803 	if(!ctx) {
804 		log_crypto_err("could not allocate SSL_CTX pointer");
805 		return NULL;
806 	}
807 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)
808 		!= SSL_OP_NO_SSLv2) {
809 		log_crypto_err("could not set SSL_OP_NO_SSLv2");
810 		SSL_CTX_free(ctx);
811 		return NULL;
812 	}
813 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)
814 		!= SSL_OP_NO_SSLv3) {
815 		log_crypto_err("could not set SSL_OP_NO_SSLv3");
816 		SSL_CTX_free(ctx);
817 		return NULL;
818 	}
819 	if(key && key[0]) {
820 		if(!SSL_CTX_use_certificate_chain_file(ctx, pem)) {
821 			log_err("error in client certificate %s", pem);
822 			log_crypto_err("error in certificate file");
823 			SSL_CTX_free(ctx);
824 			return NULL;
825 		}
826 		if(!SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM)) {
827 			log_err("error in client private key %s", key);
828 			log_crypto_err("error in key file");
829 			SSL_CTX_free(ctx);
830 			return NULL;
831 		}
832 		if(!SSL_CTX_check_private_key(ctx)) {
833 			log_err("error in client key %s", key);
834 			log_crypto_err("error in SSL_CTX_check_private_key");
835 			SSL_CTX_free(ctx);
836 			return NULL;
837 		}
838 	}
839 	if(verifypem && verifypem[0]) {
840 		if(!SSL_CTX_load_verify_locations(ctx, verifypem, NULL)) {
841 			log_crypto_err("error in SSL_CTX verify");
842 			SSL_CTX_free(ctx);
843 			return NULL;
844 		}
845 		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
846 	}
847 	return ctx;
848 #else
849 	(void)key; (void)pem; (void)verifypem;
850 	return NULL;
851 #endif
852 }
853 
854 void* incoming_ssl_fd(void* sslctx, int fd)
855 {
856 #ifdef HAVE_SSL
857 	SSL* ssl = SSL_new((SSL_CTX*)sslctx);
858 	if(!ssl) {
859 		log_crypto_err("could not SSL_new");
860 		return NULL;
861 	}
862 	SSL_set_accept_state(ssl);
863 	(void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
864 	if(!SSL_set_fd(ssl, fd)) {
865 		log_crypto_err("could not SSL_set_fd");
866 		SSL_free(ssl);
867 		return NULL;
868 	}
869 	return ssl;
870 #else
871 	(void)sslctx; (void)fd;
872 	return NULL;
873 #endif
874 }
875 
876 void* outgoing_ssl_fd(void* sslctx, int fd)
877 {
878 #ifdef HAVE_SSL
879 	SSL* ssl = SSL_new((SSL_CTX*)sslctx);
880 	if(!ssl) {
881 		log_crypto_err("could not SSL_new");
882 		return NULL;
883 	}
884 	SSL_set_connect_state(ssl);
885 	(void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
886 	if(!SSL_set_fd(ssl, fd)) {
887 		log_crypto_err("could not SSL_set_fd");
888 		SSL_free(ssl);
889 		return NULL;
890 	}
891 	return ssl;
892 #else
893 	(void)sslctx; (void)fd;
894 	return NULL;
895 #endif
896 }
897 
898 #if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED) && defined(CRYPTO_LOCK) && OPENSSL_VERSION_NUMBER < 0x10100000L
899 /** global lock list for openssl locks */
900 static lock_basic_type *ub_openssl_locks = NULL;
901 
902 /** callback that gets thread id for openssl */
903 static unsigned long
904 ub_crypto_id_cb(void)
905 {
906 	return (unsigned long)log_thread_get();
907 }
908 
909 static void
910 ub_crypto_lock_cb(int mode, int type, const char *ATTR_UNUSED(file),
911 	int ATTR_UNUSED(line))
912 {
913 	if((mode&CRYPTO_LOCK)) {
914 		lock_basic_lock(&ub_openssl_locks[type]);
915 	} else {
916 		lock_basic_unlock(&ub_openssl_locks[type]);
917 	}
918 }
919 #endif /* OPENSSL_THREADS */
920 
921 int ub_openssl_lock_init(void)
922 {
923 #if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED) && defined(CRYPTO_LOCK) && OPENSSL_VERSION_NUMBER < 0x10100000L
924 	int i;
925 	ub_openssl_locks = (lock_basic_type*)reallocarray(
926 		NULL, (size_t)CRYPTO_num_locks(), sizeof(lock_basic_type));
927 	if(!ub_openssl_locks)
928 		return 0;
929 	for(i=0; i<CRYPTO_num_locks(); i++) {
930 		lock_basic_init(&ub_openssl_locks[i]);
931 	}
932 	CRYPTO_set_id_callback(&ub_crypto_id_cb);
933 	CRYPTO_set_locking_callback(&ub_crypto_lock_cb);
934 #endif /* OPENSSL_THREADS */
935 	return 1;
936 }
937 
938 void ub_openssl_lock_delete(void)
939 {
940 #if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED) && defined(CRYPTO_LOCK) && OPENSSL_VERSION_NUMBER < 0x10100000L
941 	int i;
942 	if(!ub_openssl_locks)
943 		return;
944 	CRYPTO_set_id_callback(NULL);
945 	CRYPTO_set_locking_callback(NULL);
946 	for(i=0; i<CRYPTO_num_locks(); i++) {
947 		lock_basic_destroy(&ub_openssl_locks[i]);
948 	}
949 	free(ub_openssl_locks);
950 #endif /* OPENSSL_THREADS */
951 }
952 
953