hostip.c 32 KB

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