2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 2000-2014 Dag-Erling Smørgrav
5 * Copyright (c) 2013 Michael Gmelin <freebsd@grem.de>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer
13 * in this position and unchanged.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. The name of the author may not be used to endorse or promote products
18 * derived from this software without specific prior written permission
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include <sys/param.h>
33 #include <sys/socket.h>
51 #define MINBUFSIZE 16384
55 static int A_flag; /* -A: do not follow 302 redirects */
56 static int a_flag; /* -a: auto retry */
57 static off_t B_size; /* -B: buffer size */
58 static int b_flag; /*! -b: workaround TCP bug */
59 static char *c_dirname; /* -c: remote directory */
60 static int d_flag; /* -d: direct connection */
61 static int F_flag; /* -F: restart without checking mtime */
62 static char *f_filename; /* -f: file to fetch */
63 static char *h_hostname; /* -h: host to fetch from */
64 static int i_flag; /* -i: specify file for mtime comparison */
65 static char *i_filename; /* name of input file */
66 static int l_flag; /* -l: link rather than copy file: URLs */
67 static int m_flag; /* -[Mm]: mirror mode */
68 static char *N_filename; /* -N: netrc file name */
69 static int n_flag; /* -n: do not preserve modification time */
70 static int o_flag; /* -o: specify output file */
71 static int o_directory; /* output file is a directory */
72 static char *o_filename; /* name of output file */
73 static int o_stdout; /* output file is stdout */
74 static int once_flag; /* -1: stop at first successful file */
75 static int p_flag; /* -[Pp]: use passive FTP */
76 static int R_flag; /* -R: don't delete partial files */
77 static int r_flag; /* -r: restart previous transfer */
78 static off_t S_size; /* -S: require size to match */
79 static int s_flag; /* -s: show size, don't fetch */
80 static long T_secs; /* -T: transfer timeout in seconds */
81 static int t_flag; /*! -t: workaround TCP bug */
82 static int U_flag; /* -U: do not use high ports */
83 static int v_level = 1; /* -v: verbosity level */
84 static int v_tty; /* stdout is a tty */
85 static int v_progress; /* whether to display progress */
86 static pid_t pgrp; /* our process group */
87 static long w_secs; /* -w: retry delay */
88 static int family = PF_UNSPEC; /* -[46]: address family to use */
90 static int sigalrm; /* SIGALRM received */
91 static int siginfo; /* SIGINFO received */
92 static int sigint; /* SIGINT received */
94 static long ftp_timeout = TIMEOUT; /* default timeout for FTP transfers */
95 static long http_timeout = TIMEOUT;/* default timeout for HTTP transfers */
96 static char *buf; /* transfer buffer */
101 OPTION_NO_FTP_PASSIVE_MODE,
103 OPTION_HTTP_USER_AGENT,
105 OPTION_SSL_CA_CERT_FILE,
106 OPTION_SSL_CA_CERT_PATH,
107 OPTION_SSL_CLIENT_CERT_FILE,
108 OPTION_SSL_CLIENT_KEY_FILE,
112 OPTION_SSL_NO_VERIFY_HOSTNAME,
113 OPTION_SSL_NO_VERIFY_PEER
117 static struct option longopts[] =
119 /* mapping to single character argument */
120 { "one-file", no_argument, NULL, '1' },
121 { "ipv4-only", no_argument, NULL, '4' },
122 { "ipv6-only", no_argument, NULL, '6' },
123 { "no-redirect", no_argument, NULL, 'A' },
124 { "retry", no_argument, NULL, 'a' },
125 { "buffer-size", required_argument, NULL, 'B' },
126 /* -c not mapped, since it's deprecated */
127 { "direct", no_argument, NULL, 'd' },
128 { "force-restart", no_argument, NULL, 'F' },
129 /* -f not mapped, since it's deprecated */
130 /* -h not mapped, since it's deprecated */
131 { "if-modified-since", required_argument, NULL, 'i' },
132 { "symlink", no_argument, NULL, 'l' },
133 /* -M not mapped since it's the same as -m */
134 { "mirror", no_argument, NULL, 'm' },
135 { "netrc", required_argument, NULL, 'N' },
136 { "no-mtime", no_argument, NULL, 'n' },
137 { "output", required_argument, NULL, 'o' },
138 /* -P not mapped since it's the same as -p */
139 { "passive", no_argument, NULL, 'p' },
140 { "quiet", no_argument, NULL, 'q' },
141 { "keep-output", no_argument, NULL, 'R' },
142 { "restart", no_argument, NULL, 'r' },
143 { "require-size", required_argument, NULL, 'S' },
144 { "print-size", no_argument, NULL, 's' },
145 { "timeout", required_argument, NULL, 'T' },
146 { "passive-portrange-default", no_argument, NULL, 'T' },
147 { "verbose", no_argument, NULL, 'v' },
148 { "retry-delay", required_argument, NULL, 'w' },
150 /* options without a single character equivalent */
151 { "bind-address", required_argument, NULL, OPTION_BIND_ADDRESS },
152 { "no-passive", no_argument, NULL, OPTION_NO_FTP_PASSIVE_MODE },
153 { "referer", required_argument, NULL, OPTION_HTTP_REFERER },
154 { "user-agent", required_argument, NULL, OPTION_HTTP_USER_AGENT },
155 { "no-proxy", required_argument, NULL, OPTION_NO_PROXY },
156 { "ca-cert", required_argument, NULL, OPTION_SSL_CA_CERT_FILE },
157 { "ca-path", required_argument, NULL, OPTION_SSL_CA_CERT_PATH },
158 { "cert", required_argument, NULL, OPTION_SSL_CLIENT_CERT_FILE },
159 { "key", required_argument, NULL, OPTION_SSL_CLIENT_KEY_FILE },
160 { "crl", required_argument, NULL, OPTION_SSL_CRL_FILE },
161 { "no-sslv3", no_argument, NULL, OPTION_SSL_NO_SSL3 },
162 { "no-tlsv1", no_argument, NULL, OPTION_SSL_NO_TLS1 },
163 { "no-verify-hostname", no_argument, NULL, OPTION_SSL_NO_VERIFY_HOSTNAME },
164 { "no-verify-peer", no_argument, NULL, OPTION_SSL_NO_VERIFY_PEER },
190 struct timeval start; /* start of transfer */
191 struct timeval last; /* time of last update */
192 struct timeval last2; /* time of previous last update */
193 off_t size; /* size of file per HTTP hdr */
194 off_t offset; /* starting offset in file */
195 off_t rcvd; /* bytes already received */
196 off_t lastrcvd; /* bytes received since last update */
200 * Format a number of seconds as either XXdYYh, XXhYYm, XXmYYs, or XXs
201 * depending on its magnitude
204 stat_seconds(char *str, size_t strsz, long seconds)
208 snprintf(str, strsz, "%02ldd%02ldh",
209 seconds / 86400, (seconds % 86400) / 3600);
210 else if (seconds > 3600)
211 snprintf(str, strsz, "%02ldh%02ldm",
212 seconds / 3600, (seconds % 3600) / 60);
213 else if (seconds > 60)
214 snprintf(str, strsz, "%02ldm%02lds",
215 seconds / 60, seconds % 60);
217 snprintf(str, strsz, " %02lds",
222 * Compute and display ETA
225 stat_eta(char *str, size_t strsz, const struct xferstat *xs)
228 off_t received, expected;
230 elapsed = xs->last.tv_sec - xs->start.tv_sec;
231 received = xs->rcvd - xs->offset;
232 expected = xs->size - xs->rcvd;
233 eta = (long)((double)elapsed * expected / received);
235 stat_seconds(str, strsz, eta);
237 stat_seconds(str, strsz, elapsed);
241 * Format a number as "xxxx YB" where Y is ' ', 'k', 'M'...
243 static const char *prefixes = " kMGTP";
245 stat_bytes(char *str, size_t strsz, off_t bytes)
247 const char *prefix = prefixes;
249 while (bytes > 9999 && prefix[1] != '\0') {
253 snprintf(str, strsz, "%4ju %cB", (uintmax_t)bytes, *prefix);
257 * Compute and display transfer rate
260 stat_bps(char *str, size_t strsz, struct xferstat *xs)
265 delta = ((double)xs->last.tv_sec + (xs->last.tv_usec / 1.e6))
266 - ((double)xs->last2.tv_sec + (xs->last2.tv_usec / 1.e6));
269 snprintf(str, strsz, "?? Bps");
271 bps = (xs->rcvd - xs->lastrcvd) / delta;
272 stat_bytes(bytes, sizeof bytes, (off_t)bps);
273 snprintf(str, strsz, "%sps", bytes);
278 * Update the stats display
281 stat_display(struct xferstat *xs, int force)
283 char bytes[16], bps[16], eta[16];
287 /* check if we're the foreground process */
288 if (ioctl(STDERR_FILENO, TIOCGPGRP, &ctty_pgrp) != 0 ||
289 (pid_t)ctty_pgrp != pgrp)
292 gettimeofday(&now, NULL);
293 if (!force && now.tv_sec <= xs->last.tv_sec)
295 xs->last2 = xs->last;
298 fprintf(stderr, "\r%-46.46s", xs->name);
299 if (xs->rcvd >= xs->size) {
300 stat_bytes(bytes, sizeof bytes, xs->rcvd);
301 setproctitle("%s [%s]", xs->name, bytes);
302 fprintf(stderr, " %s", bytes);
304 stat_bytes(bytes, sizeof bytes, xs->size);
305 setproctitle("%s [%d%% of %s]", xs->name,
306 (int)((100.0 * xs->rcvd) / xs->size),
308 fprintf(stderr, "%3d%% of %s",
309 (int)((100.0 * xs->rcvd) / xs->size),
313 xs->lastrcvd = xs->offset;
314 xs->last2 = xs->start;
316 stat_bps(bps, sizeof bps, xs);
317 fprintf(stderr, " %s", bps);
318 if ((xs->size > 0 && xs->rcvd > 0 &&
319 xs->last.tv_sec >= xs->start.tv_sec + 3) ||
321 stat_eta(eta, sizeof eta, xs);
322 fprintf(stderr, " %s", eta);
324 xs->lastrcvd = xs->rcvd;
328 * Initialize the transfer statistics
331 stat_start(struct xferstat *xs, const char *name, off_t size, off_t offset)
334 memset(xs, 0, sizeof *xs);
335 snprintf(xs->name, sizeof xs->name, "%s", name);
336 gettimeofday(&xs->start, NULL);
337 xs->last2 = xs->last = xs->start;
341 xs->lastrcvd = offset;
344 else if (v_level > 0)
345 fprintf(stderr, "%-46s", xs->name);
349 * Update the transfer statistics
352 stat_update(struct xferstat *xs, off_t rcvd)
361 * Finalize the transfer statistics
364 stat_end(struct xferstat *xs)
366 char bytes[16], bps[16], eta[16];
368 gettimeofday(&xs->last, NULL);
372 } else if (v_level > 0) {
373 stat_bytes(bytes, sizeof bytes, xs->rcvd);
374 stat_bps(bps, sizeof bps, xs);
375 stat_eta(eta, sizeof eta, xs);
376 fprintf(stderr, " %s %s %s\n", bytes, bps, eta);
381 * Ask the user for authentication details
384 query_auth(struct url *URL)
387 tcflag_t saved_flags;
390 fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
391 URL->scheme, URL->host, URL->port);
393 fprintf(stderr, "Login: ");
394 if (fgets(URL->user, sizeof URL->user, stdin) == NULL)
396 for (i = strlen(URL->user); i >= 0; --i)
397 if (URL->user[i] == '\r' || URL->user[i] == '\n')
400 fprintf(stderr, "Password: ");
401 if (tcgetattr(STDIN_FILENO, &tios) == 0) {
402 saved_flags = tios.c_lflag;
403 tios.c_lflag &= ~ECHO;
404 tios.c_lflag |= ECHONL|ICANON;
405 tcsetattr(STDIN_FILENO, TCSAFLUSH|TCSASOFT, &tios);
406 nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
407 tios.c_lflag = saved_flags;
408 tcsetattr(STDIN_FILENO, TCSANOW|TCSASOFT, &tios);
410 nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
414 for (i = strlen(URL->pwd); i >= 0; --i)
415 if (URL->pwd[i] == '\r' || URL->pwd[i] == '\n')
425 fetch(char *URL, const char *path, int *is_http)
432 size_t size, readcnt, wr;
433 off_t count, size_prev;
448 /* set verbosity level */
460 if ((url = fetchParseURL(URL)) == NULL) {
461 warnx("%s: parse error", URL);
465 /* if no scheme was specified, take a guess */
468 strcpy(url->scheme, SCHEME_FILE);
469 else if (strncasecmp(url->host, "ftp.", 4) == 0)
470 strcpy(url->scheme, SCHEME_FTP);
471 else if (strncasecmp(url->host, "www.", 4) == 0)
472 strcpy(url->scheme, SCHEME_HTTP);
475 /* for both of http and https */
476 *is_http = strncmp(url->scheme, "http", 4) == 0;
488 /* FTP specific flags */
489 if (strcmp(url->scheme, SCHEME_FTP) == 0) {
496 timeout = T_secs ? T_secs : ftp_timeout;
499 /* HTTP specific flags */
500 if (strcmp(url->scheme, SCHEME_HTTP) == 0 ||
501 strcmp(url->scheme, SCHEME_HTTPS) == 0) {
506 timeout = T_secs ? T_secs : http_timeout;
508 if (stat(i_filename, &sb)) {
509 warn("%s: stat()", i_filename);
512 url->ims_time = sb.st_mtime;
517 /* set the protocol timeout. */
518 fetchTimeout = timeout;
520 /* just print size */
524 r = fetchStat(url, &us, flags);
527 if (sigalrm || sigint)
530 warnx("%s", fetchLastErrString);
536 printf("%jd\n", (intmax_t)us.size);
544 * If the -r flag was specified, we have to compare the local
545 * and remote files, so we should really do a fetchStat()
546 * first, but I know of at least one HTTP server that only
547 * sends the content size in response to GET requests, and
548 * leaves it out of replies to HEAD requests. Also, in the
549 * (frequent) case that the local and remote files match but
550 * the local file is truncated, we have sufficient information
551 * before the compare to issue a correct request. Therefore,
552 * we always issue a GET request as if we were sure the local
553 * file was a truncated copy of the remote file; we can drop
554 * the connection later if we change our minds.
559 if (r == 0 && (r_flag || tries > 1) && S_ISREG(sb.st_mode)) {
560 url->offset = sb.st_size;
561 } else if (r == -1 || !S_ISREG(sb.st_mode)) {
563 * Whatever value sb.st_size has now is either
564 * wrong (if stat(2) failed) or irrelevant (if the
565 * path does not refer to a regular file)
569 if (r == -1 && errno != ENOENT) {
570 warnx("%s: stat()", path);
574 size_prev = sb.st_size;
576 /* start the transfer */
579 f = fetchXGet(url, &us, flags);
582 if (sigalrm || sigint)
585 warnx("%s: %s", URL, fetchLastErrString);
586 if (i_flag && (strcmp(url->scheme, SCHEME_HTTP) == 0 ||
587 strcmp(url->scheme, SCHEME_HTTPS) == 0) &&
588 fetchLastErrCode == FETCH_OK &&
589 strcmp(fetchLastErrString, "Not Modified") == 0) {
590 /* HTTP Not Modified Response, return OK. */
599 /* check that size is as expected */
602 warnx("%s: size unknown", URL);
603 } else if (us.size != S_size) {
604 warnx("%s: size mismatch: expected %jd, actual %jd",
605 URL, (intmax_t)S_size, (intmax_t)us.size);
610 /* symlink instead of copy */
611 if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
612 if (symlink(url->doc, path) == -1) {
613 warn("%s: symlink()", path);
619 if (us.size == -1 && !o_stdout && v_level > 0)
620 warnx("%s: size of remote file is not known", URL);
622 if (sb.st_size != -1)
623 fprintf(stderr, "local size / mtime: %jd / %ld\n",
624 (intmax_t)sb.st_size, (long)sb.st_mtime);
626 fprintf(stderr, "remote size / mtime: %jd / %ld\n",
627 (intmax_t)us.size, (long)us.mtime);
630 /* open output file */
632 /* output to stdout */
634 } else if (r_flag && sb.st_size != -1) {
635 /* resume mode, local file exists */
636 if (!F_flag && us.mtime && sb.st_mtime != us.mtime && tries == 1) {
637 /* no match! have to refetch */
639 /* if precious, warn the user and give up */
641 warnx("%s: local modification time "
642 "does not match remote", path);
645 } else if (url->offset > sb.st_size) {
646 /* gap between what we asked for and what we got */
647 warnx("%s: gap in resume mode", URL);
650 /* picked up again later */
651 } else if (us.size != -1) {
652 if (us.size == sb.st_size)
655 if (sb.st_size > us.size) {
656 /* local file too long! */
657 warnx("%s: local file (%jd bytes) is longer "
658 "than remote file (%jd bytes)", path,
659 (intmax_t)sb.st_size, (intmax_t)us.size);
662 /* we got it, open local file */
663 if ((of = fopen(path, "r+")) == NULL) {
664 warn("%s: fopen()", path);
667 /* check that it didn't move under our feet */
668 if (fstat(fileno(of), &nsb) == -1) {
670 warn("%s: fstat()", path);
673 if (nsb.st_dev != sb.st_dev ||
674 nsb.st_ino != sb.st_ino ||
675 nsb.st_size != sb.st_size) {
676 warnx("%s: file has changed", URL);
680 /* picked up again later */
683 /* seek to where we left off */
684 if (of != NULL && fseeko(of, url->offset, SEEK_SET) != 0) {
685 warn("%s: fseeko()", path);
688 /* picked up again later */
690 } else if (m_flag && sb.st_size != -1) {
691 /* mirror mode, local file exists */
692 if (sb.st_size == us.size && sb.st_mtime == us.mtime)
698 * We don't yet have an output file; either this is a
699 * vanilla run with no special flags, or the local and
700 * remote files didn't match.
703 if (url->offset > 0) {
705 * We tried to restart a transfer, but for
706 * some reason gave up - so we have to restart
707 * from scratch if we want the whole file
710 if ((f = fetchXGet(url, &us, flags)) == NULL) {
711 warnx("%s: %s", URL, fetchLastErrString);
718 /* construct a temp file name */
719 if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
720 if ((slash = strrchr(path, '/')) == NULL)
726 asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s",
727 (int)(slash - path), path, slash);
728 if (tmppath != NULL) {
729 if (mkstemps(tmppath, strlen(slash) + 1) == -1) {
730 warn("%s: mkstemps()", path);
733 of = fopen(tmppath, "w");
734 chown(tmppath, sb.st_uid, sb.st_gid);
735 chmod(tmppath, sb.st_mode & ALLPERMS);
739 of = fopen(path, "w");
741 warn("%s: open()", path);
747 /* start the counter */
748 stat_start(&xs, path, us.size, count);
750 sigalrm = siginfo = sigint = 0;
752 /* suck in the data */
753 setvbuf(f, NULL, _IOFBF, B_size);
754 signal(SIGINFO, sig_handler);
756 if (us.size != -1 && us.size - count < B_size &&
757 us.size - count >= 0)
758 size = us.size - count;
769 if ((readcnt = fread(buf, 1, size, f)) < size) {
770 if (ferror(f) && errno == EINTR && !sigint)
772 else if (readcnt == 0)
776 stat_update(&xs, count += readcnt);
777 for (ptr = buf; readcnt > 0; ptr += wr, readcnt -= wr)
778 if ((wr = fwrite(ptr, 1, readcnt, of)) < readcnt) {
779 if (ferror(of) && errno == EINTR && !sigint)
788 sigalrm = ferror(f) && errno == ETIMEDOUT;
789 signal(SIGINFO, SIG_DFL);
794 * If the transfer timed out or was interrupted, we still want to
795 * set the mtime in case the file is not removed (-r or -R) and
796 * the user later restarts the transfer.
799 /* set mtime of local file */
800 if (!n_flag && us.mtime && !o_stdout && of != NULL &&
801 (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
802 struct timeval tv[2];
805 tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
806 tv[1].tv_sec = (long)us.mtime;
807 tv[0].tv_usec = tv[1].tv_usec = 0;
808 if (utimes(tmppath ? tmppath : path, tv))
809 warn("%s: utimes()", tmppath ? tmppath : path);
812 /* timed out or interrupted? */
814 warnx("transfer timed out");
816 warnx("transfer interrupted");
820 /* timeout / interrupt before connection completley established? */
825 /* check the status of our files */
830 if (ferror(f) || ferror(of))
834 /* did the transfer complete normally? */
835 if (us.size != -1 && count < us.size) {
836 warnx("%s appears to be truncated: %jd/%jd bytes",
837 path, (intmax_t)count, (intmax_t)us.size);
838 if(!o_stdout && a_flag && count > size_prev) {
849 * If the transfer timed out and we didn't know how much to
850 * expect, assume the worst (i.e. we didn't get all of it)
852 if (sigalrm && us.size == -1) {
853 warnx("%s may be truncated", path);
859 if (tmppath != NULL && rename(tmppath, path) == -1) {
860 warn("%s: rename()", path);
865 if (of && of != stdout && !R_flag && !r_flag)
866 if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
867 unlink(tmppath ? tmppath : path);
868 if (R_flag && tmppath != NULL && sb.st_size == -1)
869 rename(tmppath, path); /* ignore errors here */
876 if (of && of != stdout)
888 fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
889 "usage: fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [--bind-address=host]",
890 " [--ca-cert=file] [--ca-path=dir] [--cert=file] [--crl=file]",
891 " [-i file] [--key=file] [-N file] [--no-passive] [--no-proxy=list]",
892 " [--no-sslv3] [--no-tlsv1] [--no-verify-hostname] [--no-verify-peer]",
893 " [-o file] [--referer=URL] [-S bytes] [-T seconds]",
894 " [--user-agent=agent-string] [-w seconds] URL ...",
895 " fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [--bind-address=host]",
896 " [--ca-cert=file] [--ca-path=dir] [--cert=file] [--crl=file]",
897 " [-i file] [--key=file] [-N file] [--no-passive] [--no-proxy=list]",
898 " [--no-sslv3] [--no-tlsv1] [--no-verify-hostname] [--no-verify-peer]",
899 " [-o file] [--referer=URL] [-S bytes] [-T seconds]",
900 " [--user-agent=agent-string] [-w seconds] -h host -f file [-c dir]");
908 main(int argc, char *argv[])
914 int c, e, is_http, r;
917 while ((c = getopt_long(argc, argv,
918 "146AaB:bc:dFf:Hh:i:lMmN:nPpo:qRrS:sT:tUvw:",
919 longopts, NULL)) != -1)
937 B_size = (off_t)strtol(optarg, &end, 10);
938 if (*optarg == '\0' || *end != '\0')
939 errx(1, "invalid buffer size (%s)", optarg);
942 warnx("warning: the -b option is deprecated");
958 warnx("the -H option is now implicit, "
959 "use -U to disable");
978 errx(1, "the -m and -r flags "
979 "are mutually exclusive");
1000 errx(1, "the -m and -r flags "
1001 "are mutually exclusive");
1005 S_size = strtoll(optarg, &end, 10);
1006 if (*optarg == '\0' || *end != '\0')
1007 errx(1, "invalid size (%s)", optarg);
1013 T_secs = strtol(optarg, &end, 10);
1014 if (*optarg == '\0' || *end != '\0')
1015 errx(1, "invalid timeout (%s)", optarg);
1019 warnx("warning: the -t option is deprecated");
1029 w_secs = strtol(optarg, &end, 10);
1030 if (*optarg == '\0' || *end != '\0')
1031 errx(1, "invalid delay (%s)", optarg);
1033 case OPTION_BIND_ADDRESS:
1034 setenv("FETCH_BIND_ADDRESS", optarg, 1);
1036 case OPTION_NO_FTP_PASSIVE_MODE:
1037 setenv("FTP_PASSIVE_MODE", "no", 1);
1039 case OPTION_HTTP_REFERER:
1040 setenv("HTTP_REFERER", optarg, 1);
1042 case OPTION_HTTP_USER_AGENT:
1043 setenv("HTTP_USER_AGENT", optarg, 1);
1045 case OPTION_NO_PROXY:
1046 setenv("NO_PROXY", optarg, 1);
1048 case OPTION_SSL_CA_CERT_FILE:
1049 setenv("SSL_CA_CERT_FILE", optarg, 1);
1051 case OPTION_SSL_CA_CERT_PATH:
1052 setenv("SSL_CA_CERT_PATH", optarg, 1);
1054 case OPTION_SSL_CLIENT_CERT_FILE:
1055 setenv("SSL_CLIENT_CERT_FILE", optarg, 1);
1057 case OPTION_SSL_CLIENT_KEY_FILE:
1058 setenv("SSL_CLIENT_KEY_FILE", optarg, 1);
1060 case OPTION_SSL_CRL_FILE:
1061 setenv("SSL_CLIENT_CRL_FILE", optarg, 1);
1063 case OPTION_SSL_NO_SSL3:
1064 setenv("SSL_NO_SSL3", "", 1);
1066 case OPTION_SSL_NO_TLS1:
1067 setenv("SSL_NO_TLS1", "", 1);
1069 case OPTION_SSL_NO_VERIFY_HOSTNAME:
1070 setenv("SSL_NO_VERIFY_HOSTNAME", "", 1);
1072 case OPTION_SSL_NO_VERIFY_PEER:
1073 setenv("SSL_NO_VERIFY_PEER", "", 1);
1083 if (h_hostname || f_filename || c_dirname) {
1084 if (!h_hostname || !f_filename || argc) {
1088 /* XXX this is a hack. */
1089 if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
1090 errx(1, "invalid hostname");
1091 if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
1092 c_dirname ? c_dirname : "", f_filename) == -1)
1093 errx(1, "%s", strerror(ENOMEM));
1102 /* allocate buffer */
1103 if (B_size < MINBUFSIZE)
1104 B_size = MINBUFSIZE;
1105 if ((buf = malloc(B_size)) == NULL)
1106 errx(1, "%s", strerror(ENOMEM));
1109 if ((s = getenv("FTP_TIMEOUT")) != NULL) {
1110 ftp_timeout = strtol(s, &end, 10);
1111 if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
1112 warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
1116 if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
1117 http_timeout = strtol(s, &end, 10);
1118 if (*s == '\0' || *end != '\0' || http_timeout < 0) {
1119 warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
1124 /* signal handling */
1126 sa.sa_handler = sig_handler;
1127 sigemptyset(&sa.sa_mask);
1128 sigaction(SIGALRM, &sa, NULL);
1129 sa.sa_flags = SA_RESETHAND;
1130 sigaction(SIGINT, &sa, NULL);
1131 fetchRestartCalls = 0;
1135 if (strcmp(o_filename, "-") == 0) {
1137 } else if (stat(o_filename, &sb) == -1) {
1138 if (errno == ENOENT) {
1140 errx(1, "%s is not a directory",
1143 err(1, "%s", o_filename);
1146 if (sb.st_mode & S_IFDIR)
1151 /* check if output is to a tty (for progress report) */
1152 v_tty = isatty(STDERR_FILENO);
1153 v_progress = v_tty && v_level > 0;
1159 /* authentication */
1161 fetchAuthMethod = query_auth;
1162 if (N_filename != NULL)
1163 if (setenv("NETRC", N_filename, 1) == -1)
1164 err(1, "setenv: cannot set NETRC=%s", N_filename);
1167 if ((p = strrchr(*argv, '/')) == NULL)
1175 fetchLastErrCode = 0;
1179 e = fetch(*argv, "-", &is_http);
1180 } else if (o_directory) {
1181 asprintf(&q, "%s/%s", o_filename, p);
1182 e = fetch(*argv, q, &is_http);
1185 e = fetch(*argv, o_filename, &is_http);
1188 e = fetch(*argv, p, &is_http);
1192 kill(getpid(), SIGINT);
1194 if (e == 0 && once_flag)
1199 if ((fetchLastErrCode
1200 && fetchLastErrCode != FETCH_AUTH
1201 && fetchLastErrCode != FETCH_UNAVAIL
1202 && fetchLastErrCode != FETCH_MOVED
1203 && fetchLastErrCode != FETCH_URL
1204 && fetchLastErrCode != FETCH_RESOLV
1205 && fetchLastErrCode != FETCH_UNKNOWN
1207 fetchLastErrCode != FETCH_PROTO
1208 && fetchLastErrCode != FETCH_SERVER
1209 && fetchLastErrCode != FETCH_TEMP
1210 && fetchLastErrCode != FETCH_TIMEOUT
1212 if (w_secs && v_level)
1213 fprintf(stderr, "Waiting %ld seconds "
1214 "before retrying\n", w_secs);