asyn-ares.c 28 KB

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