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 "util/proxy_protocol.h"
49 #include "util/timeval_func.h"
50 #include "sldns/pkthdr.h"
51 #include "sldns/sbuffer.h"
52 #include "sldns/str2wire.h"
53 #include "dnstap/dnstap.h"
54 #include "dnscrypt/dnscrypt.h"
55 #include "services/listen_dnsport.h"
56 #ifdef HAVE_SYS_TYPES_H
57 #include <sys/types.h>
59 #ifdef HAVE_SYS_SOCKET_H
60 #include <sys/socket.h>
69 #ifdef HAVE_OPENSSL_SSL_H
70 #include <openssl/ssl.h>
72 #ifdef HAVE_OPENSSL_ERR_H
73 #include <openssl/err.h>
75 #ifdef HAVE_LINUX_NET_TSTAMP_H
76 #include <linux/net_tstamp.h>
78 /* -------- Start of local definitions -------- */
79 /** if CMSG_ALIGN is not defined on this platform, a workaround */
82 # define CMSG_ALIGN(n) __CMSG_ALIGN(n)
83 # elif defined(CMSG_DATA_ALIGN)
84 # define CMSG_ALIGN _CMSG_DATA_ALIGN
86 # define CMSG_ALIGN(len) (((len)+sizeof(long)-1) & ~(sizeof(long)-1))
90 /** if CMSG_LEN is not defined on this platform, a workaround */
92 # define CMSG_LEN(len) (CMSG_ALIGN(sizeof(struct cmsghdr))+(len))
95 /** if CMSG_SPACE is not defined on this platform, a workaround */
97 # ifdef _CMSG_HDR_ALIGN
98 # define CMSG_SPACE(l) (CMSG_ALIGN(l)+_CMSG_HDR_ALIGN(sizeof(struct cmsghdr)))
100 # define CMSG_SPACE(l) (CMSG_ALIGN(l)+CMSG_ALIGN(sizeof(struct cmsghdr)))
104 /** The TCP writing query timeout in milliseconds */
105 #define TCP_QUERY_TIMEOUT 120000
106 /** The minimum actual TCP timeout to use, regardless of what we advertise,
108 #define TCP_QUERY_TIMEOUT_MINIMUM 200
110 #ifndef NONBLOCKING_IS_BROKEN
111 /** number of UDP reads to perform per read indication from select */
112 #define NUM_UDP_PER_SELECT 100
114 #define NUM_UDP_PER_SELECT 1
117 /** timeout in millisec to wait for write to unblock, packets dropped after.*/
118 #define SEND_BLOCKED_WAIT_TIMEOUT 200
120 /** Let's make timestamping code cleaner and redefine SO_TIMESTAMP* */
122 #define SO_TIMESTAMP 29
124 #ifndef SO_TIMESTAMPNS
125 #define SO_TIMESTAMPNS 35
127 #ifndef SO_TIMESTAMPING
128 #define SO_TIMESTAMPING 37
131 * The internal event structure for keeping ub_event info for the event.
132 * Possibly other structures (list, tree) this is part of.
134 struct internal_event {
136 struct comm_base* base;
137 /** ub_event event type */
142 * Internal base structure, so that every thread has its own events.
144 struct internal_base {
145 /** ub_event event_base type. */
146 struct ub_event_base* base;
147 /** seconds time pointer points here */
149 /** timeval with current time */
151 /** the event used for slow_accept timeouts */
152 struct ub_event* slow_accept;
153 /** true if slow_accept is enabled */
154 int slow_accept_enabled;
155 /** last log time for slow logging of file descriptor errors */
156 time_t last_slow_log;
157 /** last log time for slow logging of write wait failures */
158 time_t last_writewait_log;
162 * Internal timer structure, to store timer event in.
164 struct internal_timer {
165 /** the super struct from which derived */
166 struct comm_timer super;
168 struct comm_base* base;
169 /** ub_event event type */
171 /** is timer enabled */
176 * Internal signal structure, to store signal event in.
178 struct internal_signal {
179 /** ub_event event type */
181 /** next in signal list */
182 struct internal_signal* next;
185 /** create a tcp handler with a parent */
186 static struct comm_point* comm_point_create_tcp_handler(
187 struct comm_base *base, struct comm_point* parent, size_t bufsize,
188 struct sldns_buffer* spoolbuf, comm_point_callback_type* callback,
189 void* callback_arg, struct unbound_socket* socket);
191 /* -------- End of local definitions -------- */
194 comm_base_create(int sigs)
196 struct comm_base* b = (struct comm_base*)calloc(1,
197 sizeof(struct comm_base));
198 const char *evnm="event", *evsys="", *evmethod="";
202 b->eb = (struct internal_base*)calloc(1, sizeof(struct internal_base));
207 b->eb->base = ub_default_event_base(sigs, &b->eb->secs, &b->eb->now);
214 ub_get_event_sys(b->eb->base, &evnm, &evsys, &evmethod);
215 verbose(VERB_ALGO, "%s %s uses %s method.", evnm, evsys, evmethod);
220 comm_base_create_event(struct ub_event_base* base)
222 struct comm_base* b = (struct comm_base*)calloc(1,
223 sizeof(struct comm_base));
226 b->eb = (struct internal_base*)calloc(1, sizeof(struct internal_base));
237 comm_base_delete(struct comm_base* b)
241 if(b->eb->slow_accept_enabled) {
242 if(ub_event_del(b->eb->slow_accept) != 0) {
243 log_err("could not event_del slow_accept");
245 ub_event_free(b->eb->slow_accept);
247 ub_event_base_free(b->eb->base);
254 comm_base_delete_no_base(struct comm_base* b)
258 if(b->eb->slow_accept_enabled) {
259 if(ub_event_del(b->eb->slow_accept) != 0) {
260 log_err("could not event_del slow_accept");
262 ub_event_free(b->eb->slow_accept);
270 comm_base_timept(struct comm_base* b, time_t** tt, struct timeval** tv)
277 comm_base_dispatch(struct comm_base* b)
280 retval = ub_event_base_dispatch(b->eb->base);
282 fatal_exit("event_dispatch returned error %d, "
283 "errno is %s", retval, strerror(errno));
287 void comm_base_exit(struct comm_base* b)
289 if(ub_event_base_loopexit(b->eb->base) != 0) {
290 log_err("Could not loopexit");
294 void comm_base_set_slow_accept_handlers(struct comm_base* b,
295 void (*stop_acc)(void*), void (*start_acc)(void*), void* arg)
297 b->stop_accept = stop_acc;
298 b->start_accept = start_acc;
302 struct ub_event_base* comm_base_internal(struct comm_base* b)
307 /** see if errno for udp has to be logged or not uses globals */
309 udp_send_errno_needs_log(struct sockaddr* addr, socklen_t addrlen)
311 /* do not log transient errors (unless high verbosity) */
312 #if defined(ENETUNREACH) || defined(EHOSTDOWN) || defined(EHOSTUNREACH) || defined(ENETDOWN)
328 if(verbosity < VERB_ALGO)
334 /* permission denied is gotten for every send if the
335 * network is disconnected (on some OS), squelch it */
336 if( ((errno == EPERM)
337 # ifdef EADDRNOTAVAIL
338 /* 'Cannot assign requested address' also when disconnected */
339 || (errno == EADDRNOTAVAIL)
341 ) && verbosity < VERB_ALGO)
344 /* If SO_REUSEADDR is set, we could try to connect to the same server
345 * from the same source port twice. */
346 if(errno == EADDRINUSE && verbosity < VERB_DETAIL)
349 /* squelch errors where people deploy AAAA ::ffff:bla for
350 * authority servers, which we try for intranets. */
351 if(errno == EINVAL && addr_is_ip4mapped(
352 (struct sockaddr_storage*)addr, addrlen) &&
353 verbosity < VERB_DETAIL)
355 /* SO_BROADCAST sockopt can give access to 255.255.255.255,
356 * but a dns cache does not need it. */
357 if(errno == EACCES && addr_is_broadcast(
358 (struct sockaddr_storage*)addr, addrlen) &&
359 verbosity < VERB_DETAIL)
364 int tcp_connect_errno_needs_log(struct sockaddr* addr, socklen_t addrlen)
366 return udp_send_errno_needs_log(addr, addrlen);
369 /* send a UDP reply */
371 comm_point_send_udp_msg(struct comm_point *c, sldns_buffer* packet,
372 struct sockaddr* addr, socklen_t addrlen, int is_connected)
375 log_assert(c->fd != -1);
377 if(sldns_buffer_remaining(packet) == 0)
378 log_err("error: send empty UDP packet");
380 log_assert(addr && addrlen > 0);
382 sent = sendto(c->fd, (void*)sldns_buffer_begin(packet),
383 sldns_buffer_remaining(packet), 0,
386 sent = send(c->fd, (void*)sldns_buffer_begin(packet),
387 sldns_buffer_remaining(packet), 0);
390 /* try again and block, waiting for IO to complete,
391 * we want to send the answer, and we will wait for
392 * the ethernet interface buffer to have space. */
394 if(errno == EAGAIN || errno == EINTR ||
396 errno == EWOULDBLOCK ||
400 if(WSAGetLastError() == WSAEINPROGRESS ||
401 WSAGetLastError() == WSAEINTR ||
402 WSAGetLastError() == WSAENOBUFS ||
403 WSAGetLastError() == WSAEWOULDBLOCK) {
405 /* if we set the fd blocking, other threads suddenly
406 * have a blocking fd that they operate on */
407 while(sent == -1 && (
409 errno == EAGAIN || errno == EINTR ||
411 errno == EWOULDBLOCK ||
415 WSAGetLastError() == WSAEINPROGRESS ||
416 WSAGetLastError() == WSAEINTR ||
417 WSAGetLastError() == WSAENOBUFS ||
418 WSAGetLastError() == WSAEWOULDBLOCK
421 #if defined(HAVE_POLL) || defined(USE_WINSOCK)
424 memset(&p, 0, sizeof(p));
426 p.events = POLLOUT | POLLERR | POLLHUP;
428 pret = poll(&p, 1, SEND_BLOCKED_WAIT_TIMEOUT);
430 pret = WSAPoll(&p, 1,
431 SEND_BLOCKED_WAIT_TIMEOUT);
435 struct comm_base* b = c->ev->base;
436 if(b->eb->last_writewait_log+SLOW_LOG_TIME <=
438 b->eb->last_writewait_log = b->eb->secs;
439 verbose(VERB_OPS, "send udp blocked "
440 "for long, dropping packet.");
443 } else if(pret < 0 &&
445 errno != EAGAIN && errno != EINTR &&
447 errno != EWOULDBLOCK &&
451 WSAGetLastError() != WSAEINPROGRESS &&
452 WSAGetLastError() != WSAEINTR &&
453 WSAGetLastError() != WSAENOBUFS &&
454 WSAGetLastError() != WSAEWOULDBLOCK
457 log_err("poll udp out failed: %s",
458 sock_strerror(errno));
461 #endif /* defined(HAVE_POLL) || defined(USE_WINSOCK) */
463 sent = sendto(c->fd, (void*)sldns_buffer_begin(packet),
464 sldns_buffer_remaining(packet), 0,
467 sent = send(c->fd, (void*)sldns_buffer_begin(packet),
468 sldns_buffer_remaining(packet), 0);
474 if(!udp_send_errno_needs_log(addr, addrlen))
477 verbose(VERB_OPS, "sendto failed: %s", sock_strerror(errno));
479 verbose(VERB_OPS, "send failed: %s", sock_strerror(errno));
482 log_addr(VERB_OPS, "remote address is",
483 (struct sockaddr_storage*)addr, addrlen);
485 } else if((size_t)sent != sldns_buffer_remaining(packet)) {
486 log_err("sent %d in place of %d bytes",
487 (int)sent, (int)sldns_buffer_remaining(packet));
493 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && (defined(HAVE_RECVMSG) || defined(HAVE_SENDMSG))
494 /** print debug ancillary info */
495 static void p_ancil(const char* str, struct comm_reply* r)
497 if(r->srctype != 4 && r->srctype != 6) {
498 log_info("%s: unknown srctype %d", str, r->srctype);
502 if(r->srctype == 6) {
505 if(inet_ntop(AF_INET6, &r->pktinfo.v6info.ipi6_addr,
506 buf, (socklen_t)sizeof(buf)) == 0) {
507 (void)strlcpy(buf, "(inet_ntop error)", sizeof(buf));
509 buf[sizeof(buf)-1]=0;
510 log_info("%s: %s %d", str, buf, r->pktinfo.v6info.ipi6_ifindex);
512 } else if(r->srctype == 4) {
514 char buf1[1024], buf2[1024];
515 if(inet_ntop(AF_INET, &r->pktinfo.v4info.ipi_addr,
516 buf1, (socklen_t)sizeof(buf1)) == 0) {
517 (void)strlcpy(buf1, "(inet_ntop error)", sizeof(buf1));
519 buf1[sizeof(buf1)-1]=0;
520 #ifdef HAVE_STRUCT_IN_PKTINFO_IPI_SPEC_DST
521 if(inet_ntop(AF_INET, &r->pktinfo.v4info.ipi_spec_dst,
522 buf2, (socklen_t)sizeof(buf2)) == 0) {
523 (void)strlcpy(buf2, "(inet_ntop error)", sizeof(buf2));
525 buf2[sizeof(buf2)-1]=0;
529 log_info("%s: %d %s %s", str, r->pktinfo.v4info.ipi_ifindex,
531 #elif defined(IP_RECVDSTADDR)
533 if(inet_ntop(AF_INET, &r->pktinfo.v4addr,
534 buf1, (socklen_t)sizeof(buf1)) == 0) {
535 (void)strlcpy(buf1, "(inet_ntop error)", sizeof(buf1));
537 buf1[sizeof(buf1)-1]=0;
538 log_info("%s: %s", str, buf1);
539 #endif /* IP_PKTINFO or PI_RECVDSTDADDR */
542 #endif /* AF_INET6 && IPV6_PKTINFO && HAVE_RECVMSG||HAVE_SENDMSG */
544 /** send a UDP reply over specified interface*/
546 comm_point_send_udp_msg_if(struct comm_point *c, sldns_buffer* packet,
547 struct sockaddr* addr, socklen_t addrlen, struct comm_reply* r)
549 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && defined(HAVE_SENDMSG)
558 struct cmsghdr *cmsg;
559 #endif /* S_SPLINT_S */
561 log_assert(c->fd != -1);
563 if(sldns_buffer_remaining(packet) == 0)
564 log_err("error: send empty UDP packet");
566 log_assert(addr && addrlen > 0);
569 msg.msg_namelen = addrlen;
570 iov[0].iov_base = sldns_buffer_begin(packet);
571 iov[0].iov_len = sldns_buffer_remaining(packet);
574 msg.msg_control = control.buf;
576 msg.msg_controllen = sizeof(control.buf);
577 #endif /* S_SPLINT_S */
581 cmsg = CMSG_FIRSTHDR(&msg);
582 if(r->srctype == 4) {
585 msg.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
586 log_assert(msg.msg_controllen <= sizeof(control.buf));
587 cmsg->cmsg_level = IPPROTO_IP;
588 cmsg->cmsg_type = IP_PKTINFO;
589 memmove(CMSG_DATA(cmsg), &r->pktinfo.v4info,
590 sizeof(struct in_pktinfo));
591 /* unset the ifindex to not bypass the routing tables */
592 cmsg_data = CMSG_DATA(cmsg);
593 ((struct in_pktinfo *) cmsg_data)->ipi_ifindex = 0;
594 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
595 /* zero the padding bytes inserted by the CMSG_LEN */
596 if(sizeof(struct in_pktinfo) < cmsg->cmsg_len)
597 memset(((uint8_t*)(CMSG_DATA(cmsg))) +
598 sizeof(struct in_pktinfo), 0, cmsg->cmsg_len
599 - sizeof(struct in_pktinfo));
600 #elif defined(IP_SENDSRCADDR)
601 msg.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
602 log_assert(msg.msg_controllen <= sizeof(control.buf));
603 cmsg->cmsg_level = IPPROTO_IP;
604 cmsg->cmsg_type = IP_SENDSRCADDR;
605 memmove(CMSG_DATA(cmsg), &r->pktinfo.v4addr,
606 sizeof(struct in_addr));
607 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
608 /* zero the padding bytes inserted by the CMSG_LEN */
609 if(sizeof(struct in_addr) < cmsg->cmsg_len)
610 memset(((uint8_t*)(CMSG_DATA(cmsg))) +
611 sizeof(struct in_addr), 0, cmsg->cmsg_len
612 - sizeof(struct in_addr));
614 verbose(VERB_ALGO, "no IP_PKTINFO or IP_SENDSRCADDR");
615 msg.msg_control = NULL;
616 #endif /* IP_PKTINFO or IP_SENDSRCADDR */
617 } else if(r->srctype == 6) {
619 msg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
620 log_assert(msg.msg_controllen <= sizeof(control.buf));
621 cmsg->cmsg_level = IPPROTO_IPV6;
622 cmsg->cmsg_type = IPV6_PKTINFO;
623 memmove(CMSG_DATA(cmsg), &r->pktinfo.v6info,
624 sizeof(struct in6_pktinfo));
625 /* unset the ifindex to not bypass the routing tables */
626 cmsg_data = CMSG_DATA(cmsg);
627 ((struct in6_pktinfo *) cmsg_data)->ipi6_ifindex = 0;
628 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
629 /* zero the padding bytes inserted by the CMSG_LEN */
630 if(sizeof(struct in6_pktinfo) < cmsg->cmsg_len)
631 memset(((uint8_t*)(CMSG_DATA(cmsg))) +
632 sizeof(struct in6_pktinfo), 0, cmsg->cmsg_len
633 - sizeof(struct in6_pktinfo));
635 /* try to pass all 0 to use default route */
636 msg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
637 log_assert(msg.msg_controllen <= sizeof(control.buf));
638 cmsg->cmsg_level = IPPROTO_IPV6;
639 cmsg->cmsg_type = IPV6_PKTINFO;
640 memset(CMSG_DATA(cmsg), 0, sizeof(struct in6_pktinfo));
641 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
642 /* zero the padding bytes inserted by the CMSG_LEN */
643 if(sizeof(struct in6_pktinfo) < cmsg->cmsg_len)
644 memset(((uint8_t*)(CMSG_DATA(cmsg))) +
645 sizeof(struct in6_pktinfo), 0, cmsg->cmsg_len
646 - sizeof(struct in6_pktinfo));
648 #endif /* S_SPLINT_S */
649 if(verbosity >= VERB_ALGO && r->srctype != 0)
650 p_ancil("send_udp over interface", r);
651 sent = sendmsg(c->fd, &msg, 0);
653 /* try again and block, waiting for IO to complete,
654 * we want to send the answer, and we will wait for
655 * the ethernet interface buffer to have space. */
657 if(errno == EAGAIN || errno == EINTR ||
659 errno == EWOULDBLOCK ||
663 if(WSAGetLastError() == WSAEINPROGRESS ||
664 WSAGetLastError() == WSAEINTR ||
665 WSAGetLastError() == WSAENOBUFS ||
666 WSAGetLastError() == WSAEWOULDBLOCK) {
668 while(sent == -1 && (
670 errno == EAGAIN || errno == EINTR ||
672 errno == EWOULDBLOCK ||
676 WSAGetLastError() == WSAEINPROGRESS ||
677 WSAGetLastError() == WSAEINTR ||
678 WSAGetLastError() == WSAENOBUFS ||
679 WSAGetLastError() == WSAEWOULDBLOCK
682 #if defined(HAVE_POLL) || defined(USE_WINSOCK)
685 memset(&p, 0, sizeof(p));
687 p.events = POLLOUT | POLLERR | POLLHUP;
689 pret = poll(&p, 1, SEND_BLOCKED_WAIT_TIMEOUT);
691 pret = WSAPoll(&p, 1,
692 SEND_BLOCKED_WAIT_TIMEOUT);
696 struct comm_base* b = c->ev->base;
697 if(b->eb->last_writewait_log+SLOW_LOG_TIME <=
699 b->eb->last_writewait_log = b->eb->secs;
700 verbose(VERB_OPS, "send udp blocked "
701 "for long, dropping packet.");
704 } else if(pret < 0 &&
706 errno != EAGAIN && errno != EINTR &&
708 errno != EWOULDBLOCK &&
712 WSAGetLastError() != WSAEINPROGRESS &&
713 WSAGetLastError() != WSAEINTR &&
714 WSAGetLastError() != WSAENOBUFS &&
715 WSAGetLastError() != WSAEWOULDBLOCK
718 log_err("poll udp out failed: %s",
719 sock_strerror(errno));
722 #endif /* defined(HAVE_POLL) || defined(USE_WINSOCK) */
723 sent = sendmsg(c->fd, &msg, 0);
728 if(!udp_send_errno_needs_log(addr, addrlen))
730 verbose(VERB_OPS, "sendmsg failed: %s", strerror(errno));
731 log_addr(VERB_OPS, "remote address is",
732 (struct sockaddr_storage*)addr, addrlen);
734 /* netbsd 7 has IP_PKTINFO for recv but not send */
735 if(errno == EINVAL && r->srctype == 4)
736 log_err("sendmsg: No support for sendmsg(IP_PKTINFO). "
737 "Please disable interface-automatic");
740 } else if((size_t)sent != sldns_buffer_remaining(packet)) {
741 log_err("sent %d in place of %d bytes",
742 (int)sent, (int)sldns_buffer_remaining(packet));
752 log_err("sendmsg: IPV6_PKTINFO not supported");
754 #endif /* AF_INET6 && IPV6_PKTINFO && HAVE_SENDMSG */
757 /** return true is UDP receive error needs to be logged */
758 static int udp_recv_needs_log(int err)
761 case EACCES: /* some hosts send ICMP 'Permission Denied' */
776 #else /* USE_WINSOCK */
777 case WSAECONNREFUSED:
780 case WSAEHOSTUNREACH:
783 if(verbosity >= VERB_ALGO)
792 /** Parses the PROXYv2 header from buf and updates the comm_reply struct.
793 * Returns 1 on success, 0 on failure. */
794 static int consume_pp2_header(struct sldns_buffer* buf, struct comm_reply* rep,
797 struct pp2_header *header = pp2_read_header(buf);
798 if(header == NULL) return 0;
799 size = PP2_HEADER_SIZE + ntohs(header->len);
800 if((header->ver_cmd & 0xF) == PP2_CMD_LOCAL) {
801 /* A connection from the proxy itself.
802 * No need to do anything with addresses. */
805 if(header->fam_prot == 0x00) {
806 /* Unspecified family and protocol. This could be used for
807 * health checks by proxies.
808 * No need to do anything with addresses. */
811 /* Read the proxied address */
812 switch(header->fam_prot) {
813 case 0x11: /* AF_INET|STREAM */
814 case 0x12: /* AF_INET|DGRAM */
816 struct sockaddr_in* addr =
817 (struct sockaddr_in*)&rep->client_addr;
818 addr->sin_family = AF_INET;
819 addr->sin_addr.s_addr = header->addr.addr4.src_addr;
820 addr->sin_port = header->addr.addr4.src_port;
821 rep->client_addrlen = (socklen_t)sizeof(struct sockaddr_in);
823 /* Ignore the destination address; it should be us. */
825 case 0x21: /* AF_INET6|STREAM */
826 case 0x22: /* AF_INET6|DGRAM */
828 struct sockaddr_in6* addr =
829 (struct sockaddr_in6*)&rep->client_addr;
830 memset(addr, 0, sizeof(*addr));
831 addr->sin6_family = AF_INET6;
832 memcpy(&addr->sin6_addr,
833 header->addr.addr6.src_addr, 16);
834 addr->sin6_port = header->addr.addr6.src_port;
835 rep->client_addrlen = (socklen_t)sizeof(struct sockaddr_in6);
837 /* Ignore the destination address; it should be us. */
843 /* We are reading a whole packet;
844 * Move the rest of the data to overwrite the PROXYv2 header */
845 /* XXX can we do better to avoid memmove? */
846 memmove(header, ((char*)header)+size,
847 sldns_buffer_limit(buf)-size);
848 sldns_buffer_set_limit(buf, sldns_buffer_limit(buf)-size);
854 comm_point_udp_ancil_callback(int fd, short event, void* arg)
856 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && defined(HAVE_RECVMSG)
857 struct comm_reply rep;
867 struct cmsghdr* cmsg;
868 #endif /* S_SPLINT_S */
869 #ifdef HAVE_LINUX_NET_TSTAMP_H
871 #endif /* HAVE_LINUX_NET_TSTAMP_H */
873 rep.c = (struct comm_point*)arg;
874 log_assert(rep.c->type == comm_udp);
876 if(!(event&UB_EV_READ))
878 log_assert(rep.c && rep.c->buffer && rep.c->fd == fd);
879 ub_comm_base_now(rep.c->ev->base);
880 for(i=0; i<NUM_UDP_PER_SELECT; i++) {
881 sldns_buffer_clear(rep.c->buffer);
882 timeval_clear(&rep.c->recv_tv);
883 rep.remote_addrlen = (socklen_t)sizeof(rep.remote_addr);
884 log_assert(fd != -1);
885 log_assert(sldns_buffer_remaining(rep.c->buffer) > 0);
886 msg.msg_name = &rep.remote_addr;
887 msg.msg_namelen = (socklen_t)sizeof(rep.remote_addr);
888 iov[0].iov_base = sldns_buffer_begin(rep.c->buffer);
889 iov[0].iov_len = sldns_buffer_remaining(rep.c->buffer);
892 msg.msg_control = ancil.buf;
894 msg.msg_controllen = sizeof(ancil.buf);
895 #endif /* S_SPLINT_S */
897 rcv = recvmsg(fd, &msg, MSG_DONTWAIT);
899 if(errno != EAGAIN && errno != EINTR
900 && udp_recv_needs_log(errno)) {
901 log_err("recvmsg failed: %s", strerror(errno));
905 rep.remote_addrlen = msg.msg_namelen;
906 sldns_buffer_skip(rep.c->buffer, rcv);
907 sldns_buffer_flip(rep.c->buffer);
911 for(cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
912 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
913 if( cmsg->cmsg_level == IPPROTO_IPV6 &&
914 cmsg->cmsg_type == IPV6_PKTINFO) {
916 memmove(&rep.pktinfo.v6info, CMSG_DATA(cmsg),
917 sizeof(struct in6_pktinfo));
920 } else if( cmsg->cmsg_level == IPPROTO_IP &&
921 cmsg->cmsg_type == IP_PKTINFO) {
923 memmove(&rep.pktinfo.v4info, CMSG_DATA(cmsg),
924 sizeof(struct in_pktinfo));
926 #elif defined(IP_RECVDSTADDR)
927 } else if( cmsg->cmsg_level == IPPROTO_IP &&
928 cmsg->cmsg_type == IP_RECVDSTADDR) {
930 memmove(&rep.pktinfo.v4addr, CMSG_DATA(cmsg),
931 sizeof(struct in_addr));
933 #endif /* IP_PKTINFO or IP_RECVDSTADDR */
934 #ifdef HAVE_LINUX_NET_TSTAMP_H
935 } else if( cmsg->cmsg_level == SOL_SOCKET &&
936 cmsg->cmsg_type == SO_TIMESTAMPNS) {
937 ts = (struct timespec *)CMSG_DATA(cmsg);
938 TIMESPEC_TO_TIMEVAL(&rep.c->recv_tv, ts);
939 } else if( cmsg->cmsg_level == SOL_SOCKET &&
940 cmsg->cmsg_type == SO_TIMESTAMPING) {
941 ts = (struct timespec *)CMSG_DATA(cmsg);
942 TIMESPEC_TO_TIMEVAL(&rep.c->recv_tv, ts);
943 } else if( cmsg->cmsg_level == SOL_SOCKET &&
944 cmsg->cmsg_type == SO_TIMESTAMP) {
945 memmove(&rep.c->recv_tv, CMSG_DATA(cmsg), sizeof(struct timeval));
946 #endif /* HAVE_LINUX_NET_TSTAMP_H */
950 if(verbosity >= VERB_ALGO && rep.srctype != 0)
951 p_ancil("receive_udp on interface", &rep);
952 #endif /* S_SPLINT_S */
954 if(rep.c->pp2_enabled && !consume_pp2_header(rep.c->buffer,
956 log_err("proxy_protocol: could not consume PROXYv2 header");
959 if(!rep.is_proxied) {
960 rep.client_addrlen = rep.remote_addrlen;
961 memmove(&rep.client_addr, &rep.remote_addr,
965 fptr_ok(fptr_whitelist_comm_point(rep.c->callback));
966 if((*rep.c->callback)(rep.c, rep.c->cb_arg, NETEVENT_NOERROR, &rep)) {
967 /* send back immediate reply */
968 (void)comm_point_send_udp_msg_if(rep.c, rep.c->buffer,
969 (struct sockaddr*)&rep.remote_addr,
970 rep.remote_addrlen, &rep);
972 if(!rep.c || rep.c->fd == -1) /* commpoint closed */
979 fatal_exit("recvmsg: No support for IPV6_PKTINFO; IP_PKTINFO or IP_RECVDSTADDR. "
980 "Please disable interface-automatic");
981 #endif /* AF_INET6 && IPV6_PKTINFO && HAVE_RECVMSG */
985 comm_point_udp_callback(int fd, short event, void* arg)
987 struct comm_reply rep;
990 struct sldns_buffer *buffer;
992 rep.c = (struct comm_point*)arg;
993 log_assert(rep.c->type == comm_udp);
995 if(!(event&UB_EV_READ))
997 log_assert(rep.c && rep.c->buffer && rep.c->fd == fd);
998 ub_comm_base_now(rep.c->ev->base);
999 for(i=0; i<NUM_UDP_PER_SELECT; i++) {
1000 sldns_buffer_clear(rep.c->buffer);
1001 rep.remote_addrlen = (socklen_t)sizeof(rep.remote_addr);
1002 log_assert(fd != -1);
1003 log_assert(sldns_buffer_remaining(rep.c->buffer) > 0);
1004 rcv = recvfrom(fd, (void*)sldns_buffer_begin(rep.c->buffer),
1005 sldns_buffer_remaining(rep.c->buffer), MSG_DONTWAIT,
1006 (struct sockaddr*)&rep.remote_addr, &rep.remote_addrlen);
1009 if(errno != EAGAIN && errno != EINTR
1010 && udp_recv_needs_log(errno))
1011 log_err("recvfrom %d failed: %s",
1012 fd, strerror(errno));
1014 if(WSAGetLastError() != WSAEINPROGRESS &&
1015 WSAGetLastError() != WSAECONNRESET &&
1016 WSAGetLastError()!= WSAEWOULDBLOCK &&
1017 udp_recv_needs_log(WSAGetLastError()))
1018 log_err("recvfrom failed: %s",
1019 wsa_strerror(WSAGetLastError()));
1023 sldns_buffer_skip(rep.c->buffer, rcv);
1024 sldns_buffer_flip(rep.c->buffer);
1028 if(rep.c->pp2_enabled && !consume_pp2_header(rep.c->buffer,
1030 log_err("proxy_protocol: could not consume PROXYv2 header");
1033 if(!rep.is_proxied) {
1034 rep.client_addrlen = rep.remote_addrlen;
1035 memmove(&rep.client_addr, &rep.remote_addr,
1036 rep.remote_addrlen);
1039 fptr_ok(fptr_whitelist_comm_point(rep.c->callback));
1040 if((*rep.c->callback)(rep.c, rep.c->cb_arg, NETEVENT_NOERROR, &rep)) {
1041 /* send back immediate reply */
1043 buffer = rep.c->dnscrypt_buffer;
1045 buffer = rep.c->buffer;
1047 (void)comm_point_send_udp_msg(rep.c, buffer,
1048 (struct sockaddr*)&rep.remote_addr,
1049 rep.remote_addrlen, 0);
1051 if(!rep.c || rep.c->fd != fd) /* commpoint closed to -1 or reused for
1052 another UDP port. Note rep.c cannot be reused with TCP fd. */
1057 int adjusted_tcp_timeout(struct comm_point* c)
1059 if(c->tcp_timeout_msec < TCP_QUERY_TIMEOUT_MINIMUM)
1060 return TCP_QUERY_TIMEOUT_MINIMUM;
1061 return c->tcp_timeout_msec;
1064 /** Use a new tcp handler for new query fd, set to read query */
1066 setup_tcp_handler(struct comm_point* c, int fd, int cur, int max)
1069 log_assert(c->type == comm_tcp || c->type == comm_http);
1070 log_assert(c->fd == -1);
1071 sldns_buffer_clear(c->buffer);
1074 sldns_buffer_clear(c->dnscrypt_buffer);
1076 c->tcp_is_reading = 1;
1077 c->tcp_byte_count = 0;
1078 c->tcp_keepalive = 0;
1079 /* if more than half the tcp handlers are in use, use a shorter
1080 * timeout for this TCP connection, we need to make space for
1081 * other connections to be able to get attention */
1082 /* If > 50% TCP handler structures in use, set timeout to 1/100th
1084 * If > 65%TCP handler structures in use, set to 1/500th configured
1086 * If > 80% TCP handler structures in use, set to 0.
1088 * If the timeout to use falls below 200 milliseconds, an actual
1089 * timeout of 200ms is used.
1091 handler_usage = (cur * 100) / max;
1092 if(handler_usage > 50 && handler_usage <= 65)
1093 c->tcp_timeout_msec /= 100;
1094 else if (handler_usage > 65 && handler_usage <= 80)
1095 c->tcp_timeout_msec /= 500;
1096 else if (handler_usage > 80)
1097 c->tcp_timeout_msec = 0;
1098 comm_point_start_listening(c, fd, adjusted_tcp_timeout(c));
1101 void comm_base_handle_slow_accept(int ATTR_UNUSED(fd),
1102 short ATTR_UNUSED(event), void* arg)
1104 struct comm_base* b = (struct comm_base*)arg;
1105 /* timeout for the slow accept, re-enable accepts again */
1106 if(b->start_accept) {
1107 verbose(VERB_ALGO, "wait is over, slow accept disabled");
1108 fptr_ok(fptr_whitelist_start_accept(b->start_accept));
1109 (*b->start_accept)(b->cb_arg);
1110 b->eb->slow_accept_enabled = 0;
1114 int comm_point_perform_accept(struct comm_point* c,
1115 struct sockaddr_storage* addr, socklen_t* addrlen)
1118 *addrlen = (socklen_t)sizeof(*addr);
1119 #ifndef HAVE_ACCEPT4
1120 new_fd = accept(c->fd, (struct sockaddr*)addr, addrlen);
1122 /* SOCK_NONBLOCK saves extra calls to fcntl for the same result */
1123 new_fd = accept4(c->fd, (struct sockaddr*)addr, addrlen, SOCK_NONBLOCK);
1127 /* EINTR is signal interrupt. others are closed connection. */
1128 if( errno == EINTR || errno == EAGAIN
1130 || errno == EWOULDBLOCK
1133 || errno == ECONNABORTED
1140 #if defined(ENFILE) && defined(EMFILE)
1141 if(errno == ENFILE || errno == EMFILE) {
1142 /* out of file descriptors, likely outside of our
1143 * control. stop accept() calls for some time */
1144 if(c->ev->base->stop_accept) {
1145 struct comm_base* b = c->ev->base;
1147 verbose(VERB_ALGO, "out of file descriptors: "
1149 ub_comm_base_now(b);
1150 if(b->eb->last_slow_log+SLOW_LOG_TIME <=
1152 b->eb->last_slow_log = b->eb->secs;
1153 verbose(VERB_OPS, "accept failed, "
1154 "slow down accept for %d "
1156 NETEVENT_SLOW_ACCEPT_TIME,
1157 sock_strerror(errno));
1159 b->eb->slow_accept_enabled = 1;
1160 fptr_ok(fptr_whitelist_stop_accept(
1162 (*b->stop_accept)(b->cb_arg);
1163 /* set timeout, no mallocs */
1164 tv.tv_sec = NETEVENT_SLOW_ACCEPT_TIME/1000;
1165 tv.tv_usec = (NETEVENT_SLOW_ACCEPT_TIME%1000)*1000;
1166 b->eb->slow_accept = ub_event_new(b->eb->base,
1168 comm_base_handle_slow_accept, b);
1169 if(b->eb->slow_accept == NULL) {
1170 /* we do not want to log here, because
1171 * that would spam the logfiles.
1172 * error: "event_base_set failed." */
1174 else if(ub_event_add(b->eb->slow_accept, &tv)
1176 /* we do not want to log here,
1177 * error: "event_add failed." */
1180 log_err("accept, with no slow down, "
1181 "failed: %s", sock_strerror(errno));
1186 #else /* USE_WINSOCK */
1187 if(WSAGetLastError() == WSAEINPROGRESS ||
1188 WSAGetLastError() == WSAECONNRESET)
1190 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1191 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1195 log_err_addr("accept failed", sock_strerror(errno), addr,
1199 if(c->tcp_conn_limit && c->type == comm_tcp_accept) {
1200 c->tcl_addr = tcl_addr_lookup(c->tcp_conn_limit, addr, *addrlen);
1201 if(!tcl_new_connection(c->tcl_addr)) {
1203 log_err_addr("accept rejected",
1204 "connection limit exceeded", addr, *addrlen);
1209 #ifndef HAVE_ACCEPT4
1210 fd_set_nonblock(new_fd);
1216 static long win_bio_cb(BIO *b, int oper, const char* ATTR_UNUSED(argp),
1217 #ifdef HAVE_BIO_SET_CALLBACK_EX
1218 size_t ATTR_UNUSED(len),
1220 int ATTR_UNUSED(argi), long argl,
1221 #ifndef HAVE_BIO_SET_CALLBACK_EX
1224 int retvalue, size_t* ATTR_UNUSED(processed)
1228 int wsa_err = WSAGetLastError(); /* store errcode before it is gone */
1229 verbose(VERB_ALGO, "bio_cb %d, %s %s %s", oper,
1230 (oper&BIO_CB_RETURN)?"return":"before",
1231 (oper&BIO_CB_READ)?"read":((oper&BIO_CB_WRITE)?"write":"other"),
1232 wsa_err==WSAEWOULDBLOCK?"wsawb":"");
1233 /* on windows, check if previous operation caused EWOULDBLOCK */
1234 if( (oper == (BIO_CB_READ|BIO_CB_RETURN) && argl == 0) ||
1235 (oper == (BIO_CB_GETS|BIO_CB_RETURN) && argl == 0)) {
1236 if(wsa_err == WSAEWOULDBLOCK)
1237 ub_winsock_tcp_wouldblock((struct ub_event*)
1238 BIO_get_callback_arg(b), UB_EV_READ);
1240 if( (oper == (BIO_CB_WRITE|BIO_CB_RETURN) && argl == 0) ||
1241 (oper == (BIO_CB_PUTS|BIO_CB_RETURN) && argl == 0)) {
1242 if(wsa_err == WSAEWOULDBLOCK)
1243 ub_winsock_tcp_wouldblock((struct ub_event*)
1244 BIO_get_callback_arg(b), UB_EV_WRITE);
1246 /* return original return value */
1250 /** set win bio callbacks for nonblocking operations */
1252 comm_point_tcp_win_bio_cb(struct comm_point* c, void* thessl)
1254 SSL* ssl = (SSL*)thessl;
1255 /* set them both just in case, but usually they are the same BIO */
1256 #ifdef HAVE_BIO_SET_CALLBACK_EX
1257 BIO_set_callback_ex(SSL_get_rbio(ssl), &win_bio_cb);
1259 BIO_set_callback(SSL_get_rbio(ssl), &win_bio_cb);
1261 BIO_set_callback_arg(SSL_get_rbio(ssl), (char*)c->ev->ev);
1262 #ifdef HAVE_BIO_SET_CALLBACK_EX
1263 BIO_set_callback_ex(SSL_get_wbio(ssl), &win_bio_cb);
1265 BIO_set_callback(SSL_get_wbio(ssl), &win_bio_cb);
1267 BIO_set_callback_arg(SSL_get_wbio(ssl), (char*)c->ev->ev);
1272 /** Create http2 session server. Per connection, after TCP accepted.*/
1273 static int http2_session_server_create(struct http2_session* h2_session)
1275 log_assert(h2_session->callbacks);
1276 h2_session->is_drop = 0;
1277 if(nghttp2_session_server_new(&h2_session->session,
1278 h2_session->callbacks,
1279 h2_session) == NGHTTP2_ERR_NOMEM) {
1280 log_err("failed to create nghttp2 session server");
1287 /** Submit http2 setting to session. Once per session. */
1288 static int http2_submit_settings(struct http2_session* h2_session)
1291 nghttp2_settings_entry settings[1] = {
1292 {NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS,
1293 h2_session->c->http2_max_streams}};
1295 ret = nghttp2_submit_settings(h2_session->session, NGHTTP2_FLAG_NONE,
1298 verbose(VERB_QUERY, "http2: submit_settings failed, "
1299 "error: %s", nghttp2_strerror(ret));
1304 #endif /* HAVE_NGHTTP2 */
1308 comm_point_tcp_accept_callback(int fd, short event, void* arg)
1310 struct comm_point* c = (struct comm_point*)arg, *c_hdl;
1312 log_assert(c->type == comm_tcp_accept);
1313 if(!(event & UB_EV_READ)) {
1314 log_info("ignoring tcp accept event %d", (int)event);
1317 ub_comm_base_now(c->ev->base);
1318 /* find free tcp handler. */
1320 log_warn("accepted too many tcp, connections full");
1323 /* accept incoming connection. */
1324 c_hdl = c->tcp_free;
1325 /* clear leftover flags from previous use, and then set the
1326 * correct event base for the event structure for libevent */
1327 ub_event_free(c_hdl->ev->ev);
1328 c_hdl->ev->ev = NULL;
1329 if((c_hdl->type == comm_tcp && c_hdl->tcp_req_info) ||
1330 c_hdl->type == comm_local || c_hdl->type == comm_raw)
1331 c_hdl->tcp_do_toggle_rw = 0;
1332 else c_hdl->tcp_do_toggle_rw = 1;
1334 if(c_hdl->type == comm_http) {
1336 if(!c_hdl->h2_session ||
1337 !http2_session_server_create(c_hdl->h2_session)) {
1338 log_warn("failed to create nghttp2");
1341 if(!c_hdl->h2_session ||
1342 !http2_submit_settings(c_hdl->h2_session)) {
1343 log_warn("failed to submit http2 settings");
1347 c_hdl->tcp_do_toggle_rw = 0;
1351 c_hdl->ev->ev = ub_event_new(c_hdl->ev->base->eb->base, -1,
1352 UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT,
1353 comm_point_http_handle_callback, c_hdl);
1355 c_hdl->ev->ev = ub_event_new(c_hdl->ev->base->eb->base, -1,
1356 UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT,
1357 comm_point_tcp_handle_callback, c_hdl);
1359 if(!c_hdl->ev->ev) {
1360 log_warn("could not ub_event_new, dropped tcp");
1363 log_assert(fd != -1);
1365 new_fd = comm_point_perform_accept(c, &c_hdl->repinfo.remote_addr,
1366 &c_hdl->repinfo.remote_addrlen);
1369 /* Copy remote_address to client_address.
1370 * Simplest way/time for streams to do that. */
1371 c_hdl->repinfo.client_addrlen = c_hdl->repinfo.remote_addrlen;
1372 memmove(&c_hdl->repinfo.client_addr,
1373 &c_hdl->repinfo.remote_addr,
1374 c_hdl->repinfo.remote_addrlen);
1376 c_hdl->ssl = incoming_ssl_fd(c->ssl, new_fd);
1379 comm_point_close(c_hdl);
1382 c_hdl->ssl_shake_state = comm_ssl_shake_read;
1384 comm_point_tcp_win_bio_cb(c_hdl, c_hdl->ssl);
1388 /* grab the tcp handler buffers */
1390 c->tcp_free = c_hdl->tcp_free;
1391 c_hdl->tcp_free = NULL;
1393 /* stop accepting incoming queries for now. */
1394 comm_point_stop_listening(c);
1396 setup_tcp_handler(c_hdl, new_fd, c->cur_tcp_count, c->max_tcp_count);
1399 /** Make tcp handler free for next assignment */
1401 reclaim_tcp_handler(struct comm_point* c)
1403 log_assert(c->type == comm_tcp);
1406 SSL_shutdown(c->ssl);
1411 comm_point_close(c);
1413 if(c != c->tcp_parent->tcp_free) {
1414 c->tcp_parent->cur_tcp_count--;
1415 c->tcp_free = c->tcp_parent->tcp_free;
1416 c->tcp_parent->tcp_free = c;
1419 /* re-enable listening on accept socket */
1420 comm_point_start_listening(c->tcp_parent, -1, -1);
1423 c->tcp_more_read_again = NULL;
1424 c->tcp_more_write_again = NULL;
1425 c->tcp_byte_count = 0;
1426 c->pp2_header_state = pp2_header_none;
1427 sldns_buffer_clear(c->buffer);
1430 /** do the callback when writing is done */
1432 tcp_callback_writer(struct comm_point* c)
1434 log_assert(c->type == comm_tcp);
1435 if(!c->tcp_write_and_read) {
1436 sldns_buffer_clear(c->buffer);
1437 c->tcp_byte_count = 0;
1439 if(c->tcp_do_toggle_rw)
1440 c->tcp_is_reading = 1;
1441 /* switch from listening(write) to listening(read) */
1442 if(c->tcp_req_info) {
1443 tcp_req_info_handle_writedone(c->tcp_req_info);
1445 comm_point_stop_listening(c);
1446 if(c->tcp_write_and_read) {
1447 fptr_ok(fptr_whitelist_comm_point(c->callback));
1448 if( (*c->callback)(c, c->cb_arg, NETEVENT_PKT_WRITTEN,
1450 comm_point_start_listening(c, -1,
1451 adjusted_tcp_timeout(c));
1454 comm_point_start_listening(c, -1,
1455 adjusted_tcp_timeout(c));
1460 /** do the callback when reading is done */
1462 tcp_callback_reader(struct comm_point* c)
1464 log_assert(c->type == comm_tcp || c->type == comm_local);
1465 sldns_buffer_flip(c->buffer);
1466 if(c->tcp_do_toggle_rw)
1467 c->tcp_is_reading = 0;
1468 c->tcp_byte_count = 0;
1469 if(c->tcp_req_info) {
1470 tcp_req_info_handle_readdone(c->tcp_req_info);
1472 if(c->type == comm_tcp)
1473 comm_point_stop_listening(c);
1474 fptr_ok(fptr_whitelist_comm_point(c->callback));
1475 if( (*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, &c->repinfo) ) {
1476 comm_point_start_listening(c, -1,
1477 adjusted_tcp_timeout(c));
1483 /** true if the ssl handshake error has to be squelched from the logs */
1485 squelch_err_ssl_handshake(unsigned long err)
1487 if(verbosity >= VERB_QUERY)
1488 return 0; /* only squelch on low verbosity */
1489 if(ERR_GET_LIB(err) == ERR_LIB_SSL &&
1490 (ERR_GET_REASON(err) == SSL_R_HTTPS_PROXY_REQUEST ||
1491 ERR_GET_REASON(err) == SSL_R_HTTP_REQUEST ||
1492 ERR_GET_REASON(err) == SSL_R_WRONG_VERSION_NUMBER ||
1493 ERR_GET_REASON(err) == SSL_R_SSLV3_ALERT_BAD_CERTIFICATE
1494 #ifdef SSL_F_TLS_POST_PROCESS_CLIENT_HELLO
1495 || ERR_GET_REASON(err) == SSL_R_NO_SHARED_CIPHER
1497 #ifdef SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO
1498 || ERR_GET_REASON(err) == SSL_R_UNKNOWN_PROTOCOL
1499 || ERR_GET_REASON(err) == SSL_R_UNSUPPORTED_PROTOCOL
1500 # ifdef SSL_R_VERSION_TOO_LOW
1501 || ERR_GET_REASON(err) == SSL_R_VERSION_TOO_LOW
1508 #endif /* HAVE_SSL */
1510 /** continue ssl handshake */
1513 ssl_handshake(struct comm_point* c)
1516 if(c->ssl_shake_state == comm_ssl_shake_hs_read) {
1517 /* read condition satisfied back to writing */
1518 comm_point_listen_for_rw(c, 0, 1);
1519 c->ssl_shake_state = comm_ssl_shake_none;
1522 if(c->ssl_shake_state == comm_ssl_shake_hs_write) {
1523 /* write condition satisfied, back to reading */
1524 comm_point_listen_for_rw(c, 1, 0);
1525 c->ssl_shake_state = comm_ssl_shake_none;
1530 r = SSL_do_handshake(c->ssl);
1532 int want = SSL_get_error(c->ssl, r);
1533 if(want == SSL_ERROR_WANT_READ) {
1534 if(c->ssl_shake_state == comm_ssl_shake_read)
1536 c->ssl_shake_state = comm_ssl_shake_read;
1537 comm_point_listen_for_rw(c, 1, 0);
1539 } else if(want == SSL_ERROR_WANT_WRITE) {
1540 if(c->ssl_shake_state == comm_ssl_shake_write)
1542 c->ssl_shake_state = comm_ssl_shake_write;
1543 comm_point_listen_for_rw(c, 0, 1);
1546 return 0; /* closed */
1547 } else if(want == SSL_ERROR_SYSCALL) {
1548 /* SYSCALL and errno==0 means closed uncleanly */
1550 if(errno == EPIPE && verbosity < 2)
1551 return 0; /* silence 'broken pipe' */
1554 if(errno == ECONNRESET && verbosity < 2)
1555 return 0; /* silence reset by peer */
1557 if(!tcp_connect_errno_needs_log(
1558 (struct sockaddr*)&c->repinfo.remote_addr,
1559 c->repinfo.remote_addrlen))
1560 return 0; /* silence connect failures that
1561 show up because after connect this is the
1562 first system call that accesses the socket */
1564 log_err("SSL_handshake syscall: %s",
1568 unsigned long err = ERR_get_error();
1569 if(!squelch_err_ssl_handshake(err)) {
1570 log_crypto_err_code("ssl handshake failed", err);
1571 log_addr(VERB_OPS, "ssl handshake failed",
1572 &c->repinfo.remote_addr,
1573 c->repinfo.remote_addrlen);
1578 /* this is where peer verification could take place */
1579 if((SSL_get_verify_mode(c->ssl)&SSL_VERIFY_PEER)) {
1581 if(SSL_get_verify_result(c->ssl) == X509_V_OK) {
1582 #ifdef HAVE_SSL_GET1_PEER_CERTIFICATE
1583 X509* x = SSL_get1_peer_certificate(c->ssl);
1585 X509* x = SSL_get_peer_certificate(c->ssl);
1588 log_addr(VERB_ALGO, "SSL connection failed: "
1590 &c->repinfo.remote_addr,
1591 c->repinfo.remote_addrlen);
1594 log_cert(VERB_ALGO, "peer certificate", x);
1595 #ifdef HAVE_SSL_GET0_PEERNAME
1596 if(SSL_get0_peername(c->ssl)) {
1598 snprintf(buf, sizeof(buf), "SSL connection "
1599 "to %s authenticated",
1600 SSL_get0_peername(c->ssl));
1601 log_addr(VERB_ALGO, buf, &c->repinfo.remote_addr,
1602 c->repinfo.remote_addrlen);
1605 log_addr(VERB_ALGO, "SSL connection "
1606 "authenticated", &c->repinfo.remote_addr,
1607 c->repinfo.remote_addrlen);
1608 #ifdef HAVE_SSL_GET0_PEERNAME
1613 #ifdef HAVE_SSL_GET1_PEER_CERTIFICATE
1614 X509* x = SSL_get1_peer_certificate(c->ssl);
1616 X509* x = SSL_get_peer_certificate(c->ssl);
1619 log_cert(VERB_ALGO, "peer certificate", x);
1622 log_addr(VERB_ALGO, "SSL connection failed: "
1623 "failed to authenticate",
1624 &c->repinfo.remote_addr,
1625 c->repinfo.remote_addrlen);
1629 /* unauthenticated, the verify peer flag was not set
1630 * in c->ssl when the ssl object was created from ssl_ctx */
1631 log_addr(VERB_ALGO, "SSL connection", &c->repinfo.remote_addr,
1632 c->repinfo.remote_addrlen);
1635 #ifdef HAVE_SSL_GET0_ALPN_SELECTED
1636 /* check if http2 use is negotiated */
1637 if(c->type == comm_http && c->h2_session) {
1638 const unsigned char *alpn;
1639 unsigned int alpnlen = 0;
1640 SSL_get0_alpn_selected(c->ssl, &alpn, &alpnlen);
1641 if(alpnlen == 2 && memcmp("h2", alpn, 2) == 0) {
1642 /* connection upgraded to HTTP2 */
1643 c->tcp_do_toggle_rw = 0;
1649 /* setup listen rw correctly */
1650 if(c->tcp_is_reading) {
1651 if(c->ssl_shake_state != comm_ssl_shake_read)
1652 comm_point_listen_for_rw(c, 1, 0);
1654 comm_point_listen_for_rw(c, 0, 1);
1656 c->ssl_shake_state = comm_ssl_shake_none;
1659 #endif /* HAVE_SSL */
1661 /** ssl read callback on TCP */
1663 ssl_handle_read(struct comm_point* c)
1667 if(c->ssl_shake_state != comm_ssl_shake_none) {
1668 if(!ssl_handshake(c))
1670 if(c->ssl_shake_state != comm_ssl_shake_none)
1673 if(c->pp2_enabled && c->pp2_header_state != pp2_header_done) {
1674 struct pp2_header* header = NULL;
1675 size_t want_read_size = 0;
1676 size_t current_read_size = 0;
1677 if(c->pp2_header_state == pp2_header_none) {
1678 want_read_size = PP2_HEADER_SIZE;
1679 if(sldns_buffer_remaining(c->buffer)<want_read_size) {
1680 log_err_addr("proxy_protocol: not enough "
1681 "buffer size to read PROXYv2 header", "",
1682 &c->repinfo.remote_addr,
1683 c->repinfo.remote_addrlen);
1686 verbose(VERB_ALGO, "proxy_protocol: reading fixed "
1687 "part of PROXYv2 header (len %lu)",
1688 (unsigned long)want_read_size);
1689 current_read_size = want_read_size;
1690 if(c->tcp_byte_count < current_read_size) {
1692 if((r=SSL_read(c->ssl, (void*)sldns_buffer_at(
1693 c->buffer, c->tcp_byte_count),
1695 c->tcp_byte_count)) <= 0) {
1696 int want = SSL_get_error(c->ssl, r);
1697 if(want == SSL_ERROR_ZERO_RETURN) {
1699 return tcp_req_info_handle_read_close(c->tcp_req_info);
1700 return 0; /* shutdown, closed */
1701 } else if(want == SSL_ERROR_WANT_READ) {
1703 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1705 return 1; /* read more later */
1706 } else if(want == SSL_ERROR_WANT_WRITE) {
1707 c->ssl_shake_state = comm_ssl_shake_hs_write;
1708 comm_point_listen_for_rw(c, 0, 1);
1710 } else if(want == SSL_ERROR_SYSCALL) {
1712 if(errno == ECONNRESET && verbosity < 2)
1713 return 0; /* silence reset by peer */
1716 log_err("SSL_read syscall: %s",
1720 log_crypto_err("could not SSL_read");
1723 c->tcp_byte_count += r;
1724 if(c->tcp_byte_count != current_read_size) return 1;
1725 c->pp2_header_state = pp2_header_init;
1728 if(c->pp2_header_state == pp2_header_init) {
1729 header = pp2_read_header(c->buffer);
1731 log_err("proxy_protocol: could not parse "
1735 want_read_size = ntohs(header->len);
1736 if(sldns_buffer_remaining(c->buffer) <
1737 PP2_HEADER_SIZE + want_read_size) {
1738 log_err_addr("proxy_protocol: not enough "
1739 "buffer size to read PROXYv2 header", "",
1740 &c->repinfo.remote_addr,
1741 c->repinfo.remote_addrlen);
1744 verbose(VERB_ALGO, "proxy_protocol: reading variable "
1745 "part of PROXYv2 header (len %lu)",
1746 (unsigned long)want_read_size);
1747 current_read_size = PP2_HEADER_SIZE + want_read_size;
1748 if(want_read_size == 0) {
1749 /* nothing more to read; header is complete */
1750 c->pp2_header_state = pp2_header_done;
1751 } else if(c->tcp_byte_count < current_read_size) {
1753 if((r=SSL_read(c->ssl, (void*)sldns_buffer_at(
1754 c->buffer, c->tcp_byte_count),
1756 c->tcp_byte_count)) <= 0) {
1757 int want = SSL_get_error(c->ssl, r);
1758 if(want == SSL_ERROR_ZERO_RETURN) {
1760 return tcp_req_info_handle_read_close(c->tcp_req_info);
1761 return 0; /* shutdown, closed */
1762 } else if(want == SSL_ERROR_WANT_READ) {
1764 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1766 return 1; /* read more later */
1767 } else if(want == SSL_ERROR_WANT_WRITE) {
1768 c->ssl_shake_state = comm_ssl_shake_hs_write;
1769 comm_point_listen_for_rw(c, 0, 1);
1771 } else if(want == SSL_ERROR_SYSCALL) {
1773 if(errno == ECONNRESET && verbosity < 2)
1774 return 0; /* silence reset by peer */
1777 log_err("SSL_read syscall: %s",
1781 log_crypto_err("could not SSL_read");
1784 c->tcp_byte_count += r;
1785 if(c->tcp_byte_count != current_read_size) return 1;
1786 c->pp2_header_state = pp2_header_done;
1789 if(c->pp2_header_state != pp2_header_done || !header) {
1790 log_err_addr("proxy_protocol: wrong state for the "
1791 "PROXYv2 header", "", &c->repinfo.remote_addr,
1792 c->repinfo.remote_addrlen);
1795 if(!consume_pp2_header(c->buffer, &c->repinfo, 1)) {
1796 log_err_addr("proxy_protocol: could not consume "
1797 "PROXYv2 header", "", &c->repinfo.remote_addr,
1798 c->repinfo.remote_addrlen);
1801 verbose(VERB_ALGO, "proxy_protocol: successful read of "
1803 /* Clear and reset the buffer to read the following
1805 sldns_buffer_clear(c->buffer);
1806 c->tcp_byte_count = 0;
1809 if(c->tcp_byte_count < sizeof(uint16_t)) {
1810 /* read length bytes */
1812 if((r=SSL_read(c->ssl, (void*)sldns_buffer_at(c->buffer,
1813 c->tcp_byte_count), (int)(sizeof(uint16_t) -
1814 c->tcp_byte_count))) <= 0) {
1815 int want = SSL_get_error(c->ssl, r);
1816 if(want == SSL_ERROR_ZERO_RETURN) {
1818 return tcp_req_info_handle_read_close(c->tcp_req_info);
1819 return 0; /* shutdown, closed */
1820 } else if(want == SSL_ERROR_WANT_READ) {
1822 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1824 return 1; /* read more later */
1825 } else if(want == SSL_ERROR_WANT_WRITE) {
1826 c->ssl_shake_state = comm_ssl_shake_hs_write;
1827 comm_point_listen_for_rw(c, 0, 1);
1829 } else if(want == SSL_ERROR_SYSCALL) {
1831 if(errno == ECONNRESET && verbosity < 2)
1832 return 0; /* silence reset by peer */
1835 log_err("SSL_read syscall: %s",
1839 log_crypto_err("could not SSL_read");
1842 c->tcp_byte_count += r;
1843 if(c->tcp_byte_count < sizeof(uint16_t))
1845 if(sldns_buffer_read_u16_at(c->buffer, 0) >
1846 sldns_buffer_capacity(c->buffer)) {
1847 verbose(VERB_QUERY, "ssl: dropped larger than buffer");
1850 sldns_buffer_set_limit(c->buffer,
1851 sldns_buffer_read_u16_at(c->buffer, 0));
1852 if(sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
1853 verbose(VERB_QUERY, "ssl: dropped bogus too short.");
1856 sldns_buffer_skip(c->buffer, (ssize_t)(c->tcp_byte_count-sizeof(uint16_t)));
1857 verbose(VERB_ALGO, "Reading ssl tcp query of length %d",
1858 (int)sldns_buffer_limit(c->buffer));
1860 if(sldns_buffer_remaining(c->buffer) > 0) {
1862 r = SSL_read(c->ssl, (void*)sldns_buffer_current(c->buffer),
1863 (int)sldns_buffer_remaining(c->buffer));
1865 int want = SSL_get_error(c->ssl, r);
1866 if(want == SSL_ERROR_ZERO_RETURN) {
1868 return tcp_req_info_handle_read_close(c->tcp_req_info);
1869 return 0; /* shutdown, closed */
1870 } else if(want == SSL_ERROR_WANT_READ) {
1872 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1874 return 1; /* read more later */
1875 } else if(want == SSL_ERROR_WANT_WRITE) {
1876 c->ssl_shake_state = comm_ssl_shake_hs_write;
1877 comm_point_listen_for_rw(c, 0, 1);
1879 } else if(want == SSL_ERROR_SYSCALL) {
1881 if(errno == ECONNRESET && verbosity < 2)
1882 return 0; /* silence reset by peer */
1885 log_err("SSL_read syscall: %s",
1889 log_crypto_err("could not SSL_read");
1892 sldns_buffer_skip(c->buffer, (ssize_t)r);
1894 if(sldns_buffer_remaining(c->buffer) <= 0) {
1895 tcp_callback_reader(c);
1901 #endif /* HAVE_SSL */
1904 /** ssl write callback on TCP */
1906 ssl_handle_write(struct comm_point* c)
1910 if(c->ssl_shake_state != comm_ssl_shake_none) {
1911 if(!ssl_handshake(c))
1913 if(c->ssl_shake_state != comm_ssl_shake_none)
1916 /* ignore return, if fails we may simply block */
1917 (void)SSL_set_mode(c->ssl, (long)SSL_MODE_ENABLE_PARTIAL_WRITE);
1918 if((c->tcp_write_and_read?c->tcp_write_byte_count:c->tcp_byte_count) < sizeof(uint16_t)) {
1919 uint16_t len = htons(c->tcp_write_and_read?c->tcp_write_pkt_len:sldns_buffer_limit(c->buffer));
1921 if(c->tcp_write_and_read) {
1922 if(c->tcp_write_pkt_len + 2 < LDNS_RR_BUF_SIZE) {
1923 /* combine the tcp length and the query for
1924 * write, this emulates writev */
1925 uint8_t buf[LDNS_RR_BUF_SIZE];
1926 memmove(buf, &len, sizeof(uint16_t));
1927 memmove(buf+sizeof(uint16_t),
1929 c->tcp_write_pkt_len);
1930 r = SSL_write(c->ssl,
1931 (void*)(buf+c->tcp_write_byte_count),
1932 c->tcp_write_pkt_len + 2 -
1933 c->tcp_write_byte_count);
1935 r = SSL_write(c->ssl,
1936 (void*)(((uint8_t*)&len)+c->tcp_write_byte_count),
1937 (int)(sizeof(uint16_t)-c->tcp_write_byte_count));
1939 } else if(sizeof(uint16_t)+sldns_buffer_remaining(c->buffer) <
1941 /* combine the tcp length and the query for write,
1942 * this emulates writev */
1943 uint8_t buf[LDNS_RR_BUF_SIZE];
1944 memmove(buf, &len, sizeof(uint16_t));
1945 memmove(buf+sizeof(uint16_t),
1946 sldns_buffer_current(c->buffer),
1947 sldns_buffer_remaining(c->buffer));
1948 r = SSL_write(c->ssl, (void*)(buf+c->tcp_byte_count),
1949 (int)(sizeof(uint16_t)+
1950 sldns_buffer_remaining(c->buffer)
1951 - c->tcp_byte_count));
1953 r = SSL_write(c->ssl,
1954 (void*)(((uint8_t*)&len)+c->tcp_byte_count),
1955 (int)(sizeof(uint16_t)-c->tcp_byte_count));
1958 int want = SSL_get_error(c->ssl, r);
1959 if(want == SSL_ERROR_ZERO_RETURN) {
1960 return 0; /* closed */
1961 } else if(want == SSL_ERROR_WANT_READ) {
1962 c->ssl_shake_state = comm_ssl_shake_hs_read;
1963 comm_point_listen_for_rw(c, 1, 0);
1964 return 1; /* wait for read condition */
1965 } else if(want == SSL_ERROR_WANT_WRITE) {
1967 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
1969 return 1; /* write more later */
1970 } else if(want == SSL_ERROR_SYSCALL) {
1972 if(errno == EPIPE && verbosity < 2)
1973 return 0; /* silence 'broken pipe' */
1976 log_err("SSL_write syscall: %s",
1980 log_crypto_err("could not SSL_write");
1983 if(c->tcp_write_and_read) {
1984 c->tcp_write_byte_count += r;
1985 if(c->tcp_write_byte_count < sizeof(uint16_t))
1988 c->tcp_byte_count += r;
1989 if(c->tcp_byte_count < sizeof(uint16_t))
1991 sldns_buffer_set_position(c->buffer, c->tcp_byte_count -
1994 if((!c->tcp_write_and_read && sldns_buffer_remaining(c->buffer) == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == c->tcp_write_pkt_len + 2)) {
1995 tcp_callback_writer(c);
1999 log_assert(c->tcp_write_and_read || sldns_buffer_remaining(c->buffer) > 0);
2000 log_assert(!c->tcp_write_and_read || c->tcp_write_byte_count < c->tcp_write_pkt_len + 2);
2002 if(c->tcp_write_and_read) {
2003 r = SSL_write(c->ssl, (void*)(c->tcp_write_pkt + c->tcp_write_byte_count - 2),
2004 (int)(c->tcp_write_pkt_len + 2 - c->tcp_write_byte_count));
2006 r = SSL_write(c->ssl, (void*)sldns_buffer_current(c->buffer),
2007 (int)sldns_buffer_remaining(c->buffer));
2010 int want = SSL_get_error(c->ssl, r);
2011 if(want == SSL_ERROR_ZERO_RETURN) {
2012 return 0; /* closed */
2013 } else if(want == SSL_ERROR_WANT_READ) {
2014 c->ssl_shake_state = comm_ssl_shake_hs_read;
2015 comm_point_listen_for_rw(c, 1, 0);
2016 return 1; /* wait for read condition */
2017 } else if(want == SSL_ERROR_WANT_WRITE) {
2019 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
2021 return 1; /* write more later */
2022 } else if(want == SSL_ERROR_SYSCALL) {
2024 if(errno == EPIPE && verbosity < 2)
2025 return 0; /* silence 'broken pipe' */
2028 log_err("SSL_write syscall: %s",
2032 log_crypto_err("could not SSL_write");
2035 if(c->tcp_write_and_read) {
2036 c->tcp_write_byte_count += r;
2038 sldns_buffer_skip(c->buffer, (ssize_t)r);
2041 if((!c->tcp_write_and_read && sldns_buffer_remaining(c->buffer) == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == c->tcp_write_pkt_len + 2)) {
2042 tcp_callback_writer(c);
2048 #endif /* HAVE_SSL */
2051 /** handle ssl tcp connection with dns contents */
2053 ssl_handle_it(struct comm_point* c, int is_write)
2055 /* handle case where renegotiation wants read during write call
2056 * or write during read calls */
2057 if(is_write && c->ssl_shake_state == comm_ssl_shake_hs_write)
2058 return ssl_handle_read(c);
2059 else if(!is_write && c->ssl_shake_state == comm_ssl_shake_hs_read)
2060 return ssl_handle_write(c);
2061 /* handle read events for read operation and write events for a
2062 * write operation */
2064 return ssl_handle_read(c);
2065 return ssl_handle_write(c);
2069 * Handle tcp reading callback.
2070 * @param fd: file descriptor of socket.
2071 * @param c: comm point to read from into buffer.
2072 * @param short_ok: if true, very short packets are OK (for comm_local).
2073 * @return: 0 on error
2076 comm_point_tcp_handle_read(int fd, struct comm_point* c, int short_ok)
2079 int recv_initial = 0;
2080 log_assert(c->type == comm_tcp || c->type == comm_local);
2082 return ssl_handle_it(c, 0);
2083 if(!c->tcp_is_reading && !c->tcp_write_and_read)
2086 log_assert(fd != -1);
2087 if(c->pp2_enabled && c->pp2_header_state != pp2_header_done) {
2088 struct pp2_header* header = NULL;
2089 size_t want_read_size = 0;
2090 size_t current_read_size = 0;
2091 if(c->pp2_header_state == pp2_header_none) {
2092 want_read_size = PP2_HEADER_SIZE;
2093 if(sldns_buffer_remaining(c->buffer)<want_read_size) {
2094 log_err_addr("proxy_protocol: not enough "
2095 "buffer size to read PROXYv2 header", "",
2096 &c->repinfo.remote_addr,
2097 c->repinfo.remote_addrlen);
2100 verbose(VERB_ALGO, "proxy_protocol: reading fixed "
2101 "part of PROXYv2 header (len %lu)",
2102 (unsigned long)want_read_size);
2103 current_read_size = want_read_size;
2104 if(c->tcp_byte_count < current_read_size) {
2105 r = recv(fd, (void*)sldns_buffer_at(c->buffer,
2107 current_read_size-c->tcp_byte_count, MSG_DONTWAIT);
2110 return tcp_req_info_handle_read_close(c->tcp_req_info);
2112 } else if(r == -1) {
2113 goto recv_error_initial;
2115 c->tcp_byte_count += r;
2116 if(c->tcp_byte_count != current_read_size) return 1;
2117 c->pp2_header_state = pp2_header_init;
2120 if(c->pp2_header_state == pp2_header_init) {
2121 header = pp2_read_header(c->buffer);
2123 log_err("proxy_protocol: could not parse "
2127 want_read_size = ntohs(header->len);
2128 if(sldns_buffer_remaining(c->buffer) <
2129 PP2_HEADER_SIZE + want_read_size) {
2130 log_err_addr("proxy_protocol: not enough "
2131 "buffer size to read PROXYv2 header", "",
2132 &c->repinfo.remote_addr,
2133 c->repinfo.remote_addrlen);
2136 verbose(VERB_ALGO, "proxy_protocol: reading variable "
2137 "part of PROXYv2 header (len %lu)",
2138 (unsigned long)want_read_size);
2139 current_read_size = PP2_HEADER_SIZE + want_read_size;
2140 if(want_read_size == 0) {
2141 /* nothing more to read; header is complete */
2142 c->pp2_header_state = pp2_header_done;
2143 } else if(c->tcp_byte_count < current_read_size) {
2144 r = recv(fd, (void*)sldns_buffer_at(c->buffer,
2146 current_read_size-c->tcp_byte_count, MSG_DONTWAIT);
2149 return tcp_req_info_handle_read_close(c->tcp_req_info);
2151 } else if(r == -1) {
2154 c->tcp_byte_count += r;
2155 if(c->tcp_byte_count != current_read_size) return 1;
2156 c->pp2_header_state = pp2_header_done;
2159 if(c->pp2_header_state != pp2_header_done || !header) {
2160 log_err_addr("proxy_protocol: wrong state for the "
2161 "PROXYv2 header", "", &c->repinfo.remote_addr,
2162 c->repinfo.remote_addrlen);
2165 if(!consume_pp2_header(c->buffer, &c->repinfo, 1)) {
2166 log_err_addr("proxy_protocol: could not consume "
2167 "PROXYv2 header", "", &c->repinfo.remote_addr,
2168 c->repinfo.remote_addrlen);
2171 verbose(VERB_ALGO, "proxy_protocol: successful read of "
2173 /* Clear and reset the buffer to read the following
2175 sldns_buffer_clear(c->buffer);
2176 c->tcp_byte_count = 0;
2180 if(c->tcp_byte_count < sizeof(uint16_t)) {
2181 /* read length bytes */
2182 r = recv(fd,(void*)sldns_buffer_at(c->buffer,c->tcp_byte_count),
2183 sizeof(uint16_t)-c->tcp_byte_count, MSG_DONTWAIT);
2186 return tcp_req_info_handle_read_close(c->tcp_req_info);
2188 } else if(r == -1) {
2189 if(c->pp2_enabled) goto recv_error;
2190 goto recv_error_initial;
2192 c->tcp_byte_count += r;
2193 if(c->tcp_byte_count != sizeof(uint16_t))
2195 if(sldns_buffer_read_u16_at(c->buffer, 0) >
2196 sldns_buffer_capacity(c->buffer)) {
2197 verbose(VERB_QUERY, "tcp: dropped larger than buffer");
2200 sldns_buffer_set_limit(c->buffer,
2201 sldns_buffer_read_u16_at(c->buffer, 0));
2203 sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
2204 verbose(VERB_QUERY, "tcp: dropped bogus too short.");
2207 verbose(VERB_ALGO, "Reading tcp query of length %d",
2208 (int)sldns_buffer_limit(c->buffer));
2211 if(sldns_buffer_remaining(c->buffer) == 0)
2212 log_err("in comm_point_tcp_handle_read buffer_remaining is "
2213 "not > 0 as expected, continuing with (harmless) 0 "
2215 r = recv(fd, (void*)sldns_buffer_current(c->buffer),
2216 sldns_buffer_remaining(c->buffer), MSG_DONTWAIT);
2219 return tcp_req_info_handle_read_close(c->tcp_req_info);
2221 } else if(r == -1) {
2224 sldns_buffer_skip(c->buffer, r);
2225 if(sldns_buffer_remaining(c->buffer) <= 0) {
2226 tcp_callback_reader(c);
2234 if(errno == EINTR || errno == EAGAIN)
2238 if(errno == ECONNRESET && verbosity < 2)
2239 return 0; /* silence reset by peer */
2242 if(errno == ECONNREFUSED && verbosity < 2)
2243 return 0; /* silence reset by peer */
2246 if(errno == ENETUNREACH && verbosity < 2)
2247 return 0; /* silence it */
2250 if(errno == EHOSTDOWN && verbosity < 2)
2251 return 0; /* silence it */
2254 if(errno == EHOSTUNREACH && verbosity < 2)
2255 return 0; /* silence it */
2258 if(errno == ENETDOWN && verbosity < 2)
2259 return 0; /* silence it */
2262 if(errno == EACCES && verbosity < 2)
2263 return 0; /* silence it */
2266 if(errno == ENOTCONN) {
2267 log_err_addr("read (in tcp s) failed and this "
2268 "could be because TCP Fast Open is "
2269 "enabled [--disable-tfo-client "
2270 "--disable-tfo-server] but does not "
2271 "work", sock_strerror(errno),
2272 &c->repinfo.remote_addr,
2273 c->repinfo.remote_addrlen);
2278 #else /* USE_WINSOCK */
2280 if(WSAGetLastError() == WSAECONNREFUSED && verbosity < 2)
2282 if(WSAGetLastError() == WSAEHOSTDOWN && verbosity < 2)
2284 if(WSAGetLastError() == WSAEHOSTUNREACH && verbosity < 2)
2286 if(WSAGetLastError() == WSAENETDOWN && verbosity < 2)
2288 if(WSAGetLastError() == WSAENETUNREACH && verbosity < 2)
2291 if(WSAGetLastError() == WSAECONNRESET)
2293 if(WSAGetLastError() == WSAEINPROGRESS)
2295 if(WSAGetLastError() == WSAEWOULDBLOCK) {
2296 ub_winsock_tcp_wouldblock(c->ev->ev,
2301 log_err_addr("read (in tcp s)", sock_strerror(errno),
2302 &c->repinfo.remote_addr, c->repinfo.remote_addrlen);
2307 * Handle tcp writing callback.
2308 * @param fd: file descriptor of socket.
2309 * @param c: comm point to write buffer out of.
2310 * @return: 0 on error
2313 comm_point_tcp_handle_write(int fd, struct comm_point* c)
2316 struct sldns_buffer *buffer;
2317 log_assert(c->type == comm_tcp);
2319 buffer = c->dnscrypt_buffer;
2323 if(c->tcp_is_reading && !c->ssl && !c->tcp_write_and_read)
2325 log_assert(fd != -1);
2326 if(((!c->tcp_write_and_read && c->tcp_byte_count == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == 0)) && c->tcp_check_nb_connect) {
2327 /* check for pending error from nonblocking connect */
2328 /* from Stevens, unix network programming, vol1, 3rd ed, p450*/
2330 socklen_t len = (socklen_t)sizeof(error);
2331 if(getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&error,
2334 error = errno; /* on solaris errno is error */
2335 #else /* USE_WINSOCK */
2336 error = WSAGetLastError();
2340 #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
2341 if(error == EINPROGRESS || error == EWOULDBLOCK)
2342 return 1; /* try again later */
2345 if(error != 0 && verbosity < 2)
2346 return 0; /* silence lots of chatter in the logs */
2347 else if(error != 0) {
2348 log_err_addr("tcp connect", strerror(error),
2349 &c->repinfo.remote_addr,
2350 c->repinfo.remote_addrlen);
2351 #else /* USE_WINSOCK */
2353 if(error == WSAEINPROGRESS)
2355 else if(error == WSAEWOULDBLOCK) {
2356 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
2358 } else if(error != 0 && verbosity < 2)
2360 else if(error != 0) {
2361 log_err_addr("tcp connect", wsa_strerror(error),
2362 &c->repinfo.remote_addr,
2363 c->repinfo.remote_addrlen);
2364 #endif /* USE_WINSOCK */
2369 return ssl_handle_it(c, 1);
2371 #ifdef USE_MSG_FASTOPEN
2372 /* Only try this on first use of a connection that uses tfo,
2373 otherwise fall through to normal write */
2374 /* Also, TFO support on WINDOWS not implemented at the moment */
2375 if(c->tcp_do_fastopen == 1) {
2376 /* this form of sendmsg() does both a connect() and send() so need to
2377 look for various flavours of error*/
2378 uint16_t len = htons(c->tcp_write_and_read?c->tcp_write_pkt_len:sldns_buffer_limit(buffer));
2380 struct iovec iov[2];
2381 c->tcp_do_fastopen = 0;
2382 memset(&msg, 0, sizeof(msg));
2383 if(c->tcp_write_and_read) {
2384 iov[0].iov_base = (uint8_t*)&len + c->tcp_write_byte_count;
2385 iov[0].iov_len = sizeof(uint16_t) - c->tcp_write_byte_count;
2386 iov[1].iov_base = c->tcp_write_pkt;
2387 iov[1].iov_len = c->tcp_write_pkt_len;
2389 iov[0].iov_base = (uint8_t*)&len + c->tcp_byte_count;
2390 iov[0].iov_len = sizeof(uint16_t) - c->tcp_byte_count;
2391 iov[1].iov_base = sldns_buffer_begin(buffer);
2392 iov[1].iov_len = sldns_buffer_limit(buffer);
2394 log_assert(iov[0].iov_len > 0);
2395 msg.msg_name = &c->repinfo.remote_addr;
2396 msg.msg_namelen = c->repinfo.remote_addrlen;
2399 r = sendmsg(fd, &msg, MSG_FASTOPEN);
2401 #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
2402 /* Handshake is underway, maybe because no TFO cookie available.
2403 Come back to write the message*/
2404 if(errno == EINPROGRESS || errno == EWOULDBLOCK)
2407 if(errno == EINTR || errno == EAGAIN)
2409 /* Not handling EISCONN here as shouldn't ever hit that case.*/
2412 /* if /proc/sys/net/ipv4/tcp_fastopen is
2413 * disabled on Linux, sendmsg may return
2414 * 'Operation not supported', if so
2415 * fallthrough to ordinary connect. */
2416 && errno != EOPNOTSUPP
2420 return 0; /* silence lots of chatter in the logs */
2421 log_err_addr("tcp sendmsg", strerror(errno),
2422 &c->repinfo.remote_addr,
2423 c->repinfo.remote_addrlen);
2426 verbose(VERB_ALGO, "tcp sendmsg for fastopen failed (with %s), try normal connect", strerror(errno));
2427 /* fallthrough to nonFASTOPEN
2428 * (MSG_FASTOPEN on Linux 3 produces EPIPE)
2429 * we need to perform connect() */
2430 if(connect(fd, (struct sockaddr *)&c->repinfo.remote_addr,
2431 c->repinfo.remote_addrlen) == -1) {
2433 if(errno == EINPROGRESS)
2434 return 1; /* wait until connect done*/
2437 if(WSAGetLastError() == WSAEINPROGRESS ||
2438 WSAGetLastError() == WSAEWOULDBLOCK)
2439 return 1; /* wait until connect done*/
2441 if(tcp_connect_errno_needs_log(
2442 (struct sockaddr *)&c->repinfo.remote_addr,
2443 c->repinfo.remote_addrlen)) {
2444 log_err_addr("outgoing tcp: connect after EPIPE for fastopen",
2446 &c->repinfo.remote_addr,
2447 c->repinfo.remote_addrlen);
2453 if(c->tcp_write_and_read) {
2454 c->tcp_write_byte_count += r;
2455 if(c->tcp_write_byte_count < sizeof(uint16_t))
2458 c->tcp_byte_count += r;
2459 if(c->tcp_byte_count < sizeof(uint16_t))
2461 sldns_buffer_set_position(buffer, c->tcp_byte_count -
2464 if((!c->tcp_write_and_read && sldns_buffer_remaining(buffer) == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == c->tcp_write_pkt_len + 2)) {
2465 tcp_callback_writer(c);
2470 #endif /* USE_MSG_FASTOPEN */
2472 if((c->tcp_write_and_read?c->tcp_write_byte_count:c->tcp_byte_count) < sizeof(uint16_t)) {
2473 uint16_t len = htons(c->tcp_write_and_read?c->tcp_write_pkt_len:sldns_buffer_limit(buffer));
2475 struct iovec iov[2];
2476 if(c->tcp_write_and_read) {
2477 iov[0].iov_base = (uint8_t*)&len + c->tcp_write_byte_count;
2478 iov[0].iov_len = sizeof(uint16_t) - c->tcp_write_byte_count;
2479 iov[1].iov_base = c->tcp_write_pkt;
2480 iov[1].iov_len = c->tcp_write_pkt_len;
2482 iov[0].iov_base = (uint8_t*)&len + c->tcp_byte_count;
2483 iov[0].iov_len = sizeof(uint16_t) - c->tcp_byte_count;
2484 iov[1].iov_base = sldns_buffer_begin(buffer);
2485 iov[1].iov_len = sldns_buffer_limit(buffer);
2487 log_assert(iov[0].iov_len > 0);
2488 r = writev(fd, iov, 2);
2489 #else /* HAVE_WRITEV */
2490 if(c->tcp_write_and_read) {
2491 r = send(fd, (void*)(((uint8_t*)&len)+c->tcp_write_byte_count),
2492 sizeof(uint16_t)-c->tcp_write_byte_count, 0);
2494 r = send(fd, (void*)(((uint8_t*)&len)+c->tcp_byte_count),
2495 sizeof(uint16_t)-c->tcp_byte_count, 0);
2497 #endif /* HAVE_WRITEV */
2501 if(errno == EPIPE && verbosity < 2)
2502 return 0; /* silence 'broken pipe' */
2504 if(errno == EINTR || errno == EAGAIN)
2507 if(errno == ECONNRESET && verbosity < 2)
2508 return 0; /* silence reset by peer */
2511 log_err_addr("tcp writev", strerror(errno),
2512 &c->repinfo.remote_addr,
2513 c->repinfo.remote_addrlen);
2514 # else /* HAVE_WRITEV */
2515 log_err_addr("tcp send s", strerror(errno),
2516 &c->repinfo.remote_addr,
2517 c->repinfo.remote_addrlen);
2518 # endif /* HAVE_WRITEV */
2520 if(WSAGetLastError() == WSAENOTCONN)
2522 if(WSAGetLastError() == WSAEINPROGRESS)
2524 if(WSAGetLastError() == WSAEWOULDBLOCK) {
2525 ub_winsock_tcp_wouldblock(c->ev->ev,
2529 if(WSAGetLastError() == WSAECONNRESET && verbosity < 2)
2530 return 0; /* silence reset by peer */
2531 log_err_addr("tcp send s",
2532 wsa_strerror(WSAGetLastError()),
2533 &c->repinfo.remote_addr,
2534 c->repinfo.remote_addrlen);
2538 if(c->tcp_write_and_read) {
2539 c->tcp_write_byte_count += r;
2540 if(c->tcp_write_byte_count < sizeof(uint16_t))
2543 c->tcp_byte_count += r;
2544 if(c->tcp_byte_count < sizeof(uint16_t))
2546 sldns_buffer_set_position(buffer, c->tcp_byte_count -
2549 if((!c->tcp_write_and_read && sldns_buffer_remaining(buffer) == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == c->tcp_write_pkt_len + 2)) {
2550 tcp_callback_writer(c);
2554 log_assert(c->tcp_write_and_read || sldns_buffer_remaining(buffer) > 0);
2555 log_assert(!c->tcp_write_and_read || c->tcp_write_byte_count < c->tcp_write_pkt_len + 2);
2556 if(c->tcp_write_and_read) {
2557 r = send(fd, (void*)(c->tcp_write_pkt + c->tcp_write_byte_count - 2),
2558 c->tcp_write_pkt_len + 2 - c->tcp_write_byte_count, 0);
2560 r = send(fd, (void*)sldns_buffer_current(buffer),
2561 sldns_buffer_remaining(buffer), 0);
2565 if(errno == EINTR || errno == EAGAIN)
2568 if(errno == ECONNRESET && verbosity < 2)
2569 return 0; /* silence reset by peer */
2572 if(WSAGetLastError() == WSAEINPROGRESS)
2574 if(WSAGetLastError() == WSAEWOULDBLOCK) {
2575 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
2578 if(WSAGetLastError() == WSAECONNRESET && verbosity < 2)
2579 return 0; /* silence reset by peer */
2581 log_err_addr("tcp send r", sock_strerror(errno),
2582 &c->repinfo.remote_addr,
2583 c->repinfo.remote_addrlen);
2586 if(c->tcp_write_and_read) {
2587 c->tcp_write_byte_count += r;
2589 sldns_buffer_skip(buffer, r);
2592 if((!c->tcp_write_and_read && sldns_buffer_remaining(buffer) == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == c->tcp_write_pkt_len + 2)) {
2593 tcp_callback_writer(c);
2599 /** read again to drain buffers when there could be more to read, returns 0
2600 * on failure which means the comm point is closed. */
2602 tcp_req_info_read_again(int fd, struct comm_point* c)
2604 while(c->tcp_req_info->read_again) {
2606 c->tcp_req_info->read_again = 0;
2607 if(c->tcp_is_reading)
2608 r = comm_point_tcp_handle_read(fd, c, 0);
2609 else r = comm_point_tcp_handle_write(fd, c);
2611 reclaim_tcp_handler(c);
2612 if(!c->tcp_do_close) {
2613 fptr_ok(fptr_whitelist_comm_point(
2615 (void)(*c->callback)(c, c->cb_arg,
2616 NETEVENT_CLOSED, NULL);
2624 /** read again to drain buffers when there could be more to read */
2626 tcp_more_read_again(int fd, struct comm_point* c)
2628 /* if the packet is done, but another one could be waiting on
2629 * the connection, the callback signals this, and we try again */
2630 /* this continues until the read routines get EAGAIN or so,
2631 * and thus does not call the callback, and the bool is 0 */
2632 int* moreread = c->tcp_more_read_again;
2633 while(moreread && *moreread) {
2635 if(!comm_point_tcp_handle_read(fd, c, 0)) {
2636 reclaim_tcp_handler(c);
2637 if(!c->tcp_do_close) {
2638 fptr_ok(fptr_whitelist_comm_point(
2640 (void)(*c->callback)(c, c->cb_arg,
2641 NETEVENT_CLOSED, NULL);
2648 /** write again to fill up when there could be more to write */
2650 tcp_more_write_again(int fd, struct comm_point* c)
2652 /* if the packet is done, but another is waiting to be written,
2653 * the callback signals it and we try again. */
2654 /* this continues until the write routines get EAGAIN or so,
2655 * and thus does not call the callback, and the bool is 0 */
2656 int* morewrite = c->tcp_more_write_again;
2657 while(morewrite && *morewrite) {
2659 if(!comm_point_tcp_handle_write(fd, c)) {
2660 reclaim_tcp_handler(c);
2661 if(!c->tcp_do_close) {
2662 fptr_ok(fptr_whitelist_comm_point(
2664 (void)(*c->callback)(c, c->cb_arg,
2665 NETEVENT_CLOSED, NULL);
2673 comm_point_tcp_handle_callback(int fd, short event, void* arg)
2675 struct comm_point* c = (struct comm_point*)arg;
2676 log_assert(c->type == comm_tcp);
2677 ub_comm_base_now(c->ev->base);
2679 if(c->fd == -1 || c->fd != fd)
2680 return; /* duplicate event, but commpoint closed. */
2683 /* Initialize if this is a dnscrypt socket */
2685 c->dnscrypt = c->tcp_parent->dnscrypt;
2687 if(c->dnscrypt && c->dnscrypt_buffer == c->buffer) {
2688 c->dnscrypt_buffer = sldns_buffer_new(sldns_buffer_capacity(c->buffer));
2689 if(!c->dnscrypt_buffer) {
2690 log_err("Could not allocate dnscrypt buffer");
2691 reclaim_tcp_handler(c);
2692 if(!c->tcp_do_close) {
2693 fptr_ok(fptr_whitelist_comm_point(
2695 (void)(*c->callback)(c, c->cb_arg,
2696 NETEVENT_CLOSED, NULL);
2703 if(event&UB_EV_TIMEOUT) {
2704 verbose(VERB_QUERY, "tcp took too long, dropped");
2705 reclaim_tcp_handler(c);
2706 if(!c->tcp_do_close) {
2707 fptr_ok(fptr_whitelist_comm_point(c->callback));
2708 (void)(*c->callback)(c, c->cb_arg,
2709 NETEVENT_TIMEOUT, NULL);
2714 #ifdef USE_MSG_FASTOPEN
2715 && !(c->tcp_do_fastopen && (event&UB_EV_WRITE))
2718 int has_tcpq = (c->tcp_req_info != NULL);
2719 int* moreread = c->tcp_more_read_again;
2720 if(!comm_point_tcp_handle_read(fd, c, 0)) {
2721 reclaim_tcp_handler(c);
2722 if(!c->tcp_do_close) {
2723 fptr_ok(fptr_whitelist_comm_point(
2725 (void)(*c->callback)(c, c->cb_arg,
2726 NETEVENT_CLOSED, NULL);
2730 if(has_tcpq && c->tcp_req_info && c->tcp_req_info->read_again) {
2731 if(!tcp_req_info_read_again(fd, c))
2734 if(moreread && *moreread)
2735 tcp_more_read_again(fd, c);
2738 if(event&UB_EV_WRITE) {
2739 int has_tcpq = (c->tcp_req_info != NULL);
2740 int* morewrite = c->tcp_more_write_again;
2741 if(!comm_point_tcp_handle_write(fd, c)) {
2742 reclaim_tcp_handler(c);
2743 if(!c->tcp_do_close) {
2744 fptr_ok(fptr_whitelist_comm_point(
2746 (void)(*c->callback)(c, c->cb_arg,
2747 NETEVENT_CLOSED, NULL);
2751 if(has_tcpq && c->tcp_req_info && c->tcp_req_info->read_again) {
2752 if(!tcp_req_info_read_again(fd, c))
2755 if(morewrite && *morewrite)
2756 tcp_more_write_again(fd, c);
2759 log_err("Ignored event %d for tcphdl.", event);
2762 /** Make http handler free for next assignment */
2764 reclaim_http_handler(struct comm_point* c)
2766 log_assert(c->type == comm_http);
2769 SSL_shutdown(c->ssl);
2774 comm_point_close(c);
2776 if(c != c->tcp_parent->tcp_free) {
2777 c->tcp_parent->cur_tcp_count--;
2778 c->tcp_free = c->tcp_parent->tcp_free;
2779 c->tcp_parent->tcp_free = c;
2782 /* re-enable listening on accept socket */
2783 comm_point_start_listening(c->tcp_parent, -1, -1);
2788 /** read more data for http (with ssl) */
2790 ssl_http_read_more(struct comm_point* c)
2794 log_assert(sldns_buffer_remaining(c->buffer) > 0);
2796 r = SSL_read(c->ssl, (void*)sldns_buffer_current(c->buffer),
2797 (int)sldns_buffer_remaining(c->buffer));
2799 int want = SSL_get_error(c->ssl, r);
2800 if(want == SSL_ERROR_ZERO_RETURN) {
2801 return 0; /* shutdown, closed */
2802 } else if(want == SSL_ERROR_WANT_READ) {
2803 return 1; /* read more later */
2804 } else if(want == SSL_ERROR_WANT_WRITE) {
2805 c->ssl_shake_state = comm_ssl_shake_hs_write;
2806 comm_point_listen_for_rw(c, 0, 1);
2808 } else if(want == SSL_ERROR_SYSCALL) {
2810 if(errno == ECONNRESET && verbosity < 2)
2811 return 0; /* silence reset by peer */
2814 log_err("SSL_read syscall: %s",
2818 log_crypto_err("could not SSL_read");
2821 verbose(VERB_ALGO, "ssl http read more skip to %d + %d",
2822 (int)sldns_buffer_position(c->buffer), (int)r);
2823 sldns_buffer_skip(c->buffer, (ssize_t)r);
2828 #endif /* HAVE_SSL */
2831 /** read more data for http */
2833 http_read_more(int fd, struct comm_point* c)
2836 log_assert(sldns_buffer_remaining(c->buffer) > 0);
2837 r = recv(fd, (void*)sldns_buffer_current(c->buffer),
2838 sldns_buffer_remaining(c->buffer), MSG_DONTWAIT);
2841 } else if(r == -1) {
2843 if(errno == EINTR || errno == EAGAIN)
2845 #else /* USE_WINSOCK */
2846 if(WSAGetLastError() == WSAECONNRESET)
2848 if(WSAGetLastError() == WSAEINPROGRESS)
2850 if(WSAGetLastError() == WSAEWOULDBLOCK) {
2851 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
2855 log_err_addr("read (in http r)", sock_strerror(errno),
2856 &c->repinfo.remote_addr, c->repinfo.remote_addrlen);
2859 verbose(VERB_ALGO, "http read more skip to %d + %d",
2860 (int)sldns_buffer_position(c->buffer), (int)r);
2861 sldns_buffer_skip(c->buffer, r);
2865 /** return true if http header has been read (one line complete) */
2867 http_header_done(sldns_buffer* buf)
2870 for(i=sldns_buffer_position(buf); i<sldns_buffer_limit(buf); i++) {
2871 /* there was a \r before the \n, but we ignore that */
2872 if((char)sldns_buffer_read_u8_at(buf, i) == '\n')
2878 /** return character string into buffer for header line, moves buffer
2879 * past that line and puts zero terminator into linefeed-newline */
2881 http_header_line(sldns_buffer* buf)
2883 char* result = (char*)sldns_buffer_current(buf);
2885 for(i=sldns_buffer_position(buf); i<sldns_buffer_limit(buf); i++) {
2886 /* terminate the string on the \r */
2887 if((char)sldns_buffer_read_u8_at(buf, i) == '\r')
2888 sldns_buffer_write_u8_at(buf, i, 0);
2889 /* terminate on the \n and skip past the it and done */
2890 if((char)sldns_buffer_read_u8_at(buf, i) == '\n') {
2891 sldns_buffer_write_u8_at(buf, i, 0);
2892 sldns_buffer_set_position(buf, i+1);
2899 /** move unread buffer to start and clear rest for putting the rest into it */
2901 http_moveover_buffer(sldns_buffer* buf)
2903 size_t pos = sldns_buffer_position(buf);
2904 size_t len = sldns_buffer_remaining(buf);
2905 sldns_buffer_clear(buf);
2906 memmove(sldns_buffer_begin(buf), sldns_buffer_at(buf, pos), len);
2907 sldns_buffer_set_position(buf, len);
2910 /** a http header is complete, process it */
2912 http_process_initial_header(struct comm_point* c)
2914 char* line = http_header_line(c->buffer);
2916 verbose(VERB_ALGO, "http header: %s", line);
2917 if(strncasecmp(line, "HTTP/1.1 ", 9) == 0) {
2918 /* check returncode */
2919 if(line[9] != '2') {
2920 verbose(VERB_ALGO, "http bad status %s", line+9);
2923 } else if(strncasecmp(line, "Content-Length: ", 16) == 0) {
2924 if(!c->http_is_chunked)
2925 c->tcp_byte_count = (size_t)atoi(line+16);
2926 } else if(strncasecmp(line, "Transfer-Encoding: chunked", 19+7) == 0) {
2927 c->tcp_byte_count = 0;
2928 c->http_is_chunked = 1;
2929 } else if(line[0] == 0) {
2930 /* end of initial headers */
2931 c->http_in_headers = 0;
2932 if(c->http_is_chunked)
2933 c->http_in_chunk_headers = 1;
2934 /* remove header text from front of buffer
2935 * the buffer is going to be used to return the data segment
2936 * itself and we don't want the header to get returned
2937 * prepended with it */
2938 http_moveover_buffer(c->buffer);
2939 sldns_buffer_flip(c->buffer);
2942 /* ignore other headers */
2946 /** a chunk header is complete, process it, return 0=fail, 1=continue next
2947 * header line, 2=done with chunked transfer*/
2949 http_process_chunk_header(struct comm_point* c)
2951 char* line = http_header_line(c->buffer);
2953 if(c->http_in_chunk_headers == 3) {
2954 verbose(VERB_ALGO, "http chunk trailer: %s", line);
2956 if(line[0] == 0 && c->tcp_byte_count == 0) {
2957 /* callback of http reader when NETEVENT_DONE,
2958 * end of data, with no data in buffer */
2959 sldns_buffer_set_position(c->buffer, 0);
2960 sldns_buffer_set_limit(c->buffer, 0);
2961 fptr_ok(fptr_whitelist_comm_point(c->callback));
2962 (void)(*c->callback)(c, c->cb_arg, NETEVENT_DONE, NULL);
2963 /* return that we are done */
2967 /* continue with header of the next chunk */
2968 c->http_in_chunk_headers = 1;
2969 /* remove header text from front of buffer */
2970 http_moveover_buffer(c->buffer);
2971 sldns_buffer_flip(c->buffer);
2974 /* ignore further trail headers */
2977 verbose(VERB_ALGO, "http chunk header: %s", line);
2978 if(c->http_in_chunk_headers == 1) {
2979 /* read chunked start line */
2981 c->tcp_byte_count = (size_t)strtol(line, &end, 16);
2984 c->http_in_chunk_headers = 0;
2985 /* remove header text from front of buffer */
2986 http_moveover_buffer(c->buffer);
2987 sldns_buffer_flip(c->buffer);
2988 if(c->tcp_byte_count == 0) {
2989 /* done with chunks, process chunk_trailer lines */
2990 c->http_in_chunk_headers = 3;
2994 /* ignore other headers */
2998 /** handle nonchunked data segment, 0=fail, 1=wait */
3000 http_nonchunk_segment(struct comm_point* c)
3002 /* c->buffer at position..limit has new data we read in.
3003 * the buffer itself is full of nonchunked data.
3004 * we are looking to read tcp_byte_count more data
3005 * and then the transfer is done. */
3006 size_t remainbufferlen;
3007 size_t got_now = sldns_buffer_limit(c->buffer);
3008 if(c->tcp_byte_count <= got_now) {
3009 /* done, this is the last data fragment */
3011 sldns_buffer_set_position(c->buffer, 0);
3012 fptr_ok(fptr_whitelist_comm_point(c->callback));
3013 (void)(*c->callback)(c, c->cb_arg, NETEVENT_DONE, NULL);
3016 /* if we have the buffer space,
3017 * read more data collected into the buffer */
3018 remainbufferlen = sldns_buffer_capacity(c->buffer) -
3019 sldns_buffer_limit(c->buffer);
3020 if(remainbufferlen+got_now >= c->tcp_byte_count ||
3021 remainbufferlen >= (size_t)(c->ssl?16384:2048)) {
3022 size_t total = sldns_buffer_limit(c->buffer);
3023 sldns_buffer_clear(c->buffer);
3024 sldns_buffer_set_position(c->buffer, total);
3025 c->http_stored = total;
3026 /* return and wait to read more */
3029 /* call callback with this data amount, then
3031 c->tcp_byte_count -= got_now;
3033 sldns_buffer_set_position(c->buffer, 0);
3034 fptr_ok(fptr_whitelist_comm_point(c->callback));
3035 (void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, NULL);
3036 /* c->callback has to buffer_clear(c->buffer). */
3037 /* return and wait to read more */
3041 /** handle chunked data segment, return 0=fail, 1=wait, 2=process more */
3043 http_chunked_segment(struct comm_point* c)
3045 /* the c->buffer has from position..limit new data we read. */
3046 /* the current chunk has length tcp_byte_count.
3047 * once we read that read more chunk headers.
3049 size_t remainbufferlen;
3050 size_t got_now = sldns_buffer_limit(c->buffer) - c->http_stored;
3051 verbose(VERB_ALGO, "http_chunked_segment: got now %d, tcpbytcount %d, http_stored %d, buffer pos %d, buffer limit %d", (int)got_now, (int)c->tcp_byte_count, (int)c->http_stored, (int)sldns_buffer_position(c->buffer), (int)sldns_buffer_limit(c->buffer));
3052 if(c->tcp_byte_count <= got_now) {
3053 /* the chunk has completed (with perhaps some extra data
3054 * from next chunk header and next chunk) */
3055 /* save too much info into temp buffer */
3057 struct comm_reply repinfo;
3059 sldns_buffer_skip(c->buffer, (ssize_t)c->tcp_byte_count);
3060 sldns_buffer_clear(c->http_temp);
3061 sldns_buffer_write(c->http_temp,
3062 sldns_buffer_current(c->buffer),
3063 sldns_buffer_remaining(c->buffer));
3064 sldns_buffer_flip(c->http_temp);
3066 /* callback with this fragment */
3067 fraglen = sldns_buffer_position(c->buffer);
3068 sldns_buffer_set_position(c->buffer, 0);
3069 sldns_buffer_set_limit(c->buffer, fraglen);
3070 repinfo = c->repinfo;
3071 fptr_ok(fptr_whitelist_comm_point(c->callback));
3072 (void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, &repinfo);
3073 /* c->callback has to buffer_clear(). */
3075 /* is commpoint deleted? */
3079 /* copy waiting info */
3080 sldns_buffer_clear(c->buffer);
3081 sldns_buffer_write(c->buffer,
3082 sldns_buffer_begin(c->http_temp),
3083 sldns_buffer_remaining(c->http_temp));
3084 sldns_buffer_flip(c->buffer);
3085 /* process end of chunk trailer header lines, until
3087 c->http_in_chunk_headers = 3;
3088 /* process more data in buffer (if any) */
3091 c->tcp_byte_count -= got_now;
3093 /* if we have the buffer space,
3094 * read more data collected into the buffer */
3095 remainbufferlen = sldns_buffer_capacity(c->buffer) -
3096 sldns_buffer_limit(c->buffer);
3097 if(remainbufferlen >= c->tcp_byte_count ||
3098 remainbufferlen >= 2048) {
3099 size_t total = sldns_buffer_limit(c->buffer);
3100 sldns_buffer_clear(c->buffer);
3101 sldns_buffer_set_position(c->buffer, total);
3102 c->http_stored = total;
3103 /* return and wait to read more */
3107 /* callback of http reader for a new part of the data */
3109 sldns_buffer_set_position(c->buffer, 0);
3110 fptr_ok(fptr_whitelist_comm_point(c->callback));
3111 (void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, NULL);
3112 /* c->callback has to buffer_clear(c->buffer). */
3113 /* return and wait to read more */
3118 /** Create new http2 session. Called when creating handling comm point. */
3119 static struct http2_session* http2_session_create(struct comm_point* c)
3121 struct http2_session* session = calloc(1, sizeof(*session));
3123 log_err("malloc failure while creating http2 session");
3132 /** Delete http2 session. After closing connection or on error */
3133 static void http2_session_delete(struct http2_session* h2_session)
3136 if(h2_session->callbacks)
3137 nghttp2_session_callbacks_del(h2_session->callbacks);
3145 struct http2_stream* http2_stream_create(int32_t stream_id)
3147 struct http2_stream* h2_stream = calloc(1, sizeof(*h2_stream));
3149 log_err("malloc failure while creating http2 stream");
3152 h2_stream->stream_id = stream_id;
3156 /** Delete http2 stream. After session delete or stream close callback */
3157 static void http2_stream_delete(struct http2_session* h2_session,
3158 struct http2_stream* h2_stream)
3160 if(h2_stream->mesh_state) {
3161 mesh_state_remove_reply(h2_stream->mesh, h2_stream->mesh_state,
3163 h2_stream->mesh_state = NULL;
3165 http2_req_stream_clear(h2_stream);
3170 void http2_stream_add_meshstate(struct http2_stream* h2_stream,
3171 struct mesh_area* mesh, struct mesh_state* m)
3173 h2_stream->mesh = mesh;
3174 h2_stream->mesh_state = m;
3177 /** delete http2 session server. After closing connection. */
3178 static void http2_session_server_delete(struct http2_session* h2_session)
3181 struct http2_stream* h2_stream, *next;
3182 nghttp2_session_del(h2_session->session); /* NULL input is fine */
3183 h2_session->session = NULL;
3184 for(h2_stream = h2_session->first_stream; h2_stream;) {
3185 next = h2_stream->next;
3186 http2_stream_delete(h2_session, h2_stream);
3189 h2_session->first_stream = NULL;
3190 h2_session->is_drop = 0;
3191 h2_session->postpone_drop = 0;
3192 h2_session->c->h2_stream = NULL;
3198 void http2_session_add_stream(struct http2_session* h2_session,
3199 struct http2_stream* h2_stream)
3201 if(h2_session->first_stream)
3202 h2_session->first_stream->prev = h2_stream;
3203 h2_stream->next = h2_session->first_stream;
3204 h2_session->first_stream = h2_stream;
3207 /** remove stream from session linked list. After stream close callback or
3208 * closing connection */
3209 static void http2_session_remove_stream(struct http2_session* h2_session,
3210 struct http2_stream* h2_stream)
3213 h2_stream->prev->next = h2_stream->next;
3215 h2_session->first_stream = h2_stream->next;
3217 h2_stream->next->prev = h2_stream->prev;
3221 int http2_stream_close_cb(nghttp2_session* ATTR_UNUSED(session),
3222 int32_t stream_id, uint32_t ATTR_UNUSED(error_code), void* cb_arg)
3224 struct http2_stream* h2_stream;
3225 struct http2_session* h2_session = (struct http2_session*)cb_arg;
3226 if(!(h2_stream = nghttp2_session_get_stream_user_data(
3227 h2_session->session, stream_id))) {
3230 http2_session_remove_stream(h2_session, h2_stream);
3231 http2_stream_delete(h2_session, h2_stream);
3235 ssize_t http2_recv_cb(nghttp2_session* ATTR_UNUSED(session), uint8_t* buf,
3236 size_t len, int ATTR_UNUSED(flags), void* cb_arg)
3238 struct http2_session* h2_session = (struct http2_session*)cb_arg;
3241 log_assert(h2_session->c->type == comm_http);
3242 log_assert(h2_session->c->h2_session);
3245 if(h2_session->c->ssl) {
3248 r = SSL_read(h2_session->c->ssl, buf, len);
3250 int want = SSL_get_error(h2_session->c->ssl, r);
3251 if(want == SSL_ERROR_ZERO_RETURN) {
3252 return NGHTTP2_ERR_EOF;
3253 } else if(want == SSL_ERROR_WANT_READ) {
3254 return NGHTTP2_ERR_WOULDBLOCK;
3255 } else if(want == SSL_ERROR_WANT_WRITE) {
3256 h2_session->c->ssl_shake_state = comm_ssl_shake_hs_write;
3257 comm_point_listen_for_rw(h2_session->c, 0, 1);
3258 return NGHTTP2_ERR_WOULDBLOCK;
3259 } else if(want == SSL_ERROR_SYSCALL) {
3261 if(errno == ECONNRESET && verbosity < 2)
3262 return NGHTTP2_ERR_CALLBACK_FAILURE;
3265 log_err("SSL_read syscall: %s",
3267 return NGHTTP2_ERR_CALLBACK_FAILURE;
3269 log_crypto_err("could not SSL_read");
3270 return NGHTTP2_ERR_CALLBACK_FAILURE;
3274 #endif /* HAVE_SSL */
3276 ret = recv(h2_session->c->fd, buf, len, MSG_DONTWAIT);
3278 return NGHTTP2_ERR_EOF;
3279 } else if(ret < 0) {
3281 if(errno == EINTR || errno == EAGAIN)
3282 return NGHTTP2_ERR_WOULDBLOCK;
3284 if(errno == ECONNRESET && verbosity < 2)
3285 return NGHTTP2_ERR_CALLBACK_FAILURE;
3287 log_err_addr("could not http2 recv: %s", strerror(errno),
3288 &h2_session->c->repinfo.remote_addr,
3289 h2_session->c->repinfo.remote_addrlen);
3290 #else /* USE_WINSOCK */
3291 if(WSAGetLastError() == WSAECONNRESET)
3292 return NGHTTP2_ERR_CALLBACK_FAILURE;
3293 if(WSAGetLastError() == WSAEINPROGRESS)
3294 return NGHTTP2_ERR_WOULDBLOCK;
3295 if(WSAGetLastError() == WSAEWOULDBLOCK) {
3296 ub_winsock_tcp_wouldblock(h2_session->c->ev->ev,
3298 return NGHTTP2_ERR_WOULDBLOCK;
3300 log_err_addr("could not http2 recv: %s",
3301 wsa_strerror(WSAGetLastError()),
3302 &h2_session->c->repinfo.remote_addr,
3303 h2_session->c->repinfo.remote_addrlen);
3305 return NGHTTP2_ERR_CALLBACK_FAILURE;
3309 #endif /* HAVE_NGHTTP2 */
3311 /** Handle http2 read */
3313 comm_point_http2_handle_read(int ATTR_UNUSED(fd), struct comm_point* c)
3317 log_assert(c->h2_session);
3319 /* reading until recv cb returns NGHTTP2_ERR_WOULDBLOCK */
3320 ret = nghttp2_session_recv(c->h2_session->session);
3322 if(ret != NGHTTP2_ERR_EOF &&
3323 ret != NGHTTP2_ERR_CALLBACK_FAILURE) {
3325 addr_to_str(&c->repinfo.remote_addr,
3326 c->repinfo.remote_addrlen, a, sizeof(a));
3327 verbose(VERB_QUERY, "http2: session_recv from %s failed, "
3328 "error: %s", a, nghttp2_strerror(ret));
3332 if(nghttp2_session_want_write(c->h2_session->session)) {
3333 c->tcp_is_reading = 0;
3334 comm_point_stop_listening(c);
3335 comm_point_start_listening(c, -1, adjusted_tcp_timeout(c));
3336 } else if(!nghttp2_session_want_read(c->h2_session->session))
3337 return 0; /* connection can be closed */
3346 * Handle http reading callback.
3347 * @param fd: file descriptor of socket.
3348 * @param c: comm point to read from into buffer.
3349 * @return: 0 on error
3352 comm_point_http_handle_read(int fd, struct comm_point* c)
3354 log_assert(c->type == comm_http);
3355 log_assert(fd != -1);
3357 /* if we are in ssl handshake, handle SSL handshake */
3359 if(c->ssl && c->ssl_shake_state != comm_ssl_shake_none) {
3360 if(!ssl_handshake(c))
3362 if(c->ssl_shake_state != comm_ssl_shake_none)
3365 #endif /* HAVE_SSL */
3367 if(!c->tcp_is_reading)
3371 return comm_point_http2_handle_read(fd, c);
3374 /* http version is <= http/1.1 */
3376 if(c->http_min_version >= http_version_2) {
3377 /* HTTP/2 failed, not allowed to use lower version. */
3381 /* read more data */
3383 if(!ssl_http_read_more(c))
3386 if(!http_read_more(fd, c))
3390 if(c->http_stored >= sldns_buffer_position(c->buffer)) {
3391 /* read did not work but we wanted more data, there is
3392 * no bytes to process now. */
3395 sldns_buffer_flip(c->buffer);
3396 /* if we are partway in a segment of data, position us at the point
3397 * where we left off previously */
3398 if(c->http_stored < sldns_buffer_limit(c->buffer))
3399 sldns_buffer_set_position(c->buffer, c->http_stored);
3400 else sldns_buffer_set_position(c->buffer, sldns_buffer_limit(c->buffer));
3402 while(sldns_buffer_remaining(c->buffer) > 0) {
3403 /* Handle HTTP/1.x data */
3404 /* if we are reading headers, read more headers */
3405 if(c->http_in_headers || c->http_in_chunk_headers) {
3406 /* if header is done, process the header */
3407 if(!http_header_done(c->buffer)) {
3408 /* copy remaining data to front of buffer
3409 * and set rest for writing into it */
3410 http_moveover_buffer(c->buffer);
3411 /* return and wait to read more */
3414 if(!c->http_in_chunk_headers) {
3415 /* process initial headers */
3416 if(!http_process_initial_header(c))
3419 /* process chunk headers */
3420 int r = http_process_chunk_header(c);
3421 if(r == 0) return 0;
3422 if(r == 2) return 1; /* done */
3423 /* r == 1, continue */
3425 /* see if we have more to process */
3429 if(!c->http_is_chunked) {
3430 /* if we are reading nonchunks, process that*/
3431 return http_nonchunk_segment(c);
3433 /* if we are reading chunks, read the chunk */
3434 int r = http_chunked_segment(c);
3435 if(r == 0) return 0;
3436 if(r == 1) return 1;
3440 /* broke out of the loop; could not process header instead need
3442 /* moveover any remaining data and read more data */
3443 http_moveover_buffer(c->buffer);
3444 /* return and wait to read more */
3448 /** check pending connect for http */
3450 http_check_connect(int fd, struct comm_point* c)
3452 /* check for pending error from nonblocking connect */
3453 /* from Stevens, unix network programming, vol1, 3rd ed, p450*/
3455 socklen_t len = (socklen_t)sizeof(error);
3456 if(getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&error,
3459 error = errno; /* on solaris errno is error */
3460 #else /* USE_WINSOCK */
3461 error = WSAGetLastError();
3465 #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
3466 if(error == EINPROGRESS || error == EWOULDBLOCK)
3467 return 1; /* try again later */
3470 if(error != 0 && verbosity < 2)
3471 return 0; /* silence lots of chatter in the logs */
3472 else if(error != 0) {
3473 log_err_addr("http connect", strerror(error),
3474 &c->repinfo.remote_addr, c->repinfo.remote_addrlen);
3475 #else /* USE_WINSOCK */
3477 if(error == WSAEINPROGRESS)
3479 else if(error == WSAEWOULDBLOCK) {
3480 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
3482 } else if(error != 0 && verbosity < 2)
3484 else if(error != 0) {
3485 log_err_addr("http connect", wsa_strerror(error),
3486 &c->repinfo.remote_addr, c->repinfo.remote_addrlen);
3487 #endif /* USE_WINSOCK */
3490 /* keep on processing this socket */
3494 /** write more data for http (with ssl) */
3496 ssl_http_write_more(struct comm_point* c)
3500 log_assert(sldns_buffer_remaining(c->buffer) > 0);
3502 r = SSL_write(c->ssl, (void*)sldns_buffer_current(c->buffer),
3503 (int)sldns_buffer_remaining(c->buffer));
3505 int want = SSL_get_error(c->ssl, r);
3506 if(want == SSL_ERROR_ZERO_RETURN) {
3507 return 0; /* closed */
3508 } else if(want == SSL_ERROR_WANT_READ) {
3509 c->ssl_shake_state = comm_ssl_shake_hs_read;
3510 comm_point_listen_for_rw(c, 1, 0);
3511 return 1; /* wait for read condition */
3512 } else if(want == SSL_ERROR_WANT_WRITE) {
3513 return 1; /* write more later */
3514 } else if(want == SSL_ERROR_SYSCALL) {
3516 if(errno == EPIPE && verbosity < 2)
3517 return 0; /* silence 'broken pipe' */
3520 log_err("SSL_write syscall: %s",
3524 log_crypto_err("could not SSL_write");
3527 sldns_buffer_skip(c->buffer, (ssize_t)r);
3532 #endif /* HAVE_SSL */
3535 /** write more data for http */
3537 http_write_more(int fd, struct comm_point* c)
3540 log_assert(sldns_buffer_remaining(c->buffer) > 0);
3541 r = send(fd, (void*)sldns_buffer_current(c->buffer),
3542 sldns_buffer_remaining(c->buffer), 0);
3545 if(errno == EINTR || errno == EAGAIN)
3548 if(WSAGetLastError() == WSAEINPROGRESS)
3550 if(WSAGetLastError() == WSAEWOULDBLOCK) {
3551 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
3555 log_err_addr("http send r", sock_strerror(errno),
3556 &c->repinfo.remote_addr, c->repinfo.remote_addrlen);
3559 sldns_buffer_skip(c->buffer, r);
3564 ssize_t http2_send_cb(nghttp2_session* ATTR_UNUSED(session), const uint8_t* buf,
3565 size_t len, int ATTR_UNUSED(flags), void* cb_arg)
3568 struct http2_session* h2_session = (struct http2_session*)cb_arg;
3569 log_assert(h2_session->c->type == comm_http);
3570 log_assert(h2_session->c->h2_session);
3573 if(h2_session->c->ssl) {
3576 r = SSL_write(h2_session->c->ssl, buf, len);
3578 int want = SSL_get_error(h2_session->c->ssl, r);
3579 if(want == SSL_ERROR_ZERO_RETURN) {
3580 return NGHTTP2_ERR_CALLBACK_FAILURE;
3581 } else if(want == SSL_ERROR_WANT_READ) {
3582 h2_session->c->ssl_shake_state = comm_ssl_shake_hs_read;
3583 comm_point_listen_for_rw(h2_session->c, 1, 0);
3584 return NGHTTP2_ERR_WOULDBLOCK;
3585 } else if(want == SSL_ERROR_WANT_WRITE) {
3586 return NGHTTP2_ERR_WOULDBLOCK;
3587 } else if(want == SSL_ERROR_SYSCALL) {
3589 if(errno == EPIPE && verbosity < 2)
3590 return NGHTTP2_ERR_CALLBACK_FAILURE;
3593 log_err("SSL_write syscall: %s",
3595 return NGHTTP2_ERR_CALLBACK_FAILURE;
3597 log_crypto_err("could not SSL_write");
3598 return NGHTTP2_ERR_CALLBACK_FAILURE;
3602 #endif /* HAVE_SSL */
3604 ret = send(h2_session->c->fd, buf, len, 0);
3606 return NGHTTP2_ERR_CALLBACK_FAILURE;
3607 } else if(ret < 0) {
3609 if(errno == EINTR || errno == EAGAIN)
3610 return NGHTTP2_ERR_WOULDBLOCK;
3612 if(errno == EPIPE && verbosity < 2)
3613 return NGHTTP2_ERR_CALLBACK_FAILURE;
3616 if(errno == ECONNRESET && verbosity < 2)
3617 return NGHTTP2_ERR_CALLBACK_FAILURE;
3619 log_err_addr("could not http2 write: %s", strerror(errno),
3620 &h2_session->c->repinfo.remote_addr,
3621 h2_session->c->repinfo.remote_addrlen);
3622 #else /* USE_WINSOCK */
3623 if(WSAGetLastError() == WSAENOTCONN)
3624 return NGHTTP2_ERR_WOULDBLOCK;
3625 if(WSAGetLastError() == WSAEINPROGRESS)
3626 return NGHTTP2_ERR_WOULDBLOCK;
3627 if(WSAGetLastError() == WSAEWOULDBLOCK) {
3628 ub_winsock_tcp_wouldblock(h2_session->c->ev->ev,
3630 return NGHTTP2_ERR_WOULDBLOCK;
3632 if(WSAGetLastError() == WSAECONNRESET && verbosity < 2)
3633 return NGHTTP2_ERR_CALLBACK_FAILURE;
3634 log_err_addr("could not http2 write: %s",
3635 wsa_strerror(WSAGetLastError()),
3636 &h2_session->c->repinfo.remote_addr,
3637 h2_session->c->repinfo.remote_addrlen);
3639 return NGHTTP2_ERR_CALLBACK_FAILURE;
3643 #endif /* HAVE_NGHTTP2 */
3645 /** Handle http2 writing */
3647 comm_point_http2_handle_write(int ATTR_UNUSED(fd), struct comm_point* c)
3651 log_assert(c->h2_session);
3653 ret = nghttp2_session_send(c->h2_session->session);
3655 verbose(VERB_QUERY, "http2: session_send failed, "
3656 "error: %s", nghttp2_strerror(ret));
3660 if(nghttp2_session_want_read(c->h2_session->session)) {
3661 c->tcp_is_reading = 1;
3662 comm_point_stop_listening(c);
3663 comm_point_start_listening(c, -1, adjusted_tcp_timeout(c));
3664 } else if(!nghttp2_session_want_write(c->h2_session->session))
3665 return 0; /* connection can be closed */
3674 * Handle http writing callback.
3675 * @param fd: file descriptor of socket.
3676 * @param c: comm point to write buffer out of.
3677 * @return: 0 on error
3680 comm_point_http_handle_write(int fd, struct comm_point* c)
3682 log_assert(c->type == comm_http);
3683 log_assert(fd != -1);
3685 /* check pending connect errors, if that fails, we wait for more,
3686 * or we can continue to write contents */
3687 if(c->tcp_check_nb_connect) {
3688 int r = http_check_connect(fd, c);
3689 if(r == 0) return 0;
3690 if(r == 1) return 1;
3691 c->tcp_check_nb_connect = 0;
3693 /* if we are in ssl handshake, handle SSL handshake */
3695 if(c->ssl && c->ssl_shake_state != comm_ssl_shake_none) {
3696 if(!ssl_handshake(c))
3698 if(c->ssl_shake_state != comm_ssl_shake_none)
3701 #endif /* HAVE_SSL */
3702 if(c->tcp_is_reading)
3706 return comm_point_http2_handle_write(fd, c);
3709 /* http version is <= http/1.1 */
3711 if(c->http_min_version >= http_version_2) {
3712 /* HTTP/2 failed, not allowed to use lower version. */
3716 /* if we are writing, write more */
3718 if(!ssl_http_write_more(c))
3721 if(!http_write_more(fd, c))
3725 /* we write a single buffer contents, that can contain
3726 * the http request, and then flip to read the results */
3727 /* see if write is done */
3728 if(sldns_buffer_remaining(c->buffer) == 0) {
3729 sldns_buffer_clear(c->buffer);
3730 if(c->tcp_do_toggle_rw)
3731 c->tcp_is_reading = 1;
3732 c->tcp_byte_count = 0;
3733 /* switch from listening(write) to listening(read) */
3734 comm_point_stop_listening(c);
3735 comm_point_start_listening(c, -1, -1);
3741 comm_point_http_handle_callback(int fd, short event, void* arg)
3743 struct comm_point* c = (struct comm_point*)arg;
3744 log_assert(c->type == comm_http);
3745 ub_comm_base_now(c->ev->base);
3747 if(event&UB_EV_TIMEOUT) {
3748 verbose(VERB_QUERY, "http took too long, dropped");
3749 reclaim_http_handler(c);
3750 if(!c->tcp_do_close) {
3751 fptr_ok(fptr_whitelist_comm_point(c->callback));
3752 (void)(*c->callback)(c, c->cb_arg,
3753 NETEVENT_TIMEOUT, NULL);
3757 if(event&UB_EV_READ) {
3758 if(!comm_point_http_handle_read(fd, c)) {
3759 reclaim_http_handler(c);
3760 if(!c->tcp_do_close) {
3761 fptr_ok(fptr_whitelist_comm_point(
3763 (void)(*c->callback)(c, c->cb_arg,
3764 NETEVENT_CLOSED, NULL);
3769 if(event&UB_EV_WRITE) {
3770 if(!comm_point_http_handle_write(fd, c)) {
3771 reclaim_http_handler(c);
3772 if(!c->tcp_do_close) {
3773 fptr_ok(fptr_whitelist_comm_point(
3775 (void)(*c->callback)(c, c->cb_arg,
3776 NETEVENT_CLOSED, NULL);
3781 log_err("Ignored event %d for httphdl.", event);
3784 void comm_point_local_handle_callback(int fd, short event, void* arg)
3786 struct comm_point* c = (struct comm_point*)arg;
3787 log_assert(c->type == comm_local);
3788 ub_comm_base_now(c->ev->base);
3790 if(event&UB_EV_READ) {
3791 if(!comm_point_tcp_handle_read(fd, c, 1)) {
3792 fptr_ok(fptr_whitelist_comm_point(c->callback));
3793 (void)(*c->callback)(c, c->cb_arg, NETEVENT_CLOSED,
3798 log_err("Ignored event %d for localhdl.", event);
3801 void comm_point_raw_handle_callback(int ATTR_UNUSED(fd),
3802 short event, void* arg)
3804 struct comm_point* c = (struct comm_point*)arg;
3805 int err = NETEVENT_NOERROR;
3806 log_assert(c->type == comm_raw);
3807 ub_comm_base_now(c->ev->base);
3809 if(event&UB_EV_TIMEOUT)
3810 err = NETEVENT_TIMEOUT;
3811 fptr_ok(fptr_whitelist_comm_point_raw(c->callback));
3812 (void)(*c->callback)(c, c->cb_arg, err, NULL);
3816 comm_point_create_udp(struct comm_base *base, int fd, sldns_buffer* buffer,
3817 int pp2_enabled, comm_point_callback_type* callback,
3818 void* callback_arg, struct unbound_socket* socket)
3820 struct comm_point* c = (struct comm_point*)calloc(1,
3821 sizeof(struct comm_point));
3825 c->ev = (struct internal_event*)calloc(1,
3826 sizeof(struct internal_event));
3835 c->tcp_is_reading = 0;
3836 c->tcp_byte_count = 0;
3837 c->tcp_parent = NULL;
3838 c->max_tcp_count = 0;
3839 c->cur_tcp_count = 0;
3840 c->tcp_handlers = NULL;
3843 c->tcp_do_close = 0;
3844 c->do_not_close = 0;
3845 c->tcp_do_toggle_rw = 0;
3846 c->tcp_check_nb_connect = 0;
3847 #ifdef USE_MSG_FASTOPEN
3848 c->tcp_do_fastopen = 0;
3852 c->dnscrypt_buffer = buffer;
3855 c->callback = callback;
3856 c->cb_arg = callback_arg;
3858 c->pp2_enabled = pp2_enabled;
3859 c->pp2_header_state = pp2_header_none;
3860 evbits = UB_EV_READ | UB_EV_PERSIST;
3861 /* ub_event stuff */
3862 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
3864 comm_point_udp_callback, c);
3866 comm_point_udp_ancil_callback, c);
3868 if(c->ev->ev == NULL) {
3869 log_err("could not baseset udp event");
3870 comm_point_delete(c);
3873 if(fd!=-1 && ub_event_add(c->ev->ev, c->timeout) != 0 ) {
3874 log_err("could not add udp event");
3875 comm_point_delete(c);
3883 comm_point_create_udp_ancil(struct comm_base *base, int fd,
3884 sldns_buffer* buffer, int pp2_enabled,
3885 comm_point_callback_type* callback, void* callback_arg, struct unbound_socket* socket)
3887 struct comm_point* c = (struct comm_point*)calloc(1,
3888 sizeof(struct comm_point));
3892 c->ev = (struct internal_event*)calloc(1,
3893 sizeof(struct internal_event));
3902 c->tcp_is_reading = 0;
3903 c->tcp_byte_count = 0;
3904 c->tcp_parent = NULL;
3905 c->max_tcp_count = 0;
3906 c->cur_tcp_count = 0;
3907 c->tcp_handlers = NULL;
3910 c->tcp_do_close = 0;
3911 c->do_not_close = 0;
3914 c->dnscrypt_buffer = buffer;
3917 c->tcp_do_toggle_rw = 0;
3918 c->tcp_check_nb_connect = 0;
3919 #ifdef USE_MSG_FASTOPEN
3920 c->tcp_do_fastopen = 0;
3922 c->callback = callback;
3923 c->cb_arg = callback_arg;
3925 c->pp2_enabled = pp2_enabled;
3926 c->pp2_header_state = pp2_header_none;
3927 evbits = UB_EV_READ | UB_EV_PERSIST;
3928 /* ub_event stuff */
3929 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
3930 comm_point_udp_ancil_callback, c);
3931 if(c->ev->ev == NULL) {
3932 log_err("could not baseset udp event");
3933 comm_point_delete(c);
3936 if(fd!=-1 && ub_event_add(c->ev->ev, c->timeout) != 0 ) {
3937 log_err("could not add udp event");
3938 comm_point_delete(c);
3945 static struct comm_point*
3946 comm_point_create_tcp_handler(struct comm_base *base,
3947 struct comm_point* parent, size_t bufsize,
3948 struct sldns_buffer* spoolbuf, comm_point_callback_type* callback,
3949 void* callback_arg, struct unbound_socket* socket)
3951 struct comm_point* c = (struct comm_point*)calloc(1,
3952 sizeof(struct comm_point));
3956 c->ev = (struct internal_event*)calloc(1,
3957 sizeof(struct internal_event));
3964 c->buffer = sldns_buffer_new(bufsize);
3970 c->timeout = (struct timeval*)malloc(sizeof(struct timeval));
3972 sldns_buffer_free(c->buffer);
3977 c->tcp_is_reading = 0;
3978 c->tcp_byte_count = 0;
3979 c->tcp_parent = parent;
3980 c->tcp_timeout_msec = parent->tcp_timeout_msec;
3981 c->tcp_conn_limit = parent->tcp_conn_limit;
3983 c->tcp_keepalive = 0;
3984 c->max_tcp_count = 0;
3985 c->cur_tcp_count = 0;
3986 c->tcp_handlers = NULL;
3989 c->tcp_do_close = 0;
3990 c->do_not_close = 0;
3991 c->tcp_do_toggle_rw = 1;
3992 c->tcp_check_nb_connect = 0;
3993 #ifdef USE_MSG_FASTOPEN
3994 c->tcp_do_fastopen = 0;
3998 /* We don't know just yet if this is a dnscrypt channel. Allocation
3999 * will be done when handling the callback. */
4000 c->dnscrypt_buffer = c->buffer;
4003 c->callback = callback;
4004 c->cb_arg = callback_arg;
4006 c->pp2_enabled = parent->pp2_enabled;
4007 c->pp2_header_state = pp2_header_none;
4009 c->tcp_req_info = tcp_req_info_create(spoolbuf);
4010 if(!c->tcp_req_info) {
4011 log_err("could not create tcp commpoint");
4012 sldns_buffer_free(c->buffer);
4018 c->tcp_req_info->cp = c;
4019 c->tcp_do_close = 1;
4020 c->tcp_do_toggle_rw = 0;
4022 /* add to parent free list */
4023 c->tcp_free = parent->tcp_free;
4024 parent->tcp_free = c;
4025 /* ub_event stuff */
4026 evbits = UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT;
4027 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
4028 comm_point_tcp_handle_callback, c);
4029 if(c->ev->ev == NULL)
4031 log_err("could not basetset tcphdl event");
4032 parent->tcp_free = c->tcp_free;
4033 tcp_req_info_delete(c->tcp_req_info);
4034 sldns_buffer_free(c->buffer);
4043 static struct comm_point*
4044 comm_point_create_http_handler(struct comm_base *base,
4045 struct comm_point* parent, size_t bufsize, int harden_large_queries,
4046 uint32_t http_max_streams, char* http_endpoint,
4047 comm_point_callback_type* callback, void* callback_arg,
4048 struct unbound_socket* socket)
4050 struct comm_point* c = (struct comm_point*)calloc(1,
4051 sizeof(struct comm_point));
4055 c->ev = (struct internal_event*)calloc(1,
4056 sizeof(struct internal_event));
4063 c->buffer = sldns_buffer_new(bufsize);
4069 c->timeout = (struct timeval*)malloc(sizeof(struct timeval));
4071 sldns_buffer_free(c->buffer);
4076 c->tcp_is_reading = 0;
4077 c->tcp_byte_count = 0;
4078 c->tcp_parent = parent;
4079 c->tcp_timeout_msec = parent->tcp_timeout_msec;
4080 c->tcp_conn_limit = parent->tcp_conn_limit;
4082 c->tcp_keepalive = 0;
4083 c->max_tcp_count = 0;
4084 c->cur_tcp_count = 0;
4085 c->tcp_handlers = NULL;
4087 c->type = comm_http;
4088 c->tcp_do_close = 1;
4089 c->do_not_close = 0;
4090 c->tcp_do_toggle_rw = 1; /* will be set to 0 after http2 upgrade */
4091 c->tcp_check_nb_connect = 0;
4092 #ifdef USE_MSG_FASTOPEN
4093 c->tcp_do_fastopen = 0;
4097 c->dnscrypt_buffer = NULL;
4100 c->callback = callback;
4101 c->cb_arg = callback_arg;
4104 c->pp2_header_state = pp2_header_none;
4106 c->http_min_version = http_version_2;
4107 c->http2_stream_max_qbuffer_size = bufsize;
4108 if(harden_large_queries && bufsize > 512)
4109 c->http2_stream_max_qbuffer_size = 512;
4110 c->http2_max_streams = http_max_streams;
4111 if(!(c->http_endpoint = strdup(http_endpoint))) {
4112 log_err("could not strdup http_endpoint");
4113 sldns_buffer_free(c->buffer);
4121 if(!(c->h2_session = http2_session_create(c))) {
4122 log_err("could not create http2 session");
4123 free(c->http_endpoint);
4124 sldns_buffer_free(c->buffer);
4130 if(!(c->h2_session->callbacks = http2_req_callbacks_create())) {
4131 log_err("could not create http2 callbacks");
4132 http2_session_delete(c->h2_session);
4133 free(c->http_endpoint);
4134 sldns_buffer_free(c->buffer);
4142 /* add to parent free list */
4143 c->tcp_free = parent->tcp_free;
4144 parent->tcp_free = c;
4145 /* ub_event stuff */
4146 evbits = UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT;
4147 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
4148 comm_point_http_handle_callback, c);
4149 if(c->ev->ev == NULL)
4151 log_err("could not set http handler event");
4152 parent->tcp_free = c->tcp_free;
4153 http2_session_delete(c->h2_session);
4154 sldns_buffer_free(c->buffer);
4164 comm_point_create_tcp(struct comm_base *base, int fd, int num,
4165 int idle_timeout, int harden_large_queries,
4166 uint32_t http_max_streams, char* http_endpoint,
4167 struct tcl_list* tcp_conn_limit, size_t bufsize,
4168 struct sldns_buffer* spoolbuf, enum listen_type port_type,
4169 int pp2_enabled, comm_point_callback_type* callback,
4170 void* callback_arg, struct unbound_socket* socket)
4172 struct comm_point* c = (struct comm_point*)calloc(1,
4173 sizeof(struct comm_point));
4176 /* first allocate the TCP accept listener */
4179 c->ev = (struct internal_event*)calloc(1,
4180 sizeof(struct internal_event));
4189 c->tcp_is_reading = 0;
4190 c->tcp_byte_count = 0;
4191 c->tcp_timeout_msec = idle_timeout;
4192 c->tcp_conn_limit = tcp_conn_limit;
4194 c->tcp_keepalive = 0;
4195 c->tcp_parent = NULL;
4196 c->max_tcp_count = num;
4197 c->cur_tcp_count = 0;
4198 c->tcp_handlers = (struct comm_point**)calloc((size_t)num,
4199 sizeof(struct comm_point*));
4200 if(!c->tcp_handlers) {
4206 c->type = comm_tcp_accept;
4207 c->tcp_do_close = 0;
4208 c->do_not_close = 0;
4209 c->tcp_do_toggle_rw = 0;
4210 c->tcp_check_nb_connect = 0;
4211 #ifdef USE_MSG_FASTOPEN
4212 c->tcp_do_fastopen = 0;
4216 c->dnscrypt_buffer = NULL;
4221 c->pp2_enabled = (port_type==listen_type_http?0:pp2_enabled);
4222 c->pp2_header_state = pp2_header_none;
4223 evbits = UB_EV_READ | UB_EV_PERSIST;
4224 /* ub_event stuff */
4225 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
4226 comm_point_tcp_accept_callback, c);
4227 if(c->ev->ev == NULL) {
4228 log_err("could not baseset tcpacc event");
4229 comm_point_delete(c);
4232 if (ub_event_add(c->ev->ev, c->timeout) != 0) {
4233 log_err("could not add tcpacc event");
4234 comm_point_delete(c);
4238 /* now prealloc the handlers */
4239 for(i=0; i<num; i++) {
4240 if(port_type == listen_type_tcp ||
4241 port_type == listen_type_ssl ||
4242 port_type == listen_type_tcp_dnscrypt) {
4243 c->tcp_handlers[i] = comm_point_create_tcp_handler(base,
4244 c, bufsize, spoolbuf, callback, callback_arg, socket);
4245 } else if(port_type == listen_type_http) {
4246 c->tcp_handlers[i] = comm_point_create_http_handler(
4247 base, c, bufsize, harden_large_queries,
4248 http_max_streams, http_endpoint,
4249 callback, callback_arg, socket);
4252 log_err("could not create tcp handler, unknown listen "
4256 if(!c->tcp_handlers[i]) {
4257 comm_point_delete(c);
4266 comm_point_create_tcp_out(struct comm_base *base, size_t bufsize,
4267 comm_point_callback_type* callback, void* callback_arg)
4269 struct comm_point* c = (struct comm_point*)calloc(1,
4270 sizeof(struct comm_point));
4274 c->ev = (struct internal_event*)calloc(1,
4275 sizeof(struct internal_event));
4282 c->buffer = sldns_buffer_new(bufsize);
4289 c->tcp_is_reading = 0;
4290 c->tcp_byte_count = 0;
4291 c->tcp_timeout_msec = TCP_QUERY_TIMEOUT;
4292 c->tcp_conn_limit = NULL;
4294 c->tcp_keepalive = 0;
4295 c->tcp_parent = NULL;
4296 c->max_tcp_count = 0;
4297 c->cur_tcp_count = 0;
4298 c->tcp_handlers = NULL;
4301 c->tcp_do_close = 0;
4302 c->do_not_close = 0;
4303 c->tcp_do_toggle_rw = 1;
4304 c->tcp_check_nb_connect = 1;
4305 #ifdef USE_MSG_FASTOPEN
4306 c->tcp_do_fastopen = 1;
4310 c->dnscrypt_buffer = c->buffer;
4313 c->callback = callback;
4314 c->cb_arg = callback_arg;
4316 c->pp2_header_state = pp2_header_none;
4317 evbits = UB_EV_PERSIST | UB_EV_WRITE;
4318 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
4319 comm_point_tcp_handle_callback, c);
4320 if(c->ev->ev == NULL)
4322 log_err("could not baseset tcpout event");
4323 sldns_buffer_free(c->buffer);
4333 comm_point_create_http_out(struct comm_base *base, size_t bufsize,
4334 comm_point_callback_type* callback, void* callback_arg,
4337 struct comm_point* c = (struct comm_point*)calloc(1,
4338 sizeof(struct comm_point));
4342 c->ev = (struct internal_event*)calloc(1,
4343 sizeof(struct internal_event));
4350 c->buffer = sldns_buffer_new(bufsize);
4357 c->tcp_is_reading = 0;
4358 c->tcp_byte_count = 0;
4359 c->tcp_parent = NULL;
4360 c->max_tcp_count = 0;
4361 c->cur_tcp_count = 0;
4362 c->tcp_handlers = NULL;
4364 c->type = comm_http;
4365 c->tcp_do_close = 0;
4366 c->do_not_close = 0;
4367 c->tcp_do_toggle_rw = 1;
4368 c->tcp_check_nb_connect = 1;
4369 c->http_in_headers = 1;
4370 c->http_in_chunk_headers = 0;
4371 c->http_is_chunked = 0;
4372 c->http_temp = temp;
4373 #ifdef USE_MSG_FASTOPEN
4374 c->tcp_do_fastopen = 1;
4378 c->dnscrypt_buffer = c->buffer;
4381 c->callback = callback;
4382 c->cb_arg = callback_arg;
4384 c->pp2_header_state = pp2_header_none;
4385 evbits = UB_EV_PERSIST | UB_EV_WRITE;
4386 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
4387 comm_point_http_handle_callback, c);
4388 if(c->ev->ev == NULL)
4390 log_err("could not baseset tcpout event");
4394 sldns_buffer_free(c->buffer);
4404 comm_point_create_local(struct comm_base *base, int fd, size_t bufsize,
4405 comm_point_callback_type* callback, void* callback_arg)
4407 struct comm_point* c = (struct comm_point*)calloc(1,
4408 sizeof(struct comm_point));
4412 c->ev = (struct internal_event*)calloc(1,
4413 sizeof(struct internal_event));
4420 c->buffer = sldns_buffer_new(bufsize);
4427 c->tcp_is_reading = 1;
4428 c->tcp_byte_count = 0;
4429 c->tcp_parent = NULL;
4430 c->max_tcp_count = 0;
4431 c->cur_tcp_count = 0;
4432 c->tcp_handlers = NULL;
4434 c->type = comm_local;
4435 c->tcp_do_close = 0;
4436 c->do_not_close = 1;
4437 c->tcp_do_toggle_rw = 0;
4438 c->tcp_check_nb_connect = 0;
4439 #ifdef USE_MSG_FASTOPEN
4440 c->tcp_do_fastopen = 0;
4444 c->dnscrypt_buffer = c->buffer;
4446 c->callback = callback;
4447 c->cb_arg = callback_arg;
4449 c->pp2_header_state = pp2_header_none;
4450 /* ub_event stuff */
4451 evbits = UB_EV_PERSIST | UB_EV_READ;
4452 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
4453 comm_point_local_handle_callback, c);
4454 if(c->ev->ev == NULL) {
4455 log_err("could not baseset localhdl event");
4460 if (ub_event_add(c->ev->ev, c->timeout) != 0) {
4461 log_err("could not add localhdl event");
4462 ub_event_free(c->ev->ev);
4472 comm_point_create_raw(struct comm_base* base, int fd, int writing,
4473 comm_point_callback_type* callback, void* callback_arg)
4475 struct comm_point* c = (struct comm_point*)calloc(1,
4476 sizeof(struct comm_point));
4480 c->ev = (struct internal_event*)calloc(1,
4481 sizeof(struct internal_event));
4490 c->tcp_is_reading = 0;
4491 c->tcp_byte_count = 0;
4492 c->tcp_parent = NULL;
4493 c->max_tcp_count = 0;
4494 c->cur_tcp_count = 0;
4495 c->tcp_handlers = NULL;
4498 c->tcp_do_close = 0;
4499 c->do_not_close = 1;
4500 c->tcp_do_toggle_rw = 0;
4501 c->tcp_check_nb_connect = 0;
4502 #ifdef USE_MSG_FASTOPEN
4503 c->tcp_do_fastopen = 0;
4507 c->dnscrypt_buffer = c->buffer;
4509 c->callback = callback;
4510 c->cb_arg = callback_arg;
4512 c->pp2_header_state = pp2_header_none;
4513 /* ub_event stuff */
4515 evbits = UB_EV_PERSIST | UB_EV_WRITE;
4516 else evbits = UB_EV_PERSIST | UB_EV_READ;
4517 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
4518 comm_point_raw_handle_callback, c);
4519 if(c->ev->ev == NULL) {
4520 log_err("could not baseset rawhdl event");
4525 if (ub_event_add(c->ev->ev, c->timeout) != 0) {
4526 log_err("could not add rawhdl event");
4527 ub_event_free(c->ev->ev);
4537 comm_point_close(struct comm_point* c)
4542 verbose(5, "comm_point_close of %d: event_del", c->fd);
4543 if(c->event_added) {
4544 if(ub_event_del(c->ev->ev) != 0) {
4545 log_err("could not event_del on close");
4550 tcl_close_connection(c->tcl_addr);
4552 tcp_req_info_clear(c->tcp_req_info);
4554 http2_session_server_delete(c->h2_session);
4555 /* stop the comm point from reading or writing after it is closed. */
4556 if(c->tcp_more_read_again && *c->tcp_more_read_again)
4557 *c->tcp_more_read_again = 0;
4558 if(c->tcp_more_write_again && *c->tcp_more_write_again)
4559 *c->tcp_more_write_again = 0;
4561 /* close fd after removing from event lists, or epoll.. is messed up */
4562 if(c->fd != -1 && !c->do_not_close) {
4564 if(c->type == comm_tcp || c->type == comm_http) {
4565 /* delete sticky events for the fd, it gets closed */
4566 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
4567 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
4570 verbose(VERB_ALGO, "close fd %d", c->fd);
4577 comm_point_delete(struct comm_point* c)
4581 if((c->type == comm_tcp || c->type == comm_http) && c->ssl) {
4583 SSL_shutdown(c->ssl);
4587 if(c->type == comm_http && c->http_endpoint) {
4588 free(c->http_endpoint);
4589 c->http_endpoint = NULL;
4591 comm_point_close(c);
4592 if(c->tcp_handlers) {
4594 for(i=0; i<c->max_tcp_count; i++)
4595 comm_point_delete(c->tcp_handlers[i]);
4596 free(c->tcp_handlers);
4599 if(c->type == comm_tcp || c->type == comm_local || c->type == comm_http) {
4600 sldns_buffer_free(c->buffer);
4602 if(c->dnscrypt && c->dnscrypt_buffer != c->buffer) {
4603 sldns_buffer_free(c->dnscrypt_buffer);
4606 if(c->tcp_req_info) {
4607 tcp_req_info_delete(c->tcp_req_info);
4610 http2_session_delete(c->h2_session);
4613 ub_event_free(c->ev->ev);
4619 comm_point_send_reply(struct comm_reply *repinfo)
4621 struct sldns_buffer* buffer;
4622 log_assert(repinfo && repinfo->c);
4624 buffer = repinfo->c->dnscrypt_buffer;
4625 if(!dnsc_handle_uncurved_request(repinfo)) {
4629 buffer = repinfo->c->buffer;
4631 if(repinfo->c->type == comm_udp) {
4632 if(repinfo->srctype)
4633 comm_point_send_udp_msg_if(repinfo->c, buffer,
4634 (struct sockaddr*)&repinfo->remote_addr,
4635 repinfo->remote_addrlen, repinfo);
4637 comm_point_send_udp_msg(repinfo->c, buffer,
4638 (struct sockaddr*)&repinfo->remote_addr,
4639 repinfo->remote_addrlen, 0);
4642 * sending src (client)/dst (local service) addresses over DNSTAP from udp callback
4644 if(repinfo->c->dtenv != NULL && repinfo->c->dtenv->log_client_response_messages) {
4645 log_addr(VERB_ALGO, "from local addr", (void*)repinfo->c->socket->addr->ai_addr, repinfo->c->socket->addr->ai_addrlen);
4646 log_addr(VERB_ALGO, "response to client", &repinfo->client_addr, repinfo->client_addrlen);
4647 dt_msg_send_client_response(repinfo->c->dtenv, &repinfo->client_addr, (void*)repinfo->c->socket->addr->ai_addr, repinfo->c->type, repinfo->c->buffer);
4653 * sending src (client)/dst (local service) addresses over DNSTAP from TCP callback
4655 if(repinfo->c->tcp_parent->dtenv != NULL && repinfo->c->tcp_parent->dtenv->log_client_response_messages) {
4656 log_addr(VERB_ALGO, "from local addr", (void*)repinfo->c->socket->addr->ai_addr, repinfo->c->socket->addr->ai_addrlen);
4657 log_addr(VERB_ALGO, "response to client", &repinfo->client_addr, repinfo->client_addrlen);
4658 dt_msg_send_client_response(repinfo->c->tcp_parent->dtenv, &repinfo->client_addr, (void*)repinfo->c->socket->addr->ai_addr, repinfo->c->type,
4659 ( repinfo->c->tcp_req_info? repinfo->c->tcp_req_info->spool_buffer: repinfo->c->buffer ));
4662 if(repinfo->c->tcp_req_info) {
4663 tcp_req_info_send_reply(repinfo->c->tcp_req_info);
4664 } else if(repinfo->c->use_h2) {
4665 if(!http2_submit_dns_response(repinfo->c->h2_session)) {
4666 comm_point_drop_reply(repinfo);
4669 repinfo->c->h2_stream = NULL;
4670 repinfo->c->tcp_is_reading = 0;
4671 comm_point_stop_listening(repinfo->c);
4672 comm_point_start_listening(repinfo->c, -1,
4673 adjusted_tcp_timeout(repinfo->c));
4676 comm_point_start_listening(repinfo->c, -1,
4677 adjusted_tcp_timeout(repinfo->c));
4683 comm_point_drop_reply(struct comm_reply* repinfo)
4687 log_assert(repinfo->c);
4688 log_assert(repinfo->c->type != comm_tcp_accept);
4689 if(repinfo->c->type == comm_udp)
4691 if(repinfo->c->tcp_req_info)
4692 repinfo->c->tcp_req_info->is_drop = 1;
4693 if(repinfo->c->type == comm_http) {
4694 if(repinfo->c->h2_session) {
4695 repinfo->c->h2_session->is_drop = 1;
4696 if(!repinfo->c->h2_session->postpone_drop)
4697 reclaim_http_handler(repinfo->c);
4700 reclaim_http_handler(repinfo->c);
4703 reclaim_tcp_handler(repinfo->c);
4707 comm_point_stop_listening(struct comm_point* c)
4709 verbose(VERB_ALGO, "comm point stop listening %d", c->fd);
4710 if(c->event_added) {
4711 if(ub_event_del(c->ev->ev) != 0) {
4712 log_err("event_del error to stoplisten");
4719 comm_point_start_listening(struct comm_point* c, int newfd, int msec)
4721 verbose(VERB_ALGO, "comm point start listening %d (%d msec)",
4722 c->fd==-1?newfd:c->fd, msec);
4723 if(c->type == comm_tcp_accept && !c->tcp_free) {
4724 /* no use to start listening no free slots. */
4727 if(c->event_added) {
4728 if(ub_event_del(c->ev->ev) != 0) {
4729 log_err("event_del error to startlisten");
4733 if(msec != -1 && msec != 0) {
4735 c->timeout = (struct timeval*)malloc(sizeof(
4738 log_err("cpsl: malloc failed. No net read.");
4742 ub_event_add_bits(c->ev->ev, UB_EV_TIMEOUT);
4743 #ifndef S_SPLINT_S /* splint fails on struct timeval. */
4744 c->timeout->tv_sec = msec/1000;
4745 c->timeout->tv_usec = (msec%1000)*1000;
4746 #endif /* S_SPLINT_S */
4748 if(msec == 0 || !c->timeout) {
4749 ub_event_del_bits(c->ev->ev, UB_EV_TIMEOUT);
4752 if(c->type == comm_tcp || c->type == comm_http) {
4753 ub_event_del_bits(c->ev->ev, UB_EV_READ|UB_EV_WRITE);
4754 if(c->tcp_write_and_read) {
4755 verbose(5, "startlistening %d mode rw", (newfd==-1?c->fd:newfd));
4756 ub_event_add_bits(c->ev->ev, UB_EV_READ|UB_EV_WRITE);
4757 } else if(c->tcp_is_reading) {
4758 verbose(5, "startlistening %d mode r", (newfd==-1?c->fd:newfd));
4759 ub_event_add_bits(c->ev->ev, UB_EV_READ);
4761 verbose(5, "startlistening %d mode w", (newfd==-1?c->fd:newfd));
4762 ub_event_add_bits(c->ev->ev, UB_EV_WRITE);
4766 if(c->fd != -1 && c->fd != newfd) {
4767 verbose(5, "cpsl close of fd %d for %d", c->fd, newfd);
4771 ub_event_set_fd(c->ev->ev, c->fd);
4773 if(ub_event_add(c->ev->ev, msec==0?NULL:c->timeout) != 0) {
4774 log_err("event_add failed. in cpsl.");
4780 void comm_point_listen_for_rw(struct comm_point* c, int rd, int wr)
4782 verbose(VERB_ALGO, "comm point listen_for_rw %d %d", c->fd, wr);
4783 if(c->event_added) {
4784 if(ub_event_del(c->ev->ev) != 0) {
4785 log_err("event_del error to cplf");
4790 ub_event_del_bits(c->ev->ev, UB_EV_TIMEOUT);
4792 ub_event_del_bits(c->ev->ev, UB_EV_READ|UB_EV_WRITE);
4793 if(rd) ub_event_add_bits(c->ev->ev, UB_EV_READ);
4794 if(wr) ub_event_add_bits(c->ev->ev, UB_EV_WRITE);
4795 if(ub_event_add(c->ev->ev, c->timeout) != 0) {
4796 log_err("event_add failed. in cplf.");
4802 size_t comm_point_get_mem(struct comm_point* c)
4807 s = sizeof(*c) + sizeof(*c->ev);
4809 s += sizeof(*c->timeout);
4810 if(c->type == comm_tcp || c->type == comm_local) {
4811 s += sizeof(*c->buffer) + sldns_buffer_capacity(c->buffer);
4813 s += sizeof(*c->dnscrypt_buffer);
4814 if(c->buffer != c->dnscrypt_buffer) {
4815 s += sldns_buffer_capacity(c->dnscrypt_buffer);
4819 if(c->type == comm_tcp_accept) {
4821 for(i=0; i<c->max_tcp_count; i++)
4822 s += comm_point_get_mem(c->tcp_handlers[i]);
4828 comm_timer_create(struct comm_base* base, void (*cb)(void*), void* cb_arg)
4830 struct internal_timer *tm = (struct internal_timer*)calloc(1,
4831 sizeof(struct internal_timer));
4833 log_err("malloc failed");
4836 tm->super.ev_timer = tm;
4838 tm->super.callback = cb;
4839 tm->super.cb_arg = cb_arg;
4840 tm->ev = ub_event_new(base->eb->base, -1, UB_EV_TIMEOUT,
4841 comm_timer_callback, &tm->super);
4842 if(tm->ev == NULL) {
4843 log_err("timer_create: event_base_set failed.");
4851 comm_timer_disable(struct comm_timer* timer)
4855 ub_timer_del(timer->ev_timer->ev);
4856 timer->ev_timer->enabled = 0;
4860 comm_timer_set(struct comm_timer* timer, struct timeval* tv)
4863 if(timer->ev_timer->enabled)
4864 comm_timer_disable(timer);
4865 if(ub_timer_add(timer->ev_timer->ev, timer->ev_timer->base->eb->base,
4866 comm_timer_callback, timer, tv) != 0)
4867 log_err("comm_timer_set: evtimer_add failed.");
4868 timer->ev_timer->enabled = 1;
4872 comm_timer_delete(struct comm_timer* timer)
4876 comm_timer_disable(timer);
4877 /* Free the sub struct timer->ev_timer derived from the super struct timer.
4878 * i.e. assert(timer == timer->ev_timer)
4880 ub_event_free(timer->ev_timer->ev);
4881 free(timer->ev_timer);
4885 comm_timer_callback(int ATTR_UNUSED(fd), short event, void* arg)
4887 struct comm_timer* tm = (struct comm_timer*)arg;
4888 if(!(event&UB_EV_TIMEOUT))
4890 ub_comm_base_now(tm->ev_timer->base);
4891 tm->ev_timer->enabled = 0;
4892 fptr_ok(fptr_whitelist_comm_timer(tm->callback));
4893 (*tm->callback)(tm->cb_arg);
4897 comm_timer_is_set(struct comm_timer* timer)
4899 return (int)timer->ev_timer->enabled;
4903 comm_timer_get_mem(struct comm_timer* ATTR_UNUSED(timer))
4905 return sizeof(struct internal_timer);
4909 comm_signal_create(struct comm_base* base,
4910 void (*callback)(int, void*), void* cb_arg)
4912 struct comm_signal* com = (struct comm_signal*)malloc(
4913 sizeof(struct comm_signal));
4915 log_err("malloc failed");
4919 com->callback = callback;
4920 com->cb_arg = cb_arg;
4921 com->ev_signal = NULL;
4926 comm_signal_callback(int sig, short event, void* arg)
4928 struct comm_signal* comsig = (struct comm_signal*)arg;
4929 if(!(event & UB_EV_SIGNAL))
4931 ub_comm_base_now(comsig->base);
4932 fptr_ok(fptr_whitelist_comm_signal(comsig->callback));
4933 (*comsig->callback)(sig, comsig->cb_arg);
4937 comm_signal_bind(struct comm_signal* comsig, int sig)
4939 struct internal_signal* entry = (struct internal_signal*)calloc(1,
4940 sizeof(struct internal_signal));
4942 log_err("malloc failed");
4946 /* add signal event */
4947 entry->ev = ub_signal_new(comsig->base->eb->base, sig,
4948 comm_signal_callback, comsig);
4949 if(entry->ev == NULL) {
4950 log_err("Could not create signal event");
4954 if(ub_signal_add(entry->ev, NULL) != 0) {
4955 log_err("Could not add signal handler");
4956 ub_event_free(entry->ev);
4960 /* link into list */
4961 entry->next = comsig->ev_signal;
4962 comsig->ev_signal = entry;
4967 comm_signal_delete(struct comm_signal* comsig)
4969 struct internal_signal* p, *np;
4972 p=comsig->ev_signal;
4975 ub_signal_del(p->ev);
4976 ub_event_free(p->ev);