hostip.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2020, 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.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include "curl_setup.h"
  23. #ifdef HAVE_NETINET_IN_H
  24. #include <netinet/in.h>
  25. #endif
  26. #ifdef HAVE_NETINET_IN6_H
  27. #include <netinet/in6.h>
  28. #endif
  29. #ifdef HAVE_NETDB_H
  30. #include <netdb.h>
  31. #endif
  32. #ifdef HAVE_ARPA_INET_H
  33. #include <arpa/inet.h>
  34. #endif
  35. #ifdef __VMS
  36. #include <in.h>
  37. #include <inet.h>
  38. #endif
  39. #ifdef HAVE_SETJMP_H
  40. #include <setjmp.h>
  41. #endif
  42. #ifdef HAVE_SIGNAL_H
  43. #include <signal.h>
  44. #endif
  45. #ifdef HAVE_PROCESS_H
  46. #include <process.h>
  47. #endif
  48. #include "urldata.h"
  49. #include "sendf.h"
  50. #include "hostip.h"
  51. #include "hash.h"
  52. #include "rand.h"
  53. #include "share.h"
  54. #include "strerror.h"
  55. #include "url.h"
  56. #include "inet_ntop.h"
  57. #include "inet_pton.h"
  58. #include "multiif.h"
  59. #include "doh.h"
  60. #include "warnless.h"
  61. /* The last 3 #include files should be in this order */
  62. #include "curl_printf.h"
  63. #include "curl_memory.h"
  64. #include "memdebug.h"
  65. #if defined(CURLRES_SYNCH) && \
  66. defined(HAVE_ALARM) && defined(SIGALRM) && defined(HAVE_SIGSETJMP)
  67. /* alarm-based timeouts can only be used with all the dependencies satisfied */
  68. #define USE_ALARM_TIMEOUT
  69. #endif
  70. #define MAX_HOSTCACHE_LEN (255 + 7) /* max FQDN + colon + port number + zero */
  71. /*
  72. * hostip.c explained
  73. * ==================
  74. *
  75. * The main COMPILE-TIME DEFINES to keep in mind when reading the host*.c
  76. * source file are these:
  77. *
  78. * CURLRES_IPV6 - this host has getaddrinfo() and family, and thus we use
  79. * that. The host may not be able to resolve IPv6, but we don't really have to
  80. * take that into account. Hosts that aren't IPv6-enabled have CURLRES_IPV4
  81. * defined.
  82. *
  83. * CURLRES_ARES - is defined if libcurl is built to use c-ares for
  84. * asynchronous name resolves. This can be Windows or *nix.
  85. *
  86. * CURLRES_THREADED - is defined if libcurl is built to run under (native)
  87. * Windows, and then the name resolve will be done in a new thread, and the
  88. * supported API will be the same as for ares-builds.
  89. *
  90. * If any of the two previous are defined, CURLRES_ASYNCH is defined too. If
  91. * libcurl is not built to use an asynchronous resolver, CURLRES_SYNCH is
  92. * defined.
  93. *
  94. * The host*.c sources files are split up like this:
  95. *
  96. * hostip.c - method-independent resolver functions and utility functions
  97. * hostasyn.c - functions for asynchronous name resolves
  98. * hostsyn.c - functions for synchronous name resolves
  99. * hostip4.c - IPv4 specific functions
  100. * hostip6.c - IPv6 specific functions
  101. *
  102. * The two asynchronous name resolver backends are implemented in:
  103. * asyn-ares.c - functions for ares-using name resolves
  104. * asyn-thread.c - functions for threaded name resolves
  105. * The hostip.h is the united header file for all this. It defines the
  106. * CURLRES_* defines based on the config*.h and curl_setup.h defines.
  107. */
  108. static void freednsentry(void *freethis);
  109. /*
  110. * Return # of addresses in a Curl_addrinfo struct
  111. */
  112. int Curl_num_addresses(const Curl_addrinfo *addr)
  113. {
  114. int i = 0;
  115. while(addr) {
  116. addr = addr->ai_next;
  117. i++;
  118. }
  119. return i;
  120. }
  121. /*
  122. * Curl_printable_address() returns a printable version of the 1st address
  123. * given in the 'ai' argument. The result will be stored in the buf that is
  124. * bufsize bytes big.
  125. *
  126. * If the conversion fails, it returns NULL.
  127. */
  128. const char *
  129. Curl_printable_address(const Curl_addrinfo *ai, char *buf, size_t bufsize)
  130. {
  131. const struct sockaddr_in *sa4;
  132. const struct in_addr *ipaddr4;
  133. #ifdef ENABLE_IPV6
  134. const struct sockaddr_in6 *sa6;
  135. const struct in6_addr *ipaddr6;
  136. #endif
  137. switch(ai->ai_family) {
  138. case AF_INET:
  139. sa4 = (const void *)ai->ai_addr;
  140. ipaddr4 = &sa4->sin_addr;
  141. return Curl_inet_ntop(ai->ai_family, (const void *)ipaddr4, buf,
  142. bufsize);
  143. #ifdef ENABLE_IPV6
  144. case AF_INET6:
  145. sa6 = (const void *)ai->ai_addr;
  146. ipaddr6 = &sa6->sin6_addr;
  147. return Curl_inet_ntop(ai->ai_family, (const void *)ipaddr6, buf,
  148. bufsize);
  149. #endif
  150. default:
  151. break;
  152. }
  153. return NULL;
  154. }
  155. /*
  156. * Create a hostcache id string for the provided host + port, to be used by
  157. * the DNS caching. Without alloc.
  158. */
  159. static void
  160. create_hostcache_id(const char *name, int port, char *ptr, size_t buflen)
  161. {
  162. size_t len = strlen(name);
  163. if(len > (buflen - 7))
  164. len = buflen - 7;
  165. /* store and lower case the name */
  166. while(len--)
  167. *ptr++ = (char)TOLOWER(*name++);
  168. msnprintf(ptr, 7, ":%u", port);
  169. }
  170. struct hostcache_prune_data {
  171. long cache_timeout;
  172. time_t now;
  173. };
  174. /*
  175. * This function is set as a callback to be called for every entry in the DNS
  176. * cache when we want to prune old unused entries.
  177. *
  178. * Returning non-zero means remove the entry, return 0 to keep it in the
  179. * cache.
  180. */
  181. static int
  182. hostcache_timestamp_remove(void *datap, void *hc)
  183. {
  184. struct hostcache_prune_data *data =
  185. (struct hostcache_prune_data *) datap;
  186. struct Curl_dns_entry *c = (struct Curl_dns_entry *) hc;
  187. return (0 != c->timestamp)
  188. && (data->now - c->timestamp >= data->cache_timeout);
  189. }
  190. /*
  191. * Prune the DNS cache. This assumes that a lock has already been taken.
  192. */
  193. static void
  194. hostcache_prune(struct curl_hash *hostcache, long cache_timeout, time_t now)
  195. {
  196. struct hostcache_prune_data user;
  197. user.cache_timeout = cache_timeout;
  198. user.now = now;
  199. Curl_hash_clean_with_criterium(hostcache,
  200. (void *) &user,
  201. hostcache_timestamp_remove);
  202. }
  203. /*
  204. * Library-wide function for pruning the DNS cache. This function takes and
  205. * returns the appropriate locks.
  206. */
  207. void Curl_hostcache_prune(struct Curl_easy *data)
  208. {
  209. time_t now;
  210. if((data->set.dns_cache_timeout == -1) || !data->dns.hostcache)
  211. /* cache forever means never prune, and NULL hostcache means
  212. we can't do it */
  213. return;
  214. if(data->share)
  215. Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
  216. time(&now);
  217. /* Remove outdated and unused entries from the hostcache */
  218. hostcache_prune(data->dns.hostcache,
  219. data->set.dns_cache_timeout,
  220. now);
  221. if(data->share)
  222. Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
  223. }
  224. #ifdef HAVE_SIGSETJMP
  225. /* Beware this is a global and unique instance. This is used to store the
  226. return address that we can jump back to from inside a signal handler. This
  227. is not thread-safe stuff. */
  228. sigjmp_buf curl_jmpenv;
  229. #endif
  230. /* lookup address, returns entry if found and not stale */
  231. static struct Curl_dns_entry *
  232. fetch_addr(struct connectdata *conn,
  233. const char *hostname,
  234. int port)
  235. {
  236. struct Curl_dns_entry *dns = NULL;
  237. size_t entry_len;
  238. struct Curl_easy *data = conn->data;
  239. char entry_id[MAX_HOSTCACHE_LEN];
  240. /* Create an entry id, based upon the hostname and port */
  241. create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
  242. entry_len = strlen(entry_id);
  243. /* See if its already in our dns cache */
  244. dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
  245. /* No entry found in cache, check if we might have a wildcard entry */
  246. if(!dns && data->change.wildcard_resolve) {
  247. create_hostcache_id("*", port, entry_id, sizeof(entry_id));
  248. entry_len = strlen(entry_id);
  249. /* See if it's already in our dns cache */
  250. dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
  251. }
  252. if(dns && (data->set.dns_cache_timeout != -1)) {
  253. /* See whether the returned entry is stale. Done before we release lock */
  254. struct hostcache_prune_data user;
  255. time(&user.now);
  256. user.cache_timeout = data->set.dns_cache_timeout;
  257. if(hostcache_timestamp_remove(&user, dns)) {
  258. infof(data, "Hostname in DNS cache was stale, zapped\n");
  259. dns = NULL; /* the memory deallocation is being handled by the hash */
  260. Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
  261. }
  262. }
  263. return dns;
  264. }
  265. /*
  266. * Curl_fetch_addr() fetches a 'Curl_dns_entry' already in the DNS cache.
  267. *
  268. * Curl_resolv() checks initially and multi_runsingle() checks each time
  269. * it discovers the handle in the state WAITRESOLVE whether the hostname
  270. * has already been resolved and the address has already been stored in
  271. * the DNS cache. This short circuits waiting for a lot of pending
  272. * lookups for the same hostname requested by different handles.
  273. *
  274. * Returns the Curl_dns_entry entry pointer or NULL if not in the cache.
  275. *
  276. * The returned data *MUST* be "unlocked" with Curl_resolv_unlock() after
  277. * use, or we'll leak memory!
  278. */
  279. struct Curl_dns_entry *
  280. Curl_fetch_addr(struct connectdata *conn,
  281. const char *hostname,
  282. int port)
  283. {
  284. struct Curl_easy *data = conn->data;
  285. struct Curl_dns_entry *dns = NULL;
  286. if(data->share)
  287. Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
  288. dns = fetch_addr(conn, hostname, port);
  289. if(dns)
  290. dns->inuse++; /* we use it! */
  291. if(data->share)
  292. Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
  293. return dns;
  294. }
  295. #ifndef CURL_DISABLE_SHUFFLE_DNS
  296. UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data,
  297. Curl_addrinfo **addr);
  298. /*
  299. * Curl_shuffle_addr() shuffles the order of addresses in a 'Curl_addrinfo'
  300. * struct by re-linking its linked list.
  301. *
  302. * The addr argument should be the address of a pointer to the head node of a
  303. * `Curl_addrinfo` list and it will be modified to point to the new head after
  304. * shuffling.
  305. *
  306. * Not declared static only to make it easy to use in a unit test!
  307. *
  308. * @unittest: 1608
  309. */
  310. UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data,
  311. Curl_addrinfo **addr)
  312. {
  313. CURLcode result = CURLE_OK;
  314. const int num_addrs = Curl_num_addresses(*addr);
  315. if(num_addrs > 1) {
  316. Curl_addrinfo **nodes;
  317. infof(data, "Shuffling %i addresses", num_addrs);
  318. nodes = malloc(num_addrs*sizeof(*nodes));
  319. if(nodes) {
  320. int i;
  321. unsigned int *rnd;
  322. const size_t rnd_size = num_addrs * sizeof(*rnd);
  323. /* build a plain array of Curl_addrinfo pointers */
  324. nodes[0] = *addr;
  325. for(i = 1; i < num_addrs; i++) {
  326. nodes[i] = nodes[i-1]->ai_next;
  327. }
  328. rnd = malloc(rnd_size);
  329. if(rnd) {
  330. /* Fisher-Yates shuffle */
  331. if(Curl_rand(data, (unsigned char *)rnd, rnd_size) == CURLE_OK) {
  332. Curl_addrinfo *swap_tmp;
  333. for(i = num_addrs - 1; i > 0; i--) {
  334. swap_tmp = nodes[rnd[i] % (i + 1)];
  335. nodes[rnd[i] % (i + 1)] = nodes[i];
  336. nodes[i] = swap_tmp;
  337. }
  338. /* relink list in the new order */
  339. for(i = 1; i < num_addrs; i++) {
  340. nodes[i-1]->ai_next = nodes[i];
  341. }
  342. nodes[num_addrs-1]->ai_next = NULL;
  343. *addr = nodes[0];
  344. }
  345. free(rnd);
  346. }
  347. else
  348. result = CURLE_OUT_OF_MEMORY;
  349. free(nodes);
  350. }
  351. else
  352. result = CURLE_OUT_OF_MEMORY;
  353. }
  354. return result;
  355. }
  356. #endif
  357. /*
  358. * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache.
  359. *
  360. * When calling Curl_resolv() has resulted in a response with a returned
  361. * address, we call this function to store the information in the dns
  362. * cache etc
  363. *
  364. * Returns the Curl_dns_entry entry pointer or NULL if the storage failed.
  365. */
  366. struct Curl_dns_entry *
  367. Curl_cache_addr(struct Curl_easy *data,
  368. Curl_addrinfo *addr,
  369. const char *hostname,
  370. int port)
  371. {
  372. char entry_id[MAX_HOSTCACHE_LEN];
  373. size_t entry_len;
  374. struct Curl_dns_entry *dns;
  375. struct Curl_dns_entry *dns2;
  376. #ifndef CURL_DISABLE_SHUFFLE_DNS
  377. /* shuffle addresses if requested */
  378. if(data->set.dns_shuffle_addresses) {
  379. CURLcode result = Curl_shuffle_addr(data, &addr);
  380. if(result)
  381. return NULL;
  382. }
  383. #endif
  384. /* Create a new cache entry */
  385. dns = calloc(1, sizeof(struct Curl_dns_entry));
  386. if(!dns) {
  387. return NULL;
  388. }
  389. /* Create an entry id, based upon the hostname and port */
  390. create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
  391. entry_len = strlen(entry_id);
  392. dns->inuse = 1; /* the cache has the first reference */
  393. dns->addr = addr; /* this is the address(es) */
  394. time(&dns->timestamp);
  395. if(dns->timestamp == 0)
  396. dns->timestamp = 1; /* zero indicates CURLOPT_RESOLVE entry */
  397. /* Store the resolved data in our DNS cache. */
  398. dns2 = Curl_hash_add(data->dns.hostcache, entry_id, entry_len + 1,
  399. (void *)dns);
  400. if(!dns2) {
  401. free(dns);
  402. return NULL;
  403. }
  404. dns = dns2;
  405. dns->inuse++; /* mark entry as in-use */
  406. return dns;
  407. }
  408. /*
  409. * Curl_resolv() is the main name resolve function within libcurl. It resolves
  410. * a name and returns a pointer to the entry in the 'entry' argument (if one
  411. * is provided). This function might return immediately if we're using asynch
  412. * resolves. See the return codes.
  413. *
  414. * The cache entry we return will get its 'inuse' counter increased when this
  415. * function is used. You MUST call Curl_resolv_unlock() later (when you're
  416. * done using this struct) to decrease the counter again.
  417. *
  418. * In debug mode, we specifically test for an interface name "LocalHost"
  419. * and resolve "localhost" instead as a means to permit test cases
  420. * to connect to a local test server with any host name.
  421. *
  422. * Return codes:
  423. *
  424. * CURLRESOLV_ERROR (-1) = error, no pointer
  425. * CURLRESOLV_RESOLVED (0) = OK, pointer provided
  426. * CURLRESOLV_PENDING (1) = waiting for response, no pointer
  427. */
  428. enum resolve_t Curl_resolv(struct connectdata *conn,
  429. const char *hostname,
  430. int port,
  431. bool allowDOH,
  432. struct Curl_dns_entry **entry)
  433. {
  434. struct Curl_dns_entry *dns = NULL;
  435. struct Curl_easy *data = conn->data;
  436. CURLcode result;
  437. enum resolve_t rc = CURLRESOLV_ERROR; /* default to failure */
  438. *entry = NULL;
  439. if(data->share)
  440. Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
  441. dns = fetch_addr(conn, hostname, port);
  442. if(dns) {
  443. infof(data, "Hostname %s was found in DNS cache\n", hostname);
  444. dns->inuse++; /* we use it! */
  445. rc = CURLRESOLV_RESOLVED;
  446. }
  447. if(data->share)
  448. Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
  449. if(!dns) {
  450. /* The entry was not in the cache. Resolve it to IP address */
  451. Curl_addrinfo *addr = NULL;
  452. int respwait = 0;
  453. #ifndef USE_RESOLVE_ON_IPS
  454. struct in_addr in;
  455. #endif
  456. /* notify the resolver start callback */
  457. if(data->set.resolver_start) {
  458. int st;
  459. Curl_set_in_callback(data, true);
  460. st = data->set.resolver_start(data->state.resolver, NULL,
  461. data->set.resolver_start_client);
  462. Curl_set_in_callback(data, false);
  463. if(st)
  464. return CURLRESOLV_ERROR;
  465. }
  466. #ifndef USE_RESOLVE_ON_IPS
  467. /* First check if this is an IPv4 address string */
  468. if(Curl_inet_pton(AF_INET, hostname, &in) > 0)
  469. /* This is a dotted IP address 123.123.123.123-style */
  470. addr = Curl_ip2addr(AF_INET, &in, hostname, port);
  471. #ifdef ENABLE_IPV6
  472. if(!addr) {
  473. struct in6_addr in6;
  474. /* check if this is an IPv6 address string */
  475. if(Curl_inet_pton(AF_INET6, hostname, &in6) > 0)
  476. /* This is an IPv6 address literal */
  477. addr = Curl_ip2addr(AF_INET6, &in6, hostname, port);
  478. }
  479. #endif /* ENABLE_IPV6 */
  480. #endif /* !USE_RESOLVE_ON_IPS */
  481. if(!addr) {
  482. /* Check what IP specifics the app has requested and if we can provide
  483. * it. If not, bail out. */
  484. if(!Curl_ipvalid(conn))
  485. return CURLRESOLV_ERROR;
  486. if(allowDOH && data->set.doh) {
  487. addr = Curl_doh(conn, hostname, port, &respwait);
  488. }
  489. else {
  490. /* If Curl_getaddrinfo() returns NULL, 'respwait' might be set to a
  491. non-zero value indicating that we need to wait for the response to
  492. the resolve call */
  493. addr = Curl_getaddrinfo(conn,
  494. #ifdef DEBUGBUILD
  495. (data->set.str[STRING_DEVICE]
  496. && !strcmp(data->set.str[STRING_DEVICE],
  497. "LocalHost"))?"localhost":
  498. #endif
  499. hostname, port, &respwait);
  500. }
  501. }
  502. if(!addr) {
  503. if(respwait) {
  504. /* the response to our resolve call will come asynchronously at
  505. a later time, good or bad */
  506. /* First, check that we haven't received the info by now */
  507. result = Curl_resolv_check(conn, &dns);
  508. if(result) /* error detected */
  509. return CURLRESOLV_ERROR;
  510. if(dns)
  511. rc = CURLRESOLV_RESOLVED; /* pointer provided */
  512. else
  513. rc = CURLRESOLV_PENDING; /* no info yet */
  514. }
  515. }
  516. else {
  517. if(data->share)
  518. Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
  519. /* we got a response, store it in the cache */
  520. dns = Curl_cache_addr(data, addr, hostname, port);
  521. if(data->share)
  522. Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
  523. if(!dns)
  524. /* returned failure, bail out nicely */
  525. Curl_freeaddrinfo(addr);
  526. else
  527. rc = CURLRESOLV_RESOLVED;
  528. }
  529. }
  530. *entry = dns;
  531. return rc;
  532. }
  533. #ifdef USE_ALARM_TIMEOUT
  534. /*
  535. * This signal handler jumps back into the main libcurl code and continues
  536. * execution. This effectively causes the remainder of the application to run
  537. * within a signal handler which is nonportable and could lead to problems.
  538. */
  539. static
  540. RETSIGTYPE alarmfunc(int sig)
  541. {
  542. /* this is for "-ansi -Wall -pedantic" to stop complaining! (rabe) */
  543. (void)sig;
  544. siglongjmp(curl_jmpenv, 1);
  545. }
  546. #endif /* USE_ALARM_TIMEOUT */
  547. /*
  548. * Curl_resolv_timeout() is the same as Curl_resolv() but specifies a
  549. * timeout. This function might return immediately if we're using asynch
  550. * resolves. See the return codes.
  551. *
  552. * The cache entry we return will get its 'inuse' counter increased when this
  553. * function is used. You MUST call Curl_resolv_unlock() later (when you're
  554. * done using this struct) to decrease the counter again.
  555. *
  556. * If built with a synchronous resolver and use of signals is not
  557. * disabled by the application, then a nonzero timeout will cause a
  558. * timeout after the specified number of milliseconds. Otherwise, timeout
  559. * is ignored.
  560. *
  561. * Return codes:
  562. *
  563. * CURLRESOLV_TIMEDOUT(-2) = warning, time too short or previous alarm expired
  564. * CURLRESOLV_ERROR (-1) = error, no pointer
  565. * CURLRESOLV_RESOLVED (0) = OK, pointer provided
  566. * CURLRESOLV_PENDING (1) = waiting for response, no pointer
  567. */
  568. enum resolve_t Curl_resolv_timeout(struct connectdata *conn,
  569. const char *hostname,
  570. int port,
  571. struct Curl_dns_entry **entry,
  572. timediff_t timeoutms)
  573. {
  574. #ifdef USE_ALARM_TIMEOUT
  575. #ifdef HAVE_SIGACTION
  576. struct sigaction keep_sigact; /* store the old struct here */
  577. volatile bool keep_copysig = FALSE; /* whether old sigact has been saved */
  578. struct sigaction sigact;
  579. #else
  580. #ifdef HAVE_SIGNAL
  581. void (*keep_sigact)(int); /* store the old handler here */
  582. #endif /* HAVE_SIGNAL */
  583. #endif /* HAVE_SIGACTION */
  584. volatile long timeout;
  585. volatile unsigned int prev_alarm = 0;
  586. struct Curl_easy *data = conn->data;
  587. #endif /* USE_ALARM_TIMEOUT */
  588. enum resolve_t rc;
  589. *entry = NULL;
  590. if(timeoutms < 0)
  591. /* got an already expired timeout */
  592. return CURLRESOLV_TIMEDOUT;
  593. #ifdef USE_ALARM_TIMEOUT
  594. if(data->set.no_signal)
  595. /* Ignore the timeout when signals are disabled */
  596. timeout = 0;
  597. else
  598. timeout = (timeoutms > LONG_MAX) ? LONG_MAX : (long)timeoutms;
  599. if(!timeout)
  600. /* USE_ALARM_TIMEOUT defined, but no timeout actually requested */
  601. return Curl_resolv(conn, hostname, port, TRUE, entry);
  602. if(timeout < 1000) {
  603. /* The alarm() function only provides integer second resolution, so if
  604. we want to wait less than one second we must bail out already now. */
  605. failf(data,
  606. "remaining timeout of %ld too small to resolve via SIGALRM method",
  607. timeout);
  608. return CURLRESOLV_TIMEDOUT;
  609. }
  610. /* This allows us to time-out from the name resolver, as the timeout
  611. will generate a signal and we will siglongjmp() from that here.
  612. This technique has problems (see alarmfunc).
  613. This should be the last thing we do before calling Curl_resolv(),
  614. as otherwise we'd have to worry about variables that get modified
  615. before we invoke Curl_resolv() (and thus use "volatile"). */
  616. if(sigsetjmp(curl_jmpenv, 1)) {
  617. /* this is coming from a siglongjmp() after an alarm signal */
  618. failf(data, "name lookup timed out");
  619. rc = CURLRESOLV_ERROR;
  620. goto clean_up;
  621. }
  622. else {
  623. /*************************************************************
  624. * Set signal handler to catch SIGALRM
  625. * Store the old value to be able to set it back later!
  626. *************************************************************/
  627. #ifdef HAVE_SIGACTION
  628. sigaction(SIGALRM, NULL, &sigact);
  629. keep_sigact = sigact;
  630. keep_copysig = TRUE; /* yes, we have a copy */
  631. sigact.sa_handler = alarmfunc;
  632. #ifdef SA_RESTART
  633. /* HPUX doesn't have SA_RESTART but defaults to that behaviour! */
  634. sigact.sa_flags &= ~SA_RESTART;
  635. #endif
  636. /* now set the new struct */
  637. sigaction(SIGALRM, &sigact, NULL);
  638. #else /* HAVE_SIGACTION */
  639. /* no sigaction(), revert to the much lamer signal() */
  640. #ifdef HAVE_SIGNAL
  641. keep_sigact = signal(SIGALRM, alarmfunc);
  642. #endif
  643. #endif /* HAVE_SIGACTION */
  644. /* alarm() makes a signal get sent when the timeout fires off, and that
  645. will abort system calls */
  646. prev_alarm = alarm(curlx_sltoui(timeout/1000L));
  647. }
  648. #else
  649. #ifndef CURLRES_ASYNCH
  650. if(timeoutms)
  651. infof(conn->data, "timeout on name lookup is not supported\n");
  652. #else
  653. (void)timeoutms; /* timeoutms not used with an async resolver */
  654. #endif
  655. #endif /* USE_ALARM_TIMEOUT */
  656. /* Perform the actual name resolution. This might be interrupted by an
  657. * alarm if it takes too long.
  658. */
  659. rc = Curl_resolv(conn, hostname, port, TRUE, entry);
  660. #ifdef USE_ALARM_TIMEOUT
  661. clean_up:
  662. if(!prev_alarm)
  663. /* deactivate a possibly active alarm before uninstalling the handler */
  664. alarm(0);
  665. #ifdef HAVE_SIGACTION
  666. if(keep_copysig) {
  667. /* we got a struct as it looked before, now put that one back nice
  668. and clean */
  669. sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */
  670. }
  671. #else
  672. #ifdef HAVE_SIGNAL
  673. /* restore the previous SIGALRM handler */
  674. signal(SIGALRM, keep_sigact);
  675. #endif
  676. #endif /* HAVE_SIGACTION */
  677. /* switch back the alarm() to either zero or to what it was before minus
  678. the time we spent until now! */
  679. if(prev_alarm) {
  680. /* there was an alarm() set before us, now put it back */
  681. timediff_t elapsed_secs = Curl_timediff(Curl_now(),
  682. conn->created) / 1000;
  683. /* the alarm period is counted in even number of seconds */
  684. unsigned long alarm_set = (unsigned long)(prev_alarm - elapsed_secs);
  685. if(!alarm_set ||
  686. ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) {
  687. /* if the alarm time-left reached zero or turned "negative" (counted
  688. with unsigned values), we should fire off a SIGALRM here, but we
  689. won't, and zero would be to switch it off so we never set it to
  690. less than 1! */
  691. alarm(1);
  692. rc = CURLRESOLV_TIMEDOUT;
  693. failf(data, "Previous alarm fired off!");
  694. }
  695. else
  696. alarm((unsigned int)alarm_set);
  697. }
  698. #endif /* USE_ALARM_TIMEOUT */
  699. return rc;
  700. }
  701. /*
  702. * Curl_resolv_unlock() unlocks the given cached DNS entry. When this has been
  703. * made, the struct may be destroyed due to pruning. It is important that only
  704. * one unlock is made for each Curl_resolv() call.
  705. *
  706. * May be called with 'data' == NULL for global cache.
  707. */
  708. void Curl_resolv_unlock(struct Curl_easy *data, struct Curl_dns_entry *dns)
  709. {
  710. if(data && data->share)
  711. Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
  712. freednsentry(dns);
  713. if(data && data->share)
  714. Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
  715. }
  716. /*
  717. * File-internal: release cache dns entry reference, free if inuse drops to 0
  718. */
  719. static void freednsentry(void *freethis)
  720. {
  721. struct Curl_dns_entry *dns = (struct Curl_dns_entry *) freethis;
  722. DEBUGASSERT(dns && (dns->inuse>0));
  723. dns->inuse--;
  724. if(dns->inuse == 0) {
  725. Curl_freeaddrinfo(dns->addr);
  726. free(dns);
  727. }
  728. }
  729. /*
  730. * Curl_mk_dnscache() inits a new DNS cache and returns success/failure.
  731. */
  732. int Curl_mk_dnscache(struct curl_hash *hash)
  733. {
  734. return Curl_hash_init(hash, 7, Curl_hash_str, Curl_str_key_compare,
  735. freednsentry);
  736. }
  737. /*
  738. * Curl_hostcache_clean()
  739. *
  740. * This _can_ be called with 'data' == NULL but then of course no locking
  741. * can be done!
  742. */
  743. void Curl_hostcache_clean(struct Curl_easy *data,
  744. struct curl_hash *hash)
  745. {
  746. if(data && data->share)
  747. Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
  748. Curl_hash_clean(hash);
  749. if(data && data->share)
  750. Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
  751. }
  752. CURLcode Curl_loadhostpairs(struct Curl_easy *data)
  753. {
  754. struct curl_slist *hostp;
  755. char hostname[256];
  756. int port = 0;
  757. /* Default is no wildcard found */
  758. data->change.wildcard_resolve = false;
  759. for(hostp = data->change.resolve; hostp; hostp = hostp->next) {
  760. char entry_id[MAX_HOSTCACHE_LEN];
  761. if(!hostp->data)
  762. continue;
  763. if(hostp->data[0] == '-') {
  764. size_t entry_len;
  765. if(2 != sscanf(hostp->data + 1, "%255[^:]:%d", hostname, &port)) {
  766. infof(data, "Couldn't parse CURLOPT_RESOLVE removal entry '%s'!\n",
  767. hostp->data);
  768. continue;
  769. }
  770. /* Create an entry id, based upon the hostname and port */
  771. create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
  772. entry_len = strlen(entry_id);
  773. if(data->share)
  774. Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
  775. /* delete entry, ignore if it didn't exist */
  776. Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
  777. if(data->share)
  778. Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
  779. }
  780. else {
  781. struct Curl_dns_entry *dns;
  782. Curl_addrinfo *head = NULL, *tail = NULL;
  783. size_t entry_len;
  784. char address[64];
  785. #if !defined(CURL_DISABLE_VERBOSE_STRINGS)
  786. char *addresses = NULL;
  787. #endif
  788. char *addr_begin;
  789. char *addr_end;
  790. char *port_ptr;
  791. char *end_ptr;
  792. char *host_end;
  793. unsigned long tmp_port;
  794. bool error = true;
  795. host_end = strchr(hostp->data, ':');
  796. if(!host_end ||
  797. ((host_end - hostp->data) >= (ptrdiff_t)sizeof(hostname)))
  798. goto err;
  799. memcpy(hostname, hostp->data, host_end - hostp->data);
  800. hostname[host_end - hostp->data] = '\0';
  801. port_ptr = host_end + 1;
  802. tmp_port = strtoul(port_ptr, &end_ptr, 10);
  803. if(tmp_port > USHRT_MAX || end_ptr == port_ptr || *end_ptr != ':')
  804. goto err;
  805. port = (int)tmp_port;
  806. #if !defined(CURL_DISABLE_VERBOSE_STRINGS)
  807. addresses = end_ptr + 1;
  808. #endif
  809. while(*end_ptr) {
  810. size_t alen;
  811. Curl_addrinfo *ai;
  812. addr_begin = end_ptr + 1;
  813. addr_end = strchr(addr_begin, ',');
  814. if(!addr_end)
  815. addr_end = addr_begin + strlen(addr_begin);
  816. end_ptr = addr_end;
  817. /* allow IP(v6) address within [brackets] */
  818. if(*addr_begin == '[') {
  819. if(addr_end == addr_begin || *(addr_end - 1) != ']')
  820. goto err;
  821. ++addr_begin;
  822. --addr_end;
  823. }
  824. alen = addr_end - addr_begin;
  825. if(!alen)
  826. continue;
  827. if(alen >= sizeof(address))
  828. goto err;
  829. memcpy(address, addr_begin, alen);
  830. address[alen] = '\0';
  831. #ifndef ENABLE_IPV6
  832. if(strchr(address, ':')) {
  833. infof(data, "Ignoring resolve address '%s', missing IPv6 support.\n",
  834. address);
  835. continue;
  836. }
  837. #endif
  838. ai = Curl_str2addr(address, port);
  839. if(!ai) {
  840. infof(data, "Resolve address '%s' found illegal!\n", address);
  841. goto err;
  842. }
  843. if(tail) {
  844. tail->ai_next = ai;
  845. tail = tail->ai_next;
  846. }
  847. else {
  848. head = tail = ai;
  849. }
  850. }
  851. if(!head)
  852. goto err;
  853. error = false;
  854. err:
  855. if(error) {
  856. infof(data, "Couldn't parse CURLOPT_RESOLVE entry '%s'!\n",
  857. hostp->data);
  858. Curl_freeaddrinfo(head);
  859. continue;
  860. }
  861. /* Create an entry id, based upon the hostname and port */
  862. create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
  863. entry_len = strlen(entry_id);
  864. if(data->share)
  865. Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
  866. /* See if its already in our dns cache */
  867. dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
  868. if(dns) {
  869. infof(data, "RESOLVE %s:%d is - old addresses discarded!\n",
  870. hostname, port);
  871. /* delete old entry entry, there are two reasons for this
  872. 1. old entry may have different addresses.
  873. 2. even if entry with correct addresses is already in the cache,
  874. but if it is close to expire, then by the time next http
  875. request is made, it can get expired and pruned because old
  876. entry is not necessarily marked as added by CURLOPT_RESOLVE. */
  877. Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
  878. }
  879. /* put this new host in the cache */
  880. dns = Curl_cache_addr(data, head, hostname, port);
  881. if(dns) {
  882. dns->timestamp = 0; /* mark as added by CURLOPT_RESOLVE */
  883. /* release the returned reference; the cache itself will keep the
  884. * entry alive: */
  885. dns->inuse--;
  886. }
  887. if(data->share)
  888. Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
  889. if(!dns) {
  890. Curl_freeaddrinfo(head);
  891. return CURLE_OUT_OF_MEMORY;
  892. }
  893. infof(data, "Added %s:%d:%s to DNS cache\n",
  894. hostname, port, addresses);
  895. /* Wildcard hostname */
  896. if(hostname[0] == '*' && hostname[1] == '\0') {
  897. infof(data, "RESOLVE %s:%d is wildcard, enabling wildcard checks\n",
  898. hostname, port);
  899. data->change.wildcard_resolve = true;
  900. }
  901. }
  902. }
  903. data->change.resolve = NULL; /* dealt with now */
  904. return CURLE_OK;
  905. }
  906. CURLcode Curl_resolv_check(struct connectdata *conn,
  907. struct Curl_dns_entry **dns)
  908. {
  909. #if defined(CURL_DISABLE_DOH) && !defined(CURLRES_ASYNCH)
  910. (void)dns;
  911. #endif
  912. if(conn->data->set.doh)
  913. return Curl_doh_is_resolved(conn, dns);
  914. return Curl_resolver_is_resolved(conn, dns);
  915. }
  916. int Curl_resolv_getsock(struct connectdata *conn,
  917. curl_socket_t *socks)
  918. {
  919. #ifdef CURLRES_ASYNCH
  920. if(conn->data->set.doh)
  921. /* nothing to wait for during DOH resolve, those handles have their own
  922. sockets */
  923. return GETSOCK_BLANK;
  924. return Curl_resolver_getsock(conn, socks);
  925. #else
  926. (void)conn;
  927. (void)socks;
  928. return GETSOCK_BLANK;
  929. #endif
  930. }
  931. /* Call this function after Curl_connect() has returned async=TRUE and
  932. then a successful name resolve has been received.
  933. Note: this function disconnects and frees the conn data in case of
  934. resolve failure */
  935. CURLcode Curl_once_resolved(struct connectdata *conn,
  936. bool *protocol_done)
  937. {
  938. CURLcode result;
  939. if(conn->async.dns) {
  940. conn->dns_entry = conn->async.dns;
  941. conn->async.dns = NULL;
  942. }
  943. result = Curl_setup_conn(conn, protocol_done);
  944. if(result) {
  945. struct Curl_easy *data = conn->data;
  946. DEBUGASSERT(data);
  947. Curl_detach_connnection(data);
  948. Curl_conncache_remove_conn(data, conn, TRUE);
  949. Curl_disconnect(data, conn, TRUE);
  950. }
  951. return result;
  952. }