]> sjero.net Git - wget/blob - src/utils.c
* utils.c (aprintf): Now we are setting limits (1 Mb) for text buffer when we use...
[wget] / src / utils.c
1 /* Various utility functions.
2    Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
3    2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4
5 This file is part of GNU Wget.
6
7 GNU Wget is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 GNU Wget is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Wget.  If not, see <http://www.gnu.org/licenses/>.
19
20 Additional permission under GNU GPL version 3 section 7
21
22 If you modify this program, or any covered work, by linking or
23 combining it with the OpenSSL project's OpenSSL library (or a
24 modified version of that library), containing parts covered by the
25 terms of the OpenSSL or SSLeay licenses, the Free Software Foundation
26 grants you additional permission to convey the resulting work.
27 Corresponding Source for a non-source form of such a combination
28 shall include the source code for the parts of OpenSSL used as well
29 as that of the covered work.  */
30
31 #include "wget.h"
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <time.h>
37 #ifdef HAVE_SYS_TIME_H
38 # include <sys/time.h>
39 #endif
40 #ifdef HAVE_UNISTD_H
41 # include <unistd.h>
42 #endif
43 #ifdef HAVE_MMAP
44 # include <sys/mman.h>
45 #endif
46 #ifdef HAVE_PROCESS_H
47 # include <process.h>  /* getpid() */
48 #endif
49 #ifdef HAVE_UTIME_H
50 # include <utime.h>
51 #endif
52 #ifdef HAVE_SYS_UTIME_H
53 # include <sys/utime.h>
54 #endif
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <assert.h>
58 #include <stdarg.h>
59 #include <locale.h>
60
61 /* For TIOCGWINSZ and friends: */
62 #ifdef HAVE_SYS_IOCTL_H
63 # include <sys/ioctl.h>
64 #endif
65 #ifdef HAVE_TERMIOS_H
66 # include <termios.h>
67 #endif
68
69 /* Needed for Unix version of run_with_timeout. */
70 #include <signal.h>
71 #include <setjmp.h>
72
73 #ifndef HAVE_SIGSETJMP
74 /* If sigsetjmp is a macro, configure won't pick it up. */
75 # ifdef sigsetjmp
76 #  define HAVE_SIGSETJMP
77 # endif
78 #endif
79
80 #if defined HAVE_SIGSETJMP || defined HAVE_SIGBLOCK
81 # define USE_SIGNAL_TIMEOUT
82 #endif
83
84 #include "utils.h"
85 #include "hash.h"
86
87 #ifdef TESTING
88 #include "test.h"
89 #endif 
90
91 /* Utility function: like xstrdup(), but also lowercases S.  */
92
93 char *
94 xstrdup_lower (const char *s)
95 {
96   char *copy = xstrdup (s);
97   char *p = copy;
98   for (; *p; p++)
99     *p = c_tolower (*p);
100   return copy;
101 }
102
103 /* Copy the string formed by two pointers (one on the beginning, other
104    on the char after the last char) to a new, malloc-ed location.
105    0-terminate it.  */
106 char *
107 strdupdelim (const char *beg, const char *end)
108 {
109   char *res = xmalloc (end - beg + 1);
110   memcpy (res, beg, end - beg);
111   res[end - beg] = '\0';
112   return res;
113 }
114
115 /* Parse a string containing comma-separated elements, and return a
116    vector of char pointers with the elements.  Spaces following the
117    commas are ignored.  */
118 char **
119 sepstring (const char *s)
120 {
121   char **res;
122   const char *p;
123   int i = 0;
124
125   if (!s || !*s)
126     return NULL;
127   res = NULL;
128   p = s;
129   while (*s)
130     {
131       if (*s == ',')
132         {
133           res = xrealloc (res, (i + 2) * sizeof (char *));
134           res[i] = strdupdelim (p, s);
135           res[++i] = NULL;
136           ++s;
137           /* Skip the blanks following the ','.  */
138           while (c_isspace (*s))
139             ++s;
140           p = s;
141         }
142       else
143         ++s;
144     }
145   res = xrealloc (res, (i + 2) * sizeof (char *));
146   res[i] = strdupdelim (p, s);
147   res[i + 1] = NULL;
148   return res;
149 }
150 \f
151 /* Like sprintf, but prints into a string of sufficient size freshly
152    allocated with malloc, which is returned.  If unable to print due
153    to invalid format, returns NULL.  Inability to allocate needed
154    memory results in abort, as with xmalloc.  This is in spirit
155    similar to the GNU/BSD extension asprintf, but somewhat easier to
156    use.
157
158    Internally the function either calls vasprintf or loops around
159    vsnprintf until the correct size is found.  Since Wget also ships a
160    fallback implementation of vsnprintf, this should be portable.  */
161
162 /* Constant is using for limits memory allocation for text buffer.
163    Applicable in situation when: vasprintf is not available in the system 
164    and vsnprintf return -1 when long line is truncated (in old versions of
165    glibc and in other system where C99 doesn`t support) */
166
167 #define FMT_MAX_LENGTH 1048576
168
169 char *
170 aprintf (const char *fmt, ...)
171 {
172 #if defined HAVE_VASPRINTF && !defined DEBUG_MALLOC
173   /* Use vasprintf. */
174   int ret;
175   va_list args;
176   char *str;
177   va_start (args, fmt);
178   ret = vasprintf (&str, fmt, args);
179   va_end (args);
180   if (ret < 0 && errno == ENOMEM)
181     memfatal ("aprintf", UNKNOWN_ATTEMPTED_SIZE);  /* for consistency with xmalloc/xrealloc */
182   else if (ret < 0)
183     return NULL;
184   return str;
185 #else  /* not HAVE_VASPRINTF */
186
187   /* vasprintf is unavailable.  snprintf into a small buffer and
188      resize it as necessary. */
189   int size = 32;
190   char *str = xmalloc (size);
191
192   /* #### This code will infloop and eventually abort in xrealloc if
193      passed a FMT that causes snprintf to consistently return -1.  */
194
195   while (1)
196     {
197       int n;
198       va_list args;
199
200       va_start (args, fmt);
201       n = vsnprintf (str, size, fmt, args);
202       va_end (args);
203
204       /* If the printing worked, return the string. */
205       if (n > -1 && n < size)
206         return str;
207
208       /* Else try again with a larger buffer. */
209       if (n > -1)               /* C99 */
210         size = n + 1;           /* precisely what is needed */
211       else
212         {
213           if (size >= FMT_MAX_LENGTH)  /* We have a huge buffer, */
214             {                          /* maybe we have some wrong format string? */
215               free (str);              /* In this case we must free already allocated memory, */
216               return NULL;             /* and return NULL pointer... */
217             }
218                                        /* else, we continue to grow our buffer. */
219           size <<= 1;                  /* twice the old size */
220         }
221       str = xrealloc (str, size);
222     }
223 #endif /* not HAVE_VASPRINTF */
224 }
225
226 /* Concatenate the NULL-terminated list of string arguments into
227    freshly allocated space.  */
228
229 char *
230 concat_strings (const char *str0, ...)
231 {
232   va_list args;
233   int saved_lengths[5];         /* inspired by Apache's apr_pstrcat */
234   char *ret, *p;
235
236   const char *next_str;
237   int total_length = 0;
238   int argcount;
239
240   /* Calculate the length of and allocate the resulting string. */
241
242   argcount = 0;
243   va_start (args, str0);
244   for (next_str = str0; next_str != NULL; next_str = va_arg (args, char *))
245     {
246       int len = strlen (next_str);
247       if (argcount < countof (saved_lengths))
248         saved_lengths[argcount++] = len;
249       total_length += len;
250     }
251   va_end (args);
252   p = ret = xmalloc (total_length + 1);
253
254   /* Copy the strings into the allocated space. */
255
256   argcount = 0;
257   va_start (args, str0);
258   for (next_str = str0; next_str != NULL; next_str = va_arg (args, char *))
259     {
260       int len;
261       if (argcount < countof (saved_lengths))
262         len = saved_lengths[argcount++];
263       else
264         len = strlen (next_str);
265       memcpy (p, next_str, len);
266       p += len;
267     }
268   va_end (args);
269   *p = '\0';
270
271   return ret;
272 }
273 \f
274 /* Format the provided time according to the specified format.  The
275    format is a string with format elements supported by strftime.  */
276
277 static char *
278 fmttime (time_t t, const char *fmt)
279 {
280   static char output[32];
281   struct tm *tm = localtime(&t);
282   if (!tm)
283     abort ();
284   if (!strftime(output, sizeof(output), fmt, tm))
285     abort ();
286   return output;
287 }
288
289 /* Return pointer to a static char[] buffer in which zero-terminated
290    string-representation of TM (in form hh:mm:ss) is printed.
291
292    If TM is NULL, the current time will be used.  */
293
294 char *
295 time_str (time_t t)
296 {
297   return fmttime(t, "%H:%M:%S");
298 }
299
300 /* Like the above, but include the date: YYYY-MM-DD hh:mm:ss.  */
301
302 char *
303 datetime_str (time_t t)
304 {
305   return fmttime(t, "%Y-%m-%d %H:%M:%S");
306 }
307 \f
308 /* The Windows versions of the following two functions are defined in
309    mswindows.c. On MSDOS this function should never be called. */
310
311 #if !defined(WINDOWS) && !defined(MSDOS)
312 void
313 fork_to_background (void)
314 {
315   pid_t pid;
316   /* Whether we arrange our own version of opt.lfilename here.  */
317   bool logfile_changed = false;
318
319   if (!opt.lfilename)
320     {
321       /* We must create the file immediately to avoid either a race
322          condition (which arises from using unique_name and failing to
323          use fopen_excl) or lying to the user about the log file name
324          (which arises from using unique_name, printing the name, and
325          using fopen_excl later on.)  */
326       FILE *new_log_fp = unique_create (DEFAULT_LOGFILE, false, &opt.lfilename);
327       if (new_log_fp)
328         {
329           logfile_changed = true;
330           fclose (new_log_fp);
331         }
332     }
333   pid = fork ();
334   if (pid < 0)
335     {
336       /* parent, error */
337       perror ("fork");
338       exit (1);
339     }
340   else if (pid != 0)
341     {
342       /* parent, no error */
343       printf (_("Continuing in background, pid %d.\n"), (int) pid);
344       if (logfile_changed)
345         printf (_("Output will be written to `%s'.\n"), opt.lfilename);
346       exit (0);                 /* #### should we use _exit()? */
347     }
348
349   /* child: give up the privileges and keep running. */
350   setsid ();
351   freopen ("/dev/null", "r", stdin);
352   freopen ("/dev/null", "w", stdout);
353   freopen ("/dev/null", "w", stderr);
354 }
355 #endif /* !WINDOWS && !MSDOS */
356 \f
357 /* "Touch" FILE, i.e. make its mtime ("modified time") equal the time
358    specified with TM.  The atime ("access time") is set to the current
359    time.  */
360
361 void
362 touch (const char *file, time_t tm)
363 {
364 #ifdef HAVE_STRUCT_UTIMBUF
365   struct utimbuf times;
366 #else
367   struct {
368     time_t actime;
369     time_t modtime;
370   } times;
371 #endif
372   times.modtime = tm;
373   times.actime = time (NULL);
374   if (utime (file, &times) == -1)
375     logprintf (LOG_NOTQUIET, "utime(%s): %s\n", file, strerror (errno));
376 }
377
378 /* Checks if FILE is a symbolic link, and removes it if it is.  Does
379    nothing under MS-Windows.  */
380 int
381 remove_link (const char *file)
382 {
383   int err = 0;
384   struct_stat st;
385
386   if (lstat (file, &st) == 0 && S_ISLNK (st.st_mode))
387     {
388       DEBUGP (("Unlinking %s (symlink).\n", file));
389       err = unlink (file);
390       if (err != 0)
391         logprintf (LOG_VERBOSE, _("Failed to unlink symlink `%s': %s\n"),
392                    file, strerror (errno));
393     }
394   return err;
395 }
396
397 /* Does FILENAME exist?  This is quite a lousy implementation, since
398    it supplies no error codes -- only a yes-or-no answer.  Thus it
399    will return that a file does not exist if, e.g., the directory is
400    unreadable.  I don't mind it too much currently, though.  The
401    proper way should, of course, be to have a third, error state,
402    other than true/false, but that would introduce uncalled-for
403    additional complexity to the callers.  */
404 bool
405 file_exists_p (const char *filename)
406 {
407 #ifdef HAVE_ACCESS
408   return access (filename, F_OK) >= 0;
409 #else
410   struct_stat buf;
411   return stat (filename, &buf) >= 0;
412 #endif
413 }
414
415 /* Returns 0 if PATH is a directory, 1 otherwise (any kind of file).
416    Returns 0 on error.  */
417 bool
418 file_non_directory_p (const char *path)
419 {
420   struct_stat buf;
421   /* Use lstat() rather than stat() so that symbolic links pointing to
422      directories can be identified correctly.  */
423   if (lstat (path, &buf) != 0)
424     return false;
425   return S_ISDIR (buf.st_mode) ? false : true;
426 }
427
428 /* Return the size of file named by FILENAME, or -1 if it cannot be
429    opened or seeked into. */
430 wgint
431 file_size (const char *filename)
432 {
433 #if defined(HAVE_FSEEKO) && defined(HAVE_FTELLO)
434   wgint size;
435   /* We use fseek rather than stat to determine the file size because
436      that way we can also verify that the file is readable without
437      explicitly checking for permissions.  Inspired by the POST patch
438      by Arnaud Wylie.  */
439   FILE *fp = fopen (filename, "rb");
440   if (!fp)
441     return -1;
442   fseeko (fp, 0, SEEK_END);
443   size = ftello (fp);
444   fclose (fp);
445   return size;
446 #else
447   struct_stat st;
448   if (stat (filename, &st) < 0)
449     return -1;
450   return st.st_size;
451 #endif
452 }
453
454 /* stat file names named PREFIX.1, PREFIX.2, etc., until one that
455    doesn't exist is found.  Return a freshly allocated copy of the
456    unused file name.  */
457
458 static char *
459 unique_name_1 (const char *prefix)
460 {
461   int count = 1;
462   int plen = strlen (prefix);
463   char *template = (char *)alloca (plen + 1 + 24);
464   char *template_tail = template + plen;
465
466   memcpy (template, prefix, plen);
467   *template_tail++ = '.';
468
469   do
470     number_to_string (template_tail, count++);
471   while (file_exists_p (template));
472
473   return xstrdup (template);
474 }
475
476 /* Return a unique file name, based on FILE.
477
478    More precisely, if FILE doesn't exist, it is returned unmodified.
479    If not, FILE.1 is tried, then FILE.2, etc.  The first FILE.<number>
480    file name that doesn't exist is returned.
481
482    The resulting file is not created, only verified that it didn't
483    exist at the point in time when the function was called.
484    Therefore, where security matters, don't rely that the file created
485    by this function exists until you open it with O_EXCL or
486    equivalent.
487
488    If ALLOW_PASSTHROUGH is 0, it always returns a freshly allocated
489    string.  Otherwise, it may return FILE if the file doesn't exist
490    (and therefore doesn't need changing).  */
491
492 char *
493 unique_name (const char *file, bool allow_passthrough)
494 {
495   /* If the FILE itself doesn't exist, return it without
496      modification. */
497   if (!file_exists_p (file))
498     return allow_passthrough ? (char *)file : xstrdup (file);
499
500   /* Otherwise, find a numeric suffix that results in unused file name
501      and return it.  */
502   return unique_name_1 (file);
503 }
504
505 /* Create a file based on NAME, except without overwriting an existing
506    file with that name.  Providing O_EXCL is correctly implemented,
507    this function does not have the race condition associated with
508    opening the file returned by unique_name.  */
509
510 FILE *
511 unique_create (const char *name, bool binary, char **opened_name)
512 {
513   /* unique file name, based on NAME */
514   char *uname = unique_name (name, false);
515   FILE *fp;
516   while ((fp = fopen_excl (uname, binary)) == NULL && errno == EEXIST)
517     {
518       xfree (uname);
519       uname = unique_name (name, false);
520     }
521   if (opened_name && fp != NULL)
522     {
523       if (fp)
524         *opened_name = uname;
525       else
526         {
527           *opened_name = NULL;
528           xfree (uname);
529         }
530     }
531   else
532     xfree (uname);
533   return fp;
534 }
535
536 /* Open the file for writing, with the addition that the file is
537    opened "exclusively".  This means that, if the file already exists,
538    this function will *fail* and errno will be set to EEXIST.  If
539    BINARY is set, the file will be opened in binary mode, equivalent
540    to fopen's "wb".
541
542    If opening the file fails for any reason, including the file having
543    previously existed, this function returns NULL and sets errno
544    appropriately.  */
545    
546 FILE *
547 fopen_excl (const char *fname, bool binary)
548 {
549   int fd;
550 #ifdef O_EXCL
551   int flags = O_WRONLY | O_CREAT | O_EXCL;
552 # ifdef O_BINARY
553   if (binary)
554     flags |= O_BINARY;
555 # endif
556   fd = open (fname, flags, 0666);
557   if (fd < 0)
558     return NULL;
559   return fdopen (fd, binary ? "wb" : "w");
560 #else  /* not O_EXCL */
561   /* Manually check whether the file exists.  This is prone to race
562      conditions, but systems without O_EXCL haven't deserved
563      better.  */
564   if (file_exists_p (fname))
565     {
566       errno = EEXIST;
567       return NULL;
568     }
569   return fopen (fname, binary ? "wb" : "w");
570 #endif /* not O_EXCL */
571 }
572 \f
573 /* Create DIRECTORY.  If some of the pathname components of DIRECTORY
574    are missing, create them first.  In case any mkdir() call fails,
575    return its error status.  Returns 0 on successful completion.
576
577    The behaviour of this function should be identical to the behaviour
578    of `mkdir -p' on systems where mkdir supports the `-p' option.  */
579 int
580 make_directory (const char *directory)
581 {
582   int i, ret, quit = 0;
583   char *dir;
584
585   /* Make a copy of dir, to be able to write to it.  Otherwise, the
586      function is unsafe if called with a read-only char *argument.  */
587   STRDUP_ALLOCA (dir, directory);
588
589   /* If the first character of dir is '/', skip it (and thus enable
590      creation of absolute-pathname directories.  */
591   for (i = (*dir == '/'); 1; ++i)
592     {
593       for (; dir[i] && dir[i] != '/'; i++)
594         ;
595       if (!dir[i])
596         quit = 1;
597       dir[i] = '\0';
598       /* Check whether the directory already exists.  Allow creation of
599          of intermediate directories to fail, as the initial path components
600          are not necessarily directories!  */
601       if (!file_exists_p (dir))
602         ret = mkdir (dir, 0777);
603       else
604         ret = 0;
605       if (quit)
606         break;
607       else
608         dir[i] = '/';
609     }
610   return ret;
611 }
612
613 /* Merge BASE with FILE.  BASE can be a directory or a file name, FILE
614    should be a file name.
615
616    file_merge("/foo/bar", "baz")  => "/foo/baz"
617    file_merge("/foo/bar/", "baz") => "/foo/bar/baz"
618    file_merge("foo", "bar")       => "bar"
619
620    In other words, it's a simpler and gentler version of uri_merge.  */
621
622 char *
623 file_merge (const char *base, const char *file)
624 {
625   char *result;
626   const char *cut = (const char *)strrchr (base, '/');
627
628   if (!cut)
629     return xstrdup (file);
630
631   result = xmalloc (cut - base + 1 + strlen (file) + 1);
632   memcpy (result, base, cut - base);
633   result[cut - base] = '/';
634   strcpy (result + (cut - base) + 1, file);
635
636   return result;
637 }
638 \f
639 /* Like fnmatch, but performs a case-insensitive match.  */
640
641 int
642 fnmatch_nocase (const char *pattern, const char *string, int flags)
643 {
644 #ifdef FNM_CASEFOLD
645   /* The FNM_CASEFOLD flag started as a GNU extension, but it is now
646      also present on *BSD platforms, and possibly elsewhere.  */
647   return fnmatch (pattern, string, flags | FNM_CASEFOLD);
648 #else
649   /* Turn PATTERN and STRING to lower case and call fnmatch on them. */
650   char *patcopy = (char *) alloca (strlen (pattern) + 1);
651   char *strcopy = (char *) alloca (strlen (string) + 1);
652   char *p;
653   for (p = patcopy; *pattern; pattern++, p++)
654     *p = c_tolower (*pattern);
655   *p = '\0';
656   for (p = strcopy; *string; string++, p++)
657     *p = c_tolower (*string);
658   *p = '\0';
659   return fnmatch (patcopy, strcopy, flags);
660 #endif
661 }
662
663 static bool in_acclist (const char *const *, const char *, bool);
664
665 /* Determine whether a file is acceptable to be followed, according to
666    lists of patterns to accept/reject.  */
667 bool
668 acceptable (const char *s)
669 {
670   int l = strlen (s);
671
672   while (l && s[l] != '/')
673     --l;
674   if (s[l] == '/')
675     s += (l + 1);
676   if (opt.accepts)
677     {
678       if (opt.rejects)
679         return (in_acclist ((const char *const *)opt.accepts, s, true)
680                 && !in_acclist ((const char *const *)opt.rejects, s, true));
681       else
682         return in_acclist ((const char *const *)opt.accepts, s, true);
683     }
684   else if (opt.rejects)
685     return !in_acclist ((const char *const *)opt.rejects, s, true);
686   return true;
687 }
688
689 /* Check if D2 is a subdirectory of D1.  E.g. if D1 is `/something', subdir_p()
690    will return true if and only if D2 begins with `/something/' or is exactly 
691    '/something'.  */
692 bool
693 subdir_p (const char *d1, const char *d2)
694 {
695   if (*d1 == '\0')
696     return true;
697   if (!opt.ignore_case)
698     for (; *d1 && *d2 && (*d1 == *d2); ++d1, ++d2)
699       ;
700   else
701     for (; *d1 && *d2 && (c_tolower (*d1) == c_tolower (*d2)); ++d1, ++d2)
702       ;
703   
704   return *d1 == '\0' && (*d2 == '\0' || *d2 == '/');
705 }
706
707 /* Iterate through DIRLIST (which must be NULL-terminated), and return the
708    first element that matches DIR, through wildcards or front comparison (as
709    appropriate).  */
710 static bool
711 dir_matches_p (char **dirlist, const char *dir)
712 {
713   char **x;
714   int (*matcher) (const char *, const char *, int)
715     = opt.ignore_case ? fnmatch_nocase : fnmatch;
716
717   for (x = dirlist; *x; x++)
718     {
719       /* Remove leading '/' */
720       char *p = *x + (**x == '/');
721       if (has_wildcards_p (p))
722         {
723           if (matcher (p, dir, FNM_PATHNAME) == 0)
724             break;
725         }
726       else
727         {
728           if (subdir_p (p, dir))
729             break;
730         }
731     }
732       
733   return *x ? true : false;
734 }
735
736 /* Returns whether DIRECTORY is acceptable for download, wrt the
737    include/exclude lists.
738
739    The leading `/' is ignored in paths; relative and absolute paths
740    may be freely intermixed.  */
741
742 bool
743 accdir (const char *directory)
744 {
745   /* Remove starting '/'.  */
746   if (*directory == '/')
747     ++directory;
748   if (opt.includes)
749     {
750       if (!dir_matches_p (opt.includes, directory))
751         return false;
752     }
753   if (opt.excludes)
754     {
755       if (dir_matches_p (opt.excludes, directory))
756         return false;
757     }
758   return true;
759 }
760
761 /* Return true if STRING ends with TAIL.  For instance:
762
763    match_tail ("abc", "bc", false)  -> 1
764    match_tail ("abc", "ab", false)  -> 0
765    match_tail ("abc", "abc", false) -> 1
766
767    If FOLD_CASE is true, the comparison will be case-insensitive.  */
768
769 bool
770 match_tail (const char *string, const char *tail, bool fold_case)
771 {
772   int i, j;
773
774   /* We want this to be fast, so we code two loops, one with
775      case-folding, one without. */
776
777   if (!fold_case)
778     {
779       for (i = strlen (string), j = strlen (tail); i >= 0 && j >= 0; i--, j--)
780         if (string[i] != tail[j])
781           break;
782     }
783   else
784     {
785       for (i = strlen (string), j = strlen (tail); i >= 0 && j >= 0; i--, j--)
786         if (c_tolower (string[i]) != c_tolower (tail[j]))
787           break;
788     }
789
790   /* If the tail was exhausted, the match was succesful.  */
791   if (j == -1)
792     return true;
793   else
794     return false;
795 }
796
797 /* Checks whether string S matches each element of ACCEPTS.  A list
798    element are matched either with fnmatch() or match_tail(),
799    according to whether the element contains wildcards or not.
800
801    If the BACKWARD is false, don't do backward comparison -- just compare
802    them normally.  */
803 static bool
804 in_acclist (const char *const *accepts, const char *s, bool backward)
805 {
806   for (; *accepts; accepts++)
807     {
808       if (has_wildcards_p (*accepts))
809         {
810           int res = opt.ignore_case
811             ? fnmatch_nocase (*accepts, s, 0) : fnmatch (*accepts, s, 0);
812           /* fnmatch returns 0 if the pattern *does* match the string.  */
813           if (res == 0)
814             return true;
815         }
816       else
817         {
818           if (backward)
819             {
820               if (match_tail (s, *accepts, opt.ignore_case))
821                 return true;
822             }
823           else
824             {
825               int cmp = opt.ignore_case
826                 ? strcasecmp (s, *accepts) : strcmp (s, *accepts);
827               if (cmp == 0)
828                 return true;
829             }
830         }
831     }
832   return false;
833 }
834
835 /* Return the location of STR's suffix (file extension).  Examples:
836    suffix ("foo.bar")       -> "bar"
837    suffix ("foo.bar.baz")   -> "baz"
838    suffix ("/foo/bar")      -> NULL
839    suffix ("/foo.bar/baz")  -> NULL  */
840 char *
841 suffix (const char *str)
842 {
843   int i;
844
845   for (i = strlen (str); i && str[i] != '/' && str[i] != '.'; i--)
846     ;
847
848   if (str[i++] == '.')
849     return (char *)str + i;
850   else
851     return NULL;
852 }
853
854 /* Return true if S contains globbing wildcards (`*', `?', `[' or
855    `]').  */
856
857 bool
858 has_wildcards_p (const char *s)
859 {
860   for (; *s; s++)
861     if (*s == '*' || *s == '?' || *s == '[' || *s == ']')
862       return true;
863   return false;
864 }
865
866 /* Return true if FNAME ends with a typical HTML suffix.  The
867    following (case-insensitive) suffixes are presumed to be HTML
868    files:
869    
870      html
871      htm
872      ?html (`?' matches one character)
873
874    #### CAVEAT.  This is not necessarily a good indication that FNAME
875    refers to a file that contains HTML!  */
876 bool
877 has_html_suffix_p (const char *fname)
878 {
879   char *suf;
880
881   if ((suf = suffix (fname)) == NULL)
882     return false;
883   if (!strcasecmp (suf, "html"))
884     return true;
885   if (!strcasecmp (suf, "htm"))
886     return true;
887   if (suf[0] && !strcasecmp (suf + 1, "html"))
888     return true;
889   return false;
890 }
891
892 /* Read a line from FP and return the pointer to freshly allocated
893    storage.  The storage space is obtained through malloc() and should
894    be freed with free() when it is no longer needed.
895
896    The length of the line is not limited, except by available memory.
897    The newline character at the end of line is retained.  The line is
898    terminated with a zero character.
899
900    After end-of-file is encountered without anything being read, NULL
901    is returned.  NULL is also returned on error.  To distinguish
902    between these two cases, use the stdio function ferror().  */
903
904 char *
905 read_whole_line (FILE *fp)
906 {
907   int length = 0;
908   int bufsize = 82;
909   char *line = xmalloc (bufsize);
910
911   while (fgets (line + length, bufsize - length, fp))
912     {
913       length += strlen (line + length);
914       if (length == 0)
915         /* Possible for example when reading from a binary file where
916            a line begins with \0.  */
917         continue;
918
919       if (line[length - 1] == '\n')
920         break;
921
922       /* fgets() guarantees to read the whole line, or to use up the
923          space we've given it.  We can double the buffer
924          unconditionally.  */
925       bufsize <<= 1;
926       line = xrealloc (line, bufsize);
927     }
928   if (length == 0 || ferror (fp))
929     {
930       xfree (line);
931       return NULL;
932     }
933   if (length + 1 < bufsize)
934     /* Relieve the memory from our exponential greediness.  We say
935        `length + 1' because the terminating \0 is not included in
936        LENGTH.  We don't need to zero-terminate the string ourselves,
937        though, because fgets() does that.  */
938     line = xrealloc (line, length + 1);
939   return line;
940 }
941 \f
942 /* Read FILE into memory.  A pointer to `struct file_memory' are
943    returned; use struct element `content' to access file contents, and
944    the element `length' to know the file length.  `content' is *not*
945    zero-terminated, and you should *not* read or write beyond the [0,
946    length) range of characters.
947
948    After you are done with the file contents, call read_file_free to
949    release the memory.
950
951    Depending on the operating system and the type of file that is
952    being read, read_file() either mmap's the file into memory, or
953    reads the file into the core using read().
954
955    If file is named "-", fileno(stdin) is used for reading instead.
956    If you want to read from a real file named "-", use "./-" instead.  */
957
958 struct file_memory *
959 read_file (const char *file)
960 {
961   int fd;
962   struct file_memory *fm;
963   long size;
964   bool inhibit_close = false;
965
966   /* Some magic in the finest tradition of Perl and its kin: if FILE
967      is "-", just use stdin.  */
968   if (HYPHENP (file))
969     {
970       fd = fileno (stdin);
971       inhibit_close = true;
972       /* Note that we don't inhibit mmap() in this case.  If stdin is
973          redirected from a regular file, mmap() will still work.  */
974     }
975   else
976     fd = open (file, O_RDONLY);
977   if (fd < 0)
978     return NULL;
979   fm = xnew (struct file_memory);
980
981 #ifdef HAVE_MMAP
982   {
983     struct_fstat buf;
984     if (fstat (fd, &buf) < 0)
985       goto mmap_lose;
986     fm->length = buf.st_size;
987     /* NOTE: As far as I know, the callers of this function never
988        modify the file text.  Relying on this would enable us to
989        specify PROT_READ and MAP_SHARED for a marginal gain in
990        efficiency, but at some cost to generality.  */
991     fm->content = mmap (NULL, fm->length, PROT_READ | PROT_WRITE,
992                         MAP_PRIVATE, fd, 0);
993     if (fm->content == (char *)MAP_FAILED)
994       goto mmap_lose;
995     if (!inhibit_close)
996       close (fd);
997
998     fm->mmap_p = 1;
999     return fm;
1000   }
1001
1002  mmap_lose:
1003   /* The most common reason why mmap() fails is that FD does not point
1004      to a plain file.  However, it's also possible that mmap() doesn't
1005      work for a particular type of file.  Therefore, whenever mmap()
1006      fails, we just fall back to the regular method.  */
1007 #endif /* HAVE_MMAP */
1008
1009   fm->length = 0;
1010   size = 512;                   /* number of bytes fm->contents can
1011                                    hold at any given time. */
1012   fm->content = xmalloc (size);
1013   while (1)
1014     {
1015       wgint nread;
1016       if (fm->length > size / 2)
1017         {
1018           /* #### I'm not sure whether the whole exponential-growth
1019              thing makes sense with kernel read.  On Linux at least,
1020              read() refuses to read more than 4K from a file at a
1021              single chunk anyway.  But other Unixes might optimize it
1022              better, and it doesn't *hurt* anything, so I'm leaving
1023              it.  */
1024
1025           /* Normally, we grow SIZE exponentially to make the number
1026              of calls to read() and realloc() logarithmic in relation
1027              to file size.  However, read() can read an amount of data
1028              smaller than requested, and it would be unreasonable to
1029              double SIZE every time *something* was read.  Therefore,
1030              we double SIZE only when the length exceeds half of the
1031              entire allocated size.  */
1032           size <<= 1;
1033           fm->content = xrealloc (fm->content, size);
1034         }
1035       nread = read (fd, fm->content + fm->length, size - fm->length);
1036       if (nread > 0)
1037         /* Successful read. */
1038         fm->length += nread;
1039       else if (nread < 0)
1040         /* Error. */
1041         goto lose;
1042       else
1043         /* EOF */
1044         break;
1045     }
1046   if (!inhibit_close)
1047     close (fd);
1048   if (size > fm->length && fm->length != 0)
1049     /* Due to exponential growth of fm->content, the allocated region
1050        might be much larger than what is actually needed.  */
1051     fm->content = xrealloc (fm->content, fm->length);
1052   fm->mmap_p = 0;
1053   return fm;
1054
1055  lose:
1056   if (!inhibit_close)
1057     close (fd);
1058   xfree (fm->content);
1059   xfree (fm);
1060   return NULL;
1061 }
1062
1063 /* Release the resources held by FM.  Specifically, this calls
1064    munmap() or xfree() on fm->content, depending whether mmap or
1065    malloc/read were used to read in the file.  It also frees the
1066    memory needed to hold the FM structure itself.  */
1067
1068 void
1069 read_file_free (struct file_memory *fm)
1070 {
1071 #ifdef HAVE_MMAP
1072   if (fm->mmap_p)
1073     {
1074       munmap (fm->content, fm->length);
1075     }
1076   else
1077 #endif
1078     {
1079       xfree (fm->content);
1080     }
1081   xfree (fm);
1082 }
1083 \f
1084 /* Free the pointers in a NULL-terminated vector of pointers, then
1085    free the pointer itself.  */
1086 void
1087 free_vec (char **vec)
1088 {
1089   if (vec)
1090     {
1091       char **p = vec;
1092       while (*p)
1093         xfree (*p++);
1094       xfree (vec);
1095     }
1096 }
1097
1098 /* Append vector V2 to vector V1.  The function frees V2 and
1099    reallocates V1 (thus you may not use the contents of neither
1100    pointer after the call).  If V1 is NULL, V2 is returned.  */
1101 char **
1102 merge_vecs (char **v1, char **v2)
1103 {
1104   int i, j;
1105
1106   if (!v1)
1107     return v2;
1108   if (!v2)
1109     return v1;
1110   if (!*v2)
1111     {
1112       /* To avoid j == 0 */
1113       xfree (v2);
1114       return v1;
1115     }
1116   /* Count v1.  */
1117   for (i = 0; v1[i]; i++)
1118     ;
1119   /* Count v2.  */
1120   for (j = 0; v2[j]; j++)
1121     ;
1122   /* Reallocate v1.  */
1123   v1 = xrealloc (v1, (i + j + 1) * sizeof (char **));
1124   memcpy (v1 + i, v2, (j + 1) * sizeof (char *));
1125   xfree (v2);
1126   return v1;
1127 }
1128
1129 /* Append a freshly allocated copy of STR to VEC.  If VEC is NULL, it
1130    is allocated as needed.  Return the new value of the vector. */
1131
1132 char **
1133 vec_append (char **vec, const char *str)
1134 {
1135   int cnt;                      /* count of vector elements, including
1136                                    the one we're about to append */
1137   if (vec != NULL)
1138     {
1139       for (cnt = 0; vec[cnt]; cnt++)
1140         ;
1141       ++cnt;
1142     }
1143   else
1144     cnt = 1;
1145   /* Reallocate the array to fit the new element and the NULL. */
1146   vec = xrealloc (vec, (cnt + 1) * sizeof (char *));
1147   /* Append a copy of STR to the vector. */
1148   vec[cnt - 1] = xstrdup (str);
1149   vec[cnt] = NULL;
1150   return vec;
1151 }
1152 \f
1153 /* Sometimes it's useful to create "sets" of strings, i.e. special
1154    hash tables where you want to store strings as keys and merely
1155    query for their existence.  Here is a set of utility routines that
1156    makes that transparent.  */
1157
1158 void
1159 string_set_add (struct hash_table *ht, const char *s)
1160 {
1161   /* First check whether the set element already exists.  If it does,
1162      do nothing so that we don't have to free() the old element and
1163      then strdup() a new one.  */
1164   if (hash_table_contains (ht, s))
1165     return;
1166
1167   /* We use "1" as value.  It provides us a useful and clear arbitrary
1168      value, and it consumes no memory -- the pointers to the same
1169      string "1" will be shared by all the key-value pairs in all `set'
1170      hash tables.  */
1171   hash_table_put (ht, xstrdup (s), "1");
1172 }
1173
1174 /* Synonym for hash_table_contains... */
1175
1176 int
1177 string_set_contains (struct hash_table *ht, const char *s)
1178 {
1179   return hash_table_contains (ht, s);
1180 }
1181
1182 /* Convert the specified string set to array.  ARRAY should be large
1183    enough to hold hash_table_count(ht) char pointers.  */
1184
1185 void string_set_to_array (struct hash_table *ht, char **array)
1186 {
1187   hash_table_iterator iter;
1188   for (hash_table_iterate (ht, &iter); hash_table_iter_next (&iter); )
1189     *array++ = iter.key;
1190 }
1191
1192 /* Free the string set.  This frees both the storage allocated for
1193    keys and the actual hash table.  (hash_table_destroy would only
1194    destroy the hash table.)  */
1195
1196 void
1197 string_set_free (struct hash_table *ht)
1198 {
1199   hash_table_iterator iter;
1200   for (hash_table_iterate (ht, &iter); hash_table_iter_next (&iter); )
1201     xfree (iter.key);
1202   hash_table_destroy (ht);
1203 }
1204
1205 /* Utility function: simply call xfree() on all keys and values of HT.  */
1206
1207 void
1208 free_keys_and_values (struct hash_table *ht)
1209 {
1210   hash_table_iterator iter;
1211   for (hash_table_iterate (ht, &iter); hash_table_iter_next (&iter); )
1212     {
1213       xfree (iter.key);
1214       xfree (iter.value);
1215     }
1216 }
1217 \f
1218 /* Get digit grouping data for thousand separors by calling
1219    localeconv().  The data includes separator string and grouping info
1220    and is cached after the first call to the function.
1221
1222    In locales that don't set a thousand separator (such as the "C"
1223    locale), this forces it to be ",".  We are now only showing
1224    thousand separators in one place, so this shouldn't be a problem in
1225    practice.  */
1226
1227 static void
1228 get_grouping_data (const char **sep, const char **grouping)
1229 {
1230   static const char *cached_sep;
1231   static const char *cached_grouping;
1232   static bool initialized;
1233   if (!initialized)
1234     {
1235       /* Get the grouping info from the locale. */
1236       struct lconv *lconv = localeconv ();
1237       cached_sep = lconv->thousands_sep;
1238       cached_grouping = lconv->grouping;
1239 #if ! USE_NLS_PROGRESS_BAR
1240       /* We can't count column widths, so ensure that the separator
1241        * is single-byte only (let check below determine what byte). */
1242       if (strlen(cached_sep) > 1)
1243         cached_sep = "";
1244 #endif
1245       if (!*cached_sep)
1246         {
1247           /* Many locales (such as "C" or "hr_HR") don't specify
1248              grouping, which we still want to use it for legibility.
1249              In those locales set the sep char to ',', unless that
1250              character is used for decimal point, in which case set it
1251              to ".".  */
1252           if (*lconv->decimal_point != ',')
1253             cached_sep = ",";
1254           else
1255             cached_sep = ".";
1256           cached_grouping = "\x03";
1257         }
1258       initialized = true;
1259     }
1260   *sep = cached_sep;
1261   *grouping = cached_grouping;
1262 }
1263
1264 /* Return a printed representation of N with thousand separators.
1265    This should respect locale settings, with the exception of the "C"
1266    locale which mandates no separator, but we use one anyway.
1267
1268    Unfortunately, we cannot use %'d (in fact it would be %'j) to get
1269    the separators because it's too non-portable, and it's hard to test
1270    for this feature at configure time.  Besides, it wouldn't display
1271    separators in the "C" locale, still used by many Unix users.  */
1272
1273 const char *
1274 with_thousand_seps (wgint n)
1275 {
1276   static char outbuf[48];
1277   char *p = outbuf + sizeof outbuf;
1278
1279   /* Info received from locale */
1280   const char *grouping, *sep;
1281   int seplen;
1282
1283   /* State information */
1284   int i = 0, groupsize;
1285   const char *atgroup;
1286
1287   bool negative = n < 0;
1288
1289   /* Initialize grouping data. */
1290   get_grouping_data (&sep, &grouping);
1291   seplen = strlen (sep);
1292   atgroup = grouping;
1293   groupsize = *atgroup++;
1294
1295   /* This would overflow on WGINT_MIN, but printing negative numbers
1296      is not an important goal of this fuinction.  */
1297   if (negative)
1298     n = -n;
1299
1300   /* Write the number into the buffer, backwards, inserting the
1301      separators as necessary.  */
1302   *--p = '\0';
1303   while (1)
1304     {
1305       *--p = n % 10 + '0';
1306       n /= 10;
1307       if (n == 0)
1308         break;
1309       /* Prepend SEP to every groupsize'd digit and get new groupsize.  */
1310       if (++i == groupsize)
1311         {
1312           if (seplen == 1)
1313             *--p = *sep;
1314           else
1315             memcpy (p -= seplen, sep, seplen);
1316           i = 0;
1317           if (*atgroup)
1318             groupsize = *atgroup++;
1319         }
1320     }
1321   if (negative)
1322     *--p = '-';
1323
1324   return p;
1325 }
1326
1327 /* N, a byte quantity, is converted to a human-readable abberviated
1328    form a la sizes printed by `ls -lh'.  The result is written to a
1329    static buffer, a pointer to which is returned.
1330
1331    Unlike `with_thousand_seps', this approximates to the nearest unit.
1332    Quoting GNU libit: "Most people visually process strings of 3-4
1333    digits effectively, but longer strings of digits are more prone to
1334    misinterpretation.  Hence, converting to an abbreviated form
1335    usually improves readability."
1336
1337    This intentionally uses kilobyte (KB), megabyte (MB), etc. in their
1338    original computer-related meaning of "powers of 1024".  We don't
1339    use the "*bibyte" names invented in 1998, and seldom used in
1340    practice.  Wikipedia's entry on "binary prefix" discusses this in
1341    some detail.  */
1342
1343 char *
1344 human_readable (HR_NUMTYPE n)
1345 {
1346   /* These suffixes are compatible with those of GNU `ls -lh'. */
1347   static char powers[] =
1348     {
1349       'K',                      /* kilobyte, 2^10 bytes */
1350       'M',                      /* megabyte, 2^20 bytes */
1351       'G',                      /* gigabyte, 2^30 bytes */
1352       'T',                      /* terabyte, 2^40 bytes */
1353       'P',                      /* petabyte, 2^50 bytes */
1354       'E',                      /* exabyte,  2^60 bytes */
1355     };
1356   static char buf[8];
1357   int i;
1358
1359   /* If the quantity is smaller than 1K, just print it. */
1360   if (n < 1024)
1361     {
1362       snprintf (buf, sizeof (buf), "%d", (int) n);
1363       return buf;
1364     }
1365
1366   /* Loop over powers, dividing N with 1024 in each iteration.  This
1367      works unchanged for all sizes of wgint, while still avoiding
1368      non-portable `long double' arithmetic.  */
1369   for (i = 0; i < countof (powers); i++)
1370     {
1371       /* At each iteration N is greater than the *subsequent* power.
1372          That way N/1024.0 produces a decimal number in the units of
1373          *this* power.  */
1374       if ((n / 1024) < 1024 || i == countof (powers) - 1)
1375         {
1376           double val = n / 1024.0;
1377           /* Print values smaller than 10 with one decimal digits, and
1378              others without any decimals.  */
1379           snprintf (buf, sizeof (buf), "%.*f%c",
1380                     val < 10 ? 1 : 0, val, powers[i]);
1381           return buf;
1382         }
1383       n /= 1024;
1384     }
1385   return NULL;                  /* unreached */
1386 }
1387
1388 /* Count the digits in the provided number.  Used to allocate space
1389    when printing numbers.  */
1390
1391 int
1392 numdigit (wgint number)
1393 {
1394   int cnt = 1;
1395   if (number < 0)
1396     ++cnt;                      /* accomodate '-' */
1397   while ((number /= 10) != 0)
1398     ++cnt;
1399   return cnt;
1400 }
1401
1402 #define PR(mask) *p++ = n / (mask) + '0'
1403
1404 /* DIGITS_<D> is used to print a D-digit number and should be called
1405    with mask==10^(D-1).  It prints n/mask (the first digit), reducing
1406    n to n%mask (the remaining digits), and calling DIGITS_<D-1>.
1407    Recursively this continues until DIGITS_1 is invoked.  */
1408
1409 #define DIGITS_1(mask) PR (mask)
1410 #define DIGITS_2(mask) PR (mask), n %= (mask), DIGITS_1 ((mask) / 10)
1411 #define DIGITS_3(mask) PR (mask), n %= (mask), DIGITS_2 ((mask) / 10)
1412 #define DIGITS_4(mask) PR (mask), n %= (mask), DIGITS_3 ((mask) / 10)
1413 #define DIGITS_5(mask) PR (mask), n %= (mask), DIGITS_4 ((mask) / 10)
1414 #define DIGITS_6(mask) PR (mask), n %= (mask), DIGITS_5 ((mask) / 10)
1415 #define DIGITS_7(mask) PR (mask), n %= (mask), DIGITS_6 ((mask) / 10)
1416 #define DIGITS_8(mask) PR (mask), n %= (mask), DIGITS_7 ((mask) / 10)
1417 #define DIGITS_9(mask) PR (mask), n %= (mask), DIGITS_8 ((mask) / 10)
1418 #define DIGITS_10(mask) PR (mask), n %= (mask), DIGITS_9 ((mask) / 10)
1419
1420 /* DIGITS_<11-20> are only used on machines with 64-bit wgints. */
1421
1422 #define DIGITS_11(mask) PR (mask), n %= (mask), DIGITS_10 ((mask) / 10)
1423 #define DIGITS_12(mask) PR (mask), n %= (mask), DIGITS_11 ((mask) / 10)
1424 #define DIGITS_13(mask) PR (mask), n %= (mask), DIGITS_12 ((mask) / 10)
1425 #define DIGITS_14(mask) PR (mask), n %= (mask), DIGITS_13 ((mask) / 10)
1426 #define DIGITS_15(mask) PR (mask), n %= (mask), DIGITS_14 ((mask) / 10)
1427 #define DIGITS_16(mask) PR (mask), n %= (mask), DIGITS_15 ((mask) / 10)
1428 #define DIGITS_17(mask) PR (mask), n %= (mask), DIGITS_16 ((mask) / 10)
1429 #define DIGITS_18(mask) PR (mask), n %= (mask), DIGITS_17 ((mask) / 10)
1430 #define DIGITS_19(mask) PR (mask), n %= (mask), DIGITS_18 ((mask) / 10)
1431
1432 /* Shorthand for casting to wgint. */
1433 #define W wgint
1434
1435 /* Print NUMBER to BUFFER in base 10.  This is equivalent to
1436    `sprintf(buffer, "%lld", (long long) number)', only typically much
1437    faster and portable to machines without long long.
1438
1439    The speedup may make a difference in programs that frequently
1440    convert numbers to strings.  Some implementations of sprintf,
1441    particularly the one in some versions of GNU libc, have been known
1442    to be quite slow when converting integers to strings.
1443
1444    Return the pointer to the location where the terminating zero was
1445    printed.  (Equivalent to calling buffer+strlen(buffer) after the
1446    function is done.)
1447
1448    BUFFER should be large enough to accept as many bytes as you expect
1449    the number to take up.  On machines with 64-bit wgints the maximum
1450    needed size is 24 bytes.  That includes the digits needed for the
1451    largest 64-bit number, the `-' sign in case it's negative, and the
1452    terminating '\0'.  */
1453
1454 char *
1455 number_to_string (char *buffer, wgint number)
1456 {
1457   char *p = buffer;
1458   wgint n = number;
1459
1460   int last_digit_char = 0;
1461
1462 #if (SIZEOF_WGINT != 4) && (SIZEOF_WGINT != 8)
1463   /* We are running in a very strange environment.  Leave the correct
1464      printing to sprintf.  */
1465   p += sprintf (buf, "%j", (intmax_t) (n));
1466 #else  /* (SIZEOF_WGINT == 4) || (SIZEOF_WGINT == 8) */
1467
1468   if (n < 0)
1469     {
1470       if (n < -WGINT_MAX)
1471         {
1472           /* n = -n would overflow because -n would evaluate to a
1473              wgint value larger than WGINT_MAX.  Need to make n
1474              smaller and handle the last digit separately.  */
1475           int last_digit = n % 10;
1476           /* The sign of n%10 is implementation-defined. */
1477           if (last_digit < 0)
1478             last_digit_char = '0' - last_digit;
1479           else
1480             last_digit_char = '0' + last_digit;
1481           /* After n is made smaller, -n will not overflow. */
1482           n /= 10;
1483         }
1484
1485       *p++ = '-';
1486       n = -n;
1487     }
1488
1489   /* Use the DIGITS_ macro appropriate for N's number of digits.  That
1490      way printing any N is fully open-coded without a loop or jump.
1491      (Also see description of DIGITS_*.)  */
1492
1493   if      (n < 10)                       DIGITS_1 (1);
1494   else if (n < 100)                      DIGITS_2 (10);
1495   else if (n < 1000)                     DIGITS_3 (100);
1496   else if (n < 10000)                    DIGITS_4 (1000);
1497   else if (n < 100000)                   DIGITS_5 (10000);
1498   else if (n < 1000000)                  DIGITS_6 (100000);
1499   else if (n < 10000000)                 DIGITS_7 (1000000);
1500   else if (n < 100000000)                DIGITS_8 (10000000);
1501   else if (n < 1000000000)               DIGITS_9 (100000000);
1502 #if SIZEOF_WGINT == 4
1503   /* wgint is 32 bits wide: no number has more than 10 digits. */
1504   else                                   DIGITS_10 (1000000000);
1505 #else
1506   /* wgint is 64 bits wide: handle numbers with 9-19 decimal digits.
1507      Constants are constructed by compile-time multiplication to avoid
1508      dealing with different notations for 64-bit constants
1509      (nL/nLL/nI64, depending on the compiler and architecture).  */
1510   else if (n < 10*(W)1000000000)         DIGITS_10 (1000000000);
1511   else if (n < 100*(W)1000000000)        DIGITS_11 (10*(W)1000000000);
1512   else if (n < 1000*(W)1000000000)       DIGITS_12 (100*(W)1000000000);
1513   else if (n < 10000*(W)1000000000)      DIGITS_13 (1000*(W)1000000000);
1514   else if (n < 100000*(W)1000000000)     DIGITS_14 (10000*(W)1000000000);
1515   else if (n < 1000000*(W)1000000000)    DIGITS_15 (100000*(W)1000000000);
1516   else if (n < 10000000*(W)1000000000)   DIGITS_16 (1000000*(W)1000000000);
1517   else if (n < 100000000*(W)1000000000)  DIGITS_17 (10000000*(W)1000000000);
1518   else if (n < 1000000000*(W)1000000000) DIGITS_18 (100000000*(W)1000000000);
1519   else                                   DIGITS_19 (1000000000*(W)1000000000);
1520 #endif
1521
1522   if (last_digit_char)
1523     *p++ = last_digit_char;
1524
1525   *p = '\0';
1526 #endif /* (SIZEOF_WGINT == 4) || (SIZEOF_WGINT == 8) */
1527
1528   return p;
1529 }
1530
1531 #undef PR
1532 #undef W
1533 #undef SPRINTF_WGINT
1534 #undef DIGITS_1
1535 #undef DIGITS_2
1536 #undef DIGITS_3
1537 #undef DIGITS_4
1538 #undef DIGITS_5
1539 #undef DIGITS_6
1540 #undef DIGITS_7
1541 #undef DIGITS_8
1542 #undef DIGITS_9
1543 #undef DIGITS_10
1544 #undef DIGITS_11
1545 #undef DIGITS_12
1546 #undef DIGITS_13
1547 #undef DIGITS_14
1548 #undef DIGITS_15
1549 #undef DIGITS_16
1550 #undef DIGITS_17
1551 #undef DIGITS_18
1552 #undef DIGITS_19
1553
1554 #define RING_SIZE 3
1555
1556 /* Print NUMBER to a statically allocated string and return a pointer
1557    to the printed representation.
1558
1559    This function is intended to be used in conjunction with printf.
1560    It is hard to portably print wgint values:
1561     a) you cannot use printf("%ld", number) because wgint can be long
1562        long on 32-bit machines with LFS.
1563     b) you cannot use printf("%lld", number) because NUMBER could be
1564        long on 32-bit machines without LFS, or on 64-bit machines,
1565        which do not require LFS.  Also, Windows doesn't support %lld.
1566     c) you cannot use printf("%j", (int_max_t) number) because not all
1567        versions of printf support "%j", the most notable being the one
1568        on Windows.
1569     d) you cannot #define WGINT_FMT to the appropriate format and use
1570        printf(WGINT_FMT, number) because that would break translations
1571        for user-visible messages, such as printf("Downloaded: %d
1572        bytes\n", number).
1573
1574    What you should use instead is printf("%s", number_to_static_string
1575    (number)).
1576
1577    CAVEAT: since the function returns pointers to static data, you
1578    must be careful to copy its result before calling it again.
1579    However, to make it more useful with printf, the function maintains
1580    an internal ring of static buffers to return.  That way things like
1581    printf("%s %s", number_to_static_string (num1),
1582    number_to_static_string (num2)) work as expected.  Three buffers
1583    are currently used, which means that "%s %s %s" will work, but "%s
1584    %s %s %s" won't.  If you need to print more than three wgints,
1585    bump the RING_SIZE (or rethink your message.)  */
1586
1587 char *
1588 number_to_static_string (wgint number)
1589 {
1590   static char ring[RING_SIZE][24];
1591   static int ringpos;
1592   char *buf = ring[ringpos];
1593   number_to_string (buf, number);
1594   ringpos = (ringpos + 1) % RING_SIZE;
1595   return buf;
1596 }
1597 \f
1598 /* Determine the width of the terminal we're running on.  If that's
1599    not possible, return 0.  */
1600
1601 int
1602 determine_screen_width (void)
1603 {
1604   /* If there's a way to get the terminal size using POSIX
1605      tcgetattr(), somebody please tell me.  */
1606 #ifdef TIOCGWINSZ
1607   int fd;
1608   struct winsize wsz;
1609
1610   if (opt.lfilename != NULL)
1611     return 0;
1612
1613   fd = fileno (stderr);
1614   if (ioctl (fd, TIOCGWINSZ, &wsz) < 0)
1615     return 0;                   /* most likely ENOTTY */
1616
1617   return wsz.ws_col;
1618 #elif defined(WINDOWS)
1619   CONSOLE_SCREEN_BUFFER_INFO csbi;
1620   if (!GetConsoleScreenBufferInfo (GetStdHandle (STD_ERROR_HANDLE), &csbi))
1621     return 0;
1622   return csbi.dwSize.X;
1623 #else  /* neither TIOCGWINSZ nor WINDOWS */
1624   return 0;
1625 #endif /* neither TIOCGWINSZ nor WINDOWS */
1626 }
1627 \f
1628 /* Whether the rnd system (either rand or [dl]rand48) has been
1629    seeded.  */
1630 static int rnd_seeded;
1631
1632 /* Return a random number between 0 and MAX-1, inclusive.
1633
1634    If the system does not support lrand48 and MAX is greater than the
1635    value of RAND_MAX+1 on the system, the returned value will be in
1636    the range [0, RAND_MAX].  This may be fixed in a future release.
1637    The random number generator is seeded automatically the first time
1638    it is called.
1639
1640    This uses lrand48 where available, rand elsewhere.  DO NOT use it
1641    for cryptography.  It is only meant to be used in situations where
1642    quality of the random numbers returned doesn't really matter.  */
1643
1644 int
1645 random_number (int max)
1646 {
1647 #ifdef HAVE_DRAND48
1648   if (!rnd_seeded)
1649     {
1650       srand48 ((long) time (NULL) ^ (long) getpid ());
1651       rnd_seeded = 1;
1652     }
1653   return lrand48 () % max;
1654 #else  /* not HAVE_DRAND48 */
1655
1656   double bounded;
1657   int rnd;
1658   if (!rnd_seeded)
1659     {
1660       srand ((unsigned) time (NULL) ^ (unsigned) getpid ());
1661       rnd_seeded = 1;
1662     }
1663   rnd = rand ();
1664
1665   /* Like rand() % max, but uses the high-order bits for better
1666      randomness on architectures where rand() is implemented using a
1667      simple congruential generator.  */
1668
1669   bounded = (double) max * rnd / (RAND_MAX + 1.0);
1670   return (int) bounded;
1671
1672 #endif /* not HAVE_DRAND48 */
1673 }
1674
1675 /* Return a random uniformly distributed floating point number in the
1676    [0, 1) range.  Uses drand48 where available, and a really lame
1677    kludge elsewhere.  */
1678
1679 double
1680 random_float (void)
1681 {
1682 #ifdef HAVE_DRAND48
1683   if (!rnd_seeded)
1684     {
1685       srand48 ((long) time (NULL) ^ (long) getpid ());
1686       rnd_seeded = 1;
1687     }
1688   return drand48 ();
1689 #else  /* not HAVE_DRAND48 */
1690   return (  random_number (10000) / 10000.0
1691           + random_number (10000) / (10000.0 * 10000.0)
1692           + random_number (10000) / (10000.0 * 10000.0 * 10000.0)
1693           + random_number (10000) / (10000.0 * 10000.0 * 10000.0 * 10000.0));
1694 #endif /* not HAVE_DRAND48 */
1695 }
1696 \f
1697 /* Implementation of run_with_timeout, a generic timeout-forcing
1698    routine for systems with Unix-like signal handling.  */
1699
1700 #ifdef USE_SIGNAL_TIMEOUT
1701 # ifdef HAVE_SIGSETJMP
1702 #  define SETJMP(env) sigsetjmp (env, 1)
1703
1704 static sigjmp_buf run_with_timeout_env;
1705
1706 static void
1707 abort_run_with_timeout (int sig)
1708 {
1709   assert (sig == SIGALRM);
1710   siglongjmp (run_with_timeout_env, -1);
1711 }
1712 # else /* not HAVE_SIGSETJMP */
1713 #  define SETJMP(env) setjmp (env)
1714
1715 static jmp_buf run_with_timeout_env;
1716
1717 static void
1718 abort_run_with_timeout (int sig)
1719 {
1720   assert (sig == SIGALRM);
1721   /* We don't have siglongjmp to preserve the set of blocked signals;
1722      if we longjumped out of the handler at this point, SIGALRM would
1723      remain blocked.  We must unblock it manually. */
1724   int mask = siggetmask ();
1725   mask &= ~sigmask (SIGALRM);
1726   sigsetmask (mask);
1727
1728   /* Now it's safe to longjump. */
1729   longjmp (run_with_timeout_env, -1);
1730 }
1731 # endif /* not HAVE_SIGSETJMP */
1732
1733 /* Arrange for SIGALRM to be delivered in TIMEOUT seconds.  This uses
1734    setitimer where available, alarm otherwise.
1735
1736    TIMEOUT should be non-zero.  If the timeout value is so small that
1737    it would be rounded to zero, it is rounded to the least legal value
1738    instead (1us for setitimer, 1s for alarm).  That ensures that
1739    SIGALRM will be delivered in all cases.  */
1740
1741 static void
1742 alarm_set (double timeout)
1743 {
1744 #ifdef ITIMER_REAL
1745   /* Use the modern itimer interface. */
1746   struct itimerval itv;
1747   xzero (itv);
1748   itv.it_value.tv_sec = (long) timeout;
1749   itv.it_value.tv_usec = 1000000 * (timeout - (long)timeout);
1750   if (itv.it_value.tv_sec == 0 && itv.it_value.tv_usec == 0)
1751     /* Ensure that we wait for at least the minimum interval.
1752        Specifying zero would mean "wait forever".  */
1753     itv.it_value.tv_usec = 1;
1754   setitimer (ITIMER_REAL, &itv, NULL);
1755 #else  /* not ITIMER_REAL */
1756   /* Use the old alarm() interface. */
1757   int secs = (int) timeout;
1758   if (secs == 0)
1759     /* Round TIMEOUTs smaller than 1 to 1, not to zero.  This is
1760        because alarm(0) means "never deliver the alarm", i.e. "wait
1761        forever", which is not what someone who specifies a 0.5s
1762        timeout would expect.  */
1763     secs = 1;
1764   alarm (secs);
1765 #endif /* not ITIMER_REAL */
1766 }
1767
1768 /* Cancel the alarm set with alarm_set. */
1769
1770 static void
1771 alarm_cancel (void)
1772 {
1773 #ifdef ITIMER_REAL
1774   struct itimerval disable;
1775   xzero (disable);
1776   setitimer (ITIMER_REAL, &disable, NULL);
1777 #else  /* not ITIMER_REAL */
1778   alarm (0);
1779 #endif /* not ITIMER_REAL */
1780 }
1781
1782 /* Call FUN(ARG), but don't allow it to run for more than TIMEOUT
1783    seconds.  Returns true if the function was interrupted with a
1784    timeout, false otherwise.
1785
1786    This works by setting up SIGALRM to be delivered in TIMEOUT seconds
1787    using setitimer() or alarm().  The timeout is enforced by
1788    longjumping out of the SIGALRM handler.  This has several
1789    advantages compared to the traditional approach of relying on
1790    signals causing system calls to exit with EINTR:
1791
1792      * The callback function is *forcibly* interrupted after the
1793        timeout expires, (almost) regardless of what it was doing and
1794        whether it was in a syscall.  For example, a calculation that
1795        takes a long time is interrupted as reliably as an IO
1796        operation.
1797
1798      * It works with both SYSV and BSD signals because it doesn't
1799        depend on the default setting of SA_RESTART.
1800
1801      * It doesn't require special handler setup beyond a simple call
1802        to signal().  (It does use sigsetjmp/siglongjmp, but they're
1803        optional.)
1804
1805    The only downside is that, if FUN allocates internal resources that
1806    are normally freed prior to exit from the functions, they will be
1807    lost in case of timeout.  */
1808
1809 bool
1810 run_with_timeout (double timeout, void (*fun) (void *), void *arg)
1811 {
1812   int saved_errno;
1813
1814   if (timeout == 0)
1815     {
1816       fun (arg);
1817       return false;
1818     }
1819
1820   signal (SIGALRM, abort_run_with_timeout);
1821   if (SETJMP (run_with_timeout_env) != 0)
1822     {
1823       /* Longjumped out of FUN with a timeout. */
1824       signal (SIGALRM, SIG_DFL);
1825       return true;
1826     }
1827   alarm_set (timeout);
1828   fun (arg);
1829
1830   /* Preserve errno in case alarm() or signal() modifies it. */
1831   saved_errno = errno;
1832   alarm_cancel ();
1833   signal (SIGALRM, SIG_DFL);
1834   errno = saved_errno;
1835
1836   return false;
1837 }
1838
1839 #else  /* not USE_SIGNAL_TIMEOUT */
1840
1841 #ifndef WINDOWS
1842 /* A stub version of run_with_timeout that just calls FUN(ARG).  Don't
1843    define it under Windows, because Windows has its own version of
1844    run_with_timeout that uses threads.  */
1845
1846 bool
1847 run_with_timeout (double timeout, void (*fun) (void *), void *arg)
1848 {
1849   fun (arg);
1850   return false;
1851 }
1852 #endif /* not WINDOWS */
1853 #endif /* not USE_SIGNAL_TIMEOUT */
1854 \f
1855 #ifndef WINDOWS
1856
1857 /* Sleep the specified amount of seconds.  On machines without
1858    nanosleep(), this may sleep shorter if interrupted by signals.  */
1859
1860 void
1861 xsleep (double seconds)
1862 {
1863 #ifdef HAVE_NANOSLEEP
1864   /* nanosleep is the preferred interface because it offers high
1865      accuracy and, more importantly, because it allows us to reliably
1866      restart receiving a signal such as SIGWINCH.  (There was an
1867      actual Debian bug report about --limit-rate malfunctioning while
1868      the terminal was being resized.)  */
1869   struct timespec sleep, remaining;
1870   sleep.tv_sec = (long) seconds;
1871   sleep.tv_nsec = 1000000000 * (seconds - (long) seconds);
1872   while (nanosleep (&sleep, &remaining) < 0 && errno == EINTR)
1873     /* If nanosleep has been interrupted by a signal, adjust the
1874        sleeping period and return to sleep.  */
1875     sleep = remaining;
1876 #elif defined(HAVE_USLEEP)
1877   /* If usleep is available, use it in preference to select.  */
1878   if (seconds >= 1)
1879     {
1880       /* On some systems, usleep cannot handle values larger than
1881          1,000,000.  If the period is larger than that, use sleep
1882          first, then add usleep for subsecond accuracy.  */
1883       sleep (seconds);
1884       seconds -= (long) seconds;
1885     }
1886   usleep (seconds * 1000000);
1887 #else /* fall back select */
1888   /* Note that, although Windows supports select, it can't be used to
1889      implement sleeping because Winsock's select doesn't implement
1890      timeout when it is passed NULL pointers for all fd sets.  (But it
1891      does under Cygwin, which implements Unix-compatible select.)  */
1892   struct timeval sleep;
1893   sleep.tv_sec = (long) seconds;
1894   sleep.tv_usec = 1000000 * (seconds - (long) seconds);
1895   select (0, NULL, NULL, NULL, &sleep);
1896   /* If select returns -1 and errno is EINTR, it means we were
1897      interrupted by a signal.  But without knowing how long we've
1898      actually slept, we can't return to sleep.  Using gettimeofday to
1899      track sleeps is slow and unreliable due to clock skew.  */
1900 #endif
1901 }
1902
1903 #endif /* not WINDOWS */
1904
1905 /* Encode the octets in DATA of length LENGTH to base64 format,
1906    storing the result to DEST.  The output will be zero-terminated,
1907    and must point to a writable buffer of at least
1908    1+BASE64_LENGTH(length) bytes.  The function returns the length of
1909    the resulting base64 data, not counting the terminating zero.
1910
1911    This implementation does not emit newlines after 76 characters of
1912    base64 data.  */
1913
1914 int
1915 base64_encode (const void *data, int length, char *dest)
1916 {
1917   /* Conversion table.  */
1918   static const char tbl[64] = {
1919     'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
1920     'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
1921     'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
1922     'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'
1923   };
1924   /* Access bytes in DATA as unsigned char, otherwise the shifts below
1925      don't work for data with MSB set. */
1926   const unsigned char *s = data;
1927   /* Theoretical ANSI violation when length < 3. */
1928   const unsigned char *end = (const unsigned char *) data + length - 2;
1929   char *p = dest;
1930
1931   /* Transform the 3x8 bits to 4x6 bits, as required by base64.  */
1932   for (; s < end; s += 3)
1933     {
1934       *p++ = tbl[s[0] >> 2];
1935       *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
1936       *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
1937       *p++ = tbl[s[2] & 0x3f];
1938     }
1939
1940   /* Pad the result if necessary...  */
1941   switch (length % 3)
1942     {
1943     case 1:
1944       *p++ = tbl[s[0] >> 2];
1945       *p++ = tbl[(s[0] & 3) << 4];
1946       *p++ = '=';
1947       *p++ = '=';
1948       break;
1949     case 2:
1950       *p++ = tbl[s[0] >> 2];
1951       *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
1952       *p++ = tbl[((s[1] & 0xf) << 2)];
1953       *p++ = '=';
1954       break;
1955     }
1956   /* ...and zero-terminate it.  */
1957   *p = '\0';
1958
1959   return p - dest;
1960 }
1961
1962 /* Store in C the next non-whitespace character from the string, or \0
1963    when end of string is reached.  */
1964 #define NEXT_CHAR(c, p) do {                    \
1965   c = (unsigned char) *p++;                     \
1966 } while (c_isspace (c))
1967
1968 #define IS_ASCII(c) (((c) & 0x80) == 0)
1969
1970 /* Decode data from BASE64 (a null-terminated string) into memory
1971    pointed to by DEST.  DEST is assumed to be large enough to
1972    accomodate the decoded data, which is guaranteed to be no more than
1973    3/4*strlen(base64).
1974
1975    Since DEST is assumed to contain binary data, it is not
1976    NUL-terminated.  The function returns the length of the data
1977    written to TO.  -1 is returned in case of error caused by malformed
1978    base64 input.
1979
1980    This function originates from Free Recode.  */
1981
1982 int
1983 base64_decode (const char *base64, void *dest)
1984 {
1985   /* Table of base64 values for first 128 characters.  Note that this
1986      assumes ASCII (but so does Wget in other places).  */
1987   static const signed char base64_char_to_value[128] =
1988     {
1989       -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  /*   0-  9 */
1990       -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  /*  10- 19 */
1991       -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  /*  20- 29 */
1992       -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  /*  30- 39 */
1993       -1,  -1,  -1,  62,  -1,  -1,  -1,  63,  52,  53,  /*  40- 49 */
1994       54,  55,  56,  57,  58,  59,  60,  61,  -1,  -1,  /*  50- 59 */
1995       -1,  -1,  -1,  -1,  -1,  0,   1,   2,   3,   4,   /*  60- 69 */
1996       5,   6,   7,   8,   9,   10,  11,  12,  13,  14,  /*  70- 79 */
1997       15,  16,  17,  18,  19,  20,  21,  22,  23,  24,  /*  80- 89 */
1998       25,  -1,  -1,  -1,  -1,  -1,  -1,  26,  27,  28,  /*  90- 99 */
1999       29,  30,  31,  32,  33,  34,  35,  36,  37,  38,  /* 100-109 */
2000       39,  40,  41,  42,  43,  44,  45,  46,  47,  48,  /* 110-119 */
2001       49,  50,  51,  -1,  -1,  -1,  -1,  -1             /* 120-127 */
2002     };
2003 #define BASE64_CHAR_TO_VALUE(c) ((int) base64_char_to_value[c])
2004 #define IS_BASE64(c) ((IS_ASCII (c) && BASE64_CHAR_TO_VALUE (c) >= 0) || c == '=')
2005
2006   const char *p = base64;
2007   char *q = dest;
2008
2009   while (1)
2010     {
2011       unsigned char c;
2012       unsigned long value;
2013
2014       /* Process first byte of a quadruplet.  */
2015       NEXT_CHAR (c, p);
2016       if (!c)
2017         break;
2018       if (c == '=' || !IS_BASE64 (c))
2019         return -1;              /* illegal char while decoding base64 */
2020       value = BASE64_CHAR_TO_VALUE (c) << 18;
2021
2022       /* Process second byte of a quadruplet.  */
2023       NEXT_CHAR (c, p);
2024       if (!c)
2025         return -1;              /* premature EOF while decoding base64 */
2026       if (c == '=' || !IS_BASE64 (c))
2027         return -1;              /* illegal char while decoding base64 */
2028       value |= BASE64_CHAR_TO_VALUE (c) << 12;
2029       *q++ = value >> 16;
2030
2031       /* Process third byte of a quadruplet.  */
2032       NEXT_CHAR (c, p);
2033       if (!c)
2034         return -1;              /* premature EOF while decoding base64 */
2035       if (!IS_BASE64 (c))
2036         return -1;              /* illegal char while decoding base64 */
2037
2038       if (c == '=')
2039         {
2040           NEXT_CHAR (c, p);
2041           if (!c)
2042             return -1;          /* premature EOF while decoding base64 */
2043           if (c != '=')
2044             return -1;          /* padding `=' expected but not found */
2045           continue;
2046         }
2047
2048       value |= BASE64_CHAR_TO_VALUE (c) << 6;
2049       *q++ = 0xff & value >> 8;
2050
2051       /* Process fourth byte of a quadruplet.  */
2052       NEXT_CHAR (c, p);
2053       if (!c)
2054         return -1;              /* premature EOF while decoding base64 */
2055       if (c == '=')
2056         continue;
2057       if (!IS_BASE64 (c))
2058         return -1;              /* illegal char while decoding base64 */
2059
2060       value |= BASE64_CHAR_TO_VALUE (c);
2061       *q++ = 0xff & value;
2062     }
2063 #undef IS_BASE64
2064 #undef BASE64_CHAR_TO_VALUE
2065
2066   return q - (char *) dest;
2067 }
2068
2069 #undef IS_ASCII
2070 #undef NEXT_CHAR
2071 \f
2072 /* Simple merge sort for use by stable_sort.  Implementation courtesy
2073    Zeljko Vrba with additional debugging by Nenad Barbutov.  */
2074
2075 static void
2076 mergesort_internal (void *base, void *temp, size_t size, size_t from, size_t to,
2077                     int (*cmpfun) (const void *, const void *))
2078 {
2079 #define ELT(array, pos) ((char *)(array) + (pos) * size)
2080   if (from < to)
2081     {
2082       size_t i, j, k;
2083       size_t mid = (to + from) / 2;
2084       mergesort_internal (base, temp, size, from, mid, cmpfun);
2085       mergesort_internal (base, temp, size, mid + 1, to, cmpfun);
2086       i = from;
2087       j = mid + 1;
2088       for (k = from; (i <= mid) && (j <= to); k++)
2089         if (cmpfun (ELT (base, i), ELT (base, j)) <= 0)
2090           memcpy (ELT (temp, k), ELT (base, i++), size);
2091         else
2092           memcpy (ELT (temp, k), ELT (base, j++), size);
2093       while (i <= mid)
2094         memcpy (ELT (temp, k++), ELT (base, i++), size);
2095       while (j <= to)
2096         memcpy (ELT (temp, k++), ELT (base, j++), size);
2097       for (k = from; k <= to; k++)
2098         memcpy (ELT (base, k), ELT (temp, k), size);
2099     }
2100 #undef ELT
2101 }
2102
2103 /* Stable sort with interface exactly like standard library's qsort.
2104    Uses mergesort internally, allocating temporary storage with
2105    alloca.  */
2106
2107 void
2108 stable_sort (void *base, size_t nmemb, size_t size,
2109              int (*cmpfun) (const void *, const void *))
2110 {
2111   if (size > 1)
2112     {
2113       void *temp = alloca (nmemb * size * sizeof (void *));
2114       mergesort_internal (base, temp, size, 0, nmemb - 1, cmpfun);
2115     }
2116 }
2117 \f
2118 /* Print a decimal number.  If it is equal to or larger than ten, the
2119    number is rounded.  Otherwise it is printed with one significant
2120    digit without trailing zeros and with no more than three fractional
2121    digits total.  For example, 0.1 is printed as "0.1", 0.035 is
2122    printed as "0.04", 0.0091 as "0.009", and 0.0003 as simply "0".
2123
2124    This is useful for displaying durations because it provides
2125    order-of-magnitude information without unnecessary clutter --
2126    long-running downloads are shown without the fractional part, and
2127    short ones still retain one significant digit.  */
2128
2129 const char *
2130 print_decimal (double number)
2131 {
2132   static char buf[32];
2133   double n = number >= 0 ? number : -number;
2134
2135   if (n >= 9.95)
2136     /* Cut off at 9.95 because the below %.1f would round 9.96 to
2137        "10.0" instead of "10".  OTOH 9.94 will print as "9.9".  */
2138     snprintf (buf, sizeof buf, "%.0f", number);
2139   else if (n >= 0.95)
2140     snprintf (buf, sizeof buf, "%.1f", number);
2141   else if (n >= 0.001)
2142     snprintf (buf, sizeof buf, "%.1g", number);
2143   else if (n >= 0.0005)
2144     /* round [0.0005, 0.001) to 0.001 */
2145     snprintf (buf, sizeof buf, "%.3f", number);
2146   else
2147     /* print numbers close to 0 as 0, not 0.000 */
2148     strcpy (buf, "0");
2149
2150   return buf;
2151 }
2152
2153 #ifdef TESTING
2154
2155 const char *
2156 test_subdir_p()
2157 {
2158   int i;
2159   struct {
2160     char *d1;
2161     char *d2;
2162     bool result;
2163   } test_array[] = {
2164     { "/somedir", "/somedir", true },
2165     { "/somedir", "/somedir/d2", true },
2166     { "/somedir/d1", "/somedir", false },
2167   };
2168   
2169   for (i = 0; i < countof(test_array); ++i) 
2170     {
2171       bool res = subdir_p (test_array[i].d1, test_array[i].d2);
2172
2173       mu_assert ("test_subdir_p: wrong result", 
2174                  res == test_array[i].result);
2175     }
2176
2177   return NULL;
2178 }
2179
2180 const char *
2181 test_dir_matches_p()
2182 {
2183   int i;
2184   struct {
2185     char *dirlist[3];
2186     char *dir;
2187     bool result;
2188   } test_array[] = {
2189     { { "/somedir", "/someotherdir", NULL }, "somedir", true },
2190     { { "/somedir", "/someotherdir", NULL }, "anotherdir", false },
2191     { { "/somedir", "/*otherdir", NULL }, "anotherdir", true },
2192     { { "/somedir/d1", "/someotherdir", NULL }, "somedir/d1", true },
2193     { { "*/*d1", "/someotherdir", NULL }, "somedir/d1", true },
2194     { { "/somedir/d1", "/someotherdir", NULL }, "d1", false },
2195     { { "!COMPLETE", NULL, NULL }, "!COMPLETE", true },
2196     { { "*COMPLETE", NULL, NULL }, "!COMPLETE", true },
2197     { { "*/!COMPLETE", NULL, NULL }, "foo/!COMPLETE", true },
2198     { { "*COMPLETE", NULL, NULL }, "foo/!COMPLETE", false },
2199     { { "*/*COMPLETE", NULL, NULL }, "foo/!COMPLETE", true },
2200     { { "/dir with spaces", NULL, NULL }, "dir with spaces", true },
2201     { { "/dir*with*spaces", NULL, NULL }, "dir with spaces", true },
2202   };
2203   
2204   for (i = 0; i < countof(test_array); ++i) 
2205     {
2206       bool res = dir_matches_p (test_array[i].dirlist, test_array[i].dir);
2207       
2208       mu_assert ("test_dir_matches_p: wrong result", 
2209                  res == test_array[i].result);
2210     }
2211
2212   return NULL;
2213 }
2214
2215 #endif /* TESTING */
2216