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