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