asyn-ares.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 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. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #ifdef CURLRES_ARES
  26. /***********************************************************************
  27. * Only for ares-enabled builds
  28. * And only for functions that fulfill the asynch resolver backend API
  29. * as defined in asyn.h, nothing else belongs in this file!
  30. **********************************************************************/
  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. #include "urldata.h"
  46. #include "cfilters.h"
  47. #include "sendf.h"
  48. #include "hostip.h"
  49. #include "hash.h"
  50. #include "share.h"
  51. #include "url.h"
  52. #include "multiif.h"
  53. #include "curlx/inet_pton.h"
  54. #include "connect.h"
  55. #include "select.h"
  56. #include "progress.h"
  57. #include "curlx/timediff.h"
  58. #include "httpsrr.h"
  59. #include "strdup.h"
  60. #include <ares.h>
  61. #include <ares_version.h> /* really old c-ares did not include this by
  62. itself */
  63. #if ARES_VERSION >= 0x010601
  64. /* IPv6 supported since 1.6.1 */
  65. #define HAVE_CARES_IPV6 1
  66. #endif
  67. #if ARES_VERSION >= 0x010704
  68. #define HAVE_CARES_SERVERS_CSV 1
  69. #define HAVE_CARES_LOCAL_DEV 1
  70. #define HAVE_CARES_SET_LOCAL 1
  71. #endif
  72. #if ARES_VERSION >= 0x010b00
  73. #define HAVE_CARES_PORTS_CSV 1
  74. #endif
  75. #if ARES_VERSION >= 0x011000
  76. /* 1.16.0 or later has ares_getaddrinfo */
  77. #define HAVE_CARES_GETADDRINFO 1
  78. #endif
  79. #ifdef USE_HTTPSRR
  80. #if ARES_VERSION < 0x011c00
  81. #error "requires c-ares 1.28.0 or newer for HTTPSRR"
  82. #endif
  83. #define HTTPSRR_WORKS
  84. #endif
  85. /* The last 3 #include files should be in this order */
  86. #include "curl_printf.h"
  87. #include "curl_memory.h"
  88. #include "memdebug.h"
  89. /* How long we are willing to wait for additional parallel responses after
  90. obtaining a "definitive" one. For old c-ares without getaddrinfo.
  91. This is intended to equal the c-ares default timeout. cURL always uses that
  92. default value. Unfortunately, c-ares does not expose its default timeout in
  93. its API, but it is officially documented as 5 seconds.
  94. See query_completed_cb() for an explanation of how this is used.
  95. */
  96. #define HAPPY_EYEBALLS_DNS_TIMEOUT 5000
  97. #define CARES_TIMEOUT_PER_ATTEMPT 2000
  98. static int ares_ver = 0;
  99. static CURLcode async_ares_set_dns_servers(struct Curl_easy *data,
  100. bool reset_on_null);
  101. /*
  102. * Curl_async_global_init() - the generic low-level asynchronous name
  103. * resolve API. Called from curl_global_init() to initialize global resolver
  104. * environment. Initializes ares library.
  105. */
  106. int Curl_async_global_init(void)
  107. {
  108. #ifdef CARES_HAVE_ARES_LIBRARY_INIT
  109. if(ares_library_init(ARES_LIB_INIT_ALL)) {
  110. return CURLE_FAILED_INIT;
  111. }
  112. #endif
  113. ares_version(&ares_ver);
  114. return CURLE_OK;
  115. }
  116. /*
  117. * Curl_async_global_cleanup()
  118. *
  119. * Called from curl_global_cleanup() to destroy global resolver environment.
  120. * Deinitializes ares library.
  121. */
  122. void Curl_async_global_cleanup(void)
  123. {
  124. #ifdef CARES_HAVE_ARES_LIBRARY_CLEANUP
  125. ares_library_cleanup();
  126. #endif
  127. }
  128. static void sock_state_cb(void *data, ares_socket_t socket_fd,
  129. int readable, int writable)
  130. {
  131. struct Curl_easy *easy = data;
  132. if(!readable && !writable) {
  133. DEBUGASSERT(easy);
  134. Curl_multi_will_close(easy, socket_fd);
  135. }
  136. }
  137. static CURLcode async_ares_init(struct Curl_easy *data)
  138. {
  139. struct async_ares_ctx *ares = &data->state.async.ares;
  140. int status;
  141. struct ares_options options;
  142. int optmask = ARES_OPT_SOCK_STATE_CB;
  143. CURLcode rc = CURLE_OK;
  144. options.sock_state_cb = sock_state_cb;
  145. options.sock_state_cb_data = data;
  146. DEBUGASSERT(!ares->channel);
  147. /*
  148. if c ares < 1.20.0: curl set timeout to CARES_TIMEOUT_PER_ATTEMPT (2s)
  149. if c-ares >= 1.20.0 it already has the timeout to 2s, curl does not need
  150. to set the timeout value;
  151. if c-ares >= 1.24.0, user can set the timeout via /etc/resolv.conf to
  152. overwrite c-ares' timeout.
  153. */
  154. DEBUGASSERT(ares_ver);
  155. if(ares_ver < 0x011400) {
  156. options.timeout = CARES_TIMEOUT_PER_ATTEMPT;
  157. optmask |= ARES_OPT_TIMEOUTMS;
  158. }
  159. status = ares_init_options(&ares->channel, &options, optmask);
  160. if(status != ARES_SUCCESS) {
  161. ares->channel = NULL;
  162. rc = (status == ARES_ENOMEM) ?
  163. CURLE_OUT_OF_MEMORY : CURLE_FAILED_INIT;
  164. goto out;
  165. }
  166. rc = async_ares_set_dns_servers(data, FALSE);
  167. if(rc && rc != CURLE_NOT_BUILT_IN)
  168. goto out;
  169. rc = Curl_async_ares_set_dns_interface(data);
  170. if(rc && rc != CURLE_NOT_BUILT_IN)
  171. goto out;
  172. rc = Curl_async_ares_set_dns_local_ip4(data);
  173. if(rc && rc != CURLE_NOT_BUILT_IN)
  174. goto out;
  175. rc = Curl_async_ares_set_dns_local_ip6(data);
  176. if(rc && rc != CURLE_NOT_BUILT_IN)
  177. goto out;
  178. rc = CURLE_OK;
  179. out:
  180. if(rc && ares->channel) {
  181. ares_destroy(ares->channel);
  182. ares->channel = NULL;
  183. }
  184. return rc;
  185. }
  186. static CURLcode async_ares_init_lazy(struct Curl_easy *data)
  187. {
  188. struct async_ares_ctx *ares = &data->state.async.ares;
  189. if(!ares->channel)
  190. return async_ares_init(data);
  191. return CURLE_OK;
  192. }
  193. CURLcode Curl_async_get_impl(struct Curl_easy *data, void **impl)
  194. {
  195. struct async_ares_ctx *ares = &data->state.async.ares;
  196. CURLcode result = CURLE_OK;
  197. if(!ares->channel) {
  198. result = async_ares_init(data);
  199. }
  200. *impl = ares->channel;
  201. return result;
  202. }
  203. static void async_ares_cleanup(struct Curl_easy *data);
  204. void Curl_async_ares_shutdown(struct Curl_easy *data)
  205. {
  206. struct async_ares_ctx *ares = &data->state.async.ares;
  207. if(ares->channel)
  208. ares_cancel(ares->channel);
  209. async_ares_cleanup(data);
  210. }
  211. void Curl_async_ares_destroy(struct Curl_easy *data)
  212. {
  213. struct async_ares_ctx *ares = &data->state.async.ares;
  214. Curl_async_ares_shutdown(data);
  215. if(ares->channel) {
  216. ares_destroy(ares->channel);
  217. ares->channel = NULL;
  218. }
  219. }
  220. /*
  221. * async_ares_cleanup() cleans up async resolver data.
  222. */
  223. static void async_ares_cleanup(struct Curl_easy *data)
  224. {
  225. struct async_ares_ctx *ares = &data->state.async.ares;
  226. if(ares->temp_ai) {
  227. Curl_freeaddrinfo(ares->temp_ai);
  228. ares->temp_ai = NULL;
  229. }
  230. #ifdef USE_HTTPSRR
  231. Curl_httpsrr_cleanup(&ares->hinfo);
  232. #endif
  233. }
  234. /*
  235. * Curl_async_getsock() is called when someone from the outside world
  236. * (using curl_multi_fdset()) wants to get our fd_set setup.
  237. */
  238. int Curl_async_getsock(struct Curl_easy *data, curl_socket_t *socks)
  239. {
  240. struct async_ares_ctx *ares = &data->state.async.ares;
  241. DEBUGASSERT(ares->channel);
  242. return Curl_ares_getsock(data, ares->channel, socks);
  243. }
  244. /*
  245. * Curl_async_is_resolved() is called repeatedly to check if a previous
  246. * name resolve request has completed. It should also make sure to time-out if
  247. * the operation seems to take too long.
  248. *
  249. * Returns normal CURLcode errors.
  250. */
  251. CURLcode Curl_async_is_resolved(struct Curl_easy *data,
  252. struct Curl_dns_entry **dns)
  253. {
  254. struct async_ares_ctx *ares = &data->state.async.ares;
  255. CURLcode result = CURLE_OK;
  256. DEBUGASSERT(dns);
  257. *dns = NULL;
  258. if(data->state.async.done) {
  259. *dns = data->state.async.dns;
  260. return CURLE_OK;
  261. }
  262. if(Curl_ares_perform(ares->channel, 0) < 0)
  263. return CURLE_UNRECOVERABLE_POLL;
  264. #ifndef HAVE_CARES_GETADDRINFO
  265. /* Now that we have checked for any last minute results above, see if there
  266. are any responses still pending when the EXPIRE_HAPPY_EYEBALLS_DNS timer
  267. expires. */
  268. if(ares->num_pending
  269. /* This is only set to non-zero if the timer was started. */
  270. && (ares->happy_eyeballs_dns_time.tv_sec
  271. || ares->happy_eyeballs_dns_time.tv_usec)
  272. && (curlx_timediff(curlx_now(), ares->happy_eyeballs_dns_time)
  273. >= HAPPY_EYEBALLS_DNS_TIMEOUT)) {
  274. /* Remember that the EXPIRE_HAPPY_EYEBALLS_DNS timer is no longer
  275. running. */
  276. memset(&ares->happy_eyeballs_dns_time, 0,
  277. sizeof(ares->happy_eyeballs_dns_time));
  278. /* Cancel the raw c-ares request, which will fire query_completed_cb() with
  279. ARES_ECANCELLED synchronously for all pending responses. This will
  280. leave us with res->num_pending == 0, which is perfect for the next
  281. block. */
  282. ares_cancel(ares->channel);
  283. DEBUGASSERT(ares->num_pending == 0);
  284. }
  285. #endif
  286. if(!ares->num_pending) {
  287. /* all c-ares operations done, what is the result to report? */
  288. Curl_resolv_unlink(data, &data->state.async.dns);
  289. data->state.async.done = TRUE;
  290. result = ares->result;
  291. if(ares->last_status == CURL_ASYNC_SUCCESS && !result) {
  292. data->state.async.dns =
  293. Curl_dnscache_mk_entry(data, ares->temp_ai,
  294. data->state.async.hostname, 0,
  295. data->state.async.port, FALSE);
  296. ares->temp_ai = NULL; /* temp_ai now owned by entry */
  297. #ifdef HTTPSRR_WORKS
  298. if(data->state.async.dns) {
  299. struct Curl_https_rrinfo *lhrr = Curl_httpsrr_dup_move(&ares->hinfo);
  300. if(!lhrr)
  301. result = CURLE_OUT_OF_MEMORY;
  302. else
  303. data->state.async.dns->hinfo = lhrr;
  304. }
  305. #endif
  306. if(!result && data->state.async.dns)
  307. result = Curl_dnscache_add(data, data->state.async.dns);
  308. }
  309. /* if we have not found anything, report the proper
  310. * CURLE_COULDNT_RESOLVE_* code */
  311. if(!result && !data->state.async.dns)
  312. result = Curl_resolver_error(data);
  313. if(result)
  314. Curl_resolv_unlink(data, &data->state.async.dns);
  315. *dns = data->state.async.dns;
  316. CURL_TRC_DNS(data, "is_resolved() result=%d, dns=%sfound",
  317. result, *dns ? "" : "not ");
  318. async_ares_cleanup(data);
  319. }
  320. return result;
  321. }
  322. /*
  323. * Curl_async_await()
  324. *
  325. * Waits for a resolve to finish. This function should be avoided since using
  326. * this risk getting the multi interface to "hang".
  327. *
  328. * 'entry' MUST be non-NULL.
  329. *
  330. * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved,
  331. * CURLE_OPERATION_TIMEDOUT if a time-out occurred, or other errors.
  332. */
  333. CURLcode Curl_async_await(struct Curl_easy *data,
  334. struct Curl_dns_entry **entry)
  335. {
  336. struct async_ares_ctx *ares = &data->state.async.ares;
  337. CURLcode result = CURLE_OK;
  338. timediff_t timeout;
  339. struct curltime now = curlx_now();
  340. DEBUGASSERT(entry);
  341. *entry = NULL; /* clear on entry */
  342. timeout = Curl_timeleft(data, &now, TRUE);
  343. if(timeout < 0) {
  344. /* already expired! */
  345. connclose(data->conn, "Timed out before name resolve started");
  346. return CURLE_OPERATION_TIMEDOUT;
  347. }
  348. if(!timeout)
  349. timeout = CURL_TIMEOUT_RESOLVE * 1000; /* default name resolve timeout */
  350. /* Wait for the name resolve query to complete. */
  351. while(!result) {
  352. struct timeval *tvp, tv, store;
  353. int itimeout;
  354. timediff_t timeout_ms;
  355. #if TIMEDIFF_T_MAX > INT_MAX
  356. itimeout = (timeout > INT_MAX) ? INT_MAX : (int)timeout;
  357. #else
  358. itimeout = (int)timeout;
  359. #endif
  360. store.tv_sec = itimeout/1000;
  361. store.tv_usec = (itimeout%1000)*1000;
  362. tvp = ares_timeout(ares->channel, &store, &tv);
  363. /* use the timeout period ares returned to us above if less than one
  364. second is left, otherwise just use 1000ms to make sure the progress
  365. callback gets called frequent enough */
  366. if(!tvp->tv_sec)
  367. timeout_ms = (timediff_t)(tvp->tv_usec/1000);
  368. else
  369. timeout_ms = 1000;
  370. if(Curl_ares_perform(ares->channel, timeout_ms) < 0)
  371. return CURLE_UNRECOVERABLE_POLL;
  372. result = Curl_async_is_resolved(data, entry);
  373. if(result || data->state.async.done)
  374. break;
  375. if(Curl_pgrsUpdate(data))
  376. result = CURLE_ABORTED_BY_CALLBACK;
  377. else {
  378. struct curltime now2 = curlx_now();
  379. timediff_t timediff = curlx_timediff(now2, now); /* spent time */
  380. if(timediff <= 0)
  381. timeout -= 1; /* always deduct at least 1 */
  382. else if(timediff > timeout)
  383. timeout = -1;
  384. else
  385. timeout -= timediff;
  386. now = now2; /* for next loop */
  387. }
  388. if(timeout < 0)
  389. result = CURLE_OPERATION_TIMEDOUT;
  390. }
  391. /* Operation complete, if the lookup was successful we now have the entry
  392. in the cache. */
  393. data->state.async.done = TRUE;
  394. *entry = data->state.async.dns;
  395. if(result)
  396. ares_cancel(ares->channel);
  397. return result;
  398. }
  399. #ifndef HAVE_CARES_GETADDRINFO
  400. /* Connects results to the list */
  401. static void async_addr_concat(struct Curl_addrinfo **pbase,
  402. struct Curl_addrinfo *ai)
  403. {
  404. if(!ai)
  405. return;
  406. /* When adding `ai` to an existing address list, we prefer ipv6
  407. * to be in front. */
  408. #ifdef USE_IPV6 /* CURLRES_IPV6 */
  409. if(*pbase && (*pbase)->ai_family == PF_INET6) {
  410. /* ipv6 already in front, append `ai` */
  411. struct Curl_addrinfo *tail = *pbase;
  412. while(tail->ai_next)
  413. tail = tail->ai_next;
  414. tail->ai_next = ai;
  415. }
  416. else
  417. #endif /* CURLRES_IPV6 */
  418. {
  419. /* prepend to the (possibly) existing list. */
  420. struct Curl_addrinfo *tail = ai;
  421. while(tail->ai_next)
  422. tail = tail->ai_next;
  423. tail->ai_next = *pbase;
  424. *pbase = ai;
  425. }
  426. }
  427. /*
  428. * ares_query_completed_cb() is the callback that ares will call when
  429. * the host query initiated by ares_gethostbyname() from
  430. * Curl_async_getaddrinfo(), when using ares, is completed either
  431. * successfully or with failure.
  432. */
  433. static void async_ares_hostbyname_cb(void *user_data,
  434. int status,
  435. int timeouts,
  436. struct hostent *hostent)
  437. {
  438. struct Curl_easy *data = (struct Curl_easy *)user_data;
  439. struct async_ares_ctx *ares = &data->state.async.ares;
  440. (void)timeouts; /* ignored */
  441. if(ARES_EDESTRUCTION == status)
  442. /* when this ares handle is getting destroyed, the 'arg' pointer may not
  443. be valid so only defer it when we know the 'status' says its fine! */
  444. return;
  445. if(CURL_ASYNC_SUCCESS == status) {
  446. ares->last_status = status; /* one success overrules any error */
  447. async_addr_concat(&ares->temp_ai,
  448. Curl_he2ai(hostent, data->state.async.port));
  449. }
  450. else if(ares->last_status != ARES_SUCCESS) {
  451. /* no success so far, remember error */
  452. ares->last_status = status;
  453. }
  454. ares->num_pending--;
  455. CURL_TRC_DNS(data, "ares: hostbyname done, status=%d, pending=%d, "
  456. "addr=%sfound",
  457. status, ares->num_pending, ares->temp_ai ? "" : "not ");
  458. /* If there are responses still pending, we presume they must be the
  459. complementary IPv4 or IPv6 lookups that we started in parallel in
  460. Curl_async_getaddrinfo() (for Happy Eyeballs). If we have got a
  461. "definitive" response from one of a set of parallel queries, we need to
  462. think about how long we are willing to wait for more responses. */
  463. if(ares->num_pending
  464. /* Only these c-ares status values count as "definitive" for these
  465. purposes. For example, ARES_ENODATA is what we expect when there is
  466. no IPv6 entry for a domain name, and that is not a reason to get more
  467. aggressive in our timeouts for the other response. Other errors are
  468. either a result of bad input (which should affect all parallel
  469. requests), local or network conditions, non-definitive server
  470. responses, or us cancelling the request. */
  471. && (status == ARES_SUCCESS || status == ARES_ENOTFOUND)) {
  472. /* Right now, there can only be up to two parallel queries, so do not
  473. bother handling any other cases. */
  474. DEBUGASSERT(ares->num_pending == 1);
  475. /* it is possible that one of these parallel queries could succeed
  476. quickly, but the other could always fail or timeout (when we are
  477. talking to a pool of DNS servers that can only successfully resolve
  478. IPv4 address, for example).
  479. it is also possible that the other request could always just take
  480. longer because it needs more time or only the second DNS server can
  481. fulfill it successfully. But, to align with the philosophy of Happy
  482. Eyeballs, we do not want to wait _too_ long or users will think
  483. requests are slow when IPv6 lookups do not actually work (but IPv4
  484. ones do).
  485. So, now that we have a usable answer (some IPv4 addresses, some IPv6
  486. addresses, or "no such domain"), we start a timeout for the remaining
  487. pending responses. Even though it is typical that this resolved
  488. request came back quickly, that needn't be the case. It might be that
  489. this completing request did not get a result from the first DNS
  490. server or even the first round of the whole DNS server pool. So it
  491. could already be quite some time after we issued the DNS queries in
  492. the first place. Without modifying c-ares, we cannot know exactly
  493. where in its retry cycle we are. We could guess based on how much
  494. time has gone by, but it does not really matter. Happy Eyeballs tells
  495. us that, given usable information in hand, we simply do not want to
  496. wait "too much longer" after we get a result.
  497. We simply wait an additional amount of time equal to the default
  498. c-ares query timeout. That is enough time for a typical parallel
  499. response to arrive without being "too long". Even on a network
  500. where one of the two types of queries is failing or timing out
  501. constantly, this will usually mean we wait a total of the default
  502. c-ares timeout (5 seconds) plus the round trip time for the successful
  503. request, which seems bearable. The downside is that c-ares might race
  504. with us to issue one more retry just before we give up, but it seems
  505. better to "waste" that request instead of trying to guess the perfect
  506. timeout to prevent it. After all, we do not even know where in the
  507. c-ares retry cycle each request is.
  508. */
  509. ares->happy_eyeballs_dns_time = curlx_now();
  510. Curl_expire(data, HAPPY_EYEBALLS_DNS_TIMEOUT,
  511. EXPIRE_HAPPY_EYEBALLS_DNS);
  512. }
  513. }
  514. #else
  515. /* c-ares 1.16.0 or later */
  516. /*
  517. * async_ares_node2addr() converts an address list provided by c-ares
  518. * to an internal libcurl compatible list.
  519. */
  520. static struct Curl_addrinfo *
  521. async_ares_node2addr(struct ares_addrinfo_node *node)
  522. {
  523. /* traverse the ares_addrinfo_node list */
  524. struct ares_addrinfo_node *ai;
  525. struct Curl_addrinfo *cafirst = NULL;
  526. struct Curl_addrinfo *calast = NULL;
  527. int error = 0;
  528. for(ai = node; ai != NULL; ai = ai->ai_next) {
  529. size_t ss_size;
  530. struct Curl_addrinfo *ca;
  531. /* ignore elements with unsupported address family, */
  532. /* settle family-specific sockaddr structure size. */
  533. if(ai->ai_family == AF_INET)
  534. ss_size = sizeof(struct sockaddr_in);
  535. #ifdef USE_IPV6
  536. else if(ai->ai_family == AF_INET6)
  537. ss_size = sizeof(struct sockaddr_in6);
  538. #endif
  539. else
  540. continue;
  541. /* ignore elements without required address info */
  542. if(!ai->ai_addr || !(ai->ai_addrlen > 0))
  543. continue;
  544. /* ignore elements with bogus address size */
  545. if((size_t)ai->ai_addrlen < ss_size)
  546. continue;
  547. ca = malloc(sizeof(struct Curl_addrinfo) + ss_size);
  548. if(!ca) {
  549. error = EAI_MEMORY;
  550. break;
  551. }
  552. /* copy each structure member individually, member ordering, */
  553. /* size, or padding might be different for each platform. */
  554. ca->ai_flags = ai->ai_flags;
  555. ca->ai_family = ai->ai_family;
  556. ca->ai_socktype = ai->ai_socktype;
  557. ca->ai_protocol = ai->ai_protocol;
  558. ca->ai_addrlen = (curl_socklen_t)ss_size;
  559. ca->ai_addr = NULL;
  560. ca->ai_canonname = NULL;
  561. ca->ai_next = NULL;
  562. ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo));
  563. memcpy(ca->ai_addr, ai->ai_addr, ss_size);
  564. /* if the return list is empty, this becomes the first element */
  565. if(!cafirst)
  566. cafirst = ca;
  567. /* add this element last in the return list */
  568. if(calast)
  569. calast->ai_next = ca;
  570. calast = ca;
  571. }
  572. /* if we failed, destroy the Curl_addrinfo list */
  573. if(error) {
  574. Curl_freeaddrinfo(cafirst);
  575. cafirst = NULL;
  576. }
  577. return cafirst;
  578. }
  579. static void async_ares_addrinfo_cb(void *user_data, int status, int timeouts,
  580. struct ares_addrinfo *result)
  581. {
  582. struct Curl_easy *data = (struct Curl_easy *)user_data;
  583. struct async_ares_ctx *ares = &data->state.async.ares;
  584. (void)timeouts;
  585. CURL_TRC_DNS(data, "asyn-ares: addrinfo callback, status=%d", status);
  586. if(ARES_SUCCESS == status) {
  587. ares->temp_ai = async_ares_node2addr(result->nodes);
  588. ares->last_status = CURL_ASYNC_SUCCESS;
  589. ares_freeaddrinfo(result);
  590. }
  591. ares->num_pending--;
  592. CURL_TRC_DNS(data, "ares: addrinfo done, status=%d, pending=%d, "
  593. "addr=%sfound",
  594. status, ares->num_pending, ares->temp_ai ? "" : "not ");
  595. }
  596. #endif
  597. #ifdef USE_HTTPSRR
  598. static void async_ares_rr_done(void *user_data, ares_status_t status,
  599. size_t timeouts,
  600. const ares_dns_record_t *dnsrec)
  601. {
  602. struct Curl_easy *data = user_data;
  603. struct async_ares_ctx *ares = &data->state.async.ares;
  604. (void)timeouts;
  605. --ares->num_pending;
  606. CURL_TRC_DNS(data, "ares: httpsrr done, status=%d, pending=%d, "
  607. "dnsres=%sfound",
  608. status, ares->num_pending,
  609. (dnsrec &&
  610. ares_dns_record_rr_cnt(dnsrec, ARES_SECTION_ANSWER)) ?
  611. "" : "not ");
  612. if((ARES_SUCCESS != status) || !dnsrec)
  613. return;
  614. ares->result = Curl_httpsrr_from_ares(data, dnsrec, &ares->hinfo);
  615. }
  616. #endif /* USE_HTTPSRR */
  617. /*
  618. * Curl_async_getaddrinfo() - when using ares
  619. *
  620. * Returns name information about the given hostname and port number. If
  621. * successful, the 'hostent' is returned and the fourth argument will point to
  622. * memory we need to free after use. That memory *MUST* be freed with
  623. * Curl_freeaddrinfo(), nothing else.
  624. */
  625. struct Curl_addrinfo *Curl_async_getaddrinfo(struct Curl_easy *data,
  626. const char *hostname,
  627. int port,
  628. int ip_version,
  629. int *waitp)
  630. {
  631. struct async_ares_ctx *ares = &data->state.async.ares;
  632. *waitp = 0; /* default to synchronous response */
  633. if(async_ares_init_lazy(data))
  634. return NULL;
  635. data->state.async.done = FALSE; /* not done */
  636. data->state.async.dns = NULL; /* clear */
  637. data->state.async.port = port;
  638. data->state.async.ip_version = ip_version;
  639. data->state.async.hostname = strdup(hostname);
  640. if(!data->state.async.hostname)
  641. return NULL;
  642. /* initial status - failed */
  643. ares->last_status = ARES_ENOTFOUND;
  644. #ifdef HAVE_CARES_GETADDRINFO
  645. {
  646. struct ares_addrinfo_hints hints;
  647. char service[12];
  648. int pf = PF_INET;
  649. memset(&hints, 0, sizeof(hints));
  650. #ifdef CURLRES_IPV6
  651. if((ip_version != CURL_IPRESOLVE_V4) &&
  652. Curl_ipv6works(data)) {
  653. /* The stack seems to be IPv6-enabled */
  654. if(ip_version == CURL_IPRESOLVE_V6)
  655. pf = PF_INET6;
  656. else
  657. pf = PF_UNSPEC;
  658. }
  659. #endif /* CURLRES_IPV6 */
  660. CURL_TRC_DNS(data, "asyn-ares: fire off getaddrinfo for %s",
  661. (pf == PF_UNSPEC) ? "A+AAAA" :
  662. ((pf == PF_INET) ? "A" : "AAAA"));
  663. hints.ai_family = pf;
  664. hints.ai_socktype =
  665. (Curl_conn_get_transport(data, data->conn) == TRNSPRT_TCP) ?
  666. SOCK_STREAM : SOCK_DGRAM;
  667. /* Since the service is a numerical one, set the hint flags
  668. * accordingly to save a call to getservbyname in inside C-Ares
  669. */
  670. hints.ai_flags = ARES_AI_NUMERICSERV;
  671. msnprintf(service, sizeof(service), "%d", port);
  672. ares->num_pending = 1;
  673. ares_getaddrinfo(ares->channel, data->state.async.hostname,
  674. service, &hints, async_ares_addrinfo_cb, data);
  675. }
  676. #else
  677. #ifdef HAVE_CARES_IPV6
  678. if((ip_version != CURL_IPRESOLVE_V4) && Curl_ipv6works(data)) {
  679. /* The stack seems to be IPv6-enabled */
  680. /* areschannel is already setup in the Curl_open() function */
  681. CURL_TRC_DNS(data, "asyn-ares: fire off query for A");
  682. ares_gethostbyname(ares->channel, hostname, PF_INET,
  683. async_ares_hostbyname_cb, data);
  684. CURL_TRC_DNS(data, "asyn-ares: fire off query for AAAA");
  685. ares->num_pending = 2;
  686. ares_gethostbyname(ares->channel, data->state.async.hostname, PF_INET6,
  687. async_ares_hostbyname_cb, data);
  688. }
  689. else
  690. #endif
  691. {
  692. /* areschannel is already setup in the Curl_open() function */
  693. CURL_TRC_DNS(data, "asyn-ares: fire off query for A");
  694. ares->num_pending = 1;
  695. ares_gethostbyname(ares->channel, data->state.async.hostname, PF_INET,
  696. async_ares_hostbyname_cb, data);
  697. }
  698. #endif
  699. #ifdef USE_HTTPSRR
  700. {
  701. CURL_TRC_DNS(data, "asyn-ares: fire off query for HTTPSRR");
  702. memset(&ares->hinfo, 0, sizeof(ares->hinfo));
  703. ares->hinfo.port = -1;
  704. ares->num_pending++; /* one more */
  705. ares_query_dnsrec(ares->channel, data->state.async.hostname,
  706. ARES_CLASS_IN, ARES_REC_TYPE_HTTPS,
  707. async_ares_rr_done, data, NULL);
  708. }
  709. #endif
  710. *waitp = 1; /* expect asynchronous response */
  711. return NULL; /* no struct yet */
  712. }
  713. /* Set what DNS server are is to use. This is called in 2 situations:
  714. * 1. when the application does 'CURLOPT_DNS_SERVERS' and passing NULL
  715. * means any previous set value should be unset. Which means
  716. * we need to destroy and create the are channel anew, if there is one.
  717. * 2. When we lazy init the ares channel and NULL means that there
  718. * are no preferences and we do not reset any existing channel. */
  719. static CURLcode async_ares_set_dns_servers(struct Curl_easy *data,
  720. bool reset_on_null)
  721. {
  722. struct async_ares_ctx *ares = &data->state.async.ares;
  723. CURLcode result = CURLE_NOT_BUILT_IN;
  724. const char *servers = data->set.str[STRING_DNS_SERVERS];
  725. int ares_result = ARES_SUCCESS;
  726. #if defined(CURLDEBUG) && defined(HAVE_CARES_SERVERS_CSV)
  727. if(getenv("CURL_DNS_SERVER"))
  728. servers = getenv("CURL_DNS_SERVER");
  729. #endif
  730. if(!servers) {
  731. if(reset_on_null) {
  732. Curl_async_destroy(data);
  733. }
  734. return CURLE_OK;
  735. }
  736. #ifdef HAVE_CARES_SERVERS_CSV
  737. /* if channel is not there, this is just a parameter check */
  738. if(ares->channel)
  739. #ifdef HAVE_CARES_PORTS_CSV
  740. ares_result = ares_set_servers_ports_csv(ares->channel, servers);
  741. #else
  742. ares_result = ares_set_servers_csv(ares->channel, 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. DEBUGF(infof(data, "bad servers set"));
  756. result = CURLE_BAD_FUNCTION_ARGUMENT;
  757. break;
  758. }
  759. #else /* too old c-ares version! */
  760. (void)data;
  761. (void)(ares_result);
  762. #endif
  763. return result;
  764. }
  765. CURLcode Curl_async_ares_set_dns_servers(struct Curl_easy *data)
  766. {
  767. return async_ares_set_dns_servers(data, TRUE);
  768. }
  769. CURLcode Curl_async_ares_set_dns_interface(struct Curl_easy *data)
  770. {
  771. #ifdef HAVE_CARES_LOCAL_DEV
  772. struct async_ares_ctx *ares = &data->state.async.ares;
  773. const char *interf = data->set.str[STRING_DNS_INTERFACE];
  774. if(!interf)
  775. interf = "";
  776. /* if channel is not there, this is just a parameter check */
  777. if(ares->channel)
  778. ares_set_local_dev(ares->channel, interf);
  779. return CURLE_OK;
  780. #else /* c-ares version too old! */
  781. (void)data;
  782. (void)interf;
  783. return CURLE_NOT_BUILT_IN;
  784. #endif
  785. }
  786. CURLcode Curl_async_ares_set_dns_local_ip4(struct Curl_easy *data)
  787. {
  788. #ifdef HAVE_CARES_SET_LOCAL
  789. struct async_ares_ctx *ares = &data->state.async.ares;
  790. struct in_addr a4;
  791. const char *local_ip4 = data->set.str[STRING_DNS_LOCAL_IP4];
  792. if((!local_ip4) || (local_ip4[0] == 0)) {
  793. a4.s_addr = 0; /* disabled: do not bind to a specific address */
  794. }
  795. else {
  796. if(curlx_inet_pton(AF_INET, local_ip4, &a4) != 1) {
  797. DEBUGF(infof(data, "bad DNS IPv4 address"));
  798. return CURLE_BAD_FUNCTION_ARGUMENT;
  799. }
  800. }
  801. /* if channel is not there yet, this is just a parameter check */
  802. if(ares->channel)
  803. ares_set_local_ip4(ares->channel, ntohl(a4.s_addr));
  804. return CURLE_OK;
  805. #else /* c-ares version too old! */
  806. (void)data;
  807. (void)local_ip4;
  808. return CURLE_NOT_BUILT_IN;
  809. #endif
  810. }
  811. CURLcode Curl_async_ares_set_dns_local_ip6(struct Curl_easy *data)
  812. {
  813. #if defined(HAVE_CARES_SET_LOCAL) && defined(USE_IPV6)
  814. struct async_ares_ctx *ares = &data->state.async.ares;
  815. unsigned char a6[INET6_ADDRSTRLEN];
  816. const char *local_ip6 = data->set.str[STRING_DNS_LOCAL_IP6];
  817. if((!local_ip6) || (local_ip6[0] == 0)) {
  818. /* disabled: do not bind to a specific address */
  819. memset(a6, 0, sizeof(a6));
  820. }
  821. else {
  822. if(curlx_inet_pton(AF_INET6, local_ip6, a6) != 1) {
  823. DEBUGF(infof(data, "bad DNS IPv6 address"));
  824. return CURLE_BAD_FUNCTION_ARGUMENT;
  825. }
  826. }
  827. /* if channel is not there, this is just a parameter check */
  828. if(ares->channel)
  829. ares_set_local_ip6(ares->channel, a6);
  830. return CURLE_OK;
  831. #else /* c-ares version too old! */
  832. (void)data;
  833. return CURLE_NOT_BUILT_IN;
  834. #endif
  835. }
  836. #endif /* CURLRES_ARES */