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