]> sjero.net Git - wget/blob - src/host.c
Steven Schweda's VMS patch.
[wget] / src / host.c
1 /* Host name resolution and matching.
2    Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
3    2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4
5 This file is part of GNU Wget.
6
7 GNU Wget is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10  (at your option) any later version.
11
12 GNU Wget is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Wget.  If not, see <http://www.gnu.org/licenses/>.
19
20 Additional permission under GNU GPL version 3 section 7
21
22 If you modify this program, or any covered work, by linking or
23 combining it with the OpenSSL project's OpenSSL library (or a
24 modified version of that library), containing parts covered by the
25 terms of the OpenSSL or SSLeay licenses, the Free Software Foundation
26 grants you additional permission to convey the resulting work.
27 Corresponding Source for a non-source form of such a combination
28 shall include the source code for the parts of OpenSSL used as well
29 as that of the covered work.  */
30
31 #include "wget.h"
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <assert.h>
37
38 #ifndef WINDOWS
39 # include <sys/socket.h>
40 # include <netinet/in.h>
41 # ifndef __BEOS__
42 #  include <arpa/inet.h>
43 # endif
44 # ifdef __VMS
45 #  include "vms_ip.h"
46 # else /* def __VMS */
47 #  include <netdb.h>
48 # endif /* def __VMS [else] */
49 # define SET_H_ERRNO(err) ((void)(h_errno = (err)))
50 #else  /* WINDOWS */
51 # define SET_H_ERRNO(err) WSASetLastError (err)
52 #endif /* WINDOWS */
53
54 #include <errno.h>
55
56 #include "utils.h"
57 #include "host.h"
58 #include "url.h"
59 #include "hash.h"
60
61 #ifndef NO_ADDRESS
62 # define NO_ADDRESS NO_DATA
63 #endif
64
65 /* Lists of IP addresses that result from running DNS queries.  See
66    lookup_host for details.  */
67
68 struct address_list {
69   int count;                    /* number of adrresses */
70   ip_address *addresses;        /* pointer to the string of addresses */
71
72   int faulty;                   /* number of addresses known not to work. */
73   bool connected;               /* whether we were able to connect to
74                                    one of the addresses in the list,
75                                    at least once. */
76
77   int refcount;                 /* reference count; when it drops to
78                                    0, the entry is freed. */
79 };
80
81 /* Get the bounds of the address list.  */
82
83 void
84 address_list_get_bounds (const struct address_list *al, int *start, int *end)
85 {
86   *start = al->faulty;
87   *end   = al->count;
88 }
89
90 /* Return a pointer to the address at position POS.  */
91
92 const ip_address *
93 address_list_address_at (const struct address_list *al, int pos)
94 {
95   assert (pos >= al->faulty && pos < al->count);
96   return al->addresses + pos;
97 }
98
99 /* Return true if AL contains IP, false otherwise.  */
100
101 bool
102 address_list_contains (const struct address_list *al, const ip_address *ip)
103 {
104   int i;
105   switch (ip->family)
106     {
107     case AF_INET:
108       for (i = 0; i < al->count; i++)
109         {
110           ip_address *cur = al->addresses + i;
111           if (cur->family == AF_INET
112               && (cur->data.d4.s_addr == ip->data.d4.s_addr))
113             return true;
114         }
115       return false;
116 #ifdef ENABLE_IPV6
117     case AF_INET6:
118       for (i = 0; i < al->count; i++)
119         {
120           ip_address *cur = al->addresses + i;
121           if (cur->family == AF_INET6
122 #ifdef HAVE_SOCKADDR_IN6_SCOPE_ID
123               && cur->ipv6_scope == ip->ipv6_scope
124 #endif
125               && IN6_ARE_ADDR_EQUAL (&cur->data.d6, &ip->data.d6))
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->family = AF_INET6;
204         ip->data.d6 = sin6->sin6_addr;
205 #ifdef HAVE_SOCKADDR_IN6_SCOPE_ID
206         ip->ipv6_scope = 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->family = AF_INET;
215         ip->data.d4 = 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)->family == AF_INET)
223
224 /* Compare two IP addresses by family, 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)->family == AF_INET6)
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->family = AF_INET;
272       memcpy (IP_INADDR_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 #ifdef ENABLE_IPV6
411   static char buf[64];
412   if (!inet_ntop (addr->family, IP_INADDR_DATA (addr), buf, sizeof buf))
413     snprintf (buf, sizeof buf, "<error: %s>", strerror (errno));
414   return buf;
415 #else
416   return inet_ntoa (addr->data.d4);
417 #endif
418 }
419
420 /* The following two functions were adapted from glibc's
421    implementation of inet_pton, written by Paul Vixie. */
422
423 static bool
424 is_valid_ipv4_address (const char *str, const char *end)
425 {
426   bool saw_digit = false;
427   int octets = 0;
428   int val = 0;
429
430   while (str < end)
431     {
432       int ch = *str++;
433
434       if (ch >= '0' && ch <= '9')
435         {
436           val = val * 10 + (ch - '0');
437
438           if (val > 255)
439             return false;
440           if (!saw_digit)
441             {
442               if (++octets > 4)
443                 return false;
444               saw_digit = true;
445             }
446         }
447       else if (ch == '.' && saw_digit)
448         {
449           if (octets == 4)
450             return false;
451           val = 0;
452           saw_digit = false;
453         }
454       else
455         return false;
456     }
457   if (octets < 4)
458     return false;
459   
460   return true;
461 }
462
463 bool
464 is_valid_ipv6_address (const char *str, const char *end)
465 {
466   /* Use lower-case for these to avoid clash with system headers.  */
467   enum {
468     ns_inaddrsz  = 4,
469     ns_in6addrsz = 16,
470     ns_int16sz   = 2
471   };
472
473   const char *curtok;
474   int tp;
475   const char *colonp;
476   bool saw_xdigit;
477   unsigned int val;
478
479   tp = 0;
480   colonp = NULL;
481
482   if (str == end)
483     return false;
484   
485   /* Leading :: requires some special handling. */
486   if (*str == ':')
487     {
488       ++str;
489       if (str == end || *str != ':')
490         return false;
491     }
492
493   curtok = str;
494   saw_xdigit = false;
495   val = 0;
496
497   while (str < end)
498     {
499       int ch = *str++;
500
501       /* if ch is a number, add it to val. */
502       if (c_isxdigit (ch))
503         {
504           val <<= 4;
505           val |= XDIGIT_TO_NUM (ch);
506           if (val > 0xffff)
507             return false;
508           saw_xdigit = true;
509           continue;
510         }
511
512       /* if ch is a colon ... */
513       if (ch == ':')
514         {
515           curtok = str;
516           if (!saw_xdigit)
517             {
518               if (colonp != NULL)
519                 return false;
520               colonp = str + tp;
521               continue;
522             }
523           else if (str == end)
524             return false;
525           if (tp > ns_in6addrsz - ns_int16sz)
526             return false;
527           tp += ns_int16sz;
528           saw_xdigit = false;
529           val = 0;
530           continue;
531         }
532
533       /* if ch is a dot ... */
534       if (ch == '.' && (tp <= ns_in6addrsz - ns_inaddrsz)
535           && is_valid_ipv4_address (curtok, end) == 1)
536         {
537           tp += ns_inaddrsz;
538           saw_xdigit = false;
539           break;
540         }
541     
542       return false;
543     }
544
545   if (saw_xdigit)
546     {
547       if (tp > ns_in6addrsz - ns_int16sz) 
548         return false;
549       tp += ns_int16sz;
550     }
551
552   if (colonp != NULL)
553     {
554       if (tp == ns_in6addrsz) 
555         return false;
556       tp = ns_in6addrsz;
557     }
558
559   if (tp != ns_in6addrsz)
560     return false;
561
562   return true;
563 }
564 \f
565 /* Simple host cache, used by lookup_host to speed up resolving.  The
566    cache doesn't handle TTL because Wget is a fairly short-lived
567    application.  Refreshing is attempted when connect fails, though --
568    see connect_to_host.  */
569
570 /* Mapping between known hosts and to lists of their addresses. */
571 static struct hash_table *host_name_addresses_map;
572
573
574 /* Return the host's resolved addresses from the cache, if
575    available.  */
576
577 static struct address_list *
578 cache_query (const char *host)
579 {
580   struct address_list *al;
581   if (!host_name_addresses_map)
582     return NULL;
583   al = hash_table_get (host_name_addresses_map, host);
584   if (al)
585     {
586       DEBUGP (("Found %s in host_name_addresses_map (%p)\n", host, al));
587       ++al->refcount;
588       return al;
589     }
590   return NULL;
591 }
592
593 /* Cache the DNS lookup of HOST.  Subsequent invocations of
594    lookup_host will return the cached value.  */
595
596 static void
597 cache_store (const char *host, struct address_list *al)
598 {
599   if (!host_name_addresses_map)
600     host_name_addresses_map = make_nocase_string_hash_table (0);
601
602   ++al->refcount;
603   hash_table_put (host_name_addresses_map, xstrdup_lower (host), al);
604
605   IF_DEBUG
606     {
607       int i;
608       debug_logprintf ("Caching %s =>", host);
609       for (i = 0; i < al->count; i++)
610         debug_logprintf (" %s", print_address (al->addresses + i));
611       debug_logprintf ("\n");
612     }
613 }
614
615 /* Remove HOST from the DNS cache.  Does nothing is HOST is not in
616    the cache.  */
617
618 static void
619 cache_remove (const char *host)
620 {
621   struct address_list *al;
622   if (!host_name_addresses_map)
623     return;
624   al = hash_table_get (host_name_addresses_map, host);
625   if (al)
626     {
627       address_list_release (al);
628       hash_table_remove (host_name_addresses_map, host);
629     }
630 }
631 \f
632 /* Look up HOST in DNS and return a list of IP addresses.
633
634    This function caches its result so that, if the same host is passed
635    the second time, the addresses are returned without DNS lookup.
636    (Use LH_REFRESH to force lookup, or set opt.dns_cache to 0 to
637    globally disable caching.)
638
639    The order of the returned addresses is affected by the setting of
640    opt.prefer_family: if it is set to prefer_ipv4, IPv4 addresses are
641    placed at the beginning; if it is prefer_ipv6, IPv6 ones are placed
642    at the beginning; otherwise, the order is left intact.  The
643    relative order of addresses with the same family is left
644    undisturbed in either case.
645
646    FLAGS can be a combination of:
647      LH_SILENT  - don't print the "resolving ... done" messages.
648      LH_BIND    - resolve addresses for use with bind, which under
649                   IPv6 means to use AI_PASSIVE flag to getaddrinfo.
650                   Passive lookups are not cached under IPv6.
651      LH_REFRESH - if HOST is cached, remove the entry from the cache
652                   and resolve it anew.  */
653
654 struct address_list *
655 lookup_host (const char *host, int flags)
656 {
657   struct address_list *al;
658   bool silent = !!(flags & LH_SILENT);
659   bool use_cache;
660   bool numeric_address = false;
661   double timeout = opt.dns_timeout;
662
663 #ifndef ENABLE_IPV6
664   /* If we're not using getaddrinfo, first check if HOST specifies a
665      numeric IPv4 address.  Some implementations of gethostbyname
666      (e.g. the Ultrix one and possibly Winsock) don't accept
667      dotted-decimal IPv4 addresses.  */
668   {
669     uint32_t addr_ipv4 = (uint32_t)inet_addr (host);
670     if (addr_ipv4 != (uint32_t) -1)
671       {
672         /* No need to cache host->addr relation, just return the
673            address.  */
674         char *vec[2];
675         vec[0] = (char *)&addr_ipv4;
676         vec[1] = NULL;
677         return address_list_from_ipv4_addresses (vec);
678       }
679   }
680 #else  /* ENABLE_IPV6 */
681   /* If we're using getaddrinfo, at least check whether the address is
682      already numeric, in which case there is no need to print the
683      "Resolving..." output.  (This comes at no additional cost since
684      the is_valid_ipv*_address are already required for
685      url_parse.)  */
686   {
687     const char *end = host + strlen (host);
688     if (is_valid_ipv4_address (host, end) || is_valid_ipv6_address (host, end))
689       numeric_address = true;
690   }
691 #endif
692
693   /* Cache is normally on, but can be turned off with --no-dns-cache.
694      Don't cache passive lookups under IPv6.  */
695   use_cache = opt.dns_cache;
696 #ifdef ENABLE_IPV6
697   if ((flags & LH_BIND) || numeric_address)
698     use_cache = false;
699 #endif
700
701   /* Try to find the host in the cache so we don't need to talk to the
702      resolver.  If LH_REFRESH is requested, remove HOST from the cache
703      instead.  */
704   if (use_cache)
705     {
706       if (!(flags & LH_REFRESH))
707         {
708           al = cache_query (host);
709           if (al)
710             return al;
711         }
712       else
713         cache_remove (host);
714     }
715
716   /* No luck with the cache; resolve HOST. */
717
718   if (!silent && !numeric_address)
719     logprintf (LOG_VERBOSE, _("Resolving %s... "), escnonprint (host));
720
721 #ifdef ENABLE_IPV6
722   {
723     int err;
724     struct addrinfo hints, *res;
725
726     xzero (hints);
727     hints.ai_socktype = SOCK_STREAM;
728     if (opt.ipv4_only)
729       hints.ai_family = AF_INET;
730     else if (opt.ipv6_only)
731       hints.ai_family = AF_INET6;
732     else
733       /* We tried using AI_ADDRCONFIG, but removed it because: it
734          misinterprets IPv6 loopbacks, it is broken on AIX 5.1, and
735          it's unneeded since we sort the addresses anyway.  */
736         hints.ai_family = AF_UNSPEC;
737
738     if (flags & LH_BIND)
739       hints.ai_flags |= AI_PASSIVE;
740
741 #ifdef AI_NUMERICHOST
742     if (numeric_address)
743       {
744         /* Where available, the AI_NUMERICHOST hint can prevent costly
745            access to DNS servers.  */
746         hints.ai_flags |= AI_NUMERICHOST;
747         timeout = 0;            /* no timeout needed when "resolving"
748                                    numeric hosts -- avoid setting up
749                                    signal handlers and such. */
750       }
751 #endif
752
753     err = getaddrinfo_with_timeout (host, NULL, &hints, &res, timeout);
754     if (err != 0 || res == NULL)
755       {
756         if (!silent)
757           logprintf (LOG_VERBOSE, _("failed: %s.\n"),
758                      err != EAI_SYSTEM ? gai_strerror (err) : strerror (errno));
759         return NULL;
760       }
761     al = address_list_from_addrinfo (res);
762     freeaddrinfo (res);
763     if (!al)
764       {
765         logprintf (LOG_VERBOSE,
766                    _("failed: No IPv4/IPv6 addresses for host.\n"));
767         return NULL;
768       }
769
770     /* Reorder addresses so that IPv4 ones (or IPv6 ones, as per
771        --prefer-family) come first.  Sorting is stable so the order of
772        the addresses with the same family is undisturbed.  */
773     if (al->count > 1 && opt.prefer_family != prefer_none)
774       stable_sort (al->addresses, al->count, sizeof (ip_address),
775                    opt.prefer_family == prefer_ipv4
776                    ? cmp_prefer_ipv4 : cmp_prefer_ipv6);
777   }
778 #else  /* not ENABLE_IPV6 */
779   {
780     struct hostent *hptr = gethostbyname_with_timeout (host, timeout);
781     if (!hptr)
782       {
783         if (!silent)
784           {
785             if (errno != ETIMEDOUT)
786               logprintf (LOG_VERBOSE, _("failed: %s.\n"),
787                          host_errstr (h_errno));
788             else
789               logputs (LOG_VERBOSE, _("failed: timed out.\n"));
790           }
791         return NULL;
792       }
793     /* Do older systems have h_addr_list?  */
794     al = address_list_from_ipv4_addresses (hptr->h_addr_list);
795   }
796 #endif /* not ENABLE_IPV6 */
797
798   /* Print the addresses determined by DNS lookup, but no more than
799      three.  */
800   if (!silent && !numeric_address)
801     {
802       int i;
803       int printmax = al->count <= 3 ? al->count : 3;
804       for (i = 0; i < printmax; i++)
805         {
806           logputs (LOG_VERBOSE, print_address (al->addresses + i));
807           if (i < printmax - 1)
808             logputs (LOG_VERBOSE, ", ");
809         }
810       if (printmax != al->count)
811         logputs (LOG_VERBOSE, ", ...");
812       logputs (LOG_VERBOSE, "\n");
813     }
814
815   /* Cache the lookup information. */
816   if (use_cache)
817     cache_store (host, al);
818
819   return al;
820 }
821 \f
822 /* Determine whether a URL is acceptable to be followed, according to
823    a list of domains to accept.  */
824 bool
825 accept_domain (struct url *u)
826 {
827   assert (u->host != NULL);
828   if (opt.domains)
829     {
830       if (!sufmatch ((const char **)opt.domains, u->host))
831         return false;
832     }
833   if (opt.exclude_domains)
834     {
835       if (sufmatch ((const char **)opt.exclude_domains, u->host))
836         return false;
837     }
838   return true;
839 }
840
841 /* Check whether WHAT is matched in LIST, each element of LIST being a
842    pattern to match WHAT against, using backward matching (see
843    match_backwards() in utils.c).
844
845    If an element of LIST matched, 1 is returned, 0 otherwise.  */
846 bool
847 sufmatch (const char **list, const char *what)
848 {
849   int i, j, k, lw;
850
851   lw = strlen (what);
852   for (i = 0; list[i]; i++)
853     {
854       for (j = strlen (list[i]), k = lw; j >= 0 && k >= 0; j--, k--)
855         if (c_tolower (list[i][j]) != c_tolower (what[k]))
856           break;
857       /* The domain must be first to reach to beginning.  */
858       if (j == -1)
859         return true;
860     }
861   return false;
862 }
863
864 void
865 host_cleanup (void)
866 {
867   if (host_name_addresses_map)
868     {
869       hash_table_iterator iter;
870       for (hash_table_iterate (host_name_addresses_map, &iter);
871            hash_table_iter_next (&iter);
872            )
873         {
874           char *host = iter.key;
875           struct address_list *al = iter.value;
876           xfree (host);
877           assert (al->refcount == 1);
878           address_list_delete (al);
879         }
880       hash_table_destroy (host_name_addresses_map);
881       host_name_addresses_map = NULL;
882     }
883 }