xref: /freebsd/contrib/unbound/dnstap/unbound-dnstap-socket.c (revision 7fdf597e96a02165cfe22ff357b857d5fa15ed8a)
1 /*
2  * dnstap/unbound-dnstap-socket.c - debug program that listens for DNSTAP logs.
3  *
4  * Copyright (c) 2020, 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 program listens on a DNSTAP socket for logged messages.
40  */
41 #include "config.h"
42 #ifdef HAVE_GETOPT_H
43 #include <getopt.h>
44 #endif
45 #include <signal.h>
46 #include <stdlib.h>
47 #include <unistd.h>
48 #include <signal.h>
49 #include <ctype.h>
50 #ifdef HAVE_SYS_UN_H
51 #include <sys/un.h>
52 #endif
53 #include <openssl/ssl.h>
54 #include <openssl/rand.h>
55 #include <openssl/err.h>
56 #include "dnstap/dtstream.h"
57 #include "dnstap/dnstap_fstrm.h"
58 #include "util/log.h"
59 #include "util/ub_event.h"
60 #include "util/net_help.h"
61 #include "services/listen_dnsport.h"
62 #include "sldns/sbuffer.h"
63 #include "sldns/wire2str.h"
64 #include "sldns/pkthdr.h"
65 #ifdef USE_DNSTAP
66 #include <protobuf-c/protobuf-c.h>
67 #include "dnstap/dnstap.pb-c.h"
68 #endif /* USE_DNSTAP */
69 #include "util/config_file.h"
70 
71 /** listen backlog on TCP connections for dnstap logs */
72 #define LISTEN_BACKLOG 16
73 
74 /** usage information for streamtcp */
75 static void usage(char* argv[])
76 {
77 	printf("usage: %s [options]\n", argv[0]);
78 	printf("	Listen to dnstap messages\n");
79 	printf("stdout has dnstap log, stderr has verbose server log\n");
80 	printf("-u <socketpath>		listen to unix socket with this file name\n");
81 	printf("-s <serverip[@port]>	listen for TCP on the IP and port\n");
82 	printf("-t <serverip[@port]>	listen for TLS on IP and port\n");
83 	printf("-x <server.key>		server key file for TLS service\n");
84 	printf("-y <server.pem>		server cert file for TLS service\n");
85 	printf("-z <verify.pem>		cert file to verify client connections\n");
86 	printf("-l			long format for DNS printout\n");
87 	printf("-v			more verbose log output\n");
88 	printf("-c			internal unit test and exit\n");
89 	printf("-h			this help text\n");
90 	exit(1);
91 }
92 
93 /** long format option, for multiline printout per message */
94 static int longformat = 0;
95 
96 struct tap_socket_list;
97 struct tap_socket;
98 /** main tap callback data */
99 struct main_tap_data {
100 	/** the event base (to loopexit) */
101 	struct ub_event_base* base;
102 	/** the list of accept sockets */
103 	struct tap_socket_list* acceptlist;
104 };
105 
106 /* list of data */
107 struct tap_data_list {
108 	/** next in list */
109 	struct tap_data_list* next;
110 	/** the data */
111 	struct tap_data* d;
112 };
113 
114 /** tap callback variables */
115 struct tap_data {
116 	/** the fd */
117 	int fd;
118 	/** the ub event */
119 	struct ub_event* ev;
120 	/** the SSL for TLS streams */
121 	SSL* ssl;
122 	/** is the ssl handshake done */
123 	int ssl_handshake_done;
124 	/** we are briefly waiting to write (in the struct event) */
125 	int ssl_brief_write;
126 	/** string that identifies the socket (or NULL), like IP address */
127 	char* id;
128 	/** have we read the length, and how many bytes of it */
129 	int len_done;
130 	/** have we read the data, and how many bytes of it */
131 	size_t data_done;
132 	/** are we reading a control frame */
133 	int control_frame;
134 	/** are we bi-directional (if false, uni-directional) */
135 	int is_bidirectional;
136 	/** data of the frame */
137 	uint8_t* frame;
138 	/** length of this frame */
139 	size_t len;
140 	/** back pointer to the tap_data_list entry;
141 	 * used to NULL the forward pointer to this data
142 	 * when this data is freed. */
143 	struct tap_data_list* data_list;
144 };
145 
146 /** list of sockets */
147 struct tap_socket_list {
148 	/** next in list */
149 	struct tap_socket_list* next;
150 	/** the socket */
151 	struct tap_socket* s;
152 };
153 
154 /** tap socket */
155 struct tap_socket {
156 	/** fd of socket */
157 	int fd;
158 	/** the event for it */
159 	struct ub_event *ev;
160 	/** has the event been added */
161 	int ev_added;
162 	/** the callback, for the event, ev_cb(fd, bits, arg) */
163 	void (*ev_cb)(int, short, void*);
164 	/** data element, (arg for the tap_socket struct) */
165 	void* data;
166 	/** socketpath, if this is an AF_LOCAL socket */
167 	char* socketpath;
168 	/** IP, if this is a TCP socket */
169 	char* ip;
170 	/** for a TLS socket, the tls context */
171 	SSL_CTX* sslctx;
172 	/** dumb way to deal with memory leaks:
173 	 * tap_data was only freed on errors and not during exit leading to
174 	 * false positives when testing for memory leaks. */
175 	struct tap_data_list* data_list;
176 };
177 
178 /** try to delete tail entries from the list if all of them have no data */
179 static void tap_data_list_try_to_free_tail(struct tap_data_list* list)
180 {
181 	struct tap_data_list* current = list;
182 	log_assert(!list->d);
183 	if(!list->next) /* we are the last, we can't remove ourselves */
184 		return;
185 	list = list->next;
186 	while(list) {
187 		if(list->d) /* a tail entry still has data; return */
188 			return;
189 		list = list->next;
190 	}
191 	/* keep the next */
192 	list = current->next;
193 	/* the tail will be removed; but not ourselves */
194 	current->next = NULL;
195 	while(list) {
196 		current = list;
197 		list = list->next;
198 		free(current);
199 	}
200 }
201 
202 /** delete the tap structure */
203 static void tap_data_free(struct tap_data* data, int free_tail)
204 {
205 	if(!data)
206 		return;
207 	if(data->ev) {
208 		ub_event_del(data->ev);
209 		ub_event_free(data->ev);
210 	}
211 #ifdef HAVE_SSL
212 	SSL_free(data->ssl);
213 #endif
214 	sock_close(data->fd);
215 	free(data->id);
216 	free(data->frame);
217 	if(data->data_list) {
218 		data->data_list->d = NULL;
219 		if(free_tail)
220 			tap_data_list_try_to_free_tail(data->data_list);
221 	}
222 	free(data);
223 }
224 
225 /** insert tap_data in the tap_data_list */
226 static int tap_data_list_insert(struct tap_data_list** liststart,
227 	struct tap_data* d)
228 {
229 	struct tap_data_list* entry = (struct tap_data_list*)
230 		malloc(sizeof(*entry));
231 	if(!entry)
232 		return 0;
233 	entry->next = *liststart;
234 	entry->d = d;
235 	d->data_list = entry;
236 	*liststart = entry;
237 	return 1;
238 }
239 
240 /** delete the tap_data_list and free any remaining tap_data */
241 static void tap_data_list_delete(struct tap_data_list* list)
242 {
243 	struct tap_data_list* e = list, *next;
244 	while(e) {
245 		next = e->next;
246 		if(e->d) {
247 			tap_data_free(e->d, 0);
248 			e->d = NULL;
249 		}
250 		free(e);
251 		e = next;
252 	}
253 }
254 
255 /** del the tap event */
256 static void tap_socket_delev(struct tap_socket* s)
257 {
258 	if(!s) return;
259 	if(!s->ev) return;
260 	if(!s->ev_added) return;
261 	ub_event_del(s->ev);
262 	s->ev_added = 0;
263 }
264 
265 /** close the tap socket */
266 static void tap_socket_close(struct tap_socket* s)
267 {
268 	if(!s) return;
269 	if(s->fd == -1) return;
270 	sock_close(s->fd);
271 	s->fd = -1;
272 }
273 
274 /** delete tap socket */
275 static void tap_socket_delete(struct tap_socket* s)
276 {
277 	if(!s) return;
278 #ifdef HAVE_SSL
279 	SSL_CTX_free(s->sslctx);
280 #endif
281 	tap_data_list_delete(s->data_list);
282 	ub_event_free(s->ev);
283 	free(s->socketpath);
284 	free(s->ip);
285 	free(s);
286 }
287 
288 /** create new socket (unconnected, not base-added), or NULL malloc fail */
289 static struct tap_socket* tap_socket_new_local(char* socketpath,
290 	void (*ev_cb)(int, short, void*), void* data)
291 {
292 	struct tap_socket* s = calloc(1, sizeof(*s));
293 	if(!s) {
294 		log_err("malloc failure");
295 		return NULL;
296 	}
297 	s->socketpath = strdup(socketpath);
298 	if(!s->socketpath) {
299 		free(s);
300 		log_err("malloc failure");
301 		return NULL;
302 	}
303 	s->fd = -1;
304 	s->ev_cb = ev_cb;
305 	s->data = data;
306 	return s;
307 }
308 
309 /** create new socket (unconnected, not base-added), or NULL malloc fail */
310 static struct tap_socket* tap_socket_new_tcpaccept(char* ip,
311 	void (*ev_cb)(int, short, void*), void* data)
312 {
313 	struct tap_socket* s = calloc(1, sizeof(*s));
314 	if(!s) {
315 		log_err("malloc failure");
316 		return NULL;
317 	}
318 	s->ip = strdup(ip);
319 	if(!s->ip) {
320 		free(s);
321 		log_err("malloc failure");
322 		return NULL;
323 	}
324 	s->fd = -1;
325 	s->ev_cb = ev_cb;
326 	s->data = data;
327 	return s;
328 }
329 
330 /** create new socket (unconnected, not base-added), or NULL malloc fail */
331 static struct tap_socket* tap_socket_new_tlsaccept(char* ip,
332 	void (*ev_cb)(int, short, void*), void* data, char* server_key,
333 	char* server_cert, char* verifypem)
334 {
335 	struct tap_socket* s = calloc(1, sizeof(*s));
336 	if(!s) {
337 		log_err("malloc failure");
338 		return NULL;
339 	}
340 	s->ip = strdup(ip);
341 	if(!s->ip) {
342 		free(s);
343 		log_err("malloc failure");
344 		return NULL;
345 	}
346 	s->fd = -1;
347 	s->ev_cb = ev_cb;
348 	s->data = data;
349 	s->sslctx = listen_sslctx_create(server_key, server_cert, verifypem);
350 	if(!s->sslctx) {
351 		log_err("could not create ssl context");
352 		free(s->ip);
353 		free(s);
354 		return NULL;
355 	}
356 	return s;
357 }
358 
359 /** setup tcp accept socket on IP string */
360 static int make_tcp_accept(char* ip)
361 {
362 #ifdef SO_REUSEADDR
363 	int on = 1;
364 #endif
365 	struct sockaddr_storage addr;
366 	socklen_t len;
367 	int s;
368 
369 	memset(&addr, 0, sizeof(addr));
370 	len = (socklen_t)sizeof(addr);
371 	if(!extstrtoaddr(ip, &addr, &len, UNBOUND_DNS_PORT)) {
372 		log_err("could not parse IP '%s'", ip);
373 		return -1;
374 	}
375 
376 	if((s = socket(addr.ss_family, SOCK_STREAM, 0)) == -1) {
377 		log_err("can't create socket: %s", sock_strerror(errno));
378 		return -1;
379 	}
380 #ifdef SO_REUSEADDR
381 	if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&on,
382 		(socklen_t)sizeof(on)) < 0) {
383 		log_err("setsockopt(.. SO_REUSEADDR ..) failed: %s",
384 			sock_strerror(errno));
385 		sock_close(s);
386 		return -1;
387 	}
388 #endif /* SO_REUSEADDR */
389 	if(bind(s, (struct sockaddr*)&addr, len) != 0) {
390 		log_err_addr("can't bind socket", sock_strerror(errno),
391 			&addr, len);
392 		sock_close(s);
393 		return -1;
394 	}
395 	if(!fd_set_nonblock(s)) {
396 		sock_close(s);
397 		return -1;
398 	}
399 	if(listen(s, LISTEN_BACKLOG) == -1) {
400 		log_err("can't listen: %s", sock_strerror(errno));
401 		sock_close(s);
402 		return -1;
403 	}
404 	return s;
405 }
406 
407 /** setup socket on event base */
408 static int tap_socket_setup(struct tap_socket* s, struct ub_event_base* base)
409 {
410 	if(s->socketpath) {
411 		/* AF_LOCAL accept socket */
412 		s->fd = create_local_accept_sock(s->socketpath, NULL, 0);
413 		if(s->fd == -1) {
414 			log_err("could not create local socket");
415 			return 0;
416 		}
417 	} else if(s->ip || s->sslctx) {
418 		/* TCP accept socket */
419 		s->fd = make_tcp_accept(s->ip);
420 		if(s->fd == -1) {
421 			log_err("could not create tcp socket");
422 			return 0;
423 		}
424 	}
425 	s->ev = ub_event_new(base, s->fd, UB_EV_READ | UB_EV_PERSIST,
426 		s->ev_cb, s);
427 	if(!s->ev) {
428 		log_err("could not ub_event_new");
429 		return 0;
430 	}
431 	if(ub_event_add(s->ev, NULL) != 0) {
432 		log_err("could not ub_event_add");
433 		return 0;
434 	}
435 	s->ev_added = 1;
436 	return 1;
437 }
438 
439 /** add tap socket to list */
440 static int tap_socket_list_insert(struct tap_socket_list** liststart,
441 	struct tap_socket* s)
442 {
443 	struct tap_socket_list* entry = (struct tap_socket_list*)
444 		malloc(sizeof(*entry));
445 	if(!entry)
446 		return 0;
447 	entry->next = *liststart;
448 	entry->s = s;
449 	*liststart = entry;
450 	return 1;
451 }
452 
453 /** delete the list */
454 static void tap_socket_list_delete(struct tap_socket_list* list)
455 {
456 	struct tap_socket_list* e = list, *next;
457 	while(e) {
458 		next = e->next;
459 		tap_socket_delev(e->s);
460 		tap_socket_close(e->s);
461 		tap_socket_delete(e->s);
462 		free(e);
463 		e = next;
464 	}
465 }
466 
467 /** setup accept events */
468 static int tap_socket_list_addevs(struct tap_socket_list* list,
469 	struct ub_event_base* base)
470 {
471 	struct tap_socket_list* entry;
472 	for(entry = list; entry; entry = entry->next) {
473 		if(!tap_socket_setup(entry->s, base)) {
474 			log_err("could not setup socket");
475 			return 0;
476 		}
477 	}
478 	return 1;
479 }
480 
481 #ifdef USE_DNSTAP
482 /** log control frame contents */
483 static void log_control_frame(uint8_t* pkt, size_t len)
484 {
485 	char* desc;
486 	if(verbosity == 0) return;
487 	desc = fstrm_describe_control(pkt, len);
488 	if(!desc) {
489 		log_err("out of memory");
490 		return;
491 	}
492 	log_info("control frame %s", desc);
493 	free(desc);
494 }
495 
496 /** convert mtype to string */
497 static const char* mtype_to_str(enum _Dnstap__Message__Type mtype)
498 {
499 	switch(mtype) {
500 		case DNSTAP__MESSAGE__TYPE__AUTH_QUERY:
501 			return "AUTH_QUERY";
502 		case DNSTAP__MESSAGE__TYPE__AUTH_RESPONSE:
503 			return "AUTH_RESPONSE";
504 		case DNSTAP__MESSAGE__TYPE__RESOLVER_QUERY:
505 			return "RESOLVER_QUERY";
506 		case DNSTAP__MESSAGE__TYPE__RESOLVER_RESPONSE:
507 			return "RESOLVER_RESPONSE";
508 		case DNSTAP__MESSAGE__TYPE__CLIENT_QUERY:
509 			return "CLIENT_QUERY";
510 		case DNSTAP__MESSAGE__TYPE__CLIENT_RESPONSE:
511 			return "CLIENT_RESPONSE";
512 		case DNSTAP__MESSAGE__TYPE__FORWARDER_QUERY:
513 			return "FORWARDER_QUERY";
514 		case DNSTAP__MESSAGE__TYPE__FORWARDER_RESPONSE:
515 			return "FORWARDER_RESPONSE";
516 		case DNSTAP__MESSAGE__TYPE__STUB_QUERY:
517 			return "STUB_QUERY";
518 		case DNSTAP__MESSAGE__TYPE__STUB_RESPONSE:
519 			return "STUB_RESPONSE";
520 		default: break;
521 	}
522 	return "unknown_message_type";
523 }
524 
525 /** convert type address to a string ip4 or ip6, malloced or NULL on fail */
526 static char* str_of_addr(ProtobufCBinaryData address)
527 {
528 	char buf[64];
529 	socklen_t len = sizeof(buf);
530 	if(address.len == 4) {
531 		if(inet_ntop(AF_INET, address.data, buf, len)!=0)
532 			return strdup(buf);
533 	} else if(address.len == 16) {
534 		if(inet_ntop(AF_INET6, address.data, buf, len)!=0)
535 			return strdup(buf);
536 	}
537 	return NULL;
538 }
539 
540 /** convert message buffer (of dns bytes) to the first qname, type, class,
541  * malloced or NULL on fail */
542 static char* q_of_msg(ProtobufCBinaryData message)
543 {
544 	char buf[300];
545 	/* header, name, type, class minimum to get the query tuple */
546 	if(message.len < 12 + 1 + 4 + 4) return NULL;
547 	if(LDNS_QDCOUNT(message.data) < 1) return NULL;
548 	if(sldns_wire2str_rrquestion_buf(message.data+12, message.len-12,
549 		buf, sizeof(buf)) != 0) {
550 		/* remove trailing newline, tabs to spaces */
551 		/* remove the newline: */
552 		if(buf[0] != 0) buf[strlen(buf)-1]=0;
553 		/* remove first tab (before type) */
554 		if(strrchr(buf, '\t')) *strrchr(buf, '\t')=' ';
555 		/* remove second tab (before class) */
556 		if(strrchr(buf, '\t')) *strrchr(buf, '\t')=' ';
557 		return strdup(buf);
558 	}
559 	return NULL;
560 }
561 
562 /** convert possible string or hex data to string. malloced or NULL */
563 static char* possible_str(ProtobufCBinaryData str)
564 {
565 	int is_str = 1;
566 	size_t i;
567 	for(i=0; i<str.len; i++) {
568 		if(!isprint((unsigned char)str.data[i]))
569 			is_str = 0;
570 	}
571 	if(is_str) {
572 		char* res = malloc(str.len+1);
573 		if(res) {
574 			memmove(res, str.data, str.len);
575 			res[str.len] = 0;
576 			return res;
577 		}
578 	} else {
579 		const char* hex = "0123456789ABCDEF";
580 		char* res = malloc(str.len*2+1);
581 		if(res) {
582 			for(i=0; i<str.len; i++) {
583 				res[i*2] = hex[(str.data[i]&0xf0)>>4];
584 				res[i*2+1] = hex[str.data[i]&0x0f];
585 			}
586 			res[str.len*2] = 0;
587 			return res;
588 		}
589 	}
590 	return NULL;
591 }
592 
593 /** convert timeval to string, malloced or NULL */
594 static char* tv_to_str(protobuf_c_boolean has_time_sec, uint64_t time_sec,
595 	protobuf_c_boolean has_time_nsec, uint32_t time_nsec)
596 {
597 	char buf[64], buf2[256];
598 	struct timeval tv;
599 	time_t time_t_sec;
600 	memset(&tv, 0, sizeof(tv));
601 	if(has_time_sec) tv.tv_sec = time_sec;
602 	if(has_time_nsec) tv.tv_usec = time_nsec/1000;
603 
604 	buf[0]=0;
605 	time_t_sec = tv.tv_sec;
606 	(void)ctime_r(&time_t_sec, buf);
607 	snprintf(buf2, sizeof(buf2), "%u.%9.9u %s",
608 		(unsigned)time_sec, (unsigned)time_nsec, buf);
609 	return strdup(buf2);
610 }
611 
612 /** log data frame contents */
613 static void log_data_frame(uint8_t* pkt, size_t len)
614 {
615 	Dnstap__Dnstap* d = dnstap__dnstap__unpack(NULL, len, pkt);
616 	const char* mtype = NULL;
617 	char* maddr=NULL, *qinf=NULL;
618 	if(!d) {
619 		log_err("could not unpack");
620 		return;
621 	}
622 	if(d->base.descriptor != &dnstap__dnstap__descriptor) {
623 		log_err("wrong base descriptor");
624 		dnstap__dnstap__free_unpacked(d, NULL);
625 		return;
626 	}
627 	if(d->type != DNSTAP__DNSTAP__TYPE__MESSAGE) {
628 		log_err("dnstap type not type_message");
629 		dnstap__dnstap__free_unpacked(d, NULL);
630 		return;
631 	}
632 	if(d->message) {
633 		mtype = mtype_to_str(d->message->type);
634 		if(d->message->has_query_address)
635 			maddr = str_of_addr(d->message->query_address);
636 		else if(d->message->has_response_address)
637 			maddr = str_of_addr(d->message->response_address);
638 		if(d->message->has_query_message)
639 			qinf = q_of_msg(d->message->query_message);
640 		else if(d->message->has_response_message)
641 			qinf = q_of_msg(d->message->response_message);
642 
643 	} else {
644 		mtype = "nomessage";
645 	}
646 
647 	printf("%s%s%s%s%s\n", mtype, (maddr?" ":""), (maddr?maddr:""),
648 		(qinf?" ":""), (qinf?qinf:""));
649 	free(maddr);
650 	free(qinf);
651 
652 	if(longformat) {
653 		char* id=NULL, *vs=NULL;
654 		if(d->has_identity) {
655 			id=possible_str(d->identity);
656 		}
657 		if(d->has_version) {
658 			vs=possible_str(d->version);
659 		}
660 		if(id || vs)
661 			printf("identity: %s%s%s\n", (id?id:""),
662 				(id&&vs?" ":""), (vs?vs:""));
663 		free(id);
664 		free(vs);
665 
666 		if(d->message && d->message->has_query_message &&
667 			d->message->query_message.data) {
668 			char* qmsg = sldns_wire2str_pkt(
669 				d->message->query_message.data,
670 				d->message->query_message.len);
671 			if(qmsg) {
672 				printf("query_message:\n%s", qmsg);
673 				free(qmsg);
674 			}
675 		}
676 		if(d->message && d->message->has_query_time_sec) {
677 			char* qtv = tv_to_str(d->message->has_query_time_sec,
678 				d->message->query_time_sec,
679 				d->message->has_query_time_nsec,
680 				d->message->query_time_nsec);
681 			if(qtv) {
682 				printf("query_time: %s\n", qtv);
683 				free(qtv);
684 			}
685 		}
686 		if(d->message && d->message->has_response_message &&
687 			d->message->response_message.data) {
688 			char* rmsg = sldns_wire2str_pkt(
689 				d->message->response_message.data,
690 				d->message->response_message.len);
691 			if(rmsg) {
692 				printf("response_message:\n%s", rmsg);
693 				free(rmsg);
694 			}
695 		}
696 		if(d->message && d->message->has_response_time_sec) {
697 			char* rtv = tv_to_str(d->message->has_response_time_sec,
698 				d->message->response_time_sec,
699 				d->message->has_response_time_nsec,
700 				d->message->response_time_nsec);
701 			if(rtv) {
702 				printf("response_time: %s\n", rtv);
703 				free(rtv);
704 			}
705 		}
706 	}
707 	fflush(stdout);
708 	dnstap__dnstap__free_unpacked(d, NULL);
709 }
710 #endif /* USE_DNSTAP */
711 
712 /** receive bytes from fd, prints errors if bad,
713  * returns 0: closed/error, -1: continue, >0 number of bytes */
714 static ssize_t receive_bytes(struct tap_data* data, int fd, void* buf,
715 	size_t len)
716 {
717 	ssize_t ret = recv(fd, buf, len, MSG_DONTWAIT);
718 	if(ret == 0) {
719 		/* closed */
720 		if(verbosity) log_info("dnstap client stream closed from %s",
721 			(data->id?data->id:""));
722 		return 0;
723 	} else if(ret == -1) {
724 		/* error */
725 #ifndef USE_WINSOCK
726 		if(errno == EINTR || errno == EAGAIN)
727 			return -1;
728 #else /* USE_WINSOCK */
729 		if(WSAGetLastError() == WSAEINPROGRESS)
730 			return -1;
731 		if(WSAGetLastError() == WSAEWOULDBLOCK) {
732 			ub_winsock_tcp_wouldblock(data->ev, UB_EV_READ);
733 			return -1;
734 		}
735 #endif
736 		log_err("could not recv: %s", sock_strerror(errno));
737 		if(verbosity) log_info("dnstap client stream closed from %s",
738 			(data->id?data->id:""));
739 		return 0;
740 	}
741 	return ret;
742 }
743 
744 /* define routine for have_ssl only to avoid unused function warning */
745 #ifdef HAVE_SSL
746 /** set to wait briefly for a write event, for one event call */
747 static void tap_enable_brief_write(struct tap_data* data)
748 {
749 	ub_event_del(data->ev);
750 	ub_event_del_bits(data->ev, UB_EV_READ);
751 	ub_event_add_bits(data->ev, UB_EV_WRITE);
752 	if(ub_event_add(data->ev, NULL) != 0)
753 		log_err("could not ub_event_add in tap_enable_brief_write");
754 	data->ssl_brief_write = 1;
755 }
756 #endif /* HAVE_SSL */
757 
758 /* define routine for have_ssl only to avoid unused function warning */
759 #ifdef HAVE_SSL
760 /** stop the brief wait for a write event. back to reading. */
761 static void tap_disable_brief_write(struct tap_data* data)
762 {
763 	ub_event_del(data->ev);
764 	ub_event_del_bits(data->ev, UB_EV_WRITE);
765 	ub_event_add_bits(data->ev, UB_EV_READ);
766 	if(ub_event_add(data->ev, NULL) != 0)
767 		log_err("could not ub_event_add in tap_disable_brief_write");
768 	data->ssl_brief_write = 0;
769 }
770 #endif /* HAVE_SSL */
771 
772 #ifdef HAVE_SSL
773 /** receive bytes over ssl stream, prints errors if bad,
774  * returns 0: closed/error, -1: continue, >0 number of bytes */
775 static ssize_t ssl_read_bytes(struct tap_data* data, void* buf, size_t len)
776 {
777 	int r;
778 	ERR_clear_error();
779 	r = SSL_read(data->ssl, buf, len);
780 	if(r <= 0) {
781 		int want = SSL_get_error(data->ssl, r);
782 		if(want == SSL_ERROR_ZERO_RETURN) {
783 			/* closed */
784 			if(verbosity) log_info("dnstap client stream closed from %s",
785 				(data->id?data->id:""));
786 			return 0;
787 		} else if(want == SSL_ERROR_WANT_READ) {
788 			/* continue later */
789 			return -1;
790 		} else if(want == SSL_ERROR_WANT_WRITE) {
791 			/* set to briefly write */
792 			tap_enable_brief_write(data);
793 			return -1;
794 		} else if(want == SSL_ERROR_SYSCALL) {
795 #ifdef ECONNRESET
796 			if(errno == ECONNRESET && verbosity < 2)
797 				return 0; /* silence reset by peer */
798 #endif
799 			if(errno != 0)
800 				log_err("SSL_read syscall: %s",
801 					strerror(errno));
802 			if(verbosity) log_info("dnstap client stream closed from %s",
803 				(data->id?data->id:""));
804 			return 0;
805 		}
806 		log_crypto_err_io("could not SSL_read", want);
807 		if(verbosity) log_info("dnstap client stream closed from %s",
808 			(data->id?data->id:""));
809 		return 0;
810 	}
811 	return r;
812 }
813 #endif /* HAVE_SSL */
814 
815 /** receive bytes on the tap connection, prints errors if bad,
816  * returns 0: closed/error, -1: continue, >0 number of bytes */
817 static ssize_t tap_receive(struct tap_data* data, void* buf, size_t len)
818 {
819 #ifdef HAVE_SSL
820 	if(data->ssl)
821 		return ssl_read_bytes(data, buf, len);
822 #endif
823 	return receive_bytes(data, data->fd, buf, len);
824 }
825 
826 /** reply with ACCEPT control frame to bidirectional client,
827  * returns 0 on error */
828 static int reply_with_accept(struct tap_data* data)
829 {
830 #ifdef USE_DNSTAP
831 	/* len includes the escape and framelength */
832 	size_t len = 0;
833 	void* acceptframe = fstrm_create_control_frame_accept(
834 		DNSTAP_CONTENT_TYPE, &len);
835 	if(!acceptframe) {
836 		log_err("out of memory");
837 		return 0;
838 	}
839 
840 	fd_set_block(data->fd);
841 	if(data->ssl) {
842 #ifdef HAVE_SSL
843 		int r;
844 		if((r=SSL_write(data->ssl, acceptframe, len)) <= 0) {
845 			int r2;
846 			if((r2=SSL_get_error(data->ssl, r)) == SSL_ERROR_ZERO_RETURN)
847 				log_err("SSL_write, peer closed connection");
848 			else
849 				log_crypto_err_io("could not SSL_write", r2);
850 			fd_set_nonblock(data->fd);
851 			free(acceptframe);
852 			return 0;
853 		}
854 #endif
855 	} else {
856 		if(send(data->fd, acceptframe, len, 0) == -1) {
857 			log_err("send failed: %s", sock_strerror(errno));
858 			fd_set_nonblock(data->fd);
859 			free(acceptframe);
860 			return 0;
861 		}
862 	}
863 	if(verbosity) log_info("sent control frame(accept) content-type:(%s)",
864 			DNSTAP_CONTENT_TYPE);
865 
866 	fd_set_nonblock(data->fd);
867 	free(acceptframe);
868 	return 1;
869 #else
870 	log_err("no dnstap compiled, no reply");
871 	(void)data;
872 	return 0;
873 #endif
874 }
875 
876 /** reply with FINISH control frame to bidirectional client,
877  * returns 0 on error */
878 static int reply_with_finish(struct tap_data* data)
879 {
880 #ifdef USE_DNSTAP
881 	size_t len = 0;
882 	void* finishframe = fstrm_create_control_frame_finish(&len);
883 	if(!finishframe) {
884 		log_err("out of memory");
885 		return 0;
886 	}
887 
888 	fd_set_block(data->fd);
889 	if(data->ssl) {
890 #ifdef HAVE_SSL
891 		int r;
892 		if((r=SSL_write(data->ssl, finishframe, len)) <= 0) {
893 			int r2;
894 			if((r2=SSL_get_error(data->ssl, r)) == SSL_ERROR_ZERO_RETURN)
895 				log_err("SSL_write, peer closed connection");
896 			else
897 				log_crypto_err_io("could not SSL_write", r2);
898 			fd_set_nonblock(data->fd);
899 			free(finishframe);
900 			return 0;
901 		}
902 #endif
903 	} else {
904 		if(send(data->fd, finishframe, len, 0) == -1) {
905 			log_err("send failed: %s", sock_strerror(errno));
906 			fd_set_nonblock(data->fd);
907 			free(finishframe);
908 			return 0;
909 		}
910 	}
911 	if(verbosity) log_info("sent control frame(finish)");
912 
913 	fd_set_nonblock(data->fd);
914 	free(finishframe);
915 	return 1;
916 #else
917 	log_err("no dnstap compiled, no reply");
918 	(void)data;
919 	return 0;
920 #endif
921 }
922 
923 #ifdef HAVE_SSL
924 /** check SSL peer certificate, return 0 on fail */
925 static int tap_check_peer(struct tap_data* data)
926 {
927 	if((SSL_get_verify_mode(data->ssl)&SSL_VERIFY_PEER)) {
928 		/* verification */
929 		if(SSL_get_verify_result(data->ssl) == X509_V_OK) {
930 #ifdef HAVE_SSL_GET1_PEER_CERTIFICATE
931 			X509* x = SSL_get1_peer_certificate(data->ssl);
932 #else
933 			X509* x = SSL_get_peer_certificate(data->ssl);
934 #endif
935 			if(!x) {
936 				if(verbosity) log_info("SSL connection %s"
937 					" failed no certificate", data->id);
938 				return 0;
939 			}
940 			if(verbosity)
941 				log_cert(VERB_ALGO, "peer certificate", x);
942 #ifdef HAVE_SSL_GET0_PEERNAME
943 			if(SSL_get0_peername(data->ssl)) {
944 				if(verbosity) log_info("SSL connection %s "
945 					"to %s authenticated", data->id,
946 					SSL_get0_peername(data->ssl));
947 			} else {
948 #endif
949 				if(verbosity) log_info("SSL connection %s "
950 					"authenticated", data->id);
951 #ifdef HAVE_SSL_GET0_PEERNAME
952 			}
953 #endif
954 			X509_free(x);
955 		} else {
956 #ifdef HAVE_SSL_GET1_PEER_CERTIFICATE
957 			X509* x = SSL_get1_peer_certificate(data->ssl);
958 #else
959 			X509* x = SSL_get_peer_certificate(data->ssl);
960 #endif
961 			if(x) {
962 				if(verbosity)
963 					log_cert(VERB_ALGO, "peer certificate", x);
964 				X509_free(x);
965 			}
966 			if(verbosity) log_info("SSL connection %s failed: "
967 				"failed to authenticate", data->id);
968 			return 0;
969 		}
970 	} else {
971 		/* unauthenticated, the verify peer flag was not set
972 		 * in ssl when the ssl object was created from ssl_ctx */
973 		if(verbosity) log_info("SSL connection %s", data->id);
974 	}
975 	return 1;
976 }
977 #endif /* HAVE_SSL */
978 
979 #ifdef HAVE_SSL
980 /** perform SSL handshake, return 0 to wait for events, 1 if done */
981 static int tap_handshake(struct tap_data* data)
982 {
983 	int r;
984 	if(data->ssl_brief_write) {
985 		/* write condition has been satisfied, back to reading */
986 		tap_disable_brief_write(data);
987 	}
988 	if(data->ssl_handshake_done)
989 		return 1;
990 
991 	ERR_clear_error();
992 	r = SSL_do_handshake(data->ssl);
993 	if(r != 1) {
994 		int want = SSL_get_error(data->ssl, r);
995 		if(want == SSL_ERROR_WANT_READ) {
996 			return 0;
997 		} else if(want == SSL_ERROR_WANT_WRITE) {
998 			tap_enable_brief_write(data);
999 			return 0;
1000 		} else if(r == 0) {
1001 			/* closed */
1002 			tap_data_free(data, 1);
1003 			return 0;
1004 		} else if(want == SSL_ERROR_SYSCALL) {
1005 			/* SYSCALL and errno==0 means closed uncleanly */
1006 			int silent = 0;
1007 #ifdef EPIPE
1008 			if(errno == EPIPE && verbosity < 2)
1009 				silent = 1; /* silence 'broken pipe' */
1010 #endif
1011 #ifdef ECONNRESET
1012 			if(errno == ECONNRESET && verbosity < 2)
1013 				silent = 1; /* silence reset by peer */
1014 #endif
1015 			if(errno == 0)
1016 				silent = 1;
1017 			if(!silent)
1018 				log_err("SSL_handshake syscall: %s",
1019 					strerror(errno));
1020 			tap_data_free(data, 1);
1021 			return 0;
1022 		} else {
1023 			unsigned long err = ERR_get_error();
1024 			if(!squelch_err_ssl_handshake(err)) {
1025 				log_crypto_err_code("ssl handshake failed",
1026 					err);
1027 				verbose(VERB_OPS, "ssl handshake failed "
1028 					"from %s", data->id);
1029 			}
1030 			tap_data_free(data, 1);
1031 			return 0;
1032 		}
1033 	}
1034 	/* check peer verification */
1035 	data->ssl_handshake_done = 1;
1036 	if(!tap_check_peer(data)) {
1037 		/* closed */
1038 		tap_data_free(data, 1);
1039 		return 0;
1040 	}
1041 	return 1;
1042 }
1043 #endif /* HAVE_SSL */
1044 
1045 /** callback for dnstap listener */
1046 void dtio_tap_callback(int ATTR_UNUSED(fd), short ATTR_UNUSED(bits), void* arg)
1047 {
1048 	struct tap_data* data = (struct tap_data*)arg;
1049 	if(verbosity>=3) log_info("tap callback");
1050 #ifdef HAVE_SSL
1051 	if(data->ssl && (!data->ssl_handshake_done ||
1052 		data->ssl_brief_write)) {
1053 		if(!tap_handshake(data))
1054 			return;
1055 	}
1056 #endif
1057 	while(data->len_done < 4) {
1058 		uint32_t l = (uint32_t)data->len;
1059 		ssize_t ret = tap_receive(data,
1060 			((uint8_t*)&l)+data->len_done, 4-data->len_done);
1061 		if(verbosity>=4) log_info("s recv %d", (int)ret);
1062 		if(ret == 0) {
1063 			/* closed or error */
1064 			tap_data_free(data, 1);
1065 			return;
1066 		} else if(ret == -1) {
1067 			/* continue later */
1068 			return;
1069 		}
1070 		data->len_done += ret;
1071 		data->len = (size_t)l;
1072 		if(data->len_done < 4)
1073 			return; /* continue later */
1074 		data->len = (size_t)(ntohl(l));
1075 		if(verbosity>=3) log_info("length is %d", (int)data->len);
1076 		if(data->len == 0) {
1077 			/* it is a control frame */
1078 			data->control_frame = 1;
1079 			/* read controlframelen */
1080 			data->len_done = 0;
1081 		} else {
1082 			/* allocate frame size */
1083 			data->frame = calloc(1, data->len);
1084 			if(!data->frame) {
1085 				log_err("out of memory");
1086 				tap_data_free(data, 1);
1087 				return;
1088 			}
1089 		}
1090 	}
1091 
1092 	/* we want to read the full length now */
1093 	if(data->data_done < data->len) {
1094 		ssize_t r = tap_receive(data, data->frame + data->data_done,
1095 			data->len - data->data_done);
1096 		if(verbosity>=4) log_info("f recv %d", (int)r);
1097 		if(r == 0) {
1098 			/* closed or error */
1099 			tap_data_free(data, 1);
1100 			return;
1101 		} else if(r == -1) {
1102 			/* continue later */
1103 			return;
1104 		}
1105 		data->data_done += r;
1106 		if(data->data_done < data->len)
1107 			return; /* continue later */
1108 	}
1109 
1110 	/* we are done with a frame */
1111 	if(verbosity>=3) log_info("received %sframe len %d",
1112 		(data->control_frame?"control ":""), (int)data->len);
1113 #ifdef USE_DNSTAP
1114 	if(data->control_frame)
1115 		log_control_frame(data->frame, data->len);
1116 	else	log_data_frame(data->frame, data->len);
1117 #endif
1118 
1119 	if(data->len >= 4 && sldns_read_uint32(data->frame) ==
1120 		FSTRM_CONTROL_FRAME_READY) {
1121 		data->is_bidirectional = 1;
1122 		if(verbosity) log_info("bidirectional stream");
1123 		if(!reply_with_accept(data)) {
1124 			tap_data_free(data, 1);
1125 			return;
1126 		}
1127 	} else if(data->len >= 4 && sldns_read_uint32(data->frame) ==
1128 		FSTRM_CONTROL_FRAME_STOP && data->is_bidirectional) {
1129 		if(!reply_with_finish(data)) {
1130 			tap_data_free(data, 1);
1131 			return;
1132 		}
1133 	}
1134 
1135 	/* prepare for next frame */
1136 	free(data->frame);
1137 	data->frame = NULL;
1138 	data->control_frame = 0;
1139 	data->len = 0;
1140 	data->len_done = 0;
1141 	data->data_done = 0;
1142 }
1143 
1144 /** callback for main listening file descriptor */
1145 void dtio_mainfdcallback(int fd, short ATTR_UNUSED(bits), void* arg)
1146 {
1147 	struct tap_socket* tap_sock = (struct tap_socket*)arg;
1148 	struct main_tap_data* maindata = (struct main_tap_data*)
1149 		tap_sock->data;
1150 	struct tap_data* data;
1151 	char* id = NULL;
1152 	struct sockaddr_storage addr;
1153 	socklen_t addrlen = (socklen_t)sizeof(addr);
1154 	int s;
1155 	memset(&addr, 0, sizeof(addr));
1156 	s = accept(fd, (struct sockaddr*)&addr, &addrlen);
1157 	if(s == -1) {
1158 #ifndef USE_WINSOCK
1159 		/* EINTR is signal interrupt. others are closed connection. */
1160 		if(     errno == EINTR || errno == EAGAIN
1161 #ifdef EWOULDBLOCK
1162 			|| errno == EWOULDBLOCK
1163 #endif
1164 #ifdef ECONNABORTED
1165 			|| errno == ECONNABORTED
1166 #endif
1167 #ifdef EPROTO
1168 			|| errno == EPROTO
1169 #endif /* EPROTO */
1170 			)
1171 			return;
1172 #else /* USE_WINSOCK */
1173 		if(WSAGetLastError() == WSAEINPROGRESS ||
1174 			WSAGetLastError() == WSAECONNRESET)
1175 			return;
1176 		if(WSAGetLastError() == WSAEWOULDBLOCK) {
1177 			ub_winsock_tcp_wouldblock(maindata->ev, UB_EV_READ);
1178 			return;
1179 		}
1180 #endif
1181 		log_err_addr("accept failed", sock_strerror(errno), &addr,
1182 			addrlen);
1183 		return;
1184 	}
1185 	fd_set_nonblock(s);
1186 	if(verbosity) {
1187 		if(addr.ss_family == AF_LOCAL) {
1188 #ifdef HAVE_SYS_UN_H
1189 			struct sockaddr_un* usock = calloc(1, sizeof(struct sockaddr_un) + 1);
1190 			if(usock) {
1191 				socklen_t ulen = sizeof(struct sockaddr_un);
1192 				if(getsockname(fd, (struct sockaddr*)usock, &ulen) != -1) {
1193 					log_info("accepted new dnstap client from %s", usock->sun_path);
1194 					id = strdup(usock->sun_path);
1195 				} else {
1196 					log_info("accepted new dnstap client");
1197 				}
1198 				free(usock);
1199 			} else {
1200 				log_info("accepted new dnstap client");
1201 			}
1202 #endif /* HAVE_SYS_UN_H */
1203 		} else if(addr.ss_family == AF_INET ||
1204 			addr.ss_family == AF_INET6) {
1205 			char ip[256];
1206 			addr_to_str(&addr, addrlen, ip, sizeof(ip));
1207 			log_info("accepted new dnstap client from %s", ip);
1208 			id = strdup(ip);
1209 		} else {
1210 			log_info("accepted new dnstap client");
1211 		}
1212 	}
1213 
1214 	data = calloc(1, sizeof(*data));
1215 	if(!data) fatal_exit("out of memory");
1216 	data->fd = s;
1217 	data->id = id;
1218 	if(tap_sock->sslctx) {
1219 		data->ssl = incoming_ssl_fd(tap_sock->sslctx, data->fd);
1220 		if(!data->ssl) fatal_exit("could not SSL_new");
1221 	}
1222 	data->ev = ub_event_new(maindata->base, s, UB_EV_READ | UB_EV_PERSIST,
1223 		&dtio_tap_callback, data);
1224 	if(!data->ev) fatal_exit("could not ub_event_new");
1225 	if(ub_event_add(data->ev, NULL) != 0) fatal_exit("could not ub_event_add");
1226 	if(!tap_data_list_insert(&tap_sock->data_list, data))
1227 		fatal_exit("could not tap_data_list_insert");
1228 }
1229 
1230 /** setup local accept sockets */
1231 static void setup_local_list(struct main_tap_data* maindata,
1232 	struct config_strlist_head* local_list)
1233 {
1234 	struct config_strlist* item;
1235 	for(item = local_list->first; item; item = item->next) {
1236 		struct tap_socket* s;
1237 		s = tap_socket_new_local(item->str, &dtio_mainfdcallback,
1238 			maindata);
1239 		if(!s) fatal_exit("out of memory");
1240 		if(!tap_socket_list_insert(&maindata->acceptlist, s))
1241 			fatal_exit("out of memory");
1242 	}
1243 }
1244 
1245 /** setup tcp accept sockets */
1246 static void setup_tcp_list(struct main_tap_data* maindata,
1247 	struct config_strlist_head* tcp_list)
1248 {
1249 	struct config_strlist* item;
1250 	for(item = tcp_list->first; item; item = item->next) {
1251 		struct tap_socket* s;
1252 		s = tap_socket_new_tcpaccept(item->str, &dtio_mainfdcallback,
1253 			maindata);
1254 		if(!s) fatal_exit("out of memory");
1255 		if(!tap_socket_list_insert(&maindata->acceptlist, s))
1256 			fatal_exit("out of memory");
1257 	}
1258 }
1259 
1260 /** setup tls accept sockets */
1261 static void setup_tls_list(struct main_tap_data* maindata,
1262 	struct config_strlist_head* tls_list, char* server_key,
1263 	char* server_cert, char* verifypem)
1264 {
1265 	struct config_strlist* item;
1266 	for(item = tls_list->first; item; item = item->next) {
1267 		struct tap_socket* s;
1268 		s = tap_socket_new_tlsaccept(item->str, &dtio_mainfdcallback,
1269 			maindata, server_key, server_cert, verifypem);
1270 		if(!s) fatal_exit("out of memory");
1271 		if(!tap_socket_list_insert(&maindata->acceptlist, s))
1272 			fatal_exit("out of memory");
1273 	}
1274 }
1275 
1276 /** signal variable */
1277 static struct ub_event_base* sig_base = NULL;
1278 /** do we have to quit */
1279 int sig_quit = 0;
1280 /** signal handler for user quit */
1281 static RETSIGTYPE main_sigh(int sig)
1282 {
1283 	if(!sig_quit) {
1284 		char str[] = "exit on signal   \n";
1285 		str[15] = '0' + (sig/10)%10;
1286 		str[16] = '0' + sig%10;
1287 		/* simple cast to void will not silence Wunused-result */
1288 		(void)!write(STDERR_FILENO, str, strlen(str));
1289 	}
1290 	if(sig_base) {
1291 		ub_event_base_loopexit(sig_base);
1292 		sig_base = NULL;
1293 	}
1294 	sig_quit = 1;
1295 }
1296 
1297 /** setup and run the server to listen to DNSTAP messages */
1298 static void
1299 setup_and_run(struct config_strlist_head* local_list,
1300 	struct config_strlist_head* tcp_list,
1301 	struct config_strlist_head* tls_list, char* server_key,
1302 	char* server_cert, char* verifypem)
1303 {
1304 	time_t secs = 0;
1305 	struct timeval now;
1306 	struct main_tap_data* maindata;
1307 	struct ub_event_base* base;
1308 	const char *evnm="event", *evsys="", *evmethod="";
1309 
1310 	maindata = calloc(1, sizeof(*maindata));
1311 	if(!maindata) fatal_exit("out of memory");
1312 	memset(&now, 0, sizeof(now));
1313 	base = ub_default_event_base(1, &secs, &now);
1314 	if(!base) fatal_exit("could not create ub_event base");
1315 	maindata->base = base;
1316 	sig_base = base;
1317 	if(sig_quit) {
1318 		ub_event_base_free(base);
1319 		free(maindata);
1320 		return;
1321 	}
1322 	ub_get_event_sys(base, &evnm, &evsys, &evmethod);
1323 	if(verbosity) log_info("%s %s uses %s method", evnm, evsys, evmethod);
1324 
1325 	setup_local_list(maindata, local_list);
1326 	setup_tcp_list(maindata, tcp_list);
1327 	setup_tls_list(maindata, tls_list, server_key, server_cert,
1328 		verifypem);
1329 	if(!tap_socket_list_addevs(maindata->acceptlist, base))
1330 		fatal_exit("could not setup accept events");
1331 	if(verbosity) log_info("start of service");
1332 
1333 	ub_event_base_dispatch(base);
1334 	sig_base = NULL;
1335 
1336 	if(verbosity) log_info("end of service");
1337 	tap_socket_list_delete(maindata->acceptlist);
1338 	ub_event_base_free(base);
1339 	free(maindata);
1340 }
1341 
1342 /* internal unit tests */
1343 static int internal_unittest()
1344 {
1345 	/* unit test tap_data_list_try_to_free_tail() */
1346 #define unit_tap_datas_max 5
1347 	struct tap_data* datas[unit_tap_datas_max];
1348 	struct tap_data_list* list;
1349 	struct tap_socket* socket = calloc(1, sizeof(*socket));
1350 	size_t i = 0;
1351 	log_assert(socket);
1352 	log_assert(unit_tap_datas_max>2); /* needed for the test */
1353 	for(i=0; i<unit_tap_datas_max; i++) {
1354 		datas[i] = calloc(1, sizeof(struct tap_data));
1355 		log_assert(datas[i]);
1356 		log_assert(tap_data_list_insert(&socket->data_list, datas[i]));
1357 	}
1358 	/* sanity base check */
1359 	list = socket->data_list;
1360 	for(i=0; list; i++) list = list->next;
1361 	log_assert(i==unit_tap_datas_max);
1362 
1363 	/* Free the last data, tail cannot be erased */
1364 	list = socket->data_list;
1365 	while(list->next) list = list->next;
1366 	free(list->d);
1367 	list->d = NULL;
1368 	tap_data_list_try_to_free_tail(list);
1369 	list = socket->data_list;
1370 	for(i=0; list; i++) list = list->next;
1371 	log_assert(i==unit_tap_datas_max);
1372 
1373 	/* Free the third to last data, tail cannot be erased */
1374 	list = socket->data_list;
1375 	for(i=0; i<unit_tap_datas_max-3; i++) list = list->next;
1376 	free(list->d);
1377 	list->d = NULL;
1378 	tap_data_list_try_to_free_tail(list);
1379 	list = socket->data_list;
1380 	for(i=0; list; i++) list = list->next;
1381 	log_assert(i==unit_tap_datas_max);
1382 
1383 	/* Free the second to last data, try to remove tail from the third
1384 	 * again, tail (last 2) should be removed */
1385 	list = socket->data_list;
1386 	for(i=0; i<unit_tap_datas_max-2; i++) list = list->next;
1387 	free(list->d);
1388 	list->d = NULL;
1389 	list = socket->data_list;
1390 	while(list->d) list = list->next;
1391 	tap_data_list_try_to_free_tail(list);
1392 	list = socket->data_list;
1393 	for(i=0; list; i++) list = list->next;
1394 	log_assert(i==unit_tap_datas_max-2);
1395 
1396 	/* Free all the remaining data, try to remove tail from the start,
1397 	 * only the start should remain */
1398 	list = socket->data_list;
1399 	while(list) {
1400 		free(list->d);
1401 		list->d = NULL;
1402 		list = list->next;
1403 	}
1404 	tap_data_list_try_to_free_tail(socket->data_list);
1405 	list = socket->data_list;
1406 	for(i=0; list; i++) list = list->next;
1407 	log_assert(i==1);
1408 
1409 	/* clean up */
1410 	tap_data_list_delete(socket->data_list);
1411 	free(socket);
1412 
1413 	/* Start again. Add two elements */
1414 	socket = calloc(1, sizeof(*socket));
1415 	log_assert(socket);
1416 	for(i=0; i<2; i++) {
1417 		datas[i] = calloc(1, sizeof(struct tap_data));
1418 		log_assert(datas[i]);
1419 		log_assert(tap_data_list_insert(&socket->data_list, datas[i]));
1420 	}
1421 	/* sanity base check */
1422 	list = socket->data_list;
1423 	for(i=0; list; i++) list = list->next;
1424 	log_assert(i==2);
1425 
1426 	/* Free the last data, tail cannot be erased */
1427 	list = socket->data_list;
1428 	while(list->next) list = list->next;
1429 	free(list->d);
1430 	list->d = NULL;
1431 	tap_data_list_try_to_free_tail(list);
1432 	list = socket->data_list;
1433 	for(i=0; list; i++) list = list->next;
1434 	log_assert(i==2);
1435 
1436 	/* clean up */
1437 	tap_data_list_delete(socket->data_list);
1438 	free(socket);
1439 
1440 	if(log_get_lock()) {
1441 		lock_basic_destroy((lock_basic_type*)log_get_lock());
1442 	}
1443 	checklock_stop();
1444 #ifdef USE_WINSOCK
1445 	WSACleanup();
1446 #endif
1447 	return 0;
1448 }
1449 
1450 /** getopt global, in case header files fail to declare it. */
1451 extern int optind;
1452 /** getopt global, in case header files fail to declare it. */
1453 extern char* optarg;
1454 
1455 /** main program for streamtcp */
1456 int main(int argc, char** argv)
1457 {
1458 	int c;
1459 	int usessl = 0;
1460 	struct config_strlist_head local_list;
1461 	struct config_strlist_head tcp_list;
1462 	struct config_strlist_head tls_list;
1463 	char* server_key = NULL, *server_cert = NULL, *verifypem = NULL;
1464 #ifdef USE_WINSOCK
1465 	WSADATA wsa_data;
1466 	if(WSAStartup(MAKEWORD(2,2), &wsa_data) != 0) {
1467 		printf("WSAStartup failed\n");
1468 		return 1;
1469 	}
1470 #endif
1471 	if(signal(SIGINT, main_sigh) == SIG_ERR ||
1472 #ifdef SIGQUIT
1473 		signal(SIGQUIT, main_sigh) == SIG_ERR ||
1474 #endif
1475 #ifdef SIGHUP
1476 		signal(SIGHUP, main_sigh) == SIG_ERR ||
1477 #endif
1478 #ifdef SIGBREAK
1479 		signal(SIGBREAK, main_sigh) == SIG_ERR ||
1480 #endif
1481 		signal(SIGTERM, main_sigh) == SIG_ERR)
1482 		fatal_exit("could not bind to signal");
1483 	memset(&local_list, 0, sizeof(local_list));
1484 	memset(&tcp_list, 0, sizeof(tcp_list));
1485 	memset(&tls_list, 0, sizeof(tls_list));
1486 
1487 	/* lock debug start (if any) */
1488 	checklock_start();
1489 	log_ident_set("unbound-dnstap-socket");
1490 	log_init(0, 0, 0);
1491 
1492 #ifdef SIGPIPE
1493 	if(signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
1494 		perror("could not install signal handler for SIGPIPE");
1495 		return 1;
1496 	}
1497 #endif
1498 
1499 	/* command line options */
1500 	while( (c=getopt(argc, argv, "hcls:t:u:vx:y:z:")) != -1) {
1501 		switch(c) {
1502 			case 'u':
1503 				if(!cfg_strlist_append(&local_list,
1504 					strdup(optarg)))
1505 					fatal_exit("out of memory");
1506 				break;
1507 			case 's':
1508 				if(!cfg_strlist_append(&tcp_list,
1509 					strdup(optarg)))
1510 					fatal_exit("out of memory");
1511 				break;
1512 			case 't':
1513 				if(!cfg_strlist_append(&tls_list,
1514 					strdup(optarg)))
1515 					fatal_exit("out of memory");
1516 				usessl = 1;
1517 				break;
1518 			case 'x':
1519 				server_key = optarg;
1520 				usessl = 1;
1521 				break;
1522 			case 'y':
1523 				server_cert = optarg;
1524 				usessl = 1;
1525 				break;
1526 			case 'z':
1527 				verifypem = optarg;
1528 				usessl = 1;
1529 				break;
1530 			case 'l':
1531 				longformat = 1;
1532 				break;
1533 			case 'v':
1534 				verbosity++;
1535 				break;
1536 			case 'c':
1537 #ifndef UNBOUND_DEBUG
1538 				fatal_exit("-c option needs compilation with "
1539 					"--enable-debug");
1540 #endif
1541 				return internal_unittest();
1542 			case 'h':
1543 			case '?':
1544 			default:
1545 				usage(argv);
1546 		}
1547 	}
1548 	/* argc -= optind; not using further arguments */
1549 	/* argv += optind; not using further arguments */
1550 
1551 	if(usessl) {
1552 #ifdef HAVE_SSL
1553 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
1554 		ERR_load_SSL_strings();
1555 #endif
1556 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
1557 #  ifndef S_SPLINT_S
1558 		OpenSSL_add_all_algorithms();
1559 #  endif
1560 #else
1561 		OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
1562 			| OPENSSL_INIT_ADD_ALL_DIGESTS
1563 			| OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
1564 #endif
1565 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
1566 		(void)SSL_library_init();
1567 #else
1568 		(void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
1569 #endif
1570 #endif /* HAVE_SSL */
1571 	}
1572 	setup_and_run(&local_list, &tcp_list, &tls_list, server_key,
1573 		server_cert, verifypem);
1574 	config_delstrlist(local_list.first);
1575 	config_delstrlist(tcp_list.first);
1576 	config_delstrlist(tls_list.first);
1577 
1578 	if(log_get_lock()) {
1579 		lock_basic_destroy((lock_basic_type*)log_get_lock());
1580 	}
1581 	checklock_stop();
1582 #ifdef USE_WINSOCK
1583 	WSACleanup();
1584 #endif
1585 	return 0;
1586 }
1587 
1588 /***--- definitions to make fptr_wlist work. ---***/
1589 /* These are callbacks, similar to smallapp callbacks, except the debug
1590  * tool callbacks are not in it */
1591 struct tube;
1592 struct query_info;
1593 #include "util/data/packed_rrset.h"
1594 #include "daemon/worker.h"
1595 #include "daemon/remote.h"
1596 #include "util/fptr_wlist.h"
1597 #include "libunbound/context.h"
1598 
1599 void worker_handle_control_cmd(struct tube* ATTR_UNUSED(tube),
1600 	uint8_t* ATTR_UNUSED(buffer), size_t ATTR_UNUSED(len),
1601 	int ATTR_UNUSED(error), void* ATTR_UNUSED(arg))
1602 {
1603 	log_assert(0);
1604 }
1605 
1606 int worker_handle_request(struct comm_point* ATTR_UNUSED(c),
1607 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1608         struct comm_reply* ATTR_UNUSED(repinfo))
1609 {
1610 	log_assert(0);
1611 	return 0;
1612 }
1613 
1614 int worker_handle_service_reply(struct comm_point* ATTR_UNUSED(c),
1615 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1616         struct comm_reply* ATTR_UNUSED(reply_info))
1617 {
1618 	log_assert(0);
1619 	return 0;
1620 }
1621 
1622 int remote_accept_callback(struct comm_point* ATTR_UNUSED(c),
1623 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1624         struct comm_reply* ATTR_UNUSED(repinfo))
1625 {
1626 	log_assert(0);
1627 	return 0;
1628 }
1629 
1630 int remote_control_callback(struct comm_point* ATTR_UNUSED(c),
1631 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1632         struct comm_reply* ATTR_UNUSED(repinfo))
1633 {
1634 	log_assert(0);
1635 	return 0;
1636 }
1637 
1638 void worker_sighandler(int ATTR_UNUSED(sig), void* ATTR_UNUSED(arg))
1639 {
1640 	log_assert(0);
1641 }
1642 
1643 struct outbound_entry* worker_send_query(
1644 	struct query_info* ATTR_UNUSED(qinfo), uint16_t ATTR_UNUSED(flags),
1645 	int ATTR_UNUSED(dnssec), int ATTR_UNUSED(want_dnssec),
1646 	int ATTR_UNUSED(nocaps), int ATTR_UNUSED(check_ratelimit),
1647 	struct sockaddr_storage* ATTR_UNUSED(addr),
1648 	socklen_t ATTR_UNUSED(addrlen), uint8_t* ATTR_UNUSED(zone),
1649 	size_t ATTR_UNUSED(zonelen), int ATTR_UNUSED(tcp_upstream),
1650 	int ATTR_UNUSED(ssl_upstream), char* ATTR_UNUSED(tls_auth_name),
1651 	struct module_qstate* ATTR_UNUSED(q), int* ATTR_UNUSED(was_ratelimited))
1652 {
1653 	log_assert(0);
1654 	return 0;
1655 }
1656 
1657 #ifdef UB_ON_WINDOWS
1658 void
1659 worker_win_stop_cb(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev), void*
1660 	ATTR_UNUSED(arg)) {
1661 	log_assert(0);
1662 }
1663 
1664 void
1665 wsvc_cron_cb(void* ATTR_UNUSED(arg))
1666 {
1667 	log_assert(0);
1668 }
1669 #endif /* UB_ON_WINDOWS */
1670 
1671 void
1672 worker_alloc_cleanup(void* ATTR_UNUSED(arg))
1673 {
1674 	log_assert(0);
1675 }
1676 
1677 struct outbound_entry* libworker_send_query(
1678 	struct query_info* ATTR_UNUSED(qinfo), uint16_t ATTR_UNUSED(flags),
1679 	int ATTR_UNUSED(dnssec), int ATTR_UNUSED(want_dnssec),
1680 	int ATTR_UNUSED(nocaps), int ATTR_UNUSED(check_ratelimit),
1681 	struct sockaddr_storage* ATTR_UNUSED(addr),
1682 	socklen_t ATTR_UNUSED(addrlen), uint8_t* ATTR_UNUSED(zone),
1683 	size_t ATTR_UNUSED(zonelen), int ATTR_UNUSED(tcp_upstream),
1684 	int ATTR_UNUSED(ssl_upstream), char* ATTR_UNUSED(tls_auth_name),
1685 	struct module_qstate* ATTR_UNUSED(q), int* ATTR_UNUSED(was_ratelimited))
1686 {
1687 	log_assert(0);
1688 	return 0;
1689 }
1690 
1691 int libworker_handle_service_reply(struct comm_point* ATTR_UNUSED(c),
1692 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1693         struct comm_reply* ATTR_UNUSED(reply_info))
1694 {
1695 	log_assert(0);
1696 	return 0;
1697 }
1698 
1699 void libworker_handle_control_cmd(struct tube* ATTR_UNUSED(tube),
1700         uint8_t* ATTR_UNUSED(buffer), size_t ATTR_UNUSED(len),
1701         int ATTR_UNUSED(error), void* ATTR_UNUSED(arg))
1702 {
1703         log_assert(0);
1704 }
1705 
1706 void libworker_fg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
1707 	struct sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
1708 	char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
1709 {
1710 	log_assert(0);
1711 }
1712 
1713 void libworker_bg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
1714 	struct sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
1715 	char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
1716 {
1717 	log_assert(0);
1718 }
1719 
1720 void libworker_event_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
1721 	struct sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
1722 	char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
1723 {
1724 	log_assert(0);
1725 }
1726 
1727 int context_query_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
1728 {
1729 	log_assert(0);
1730 	return 0;
1731 }
1732 
1733 void worker_stat_timer_cb(void* ATTR_UNUSED(arg))
1734 {
1735 	log_assert(0);
1736 }
1737 
1738 void worker_probe_timer_cb(void* ATTR_UNUSED(arg))
1739 {
1740 	log_assert(0);
1741 }
1742 
1743 void worker_start_accept(void* ATTR_UNUSED(arg))
1744 {
1745 	log_assert(0);
1746 }
1747 
1748 void worker_stop_accept(void* ATTR_UNUSED(arg))
1749 {
1750 	log_assert(0);
1751 }
1752 
1753 /** keep track of lock id in lock-verify application */
1754 struct order_id {
1755         /** the thread id that created it */
1756         int thr;
1757         /** the instance number of creation */
1758         int instance;
1759 };
1760 
1761 int order_lock_cmp(const void* e1, const void* e2)
1762 {
1763         const struct order_id* o1 = e1;
1764         const struct order_id* o2 = e2;
1765         if(o1->thr < o2->thr) return -1;
1766         if(o1->thr > o2->thr) return 1;
1767         if(o1->instance < o2->instance) return -1;
1768         if(o1->instance > o2->instance) return 1;
1769         return 0;
1770 }
1771 
1772 int
1773 codeline_cmp(const void* a, const void* b)
1774 {
1775         return strcmp(a, b);
1776 }
1777 
1778 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
1779 {
1780         log_assert(0);
1781         return 0;
1782 }
1783 
1784 void remote_get_opt_ssl(char* ATTR_UNUSED(str), void* ATTR_UNUSED(arg))
1785 {
1786         log_assert(0);
1787 }
1788 
1789 #ifdef HAVE_NGTCP2
1790 void doq_client_event_cb(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
1791 	void* ATTR_UNUSED(arg))
1792 {
1793 	log_assert(0);
1794 }
1795 #endif
1796 
1797 #ifdef HAVE_NGTCP2
1798 void doq_client_timer_cb(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
1799 	void* ATTR_UNUSED(arg))
1800 {
1801 	log_assert(0);
1802 }
1803 #endif
1804