]> sjero.net Git - wget/blob - src/convert.c
[svn] Use sets/hash-tables instead of "slists". Remove slist implementation from
[wget] / src / convert.c
1 /* Conversion of links to local files.
2    Copyright (C) 2005 Free Software Foundation, Inc.
3
4 This file is part of GNU Wget.
5
6 GNU Wget is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9  (at your option) any later version.
10
11 GNU Wget is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Wget; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20 In addition, as a special exception, the Free Software Foundation
21 gives permission to link the code of its release of Wget with the
22 OpenSSL project's "OpenSSL" library (or with modified versions of it
23 that use the same license as the "OpenSSL" library), and distribute
24 the linked executables.  You must obey the GNU General Public License
25 in all respects for all of the code used other than "OpenSSL".  If you
26 modify this file, you may extend this exception to your version of the
27 file, but you are not obligated to do so.  If you do not wish to do
28 so, delete this exception statement from your version.  */
29
30 #include <config.h>
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #ifdef HAVE_STRING_H
35 # include <string.h>
36 #else
37 # include <strings.h>
38 #endif /* HAVE_STRING_H */
39 #ifdef HAVE_UNISTD_H
40 # include <unistd.h>
41 #endif /* HAVE_UNISTD_H */
42 #include <errno.h>
43 #include <assert.h>
44 #include <sys/types.h>
45
46 #include "wget.h"
47 #include "convert.h"
48 #include "url.h"
49 #include "recur.h"
50 #include "utils.h"
51 #include "hash.h"
52
53 static struct hash_table *dl_file_url_map;
54 struct hash_table *dl_url_file_map;
55
56 /* Set of HTML files downloaded in this Wget run, used for link
57    conversion after Wget is done.  */
58 struct hash_table *downloaded_html_set;
59
60 static void convert_links PARAMS ((const char *, struct urlpos *));
61
62 /* This function is called when the retrieval is done to convert the
63    links that have been downloaded.  It has to be called at the end of
64    the retrieval, because only then does Wget know conclusively which
65    URLs have been downloaded, and which not, so it can tell which
66    direction to convert to.
67
68    The "direction" means that the URLs to the files that have been
69    downloaded get converted to the relative URL which will point to
70    that file.  And the other URLs get converted to the remote URL on
71    the server.
72
73    All the downloaded HTMLs are kept in downloaded_html_files, and
74    downloaded URLs in urls_downloaded.  All the information is
75    extracted from these two lists.  */
76
77 void
78 convert_all_links (void)
79 {
80   int i;
81   double secs;
82   int file_count = 0;
83
84   struct wget_timer *timer = wtimer_new ();
85
86   int cnt;
87   char **file_array;
88
89   cnt = 0;
90   if (downloaded_html_set)
91     cnt = hash_table_count (downloaded_html_set);
92   if (cnt == 0)
93     return;
94   file_array = alloca_array (char *, cnt);
95   string_set_to_array (downloaded_html_set, file_array);
96
97   for (i = 0; i < cnt; i++)
98     {
99       struct urlpos *urls, *cur_url;
100       char *url;
101       char *file = file_array[i];
102
103       /* Determine the URL of the HTML file.  get_urls_html will need
104          it.  */
105       url = hash_table_get (dl_file_url_map, file);
106       if (!url)
107         {
108           DEBUGP (("Apparently %s has been removed.\n", file));
109           continue;
110         }
111
112       DEBUGP (("Scanning %s (from %s)\n", file, url));
113
114       /* Parse the HTML file...  */
115       urls = get_urls_html (file, url, NULL);
116
117       /* We don't respect meta_disallow_follow here because, even if
118          the file is not followed, we might still want to convert the
119          links that have been followed from other files.  */
120
121       for (cur_url = urls; cur_url; cur_url = cur_url->next)
122         {
123           char *local_name;
124           struct url *u = cur_url->url;
125
126           if (cur_url->link_base_p)
127             {
128               /* Base references have been resolved by our parser, so
129                  we turn the base URL into an empty string.  (Perhaps
130                  we should remove the tag entirely?)  */
131               cur_url->convert = CO_NULLIFY_BASE;
132               continue;
133             }
134
135           /* We decide the direction of conversion according to whether
136              a URL was downloaded.  Downloaded URLs will be converted
137              ABS2REL, whereas non-downloaded will be converted REL2ABS.  */
138           local_name = hash_table_get (dl_url_file_map, u->url);
139
140           /* Decide on the conversion type.  */
141           if (local_name)
142             {
143               /* We've downloaded this URL.  Convert it to relative
144                  form.  We do this even if the URL already is in
145                  relative form, because our directory structure may
146                  not be identical to that on the server (think `-nd',
147                  `--cut-dirs', etc.)  */
148               cur_url->convert = CO_CONVERT_TO_RELATIVE;
149               cur_url->local_name = xstrdup (local_name);
150               DEBUGP (("will convert url %s to local %s\n", u->url, local_name));
151             }
152           else
153             {
154               /* We haven't downloaded this URL.  If it's not already
155                  complete (including a full host name), convert it to
156                  that form, so it can be reached while browsing this
157                  HTML locally.  */
158               if (!cur_url->link_complete_p)
159                 cur_url->convert = CO_CONVERT_TO_COMPLETE;
160               cur_url->local_name = NULL;
161               DEBUGP (("will convert url %s to complete\n", u->url));
162             }
163         }
164
165       /* Convert the links in the file.  */
166       convert_links (file, urls);
167       ++file_count;
168
169       /* Free the data.  */
170       free_urlpos (urls);
171     }
172
173   wtimer_update (timer);
174   secs = wtimer_read (timer) / 1000;
175   wtimer_delete (timer);
176   logprintf (LOG_VERBOSE, _("Converted %d files in %.*f seconds.\n"),
177              file_count, secs < 10 ? 3 : 1, secs);
178 }
179
180 static void write_backup_file PARAMS ((const char *, downloaded_file_t));
181 static const char *replace_attr PARAMS ((const char *, int, FILE *,
182                                          const char *));
183 static const char *replace_attr_refresh_hack PARAMS ((const char *, int, FILE *,
184                                                       const char *, int));
185 static char *local_quote_string PARAMS ((const char *));
186 static char *construct_relative PARAMS ((const char *, const char *));
187
188 /* Change the links in one HTML file.  LINKS is a list of links in the
189    document, along with their positions and the desired direction of
190    the conversion.  */
191 static void
192 convert_links (const char *file, struct urlpos *links)
193 {
194   struct file_memory *fm;
195   FILE *fp;
196   const char *p;
197   downloaded_file_t downloaded_file_return;
198
199   struct urlpos *link;
200   int to_url_count = 0, to_file_count = 0;
201
202   logprintf (LOG_VERBOSE, _("Converting %s... "), file);
203
204   {
205     /* First we do a "dry run": go through the list L and see whether
206        any URL needs to be converted in the first place.  If not, just
207        leave the file alone.  */
208     int dry_count = 0;
209     struct urlpos *dry;
210     for (dry = links; dry; dry = dry->next)
211       if (dry->convert != CO_NOCONVERT)
212         ++dry_count;
213     if (!dry_count)
214       {
215         logputs (LOG_VERBOSE, _("nothing to do.\n"));
216         return;
217       }
218   }
219
220   fm = read_file (file);
221   if (!fm)
222     {
223       logprintf (LOG_NOTQUIET, _("Cannot convert links in %s: %s\n"),
224                  file, strerror (errno));
225       return;
226     }
227
228   downloaded_file_return = downloaded_file (CHECK_FOR_FILE, file);
229   if (opt.backup_converted && downloaded_file_return)
230     write_backup_file (file, downloaded_file_return);
231
232   /* Before opening the file for writing, unlink the file.  This is
233      important if the data in FM is mmaped.  In such case, nulling the
234      file, which is what fopen() below does, would make us read all
235      zeroes from the mmaped region.  */
236   if (unlink (file) < 0 && errno != ENOENT)
237     {
238       logprintf (LOG_NOTQUIET, _("Unable to delete `%s': %s\n"),
239                  file, strerror (errno));
240       read_file_free (fm);
241       return;
242     }
243   /* Now open the file for writing.  */
244   fp = fopen (file, "wb");
245   if (!fp)
246     {
247       logprintf (LOG_NOTQUIET, _("Cannot convert links in %s: %s\n"),
248                  file, strerror (errno));
249       read_file_free (fm);
250       return;
251     }
252
253   /* Here we loop through all the URLs in file, replacing those of
254      them that are downloaded with relative references.  */
255   p = fm->content;
256   for (link = links; link; link = link->next)
257     {
258       char *url_start = fm->content + link->pos;
259
260       if (link->pos >= fm->length)
261         {
262           DEBUGP (("Something strange is going on.  Please investigate."));
263           break;
264         }
265       /* If the URL is not to be converted, skip it.  */
266       if (link->convert == CO_NOCONVERT)
267         {
268           DEBUGP (("Skipping %s at position %d.\n", link->url->url, link->pos));
269           continue;
270         }
271
272       /* Echo the file contents, up to the offending URL's opening
273          quote, to the outfile.  */
274       fwrite (p, 1, url_start - p, fp);
275       p = url_start;
276
277       switch (link->convert)
278         {
279         case CO_CONVERT_TO_RELATIVE:
280           /* Convert absolute URL to relative. */
281           {
282             char *newname = construct_relative (file, link->local_name);
283             char *quoted_newname = local_quote_string (newname);
284
285             if (!link->link_refresh_p)
286               p = replace_attr (p, link->size, fp, quoted_newname);
287             else
288               p = replace_attr_refresh_hack (p, link->size, fp, quoted_newname,
289                                              link->refresh_timeout);
290
291             DEBUGP (("TO_RELATIVE: %s to %s at position %d in %s.\n",
292                      link->url->url, newname, link->pos, file));
293             xfree (newname);
294             xfree (quoted_newname);
295             ++to_file_count;
296             break;
297           }
298         case CO_CONVERT_TO_COMPLETE:
299           /* Convert the link to absolute URL. */
300           {
301             char *newlink = link->url->url;
302             char *quoted_newlink = html_quote_string (newlink);
303
304             if (!link->link_refresh_p)
305               p = replace_attr (p, link->size, fp, quoted_newlink);
306             else
307               p = replace_attr_refresh_hack (p, link->size, fp, quoted_newlink,
308                                              link->refresh_timeout);
309
310             DEBUGP (("TO_COMPLETE: <something> to %s at position %d in %s.\n",
311                      newlink, link->pos, file));
312             xfree (quoted_newlink);
313             ++to_url_count;
314             break;
315           }
316         case CO_NULLIFY_BASE:
317           /* Change the base href to "". */
318           p = replace_attr (p, link->size, fp, "");
319           break;
320         case CO_NOCONVERT:
321           abort ();
322           break;
323         }
324     }
325
326   /* Output the rest of the file. */
327   if (p - fm->content < fm->length)
328     fwrite (p, 1, fm->length - (p - fm->content), fp);
329   fclose (fp);
330   read_file_free (fm);
331
332   logprintf (LOG_VERBOSE, "%d-%d\n", to_file_count, to_url_count);
333 }
334
335 /* Construct and return a link that points from BASEFILE to LINKFILE.
336    Both files should be local file names, BASEFILE of the referrering
337    file, and LINKFILE of the referred file.
338
339    Examples:
340
341    cr("foo", "bar")         -> "bar"
342    cr("A/foo", "A/bar")     -> "bar"
343    cr("A/foo", "A/B/bar")   -> "B/bar"
344    cr("A/X/foo", "A/Y/bar") -> "../Y/bar"
345    cr("X/", "Y/bar")        -> "../Y/bar" (trailing slash does matter in BASE)
346
347    Both files should be absolute or relative, otherwise strange
348    results might ensue.  The function makes no special efforts to
349    handle "." and ".." in links, so make sure they're not there
350    (e.g. using path_simplify).  */
351
352 static char *
353 construct_relative (const char *basefile, const char *linkfile)
354 {
355   char *link;
356   int basedirs;
357   const char *b, *l;
358   int i, start;
359
360   /* First, skip the initial directory components common to both
361      files.  */
362   start = 0;
363   for (b = basefile, l = linkfile; *b == *l && *b != '\0'; ++b, ++l)
364     {
365       if (*b == '/')
366         start = (b - basefile) + 1;
367     }
368   basefile += start;
369   linkfile += start;
370
371   /* With common directories out of the way, the situation we have is
372      as follows:
373          b - b1/b2/[...]/bfile
374          l - l1/l2/[...]/lfile
375
376      The link we're constructing needs to be:
377        lnk - ../../l1/l2/[...]/lfile
378
379      Where the number of ".."'s equals the number of bN directory
380      components in B.  */
381
382   /* Count the directory components in B. */
383   basedirs = 0;
384   for (b = basefile; *b; b++)
385     {
386       if (*b == '/')
387         ++basedirs;
388     }
389
390   /* Construct LINK as explained above. */
391   link = (char *)xmalloc (3 * basedirs + strlen (linkfile) + 1);
392   for (i = 0; i < basedirs; i++)
393     memcpy (link + 3 * i, "../", 3);
394   strcpy (link + 3 * i, linkfile);
395   return link;
396 }
397
398 static void
399 write_backup_file (const char *file, downloaded_file_t downloaded_file_return)
400 {
401   /* Rather than just writing over the original .html file with the
402      converted version, save the former to *.orig.  Note we only do
403      this for files we've _successfully_ downloaded, so we don't
404      clobber .orig files sitting around from previous invocations. */
405
406   /* Construct the backup filename as the original name plus ".orig". */
407   size_t         filename_len = strlen (file);
408   char*          filename_plus_orig_suffix;
409   static struct hash_table *converted_files;
410
411   if (downloaded_file_return == FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED)
412     {
413       /* Just write "orig" over "html".  We need to do it this way
414          because when we're checking to see if we've downloaded the
415          file before (to see if we can skip downloading it), we don't
416          know if it's a text/html file.  Therefore we don't know yet
417          at that stage that -E is going to cause us to tack on
418          ".html", so we need to compare vs. the original URL plus
419          ".orig", not the original URL plus ".html.orig". */
420       filename_plus_orig_suffix = alloca (filename_len + 1);
421       strcpy (filename_plus_orig_suffix, file);
422       strcpy ((filename_plus_orig_suffix + filename_len) - 4, "orig");
423     }
424   else /* downloaded_file_return == FILE_DOWNLOADED_NORMALLY */
425     {
426       /* Append ".orig" to the name. */
427       filename_plus_orig_suffix = alloca (filename_len + sizeof (".orig"));
428       strcpy (filename_plus_orig_suffix, file);
429       strcpy (filename_plus_orig_suffix + filename_len, ".orig");
430     }
431
432   if (!converted_files)
433     converted_files = make_string_hash_table (0);
434
435   /* We can get called twice on the same URL thanks to the
436      convert_all_links() call in main().  If we write the .orig file
437      each time in such a case, it'll end up containing the first-pass
438      conversion, not the original file.  So, see if we've already been
439      called on this file. */
440   if (!string_set_contains (converted_files, file))
441     {
442       /* Rename <file> to <file>.orig before former gets written over. */
443       if (rename (file, filename_plus_orig_suffix) != 0)
444         logprintf (LOG_NOTQUIET, _("Cannot back up %s as %s: %s\n"),
445                    file, filename_plus_orig_suffix, strerror (errno));
446
447       /* Remember that we've already written a .orig backup for this file.
448          Note that we never free this memory since we need it till the
449          convert_all_links() call, which is one of the last things the
450          program does before terminating.  BTW, I'm not sure if it would be
451          safe to just set 'converted_file_ptr->string' to 'file' below,
452          rather than making a copy of the string...  Another note is that I
453          thought I could just add a field to the urlpos structure saying
454          that we'd written a .orig file for this URL, but that didn't work,
455          so I had to make this separate list.
456          -- Dan Harkless <wget@harkless.org>
457
458          This [adding a field to the urlpos structure] didn't work
459          because convert_file() is called from convert_all_links at
460          the end of the retrieval with a freshly built new urlpos
461          list.
462          -- Hrvoje Niksic <hniksic@xemacs.org>
463       */
464       string_set_add (converted_files, file);
465     }
466 }
467
468 static int find_fragment PARAMS ((const char *, int, const char **,
469                                   const char **));
470
471 /* Replace an attribute's original text with NEW_TEXT. */
472
473 static const char *
474 replace_attr (const char *p, int size, FILE *fp, const char *new_text)
475 {
476   int quote_flag = 0;
477   char quote_char = '\"';       /* use "..." for quoting, unless the
478                                    original value is quoted, in which
479                                    case reuse its quoting char. */
480   const char *frag_beg, *frag_end;
481
482   /* Structure of our string is:
483        "...old-contents..."
484        <---    size    --->  (with quotes)
485      OR:
486        ...old-contents...
487        <---    size   -->    (no quotes)   */
488
489   if (*p == '\"' || *p == '\'')
490     {
491       quote_char = *p;
492       quote_flag = 1;
493       ++p;
494       size -= 2;                /* disregard opening and closing quote */
495     }
496   putc (quote_char, fp);
497   fputs (new_text, fp);
498
499   /* Look for fragment identifier, if any. */
500   if (find_fragment (p, size, &frag_beg, &frag_end))
501     fwrite (frag_beg, 1, frag_end - frag_beg, fp);
502   p += size;
503   if (quote_flag)
504     ++p;
505   putc (quote_char, fp);
506
507   return p;
508 }
509
510 /* The same as REPLACE_ATTR, but used when replacing
511    <meta http-equiv=refresh content="new_text"> because we need to
512    append "timeout_value; URL=" before the next_text.  */
513
514 static const char *
515 replace_attr_refresh_hack (const char *p, int size, FILE *fp,
516                            const char *new_text, int timeout)
517 {
518   /* "0; URL=..." */
519   char *new_with_timeout = (char *)alloca (numdigit (timeout)
520                                            + 6 /* "; URL=" */
521                                            + strlen (new_text)
522                                            + 1);
523   sprintf (new_with_timeout, "%d; URL=%s", timeout, new_text);
524
525   return replace_attr (p, size, fp, new_with_timeout);
526 }
527
528 /* Find the first occurrence of '#' in [BEG, BEG+SIZE) that is not
529    preceded by '&'.  If the character is not found, return zero.  If
530    the character is found, return 1 and set BP and EP to point to the
531    beginning and end of the region.
532
533    This is used for finding the fragment indentifiers in URLs.  */
534
535 static int
536 find_fragment (const char *beg, int size, const char **bp, const char **ep)
537 {
538   const char *end = beg + size;
539   int saw_amp = 0;
540   for (; beg < end; beg++)
541     {
542       switch (*beg)
543         {
544         case '&':
545           saw_amp = 1;
546           break;
547         case '#':
548           if (!saw_amp)
549             {
550               *bp = beg;
551               *ep = end;
552               return 1;
553             }
554           /* fallthrough */
555         default:
556           saw_amp = 0;
557         }
558     }
559   return 0;
560 }
561
562 /* Quote FILE for use as local reference to an HTML file.
563
564    We quote ? as %3F to avoid passing part of the file name as the
565    parameter when browsing the converted file through HTTP.  However,
566    it is safe to do this only when `--html-extension' is turned on.
567    This is because converting "index.html?foo=bar" to
568    "index.html%3Ffoo=bar" would break local browsing, as the latter
569    isn't even recognized as an HTML file!  However, converting
570    "index.html?foo=bar.html" to "index.html%3Ffoo=bar.html" should be
571    safe for both local and HTTP-served browsing.
572
573    We always quote "#" as "%23" and "%" as "%25" because those
574    characters have special meanings in URLs.  */
575
576 static char *
577 local_quote_string (const char *file)
578 {
579   const char *from;
580   char *newname, *to;
581
582   char *any = strpbrk (file, "?#%");
583   if (!any)
584     return html_quote_string (file);
585
586   /* Allocate space assuming the worst-case scenario, each character
587      having to be quoted.  */
588   to = newname = (char *)alloca (3 * strlen (file) + 1);
589   for (from = file; *from; from++)
590     switch (*from)
591       {
592       case '%':
593         *to++ = '%';
594         *to++ = '2';
595         *to++ = '5';
596         break;
597       case '#':
598         *to++ = '%';
599         *to++ = '2';
600         *to++ = '3';
601         break;
602       case '?':
603         if (opt.html_extension)
604           {
605             *to++ = '%';
606             *to++ = '3';
607             *to++ = 'F';
608             break;
609           }
610         /* fallthrough */
611       default:
612         *to++ = *from;
613       }
614   *to = '\0';
615
616   return html_quote_string (newname);
617 }
618 \f
619 /* Book-keeping code for dl_file_url_map, dl_url_file_map,
620    downloaded_html_list, and downloaded_html_set.  Other code calls
621    these functions to let us know that a file has been downloaded.  */
622
623 #define ENSURE_TABLES_EXIST do {                        \
624   if (!dl_file_url_map)                                 \
625     dl_file_url_map = make_string_hash_table (0);       \
626   if (!dl_url_file_map)                                 \
627     dl_url_file_map = make_string_hash_table (0);       \
628 } while (0)
629
630 /* Return 1 if S1 and S2 are the same, except for "/index.html".  The
631    three cases in which it returns one are (substitute any substring
632    for "foo"):
633
634    m("foo/index.html", "foo/")  ==> 1
635    m("foo/", "foo/index.html")  ==> 1
636    m("foo", "foo/index.html")   ==> 1
637    m("foo", "foo/"              ==> 1
638    m("foo", "foo")              ==> 1  */
639
640 static int
641 match_except_index (const char *s1, const char *s2)
642 {
643   int i;
644   const char *lng;
645
646   /* Skip common substring. */
647   for (i = 0; *s1 && *s2 && *s1 == *s2; s1++, s2++, i++)
648     ;
649   if (i == 0)
650     /* Strings differ at the very beginning -- bail out.  We need to
651        check this explicitly to avoid `lng - 1' reading outside the
652        array.  */
653     return 0;
654
655   if (!*s1 && !*s2)
656     /* Both strings hit EOF -- strings are equal. */
657     return 1;
658   else if (*s1 && *s2)
659     /* Strings are randomly different, e.g. "/foo/bar" and "/foo/qux". */
660     return 0;
661   else if (*s1)
662     /* S1 is the longer one. */
663     lng = s1;
664   else
665     /* S2 is the longer one. */
666     lng = s2;
667
668   /* foo            */            /* foo/           */
669   /* foo/index.html */  /* or */  /* foo/index.html */
670   /*    ^           */            /*     ^          */
671
672   if (*lng != '/')
673     /* The right-hand case. */
674     --lng;
675
676   if (*lng == '/' && *(lng + 1) == '\0')
677     /* foo  */
678     /* foo/ */
679     return 1;
680
681   return 0 == strcmp (lng, "/index.html");
682 }
683
684 static int
685 dissociate_urls_from_file_mapper (void *key, void *value, void *arg)
686 {
687   char *mapping_url = (char *)key;
688   char *mapping_file = (char *)value;
689   char *file = (char *)arg;
690
691   if (0 == strcmp (mapping_file, file))
692     {
693       hash_table_remove (dl_url_file_map, mapping_url);
694       xfree (mapping_url);
695       xfree (mapping_file);
696     }
697
698   /* Continue mapping. */
699   return 0;
700 }
701
702 /* Remove all associations from various URLs to FILE from dl_url_file_map. */
703
704 static void
705 dissociate_urls_from_file (const char *file)
706 {
707   hash_table_map (dl_url_file_map, dissociate_urls_from_file_mapper,
708                   (char *)file);
709 }
710
711 /* Register that URL has been successfully downloaded to FILE.  This
712    is used by the link conversion code to convert references to URLs
713    to references to local files.  It is also being used to check if a
714    URL has already been downloaded.  */
715
716 void
717 register_download (const char *url, const char *file)
718 {
719   char *old_file, *old_url;
720
721   ENSURE_TABLES_EXIST;
722
723   /* With some forms of retrieval, it is possible, although not likely
724      or particularly desirable.  If both are downloaded, the second
725      download will override the first one.  When that happens,
726      dissociate the old file name from the URL.  */
727
728   if (hash_table_get_pair (dl_file_url_map, file, &old_file, &old_url))
729     {
730       if (0 == strcmp (url, old_url))
731         /* We have somehow managed to download the same URL twice.
732            Nothing to do.  */
733         return;
734
735       if (match_except_index (url, old_url)
736           && !hash_table_contains (dl_url_file_map, url))
737         /* The two URLs differ only in the "index.html" ending.  For
738            example, one is "http://www.server.com/", and the other is
739            "http://www.server.com/index.html".  Don't remove the old
740            one, just add the new one as a non-canonical entry.  */
741         goto url_only;
742
743       hash_table_remove (dl_file_url_map, file);
744       xfree (old_file);
745       xfree (old_url);
746
747       /* Remove all the URLs that point to this file.  Yes, there can
748          be more than one such URL, because we store redirections as
749          multiple entries in dl_url_file_map.  For example, if URL1
750          redirects to URL2 which gets downloaded to FILE, we map both
751          URL1 and URL2 to FILE in dl_url_file_map.  (dl_file_url_map
752          only points to URL2.)  When another URL gets loaded to FILE,
753          we want both URL1 and URL2 dissociated from it.
754
755          This is a relatively expensive operation because it performs
756          a linear search of the whole hash table, but it should be
757          called very rarely, only when two URLs resolve to the same
758          file name, *and* the "<file>.1" extensions are turned off.
759          In other words, almost never.  */
760       dissociate_urls_from_file (file);
761     }
762
763   hash_table_put (dl_file_url_map, xstrdup (file), xstrdup (url));
764
765  url_only:
766   /* A URL->FILE mapping is not possible without a FILE->URL mapping.
767      If the latter were present, it should have been removed by the
768      above `if'.  So we could write:
769
770          assert (!hash_table_contains (dl_url_file_map, url));
771
772      The above is correct when running in recursive mode where the
773      same URL always resolves to the same file.  But if you do
774      something like:
775
776          wget URL URL
777
778      then the first URL will resolve to "FILE", and the other to
779      "FILE.1".  In that case, FILE.1 will not be found in
780      dl_file_url_map, but URL will still point to FILE in
781      dl_url_file_map.  */
782   if (hash_table_get_pair (dl_url_file_map, url, &old_url, &old_file))
783     {
784       hash_table_remove (dl_url_file_map, url);
785       xfree (old_url);
786       xfree (old_file);
787     }
788
789   hash_table_put (dl_url_file_map, xstrdup (url), xstrdup (file));
790 }
791
792 /* Register that FROM has been redirected to TO.  This assumes that TO
793    is successfully downloaded and already registered using
794    register_download() above.  */
795
796 void
797 register_redirection (const char *from, const char *to)
798 {
799   char *file;
800
801   ENSURE_TABLES_EXIST;
802
803   file = hash_table_get (dl_url_file_map, to);
804   assert (file != NULL);
805   if (!hash_table_contains (dl_url_file_map, from))
806     hash_table_put (dl_url_file_map, xstrdup (from), xstrdup (file));
807 }
808
809 /* Register that the file has been deleted. */
810
811 void
812 register_delete_file (const char *file)
813 {
814   char *old_url, *old_file;
815
816   ENSURE_TABLES_EXIST;
817
818   if (!hash_table_get_pair (dl_file_url_map, file, &old_file, &old_url))
819     return;
820
821   hash_table_remove (dl_file_url_map, file);
822   xfree (old_file);
823   xfree (old_url);
824   dissociate_urls_from_file (file);
825 }
826
827 /* Register that FILE is an HTML file that has been downloaded. */
828
829 void
830 register_html (const char *url, const char *file)
831 {
832   if (!downloaded_html_set)
833     downloaded_html_set = make_string_hash_table (0);
834   string_set_add (downloaded_html_set, file);
835 }
836
837 /* Cleanup the data structures associated with recursive retrieving
838    (the variables above).  */
839 void
840 convert_cleanup (void)
841 {
842   if (dl_file_url_map)
843     {
844       free_keys_and_values (dl_file_url_map);
845       hash_table_destroy (dl_file_url_map);
846       dl_file_url_map = NULL;
847     }
848   if (dl_url_file_map)
849     {
850       free_keys_and_values (dl_url_file_map);
851       hash_table_destroy (dl_url_file_map);
852       dl_url_file_map = NULL;
853     }
854   if (downloaded_html_set)
855     string_set_free (downloaded_html_set);
856 }
857 \f
858 /* Book-keeping code for downloaded files that enables extension
859    hacks.  */
860
861 /* This table should really be merged with dl_file_url_map and
862    downloaded_html_files.  This was originally a list, but I changed
863    it to a hash table beause it was actually taking a lot of time to
864    find things in it.  */
865
866 static struct hash_table *downloaded_files_hash;
867
868 /* We're storing "modes" of type downloaded_file_t in the hash table.
869    However, our hash tables only accept pointers for keys and values.
870    So when we need a pointer, we use the address of a
871    downloaded_file_t variable of static storage.  */
872    
873 static downloaded_file_t *
874 downloaded_mode_to_ptr (downloaded_file_t mode)
875 {
876   static downloaded_file_t
877     v1 = FILE_NOT_ALREADY_DOWNLOADED,
878     v2 = FILE_DOWNLOADED_NORMALLY,
879     v3 = FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED,
880     v4 = CHECK_FOR_FILE;
881
882   switch (mode)
883     {
884     case FILE_NOT_ALREADY_DOWNLOADED:
885       return &v1;
886     case FILE_DOWNLOADED_NORMALLY:
887       return &v2;
888     case FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED:
889       return &v3;
890     case CHECK_FOR_FILE:
891       return &v4;
892     }
893   return NULL;
894 }
895
896 /* Remembers which files have been downloaded.  In the standard case,
897    should be called with mode == FILE_DOWNLOADED_NORMALLY for each
898    file we actually download successfully (i.e. not for ones we have
899    failures on or that we skip due to -N).
900
901    When we've downloaded a file and tacked on a ".html" extension due
902    to -E, call this function with
903    FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED rather than
904    FILE_DOWNLOADED_NORMALLY.
905
906    If you just want to check if a file has been previously added
907    without adding it, call with mode == CHECK_FOR_FILE.  Please be
908    sure to call this function with local filenames, not remote
909    URLs.  */
910
911 downloaded_file_t
912 downloaded_file (downloaded_file_t mode, const char *file)
913 {
914   downloaded_file_t *ptr;
915
916   if (mode == CHECK_FOR_FILE)
917     {
918       if (!downloaded_files_hash)
919         return FILE_NOT_ALREADY_DOWNLOADED;
920       ptr = hash_table_get (downloaded_files_hash, file);
921       if (!ptr)
922         return FILE_NOT_ALREADY_DOWNLOADED;
923       return *ptr;
924     }
925
926   if (!downloaded_files_hash)
927     downloaded_files_hash = make_string_hash_table (0);
928
929   ptr = hash_table_get (downloaded_files_hash, file);
930   if (ptr)
931     return *ptr;
932
933   ptr = downloaded_mode_to_ptr (mode);
934   hash_table_put (downloaded_files_hash, xstrdup (file), &ptr);
935
936   return FILE_NOT_ALREADY_DOWNLOADED;
937 }
938
939 static int
940 df_free_mapper (void *key, void *value, void *ignored)
941 {
942   xfree (key);
943   return 0;
944 }
945
946 void
947 downloaded_files_free (void)
948 {
949   if (downloaded_files_hash)
950     {
951       hash_table_map (downloaded_files_hash, df_free_mapper, NULL);
952       hash_table_destroy (downloaded_files_hash);
953       downloaded_files_hash = NULL;
954     }
955 }