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/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include <sys/param.h>
36 #include <sys/socket.h>
54 #define MINBUFSIZE 16384
58 static int A_flag; /* -A: do not follow 302 redirects */
59 static int a_flag; /* -a: auto retry */
60 static off_t B_size; /* -B: buffer size */
61 static int b_flag; /*! -b: workaround TCP bug */
62 static char *c_dirname; /* -c: remote directory */
63 static int d_flag; /* -d: direct connection */
64 static int F_flag; /* -F: restart without checking mtime */
65 static char *f_filename; /* -f: file to fetch */
66 static char *h_hostname; /* -h: host to fetch from */
67 static int i_flag; /* -i: specify file for mtime comparison */
68 static char *i_filename; /* name of input file */
69 static int l_flag; /* -l: link rather than copy file: URLs */
70 static int m_flag; /* -[Mm]: mirror mode */
71 static char *N_filename; /* -N: netrc file name */
72 static int n_flag; /* -n: do not preserve modification time */
73 static int o_flag; /* -o: specify output file */
74 static int o_directory; /* output file is a directory */
75 static char *o_filename; /* name of output file */
76 static int o_stdout; /* output file is stdout */
77 static int once_flag; /* -1: stop at first successful file */
78 static int p_flag; /* -[Pp]: use passive FTP */
79 static int R_flag; /* -R: don't delete partial files */
80 static int r_flag; /* -r: restart previous transfer */
81 static off_t S_size; /* -S: require size to match */
82 static int s_flag; /* -s: show size, don't fetch */
83 static long T_secs; /* -T: transfer timeout in seconds */
84 static int t_flag; /*! -t: workaround TCP bug */
85 static int U_flag; /* -U: do not use high ports */
86 static int v_level = 1; /* -v: verbosity level */
87 static int v_tty; /* stdout is a tty */
88 static int v_progress; /* whether to display progress */
89 static pid_t pgrp; /* our process group */
90 static long w_secs; /* -w: retry delay */
91 static int family = PF_UNSPEC; /* -[46]: address family to use */
93 static int sigalrm; /* SIGALRM received */
94 static int siginfo; /* SIGINFO received */
95 static int sigint; /* SIGINT received */
97 static long ftp_timeout = TIMEOUT; /* default timeout for FTP transfers */
98 static long http_timeout = TIMEOUT;/* default timeout for HTTP transfers */
99 static char *buf; /* transfer buffer */
104 OPTION_NO_FTP_PASSIVE_MODE,
106 OPTION_HTTP_USER_AGENT,
108 OPTION_SSL_CA_CERT_FILE,
109 OPTION_SSL_CA_CERT_PATH,
110 OPTION_SSL_CLIENT_CERT_FILE,
111 OPTION_SSL_CLIENT_KEY_FILE,
115 OPTION_SSL_NO_VERIFY_HOSTNAME,
116 OPTION_SSL_NO_VERIFY_PEER
120 static struct option longopts[] =
122 /* mapping to single character argument */
123 { "one-file", no_argument, NULL, '1' },
124 { "ipv4-only", no_argument, NULL, '4' },
125 { "ipv6-only", no_argument, NULL, '6' },
126 { "no-redirect", no_argument, NULL, 'A' },
127 { "retry", no_argument, NULL, 'a' },
128 { "buffer-size", required_argument, NULL, 'B' },
129 /* -c not mapped, since it's deprecated */
130 { "direct", no_argument, NULL, 'd' },
131 { "force-restart", no_argument, NULL, 'F' },
132 /* -f not mapped, since it's deprecated */
133 /* -h not mapped, since it's deprecated */
134 { "if-modified-since", required_argument, NULL, 'i' },
135 { "symlink", no_argument, NULL, 'l' },
136 /* -M not mapped since it's the same as -m */
137 { "mirror", no_argument, NULL, 'm' },
138 { "netrc", required_argument, NULL, 'N' },
139 { "no-mtime", no_argument, NULL, 'n' },
140 { "output", required_argument, NULL, 'o' },
141 /* -P not mapped since it's the same as -p */
142 { "passive", no_argument, NULL, 'p' },
143 { "quiet", no_argument, NULL, 'q' },
144 { "keep-output", no_argument, NULL, 'R' },
145 { "restart", no_argument, NULL, 'r' },
146 { "require-size", required_argument, NULL, 'S' },
147 { "print-size", no_argument, NULL, 's' },
148 { "timeout", required_argument, NULL, 'T' },
149 { "passive-portrange-default", no_argument, NULL, 'T' },
150 { "verbose", no_argument, NULL, 'v' },
151 { "retry-delay", required_argument, NULL, 'w' },
153 /* options without a single character equivalent */
154 { "bind-address", required_argument, NULL, OPTION_BIND_ADDRESS },
155 { "no-passive", no_argument, NULL, OPTION_NO_FTP_PASSIVE_MODE },
156 { "referer", required_argument, NULL, OPTION_HTTP_REFERER },
157 { "user-agent", required_argument, NULL, OPTION_HTTP_USER_AGENT },
158 { "no-proxy", required_argument, NULL, OPTION_NO_PROXY },
159 { "ca-cert", required_argument, NULL, OPTION_SSL_CA_CERT_FILE },
160 { "ca-path", required_argument, NULL, OPTION_SSL_CA_CERT_PATH },
161 { "cert", required_argument, NULL, OPTION_SSL_CLIENT_CERT_FILE },
162 { "key", required_argument, NULL, OPTION_SSL_CLIENT_KEY_FILE },
163 { "crl", required_argument, NULL, OPTION_SSL_CRL_FILE },
164 { "no-sslv3", no_argument, NULL, OPTION_SSL_NO_SSL3 },
165 { "no-tlsv1", no_argument, NULL, OPTION_SSL_NO_TLS1 },
166 { "no-verify-hostname", no_argument, NULL, OPTION_SSL_NO_VERIFY_HOSTNAME },
167 { "no-verify-peer", no_argument, NULL, OPTION_SSL_NO_VERIFY_PEER },
193 struct timeval start; /* start of transfer */
194 struct timeval last; /* time of last update */
195 struct timeval last2; /* time of previous last update */
196 off_t size; /* size of file per HTTP hdr */
197 off_t offset; /* starting offset in file */
198 off_t rcvd; /* bytes already received */
199 off_t lastrcvd; /* bytes received since last update */
203 * Format a number of seconds as either XXdYYh, XXhYYm, XXmYYs, or XXs
204 * depending on its magnitude
207 stat_seconds(char *str, size_t strsz, long seconds)
211 snprintf(str, strsz, "%02ldd%02ldh",
212 seconds / 86400, (seconds % 86400) / 3600);
213 else if (seconds > 3600)
214 snprintf(str, strsz, "%02ldh%02ldm",
215 seconds / 3600, (seconds % 3600) / 60);
216 else if (seconds > 60)
217 snprintf(str, strsz, "%02ldm%02lds",
218 seconds / 60, seconds % 60);
220 snprintf(str, strsz, " %02lds",
225 * Compute and display ETA
228 stat_eta(char *str, size_t strsz, const struct xferstat *xs)
231 off_t received, expected;
233 elapsed = xs->last.tv_sec - xs->start.tv_sec;
234 received = xs->rcvd - xs->offset;
235 expected = xs->size - xs->rcvd;
236 eta = (long)((double)elapsed * expected / received);
238 stat_seconds(str, strsz, eta);
240 stat_seconds(str, strsz, elapsed);
244 * Format a number as "xxxx YB" where Y is ' ', 'k', 'M'...
246 static const char *prefixes = " kMGTP";
248 stat_bytes(char *str, size_t strsz, off_t bytes)
250 const char *prefix = prefixes;
252 while (bytes > 9999 && prefix[1] != '\0') {
256 snprintf(str, strsz, "%4ju %cB", (uintmax_t)bytes, *prefix);
260 * Compute and display transfer rate
263 stat_bps(char *str, size_t strsz, struct xferstat *xs)
268 delta = ((double)xs->last.tv_sec + (xs->last.tv_usec / 1.e6))
269 - ((double)xs->last2.tv_sec + (xs->last2.tv_usec / 1.e6));
272 snprintf(str, strsz, "?? Bps");
274 bps = (xs->rcvd - xs->lastrcvd) / delta;
275 stat_bytes(bytes, sizeof bytes, (off_t)bps);
276 snprintf(str, strsz, "%sps", bytes);
281 * Update the stats display
284 stat_display(struct xferstat *xs, int force)
286 char bytes[16], bps[16], eta[16];
290 /* check if we're the foreground process */
291 if (ioctl(STDERR_FILENO, TIOCGPGRP, &ctty_pgrp) != 0 ||
292 (pid_t)ctty_pgrp != pgrp)
295 gettimeofday(&now, NULL);
296 if (!force && now.tv_sec <= xs->last.tv_sec)
298 xs->last2 = xs->last;
301 fprintf(stderr, "\r%-46.46s", xs->name);
302 if (xs->rcvd >= xs->size) {
303 stat_bytes(bytes, sizeof bytes, xs->rcvd);
304 setproctitle("%s [%s]", xs->name, bytes);
305 fprintf(stderr, " %s", bytes);
307 stat_bytes(bytes, sizeof bytes, xs->size);
308 setproctitle("%s [%d%% of %s]", xs->name,
309 (int)((100.0 * xs->rcvd) / xs->size),
311 fprintf(stderr, "%3d%% of %s",
312 (int)((100.0 * xs->rcvd) / xs->size),
316 xs->lastrcvd = xs->offset;
317 xs->last2 = xs->start;
319 stat_bps(bps, sizeof bps, xs);
320 fprintf(stderr, " %s", bps);
321 if ((xs->size > 0 && xs->rcvd > 0 &&
322 xs->last.tv_sec >= xs->start.tv_sec + 3) ||
324 stat_eta(eta, sizeof eta, xs);
325 fprintf(stderr, " %s", eta);
327 xs->lastrcvd = xs->rcvd;
331 * Initialize the transfer statistics
334 stat_start(struct xferstat *xs, const char *name, off_t size, off_t offset)
337 memset(xs, 0, sizeof *xs);
338 snprintf(xs->name, sizeof xs->name, "%s", name);
339 gettimeofday(&xs->start, NULL);
340 xs->last2 = xs->last = xs->start;
344 xs->lastrcvd = offset;
347 else if (v_level > 0)
348 fprintf(stderr, "%-46s", xs->name);
352 * Update the transfer statistics
355 stat_update(struct xferstat *xs, off_t rcvd)
364 * Finalize the transfer statistics
367 stat_end(struct xferstat *xs)
369 char bytes[16], bps[16], eta[16];
371 gettimeofday(&xs->last, NULL);
375 } else if (v_level > 0) {
376 stat_bytes(bytes, sizeof bytes, xs->rcvd);
377 stat_bps(bps, sizeof bps, xs);
378 stat_eta(eta, sizeof eta, xs);
379 fprintf(stderr, " %s %s %s\n", bytes, bps, eta);
384 * Ask the user for authentication details
387 query_auth(struct url *URL)
390 tcflag_t saved_flags;
393 fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
394 URL->scheme, URL->host, URL->port);
396 fprintf(stderr, "Login: ");
397 if (fgets(URL->user, sizeof URL->user, stdin) == NULL)
399 for (i = strlen(URL->user); i >= 0; --i)
400 if (URL->user[i] == '\r' || URL->user[i] == '\n')
403 fprintf(stderr, "Password: ");
404 if (tcgetattr(STDIN_FILENO, &tios) == 0) {
405 saved_flags = tios.c_lflag;
406 tios.c_lflag &= ~ECHO;
407 tios.c_lflag |= ECHONL|ICANON;
408 tcsetattr(STDIN_FILENO, TCSAFLUSH|TCSASOFT, &tios);
409 nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
410 tios.c_lflag = saved_flags;
411 tcsetattr(STDIN_FILENO, TCSANOW|TCSASOFT, &tios);
413 nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
417 for (i = strlen(URL->pwd); i >= 0; --i)
418 if (URL->pwd[i] == '\r' || URL->pwd[i] == '\n')
428 fetch(char *URL, const char *path, int *is_http)
435 size_t size, readcnt, wr;
436 off_t count, size_prev;
451 /* set verbosity level */
463 if ((url = fetchParseURL(URL)) == NULL) {
464 warnx("%s: parse error", URL);
468 /* if no scheme was specified, take a guess */
471 strcpy(url->scheme, SCHEME_FILE);
472 else if (strncasecmp(url->host, "ftp.", 4) == 0)
473 strcpy(url->scheme, SCHEME_FTP);
474 else if (strncasecmp(url->host, "www.", 4) == 0)
475 strcpy(url->scheme, SCHEME_HTTP);
478 /* for both of http and https */
479 *is_http = strncmp(url->scheme, "http", 4) == 0;
491 /* FTP specific flags */
492 if (strcmp(url->scheme, SCHEME_FTP) == 0) {
499 timeout = T_secs ? T_secs : ftp_timeout;
502 /* HTTP specific flags */
503 if (strcmp(url->scheme, SCHEME_HTTP) == 0 ||
504 strcmp(url->scheme, SCHEME_HTTPS) == 0) {
509 timeout = T_secs ? T_secs : http_timeout;
511 if (stat(i_filename, &sb)) {
512 warn("%s: stat()", i_filename);
515 url->ims_time = sb.st_mtime;
520 /* set the protocol timeout. */
521 fetchTimeout = timeout;
523 /* just print size */
527 r = fetchStat(url, &us, flags);
530 if (sigalrm || sigint)
533 warnx("%s", fetchLastErrString);
539 printf("%jd\n", (intmax_t)us.size);
547 * If the -r flag was specified, we have to compare the local
548 * and remote files, so we should really do a fetchStat()
549 * first, but I know of at least one HTTP server that only
550 * sends the content size in response to GET requests, and
551 * leaves it out of replies to HEAD requests. Also, in the
552 * (frequent) case that the local and remote files match but
553 * the local file is truncated, we have sufficient information
554 * before the compare to issue a correct request. Therefore,
555 * we always issue a GET request as if we were sure the local
556 * file was a truncated copy of the remote file; we can drop
557 * the connection later if we change our minds.
562 if (r == 0 && (r_flag || tries > 1) && S_ISREG(sb.st_mode)) {
563 url->offset = sb.st_size;
564 } else if (r == -1 || !S_ISREG(sb.st_mode)) {
566 * Whatever value sb.st_size has now is either
567 * wrong (if stat(2) failed) or irrelevant (if the
568 * path does not refer to a regular file)
572 if (r == -1 && errno != ENOENT) {
573 warnx("%s: stat()", path);
577 size_prev = sb.st_size;
579 /* start the transfer */
582 f = fetchXGet(url, &us, flags);
585 if (sigalrm || sigint)
588 warnx("%s: %s", URL, fetchLastErrString);
589 if (i_flag && (strcmp(url->scheme, SCHEME_HTTP) == 0 ||
590 strcmp(url->scheme, SCHEME_HTTPS) == 0) &&
591 fetchLastErrCode == FETCH_OK &&
592 strcmp(fetchLastErrString, "Not Modified") == 0) {
593 /* HTTP Not Modified Response, return OK. */
602 /* check that size is as expected */
605 warnx("%s: size unknown", URL);
606 } else if (us.size != S_size) {
607 warnx("%s: size mismatch: expected %jd, actual %jd",
608 URL, (intmax_t)S_size, (intmax_t)us.size);
613 /* symlink instead of copy */
614 if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
615 if (symlink(url->doc, path) == -1) {
616 warn("%s: symlink()", path);
622 if (us.size == -1 && !o_stdout && v_level > 0)
623 warnx("%s: size of remote file is not known", URL);
625 if (sb.st_size != -1)
626 fprintf(stderr, "local size / mtime: %jd / %ld\n",
627 (intmax_t)sb.st_size, (long)sb.st_mtime);
629 fprintf(stderr, "remote size / mtime: %jd / %ld\n",
630 (intmax_t)us.size, (long)us.mtime);
633 /* open output file */
635 /* output to stdout */
637 } else if (r_flag && sb.st_size != -1) {
638 /* resume mode, local file exists */
639 if (!F_flag && us.mtime && sb.st_mtime != us.mtime && tries == 1) {
640 /* no match! have to refetch */
642 /* if precious, warn the user and give up */
644 warnx("%s: local modification time "
645 "does not match remote", path);
648 } else if (url->offset > sb.st_size) {
649 /* gap between what we asked for and what we got */
650 warnx("%s: gap in resume mode", URL);
653 /* picked up again later */
654 } else if (us.size != -1) {
655 if (us.size == sb.st_size)
658 if (sb.st_size > us.size) {
659 /* local file too long! */
660 warnx("%s: local file (%jd bytes) is longer "
661 "than remote file (%jd bytes)", path,
662 (intmax_t)sb.st_size, (intmax_t)us.size);
665 /* we got it, open local file */
666 if ((of = fopen(path, "r+")) == NULL) {
667 warn("%s: fopen()", path);
670 /* check that it didn't move under our feet */
671 if (fstat(fileno(of), &nsb) == -1) {
673 warn("%s: fstat()", path);
676 if (nsb.st_dev != sb.st_dev ||
677 nsb.st_ino != sb.st_ino ||
678 nsb.st_size != sb.st_size) {
679 warnx("%s: file has changed", URL);
683 /* picked up again later */
686 /* seek to where we left off */
687 if (of != NULL && fseeko(of, url->offset, SEEK_SET) != 0) {
688 warn("%s: fseeko()", path);
691 /* picked up again later */
693 } else if (m_flag && sb.st_size != -1) {
694 /* mirror mode, local file exists */
695 if (sb.st_size == us.size && sb.st_mtime == us.mtime)
701 * We don't yet have an output file; either this is a
702 * vanilla run with no special flags, or the local and
703 * remote files didn't match.
706 if (url->offset > 0) {
708 * We tried to restart a transfer, but for
709 * some reason gave up - so we have to restart
710 * from scratch if we want the whole file
713 if ((f = fetchXGet(url, &us, flags)) == NULL) {
714 warnx("%s: %s", URL, fetchLastErrString);
721 /* construct a temp file name */
722 if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
723 if ((slash = strrchr(path, '/')) == NULL)
729 asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s",
730 (int)(slash - path), path, slash);
731 if (tmppath != NULL) {
732 if (mkstemps(tmppath, strlen(slash) + 1) == -1) {
733 warn("%s: mkstemps()", path);
736 of = fopen(tmppath, "w");
737 chown(tmppath, sb.st_uid, sb.st_gid);
738 chmod(tmppath, sb.st_mode & ALLPERMS);
742 of = fopen(path, "w");
744 warn("%s: open()", path);
750 /* start the counter */
751 stat_start(&xs, path, us.size, count);
753 sigalrm = siginfo = sigint = 0;
755 /* suck in the data */
756 setvbuf(f, NULL, _IOFBF, B_size);
757 signal(SIGINFO, sig_handler);
759 if (us.size != -1 && us.size - count < B_size &&
760 us.size - count >= 0)
761 size = us.size - count;
772 if ((readcnt = fread(buf, 1, size, f)) < size) {
773 if (ferror(f) && errno == EINTR && !sigint)
775 else if (readcnt == 0)
779 stat_update(&xs, count += readcnt);
780 for (ptr = buf; readcnt > 0; ptr += wr, readcnt -= wr)
781 if ((wr = fwrite(ptr, 1, readcnt, of)) < readcnt) {
782 if (ferror(of) && errno == EINTR && !sigint)
791 sigalrm = ferror(f) && errno == ETIMEDOUT;
792 signal(SIGINFO, SIG_DFL);
797 * If the transfer timed out or was interrupted, we still want to
798 * set the mtime in case the file is not removed (-r or -R) and
799 * the user later restarts the transfer.
802 /* set mtime of local file */
803 if (!n_flag && us.mtime && !o_stdout && of != NULL &&
804 (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
805 struct timeval tv[2];
808 tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
809 tv[1].tv_sec = (long)us.mtime;
810 tv[0].tv_usec = tv[1].tv_usec = 0;
811 if (utimes(tmppath ? tmppath : path, tv))
812 warn("%s: utimes()", tmppath ? tmppath : path);
815 /* timed out or interrupted? */
817 warnx("transfer timed out");
819 warnx("transfer interrupted");
823 /* timeout / interrupt before connection completley established? */
828 /* check the status of our files */
833 if (ferror(f) || ferror(of))
837 /* did the transfer complete normally? */
838 if (us.size != -1 && count < us.size) {
839 warnx("%s appears to be truncated: %jd/%jd bytes",
840 path, (intmax_t)count, (intmax_t)us.size);
841 if(!o_stdout && a_flag && count > size_prev) {
852 * If the transfer timed out and we didn't know how much to
853 * expect, assume the worst (i.e. we didn't get all of it)
855 if (sigalrm && us.size == -1) {
856 warnx("%s may be truncated", path);
862 if (tmppath != NULL && rename(tmppath, path) == -1) {
863 warn("%s: rename()", path);
868 if (of && of != stdout && !R_flag && !r_flag)
869 if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
870 unlink(tmppath ? tmppath : path);
871 if (R_flag && tmppath != NULL && sb.st_size == -1)
872 rename(tmppath, path); /* ignore errors here */
879 if (of && of != stdout)
891 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",
892 "usage: fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [--bind-address=host]",
893 " [--ca-cert=file] [--ca-path=dir] [--cert=file] [--crl=file]",
894 " [-i file] [--key=file] [-N file] [--no-passive] [--no-proxy=list]",
895 " [--no-sslv3] [--no-tlsv1] [--no-verify-hostname] [--no-verify-peer]",
896 " [-o file] [--referer=URL] [-S bytes] [-T seconds]",
897 " [--user-agent=agent-string] [-w seconds] URL ...",
898 " fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [--bind-address=host]",
899 " [--ca-cert=file] [--ca-path=dir] [--cert=file] [--crl=file]",
900 " [-i file] [--key=file] [-N file] [--no-passive] [--no-proxy=list]",
901 " [--no-sslv3] [--no-tlsv1] [--no-verify-hostname] [--no-verify-peer]",
902 " [-o file] [--referer=URL] [-S bytes] [-T seconds]",
903 " [--user-agent=agent-string] [-w seconds] -h host -f file [-c dir]");
911 main(int argc, char *argv[])
917 int c, e, is_http, r;
920 while ((c = getopt_long(argc, argv,
921 "146AaB:bc:dFf:Hh:i:lMmN:nPpo:qRrS:sT:tUvw:",
922 longopts, NULL)) != -1)
940 B_size = (off_t)strtol(optarg, &end, 10);
941 if (*optarg == '\0' || *end != '\0')
942 errx(1, "invalid buffer size (%s)", optarg);
945 warnx("warning: the -b option is deprecated");
961 warnx("the -H option is now implicit, "
962 "use -U to disable");
981 errx(1, "the -m and -r flags "
982 "are mutually exclusive");
1003 errx(1, "the -m and -r flags "
1004 "are mutually exclusive");
1008 S_size = strtoll(optarg, &end, 10);
1009 if (*optarg == '\0' || *end != '\0')
1010 errx(1, "invalid size (%s)", optarg);
1016 T_secs = strtol(optarg, &end, 10);
1017 if (*optarg == '\0' || *end != '\0')
1018 errx(1, "invalid timeout (%s)", optarg);
1022 warnx("warning: the -t option is deprecated");
1032 w_secs = strtol(optarg, &end, 10);
1033 if (*optarg == '\0' || *end != '\0')
1034 errx(1, "invalid delay (%s)", optarg);
1036 case OPTION_BIND_ADDRESS:
1037 setenv("FETCH_BIND_ADDRESS", optarg, 1);
1039 case OPTION_NO_FTP_PASSIVE_MODE:
1040 setenv("FTP_PASSIVE_MODE", "no", 1);
1042 case OPTION_HTTP_REFERER:
1043 setenv("HTTP_REFERER", optarg, 1);
1045 case OPTION_HTTP_USER_AGENT:
1046 setenv("HTTP_USER_AGENT", optarg, 1);
1048 case OPTION_NO_PROXY:
1049 setenv("NO_PROXY", optarg, 1);
1051 case OPTION_SSL_CA_CERT_FILE:
1052 setenv("SSL_CA_CERT_FILE", optarg, 1);
1054 case OPTION_SSL_CA_CERT_PATH:
1055 setenv("SSL_CA_CERT_PATH", optarg, 1);
1057 case OPTION_SSL_CLIENT_CERT_FILE:
1058 setenv("SSL_CLIENT_CERT_FILE", optarg, 1);
1060 case OPTION_SSL_CLIENT_KEY_FILE:
1061 setenv("SSL_CLIENT_KEY_FILE", optarg, 1);
1063 case OPTION_SSL_CRL_FILE:
1064 setenv("SSL_CLIENT_CRL_FILE", optarg, 1);
1066 case OPTION_SSL_NO_SSL3:
1067 setenv("SSL_NO_SSL3", "", 1);
1069 case OPTION_SSL_NO_TLS1:
1070 setenv("SSL_NO_TLS1", "", 1);
1072 case OPTION_SSL_NO_VERIFY_HOSTNAME:
1073 setenv("SSL_NO_VERIFY_HOSTNAME", "", 1);
1075 case OPTION_SSL_NO_VERIFY_PEER:
1076 setenv("SSL_NO_VERIFY_PEER", "", 1);
1086 if (h_hostname || f_filename || c_dirname) {
1087 if (!h_hostname || !f_filename || argc) {
1091 /* XXX this is a hack. */
1092 if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
1093 errx(1, "invalid hostname");
1094 if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
1095 c_dirname ? c_dirname : "", f_filename) == -1)
1096 errx(1, "%s", strerror(ENOMEM));
1105 /* allocate buffer */
1106 if (B_size < MINBUFSIZE)
1107 B_size = MINBUFSIZE;
1108 if ((buf = malloc(B_size)) == NULL)
1109 errx(1, "%s", strerror(ENOMEM));
1112 if ((s = getenv("FTP_TIMEOUT")) != NULL) {
1113 ftp_timeout = strtol(s, &end, 10);
1114 if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
1115 warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
1119 if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
1120 http_timeout = strtol(s, &end, 10);
1121 if (*s == '\0' || *end != '\0' || http_timeout < 0) {
1122 warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
1127 /* signal handling */
1129 sa.sa_handler = sig_handler;
1130 sigemptyset(&sa.sa_mask);
1131 sigaction(SIGALRM, &sa, NULL);
1132 sa.sa_flags = SA_RESETHAND;
1133 sigaction(SIGINT, &sa, NULL);
1134 fetchRestartCalls = 0;
1138 if (strcmp(o_filename, "-") == 0) {
1140 } else if (stat(o_filename, &sb) == -1) {
1141 if (errno == ENOENT) {
1143 errx(1, "%s is not a directory",
1146 err(1, "%s", o_filename);
1149 if (sb.st_mode & S_IFDIR)
1154 /* check if output is to a tty (for progress report) */
1155 v_tty = isatty(STDERR_FILENO);
1156 v_progress = v_tty && v_level > 0;
1162 /* authentication */
1164 fetchAuthMethod = query_auth;
1165 if (N_filename != NULL)
1166 if (setenv("NETRC", N_filename, 1) == -1)
1167 err(1, "setenv: cannot set NETRC=%s", N_filename);
1170 if ((p = strrchr(*argv, '/')) == NULL)
1178 fetchLastErrCode = 0;
1182 e = fetch(*argv, "-", &is_http);
1183 } else if (o_directory) {
1184 asprintf(&q, "%s/%s", o_filename, p);
1185 e = fetch(*argv, q, &is_http);
1188 e = fetch(*argv, o_filename, &is_http);
1191 e = fetch(*argv, p, &is_http);
1195 kill(getpid(), SIGINT);
1197 if (e == 0 && once_flag)
1202 if ((fetchLastErrCode
1203 && fetchLastErrCode != FETCH_AUTH
1204 && fetchLastErrCode != FETCH_UNAVAIL
1205 && fetchLastErrCode != FETCH_MOVED
1206 && fetchLastErrCode != FETCH_URL
1207 && fetchLastErrCode != FETCH_RESOLV
1208 && fetchLastErrCode != FETCH_UNKNOWN
1210 fetchLastErrCode != FETCH_PROTO
1211 && fetchLastErrCode != FETCH_SERVER
1212 && fetchLastErrCode != FETCH_TEMP
1213 && fetchLastErrCode != FETCH_TIMEOUT
1215 if (w_secs && v_level)
1216 fprintf(stderr, "Waiting %ld seconds "
1217 "before retrying\n", w_secs);