1 /* Handling of recursive HTTP retrieving.
2 Copyright (C) 1995, 1996, 1997, 2000, 2001 Free Software Foundation, Inc.
4 This file is part of GNU Wget.
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.
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.
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. */
28 #endif /* HAVE_STRING_H */
31 #endif /* HAVE_UNISTD_H */
34 #include <sys/types.h>
51 extern char *version_string;
53 static struct hash_table *dl_file_url_map;
54 static struct hash_table *dl_url_file_map;
56 /* List of HTML files downloaded in this Wget run, used for link
57 conversion after Wget is done. The list and the set contain the
58 same information, except the list maintains the order. Perhaps I
59 should get rid of the list, it's there for historical reasons. */
60 static slist *downloaded_html_list;
61 static struct hash_table *downloaded_html_set;
63 static void register_delete_file PARAMS ((const char *));
65 /* Functions for maintaining the URL queue. */
67 struct queue_element {
71 struct queue_element *next;
75 struct queue_element *head;
76 struct queue_element *tail;
80 /* Create a URL queue. */
82 static struct url_queue *
85 struct url_queue *queue = xmalloc (sizeof (*queue));
86 memset (queue, '\0', sizeof (*queue));
90 /* Delete a URL queue. */
93 url_queue_delete (struct url_queue *queue)
98 /* Enqueue a URL in the queue. The queue is FIFO: the items will be
99 retrieved ("dequeued") from the queue in the order they were placed
103 url_enqueue (struct url_queue *queue,
104 const char *url, const char *referer, int depth)
106 struct queue_element *qel = xmalloc (sizeof (*qel));
108 qel->referer = referer;
113 if (queue->count > queue->maxcount)
114 queue->maxcount = queue->count;
116 DEBUGP (("Enqueuing %s at depth %d\n", url, depth));
117 DEBUGP (("Queue count %d, maxcount %d.\n", queue->count, queue->maxcount));
120 queue->tail->next = qel;
124 queue->head = queue->tail;
127 /* Take a URL out of the queue. Return 1 if this operation succeeded,
128 or 0 if the queue is empty. */
131 url_dequeue (struct url_queue *queue,
132 const char **url, const char **referer, int *depth)
134 struct queue_element *qel = queue->head;
139 queue->head = queue->head->next;
144 *referer = qel->referer;
149 DEBUGP (("Dequeuing %s at depth %d\n", qel->url, qel->depth));
150 DEBUGP (("Queue count %d, maxcount %d.\n", queue->count, queue->maxcount));
156 static int download_child_p PARAMS ((const struct urlpos *, struct url *, int,
157 struct url *, struct hash_table *));
158 static int descend_redirect_p PARAMS ((const char *, const char *, int,
159 struct url *, struct hash_table *));
162 /* Retrieve a part of the web beginning with START_URL. This used to
163 be called "recursive retrieval", because the old function was
164 recursive and implemented depth-first search. retrieve_tree on the
165 other hand implements breadth-search traversal of the tree, which
166 results in much nicer ordering of downloads.
168 The algorithm this function uses is simple:
170 1. put START_URL in the queue.
171 2. while there are URLs in the queue:
173 3. get next URL from the queue.
175 5. if the URL is HTML and its depth does not exceed maximum depth,
176 get the list of URLs embedded therein.
177 6. for each of those URLs do the following:
179 7. if the URL is not one of those downloaded before, and if it
180 satisfies the criteria specified by the various command-line
181 options, add it to the queue. */
184 retrieve_tree (const char *start_url)
186 uerr_t status = RETROK;
188 /* The queue of URLs we need to load. */
189 struct url_queue *queue = url_queue_new ();
191 /* The URLs we do not wish to enqueue, because they are already in
192 the queue, but haven't been downloaded yet. */
193 struct hash_table *blacklist = make_string_hash_table (0);
195 /* We'll need various components of this, so better get it over with
197 struct url *start_url_parsed = url_parse (start_url, NULL);
199 url_enqueue (queue, xstrdup (start_url), NULL, 0);
200 string_set_add (blacklist, start_url);
205 char *url, *referer, *file = NULL;
207 boolean dash_p_leaf_HTML = FALSE;
209 if (downloaded_exceeds_quota ())
211 if (status == FWRITEERR)
214 /* Get the next URL from the queue... */
216 if (!url_dequeue (queue,
217 (const char **)&url, (const char **)&referer,
221 /* ...and download it. Note that this download is in most cases
222 unconditional, as download_child_p already makes sure a file
223 doesn't get enqueued twice -- and yet this check is here, and
224 not in download_child_p. This is so that if you run `wget -r
225 URL1 URL2', and a random URL is encountered once under URL1
226 and again under URL2, but at a different (possibly smaller)
227 depth, we want the URL's children to be taken into account
229 if (dl_url_file_map && hash_table_contains (dl_url_file_map, url))
231 file = xstrdup (hash_table_get (dl_url_file_map, url));
233 DEBUGP (("Already downloaded \"%s\", reusing it from \"%s\".\n",
236 if (string_set_contains (downloaded_html_set, file))
242 char *redirected = NULL;
243 int oldrec = opt.recursive;
246 status = retrieve_url (url, &file, &redirected, referer, &dt);
247 opt.recursive = oldrec;
249 if (file && status == RETROK
250 && (dt & RETROKF) && (dt & TEXTHTML))
255 /* We have been redirected, possibly to another host, or
256 different path, or wherever. Check whether we really
257 want to follow it. */
260 if (!descend_redirect_p (redirected, url, depth,
261 start_url_parsed, blacklist))
264 /* Make sure that the old pre-redirect form gets
266 string_set_add (blacklist, url);
275 && depth >= opt.reclevel && opt.reclevel != INFINITE_RECURSION)
277 if (opt.page_requisites
278 && (depth == opt.reclevel || depth == opt.reclevel + 1))
280 /* When -p is specified, we are allowed to exceed the
281 maximum depth, but only for the "inline" links,
282 i.e. those that are needed to display the page.
283 Originally this could exceed the depth at most by
284 one, but we allow one more level so that the leaf
285 pages that contain frames can be loaded
287 dash_p_leaf_HTML = TRUE;
291 /* Either -p wasn't specified or it was and we've
292 already spent the two extra (pseudo-)levels that it
293 affords us, so we need to bail out. */
294 DEBUGP (("Not descending further; at depth %d, max. %d.\n",
295 depth, opt.reclevel));
300 /* If the downloaded document was HTML, parse it and enqueue the
301 links it contains. */
305 int meta_disallow_follow = 0;
306 struct urlpos *children
307 = get_urls_html (file, url, &meta_disallow_follow);
309 if (opt.use_robots && meta_disallow_follow)
311 free_urlpos (children);
317 struct urlpos *child = children;
318 struct url *url_parsed = url_parsed = url_parse (url, NULL);
319 assert (url_parsed != NULL);
321 for (; child; child = child->next)
323 if (child->ignore_when_downloading)
325 if (dash_p_leaf_HTML && !child->link_inline_p)
327 if (download_child_p (child, url_parsed, depth, start_url_parsed,
330 url_enqueue (queue, xstrdup (child->url->url),
331 xstrdup (url), depth + 1);
332 /* We blacklist the URL we have enqueued, because we
333 don't want to enqueue (and hence download) the
335 string_set_add (blacklist, child->url->url);
339 url_free (url_parsed);
340 free_urlpos (children);
344 if (opt.delete_after || (file && !acceptable (file)))
346 /* Either --delete-after was specified, or we loaded this
347 otherwise rejected (e.g. by -R) HTML file just so we
348 could harvest its hyperlinks -- in either case, delete
350 DEBUGP (("Removing file due to %s in recursive_retrieve():\n",
351 opt.delete_after ? "--delete-after" :
352 "recursive rejection criteria"));
353 logprintf (LOG_VERBOSE,
355 ? _("Removing %s.\n")
356 : _("Removing %s since it should be rejected.\n")),
359 logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno));
360 register_delete_file (file);
364 FREE_MAYBE (referer);
368 /* If anything is left of the queue due to a premature exit, free it
373 while (url_dequeue (queue, (const char **)&d1, (const char **)&d2, &d3))
379 url_queue_delete (queue);
381 if (start_url_parsed)
382 url_free (start_url_parsed);
383 string_set_free (blacklist);
385 if (downloaded_exceeds_quota ())
387 else if (status == FWRITEERR)
393 /* Based on the context provided by retrieve_tree, decide whether a
394 URL is to be descended to. This is only ever called from
395 retrieve_tree, but is in a separate function for clarity.
397 The most expensive checks (such as those for robots) are memoized
398 by storing these URLs to BLACKLIST. This may or may not help. It
399 will help if those URLs are encountered many times. */
402 download_child_p (const struct urlpos *upos, struct url *parent, int depth,
403 struct url *start_url_parsed, struct hash_table *blacklist)
405 struct url *u = upos->url;
406 const char *url = u->url;
408 DEBUGP (("Deciding whether to enqueue \"%s\".\n", url));
410 if (string_set_contains (blacklist, url))
412 DEBUGP (("Already on the black list.\n"));
416 /* Several things to check for:
417 1. if scheme is not http, and we don't load it
418 2. check for relative links (if relative_only is set)
420 4. check for no-parent
421 5. check for excludes && includes
423 7. check for same host (if spanhost is unset), with possible
424 gethostbyname baggage
425 8. check for robots.txt
427 Addendum: If the URL is FTP, and it is to be loaded, only the
428 domain and suffix settings are "stronger".
430 Note that .html files will get loaded regardless of suffix rules
431 (but that is remedied later with unlink) unless the depth equals
434 More time- and memory- consuming tests should be put later on
437 /* 1. Schemes other than HTTP are normally not recursed into. */
438 if (u->scheme != SCHEME_HTTP
439 && !(u->scheme == SCHEME_FTP && opt.follow_ftp))
441 DEBUGP (("Not following non-HTTP schemes.\n"));
445 /* 2. If it is an absolute link and they are not followed, throw it
447 if (u->scheme == SCHEME_HTTP)
448 if (opt.relative_only && !upos->link_relative_p)
450 DEBUGP (("It doesn't really look like a relative link.\n"));
454 /* 3. If its domain is not to be accepted/looked-up, chuck it
456 if (!accept_domain (u))
458 DEBUGP (("The domain was not accepted.\n"));
462 /* 4. Check for parent directory.
464 If we descended to a different host or changed the scheme, ignore
465 opt.no_parent. Also ignore it for documents needed to display
466 the parent page when in -p mode. */
468 && u->scheme == start_url_parsed->scheme
469 && 0 == strcasecmp (u->host, start_url_parsed->host)
470 && u->port == start_url_parsed->port
471 && !(opt.page_requisites && upos->link_inline_p))
473 if (!frontcmp (start_url_parsed->dir, u->dir))
475 DEBUGP (("Going to \"%s\" would escape \"%s\" with no_parent on.\n",
476 u->dir, start_url_parsed->dir));
481 /* 5. If the file does not match the acceptance list, or is on the
482 rejection list, chuck it out. The same goes for the directory
483 exclusion and inclusion lists. */
484 if (opt.includes || opt.excludes)
486 if (!accdir (u->dir, ALLABS))
488 DEBUGP (("%s (%s) is excluded/not-included.\n", url, u->dir));
496 /* Check for acceptance/rejection rules. We ignore these rules
497 for HTML documents because they might lead to other files which
498 need to be downloaded. Of course, we don't know which
499 documents are HTML before downloading them, so we guess.
501 A file is subject to acceptance/rejection rules if:
503 * u->file is not "" (i.e. it is not a directory)
505 + there is no file suffix,
506 + or there is a suffix, but is not "html" or "htm",
508 - recursion is not infinite,
509 - and we are at its very end. */
511 if (u->file[0] != '\0'
512 && ((suf = suffix (url)) == NULL
513 || (0 != strcmp (suf, "html") && 0 != strcmp (suf, "htm"))
514 || (opt.reclevel != INFINITE_RECURSION && depth >= opt.reclevel)))
516 if (!acceptable (u->file))
518 DEBUGP (("%s (%s) does not match acc/rej rules.\n",
526 if (u->scheme == parent->scheme)
527 if (!opt.spanhost && 0 != strcasecmp (parent->host, u->host))
529 DEBUGP (("This is not the same hostname as the parent's (%s and %s).\n",
530 u->host, parent->host));
535 if (opt.use_robots && u->scheme == SCHEME_HTTP)
537 struct robot_specs *specs = res_get_specs (u->host, u->port);
541 if (res_retrieve_file (url, &rfile))
543 specs = res_parse_from_file (rfile);
548 /* If we cannot get real specs, at least produce
549 dummy ones so that we can register them and stop
550 trying to retrieve them. */
551 specs = res_parse ("", 0);
553 res_register_specs (u->host, u->port, specs);
556 /* Now that we have (or don't have) robots.txt specs, we can
557 check what they say. */
558 if (!res_match_path (specs, u->path))
560 DEBUGP (("Not following %s because robots.txt forbids it.\n", url));
561 string_set_add (blacklist, url);
566 /* The URL has passed all the tests. It can be placed in the
568 DEBUGP (("Decided to load it.\n"));
573 DEBUGP (("Decided NOT to load it.\n"));
578 /* This function determines whether we will consider downloading the
579 children of a URL whose download resulted in a redirection,
580 possibly to another host, etc. It is needed very rarely, and thus
581 it is merely a simple-minded wrapper around download_child_p. */
584 descend_redirect_p (const char *redirected, const char *original, int depth,
585 struct url *start_url_parsed, struct hash_table *blacklist)
587 struct url *orig_parsed, *new_parsed;
591 orig_parsed = url_parse (original, NULL);
592 assert (orig_parsed != NULL);
594 new_parsed = url_parse (redirected, NULL);
595 assert (new_parsed != NULL);
597 upos = xmalloc (sizeof (struct urlpos));
598 memset (upos, 0, sizeof (*upos));
599 upos->url = new_parsed;
601 success = download_child_p (upos, orig_parsed, depth,
602 start_url_parsed, blacklist);
604 url_free (orig_parsed);
605 url_free (new_parsed);
609 DEBUGP (("Redirection \"%s\" failed the test.\n", redirected));
615 #define ENSURE_TABLES_EXIST do { \
616 if (!dl_file_url_map) \
617 dl_file_url_map = make_string_hash_table (0); \
618 if (!dl_url_file_map) \
619 dl_url_file_map = make_string_hash_table (0); \
622 /* Return 1 if S1 and S2 are the same, except for "/index.html". The
623 three cases in which it returns one are (substitute any substring
626 m("foo/index.html", "foo/") ==> 1
627 m("foo/", "foo/index.html") ==> 1
628 m("foo", "foo/index.html") ==> 1
629 m("foo", "foo/" ==> 1
630 m("foo", "foo") ==> 1 */
633 match_except_index (const char *s1, const char *s2)
638 /* Skip common substring. */
639 for (i = 0; *s1 && *s2 && *s1 == *s2; s1++, s2++, i++)
642 /* Strings differ at the very beginning -- bail out. We need to
643 check this explicitly to avoid `lng - 1' reading outside the
648 /* Both strings hit EOF -- strings are equal. */
651 /* Strings are randomly different, e.g. "/foo/bar" and "/foo/qux". */
654 /* S1 is the longer one. */
657 /* S2 is the longer one. */
661 /* foo/index.html */ /* or */ /* foo/index.html */
665 /* The right-hand case. */
668 if (*lng == '/' && *(lng + 1) == '\0')
673 return 0 == strcmp (lng, "/index.html");
677 dissociate_urls_from_file_mapper (void *key, void *value, void *arg)
679 char *mapping_url = (char *)key;
680 char *mapping_file = (char *)value;
681 char *file = (char *)arg;
683 if (0 == strcmp (mapping_file, file))
685 hash_table_remove (dl_url_file_map, mapping_url);
687 xfree (mapping_file);
690 /* Continue mapping. */
694 /* Remove all associations from various URLs to FILE from dl_url_file_map. */
697 dissociate_urls_from_file (const char *file)
699 hash_table_map (dl_url_file_map, dissociate_urls_from_file_mapper,
703 /* Register that URL has been successfully downloaded to FILE. This
704 is used by the link conversion code to convert references to URLs
705 to references to local files. It is also being used to check if a
706 URL has already been downloaded. */
709 register_download (const char *url, const char *file)
711 char *old_file, *old_url;
715 /* With some forms of retrieval, it is possible, although not likely
716 or particularly desirable. If both are downloaded, the second
717 download will override the first one. When that happens,
718 dissociate the old file name from the URL. */
720 if (hash_table_get_pair (dl_file_url_map, file, &old_file, &old_url))
722 if (0 == strcmp (url, old_url))
723 /* We have somehow managed to download the same URL twice.
727 if (match_except_index (url, old_url)
728 && !hash_table_contains (dl_url_file_map, url))
729 /* The two URLs differ only in the "index.html" ending. For
730 example, one is "http://www.server.com/", and the other is
731 "http://www.server.com/index.html". Don't remove the old
732 one, just add the new one as a non-canonical entry. */
735 hash_table_remove (dl_file_url_map, file);
739 /* Remove all the URLs that point to this file. Yes, there can
740 be more than one such URL, because we store redirections as
741 multiple entries in dl_url_file_map. For example, if URL1
742 redirects to URL2 which gets downloaded to FILE, we map both
743 URL1 and URL2 to FILE in dl_url_file_map. (dl_file_url_map
744 only points to URL2.) When another URL gets loaded to FILE,
745 we want both URL1 and URL2 dissociated from it.
747 This is a relatively expensive operation because it performs
748 a linear search of the whole hash table, but it should be
749 called very rarely, only when two URLs resolve to the same
750 file name, *and* the "<file>.1" extensions are turned off.
751 In other words, almost never. */
752 dissociate_urls_from_file (file);
755 hash_table_put (dl_file_url_map, xstrdup (file), xstrdup (url));
758 /* A URL->FILE mapping is not possible without a FILE->URL mapping.
759 If the latter were present, it should have been removed by the
760 above `if'. So we could write:
762 assert (!hash_table_contains (dl_url_file_map, url));
764 The above is correct when running in recursive mode where the
765 same URL always resolves to the same file. But if you do
770 then the first URL will resolve to "FILE", and the other to
771 "FILE.1". In that case, FILE.1 will not be found in
772 dl_file_url_map, but URL will still point to FILE in
774 if (hash_table_get_pair (dl_url_file_map, url, &old_url, &old_file))
776 hash_table_remove (dl_url_file_map, url);
781 hash_table_put (dl_url_file_map, xstrdup (url), xstrdup (file));
784 /* Register that FROM has been redirected to TO. This assumes that TO
785 is successfully downloaded and already registered using
786 register_download() above. */
789 register_redirection (const char *from, const char *to)
795 file = hash_table_get (dl_url_file_map, to);
796 assert (file != NULL);
797 if (!hash_table_contains (dl_url_file_map, from))
798 hash_table_put (dl_url_file_map, xstrdup (from), xstrdup (file));
801 /* Register that the file has been deleted. */
804 register_delete_file (const char *file)
806 char *old_url, *old_file;
810 if (!hash_table_get_pair (dl_file_url_map, file, &old_file, &old_url))
813 hash_table_remove (dl_file_url_map, file);
816 dissociate_urls_from_file (file);
819 /* Register that FILE is an HTML file that has been downloaded. */
822 register_html (const char *url, const char *file)
824 if (!downloaded_html_set)
825 downloaded_html_set = make_string_hash_table (0);
826 else if (hash_table_contains (downloaded_html_set, file))
829 /* The set and the list should use the same copy of FILE, but the
830 slist interface insists on strduping the string it gets. Oh
832 string_set_add (downloaded_html_set, file);
833 downloaded_html_list = slist_prepend (downloaded_html_list, file);
836 /* This function is called when the retrieval is done to convert the
837 links that have been downloaded. It has to be called at the end of
838 the retrieval, because only then does Wget know conclusively which
839 URLs have been downloaded, and which not, so it can tell which
840 direction to convert to.
842 The "direction" means that the URLs to the files that have been
843 downloaded get converted to the relative URL which will point to
844 that file. And the other URLs get converted to the remote URL on
847 All the downloaded HTMLs are kept in downloaded_html_files, and
848 downloaded URLs in urls_downloaded. All the information is
849 extracted from these two lists. */
852 convert_all_links (void)
858 struct wget_timer *timer = wtimer_new ();
860 /* Destructively reverse downloaded_html_files to get it in the right order.
861 recursive_retrieve() used slist_prepend() consistently. */
862 downloaded_html_list = slist_nreverse (downloaded_html_list);
864 for (html = downloaded_html_list; html; html = html->next)
866 struct urlpos *urls, *cur_url;
868 char *file = html->string;
870 /* Determine the URL of the HTML file. get_urls_html will need
872 url = hash_table_get (dl_file_url_map, file);
875 DEBUGP (("Apparently %s has been removed.\n", file));
879 DEBUGP (("Scanning %s (from %s)\n", file, url));
881 /* Parse the HTML file... */
882 urls = get_urls_html (file, url, NULL);
884 /* We don't respect meta_disallow_follow here because, even if
885 the file is not followed, we might still want to convert the
886 links that have been followed from other files. */
888 for (cur_url = urls; cur_url; cur_url = cur_url->next)
891 struct url *u = cur_url->url;
893 if (cur_url->link_base_p)
895 /* Base references have been resolved by our parser, so
896 we turn the base URL into an empty string. (Perhaps
897 we should remove the tag entirely?) */
898 cur_url->convert = CO_NULLIFY_BASE;
902 /* We decide the direction of conversion according to whether
903 a URL was downloaded. Downloaded URLs will be converted
904 ABS2REL, whereas non-downloaded will be converted REL2ABS. */
905 local_name = hash_table_get (dl_url_file_map, u->url);
907 /* Decide on the conversion type. */
910 /* We've downloaded this URL. Convert it to relative
911 form. We do this even if the URL already is in
912 relative form, because our directory structure may
913 not be identical to that on the server (think `-nd',
914 `--cut-dirs', etc.) */
915 cur_url->convert = CO_CONVERT_TO_RELATIVE;
916 cur_url->local_name = xstrdup (local_name);
917 DEBUGP (("will convert url %s to local %s\n", u->url, local_name));
921 /* We haven't downloaded this URL. If it's not already
922 complete (including a full host name), convert it to
923 that form, so it can be reached while browsing this
925 if (!cur_url->link_complete_p)
926 cur_url->convert = CO_CONVERT_TO_COMPLETE;
927 cur_url->local_name = NULL;
928 DEBUGP (("will convert url %s to complete\n", u->url));
932 /* Convert the links in the file. */
933 convert_links (file, urls);
940 msecs = wtimer_elapsed (timer);
941 wtimer_delete (timer);
942 logprintf (LOG_VERBOSE, _("Converted %d files in %.2f seconds.\n"),
943 file_count, (double)msecs / 1000);
946 /* Cleanup the data structures associated with recursive retrieving
947 (the variables above). */
949 recursive_cleanup (void)
953 free_keys_and_values (dl_file_url_map);
954 hash_table_destroy (dl_file_url_map);
955 dl_file_url_map = NULL;
959 free_keys_and_values (dl_url_file_map);
960 hash_table_destroy (dl_url_file_map);
961 dl_url_file_map = NULL;
963 if (downloaded_html_set)
964 string_set_free (downloaded_html_set);
965 slist_free (downloaded_html_list);
966 downloaded_html_list = NULL;