2 * util/netevent.c - event notification
4 * Copyright (c) 2007, 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 file contains event notification functions.
42 #include "util/netevent.h"
43 #include "util/ub_event.h"
45 #include "util/net_help.h"
46 #include "util/tcp_conn_limit.h"
47 #include "util/fptr_wlist.h"
48 #include "sldns/pkthdr.h"
49 #include "sldns/sbuffer.h"
50 #include "sldns/str2wire.h"
51 #include "dnstap/dnstap.h"
52 #include "dnscrypt/dnscrypt.h"
53 #include "services/listen_dnsport.h"
54 #ifdef HAVE_OPENSSL_SSL_H
55 #include <openssl/ssl.h>
57 #ifdef HAVE_OPENSSL_ERR_H
58 #include <openssl/err.h>
61 /* -------- Start of local definitions -------- */
62 /** if CMSG_ALIGN is not defined on this platform, a workaround */
65 # define CMSG_ALIGN(n) __CMSG_ALIGN(n)
66 # elif defined(CMSG_DATA_ALIGN)
67 # define CMSG_ALIGN _CMSG_DATA_ALIGN
69 # define CMSG_ALIGN(len) (((len)+sizeof(long)-1) & ~(sizeof(long)-1))
73 /** if CMSG_LEN is not defined on this platform, a workaround */
75 # define CMSG_LEN(len) (CMSG_ALIGN(sizeof(struct cmsghdr))+(len))
78 /** if CMSG_SPACE is not defined on this platform, a workaround */
80 # ifdef _CMSG_HDR_ALIGN
81 # define CMSG_SPACE(l) (CMSG_ALIGN(l)+_CMSG_HDR_ALIGN(sizeof(struct cmsghdr)))
83 # define CMSG_SPACE(l) (CMSG_ALIGN(l)+CMSG_ALIGN(sizeof(struct cmsghdr)))
87 /** The TCP writing query timeout in milliseconds */
88 #define TCP_QUERY_TIMEOUT 120000
89 /** The minimum actual TCP timeout to use, regardless of what we advertise,
91 #define TCP_QUERY_TIMEOUT_MINIMUM 200
93 #ifndef NONBLOCKING_IS_BROKEN
94 /** number of UDP reads to perform per read indication from select */
95 #define NUM_UDP_PER_SELECT 100
97 #define NUM_UDP_PER_SELECT 1
101 * The internal event structure for keeping ub_event info for the event.
102 * Possibly other structures (list, tree) this is part of.
104 struct internal_event {
106 struct comm_base* base;
107 /** ub_event event type */
112 * Internal base structure, so that every thread has its own events.
114 struct internal_base {
115 /** ub_event event_base type. */
116 struct ub_event_base* base;
117 /** seconds time pointer points here */
119 /** timeval with current time */
121 /** the event used for slow_accept timeouts */
122 struct ub_event* slow_accept;
123 /** true if slow_accept is enabled */
124 int slow_accept_enabled;
128 * Internal timer structure, to store timer event in.
130 struct internal_timer {
131 /** the super struct from which derived */
132 struct comm_timer super;
134 struct comm_base* base;
135 /** ub_event event type */
137 /** is timer enabled */
142 * Internal signal structure, to store signal event in.
144 struct internal_signal {
145 /** ub_event event type */
147 /** next in signal list */
148 struct internal_signal* next;
151 /** create a tcp handler with a parent */
152 static struct comm_point* comm_point_create_tcp_handler(
153 struct comm_base *base, struct comm_point* parent, size_t bufsize,
154 struct sldns_buffer* spoolbuf, comm_point_callback_type* callback,
157 /* -------- End of local definitions -------- */
160 comm_base_create(int sigs)
162 struct comm_base* b = (struct comm_base*)calloc(1,
163 sizeof(struct comm_base));
164 const char *evnm="event", *evsys="", *evmethod="";
168 b->eb = (struct internal_base*)calloc(1, sizeof(struct internal_base));
173 b->eb->base = ub_default_event_base(sigs, &b->eb->secs, &b->eb->now);
180 ub_get_event_sys(b->eb->base, &evnm, &evsys, &evmethod);
181 verbose(VERB_ALGO, "%s %s uses %s method.", evnm, evsys, evmethod);
186 comm_base_create_event(struct ub_event_base* base)
188 struct comm_base* b = (struct comm_base*)calloc(1,
189 sizeof(struct comm_base));
192 b->eb = (struct internal_base*)calloc(1, sizeof(struct internal_base));
203 comm_base_delete(struct comm_base* b)
207 if(b->eb->slow_accept_enabled) {
208 if(ub_event_del(b->eb->slow_accept) != 0) {
209 log_err("could not event_del slow_accept");
211 ub_event_free(b->eb->slow_accept);
213 ub_event_base_free(b->eb->base);
220 comm_base_delete_no_base(struct comm_base* b)
224 if(b->eb->slow_accept_enabled) {
225 if(ub_event_del(b->eb->slow_accept) != 0) {
226 log_err("could not event_del slow_accept");
228 ub_event_free(b->eb->slow_accept);
236 comm_base_timept(struct comm_base* b, time_t** tt, struct timeval** tv)
243 comm_base_dispatch(struct comm_base* b)
246 retval = ub_event_base_dispatch(b->eb->base);
248 fatal_exit("event_dispatch returned error %d, "
249 "errno is %s", retval, strerror(errno));
253 void comm_base_exit(struct comm_base* b)
255 if(ub_event_base_loopexit(b->eb->base) != 0) {
256 log_err("Could not loopexit");
260 void comm_base_set_slow_accept_handlers(struct comm_base* b,
261 void (*stop_acc)(void*), void (*start_acc)(void*), void* arg)
263 b->stop_accept = stop_acc;
264 b->start_accept = start_acc;
268 struct ub_event_base* comm_base_internal(struct comm_base* b)
273 /** see if errno for udp has to be logged or not uses globals */
275 udp_send_errno_needs_log(struct sockaddr* addr, socklen_t addrlen)
277 /* do not log transient errors (unless high verbosity) */
278 #if defined(ENETUNREACH) || defined(EHOSTDOWN) || defined(EHOSTUNREACH) || defined(ENETDOWN)
292 if(verbosity < VERB_ALGO)
298 /* permission denied is gotten for every send if the
299 * network is disconnected (on some OS), squelch it */
300 if( ((errno == EPERM)
301 # ifdef EADDRNOTAVAIL
302 /* 'Cannot assign requested address' also when disconnected */
303 || (errno == EADDRNOTAVAIL)
305 ) && verbosity < VERB_DETAIL)
308 /* If SO_REUSEADDR is set, we could try to connect to the same server
309 * from the same source port twice. */
310 if(errno == EADDRINUSE && verbosity < VERB_DETAIL)
313 /* squelch errors where people deploy AAAA ::ffff:bla for
314 * authority servers, which we try for intranets. */
315 if(errno == EINVAL && addr_is_ip4mapped(
316 (struct sockaddr_storage*)addr, addrlen) &&
317 verbosity < VERB_DETAIL)
319 /* SO_BROADCAST sockopt can give access to 255.255.255.255,
320 * but a dns cache does not need it. */
321 if(errno == EACCES && addr_is_broadcast(
322 (struct sockaddr_storage*)addr, addrlen) &&
323 verbosity < VERB_DETAIL)
328 int tcp_connect_errno_needs_log(struct sockaddr* addr, socklen_t addrlen)
330 return udp_send_errno_needs_log(addr, addrlen);
333 /* send a UDP reply */
335 comm_point_send_udp_msg(struct comm_point *c, sldns_buffer* packet,
336 struct sockaddr* addr, socklen_t addrlen)
339 log_assert(c->fd != -1);
341 if(sldns_buffer_remaining(packet) == 0)
342 log_err("error: send empty UDP packet");
344 log_assert(addr && addrlen > 0);
345 sent = sendto(c->fd, (void*)sldns_buffer_begin(packet),
346 sldns_buffer_remaining(packet), 0,
349 /* try again and block, waiting for IO to complete,
350 * we want to send the answer, and we will wait for
351 * the ethernet interface buffer to have space. */
353 if(errno == EAGAIN ||
355 errno == EWOULDBLOCK ||
359 if(WSAGetLastError() == WSAEINPROGRESS ||
360 WSAGetLastError() == WSAENOBUFS ||
361 WSAGetLastError() == WSAEWOULDBLOCK) {
365 sent = sendto(c->fd, (void*)sldns_buffer_begin(packet),
366 sldns_buffer_remaining(packet), 0,
369 fd_set_nonblock(c->fd);
374 if(!udp_send_errno_needs_log(addr, addrlen))
377 verbose(VERB_OPS, "sendto failed: %s", strerror(errno));
379 verbose(VERB_OPS, "sendto failed: %s",
380 wsa_strerror(WSAGetLastError()));
382 log_addr(VERB_OPS, "remote address is",
383 (struct sockaddr_storage*)addr, addrlen);
385 } else if((size_t)sent != sldns_buffer_remaining(packet)) {
386 log_err("sent %d in place of %d bytes",
387 (int)sent, (int)sldns_buffer_remaining(packet));
393 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && (defined(HAVE_RECVMSG) || defined(HAVE_SENDMSG))
394 /** print debug ancillary info */
395 static void p_ancil(const char* str, struct comm_reply* r)
397 if(r->srctype != 4 && r->srctype != 6) {
398 log_info("%s: unknown srctype %d", str, r->srctype);
401 if(r->srctype == 6) {
403 if(inet_ntop(AF_INET6, &r->pktinfo.v6info.ipi6_addr,
404 buf, (socklen_t)sizeof(buf)) == 0) {
405 (void)strlcpy(buf, "(inet_ntop error)", sizeof(buf));
407 buf[sizeof(buf)-1]=0;
408 log_info("%s: %s %d", str, buf, r->pktinfo.v6info.ipi6_ifindex);
409 } else if(r->srctype == 4) {
411 char buf1[1024], buf2[1024];
412 if(inet_ntop(AF_INET, &r->pktinfo.v4info.ipi_addr,
413 buf1, (socklen_t)sizeof(buf1)) == 0) {
414 (void)strlcpy(buf1, "(inet_ntop error)", sizeof(buf1));
416 buf1[sizeof(buf1)-1]=0;
417 #ifdef HAVE_STRUCT_IN_PKTINFO_IPI_SPEC_DST
418 if(inet_ntop(AF_INET, &r->pktinfo.v4info.ipi_spec_dst,
419 buf2, (socklen_t)sizeof(buf2)) == 0) {
420 (void)strlcpy(buf2, "(inet_ntop error)", sizeof(buf2));
422 buf2[sizeof(buf2)-1]=0;
426 log_info("%s: %d %s %s", str, r->pktinfo.v4info.ipi_ifindex,
428 #elif defined(IP_RECVDSTADDR)
430 if(inet_ntop(AF_INET, &r->pktinfo.v4addr,
431 buf1, (socklen_t)sizeof(buf1)) == 0) {
432 (void)strlcpy(buf1, "(inet_ntop error)", sizeof(buf1));
434 buf1[sizeof(buf1)-1]=0;
435 log_info("%s: %s", str, buf1);
436 #endif /* IP_PKTINFO or PI_RECVDSTDADDR */
439 #endif /* AF_INET6 && IPV6_PKTINFO && HAVE_RECVMSG||HAVE_SENDMSG */
441 /** send a UDP reply over specified interface*/
443 comm_point_send_udp_msg_if(struct comm_point *c, sldns_buffer* packet,
444 struct sockaddr* addr, socklen_t addrlen, struct comm_reply* r)
446 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && defined(HAVE_SENDMSG)
452 struct cmsghdr *cmsg;
453 #endif /* S_SPLINT_S */
455 log_assert(c->fd != -1);
457 if(sldns_buffer_remaining(packet) == 0)
458 log_err("error: send empty UDP packet");
460 log_assert(addr && addrlen > 0);
463 msg.msg_namelen = addrlen;
464 iov[0].iov_base = sldns_buffer_begin(packet);
465 iov[0].iov_len = sldns_buffer_remaining(packet);
468 msg.msg_control = control;
470 msg.msg_controllen = sizeof(control);
471 #endif /* S_SPLINT_S */
475 cmsg = CMSG_FIRSTHDR(&msg);
476 if(r->srctype == 4) {
479 msg.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
480 log_assert(msg.msg_controllen <= sizeof(control));
481 cmsg->cmsg_level = IPPROTO_IP;
482 cmsg->cmsg_type = IP_PKTINFO;
483 memmove(CMSG_DATA(cmsg), &r->pktinfo.v4info,
484 sizeof(struct in_pktinfo));
485 /* unset the ifindex to not bypass the routing tables */
486 cmsg_data = CMSG_DATA(cmsg);
487 ((struct in_pktinfo *) cmsg_data)->ipi_ifindex = 0;
488 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
489 #elif defined(IP_SENDSRCADDR)
490 msg.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
491 log_assert(msg.msg_controllen <= sizeof(control));
492 cmsg->cmsg_level = IPPROTO_IP;
493 cmsg->cmsg_type = IP_SENDSRCADDR;
494 memmove(CMSG_DATA(cmsg), &r->pktinfo.v4addr,
495 sizeof(struct in_addr));
496 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
498 verbose(VERB_ALGO, "no IP_PKTINFO or IP_SENDSRCADDR");
499 msg.msg_control = NULL;
500 #endif /* IP_PKTINFO or IP_SENDSRCADDR */
501 } else if(r->srctype == 6) {
503 msg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
504 log_assert(msg.msg_controllen <= sizeof(control));
505 cmsg->cmsg_level = IPPROTO_IPV6;
506 cmsg->cmsg_type = IPV6_PKTINFO;
507 memmove(CMSG_DATA(cmsg), &r->pktinfo.v6info,
508 sizeof(struct in6_pktinfo));
509 /* unset the ifindex to not bypass the routing tables */
510 cmsg_data = CMSG_DATA(cmsg);
511 ((struct in6_pktinfo *) cmsg_data)->ipi6_ifindex = 0;
512 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
514 /* try to pass all 0 to use default route */
515 msg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
516 log_assert(msg.msg_controllen <= sizeof(control));
517 cmsg->cmsg_level = IPPROTO_IPV6;
518 cmsg->cmsg_type = IPV6_PKTINFO;
519 memset(CMSG_DATA(cmsg), 0, sizeof(struct in6_pktinfo));
520 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
522 #endif /* S_SPLINT_S */
523 if(verbosity >= VERB_ALGO)
524 p_ancil("send_udp over interface", r);
525 sent = sendmsg(c->fd, &msg, 0);
527 /* try again and block, waiting for IO to complete,
528 * we want to send the answer, and we will wait for
529 * the ethernet interface buffer to have space. */
531 if(errno == EAGAIN ||
533 errno == EWOULDBLOCK ||
537 if(WSAGetLastError() == WSAEINPROGRESS ||
538 WSAGetLastError() == WSAENOBUFS ||
539 WSAGetLastError() == WSAEWOULDBLOCK) {
543 sent = sendmsg(c->fd, &msg, 0);
545 fd_set_nonblock(c->fd);
550 if(!udp_send_errno_needs_log(addr, addrlen))
552 verbose(VERB_OPS, "sendmsg failed: %s", strerror(errno));
553 log_addr(VERB_OPS, "remote address is",
554 (struct sockaddr_storage*)addr, addrlen);
556 /* netbsd 7 has IP_PKTINFO for recv but not send */
557 if(errno == EINVAL && r->srctype == 4)
558 log_err("sendmsg: No support for sendmsg(IP_PKTINFO). "
559 "Please disable interface-automatic");
562 } else if((size_t)sent != sldns_buffer_remaining(packet)) {
563 log_err("sent %d in place of %d bytes",
564 (int)sent, (int)sldns_buffer_remaining(packet));
574 log_err("sendmsg: IPV6_PKTINFO not supported");
576 #endif /* AF_INET6 && IPV6_PKTINFO && HAVE_SENDMSG */
580 comm_point_udp_ancil_callback(int fd, short event, void* arg)
582 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && defined(HAVE_RECVMSG)
583 struct comm_reply rep;
590 struct cmsghdr* cmsg;
591 #endif /* S_SPLINT_S */
593 rep.c = (struct comm_point*)arg;
594 log_assert(rep.c->type == comm_udp);
596 if(!(event&UB_EV_READ))
598 log_assert(rep.c && rep.c->buffer && rep.c->fd == fd);
599 ub_comm_base_now(rep.c->ev->base);
600 for(i=0; i<NUM_UDP_PER_SELECT; i++) {
601 sldns_buffer_clear(rep.c->buffer);
602 rep.addrlen = (socklen_t)sizeof(rep.addr);
603 log_assert(fd != -1);
604 log_assert(sldns_buffer_remaining(rep.c->buffer) > 0);
605 msg.msg_name = &rep.addr;
606 msg.msg_namelen = (socklen_t)sizeof(rep.addr);
607 iov[0].iov_base = sldns_buffer_begin(rep.c->buffer);
608 iov[0].iov_len = sldns_buffer_remaining(rep.c->buffer);
611 msg.msg_control = ancil;
613 msg.msg_controllen = sizeof(ancil);
614 #endif /* S_SPLINT_S */
616 rcv = recvmsg(fd, &msg, 0);
618 if(errno != EAGAIN && errno != EINTR) {
619 log_err("recvmsg failed: %s", strerror(errno));
623 rep.addrlen = msg.msg_namelen;
624 sldns_buffer_skip(rep.c->buffer, rcv);
625 sldns_buffer_flip(rep.c->buffer);
628 for(cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
629 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
630 if( cmsg->cmsg_level == IPPROTO_IPV6 &&
631 cmsg->cmsg_type == IPV6_PKTINFO) {
633 memmove(&rep.pktinfo.v6info, CMSG_DATA(cmsg),
634 sizeof(struct in6_pktinfo));
637 } else if( cmsg->cmsg_level == IPPROTO_IP &&
638 cmsg->cmsg_type == IP_PKTINFO) {
640 memmove(&rep.pktinfo.v4info, CMSG_DATA(cmsg),
641 sizeof(struct in_pktinfo));
643 #elif defined(IP_RECVDSTADDR)
644 } else if( cmsg->cmsg_level == IPPROTO_IP &&
645 cmsg->cmsg_type == IP_RECVDSTADDR) {
647 memmove(&rep.pktinfo.v4addr, CMSG_DATA(cmsg),
648 sizeof(struct in_addr));
650 #endif /* IP_PKTINFO or IP_RECVDSTADDR */
653 if(verbosity >= VERB_ALGO)
654 p_ancil("receive_udp on interface", &rep);
655 #endif /* S_SPLINT_S */
656 fptr_ok(fptr_whitelist_comm_point(rep.c->callback));
657 if((*rep.c->callback)(rep.c, rep.c->cb_arg, NETEVENT_NOERROR, &rep)) {
658 /* send back immediate reply */
659 (void)comm_point_send_udp_msg_if(rep.c, rep.c->buffer,
660 (struct sockaddr*)&rep.addr, rep.addrlen, &rep);
662 if(!rep.c || rep.c->fd == -1) /* commpoint closed */
669 fatal_exit("recvmsg: No support for IPV6_PKTINFO; IP_PKTINFO or IP_RECVDSTADDR. "
670 "Please disable interface-automatic");
671 #endif /* AF_INET6 && IPV6_PKTINFO && HAVE_RECVMSG */
675 comm_point_udp_callback(int fd, short event, void* arg)
677 struct comm_reply rep;
680 struct sldns_buffer *buffer;
682 rep.c = (struct comm_point*)arg;
683 log_assert(rep.c->type == comm_udp);
685 if(!(event&UB_EV_READ))
687 log_assert(rep.c && rep.c->buffer && rep.c->fd == fd);
688 ub_comm_base_now(rep.c->ev->base);
689 for(i=0; i<NUM_UDP_PER_SELECT; i++) {
690 sldns_buffer_clear(rep.c->buffer);
691 rep.addrlen = (socklen_t)sizeof(rep.addr);
692 log_assert(fd != -1);
693 log_assert(sldns_buffer_remaining(rep.c->buffer) > 0);
694 rcv = recvfrom(fd, (void*)sldns_buffer_begin(rep.c->buffer),
695 sldns_buffer_remaining(rep.c->buffer), 0,
696 (struct sockaddr*)&rep.addr, &rep.addrlen);
699 if(errno != EAGAIN && errno != EINTR)
700 log_err("recvfrom %d failed: %s",
701 fd, strerror(errno));
703 if(WSAGetLastError() != WSAEINPROGRESS &&
704 WSAGetLastError() != WSAECONNRESET &&
705 WSAGetLastError()!= WSAEWOULDBLOCK)
706 log_err("recvfrom failed: %s",
707 wsa_strerror(WSAGetLastError()));
711 sldns_buffer_skip(rep.c->buffer, rcv);
712 sldns_buffer_flip(rep.c->buffer);
714 fptr_ok(fptr_whitelist_comm_point(rep.c->callback));
715 if((*rep.c->callback)(rep.c, rep.c->cb_arg, NETEVENT_NOERROR, &rep)) {
716 /* send back immediate reply */
718 buffer = rep.c->dnscrypt_buffer;
720 buffer = rep.c->buffer;
722 (void)comm_point_send_udp_msg(rep.c, buffer,
723 (struct sockaddr*)&rep.addr, rep.addrlen);
725 if(!rep.c || rep.c->fd != fd) /* commpoint closed to -1 or reused for
726 another UDP port. Note rep.c cannot be reused with TCP fd. */
731 /** Use a new tcp handler for new query fd, set to read query */
733 setup_tcp_handler(struct comm_point* c, int fd, int cur, int max)
736 log_assert(c->type == comm_tcp);
737 log_assert(c->fd == -1);
738 sldns_buffer_clear(c->buffer);
741 sldns_buffer_clear(c->dnscrypt_buffer);
743 c->tcp_is_reading = 1;
744 c->tcp_byte_count = 0;
745 /* if more than half the tcp handlers are in use, use a shorter
746 * timeout for this TCP connection, we need to make space for
747 * other connections to be able to get attention */
748 /* If > 50% TCP handler structures in use, set timeout to 1/100th
750 * If > 65%TCP handler structures in use, set to 1/500th configured
752 * If > 80% TCP handler structures in use, set to 0.
754 * If the timeout to use falls below 200 milliseconds, an actual
755 * timeout of 200ms is used.
757 handler_usage = (cur * 100) / max;
758 if(handler_usage > 50 && handler_usage <= 65)
759 c->tcp_timeout_msec /= 100;
760 else if (handler_usage > 65 && handler_usage <= 80)
761 c->tcp_timeout_msec /= 500;
762 else if (handler_usage > 80)
763 c->tcp_timeout_msec = 0;
764 comm_point_start_listening(c, fd,
765 c->tcp_timeout_msec < TCP_QUERY_TIMEOUT_MINIMUM
766 ? TCP_QUERY_TIMEOUT_MINIMUM
767 : c->tcp_timeout_msec);
770 void comm_base_handle_slow_accept(int ATTR_UNUSED(fd),
771 short ATTR_UNUSED(event), void* arg)
773 struct comm_base* b = (struct comm_base*)arg;
774 /* timeout for the slow accept, re-enable accepts again */
775 if(b->start_accept) {
776 verbose(VERB_ALGO, "wait is over, slow accept disabled");
777 fptr_ok(fptr_whitelist_start_accept(b->start_accept));
778 (*b->start_accept)(b->cb_arg);
779 b->eb->slow_accept_enabled = 0;
783 int comm_point_perform_accept(struct comm_point* c,
784 struct sockaddr_storage* addr, socklen_t* addrlen)
787 *addrlen = (socklen_t)sizeof(*addr);
789 new_fd = accept(c->fd, (struct sockaddr*)addr, addrlen);
791 /* SOCK_NONBLOCK saves extra calls to fcntl for the same result */
792 new_fd = accept4(c->fd, (struct sockaddr*)addr, addrlen, SOCK_NONBLOCK);
796 /* EINTR is signal interrupt. others are closed connection. */
797 if( errno == EINTR || errno == EAGAIN
799 || errno == EWOULDBLOCK
802 || errno == ECONNABORTED
809 #if defined(ENFILE) && defined(EMFILE)
810 if(errno == ENFILE || errno == EMFILE) {
811 /* out of file descriptors, likely outside of our
812 * control. stop accept() calls for some time */
813 if(c->ev->base->stop_accept) {
814 struct comm_base* b = c->ev->base;
816 verbose(VERB_ALGO, "out of file descriptors: "
818 b->eb->slow_accept_enabled = 1;
819 fptr_ok(fptr_whitelist_stop_accept(
821 (*b->stop_accept)(b->cb_arg);
822 /* set timeout, no mallocs */
823 tv.tv_sec = NETEVENT_SLOW_ACCEPT_TIME/1000;
824 tv.tv_usec = (NETEVENT_SLOW_ACCEPT_TIME%1000)*1000;
825 b->eb->slow_accept = ub_event_new(b->eb->base,
827 comm_base_handle_slow_accept, b);
828 if(b->eb->slow_accept == NULL) {
829 /* we do not want to log here, because
830 * that would spam the logfiles.
831 * error: "event_base_set failed." */
833 else if(ub_event_add(b->eb->slow_accept, &tv)
835 /* we do not want to log here,
836 * error: "event_add failed." */
842 log_err_addr("accept failed", strerror(errno), addr, *addrlen);
843 #else /* USE_WINSOCK */
844 if(WSAGetLastError() == WSAEINPROGRESS ||
845 WSAGetLastError() == WSAECONNRESET)
847 if(WSAGetLastError() == WSAEWOULDBLOCK) {
848 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
851 log_err_addr("accept failed", wsa_strerror(WSAGetLastError()),
856 if(c->tcp_conn_limit && c->type == comm_tcp_accept) {
857 c->tcl_addr = tcl_addr_lookup(c->tcp_conn_limit, addr, *addrlen);
858 if(!tcl_new_connection(c->tcl_addr)) {
860 log_err_addr("accept rejected",
861 "connection limit exceeded", addr, *addrlen);
867 fd_set_nonblock(new_fd);
873 static long win_bio_cb(BIO *b, int oper, const char* ATTR_UNUSED(argp),
874 int ATTR_UNUSED(argi), long argl, long retvalue)
876 int wsa_err = WSAGetLastError(); /* store errcode before it is gone */
877 verbose(VERB_ALGO, "bio_cb %d, %s %s %s", oper,
878 (oper&BIO_CB_RETURN)?"return":"before",
879 (oper&BIO_CB_READ)?"read":((oper&BIO_CB_WRITE)?"write":"other"),
880 wsa_err==WSAEWOULDBLOCK?"wsawb":"");
881 /* on windows, check if previous operation caused EWOULDBLOCK */
882 if( (oper == (BIO_CB_READ|BIO_CB_RETURN) && argl == 0) ||
883 (oper == (BIO_CB_GETS|BIO_CB_RETURN) && argl == 0)) {
884 if(wsa_err == WSAEWOULDBLOCK)
885 ub_winsock_tcp_wouldblock((struct ub_event*)
886 BIO_get_callback_arg(b), UB_EV_READ);
888 if( (oper == (BIO_CB_WRITE|BIO_CB_RETURN) && argl == 0) ||
889 (oper == (BIO_CB_PUTS|BIO_CB_RETURN) && argl == 0)) {
890 if(wsa_err == WSAEWOULDBLOCK)
891 ub_winsock_tcp_wouldblock((struct ub_event*)
892 BIO_get_callback_arg(b), UB_EV_WRITE);
894 /* return original return value */
898 /** set win bio callbacks for nonblocking operations */
900 comm_point_tcp_win_bio_cb(struct comm_point* c, void* thessl)
902 SSL* ssl = (SSL*)thessl;
903 /* set them both just in case, but usually they are the same BIO */
904 BIO_set_callback(SSL_get_rbio(ssl), &win_bio_cb);
905 BIO_set_callback_arg(SSL_get_rbio(ssl), (char*)c->ev->ev);
906 BIO_set_callback(SSL_get_wbio(ssl), &win_bio_cb);
907 BIO_set_callback_arg(SSL_get_wbio(ssl), (char*)c->ev->ev);
912 comm_point_tcp_accept_callback(int fd, short event, void* arg)
914 struct comm_point* c = (struct comm_point*)arg, *c_hdl;
916 log_assert(c->type == comm_tcp_accept);
917 if(!(event & UB_EV_READ)) {
918 log_info("ignoring tcp accept event %d", (int)event);
921 ub_comm_base_now(c->ev->base);
922 /* find free tcp handler. */
924 log_warn("accepted too many tcp, connections full");
927 /* accept incoming connection. */
929 /* clear leftover flags from previous use, and then set the
930 * correct event base for the event structure for libevent */
931 ub_event_free(c_hdl->ev->ev);
932 c_hdl->ev->ev = ub_event_new(c_hdl->ev->base->eb->base, -1, UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT, comm_point_tcp_handle_callback, c_hdl);
934 log_warn("could not ub_event_new, dropped tcp");
937 log_assert(fd != -1);
939 new_fd = comm_point_perform_accept(c, &c_hdl->repinfo.addr,
940 &c_hdl->repinfo.addrlen);
944 c_hdl->ssl = incoming_ssl_fd(c->ssl, new_fd);
947 comm_point_close(c_hdl);
950 c_hdl->ssl_shake_state = comm_ssl_shake_read;
952 comm_point_tcp_win_bio_cb(c_hdl, c_hdl->ssl);
956 /* grab the tcp handler buffers */
958 c->tcp_free = c_hdl->tcp_free;
960 /* stop accepting incoming queries for now. */
961 comm_point_stop_listening(c);
963 setup_tcp_handler(c_hdl, new_fd, c->cur_tcp_count, c->max_tcp_count);
966 /** Make tcp handler free for next assignment */
968 reclaim_tcp_handler(struct comm_point* c)
970 log_assert(c->type == comm_tcp);
973 SSL_shutdown(c->ssl);
980 c->tcp_parent->cur_tcp_count--;
981 c->tcp_free = c->tcp_parent->tcp_free;
982 c->tcp_parent->tcp_free = c;
984 /* re-enable listening on accept socket */
985 comm_point_start_listening(c->tcp_parent, -1, -1);
990 /** do the callback when writing is done */
992 tcp_callback_writer(struct comm_point* c)
994 log_assert(c->type == comm_tcp);
995 sldns_buffer_clear(c->buffer);
996 if(c->tcp_do_toggle_rw)
997 c->tcp_is_reading = 1;
998 c->tcp_byte_count = 0;
999 /* switch from listening(write) to listening(read) */
1000 if(c->tcp_req_info) {
1001 tcp_req_info_handle_writedone(c->tcp_req_info);
1003 comm_point_stop_listening(c);
1004 comm_point_start_listening(c, -1, -1);
1008 /** do the callback when reading is done */
1010 tcp_callback_reader(struct comm_point* c)
1012 log_assert(c->type == comm_tcp || c->type == comm_local);
1013 sldns_buffer_flip(c->buffer);
1014 if(c->tcp_do_toggle_rw)
1015 c->tcp_is_reading = 0;
1016 c->tcp_byte_count = 0;
1017 if(c->tcp_req_info) {
1018 tcp_req_info_handle_readdone(c->tcp_req_info);
1020 if(c->type == comm_tcp)
1021 comm_point_stop_listening(c);
1022 fptr_ok(fptr_whitelist_comm_point(c->callback));
1023 if( (*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, &c->repinfo) ) {
1024 comm_point_start_listening(c, -1, c->tcp_timeout_msec);
1030 /** log certificate details */
1032 log_cert(unsigned level, const char* str, X509* cert)
1038 if(verbosity < level) return;
1039 bio = BIO_new(BIO_s_mem());
1041 X509_print_ex(bio, cert, 0, (unsigned long)-1
1042 ^(X509_FLAG_NO_SUBJECT
1043 |X509_FLAG_NO_ISSUER|X509_FLAG_NO_VALIDITY
1044 |X509_FLAG_NO_EXTENSIONS|X509_FLAG_NO_AUX
1045 |X509_FLAG_NO_ATTRIBUTES));
1046 BIO_write(bio, &nul, (int)sizeof(nul));
1047 len = BIO_get_mem_data(bio, &pp);
1048 if(len != 0 && pp) {
1049 verbose(level, "%s: \n%s", str, pp);
1053 #endif /* HAVE_SSL */
1055 /** continue ssl handshake */
1058 ssl_handshake(struct comm_point* c)
1061 if(c->ssl_shake_state == comm_ssl_shake_hs_read) {
1062 /* read condition satisfied back to writing */
1063 comm_point_listen_for_rw(c, 1, 1);
1064 c->ssl_shake_state = comm_ssl_shake_none;
1067 if(c->ssl_shake_state == comm_ssl_shake_hs_write) {
1068 /* write condition satisfied, back to reading */
1069 comm_point_listen_for_rw(c, 1, 0);
1070 c->ssl_shake_state = comm_ssl_shake_none;
1075 r = SSL_do_handshake(c->ssl);
1077 int want = SSL_get_error(c->ssl, r);
1078 if(want == SSL_ERROR_WANT_READ) {
1079 if(c->ssl_shake_state == comm_ssl_shake_read)
1081 c->ssl_shake_state = comm_ssl_shake_read;
1082 comm_point_listen_for_rw(c, 1, 0);
1084 } else if(want == SSL_ERROR_WANT_WRITE) {
1085 if(c->ssl_shake_state == comm_ssl_shake_write)
1087 c->ssl_shake_state = comm_ssl_shake_write;
1088 comm_point_listen_for_rw(c, 0, 1);
1091 return 0; /* closed */
1092 } else if(want == SSL_ERROR_SYSCALL) {
1093 /* SYSCALL and errno==0 means closed uncleanly */
1095 log_err("SSL_handshake syscall: %s",
1099 log_crypto_err("ssl handshake failed");
1100 log_addr(1, "ssl handshake failed", &c->repinfo.addr,
1101 c->repinfo.addrlen);
1105 /* this is where peer verification could take place */
1106 if((SSL_get_verify_mode(c->ssl)&SSL_VERIFY_PEER)) {
1108 if(SSL_get_verify_result(c->ssl) == X509_V_OK) {
1109 X509* x = SSL_get_peer_certificate(c->ssl);
1111 log_addr(VERB_ALGO, "SSL connection failed: "
1113 &c->repinfo.addr, c->repinfo.addrlen);
1116 log_cert(VERB_ALGO, "peer certificate", x);
1117 #ifdef HAVE_SSL_GET0_PEERNAME
1118 if(SSL_get0_peername(c->ssl)) {
1120 snprintf(buf, sizeof(buf), "SSL connection "
1121 "to %s authenticated",
1122 SSL_get0_peername(c->ssl));
1123 log_addr(VERB_ALGO, buf, &c->repinfo.addr,
1124 c->repinfo.addrlen);
1127 log_addr(VERB_ALGO, "SSL connection "
1128 "authenticated", &c->repinfo.addr,
1129 c->repinfo.addrlen);
1130 #ifdef HAVE_SSL_GET0_PEERNAME
1135 X509* x = SSL_get_peer_certificate(c->ssl);
1137 log_cert(VERB_ALGO, "peer certificate", x);
1140 log_addr(VERB_ALGO, "SSL connection failed: "
1141 "failed to authenticate",
1142 &c->repinfo.addr, c->repinfo.addrlen);
1146 /* unauthenticated, the verify peer flag was not set
1147 * in c->ssl when the ssl object was created from ssl_ctx */
1148 log_addr(VERB_ALGO, "SSL connection", &c->repinfo.addr,
1149 c->repinfo.addrlen);
1152 /* setup listen rw correctly */
1153 if(c->tcp_is_reading) {
1154 if(c->ssl_shake_state != comm_ssl_shake_read)
1155 comm_point_listen_for_rw(c, 1, 0);
1157 comm_point_listen_for_rw(c, 1, 1);
1159 c->ssl_shake_state = comm_ssl_shake_none;
1162 #endif /* HAVE_SSL */
1164 /** ssl read callback on TCP */
1166 ssl_handle_read(struct comm_point* c)
1170 if(c->ssl_shake_state != comm_ssl_shake_none) {
1171 if(!ssl_handshake(c))
1173 if(c->ssl_shake_state != comm_ssl_shake_none)
1176 if(c->tcp_byte_count < sizeof(uint16_t)) {
1177 /* read length bytes */
1179 if((r=SSL_read(c->ssl, (void*)sldns_buffer_at(c->buffer,
1180 c->tcp_byte_count), (int)(sizeof(uint16_t) -
1181 c->tcp_byte_count))) <= 0) {
1182 int want = SSL_get_error(c->ssl, r);
1183 if(want == SSL_ERROR_ZERO_RETURN) {
1185 return tcp_req_info_handle_read_close(c->tcp_req_info);
1186 return 0; /* shutdown, closed */
1187 } else if(want == SSL_ERROR_WANT_READ) {
1188 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1189 return 1; /* read more later */
1190 } else if(want == SSL_ERROR_WANT_WRITE) {
1191 c->ssl_shake_state = comm_ssl_shake_hs_write;
1192 comm_point_listen_for_rw(c, 0, 1);
1194 } else if(want == SSL_ERROR_SYSCALL) {
1196 if(errno == ECONNRESET && verbosity < 2)
1197 return 0; /* silence reset by peer */
1200 log_err("SSL_read syscall: %s",
1204 log_crypto_err("could not SSL_read");
1207 c->tcp_byte_count += r;
1208 if(c->tcp_byte_count < sizeof(uint16_t))
1210 if(sldns_buffer_read_u16_at(c->buffer, 0) >
1211 sldns_buffer_capacity(c->buffer)) {
1212 verbose(VERB_QUERY, "ssl: dropped larger than buffer");
1215 sldns_buffer_set_limit(c->buffer,
1216 sldns_buffer_read_u16_at(c->buffer, 0));
1217 if(sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
1218 verbose(VERB_QUERY, "ssl: dropped bogus too short.");
1221 sldns_buffer_skip(c->buffer, (ssize_t)(c->tcp_byte_count-sizeof(uint16_t)));
1222 verbose(VERB_ALGO, "Reading ssl tcp query of length %d",
1223 (int)sldns_buffer_limit(c->buffer));
1225 if(sldns_buffer_remaining(c->buffer) > 0) {
1227 r = SSL_read(c->ssl, (void*)sldns_buffer_current(c->buffer),
1228 (int)sldns_buffer_remaining(c->buffer));
1230 int want = SSL_get_error(c->ssl, r);
1231 if(want == SSL_ERROR_ZERO_RETURN) {
1233 return tcp_req_info_handle_read_close(c->tcp_req_info);
1234 return 0; /* shutdown, closed */
1235 } else if(want == SSL_ERROR_WANT_READ) {
1236 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1237 return 1; /* read more later */
1238 } else if(want == SSL_ERROR_WANT_WRITE) {
1239 c->ssl_shake_state = comm_ssl_shake_hs_write;
1240 comm_point_listen_for_rw(c, 0, 1);
1242 } else if(want == SSL_ERROR_SYSCALL) {
1244 if(errno == ECONNRESET && verbosity < 2)
1245 return 0; /* silence reset by peer */
1248 log_err("SSL_read syscall: %s",
1252 log_crypto_err("could not SSL_read");
1255 sldns_buffer_skip(c->buffer, (ssize_t)r);
1257 if(sldns_buffer_remaining(c->buffer) <= 0) {
1258 tcp_callback_reader(c);
1264 #endif /* HAVE_SSL */
1267 /** ssl write callback on TCP */
1269 ssl_handle_write(struct comm_point* c)
1273 if(c->ssl_shake_state != comm_ssl_shake_none) {
1274 if(!ssl_handshake(c))
1276 if(c->ssl_shake_state != comm_ssl_shake_none)
1279 /* ignore return, if fails we may simply block */
1280 (void)SSL_set_mode(c->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE);
1281 if(c->tcp_byte_count < sizeof(uint16_t)) {
1282 uint16_t len = htons(sldns_buffer_limit(c->buffer));
1284 if(sizeof(uint16_t)+sldns_buffer_remaining(c->buffer) <
1286 /* combine the tcp length and the query for write,
1287 * this emulates writev */
1288 uint8_t buf[LDNS_RR_BUF_SIZE];
1289 memmove(buf, &len, sizeof(uint16_t));
1290 memmove(buf+sizeof(uint16_t),
1291 sldns_buffer_current(c->buffer),
1292 sldns_buffer_remaining(c->buffer));
1293 r = SSL_write(c->ssl, (void*)(buf+c->tcp_byte_count),
1294 (int)(sizeof(uint16_t)+
1295 sldns_buffer_remaining(c->buffer)
1296 - c->tcp_byte_count));
1298 r = SSL_write(c->ssl,
1299 (void*)(((uint8_t*)&len)+c->tcp_byte_count),
1300 (int)(sizeof(uint16_t)-c->tcp_byte_count));
1303 int want = SSL_get_error(c->ssl, r);
1304 if(want == SSL_ERROR_ZERO_RETURN) {
1305 return 0; /* closed */
1306 } else if(want == SSL_ERROR_WANT_READ) {
1307 c->ssl_shake_state = comm_ssl_shake_hs_read;
1308 comm_point_listen_for_rw(c, 1, 0);
1309 return 1; /* wait for read condition */
1310 } else if(want == SSL_ERROR_WANT_WRITE) {
1311 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
1312 return 1; /* write more later */
1313 } else if(want == SSL_ERROR_SYSCALL) {
1315 if(errno == EPIPE && verbosity < 2)
1316 return 0; /* silence 'broken pipe' */
1319 log_err("SSL_write syscall: %s",
1323 log_crypto_err("could not SSL_write");
1326 c->tcp_byte_count += r;
1327 if(c->tcp_byte_count < sizeof(uint16_t))
1329 sldns_buffer_set_position(c->buffer, c->tcp_byte_count -
1331 if(sldns_buffer_remaining(c->buffer) == 0) {
1332 tcp_callback_writer(c);
1336 log_assert(sldns_buffer_remaining(c->buffer) > 0);
1338 r = SSL_write(c->ssl, (void*)sldns_buffer_current(c->buffer),
1339 (int)sldns_buffer_remaining(c->buffer));
1341 int want = SSL_get_error(c->ssl, r);
1342 if(want == SSL_ERROR_ZERO_RETURN) {
1343 return 0; /* closed */
1344 } else if(want == SSL_ERROR_WANT_READ) {
1345 c->ssl_shake_state = comm_ssl_shake_hs_read;
1346 comm_point_listen_for_rw(c, 1, 0);
1347 return 1; /* wait for read condition */
1348 } else if(want == SSL_ERROR_WANT_WRITE) {
1349 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
1350 return 1; /* write more later */
1351 } else if(want == SSL_ERROR_SYSCALL) {
1353 if(errno == EPIPE && verbosity < 2)
1354 return 0; /* silence 'broken pipe' */
1357 log_err("SSL_write syscall: %s",
1361 log_crypto_err("could not SSL_write");
1364 sldns_buffer_skip(c->buffer, (ssize_t)r);
1366 if(sldns_buffer_remaining(c->buffer) == 0) {
1367 tcp_callback_writer(c);
1373 #endif /* HAVE_SSL */
1376 /** handle ssl tcp connection with dns contents */
1378 ssl_handle_it(struct comm_point* c)
1380 if(c->tcp_is_reading)
1381 return ssl_handle_read(c);
1382 return ssl_handle_write(c);
1385 /** Handle tcp reading callback.
1386 * @param fd: file descriptor of socket.
1387 * @param c: comm point to read from into buffer.
1388 * @param short_ok: if true, very short packets are OK (for comm_local).
1389 * @return: 0 on error
1392 comm_point_tcp_handle_read(int fd, struct comm_point* c, int short_ok)
1395 log_assert(c->type == comm_tcp || c->type == comm_local);
1397 return ssl_handle_it(c);
1398 if(!c->tcp_is_reading)
1401 log_assert(fd != -1);
1402 if(c->tcp_byte_count < sizeof(uint16_t)) {
1403 /* read length bytes */
1404 r = recv(fd,(void*)sldns_buffer_at(c->buffer,c->tcp_byte_count),
1405 sizeof(uint16_t)-c->tcp_byte_count, 0);
1408 return tcp_req_info_handle_read_close(c->tcp_req_info);
1410 } else if(r == -1) {
1412 if(errno == EINTR || errno == EAGAIN)
1415 if(errno == ECONNRESET && verbosity < 2)
1416 return 0; /* silence reset by peer */
1418 log_err_addr("read (in tcp s)", strerror(errno),
1419 &c->repinfo.addr, c->repinfo.addrlen);
1420 #else /* USE_WINSOCK */
1421 if(WSAGetLastError() == WSAECONNRESET)
1423 if(WSAGetLastError() == WSAEINPROGRESS)
1425 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1426 ub_winsock_tcp_wouldblock(c->ev->ev,
1430 log_err_addr("read (in tcp s)",
1431 wsa_strerror(WSAGetLastError()),
1432 &c->repinfo.addr, c->repinfo.addrlen);
1436 c->tcp_byte_count += r;
1437 if(c->tcp_byte_count != sizeof(uint16_t))
1439 if(sldns_buffer_read_u16_at(c->buffer, 0) >
1440 sldns_buffer_capacity(c->buffer)) {
1441 verbose(VERB_QUERY, "tcp: dropped larger than buffer");
1444 sldns_buffer_set_limit(c->buffer,
1445 sldns_buffer_read_u16_at(c->buffer, 0));
1447 sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
1448 verbose(VERB_QUERY, "tcp: dropped bogus too short.");
1451 verbose(VERB_ALGO, "Reading tcp query of length %d",
1452 (int)sldns_buffer_limit(c->buffer));
1455 log_assert(sldns_buffer_remaining(c->buffer) > 0);
1456 r = recv(fd, (void*)sldns_buffer_current(c->buffer),
1457 sldns_buffer_remaining(c->buffer), 0);
1460 return tcp_req_info_handle_read_close(c->tcp_req_info);
1462 } else if(r == -1) {
1464 if(errno == EINTR || errno == EAGAIN)
1466 log_err_addr("read (in tcp r)", strerror(errno),
1467 &c->repinfo.addr, c->repinfo.addrlen);
1468 #else /* USE_WINSOCK */
1469 if(WSAGetLastError() == WSAECONNRESET)
1471 if(WSAGetLastError() == WSAEINPROGRESS)
1473 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1474 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1477 log_err_addr("read (in tcp r)",
1478 wsa_strerror(WSAGetLastError()),
1479 &c->repinfo.addr, c->repinfo.addrlen);
1483 sldns_buffer_skip(c->buffer, r);
1484 if(sldns_buffer_remaining(c->buffer) <= 0) {
1485 tcp_callback_reader(c);
1491 * Handle tcp writing callback.
1492 * @param fd: file descriptor of socket.
1493 * @param c: comm point to write buffer out of.
1494 * @return: 0 on error
1497 comm_point_tcp_handle_write(int fd, struct comm_point* c)
1500 struct sldns_buffer *buffer;
1501 log_assert(c->type == comm_tcp);
1503 buffer = c->dnscrypt_buffer;
1507 if(c->tcp_is_reading && !c->ssl)
1509 log_assert(fd != -1);
1510 if(c->tcp_byte_count == 0 && c->tcp_check_nb_connect) {
1511 /* check for pending error from nonblocking connect */
1512 /* from Stevens, unix network programming, vol1, 3rd ed, p450*/
1514 socklen_t len = (socklen_t)sizeof(error);
1515 if(getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&error,
1518 error = errno; /* on solaris errno is error */
1519 #else /* USE_WINSOCK */
1520 error = WSAGetLastError();
1524 #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
1525 if(error == EINPROGRESS || error == EWOULDBLOCK)
1526 return 1; /* try again later */
1529 if(error != 0 && verbosity < 2)
1530 return 0; /* silence lots of chatter in the logs */
1531 else if(error != 0) {
1532 log_err_addr("tcp connect", strerror(error),
1533 &c->repinfo.addr, c->repinfo.addrlen);
1534 #else /* USE_WINSOCK */
1536 if(error == WSAEINPROGRESS)
1538 else if(error == WSAEWOULDBLOCK) {
1539 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
1541 } else if(error != 0 && verbosity < 2)
1543 else if(error != 0) {
1544 log_err_addr("tcp connect", wsa_strerror(error),
1545 &c->repinfo.addr, c->repinfo.addrlen);
1546 #endif /* USE_WINSOCK */
1551 return ssl_handle_it(c);
1553 #ifdef USE_MSG_FASTOPEN
1554 /* Only try this on first use of a connection that uses tfo,
1555 otherwise fall through to normal write */
1556 /* Also, TFO support on WINDOWS not implemented at the moment */
1557 if(c->tcp_do_fastopen == 1) {
1558 /* this form of sendmsg() does both a connect() and send() so need to
1559 look for various flavours of error*/
1560 uint16_t len = htons(sldns_buffer_limit(buffer));
1562 struct iovec iov[2];
1563 c->tcp_do_fastopen = 0;
1564 memset(&msg, 0, sizeof(msg));
1565 iov[0].iov_base = (uint8_t*)&len + c->tcp_byte_count;
1566 iov[0].iov_len = sizeof(uint16_t) - c->tcp_byte_count;
1567 iov[1].iov_base = sldns_buffer_begin(buffer);
1568 iov[1].iov_len = sldns_buffer_limit(buffer);
1569 log_assert(iov[0].iov_len > 0);
1570 msg.msg_name = &c->repinfo.addr;
1571 msg.msg_namelen = c->repinfo.addrlen;
1574 r = sendmsg(fd, &msg, MSG_FASTOPEN);
1576 #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
1577 /* Handshake is underway, maybe because no TFO cookie available.
1578 Come back to write the message*/
1579 if(errno == EINPROGRESS || errno == EWOULDBLOCK)
1582 if(errno == EINTR || errno == EAGAIN)
1584 /* Not handling EISCONN here as shouldn't ever hit that case.*/
1585 if(errno != EPIPE && errno != 0 && verbosity < 2)
1586 return 0; /* silence lots of chatter in the logs */
1587 if(errno != EPIPE && errno != 0) {
1588 log_err_addr("tcp sendmsg", strerror(errno),
1589 &c->repinfo.addr, c->repinfo.addrlen);
1592 /* fallthrough to nonFASTOPEN
1593 * (MSG_FASTOPEN on Linux 3 produces EPIPE)
1594 * we need to perform connect() */
1595 if(connect(fd, (struct sockaddr *)&c->repinfo.addr, c->repinfo.addrlen) == -1) {
1597 if(errno == EINPROGRESS)
1598 return 1; /* wait until connect done*/
1601 if(WSAGetLastError() == WSAEINPROGRESS ||
1602 WSAGetLastError() == WSAEWOULDBLOCK)
1603 return 1; /* wait until connect done*/
1605 if(tcp_connect_errno_needs_log(
1606 (struct sockaddr *)&c->repinfo.addr, c->repinfo.addrlen)) {
1607 log_err_addr("outgoing tcp: connect after EPIPE for fastopen",
1608 strerror(errno), &c->repinfo.addr, c->repinfo.addrlen);
1614 c->tcp_byte_count += r;
1615 if(c->tcp_byte_count < sizeof(uint16_t))
1617 sldns_buffer_set_position(buffer, c->tcp_byte_count -
1619 if(sldns_buffer_remaining(buffer) == 0) {
1620 tcp_callback_writer(c);
1625 #endif /* USE_MSG_FASTOPEN */
1627 if(c->tcp_byte_count < sizeof(uint16_t)) {
1628 uint16_t len = htons(sldns_buffer_limit(buffer));
1630 struct iovec iov[2];
1631 iov[0].iov_base = (uint8_t*)&len + c->tcp_byte_count;
1632 iov[0].iov_len = sizeof(uint16_t) - c->tcp_byte_count;
1633 iov[1].iov_base = sldns_buffer_begin(buffer);
1634 iov[1].iov_len = sldns_buffer_limit(buffer);
1635 log_assert(iov[0].iov_len > 0);
1636 r = writev(fd, iov, 2);
1637 #else /* HAVE_WRITEV */
1638 r = send(fd, (void*)(((uint8_t*)&len)+c->tcp_byte_count),
1639 sizeof(uint16_t)-c->tcp_byte_count, 0);
1640 #endif /* HAVE_WRITEV */
1644 if(errno == EPIPE && verbosity < 2)
1645 return 0; /* silence 'broken pipe' */
1647 if(errno == EINTR || errno == EAGAIN)
1650 if(errno == ECONNRESET && verbosity < 2)
1651 return 0; /* silence reset by peer */
1654 log_err_addr("tcp writev", strerror(errno),
1655 &c->repinfo.addr, c->repinfo.addrlen);
1656 # else /* HAVE_WRITEV */
1657 log_err_addr("tcp send s", strerror(errno),
1658 &c->repinfo.addr, c->repinfo.addrlen);
1659 # endif /* HAVE_WRITEV */
1661 if(WSAGetLastError() == WSAENOTCONN)
1663 if(WSAGetLastError() == WSAEINPROGRESS)
1665 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1666 ub_winsock_tcp_wouldblock(c->ev->ev,
1670 if(WSAGetLastError() == WSAECONNRESET && verbosity < 2)
1671 return 0; /* silence reset by peer */
1672 log_err_addr("tcp send s",
1673 wsa_strerror(WSAGetLastError()),
1674 &c->repinfo.addr, c->repinfo.addrlen);
1678 c->tcp_byte_count += r;
1679 if(c->tcp_byte_count < sizeof(uint16_t))
1681 sldns_buffer_set_position(buffer, c->tcp_byte_count -
1683 if(sldns_buffer_remaining(buffer) == 0) {
1684 tcp_callback_writer(c);
1688 log_assert(sldns_buffer_remaining(buffer) > 0);
1689 r = send(fd, (void*)sldns_buffer_current(buffer),
1690 sldns_buffer_remaining(buffer), 0);
1693 if(errno == EINTR || errno == EAGAIN)
1696 if(errno == ECONNRESET && verbosity < 2)
1697 return 0; /* silence reset by peer */
1699 log_err_addr("tcp send r", strerror(errno),
1700 &c->repinfo.addr, c->repinfo.addrlen);
1702 if(WSAGetLastError() == WSAEINPROGRESS)
1704 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1705 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
1708 if(WSAGetLastError() == WSAECONNRESET && verbosity < 2)
1709 return 0; /* silence reset by peer */
1710 log_err_addr("tcp send r", wsa_strerror(WSAGetLastError()),
1711 &c->repinfo.addr, c->repinfo.addrlen);
1715 sldns_buffer_skip(buffer, r);
1717 if(sldns_buffer_remaining(buffer) == 0) {
1718 tcp_callback_writer(c);
1724 /** read again to drain buffers when there could be more to read */
1726 tcp_req_info_read_again(int fd, struct comm_point* c)
1728 while(c->tcp_req_info->read_again) {
1730 c->tcp_req_info->read_again = 0;
1731 if(c->tcp_is_reading)
1732 r = comm_point_tcp_handle_read(fd, c, 0);
1733 else r = comm_point_tcp_handle_write(fd, c);
1735 reclaim_tcp_handler(c);
1736 if(!c->tcp_do_close) {
1737 fptr_ok(fptr_whitelist_comm_point(
1739 (void)(*c->callback)(c, c->cb_arg,
1740 NETEVENT_CLOSED, NULL);
1748 comm_point_tcp_handle_callback(int fd, short event, void* arg)
1750 struct comm_point* c = (struct comm_point*)arg;
1751 log_assert(c->type == comm_tcp);
1752 ub_comm_base_now(c->ev->base);
1755 /* Initialize if this is a dnscrypt socket */
1757 c->dnscrypt = c->tcp_parent->dnscrypt;
1759 if(c->dnscrypt && c->dnscrypt_buffer == c->buffer) {
1760 c->dnscrypt_buffer = sldns_buffer_new(sldns_buffer_capacity(c->buffer));
1761 if(!c->dnscrypt_buffer) {
1762 log_err("Could not allocate dnscrypt buffer");
1763 reclaim_tcp_handler(c);
1764 if(!c->tcp_do_close) {
1765 fptr_ok(fptr_whitelist_comm_point(
1767 (void)(*c->callback)(c, c->cb_arg,
1768 NETEVENT_CLOSED, NULL);
1775 if(event&UB_EV_TIMEOUT) {
1776 verbose(VERB_QUERY, "tcp took too long, dropped");
1777 reclaim_tcp_handler(c);
1778 if(!c->tcp_do_close) {
1779 fptr_ok(fptr_whitelist_comm_point(c->callback));
1780 (void)(*c->callback)(c, c->cb_arg,
1781 NETEVENT_TIMEOUT, NULL);
1785 if(event&UB_EV_READ) {
1786 int has_tcpq = (c->tcp_req_info != NULL);
1787 if(!comm_point_tcp_handle_read(fd, c, 0)) {
1788 reclaim_tcp_handler(c);
1789 if(!c->tcp_do_close) {
1790 fptr_ok(fptr_whitelist_comm_point(
1792 (void)(*c->callback)(c, c->cb_arg,
1793 NETEVENT_CLOSED, NULL);
1796 if(has_tcpq && c->tcp_req_info && c->tcp_req_info->read_again)
1797 tcp_req_info_read_again(fd, c);
1800 if(event&UB_EV_WRITE) {
1801 int has_tcpq = (c->tcp_req_info != NULL);
1802 if(!comm_point_tcp_handle_write(fd, c)) {
1803 reclaim_tcp_handler(c);
1804 if(!c->tcp_do_close) {
1805 fptr_ok(fptr_whitelist_comm_point(
1807 (void)(*c->callback)(c, c->cb_arg,
1808 NETEVENT_CLOSED, NULL);
1811 if(has_tcpq && c->tcp_req_info && c->tcp_req_info->read_again)
1812 tcp_req_info_read_again(fd, c);
1815 log_err("Ignored event %d for tcphdl.", event);
1818 /** Make http handler free for next assignment */
1820 reclaim_http_handler(struct comm_point* c)
1822 log_assert(c->type == comm_http);
1825 SSL_shutdown(c->ssl);
1830 comm_point_close(c);
1832 c->tcp_parent->cur_tcp_count--;
1833 c->tcp_free = c->tcp_parent->tcp_free;
1834 c->tcp_parent->tcp_free = c;
1836 /* re-enable listening on accept socket */
1837 comm_point_start_listening(c->tcp_parent, -1, -1);
1842 /** read more data for http (with ssl) */
1844 ssl_http_read_more(struct comm_point* c)
1848 log_assert(sldns_buffer_remaining(c->buffer) > 0);
1850 r = SSL_read(c->ssl, (void*)sldns_buffer_current(c->buffer),
1851 (int)sldns_buffer_remaining(c->buffer));
1853 int want = SSL_get_error(c->ssl, r);
1854 if(want == SSL_ERROR_ZERO_RETURN) {
1855 return 0; /* shutdown, closed */
1856 } else if(want == SSL_ERROR_WANT_READ) {
1857 return 1; /* read more later */
1858 } else if(want == SSL_ERROR_WANT_WRITE) {
1859 c->ssl_shake_state = comm_ssl_shake_hs_write;
1860 comm_point_listen_for_rw(c, 0, 1);
1862 } else if(want == SSL_ERROR_SYSCALL) {
1864 if(errno == ECONNRESET && verbosity < 2)
1865 return 0; /* silence reset by peer */
1868 log_err("SSL_read syscall: %s",
1872 log_crypto_err("could not SSL_read");
1875 sldns_buffer_skip(c->buffer, (ssize_t)r);
1880 #endif /* HAVE_SSL */
1883 /** read more data for http */
1885 http_read_more(int fd, struct comm_point* c)
1888 log_assert(sldns_buffer_remaining(c->buffer) > 0);
1889 r = recv(fd, (void*)sldns_buffer_current(c->buffer),
1890 sldns_buffer_remaining(c->buffer), 0);
1893 } else if(r == -1) {
1895 if(errno == EINTR || errno == EAGAIN)
1897 log_err_addr("read (in http r)", strerror(errno),
1898 &c->repinfo.addr, c->repinfo.addrlen);
1899 #else /* USE_WINSOCK */
1900 if(WSAGetLastError() == WSAECONNRESET)
1902 if(WSAGetLastError() == WSAEINPROGRESS)
1904 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1905 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1908 log_err_addr("read (in http r)",
1909 wsa_strerror(WSAGetLastError()),
1910 &c->repinfo.addr, c->repinfo.addrlen);
1914 sldns_buffer_skip(c->buffer, r);
1918 /** return true if http header has been read (one line complete) */
1920 http_header_done(sldns_buffer* buf)
1923 for(i=sldns_buffer_position(buf); i<sldns_buffer_limit(buf); i++) {
1924 /* there was a \r before the \n, but we ignore that */
1925 if((char)sldns_buffer_read_u8_at(buf, i) == '\n')
1931 /** return character string into buffer for header line, moves buffer
1932 * past that line and puts zero terminator into linefeed-newline */
1934 http_header_line(sldns_buffer* buf)
1936 char* result = (char*)sldns_buffer_current(buf);
1938 for(i=sldns_buffer_position(buf); i<sldns_buffer_limit(buf); i++) {
1939 /* terminate the string on the \r */
1940 if((char)sldns_buffer_read_u8_at(buf, i) == '\r')
1941 sldns_buffer_write_u8_at(buf, i, 0);
1942 /* terminate on the \n and skip past the it and done */
1943 if((char)sldns_buffer_read_u8_at(buf, i) == '\n') {
1944 sldns_buffer_write_u8_at(buf, i, 0);
1945 sldns_buffer_set_position(buf, i+1);
1952 /** move unread buffer to start and clear rest for putting the rest into it */
1954 http_moveover_buffer(sldns_buffer* buf)
1956 size_t pos = sldns_buffer_position(buf);
1957 size_t len = sldns_buffer_remaining(buf);
1958 sldns_buffer_clear(buf);
1959 memmove(sldns_buffer_begin(buf), sldns_buffer_at(buf, pos), len);
1960 sldns_buffer_set_position(buf, len);
1963 /** a http header is complete, process it */
1965 http_process_initial_header(struct comm_point* c)
1967 char* line = http_header_line(c->buffer);
1969 verbose(VERB_ALGO, "http header: %s", line);
1970 if(strncasecmp(line, "HTTP/1.1 ", 9) == 0) {
1971 /* check returncode */
1972 if(line[9] != '2') {
1973 verbose(VERB_ALGO, "http bad status %s", line+9);
1976 } else if(strncasecmp(line, "Content-Length: ", 16) == 0) {
1977 if(!c->http_is_chunked)
1978 c->tcp_byte_count = (size_t)atoi(line+16);
1979 } else if(strncasecmp(line, "Transfer-Encoding: chunked", 19+7) == 0) {
1980 c->tcp_byte_count = 0;
1981 c->http_is_chunked = 1;
1982 } else if(line[0] == 0) {
1983 /* end of initial headers */
1984 c->http_in_headers = 0;
1985 if(c->http_is_chunked)
1986 c->http_in_chunk_headers = 1;
1987 /* remove header text from front of buffer
1988 * the buffer is going to be used to return the data segment
1989 * itself and we don't want the header to get returned
1990 * prepended with it */
1991 http_moveover_buffer(c->buffer);
1992 sldns_buffer_flip(c->buffer);
1995 /* ignore other headers */
1999 /** a chunk header is complete, process it, return 0=fail, 1=continue next
2000 * header line, 2=done with chunked transfer*/
2002 http_process_chunk_header(struct comm_point* c)
2004 char* line = http_header_line(c->buffer);
2006 if(c->http_in_chunk_headers == 3) {
2007 verbose(VERB_ALGO, "http chunk trailer: %s", line);
2009 if(line[0] == 0 && c->tcp_byte_count == 0) {
2010 /* callback of http reader when NETEVENT_DONE,
2011 * end of data, with no data in buffer */
2012 sldns_buffer_set_position(c->buffer, 0);
2013 sldns_buffer_set_limit(c->buffer, 0);
2014 fptr_ok(fptr_whitelist_comm_point(c->callback));
2015 (void)(*c->callback)(c, c->cb_arg, NETEVENT_DONE, NULL);
2016 /* return that we are done */
2020 /* continue with header of the next chunk */
2021 c->http_in_chunk_headers = 1;
2022 /* remove header text from front of buffer */
2023 http_moveover_buffer(c->buffer);
2024 sldns_buffer_flip(c->buffer);
2027 /* ignore further trail headers */
2030 verbose(VERB_ALGO, "http chunk header: %s", line);
2031 if(c->http_in_chunk_headers == 1) {
2032 /* read chunked start line */
2034 c->tcp_byte_count = (size_t)strtol(line, &end, 16);
2037 c->http_in_chunk_headers = 0;
2038 /* remove header text from front of buffer */
2039 http_moveover_buffer(c->buffer);
2040 sldns_buffer_flip(c->buffer);
2041 if(c->tcp_byte_count == 0) {
2042 /* done with chunks, process chunk_trailer lines */
2043 c->http_in_chunk_headers = 3;
2047 /* ignore other headers */
2051 /** handle nonchunked data segment */
2053 http_nonchunk_segment(struct comm_point* c)
2055 /* c->buffer at position..limit has new data we read in.
2056 * the buffer itself is full of nonchunked data.
2057 * we are looking to read tcp_byte_count more data
2058 * and then the transfer is done. */
2059 size_t remainbufferlen;
2060 size_t got_now = sldns_buffer_limit(c->buffer) - c->http_stored;
2061 if(c->tcp_byte_count <= got_now) {
2062 /* done, this is the last data fragment */
2064 sldns_buffer_set_position(c->buffer, 0);
2065 fptr_ok(fptr_whitelist_comm_point(c->callback));
2066 (void)(*c->callback)(c, c->cb_arg, NETEVENT_DONE, NULL);
2069 c->tcp_byte_count -= got_now;
2070 /* if we have the buffer space,
2071 * read more data collected into the buffer */
2072 remainbufferlen = sldns_buffer_capacity(c->buffer) -
2073 sldns_buffer_limit(c->buffer);
2074 if(remainbufferlen >= c->tcp_byte_count ||
2075 remainbufferlen >= 2048) {
2076 size_t total = sldns_buffer_limit(c->buffer);
2077 sldns_buffer_clear(c->buffer);
2078 sldns_buffer_set_position(c->buffer, total);
2079 c->http_stored = total;
2080 /* return and wait to read more */
2083 /* call callback with this data amount, then
2086 sldns_buffer_set_position(c->buffer, 0);
2087 fptr_ok(fptr_whitelist_comm_point(c->callback));
2088 (void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, NULL);
2089 /* c->callback has to buffer_clear(c->buffer). */
2090 /* return and wait to read more */
2094 /** handle nonchunked data segment, return 0=fail, 1=wait, 2=process more */
2096 http_chunked_segment(struct comm_point* c)
2098 /* the c->buffer has from position..limit new data we read. */
2099 /* the current chunk has length tcp_byte_count.
2100 * once we read that read more chunk headers.
2102 size_t remainbufferlen;
2103 size_t got_now = sldns_buffer_limit(c->buffer) - c->http_stored;
2104 if(c->tcp_byte_count <= got_now) {
2105 /* the chunk has completed (with perhaps some extra data
2106 * from next chunk header and next chunk) */
2107 /* save too much info into temp buffer */
2109 struct comm_reply repinfo;
2111 sldns_buffer_skip(c->buffer, (ssize_t)c->tcp_byte_count);
2112 sldns_buffer_clear(c->http_temp);
2113 sldns_buffer_write(c->http_temp,
2114 sldns_buffer_current(c->buffer),
2115 sldns_buffer_remaining(c->buffer));
2116 sldns_buffer_flip(c->http_temp);
2118 /* callback with this fragment */
2119 fraglen = sldns_buffer_position(c->buffer);
2120 sldns_buffer_set_position(c->buffer, 0);
2121 sldns_buffer_set_limit(c->buffer, fraglen);
2122 repinfo = c->repinfo;
2123 fptr_ok(fptr_whitelist_comm_point(c->callback));
2124 (void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, &repinfo);
2125 /* c->callback has to buffer_clear(). */
2127 /* is commpoint deleted? */
2131 /* copy waiting info */
2132 sldns_buffer_clear(c->buffer);
2133 sldns_buffer_write(c->buffer,
2134 sldns_buffer_begin(c->http_temp),
2135 sldns_buffer_remaining(c->http_temp));
2136 sldns_buffer_flip(c->buffer);
2137 /* process end of chunk trailer header lines, until
2139 c->http_in_chunk_headers = 3;
2140 /* process more data in buffer (if any) */
2143 c->tcp_byte_count -= got_now;
2145 /* if we have the buffer space,
2146 * read more data collected into the buffer */
2147 remainbufferlen = sldns_buffer_capacity(c->buffer) -
2148 sldns_buffer_limit(c->buffer);
2149 if(remainbufferlen >= c->tcp_byte_count ||
2150 remainbufferlen >= 2048) {
2151 size_t total = sldns_buffer_limit(c->buffer);
2152 sldns_buffer_clear(c->buffer);
2153 sldns_buffer_set_position(c->buffer, total);
2154 c->http_stored = total;
2155 /* return and wait to read more */
2159 /* callback of http reader for a new part of the data */
2161 sldns_buffer_set_position(c->buffer, 0);
2162 fptr_ok(fptr_whitelist_comm_point(c->callback));
2163 (void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, NULL);
2164 /* c->callback has to buffer_clear(c->buffer). */
2165 /* return and wait to read more */
2170 * Handle http reading callback.
2171 * @param fd: file descriptor of socket.
2172 * @param c: comm point to read from into buffer.
2173 * @return: 0 on error
2176 comm_point_http_handle_read(int fd, struct comm_point* c)
2178 log_assert(c->type == comm_http);
2179 log_assert(fd != -1);
2181 /* if we are in ssl handshake, handle SSL handshake */
2183 if(c->ssl && c->ssl_shake_state != comm_ssl_shake_none) {
2184 if(!ssl_handshake(c))
2186 if(c->ssl_shake_state != comm_ssl_shake_none)
2189 #endif /* HAVE_SSL */
2191 if(!c->tcp_is_reading)
2193 /* read more data */
2195 if(!ssl_http_read_more(c))
2198 if(!http_read_more(fd, c))
2202 sldns_buffer_flip(c->buffer);
2203 while(sldns_buffer_remaining(c->buffer) > 0) {
2204 /* if we are reading headers, read more headers */
2205 if(c->http_in_headers || c->http_in_chunk_headers) {
2206 /* if header is done, process the header */
2207 if(!http_header_done(c->buffer)) {
2208 /* copy remaining data to front of buffer
2209 * and set rest for writing into it */
2210 http_moveover_buffer(c->buffer);
2211 /* return and wait to read more */
2214 if(!c->http_in_chunk_headers) {
2215 /* process initial headers */
2216 if(!http_process_initial_header(c))
2219 /* process chunk headers */
2220 int r = http_process_chunk_header(c);
2221 if(r == 0) return 0;
2222 if(r == 2) return 1; /* done */
2223 /* r == 1, continue */
2225 /* see if we have more to process */
2229 if(!c->http_is_chunked) {
2230 /* if we are reading nonchunks, process that*/
2231 return http_nonchunk_segment(c);
2233 /* if we are reading chunks, read the chunk */
2234 int r = http_chunked_segment(c);
2235 if(r == 0) return 0;
2236 if(r == 1) return 1;
2240 /* broke out of the loop; could not process header instead need
2242 /* moveover any remaining data and read more data */
2243 http_moveover_buffer(c->buffer);
2244 /* return and wait to read more */
2248 /** check pending connect for http */
2250 http_check_connect(int fd, struct comm_point* c)
2252 /* check for pending error from nonblocking connect */
2253 /* from Stevens, unix network programming, vol1, 3rd ed, p450*/
2255 socklen_t len = (socklen_t)sizeof(error);
2256 if(getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&error,
2259 error = errno; /* on solaris errno is error */
2260 #else /* USE_WINSOCK */
2261 error = WSAGetLastError();
2265 #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
2266 if(error == EINPROGRESS || error == EWOULDBLOCK)
2267 return 1; /* try again later */
2270 if(error != 0 && verbosity < 2)
2271 return 0; /* silence lots of chatter in the logs */
2272 else if(error != 0) {
2273 log_err_addr("http connect", strerror(error),
2274 &c->repinfo.addr, c->repinfo.addrlen);
2275 #else /* USE_WINSOCK */
2277 if(error == WSAEINPROGRESS)
2279 else if(error == WSAEWOULDBLOCK) {
2280 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
2282 } else if(error != 0 && verbosity < 2)
2284 else if(error != 0) {
2285 log_err_addr("http connect", wsa_strerror(error),
2286 &c->repinfo.addr, c->repinfo.addrlen);
2287 #endif /* USE_WINSOCK */
2290 /* keep on processing this socket */
2294 /** write more data for http (with ssl) */
2296 ssl_http_write_more(struct comm_point* c)
2300 log_assert(sldns_buffer_remaining(c->buffer) > 0);
2302 r = SSL_write(c->ssl, (void*)sldns_buffer_current(c->buffer),
2303 (int)sldns_buffer_remaining(c->buffer));
2305 int want = SSL_get_error(c->ssl, r);
2306 if(want == SSL_ERROR_ZERO_RETURN) {
2307 return 0; /* closed */
2308 } else if(want == SSL_ERROR_WANT_READ) {
2309 c->ssl_shake_state = comm_ssl_shake_hs_read;
2310 comm_point_listen_for_rw(c, 1, 0);
2311 return 1; /* wait for read condition */
2312 } else if(want == SSL_ERROR_WANT_WRITE) {
2313 return 1; /* write more later */
2314 } else if(want == SSL_ERROR_SYSCALL) {
2316 if(errno == EPIPE && verbosity < 2)
2317 return 0; /* silence 'broken pipe' */
2320 log_err("SSL_write syscall: %s",
2324 log_crypto_err("could not SSL_write");
2327 sldns_buffer_skip(c->buffer, (ssize_t)r);
2332 #endif /* HAVE_SSL */
2335 /** write more data for http */
2337 http_write_more(int fd, struct comm_point* c)
2340 log_assert(sldns_buffer_remaining(c->buffer) > 0);
2341 r = send(fd, (void*)sldns_buffer_current(c->buffer),
2342 sldns_buffer_remaining(c->buffer), 0);
2345 if(errno == EINTR || errno == EAGAIN)
2347 log_err_addr("http send r", strerror(errno),
2348 &c->repinfo.addr, c->repinfo.addrlen);
2350 if(WSAGetLastError() == WSAEINPROGRESS)
2352 if(WSAGetLastError() == WSAEWOULDBLOCK) {
2353 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
2356 log_err_addr("http send r", wsa_strerror(WSAGetLastError()),
2357 &c->repinfo.addr, c->repinfo.addrlen);
2361 sldns_buffer_skip(c->buffer, r);
2366 * Handle http writing callback.
2367 * @param fd: file descriptor of socket.
2368 * @param c: comm point to write buffer out of.
2369 * @return: 0 on error
2372 comm_point_http_handle_write(int fd, struct comm_point* c)
2374 log_assert(c->type == comm_http);
2375 log_assert(fd != -1);
2377 /* check pending connect errors, if that fails, we wait for more,
2378 * or we can continue to write contents */
2379 if(c->tcp_check_nb_connect) {
2380 int r = http_check_connect(fd, c);
2381 if(r == 0) return 0;
2382 if(r == 1) return 1;
2383 c->tcp_check_nb_connect = 0;
2385 /* if we are in ssl handshake, handle SSL handshake */
2387 if(c->ssl && c->ssl_shake_state != comm_ssl_shake_none) {
2388 if(!ssl_handshake(c))
2390 if(c->ssl_shake_state != comm_ssl_shake_none)
2393 #endif /* HAVE_SSL */
2394 if(c->tcp_is_reading)
2396 /* if we are writing, write more */
2398 if(!ssl_http_write_more(c))
2401 if(!http_write_more(fd, c))
2405 /* we write a single buffer contents, that can contain
2406 * the http request, and then flip to read the results */
2407 /* see if write is done */
2408 if(sldns_buffer_remaining(c->buffer) == 0) {
2409 sldns_buffer_clear(c->buffer);
2410 if(c->tcp_do_toggle_rw)
2411 c->tcp_is_reading = 1;
2412 c->tcp_byte_count = 0;
2413 /* switch from listening(write) to listening(read) */
2414 comm_point_stop_listening(c);
2415 comm_point_start_listening(c, -1, -1);
2421 comm_point_http_handle_callback(int fd, short event, void* arg)
2423 struct comm_point* c = (struct comm_point*)arg;
2424 log_assert(c->type == comm_http);
2425 ub_comm_base_now(c->ev->base);
2427 if(event&UB_EV_TIMEOUT) {
2428 verbose(VERB_QUERY, "http took too long, dropped");
2429 reclaim_http_handler(c);
2430 if(!c->tcp_do_close) {
2431 fptr_ok(fptr_whitelist_comm_point(c->callback));
2432 (void)(*c->callback)(c, c->cb_arg,
2433 NETEVENT_TIMEOUT, NULL);
2437 if(event&UB_EV_READ) {
2438 if(!comm_point_http_handle_read(fd, c)) {
2439 reclaim_http_handler(c);
2440 if(!c->tcp_do_close) {
2441 fptr_ok(fptr_whitelist_comm_point(
2443 (void)(*c->callback)(c, c->cb_arg,
2444 NETEVENT_CLOSED, NULL);
2449 if(event&UB_EV_WRITE) {
2450 if(!comm_point_http_handle_write(fd, c)) {
2451 reclaim_http_handler(c);
2452 if(!c->tcp_do_close) {
2453 fptr_ok(fptr_whitelist_comm_point(
2455 (void)(*c->callback)(c, c->cb_arg,
2456 NETEVENT_CLOSED, NULL);
2461 log_err("Ignored event %d for httphdl.", event);
2464 void comm_point_local_handle_callback(int fd, short event, void* arg)
2466 struct comm_point* c = (struct comm_point*)arg;
2467 log_assert(c->type == comm_local);
2468 ub_comm_base_now(c->ev->base);
2470 if(event&UB_EV_READ) {
2471 if(!comm_point_tcp_handle_read(fd, c, 1)) {
2472 fptr_ok(fptr_whitelist_comm_point(c->callback));
2473 (void)(*c->callback)(c, c->cb_arg, NETEVENT_CLOSED,
2478 log_err("Ignored event %d for localhdl.", event);
2481 void comm_point_raw_handle_callback(int ATTR_UNUSED(fd),
2482 short event, void* arg)
2484 struct comm_point* c = (struct comm_point*)arg;
2485 int err = NETEVENT_NOERROR;
2486 log_assert(c->type == comm_raw);
2487 ub_comm_base_now(c->ev->base);
2489 if(event&UB_EV_TIMEOUT)
2490 err = NETEVENT_TIMEOUT;
2491 fptr_ok(fptr_whitelist_comm_point_raw(c->callback));
2492 (void)(*c->callback)(c, c->cb_arg, err, NULL);
2496 comm_point_create_udp(struct comm_base *base, int fd, sldns_buffer* buffer,
2497 comm_point_callback_type* callback, void* callback_arg)
2499 struct comm_point* c = (struct comm_point*)calloc(1,
2500 sizeof(struct comm_point));
2504 c->ev = (struct internal_event*)calloc(1,
2505 sizeof(struct internal_event));
2514 c->tcp_is_reading = 0;
2515 c->tcp_byte_count = 0;
2516 c->tcp_parent = NULL;
2517 c->max_tcp_count = 0;
2518 c->cur_tcp_count = 0;
2519 c->tcp_handlers = NULL;
2522 c->tcp_do_close = 0;
2523 c->do_not_close = 0;
2524 c->tcp_do_toggle_rw = 0;
2525 c->tcp_check_nb_connect = 0;
2526 #ifdef USE_MSG_FASTOPEN
2527 c->tcp_do_fastopen = 0;
2531 c->dnscrypt_buffer = buffer;
2534 c->callback = callback;
2535 c->cb_arg = callback_arg;
2536 evbits = UB_EV_READ | UB_EV_PERSIST;
2537 /* ub_event stuff */
2538 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2539 comm_point_udp_callback, c);
2540 if(c->ev->ev == NULL) {
2541 log_err("could not baseset udp event");
2542 comm_point_delete(c);
2545 if(fd!=-1 && ub_event_add(c->ev->ev, c->timeout) != 0 ) {
2546 log_err("could not add udp event");
2547 comm_point_delete(c);
2554 comm_point_create_udp_ancil(struct comm_base *base, int fd,
2555 sldns_buffer* buffer,
2556 comm_point_callback_type* callback, void* callback_arg)
2558 struct comm_point* c = (struct comm_point*)calloc(1,
2559 sizeof(struct comm_point));
2563 c->ev = (struct internal_event*)calloc(1,
2564 sizeof(struct internal_event));
2573 c->tcp_is_reading = 0;
2574 c->tcp_byte_count = 0;
2575 c->tcp_parent = NULL;
2576 c->max_tcp_count = 0;
2577 c->cur_tcp_count = 0;
2578 c->tcp_handlers = NULL;
2581 c->tcp_do_close = 0;
2582 c->do_not_close = 0;
2585 c->dnscrypt_buffer = buffer;
2588 c->tcp_do_toggle_rw = 0;
2589 c->tcp_check_nb_connect = 0;
2590 #ifdef USE_MSG_FASTOPEN
2591 c->tcp_do_fastopen = 0;
2593 c->callback = callback;
2594 c->cb_arg = callback_arg;
2595 evbits = UB_EV_READ | UB_EV_PERSIST;
2596 /* ub_event stuff */
2597 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2598 comm_point_udp_ancil_callback, c);
2599 if(c->ev->ev == NULL) {
2600 log_err("could not baseset udp event");
2601 comm_point_delete(c);
2604 if(fd!=-1 && ub_event_add(c->ev->ev, c->timeout) != 0 ) {
2605 log_err("could not add udp event");
2606 comm_point_delete(c);
2612 static struct comm_point*
2613 comm_point_create_tcp_handler(struct comm_base *base,
2614 struct comm_point* parent, size_t bufsize,
2615 struct sldns_buffer* spoolbuf, comm_point_callback_type* callback,
2618 struct comm_point* c = (struct comm_point*)calloc(1,
2619 sizeof(struct comm_point));
2623 c->ev = (struct internal_event*)calloc(1,
2624 sizeof(struct internal_event));
2631 c->buffer = sldns_buffer_new(bufsize);
2637 c->timeout = (struct timeval*)malloc(sizeof(struct timeval));
2639 sldns_buffer_free(c->buffer);
2644 c->tcp_is_reading = 0;
2645 c->tcp_byte_count = 0;
2646 c->tcp_parent = parent;
2647 c->tcp_timeout_msec = parent->tcp_timeout_msec;
2648 c->tcp_conn_limit = parent->tcp_conn_limit;
2650 c->tcp_keepalive = 0;
2651 c->max_tcp_count = 0;
2652 c->cur_tcp_count = 0;
2653 c->tcp_handlers = NULL;
2656 c->tcp_do_close = 0;
2657 c->do_not_close = 0;
2658 c->tcp_do_toggle_rw = 1;
2659 c->tcp_check_nb_connect = 0;
2660 #ifdef USE_MSG_FASTOPEN
2661 c->tcp_do_fastopen = 0;
2665 /* We don't know just yet if this is a dnscrypt channel. Allocation
2666 * will be done when handling the callback. */
2667 c->dnscrypt_buffer = c->buffer;
2670 c->callback = callback;
2671 c->cb_arg = callback_arg;
2673 c->tcp_req_info = tcp_req_info_create(spoolbuf);
2674 if(!c->tcp_req_info) {
2675 log_err("could not create tcp commpoint");
2676 sldns_buffer_free(c->buffer);
2682 c->tcp_req_info->cp = c;
2683 c->tcp_do_close = 1;
2684 c->tcp_do_toggle_rw = 0;
2686 /* add to parent free list */
2687 c->tcp_free = parent->tcp_free;
2688 parent->tcp_free = c;
2689 /* ub_event stuff */
2690 evbits = UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT;
2691 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2692 comm_point_tcp_handle_callback, c);
2693 if(c->ev->ev == NULL)
2695 log_err("could not basetset tcphdl event");
2696 parent->tcp_free = c->tcp_free;
2697 tcp_req_info_delete(c->tcp_req_info);
2698 sldns_buffer_free(c->buffer);
2708 comm_point_create_tcp(struct comm_base *base, int fd, int num,
2709 int idle_timeout, struct tcl_list* tcp_conn_limit, size_t bufsize,
2710 struct sldns_buffer* spoolbuf, comm_point_callback_type* callback,
2713 struct comm_point* c = (struct comm_point*)calloc(1,
2714 sizeof(struct comm_point));
2717 /* first allocate the TCP accept listener */
2720 c->ev = (struct internal_event*)calloc(1,
2721 sizeof(struct internal_event));
2730 c->tcp_is_reading = 0;
2731 c->tcp_byte_count = 0;
2732 c->tcp_timeout_msec = idle_timeout;
2733 c->tcp_conn_limit = tcp_conn_limit;
2735 c->tcp_keepalive = 0;
2736 c->tcp_parent = NULL;
2737 c->max_tcp_count = num;
2738 c->cur_tcp_count = 0;
2739 c->tcp_handlers = (struct comm_point**)calloc((size_t)num,
2740 sizeof(struct comm_point*));
2741 if(!c->tcp_handlers) {
2747 c->type = comm_tcp_accept;
2748 c->tcp_do_close = 0;
2749 c->do_not_close = 0;
2750 c->tcp_do_toggle_rw = 0;
2751 c->tcp_check_nb_connect = 0;
2752 #ifdef USE_MSG_FASTOPEN
2753 c->tcp_do_fastopen = 0;
2757 c->dnscrypt_buffer = NULL;
2761 evbits = UB_EV_READ | UB_EV_PERSIST;
2762 /* ub_event stuff */
2763 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2764 comm_point_tcp_accept_callback, c);
2765 if(c->ev->ev == NULL) {
2766 log_err("could not baseset tcpacc event");
2767 comm_point_delete(c);
2770 if (ub_event_add(c->ev->ev, c->timeout) != 0) {
2771 log_err("could not add tcpacc event");
2772 comm_point_delete(c);
2775 /* now prealloc the tcp handlers */
2776 for(i=0; i<num; i++) {
2777 c->tcp_handlers[i] = comm_point_create_tcp_handler(base,
2778 c, bufsize, spoolbuf, callback, callback_arg);
2779 if(!c->tcp_handlers[i]) {
2780 comm_point_delete(c);
2789 comm_point_create_tcp_out(struct comm_base *base, size_t bufsize,
2790 comm_point_callback_type* callback, void* callback_arg)
2792 struct comm_point* c = (struct comm_point*)calloc(1,
2793 sizeof(struct comm_point));
2797 c->ev = (struct internal_event*)calloc(1,
2798 sizeof(struct internal_event));
2805 c->buffer = sldns_buffer_new(bufsize);
2812 c->tcp_is_reading = 0;
2813 c->tcp_byte_count = 0;
2814 c->tcp_timeout_msec = TCP_QUERY_TIMEOUT;
2815 c->tcp_conn_limit = NULL;
2817 c->tcp_keepalive = 0;
2818 c->tcp_parent = NULL;
2819 c->max_tcp_count = 0;
2820 c->cur_tcp_count = 0;
2821 c->tcp_handlers = NULL;
2824 c->tcp_do_close = 0;
2825 c->do_not_close = 0;
2826 c->tcp_do_toggle_rw = 1;
2827 c->tcp_check_nb_connect = 1;
2828 #ifdef USE_MSG_FASTOPEN
2829 c->tcp_do_fastopen = 1;
2833 c->dnscrypt_buffer = c->buffer;
2836 c->callback = callback;
2837 c->cb_arg = callback_arg;
2838 evbits = UB_EV_PERSIST | UB_EV_WRITE;
2839 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2840 comm_point_tcp_handle_callback, c);
2841 if(c->ev->ev == NULL)
2843 log_err("could not baseset tcpout event");
2844 sldns_buffer_free(c->buffer);
2854 comm_point_create_http_out(struct comm_base *base, size_t bufsize,
2855 comm_point_callback_type* callback, void* callback_arg,
2858 struct comm_point* c = (struct comm_point*)calloc(1,
2859 sizeof(struct comm_point));
2863 c->ev = (struct internal_event*)calloc(1,
2864 sizeof(struct internal_event));
2871 c->buffer = sldns_buffer_new(bufsize);
2878 c->tcp_is_reading = 0;
2879 c->tcp_byte_count = 0;
2880 c->tcp_parent = NULL;
2881 c->max_tcp_count = 0;
2882 c->cur_tcp_count = 0;
2883 c->tcp_handlers = NULL;
2885 c->type = comm_http;
2886 c->tcp_do_close = 0;
2887 c->do_not_close = 0;
2888 c->tcp_do_toggle_rw = 1;
2889 c->tcp_check_nb_connect = 1;
2890 c->http_in_headers = 1;
2891 c->http_in_chunk_headers = 0;
2892 c->http_is_chunked = 0;
2893 c->http_temp = temp;
2894 #ifdef USE_MSG_FASTOPEN
2895 c->tcp_do_fastopen = 1;
2899 c->dnscrypt_buffer = c->buffer;
2902 c->callback = callback;
2903 c->cb_arg = callback_arg;
2904 evbits = UB_EV_PERSIST | UB_EV_WRITE;
2905 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2906 comm_point_http_handle_callback, c);
2907 if(c->ev->ev == NULL)
2909 log_err("could not baseset tcpout event");
2913 sldns_buffer_free(c->buffer);
2923 comm_point_create_local(struct comm_base *base, int fd, size_t bufsize,
2924 comm_point_callback_type* callback, void* callback_arg)
2926 struct comm_point* c = (struct comm_point*)calloc(1,
2927 sizeof(struct comm_point));
2931 c->ev = (struct internal_event*)calloc(1,
2932 sizeof(struct internal_event));
2939 c->buffer = sldns_buffer_new(bufsize);
2946 c->tcp_is_reading = 1;
2947 c->tcp_byte_count = 0;
2948 c->tcp_parent = NULL;
2949 c->max_tcp_count = 0;
2950 c->cur_tcp_count = 0;
2951 c->tcp_handlers = NULL;
2953 c->type = comm_local;
2954 c->tcp_do_close = 0;
2955 c->do_not_close = 1;
2956 c->tcp_do_toggle_rw = 0;
2957 c->tcp_check_nb_connect = 0;
2958 #ifdef USE_MSG_FASTOPEN
2959 c->tcp_do_fastopen = 0;
2963 c->dnscrypt_buffer = c->buffer;
2965 c->callback = callback;
2966 c->cb_arg = callback_arg;
2967 /* ub_event stuff */
2968 evbits = UB_EV_PERSIST | UB_EV_READ;
2969 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2970 comm_point_local_handle_callback, c);
2971 if(c->ev->ev == NULL) {
2972 log_err("could not baseset localhdl event");
2977 if (ub_event_add(c->ev->ev, c->timeout) != 0) {
2978 log_err("could not add localhdl event");
2979 ub_event_free(c->ev->ev);
2988 comm_point_create_raw(struct comm_base* base, int fd, int writing,
2989 comm_point_callback_type* callback, void* callback_arg)
2991 struct comm_point* c = (struct comm_point*)calloc(1,
2992 sizeof(struct comm_point));
2996 c->ev = (struct internal_event*)calloc(1,
2997 sizeof(struct internal_event));
3006 c->tcp_is_reading = 0;
3007 c->tcp_byte_count = 0;
3008 c->tcp_parent = NULL;
3009 c->max_tcp_count = 0;
3010 c->cur_tcp_count = 0;
3011 c->tcp_handlers = NULL;
3014 c->tcp_do_close = 0;
3015 c->do_not_close = 1;
3016 c->tcp_do_toggle_rw = 0;
3017 c->tcp_check_nb_connect = 0;
3018 #ifdef USE_MSG_FASTOPEN
3019 c->tcp_do_fastopen = 0;
3023 c->dnscrypt_buffer = c->buffer;
3025 c->callback = callback;
3026 c->cb_arg = callback_arg;
3027 /* ub_event stuff */
3029 evbits = UB_EV_PERSIST | UB_EV_WRITE;
3030 else evbits = UB_EV_PERSIST | UB_EV_READ;
3031 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
3032 comm_point_raw_handle_callback, c);
3033 if(c->ev->ev == NULL) {
3034 log_err("could not baseset rawhdl event");
3039 if (ub_event_add(c->ev->ev, c->timeout) != 0) {
3040 log_err("could not add rawhdl event");
3041 ub_event_free(c->ev->ev);
3050 comm_point_close(struct comm_point* c)
3055 if(ub_event_del(c->ev->ev) != 0) {
3056 log_err("could not event_del on close");
3059 tcl_close_connection(c->tcl_addr);
3061 tcp_req_info_clear(c->tcp_req_info);
3062 /* close fd after removing from event lists, or epoll.. is messed up */
3063 if(c->fd != -1 && !c->do_not_close) {
3064 if(c->type == comm_tcp || c->type == comm_http) {
3065 /* delete sticky events for the fd, it gets closed */
3066 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
3067 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
3069 verbose(VERB_ALGO, "close fd %d", c->fd);
3080 comm_point_delete(struct comm_point* c)
3084 if((c->type == comm_tcp || c->type == comm_http) && c->ssl) {
3086 SSL_shutdown(c->ssl);
3090 comm_point_close(c);
3091 if(c->tcp_handlers) {
3093 for(i=0; i<c->max_tcp_count; i++)
3094 comm_point_delete(c->tcp_handlers[i]);
3095 free(c->tcp_handlers);
3098 if(c->type == comm_tcp || c->type == comm_local || c->type == comm_http) {
3099 sldns_buffer_free(c->buffer);
3101 if(c->dnscrypt && c->dnscrypt_buffer != c->buffer) {
3102 sldns_buffer_free(c->dnscrypt_buffer);
3105 if(c->tcp_req_info) {
3106 tcp_req_info_delete(c->tcp_req_info);
3109 ub_event_free(c->ev->ev);
3115 comm_point_send_reply(struct comm_reply *repinfo)
3117 struct sldns_buffer* buffer;
3118 log_assert(repinfo && repinfo->c);
3120 buffer = repinfo->c->dnscrypt_buffer;
3121 if(!dnsc_handle_uncurved_request(repinfo)) {
3125 buffer = repinfo->c->buffer;
3127 if(repinfo->c->type == comm_udp) {
3128 if(repinfo->srctype)
3129 comm_point_send_udp_msg_if(repinfo->c,
3130 buffer, (struct sockaddr*)&repinfo->addr,
3131 repinfo->addrlen, repinfo);
3133 comm_point_send_udp_msg(repinfo->c, buffer,
3134 (struct sockaddr*)&repinfo->addr, repinfo->addrlen);
3136 if(repinfo->c->dtenv != NULL &&
3137 repinfo->c->dtenv->log_client_response_messages)
3138 dt_msg_send_client_response(repinfo->c->dtenv,
3139 &repinfo->addr, repinfo->c->type, repinfo->c->buffer);
3143 if(repinfo->c->tcp_parent->dtenv != NULL &&
3144 repinfo->c->tcp_parent->dtenv->log_client_response_messages)
3145 dt_msg_send_client_response(repinfo->c->tcp_parent->dtenv,
3146 &repinfo->addr, repinfo->c->type, repinfo->c->buffer);
3148 if(repinfo->c->tcp_req_info) {
3149 tcp_req_info_send_reply(repinfo->c->tcp_req_info);
3151 comm_point_start_listening(repinfo->c, -1,
3152 repinfo->c->tcp_timeout_msec);
3158 comm_point_drop_reply(struct comm_reply* repinfo)
3162 log_assert(repinfo && repinfo->c);
3163 log_assert(repinfo->c->type != comm_tcp_accept);
3164 if(repinfo->c->type == comm_udp)
3166 if(repinfo->c->tcp_req_info)
3167 repinfo->c->tcp_req_info->is_drop = 1;
3168 reclaim_tcp_handler(repinfo->c);
3172 comm_point_stop_listening(struct comm_point* c)
3174 verbose(VERB_ALGO, "comm point stop listening %d", c->fd);
3175 if(ub_event_del(c->ev->ev) != 0) {
3176 log_err("event_del error to stoplisten");
3181 comm_point_start_listening(struct comm_point* c, int newfd, int msec)
3183 verbose(VERB_ALGO, "comm point start listening %d (%d msec)",
3184 c->fd==-1?newfd:c->fd, msec);
3185 if(c->type == comm_tcp_accept && !c->tcp_free) {
3186 /* no use to start listening no free slots. */
3189 if(msec != -1 && msec != 0) {
3191 c->timeout = (struct timeval*)malloc(sizeof(
3194 log_err("cpsl: malloc failed. No net read.");
3198 ub_event_add_bits(c->ev->ev, UB_EV_TIMEOUT);
3199 #ifndef S_SPLINT_S /* splint fails on struct timeval. */
3200 c->timeout->tv_sec = msec/1000;
3201 c->timeout->tv_usec = (msec%1000)*1000;
3202 #endif /* S_SPLINT_S */
3204 if(c->type == comm_tcp || c->type == comm_http) {
3205 ub_event_del_bits(c->ev->ev, UB_EV_READ|UB_EV_WRITE);
3206 if(c->tcp_is_reading)
3207 ub_event_add_bits(c->ev->ev, UB_EV_READ);
3208 else ub_event_add_bits(c->ev->ev, UB_EV_WRITE);
3219 ub_event_set_fd(c->ev->ev, c->fd);
3221 if(ub_event_add(c->ev->ev, msec==0?NULL:c->timeout) != 0) {
3222 log_err("event_add failed. in cpsl.");
3226 void comm_point_listen_for_rw(struct comm_point* c, int rd, int wr)
3228 verbose(VERB_ALGO, "comm point listen_for_rw %d %d", c->fd, wr);
3229 if(ub_event_del(c->ev->ev) != 0) {
3230 log_err("event_del error to cplf");
3232 ub_event_del_bits(c->ev->ev, UB_EV_READ|UB_EV_WRITE);
3233 if(rd) ub_event_add_bits(c->ev->ev, UB_EV_READ);
3234 if(wr) ub_event_add_bits(c->ev->ev, UB_EV_WRITE);
3235 if(ub_event_add(c->ev->ev, c->timeout) != 0) {
3236 log_err("event_add failed. in cplf.");
3240 size_t comm_point_get_mem(struct comm_point* c)
3245 s = sizeof(*c) + sizeof(*c->ev);
3247 s += sizeof(*c->timeout);
3248 if(c->type == comm_tcp || c->type == comm_local) {
3249 s += sizeof(*c->buffer) + sldns_buffer_capacity(c->buffer);
3251 s += sizeof(*c->dnscrypt_buffer);
3252 if(c->buffer != c->dnscrypt_buffer) {
3253 s += sldns_buffer_capacity(c->dnscrypt_buffer);
3257 if(c->type == comm_tcp_accept) {
3259 for(i=0; i<c->max_tcp_count; i++)
3260 s += comm_point_get_mem(c->tcp_handlers[i]);
3266 comm_timer_create(struct comm_base* base, void (*cb)(void*), void* cb_arg)
3268 struct internal_timer *tm = (struct internal_timer*)calloc(1,
3269 sizeof(struct internal_timer));
3271 log_err("malloc failed");
3274 tm->super.ev_timer = tm;
3276 tm->super.callback = cb;
3277 tm->super.cb_arg = cb_arg;
3278 tm->ev = ub_event_new(base->eb->base, -1, UB_EV_TIMEOUT,
3279 comm_timer_callback, &tm->super);
3280 if(tm->ev == NULL) {
3281 log_err("timer_create: event_base_set failed.");
3289 comm_timer_disable(struct comm_timer* timer)
3293 ub_timer_del(timer->ev_timer->ev);
3294 timer->ev_timer->enabled = 0;
3298 comm_timer_set(struct comm_timer* timer, struct timeval* tv)
3301 if(timer->ev_timer->enabled)
3302 comm_timer_disable(timer);
3303 if(ub_timer_add(timer->ev_timer->ev, timer->ev_timer->base->eb->base,
3304 comm_timer_callback, timer, tv) != 0)
3305 log_err("comm_timer_set: evtimer_add failed.");
3306 timer->ev_timer->enabled = 1;
3310 comm_timer_delete(struct comm_timer* timer)
3314 comm_timer_disable(timer);
3315 /* Free the sub struct timer->ev_timer derived from the super struct timer.
3316 * i.e. assert(timer == timer->ev_timer)
3318 ub_event_free(timer->ev_timer->ev);
3319 free(timer->ev_timer);
3323 comm_timer_callback(int ATTR_UNUSED(fd), short event, void* arg)
3325 struct comm_timer* tm = (struct comm_timer*)arg;
3326 if(!(event&UB_EV_TIMEOUT))
3328 ub_comm_base_now(tm->ev_timer->base);
3329 tm->ev_timer->enabled = 0;
3330 fptr_ok(fptr_whitelist_comm_timer(tm->callback));
3331 (*tm->callback)(tm->cb_arg);
3335 comm_timer_is_set(struct comm_timer* timer)
3337 return (int)timer->ev_timer->enabled;
3341 comm_timer_get_mem(struct comm_timer* ATTR_UNUSED(timer))
3343 return sizeof(struct internal_timer);
3347 comm_signal_create(struct comm_base* base,
3348 void (*callback)(int, void*), void* cb_arg)
3350 struct comm_signal* com = (struct comm_signal*)malloc(
3351 sizeof(struct comm_signal));
3353 log_err("malloc failed");
3357 com->callback = callback;
3358 com->cb_arg = cb_arg;
3359 com->ev_signal = NULL;
3364 comm_signal_callback(int sig, short event, void* arg)
3366 struct comm_signal* comsig = (struct comm_signal*)arg;
3367 if(!(event & UB_EV_SIGNAL))
3369 ub_comm_base_now(comsig->base);
3370 fptr_ok(fptr_whitelist_comm_signal(comsig->callback));
3371 (*comsig->callback)(sig, comsig->cb_arg);
3375 comm_signal_bind(struct comm_signal* comsig, int sig)
3377 struct internal_signal* entry = (struct internal_signal*)calloc(1,
3378 sizeof(struct internal_signal));
3380 log_err("malloc failed");
3384 /* add signal event */
3385 entry->ev = ub_signal_new(comsig->base->eb->base, sig,
3386 comm_signal_callback, comsig);
3387 if(entry->ev == NULL) {
3388 log_err("Could not create signal event");
3392 if(ub_signal_add(entry->ev, NULL) != 0) {
3393 log_err("Could not add signal handler");
3394 ub_event_free(entry->ev);
3398 /* link into list */
3399 entry->next = comsig->ev_signal;
3400 comsig->ev_signal = entry;
3405 comm_signal_delete(struct comm_signal* comsig)
3407 struct internal_signal* p, *np;
3410 p=comsig->ev_signal;
3413 ub_signal_del(p->ev);
3414 ub_event_free(p->ev);