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