2 * dnstap/unbound-dnstap-socket.c - debug program that listens for DNSTAP logs.
4 * Copyright (c) 2020, NLnet Labs. All rights reserved.
6 * This software is open source.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
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.
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.
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.
39 * This program listens on a DNSTAP socket for logged messages.
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"
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"
66 #include <protobuf-c/protobuf-c.h>
67 #include "dnstap/dnstap.pb-c.h"
68 #endif /* USE_DNSTAP */
69 #include "util/config_file.h"
71 /** listen backlog on TCP connections for dnstap logs */
72 #define LISTEN_BACKLOG 16
74 /** usage information for streamtcp */
75 static void usage(char* argv[])
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("-h this help text\n");
92 /** long format option, for multiline printout per message */
93 static int longformat = 0;
95 struct tap_socket_list;
97 /** main tap callback data */
98 struct main_tap_data {
99 /** the event base (to loopexit) */
100 struct ub_event_base* base;
101 /** the list of accept sockets */
102 struct tap_socket_list* acceptlist;
105 /** tap callback variables */
111 /** the SSL for TLS streams */
113 /** is the ssl handshake done */
114 int ssl_handshake_done;
115 /** we are briefly waiting to write (in the struct event) */
117 /** string that identifies the socket (or NULL), like IP address */
119 /** have we read the length, and how many bytes of it */
121 /** have we read the data, and how many bytes of it */
123 /** are we reading a control frame */
125 /** are we bi-directional (if false, uni-directional) */
126 int is_bidirectional;
127 /** data of the frame */
129 /** length of this frame */
133 /** list of sockets */
134 struct tap_socket_list {
136 struct tap_socket_list* next;
138 struct tap_socket* s;
145 /** the event for it */
147 /** has the event been added */
149 /** the callback, for the event, ev_cb(fd, bits, arg) */
150 void (*ev_cb)(int, short, void*);
151 /** data element, (arg for the tap_socket struct) */
153 /** socketpath, if this is an AF_LOCAL socket */
155 /** IP, if this is a TCP socket */
157 /** for a TLS socket, the tls context */
161 /** del the tap event */
162 static void tap_socket_delev(struct tap_socket* s)
166 if(!s->ev_added) return;
171 /** close the tap socket */
172 static void tap_socket_close(struct tap_socket* s)
175 if(s->fd == -1) return;
180 /** delete tap socket */
181 static void tap_socket_delete(struct tap_socket* s)
185 SSL_CTX_free(s->sslctx);
187 ub_event_free(s->ev);
193 /** create new socket (unconnected, not base-added), or NULL malloc fail */
194 static struct tap_socket* tap_socket_new_local(char* socketpath,
195 void (*ev_cb)(int, short, void*), void* data)
197 struct tap_socket* s = calloc(1, sizeof(*s));
199 log_err("malloc failure");
202 s->socketpath = strdup(socketpath);
205 log_err("malloc failure");
214 /** create new socket (unconnected, not base-added), or NULL malloc fail */
215 static struct tap_socket* tap_socket_new_tcpaccept(char* ip,
216 void (*ev_cb)(int, short, void*), void* data)
218 struct tap_socket* s = calloc(1, sizeof(*s));
220 log_err("malloc failure");
226 log_err("malloc failure");
235 /** create new socket (unconnected, not base-added), or NULL malloc fail */
236 static struct tap_socket* tap_socket_new_tlsaccept(char* ip,
237 void (*ev_cb)(int, short, void*), void* data, char* server_key,
238 char* server_cert, char* verifypem)
240 struct tap_socket* s = calloc(1, sizeof(*s));
242 log_err("malloc failure");
248 log_err("malloc failure");
254 s->sslctx = listen_sslctx_create(server_key, server_cert, verifypem);
256 log_err("could not create ssl context");
264 /** setup tcp accept socket on IP string */
265 static int make_tcp_accept(char* ip)
270 struct sockaddr_storage addr;
274 memset(&addr, 0, sizeof(addr));
275 len = (socklen_t)sizeof(addr);
276 if(!extstrtoaddr(ip, &addr, &len, UNBOUND_DNS_PORT)) {
277 log_err("could not parse IP '%s'", ip);
281 if((s = socket(addr.ss_family, SOCK_STREAM, 0)) == -1) {
282 log_err("can't create socket: %s", sock_strerror(errno));
286 if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&on,
287 (socklen_t)sizeof(on)) < 0) {
288 log_err("setsockopt(.. SO_REUSEADDR ..) failed: %s",
289 sock_strerror(errno));
293 #endif /* SO_REUSEADDR */
294 if(bind(s, (struct sockaddr*)&addr, len) != 0) {
295 log_err_addr("can't bind socket", sock_strerror(errno),
300 if(!fd_set_nonblock(s)) {
304 if(listen(s, LISTEN_BACKLOG) == -1) {
305 log_err("can't listen: %s", sock_strerror(errno));
312 /** setup socket on event base */
313 static int tap_socket_setup(struct tap_socket* s, struct ub_event_base* base)
316 /* AF_LOCAL accept socket */
317 s->fd = create_local_accept_sock(s->socketpath, NULL, 0);
319 log_err("could not create local socket");
322 } else if(s->ip || s->sslctx) {
323 /* TCP accept socket */
324 s->fd = make_tcp_accept(s->ip);
326 log_err("could not create tcp socket");
330 s->ev = ub_event_new(base, s->fd, UB_EV_READ | UB_EV_PERSIST,
333 log_err("could not ub_event_new");
336 if(ub_event_add(s->ev, NULL) != 0) {
337 log_err("could not ub_event_add");
344 /** add tap socket to list */
345 static int tap_socket_list_insert(struct tap_socket_list** liststart,
346 struct tap_socket* s)
348 struct tap_socket_list* entry = (struct tap_socket_list*)
349 malloc(sizeof(*entry));
352 entry->next = *liststart;
358 /** delete the list */
359 static void tap_socket_list_delete(struct tap_socket_list* list)
361 struct tap_socket_list* e = list, *next;
364 tap_socket_delev(e->s);
365 tap_socket_close(e->s);
366 tap_socket_delete(e->s);
372 /** setup accept events */
373 static int tap_socket_list_addevs(struct tap_socket_list* list,
374 struct ub_event_base* base)
376 struct tap_socket_list* entry;
377 for(entry = list; entry; entry = entry->next) {
378 if(!tap_socket_setup(entry->s, base)) {
379 log_err("could not setup socket");
387 /** log control frame contents */
388 static void log_control_frame(uint8_t* pkt, size_t len)
391 if(verbosity == 0) return;
392 desc = fstrm_describe_control(pkt, len);
394 log_err("out of memory");
397 log_info("control frame %s", desc);
401 /** convert mtype to string */
402 static const char* mtype_to_str(enum _Dnstap__Message__Type mtype)
405 case DNSTAP__MESSAGE__TYPE__AUTH_QUERY:
407 case DNSTAP__MESSAGE__TYPE__AUTH_RESPONSE:
408 return "AUTH_RESPONSE";
409 case DNSTAP__MESSAGE__TYPE__RESOLVER_QUERY:
410 return "RESOLVER_QUERY";
411 case DNSTAP__MESSAGE__TYPE__RESOLVER_RESPONSE:
412 return "RESOLVER_RESPONSE";
413 case DNSTAP__MESSAGE__TYPE__CLIENT_QUERY:
414 return "CLIENT_QUERY";
415 case DNSTAP__MESSAGE__TYPE__CLIENT_RESPONSE:
416 return "CLIENT_RESPONSE";
417 case DNSTAP__MESSAGE__TYPE__FORWARDER_QUERY:
418 return "FORWARDER_QUERY";
419 case DNSTAP__MESSAGE__TYPE__FORWARDER_RESPONSE:
420 return "FORWARDER_RESPONSE";
421 case DNSTAP__MESSAGE__TYPE__STUB_QUERY:
423 case DNSTAP__MESSAGE__TYPE__STUB_RESPONSE:
424 return "STUB_RESPONSE";
427 return "unknown_message_type";
430 /** convert type address to a string ip4 or ip6, malloced or NULL on fail */
431 static char* str_of_addr(ProtobufCBinaryData address)
434 socklen_t len = sizeof(buf);
435 if(address.len == 4) {
436 if(inet_ntop(AF_INET, address.data, buf, len)!=0)
438 } else if(address.len == 16) {
439 if(inet_ntop(AF_INET6, address.data, buf, len)!=0)
445 /** convert message buffer (of dns bytes) to the first qname, type, class,
446 * malloced or NULL on fail */
447 static char* q_of_msg(ProtobufCBinaryData message)
450 /* header, name, type, class minimum to get the query tuple */
451 if(message.len < 12 + 1 + 4 + 4) return NULL;
452 if(LDNS_QDCOUNT(message.data) < 1) return NULL;
453 if(sldns_wire2str_rrquestion_buf(message.data+12, message.len-12,
454 buf, sizeof(buf)) != 0) {
455 /* remove trailing newline, tabs to spaces */
456 /* remove the newline: */
457 if(buf[0] != 0) buf[strlen(buf)-1]=0;
458 /* remove first tab (before type) */
459 if(strrchr(buf, '\t')) *strrchr(buf, '\t')=' ';
460 /* remove second tab (before class) */
461 if(strrchr(buf, '\t')) *strrchr(buf, '\t')=' ';
467 /** convert possible string or hex data to string. malloced or NULL */
468 static char* possible_str(ProtobufCBinaryData str)
472 for(i=0; i<str.len; i++) {
473 if(!isprint((unsigned char)str.data[i]))
477 char* res = malloc(str.len+1);
479 memmove(res, str.data, str.len);
484 const char* hex = "0123456789ABCDEF";
485 char* res = malloc(str.len*2+1);
487 for(i=0; i<str.len; i++) {
488 res[i*2] = hex[(str.data[i]&0xf0)>>4];
489 res[i*2+1] = hex[str.data[i]&0x0f];
498 /** convert timeval to string, malloced or NULL */
499 static char* tv_to_str(protobuf_c_boolean has_time_sec, uint64_t time_sec,
500 protobuf_c_boolean has_time_nsec, uint32_t time_nsec)
502 char buf[64], buf2[256];
505 memset(&tv, 0, sizeof(tv));
506 if(has_time_sec) tv.tv_sec = time_sec;
507 if(has_time_nsec) tv.tv_usec = time_nsec/1000;
510 time_t_sec = tv.tv_sec;
511 (void)ctime_r(&time_t_sec, buf);
512 snprintf(buf2, sizeof(buf2), "%u.%9.9u %s",
513 (unsigned)time_sec, (unsigned)time_nsec, buf);
517 /** log data frame contents */
518 static void log_data_frame(uint8_t* pkt, size_t len)
520 Dnstap__Dnstap* d = dnstap__dnstap__unpack(NULL, len, pkt);
521 const char* mtype = NULL;
522 char* maddr=NULL, *qinf=NULL;
524 log_err("could not unpack");
527 if(d->base.descriptor != &dnstap__dnstap__descriptor) {
528 log_err("wrong base descriptor");
529 dnstap__dnstap__free_unpacked(d, NULL);
532 if(d->type != DNSTAP__DNSTAP__TYPE__MESSAGE) {
533 log_err("dnstap type not type_message");
534 dnstap__dnstap__free_unpacked(d, NULL);
538 mtype = mtype_to_str(d->message->type);
539 if(d->message->has_query_address)
540 maddr = str_of_addr(d->message->query_address);
541 else if(d->message->has_response_address)
542 maddr = str_of_addr(d->message->response_address);
543 if(d->message->has_query_message)
544 qinf = q_of_msg(d->message->query_message);
545 else if(d->message->has_response_message)
546 qinf = q_of_msg(d->message->response_message);
552 printf("%s%s%s%s%s\n", mtype, (maddr?" ":""), (maddr?maddr:""),
553 (qinf?" ":""), (qinf?qinf:""));
558 char* id=NULL, *vs=NULL;
559 if(d->has_identity) {
560 id=possible_str(d->identity);
563 vs=possible_str(d->version);
566 printf("identity: %s%s%s\n", (id?id:""),
567 (id&&vs?" ":""), (vs?vs:""));
571 if(d->message && d->message->has_query_message &&
572 d->message->query_message.data) {
573 char* qmsg = sldns_wire2str_pkt(
574 d->message->query_message.data,
575 d->message->query_message.len);
577 printf("query_message:\n%s", qmsg);
581 if(d->message && d->message->has_query_time_sec) {
582 char* qtv = tv_to_str(d->message->has_query_time_sec,
583 d->message->query_time_sec,
584 d->message->has_query_time_nsec,
585 d->message->query_time_nsec);
587 printf("query_time: %s\n", qtv);
591 if(d->message && d->message->has_response_message &&
592 d->message->response_message.data) {
593 char* rmsg = sldns_wire2str_pkt(
594 d->message->response_message.data,
595 d->message->response_message.len);
597 printf("response_message:\n%s", rmsg);
601 if(d->message && d->message->has_response_time_sec) {
602 char* rtv = tv_to_str(d->message->has_response_time_sec,
603 d->message->response_time_sec,
604 d->message->has_response_time_nsec,
605 d->message->response_time_nsec);
607 printf("response_time: %s\n", rtv);
613 dnstap__dnstap__free_unpacked(d, NULL);
615 #endif /* USE_DNSTAP */
617 /** receive bytes from fd, prints errors if bad,
618 * returns 0: closed/error, -1: continue, >0 number of bytes */
619 static ssize_t receive_bytes(struct tap_data* data, int fd, void* buf,
622 ssize_t ret = recv(fd, buf, len, MSG_DONTWAIT);
625 if(verbosity) log_info("dnstap client stream closed from %s",
626 (data->id?data->id:""));
628 } else if(ret == -1) {
631 if(errno == EINTR || errno == EAGAIN)
633 #else /* USE_WINSOCK */
634 if(WSAGetLastError() == WSAEINPROGRESS)
636 if(WSAGetLastError() == WSAEWOULDBLOCK) {
637 ub_winsock_tcp_wouldblock(data->ev, UB_EV_READ);
641 log_err("could not recv: %s", sock_strerror(errno));
642 if(verbosity) log_info("dnstap client stream closed from %s",
643 (data->id?data->id:""));
649 /* define routine for have_ssl only to avoid unused function warning */
651 /** set to wait briefly for a write event, for one event call */
652 static void tap_enable_brief_write(struct tap_data* data)
654 ub_event_del(data->ev);
655 ub_event_del_bits(data->ev, UB_EV_READ);
656 ub_event_add_bits(data->ev, UB_EV_WRITE);
657 if(ub_event_add(data->ev, NULL) != 0)
658 log_err("could not ub_event_add in tap_enable_brief_write");
659 data->ssl_brief_write = 1;
661 #endif /* HAVE_SSL */
663 /* define routine for have_ssl only to avoid unused function warning */
665 /** stop the brief wait for a write event. back to reading. */
666 static void tap_disable_brief_write(struct tap_data* data)
668 ub_event_del(data->ev);
669 ub_event_del_bits(data->ev, UB_EV_WRITE);
670 ub_event_add_bits(data->ev, UB_EV_READ);
671 if(ub_event_add(data->ev, NULL) != 0)
672 log_err("could not ub_event_add in tap_disable_brief_write");
673 data->ssl_brief_write = 0;
675 #endif /* HAVE_SSL */
678 /** receive bytes over ssl stream, prints errors if bad,
679 * returns 0: closed/error, -1: continue, >0 number of bytes */
680 static ssize_t ssl_read_bytes(struct tap_data* data, void* buf, size_t len)
684 r = SSL_read(data->ssl, buf, len);
686 int want = SSL_get_error(data->ssl, r);
687 if(want == SSL_ERROR_ZERO_RETURN) {
689 if(verbosity) log_info("dnstap client stream closed from %s",
690 (data->id?data->id:""));
692 } else if(want == SSL_ERROR_WANT_READ) {
695 } else if(want == SSL_ERROR_WANT_WRITE) {
696 /* set to briefly write */
697 tap_enable_brief_write(data);
699 } else if(want == SSL_ERROR_SYSCALL) {
701 if(errno == ECONNRESET && verbosity < 2)
702 return 0; /* silence reset by peer */
705 log_err("SSL_read syscall: %s",
707 if(verbosity) log_info("dnstap client stream closed from %s",
708 (data->id?data->id:""));
711 log_crypto_err_io("could not SSL_read", want);
712 if(verbosity) log_info("dnstap client stream closed from %s",
713 (data->id?data->id:""));
718 #endif /* HAVE_SSL */
720 /** receive bytes on the tap connection, prints errors if bad,
721 * returns 0: closed/error, -1: continue, >0 number of bytes */
722 static ssize_t tap_receive(struct tap_data* data, void* buf, size_t len)
726 return ssl_read_bytes(data, buf, len);
728 return receive_bytes(data, data->fd, buf, len);
731 /** delete the tap structure */
732 static void tap_data_free(struct tap_data* data)
734 ub_event_del(data->ev);
735 ub_event_free(data->ev);
745 /** reply with ACCEPT control frame to bidirectional client,
746 * returns 0 on error */
747 static int reply_with_accept(struct tap_data* data)
750 /* len includes the escape and framelength */
753 void* acceptframe = fstrm_create_control_frame_accept(
754 DNSTAP_CONTENT_TYPE, &len);
756 log_err("out of memory");
760 fd_set_block(data->fd);
762 if((r=SSL_write(data->ssl, acceptframe, len)) <= 0) {
764 if((r2=SSL_get_error(data->ssl, r)) == SSL_ERROR_ZERO_RETURN)
765 log_err("SSL_write, peer closed connection");
767 log_crypto_err_io("could not SSL_write", r2);
768 fd_set_nonblock(data->fd);
773 if(send(data->fd, acceptframe, len, 0) == -1) {
774 log_err("send failed: %s", sock_strerror(errno));
775 fd_set_nonblock(data->fd);
780 if(verbosity) log_info("sent control frame(accept) content-type:(%s)",
781 DNSTAP_CONTENT_TYPE);
783 fd_set_nonblock(data->fd);
787 log_err("no dnstap compiled, no reply");
793 /** reply with FINISH control frame to bidirectional client,
794 * returns 0 on error */
795 static int reply_with_finish(struct tap_data* data)
799 void* finishframe = fstrm_create_control_frame_finish(&len);
801 log_err("out of memory");
805 fd_set_block(data->fd);
808 if((r=SSL_write(data->ssl, finishframe, len)) <= 0) {
810 if((r2=SSL_get_error(data->ssl, r)) == SSL_ERROR_ZERO_RETURN)
811 log_err("SSL_write, peer closed connection");
813 log_crypto_err_io("could not SSL_write", r2);
814 fd_set_nonblock(data->fd);
819 if(send(data->fd, finishframe, len, 0) == -1) {
820 log_err("send failed: %s", sock_strerror(errno));
821 fd_set_nonblock(data->fd);
826 if(verbosity) log_info("sent control frame(finish)");
828 fd_set_nonblock(data->fd);
832 log_err("no dnstap compiled, no reply");
839 /** check SSL peer certificate, return 0 on fail */
840 static int tap_check_peer(struct tap_data* data)
842 if((SSL_get_verify_mode(data->ssl)&SSL_VERIFY_PEER)) {
844 if(SSL_get_verify_result(data->ssl) == X509_V_OK) {
845 X509* x = SSL_get_peer_certificate(data->ssl);
847 if(verbosity) log_info("SSL connection %s"
848 " failed no certificate", data->id);
852 log_cert(VERB_ALGO, "peer certificate", x);
853 #ifdef HAVE_SSL_GET0_PEERNAME
854 if(SSL_get0_peername(data->ssl)) {
855 if(verbosity) log_info("SSL connection %s "
856 "to %s authenticated", data->id,
857 SSL_get0_peername(data->ssl));
860 if(verbosity) log_info("SSL connection %s "
861 "authenticated", data->id);
862 #ifdef HAVE_SSL_GET0_PEERNAME
867 X509* x = SSL_get_peer_certificate(data->ssl);
870 log_cert(VERB_ALGO, "peer certificate", x);
873 if(verbosity) log_info("SSL connection %s failed: "
874 "failed to authenticate", data->id);
878 /* unauthenticated, the verify peer flag was not set
879 * in ssl when the ssl object was created from ssl_ctx */
880 if(verbosity) log_info("SSL connection %s", data->id);
884 #endif /* HAVE_SSL */
887 /** perform SSL handshake, return 0 to wait for events, 1 if done */
888 static int tap_handshake(struct tap_data* data)
891 if(data->ssl_brief_write) {
892 /* write condition has been satisfied, back to reading */
893 tap_disable_brief_write(data);
895 if(data->ssl_handshake_done)
899 r = SSL_do_handshake(data->ssl);
901 int want = SSL_get_error(data->ssl, r);
902 if(want == SSL_ERROR_WANT_READ) {
904 } else if(want == SSL_ERROR_WANT_WRITE) {
905 tap_enable_brief_write(data);
911 } else if(want == SSL_ERROR_SYSCALL) {
912 /* SYSCALL and errno==0 means closed uncleanly */
915 if(errno == EPIPE && verbosity < 2)
916 silent = 1; /* silence 'broken pipe' */
919 if(errno == ECONNRESET && verbosity < 2)
920 silent = 1; /* silence reset by peer */
925 log_err("SSL_handshake syscall: %s",
930 unsigned long err = ERR_get_error();
931 if(!squelch_err_ssl_handshake(err)) {
932 log_crypto_err_code("ssl handshake failed",
934 verbose(VERB_OPS, "ssl handshake failed "
935 "from %s", data->id);
941 /* check peer verification */
942 data->ssl_handshake_done = 1;
943 if(!tap_check_peer(data)) {
950 #endif /* HAVE_SSL */
952 /** callback for dnstap listener */
953 void dtio_tap_callback(int ATTR_UNUSED(fd), short ATTR_UNUSED(bits), void* arg)
955 struct tap_data* data = (struct tap_data*)arg;
956 if(verbosity>=3) log_info("tap callback");
958 if(data->ssl && (!data->ssl_handshake_done ||
959 data->ssl_brief_write)) {
960 if(!tap_handshake(data))
964 while(data->len_done < 4) {
965 uint32_t l = (uint32_t)data->len;
966 ssize_t ret = tap_receive(data,
967 ((uint8_t*)&l)+data->len_done, 4-data->len_done);
968 if(verbosity>=4) log_info("s recv %d", (int)ret);
970 /* closed or error */
973 } else if(ret == -1) {
977 data->len_done += ret;
978 data->len = (size_t)l;
979 if(data->len_done < 4)
980 return; /* continue later */
981 data->len = (size_t)(ntohl(l));
982 if(verbosity>=3) log_info("length is %d", (int)data->len);
984 /* it is a control frame */
985 data->control_frame = 1;
986 /* read controlframelen */
989 /* allocate frame size */
990 data->frame = calloc(1, data->len);
992 log_err("out of memory");
999 /* we want to read the full length now */
1000 if(data->data_done < data->len) {
1001 ssize_t r = tap_receive(data, data->frame + data->data_done,
1002 data->len - data->data_done);
1003 if(verbosity>=4) log_info("f recv %d", (int)r);
1005 /* closed or error */
1006 tap_data_free(data);
1008 } else if(r == -1) {
1009 /* continue later */
1012 data->data_done += r;
1013 if(data->data_done < data->len)
1014 return; /* continue later */
1017 /* we are done with a frame */
1018 if(verbosity>=3) log_info("received %sframe len %d",
1019 (data->control_frame?"control ":""), (int)data->len);
1021 if(data->control_frame)
1022 log_control_frame(data->frame, data->len);
1023 else log_data_frame(data->frame, data->len);
1026 if(data->len >= 4 && sldns_read_uint32(data->frame) ==
1027 FSTRM_CONTROL_FRAME_READY) {
1028 data->is_bidirectional = 1;
1029 if(verbosity) log_info("bidirectional stream");
1030 if(!reply_with_accept(data)) {
1031 tap_data_free(data);
1034 } else if(data->len >= 4 && sldns_read_uint32(data->frame) ==
1035 FSTRM_CONTROL_FRAME_STOP && data->is_bidirectional) {
1036 if(!reply_with_finish(data)) {
1037 tap_data_free(data);
1042 /* prepare for next frame */
1045 data->control_frame = 0;
1048 data->data_done = 0;
1052 /** callback for main listening file descriptor */
1053 void dtio_mainfdcallback(int fd, short ATTR_UNUSED(bits), void* arg)
1055 struct tap_socket* tap_sock = (struct tap_socket*)arg;
1056 struct main_tap_data* maindata = (struct main_tap_data*)
1058 struct tap_data* data;
1060 struct sockaddr_storage addr;
1061 socklen_t addrlen = (socklen_t)sizeof(addr);
1062 int s = accept(fd, (struct sockaddr*)&addr, &addrlen);
1065 /* EINTR is signal interrupt. others are closed connection. */
1066 if( errno == EINTR || errno == EAGAIN
1068 || errno == EWOULDBLOCK
1071 || errno == ECONNABORTED
1078 #else /* USE_WINSOCK */
1079 if(WSAGetLastError() == WSAEINPROGRESS ||
1080 WSAGetLastError() == WSAECONNRESET)
1082 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1083 ub_winsock_tcp_wouldblock(maindata->ev, UB_EV_READ);
1087 log_err_addr("accept failed", sock_strerror(errno), &addr,
1093 if(addr.ss_family == AF_LOCAL) {
1094 #ifdef HAVE_SYS_UN_H
1095 struct sockaddr_un* usock = calloc(1, sizeof(struct sockaddr_un) + 1);
1097 socklen_t ulen = sizeof(struct sockaddr_un);
1098 if(getsockname(fd, (struct sockaddr*)usock, &ulen) != -1) {
1099 log_info("accepted new dnstap client from %s", usock->sun_path);
1100 id = strdup(usock->sun_path);
1102 log_info("accepted new dnstap client");
1106 log_info("accepted new dnstap client");
1108 #endif /* HAVE_SYS_UN_H */
1109 } else if(addr.ss_family == AF_INET ||
1110 addr.ss_family == AF_INET6) {
1112 addr_to_str(&addr, addrlen, ip, sizeof(ip));
1113 log_info("accepted new dnstap client from %s", ip);
1116 log_info("accepted new dnstap client");
1120 data = calloc(1, sizeof(*data));
1121 if(!data) fatal_exit("out of memory");
1124 if(tap_sock->sslctx) {
1125 data->ssl = incoming_ssl_fd(tap_sock->sslctx, data->fd);
1126 if(!data->ssl) fatal_exit("could not SSL_new");
1128 data->ev = ub_event_new(maindata->base, s, UB_EV_READ | UB_EV_PERSIST,
1129 &dtio_tap_callback, data);
1130 if(!data->ev) fatal_exit("could not ub_event_new");
1131 if(ub_event_add(data->ev, NULL) != 0) fatal_exit("could not ub_event_add");
1134 /** setup local accept sockets */
1135 static void setup_local_list(struct main_tap_data* maindata,
1136 struct config_strlist_head* local_list)
1138 struct config_strlist* item;
1139 for(item = local_list->first; item; item = item->next) {
1140 struct tap_socket* s;
1141 s = tap_socket_new_local(item->str, &dtio_mainfdcallback,
1143 if(!s) fatal_exit("out of memory");
1144 if(!tap_socket_list_insert(&maindata->acceptlist, s))
1145 fatal_exit("out of memory");
1149 /** setup tcp accept sockets */
1150 static void setup_tcp_list(struct main_tap_data* maindata,
1151 struct config_strlist_head* tcp_list)
1153 struct config_strlist* item;
1154 for(item = tcp_list->first; item; item = item->next) {
1155 struct tap_socket* s;
1156 s = tap_socket_new_tcpaccept(item->str, &dtio_mainfdcallback,
1158 if(!s) fatal_exit("out of memory");
1159 if(!tap_socket_list_insert(&maindata->acceptlist, s))
1160 fatal_exit("out of memory");
1164 /** setup tls accept sockets */
1165 static void setup_tls_list(struct main_tap_data* maindata,
1166 struct config_strlist_head* tls_list, char* server_key,
1167 char* server_cert, char* verifypem)
1169 struct config_strlist* item;
1170 for(item = tls_list->first; item; item = item->next) {
1171 struct tap_socket* s;
1172 s = tap_socket_new_tlsaccept(item->str, &dtio_mainfdcallback,
1173 maindata, server_key, server_cert, verifypem);
1174 if(!s) fatal_exit("out of memory");
1175 if(!tap_socket_list_insert(&maindata->acceptlist, s))
1176 fatal_exit("out of memory");
1180 /** signal variable */
1181 static struct ub_event_base* sig_base = NULL;
1182 /** do we have to quit */
1184 /** signal handler for user quit */
1185 static RETSIGTYPE main_sigh(int sig)
1188 char str[] = "exit on signal \n";
1189 str[15] = '0' + (sig/10)%10;
1190 str[16] = '0' + sig%10;
1191 /* simple cast to void will not silence Wunused-result */
1192 (void)!write(STDERR_FILENO, str, strlen(str));
1195 ub_event_base_loopexit(sig_base);
1201 /** setup and run the server to listen to DNSTAP messages */
1203 setup_and_run(struct config_strlist_head* local_list,
1204 struct config_strlist_head* tcp_list,
1205 struct config_strlist_head* tls_list, char* server_key,
1206 char* server_cert, char* verifypem)
1210 struct main_tap_data* maindata;
1211 struct ub_event_base* base;
1212 const char *evnm="event", *evsys="", *evmethod="";
1214 maindata = calloc(1, sizeof(*maindata));
1215 if(!maindata) fatal_exit("out of memory");
1216 memset(&now, 0, sizeof(now));
1217 base = ub_default_event_base(1, &secs, &now);
1218 if(!base) fatal_exit("could not create ub_event base");
1219 maindata->base = base;
1222 ub_event_base_free(base);
1226 ub_get_event_sys(base, &evnm, &evsys, &evmethod);
1227 if(verbosity) log_info("%s %s uses %s method", evnm, evsys, evmethod);
1229 setup_local_list(maindata, local_list);
1230 setup_tcp_list(maindata, tcp_list);
1231 setup_tls_list(maindata, tls_list, server_key, server_cert,
1233 if(!tap_socket_list_addevs(maindata->acceptlist, base))
1234 fatal_exit("could not setup accept events");
1235 if(verbosity) log_info("start of service");
1237 ub_event_base_dispatch(base);
1240 if(verbosity) log_info("end of service");
1241 tap_socket_list_delete(maindata->acceptlist);
1242 ub_event_base_free(base);
1246 /** getopt global, in case header files fail to declare it. */
1248 /** getopt global, in case header files fail to declare it. */
1249 extern char* optarg;
1251 /** main program for streamtcp */
1252 int main(int argc, char** argv)
1256 struct config_strlist_head local_list;
1257 struct config_strlist_head tcp_list;
1258 struct config_strlist_head tls_list;
1259 char* server_key = NULL, *server_cert = NULL, *verifypem = NULL;
1262 if(WSAStartup(MAKEWORD(2,2), &wsa_data) != 0) {
1263 printf("WSAStartup failed\n");
1267 if(signal(SIGINT, main_sigh) == SIG_ERR ||
1269 signal(SIGQUIT, main_sigh) == SIG_ERR ||
1272 signal(SIGHUP, main_sigh) == SIG_ERR ||
1275 signal(SIGBREAK, main_sigh) == SIG_ERR ||
1277 signal(SIGTERM, main_sigh) == SIG_ERR)
1278 fatal_exit("could not bind to signal");
1279 memset(&local_list, 0, sizeof(local_list));
1280 memset(&tcp_list, 0, sizeof(tcp_list));
1281 memset(&tls_list, 0, sizeof(tls_list));
1283 /* lock debug start (if any) */
1285 log_ident_set("unbound-dnstap-socket");
1289 if(signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
1290 perror("could not install signal handler for SIGPIPE");
1295 /* command line options */
1296 while( (c=getopt(argc, argv, "hls:t:u:vx:y:z:")) != -1) {
1299 if(!cfg_strlist_append(&local_list,
1301 fatal_exit("out of memory");
1304 if(!cfg_strlist_append(&tcp_list,
1306 fatal_exit("out of memory");
1309 if(!cfg_strlist_append(&tls_list,
1311 fatal_exit("out of memory");
1315 server_key = optarg;
1319 server_cert = optarg;
1343 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
1344 ERR_load_SSL_strings();
1346 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
1348 OpenSSL_add_all_algorithms();
1351 OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
1352 | OPENSSL_INIT_ADD_ALL_DIGESTS
1353 | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
1355 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
1356 (void)SSL_library_init();
1358 (void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
1360 #endif /* HAVE_SSL */
1362 setup_and_run(&local_list, &tcp_list, &tls_list, server_key,
1363 server_cert, verifypem);
1364 config_delstrlist(local_list.first);
1365 config_delstrlist(tcp_list.first);
1366 config_delstrlist(tls_list.first);
1375 /***--- definitions to make fptr_wlist work. ---***/
1376 /* These are callbacks, similar to smallapp callbacks, except the debug
1377 * tool callbacks are not in it */
1380 #include "util/data/packed_rrset.h"
1381 #include "daemon/worker.h"
1382 #include "daemon/remote.h"
1383 #include "util/fptr_wlist.h"
1384 #include "libunbound/context.h"
1386 void worker_handle_control_cmd(struct tube* ATTR_UNUSED(tube),
1387 uint8_t* ATTR_UNUSED(buffer), size_t ATTR_UNUSED(len),
1388 int ATTR_UNUSED(error), void* ATTR_UNUSED(arg))
1393 int worker_handle_request(struct comm_point* ATTR_UNUSED(c),
1394 void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1395 struct comm_reply* ATTR_UNUSED(repinfo))
1401 int worker_handle_service_reply(struct comm_point* ATTR_UNUSED(c),
1402 void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1403 struct comm_reply* ATTR_UNUSED(reply_info))
1409 int remote_accept_callback(struct comm_point* ATTR_UNUSED(c),
1410 void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1411 struct comm_reply* ATTR_UNUSED(repinfo))
1417 int remote_control_callback(struct comm_point* ATTR_UNUSED(c),
1418 void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1419 struct comm_reply* ATTR_UNUSED(repinfo))
1425 void worker_sighandler(int ATTR_UNUSED(sig), void* ATTR_UNUSED(arg))
1430 struct outbound_entry* worker_send_query(
1431 struct query_info* ATTR_UNUSED(qinfo), uint16_t ATTR_UNUSED(flags),
1432 int ATTR_UNUSED(dnssec), int ATTR_UNUSED(want_dnssec),
1433 int ATTR_UNUSED(nocaps), int ATTR_UNUSED(check_ratelimit),
1434 struct sockaddr_storage* ATTR_UNUSED(addr),
1435 socklen_t ATTR_UNUSED(addrlen), uint8_t* ATTR_UNUSED(zone),
1436 size_t ATTR_UNUSED(zonelen), int ATTR_UNUSED(tcp_upstream),
1437 int ATTR_UNUSED(ssl_upstream), char* ATTR_UNUSED(tls_auth_name),
1438 struct module_qstate* ATTR_UNUSED(q), int* ATTR_UNUSED(was_ratelimited))
1444 #ifdef UB_ON_WINDOWS
1446 worker_win_stop_cb(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev), void*
1452 wsvc_cron_cb(void* ATTR_UNUSED(arg))
1456 #endif /* UB_ON_WINDOWS */
1459 worker_alloc_cleanup(void* ATTR_UNUSED(arg))
1464 struct outbound_entry* libworker_send_query(
1465 struct query_info* ATTR_UNUSED(qinfo), uint16_t ATTR_UNUSED(flags),
1466 int ATTR_UNUSED(dnssec), int ATTR_UNUSED(want_dnssec),
1467 int ATTR_UNUSED(nocaps), int ATTR_UNUSED(check_ratelimit),
1468 struct sockaddr_storage* ATTR_UNUSED(addr),
1469 socklen_t ATTR_UNUSED(addrlen), uint8_t* ATTR_UNUSED(zone),
1470 size_t ATTR_UNUSED(zonelen), int ATTR_UNUSED(tcp_upstream),
1471 int ATTR_UNUSED(ssl_upstream), char* ATTR_UNUSED(tls_auth_name),
1472 struct module_qstate* ATTR_UNUSED(q), int* ATTR_UNUSED(was_ratelimited))
1478 int libworker_handle_service_reply(struct comm_point* ATTR_UNUSED(c),
1479 void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
1480 struct comm_reply* ATTR_UNUSED(reply_info))
1486 void libworker_handle_control_cmd(struct tube* ATTR_UNUSED(tube),
1487 uint8_t* ATTR_UNUSED(buffer), size_t ATTR_UNUSED(len),
1488 int ATTR_UNUSED(error), void* ATTR_UNUSED(arg))
1493 void libworker_fg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
1494 struct sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
1495 char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
1500 void libworker_bg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
1501 struct sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
1502 char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
1507 void libworker_event_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
1508 struct sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
1509 char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
1514 int context_query_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
1520 void worker_stat_timer_cb(void* ATTR_UNUSED(arg))
1525 void worker_probe_timer_cb(void* ATTR_UNUSED(arg))
1530 void worker_start_accept(void* ATTR_UNUSED(arg))
1535 void worker_stop_accept(void* ATTR_UNUSED(arg))
1540 /** keep track of lock id in lock-verify application */
1542 /** the thread id that created it */
1544 /** the instance number of creation */
1548 int order_lock_cmp(const void* e1, const void* e2)
1550 const struct order_id* o1 = e1;
1551 const struct order_id* o2 = e2;
1552 if(o1->thr < o2->thr) return -1;
1553 if(o1->thr > o2->thr) return 1;
1554 if(o1->instance < o2->instance) return -1;
1555 if(o1->instance > o2->instance) return 1;
1560 codeline_cmp(const void* a, const void* b)
1562 return strcmp(a, b);
1565 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
1571 void remote_get_opt_ssl(char* ATTR_UNUSED(str), void* ATTR_UNUSED(arg))