]> sjero.net Git - wget/blob - src/host.c
[svn] Use bool type for boolean variables and values.
[wget] / src / host.c
1 /* Host name resolution and matching.
2    Copyright (C) 1995, 1996, 1997, 2000, 2001 Free Software Foundation, Inc.
3
4 This file is part of GNU Wget.
5
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.
10
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.
15
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.
19
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.  */
29
30 #include <config.h>
31
32 #ifndef WINDOWS
33 #include <netdb.h>
34 #endif
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <assert.h>
40
41 #ifndef WINDOWS
42 # include <sys/socket.h>
43 # include <netinet/in.h>
44 # ifndef __BEOS__
45 #  include <arpa/inet.h>
46 # endif
47 # include <netdb.h>
48 # define SET_H_ERRNO(err) ((void)(h_errno = (err)))
49 #else  /* WINDOWS */
50 # define SET_H_ERRNO(err) WSASetLastError (err)
51 #endif /* WINDOWS */
52
53 #include <errno.h>
54
55 #include "wget.h"
56 #include "utils.h"
57 #include "host.h"
58 #include "url.h"
59 #include "hash.h"
60 #include "connect.h"            /* for socket_has_inet6 */
61
62 #ifndef NO_ADDRESS
63 # define NO_ADDRESS NO_DATA
64 #endif
65
66 /* Lists of IP addresses that result from running DNS queries.  See
67    lookup_host for details.  */
68
69 struct address_list {
70   int count;                    /* number of adrresses */
71   ip_address *addresses;        /* pointer to the string of addresses */
72
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,
76                                    at least once. */
77
78   int refcount;                 /* reference count; when it drops to
79                                    0, the entry is freed. */
80 };
81
82 /* Get the bounds of the address list.  */
83
84 void
85 address_list_get_bounds (const struct address_list *al, int *start, int *end)
86 {
87   *start = al->faulty;
88   *end   = al->count;
89 }
90
91 /* Return a pointer to the address at position POS.  */
92
93 const ip_address *
94 address_list_address_at (const struct address_list *al, int pos)
95 {
96   assert (pos >= al->faulty && pos < al->count);
97   return al->addresses + pos;
98 }
99
100 /* Return true if AL contains IP, false otherwise.  */
101
102 bool
103 address_list_contains (const struct address_list *al, const ip_address *ip)
104 {
105   int i;
106   switch (ip->type)
107     {
108     case IPV4_ADDRESS:
109       for (i = 0; i < al->count; i++)
110         {
111           ip_address *cur = al->addresses + i;
112           if (cur->type == IPV4_ADDRESS
113               && (ADDRESS_IPV4_IN_ADDR (cur).s_addr
114                   ==
115                   ADDRESS_IPV4_IN_ADDR (ip).s_addr))
116             return true;
117         }
118       return false;
119 #ifdef ENABLE_IPV6
120     case IPV6_ADDRESS:
121       for (i = 0; i < al->count; i++)
122         {
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)
127 #endif
128               && IN6_ARE_ADDR_EQUAL (&ADDRESS_IPV6_IN6_ADDR (cur),
129                                      &ADDRESS_IPV6_IN6_ADDR (ip)))
130             return true;
131         }
132       return false;
133 #endif /* ENABLE_IPV6 */
134     default:
135       abort ();
136     }
137 }
138
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.  */
141
142 void
143 address_list_set_faulty (struct address_list *al, int index)
144 {
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);
149
150   ++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
155        retried anew.  */
156     al->faulty = 0;
157 }
158
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.  */
161
162 void
163 address_list_set_connected (struct address_list *al)
164 {
165   al->connected = true;
166 }
167
168 /* Return the value of the "connected" flag. */
169
170 bool
171 address_list_connected_p (const struct address_list *al)
172 {
173   return al->connected;
174 }
175
176 #ifdef ENABLE_IPV6
177
178 /* Create an address_list from the addresses in the given struct
179    addrinfo.  */
180
181 static struct address_list *
182 address_list_from_addrinfo (const struct addrinfo *ai)
183 {
184   struct address_list *al;
185   const struct addrinfo *ptr;
186   int cnt;
187   ip_address *ip;
188
189   cnt = 0;
190   for (ptr = ai; ptr != NULL ; ptr = ptr->ai_next)
191     if (ptr->ai_family == AF_INET || ptr->ai_family == AF_INET6)
192       ++cnt;
193   if (cnt == 0)
194     return NULL;
195
196   al = xnew0 (struct address_list);
197   al->addresses = xnew_array (ip_address, cnt);
198   al->count     = cnt;
199   al->refcount  = 1;
200
201   ip = al->addresses;
202   for (ptr = ai; ptr != NULL; ptr = ptr->ai_next)
203     if (ptr->ai_family == AF_INET6) 
204       {
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;
211 #endif
212         ++ip;
213       } 
214     else if (ptr->ai_family == AF_INET)
215       {
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;
220         ++ip;
221       }
222   assert (ip - al->addresses == cnt);
223   return al;
224 }
225
226 #define IS_IPV4(addr) (((const ip_address *) addr)->type == IPV4_ADDRESS)
227
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
231    0 otherwise.
232
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.  */
235
236 static int
237 cmp_prefer_ipv4 (const void *addr1, const void *addr2)
238 {
239   return !IS_IPV4 (addr1) - !IS_IPV4 (addr2);
240 }
241
242 #define IS_IPV6(addr) (((const ip_address *) addr)->type == IPV6_ADDRESS)
243
244 /* Like the above, but give preference to the IPv6 address.  */
245
246 static int
247 cmp_prefer_ipv6 (const void *addr1, const void *addr2)
248 {
249   return !IS_IPV6 (addr1) - !IS_IPV6 (addr2);
250 }
251
252 #else  /* not ENABLE_IPV6 */
253
254 /* Create an address_list from a NULL-terminated vector of IPv4
255    addresses.  This kind of vector is returned by gethostbyname.  */
256
257 static struct address_list *
258 address_list_from_ipv4_addresses (char **vec)
259 {
260   int count, i;
261   struct address_list *al = xnew0 (struct address_list);
262
263   count = 0;
264   while (vec[count])
265     ++count;
266   assert (count > 0);
267
268   al->addresses = xnew_array (ip_address, count);
269   al->count     = count;
270   al->refcount  = 1;
271
272   for (i = 0; i < count; i++)
273     {
274       ip_address *ip = &al->addresses[i];
275       ip->type = IPV4_ADDRESS;
276       memcpy (ADDRESS_IPV4_DATA (ip), vec[i], 4);
277     }
278
279   return al;
280 }
281
282 #endif /* not ENABLE_IPV6 */
283
284 static void
285 address_list_delete (struct address_list *al)
286 {
287   xfree (al->addresses);
288   xfree (al);
289 }
290
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
293    count reaches 0.  */
294
295 void
296 address_list_release (struct address_list *al)
297 {
298   --al->refcount;
299   DEBUGP (("Releasing 0x%0*lx (new refcount %d).\n", PTR_FORMAT (al),
300            al->refcount));
301   if (al->refcount <= 0)
302     {
303       DEBUGP (("Deleting unused 0x%0*lx.\n", PTR_FORMAT (al)));
304       address_list_delete (al);
305     }
306 }
307 \f
308 /* Versions of gethostbyname and getaddrinfo that support timeout. */
309
310 #ifndef ENABLE_IPV6
311
312 struct ghbnwt_context {
313   const char *host_name;
314   struct hostent *hptr;
315 };
316
317 static void
318 gethostbyname_with_timeout_callback (void *arg)
319 {
320   struct ghbnwt_context *ctx = (struct ghbnwt_context *)arg;
321   ctx->hptr = gethostbyname (ctx->host_name);
322 }
323
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.  */
328
329 static struct hostent *
330 gethostbyname_with_timeout (const char *host_name, double timeout)
331 {
332   struct ghbnwt_context ctx;
333   ctx.host_name = host_name;
334   if (run_with_timeout (timeout, gethostbyname_with_timeout_callback, &ctx))
335     {
336       SET_H_ERRNO (HOST_NOT_FOUND);
337       errno = ETIMEDOUT;
338       return NULL;
339     }
340   if (!ctx.hptr)
341     errno = 0;
342   return ctx.hptr;
343 }
344
345 /* Print error messages for host errors.  */
346 static char *
347 host_errstr (int error)
348 {
349   /* Can't use switch since some of these constants can be equal,
350      which makes the compiler complain about duplicate case
351      values.  */
352   if (error == HOST_NOT_FOUND
353       || error == NO_RECOVERY
354       || error == NO_DATA
355       || error == NO_ADDRESS)
356     return _("Unknown host");
357   else if (error == TRY_AGAIN)
358     /* Message modeled after what gai_strerror returns in similar
359        circumstances.  */
360     return _("Temporary failure in name resolution");
361   else
362     return _("Unknown error");
363 }
364
365 #else  /* ENABLE_IPV6 */
366
367 struct gaiwt_context {
368   const char *node;
369   const char *service;
370   const struct addrinfo *hints;
371   struct addrinfo **res;
372   int exit_code;
373 };
374
375 static void
376 getaddrinfo_with_timeout_callback (void *arg)
377 {
378   struct gaiwt_context *ctx = (struct gaiwt_context *)arg;
379   ctx->exit_code = getaddrinfo (ctx->node, ctx->service, ctx->hints, ctx->res);
380 }
381
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.  */
385
386 static int
387 getaddrinfo_with_timeout (const char *node, const char *service,
388                           const struct addrinfo *hints, struct addrinfo **res,
389                           double timeout)
390 {
391   struct gaiwt_context ctx;
392   ctx.node = node;
393   ctx.service = service;
394   ctx.hints = hints;
395   ctx.res = res;
396
397   if (run_with_timeout (timeout, getaddrinfo_with_timeout_callback, &ctx))
398     {
399       errno = ETIMEDOUT;
400       return EAI_SYSTEM;
401     }
402   return ctx.exit_code;
403 }
404
405 #endif /* ENABLE_IPV6 */
406 \f
407 /* Pretty-print ADDR.  When compiled without IPv6, this is the same as
408    inet_ntoa.  With IPv6, it either prints an IPv6 address or an IPv4
409    address.  */
410
411 const char *
412 pretty_print_address (const ip_address *addr)
413 {
414   switch (addr->type) 
415     {
416     case IPV4_ADDRESS:
417       return inet_ntoa (ADDRESS_IPV4_IN_ADDR (addr));
418 #ifdef ENABLE_IPV6
419     case IPV6_ADDRESS:
420       {
421         static char buf[128];
422         inet_ntop (AF_INET6, &ADDRESS_IPV6_IN6_ADDR (addr), buf, sizeof (buf));
423 #if 0
424 #ifdef HAVE_SOCKADDR_IN6_SCOPE_ID
425         {
426           /* append "%SCOPE_ID" for all ?non-global? addresses */
427           char *p = buf + strlen (buf);
428           *p++ = '%';
429           number_to_string (p, ADDRESS_IPV6_SCOPE (addr));
430         }
431 #endif
432 #endif
433         buf[sizeof (buf) - 1] = '\0';
434         return buf;
435       }
436 #endif
437     }
438   abort ();
439 }
440
441 /* The following two functions were adapted from glibc. */
442
443 static bool
444 is_valid_ipv4_address (const char *str, const char *end)
445 {
446   bool saw_digit = false;
447   int octets = 0;
448   int val = 0;
449
450   while (str < end)
451     {
452       int ch = *str++;
453
454       if (ch >= '0' && ch <= '9')
455         {
456           val = val * 10 + (ch - '0');
457
458           if (val > 255)
459             return false;
460           if (!saw_digit)
461             {
462               if (++octets > 4)
463                 return false;
464               saw_digit = true;
465             }
466         }
467       else if (ch == '.' && saw_digit)
468         {
469           if (octets == 4)
470             return false;
471           val = 0;
472           saw_digit = false;
473         }
474       else
475         return false;
476     }
477   if (octets < 4)
478     return false;
479   
480   return true;
481 }
482
483 bool
484 is_valid_ipv6_address (const char *str, const char *end)
485 {
486   /* Use lower-case for these to avoid clash with system headers.  */
487   enum {
488     ns_inaddrsz  = 4,
489     ns_in6addrsz = 16,
490     ns_int16sz   = 2
491   };
492
493   const char *curtok;
494   int tp;
495   const char *colonp;
496   bool saw_xdigit;
497   unsigned int val;
498
499   tp = 0;
500   colonp = NULL;
501
502   if (str == end)
503     return false;
504   
505   /* Leading :: requires some special handling. */
506   if (*str == ':')
507     {
508       ++str;
509       if (str == end || *str != ':')
510         return false;
511     }
512
513   curtok = str;
514   saw_xdigit = false;
515   val = 0;
516
517   while (str < end)
518     {
519       int ch = *str++;
520
521       /* if ch is a number, add it to val. */
522       if (ISXDIGIT (ch))
523         {
524           val <<= 4;
525           val |= XDIGIT_TO_NUM (ch);
526           if (val > 0xffff)
527             return false;
528           saw_xdigit = true;
529           continue;
530         }
531
532       /* if ch is a colon ... */
533       if (ch == ':')
534         {
535           curtok = str;
536           if (!saw_xdigit)
537             {
538               if (colonp != NULL)
539                 return false;
540               colonp = str + tp;
541               continue;
542             }
543           else if (str == end)
544             return false;
545           if (tp > ns_in6addrsz - ns_int16sz)
546             return false;
547           tp += ns_int16sz;
548           saw_xdigit = false;
549           val = 0;
550           continue;
551         }
552
553       /* if ch is a dot ... */
554       if (ch == '.' && (tp <= ns_in6addrsz - ns_inaddrsz)
555           && is_valid_ipv4_address (curtok, end) == 1)
556         {
557           tp += ns_inaddrsz;
558           saw_xdigit = false;
559           break;
560         }
561     
562       return false;
563     }
564
565   if (saw_xdigit)
566     {
567       if (tp > ns_in6addrsz - ns_int16sz) 
568         return false;
569       tp += ns_int16sz;
570     }
571
572   if (colonp != NULL)
573     {
574       if (tp == ns_in6addrsz) 
575         return false;
576       tp = ns_in6addrsz;
577     }
578
579   if (tp != ns_in6addrsz)
580     return false;
581
582   return true;
583 }
584 \f
585 /* Simple host cache, used by lookup_host to speed up resolving.  The
586    cache doesn't handle TTL because Wget is a fairly short-lived
587    application.  Refreshing is attempted when connect fails, though --
588    see connect_to_host.  */
589
590 /* Mapping between known hosts and to lists of their addresses. */
591 static struct hash_table *host_name_addresses_map;
592
593
594 /* Return the host's resolved addresses from the cache, if
595    available.  */
596
597 static struct address_list *
598 cache_query (const char *host)
599 {
600   struct address_list *al;
601   if (!host_name_addresses_map)
602     return NULL;
603   al = hash_table_get (host_name_addresses_map, host);
604   if (al)
605     {
606       DEBUGP (("Found %s in host_name_addresses_map (%p)\n", host, al));
607       ++al->refcount;
608       return al;
609     }
610   return NULL;
611 }
612
613 /* Cache the DNS lookup of HOST.  Subsequent invocations of
614    lookup_host will return the cached value.  */
615
616 static void
617 cache_store (const char *host, struct address_list *al)
618 {
619   if (!host_name_addresses_map)
620     host_name_addresses_map = make_nocase_string_hash_table (0);
621
622   ++al->refcount;
623   hash_table_put (host_name_addresses_map, xstrdup_lower (host), al);
624
625   IF_DEBUG
626     {
627       int i;
628       debug_logprintf ("Caching %s =>", host);
629       for (i = 0; i < al->count; i++)
630         debug_logprintf (" %s", pretty_print_address (al->addresses + i));
631       debug_logprintf ("\n");
632     }
633 }
634
635 /* Remove HOST from the DNS cache.  Does nothing is HOST is not in
636    the cache.  */
637
638 static void
639 cache_remove (const char *host)
640 {
641   struct address_list *al;
642   if (!host_name_addresses_map)
643     return;
644   al = hash_table_get (host_name_addresses_map, host);
645   if (al)
646     {
647       address_list_release (al);
648       hash_table_remove (host_name_addresses_map, host);
649     }
650 }
651 \f
652 /* Look up HOST in DNS and return a list of IP addresses.
653
654    This function caches its result so that, if the same host is passed
655    the second time, the addresses are returned without DNS lookup.
656    (Use LH_REFRESH to force lookup, or set opt.dns_cache to 0 to
657    globally disable caching.)
658
659    The order of the returned addresses is affected by the setting of
660    opt.prefer_family: if it is set to prefer_ipv4, IPv4 addresses are
661    placed at the beginning; if it is prefer_ipv6, IPv6 ones are placed
662    at the beginning; otherwise, the order is left intact.  The
663    relative order of addresses with the same family is left
664    undisturbed in either case.
665
666    FLAGS can be a combination of:
667      LH_SILENT  - don't print the "resolving ... done" messages.
668      LH_BIND    - resolve addresses for use with bind, which under
669                   IPv6 means to use AI_PASSIVE flag to getaddrinfo.
670                   Passive lookups are not cached under IPv6.
671      LH_REFRESH - if HOST is cached, remove the entry from the cache
672                   and resolve it anew.  */
673
674 struct address_list *
675 lookup_host (const char *host, int flags)
676 {
677   struct address_list *al;
678   bool silent = !!(flags & LH_SILENT);
679   bool use_cache;
680   bool numeric_address = false;
681   double timeout = opt.dns_timeout;
682
683 #ifndef ENABLE_IPV6
684   /* If we're not using getaddrinfo, first check if HOST specifies a
685      numeric IPv4 address.  Some implementations of gethostbyname
686      (e.g. the Ultrix one and possibly Winsock) don't accept
687      dotted-decimal IPv4 addresses.  */
688   {
689     uint32_t addr_ipv4 = (uint32_t)inet_addr (host);
690     if (addr_ipv4 != (uint32_t) -1)
691       {
692         /* No need to cache host->addr relation, just return the
693            address.  */
694         char *vec[2];
695         vec[0] = (char *)&addr_ipv4;
696         vec[1] = NULL;
697         return address_list_from_ipv4_addresses (vec);
698       }
699   }
700 #else  /* ENABLE_IPV6 */
701   /* If we're using getaddrinfo, at least check whether the address is
702      already numeric, in which case there is no need to print the
703      "Resolving..." output.  (This comes at no additional cost since
704      the is_valid_ipv*_address are already required for
705      url_parse.)  */
706   {
707     const char *end = host + strlen (host);
708     if (is_valid_ipv4_address (host, end) || is_valid_ipv6_address (host, end))
709       numeric_address = true;
710   }
711 #endif
712
713   /* Cache is normally on, but can be turned off with --no-dns-cache.
714      Don't cache passive lookups under IPv6.  */
715   use_cache = opt.dns_cache;
716 #ifdef ENABLE_IPV6
717   if ((flags & LH_BIND) || numeric_address)
718     use_cache = false;
719 #endif
720
721   /* Try to find the host in the cache so we don't need to talk to the
722      resolver.  If LH_REFRESH is requested, remove HOST from the cache
723      instead.  */
724   if (use_cache)
725     {
726       if (!(flags & LH_REFRESH))
727         {
728           al = cache_query (host);
729           if (al)
730             return al;
731         }
732       else
733         cache_remove (host);
734     }
735
736   /* No luck with the cache; resolve HOST. */
737
738   if (!silent && !numeric_address)
739     logprintf (LOG_VERBOSE, _("Resolving %s... "), escnonprint (host));
740
741 #ifdef ENABLE_IPV6
742   {
743     int err;
744     struct addrinfo hints, *res;
745
746     xzero (hints);
747     hints.ai_socktype = SOCK_STREAM;
748     if (opt.ipv4_only)
749       hints.ai_family = AF_INET;
750     else if (opt.ipv6_only)
751       hints.ai_family = AF_INET6;
752     else
753       /* We tried using AI_ADDRCONFIG, but removed it because: it
754          misinterprets IPv6 loopbacks, it is broken on AIX 5.1, and
755          it's unneeded since we sort the addresses anyway.  */
756         hints.ai_family = AF_UNSPEC;
757
758     if (flags & LH_BIND)
759       hints.ai_flags |= AI_PASSIVE;
760
761 #ifdef AI_NUMERICHOST
762     if (numeric_address)
763       {
764         /* Where available, the AI_NUMERICHOST hint can prevent costly
765            access to DNS servers.  */
766         hints.ai_flags |= AI_NUMERICHOST;
767         timeout = 0;            /* no timeout needed when "resolving"
768                                    numeric hosts -- avoid setting up
769                                    signal handlers and such. */
770       }
771 #endif
772
773     err = getaddrinfo_with_timeout (host, NULL, &hints, &res, timeout);
774     if (err != 0 || res == NULL)
775       {
776         if (!silent)
777           logprintf (LOG_VERBOSE, _("failed: %s.\n"),
778                      err != EAI_SYSTEM ? gai_strerror (err) : strerror (errno));
779         return NULL;
780       }
781     al = address_list_from_addrinfo (res);
782     freeaddrinfo (res);
783     if (!al)
784       {
785         logprintf (LOG_VERBOSE,
786                    _("failed: No IPv4/IPv6 addresses for host.\n"));
787         return NULL;
788       }
789
790     /* Reorder addresses so that IPv4 ones (or IPv6 ones, as per
791        --prefer-family) come first.  Sorting is stable so the order of
792        the addresses with the same family is undisturbed.  */
793     if (al->count > 1 && opt.prefer_family != prefer_none)
794       stable_sort (al->addresses, al->count, sizeof (ip_address),
795                    opt.prefer_family == prefer_ipv4
796                    ? cmp_prefer_ipv4 : cmp_prefer_ipv6);
797   }
798 #else  /* not ENABLE_IPV6 */
799   {
800     struct hostent *hptr = gethostbyname_with_timeout (host, timeout);
801     if (!hptr)
802       {
803         if (!silent)
804           {
805             if (errno != ETIMEDOUT)
806               logprintf (LOG_VERBOSE, _("failed: %s.\n"),
807                          host_errstr (h_errno));
808             else
809               logputs (LOG_VERBOSE, _("failed: timed out.\n"));
810           }
811         return NULL;
812       }
813     /* Do older systems have h_addr_list?  */
814     al = address_list_from_ipv4_addresses (hptr->h_addr_list);
815   }
816 #endif /* not ENABLE_IPV6 */
817
818   /* Print the addresses determined by DNS lookup, but no more than
819      three.  */
820   if (!silent && !numeric_address)
821     {
822       int i;
823       int printmax = al->count <= 3 ? al->count : 3;
824       for (i = 0; i < printmax; i++)
825         {
826           logprintf (LOG_VERBOSE, "%s",
827                      pretty_print_address (al->addresses + i));
828           if (i < printmax - 1)
829             logputs (LOG_VERBOSE, ", ");
830         }
831       if (printmax != al->count)
832         logputs (LOG_VERBOSE, ", ...");
833       logputs (LOG_VERBOSE, "\n");
834     }
835
836   /* Cache the lookup information. */
837   if (use_cache)
838     cache_store (host, al);
839
840   return al;
841 }
842 \f
843 /* Determine whether a URL is acceptable to be followed, according to
844    a list of domains to accept.  */
845 bool
846 accept_domain (struct url *u)
847 {
848   assert (u->host != NULL);
849   if (opt.domains)
850     {
851       if (!sufmatch ((const char **)opt.domains, u->host))
852         return false;
853     }
854   if (opt.exclude_domains)
855     {
856       if (sufmatch ((const char **)opt.exclude_domains, u->host))
857         return false;
858     }
859   return true;
860 }
861
862 /* Check whether WHAT is matched in LIST, each element of LIST being a
863    pattern to match WHAT against, using backward matching (see
864    match_backwards() in utils.c).
865
866    If an element of LIST matched, 1 is returned, 0 otherwise.  */
867 bool
868 sufmatch (const char **list, const char *what)
869 {
870   int i, j, k, lw;
871
872   lw = strlen (what);
873   for (i = 0; list[i]; i++)
874     {
875       for (j = strlen (list[i]), k = lw; j >= 0 && k >= 0; j--, k--)
876         if (TOLOWER (list[i][j]) != TOLOWER (what[k]))
877           break;
878       /* The domain must be first to reach to beginning.  */
879       if (j == -1)
880         return true;
881     }
882   return false;
883 }
884
885 static int
886 host_cleanup_mapper (void *key, void *value, void *arg_ignored)
887 {
888   struct address_list *al;
889
890   xfree (key);                  /* host */
891
892   al = (struct address_list *)value;
893   assert (al->refcount == 1);
894   address_list_delete (al);
895
896   return 0;
897 }
898
899 void
900 host_cleanup (void)
901 {
902   if (host_name_addresses_map)
903     {
904       hash_table_map (host_name_addresses_map, host_cleanup_mapper, NULL);
905       hash_table_destroy (host_name_addresses_map);
906       host_name_addresses_map = NULL;
907     }
908 }