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 */
usage(char * argv[])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 */
tap_data_list_try_to_free_tail(struct tap_data_list * list)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 */
tap_data_free(struct tap_data * data,int free_tail)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 */
tap_data_list_insert(struct tap_data_list ** liststart,struct tap_data * d)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 */
tap_data_list_delete(struct tap_data_list * list)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 */
tap_socket_delev(struct tap_socket * s)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 */
tap_socket_close(struct tap_socket * s)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 */
tap_socket_delete(struct tap_socket * s)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 */
tap_socket_new_local(char * socketpath,void (* ev_cb)(int,short,void *),void * data)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 */
tap_socket_new_tcpaccept(char * ip,void (* ev_cb)(int,short,void *),void * data)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 */
tap_socket_new_tlsaccept(char * ip,void (* ev_cb)(int,short,void *),void * data,char * server_key,char * server_cert,char * verifypem)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 */
make_tcp_accept(char * ip)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 */
tap_socket_setup(struct tap_socket * s,struct ub_event_base * 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 */
tap_socket_list_insert(struct tap_socket_list ** liststart,struct tap_socket * s)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 */
tap_socket_list_delete(struct tap_socket_list * 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 */
tap_socket_list_addevs(struct tap_socket_list * list,struct ub_event_base * base)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 */
log_control_frame(uint8_t * pkt,size_t len)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 */
mtype_to_str(enum _Dnstap__Message__Type mtype)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 */
str_of_addr(ProtobufCBinaryData address)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 */
q_of_msg(ProtobufCBinaryData message)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 */
possible_str(ProtobufCBinaryData str)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 */
tv_to_str(protobuf_c_boolean has_time_sec,uint64_t time_sec,protobuf_c_boolean has_time_nsec,uint32_t time_nsec)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 */
log_data_frame(uint8_t * pkt,size_t len)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 */
receive_bytes(struct tap_data * data,int fd,void * buf,size_t len)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 */
tap_enable_brief_write(struct tap_data * data)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. */
tap_disable_brief_write(struct tap_data * data)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 */
ssl_read_bytes(struct tap_data * data,void * buf,size_t len)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 */
tap_receive(struct tap_data * data,void * buf,size_t len)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 */
reply_with_accept(struct tap_data * data)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 */
reply_with_finish(struct tap_data * data)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 */
tap_check_peer(struct tap_data * data)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 */
tap_handshake(struct tap_data * data)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 */
dtio_tap_callback(int ATTR_UNUSED (fd),short ATTR_UNUSED (bits),void * arg)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 */
dtio_mainfdcallback(int fd,short ATTR_UNUSED (bits),void * arg)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 = accept(fd, (struct sockaddr*)&addr, &addrlen);
1155 if(s == -1) {
1156 #ifndef USE_WINSOCK
1157 /* EINTR is signal interrupt. others are closed connection. */
1158 if( errno == EINTR || errno == EAGAIN
1159 #ifdef EWOULDBLOCK
1160 || errno == EWOULDBLOCK
1161 #endif
1162 #ifdef ECONNABORTED
1163 || errno == ECONNABORTED
1164 #endif
1165 #ifdef EPROTO
1166 || errno == EPROTO
1167 #endif /* EPROTO */
1168 )
1169 return;
1170 #else /* USE_WINSOCK */
1171 if(WSAGetLastError() == WSAEINPROGRESS ||
1172 WSAGetLastError() == WSAECONNRESET)
1173 return;
1174 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1175 ub_winsock_tcp_wouldblock(maindata->ev, UB_EV_READ);
1176 return;
1177 }
1178 #endif
1179 log_err_addr("accept failed", sock_strerror(errno), &addr,
1180 addrlen);
1181 return;
1182 }
1183 fd_set_nonblock(s);
1184 if(verbosity) {
1185 if(addr.ss_family == AF_LOCAL) {
1186 #ifdef HAVE_SYS_UN_H
1187 struct sockaddr_un* usock = calloc(1, sizeof(struct sockaddr_un) + 1);
1188 if(usock) {
1189 socklen_t ulen = sizeof(struct sockaddr_un);
1190 if(getsockname(fd, (struct sockaddr*)usock, &ulen) != -1) {
1191 log_info("accepted new dnstap client from %s", usock->sun_path);
1192 id = strdup(usock->sun_path);
1193 } else {
1194 log_info("accepted new dnstap client");
1195 }
1196 free(usock);
1197 } else {
1198 log_info("accepted new dnstap client");
1199 }
1200 #endif /* HAVE_SYS_UN_H */
1201 } else if(addr.ss_family == AF_INET ||
1202 addr.ss_family == AF_INET6) {
1203 char ip[256];
1204 addr_to_str(&addr, addrlen, ip, sizeof(ip));
1205 log_info("accepted new dnstap client from %s", ip);
1206 id = strdup(ip);
1207 } else {
1208 log_info("accepted new dnstap client");
1209 }
1210 }
1211
1212 data = calloc(1, sizeof(*data));
1213 if(!data) fatal_exit("out of memory");
1214 data->fd = s;
1215 data->id = id;
1216 if(tap_sock->sslctx) {
1217 data->ssl = incoming_ssl_fd(tap_sock->sslctx, data->fd);
1218 if(!data->ssl) fatal_exit("could not SSL_new");
1219 }
1220 data->ev = ub_event_new(maindata->base, s, UB_EV_READ | UB_EV_PERSIST,
1221 &dtio_tap_callback, data);
1222 if(!data->ev) fatal_exit("could not ub_event_new");
1223 if(ub_event_add(data->ev, NULL) != 0) fatal_exit("could not ub_event_add");
1224 if(!tap_data_list_insert(&tap_sock->data_list, data))
1225 fatal_exit("could not tap_data_list_insert");
1226 }
1227
1228 /** setup local accept sockets */
setup_local_list(struct main_tap_data * maindata,struct config_strlist_head * local_list)1229 static void setup_local_list(struct main_tap_data* maindata,
1230 struct config_strlist_head* local_list)
1231 {
1232 struct config_strlist* item;
1233 for(item = local_list->first; item; item = item->next) {
1234 struct tap_socket* s;
1235 s = tap_socket_new_local(item->str, &dtio_mainfdcallback,
1236 maindata);
1237 if(!s) fatal_exit("out of memory");
1238 if(!tap_socket_list_insert(&maindata->acceptlist, s))
1239 fatal_exit("out of memory");
1240 }
1241 }
1242
1243 /** setup tcp accept sockets */
setup_tcp_list(struct main_tap_data * maindata,struct config_strlist_head * tcp_list)1244 static void setup_tcp_list(struct main_tap_data* maindata,
1245 struct config_strlist_head* tcp_list)
1246 {
1247 struct config_strlist* item;
1248 for(item = tcp_list->first; item; item = item->next) {
1249 struct tap_socket* s;
1250 s = tap_socket_new_tcpaccept(item->str, &dtio_mainfdcallback,
1251 maindata);
1252 if(!s) fatal_exit("out of memory");
1253 if(!tap_socket_list_insert(&maindata->acceptlist, s))
1254 fatal_exit("out of memory");
1255 }
1256 }
1257
1258 /** setup tls accept sockets */
setup_tls_list(struct main_tap_data * maindata,struct config_strlist_head * tls_list,char * server_key,char * server_cert,char * verifypem)1259 static void setup_tls_list(struct main_tap_data* maindata,
1260 struct config_strlist_head* tls_list, char* server_key,
1261 char* server_cert, char* verifypem)
1262 {
1263 struct config_strlist* item;
1264 for(item = tls_list->first; item; item = item->next) {
1265 struct tap_socket* s;
1266 s = tap_socket_new_tlsaccept(item->str, &dtio_mainfdcallback,
1267 maindata, server_key, server_cert, verifypem);
1268 if(!s) fatal_exit("out of memory");
1269 if(!tap_socket_list_insert(&maindata->acceptlist, s))
1270 fatal_exit("out of memory");
1271 }
1272 }
1273
1274 /** signal variable */
1275 static struct ub_event_base* sig_base = NULL;
1276 /** do we have to quit */
1277 int sig_quit = 0;
1278 /** signal handler for user quit */
main_sigh(int sig)1279 static RETSIGTYPE main_sigh(int sig)
1280 {
1281 if(!sig_quit) {
1282 char str[] = "exit on signal \n";
1283 str[15] = '0' + (sig/10)%10;
1284 str[16] = '0' + sig%10;
1285 /* simple cast to void will not silence Wunused-result */
1286 (void)!write(STDERR_FILENO, str, strlen(str));
1287 }
1288 if(sig_base) {
1289 ub_event_base_loopexit(sig_base);
1290 sig_base = NULL;
1291 }
1292 sig_quit = 1;
1293 }
1294
1295 /** setup and run the server to listen to DNSTAP messages */
1296 static void
setup_and_run(struct config_strlist_head * local_list,struct config_strlist_head * tcp_list,struct config_strlist_head * tls_list,char * server_key,char * server_cert,char * verifypem)1297 setup_and_run(struct config_strlist_head* local_list,
1298 struct config_strlist_head* tcp_list,
1299 struct config_strlist_head* tls_list, char* server_key,
1300 char* server_cert, char* verifypem)
1301 {
1302 time_t secs = 0;
1303 struct timeval now;
1304 struct main_tap_data* maindata;
1305 struct ub_event_base* base;
1306 const char *evnm="event", *evsys="", *evmethod="";
1307
1308 maindata = calloc(1, sizeof(*maindata));
1309 if(!maindata) fatal_exit("out of memory");
1310 memset(&now, 0, sizeof(now));
1311 base = ub_default_event_base(1, &secs, &now);
1312 if(!base) fatal_exit("could not create ub_event base");
1313 maindata->base = base;
1314 sig_base = base;
1315 if(sig_quit) {
1316 ub_event_base_free(base);
1317 free(maindata);
1318 return;
1319 }
1320 ub_get_event_sys(base, &evnm, &evsys, &evmethod);
1321 if(verbosity) log_info("%s %s uses %s method", evnm, evsys, evmethod);
1322
1323 setup_local_list(maindata, local_list);
1324 setup_tcp_list(maindata, tcp_list);
1325 setup_tls_list(maindata, tls_list, server_key, server_cert,
1326 verifypem);
1327 if(!tap_socket_list_addevs(maindata->acceptlist, base))
1328 fatal_exit("could not setup accept events");
1329 if(verbosity) log_info("start of service");
1330
1331 ub_event_base_dispatch(base);
1332 sig_base = NULL;
1333
1334 if(verbosity) log_info("end of service");
1335 tap_socket_list_delete(maindata->acceptlist);
1336 ub_event_base_free(base);
1337 free(maindata);
1338 }
1339
1340 /* internal unit tests */
internal_unittest()1341 static int internal_unittest()
1342 {
1343 /* unit test tap_data_list_try_to_free_tail() */
1344 #define unit_tap_datas_max 5
1345 struct tap_data* datas[unit_tap_datas_max];
1346 struct tap_data_list* list;
1347 struct tap_socket* socket = calloc(1, sizeof(*socket));
1348 size_t i = 0;
1349 log_assert(socket);
1350 log_assert(unit_tap_datas_max>2); /* needed for the test */
1351 for(i=0; i<unit_tap_datas_max; i++) {
1352 datas[i] = calloc(1, sizeof(struct tap_data));
1353 log_assert(datas[i]);
1354 log_assert(tap_data_list_insert(&socket->data_list, datas[i]));
1355 }
1356 /* sanity base check */
1357 list = socket->data_list;
1358 for(i=0; list; i++) list = list->next;
1359 log_assert(i==unit_tap_datas_max);
1360
1361 /* Free the last data, tail cannot be erased */
1362 list = socket->data_list;
1363 while(list->next) list = list->next;
1364 free(list->d);
1365 list->d = NULL;
1366 tap_data_list_try_to_free_tail(list);
1367 list = socket->data_list;
1368 for(i=0; list; i++) list = list->next;
1369 log_assert(i==unit_tap_datas_max);
1370
1371 /* Free the third to last data, tail cannot be erased */
1372 list = socket->data_list;
1373 for(i=0; i<unit_tap_datas_max-3; i++) list = list->next;
1374 free(list->d);
1375 list->d = NULL;
1376 tap_data_list_try_to_free_tail(list);
1377 list = socket->data_list;
1378 for(i=0; list; i++) list = list->next;
1379 log_assert(i==unit_tap_datas_max);
1380
1381 /* Free the second to last data, try to remove tail from the third
1382 * again, tail (last 2) should be removed */
1383 list = socket->data_list;
1384 for(i=0; i<unit_tap_datas_max-2; i++) list = list->next;
1385 free(list->d);
1386 list->d = NULL;
1387 list = socket->data_list;
1388 while(list->d) list = list->next;
1389 tap_data_list_try_to_free_tail(list);
1390 list = socket->data_list;
1391 for(i=0; list; i++) list = list->next;
1392 log_assert(i==unit_tap_datas_max-2);
1393
1394 /* Free all the remaining data, try to remove tail from the start,
1395 * only the start should remain */
1396 list = socket->data_list;
1397 while(list) {
1398 free(list->d);
1399 list->d = NULL;
1400 list = list->next;
1401 }
1402 tap_data_list_try_to_free_tail(socket->data_list);
1403 list = socket->data_list;
1404 for(i=0; list; i++) list = list->next;
1405 log_assert(i==1);
1406
1407 /* clean up */
1408 tap_data_list_delete(socket->data_list);
1409 free(socket);
1410
1411 /* Start again. Add two elements */
1412 socket = calloc(1, sizeof(*socket));
1413 log_assert(socket);
1414 for(i=0; i<2; i++) {
1415 datas[i] = calloc(1, sizeof(struct tap_data));
1416 log_assert(datas[i]);
1417 log_assert(tap_data_list_insert(&socket->data_list, datas[i]));
1418 }
1419 /* sanity base check */
1420 list = socket->data_list;
1421 for(i=0; list; i++) list = list->next;
1422 log_assert(i==2);
1423
1424 /* Free the last data, tail cannot be erased */
1425 list = socket->data_list;
1426 while(list->next) list = list->next;
1427 free(list->d);
1428 list->d = NULL;
1429 tap_data_list_try_to_free_tail(list);
1430 list = socket->data_list;
1431 for(i=0; list; i++) list = list->next;
1432 log_assert(i==2);
1433
1434 /* clean up */
1435 tap_data_list_delete(socket->data_list);
1436 free(socket);
1437
1438 if(log_get_lock()) {
1439 lock_basic_destroy((lock_basic_type*)log_get_lock());
1440 }
1441 checklock_stop();
1442 #ifdef USE_WINSOCK
1443 WSACleanup();
1444 #endif
1445 return 0;
1446 }
1447
1448 /** getopt global, in case header files fail to declare it. */
1449 extern int optind;
1450 /** getopt global, in case header files fail to declare it. */
1451 extern char* optarg;
1452
1453 /** main program for streamtcp */
main(int argc,char ** argv)1454 int main(int argc, char** argv)
1455 {
1456 int c;
1457 int usessl = 0;
1458 struct config_strlist_head local_list;
1459 struct config_strlist_head tcp_list;
1460 struct config_strlist_head tls_list;
1461 char* server_key = NULL, *server_cert = NULL, *verifypem = NULL;
1462 #ifdef USE_WINSOCK
1463 WSADATA wsa_data;
1464 if(WSAStartup(MAKEWORD(2,2), &wsa_data) != 0) {
1465 printf("WSAStartup failed\n");
1466 return 1;
1467 }
1468 #endif
1469 if(signal(SIGINT, main_sigh) == SIG_ERR ||
1470 #ifdef SIGQUIT
1471 signal(SIGQUIT, main_sigh) == SIG_ERR ||
1472 #endif
1473 #ifdef SIGHUP
1474 signal(SIGHUP, main_sigh) == SIG_ERR ||
1475 #endif
1476 #ifdef SIGBREAK
1477 signal(SIGBREAK, main_sigh) == SIG_ERR ||
1478 #endif
1479 signal(SIGTERM, main_sigh) == SIG_ERR)
1480 fatal_exit("could not bind to signal");
1481 memset(&local_list, 0, sizeof(local_list));
1482 memset(&tcp_list, 0, sizeof(tcp_list));
1483 memset(&tls_list, 0, sizeof(tls_list));
1484
1485 /* lock debug start (if any) */
1486 checklock_start();
1487 log_ident_set("unbound-dnstap-socket");
1488 log_init(0, 0, 0);
1489
1490 #ifdef SIGPIPE
1491 if(signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
1492 perror("could not install signal handler for SIGPIPE");
1493 return 1;
1494 }
1495 #endif
1496
1497 /* command line options */
1498 while( (c=getopt(argc, argv, "hcls:t:u:vx:y:z:")) != -1) {
1499 switch(c) {
1500 case 'u':
1501 if(!cfg_strlist_append(&local_list,
1502 strdup(optarg)))
1503 fatal_exit("out of memory");
1504 break;
1505 case 's':
1506 if(!cfg_strlist_append(&tcp_list,
1507 strdup(optarg)))
1508 fatal_exit("out of memory");
1509 break;
1510 case 't':
1511 if(!cfg_strlist_append(&tls_list,
1512 strdup(optarg)))
1513 fatal_exit("out of memory");
1514 usessl = 1;
1515 break;
1516 case 'x':
1517 server_key = optarg;
1518 usessl = 1;
1519 break;
1520 case 'y':
1521 server_cert = optarg;
1522 usessl = 1;
1523 break;
1524 case 'z':
1525 verifypem = optarg;
1526 usessl = 1;
1527 break;
1528 case 'l':
1529 longformat = 1;
1530 break;
1531 case 'v':
1532 verbosity++;
1533 break;
1534 case 'c':
1535 #ifndef UNBOUND_DEBUG
1536 fatal_exit("-c option needs compilation with "
1537 "--enable-debug");
1538 #endif
1539 return internal_unittest();
1540 case 'h':
1541 case '?':
1542 default:
1543 usage(argv);
1544 }
1545 }
1546 argc -= optind;
1547 argv += optind;
1548
1549 if(usessl) {
1550 #ifdef HAVE_SSL
1551 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
1552 ERR_load_SSL_strings();
1553 #endif
1554 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
1555 # ifndef S_SPLINT_S
1556 OpenSSL_add_all_algorithms();
1557 # endif
1558 #else
1559 OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
1560 | OPENSSL_INIT_ADD_ALL_DIGESTS
1561 | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
1562 #endif
1563 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
1564 (void)SSL_library_init();
1565 #else
1566 (void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
1567 #endif
1568 #endif /* HAVE_SSL */
1569 }
1570 setup_and_run(&local_list, &tcp_list, &tls_list, server_key,
1571 server_cert, verifypem);
1572 config_delstrlist(local_list.first);
1573 config_delstrlist(tcp_list.first);
1574 config_delstrlist(tls_list.first);
1575
1576 if(log_get_lock()) {
1577 lock_basic_destroy((lock_basic_type*)log_get_lock());
1578 }
1579 checklock_stop();
1580 #ifdef USE_WINSOCK
1581 WSACleanup();
1582 #endif
1583 return 0;
1584 }
1585
1586 /***--- definitions to make fptr_wlist work. ---***/
1587 /* These are callbacks, similar to smallapp callbacks, except the debug
1588 * tool callbacks are not in it */
1589 struct tube;
1590 struct query_info;
1591 #include "util/data/packed_rrset.h"
1592 #include "daemon/worker.h"
1593 #include "daemon/remote.h"
1594 #include "util/fptr_wlist.h"
1595 #include "libunbound/context.h"
1596
worker_handle_control_cmd(struct tube * ATTR_UNUSED (tube),uint8_t * ATTR_UNUSED (buffer),size_t ATTR_UNUSED (len),int ATTR_UNUSED (error),void * ATTR_UNUSED (arg))1597 void worker_handle_control_cmd(struct tube* ATTR_UNUSED(tube),
1598 uint8_t* ATTR_UNUSED(buffer), size_t ATTR_UNUSED(len),
1599 int ATTR_UNUSED(error), void* ATTR_UNUSED(arg))
1600 {
1601 log_assert(0);
1602 }
1603
worker_handle_request(struct comm_point * ATTR_UNUSED (c),void * ATTR_UNUSED (arg),int ATTR_UNUSED (error),struct comm_reply * ATTR_UNUSED (repinfo))1604 int worker_handle_request(struct comm_point* ATTR_UNUSED(c),
1605 void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1606 struct comm_reply* ATTR_UNUSED(repinfo))
1607 {
1608 log_assert(0);
1609 return 0;
1610 }
1611
worker_handle_service_reply(struct comm_point * ATTR_UNUSED (c),void * ATTR_UNUSED (arg),int ATTR_UNUSED (error),struct comm_reply * ATTR_UNUSED (reply_info))1612 int worker_handle_service_reply(struct comm_point* ATTR_UNUSED(c),
1613 void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1614 struct comm_reply* ATTR_UNUSED(reply_info))
1615 {
1616 log_assert(0);
1617 return 0;
1618 }
1619
remote_accept_callback(struct comm_point * ATTR_UNUSED (c),void * ATTR_UNUSED (arg),int ATTR_UNUSED (error),struct comm_reply * ATTR_UNUSED (repinfo))1620 int remote_accept_callback(struct comm_point* ATTR_UNUSED(c),
1621 void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1622 struct comm_reply* ATTR_UNUSED(repinfo))
1623 {
1624 log_assert(0);
1625 return 0;
1626 }
1627
remote_control_callback(struct comm_point * ATTR_UNUSED (c),void * ATTR_UNUSED (arg),int ATTR_UNUSED (error),struct comm_reply * ATTR_UNUSED (repinfo))1628 int remote_control_callback(struct comm_point* ATTR_UNUSED(c),
1629 void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1630 struct comm_reply* ATTR_UNUSED(repinfo))
1631 {
1632 log_assert(0);
1633 return 0;
1634 }
1635
worker_sighandler(int ATTR_UNUSED (sig),void * ATTR_UNUSED (arg))1636 void worker_sighandler(int ATTR_UNUSED(sig), void* ATTR_UNUSED(arg))
1637 {
1638 log_assert(0);
1639 }
1640
worker_send_query(struct query_info * ATTR_UNUSED (qinfo),uint16_t ATTR_UNUSED (flags),int ATTR_UNUSED (dnssec),int ATTR_UNUSED (want_dnssec),int ATTR_UNUSED (nocaps),int ATTR_UNUSED (check_ratelimit),struct sockaddr_storage * ATTR_UNUSED (addr),socklen_t ATTR_UNUSED (addrlen),uint8_t * ATTR_UNUSED (zone),size_t ATTR_UNUSED (zonelen),int ATTR_UNUSED (tcp_upstream),int ATTR_UNUSED (ssl_upstream),char * ATTR_UNUSED (tls_auth_name),struct module_qstate * ATTR_UNUSED (q),int * ATTR_UNUSED (was_ratelimited))1641 struct outbound_entry* worker_send_query(
1642 struct query_info* ATTR_UNUSED(qinfo), uint16_t ATTR_UNUSED(flags),
1643 int ATTR_UNUSED(dnssec), int ATTR_UNUSED(want_dnssec),
1644 int ATTR_UNUSED(nocaps), int ATTR_UNUSED(check_ratelimit),
1645 struct sockaddr_storage* ATTR_UNUSED(addr),
1646 socklen_t ATTR_UNUSED(addrlen), uint8_t* ATTR_UNUSED(zone),
1647 size_t ATTR_UNUSED(zonelen), int ATTR_UNUSED(tcp_upstream),
1648 int ATTR_UNUSED(ssl_upstream), char* ATTR_UNUSED(tls_auth_name),
1649 struct module_qstate* ATTR_UNUSED(q), int* ATTR_UNUSED(was_ratelimited))
1650 {
1651 log_assert(0);
1652 return 0;
1653 }
1654
1655 #ifdef UB_ON_WINDOWS
1656 void
worker_win_stop_cb(int ATTR_UNUSED (fd),short ATTR_UNUSED (ev),void * ATTR_UNUSED (arg))1657 worker_win_stop_cb(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev), void*
1658 ATTR_UNUSED(arg)) {
1659 log_assert(0);
1660 }
1661
1662 void
wsvc_cron_cb(void * ATTR_UNUSED (arg))1663 wsvc_cron_cb(void* ATTR_UNUSED(arg))
1664 {
1665 log_assert(0);
1666 }
1667 #endif /* UB_ON_WINDOWS */
1668
1669 void
worker_alloc_cleanup(void * ATTR_UNUSED (arg))1670 worker_alloc_cleanup(void* ATTR_UNUSED(arg))
1671 {
1672 log_assert(0);
1673 }
1674
libworker_send_query(struct query_info * ATTR_UNUSED (qinfo),uint16_t ATTR_UNUSED (flags),int ATTR_UNUSED (dnssec),int ATTR_UNUSED (want_dnssec),int ATTR_UNUSED (nocaps),int ATTR_UNUSED (check_ratelimit),struct sockaddr_storage * ATTR_UNUSED (addr),socklen_t ATTR_UNUSED (addrlen),uint8_t * ATTR_UNUSED (zone),size_t ATTR_UNUSED (zonelen),int ATTR_UNUSED (tcp_upstream),int ATTR_UNUSED (ssl_upstream),char * ATTR_UNUSED (tls_auth_name),struct module_qstate * ATTR_UNUSED (q),int * ATTR_UNUSED (was_ratelimited))1675 struct outbound_entry* libworker_send_query(
1676 struct query_info* ATTR_UNUSED(qinfo), uint16_t ATTR_UNUSED(flags),
1677 int ATTR_UNUSED(dnssec), int ATTR_UNUSED(want_dnssec),
1678 int ATTR_UNUSED(nocaps), int ATTR_UNUSED(check_ratelimit),
1679 struct sockaddr_storage* ATTR_UNUSED(addr),
1680 socklen_t ATTR_UNUSED(addrlen), uint8_t* ATTR_UNUSED(zone),
1681 size_t ATTR_UNUSED(zonelen), int ATTR_UNUSED(tcp_upstream),
1682 int ATTR_UNUSED(ssl_upstream), char* ATTR_UNUSED(tls_auth_name),
1683 struct module_qstate* ATTR_UNUSED(q), int* ATTR_UNUSED(was_ratelimited))
1684 {
1685 log_assert(0);
1686 return 0;
1687 }
1688
libworker_handle_service_reply(struct comm_point * ATTR_UNUSED (c),void * ATTR_UNUSED (arg),int ATTR_UNUSED (error),struct comm_reply * ATTR_UNUSED (reply_info))1689 int libworker_handle_service_reply(struct comm_point* ATTR_UNUSED(c),
1690 void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1691 struct comm_reply* ATTR_UNUSED(reply_info))
1692 {
1693 log_assert(0);
1694 return 0;
1695 }
1696
libworker_handle_control_cmd(struct tube * ATTR_UNUSED (tube),uint8_t * ATTR_UNUSED (buffer),size_t ATTR_UNUSED (len),int ATTR_UNUSED (error),void * ATTR_UNUSED (arg))1697 void libworker_handle_control_cmd(struct tube* ATTR_UNUSED(tube),
1698 uint8_t* ATTR_UNUSED(buffer), size_t ATTR_UNUSED(len),
1699 int ATTR_UNUSED(error), void* ATTR_UNUSED(arg))
1700 {
1701 log_assert(0);
1702 }
1703
libworker_fg_done_cb(void * ATTR_UNUSED (arg),int ATTR_UNUSED (rcode),struct sldns_buffer * ATTR_UNUSED (buf),enum sec_status ATTR_UNUSED (s),char * ATTR_UNUSED (why_bogus),int ATTR_UNUSED (was_ratelimited))1704 void libworker_fg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
1705 struct sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
1706 char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
1707 {
1708 log_assert(0);
1709 }
1710
libworker_bg_done_cb(void * ATTR_UNUSED (arg),int ATTR_UNUSED (rcode),struct sldns_buffer * ATTR_UNUSED (buf),enum sec_status ATTR_UNUSED (s),char * ATTR_UNUSED (why_bogus),int ATTR_UNUSED (was_ratelimited))1711 void libworker_bg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
1712 struct sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
1713 char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
1714 {
1715 log_assert(0);
1716 }
1717
libworker_event_done_cb(void * ATTR_UNUSED (arg),int ATTR_UNUSED (rcode),struct sldns_buffer * ATTR_UNUSED (buf),enum sec_status ATTR_UNUSED (s),char * ATTR_UNUSED (why_bogus),int ATTR_UNUSED (was_ratelimited))1718 void libworker_event_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
1719 struct sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
1720 char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
1721 {
1722 log_assert(0);
1723 }
1724
context_query_cmp(const void * ATTR_UNUSED (a),const void * ATTR_UNUSED (b))1725 int context_query_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
1726 {
1727 log_assert(0);
1728 return 0;
1729 }
1730
worker_stat_timer_cb(void * ATTR_UNUSED (arg))1731 void worker_stat_timer_cb(void* ATTR_UNUSED(arg))
1732 {
1733 log_assert(0);
1734 }
1735
worker_probe_timer_cb(void * ATTR_UNUSED (arg))1736 void worker_probe_timer_cb(void* ATTR_UNUSED(arg))
1737 {
1738 log_assert(0);
1739 }
1740
worker_start_accept(void * ATTR_UNUSED (arg))1741 void worker_start_accept(void* ATTR_UNUSED(arg))
1742 {
1743 log_assert(0);
1744 }
1745
worker_stop_accept(void * ATTR_UNUSED (arg))1746 void worker_stop_accept(void* ATTR_UNUSED(arg))
1747 {
1748 log_assert(0);
1749 }
1750
1751 /** keep track of lock id in lock-verify application */
1752 struct order_id {
1753 /** the thread id that created it */
1754 int thr;
1755 /** the instance number of creation */
1756 int instance;
1757 };
1758
order_lock_cmp(const void * e1,const void * e2)1759 int order_lock_cmp(const void* e1, const void* e2)
1760 {
1761 const struct order_id* o1 = e1;
1762 const struct order_id* o2 = e2;
1763 if(o1->thr < o2->thr) return -1;
1764 if(o1->thr > o2->thr) return 1;
1765 if(o1->instance < o2->instance) return -1;
1766 if(o1->instance > o2->instance) return 1;
1767 return 0;
1768 }
1769
1770 int
codeline_cmp(const void * a,const void * b)1771 codeline_cmp(const void* a, const void* b)
1772 {
1773 return strcmp(a, b);
1774 }
1775
replay_var_compare(const void * ATTR_UNUSED (a),const void * ATTR_UNUSED (b))1776 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
1777 {
1778 log_assert(0);
1779 return 0;
1780 }
1781
remote_get_opt_ssl(char * ATTR_UNUSED (str),void * ATTR_UNUSED (arg))1782 void remote_get_opt_ssl(char* ATTR_UNUSED(str), void* ATTR_UNUSED(arg))
1783 {
1784 log_assert(0);
1785 }
1786