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. */
42 # include <sys/socket.h>
43 # include <netinet/in.h>
45 # include <arpa/inet.h>
48 # define SET_H_ERRNO(err) ((void)(h_errno = (err)))
50 # define SET_H_ERRNO(err) WSASetLastError (err)
60 #include "connect.h" /* for socket_has_inet6 */
63 # define NO_ADDRESS NO_DATA
66 /* Lists of IP addresses that result from running DNS queries. See
67 lookup_host for details. */
70 int count; /* number of adrresses */
71 ip_address *addresses; /* pointer to the string of addresses */
73 int faulty; /* number of addresses known not to work. */
74 bool connected; /* whether we were able to connect to
75 one of the addresses in the list,
78 int refcount; /* reference count; when it drops to
79 0, the entry is freed. */
82 /* Get the bounds of the address list. */
85 address_list_get_bounds (const struct address_list *al, int *start, int *end)
91 /* Return a pointer to the address at position POS. */
94 address_list_address_at (const struct address_list *al, int pos)
96 assert (pos >= al->faulty && pos < al->count);
97 return al->addresses + pos;
100 /* Return true if AL contains IP, false otherwise. */
103 address_list_contains (const struct address_list *al, const ip_address *ip)
109 for (i = 0; i < al->count; i++)
111 ip_address *cur = al->addresses + i;
112 if (cur->type == IPV4_ADDRESS
113 && (ADDRESS_IPV4_IN_ADDR (cur).s_addr
115 ADDRESS_IPV4_IN_ADDR (ip).s_addr))
121 for (i = 0; i < al->count; i++)
123 ip_address *cur = al->addresses + i;
124 if (cur->type == IPV6_ADDRESS
125 #ifdef HAVE_SOCKADDR_IN6_SCOPE_ID
126 && ADDRESS_IPV6_SCOPE (cur) == ADDRESS_IPV6_SCOPE (ip)
128 && IN6_ARE_ADDR_EQUAL (&ADDRESS_IPV6_IN6_ADDR (cur),
129 &ADDRESS_IPV6_IN6_ADDR (ip)))
133 #endif /* ENABLE_IPV6 */
139 /* Mark the INDEXth element of AL as faulty, so that the next time
140 this address list is used, the faulty element will be skipped. */
143 address_list_set_faulty (struct address_list *al, int index)
145 /* We assume that the address list is traversed in order, so that a
146 "faulty" attempt is always preceded with all-faulty addresses,
147 and this is how Wget uses it. */
148 assert (index == al->faulty);
151 if (al->faulty >= al->count)
152 /* All addresses have been proven faulty. Since there's not much
153 sense in returning the user an empty address list the next
154 time, we'll rather make them all clean, so that they can be
159 /* Set the "connected" flag to true. This flag used by connect.c to
160 see if the host perhaps needs to be resolved again. */
163 address_list_set_connected (struct address_list *al)
165 al->connected = true;
168 /* Return the value of the "connected" flag. */
171 address_list_connected_p (const struct address_list *al)
173 return al->connected;
178 /* Create an address_list from the addresses in the given struct
181 static struct address_list *
182 address_list_from_addrinfo (const struct addrinfo *ai)
184 struct address_list *al;
185 const struct addrinfo *ptr;
190 for (ptr = ai; ptr != NULL ; ptr = ptr->ai_next)
191 if (ptr->ai_family == AF_INET || ptr->ai_family == AF_INET6)
196 al = xnew0 (struct address_list);
197 al->addresses = xnew_array (ip_address, cnt);
202 for (ptr = ai; ptr != NULL; ptr = ptr->ai_next)
203 if (ptr->ai_family == AF_INET6)
205 const struct sockaddr_in6 *sin6 =
206 (const struct sockaddr_in6 *)ptr->ai_addr;
207 ip->type = IPV6_ADDRESS;
208 ADDRESS_IPV6_IN6_ADDR (ip) = sin6->sin6_addr;
209 #ifdef HAVE_SOCKADDR_IN6_SCOPE_ID
210 ADDRESS_IPV6_SCOPE (ip) = sin6->sin6_scope_id;
214 else if (ptr->ai_family == AF_INET)
216 const struct sockaddr_in *sin =
217 (const struct sockaddr_in *)ptr->ai_addr;
218 ip->type = IPV4_ADDRESS;
219 ADDRESS_IPV4_IN_ADDR (ip) = sin->sin_addr;
222 assert (ip - al->addresses == cnt);
226 #define IS_IPV4(addr) (((const ip_address *) addr)->type == IPV4_ADDRESS)
228 /* Compare two IP addresses by type, giving preference to the IPv4
229 address (sorting it first). In other words, return -1 if ADDR1 is
230 IPv4 and ADDR2 is IPv6, +1 if ADDR1 is IPv6 and ADDR2 is IPv4, and
233 This is intended to be used as the comparator arg to a qsort-like
234 sorting function, which is why it accepts generic pointers. */
237 cmp_prefer_ipv4 (const void *addr1, const void *addr2)
239 return !IS_IPV4 (addr1) - !IS_IPV4 (addr2);
242 #define IS_IPV6(addr) (((const ip_address *) addr)->type == IPV6_ADDRESS)
244 /* Like the above, but give preference to the IPv6 address. */
247 cmp_prefer_ipv6 (const void *addr1, const void *addr2)
249 return !IS_IPV6 (addr1) - !IS_IPV6 (addr2);
252 #else /* not ENABLE_IPV6 */
254 /* Create an address_list from a NULL-terminated vector of IPv4
255 addresses. This kind of vector is returned by gethostbyname. */
257 static struct address_list *
258 address_list_from_ipv4_addresses (char **vec)
261 struct address_list *al = xnew0 (struct address_list);
268 al->addresses = xnew_array (ip_address, count);
272 for (i = 0; i < count; i++)
274 ip_address *ip = &al->addresses[i];
275 ip->type = IPV4_ADDRESS;
276 memcpy (ADDRESS_IPV4_DATA (ip), vec[i], 4);
282 #endif /* not ENABLE_IPV6 */
285 address_list_delete (struct address_list *al)
287 xfree (al->addresses);
291 /* Mark the address list as being no longer in use. This will reduce
292 its reference count which will cause the list to be freed when the
296 address_list_release (struct address_list *al)
299 DEBUGP (("Releasing 0x%0*lx (new refcount %d).\n", PTR_FORMAT (al),
301 if (al->refcount <= 0)
303 DEBUGP (("Deleting unused 0x%0*lx.\n", PTR_FORMAT (al)));
304 address_list_delete (al);
308 /* Versions of gethostbyname and getaddrinfo that support timeout. */
312 struct ghbnwt_context {
313 const char *host_name;
314 struct hostent *hptr;
318 gethostbyname_with_timeout_callback (void *arg)
320 struct ghbnwt_context *ctx = (struct ghbnwt_context *)arg;
321 ctx->hptr = gethostbyname (ctx->host_name);
324 /* Just like gethostbyname, except it times out after TIMEOUT seconds.
325 In case of timeout, NULL is returned and errno is set to ETIMEDOUT.
326 The function makes sure that when NULL is returned for reasons
327 other than timeout, errno is reset. */
329 static struct hostent *
330 gethostbyname_with_timeout (const char *host_name, double timeout)
332 struct ghbnwt_context ctx;
333 ctx.host_name = host_name;
334 if (run_with_timeout (timeout, gethostbyname_with_timeout_callback, &ctx))
336 SET_H_ERRNO (HOST_NOT_FOUND);
345 /* Print error messages for host errors. */
347 host_errstr (int error)
349 /* Can't use switch since some of these constants can be equal,
350 which makes the compiler complain about duplicate case
352 if (error == HOST_NOT_FOUND
353 || error == NO_RECOVERY
355 || error == NO_ADDRESS)
356 return _("Unknown host");
357 else if (error == TRY_AGAIN)
358 /* Message modeled after what gai_strerror returns in similar
360 return _("Temporary failure in name resolution");
362 return _("Unknown error");
365 #else /* ENABLE_IPV6 */
367 struct gaiwt_context {
370 const struct addrinfo *hints;
371 struct addrinfo **res;
376 getaddrinfo_with_timeout_callback (void *arg)
378 struct gaiwt_context *ctx = (struct gaiwt_context *)arg;
379 ctx->exit_code = getaddrinfo (ctx->node, ctx->service, ctx->hints, ctx->res);
382 /* Just like getaddrinfo, except it times out after TIMEOUT seconds.
383 In case of timeout, the EAI_SYSTEM error code is returned and errno
384 is set to ETIMEDOUT. */
387 getaddrinfo_with_timeout (const char *node, const char *service,
388 const struct addrinfo *hints, struct addrinfo **res,
391 struct gaiwt_context ctx;
393 ctx.service = service;
397 if (run_with_timeout (timeout, getaddrinfo_with_timeout_callback, &ctx))
402 return ctx.exit_code;
405 #endif /* ENABLE_IPV6 */
407 /* Return a textual representation of ADDR, i.e. the dotted quad for
408 IPv4 addresses, and the colon-separated list of hex words (with all
409 zeros omitted, etc.) for IPv6 addresses. */
412 print_address (const ip_address *addr)
417 return inet_ntoa (ADDRESS_IPV4_IN_ADDR (addr));
422 if (!inet_ntop (AF_INET6, &ADDRESS_IPV6_IN6_ADDR (addr),
424 snprintf (buf, sizeof buf, "<error: %s>", strerror (errno));
425 buf[sizeof (buf) - 1] = '\0';
433 /* The following two functions were adapted from glibc. */
436 is_valid_ipv4_address (const char *str, const char *end)
438 bool saw_digit = false;
446 if (ch >= '0' && ch <= '9')
448 val = val * 10 + (ch - '0');
459 else if (ch == '.' && saw_digit)
476 is_valid_ipv6_address (const char *str, const char *end)
478 /* Use lower-case for these to avoid clash with system headers. */
497 /* Leading :: requires some special handling. */
501 if (str == end || *str != ':')
513 /* if ch is a number, add it to val. */
517 val |= XDIGIT_TO_NUM (ch);
524 /* if ch is a colon ... */
537 if (tp > ns_in6addrsz - ns_int16sz)
545 /* if ch is a dot ... */
546 if (ch == '.' && (tp <= ns_in6addrsz - ns_inaddrsz)
547 && is_valid_ipv4_address (curtok, end) == 1)
559 if (tp > ns_in6addrsz - ns_int16sz)
566 if (tp == ns_in6addrsz)
571 if (tp != ns_in6addrsz)
577 /* Simple host cache, used by lookup_host to speed up resolving. The
578 cache doesn't handle TTL because Wget is a fairly short-lived
579 application. Refreshing is attempted when connect fails, though --
580 see connect_to_host. */
582 /* Mapping between known hosts and to lists of their addresses. */
583 static struct hash_table *host_name_addresses_map;
586 /* Return the host's resolved addresses from the cache, if
589 static struct address_list *
590 cache_query (const char *host)
592 struct address_list *al;
593 if (!host_name_addresses_map)
595 al = hash_table_get (host_name_addresses_map, host);
598 DEBUGP (("Found %s in host_name_addresses_map (%p)\n", host, al));
605 /* Cache the DNS lookup of HOST. Subsequent invocations of
606 lookup_host will return the cached value. */
609 cache_store (const char *host, struct address_list *al)
611 if (!host_name_addresses_map)
612 host_name_addresses_map = make_nocase_string_hash_table (0);
615 hash_table_put (host_name_addresses_map, xstrdup_lower (host), al);
620 debug_logprintf ("Caching %s =>", host);
621 for (i = 0; i < al->count; i++)
622 debug_logprintf (" %s", print_address (al->addresses + i));
623 debug_logprintf ("\n");
627 /* Remove HOST from the DNS cache. Does nothing is HOST is not in
631 cache_remove (const char *host)
633 struct address_list *al;
634 if (!host_name_addresses_map)
636 al = hash_table_get (host_name_addresses_map, host);
639 address_list_release (al);
640 hash_table_remove (host_name_addresses_map, host);
644 /* Look up HOST in DNS and return a list of IP addresses.
646 This function caches its result so that, if the same host is passed
647 the second time, the addresses are returned without DNS lookup.
648 (Use LH_REFRESH to force lookup, or set opt.dns_cache to 0 to
649 globally disable caching.)
651 The order of the returned addresses is affected by the setting of
652 opt.prefer_family: if it is set to prefer_ipv4, IPv4 addresses are
653 placed at the beginning; if it is prefer_ipv6, IPv6 ones are placed
654 at the beginning; otherwise, the order is left intact. The
655 relative order of addresses with the same family is left
656 undisturbed in either case.
658 FLAGS can be a combination of:
659 LH_SILENT - don't print the "resolving ... done" messages.
660 LH_BIND - resolve addresses for use with bind, which under
661 IPv6 means to use AI_PASSIVE flag to getaddrinfo.
662 Passive lookups are not cached under IPv6.
663 LH_REFRESH - if HOST is cached, remove the entry from the cache
664 and resolve it anew. */
666 struct address_list *
667 lookup_host (const char *host, int flags)
669 struct address_list *al;
670 bool silent = !!(flags & LH_SILENT);
672 bool numeric_address = false;
673 double timeout = opt.dns_timeout;
676 /* If we're not using getaddrinfo, first check if HOST specifies a
677 numeric IPv4 address. Some implementations of gethostbyname
678 (e.g. the Ultrix one and possibly Winsock) don't accept
679 dotted-decimal IPv4 addresses. */
681 uint32_t addr_ipv4 = (uint32_t)inet_addr (host);
682 if (addr_ipv4 != (uint32_t) -1)
684 /* No need to cache host->addr relation, just return the
687 vec[0] = (char *)&addr_ipv4;
689 return address_list_from_ipv4_addresses (vec);
692 #else /* ENABLE_IPV6 */
693 /* If we're using getaddrinfo, at least check whether the address is
694 already numeric, in which case there is no need to print the
695 "Resolving..." output. (This comes at no additional cost since
696 the is_valid_ipv*_address are already required for
699 const char *end = host + strlen (host);
700 if (is_valid_ipv4_address (host, end) || is_valid_ipv6_address (host, end))
701 numeric_address = true;
705 /* Cache is normally on, but can be turned off with --no-dns-cache.
706 Don't cache passive lookups under IPv6. */
707 use_cache = opt.dns_cache;
709 if ((flags & LH_BIND) || numeric_address)
713 /* Try to find the host in the cache so we don't need to talk to the
714 resolver. If LH_REFRESH is requested, remove HOST from the cache
718 if (!(flags & LH_REFRESH))
720 al = cache_query (host);
728 /* No luck with the cache; resolve HOST. */
730 if (!silent && !numeric_address)
731 logprintf (LOG_VERBOSE, _("Resolving %s... "), escnonprint (host));
736 struct addrinfo hints, *res;
739 hints.ai_socktype = SOCK_STREAM;
741 hints.ai_family = AF_INET;
742 else if (opt.ipv6_only)
743 hints.ai_family = AF_INET6;
745 /* We tried using AI_ADDRCONFIG, but removed it because: it
746 misinterprets IPv6 loopbacks, it is broken on AIX 5.1, and
747 it's unneeded since we sort the addresses anyway. */
748 hints.ai_family = AF_UNSPEC;
751 hints.ai_flags |= AI_PASSIVE;
753 #ifdef AI_NUMERICHOST
756 /* Where available, the AI_NUMERICHOST hint can prevent costly
757 access to DNS servers. */
758 hints.ai_flags |= AI_NUMERICHOST;
759 timeout = 0; /* no timeout needed when "resolving"
760 numeric hosts -- avoid setting up
761 signal handlers and such. */
765 err = getaddrinfo_with_timeout (host, NULL, &hints, &res, timeout);
766 if (err != 0 || res == NULL)
769 logprintf (LOG_VERBOSE, _("failed: %s.\n"),
770 err != EAI_SYSTEM ? gai_strerror (err) : strerror (errno));
773 al = address_list_from_addrinfo (res);
777 logprintf (LOG_VERBOSE,
778 _("failed: No IPv4/IPv6 addresses for host.\n"));
782 /* Reorder addresses so that IPv4 ones (or IPv6 ones, as per
783 --prefer-family) come first. Sorting is stable so the order of
784 the addresses with the same family is undisturbed. */
785 if (al->count > 1 && opt.prefer_family != prefer_none)
786 stable_sort (al->addresses, al->count, sizeof (ip_address),
787 opt.prefer_family == prefer_ipv4
788 ? cmp_prefer_ipv4 : cmp_prefer_ipv6);
790 #else /* not ENABLE_IPV6 */
792 struct hostent *hptr = gethostbyname_with_timeout (host, timeout);
797 if (errno != ETIMEDOUT)
798 logprintf (LOG_VERBOSE, _("failed: %s.\n"),
799 host_errstr (h_errno));
801 logputs (LOG_VERBOSE, _("failed: timed out.\n"));
805 /* Do older systems have h_addr_list? */
806 al = address_list_from_ipv4_addresses (hptr->h_addr_list);
808 #endif /* not ENABLE_IPV6 */
810 /* Print the addresses determined by DNS lookup, but no more than
812 if (!silent && !numeric_address)
815 int printmax = al->count <= 3 ? al->count : 3;
816 for (i = 0; i < printmax; i++)
818 logputs (LOG_VERBOSE, print_address (al->addresses + i));
819 if (i < printmax - 1)
820 logputs (LOG_VERBOSE, ", ");
822 if (printmax != al->count)
823 logputs (LOG_VERBOSE, ", ...");
824 logputs (LOG_VERBOSE, "\n");
827 /* Cache the lookup information. */
829 cache_store (host, al);
834 /* Determine whether a URL is acceptable to be followed, according to
835 a list of domains to accept. */
837 accept_domain (struct url *u)
839 assert (u->host != NULL);
842 if (!sufmatch ((const char **)opt.domains, u->host))
845 if (opt.exclude_domains)
847 if (sufmatch ((const char **)opt.exclude_domains, u->host))
853 /* Check whether WHAT is matched in LIST, each element of LIST being a
854 pattern to match WHAT against, using backward matching (see
855 match_backwards() in utils.c).
857 If an element of LIST matched, 1 is returned, 0 otherwise. */
859 sufmatch (const char **list, const char *what)
864 for (i = 0; list[i]; i++)
866 for (j = strlen (list[i]), k = lw; j >= 0 && k >= 0; j--, k--)
867 if (TOLOWER (list[i][j]) != TOLOWER (what[k]))
869 /* The domain must be first to reach to beginning. */
877 host_cleanup_mapper (void *key, void *value, void *arg_ignored)
879 struct address_list *al;
881 xfree (key); /* host */
883 al = (struct address_list *)value;
884 assert (al->refcount == 1);
885 address_list_delete (al);
893 if (host_name_addresses_map)
895 hash_table_map (host_name_addresses_map, host_cleanup_mapper, NULL);
896 hash_table_destroy (host_name_addresses_map);
897 host_name_addresses_map = NULL;