1 /* Host name resolution and matching.
2 Copyright (C) 1996-2005 Free Software Foundation, Inc.
4 This file is part of GNU Wget.
6 GNU Wget is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 GNU Wget is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with Wget; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 In addition, as a special exception, the Free Software Foundation
21 gives permission to link the code of its release of Wget with the
22 OpenSSL project's "OpenSSL" library (or with modified versions of it
23 that use the same license as the "OpenSSL" library), and distribute
24 the linked executables. You must obey the GNU General Public License
25 in all respects for all of the code used other than "OpenSSL". If you
26 modify this file, you may extend this exception to your version of the
27 file, but you are not obligated to do so. If you do not wish to do
28 so, delete this exception statement from your version. */
38 # include <sys/socket.h>
39 # include <netinet/in.h>
41 # include <arpa/inet.h>
44 # define SET_H_ERRNO(err) ((void)(h_errno = (err)))
46 # define SET_H_ERRNO(err) WSASetLastError (err)
56 #include "connect.h" /* for socket_has_inet6 */
59 # define NO_ADDRESS NO_DATA
62 /* Lists of IP addresses that result from running DNS queries. See
63 lookup_host for details. */
66 int count; /* number of adrresses */
67 ip_address *addresses; /* pointer to the string of addresses */
69 int faulty; /* number of addresses known not to work. */
70 bool connected; /* whether we were able to connect to
71 one of the addresses in the list,
74 int refcount; /* reference count; when it drops to
75 0, the entry is freed. */
78 /* Get the bounds of the address list. */
81 address_list_get_bounds (const struct address_list *al, int *start, int *end)
87 /* Return a pointer to the address at position POS. */
90 address_list_address_at (const struct address_list *al, int pos)
92 assert (pos >= al->faulty && pos < al->count);
93 return al->addresses + pos;
96 /* Return true if AL contains IP, false otherwise. */
99 address_list_contains (const struct address_list *al, const ip_address *ip)
105 for (i = 0; i < al->count; i++)
107 ip_address *cur = al->addresses + i;
108 if (cur->type == IPV4_ADDRESS
109 && (ADDRESS_IPV4_IN_ADDR (cur).s_addr
111 ADDRESS_IPV4_IN_ADDR (ip).s_addr))
117 for (i = 0; i < al->count; i++)
119 ip_address *cur = al->addresses + i;
120 if (cur->type == IPV6_ADDRESS
121 #ifdef HAVE_SOCKADDR_IN6_SCOPE_ID
122 && ADDRESS_IPV6_SCOPE (cur) == ADDRESS_IPV6_SCOPE (ip)
124 && IN6_ARE_ADDR_EQUAL (&ADDRESS_IPV6_IN6_ADDR (cur),
125 &ADDRESS_IPV6_IN6_ADDR (ip)))
129 #endif /* ENABLE_IPV6 */
135 /* Mark the INDEXth element of AL as faulty, so that the next time
136 this address list is used, the faulty element will be skipped. */
139 address_list_set_faulty (struct address_list *al, int index)
141 /* We assume that the address list is traversed in order, so that a
142 "faulty" attempt is always preceded with all-faulty addresses,
143 and this is how Wget uses it. */
144 assert (index == al->faulty);
147 if (al->faulty >= al->count)
148 /* All addresses have been proven faulty. Since there's not much
149 sense in returning the user an empty address list the next
150 time, we'll rather make them all clean, so that they can be
155 /* Set the "connected" flag to true. This flag used by connect.c to
156 see if the host perhaps needs to be resolved again. */
159 address_list_set_connected (struct address_list *al)
161 al->connected = true;
164 /* Return the value of the "connected" flag. */
167 address_list_connected_p (const struct address_list *al)
169 return al->connected;
174 /* Create an address_list from the addresses in the given struct
177 static struct address_list *
178 address_list_from_addrinfo (const struct addrinfo *ai)
180 struct address_list *al;
181 const struct addrinfo *ptr;
186 for (ptr = ai; ptr != NULL ; ptr = ptr->ai_next)
187 if (ptr->ai_family == AF_INET || ptr->ai_family == AF_INET6)
192 al = xnew0 (struct address_list);
193 al->addresses = xnew_array (ip_address, cnt);
198 for (ptr = ai; ptr != NULL; ptr = ptr->ai_next)
199 if (ptr->ai_family == AF_INET6)
201 const struct sockaddr_in6 *sin6 =
202 (const struct sockaddr_in6 *)ptr->ai_addr;
203 ip->type = IPV6_ADDRESS;
204 ADDRESS_IPV6_IN6_ADDR (ip) = sin6->sin6_addr;
205 #ifdef HAVE_SOCKADDR_IN6_SCOPE_ID
206 ADDRESS_IPV6_SCOPE (ip) = sin6->sin6_scope_id;
210 else if (ptr->ai_family == AF_INET)
212 const struct sockaddr_in *sin =
213 (const struct sockaddr_in *)ptr->ai_addr;
214 ip->type = IPV4_ADDRESS;
215 ADDRESS_IPV4_IN_ADDR (ip) = sin->sin_addr;
218 assert (ip - al->addresses == cnt);
222 #define IS_IPV4(addr) (((const ip_address *) addr)->type == IPV4_ADDRESS)
224 /* Compare two IP addresses by type, giving preference to the IPv4
225 address (sorting it first). In other words, return -1 if ADDR1 is
226 IPv4 and ADDR2 is IPv6, +1 if ADDR1 is IPv6 and ADDR2 is IPv4, and
229 This is intended to be used as the comparator arg to a qsort-like
230 sorting function, which is why it accepts generic pointers. */
233 cmp_prefer_ipv4 (const void *addr1, const void *addr2)
235 return !IS_IPV4 (addr1) - !IS_IPV4 (addr2);
238 #define IS_IPV6(addr) (((const ip_address *) addr)->type == IPV6_ADDRESS)
240 /* Like the above, but give preference to the IPv6 address. */
243 cmp_prefer_ipv6 (const void *addr1, const void *addr2)
245 return !IS_IPV6 (addr1) - !IS_IPV6 (addr2);
248 #else /* not ENABLE_IPV6 */
250 /* Create an address_list from a NULL-terminated vector of IPv4
251 addresses. This kind of vector is returned by gethostbyname. */
253 static struct address_list *
254 address_list_from_ipv4_addresses (char **vec)
257 struct address_list *al = xnew0 (struct address_list);
264 al->addresses = xnew_array (ip_address, count);
268 for (i = 0; i < count; i++)
270 ip_address *ip = &al->addresses[i];
271 ip->type = IPV4_ADDRESS;
272 memcpy (ADDRESS_IPV4_DATA (ip), vec[i], 4);
278 #endif /* not ENABLE_IPV6 */
281 address_list_delete (struct address_list *al)
283 xfree (al->addresses);
287 /* Mark the address list as being no longer in use. This will reduce
288 its reference count which will cause the list to be freed when the
292 address_list_release (struct address_list *al)
295 DEBUGP (("Releasing 0x%0*lx (new refcount %d).\n", PTR_FORMAT (al),
297 if (al->refcount <= 0)
299 DEBUGP (("Deleting unused 0x%0*lx.\n", PTR_FORMAT (al)));
300 address_list_delete (al);
304 /* Versions of gethostbyname and getaddrinfo that support timeout. */
308 struct ghbnwt_context {
309 const char *host_name;
310 struct hostent *hptr;
314 gethostbyname_with_timeout_callback (void *arg)
316 struct ghbnwt_context *ctx = (struct ghbnwt_context *)arg;
317 ctx->hptr = gethostbyname (ctx->host_name);
320 /* Just like gethostbyname, except it times out after TIMEOUT seconds.
321 In case of timeout, NULL is returned and errno is set to ETIMEDOUT.
322 The function makes sure that when NULL is returned for reasons
323 other than timeout, errno is reset. */
325 static struct hostent *
326 gethostbyname_with_timeout (const char *host_name, double timeout)
328 struct ghbnwt_context ctx;
329 ctx.host_name = host_name;
330 if (run_with_timeout (timeout, gethostbyname_with_timeout_callback, &ctx))
332 SET_H_ERRNO (HOST_NOT_FOUND);
341 /* Print error messages for host errors. */
343 host_errstr (int error)
345 /* Can't use switch since some of these constants can be equal,
346 which makes the compiler complain about duplicate case
348 if (error == HOST_NOT_FOUND
349 || error == NO_RECOVERY
351 || error == NO_ADDRESS)
352 return _("Unknown host");
353 else if (error == TRY_AGAIN)
354 /* Message modeled after what gai_strerror returns in similar
356 return _("Temporary failure in name resolution");
358 return _("Unknown error");
361 #else /* ENABLE_IPV6 */
363 struct gaiwt_context {
366 const struct addrinfo *hints;
367 struct addrinfo **res;
372 getaddrinfo_with_timeout_callback (void *arg)
374 struct gaiwt_context *ctx = (struct gaiwt_context *)arg;
375 ctx->exit_code = getaddrinfo (ctx->node, ctx->service, ctx->hints, ctx->res);
378 /* Just like getaddrinfo, except it times out after TIMEOUT seconds.
379 In case of timeout, the EAI_SYSTEM error code is returned and errno
380 is set to ETIMEDOUT. */
383 getaddrinfo_with_timeout (const char *node, const char *service,
384 const struct addrinfo *hints, struct addrinfo **res,
387 struct gaiwt_context ctx;
389 ctx.service = service;
393 if (run_with_timeout (timeout, getaddrinfo_with_timeout_callback, &ctx))
398 return ctx.exit_code;
401 #endif /* ENABLE_IPV6 */
403 /* Return a textual representation of ADDR, i.e. the dotted quad for
404 IPv4 addresses, and the colon-separated list of hex words (with all
405 zeros omitted, etc.) for IPv6 addresses. */
408 print_address (const ip_address *addr)
413 return inet_ntoa (ADDRESS_IPV4_IN_ADDR (addr));
418 if (!inet_ntop (AF_INET6, &ADDRESS_IPV6_IN6_ADDR (addr),
420 snprintf (buf, sizeof buf, "<error: %s>", strerror (errno));
421 buf[sizeof (buf) - 1] = '\0';
429 /* The following two functions were adapted from glibc. */
432 is_valid_ipv4_address (const char *str, const char *end)
434 bool saw_digit = false;
442 if (ch >= '0' && ch <= '9')
444 val = val * 10 + (ch - '0');
455 else if (ch == '.' && saw_digit)
472 is_valid_ipv6_address (const char *str, const char *end)
474 /* Use lower-case for these to avoid clash with system headers. */
493 /* Leading :: requires some special handling. */
497 if (str == end || *str != ':')
509 /* if ch is a number, add it to val. */
513 val |= XDIGIT_TO_NUM (ch);
520 /* if ch is a colon ... */
533 if (tp > ns_in6addrsz - ns_int16sz)
541 /* if ch is a dot ... */
542 if (ch == '.' && (tp <= ns_in6addrsz - ns_inaddrsz)
543 && is_valid_ipv4_address (curtok, end) == 1)
555 if (tp > ns_in6addrsz - ns_int16sz)
562 if (tp == ns_in6addrsz)
567 if (tp != ns_in6addrsz)
573 /* Simple host cache, used by lookup_host to speed up resolving. The
574 cache doesn't handle TTL because Wget is a fairly short-lived
575 application. Refreshing is attempted when connect fails, though --
576 see connect_to_host. */
578 /* Mapping between known hosts and to lists of their addresses. */
579 static struct hash_table *host_name_addresses_map;
582 /* Return the host's resolved addresses from the cache, if
585 static struct address_list *
586 cache_query (const char *host)
588 struct address_list *al;
589 if (!host_name_addresses_map)
591 al = hash_table_get (host_name_addresses_map, host);
594 DEBUGP (("Found %s in host_name_addresses_map (%p)\n", host, al));
601 /* Cache the DNS lookup of HOST. Subsequent invocations of
602 lookup_host will return the cached value. */
605 cache_store (const char *host, struct address_list *al)
607 if (!host_name_addresses_map)
608 host_name_addresses_map = make_nocase_string_hash_table (0);
611 hash_table_put (host_name_addresses_map, xstrdup_lower (host), al);
616 debug_logprintf ("Caching %s =>", host);
617 for (i = 0; i < al->count; i++)
618 debug_logprintf (" %s", print_address (al->addresses + i));
619 debug_logprintf ("\n");
623 /* Remove HOST from the DNS cache. Does nothing is HOST is not in
627 cache_remove (const char *host)
629 struct address_list *al;
630 if (!host_name_addresses_map)
632 al = hash_table_get (host_name_addresses_map, host);
635 address_list_release (al);
636 hash_table_remove (host_name_addresses_map, host);
640 /* Look up HOST in DNS and return a list of IP addresses.
642 This function caches its result so that, if the same host is passed
643 the second time, the addresses are returned without DNS lookup.
644 (Use LH_REFRESH to force lookup, or set opt.dns_cache to 0 to
645 globally disable caching.)
647 The order of the returned addresses is affected by the setting of
648 opt.prefer_family: if it is set to prefer_ipv4, IPv4 addresses are
649 placed at the beginning; if it is prefer_ipv6, IPv6 ones are placed
650 at the beginning; otherwise, the order is left intact. The
651 relative order of addresses with the same family is left
652 undisturbed in either case.
654 FLAGS can be a combination of:
655 LH_SILENT - don't print the "resolving ... done" messages.
656 LH_BIND - resolve addresses for use with bind, which under
657 IPv6 means to use AI_PASSIVE flag to getaddrinfo.
658 Passive lookups are not cached under IPv6.
659 LH_REFRESH - if HOST is cached, remove the entry from the cache
660 and resolve it anew. */
662 struct address_list *
663 lookup_host (const char *host, int flags)
665 struct address_list *al;
666 bool silent = !!(flags & LH_SILENT);
668 bool numeric_address = false;
669 double timeout = opt.dns_timeout;
672 /* If we're not using getaddrinfo, first check if HOST specifies a
673 numeric IPv4 address. Some implementations of gethostbyname
674 (e.g. the Ultrix one and possibly Winsock) don't accept
675 dotted-decimal IPv4 addresses. */
677 uint32_t addr_ipv4 = (uint32_t)inet_addr (host);
678 if (addr_ipv4 != (uint32_t) -1)
680 /* No need to cache host->addr relation, just return the
683 vec[0] = (char *)&addr_ipv4;
685 return address_list_from_ipv4_addresses (vec);
688 #else /* ENABLE_IPV6 */
689 /* If we're using getaddrinfo, at least check whether the address is
690 already numeric, in which case there is no need to print the
691 "Resolving..." output. (This comes at no additional cost since
692 the is_valid_ipv*_address are already required for
695 const char *end = host + strlen (host);
696 if (is_valid_ipv4_address (host, end) || is_valid_ipv6_address (host, end))
697 numeric_address = true;
701 /* Cache is normally on, but can be turned off with --no-dns-cache.
702 Don't cache passive lookups under IPv6. */
703 use_cache = opt.dns_cache;
705 if ((flags & LH_BIND) || numeric_address)
709 /* Try to find the host in the cache so we don't need to talk to the
710 resolver. If LH_REFRESH is requested, remove HOST from the cache
714 if (!(flags & LH_REFRESH))
716 al = cache_query (host);
724 /* No luck with the cache; resolve HOST. */
726 if (!silent && !numeric_address)
727 logprintf (LOG_VERBOSE, _("Resolving %s... "), escnonprint (host));
732 struct addrinfo hints, *res;
735 hints.ai_socktype = SOCK_STREAM;
737 hints.ai_family = AF_INET;
738 else if (opt.ipv6_only)
739 hints.ai_family = AF_INET6;
741 /* We tried using AI_ADDRCONFIG, but removed it because: it
742 misinterprets IPv6 loopbacks, it is broken on AIX 5.1, and
743 it's unneeded since we sort the addresses anyway. */
744 hints.ai_family = AF_UNSPEC;
747 hints.ai_flags |= AI_PASSIVE;
749 #ifdef AI_NUMERICHOST
752 /* Where available, the AI_NUMERICHOST hint can prevent costly
753 access to DNS servers. */
754 hints.ai_flags |= AI_NUMERICHOST;
755 timeout = 0; /* no timeout needed when "resolving"
756 numeric hosts -- avoid setting up
757 signal handlers and such. */
761 err = getaddrinfo_with_timeout (host, NULL, &hints, &res, timeout);
762 if (err != 0 || res == NULL)
765 logprintf (LOG_VERBOSE, _("failed: %s.\n"),
766 err != EAI_SYSTEM ? gai_strerror (err) : strerror (errno));
769 al = address_list_from_addrinfo (res);
773 logprintf (LOG_VERBOSE,
774 _("failed: No IPv4/IPv6 addresses for host.\n"));
778 /* Reorder addresses so that IPv4 ones (or IPv6 ones, as per
779 --prefer-family) come first. Sorting is stable so the order of
780 the addresses with the same family is undisturbed. */
781 if (al->count > 1 && opt.prefer_family != prefer_none)
782 stable_sort (al->addresses, al->count, sizeof (ip_address),
783 opt.prefer_family == prefer_ipv4
784 ? cmp_prefer_ipv4 : cmp_prefer_ipv6);
786 #else /* not ENABLE_IPV6 */
788 struct hostent *hptr = gethostbyname_with_timeout (host, timeout);
793 if (errno != ETIMEDOUT)
794 logprintf (LOG_VERBOSE, _("failed: %s.\n"),
795 host_errstr (h_errno));
797 logputs (LOG_VERBOSE, _("failed: timed out.\n"));
801 /* Do older systems have h_addr_list? */
802 al = address_list_from_ipv4_addresses (hptr->h_addr_list);
804 #endif /* not ENABLE_IPV6 */
806 /* Print the addresses determined by DNS lookup, but no more than
808 if (!silent && !numeric_address)
811 int printmax = al->count <= 3 ? al->count : 3;
812 for (i = 0; i < printmax; i++)
814 logputs (LOG_VERBOSE, print_address (al->addresses + i));
815 if (i < printmax - 1)
816 logputs (LOG_VERBOSE, ", ");
818 if (printmax != al->count)
819 logputs (LOG_VERBOSE, ", ...");
820 logputs (LOG_VERBOSE, "\n");
823 /* Cache the lookup information. */
825 cache_store (host, al);
830 /* Determine whether a URL is acceptable to be followed, according to
831 a list of domains to accept. */
833 accept_domain (struct url *u)
835 assert (u->host != NULL);
838 if (!sufmatch ((const char **)opt.domains, u->host))
841 if (opt.exclude_domains)
843 if (sufmatch ((const char **)opt.exclude_domains, u->host))
849 /* Check whether WHAT is matched in LIST, each element of LIST being a
850 pattern to match WHAT against, using backward matching (see
851 match_backwards() in utils.c).
853 If an element of LIST matched, 1 is returned, 0 otherwise. */
855 sufmatch (const char **list, const char *what)
860 for (i = 0; list[i]; i++)
862 for (j = strlen (list[i]), k = lw; j >= 0 && k >= 0; j--, k--)
863 if (TOLOWER (list[i][j]) != TOLOWER (what[k]))
865 /* The domain must be first to reach to beginning. */
873 host_cleanup_mapper (void *key, void *value, void *arg_ignored)
875 struct address_list *al;
877 xfree (key); /* host */
879 al = (struct address_list *)value;
880 assert (al->refcount == 1);
881 address_list_delete (al);
889 if (host_name_addresses_map)
891 hash_table_map (host_name_addresses_map, host_cleanup_mapper, NULL);
892 hash_table_destroy (host_name_addresses_map);
893 host_name_addresses_map = NULL;