3 /* Copyright 1998 by the Massachusetts Institute of Technology.
4 * Copyright (C) 2004-2008 by Daniel Stenberg
6 * Permission to use, copy, modify, and distribute this
7 * software and its documentation for any purpose and without
8 * fee is hereby granted, provided that the above copyright
9 * notice appear in all copies and that both that copyright
10 * notice and this permission notice appear in supporting
11 * documentation, and that the name of M.I.T. not be used in
12 * advertising or publicity pertaining to distribution of the
13 * software without specific, written prior permission.
14 * M.I.T. makes no representations about the suitability of
15 * this software for any purpose. It is provided "as is"
16 * without express or implied warranty.
21 #if defined(WIN32) && !defined(WATT32)
25 #ifdef HAVE_SYS_SOCKET_H
26 #include <sys/socket.h>
31 #ifdef HAVE_NETINET_IN_H
32 #include <netinet/in.h> /* <netinet/tcp.h> may need it */
34 #ifdef HAVE_NETINET_TCP_H
35 #include <netinet/tcp.h> /* for TCP_NODELAY */
40 #ifdef HAVE_ARPA_NAMESER_H
41 #include <arpa/nameser.h>
43 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
44 #include <arpa/nameser_compat.h>
46 #ifdef HAVE_SYS_TIME_H
49 #endif /* WIN32 && !WATT32 */
57 #ifdef HAVE_SYS_IOCTL_H
58 #include <sys/ioctl.h>
61 #include <sys/filio.h>
73 #include "ares_private.h"
76 static int try_again(int errnum);
77 static void write_tcp_data(ares_channel channel, fd_set *write_fds,
78 ares_socket_t write_fd, struct timeval *now);
79 static void read_tcp_data(ares_channel channel, fd_set *read_fds,
80 ares_socket_t read_fd, struct timeval *now);
81 static void read_udp_packets(ares_channel channel, fd_set *read_fds,
82 ares_socket_t read_fd, struct timeval *now);
83 static void advance_tcp_send_queue(ares_channel channel, int whichserver,
85 static void process_timeouts(ares_channel channel, struct timeval *now);
86 static void process_broken_connections(ares_channel channel,
88 static void process_answer(ares_channel channel, unsigned char *abuf,
89 int alen, int whichserver, int tcp,
91 static void handle_error(ares_channel channel, int whichserver,
93 static void skip_server(ares_channel channel, struct query *query,
95 static void next_server(ares_channel channel, struct query *query,
97 static int configure_socket(int s, ares_channel channel);
98 static int open_tcp_socket(ares_channel channel, struct server_state *server);
99 static int open_udp_socket(ares_channel channel, struct server_state *server);
100 static int same_questions(const unsigned char *qbuf, int qlen,
101 const unsigned char *abuf, int alen);
102 static void end_query(ares_channel channel, struct query *query, int status,
103 unsigned char *abuf, int alen);
105 /* return true if now is exactly check time or later */
106 int ares__timedout(struct timeval *now,
107 struct timeval *check)
109 int secs = (now->tv_sec - check->tv_sec);
112 return 1; /* yes, timed out */
114 return 0; /* nope, not timed out */
116 /* if the full seconds were identical, check the sub second parts */
117 return (now->tv_usec - check->tv_usec >= 0);
120 /* add the specific number of milliseconds to the time in the first argument */
121 int ares__timeadd(struct timeval *now,
124 now->tv_sec += millisecs/1000;
125 now->tv_usec += (millisecs%1000)*1000;
127 if(now->tv_usec >= 1000000) {
129 now->tv_usec -= 1000000;
135 /* return time offset between now and (future) check, in milliseconds */
136 long ares__timeoffset(struct timeval *now,
137 struct timeval *check)
139 return (check->tv_sec - now->tv_sec)*1000 +
140 (check->tv_usec - now->tv_usec)/1000;
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 struct timeval now = ares__tvnow();
151 write_tcp_data(channel, write_fds, ARES_SOCKET_BAD, &now);
152 read_tcp_data(channel, read_fds, ARES_SOCKET_BAD, &now);
153 read_udp_packets(channel, read_fds, ARES_SOCKET_BAD, &now);
154 process_timeouts(channel, &now);
155 process_broken_connections(channel, &now);
158 /* Something interesting happened on the wire, or there was a timeout.
159 * See what's up and respond accordingly.
161 void ares_process_fd(ares_channel channel,
162 ares_socket_t read_fd, /* use ARES_SOCKET_BAD or valid
164 ares_socket_t write_fd)
166 struct timeval now = ares__tvnow();
168 write_tcp_data(channel, NULL, write_fd, &now);
169 read_tcp_data(channel, NULL, read_fd, &now);
170 read_udp_packets(channel, NULL, read_fd, &now);
171 process_timeouts(channel, &now);
175 /* Return 1 if the specified error number describes a readiness error, or 0
176 * otherwise. This is mostly for HP-UX, which could return EAGAIN or
177 * EWOULDBLOCK. See this man page
179 * http://devrsrc1.external.hp.com/STKS/cgi-bin/man2html?manpage=/usr/share/man/man2.Z/send.2
181 static int try_again(int errnum)
183 #if !defined EWOULDBLOCK && !defined EAGAIN
184 #error "Neither EWOULDBLOCK nor EAGAIN defined"
192 #if defined EAGAIN && EAGAIN != EWOULDBLOCK
200 /* If any TCP sockets select true for writing, write out queued data
203 static void write_tcp_data(ares_channel channel,
205 ares_socket_t write_fd,
208 struct server_state *server;
209 struct send_request *sendreq;
216 if(!write_fds && (write_fd == ARES_SOCKET_BAD))
217 /* no possible action */
220 for (i = 0; i < channel->nservers; i++)
222 /* Make sure server has data to send and is selected in write_fds or
224 server = &channel->servers[i];
225 if (!server->qhead || server->tcp_socket == ARES_SOCKET_BAD ||
230 if(!FD_ISSET(server->tcp_socket, write_fds))
234 if(server->tcp_socket != write_fd)
239 /* If there's an error and we close this socket, then open
240 * another with the same fd to talk to another server, then we
241 * don't want to think that it was the new socket that was
242 * ready. This is not disastrous, but is likely to result in
243 * extra system calls and confusion. */
244 FD_CLR(server->tcp_socket, write_fds);
246 /* Count the number of send queue items. */
248 for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
251 /* Allocate iovecs so we can send all our data at once. */
252 vec = malloc(n * sizeof(struct iovec));
255 /* Fill in the iovecs and send. */
257 for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
259 vec[n].iov_base = (char *) sendreq->data;
260 vec[n].iov_len = sendreq->len;
263 wcount = (ssize_t)writev(server->tcp_socket, vec, (int)n);
267 if (!try_again(SOCKERRNO))
268 handle_error(channel, i, now);
272 /* Advance the send queue by as many bytes as we sent. */
273 advance_tcp_send_queue(channel, i, wcount);
277 /* Can't allocate iovecs; just send the first request. */
278 sendreq = server->qhead;
280 scount = swrite(server->tcp_socket, sendreq->data, sendreq->len);
283 if (!try_again(SOCKERRNO))
284 handle_error(channel, i, now);
288 /* Advance the send queue by as many bytes as we sent. */
289 advance_tcp_send_queue(channel, i, scount);
294 /* Consume the given number of bytes from the head of the TCP send queue. */
295 static void advance_tcp_send_queue(ares_channel channel, int whichserver,
298 struct send_request *sendreq;
299 struct server_state *server = &channel->servers[whichserver];
300 while (num_bytes > 0)
302 sendreq = server->qhead;
303 if ((size_t)num_bytes >= sendreq->len)
305 num_bytes -= sendreq->len;
306 server->qhead = sendreq->next;
307 if (server->qhead == NULL)
309 SOCK_STATE_CALLBACK(channel, server->tcp_socket, 1, 0);
310 server->qtail = NULL;
312 if (sendreq->data_storage != NULL)
313 free(sendreq->data_storage);
318 sendreq->data += num_bytes;
319 sendreq->len -= num_bytes;
325 /* If any TCP socket selects true for reading, read some data,
326 * allocate a buffer if we finish reading the length word, and process
327 * a packet if we finish reading one.
329 static void read_tcp_data(ares_channel channel, fd_set *read_fds,
330 ares_socket_t read_fd, struct timeval *now)
332 struct server_state *server;
336 if(!read_fds && (read_fd == ARES_SOCKET_BAD))
337 /* no possible action */
340 for (i = 0; i < channel->nservers; i++)
342 /* Make sure the server has a socket and is selected in read_fds. */
343 server = &channel->servers[i];
344 if (server->tcp_socket == ARES_SOCKET_BAD || server->is_broken)
348 if(!FD_ISSET(server->tcp_socket, read_fds))
352 if(server->tcp_socket != read_fd)
357 /* If there's an error and we close this socket, then open
358 * another with the same fd to talk to another server, then we
359 * don't want to think that it was the new socket that was
360 * ready. This is not disastrous, but is likely to result in
361 * extra system calls and confusion. */
362 FD_CLR(server->tcp_socket, read_fds);
364 if (server->tcp_lenbuf_pos != 2)
366 /* We haven't yet read a length word, so read that (or
367 * what's left to read of it).
369 count = sread(server->tcp_socket,
370 server->tcp_lenbuf + server->tcp_lenbuf_pos,
371 2 - server->tcp_lenbuf_pos);
374 if (!(count == -1 && try_again(SOCKERRNO)))
375 handle_error(channel, i, now);
379 server->tcp_lenbuf_pos += (int)count;
380 if (server->tcp_lenbuf_pos == 2)
382 /* We finished reading the length word. Decode the
383 * length and allocate a buffer for the data.
385 server->tcp_length = server->tcp_lenbuf[0] << 8
386 | server->tcp_lenbuf[1];
387 server->tcp_buffer = malloc(server->tcp_length);
388 if (!server->tcp_buffer)
389 handle_error(channel, i, now);
390 server->tcp_buffer_pos = 0;
395 /* Read data into the allocated buffer. */
396 count = sread(server->tcp_socket,
397 server->tcp_buffer + server->tcp_buffer_pos,
398 server->tcp_length - server->tcp_buffer_pos);
401 if (!(count == -1 && try_again(SOCKERRNO)))
402 handle_error(channel, i, now);
406 server->tcp_buffer_pos += (int)count;
407 if (server->tcp_buffer_pos == server->tcp_length)
409 /* We finished reading this answer; process it and
410 * prepare to read another length word.
412 process_answer(channel, server->tcp_buffer, server->tcp_length,
414 if (server->tcp_buffer)
415 free(server->tcp_buffer);
416 server->tcp_buffer = NULL;
417 server->tcp_lenbuf_pos = 0;
418 server->tcp_buffer_pos = 0;
424 /* If any UDP sockets select true for reading, process them. */
425 static void read_udp_packets(ares_channel channel, fd_set *read_fds,
426 ares_socket_t read_fd, struct timeval *now)
428 struct server_state *server;
431 unsigned char buf[PACKETSZ + 1];
433 if(!read_fds && (read_fd == ARES_SOCKET_BAD))
434 /* no possible action */
437 for (i = 0; i < channel->nservers; i++)
439 /* Make sure the server has a socket and is selected in read_fds. */
440 server = &channel->servers[i];
442 if (server->udp_socket == ARES_SOCKET_BAD || server->is_broken)
446 if(!FD_ISSET(server->udp_socket, read_fds))
450 if(server->udp_socket != read_fd)
455 /* If there's an error and we close this socket, then open
456 * another with the same fd to talk to another server, then we
457 * don't want to think that it was the new socket that was
458 * ready. This is not disastrous, but is likely to result in
459 * extra system calls and confusion. */
460 FD_CLR(server->udp_socket, read_fds);
462 /* To reduce event loop overhead, read and process as many
463 * packets as we can. */
465 count = sread(server->udp_socket, buf, sizeof(buf));
466 if (count == -1 && try_again(SOCKERRNO))
469 handle_error(channel, i, now);
471 process_answer(channel, buf, (int)count, i, 0, now);
476 /* If any queries have timed out, note the timeout and move them on. */
477 static void process_timeouts(ares_channel channel, struct timeval *now)
479 time_t t; /* the time of the timeouts we're processing */
481 struct list_node* list_head;
482 struct list_node* list_node;
484 /* Process all the timeouts that have fired since the last time we
485 * processed timeouts. If things are going well, then we'll have
486 * hundreds/thousands of queries that fall into future buckets, and
487 * only a handful of requests that fall into the "now" bucket, so
488 * this should be quite quick.
490 for (t = channel->last_timeout_processed; t <= now->tv_sec; t++)
492 list_head = &(channel->queries_by_timeout[t % ARES_TIMEOUT_TABLE_SIZE]);
493 for (list_node = list_head->next; list_node != list_head; )
495 query = list_node->data;
496 list_node = list_node->next; /* in case the query gets deleted */
497 if (query->timeout.tv_sec && ares__timedout(now, &query->timeout))
499 query->error_status = ARES_ETIMEOUT;
501 next_server(channel, query, now);
505 channel->last_timeout_processed = now->tv_sec;
508 /* Handle an answer from a server. */
509 static void process_answer(ares_channel channel, unsigned char *abuf,
510 int alen, int whichserver, int tcp,
516 struct list_node* list_head;
517 struct list_node* list_node;
519 /* If there's no room in the answer for a header, we can't do much
524 /* Grab the query ID, truncate bit, and response code from the packet. */
525 id = DNS_HEADER_QID(abuf);
526 tc = DNS_HEADER_TC(abuf);
527 rcode = DNS_HEADER_RCODE(abuf);
529 /* Find the query corresponding to this packet. The queries are
530 * hashed/bucketed by query id, so this lookup should be quick.
531 * Note that both the query id and the questions must be the same;
532 * when the query id wraps around we can have multiple outstanding
533 * queries with the same query id, so we need to check both the id and
537 list_head = &(channel->queries_by_qid[id % ARES_QID_TABLE_SIZE]);
538 for (list_node = list_head->next; list_node != list_head;
539 list_node = list_node->next)
541 struct query *q = list_node->data;
542 if ((q->qid == id) && same_questions(q->qbuf, q->qlen, abuf, alen))
551 /* If we got a truncated UDP packet and are not ignoring truncation,
552 * don't accept the packet, and switch the query to TCP if we hadn't
555 if ((tc || alen > PACKETSZ) && !tcp && !(channel->flags & ARES_FLAG_IGNTC))
557 if (!query->using_tcp)
559 query->using_tcp = 1;
560 ares__send_query(channel, query, now);
565 /* Limit alen to PACKETSZ if we aren't using TCP (only relevant if we
566 * are ignoring truncation.
568 if (alen > PACKETSZ && !tcp)
571 /* If we aren't passing through all error packets, discard packets
572 * with SERVFAIL, NOTIMP, or REFUSED response codes.
574 if (!(channel->flags & ARES_FLAG_NOCHECKRESP))
576 if (rcode == SERVFAIL || rcode == NOTIMP || rcode == REFUSED)
578 skip_server(channel, query, whichserver);
579 if (query->server == whichserver)
580 next_server(channel, query, now);
585 end_query(channel, query, ARES_SUCCESS, abuf, alen);
588 /* Close all the connections that are no longer usable. */
589 static void process_broken_connections(ares_channel channel,
593 for (i = 0; i < channel->nservers; i++)
595 struct server_state *server = &channel->servers[i];
596 if (server->is_broken)
598 handle_error(channel, i, now);
603 static void handle_error(ares_channel channel, int whichserver,
606 struct server_state *server;
608 struct list_node list_head;
609 struct list_node* list_node;
611 server = &channel->servers[whichserver];
613 /* Reset communications with this server. */
614 ares__close_sockets(channel, server);
616 /* Tell all queries talking to this server to move on and not try
617 * this server again. We steal the current list of queries that were
618 * in-flight to this server, since when we call next_server this can
619 * cause the queries to be re-sent to this server, which will
620 * re-insert these queries in that same server->queries_to_server
623 ares__init_list_head(&list_head);
624 ares__swap_lists(&list_head, &(server->queries_to_server));
625 for (list_node = list_head.next; list_node != &list_head; )
627 query = list_node->data;
628 list_node = list_node->next; /* in case the query gets deleted */
629 assert(query->server == whichserver);
630 skip_server(channel, query, whichserver);
631 next_server(channel, query, now);
633 /* Each query should have removed itself from our temporary list as
634 * it re-sent itself or finished up...
636 assert(ares__is_list_empty(&list_head));
639 static void skip_server(ares_channel channel, struct query *query,
641 /* The given server gave us problems with this query, so if we have
642 * the luxury of using other servers, then let's skip the
643 * potentially broken server and just use the others. If we only
644 * have one server and we need to retry then we should just go ahead
645 * and re-use that server, since it's our only hope; perhaps we
646 * just got unlucky, and retrying will work (eg, the server timed
647 * out our TCP connection just as we were sending another request).
649 if (channel->nservers > 1)
651 query->server_info[whichserver].skip_server = 1;
655 static void next_server(ares_channel channel, struct query *query,
658 /* Advance to the next server or try. */
660 for (; query->try < channel->tries; query->try++)
662 for (; query->server < channel->nservers; query->server++)
664 struct server_state *server = &channel->servers[query->server];
665 /* We don't want to use this server if (1) we decided this
666 * connection is broken, and thus about to be closed, (2)
667 * we've decided to skip this server because of earlier
668 * errors we encountered, or (3) we already sent this query
669 * over this exact connection.
671 if (!server->is_broken &&
672 !query->server_info[query->server].skip_server &&
673 !(query->using_tcp &&
674 (query->server_info[query->server].tcp_connection_generation ==
675 server->tcp_connection_generation)))
677 ares__send_query(channel, query, now);
683 /* You might think that with TCP we only need one try. However,
684 * even when using TCP, servers can time-out our connection just
685 * as we're sending a request, or close our connection because
686 * they die, or never send us a reply because they get wedged or
687 * tickle a bug that drops our request.
690 end_query(channel, query, query->error_status, NULL, 0);
693 void ares__send_query(ares_channel channel, struct query *query,
696 struct send_request *sendreq;
697 struct server_state *server;
699 server = &channel->servers[query->server];
700 if (query->using_tcp)
702 /* Make sure the TCP socket for this server is set up and queue
705 if (server->tcp_socket == ARES_SOCKET_BAD)
707 if (open_tcp_socket(channel, server) == -1)
709 skip_server(channel, query, query->server);
710 next_server(channel, query, now);
714 sendreq = calloc(sizeof(struct send_request), 1);
717 end_query(channel, query, ARES_ENOMEM, NULL, 0);
720 /* To make the common case fast, we avoid copies by using the
721 * query's tcpbuf for as long as the query is alive. In the rare
722 * case where the query ends while it's queued for transmission,
723 * then we give the sendreq its own copy of the request packet
724 * and put it in sendreq->data_storage.
726 sendreq->data_storage = NULL;
727 sendreq->data = query->tcpbuf;
728 sendreq->len = query->tcplen;
729 sendreq->owner_query = query;
730 sendreq->next = NULL;
732 server->qtail->next = sendreq;
735 SOCK_STATE_CALLBACK(channel, server->tcp_socket, 1, 1);
736 server->qhead = sendreq;
738 server->qtail = sendreq;
739 query->server_info[query->server].tcp_connection_generation =
740 server->tcp_connection_generation;
744 if (server->udp_socket == ARES_SOCKET_BAD)
746 if (open_udp_socket(channel, server) == -1)
748 skip_server(channel, query, query->server);
749 next_server(channel, query, now);
753 if (swrite(server->udp_socket, query->qbuf, query->qlen) == -1)
755 /* FIXME: Handle EAGAIN here since it likely can happen. */
756 skip_server(channel, query, query->server);
757 next_server(channel, query, now);
761 query->timeout = *now;
762 ares__timeadd(&query->timeout,
763 (query->try == 0) ? channel->timeout
764 : channel->timeout << query->try / channel->nservers);
765 /* Keep track of queries bucketed by timeout, so we can process
766 * timeout events quickly.
768 ares__remove_from_list(&(query->queries_by_timeout));
769 ares__insert_in_list(
770 &(query->queries_by_timeout),
771 &(channel->queries_by_timeout[query->timeout.tv_sec %
772 ARES_TIMEOUT_TABLE_SIZE]));
774 /* Keep track of queries bucketed by server, so we can process server
777 ares__remove_from_list(&(query->queries_to_server));
778 ares__insert_in_list(&(query->queries_to_server),
779 &(server->queries_to_server));
783 * setsocknonblock sets the given socket to either blocking or non-blocking mode
784 * based on the 'nonblock' boolean argument. This function is highly portable.
786 static int setsocknonblock(ares_socket_t sockfd, /* operate on this */
787 int nonblock /* TRUE or FALSE */)
791 #ifdef HAVE_O_NONBLOCK
792 /* most recent unix versions */
795 flags = fcntl(sockfd, F_GETFL, 0);
796 if (FALSE != nonblock)
797 return fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
799 return fcntl(sockfd, F_SETFL, flags & (~O_NONBLOCK));
804 #if defined(HAVE_FIONBIO) && (SETBLOCK == 0)
805 /* older unix versions */
809 return ioctl(sockfd, FIONBIO, &flags);
814 #if defined(HAVE_IOCTLSOCKET) && (SETBLOCK == 0)
823 return ioctlsocket(sockfd, FIONBIO, &flags);
828 #if defined(HAVE_IOCTLSOCKET_CASE) && (SETBLOCK == 0)
829 /* presumably for Amiga */
830 return IoctlSocket(sockfd, FIONBIO, (long)nonblock);
835 #if defined(HAVE_SO_NONBLOCK) && (SETBLOCK == 0)
837 long b = nonblock ? 1 : 0;
838 return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
843 #ifdef HAVE_DISABLED_NONBLOCKING
844 return 0; /* returns success */
850 #error "no non-blocking method was found/used/set"
854 static int configure_socket(int s, ares_channel channel)
856 setsocknonblock(s, TRUE);
858 #if defined(FD_CLOEXEC) && !defined(MSDOS)
859 /* Configure the socket fd as close-on-exec. */
860 if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1)
864 /* Set the socket's send and receive buffer sizes. */
865 if ((channel->socket_send_buffer_size > 0) &&
866 setsockopt(s, SOL_SOCKET, SO_SNDBUF,
867 (void *)&channel->socket_send_buffer_size,
868 sizeof(channel->socket_send_buffer_size)) == -1)
871 if ((channel->socket_receive_buffer_size > 0) &&
872 setsockopt(s, SOL_SOCKET, SO_RCVBUF,
873 (void *)&channel->socket_receive_buffer_size,
874 sizeof(channel->socket_receive_buffer_size)) == -1)
880 static int open_tcp_socket(ares_channel channel, struct server_state *server)
884 struct sockaddr_in sockin;
886 /* Acquire a socket. */
887 s = socket(AF_INET, SOCK_STREAM, 0);
888 if (s == ARES_SOCKET_BAD)
892 if (configure_socket(s, channel) < 0)
899 * Disable the Nagle algorithm (only relevant for TCP sockets, and thus not in
900 * configure_socket). In general, in DNS lookups we're pretty much interested
901 * in firing off a single request and then waiting for a reply, so batching
902 * isn't very interesting in general.
905 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
906 (void *)&opt, sizeof(opt)) == -1)
912 /* Connect to the server. */
913 memset(&sockin, 0, sizeof(sockin));
914 sockin.sin_family = AF_INET;
915 sockin.sin_addr = server->addr;
916 sockin.sin_port = (unsigned short)(channel->tcp_port & 0xffff);
917 if (connect(s, (struct sockaddr *) &sockin, sizeof(sockin)) == -1) {
920 if (err != EINPROGRESS && err != EWOULDBLOCK) {
926 SOCK_STATE_CALLBACK(channel, s, 1, 0);
927 server->tcp_buffer_pos = 0;
928 server->tcp_socket = s;
929 server->tcp_connection_generation = ++channel->tcp_connection_generation;
933 static int open_udp_socket(ares_channel channel, struct server_state *server)
936 struct sockaddr_in sockin;
938 /* Acquire a socket. */
939 s = socket(AF_INET, SOCK_DGRAM, 0);
940 if (s == ARES_SOCKET_BAD)
943 /* Set the socket non-blocking. */
944 if (configure_socket(s, channel) < 0)
950 /* Connect to the server. */
951 memset(&sockin, 0, sizeof(sockin));
952 sockin.sin_family = AF_INET;
953 sockin.sin_addr = server->addr;
954 sockin.sin_port = (unsigned short)(channel->udp_port & 0xffff);
955 if (connect(s, (struct sockaddr *) &sockin, sizeof(sockin)) == -1)
961 SOCK_STATE_CALLBACK(channel, s, 1, 0);
963 server->udp_socket = s;
967 static int same_questions(const unsigned char *qbuf, int qlen,
968 const unsigned char *abuf, int alen)
971 const unsigned char *p;
980 if (qlen < HFIXEDSZ || alen < HFIXEDSZ)
983 /* Extract qdcount from the request and reply buffers and compare them. */
984 q.qdcount = DNS_HEADER_QDCOUNT(qbuf);
985 a.qdcount = DNS_HEADER_QDCOUNT(abuf);
986 if (q.qdcount != a.qdcount)
989 /* For each question in qbuf, find it in abuf. */
990 q.p = qbuf + HFIXEDSZ;
991 for (i = 0; i < q.qdcount; i++)
993 /* Decode the question in the query. */
994 if (ares_expand_name(q.p, qbuf, qlen, &q.name, &q.namelen)
998 if (q.p + QFIXEDSZ > qbuf + qlen)
1003 q.type = DNS_QUESTION_TYPE(q.p);
1004 q.dnsclass = DNS_QUESTION_CLASS(q.p);
1007 /* Search for this question in the answer. */
1008 a.p = abuf + HFIXEDSZ;
1009 for (j = 0; j < a.qdcount; j++)
1011 /* Decode the question in the answer. */
1012 if (ares_expand_name(a.p, abuf, alen, &a.name, &a.namelen)
1019 if (a.p + QFIXEDSZ > abuf + alen)
1025 a.type = DNS_QUESTION_TYPE(a.p);
1026 a.dnsclass = DNS_QUESTION_CLASS(a.p);
1029 /* Compare the decoded questions. */
1030 if (strcasecmp(q.name, a.name) == 0 && q.type == a.type
1031 && q.dnsclass == a.dnsclass)
1046 static void end_query (ares_channel channel, struct query *query, int status,
1047 unsigned char *abuf, int alen)
1051 /* First we check to see if this query ended while one of our send
1052 * queues still has pointers to it.
1054 for (i = 0; i < channel->nservers; i++)
1056 struct server_state *server = &channel->servers[i];
1057 struct send_request *sendreq;
1058 for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
1059 if (sendreq->owner_query == query)
1061 sendreq->owner_query = NULL;
1062 assert(sendreq->data_storage == NULL);
1063 if (status == ARES_SUCCESS)
1065 /* We got a reply for this query, but this queued
1066 * sendreq points into this soon-to-be-gone query's
1067 * tcpbuf. Probably this means we timed out and queued
1068 * the query for retransmission, then received a
1069 * response before actually retransmitting. This is
1070 * perfectly fine, so we want to keep the connection
1071 * running smoothly if we can. But in the worst case
1072 * we may have sent only some prefix of the query,
1073 * with some suffix of the query left to send. Also,
1074 * the buffer may be queued on multiple queues. To
1075 * prevent dangling pointers to the query's tcpbuf and
1076 * handle these cases, we just give such sendreqs
1077 * their own copy of the query packet.
1079 sendreq->data_storage = malloc(sendreq->len);
1080 if (sendreq->data_storage != NULL)
1082 memcpy(sendreq->data_storage, sendreq->data, sendreq->len);
1083 sendreq->data = sendreq->data_storage;
1086 if ((status != ARES_SUCCESS) || (sendreq->data_storage == NULL))
1088 /* We encountered an error (probably a timeout,
1089 * suggesting the DNS server we're talking to is
1090 * probably unreachable, wedged, or severely
1091 * overloaded) or we couldn't copy the request, so
1092 * mark the connection as broken. When we get to
1093 * process_broken_connections() we'll close the
1094 * connection and try to re-send requests to another
1097 server->is_broken = 1;
1098 /* Just to be paranoid, zero out this sendreq... */
1099 sendreq->data = NULL;
1105 /* Invoke the callback */
1106 query->callback(query->arg, status, query->timeouts, abuf, alen);
1107 ares__free_query(query);
1109 /* Simple cleanup policy: if no queries are remaining, close all
1110 * network sockets unless STAYOPEN is set.
1112 if (!(channel->flags & ARES_FLAG_STAYOPEN) &&
1113 ares__is_list_empty(&(channel->all_queries)))
1115 for (i = 0; i < channel->nservers; i++)
1116 ares__close_sockets(channel, &channel->servers[i]);
1120 void ares__free_query(struct query *query)
1122 /* Remove the query from all the lists in which it is linked */
1123 ares__remove_from_list(&(query->queries_by_qid));
1124 ares__remove_from_list(&(query->queries_by_timeout));
1125 ares__remove_from_list(&(query->queries_to_server));
1126 ares__remove_from_list(&(query->all_queries));
1127 /* Zero out some important stuff, to help catch bugs */
1128 query->callback = NULL;
1130 /* Deallocate the memory associated with the query */
1131 free(query->tcpbuf);
1132 free(query->server_info);