]> sjero.net Git - wget/blob - src/main.c
[svn] New option --keep-session-cookies.
[wget] / src / main.c
1 /* Command line parsing.
2    Copyright (C) 1995, 1996, 1997, 1998, 2000, 2001, 2002
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 <stdlib.h>
35 #ifdef HAVE_UNISTD_H
36 # include <unistd.h>
37 #endif /* HAVE_UNISTD_H */
38 #include <sys/types.h>
39 #ifdef HAVE_STRING_H
40 # include <string.h>
41 #else
42 # include <strings.h>
43 #endif /* HAVE_STRING_H */
44 #ifdef HAVE_SIGNAL_H
45 # include <signal.h>
46 #endif
47 #ifdef HAVE_NLS
48 #ifdef HAVE_LOCALE_H
49 # include <locale.h>
50 #endif /* HAVE_LOCALE_H */
51 #endif /* HAVE_NLS */
52 #include <errno.h>
53 #ifndef errno
54 extern int errno;
55 #endif
56
57 #include "wget.h"
58 #include "utils.h"
59 #include "init.h"
60 #include "retr.h"
61 #include "recur.h"
62 #include "host.h"
63 #include "cookies.h"
64 #include "url.h"
65 #include "progress.h"           /* for progress_handle_sigwinch */
66 #include "convert.h"
67
68 #ifdef HAVE_SSL
69 # include "gen_sslfunc.h"
70 #endif
71
72 /* On GNU system this will include system-wide getopt.h. */
73 #include "getopt.h"
74
75 #ifndef PATH_SEPARATOR
76 # define PATH_SEPARATOR '/'
77 #endif
78
79 struct options opt;
80
81 extern LARGE_INT total_downloaded_bytes;
82 extern char *version_string;
83
84 extern struct cookie_jar *wget_cookie_jar;
85
86 /* From log.c.  */
87 void log_init PARAMS ((const char *, int));
88 void log_close PARAMS ((void));
89 void log_request_redirect_output PARAMS ((const char *));
90
91 static RETSIGTYPE redirect_output_signal PARAMS ((int));
92
93 const char *exec_name;
94 \f
95 /* Initialize I18N.  The initialization amounts to invoking
96    setlocale(), bindtextdomain() and textdomain().
97    Does nothing if NLS is disabled or missing.  */
98 static void
99 i18n_initialize (void)
100 {
101   /* If HAVE_NLS is defined, assume the existence of the three
102      functions invoked here.  */
103 #ifdef HAVE_NLS
104   /* Set the current locale.  */
105   /* Here we use LC_MESSAGES instead of LC_ALL, for two reasons.
106      First, message catalogs are all of I18N Wget uses anyway.
107      Second, setting LC_ALL has a dangerous potential of messing
108      things up.  For example, when in a foreign locale, Solaris
109      strptime() fails to handle international dates correctly, which
110      makes http_atotm() malfunction.  */
111 #ifdef LC_MESSAGES
112   setlocale (LC_MESSAGES, "");
113   setlocale (LC_CTYPE, "");
114 #else
115   setlocale (LC_ALL, "");
116 #endif
117   /* Set the text message domain.  */
118   bindtextdomain ("wget", LOCALEDIR);
119   textdomain ("wget");
120 #endif /* HAVE_NLS */
121 }
122 \f
123 /* Print the usage message.  */
124 static void
125 print_usage (void)
126 {
127   printf (_("Usage: %s [OPTION]... [URL]...\n"), exec_name);
128 }
129
130 /* Print the help message, describing all the available options.  If
131    you add an option, be sure to update this list.  */
132 static void
133 print_help (void)
134 {
135   printf (_("GNU Wget %s, a non-interactive network retriever.\n"),
136           version_string);
137   print_usage ();
138   /* Had to split this in parts, so the #@@#%# Ultrix compiler and cpp
139      don't bitch.  Also, it makes translation much easier.  */
140   fputs (_("\
141 \n\
142 Mandatory arguments to long options are mandatory for short options too.\n\
143 \n"), stdout);
144   fputs (_("\
145 Startup:\n\
146   -V,  --version           display the version of Wget and exit.\n\
147   -h,  --help              print this help.\n\
148   -b,  --background        go to background after startup.\n\
149   -e,  --execute=COMMAND   execute a `.wgetrc\'-style command.\n\
150 \n"), stdout);
151   fputs (_("\
152 Logging and input file:\n\
153   -o,  --output-file=FILE     log messages to FILE.\n\
154   -a,  --append-output=FILE   append messages to FILE.\n\
155   -d,  --debug                print debug output.\n\
156   -q,  --quiet                quiet (no output).\n\
157   -v,  --verbose              be verbose (this is the default).\n\
158   -nv, --non-verbose          turn off verboseness, without being quiet.\n\
159   -i,  --input-file=FILE      download URLs found in FILE.\n\
160   -F,  --force-html           treat input file as HTML.\n\
161   -B,  --base=URL             prepends URL to relative links in -F -i file.\n\
162 \n"),stdout);
163   fputs (_("\
164 Download:\n\
165   -t,  --tries=NUMBER           set number of retries to NUMBER (0 unlimits).\n\
166        --retry-connrefused      retry even if connection is refused.\n\
167   -O   --output-document=FILE   write documents to FILE.\n\
168   -nc, --no-clobber             don\'t clobber existing files or use .# suffixes.\n\
169   -c,  --continue               resume getting a partially-downloaded file.\n\
170        --progress=TYPE          select progress gauge type.\n\
171   -N,  --timestamping           don\'t re-retrieve files unless newer than local.\n\
172   -S,  --server-response        print server response.\n\
173        --spider                 don\'t download anything.\n\
174   -T,  --timeout=SECONDS        set all timeout values to SECONDS.\n\
175        --dns-timeout=SECS       set the DNS lookup timeout to SECS.\n\
176        --connect-timeout=SECS   set the connect timeout to SECS.\n\
177        --read-timeout=SECS      set the read timeout to SECS.\n\
178   -w,  --wait=SECONDS           wait SECONDS between retrievals.\n\
179        --waitretry=SECONDS      wait 1...SECONDS between retries of a retrieval.\n\
180        --random-wait            wait from 0...2*WAIT secs between retrievals.\n\
181   -Y,  --proxy=on/off           turn proxy on or off.\n\
182   -Q,  --quota=NUMBER           set retrieval quota to NUMBER.\n\
183        --bind-address=ADDRESS   bind to ADDRESS (hostname or IP) on local host.\n\
184        --limit-rate=RATE        limit download rate to RATE.\n\
185        --dns-cache=off          disable caching DNS lookups.\n\
186        --restrict-file-names=OS restrict chars in file names to ones OS allows.\n\
187 \n"), stdout);
188   fputs (_("\
189 Directories:\n\
190   -nd, --no-directories            don\'t create directories.\n\
191   -x,  --force-directories         force creation of directories.\n\
192   -nH, --no-host-directories       don\'t create host directories.\n\
193   -P,  --directory-prefix=PREFIX   save files to PREFIX/...\n\
194        --cut-dirs=NUMBER           ignore NUMBER remote directory components.\n\
195 \n"), stdout);
196   fputs (_("\
197 HTTP options:\n\
198        --http-user=USER      set http user to USER.\n\
199        --http-passwd=PASS    set http password to PASS.\n\
200   -C,  --cache=on/off        (dis)allow server-cached data (normally allowed).\n\
201   -E,  --html-extension      save all text/html documents with .html extension.\n\
202        --ignore-length       ignore `Content-Length\' header field.\n\
203        --header=STRING       insert STRING among the headers.\n\
204        --proxy-user=USER     set USER as proxy username.\n\
205        --proxy-passwd=PASS   set PASS as proxy password.\n\
206        --referer=URL         include `Referer: URL\' header in HTTP request.\n\
207   -s,  --save-headers        save the HTTP headers to file.\n\
208   -U,  --user-agent=AGENT    identify as AGENT instead of Wget/VERSION.\n\
209        --no-http-keep-alive  disable HTTP keep-alive (persistent connections).\n\
210        --cookies=off         don't use cookies.\n\
211        --load-cookies=FILE   load cookies from FILE before session.\n\
212        --save-cookies=FILE   save cookies to FILE after session.\n\
213        --keep-session-cookies  load and save session (non-permanent) cookies.\n\
214        --post-data=STRING    use the POST method; send STRING as the data.\n\
215        --post-file=FILE      use the POST method; send contents of FILE.\n\
216 \n"), stdout);
217 #ifdef HAVE_SSL
218   fputs (_("\
219 HTTPS (SSL) options:\n\
220        --sslcertfile=FILE     optional client certificate.\n\
221        --sslcertkey=KEYFILE   optional keyfile for this certificate.\n\
222        --egd-file=FILE        file name of the EGD socket.\n\
223        --sslcadir=DIR         dir where hash list of CA's are stored.\n\
224        --sslcafile=FILE       file with bundle of CA's\n\
225        --sslcerttype=0/1      Client-Cert type 0=PEM (default) / 1=ASN1 (DER)\n\
226        --sslcheckcert=0/1     Check the server cert agenst given CA\n\
227        --sslprotocol=0-3      choose SSL protocol; 0=automatic,\n\
228                               1=SSLv2 2=SSLv3 3=TLSv1\n\
229 \n"), stdout);
230 #endif
231   fputs (_("\
232 FTP options:\n\
233   -nr, --dont-remove-listing   don\'t remove `.listing\' files.\n\
234   -g,  --glob=on/off           turn file name globbing on or off.\n\
235        --passive-ftp           use the \"passive\" transfer mode.\n\
236        --retr-symlinks         when recursing, get linked-to files (not dirs).\n\
237 \n"), stdout);
238   fputs (_("\
239 Recursive retrieval:\n\
240   -r,  --recursive          recursive download.\n\
241   -l,  --level=NUMBER       maximum recursion depth (inf or 0 for infinite).\n\
242        --delete-after       delete files locally after downloading them.\n\
243   -k,  --convert-links      convert non-relative links to relative.\n\
244   -K,  --backup-converted   before converting file X, back up as X.orig.\n\
245   -m,  --mirror             shortcut option equivalent to -r -N -l inf -nr.\n\
246   -p,  --page-requisites    get all images, etc. needed to display HTML page.\n\
247        --strict-comments    turn on strict (SGML) handling of HTML comments.\n\
248 \n"), stdout);
249   fputs (_("\
250 Recursive accept/reject:\n\
251   -A,  --accept=LIST                comma-separated list of accepted extensions.\n\
252   -R,  --reject=LIST                comma-separated list of rejected extensions.\n\
253   -D,  --domains=LIST               comma-separated list of accepted domains.\n\
254        --exclude-domains=LIST       comma-separated list of rejected domains.\n\
255        --follow-ftp                 follow FTP links from HTML documents.\n\
256        --follow-tags=LIST           comma-separated list of followed HTML tags.\n\
257   -G,  --ignore-tags=LIST           comma-separated list of ignored HTML tags.\n\
258   -H,  --span-hosts                 go to foreign hosts when recursive.\n\
259   -L,  --relative                   follow relative links only.\n\
260   -I,  --include-directories=LIST   list of allowed directories.\n\
261   -X,  --exclude-directories=LIST   list of excluded directories.\n\
262   -np, --no-parent                  don\'t ascend to the parent directory.\n\
263 \n"), stdout);
264   fputs (_("Mail bug reports and suggestions to <bug-wget@gnu.org>.\n"),
265          stdout);
266 }
267 \f
268 int
269 main (int argc, char *const *argv)
270 {
271   char **url, **t;
272   int i, c, nurl, status, append_to_log;
273
274   static struct option long_options[] =
275   {
276     /* Options without arguments: */
277     { "background", no_argument, NULL, 'b' },
278     { "backup-converted", no_argument, NULL, 'K' },
279     { "continue", no_argument, NULL, 'c' },
280     { "convert-links", no_argument, NULL, 'k' },
281     { "debug", no_argument, NULL, 'd' },
282     { "delete-after", no_argument, NULL, 136 },
283     { "dont-remove-listing", no_argument, NULL, 149 },
284     { "follow-ftp", no_argument, NULL, 142 },
285     { "force-directories", no_argument, NULL, 'x' },
286     { "force-hier", no_argument, NULL, 'x' }, /* obsolete */
287     { "force-html", no_argument, NULL, 'F'},
288     { "help", no_argument, NULL, 'h' },
289     { "html-extension", no_argument, NULL, 'E' },
290     { "ignore-length", no_argument, NULL, 138 },
291     { "keep-session-cookies", no_argument, NULL, 181 },
292     { "mirror", no_argument, NULL, 'm' },
293     { "no-clobber", no_argument, NULL, 141 },
294     { "no-directories", no_argument, NULL, 147 },
295     { "no-host-directories", no_argument, NULL, 148 },
296     { "no-host-lookup", no_argument, NULL, 150 },
297     { "no-http-keep-alive", no_argument, NULL, 156 },
298     { "no-parent", no_argument, NULL, 133 },
299     { "non-verbose", no_argument, NULL, 146 },
300     { "passive-ftp", no_argument, NULL, 139 },
301     { "page-requisites", no_argument, NULL, 'p' },
302     { "quiet", no_argument, NULL, 'q' },
303     { "random-wait", no_argument, NULL, 165 },
304     { "recursive", no_argument, NULL, 'r' },
305     { "relative", no_argument, NULL, 'L' },
306     { "retr-symlinks", no_argument, NULL, 137 },
307     { "retry-connrefused", no_argument, NULL, 174 },
308     { "save-headers", no_argument, NULL, 's' },
309     { "server-response", no_argument, NULL, 'S' },
310     { "span-hosts", no_argument, NULL, 'H' },
311     { "spider", no_argument, NULL, 132 },
312     { "strict-comments", no_argument, NULL, 177 },
313     { "timestamping", no_argument, NULL, 'N' },
314     { "verbose", no_argument, NULL, 'v' },
315     { "version", no_argument, NULL, 'V' },
316
317     /* Options accepting an argument: */
318     { "accept", required_argument, NULL, 'A' },
319     { "append-output", required_argument, NULL, 'a' },
320     { "backups", required_argument, NULL, 151 }, /* undocumented */
321     { "base", required_argument, NULL, 'B' },
322     { "bind-address", required_argument, NULL, 155 },
323     { "cache", required_argument, NULL, 'C' },
324     { "connect-timeout", required_argument, NULL, 180 },
325     { "cookies", required_argument, NULL, 160 },
326     { "cut-dirs", required_argument, NULL, 145 },
327     { "dns-timeout", required_argument, NULL, 178 },
328     { "directory-prefix", required_argument, NULL, 'P' },
329     { "dns-cache", required_argument, NULL, 175 },
330     { "domains", required_argument, NULL, 'D' },
331     { "dot-style", required_argument, NULL, 134 },
332     { "execute", required_argument, NULL, 'e' },
333     { "exclude-directories", required_argument, NULL, 'X' },
334     { "exclude-domains", required_argument, NULL, 140 },
335     { "follow-tags", required_argument, NULL, 153 },
336     { "glob", required_argument, NULL, 'g' },
337     { "header", required_argument, NULL, 131 },
338     { "htmlify", required_argument, NULL, 135 },
339     { "http-passwd", required_argument, NULL, 130 },
340     { "http-user", required_argument, NULL, 129 },
341     { "ignore-tags", required_argument, NULL, 'G' },
342     { "include-directories", required_argument, NULL, 'I' },
343     { "input-file", required_argument, NULL, 'i' },
344     { "level", required_argument, NULL, 'l' },
345     { "limit-rate", required_argument, NULL, 164 },
346     { "load-cookies", required_argument, NULL, 161 },
347     { "no", required_argument, NULL, 'n' },
348     { "output-document", required_argument, NULL, 'O' },
349     { "output-file", required_argument, NULL, 'o' },
350     { "post-data", required_argument, NULL, 167 },
351     { "post-file", required_argument, NULL, 168 },
352     { "progress", required_argument, NULL, 163 },
353     { "proxy", required_argument, NULL, 'Y' },
354     { "proxy-passwd", required_argument, NULL, 144 },
355     { "proxy-user", required_argument, NULL, 143 },
356     { "quota", required_argument, NULL, 'Q' },
357     { "read-timeout", required_argument, NULL, 179 },
358     { "reject", required_argument, NULL, 'R' },
359     { "restrict-file-names", required_argument, NULL, 176 },
360     { "save-cookies", required_argument, NULL, 162 },
361     { "timeout", required_argument, NULL, 'T' },
362     { "tries", required_argument, NULL, 't' },
363     { "user-agent", required_argument, NULL, 'U' },
364     { "referer", required_argument, NULL, 157 },
365     { "use-proxy", required_argument, NULL, 'Y' },
366 #ifdef HAVE_SSL
367     { "sslcertfile", required_argument, NULL, 158 },
368     { "sslcertkey", required_argument, NULL, 159 },
369     { "egd-file", required_argument, NULL, 166 },
370     { "sslcadir",         required_argument, NULL, 169},
371     { "sslcafile",        required_argument, NULL, 170},
372     { "sslcerttype",      required_argument, NULL, 171},
373     { "sslcheckcert",     required_argument, NULL, 172},
374     { "sslprotocol",      required_argument, NULL, 173},
375 #endif /* HAVE_SSL */
376     { "wait", required_argument, NULL, 'w' },
377     { "waitretry", required_argument, NULL, 152 },
378     { 0, 0, 0, 0 }
379   };
380
381   i18n_initialize ();
382
383   append_to_log = 0;
384
385   /* Construct the name of the executable, without the directory part.  */
386   exec_name = strrchr (argv[0], PATH_SEPARATOR);
387   if (!exec_name)
388     exec_name = argv[0];
389   else
390     ++exec_name;
391
392 #ifdef WINDOWS
393   windows_main_junk (&argc, (char **) argv, (char **) &exec_name);
394 #endif
395
396   initialize (); /* sets option defaults; reads the system wgetrc and .wgetrc */
397
398   /* [Is the order of the option letters significant?  If not, they should be
399       alphabetized, like the long_options.  The only thing I know for sure is
400       that the options with required arguments must be followed by a ':'.
401       -- Dan Harkless <wget@harkless.org>] */
402   while ((c = getopt_long (argc, argv, "\
403 hpVqvdkKsxmNWrHSLcFbEY:G:g:T:U:O:l:n:i:o:a:t:D:A:R:P:B:e:Q:X:I:w:C:",
404                            long_options, (int *)0)) != EOF)
405     {
406       switch (c)
407         {
408           /* Options without arguments: */
409         case 132:
410           setoptval ("spider", "on");
411           break;
412         case 133:
413           setoptval ("noparent", "on");
414           break;
415         case 136:
416           setoptval ("deleteafter", "on");
417           break;
418         case 137:
419           setoptval ("retrsymlinks", "on");
420           break;
421         case 138:
422           setoptval ("ignorelength", "on");
423           break;
424         case 139:
425           setoptval ("passiveftp", "on");
426           break;
427         case 141:
428           setoptval ("noclobber", "on");
429           break;
430         case 142:
431           setoptval ("followftp", "on");
432           break;
433         case 145:
434           setoptval ("cutdirs", optarg);
435           break;
436         case 146:
437           setoptval ("verbose", "off");
438           break;
439         case 147:
440           setoptval ("dirstruct", "off");
441           break;
442         case 148:
443           setoptval ("addhostdir", "off");
444           break;
445         case 149:
446           setoptval ("removelisting", "off");
447           break;
448         case 155:
449           setoptval ("bindaddress", optarg);
450           break;
451         case 156:
452           setoptval ("httpkeepalive", "off");
453           break;
454         case 165:
455           setoptval ("randomwait", "on");
456           break;
457         case 'b':
458           setoptval ("background", "on");
459           break;
460         case 'c':
461           setoptval ("continue", "on");
462           break;
463         case 'd':
464 #ifdef ENABLE_DEBUG
465           setoptval ("debug", "on");
466 #else
467           fprintf (stderr, _("%s: debug support not compiled in.\n"),
468                    exec_name);
469 #endif
470           break;
471         case 'E':
472           setoptval ("htmlextension", "on");
473           break;
474         case 'F':
475           setoptval ("forcehtml", "on");
476           break;
477         case 'H':
478           setoptval ("spanhosts", "on");
479           break;
480         case 'h':
481           print_help ();
482 #ifdef WINDOWS
483           ws_help (exec_name);
484 #endif
485           exit (0);
486           break;
487         case 'K':
488           setoptval ("backupconverted", "on");
489           break;
490         case 'k':
491           setoptval ("convertlinks", "on");
492           break;
493         case 'L':
494           setoptval ("relativeonly", "on");
495           break;
496         case 'm':
497           setoptval ("mirror", "on");
498           break;
499         case 'N':
500           setoptval ("timestamping", "on");
501           break;
502         case 'p':
503           setoptval ("pagerequisites", "on");
504           break;
505         case 'S':
506           setoptval ("serverresponse", "on");
507           break;
508         case 's':
509           setoptval ("saveheaders", "on");
510           break;
511         case 'q':
512           setoptval ("quiet", "on");
513           break;
514         case 'r':
515           setoptval ("recursive", "on");
516           break;
517         case 'V':
518           printf ("GNU Wget %s\n\n", version_string);
519           printf ("%s", _("\
520 Copyright (C) 2003 Free Software Foundation, Inc.\n"));
521           printf ("%s", _("\
522 This program is distributed in the hope that it will be useful,\n\
523 but WITHOUT ANY WARRANTY; without even the implied warranty of\n\
524 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\
525 GNU General Public License for more details.\n"));
526           printf (_("\nOriginally written by Hrvoje Niksic <hniksic@xemacs.org>.\n"));
527           exit (0);
528           break;
529         case 'v':
530           setoptval ("verbose", "on");
531           break;
532         case 'x':
533           setoptval ("dirstruct", "on");
534           break;
535         case 174:
536           setoptval ("retryconnrefused", "on");
537           break;
538         case 177:
539           setoptval ("strictcomments", "on");
540           break;
541         case 181:
542           setoptval ("keepsessioncookies", "on");
543           break;
544
545           /* Options accepting an argument: */
546         case 129:
547           setoptval ("httpuser", optarg);
548           break;
549         case 130:
550           setoptval ("httppasswd", optarg);
551           break;
552         case 131:
553           setoptval ("header", optarg);
554           break;
555         case 134:
556           setoptval ("dotstyle", optarg);
557           break;
558         case 135:
559           setoptval ("htmlify", optarg);
560           break;
561         case 140:
562           setoptval ("excludedomains", optarg);
563           break;
564         case 143:
565           setoptval ("proxyuser", optarg);
566           break;
567         case 144:
568           setoptval ("proxypasswd", optarg);
569           break;
570         case 151:
571           setoptval ("backups", optarg);
572           break;
573         case 152:
574           setoptval ("waitretry", optarg);
575           break;
576         case 153:
577           setoptval ("followtags", optarg);
578           break;
579         case 160:
580           setoptval ("cookies", optarg);
581           break;
582         case 161:
583           setoptval ("loadcookies", optarg);
584           break;
585         case 162:
586           setoptval ("savecookies", optarg);
587           break;
588         case 163:
589           setoptval ("progress", optarg);
590           break;
591         case 164:
592           setoptval ("limitrate", optarg);
593           break;
594         case 157:
595           setoptval ("referer", optarg);
596           break;
597 #ifdef HAVE_SSL
598         case 158:
599           setoptval ("sslcertfile", optarg);
600           break;
601         case 159:
602           setoptval ("sslcertkey", optarg);
603           break;
604         case 166:
605           setoptval ("egdfile", optarg);
606           break;
607         case 169:
608           setoptval ("sslcadir", optarg);
609           break;
610         case 170:
611           setoptval ("sslcafile", optarg);
612           break;
613         case 171:
614           setoptval ("sslcerttype", optarg);
615           break;
616         case 172:
617           setoptval ("sslcheckcert", optarg);
618           break;
619         case 173:
620           setoptval ("sslprotocol", optarg);
621           break;
622 #endif /* HAVE_SSL */
623         case 167:
624           setoptval ("postdata", optarg);
625           break;
626         case 168:
627           setoptval ("postfile", optarg);
628           break;
629         case 175:
630           setoptval ("dnscache", optarg);
631           break;
632         case 176:
633           setoptval ("restrictfilenames", optarg);
634           break;
635         case 178:
636           setoptval ("dnstimeout", optarg);
637           break;
638         case 179:
639           setoptval ("readtimeout", optarg);
640           break;
641         case 180:
642           setoptval ("connecttimeout", optarg);
643           break;
644         case 'A':
645           setoptval ("accept", optarg);
646           break;
647         case 'a':
648           setoptval ("logfile", optarg);
649           append_to_log = 1;
650           break;
651         case 'B':
652           setoptval ("base", optarg);
653           break;
654         case 'C':
655           setoptval ("cache", optarg);
656           break;
657         case 'D':
658           setoptval ("domains", optarg);
659           break;
660         case 'e':
661           run_command (optarg);
662           break;
663         case 'G':
664           setoptval ("ignoretags", optarg);
665           break;
666         case 'g':
667           setoptval ("glob", optarg);
668           break;
669         case 'I':
670           setoptval ("includedirectories", optarg);
671           break;
672         case 'i':
673           setoptval ("input", optarg);
674           break;
675         case 'l':
676           setoptval ("reclevel", optarg);
677           break;
678         case 'n':
679           {
680             /* #### What we really want here is --no-foo. */
681             char *p;
682
683             for (p = optarg; *p; p++)
684               switch (*p)
685                 {
686                 case 'v':
687                   setoptval ("verbose", "off");
688                   break;
689                 case 'H':
690                   setoptval ("addhostdir", "off");
691                   break;
692                 case 'd':
693                   setoptval ("dirstruct", "off");
694                   break;
695                 case 'c':
696                   setoptval ("noclobber", "on");
697                   break;
698                 case 'r':
699                   setoptval ("removelisting", "off");
700                   break;
701                 case 'p':
702                   setoptval ("noparent", "on");
703                   break;
704                 case 'k':
705                   setoptval ("httpkeepalive", "off");
706                   break;
707                 default:
708                   printf (_("%s: illegal option -- `-n%c'\n"), exec_name, *p);
709                   print_usage ();
710                   printf ("\n");
711                   printf (_("Try `%s --help\' for more options.\n"), exec_name);
712                   exit (1);
713                 }
714             break;
715           }
716         case 'O':
717           setoptval ("outputdocument", optarg);
718           break;
719         case 'o':
720           setoptval ("logfile", optarg);
721           break;
722         case 'P':
723           setoptval ("dirprefix", optarg);
724           break;
725         case 'Q':
726           setoptval ("quota", optarg);
727           break;
728         case 'R':
729           setoptval ("reject", optarg);
730           break;
731         case 'T':
732           setoptval ("timeout", optarg);
733           break;
734         case 't':
735           setoptval ("tries", optarg);
736           break;
737         case 'U':
738           setoptval ("useragent", optarg);
739           break;
740         case 'w':
741           setoptval ("wait", optarg);
742           break;
743         case 'X':
744           setoptval ("excludedirectories", optarg);
745           break;
746         case 'Y':
747           setoptval ("useproxy", optarg);
748           break;
749
750         case '?':
751           print_usage ();
752           printf ("\n");
753           printf (_("Try `%s --help' for more options.\n"), exec_name);
754           exit (0);
755           break;
756         }
757     }
758
759   /* All user options have now been processed, so it's now safe to do
760      interoption dependency checks. */
761
762   if (opt.reclevel == 0)
763     opt.reclevel = INFINITE_RECURSION;  /* see wget.h for commentary on this */
764
765   if (opt.page_requisites && !opt.recursive)
766     {
767       /* Don't set opt.recursive here because it would confuse the FTP
768          code.  Instead, call retrieve_tree below when either
769          page_requisites or recursive is requested.  */
770       opt.reclevel = 0;
771       if (!opt.no_dirstruct)
772         opt.dirstruct = 1;      /* normally handled by cmd_spec_recursive() */
773     }
774
775   if (opt.verbose == -1)
776     opt.verbose = !opt.quiet;
777
778   /* Sanity checks.  */
779   if (opt.verbose && opt.quiet)
780     {
781       printf (_("Can't be verbose and quiet at the same time.\n"));
782       print_usage ();
783       exit (1);
784     }
785   if (opt.timestamping && opt.noclobber)
786     {
787       printf (_("\
788 Can't timestamp and not clobber old files at the same time.\n"));
789       print_usage ();
790       exit (1);
791     }
792   nurl = argc - optind;
793   if (!nurl && !opt.input_filename)
794     {
795       /* No URL specified.  */
796       printf (_("%s: missing URL\n"), exec_name);
797       print_usage ();
798       printf ("\n");
799       /* #### Something nicer should be printed here -- similar to the
800          pre-1.5 `--help' page.  */
801       printf (_("Try `%s --help' for more options.\n"), exec_name);
802       exit (1);
803     }
804
805   if (opt.background)
806     fork_to_background ();
807
808   /* Initialize progress.  Have to do this after the options are
809      processed so we know where the log file is.  */
810   if (opt.verbose)
811     set_progress_implementation (opt.progress_type);
812
813   /* Fill in the arguments.  */
814   url = alloca_array (char *, nurl + 1);
815   for (i = 0; i < nurl; i++, optind++)
816     {
817       char *rewritten = rewrite_shorthand_url (argv[optind]);
818       if (rewritten)
819         url[i] = rewritten;
820       else
821         url[i] = xstrdup (argv[optind]);
822     }
823   url[i] = NULL;
824
825   /* Change the title of console window on Windows.  #### I think this
826      statement should belong to retrieve_url().  --hniksic.  */
827 #ifdef WINDOWS
828   ws_changetitle (*url, nurl);
829 #endif
830
831   /* Initialize logging.  */
832   log_init (opt.lfilename, append_to_log);
833
834   DEBUGP (("DEBUG output created by Wget %s on %s.\n\n", version_string,
835            OS_TYPE));
836
837   /* Open the output filename if necessary.  */
838   if (opt.output_document)
839     {
840       if (HYPHENP (opt.output_document))
841         opt.dfp = stdout;
842       else
843         {
844           struct stat st;
845           opt.dfp = fopen (opt.output_document, opt.always_rest ? "ab" : "wb");
846           if (opt.dfp == NULL)
847             {
848               perror (opt.output_document);
849               exit (1);
850             }
851           if (fstat (fileno (opt.dfp), &st) == 0 && S_ISREG (st.st_mode))
852             opt.od_known_regular = 1;
853         }
854     }
855
856 #ifdef WINDOWS
857   ws_startup ();
858 #endif
859
860   /* Setup the signal handler to redirect output when hangup is
861      received.  */
862 #ifdef HAVE_SIGNAL
863   if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
864     signal(SIGHUP, redirect_output_signal);
865   /* ...and do the same for SIGUSR1.  */
866   signal (SIGUSR1, redirect_output_signal);
867   /* Writing to a closed socket normally signals SIGPIPE, and the
868      process exits.  What we want is to ignore SIGPIPE and just check
869      for the return value of write().  */
870   signal (SIGPIPE, SIG_IGN);
871 #ifdef SIGWINCH
872   signal (SIGWINCH, progress_handle_sigwinch);
873 #endif
874 #endif /* HAVE_SIGNAL */
875
876 #ifdef HAVE_SSL
877   /* Must call this before resolving any URLs because it has the power
878      to disable `https'.  */
879   ssl_init_prng ();
880 #endif
881
882   status = RETROK;              /* initialize it, just-in-case */
883   /* Retrieve the URLs from argument list.  */
884   for (t = url; *t; t++)
885     {
886       char *filename = NULL, *redirected_URL = NULL;
887       int dt;
888
889       if ((opt.recursive || opt.page_requisites)
890           && url_scheme (*t) != SCHEME_FTP)
891         status = retrieve_tree (*t);
892       else
893         status = retrieve_url (*t, &filename, &redirected_URL, NULL, &dt);
894
895       if (opt.delete_after && file_exists_p(filename))
896         {
897           DEBUGP (("Removing file due to --delete-after in main():\n"));
898           logprintf (LOG_VERBOSE, _("Removing %s.\n"), filename);
899           if (unlink (filename))
900             logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno));
901         }
902
903       xfree_null (redirected_URL);
904       xfree_null (filename);
905     }
906
907   /* And then from the input file, if any.  */
908   if (opt.input_filename)
909     {
910       int count;
911       status = retrieve_from_file (opt.input_filename, opt.force_html, &count);
912       if (!count)
913         logprintf (LOG_NOTQUIET, _("No URLs found in %s.\n"),
914                    opt.input_filename);
915     }
916   /* Print the downloaded sum.  */
917   if (opt.recursive || opt.page_requisites
918       || nurl > 1
919       || (opt.input_filename && total_downloaded_bytes != 0))
920     {
921       logprintf (LOG_NOTQUIET,
922                  _("\nFINISHED --%s--\nDownloaded: %s bytes in %d files\n"),
923                  time_str (NULL), legible_large_int (total_downloaded_bytes),
924                  opt.numurls);
925       /* Print quota warning, if exceeded.  */
926       if (opt.quota && total_downloaded_bytes > opt.quota)
927         logprintf (LOG_NOTQUIET,
928                    _("Download quota (%s bytes) EXCEEDED!\n"),
929                    legible (opt.quota));
930     }
931
932   if (opt.cookies_output && wget_cookie_jar)
933     cookie_jar_save (wget_cookie_jar, opt.cookies_output);
934
935   if (opt.convert_links && !opt.delete_after)
936     convert_all_links ();
937
938   log_close ();
939   for (i = 0; i < nurl; i++)
940     xfree (url[i]);
941   cleanup ();
942
943 #ifdef DEBUG_MALLOC
944   print_malloc_debug_stats ();
945 #endif
946   if (status == RETROK)
947     return 0;
948   else
949     return 1;
950 }
951 \f
952 #ifdef HAVE_SIGNAL
953 /* Hangup signal handler.  When wget receives SIGHUP or SIGUSR1, it
954    will proceed operation as usual, trying to write into a log file.
955    If that is impossible, the output will be turned off.
956
957    #### It is unsafe to do call libc functions from a signal handler.
958    What we should do is, set a global variable, and have the code in
959    log.c pick it up.  */
960
961 static RETSIGTYPE
962 redirect_output_signal (int sig)
963 {
964   char *signal_name = (sig == SIGHUP ? "SIGHUP" :
965                        (sig == SIGUSR1 ? "SIGUSR1" :
966                         "WTF?!"));
967   log_request_redirect_output (signal_name);
968   progress_schedule_redirect ();
969   signal (sig, redirect_output_signal);
970 }
971 #endif /* HAVE_SIGNAL */