]> sjero.net Git - wget/blob - src/main.c
[svn] Add the POST method.
[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     { "post-data", required_argument, NULL, 167 },
311     { "post-file", required_argument, NULL, 168 },
312     { "progress", required_argument, NULL, 163 },
313     { "proxy", required_argument, NULL, 'Y' },
314     { "proxy-passwd", required_argument, NULL, 144 },
315     { "proxy-user", required_argument, NULL, 143 },
316     { "quota", required_argument, NULL, 'Q' },
317     { "reject", required_argument, NULL, 'R' },
318     { "save-cookies", required_argument, NULL, 162 },
319     { "timeout", required_argument, NULL, 'T' },
320     { "tries", required_argument, NULL, 't' },
321     { "user-agent", required_argument, NULL, 'U' },
322     { "referer", required_argument, NULL, 157 },
323     { "use-proxy", required_argument, NULL, 'Y' },
324 #ifdef HAVE_SSL
325     { "sslcertfile", required_argument, NULL, 158 },
326     { "sslcertkey", required_argument, NULL, 159 },
327     { "egd-file", required_argument, NULL, 166 },
328 #endif /* HAVE_SSL */
329     { "wait", required_argument, NULL, 'w' },
330     { "waitretry", required_argument, NULL, 152 },
331     { 0, 0, 0, 0 }
332   };
333
334   i18n_initialize ();
335
336   append_to_log = 0;
337
338   /* Construct the name of the executable, without the directory part.  */
339   exec_name = strrchr (argv[0], PATH_SEPARATOR);
340   if (!exec_name)
341     exec_name = argv[0];
342   else
343     ++exec_name;
344
345 #ifdef WINDOWS
346   windows_main_junk (&argc, (char **) argv, (char **) &exec_name);
347 #endif
348
349   initialize (); /* sets option defaults; reads the system wgetrc and .wgetrc */
350
351   /* [Is the order of the option letters significant?  If not, they should be
352       alphabetized, like the long_options.  The only thing I know for sure is
353       that the options with required arguments must be followed by a ':'.
354       -- Dan Harkless <wget@harkless.org>] */
355   while ((c = getopt_long (argc, argv, "\
356 hpVqvdkKsxmNWrHSLcFbEY:G:g:T:U:O:l:n:i:o:a:t:D:A:R:P:B:e:Q:X:I:w:C:",
357                            long_options, (int *)0)) != EOF)
358     {
359       switch (c)
360         {
361           /* Options without arguments: */
362         case 132:
363           setval ("spider", "on");
364           break;
365         case 133:
366           setval ("noparent", "on");
367           break;
368         case 136:
369           setval ("deleteafter", "on");
370           break;
371         case 137:
372           setval ("retrsymlinks", "on");
373           break;
374         case 138:
375           setval ("ignorelength", "on");
376           break;
377         case 139:
378           setval ("passiveftp", "on");
379           break;
380         case 141:
381           setval ("noclobber", "on");
382           break;
383         case 142:
384           setval ("followftp", "on");
385           break;
386         case 145:
387           setval ("cutdirs", optarg);
388           break;
389         case 146:
390           setval ("verbose", "off");
391           break;
392         case 147:
393           setval ("dirstruct", "off");
394           break;
395         case 148:
396           setval ("addhostdir", "off");
397           break;
398         case 149:
399           setval ("removelisting", "off");
400           break;
401         case 155:
402           setval ("bindaddress", optarg);
403           break;
404         case 156:
405           setval ("httpkeepalive", "off");
406           break;
407         case 165:
408           setval ("randomwait", "on");
409           break;
410         case 'b':
411           setval ("background", "on");
412           break;
413         case 'c':
414           setval ("continue", "on");
415           break;
416         case 'd':
417 #ifdef DEBUG
418           setval ("debug", "on");
419 #else  /* not DEBUG */
420           fprintf (stderr, _("%s: debug support not compiled in.\n"),
421                    exec_name);
422 #endif /* not DEBUG */
423           break;
424         case 'E':
425           setval ("htmlextension", "on");
426           break;
427         case 'F':
428           setval ("forcehtml", "on");
429           break;
430         case 'H':
431           setval ("spanhosts", "on");
432           break;
433         case 'h':
434           print_help ();
435 #ifdef WINDOWS
436           ws_help (exec_name);
437 #endif
438           exit (0);
439           break;
440         case 'K':
441           setval ("backupconverted", "on");
442           break;
443         case 'k':
444           setval ("convertlinks", "on");
445           break;
446         case 'L':
447           setval ("relativeonly", "on");
448           break;
449         case 'm':
450           setval ("mirror", "on");
451           break;
452         case 'N':
453           setval ("timestamping", "on");
454           break;
455         case 'p':
456           setval ("pagerequisites", "on");
457           break;
458         case 'S':
459           setval ("serverresponse", "on");
460           break;
461         case 's':
462           setval ("saveheaders", "on");
463           break;
464         case 'q':
465           setval ("quiet", "on");
466           break;
467         case 'r':
468           setval ("recursive", "on");
469           break;
470         case 'V':
471           printf ("GNU Wget %s\n\n", version_string);
472           printf ("%s", _("\
473 Copyright (C) 1995, 1996, 1997, 1998, 2000, 2001 Free Software Foundation, Inc.\n"));
474           printf ("%s", _("\
475 This program is distributed in the hope that it will be useful,\n\
476 but WITHOUT ANY WARRANTY; without even the implied warranty of\n\
477 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\
478 GNU General Public License for more details.\n"));
479           printf (_("\nOriginally written by Hrvoje Niksic <hniksic@arsdigita.com>.\n"));
480           exit (0);
481           break;
482         case 'v':
483           setval ("verbose", "on");
484           break;
485         case 'x':
486           setval ("dirstruct", "on");
487           break;
488
489           /* Options accepting an argument: */
490         case 129:
491           setval ("httpuser", optarg);
492           break;
493         case 130:
494           setval ("httppasswd", optarg);
495           break;
496         case 131:
497           setval ("header", optarg);
498           break;
499         case 134:
500           setval ("dotstyle", optarg);
501           break;
502         case 135:
503           setval ("htmlify", optarg);
504           break;
505         case 140:
506           setval ("excludedomains", optarg);
507           break;
508         case 143:
509           setval ("proxyuser", optarg);
510           break;
511         case 144:
512           setval ("proxypasswd", optarg);
513           break;
514         case 151:
515           setval ("backups", optarg);
516           break;
517         case 152:
518           setval ("waitretry", optarg);
519           break;
520         case 153:
521           setval ("followtags", optarg);
522           break;
523         case 160:
524           setval ("cookies", optarg);
525           break;
526         case 161:
527           setval ("loadcookies", optarg);
528           break;
529         case 162:
530           setval ("savecookies", optarg);
531           break;
532         case 163:
533           setval ("progress", optarg);
534           break;
535         case 164:
536           setval ("limitrate", optarg);
537           break;
538         case 157:
539           setval ("referer", optarg);
540           break;
541 #ifdef HAVE_SSL
542         case 158:
543           setval ("sslcertfile", optarg);
544           break;
545         case 159:
546           setval ("sslcertkey", optarg);
547           break;
548         case 166:
549           setval ("egdfile", optarg);
550           break;
551 #endif /* HAVE_SSL */
552         case 167:
553           setval ("postdata", optarg);
554           break;
555         case 168:
556           setval ("postfile", optarg);
557           break;
558         case 'A':
559           setval ("accept", optarg);
560           break;
561         case 'a':
562           setval ("logfile", optarg);
563           append_to_log = 1;
564           break;
565         case 'B':
566           setval ("base", optarg);
567           break;
568         case 'C':
569           setval ("cache", optarg);
570           break;
571         case 'D':
572           setval ("domains", optarg);
573           break;
574         case 'e':
575           {
576             char *com, *val;
577             if (parse_line (optarg, &com, &val))
578               {
579                 if (!setval (com, val))
580                   exit (1);
581               }
582             else
583               {
584                 fprintf (stderr, _("%s: %s: invalid command\n"), exec_name,
585                          optarg);
586                 exit (1);
587               }
588             xfree (com);
589             xfree (val);
590           }
591           break;
592         case 'G':
593           setval ("ignoretags", optarg);
594           break;
595         case 'g':
596           setval ("glob", optarg);
597           break;
598         case 'I':
599           setval ("includedirectories", optarg);
600           break;
601         case 'i':
602           setval ("input", optarg);
603           break;
604         case 'l':
605           setval ("reclevel", optarg);
606           break;
607         case 'n':
608           {
609             /* #### What we really want here is --no-foo. */
610             char *p;
611
612             for (p = optarg; *p; p++)
613               switch (*p)
614                 {
615                 case 'v':
616                   setval ("verbose", "off");
617                   break;
618                 case 'H':
619                   setval ("addhostdir", "off");
620                   break;
621                 case 'd':
622                   setval ("dirstruct", "off");
623                   break;
624                 case 'c':
625                   setval ("noclobber", "on");
626                   break;
627                 case 'r':
628                   setval ("removelisting", "off");
629                   break;
630                 case 'p':
631                   setval ("noparent", "on");
632                   break;
633                 case 'k':
634                   setval ("httpkeepalive", "off");
635                   break;
636                 default:
637                   printf (_("%s: illegal option -- `-n%c'\n"), exec_name, *p);
638                   print_usage ();
639                   printf ("\n");
640                   printf (_("Try `%s --help\' for more options.\n"), exec_name);
641                   exit (1);
642                 }
643             break;
644           }
645         case 'O':
646           setval ("outputdocument", optarg);
647           break;
648         case 'o':
649           setval ("logfile", optarg);
650           break;
651         case 'P':
652           setval ("dirprefix", optarg);
653           break;
654         case 'Q':
655           setval ("quota", optarg);
656           break;
657         case 'R':
658           setval ("reject", optarg);
659           break;
660         case 'T':
661           setval ("timeout", optarg);
662           break;
663         case 't':
664           setval ("tries", optarg);
665           break;
666         case 'U':
667           setval ("useragent", optarg);
668           break;
669         case 'w':
670           setval ("wait", optarg);
671           break;
672         case 'X':
673           setval ("excludedirectories", optarg);
674           break;
675         case 'Y':
676           setval ("useproxy", optarg);
677           break;
678
679         case '?':
680           print_usage ();
681           printf ("\n");
682           printf (_("Try `%s --help' for more options.\n"), exec_name);
683           exit (0);
684           break;
685         }
686     }
687
688   /* All user options have now been processed, so it's now safe to do
689      interoption dependency checks. */
690
691   if (opt.reclevel == 0)
692     opt.reclevel = INFINITE_RECURSION;  /* see wget.h for commentary on this */
693
694   if (opt.page_requisites && !opt.recursive)
695     {
696       opt.recursive = TRUE;
697       opt.reclevel = 0;
698       if (!opt.no_dirstruct)
699         opt.dirstruct = TRUE;  /* usually handled by cmd_spec_recursive() */
700     }
701
702   if (opt.verbose == -1)
703     opt.verbose = !opt.quiet;
704
705   /* Sanity checks.  */
706   if (opt.verbose && opt.quiet)
707     {
708       printf (_("Can't be verbose and quiet at the same time.\n"));
709       print_usage ();
710       exit (1);
711     }
712   if (opt.timestamping && opt.noclobber)
713     {
714       printf (_("\
715 Can't timestamp and not clobber old files at the same time.\n"));
716       print_usage ();
717       exit (1);
718     }
719   nurl = argc - optind;
720   if (!nurl && !opt.input_filename)
721     {
722       /* No URL specified.  */
723       printf (_("%s: missing URL\n"), exec_name);
724       print_usage ();
725       printf ("\n");
726       /* #### Something nicer should be printed here -- similar to the
727          pre-1.5 `--help' page.  */
728       printf (_("Try `%s --help' for more options.\n"), exec_name);
729       exit (1);
730     }
731
732   if (opt.background)
733     fork_to_background ();
734
735   /* Initialize progress.  Have to do this after the options are
736      processed so we know where the log file is.  */
737   if (opt.verbose)
738     set_progress_implementation (opt.progress_type);
739
740   /* Allocate basic pointer.  */
741   url = ALLOCA_ARRAY (char *, nurl + 1);
742   /* Fill in the arguments.  */
743   for (i = 0; i < nurl; i++, optind++)
744     {
745       char *rewritten = rewrite_shorthand_url (argv[optind]);
746       if (rewritten)
747         url[i] = rewritten;
748       else
749         url[i] = xstrdup (argv[optind]);
750     }
751   url[i] = NULL;
752
753   /* Change the title of console window on Windows.  #### I think this
754      statement should belong to retrieve_url().  --hniksic.  */
755 #ifdef WINDOWS
756   ws_changetitle (*url, nurl);
757 #endif
758
759   /* Initialize logging.  */
760   log_init (opt.lfilename, append_to_log);
761
762   DEBUGP (("DEBUG output created by Wget %s on %s.\n\n", version_string,
763            OS_TYPE));
764
765   /* Open the output filename if necessary.  */
766   if (opt.output_document)
767     {
768       if (HYPHENP (opt.output_document))
769         opt.dfp = stdout;
770       else
771         {
772           struct stat st;
773           opt.dfp = fopen (opt.output_document, opt.always_rest ? "ab" : "wb");
774           if (opt.dfp == NULL)
775             {
776               perror (opt.output_document);
777               exit (1);
778             }
779           if (fstat (fileno (opt.dfp), &st) == 0 && S_ISREG (st.st_mode))
780             opt.od_known_regular = 1;
781         }
782     }
783
784 #ifdef WINDOWS
785   ws_startup ();
786 #endif
787
788   /* Setup the signal handler to redirect output when hangup is
789      received.  */
790 #ifdef HAVE_SIGNAL
791   if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
792     signal(SIGHUP, redirect_output_signal);
793   /* ...and do the same for SIGUSR1.  */
794   signal (SIGUSR1, redirect_output_signal);
795   /* Writing to a closed socket normally signals SIGPIPE, and the
796      process exits.  What we want is to ignore SIGPIPE and just check
797      for the return value of write().  */
798   signal (SIGPIPE, SIG_IGN);
799 #ifdef SIGWINCH
800   signal (SIGWINCH, progress_handle_sigwinch);
801 #endif
802 #endif /* HAVE_SIGNAL */
803
804 #ifdef HAVE_SSL
805   /* Must call this before resolving any URLs because it has the power
806      to disable `https'.  */
807   ssl_init_prng ();
808 #endif
809
810   status = RETROK;              /* initialize it, just-in-case */
811   /* Retrieve the URLs from argument list.  */
812   for (t = url; *t; t++)
813     {
814       char *filename = NULL, *redirected_URL = NULL;
815       int dt;
816
817       if (opt.recursive && url_scheme (*t) != SCHEME_FTP)
818         status = retrieve_tree (*t);
819       else
820         status = retrieve_url (*t, &filename, &redirected_URL, NULL, &dt);
821
822       if (opt.delete_after && file_exists_p(filename))
823         {
824           DEBUGP (("Removing file due to --delete-after in main():\n"));
825           logprintf (LOG_VERBOSE, _("Removing %s.\n"), filename);
826           if (unlink (filename))
827             logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno));
828         }
829
830       FREE_MAYBE (redirected_URL);
831       FREE_MAYBE (filename);
832     }
833
834   /* And then from the input file, if any.  */
835   if (opt.input_filename)
836     {
837       int count;
838       status = retrieve_from_file (opt.input_filename, opt.force_html, &count);
839       if (!count)
840         logprintf (LOG_NOTQUIET, _("No URLs found in %s.\n"),
841                    opt.input_filename);
842     }
843   /* Print the downloaded sum.  */
844   if (opt.recursive
845       || nurl > 1
846       || (opt.input_filename && opt.downloaded != 0))
847     {
848       logprintf (LOG_NOTQUIET,
849                  _("\nFINISHED --%s--\nDownloaded: %s bytes in %d files\n"),
850                  time_str (NULL),
851                  (opt.downloaded_overflow ?
852                   "<overflow>" : legible_very_long (opt.downloaded)),
853                  opt.numurls);
854       /* Print quota warning, if exceeded.  */
855       if (downloaded_exceeds_quota ())
856         logprintf (LOG_NOTQUIET,
857                    _("Download quota (%s bytes) EXCEEDED!\n"),
858                    legible (opt.quota));
859     }
860
861   if (opt.cookies_output)
862     save_cookies (opt.cookies_output);
863
864   if (opt.convert_links && !opt.delete_after)
865     {
866       convert_all_links ();
867     }
868
869   log_close ();
870   for (i = 0; i < nurl; i++)
871     xfree (url[i]);
872   cleanup ();
873
874 #ifdef DEBUG_MALLOC
875   print_malloc_debug_stats ();
876 #endif
877   if (status == RETROK)
878     return 0;
879   else
880     return 1;
881 }
882 \f
883 #ifdef HAVE_SIGNAL
884 /* Hangup signal handler.  When wget receives SIGHUP or SIGUSR1, it
885    will proceed operation as usual, trying to write into a log file.
886    If that is impossible, the output will be turned off.
887
888    #### It is unsafe to do call libc functions from a signal handler.
889    What we should do is, set a global variable, and have the code in
890    log.c pick it up.  */
891
892 static RETSIGTYPE
893 redirect_output_signal (int sig)
894 {
895   char *signal_name = (sig == SIGHUP ? "SIGHUP" :
896                        (sig == SIGUSR1 ? "SIGUSR1" :
897                         "WTF?!"));
898   log_request_redirect_output (signal_name);
899   progress_schedule_redirect ();
900   signal (sig, redirect_output_signal);
901 }
902 #endif /* HAVE_SIGNAL */