2 /* Copyright 1998 by the Massachusetts Institute of Technology.
3 * Copyright (C) 2004-2013 by Daniel Stenberg
5 * Permission to use, copy, modify, and distribute this
6 * software and its documentation for any purpose and without
7 * fee is hereby granted, provided that the above copyright
8 * notice appear in all copies and that both that copyright
9 * notice and this permission notice appear in supporting
10 * documentation, and that the name of M.I.T. not be used in
11 * advertising or publicity pertaining to distribution of the
12 * software without specific, written prior permission.
13 * M.I.T. makes no representations about the suitability of
14 * this software for any purpose. It is provided "as is"
15 * without express or implied warranty.
18 #include "ares_setup.h"
23 #ifdef HAVE_NETINET_IN_H
24 # include <netinet/in.h>
26 #ifdef HAVE_NETINET_TCP_H
27 # include <netinet/tcp.h>
32 #ifdef HAVE_ARPA_NAMESER_H
33 # include <arpa/nameser.h>
37 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
38 # include <arpa/nameser_compat.h>
44 #ifdef HAVE_SYS_IOCTL_H
45 # include <sys/ioctl.h>
48 # include <sys/filio.h>
56 #include "ares_nowarn.h"
57 #include "ares_private.h"
60 static int try_again(int errnum);
61 static void write_tcp_data(ares_channel channel, fd_set *write_fds,
62 ares_socket_t write_fd, struct timeval *now);
63 static void read_tcp_data(ares_channel channel, fd_set *read_fds,
64 ares_socket_t read_fd, struct timeval *now);
65 static void read_udp_packets(ares_channel channel, fd_set *read_fds,
66 ares_socket_t read_fd, struct timeval *now);
67 static void advance_tcp_send_queue(ares_channel channel, int whichserver,
69 static void process_timeouts(ares_channel channel, struct timeval *now);
70 static void process_broken_connections(ares_channel channel,
72 static void process_answer(ares_channel channel, unsigned char *abuf,
73 int alen, int whichserver, int tcp,
75 static void handle_error(ares_channel channel, int whichserver,
77 static void skip_server(ares_channel channel, struct query *query,
79 static void next_server(ares_channel channel, struct query *query,
81 static int open_tcp_socket(ares_channel channel, struct server_state *server);
82 static int open_udp_socket(ares_channel channel, struct server_state *server);
83 static int same_questions(const unsigned char *qbuf, int qlen,
84 const unsigned char *abuf, int alen);
85 static int same_address(struct sockaddr *sa, struct ares_addr *aa);
86 static void end_query(ares_channel channel, struct query *query, int status,
87 unsigned char *abuf, int alen);
89 /* return true if now is exactly check time or later */
90 int ares__timedout(struct timeval *now,
91 struct timeval *check)
93 long secs = (now->tv_sec - check->tv_sec);
96 return 1; /* yes, timed out */
98 return 0; /* nope, not timed out */
100 /* if the full seconds were identical, check the sub second parts */
101 return (now->tv_usec - check->tv_usec >= 0);
104 /* add the specific number of milliseconds to the time in the first argument */
105 int ares__timeadd(struct timeval *now,
108 now->tv_sec += millisecs/1000;
109 now->tv_usec += (millisecs%1000)*1000;
111 if(now->tv_usec >= 1000000) {
113 now->tv_usec -= 1000000;
119 /* return time offset between now and (future) check, in milliseconds */
120 long ares__timeoffset(struct timeval *now,
121 struct timeval *check)
123 return (check->tv_sec - now->tv_sec)*1000 +
124 (check->tv_usec - now->tv_usec)/1000;
129 * generic process function
131 static void processfds(ares_channel channel,
132 fd_set *read_fds, ares_socket_t read_fd,
133 fd_set *write_fds, ares_socket_t write_fd)
135 struct timeval now = ares__tvnow();
137 write_tcp_data(channel, write_fds, write_fd, &now);
138 read_tcp_data(channel, read_fds, read_fd, &now);
139 read_udp_packets(channel, read_fds, read_fd, &now);
140 process_timeouts(channel, &now);
141 process_broken_connections(channel, &now);
144 /* Something interesting happened on the wire, or there was a timeout.
145 * See what's up and respond accordingly.
147 void ares_process(ares_channel channel, fd_set *read_fds, fd_set *write_fds)
149 processfds(channel, read_fds, ARES_SOCKET_BAD, write_fds, ARES_SOCKET_BAD);
152 /* Something interesting happened on the wire, or there was a timeout.
153 * See what's up and respond accordingly.
155 void ares_process_fd(ares_channel channel,
156 ares_socket_t read_fd, /* use ARES_SOCKET_BAD or valid
158 ares_socket_t write_fd)
160 processfds(channel, NULL, read_fd, NULL, write_fd);
164 /* Return 1 if the specified error number describes a readiness error, or 0
165 * otherwise. This is mostly for HP-UX, which could return EAGAIN or
166 * EWOULDBLOCK. See this man page
168 * http://devrsrc1.external.hp.com/STKS/cgi-bin/man2html?
169 * manpage=/usr/share/man/man2.Z/send.2
171 static int try_again(int errnum)
173 #if !defined EWOULDBLOCK && !defined EAGAIN
174 #error "Neither EWOULDBLOCK nor EAGAIN defined"
182 #if defined EAGAIN && EAGAIN != EWOULDBLOCK
190 /* If any TCP sockets select true for writing, write out queued data
193 static void write_tcp_data(ares_channel channel,
195 ares_socket_t write_fd,
198 struct server_state *server;
199 struct send_request *sendreq;
206 if(!write_fds && (write_fd == ARES_SOCKET_BAD))
207 /* no possible action */
210 for (i = 0; i < channel->nservers; i++)
212 /* Make sure server has data to send and is selected in write_fds or
214 server = &channel->servers[i];
215 if (!server->qhead || server->tcp_socket == ARES_SOCKET_BAD ||
220 if(!FD_ISSET(server->tcp_socket, write_fds))
224 if(server->tcp_socket != write_fd)
229 /* If there's an error and we close this socket, then open
230 * another with the same fd to talk to another server, then we
231 * don't want to think that it was the new socket that was
232 * ready. This is not disastrous, but is likely to result in
233 * extra system calls and confusion. */
234 FD_CLR(server->tcp_socket, write_fds);
236 /* Count the number of send queue items. */
238 for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
241 /* Allocate iovecs so we can send all our data at once. */
242 vec = malloc(n * sizeof(struct iovec));
245 /* Fill in the iovecs and send. */
247 for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
249 vec[n].iov_base = (char *) sendreq->data;
250 vec[n].iov_len = sendreq->len;
253 wcount = (ssize_t)writev(server->tcp_socket, vec, (int)n);
257 if (!try_again(SOCKERRNO))
258 handle_error(channel, i, now);
262 /* Advance the send queue by as many bytes as we sent. */
263 advance_tcp_send_queue(channel, i, wcount);
267 /* Can't allocate iovecs; just send the first request. */
268 sendreq = server->qhead;
270 scount = swrite(server->tcp_socket, sendreq->data, sendreq->len);
273 if (!try_again(SOCKERRNO))
274 handle_error(channel, i, now);
278 /* Advance the send queue by as many bytes as we sent. */
279 advance_tcp_send_queue(channel, i, scount);
284 /* Consume the given number of bytes from the head of the TCP send queue. */
285 static void advance_tcp_send_queue(ares_channel channel, int whichserver,
288 struct send_request *sendreq;
289 struct server_state *server = &channel->servers[whichserver];
290 while (num_bytes > 0) {
291 sendreq = server->qhead;
292 if ((size_t)num_bytes >= sendreq->len) {
293 num_bytes -= sendreq->len;
294 server->qhead = sendreq->next;
295 if (sendreq->data_storage)
296 free(sendreq->data_storage);
298 if (server->qhead == NULL) {
299 SOCK_STATE_CALLBACK(channel, server->tcp_socket, 1, 0);
300 server->qtail = NULL;
302 /* qhead is NULL so we cannot continue this loop */
307 sendreq->data += num_bytes;
308 sendreq->len -= num_bytes;
314 /* If any TCP socket selects true for reading, read some data,
315 * allocate a buffer if we finish reading the length word, and process
316 * a packet if we finish reading one.
318 static void read_tcp_data(ares_channel channel, fd_set *read_fds,
319 ares_socket_t read_fd, struct timeval *now)
321 struct server_state *server;
325 if(!read_fds && (read_fd == ARES_SOCKET_BAD))
326 /* no possible action */
329 for (i = 0; i < channel->nservers; i++)
331 /* Make sure the server has a socket and is selected in read_fds. */
332 server = &channel->servers[i];
333 if (server->tcp_socket == ARES_SOCKET_BAD || server->is_broken)
337 if(!FD_ISSET(server->tcp_socket, read_fds))
341 if(server->tcp_socket != read_fd)
346 /* If there's an error and we close this socket, then open another
347 * with the same fd to talk to another server, then we don't want to
348 * think that it was the new socket that was ready. This is not
349 * disastrous, but is likely to result in extra system calls and
351 FD_CLR(server->tcp_socket, read_fds);
353 if (server->tcp_lenbuf_pos != 2)
355 /* We haven't yet read a length word, so read that (or
356 * what's left to read of it).
358 count = sread(server->tcp_socket,
359 server->tcp_lenbuf + server->tcp_lenbuf_pos,
360 2 - server->tcp_lenbuf_pos);
363 if (!(count == -1 && try_again(SOCKERRNO)))
364 handle_error(channel, i, now);
368 server->tcp_lenbuf_pos += (int)count;
369 if (server->tcp_lenbuf_pos == 2)
371 /* We finished reading the length word. Decode the
372 * length and allocate a buffer for the data.
374 server->tcp_length = server->tcp_lenbuf[0] << 8
375 | server->tcp_lenbuf[1];
376 server->tcp_buffer = malloc(server->tcp_length);
377 if (!server->tcp_buffer)
378 handle_error(channel, i, now);
379 server->tcp_buffer_pos = 0;
384 /* Read data into the allocated buffer. */
385 count = sread(server->tcp_socket,
386 server->tcp_buffer + server->tcp_buffer_pos,
387 server->tcp_length - server->tcp_buffer_pos);
390 if (!(count == -1 && try_again(SOCKERRNO)))
391 handle_error(channel, i, now);
395 server->tcp_buffer_pos += (int)count;
396 if (server->tcp_buffer_pos == server->tcp_length)
398 /* We finished reading this answer; process it and
399 * prepare to read another length word.
401 process_answer(channel, server->tcp_buffer, server->tcp_length,
403 if (server->tcp_buffer)
404 free(server->tcp_buffer);
405 server->tcp_buffer = NULL;
406 server->tcp_lenbuf_pos = 0;
407 server->tcp_buffer_pos = 0;
413 /* If any UDP sockets select true for reading, process them. */
414 static void read_udp_packets(ares_channel channel, fd_set *read_fds,
415 ares_socket_t read_fd, struct timeval *now)
417 struct server_state *server;
420 unsigned char buf[MAXENDSSZ + 1];
422 ares_socklen_t fromlen;
425 struct sockaddr_in sa4;
426 struct sockaddr_in6 sa6;
430 if(!read_fds && (read_fd == ARES_SOCKET_BAD))
431 /* no possible action */
434 for (i = 0; i < channel->nservers; i++)
436 /* Make sure the server has a socket and is selected in read_fds. */
437 server = &channel->servers[i];
439 if (server->udp_socket == ARES_SOCKET_BAD || server->is_broken)
443 if(!FD_ISSET(server->udp_socket, read_fds))
447 if(server->udp_socket != read_fd)
452 /* If there's an error and we close this socket, then open
453 * another with the same fd to talk to another server, then we
454 * don't want to think that it was the new socket that was
455 * ready. This is not disastrous, but is likely to result in
456 * extra system calls and confusion. */
457 FD_CLR(server->udp_socket, read_fds);
459 /* To reduce event loop overhead, read and process as many
460 * packets as we can. */
462 if (server->udp_socket == ARES_SOCKET_BAD)
467 if (server->addr.family == AF_INET)
468 fromlen = sizeof(from.sa4);
470 fromlen = sizeof(from.sa6);
471 count = (ssize_t)recvfrom(server->udp_socket, (void *)buf,
472 sizeof(buf), 0, &from.sa, &fromlen);
474 count = sread(server->udp_socket, buf, sizeof(buf));
478 if (count == -1 && try_again(SOCKERRNO))
481 handle_error(channel, i, now);
483 else if (!same_address(&from.sa, &server->addr))
484 /* The address the response comes from does not match the address we
485 * sent the request to. Someone may be attempting to perform a cache
486 * poisoning attack. */
490 process_answer(channel, buf, (int)count, i, 0, now);
495 /* If any queries have timed out, note the timeout and move them on. */
496 static void process_timeouts(ares_channel channel, struct timeval *now)
498 time_t t; /* the time of the timeouts we're processing */
500 struct list_node* list_head;
501 struct list_node* list_node;
503 /* Process all the timeouts that have fired since the last time we processed
504 * timeouts. If things are going well, then we'll have hundreds/thousands of
505 * queries that fall into future buckets, and only a handful of requests
506 * that fall into the "now" bucket, so this should be quite quick.
508 for (t = channel->last_timeout_processed; t <= now->tv_sec; t++)
510 list_head = &(channel->queries_by_timeout[t % ARES_TIMEOUT_TABLE_SIZE]);
511 for (list_node = list_head->next; list_node != list_head; )
513 query = list_node->data;
514 list_node = list_node->next; /* in case the query gets deleted */
515 if (query->timeout.tv_sec && ares__timedout(now, &query->timeout))
517 query->error_status = ARES_ETIMEOUT;
519 next_server(channel, query, now);
523 channel->last_timeout_processed = now->tv_sec;
526 /* Handle an answer from a server. */
527 static void process_answer(ares_channel channel, unsigned char *abuf,
528 int alen, int whichserver, int tcp,
531 int tc, rcode, packetsz;
534 struct list_node* list_head;
535 struct list_node* list_node;
537 /* If there's no room in the answer for a header, we can't do much
542 /* Grab the query ID, truncate bit, and response code from the packet. */
543 id = DNS_HEADER_QID(abuf);
544 tc = DNS_HEADER_TC(abuf);
545 rcode = DNS_HEADER_RCODE(abuf);
547 /* Find the query corresponding to this packet. The queries are
548 * hashed/bucketed by query id, so this lookup should be quick. Note that
549 * both the query id and the questions must be the same; when the query id
550 * wraps around we can have multiple outstanding queries with the same query
551 * id, so we need to check both the id and question.
554 list_head = &(channel->queries_by_qid[id % ARES_QID_TABLE_SIZE]);
555 for (list_node = list_head->next; list_node != list_head;
556 list_node = list_node->next)
558 struct query *q = list_node->data;
559 if ((q->qid == id) && same_questions(q->qbuf, q->qlen, abuf, alen))
569 /* If we use EDNS and server answers with one of these RCODES, the protocol
570 * extension is not understood by the responder. We must retry the query
571 * without EDNS enabled.
573 if (channel->flags & ARES_FLAG_EDNS)
575 packetsz = channel->ednspsz;
576 if (rcode == NOTIMP || rcode == FORMERR || rcode == SERVFAIL)
578 int qlen = alen - EDNSFIXEDSZ;
579 channel->flags ^= ARES_FLAG_EDNS;
580 query->tcplen -= EDNSFIXEDSZ;
581 query->qlen -= EDNSFIXEDSZ;
582 query->tcpbuf[0] = (unsigned char)((qlen >> 8) & 0xff);
583 query->tcpbuf[1] = (unsigned char)(qlen & 0xff);
584 DNS_HEADER_SET_ARCOUNT(query->tcpbuf + 2, 0);
585 query->tcpbuf = realloc(query->tcpbuf, query->tcplen);
586 ares__send_query(channel, query, now);
591 /* If we got a truncated UDP packet and are not ignoring truncation,
592 * don't accept the packet, and switch the query to TCP if we hadn't
595 if ((tc || alen > packetsz) && !tcp && !(channel->flags & ARES_FLAG_IGNTC))
597 if (!query->using_tcp)
599 query->using_tcp = 1;
600 ares__send_query(channel, query, now);
605 /* Limit alen to PACKETSZ if we aren't using TCP (only relevant if we
606 * are ignoring truncation.
608 if (alen > packetsz && !tcp)
611 /* If we aren't passing through all error packets, discard packets
612 * with SERVFAIL, NOTIMP, or REFUSED response codes.
614 if (!(channel->flags & ARES_FLAG_NOCHECKRESP))
616 if (rcode == SERVFAIL || rcode == NOTIMP || rcode == REFUSED)
618 skip_server(channel, query, whichserver);
619 if (query->server == whichserver)
620 next_server(channel, query, now);
625 end_query(channel, query, ARES_SUCCESS, abuf, alen);
628 /* Close all the connections that are no longer usable. */
629 static void process_broken_connections(ares_channel channel,
633 for (i = 0; i < channel->nservers; i++)
635 struct server_state *server = &channel->servers[i];
636 if (server->is_broken)
638 handle_error(channel, i, now);
643 /* Swap the contents of two lists */
644 static void swap_lists(struct list_node* head_a,
645 struct list_node* head_b)
647 int is_a_empty = ares__is_list_empty(head_a);
648 int is_b_empty = ares__is_list_empty(head_b);
649 struct list_node old_a = *head_a;
650 struct list_node old_b = *head_b;
653 ares__init_list_head(head_b);
656 old_a.next->prev = head_b;
657 old_a.prev->next = head_b;
660 ares__init_list_head(head_a);
663 old_b.next->prev = head_a;
664 old_b.prev->next = head_a;
668 static void handle_error(ares_channel channel, int whichserver,
671 struct server_state *server;
673 struct list_node list_head;
674 struct list_node* list_node;
676 server = &channel->servers[whichserver];
678 /* Reset communications with this server. */
679 ares__close_sockets(channel, server);
681 /* Tell all queries talking to this server to move on and not try this
682 * server again. We steal the current list of queries that were in-flight to
683 * this server, since when we call next_server this can cause the queries to
684 * be re-sent to this server, which will re-insert these queries in that
685 * same server->queries_to_server list.
687 ares__init_list_head(&list_head);
688 swap_lists(&list_head, &(server->queries_to_server));
689 for (list_node = list_head.next; list_node != &list_head; )
691 query = list_node->data;
692 list_node = list_node->next; /* in case the query gets deleted */
693 assert(query->server == whichserver);
694 skip_server(channel, query, whichserver);
695 next_server(channel, query, now);
697 /* Each query should have removed itself from our temporary list as
698 * it re-sent itself or finished up...
700 assert(ares__is_list_empty(&list_head));
703 static void skip_server(ares_channel channel, struct query *query,
706 /* The given server gave us problems with this query, so if we have the
707 * luxury of using other servers, then let's skip the potentially broken
708 * server and just use the others. If we only have one server and we need to
709 * retry then we should just go ahead and re-use that server, since it's our
710 * only hope; perhaps we just got unlucky, and retrying will work (eg, the
711 * server timed out our TCP connection just as we were sending another
714 if (channel->nservers > 1)
716 query->server_info[whichserver].skip_server = 1;
720 static void next_server(ares_channel channel, struct query *query,
723 /* We need to try each server channel->tries times. We have channel->nservers
724 * servers to try. In total, we need to do channel->nservers * channel->tries
725 * attempts. Use query->try to remember how many times we already attempted
726 * this query. Use modular arithmetic to find the next server to try. */
727 while (++(query->try_count) < (channel->nservers * channel->tries))
729 struct server_state *server;
731 /* Move on to the next server. */
732 query->server = (query->server + 1) % channel->nservers;
733 server = &channel->servers[query->server];
735 /* We don't want to use this server if (1) we decided this connection is
736 * broken, and thus about to be closed, (2) we've decided to skip this
737 * server because of earlier errors we encountered, or (3) we already
738 * sent this query over this exact connection.
740 if (!server->is_broken &&
741 !query->server_info[query->server].skip_server &&
742 !(query->using_tcp &&
743 (query->server_info[query->server].tcp_connection_generation ==
744 server->tcp_connection_generation)))
746 ares__send_query(channel, query, now);
750 /* You might think that with TCP we only need one try. However, even
751 * when using TCP, servers can time-out our connection just as we're
752 * sending a request, or close our connection because they die, or never
753 * send us a reply because they get wedged or tickle a bug that drops
758 /* If we are here, all attempts to perform query failed. */
759 end_query(channel, query, query->error_status, NULL, 0);
762 void ares__send_query(ares_channel channel, struct query *query,
765 struct send_request *sendreq;
766 struct server_state *server;
769 server = &channel->servers[query->server];
770 if (query->using_tcp)
772 /* Make sure the TCP socket for this server is set up and queue
775 if (server->tcp_socket == ARES_SOCKET_BAD)
777 if (open_tcp_socket(channel, server) == -1)
779 skip_server(channel, query, query->server);
780 next_server(channel, query, now);
784 sendreq = calloc(1, sizeof(struct send_request));
787 end_query(channel, query, ARES_ENOMEM, NULL, 0);
790 /* To make the common case fast, we avoid copies by using the query's
791 * tcpbuf for as long as the query is alive. In the rare case where the
792 * query ends while it's queued for transmission, then we give the
793 * sendreq its own copy of the request packet and put it in
794 * sendreq->data_storage.
796 sendreq->data_storage = NULL;
797 sendreq->data = query->tcpbuf;
798 sendreq->len = query->tcplen;
799 sendreq->owner_query = query;
800 sendreq->next = NULL;
802 server->qtail->next = sendreq;
805 SOCK_STATE_CALLBACK(channel, server->tcp_socket, 1, 1);
806 server->qhead = sendreq;
808 server->qtail = sendreq;
809 query->server_info[query->server].tcp_connection_generation =
810 server->tcp_connection_generation;
814 if (server->udp_socket == ARES_SOCKET_BAD)
816 if (open_udp_socket(channel, server) == -1)
818 skip_server(channel, query, query->server);
819 next_server(channel, query, now);
823 if (swrite(server->udp_socket, query->qbuf, query->qlen) == -1)
825 /* FIXME: Handle EAGAIN here since it likely can happen. */
826 skip_server(channel, query, query->server);
827 next_server(channel, query, now);
831 timeplus = channel->timeout << (query->try_count / channel->nservers);
832 timeplus = (timeplus * (9 + (rand () & 7))) / 16;
833 query->timeout = *now;
834 ares__timeadd(&query->timeout,
836 /* Keep track of queries bucketed by timeout, so we can process
837 * timeout events quickly.
839 ares__remove_from_list(&(query->queries_by_timeout));
840 ares__insert_in_list(
841 &(query->queries_by_timeout),
842 &(channel->queries_by_timeout[query->timeout.tv_sec %
843 ARES_TIMEOUT_TABLE_SIZE]));
845 /* Keep track of queries bucketed by server, so we can process server
848 ares__remove_from_list(&(query->queries_to_server));
849 ares__insert_in_list(&(query->queries_to_server),
850 &(server->queries_to_server));
854 * setsocknonblock sets the given socket to either blocking or non-blocking
855 * mode based on the 'nonblock' boolean argument. This function is highly
858 static int setsocknonblock(ares_socket_t sockfd, /* operate on this */
859 int nonblock /* TRUE or FALSE */)
861 #if defined(USE_BLOCKING_SOCKETS)
863 return 0; /* returns success */
865 #elif defined(HAVE_FCNTL_O_NONBLOCK)
867 /* most recent unix versions */
869 flags = fcntl(sockfd, F_GETFL, 0);
870 if (FALSE != nonblock)
871 return fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
873 return fcntl(sockfd, F_SETFL, flags & (~O_NONBLOCK));
875 #elif defined(HAVE_IOCTL_FIONBIO)
877 /* older unix versions */
878 int flags = nonblock ? 1 : 0;
879 return ioctl(sockfd, FIONBIO, &flags);
881 #elif defined(HAVE_IOCTLSOCKET_FIONBIO)
884 char flags = nonblock ? 1 : 0;
887 unsigned long flags = nonblock ? 1UL : 0UL;
889 return ioctlsocket(sockfd, FIONBIO, &flags);
891 #elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO)
894 long flags = nonblock ? 1L : 0L;
895 return IoctlSocket(sockfd, FIONBIO, flags);
897 #elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK)
900 long b = nonblock ? 1L : 0L;
901 return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
904 # error "no non-blocking method was found/used/set"
908 static int configure_socket(ares_socket_t s, int family, ares_channel channel)
912 struct sockaddr_in sa4;
913 struct sockaddr_in6 sa6;
916 setsocknonblock(s, TRUE);
918 #if defined(FD_CLOEXEC) && !defined(MSDOS)
919 /* Configure the socket fd as close-on-exec. */
920 if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1)
924 /* Set the socket's send and receive buffer sizes. */
925 if ((channel->socket_send_buffer_size > 0) &&
926 setsockopt(s, SOL_SOCKET, SO_SNDBUF,
927 (void *)&channel->socket_send_buffer_size,
928 sizeof(channel->socket_send_buffer_size)) == -1)
931 if ((channel->socket_receive_buffer_size > 0) &&
932 setsockopt(s, SOL_SOCKET, SO_RCVBUF,
933 (void *)&channel->socket_receive_buffer_size,
934 sizeof(channel->socket_receive_buffer_size)) == -1)
937 #ifdef SO_BINDTODEVICE
938 if (channel->local_dev_name[0]) {
939 if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE,
940 channel->local_dev_name, sizeof(channel->local_dev_name))) {
941 /* Only root can do this, and usually not fatal if it doesn't work, so */
942 /* just continue on. */
947 if (family == AF_INET) {
948 if (channel->local_ip4) {
949 memset(&local.sa4, 0, sizeof(local.sa4));
950 local.sa4.sin_family = AF_INET;
951 local.sa4.sin_addr.s_addr = htonl(channel->local_ip4);
952 if (bind(s, &local.sa, sizeof(local.sa4)) < 0)
956 else if (family == AF_INET6) {
957 if (memcmp(channel->local_ip6, &ares_in6addr_any,
958 sizeof(channel->local_ip6)) != 0) {
959 memset(&local.sa6, 0, sizeof(local.sa6));
960 local.sa6.sin6_family = AF_INET6;
961 memcpy(&local.sa6.sin6_addr, channel->local_ip6,
962 sizeof(channel->local_ip6));
963 if (bind(s, &local.sa, sizeof(local.sa6)) < 0)
971 static int open_tcp_socket(ares_channel channel, struct server_state *server)
975 ares_socklen_t salen;
977 struct sockaddr_in sa4;
978 struct sockaddr_in6 sa6;
982 switch (server->addr.family)
985 sa = (void *)&saddr.sa4;
986 salen = sizeof(saddr.sa4);
987 memset(sa, 0, salen);
988 saddr.sa4.sin_family = AF_INET;
989 saddr.sa4.sin_port = aresx_sitous(channel->tcp_port);
990 memcpy(&saddr.sa4.sin_addr, &server->addr.addrV4,
991 sizeof(server->addr.addrV4));
994 sa = (void *)&saddr.sa6;
995 salen = sizeof(saddr.sa6);
996 memset(sa, 0, salen);
997 saddr.sa6.sin6_family = AF_INET6;
998 saddr.sa6.sin6_port = aresx_sitous(channel->tcp_port);
999 memcpy(&saddr.sa6.sin6_addr, &server->addr.addrV6,
1000 sizeof(server->addr.addrV6));
1006 /* Acquire a socket. */
1007 s = socket(server->addr.family, SOCK_STREAM, 0);
1008 if (s == ARES_SOCKET_BAD)
1012 if (configure_socket(s, server->addr.family, channel) < 0)
1020 * Disable the Nagle algorithm (only relevant for TCP sockets, and thus not
1021 * in configure_socket). In general, in DNS lookups we're pretty much
1022 * interested in firing off a single request and then waiting for a reply,
1023 * so batching isn't very interesting.
1026 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
1027 (void *)&opt, sizeof(opt)) == -1)
1034 /* Connect to the server. */
1035 if (connect(s, sa, salen) == -1)
1037 int err = SOCKERRNO;
1039 if (err != EINPROGRESS && err != EWOULDBLOCK)
1046 if (channel->sock_create_cb)
1048 int err = channel->sock_create_cb(s, SOCK_STREAM,
1049 channel->sock_create_cb_data);
1057 SOCK_STATE_CALLBACK(channel, s, 1, 0);
1058 server->tcp_buffer_pos = 0;
1059 server->tcp_socket = s;
1060 server->tcp_connection_generation = ++channel->tcp_connection_generation;
1064 static int open_udp_socket(ares_channel channel, struct server_state *server)
1067 ares_socklen_t salen;
1069 struct sockaddr_in sa4;
1070 struct sockaddr_in6 sa6;
1072 struct sockaddr *sa;
1074 switch (server->addr.family)
1077 sa = (void *)&saddr.sa4;
1078 salen = sizeof(saddr.sa4);
1079 memset(sa, 0, salen);
1080 saddr.sa4.sin_family = AF_INET;
1081 saddr.sa4.sin_port = aresx_sitous(channel->udp_port);
1082 memcpy(&saddr.sa4.sin_addr, &server->addr.addrV4,
1083 sizeof(server->addr.addrV4));
1086 sa = (void *)&saddr.sa6;
1087 salen = sizeof(saddr.sa6);
1088 memset(sa, 0, salen);
1089 saddr.sa6.sin6_family = AF_INET6;
1090 saddr.sa6.sin6_port = aresx_sitous(channel->udp_port);
1091 memcpy(&saddr.sa6.sin6_addr, &server->addr.addrV6,
1092 sizeof(server->addr.addrV6));
1098 /* Acquire a socket. */
1099 s = socket(server->addr.family, SOCK_DGRAM, 0);
1100 if (s == ARES_SOCKET_BAD)
1103 /* Set the socket non-blocking. */
1104 if (configure_socket(s, server->addr.family, channel) < 0)
1110 /* Connect to the server. */
1111 if (connect(s, sa, salen) == -1)
1113 int err = SOCKERRNO;
1115 if (err != EINPROGRESS && err != EWOULDBLOCK)
1122 if (channel->sock_create_cb)
1124 int err = channel->sock_create_cb(s, SOCK_DGRAM,
1125 channel->sock_create_cb_data);
1133 SOCK_STATE_CALLBACK(channel, s, 1, 0);
1135 server->udp_socket = s;
1139 static int same_questions(const unsigned char *qbuf, int qlen,
1140 const unsigned char *abuf, int alen)
1143 const unsigned char *p;
1152 if (qlen < HFIXEDSZ || alen < HFIXEDSZ)
1155 /* Extract qdcount from the request and reply buffers and compare them. */
1156 q.qdcount = DNS_HEADER_QDCOUNT(qbuf);
1157 a.qdcount = DNS_HEADER_QDCOUNT(abuf);
1158 if (q.qdcount != a.qdcount)
1161 /* For each question in qbuf, find it in abuf. */
1162 q.p = qbuf + HFIXEDSZ;
1163 for (i = 0; i < q.qdcount; i++)
1165 /* Decode the question in the query. */
1166 if (ares_expand_name(q.p, qbuf, qlen, &q.name, &q.namelen)
1170 if (q.p + QFIXEDSZ > qbuf + qlen)
1175 q.type = DNS_QUESTION_TYPE(q.p);
1176 q.dnsclass = DNS_QUESTION_CLASS(q.p);
1179 /* Search for this question in the answer. */
1180 a.p = abuf + HFIXEDSZ;
1181 for (j = 0; j < a.qdcount; j++)
1183 /* Decode the question in the answer. */
1184 if (ares_expand_name(a.p, abuf, alen, &a.name, &a.namelen)
1191 if (a.p + QFIXEDSZ > abuf + alen)
1197 a.type = DNS_QUESTION_TYPE(a.p);
1198 a.dnsclass = DNS_QUESTION_CLASS(a.p);
1201 /* Compare the decoded questions. */
1202 if (strcasecmp(q.name, a.name) == 0 && q.type == a.type
1203 && q.dnsclass == a.dnsclass)
1218 static int same_address(struct sockaddr *sa, struct ares_addr *aa)
1223 if (sa->sa_family == aa->family)
1228 addr1 = &aa->addrV4;
1229 addr2 = &((struct sockaddr_in *)sa)->sin_addr;
1230 if (memcmp(addr1, addr2, sizeof(aa->addrV4)) == 0)
1231 return 1; /* match */
1234 addr1 = &aa->addrV6;
1235 addr2 = &((struct sockaddr_in6 *)sa)->sin6_addr;
1236 if (memcmp(addr1, addr2, sizeof(aa->addrV6)) == 0)
1237 return 1; /* match */
1243 return 0; /* different */
1246 static void end_query (ares_channel channel, struct query *query, int status,
1247 unsigned char *abuf, int alen)
1251 /* First we check to see if this query ended while one of our send
1252 * queues still has pointers to it.
1254 for (i = 0; i < channel->nservers; i++)
1256 struct server_state *server = &channel->servers[i];
1257 struct send_request *sendreq;
1258 for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
1259 if (sendreq->owner_query == query)
1261 sendreq->owner_query = NULL;
1262 assert(sendreq->data_storage == NULL);
1263 if (status == ARES_SUCCESS)
1265 /* We got a reply for this query, but this queued sendreq
1266 * points into this soon-to-be-gone query's tcpbuf. Probably
1267 * this means we timed out and queued the query for
1268 * retransmission, then received a response before actually
1269 * retransmitting. This is perfectly fine, so we want to keep
1270 * the connection running smoothly if we can. But in the worst
1271 * case we may have sent only some prefix of the query, with
1272 * some suffix of the query left to send. Also, the buffer may
1273 * be queued on multiple queues. To prevent dangling pointers
1274 * to the query's tcpbuf and handle these cases, we just give
1275 * such sendreqs their own copy of the query packet.
1277 sendreq->data_storage = malloc(sendreq->len);
1278 if (sendreq->data_storage != NULL)
1280 memcpy(sendreq->data_storage, sendreq->data, sendreq->len);
1281 sendreq->data = sendreq->data_storage;
1284 if ((status != ARES_SUCCESS) || (sendreq->data_storage == NULL))
1286 /* We encountered an error (probably a timeout, suggesting the
1287 * DNS server we're talking to is probably unreachable,
1288 * wedged, or severely overloaded) or we couldn't copy the
1289 * request, so mark the connection as broken. When we get to
1290 * process_broken_connections() we'll close the connection and
1291 * try to re-send requests to another server.
1293 server->is_broken = 1;
1294 /* Just to be paranoid, zero out this sendreq... */
1295 sendreq->data = NULL;
1301 /* Invoke the callback */
1302 query->callback(query->arg, status, query->timeouts, abuf, alen);
1303 ares__free_query(query);
1305 /* Simple cleanup policy: if no queries are remaining, close all network
1306 * sockets unless STAYOPEN is set.
1308 if (!(channel->flags & ARES_FLAG_STAYOPEN) &&
1309 ares__is_list_empty(&(channel->all_queries)))
1311 for (i = 0; i < channel->nservers; i++)
1312 ares__close_sockets(channel, &channel->servers[i]);
1316 void ares__free_query(struct query *query)
1318 /* Remove the query from all the lists in which it is linked */
1319 ares__remove_from_list(&(query->queries_by_qid));
1320 ares__remove_from_list(&(query->queries_by_timeout));
1321 ares__remove_from_list(&(query->queries_to_server));
1322 ares__remove_from_list(&(query->all_queries));
1323 /* Zero out some important stuff, to help catch bugs */
1324 query->callback = NULL;
1326 /* Deallocate the memory associated with the query */
1327 free(query->tcpbuf);
1328 free(query->server_info);