1 /* Host name resolution and matching.
2 Copyright (C) 1995, 1996, 1997, 2000, 2001 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
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, 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. */
44 #include <sys/types.h>
48 # define SET_H_ERRNO(err) WSASetLastError (err)
50 # include <sys/socket.h>
51 # include <netinet/in.h>
53 # include <arpa/inet.h>
56 # define SET_H_ERRNO(err) ((void)(h_errno = (err)))
60 # define NO_ADDRESS NO_DATA
81 /* Lists of IP addresses that result from running DNS queries. See
82 lookup_host for details. */
85 int count; /* number of adrresses */
86 ip_address *addresses; /* pointer to the string of addresses */
88 int faulty; /* number of addresses known not to work. */
89 int connected; /* whether we were able to connect to
90 one of the addresses in the list,
93 int refcount; /* reference count; when it drops to
94 0, the entry is freed. */
97 /* Get the bounds of the address list. */
100 address_list_get_bounds (const struct address_list *al, int *start, int *end)
106 /* Return a pointer to the address at position POS. */
109 address_list_address_at (const struct address_list *al, int pos)
111 assert (pos >= al->faulty && pos < al->count);
112 return al->addresses + pos;
115 /* Return 1 if IP is one of the addresses in AL. */
118 address_list_find (const struct address_list *al, const ip_address *ip)
124 for (i = 0; i < al->count; i++)
126 ip_address *cur = al->addresses + i;
127 if (cur->type == IPV4_ADDRESS
128 && (ADDRESS_IPV4_IN_ADDR (cur).s_addr
130 ADDRESS_IPV4_IN_ADDR (ip).s_addr))
136 for (i = 0; i < al->count; i++)
138 ip_address *cur = al->addresses + i;
139 if (cur->type == IPV6_ADDRESS
140 #ifdef HAVE_SOCKADDR_IN6_SCOPE_ID
141 && ADDRESS_IPV6_SCOPE (cur) == ADDRESS_IPV6_SCOPE (ip)
143 && IN6_ARE_ADDR_EQUAL (&ADDRESS_IPV6_IN6_ADDR (cur),
144 &ADDRESS_IPV6_IN6_ADDR (ip)))
148 #endif /* ENABLE_IPV6 */
155 /* Mark the INDEXth element of AL as faulty, so that the next time
156 this address list is used, the faulty element will be skipped. */
159 address_list_set_faulty (struct address_list *al, int index)
161 /* We assume that the address list is traversed in order, so that a
162 "faulty" attempt is always preceded with all-faulty addresses,
163 and this is how Wget uses it. */
164 assert (index == al->faulty);
167 if (al->faulty >= al->count)
168 /* All addresses have been proven faulty. Since there's not much
169 sense in returning the user an empty address list the next
170 time, we'll rather make them all clean, so that they can be
175 /* Set the "connected" flag to true. This flag used by connect.c to
176 see if the host perhaps needs to be resolved again. */
179 address_list_set_connected (struct address_list *al)
184 /* Return the value of the "connected" flag. */
187 address_list_connected_p (const struct address_list *al)
189 return al->connected;
194 /* Create an address_list from the addresses in the given struct
197 static struct address_list *
198 address_list_from_addrinfo (const struct addrinfo *ai)
200 struct address_list *al;
201 const struct addrinfo *ptr;
206 for (ptr = ai; ptr != NULL ; ptr = ptr->ai_next)
207 if (ptr->ai_family == AF_INET || ptr->ai_family == AF_INET6)
212 al = xnew0 (struct address_list);
213 al->addresses = xnew_array (ip_address, cnt);
218 for (ptr = ai; ptr != NULL; ptr = ptr->ai_next)
219 if (ptr->ai_family == AF_INET6)
221 const struct sockaddr_in6 *sin6 =
222 (const struct sockaddr_in6 *)ptr->ai_addr;
223 ip->type = IPV6_ADDRESS;
224 ADDRESS_IPV6_IN6_ADDR (ip) = sin6->sin6_addr;
225 #ifdef HAVE_SOCKADDR_IN6_SCOPE_ID
226 ADDRESS_IPV6_SCOPE (ip) = sin6->sin6_scope_id;
230 else if (ptr->ai_family == AF_INET)
232 const struct sockaddr_in *sin =
233 (const struct sockaddr_in *)ptr->ai_addr;
234 ip->type = IPV4_ADDRESS;
235 ADDRESS_IPV4_IN_ADDR (ip) = sin->sin_addr;
238 assert (ip - al->addresses == cnt);
242 #else /* not ENABLE_IPV6 */
244 /* Create an address_list from a NULL-terminated vector of IPv4
245 addresses. This kind of vector is returned by gethostbyname. */
247 static struct address_list *
248 address_list_from_ipv4_addresses (char **vec)
251 struct address_list *al = xnew0 (struct address_list);
258 al->addresses = xnew_array (ip_address, count);
262 for (i = 0; i < count; i++)
264 ip_address *ip = &al->addresses[i];
265 ip->type = IPV4_ADDRESS;
266 memcpy (ADDRESS_IPV4_DATA (ip), vec[i], 4);
272 #endif /* not ENABLE_IPV6 */
275 address_list_delete (struct address_list *al)
277 xfree (al->addresses);
281 /* Mark the address list as being no longer in use. This will reduce
282 its reference count which will cause the list to be freed when the
286 address_list_release (struct address_list *al)
289 DEBUGP (("Releasing %p (new refcount %d).\n", al, al->refcount));
290 if (al->refcount <= 0)
292 DEBUGP (("Deleting unused %p.\n", al));
293 address_list_delete (al);
297 /* Versions of gethostbyname and getaddrinfo that support timeout. */
301 struct ghbnwt_context {
302 const char *host_name;
303 struct hostent *hptr;
307 gethostbyname_with_timeout_callback (void *arg)
309 struct ghbnwt_context *ctx = (struct ghbnwt_context *)arg;
310 ctx->hptr = gethostbyname (ctx->host_name);
313 /* Just like gethostbyname, except it times out after TIMEOUT seconds.
314 In case of timeout, NULL is returned and errno is set to ETIMEDOUT.
315 The function makes sure that when NULL is returned for reasons
316 other than timeout, errno is reset. */
318 static struct hostent *
319 gethostbyname_with_timeout (const char *host_name, double timeout)
321 struct ghbnwt_context ctx;
322 ctx.host_name = host_name;
323 if (run_with_timeout (timeout, gethostbyname_with_timeout_callback, &ctx))
325 SET_H_ERRNO (HOST_NOT_FOUND);
334 /* Print error messages for host errors. */
336 host_errstr (int error)
338 /* Can't use switch since some of these constants can be equal,
339 which makes the compiler complain about duplicate case
341 if (error == HOST_NOT_FOUND
342 || error == NO_RECOVERY
344 || error == NO_ADDRESS)
345 return _("Unknown host");
346 else if (error == TRY_AGAIN)
347 /* Message modeled after what gai_strerror returns in similar
349 return _("Temporary failure in name resolution");
351 return _("Unknown error");
354 #else /* ENABLE_IPV6 */
356 struct gaiwt_context {
359 const struct addrinfo *hints;
360 struct addrinfo **res;
365 getaddrinfo_with_timeout_callback (void *arg)
367 struct gaiwt_context *ctx = (struct gaiwt_context *)arg;
368 ctx->exit_code = getaddrinfo (ctx->node, ctx->service, ctx->hints, ctx->res);
371 /* Just like getaddrinfo, except it times out after TIMEOUT seconds.
372 In case of timeout, the EAI_SYSTEM error code is returned and errno
373 is set to ETIMEDOUT. */
376 getaddrinfo_with_timeout (const char *node, const char *service,
377 const struct addrinfo *hints, struct addrinfo **res,
380 struct gaiwt_context ctx;
382 ctx.service = service;
386 if (run_with_timeout (timeout, getaddrinfo_with_timeout_callback, &ctx))
391 return ctx.exit_code;
394 #endif /* ENABLE_IPV6 */
396 /* Pretty-print ADDR. When compiled without IPv6, this is the same as
397 inet_ntoa. With IPv6, it either prints an IPv6 address or an IPv4
401 pretty_print_address (const ip_address *addr)
406 return inet_ntoa (ADDRESS_IPV4_IN_ADDR (addr));
410 static char buf[128];
411 inet_ntop (AF_INET6, &ADDRESS_IPV6_IN6_ADDR (addr), buf, sizeof (buf));
413 #ifdef HAVE_SOCKADDR_IN6_SCOPE_ID
415 /* append "%SCOPE_ID" for all ?non-global? addresses */
416 char *p = buf + strlen (buf);
418 number_to_string (p, ADDRESS_IPV6_SCOPE (addr));
422 buf[sizeof (buf) - 1] = '\0';
431 /* Simple host cache, used by lookup_host to speed up resolving. The
432 cache doesn't handle TTL because Wget is a fairly short-lived
433 application. Refreshing is attempted when connect fails, though --
434 see connect_to_host. */
436 /* Mapping between known hosts and to lists of their addresses. */
437 static struct hash_table *host_name_addresses_map;
440 /* Return the host's resolved addresses from the cache, if
443 static struct address_list *
444 cache_query (const char *host)
446 struct address_list *al;
447 if (!host_name_addresses_map)
449 al = hash_table_get (host_name_addresses_map, host);
452 DEBUGP (("Found %s in host_name_addresses_map (%p)\n", host, al));
459 /* Cache the DNS lookup of HOST. Subsequent invocations of
460 lookup_host will return the cached value. */
463 cache_store (const char *host, struct address_list *al)
465 if (!host_name_addresses_map)
466 host_name_addresses_map = make_nocase_string_hash_table (0);
469 hash_table_put (host_name_addresses_map, xstrdup_lower (host), al);
475 debug_logprintf ("Caching %s =>", host);
476 for (i = 0; i < al->count; i++)
477 debug_logprintf (" %s", pretty_print_address (al->addresses + i));
478 debug_logprintf ("\n");
483 /* Remove HOST from the DNS cache. Does nothing is HOST is not in
487 cache_remove (const char *host)
489 struct address_list *al;
490 if (!host_name_addresses_map)
492 al = hash_table_get (host_name_addresses_map, host);
495 address_list_release (al);
496 hash_table_remove (host_name_addresses_map, host);
500 /* Look up HOST in DNS and return a list of IP addresses. The
501 addresses in the list are in the same order in which
502 gethostbyname/getaddrinfo returned them.
504 This function caches its result so that, if the same host is passed
505 the second time, the addresses are returned without DNS lookup.
506 (Use LH_REFRESH to force lookup, or set opt.dns_cache to 0 to
507 globally disable caching.)
509 FLAGS can be a combination of:
510 LH_SILENT - don't print the "resolving ... done" messages.
511 LH_BIND - resolve addresses for use with bind, which under
512 IPv6 means to use AI_PASSIVE flag to getaddrinfo.
513 Passive lookups are not cached under IPv6.
514 LH_REFRESH - if HOST is cached, remove the entry from the cache
515 and resolve it anew. */
517 struct address_list *
518 lookup_host (const char *host, int flags)
520 struct address_list *al = NULL;
521 int silent = flags & LH_SILENT;
525 /* If we're not using getaddrinfo, first check if HOST specifies a
526 numeric IPv4 address. gethostbyname is not required to accept
527 dotted-decimal IPv4 addresses, and some implementations (e.g. the
528 Ultrix one and possibly Winsock) indeed don't. */
530 uint32_t addr_ipv4 = (uint32_t)inet_addr (host);
531 if (addr_ipv4 != (uint32_t) -1)
533 /* No need to cache host->addr relation, just return the
536 vec[0] = (char *)&addr_ipv4;
538 return address_list_from_ipv4_addresses (vec);
543 /* Cache is normally on, but can be turned off with --no-dns-cache.
544 Don't cache passive lookups under IPv6. */
545 use_cache = opt.dns_cache;
551 /* Try to find the host in the cache so we don't need to talk to the
552 resolver. If LH_REFRESH is requested, remove HOST from the cache
556 if (!(flags & LH_REFRESH))
558 al = cache_query (host);
566 /* No luck with the cache; resolve HOST. */
569 logprintf (LOG_VERBOSE, _("Resolving %s... "), host);
574 struct addrinfo hints, *res;
577 hints.ai_socktype = SOCK_STREAM;
578 if (opt.ipv4_only && !opt.ipv6_only)
579 hints.ai_family = AF_INET;
580 else if (opt.ipv6_only && !opt.ipv4_only)
581 hints.ai_family = AF_INET6;
584 hints.ai_family = AF_UNSPEC;
585 #ifdef HAVE_GETADDRINFO_AI_ADDRCONFIG
586 /* Use AI_ADDRCONFIG if available and if specific family isn't
587 explicitly requested. See init.c:defaults(). */
588 hints.ai_flags |= AI_ADDRCONFIG;
592 hints.ai_flags |= AI_PASSIVE;
594 err = getaddrinfo_with_timeout (host, NULL, &hints, &res, opt.dns_timeout);
595 if (err != 0 || res == NULL)
598 logprintf (LOG_VERBOSE, _("failed: %s.\n"),
599 err != EAI_SYSTEM ? gai_strerror (err) : strerror (errno));
602 al = address_list_from_addrinfo (res);
606 logprintf (LOG_VERBOSE,
607 _("failed: No IPv4/IPv6 addresses for host.\n"));
613 struct hostent *hptr = gethostbyname_with_timeout (host, opt.dns_timeout);
618 if (errno != ETIMEDOUT)
619 logprintf (LOG_VERBOSE, _("failed: %s.\n"),
620 host_errstr (h_errno));
622 logputs (LOG_VERBOSE, _("failed: timed out.\n"));
626 /* Do older systems have h_addr_list? */
627 al = address_list_from_ipv4_addresses (hptr->h_addr_list);
631 /* Print the addresses determined by DNS lookup, but no more than
636 int printmax = al->count <= 3 ? al->count : 3;
637 for (i = 0; i < printmax; i++)
639 logprintf (LOG_VERBOSE, "%s",
640 pretty_print_address (al->addresses + i));
641 if (i < printmax - 1)
642 logputs (LOG_VERBOSE, ", ");
644 if (printmax != al->count)
645 logputs (LOG_VERBOSE, ", ...");
646 logputs (LOG_VERBOSE, "\n");
649 /* Cache the lookup information. */
651 cache_store (host, al);
656 /* Determine whether a URL is acceptable to be followed, according to
657 a list of domains to accept. */
659 accept_domain (struct url *u)
661 assert (u->host != NULL);
664 if (!sufmatch ((const char **)opt.domains, u->host))
667 if (opt.exclude_domains)
669 if (sufmatch ((const char **)opt.exclude_domains, u->host))
675 /* Check whether WHAT is matched in LIST, each element of LIST being a
676 pattern to match WHAT against, using backward matching (see
677 match_backwards() in utils.c).
679 If an element of LIST matched, 1 is returned, 0 otherwise. */
681 sufmatch (const char **list, const char *what)
686 for (i = 0; list[i]; i++)
688 for (j = strlen (list[i]), k = lw; j >= 0 && k >= 0; j--, k--)
689 if (TOLOWER (list[i][j]) != TOLOWER (what[k]))
691 /* The domain must be first to reach to beginning. */
699 host_cleanup_mapper (void *key, void *value, void *arg_ignored)
701 struct address_list *al;
703 xfree (key); /* host */
705 al = (struct address_list *)value;
706 assert (al->refcount == 1);
707 address_list_delete (al);
715 if (host_name_addresses_map)
717 hash_table_map (host_name_addresses_map, host_cleanup_mapper, NULL);
718 hash_table_destroy (host_name_addresses_map);
719 host_name_addresses_map = NULL;