]> sjero.net Git - wget/blob - src/init.c
b504a27b36ef97497c2cb3c0c615f6146e0b9ef1
[wget] / src / init.c
1 /* Reading/parsing the initialization file.
2    Copyright (C) 1995, 1996, 1997, 1998, 2000, 2001, 2003, 2004
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 In addition, as a special exception, the Free Software Foundation
22 gives permission to link the code of its release of Wget with the
23 OpenSSL project's "OpenSSL" library (or with modified versions of it
24 that use the same license as the "OpenSSL" library), and distribute
25 the linked executables.  You must obey the GNU General Public License
26 in all respects for all of the code used other than "OpenSSL".  If you
27 modify this file, you may extend this exception to your version of the
28 file, but you are not obligated to do so.  If you do not wish to do
29 so, delete this exception statement from your version.  */
30
31 #include <config.h>
32
33 #include <stdio.h>
34 #include <sys/types.h>
35 #include <stdlib.h>
36 #ifdef HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
39 #ifdef HAVE_STRING_H
40 # include <string.h>
41 #else
42 # include <strings.h>
43 #endif
44 #include <errno.h>
45
46 #ifdef HAVE_PWD_H
47 # include <pwd.h>
48 #endif
49 #include <assert.h>
50
51 #include "wget.h"
52 #include "utils.h"
53 #include "init.h"
54 #include "host.h"
55 #include "netrc.h"
56 #include "cookies.h"            /* for cookie_jar_delete */
57 #include "progress.h"
58 #include "recur.h"              /* for INFINITE_RECURSION */
59
60 #ifndef errno
61 extern int errno;
62 #endif
63
64 extern struct cookie_jar *wget_cookie_jar;
65
66 /* We want tilde expansion enabled only when reading `.wgetrc' lines;
67    otherwise, it will be performed by the shell.  This variable will
68    be set by the wgetrc-reading function.  */
69
70 static int enable_tilde_expansion;
71
72
73 #define CMD_DECLARE(func) static int func \
74   PARAMS ((const char *, const char *, void *))
75
76 CMD_DECLARE (cmd_boolean);
77 CMD_DECLARE (cmd_bytes);
78 CMD_DECLARE (cmd_bytes_large);
79 CMD_DECLARE (cmd_directory_vector);
80 CMD_DECLARE (cmd_lockable_boolean);
81 CMD_DECLARE (cmd_number);
82 CMD_DECLARE (cmd_number_inf);
83 CMD_DECLARE (cmd_string);
84 CMD_DECLARE (cmd_file);
85 CMD_DECLARE (cmd_directory);
86 CMD_DECLARE (cmd_time);
87 CMD_DECLARE (cmd_vector);
88
89 CMD_DECLARE (cmd_spec_dirstruct);
90 CMD_DECLARE (cmd_spec_header);
91 CMD_DECLARE (cmd_spec_htmlify);
92 CMD_DECLARE (cmd_spec_mirror);
93 CMD_DECLARE (cmd_spec_progress);
94 CMD_DECLARE (cmd_spec_recursive);
95 CMD_DECLARE (cmd_spec_restrict_file_names);
96 CMD_DECLARE (cmd_spec_timeout);
97 CMD_DECLARE (cmd_spec_useragent);
98
99 /* List of recognized commands, each consisting of name, closure and
100    function.  When adding a new command, simply add it to the list,
101    but be sure to keep the list sorted alphabetically, as
102    command_by_name depends on it.  Also, be sure to add any entries
103    that allocate memory (e.g. cmd_string and cmd_vector guys) to the
104    cleanup() function below. */
105
106 static struct {
107   const char *name;
108   void *closure;
109   int (*action) PARAMS ((const char *, const char *, void *));
110 } commands[] = {
111   { "accept",           &opt.accepts,           cmd_vector },
112   { "addhostdir",       &opt.add_hostdir,       cmd_boolean },
113   { "alwaysrest",       &opt.always_rest,       cmd_boolean }, /* deprecated */
114   { "background",       &opt.background,        cmd_boolean },
115   { "backupconverted",  &opt.backup_converted,  cmd_boolean },
116   { "backups",          &opt.backups,           cmd_number },
117   { "base",             &opt.base_href,         cmd_string },
118   { "bindaddress",      &opt.bind_address,      cmd_string },
119   { "cache",            &opt.allow_cache,       cmd_boolean },
120   { "connecttimeout",   &opt.connect_timeout,   cmd_time },
121   { "continue",         &opt.always_rest,       cmd_boolean },
122   { "convertlinks",     &opt.convert_links,     cmd_boolean },
123   { "cookies",          &opt.cookies,           cmd_boolean },
124   { "cutdirs",          &opt.cut_dirs,          cmd_number },
125 #ifdef ENABLE_DEBUG
126   { "debug",            &opt.debug,             cmd_boolean },
127 #endif
128   { "deleteafter",      &opt.delete_after,      cmd_boolean },
129   { "dirprefix",        &opt.dir_prefix,        cmd_directory },
130   { "dirstruct",        NULL,                   cmd_spec_dirstruct },
131   { "dnscache",         &opt.dns_cache,         cmd_boolean },
132   { "dnstimeout",       &opt.dns_timeout,       cmd_time },
133   { "domains",          &opt.domains,           cmd_vector },
134   { "dotbytes",         &opt.dot_bytes,         cmd_bytes },
135   { "dotsinline",       &opt.dots_in_line,      cmd_number },
136   { "dotspacing",       &opt.dot_spacing,       cmd_number },
137   { "dotstyle",         &opt.dot_style,         cmd_string },
138 #ifdef HAVE_SSL
139   { "egdfile",          &opt.sslegdsock,        cmd_file },
140 #endif
141   { "excludedirectories", &opt.excludes,        cmd_directory_vector },
142   { "excludedomains",   &opt.exclude_domains,   cmd_vector },
143   { "followftp",        &opt.follow_ftp,        cmd_boolean },
144   { "followtags",       &opt.follow_tags,       cmd_vector },
145   { "forcehtml",        &opt.force_html,        cmd_boolean },
146   { "ftppasswd",        &opt.ftp_pass,          cmd_string },
147   { "ftpproxy",         &opt.ftp_proxy,         cmd_string },
148   { "glob",             &opt.ftp_glob,          cmd_boolean },
149   { "header",           &opt.user_headers,      cmd_spec_header },
150   { "htmlextension",    &opt.html_extension,    cmd_boolean },
151   { "htmlify",          NULL,                   cmd_spec_htmlify },
152   { "httpkeepalive",    &opt.http_keep_alive,   cmd_boolean },
153   { "httppasswd",       &opt.http_passwd,       cmd_string },
154   { "httpproxy",        &opt.http_proxy,        cmd_string },
155   { "httpsproxy",       &opt.https_proxy,       cmd_string },
156   { "httpuser",         &opt.http_user,         cmd_string },
157   { "ignorelength",     &opt.ignore_length,     cmd_boolean },
158   { "ignoretags",       &opt.ignore_tags,       cmd_vector },
159   { "includedirectories", &opt.includes,        cmd_directory_vector },
160 #ifdef ENABLE_IPV6
161   { "inet4only",        &opt.ipv4_only,         cmd_boolean },
162   { "inet6only",        &opt.ipv6_only,         cmd_boolean },
163 #endif
164   { "input",            &opt.input_filename,    cmd_file },
165   { "keepsessioncookies", &opt.keep_session_cookies, cmd_boolean },
166   { "killlonger",       &opt.kill_longer,       cmd_boolean },
167   { "limitrate",        &opt.limit_rate,        cmd_bytes },
168   { "loadcookies",      &opt.cookies_input,     cmd_file },
169   { "logfile",          &opt.lfilename,         cmd_file },
170   { "login",            &opt.ftp_acc,           cmd_string },
171   { "mirror",           NULL,                   cmd_spec_mirror },
172   { "netrc",            &opt.netrc,             cmd_boolean },
173   { "noclobber",        &opt.noclobber,         cmd_boolean },
174   { "noparent",         &opt.no_parent,         cmd_boolean },
175   { "noproxy",          &opt.no_proxy,          cmd_vector },
176   { "numtries",         &opt.ntry,              cmd_number_inf },/* deprecated*/
177   { "outputdocument",   &opt.output_document,   cmd_file },
178   { "pagerequisites",   &opt.page_requisites,   cmd_boolean },
179   { "passiveftp",       &opt.ftp_pasv,          cmd_lockable_boolean },
180   { "postdata",         &opt.post_data,         cmd_string },
181   { "postfile",         &opt.post_file_name,    cmd_file },
182   { "preservepermissions", &opt.preserve_perm,  cmd_boolean },
183   { "progress",         &opt.progress_type,     cmd_spec_progress },
184   { "protocoldirectories", &opt.protocol_directories, cmd_boolean },
185   { "proxypasswd",      &opt.proxy_passwd,      cmd_string },
186   { "proxyuser",        &opt.proxy_user,        cmd_string },
187   { "quiet",            &opt.quiet,             cmd_boolean },
188   { "quota",            &opt.quota,             cmd_bytes_large },
189   { "randomwait",       &opt.random_wait,       cmd_boolean },
190   { "readtimeout",      &opt.read_timeout,      cmd_time },
191   { "reclevel",         &opt.reclevel,          cmd_number_inf },
192   { "recursive",        NULL,                   cmd_spec_recursive },
193   { "referer",          &opt.referer,           cmd_string },
194   { "reject",           &opt.rejects,           cmd_vector },
195   { "relativeonly",     &opt.relative_only,     cmd_boolean },
196   { "removelisting",    &opt.remove_listing,    cmd_boolean },
197   { "restrictfilenames", NULL,                  cmd_spec_restrict_file_names },
198   { "retrsymlinks",     &opt.retr_symlinks,     cmd_boolean },
199   { "retryconnrefused", &opt.retry_connrefused, cmd_boolean },
200   { "robots",           &opt.use_robots,        cmd_boolean },
201   { "savecookies",      &opt.cookies_output,    cmd_file },
202   { "saveheaders",      &opt.save_headers,      cmd_boolean },
203   { "serverresponse",   &opt.server_response,   cmd_boolean },
204   { "spanhosts",        &opt.spanhost,          cmd_boolean },
205   { "spider",           &opt.spider,            cmd_boolean },
206 #ifdef HAVE_SSL
207   { "sslcadir",         &opt.sslcadir,          cmd_directory },
208   { "sslcafile",        &opt.sslcafile,         cmd_file },
209   { "sslcertfile",      &opt.sslcertfile,       cmd_file },
210   { "sslcertkey",       &opt.sslcertkey,        cmd_file },
211   { "sslcerttype",      &opt.sslcerttype,       cmd_number },
212   { "sslcheckcert",     &opt.sslcheckcert,      cmd_number },
213   { "sslprotocol",      &opt.sslprotocol,       cmd_number },
214 #endif /* HAVE_SSL */
215   { "strictcomments",   &opt.strict_comments,   cmd_boolean },
216   { "timeout",          NULL,                   cmd_spec_timeout },
217   { "timestamping",     &opt.timestamping,      cmd_boolean },
218   { "tries",            &opt.ntry,              cmd_number_inf },
219   { "useproxy",         &opt.use_proxy,         cmd_boolean },
220   { "useragent",        NULL,                   cmd_spec_useragent },
221   { "verbose",          &opt.verbose,           cmd_boolean },
222   { "wait",             &opt.wait,              cmd_time },
223   { "waitretry",        &opt.waitretry,         cmd_time }
224 };
225
226 /* Look up CMDNAME in the commands[] and return its position in the
227    array.  If CMDNAME is not found, return -1.  */
228
229 static int
230 command_by_name (const char *cmdname)
231 {
232   /* Use binary search for speed.  Wget has ~100 commands, which
233      guarantees a worst case performance of 7 string comparisons.  */
234   int lo = 0, hi = countof (commands) - 1;
235
236   while (lo <= hi)
237     {
238       int mid = (lo + hi) >> 1;
239       int cmp = strcasecmp (cmdname, commands[mid].name);
240       if (cmp < 0)
241         hi = mid - 1;
242       else if (cmp > 0)
243         lo = mid + 1;
244       else
245         return mid;
246     }
247   return -1;
248 }
249 \f
250 /* Reset the variables to default values.  */
251 static void
252 defaults (void)
253 {
254   char *tmp;
255
256   /* Most of the default values are 0.  Just reset everything, and
257      fill in the non-zero values.  Note that initializing pointers to
258      NULL this way is technically illegal, but porting Wget to a
259      machine where NULL is not all-zero bit pattern will be the least
260      of the implementors' worries.  */
261   xzero (opt);
262
263   opt.cookies = 1;
264   opt.verbose = -1;
265   opt.ntry = 20;
266   opt.reclevel = 5;
267   opt.add_hostdir = 1;
268   opt.ftp_acc  = xstrdup ("anonymous");
269   opt.ftp_pass = xstrdup ("-wget@");
270   opt.netrc = 1;
271   opt.ftp_glob = 1;
272   opt.htmlify = 1;
273   opt.http_keep_alive = 1;
274   opt.use_proxy = 1;
275   tmp = getenv ("no_proxy");
276   if (tmp)
277     opt.no_proxy = sepstring (tmp);
278   opt.allow_cache = 1;
279
280   opt.read_timeout = 900;
281   opt.use_robots = 1;
282
283   opt.remove_listing = 1;
284
285   opt.dot_bytes = 1024;
286   opt.dot_spacing = 10;
287   opt.dots_in_line = 50;
288
289   opt.dns_cache = 1;
290   opt.ftp_pasv = 1;
291
292   /* The default for file name restriction defaults to the OS type. */
293 #if !defined(WINDOWS) && !defined(__CYGWIN__)
294   opt.restrict_files_os = restrict_unix;
295 #else
296   opt.restrict_files_os = restrict_windows;
297 #endif
298   opt.restrict_files_ctrl = 1;
299 }
300 \f
301 /* Return the user's home directory (strdup-ed), or NULL if none is
302    found.  */
303 char *
304 home_dir (void)
305 {
306   char *home = getenv ("HOME");
307
308   if (!home)
309     {
310 #ifndef WINDOWS
311       /* If HOME is not defined, try getting it from the password
312          file.  */
313       struct passwd *pwd = getpwuid (getuid ());
314       if (!pwd || !pwd->pw_dir)
315         return NULL;
316       home = pwd->pw_dir;
317 #else  /* WINDOWS */
318       /* Under Windows, if $HOME isn't defined, use the directory where
319          `wget.exe' resides.  */
320       home = ws_mypath ();
321 #endif /* WINDOWS */
322     }
323
324   return home ? xstrdup (home) : NULL;
325 }
326
327 /* Return the path to the user's .wgetrc.  This is either the value of
328    `WGETRC' environment variable, or `$HOME/.wgetrc'.
329
330    If the `WGETRC' variable exists but the file does not exist, the
331    function will exit().  */
332 static char *
333 wgetrc_file_name (void)
334 {
335   char *env, *home;
336   char *file = NULL;
337
338   /* Try the environment.  */
339   env = getenv ("WGETRC");
340   if (env && *env)
341     {
342       if (!file_exists_p (env))
343         {
344           fprintf (stderr, _("%s: WGETRC points to %s, which doesn't exist.\n"),
345                    exec_name, env);
346           exit (1);
347         }
348       return xstrdup (env);
349     }
350
351   /* If that failed, try $HOME/.wgetrc.  */
352   home = home_dir ();
353   if (home)
354     file = aprintf ("%s/.wgetrc", home);
355   xfree_null (home);
356
357 #ifdef WINDOWS
358   /* Under Windows, if we still haven't found .wgetrc, look for the file
359      `wget.ini' in the directory where `wget.exe' resides; we do this for
360      backward compatibility with previous versions of Wget.
361      SYSTEM_WGETRC should not be defined under WINDOWS.  */
362   if (!file || !file_exists_p (file))
363     {
364       xfree_null (file);
365       file = NULL;
366       home = ws_mypath ();
367       if (home)
368         file = aprintf ("%s/wget.ini", home);
369     }
370 #endif /* WINDOWS */
371
372   if (!file)
373     return NULL;
374   if (!file_exists_p (file))
375     {
376       xfree (file);
377       return NULL;
378     }
379   return file;
380 }
381
382 static int parse_line PARAMS ((const char *, char **, char **, int *));
383 static int setval_internal PARAMS ((int, const char *, const char *));
384
385 /* Initialize variables from a wgetrc file.  */
386
387 static void
388 run_wgetrc (const char *file)
389 {
390   FILE *fp;
391   char *line;
392   int ln;
393
394   fp = fopen (file, "rb");
395   if (!fp)
396     {
397       fprintf (stderr, _("%s: Cannot read %s (%s).\n"), exec_name,
398                file, strerror (errno));
399       return;
400     }
401   enable_tilde_expansion = 1;
402   ln = 1;
403   while ((line = read_whole_line (fp)) != NULL)
404     {
405       char *com, *val;
406       int comind, status;
407
408       /* Parse the line.  */
409       status = parse_line (line, &com, &val, &comind);
410       xfree (line);
411       /* If everything is OK, set the value.  */
412       if (status == 1)
413         {
414           if (!setval_internal (comind, com, val))
415             fprintf (stderr, _("%s: Error in %s at line %d.\n"), exec_name,
416                      file, ln);
417           xfree (com);
418           xfree (val);
419         }
420       else if (status == 0)
421         fprintf (stderr, _("%s: Error in %s at line %d.\n"), exec_name,
422                  file, ln);
423       ++ln;
424     }
425   enable_tilde_expansion = 0;
426   fclose (fp);
427 }
428
429 /* Initialize the defaults and run the system wgetrc and user's own
430    wgetrc.  */
431 void
432 initialize (void)
433 {
434   char *file;
435
436   /* Load the hard-coded defaults.  */
437   defaults ();
438
439   /* If SYSTEM_WGETRC is defined, use it.  */
440 #ifdef SYSTEM_WGETRC
441   if (file_exists_p (SYSTEM_WGETRC))
442     run_wgetrc (SYSTEM_WGETRC);
443 #endif
444   /* Override it with your own, if one exists.  */
445   file = wgetrc_file_name ();
446   if (!file)
447     return;
448   /* #### We should canonicalize `file' and SYSTEM_WGETRC with
449      something like realpath() before comparing them with `strcmp'  */
450 #ifdef SYSTEM_WGETRC
451   if (!strcmp (file, SYSTEM_WGETRC))
452     {
453       fprintf (stderr, _("\
454 %s: Warning: Both system and user wgetrc point to `%s'.\n"),
455                exec_name, file);
456     }
457   else
458 #endif
459     run_wgetrc (file);
460   xfree (file);
461   return;
462 }
463 \f
464 /* Remove dashes and underscores from S, modifying S in the
465    process. */
466
467 static void
468 dehyphen (char *s)
469 {
470   char *t = s;                  /* t - tortoise */
471   char *h = s;                  /* h - hare     */
472   while (*h)
473     if (*h == '_' || *h == '-')
474       ++h;
475     else
476       *t++ = *h++;
477   *t = '\0';
478 }
479
480 /* Parse the line pointed by line, with the syntax:
481    <sp>* command <sp>* = <sp>* value <sp>*
482    Uses malloc to allocate space for command and value.
483    If the line is invalid, data is freed and 0 is returned.
484
485    Return values:
486     1 - success
487     0 - error
488    -1 - empty
489
490    In case of success, *COM and *VAL point to freshly allocated
491    strings, and *COMIND points to com's index.  In case of error or
492    empty line, those values are unaffected.  */
493
494 static int
495 parse_line (const char *line, char **com, char **val, int *comind)
496 {
497   const char *p;
498   const char *end = line + strlen (line);
499   const char *cmdstart, *cmdend;
500   const char *valstart, *valend;
501
502   char *cmdcopy;
503   int ind;
504
505   /* Skip leading and trailing whitespace.  */
506   while (*line && ISSPACE (*line))
507     ++line;
508   while (end > line && ISSPACE (end[-1]))
509     --end;
510
511   /* Skip empty lines and comments.  */
512   if (!*line || *line == '#')
513     return -1;
514
515   p = line;
516
517   cmdstart = p;
518   while (p < end && (ISALPHA (*p) || *p == '_' || *p == '-'))
519     ++p;
520   cmdend = p;
521
522   /* Skip '=', as well as any space before or after it. */
523   while (p < end && ISSPACE (*p))
524     ++p;
525   if (p == end || *p != '=')
526     return 0;
527   ++p;
528   while (p < end && ISSPACE (*p))
529     ++p;
530
531   valstart = p;
532   valend   = end;
533
534   /* The line now known to be syntactically correct.  Check whether
535      the command is valid.  */
536   BOUNDED_TO_ALLOCA (cmdstart, cmdend, cmdcopy);
537   dehyphen (cmdcopy);
538   ind = command_by_name (cmdcopy);
539   if (ind == -1)
540     return 0;
541
542   /* The command is valid.  Now fill in the values and report success
543      to the caller.  */
544   *comind = ind;
545   *com = strdupdelim (cmdstart, cmdend);
546   *val = strdupdelim (valstart, valend);
547   return 1;
548 }
549
550 /* Run commands[comind].action. */
551
552 static int
553 setval_internal (int comind, const char *com, const char *val)
554 {
555   assert (0 <= comind && comind < countof (commands));
556   DEBUGP (("Setting %s (%d) to %s\n", com, comind, val));
557   return ((*commands[comind].action) (com, val, commands[comind].closure));
558 }
559
560 /* Run command COM with value VAL.  If running the command produces an
561    error, report the error and exit.
562
563    This is intended to be called from main() to modify Wget's behavior
564    through command-line switches.  Since COM is hard-coded in main(),
565    it is not canonicalized, and this aborts when COM is not found.
566
567    If COMIND's are exported to init.h, this function will be changed
568    to accept COMIND directly.  */
569
570 void
571 setoptval (const char *com, const char *val)
572 {
573   assert (val != NULL);
574   if (!setval_internal (command_by_name (com), com, val))
575     exit (2);
576 }
577
578 /* Parse OPT into command and value and run it.  For example,
579    run_command("foo=bar") is equivalent to setoptval("foo", "bar").
580    This is used by the `--execute' flag in main.c.  */
581
582 void
583 run_command (const char *opt)
584 {
585   char *com, *val;
586   int comind;
587   int status = parse_line (opt, &com, &val, &comind);
588   if (status == 1)
589     {
590       if (!setval_internal (comind, com, val))
591         exit (2);
592       xfree (com);
593       xfree (val);
594     }
595   else if (status == 0)
596     {
597       fprintf (stderr, _("%s: Invalid --execute command `%s'\n"),
598                exec_name, opt);
599       exit (2);
600     }
601 }
602 \f
603 /* Generic helper functions, for use with `commands'. */
604
605 #define CMP1(p, c0) (TOLOWER((p)[0]) == (c0) && (p)[1] == '\0')
606
607 #define CMP2(p, c0, c1) (TOLOWER((p)[0]) == (c0)        \
608                          && TOLOWER((p)[1]) == (c1)     \
609                          && (p)[2] == '\0')
610
611 #define CMP3(p, c0, c1, c2) (TOLOWER((p)[0]) == (c0)    \
612                      && TOLOWER((p)[1]) == (c1)         \
613                      && TOLOWER((p)[2]) == (c2)         \
614                      && (p)[3] == '\0')
615
616
617 /* Store the boolean value from VAL to CLOSURE.  COM is ignored,
618    except for error messages.  */
619 static int
620 cmd_boolean (const char *com, const char *val, void *closure)
621 {
622   int bool_value;
623
624   if (CMP2 (val, 'o', 'n') || CMP3 (val, 'y', 'e', 's') || CMP1 (val, '1'))
625     /* "on", "yes" and "1" mean true. */
626     bool_value = 1;
627   else if (CMP3 (val, 'o', 'f', 'f') || CMP2 (val, 'n', 'o') || CMP1 (val, '0'))
628     /* "off", "no" and "0" mean false. */
629     bool_value = 0;
630   else
631     {
632       fprintf (stderr,
633                _("%s: %s: Invalid boolean `%s', use `on' or `off'.\n"),
634                exec_name, com, val);
635       return 0;
636     }
637
638   *(int *)closure = bool_value;
639   return 1;
640 }
641
642 /* Store the lockable_boolean {2, 1, 0, -1} value from VAL to CLOSURE.
643    COM is ignored, except for error messages.  Values 2 and -1
644    indicate that once defined, the value may not be changed by
645    successive wgetrc files or command-line arguments.
646
647    Values: 2 - Enable a particular option for good ("always")
648            1 - Enable an option ("on")
649            0 - Disable an option ("off")
650           -1 - Disable an option for good ("never") */
651 static int
652 cmd_lockable_boolean (const char *com, const char *val, void *closure)
653 {
654   int lockable_boolean_value;
655
656   int oldval = *(int *)closure;
657
658   /*
659    * If a config file said "always" or "never", don't allow command line
660    * arguments to override the config file.
661    */
662   if (oldval == -1 || oldval == 2)
663     return 1;
664
665   if (0 == strcasecmp (val, "always") || CMP1 (val, '2'))
666     lockable_boolean_value = 2;
667   else if (CMP2 (val, 'o', 'n') || CMP3 (val, 'y', 'e', 's') || CMP1 (val, '1'))
668     lockable_boolean_value = 1;
669   else if (CMP3 (val, 'o', 'f', 'f') || CMP2 (val, 'n', 'o') || CMP1 (val, '0'))
670     lockable_boolean_value = 0;
671   else if (0 == strcasecmp (val, "never") || CMP2 (val, '-', '1'))
672     lockable_boolean_value = -1;
673   else
674     {
675       fprintf (stderr,
676                _("%s: %s: Invalid boolean `%s', use always, on, off, or never.\n"),
677                exec_name, com, val);
678       return 0;
679     }
680
681   *(int *)closure = lockable_boolean_value;
682   return 1;
683 }
684
685 static int simple_atoi PARAMS ((const char *, const char *, int *));
686
687 /* Set the non-negative integer value from VAL to CLOSURE.  With
688    incorrect specification, the number remains unchanged.  */
689 static int
690 cmd_number (const char *com, const char *val, void *closure)
691 {
692   if (!simple_atoi (val, val + strlen (val), closure)
693       || *(int *) closure < 0)
694     {
695       fprintf (stderr, _("%s: %s: Invalid number `%s'.\n"),
696                exec_name, com, val);
697       return 0;
698     }
699   return 1;
700 }
701
702 /* Similar to cmd_number(), only accepts `inf' as a synonym for 0.  */
703 static int
704 cmd_number_inf (const char *com, const char *val, void *closure)
705 {
706   if (!strcasecmp (val, "inf"))
707     {
708       *(int *)closure = 0;
709       return 1;
710     }
711   return cmd_number (com, val, closure);
712 }
713
714 /* Copy (strdup) the string at COM to a new location and place a
715    pointer to *CLOSURE.  */
716 static int
717 cmd_string (const char *com, const char *val, void *closure)
718 {
719   char **pstring = (char **)closure;
720
721   xfree_null (*pstring);
722   *pstring = xstrdup (val);
723   return 1;
724 }
725
726 #ifndef WINDOWS
727 # define ISSEP(c) ((c) == '/')
728 #else
729 # define ISSEP(c) ((c) == '/' || (c) == '\\')
730 #endif
731
732 /* Like the above, but handles tilde-expansion when reading a user's
733    `.wgetrc'.  In that case, and if VAL begins with `~', the tilde
734    gets expanded to the user's home directory.  */
735 static int
736 cmd_file (const char *com, const char *val, void *closure)
737 {
738   char **pstring = (char **)closure;
739
740   xfree_null (*pstring);
741
742   /* #### If VAL is empty, perhaps should set *CLOSURE to NULL.  */
743
744   if (!enable_tilde_expansion || !(*val == '~' && ISSEP (val[1])))
745     {
746     noexpand:
747       *pstring = xstrdup (val);
748     }
749   else
750     {
751       char *result;
752       int homelen;
753       char *home = home_dir ();
754       if (!home)
755         goto noexpand;
756
757       homelen = strlen (home);
758       while (homelen && ISSEP (home[homelen - 1]))
759         home[--homelen] = '\0';
760
761       /* Skip the leading "~/". */
762       for (++val; ISSEP (*val); val++)
763         ;
764
765       result = xmalloc (homelen + 1 + strlen (val) + 1);
766       memcpy (result, home, homelen);
767       result[homelen] = '/';
768       strcpy (result + homelen + 1, val);
769
770       *pstring = result;
771     }
772
773 #ifdef WINDOWS
774   /* Convert "\" to "/". */
775   {
776     char *s;
777     for (s = *pstring; *s; s++)
778       if (*s == '\\')
779         *s = '/';
780   }
781 #endif
782   return 1;
783 }
784
785 /* Like cmd_file, but strips trailing '/' characters.  */
786 static int
787 cmd_directory (const char *com, const char *val, void *closure)
788 {
789   char *s, *t;
790
791   /* Call cmd_file() for tilde expansion and separator
792      canonicalization (backslash -> slash under Windows).  These
793      things should perhaps be in a separate function.  */
794   if (!cmd_file (com, val, closure))
795     return 0;
796
797   s = *(char **)closure;
798   t = s + strlen (s);
799   while (t > s && *--t == '/')
800     *t = '\0';
801
802   return 1;
803 }
804
805 /* Split VAL by space to a vector of values, and append those values
806    to vector pointed to by the CLOSURE argument.  If VAL is empty, the
807    CLOSURE vector is cleared instead.  */
808
809 static int
810 cmd_vector (const char *com, const char *val, void *closure)
811 {
812   char ***pvec = (char ***)closure;
813
814   if (*val)
815     *pvec = merge_vecs (*pvec, sepstring (val));
816   else
817     {
818       free_vec (*pvec);
819       *pvec = NULL;
820     }
821   return 1;
822 }
823
824 static int
825 cmd_directory_vector (const char *com, const char *val, void *closure)
826 {
827   char ***pvec = (char ***)closure;
828
829   if (*val)
830     {
831       /* Strip the trailing slashes from directories.  */
832       char **t, **seps;
833
834       seps = sepstring (val);
835       for (t = seps; t && *t; t++)
836         {
837           int len = strlen (*t);
838           /* Skip degenerate case of root directory.  */
839           if (len > 1)
840             {
841               if ((*t)[len - 1] == '/')
842                 (*t)[len - 1] = '\0';
843             }
844         }
845       *pvec = merge_vecs (*pvec, seps);
846     }
847   else
848     {
849       free_vec (*pvec);
850       *pvec = NULL;
851     }
852   return 1;
853 }
854
855 static int simple_atof PARAMS ((const char *, const char *, double *));
856
857 /* Engine for cmd_bytes and cmd_bytes_large: converts a string such as
858    "100k" or "2.5G" to a floating point number.  */
859
860 static int
861 parse_bytes_helper (const char *val, double *result)
862 {
863   double number, mult;
864   const char *end = val + strlen (val);
865
866   /* Check for "inf".  */
867   if (0 == strcmp (val, "inf"))
868     {
869       *result = 0;
870       return 1;
871     }
872
873   /* Strip trailing whitespace.  */
874   while (val < end && ISSPACE (end[-1]))
875     --end;
876   if (val == end)
877     return 0;
878
879   switch (TOLOWER (end[-1]))
880     {
881     case 'k':
882       --end, mult = 1024.0;
883       break;
884     case 'm':
885       --end, mult = 1048576.0;
886       break;
887     case 'g':
888       --end, mult = 1073741824.0;
889       break;
890     case 't':
891       --end, mult = 1099511627776.0;
892       break;
893     default:
894       /* Not a recognized suffix: assume it's a digit.  (If not,
895          simple_atof will raise an error.)  */
896       mult = 1;
897     }
898
899   /* Skip leading and trailing whitespace. */
900   while (val < end && ISSPACE (*val))
901     ++val;
902   while (val < end && ISSPACE (end[-1]))
903     --end;
904   if (val == end)
905     return 0;
906
907   if (!simple_atof (val, end, &number) || number < 0)
908     return 0;
909
910   *result = number * mult;
911   return 1;
912 }
913
914 /* Parse VAL as a number and set its value to CLOSURE (which should
915    point to a wgint).
916
917    By default, the value is assumed to be in bytes.  If "K", "M", or
918    "G" are appended, the value is multiplied with 1<<10, 1<<20, or
919    1<<30, respectively.  Floating point values are allowed and are
920    cast to integer before use.  The idea is to be able to use things
921    like 1.5k instead of "1536".
922
923    The string "inf" is returned as 0.
924
925    In case of error, 0 is returned and memory pointed to by CLOSURE
926    remains unmodified.  */
927
928 static int
929 cmd_bytes (const char *com, const char *val, void *closure)
930 {
931   double byte_value;
932   if (!parse_bytes_helper (val, &byte_value))
933     {
934       fprintf (stderr, _("%s: %s: Invalid byte value `%s'\n"),
935                exec_name, com, val);
936       return 0;
937     }
938   *(wgint *)closure = (wgint)byte_value;
939   return 1;
940 }
941
942 /* Like cmd_bytes, but CLOSURE is interpreted as a pointer to
943    LARGE_INT.  It works by converting the string to double, therefore
944    working with values up to 2^53-1 without loss of precision.  This
945    value (8192 TB) is large enough to serve for a while.  */
946
947 static int
948 cmd_bytes_large (const char *com, const char *val, void *closure)
949 {
950   double byte_value;
951   if (!parse_bytes_helper (val, &byte_value))
952     {
953       fprintf (stderr, _("%s: %s: Invalid byte value `%s'\n"),
954                exec_name, com, val);
955       return 0;
956     }
957   *(LARGE_INT *)closure = (LARGE_INT)byte_value;
958   return 1;
959 }
960
961 /* Store the value of VAL to *OUT.  The value is a time period, by
962    default expressed in seconds, but also accepting suffixes "m", "h",
963    "d", and "w" for minutes, hours, days, and weeks respectively.  */
964
965 static int
966 cmd_time (const char *com, const char *val, void *closure)
967 {
968   double number, mult;
969   const char *end = val + strlen (val);
970
971   /* Strip trailing whitespace.  */
972   while (val < end && ISSPACE (end[-1]))
973     --end;
974
975   if (val == end)
976     {
977     err:
978       fprintf (stderr, _("%s: %s: Invalid time period `%s'\n"),
979                exec_name, com, val);
980       return 0;
981     }
982
983   switch (TOLOWER (end[-1]))
984     {
985     case 's':
986       --end, mult = 1;          /* seconds */
987       break;
988     case 'm':
989       --end, mult = 60;         /* minutes */
990       break;
991     case 'h':
992       --end, mult = 3600;       /* hours */
993       break;
994     case 'd':
995       --end, mult = 86400.0;    /* days */
996       break;
997     case 'w':
998       --end, mult = 604800.0;   /* weeks */
999       break;
1000     default:
1001       /* Not a recognized suffix: assume it belongs to the number.
1002          (If not, atof simple_atof will raise an error.)  */
1003       mult = 1;
1004     }
1005
1006   /* Skip leading and trailing whitespace. */
1007   while (val < end && ISSPACE (*val))
1008     ++val;
1009   while (val < end && ISSPACE (end[-1]))
1010     --end;
1011   if (val == end)
1012     goto err;
1013
1014   if (!simple_atof (val, end, &number))
1015     goto err;
1016
1017   *(double *)closure = number * mult;
1018   return 1;
1019 }
1020 \f
1021 /* Specialized helper functions, used by `commands' to handle some
1022    options specially.  */
1023
1024 static int check_user_specified_header PARAMS ((const char *));
1025
1026 static int
1027 cmd_spec_dirstruct (const char *com, const char *val, void *closure)
1028 {
1029   if (!cmd_boolean (com, val, &opt.dirstruct))
1030     return 0;
1031   /* Since dirstruct behaviour is explicitly changed, no_dirstruct
1032      must be affected inversely.  */
1033   if (opt.dirstruct)
1034     opt.no_dirstruct = 0;
1035   else
1036     opt.no_dirstruct = 1;
1037   return 1;
1038 }
1039
1040 static int
1041 cmd_spec_header (const char *com, const char *val, void *closure)
1042 {
1043   if (!check_user_specified_header (val))
1044     {
1045       fprintf (stderr, _("%s: %s: Invalid header `%s'.\n"),
1046                exec_name, com, val);
1047       return 0;
1048     }
1049   return cmd_vector (com, val, closure);
1050 }
1051
1052 static int
1053 cmd_spec_htmlify (const char *com, const char *val, void *closure)
1054 {
1055   int flag = cmd_boolean (com, val, &opt.htmlify);
1056   if (flag && !opt.htmlify)
1057     opt.remove_listing = 0;
1058   return flag;
1059 }
1060
1061 /* Set the "mirror" mode.  It means: recursive download, timestamping,
1062    no limit on max. recursion depth, and don't remove listings.  */
1063
1064 static int
1065 cmd_spec_mirror (const char *com, const char *val, void *closure)
1066 {
1067   int mirror;
1068
1069   if (!cmd_boolean (com, val, &mirror))
1070     return 0;
1071   if (mirror)
1072     {
1073       opt.recursive = 1;
1074       if (!opt.no_dirstruct)
1075         opt.dirstruct = 1;
1076       opt.timestamping = 1;
1077       opt.reclevel = INFINITE_RECURSION;
1078       opt.remove_listing = 0;
1079     }
1080   return 1;
1081 }
1082
1083 /* Set progress.type to VAL, but verify that it's a valid progress
1084    implementation before that.  */
1085
1086 static int
1087 cmd_spec_progress (const char *com, const char *val, void *closure)
1088 {
1089   if (!valid_progress_implementation_p (val))
1090     {
1091       fprintf (stderr, _("%s: %s: Invalid progress type `%s'.\n"),
1092                exec_name, com, val);
1093       return 0;
1094     }
1095   xfree_null (opt.progress_type);
1096
1097   /* Don't call set_progress_implementation here.  It will be called
1098      in main() when it becomes clear what the log output is.  */
1099   opt.progress_type = xstrdup (val);
1100   return 1;
1101 }
1102
1103 /* Set opt.recursive to VAL as with cmd_boolean.  If opt.recursive is
1104    set to true, also set opt.dirstruct to 1, unless opt.no_dirstruct
1105    is specified.  */
1106
1107 static int
1108 cmd_spec_recursive (const char *com, const char *val, void *closure)
1109 {
1110   if (!cmd_boolean (com, val, &opt.recursive))
1111     return 0;
1112   else
1113     {
1114       if (opt.recursive && !opt.no_dirstruct)
1115         opt.dirstruct = 1;
1116     }
1117   return 1;
1118 }
1119
1120 static int
1121 cmd_spec_restrict_file_names (const char *com, const char *val, void *closure)
1122 {
1123   int restrict_os = opt.restrict_files_os;
1124   int restrict_ctrl = opt.restrict_files_ctrl;
1125
1126   const char *end = strchr (val, ',');
1127   if (!end)
1128     end = val + strlen (val);
1129
1130 #define VAL_IS(string_literal) BOUNDED_EQUAL (val, end, string_literal)
1131
1132   if (VAL_IS ("unix"))
1133     restrict_os = restrict_unix;
1134   else if (VAL_IS ("windows"))
1135     restrict_os = restrict_windows;
1136   else if (VAL_IS ("nocontrol"))
1137     restrict_ctrl = 0;
1138   else
1139     {
1140     err:
1141       fprintf (stderr,
1142                _("%s: %s: Invalid restriction `%s', use `unix' or `windows'.\n"),
1143                exec_name, com, val);
1144       return 0;
1145     }
1146
1147 #undef VAL_IS
1148
1149   if (*end)
1150     {
1151       if (!strcmp (end + 1, "nocontrol"))
1152         restrict_ctrl = 0;
1153       else
1154         goto err;
1155     }
1156
1157   opt.restrict_files_os = restrict_os;
1158   opt.restrict_files_ctrl = restrict_ctrl;
1159   return 1;
1160 }
1161
1162 /* Set all three timeout values. */
1163
1164 static int
1165 cmd_spec_timeout (const char *com, const char *val, void *closure)
1166 {
1167   double value;
1168   if (!cmd_time (com, val, &value))
1169     return 0;
1170   opt.read_timeout = value;
1171   opt.connect_timeout = value;
1172   opt.dns_timeout = value;
1173   return 1;
1174 }
1175
1176 static int
1177 cmd_spec_useragent (const char *com, const char *val, void *closure)
1178 {
1179   /* Just check for empty string and newline, so we don't throw total
1180      junk to the server.  */
1181   if (!*val || strchr (val, '\n'))
1182     {
1183       fprintf (stderr, _("%s: %s: Invalid value `%s'.\n"),
1184                exec_name, com, val);
1185       return 0;
1186     }
1187   opt.useragent = xstrdup (val);
1188   return 1;
1189 }
1190 \f
1191 /* Miscellaneous useful routines.  */
1192
1193 /* A very simple atoi clone, more useful than atoi because it works on
1194    delimited strings, and has error reportage.  Returns 1 on success,
1195    0 on failure.  If successful, stores result to *DEST.  */
1196
1197 static int
1198 simple_atoi (const char *beg, const char *end, int *dest)
1199 {
1200   int result = 0;
1201   int negative = 0;
1202   const char *p = beg;
1203
1204   while (p < end && ISSPACE (*p))
1205     ++p;
1206   if (p < end && (*p == '-' || *p == '+'))
1207     {
1208       negative = (*p == '-');
1209       ++p;
1210     }
1211   if (p == end)
1212     return 0;
1213
1214   /* Read negative numbers in a separate loop because the most
1215      negative integer cannot be represented as a positive number.  */
1216
1217   if (!negative)
1218     for (; p < end && ISDIGIT (*p); p++)
1219       {
1220         int next = (10 * result) + (*p - '0');
1221         if (next < result)
1222           return 0;             /* overflow */
1223         result = next;
1224       }
1225   else
1226     for (; p < end && ISDIGIT (*p); p++)
1227       {
1228         int next = (10 * result) - (*p - '0');
1229         if (next > result)
1230           return 0;             /* underflow */
1231         result = next;
1232       }
1233
1234   if (p != end)
1235     return 0;
1236
1237   *dest = result;
1238   return 1;
1239 }
1240
1241 /* Trivial atof, with error reporting.  Handles "<digits>[.<digits>]",
1242    doesn't handle exponential notation.  Returns 1 on success, 0 on
1243    failure.  In case of success, stores its result to *DEST.  */
1244
1245 static int
1246 simple_atof (const char *beg, const char *end, double *dest)
1247 {
1248   double result = 0;
1249
1250   int negative = 0;
1251   int seen_dot = 0;
1252   int seen_digit = 0;
1253   double divider = 1;
1254
1255   const char *p = beg;
1256
1257   while (p < end && ISSPACE (*p))
1258     ++p;
1259   if (p < end && (*p == '-' || *p == '+'))
1260     {
1261       negative = (*p == '-');
1262       ++p;
1263     }
1264
1265   for (; p < end; p++)
1266     {
1267       char ch = *p;
1268       if (ISDIGIT (ch))
1269         {
1270           if (!seen_dot)
1271             result = (10 * result) + (ch - '0');
1272           else
1273             result += (ch - '0') / (divider *= 10);
1274           seen_digit = 1;
1275         }
1276       else if (ch == '.')
1277         {
1278           if (!seen_dot)
1279             seen_dot = 1;
1280           else
1281             return 0;
1282         }
1283       else
1284         return 0;
1285     }
1286   if (!seen_digit)
1287     return 0;
1288   if (negative)
1289     result = -result;
1290
1291   *dest = result;
1292   return 1;
1293 }
1294
1295 static int
1296 check_user_specified_header (const char *s)
1297 {
1298   const char *p;
1299
1300   for (p = s; *p && *p != ':' && !ISSPACE (*p); p++);
1301   /* The header MUST contain `:' preceded by at least one
1302      non-whitespace character.  */
1303   if (*p != ':' || p == s)
1304     return 0;
1305   /* The header MUST NOT contain newlines.  */
1306   if (strchr (s, '\n'))
1307     return 0;
1308   return 1;
1309 }
1310 \f
1311 void cleanup_html_url PARAMS ((void));
1312 void res_cleanup PARAMS ((void));
1313 void downloaded_files_free PARAMS ((void));
1314 void http_cleanup PARAMS ((void));
1315
1316
1317 /* Free the memory allocated by global variables.  */
1318 void
1319 cleanup (void)
1320 {
1321   /* Free external resources, close files, etc. */
1322
1323   {
1324     extern FILE *output_stream;
1325     if (output_stream)
1326       fclose (output_stream);
1327     /* No need to check for error because Wget flushes its output (and
1328        checks for errors) after any data arrives.  */
1329   }
1330
1331   /* We're exiting anyway so there's no real need to call free()
1332      hundreds of times.  Skipping the frees will make Wget exit
1333      faster.
1334
1335      However, when detecting leaks, it's crucial to free() everything
1336      because then you can find the real leaks, i.e. the allocated
1337      memory which grows with the size of the program.  */
1338
1339 #ifdef DEBUG_MALLOC
1340   convert_cleanup ();
1341   res_cleanup ();
1342   http_cleanup ();
1343   cleanup_html_url ();
1344   downloaded_files_free ();
1345   host_cleanup ();
1346   if (wget_cookie_jar)
1347     cookie_jar_delete (wget_cookie_jar);
1348
1349   {
1350     extern acc_t *netrc_list;
1351     free_netrc (netrc_list);
1352   }
1353   xfree_null (opt.lfilename);
1354   xfree_null (opt.dir_prefix);
1355   xfree_null (opt.input_filename);
1356   xfree_null (opt.output_document);
1357   free_vec (opt.accepts);
1358   free_vec (opt.rejects);
1359   free_vec (opt.excludes);
1360   free_vec (opt.includes);
1361   free_vec (opt.domains);
1362   free_vec (opt.follow_tags);
1363   free_vec (opt.ignore_tags);
1364   xfree_null (opt.progress_type);
1365   xfree (opt.ftp_acc);
1366   xfree_null (opt.ftp_pass);
1367   xfree_null (opt.ftp_proxy);
1368   xfree_null (opt.https_proxy);
1369   xfree_null (opt.http_proxy);
1370   free_vec (opt.no_proxy);
1371   xfree_null (opt.useragent);
1372   xfree_null (opt.referer);
1373   xfree_null (opt.http_user);
1374   xfree_null (opt.http_passwd);
1375   xfree_null (opt.user_header);
1376 #ifdef HAVE_SSL
1377   xfree_null (opt.sslcertkey);
1378   xfree_null (opt.sslcertfile);
1379 #endif /* HAVE_SSL */
1380   xfree_null (opt.bind_address);
1381   xfree_null (opt.cookies_input);
1382   xfree_null (opt.cookies_output);
1383 #endif
1384 }