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