2 * Copyright (c) 2000-2004 Dag-Erling Coïdan Smørgrav
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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
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.
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/param.h>
33 #include <sys/socket.h>
50 #define MINBUFSIZE 4096
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 */
88 int sigalrm; /* SIGALRM received */
89 int siginfo; /* SIGINFO received */
90 int sigint; /* SIGINT received */
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 */
118 struct timeval start;
126 * Compute and display ETA
129 stat_eta(struct xferstat *xs)
133 off_t received, expected;
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);
140 snprintf(str, sizeof str, "%02ldh%02ldm",
141 eta / 3600, (eta % 3600) / 60);
143 snprintf(str, sizeof str, "%02ldm%02lds",
149 * Format a number as "xxxx YB" where Y is ' ', 'k', 'M'...
151 static const char *prefixes = " kMGTP";
153 stat_bytes(off_t bytes)
156 const char *prefix = prefixes;
158 while (bytes > 9999 && prefix[1] != '\0') {
162 snprintf(str, sizeof str, "%4jd %cB", (intmax_t)bytes, *prefix);
167 * Compute and display transfer rate
170 stat_bps(struct xferstat *xs)
175 delta = (xs->last.tv_sec + (xs->last.tv_usec / 1.e6))
176 - (xs->start.tv_sec + (xs->start.tv_usec / 1.e6));
178 snprintf(str, sizeof str, "?? Bps");
180 bps = (xs->rcvd - xs->offset) / delta;
181 snprintf(str, sizeof str, "%sps", stat_bytes((off_t)bps));
187 * Update the stats display
190 stat_display(struct xferstat *xs, int force)
195 /* check if we're the foreground process */
196 if (ioctl(STDERR_FILENO, TIOCGPGRP, &ctty_pgrp) == -1 ||
197 (pid_t)ctty_pgrp != pgrp)
200 gettimeofday(&now, NULL);
201 if (!force && now.tv_sec <= xs->last.tv_sec)
205 fprintf(stderr, "\r%-46.46s", xs->name);
207 setproctitle("%s [%s]", xs->name, stat_bytes(xs->rcvd));
208 fprintf(stderr, " %s", stat_bytes(xs->rcvd));
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));
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));
224 * Initialize the transfer statistics
227 stat_start(struct xferstat *xs, const char *name, off_t size, off_t offset)
229 snprintf(xs->name, sizeof xs->name, "%s", name);
230 gettimeofday(&xs->start, NULL);
231 xs->last.tv_sec = xs->last.tv_usec = 0;
235 if (v_tty && v_level > 0)
237 else if (v_level > 0)
238 fprintf(stderr, "%-46s", xs->name);
242 * Update the transfer statistics
245 stat_update(struct xferstat *xs, off_t rcvd)
248 if (v_tty && v_level > 0)
253 * Finalize the transfer statistics
256 stat_end(struct xferstat *xs)
258 gettimeofday(&xs->last, NULL);
259 if (v_tty && v_level > 0) {
262 } else if (v_level > 0) {
263 fprintf(stderr, " %s %s\n",
264 stat_bytes(xs->size), stat_bps(xs));
269 * Ask the user for authentication details
272 query_auth(struct url *URL)
275 tcflag_t saved_flags;
278 fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
279 URL->scheme, URL->host, URL->port);
281 fprintf(stderr, "Login: ");
282 if (fgets(URL->user, sizeof URL->user, stdin) == NULL)
284 for (i = strlen(URL->user); i >= 0; --i)
285 if (URL->user[i] == '\r' || URL->user[i] == '\n')
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);
298 nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
302 for (i = strlen(URL->pwd); i >= 0; --i)
303 if (URL->pwd[i] == '\r' || URL->pwd[i] == '\n')
313 fetch(char *URL, const char *path)
336 /* set verbosity level */
348 if ((url = fetchParseURL(URL)) == NULL) {
349 warnx("%s: parse error", URL);
353 /* if no scheme was specified, take a guess */
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);
373 /* FTP specific flags */
374 if (strcmp(url->scheme, SCHEME_FTP) == 0) {
381 timeout = T_secs ? T_secs : ftp_timeout;
384 /* HTTP specific flags */
385 if (strcmp(url->scheme, SCHEME_HTTP) == 0 ||
386 strcmp(url->scheme, SCHEME_HTTPS) == 0) {
391 timeout = T_secs ? T_secs : http_timeout;
393 if (stat(i_filename, &sb)) {
394 warn("%s: stat()", i_filename);
397 url->ims_time = sb.st_mtime;
402 /* set the protocol timeout. */
403 fetchTimeout = timeout;
405 /* just print size */
409 r = fetchStat(url, &us, flags);
412 if (sigalrm || sigint)
415 warnx("%s", fetchLastErrString);
421 printf("%jd\n", (intmax_t)us.size);
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.
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)) {
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)
451 if (r == -1 && errno != ENOENT) {
452 warnx("%s: stat()", path);
457 /* start the transfer */
460 f = fetchXGet(url, &us, flags);
463 if (sigalrm || sigint)
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. */
479 /* check that size is as expected */
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);
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);
499 if (us.size == -1 && !o_stdout && v_level > 0)
500 warnx("%s: size of remote file is not known", URL);
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);
506 fprintf(stderr, "remote size / mtime: %jd / %ld\n",
507 (intmax_t)us.size, (long)us.mtime);
510 /* open output file */
512 /* output to 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 */
519 /* if precious, warn the user and give up */
521 warnx("%s: local modification time "
522 "does not match remote", path);
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);
530 /* picked up again later */
531 } else if (us.size != -1) {
532 if (us.size == sb.st_size)
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);
542 /* we got it, open local file */
543 if ((of = fopen(path, "r+")) == NULL) {
544 warn("%s: fopen()", path);
547 /* check that it didn't move under our feet */
548 if (fstat(fileno(of), &nsb) == -1) {
550 warn("%s: fstat()", path);
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);
560 /* picked up again later */
563 /* seek to where we left off */
564 if (of != NULL && fseeko(of, url->offset, SEEK_SET) != 0) {
565 warn("%s: fseeko()", path);
568 /* picked up again later */
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)
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.
583 if (url->offset > 0) {
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
590 if ((f = fetchXGet(url, &us, flags)) == NULL) {
591 warnx("%s: %s", URL, fetchLastErrString);
598 /* construct a temp file name */
599 if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
600 if ((slash = strrchr(path, '/')) == NULL)
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);
614 of = fopen(path, "w");
616 warn("%s: open()", path);
622 /* start the counter */
623 stat_start(&xs, path, us.size, count);
625 sigalrm = siginfo = sigint = 0;
627 /* suck in the data */
628 signal(SIGINFO, sig_handler);
630 if (us.size != -1 && us.size - count < B_size &&
631 us.size - count >= 0)
632 size = us.size - count;
639 if ((size = fread(buf, 1, size, f)) == 0) {
640 if (ferror(f) && errno == EINTR && !sigint)
645 stat_update(&xs, count += size);
646 for (ptr = buf; size > 0; ptr += wr, size -= wr)
647 if ((wr = fwrite(ptr, 1, size, of)) < size) {
648 if (ferror(of) && errno == EINTR && !sigint)
657 sigalrm = ferror(f) && errno == ETIMEDOUT;
658 signal(SIGINFO, SIG_DFL);
663 * If the transfer timed out or was interrupted, we still want to
664 * set the mtime in case the file is not removed (-r or -R) and
665 * the user later restarts the transfer.
668 /* set mtime of local file */
669 if (!n_flag && us.mtime && !o_stdout && of != NULL &&
670 (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
671 struct timeval tv[2];
674 tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
675 tv[1].tv_sec = (long)us.mtime;
676 tv[0].tv_usec = tv[1].tv_usec = 0;
677 if (utimes(tmppath ? tmppath : path, tv))
678 warn("%s: utimes()", tmppath ? tmppath : path);
681 /* timed out or interrupted? */
683 warnx("transfer timed out");
685 warnx("transfer interrupted");
689 /* timeout / interrupt before connection completley established? */
694 /* check the status of our files */
699 if (ferror(f) || ferror(of))
703 /* did the transfer complete normally? */
704 if (us.size != -1 && count < us.size) {
705 warnx("%s appears to be truncated: %jd/%jd bytes",
706 path, (intmax_t)count, (intmax_t)us.size);
711 * If the transfer timed out and we didn't know how much to
712 * expect, assume the worst (i.e. we didn't get all of it)
714 if (sigalrm && us.size == -1) {
715 warnx("%s may be truncated", path);
721 if (tmppath != NULL && rename(tmppath, path) == -1) {
722 warn("%s: rename()", path);
727 if (of && of != stdout && !R_flag && !r_flag)
728 if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
729 unlink(tmppath ? tmppath : path);
730 if (R_flag && tmppath != NULL && sb.st_size == -1)
731 rename(tmppath, path); /* ignore errors here */
738 if (of && of != stdout)
750 fprintf(stderr, "%s\n%s\n%s\n%s\n",
751 "usage: fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [-N file] [-o file] [-S bytes]",
752 " [-T seconds] [-w seconds] [-i file] URL ...",
753 " fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [-N file] [-o file] [-S bytes]",
754 " [-T seconds] [-w seconds] [-i file] -h host -f file [-c dir]");
762 main(int argc, char *argv[])
770 while ((c = getopt(argc, argv,
771 "146AaB:bc:dFf:Hh:i:lMmN:nPpo:qRrS:sT:tUvw:")) != -1)
789 B_size = (off_t)strtol(optarg, &end, 10);
790 if (*optarg == '\0' || *end != '\0')
791 errx(1, "invalid buffer size (%s)", optarg);
794 warnx("warning: the -b option is deprecated");
810 warnx("the -H option is now implicit, "
811 "use -U to disable");
830 errx(1, "the -m and -r flags "
831 "are mutually exclusive");
852 errx(1, "the -m and -r flags "
853 "are mutually exclusive");
857 S_size = (off_t)strtol(optarg, &end, 10);
858 if (*optarg == '\0' || *end != '\0')
859 errx(1, "invalid size (%s)", optarg);
865 T_secs = strtol(optarg, &end, 10);
866 if (*optarg == '\0' || *end != '\0')
867 errx(1, "invalid timeout (%s)", optarg);
871 warnx("warning: the -t option is deprecated");
881 w_secs = strtol(optarg, &end, 10);
882 if (*optarg == '\0' || *end != '\0')
883 errx(1, "invalid delay (%s)", optarg);
893 if (h_hostname || f_filename || c_dirname) {
894 if (!h_hostname || !f_filename || argc) {
898 /* XXX this is a hack. */
899 if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
900 errx(1, "invalid hostname");
901 if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
902 c_dirname ? c_dirname : "", f_filename) == -1)
903 errx(1, "%s", strerror(ENOMEM));
912 /* allocate buffer */
913 if (B_size < MINBUFSIZE)
915 if ((buf = malloc(B_size)) == NULL)
916 errx(1, "%s", strerror(ENOMEM));
919 if ((s = getenv("FTP_TIMEOUT")) != NULL) {
920 ftp_timeout = strtol(s, &end, 10);
921 if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
922 warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
926 if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
927 http_timeout = strtol(s, &end, 10);
928 if (*s == '\0' || *end != '\0' || http_timeout < 0) {
929 warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
934 /* signal handling */
936 sa.sa_handler = sig_handler;
937 sigemptyset(&sa.sa_mask);
938 sigaction(SIGALRM, &sa, NULL);
939 sa.sa_flags = SA_RESETHAND;
940 sigaction(SIGINT, &sa, NULL);
941 fetchRestartCalls = 0;
945 if (strcmp(o_filename, "-") == 0) {
947 } else if (stat(o_filename, &sb) == -1) {
948 if (errno == ENOENT) {
950 errx(1, "%s is not a directory",
953 err(1, "%s", o_filename);
956 if (sb.st_mode & S_IFDIR)
961 /* check if output is to a tty (for progress report) */
962 v_tty = isatty(STDERR_FILENO);
970 fetchAuthMethod = query_auth;
971 if (N_filename != NULL)
972 setenv("NETRC", N_filename, 1);
975 if ((p = strrchr(*argv, '/')) == NULL)
983 fetchLastErrCode = 0;
987 e = fetch(*argv, "-");
988 } else if (o_directory) {
989 asprintf(&q, "%s/%s", o_filename, p);
993 e = fetch(*argv, o_filename);
1000 kill(getpid(), SIGINT);
1002 if (e == 0 && once_flag)
1007 if ((fetchLastErrCode
1008 && fetchLastErrCode != FETCH_UNAVAIL
1009 && fetchLastErrCode != FETCH_MOVED
1010 && fetchLastErrCode != FETCH_URL
1011 && fetchLastErrCode != FETCH_RESOLV
1012 && fetchLastErrCode != FETCH_UNKNOWN)) {
1013 if (w_secs && v_level)
1014 fprintf(stderr, "Waiting %ld seconds "
1015 "before retrying\n", w_secs);