2 * util/netevent.c - event notification
4 * Copyright (c) 2007, NLnet Labs. All rights reserved.
6 * This software is open source.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
15 * Redistributions in binary form must reproduce the above copyright notice,
16 * this list of conditions and the following disclaimer in the documentation
17 * and/or other materials provided with the distribution.
19 * Neither the name of the NLNET LABS nor the names of its contributors may
20 * be used to endorse or promote products derived from this software without
21 * specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 * This file contains event notification functions.
42 #include "util/netevent.h"
43 #include "util/ub_event.h"
45 #include "util/net_help.h"
46 #include "util/tcp_conn_limit.h"
47 #include "util/fptr_wlist.h"
48 #include "sldns/pkthdr.h"
49 #include "sldns/sbuffer.h"
50 #include "sldns/str2wire.h"
51 #include "dnstap/dnstap.h"
52 #include "dnscrypt/dnscrypt.h"
53 #include "services/listen_dnsport.h"
54 #ifdef HAVE_OPENSSL_SSL_H
55 #include <openssl/ssl.h>
57 #ifdef HAVE_OPENSSL_ERR_H
58 #include <openssl/err.h>
61 /* -------- Start of local definitions -------- */
62 /** if CMSG_ALIGN is not defined on this platform, a workaround */
65 # define CMSG_ALIGN(n) __CMSG_ALIGN(n)
66 # elif defined(CMSG_DATA_ALIGN)
67 # define CMSG_ALIGN _CMSG_DATA_ALIGN
69 # define CMSG_ALIGN(len) (((len)+sizeof(long)-1) & ~(sizeof(long)-1))
73 /** if CMSG_LEN is not defined on this platform, a workaround */
75 # define CMSG_LEN(len) (CMSG_ALIGN(sizeof(struct cmsghdr))+(len))
78 /** if CMSG_SPACE is not defined on this platform, a workaround */
80 # ifdef _CMSG_HDR_ALIGN
81 # define CMSG_SPACE(l) (CMSG_ALIGN(l)+_CMSG_HDR_ALIGN(sizeof(struct cmsghdr)))
83 # define CMSG_SPACE(l) (CMSG_ALIGN(l)+CMSG_ALIGN(sizeof(struct cmsghdr)))
87 /** The TCP writing query timeout in milliseconds */
88 #define TCP_QUERY_TIMEOUT 120000
89 /** The minimum actual TCP timeout to use, regardless of what we advertise,
91 #define TCP_QUERY_TIMEOUT_MINIMUM 200
93 #ifndef NONBLOCKING_IS_BROKEN
94 /** number of UDP reads to perform per read indication from select */
95 #define NUM_UDP_PER_SELECT 100
97 #define NUM_UDP_PER_SELECT 1
101 * The internal event structure for keeping ub_event info for the event.
102 * Possibly other structures (list, tree) this is part of.
104 struct internal_event {
106 struct comm_base* base;
107 /** ub_event event type */
112 * Internal base structure, so that every thread has its own events.
114 struct internal_base {
115 /** ub_event event_base type. */
116 struct ub_event_base* base;
117 /** seconds time pointer points here */
119 /** timeval with current time */
121 /** the event used for slow_accept timeouts */
122 struct ub_event* slow_accept;
123 /** true if slow_accept is enabled */
124 int slow_accept_enabled;
128 * Internal timer structure, to store timer event in.
130 struct internal_timer {
131 /** the super struct from which derived */
132 struct comm_timer super;
134 struct comm_base* base;
135 /** ub_event event type */
137 /** is timer enabled */
142 * Internal signal structure, to store signal event in.
144 struct internal_signal {
145 /** ub_event event type */
147 /** next in signal list */
148 struct internal_signal* next;
151 /** create a tcp handler with a parent */
152 static struct comm_point* comm_point_create_tcp_handler(
153 struct comm_base *base, struct comm_point* parent, size_t bufsize,
154 struct sldns_buffer* spoolbuf, comm_point_callback_type* callback,
157 /* -------- End of local definitions -------- */
160 comm_base_create(int sigs)
162 struct comm_base* b = (struct comm_base*)calloc(1,
163 sizeof(struct comm_base));
164 const char *evnm="event", *evsys="", *evmethod="";
168 b->eb = (struct internal_base*)calloc(1, sizeof(struct internal_base));
173 b->eb->base = ub_default_event_base(sigs, &b->eb->secs, &b->eb->now);
180 ub_get_event_sys(b->eb->base, &evnm, &evsys, &evmethod);
181 verbose(VERB_ALGO, "%s %s user %s method.", evnm, evsys, evmethod);
186 comm_base_create_event(struct ub_event_base* base)
188 struct comm_base* b = (struct comm_base*)calloc(1,
189 sizeof(struct comm_base));
192 b->eb = (struct internal_base*)calloc(1, sizeof(struct internal_base));
203 comm_base_delete(struct comm_base* b)
207 if(b->eb->slow_accept_enabled) {
208 if(ub_event_del(b->eb->slow_accept) != 0) {
209 log_err("could not event_del slow_accept");
211 ub_event_free(b->eb->slow_accept);
213 ub_event_base_free(b->eb->base);
220 comm_base_delete_no_base(struct comm_base* b)
224 if(b->eb->slow_accept_enabled) {
225 if(ub_event_del(b->eb->slow_accept) != 0) {
226 log_err("could not event_del slow_accept");
228 ub_event_free(b->eb->slow_accept);
236 comm_base_timept(struct comm_base* b, time_t** tt, struct timeval** tv)
243 comm_base_dispatch(struct comm_base* b)
246 retval = ub_event_base_dispatch(b->eb->base);
248 fatal_exit("event_dispatch returned error %d, "
249 "errno is %s", retval, strerror(errno));
253 void comm_base_exit(struct comm_base* b)
255 if(ub_event_base_loopexit(b->eb->base) != 0) {
256 log_err("Could not loopexit");
260 void comm_base_set_slow_accept_handlers(struct comm_base* b,
261 void (*stop_acc)(void*), void (*start_acc)(void*), void* arg)
263 b->stop_accept = stop_acc;
264 b->start_accept = start_acc;
268 struct ub_event_base* comm_base_internal(struct comm_base* b)
273 /** see if errno for udp has to be logged or not uses globals */
275 udp_send_errno_needs_log(struct sockaddr* addr, socklen_t addrlen)
277 /* do not log transient errors (unless high verbosity) */
278 #if defined(ENETUNREACH) || defined(EHOSTDOWN) || defined(EHOSTUNREACH) || defined(ENETDOWN)
292 if(verbosity < VERB_ALGO)
298 /* permission denied is gotten for every send if the
299 * network is disconnected (on some OS), squelch it */
300 if( ((errno == EPERM)
301 # ifdef EADDRNOTAVAIL
302 /* 'Cannot assign requested address' also when disconnected */
303 || (errno == EADDRNOTAVAIL)
305 ) && verbosity < VERB_DETAIL)
308 /* If SO_REUSEADDR is set, we could try to connect to the same server
309 * from the same source port twice. */
310 if(errno == EADDRINUSE && verbosity < VERB_DETAIL)
313 /* squelch errors where people deploy AAAA ::ffff:bla for
314 * authority servers, which we try for intranets. */
315 if(errno == EINVAL && addr_is_ip4mapped(
316 (struct sockaddr_storage*)addr, addrlen) &&
317 verbosity < VERB_DETAIL)
319 /* SO_BROADCAST sockopt can give access to 255.255.255.255,
320 * but a dns cache does not need it. */
321 if(errno == EACCES && addr_is_broadcast(
322 (struct sockaddr_storage*)addr, addrlen) &&
323 verbosity < VERB_DETAIL)
328 int tcp_connect_errno_needs_log(struct sockaddr* addr, socklen_t addrlen)
330 return udp_send_errno_needs_log(addr, addrlen);
333 /* send a UDP reply */
335 comm_point_send_udp_msg(struct comm_point *c, sldns_buffer* packet,
336 struct sockaddr* addr, socklen_t addrlen)
339 log_assert(c->fd != -1);
341 if(sldns_buffer_remaining(packet) == 0)
342 log_err("error: send empty UDP packet");
344 log_assert(addr && addrlen > 0);
345 sent = sendto(c->fd, (void*)sldns_buffer_begin(packet),
346 sldns_buffer_remaining(packet), 0,
349 /* try again and block, waiting for IO to complete,
350 * we want to send the answer, and we will wait for
351 * the ethernet interface buffer to have space. */
353 if(errno == EAGAIN ||
355 errno == EWOULDBLOCK ||
359 if(WSAGetLastError() == WSAEINPROGRESS ||
360 WSAGetLastError() == WSAENOBUFS ||
361 WSAGetLastError() == WSAEWOULDBLOCK) {
365 sent = sendto(c->fd, (void*)sldns_buffer_begin(packet),
366 sldns_buffer_remaining(packet), 0,
369 fd_set_nonblock(c->fd);
374 if(!udp_send_errno_needs_log(addr, addrlen))
377 verbose(VERB_OPS, "sendto failed: %s", strerror(errno));
379 verbose(VERB_OPS, "sendto failed: %s",
380 wsa_strerror(WSAGetLastError()));
382 log_addr(VERB_OPS, "remote address is",
383 (struct sockaddr_storage*)addr, addrlen);
385 } else if((size_t)sent != sldns_buffer_remaining(packet)) {
386 log_err("sent %d in place of %d bytes",
387 (int)sent, (int)sldns_buffer_remaining(packet));
393 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && (defined(HAVE_RECVMSG) || defined(HAVE_SENDMSG))
394 /** print debug ancillary info */
395 static void p_ancil(const char* str, struct comm_reply* r)
397 if(r->srctype != 4 && r->srctype != 6) {
398 log_info("%s: unknown srctype %d", str, r->srctype);
401 if(r->srctype == 6) {
403 if(inet_ntop(AF_INET6, &r->pktinfo.v6info.ipi6_addr,
404 buf, (socklen_t)sizeof(buf)) == 0) {
405 (void)strlcpy(buf, "(inet_ntop error)", sizeof(buf));
407 buf[sizeof(buf)-1]=0;
408 log_info("%s: %s %d", str, buf, r->pktinfo.v6info.ipi6_ifindex);
409 } else if(r->srctype == 4) {
411 char buf1[1024], buf2[1024];
412 if(inet_ntop(AF_INET, &r->pktinfo.v4info.ipi_addr,
413 buf1, (socklen_t)sizeof(buf1)) == 0) {
414 (void)strlcpy(buf1, "(inet_ntop error)", sizeof(buf1));
416 buf1[sizeof(buf1)-1]=0;
417 #ifdef HAVE_STRUCT_IN_PKTINFO_IPI_SPEC_DST
418 if(inet_ntop(AF_INET, &r->pktinfo.v4info.ipi_spec_dst,
419 buf2, (socklen_t)sizeof(buf2)) == 0) {
420 (void)strlcpy(buf2, "(inet_ntop error)", sizeof(buf2));
422 buf2[sizeof(buf2)-1]=0;
426 log_info("%s: %d %s %s", str, r->pktinfo.v4info.ipi_ifindex,
428 #elif defined(IP_RECVDSTADDR)
430 if(inet_ntop(AF_INET, &r->pktinfo.v4addr,
431 buf1, (socklen_t)sizeof(buf1)) == 0) {
432 (void)strlcpy(buf1, "(inet_ntop error)", sizeof(buf1));
434 buf1[sizeof(buf1)-1]=0;
435 log_info("%s: %s", str, buf1);
436 #endif /* IP_PKTINFO or PI_RECVDSTDADDR */
439 #endif /* AF_INET6 && IPV6_PKTINFO && HAVE_RECVMSG||HAVE_SENDMSG */
441 /** send a UDP reply over specified interface*/
443 comm_point_send_udp_msg_if(struct comm_point *c, sldns_buffer* packet,
444 struct sockaddr* addr, socklen_t addrlen, struct comm_reply* r)
446 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && defined(HAVE_SENDMSG)
452 struct cmsghdr *cmsg;
453 #endif /* S_SPLINT_S */
455 log_assert(c->fd != -1);
457 if(sldns_buffer_remaining(packet) == 0)
458 log_err("error: send empty UDP packet");
460 log_assert(addr && addrlen > 0);
463 msg.msg_namelen = addrlen;
464 iov[0].iov_base = sldns_buffer_begin(packet);
465 iov[0].iov_len = sldns_buffer_remaining(packet);
468 msg.msg_control = control;
470 msg.msg_controllen = sizeof(control);
471 #endif /* S_SPLINT_S */
475 cmsg = CMSG_FIRSTHDR(&msg);
476 if(r->srctype == 4) {
479 msg.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
480 log_assert(msg.msg_controllen <= sizeof(control));
481 cmsg->cmsg_level = IPPROTO_IP;
482 cmsg->cmsg_type = IP_PKTINFO;
483 memmove(CMSG_DATA(cmsg), &r->pktinfo.v4info,
484 sizeof(struct in_pktinfo));
485 /* unset the ifindex to not bypass the routing tables */
486 cmsg_data = CMSG_DATA(cmsg);
487 ((struct in_pktinfo *) cmsg_data)->ipi_ifindex = 0;
488 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
489 #elif defined(IP_SENDSRCADDR)
490 msg.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
491 log_assert(msg.msg_controllen <= sizeof(control));
492 cmsg->cmsg_level = IPPROTO_IP;
493 cmsg->cmsg_type = IP_SENDSRCADDR;
494 memmove(CMSG_DATA(cmsg), &r->pktinfo.v4addr,
495 sizeof(struct in_addr));
496 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
498 verbose(VERB_ALGO, "no IP_PKTINFO or IP_SENDSRCADDR");
499 msg.msg_control = NULL;
500 #endif /* IP_PKTINFO or IP_SENDSRCADDR */
501 } else if(r->srctype == 6) {
503 msg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
504 log_assert(msg.msg_controllen <= sizeof(control));
505 cmsg->cmsg_level = IPPROTO_IPV6;
506 cmsg->cmsg_type = IPV6_PKTINFO;
507 memmove(CMSG_DATA(cmsg), &r->pktinfo.v6info,
508 sizeof(struct in6_pktinfo));
509 /* unset the ifindex to not bypass the routing tables */
510 cmsg_data = CMSG_DATA(cmsg);
511 ((struct in6_pktinfo *) cmsg_data)->ipi6_ifindex = 0;
512 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
514 /* try to pass all 0 to use default route */
515 msg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
516 log_assert(msg.msg_controllen <= sizeof(control));
517 cmsg->cmsg_level = IPPROTO_IPV6;
518 cmsg->cmsg_type = IPV6_PKTINFO;
519 memset(CMSG_DATA(cmsg), 0, sizeof(struct in6_pktinfo));
520 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
522 #endif /* S_SPLINT_S */
523 if(verbosity >= VERB_ALGO)
524 p_ancil("send_udp over interface", r);
525 sent = sendmsg(c->fd, &msg, 0);
527 /* try again and block, waiting for IO to complete,
528 * we want to send the answer, and we will wait for
529 * the ethernet interface buffer to have space. */
531 if(errno == EAGAIN ||
533 errno == EWOULDBLOCK ||
537 if(WSAGetLastError() == WSAEINPROGRESS ||
538 WSAGetLastError() == WSAENOBUFS ||
539 WSAGetLastError() == WSAEWOULDBLOCK) {
543 sent = sendmsg(c->fd, &msg, 0);
545 fd_set_nonblock(c->fd);
550 if(!udp_send_errno_needs_log(addr, addrlen))
552 verbose(VERB_OPS, "sendmsg failed: %s", strerror(errno));
553 log_addr(VERB_OPS, "remote address is",
554 (struct sockaddr_storage*)addr, addrlen);
556 /* netbsd 7 has IP_PKTINFO for recv but not send */
557 if(errno == EINVAL && r->srctype == 4)
558 log_err("sendmsg: No support for sendmsg(IP_PKTINFO). "
559 "Please disable interface-automatic");
562 } else if((size_t)sent != sldns_buffer_remaining(packet)) {
563 log_err("sent %d in place of %d bytes",
564 (int)sent, (int)sldns_buffer_remaining(packet));
574 log_err("sendmsg: IPV6_PKTINFO not supported");
576 #endif /* AF_INET6 && IPV6_PKTINFO && HAVE_SENDMSG */
580 comm_point_udp_ancil_callback(int fd, short event, void* arg)
582 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && defined(HAVE_RECVMSG)
583 struct comm_reply rep;
590 struct cmsghdr* cmsg;
591 #endif /* S_SPLINT_S */
593 rep.c = (struct comm_point*)arg;
594 log_assert(rep.c->type == comm_udp);
596 if(!(event&UB_EV_READ))
598 log_assert(rep.c && rep.c->buffer && rep.c->fd == fd);
599 ub_comm_base_now(rep.c->ev->base);
600 for(i=0; i<NUM_UDP_PER_SELECT; i++) {
601 sldns_buffer_clear(rep.c->buffer);
602 rep.addrlen = (socklen_t)sizeof(rep.addr);
603 log_assert(fd != -1);
604 log_assert(sldns_buffer_remaining(rep.c->buffer) > 0);
605 msg.msg_name = &rep.addr;
606 msg.msg_namelen = (socklen_t)sizeof(rep.addr);
607 iov[0].iov_base = sldns_buffer_begin(rep.c->buffer);
608 iov[0].iov_len = sldns_buffer_remaining(rep.c->buffer);
611 msg.msg_control = ancil;
613 msg.msg_controllen = sizeof(ancil);
614 #endif /* S_SPLINT_S */
616 rcv = recvmsg(fd, &msg, 0);
618 if(errno != EAGAIN && errno != EINTR) {
619 log_err("recvmsg failed: %s", strerror(errno));
623 rep.addrlen = msg.msg_namelen;
624 sldns_buffer_skip(rep.c->buffer, rcv);
625 sldns_buffer_flip(rep.c->buffer);
628 for(cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
629 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
630 if( cmsg->cmsg_level == IPPROTO_IPV6 &&
631 cmsg->cmsg_type == IPV6_PKTINFO) {
633 memmove(&rep.pktinfo.v6info, CMSG_DATA(cmsg),
634 sizeof(struct in6_pktinfo));
637 } else if( cmsg->cmsg_level == IPPROTO_IP &&
638 cmsg->cmsg_type == IP_PKTINFO) {
640 memmove(&rep.pktinfo.v4info, CMSG_DATA(cmsg),
641 sizeof(struct in_pktinfo));
643 #elif defined(IP_RECVDSTADDR)
644 } else if( cmsg->cmsg_level == IPPROTO_IP &&
645 cmsg->cmsg_type == IP_RECVDSTADDR) {
647 memmove(&rep.pktinfo.v4addr, CMSG_DATA(cmsg),
648 sizeof(struct in_addr));
650 #endif /* IP_PKTINFO or IP_RECVDSTADDR */
653 if(verbosity >= VERB_ALGO)
654 p_ancil("receive_udp on interface", &rep);
655 #endif /* S_SPLINT_S */
656 fptr_ok(fptr_whitelist_comm_point(rep.c->callback));
657 if((*rep.c->callback)(rep.c, rep.c->cb_arg, NETEVENT_NOERROR, &rep)) {
658 /* send back immediate reply */
659 (void)comm_point_send_udp_msg_if(rep.c, rep.c->buffer,
660 (struct sockaddr*)&rep.addr, rep.addrlen, &rep);
662 if(!rep.c || rep.c->fd == -1) /* commpoint closed */
669 fatal_exit("recvmsg: No support for IPV6_PKTINFO; IP_PKTINFO or IP_RECVDSTADDR. "
670 "Please disable interface-automatic");
671 #endif /* AF_INET6 && IPV6_PKTINFO && HAVE_RECVMSG */
675 comm_point_udp_callback(int fd, short event, void* arg)
677 struct comm_reply rep;
680 struct sldns_buffer *buffer;
682 rep.c = (struct comm_point*)arg;
683 log_assert(rep.c->type == comm_udp);
685 if(!(event&UB_EV_READ))
687 log_assert(rep.c && rep.c->buffer && rep.c->fd == fd);
688 ub_comm_base_now(rep.c->ev->base);
689 for(i=0; i<NUM_UDP_PER_SELECT; i++) {
690 sldns_buffer_clear(rep.c->buffer);
691 rep.addrlen = (socklen_t)sizeof(rep.addr);
692 log_assert(fd != -1);
693 log_assert(sldns_buffer_remaining(rep.c->buffer) > 0);
694 rcv = recvfrom(fd, (void*)sldns_buffer_begin(rep.c->buffer),
695 sldns_buffer_remaining(rep.c->buffer), 0,
696 (struct sockaddr*)&rep.addr, &rep.addrlen);
699 if(errno != EAGAIN && errno != EINTR)
700 log_err("recvfrom %d failed: %s",
701 fd, strerror(errno));
703 if(WSAGetLastError() != WSAEINPROGRESS &&
704 WSAGetLastError() != WSAECONNRESET &&
705 WSAGetLastError()!= WSAEWOULDBLOCK)
706 log_err("recvfrom failed: %s",
707 wsa_strerror(WSAGetLastError()));
711 sldns_buffer_skip(rep.c->buffer, rcv);
712 sldns_buffer_flip(rep.c->buffer);
714 fptr_ok(fptr_whitelist_comm_point(rep.c->callback));
715 if((*rep.c->callback)(rep.c, rep.c->cb_arg, NETEVENT_NOERROR, &rep)) {
716 /* send back immediate reply */
718 buffer = rep.c->dnscrypt_buffer;
720 buffer = rep.c->buffer;
722 (void)comm_point_send_udp_msg(rep.c, buffer,
723 (struct sockaddr*)&rep.addr, rep.addrlen);
725 if(!rep.c || rep.c->fd != fd) /* commpoint closed to -1 or reused for
726 another UDP port. Note rep.c cannot be reused with TCP fd. */
731 /** Use a new tcp handler for new query fd, set to read query */
733 setup_tcp_handler(struct comm_point* c, int fd, int cur, int max)
736 log_assert(c->type == comm_tcp);
737 log_assert(c->fd == -1);
738 sldns_buffer_clear(c->buffer);
741 sldns_buffer_clear(c->dnscrypt_buffer);
743 c->tcp_is_reading = 1;
744 c->tcp_byte_count = 0;
745 /* if more than half the tcp handlers are in use, use a shorter
746 * timeout for this TCP connection, we need to make space for
747 * other connections to be able to get attention */
748 /* If > 50% TCP handler structures in use, set timeout to 1/100th
750 * If > 65%TCP handler structures in use, set to 1/500th configured
752 * If > 80% TCP handler structures in use, set to 0.
754 * If the timeout to use falls below 200 milliseconds, an actual
755 * timeout of 200ms is used.
757 handler_usage = (cur * 100) / max;
758 if(handler_usage > 50 && handler_usage <= 65)
759 c->tcp_timeout_msec /= 100;
760 else if (handler_usage > 65 && handler_usage <= 80)
761 c->tcp_timeout_msec /= 500;
762 else if (handler_usage > 80)
763 c->tcp_timeout_msec = 0;
764 comm_point_start_listening(c, fd,
765 c->tcp_timeout_msec < TCP_QUERY_TIMEOUT_MINIMUM
766 ? TCP_QUERY_TIMEOUT_MINIMUM
767 : c->tcp_timeout_msec);
770 void comm_base_handle_slow_accept(int ATTR_UNUSED(fd),
771 short ATTR_UNUSED(event), void* arg)
773 struct comm_base* b = (struct comm_base*)arg;
774 /* timeout for the slow accept, re-enable accepts again */
775 if(b->start_accept) {
776 verbose(VERB_ALGO, "wait is over, slow accept disabled");
777 fptr_ok(fptr_whitelist_start_accept(b->start_accept));
778 (*b->start_accept)(b->cb_arg);
779 b->eb->slow_accept_enabled = 0;
783 int comm_point_perform_accept(struct comm_point* c,
784 struct sockaddr_storage* addr, socklen_t* addrlen)
787 *addrlen = (socklen_t)sizeof(*addr);
789 new_fd = accept(c->fd, (struct sockaddr*)addr, addrlen);
791 /* SOCK_NONBLOCK saves extra calls to fcntl for the same result */
792 new_fd = accept4(c->fd, (struct sockaddr*)addr, addrlen, SOCK_NONBLOCK);
796 /* EINTR is signal interrupt. others are closed connection. */
797 if( errno == EINTR || errno == EAGAIN
799 || errno == EWOULDBLOCK
802 || errno == ECONNABORTED
809 #if defined(ENFILE) && defined(EMFILE)
810 if(errno == ENFILE || errno == EMFILE) {
811 /* out of file descriptors, likely outside of our
812 * control. stop accept() calls for some time */
813 if(c->ev->base->stop_accept) {
814 struct comm_base* b = c->ev->base;
816 verbose(VERB_ALGO, "out of file descriptors: "
818 b->eb->slow_accept_enabled = 1;
819 fptr_ok(fptr_whitelist_stop_accept(
821 (*b->stop_accept)(b->cb_arg);
822 /* set timeout, no mallocs */
823 tv.tv_sec = NETEVENT_SLOW_ACCEPT_TIME/1000;
824 tv.tv_usec = (NETEVENT_SLOW_ACCEPT_TIME%1000)*1000;
825 b->eb->slow_accept = ub_event_new(b->eb->base,
827 comm_base_handle_slow_accept, b);
828 if(b->eb->slow_accept == NULL) {
829 /* we do not want to log here, because
830 * that would spam the logfiles.
831 * error: "event_base_set failed." */
833 else if(ub_event_add(b->eb->slow_accept, &tv)
835 /* we do not want to log here,
836 * error: "event_add failed." */
842 log_err_addr("accept failed", strerror(errno), addr, *addrlen);
843 #else /* USE_WINSOCK */
844 if(WSAGetLastError() == WSAEINPROGRESS ||
845 WSAGetLastError() == WSAECONNRESET)
847 if(WSAGetLastError() == WSAEWOULDBLOCK) {
848 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
851 log_err_addr("accept failed", wsa_strerror(WSAGetLastError()),
856 if(c->tcp_conn_limit && c->type == comm_tcp_accept) {
857 c->tcl_addr = tcl_addr_lookup(c->tcp_conn_limit, addr, *addrlen);
858 if(!tcl_new_connection(c->tcl_addr)) {
860 log_err_addr("accept rejected",
861 "connection limit exceeded", addr, *addrlen);
867 fd_set_nonblock(new_fd);
873 static long win_bio_cb(BIO *b, int oper, const char* ATTR_UNUSED(argp),
874 int ATTR_UNUSED(argi), long argl, long retvalue)
876 int wsa_err = WSAGetLastError(); /* store errcode before it is gone */
877 verbose(VERB_ALGO, "bio_cb %d, %s %s %s", oper,
878 (oper&BIO_CB_RETURN)?"return":"before",
879 (oper&BIO_CB_READ)?"read":((oper&BIO_CB_WRITE)?"write":"other"),
880 wsa_err==WSAEWOULDBLOCK?"wsawb":"");
881 /* on windows, check if previous operation caused EWOULDBLOCK */
882 if( (oper == (BIO_CB_READ|BIO_CB_RETURN) && argl == 0) ||
883 (oper == (BIO_CB_GETS|BIO_CB_RETURN) && argl == 0)) {
884 if(wsa_err == WSAEWOULDBLOCK)
885 ub_winsock_tcp_wouldblock((struct ub_event*)
886 BIO_get_callback_arg(b), UB_EV_READ);
888 if( (oper == (BIO_CB_WRITE|BIO_CB_RETURN) && argl == 0) ||
889 (oper == (BIO_CB_PUTS|BIO_CB_RETURN) && argl == 0)) {
890 if(wsa_err == WSAEWOULDBLOCK)
891 ub_winsock_tcp_wouldblock((struct ub_event*)
892 BIO_get_callback_arg(b), UB_EV_WRITE);
894 /* return original return value */
898 /** set win bio callbacks for nonblocking operations */
900 comm_point_tcp_win_bio_cb(struct comm_point* c, void* thessl)
902 SSL* ssl = (SSL*)thessl;
903 /* set them both just in case, but usually they are the same BIO */
904 BIO_set_callback(SSL_get_rbio(ssl), &win_bio_cb);
905 BIO_set_callback_arg(SSL_get_rbio(ssl), (char*)c->ev->ev);
906 BIO_set_callback(SSL_get_wbio(ssl), &win_bio_cb);
907 BIO_set_callback_arg(SSL_get_wbio(ssl), (char*)c->ev->ev);
912 comm_point_tcp_accept_callback(int fd, short event, void* arg)
914 struct comm_point* c = (struct comm_point*)arg, *c_hdl;
916 log_assert(c->type == comm_tcp_accept);
917 if(!(event & UB_EV_READ)) {
918 log_info("ignoring tcp accept event %d", (int)event);
921 ub_comm_base_now(c->ev->base);
922 /* find free tcp handler. */
924 log_warn("accepted too many tcp, connections full");
927 /* accept incoming connection. */
929 log_assert(fd != -1);
931 new_fd = comm_point_perform_accept(c, &c_hdl->repinfo.addr,
932 &c_hdl->repinfo.addrlen);
936 c_hdl->ssl = incoming_ssl_fd(c->ssl, new_fd);
939 comm_point_close(c_hdl);
942 c_hdl->ssl_shake_state = comm_ssl_shake_read;
944 comm_point_tcp_win_bio_cb(c_hdl, c_hdl->ssl);
948 /* grab the tcp handler buffers */
950 c->tcp_free = c_hdl->tcp_free;
952 /* stop accepting incoming queries for now. */
953 comm_point_stop_listening(c);
955 setup_tcp_handler(c_hdl, new_fd, c->cur_tcp_count, c->max_tcp_count);
958 /** Make tcp handler free for next assignment */
960 reclaim_tcp_handler(struct comm_point* c)
962 log_assert(c->type == comm_tcp);
965 SSL_shutdown(c->ssl);
972 c->tcp_parent->cur_tcp_count--;
973 c->tcp_free = c->tcp_parent->tcp_free;
974 c->tcp_parent->tcp_free = c;
976 /* re-enable listening on accept socket */
977 comm_point_start_listening(c->tcp_parent, -1, -1);
982 /** do the callback when writing is done */
984 tcp_callback_writer(struct comm_point* c)
986 log_assert(c->type == comm_tcp);
987 sldns_buffer_clear(c->buffer);
988 if(c->tcp_do_toggle_rw)
989 c->tcp_is_reading = 1;
990 c->tcp_byte_count = 0;
991 /* switch from listening(write) to listening(read) */
992 comm_point_stop_listening(c);
993 if(c->tcp_req_info) {
994 tcp_req_info_handle_writedone(c->tcp_req_info);
996 comm_point_start_listening(c, -1, -1);
1000 /** do the callback when reading is done */
1002 tcp_callback_reader(struct comm_point* c)
1004 log_assert(c->type == comm_tcp || c->type == comm_local);
1005 sldns_buffer_flip(c->buffer);
1006 if(c->tcp_do_toggle_rw)
1007 c->tcp_is_reading = 0;
1008 c->tcp_byte_count = 0;
1009 if(c->type == comm_tcp)
1010 comm_point_stop_listening(c);
1011 if(c->tcp_req_info) {
1012 tcp_req_info_handle_readdone(c->tcp_req_info);
1014 fptr_ok(fptr_whitelist_comm_point(c->callback));
1015 if( (*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, &c->repinfo) ) {
1016 comm_point_start_listening(c, -1, c->tcp_timeout_msec);
1022 /** log certificate details */
1024 log_cert(unsigned level, const char* str, X509* cert)
1030 if(verbosity < level) return;
1031 bio = BIO_new(BIO_s_mem());
1033 X509_print_ex(bio, cert, 0, (unsigned long)-1
1034 ^(X509_FLAG_NO_SUBJECT
1035 |X509_FLAG_NO_ISSUER|X509_FLAG_NO_VALIDITY
1036 |X509_FLAG_NO_EXTENSIONS|X509_FLAG_NO_AUX
1037 |X509_FLAG_NO_ATTRIBUTES));
1038 BIO_write(bio, &nul, (int)sizeof(nul));
1039 len = BIO_get_mem_data(bio, &pp);
1040 if(len != 0 && pp) {
1041 verbose(level, "%s: \n%s", str, pp);
1045 #endif /* HAVE_SSL */
1047 /** continue ssl handshake */
1050 ssl_handshake(struct comm_point* c)
1053 if(c->ssl_shake_state == comm_ssl_shake_hs_read) {
1054 /* read condition satisfied back to writing */
1055 comm_point_listen_for_rw(c, 1, 1);
1056 c->ssl_shake_state = comm_ssl_shake_none;
1059 if(c->ssl_shake_state == comm_ssl_shake_hs_write) {
1060 /* write condition satisfied, back to reading */
1061 comm_point_listen_for_rw(c, 1, 0);
1062 c->ssl_shake_state = comm_ssl_shake_none;
1067 r = SSL_do_handshake(c->ssl);
1069 int want = SSL_get_error(c->ssl, r);
1070 if(want == SSL_ERROR_WANT_READ) {
1071 if(c->ssl_shake_state == comm_ssl_shake_read)
1073 c->ssl_shake_state = comm_ssl_shake_read;
1074 comm_point_listen_for_rw(c, 1, 0);
1076 } else if(want == SSL_ERROR_WANT_WRITE) {
1077 if(c->ssl_shake_state == comm_ssl_shake_write)
1079 c->ssl_shake_state = comm_ssl_shake_write;
1080 comm_point_listen_for_rw(c, 0, 1);
1083 return 0; /* closed */
1084 } else if(want == SSL_ERROR_SYSCALL) {
1085 /* SYSCALL and errno==0 means closed uncleanly */
1087 log_err("SSL_handshake syscall: %s",
1091 log_crypto_err("ssl handshake failed");
1092 log_addr(1, "ssl handshake failed", &c->repinfo.addr,
1093 c->repinfo.addrlen);
1097 /* this is where peer verification could take place */
1098 if((SSL_get_verify_mode(c->ssl)&SSL_VERIFY_PEER)) {
1100 if(SSL_get_verify_result(c->ssl) == X509_V_OK) {
1101 X509* x = SSL_get_peer_certificate(c->ssl);
1103 log_addr(VERB_ALGO, "SSL connection failed: "
1105 &c->repinfo.addr, c->repinfo.addrlen);
1108 log_cert(VERB_ALGO, "peer certificate", x);
1109 #ifdef HAVE_SSL_GET0_PEERNAME
1110 if(SSL_get0_peername(c->ssl)) {
1112 snprintf(buf, sizeof(buf), "SSL connection "
1113 "to %s authenticated",
1114 SSL_get0_peername(c->ssl));
1115 log_addr(VERB_ALGO, buf, &c->repinfo.addr,
1116 c->repinfo.addrlen);
1119 log_addr(VERB_ALGO, "SSL connection "
1120 "authenticated", &c->repinfo.addr,
1121 c->repinfo.addrlen);
1122 #ifdef HAVE_SSL_GET0_PEERNAME
1127 X509* x = SSL_get_peer_certificate(c->ssl);
1129 log_cert(VERB_ALGO, "peer certificate", x);
1132 log_addr(VERB_ALGO, "SSL connection failed: "
1133 "failed to authenticate",
1134 &c->repinfo.addr, c->repinfo.addrlen);
1138 /* unauthenticated, the verify peer flag was not set
1139 * in c->ssl when the ssl object was created from ssl_ctx */
1140 log_addr(VERB_ALGO, "SSL connection", &c->repinfo.addr,
1141 c->repinfo.addrlen);
1144 /* setup listen rw correctly */
1145 if(c->tcp_is_reading) {
1146 if(c->ssl_shake_state != comm_ssl_shake_read)
1147 comm_point_listen_for_rw(c, 1, 0);
1149 comm_point_listen_for_rw(c, 1, 1);
1151 c->ssl_shake_state = comm_ssl_shake_none;
1154 #endif /* HAVE_SSL */
1156 /** ssl read callback on TCP */
1158 ssl_handle_read(struct comm_point* c)
1162 if(c->ssl_shake_state != comm_ssl_shake_none) {
1163 if(!ssl_handshake(c))
1165 if(c->ssl_shake_state != comm_ssl_shake_none)
1168 if(c->tcp_byte_count < sizeof(uint16_t)) {
1169 /* read length bytes */
1171 if((r=SSL_read(c->ssl, (void*)sldns_buffer_at(c->buffer,
1172 c->tcp_byte_count), (int)(sizeof(uint16_t) -
1173 c->tcp_byte_count))) <= 0) {
1174 int want = SSL_get_error(c->ssl, r);
1175 if(want == SSL_ERROR_ZERO_RETURN) {
1177 return tcp_req_info_handle_read_close(c->tcp_req_info);
1178 return 0; /* shutdown, closed */
1179 } else if(want == SSL_ERROR_WANT_READ) {
1180 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1181 return 1; /* read more later */
1182 } else if(want == SSL_ERROR_WANT_WRITE) {
1183 c->ssl_shake_state = comm_ssl_shake_hs_write;
1184 comm_point_listen_for_rw(c, 0, 1);
1186 } else if(want == SSL_ERROR_SYSCALL) {
1188 log_err("SSL_read syscall: %s",
1192 log_crypto_err("could not SSL_read");
1195 c->tcp_byte_count += r;
1196 if(c->tcp_byte_count < sizeof(uint16_t))
1198 if(sldns_buffer_read_u16_at(c->buffer, 0) >
1199 sldns_buffer_capacity(c->buffer)) {
1200 verbose(VERB_QUERY, "ssl: dropped larger than buffer");
1203 sldns_buffer_set_limit(c->buffer,
1204 sldns_buffer_read_u16_at(c->buffer, 0));
1205 if(sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
1206 verbose(VERB_QUERY, "ssl: dropped bogus too short.");
1209 sldns_buffer_skip(c->buffer, (ssize_t)(c->tcp_byte_count-sizeof(uint16_t)));
1210 verbose(VERB_ALGO, "Reading ssl tcp query of length %d",
1211 (int)sldns_buffer_limit(c->buffer));
1213 if(sldns_buffer_remaining(c->buffer) > 0) {
1215 r = SSL_read(c->ssl, (void*)sldns_buffer_current(c->buffer),
1216 (int)sldns_buffer_remaining(c->buffer));
1218 int want = SSL_get_error(c->ssl, r);
1219 if(want == SSL_ERROR_ZERO_RETURN) {
1221 return tcp_req_info_handle_read_close(c->tcp_req_info);
1222 return 0; /* shutdown, closed */
1223 } else if(want == SSL_ERROR_WANT_READ) {
1224 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1225 return 1; /* read more later */
1226 } else if(want == SSL_ERROR_WANT_WRITE) {
1227 c->ssl_shake_state = comm_ssl_shake_hs_write;
1228 comm_point_listen_for_rw(c, 0, 1);
1230 } else if(want == SSL_ERROR_SYSCALL) {
1232 log_err("SSL_read syscall: %s",
1236 log_crypto_err("could not SSL_read");
1239 sldns_buffer_skip(c->buffer, (ssize_t)r);
1241 if(sldns_buffer_remaining(c->buffer) <= 0) {
1242 tcp_callback_reader(c);
1248 #endif /* HAVE_SSL */
1251 /** ssl write callback on TCP */
1253 ssl_handle_write(struct comm_point* c)
1257 if(c->ssl_shake_state != comm_ssl_shake_none) {
1258 if(!ssl_handshake(c))
1260 if(c->ssl_shake_state != comm_ssl_shake_none)
1263 /* ignore return, if fails we may simply block */
1264 (void)SSL_set_mode(c->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE);
1265 if(c->tcp_byte_count < sizeof(uint16_t)) {
1266 uint16_t len = htons(sldns_buffer_limit(c->buffer));
1268 if(sizeof(uint16_t)+sldns_buffer_remaining(c->buffer) <
1270 /* combine the tcp length and the query for write,
1271 * this emulates writev */
1272 uint8_t buf[LDNS_RR_BUF_SIZE];
1273 memmove(buf, &len, sizeof(uint16_t));
1274 memmove(buf+sizeof(uint16_t),
1275 sldns_buffer_current(c->buffer),
1276 sldns_buffer_remaining(c->buffer));
1277 r = SSL_write(c->ssl, (void*)(buf+c->tcp_byte_count),
1278 (int)(sizeof(uint16_t)+
1279 sldns_buffer_remaining(c->buffer)
1280 - c->tcp_byte_count));
1282 r = SSL_write(c->ssl,
1283 (void*)(((uint8_t*)&len)+c->tcp_byte_count),
1284 (int)(sizeof(uint16_t)-c->tcp_byte_count));
1287 int want = SSL_get_error(c->ssl, r);
1288 if(want == SSL_ERROR_ZERO_RETURN) {
1289 return 0; /* closed */
1290 } else if(want == SSL_ERROR_WANT_READ) {
1291 c->ssl_shake_state = comm_ssl_shake_read;
1292 comm_point_listen_for_rw(c, 1, 0);
1293 return 1; /* wait for read condition */
1294 } else if(want == SSL_ERROR_WANT_WRITE) {
1295 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
1296 return 1; /* write more later */
1297 } else if(want == SSL_ERROR_SYSCALL) {
1299 log_err("SSL_write syscall: %s",
1303 log_crypto_err("could not SSL_write");
1306 c->tcp_byte_count += r;
1307 if(c->tcp_byte_count < sizeof(uint16_t))
1309 sldns_buffer_set_position(c->buffer, c->tcp_byte_count -
1311 if(sldns_buffer_remaining(c->buffer) == 0) {
1312 tcp_callback_writer(c);
1316 log_assert(sldns_buffer_remaining(c->buffer) > 0);
1318 r = SSL_write(c->ssl, (void*)sldns_buffer_current(c->buffer),
1319 (int)sldns_buffer_remaining(c->buffer));
1321 int want = SSL_get_error(c->ssl, r);
1322 if(want == SSL_ERROR_ZERO_RETURN) {
1323 return 0; /* closed */
1324 } else if(want == SSL_ERROR_WANT_READ) {
1325 c->ssl_shake_state = comm_ssl_shake_read;
1326 comm_point_listen_for_rw(c, 1, 0);
1327 return 1; /* wait for read condition */
1328 } else if(want == SSL_ERROR_WANT_WRITE) {
1329 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
1330 return 1; /* write more later */
1331 } else if(want == SSL_ERROR_SYSCALL) {
1333 log_err("SSL_write syscall: %s",
1337 log_crypto_err("could not SSL_write");
1340 sldns_buffer_skip(c->buffer, (ssize_t)r);
1342 if(sldns_buffer_remaining(c->buffer) == 0) {
1343 tcp_callback_writer(c);
1349 #endif /* HAVE_SSL */
1352 /** handle ssl tcp connection with dns contents */
1354 ssl_handle_it(struct comm_point* c)
1356 if(c->tcp_is_reading)
1357 return ssl_handle_read(c);
1358 return ssl_handle_write(c);
1361 /** Handle tcp reading callback.
1362 * @param fd: file descriptor of socket.
1363 * @param c: comm point to read from into buffer.
1364 * @param short_ok: if true, very short packets are OK (for comm_local).
1365 * @return: 0 on error
1368 comm_point_tcp_handle_read(int fd, struct comm_point* c, int short_ok)
1371 log_assert(c->type == comm_tcp || c->type == comm_local);
1373 return ssl_handle_it(c);
1374 if(!c->tcp_is_reading)
1377 log_assert(fd != -1);
1378 if(c->tcp_byte_count < sizeof(uint16_t)) {
1379 /* read length bytes */
1380 r = recv(fd,(void*)sldns_buffer_at(c->buffer,c->tcp_byte_count),
1381 sizeof(uint16_t)-c->tcp_byte_count, 0);
1384 return tcp_req_info_handle_read_close(c->tcp_req_info);
1386 } else if(r == -1) {
1388 if(errno == EINTR || errno == EAGAIN)
1391 if(errno == ECONNRESET && verbosity < 2)
1392 return 0; /* silence reset by peer */
1394 log_err_addr("read (in tcp s)", strerror(errno),
1395 &c->repinfo.addr, c->repinfo.addrlen);
1396 #else /* USE_WINSOCK */
1397 if(WSAGetLastError() == WSAECONNRESET)
1399 if(WSAGetLastError() == WSAEINPROGRESS)
1401 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1402 ub_winsock_tcp_wouldblock(c->ev->ev,
1406 log_err_addr("read (in tcp s)",
1407 wsa_strerror(WSAGetLastError()),
1408 &c->repinfo.addr, c->repinfo.addrlen);
1412 c->tcp_byte_count += r;
1413 if(c->tcp_byte_count != sizeof(uint16_t))
1415 if(sldns_buffer_read_u16_at(c->buffer, 0) >
1416 sldns_buffer_capacity(c->buffer)) {
1417 verbose(VERB_QUERY, "tcp: dropped larger than buffer");
1420 sldns_buffer_set_limit(c->buffer,
1421 sldns_buffer_read_u16_at(c->buffer, 0));
1423 sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
1424 verbose(VERB_QUERY, "tcp: dropped bogus too short.");
1427 verbose(VERB_ALGO, "Reading tcp query of length %d",
1428 (int)sldns_buffer_limit(c->buffer));
1431 log_assert(sldns_buffer_remaining(c->buffer) > 0);
1432 r = recv(fd, (void*)sldns_buffer_current(c->buffer),
1433 sldns_buffer_remaining(c->buffer), 0);
1436 return tcp_req_info_handle_read_close(c->tcp_req_info);
1438 } else if(r == -1) {
1440 if(errno == EINTR || errno == EAGAIN)
1442 log_err_addr("read (in tcp r)", strerror(errno),
1443 &c->repinfo.addr, c->repinfo.addrlen);
1444 #else /* USE_WINSOCK */
1445 if(WSAGetLastError() == WSAECONNRESET)
1447 if(WSAGetLastError() == WSAEINPROGRESS)
1449 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1450 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1453 log_err_addr("read (in tcp r)",
1454 wsa_strerror(WSAGetLastError()),
1455 &c->repinfo.addr, c->repinfo.addrlen);
1459 sldns_buffer_skip(c->buffer, r);
1460 if(sldns_buffer_remaining(c->buffer) <= 0) {
1461 tcp_callback_reader(c);
1467 * Handle tcp writing callback.
1468 * @param fd: file descriptor of socket.
1469 * @param c: comm point to write buffer out of.
1470 * @return: 0 on error
1473 comm_point_tcp_handle_write(int fd, struct comm_point* c)
1476 struct sldns_buffer *buffer;
1477 log_assert(c->type == comm_tcp);
1479 buffer = c->dnscrypt_buffer;
1483 if(c->tcp_is_reading && !c->ssl)
1485 log_assert(fd != -1);
1486 if(c->tcp_byte_count == 0 && c->tcp_check_nb_connect) {
1487 /* check for pending error from nonblocking connect */
1488 /* from Stevens, unix network programming, vol1, 3rd ed, p450*/
1490 socklen_t len = (socklen_t)sizeof(error);
1491 if(getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&error,
1494 error = errno; /* on solaris errno is error */
1495 #else /* USE_WINSOCK */
1496 error = WSAGetLastError();
1500 #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
1501 if(error == EINPROGRESS || error == EWOULDBLOCK)
1502 return 1; /* try again later */
1505 if(error != 0 && verbosity < 2)
1506 return 0; /* silence lots of chatter in the logs */
1507 else if(error != 0) {
1508 log_err_addr("tcp connect", strerror(error),
1509 &c->repinfo.addr, c->repinfo.addrlen);
1510 #else /* USE_WINSOCK */
1512 if(error == WSAEINPROGRESS)
1514 else if(error == WSAEWOULDBLOCK) {
1515 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
1517 } else if(error != 0 && verbosity < 2)
1519 else if(error != 0) {
1520 log_err_addr("tcp connect", wsa_strerror(error),
1521 &c->repinfo.addr, c->repinfo.addrlen);
1522 #endif /* USE_WINSOCK */
1527 return ssl_handle_it(c);
1529 #ifdef USE_MSG_FASTOPEN
1530 /* Only try this on first use of a connection that uses tfo,
1531 otherwise fall through to normal write */
1532 /* Also, TFO support on WINDOWS not implemented at the moment */
1533 if(c->tcp_do_fastopen == 1) {
1534 /* this form of sendmsg() does both a connect() and send() so need to
1535 look for various flavours of error*/
1536 uint16_t len = htons(sldns_buffer_limit(buffer));
1538 struct iovec iov[2];
1539 c->tcp_do_fastopen = 0;
1540 memset(&msg, 0, sizeof(msg));
1541 iov[0].iov_base = (uint8_t*)&len + c->tcp_byte_count;
1542 iov[0].iov_len = sizeof(uint16_t) - c->tcp_byte_count;
1543 iov[1].iov_base = sldns_buffer_begin(buffer);
1544 iov[1].iov_len = sldns_buffer_limit(buffer);
1545 log_assert(iov[0].iov_len > 0);
1546 log_assert(iov[1].iov_len > 0);
1547 msg.msg_name = &c->repinfo.addr;
1548 msg.msg_namelen = c->repinfo.addrlen;
1551 r = sendmsg(fd, &msg, MSG_FASTOPEN);
1553 #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
1554 /* Handshake is underway, maybe because no TFO cookie available.
1555 Come back to write the message*/
1556 if(errno == EINPROGRESS || errno == EWOULDBLOCK)
1559 if(errno == EINTR || errno == EAGAIN)
1561 /* Not handling EISCONN here as shouldn't ever hit that case.*/
1562 if(errno != EPIPE && errno != 0 && verbosity < 2)
1563 return 0; /* silence lots of chatter in the logs */
1564 if(errno != EPIPE && errno != 0) {
1565 log_err_addr("tcp sendmsg", strerror(errno),
1566 &c->repinfo.addr, c->repinfo.addrlen);
1569 /* fallthrough to nonFASTOPEN
1570 * (MSG_FASTOPEN on Linux 3 produces EPIPE)
1571 * we need to perform connect() */
1572 if(connect(fd, (struct sockaddr *)&c->repinfo.addr, c->repinfo.addrlen) == -1) {
1574 if(errno == EINPROGRESS)
1575 return 1; /* wait until connect done*/
1578 if(WSAGetLastError() == WSAEINPROGRESS ||
1579 WSAGetLastError() == WSAEWOULDBLOCK)
1580 return 1; /* wait until connect done*/
1582 if(tcp_connect_errno_needs_log(
1583 (struct sockaddr *)&c->repinfo.addr, c->repinfo.addrlen)) {
1584 log_err_addr("outgoing tcp: connect after EPIPE for fastopen",
1585 strerror(errno), &c->repinfo.addr, c->repinfo.addrlen);
1591 c->tcp_byte_count += r;
1592 if(c->tcp_byte_count < sizeof(uint16_t))
1594 sldns_buffer_set_position(buffer, c->tcp_byte_count -
1596 if(sldns_buffer_remaining(buffer) == 0) {
1597 tcp_callback_writer(c);
1602 #endif /* USE_MSG_FASTOPEN */
1604 if(c->tcp_byte_count < sizeof(uint16_t)) {
1605 uint16_t len = htons(sldns_buffer_limit(buffer));
1607 struct iovec iov[2];
1608 iov[0].iov_base = (uint8_t*)&len + c->tcp_byte_count;
1609 iov[0].iov_len = sizeof(uint16_t) - c->tcp_byte_count;
1610 iov[1].iov_base = sldns_buffer_begin(buffer);
1611 iov[1].iov_len = sldns_buffer_limit(buffer);
1612 log_assert(iov[0].iov_len > 0);
1613 log_assert(iov[1].iov_len > 0);
1614 r = writev(fd, iov, 2);
1615 #else /* HAVE_WRITEV */
1616 r = send(fd, (void*)(((uint8_t*)&len)+c->tcp_byte_count),
1617 sizeof(uint16_t)-c->tcp_byte_count, 0);
1618 #endif /* HAVE_WRITEV */
1622 if(errno == EPIPE && verbosity < 2)
1623 return 0; /* silence 'broken pipe' */
1625 if(errno == EINTR || errno == EAGAIN)
1628 log_err_addr("tcp writev", strerror(errno),
1629 &c->repinfo.addr, c->repinfo.addrlen);
1630 # else /* HAVE_WRITEV */
1631 log_err_addr("tcp send s", strerror(errno),
1632 &c->repinfo.addr, c->repinfo.addrlen);
1633 # endif /* HAVE_WRITEV */
1635 if(WSAGetLastError() == WSAENOTCONN)
1637 if(WSAGetLastError() == WSAEINPROGRESS)
1639 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1640 ub_winsock_tcp_wouldblock(c->ev->ev,
1644 log_err_addr("tcp send s",
1645 wsa_strerror(WSAGetLastError()),
1646 &c->repinfo.addr, c->repinfo.addrlen);
1650 c->tcp_byte_count += r;
1651 if(c->tcp_byte_count < sizeof(uint16_t))
1653 sldns_buffer_set_position(buffer, c->tcp_byte_count -
1655 if(sldns_buffer_remaining(buffer) == 0) {
1656 tcp_callback_writer(c);
1660 log_assert(sldns_buffer_remaining(buffer) > 0);
1661 r = send(fd, (void*)sldns_buffer_current(buffer),
1662 sldns_buffer_remaining(buffer), 0);
1665 if(errno == EINTR || errno == EAGAIN)
1667 log_err_addr("tcp send r", strerror(errno),
1668 &c->repinfo.addr, c->repinfo.addrlen);
1670 if(WSAGetLastError() == WSAEINPROGRESS)
1672 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1673 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
1676 log_err_addr("tcp send r", wsa_strerror(WSAGetLastError()),
1677 &c->repinfo.addr, c->repinfo.addrlen);
1681 sldns_buffer_skip(buffer, r);
1683 if(sldns_buffer_remaining(buffer) == 0) {
1684 tcp_callback_writer(c);
1690 /** read again to drain buffers when there could be more to read */
1692 tcp_req_info_read_again(int fd, struct comm_point* c)
1694 while(c->tcp_req_info->read_again) {
1696 c->tcp_req_info->read_again = 0;
1697 if(c->tcp_is_reading)
1698 r = comm_point_tcp_handle_read(fd, c, 0);
1699 else r = comm_point_tcp_handle_write(fd, c);
1701 reclaim_tcp_handler(c);
1702 if(!c->tcp_do_close) {
1703 fptr_ok(fptr_whitelist_comm_point(
1705 (void)(*c->callback)(c, c->cb_arg,
1706 NETEVENT_CLOSED, NULL);
1714 comm_point_tcp_handle_callback(int fd, short event, void* arg)
1716 struct comm_point* c = (struct comm_point*)arg;
1717 log_assert(c->type == comm_tcp);
1718 ub_comm_base_now(c->ev->base);
1721 /* Initialize if this is a dnscrypt socket */
1723 c->dnscrypt = c->tcp_parent->dnscrypt;
1725 if(c->dnscrypt && c->dnscrypt_buffer == c->buffer) {
1726 c->dnscrypt_buffer = sldns_buffer_new(sldns_buffer_capacity(c->buffer));
1727 if(!c->dnscrypt_buffer) {
1728 log_err("Could not allocate dnscrypt buffer");
1729 reclaim_tcp_handler(c);
1730 if(!c->tcp_do_close) {
1731 fptr_ok(fptr_whitelist_comm_point(
1733 (void)(*c->callback)(c, c->cb_arg,
1734 NETEVENT_CLOSED, NULL);
1741 if(event&UB_EV_READ) {
1742 int has_tcpq = (c->tcp_req_info != NULL);
1743 if(!comm_point_tcp_handle_read(fd, c, 0)) {
1744 reclaim_tcp_handler(c);
1745 if(!c->tcp_do_close) {
1746 fptr_ok(fptr_whitelist_comm_point(
1748 (void)(*c->callback)(c, c->cb_arg,
1749 NETEVENT_CLOSED, NULL);
1752 if(has_tcpq && c->tcp_req_info && c->tcp_req_info->read_again)
1753 tcp_req_info_read_again(fd, c);
1756 if(event&UB_EV_WRITE) {
1757 int has_tcpq = (c->tcp_req_info != NULL);
1758 if(!comm_point_tcp_handle_write(fd, c)) {
1759 reclaim_tcp_handler(c);
1760 if(!c->tcp_do_close) {
1761 fptr_ok(fptr_whitelist_comm_point(
1763 (void)(*c->callback)(c, c->cb_arg,
1764 NETEVENT_CLOSED, NULL);
1767 if(has_tcpq && c->tcp_req_info && c->tcp_req_info->read_again)
1768 tcp_req_info_read_again(fd, c);
1771 if(event&UB_EV_TIMEOUT) {
1772 verbose(VERB_QUERY, "tcp took too long, dropped");
1773 reclaim_tcp_handler(c);
1774 if(!c->tcp_do_close) {
1775 fptr_ok(fptr_whitelist_comm_point(c->callback));
1776 (void)(*c->callback)(c, c->cb_arg,
1777 NETEVENT_TIMEOUT, NULL);
1781 log_err("Ignored event %d for tcphdl.", event);
1784 /** Make http handler free for next assignment */
1786 reclaim_http_handler(struct comm_point* c)
1788 log_assert(c->type == comm_http);
1791 SSL_shutdown(c->ssl);
1796 comm_point_close(c);
1798 c->tcp_parent->cur_tcp_count--;
1799 c->tcp_free = c->tcp_parent->tcp_free;
1800 c->tcp_parent->tcp_free = c;
1802 /* re-enable listening on accept socket */
1803 comm_point_start_listening(c->tcp_parent, -1, -1);
1808 /** read more data for http (with ssl) */
1810 ssl_http_read_more(struct comm_point* c)
1814 log_assert(sldns_buffer_remaining(c->buffer) > 0);
1816 r = SSL_read(c->ssl, (void*)sldns_buffer_current(c->buffer),
1817 (int)sldns_buffer_remaining(c->buffer));
1819 int want = SSL_get_error(c->ssl, r);
1820 if(want == SSL_ERROR_ZERO_RETURN) {
1821 return 0; /* shutdown, closed */
1822 } else if(want == SSL_ERROR_WANT_READ) {
1823 return 1; /* read more later */
1824 } else if(want == SSL_ERROR_WANT_WRITE) {
1825 c->ssl_shake_state = comm_ssl_shake_hs_write;
1826 comm_point_listen_for_rw(c, 0, 1);
1828 } else if(want == SSL_ERROR_SYSCALL) {
1830 log_err("SSL_read syscall: %s",
1834 log_crypto_err("could not SSL_read");
1837 sldns_buffer_skip(c->buffer, (ssize_t)r);
1842 #endif /* HAVE_SSL */
1845 /** read more data for http */
1847 http_read_more(int fd, struct comm_point* c)
1850 log_assert(sldns_buffer_remaining(c->buffer) > 0);
1851 r = recv(fd, (void*)sldns_buffer_current(c->buffer),
1852 sldns_buffer_remaining(c->buffer), 0);
1855 } else if(r == -1) {
1857 if(errno == EINTR || errno == EAGAIN)
1859 log_err_addr("read (in http r)", strerror(errno),
1860 &c->repinfo.addr, c->repinfo.addrlen);
1861 #else /* USE_WINSOCK */
1862 if(WSAGetLastError() == WSAECONNRESET)
1864 if(WSAGetLastError() == WSAEINPROGRESS)
1866 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1867 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1870 log_err_addr("read (in http r)",
1871 wsa_strerror(WSAGetLastError()),
1872 &c->repinfo.addr, c->repinfo.addrlen);
1876 sldns_buffer_skip(c->buffer, r);
1880 /** return true if http header has been read (one line complete) */
1882 http_header_done(sldns_buffer* buf)
1885 for(i=sldns_buffer_position(buf); i<sldns_buffer_limit(buf); i++) {
1886 /* there was a \r before the \n, but we ignore that */
1887 if((char)sldns_buffer_read_u8_at(buf, i) == '\n')
1893 /** return character string into buffer for header line, moves buffer
1894 * past that line and puts zero terminator into linefeed-newline */
1896 http_header_line(sldns_buffer* buf)
1898 char* result = (char*)sldns_buffer_current(buf);
1900 for(i=sldns_buffer_position(buf); i<sldns_buffer_limit(buf); i++) {
1901 /* terminate the string on the \r */
1902 if((char)sldns_buffer_read_u8_at(buf, i) == '\r')
1903 sldns_buffer_write_u8_at(buf, i, 0);
1904 /* terminate on the \n and skip past the it and done */
1905 if((char)sldns_buffer_read_u8_at(buf, i) == '\n') {
1906 sldns_buffer_write_u8_at(buf, i, 0);
1907 sldns_buffer_set_position(buf, i+1);
1914 /** move unread buffer to start and clear rest for putting the rest into it */
1916 http_moveover_buffer(sldns_buffer* buf)
1918 size_t pos = sldns_buffer_position(buf);
1919 size_t len = sldns_buffer_remaining(buf);
1920 sldns_buffer_clear(buf);
1921 memmove(sldns_buffer_begin(buf), sldns_buffer_at(buf, pos), len);
1922 sldns_buffer_set_position(buf, len);
1925 /** a http header is complete, process it */
1927 http_process_initial_header(struct comm_point* c)
1929 char* line = http_header_line(c->buffer);
1931 verbose(VERB_ALGO, "http header: %s", line);
1932 if(strncasecmp(line, "HTTP/1.1 ", 9) == 0) {
1933 /* check returncode */
1934 if(line[9] != '2') {
1935 verbose(VERB_ALGO, "http bad status %s", line+9);
1938 } else if(strncasecmp(line, "Content-Length: ", 16) == 0) {
1939 if(!c->http_is_chunked)
1940 c->tcp_byte_count = (size_t)atoi(line+16);
1941 } else if(strncasecmp(line, "Transfer-Encoding: chunked", 19+7) == 0) {
1942 c->tcp_byte_count = 0;
1943 c->http_is_chunked = 1;
1944 } else if(line[0] == 0) {
1945 /* end of initial headers */
1946 c->http_in_headers = 0;
1947 if(c->http_is_chunked)
1948 c->http_in_chunk_headers = 1;
1949 /* remove header text from front of buffer
1950 * the buffer is going to be used to return the data segment
1951 * itself and we don't want the header to get returned
1952 * prepended with it */
1953 http_moveover_buffer(c->buffer);
1954 sldns_buffer_flip(c->buffer);
1957 /* ignore other headers */
1961 /** a chunk header is complete, process it, return 0=fail, 1=continue next
1962 * header line, 2=done with chunked transfer*/
1964 http_process_chunk_header(struct comm_point* c)
1966 char* line = http_header_line(c->buffer);
1968 if(c->http_in_chunk_headers == 3) {
1969 verbose(VERB_ALGO, "http chunk trailer: %s", line);
1971 if(line[0] == 0 && c->tcp_byte_count == 0) {
1972 /* callback of http reader when NETEVENT_DONE,
1973 * end of data, with no data in buffer */
1974 sldns_buffer_set_position(c->buffer, 0);
1975 sldns_buffer_set_limit(c->buffer, 0);
1976 fptr_ok(fptr_whitelist_comm_point(c->callback));
1977 (void)(*c->callback)(c, c->cb_arg, NETEVENT_DONE, NULL);
1978 /* return that we are done */
1982 /* continue with header of the next chunk */
1983 c->http_in_chunk_headers = 1;
1984 /* remove header text from front of buffer */
1985 http_moveover_buffer(c->buffer);
1986 sldns_buffer_flip(c->buffer);
1989 /* ignore further trail headers */
1992 verbose(VERB_ALGO, "http chunk header: %s", line);
1993 if(c->http_in_chunk_headers == 1) {
1994 /* read chunked start line */
1996 c->tcp_byte_count = (size_t)strtol(line, &end, 16);
1999 c->http_in_chunk_headers = 0;
2000 /* remove header text from front of buffer */
2001 http_moveover_buffer(c->buffer);
2002 sldns_buffer_flip(c->buffer);
2003 if(c->tcp_byte_count == 0) {
2004 /* done with chunks, process chunk_trailer lines */
2005 c->http_in_chunk_headers = 3;
2009 /* ignore other headers */
2013 /** handle nonchunked data segment */
2015 http_nonchunk_segment(struct comm_point* c)
2017 /* c->buffer at position..limit has new data we read in.
2018 * the buffer itself is full of nonchunked data.
2019 * we are looking to read tcp_byte_count more data
2020 * and then the transfer is done. */
2021 size_t remainbufferlen;
2022 size_t got_now = sldns_buffer_limit(c->buffer) - c->http_stored;
2023 if(c->tcp_byte_count <= got_now) {
2024 /* done, this is the last data fragment */
2026 sldns_buffer_set_position(c->buffer, 0);
2027 fptr_ok(fptr_whitelist_comm_point(c->callback));
2028 (void)(*c->callback)(c, c->cb_arg, NETEVENT_DONE, NULL);
2031 c->tcp_byte_count -= got_now;
2032 /* if we have the buffer space,
2033 * read more data collected into the buffer */
2034 remainbufferlen = sldns_buffer_capacity(c->buffer) -
2035 sldns_buffer_limit(c->buffer);
2036 if(remainbufferlen >= c->tcp_byte_count ||
2037 remainbufferlen >= 2048) {
2038 size_t total = sldns_buffer_limit(c->buffer);
2039 sldns_buffer_clear(c->buffer);
2040 sldns_buffer_set_position(c->buffer, total);
2041 c->http_stored = total;
2042 /* return and wait to read more */
2045 /* call callback with this data amount, then
2048 sldns_buffer_set_position(c->buffer, 0);
2049 fptr_ok(fptr_whitelist_comm_point(c->callback));
2050 (void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, NULL);
2051 /* c->callback has to buffer_clear(c->buffer). */
2052 /* return and wait to read more */
2056 /** handle nonchunked data segment, return 0=fail, 1=wait, 2=process more */
2058 http_chunked_segment(struct comm_point* c)
2060 /* the c->buffer has from position..limit new data we read. */
2061 /* the current chunk has length tcp_byte_count.
2062 * once we read that read more chunk headers.
2064 size_t remainbufferlen;
2065 size_t got_now = sldns_buffer_limit(c->buffer) - c->http_stored;
2066 if(c->tcp_byte_count <= got_now) {
2067 /* the chunk has completed (with perhaps some extra data
2068 * from next chunk header and next chunk) */
2069 /* save too much info into temp buffer */
2071 struct comm_reply repinfo;
2073 sldns_buffer_skip(c->buffer, (ssize_t)c->tcp_byte_count);
2074 sldns_buffer_clear(c->http_temp);
2075 sldns_buffer_write(c->http_temp,
2076 sldns_buffer_current(c->buffer),
2077 sldns_buffer_remaining(c->buffer));
2078 sldns_buffer_flip(c->http_temp);
2080 /* callback with this fragment */
2081 fraglen = sldns_buffer_position(c->buffer);
2082 sldns_buffer_set_position(c->buffer, 0);
2083 sldns_buffer_set_limit(c->buffer, fraglen);
2084 repinfo = c->repinfo;
2085 fptr_ok(fptr_whitelist_comm_point(c->callback));
2086 (void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, &repinfo);
2087 /* c->callback has to buffer_clear(). */
2089 /* is commpoint deleted? */
2093 /* copy waiting info */
2094 sldns_buffer_clear(c->buffer);
2095 sldns_buffer_write(c->buffer,
2096 sldns_buffer_begin(c->http_temp),
2097 sldns_buffer_remaining(c->http_temp));
2098 sldns_buffer_flip(c->buffer);
2099 /* process end of chunk trailer header lines, until
2101 c->http_in_chunk_headers = 3;
2102 /* process more data in buffer (if any) */
2105 c->tcp_byte_count -= got_now;
2107 /* if we have the buffer space,
2108 * read more data collected into the buffer */
2109 remainbufferlen = sldns_buffer_capacity(c->buffer) -
2110 sldns_buffer_limit(c->buffer);
2111 if(remainbufferlen >= c->tcp_byte_count ||
2112 remainbufferlen >= 2048) {
2113 size_t total = sldns_buffer_limit(c->buffer);
2114 sldns_buffer_clear(c->buffer);
2115 sldns_buffer_set_position(c->buffer, total);
2116 c->http_stored = total;
2117 /* return and wait to read more */
2121 /* callback of http reader for a new part of the data */
2123 sldns_buffer_set_position(c->buffer, 0);
2124 fptr_ok(fptr_whitelist_comm_point(c->callback));
2125 (void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, NULL);
2126 /* c->callback has to buffer_clear(c->buffer). */
2127 /* return and wait to read more */
2132 * Handle http reading callback.
2133 * @param fd: file descriptor of socket.
2134 * @param c: comm point to read from into buffer.
2135 * @return: 0 on error
2138 comm_point_http_handle_read(int fd, struct comm_point* c)
2140 log_assert(c->type == comm_http);
2141 log_assert(fd != -1);
2143 /* if we are in ssl handshake, handle SSL handshake */
2145 if(c->ssl && c->ssl_shake_state != comm_ssl_shake_none) {
2146 if(!ssl_handshake(c))
2148 if(c->ssl_shake_state != comm_ssl_shake_none)
2151 #endif /* HAVE_SSL */
2153 if(!c->tcp_is_reading)
2155 /* read more data */
2157 if(!ssl_http_read_more(c))
2160 if(!http_read_more(fd, c))
2164 sldns_buffer_flip(c->buffer);
2165 while(sldns_buffer_remaining(c->buffer) > 0) {
2166 /* if we are reading headers, read more headers */
2167 if(c->http_in_headers || c->http_in_chunk_headers) {
2168 /* if header is done, process the header */
2169 if(!http_header_done(c->buffer)) {
2170 /* copy remaining data to front of buffer
2171 * and set rest for writing into it */
2172 http_moveover_buffer(c->buffer);
2173 /* return and wait to read more */
2176 if(!c->http_in_chunk_headers) {
2177 /* process initial headers */
2178 if(!http_process_initial_header(c))
2181 /* process chunk headers */
2182 int r = http_process_chunk_header(c);
2183 if(r == 0) return 0;
2184 if(r == 2) return 1; /* done */
2185 /* r == 1, continue */
2187 /* see if we have more to process */
2191 if(!c->http_is_chunked) {
2192 /* if we are reading nonchunks, process that*/
2193 return http_nonchunk_segment(c);
2195 /* if we are reading chunks, read the chunk */
2196 int r = http_chunked_segment(c);
2197 if(r == 0) return 0;
2198 if(r == 1) return 1;
2202 /* broke out of the loop; could not process header instead need
2204 /* moveover any remaining data and read more data */
2205 http_moveover_buffer(c->buffer);
2206 /* return and wait to read more */
2210 /** check pending connect for http */
2212 http_check_connect(int fd, struct comm_point* c)
2214 /* check for pending error from nonblocking connect */
2215 /* from Stevens, unix network programming, vol1, 3rd ed, p450*/
2217 socklen_t len = (socklen_t)sizeof(error);
2218 if(getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&error,
2221 error = errno; /* on solaris errno is error */
2222 #else /* USE_WINSOCK */
2223 error = WSAGetLastError();
2227 #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
2228 if(error == EINPROGRESS || error == EWOULDBLOCK)
2229 return 1; /* try again later */
2232 if(error != 0 && verbosity < 2)
2233 return 0; /* silence lots of chatter in the logs */
2234 else if(error != 0) {
2235 log_err_addr("http connect", strerror(error),
2236 &c->repinfo.addr, c->repinfo.addrlen);
2237 #else /* USE_WINSOCK */
2239 if(error == WSAEINPROGRESS)
2241 else if(error == WSAEWOULDBLOCK) {
2242 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
2244 } else if(error != 0 && verbosity < 2)
2246 else if(error != 0) {
2247 log_err_addr("http connect", wsa_strerror(error),
2248 &c->repinfo.addr, c->repinfo.addrlen);
2249 #endif /* USE_WINSOCK */
2252 /* keep on processing this socket */
2256 /** write more data for http (with ssl) */
2258 ssl_http_write_more(struct comm_point* c)
2262 log_assert(sldns_buffer_remaining(c->buffer) > 0);
2264 r = SSL_write(c->ssl, (void*)sldns_buffer_current(c->buffer),
2265 (int)sldns_buffer_remaining(c->buffer));
2267 int want = SSL_get_error(c->ssl, r);
2268 if(want == SSL_ERROR_ZERO_RETURN) {
2269 return 0; /* closed */
2270 } else if(want == SSL_ERROR_WANT_READ) {
2271 c->ssl_shake_state = comm_ssl_shake_read;
2272 comm_point_listen_for_rw(c, 1, 0);
2273 return 1; /* wait for read condition */
2274 } else if(want == SSL_ERROR_WANT_WRITE) {
2275 return 1; /* write more later */
2276 } else if(want == SSL_ERROR_SYSCALL) {
2278 log_err("SSL_write syscall: %s",
2282 log_crypto_err("could not SSL_write");
2285 sldns_buffer_skip(c->buffer, (ssize_t)r);
2290 #endif /* HAVE_SSL */
2293 /** write more data for http */
2295 http_write_more(int fd, struct comm_point* c)
2298 log_assert(sldns_buffer_remaining(c->buffer) > 0);
2299 r = send(fd, (void*)sldns_buffer_current(c->buffer),
2300 sldns_buffer_remaining(c->buffer), 0);
2303 if(errno == EINTR || errno == EAGAIN)
2305 log_err_addr("http send r", strerror(errno),
2306 &c->repinfo.addr, c->repinfo.addrlen);
2308 if(WSAGetLastError() == WSAEINPROGRESS)
2310 if(WSAGetLastError() == WSAEWOULDBLOCK) {
2311 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
2314 log_err_addr("http send r", wsa_strerror(WSAGetLastError()),
2315 &c->repinfo.addr, c->repinfo.addrlen);
2319 sldns_buffer_skip(c->buffer, r);
2324 * Handle http writing callback.
2325 * @param fd: file descriptor of socket.
2326 * @param c: comm point to write buffer out of.
2327 * @return: 0 on error
2330 comm_point_http_handle_write(int fd, struct comm_point* c)
2332 log_assert(c->type == comm_http);
2333 log_assert(fd != -1);
2335 /* check pending connect errors, if that fails, we wait for more,
2336 * or we can continue to write contents */
2337 if(c->tcp_check_nb_connect) {
2338 int r = http_check_connect(fd, c);
2339 if(r == 0) return 0;
2340 if(r == 1) return 1;
2341 c->tcp_check_nb_connect = 0;
2343 /* if we are in ssl handshake, handle SSL handshake */
2345 if(c->ssl && c->ssl_shake_state != comm_ssl_shake_none) {
2346 if(!ssl_handshake(c))
2348 if(c->ssl_shake_state != comm_ssl_shake_none)
2351 #endif /* HAVE_SSL */
2352 if(c->tcp_is_reading)
2354 /* if we are writing, write more */
2356 if(!ssl_http_write_more(c))
2359 if(!http_write_more(fd, c))
2363 /* we write a single buffer contents, that can contain
2364 * the http request, and then flip to read the results */
2365 /* see if write is done */
2366 if(sldns_buffer_remaining(c->buffer) == 0) {
2367 sldns_buffer_clear(c->buffer);
2368 if(c->tcp_do_toggle_rw)
2369 c->tcp_is_reading = 1;
2370 c->tcp_byte_count = 0;
2371 /* switch from listening(write) to listening(read) */
2372 comm_point_stop_listening(c);
2373 comm_point_start_listening(c, -1, -1);
2379 comm_point_http_handle_callback(int fd, short event, void* arg)
2381 struct comm_point* c = (struct comm_point*)arg;
2382 log_assert(c->type == comm_http);
2383 ub_comm_base_now(c->ev->base);
2385 if(event&UB_EV_READ) {
2386 if(!comm_point_http_handle_read(fd, c)) {
2387 reclaim_http_handler(c);
2388 if(!c->tcp_do_close) {
2389 fptr_ok(fptr_whitelist_comm_point(
2391 (void)(*c->callback)(c, c->cb_arg,
2392 NETEVENT_CLOSED, NULL);
2397 if(event&UB_EV_WRITE) {
2398 if(!comm_point_http_handle_write(fd, c)) {
2399 reclaim_http_handler(c);
2400 if(!c->tcp_do_close) {
2401 fptr_ok(fptr_whitelist_comm_point(
2403 (void)(*c->callback)(c, c->cb_arg,
2404 NETEVENT_CLOSED, NULL);
2409 if(event&UB_EV_TIMEOUT) {
2410 verbose(VERB_QUERY, "http took too long, dropped");
2411 reclaim_http_handler(c);
2412 if(!c->tcp_do_close) {
2413 fptr_ok(fptr_whitelist_comm_point(c->callback));
2414 (void)(*c->callback)(c, c->cb_arg,
2415 NETEVENT_TIMEOUT, NULL);
2419 log_err("Ignored event %d for httphdl.", event);
2422 void comm_point_local_handle_callback(int fd, short event, void* arg)
2424 struct comm_point* c = (struct comm_point*)arg;
2425 log_assert(c->type == comm_local);
2426 ub_comm_base_now(c->ev->base);
2428 if(event&UB_EV_READ) {
2429 if(!comm_point_tcp_handle_read(fd, c, 1)) {
2430 fptr_ok(fptr_whitelist_comm_point(c->callback));
2431 (void)(*c->callback)(c, c->cb_arg, NETEVENT_CLOSED,
2436 log_err("Ignored event %d for localhdl.", event);
2439 void comm_point_raw_handle_callback(int ATTR_UNUSED(fd),
2440 short event, void* arg)
2442 struct comm_point* c = (struct comm_point*)arg;
2443 int err = NETEVENT_NOERROR;
2444 log_assert(c->type == comm_raw);
2445 ub_comm_base_now(c->ev->base);
2447 if(event&UB_EV_TIMEOUT)
2448 err = NETEVENT_TIMEOUT;
2449 fptr_ok(fptr_whitelist_comm_point_raw(c->callback));
2450 (void)(*c->callback)(c, c->cb_arg, err, NULL);
2454 comm_point_create_udp(struct comm_base *base, int fd, sldns_buffer* buffer,
2455 comm_point_callback_type* callback, void* callback_arg)
2457 struct comm_point* c = (struct comm_point*)calloc(1,
2458 sizeof(struct comm_point));
2462 c->ev = (struct internal_event*)calloc(1,
2463 sizeof(struct internal_event));
2472 c->tcp_is_reading = 0;
2473 c->tcp_byte_count = 0;
2474 c->tcp_parent = NULL;
2475 c->max_tcp_count = 0;
2476 c->cur_tcp_count = 0;
2477 c->tcp_handlers = NULL;
2480 c->tcp_do_close = 0;
2481 c->do_not_close = 0;
2482 c->tcp_do_toggle_rw = 0;
2483 c->tcp_check_nb_connect = 0;
2484 #ifdef USE_MSG_FASTOPEN
2485 c->tcp_do_fastopen = 0;
2489 c->dnscrypt_buffer = buffer;
2492 c->callback = callback;
2493 c->cb_arg = callback_arg;
2494 evbits = UB_EV_READ | UB_EV_PERSIST;
2495 /* ub_event stuff */
2496 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2497 comm_point_udp_callback, c);
2498 if(c->ev->ev == NULL) {
2499 log_err("could not baseset udp event");
2500 comm_point_delete(c);
2503 if(fd!=-1 && ub_event_add(c->ev->ev, c->timeout) != 0 ) {
2504 log_err("could not add udp event");
2505 comm_point_delete(c);
2512 comm_point_create_udp_ancil(struct comm_base *base, int fd,
2513 sldns_buffer* buffer,
2514 comm_point_callback_type* callback, void* callback_arg)
2516 struct comm_point* c = (struct comm_point*)calloc(1,
2517 sizeof(struct comm_point));
2521 c->ev = (struct internal_event*)calloc(1,
2522 sizeof(struct internal_event));
2531 c->tcp_is_reading = 0;
2532 c->tcp_byte_count = 0;
2533 c->tcp_parent = NULL;
2534 c->max_tcp_count = 0;
2535 c->cur_tcp_count = 0;
2536 c->tcp_handlers = NULL;
2539 c->tcp_do_close = 0;
2540 c->do_not_close = 0;
2543 c->dnscrypt_buffer = buffer;
2546 c->tcp_do_toggle_rw = 0;
2547 c->tcp_check_nb_connect = 0;
2548 #ifdef USE_MSG_FASTOPEN
2549 c->tcp_do_fastopen = 0;
2551 c->callback = callback;
2552 c->cb_arg = callback_arg;
2553 evbits = UB_EV_READ | UB_EV_PERSIST;
2554 /* ub_event stuff */
2555 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2556 comm_point_udp_ancil_callback, c);
2557 if(c->ev->ev == NULL) {
2558 log_err("could not baseset udp event");
2559 comm_point_delete(c);
2562 if(fd!=-1 && ub_event_add(c->ev->ev, c->timeout) != 0 ) {
2563 log_err("could not add udp event");
2564 comm_point_delete(c);
2570 static struct comm_point*
2571 comm_point_create_tcp_handler(struct comm_base *base,
2572 struct comm_point* parent, size_t bufsize,
2573 struct sldns_buffer* spoolbuf, comm_point_callback_type* callback,
2576 struct comm_point* c = (struct comm_point*)calloc(1,
2577 sizeof(struct comm_point));
2581 c->ev = (struct internal_event*)calloc(1,
2582 sizeof(struct internal_event));
2589 c->buffer = sldns_buffer_new(bufsize);
2595 c->timeout = (struct timeval*)malloc(sizeof(struct timeval));
2597 sldns_buffer_free(c->buffer);
2602 c->tcp_is_reading = 0;
2603 c->tcp_byte_count = 0;
2604 c->tcp_parent = parent;
2605 c->tcp_timeout_msec = parent->tcp_timeout_msec;
2606 c->tcp_conn_limit = parent->tcp_conn_limit;
2608 c->tcp_keepalive = 0;
2609 c->max_tcp_count = 0;
2610 c->cur_tcp_count = 0;
2611 c->tcp_handlers = NULL;
2614 c->tcp_do_close = 0;
2615 c->do_not_close = 0;
2616 c->tcp_do_toggle_rw = 1;
2617 c->tcp_check_nb_connect = 0;
2618 #ifdef USE_MSG_FASTOPEN
2619 c->tcp_do_fastopen = 0;
2623 /* We don't know just yet if this is a dnscrypt channel. Allocation
2624 * will be done when handling the callback. */
2625 c->dnscrypt_buffer = c->buffer;
2628 c->callback = callback;
2629 c->cb_arg = callback_arg;
2631 c->tcp_req_info = tcp_req_info_create(spoolbuf);
2632 if(!c->tcp_req_info) {
2633 log_err("could not create tcp commpoint");
2634 sldns_buffer_free(c->buffer);
2640 c->tcp_req_info->cp = c;
2641 c->tcp_do_close = 1;
2642 c->tcp_do_toggle_rw = 0;
2644 /* add to parent free list */
2645 c->tcp_free = parent->tcp_free;
2646 parent->tcp_free = c;
2647 /* ub_event stuff */
2648 evbits = UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT;
2649 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2650 comm_point_tcp_handle_callback, c);
2651 if(c->ev->ev == NULL)
2653 log_err("could not basetset tcphdl event");
2654 parent->tcp_free = c->tcp_free;
2655 tcp_req_info_delete(c->tcp_req_info);
2656 sldns_buffer_free(c->buffer);
2666 comm_point_create_tcp(struct comm_base *base, int fd, int num,
2667 int idle_timeout, struct tcl_list* tcp_conn_limit, size_t bufsize,
2668 struct sldns_buffer* spoolbuf, comm_point_callback_type* callback,
2671 struct comm_point* c = (struct comm_point*)calloc(1,
2672 sizeof(struct comm_point));
2675 /* first allocate the TCP accept listener */
2678 c->ev = (struct internal_event*)calloc(1,
2679 sizeof(struct internal_event));
2688 c->tcp_is_reading = 0;
2689 c->tcp_byte_count = 0;
2690 c->tcp_timeout_msec = idle_timeout;
2691 c->tcp_conn_limit = tcp_conn_limit;
2693 c->tcp_keepalive = 0;
2694 c->tcp_parent = NULL;
2695 c->max_tcp_count = num;
2696 c->cur_tcp_count = 0;
2697 c->tcp_handlers = (struct comm_point**)calloc((size_t)num,
2698 sizeof(struct comm_point*));
2699 if(!c->tcp_handlers) {
2705 c->type = comm_tcp_accept;
2706 c->tcp_do_close = 0;
2707 c->do_not_close = 0;
2708 c->tcp_do_toggle_rw = 0;
2709 c->tcp_check_nb_connect = 0;
2710 #ifdef USE_MSG_FASTOPEN
2711 c->tcp_do_fastopen = 0;
2715 c->dnscrypt_buffer = NULL;
2719 evbits = UB_EV_READ | UB_EV_PERSIST;
2720 /* ub_event stuff */
2721 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2722 comm_point_tcp_accept_callback, c);
2723 if(c->ev->ev == NULL) {
2724 log_err("could not baseset tcpacc event");
2725 comm_point_delete(c);
2728 if (ub_event_add(c->ev->ev, c->timeout) != 0) {
2729 log_err("could not add tcpacc event");
2730 comm_point_delete(c);
2733 /* now prealloc the tcp handlers */
2734 for(i=0; i<num; i++) {
2735 c->tcp_handlers[i] = comm_point_create_tcp_handler(base,
2736 c, bufsize, spoolbuf, callback, callback_arg);
2737 if(!c->tcp_handlers[i]) {
2738 comm_point_delete(c);
2747 comm_point_create_tcp_out(struct comm_base *base, size_t bufsize,
2748 comm_point_callback_type* callback, void* callback_arg)
2750 struct comm_point* c = (struct comm_point*)calloc(1,
2751 sizeof(struct comm_point));
2755 c->ev = (struct internal_event*)calloc(1,
2756 sizeof(struct internal_event));
2763 c->buffer = sldns_buffer_new(bufsize);
2770 c->tcp_is_reading = 0;
2771 c->tcp_byte_count = 0;
2772 c->tcp_timeout_msec = TCP_QUERY_TIMEOUT;
2773 c->tcp_conn_limit = NULL;
2775 c->tcp_keepalive = 0;
2776 c->tcp_parent = NULL;
2777 c->max_tcp_count = 0;
2778 c->cur_tcp_count = 0;
2779 c->tcp_handlers = NULL;
2782 c->tcp_do_close = 0;
2783 c->do_not_close = 0;
2784 c->tcp_do_toggle_rw = 1;
2785 c->tcp_check_nb_connect = 1;
2786 #ifdef USE_MSG_FASTOPEN
2787 c->tcp_do_fastopen = 1;
2791 c->dnscrypt_buffer = c->buffer;
2794 c->callback = callback;
2795 c->cb_arg = callback_arg;
2796 evbits = UB_EV_PERSIST | UB_EV_WRITE;
2797 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2798 comm_point_tcp_handle_callback, c);
2799 if(c->ev->ev == NULL)
2801 log_err("could not baseset tcpout event");
2802 sldns_buffer_free(c->buffer);
2812 comm_point_create_http_out(struct comm_base *base, size_t bufsize,
2813 comm_point_callback_type* callback, void* callback_arg,
2816 struct comm_point* c = (struct comm_point*)calloc(1,
2817 sizeof(struct comm_point));
2821 c->ev = (struct internal_event*)calloc(1,
2822 sizeof(struct internal_event));
2829 c->buffer = sldns_buffer_new(bufsize);
2836 c->tcp_is_reading = 0;
2837 c->tcp_byte_count = 0;
2838 c->tcp_parent = NULL;
2839 c->max_tcp_count = 0;
2840 c->cur_tcp_count = 0;
2841 c->tcp_handlers = NULL;
2843 c->type = comm_http;
2844 c->tcp_do_close = 0;
2845 c->do_not_close = 0;
2846 c->tcp_do_toggle_rw = 1;
2847 c->tcp_check_nb_connect = 1;
2848 c->http_in_headers = 1;
2849 c->http_in_chunk_headers = 0;
2850 c->http_is_chunked = 0;
2851 c->http_temp = temp;
2852 #ifdef USE_MSG_FASTOPEN
2853 c->tcp_do_fastopen = 1;
2857 c->dnscrypt_buffer = c->buffer;
2860 c->callback = callback;
2861 c->cb_arg = callback_arg;
2862 evbits = UB_EV_PERSIST | UB_EV_WRITE;
2863 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2864 comm_point_http_handle_callback, c);
2865 if(c->ev->ev == NULL)
2867 log_err("could not baseset tcpout event");
2871 sldns_buffer_free(c->buffer);
2881 comm_point_create_local(struct comm_base *base, int fd, size_t bufsize,
2882 comm_point_callback_type* callback, void* callback_arg)
2884 struct comm_point* c = (struct comm_point*)calloc(1,
2885 sizeof(struct comm_point));
2889 c->ev = (struct internal_event*)calloc(1,
2890 sizeof(struct internal_event));
2897 c->buffer = sldns_buffer_new(bufsize);
2904 c->tcp_is_reading = 1;
2905 c->tcp_byte_count = 0;
2906 c->tcp_parent = NULL;
2907 c->max_tcp_count = 0;
2908 c->cur_tcp_count = 0;
2909 c->tcp_handlers = NULL;
2911 c->type = comm_local;
2912 c->tcp_do_close = 0;
2913 c->do_not_close = 1;
2914 c->tcp_do_toggle_rw = 0;
2915 c->tcp_check_nb_connect = 0;
2916 #ifdef USE_MSG_FASTOPEN
2917 c->tcp_do_fastopen = 0;
2921 c->dnscrypt_buffer = c->buffer;
2923 c->callback = callback;
2924 c->cb_arg = callback_arg;
2925 /* ub_event stuff */
2926 evbits = UB_EV_PERSIST | UB_EV_READ;
2927 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2928 comm_point_local_handle_callback, c);
2929 if(c->ev->ev == NULL) {
2930 log_err("could not baseset localhdl event");
2935 if (ub_event_add(c->ev->ev, c->timeout) != 0) {
2936 log_err("could not add localhdl event");
2937 ub_event_free(c->ev->ev);
2946 comm_point_create_raw(struct comm_base* base, int fd, int writing,
2947 comm_point_callback_type* callback, void* callback_arg)
2949 struct comm_point* c = (struct comm_point*)calloc(1,
2950 sizeof(struct comm_point));
2954 c->ev = (struct internal_event*)calloc(1,
2955 sizeof(struct internal_event));
2964 c->tcp_is_reading = 0;
2965 c->tcp_byte_count = 0;
2966 c->tcp_parent = NULL;
2967 c->max_tcp_count = 0;
2968 c->cur_tcp_count = 0;
2969 c->tcp_handlers = NULL;
2972 c->tcp_do_close = 0;
2973 c->do_not_close = 1;
2974 c->tcp_do_toggle_rw = 0;
2975 c->tcp_check_nb_connect = 0;
2976 #ifdef USE_MSG_FASTOPEN
2977 c->tcp_do_fastopen = 0;
2981 c->dnscrypt_buffer = c->buffer;
2983 c->callback = callback;
2984 c->cb_arg = callback_arg;
2985 /* ub_event stuff */
2987 evbits = UB_EV_PERSIST | UB_EV_WRITE;
2988 else evbits = UB_EV_PERSIST | UB_EV_READ;
2989 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2990 comm_point_raw_handle_callback, c);
2991 if(c->ev->ev == NULL) {
2992 log_err("could not baseset rawhdl event");
2997 if (ub_event_add(c->ev->ev, c->timeout) != 0) {
2998 log_err("could not add rawhdl event");
2999 ub_event_free(c->ev->ev);
3008 comm_point_close(struct comm_point* c)
3013 if(ub_event_del(c->ev->ev) != 0) {
3014 log_err("could not event_del on close");
3017 tcl_close_connection(c->tcl_addr);
3019 tcp_req_info_clear(c->tcp_req_info);
3020 /* close fd after removing from event lists, or epoll.. is messed up */
3021 if(c->fd != -1 && !c->do_not_close) {
3022 if(c->type == comm_tcp || c->type == comm_http) {
3023 /* delete sticky events for the fd, it gets closed */
3024 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
3025 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
3027 verbose(VERB_ALGO, "close fd %d", c->fd);
3038 comm_point_delete(struct comm_point* c)
3042 if((c->type == comm_tcp || c->type == comm_http) && c->ssl) {
3044 SSL_shutdown(c->ssl);
3048 comm_point_close(c);
3049 if(c->tcp_handlers) {
3051 for(i=0; i<c->max_tcp_count; i++)
3052 comm_point_delete(c->tcp_handlers[i]);
3053 free(c->tcp_handlers);
3056 if(c->type == comm_tcp || c->type == comm_local || c->type == comm_http) {
3057 sldns_buffer_free(c->buffer);
3059 if(c->dnscrypt && c->dnscrypt_buffer != c->buffer) {
3060 sldns_buffer_free(c->dnscrypt_buffer);
3063 if(c->tcp_req_info) {
3064 tcp_req_info_delete(c->tcp_req_info);
3067 ub_event_free(c->ev->ev);
3073 comm_point_send_reply(struct comm_reply *repinfo)
3075 struct sldns_buffer* buffer;
3076 log_assert(repinfo && repinfo->c);
3078 buffer = repinfo->c->dnscrypt_buffer;
3079 if(!dnsc_handle_uncurved_request(repinfo)) {
3083 buffer = repinfo->c->buffer;
3085 if(repinfo->c->type == comm_udp) {
3086 if(repinfo->srctype)
3087 comm_point_send_udp_msg_if(repinfo->c,
3088 buffer, (struct sockaddr*)&repinfo->addr,
3089 repinfo->addrlen, repinfo);
3091 comm_point_send_udp_msg(repinfo->c, buffer,
3092 (struct sockaddr*)&repinfo->addr, repinfo->addrlen);
3094 if(repinfo->c->dtenv != NULL &&
3095 repinfo->c->dtenv->log_client_response_messages)
3096 dt_msg_send_client_response(repinfo->c->dtenv,
3097 &repinfo->addr, repinfo->c->type, repinfo->c->buffer);
3101 if(repinfo->c->tcp_parent->dtenv != NULL &&
3102 repinfo->c->tcp_parent->dtenv->log_client_response_messages)
3103 dt_msg_send_client_response(repinfo->c->tcp_parent->dtenv,
3104 &repinfo->addr, repinfo->c->type, repinfo->c->buffer);
3106 if(repinfo->c->tcp_req_info) {
3107 tcp_req_info_send_reply(repinfo->c->tcp_req_info);
3109 comm_point_start_listening(repinfo->c, -1,
3110 repinfo->c->tcp_timeout_msec);
3116 comm_point_drop_reply(struct comm_reply* repinfo)
3120 log_assert(repinfo && repinfo->c);
3121 log_assert(repinfo->c->type != comm_tcp_accept);
3122 if(repinfo->c->type == comm_udp)
3124 if(repinfo->c->tcp_req_info)
3125 repinfo->c->tcp_req_info->is_drop = 1;
3126 reclaim_tcp_handler(repinfo->c);
3130 comm_point_stop_listening(struct comm_point* c)
3132 verbose(VERB_ALGO, "comm point stop listening %d", c->fd);
3133 if(ub_event_del(c->ev->ev) != 0) {
3134 log_err("event_del error to stoplisten");
3139 comm_point_start_listening(struct comm_point* c, int newfd, int msec)
3141 verbose(VERB_ALGO, "comm point start listening %d",
3142 c->fd==-1?newfd:c->fd);
3143 if(c->type == comm_tcp_accept && !c->tcp_free) {
3144 /* no use to start listening no free slots. */
3147 if(msec != -1 && msec != 0) {
3149 c->timeout = (struct timeval*)malloc(sizeof(
3152 log_err("cpsl: malloc failed. No net read.");
3156 ub_event_add_bits(c->ev->ev, UB_EV_TIMEOUT);
3157 #ifndef S_SPLINT_S /* splint fails on struct timeval. */
3158 c->timeout->tv_sec = msec/1000;
3159 c->timeout->tv_usec = (msec%1000)*1000;
3160 #endif /* S_SPLINT_S */
3162 if(c->type == comm_tcp || c->type == comm_http) {
3163 ub_event_del_bits(c->ev->ev, UB_EV_READ|UB_EV_WRITE);
3164 if(c->tcp_is_reading)
3165 ub_event_add_bits(c->ev->ev, UB_EV_READ);
3166 else ub_event_add_bits(c->ev->ev, UB_EV_WRITE);
3177 ub_event_set_fd(c->ev->ev, c->fd);
3179 if(ub_event_add(c->ev->ev, msec==0?NULL:c->timeout) != 0) {
3180 log_err("event_add failed. in cpsl.");
3184 void comm_point_listen_for_rw(struct comm_point* c, int rd, int wr)
3186 verbose(VERB_ALGO, "comm point listen_for_rw %d %d", c->fd, wr);
3187 if(ub_event_del(c->ev->ev) != 0) {
3188 log_err("event_del error to cplf");
3190 ub_event_del_bits(c->ev->ev, UB_EV_READ|UB_EV_WRITE);
3191 if(rd) ub_event_add_bits(c->ev->ev, UB_EV_READ);
3192 if(wr) ub_event_add_bits(c->ev->ev, UB_EV_WRITE);
3193 if(ub_event_add(c->ev->ev, c->timeout) != 0) {
3194 log_err("event_add failed. in cplf.");
3198 size_t comm_point_get_mem(struct comm_point* c)
3203 s = sizeof(*c) + sizeof(*c->ev);
3205 s += sizeof(*c->timeout);
3206 if(c->type == comm_tcp || c->type == comm_local) {
3207 s += sizeof(*c->buffer) + sldns_buffer_capacity(c->buffer);
3209 s += sizeof(*c->dnscrypt_buffer);
3210 if(c->buffer != c->dnscrypt_buffer) {
3211 s += sldns_buffer_capacity(c->dnscrypt_buffer);
3215 if(c->type == comm_tcp_accept) {
3217 for(i=0; i<c->max_tcp_count; i++)
3218 s += comm_point_get_mem(c->tcp_handlers[i]);
3224 comm_timer_create(struct comm_base* base, void (*cb)(void*), void* cb_arg)
3226 struct internal_timer *tm = (struct internal_timer*)calloc(1,
3227 sizeof(struct internal_timer));
3229 log_err("malloc failed");
3232 tm->super.ev_timer = tm;
3234 tm->super.callback = cb;
3235 tm->super.cb_arg = cb_arg;
3236 tm->ev = ub_event_new(base->eb->base, -1, UB_EV_TIMEOUT,
3237 comm_timer_callback, &tm->super);
3238 if(tm->ev == NULL) {
3239 log_err("timer_create: event_base_set failed.");
3247 comm_timer_disable(struct comm_timer* timer)
3251 ub_timer_del(timer->ev_timer->ev);
3252 timer->ev_timer->enabled = 0;
3256 comm_timer_set(struct comm_timer* timer, struct timeval* tv)
3259 if(timer->ev_timer->enabled)
3260 comm_timer_disable(timer);
3261 if(ub_timer_add(timer->ev_timer->ev, timer->ev_timer->base->eb->base,
3262 comm_timer_callback, timer, tv) != 0)
3263 log_err("comm_timer_set: evtimer_add failed.");
3264 timer->ev_timer->enabled = 1;
3268 comm_timer_delete(struct comm_timer* timer)
3272 comm_timer_disable(timer);
3273 /* Free the sub struct timer->ev_timer derived from the super struct timer.
3274 * i.e. assert(timer == timer->ev_timer)
3276 ub_event_free(timer->ev_timer->ev);
3277 free(timer->ev_timer);
3281 comm_timer_callback(int ATTR_UNUSED(fd), short event, void* arg)
3283 struct comm_timer* tm = (struct comm_timer*)arg;
3284 if(!(event&UB_EV_TIMEOUT))
3286 ub_comm_base_now(tm->ev_timer->base);
3287 tm->ev_timer->enabled = 0;
3288 fptr_ok(fptr_whitelist_comm_timer(tm->callback));
3289 (*tm->callback)(tm->cb_arg);
3293 comm_timer_is_set(struct comm_timer* timer)
3295 return (int)timer->ev_timer->enabled;
3299 comm_timer_get_mem(struct comm_timer* ATTR_UNUSED(timer))
3301 return sizeof(struct internal_timer);
3305 comm_signal_create(struct comm_base* base,
3306 void (*callback)(int, void*), void* cb_arg)
3308 struct comm_signal* com = (struct comm_signal*)malloc(
3309 sizeof(struct comm_signal));
3311 log_err("malloc failed");
3315 com->callback = callback;
3316 com->cb_arg = cb_arg;
3317 com->ev_signal = NULL;
3322 comm_signal_callback(int sig, short event, void* arg)
3324 struct comm_signal* comsig = (struct comm_signal*)arg;
3325 if(!(event & UB_EV_SIGNAL))
3327 ub_comm_base_now(comsig->base);
3328 fptr_ok(fptr_whitelist_comm_signal(comsig->callback));
3329 (*comsig->callback)(sig, comsig->cb_arg);
3333 comm_signal_bind(struct comm_signal* comsig, int sig)
3335 struct internal_signal* entry = (struct internal_signal*)calloc(1,
3336 sizeof(struct internal_signal));
3338 log_err("malloc failed");
3342 /* add signal event */
3343 entry->ev = ub_signal_new(comsig->base->eb->base, sig,
3344 comm_signal_callback, comsig);
3345 if(entry->ev == NULL) {
3346 log_err("Could not create signal event");
3350 if(ub_signal_add(entry->ev, NULL) != 0) {
3351 log_err("Could not add signal handler");
3352 ub_event_free(entry->ev);
3356 /* link into list */
3357 entry->next = comsig->ev_signal;
3358 comsig->ev_signal = entry;
3363 comm_signal_delete(struct comm_signal* comsig)
3365 struct internal_signal* p, *np;
3368 p=comsig->ev_signal;
3371 ub_signal_del(p->ev);
3372 ub_event_free(p->ev);