2
0

asyn-ares.c 28 KB

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