]> sjero.net Git - wget/blob - src/init.c
76fbc45d9244c487e8ab4829ffbab298e1baac03
[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   { "loadcookies",      &opt.cookies_input,     cmd_file },
146   { "logfile",          &opt.lfilename,         cmd_file },
147   { "login",            &opt.ftp_acc,           cmd_string },
148   { "mirror",           NULL,                   cmd_spec_mirror },
149   { "netrc",            &opt.netrc,             cmd_boolean },
150   { "noclobber",        &opt.noclobber,         cmd_boolean },
151   { "noparent",         &opt.no_parent,         cmd_boolean },
152   { "noproxy",          &opt.no_proxy,          cmd_vector },
153   { "numtries",         &opt.ntry,              cmd_number_inf },/* deprecated*/
154   { "outputdocument",   &opt.output_document,   cmd_file },
155   { "pagerequisites",   &opt.page_requisites,   cmd_boolean },
156   { "passiveftp",       &opt.ftp_pasv,          cmd_lockable_boolean },
157   { "passwd",           &opt.ftp_pass,          cmd_string },
158   { "progress",         NULL,                   cmd_spec_progress },
159   { "proxypasswd",      &opt.proxy_passwd,      cmd_string },
160   { "proxyuser",        &opt.proxy_user,        cmd_string },
161   { "quiet",            &opt.quiet,             cmd_boolean },
162   { "quota",            &opt.quota,             cmd_bytes },
163   { "reclevel",         &opt.reclevel,          cmd_number_inf },
164   { "recursive",        NULL,                   cmd_spec_recursive },
165   { "referer",          &opt.referer,           cmd_string },
166   { "reject",           &opt.rejects,           cmd_vector },
167   { "relativeonly",     &opt.relative_only,     cmd_boolean },
168   { "removelisting",    &opt.remove_listing,    cmd_boolean },
169   { "retrsymlinks",     &opt.retr_symlinks,     cmd_boolean },
170   { "robots",           &opt.use_robots,        cmd_boolean },
171   { "savecookies",      &opt.cookies_output,    cmd_file },
172   { "saveheaders",      &opt.save_headers,      cmd_boolean },
173   { "serverresponse",   &opt.server_response,   cmd_boolean },
174   { "simplehostcheck",  &opt.simple_check,      cmd_boolean },
175   { "spanhosts",        &opt.spanhost,          cmd_boolean },
176   { "spider",           &opt.spider,            cmd_boolean },
177 #ifdef HAVE_SSL
178   { "sslcertfile",      &opt.sslcertfile,       cmd_file },
179   { "sslcertkey",       &opt.sslcertkey,        cmd_file },
180 #endif /* HAVE_SSL */
181   { "timeout",          &opt.timeout,           cmd_time },
182   { "timestamping",     &opt.timestamping,      cmd_boolean },
183   { "tries",            &opt.ntry,              cmd_number_inf },
184   { "useproxy",         &opt.use_proxy,         cmd_boolean },
185   { "useragent",        NULL,                   cmd_spec_useragent },
186   { "verbose",          &opt.verbose,           cmd_boolean },
187   { "wait",             &opt.wait,              cmd_time },
188   { "waitretry",        &opt.waitretry,         cmd_time }
189 };
190
191 /* Return index of COM if it is a valid command, or -1 otherwise.  COM
192    is looked up in `commands' using binary search algorithm.  */
193 static int
194 comind (const char *com)
195 {
196   int min = 0, max = ARRAY_SIZE (commands) - 1;
197
198   do
199     {
200       int i = (min + max) / 2;
201       int cmp = strcasecmp (com, commands[i].name);
202       if (cmp == 0)
203         return i;
204       else if (cmp < 0)
205         max = i - 1;
206       else
207         min = i + 1;
208     }
209   while (min <= max);
210   return -1;
211 }
212 \f
213 /* Reset the variables to default values.  */
214 static void
215 defaults (void)
216 {
217   char *tmp;
218
219   /* Most of the default values are 0.  Just reset everything, and
220      fill in the non-zero values.  Note that initializing pointers to
221      NULL this way is technically illegal, but porting Wget to a
222      machine where NULL is not all-zero bit pattern will be the least
223      of the implementors' worries.  */
224   memset (&opt, 0, sizeof (opt));
225
226   opt.cookies = 1;
227
228   opt.verbose = -1;
229   opt.dir_prefix = xstrdup (".");
230   opt.ntry = 20;
231   opt.reclevel = 5;
232   opt.add_hostdir = 1;
233   opt.ftp_acc  = xstrdup ("anonymous");
234   opt.ftp_pass = xstrdup ("-wget@");
235   opt.netrc = 1;
236   opt.ftp_glob = 1;
237   opt.htmlify = 1;
238   opt.http_keep_alive = 1;
239   opt.use_proxy = 1;
240   tmp = getenv ("no_proxy");
241   if (tmp)
242     opt.no_proxy = sepstring (tmp);
243   opt.allow_cache = 1;
244
245 #ifdef HAVE_SELECT
246   opt.timeout = 900;
247 #endif
248   opt.use_robots = 1;
249
250   opt.remove_listing = 1;
251
252   set_progress_implementation ("dot");
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 sockaddr_in sin;
526   struct sockaddr_in **target = (struct sockaddr_in **)closure;
527
528   memset (&sin, '\0', sizeof (sin));
529
530   if (!store_hostaddress ((unsigned char *)&sin.sin_addr, val))
531     {
532       fprintf (stderr, _("%s: %s: Cannot convert `%s' to an IP address.\n"),
533                exec_name, com, val);
534       return 0;
535     }
536   sin.sin_family = AF_INET;
537   sin.sin_port = 0;
538
539   FREE_MAYBE (*target);
540
541   *target = xmalloc (sizeof (sin));
542   memcpy (*target, &sin, sizeof (sin));
543
544   return 1;
545 }
546
547 /* Store the boolean value from VAL to CLOSURE.  COM is ignored,
548    except for error messages.  */
549 static int
550 cmd_boolean (const char *com, const char *val, void *closure)
551 {
552   int bool_value;
553
554   if (!strcasecmp (val, "on")
555       || (*val == '1' && !*(val + 1)))
556     bool_value = 1;
557   else if (!strcasecmp (val, "off")
558            || (*val == '0' && !*(val + 1)))
559     bool_value = 0;
560   else
561     {
562       fprintf (stderr, _("%s: %s: Please specify on or off.\n"),
563                exec_name, com);
564       return 0;
565     }
566
567   *(int *)closure = bool_value;
568   return 1;
569 }
570
571 /* Store the lockable_boolean {2, 1, 0, -1} value from VAL to CLOSURE.  COM is
572    ignored, except for error messages.  Values 2 and -1 indicate that once
573    defined, the value may not be changed by successive wgetrc files or
574    command-line arguments.
575
576    Values: 2 - Enable a particular option for good ("always")
577            1 - Enable an option ("on")
578            0 - Disable an option ("off")
579           -1 - Disable an option for good ("never") */
580 static int
581 cmd_lockable_boolean (const char *com, const char *val, void *closure)
582 {
583   int lockable_boolean_value;
584
585   /*
586    * If a config file said "always" or "never", don't allow command line
587    * arguments to override the config file.
588    */
589   if (*(int *)closure == -1 || *(int *)closure == 2)
590     return 1;
591
592   if (!strcasecmp (val, "always")
593       || (*val == '2' && !*(val + 1)))
594     lockable_boolean_value = 2;
595   else if (!strcasecmp (val, "on")
596       || (*val == '1' && !*(val + 1)))
597     lockable_boolean_value = 1;
598   else if (!strcasecmp (val, "off")
599           || (*val == '0' && !*(val + 1)))
600     lockable_boolean_value = 0;
601   else if (!strcasecmp (val, "never")
602       || (*val == '-' && *(val + 1) == '1' && !*(val + 2)))
603     lockable_boolean_value = -1;
604   else
605     {
606       fprintf (stderr, _("%s: %s: Please specify always, on, off, "
607                          "or never.\n"),
608                exec_name, com);
609       return 0;
610     }
611
612   *(int *)closure = lockable_boolean_value;
613   return 1;
614 }
615
616 /* Set the non-negative integer value from VAL to CLOSURE.  With
617    incorrect specification, the number remains unchanged.  */
618 static int
619 cmd_number (const char *com, const char *val, void *closure)
620 {
621   int num = myatoi (val);
622
623   if (num == -1)
624     {
625       fprintf (stderr, _("%s: %s: Invalid specification `%s'.\n"),
626                exec_name, com, val);
627       return 0;
628     }
629   *(int *)closure = num;
630   return 1;
631 }
632
633 /* Similar to cmd_number(), only accepts `inf' as a synonym for 0.  */
634 static int
635 cmd_number_inf (const char *com, const char *val, void *closure)
636 {
637   if (!strcasecmp (val, "inf"))
638     {
639       *(int *)closure = 0;
640       return 1;
641     }
642   return cmd_number (com, val, closure);
643 }
644
645 /* Copy (strdup) the string at COM to a new location and place a
646    pointer to *CLOSURE.  */
647 static int
648 cmd_string (const char *com, const char *val, void *closure)
649 {
650   char **pstring = (char **)closure;
651
652   FREE_MAYBE (*pstring);
653   *pstring = xstrdup (val);
654   return 1;
655 }
656
657 /* Like the above, but handles tilde-expansion when reading a user's
658    `.wgetrc'.  In that case, and if VAL begins with `~', the tilde
659    gets expanded to the user's home directory.  */
660 static int
661 cmd_file (const char *com, const char *val, void *closure)
662 {
663   char **pstring = (char **)closure;
664
665   FREE_MAYBE (*pstring);
666   if (!enable_tilde_expansion || !(*val == '~' && *(val + 1) == '/'))
667     {
668     noexpand:
669       *pstring = xstrdup (val);
670     }
671   else
672     {
673       char *result;
674       int homelen;
675       char *home = home_dir ();
676       if (!home)
677         goto noexpand;
678
679       homelen = strlen (home);
680       while (homelen && home[homelen - 1] == '/')
681         home[--homelen] = '\0';
682
683       /* Skip the leading "~/". */
684       for (++val; *val == '/'; val++)
685         ;
686
687       result = xmalloc (homelen + 1 + strlen (val));
688       memcpy (result, home, homelen);
689       result[homelen] = '/';
690       strcpy (result + homelen + 1, val);
691
692       *pstring = result;
693     }
694   return 1;
695 }
696
697 /* Merge the vector (array of strings separated with `,') in COM with
698    the vector (NULL-terminated array of strings) pointed to by
699    CLOSURE.  */
700 static int
701 cmd_vector (const char *com, const char *val, void *closure)
702 {
703   char ***pvec = (char ***)closure;
704
705   if (*val)
706     *pvec = merge_vecs (*pvec, sepstring (val));
707   else
708     {
709       free_vec (*pvec);
710       *pvec = NULL;
711     }
712   return 1;
713 }
714
715 static int
716 cmd_directory_vector (const char *com, const char *val, void *closure)
717 {
718   char ***pvec = (char ***)closure;
719
720   if (*val)
721     {
722       /* Strip the trailing slashes from directories.  */
723       char **t, **seps;
724
725       seps = sepstring (val);
726       for (t = seps; t && *t; t++)
727         {
728           int len = strlen (*t);
729           /* Skip degenerate case of root directory.  */
730           if (len > 1)
731             {
732               if ((*t)[len - 1] == '/')
733                 (*t)[len - 1] = '\0';
734             }
735         }
736       *pvec = merge_vecs (*pvec, seps);
737     }
738   else
739     {
740       free_vec (*pvec);
741       *pvec = NULL;
742     }
743   return 1;
744 }
745
746 /* Set the value stored in VAL to CLOSURE (which should point to a
747    long int), allowing several postfixes, with the following syntax
748    (regexp):
749
750    [0-9]+       -> bytes
751    [0-9]+[kK]   -> bytes * 1024
752    [0-9]+[mM]   -> bytes * 1024 * 1024
753    inf          -> 0
754
755    Anything else is flagged as incorrect, and CLOSURE is unchanged.  */
756 static int
757 cmd_bytes (const char *com, const char *val, void *closure)
758 {
759   long result;
760   long *out = (long *)closure;
761   const char *p;
762
763   result = 0;
764   p = val;
765   /* Check for "inf".  */
766   if (p[0] == 'i' && p[1] == 'n' && p[2] == 'f' && p[3] == '\0')
767     {
768       *out = 0;
769       return 1;
770     }
771   /* Search for digits and construct result.  */
772   for (; *p && ISDIGIT (*p); p++)
773     result = (10 * result) + (*p - '0');
774   /* If no digits were found, or more than one character is following
775      them, bail out.  */
776   if (p == val || (*p != '\0' && *(p + 1) != '\0'))
777     {
778       printf (_("%s: Invalid specification `%s'\n"), com, val);
779       return 0;
780     }
781   /* Search for a designator.  */
782   switch (TOLOWER (*p))
783     {
784     case '\0':
785       /* None */
786       break;
787     case 'k':
788       /* Kilobytes */
789       result *= 1024;
790       break;
791     case 'm':
792       /* Megabytes */
793       result *= (long)1024 * 1024;
794       break;
795     case 'g':
796       /* Gigabytes */
797       result *= (long)1024 * 1024 * 1024;
798       break;
799     default:
800       printf (_("%s: Invalid specification `%s'\n"), com, val);
801       return 0;
802     }
803   *out = result;
804   return 1;
805 }
806
807 /* Store the value of VAL to *OUT, allowing suffixes for minutes and
808    hours.  */
809 static int
810 cmd_time (const char *com, const char *val, void *closure)
811 {
812   long result = 0;
813   const char *p = val;
814
815   /* Search for digits and construct result.  */
816   for (; *p && ISDIGIT (*p); p++)
817     result = (10 * result) + (*p - '0');
818   /* If no digits were found, or more than one character is following
819      them, bail out.  */
820   if (p == val || (*p != '\0' && *(p + 1) != '\0'))
821     {
822       printf (_("%s: Invalid specification `%s'\n"), com, val);
823       return 0;
824     }
825   /* Search for a suffix.  */
826   switch (TOLOWER (*p))
827     {
828     case '\0':
829       /* None */
830       break;
831     case 'm':
832       /* Minutes */
833       result *= 60;
834       break;
835     case 'h':
836       /* Seconds */
837       result *= 3600;
838       break;
839     case 'd':
840       /* Days (overflow on 16bit machines) */
841       result *= 86400L;
842       break;
843     case 'w':
844       /* Weeks :-) */
845       result *= 604800L;
846       break;
847     default:
848       printf (_("%s: Invalid specification `%s'\n"), com, val);
849       return 0;
850     }
851   *(long *)closure = result;
852   return 1;
853 }
854 \f
855 /* Specialized helper functions, used by `commands' to handle some
856    options specially.  */
857
858 static int check_user_specified_header PARAMS ((const char *));
859
860 static int
861 cmd_spec_dirstruct (const char *com, const char *val, void *closure)
862 {
863   if (!cmd_boolean (com, val, &opt.dirstruct))
864     return 0;
865   /* Since dirstruct behaviour is explicitly changed, no_dirstruct
866      must be affected inversely.  */
867   if (opt.dirstruct)
868     opt.no_dirstruct = 0;
869   else
870     opt.no_dirstruct = 1;
871   return 1;
872 }
873
874 static int
875 cmd_spec_header (const char *com, const char *val, void *closure)
876 {
877   if (!*val)
878     {
879       /* Empty header means reset headers.  */
880       FREE_MAYBE (opt.user_header);
881       opt.user_header = NULL;
882     }
883   else
884     {
885       int i;
886
887       if (!check_user_specified_header (val))
888         {
889           fprintf (stderr, _("%s: %s: Invalid specification `%s'.\n"),
890                    exec_name, com, val);
891           return 0;
892         }
893       i = opt.user_header ? strlen (opt.user_header) : 0;
894       opt.user_header = (char *)xrealloc (opt.user_header, i + strlen (val)
895                                           + 2 + 1);
896       strcpy (opt.user_header + i, val);
897       i += strlen (val);
898       opt.user_header[i++] = '\r';
899       opt.user_header[i++] = '\n';
900       opt.user_header[i] = '\0';
901     }
902   return 1;
903 }
904
905 static int
906 cmd_spec_htmlify (const char *com, const char *val, void *closure)
907 {
908   int flag = cmd_boolean (com, val, &opt.htmlify);
909   if (flag && !opt.htmlify)
910     opt.remove_listing = 0;
911   return flag;
912 }
913
914 static int
915 cmd_spec_mirror (const char *com, const char *val, void *closure)
916 {
917   int mirror;
918
919   if (!cmd_boolean (com, val, &mirror))
920     return 0;
921   if (mirror)
922     {
923       opt.recursive = 1;
924       if (!opt.no_dirstruct)
925         opt.dirstruct = 1;
926       opt.timestamping = 1;
927       opt.reclevel = INFINITE_RECURSION;
928       opt.remove_listing = 0;
929     }
930   return 1;
931 }
932
933 static int
934 cmd_spec_progress (const char *com, const char *val, void *closure)
935 {
936   if (!valid_progress_implementation_p (val))
937     {
938       fprintf (stderr, _("%s: %s: Invalid progress type `%s'.\n"),
939                exec_name, com, val);
940       return 0;
941     }
942   set_progress_implementation (val);
943   return 1;
944 }
945
946 static int
947 cmd_spec_recursive (const char *com, const char *val, void *closure)
948 {
949   if (!cmd_boolean (com, val, &opt.recursive))
950     return 0;
951   else
952     {
953       if (opt.recursive && !opt.no_dirstruct)
954         opt.dirstruct = 1;
955     }
956   return 1;
957 }
958
959 static int
960 cmd_spec_useragent (const char *com, const char *val, void *closure)
961 {
962   /* Just check for empty string and newline, so we don't throw total
963      junk to the server.  */
964   if (!*val || strchr (val, '\n'))
965     {
966       fprintf (stderr, _("%s: %s: Invalid specification `%s'.\n"),
967                exec_name, com, val);
968       return 0;
969     }
970   opt.useragent = xstrdup (val);
971   return 1;
972 }
973 \f
974 /* Miscellaneous useful routines.  */
975
976 /* Return the integer value of a positive integer written in S, or -1
977    if an error was encountered.  */
978 static int
979 myatoi (const char *s)
980 {
981   int res;
982   const char *orig = s;
983
984   for (res = 0; *s && ISDIGIT (*s); s++)
985     res = 10 * res + (*s - '0');
986   if (*s || orig == s)
987     return -1;
988   else
989     return res;
990 }
991
992 #define ISODIGIT(x) ((x) >= '0' && (x) <= '7')
993
994 static int
995 check_user_specified_header (const char *s)
996 {
997   const char *p;
998
999   for (p = s; *p && *p != ':' && !ISSPACE (*p); p++);
1000   /* The header MUST contain `:' preceded by at least one
1001      non-whitespace character.  */
1002   if (*p != ':' || p == s)
1003     return 0;
1004   /* The header MUST NOT contain newlines.  */
1005   if (strchr (s, '\n'))
1006     return 0;
1007   return 1;
1008 }
1009 \f
1010 void cleanup_html_url PARAMS ((void));
1011 void downloaded_files_free PARAMS ((void));
1012
1013
1014 /* Free the memory allocated by global variables.  */
1015 void
1016 cleanup (void)
1017 {
1018   extern acc_t *netrc_list;
1019
1020   recursive_cleanup ();
1021   clean_hosts ();
1022   free_netrc (netrc_list);
1023   if (opt.dfp)
1024     fclose (opt.dfp);
1025   cleanup_html_url ();
1026   downloaded_files_free ();
1027   cookies_cleanup ();
1028   FREE_MAYBE (opt.lfilename);
1029   xfree (opt.dir_prefix);
1030   FREE_MAYBE (opt.input_filename);
1031   FREE_MAYBE (opt.output_document);
1032   free_vec (opt.accepts);
1033   free_vec (opt.rejects);
1034   free_vec (opt.excludes);
1035   free_vec (opt.includes);
1036   free_vec (opt.domains);
1037   free_vec (opt.follow_tags);
1038   free_vec (opt.ignore_tags);
1039   xfree (opt.ftp_acc);
1040   FREE_MAYBE (opt.ftp_pass);
1041   FREE_MAYBE (opt.ftp_proxy);
1042   FREE_MAYBE (opt.https_proxy);
1043   FREE_MAYBE (opt.http_proxy);
1044   free_vec (opt.no_proxy);
1045   FREE_MAYBE (opt.useragent);
1046   FREE_MAYBE (opt.referer);
1047   FREE_MAYBE (opt.http_user);
1048   FREE_MAYBE (opt.http_passwd);
1049   FREE_MAYBE (opt.user_header);
1050 #ifdef HAVE_SSL
1051   FREE_MAYBE (opt.sslcertkey);
1052   FREE_MAYBE (opt.sslcertfile);
1053 #endif /* HAVE_SSL */
1054   FREE_MAYBE (opt.bind_address);
1055   FREE_MAYBE (opt.cookies_input);
1056   FREE_MAYBE (opt.cookies_output);
1057 }