ares_inet_ntop.3: s/socklen_t/ares_socklen_t
[platform/upstream/c-ares.git] / ares_process.c
1
2 /* Copyright 1998 by the Massachusetts Institute of Technology.
3  * Copyright (C) 2004-2013 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_NAMESER_H
33 #  include <arpa/nameser.h>
34 #else
35 #  include "nameser.h"
36 #endif
37 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
38 #  include <arpa/nameser_compat.h>
39 #endif
40
41 #ifdef HAVE_STRINGS_H
42 #  include <strings.h>
43 #endif
44 #ifdef HAVE_SYS_IOCTL_H
45 #  include <sys/ioctl.h>
46 #endif
47 #ifdef NETWARE
48 #  include <sys/filio.h>
49 #endif
50
51 #include <assert.h>
52 #include <fcntl.h>
53
54 #include "ares.h"
55 #include "ares_dns.h"
56 #include "ares_nowarn.h"
57 #include "ares_private.h"
58
59
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,
68                                    ssize_t num_bytes);
69 static void process_timeouts(ares_channel channel, struct timeval *now);
70 static void process_broken_connections(ares_channel channel,
71                                        struct timeval *now);
72 static void process_answer(ares_channel channel, unsigned char *abuf,
73                            int alen, int whichserver, int tcp,
74                            struct timeval *now);
75 static void handle_error(ares_channel channel, int whichserver,
76                          struct timeval *now);
77 static void skip_server(ares_channel channel, struct query *query,
78                         int whichserver);
79 static void next_server(ares_channel channel, struct query *query,
80                         struct timeval *now);
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);
88
89 /* return true if now is exactly check time or later */
90 int ares__timedout(struct timeval *now,
91                    struct timeval *check)
92 {
93   long secs = (now->tv_sec - check->tv_sec);
94
95   if(secs > 0)
96     return 1; /* yes, timed out */
97   if(secs < 0)
98     return 0; /* nope, not timed out */
99
100   /* if the full seconds were identical, check the sub second parts */
101   return (now->tv_usec - check->tv_usec >= 0);
102 }
103
104 /* add the specific number of milliseconds to the time in the first argument */
105 int ares__timeadd(struct timeval *now,
106                   int millisecs)
107 {
108   now->tv_sec += millisecs/1000;
109   now->tv_usec += (millisecs%1000)*1000;
110
111   if(now->tv_usec >= 1000000) {
112     ++(now->tv_sec);
113     now->tv_usec -= 1000000;
114   }
115
116   return 0;
117 }
118
119 /* return time offset between now and (future) check, in milliseconds */
120 long ares__timeoffset(struct timeval *now,
121                       struct timeval *check)
122 {
123   return (check->tv_sec - now->tv_sec)*1000 +
124          (check->tv_usec - now->tv_usec)/1000;
125 }
126
127
128 /*
129  * generic process function
130  */
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)
134 {
135   struct timeval now = ares__tvnow();
136
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);
142 }
143
144 /* Something interesting happened on the wire, or there was a timeout.
145  * See what's up and respond accordingly.
146  */
147 void ares_process(ares_channel channel, fd_set *read_fds, fd_set *write_fds)
148 {
149   processfds(channel, read_fds, ARES_SOCKET_BAD, write_fds, ARES_SOCKET_BAD);
150 }
151
152 /* Something interesting happened on the wire, or there was a timeout.
153  * See what's up and respond accordingly.
154  */
155 void ares_process_fd(ares_channel channel,
156                      ares_socket_t read_fd, /* use ARES_SOCKET_BAD or valid
157                                                file descriptors */
158                      ares_socket_t write_fd)
159 {
160   processfds(channel, NULL, read_fd, NULL, write_fd);
161 }
162
163
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
167  *
168  * http://devrsrc1.external.hp.com/STKS/cgi-bin/man2html?
169  *     manpage=/usr/share/man/man2.Z/send.2
170  */
171 static int try_again(int errnum)
172 {
173 #if !defined EWOULDBLOCK && !defined EAGAIN
174 #error "Neither EWOULDBLOCK nor EAGAIN defined"
175 #endif
176   switch (errnum)
177     {
178 #ifdef EWOULDBLOCK
179     case EWOULDBLOCK:
180       return 1;
181 #endif
182 #if defined EAGAIN && EAGAIN != EWOULDBLOCK
183     case EAGAIN:
184       return 1;
185 #endif
186     }
187   return 0;
188 }
189
190 /* If any TCP sockets select true for writing, write out queued data
191  * we have for them.
192  */
193 static void write_tcp_data(ares_channel channel,
194                            fd_set *write_fds,
195                            ares_socket_t write_fd,
196                            struct timeval *now)
197 {
198   struct server_state *server;
199   struct send_request *sendreq;
200   struct iovec *vec;
201   int i;
202   ssize_t scount;
203   ssize_t wcount;
204   size_t n;
205
206   if(!write_fds && (write_fd == ARES_SOCKET_BAD))
207     /* no possible action */
208     return;
209
210   for (i = 0; i < channel->nservers; i++)
211     {
212       /* Make sure server has data to send and is selected in write_fds or
213          write_fd. */
214       server = &channel->servers[i];
215       if (!server->qhead || server->tcp_socket == ARES_SOCKET_BAD ||
216           server->is_broken)
217         continue;
218
219       if(write_fds) {
220         if(!FD_ISSET(server->tcp_socket, write_fds))
221           continue;
222       }
223       else {
224         if(server->tcp_socket != write_fd)
225           continue;
226       }
227
228       if(write_fds)
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);
235
236       /* Count the number of send queue items. */
237       n = 0;
238       for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
239         n++;
240
241       /* Allocate iovecs so we can send all our data at once. */
242       vec = malloc(n * sizeof(struct iovec));
243       if (vec)
244         {
245           /* Fill in the iovecs and send. */
246           n = 0;
247           for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
248             {
249               vec[n].iov_base = (char *) sendreq->data;
250               vec[n].iov_len = sendreq->len;
251               n++;
252             }
253           wcount = (ssize_t)writev(server->tcp_socket, vec, (int)n);
254           free(vec);
255           if (wcount < 0)
256             {
257               if (!try_again(SOCKERRNO))
258                 handle_error(channel, i, now);
259               continue;
260             }
261
262           /* Advance the send queue by as many bytes as we sent. */
263           advance_tcp_send_queue(channel, i, wcount);
264         }
265       else
266         {
267           /* Can't allocate iovecs; just send the first request. */
268           sendreq = server->qhead;
269
270           scount = swrite(server->tcp_socket, sendreq->data, sendreq->len);
271           if (scount < 0)
272             {
273               if (!try_again(SOCKERRNO))
274                 handle_error(channel, i, now);
275               continue;
276             }
277
278           /* Advance the send queue by as many bytes as we sent. */
279           advance_tcp_send_queue(channel, i, scount);
280         }
281     }
282 }
283
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,
286                                    ssize_t num_bytes)
287 {
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);
297       free(sendreq);
298       if (server->qhead == NULL) {
299         SOCK_STATE_CALLBACK(channel, server->tcp_socket, 1, 0);
300         server->qtail = NULL;
301
302         /* qhead is NULL so we cannot continue this loop */
303         break;
304       }
305     }
306     else {
307       sendreq->data += num_bytes;
308       sendreq->len -= num_bytes;
309       num_bytes = 0;
310     }
311   }
312 }
313
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.
317  */
318 static void read_tcp_data(ares_channel channel, fd_set *read_fds,
319                           ares_socket_t read_fd, struct timeval *now)
320 {
321   struct server_state *server;
322   int i;
323   ssize_t count;
324
325   if(!read_fds && (read_fd == ARES_SOCKET_BAD))
326     /* no possible action */
327     return;
328
329   for (i = 0; i < channel->nservers; i++)
330     {
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)
334         continue;
335
336       if(read_fds) {
337         if(!FD_ISSET(server->tcp_socket, read_fds))
338           continue;
339       }
340       else {
341         if(server->tcp_socket != read_fd)
342           continue;
343       }
344
345       if(read_fds)
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
350          * confusion. */
351         FD_CLR(server->tcp_socket, read_fds);
352
353       if (server->tcp_lenbuf_pos != 2)
354         {
355           /* We haven't yet read a length word, so read that (or
356            * what's left to read of it).
357            */
358           count = sread(server->tcp_socket,
359                         server->tcp_lenbuf + server->tcp_lenbuf_pos,
360                         2 - server->tcp_lenbuf_pos);
361           if (count <= 0)
362             {
363               if (!(count == -1 && try_again(SOCKERRNO)))
364                 handle_error(channel, i, now);
365               continue;
366             }
367
368           server->tcp_lenbuf_pos += (int)count;
369           if (server->tcp_lenbuf_pos == 2)
370             {
371               /* We finished reading the length word.  Decode the
372                * length and allocate a buffer for the data.
373                */
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;
380             }
381         }
382       else
383         {
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);
388           if (count <= 0)
389             {
390               if (!(count == -1 && try_again(SOCKERRNO)))
391                 handle_error(channel, i, now);
392               continue;
393             }
394
395           server->tcp_buffer_pos += (int)count;
396           if (server->tcp_buffer_pos == server->tcp_length)
397             {
398               /* We finished reading this answer; process it and
399                * prepare to read another length word.
400                */
401               process_answer(channel, server->tcp_buffer, server->tcp_length,
402                              i, 1, now);
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;
408             }
409         }
410     }
411 }
412
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)
416 {
417   struct server_state *server;
418   int i;
419   ssize_t count;
420   unsigned char buf[MAXENDSSZ + 1];
421 #ifdef HAVE_RECVFROM
422   ares_socklen_t fromlen;
423   union {
424     struct sockaddr     sa;
425     struct sockaddr_in  sa4;
426     struct sockaddr_in6 sa6;
427   } from;
428 #endif
429
430   if(!read_fds && (read_fd == ARES_SOCKET_BAD))
431     /* no possible action */
432     return;
433
434   for (i = 0; i < channel->nservers; i++)
435     {
436       /* Make sure the server has a socket and is selected in read_fds. */
437       server = &channel->servers[i];
438
439       if (server->udp_socket == ARES_SOCKET_BAD || server->is_broken)
440         continue;
441
442       if(read_fds) {
443         if(!FD_ISSET(server->udp_socket, read_fds))
444           continue;
445       }
446       else {
447         if(server->udp_socket != read_fd)
448           continue;
449       }
450
451       if(read_fds)
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);
458
459       /* To reduce event loop overhead, read and process as many
460        * packets as we can. */
461       do {
462         if (server->udp_socket == ARES_SOCKET_BAD)
463           count = 0;
464
465         else {
466 #ifdef HAVE_RECVFROM
467           if (server->addr.family == AF_INET)
468             fromlen = sizeof(from.sa4);
469           else
470             fromlen = sizeof(from.sa6);
471           count = (ssize_t)recvfrom(server->udp_socket, (void *)buf,
472                                     sizeof(buf), 0, &from.sa, &fromlen);
473 #else
474           count = sread(server->udp_socket, buf, sizeof(buf));
475 #endif
476         }
477
478         if (count == -1 && try_again(SOCKERRNO))
479           continue;
480         else if (count <= 0)
481           handle_error(channel, i, now);
482 #ifdef HAVE_RECVFROM
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. */
487           break;
488 #endif
489         else
490           process_answer(channel, buf, (int)count, i, 0, now);
491        } while (count > 0);
492     }
493 }
494
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)
497 {
498   time_t t;  /* the time of the timeouts we're processing */
499   struct query *query;
500   struct list_node* list_head;
501   struct list_node* list_node;
502
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.
507    */
508   for (t = channel->last_timeout_processed; t <= now->tv_sec; t++)
509     {
510       list_head = &(channel->queries_by_timeout[t % ARES_TIMEOUT_TABLE_SIZE]);
511       for (list_node = list_head->next; list_node != list_head; )
512         {
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))
516             {
517               query->error_status = ARES_ETIMEOUT;
518               ++query->timeouts;
519               next_server(channel, query, now);
520             }
521         }
522      }
523   channel->last_timeout_processed = now->tv_sec;
524 }
525
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,
529                            struct timeval *now)
530 {
531   int tc, rcode, packetsz;
532   unsigned short id;
533   struct query *query;
534   struct list_node* list_head;
535   struct list_node* list_node;
536
537   /* If there's no room in the answer for a header, we can't do much
538    * with it. */
539   if (alen < HFIXEDSZ)
540     return;
541
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);
546
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.
552    */
553   query = NULL;
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)
557     {
558       struct query *q = list_node->data;
559       if ((q->qid == id) && same_questions(q->qbuf, q->qlen, abuf, alen))
560         {
561           query = q;
562           break;
563         }
564     }
565   if (!query)
566     return;
567
568   packetsz = PACKETSZ;
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.
572    */
573   if (channel->flags & ARES_FLAG_EDNS)
574   {
575       packetsz = channel->ednspsz;
576       if (rcode == NOTIMP || rcode == FORMERR || rcode == SERVFAIL)
577       {
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);
587           return;
588       }
589   }
590
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
593    * done so already.
594    */
595   if ((tc || alen > packetsz) && !tcp && !(channel->flags & ARES_FLAG_IGNTC))
596     {
597       if (!query->using_tcp)
598         {
599           query->using_tcp = 1;
600           ares__send_query(channel, query, now);
601         }
602       return;
603     }
604
605   /* Limit alen to PACKETSZ if we aren't using TCP (only relevant if we
606    * are ignoring truncation.
607    */
608   if (alen > packetsz && !tcp)
609       alen = packetsz;
610
611   /* If we aren't passing through all error packets, discard packets
612    * with SERVFAIL, NOTIMP, or REFUSED response codes.
613    */
614   if (!(channel->flags & ARES_FLAG_NOCHECKRESP))
615     {
616       if (rcode == SERVFAIL || rcode == NOTIMP || rcode == REFUSED)
617         {
618           skip_server(channel, query, whichserver);
619           if (query->server == whichserver)
620             next_server(channel, query, now);
621           return;
622         }
623     }
624
625   end_query(channel, query, ARES_SUCCESS, abuf, alen);
626 }
627
628 /* Close all the connections that are no longer usable. */
629 static void process_broken_connections(ares_channel channel,
630                                        struct timeval *now)
631 {
632   int i;
633   for (i = 0; i < channel->nservers; i++)
634     {
635       struct server_state *server = &channel->servers[i];
636       if (server->is_broken)
637         {
638           handle_error(channel, i, now);
639         }
640     }
641 }
642
643 /* Swap the contents of two lists */
644 static void swap_lists(struct list_node* head_a,
645                        struct list_node* head_b)
646 {
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;
651
652   if (is_a_empty) {
653     ares__init_list_head(head_b);
654   } else {
655     *head_b = old_a;
656     old_a.next->prev = head_b;
657     old_a.prev->next = head_b;
658   }
659   if (is_b_empty) {
660     ares__init_list_head(head_a);
661   } else {
662     *head_a = old_b;
663     old_b.next->prev = head_a;
664     old_b.prev->next = head_a;
665   }
666 }
667
668 static void handle_error(ares_channel channel, int whichserver,
669                          struct timeval *now)
670 {
671   struct server_state *server;
672   struct query *query;
673   struct list_node list_head;
674   struct list_node* list_node;
675
676   server = &channel->servers[whichserver];
677
678   /* Reset communications with this server. */
679   ares__close_sockets(channel, server);
680
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.
686    */
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; )
690     {
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);
696     }
697   /* Each query should have removed itself from our temporary list as
698    * it re-sent itself or finished up...
699    */
700   assert(ares__is_list_empty(&list_head));
701 }
702
703 static void skip_server(ares_channel channel, struct query *query,
704                         int whichserver)
705 {
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
712    * request).
713    */
714   if (channel->nservers > 1)
715     {
716       query->server_info[whichserver].skip_server = 1;
717     }
718 }
719
720 static void next_server(ares_channel channel, struct query *query,
721                         struct timeval *now)
722 {
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))
728     {
729       struct server_state *server;
730
731       /* Move on to the next server. */
732       query->server = (query->server + 1) % channel->nservers;
733       server = &channel->servers[query->server];
734
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.
739        */
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)))
745         {
746            ares__send_query(channel, query, now);
747            return;
748         }
749
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
754        * our request.
755        */
756     }
757
758   /* If we are here, all attempts to perform query failed. */
759   end_query(channel, query, query->error_status, NULL, 0);
760 }
761
762 void ares__send_query(ares_channel channel, struct query *query,
763                       struct timeval *now)
764 {
765   struct send_request *sendreq;
766   struct server_state *server;
767   int timeplus;
768
769   server = &channel->servers[query->server];
770   if (query->using_tcp)
771     {
772       /* Make sure the TCP socket for this server is set up and queue
773        * a send request.
774        */
775       if (server->tcp_socket == ARES_SOCKET_BAD)
776         {
777           if (open_tcp_socket(channel, server) == -1)
778             {
779               skip_server(channel, query, query->server);
780               next_server(channel, query, now);
781               return;
782             }
783         }
784       sendreq = calloc(1, sizeof(struct send_request));
785       if (!sendreq)
786         {
787         end_query(channel, query, ARES_ENOMEM, NULL, 0);
788           return;
789         }
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.
795        */
796       sendreq->data_storage = NULL;
797       sendreq->data = query->tcpbuf;
798       sendreq->len = query->tcplen;
799       sendreq->owner_query = query;
800       sendreq->next = NULL;
801       if (server->qtail)
802         server->qtail->next = sendreq;
803       else
804         {
805           SOCK_STATE_CALLBACK(channel, server->tcp_socket, 1, 1);
806           server->qhead = sendreq;
807         }
808       server->qtail = sendreq;
809       query->server_info[query->server].tcp_connection_generation =
810         server->tcp_connection_generation;
811     }
812   else
813     {
814       if (server->udp_socket == ARES_SOCKET_BAD)
815         {
816           if (open_udp_socket(channel, server) == -1)
817             {
818               skip_server(channel, query, query->server);
819               next_server(channel, query, now);
820               return;
821             }
822         }
823       if (swrite(server->udp_socket, query->qbuf, query->qlen) == -1)
824         {
825           /* FIXME: Handle EAGAIN here since it likely can happen. */
826           skip_server(channel, query, query->server);
827           next_server(channel, query, now);
828           return;
829         }
830     }
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,
835                   timeplus);
836     /* Keep track of queries bucketed by timeout, so we can process
837      * timeout events quickly.
838      */
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]));
844
845     /* Keep track of queries bucketed by server, so we can process server
846      * errors quickly.
847      */
848     ares__remove_from_list(&(query->queries_to_server));
849     ares__insert_in_list(&(query->queries_to_server),
850                          &(server->queries_to_server));
851 }
852
853 /*
854  * setsocknonblock sets the given socket to either blocking or non-blocking
855  * mode based on the 'nonblock' boolean argument. This function is highly
856  * portable.
857  */
858 static int setsocknonblock(ares_socket_t sockfd,    /* operate on this */
859                     int nonblock   /* TRUE or FALSE */)
860 {
861 #if defined(USE_BLOCKING_SOCKETS)
862
863   return 0; /* returns success */
864
865 #elif defined(HAVE_FCNTL_O_NONBLOCK)
866
867   /* most recent unix versions */
868   int flags;
869   flags = fcntl(sockfd, F_GETFL, 0);
870   if (FALSE != nonblock)
871     return fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
872   else
873     return fcntl(sockfd, F_SETFL, flags & (~O_NONBLOCK));
874
875 #elif defined(HAVE_IOCTL_FIONBIO)
876
877   /* older unix versions */
878   int flags = nonblock ? 1 : 0;
879   return ioctl(sockfd, FIONBIO, &flags);
880
881 #elif defined(HAVE_IOCTLSOCKET_FIONBIO)
882
883 #ifdef WATT32
884   char flags = nonblock ? 1 : 0;
885 #else
886   /* Windows */
887   unsigned long flags = nonblock ? 1UL : 0UL;
888 #endif
889   return ioctlsocket(sockfd, FIONBIO, &flags);
890
891 #elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO)
892
893   /* Amiga */
894   long flags = nonblock ? 1L : 0L;
895   return IoctlSocket(sockfd, FIONBIO, flags);
896
897 #elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK)
898
899   /* BeOS */
900   long b = nonblock ? 1L : 0L;
901   return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
902
903 #else
904 #  error "no non-blocking method was found/used/set"
905 #endif
906 }
907
908 static int configure_socket(ares_socket_t s, int family, ares_channel channel)
909 {
910   union {
911     struct sockaddr     sa;
912     struct sockaddr_in  sa4;
913     struct sockaddr_in6 sa6;
914   } local;
915
916   setsocknonblock(s, TRUE);
917
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)
921     return -1;
922 #endif
923
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)
929     return -1;
930
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)
935     return -1;
936
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. */
943     }
944   }
945 #endif
946
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)
953         return -1;
954     }
955   }
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)
964         return -1;
965     }
966   }
967
968   return 0;
969 }
970
971 static int open_tcp_socket(ares_channel channel, struct server_state *server)
972 {
973   ares_socket_t s;
974   int opt;
975   ares_socklen_t salen;
976   union {
977     struct sockaddr_in  sa4;
978     struct sockaddr_in6 sa6;
979   } saddr;
980   struct sockaddr *sa;
981
982   switch (server->addr.family)
983     {
984       case AF_INET:
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));
992         break;
993       case AF_INET6:
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));
1001         break;
1002       default:
1003         return -1;
1004     }
1005
1006   /* Acquire a socket. */
1007   s = socket(server->addr.family, SOCK_STREAM, 0);
1008   if (s == ARES_SOCKET_BAD)
1009     return -1;
1010
1011   /* Configure it. */
1012   if (configure_socket(s, server->addr.family, channel) < 0)
1013     {
1014        sclose(s);
1015        return -1;
1016     }
1017
1018 #ifdef TCP_NODELAY
1019   /*
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.
1024    */
1025   opt = 1;
1026   if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
1027                  (void *)&opt, sizeof(opt)) == -1)
1028     {
1029        sclose(s);
1030        return -1;
1031     }
1032 #endif
1033
1034   /* Connect to the server. */
1035   if (connect(s, sa, salen) == -1)
1036     {
1037       int err = SOCKERRNO;
1038
1039       if (err != EINPROGRESS && err != EWOULDBLOCK)
1040         {
1041           sclose(s);
1042           return -1;
1043         }
1044     }
1045
1046   if (channel->sock_create_cb)
1047     {
1048       int err = channel->sock_create_cb(s, SOCK_STREAM,
1049                                         channel->sock_create_cb_data);
1050       if (err < 0)
1051         {
1052           sclose(s);
1053           return err;
1054         }
1055     }
1056
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;
1061   return 0;
1062 }
1063
1064 static int open_udp_socket(ares_channel channel, struct server_state *server)
1065 {
1066   ares_socket_t s;
1067   ares_socklen_t salen;
1068   union {
1069     struct sockaddr_in  sa4;
1070     struct sockaddr_in6 sa6;
1071   } saddr;
1072   struct sockaddr *sa;
1073
1074   switch (server->addr.family)
1075     {
1076       case AF_INET:
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));
1084         break;
1085       case AF_INET6:
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));
1093         break;
1094       default:
1095         return -1;
1096     }
1097
1098   /* Acquire a socket. */
1099   s = socket(server->addr.family, SOCK_DGRAM, 0);
1100   if (s == ARES_SOCKET_BAD)
1101     return -1;
1102
1103   /* Set the socket non-blocking. */
1104   if (configure_socket(s, server->addr.family, channel) < 0)
1105     {
1106        sclose(s);
1107        return -1;
1108     }
1109
1110   /* Connect to the server. */
1111   if (connect(s, sa, salen) == -1)
1112     {
1113       int err = SOCKERRNO;
1114
1115       if (err != EINPROGRESS && err != EWOULDBLOCK)
1116         {
1117           sclose(s);
1118           return -1;
1119         }
1120     }
1121
1122   if (channel->sock_create_cb)
1123     {
1124       int err = channel->sock_create_cb(s, SOCK_DGRAM,
1125                                         channel->sock_create_cb_data);
1126       if (err < 0)
1127         {
1128           sclose(s);
1129           return err;
1130         }
1131     }
1132
1133   SOCK_STATE_CALLBACK(channel, s, 1, 0);
1134
1135   server->udp_socket = s;
1136   return 0;
1137 }
1138
1139 static int same_questions(const unsigned char *qbuf, int qlen,
1140                           const unsigned char *abuf, int alen)
1141 {
1142   struct {
1143     const unsigned char *p;
1144     int qdcount;
1145     char *name;
1146     long namelen;
1147     int type;
1148     int dnsclass;
1149   } q, a;
1150   int i, j;
1151
1152   if (qlen < HFIXEDSZ || alen < HFIXEDSZ)
1153     return 0;
1154
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)
1159     return 0;
1160
1161   /* For each question in qbuf, find it in abuf. */
1162   q.p = qbuf + HFIXEDSZ;
1163   for (i = 0; i < q.qdcount; i++)
1164     {
1165       /* Decode the question in the query. */
1166       if (ares_expand_name(q.p, qbuf, qlen, &q.name, &q.namelen)
1167           != ARES_SUCCESS)
1168         return 0;
1169       q.p += q.namelen;
1170       if (q.p + QFIXEDSZ > qbuf + qlen)
1171         {
1172           free(q.name);
1173           return 0;
1174         }
1175       q.type = DNS_QUESTION_TYPE(q.p);
1176       q.dnsclass = DNS_QUESTION_CLASS(q.p);
1177       q.p += QFIXEDSZ;
1178
1179       /* Search for this question in the answer. */
1180       a.p = abuf + HFIXEDSZ;
1181       for (j = 0; j < a.qdcount; j++)
1182         {
1183           /* Decode the question in the answer. */
1184           if (ares_expand_name(a.p, abuf, alen, &a.name, &a.namelen)
1185               != ARES_SUCCESS)
1186             {
1187               free(q.name);
1188               return 0;
1189             }
1190           a.p += a.namelen;
1191           if (a.p + QFIXEDSZ > abuf + alen)
1192             {
1193               free(q.name);
1194               free(a.name);
1195               return 0;
1196             }
1197           a.type = DNS_QUESTION_TYPE(a.p);
1198           a.dnsclass = DNS_QUESTION_CLASS(a.p);
1199           a.p += QFIXEDSZ;
1200
1201           /* Compare the decoded questions. */
1202           if (strcasecmp(q.name, a.name) == 0 && q.type == a.type
1203               && q.dnsclass == a.dnsclass)
1204             {
1205               free(a.name);
1206               break;
1207             }
1208           free(a.name);
1209         }
1210
1211       free(q.name);
1212       if (j == a.qdcount)
1213         return 0;
1214     }
1215   return 1;
1216 }
1217
1218 static int same_address(struct sockaddr *sa, struct ares_addr *aa)
1219 {
1220   void *addr1;
1221   void *addr2;
1222
1223   if (sa->sa_family == aa->family)
1224     {
1225       switch (aa->family)
1226         {
1227           case AF_INET:
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 */
1232             break;
1233           case AF_INET6:
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 */
1238             break;
1239           default:
1240             break;
1241         }
1242     }
1243   return 0; /* different */
1244 }
1245
1246 static void end_query (ares_channel channel, struct query *query, int status,
1247                        unsigned char *abuf, int alen)
1248 {
1249   int i;
1250
1251   /* First we check to see if this query ended while one of our send
1252    * queues still has pointers to it.
1253    */
1254   for (i = 0; i < channel->nservers; i++)
1255     {
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)
1260           {
1261             sendreq->owner_query = NULL;
1262             assert(sendreq->data_storage == NULL);
1263             if (status == ARES_SUCCESS)
1264               {
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.
1276                  */
1277                sendreq->data_storage = malloc(sendreq->len);
1278                if (sendreq->data_storage != NULL)
1279                  {
1280                    memcpy(sendreq->data_storage, sendreq->data, sendreq->len);
1281                    sendreq->data = sendreq->data_storage;
1282                  }
1283               }
1284             if ((status != ARES_SUCCESS) || (sendreq->data_storage == NULL))
1285               {
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.
1292                  */
1293                server->is_broken = 1;
1294                /* Just to be paranoid, zero out this sendreq... */
1295                sendreq->data = NULL;
1296                sendreq->len = 0;
1297              }
1298           }
1299     }
1300
1301   /* Invoke the callback */
1302   query->callback(query->arg, status, query->timeouts, abuf, alen);
1303   ares__free_query(query);
1304
1305   /* Simple cleanup policy: if no queries are remaining, close all network
1306    * sockets unless STAYOPEN is set.
1307    */
1308   if (!(channel->flags & ARES_FLAG_STAYOPEN) &&
1309       ares__is_list_empty(&(channel->all_queries)))
1310     {
1311       for (i = 0; i < channel->nservers; i++)
1312         ares__close_sockets(channel, &channel->servers[i]);
1313     }
1314 }
1315
1316 void ares__free_query(struct query *query)
1317 {
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;
1325   query->arg = NULL;
1326   /* Deallocate the memory associated with the query */
1327   free(query->tcpbuf);
1328   free(query->server_info);
1329   free(query);
1330 }