Support Watt-32 under Win32.
[platform/upstream/c-ares.git] / ares_process.c
1 /* $Id$ */
2
3 /* Copyright 1998 by the Massachusetts Institute of Technology.
4  * Copyright (C) 2004-2008 by Daniel Stenberg
5  *
6  * Permission to use, copy, modify, and distribute this
7  * software and its documentation for any purpose and without
8  * fee is hereby granted, provided that the above copyright
9  * notice appear in all copies and that both that copyright
10  * notice and this permission notice appear in supporting
11  * documentation, and that the name of M.I.T. not be used in
12  * advertising or publicity pertaining to distribution of the
13  * software without specific, written prior permission.
14  * M.I.T. makes no representations about the suitability of
15  * this software for any purpose.  It is provided "as is"
16  * without express or implied warranty.
17  */
18
19 #include "setup.h"
20
21 #if defined(WIN32) && !defined(WATT32)
22 #include "nameser.h"
23
24 #else
25 #ifdef HAVE_SYS_SOCKET_H
26 #include <sys/socket.h>
27 #endif
28 #ifdef HAVE_SYS_UIO_H
29 #include <sys/uio.h>
30 #endif
31 #ifdef HAVE_NETINET_IN_H
32 #include <netinet/in.h> /* <netinet/tcp.h> may need it */
33 #endif
34 #ifdef HAVE_NETINET_TCP_H
35 #include <netinet/tcp.h> /* for TCP_NODELAY */
36 #endif
37 #ifdef HAVE_NETDB_H
38 #include <netdb.h>
39 #endif
40 #ifdef HAVE_ARPA_NAMESER_H
41 #include <arpa/nameser.h>
42 #endif
43 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
44 #include <arpa/nameser_compat.h>
45 #endif
46 #ifdef HAVE_SYS_TIME_H
47 #include <sys/time.h>
48 #endif
49 #endif /* WIN32 && !WATT32 */
50
51 #ifdef HAVE_STRINGS_H
52 #include <strings.h>
53 #endif
54 #ifdef HAVE_UNISTD_H
55 #include <unistd.h>
56 #endif
57 #ifdef HAVE_SYS_IOCTL_H
58 #include <sys/ioctl.h>
59 #endif
60 #ifdef NETWARE
61 #include <sys/filio.h>
62 #endif
63
64 #include <assert.h>
65 #include <string.h>
66 #include <stdlib.h>
67 #include <fcntl.h>
68 #include <time.h>
69 #include <errno.h>
70
71 #include "ares.h"
72 #include "ares_dns.h"
73 #include "ares_private.h"
74
75
76 static int try_again(int errnum);
77 static void write_tcp_data(ares_channel channel, fd_set *write_fds,
78                            ares_socket_t write_fd, struct timeval *now);
79 static void read_tcp_data(ares_channel channel, fd_set *read_fds,
80                           ares_socket_t read_fd, struct timeval *now);
81 static void read_udp_packets(ares_channel channel, fd_set *read_fds,
82                              ares_socket_t read_fd, struct timeval *now);
83 static void advance_tcp_send_queue(ares_channel channel, int whichserver,
84                                    ssize_t num_bytes);
85 static void process_timeouts(ares_channel channel, struct timeval *now);
86 static void process_broken_connections(ares_channel channel,
87                                        struct timeval *now);
88 static void process_answer(ares_channel channel, unsigned char *abuf,
89                            int alen, int whichserver, int tcp,
90                            struct timeval *now);
91 static void handle_error(ares_channel channel, int whichserver,
92                          struct timeval *now);
93 static void skip_server(ares_channel channel, struct query *query,
94                         int whichserver);
95 static void next_server(ares_channel channel, struct query *query,
96                         struct timeval *now);
97 static int configure_socket(int s, ares_channel channel);
98 static int open_tcp_socket(ares_channel channel, struct server_state *server);
99 static int open_udp_socket(ares_channel channel, struct server_state *server);
100 static int same_questions(const unsigned char *qbuf, int qlen,
101                           const unsigned char *abuf, int alen);
102 static void end_query(ares_channel channel, struct query *query, int status,
103                       unsigned char *abuf, int alen);
104
105 /* return true if now is exactly check time or later */
106 int ares__timedout(struct timeval *now,
107                    struct timeval *check)
108 {
109   int secs = (now->tv_sec - check->tv_sec);
110
111   if(secs > 0)
112     return 1; /* yes, timed out */
113   if(secs < 0)
114     return 0; /* nope, not timed out */
115
116   /* if the full seconds were identical, check the sub second parts */
117   return (now->tv_usec - check->tv_usec >= 0);
118 }
119
120 /* add the specific number of milliseconds to the time in the first argument */
121 int ares__timeadd(struct timeval *now,
122                   int millisecs)
123 {
124   now->tv_sec += millisecs/1000;
125   now->tv_usec += (millisecs%1000)*1000;
126
127   if(now->tv_usec >= 1000000) {
128     ++(now->tv_sec);
129     now->tv_usec -= 1000000;
130   }
131
132   return 0;
133 }
134
135 /* return time offset between now and (future) check, in milliseconds */
136 long ares__timeoffset(struct timeval *now,
137                       struct timeval *check)
138 {
139   return (check->tv_sec - now->tv_sec)*1000 +
140          (check->tv_usec - now->tv_usec)/1000;
141 }
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   struct timeval now = ares__tvnow();
150
151   write_tcp_data(channel, write_fds, ARES_SOCKET_BAD, &now);
152   read_tcp_data(channel, read_fds, ARES_SOCKET_BAD, &now);
153   read_udp_packets(channel, read_fds, ARES_SOCKET_BAD, &now);
154   process_timeouts(channel, &now);
155   process_broken_connections(channel, &now);
156 }
157
158 /* Something interesting happened on the wire, or there was a timeout.
159  * See what's up and respond accordingly.
160  */
161 void ares_process_fd(ares_channel channel,
162                      ares_socket_t read_fd, /* use ARES_SOCKET_BAD or valid
163                                                file descriptors */
164                      ares_socket_t write_fd)
165 {
166   struct timeval now = ares__tvnow();
167
168   write_tcp_data(channel, NULL, write_fd, &now);
169   read_tcp_data(channel, NULL, read_fd, &now);
170   read_udp_packets(channel, NULL, read_fd, &now);
171   process_timeouts(channel, &now);
172 }
173
174
175 /* Return 1 if the specified error number describes a readiness error, or 0
176  * otherwise. This is mostly for HP-UX, which could return EAGAIN or
177  * EWOULDBLOCK. See this man page
178  *
179  *      http://devrsrc1.external.hp.com/STKS/cgi-bin/man2html?manpage=/usr/share/man/man2.Z/send.2
180  */
181 static int try_again(int errnum)
182 {
183 #if !defined EWOULDBLOCK && !defined EAGAIN
184 #error "Neither EWOULDBLOCK nor EAGAIN defined"
185 #endif
186   switch (errnum)
187     {
188 #ifdef EWOULDBLOCK
189     case EWOULDBLOCK:
190       return 1;
191 #endif
192 #if defined EAGAIN && EAGAIN != EWOULDBLOCK
193     case EAGAIN:
194       return 1;
195 #endif
196     }
197   return 0;
198 }
199
200 /* If any TCP sockets select true for writing, write out queued data
201  * we have for them.
202  */
203 static void write_tcp_data(ares_channel channel,
204                            fd_set *write_fds,
205                            ares_socket_t write_fd,
206                            struct timeval *now)
207 {
208   struct server_state *server;
209   struct send_request *sendreq;
210   struct iovec *vec;
211   int i;
212   ssize_t scount;
213   ssize_t wcount;
214   size_t n;
215
216   if(!write_fds && (write_fd == ARES_SOCKET_BAD))
217     /* no possible action */
218     return;
219
220   for (i = 0; i < channel->nservers; i++)
221     {
222       /* Make sure server has data to send and is selected in write_fds or
223          write_fd. */
224       server = &channel->servers[i];
225       if (!server->qhead || server->tcp_socket == ARES_SOCKET_BAD ||
226           server->is_broken)
227         continue;
228
229       if(write_fds) {
230         if(!FD_ISSET(server->tcp_socket, write_fds))
231           continue;
232       }
233       else {
234         if(server->tcp_socket != write_fd)
235           continue;
236       }
237
238       if(write_fds)
239         /* If there's an error and we close this socket, then open
240          * another with the same fd to talk to another server, then we
241          * don't want to think that it was the new socket that was
242          * ready. This is not disastrous, but is likely to result in
243          * extra system calls and confusion. */
244         FD_CLR(server->tcp_socket, write_fds);
245
246       /* Count the number of send queue items. */
247       n = 0;
248       for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
249         n++;
250
251       /* Allocate iovecs so we can send all our data at once. */
252       vec = malloc(n * sizeof(struct iovec));
253       if (vec)
254         {
255           /* Fill in the iovecs and send. */
256           n = 0;
257           for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
258             {
259               vec[n].iov_base = (char *) sendreq->data;
260               vec[n].iov_len = sendreq->len;
261               n++;
262             }
263           wcount = (ssize_t)writev(server->tcp_socket, vec, (int)n);
264           free(vec);
265           if (wcount < 0)
266             {
267               if (!try_again(SOCKERRNO))
268                   handle_error(channel, i, now);
269               continue;
270             }
271
272           /* Advance the send queue by as many bytes as we sent. */
273           advance_tcp_send_queue(channel, i, wcount);
274         }
275       else
276         {
277           /* Can't allocate iovecs; just send the first request. */
278           sendreq = server->qhead;
279
280           scount = swrite(server->tcp_socket, sendreq->data, sendreq->len);
281           if (scount < 0)
282             {
283               if (!try_again(SOCKERRNO))
284                   handle_error(channel, i, now);
285               continue;
286             }
287
288           /* Advance the send queue by as many bytes as we sent. */
289           advance_tcp_send_queue(channel, i, scount);
290         }
291     }
292 }
293
294 /* Consume the given number of bytes from the head of the TCP send queue. */
295 static void advance_tcp_send_queue(ares_channel channel, int whichserver,
296                                    ssize_t num_bytes)
297 {
298   struct send_request *sendreq;
299   struct server_state *server = &channel->servers[whichserver];
300   while (num_bytes > 0)
301     {
302       sendreq = server->qhead;
303       if ((size_t)num_bytes >= sendreq->len)
304        {
305          num_bytes -= sendreq->len;
306          server->qhead = sendreq->next;
307          if (server->qhead == NULL)
308            {
309              SOCK_STATE_CALLBACK(channel, server->tcp_socket, 1, 0);
310              server->qtail = NULL;
311            }
312          if (sendreq->data_storage != NULL)
313            free(sendreq->data_storage);
314          free(sendreq);
315        }
316       else
317        {
318          sendreq->data += num_bytes;
319          sendreq->len -= num_bytes;
320          num_bytes = 0;
321        }
322     }
323 }
324
325 /* If any TCP socket selects true for reading, read some data,
326  * allocate a buffer if we finish reading the length word, and process
327  * a packet if we finish reading one.
328  */
329 static void read_tcp_data(ares_channel channel, fd_set *read_fds,
330                           ares_socket_t read_fd, struct timeval *now)
331 {
332   struct server_state *server;
333   int i;
334   ssize_t count;
335
336   if(!read_fds && (read_fd == ARES_SOCKET_BAD))
337     /* no possible action */
338     return;
339
340   for (i = 0; i < channel->nservers; i++)
341     {
342       /* Make sure the server has a socket and is selected in read_fds. */
343       server = &channel->servers[i];
344       if (server->tcp_socket == ARES_SOCKET_BAD || server->is_broken)
345         continue;
346
347       if(read_fds) {
348         if(!FD_ISSET(server->tcp_socket, read_fds))
349           continue;
350       }
351       else {
352         if(server->tcp_socket != read_fd)
353           continue;
354       }
355
356       if(read_fds)
357         /* If there's an error and we close this socket, then open
358          * another with the same fd to talk to another server, then we
359          * don't want to think that it was the new socket that was
360          * ready. This is not disastrous, but is likely to result in
361          * extra system calls and confusion. */
362         FD_CLR(server->tcp_socket, read_fds);
363
364       if (server->tcp_lenbuf_pos != 2)
365         {
366           /* We haven't yet read a length word, so read that (or
367            * what's left to read of it).
368            */
369           count = sread(server->tcp_socket,
370                         server->tcp_lenbuf + server->tcp_lenbuf_pos,
371                         2 - server->tcp_lenbuf_pos);
372           if (count <= 0)
373             {
374               if (!(count == -1 && try_again(SOCKERRNO)))
375                   handle_error(channel, i, now);
376               continue;
377             }
378
379           server->tcp_lenbuf_pos += (int)count;
380           if (server->tcp_lenbuf_pos == 2)
381             {
382               /* We finished reading the length word.  Decode the
383                * length and allocate a buffer for the data.
384                */
385               server->tcp_length = server->tcp_lenbuf[0] << 8
386                 | server->tcp_lenbuf[1];
387               server->tcp_buffer = malloc(server->tcp_length);
388               if (!server->tcp_buffer)
389                 handle_error(channel, i, now);
390               server->tcp_buffer_pos = 0;
391             }
392         }
393       else
394         {
395           /* Read data into the allocated buffer. */
396           count = sread(server->tcp_socket,
397                         server->tcp_buffer + server->tcp_buffer_pos,
398                         server->tcp_length - server->tcp_buffer_pos);
399           if (count <= 0)
400             {
401               if (!(count == -1 && try_again(SOCKERRNO)))
402                   handle_error(channel, i, now);
403               continue;
404             }
405
406           server->tcp_buffer_pos += (int)count;
407           if (server->tcp_buffer_pos == server->tcp_length)
408             {
409               /* We finished reading this answer; process it and
410                * prepare to read another length word.
411                */
412               process_answer(channel, server->tcp_buffer, server->tcp_length,
413                              i, 1, now);
414           if (server->tcp_buffer)
415                         free(server->tcp_buffer);
416               server->tcp_buffer = NULL;
417               server->tcp_lenbuf_pos = 0;
418               server->tcp_buffer_pos = 0;
419             }
420         }
421     }
422 }
423
424 /* If any UDP sockets select true for reading, process them. */
425 static void read_udp_packets(ares_channel channel, fd_set *read_fds,
426                              ares_socket_t read_fd, struct timeval *now)
427 {
428   struct server_state *server;
429   int i;
430   ssize_t count;
431   unsigned char buf[PACKETSZ + 1];
432
433   if(!read_fds && (read_fd == ARES_SOCKET_BAD))
434     /* no possible action */
435     return;
436
437   for (i = 0; i < channel->nservers; i++)
438     {
439       /* Make sure the server has a socket and is selected in read_fds. */
440       server = &channel->servers[i];
441
442       if (server->udp_socket == ARES_SOCKET_BAD || server->is_broken)
443         continue;
444
445       if(read_fds) {
446         if(!FD_ISSET(server->udp_socket, read_fds))
447           continue;
448       }
449       else {
450         if(server->udp_socket != read_fd)
451           continue;
452       }
453
454       if(read_fds)
455         /* If there's an error and we close this socket, then open
456          * another with the same fd to talk to another server, then we
457          * don't want to think that it was the new socket that was
458          * ready. This is not disastrous, but is likely to result in
459          * extra system calls and confusion. */
460         FD_CLR(server->udp_socket, read_fds);
461
462       /* To reduce event loop overhead, read and process as many
463        * packets as we can. */
464       do {
465         count = sread(server->udp_socket, buf, sizeof(buf));
466         if (count == -1 && try_again(SOCKERRNO))
467           continue;
468         else if (count <= 0)
469           handle_error(channel, i, now);
470         else
471           process_answer(channel, buf, (int)count, i, 0, now);
472        } while (count > 0);
473     }
474 }
475
476 /* If any queries have timed out, note the timeout and move them on. */
477 static void process_timeouts(ares_channel channel, struct timeval *now)
478 {
479   time_t t;  /* the time of the timeouts we're processing */
480   struct query *query;
481   struct list_node* list_head;
482   struct list_node* list_node;
483
484   /* Process all the timeouts that have fired since the last time we
485    * processed timeouts. If things are going well, then we'll have
486    * hundreds/thousands of queries that fall into future buckets, and
487    * only a handful of requests that fall into the "now" bucket, so
488    * this should be quite quick.
489    */
490   for (t = channel->last_timeout_processed; t <= now->tv_sec; t++)
491     {
492       list_head = &(channel->queries_by_timeout[t % ARES_TIMEOUT_TABLE_SIZE]);
493       for (list_node = list_head->next; list_node != list_head; )
494         {
495           query = list_node->data;
496           list_node = list_node->next;  /* in case the query gets deleted */
497           if (query->timeout.tv_sec && ares__timedout(now, &query->timeout))
498             {
499               query->error_status = ARES_ETIMEOUT;
500               ++query->timeouts;
501               next_server(channel, query, now);
502             }
503         }
504      }
505   channel->last_timeout_processed = now->tv_sec;
506 }
507
508 /* Handle an answer from a server. */
509 static void process_answer(ares_channel channel, unsigned char *abuf,
510                            int alen, int whichserver, int tcp,
511                            struct timeval *now)
512 {
513   int tc, rcode;
514   unsigned short id;
515   struct query *query;
516   struct list_node* list_head;
517   struct list_node* list_node;
518
519   /* If there's no room in the answer for a header, we can't do much
520    * with it. */
521   if (alen < HFIXEDSZ)
522     return;
523
524   /* Grab the query ID, truncate bit, and response code from the packet. */
525   id = DNS_HEADER_QID(abuf);
526   tc = DNS_HEADER_TC(abuf);
527   rcode = DNS_HEADER_RCODE(abuf);
528
529   /* Find the query corresponding to this packet. The queries are
530    * hashed/bucketed by query id, so this lookup should be quick.
531    * Note that both the query id and the questions must be the same;
532    * when the query id wraps around we can have multiple outstanding
533    * queries with the same query id, so we need to check both the id and
534    * question.
535    */
536   query = NULL;
537   list_head = &(channel->queries_by_qid[id % ARES_QID_TABLE_SIZE]);
538   for (list_node = list_head->next; list_node != list_head;
539        list_node = list_node->next)
540     {
541       struct query *q = list_node->data;
542       if ((q->qid == id) && same_questions(q->qbuf, q->qlen, abuf, alen))
543         {
544           query = q;
545           break;
546         }
547     }
548   if (!query)
549     return;
550
551   /* If we got a truncated UDP packet and are not ignoring truncation,
552    * don't accept the packet, and switch the query to TCP if we hadn't
553    * done so already.
554    */
555   if ((tc || alen > PACKETSZ) && !tcp && !(channel->flags & ARES_FLAG_IGNTC))
556     {
557       if (!query->using_tcp)
558         {
559           query->using_tcp = 1;
560           ares__send_query(channel, query, now);
561         }
562       return;
563     }
564
565   /* Limit alen to PACKETSZ if we aren't using TCP (only relevant if we
566    * are ignoring truncation.
567    */
568   if (alen > PACKETSZ && !tcp)
569     alen = PACKETSZ;
570
571   /* If we aren't passing through all error packets, discard packets
572    * with SERVFAIL, NOTIMP, or REFUSED response codes.
573    */
574   if (!(channel->flags & ARES_FLAG_NOCHECKRESP))
575     {
576       if (rcode == SERVFAIL || rcode == NOTIMP || rcode == REFUSED)
577         {
578           skip_server(channel, query, whichserver);
579           if (query->server == whichserver)
580             next_server(channel, query, now);
581           return;
582         }
583     }
584
585   end_query(channel, query, ARES_SUCCESS, abuf, alen);
586 }
587
588 /* Close all the connections that are no longer usable. */
589 static void process_broken_connections(ares_channel channel,
590                                        struct timeval *now)
591 {
592   int i;
593   for (i = 0; i < channel->nservers; i++)
594     {
595       struct server_state *server = &channel->servers[i];
596       if (server->is_broken)
597         {
598           handle_error(channel, i, now);
599         }
600     }
601 }
602
603 static void handle_error(ares_channel channel, int whichserver,
604                          struct timeval *now)
605 {
606   struct server_state *server;
607   struct query *query;
608   struct list_node list_head;
609   struct list_node* list_node;
610
611   server = &channel->servers[whichserver];
612
613   /* Reset communications with this server. */
614   ares__close_sockets(channel, server);
615
616   /* Tell all queries talking to this server to move on and not try
617    * this server again. We steal the current list of queries that were
618    * in-flight to this server, since when we call next_server this can
619    * cause the queries to be re-sent to this server, which will
620    * re-insert these queries in that same server->queries_to_server
621    * list.
622    */
623   ares__init_list_head(&list_head);
624   ares__swap_lists(&list_head, &(server->queries_to_server));
625   for (list_node = list_head.next; list_node != &list_head; )
626     {
627       query = list_node->data;
628       list_node = list_node->next;  /* in case the query gets deleted */
629       assert(query->server == whichserver);
630       skip_server(channel, query, whichserver);
631       next_server(channel, query, now);
632     }
633   /* Each query should have removed itself from our temporary list as
634    * it re-sent itself or finished up...
635    */
636   assert(ares__is_list_empty(&list_head));
637 }
638
639 static void skip_server(ares_channel channel, struct query *query,
640                         int whichserver) {
641   /* The given server gave us problems with this query, so if we have
642    * the luxury of using other servers, then let's skip the
643    * potentially broken server and just use the others. If we only
644    * have one server and we need to retry then we should just go ahead
645    * and re-use that server, since it's our only hope; perhaps we
646    * just got unlucky, and retrying will work (eg, the server timed
647    * out our TCP connection just as we were sending another request).
648    */
649   if (channel->nservers > 1)
650     {
651       query->server_info[whichserver].skip_server = 1;
652     }
653 }
654
655 static void next_server(ares_channel channel, struct query *query,
656                         struct timeval *now)
657 {
658   /* Advance to the next server or try. */
659   query->server++;
660   for (; query->try < channel->tries; query->try++)
661     {
662       for (; query->server < channel->nservers; query->server++)
663         {
664           struct server_state *server = &channel->servers[query->server];
665           /* We don't want to use this server if (1) we decided this
666            * connection is broken, and thus about to be closed, (2)
667            * we've decided to skip this server because of earlier
668            * errors we encountered, or (3) we already sent this query
669            * over this exact connection.
670            */
671           if (!server->is_broken &&
672                !query->server_info[query->server].skip_server &&
673                !(query->using_tcp &&
674                  (query->server_info[query->server].tcp_connection_generation ==
675                   server->tcp_connection_generation)))
676             {
677                ares__send_query(channel, query, now);
678                return;
679             }
680         }
681       query->server = 0;
682
683       /* You might think that with TCP we only need one try. However,
684        * even when using TCP, servers can time-out our connection just
685        * as we're sending a request, or close our connection because
686        * they die, or never send us a reply because they get wedged or
687        * tickle a bug that drops our request.
688        */
689     }
690   end_query(channel, query, query->error_status, NULL, 0);
691 }
692
693 void ares__send_query(ares_channel channel, struct query *query,
694                       struct timeval *now)
695 {
696   struct send_request *sendreq;
697   struct server_state *server;
698
699   server = &channel->servers[query->server];
700   if (query->using_tcp)
701     {
702       /* Make sure the TCP socket for this server is set up and queue
703        * a send request.
704        */
705       if (server->tcp_socket == ARES_SOCKET_BAD)
706         {
707           if (open_tcp_socket(channel, server) == -1)
708             {
709               skip_server(channel, query, query->server);
710               next_server(channel, query, now);
711               return;
712             }
713         }
714       sendreq = calloc(sizeof(struct send_request), 1);
715       if (!sendreq)
716         {
717         end_query(channel, query, ARES_ENOMEM, NULL, 0);
718           return;
719         }
720       /* To make the common case fast, we avoid copies by using the
721        * query's tcpbuf for as long as the query is alive. In the rare
722        * case where the query ends while it's queued for transmission,
723        * then we give the sendreq its own copy of the request packet
724        * and put it in sendreq->data_storage.
725        */
726       sendreq->data_storage = NULL;
727       sendreq->data = query->tcpbuf;
728       sendreq->len = query->tcplen;
729       sendreq->owner_query = query;
730       sendreq->next = NULL;
731       if (server->qtail)
732         server->qtail->next = sendreq;
733       else
734         {
735           SOCK_STATE_CALLBACK(channel, server->tcp_socket, 1, 1);
736           server->qhead = sendreq;
737         }
738       server->qtail = sendreq;
739       query->server_info[query->server].tcp_connection_generation =
740         server->tcp_connection_generation;
741     }
742   else
743     {
744       if (server->udp_socket == ARES_SOCKET_BAD)
745         {
746           if (open_udp_socket(channel, server) == -1)
747             {
748               skip_server(channel, query, query->server);
749               next_server(channel, query, now);
750               return;
751             }
752         }
753       if (swrite(server->udp_socket, query->qbuf, query->qlen) == -1)
754         {
755           /* FIXME: Handle EAGAIN here since it likely can happen. */
756           skip_server(channel, query, query->server);
757           next_server(channel, query, now);
758           return;
759         }
760     }
761     query->timeout = *now;
762     ares__timeadd(&query->timeout,
763                   (query->try == 0) ? channel->timeout
764                   : channel->timeout << query->try / channel->nservers);
765     /* Keep track of queries bucketed by timeout, so we can process
766      * timeout events quickly.
767      */
768     ares__remove_from_list(&(query->queries_by_timeout));
769     ares__insert_in_list(
770         &(query->queries_by_timeout),
771         &(channel->queries_by_timeout[query->timeout.tv_sec %
772                                       ARES_TIMEOUT_TABLE_SIZE]));
773
774     /* Keep track of queries bucketed by server, so we can process server
775      * errors quickly.
776      */
777     ares__remove_from_list(&(query->queries_to_server));
778     ares__insert_in_list(&(query->queries_to_server),
779                          &(server->queries_to_server));
780 }
781
782 /*
783  * setsocknonblock sets the given socket to either blocking or non-blocking mode
784  * based on the 'nonblock' boolean argument. This function is highly portable.
785  */
786 static int setsocknonblock(ares_socket_t sockfd,    /* operate on this */
787                     int nonblock   /* TRUE or FALSE */)
788 {
789 #undef SETBLOCK
790 #define SETBLOCK 0
791 #ifdef HAVE_O_NONBLOCK
792   /* most recent unix versions */
793   int flags;
794
795   flags = fcntl(sockfd, F_GETFL, 0);
796   if (FALSE != nonblock)
797     return fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
798   else
799     return fcntl(sockfd, F_SETFL, flags & (~O_NONBLOCK));
800 #undef SETBLOCK
801 #define SETBLOCK 1
802 #endif
803
804 #if defined(HAVE_FIONBIO) && (SETBLOCK == 0)
805   /* older unix versions */
806   int flags;
807
808   flags = nonblock;
809   return ioctl(sockfd, FIONBIO, &flags);
810 #undef SETBLOCK
811 #define SETBLOCK 2
812 #endif
813
814 #if defined(HAVE_IOCTLSOCKET) && (SETBLOCK == 0)
815 #ifdef WATT32
816   char flags;
817 #else
818   /* Windows? */
819   unsigned long flags;
820 #endif
821   flags = nonblock;
822
823   return ioctlsocket(sockfd, FIONBIO, &flags);
824 #undef SETBLOCK
825 #define SETBLOCK 3
826 #endif
827
828 #if defined(HAVE_IOCTLSOCKET_CASE) && (SETBLOCK == 0)
829   /* presumably for Amiga */
830   return IoctlSocket(sockfd, FIONBIO, (long)nonblock);
831 #undef SETBLOCK
832 #define SETBLOCK 4
833 #endif
834
835 #if defined(HAVE_SO_NONBLOCK) && (SETBLOCK == 0)
836   /* BeOS */
837   long b = nonblock ? 1 : 0;
838   return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
839 #undef SETBLOCK
840 #define SETBLOCK 5
841 #endif
842
843 #ifdef HAVE_DISABLED_NONBLOCKING
844   return 0; /* returns success */
845 #undef SETBLOCK
846 #define SETBLOCK 6
847 #endif
848
849 #if (SETBLOCK == 0)
850 #error "no non-blocking method was found/used/set"
851 #endif
852 }
853
854 static int configure_socket(int s, ares_channel channel)
855 {
856   setsocknonblock(s, TRUE);
857
858 #if defined(FD_CLOEXEC) && !defined(MSDOS)
859   /* Configure the socket fd as close-on-exec. */
860   if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1)
861     return -1;
862 #endif
863
864   /* Set the socket's send and receive buffer sizes. */
865   if ((channel->socket_send_buffer_size > 0) &&
866       setsockopt(s, SOL_SOCKET, SO_SNDBUF,
867                  (void *)&channel->socket_send_buffer_size,
868                  sizeof(channel->socket_send_buffer_size)) == -1)
869     return -1;
870
871   if ((channel->socket_receive_buffer_size > 0) &&
872       setsockopt(s, SOL_SOCKET, SO_RCVBUF,
873                  (void *)&channel->socket_receive_buffer_size,
874                  sizeof(channel->socket_receive_buffer_size)) == -1)
875     return -1;
876
877   return 0;
878  }
879
880 static int open_tcp_socket(ares_channel channel, struct server_state *server)
881 {
882   ares_socket_t s;
883   int opt;
884   struct sockaddr_in sockin;
885
886   /* Acquire a socket. */
887   s = socket(AF_INET, SOCK_STREAM, 0);
888   if (s == ARES_SOCKET_BAD)
889     return -1;
890
891   /* Configure it. */
892   if (configure_socket(s, channel) < 0)
893     {
894        close(s);
895        return -1;
896     }
897
898   /*
899    * Disable the Nagle algorithm (only relevant for TCP sockets, and thus not in
900    * configure_socket). In general, in DNS lookups we're pretty much interested
901    * in firing off a single request and then waiting for a reply, so batching
902    * isn't very interesting in general.
903    */
904   opt = 1;
905   if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
906                  (void *)&opt, sizeof(opt)) == -1)
907     {
908        close(s);
909        return -1;
910     }
911
912   /* Connect to the server. */
913   memset(&sockin, 0, sizeof(sockin));
914   sockin.sin_family = AF_INET;
915   sockin.sin_addr = server->addr;
916   sockin.sin_port = (unsigned short)(channel->tcp_port & 0xffff);
917   if (connect(s, (struct sockaddr *) &sockin, sizeof(sockin)) == -1) {
918     int err = SOCKERRNO;
919
920     if (err != EINPROGRESS && err != EWOULDBLOCK) {
921       closesocket(s);
922       return -1;
923     }
924   }
925
926   SOCK_STATE_CALLBACK(channel, s, 1, 0);
927   server->tcp_buffer_pos = 0;
928   server->tcp_socket = s;
929   server->tcp_connection_generation = ++channel->tcp_connection_generation;
930   return 0;
931 }
932
933 static int open_udp_socket(ares_channel channel, struct server_state *server)
934 {
935   ares_socket_t s;
936   struct sockaddr_in sockin;
937
938   /* Acquire a socket. */
939   s = socket(AF_INET, SOCK_DGRAM, 0);
940   if (s == ARES_SOCKET_BAD)
941     return -1;
942
943   /* Set the socket non-blocking. */
944   if (configure_socket(s, channel) < 0)
945     {
946        close(s);
947        return -1;
948     }
949
950   /* Connect to the server. */
951   memset(&sockin, 0, sizeof(sockin));
952   sockin.sin_family = AF_INET;
953   sockin.sin_addr = server->addr;
954   sockin.sin_port = (unsigned short)(channel->udp_port & 0xffff);
955   if (connect(s, (struct sockaddr *) &sockin, sizeof(sockin)) == -1)
956     {
957       closesocket(s);
958       return -1;
959     }
960
961   SOCK_STATE_CALLBACK(channel, s, 1, 0);
962
963   server->udp_socket = s;
964   return 0;
965 }
966
967 static int same_questions(const unsigned char *qbuf, int qlen,
968                           const unsigned char *abuf, int alen)
969 {
970   struct {
971     const unsigned char *p;
972     int qdcount;
973     char *name;
974     long namelen;
975     int type;
976     int dnsclass;
977   } q, a;
978   int i, j;
979
980   if (qlen < HFIXEDSZ || alen < HFIXEDSZ)
981     return 0;
982
983   /* Extract qdcount from the request and reply buffers and compare them. */
984   q.qdcount = DNS_HEADER_QDCOUNT(qbuf);
985   a.qdcount = DNS_HEADER_QDCOUNT(abuf);
986   if (q.qdcount != a.qdcount)
987     return 0;
988
989   /* For each question in qbuf, find it in abuf. */
990   q.p = qbuf + HFIXEDSZ;
991   for (i = 0; i < q.qdcount; i++)
992     {
993       /* Decode the question in the query. */
994       if (ares_expand_name(q.p, qbuf, qlen, &q.name, &q.namelen)
995           != ARES_SUCCESS)
996         return 0;
997       q.p += q.namelen;
998       if (q.p + QFIXEDSZ > qbuf + qlen)
999         {
1000           free(q.name);
1001           return 0;
1002         }
1003       q.type = DNS_QUESTION_TYPE(q.p);
1004       q.dnsclass = DNS_QUESTION_CLASS(q.p);
1005       q.p += QFIXEDSZ;
1006
1007       /* Search for this question in the answer. */
1008       a.p = abuf + HFIXEDSZ;
1009       for (j = 0; j < a.qdcount; j++)
1010         {
1011           /* Decode the question in the answer. */
1012           if (ares_expand_name(a.p, abuf, alen, &a.name, &a.namelen)
1013               != ARES_SUCCESS)
1014             {
1015               free(q.name);
1016               return 0;
1017             }
1018           a.p += a.namelen;
1019           if (a.p + QFIXEDSZ > abuf + alen)
1020             {
1021               free(q.name);
1022               free(a.name);
1023               return 0;
1024             }
1025           a.type = DNS_QUESTION_TYPE(a.p);
1026           a.dnsclass = DNS_QUESTION_CLASS(a.p);
1027           a.p += QFIXEDSZ;
1028
1029           /* Compare the decoded questions. */
1030           if (strcasecmp(q.name, a.name) == 0 && q.type == a.type
1031               && q.dnsclass == a.dnsclass)
1032             {
1033               free(a.name);
1034               break;
1035             }
1036           free(a.name);
1037         }
1038
1039       free(q.name);
1040       if (j == a.qdcount)
1041         return 0;
1042     }
1043   return 1;
1044 }
1045
1046 static void end_query (ares_channel channel, struct query *query, int status,
1047                        unsigned char *abuf, int alen)
1048 {
1049   int i;
1050
1051   /* First we check to see if this query ended while one of our send
1052    * queues still has pointers to it.
1053    */
1054   for (i = 0; i < channel->nservers; i++)
1055     {
1056       struct server_state *server = &channel->servers[i];
1057       struct send_request *sendreq;
1058       for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
1059         if (sendreq->owner_query == query)
1060           {
1061             sendreq->owner_query = NULL;
1062             assert(sendreq->data_storage == NULL);
1063             if (status == ARES_SUCCESS)
1064               {
1065                 /* We got a reply for this query, but this queued
1066                  * sendreq points into this soon-to-be-gone query's
1067                  * tcpbuf. Probably this means we timed out and queued
1068                  * the query for retransmission, then received a
1069                  * response before actually retransmitting. This is
1070                  * perfectly fine, so we want to keep the connection
1071                  * running smoothly if we can. But in the worst case
1072                  * we may have sent only some prefix of the query,
1073                  * with some suffix of the query left to send. Also,
1074                  * the buffer may be queued on multiple queues. To
1075                  * prevent dangling pointers to the query's tcpbuf and
1076                  * handle these cases, we just give such sendreqs
1077                  * their own copy of the query packet.
1078                  */
1079                sendreq->data_storage = malloc(sendreq->len);
1080                if (sendreq->data_storage != NULL)
1081                  {
1082                    memcpy(sendreq->data_storage, sendreq->data, sendreq->len);
1083                    sendreq->data = sendreq->data_storage;
1084                  }
1085               }
1086             if ((status != ARES_SUCCESS) || (sendreq->data_storage == NULL))
1087               {
1088                 /* We encountered an error (probably a timeout,
1089                  * suggesting the DNS server we're talking to is
1090                  * probably unreachable, wedged, or severely
1091                  * overloaded) or we couldn't copy the request, so
1092                  * mark the connection as broken. When we get to
1093                  * process_broken_connections() we'll close the
1094                  * connection and try to re-send requests to another
1095                  * server.
1096                  */
1097                server->is_broken = 1;
1098                /* Just to be paranoid, zero out this sendreq... */
1099                sendreq->data = NULL;
1100                sendreq->len = 0;
1101              }
1102           }
1103     }
1104
1105   /* Invoke the callback */
1106   query->callback(query->arg, status, query->timeouts, abuf, alen);
1107   ares__free_query(query);
1108
1109   /* Simple cleanup policy: if no queries are remaining, close all
1110    * network sockets unless STAYOPEN is set.
1111    */
1112   if (!(channel->flags & ARES_FLAG_STAYOPEN) &&
1113       ares__is_list_empty(&(channel->all_queries)))
1114     {
1115       for (i = 0; i < channel->nservers; i++)
1116         ares__close_sockets(channel, &channel->servers[i]);
1117     }
1118 }
1119
1120 void ares__free_query(struct query *query)
1121 {
1122   /* Remove the query from all the lists in which it is linked */
1123   ares__remove_from_list(&(query->queries_by_qid));
1124   ares__remove_from_list(&(query->queries_by_timeout));
1125   ares__remove_from_list(&(query->queries_to_server));
1126   ares__remove_from_list(&(query->all_queries));
1127   /* Zero out some important stuff, to help catch bugs */
1128   query->callback = NULL;
1129   query->arg = NULL;
1130   /* Deallocate the memory associated with the query */
1131   free(query->tcpbuf);
1132   free(query->server_info);
1133   free(query);
1134 }