Upgrade to 1.17.1
[platform/upstream/c-ares.git] / src / lib / ares_process.c
1
2 /* Copyright 1998 by the Massachusetts Institute of Technology.
3  * Copyright (C) 2004-2017 by Daniel Stenberg
4  *
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.
16  */
17
18 #include "ares_setup.h"
19
20 #ifdef HAVE_SYS_UIO_H
21 #  include <sys/uio.h>
22 #endif
23 #ifdef HAVE_NETINET_IN_H
24 #  include <netinet/in.h>
25 #endif
26 #ifdef HAVE_NETINET_TCP_H
27 #  include <netinet/tcp.h>
28 #endif
29 #ifdef HAVE_NETDB_H
30 #  include <netdb.h>
31 #endif
32 #ifdef HAVE_ARPA_INET_H
33 #  include <arpa/inet.h>
34 #endif
35 #ifdef HAVE_ARPA_NAMESER_H
36 #  include <arpa/nameser.h>
37 #endif
38 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
39 #  include <arpa/nameser_compat.h>
40 #endif
41
42 #include "nameser.h"
43
44 #ifdef HAVE_STRINGS_H
45 #  include <strings.h>
46 #endif
47 #ifdef HAVE_SYS_IOCTL_H
48 #  include <sys/ioctl.h>
49 #endif
50 #ifdef NETWARE
51 #  include <sys/filio.h>
52 #endif
53
54 #include <assert.h>
55 #include <fcntl.h>
56 #include <limits.h>
57
58 #include "ares.h"
59 #include "ares_dns.h"
60 #include "ares_nowarn.h"
61 #include "ares_private.h"
62
63
64 static int try_again(int errnum);
65 static void write_tcp_data(ares_channel channel, fd_set *write_fds,
66                            ares_socket_t write_fd, struct timeval *now);
67 static void read_tcp_data(ares_channel channel, fd_set *read_fds,
68                           ares_socket_t read_fd, struct timeval *now);
69 static void read_udp_packets(ares_channel channel, fd_set *read_fds,
70                              ares_socket_t read_fd, struct timeval *now);
71 static void advance_tcp_send_queue(ares_channel channel, int whichserver,
72                                    ares_ssize_t num_bytes);
73 static void process_timeouts(ares_channel channel, struct timeval *now);
74 static void process_broken_connections(ares_channel channel,
75                                        struct timeval *now);
76 static void process_answer(ares_channel channel, unsigned char *abuf,
77                            int alen, int whichserver, int tcp,
78                            struct timeval *now);
79 static void handle_error(ares_channel channel, int whichserver,
80                          struct timeval *now);
81 static void skip_server(ares_channel channel, struct query *query,
82                         int whichserver);
83 static void next_server(ares_channel channel, struct query *query,
84                         struct timeval *now);
85 static int open_tcp_socket(ares_channel channel, struct server_state *server);
86 static int open_udp_socket(ares_channel channel, struct server_state *server);
87 static int same_questions(const unsigned char *qbuf, int qlen,
88                           const unsigned char *abuf, int alen);
89 static int same_address(struct sockaddr *sa, struct ares_addr *aa);
90 static int has_opt_rr(const unsigned char *abuf, int alen);
91 static void end_query(ares_channel channel, struct query *query, int status,
92                       unsigned char *abuf, int alen);
93
94 /* return true if now is exactly check time or later */
95 int ares__timedout(struct timeval *now,
96                    struct timeval *check)
97 {
98   long secs = (now->tv_sec - check->tv_sec);
99
100   if(secs > 0)
101     return 1; /* yes, timed out */
102   if(secs < 0)
103     return 0; /* nope, not timed out */
104
105   /* if the full seconds were identical, check the sub second parts */
106   return (now->tv_usec - check->tv_usec >= 0);
107 }
108
109 /* add the specific number of milliseconds to the time in the first argument */
110 static void timeadd(struct timeval *now, int millisecs)
111 {
112   now->tv_sec += millisecs/1000;
113   now->tv_usec += (millisecs%1000)*1000;
114
115   if(now->tv_usec >= 1000000) {
116     ++(now->tv_sec);
117     now->tv_usec -= 1000000;
118   }
119 }
120
121 /*
122  * generic process function
123  */
124 static void processfds(ares_channel channel,
125                        fd_set *read_fds, ares_socket_t read_fd,
126                        fd_set *write_fds, ares_socket_t write_fd)
127 {
128   struct timeval now = ares__tvnow();
129
130   write_tcp_data(channel, write_fds, write_fd, &now);
131   read_tcp_data(channel, read_fds, read_fd, &now);
132   read_udp_packets(channel, read_fds, read_fd, &now);
133   process_timeouts(channel, &now);
134   process_broken_connections(channel, &now);
135 }
136
137 /* Something interesting happened on the wire, or there was a timeout.
138  * See what's up and respond accordingly.
139  */
140 void ares_process(ares_channel channel, fd_set *read_fds, fd_set *write_fds)
141 {
142   processfds(channel, read_fds, ARES_SOCKET_BAD, write_fds, ARES_SOCKET_BAD);
143 }
144
145 /* Something interesting happened on the wire, or there was a timeout.
146  * See what's up and respond accordingly.
147  */
148 void ares_process_fd(ares_channel channel,
149                      ares_socket_t read_fd, /* use ARES_SOCKET_BAD or valid
150                                                file descriptors */
151                      ares_socket_t write_fd)
152 {
153   processfds(channel, NULL, read_fd, NULL, write_fd);
154 }
155
156
157 /* Return 1 if the specified error number describes a readiness error, or 0
158  * otherwise. This is mostly for HP-UX, which could return EAGAIN or
159  * EWOULDBLOCK. See this man page
160  *
161  * http://devrsrc1.external.hp.com/STKS/cgi-bin/man2html?
162  *     manpage=/usr/share/man/man2.Z/send.2
163  */
164 static int try_again(int errnum)
165 {
166 #if !defined EWOULDBLOCK && !defined EAGAIN
167 #error "Neither EWOULDBLOCK nor EAGAIN defined"
168 #endif
169   switch (errnum)
170     {
171 #ifdef EWOULDBLOCK
172     case EWOULDBLOCK:
173       return 1;
174 #endif
175 #if defined EAGAIN && EAGAIN != EWOULDBLOCK
176     case EAGAIN:
177       return 1;
178 #endif
179     }
180   return 0;
181 }
182
183 static ares_ssize_t socket_writev(ares_channel channel, ares_socket_t s, const struct iovec * vec, int len)
184 {
185   if (channel->sock_funcs)
186     return channel->sock_funcs->asendv(s, vec, len, channel->sock_func_cb_data);
187
188   return writev(s, vec, len);
189 }
190
191 static ares_ssize_t socket_write(ares_channel channel, ares_socket_t s, const void * data, size_t len)
192 {
193   if (channel->sock_funcs)
194     {
195       struct iovec vec;
196       vec.iov_base = (void*)data;
197       vec.iov_len = len;
198       return channel->sock_funcs->asendv(s, &vec, 1, channel->sock_func_cb_data);
199     }
200   return swrite(s, data, len);
201 }
202
203 /* If any TCP sockets select true for writing, write out queued data
204  * we have for them.
205  */
206 static void write_tcp_data(ares_channel channel,
207                            fd_set *write_fds,
208                            ares_socket_t write_fd,
209                            struct timeval *now)
210 {
211   struct server_state *server;
212   struct send_request *sendreq;
213   struct iovec *vec;
214   int i;
215   ares_ssize_t scount;
216   ares_ssize_t wcount;
217   size_t n;
218
219   if(!write_fds && (write_fd == ARES_SOCKET_BAD))
220     /* no possible action */
221     return;
222
223   for (i = 0; i < channel->nservers; i++)
224     {
225       /* Make sure server has data to send and is selected in write_fds or
226          write_fd. */
227       server = &channel->servers[i];
228       if (!server->qhead || server->tcp_socket == ARES_SOCKET_BAD ||
229           server->is_broken)
230         continue;
231
232       if(write_fds) {
233         if(!FD_ISSET(server->tcp_socket, write_fds))
234           continue;
235       }
236       else {
237         if(server->tcp_socket != write_fd)
238           continue;
239       }
240
241       if(write_fds)
242         /* If there's an error and we close this socket, then open
243          * another with the same fd to talk to another server, then we
244          * don't want to think that it was the new socket that was
245          * ready. This is not disastrous, but is likely to result in
246          * extra system calls and confusion. */
247         FD_CLR(server->tcp_socket, write_fds);
248
249       /* Count the number of send queue items. */
250       n = 0;
251       for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
252         n++;
253
254       /* Allocate iovecs so we can send all our data at once. */
255       vec = ares_malloc(n * sizeof(struct iovec));
256       if (vec)
257         {
258           /* Fill in the iovecs and send. */
259           n = 0;
260           for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
261             {
262               vec[n].iov_base = (char *) sendreq->data;
263               vec[n].iov_len = sendreq->len;
264               n++;
265             }
266           wcount = socket_writev(channel, server->tcp_socket, vec, (int)n);
267           ares_free(vec);
268           if (wcount < 0)
269             {
270               if (!try_again(SOCKERRNO))
271                 handle_error(channel, i, now);
272               continue;
273             }
274
275           /* Advance the send queue by as many bytes as we sent. */
276           advance_tcp_send_queue(channel, i, wcount);
277         }
278       else
279         {
280           /* Can't allocate iovecs; just send the first request. */
281           sendreq = server->qhead;
282
283           scount = socket_write(channel, server->tcp_socket, sendreq->data, sendreq->len);
284           if (scount < 0)
285             {
286               if (!try_again(SOCKERRNO))
287                 handle_error(channel, i, now);
288               continue;
289             }
290
291           /* Advance the send queue by as many bytes as we sent. */
292           advance_tcp_send_queue(channel, i, scount);
293         }
294     }
295 }
296
297 /* Consume the given number of bytes from the head of the TCP send queue. */
298 static void advance_tcp_send_queue(ares_channel channel, int whichserver,
299                                    ares_ssize_t num_bytes)
300 {
301   struct send_request *sendreq;
302   struct server_state *server = &channel->servers[whichserver];
303   while (num_bytes > 0) {
304     sendreq = server->qhead;
305     if ((size_t)num_bytes >= sendreq->len) {
306       num_bytes -= sendreq->len;
307       server->qhead = sendreq->next;
308       if (sendreq->data_storage)
309         ares_free(sendreq->data_storage);
310       ares_free(sendreq);
311       if (server->qhead == NULL) {
312         SOCK_STATE_CALLBACK(channel, server->tcp_socket, 1, 0);
313         server->qtail = NULL;
314
315         /* qhead is NULL so we cannot continue this loop */
316         break;
317       }
318     }
319     else {
320       sendreq->data += num_bytes;
321       sendreq->len -= num_bytes;
322       num_bytes = 0;
323     }
324   }
325 }
326
327 static ares_ssize_t socket_recvfrom(ares_channel channel,
328    ares_socket_t s,
329    void * data,
330    size_t data_len,
331    int flags,
332    struct sockaddr *from,
333    ares_socklen_t *from_len)
334 {
335    if (channel->sock_funcs)
336       return channel->sock_funcs->arecvfrom(s, data, data_len,
337          flags, from, from_len,
338          channel->sock_func_cb_data);
339
340 #ifdef HAVE_RECVFROM
341    return recvfrom(s, data, data_len, flags, from, from_len);
342 #else
343    return sread(s, data, data_len);
344 #endif
345 }
346
347 static ares_ssize_t socket_recv(ares_channel channel,
348    ares_socket_t s,
349    void * data,
350    size_t data_len)
351 {
352    if (channel->sock_funcs)
353       return channel->sock_funcs->arecvfrom(s, data, data_len, 0, 0, 0,
354          channel->sock_func_cb_data);
355
356    return sread(s, data, data_len);
357 }
358
359 /* If any TCP socket selects true for reading, read some data,
360  * allocate a buffer if we finish reading the length word, and process
361  * a packet if we finish reading one.
362  */
363 static void read_tcp_data(ares_channel channel, fd_set *read_fds,
364                           ares_socket_t read_fd, struct timeval *now)
365 {
366   struct server_state *server;
367   int i;
368   ares_ssize_t count;
369
370   if(!read_fds && (read_fd == ARES_SOCKET_BAD))
371     /* no possible action */
372     return;
373
374   for (i = 0; i < channel->nservers; i++)
375     {
376       /* Make sure the server has a socket and is selected in read_fds. */
377       server = &channel->servers[i];
378       if (server->tcp_socket == ARES_SOCKET_BAD || server->is_broken)
379         continue;
380
381       if(read_fds) {
382         if(!FD_ISSET(server->tcp_socket, read_fds))
383           continue;
384       }
385       else {
386         if(server->tcp_socket != read_fd)
387           continue;
388       }
389
390       if(read_fds)
391         /* If there's an error and we close this socket, then open another
392          * with the same fd to talk to another server, then we don't want to
393          * think that it was the new socket that was ready. This is not
394          * disastrous, but is likely to result in extra system calls and
395          * confusion. */
396         FD_CLR(server->tcp_socket, read_fds);
397
398       if (server->tcp_lenbuf_pos != 2)
399         {
400           /* We haven't yet read a length word, so read that (or
401            * what's left to read of it).
402            */
403           count = socket_recv(channel, server->tcp_socket,
404                               server->tcp_lenbuf + server->tcp_lenbuf_pos,
405                               2 - server->tcp_lenbuf_pos);
406           if (count <= 0)
407             {
408               if (!(count == -1 && try_again(SOCKERRNO)))
409                 handle_error(channel, i, now);
410               continue;
411             }
412
413           server->tcp_lenbuf_pos += (int)count;
414           if (server->tcp_lenbuf_pos == 2)
415             {
416               /* We finished reading the length word.  Decode the
417                * length and allocate a buffer for the data.
418                */
419               server->tcp_length = server->tcp_lenbuf[0] << 8
420                 | server->tcp_lenbuf[1];
421               server->tcp_buffer = ares_malloc(server->tcp_length);
422               if (!server->tcp_buffer) {
423                 handle_error(channel, i, now);
424                 return; /* bail out on malloc failure. TODO: make this
425                            function return error codes */
426               }
427               server->tcp_buffer_pos = 0;
428             }
429         }
430       else
431         {
432           /* Read data into the allocated buffer. */
433           count = socket_recv(channel, server->tcp_socket,
434                               server->tcp_buffer + server->tcp_buffer_pos,
435                               server->tcp_length - server->tcp_buffer_pos);
436           if (count <= 0)
437             {
438               if (!(count == -1 && try_again(SOCKERRNO)))
439                 handle_error(channel, i, now);
440               continue;
441             }
442
443           server->tcp_buffer_pos += (int)count;
444           if (server->tcp_buffer_pos == server->tcp_length)
445             {
446               /* We finished reading this answer; process it and
447                * prepare to read another length word.
448                */
449               process_answer(channel, server->tcp_buffer, server->tcp_length,
450                              i, 1, now);
451               ares_free(server->tcp_buffer);
452               server->tcp_buffer = NULL;
453               server->tcp_lenbuf_pos = 0;
454               server->tcp_buffer_pos = 0;
455             }
456         }
457     }
458 }
459
460 /* If any UDP sockets select true for reading, process them. */
461 static void read_udp_packets(ares_channel channel, fd_set *read_fds,
462                              ares_socket_t read_fd, struct timeval *now)
463 {
464   struct server_state *server;
465   int i;
466   ares_ssize_t count;
467   unsigned char buf[MAXENDSSZ + 1];
468 #ifdef HAVE_RECVFROM
469   ares_socklen_t fromlen;
470   union {
471     struct sockaddr     sa;
472     struct sockaddr_in  sa4;
473     struct sockaddr_in6 sa6;
474   } from;
475 #endif
476
477   if(!read_fds && (read_fd == ARES_SOCKET_BAD))
478     /* no possible action */
479     return;
480
481   for (i = 0; i < channel->nservers; i++)
482     {
483       /* Make sure the server has a socket and is selected in read_fds. */
484       server = &channel->servers[i];
485
486       if (server->udp_socket == ARES_SOCKET_BAD || server->is_broken)
487         continue;
488
489       if(read_fds) {
490         if(!FD_ISSET(server->udp_socket, read_fds))
491           continue;
492       }
493       else {
494         if(server->udp_socket != read_fd)
495           continue;
496       }
497
498       if(read_fds)
499         /* If there's an error and we close this socket, then open
500          * another with the same fd to talk to another server, then we
501          * don't want to think that it was the new socket that was
502          * ready. This is not disastrous, but is likely to result in
503          * extra system calls and confusion. */
504         FD_CLR(server->udp_socket, read_fds);
505
506       /* To reduce event loop overhead, read and process as many
507        * packets as we can. */
508       do {
509         if (server->udp_socket == ARES_SOCKET_BAD)
510           count = 0;
511
512         else {
513           if (server->addr.family == AF_INET)
514             fromlen = sizeof(from.sa4);
515           else
516             fromlen = sizeof(from.sa6);
517           count = socket_recvfrom(channel, server->udp_socket, (void *)buf,
518                                   sizeof(buf), 0, &from.sa, &fromlen);
519         }
520
521         if (count == -1 && try_again(SOCKERRNO))
522           continue;
523         else if (count <= 0)
524           handle_error(channel, i, now);
525 #ifdef HAVE_RECVFROM
526         else if (!same_address(&from.sa, &server->addr))
527           /* The address the response comes from does not match the address we
528            * sent the request to. Someone may be attempting to perform a cache
529            * poisoning attack. */
530           break;
531 #endif
532         else
533           process_answer(channel, buf, (int)count, i, 0, now);
534        } while (count > 0);
535     }
536 }
537
538 /* If any queries have timed out, note the timeout and move them on. */
539 static void process_timeouts(ares_channel channel, struct timeval *now)
540 {
541   time_t t;  /* the time of the timeouts we're processing */
542   struct query *query;
543   struct list_node* list_head;
544   struct list_node* list_node;
545
546   /* Process all the timeouts that have fired since the last time we processed
547    * timeouts. If things are going well, then we'll have hundreds/thousands of
548    * queries that fall into future buckets, and only a handful of requests
549    * that fall into the "now" bucket, so this should be quite quick.
550    */
551   for (t = channel->last_timeout_processed; t <= now->tv_sec; t++)
552     {
553       list_head = &(channel->queries_by_timeout[t % ARES_TIMEOUT_TABLE_SIZE]);
554       for (list_node = list_head->next; list_node != list_head; )
555         {
556           query = list_node->data;
557           list_node = list_node->next;  /* in case the query gets deleted */
558           if (query->timeout.tv_sec && ares__timedout(now, &query->timeout))
559             {
560               query->error_status = ARES_ETIMEOUT;
561               ++query->timeouts;
562               next_server(channel, query, now);
563             }
564         }
565      }
566   channel->last_timeout_processed = now->tv_sec;
567 }
568
569 /* Handle an answer from a server. */
570 static void process_answer(ares_channel channel, unsigned char *abuf,
571                            int alen, int whichserver, int tcp,
572                            struct timeval *now)
573 {
574   int tc, rcode, packetsz;
575   unsigned short id;
576   struct query *query;
577   struct list_node* list_head;
578   struct list_node* list_node;
579
580   /* If there's no room in the answer for a header, we can't do much
581    * with it. */
582   if (alen < HFIXEDSZ)
583     return;
584
585   /* Grab the query ID, truncate bit, and response code from the packet. */
586   id = DNS_HEADER_QID(abuf);
587   tc = DNS_HEADER_TC(abuf);
588   rcode = DNS_HEADER_RCODE(abuf);
589
590   /* Find the query corresponding to this packet. The queries are
591    * hashed/bucketed by query id, so this lookup should be quick.  Note that
592    * both the query id and the questions must be the same; when the query id
593    * wraps around we can have multiple outstanding queries with the same query
594    * id, so we need to check both the id and question.
595    */
596   query = NULL;
597   list_head = &(channel->queries_by_qid[id % ARES_QID_TABLE_SIZE]);
598   for (list_node = list_head->next; list_node != list_head;
599        list_node = list_node->next)
600     {
601       struct query *q = list_node->data;
602       if ((q->qid == id) && same_questions(q->qbuf, q->qlen, abuf, alen))
603         {
604           query = q;
605           break;
606         }
607     }
608   if (!query)
609     return;
610
611   packetsz = PACKETSZ;
612   /* If we use EDNS and server answers with FORMERR without an OPT RR, the protocol
613    * extension is not understood by the responder. We must retry the query
614    * without EDNS enabled.
615    */
616   if (channel->flags & ARES_FLAG_EDNS)
617   {
618       packetsz = channel->ednspsz;
619       if (rcode == FORMERR && has_opt_rr(abuf, alen) != 1)
620       {
621           int qlen = (query->tcplen - 2) - EDNSFIXEDSZ;
622           channel->flags ^= ARES_FLAG_EDNS;
623           query->tcplen -= EDNSFIXEDSZ;
624           query->qlen -= EDNSFIXEDSZ;
625           query->tcpbuf[0] = (unsigned char)((qlen >> 8) & 0xff);
626           query->tcpbuf[1] = (unsigned char)(qlen & 0xff);
627           DNS_HEADER_SET_ARCOUNT(query->tcpbuf + 2, 0);
628           query->tcpbuf = ares_realloc(query->tcpbuf, query->tcplen);
629           query->qbuf = query->tcpbuf + 2;
630           ares__send_query(channel, query, now);
631           return;
632       }
633   }
634
635   /* If we got a truncated UDP packet and are not ignoring truncation,
636    * don't accept the packet, and switch the query to TCP if we hadn't
637    * done so already.
638    */
639   if ((tc || alen > packetsz) && !tcp && !(channel->flags & ARES_FLAG_IGNTC))
640     {
641       if (!query->using_tcp)
642         {
643           query->using_tcp = 1;
644           ares__send_query(channel, query, now);
645         }
646       return;
647     }
648
649   /* Limit alen to PACKETSZ if we aren't using TCP (only relevant if we
650    * are ignoring truncation.
651    */
652   if (alen > packetsz && !tcp)
653       alen = packetsz;
654
655   /* If we aren't passing through all error packets, discard packets
656    * with SERVFAIL, NOTIMP, or REFUSED response codes.
657    */
658   if (!(channel->flags & ARES_FLAG_NOCHECKRESP))
659     {
660       if (rcode == SERVFAIL || rcode == NOTIMP || rcode == REFUSED)
661         {
662           skip_server(channel, query, whichserver);
663           if (query->server == whichserver)
664             next_server(channel, query, now);
665           return;
666         }
667     }
668
669   end_query(channel, query, ARES_SUCCESS, abuf, alen);
670 }
671
672 /* Close all the connections that are no longer usable. */
673 static void process_broken_connections(ares_channel channel,
674                                        struct timeval *now)
675 {
676   int i;
677   for (i = 0; i < channel->nservers; i++)
678     {
679       struct server_state *server = &channel->servers[i];
680       if (server->is_broken)
681         {
682           handle_error(channel, i, now);
683         }
684     }
685 }
686
687 /* Swap the contents of two lists */
688 static void swap_lists(struct list_node* head_a,
689                        struct list_node* head_b)
690 {
691   int is_a_empty = ares__is_list_empty(head_a);
692   int is_b_empty = ares__is_list_empty(head_b);
693   struct list_node old_a = *head_a;
694   struct list_node old_b = *head_b;
695
696   if (is_a_empty) {
697     ares__init_list_head(head_b);
698   } else {
699     *head_b = old_a;
700     old_a.next->prev = head_b;
701     old_a.prev->next = head_b;
702   }
703   if (is_b_empty) {
704     ares__init_list_head(head_a);
705   } else {
706     *head_a = old_b;
707     old_b.next->prev = head_a;
708     old_b.prev->next = head_a;
709   }
710 }
711
712 static void handle_error(ares_channel channel, int whichserver,
713                          struct timeval *now)
714 {
715   struct server_state *server;
716   struct query *query;
717   struct list_node list_head;
718   struct list_node* list_node;
719
720   server = &channel->servers[whichserver];
721
722   /* Reset communications with this server. */
723   ares__close_sockets(channel, server);
724
725   /* Tell all queries talking to this server to move on and not try this
726    * server again. We steal the current list of queries that were in-flight to
727    * this server, since when we call next_server this can cause the queries to
728    * be re-sent to this server, which will re-insert these queries in that
729    * same server->queries_to_server list.
730    */
731   ares__init_list_head(&list_head);
732   swap_lists(&list_head, &(server->queries_to_server));
733   for (list_node = list_head.next; list_node != &list_head; )
734     {
735       query = list_node->data;
736       list_node = list_node->next;  /* in case the query gets deleted */
737       assert(query->server == whichserver);
738       skip_server(channel, query, whichserver);
739       next_server(channel, query, now);
740     }
741   /* Each query should have removed itself from our temporary list as
742    * it re-sent itself or finished up...
743    */
744   assert(ares__is_list_empty(&list_head));
745 }
746
747 static void skip_server(ares_channel channel, struct query *query,
748                         int whichserver)
749 {
750   /* The given server gave us problems with this query, so if we have the
751    * luxury of using other servers, then let's skip the potentially broken
752    * server and just use the others. If we only have one server and we need to
753    * retry then we should just go ahead and re-use that server, since it's our
754    * only hope; perhaps we just got unlucky, and retrying will work (eg, the
755    * server timed out our TCP connection just as we were sending another
756    * request).
757    */
758   if (channel->nservers > 1)
759     {
760       query->server_info[whichserver].skip_server = 1;
761     }
762 }
763
764 static void next_server(ares_channel channel, struct query *query,
765                         struct timeval *now)
766 {
767   /* We need to try each server channel->tries times. We have channel->nservers
768    * servers to try. In total, we need to do channel->nservers * channel->tries
769    * attempts. Use query->try to remember how many times we already attempted
770    * this query. Use modular arithmetic to find the next server to try. */
771   while (++(query->try_count) < (channel->nservers * channel->tries))
772     {
773       struct server_state *server;
774
775       /* Move on to the next server. */
776       query->server = (query->server + 1) % channel->nservers;
777       server = &channel->servers[query->server];
778
779       /* We don't want to use this server if (1) we decided this connection is
780        * broken, and thus about to be closed, (2) we've decided to skip this
781        * server because of earlier errors we encountered, or (3) we already
782        * sent this query over this exact connection.
783        */
784       if (!server->is_broken &&
785            !query->server_info[query->server].skip_server &&
786            !(query->using_tcp &&
787              (query->server_info[query->server].tcp_connection_generation ==
788               server->tcp_connection_generation)))
789         {
790            ares__send_query(channel, query, now);
791            return;
792         }
793
794       /* You might think that with TCP we only need one try. However, even
795        * when using TCP, servers can time-out our connection just as we're
796        * sending a request, or close our connection because they die, or never
797        * send us a reply because they get wedged or tickle a bug that drops
798        * our request.
799        */
800     }
801
802   /* If we are here, all attempts to perform query failed. */
803   end_query(channel, query, query->error_status, NULL, 0);
804 }
805
806 void ares__send_query(ares_channel channel, struct query *query,
807                       struct timeval *now)
808 {
809   struct send_request *sendreq;
810   struct server_state *server;
811   int timeplus;
812
813   server = &channel->servers[query->server];
814   if (query->using_tcp)
815     {
816       /* Make sure the TCP socket for this server is set up and queue
817        * a send request.
818        */
819       if (server->tcp_socket == ARES_SOCKET_BAD)
820         {
821           if (open_tcp_socket(channel, server) == -1)
822             {
823               skip_server(channel, query, query->server);
824               next_server(channel, query, now);
825               return;
826             }
827         }
828       sendreq = ares_malloc(sizeof(struct send_request));
829       if (!sendreq)
830         {
831         end_query(channel, query, ARES_ENOMEM, NULL, 0);
832           return;
833         }
834       memset(sendreq, 0, sizeof(struct send_request));
835       /* To make the common case fast, we avoid copies by using the query's
836        * tcpbuf for as long as the query is alive. In the rare case where the
837        * query ends while it's queued for transmission, then we give the
838        * sendreq its own copy of the request packet and put it in
839        * sendreq->data_storage.
840        */
841       sendreq->data_storage = NULL;
842       sendreq->data = query->tcpbuf;
843       sendreq->len = query->tcplen;
844       sendreq->owner_query = query;
845       sendreq->next = NULL;
846       if (server->qtail)
847         server->qtail->next = sendreq;
848       else
849         {
850           SOCK_STATE_CALLBACK(channel, server->tcp_socket, 1, 1);
851           server->qhead = sendreq;
852         }
853       server->qtail = sendreq;
854       query->server_info[query->server].tcp_connection_generation =
855         server->tcp_connection_generation;
856     }
857   else
858     {
859       if (server->udp_socket == ARES_SOCKET_BAD)
860         {
861           if (open_udp_socket(channel, server) == -1)
862             {
863               skip_server(channel, query, query->server);
864               next_server(channel, query, now);
865               return;
866             }
867         }
868       if (socket_write(channel, server->udp_socket, query->qbuf, query->qlen) == -1)
869         {
870           /* FIXME: Handle EAGAIN here since it likely can happen. */
871           skip_server(channel, query, query->server);
872           next_server(channel, query, now);
873           return;
874         }
875     }
876
877     /* For each trip through the entire server list, double the channel's
878      * assigned timeout, avoiding overflow.  If channel->timeout is negative,
879      * leave it as-is, even though that should be impossible here.
880      */
881     timeplus = channel->timeout;
882     {
883       /* How many times do we want to double it?  Presume sane values here. */
884       const int shift = query->try_count / channel->nservers;
885
886       /* Is there enough room to shift timeplus left that many times?
887        *
888        * To find out, confirm that all of the bits we'll shift away are zero.
889        * Stop considering a shift if we get to the point where we could shift
890        * a 1 into the sign bit (i.e. when shift is within two of the bit
891        * count).
892        *
893        * This has the side benefit of leaving negative numbers unchanged.
894        */
895       if(shift <= (int)(sizeof(int) * CHAR_BIT - 1)
896          && (timeplus >> (sizeof(int) * CHAR_BIT - 1 - shift)) == 0)
897       {
898         timeplus <<= shift;
899       }
900     }
901
902     query->timeout = *now;
903     timeadd(&query->timeout, timeplus);
904     /* Keep track of queries bucketed by timeout, so we can process
905      * timeout events quickly.
906      */
907     ares__remove_from_list(&(query->queries_by_timeout));
908     ares__insert_in_list(
909         &(query->queries_by_timeout),
910         &(channel->queries_by_timeout[query->timeout.tv_sec %
911                                       ARES_TIMEOUT_TABLE_SIZE]));
912
913     /* Keep track of queries bucketed by server, so we can process server
914      * errors quickly.
915      */
916     ares__remove_from_list(&(query->queries_to_server));
917     ares__insert_in_list(&(query->queries_to_server),
918                          &(server->queries_to_server));
919 }
920
921 /*
922  * setsocknonblock sets the given socket to either blocking or non-blocking
923  * mode based on the 'nonblock' boolean argument. This function is highly
924  * portable.
925  */
926 static int setsocknonblock(ares_socket_t sockfd,    /* operate on this */
927                            int nonblock   /* TRUE or FALSE */)
928 {
929 #if defined(USE_BLOCKING_SOCKETS)
930
931   return 0; /* returns success */
932
933 #elif defined(HAVE_FCNTL_O_NONBLOCK)
934
935   /* most recent unix versions */
936   int flags;
937   flags = fcntl(sockfd, F_GETFL, 0);
938   if (FALSE != nonblock)
939     return fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
940   else
941     return fcntl(sockfd, F_SETFL, flags & (~O_NONBLOCK));  /* LCOV_EXCL_LINE */
942
943 #elif defined(HAVE_IOCTL_FIONBIO)
944
945   /* older unix versions */
946   int flags = nonblock ? 1 : 0;
947   return ioctl(sockfd, FIONBIO, &flags);
948
949 #elif defined(HAVE_IOCTLSOCKET_FIONBIO)
950
951 #ifdef WATT32
952   char flags = nonblock ? 1 : 0;
953 #else
954   /* Windows */
955   unsigned long flags = nonblock ? 1UL : 0UL;
956 #endif
957   return ioctlsocket(sockfd, FIONBIO, &flags);
958
959 #elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO)
960
961   /* Amiga */
962   long flags = nonblock ? 1L : 0L;
963   return IoctlSocket(sockfd, FIONBIO, flags);
964
965 #elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK)
966
967   /* BeOS */
968   long b = nonblock ? 1L : 0L;
969   return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
970
971 #else
972 #  error "no non-blocking method was found/used/set"
973 #endif
974 }
975
976 static int configure_socket(ares_socket_t s, int family, ares_channel channel)
977 {
978   union {
979     struct sockaddr     sa;
980     struct sockaddr_in  sa4;
981     struct sockaddr_in6 sa6;
982   } local;
983
984   /* do not set options for user-managed sockets */
985   if (channel->sock_funcs)
986     return 0;
987
988   (void)setsocknonblock(s, TRUE);
989
990 #if defined(FD_CLOEXEC) && !defined(MSDOS)
991   /* Configure the socket fd as close-on-exec. */
992   if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1)
993     return -1;  /* LCOV_EXCL_LINE */
994 #endif
995
996   /* Set the socket's send and receive buffer sizes. */
997   if ((channel->socket_send_buffer_size > 0) &&
998       setsockopt(s, SOL_SOCKET, SO_SNDBUF,
999                  (void *)&channel->socket_send_buffer_size,
1000                  sizeof(channel->socket_send_buffer_size)) == -1)
1001     return -1;
1002
1003   if ((channel->socket_receive_buffer_size > 0) &&
1004       setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1005                  (void *)&channel->socket_receive_buffer_size,
1006                  sizeof(channel->socket_receive_buffer_size)) == -1)
1007     return -1;
1008
1009 #ifdef SO_BINDTODEVICE
1010   if (channel->local_dev_name[0]) {
1011     if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE,
1012                    channel->local_dev_name, sizeof(channel->local_dev_name))) {
1013       /* Only root can do this, and usually not fatal if it doesn't work, so */
1014       /* just continue on. */
1015     }
1016   }
1017 #endif
1018
1019   if (family == AF_INET) {
1020     if (channel->local_ip4) {
1021       memset(&local.sa4, 0, sizeof(local.sa4));
1022       local.sa4.sin_family = AF_INET;
1023       local.sa4.sin_addr.s_addr = htonl(channel->local_ip4);
1024       if (bind(s, &local.sa, sizeof(local.sa4)) < 0)
1025         return -1;
1026     }
1027   }
1028   else if (family == AF_INET6) {
1029     if (memcmp(channel->local_ip6, &ares_in6addr_any,
1030                sizeof(channel->local_ip6)) != 0) {
1031       memset(&local.sa6, 0, sizeof(local.sa6));
1032       local.sa6.sin6_family = AF_INET6;
1033       memcpy(&local.sa6.sin6_addr, channel->local_ip6,
1034              sizeof(channel->local_ip6));
1035       if (bind(s, &local.sa, sizeof(local.sa6)) < 0)
1036         return -1;
1037     }
1038   }
1039
1040   return 0;
1041 }
1042
1043 static int open_tcp_socket(ares_channel channel, struct server_state *server)
1044 {
1045   ares_socket_t s;
1046   int opt;
1047   ares_socklen_t salen;
1048   union {
1049     struct sockaddr_in  sa4;
1050     struct sockaddr_in6 sa6;
1051   } saddr;
1052   struct sockaddr *sa;
1053
1054   switch (server->addr.family)
1055     {
1056       case AF_INET:
1057         sa = (void *)&saddr.sa4;
1058         salen = sizeof(saddr.sa4);
1059         memset(sa, 0, salen);
1060         saddr.sa4.sin_family = AF_INET;
1061         if (server->addr.tcp_port) {
1062           saddr.sa4.sin_port = aresx_sitous(server->addr.tcp_port);
1063         } else {
1064           saddr.sa4.sin_port = aresx_sitous(channel->tcp_port);
1065         }
1066         memcpy(&saddr.sa4.sin_addr, &server->addr.addrV4,
1067                sizeof(server->addr.addrV4));
1068         break;
1069       case AF_INET6:
1070         sa = (void *)&saddr.sa6;
1071         salen = sizeof(saddr.sa6);
1072         memset(sa, 0, salen);
1073         saddr.sa6.sin6_family = AF_INET6;
1074         if (server->addr.tcp_port) {
1075           saddr.sa6.sin6_port = aresx_sitous(server->addr.tcp_port);
1076         } else {
1077           saddr.sa6.sin6_port = aresx_sitous(channel->tcp_port);
1078         }
1079         memcpy(&saddr.sa6.sin6_addr, &server->addr.addrV6,
1080                sizeof(server->addr.addrV6));
1081         break;
1082       default:
1083         return -1;  /* LCOV_EXCL_LINE */
1084     }
1085
1086   /* Acquire a socket. */
1087   s = ares__open_socket(channel, server->addr.family, SOCK_STREAM, 0);
1088   if (s == ARES_SOCKET_BAD)
1089     return -1;
1090
1091   /* Configure it. */
1092   if (configure_socket(s, server->addr.family, channel) < 0)
1093     {
1094        ares__close_socket(channel, s);
1095        return -1;
1096     }
1097
1098 #ifdef TCP_NODELAY
1099   /*
1100    * Disable the Nagle algorithm (only relevant for TCP sockets, and thus not
1101    * in configure_socket). In general, in DNS lookups we're pretty much
1102    * interested in firing off a single request and then waiting for a reply,
1103    * so batching isn't very interesting.
1104    */
1105   opt = 1;
1106   if (channel->sock_funcs == 0
1107      &&
1108      setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
1109                 (void *)&opt, sizeof(opt)) == -1)
1110     {
1111        ares__close_socket(channel, s);
1112        return -1;
1113     }
1114 #endif
1115
1116   if (channel->sock_config_cb)
1117     {
1118       int err = channel->sock_config_cb(s, SOCK_STREAM,
1119                                         channel->sock_config_cb_data);
1120       if (err < 0)
1121         {
1122           ares__close_socket(channel, s);
1123           return err;
1124         }
1125     }
1126
1127   /* Connect to the server. */
1128   if (ares__connect_socket(channel, s, sa, salen) == -1)
1129     {
1130       int err = SOCKERRNO;
1131
1132       if (err != EINPROGRESS && err != EWOULDBLOCK)
1133         {
1134           ares__close_socket(channel, s);
1135           return -1;
1136         }
1137     }
1138
1139   if (channel->sock_create_cb)
1140     {
1141       int err = channel->sock_create_cb(s, SOCK_STREAM,
1142                                         channel->sock_create_cb_data);
1143       if (err < 0)
1144         {
1145           ares__close_socket(channel, s);
1146           return err;
1147         }
1148     }
1149
1150   SOCK_STATE_CALLBACK(channel, s, 1, 0);
1151   server->tcp_buffer_pos = 0;
1152   server->tcp_socket = s;
1153   server->tcp_connection_generation = ++channel->tcp_connection_generation;
1154   return 0;
1155 }
1156
1157 static int open_udp_socket(ares_channel channel, struct server_state *server)
1158 {
1159   ares_socket_t s;
1160   ares_socklen_t salen;
1161   union {
1162     struct sockaddr_in  sa4;
1163     struct sockaddr_in6 sa6;
1164   } saddr;
1165   struct sockaddr *sa;
1166
1167   switch (server->addr.family)
1168     {
1169       case AF_INET:
1170         sa = (void *)&saddr.sa4;
1171         salen = sizeof(saddr.sa4);
1172         memset(sa, 0, salen);
1173         saddr.sa4.sin_family = AF_INET;
1174         if (server->addr.udp_port) {
1175           saddr.sa4.sin_port = aresx_sitous(server->addr.udp_port);
1176         } else {
1177           saddr.sa4.sin_port = aresx_sitous(channel->udp_port);
1178         }
1179         memcpy(&saddr.sa4.sin_addr, &server->addr.addrV4,
1180                sizeof(server->addr.addrV4));
1181         break;
1182       case AF_INET6:
1183         sa = (void *)&saddr.sa6;
1184         salen = sizeof(saddr.sa6);
1185         memset(sa, 0, salen);
1186         saddr.sa6.sin6_family = AF_INET6;
1187         if (server->addr.udp_port) {
1188           saddr.sa6.sin6_port = aresx_sitous(server->addr.udp_port);
1189         } else {
1190           saddr.sa6.sin6_port = aresx_sitous(channel->udp_port);
1191         }
1192         memcpy(&saddr.sa6.sin6_addr, &server->addr.addrV6,
1193                sizeof(server->addr.addrV6));
1194         break;
1195       default:
1196         return -1;  /* LCOV_EXCL_LINE */
1197     }
1198
1199   /* Acquire a socket. */
1200   s = ares__open_socket(channel, server->addr.family, SOCK_DGRAM, 0);
1201   if (s == ARES_SOCKET_BAD)
1202     return -1;
1203
1204   /* Set the socket non-blocking. */
1205   if (configure_socket(s, server->addr.family, channel) < 0)
1206     {
1207        ares__close_socket(channel, s);
1208        return -1;
1209     }
1210
1211   if (channel->sock_config_cb)
1212     {
1213       int err = channel->sock_config_cb(s, SOCK_DGRAM,
1214                                         channel->sock_config_cb_data);
1215       if (err < 0)
1216         {
1217           ares__close_socket(channel, s);
1218           return err;
1219         }
1220     }
1221
1222   /* Connect to the server. */
1223   if (ares__connect_socket(channel, s, sa, salen) == -1)
1224     {
1225       int err = SOCKERRNO;
1226
1227       if (err != EINPROGRESS && err != EWOULDBLOCK)
1228         {
1229           ares__close_socket(channel, s);
1230           return -1;
1231         }
1232     }
1233
1234   if (channel->sock_create_cb)
1235     {
1236       int err = channel->sock_create_cb(s, SOCK_DGRAM,
1237                                         channel->sock_create_cb_data);
1238       if (err < 0)
1239         {
1240           ares__close_socket(channel, s);
1241           return err;
1242         }
1243     }
1244
1245   SOCK_STATE_CALLBACK(channel, s, 1, 0);
1246
1247   server->udp_socket = s;
1248   return 0;
1249 }
1250
1251 static int same_questions(const unsigned char *qbuf, int qlen,
1252                           const unsigned char *abuf, int alen)
1253 {
1254   struct {
1255     const unsigned char *p;
1256     int qdcount;
1257     char *name;
1258     long namelen;
1259     int type;
1260     int dnsclass;
1261   } q, a;
1262   int i, j;
1263
1264   if (qlen < HFIXEDSZ || alen < HFIXEDSZ)
1265     return 0;
1266
1267   /* Extract qdcount from the request and reply buffers and compare them. */
1268   q.qdcount = DNS_HEADER_QDCOUNT(qbuf);
1269   a.qdcount = DNS_HEADER_QDCOUNT(abuf);
1270   if (q.qdcount != a.qdcount)
1271     return 0;
1272
1273   /* For each question in qbuf, find it in abuf. */
1274   q.p = qbuf + HFIXEDSZ;
1275   for (i = 0; i < q.qdcount; i++)
1276     {
1277       /* Decode the question in the query. */
1278       if (ares_expand_name(q.p, qbuf, qlen, &q.name, &q.namelen)
1279           != ARES_SUCCESS)
1280         return 0;
1281       q.p += q.namelen;
1282       if (q.p + QFIXEDSZ > qbuf + qlen)
1283         {
1284           ares_free(q.name);
1285           return 0;
1286         }
1287       q.type = DNS_QUESTION_TYPE(q.p);
1288       q.dnsclass = DNS_QUESTION_CLASS(q.p);
1289       q.p += QFIXEDSZ;
1290
1291       /* Search for this question in the answer. */
1292       a.p = abuf + HFIXEDSZ;
1293       for (j = 0; j < a.qdcount; j++)
1294         {
1295           /* Decode the question in the answer. */
1296           if (ares_expand_name(a.p, abuf, alen, &a.name, &a.namelen)
1297               != ARES_SUCCESS)
1298             {
1299               ares_free(q.name);
1300               return 0;
1301             }
1302           a.p += a.namelen;
1303           if (a.p + QFIXEDSZ > abuf + alen)
1304             {
1305               ares_free(q.name);
1306               ares_free(a.name);
1307               return 0;
1308             }
1309           a.type = DNS_QUESTION_TYPE(a.p);
1310           a.dnsclass = DNS_QUESTION_CLASS(a.p);
1311           a.p += QFIXEDSZ;
1312
1313           /* Compare the decoded questions. */
1314           if (strcasecmp(q.name, a.name) == 0 && q.type == a.type
1315               && q.dnsclass == a.dnsclass)
1316             {
1317               ares_free(a.name);
1318               break;
1319             }
1320           ares_free(a.name);
1321         }
1322
1323       ares_free(q.name);
1324       if (j == a.qdcount)
1325         return 0;
1326     }
1327   return 1;
1328 }
1329
1330 static int same_address(struct sockaddr *sa, struct ares_addr *aa)
1331 {
1332   void *addr1;
1333   void *addr2;
1334
1335   if (sa->sa_family == aa->family)
1336     {
1337       switch (aa->family)
1338         {
1339           case AF_INET:
1340             addr1 = &aa->addrV4;
1341             addr2 = &(CARES_INADDR_CAST(struct sockaddr_in *, sa))->sin_addr;
1342             if (memcmp(addr1, addr2, sizeof(aa->addrV4)) == 0)
1343               return 1; /* match */
1344             break;
1345           case AF_INET6:
1346             addr1 = &aa->addrV6;
1347             addr2 = &(CARES_INADDR_CAST(struct sockaddr_in6 *, sa))->sin6_addr;
1348             if (memcmp(addr1, addr2, sizeof(aa->addrV6)) == 0)
1349               return 1; /* match */
1350             break;
1351           default:
1352             break;  /* LCOV_EXCL_LINE */
1353         }
1354     }
1355   return 0; /* different */
1356 }
1357
1358 /* search for an OPT RR in the response */
1359 static int has_opt_rr(const unsigned char *abuf, int alen)
1360 {
1361   unsigned int qdcount, ancount, nscount, arcount, i;
1362   const unsigned char *aptr;
1363   int status;
1364
1365   if (alen < HFIXEDSZ)
1366     return -1;
1367
1368   /* Parse the answer header. */
1369   qdcount = DNS_HEADER_QDCOUNT(abuf);
1370   ancount = DNS_HEADER_ANCOUNT(abuf);
1371   nscount = DNS_HEADER_NSCOUNT(abuf);
1372   arcount = DNS_HEADER_ARCOUNT(abuf);
1373
1374   aptr = abuf + HFIXEDSZ;
1375
1376   /* skip the questions */
1377   for (i = 0; i < qdcount; i++)
1378     {
1379       char* name;
1380       long len;
1381       status = ares_expand_name(aptr, abuf, alen, &name, &len);
1382       if (status != ARES_SUCCESS)
1383         return -1;
1384       ares_free_string(name);
1385       if (aptr + len + QFIXEDSZ > abuf + alen)
1386         return -1;
1387       aptr += len + QFIXEDSZ;
1388     }
1389
1390   /* skip the ancount and nscount */
1391   for (i = 0; i < ancount + nscount; i++)
1392     {
1393       char* name;
1394       long len;
1395       int dlen;
1396       status = ares_expand_name(aptr, abuf, alen, &name, &len);
1397       if (status != ARES_SUCCESS)
1398         return -1;
1399       ares_free_string(name);
1400       if (aptr + len + RRFIXEDSZ > abuf + alen)
1401         return -1;
1402       aptr += len;
1403       dlen = DNS_RR_LEN(aptr);
1404       aptr += RRFIXEDSZ;
1405       if (aptr + dlen > abuf + alen)
1406         return -1;
1407       aptr += dlen;
1408     }
1409
1410   /* search for rr type (41) - opt */
1411   for (i = 0; i < arcount; i++)
1412     {
1413       char* name;
1414       long len;
1415       int dlen;
1416       status = ares_expand_name(aptr, abuf, alen, &name, &len);
1417       if (status != ARES_SUCCESS)
1418         return -1;
1419       ares_free_string(name);
1420       if (aptr + len + RRFIXEDSZ > abuf + alen)
1421         return -1;
1422       aptr += len;
1423
1424       if (DNS_RR_TYPE(aptr) == T_OPT)
1425         return 1;
1426
1427       dlen = DNS_RR_LEN(aptr);
1428       aptr += RRFIXEDSZ;
1429       if (aptr + dlen > abuf + alen)
1430         return -1;
1431       aptr += dlen;
1432     }
1433
1434   return 0;
1435 }
1436
1437 static void end_query (ares_channel channel, struct query *query, int status,
1438                        unsigned char *abuf, int alen)
1439 {
1440   int i;
1441
1442   /* First we check to see if this query ended while one of our send
1443    * queues still has pointers to it.
1444    */
1445   for (i = 0; i < channel->nservers; i++)
1446     {
1447       struct server_state *server = &channel->servers[i];
1448       struct send_request *sendreq;
1449       for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
1450         if (sendreq->owner_query == query)
1451           {
1452             sendreq->owner_query = NULL;
1453             assert(sendreq->data_storage == NULL);
1454             if (status == ARES_SUCCESS)
1455               {
1456                 /* We got a reply for this query, but this queued sendreq
1457                  * points into this soon-to-be-gone query's tcpbuf. Probably
1458                  * this means we timed out and queued the query for
1459                  * retransmission, then received a response before actually
1460                  * retransmitting. This is perfectly fine, so we want to keep
1461                  * the connection running smoothly if we can. But in the worst
1462                  * case we may have sent only some prefix of the query, with
1463                  * some suffix of the query left to send. Also, the buffer may
1464                  * be queued on multiple queues. To prevent dangling pointers
1465                  * to the query's tcpbuf and handle these cases, we just give
1466                  * such sendreqs their own copy of the query packet.
1467                  */
1468                sendreq->data_storage = ares_malloc(sendreq->len);
1469                if (sendreq->data_storage != NULL)
1470                  {
1471                    memcpy(sendreq->data_storage, sendreq->data, sendreq->len);
1472                    sendreq->data = sendreq->data_storage;
1473                  }
1474               }
1475             if ((status != ARES_SUCCESS) || (sendreq->data_storage == NULL))
1476               {
1477                 /* We encountered an error (probably a timeout, suggesting the
1478                  * DNS server we're talking to is probably unreachable,
1479                  * wedged, or severely overloaded) or we couldn't copy the
1480                  * request, so mark the connection as broken. When we get to
1481                  * process_broken_connections() we'll close the connection and
1482                  * try to re-send requests to another server.
1483                  */
1484                server->is_broken = 1;
1485                /* Just to be paranoid, zero out this sendreq... */
1486                sendreq->data = NULL;
1487                sendreq->len = 0;
1488              }
1489           }
1490     }
1491
1492   /* Invoke the callback */
1493   query->callback(query->arg, status, query->timeouts, abuf, alen);
1494   ares__free_query(query);
1495
1496   /* Simple cleanup policy: if no queries are remaining, close all network
1497    * sockets unless STAYOPEN is set.
1498    */
1499   if (!(channel->flags & ARES_FLAG_STAYOPEN) &&
1500       ares__is_list_empty(&(channel->all_queries)))
1501     {
1502       for (i = 0; i < channel->nservers; i++)
1503         ares__close_sockets(channel, &channel->servers[i]);
1504     }
1505 }
1506
1507 void ares__free_query(struct query *query)
1508 {
1509   /* Remove the query from all the lists in which it is linked */
1510   ares__remove_from_list(&(query->queries_by_qid));
1511   ares__remove_from_list(&(query->queries_by_timeout));
1512   ares__remove_from_list(&(query->queries_to_server));
1513   ares__remove_from_list(&(query->all_queries));
1514   /* Zero out some important stuff, to help catch bugs */
1515   query->callback = NULL;
1516   query->arg = NULL;
1517   /* Deallocate the memory associated with the query */
1518   ares_free(query->tcpbuf);
1519   ares_free(query->server_info);
1520   ares_free(query);
1521 }
1522
1523 ares_socket_t ares__open_socket(ares_channel channel,
1524                                 int af, int type, int protocol)
1525 {
1526   if (channel->sock_funcs)
1527     return channel->sock_funcs->asocket(af,
1528                                         type,
1529                                         protocol,
1530                                         channel->sock_func_cb_data);
1531   else
1532     return socket(af, type, protocol);
1533 }
1534
1535 int ares__connect_socket(ares_channel channel,
1536                          ares_socket_t sockfd,
1537                          const struct sockaddr *addr,
1538                          ares_socklen_t addrlen)
1539 {
1540   if (channel->sock_funcs)
1541     return channel->sock_funcs->aconnect(sockfd,
1542                                          addr,
1543                                          addrlen,
1544                                          channel->sock_func_cb_data);
1545   else
1546     return connect(sockfd, addr, addrlen);
1547 }
1548
1549 void ares__close_socket(ares_channel channel, ares_socket_t s)
1550 {
1551   if (channel->sock_funcs)
1552     channel->sock_funcs->aclose(s, channel->sock_func_cb_data);
1553   else
1554     sclose(s);
1555 }