Check for a mkstemps() failure, generate a proper warning if the fopen()
[dragonfly.git] / usr.bin / fetch / fetch.c
1 /*-
2  * Copyright (c) 2000 Dag-Erling Coïdan Smørgrav
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer
10  *    in this position and unchanged.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  * $FreeBSD: src/usr.bin/fetch/fetch.c,v 1.10.2.21 2003/06/06 06:48:42 des Exp $
29  * $DragonFly: src/usr.bin/fetch/fetch.c,v 1.3 2004/08/25 01:42:26 dillon Exp $
30  */
31
32 #include <sys/param.h>
33 #include <sys/socket.h>
34 #include <sys/stat.h>
35 #include <sys/time.h>
36
37 #include <ctype.h>
38 #include <err.h>
39 #include <errno.h>
40 #include <signal.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <sysexits.h>
45 #include <termios.h>
46 #include <unistd.h>
47
48 #include <fetch.h>
49
50 #define MINBUFSIZE      4096
51
52 /* Option flags */
53 int      A_flag;        /*    -A: do not follow 302 redirects */
54 int      a_flag;        /*    -a: auto retry */
55 off_t    B_size;        /*    -B: buffer size */
56 int      b_flag;        /*!   -b: workaround TCP bug */
57 char    *c_dirname;     /*    -c: remote directory */
58 int      d_flag;        /*    -d: direct connection */
59 int      F_flag;        /*    -F: restart without checking mtime  */
60 char    *f_filename;    /*    -f: file to fetch */
61 char    *h_hostname;    /*    -h: host to fetch from */
62 int      l_flag;        /*    -l: link rather than copy file: URLs */
63 int      m_flag;        /* -[Mm]: mirror mode */
64 char    *N_filename;    /*    -N: netrc file name */
65 int      n_flag;        /*    -n: do not preserve modification time */
66 int      o_flag;        /*    -o: specify output file */
67 int      o_directory;   /*        output file is a directory */
68 char    *o_filename;    /*        name of output file */
69 int      o_stdout;      /*        output file is stdout */
70 int      once_flag;     /*    -1: stop at first successful file */
71 int      p_flag;        /* -[Pp]: use passive FTP */
72 int      R_flag;        /*    -R: don't delete partially transferred files */
73 int      r_flag;        /*    -r: restart previously interrupted transfer */
74 off_t    S_size;        /*    -S: require size to match */
75 int      s_flag;        /*    -s: show size, don't fetch */
76 long     T_secs = 120;  /*    -T: transfer timeout in seconds */
77 int      t_flag;        /*!   -t: workaround TCP bug */
78 int      U_flag;        /*    -U: do not use high ports */
79 int      v_level = 1;   /*    -v: verbosity level */
80 int      v_tty;         /*        stdout is a tty */
81 pid_t    pgrp;          /*        our process group */
82 long     w_secs;        /*    -w: retry delay */
83 int      family = PF_UNSPEC;    /* -[46]: address family to use */
84
85 int      sigalrm;       /* SIGALRM received */
86 int      siginfo;       /* SIGINFO received */
87 int      sigint;        /* SIGINT received */
88
89 long     ftp_timeout;   /* default timeout for FTP transfers */
90 long     http_timeout;  /* default timeout for HTTP transfers */
91 u_char  *buf;           /* transfer buffer */
92
93
94 /*
95  * Signal handler
96  */
97 static void
98 sig_handler(int sig)
99 {
100         switch (sig) {
101         case SIGALRM:
102                 sigalrm = 1;
103                 break;
104         case SIGINFO:
105                 siginfo = 1;
106                 break;
107         case SIGINT:
108                 sigint = 1;
109                 break;
110         }
111 }
112
113 struct xferstat {
114         char             name[40];
115         struct timeval   start;
116         struct timeval   last;
117         off_t            size;
118         off_t            offset;
119         off_t            rcvd;
120 };
121
122 /*
123  * Compute and display ETA
124  */
125 static void
126 stat_eta(struct xferstat *xs)
127 {
128         long elapsed, received, expected, eta;
129
130         elapsed = xs->last.tv_sec - xs->start.tv_sec;
131         received = xs->rcvd - xs->offset;
132         expected = xs->size - xs->rcvd;
133         eta = (long)((double)elapsed * expected / received);
134         if (eta > 3600) {
135                 fprintf(stderr, "%02ld:", eta / 3600);
136                 eta %= 3600;
137         }
138         fprintf(stderr, "%02ld:%02ld", eta / 60, eta % 60);
139 }
140
141 /*
142  * Compute and display transfer rate
143  */
144 static void
145 stat_bps(struct xferstat *xs)
146 {
147         double delta, bps;
148
149         delta = (xs->last.tv_sec + (xs->last.tv_usec / 1.e6))
150             - (xs->start.tv_sec + (xs->start.tv_usec / 1.e6));
151         if (delta == 0.0) {
152                 fprintf(stderr, "?? Bps");
153                 return;
154         }
155         bps = (xs->rcvd - xs->offset) / delta;
156         if (bps > 1024*1024)
157                 fprintf(stderr, "%.2f MBps", bps / (1024*1024));
158         else if (bps > 1024)
159                 fprintf(stderr, "%.2f kBps", bps / 1024);
160         else
161                 fprintf(stderr, "%.2f Bps", bps);
162 }
163
164 /*
165  * Update the stats display
166  */
167 static void
168 stat_display(struct xferstat *xs, int force)
169 {
170         struct timeval now;
171         int ctty_pgrp;
172
173         if (!v_tty || !v_level)
174                 return;
175
176         /* check if we're the foreground process */
177         if (ioctl(STDERR_FILENO, TIOCGPGRP, &ctty_pgrp) == -1 ||
178             (pid_t)ctty_pgrp != pgrp)
179                 return;
180
181         gettimeofday(&now, NULL);
182         if (!force && now.tv_sec <= xs->last.tv_sec)
183                 return;
184         xs->last = now;
185
186         fprintf(stderr, "\rReceiving %s", xs->name);
187         if (xs->size <= 0) {
188                 fprintf(stderr, ": %lld bytes", (long long)xs->rcvd);
189         } else {
190                 fprintf(stderr, " (%lld bytes): %d%%", (long long)xs->size,
191                     (int)((100.0 * xs->rcvd) / xs->size));
192                 if (xs->rcvd > 0 && xs->last.tv_sec >= xs->start.tv_sec + 30) {
193                         fprintf(stderr, " (ETA ");
194                         stat_eta(xs);
195                         if (v_level > 1) {
196                                 fprintf(stderr, " at ");
197                                 stat_bps(xs);
198                         }
199                         fprintf(stderr, ")  ");
200                 }
201         }
202 }
203
204 /*
205  * Initialize the transfer statistics
206  */
207 static void
208 stat_start(struct xferstat *xs, const char *name, off_t size, off_t offset)
209 {
210         snprintf(xs->name, sizeof xs->name, "%s", name);
211         gettimeofday(&xs->start, NULL);
212         xs->last.tv_sec = xs->last.tv_usec = 0;
213         xs->size = size;
214         xs->offset = offset;
215         xs->rcvd = offset;
216         stat_display(xs, 1);
217 }
218
219 /*
220  * Update the transfer statistics
221  */
222 static void
223 stat_update(struct xferstat *xs, off_t rcvd)
224 {
225         xs->rcvd = rcvd;
226         stat_display(xs, 0);
227 }
228
229 /*
230  * Finalize the transfer statistics
231  */
232 static void
233 stat_end(struct xferstat *xs)
234 {
235         double delta;
236
237         if (!v_level)
238                 return;
239
240         gettimeofday(&xs->last, NULL);
241
242         stat_display(xs, 1);
243         fputc('\n', stderr);
244         delta = (xs->last.tv_sec + (xs->last.tv_usec / 1.e6))
245             - (xs->start.tv_sec + (xs->start.tv_usec / 1.e6));
246         fprintf(stderr, "%lld bytes transferred in %.1f seconds (",
247             (long long)(xs->rcvd - xs->offset), delta);
248         stat_bps(xs);
249         fprintf(stderr, ")\n");
250 }
251
252 /*
253  * Ask the user for authentication details
254  */
255 static int
256 query_auth(struct url *URL)
257 {
258         struct termios tios;
259         tcflag_t saved_flags;
260         int i, nopwd;
261
262
263         fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
264             URL->scheme, URL->host, URL->port);
265
266         fprintf(stderr, "Login: ");
267         if (fgets(URL->user, sizeof URL->user, stdin) == NULL)
268                 return -1;
269         for (i = 0; URL->user[i]; ++i)
270                 if (isspace(URL->user[i]))
271                         URL->user[i] = '\0';
272
273         fprintf(stderr, "Password: ");
274         if (tcgetattr(STDIN_FILENO, &tios) == 0) {
275                 saved_flags = tios.c_lflag;
276                 tios.c_lflag &= ~ECHO;
277                 tios.c_lflag |= ECHONL|ICANON;
278                 tcsetattr(STDIN_FILENO, TCSAFLUSH|TCSASOFT, &tios);
279                 nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
280                 tios.c_lflag = saved_flags;
281                 tcsetattr(STDIN_FILENO, TCSANOW|TCSASOFT, &tios);
282         } else {
283                 nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
284         }
285         if (nopwd)
286                 return -1;
287
288         for (i = 0; URL->pwd[i]; ++i)
289                 if (isspace(URL->pwd[i]))
290                         URL->pwd[i] = '\0';
291         return 0;
292 }
293
294 /*
295  * Fetch a file
296  */
297 static int
298 fetch(char *URL, const char *path)
299 {
300         struct url *url;
301         struct url_stat us;
302         struct stat sb, nsb;
303         struct xferstat xs;
304         FILE *f, *of;
305         size_t size, wr;
306         off_t count;
307         char flags[8];
308         const char *slash;
309         char *tmppath;
310         int r;
311         u_int timeout;
312         u_char *ptr;
313
314         f = of = NULL;
315         tmppath = NULL;
316
317         timeout = 0;
318         *flags = 0;
319         count = 0;
320
321         /* set verbosity level */
322         if (v_level > 1)
323                 strcat(flags, "v");
324         if (v_level > 2)
325                 fetchDebug = 1;
326
327         /* parse URL */
328         if ((url = fetchParseURL(URL)) == NULL) {
329                 warnx("%s: parse error", URL);
330                 goto failure;
331         }
332
333         /* if no scheme was specified, take a guess */
334         if (!*url->scheme) {
335                 if (!*url->host)
336                         strcpy(url->scheme, SCHEME_FILE);
337                 else if (strncasecmp(url->host, "ftp.", 4) == 0)
338                         strcpy(url->scheme, SCHEME_FTP);
339                 else if (strncasecmp(url->host, "www.", 4) == 0)
340                         strcpy(url->scheme, SCHEME_HTTP);
341         }
342
343         /* common flags */
344         switch (family) {
345         case PF_INET:
346                 strcat(flags, "4");
347                 break;
348         case PF_INET6:
349                 strcat(flags, "6");
350                 break;
351         }
352
353         /* FTP specific flags */
354         if (strcmp(url->scheme, "ftp") == 0) {
355                 if (p_flag)
356                         strcat(flags, "p");
357                 if (d_flag)
358                         strcat(flags, "d");
359                 if (U_flag)
360                         strcat(flags, "l");
361                 timeout = T_secs ? T_secs : ftp_timeout;
362         }
363
364         /* HTTP specific flags */
365         if (strcmp(url->scheme, "http") == 0) {
366                 if (d_flag)
367                         strcat(flags, "d");
368                 if (A_flag)
369                         strcat(flags, "A");
370                 timeout = T_secs ? T_secs : http_timeout;
371         }
372
373         /* set the protocol timeout. */
374         fetchTimeout = timeout;
375
376         /* just print size */
377         if (s_flag) {
378                 if (timeout)
379                         alarm(timeout);
380                 r = fetchStat(url, &us, flags);
381                 if (timeout)
382                         alarm(0);
383                 if (sigalrm || sigint)
384                         goto signal;
385                 if (r == -1) {
386                         warnx("%s", fetchLastErrString);
387                         goto failure;
388                 }
389                 if (us.size == -1)
390                         printf("Unknown\n");
391                 else
392                         printf("%lld\n", (long long)us.size);
393                 goto success;
394         }
395
396         /*
397          * If the -r flag was specified, we have to compare the local
398          * and remote files, so we should really do a fetchStat()
399          * first, but I know of at least one HTTP server that only
400          * sends the content size in response to GET requests, and
401          * leaves it out of replies to HEAD requests.  Also, in the
402          * (frequent) case that the local and remote files match but
403          * the local file is truncated, we have sufficient information
404          * before the compare to issue a correct request.  Therefore,
405          * we always issue a GET request as if we were sure the local
406          * file was a truncated copy of the remote file; we can drop
407          * the connection later if we change our minds.
408          */
409         sb.st_size = -1;
410         if (!o_stdout && stat(path, &sb) == -1 && errno != ENOENT) {
411                 warnx("%s: stat()", path);
412                 goto failure;
413         }
414         if (!o_stdout && r_flag && S_ISREG(sb.st_mode))
415                 url->offset = sb.st_size;
416
417         /* start the transfer */
418         if (timeout)
419                 alarm(timeout);
420         f = fetchXGet(url, &us, flags);
421         if (timeout)
422                 alarm(0);
423         if (sigalrm || sigint)
424                 goto signal;
425         if (f == NULL) {
426                 warnx("%s: %s", URL, fetchLastErrString);
427                 goto failure;
428         }
429         if (sigint)
430                 goto signal;
431
432         /* check that size is as expected */
433         if (S_size) {
434                 if (us.size == -1) {
435                         warnx("%s: size unknown", URL);
436                         goto failure;
437                 } else if (us.size != S_size) {
438                         warnx("%s: size mismatch: expected %lld, actual %lld",
439                             URL, (long long)S_size, (long long)us.size);
440                         goto failure;
441                 }
442         }
443
444         /* symlink instead of copy */
445         if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
446                 if (symlink(url->doc, path) == -1) {
447                         warn("%s: symlink()", path);
448                         goto failure;
449                 }
450                 goto success;
451         }
452
453         if (us.size == -1 && !o_stdout && v_level > 0)
454                 warnx("%s: size of remote file is not known", URL);
455         if (v_level > 1) {
456                 if (sb.st_size != -1)
457                         fprintf(stderr, "local size / mtime: %lld / %ld\n",
458                             (long long)sb.st_size, (long)sb.st_mtime);
459                 if (us.size != -1)
460                         fprintf(stderr, "remote size / mtime: %lld / %ld\n",
461                             (long long)us.size, (long)us.mtime);
462         }
463
464         /* open output file */
465         if (o_stdout) {
466                 /* output to stdout */
467                 of = stdout;
468         } else if (r_flag && sb.st_size != -1) {
469                 /* resume mode, local file exists */
470                 if (!F_flag && us.mtime && sb.st_mtime != us.mtime) {
471                         /* no match! have to refetch */
472                         fclose(f);
473                         /* if precious, warn the user and give up */
474                         if (R_flag) {
475                                 warnx("%s: local modification time "
476                                     "does not match remote", path);
477                                 goto failure_keep;
478                         }
479                 } else {
480                         if (us.size == sb.st_size)
481                                 /* nothing to do */
482                                 goto success;
483                         if (sb.st_size > us.size) {
484                                 /* local file too long! */
485                                 warnx("%s: local file (%lld bytes) is longer "
486                                     "than remote file (%lld bytes)", path,
487                                     (long long)sb.st_size, (long long)us.size);
488                                 goto failure;
489                         }
490                         /* we got it, open local file */
491                         if ((of = fopen(path, "a")) == NULL) {
492                                 warn("%s: fopen()", path);
493                                 goto failure;
494                         }
495                         /* check that it didn't move under our feet */
496                         if (fstat(fileno(of), &nsb) == -1) {
497                                 /* can't happen! */
498                                 warn("%s: fstat()", path);
499                                 goto failure;
500                         }
501                         if (nsb.st_dev != sb.st_dev ||
502                             nsb.st_ino != nsb.st_ino ||
503                             nsb.st_size != sb.st_size) {
504                                 warnx("%s: file has changed", URL);
505                                 fclose(of);
506                                 of = NULL;
507                                 sb = nsb;
508                         }
509                 }
510         } else if (m_flag && sb.st_size != -1) {
511                 /* mirror mode, local file exists */
512                 if (sb.st_size == us.size && sb.st_mtime == us.mtime)
513                         goto success;
514         }
515
516         if (of == NULL) {
517                 /*
518                  * We don't yet have an output file; either this is a
519                  * vanilla run with no special flags, or the local and
520                  * remote files didn't match.
521                  */
522
523                 if (url->offset > 0) {
524                         /*
525                          * We tried to restart a transfer, but for
526                          * some reason gave up - so we have to restart
527                          * from scratch if we want the whole file
528                          */
529                         url->offset = 0;
530                         if ((f = fetchXGet(url, &us, flags)) == NULL) {
531                                 warnx("%s: %s", URL, fetchLastErrString);
532                                 goto failure;
533                         }
534                         if (sigint)
535                                 goto signal;
536                 }
537
538                 /* construct a temporary file name */
539                 if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
540                         if ((slash = strrchr(path, '/')) == NULL)
541                                 slash = path;
542                         else
543                                 ++slash;
544                         asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s",
545                             (int)(slash - path), path, slash);
546                         if (tmppath != NULL) {
547                                 if (mkstemps(tmppath, strlen(slash)+1) == -1) {
548                                         warn("%s: mkstemps()", path);
549                                         goto failure;
550                                 }
551
552                                 of = fopen(tmppath, "w");
553                         }
554                 }
555
556                 if (of == NULL)
557                         if ((of = fopen(path, "w")) == NULL) {
558                                 warn("%s: fopen()", path);
559                         goto failure;
560                 }
561         }
562         count = url->offset;
563
564         /* start the counter */
565         stat_start(&xs, path, us.size, count);
566
567         sigalrm = siginfo = sigint = 0;
568
569         /* suck in the data */
570         signal(SIGINFO, sig_handler);
571         while (!sigint) {
572                 if (us.size != -1 && us.size - count < B_size)
573                         size = us.size - count;
574                 else
575                         size = B_size;
576                 if (siginfo) {
577                         stat_end(&xs);
578                         siginfo = 0;
579                 }
580                 if ((size = fread(buf, 1, size, f)) == 0) {
581                         if (ferror(f) && errno == EINTR && !sigint)
582                                 clearerr(f);
583                         else
584                                 break;
585                 }
586                 stat_update(&xs, count += size);
587                 for (ptr = buf; size > 0; ptr += wr, size -= wr)
588                         if ((wr = fwrite(ptr, 1, size, of)) < size) {
589                                 if (ferror(of) && errno == EINTR && !sigint)
590                                         clearerr(of);
591                                 else
592                                         break;
593                         }
594                 if (size != 0)
595                         break;
596         }
597         if (!sigalrm)
598                 sigalrm = ferror(f) && errno == ETIMEDOUT;
599         signal(SIGINFO, SIG_DFL);
600
601         stat_end(&xs);
602
603         /*
604          * If the transfer timed out or was interrupted, we still want to
605          * set the mtime in case the file is not removed (-r or -R) and
606          * the user later restarts the transfer.
607          */
608  signal:
609         /* set mtime of local file */
610         if (!n_flag && us.mtime && !o_stdout && of != NULL &&
611             (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
612                 struct timeval tv[2];
613
614                 fflush(of);
615                 tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
616                 tv[1].tv_sec = (long)us.mtime;
617                 tv[0].tv_usec = tv[1].tv_usec = 0;
618                 if (utimes(tmppath ? tmppath : path, tv))
619                         warn("%s: utimes()", tmppath ? tmppath : path);
620         }
621
622         /* timed out or interrupted? */
623         if (sigalrm)
624                 warnx("transfer timed out");
625         if (sigint) {
626                 warnx("transfer interrupted");
627                 goto failure;
628         }
629
630         /* timeout / interrupt before connection completley established? */
631         if (f == NULL)
632                 goto failure;
633
634         if (!sigalrm) {
635                 /* check the status of our files */
636                 if (ferror(f))
637                         warn("%s", URL);
638                 if (ferror(of))
639                         warn("%s", path);
640                 if (ferror(f) || ferror(of))
641                         goto failure;
642         }
643
644         /* did the transfer complete normally? */
645         if (us.size != -1 && count < us.size) {
646                 warnx("%s appears to be truncated: %lld/%lld bytes",
647                     path, (long long)count, (long long)us.size);
648                 goto failure_keep;
649         }
650
651         /*
652          * If the transfer timed out and we didn't know how much to
653          * expect, assume the worst (i.e. we didn't get all of it)
654          */
655         if (sigalrm && us.size == -1) {
656                 warnx("%s may be truncated", path);
657                 goto failure_keep;
658         }
659
660  success:
661         r = 0;
662         if (tmppath != NULL && rename(tmppath, path) == -1) {
663                 warn("%s: rename()", path);
664                 goto failure_keep;
665         }
666         goto done;
667  failure:
668         if (of && of != stdout && !R_flag && !r_flag)
669                 if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
670                         unlink(tmppath ? tmppath : path);
671         if (R_flag && tmppath != NULL && sb.st_size == -1)
672                 rename(tmppath, path); /* ignore errors here */
673  failure_keep:
674         r = -1;
675         goto done;
676  done:
677         if (f)
678                 fclose(f);
679         if (of && of != stdout)
680                 fclose(of);
681         if (url)
682                 fetchFreeURL(url);
683         if (tmppath != NULL)
684                 free(tmppath);
685         return r;
686 }
687
688 static void
689 usage(void)
690 {
691         fprintf(stderr, "%s\n%s\n%s\n",
692             "usage: fetch [-146AFMPRUadlmnpqrsv] [-N netrc] [-o outputfile]",
693             "             [-S bytes] [-B bytes] [-T seconds] [-w seconds]",
694             "             [-h host -f file [-c dir] | URL ...]");
695 }
696
697
698 /*
699  * Entry point
700  */
701 int
702 main(int argc, char *argv[])
703 {
704         struct stat sb;
705         struct sigaction sa;
706         const char *p, *s;
707         char *end, *q;
708         int c, e, r;
709
710         while ((c = getopt(argc, argv,
711             "146AaB:bc:dFf:Hh:lMmN:nPpo:qRrS:sT:tUvw:")) != -1)
712                 switch (c) {
713                 case '1':
714                         once_flag = 1;
715                         break;
716                 case '4':
717                         family = PF_INET;
718                         break;
719                 case '6':
720                         family = PF_INET6;
721                         break;
722                 case 'A':
723                         A_flag = 1;
724                         break;
725                 case 'a':
726                         a_flag = 1;
727                         break;
728                 case 'B':
729                         B_size = (off_t)strtol(optarg, &end, 10);
730                         if (*optarg == '\0' || *end != '\0')
731                                 errx(1, "invalid buffer size (%s)", optarg);
732                         break;
733                 case 'b':
734                         warnx("warning: the -b option is deprecated");
735                         b_flag = 1;
736                         break;
737                 case 'c':
738                         c_dirname = optarg;
739                         break;
740                 case 'd':
741                         d_flag = 1;
742                         break;
743                 case 'F':
744                         F_flag = 1;
745                         break;
746                 case 'f':
747                         f_filename = optarg;
748                         break;
749                 case 'H':
750                         warnx("the -H option is now implicit, "
751                             "use -U to disable");
752                         break;
753                 case 'h':
754                         h_hostname = optarg;
755                         break;
756                 case 'l':
757                         l_flag = 1;
758                         break;
759                 case 'o':
760                         o_flag = 1;
761                         o_filename = optarg;
762                         break;
763                 case 'M':
764                 case 'm':
765                         if (r_flag)
766                                 errx(1, "the -m and -r flags "
767                                     "are mutually exclusive");
768                         m_flag = 1;
769                         break;
770                 case 'N':
771                         N_filename = optarg;
772                         break;
773                 case 'n':
774                         n_flag = 1;
775                         break;
776                 case 'P':
777                 case 'p':
778                         p_flag = 1;
779                         break;
780                 case 'q':
781                         v_level = 0;
782                         break;
783                 case 'R':
784                         R_flag = 1;
785                         break;
786                 case 'r':
787                         if (m_flag)
788                                 errx(1, "the -m and -r flags "
789                                     "are mutually exclusive");
790                         r_flag = 1;
791                         break;
792                 case 'S':
793                         S_size = (off_t)strtol(optarg, &end, 10);
794                         if (*optarg == '\0' || *end != '\0')
795                                 errx(1, "invalid size (%s)", optarg);
796                         break;
797                 case 's':
798                         s_flag = 1;
799                         break;
800                 case 'T':
801                         T_secs = strtol(optarg, &end, 10);
802                         if (*optarg == '\0' || *end != '\0')
803                                 errx(1, "invalid timeout (%s)", optarg);
804                         break;
805                 case 't':
806                         t_flag = 1;
807                         warnx("warning: the -t option is deprecated");
808                         break;
809                 case 'U':
810                         U_flag = 1;
811                         break;
812                 case 'v':
813                         v_level++;
814                         break;
815                 case 'w':
816                         a_flag = 1;
817                         w_secs = strtol(optarg, &end, 10);
818                         if (*optarg == '\0' || *end != '\0')
819                                 errx(1, "invalid delay (%s)", optarg);
820                         break;
821                 default:
822                         usage();
823                         exit(EX_USAGE);
824                 }
825
826         argc -= optind;
827         argv += optind;
828
829         if (h_hostname || f_filename || c_dirname) {
830                 if (!h_hostname || !f_filename || argc) {
831                         usage();
832                         exit(EX_USAGE);
833                 }
834                 /* XXX this is a hack. */
835                 if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
836                         errx(1, "invalid hostname");
837                 if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
838                     c_dirname ? c_dirname : "", f_filename) == -1)
839                         errx(1, "%s", strerror(ENOMEM));
840                 argc++;
841         }
842
843         if (!argc) {
844                 usage();
845                 exit(EX_USAGE);
846         }
847
848         /* allocate buffer */
849         if (B_size < MINBUFSIZE)
850                 B_size = MINBUFSIZE;
851         if ((buf = malloc(B_size)) == NULL)
852                 errx(1, "%s", strerror(ENOMEM));
853
854         /* timeouts */
855         if ((s = getenv("FTP_TIMEOUT")) != NULL) {
856                 ftp_timeout = strtol(s, &end, 10);
857                 if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
858                         warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
859                         ftp_timeout = 0;
860                 }
861         }
862         if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
863                 http_timeout = strtol(s, &end, 10);
864                 if (*s == '\0' || *end != '\0' || http_timeout < 0) {
865                         warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
866                         http_timeout = 0;
867                 }
868         }
869
870         /* signal handling */
871         sa.sa_flags = 0;
872         sa.sa_handler = sig_handler;
873         sigemptyset(&sa.sa_mask);
874         sigaction(SIGALRM, &sa, NULL);
875         sa.sa_flags = SA_RESETHAND;
876         sigaction(SIGINT, &sa, NULL);
877         fetchRestartCalls = 0;
878
879         /* output file */
880         if (o_flag) {
881                 if (strcmp(o_filename, "-") == 0) {
882                         o_stdout = 1;
883                 } else if (stat(o_filename, &sb) == -1) {
884                         if (errno == ENOENT) {
885                                 if (argc > 1)
886                                         errx(EX_USAGE, "%s is not a directory",
887                                             o_filename);
888                         } else {
889                                 err(EX_IOERR, "%s", o_filename);
890                         }
891                 } else {
892                         if (sb.st_mode & S_IFDIR)
893                                 o_directory = 1;
894                 }
895         }
896
897         /* check if output is to a tty (for progress report) */
898         v_tty = isatty(STDERR_FILENO);
899         if (v_tty)
900                 pgrp = getpgrp();
901
902         r = 0;
903
904         /* authentication */
905         if (v_tty)
906                 fetchAuthMethod = query_auth;
907         if (N_filename != NULL)
908                 setenv("NETRC", N_filename, 1);
909
910         while (argc) {
911                 if ((p = strrchr(*argv, '/')) == NULL)
912                         p = *argv;
913                 else
914                         p++;
915
916                 if (!*p)
917                         p = "fetch.out";
918
919                 fetchLastErrCode = 0;
920
921                 if (o_flag) {
922                         if (o_stdout) {
923                                 e = fetch(*argv, "-");
924                         } else if (o_directory) {
925                                 asprintf(&q, "%s/%s", o_filename, p);
926                                 e = fetch(*argv, q);
927                                 free(q);
928                         } else {
929                                 e = fetch(*argv, o_filename);
930                         }
931                 } else {
932                         e = fetch(*argv, p);
933                 }
934
935                 if (sigint)
936                         kill(getpid(), SIGINT);
937
938                 if (e == 0 && once_flag)
939                         exit(0);
940
941                 if (e) {
942                         r = 1;
943                         if ((fetchLastErrCode
944                             && fetchLastErrCode != FETCH_UNAVAIL
945                             && fetchLastErrCode != FETCH_MOVED
946                             && fetchLastErrCode != FETCH_URL
947                             && fetchLastErrCode != FETCH_RESOLV
948                             && fetchLastErrCode != FETCH_UNKNOWN)) {
949                                 if (w_secs && v_level)
950                                         fprintf(stderr, "Waiting %ld seconds "
951                                             "before retrying\n", w_secs);
952                                 if (w_secs)
953                                         sleep(w_secs);
954                                 if (a_flag)
955                                         continue;
956                         }
957                 }
958
959                 argc--, argv++;
960         }
961
962         exit(r);
963 }