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>
51 #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 l_flag; /* -l: link rather than copy file: URLs */
64 int m_flag; /* -[Mm]: mirror mode */
65 char *N_filename; /* -N: netrc file name */
66 int n_flag; /* -n: do not preserve modification time */
67 int o_flag; /* -o: specify output file */
68 int o_directory; /* output file is a directory */
69 char *o_filename; /* name of output file */
70 int o_stdout; /* output file is stdout */
71 int once_flag; /* -1: stop at first successful file */
72 int p_flag; /* -[Pp]: use passive FTP */
73 int R_flag; /* -R: don't delete partially transferred files */
74 int r_flag; /* -r: restart previously interrupted transfer */
75 off_t S_size; /* -S: require size to match */
76 int s_flag; /* -s: show size, don't fetch */
77 long T_secs = 120; /* -T: transfer timeout in seconds */
78 int t_flag; /*! -t: workaround TCP bug */
79 int U_flag; /* -U: do not use high ports */
80 int v_level = 1; /* -v: verbosity level */
81 int v_tty; /* stdout is a tty */
82 pid_t pgrp; /* our process group */
83 long w_secs; /* -w: retry delay */
84 int family = PF_UNSPEC; /* -[46]: address family to use */
86 int sigalrm; /* SIGALRM received */
87 int siginfo; /* SIGINFO received */
88 int sigint; /* SIGINT received */
90 long ftp_timeout; /* default timeout for FTP transfers */
91 long http_timeout; /* default timeout for HTTP transfers */
92 char *buf; /* transfer buffer */
116 struct timeval start;
124 * Compute and display ETA
127 stat_eta(struct xferstat *xs)
131 off_t received, expected;
133 elapsed = xs->last.tv_sec - xs->start.tv_sec;
134 received = xs->rcvd - xs->offset;
135 expected = xs->size - xs->rcvd;
136 eta = (long)((double)elapsed * expected / received);
138 snprintf(str, sizeof str, "%02ldh%02ldm",
139 eta / 3600, (eta % 3600) / 60);
141 snprintf(str, sizeof str, "%02ldm%02lds",
147 * Format a number as "xxxx YB" where Y is ' ', 'k', 'M'...
149 static const char *prefixes = " kMGTP";
151 stat_bytes(off_t bytes)
154 const char *prefix = prefixes;
156 while (bytes > 9999 && prefix[1] != '\0') {
160 snprintf(str, sizeof str, "%4jd %cB", (intmax_t)bytes, *prefix);
165 * Compute and display transfer rate
168 stat_bps(struct xferstat *xs)
173 delta = (xs->last.tv_sec + (xs->last.tv_usec / 1.e6))
174 - (xs->start.tv_sec + (xs->start.tv_usec / 1.e6));
176 snprintf(str, sizeof str, "?? Bps");
178 bps = (xs->rcvd - xs->offset) / delta;
179 snprintf(str, sizeof str, "%sps", stat_bytes((off_t)bps));
185 * Update the stats display
188 stat_display(struct xferstat *xs, int force)
193 /* check if we're the foreground process */
194 if (ioctl(STDERR_FILENO, TIOCGPGRP, &ctty_pgrp) == -1 ||
195 (pid_t)ctty_pgrp != pgrp)
198 gettimeofday(&now, NULL);
199 if (!force && now.tv_sec <= xs->last.tv_sec)
203 fprintf(stderr, "\r%-46.46s", xs->name);
205 fprintf(stderr, " %s", stat_bytes(xs->rcvd));
207 fprintf(stderr, "%3d%% of %s",
208 (int)((100.0 * xs->rcvd) / xs->size),
209 stat_bytes(xs->size));
211 fprintf(stderr, " %s", stat_bps(xs));
212 if (xs->size > 0 && xs->rcvd > 0 &&
213 xs->last.tv_sec >= xs->start.tv_sec + 10)
214 fprintf(stderr, " %s", stat_eta(xs));
218 * Initialize the transfer statistics
221 stat_start(struct xferstat *xs, const char *name, off_t size, off_t offset)
223 snprintf(xs->name, sizeof xs->name, "%s", name);
224 gettimeofday(&xs->start, NULL);
225 xs->last.tv_sec = xs->last.tv_usec = 0;
229 if (v_tty && v_level > 0)
231 else if (v_level > 0)
232 fprintf(stderr, "%-46s", xs->name);
236 * Update the transfer statistics
239 stat_update(struct xferstat *xs, off_t rcvd)
242 if (v_tty && v_level > 0)
247 * Finalize the transfer statistics
250 stat_end(struct xferstat *xs)
252 gettimeofday(&xs->last, NULL);
253 if (v_tty && v_level > 0) {
256 } else if (v_level > 0) {
257 fprintf(stderr, " %s %s\n",
258 stat_bytes(xs->size), stat_bps(xs));
263 * Ask the user for authentication details
266 query_auth(struct url *URL)
269 tcflag_t saved_flags;
272 fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
273 URL->scheme, URL->host, URL->port);
275 fprintf(stderr, "Login: ");
276 if (fgets(URL->user, sizeof URL->user, stdin) == NULL)
278 for (i = strlen(URL->user); i >= 0; --i)
279 if (URL->user[i] == '\r' || URL->user[i] == '\n')
282 fprintf(stderr, "Password: ");
283 if (tcgetattr(STDIN_FILENO, &tios) == 0) {
284 saved_flags = tios.c_lflag;
285 tios.c_lflag &= ~ECHO;
286 tios.c_lflag |= ECHONL|ICANON;
287 tcsetattr(STDIN_FILENO, TCSAFLUSH|TCSASOFT, &tios);
288 nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
289 tios.c_lflag = saved_flags;
290 tcsetattr(STDIN_FILENO, TCSANOW|TCSASOFT, &tios);
292 nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
296 for (i = strlen(URL->pwd); i >= 0; --i)
297 if (URL->pwd[i] == '\r' || URL->pwd[i] == '\n')
307 fetch(char *URL, const char *path)
330 /* set verbosity level */
337 if ((url = fetchParseURL(URL)) == NULL) {
338 warnx("%s: parse error", URL);
342 /* if no scheme was specified, take a guess */
345 strcpy(url->scheme, SCHEME_FILE);
346 else if (strncasecmp(url->host, "ftp.", 4) == 0)
347 strcpy(url->scheme, SCHEME_FTP);
348 else if (strncasecmp(url->host, "www.", 4) == 0)
349 strcpy(url->scheme, SCHEME_HTTP);
362 /* FTP specific flags */
363 if (strcmp(url->scheme, "ftp") == 0) {
370 timeout = T_secs ? T_secs : ftp_timeout;
373 /* HTTP specific flags */
374 if (strcmp(url->scheme, "http") == 0) {
379 timeout = T_secs ? T_secs : http_timeout;
382 /* set the protocol timeout. */
383 fetchTimeout = timeout;
385 /* just print size */
389 r = fetchStat(url, &us, flags);
392 if (sigalrm || sigint)
395 warnx("%s", fetchLastErrString);
401 printf("%jd\n", (intmax_t)us.size);
406 * If the -r flag was specified, we have to compare the local
407 * and remote files, so we should really do a fetchStat()
408 * first, but I know of at least one HTTP server that only
409 * sends the content size in response to GET requests, and
410 * leaves it out of replies to HEAD requests. Also, in the
411 * (frequent) case that the local and remote files match but
412 * the local file is truncated, we have sufficient information
413 * before the compare to issue a correct request. Therefore,
414 * we always issue a GET request as if we were sure the local
415 * file was a truncated copy of the remote file; we can drop
416 * the connection later if we change our minds.
421 if (r == 0 && r_flag && S_ISREG(sb.st_mode)) {
422 url->offset = sb.st_size;
425 * Whatever value sb.st_size has now is either
426 * wrong (if stat(2) failed) or irrelevant (if the
427 * path does not refer to a regular file)
430 if (r == -1 && errno != ENOENT) {
431 warnx("%s: stat()", path);
437 /* start the transfer */
440 f = fetchXGet(url, &us, flags);
443 if (sigalrm || sigint)
446 warnx("%s: %s", URL, fetchLastErrString);
452 /* check that size is as expected */
455 warnx("%s: size unknown", URL);
456 } else if (us.size != S_size) {
457 warnx("%s: size mismatch: expected %jd, actual %jd",
458 URL, (intmax_t)S_size, (intmax_t)us.size);
463 /* symlink instead of copy */
464 if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
465 if (symlink(url->doc, path) == -1) {
466 warn("%s: symlink()", path);
472 if (us.size == -1 && !o_stdout && v_level > 0)
473 warnx("%s: size of remote file is not known", URL);
475 if (sb.st_size != -1)
476 fprintf(stderr, "local size / mtime: %jd / %ld\n",
477 (intmax_t)sb.st_size, (long)sb.st_mtime);
479 fprintf(stderr, "remote size / mtime: %jd / %ld\n",
480 (intmax_t)us.size, (long)us.mtime);
483 /* open output file */
485 /* output to stdout */
487 } else if (r_flag && sb.st_size != -1) {
488 /* resume mode, local file exists */
489 if (!F_flag && us.mtime && sb.st_mtime != us.mtime) {
490 /* no match! have to refetch */
492 /* if precious, warn the user and give up */
494 warnx("%s: local modification time "
495 "does not match remote", path);
498 } else if (us.size != -1) {
499 if (us.size == sb.st_size)
502 if (sb.st_size > us.size) {
503 /* local file too long! */
504 warnx("%s: local file (%jd bytes) is longer "
505 "than remote file (%jd bytes)", path,
506 (intmax_t)sb.st_size, (intmax_t)us.size);
509 /* we got it, open local file */
510 if ((of = fopen(path, "a")) == NULL) {
511 warn("%s: fopen()", path);
514 /* check that it didn't move under our feet */
515 if (fstat(fileno(of), &nsb) == -1) {
517 warn("%s: fstat()", path);
520 if (nsb.st_dev != sb.st_dev ||
521 nsb.st_ino != nsb.st_ino ||
522 nsb.st_size != sb.st_size) {
523 warnx("%s: file has changed", URL);
529 } else if (m_flag && sb.st_size != -1) {
530 /* mirror mode, local file exists */
531 if (sb.st_size == us.size && sb.st_mtime == us.mtime)
537 * We don't yet have an output file; either this is a
538 * vanilla run with no special flags, or the local and
539 * remote files didn't match.
542 if (url->offset > 0) {
544 * We tried to restart a transfer, but for
545 * some reason gave up - so we have to restart
546 * from scratch if we want the whole file
549 if ((f = fetchXGet(url, &us, flags)) == NULL) {
550 warnx("%s: %s", URL, fetchLastErrString);
557 /* construct a temp file name */
558 if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
559 if ((slash = strrchr(path, '/')) == NULL)
563 asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s",
564 (int)(slash - path), path, slash);
565 if (tmppath != NULL) {
566 mkstemps(tmppath, strlen(slash) + 1);
567 of = fopen(tmppath, "w");
571 of = fopen(path, "w");
573 warn("%s: open()", path);
579 /* start the counter */
580 stat_start(&xs, path, us.size, count);
582 sigalrm = siginfo = sigint = 0;
584 /* suck in the data */
585 signal(SIGINFO, sig_handler);
587 if (us.size != -1 && us.size - count < B_size &&
588 us.size - count >= 0)
589 size = us.size - count;
596 if ((size = fread(buf, 1, size, f)) == 0) {
597 if (ferror(f) && errno == EINTR && !sigint)
602 stat_update(&xs, count += size);
603 for (ptr = buf; size > 0; ptr += wr, size -= wr)
604 if ((wr = fwrite(ptr, 1, size, of)) < size) {
605 if (ferror(of) && errno == EINTR && !sigint)
614 sigalrm = ferror(f) && errno == ETIMEDOUT;
615 signal(SIGINFO, SIG_DFL);
620 * If the transfer timed out or was interrupted, we still want to
621 * set the mtime in case the file is not removed (-r or -R) and
622 * the user later restarts the transfer.
625 /* set mtime of local file */
626 if (!n_flag && us.mtime && !o_stdout && of != NULL &&
627 (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
628 struct timeval tv[2];
631 tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
632 tv[1].tv_sec = (long)us.mtime;
633 tv[0].tv_usec = tv[1].tv_usec = 0;
634 if (utimes(tmppath ? tmppath : path, tv))
635 warn("%s: utimes()", tmppath ? tmppath : path);
638 /* timed out or interrupted? */
640 warnx("transfer timed out");
642 warnx("transfer interrupted");
646 /* timeout / interrupt before connection completley established? */
651 /* check the status of our files */
656 if (ferror(f) || ferror(of))
660 /* did the transfer complete normally? */
661 if (us.size != -1 && count < us.size) {
662 warnx("%s appears to be truncated: %jd/%jd bytes",
663 path, (intmax_t)count, (intmax_t)us.size);
668 * If the transfer timed out and we didn't know how much to
669 * expect, assume the worst (i.e. we didn't get all of it)
671 if (sigalrm && us.size == -1) {
672 warnx("%s may be truncated", path);
678 if (tmppath != NULL && rename(tmppath, path) == -1) {
679 warn("%s: rename()", path);
684 if (of && of != stdout && !R_flag && !r_flag)
685 if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
686 unlink(tmppath ? tmppath : path);
687 if (R_flag && tmppath != NULL && sb.st_size == -1)
688 rename(tmppath, path); /* ignore errors here */
695 if (of && of != stdout)
707 fprintf(stderr, "%s\n%s\n%s\n",
708 "usage: fetch [-146AFMPRUadlmnpqrsv] [-N netrc] [-o outputfile]",
709 " [-S bytes] [-B bytes] [-T seconds] [-w seconds]",
710 " [-h host -f file [-c dir] | URL ...]");
718 main(int argc, char *argv[])
726 while ((c = getopt(argc, argv,
727 "146AaB:bc:dFf:Hh:lMmN:nPpo:qRrS:sT:tUvw:")) != -1)
745 B_size = (off_t)strtol(optarg, &end, 10);
746 if (*optarg == '\0' || *end != '\0')
747 errx(1, "invalid buffer size (%s)", optarg);
750 warnx("warning: the -b option is deprecated");
766 warnx("the -H option is now implicit, "
767 "use -U to disable");
782 errx(1, "the -m and -r flags "
783 "are mutually exclusive");
804 errx(1, "the -m and -r flags "
805 "are mutually exclusive");
809 S_size = (off_t)strtol(optarg, &end, 10);
810 if (*optarg == '\0' || *end != '\0')
811 errx(1, "invalid size (%s)", optarg);
817 T_secs = strtol(optarg, &end, 10);
818 if (*optarg == '\0' || *end != '\0')
819 errx(1, "invalid timeout (%s)", optarg);
823 warnx("warning: the -t option is deprecated");
833 w_secs = strtol(optarg, &end, 10);
834 if (*optarg == '\0' || *end != '\0')
835 errx(1, "invalid delay (%s)", optarg);
845 if (h_hostname || f_filename || c_dirname) {
846 if (!h_hostname || !f_filename || argc) {
850 /* XXX this is a hack. */
851 if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
852 errx(1, "invalid hostname");
853 if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
854 c_dirname ? c_dirname : "", f_filename) == -1)
855 errx(1, "%s", strerror(ENOMEM));
864 /* allocate buffer */
865 if (B_size < MINBUFSIZE)
867 if ((buf = malloc(B_size)) == NULL)
868 errx(1, "%s", strerror(ENOMEM));
871 if ((s = getenv("FTP_TIMEOUT")) != NULL) {
872 ftp_timeout = strtol(s, &end, 10);
873 if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
874 warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
878 if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
879 http_timeout = strtol(s, &end, 10);
880 if (*s == '\0' || *end != '\0' || http_timeout < 0) {
881 warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
886 /* signal handling */
888 sa.sa_handler = sig_handler;
889 sigemptyset(&sa.sa_mask);
890 sigaction(SIGALRM, &sa, NULL);
891 sa.sa_flags = SA_RESETHAND;
892 sigaction(SIGINT, &sa, NULL);
893 fetchRestartCalls = 0;
897 if (strcmp(o_filename, "-") == 0) {
899 } else if (stat(o_filename, &sb) == -1) {
900 if (errno == ENOENT) {
902 errx(EX_USAGE, "%s is not a directory",
905 err(EX_IOERR, "%s", o_filename);
908 if (sb.st_mode & S_IFDIR)
913 /* check if output is to a tty (for progress report) */
914 v_tty = isatty(STDERR_FILENO);
922 fetchAuthMethod = query_auth;
923 if (N_filename != NULL)
924 setenv("NETRC", N_filename, 1);
927 if ((p = strrchr(*argv, '/')) == NULL)
935 fetchLastErrCode = 0;
939 e = fetch(*argv, "-");
940 } else if (o_directory) {
941 asprintf(&q, "%s/%s", o_filename, p);
945 e = fetch(*argv, o_filename);
952 kill(getpid(), SIGINT);
954 if (e == 0 && once_flag)
959 if ((fetchLastErrCode
960 && fetchLastErrCode != FETCH_UNAVAIL
961 && fetchLastErrCode != FETCH_MOVED
962 && fetchLastErrCode != FETCH_URL
963 && fetchLastErrCode != FETCH_RESOLV
964 && fetchLastErrCode != FETCH_UNKNOWN)) {
965 if (w_secs && v_level)
966 fprintf(stderr, "Waiting %ld seconds "
967 "before retrying\n", w_secs);