]> sjero.net Git - wget/blob - src/init.c
[svn] New option `--limit-rate'.
[wget] / src / init.c
1 /* Reading/parsing the initialization file.
2    Copyright (C) 1995, 1996, 1997, 1998, 2000, 2001
3    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 2 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, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21 #include <config.h>
22
23 #include <stdio.h>
24 #include <sys/types.h>
25 #include <stdlib.h>
26 #ifdef HAVE_UNISTD_H
27 # include <unistd.h>
28 #endif
29 #ifdef HAVE_STRING_H
30 # include <string.h>
31 #else
32 # include <strings.h>
33 #endif
34 #include <errno.h>
35
36 #ifdef WINDOWS
37 # include <winsock.h>
38 #else
39 # include <sys/socket.h>
40 # include <netinet/in.h>
41 #ifndef __BEOS__
42 # include <arpa/inet.h>
43 #endif
44 #endif
45
46 #ifdef HAVE_PWD_H
47 #include <pwd.h>
48 #endif
49
50 #include "wget.h"
51 #include "utils.h"
52 #include "init.h"
53 #include "host.h"
54 #include "recur.h"
55 #include "netrc.h"
56 #include "cookies.h"            /* for cookies_cleanup */
57
58 #ifndef errno
59 extern int errno;
60 #endif
61
62 /* We want tilde expansion enabled only when reading `.wgetrc' lines;
63    otherwise, it will be performed by the shell.  This variable will
64    be set by the wgetrc-reading function.  */
65
66 static int enable_tilde_expansion;
67
68
69 #define CMD_DECLARE(func) static int func \
70   PARAMS ((const char *, const char *, void *))
71
72 CMD_DECLARE (cmd_address);
73 CMD_DECLARE (cmd_boolean);
74 CMD_DECLARE (cmd_bytes);
75 CMD_DECLARE (cmd_directory_vector);
76 CMD_DECLARE (cmd_lockable_boolean);
77 CMD_DECLARE (cmd_number);
78 CMD_DECLARE (cmd_number_inf);
79 CMD_DECLARE (cmd_string);
80 CMD_DECLARE (cmd_file);
81 CMD_DECLARE (cmd_time);
82 CMD_DECLARE (cmd_vector);
83
84 CMD_DECLARE (cmd_spec_dirstruct);
85 CMD_DECLARE (cmd_spec_header);
86 CMD_DECLARE (cmd_spec_htmlify);
87 CMD_DECLARE (cmd_spec_mirror);
88 /*CMD_DECLARE (cmd_spec_progress);*/
89 CMD_DECLARE (cmd_spec_recursive);
90 CMD_DECLARE (cmd_spec_useragent);
91
92 /* List of recognized commands, each consisting of name, closure and function.
93    When adding a new command, simply add it to the list, but be sure to keep the
94    list sorted alphabetically, as comind() depends on it.  Also, be sure to add
95    any entries that allocate memory (e.g. cmd_string and cmd_vector guys) to the
96    cleanup() function below. */
97 static struct {
98   char *name;
99   void *closure;
100   int (*action) PARAMS ((const char *, const char *, void *));
101 } commands[] = {
102   { "accept",           &opt.accepts,           cmd_vector },
103   { "addhostdir",       &opt.add_hostdir,       cmd_boolean },
104   { "alwaysrest",       &opt.always_rest,       cmd_boolean }, /* deprecated */
105   { "background",       &opt.background,        cmd_boolean },
106   { "backupconverted",  &opt.backup_converted,  cmd_boolean },
107   { "backups",          &opt.backups,           cmd_number },
108   { "base",             &opt.base_href,         cmd_string },
109   { "bindaddress",      &opt.bind_address,      cmd_address },
110   { "cache",            &opt.allow_cache,       cmd_boolean },
111   { "continue",         &opt.always_rest,       cmd_boolean },
112   { "convertlinks",     &opt.convert_links,     cmd_boolean },
113   { "cookies",          &opt.cookies,           cmd_boolean },
114   { "cutdirs",          &opt.cut_dirs,          cmd_number },
115 #ifdef DEBUG
116   { "debug",            &opt.debug,             cmd_boolean },
117 #endif
118   { "deleteafter",      &opt.delete_after,      cmd_boolean },
119   { "dirprefix",        &opt.dir_prefix,        cmd_file },
120   { "dirstruct",        NULL,                   cmd_spec_dirstruct },
121   { "domains",          &opt.domains,           cmd_vector },
122   { "dotbytes",         &opt.dot_bytes,         cmd_bytes },
123   { "dotsinline",       &opt.dots_in_line,      cmd_number },
124   { "dotspacing",       &opt.dot_spacing,       cmd_number },
125   { "excludedirectories", &opt.excludes,        cmd_directory_vector },
126   { "excludedomains",   &opt.exclude_domains,   cmd_vector },
127   { "followftp",        &opt.follow_ftp,        cmd_boolean },
128   { "followtags",       &opt.follow_tags,       cmd_vector },
129   { "forcehtml",        &opt.force_html,        cmd_boolean },
130   { "ftpproxy",         &opt.ftp_proxy,         cmd_string },
131   { "glob",             &opt.ftp_glob,          cmd_boolean },
132   { "header",           NULL,                   cmd_spec_header },
133   { "htmlextension",    &opt.html_extension,    cmd_boolean },
134   { "htmlify",          NULL,                   cmd_spec_htmlify },
135   { "httpkeepalive",    &opt.http_keep_alive,   cmd_boolean },
136   { "httppasswd",       &opt.http_passwd,       cmd_string },
137   { "httpproxy",        &opt.http_proxy,        cmd_string },
138   { "httpsproxy",       &opt.https_proxy,       cmd_string },
139   { "httpuser",         &opt.http_user,         cmd_string },
140   { "ignorelength",     &opt.ignore_length,     cmd_boolean },
141   { "ignoretags",       &opt.ignore_tags,       cmd_vector },
142   { "includedirectories", &opt.includes,        cmd_directory_vector },
143   { "input",            &opt.input_filename,    cmd_file },
144   { "killlonger",       &opt.kill_longer,       cmd_boolean },
145   { "limitrate",        &opt.limit_rate,        cmd_bytes },
146   { "loadcookies",      &opt.cookies_input,     cmd_file },
147   { "logfile",          &opt.lfilename,         cmd_file },
148   { "login",            &opt.ftp_acc,           cmd_string },
149   { "mirror",           NULL,                   cmd_spec_mirror },
150   { "netrc",            &opt.netrc,             cmd_boolean },
151   { "noclobber",        &opt.noclobber,         cmd_boolean },
152   { "noparent",         &opt.no_parent,         cmd_boolean },
153   { "noproxy",          &opt.no_proxy,          cmd_vector },
154   { "numtries",         &opt.ntry,              cmd_number_inf },/* deprecated*/
155   { "outputdocument",   &opt.output_document,   cmd_file },
156   { "pagerequisites",   &opt.page_requisites,   cmd_boolean },
157   { "passiveftp",       &opt.ftp_pasv,          cmd_lockable_boolean },
158   { "passwd",           &opt.ftp_pass,          cmd_string },
159   { "progress",         &opt.progress_type,     cmd_string },
160   { "proxypasswd",      &opt.proxy_passwd,      cmd_string },
161   { "proxyuser",        &opt.proxy_user,        cmd_string },
162   { "quiet",            &opt.quiet,             cmd_boolean },
163   { "quota",            &opt.quota,             cmd_bytes },
164   { "randomwait",       &opt.random_wait,       cmd_boolean },
165   { "reclevel",         &opt.reclevel,          cmd_number_inf },
166   { "recursive",        NULL,                   cmd_spec_recursive },
167   { "referer",          &opt.referer,           cmd_string },
168   { "reject",           &opt.rejects,           cmd_vector },
169   { "relativeonly",     &opt.relative_only,     cmd_boolean },
170   { "removelisting",    &opt.remove_listing,    cmd_boolean },
171   { "retrsymlinks",     &opt.retr_symlinks,     cmd_boolean },
172   { "robots",           &opt.use_robots,        cmd_boolean },
173   { "savecookies",      &opt.cookies_output,    cmd_file },
174   { "saveheaders",      &opt.save_headers,      cmd_boolean },
175   { "serverresponse",   &opt.server_response,   cmd_boolean },
176   { "spanhosts",        &opt.spanhost,          cmd_boolean },
177   { "spider",           &opt.spider,            cmd_boolean },
178 #ifdef HAVE_SSL
179   { "sslcertfile",      &opt.sslcertfile,       cmd_file },
180   { "sslcertkey",       &opt.sslcertkey,        cmd_file },
181 #endif /* HAVE_SSL */
182   { "timeout",          &opt.timeout,           cmd_time },
183   { "timestamping",     &opt.timestamping,      cmd_boolean },
184   { "tries",            &opt.ntry,              cmd_number_inf },
185   { "useproxy",         &opt.use_proxy,         cmd_boolean },
186   { "useragent",        NULL,                   cmd_spec_useragent },
187   { "verbose",          &opt.verbose,           cmd_boolean },
188   { "wait",             &opt.wait,              cmd_time },
189   { "waitretry",        &opt.waitretry,         cmd_time }
190 };
191
192 /* Return index of COM if it is a valid command, or -1 otherwise.  COM
193    is looked up in `commands' using binary search algorithm.  */
194 static int
195 comind (const char *com)
196 {
197   int min = 0, max = ARRAY_SIZE (commands) - 1;
198
199   do
200     {
201       int i = (min + max) / 2;
202       int cmp = strcasecmp (com, commands[i].name);
203       if (cmp == 0)
204         return i;
205       else if (cmp < 0)
206         max = i - 1;
207       else
208         min = i + 1;
209     }
210   while (min <= max);
211   return -1;
212 }
213 \f
214 /* Reset the variables to default values.  */
215 static void
216 defaults (void)
217 {
218   char *tmp;
219
220   /* Most of the default values are 0.  Just reset everything, and
221      fill in the non-zero values.  Note that initializing pointers to
222      NULL this way is technically illegal, but porting Wget to a
223      machine where NULL is not all-zero bit pattern will be the least
224      of the implementors' worries.  */
225   memset (&opt, 0, sizeof (opt));
226
227   opt.cookies = 1;
228
229   opt.verbose = -1;
230   opt.dir_prefix = xstrdup (".");
231   opt.ntry = 20;
232   opt.reclevel = 5;
233   opt.add_hostdir = 1;
234   opt.ftp_acc  = xstrdup ("anonymous");
235   opt.ftp_pass = xstrdup ("-wget@");
236   opt.netrc = 1;
237   opt.ftp_glob = 1;
238   opt.htmlify = 1;
239   opt.http_keep_alive = 1;
240   opt.use_proxy = 1;
241   tmp = getenv ("no_proxy");
242   if (tmp)
243     opt.no_proxy = sepstring (tmp);
244   opt.allow_cache = 1;
245
246 #ifdef HAVE_SELECT
247   opt.timeout = 900;
248 #endif
249   opt.use_robots = 1;
250
251   opt.remove_listing = 1;
252
253   opt.dot_bytes = 1024;
254   opt.dot_spacing = 10;
255   opt.dots_in_line = 50;
256 }
257 \f
258 /* Return the user's home directory (strdup-ed), or NULL if none is
259    found.  */
260 char *
261 home_dir (void)
262 {
263   char *home = getenv ("HOME");
264
265   if (!home)
266     {
267 #ifndef WINDOWS
268       /* If HOME is not defined, try getting it from the password
269          file.  */
270       struct passwd *pwd = getpwuid (getuid ());
271       if (!pwd || !pwd->pw_dir)
272         return NULL;
273       home = pwd->pw_dir;
274 #else  /* WINDOWS */
275       home = "C:\\";
276       /* #### Maybe I should grab home_dir from registry, but the best
277          that I could get from there is user's Start menu.  It sucks!  */
278 #endif /* WINDOWS */
279     }
280
281   return home ? xstrdup (home) : NULL;
282 }
283
284 /* Return the path to the user's .wgetrc.  This is either the value of
285    `WGETRC' environment variable, or `$HOME/.wgetrc'.
286
287    If the `WGETRC' variable exists but the file does not exist, the
288    function will exit().  */
289 static char *
290 wgetrc_file_name (void)
291 {
292   char *env, *home;
293   char *file = NULL;
294
295   /* Try the environment.  */
296   env = getenv ("WGETRC");
297   if (env && *env)
298     {
299       if (!file_exists_p (env))
300         {
301           fprintf (stderr, "%s: %s: %s.\n", exec_name, file, strerror (errno));
302           exit (1);
303         }
304       return xstrdup (env);
305     }
306
307 #ifndef WINDOWS
308   /* If that failed, try $HOME/.wgetrc.  */
309   home = home_dir ();
310   if (home)
311     {
312       file = (char *)xmalloc (strlen (home) + 1 + strlen (".wgetrc") + 1);
313       sprintf (file, "%s/.wgetrc", home);
314     }
315   FREE_MAYBE (home);
316 #else  /* WINDOWS */
317   /* Under Windows, "home" is (for the purposes of this function) the
318      directory where `wget.exe' resides, and `wget.ini' will be used
319      as file name.  SYSTEM_WGETRC should not be defined under WINDOWS.
320
321      It is not as trivial as I assumed, because on 95 argv[0] is full
322      path, but on NT you get what you typed in command line.  --dbudor */
323   home = ws_mypath ();
324   if (home)
325     {
326       file = (char *)xmalloc (strlen (home) + strlen ("wget.ini") + 1);
327       sprintf (file, "%swget.ini", home);
328     }
329 #endif /* WINDOWS */
330
331   if (!file)
332     return NULL;
333   if (!file_exists_p (file))
334     {
335       xfree (file);
336       return NULL;
337     }
338   return file;
339 }
340
341 /* Initialize variables from a wgetrc file */
342 static void
343 run_wgetrc (const char *file)
344 {
345   FILE *fp;
346   char *line;
347   int ln;
348
349   fp = fopen (file, "rb");
350   if (!fp)
351     {
352       fprintf (stderr, _("%s: Cannot read %s (%s).\n"), exec_name,
353                file, strerror (errno));
354       return;
355     }
356   enable_tilde_expansion = 1;
357   ln = 1;
358   while ((line = read_whole_line (fp)))
359     {
360       char *com, *val;
361       int status;
362
363       /* Parse the line.  */
364       status = parse_line (line, &com, &val);
365       xfree (line);
366       /* If everything is OK, set the value.  */
367       if (status == 1)
368         {
369           if (!setval (com, val))
370             fprintf (stderr, _("%s: Error in %s at line %d.\n"), exec_name,
371                      file, ln);
372           xfree (com);
373           xfree (val);
374         }
375       else if (status == 0)
376         fprintf (stderr, _("%s: Error in %s at line %d.\n"), exec_name,
377                  file, ln);
378       ++ln;
379     }
380   enable_tilde_expansion = 0;
381   fclose (fp);
382 }
383
384 /* Initialize the defaults and run the system wgetrc and user's own
385    wgetrc.  */
386 void
387 initialize (void)
388 {
389   char *file;
390
391   /* Load the hard-coded defaults.  */
392   defaults ();
393
394   /* If SYSTEM_WGETRC is defined, use it.  */
395 #ifdef SYSTEM_WGETRC
396   if (file_exists_p (SYSTEM_WGETRC))
397     run_wgetrc (SYSTEM_WGETRC);
398 #endif
399   /* Override it with your own, if one exists.  */
400   file = wgetrc_file_name ();
401   if (!file)
402     return;
403   /* #### We should somehow canonicalize `file' and SYSTEM_WGETRC,
404      really.  */
405 #ifdef SYSTEM_WGETRC
406   if (!strcmp (file, SYSTEM_WGETRC))
407     {
408       fprintf (stderr, _("\
409 %s: Warning: Both system and user wgetrc point to `%s'.\n"),
410                exec_name, file);
411     }
412   else
413 #endif
414     run_wgetrc (file);
415   xfree (file);
416   return;
417 }
418 \f
419 /* Parse the line pointed by line, with the syntax:
420    <sp>* command <sp>* = <sp>* value <newline>
421    Uses malloc to allocate space for command and value.
422    If the line is invalid, data is freed and 0 is returned.
423
424    Return values:
425     1 - success
426     0 - failure
427    -1 - empty */
428 int
429 parse_line (const char *line, char **com, char **val)
430 {
431   const char *p = line;
432   const char *orig_comptr, *end;
433   char *new_comptr;
434
435   /* Skip whitespace.  */
436   while (*p && ISSPACE (*p))
437     ++p;
438
439   /* Don't process empty lines.  */
440   if (!*p || *p == '#')
441     return -1;
442
443   for (orig_comptr = p; ISALPHA (*p) || *p == '_' || *p == '-'; p++)
444     ;
445   /* The next char should be space or '='.  */
446   if (!ISSPACE (*p) && (*p != '='))
447     return 0;
448   /* Here we cannot use strdupdelim() as we normally would because we
449      want to skip the `-' and `_' characters in the input string.  */
450   *com = (char *)xmalloc (p - orig_comptr + 1);
451   for (new_comptr = *com; orig_comptr < p; orig_comptr++)
452     {
453       if (*orig_comptr == '_' || *orig_comptr == '-')
454         continue;
455       *new_comptr++ = *orig_comptr;
456     }
457   *new_comptr = '\0';
458   /* If the command is invalid, exit now.  */
459   if (comind (*com) == -1)
460     {
461       xfree (*com);
462       return 0;
463     }
464
465   /* Skip spaces before '='.  */
466   for (; ISSPACE (*p); p++);
467   /* If '=' not found, bail out.  */
468   if (*p != '=')
469     {
470       xfree (*com);
471       return 0;
472     }
473   /* Skip spaces after '='.  */
474   for (++p; ISSPACE (*p); p++);
475   /* Get the ending position for VAL by starting with the end of the
476      line and skipping whitespace.  */
477   end = line + strlen (line) - 1;
478   while (end > p && ISSPACE (*end))
479     --end;
480   *val = strdupdelim (p, end + 1);
481   return 1;
482 }
483
484 /* Set COM to VAL.  This is the meat behind processing `.wgetrc'.  No
485    fatals -- error signal prints a warning and resets to default
486    value.  All error messages are printed to stderr, *not* to
487    opt.lfile, since opt.lfile wasn't even generated yet.  */
488 int
489 setval (const char *com, const char *val)
490 {
491   int ind;
492
493   if (!com || !val)
494     return 0;
495   ind = comind (com);
496   if (ind == -1)
497     {
498       /* #### Should I just abort()?  */
499 #ifdef DEBUG
500       fprintf (stderr, _("%s: BUG: unknown command `%s', value `%s'.\n"),
501                exec_name, com, val);
502 #endif
503       return 0;
504     }
505   return ((*commands[ind].action) (com, val, commands[ind].closure));
506 }
507 \f
508 /* Generic helper functions, for use with `commands'. */
509
510 static int myatoi PARAMS ((const char *s));
511
512 /* Interpret VAL as an Internet address (a hostname or a dotted-quad
513    IP address), and write it (in network order) to a malloc-allocated
514    address.  That address gets stored to the memory pointed to by
515    CLOSURE.  COM is ignored, except for error messages.
516
517    #### IMHO it's a mistake to do this kind of work so early in the
518    process (before any download even started!)  opt.bind_address
519    should simply remember the provided value as a string.  Another
520    function should do the lookup, when needed, and cache the
521    result.  --hniksic  */
522 static int
523 cmd_address (const char *com, const char *val, void *closure)
524 {
525   struct address_list *al;
526   struct sockaddr_in sin;
527   struct sockaddr_in **target = (struct sockaddr_in **)closure;
528
529   memset (&sin, '\0', sizeof (sin));
530
531   al = lookup_host (val, 1);
532   if (!al)
533     {
534       fprintf (stderr, _("%s: %s: Cannot convert `%s' to an IP address.\n"),
535                exec_name, com, val);
536       return 0;
537     }
538   address_list_copy_one (al, 0, (unsigned char *)&sin.sin_addr);
539   address_list_release (al);
540
541   sin.sin_family = AF_INET;
542   sin.sin_port = 0;
543
544   FREE_MAYBE (*target);
545
546   *target = xmalloc (sizeof (sin));
547   memcpy (*target, &sin, sizeof (sin));
548
549   return 1;
550 }
551
552 /* Store the boolean value from VAL to CLOSURE.  COM is ignored,
553    except for error messages.  */
554 static int
555 cmd_boolean (const char *com, const char *val, void *closure)
556 {
557   int bool_value;
558
559   if (!strcasecmp (val, "on")
560       || (*val == '1' && !*(val + 1)))
561     bool_value = 1;
562   else if (!strcasecmp (val, "off")
563            || (*val == '0' && !*(val + 1)))
564     bool_value = 0;
565   else
566     {
567       fprintf (stderr, _("%s: %s: Please specify on or off.\n"),
568                exec_name, com);
569       return 0;
570     }
571
572   *(int *)closure = bool_value;
573   return 1;
574 }
575
576 /* Store the lockable_boolean {2, 1, 0, -1} value from VAL to CLOSURE.  COM is
577    ignored, except for error messages.  Values 2 and -1 indicate that once
578    defined, the value may not be changed by successive wgetrc files or
579    command-line arguments.
580
581    Values: 2 - Enable a particular option for good ("always")
582            1 - Enable an option ("on")
583            0 - Disable an option ("off")
584           -1 - Disable an option for good ("never") */
585 static int
586 cmd_lockable_boolean (const char *com, const char *val, void *closure)
587 {
588   int lockable_boolean_value;
589
590   /*
591    * If a config file said "always" or "never", don't allow command line
592    * arguments to override the config file.
593    */
594   if (*(int *)closure == -1 || *(int *)closure == 2)
595     return 1;
596
597   if (!strcasecmp (val, "always")
598       || (*val == '2' && !*(val + 1)))
599     lockable_boolean_value = 2;
600   else if (!strcasecmp (val, "on")
601       || (*val == '1' && !*(val + 1)))
602     lockable_boolean_value = 1;
603   else if (!strcasecmp (val, "off")
604           || (*val == '0' && !*(val + 1)))
605     lockable_boolean_value = 0;
606   else if (!strcasecmp (val, "never")
607       || (*val == '-' && *(val + 1) == '1' && !*(val + 2)))
608     lockable_boolean_value = -1;
609   else
610     {
611       fprintf (stderr, _("%s: %s: Please specify always, on, off, "
612                          "or never.\n"),
613                exec_name, com);
614       return 0;
615     }
616
617   *(int *)closure = lockable_boolean_value;
618   return 1;
619 }
620
621 /* Set the non-negative integer value from VAL to CLOSURE.  With
622    incorrect specification, the number remains unchanged.  */
623 static int
624 cmd_number (const char *com, const char *val, void *closure)
625 {
626   int num = myatoi (val);
627
628   if (num == -1)
629     {
630       fprintf (stderr, _("%s: %s: Invalid specification `%s'.\n"),
631                exec_name, com, val);
632       return 0;
633     }
634   *(int *)closure = num;
635   return 1;
636 }
637
638 /* Similar to cmd_number(), only accepts `inf' as a synonym for 0.  */
639 static int
640 cmd_number_inf (const char *com, const char *val, void *closure)
641 {
642   if (!strcasecmp (val, "inf"))
643     {
644       *(int *)closure = 0;
645       return 1;
646     }
647   return cmd_number (com, val, closure);
648 }
649
650 /* Copy (strdup) the string at COM to a new location and place a
651    pointer to *CLOSURE.  */
652 static int
653 cmd_string (const char *com, const char *val, void *closure)
654 {
655   char **pstring = (char **)closure;
656
657   FREE_MAYBE (*pstring);
658   *pstring = xstrdup (val);
659   return 1;
660 }
661
662 /* Like the above, but handles tilde-expansion when reading a user's
663    `.wgetrc'.  In that case, and if VAL begins with `~', the tilde
664    gets expanded to the user's home directory.  */
665 static int
666 cmd_file (const char *com, const char *val, void *closure)
667 {
668   char **pstring = (char **)closure;
669
670   FREE_MAYBE (*pstring);
671   if (!enable_tilde_expansion || !(*val == '~' && *(val + 1) == '/'))
672     {
673     noexpand:
674       *pstring = xstrdup (val);
675     }
676   else
677     {
678       char *result;
679       int homelen;
680       char *home = home_dir ();
681       if (!home)
682         goto noexpand;
683
684       homelen = strlen (home);
685       while (homelen && home[homelen - 1] == '/')
686         home[--homelen] = '\0';
687
688       /* Skip the leading "~/". */
689       for (++val; *val == '/'; val++)
690         ;
691
692       result = xmalloc (homelen + 1 + strlen (val));
693       memcpy (result, home, homelen);
694       result[homelen] = '/';
695       strcpy (result + homelen + 1, val);
696
697       *pstring = result;
698     }
699   return 1;
700 }
701
702 /* Merge the vector (array of strings separated with `,') in COM with
703    the vector (NULL-terminated array of strings) pointed to by
704    CLOSURE.  */
705 static int
706 cmd_vector (const char *com, const char *val, void *closure)
707 {
708   char ***pvec = (char ***)closure;
709
710   if (*val)
711     *pvec = merge_vecs (*pvec, sepstring (val));
712   else
713     {
714       free_vec (*pvec);
715       *pvec = NULL;
716     }
717   return 1;
718 }
719
720 static int
721 cmd_directory_vector (const char *com, const char *val, void *closure)
722 {
723   char ***pvec = (char ***)closure;
724
725   if (*val)
726     {
727       /* Strip the trailing slashes from directories.  */
728       char **t, **seps;
729
730       seps = sepstring (val);
731       for (t = seps; t && *t; t++)
732         {
733           int len = strlen (*t);
734           /* Skip degenerate case of root directory.  */
735           if (len > 1)
736             {
737               if ((*t)[len - 1] == '/')
738                 (*t)[len - 1] = '\0';
739             }
740         }
741       *pvec = merge_vecs (*pvec, seps);
742     }
743   else
744     {
745       free_vec (*pvec);
746       *pvec = NULL;
747     }
748   return 1;
749 }
750
751 /* Set the value stored in VAL to CLOSURE (which should point to a
752    long int), allowing several postfixes, with the following syntax
753    (regexp):
754
755    [0-9]+       -> bytes
756    [0-9]+[kK]   -> bytes * 1024
757    [0-9]+[mM]   -> bytes * 1024 * 1024
758    inf          -> 0
759
760    Anything else is flagged as incorrect, and CLOSURE is unchanged.  */
761 static int
762 cmd_bytes (const char *com, const char *val, void *closure)
763 {
764   long result;
765   long *out = (long *)closure;
766   const char *p;
767
768   result = 0;
769   p = val;
770   /* Check for "inf".  */
771   if (p[0] == 'i' && p[1] == 'n' && p[2] == 'f' && p[3] == '\0')
772     {
773       *out = 0;
774       return 1;
775     }
776   /* Search for digits and construct result.  */
777   for (; *p && ISDIGIT (*p); p++)
778     result = (10 * result) + (*p - '0');
779   /* If no digits were found, or more than one character is following
780      them, bail out.  */
781   if (p == val || (*p != '\0' && *(p + 1) != '\0'))
782     {
783       printf (_("%s: Invalid specification `%s'\n"), com, val);
784       return 0;
785     }
786   /* Search for a designator.  */
787   switch (TOLOWER (*p))
788     {
789     case '\0':
790       /* None */
791       break;
792     case 'k':
793       /* Kilobytes */
794       result *= 1024;
795       break;
796     case 'm':
797       /* Megabytes */
798       result *= (long)1024 * 1024;
799       break;
800     case 'g':
801       /* Gigabytes */
802       result *= (long)1024 * 1024 * 1024;
803       break;
804     default:
805       printf (_("%s: Invalid specification `%s'\n"), com, val);
806       return 0;
807     }
808   *out = result;
809   return 1;
810 }
811
812 /* Store the value of VAL to *OUT, allowing suffixes for minutes and
813    hours.  */
814 static int
815 cmd_time (const char *com, const char *val, void *closure)
816 {
817   long result = 0;
818   const char *p = val;
819
820   /* Search for digits and construct result.  */
821   for (; *p && ISDIGIT (*p); p++)
822     result = (10 * result) + (*p - '0');
823   /* If no digits were found, or more than one character is following
824      them, bail out.  */
825   if (p == val || (*p != '\0' && *(p + 1) != '\0'))
826     {
827       printf (_("%s: Invalid specification `%s'\n"), com, val);
828       return 0;
829     }
830   /* Search for a suffix.  */
831   switch (TOLOWER (*p))
832     {
833     case '\0':
834       /* None */
835       break;
836     case 'm':
837       /* Minutes */
838       result *= 60;
839       break;
840     case 'h':
841       /* Seconds */
842       result *= 3600;
843       break;
844     case 'd':
845       /* Days (overflow on 16bit machines) */
846       result *= 86400L;
847       break;
848     case 'w':
849       /* Weeks :-) */
850       result *= 604800L;
851       break;
852     default:
853       printf (_("%s: Invalid specification `%s'\n"), com, val);
854       return 0;
855     }
856   *(long *)closure = result;
857   return 1;
858 }
859 \f
860 /* Specialized helper functions, used by `commands' to handle some
861    options specially.  */
862
863 static int check_user_specified_header PARAMS ((const char *));
864
865 static int
866 cmd_spec_dirstruct (const char *com, const char *val, void *closure)
867 {
868   if (!cmd_boolean (com, val, &opt.dirstruct))
869     return 0;
870   /* Since dirstruct behaviour is explicitly changed, no_dirstruct
871      must be affected inversely.  */
872   if (opt.dirstruct)
873     opt.no_dirstruct = 0;
874   else
875     opt.no_dirstruct = 1;
876   return 1;
877 }
878
879 static int
880 cmd_spec_header (const char *com, const char *val, void *closure)
881 {
882   if (!*val)
883     {
884       /* Empty header means reset headers.  */
885       FREE_MAYBE (opt.user_header);
886       opt.user_header = NULL;
887     }
888   else
889     {
890       int i;
891
892       if (!check_user_specified_header (val))
893         {
894           fprintf (stderr, _("%s: %s: Invalid specification `%s'.\n"),
895                    exec_name, com, val);
896           return 0;
897         }
898       i = opt.user_header ? strlen (opt.user_header) : 0;
899       opt.user_header = (char *)xrealloc (opt.user_header, i + strlen (val)
900                                           + 2 + 1);
901       strcpy (opt.user_header + i, val);
902       i += strlen (val);
903       opt.user_header[i++] = '\r';
904       opt.user_header[i++] = '\n';
905       opt.user_header[i] = '\0';
906     }
907   return 1;
908 }
909
910 static int
911 cmd_spec_htmlify (const char *com, const char *val, void *closure)
912 {
913   int flag = cmd_boolean (com, val, &opt.htmlify);
914   if (flag && !opt.htmlify)
915     opt.remove_listing = 0;
916   return flag;
917 }
918
919 static int
920 cmd_spec_mirror (const char *com, const char *val, void *closure)
921 {
922   int mirror;
923
924   if (!cmd_boolean (com, val, &mirror))
925     return 0;
926   if (mirror)
927     {
928       opt.recursive = 1;
929       if (!opt.no_dirstruct)
930         opt.dirstruct = 1;
931       opt.timestamping = 1;
932       opt.reclevel = INFINITE_RECURSION;
933       opt.remove_listing = 0;
934     }
935   return 1;
936 }
937
938 #if 0
939 static int
940 cmd_spec_progress (const char *com, const char *val, void *closure)
941 {
942   if (!valid_progress_implementation_p (val))
943     {
944       fprintf (stderr, _("%s: %s: Invalid progress type `%s'.\n"),
945                exec_name, com, val);
946       return 0;
947     }
948   set_progress_implementation (val);
949   return 1;
950 }
951 #endif
952
953 static int
954 cmd_spec_recursive (const char *com, const char *val, void *closure)
955 {
956   if (!cmd_boolean (com, val, &opt.recursive))
957     return 0;
958   else
959     {
960       if (opt.recursive && !opt.no_dirstruct)
961         opt.dirstruct = 1;
962     }
963   return 1;
964 }
965
966 static int
967 cmd_spec_useragent (const char *com, const char *val, void *closure)
968 {
969   /* Just check for empty string and newline, so we don't throw total
970      junk to the server.  */
971   if (!*val || strchr (val, '\n'))
972     {
973       fprintf (stderr, _("%s: %s: Invalid specification `%s'.\n"),
974                exec_name, com, val);
975       return 0;
976     }
977   opt.useragent = xstrdup (val);
978   return 1;
979 }
980 \f
981 /* Miscellaneous useful routines.  */
982
983 /* Return the integer value of a positive integer written in S, or -1
984    if an error was encountered.  */
985 static int
986 myatoi (const char *s)
987 {
988   int res;
989   const char *orig = s;
990
991   for (res = 0; *s && ISDIGIT (*s); s++)
992     res = 10 * res + (*s - '0');
993   if (*s || orig == s)
994     return -1;
995   else
996     return res;
997 }
998
999 #define ISODIGIT(x) ((x) >= '0' && (x) <= '7')
1000
1001 static int
1002 check_user_specified_header (const char *s)
1003 {
1004   const char *p;
1005
1006   for (p = s; *p && *p != ':' && !ISSPACE (*p); p++);
1007   /* The header MUST contain `:' preceded by at least one
1008      non-whitespace character.  */
1009   if (*p != ':' || p == s)
1010     return 0;
1011   /* The header MUST NOT contain newlines.  */
1012   if (strchr (s, '\n'))
1013     return 0;
1014   return 1;
1015 }
1016 \f
1017 void cleanup_html_url PARAMS ((void));
1018 void res_cleanup PARAMS ((void));
1019 void downloaded_files_free PARAMS ((void));
1020 void http_cleanup PARAMS ((void));
1021
1022
1023 /* Free the memory allocated by global variables.  */
1024 void
1025 cleanup (void)
1026 {
1027   /* Free external resources, close files, etc. */
1028
1029   if (opt.dfp)
1030     fclose (opt.dfp);
1031
1032   /* We're exiting anyway so there's no real need to call free()
1033      hundreds of times.  Skipping the frees will make Wget exit
1034      faster.
1035
1036      However, when detecting leaks, it's crucial to free() everything
1037      because then you can find the real leaks, i.e. the allocated
1038      memory which grows with the size of the program.  */
1039
1040 #ifdef DEBUG_MALLOC
1041   recursive_cleanup ();
1042   res_cleanup ();
1043   http_cleanup ();
1044   cleanup_html_url ();
1045   downloaded_files_free ();
1046   cookies_cleanup ();
1047   host_cleanup ();
1048
1049   {
1050     extern acc_t *netrc_list;
1051     free_netrc (netrc_list);
1052   }
1053   FREE_MAYBE (opt.lfilename);
1054   xfree (opt.dir_prefix);
1055   FREE_MAYBE (opt.input_filename);
1056   FREE_MAYBE (opt.output_document);
1057   free_vec (opt.accepts);
1058   free_vec (opt.rejects);
1059   free_vec (opt.excludes);
1060   free_vec (opt.includes);
1061   free_vec (opt.domains);
1062   free_vec (opt.follow_tags);
1063   free_vec (opt.ignore_tags);
1064   FREE_MAYBE (opt.progress_type);
1065   xfree (opt.ftp_acc);
1066   FREE_MAYBE (opt.ftp_pass);
1067   FREE_MAYBE (opt.ftp_proxy);
1068   FREE_MAYBE (opt.https_proxy);
1069   FREE_MAYBE (opt.http_proxy);
1070   free_vec (opt.no_proxy);
1071   FREE_MAYBE (opt.useragent);
1072   FREE_MAYBE (opt.referer);
1073   FREE_MAYBE (opt.http_user);
1074   FREE_MAYBE (opt.http_passwd);
1075   FREE_MAYBE (opt.user_header);
1076 #ifdef HAVE_SSL
1077   FREE_MAYBE (opt.sslcertkey);
1078   FREE_MAYBE (opt.sslcertfile);
1079 #endif /* HAVE_SSL */
1080   FREE_MAYBE (opt.bind_address);
1081   FREE_MAYBE (opt.cookies_input);
1082   FREE_MAYBE (opt.cookies_output);
1083 #endif
1084 }