• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2021, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22 
23 #include "curl_setup.h"
24 
25 /***********************************************************************
26  * Only for ares-enabled builds
27  * And only for functions that fulfill the asynch resolver backend API
28  * as defined in asyn.h, nothing else belongs in this file!
29  **********************************************************************/
30 
31 #ifdef CURLRES_ARES
32 
33 #include <limits.h>
34 #ifdef HAVE_NETINET_IN_H
35 #include <netinet/in.h>
36 #endif
37 #ifdef HAVE_NETDB_H
38 #include <netdb.h>
39 #endif
40 #ifdef HAVE_ARPA_INET_H
41 #include <arpa/inet.h>
42 #endif
43 #ifdef __VMS
44 #include <in.h>
45 #include <inet.h>
46 #endif
47 
48 #ifdef HAVE_PROCESS_H
49 #include <process.h>
50 #endif
51 
52 #if (defined(NETWARE) && defined(__NOVELL_LIBC__))
53 #undef in_addr_t
54 #define in_addr_t unsigned long
55 #endif
56 
57 #include "urldata.h"
58 #include "sendf.h"
59 #include "hostip.h"
60 #include "hash.h"
61 #include "share.h"
62 #include "url.h"
63 #include "multiif.h"
64 #include "inet_pton.h"
65 #include "connect.h"
66 #include "select.h"
67 #include "progress.h"
68 
69 #  if defined(CURL_STATICLIB) && !defined(CARES_STATICLIB) &&   \
70   defined(WIN32)
71 #    define CARES_STATICLIB
72 #  endif
73 #  include <ares.h>
74 #  include <ares_version.h> /* really old c-ares didn't include this by
75                                itself */
76 
77 #if ARES_VERSION >= 0x010500
78 /* c-ares 1.5.0 or later, the callback proto is modified */
79 #define HAVE_CARES_CALLBACK_TIMEOUTS 1
80 #endif
81 
82 #if ARES_VERSION >= 0x010601
83 /* IPv6 supported since 1.6.1 */
84 #define HAVE_CARES_IPV6 1
85 #endif
86 
87 #if ARES_VERSION >= 0x010704
88 #define HAVE_CARES_SERVERS_CSV 1
89 #define HAVE_CARES_LOCAL_DEV 1
90 #define HAVE_CARES_SET_LOCAL 1
91 #endif
92 
93 #if ARES_VERSION >= 0x010b00
94 #define HAVE_CARES_PORTS_CSV 1
95 #endif
96 
97 #if ARES_VERSION >= 0x011000
98 /* 1.16.0 or later has ares_getaddrinfo */
99 #define HAVE_CARES_GETADDRINFO 1
100 #endif
101 
102 /* The last 3 #include files should be in this order */
103 #include "curl_printf.h"
104 #include "curl_memory.h"
105 #include "memdebug.h"
106 
107 struct thread_data {
108   int num_pending; /* number of outstanding c-ares requests */
109   struct Curl_addrinfo *temp_ai; /* intermediary result while fetching c-ares
110                                     parts */
111   int last_status;
112   struct curltime happy_eyeballs_dns_time; /* when this timer started, or 0 */
113 };
114 
115 /* How long we are willing to wait for additional parallel responses after
116    obtaining a "definitive" one.
117 
118    This is intended to equal the c-ares default timeout.  cURL always uses that
119    default value.  Unfortunately, c-ares doesn't expose its default timeout in
120    its API, but it is officially documented as 5 seconds.
121 
122    See query_completed_cb() for an explanation of how this is used.
123  */
124 #define HAPPY_EYEBALLS_DNS_TIMEOUT 5000
125 
126 /*
127  * Curl_resolver_global_init() - the generic low-level asynchronous name
128  * resolve API.  Called from curl_global_init() to initialize global resolver
129  * environment.  Initializes ares library.
130  */
Curl_resolver_global_init(void)131 int Curl_resolver_global_init(void)
132 {
133 #ifdef CARES_HAVE_ARES_LIBRARY_INIT
134   if(ares_library_init(ARES_LIB_INIT_ALL)) {
135     return CURLE_FAILED_INIT;
136   }
137 #endif
138   return CURLE_OK;
139 }
140 
141 /*
142  * Curl_resolver_global_cleanup()
143  *
144  * Called from curl_global_cleanup() to destroy global resolver environment.
145  * Deinitializes ares library.
146  */
Curl_resolver_global_cleanup(void)147 void Curl_resolver_global_cleanup(void)
148 {
149 #ifdef CARES_HAVE_ARES_LIBRARY_CLEANUP
150   ares_library_cleanup();
151 #endif
152 }
153 
154 
sock_state_cb(void * data,ares_socket_t socket_fd,int readable,int writable)155 static void sock_state_cb(void *data, ares_socket_t socket_fd,
156                           int readable, int writable)
157 {
158   struct Curl_easy *easy = data;
159   if(!readable && !writable) {
160     DEBUGASSERT(easy);
161     Curl_multi_closed(easy, socket_fd);
162   }
163 }
164 
165 /*
166  * Curl_resolver_init()
167  *
168  * Called from curl_easy_init() -> Curl_open() to initialize resolver
169  * URL-state specific environment ('resolver' member of the UrlState
170  * structure).  Fills the passed pointer by the initialized ares_channel.
171  */
Curl_resolver_init(struct Curl_easy * easy,void ** resolver)172 CURLcode Curl_resolver_init(struct Curl_easy *easy, void **resolver)
173 {
174   int status;
175   struct ares_options options;
176   int optmask = ARES_OPT_SOCK_STATE_CB;
177   options.sock_state_cb = sock_state_cb;
178   options.sock_state_cb_data = easy;
179   status = ares_init_options((ares_channel*)resolver, &options, optmask);
180   if(status != ARES_SUCCESS) {
181     if(status == ARES_ENOMEM)
182       return CURLE_OUT_OF_MEMORY;
183     else
184       return CURLE_FAILED_INIT;
185   }
186   return CURLE_OK;
187   /* make sure that all other returns from this function should destroy the
188      ares channel before returning error! */
189 }
190 
191 /*
192  * Curl_resolver_cleanup()
193  *
194  * Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver
195  * URL-state specific environment ('resolver' member of the UrlState
196  * structure).  Destroys the ares channel.
197  */
Curl_resolver_cleanup(void * resolver)198 void Curl_resolver_cleanup(void *resolver)
199 {
200   ares_destroy((ares_channel)resolver);
201 }
202 
203 /*
204  * Curl_resolver_duphandle()
205  *
206  * Called from curl_easy_duphandle() to duplicate resolver URL-state specific
207  * environment ('resolver' member of the UrlState structure).  Duplicates the
208  * 'from' ares channel and passes the resulting channel to the 'to' pointer.
209  */
Curl_resolver_duphandle(struct Curl_easy * easy,void ** to,void * from)210 CURLcode Curl_resolver_duphandle(struct Curl_easy *easy, void **to, void *from)
211 {
212   (void)from;
213   /*
214    * it would be better to call ares_dup instead, but right now
215    * it is not possible to set 'sock_state_cb_data' outside of
216    * ares_init_options
217    */
218   return Curl_resolver_init(easy, to);
219 }
220 
221 static void destroy_async_data(struct Curl_async *async);
222 
223 /*
224  * Cancel all possibly still on-going resolves for this connection.
225  */
Curl_resolver_cancel(struct Curl_easy * data)226 void Curl_resolver_cancel(struct Curl_easy *data)
227 {
228   DEBUGASSERT(data);
229   if(data->state.async.resolver)
230     ares_cancel((ares_channel)data->state.async.resolver);
231   destroy_async_data(&data->state.async);
232 }
233 
234 /*
235  * We're equivalent to Curl_resolver_cancel() for the c-ares resolver.  We
236  * never block.
237  */
Curl_resolver_kill(struct Curl_easy * data)238 void Curl_resolver_kill(struct Curl_easy *data)
239 {
240   /* We don't need to check the resolver state because we can be called safely
241      at any time and we always do the same thing. */
242   Curl_resolver_cancel(data);
243 }
244 
245 /*
246  * destroy_async_data() cleans up async resolver data.
247  */
destroy_async_data(struct Curl_async * async)248 static void destroy_async_data(struct Curl_async *async)
249 {
250   free(async->hostname);
251 
252   if(async->tdata) {
253     struct thread_data *res = async->tdata;
254     if(res) {
255       if(res->temp_ai) {
256         Curl_freeaddrinfo(res->temp_ai);
257         res->temp_ai = NULL;
258       }
259       free(res);
260     }
261     async->tdata = NULL;
262   }
263 
264   async->hostname = NULL;
265 }
266 
267 /*
268  * Curl_resolver_getsock() is called when someone from the outside world
269  * (using curl_multi_fdset()) wants to get our fd_set setup and we're talking
270  * with ares. The caller must make sure that this function is only called when
271  * we have a working ares channel.
272  *
273  * Returns: sockets-in-use-bitmap
274  */
275 
Curl_resolver_getsock(struct Curl_easy * data,curl_socket_t * socks)276 int Curl_resolver_getsock(struct Curl_easy *data,
277                           curl_socket_t *socks)
278 {
279   struct timeval maxtime;
280   struct timeval timebuf;
281   struct timeval *timeout;
282   long milli;
283   int max = ares_getsock((ares_channel)data->state.async.resolver,
284                          (ares_socket_t *)socks, MAX_SOCKSPEREASYHANDLE);
285 
286   maxtime.tv_sec = CURL_TIMEOUT_RESOLVE;
287   maxtime.tv_usec = 0;
288 
289   timeout = ares_timeout((ares_channel)data->state.async.resolver, &maxtime,
290                          &timebuf);
291   milli = (timeout->tv_sec * 1000) + (timeout->tv_usec/1000);
292   if(milli == 0)
293     milli += 10;
294   Curl_expire(data, milli, EXPIRE_ASYNC_NAME);
295 
296   return max;
297 }
298 
299 /*
300  * waitperform()
301  *
302  * 1) Ask ares what sockets it currently plays with, then
303  * 2) wait for the timeout period to check for action on ares' sockets.
304  * 3) tell ares to act on all the sockets marked as "with action"
305  *
306  * return number of sockets it worked on
307  */
308 
waitperform(struct Curl_easy * data,timediff_t timeout_ms)309 static int waitperform(struct Curl_easy *data, timediff_t timeout_ms)
310 {
311   int nfds;
312   int bitmask;
313   ares_socket_t socks[ARES_GETSOCK_MAXNUM];
314   struct pollfd pfd[ARES_GETSOCK_MAXNUM];
315   int i;
316   int num = 0;
317 
318   bitmask = ares_getsock((ares_channel)data->state.async.resolver, socks,
319                          ARES_GETSOCK_MAXNUM);
320 
321   for(i = 0; i < ARES_GETSOCK_MAXNUM; i++) {
322     pfd[i].events = 0;
323     pfd[i].revents = 0;
324     if(ARES_GETSOCK_READABLE(bitmask, i)) {
325       pfd[i].fd = socks[i];
326       pfd[i].events |= POLLRDNORM|POLLIN;
327     }
328     if(ARES_GETSOCK_WRITABLE(bitmask, i)) {
329       pfd[i].fd = socks[i];
330       pfd[i].events |= POLLWRNORM|POLLOUT;
331     }
332     if(pfd[i].events)
333       num++;
334     else
335       break;
336   }
337 
338   if(num)
339     nfds = Curl_poll(pfd, num, timeout_ms);
340   else
341     nfds = 0;
342 
343   if(!nfds)
344     /* Call ares_process() unconditionally here, even if we simply timed out
345        above, as otherwise the ares name resolve won't timeout! */
346     ares_process_fd((ares_channel)data->state.async.resolver, ARES_SOCKET_BAD,
347                     ARES_SOCKET_BAD);
348   else {
349     /* move through the descriptors and ask for processing on them */
350     for(i = 0; i < num; i++)
351       ares_process_fd((ares_channel)data->state.async.resolver,
352                       (pfd[i].revents & (POLLRDNORM|POLLIN))?
353                       pfd[i].fd:ARES_SOCKET_BAD,
354                       (pfd[i].revents & (POLLWRNORM|POLLOUT))?
355                       pfd[i].fd:ARES_SOCKET_BAD);
356   }
357   return nfds;
358 }
359 
360 /*
361  * Curl_resolver_is_resolved() is called repeatedly to check if a previous
362  * name resolve request has completed. It should also make sure to time-out if
363  * the operation seems to take too long.
364  *
365  * Returns normal CURLcode errors.
366  */
Curl_resolver_is_resolved(struct Curl_easy * data,struct Curl_dns_entry ** dns)367 CURLcode Curl_resolver_is_resolved(struct Curl_easy *data,
368                                    struct Curl_dns_entry **dns)
369 {
370   struct thread_data *res = data->state.async.tdata;
371   CURLcode result = CURLE_OK;
372 
373   DEBUGASSERT(dns);
374   *dns = NULL;
375 
376   waitperform(data, 0);
377 
378   /* Now that we've checked for any last minute results above, see if there are
379      any responses still pending when the EXPIRE_HAPPY_EYEBALLS_DNS timer
380      expires. */
381   if(res
382      && res->num_pending
383      /* This is only set to non-zero if the timer was started. */
384      && (res->happy_eyeballs_dns_time.tv_sec
385          || res->happy_eyeballs_dns_time.tv_usec)
386      && (Curl_timediff(Curl_now(), res->happy_eyeballs_dns_time)
387          >= HAPPY_EYEBALLS_DNS_TIMEOUT)) {
388     /* Remember that the EXPIRE_HAPPY_EYEBALLS_DNS timer is no longer
389        running. */
390     memset(
391       &res->happy_eyeballs_dns_time, 0, sizeof(res->happy_eyeballs_dns_time));
392 
393     /* Cancel the raw c-ares request, which will fire query_completed_cb() with
394        ARES_ECANCELLED synchronously for all pending responses.  This will
395        leave us with res->num_pending == 0, which is perfect for the next
396        block. */
397     ares_cancel((ares_channel)data->state.async.resolver);
398     DEBUGASSERT(res->num_pending == 0);
399   }
400 
401   if(res && !res->num_pending) {
402     (void)Curl_addrinfo_callback(data, res->last_status, res->temp_ai);
403     /* temp_ai ownership is moved to the connection, so we need not free-up
404        them */
405     res->temp_ai = NULL;
406 
407     if(!data->state.async.dns)
408       result = Curl_resolver_error(data);
409     else
410       *dns = data->state.async.dns;
411 
412     destroy_async_data(&data->state.async);
413   }
414 
415   return result;
416 }
417 
418 /*
419  * Curl_resolver_wait_resolv()
420  *
421  * Waits for a resolve to finish. This function should be avoided since using
422  * this risk getting the multi interface to "hang".
423  *
424  * 'entry' MUST be non-NULL.
425  *
426  * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved,
427  * CURLE_OPERATION_TIMEDOUT if a time-out occurred, or other errors.
428  */
Curl_resolver_wait_resolv(struct Curl_easy * data,struct Curl_dns_entry ** entry)429 CURLcode Curl_resolver_wait_resolv(struct Curl_easy *data,
430                                    struct Curl_dns_entry **entry)
431 {
432   CURLcode result = CURLE_OK;
433   timediff_t timeout;
434   struct curltime now = Curl_now();
435 
436   DEBUGASSERT(entry);
437   *entry = NULL; /* clear on entry */
438 
439   timeout = Curl_timeleft(data, &now, TRUE);
440   if(timeout < 0) {
441     /* already expired! */
442     connclose(data->conn, "Timed out before name resolve started");
443     return CURLE_OPERATION_TIMEDOUT;
444   }
445   if(!timeout)
446     timeout = CURL_TIMEOUT_RESOLVE * 1000; /* default name resolve timeout */
447 
448   /* Wait for the name resolve query to complete. */
449   while(!result) {
450     struct timeval *tvp, tv, store;
451     int itimeout;
452     timediff_t timeout_ms;
453 
454 #if TIMEDIFF_T_MAX > INT_MAX
455     itimeout = (timeout > INT_MAX) ? INT_MAX : (int)timeout;
456 #else
457     itimeout = (int)timeout;
458 #endif
459 
460     store.tv_sec = itimeout/1000;
461     store.tv_usec = (itimeout%1000)*1000;
462 
463     tvp = ares_timeout((ares_channel)data->state.async.resolver, &store, &tv);
464 
465     /* use the timeout period ares returned to us above if less than one
466        second is left, otherwise just use 1000ms to make sure the progress
467        callback gets called frequent enough */
468     if(!tvp->tv_sec)
469       timeout_ms = (timediff_t)(tvp->tv_usec/1000);
470     else
471       timeout_ms = 1000;
472 
473     waitperform(data, timeout_ms);
474     result = Curl_resolver_is_resolved(data, entry);
475 
476     if(result || data->state.async.done)
477       break;
478 
479     if(Curl_pgrsUpdate(data))
480       result = CURLE_ABORTED_BY_CALLBACK;
481     else {
482       struct curltime now2 = Curl_now();
483       timediff_t timediff = Curl_timediff(now2, now); /* spent time */
484       if(timediff <= 0)
485         timeout -= 1; /* always deduct at least 1 */
486       else if(timediff > timeout)
487         timeout = -1;
488       else
489         timeout -= timediff;
490       now = now2; /* for next loop */
491     }
492     if(timeout < 0)
493       result = CURLE_OPERATION_TIMEDOUT;
494   }
495   if(result)
496     /* failure, so we cancel the ares operation */
497     ares_cancel((ares_channel)data->state.async.resolver);
498 
499   /* Operation complete, if the lookup was successful we now have the entry
500      in the cache. */
501   if(entry)
502     *entry = data->state.async.dns;
503 
504   if(result)
505     /* close the connection, since we can't return failure here without
506        cleaning up this connection properly. */
507     connclose(data->conn, "c-ares resolve failed");
508 
509   return result;
510 }
511 
512 #ifndef HAVE_CARES_GETADDRINFO
513 
514 /* Connects results to the list */
compound_results(struct thread_data * res,struct Curl_addrinfo * ai)515 static void compound_results(struct thread_data *res,
516                              struct Curl_addrinfo *ai)
517 {
518   if(!ai)
519     return;
520 
521 #ifdef ENABLE_IPV6 /* CURLRES_IPV6 */
522   if(res->temp_ai && res->temp_ai->ai_family == PF_INET6) {
523     /* We have results already, put the new IPv6 entries at the head of the
524        list. */
525     struct Curl_addrinfo *temp_ai_tail = res->temp_ai;
526 
527     while(temp_ai_tail->ai_next)
528       temp_ai_tail = temp_ai_tail->ai_next;
529 
530     temp_ai_tail->ai_next = ai;
531   }
532   else
533 #endif /* CURLRES_IPV6 */
534   {
535     /* Add the new results to the list of old results. */
536     struct Curl_addrinfo *ai_tail = ai;
537     while(ai_tail->ai_next)
538       ai_tail = ai_tail->ai_next;
539 
540     ai_tail->ai_next = res->temp_ai;
541     res->temp_ai = ai;
542   }
543 }
544 
545 /*
546  * ares_query_completed_cb() is the callback that ares will call when
547  * the host query initiated by ares_gethostbyname() from Curl_getaddrinfo(),
548  * when using ares, is completed either successfully or with failure.
549  */
query_completed_cb(void * arg,int status,int timeouts,struct hostent * hostent)550 static void query_completed_cb(void *arg,  /* (struct connectdata *) */
551                                int status,
552 #ifdef HAVE_CARES_CALLBACK_TIMEOUTS
553                                int timeouts,
554 #endif
555                                struct hostent *hostent)
556 {
557   struct Curl_easy *data = (struct Curl_easy *)arg;
558   struct thread_data *res;
559 
560 #ifdef HAVE_CARES_CALLBACK_TIMEOUTS
561   (void)timeouts; /* ignored */
562 #endif
563 
564   if(ARES_EDESTRUCTION == status)
565     /* when this ares handle is getting destroyed, the 'arg' pointer may not
566        be valid so only defer it when we know the 'status' says its fine! */
567     return;
568 
569   res = data->state.async.tdata;
570   if(res) {
571     res->num_pending--;
572 
573     if(CURL_ASYNC_SUCCESS == status) {
574       struct Curl_addrinfo *ai = Curl_he2ai(hostent, data->state.async.port);
575       if(ai) {
576         compound_results(res, ai);
577       }
578     }
579     /* A successful result overwrites any previous error */
580     if(res->last_status != ARES_SUCCESS)
581       res->last_status = status;
582 
583     /* If there are responses still pending, we presume they must be the
584        complementary IPv4 or IPv6 lookups that we started in parallel in
585        Curl_resolver_getaddrinfo() (for Happy Eyeballs).  If we've got a
586        "definitive" response from one of a set of parallel queries, we need to
587        think about how long we're willing to wait for more responses. */
588     if(res->num_pending
589        /* Only these c-ares status values count as "definitive" for these
590           purposes.  For example, ARES_ENODATA is what we expect when there is
591           no IPv6 entry for a domain name, and that's not a reason to get more
592           aggressive in our timeouts for the other response.  Other errors are
593           either a result of bad input (which should affect all parallel
594           requests), local or network conditions, non-definitive server
595           responses, or us cancelling the request. */
596        && (status == ARES_SUCCESS || status == ARES_ENOTFOUND)) {
597       /* Right now, there can only be up to two parallel queries, so don't
598          bother handling any other cases. */
599       DEBUGASSERT(res->num_pending == 1);
600 
601       /* It's possible that one of these parallel queries could succeed
602          quickly, but the other could always fail or timeout (when we're
603          talking to a pool of DNS servers that can only successfully resolve
604          IPv4 address, for example).
605 
606          It's also possible that the other request could always just take
607          longer because it needs more time or only the second DNS server can
608          fulfill it successfully.  But, to align with the philosophy of Happy
609          Eyeballs, we don't want to wait _too_ long or users will think
610          requests are slow when IPv6 lookups don't actually work (but IPv4 ones
611          do).
612 
613          So, now that we have a usable answer (some IPv4 addresses, some IPv6
614          addresses, or "no such domain"), we start a timeout for the remaining
615          pending responses.  Even though it is typical that this resolved
616          request came back quickly, that needn't be the case.  It might be that
617          this completing request didn't get a result from the first DNS server
618          or even the first round of the whole DNS server pool.  So it could
619          already be quite some time after we issued the DNS queries in the
620          first place.  Without modifying c-ares, we can't know exactly where in
621          its retry cycle we are.  We could guess based on how much time has
622          gone by, but it doesn't really matter.  Happy Eyeballs tells us that,
623          given usable information in hand, we simply don't want to wait "too
624          much longer" after we get a result.
625 
626          We simply wait an additional amount of time equal to the default
627          c-ares query timeout.  That is enough time for a typical parallel
628          response to arrive without being "too long".  Even on a network
629          where one of the two types of queries is failing or timing out
630          constantly, this will usually mean we wait a total of the default
631          c-ares timeout (5 seconds) plus the round trip time for the successful
632          request, which seems bearable.  The downside is that c-ares might race
633          with us to issue one more retry just before we give up, but it seems
634          better to "waste" that request instead of trying to guess the perfect
635          timeout to prevent it.  After all, we don't even know where in the
636          c-ares retry cycle each request is.
637       */
638       res->happy_eyeballs_dns_time = Curl_now();
639       Curl_expire(data, HAPPY_EYEBALLS_DNS_TIMEOUT,
640                   EXPIRE_HAPPY_EYEBALLS_DNS);
641     }
642   }
643 }
644 #else
645 /* c-ares 1.16.0 or later */
646 
647 /*
648  * ares2addr() converts an address list provided by c-ares to an internal
649  * libcurl compatible list
650  */
ares2addr(struct ares_addrinfo_node * node)651 static struct Curl_addrinfo *ares2addr(struct ares_addrinfo_node *node)
652 {
653   /* traverse the ares_addrinfo_node list */
654   struct ares_addrinfo_node *ai;
655   struct Curl_addrinfo *cafirst = NULL;
656   struct Curl_addrinfo *calast = NULL;
657   int error = 0;
658 
659   for(ai = node; ai != NULL; ai = ai->ai_next) {
660     size_t ss_size;
661     struct Curl_addrinfo *ca;
662     /* ignore elements with unsupported address family, */
663     /* settle family-specific sockaddr structure size.  */
664     if(ai->ai_family == AF_INET)
665       ss_size = sizeof(struct sockaddr_in);
666 #ifdef ENABLE_IPV6
667     else if(ai->ai_family == AF_INET6)
668       ss_size = sizeof(struct sockaddr_in6);
669 #endif
670     else
671       continue;
672 
673     /* ignore elements without required address info */
674     if(!ai->ai_addr || !(ai->ai_addrlen > 0))
675       continue;
676 
677     /* ignore elements with bogus address size */
678     if((size_t)ai->ai_addrlen < ss_size)
679       continue;
680 
681     ca = malloc(sizeof(struct Curl_addrinfo) + ss_size);
682     if(!ca) {
683       error = EAI_MEMORY;
684       break;
685     }
686 
687     /* copy each structure member individually, member ordering, */
688     /* size, or padding might be different for each platform.    */
689 
690     ca->ai_flags     = ai->ai_flags;
691     ca->ai_family    = ai->ai_family;
692     ca->ai_socktype  = ai->ai_socktype;
693     ca->ai_protocol  = ai->ai_protocol;
694     ca->ai_addrlen   = (curl_socklen_t)ss_size;
695     ca->ai_addr      = NULL;
696     ca->ai_canonname = NULL;
697     ca->ai_next      = NULL;
698 
699     ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo));
700     memcpy(ca->ai_addr, ai->ai_addr, ss_size);
701 
702     /* if the return list is empty, this becomes the first element */
703     if(!cafirst)
704       cafirst = ca;
705 
706     /* add this element last in the return list */
707     if(calast)
708       calast->ai_next = ca;
709     calast = ca;
710   }
711 
712   /* if we failed, destroy the Curl_addrinfo list */
713   if(error) {
714     Curl_freeaddrinfo(cafirst);
715     cafirst = NULL;
716   }
717 
718   return cafirst;
719 }
720 
addrinfo_cb(void * arg,int status,int timeouts,struct ares_addrinfo * result)721 static void addrinfo_cb(void *arg, int status, int timeouts,
722                         struct ares_addrinfo *result)
723 {
724   struct Curl_easy *data = (struct Curl_easy *)arg;
725   struct thread_data *res = data->state.async.tdata;
726   (void)timeouts;
727   if(ARES_SUCCESS == status) {
728     res->temp_ai = ares2addr(result->nodes);
729     res->last_status = CURL_ASYNC_SUCCESS;
730     ares_freeaddrinfo(result);
731   }
732   res->num_pending--;
733 }
734 
735 #endif
736 /*
737  * Curl_resolver_getaddrinfo() - when using ares
738  *
739  * Returns name information about the given hostname and port number. If
740  * successful, the 'hostent' is returned and the forth argument will point to
741  * memory we need to free after use. That memory *MUST* be freed with
742  * Curl_freeaddrinfo(), nothing else.
743  */
Curl_resolver_getaddrinfo(struct Curl_easy * data,const char * hostname,int port,int * waitp)744 struct Curl_addrinfo *Curl_resolver_getaddrinfo(struct Curl_easy *data,
745                                                 const char *hostname,
746                                                 int port,
747                                                 int *waitp)
748 {
749   char *bufp;
750 
751   *waitp = 0; /* default to synchronous response */
752 
753   bufp = strdup(hostname);
754   if(bufp) {
755     struct thread_data *res = NULL;
756     free(data->state.async.hostname);
757     data->state.async.hostname = bufp;
758     data->state.async.port = port;
759     data->state.async.done = FALSE;   /* not done */
760     data->state.async.status = 0;     /* clear */
761     data->state.async.dns = NULL;     /* clear */
762     res = calloc(sizeof(struct thread_data), 1);
763     if(!res) {
764       free(data->state.async.hostname);
765       data->state.async.hostname = NULL;
766       return NULL;
767     }
768     data->state.async.tdata = res;
769 
770     /* initial status - failed */
771     res->last_status = ARES_ENOTFOUND;
772 
773 #ifdef HAVE_CARES_GETADDRINFO
774     {
775       struct ares_addrinfo_hints hints;
776       char service[12];
777       int pf = PF_INET;
778       memset(&hints, 0, sizeof(hints));
779 #ifdef CURLRES_IPV6
780       if(Curl_ipv6works(data))
781         /* The stack seems to be IPv6-enabled */
782         pf = PF_UNSPEC;
783 #endif /* CURLRES_IPV6 */
784       hints.ai_family = pf;
785       hints.ai_socktype = (data->conn->transport == TRNSPRT_TCP)?
786         SOCK_STREAM : SOCK_DGRAM;
787       msnprintf(service, sizeof(service), "%d", port);
788       res->num_pending = 1;
789       ares_getaddrinfo((ares_channel)data->state.async.resolver, hostname,
790                        service, &hints, addrinfo_cb, data);
791     }
792 #else
793 
794 #ifdef HAVE_CARES_IPV6
795     if(Curl_ipv6works(data)) {
796       /* The stack seems to be IPv6-enabled */
797       res->num_pending = 2;
798 
799       /* areschannel is already setup in the Curl_open() function */
800       ares_gethostbyname((ares_channel)data->state.async.resolver, hostname,
801                           PF_INET, query_completed_cb, data);
802       ares_gethostbyname((ares_channel)data->state.async.resolver, hostname,
803                           PF_INET6, query_completed_cb, data);
804     }
805     else
806 #endif
807     {
808       res->num_pending = 1;
809 
810       /* areschannel is already setup in the Curl_open() function */
811       ares_gethostbyname((ares_channel)data->state.async.resolver,
812                          hostname, PF_INET,
813                          query_completed_cb, data);
814     }
815 #endif
816     *waitp = 1; /* expect asynchronous response */
817   }
818   return NULL; /* no struct yet */
819 }
820 
Curl_set_dns_servers(struct Curl_easy * data,char * servers)821 CURLcode Curl_set_dns_servers(struct Curl_easy *data,
822                               char *servers)
823 {
824   CURLcode result = CURLE_NOT_BUILT_IN;
825   int ares_result;
826 
827   /* If server is NULL or empty, this would purge all DNS servers
828    * from ares library, which will cause any and all queries to fail.
829    * So, just return OK if none are configured and don't actually make
830    * any changes to c-ares.  This lets c-ares use it's defaults, which
831    * it gets from the OS (for instance from /etc/resolv.conf on Linux).
832    */
833   if(!(servers && servers[0]))
834     return CURLE_OK;
835 
836 #ifdef HAVE_CARES_SERVERS_CSV
837 #ifdef HAVE_CARES_PORTS_CSV
838   ares_result = ares_set_servers_ports_csv(data->state.async.resolver,
839                                            servers);
840 #else
841   ares_result = ares_set_servers_csv(data->state.async.resolver, servers);
842 #endif
843   switch(ares_result) {
844   case ARES_SUCCESS:
845     result = CURLE_OK;
846     break;
847   case ARES_ENOMEM:
848     result = CURLE_OUT_OF_MEMORY;
849     break;
850   case ARES_ENOTINITIALIZED:
851   case ARES_ENODATA:
852   case ARES_EBADSTR:
853   default:
854     result = CURLE_BAD_FUNCTION_ARGUMENT;
855     break;
856   }
857 #else /* too old c-ares version! */
858   (void)data;
859   (void)(ares_result);
860 #endif
861   return result;
862 }
863 
Curl_set_dns_interface(struct Curl_easy * data,const char * interf)864 CURLcode Curl_set_dns_interface(struct Curl_easy *data,
865                                 const char *interf)
866 {
867 #ifdef HAVE_CARES_LOCAL_DEV
868   if(!interf)
869     interf = "";
870 
871   ares_set_local_dev((ares_channel)data->state.async.resolver, interf);
872 
873   return CURLE_OK;
874 #else /* c-ares version too old! */
875   (void)data;
876   (void)interf;
877   return CURLE_NOT_BUILT_IN;
878 #endif
879 }
880 
Curl_set_dns_local_ip4(struct Curl_easy * data,const char * local_ip4)881 CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data,
882                                 const char *local_ip4)
883 {
884 #ifdef HAVE_CARES_SET_LOCAL
885   struct in_addr a4;
886 
887   if((!local_ip4) || (local_ip4[0] == 0)) {
888     a4.s_addr = 0; /* disabled: do not bind to a specific address */
889   }
890   else {
891     if(Curl_inet_pton(AF_INET, local_ip4, &a4) != 1) {
892       return CURLE_BAD_FUNCTION_ARGUMENT;
893     }
894   }
895 
896   ares_set_local_ip4((ares_channel)data->state.async.resolver,
897                      ntohl(a4.s_addr));
898 
899   return CURLE_OK;
900 #else /* c-ares version too old! */
901   (void)data;
902   (void)local_ip4;
903   return CURLE_NOT_BUILT_IN;
904 #endif
905 }
906 
Curl_set_dns_local_ip6(struct Curl_easy * data,const char * local_ip6)907 CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data,
908                                 const char *local_ip6)
909 {
910 #if defined(HAVE_CARES_SET_LOCAL) && defined(ENABLE_IPV6)
911   unsigned char a6[INET6_ADDRSTRLEN];
912 
913   if((!local_ip6) || (local_ip6[0] == 0)) {
914     /* disabled: do not bind to a specific address */
915     memset(a6, 0, sizeof(a6));
916   }
917   else {
918     if(Curl_inet_pton(AF_INET6, local_ip6, a6) != 1) {
919       return CURLE_BAD_FUNCTION_ARGUMENT;
920     }
921   }
922 
923   ares_set_local_ip6((ares_channel)data->state.async.resolver, a6);
924 
925   return CURLE_OK;
926 #else /* c-ares version too old! */
927   (void)data;
928   (void)local_ip6;
929   return CURLE_NOT_BUILT_IN;
930 #endif
931 }
932 #endif /* CURLRES_ARES */
933