hostip.c 30 KB

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