]> sjero.net Git - wget/blob - src/host.c
[svn] Remove extraneous include of netdb.h.
[wget] / src / host.c
1 /* Host name resolution and matching.
2    Copyright (C) 1996-2005 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 Foundation, Inc.,
18 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 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 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <assert.h>
36
37 #ifndef WINDOWS
38 # include <sys/socket.h>
39 # include <netinet/in.h>
40 # ifndef __BEOS__
41 #  include <arpa/inet.h>
42 # endif
43 # include <netdb.h>
44 # define SET_H_ERRNO(err) ((void)(h_errno = (err)))
45 #else  /* WINDOWS */
46 # define SET_H_ERRNO(err) WSASetLastError (err)
47 #endif /* WINDOWS */
48
49 #include <errno.h>
50
51 #include "wget.h"
52 #include "utils.h"
53 #include "host.h"
54 #include "url.h"
55 #include "hash.h"
56 #include "connect.h"            /* for socket_has_inet6 */
57
58 #ifndef NO_ADDRESS
59 # define NO_ADDRESS NO_DATA
60 #endif
61
62 /* Lists of IP addresses that result from running DNS queries.  See
63    lookup_host for details.  */
64
65 struct address_list {
66   int count;                    /* number of adrresses */
67   ip_address *addresses;        /* pointer to the string of addresses */
68
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,
72                                    at least once. */
73
74   int refcount;                 /* reference count; when it drops to
75                                    0, the entry is freed. */
76 };
77
78 /* Get the bounds of the address list.  */
79
80 void
81 address_list_get_bounds (const struct address_list *al, int *start, int *end)
82 {
83   *start = al->faulty;
84   *end   = al->count;
85 }
86
87 /* Return a pointer to the address at position POS.  */
88
89 const ip_address *
90 address_list_address_at (const struct address_list *al, int pos)
91 {
92   assert (pos >= al->faulty && pos < al->count);
93   return al->addresses + pos;
94 }
95
96 /* Return true if AL contains IP, false otherwise.  */
97
98 bool
99 address_list_contains (const struct address_list *al, const ip_address *ip)
100 {
101   int i;
102   switch (ip->type)
103     {
104     case IPV4_ADDRESS:
105       for (i = 0; i < al->count; i++)
106         {
107           ip_address *cur = al->addresses + i;
108           if (cur->type == IPV4_ADDRESS
109               && (ADDRESS_IPV4_IN_ADDR (cur).s_addr
110                   ==
111                   ADDRESS_IPV4_IN_ADDR (ip).s_addr))
112             return true;
113         }
114       return false;
115 #ifdef ENABLE_IPV6
116     case IPV6_ADDRESS:
117       for (i = 0; i < al->count; i++)
118         {
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)
123 #endif
124               && IN6_ARE_ADDR_EQUAL (&ADDRESS_IPV6_IN6_ADDR (cur),
125                                      &ADDRESS_IPV6_IN6_ADDR (ip)))
126             return true;
127         }
128       return false;
129 #endif /* ENABLE_IPV6 */
130     default:
131       abort ();
132     }
133 }
134
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.  */
137
138 void
139 address_list_set_faulty (struct address_list *al, int index)
140 {
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);
145
146   ++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
151        retried anew.  */
152     al->faulty = 0;
153 }
154
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.  */
157
158 void
159 address_list_set_connected (struct address_list *al)
160 {
161   al->connected = true;
162 }
163
164 /* Return the value of the "connected" flag. */
165
166 bool
167 address_list_connected_p (const struct address_list *al)
168 {
169   return al->connected;
170 }
171
172 #ifdef ENABLE_IPV6
173
174 /* Create an address_list from the addresses in the given struct
175    addrinfo.  */
176
177 static struct address_list *
178 address_list_from_addrinfo (const struct addrinfo *ai)
179 {
180   struct address_list *al;
181   const struct addrinfo *ptr;
182   int cnt;
183   ip_address *ip;
184
185   cnt = 0;
186   for (ptr = ai; ptr != NULL ; ptr = ptr->ai_next)
187     if (ptr->ai_family == AF_INET || ptr->ai_family == AF_INET6)
188       ++cnt;
189   if (cnt == 0)
190     return NULL;
191
192   al = xnew0 (struct address_list);
193   al->addresses = xnew_array (ip_address, cnt);
194   al->count     = cnt;
195   al->refcount  = 1;
196
197   ip = al->addresses;
198   for (ptr = ai; ptr != NULL; ptr = ptr->ai_next)
199     if (ptr->ai_family == AF_INET6) 
200       {
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;
207 #endif
208         ++ip;
209       } 
210     else if (ptr->ai_family == AF_INET)
211       {
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;
216         ++ip;
217       }
218   assert (ip - al->addresses == cnt);
219   return al;
220 }
221
222 #define IS_IPV4(addr) (((const ip_address *) addr)->type == IPV4_ADDRESS)
223
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
227    0 otherwise.
228
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.  */
231
232 static int
233 cmp_prefer_ipv4 (const void *addr1, const void *addr2)
234 {
235   return !IS_IPV4 (addr1) - !IS_IPV4 (addr2);
236 }
237
238 #define IS_IPV6(addr) (((const ip_address *) addr)->type == IPV6_ADDRESS)
239
240 /* Like the above, but give preference to the IPv6 address.  */
241
242 static int
243 cmp_prefer_ipv6 (const void *addr1, const void *addr2)
244 {
245   return !IS_IPV6 (addr1) - !IS_IPV6 (addr2);
246 }
247
248 #else  /* not ENABLE_IPV6 */
249
250 /* Create an address_list from a NULL-terminated vector of IPv4
251    addresses.  This kind of vector is returned by gethostbyname.  */
252
253 static struct address_list *
254 address_list_from_ipv4_addresses (char **vec)
255 {
256   int count, i;
257   struct address_list *al = xnew0 (struct address_list);
258
259   count = 0;
260   while (vec[count])
261     ++count;
262   assert (count > 0);
263
264   al->addresses = xnew_array (ip_address, count);
265   al->count     = count;
266   al->refcount  = 1;
267
268   for (i = 0; i < count; i++)
269     {
270       ip_address *ip = &al->addresses[i];
271       ip->type = IPV4_ADDRESS;
272       memcpy (ADDRESS_IPV4_DATA (ip), vec[i], 4);
273     }
274
275   return al;
276 }
277
278 #endif /* not ENABLE_IPV6 */
279
280 static void
281 address_list_delete (struct address_list *al)
282 {
283   xfree (al->addresses);
284   xfree (al);
285 }
286
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
289    count reaches 0.  */
290
291 void
292 address_list_release (struct address_list *al)
293 {
294   --al->refcount;
295   DEBUGP (("Releasing 0x%0*lx (new refcount %d).\n", PTR_FORMAT (al),
296            al->refcount));
297   if (al->refcount <= 0)
298     {
299       DEBUGP (("Deleting unused 0x%0*lx.\n", PTR_FORMAT (al)));
300       address_list_delete (al);
301     }
302 }
303 \f
304 /* Versions of gethostbyname and getaddrinfo that support timeout. */
305
306 #ifndef ENABLE_IPV6
307
308 struct ghbnwt_context {
309   const char *host_name;
310   struct hostent *hptr;
311 };
312
313 static void
314 gethostbyname_with_timeout_callback (void *arg)
315 {
316   struct ghbnwt_context *ctx = (struct ghbnwt_context *)arg;
317   ctx->hptr = gethostbyname (ctx->host_name);
318 }
319
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.  */
324
325 static struct hostent *
326 gethostbyname_with_timeout (const char *host_name, double timeout)
327 {
328   struct ghbnwt_context ctx;
329   ctx.host_name = host_name;
330   if (run_with_timeout (timeout, gethostbyname_with_timeout_callback, &ctx))
331     {
332       SET_H_ERRNO (HOST_NOT_FOUND);
333       errno = ETIMEDOUT;
334       return NULL;
335     }
336   if (!ctx.hptr)
337     errno = 0;
338   return ctx.hptr;
339 }
340
341 /* Print error messages for host errors.  */
342 static char *
343 host_errstr (int error)
344 {
345   /* Can't use switch since some of these constants can be equal,
346      which makes the compiler complain about duplicate case
347      values.  */
348   if (error == HOST_NOT_FOUND
349       || error == NO_RECOVERY
350       || error == NO_DATA
351       || error == NO_ADDRESS)
352     return _("Unknown host");
353   else if (error == TRY_AGAIN)
354     /* Message modeled after what gai_strerror returns in similar
355        circumstances.  */
356     return _("Temporary failure in name resolution");
357   else
358     return _("Unknown error");
359 }
360
361 #else  /* ENABLE_IPV6 */
362
363 struct gaiwt_context {
364   const char *node;
365   const char *service;
366   const struct addrinfo *hints;
367   struct addrinfo **res;
368   int exit_code;
369 };
370
371 static void
372 getaddrinfo_with_timeout_callback (void *arg)
373 {
374   struct gaiwt_context *ctx = (struct gaiwt_context *)arg;
375   ctx->exit_code = getaddrinfo (ctx->node, ctx->service, ctx->hints, ctx->res);
376 }
377
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.  */
381
382 static int
383 getaddrinfo_with_timeout (const char *node, const char *service,
384                           const struct addrinfo *hints, struct addrinfo **res,
385                           double timeout)
386 {
387   struct gaiwt_context ctx;
388   ctx.node = node;
389   ctx.service = service;
390   ctx.hints = hints;
391   ctx.res = res;
392
393   if (run_with_timeout (timeout, getaddrinfo_with_timeout_callback, &ctx))
394     {
395       errno = ETIMEDOUT;
396       return EAI_SYSTEM;
397     }
398   return ctx.exit_code;
399 }
400
401 #endif /* ENABLE_IPV6 */
402 \f
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.  */
406
407 const char *
408 print_address (const ip_address *addr)
409 {
410   switch (addr->type) 
411     {
412     case IPV4_ADDRESS:
413       return inet_ntoa (ADDRESS_IPV4_IN_ADDR (addr));
414 #ifdef ENABLE_IPV6
415     case IPV6_ADDRESS:
416       {
417         static char buf[64];
418         if (!inet_ntop (AF_INET6, &ADDRESS_IPV6_IN6_ADDR (addr),
419                         buf, sizeof (buf)))
420           snprintf (buf, sizeof buf, "<error: %s>", strerror (errno));
421         buf[sizeof (buf) - 1] = '\0';
422         return buf;
423       }
424 #endif
425     }
426   abort ();
427 }
428
429 /* The following two functions were adapted from glibc. */
430
431 static bool
432 is_valid_ipv4_address (const char *str, const char *end)
433 {
434   bool saw_digit = false;
435   int octets = 0;
436   int val = 0;
437
438   while (str < end)
439     {
440       int ch = *str++;
441
442       if (ch >= '0' && ch <= '9')
443         {
444           val = val * 10 + (ch - '0');
445
446           if (val > 255)
447             return false;
448           if (!saw_digit)
449             {
450               if (++octets > 4)
451                 return false;
452               saw_digit = true;
453             }
454         }
455       else if (ch == '.' && saw_digit)
456         {
457           if (octets == 4)
458             return false;
459           val = 0;
460           saw_digit = false;
461         }
462       else
463         return false;
464     }
465   if (octets < 4)
466     return false;
467   
468   return true;
469 }
470
471 bool
472 is_valid_ipv6_address (const char *str, const char *end)
473 {
474   /* Use lower-case for these to avoid clash with system headers.  */
475   enum {
476     ns_inaddrsz  = 4,
477     ns_in6addrsz = 16,
478     ns_int16sz   = 2
479   };
480
481   const char *curtok;
482   int tp;
483   const char *colonp;
484   bool saw_xdigit;
485   unsigned int val;
486
487   tp = 0;
488   colonp = NULL;
489
490   if (str == end)
491     return false;
492   
493   /* Leading :: requires some special handling. */
494   if (*str == ':')
495     {
496       ++str;
497       if (str == end || *str != ':')
498         return false;
499     }
500
501   curtok = str;
502   saw_xdigit = false;
503   val = 0;
504
505   while (str < end)
506     {
507       int ch = *str++;
508
509       /* if ch is a number, add it to val. */
510       if (ISXDIGIT (ch))
511         {
512           val <<= 4;
513           val |= XDIGIT_TO_NUM (ch);
514           if (val > 0xffff)
515             return false;
516           saw_xdigit = true;
517           continue;
518         }
519
520       /* if ch is a colon ... */
521       if (ch == ':')
522         {
523           curtok = str;
524           if (!saw_xdigit)
525             {
526               if (colonp != NULL)
527                 return false;
528               colonp = str + tp;
529               continue;
530             }
531           else if (str == end)
532             return false;
533           if (tp > ns_in6addrsz - ns_int16sz)
534             return false;
535           tp += ns_int16sz;
536           saw_xdigit = false;
537           val = 0;
538           continue;
539         }
540
541       /* if ch is a dot ... */
542       if (ch == '.' && (tp <= ns_in6addrsz - ns_inaddrsz)
543           && is_valid_ipv4_address (curtok, end) == 1)
544         {
545           tp += ns_inaddrsz;
546           saw_xdigit = false;
547           break;
548         }
549     
550       return false;
551     }
552
553   if (saw_xdigit)
554     {
555       if (tp > ns_in6addrsz - ns_int16sz) 
556         return false;
557       tp += ns_int16sz;
558     }
559
560   if (colonp != NULL)
561     {
562       if (tp == ns_in6addrsz) 
563         return false;
564       tp = ns_in6addrsz;
565     }
566
567   if (tp != ns_in6addrsz)
568     return false;
569
570   return true;
571 }
572 \f
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.  */
577
578 /* Mapping between known hosts and to lists of their addresses. */
579 static struct hash_table *host_name_addresses_map;
580
581
582 /* Return the host's resolved addresses from the cache, if
583    available.  */
584
585 static struct address_list *
586 cache_query (const char *host)
587 {
588   struct address_list *al;
589   if (!host_name_addresses_map)
590     return NULL;
591   al = hash_table_get (host_name_addresses_map, host);
592   if (al)
593     {
594       DEBUGP (("Found %s in host_name_addresses_map (%p)\n", host, al));
595       ++al->refcount;
596       return al;
597     }
598   return NULL;
599 }
600
601 /* Cache the DNS lookup of HOST.  Subsequent invocations of
602    lookup_host will return the cached value.  */
603
604 static void
605 cache_store (const char *host, struct address_list *al)
606 {
607   if (!host_name_addresses_map)
608     host_name_addresses_map = make_nocase_string_hash_table (0);
609
610   ++al->refcount;
611   hash_table_put (host_name_addresses_map, xstrdup_lower (host), al);
612
613   IF_DEBUG
614     {
615       int i;
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");
620     }
621 }
622
623 /* Remove HOST from the DNS cache.  Does nothing is HOST is not in
624    the cache.  */
625
626 static void
627 cache_remove (const char *host)
628 {
629   struct address_list *al;
630   if (!host_name_addresses_map)
631     return;
632   al = hash_table_get (host_name_addresses_map, host);
633   if (al)
634     {
635       address_list_release (al);
636       hash_table_remove (host_name_addresses_map, host);
637     }
638 }
639 \f
640 /* Look up HOST in DNS and return a list of IP addresses.
641
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.)
646
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.
653
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.  */
661
662 struct address_list *
663 lookup_host (const char *host, int flags)
664 {
665   struct address_list *al;
666   bool silent = !!(flags & LH_SILENT);
667   bool use_cache;
668   bool numeric_address = false;
669   double timeout = opt.dns_timeout;
670
671 #ifndef ENABLE_IPV6
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.  */
676   {
677     uint32_t addr_ipv4 = (uint32_t)inet_addr (host);
678     if (addr_ipv4 != (uint32_t) -1)
679       {
680         /* No need to cache host->addr relation, just return the
681            address.  */
682         char *vec[2];
683         vec[0] = (char *)&addr_ipv4;
684         vec[1] = NULL;
685         return address_list_from_ipv4_addresses (vec);
686       }
687   }
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
693      url_parse.)  */
694   {
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;
698   }
699 #endif
700
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;
704 #ifdef ENABLE_IPV6
705   if ((flags & LH_BIND) || numeric_address)
706     use_cache = false;
707 #endif
708
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
711      instead.  */
712   if (use_cache)
713     {
714       if (!(flags & LH_REFRESH))
715         {
716           al = cache_query (host);
717           if (al)
718             return al;
719         }
720       else
721         cache_remove (host);
722     }
723
724   /* No luck with the cache; resolve HOST. */
725
726   if (!silent && !numeric_address)
727     logprintf (LOG_VERBOSE, _("Resolving %s... "), escnonprint (host));
728
729 #ifdef ENABLE_IPV6
730   {
731     int err;
732     struct addrinfo hints, *res;
733
734     xzero (hints);
735     hints.ai_socktype = SOCK_STREAM;
736     if (opt.ipv4_only)
737       hints.ai_family = AF_INET;
738     else if (opt.ipv6_only)
739       hints.ai_family = AF_INET6;
740     else
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;
745
746     if (flags & LH_BIND)
747       hints.ai_flags |= AI_PASSIVE;
748
749 #ifdef AI_NUMERICHOST
750     if (numeric_address)
751       {
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. */
758       }
759 #endif
760
761     err = getaddrinfo_with_timeout (host, NULL, &hints, &res, timeout);
762     if (err != 0 || res == NULL)
763       {
764         if (!silent)
765           logprintf (LOG_VERBOSE, _("failed: %s.\n"),
766                      err != EAI_SYSTEM ? gai_strerror (err) : strerror (errno));
767         return NULL;
768       }
769     al = address_list_from_addrinfo (res);
770     freeaddrinfo (res);
771     if (!al)
772       {
773         logprintf (LOG_VERBOSE,
774                    _("failed: No IPv4/IPv6 addresses for host.\n"));
775         return NULL;
776       }
777
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);
785   }
786 #else  /* not ENABLE_IPV6 */
787   {
788     struct hostent *hptr = gethostbyname_with_timeout (host, timeout);
789     if (!hptr)
790       {
791         if (!silent)
792           {
793             if (errno != ETIMEDOUT)
794               logprintf (LOG_VERBOSE, _("failed: %s.\n"),
795                          host_errstr (h_errno));
796             else
797               logputs (LOG_VERBOSE, _("failed: timed out.\n"));
798           }
799         return NULL;
800       }
801     /* Do older systems have h_addr_list?  */
802     al = address_list_from_ipv4_addresses (hptr->h_addr_list);
803   }
804 #endif /* not ENABLE_IPV6 */
805
806   /* Print the addresses determined by DNS lookup, but no more than
807      three.  */
808   if (!silent && !numeric_address)
809     {
810       int i;
811       int printmax = al->count <= 3 ? al->count : 3;
812       for (i = 0; i < printmax; i++)
813         {
814           logputs (LOG_VERBOSE, print_address (al->addresses + i));
815           if (i < printmax - 1)
816             logputs (LOG_VERBOSE, ", ");
817         }
818       if (printmax != al->count)
819         logputs (LOG_VERBOSE, ", ...");
820       logputs (LOG_VERBOSE, "\n");
821     }
822
823   /* Cache the lookup information. */
824   if (use_cache)
825     cache_store (host, al);
826
827   return al;
828 }
829 \f
830 /* Determine whether a URL is acceptable to be followed, according to
831    a list of domains to accept.  */
832 bool
833 accept_domain (struct url *u)
834 {
835   assert (u->host != NULL);
836   if (opt.domains)
837     {
838       if (!sufmatch ((const char **)opt.domains, u->host))
839         return false;
840     }
841   if (opt.exclude_domains)
842     {
843       if (sufmatch ((const char **)opt.exclude_domains, u->host))
844         return false;
845     }
846   return true;
847 }
848
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).
852
853    If an element of LIST matched, 1 is returned, 0 otherwise.  */
854 bool
855 sufmatch (const char **list, const char *what)
856 {
857   int i, j, k, lw;
858
859   lw = strlen (what);
860   for (i = 0; list[i]; i++)
861     {
862       for (j = strlen (list[i]), k = lw; j >= 0 && k >= 0; j--, k--)
863         if (TOLOWER (list[i][j]) != TOLOWER (what[k]))
864           break;
865       /* The domain must be first to reach to beginning.  */
866       if (j == -1)
867         return true;
868     }
869   return false;
870 }
871
872 static int
873 host_cleanup_mapper (void *key, void *value, void *arg_ignored)
874 {
875   struct address_list *al;
876
877   xfree (key);                  /* host */
878
879   al = (struct address_list *)value;
880   assert (al->refcount == 1);
881   address_list_delete (al);
882
883   return 0;
884 }
885
886 void
887 host_cleanup (void)
888 {
889   if (host_name_addresses_map)
890     {
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;
894     }
895 }