asyn-ares.c 28 KB

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