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
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 i_flag; /* -i: specify input file for mtime comparison */
63 char *i_filename; /* name of input file */
64 int l_flag; /* -l: link rather than copy file: URLs */
65 int m_flag; /* -[Mm]: mirror mode */
66 char *N_filename; /* -N: netrc file name */
67 int n_flag; /* -n: do not preserve modification time */
68 int o_flag; /* -o: specify output file */
69 int o_directory; /* output file is a directory */
70 char *o_filename; /* name of output file */
71 int o_stdout; /* output file is stdout */
72 int once_flag; /* -1: stop at first successful file */
73 int p_flag; /* -[Pp]: use passive FTP */
74 int R_flag; /* -R: don't delete partially transferred files */
75 int r_flag; /* -r: restart previously interrupted transfer */
76 off_t S_size; /* -S: require size to match */
77 int s_flag; /* -s: show size, don't fetch */
78 long T_secs = 120; /* -T: transfer timeout in seconds */
79 int t_flag; /*! -t: workaround TCP bug */
80 int U_flag; /* -U: do not use high ports */
81 int v_level = 1; /* -v: verbosity level */
82 int v_tty; /* stdout is a tty */
83 pid_t pgrp; /* our process group */
84 long w_secs; /* -w: retry delay */
85 int family = PF_UNSPEC; /* -[46]: address family to use */
87 int sigalrm; /* SIGALRM received */
88 int siginfo; /* SIGINFO received */
89 int sigint; /* SIGINT received */
91 long ftp_timeout; /* default timeout for FTP transfers */
92 long http_timeout; /* default timeout for HTTP transfers */
93 char *buf; /* transfer buffer */
117 struct timeval start;
125 * Compute and display ETA
128 stat_eta(struct xferstat *xs)
132 off_t received, expected;
134 elapsed = xs->last.tv_sec - xs->start.tv_sec;
135 received = xs->rcvd - xs->offset;
136 expected = xs->size - xs->rcvd;
137 eta = (long)((double)elapsed * expected / received);
139 snprintf(str, sizeof str, "%02ldh%02ldm",
140 eta / 3600, (eta % 3600) / 60);
142 snprintf(str, sizeof str, "%02ldm%02lds",
148 * Format a number as "xxxx YB" where Y is ' ', 'k', 'M'...
150 static const char *prefixes = " kMGTP";
152 stat_bytes(off_t bytes)
155 const char *prefix = prefixes;
157 while (bytes > 9999 && prefix[1] != '\0') {
161 snprintf(str, sizeof str, "%4jd %cB", (intmax_t)bytes, *prefix);
166 * Compute and display transfer rate
169 stat_bps(struct xferstat *xs)
174 delta = (xs->last.tv_sec + (xs->last.tv_usec / 1.e6))
175 - (xs->start.tv_sec + (xs->start.tv_usec / 1.e6));
177 snprintf(str, sizeof str, "?? Bps");
179 bps = (xs->rcvd - xs->offset) / delta;
180 snprintf(str, sizeof str, "%sps", stat_bytes((off_t)bps));
186 * Update the stats display
189 stat_display(struct xferstat *xs, int force)
194 /* check if we're the foreground process */
195 if (ioctl(STDERR_FILENO, TIOCGPGRP, &ctty_pgrp) == -1 ||
196 (pid_t)ctty_pgrp != pgrp)
199 gettimeofday(&now, NULL);
200 if (!force && now.tv_sec <= xs->last.tv_sec)
204 fprintf(stderr, "\r%-46.46s", xs->name);
206 setproctitle("%s [%s]", xs->name, stat_bytes(xs->rcvd));
207 fprintf(stderr, " %s", stat_bytes(xs->rcvd));
209 setproctitle("%s [%d%% of %s]", xs->name,
210 (int)((100.0 * xs->rcvd) / xs->size),
211 stat_bytes(xs->size));
212 fprintf(stderr, "%3d%% of %s",
213 (int)((100.0 * xs->rcvd) / xs->size),
214 stat_bytes(xs->size));
216 fprintf(stderr, " %s", stat_bps(xs));
217 if (xs->size > 0 && xs->rcvd > 0 &&
218 xs->last.tv_sec >= xs->start.tv_sec + 10)
219 fprintf(stderr, " %s", stat_eta(xs));
223 * Initialize the transfer statistics
226 stat_start(struct xferstat *xs, const char *name, off_t size, off_t offset)
228 snprintf(xs->name, sizeof xs->name, "%s", name);
229 gettimeofday(&xs->start, NULL);
230 xs->last.tv_sec = xs->last.tv_usec = 0;
234 if (v_tty && v_level > 0)
236 else if (v_level > 0)
237 fprintf(stderr, "%-46s", xs->name);
241 * Update the transfer statistics
244 stat_update(struct xferstat *xs, off_t rcvd)
247 if (v_tty && v_level > 0)
252 * Finalize the transfer statistics
255 stat_end(struct xferstat *xs)
257 gettimeofday(&xs->last, NULL);
258 if (v_tty && v_level > 0) {
261 } else if (v_level > 0) {
262 fprintf(stderr, " %s %s\n",
263 stat_bytes(xs->size), stat_bps(xs));
268 * Ask the user for authentication details
271 query_auth(struct url *URL)
274 tcflag_t saved_flags;
277 fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
278 URL->scheme, URL->host, URL->port);
280 fprintf(stderr, "Login: ");
281 if (fgets(URL->user, sizeof URL->user, stdin) == NULL)
283 for (i = strlen(URL->user); i >= 0; --i)
284 if (URL->user[i] == '\r' || URL->user[i] == '\n')
287 fprintf(stderr, "Password: ");
288 if (tcgetattr(STDIN_FILENO, &tios) == 0) {
289 saved_flags = tios.c_lflag;
290 tios.c_lflag &= ~ECHO;
291 tios.c_lflag |= ECHONL|ICANON;
292 tcsetattr(STDIN_FILENO, TCSAFLUSH|TCSASOFT, &tios);
293 nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
294 tios.c_lflag = saved_flags;
295 tcsetattr(STDIN_FILENO, TCSANOW|TCSASOFT, &tios);
297 nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
301 for (i = strlen(URL->pwd); i >= 0; --i)
302 if (URL->pwd[i] == '\r' || URL->pwd[i] == '\n')
312 fetch(char *URL, const char *path)
335 /* set verbosity level */
342 if ((url = fetchParseURL(URL)) == NULL) {
343 warnx("%s: parse error", URL);
347 /* if no scheme was specified, take a guess */
350 strcpy(url->scheme, SCHEME_FILE);
351 else if (strncasecmp(url->host, "ftp.", 4) == 0)
352 strcpy(url->scheme, SCHEME_FTP);
353 else if (strncasecmp(url->host, "www.", 4) == 0)
354 strcpy(url->scheme, SCHEME_HTTP);
367 /* FTP specific flags */
368 if (strcmp(url->scheme, SCHEME_FTP) == 0) {
375 timeout = T_secs ? T_secs : ftp_timeout;
378 /* HTTP specific flags */
379 if (strcmp(url->scheme, SCHEME_HTTP) == 0) {
384 timeout = T_secs ? T_secs : http_timeout;
386 if (stat(i_filename, &sb)) {
387 warn("%s: stat()", i_filename);
390 url->ims_time = sb.st_mtime;
395 /* set the protocol timeout. */
396 fetchTimeout = timeout;
398 /* just print size */
402 r = fetchStat(url, &us, flags);
405 if (sigalrm || sigint)
408 warnx("%s", fetchLastErrString);
414 printf("%jd\n", (intmax_t)us.size);
419 * If the -r flag was specified, we have to compare the local
420 * and remote files, so we should really do a fetchStat()
421 * first, but I know of at least one HTTP server that only
422 * sends the content size in response to GET requests, and
423 * leaves it out of replies to HEAD requests. Also, in the
424 * (frequent) case that the local and remote files match but
425 * the local file is truncated, we have sufficient information
426 * before the compare to issue a correct request. Therefore,
427 * we always issue a GET request as if we were sure the local
428 * file was a truncated copy of the remote file; we can drop
429 * the connection later if we change our minds.
434 if (r == 0 && r_flag && S_ISREG(sb.st_mode)) {
435 url->offset = sb.st_size;
436 } else if (r == -1 || !S_ISREG(sb.st_mode)) {
438 * Whatever value sb.st_size has now is either
439 * wrong (if stat(2) failed) or irrelevant (if the
440 * path does not refer to a regular file)
444 if (r == -1 && errno != ENOENT) {
445 warnx("%s: stat()", path);
450 /* start the transfer */
453 f = fetchXGet(url, &us, flags);
456 if (sigalrm || sigint)
459 warnx("%s: %s", URL, fetchLastErrString);
460 if (i_flag && strcmp(url->scheme, SCHEME_HTTP) == 0
461 && fetchLastErrCode == FETCH_OK
462 && strcmp(fetchLastErrString, "Not Modified") == 0) {
463 /* HTTP Not Modified Response, return OK. */
472 /* check that size is as expected */
475 warnx("%s: size unknown", URL);
476 } else if (us.size != S_size) {
477 warnx("%s: size mismatch: expected %jd, actual %jd",
478 URL, (intmax_t)S_size, (intmax_t)us.size);
483 /* symlink instead of copy */
484 if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
485 if (symlink(url->doc, path) == -1) {
486 warn("%s: symlink()", path);
492 if (us.size == -1 && !o_stdout && v_level > 0)
493 warnx("%s: size of remote file is not known", URL);
495 if (sb.st_size != -1)
496 fprintf(stderr, "local size / mtime: %jd / %ld\n",
497 (intmax_t)sb.st_size, (long)sb.st_mtime);
499 fprintf(stderr, "remote size / mtime: %jd / %ld\n",
500 (intmax_t)us.size, (long)us.mtime);
503 /* open output file */
505 /* output to stdout */
507 } else if (r_flag && sb.st_size != -1) {
508 /* resume mode, local file exists */
509 if (!F_flag && us.mtime && sb.st_mtime != us.mtime) {
510 /* no match! have to refetch */
512 /* if precious, warn the user and give up */
514 warnx("%s: local modification time "
515 "does not match remote", path);
518 } else if (us.size != -1) {
519 if (us.size == sb.st_size)
522 if (sb.st_size > us.size) {
523 /* local file too long! */
524 warnx("%s: local file (%jd bytes) is longer "
525 "than remote file (%jd bytes)", path,
526 (intmax_t)sb.st_size, (intmax_t)us.size);
529 /* we got it, open local file */
530 if ((of = fopen(path, "a")) == NULL) {
531 warn("%s: fopen()", path);
534 /* check that it didn't move under our feet */
535 if (fstat(fileno(of), &nsb) == -1) {
537 warn("%s: fstat()", path);
540 if (nsb.st_dev != sb.st_dev ||
541 nsb.st_ino != nsb.st_ino ||
542 nsb.st_size != sb.st_size) {
543 warnx("%s: file has changed", URL);
549 } else if (m_flag && sb.st_size != -1) {
550 /* mirror mode, local file exists */
551 if (sb.st_size == us.size && sb.st_mtime == us.mtime)
557 * We don't yet have an output file; either this is a
558 * vanilla run with no special flags, or the local and
559 * remote files didn't match.
562 if (url->offset > 0) {
564 * We tried to restart a transfer, but for
565 * some reason gave up - so we have to restart
566 * from scratch if we want the whole file
569 if ((f = fetchXGet(url, &us, flags)) == NULL) {
570 warnx("%s: %s", URL, fetchLastErrString);
577 /* construct a temp file name */
578 if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
579 if ((slash = strrchr(path, '/')) == NULL)
583 asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s",
584 (int)(slash - path), path, slash);
585 if (tmppath != NULL) {
586 mkstemps(tmppath, strlen(slash) + 1);
587 of = fopen(tmppath, "w");
588 chown(tmppath, sb.st_uid, sb.st_gid);
589 chmod(tmppath, sb.st_mode & ALLPERMS);
593 of = fopen(path, "w");
595 warn("%s: open()", path);
601 /* start the counter */
602 stat_start(&xs, path, us.size, count);
604 sigalrm = siginfo = sigint = 0;
606 /* suck in the data */
607 signal(SIGINFO, sig_handler);
609 if (us.size != -1 && us.size - count < B_size &&
610 us.size - count >= 0)
611 size = us.size - count;
618 if ((size = fread(buf, 1, size, f)) == 0) {
619 if (ferror(f) && errno == EINTR && !sigint)
624 stat_update(&xs, count += size);
625 for (ptr = buf; size > 0; ptr += wr, size -= wr)
626 if ((wr = fwrite(ptr, 1, size, of)) < size) {
627 if (ferror(of) && errno == EINTR && !sigint)
636 sigalrm = ferror(f) && errno == ETIMEDOUT;
637 signal(SIGINFO, SIG_DFL);
642 * If the transfer timed out or was interrupted, we still want to
643 * set the mtime in case the file is not removed (-r or -R) and
644 * the user later restarts the transfer.
647 /* set mtime of local file */
648 if (!n_flag && us.mtime && !o_stdout && of != NULL &&
649 (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
650 struct timeval tv[2];
653 tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
654 tv[1].tv_sec = (long)us.mtime;
655 tv[0].tv_usec = tv[1].tv_usec = 0;
656 if (utimes(tmppath ? tmppath : path, tv))
657 warn("%s: utimes()", tmppath ? tmppath : path);
660 /* timed out or interrupted? */
662 warnx("transfer timed out");
664 warnx("transfer interrupted");
668 /* timeout / interrupt before connection completley established? */
673 /* check the status of our files */
678 if (ferror(f) || ferror(of))
682 /* did the transfer complete normally? */
683 if (us.size != -1 && count < us.size) {
684 warnx("%s appears to be truncated: %jd/%jd bytes",
685 path, (intmax_t)count, (intmax_t)us.size);
690 * If the transfer timed out and we didn't know how much to
691 * expect, assume the worst (i.e. we didn't get all of it)
693 if (sigalrm && us.size == -1) {
694 warnx("%s may be truncated", path);
700 if (tmppath != NULL && rename(tmppath, path) == -1) {
701 warn("%s: rename()", path);
706 if (of && of != stdout && !R_flag && !r_flag)
707 if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
708 unlink(tmppath ? tmppath : path);
709 if (R_flag && tmppath != NULL && sb.st_size == -1)
710 rename(tmppath, path); /* ignore errors here */
717 if (of && of != stdout)
729 fprintf(stderr, "%s\n%s\n%s\n%s\n",
730 "usage: fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [-N file] [-o file] [-S bytes]",
731 " [-T seconds] [-w seconds] [-i file] URL ...",
732 " fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [-N file] [-o file] [-S bytes]",
733 " [-T seconds] [-w seconds] [-i file] -h host -f file [-c dir]");
741 main(int argc, char *argv[])
749 while ((c = getopt(argc, argv,
750 "146AaB:bc:dFf:Hh:i:lMmN:nPpo:qRrS:sT:tUvw:")) != -1)
768 B_size = (off_t)strtol(optarg, &end, 10);
769 if (*optarg == '\0' || *end != '\0')
770 errx(1, "invalid buffer size (%s)", optarg);
773 warnx("warning: the -b option is deprecated");
789 warnx("the -H option is now implicit, "
790 "use -U to disable");
809 errx(1, "the -m and -r flags "
810 "are mutually exclusive");
831 errx(1, "the -m and -r flags "
832 "are mutually exclusive");
836 S_size = (off_t)strtol(optarg, &end, 10);
837 if (*optarg == '\0' || *end != '\0')
838 errx(1, "invalid size (%s)", optarg);
844 T_secs = strtol(optarg, &end, 10);
845 if (*optarg == '\0' || *end != '\0')
846 errx(1, "invalid timeout (%s)", optarg);
850 warnx("warning: the -t option is deprecated");
860 w_secs = strtol(optarg, &end, 10);
861 if (*optarg == '\0' || *end != '\0')
862 errx(1, "invalid delay (%s)", optarg);
872 if (h_hostname || f_filename || c_dirname) {
873 if (!h_hostname || !f_filename || argc) {
877 /* XXX this is a hack. */
878 if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
879 errx(1, "invalid hostname");
880 if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
881 c_dirname ? c_dirname : "", f_filename) == -1)
882 errx(1, "%s", strerror(ENOMEM));
891 /* allocate buffer */
892 if (B_size < MINBUFSIZE)
894 if ((buf = malloc(B_size)) == NULL)
895 errx(1, "%s", strerror(ENOMEM));
898 if ((s = getenv("FTP_TIMEOUT")) != NULL) {
899 ftp_timeout = strtol(s, &end, 10);
900 if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
901 warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
905 if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
906 http_timeout = strtol(s, &end, 10);
907 if (*s == '\0' || *end != '\0' || http_timeout < 0) {
908 warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
913 /* signal handling */
915 sa.sa_handler = sig_handler;
916 sigemptyset(&sa.sa_mask);
917 sigaction(SIGALRM, &sa, NULL);
918 sa.sa_flags = SA_RESETHAND;
919 sigaction(SIGINT, &sa, NULL);
920 fetchRestartCalls = 0;
924 if (strcmp(o_filename, "-") == 0) {
926 } else if (stat(o_filename, &sb) == -1) {
927 if (errno == ENOENT) {
929 errx(1, "%s is not a directory",
932 err(1, "%s", o_filename);
935 if (sb.st_mode & S_IFDIR)
940 /* check if output is to a tty (for progress report) */
941 v_tty = isatty(STDERR_FILENO);
949 fetchAuthMethod = query_auth;
950 if (N_filename != NULL)
951 setenv("NETRC", N_filename, 1);
954 if ((p = strrchr(*argv, '/')) == NULL)
962 fetchLastErrCode = 0;
966 e = fetch(*argv, "-");
967 } else if (o_directory) {
968 asprintf(&q, "%s/%s", o_filename, p);
972 e = fetch(*argv, o_filename);
979 kill(getpid(), SIGINT);
981 if (e == 0 && once_flag)
986 if ((fetchLastErrCode
987 && fetchLastErrCode != FETCH_UNAVAIL
988 && fetchLastErrCode != FETCH_MOVED
989 && fetchLastErrCode != FETCH_URL
990 && fetchLastErrCode != FETCH_RESOLV
991 && fetchLastErrCode != FETCH_UNKNOWN)) {
992 if (w_secs && v_level)
993 fprintf(stderr, "Waiting %ld seconds "
994 "before retrying\n", w_secs);