hostip.c 33 KB

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