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 * SPDX-License-Identifier: curl
23 ***************************************************************************/
25 #include "curl_setup.h"
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
30 #ifdef HAVE_NETINET_IN6_H
31 #include <netinet/in6.h>
36 #ifdef HAVE_ARPA_INET_H
37 #include <arpa/inet.h>
62 #include "inet_ntop.h"
63 #include "inet_pton.h"
68 /* The last 3 #include files should be in this order */
69 #include "curl_printf.h"
70 #include "curl_memory.h"
73 #if defined(ENABLE_IPV6) && defined(CURL_OSX_CALL_COPYPROXIES)
74 #include <SystemConfiguration/SCDynamicStoreCopySpecific.h>
77 #if defined(CURLRES_SYNCH) && \
78 defined(HAVE_ALARM) && defined(SIGALRM) && defined(HAVE_SIGSETJMP)
79 /* alarm-based timeouts can only be used with all the dependencies satisfied */
80 #define USE_ALARM_TIMEOUT
83 #define MAX_HOSTCACHE_LEN (255 + 7) /* max FQDN + colon + port number + zero */
89 * The main COMPILE-TIME DEFINES to keep in mind when reading the host*.c
90 * source file are these:
92 * CURLRES_IPV6 - this host has getaddrinfo() and family, and thus we use
93 * that. The host may not be able to resolve IPv6, but we don't really have to
94 * take that into account. Hosts that aren't IPv6-enabled have CURLRES_IPV4
97 * CURLRES_ARES - is defined if libcurl is built to use c-ares for
98 * asynchronous name resolves. This can be Windows or *nix.
100 * CURLRES_THREADED - is defined if libcurl is built to run under (native)
101 * Windows, and then the name resolve will be done in a new thread, and the
102 * supported API will be the same as for ares-builds.
104 * If any of the two previous are defined, CURLRES_ASYNCH is defined too. If
105 * libcurl is not built to use an asynchronous resolver, CURLRES_SYNCH is
108 * The host*.c sources files are split up like this:
110 * hostip.c - method-independent resolver functions and utility functions
111 * hostasyn.c - functions for asynchronous name resolves
112 * hostsyn.c - functions for synchronous name resolves
113 * hostip4.c - IPv4 specific functions
114 * hostip6.c - IPv6 specific functions
116 * The two asynchronous name resolver backends are implemented in:
117 * asyn-ares.c - functions for ares-using name resolves
118 * asyn-thread.c - functions for threaded name resolves
120 * The hostip.h is the united header file for all this. It defines the
121 * CURLRES_* defines based on the config*.h and curl_setup.h defines.
124 static void freednsentry(void *freethis);
127 * Return # of addresses in a Curl_addrinfo struct
129 int Curl_num_addresses(const struct Curl_addrinfo *addr)
133 addr = addr->ai_next;
140 * Curl_printable_address() stores a printable version of the 1st address
141 * given in the 'ai' argument. The result will be stored in the buf that is
144 * If the conversion fails, the target buffer is empty.
146 void Curl_printable_address(const struct Curl_addrinfo *ai, char *buf,
149 DEBUGASSERT(bufsize);
152 switch(ai->ai_family) {
154 const struct sockaddr_in *sa4 = (const void *)ai->ai_addr;
155 const struct in_addr *ipaddr4 = &sa4->sin_addr;
156 (void)Curl_inet_ntop(ai->ai_family, (const void *)ipaddr4, buf, bufsize);
161 const struct sockaddr_in6 *sa6 = (const void *)ai->ai_addr;
162 const struct in6_addr *ipaddr6 = &sa6->sin6_addr;
163 (void)Curl_inet_ntop(ai->ai_family, (const void *)ipaddr6, buf, bufsize);
173 * Create a hostcache id string for the provided host + port, to be used by
174 * the DNS caching. Without alloc.
177 create_hostcache_id(const char *name, int port, char *ptr, size_t buflen)
179 size_t len = strlen(name);
180 if(len > (buflen - 7))
182 /* store and lower case the name */
184 *ptr++ = Curl_raw_tolower(*name++);
185 msnprintf(ptr, 7, ":%u", port);
188 struct hostcache_prune_data {
194 * This function is set as a callback to be called for every entry in the DNS
195 * cache when we want to prune old unused entries.
197 * Returning non-zero means remove the entry, return 0 to keep it in the
201 hostcache_timestamp_remove(void *datap, void *hc)
203 struct hostcache_prune_data *data =
204 (struct hostcache_prune_data *) datap;
205 struct Curl_dns_entry *c = (struct Curl_dns_entry *) hc;
207 return (0 != c->timestamp)
208 && (data->now - c->timestamp >= data->cache_timeout);
212 * Prune the DNS cache. This assumes that a lock has already been taken.
215 hostcache_prune(struct Curl_hash *hostcache, long cache_timeout, time_t now)
217 struct hostcache_prune_data user;
219 user.cache_timeout = cache_timeout;
222 Curl_hash_clean_with_criterium(hostcache,
224 hostcache_timestamp_remove);
228 * Library-wide function for pruning the DNS cache. This function takes and
229 * returns the appropriate locks.
231 void Curl_hostcache_prune(struct Curl_easy *data)
235 if((data->set.dns_cache_timeout == -1) || !data->dns.hostcache)
236 /* cache forever means never prune, and NULL hostcache means
241 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
245 /* Remove outdated and unused entries from the hostcache */
246 hostcache_prune(data->dns.hostcache,
247 data->set.dns_cache_timeout,
251 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
254 #ifdef HAVE_SIGSETJMP
255 /* Beware this is a global and unique instance. This is used to store the
256 return address that we can jump back to from inside a signal handler. This
257 is not thread-safe stuff. */
258 sigjmp_buf curl_jmpenv;
261 /* lookup address, returns entry if found and not stale */
262 static struct Curl_dns_entry *fetch_addr(struct Curl_easy *data,
263 const char *hostname,
266 struct Curl_dns_entry *dns = NULL;
268 char entry_id[MAX_HOSTCACHE_LEN];
270 /* Create an entry id, based upon the hostname and port */
271 create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
272 entry_len = strlen(entry_id);
274 /* See if its already in our dns cache */
275 dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
277 /* No entry found in cache, check if we might have a wildcard entry */
278 if(!dns && data->state.wildcard_resolve) {
279 create_hostcache_id("*", port, entry_id, sizeof(entry_id));
280 entry_len = strlen(entry_id);
282 /* See if it's already in our dns cache */
283 dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
286 if(dns && (data->set.dns_cache_timeout != -1)) {
287 /* See whether the returned entry is stale. Done before we release lock */
288 struct hostcache_prune_data user;
291 user.cache_timeout = data->set.dns_cache_timeout;
293 if(hostcache_timestamp_remove(&user, dns)) {
294 infof(data, "Hostname in DNS cache was stale, zapped");
295 dns = NULL; /* the memory deallocation is being handled by the hash */
296 Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
300 /* See if the returned entry matches the required resolve mode */
301 if(dns && data->conn->ip_version != CURL_IPRESOLVE_WHATEVER) {
304 struct Curl_addrinfo *addr = dns->addr;
307 if(data->conn->ip_version == CURL_IPRESOLVE_V6)
312 if(addr->ai_family == pf) {
316 addr = addr->ai_next;
320 infof(data, "Hostname in DNS cache doesn't have needed family, zapped");
321 dns = NULL; /* the memory deallocation is being handled by the hash */
322 Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
329 * Curl_fetch_addr() fetches a 'Curl_dns_entry' already in the DNS cache.
331 * Curl_resolv() checks initially and multi_runsingle() checks each time
332 * it discovers the handle in the state WAITRESOLVE whether the hostname
333 * has already been resolved and the address has already been stored in
334 * the DNS cache. This short circuits waiting for a lot of pending
335 * lookups for the same hostname requested by different handles.
337 * Returns the Curl_dns_entry entry pointer or NULL if not in the cache.
339 * The returned data *MUST* be "unlocked" with Curl_resolv_unlock() after
340 * use, or we'll leak memory!
342 struct Curl_dns_entry *
343 Curl_fetch_addr(struct Curl_easy *data,
344 const char *hostname,
347 struct Curl_dns_entry *dns = NULL;
350 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
352 dns = fetch_addr(data, hostname, port);
355 dns->inuse++; /* we use it! */
358 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
363 #ifndef CURL_DISABLE_SHUFFLE_DNS
364 UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data,
365 struct Curl_addrinfo **addr);
367 * Curl_shuffle_addr() shuffles the order of addresses in a 'Curl_addrinfo'
368 * struct by re-linking its linked list.
370 * The addr argument should be the address of a pointer to the head node of a
371 * `Curl_addrinfo` list and it will be modified to point to the new head after
374 * Not declared static only to make it easy to use in a unit test!
378 UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data,
379 struct Curl_addrinfo **addr)
381 CURLcode result = CURLE_OK;
382 const int num_addrs = Curl_num_addresses(*addr);
385 struct Curl_addrinfo **nodes;
386 infof(data, "Shuffling %i addresses", num_addrs);
388 nodes = malloc(num_addrs*sizeof(*nodes));
392 const size_t rnd_size = num_addrs * sizeof(*rnd);
394 /* build a plain array of Curl_addrinfo pointers */
396 for(i = 1; i < num_addrs; i++) {
397 nodes[i] = nodes[i-1]->ai_next;
400 rnd = malloc(rnd_size);
402 /* Fisher-Yates shuffle */
403 if(Curl_rand(data, (unsigned char *)rnd, rnd_size) == CURLE_OK) {
404 struct Curl_addrinfo *swap_tmp;
405 for(i = num_addrs - 1; i > 0; i--) {
406 swap_tmp = nodes[rnd[i] % (i + 1)];
407 nodes[rnd[i] % (i + 1)] = nodes[i];
411 /* relink list in the new order */
412 for(i = 1; i < num_addrs; i++) {
413 nodes[i-1]->ai_next = nodes[i];
416 nodes[num_addrs-1]->ai_next = NULL;
422 result = CURLE_OUT_OF_MEMORY;
426 result = CURLE_OUT_OF_MEMORY;
433 * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache.
435 * When calling Curl_resolv() has resulted in a response with a returned
436 * address, we call this function to store the information in the dns
439 * Returns the Curl_dns_entry entry pointer or NULL if the storage failed.
441 struct Curl_dns_entry *
442 Curl_cache_addr(struct Curl_easy *data,
443 struct Curl_addrinfo *addr,
444 const char *hostname,
447 char entry_id[MAX_HOSTCACHE_LEN];
449 struct Curl_dns_entry *dns;
450 struct Curl_dns_entry *dns2;
452 #ifndef CURL_DISABLE_SHUFFLE_DNS
453 /* shuffle addresses if requested */
454 if(data->set.dns_shuffle_addresses) {
455 CURLcode result = Curl_shuffle_addr(data, &addr);
461 /* Create a new cache entry */
462 dns = calloc(1, sizeof(struct Curl_dns_entry));
467 /* Create an entry id, based upon the hostname and port */
468 create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
469 entry_len = strlen(entry_id);
471 dns->inuse = 1; /* the cache has the first reference */
472 dns->addr = addr; /* this is the address(es) */
473 time(&dns->timestamp);
474 if(dns->timestamp == 0)
475 dns->timestamp = 1; /* zero indicates permanent CURLOPT_RESOLVE entry */
477 /* Store the resolved data in our DNS cache. */
478 dns2 = Curl_hash_add(data->dns.hostcache, entry_id, entry_len + 1,
486 dns->inuse++; /* mark entry as in-use */
491 /* return a static IPv6 ::1 for the name */
492 static struct Curl_addrinfo *get_localhost6(int port, const char *name)
494 struct Curl_addrinfo *ca;
495 const size_t ss_size = sizeof(struct sockaddr_in6);
496 const size_t hostlen = strlen(name);
497 struct sockaddr_in6 sa6;
498 unsigned char ipv6[16];
499 unsigned short port16 = (unsigned short)(port & 0xffff);
500 ca = calloc(sizeof(struct Curl_addrinfo) + ss_size + hostlen + 1, 1);
504 sa6.sin6_family = AF_INET6;
505 sa6.sin6_port = htons(port16);
506 sa6.sin6_flowinfo = 0;
507 sa6.sin6_scope_id = 0;
508 if(Curl_inet_pton(AF_INET6, "::1", ipv6) < 1)
510 memcpy(&sa6.sin6_addr, ipv6, sizeof(ipv6));
513 ca->ai_family = AF_INET6;
514 ca->ai_socktype = SOCK_STREAM;
515 ca->ai_protocol = IPPROTO_TCP;
516 ca->ai_addrlen = (curl_socklen_t)ss_size;
518 ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo));
519 memcpy(ca->ai_addr, &sa6, ss_size);
520 ca->ai_canonname = (char *)ca->ai_addr + ss_size;
521 strcpy(ca->ai_canonname, name);
525 #define get_localhost6(x,y) NULL
528 /* return a static IPv4 127.0.0.1 for the given name */
529 static struct Curl_addrinfo *get_localhost(int port, const char *name)
531 struct Curl_addrinfo *ca;
532 const size_t ss_size = sizeof(struct sockaddr_in);
533 const size_t hostlen = strlen(name);
534 struct sockaddr_in sa;
536 unsigned short port16 = (unsigned short)(port & 0xffff);
538 /* memset to clear the sa.sin_zero field */
539 memset(&sa, 0, sizeof(sa));
540 sa.sin_family = AF_INET;
541 sa.sin_port = htons(port16);
542 if(Curl_inet_pton(AF_INET, "127.0.0.1", (char *)&ipv4) < 1)
544 memcpy(&sa.sin_addr, &ipv4, sizeof(ipv4));
546 ca = calloc(sizeof(struct Curl_addrinfo) + ss_size + hostlen + 1, 1);
550 ca->ai_family = AF_INET;
551 ca->ai_socktype = SOCK_STREAM;
552 ca->ai_protocol = IPPROTO_TCP;
553 ca->ai_addrlen = (curl_socklen_t)ss_size;
554 ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo));
555 memcpy(ca->ai_addr, &sa, ss_size);
556 ca->ai_canonname = (char *)ca->ai_addr + ss_size;
557 strcpy(ca->ai_canonname, name);
558 ca->ai_next = get_localhost6(port, name);
564 * Curl_ipv6works() returns TRUE if IPv6 seems to work.
566 bool Curl_ipv6works(struct Curl_easy *data)
569 /* the nature of most system is that IPv6 status doesn't come and go
570 during a program's lifetime so we only probe the first time and then we
571 have the info kept for fast re-use */
573 DEBUGASSERT(data->multi);
574 if(data->multi->ipv6_up == IPV6_UNKNOWN) {
575 bool works = Curl_ipv6works(NULL);
576 data->multi->ipv6_up = works ? IPV6_WORKS : IPV6_DEAD;
578 return data->multi->ipv6_up == IPV6_WORKS;
582 /* probe to see if we have a working IPv6 stack */
583 curl_socket_t s = socket(PF_INET6, SOCK_DGRAM, 0);
584 if(s == CURL_SOCKET_BAD)
585 /* an IPv6 address was requested but we can't get/use one */
591 return (ipv6_works>0)?TRUE:FALSE;
594 #endif /* ENABLE_IPV6 */
597 * Curl_host_is_ipnum() returns TRUE if the given string is a numerical IPv4
598 * (or IPv6 if supported) address.
600 bool Curl_host_is_ipnum(const char *hostname)
606 if(Curl_inet_pton(AF_INET, hostname, &in) > 0
608 || Curl_inet_pton(AF_INET6, hostname, &in6) > 0
616 /* return TRUE if 'part' is a case insensitive tail of 'full' */
617 static bool tailmatch(const char *full, const char *part)
619 size_t plen = strlen(part);
620 size_t flen = strlen(full);
623 return strncasecompare(part, &full[flen - plen], plen);
627 * Curl_resolv() is the main name resolve function within libcurl. It resolves
628 * a name and returns a pointer to the entry in the 'entry' argument (if one
629 * is provided). This function might return immediately if we're using asynch
630 * resolves. See the return codes.
632 * The cache entry we return will get its 'inuse' counter increased when this
633 * function is used. You MUST call Curl_resolv_unlock() later (when you're
634 * done using this struct) to decrease the counter again.
638 * CURLRESOLV_ERROR (-1) = error, no pointer
639 * CURLRESOLV_RESOLVED (0) = OK, pointer provided
640 * CURLRESOLV_PENDING (1) = waiting for response, no pointer
643 enum resolve_t Curl_resolv(struct Curl_easy *data,
644 const char *hostname,
647 struct Curl_dns_entry **entry)
649 struct Curl_dns_entry *dns = NULL;
651 enum resolve_t rc = CURLRESOLV_ERROR; /* default to failure */
652 struct connectdata *conn = data->conn;
654 #ifndef CURL_DISABLE_DOH
655 conn->bits.doh = FALSE; /* default is not */
661 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
663 dns = fetch_addr(data, hostname, port);
666 infof(data, "Hostname %s was found in DNS cache", hostname);
667 dns->inuse++; /* we use it! */
668 rc = CURLRESOLV_RESOLVED;
672 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
675 /* The entry was not in the cache. Resolve it to IP address */
677 struct Curl_addrinfo *addr = NULL;
679 #if !defined(CURL_DISABLE_DOH) || !defined(USE_RESOLVE_ON_IPS)
682 #ifndef CURL_DISABLE_DOH
683 #ifndef USE_RESOLVE_ON_IPS
689 /* notify the resolver start callback */
690 if(data->set.resolver_start) {
692 Curl_set_in_callback(data, true);
693 st = data->set.resolver_start(
694 #ifdef USE_CURL_ASYNC
695 data->state.async.resolver,
700 data->set.resolver_start_client);
701 Curl_set_in_callback(data, false);
703 return CURLRESOLV_ERROR;
706 #if defined(ENABLE_IPV6) && defined(CURL_OSX_CALL_COPYPROXIES)
709 * The automagic conversion from IPv4 literals to IPv6 literals only
710 * works if the SCDynamicStoreCopyProxies system function gets called
711 * first. As Curl currently doesn't support system-wide HTTP proxies, we
712 * therefore don't use any value this function might return.
714 * This function is only available on a macOS and is not needed for
715 * IPv4-only builds, hence the conditions above.
717 CFDictionaryRef dict = SCDynamicStoreCopyProxies(NULL);
723 #ifndef USE_RESOLVE_ON_IPS
724 /* First check if this is an IPv4 address string */
725 if(Curl_inet_pton(AF_INET, hostname, &in) > 0)
726 /* This is a dotted IP address 123.123.123.123-style */
727 addr = Curl_ip2addr(AF_INET, &in, hostname, port);
731 /* check if this is an IPv6 address string */
732 if(Curl_inet_pton(AF_INET6, hostname, &in6) > 0)
733 /* This is an IPv6 address literal */
734 addr = Curl_ip2addr(AF_INET6, &in6, hostname, port);
736 #endif /* ENABLE_IPV6 */
738 #else /* if USE_RESOLVE_ON_IPS */
739 #ifndef CURL_DISABLE_DOH
740 /* First check if this is an IPv4 address string */
741 if(Curl_inet_pton(AF_INET, hostname, &in) > 0)
742 /* This is a dotted IP address 123.123.123.123-style */
747 /* check if this is an IPv6 address string */
748 if(Curl_inet_pton(AF_INET6, hostname, &in6) > 0)
749 /* This is an IPv6 address literal */
752 #endif /* ENABLE_IPV6 */
753 #endif /* CURL_DISABLE_DOH */
755 #endif /* !USE_RESOLVE_ON_IPS */
758 if(conn->ip_version == CURL_IPRESOLVE_V6 && !Curl_ipv6works(data))
759 return CURLRESOLV_ERROR;
761 if(strcasecompare(hostname, "localhost") ||
762 tailmatch(hostname, ".localhost"))
763 addr = get_localhost(port, hostname);
764 #ifndef CURL_DISABLE_DOH
765 else if(allowDOH && data->set.doh && !ipnum)
766 addr = Curl_doh(data, hostname, port, &respwait);
769 /* Check what IP specifics the app has requested and if we can provide
770 * it. If not, bail out. */
771 if(!Curl_ipvalid(data, conn))
772 return CURLRESOLV_ERROR;
773 /* If Curl_getaddrinfo() returns NULL, 'respwait' might be set to a
774 non-zero value indicating that we need to wait for the response to
776 addr = Curl_getaddrinfo(data, hostname, port, &respwait);
781 /* the response to our resolve call will come asynchronously at
782 a later time, good or bad */
783 /* First, check that we haven't received the info by now */
784 result = Curl_resolv_check(data, &dns);
785 if(result) /* error detected */
786 return CURLRESOLV_ERROR;
788 rc = CURLRESOLV_RESOLVED; /* pointer provided */
790 rc = CURLRESOLV_PENDING; /* no info yet */
795 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
797 /* we got a response, store it in the cache */
798 dns = Curl_cache_addr(data, addr, hostname, port);
801 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
804 /* returned failure, bail out nicely */
805 Curl_freeaddrinfo(addr);
807 rc = CURLRESOLV_RESOLVED;
816 #ifdef USE_ALARM_TIMEOUT
818 * This signal handler jumps back into the main libcurl code and continues
819 * execution. This effectively causes the remainder of the application to run
820 * within a signal handler which is nonportable and could lead to problems.
823 void alarmfunc(int sig)
825 /* this is for "-ansi -Wall -pedantic" to stop complaining! (rabe) */
827 siglongjmp(curl_jmpenv, 1);
829 #endif /* USE_ALARM_TIMEOUT */
832 * Curl_resolv_timeout() is the same as Curl_resolv() but specifies a
833 * timeout. This function might return immediately if we're using asynch
834 * resolves. See the return codes.
836 * The cache entry we return will get its 'inuse' counter increased when this
837 * function is used. You MUST call Curl_resolv_unlock() later (when you're
838 * done using this struct) to decrease the counter again.
840 * If built with a synchronous resolver and use of signals is not
841 * disabled by the application, then a nonzero timeout will cause a
842 * timeout after the specified number of milliseconds. Otherwise, timeout
847 * CURLRESOLV_TIMEDOUT(-2) = warning, time too short or previous alarm expired
848 * CURLRESOLV_ERROR (-1) = error, no pointer
849 * CURLRESOLV_RESOLVED (0) = OK, pointer provided
850 * CURLRESOLV_PENDING (1) = waiting for response, no pointer
853 enum resolve_t Curl_resolv_timeout(struct Curl_easy *data,
854 const char *hostname,
856 struct Curl_dns_entry **entry,
857 timediff_t timeoutms)
859 #ifdef USE_ALARM_TIMEOUT
860 #ifdef HAVE_SIGACTION
861 struct sigaction keep_sigact; /* store the old struct here */
862 volatile bool keep_copysig = FALSE; /* whether old sigact has been saved */
863 struct sigaction sigact;
866 void (*keep_sigact)(int); /* store the old handler here */
867 #endif /* HAVE_SIGNAL */
868 #endif /* HAVE_SIGACTION */
869 volatile long timeout;
870 volatile unsigned int prev_alarm = 0;
871 #endif /* USE_ALARM_TIMEOUT */
877 /* got an already expired timeout */
878 return CURLRESOLV_TIMEDOUT;
880 #ifdef USE_ALARM_TIMEOUT
881 if(data->set.no_signal)
882 /* Ignore the timeout when signals are disabled */
885 timeout = (timeoutms > LONG_MAX) ? LONG_MAX : (long)timeoutms;
888 /* USE_ALARM_TIMEOUT defined, but no timeout actually requested */
889 return Curl_resolv(data, hostname, port, TRUE, entry);
892 /* The alarm() function only provides integer second resolution, so if
893 we want to wait less than one second we must bail out already now. */
895 "remaining timeout of %ld too small to resolve via SIGALRM method",
897 return CURLRESOLV_TIMEDOUT;
899 /* This allows us to time-out from the name resolver, as the timeout
900 will generate a signal and we will siglongjmp() from that here.
901 This technique has problems (see alarmfunc).
902 This should be the last thing we do before calling Curl_resolv(),
903 as otherwise we'd have to worry about variables that get modified
904 before we invoke Curl_resolv() (and thus use "volatile"). */
905 if(sigsetjmp(curl_jmpenv, 1)) {
906 /* this is coming from a siglongjmp() after an alarm signal */
907 failf(data, "name lookup timed out");
908 rc = CURLRESOLV_ERROR;
912 /*************************************************************
913 * Set signal handler to catch SIGALRM
914 * Store the old value to be able to set it back later!
915 *************************************************************/
916 #ifdef HAVE_SIGACTION
917 sigaction(SIGALRM, NULL, &sigact);
918 keep_sigact = sigact;
919 keep_copysig = TRUE; /* yes, we have a copy */
920 sigact.sa_handler = alarmfunc;
922 /* HPUX doesn't have SA_RESTART but defaults to that behavior! */
923 sigact.sa_flags &= ~SA_RESTART;
925 /* now set the new struct */
926 sigaction(SIGALRM, &sigact, NULL);
927 #else /* HAVE_SIGACTION */
928 /* no sigaction(), revert to the much lamer signal() */
930 keep_sigact = signal(SIGALRM, alarmfunc);
932 #endif /* HAVE_SIGACTION */
934 /* alarm() makes a signal get sent when the timeout fires off, and that
935 will abort system calls */
936 prev_alarm = alarm(curlx_sltoui(timeout/1000L));
940 #ifndef CURLRES_ASYNCH
942 infof(data, "timeout on name lookup is not supported");
944 (void)timeoutms; /* timeoutms not used with an async resolver */
946 #endif /* USE_ALARM_TIMEOUT */
948 /* Perform the actual name resolution. This might be interrupted by an
949 * alarm if it takes too long.
951 rc = Curl_resolv(data, hostname, port, TRUE, entry);
953 #ifdef USE_ALARM_TIMEOUT
957 /* deactivate a possibly active alarm before uninstalling the handler */
960 #ifdef HAVE_SIGACTION
962 /* we got a struct as it looked before, now put that one back nice
964 sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */
968 /* restore the previous SIGALRM handler */
969 signal(SIGALRM, keep_sigact);
971 #endif /* HAVE_SIGACTION */
973 /* switch back the alarm() to either zero or to what it was before minus
974 the time we spent until now! */
976 /* there was an alarm() set before us, now put it back */
977 timediff_t elapsed_secs = Curl_timediff(Curl_now(),
978 data->conn->created) / 1000;
980 /* the alarm period is counted in even number of seconds */
981 unsigned long alarm_set = (unsigned long)(prev_alarm - elapsed_secs);
984 ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) {
985 /* if the alarm time-left reached zero or turned "negative" (counted
986 with unsigned values), we should fire off a SIGALRM here, but we
987 won't, and zero would be to switch it off so we never set it to
990 rc = CURLRESOLV_TIMEDOUT;
991 failf(data, "Previous alarm fired off");
994 alarm((unsigned int)alarm_set);
996 #endif /* USE_ALARM_TIMEOUT */
1002 * Curl_resolv_unlock() unlocks the given cached DNS entry. When this has been
1003 * made, the struct may be destroyed due to pruning. It is important that only
1004 * one unlock is made for each Curl_resolv() call.
1006 * May be called with 'data' == NULL for global cache.
1008 void Curl_resolv_unlock(struct Curl_easy *data, struct Curl_dns_entry *dns)
1010 if(data && data->share)
1011 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
1015 if(data && data->share)
1016 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
1020 * File-internal: release cache dns entry reference, free if inuse drops to 0
1022 static void freednsentry(void *freethis)
1024 struct Curl_dns_entry *dns = (struct Curl_dns_entry *) freethis;
1025 DEBUGASSERT(dns && (dns->inuse>0));
1028 if(dns->inuse == 0) {
1029 Curl_freeaddrinfo(dns->addr);
1035 * Curl_init_dnscache() inits a new DNS cache.
1037 void Curl_init_dnscache(struct Curl_hash *hash, int size)
1039 Curl_hash_init(hash, size, Curl_hash_str, Curl_str_key_compare,
1044 * Curl_hostcache_clean()
1046 * This _can_ be called with 'data' == NULL but then of course no locking
1050 void Curl_hostcache_clean(struct Curl_easy *data,
1051 struct Curl_hash *hash)
1053 if(data && data->share)
1054 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
1056 Curl_hash_clean(hash);
1058 if(data && data->share)
1059 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
1063 CURLcode Curl_loadhostpairs(struct Curl_easy *data)
1065 struct curl_slist *hostp;
1069 /* Default is no wildcard found */
1070 data->state.wildcard_resolve = false;
1072 for(hostp = data->state.resolve; hostp; hostp = hostp->next) {
1073 char entry_id[MAX_HOSTCACHE_LEN];
1076 if(hostp->data[0] == '-') {
1079 if(2 != sscanf(hostp->data + 1, "%255[^:]:%d", hostname, &port)) {
1080 infof(data, "Couldn't parse CURLOPT_RESOLVE removal entry '%s'",
1085 /* Create an entry id, based upon the hostname and port */
1086 create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
1087 entry_len = strlen(entry_id);
1090 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
1092 /* delete entry, ignore if it didn't exist */
1093 Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
1096 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
1099 struct Curl_dns_entry *dns;
1100 struct Curl_addrinfo *head = NULL, *tail = NULL;
1103 #if !defined(CURL_DISABLE_VERBOSE_STRINGS)
1104 char *addresses = NULL;
1110 bool permanent = TRUE;
1113 unsigned long tmp_port;
1116 host_begin = hostp->data;
1117 if(host_begin[0] == '+') {
1121 host_end = strchr(host_begin, ':');
1123 ((host_end - host_begin) >= (ptrdiff_t)sizeof(hostname)))
1126 memcpy(hostname, host_begin, host_end - host_begin);
1127 hostname[host_end - host_begin] = '\0';
1129 port_ptr = host_end + 1;
1130 tmp_port = strtoul(port_ptr, &end_ptr, 10);
1131 if(tmp_port > USHRT_MAX || end_ptr == port_ptr || *end_ptr != ':')
1134 port = (int)tmp_port;
1135 #if !defined(CURL_DISABLE_VERBOSE_STRINGS)
1136 addresses = end_ptr + 1;
1141 struct Curl_addrinfo *ai;
1143 addr_begin = end_ptr + 1;
1144 addr_end = strchr(addr_begin, ',');
1146 addr_end = addr_begin + strlen(addr_begin);
1149 /* allow IP(v6) address within [brackets] */
1150 if(*addr_begin == '[') {
1151 if(addr_end == addr_begin || *(addr_end - 1) != ']')
1157 alen = addr_end - addr_begin;
1161 if(alen >= sizeof(address))
1164 memcpy(address, addr_begin, alen);
1165 address[alen] = '\0';
1168 if(strchr(address, ':')) {
1169 infof(data, "Ignoring resolve address '%s', missing IPv6 support.",
1175 ai = Curl_str2addr(address, port);
1177 infof(data, "Resolve address '%s' found illegal", address);
1183 tail = tail->ai_next;
1196 failf(data, "Couldn't parse CURLOPT_RESOLVE entry '%s'",
1198 Curl_freeaddrinfo(head);
1199 return CURLE_SETOPT_OPTION_SYNTAX;
1202 /* Create an entry id, based upon the hostname and port */
1203 create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
1204 entry_len = strlen(entry_id);
1207 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
1209 /* See if it's already in our dns cache */
1210 dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
1213 infof(data, "RESOLVE %s:%d is - old addresses discarded",
1215 /* delete old entry, there are two reasons for this
1216 1. old entry may have different addresses.
1217 2. even if entry with correct addresses is already in the cache,
1218 but if it is close to expire, then by the time next http
1219 request is made, it can get expired and pruned because old
1220 entry is not necessarily marked as permanent.
1221 3. when adding a non-permanent entry, we want it to remove and
1222 replace an existing permanent entry.
1223 4. when adding a non-permanent entry, we want it to get a "fresh"
1224 timeout that starts _now_. */
1226 Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
1229 /* put this new host in the cache */
1230 dns = Curl_cache_addr(data, head, hostname, port);
1233 dns->timestamp = 0; /* mark as permanent */
1234 /* release the returned reference; the cache itself will keep the
1240 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
1243 Curl_freeaddrinfo(head);
1244 return CURLE_OUT_OF_MEMORY;
1246 infof(data, "Added %s:%d:%s to DNS cache%s",
1247 hostname, port, addresses, permanent ? "" : " (non-permanent)");
1249 /* Wildcard hostname */
1250 if(hostname[0] == '*' && hostname[1] == '\0') {
1251 infof(data, "RESOLVE %s:%d is wildcard, enabling wildcard checks",
1253 data->state.wildcard_resolve = true;
1257 data->state.resolve = NULL; /* dealt with now */
1262 CURLcode Curl_resolv_check(struct Curl_easy *data,
1263 struct Curl_dns_entry **dns)
1265 #if defined(CURL_DISABLE_DOH) && !defined(CURLRES_ASYNCH)
1269 #ifndef CURL_DISABLE_DOH
1270 if(data->conn->bits.doh)
1271 return Curl_doh_is_resolved(data, dns);
1273 return Curl_resolver_is_resolved(data, dns);
1276 int Curl_resolv_getsock(struct Curl_easy *data,
1277 curl_socket_t *socks)
1279 #ifdef CURLRES_ASYNCH
1280 #ifndef CURL_DISABLE_DOH
1281 if(data->conn->bits.doh)
1282 /* nothing to wait for during DoH resolve, those handles have their own
1284 return GETSOCK_BLANK;
1286 return Curl_resolver_getsock(data, socks);
1290 return GETSOCK_BLANK;
1294 /* Call this function after Curl_connect() has returned async=TRUE and
1295 then a successful name resolve has been received.
1297 Note: this function disconnects and frees the conn data in case of
1299 CURLcode Curl_once_resolved(struct Curl_easy *data, bool *protocol_done)
1302 struct connectdata *conn = data->conn;
1304 #ifdef USE_CURL_ASYNC
1305 if(data->state.async.dns) {
1306 conn->dns_entry = data->state.async.dns;
1307 data->state.async.dns = NULL;
1311 result = Curl_setup_conn(data, protocol_done);
1314 Curl_detach_connection(data);
1315 Curl_conncache_remove_conn(data, conn, TRUE);
1316 Curl_disconnect(data, conn, TRUE);
1322 * Curl_resolver_error() calls failf() with the appropriate message after a
1326 #ifdef USE_CURL_ASYNC
1327 CURLcode Curl_resolver_error(struct Curl_easy *data)
1329 const char *host_or_proxy;
1332 #ifndef CURL_DISABLE_PROXY
1333 struct connectdata *conn = data->conn;
1334 if(conn->bits.httpproxy) {
1335 host_or_proxy = "proxy";
1336 result = CURLE_COULDNT_RESOLVE_PROXY;
1341 host_or_proxy = "host";
1342 result = CURLE_COULDNT_RESOLVE_HOST;
1345 failf(data, "Could not resolve %s: %s", host_or_proxy,
1346 data->state.async.hostname);
1350 #endif /* USE_CURL_ASYNC */