1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
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.se/docs/copyright.html.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
23 #include "curl_setup.h"
25 #ifdef HAVE_NETINET_IN_H
26 #include <netinet/in.h>
28 #ifdef HAVE_NETINET_IN6_H
29 #include <netinet/in6.h>
34 #ifdef HAVE_ARPA_INET_H
35 #include <arpa/inet.h>
60 #include "inet_ntop.h"
61 #include "inet_pton.h"
66 /* The last 3 #include files should be in this order */
67 #include "curl_printf.h"
68 #include "curl_memory.h"
71 #if defined(ENABLE_IPV6) && defined(CURL_OSX_CALL_COPYPROXIES)
72 #include <SystemConfiguration/SCDynamicStoreCopySpecific.h>
75 #if defined(CURLRES_SYNCH) && \
76 defined(HAVE_ALARM) && defined(SIGALRM) && defined(HAVE_SIGSETJMP)
77 /* alarm-based timeouts can only be used with all the dependencies satisfied */
78 #define USE_ALARM_TIMEOUT
81 #define MAX_HOSTCACHE_LEN (255 + 7) /* max FQDN + colon + port number + zero */
87 * The main COMPILE-TIME DEFINES to keep in mind when reading the host*.c
88 * source file are these:
90 * CURLRES_IPV6 - this host has getaddrinfo() and family, and thus we use
91 * that. The host may not be able to resolve IPv6, but we don't really have to
92 * take that into account. Hosts that aren't IPv6-enabled have CURLRES_IPV4
95 * CURLRES_ARES - is defined if libcurl is built to use c-ares for
96 * asynchronous name resolves. This can be Windows or *nix.
98 * CURLRES_THREADED - is defined if libcurl is built to run under (native)
99 * Windows, and then the name resolve will be done in a new thread, and the
100 * supported API will be the same as for ares-builds.
102 * If any of the two previous are defined, CURLRES_ASYNCH is defined too. If
103 * libcurl is not built to use an asynchronous resolver, CURLRES_SYNCH is
106 * The host*.c sources files are split up like this:
108 * hostip.c - method-independent resolver functions and utility functions
109 * hostasyn.c - functions for asynchronous name resolves
110 * hostsyn.c - functions for synchronous name resolves
111 * hostip4.c - IPv4 specific functions
112 * hostip6.c - IPv6 specific functions
114 * The two asynchronous name resolver backends are implemented in:
115 * asyn-ares.c - functions for ares-using name resolves
116 * asyn-thread.c - functions for threaded name resolves
118 * The hostip.h is the united header file for all this. It defines the
119 * CURLRES_* defines based on the config*.h and curl_setup.h defines.
122 static void freednsentry(void *freethis);
125 * Return # of addresses in a Curl_addrinfo struct
127 int Curl_num_addresses(const struct Curl_addrinfo *addr)
131 addr = addr->ai_next;
138 * Curl_printable_address() stores a printable version of the 1st address
139 * given in the 'ai' argument. The result will be stored in the buf that is
142 * If the conversion fails, the target buffer is empty.
144 void Curl_printable_address(const struct Curl_addrinfo *ai, char *buf,
147 DEBUGASSERT(bufsize);
150 switch(ai->ai_family) {
152 const struct sockaddr_in *sa4 = (const void *)ai->ai_addr;
153 const struct in_addr *ipaddr4 = &sa4->sin_addr;
154 (void)Curl_inet_ntop(ai->ai_family, (const void *)ipaddr4, buf, bufsize);
159 const struct sockaddr_in6 *sa6 = (const void *)ai->ai_addr;
160 const struct in6_addr *ipaddr6 = &sa6->sin6_addr;
161 (void)Curl_inet_ntop(ai->ai_family, (const void *)ipaddr6, buf, bufsize);
171 * Create a hostcache id string for the provided host + port, to be used by
172 * the DNS caching. Without alloc.
175 create_hostcache_id(const char *name, int port, char *ptr, size_t buflen)
177 size_t len = strlen(name);
178 if(len > (buflen - 7))
180 /* store and lower case the name */
182 *ptr++ = (char)TOLOWER(*name++);
183 msnprintf(ptr, 7, ":%u", port);
186 struct hostcache_prune_data {
192 * This function is set as a callback to be called for every entry in the DNS
193 * cache when we want to prune old unused entries.
195 * Returning non-zero means remove the entry, return 0 to keep it in the
199 hostcache_timestamp_remove(void *datap, void *hc)
201 struct hostcache_prune_data *data =
202 (struct hostcache_prune_data *) datap;
203 struct Curl_dns_entry *c = (struct Curl_dns_entry *) hc;
205 return (0 != c->timestamp)
206 && (data->now - c->timestamp >= data->cache_timeout);
210 * Prune the DNS cache. This assumes that a lock has already been taken.
213 hostcache_prune(struct Curl_hash *hostcache, long cache_timeout, time_t now)
215 struct hostcache_prune_data user;
217 user.cache_timeout = cache_timeout;
220 Curl_hash_clean_with_criterium(hostcache,
222 hostcache_timestamp_remove);
226 * Library-wide function for pruning the DNS cache. This function takes and
227 * returns the appropriate locks.
229 void Curl_hostcache_prune(struct Curl_easy *data)
233 if((data->set.dns_cache_timeout == -1) || !data->dns.hostcache)
234 /* cache forever means never prune, and NULL hostcache means
239 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
243 /* Remove outdated and unused entries from the hostcache */
244 hostcache_prune(data->dns.hostcache,
245 data->set.dns_cache_timeout,
249 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
252 #ifdef HAVE_SIGSETJMP
253 /* Beware this is a global and unique instance. This is used to store the
254 return address that we can jump back to from inside a signal handler. This
255 is not thread-safe stuff. */
256 sigjmp_buf curl_jmpenv;
259 /* lookup address, returns entry if found and not stale */
260 static struct Curl_dns_entry *fetch_addr(struct Curl_easy *data,
261 const char *hostname,
264 struct Curl_dns_entry *dns = NULL;
266 char entry_id[MAX_HOSTCACHE_LEN];
268 /* Create an entry id, based upon the hostname and port */
269 create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
270 entry_len = strlen(entry_id);
272 /* See if its already in our dns cache */
273 dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
275 /* No entry found in cache, check if we might have a wildcard entry */
276 if(!dns && data->state.wildcard_resolve) {
277 create_hostcache_id("*", port, entry_id, sizeof(entry_id));
278 entry_len = strlen(entry_id);
280 /* See if it's already in our dns cache */
281 dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
284 if(dns && (data->set.dns_cache_timeout != -1)) {
285 /* See whether the returned entry is stale. Done before we release lock */
286 struct hostcache_prune_data user;
289 user.cache_timeout = data->set.dns_cache_timeout;
291 if(hostcache_timestamp_remove(&user, dns)) {
292 infof(data, "Hostname in DNS cache was stale, zapped");
293 dns = NULL; /* the memory deallocation is being handled by the hash */
294 Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
302 * Curl_fetch_addr() fetches a 'Curl_dns_entry' already in the DNS cache.
304 * Curl_resolv() checks initially and multi_runsingle() checks each time
305 * it discovers the handle in the state WAITRESOLVE whether the hostname
306 * has already been resolved and the address has already been stored in
307 * the DNS cache. This short circuits waiting for a lot of pending
308 * lookups for the same hostname requested by different handles.
310 * Returns the Curl_dns_entry entry pointer or NULL if not in the cache.
312 * The returned data *MUST* be "unlocked" with Curl_resolv_unlock() after
313 * use, or we'll leak memory!
315 struct Curl_dns_entry *
316 Curl_fetch_addr(struct Curl_easy *data,
317 const char *hostname,
320 struct Curl_dns_entry *dns = NULL;
323 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
325 dns = fetch_addr(data, hostname, port);
328 dns->inuse++; /* we use it! */
331 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
336 #ifndef CURL_DISABLE_SHUFFLE_DNS
337 UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data,
338 struct Curl_addrinfo **addr);
340 * Curl_shuffle_addr() shuffles the order of addresses in a 'Curl_addrinfo'
341 * struct by re-linking its linked list.
343 * The addr argument should be the address of a pointer to the head node of a
344 * `Curl_addrinfo` list and it will be modified to point to the new head after
347 * Not declared static only to make it easy to use in a unit test!
351 UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data,
352 struct Curl_addrinfo **addr)
354 CURLcode result = CURLE_OK;
355 const int num_addrs = Curl_num_addresses(*addr);
358 struct Curl_addrinfo **nodes;
359 infof(data, "Shuffling %i addresses", num_addrs);
361 nodes = malloc(num_addrs*sizeof(*nodes));
365 const size_t rnd_size = num_addrs * sizeof(*rnd);
367 /* build a plain array of Curl_addrinfo pointers */
369 for(i = 1; i < num_addrs; i++) {
370 nodes[i] = nodes[i-1]->ai_next;
373 rnd = malloc(rnd_size);
375 /* Fisher-Yates shuffle */
376 if(Curl_rand(data, (unsigned char *)rnd, rnd_size) == CURLE_OK) {
377 struct Curl_addrinfo *swap_tmp;
378 for(i = num_addrs - 1; i > 0; i--) {
379 swap_tmp = nodes[rnd[i] % (i + 1)];
380 nodes[rnd[i] % (i + 1)] = nodes[i];
384 /* relink list in the new order */
385 for(i = 1; i < num_addrs; i++) {
386 nodes[i-1]->ai_next = nodes[i];
389 nodes[num_addrs-1]->ai_next = NULL;
395 result = CURLE_OUT_OF_MEMORY;
399 result = CURLE_OUT_OF_MEMORY;
406 * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache.
408 * When calling Curl_resolv() has resulted in a response with a returned
409 * address, we call this function to store the information in the dns
412 * Returns the Curl_dns_entry entry pointer or NULL if the storage failed.
414 struct Curl_dns_entry *
415 Curl_cache_addr(struct Curl_easy *data,
416 struct Curl_addrinfo *addr,
417 const char *hostname,
420 char entry_id[MAX_HOSTCACHE_LEN];
422 struct Curl_dns_entry *dns;
423 struct Curl_dns_entry *dns2;
425 #ifndef CURL_DISABLE_SHUFFLE_DNS
426 /* shuffle addresses if requested */
427 if(data->set.dns_shuffle_addresses) {
428 CURLcode result = Curl_shuffle_addr(data, &addr);
434 /* Create a new cache entry */
435 dns = calloc(1, sizeof(struct Curl_dns_entry));
440 /* Create an entry id, based upon the hostname and port */
441 create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
442 entry_len = strlen(entry_id);
444 dns->inuse = 1; /* the cache has the first reference */
445 dns->addr = addr; /* this is the address(es) */
446 time(&dns->timestamp);
447 if(dns->timestamp == 0)
448 dns->timestamp = 1; /* zero indicates permanent CURLOPT_RESOLVE entry */
450 /* Store the resolved data in our DNS cache. */
451 dns2 = Curl_hash_add(data->dns.hostcache, entry_id, entry_len + 1,
459 dns->inuse++; /* mark entry as in-use */
464 /* return a static IPv6 resolve for 'localhost' */
465 static struct Curl_addrinfo *get_localhost6(int port)
467 struct Curl_addrinfo *ca;
468 const size_t ss_size = sizeof(struct sockaddr_in6);
469 const size_t hostlen = strlen("localhost");
470 struct sockaddr_in6 sa6;
471 unsigned char ipv6[16];
472 unsigned short port16 = (unsigned short)(port & 0xffff);
473 ca = calloc(sizeof(struct Curl_addrinfo) + ss_size + hostlen + 1, 1);
477 sa6.sin6_family = AF_INET6;
478 sa6.sin6_port = htons(port16);
479 sa6.sin6_flowinfo = 0;
480 sa6.sin6_scope_id = 0;
481 if(Curl_inet_pton(AF_INET6, "::1", ipv6) < 1)
483 memcpy(&sa6.sin6_addr, ipv6, sizeof(ipv6));
486 ca->ai_family = AF_INET6;
487 ca->ai_socktype = SOCK_STREAM;
488 ca->ai_protocol = IPPROTO_TCP;
489 ca->ai_addrlen = (curl_socklen_t)ss_size;
491 ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo));
492 memcpy(ca->ai_addr, &sa6, ss_size);
493 ca->ai_canonname = (char *)ca->ai_addr + ss_size;
494 strcpy(ca->ai_canonname, "localhost");
498 #define get_localhost6(x) NULL
501 /* return a static IPv4 resolve for 'localhost' */
502 static struct Curl_addrinfo *get_localhost(int port)
504 struct Curl_addrinfo *ca;
505 const size_t ss_size = sizeof(struct sockaddr_in);
506 const size_t hostlen = strlen("localhost");
507 struct sockaddr_in sa;
509 unsigned short port16 = (unsigned short)(port & 0xffff);
511 /* memset to clear the sa.sin_zero field */
512 memset(&sa, 0, sizeof(sa));
513 sa.sin_family = AF_INET;
514 sa.sin_port = htons(port16);
515 if(Curl_inet_pton(AF_INET, "127.0.0.1", (char *)&ipv4) < 1)
517 memcpy(&sa.sin_addr, &ipv4, sizeof(ipv4));
519 ca = calloc(sizeof(struct Curl_addrinfo) + ss_size + hostlen + 1, 1);
523 ca->ai_family = AF_INET;
524 ca->ai_socktype = SOCK_STREAM;
525 ca->ai_protocol = IPPROTO_TCP;
526 ca->ai_addrlen = (curl_socklen_t)ss_size;
527 ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo));
528 memcpy(ca->ai_addr, &sa, ss_size);
529 ca->ai_canonname = (char *)ca->ai_addr + ss_size;
530 strcpy(ca->ai_canonname, "localhost");
531 ca->ai_next = get_localhost6(port);
537 * Curl_ipv6works() returns TRUE if IPv6 seems to work.
539 bool Curl_ipv6works(struct Curl_easy *data)
542 /* the nature of most system is that IPv6 status doesn't come and go
543 during a program's lifetime so we only probe the first time and then we
544 have the info kept for fast re-use */
546 DEBUGASSERT(data->multi);
547 return data->multi->ipv6_works;
551 /* probe to see if we have a working IPv6 stack */
552 curl_socket_t s = socket(PF_INET6, SOCK_DGRAM, 0);
553 if(s == CURL_SOCKET_BAD)
554 /* an IPv6 address was requested but we can't get/use one */
560 return (ipv6_works>0)?TRUE:FALSE;
563 #endif /* ENABLE_IPV6 */
566 * Curl_host_is_ipnum() returns TRUE if the given string is a numerical IPv4
567 * (or IPv6 if supported) address.
569 bool Curl_host_is_ipnum(const char *hostname)
575 if(Curl_inet_pton(AF_INET, hostname, &in) > 0
577 || Curl_inet_pton(AF_INET6, hostname, &in6) > 0
585 * Curl_resolv() is the main name resolve function within libcurl. It resolves
586 * a name and returns a pointer to the entry in the 'entry' argument (if one
587 * is provided). This function might return immediately if we're using asynch
588 * resolves. See the return codes.
590 * The cache entry we return will get its 'inuse' counter increased when this
591 * function is used. You MUST call Curl_resolv_unlock() later (when you're
592 * done using this struct) to decrease the counter again.
596 * CURLRESOLV_ERROR (-1) = error, no pointer
597 * CURLRESOLV_RESOLVED (0) = OK, pointer provided
598 * CURLRESOLV_PENDING (1) = waiting for response, no pointer
601 enum resolve_t Curl_resolv(struct Curl_easy *data,
602 const char *hostname,
605 struct Curl_dns_entry **entry)
607 struct Curl_dns_entry *dns = NULL;
609 enum resolve_t rc = CURLRESOLV_ERROR; /* default to failure */
610 struct connectdata *conn = data->conn;
612 #ifndef CURL_DISABLE_DOH
613 conn->bits.doh = FALSE; /* default is not */
619 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
621 dns = fetch_addr(data, hostname, port);
624 infof(data, "Hostname %s was found in DNS cache", hostname);
625 dns->inuse++; /* we use it! */
626 rc = CURLRESOLV_RESOLVED;
630 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
633 /* The entry was not in the cache. Resolve it to IP address */
635 struct Curl_addrinfo *addr = NULL;
637 #if !defined(CURL_DISABLE_DOH) || !defined(USE_RESOLVE_ON_IPS)
640 #ifndef CURL_DISABLE_DOH
641 #ifndef USE_RESOLVE_ON_IPS
647 /* notify the resolver start callback */
648 if(data->set.resolver_start) {
650 Curl_set_in_callback(data, true);
651 st = data->set.resolver_start(
652 #ifdef USE_CURL_ASYNC
653 data->state.async.resolver,
658 data->set.resolver_start_client);
659 Curl_set_in_callback(data, false);
661 return CURLRESOLV_ERROR;
664 #if defined(ENABLE_IPV6) && defined(CURL_OSX_CALL_COPYPROXIES)
667 * The automagic conversion from IPv4 literals to IPv6 literals only
668 * works if the SCDynamicStoreCopyProxies system function gets called
669 * first. As Curl currently doesn't support system-wide HTTP proxies, we
670 * therefore don't use any value this function might return.
672 * This function is only available on a macOS and is not needed for
673 * IPv4-only builds, hence the conditions above.
675 CFDictionaryRef dict = SCDynamicStoreCopyProxies(NULL);
681 #ifndef USE_RESOLVE_ON_IPS
682 /* First check if this is an IPv4 address string */
683 if(Curl_inet_pton(AF_INET, hostname, &in) > 0)
684 /* This is a dotted IP address 123.123.123.123-style */
685 addr = Curl_ip2addr(AF_INET, &in, hostname, port);
689 /* check if this is an IPv6 address string */
690 if(Curl_inet_pton(AF_INET6, hostname, &in6) > 0)
691 /* This is an IPv6 address literal */
692 addr = Curl_ip2addr(AF_INET6, &in6, hostname, port);
694 #endif /* ENABLE_IPV6 */
696 #else /* if USE_RESOLVE_ON_IPS */
697 #ifndef CURL_DISABLE_DOH
698 /* First check if this is an IPv4 address string */
699 if(Curl_inet_pton(AF_INET, hostname, &in) > 0)
700 /* This is a dotted IP address 123.123.123.123-style */
705 /* check if this is an IPv6 address string */
706 if(Curl_inet_pton(AF_INET6, hostname, &in6) > 0)
707 /* This is an IPv6 address literal */
710 #endif /* ENABLE_IPV6 */
711 #endif /* CURL_DISABLE_DOH */
713 #endif /* !USE_RESOLVE_ON_IPS */
716 if(conn->ip_version == CURL_IPRESOLVE_V6 && !Curl_ipv6works(data))
717 return CURLRESOLV_ERROR;
719 if(strcasecompare(hostname, "localhost"))
720 addr = get_localhost(port);
721 #ifndef CURL_DISABLE_DOH
722 else if(allowDOH && data->set.doh && !ipnum)
723 addr = Curl_doh(data, hostname, port, &respwait);
726 /* Check what IP specifics the app has requested and if we can provide
727 * it. If not, bail out. */
728 if(!Curl_ipvalid(data, conn))
729 return CURLRESOLV_ERROR;
730 /* If Curl_getaddrinfo() returns NULL, 'respwait' might be set to a
731 non-zero value indicating that we need to wait for the response to
733 addr = Curl_getaddrinfo(data, hostname, port, &respwait);
738 /* the response to our resolve call will come asynchronously at
739 a later time, good or bad */
740 /* First, check that we haven't received the info by now */
741 result = Curl_resolv_check(data, &dns);
742 if(result) /* error detected */
743 return CURLRESOLV_ERROR;
745 rc = CURLRESOLV_RESOLVED; /* pointer provided */
747 rc = CURLRESOLV_PENDING; /* no info yet */
752 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
754 /* we got a response, store it in the cache */
755 dns = Curl_cache_addr(data, addr, hostname, port);
758 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
761 /* returned failure, bail out nicely */
762 Curl_freeaddrinfo(addr);
764 rc = CURLRESOLV_RESOLVED;
773 #ifdef USE_ALARM_TIMEOUT
775 * This signal handler jumps back into the main libcurl code and continues
776 * execution. This effectively causes the remainder of the application to run
777 * within a signal handler which is nonportable and could lead to problems.
780 void alarmfunc(int sig)
782 /* this is for "-ansi -Wall -pedantic" to stop complaining! (rabe) */
784 siglongjmp(curl_jmpenv, 1);
786 #endif /* USE_ALARM_TIMEOUT */
789 * Curl_resolv_timeout() is the same as Curl_resolv() but specifies a
790 * timeout. This function might return immediately if we're using asynch
791 * resolves. See the return codes.
793 * The cache entry we return will get its 'inuse' counter increased when this
794 * function is used. You MUST call Curl_resolv_unlock() later (when you're
795 * done using this struct) to decrease the counter again.
797 * If built with a synchronous resolver and use of signals is not
798 * disabled by the application, then a nonzero timeout will cause a
799 * timeout after the specified number of milliseconds. Otherwise, timeout
804 * CURLRESOLV_TIMEDOUT(-2) = warning, time too short or previous alarm expired
805 * CURLRESOLV_ERROR (-1) = error, no pointer
806 * CURLRESOLV_RESOLVED (0) = OK, pointer provided
807 * CURLRESOLV_PENDING (1) = waiting for response, no pointer
810 enum resolve_t Curl_resolv_timeout(struct Curl_easy *data,
811 const char *hostname,
813 struct Curl_dns_entry **entry,
814 timediff_t timeoutms)
816 #ifdef USE_ALARM_TIMEOUT
817 #ifdef HAVE_SIGACTION
818 struct sigaction keep_sigact; /* store the old struct here */
819 volatile bool keep_copysig = FALSE; /* whether old sigact has been saved */
820 struct sigaction sigact;
823 void (*keep_sigact)(int); /* store the old handler here */
824 #endif /* HAVE_SIGNAL */
825 #endif /* HAVE_SIGACTION */
826 volatile long timeout;
827 volatile unsigned int prev_alarm = 0;
828 #endif /* USE_ALARM_TIMEOUT */
834 /* got an already expired timeout */
835 return CURLRESOLV_TIMEDOUT;
837 #ifdef USE_ALARM_TIMEOUT
838 if(data->set.no_signal)
839 /* Ignore the timeout when signals are disabled */
842 timeout = (timeoutms > LONG_MAX) ? LONG_MAX : (long)timeoutms;
845 /* USE_ALARM_TIMEOUT defined, but no timeout actually requested */
846 return Curl_resolv(data, hostname, port, TRUE, entry);
849 /* The alarm() function only provides integer second resolution, so if
850 we want to wait less than one second we must bail out already now. */
852 "remaining timeout of %ld too small to resolve via SIGALRM method",
854 return CURLRESOLV_TIMEDOUT;
856 /* This allows us to time-out from the name resolver, as the timeout
857 will generate a signal and we will siglongjmp() from that here.
858 This technique has problems (see alarmfunc).
859 This should be the last thing we do before calling Curl_resolv(),
860 as otherwise we'd have to worry about variables that get modified
861 before we invoke Curl_resolv() (and thus use "volatile"). */
862 if(sigsetjmp(curl_jmpenv, 1)) {
863 /* this is coming from a siglongjmp() after an alarm signal */
864 failf(data, "name lookup timed out");
865 rc = CURLRESOLV_ERROR;
869 /*************************************************************
870 * Set signal handler to catch SIGALRM
871 * Store the old value to be able to set it back later!
872 *************************************************************/
873 #ifdef HAVE_SIGACTION
874 sigaction(SIGALRM, NULL, &sigact);
875 keep_sigact = sigact;
876 keep_copysig = TRUE; /* yes, we have a copy */
877 sigact.sa_handler = alarmfunc;
879 /* HPUX doesn't have SA_RESTART but defaults to that behavior! */
880 sigact.sa_flags &= ~SA_RESTART;
882 /* now set the new struct */
883 sigaction(SIGALRM, &sigact, NULL);
884 #else /* HAVE_SIGACTION */
885 /* no sigaction(), revert to the much lamer signal() */
887 keep_sigact = signal(SIGALRM, alarmfunc);
889 #endif /* HAVE_SIGACTION */
891 /* alarm() makes a signal get sent when the timeout fires off, and that
892 will abort system calls */
893 prev_alarm = alarm(curlx_sltoui(timeout/1000L));
897 #ifndef CURLRES_ASYNCH
899 infof(data, "timeout on name lookup is not supported");
901 (void)timeoutms; /* timeoutms not used with an async resolver */
903 #endif /* USE_ALARM_TIMEOUT */
905 /* Perform the actual name resolution. This might be interrupted by an
906 * alarm if it takes too long.
908 rc = Curl_resolv(data, hostname, port, TRUE, entry);
910 #ifdef USE_ALARM_TIMEOUT
914 /* deactivate a possibly active alarm before uninstalling the handler */
917 #ifdef HAVE_SIGACTION
919 /* we got a struct as it looked before, now put that one back nice
921 sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */
925 /* restore the previous SIGALRM handler */
926 signal(SIGALRM, keep_sigact);
928 #endif /* HAVE_SIGACTION */
930 /* switch back the alarm() to either zero or to what it was before minus
931 the time we spent until now! */
933 /* there was an alarm() set before us, now put it back */
934 timediff_t elapsed_secs = Curl_timediff(Curl_now(),
935 data->conn->created) / 1000;
937 /* the alarm period is counted in even number of seconds */
938 unsigned long alarm_set = (unsigned long)(prev_alarm - elapsed_secs);
941 ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) {
942 /* if the alarm time-left reached zero or turned "negative" (counted
943 with unsigned values), we should fire off a SIGALRM here, but we
944 won't, and zero would be to switch it off so we never set it to
947 rc = CURLRESOLV_TIMEDOUT;
948 failf(data, "Previous alarm fired off");
951 alarm((unsigned int)alarm_set);
953 #endif /* USE_ALARM_TIMEOUT */
959 * Curl_resolv_unlock() unlocks the given cached DNS entry. When this has been
960 * made, the struct may be destroyed due to pruning. It is important that only
961 * one unlock is made for each Curl_resolv() call.
963 * May be called with 'data' == NULL for global cache.
965 void Curl_resolv_unlock(struct Curl_easy *data, struct Curl_dns_entry *dns)
967 if(data && data->share)
968 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
972 if(data && data->share)
973 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
977 * File-internal: release cache dns entry reference, free if inuse drops to 0
979 static void freednsentry(void *freethis)
981 struct Curl_dns_entry *dns = (struct Curl_dns_entry *) freethis;
982 DEBUGASSERT(dns && (dns->inuse>0));
985 if(dns->inuse == 0) {
986 Curl_freeaddrinfo(dns->addr);
992 * Curl_init_dnscache() inits a new DNS cache.
994 void Curl_init_dnscache(struct Curl_hash *hash)
996 Curl_hash_init(hash, 7, Curl_hash_str, Curl_str_key_compare,
1001 * Curl_hostcache_clean()
1003 * This _can_ be called with 'data' == NULL but then of course no locking
1007 void Curl_hostcache_clean(struct Curl_easy *data,
1008 struct Curl_hash *hash)
1010 if(data && data->share)
1011 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
1013 Curl_hash_clean(hash);
1015 if(data && data->share)
1016 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
1020 CURLcode Curl_loadhostpairs(struct Curl_easy *data)
1022 struct curl_slist *hostp;
1026 /* Default is no wildcard found */
1027 data->state.wildcard_resolve = false;
1029 for(hostp = data->state.resolve; hostp; hostp = hostp->next) {
1030 char entry_id[MAX_HOSTCACHE_LEN];
1033 if(hostp->data[0] == '-') {
1036 if(2 != sscanf(hostp->data + 1, "%255[^:]:%d", hostname, &port)) {
1037 infof(data, "Couldn't parse CURLOPT_RESOLVE removal entry '%s'",
1042 /* Create an entry id, based upon the hostname and port */
1043 create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
1044 entry_len = strlen(entry_id);
1047 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
1049 /* delete entry, ignore if it didn't exist */
1050 Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
1053 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
1056 struct Curl_dns_entry *dns;
1057 struct Curl_addrinfo *head = NULL, *tail = NULL;
1060 #if !defined(CURL_DISABLE_VERBOSE_STRINGS)
1061 char *addresses = NULL;
1067 bool permanent = TRUE;
1070 unsigned long tmp_port;
1073 host_begin = hostp->data;
1074 if(host_begin[0] == '+') {
1078 host_end = strchr(host_begin, ':');
1080 ((host_end - host_begin) >= (ptrdiff_t)sizeof(hostname)))
1083 memcpy(hostname, host_begin, host_end - host_begin);
1084 hostname[host_end - host_begin] = '\0';
1086 port_ptr = host_end + 1;
1087 tmp_port = strtoul(port_ptr, &end_ptr, 10);
1088 if(tmp_port > USHRT_MAX || end_ptr == port_ptr || *end_ptr != ':')
1091 port = (int)tmp_port;
1092 #if !defined(CURL_DISABLE_VERBOSE_STRINGS)
1093 addresses = end_ptr + 1;
1098 struct Curl_addrinfo *ai;
1100 addr_begin = end_ptr + 1;
1101 addr_end = strchr(addr_begin, ',');
1103 addr_end = addr_begin + strlen(addr_begin);
1106 /* allow IP(v6) address within [brackets] */
1107 if(*addr_begin == '[') {
1108 if(addr_end == addr_begin || *(addr_end - 1) != ']')
1114 alen = addr_end - addr_begin;
1118 if(alen >= sizeof(address))
1121 memcpy(address, addr_begin, alen);
1122 address[alen] = '\0';
1125 if(strchr(address, ':')) {
1126 infof(data, "Ignoring resolve address '%s', missing IPv6 support.",
1132 ai = Curl_str2addr(address, port);
1134 infof(data, "Resolve address '%s' found illegal", address);
1140 tail = tail->ai_next;
1153 failf(data, "Couldn't parse CURLOPT_RESOLVE entry '%s'",
1155 Curl_freeaddrinfo(head);
1156 return CURLE_SETOPT_OPTION_SYNTAX;
1159 /* Create an entry id, based upon the hostname and port */
1160 create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
1161 entry_len = strlen(entry_id);
1164 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
1166 /* See if it's already in our dns cache */
1167 dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
1170 infof(data, "RESOLVE %s:%d is - old addresses discarded",
1172 /* delete old entry, there are two reasons for this
1173 1. old entry may have different addresses.
1174 2. even if entry with correct addresses is already in the cache,
1175 but if it is close to expire, then by the time next http
1176 request is made, it can get expired and pruned because old
1177 entry is not necessarily marked as permanent.
1178 3. when adding a non-permanent entry, we want it to remove and
1179 replace an existing permanent entry.
1180 4. when adding a non-permanent entry, we want it to get a "fresh"
1181 timeout that starts _now_. */
1183 Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
1186 /* put this new host in the cache */
1187 dns = Curl_cache_addr(data, head, hostname, port);
1190 dns->timestamp = 0; /* mark as permanent */
1191 /* release the returned reference; the cache itself will keep the
1197 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
1200 Curl_freeaddrinfo(head);
1201 return CURLE_OUT_OF_MEMORY;
1203 infof(data, "Added %s:%d:%s to DNS cache%s",
1204 hostname, port, addresses, permanent ? "" : " (non-permanent)");
1206 /* Wildcard hostname */
1207 if(hostname[0] == '*' && hostname[1] == '\0') {
1208 infof(data, "RESOLVE %s:%d is wildcard, enabling wildcard checks",
1210 data->state.wildcard_resolve = true;
1214 data->state.resolve = NULL; /* dealt with now */
1219 CURLcode Curl_resolv_check(struct Curl_easy *data,
1220 struct Curl_dns_entry **dns)
1222 #if defined(CURL_DISABLE_DOH) && !defined(CURLRES_ASYNCH)
1226 #ifndef CURL_DISABLE_DOH
1227 if(data->conn->bits.doh)
1228 return Curl_doh_is_resolved(data, dns);
1230 return Curl_resolver_is_resolved(data, dns);
1233 int Curl_resolv_getsock(struct Curl_easy *data,
1234 curl_socket_t *socks)
1236 #ifdef CURLRES_ASYNCH
1237 #ifndef CURL_DISABLE_DOH
1238 if(data->conn->bits.doh)
1239 /* nothing to wait for during DoH resolve, those handles have their own
1241 return GETSOCK_BLANK;
1243 return Curl_resolver_getsock(data, socks);
1247 return GETSOCK_BLANK;
1251 /* Call this function after Curl_connect() has returned async=TRUE and
1252 then a successful name resolve has been received.
1254 Note: this function disconnects and frees the conn data in case of
1256 CURLcode Curl_once_resolved(struct Curl_easy *data, bool *protocol_done)
1259 struct connectdata *conn = data->conn;
1261 #ifdef USE_CURL_ASYNC
1262 if(data->state.async.dns) {
1263 conn->dns_entry = data->state.async.dns;
1264 data->state.async.dns = NULL;
1268 result = Curl_setup_conn(data, protocol_done);
1271 Curl_detach_connection(data);
1272 Curl_conncache_remove_conn(data, conn, TRUE);
1273 Curl_disconnect(data, conn, TRUE);
1279 * Curl_resolver_error() calls failf() with the appropriate message after a
1283 #ifdef USE_CURL_ASYNC
1284 CURLcode Curl_resolver_error(struct Curl_easy *data)
1286 const char *host_or_proxy;
1289 #ifndef CURL_DISABLE_PROXY
1290 struct connectdata *conn = data->conn;
1291 if(conn->bits.httpproxy) {
1292 host_or_proxy = "proxy";
1293 result = CURLE_COULDNT_RESOLVE_PROXY;
1298 host_or_proxy = "host";
1299 result = CURLE_COULDNT_RESOLVE_HOST;
1302 failf(data, "Could not resolve %s: %s", host_or_proxy,
1303 data->state.async.hostname);
1307 #endif /* USE_CURL_ASYNC */