]> sjero.net Git - wget/blob - src/utils.c
[svn] Committed a bunch of different tweaks of mine.
[wget] / src / utils.c
1 /* Various functions of utilitarian nature.
2    Copyright (C) 1995, 1996, 1997, 1998, 2000 Free Software Foundation, Inc.
3
4 This file is part of Wget.
5
6 This program 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 This program 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 this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
19
20 #include <config.h>
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #ifdef HAVE_STRING_H
25 # include <string.h>
26 #else  /* not HAVE_STRING_H */
27 # include <strings.h>
28 #endif /* not HAVE_STRING_H */
29 #include <ctype.h>
30 #include <sys/types.h>
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34 #ifdef HAVE_MMAP
35 # include <sys/mman.h>
36 #endif
37 #ifdef HAVE_PWD_H
38 # include <pwd.h>
39 #endif
40 #include <limits.h>
41 #ifdef HAVE_UTIME_H
42 # include <utime.h>
43 #endif
44 #ifdef HAVE_SYS_UTIME_H
45 # include <sys/utime.h>
46 #endif
47 #include <errno.h>
48 #ifdef NeXT
49 # include <libc.h>              /* for access() */
50 #endif
51 #include <fcntl.h>
52 #include <assert.h>
53
54 #include "wget.h"
55 #include "utils.h"
56 #include "fnmatch.h"
57 #include "hash.h"
58
59 #ifndef errno
60 extern int errno;
61 #endif
62
63
64 /* Croak the fatal memory error and bail out with non-zero exit
65    status.  */
66 static void
67 memfatal (const char *s)
68 {
69   /* HACK: expose save_log_p from log.c, so we can turn it off in
70      order to prevent saving the log.  Saving the log is dangerous
71      because logprintf() and logputs() can call malloc(), so this
72      could infloop.  When logging is turned off, infloop can no longer
73      happen.  */
74   extern int save_log_p;
75
76   save_log_p = 0;
77   logprintf (LOG_ALWAYS, _("%s: %s: Not enough memory.\n"), exec_name, s);
78   exit (1);
79 }
80
81 /* xmalloc, xrealloc and xstrdup exit the program if there is not
82    enough memory.  xstrdup also implements strdup on systems that do
83    not have it.  */
84 void *
85 xmalloc (size_t size)
86 {
87   void *res;
88
89   res = malloc (size);
90   if (!res)
91     memfatal ("malloc");
92   return res;
93 }
94
95 void *
96 xrealloc (void *obj, size_t size)
97 {
98   void *res;
99
100   /* Not all Un*xes have the feature of realloc() that calling it with
101      a NULL-pointer is the same as malloc(), but it is easy to
102      simulate.  */
103   if (obj)
104     res = realloc (obj, size);
105   else
106     res = malloc (size);
107   if (!res)
108     memfatal ("realloc");
109   return res;
110 }
111
112 char *
113 xstrdup (const char *s)
114 {
115 #ifndef HAVE_STRDUP
116   int l = strlen (s);
117   char *s1 = malloc (l + 1);
118   if (!s1)
119     memfatal ("strdup");
120   memcpy (s1, s, l + 1);
121   return s1;
122 #else  /* HAVE_STRDUP */
123   char *s1 = strdup (s);
124   if (!s1)
125     memfatal ("strdup");
126   return s1;
127 #endif /* HAVE_STRDUP */
128 }
129 \f
130 /* Copy the string formed by two pointers (one on the beginning, other
131    on the char after the last char) to a new, malloc-ed location.
132    0-terminate it.  */
133 char *
134 strdupdelim (const char *beg, const char *end)
135 {
136   char *res = (char *)xmalloc (end - beg + 1);
137   memcpy (res, beg, end - beg);
138   res[end - beg] = '\0';
139   return res;
140 }
141
142 /* Parse a string containing comma-separated elements, and return a
143    vector of char pointers with the elements.  Spaces following the
144    commas are ignored.  */
145 char **
146 sepstring (const char *s)
147 {
148   char **res;
149   const char *p;
150   int i = 0;
151
152   if (!s || !*s)
153     return NULL;
154   res = NULL;
155   p = s;
156   while (*s)
157     {
158       if (*s == ',')
159         {
160           res = (char **)xrealloc (res, (i + 2) * sizeof (char *));
161           res[i] = strdupdelim (p, s);
162           res[++i] = NULL;
163           ++s;
164           /* Skip the blanks following the ','.  */
165           while (ISSPACE (*s))
166             ++s;
167           p = s;
168         }
169       else
170         ++s;
171     }
172   res = (char **)xrealloc (res, (i + 2) * sizeof (char *));
173   res[i] = strdupdelim (p, s);
174   res[i + 1] = NULL;
175   return res;
176 }
177 \f
178 /* Return pointer to a static char[] buffer in which zero-terminated
179    string-representation of TM (in form hh:mm:ss) is printed.  It is
180    shamelessly non-reentrant, but it doesn't matter, really.
181
182    If TM is non-NULL, the time_t of the current time will be stored
183    there.  */
184 char *
185 time_str (time_t *tm)
186 {
187   static char tms[15];
188   struct tm *ptm;
189   time_t tim;
190
191   *tms = '\0';
192   tim = time (tm);
193   if (tim == -1)
194     return tms;
195   ptm = localtime (&tim);
196   sprintf (tms, "%02d:%02d:%02d", ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
197   return tms;
198 }
199
200 /* Returns an error message for ERRNUM.  #### This requires more work.
201    This function, as well as the whole error system, is very
202    ill-conceived.  */
203 const char *
204 uerrmsg (uerr_t errnum)
205 {
206   switch (errnum)
207     {
208     case URLUNKNOWN:
209       return _("Unknown/unsupported protocol");
210       break;
211     case URLBADPORT:
212       return _("Invalid port specification");
213       break;
214     case URLBADHOST:
215       return _("Invalid host name");
216       break;
217     default:
218       abort ();
219       /* $@#@#$ compiler.  */
220       return NULL;
221     }
222 }
223 \f
224 /* The Windows versions of the following two functions are defined in
225    mswindows.c.  */
226
227 /* A cuserid() immitation using getpwuid(), to avoid hassling with
228    utmp.  Besides, not all systems have cuesrid().  Under Windows, it
229    is defined in mswindows.c.
230
231    If WHERE is non-NULL, the username will be stored there.
232    Otherwise, it will be returned as a static buffer (as returned by
233    getpwuid()).  In the latter case, the buffer should be copied
234    before calling getpwuid() or pwd_cuserid() again.  */
235 #ifndef WINDOWS
236 char *
237 pwd_cuserid (char *where)
238 {
239   struct passwd *pwd;
240
241   if (!(pwd = getpwuid (getuid ())) || !pwd->pw_name)
242     return NULL;
243   if (where)
244     {
245       strcpy (where, pwd->pw_name);
246       return where;
247     }
248   else
249     return pwd->pw_name;
250 }
251
252 void
253 fork_to_background (void)
254 {
255   pid_t pid;
256   /* Whether we arrange our own version of opt.lfilename here.  */
257   int changedp = 0;
258
259   if (!opt.lfilename)
260     {
261       opt.lfilename = unique_name (DEFAULT_LOGFILE);
262       changedp = 1;
263     }
264   pid = fork ();
265   if (pid < 0)
266     {
267       /* parent, error */
268       perror ("fork");
269       exit (1);
270     }
271   else if (pid != 0)
272     {
273       /* parent, no error */
274       printf (_("Continuing in background.\n"));
275       if (changedp)
276         printf (_("Output will be written to `%s'.\n"), opt.lfilename);
277       exit (0);
278     }
279   /* child: keep running */
280 }
281 #endif /* not WINDOWS */
282 \f
283 /* Canonicalize PATH, and return a new path.  The new path differs from PATH
284    in that:
285         Multple `/'s are collapsed to a single `/'.
286         Leading `./'s and trailing `/.'s are removed.
287         Trailing `/'s are removed.
288         Non-leading `../'s and trailing `..'s are handled by removing
289         portions of the path.
290
291    E.g. "a/b/c/./../d/.." will yield "a/b".  This function originates
292    from GNU Bash.
293
294    Changes for Wget:
295         Always use '/' as stub_char.
296         Don't check for local things using canon_stat.
297         Change the original string instead of strdup-ing.
298         React correctly when beginning with `./' and `../'.  */
299 void
300 path_simplify (char *path)
301 {
302   register int i, start, ddot;
303   char stub_char;
304
305   if (!*path)
306     return;
307
308   /*stub_char = (*path == '/') ? '/' : '.';*/
309   stub_char = '/';
310
311   /* Addition: Remove all `./'-s preceding the string.  If `../'-s
312      precede, put `/' in front and remove them too.  */
313   i = 0;
314   ddot = 0;
315   while (1)
316     {
317       if (path[i] == '.' && path[i + 1] == '/')
318         i += 2;
319       else if (path[i] == '.' && path[i + 1] == '.' && path[i + 2] == '/')
320         {
321           i += 3;
322           ddot = 1;
323         }
324       else
325         break;
326     }
327   if (i)
328     strcpy (path, path + i - ddot);
329
330   /* Replace single `.' or `..' with `/'.  */
331   if ((path[0] == '.' && path[1] == '\0')
332       || (path[0] == '.' && path[1] == '.' && path[2] == '\0'))
333     {
334       path[0] = stub_char;
335       path[1] = '\0';
336       return;
337     }
338   /* Walk along PATH looking for things to compact.  */
339   i = 0;
340   while (1)
341     {
342       if (!path[i])
343         break;
344
345       while (path[i] && path[i] != '/')
346         i++;
347
348       start = i++;
349
350       /* If we didn't find any slashes, then there is nothing left to do.  */
351       if (!path[start])
352         break;
353
354       /* Handle multiple `/'s in a row.  */
355       while (path[i] == '/')
356         i++;
357
358       if ((start + 1) != i)
359         {
360           strcpy (path + start + 1, path + i);
361           i = start + 1;
362         }
363
364       /* Check for trailing `/'.  */
365       if (start && !path[i])
366         {
367         zero_last:
368           path[--i] = '\0';
369           break;
370         }
371
372       /* Check for `../', `./' or trailing `.' by itself.  */
373       if (path[i] == '.')
374         {
375           /* Handle trailing `.' by itself.  */
376           if (!path[i + 1])
377             goto zero_last;
378
379           /* Handle `./'.  */
380           if (path[i + 1] == '/')
381             {
382               strcpy (path + i, path + i + 1);
383               i = (start < 0) ? 0 : start;
384               continue;
385             }
386
387           /* Handle `../' or trailing `..' by itself.  */
388           if (path[i + 1] == '.' &&
389               (path[i + 2] == '/' || !path[i + 2]))
390             {
391               while (--start > -1 && path[start] != '/');
392               strcpy (path + start + 1, path + i + 2);
393               i = (start < 0) ? 0 : start;
394               continue;
395             }
396         }       /* path == '.' */
397     } /* while */
398
399   if (!*path)
400     {
401       *path = stub_char;
402       path[1] = '\0';
403     }
404 }
405 \f
406 /* "Touch" FILE, i.e. make its atime and mtime equal to the time
407    specified with TM.  */
408 void
409 touch (const char *file, time_t tm)
410 {
411 #ifdef HAVE_STRUCT_UTIMBUF
412   struct utimbuf times;
413   times.actime = times.modtime = tm;
414 #else
415   time_t times[2];
416   times[0] = times[1] = tm;
417 #endif
418
419   if (utime (file, &times) == -1)
420     logprintf (LOG_NOTQUIET, "utime(%s): %s\n", file, strerror (errno));
421 }
422
423 /* Checks if FILE is a symbolic link, and removes it if it is.  Does
424    nothing under MS-Windows.  */
425 int
426 remove_link (const char *file)
427 {
428   int err = 0;
429   struct stat st;
430
431   if (lstat (file, &st) == 0 && S_ISLNK (st.st_mode))
432     {
433       DEBUGP (("Unlinking %s (symlink).\n", file));
434       err = unlink (file);
435       if (err != 0)
436         logprintf (LOG_VERBOSE, _("Failed to unlink symlink `%s': %s\n"),
437                    file, strerror (errno));
438     }
439   return err;
440 }
441
442 /* Does FILENAME exist?  This is quite a lousy implementation, since
443    it supplies no error codes -- only a yes-or-no answer.  Thus it
444    will return that a file does not exist if, e.g., the directory is
445    unreadable.  I don't mind it too much currently, though.  The
446    proper way should, of course, be to have a third, error state,
447    other than true/false, but that would introduce uncalled-for
448    additional complexity to the callers.  */
449 int
450 file_exists_p (const char *filename)
451 {
452 #ifdef HAVE_ACCESS
453   return access (filename, F_OK) >= 0;
454 #else
455   struct stat buf;
456   return stat (filename, &buf) >= 0;
457 #endif
458 }
459
460 /* Returns 0 if PATH is a directory, 1 otherwise (any kind of file).
461    Returns 0 on error.  */
462 int
463 file_non_directory_p (const char *path)
464 {
465   struct stat buf;
466   /* Use lstat() rather than stat() so that symbolic links pointing to
467      directories can be identified correctly.  */
468   if (lstat (path, &buf) != 0)
469     return 0;
470   return S_ISDIR (buf.st_mode) ? 0 : 1;
471 }
472
473 /* Return a unique filename, given a prefix and count */
474 static char *
475 unique_name_1 (const char *fileprefix, int count)
476 {
477   char *filename;
478
479   if (count)
480     {
481       filename = (char *)xmalloc (strlen (fileprefix) + numdigit (count) + 2);
482       sprintf (filename, "%s.%d", fileprefix, count);
483     }
484   else
485     filename = xstrdup (fileprefix);
486
487   if (!file_exists_p (filename))
488     return filename;
489   else
490     {
491       free (filename);
492       return NULL;
493     }
494 }
495
496 /* Return a unique file name, based on PREFIX.  */
497 char *
498 unique_name (const char *prefix)
499 {
500   char *file = NULL;
501   int count = 0;
502
503   while (!file)
504     file = unique_name_1 (prefix, count++);
505   return file;
506 }
507 \f
508 /* Create DIRECTORY.  If some of the pathname components of DIRECTORY
509    are missing, create them first.  In case any mkdir() call fails,
510    return its error status.  Returns 0 on successful completion.
511
512    The behaviour of this function should be identical to the behaviour
513    of `mkdir -p' on systems where mkdir supports the `-p' option.  */
514 int
515 make_directory (const char *directory)
516 {
517   int quit = 0;
518   int i;
519   char *dir;
520
521   /* Make a copy of dir, to be able to write to it.  Otherwise, the
522      function is unsafe if called with a read-only char *argument.  */
523   STRDUP_ALLOCA (dir, directory);
524
525   /* If the first character of dir is '/', skip it (and thus enable
526      creation of absolute-pathname directories.  */
527   for (i = (*dir == '/'); 1; ++i)
528     {
529       for (; dir[i] && dir[i] != '/'; i++)
530         ;
531       if (!dir[i])
532         quit = 1;
533       dir[i] = '\0';
534       /* Check whether the directory already exists.  */
535       if (!file_exists_p (dir))
536         {
537           if (mkdir (dir, 0777) < 0)
538             return -1;
539         }
540       if (quit)
541         break;
542       else
543         dir[i] = '/';
544     }
545   return 0;
546 }
547 \f
548 static int in_acclist PARAMS ((const char *const *, const char *, int));
549
550 /* Determine whether a file is acceptable to be followed, according to
551    lists of patterns to accept/reject.  */
552 int
553 acceptable (const char *s)
554 {
555   int l = strlen (s);
556
557   while (l && s[l] != '/')
558     --l;
559   if (s[l] == '/')
560     s += (l + 1);
561   if (opt.accepts)
562     {
563       if (opt.rejects)
564         return (in_acclist ((const char *const *)opt.accepts, s, 1)
565                 && !in_acclist ((const char *const *)opt.rejects, s, 1));
566       else
567         return in_acclist ((const char *const *)opt.accepts, s, 1);
568     }
569   else if (opt.rejects)
570     return !in_acclist ((const char *const *)opt.rejects, s, 1);
571   return 1;
572 }
573
574 /* Compare S1 and S2 frontally; S2 must begin with S1.  E.g. if S1 is
575    `/something', frontcmp() will return 1 only if S2 begins with
576    `/something'.  Otherwise, 0 is returned.  */
577 int
578 frontcmp (const char *s1, const char *s2)
579 {
580   for (; *s1 && *s2 && (*s1 == *s2); ++s1, ++s2);
581   return !*s1;
582 }
583
584 /* Iterate through STRLIST, and return the first element that matches
585    S, through wildcards or front comparison (as appropriate).  */
586 static char *
587 proclist (char **strlist, const char *s, enum accd flags)
588 {
589   char **x;
590
591   for (x = strlist; *x; x++)
592     if (has_wildcards_p (*x))
593       {
594         if (fnmatch (*x, s, FNM_PATHNAME) == 0)
595           break;
596       }
597     else
598       {
599         char *p = *x + ((flags & ALLABS) && (**x == '/')); /* Remove '/' */
600         if (frontcmp (p, s))
601           break;
602       }
603   return *x;
604 }
605
606 /* Returns whether DIRECTORY is acceptable for download, wrt the
607    include/exclude lists.
608
609    If FLAGS is ALLABS, the leading `/' is ignored in paths; relative
610    and absolute paths may be freely intermixed.  */
611 int
612 accdir (const char *directory, enum accd flags)
613 {
614   /* Remove starting '/'.  */
615   if (flags & ALLABS && *directory == '/')
616     ++directory;
617   if (opt.includes)
618     {
619       if (!proclist (opt.includes, directory, flags))
620         return 0;
621     }
622   if (opt.excludes)
623     {
624       if (proclist (opt.excludes, directory, flags))
625         return 0;
626     }
627   return 1;
628 }
629
630 /* Match the end of STRING against PATTERN.  For instance:
631
632    match_backwards ("abc", "bc") -> 1
633    match_backwards ("abc", "ab") -> 0
634    match_backwards ("abc", "abc") -> 1 */
635 static int
636 match_backwards (const char *string, const char *pattern)
637 {
638   int i, j;
639
640   for (i = strlen (string), j = strlen (pattern); i >= 0 && j >= 0; i--, j--)
641     if (string[i] != pattern[j])
642       break;
643   /* If the pattern was exhausted, the match was succesful.  */
644   if (j == -1)
645     return 1;
646   else
647     return 0;
648 }
649
650 /* Checks whether string S matches each element of ACCEPTS.  A list
651    element are matched either with fnmatch() or match_backwards(),
652    according to whether the element contains wildcards or not.
653
654    If the BACKWARD is 0, don't do backward comparison -- just compare
655    them normally.  */
656 static int
657 in_acclist (const char *const *accepts, const char *s, int backward)
658 {
659   for (; *accepts; accepts++)
660     {
661       if (has_wildcards_p (*accepts))
662         {
663           /* fnmatch returns 0 if the pattern *does* match the
664              string.  */
665           if (fnmatch (*accepts, s, 0) == 0)
666             return 1;
667         }
668       else
669         {
670           if (backward)
671             {
672               if (match_backwards (s, *accepts))
673                 return 1;
674             }
675           else
676             {
677               if (!strcmp (s, *accepts))
678                 return 1;
679             }
680         }
681     }
682   return 0;
683 }
684
685 /* Return the malloc-ed suffix of STR.  For instance:
686    suffix ("foo.bar")       -> "bar"
687    suffix ("foo.bar.baz")   -> "baz"
688    suffix ("/foo/bar")      -> NULL
689    suffix ("/foo.bar/baz")  -> NULL  */
690 char *
691 suffix (const char *str)
692 {
693   int i;
694
695   for (i = strlen (str); i && str[i] != '/' && str[i] != '.'; i--);
696   if (str[i++] == '.')
697     return xstrdup (str + i);
698   else
699     return NULL;
700 }
701
702 /* Read a line from FP.  The function reallocs the storage as needed
703    to accomodate for any length of the line.  Reallocs are done
704    storage exponentially, doubling the storage after each overflow to
705    minimize the number of calls to realloc() and fgets().  The newline
706    character at the end of line is retained.
707
708    After end-of-file is encountered without anything being read, NULL
709    is returned.  NULL is also returned on error.  To distinguish
710    between these two cases, use the stdio function ferror().  */
711
712 char *
713 read_whole_line (FILE *fp)
714 {
715   int length = 0;
716   int bufsize = 81;
717   char *line = (char *)xmalloc (bufsize);
718
719   while (fgets (line + length, bufsize - length, fp))
720     {
721       length += strlen (line + length);
722       assert (length > 0);
723       if (line[length - 1] == '\n')
724         break;
725       /* fgets() guarantees to read the whole line, or to use up the
726          space we've given it.  We can double the buffer
727          unconditionally.  */
728       bufsize <<= 1;
729       line = xrealloc (line, bufsize);
730     }
731   if (length == 0 || ferror (fp))
732     {
733       free (line);
734       return NULL;
735     }
736   if (length + 1 < bufsize)
737     /* Relieve the memory from our exponential greediness.  We say
738        `length + 1' because the terminating \0 is not included in
739        LENGTH.  We don't need to zero-terminate the string ourselves,
740        though, because fgets() does that.  */
741     line = xrealloc (line, length + 1);
742   return line;
743 }
744 \f
745 /* Read FILE into memory.  A pointer to `struct file_memory' are
746    returned; use struct element `content' to access file contents, and
747    the element `length' to know the file length.  `content' is *not*
748    zero-terminated, and you should *not* read or write beyond the [0,
749    length) range of characters.
750
751    After you are done with the file contents, call read_file_free to
752    release the memory.
753
754    Depending on the operating system and the type of file that is
755    being read, read_file() either mmap's the file into memory, or
756    reads the file into the core using read().
757
758    If file is named "-", fileno(stdin) is used for reading instead.
759    If you want to read from a real file named "-", use "./-" instead.  */
760
761 struct file_memory *
762 read_file (const char *file)
763 {
764   int fd;
765   struct file_memory *fm;
766   long size;
767   int inhibit_close = 0;
768
769   /* Some magic in the finest tradition of Perl and its kin: if FILE
770      is "-", just use stdin.  */
771   if (HYPHENP (file))
772     {
773       fd = fileno (stdin);
774       inhibit_close = 1;
775       /* Note that we don't inhibit mmap() in this case.  If stdin is
776          redirected from a regular file, mmap() will still work.  */
777     }
778   else
779     fd = open (file, O_RDONLY);
780   if (fd < 0)
781     return NULL;
782   fm = xmalloc (sizeof (struct file_memory));
783
784 #ifdef HAVE_MMAP
785   {
786     struct stat buf;
787     if (fstat (fd, &buf) < 0)
788       goto mmap_lose;
789     fm->length = buf.st_size;
790     /* NOTE: As far as I know, the callers of this function never
791        modify the file text.  Relying on this would enable us to
792        specify PROT_READ and MAP_SHARED for a marginal gain in
793        efficiency, but at some cost to generality.  */
794     fm->content = mmap (NULL, fm->length, PROT_READ | PROT_WRITE,
795                         MAP_PRIVATE, fd, 0);
796     if (fm->content == MAP_FAILED)
797       goto mmap_lose;
798     if (!inhibit_close)
799       close (fd);
800
801     fm->mmap_p = 1;
802     return fm;
803   }
804
805  mmap_lose:
806   /* The most common reason why mmap() fails is that FD does not point
807      to a plain file.  However, it's also possible that mmap() doesn't
808      work for a particular type of file.  Therefore, whenever mmap()
809      fails, we just fall back to the regular method.  */
810 #endif /* HAVE_MMAP */
811
812   fm->length = 0;
813   size = 512;                   /* number of bytes fm->contents can
814                                    hold at any given time. */
815   fm->content = xmalloc (size);
816   while (1)
817     {
818       long nread;
819       if (fm->length > size / 2)
820         {
821           /* #### I'm not sure whether the whole exponential-growth
822              thing makes sense with kernel read.  On Linux at least,
823              read() refuses to read more than 4K from a file at a
824              single chunk anyway.  But other Unixes might optimize it
825              better, and it doesn't *hurt* anything, so I'm leaving
826              it.  */
827
828           /* Normally, we grow SIZE exponentially to make the number
829              of calls to read() and realloc() logarithmic in relation
830              to file size.  However, read() can read an amount of data
831              smaller than requested, and it would be unreasonably to
832              double SIZE every time *something* was read.  Therefore,
833              we double SIZE only when the length exceeds half of the
834              entire allocated size.  */
835           size <<= 1;
836           fm->content = xrealloc (fm->content, size);
837         }
838       nread = read (fd, fm->content + fm->length, size - fm->length);
839       if (nread > 0)
840         /* Successful read. */
841         fm->length += nread;
842       else if (nread < 0)
843         /* Error. */
844         goto lose;
845       else
846         /* EOF */
847         break;
848     }
849   if (!inhibit_close)
850     close (fd);
851   if (size > fm->length && fm->length != 0)
852     /* Due to exponential growth of fm->content, the allocated region
853        might be much larger than what is actually needed.  */
854     fm->content = xrealloc (fm->content, fm->length);
855   fm->mmap_p = 0;
856   return fm;
857
858  lose:
859   if (!inhibit_close)
860     close (fd);
861   free (fm->content);
862   free (fm);
863   return NULL;
864 }
865
866 /* Release the resources held by FM.  Specifically, this calls
867    munmap() or free() on fm->content, depending whether mmap or
868    malloc/read were used to read in the file.  It also frees the
869    memory needed to hold the FM structure itself.  */
870
871 void
872 read_file_free (struct file_memory *fm)
873 {
874 #ifdef HAVE_MMAP
875   if (fm->mmap_p)
876     {
877       munmap (fm->content, fm->length);
878     }
879   else
880 #endif
881     {
882       free (fm->content);
883     }
884   free (fm);
885 }
886 \f
887 /* Free the pointers in a NULL-terminated vector of pointers, then
888    free the pointer itself.  */
889 void
890 free_vec (char **vec)
891 {
892   if (vec)
893     {
894       char **p = vec;
895       while (*p)
896         free (*p++);
897       free (vec);
898     }
899 }
900
901 /* Append vector V2 to vector V1.  The function frees V2 and
902    reallocates V1 (thus you may not use the contents of neither
903    pointer after the call).  If V1 is NULL, V2 is returned.  */
904 char **
905 merge_vecs (char **v1, char **v2)
906 {
907   int i, j;
908
909   if (!v1)
910     return v2;
911   if (!v2)
912     return v1;
913   if (!*v2)
914     {
915       /* To avoid j == 0 */
916       free (v2);
917       return v1;
918     }
919   /* Count v1.  */
920   for (i = 0; v1[i]; i++);
921   /* Count v2.  */
922   for (j = 0; v2[j]; j++);
923   /* Reallocate v1.  */
924   v1 = (char **)xrealloc (v1, (i + j + 1) * sizeof (char **));
925   memcpy (v1 + i, v2, (j + 1) * sizeof (char *));
926   free (v2);
927   return v1;
928 }
929
930 /* A set of simple-minded routines to store strings in a linked list.
931    This used to also be used for searching, but now we have hash
932    tables for that.  */
933
934 /* It's a shame that these simple things like linked lists and hash
935    tables (see hash.c) need to be implemented over and over again.  It
936    would be nice to be able to use the routines from glib -- see
937    www.gtk.org for details.  However, that would make Wget depend on
938    glib, and I want to avoid dependencies to external libraries for
939    reasons of convenience and portability (I suspect Wget is more
940    portable than anything ever written for Gnome).  */
941
942 /* Append an element to the list.  If the list has a huge number of
943    elements, this can get slow because it has to find the list's
944    ending.  If you think you have to call slist_append in a loop,
945    think about calling slist_prepend() followed by slist_nreverse().  */
946
947 slist *
948 slist_append (slist *l, const char *s)
949 {
950   slist *newel = (slist *)xmalloc (sizeof (slist));
951   slist *beg = l;
952
953   newel->string = xstrdup (s);
954   newel->next = NULL;
955
956   if (!l)
957     return newel;
958   /* Find the last element.  */
959   while (l->next)
960     l = l->next;
961   l->next = newel;
962   return beg;
963 }
964
965 /* Prepend S to the list.  Unlike slist_append(), this is O(1).  */
966
967 slist *
968 slist_prepend (slist *l, const char *s)
969 {
970   slist *newel = (slist *)xmalloc (sizeof (slist));
971   newel->string = xstrdup (s);
972   newel->next = l;
973   return newel;
974 }
975
976 /* Destructively reverse L. */
977
978 slist *
979 slist_nreverse (slist *l)
980 {
981   slist *prev = NULL;
982   while (l)
983     {
984       slist *next = l->next;
985       l->next = prev;
986       prev = l;
987       l = next;
988     }
989   return prev;
990 }
991
992 /* Is there a specific entry in the list?  */
993 int
994 slist_contains (slist *l, const char *s)
995 {
996   for (; l; l = l->next)
997     if (!strcmp (l->string, s))
998       return 1;
999   return 0;
1000 }
1001
1002 /* Free the whole slist.  */
1003 void
1004 slist_free (slist *l)
1005 {
1006   while (l)
1007     {
1008       slist *n = l->next;
1009       free (l->string);
1010       free (l);
1011       l = n;
1012     }
1013 }
1014 \f
1015 /* Sometimes it's useful to create "sets" of strings, i.e. special
1016    hash tables where you want to store strings as keys and merely
1017    query for their existence.  Here is a set of utility routines that
1018    makes that transparent.  */
1019
1020 void
1021 string_set_add (struct hash_table *ht, const char *s)
1022 {
1023   /* First check whether the set element already exists.  If it does,
1024      do nothing so that we don't have to free() the old element and
1025      then strdup() a new one.  */
1026   if (hash_table_exists (ht, s))
1027     return;
1028
1029   /* We use "1" as value.  It provides us a useful and clear arbitrary
1030      value, and it consumes no memory -- the pointers to the same
1031      string "1" will be shared by all the key-value pairs in all `set'
1032      hash tables.  */
1033   hash_table_put (ht, xstrdup (s), "1");
1034 }
1035
1036 /* Synonym for hash_table_exists... */
1037
1038 int
1039 string_set_exists (struct hash_table *ht, const char *s)
1040 {
1041   return hash_table_exists (ht, s);
1042 }
1043
1044 static int
1045 string_set_free_mapper (void *key, void *value_ignored, void *arg_ignored)
1046 {
1047   free (key);
1048   return 0;
1049 }
1050
1051 void
1052 string_set_free (struct hash_table *ht)
1053 {
1054   hash_table_map (ht, string_set_free_mapper, NULL);
1055   hash_table_destroy (ht);
1056 }
1057
1058 static int
1059 free_keys_and_values_mapper (void *key, void *value, void *arg_ignored)
1060 {
1061   free (key);
1062   free (value);
1063   return 0;
1064 }
1065
1066 /* Another utility function: call free() on all keys and values of HT.  */
1067
1068 void
1069 free_keys_and_values (struct hash_table *ht)
1070 {
1071   hash_table_map (ht, free_keys_and_values_mapper, NULL);
1072 }
1073
1074 \f
1075 /* Engine for legible and legible_long_long; this function works on
1076    strings.  */
1077
1078 static char *
1079 legible_1 (const char *repr)
1080 {
1081   static char outbuf[128];
1082   int i, i1, mod;
1083   char *outptr;
1084   const char *inptr;
1085
1086   /* Reset the pointers.  */
1087   outptr = outbuf;
1088   inptr = repr;
1089   /* If the number is negative, shift the pointers.  */
1090   if (*inptr == '-')
1091     {
1092       *outptr++ = '-';
1093       ++inptr;
1094     }
1095   /* How many digits before the first separator?  */
1096   mod = strlen (inptr) % 3;
1097   /* Insert them.  */
1098   for (i = 0; i < mod; i++)
1099     *outptr++ = inptr[i];
1100   /* Now insert the rest of them, putting separator before every
1101      third digit.  */
1102   for (i1 = i, i = 0; inptr[i1]; i++, i1++)
1103     {
1104       if (i % 3 == 0 && i1 != 0)
1105         *outptr++ = ',';
1106       *outptr++ = inptr[i1];
1107     }
1108   /* Zero-terminate the string.  */
1109   *outptr = '\0';
1110   return outbuf;
1111 }
1112
1113 /* Legible -- return a static pointer to the legibly printed long.  */
1114 char *
1115 legible (long l)
1116 {
1117   char inbuf[24];
1118   /* Print the number into the buffer.  */
1119   long_to_string (inbuf, l);
1120   return legible_1 (inbuf);
1121 }
1122
1123 /* The same as legible(), but works on VERY_LONG_TYPE.  See sysdep.h.  */
1124 char *
1125 legible_very_long (VERY_LONG_TYPE l)
1126 {
1127   char inbuf[128];
1128   /* Print the number into the buffer.  */
1129   sprintf (inbuf, VERY_LONG_FORMAT, l);
1130   return legible_1 (inbuf);
1131 }
1132
1133 /* Count the digits in a (long) integer.  */
1134 int
1135 numdigit (long a)
1136 {
1137   int res = 1;
1138   while ((a /= 10) != 0)
1139     ++res;
1140   return res;
1141 }
1142
1143 /* Print NUMBER to BUFFER.  This is equivalent to sprintf(buffer,
1144    "%ld", number), only much faster.
1145
1146    BUFFER should accept 24 bytes.  This should suffice for the longest
1147    numbers on 64-bit machines, including the `-' sign and the trailing
1148    \0.  */
1149 void
1150 long_to_string (char *buffer, long number)
1151 {
1152 #if (SIZEOF_LONG != 4) && (SIZEOF_LONG != 8)
1153   /* Huh? */
1154   sprintf (buffer, "%ld", number);
1155 #else /* (SIZEOF_LONG == 4) || (SIZEOF_LONG == 8) */
1156   char *p = buffer;
1157   int force = 0;
1158
1159   if (number < 0)
1160     {
1161       *p++ = '-';
1162       number = -number;
1163     }
1164
1165 #define FROB(figure) do {                                               \
1166     if (force || number >= figure)                                      \
1167       *p++ = number / figure + '0', number %= figure, force = 1;        \
1168     } while (0)
1169 #if SIZEOF_LONG == 8
1170   FROB (1000000000000000000L);
1171   FROB (100000000000000000L);
1172   FROB (10000000000000000L);
1173   FROB (1000000000000000L);
1174   FROB (100000000000000L);
1175   FROB (10000000000000L);
1176   FROB (1000000000000L);
1177   FROB (100000000000L);
1178   FROB (10000000000L);
1179 #endif /* SIZEOF_LONG == 8 */
1180   FROB (1000000000);
1181   FROB (100000000);
1182   FROB (10000000);
1183   FROB (1000000);
1184   FROB (100000);
1185   FROB (10000);
1186   FROB (1000);
1187   FROB (100);
1188   FROB (10);
1189 #undef FROB
1190   *p++ = number + '0';
1191   *p = '\0';
1192 #endif /* (SIZEOF_LONG == 4) || (SIZEOF_LONG == 8) */
1193 }