]> sjero.net Git - wget/blob - src/host.c
[svn] Extend the timeout to DNS lookups.
[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 #include <config.h>
21
22 #ifndef WINDOWS
23 #include <netdb.h>
24 #endif
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #ifdef HAVE_STRING_H
29 # include <string.h>
30 #else
31 # include <strings.h>
32 #endif
33 #include <assert.h>
34 #include <sys/types.h>
35
36 #ifdef WINDOWS
37 # include <winsock.h>
38 #else
39 # include <sys/socket.h>
40 # include <netinet/in.h>
41 # ifndef __BEOS__
42 #  include <arpa/inet.h>
43 # endif
44 # include <netdb.h>
45 #endif /* WINDOWS */
46
47 #ifndef NO_ADDRESS
48 #define NO_ADDRESS NO_DATA
49 #endif
50
51 #ifdef HAVE_SYS_UTSNAME_H
52 # include <sys/utsname.h>
53 #endif
54 #include <errno.h>
55
56 #include "wget.h"
57 #include "utils.h"
58 #include "host.h"
59 #include "url.h"
60 #include "hash.h"
61
62 #ifndef errno
63 extern int errno;
64 #endif
65
66 #ifndef h_errno
67 # ifndef __CYGWIN__
68 extern int h_errno;
69 # endif
70 #endif
71
72 #ifdef INET6
73 int     ip_default_family = AF_INET6;
74 #else
75 int     ip_default_family = AF_INET;
76 #endif
77
78 /* Mapping between known hosts and to lists of their addresses. */
79
80 static struct hash_table *host_name_addresses_map;
81 \f
82 /* Lists of addresses.  This should eventually be extended to handle
83    IPv6.  */
84
85 struct address_list {
86   int count;                    /* number of adrresses */
87   ip_address *addresses;        /* pointer to the string of addresses */
88
89   int faulty;                   /* number of addresses known not to work. */
90   int refcount;                 /* so we know whether to free it or not. */
91 };
92
93 /* Get the bounds of the address list.  */
94
95 void
96 address_list_get_bounds (struct address_list *al, int *start, int *end)
97 {
98   *start = al->faulty;
99   *end   = al->count;
100 }
101
102 /* Copy address number INDEX to IP_STORE.  */
103
104 void
105 address_list_copy_one (struct address_list *al, int index, ip_address *ip_store)
106 {
107   assert (index >= al->faulty && index < al->count);
108   memcpy (ip_store, al->addresses + index, sizeof (ip_address));
109 }
110
111 /* Check whether two address lists have all their IPs in common.  */
112
113 int
114 address_list_match_all (struct address_list *al1, struct address_list *al2)
115 {
116   if (al1 == al2)
117     return 1;
118   if (al1->count != al2->count)
119     return 0;
120   return 0 == memcmp (al1->addresses, al2->addresses,
121                       al1->count * sizeof (ip_address));
122 }
123
124 /* Mark the INDEXth element of AL as faulty, so that the next time
125    this address list is used, the faulty element will be skipped.  */
126
127 void
128 address_list_set_faulty (struct address_list *al, int index)
129 {
130   /* We assume that the address list is traversed in order, so that a
131      "faulty" attempt is always preceded with all-faulty addresses,
132      and this is how Wget uses it.  */
133   assert (index == al->faulty);
134
135   ++al->faulty;
136   if (al->faulty >= al->count)
137     /* All addresses have been proven faulty.  Since there's not much
138        sense in returning the user an empty address list the next
139        time, we'll rather make them all clean, so that they can be
140        retried anew.  */
141     al->faulty = 0;
142 }
143
144 #ifdef INET6
145 /**
146   * address_list_from_addrinfo
147   *
148   * This function transform an addrinfo links list in and address_list.
149   *
150   * Input:
151   * addrinfo*           Linkt list of addrinfo
152   *
153   * Output:
154   * address_list*       New allocated address_list
155   */
156 static struct address_list *
157 address_list_from_addrinfo (struct addrinfo *ai)
158 {
159   struct address_list *al;
160   struct addrinfo *ai_head = ai;
161   int cnt = 0;
162   int i;
163
164   for (ai = ai_head; ai; ai = ai->ai_next)
165     if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6)
166       ++cnt;
167   if (cnt == 0)
168     return NULL;
169
170   al = xmalloc (sizeof (struct address_list));
171   al->addresses = xmalloc (cnt * sizeof (ip_address));
172   al->count     = cnt;
173   al->faulty    = 0;
174   al->refcount  = 1;
175
176   for (i = 0, ai = ai_head; ai; ai = ai->ai_next)
177     if (ai->ai_family == AF_INET6) 
178       {
179         struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)ai->ai_addr;
180         memcpy (al->addresses + i, &sin6->sin6_addr, 16);
181         ++i;
182       } 
183     else if (ai->ai_family == AF_INET)
184       {
185         struct sockaddr_in *sin = (struct sockaddr_in *)ai->ai_addr;
186         map_ipv4_to_ip ((ip4_address *)&sin->sin_addr, al->addresses + i);
187         ++i;
188       }
189   assert (i == cnt);
190   return al;
191 }
192 #else
193 /* Create an address_list out of a NULL-terminated list of addresses,
194    as returned by gethostbyname.  */
195 static struct address_list *
196 address_list_new (char **h_addr_list)
197 {
198   int count = 0, i;
199
200   struct address_list *al = xmalloc (sizeof (struct address_list));
201
202   while (h_addr_list[count])
203     ++count;
204   assert (count > 0);
205   al->count     = count;
206   al->faulty    = 0;
207   al->addresses = xmalloc (count * sizeof (ip_address));
208   al->refcount  = 1;
209
210   for (i = 0; i < count; i++)
211     map_ipv4_to_ip ((ip4_address *)h_addr_list[i], al->addresses + i);
212
213   return al;
214 }
215 #endif
216
217 /* Like address_list_new, but initialized with only one address. */
218
219 static struct address_list *
220 address_list_new_one (ip_address *addr)
221 {
222   struct address_list *al = xmalloc (sizeof (struct address_list));
223   al->count     = 1;
224   al->faulty    = 0;
225   al->addresses = xmalloc (sizeof (ip_address));
226   al->refcount  = 1;
227   memcpy (al->addresses, addr, sizeof (ip_address));
228
229   return al;
230 }
231
232 static void
233 address_list_delete (struct address_list *al)
234 {
235   xfree (al->addresses);
236   xfree (al);
237 }
238
239 void
240 address_list_release (struct address_list *al)
241 {
242   --al->refcount;
243   DEBUGP (("Releasing %p (new refcount %d).\n", al, al->refcount));
244   if (al->refcount <= 0)
245     {
246       DEBUGP (("Deleting unused %p.\n", al));
247       address_list_delete (al);
248     }
249 }
250 \f
251 /**
252   * wget_sockaddr_set_address
253   *
254   * This function takes an wget_sockaddr and fill in the protocol type,
255   * the port number and the address, there NULL in address means wildcard.
256   * Unsuported adress family will abort the whole programm.
257   *
258   * Input:
259   * wget_sockaddr*      The space to be filled
260   * int                 The wished protocol
261   * unsigned short      The port
262   * const ip_address    The Binary IP adress
263   *
264   * Return:
265   * -                   Only modify 1. param
266   */
267 void
268 wget_sockaddr_set_address (wget_sockaddr *sa, 
269                            int ip_family, unsigned short port, ip_address *addr)
270 {
271   if (ip_family == AF_INET) 
272     {
273       sa->sin.sin_family = ip_family;
274       sa->sin.sin_port = htons (port);
275       if (addr == NULL) 
276         memset (&sa->sin.sin_addr, 0,      sizeof(ip4_address));
277       else
278         {
279           ip4_address addr4;
280           if (!map_ip_to_ipv4 (addr, &addr4))
281             /* should the callers have prevented this? */
282             abort ();
283           memcpy (&sa->sin.sin_addr, &addr4, sizeof(ip4_address));
284         }
285       return;
286     }
287 #ifdef INET6
288   if (ip_family == AF_INET6) 
289     {
290       sa->sin6.sin6_family = ip_family;
291       sa->sin6.sin6_port = htons (port);
292       if (addr == NULL) 
293         memset (&sa->sin6.sin6_addr, 0   , 16);
294       else           
295         memcpy (&sa->sin6.sin6_addr, addr, 16);
296       return;
297     }
298 #endif  
299   abort();
300 }
301
302 /**
303   * wget_sockaddr_set_port
304   *
305   * This funtion only fill the port of the socket information.
306   * If the protocol is not supported nothing is done.
307   * Unsuported adress family will abort the whole programm.
308   * 
309   * Require:
310   * that the IP-Protocol already is set.
311   *
312   * Input:
313   * wget_sockaddr*      The space there port should be entered
314   * unsigned int        The port that should be entered in host order
315   *
316   * Return:
317   * -                   Only modify 1. param
318   */
319 void 
320 wget_sockaddr_set_port (wget_sockaddr *sa, unsigned short port)
321 {
322   if (sa->sa.sa_family == AF_INET)
323     {
324       sa->sin.sin_port = htons (port);
325       return;
326     }  
327 #ifdef INET6
328   if (sa->sa.sa_family == AF_INET6)
329     {
330       sa->sin6.sin6_port = htons (port);
331       return;
332     }
333 #endif
334   abort();
335 }
336
337 /**
338   * wget_sockaddr_get_addr
339   *
340   * This function return the adress from an sockaddr as byte string.
341   * Unsuported adress family will abort the whole programm.
342   * 
343   * Require:
344   * that the IP-Protocol already is set.
345   *
346   * Input:
347   * wget_sockaddr*      Socket Information
348   *
349   * Output:
350   * unsigned char *     IP address as byte string.
351   */
352 void *
353 wget_sockaddr_get_addr (wget_sockaddr *sa)
354
355   if (sa->sa.sa_family == AF_INET)
356     return &sa->sin.sin_addr;
357 #ifdef INET6
358   if (sa->sa.sa_family == AF_INET6)
359     return &sa->sin6.sin6_addr;
360 #endif
361   abort();
362   /* unreached */
363   return NULL;
364 }
365
366 /**
367   * wget_sockaddr_get_port
368   *
369   * This function only return the port from the input structure
370   * Unsuported adress family will abort the whole programm.
371   * 
372   * Require:
373   * that the IP-Protocol already is set.
374   *
375   * Input:
376   * wget_sockaddr*      Information where to get the port
377   *
378   * Output:
379   * unsigned short      Port Number in host order.
380   */
381 unsigned short 
382 wget_sockaddr_get_port (const wget_sockaddr *sa)
383 {
384   if (sa->sa.sa_family == AF_INET)
385       return htons (sa->sin.sin_port);
386 #ifdef INET6
387   if (sa->sa.sa_family == AF_INET6)
388       return htons (sa->sin6.sin6_port);
389 #endif
390   abort();
391   /* do not complain about return nothing */
392   return -1;
393 }
394
395 /**
396   * sockaddr_len
397   *
398   * This function return the length of the sockaddr corresponding to 
399   * the acutall prefered protocol for (bind, connect etc...)
400   * Unsuported adress family will abort the whole programm.
401   * 
402   * Require:
403   * that the IP-Protocol already is set.
404   *
405   * Input:
406   * -           Public IP-Family Information
407   *
408   * Output:
409   * int         structure length for socket options
410   */
411 int 
412 sockaddr_len () 
413 {
414   if (ip_default_family == AF_INET) 
415     return sizeof (struct sockaddr_in);
416 #ifdef INET6
417   if (ip_default_family == AF_INET6) 
418     return sizeof (struct sockaddr_in6);
419 #endif
420   abort();
421   /* do not complain about return nothing */
422   return 0;
423 }
424
425 /**
426   * Map an IPv4 adress to the internal adress format.
427   */
428 void 
429 map_ipv4_to_ip (ip4_address *ipv4, ip_address *ip) 
430 {
431 #ifdef INET6
432   static unsigned char ipv64[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff};
433   memcpy ((char *)ip + 12, ipv4 , 4);
434   memcpy ((char *)ip + 0, ipv64, 12);
435 #else
436   if ((char *)ip != (char *)ipv4)
437     memcpy (ip, ipv4, 4);
438 #endif
439 }
440
441 /* Detect whether an IP adress represents an IPv4 address and, if so,
442    copy it to IPV4.  0 is returned on failure.
443    This operation always succeeds when Wget is compiled without IPv6.
444    If IPV4 is NULL, don't copy, just detect.  */
445
446 int 
447 map_ip_to_ipv4 (ip_address *ip, ip4_address *ipv4) 
448 {
449 #ifdef INET6
450   static unsigned char ipv64[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff};
451   if (0 != memcmp (ip, ipv64, 12))
452     return 0;
453   if (ipv4)
454     memcpy (ipv4, (char *)ip + 12, 4);
455 #else
456   if (ipv4)
457     memcpy (ipv4, (char *)ip, 4);
458 #endif
459   return 1;
460 }
461 \f
462 /* Versions of gethostbyname and getaddrinfo that support timeout. */
463
464 #ifndef INET6
465
466 struct ghbnwt_context {
467   const char *host_name;
468   struct hostent *hptr;
469 };
470
471 static void
472 gethostbyname_with_timeout_callback (void *arg)
473 {
474   struct ghbnwt_context *ctx = (struct ghbnwt_context *)arg;
475   ctx->hptr = gethostbyname (ctx->host_name);
476 }
477
478 /* Just like gethostbyname, except it times out after TIMEOUT seconds.
479    In case of timeout, NULL is returned and errno is set to ETIMEDOUT.
480    The function makes sure that when NULL is returned for reasons
481    other than timeout, errno is reset.  */
482
483 static struct hostent *
484 gethostbyname_with_timeout (const char *host_name, int timeout)
485 {
486   struct ghbnwt_context ctx;
487   ctx.host_name = host_name;
488   if (run_with_timeout (timeout, gethostbyname_with_timeout_callback, &ctx))
489     {
490       h_errno = HOST_NOT_FOUND;
491       errno = ETIMEDOUT;
492       return NULL;
493     }
494   if (!ctx.hptr)
495     errno = 0;
496   return ctx.hptr;
497 }
498
499 #else  /* INET6 */
500
501 struct gaiwt_context {
502   const char *node;
503   const char *service;
504   const struct addrinfo *hints;
505   struct addrinfo **res;
506   int exit_code;
507 };
508
509 static void
510 getaddrinfo_with_timeout_callback (void *arg)
511 {
512   struct gaiwt_context *ctx = (struct gaiwt_context *)arg;
513   ctx->exit_code = getaddrinfo (ctx->node, ctx->service, ctx->hints, ctx->res);
514 }
515
516 /* Just like getaddrinfo, except it times out after TIMEOUT seconds.
517    In case of timeout, the EAI_SYSTEM error code is returned and errno
518    is set to ETIMEDOUT.  */
519
520 static int
521 getaddrinfo_with_timeout (const char *node, const char *service,
522                           const struct addrinfo *hints, struct addrinfo **res,
523                           int timeout)
524 {
525   struct gaiwt_context ctx;
526   ctx.node = node;
527   ctx.service = service;
528   ctx.hints = hints;
529   ctx.res = res;
530
531   if (run_with_timeout (timeout, getaddrinfo_with_timeout_callback, &ctx))
532     {
533       errno = ETIMEDOUT;
534       return EAI_SYSTEM;
535     }
536   return ctx.exit_code;
537 }
538
539 #endif /* INET6 */
540 \f
541 /* Pretty-print ADDR.  When compiled without IPv6, this is the same as
542    inet_ntoa.  With IPv6, it either prints an IPv6 address or an IPv4
543    address.  */
544
545 char *
546 pretty_print_address (ip_address *addr)
547 {
548 #ifdef INET6
549   ip4_address addr4;
550   static char buf[128];
551
552   if (map_ip_to_ipv4 (addr, &addr4))
553     return inet_ntoa (*(struct in_addr *)&addr4);
554
555   if (!inet_ntop (AF_INET6, addr, buf, sizeof (buf)))
556     return "<unknown>";
557   return buf;
558 #endif
559   return inet_ntoa (*(struct in_addr *)addr);
560 }
561
562 /* Add host name HOST with the address ADDR_TEXT to the cache.
563    ADDR_LIST is a NULL-terminated list of addresses, as in struct
564    hostent.  */
565
566 static void
567 cache_host_lookup (const char *host, struct address_list *al)
568 {
569   if (!host_name_addresses_map)
570     host_name_addresses_map = make_nocase_string_hash_table (0);
571
572   ++al->refcount;
573   hash_table_put (host_name_addresses_map, xstrdup_lower (host), al);
574
575 #ifdef DEBUG
576   if (opt.debug)
577     {
578       int i;
579       debug_logprintf ("Caching %s =>", host);
580       for (i = 0; i < al->count; i++)
581         debug_logprintf (" %s", pretty_print_address (al->addresses + i));
582       debug_logprintf ("\n");
583     }
584 #endif
585 }
586
587 struct address_list *
588 lookup_host (const char *host, int silent)
589 {
590   struct address_list *al = NULL;
591   unsigned long addr_ipv4;      /* #### use a 32-bit type here. */
592   ip_address addr;
593
594   /* First, try to check whether the address is already a numeric
595      address.  */
596
597 #ifdef INET6
598   if (inet_pton (AF_INET6, host, &addr) > 0)
599     return address_list_new_one (&addr);
600 #endif
601
602   addr_ipv4 = (unsigned long)inet_addr (host);
603   if ((int)addr_ipv4 != -1)
604     {
605       /* ADDR is defined to be in network byte order, which is what
606          this returns, so we can just copy it to STORE_IP.  However,
607          on big endian 64-bit architectures the value will be stored
608          in the *last*, not first four bytes.  OFFSET makes sure that
609          we copy the correct four bytes.  */
610       int offset = 0;
611 #ifdef WORDS_BIGENDIAN
612       offset = sizeof (unsigned long) - sizeof (ip4_address);
613 #endif
614       map_ipv4_to_ip ((ip4_address *)((char *)&addr_ipv4 + offset), &addr);
615       return address_list_new_one (&addr);
616     }
617
618   if (host_name_addresses_map)
619     {
620       al = hash_table_get (host_name_addresses_map, host);
621
622       if (al)
623         {
624           DEBUGP (("Found %s in host_name_addresses_map (%p)\n", host, al));
625           ++al->refcount;
626           return al;
627         }
628     }
629
630   if (!silent)
631     logprintf (LOG_VERBOSE, _("Resolving %s... "), host);
632
633   /* Host name lookup goes on below. */
634
635 #ifdef INET6
636   {
637     struct addrinfo hints, *ai;
638     int err;
639
640     memset (&hints, 0, sizeof (hints));
641     if (ip_default_family == AF_INET)
642       hints.ai_family   = AF_INET;
643     else
644       hints.ai_family   = PF_UNSPEC;
645     hints.ai_socktype = SOCK_STREAM;
646     err = getaddrinfo_with_timeout (host, NULL, &hints, &ai, opt.timeout);
647
648     if (err != 0 || ai == NULL)
649       {
650         if (!silent)
651           logprintf (LOG_VERBOSE, _("failed: %s.\n"),
652                      err != EAI_SYSTEM ? gai_strerror (err) : strerror (errno));
653         return NULL;
654       }
655     al = address_list_from_addrinfo (ai);
656     freeaddrinfo (ai);
657   }
658 #else
659   {
660     struct hostent *hptr = gethostbyname_with_timeout (host, opt.timeout);
661     if (!hptr)
662       {
663         if (!silent)
664           {
665             if (errno != ETIMEDOUT)
666               logprintf (LOG_VERBOSE, _("failed: %s.\n"), herrmsg (h_errno));
667             else
668               logputs (LOG_VERBOSE, _("failed: timed out.\n"));
669           }
670         return NULL;
671       }
672     /* Do all systems have h_addr_list, or is it a newer thing?  If
673        the latter, use address_list_new_one.  */
674     al = address_list_new (hptr->h_addr_list);
675   }
676 #endif
677
678   if (!silent)
679     logprintf (LOG_VERBOSE, _("done.\n"));
680
681   /* Cache the lookup information. */
682   cache_host_lookup (host, al);
683
684   return al;
685 }
686 \f
687 /* Determine whether a URL is acceptable to be followed, according to
688    a list of domains to accept.  */
689 int
690 accept_domain (struct url *u)
691 {
692   assert (u->host != NULL);
693   if (opt.domains)
694     {
695       if (!sufmatch ((const char **)opt.domains, u->host))
696         return 0;
697     }
698   if (opt.exclude_domains)
699     {
700       if (sufmatch ((const char **)opt.exclude_domains, u->host))
701         return 0;
702     }
703   return 1;
704 }
705
706 /* Check whether WHAT is matched in LIST, each element of LIST being a
707    pattern to match WHAT against, using backward matching (see
708    match_backwards() in utils.c).
709
710    If an element of LIST matched, 1 is returned, 0 otherwise.  */
711 int
712 sufmatch (const char **list, const char *what)
713 {
714   int i, j, k, lw;
715
716   lw = strlen (what);
717   for (i = 0; list[i]; i++)
718     {
719       for (j = strlen (list[i]), k = lw; j >= 0 && k >= 0; j--, k--)
720         if (TOLOWER (list[i][j]) != TOLOWER (what[k]))
721           break;
722       /* The domain must be first to reach to beginning.  */
723       if (j == -1)
724         return 1;
725     }
726   return 0;
727 }
728
729 /* Print error messages for host errors.  */
730 char *
731 herrmsg (int error)
732 {
733   /* Can't use switch since some constants are equal (at least on my
734      system), and the compiler signals "duplicate case value".  */
735   if (error == HOST_NOT_FOUND
736       || error == NO_RECOVERY
737       || error == NO_DATA
738       || error == NO_ADDRESS
739       || error == TRY_AGAIN)
740     return _("Host not found");
741   else
742     return _("Unknown error");
743 }
744
745 static int
746 host_cleanup_mapper (void *key, void *value, void *arg_ignored)
747 {
748   struct address_list *al;
749
750   xfree (key);                  /* host */
751
752   al = (struct address_list *)value;
753   assert (al->refcount == 1);
754   address_list_delete (al);
755
756   return 0;
757 }
758
759 void
760 host_cleanup (void)
761 {
762   if (host_name_addresses_map)
763     {
764       hash_table_map (host_name_addresses_map, host_cleanup_mapper, NULL);
765       hash_table_destroy (host_name_addresses_map);
766       host_name_addresses_map = NULL;
767     }
768 }