hostip.c 31 KB

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