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/fptr_wlist.h"
47 #include "sldns/pkthdr.h"
48 #include "sldns/sbuffer.h"
49 #include "sldns/str2wire.h"
50 #include "dnstap/dnstap.h"
51 #include "dnscrypt/dnscrypt.h"
52 #ifdef HAVE_OPENSSL_SSL_H
53 #include <openssl/ssl.h>
55 #ifdef HAVE_OPENSSL_ERR_H
56 #include <openssl/err.h>
59 /* -------- Start of local definitions -------- */
60 /** if CMSG_ALIGN is not defined on this platform, a workaround */
63 # define CMSG_ALIGN(n) __CMSG_ALIGN(n)
64 # elif defined(CMSG_DATA_ALIGN)
65 # define CMSG_ALIGN _CMSG_DATA_ALIGN
67 # define CMSG_ALIGN(len) (((len)+sizeof(long)-1) & ~(sizeof(long)-1))
71 /** if CMSG_LEN is not defined on this platform, a workaround */
73 # define CMSG_LEN(len) (CMSG_ALIGN(sizeof(struct cmsghdr))+(len))
76 /** if CMSG_SPACE is not defined on this platform, a workaround */
78 # ifdef _CMSG_HDR_ALIGN
79 # define CMSG_SPACE(l) (CMSG_ALIGN(l)+_CMSG_HDR_ALIGN(sizeof(struct cmsghdr)))
81 # define CMSG_SPACE(l) (CMSG_ALIGN(l)+CMSG_ALIGN(sizeof(struct cmsghdr)))
85 /** The TCP reading or writing query timeout in milliseconds */
86 #define TCP_QUERY_TIMEOUT 120000
87 /** The TCP timeout in msec for fast queries, above half are used */
88 #define TCP_QUERY_TIMEOUT_FAST 200
90 #ifndef NONBLOCKING_IS_BROKEN
91 /** number of UDP reads to perform per read indication from select */
92 #define NUM_UDP_PER_SELECT 100
94 #define NUM_UDP_PER_SELECT 1
98 * The internal event structure for keeping ub_event info for the event.
99 * Possibly other structures (list, tree) this is part of.
101 struct internal_event {
103 struct comm_base* base;
104 /** ub_event event type */
109 * Internal base structure, so that every thread has its own events.
111 struct internal_base {
112 /** ub_event event_base type. */
113 struct ub_event_base* base;
114 /** seconds time pointer points here */
116 /** timeval with current time */
118 /** the event used for slow_accept timeouts */
119 struct ub_event* slow_accept;
120 /** true if slow_accept is enabled */
121 int slow_accept_enabled;
125 * Internal timer structure, to store timer event in.
127 struct internal_timer {
128 /** the super struct from which derived */
129 struct comm_timer super;
131 struct comm_base* base;
132 /** ub_event event type */
134 /** is timer enabled */
139 * Internal signal structure, to store signal event in.
141 struct internal_signal {
142 /** ub_event event type */
144 /** next in signal list */
145 struct internal_signal* next;
148 /** create a tcp handler with a parent */
149 static struct comm_point* comm_point_create_tcp_handler(
150 struct comm_base *base, struct comm_point* parent, size_t bufsize,
151 comm_point_callback_type* callback, void* callback_arg);
153 /* -------- End of local definitions -------- */
156 comm_base_create(int sigs)
158 struct comm_base* b = (struct comm_base*)calloc(1,
159 sizeof(struct comm_base));
160 const char *evnm="event", *evsys="", *evmethod="";
164 b->eb = (struct internal_base*)calloc(1, sizeof(struct internal_base));
169 b->eb->base = ub_default_event_base(sigs, &b->eb->secs, &b->eb->now);
176 ub_get_event_sys(b->eb->base, &evnm, &evsys, &evmethod);
177 verbose(VERB_ALGO, "%s %s user %s method.", evnm, evsys, evmethod);
182 comm_base_create_event(struct ub_event_base* base)
184 struct comm_base* b = (struct comm_base*)calloc(1,
185 sizeof(struct comm_base));
188 b->eb = (struct internal_base*)calloc(1, sizeof(struct internal_base));
199 comm_base_delete(struct comm_base* b)
203 if(b->eb->slow_accept_enabled) {
204 if(ub_event_del(b->eb->slow_accept) != 0) {
205 log_err("could not event_del slow_accept");
207 ub_event_free(b->eb->slow_accept);
209 ub_event_base_free(b->eb->base);
216 comm_base_delete_no_base(struct comm_base* b)
220 if(b->eb->slow_accept_enabled) {
221 if(ub_event_del(b->eb->slow_accept) != 0) {
222 log_err("could not event_del slow_accept");
224 ub_event_free(b->eb->slow_accept);
232 comm_base_timept(struct comm_base* b, time_t** tt, struct timeval** tv)
239 comm_base_dispatch(struct comm_base* b)
242 retval = ub_event_base_dispatch(b->eb->base);
244 fatal_exit("event_dispatch returned error %d, "
245 "errno is %s", retval, strerror(errno));
249 void comm_base_exit(struct comm_base* b)
251 if(ub_event_base_loopexit(b->eb->base) != 0) {
252 log_err("Could not loopexit");
256 void comm_base_set_slow_accept_handlers(struct comm_base* b,
257 void (*stop_acc)(void*), void (*start_acc)(void*), void* arg)
259 b->stop_accept = stop_acc;
260 b->start_accept = start_acc;
264 struct ub_event_base* comm_base_internal(struct comm_base* b)
269 /** see if errno for udp has to be logged or not uses globals */
271 udp_send_errno_needs_log(struct sockaddr* addr, socklen_t addrlen)
273 /* do not log transient errors (unless high verbosity) */
274 #if defined(ENETUNREACH) || defined(EHOSTDOWN) || defined(EHOSTUNREACH) || defined(ENETDOWN)
288 if(verbosity < VERB_ALGO)
294 /* permission denied is gotten for every send if the
295 * network is disconnected (on some OS), squelch it */
296 if( ((errno == EPERM)
297 # ifdef EADDRNOTAVAIL
298 /* 'Cannot assign requested address' also when disconnected */
299 || (errno == EADDRNOTAVAIL)
301 ) && verbosity < VERB_DETAIL)
304 /* If SO_REUSEADDR is set, we could try to connect to the same server
305 * from the same source port twice. */
306 if(errno == EADDRINUSE && verbosity < VERB_DETAIL)
309 /* squelch errors where people deploy AAAA ::ffff:bla for
310 * authority servers, which we try for intranets. */
311 if(errno == EINVAL && addr_is_ip4mapped(
312 (struct sockaddr_storage*)addr, addrlen) &&
313 verbosity < VERB_DETAIL)
315 /* SO_BROADCAST sockopt can give access to 255.255.255.255,
316 * but a dns cache does not need it. */
317 if(errno == EACCES && addr_is_broadcast(
318 (struct sockaddr_storage*)addr, addrlen) &&
319 verbosity < VERB_DETAIL)
324 int tcp_connect_errno_needs_log(struct sockaddr* addr, socklen_t addrlen)
326 return udp_send_errno_needs_log(addr, addrlen);
329 /* send a UDP reply */
331 comm_point_send_udp_msg(struct comm_point *c, sldns_buffer* packet,
332 struct sockaddr* addr, socklen_t addrlen)
335 log_assert(c->fd != -1);
337 if(sldns_buffer_remaining(packet) == 0)
338 log_err("error: send empty UDP packet");
340 log_assert(addr && addrlen > 0);
341 sent = sendto(c->fd, (void*)sldns_buffer_begin(packet),
342 sldns_buffer_remaining(packet), 0,
345 /* try again and block, waiting for IO to complete,
346 * we want to send the answer, and we will wait for
347 * the ethernet interface buffer to have space. */
349 if(errno == EAGAIN ||
351 errno == EWOULDBLOCK ||
355 if(WSAGetLastError() == WSAEINPROGRESS ||
356 WSAGetLastError() == WSAENOBUFS ||
357 WSAGetLastError() == WSAEWOULDBLOCK) {
361 sent = sendto(c->fd, (void*)sldns_buffer_begin(packet),
362 sldns_buffer_remaining(packet), 0,
365 fd_set_nonblock(c->fd);
370 if(!udp_send_errno_needs_log(addr, addrlen))
373 verbose(VERB_OPS, "sendto failed: %s", strerror(errno));
375 verbose(VERB_OPS, "sendto failed: %s",
376 wsa_strerror(WSAGetLastError()));
378 log_addr(VERB_OPS, "remote address is",
379 (struct sockaddr_storage*)addr, addrlen);
381 } else if((size_t)sent != sldns_buffer_remaining(packet)) {
382 log_err("sent %d in place of %d bytes",
383 (int)sent, (int)sldns_buffer_remaining(packet));
389 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && (defined(HAVE_RECVMSG) || defined(HAVE_SENDMSG))
390 /** print debug ancillary info */
391 static void p_ancil(const char* str, struct comm_reply* r)
393 if(r->srctype != 4 && r->srctype != 6) {
394 log_info("%s: unknown srctype %d", str, r->srctype);
397 if(r->srctype == 6) {
399 if(inet_ntop(AF_INET6, &r->pktinfo.v6info.ipi6_addr,
400 buf, (socklen_t)sizeof(buf)) == 0) {
401 (void)strlcpy(buf, "(inet_ntop error)", sizeof(buf));
403 buf[sizeof(buf)-1]=0;
404 log_info("%s: %s %d", str, buf, r->pktinfo.v6info.ipi6_ifindex);
405 } else if(r->srctype == 4) {
407 char buf1[1024], buf2[1024];
408 if(inet_ntop(AF_INET, &r->pktinfo.v4info.ipi_addr,
409 buf1, (socklen_t)sizeof(buf1)) == 0) {
410 (void)strlcpy(buf1, "(inet_ntop error)", sizeof(buf1));
412 buf1[sizeof(buf1)-1]=0;
413 #ifdef HAVE_STRUCT_IN_PKTINFO_IPI_SPEC_DST
414 if(inet_ntop(AF_INET, &r->pktinfo.v4info.ipi_spec_dst,
415 buf2, (socklen_t)sizeof(buf2)) == 0) {
416 (void)strlcpy(buf2, "(inet_ntop error)", sizeof(buf2));
418 buf2[sizeof(buf2)-1]=0;
422 log_info("%s: %d %s %s", str, r->pktinfo.v4info.ipi_ifindex,
424 #elif defined(IP_RECVDSTADDR)
426 if(inet_ntop(AF_INET, &r->pktinfo.v4addr,
427 buf1, (socklen_t)sizeof(buf1)) == 0) {
428 (void)strlcpy(buf1, "(inet_ntop error)", sizeof(buf1));
430 buf1[sizeof(buf1)-1]=0;
431 log_info("%s: %s", str, buf1);
432 #endif /* IP_PKTINFO or PI_RECVDSTDADDR */
435 #endif /* AF_INET6 && IPV6_PKTINFO && HAVE_RECVMSG||HAVE_SENDMSG */
437 /** send a UDP reply over specified interface*/
439 comm_point_send_udp_msg_if(struct comm_point *c, sldns_buffer* packet,
440 struct sockaddr* addr, socklen_t addrlen, struct comm_reply* r)
442 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && defined(HAVE_SENDMSG)
448 struct cmsghdr *cmsg;
449 #endif /* S_SPLINT_S */
451 log_assert(c->fd != -1);
453 if(sldns_buffer_remaining(packet) == 0)
454 log_err("error: send empty UDP packet");
456 log_assert(addr && addrlen > 0);
459 msg.msg_namelen = addrlen;
460 iov[0].iov_base = sldns_buffer_begin(packet);
461 iov[0].iov_len = sldns_buffer_remaining(packet);
464 msg.msg_control = control;
466 msg.msg_controllen = sizeof(control);
467 #endif /* S_SPLINT_S */
471 cmsg = CMSG_FIRSTHDR(&msg);
472 if(r->srctype == 4) {
475 msg.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
476 log_assert(msg.msg_controllen <= sizeof(control));
477 cmsg->cmsg_level = IPPROTO_IP;
478 cmsg->cmsg_type = IP_PKTINFO;
479 memmove(CMSG_DATA(cmsg), &r->pktinfo.v4info,
480 sizeof(struct in_pktinfo));
481 /* unset the ifindex to not bypass the routing tables */
482 cmsg_data = CMSG_DATA(cmsg);
483 ((struct in_pktinfo *) cmsg_data)->ipi_ifindex = 0;
484 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
485 #elif defined(IP_SENDSRCADDR)
486 msg.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
487 log_assert(msg.msg_controllen <= sizeof(control));
488 cmsg->cmsg_level = IPPROTO_IP;
489 cmsg->cmsg_type = IP_SENDSRCADDR;
490 memmove(CMSG_DATA(cmsg), &r->pktinfo.v4addr,
491 sizeof(struct in_addr));
492 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
494 verbose(VERB_ALGO, "no IP_PKTINFO or IP_SENDSRCADDR");
495 msg.msg_control = NULL;
496 #endif /* IP_PKTINFO or IP_SENDSRCADDR */
497 } else if(r->srctype == 6) {
499 msg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
500 log_assert(msg.msg_controllen <= sizeof(control));
501 cmsg->cmsg_level = IPPROTO_IPV6;
502 cmsg->cmsg_type = IPV6_PKTINFO;
503 memmove(CMSG_DATA(cmsg), &r->pktinfo.v6info,
504 sizeof(struct in6_pktinfo));
505 /* unset the ifindex to not bypass the routing tables */
506 cmsg_data = CMSG_DATA(cmsg);
507 ((struct in6_pktinfo *) cmsg_data)->ipi6_ifindex = 0;
508 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
510 /* try to pass all 0 to use default route */
511 msg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
512 log_assert(msg.msg_controllen <= sizeof(control));
513 cmsg->cmsg_level = IPPROTO_IPV6;
514 cmsg->cmsg_type = IPV6_PKTINFO;
515 memset(CMSG_DATA(cmsg), 0, sizeof(struct in6_pktinfo));
516 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
518 #endif /* S_SPLINT_S */
519 if(verbosity >= VERB_ALGO)
520 p_ancil("send_udp over interface", r);
521 sent = sendmsg(c->fd, &msg, 0);
523 /* try again and block, waiting for IO to complete,
524 * we want to send the answer, and we will wait for
525 * the ethernet interface buffer to have space. */
527 if(errno == EAGAIN ||
529 errno == EWOULDBLOCK ||
533 if(WSAGetLastError() == WSAEINPROGRESS ||
534 WSAGetLastError() == WSAENOBUFS ||
535 WSAGetLastError() == WSAEWOULDBLOCK) {
539 sent = sendmsg(c->fd, &msg, 0);
541 fd_set_nonblock(c->fd);
546 if(!udp_send_errno_needs_log(addr, addrlen))
548 verbose(VERB_OPS, "sendmsg failed: %s", strerror(errno));
549 log_addr(VERB_OPS, "remote address is",
550 (struct sockaddr_storage*)addr, addrlen);
552 /* netbsd 7 has IP_PKTINFO for recv but not send */
553 if(errno == EINVAL && r->srctype == 4)
554 log_err("sendmsg: No support for sendmsg(IP_PKTINFO). "
555 "Please disable interface-automatic");
558 } else if((size_t)sent != sldns_buffer_remaining(packet)) {
559 log_err("sent %d in place of %d bytes",
560 (int)sent, (int)sldns_buffer_remaining(packet));
570 log_err("sendmsg: IPV6_PKTINFO not supported");
572 #endif /* AF_INET6 && IPV6_PKTINFO && HAVE_SENDMSG */
576 comm_point_udp_ancil_callback(int fd, short event, void* arg)
578 #if defined(AF_INET6) && defined(IPV6_PKTINFO) && defined(HAVE_RECVMSG)
579 struct comm_reply rep;
586 struct cmsghdr* cmsg;
587 #endif /* S_SPLINT_S */
589 rep.c = (struct comm_point*)arg;
590 log_assert(rep.c->type == comm_udp);
592 if(!(event&UB_EV_READ))
594 log_assert(rep.c && rep.c->buffer && rep.c->fd == fd);
595 ub_comm_base_now(rep.c->ev->base);
596 for(i=0; i<NUM_UDP_PER_SELECT; i++) {
597 sldns_buffer_clear(rep.c->buffer);
598 rep.addrlen = (socklen_t)sizeof(rep.addr);
599 log_assert(fd != -1);
600 log_assert(sldns_buffer_remaining(rep.c->buffer) > 0);
601 msg.msg_name = &rep.addr;
602 msg.msg_namelen = (socklen_t)sizeof(rep.addr);
603 iov[0].iov_base = sldns_buffer_begin(rep.c->buffer);
604 iov[0].iov_len = sldns_buffer_remaining(rep.c->buffer);
607 msg.msg_control = ancil;
609 msg.msg_controllen = sizeof(ancil);
610 #endif /* S_SPLINT_S */
612 rcv = recvmsg(fd, &msg, 0);
614 if(errno != EAGAIN && errno != EINTR) {
615 log_err("recvmsg failed: %s", strerror(errno));
619 rep.addrlen = msg.msg_namelen;
620 sldns_buffer_skip(rep.c->buffer, rcv);
621 sldns_buffer_flip(rep.c->buffer);
624 for(cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
625 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
626 if( cmsg->cmsg_level == IPPROTO_IPV6 &&
627 cmsg->cmsg_type == IPV6_PKTINFO) {
629 memmove(&rep.pktinfo.v6info, CMSG_DATA(cmsg),
630 sizeof(struct in6_pktinfo));
633 } else if( cmsg->cmsg_level == IPPROTO_IP &&
634 cmsg->cmsg_type == IP_PKTINFO) {
636 memmove(&rep.pktinfo.v4info, CMSG_DATA(cmsg),
637 sizeof(struct in_pktinfo));
639 #elif defined(IP_RECVDSTADDR)
640 } else if( cmsg->cmsg_level == IPPROTO_IP &&
641 cmsg->cmsg_type == IP_RECVDSTADDR) {
643 memmove(&rep.pktinfo.v4addr, CMSG_DATA(cmsg),
644 sizeof(struct in_addr));
646 #endif /* IP_PKTINFO or IP_RECVDSTADDR */
649 if(verbosity >= VERB_ALGO)
650 p_ancil("receive_udp on interface", &rep);
651 #endif /* S_SPLINT_S */
652 fptr_ok(fptr_whitelist_comm_point(rep.c->callback));
653 if((*rep.c->callback)(rep.c, rep.c->cb_arg, NETEVENT_NOERROR, &rep)) {
654 /* send back immediate reply */
655 (void)comm_point_send_udp_msg_if(rep.c, rep.c->buffer,
656 (struct sockaddr*)&rep.addr, rep.addrlen, &rep);
658 if(!rep.c || rep.c->fd == -1) /* commpoint closed */
665 fatal_exit("recvmsg: No support for IPV6_PKTINFO; IP_PKTINFO or IP_RECVDSTADDR. "
666 "Please disable interface-automatic");
667 #endif /* AF_INET6 && IPV6_PKTINFO && HAVE_RECVMSG */
671 comm_point_udp_callback(int fd, short event, void* arg)
673 struct comm_reply rep;
676 struct sldns_buffer *buffer;
678 rep.c = (struct comm_point*)arg;
679 log_assert(rep.c->type == comm_udp);
681 if(!(event&UB_EV_READ))
683 log_assert(rep.c && rep.c->buffer && rep.c->fd == fd);
684 ub_comm_base_now(rep.c->ev->base);
685 for(i=0; i<NUM_UDP_PER_SELECT; i++) {
686 sldns_buffer_clear(rep.c->buffer);
687 rep.addrlen = (socklen_t)sizeof(rep.addr);
688 log_assert(fd != -1);
689 log_assert(sldns_buffer_remaining(rep.c->buffer) > 0);
690 rcv = recvfrom(fd, (void*)sldns_buffer_begin(rep.c->buffer),
691 sldns_buffer_remaining(rep.c->buffer), 0,
692 (struct sockaddr*)&rep.addr, &rep.addrlen);
695 if(errno != EAGAIN && errno != EINTR)
696 log_err("recvfrom %d failed: %s",
697 fd, strerror(errno));
699 if(WSAGetLastError() != WSAEINPROGRESS &&
700 WSAGetLastError() != WSAECONNRESET &&
701 WSAGetLastError()!= WSAEWOULDBLOCK)
702 log_err("recvfrom failed: %s",
703 wsa_strerror(WSAGetLastError()));
707 sldns_buffer_skip(rep.c->buffer, rcv);
708 sldns_buffer_flip(rep.c->buffer);
710 fptr_ok(fptr_whitelist_comm_point(rep.c->callback));
711 if((*rep.c->callback)(rep.c, rep.c->cb_arg, NETEVENT_NOERROR, &rep)) {
712 /* send back immediate reply */
714 buffer = rep.c->dnscrypt_buffer;
716 buffer = rep.c->buffer;
718 (void)comm_point_send_udp_msg(rep.c, buffer,
719 (struct sockaddr*)&rep.addr, rep.addrlen);
721 if(!rep.c || rep.c->fd != fd) /* commpoint closed to -1 or reused for
722 another UDP port. Note rep.c cannot be reused with TCP fd. */
727 /** Use a new tcp handler for new query fd, set to read query */
729 setup_tcp_handler(struct comm_point* c, int fd, int cur, int max)
731 log_assert(c->type == comm_tcp);
732 log_assert(c->fd == -1);
733 sldns_buffer_clear(c->buffer);
736 sldns_buffer_clear(c->dnscrypt_buffer);
738 c->tcp_is_reading = 1;
739 c->tcp_byte_count = 0;
740 c->tcp_timeout_msec = TCP_QUERY_TIMEOUT;
741 /* if more than half the tcp handlers are in use, use a shorter
742 * timeout for this TCP connection, we need to make space for
743 * other connections to be able to get attention */
745 c->tcp_timeout_msec = TCP_QUERY_TIMEOUT_FAST;
746 comm_point_start_listening(c, fd, c->tcp_timeout_msec);
749 void comm_base_handle_slow_accept(int ATTR_UNUSED(fd),
750 short ATTR_UNUSED(event), void* arg)
752 struct comm_base* b = (struct comm_base*)arg;
753 /* timeout for the slow accept, re-enable accepts again */
754 if(b->start_accept) {
755 verbose(VERB_ALGO, "wait is over, slow accept disabled");
756 fptr_ok(fptr_whitelist_start_accept(b->start_accept));
757 (*b->start_accept)(b->cb_arg);
758 b->eb->slow_accept_enabled = 0;
762 int comm_point_perform_accept(struct comm_point* c,
763 struct sockaddr_storage* addr, socklen_t* addrlen)
766 *addrlen = (socklen_t)sizeof(*addr);
768 new_fd = accept(c->fd, (struct sockaddr*)addr, addrlen);
770 /* SOCK_NONBLOCK saves extra calls to fcntl for the same result */
771 new_fd = accept4(c->fd, (struct sockaddr*)addr, addrlen, SOCK_NONBLOCK);
775 /* EINTR is signal interrupt. others are closed connection. */
776 if( errno == EINTR || errno == EAGAIN
778 || errno == EWOULDBLOCK
781 || errno == ECONNABORTED
788 #if defined(ENFILE) && defined(EMFILE)
789 if(errno == ENFILE || errno == EMFILE) {
790 /* out of file descriptors, likely outside of our
791 * control. stop accept() calls for some time */
792 if(c->ev->base->stop_accept) {
793 struct comm_base* b = c->ev->base;
795 verbose(VERB_ALGO, "out of file descriptors: "
797 b->eb->slow_accept_enabled = 1;
798 fptr_ok(fptr_whitelist_stop_accept(
800 (*b->stop_accept)(b->cb_arg);
801 /* set timeout, no mallocs */
802 tv.tv_sec = NETEVENT_SLOW_ACCEPT_TIME/1000;
803 tv.tv_usec = (NETEVENT_SLOW_ACCEPT_TIME%1000)*1000;
804 b->eb->slow_accept = ub_event_new(b->eb->base,
806 comm_base_handle_slow_accept, b);
807 if(b->eb->slow_accept == NULL) {
808 /* we do not want to log here, because
809 * that would spam the logfiles.
810 * error: "event_base_set failed." */
812 else if(ub_event_add(b->eb->slow_accept, &tv)
814 /* we do not want to log here,
815 * error: "event_add failed." */
821 log_err_addr("accept failed", strerror(errno), addr, *addrlen);
822 #else /* USE_WINSOCK */
823 if(WSAGetLastError() == WSAEINPROGRESS ||
824 WSAGetLastError() == WSAECONNRESET)
826 if(WSAGetLastError() == WSAEWOULDBLOCK) {
827 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
830 log_err_addr("accept failed", wsa_strerror(WSAGetLastError()),
836 fd_set_nonblock(new_fd);
842 static long win_bio_cb(BIO *b, int oper, const char* ATTR_UNUSED(argp),
843 int ATTR_UNUSED(argi), long argl, long retvalue)
845 int wsa_err = WSAGetLastError(); /* store errcode before it is gone */
846 verbose(VERB_ALGO, "bio_cb %d, %s %s %s", oper,
847 (oper&BIO_CB_RETURN)?"return":"before",
848 (oper&BIO_CB_READ)?"read":((oper&BIO_CB_WRITE)?"write":"other"),
849 wsa_err==WSAEWOULDBLOCK?"wsawb":"");
850 /* on windows, check if previous operation caused EWOULDBLOCK */
851 if( (oper == (BIO_CB_READ|BIO_CB_RETURN) && argl == 0) ||
852 (oper == (BIO_CB_GETS|BIO_CB_RETURN) && argl == 0)) {
853 if(wsa_err == WSAEWOULDBLOCK)
854 ub_winsock_tcp_wouldblock((struct ub_event*)
855 BIO_get_callback_arg(b), UB_EV_READ);
857 if( (oper == (BIO_CB_WRITE|BIO_CB_RETURN) && argl == 0) ||
858 (oper == (BIO_CB_PUTS|BIO_CB_RETURN) && argl == 0)) {
859 if(wsa_err == WSAEWOULDBLOCK)
860 ub_winsock_tcp_wouldblock((struct ub_event*)
861 BIO_get_callback_arg(b), UB_EV_WRITE);
863 /* return original return value */
867 /** set win bio callbacks for nonblocking operations */
869 comm_point_tcp_win_bio_cb(struct comm_point* c, void* thessl)
871 SSL* ssl = (SSL*)thessl;
872 /* set them both just in case, but usually they are the same BIO */
873 BIO_set_callback(SSL_get_rbio(ssl), &win_bio_cb);
874 BIO_set_callback_arg(SSL_get_rbio(ssl), (char*)c->ev->ev);
875 BIO_set_callback(SSL_get_wbio(ssl), &win_bio_cb);
876 BIO_set_callback_arg(SSL_get_wbio(ssl), (char*)c->ev->ev);
881 comm_point_tcp_accept_callback(int fd, short event, void* arg)
883 struct comm_point* c = (struct comm_point*)arg, *c_hdl;
885 log_assert(c->type == comm_tcp_accept);
886 if(!(event & UB_EV_READ)) {
887 log_info("ignoring tcp accept event %d", (int)event);
890 ub_comm_base_now(c->ev->base);
891 /* find free tcp handler. */
893 log_warn("accepted too many tcp, connections full");
896 /* accept incoming connection. */
898 log_assert(fd != -1);
900 new_fd = comm_point_perform_accept(c, &c_hdl->repinfo.addr,
901 &c_hdl->repinfo.addrlen);
905 c_hdl->ssl = incoming_ssl_fd(c->ssl, new_fd);
908 comm_point_close(c_hdl);
911 c_hdl->ssl_shake_state = comm_ssl_shake_read;
913 comm_point_tcp_win_bio_cb(c_hdl, c_hdl->ssl);
917 /* grab the tcp handler buffers */
919 c->tcp_free = c_hdl->tcp_free;
921 /* stop accepting incoming queries for now. */
922 comm_point_stop_listening(c);
924 setup_tcp_handler(c_hdl, new_fd, c->cur_tcp_count, c->max_tcp_count);
927 /** Make tcp handler free for next assignment */
929 reclaim_tcp_handler(struct comm_point* c)
931 log_assert(c->type == comm_tcp);
934 SSL_shutdown(c->ssl);
941 c->tcp_parent->cur_tcp_count--;
942 c->tcp_free = c->tcp_parent->tcp_free;
943 c->tcp_parent->tcp_free = c;
945 /* re-enable listening on accept socket */
946 comm_point_start_listening(c->tcp_parent, -1, -1);
951 /** do the callback when writing is done */
953 tcp_callback_writer(struct comm_point* c)
955 log_assert(c->type == comm_tcp);
956 sldns_buffer_clear(c->buffer);
957 if(c->tcp_do_toggle_rw)
958 c->tcp_is_reading = 1;
959 c->tcp_byte_count = 0;
960 /* switch from listening(write) to listening(read) */
961 comm_point_stop_listening(c);
962 comm_point_start_listening(c, -1, -1);
965 /** do the callback when reading is done */
967 tcp_callback_reader(struct comm_point* c)
969 log_assert(c->type == comm_tcp || c->type == comm_local);
970 sldns_buffer_flip(c->buffer);
971 if(c->tcp_do_toggle_rw)
972 c->tcp_is_reading = 0;
973 c->tcp_byte_count = 0;
974 if(c->type == comm_tcp)
975 comm_point_stop_listening(c);
976 fptr_ok(fptr_whitelist_comm_point(c->callback));
977 if( (*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, &c->repinfo) ) {
978 comm_point_start_listening(c, -1, c->tcp_timeout_msec);
983 /** log certificate details */
985 log_cert(unsigned level, const char* str, X509* cert)
991 if(verbosity < level) return;
992 bio = BIO_new(BIO_s_mem());
994 X509_print_ex(bio, cert, 0, (unsigned long)-1
995 ^(X509_FLAG_NO_SUBJECT
996 |X509_FLAG_NO_ISSUER|X509_FLAG_NO_VALIDITY
997 |X509_FLAG_NO_EXTENSIONS|X509_FLAG_NO_AUX
998 |X509_FLAG_NO_ATTRIBUTES));
999 BIO_write(bio, &nul, (int)sizeof(nul));
1000 len = BIO_get_mem_data(bio, &pp);
1001 if(len != 0 && pp) {
1002 verbose(level, "%s: \n%s", str, pp);
1006 #endif /* HAVE_SSL */
1008 /** continue ssl handshake */
1011 ssl_handshake(struct comm_point* c)
1014 if(c->ssl_shake_state == comm_ssl_shake_hs_read) {
1015 /* read condition satisfied back to writing */
1016 comm_point_listen_for_rw(c, 1, 1);
1017 c->ssl_shake_state = comm_ssl_shake_none;
1020 if(c->ssl_shake_state == comm_ssl_shake_hs_write) {
1021 /* write condition satisfied, back to reading */
1022 comm_point_listen_for_rw(c, 1, 0);
1023 c->ssl_shake_state = comm_ssl_shake_none;
1028 r = SSL_do_handshake(c->ssl);
1030 int want = SSL_get_error(c->ssl, r);
1031 if(want == SSL_ERROR_WANT_READ) {
1032 if(c->ssl_shake_state == comm_ssl_shake_read)
1034 c->ssl_shake_state = comm_ssl_shake_read;
1035 comm_point_listen_for_rw(c, 1, 0);
1037 } else if(want == SSL_ERROR_WANT_WRITE) {
1038 if(c->ssl_shake_state == comm_ssl_shake_write)
1040 c->ssl_shake_state = comm_ssl_shake_write;
1041 comm_point_listen_for_rw(c, 0, 1);
1044 return 0; /* closed */
1045 } else if(want == SSL_ERROR_SYSCALL) {
1046 /* SYSCALL and errno==0 means closed uncleanly */
1048 log_err("SSL_handshake syscall: %s",
1052 log_crypto_err("ssl handshake failed");
1053 log_addr(1, "ssl handshake failed", &c->repinfo.addr,
1054 c->repinfo.addrlen);
1058 /* this is where peer verification could take place */
1059 if((SSL_get_verify_mode(c->ssl)&SSL_VERIFY_PEER)) {
1061 if(SSL_get_verify_result(c->ssl) == X509_V_OK) {
1062 X509* x = SSL_get_peer_certificate(c->ssl);
1064 log_addr(VERB_ALGO, "SSL connection failed: "
1066 &c->repinfo.addr, c->repinfo.addrlen);
1069 log_cert(VERB_ALGO, "peer certificate", x);
1070 #ifdef HAVE_SSL_GET0_PEERNAME
1071 if(SSL_get0_peername(c->ssl)) {
1073 snprintf(buf, sizeof(buf), "SSL connection "
1074 "to %s authenticated",
1075 SSL_get0_peername(c->ssl));
1076 log_addr(VERB_ALGO, buf, &c->repinfo.addr,
1077 c->repinfo.addrlen);
1080 log_addr(VERB_ALGO, "SSL connection "
1081 "authenticated", &c->repinfo.addr,
1082 c->repinfo.addrlen);
1083 #ifdef HAVE_SSL_GET0_PEERNAME
1088 X509* x = SSL_get_peer_certificate(c->ssl);
1090 log_cert(VERB_ALGO, "peer certificate", x);
1093 log_addr(VERB_ALGO, "SSL connection failed: "
1094 "failed to authenticate",
1095 &c->repinfo.addr, c->repinfo.addrlen);
1099 /* unauthenticated, the verify peer flag was not set
1100 * in c->ssl when the ssl object was created from ssl_ctx */
1101 log_addr(VERB_ALGO, "SSL connection", &c->repinfo.addr,
1102 c->repinfo.addrlen);
1105 /* setup listen rw correctly */
1106 if(c->tcp_is_reading) {
1107 if(c->ssl_shake_state != comm_ssl_shake_read)
1108 comm_point_listen_for_rw(c, 1, 0);
1110 comm_point_listen_for_rw(c, 1, 1);
1112 c->ssl_shake_state = comm_ssl_shake_none;
1115 #endif /* HAVE_SSL */
1117 /** ssl read callback on TCP */
1119 ssl_handle_read(struct comm_point* c)
1123 if(c->ssl_shake_state != comm_ssl_shake_none) {
1124 if(!ssl_handshake(c))
1126 if(c->ssl_shake_state != comm_ssl_shake_none)
1129 if(c->tcp_byte_count < sizeof(uint16_t)) {
1130 /* read length bytes */
1132 if((r=SSL_read(c->ssl, (void*)sldns_buffer_at(c->buffer,
1133 c->tcp_byte_count), (int)(sizeof(uint16_t) -
1134 c->tcp_byte_count))) <= 0) {
1135 int want = SSL_get_error(c->ssl, r);
1136 if(want == SSL_ERROR_ZERO_RETURN) {
1137 return 0; /* shutdown, closed */
1138 } else if(want == SSL_ERROR_WANT_READ) {
1139 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1140 return 1; /* read more later */
1141 } else if(want == SSL_ERROR_WANT_WRITE) {
1142 c->ssl_shake_state = comm_ssl_shake_hs_write;
1143 comm_point_listen_for_rw(c, 0, 1);
1145 } else if(want == SSL_ERROR_SYSCALL) {
1147 log_err("SSL_read syscall: %s",
1151 log_crypto_err("could not SSL_read");
1154 c->tcp_byte_count += r;
1155 if(c->tcp_byte_count < sizeof(uint16_t))
1157 if(sldns_buffer_read_u16_at(c->buffer, 0) >
1158 sldns_buffer_capacity(c->buffer)) {
1159 verbose(VERB_QUERY, "ssl: dropped larger than buffer");
1162 sldns_buffer_set_limit(c->buffer,
1163 sldns_buffer_read_u16_at(c->buffer, 0));
1164 if(sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
1165 verbose(VERB_QUERY, "ssl: dropped bogus too short.");
1168 sldns_buffer_skip(c->buffer, (ssize_t)(c->tcp_byte_count-sizeof(uint16_t)));
1169 verbose(VERB_ALGO, "Reading ssl tcp query of length %d",
1170 (int)sldns_buffer_limit(c->buffer));
1172 if(sldns_buffer_remaining(c->buffer) > 0) {
1174 r = SSL_read(c->ssl, (void*)sldns_buffer_current(c->buffer),
1175 (int)sldns_buffer_remaining(c->buffer));
1177 int want = SSL_get_error(c->ssl, r);
1178 if(want == SSL_ERROR_ZERO_RETURN) {
1179 return 0; /* shutdown, closed */
1180 } else if(want == SSL_ERROR_WANT_READ) {
1181 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1182 return 1; /* read more later */
1183 } else if(want == SSL_ERROR_WANT_WRITE) {
1184 c->ssl_shake_state = comm_ssl_shake_hs_write;
1185 comm_point_listen_for_rw(c, 0, 1);
1187 } else if(want == SSL_ERROR_SYSCALL) {
1189 log_err("SSL_read syscall: %s",
1193 log_crypto_err("could not SSL_read");
1196 sldns_buffer_skip(c->buffer, (ssize_t)r);
1198 if(sldns_buffer_remaining(c->buffer) <= 0) {
1199 tcp_callback_reader(c);
1205 #endif /* HAVE_SSL */
1208 /** ssl write callback on TCP */
1210 ssl_handle_write(struct comm_point* c)
1214 if(c->ssl_shake_state != comm_ssl_shake_none) {
1215 if(!ssl_handshake(c))
1217 if(c->ssl_shake_state != comm_ssl_shake_none)
1220 /* ignore return, if fails we may simply block */
1221 (void)SSL_set_mode(c->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE);
1222 if(c->tcp_byte_count < sizeof(uint16_t)) {
1223 uint16_t len = htons(sldns_buffer_limit(c->buffer));
1225 if(sizeof(uint16_t)+sldns_buffer_remaining(c->buffer) <
1227 /* combine the tcp length and the query for write,
1228 * this emulates writev */
1229 uint8_t buf[LDNS_RR_BUF_SIZE];
1230 memmove(buf, &len, sizeof(uint16_t));
1231 memmove(buf+sizeof(uint16_t),
1232 sldns_buffer_current(c->buffer),
1233 sldns_buffer_remaining(c->buffer));
1234 r = SSL_write(c->ssl, (void*)(buf+c->tcp_byte_count),
1235 (int)(sizeof(uint16_t)+
1236 sldns_buffer_remaining(c->buffer)
1237 - c->tcp_byte_count));
1239 r = SSL_write(c->ssl,
1240 (void*)(((uint8_t*)&len)+c->tcp_byte_count),
1241 (int)(sizeof(uint16_t)-c->tcp_byte_count));
1244 int want = SSL_get_error(c->ssl, r);
1245 if(want == SSL_ERROR_ZERO_RETURN) {
1246 return 0; /* closed */
1247 } else if(want == SSL_ERROR_WANT_READ) {
1248 c->ssl_shake_state = comm_ssl_shake_read;
1249 comm_point_listen_for_rw(c, 1, 0);
1250 return 1; /* wait for read condition */
1251 } else if(want == SSL_ERROR_WANT_WRITE) {
1252 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
1253 return 1; /* write more later */
1254 } else if(want == SSL_ERROR_SYSCALL) {
1256 log_err("SSL_write syscall: %s",
1260 log_crypto_err("could not SSL_write");
1263 c->tcp_byte_count += r;
1264 if(c->tcp_byte_count < sizeof(uint16_t))
1266 sldns_buffer_set_position(c->buffer, c->tcp_byte_count -
1268 if(sldns_buffer_remaining(c->buffer) == 0) {
1269 tcp_callback_writer(c);
1273 log_assert(sldns_buffer_remaining(c->buffer) > 0);
1275 r = SSL_write(c->ssl, (void*)sldns_buffer_current(c->buffer),
1276 (int)sldns_buffer_remaining(c->buffer));
1278 int want = SSL_get_error(c->ssl, r);
1279 if(want == SSL_ERROR_ZERO_RETURN) {
1280 return 0; /* closed */
1281 } else if(want == SSL_ERROR_WANT_READ) {
1282 c->ssl_shake_state = comm_ssl_shake_read;
1283 comm_point_listen_for_rw(c, 1, 0);
1284 return 1; /* wait for read condition */
1285 } else if(want == SSL_ERROR_WANT_WRITE) {
1286 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
1287 return 1; /* write more later */
1288 } else if(want == SSL_ERROR_SYSCALL) {
1290 log_err("SSL_write syscall: %s",
1294 log_crypto_err("could not SSL_write");
1297 sldns_buffer_skip(c->buffer, (ssize_t)r);
1299 if(sldns_buffer_remaining(c->buffer) == 0) {
1300 tcp_callback_writer(c);
1306 #endif /* HAVE_SSL */
1309 /** handle ssl tcp connection with dns contents */
1311 ssl_handle_it(struct comm_point* c)
1313 if(c->tcp_is_reading)
1314 return ssl_handle_read(c);
1315 return ssl_handle_write(c);
1318 /** Handle tcp reading callback.
1319 * @param fd: file descriptor of socket.
1320 * @param c: comm point to read from into buffer.
1321 * @param short_ok: if true, very short packets are OK (for comm_local).
1322 * @return: 0 on error
1325 comm_point_tcp_handle_read(int fd, struct comm_point* c, int short_ok)
1328 log_assert(c->type == comm_tcp || c->type == comm_local);
1330 return ssl_handle_it(c);
1331 if(!c->tcp_is_reading)
1334 log_assert(fd != -1);
1335 if(c->tcp_byte_count < sizeof(uint16_t)) {
1336 /* read length bytes */
1337 r = recv(fd,(void*)sldns_buffer_at(c->buffer,c->tcp_byte_count),
1338 sizeof(uint16_t)-c->tcp_byte_count, 0);
1343 if(errno == EINTR || errno == EAGAIN)
1346 if(errno == ECONNRESET && verbosity < 2)
1347 return 0; /* silence reset by peer */
1349 log_err_addr("read (in tcp s)", strerror(errno),
1350 &c->repinfo.addr, c->repinfo.addrlen);
1351 #else /* USE_WINSOCK */
1352 if(WSAGetLastError() == WSAECONNRESET)
1354 if(WSAGetLastError() == WSAEINPROGRESS)
1356 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1357 ub_winsock_tcp_wouldblock(c->ev->ev,
1361 log_err_addr("read (in tcp s)",
1362 wsa_strerror(WSAGetLastError()),
1363 &c->repinfo.addr, c->repinfo.addrlen);
1367 c->tcp_byte_count += r;
1368 if(c->tcp_byte_count != sizeof(uint16_t))
1370 if(sldns_buffer_read_u16_at(c->buffer, 0) >
1371 sldns_buffer_capacity(c->buffer)) {
1372 verbose(VERB_QUERY, "tcp: dropped larger than buffer");
1375 sldns_buffer_set_limit(c->buffer,
1376 sldns_buffer_read_u16_at(c->buffer, 0));
1378 sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
1379 verbose(VERB_QUERY, "tcp: dropped bogus too short.");
1382 verbose(VERB_ALGO, "Reading tcp query of length %d",
1383 (int)sldns_buffer_limit(c->buffer));
1386 log_assert(sldns_buffer_remaining(c->buffer) > 0);
1387 r = recv(fd, (void*)sldns_buffer_current(c->buffer),
1388 sldns_buffer_remaining(c->buffer), 0);
1391 } else if(r == -1) {
1393 if(errno == EINTR || errno == EAGAIN)
1395 log_err_addr("read (in tcp r)", strerror(errno),
1396 &c->repinfo.addr, c->repinfo.addrlen);
1397 #else /* USE_WINSOCK */
1398 if(WSAGetLastError() == WSAECONNRESET)
1400 if(WSAGetLastError() == WSAEINPROGRESS)
1402 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1403 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1406 log_err_addr("read (in tcp r)",
1407 wsa_strerror(WSAGetLastError()),
1408 &c->repinfo.addr, c->repinfo.addrlen);
1412 sldns_buffer_skip(c->buffer, r);
1413 if(sldns_buffer_remaining(c->buffer) <= 0) {
1414 tcp_callback_reader(c);
1420 * Handle tcp writing callback.
1421 * @param fd: file descriptor of socket.
1422 * @param c: comm point to write buffer out of.
1423 * @return: 0 on error
1426 comm_point_tcp_handle_write(int fd, struct comm_point* c)
1429 struct sldns_buffer *buffer;
1430 log_assert(c->type == comm_tcp);
1432 buffer = c->dnscrypt_buffer;
1436 if(c->tcp_is_reading && !c->ssl)
1438 log_assert(fd != -1);
1439 if(c->tcp_byte_count == 0 && c->tcp_check_nb_connect) {
1440 /* check for pending error from nonblocking connect */
1441 /* from Stevens, unix network programming, vol1, 3rd ed, p450*/
1443 socklen_t len = (socklen_t)sizeof(error);
1444 if(getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&error,
1447 error = errno; /* on solaris errno is error */
1448 #else /* USE_WINSOCK */
1449 error = WSAGetLastError();
1453 #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
1454 if(error == EINPROGRESS || error == EWOULDBLOCK)
1455 return 1; /* try again later */
1458 if(error != 0 && verbosity < 2)
1459 return 0; /* silence lots of chatter in the logs */
1460 else if(error != 0) {
1461 log_err_addr("tcp connect", strerror(error),
1462 &c->repinfo.addr, c->repinfo.addrlen);
1463 #else /* USE_WINSOCK */
1465 if(error == WSAEINPROGRESS)
1467 else if(error == WSAEWOULDBLOCK) {
1468 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
1470 } else if(error != 0 && verbosity < 2)
1472 else if(error != 0) {
1473 log_err_addr("tcp connect", wsa_strerror(error),
1474 &c->repinfo.addr, c->repinfo.addrlen);
1475 #endif /* USE_WINSOCK */
1480 return ssl_handle_it(c);
1482 #ifdef USE_MSG_FASTOPEN
1483 /* Only try this on first use of a connection that uses tfo,
1484 otherwise fall through to normal write */
1485 /* Also, TFO support on WINDOWS not implemented at the moment */
1486 if(c->tcp_do_fastopen == 1) {
1487 /* this form of sendmsg() does both a connect() and send() so need to
1488 look for various flavours of error*/
1489 uint16_t len = htons(sldns_buffer_limit(buffer));
1491 struct iovec iov[2];
1492 c->tcp_do_fastopen = 0;
1493 memset(&msg, 0, sizeof(msg));
1494 iov[0].iov_base = (uint8_t*)&len + c->tcp_byte_count;
1495 iov[0].iov_len = sizeof(uint16_t) - c->tcp_byte_count;
1496 iov[1].iov_base = sldns_buffer_begin(buffer);
1497 iov[1].iov_len = sldns_buffer_limit(buffer);
1498 log_assert(iov[0].iov_len > 0);
1499 log_assert(iov[1].iov_len > 0);
1500 msg.msg_name = &c->repinfo.addr;
1501 msg.msg_namelen = c->repinfo.addrlen;
1504 r = sendmsg(fd, &msg, MSG_FASTOPEN);
1506 #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
1507 /* Handshake is underway, maybe because no TFO cookie available.
1508 Come back to write the message*/
1509 if(errno == EINPROGRESS || errno == EWOULDBLOCK)
1512 if(errno == EINTR || errno == EAGAIN)
1514 /* Not handling EISCONN here as shouldn't ever hit that case.*/
1515 if(errno != EPIPE && errno != 0 && verbosity < 2)
1516 return 0; /* silence lots of chatter in the logs */
1517 if(errno != EPIPE && errno != 0) {
1518 log_err_addr("tcp sendmsg", strerror(errno),
1519 &c->repinfo.addr, c->repinfo.addrlen);
1522 /* fallthrough to nonFASTOPEN
1523 * (MSG_FASTOPEN on Linux 3 produces EPIPE)
1524 * we need to perform connect() */
1525 if(connect(fd, (struct sockaddr *)&c->repinfo.addr, c->repinfo.addrlen) == -1) {
1527 if(errno == EINPROGRESS)
1528 return 1; /* wait until connect done*/
1531 if(WSAGetLastError() == WSAEINPROGRESS ||
1532 WSAGetLastError() == WSAEWOULDBLOCK)
1533 return 1; /* wait until connect done*/
1535 if(tcp_connect_errno_needs_log(
1536 (struct sockaddr *)&c->repinfo.addr, c->repinfo.addrlen)) {
1537 log_err_addr("outgoing tcp: connect after EPIPE for fastopen",
1538 strerror(errno), &c->repinfo.addr, c->repinfo.addrlen);
1544 c->tcp_byte_count += r;
1545 if(c->tcp_byte_count < sizeof(uint16_t))
1547 sldns_buffer_set_position(buffer, c->tcp_byte_count -
1549 if(sldns_buffer_remaining(buffer) == 0) {
1550 tcp_callback_writer(c);
1555 #endif /* USE_MSG_FASTOPEN */
1557 if(c->tcp_byte_count < sizeof(uint16_t)) {
1558 uint16_t len = htons(sldns_buffer_limit(buffer));
1560 struct iovec iov[2];
1561 iov[0].iov_base = (uint8_t*)&len + c->tcp_byte_count;
1562 iov[0].iov_len = sizeof(uint16_t) - c->tcp_byte_count;
1563 iov[1].iov_base = sldns_buffer_begin(buffer);
1564 iov[1].iov_len = sldns_buffer_limit(buffer);
1565 log_assert(iov[0].iov_len > 0);
1566 log_assert(iov[1].iov_len > 0);
1567 r = writev(fd, iov, 2);
1568 #else /* HAVE_WRITEV */
1569 r = send(fd, (void*)(((uint8_t*)&len)+c->tcp_byte_count),
1570 sizeof(uint16_t)-c->tcp_byte_count, 0);
1571 #endif /* HAVE_WRITEV */
1575 if(errno == EPIPE && verbosity < 2)
1576 return 0; /* silence 'broken pipe' */
1578 if(errno == EINTR || errno == EAGAIN)
1581 log_err_addr("tcp writev", strerror(errno),
1582 &c->repinfo.addr, c->repinfo.addrlen);
1583 # else /* HAVE_WRITEV */
1584 log_err_addr("tcp send s", strerror(errno),
1585 &c->repinfo.addr, c->repinfo.addrlen);
1586 # endif /* HAVE_WRITEV */
1588 if(WSAGetLastError() == WSAENOTCONN)
1590 if(WSAGetLastError() == WSAEINPROGRESS)
1592 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1593 ub_winsock_tcp_wouldblock(c->ev->ev,
1597 log_err_addr("tcp send s",
1598 wsa_strerror(WSAGetLastError()),
1599 &c->repinfo.addr, c->repinfo.addrlen);
1603 c->tcp_byte_count += r;
1604 if(c->tcp_byte_count < sizeof(uint16_t))
1606 sldns_buffer_set_position(buffer, c->tcp_byte_count -
1608 if(sldns_buffer_remaining(buffer) == 0) {
1609 tcp_callback_writer(c);
1613 log_assert(sldns_buffer_remaining(buffer) > 0);
1614 r = send(fd, (void*)sldns_buffer_current(buffer),
1615 sldns_buffer_remaining(buffer), 0);
1618 if(errno == EINTR || errno == EAGAIN)
1620 log_err_addr("tcp send r", strerror(errno),
1621 &c->repinfo.addr, c->repinfo.addrlen);
1623 if(WSAGetLastError() == WSAEINPROGRESS)
1625 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1626 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
1629 log_err_addr("tcp send r", wsa_strerror(WSAGetLastError()),
1630 &c->repinfo.addr, c->repinfo.addrlen);
1634 sldns_buffer_skip(buffer, r);
1636 if(sldns_buffer_remaining(buffer) == 0) {
1637 tcp_callback_writer(c);
1644 comm_point_tcp_handle_callback(int fd, short event, void* arg)
1646 struct comm_point* c = (struct comm_point*)arg;
1647 log_assert(c->type == comm_tcp);
1648 ub_comm_base_now(c->ev->base);
1651 /* Initialize if this is a dnscrypt socket */
1653 c->dnscrypt = c->tcp_parent->dnscrypt;
1655 if(c->dnscrypt && c->dnscrypt_buffer == c->buffer) {
1656 c->dnscrypt_buffer = sldns_buffer_new(sldns_buffer_capacity(c->buffer));
1657 if(!c->dnscrypt_buffer) {
1658 log_err("Could not allocate dnscrypt buffer");
1659 reclaim_tcp_handler(c);
1660 if(!c->tcp_do_close) {
1661 fptr_ok(fptr_whitelist_comm_point(
1663 (void)(*c->callback)(c, c->cb_arg,
1664 NETEVENT_CLOSED, NULL);
1671 if(event&UB_EV_READ) {
1672 if(!comm_point_tcp_handle_read(fd, c, 0)) {
1673 reclaim_tcp_handler(c);
1674 if(!c->tcp_do_close) {
1675 fptr_ok(fptr_whitelist_comm_point(
1677 (void)(*c->callback)(c, c->cb_arg,
1678 NETEVENT_CLOSED, NULL);
1683 if(event&UB_EV_WRITE) {
1684 if(!comm_point_tcp_handle_write(fd, c)) {
1685 reclaim_tcp_handler(c);
1686 if(!c->tcp_do_close) {
1687 fptr_ok(fptr_whitelist_comm_point(
1689 (void)(*c->callback)(c, c->cb_arg,
1690 NETEVENT_CLOSED, NULL);
1695 if(event&UB_EV_TIMEOUT) {
1696 verbose(VERB_QUERY, "tcp took too long, dropped");
1697 reclaim_tcp_handler(c);
1698 if(!c->tcp_do_close) {
1699 fptr_ok(fptr_whitelist_comm_point(c->callback));
1700 (void)(*c->callback)(c, c->cb_arg,
1701 NETEVENT_TIMEOUT, NULL);
1705 log_err("Ignored event %d for tcphdl.", event);
1708 /** Make http handler free for next assignment */
1710 reclaim_http_handler(struct comm_point* c)
1712 log_assert(c->type == comm_http);
1715 SSL_shutdown(c->ssl);
1720 comm_point_close(c);
1722 c->tcp_parent->cur_tcp_count--;
1723 c->tcp_free = c->tcp_parent->tcp_free;
1724 c->tcp_parent->tcp_free = c;
1726 /* re-enable listening on accept socket */
1727 comm_point_start_listening(c->tcp_parent, -1, -1);
1732 /** read more data for http (with ssl) */
1734 ssl_http_read_more(struct comm_point* c)
1738 log_assert(sldns_buffer_remaining(c->buffer) > 0);
1740 r = SSL_read(c->ssl, (void*)sldns_buffer_current(c->buffer),
1741 (int)sldns_buffer_remaining(c->buffer));
1743 int want = SSL_get_error(c->ssl, r);
1744 if(want == SSL_ERROR_ZERO_RETURN) {
1745 return 0; /* shutdown, closed */
1746 } else if(want == SSL_ERROR_WANT_READ) {
1747 return 1; /* read more later */
1748 } else if(want == SSL_ERROR_WANT_WRITE) {
1749 c->ssl_shake_state = comm_ssl_shake_hs_write;
1750 comm_point_listen_for_rw(c, 0, 1);
1752 } else if(want == SSL_ERROR_SYSCALL) {
1754 log_err("SSL_read syscall: %s",
1758 log_crypto_err("could not SSL_read");
1761 sldns_buffer_skip(c->buffer, (ssize_t)r);
1766 #endif /* HAVE_SSL */
1769 /** read more data for http */
1771 http_read_more(int fd, struct comm_point* c)
1774 log_assert(sldns_buffer_remaining(c->buffer) > 0);
1775 r = recv(fd, (void*)sldns_buffer_current(c->buffer),
1776 sldns_buffer_remaining(c->buffer), 0);
1779 } else if(r == -1) {
1781 if(errno == EINTR || errno == EAGAIN)
1783 log_err_addr("read (in http r)", strerror(errno),
1784 &c->repinfo.addr, c->repinfo.addrlen);
1785 #else /* USE_WINSOCK */
1786 if(WSAGetLastError() == WSAECONNRESET)
1788 if(WSAGetLastError() == WSAEINPROGRESS)
1790 if(WSAGetLastError() == WSAEWOULDBLOCK) {
1791 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
1794 log_err_addr("read (in http r)",
1795 wsa_strerror(WSAGetLastError()),
1796 &c->repinfo.addr, c->repinfo.addrlen);
1800 sldns_buffer_skip(c->buffer, r);
1804 /** return true if http header has been read (one line complete) */
1806 http_header_done(sldns_buffer* buf)
1809 for(i=sldns_buffer_position(buf); i<sldns_buffer_limit(buf); i++) {
1810 /* there was a \r before the \n, but we ignore that */
1811 if((char)sldns_buffer_read_u8_at(buf, i) == '\n')
1817 /** return character string into buffer for header line, moves buffer
1818 * past that line and puts zero terminator into linefeed-newline */
1820 http_header_line(sldns_buffer* buf)
1822 char* result = (char*)sldns_buffer_current(buf);
1824 for(i=sldns_buffer_position(buf); i<sldns_buffer_limit(buf); i++) {
1825 /* terminate the string on the \r */
1826 if((char)sldns_buffer_read_u8_at(buf, i) == '\r')
1827 sldns_buffer_write_u8_at(buf, i, 0);
1828 /* terminate on the \n and skip past the it and done */
1829 if((char)sldns_buffer_read_u8_at(buf, i) == '\n') {
1830 sldns_buffer_write_u8_at(buf, i, 0);
1831 sldns_buffer_set_position(buf, i+1);
1838 /** move unread buffer to start and clear rest for putting the rest into it */
1840 http_moveover_buffer(sldns_buffer* buf)
1842 size_t pos = sldns_buffer_position(buf);
1843 size_t len = sldns_buffer_remaining(buf);
1844 sldns_buffer_clear(buf);
1845 memmove(sldns_buffer_begin(buf), sldns_buffer_at(buf, pos), len);
1846 sldns_buffer_set_position(buf, len);
1849 /** a http header is complete, process it */
1851 http_process_initial_header(struct comm_point* c)
1853 char* line = http_header_line(c->buffer);
1855 verbose(VERB_ALGO, "http header: %s", line);
1856 if(strncasecmp(line, "HTTP/1.1 ", 9) == 0) {
1857 /* check returncode */
1858 if(line[9] != '2') {
1859 verbose(VERB_ALGO, "http bad status %s", line+9);
1862 } else if(strncasecmp(line, "Content-Length: ", 16) == 0) {
1863 if(!c->http_is_chunked)
1864 c->tcp_byte_count = (size_t)atoi(line+16);
1865 } else if(strncasecmp(line, "Transfer-Encoding: chunked", 19+7) == 0) {
1866 c->tcp_byte_count = 0;
1867 c->http_is_chunked = 1;
1868 } else if(line[0] == 0) {
1869 /* end of initial headers */
1870 c->http_in_headers = 0;
1871 if(c->http_is_chunked)
1872 c->http_in_chunk_headers = 1;
1873 /* remove header text from front of buffer
1874 * the buffer is going to be used to return the data segment
1875 * itself and we don't want the header to get returned
1876 * prepended with it */
1877 http_moveover_buffer(c->buffer);
1878 sldns_buffer_flip(c->buffer);
1881 /* ignore other headers */
1885 /** a chunk header is complete, process it, return 0=fail, 1=continue next
1886 * header line, 2=done with chunked transfer*/
1888 http_process_chunk_header(struct comm_point* c)
1890 char* line = http_header_line(c->buffer);
1892 if(c->http_in_chunk_headers == 3) {
1893 verbose(VERB_ALGO, "http chunk trailer: %s", line);
1895 if(line[0] == 0 && c->tcp_byte_count == 0) {
1896 /* callback of http reader when NETEVENT_DONE,
1897 * end of data, with no data in buffer */
1898 sldns_buffer_set_position(c->buffer, 0);
1899 sldns_buffer_set_limit(c->buffer, 0);
1900 fptr_ok(fptr_whitelist_comm_point(c->callback));
1901 (void)(*c->callback)(c, c->cb_arg, NETEVENT_DONE, NULL);
1902 /* return that we are done */
1906 /* continue with header of the next chunk */
1907 c->http_in_chunk_headers = 1;
1908 /* remove header text from front of buffer */
1909 http_moveover_buffer(c->buffer);
1910 sldns_buffer_flip(c->buffer);
1913 /* ignore further trail headers */
1916 verbose(VERB_ALGO, "http chunk header: %s", line);
1917 if(c->http_in_chunk_headers == 1) {
1918 /* read chunked start line */
1920 c->tcp_byte_count = (size_t)strtol(line, &end, 16);
1923 c->http_in_chunk_headers = 0;
1924 /* remove header text from front of buffer */
1925 http_moveover_buffer(c->buffer);
1926 sldns_buffer_flip(c->buffer);
1927 if(c->tcp_byte_count == 0) {
1928 /* done with chunks, process chunk_trailer lines */
1929 c->http_in_chunk_headers = 3;
1933 /* ignore other headers */
1937 /** handle nonchunked data segment */
1939 http_nonchunk_segment(struct comm_point* c)
1941 /* c->buffer at position..limit has new data we read in.
1942 * the buffer itself is full of nonchunked data.
1943 * we are looking to read tcp_byte_count more data
1944 * and then the transfer is done. */
1945 size_t remainbufferlen;
1946 size_t got_now = sldns_buffer_limit(c->buffer) - c->http_stored;
1947 if(c->tcp_byte_count <= got_now) {
1948 /* done, this is the last data fragment */
1950 sldns_buffer_set_position(c->buffer, 0);
1951 fptr_ok(fptr_whitelist_comm_point(c->callback));
1952 (void)(*c->callback)(c, c->cb_arg, NETEVENT_DONE, NULL);
1955 c->tcp_byte_count -= got_now;
1956 /* if we have the buffer space,
1957 * read more data collected into the buffer */
1958 remainbufferlen = sldns_buffer_capacity(c->buffer) -
1959 sldns_buffer_limit(c->buffer);
1960 if(remainbufferlen >= c->tcp_byte_count ||
1961 remainbufferlen >= 2048) {
1962 size_t total = sldns_buffer_limit(c->buffer);
1963 sldns_buffer_clear(c->buffer);
1964 sldns_buffer_set_position(c->buffer, total);
1965 c->http_stored = total;
1966 /* return and wait to read more */
1969 /* call callback with this data amount, then
1972 sldns_buffer_set_position(c->buffer, 0);
1973 fptr_ok(fptr_whitelist_comm_point(c->callback));
1974 (void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, NULL);
1975 /* c->callback has to buffer_clear(c->buffer). */
1976 /* return and wait to read more */
1980 /** handle nonchunked data segment, return 0=fail, 1=wait, 2=process more */
1982 http_chunked_segment(struct comm_point* c)
1984 /* the c->buffer has from position..limit new data we read. */
1985 /* the current chunk has length tcp_byte_count.
1986 * once we read that read more chunk headers.
1988 size_t remainbufferlen;
1989 size_t got_now = sldns_buffer_limit(c->buffer) - c->http_stored;
1990 if(c->tcp_byte_count <= got_now) {
1991 /* the chunk has completed (with perhaps some extra data
1992 * from next chunk header and next chunk) */
1993 /* save too much info into temp buffer */
1995 struct comm_reply repinfo;
1997 sldns_buffer_skip(c->buffer, (ssize_t)c->tcp_byte_count);
1998 sldns_buffer_clear(c->http_temp);
1999 sldns_buffer_write(c->http_temp,
2000 sldns_buffer_current(c->buffer),
2001 sldns_buffer_remaining(c->buffer));
2002 sldns_buffer_flip(c->http_temp);
2004 /* callback with this fragment */
2005 fraglen = sldns_buffer_position(c->buffer);
2006 sldns_buffer_set_position(c->buffer, 0);
2007 sldns_buffer_set_limit(c->buffer, fraglen);
2008 repinfo = c->repinfo;
2009 fptr_ok(fptr_whitelist_comm_point(c->callback));
2010 (void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, &repinfo);
2011 /* c->callback has to buffer_clear(). */
2013 /* is commpoint deleted? */
2017 /* copy waiting info */
2018 sldns_buffer_clear(c->buffer);
2019 sldns_buffer_write(c->buffer,
2020 sldns_buffer_begin(c->http_temp),
2021 sldns_buffer_remaining(c->http_temp));
2022 sldns_buffer_flip(c->buffer);
2023 /* process end of chunk trailer header lines, until
2025 c->http_in_chunk_headers = 3;
2026 /* process more data in buffer (if any) */
2029 c->tcp_byte_count -= got_now;
2031 /* if we have the buffer space,
2032 * read more data collected into the buffer */
2033 remainbufferlen = sldns_buffer_capacity(c->buffer) -
2034 sldns_buffer_limit(c->buffer);
2035 if(remainbufferlen >= c->tcp_byte_count ||
2036 remainbufferlen >= 2048) {
2037 size_t total = sldns_buffer_limit(c->buffer);
2038 sldns_buffer_clear(c->buffer);
2039 sldns_buffer_set_position(c->buffer, total);
2040 c->http_stored = total;
2041 /* return and wait to read more */
2045 /* callback of http reader for a new part of the data */
2047 sldns_buffer_set_position(c->buffer, 0);
2048 fptr_ok(fptr_whitelist_comm_point(c->callback));
2049 (void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, NULL);
2050 /* c->callback has to buffer_clear(c->buffer). */
2051 /* return and wait to read more */
2056 * Handle http reading callback.
2057 * @param fd: file descriptor of socket.
2058 * @param c: comm point to read from into buffer.
2059 * @return: 0 on error
2062 comm_point_http_handle_read(int fd, struct comm_point* c)
2064 log_assert(c->type == comm_http);
2065 log_assert(fd != -1);
2067 /* if we are in ssl handshake, handle SSL handshake */
2069 if(c->ssl && c->ssl_shake_state != comm_ssl_shake_none) {
2070 if(!ssl_handshake(c))
2072 if(c->ssl_shake_state != comm_ssl_shake_none)
2075 #endif /* HAVE_SSL */
2077 if(!c->tcp_is_reading)
2079 /* read more data */
2081 if(!ssl_http_read_more(c))
2084 if(!http_read_more(fd, c))
2088 sldns_buffer_flip(c->buffer);
2089 while(sldns_buffer_remaining(c->buffer) > 0) {
2090 /* if we are reading headers, read more headers */
2091 if(c->http_in_headers || c->http_in_chunk_headers) {
2092 /* if header is done, process the header */
2093 if(!http_header_done(c->buffer)) {
2094 /* copy remaining data to front of buffer
2095 * and set rest for writing into it */
2096 http_moveover_buffer(c->buffer);
2097 /* return and wait to read more */
2100 if(!c->http_in_chunk_headers) {
2101 /* process initial headers */
2102 if(!http_process_initial_header(c))
2105 /* process chunk headers */
2106 int r = http_process_chunk_header(c);
2107 if(r == 0) return 0;
2108 if(r == 2) return 1; /* done */
2109 /* r == 1, continue */
2111 /* see if we have more to process */
2115 if(!c->http_is_chunked) {
2116 /* if we are reading nonchunks, process that*/
2117 return http_nonchunk_segment(c);
2119 /* if we are reading chunks, read the chunk */
2120 int r = http_chunked_segment(c);
2121 if(r == 0) return 0;
2122 if(r == 1) return 1;
2126 /* broke out of the loop; could not process header instead need
2128 /* moveover any remaining data and read more data */
2129 http_moveover_buffer(c->buffer);
2130 /* return and wait to read more */
2134 /** check pending connect for http */
2136 http_check_connect(int fd, struct comm_point* c)
2138 /* check for pending error from nonblocking connect */
2139 /* from Stevens, unix network programming, vol1, 3rd ed, p450*/
2141 socklen_t len = (socklen_t)sizeof(error);
2142 if(getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&error,
2145 error = errno; /* on solaris errno is error */
2146 #else /* USE_WINSOCK */
2147 error = WSAGetLastError();
2151 #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
2152 if(error == EINPROGRESS || error == EWOULDBLOCK)
2153 return 1; /* try again later */
2156 if(error != 0 && verbosity < 2)
2157 return 0; /* silence lots of chatter in the logs */
2158 else if(error != 0) {
2159 log_err_addr("http connect", strerror(error),
2160 &c->repinfo.addr, c->repinfo.addrlen);
2161 #else /* USE_WINSOCK */
2163 if(error == WSAEINPROGRESS)
2165 else if(error == WSAEWOULDBLOCK) {
2166 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
2168 } else if(error != 0 && verbosity < 2)
2170 else if(error != 0) {
2171 log_err_addr("http connect", wsa_strerror(error),
2172 &c->repinfo.addr, c->repinfo.addrlen);
2173 #endif /* USE_WINSOCK */
2176 /* keep on processing this socket */
2180 /** write more data for http (with ssl) */
2182 ssl_http_write_more(struct comm_point* c)
2186 log_assert(sldns_buffer_remaining(c->buffer) > 0);
2188 r = SSL_write(c->ssl, (void*)sldns_buffer_current(c->buffer),
2189 (int)sldns_buffer_remaining(c->buffer));
2191 int want = SSL_get_error(c->ssl, r);
2192 if(want == SSL_ERROR_ZERO_RETURN) {
2193 return 0; /* closed */
2194 } else if(want == SSL_ERROR_WANT_READ) {
2195 c->ssl_shake_state = comm_ssl_shake_read;
2196 comm_point_listen_for_rw(c, 1, 0);
2197 return 1; /* wait for read condition */
2198 } else if(want == SSL_ERROR_WANT_WRITE) {
2199 return 1; /* write more later */
2200 } else if(want == SSL_ERROR_SYSCALL) {
2202 log_err("SSL_write syscall: %s",
2206 log_crypto_err("could not SSL_write");
2209 sldns_buffer_skip(c->buffer, (ssize_t)r);
2214 #endif /* HAVE_SSL */
2217 /** write more data for http */
2219 http_write_more(int fd, struct comm_point* c)
2222 log_assert(sldns_buffer_remaining(c->buffer) > 0);
2223 r = send(fd, (void*)sldns_buffer_current(c->buffer),
2224 sldns_buffer_remaining(c->buffer), 0);
2227 if(errno == EINTR || errno == EAGAIN)
2229 log_err_addr("http send r", strerror(errno),
2230 &c->repinfo.addr, c->repinfo.addrlen);
2232 if(WSAGetLastError() == WSAEINPROGRESS)
2234 if(WSAGetLastError() == WSAEWOULDBLOCK) {
2235 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
2238 log_err_addr("http send r", wsa_strerror(WSAGetLastError()),
2239 &c->repinfo.addr, c->repinfo.addrlen);
2243 sldns_buffer_skip(c->buffer, r);
2248 * Handle http writing callback.
2249 * @param fd: file descriptor of socket.
2250 * @param c: comm point to write buffer out of.
2251 * @return: 0 on error
2254 comm_point_http_handle_write(int fd, struct comm_point* c)
2256 log_assert(c->type == comm_http);
2257 log_assert(fd != -1);
2259 /* check pending connect errors, if that fails, we wait for more,
2260 * or we can continue to write contents */
2261 if(c->tcp_check_nb_connect) {
2262 int r = http_check_connect(fd, c);
2263 if(r == 0) return 0;
2264 if(r == 1) return 1;
2265 c->tcp_check_nb_connect = 0;
2267 /* if we are in ssl handshake, handle SSL handshake */
2269 if(c->ssl && c->ssl_shake_state != comm_ssl_shake_none) {
2270 if(!ssl_handshake(c))
2272 if(c->ssl_shake_state != comm_ssl_shake_none)
2275 #endif /* HAVE_SSL */
2276 if(c->tcp_is_reading)
2278 /* if we are writing, write more */
2280 if(!ssl_http_write_more(c))
2283 if(!http_write_more(fd, c))
2287 /* we write a single buffer contents, that can contain
2288 * the http request, and then flip to read the results */
2289 /* see if write is done */
2290 if(sldns_buffer_remaining(c->buffer) == 0) {
2291 sldns_buffer_clear(c->buffer);
2292 if(c->tcp_do_toggle_rw)
2293 c->tcp_is_reading = 1;
2294 c->tcp_byte_count = 0;
2295 /* switch from listening(write) to listening(read) */
2296 comm_point_stop_listening(c);
2297 comm_point_start_listening(c, -1, -1);
2303 comm_point_http_handle_callback(int fd, short event, void* arg)
2305 struct comm_point* c = (struct comm_point*)arg;
2306 log_assert(c->type == comm_http);
2307 ub_comm_base_now(c->ev->base);
2309 if(event&UB_EV_READ) {
2310 if(!comm_point_http_handle_read(fd, c)) {
2311 reclaim_http_handler(c);
2312 if(!c->tcp_do_close) {
2313 fptr_ok(fptr_whitelist_comm_point(
2315 (void)(*c->callback)(c, c->cb_arg,
2316 NETEVENT_CLOSED, NULL);
2321 if(event&UB_EV_WRITE) {
2322 if(!comm_point_http_handle_write(fd, c)) {
2323 reclaim_http_handler(c);
2324 if(!c->tcp_do_close) {
2325 fptr_ok(fptr_whitelist_comm_point(
2327 (void)(*c->callback)(c, c->cb_arg,
2328 NETEVENT_CLOSED, NULL);
2333 if(event&UB_EV_TIMEOUT) {
2334 verbose(VERB_QUERY, "http took too long, dropped");
2335 reclaim_http_handler(c);
2336 if(!c->tcp_do_close) {
2337 fptr_ok(fptr_whitelist_comm_point(c->callback));
2338 (void)(*c->callback)(c, c->cb_arg,
2339 NETEVENT_TIMEOUT, NULL);
2343 log_err("Ignored event %d for httphdl.", event);
2346 void comm_point_local_handle_callback(int fd, short event, void* arg)
2348 struct comm_point* c = (struct comm_point*)arg;
2349 log_assert(c->type == comm_local);
2350 ub_comm_base_now(c->ev->base);
2352 if(event&UB_EV_READ) {
2353 if(!comm_point_tcp_handle_read(fd, c, 1)) {
2354 fptr_ok(fptr_whitelist_comm_point(c->callback));
2355 (void)(*c->callback)(c, c->cb_arg, NETEVENT_CLOSED,
2360 log_err("Ignored event %d for localhdl.", event);
2363 void comm_point_raw_handle_callback(int ATTR_UNUSED(fd),
2364 short event, void* arg)
2366 struct comm_point* c = (struct comm_point*)arg;
2367 int err = NETEVENT_NOERROR;
2368 log_assert(c->type == comm_raw);
2369 ub_comm_base_now(c->ev->base);
2371 if(event&UB_EV_TIMEOUT)
2372 err = NETEVENT_TIMEOUT;
2373 fptr_ok(fptr_whitelist_comm_point_raw(c->callback));
2374 (void)(*c->callback)(c, c->cb_arg, err, NULL);
2378 comm_point_create_udp(struct comm_base *base, int fd, sldns_buffer* buffer,
2379 comm_point_callback_type* callback, void* callback_arg)
2381 struct comm_point* c = (struct comm_point*)calloc(1,
2382 sizeof(struct comm_point));
2386 c->ev = (struct internal_event*)calloc(1,
2387 sizeof(struct internal_event));
2396 c->tcp_is_reading = 0;
2397 c->tcp_byte_count = 0;
2398 c->tcp_parent = NULL;
2399 c->max_tcp_count = 0;
2400 c->cur_tcp_count = 0;
2401 c->tcp_handlers = NULL;
2404 c->tcp_do_close = 0;
2405 c->do_not_close = 0;
2406 c->tcp_do_toggle_rw = 0;
2407 c->tcp_check_nb_connect = 0;
2408 #ifdef USE_MSG_FASTOPEN
2409 c->tcp_do_fastopen = 0;
2413 c->dnscrypt_buffer = buffer;
2416 c->callback = callback;
2417 c->cb_arg = callback_arg;
2418 evbits = UB_EV_READ | UB_EV_PERSIST;
2419 /* ub_event stuff */
2420 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2421 comm_point_udp_callback, c);
2422 if(c->ev->ev == NULL) {
2423 log_err("could not baseset udp event");
2424 comm_point_delete(c);
2427 if(fd!=-1 && ub_event_add(c->ev->ev, c->timeout) != 0 ) {
2428 log_err("could not add udp event");
2429 comm_point_delete(c);
2436 comm_point_create_udp_ancil(struct comm_base *base, int fd,
2437 sldns_buffer* buffer,
2438 comm_point_callback_type* callback, void* callback_arg)
2440 struct comm_point* c = (struct comm_point*)calloc(1,
2441 sizeof(struct comm_point));
2445 c->ev = (struct internal_event*)calloc(1,
2446 sizeof(struct internal_event));
2455 c->tcp_is_reading = 0;
2456 c->tcp_byte_count = 0;
2457 c->tcp_parent = NULL;
2458 c->max_tcp_count = 0;
2459 c->cur_tcp_count = 0;
2460 c->tcp_handlers = NULL;
2463 c->tcp_do_close = 0;
2464 c->do_not_close = 0;
2467 c->dnscrypt_buffer = buffer;
2470 c->tcp_do_toggle_rw = 0;
2471 c->tcp_check_nb_connect = 0;
2472 #ifdef USE_MSG_FASTOPEN
2473 c->tcp_do_fastopen = 0;
2475 c->callback = callback;
2476 c->cb_arg = callback_arg;
2477 evbits = UB_EV_READ | UB_EV_PERSIST;
2478 /* ub_event stuff */
2479 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2480 comm_point_udp_ancil_callback, c);
2481 if(c->ev->ev == NULL) {
2482 log_err("could not baseset udp event");
2483 comm_point_delete(c);
2486 if(fd!=-1 && ub_event_add(c->ev->ev, c->timeout) != 0 ) {
2487 log_err("could not add udp event");
2488 comm_point_delete(c);
2494 static struct comm_point*
2495 comm_point_create_tcp_handler(struct comm_base *base,
2496 struct comm_point* parent, size_t bufsize,
2497 comm_point_callback_type* callback, void* callback_arg)
2499 struct comm_point* c = (struct comm_point*)calloc(1,
2500 sizeof(struct comm_point));
2504 c->ev = (struct internal_event*)calloc(1,
2505 sizeof(struct internal_event));
2512 c->buffer = sldns_buffer_new(bufsize);
2518 c->timeout = (struct timeval*)malloc(sizeof(struct timeval));
2520 sldns_buffer_free(c->buffer);
2525 c->tcp_is_reading = 0;
2526 c->tcp_byte_count = 0;
2527 c->tcp_parent = parent;
2528 c->max_tcp_count = 0;
2529 c->cur_tcp_count = 0;
2530 c->tcp_handlers = NULL;
2533 c->tcp_do_close = 0;
2534 c->do_not_close = 0;
2535 c->tcp_do_toggle_rw = 1;
2536 c->tcp_check_nb_connect = 0;
2537 #ifdef USE_MSG_FASTOPEN
2538 c->tcp_do_fastopen = 0;
2542 /* We don't know just yet if this is a dnscrypt channel. Allocation
2543 * will be done when handling the callback. */
2544 c->dnscrypt_buffer = c->buffer;
2547 c->callback = callback;
2548 c->cb_arg = callback_arg;
2549 /* add to parent free list */
2550 c->tcp_free = parent->tcp_free;
2551 parent->tcp_free = c;
2552 /* ub_event stuff */
2553 evbits = UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT;
2554 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2555 comm_point_tcp_handle_callback, c);
2556 if(c->ev->ev == NULL)
2558 log_err("could not basetset tcphdl event");
2559 parent->tcp_free = c->tcp_free;
2568 comm_point_create_tcp(struct comm_base *base, int fd, int num, size_t bufsize,
2569 comm_point_callback_type* callback, void* callback_arg)
2571 struct comm_point* c = (struct comm_point*)calloc(1,
2572 sizeof(struct comm_point));
2575 /* first allocate the TCP accept listener */
2578 c->ev = (struct internal_event*)calloc(1,
2579 sizeof(struct internal_event));
2588 c->tcp_is_reading = 0;
2589 c->tcp_byte_count = 0;
2590 c->tcp_parent = NULL;
2591 c->max_tcp_count = num;
2592 c->cur_tcp_count = 0;
2593 c->tcp_handlers = (struct comm_point**)calloc((size_t)num,
2594 sizeof(struct comm_point*));
2595 if(!c->tcp_handlers) {
2601 c->type = comm_tcp_accept;
2602 c->tcp_do_close = 0;
2603 c->do_not_close = 0;
2604 c->tcp_do_toggle_rw = 0;
2605 c->tcp_check_nb_connect = 0;
2606 #ifdef USE_MSG_FASTOPEN
2607 c->tcp_do_fastopen = 0;
2611 c->dnscrypt_buffer = NULL;
2615 evbits = UB_EV_READ | UB_EV_PERSIST;
2616 /* ub_event stuff */
2617 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2618 comm_point_tcp_accept_callback, c);
2619 if(c->ev->ev == NULL) {
2620 log_err("could not baseset tcpacc event");
2621 comm_point_delete(c);
2624 if (ub_event_add(c->ev->ev, c->timeout) != 0) {
2625 log_err("could not add tcpacc event");
2626 comm_point_delete(c);
2629 /* now prealloc the tcp handlers */
2630 for(i=0; i<num; i++) {
2631 c->tcp_handlers[i] = comm_point_create_tcp_handler(base,
2632 c, bufsize, callback, callback_arg);
2633 if(!c->tcp_handlers[i]) {
2634 comm_point_delete(c);
2643 comm_point_create_tcp_out(struct comm_base *base, size_t bufsize,
2644 comm_point_callback_type* callback, void* callback_arg)
2646 struct comm_point* c = (struct comm_point*)calloc(1,
2647 sizeof(struct comm_point));
2651 c->ev = (struct internal_event*)calloc(1,
2652 sizeof(struct internal_event));
2659 c->buffer = sldns_buffer_new(bufsize);
2666 c->tcp_is_reading = 0;
2667 c->tcp_byte_count = 0;
2668 c->tcp_parent = NULL;
2669 c->max_tcp_count = 0;
2670 c->cur_tcp_count = 0;
2671 c->tcp_handlers = NULL;
2674 c->tcp_do_close = 0;
2675 c->do_not_close = 0;
2676 c->tcp_do_toggle_rw = 1;
2677 c->tcp_check_nb_connect = 1;
2678 #ifdef USE_MSG_FASTOPEN
2679 c->tcp_do_fastopen = 1;
2683 c->dnscrypt_buffer = c->buffer;
2686 c->callback = callback;
2687 c->cb_arg = callback_arg;
2688 evbits = UB_EV_PERSIST | UB_EV_WRITE;
2689 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2690 comm_point_tcp_handle_callback, c);
2691 if(c->ev->ev == NULL)
2693 log_err("could not baseset tcpout event");
2694 sldns_buffer_free(c->buffer);
2704 comm_point_create_http_out(struct comm_base *base, size_t bufsize,
2705 comm_point_callback_type* callback, void* callback_arg,
2708 struct comm_point* c = (struct comm_point*)calloc(1,
2709 sizeof(struct comm_point));
2713 c->ev = (struct internal_event*)calloc(1,
2714 sizeof(struct internal_event));
2721 c->buffer = sldns_buffer_new(bufsize);
2728 c->tcp_is_reading = 0;
2729 c->tcp_byte_count = 0;
2730 c->tcp_parent = NULL;
2731 c->max_tcp_count = 0;
2732 c->cur_tcp_count = 0;
2733 c->tcp_handlers = NULL;
2735 c->type = comm_http;
2736 c->tcp_do_close = 0;
2737 c->do_not_close = 0;
2738 c->tcp_do_toggle_rw = 1;
2739 c->tcp_check_nb_connect = 1;
2740 c->http_in_headers = 1;
2741 c->http_in_chunk_headers = 0;
2742 c->http_is_chunked = 0;
2743 c->http_temp = temp;
2744 #ifdef USE_MSG_FASTOPEN
2745 c->tcp_do_fastopen = 1;
2749 c->dnscrypt_buffer = c->buffer;
2752 c->callback = callback;
2753 c->cb_arg = callback_arg;
2754 evbits = UB_EV_PERSIST | UB_EV_WRITE;
2755 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2756 comm_point_http_handle_callback, c);
2757 if(c->ev->ev == NULL)
2759 log_err("could not baseset tcpout event");
2763 sldns_buffer_free(c->buffer);
2773 comm_point_create_local(struct comm_base *base, int fd, size_t bufsize,
2774 comm_point_callback_type* callback, void* callback_arg)
2776 struct comm_point* c = (struct comm_point*)calloc(1,
2777 sizeof(struct comm_point));
2781 c->ev = (struct internal_event*)calloc(1,
2782 sizeof(struct internal_event));
2789 c->buffer = sldns_buffer_new(bufsize);
2796 c->tcp_is_reading = 1;
2797 c->tcp_byte_count = 0;
2798 c->tcp_parent = NULL;
2799 c->max_tcp_count = 0;
2800 c->cur_tcp_count = 0;
2801 c->tcp_handlers = NULL;
2803 c->type = comm_local;
2804 c->tcp_do_close = 0;
2805 c->do_not_close = 1;
2806 c->tcp_do_toggle_rw = 0;
2807 c->tcp_check_nb_connect = 0;
2808 #ifdef USE_MSG_FASTOPEN
2809 c->tcp_do_fastopen = 0;
2813 c->dnscrypt_buffer = c->buffer;
2815 c->callback = callback;
2816 c->cb_arg = callback_arg;
2817 /* ub_event stuff */
2818 evbits = UB_EV_PERSIST | UB_EV_READ;
2819 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2820 comm_point_local_handle_callback, c);
2821 if(c->ev->ev == NULL) {
2822 log_err("could not baseset localhdl event");
2827 if (ub_event_add(c->ev->ev, c->timeout) != 0) {
2828 log_err("could not add localhdl event");
2829 ub_event_free(c->ev->ev);
2838 comm_point_create_raw(struct comm_base* base, int fd, int writing,
2839 comm_point_callback_type* callback, void* callback_arg)
2841 struct comm_point* c = (struct comm_point*)calloc(1,
2842 sizeof(struct comm_point));
2846 c->ev = (struct internal_event*)calloc(1,
2847 sizeof(struct internal_event));
2856 c->tcp_is_reading = 0;
2857 c->tcp_byte_count = 0;
2858 c->tcp_parent = NULL;
2859 c->max_tcp_count = 0;
2860 c->cur_tcp_count = 0;
2861 c->tcp_handlers = NULL;
2864 c->tcp_do_close = 0;
2865 c->do_not_close = 1;
2866 c->tcp_do_toggle_rw = 0;
2867 c->tcp_check_nb_connect = 0;
2868 #ifdef USE_MSG_FASTOPEN
2869 c->tcp_do_fastopen = 0;
2873 c->dnscrypt_buffer = c->buffer;
2875 c->callback = callback;
2876 c->cb_arg = callback_arg;
2877 /* ub_event stuff */
2879 evbits = UB_EV_PERSIST | UB_EV_WRITE;
2880 else evbits = UB_EV_PERSIST | UB_EV_READ;
2881 c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
2882 comm_point_raw_handle_callback, c);
2883 if(c->ev->ev == NULL) {
2884 log_err("could not baseset rawhdl event");
2889 if (ub_event_add(c->ev->ev, c->timeout) != 0) {
2890 log_err("could not add rawhdl event");
2891 ub_event_free(c->ev->ev);
2900 comm_point_close(struct comm_point* c)
2905 if(ub_event_del(c->ev->ev) != 0) {
2906 log_err("could not event_del on close");
2909 /* close fd after removing from event lists, or epoll.. is messed up */
2910 if(c->fd != -1 && !c->do_not_close) {
2911 if(c->type == comm_tcp || c->type == comm_http) {
2912 /* delete sticky events for the fd, it gets closed */
2913 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
2914 ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
2916 verbose(VERB_ALGO, "close fd %d", c->fd);
2927 comm_point_delete(struct comm_point* c)
2931 if((c->type == comm_tcp || c->type == comm_http) && c->ssl) {
2933 SSL_shutdown(c->ssl);
2937 comm_point_close(c);
2938 if(c->tcp_handlers) {
2940 for(i=0; i<c->max_tcp_count; i++)
2941 comm_point_delete(c->tcp_handlers[i]);
2942 free(c->tcp_handlers);
2945 if(c->type == comm_tcp || c->type == comm_local || c->type == comm_http) {
2946 sldns_buffer_free(c->buffer);
2948 if(c->dnscrypt && c->dnscrypt_buffer != c->buffer) {
2949 sldns_buffer_free(c->dnscrypt_buffer);
2953 ub_event_free(c->ev->ev);
2959 comm_point_send_reply(struct comm_reply *repinfo)
2961 struct sldns_buffer* buffer;
2962 log_assert(repinfo && repinfo->c);
2964 buffer = repinfo->c->dnscrypt_buffer;
2965 if(!dnsc_handle_uncurved_request(repinfo)) {
2969 buffer = repinfo->c->buffer;
2971 if(repinfo->c->type == comm_udp) {
2972 if(repinfo->srctype)
2973 comm_point_send_udp_msg_if(repinfo->c,
2974 buffer, (struct sockaddr*)&repinfo->addr,
2975 repinfo->addrlen, repinfo);
2977 comm_point_send_udp_msg(repinfo->c, buffer,
2978 (struct sockaddr*)&repinfo->addr, repinfo->addrlen);
2980 if(repinfo->c->dtenv != NULL &&
2981 repinfo->c->dtenv->log_client_response_messages)
2982 dt_msg_send_client_response(repinfo->c->dtenv,
2983 &repinfo->addr, repinfo->c->type, repinfo->c->buffer);
2987 if(repinfo->c->tcp_parent->dtenv != NULL &&
2988 repinfo->c->tcp_parent->dtenv->log_client_response_messages)
2989 dt_msg_send_client_response(repinfo->c->tcp_parent->dtenv,
2990 &repinfo->addr, repinfo->c->type, repinfo->c->buffer);
2992 comm_point_start_listening(repinfo->c, -1,
2993 repinfo->c->tcp_timeout_msec);
2998 comm_point_drop_reply(struct comm_reply* repinfo)
3002 log_assert(repinfo && repinfo->c);
3003 log_assert(repinfo->c->type != comm_tcp_accept);
3004 if(repinfo->c->type == comm_udp)
3006 reclaim_tcp_handler(repinfo->c);
3010 comm_point_stop_listening(struct comm_point* c)
3012 verbose(VERB_ALGO, "comm point stop listening %d", c->fd);
3013 if(ub_event_del(c->ev->ev) != 0) {
3014 log_err("event_del error to stoplisten");
3019 comm_point_start_listening(struct comm_point* c, int newfd, int msec)
3021 verbose(VERB_ALGO, "comm point start listening %d",
3022 c->fd==-1?newfd:c->fd);
3023 if(c->type == comm_tcp_accept && !c->tcp_free) {
3024 /* no use to start listening no free slots. */
3027 if(msec != -1 && msec != 0) {
3029 c->timeout = (struct timeval*)malloc(sizeof(
3032 log_err("cpsl: malloc failed. No net read.");
3036 ub_event_add_bits(c->ev->ev, UB_EV_TIMEOUT);
3037 #ifndef S_SPLINT_S /* splint fails on struct timeval. */
3038 c->timeout->tv_sec = msec/1000;
3039 c->timeout->tv_usec = (msec%1000)*1000;
3040 #endif /* S_SPLINT_S */
3042 if(c->type == comm_tcp || c->type == comm_http) {
3043 ub_event_del_bits(c->ev->ev, UB_EV_READ|UB_EV_WRITE);
3044 if(c->tcp_is_reading)
3045 ub_event_add_bits(c->ev->ev, UB_EV_READ);
3046 else ub_event_add_bits(c->ev->ev, UB_EV_WRITE);
3057 ub_event_set_fd(c->ev->ev, c->fd);
3059 if(ub_event_add(c->ev->ev, msec==0?NULL:c->timeout) != 0) {
3060 log_err("event_add failed. in cpsl.");
3064 void comm_point_listen_for_rw(struct comm_point* c, int rd, int wr)
3066 verbose(VERB_ALGO, "comm point listen_for_rw %d %d", c->fd, wr);
3067 if(ub_event_del(c->ev->ev) != 0) {
3068 log_err("event_del error to cplf");
3070 ub_event_del_bits(c->ev->ev, UB_EV_READ|UB_EV_WRITE);
3071 if(rd) ub_event_add_bits(c->ev->ev, UB_EV_READ);
3072 if(wr) ub_event_add_bits(c->ev->ev, UB_EV_WRITE);
3073 if(ub_event_add(c->ev->ev, c->timeout) != 0) {
3074 log_err("event_add failed. in cplf.");
3078 size_t comm_point_get_mem(struct comm_point* c)
3083 s = sizeof(*c) + sizeof(*c->ev);
3085 s += sizeof(*c->timeout);
3086 if(c->type == comm_tcp || c->type == comm_local) {
3087 s += sizeof(*c->buffer) + sldns_buffer_capacity(c->buffer);
3089 s += sizeof(*c->dnscrypt_buffer);
3090 if(c->buffer != c->dnscrypt_buffer) {
3091 s += sldns_buffer_capacity(c->dnscrypt_buffer);
3095 if(c->type == comm_tcp_accept) {
3097 for(i=0; i<c->max_tcp_count; i++)
3098 s += comm_point_get_mem(c->tcp_handlers[i]);
3104 comm_timer_create(struct comm_base* base, void (*cb)(void*), void* cb_arg)
3106 struct internal_timer *tm = (struct internal_timer*)calloc(1,
3107 sizeof(struct internal_timer));
3109 log_err("malloc failed");
3112 tm->super.ev_timer = tm;
3114 tm->super.callback = cb;
3115 tm->super.cb_arg = cb_arg;
3116 tm->ev = ub_event_new(base->eb->base, -1, UB_EV_TIMEOUT,
3117 comm_timer_callback, &tm->super);
3118 if(tm->ev == NULL) {
3119 log_err("timer_create: event_base_set failed.");
3127 comm_timer_disable(struct comm_timer* timer)
3131 ub_timer_del(timer->ev_timer->ev);
3132 timer->ev_timer->enabled = 0;
3136 comm_timer_set(struct comm_timer* timer, struct timeval* tv)
3139 if(timer->ev_timer->enabled)
3140 comm_timer_disable(timer);
3141 if(ub_timer_add(timer->ev_timer->ev, timer->ev_timer->base->eb->base,
3142 comm_timer_callback, timer, tv) != 0)
3143 log_err("comm_timer_set: evtimer_add failed.");
3144 timer->ev_timer->enabled = 1;
3148 comm_timer_delete(struct comm_timer* timer)
3152 comm_timer_disable(timer);
3153 /* Free the sub struct timer->ev_timer derived from the super struct timer.
3154 * i.e. assert(timer == timer->ev_timer)
3156 ub_event_free(timer->ev_timer->ev);
3157 free(timer->ev_timer);
3161 comm_timer_callback(int ATTR_UNUSED(fd), short event, void* arg)
3163 struct comm_timer* tm = (struct comm_timer*)arg;
3164 if(!(event&UB_EV_TIMEOUT))
3166 ub_comm_base_now(tm->ev_timer->base);
3167 tm->ev_timer->enabled = 0;
3168 fptr_ok(fptr_whitelist_comm_timer(tm->callback));
3169 (*tm->callback)(tm->cb_arg);
3173 comm_timer_is_set(struct comm_timer* timer)
3175 return (int)timer->ev_timer->enabled;
3179 comm_timer_get_mem(struct comm_timer* ATTR_UNUSED(timer))
3181 return sizeof(struct internal_timer);
3185 comm_signal_create(struct comm_base* base,
3186 void (*callback)(int, void*), void* cb_arg)
3188 struct comm_signal* com = (struct comm_signal*)malloc(
3189 sizeof(struct comm_signal));
3191 log_err("malloc failed");
3195 com->callback = callback;
3196 com->cb_arg = cb_arg;
3197 com->ev_signal = NULL;
3202 comm_signal_callback(int sig, short event, void* arg)
3204 struct comm_signal* comsig = (struct comm_signal*)arg;
3205 if(!(event & UB_EV_SIGNAL))
3207 ub_comm_base_now(comsig->base);
3208 fptr_ok(fptr_whitelist_comm_signal(comsig->callback));
3209 (*comsig->callback)(sig, comsig->cb_arg);
3213 comm_signal_bind(struct comm_signal* comsig, int sig)
3215 struct internal_signal* entry = (struct internal_signal*)calloc(1,
3216 sizeof(struct internal_signal));
3218 log_err("malloc failed");
3222 /* add signal event */
3223 entry->ev = ub_signal_new(comsig->base->eb->base, sig,
3224 comm_signal_callback, comsig);
3225 if(entry->ev == NULL) {
3226 log_err("Could not create signal event");
3230 if(ub_signal_add(entry->ev, NULL) != 0) {
3231 log_err("Could not add signal handler");
3232 ub_event_free(entry->ev);
3236 /* link into list */
3237 entry->next = comsig->ev_signal;
3238 comsig->ev_signal = entry;
3243 comm_signal_delete(struct comm_signal* comsig)
3245 struct internal_signal* p, *np;
3248 p=comsig->ev_signal;
3251 ub_signal_del(p->ev);
3252 ub_event_free(p->ev);