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.
28 * $FreeBSD: src/usr.bin/fetch/fetch.c,v 1.84 2009/01/17 13:34:56 des Exp $
31 #include <sys/param.h>
32 #include <sys/socket.h>
49 #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; /* -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 = TIMEOUT; /* default timeout for FTP transfers */
92 long http_timeout = 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)
319 size_t size, readcnt, wr;
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 */
348 if (*url->scheme == 0) {
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 ||
380 strcmp(url->scheme, SCHEME_HTTPS) == 0) {
385 timeout = T_secs ? T_secs : http_timeout;
387 if (stat(i_filename, &sb)) {
388 warn("%s: stat()", i_filename);
391 url->ims_time = sb.st_mtime;
396 /* set the protocol timeout. */
397 fetchTimeout = timeout;
399 /* just print size */
403 r = fetchStat(url, &us, flags);
406 if (sigalrm || sigint)
409 warnx("%s", fetchLastErrString);
415 printf("%jd\n", (intmax_t)us.size);
420 * If the -r flag was specified, we have to compare the local
421 * and remote files, so we should really do a fetchStat()
422 * first, but I know of at least one HTTP server that only
423 * sends the content size in response to GET requests, and
424 * leaves it out of replies to HEAD requests. Also, in the
425 * (frequent) case that the local and remote files match but
426 * the local file is truncated, we have sufficient information
427 * before the compare to issue a correct request. Therefore,
428 * we always issue a GET request as if we were sure the local
429 * file was a truncated copy of the remote file; we can drop
430 * the connection later if we change our minds.
435 if (r == 0 && r_flag && S_ISREG(sb.st_mode)) {
436 url->offset = sb.st_size;
437 } else if (r == -1 || !S_ISREG(sb.st_mode)) {
439 * Whatever value sb.st_size has now is either
440 * wrong (if stat(2) failed) or irrelevant (if the
441 * path does not refer to a regular file)
445 if (r == -1 && errno != ENOENT) {
446 warnx("%s: stat()", path);
451 /* start the transfer */
454 f = fetchXGet(url, &us, flags);
457 if (sigalrm || sigint)
460 warnx("%s: %s", URL, fetchLastErrString);
461 if (i_flag && strcmp(url->scheme, SCHEME_HTTP) == 0
462 && fetchLastErrCode == FETCH_OK
463 && strcmp(fetchLastErrString, "Not Modified") == 0) {
464 /* HTTP Not Modified Response, return OK. */
473 /* check that size is as expected */
476 warnx("%s: size unknown", URL);
477 } else if (us.size != S_size) {
478 warnx("%s: size mismatch: expected %jd, actual %jd",
479 URL, (intmax_t)S_size, (intmax_t)us.size);
484 /* symlink instead of copy */
485 if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
486 if (symlink(url->doc, path) == -1) {
487 warn("%s: symlink()", path);
493 if (us.size == -1 && !o_stdout && v_level > 0)
494 warnx("%s: size of remote file is not known", URL);
496 if (sb.st_size != -1)
497 fprintf(stderr, "local size / mtime: %jd / %ld\n",
498 (intmax_t)sb.st_size, (long)sb.st_mtime);
500 fprintf(stderr, "remote size / mtime: %jd / %ld\n",
501 (intmax_t)us.size, (long)us.mtime);
504 /* open output file */
506 /* output to stdout */
508 } else if (r_flag && sb.st_size != -1) {
509 /* resume mode, local file exists */
510 if (!F_flag && us.mtime && sb.st_mtime != us.mtime) {
511 /* no match! have to refetch */
513 /* if precious, warn the user and give up */
515 warnx("%s: local modification time "
516 "does not match remote", path);
519 } else if (us.size != -1) {
520 if (us.size == sb.st_size)
523 if (sb.st_size > us.size) {
524 /* local file too long! */
525 warnx("%s: local file (%jd bytes) is longer "
526 "than remote file (%jd bytes)", path,
527 (intmax_t)sb.st_size, (intmax_t)us.size);
530 /* we got it, open local file */
531 if ((of = fopen(path, "a")) == NULL) {
532 warn("%s: fopen()", path);
535 /* check that it didn't move under our feet */
536 if (fstat(fileno(of), &nsb) == -1) {
538 warn("%s: fstat()", path);
541 if (nsb.st_dev != sb.st_dev ||
542 nsb.st_ino != sb.st_ino ||
543 nsb.st_size != sb.st_size) {
544 warnx("%s: file has changed", URL);
550 } else if (m_flag && sb.st_size != -1) {
551 /* mirror mode, local file exists */
552 if (sb.st_size == us.size && sb.st_mtime == us.mtime)
558 * We don't yet have an output file; either this is a
559 * vanilla run with no special flags, or the local and
560 * remote files didn't match.
563 if (url->offset > 0) {
565 * We tried to restart a transfer, but for
566 * some reason gave up - so we have to restart
567 * from scratch if we want the whole file
570 if ((f = fetchXGet(url, &us, flags)) == NULL) {
571 warnx("%s: %s", URL, fetchLastErrString);
578 /* construct a temporary file name */
579 if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
580 if ((slash = strrchr(path, '/')) == NULL)
584 asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s",
585 (int)(slash - path), path, slash);
586 if (tmppath != NULL) {
587 if (mkstemps(tmppath, strlen(slash)+1) == -1) {
588 warn("%s: mkstemps()", path);
592 of = fopen(tmppath, "w");
593 chown(tmppath, sb.st_uid, sb.st_gid);
594 chmod(tmppath, sb.st_mode & ALLPERMS);
599 if ((of = fopen(path, "w")) == NULL) {
600 warn("%s: fopen()", path);
606 /* start the counter */
607 stat_start(&xs, path, us.size, count);
609 sigalrm = siginfo = sigint = 0;
611 /* suck in the data */
612 signal(SIGINFO, sig_handler);
614 if (us.size != -1 && us.size - count < B_size &&
615 us.size - count >= 0)
616 size = us.size - count;
627 if ((readcnt = fread(buf, 1, size, f)) < size) {
628 if (ferror(f) && errno == EINTR && !sigint)
630 else if (readcnt == 0)
634 stat_update(&xs, count += readcnt);
635 for (ptr = buf; readcnt > 0; ptr += wr, readcnt -= wr)
636 if ((wr = fwrite(ptr, 1, readcnt, of)) < readcnt) {
637 if (ferror(of) && errno == EINTR && !sigint)
646 sigalrm = ferror(f) && errno == ETIMEDOUT;
647 signal(SIGINFO, SIG_DFL);
652 * If the transfer timed out or was interrupted, we still want to
653 * set the mtime in case the file is not removed (-r or -R) and
654 * the user later restarts the transfer.
657 /* set mtime of local file */
658 if (!n_flag && us.mtime && !o_stdout && of != NULL &&
659 (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
660 struct timeval tv[2];
663 tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
664 tv[1].tv_sec = (long)us.mtime;
665 tv[0].tv_usec = tv[1].tv_usec = 0;
666 if (utimes(tmppath ? tmppath : path, tv))
667 warn("%s: utimes()", tmppath ? tmppath : path);
670 /* timed out or interrupted? */
672 warnx("transfer timed out");
674 warnx("transfer interrupted");
678 /* timeout / interrupt before connection completley established? */
683 /* check the status of our files */
688 if (ferror(f) || ferror(of))
692 /* did the transfer complete normally? */
693 if (us.size != -1 && count < us.size) {
694 warnx("%s appears to be truncated: %jd/%jd bytes",
695 path, (intmax_t)count, (intmax_t)us.size);
700 * If the transfer timed out and we didn't know how much to
701 * expect, assume the worst (i.e. we didn't get all of it)
703 if (sigalrm && us.size == -1) {
704 warnx("%s may be truncated", path);
710 if (tmppath != NULL && rename(tmppath, path) == -1) {
711 warn("%s: rename()", path);
716 if (of && of != stdout && !R_flag && !r_flag)
717 if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
718 unlink(tmppath ? tmppath : path);
719 if (R_flag && tmppath != NULL && sb.st_size == -1)
720 rename(tmppath, path); /* ignore errors here */
727 if (of && of != stdout)
739 fprintf(stderr, "%s\n%s\n%s\n%s\n",
740 "usage: fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [-N file] [-o file] [-S bytes]",
741 " [-T seconds] [-w seconds] [-i file] URL ...",
742 " fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [-N file] [-o file] [-S bytes]",
743 " [-T seconds] [-w seconds] [-i file] -h host -f file [-c dir]");
751 main(int argc, char *argv[])
759 while ((c = getopt(argc, argv,
760 "146AaB:bc:dFf:Hh:i:lMmN:nPpo:qRrS:sT:tUvw:")) != -1)
778 B_size = (off_t)strtol(optarg, &end, 10);
779 if (*optarg == '\0' || *end != '\0')
780 errx(1, "invalid buffer size (%s)", optarg);
783 warnx("warning: the -b option is deprecated");
799 warnx("the -H option is now implicit, "
800 "use -U to disable");
819 errx(1, "the -m and -r flags "
820 "are mutually exclusive");
841 errx(1, "the -m and -r flags "
842 "are mutually exclusive");
846 S_size = (off_t)strtol(optarg, &end, 10);
847 if (*optarg == '\0' || *end != '\0')
848 errx(1, "invalid size (%s)", optarg);
854 T_secs = strtol(optarg, &end, 10);
855 if (*optarg == '\0' || *end != '\0')
856 errx(1, "invalid timeout (%s)", optarg);
860 warnx("warning: the -t option is deprecated");
870 w_secs = strtol(optarg, &end, 10);
871 if (*optarg == '\0' || *end != '\0')
872 errx(1, "invalid delay (%s)", optarg);
882 if (h_hostname || f_filename || c_dirname) {
883 if (!h_hostname || !f_filename || argc) {
887 /* XXX this is a hack. */
888 if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
889 errx(1, "invalid hostname");
890 if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
891 c_dirname ? c_dirname : "", f_filename) == -1)
892 errx(1, "%s", strerror(ENOMEM));
901 /* allocate buffer */
902 if (B_size < MINBUFSIZE)
904 if ((buf = malloc(B_size)) == NULL)
905 errx(1, "%s", strerror(ENOMEM));
908 if ((s = getenv("FTP_TIMEOUT")) != NULL) {
909 ftp_timeout = strtol(s, &end, 10);
910 if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
911 warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
915 if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
916 http_timeout = strtol(s, &end, 10);
917 if (*s == '\0' || *end != '\0' || http_timeout < 0) {
918 warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
923 /* signal handling */
925 sa.sa_handler = sig_handler;
926 sigemptyset(&sa.sa_mask);
927 sigaction(SIGALRM, &sa, NULL);
928 sa.sa_flags = SA_RESETHAND;
929 sigaction(SIGINT, &sa, NULL);
930 fetchRestartCalls = 0;
934 if (strcmp(o_filename, "-") == 0) {
936 } else if (stat(o_filename, &sb) == -1) {
937 if (errno == ENOENT) {
939 errx(1, "%s is not a directory",
942 err(1, "%s", o_filename);
945 if (sb.st_mode & S_IFDIR)
950 /* check if output is to a tty (for progress report) */
951 v_tty = isatty(STDERR_FILENO);
959 fetchAuthMethod = query_auth;
960 if (N_filename != NULL) {
961 if (setenv("NETRC", N_filename, 1) == -1)
962 err(1, "setenv: cannot set NETRC=%s", N_filename);
966 if ((p = strrchr(*argv, '/')) == NULL)
974 fetchLastErrCode = 0;
978 e = fetch(*argv, "-");
979 } else if (o_directory) {
980 asprintf(&q, "%s/%s", o_filename, p);
984 e = fetch(*argv, o_filename);
991 kill(getpid(), SIGINT);
993 if (e == 0 && once_flag)
998 if ((fetchLastErrCode
999 && fetchLastErrCode != FETCH_UNAVAIL
1000 && fetchLastErrCode != FETCH_MOVED
1001 && fetchLastErrCode != FETCH_URL
1002 && fetchLastErrCode != FETCH_RESOLV
1003 && fetchLastErrCode != FETCH_UNKNOWN)) {
1004 if (w_secs && v_level)
1005 fprintf(stderr, "Waiting %ld seconds "
1006 "before retrying\n", w_secs);