2 * Copyright (c) 2000 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.
31 #include <sys/param.h>
33 #include <sys/socket.h>
47 #define MINBUFSIZE 4096
50 int A_flag; /* -A: do not follow 302 redirects */
51 int a_flag; /* -a: auto retry */
52 size_t B_size; /* -B: buffer size */
53 int b_flag; /*! -b: workaround TCP bug */
54 char *c_dirname; /* -c: remote directory */
55 int d_flag; /* -d: direct connection */
56 int F_flag; /* -F: restart without checking mtime */
57 char *f_filename; /* -f: file to fetch */
58 int H_flag; /* -H: use high port */
59 char *h_hostname; /* -h: host to fetch from */
60 int l_flag; /* -l: link rather than copy file: URLs */
61 int m_flag; /* -[Mm]: mirror mode */
62 int n_flag; /* -n: do not preserve modification time */
63 int o_flag; /* -o: specify output file */
64 int o_directory; /* output file is a directory */
65 char *o_filename; /* name of output file */
66 int o_stdout; /* output file is stdout */
67 int once_flag; /* -1: stop at first successful file */
68 int p_flag = 1; /* -[Pp]: use passive FTP */
69 int R_flag; /* -R: don't delete partially transferred files */
70 int r_flag; /* -r: restart previously interrupted transfer */
71 u_int T_secs = 0; /* -T: transfer timeout in seconds */
72 int s_flag; /* -s: show size, don't fetch */
73 off_t S_size; /* -S: require size to match */
74 int t_flag; /*! -t: workaround TCP bug */
75 int v_level = 1; /* -v: verbosity level */
76 int v_tty; /* stdout is a tty */
77 u_int w_secs; /* -w: retry delay */
78 int family = PF_UNSPEC; /* -[46]: address family to use */
80 int sigalrm; /* SIGALRM received */
81 int sigint; /* SIGINT received */
83 u_int ftp_timeout; /* default timeout for FTP transfers */
84 u_int http_timeout; /* default timeout for HTTP transfers */
85 u_char *buf; /* transfer buffer */
103 struct timeval start;
112 stat_display(struct xferstat *xs, int force)
119 gettimeofday(&now, NULL);
120 if (!force && now.tv_sec <= xs->last.tv_sec)
124 fprintf(stderr, "\rReceiving %s", xs->name);
126 fprintf(stderr, ": %lld bytes", xs->rcvd);
128 fprintf(stderr, " (%lld bytes): %d%%", xs->size,
129 (int)((100.0 * xs->rcvd) / xs->size));
133 stat_start(struct xferstat *xs, char *name, off_t size, off_t offset)
135 snprintf(xs->name, sizeof xs->name, "%s", name);
136 gettimeofday(&xs->start, NULL);
137 xs->last.tv_sec = xs->last.tv_usec = 0;
146 stat_update(struct xferstat *xs, off_t rcvd, int force)
153 stat_end(struct xferstat *xs)
158 gettimeofday(&xs->end, NULL);
162 delta = (xs->end.tv_sec + (xs->end.tv_usec / 1.e6))
163 - (xs->start.tv_sec + (xs->start.tv_usec / 1.e6));
164 fprintf(stderr, "%lld bytes transferred in %.1f seconds ",
165 xs->rcvd - xs->offset, delta);
166 bps = (xs->rcvd - xs->offset) / delta;
168 fprintf(stderr, "(%.2f MBps)\n", bps / (1024*1024));
170 fprintf(stderr, "(%.2f kBps)\n", bps / 1024);
172 fprintf(stderr, "(%.2f Bps)\n", bps);
176 fetch(char *URL, char *path)
192 if ((url = fetchParseURL(URL)) == NULL) {
193 warnx("%s: parse error", URL);
213 /* FTP specific flags */
214 if (strcmp(url->scheme, "ftp") == 0) {
221 timeout = T_secs ? T_secs : ftp_timeout;
224 /* HTTP specific flags */
225 if (strcmp(url->scheme, "http") == 0) {
230 timeout = T_secs ? T_secs : http_timeout;
233 /* set the protocol timeout. */
234 fetchTimeout = timeout;
236 /* just print size */
238 if (fetchStat(url, &us, flags) == -1)
243 printf("%lld\n", us.size);
248 * If the -r flag was specified, we have to compare the local and
249 * remote files, so we should really do a fetchStat() first, but I
250 * know of at least one HTTP server that only sends the content
251 * size in response to GET requests, and leaves it out of replies
252 * to HEAD requests. Also, in the (frequent) case that the local
253 * and remote files match but the local file is truncated, we have
254 * sufficient information *before* the compare to issue a correct
255 * request. Therefore, we always issue a GET request as if we were
256 * sure the local file was a truncated copy of the remote file; we
257 * can drop the connection later if we change our minds.
259 if (r_flag && !o_stdout && stat(path, &sb) != -1)
260 url->offset = sb.st_size;
262 /* start the transfer */
263 if ((f = fetchXGet(url, &us, flags)) == NULL) {
264 warnx("%s: %s", path, fetchLastErrString);
270 /* check that size is as expected */
273 warnx("%s: size unknown", path);
275 } else if (us.size != S_size) {
276 warnx("%s: size mismatch: expected %lld, actual %lld",
277 path, S_size, us.size);
282 /* symlink instead of copy */
283 if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
284 if (symlink(url->doc, path) == -1) {
285 warn("%s: symlink()", path);
291 /* open output file */
293 /* output to stdout */
295 } else if (url->offset) {
296 /* resume mode, local file exists */
297 if (!F_flag && us.mtime && sb.st_mtime != us.mtime) {
298 /* no match! have to refetch */
301 if ((f = fetchXGet(url, &us, flags)) == NULL) {
302 warnx("%s: %s", path, fetchLastErrString);
308 us.size += url->offset;
310 if (us.size == sb.st_size)
313 if (sb.st_size > us.size) {
314 /* local file too long! */
315 warnx("%s: local file (%lld bytes) is longer "
316 "than remote file (%lld bytes)",
317 path, sb.st_size, us.size);
320 /* we got through, open local file in append mode */
322 * XXX there's a race condition here - the file we open is not
323 * necessarily the same as the one we stat()'ed earlier...
325 if ((of = fopen(path, "a")) == NULL) {
326 warn("%s: open()", path);
330 if (m_flag && stat(path, &sb) != -1) {
331 /* mirror mode, local file exists */
332 if (sb.st_size == us.size && sb.st_mtime == us.mtime)
337 * We don't yet have an output file; either this is a vanilla
338 * run with no special flags, or the local and remote files
341 if ((of = fopen(path, "w")) == NULL) {
342 warn("%s: open()", path);
348 /* start the counter */
349 stat_start(&xs, path, us.size, count);
351 sigint = sigalrm = 0;
353 /* suck in the data */
354 for (n = 0; !sigint && !sigalrm; ++n) {
355 if (us.size != -1 && us.size - count < B_size)
356 size = us.size - count;
361 if ((size = fread(buf, 1, size, f)) <= 0)
363 stat_update(&xs, count += size, 0);
364 if (fwrite(buf, size, 1, of) != 1)
373 /* Set mtime of local file */
374 if (!n_flag && us.mtime && !o_stdout) {
375 struct timeval tv[2];
378 tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
379 tv[1].tv_sec = (long)us.mtime;
380 tv[0].tv_usec = tv[1].tv_usec = 0;
381 if (utimes(path, tv))
382 warn("%s: utimes()", path);
385 /* timed out or interrupted? */
388 warnx("transfer timed out");
390 warnx("transfer interrupted");
392 if (!sigalrm && !sigint) {
393 /* check the status of our files */
398 if (ferror(f) || ferror(of))
402 /* did the transfer complete normally? */
403 if (us.size != -1 && count < us.size) {
404 warnx("%s appears to be truncated: %lld/%lld bytes",
405 path, count, us.size);
413 if (of && of != stdout && !R_flag && !r_flag)
421 if (of && of != stdout)
431 /* XXX badly out of synch */
433 "Usage: fetch [-1AFHMPRabdlmnpqrstv] [-o outputfile] [-S bytes]\n"
434 " [-B bytes] [-T seconds] [-w seconds]\n"
435 " [-f file -h host [-c dir] | URL ...]\n"
440 #define PARSENUM(NAME, TYPE) \
442 NAME(char *s, TYPE *v) \
445 for (*v = 0; *s; s++) \
447 *v = *v * 10 + *s - '0'; \
453 PARSENUM(parseint, u_int)
454 PARSENUM(parsesize, size_t)
455 PARSENUM(parseoff, off_t)
458 main(int argc, char *argv[])
465 while ((c = getopt(argc, argv,
466 "146AaB:bc:dFf:h:lHMmnPpo:qRrS:sT:tvw:")) != EOF)
484 if (parsesize(optarg, &B_size) == -1)
485 errx(1, "invalid buffer size");
488 warnx("warning: the -b option is deprecated");
519 errx(1, "the -m and -r flags are mutually exclusive");
537 errx(1, "the -m and -r flags are mutually exclusive");
541 if (parseoff(optarg, &S_size) == -1)
542 errx(1, "invalid size");
548 if (parseint(optarg, &T_secs) == -1)
549 errx(1, "invalid timeout");
553 warnx("warning: the -t option is deprecated");
560 if (parseint(optarg, &w_secs) == -1)
561 errx(1, "invalid delay");
571 if (h_hostname || f_filename || c_dirname) {
572 if (!h_hostname || !f_filename || argc) {
576 /* XXX this is a hack. */
577 if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
578 errx(1, "invalid hostname");
579 if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
580 c_dirname ? c_dirname : "", f_filename) == -1)
581 errx(1, strerror(ENOMEM));
590 /* allocate buffer */
591 if (B_size < MINBUFSIZE)
593 if ((buf = malloc(B_size)) == NULL)
594 errx(1, strerror(ENOMEM));
597 if ((s = getenv("FTP_TIMEOUT")) != NULL) {
598 if (parseint(s, &ftp_timeout) == -1) {
599 warnx("FTP_TIMEOUT is not a positive integer");
603 if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
604 if (parseint(s, &http_timeout) == -1) {
605 warnx("HTTP_TIMEOUT is not a positive integer");
610 /* signal handling */
612 sa.sa_handler = sig_handler;
613 sigemptyset(&sa.sa_mask);
614 sigaction(SIGALRM, &sa, NULL);
615 sa.sa_flags = SA_RESETHAND;
616 sigaction(SIGINT, &sa, NULL);
617 fetchRestartCalls = 0;
621 if (strcmp(o_filename, "-") == 0) {
623 } else if (stat(o_filename, &sb) == -1) {
624 if (errno == ENOENT) {
626 errx(EX_USAGE, "%s is not a directory", o_filename);
628 err(EX_IOERR, "%s", o_filename);
631 if (sb.st_mode & S_IFDIR)
636 /* check if output is to a tty (for progress report) */
637 v_tty = isatty(STDERR_FILENO);
641 if ((p = strrchr(*argv, '/')) == NULL)
649 fetchLastErrCode = 0;
653 e = fetch(*argv, "-");
654 } else if (o_directory) {
655 asprintf(&q, "%s/%s", o_filename, p);
659 e = fetch(*argv, o_filename);
666 kill(getpid(), SIGINT);
668 if (e == 0 && once_flag)
673 if ((fetchLastErrCode
674 && fetchLastErrCode != FETCH_UNAVAIL
675 && fetchLastErrCode != FETCH_MOVED
676 && fetchLastErrCode != FETCH_URL
677 && fetchLastErrCode != FETCH_RESOLV
678 && fetchLastErrCode != FETCH_UNKNOWN)) {
681 fprintf(stderr, "Waiting %d seconds before retrying\n",