1 /* $NetBSD: fetch.c,v 1.18 2009/11/15 10:12:37 lukem Exp $ */
2 /* from NetBSD: fetch.c,v 1.191 2009/08/17 09:08:16 christos Exp */
5 * Copyright (c) 1997-2009 The NetBSD Foundation, Inc.
8 * This code is derived from software contributed to The NetBSD Foundation
11 * This code is derived from software contributed to The NetBSD Foundation
12 * by Scott Aaron Bamford.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
23 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
24 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
25 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
27 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * POSSIBILITY OF SUCH DAMAGE.
40 #include <sys/cdefs.h>
42 __RCSID(" NetBSD: fetch.c,v 1.191 2009/08/17 09:08:16 christos Exp ");
46 * FTP User Program -- Command line file retrieval
49 #include <sys/types.h>
50 #include <sys/param.h>
51 #include <sys/socket.h>
55 #include <netinet/in.h>
58 #include <arpa/inet.h>
86 static int auth_url(const char *, char **, const char *, const char *);
87 static void base64_encode(const unsigned char *, size_t, unsigned char *);
89 static int go_fetch(const char *);
90 static int fetch_ftp(const char *);
91 static int fetch_url(const char *, const char *, char *, char *);
92 static const char *match_token(const char **, const char *);
93 static int parse_url(const char *, const char *, url_t *, char **,
94 char **, char **, char **, in_port_t *, char **);
95 static void url_decode(char *);
97 static int redirect_loop;
100 #define STRNEQUAL(a,b) (strncasecmp((a), (b), sizeof((b))-1) == 0)
101 #define ISLWS(x) ((x)=='\r' || (x)=='\n' || (x)==' ' || (x)=='\t')
102 #define SKIPLWS(x) do { while (ISLWS((*x))) x++; } while (0)
105 #define ABOUT_URL "about:" /* propaganda */
106 #define FILE_URL "file://" /* file URL prefix */
107 #define FTP_URL "ftp://" /* ftp URL prefix */
108 #define HTTP_URL "http://" /* http URL prefix */
112 * Determine if token is the next word in buf (case insensitive).
113 * If so, advance buf past the token and any trailing LWS, and
114 * return a pointer to the token (in buf). Otherwise, return NULL.
115 * token may be preceded by LWS.
116 * token must be followed by LWS or NUL. (I.e, don't partial match).
119 match_token(const char **buf, const char *token)
121 const char *p, *orig;
124 tlen = strlen(token);
128 if (strncasecmp(p, token, tlen) != 0)
131 if (*p != '\0' && !ISLWS(*p))
141 * Generate authorization response based on given authentication challenge.
142 * Returns -1 if an error occurred, otherwise 0.
143 * Sets response to a malloc(3)ed string; caller should free.
146 auth_url(const char *challenge, char **response, const char *guser,
149 const char *cp, *scheme, *errormsg;
150 char *ep, *clear, *realm;
151 char uuser[BUFSIZ], *gotpass;
154 size_t len, clen, rlen;
157 clear = realm = NULL;
160 scheme = "Basic"; /* only support Basic authentication */
163 DPRINTF("auth_url: challenge `%s'\n", challenge);
165 if (! match_token(&cp, scheme)) {
166 warnx("Unsupported authentication challenge `%s'",
168 goto cleanup_auth_url;
171 #define REALM "realm=\""
172 if (STRNEQUAL(cp, REALM))
173 cp += sizeof(REALM) - 1;
175 warnx("Unsupported authentication challenge `%s'",
177 goto cleanup_auth_url;
179 /* XXX: need to improve quoted-string parsing to support \ quoting, etc. */
180 if ((ep = strchr(cp, '\"')) != NULL) {
182 realm = (char *)ftp_malloc(len + 1);
183 (void)strlcpy(realm, cp, len + 1);
185 warnx("Unsupported authentication challenge `%s'",
187 goto cleanup_auth_url;
190 fprintf(ttyout, "Username for `%s': ", realm);
192 (void)strlcpy(uuser, guser, sizeof(uuser));
193 fprintf(ttyout, "%s\n", uuser);
195 (void)fflush(ttyout);
196 if (get_line(stdin, uuser, sizeof(uuser), &errormsg) < 0) {
197 warnx("%s; can't authenticate", errormsg);
198 goto cleanup_auth_url;
204 gotpass = getpass("Password: ");
205 if (gotpass == NULL) {
206 warnx("Can't read password");
207 goto cleanup_auth_url;
212 clen = strlen(uuser) + strlen(upass) + 2; /* user + ":" + pass + "\0" */
213 clear = (char *)ftp_malloc(clen);
214 (void)strlcpy(clear, uuser, clen);
215 (void)strlcat(clear, ":", clen);
216 (void)strlcat(clear, upass, clen);
218 memset(gotpass, 0, strlen(gotpass));
220 /* scheme + " " + enc + "\0" */
221 rlen = strlen(scheme) + 1 + (clen + 2) * 4 / 3 + 1;
222 *response = (char *)ftp_malloc(rlen);
223 (void)strlcpy(*response, scheme, rlen);
224 len = strlcat(*response, " ", rlen);
225 /* use `clen - 1' to not encode the trailing NUL */
226 base64_encode((unsigned char *)clear, clen - 1,
227 (unsigned char *)*response + len);
228 memset(clear, 0, clen);
238 * Encode len bytes starting at clear using base64 encoding into encoded,
239 * which should be at least ((len + 2) * 4 / 3 + 1) in size.
242 base64_encode(const unsigned char *clear, size_t len, unsigned char *encoded)
244 static const unsigned char enc[] =
245 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
250 for (i = 0; i < len; i += 3) {
251 *(cp++) = enc[((clear[i + 0] >> 2))];
252 *(cp++) = enc[((clear[i + 0] << 4) & 0x30)
253 | ((clear[i + 1] >> 4) & 0x0f)];
254 *(cp++) = enc[((clear[i + 1] << 2) & 0x3c)
255 | ((clear[i + 2] >> 6) & 0x03)];
256 *(cp++) = enc[((clear[i + 2] ) & 0x3f)];
265 * Decode %xx escapes in given string, `in-place'.
268 url_decode(char *url)
270 unsigned char *p, *q;
272 if (EMPTYSTRING(url))
274 p = q = (unsigned char *)url;
276 #define HEXTOINT(x) (x - (isdigit(x) ? '0' : (islower(x) ? 'a' : 'A') - 10))
279 && p[1] && isxdigit((unsigned char)p[1])
280 && p[2] && isxdigit((unsigned char)p[2])) {
281 *q++ = HEXTOINT(p[1]) * 16 + HEXTOINT(p[2]);
291 * Parse URL of form (per RFC3986):
292 * <type>://[<user>[:<password>]@]<host>[:<port>][/<path>]
293 * Returns -1 if a parse error occurred, otherwise 0.
294 * It's the caller's responsibility to url_decode() the returned
295 * user, pass and path.
297 * Sets type to url_t, each of the given char ** pointers to a
298 * malloc(3)ed strings of the relevant section, and port to
299 * the number given, or ftpport if ftp://, or httpport if http://.
301 * XXX: this is not totally RFC3986 compliant; <path> will have the
302 * leading `/' unless it's an ftp:// URL, as this makes things easier
303 * for file:// and http:// URLs. ftp:// URLs have the `/' between the
304 * host and the URL-path removed, but any additional leading slashes
305 * in the URL-path are retained (because they imply that we should
306 * later do "CWD" with a null argument).
309 * input URL output path
310 * --------- -----------
313 * "http://host/path" "/path"
314 * "file://host/dir/file" "dir/file"
318 * "ftp://host/dir/file" "dir/file"
319 * "ftp://host//dir/file" "/dir/file"
322 parse_url(const char *url, const char *desc, url_t *utype,
323 char **uuser, char **pass, char **host, char **port,
324 in_port_t *portnum, char **path)
326 const char *origurl, *tport;
327 char *cp, *ep, *thost;
330 if (url == NULL || desc == NULL || utype == NULL || uuser == NULL
331 || pass == NULL || host == NULL || port == NULL || portnum == NULL
333 errx(1, "parse_url: invoked with NULL argument!");
334 DPRINTF("parse_url: %s `%s'\n", desc, url);
337 *utype = UNKNOWN_URL_T;
338 *uuser = *pass = *host = *port = *path = NULL;
342 if (STRNEQUAL(url, HTTP_URL)) {
343 url += sizeof(HTTP_URL) - 1;
345 *portnum = HTTP_PORT;
347 } else if (STRNEQUAL(url, FTP_URL)) {
348 url += sizeof(FTP_URL) - 1;
352 } else if (STRNEQUAL(url, FILE_URL)) {
353 url += sizeof(FILE_URL) - 1;
356 warnx("Invalid %s `%s'", desc, url);
360 memset(*pass, 0, strlen(*pass));
371 /* find [user[:pass]@]host[:port] */
372 ep = strchr(url, '/');
374 thost = ftp_strdup(url);
377 thost = (char *)ftp_malloc(len + 1);
378 (void)strlcpy(thost, url, len + 1);
379 if (*utype == FTP_URL_T) /* skip first / for ftp URLs */
381 *path = ftp_strdup(ep);
384 cp = strchr(thost, '@'); /* look for user[:pass]@ in URLs */
386 if (*utype == FTP_URL_T)
387 anonftp = 0; /* disable anonftp */
390 thost = ftp_strdup(cp + 1);
391 cp = strchr(*uuser, ':');
394 *pass = ftp_strdup(cp + 1);
403 * Check if thost is an encoded IPv6 address, as per
405 * `[' ipv6-address ']'
409 if ((ep = strchr(cp, ']')) == NULL ||
410 (ep[1] != '\0' && ep[1] != ':')) {
411 warnx("Invalid address `%s' in %s `%s'",
412 thost, desc, origurl);
413 goto cleanup_parse_url;
415 len = ep - cp; /* change `[xyz]' -> `xyz' */
416 memmove(thost, thost + 1, len);
418 if (! isipv6addr(thost)) {
419 warnx("Invalid IPv6 address `%s' in %s `%s'",
420 thost, desc, origurl);
421 goto cleanup_parse_url;
430 if ((cp = strchr(thost, ':')) != NULL)
434 /* look for [:port] */
438 nport = strtoul(cp, &ep, 10);
439 if (*cp == '\0' || *ep != '\0' ||
440 nport < 1 || nport > MAX_IN_PORT_T) {
441 warnx("Unknown port `%s' in %s `%s'",
443 goto cleanup_parse_url;
450 *port = ftp_strdup(tport);
452 const char *emptypath = "/";
453 if (*utype == FTP_URL_T) /* skip first / for ftp URLs */
455 *path = ftp_strdup(emptypath);
458 DPRINTF("parse_url: user `%s' pass `%s' host %s port %s(%d) "
460 STRorNULL(*uuser), STRorNULL(*pass),
461 STRorNULL(*host), STRorNULL(*port),
462 *portnum ? *portnum : -1, STRorNULL(*path));
467 sigjmp_buf httpabort;
470 * Retrieve URL, via a proxy if necessary, using HTTP.
471 * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
472 * http_proxy as appropriate.
473 * Supports HTTP redirects.
474 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
475 * is still open (e.g, ftp xfer with trailing /)
478 fetch_url(const char *url, const char *proxyenv, char *proxyauth, char *wwwauth)
480 struct addrinfo hints, *res, *res0 = NULL;
482 sigfunc volatile oldintr;
483 sigfunc volatile oldintp;
486 int volatile ischunked;
487 int volatile isproxy;
492 static size_t bufsize;
493 static char *xferbuf;
494 const char *cp, *token;
497 const char *errormsg;
498 char *volatile savefile;
500 char *volatile location;
501 char *volatile message;
502 char *uuser, *pass, *host, *port, *path;
503 char *volatile decodedpath;
504 char *puser, *ppass, *useragent;
505 off_t hashbytes, rangestart, rangeend, entitylen;
506 int (*volatile closefunc)(FILE *);
513 DPRINTF("fetch_url: `%s' proxyenv `%s'\n", url, STRorNULL(proxyenv));
515 oldintr = oldintp = NULL;
520 auth = location = message = NULL;
521 ischunked = isproxy = hcode = 0;
523 uuser = pass = host = path = decodedpath = puser = ppass = NULL;
525 if (parse_url(url, "URL", &urltype, &uuser, &pass, &host, &port,
526 &portnum, &path) == -1)
527 goto cleanup_fetch_url;
529 if (urltype == FILE_URL_T && ! EMPTYSTRING(host)
530 && strcasecmp(host, "localhost") != 0) {
531 warnx("No support for non local file URL `%s'", url);
532 goto cleanup_fetch_url;
535 if (EMPTYSTRING(path)) {
536 if (urltype == FTP_URL_T) {
537 rval = fetch_ftp(url);
538 goto cleanup_fetch_url;
540 if (urltype != HTTP_URL_T || outfile == NULL) {
541 warnx("Invalid URL (no file after host) `%s'", url);
542 goto cleanup_fetch_url;
546 decodedpath = ftp_strdup(path);
547 url_decode(decodedpath);
550 savefile = ftp_strdup(outfile);
552 cp = strrchr(decodedpath, '/'); /* find savefile */
554 savefile = ftp_strdup(cp + 1);
556 savefile = ftp_strdup(decodedpath);
558 DPRINTF("fetch_url: savefile `%s'\n", savefile);
559 if (EMPTYSTRING(savefile)) {
560 if (urltype == FTP_URL_T) {
561 rval = fetch_ftp(url);
562 goto cleanup_fetch_url;
564 warnx("No file after directory (you must specify an "
565 "output file) `%s'", url);
566 goto cleanup_fetch_url;
571 rangestart = rangeend = entitylen = -1;
573 if (restartautofetch) {
574 if (strcmp(savefile, "-") != 0 && *savefile != '|' &&
575 stat(savefile, &sb) == 0)
576 restart_point = sb.st_size;
578 if (urltype == FILE_URL_T) { /* file:// URLs */
579 direction = "copied";
580 fin = fopen(decodedpath, "r");
582 warn("Can't open `%s'", decodedpath);
583 goto cleanup_fetch_url;
585 if (fstat(fileno(fin), &sb) == 0) {
587 filesize = sb.st_size;
590 if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
591 warn("Can't seek to restart `%s'",
593 goto cleanup_fetch_url;
597 fprintf(ttyout, "Copying %s", decodedpath);
599 fprintf(ttyout, " (restarting at " LLF ")",
603 } else { /* ftp:// or http:// URLs */
607 if (proxyenv == NULL) {
608 if (urltype == HTTP_URL_T)
609 proxyenv = getoptionvalue("http_proxy");
610 else if (urltype == FTP_URL_T)
611 proxyenv = getoptionvalue("ftp_proxy");
613 direction = "retrieved";
614 if (! EMPTYSTRING(proxyenv)) { /* use proxy */
617 char *pport, *no_proxy;
622 /* check URL against list of no_proxied sites */
623 no_proxy = getoptionvalue("no_proxy");
624 if (! EMPTYSTRING(no_proxy)) {
625 char *np, *np_copy, *np_iter;
626 unsigned long np_port;
629 np_iter = np_copy = ftp_strdup(no_proxy);
631 while ((cp = strsep(&np_iter, " ,")) != NULL) {
634 if ((np = strrchr(cp, ':')) != NULL) {
636 np_port = strtoul(np, &ep, 10);
637 if (*np == '\0' || *ep != '\0')
639 if (np_port != portnum)
645 if (strncasecmp(host + hlen - plen,
652 if (isproxy == 0 && urltype == FTP_URL_T) {
653 rval = fetch_ftp(url);
654 goto cleanup_fetch_url;
660 warnx("Can't restart via proxy URL `%s'",
662 goto cleanup_fetch_url;
664 if (parse_url(proxyenv, "proxy URL", &purltype,
665 &puser, &ppass, &phost, &pport, &pportnum,
667 goto cleanup_fetch_url;
669 if ((purltype != HTTP_URL_T
670 && purltype != FTP_URL_T) ||
671 EMPTYSTRING(phost) ||
672 (! EMPTYSTRING(ppath)
673 && strcmp(ppath, "/") != 0)) {
674 warnx("Malformed proxy URL `%s'",
679 goto cleanup_fetch_url;
681 if (isipv6addr(host) &&
682 strchr(host, '%') != NULL) {
684 "Scoped address notation `%s' disallowed via web proxy",
689 goto cleanup_fetch_url;
697 path = ftp_strdup(url);
700 } /* ! EMPTYSTRING(proxyenv) */
702 memset(&hints, 0, sizeof(hints));
704 hints.ai_family = family;
705 hints.ai_socktype = SOCK_STREAM;
706 hints.ai_protocol = 0;
707 error = getaddrinfo(host, port, &hints, &res0);
709 warnx("Can't lookup `%s:%s': %s", host, port,
710 (error == EAI_SYSTEM) ? strerror(errno)
711 : gai_strerror(error));
712 goto cleanup_fetch_url;
714 if (res0->ai_canonname)
715 host = res0->ai_canonname;
718 for (res = res0; res; res = res->ai_next) {
719 char hname[NI_MAXHOST], sname[NI_MAXSERV];
722 if (getnameinfo(res->ai_addr, res->ai_addrlen,
723 hname, sizeof(hname), sname, sizeof(sname),
724 NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
725 strlcpy(hname, "?", sizeof(hname));
726 strlcpy(sname, "?", sizeof(sname));
729 if (verbose && res0->ai_next) {
730 fprintf(ttyout, "Trying %s:%s ...\n",
734 s = socket(res->ai_family, SOCK_STREAM,
738 "Can't create socket for connection to "
739 "`%s:%s'", hname, sname);
743 if (ftp_connect(s, res->ai_addr, res->ai_addrlen) < 0) {
754 warnx("Can't connect to `%s:%s'", host, port);
755 goto cleanup_fetch_url;
758 fin = fdopen(s, "r+");
760 * Construct and send the request.
763 fprintf(ttyout, "Requesting %s\n", url);
768 fprintf(ttyout, "%svia %s:%s", leading,
773 fprintf(fin, "GET %s HTTP/1.0\r\n", path);
775 fprintf(fin, "Pragma: no-cache\r\n");
777 fprintf(fin, "GET %s HTTP/1.1\r\n", path);
778 if (strchr(host, ':')) {
782 * strip off IPv6 scope identifier, since it is
785 h = ftp_strdup(host);
787 (p = strchr(h, '%')) != NULL) {
790 fprintf(fin, "Host: [%s]", h);
793 fprintf(fin, "Host: %s", host);
794 if (portnum != HTTP_PORT)
795 fprintf(fin, ":%u", portnum);
796 fprintf(fin, "\r\n");
797 fprintf(fin, "Accept: */*\r\n");
798 fprintf(fin, "Connection: close\r\n");
800 fputs(leading, ttyout);
801 fprintf(fin, "Range: bytes=" LLF "-\r\n",
803 fprintf(ttyout, "restarting at " LLF,
809 fprintf(fin, "Cache-Control: no-cache\r\n");
811 if ((useragent=getenv("FTPUSERAGENT")) != NULL) {
812 fprintf(fin, "User-Agent: %s\r\n", useragent);
814 fprintf(fin, "User-Agent: %s/%s\r\n",
815 FTP_PRODUCT, FTP_VERSION);
819 fprintf(ttyout, "%swith authorization",
824 fprintf(fin, "Authorization: %s\r\n", wwwauth);
829 "%swith proxy authorization", leading);
833 fprintf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
835 if (verbose && hasleading)
836 fputs(")\n", ttyout);
837 fprintf(fin, "\r\n");
838 if (fflush(fin) == EOF) {
839 warn("Writing HTTP request");
840 goto cleanup_fetch_url;
843 /* Read the response */
844 len = get_line(fin, buf, sizeof(buf), &errormsg);
846 if (*errormsg == '\n')
848 warnx("Receiving HTTP reply: %s", errormsg);
849 goto cleanup_fetch_url;
851 while (len > 0 && (ISLWS(buf[len-1])))
853 DPRINTF("fetch_url: received `%s'\n", buf);
855 /* Determine HTTP response code */
856 cp = strchr(buf, ' ');
861 hcode = strtol(cp, &ep, 10);
862 if (*ep != '\0' && !isspace((unsigned char)*ep))
864 message = ftp_strdup(cp);
866 /* Read the rest of the header. */
868 len = get_line(fin, buf, sizeof(buf), &errormsg);
870 if (*errormsg == '\n')
872 warnx("Receiving HTTP reply: %s", errormsg);
873 goto cleanup_fetch_url;
875 while (len > 0 && (ISLWS(buf[len-1])))
879 DPRINTF("fetch_url: received `%s'\n", buf);
882 * Look for some headers
887 if (match_token(&cp, "Content-Length:")) {
888 filesize = STRTOLL(cp, &ep, 10);
889 if (filesize < 0 || *ep != '\0')
891 DPRINTF("fetch_url: parsed len as: " LLF "\n",
894 } else if (match_token(&cp, "Content-Range:")) {
895 if (! match_token(&cp, "bytes"))
901 rangestart = STRTOLL(cp, &ep, 10);
902 if (rangestart < 0 || *ep != '-')
905 rangeend = STRTOLL(cp, &ep, 10);
906 if (rangeend < 0 || rangeend < rangestart)
916 entitylen = STRTOLL(cp, &ep, 10);
926 fprintf(ttyout, "parsed range as: ");
927 if (rangestart == -1)
928 fprintf(ttyout, "*");
930 fprintf(ttyout, LLF "-" LLF,
933 fprintf(ttyout, "/" LLF "\n", (LLT)entitylen);
936 if (! restart_point) {
938 "Received unexpected Content-Range header");
939 goto cleanup_fetch_url;
942 } else if (match_token(&cp, "Last-Modified:")) {
946 memset(&parsed, 0, sizeof(parsed));
948 if ((t = strptime(cp,
949 "%a, %d %b %Y %H:%M:%S GMT",
953 "%a, %d-%b-%y %H:%M:%S GMT",
957 "%a, %b %d %H:%M:%S %Y",
959 parsed.tm_isdst = -1;
961 mtime = timegm(&parsed);
963 if (ftp_debug && mtime != -1) {
965 "parsed date as: %s",
966 rfc2822time(localtime(&mtime)));
971 } else if (match_token(&cp, "Location:")) {
972 location = ftp_strdup(cp);
973 DPRINTF("fetch_url: parsed location as `%s'\n",
976 } else if (match_token(&cp, "Transfer-Encoding:")) {
977 if (match_token(&cp, "binary")) {
979 "Bogus transfer encoding `binary' (fetching anyway)");
982 if (! (token = match_token(&cp, "chunked"))) {
984 "Unsupported transfer encoding `%s'",
986 goto cleanup_fetch_url;
989 DPRINTF("fetch_url: using chunked encoding\n");
991 } else if (match_token(&cp, "Proxy-Authenticate:")
992 || match_token(&cp, "WWW-Authenticate:")) {
993 if (! (token = match_token(&cp, "Basic"))) {
995 "fetch_url: skipping unknown auth scheme `%s'\n",
1000 auth = ftp_strdup(token);
1001 DPRINTF("fetch_url: parsed auth as `%s'\n", cp);
1005 /* finished parsing header */
1011 if (! restart_point) {
1012 warnx("Not expecting partial content header");
1013 goto cleanup_fetch_url;
1022 if (EMPTYSTRING(location)) {
1024 "No redirection Location provided by server");
1025 goto cleanup_fetch_url;
1027 if (redirect_loop++ > 5) {
1028 warnx("Too many redirections requested");
1029 goto cleanup_fetch_url;
1033 fprintf(ttyout, "Redirected via %s\n",
1035 rval = fetch_url(url, location,
1036 proxyauth, wwwauth);
1039 fprintf(ttyout, "Redirected to %s\n",
1041 rval = go_fetch(location);
1043 goto cleanup_fetch_url;
1049 char *auser, *apass;
1060 if (verbose || *authp == NULL ||
1061 auser == NULL || apass == NULL)
1062 fprintf(ttyout, "%s\n", message);
1063 if (EMPTYSTRING(auth)) {
1065 "No authentication challenge provided by server");
1066 goto cleanup_fetch_url;
1068 if (*authp != NULL) {
1072 "Authorization failed. Retry (y/n)? ");
1073 if (get_line(stdin, reply, sizeof(reply), NULL)
1075 goto cleanup_fetch_url;
1077 if (tolower((unsigned char)reply[0]) != 'y')
1078 goto cleanup_fetch_url;
1082 if (auth_url(auth, authp, auser, apass) == 0) {
1083 rval = fetch_url(url, proxyenv,
1084 proxyauth, wwwauth);
1085 memset(*authp, 0, strlen(*authp));
1088 goto cleanup_fetch_url;
1093 warnx("Error retrieving file `%s'", message);
1095 warnx("Unknown error retrieving file");
1096 goto cleanup_fetch_url;
1098 } /* end of ftp:// or http:// specific setup */
1100 /* Open the output file. */
1101 if (strcmp(savefile, "-") == 0) {
1103 } else if (*savefile == '|') {
1104 oldintp = xsignal(SIGPIPE, SIG_IGN);
1105 fout = popen(savefile + 1, "w");
1107 warn("Can't execute `%s'", savefile + 1);
1108 goto cleanup_fetch_url;
1112 if ((rangeend != -1 && rangeend <= restart_point) ||
1113 (rangestart == -1 && filesize != -1 && filesize <= restart_point)) {
1116 fprintf(ttyout, "already done\n");
1118 goto cleanup_fetch_url;
1120 if (restart_point && rangestart != -1) {
1121 if (entitylen != -1)
1122 filesize = entitylen;
1123 if (rangestart != restart_point) {
1125 "Size of `%s' differs from save file `%s'",
1127 goto cleanup_fetch_url;
1129 fout = fopen(savefile, "a");
1131 fout = fopen(savefile, "w");
1133 warn("Can't open `%s'", savefile);
1134 goto cleanup_fetch_url;
1140 if (sigsetjmp(httpabort, 1))
1141 goto cleanup_fetch_url;
1142 (void)xsignal(SIGQUIT, psummary);
1143 oldintr = xsignal(SIGINT, aborthttp);
1145 if ((size_t)rcvbuf_size > bufsize) {
1147 (void)free(xferbuf);
1148 bufsize = rcvbuf_size;
1149 xferbuf = ftp_malloc(bufsize);
1156 /* Finally, suck down the file. */
1163 /* read chunk-size */
1165 if (fgets(xferbuf, bufsize, fin) == NULL) {
1166 warnx("Unexpected EOF reading chunk-size");
1167 goto cleanup_fetch_url;
1170 chunksize = strtol(xferbuf, &ep, 16);
1171 if (ep == xferbuf) {
1172 warnx("Invalid chunk-size");
1173 goto cleanup_fetch_url;
1175 if (errno == ERANGE || chunksize < 0) {
1177 warn("Chunk-size `%.*s'",
1178 (int)(ep-xferbuf), xferbuf);
1179 goto cleanup_fetch_url;
1183 * XXX: Work around bug in Apache 1.3.9 and
1184 * 1.3.11, which incorrectly put trailing
1185 * space after the chunk-size.
1190 /* skip [ chunk-ext ] */
1192 while (*ep && *ep != '\r')
1196 if (strcmp(ep, "\r\n") != 0) {
1197 warnx("Unexpected data following chunk-size");
1198 goto cleanup_fetch_url;
1200 DPRINTF("fetch_url: got chunk-size of " LLF "\n",
1202 if (chunksize == 0) {
1207 /* transfer file or chunk */
1209 struct timeval then, now, td;
1213 (void)gettimeofday(&then, NULL);
1214 bufrem = rate_get ? rate_get : (off_t)bufsize;
1216 bufrem = MIN(chunksize, bufrem);
1217 while (bufrem > 0) {
1218 flen = fread(xferbuf, sizeof(char),
1219 MIN((off_t)bufsize, bufrem), fin);
1224 if (fwrite(xferbuf, sizeof(char), flen, fout)
1226 warn("Writing `%s'", savefile);
1227 goto cleanup_fetch_url;
1229 if (hash && !progress) {
1230 while (bytes >= hashbytes) {
1231 (void)putc('#', ttyout);
1234 (void)fflush(ttyout);
1244 (void)gettimeofday(&now, NULL);
1245 timersub(&now, &then, &td);
1248 usleep(1000000 - td.tv_usec);
1251 if (ischunked && chunksize <= 0)
1254 /* read CRLF after chunk*/
1257 if (fgets(xferbuf, bufsize, fin) == NULL) {
1258 warnx("Unexpected EOF reading chunk CRLF");
1259 goto cleanup_fetch_url;
1261 if (strcmp(xferbuf, "\r\n") != 0) {
1262 warnx("Unexpected data following chunk");
1263 goto cleanup_fetch_url;
1268 } while (ischunked);
1270 /* XXX: deal with optional trailer & CRLF here? */
1272 if (hash && !progress && bytes > 0) {
1274 (void)putc('#', ttyout);
1275 (void)putc('\n', ttyout);
1278 warn("Reading file");
1279 goto cleanup_fetch_url;
1283 if (closefunc == fclose && mtime != -1) {
1284 struct timeval tval[2];
1286 (void)gettimeofday(&tval[0], NULL);
1287 tval[1].tv_sec = mtime;
1288 tval[1].tv_usec = 0;
1292 if (utimes(savefile, tval) == -1) {
1294 "Can't change modification time to %s",
1295 rfc2822time(localtime(&mtime)));
1303 goto cleanup_fetch_url;
1306 warnx("Improper response from `%s:%s'", host, port);
1310 (void)xsignal(SIGINT, oldintr);
1312 (void)xsignal(SIGPIPE, oldintp);
1317 if (closefunc != NULL && fout != NULL)
1324 memset(pass, 0, strlen(pass));
1329 FREEPTR(decodedpath);
1332 memset(ppass, 0, strlen(ppass));
1341 * Abort a HTTP retrieval
1344 aborthttp(int notused)
1351 len = strlcpy(msgbuf, "\nHTTP fetch aborted.\n", sizeof(msgbuf));
1352 write(fileno(ttyout), msgbuf, len);
1353 siglongjmp(httpabort, 1);
1357 * Retrieve ftp URL or classic ftp argument using FTP.
1358 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1359 * is still open (e.g, ftp xfer with trailing /)
1362 fetch_ftp(const char *url)
1364 char *cp, *xargv[5], rempath[MAXPATHLEN];
1365 char *host, *path, *dir, *file, *uuser, *pass;
1367 char cmdbuf[MAXPATHLEN];
1369 int dirhasglob, filehasglob, rval, transtype, xargc;
1370 int oanonftp, oautologin;
1374 DPRINTF("fetch_ftp: `%s'\n", url);
1375 host = path = dir = file = uuser = pass = NULL;
1380 if (STRNEQUAL(url, FTP_URL)) {
1381 if ((parse_url(url, "URL", &urltype, &uuser, &pass,
1382 &host, &port, &portnum, &path) == -1) ||
1383 (uuser != NULL && *uuser == '\0') ||
1384 EMPTYSTRING(host)) {
1385 warnx("Invalid URL `%s'", url);
1386 goto cleanup_fetch_ftp;
1389 * Note: Don't url_decode(path) here. We need to keep the
1390 * distinction between "/" and "%2F" until later.
1393 /* check for trailing ';type=[aid]' */
1394 if (! EMPTYSTRING(path) && (cp = strrchr(path, ';')) != NULL) {
1395 if (strcasecmp(cp, ";type=a") == 0)
1397 else if (strcasecmp(cp, ";type=i") == 0)
1399 else if (strcasecmp(cp, ";type=d") == 0) {
1401 "Directory listing via a URL is not supported");
1402 goto cleanup_fetch_ftp;
1404 warnx("Invalid suffix `%s' in URL `%s'", cp,
1406 goto cleanup_fetch_ftp;
1410 } else { /* classic style `[user@]host:[file]' */
1411 urltype = CLASSIC_URL_T;
1412 host = ftp_strdup(url);
1413 cp = strchr(host, '@');
1417 anonftp = 0; /* disable anonftp */
1418 host = ftp_strdup(cp + 1);
1420 cp = strchr(host, ':');
1423 path = ftp_strdup(cp + 1);
1426 if (EMPTYSTRING(host))
1427 goto cleanup_fetch_ftp;
1429 /* Extract the file and (if present) directory name. */
1431 if (! EMPTYSTRING(dir)) {
1433 * If we are dealing with classic `[user@]host:[path]' syntax,
1434 * then a path of the form `/file' (resulting from input of the
1435 * form `host:/file') means that we should do "CWD /" before
1436 * retrieving the file. So we set dir="/" and file="file".
1438 * But if we are dealing with URLs like `ftp://host/path' then
1439 * a path of the form `/file' (resulting from a URL of the form
1440 * `ftp://host//file') means that we should do `CWD ' (with an
1441 * empty argument) before retrieving the file. So we set
1442 * dir="" and file="file".
1444 * If the path does not contain / at all, we set dir=NULL.
1445 * (We get a path without any slashes if we are dealing with
1446 * classic `[user@]host:[file]' or URL `ftp://host/file'.)
1448 * In all other cases, we set dir to a string that does not
1449 * include the final '/' that separates the dir part from the
1450 * file part of the path. (This will be the empty string if
1451 * and only if we are dealing with a path of the form `/file'
1452 * resulting from an URL of the form `ftp://host//file'.)
1454 cp = strrchr(dir, '/');
1455 if (cp == dir && urltype == CLASSIC_URL_T) {
1457 (void)strlcpy(dirbuf, "/", sizeof(dirbuf));
1459 } else if (cp != NULL) {
1468 if (urltype == FTP_URL_T && file != NULL) {
1470 /* but still don't url_decode(dir) */
1472 DPRINTF("fetch_ftp: user `%s' pass `%s' host %s port %s "
1473 "path `%s' dir `%s' file `%s'\n",
1474 STRorNULL(uuser), STRorNULL(pass),
1475 STRorNULL(host), STRorNULL(port),
1476 STRorNULL(path), STRorNULL(dir), STRorNULL(file));
1478 dirhasglob = filehasglob = 0;
1479 if (doglob && urltype == CLASSIC_URL_T) {
1480 if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
1482 if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
1486 /* Set up the connection */
1489 disconnect(0, NULL);
1491 (void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
1501 oautologin = autologin;
1502 /* don't autologin in setpeer(), use ftp_login() below */
1504 setpeer(xargc, xargv);
1505 autologin = oautologin;
1506 if ((connected == 0) ||
1507 (connected == 1 && !ftp_login(host, uuser, pass))) {
1508 warnx("Can't connect or login to host `%s:%s'",
1509 host, port ? port : "?");
1510 goto cleanup_fetch_ftp;
1513 switch (transtype) {
1518 setbinary(1, xargv);
1521 errx(1, "fetch_ftp: unknown transfer type %d", transtype);
1525 * Change directories, if necessary.
1527 * Note: don't use EMPTYSTRING(dir) below, because
1528 * dir=="" means something different from dir==NULL.
1530 if (dir != NULL && !dirhasglob) {
1534 * If we are dealing with a classic `[user@]host:[path]'
1535 * (urltype is CLASSIC_URL_T) then we have a raw directory
1536 * name (not encoded in any way) and we can change
1537 * directories in one step.
1539 * If we are dealing with an `ftp://host/path' URL
1540 * (urltype is FTP_URL_T), then RFC3986 says we need to
1541 * send a separate CWD command for each unescaped "/"
1542 * in the path, and we have to interpret %hex escaping
1543 * *after* we find the slashes. It's possible to get
1544 * empty components here, (from multiple adjacent
1545 * slashes in the path) and RFC3986 says that we should
1546 * still do `CWD ' (with a null argument) in such cases.
1548 * Many ftp servers don't support `CWD ', so if there's an
1549 * error performing that command, bail out with a descriptive
1554 * host: dir="", urltype=CLASSIC_URL_T
1555 * logged in (to default directory)
1556 * host:file dir=NULL, urltype=CLASSIC_URL_T
1558 * host:dir/ dir="dir", urltype=CLASSIC_URL_T
1559 * "CWD dir", logged in
1560 * ftp://host/ dir="", urltype=FTP_URL_T
1561 * logged in (to default directory)
1562 * ftp://host/dir/ dir="dir", urltype=FTP_URL_T
1563 * "CWD dir", logged in
1564 * ftp://host/file dir=NULL, urltype=FTP_URL_T
1566 * ftp://host//file dir="", urltype=FTP_URL_T
1567 * "CWD ", "RETR file"
1568 * host:/file dir="/", urltype=CLASSIC_URL_T
1569 * "CWD /", "RETR file"
1570 * ftp://host///file dir="/", urltype=FTP_URL_T
1571 * "CWD ", "CWD ", "RETR file"
1572 * ftp://host/%2F/file dir="%2F", urltype=FTP_URL_T
1573 * "CWD /", "RETR file"
1574 * ftp://host/foo/file dir="foo", urltype=FTP_URL_T
1575 * "CWD foo", "RETR file"
1576 * ftp://host/foo/bar/file dir="foo/bar"
1577 * "CWD foo", "CWD bar", "RETR file"
1578 * ftp://host//foo/bar/file dir="/foo/bar"
1579 * "CWD ", "CWD foo", "CWD bar", "RETR file"
1580 * ftp://host/foo//bar/file dir="foo//bar"
1581 * "CWD foo", "CWD ", "CWD bar", "RETR file"
1582 * ftp://host/%2F/foo/bar/file dir="%2F/foo/bar"
1583 * "CWD /", "CWD foo", "CWD bar", "RETR file"
1584 * ftp://host/%2Ffoo/bar/file dir="%2Ffoo/bar"
1585 * "CWD /foo", "CWD bar", "RETR file"
1586 * ftp://host/%2Ffoo%2Fbar/file dir="%2Ffoo%2Fbar"
1587 * "CWD /foo/bar", "RETR file"
1588 * ftp://host/%2Ffoo%2Fbar%2Ffile dir=NULL
1589 * "RETR /foo/bar/file"
1591 * Note that we don't need `dir' after this point.
1594 if (urltype == FTP_URL_T) {
1595 nextpart = strchr(dir, '/');
1603 DPRINTF("fetch_ftp: dir `%s', nextpart `%s'\n",
1604 STRorNULL(dir), STRorNULL(nextpart));
1605 if (urltype == FTP_URL_T || *dir != '\0') {
1606 (void)strlcpy(cmdbuf, "cd", sizeof(cmdbuf));
1613 if (*dir == '\0' && code == 500)
1616 "ftp: The `CWD ' command (without a directory), which is required by\n"
1617 " RFC3986 to support the empty directory in the URL pathname (`//'),\n"
1618 " conflicts with the server's conformance to RFC0959.\n"
1619 " Try the same URL without the `//' in the URL pathname.\n"
1621 goto cleanup_fetch_ftp;
1625 } while (dir != NULL);
1628 if (EMPTYSTRING(file)) {
1630 goto cleanup_fetch_ftp;
1634 (void)strlcpy(rempath, dir, sizeof(rempath));
1635 (void)strlcat(rempath, "/", sizeof(rempath));
1636 (void)strlcat(rempath, file, sizeof(rempath));
1640 /* Fetch the file(s). */
1642 (void)strlcpy(cmdbuf, "get", sizeof(cmdbuf));
1646 if (dirhasglob || filehasglob) {
1649 ointeractive = interactive;
1651 if (restartautofetch)
1652 (void)strlcpy(cmdbuf, "mreget", sizeof(cmdbuf));
1654 (void)strlcpy(cmdbuf, "mget", sizeof(cmdbuf));
1657 interactive = ointeractive;
1659 if (outfile == NULL) {
1660 cp = strrchr(file, '/'); /* find savefile */
1666 xargv[2] = (char *)outfile;
1669 if (restartautofetch)
1670 reget(xargc, xargv);
1675 if ((code / 100) == COMPLETE)
1684 memset(pass, 0, strlen(pass));
1690 * Retrieve the given file to outfile.
1691 * Supports arguments of the form:
1692 * "host:path", "ftp://host/path" if $ftpproxy, call fetch_url() else
1694 * "http://host/path" call fetch_url() to use HTTP
1695 * "file:///path" call fetch_url() to copy
1696 * "about:..." print a message
1698 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1699 * is still open (e.g, ftp xfer with trailing /)
1702 go_fetch(const char *url)
1710 if (STRNEQUAL(url, ABOUT_URL)) {
1711 url += sizeof(ABOUT_URL) -1;
1712 if (strcasecmp(url, "ftp") == 0 ||
1713 strcasecmp(url, "tnftp") == 0) {
1715 "This version of ftp has been enhanced by Luke Mewburn <lukem@NetBSD.org>\n"
1716 "for the NetBSD project. Execute `man ftp' for more details.\n", ttyout);
1717 } else if (strcasecmp(url, "lukem") == 0) {
1719 "Luke Mewburn is the author of most of the enhancements in this ftp client.\n"
1720 "Please email feedback to <lukem@NetBSD.org>.\n", ttyout);
1721 } else if (strcasecmp(url, "netbsd") == 0) {
1723 "NetBSD is a freely available and redistributable UNIX-like operating system.\n"
1724 "For more information, see http://www.NetBSD.org/\n", ttyout);
1725 } else if (strcasecmp(url, "version") == 0) {
1726 fprintf(ttyout, "Version: %s %s%s\n",
1727 FTP_PRODUCT, FTP_VERSION,
1735 fprintf(ttyout, "`%s' is an interesting topic.\n", url);
1737 fputs("\n", ttyout);
1743 * Check for file:// and http:// URLs.
1745 if (STRNEQUAL(url, HTTP_URL) || STRNEQUAL(url, FILE_URL))
1746 return (fetch_url(url, NULL, NULL, NULL));
1749 * Try FTP URL-style and host:file arguments next.
1750 * If ftpproxy is set with an FTP URL, use fetch_url()
1751 * Othewise, use fetch_ftp().
1753 proxyenv = getoptionvalue("ftp_proxy");
1754 if (!EMPTYSTRING(proxyenv) && STRNEQUAL(url, FTP_URL))
1755 return (fetch_url(url, NULL, NULL, NULL));
1757 return (fetch_ftp(url));
1761 * Retrieve multiple files from the command line,
1762 * calling go_fetch() for each file.
1764 * If an ftp path has a trailing "/", the path will be cd-ed into and
1765 * the connection remains open, and the function will return -1
1766 * (to indicate the connection is alive).
1767 * If an error occurs the return value will be the offset+1 in
1768 * argv[] of the file that caused a problem (i.e, argv[x]
1770 * Otherwise, 0 is returned if all files retrieved successfully.
1773 auto_fetch(int argc, char *argv[])
1775 volatile int argpos, rval;
1779 if (sigsetjmp(toplevel, 1)) {
1781 disconnect(0, NULL);
1786 (void)xsignal(SIGINT, intr);
1787 (void)xsignal(SIGPIPE, lostpeer);
1790 * Loop through as long as there's files to fetch.
1792 for (; (rval == 0) && (argpos < argc); argpos++) {
1793 if (strchr(argv[argpos], ':') == NULL)
1797 anonftp = 2; /* Handle "automatic" transfers. */
1798 rval = go_fetch(argv[argpos]);
1799 if (outfile != NULL && strcmp(outfile, "-") != 0
1800 && outfile[0] != '|')
1806 if (connected && rval != -1)
1807 disconnect(0, NULL);
1813 * Upload multiple files from the command line.
1815 * If an error occurs the return value will be the offset+1 in
1816 * argv[] of the file that caused a problem (i.e, argv[x]
1818 * Otherwise, 0 is returned if all files uploaded successfully.
1821 auto_put(int argc, char **argv, const char *uploadserver)
1823 char *uargv[4], *path, *pathsep;
1824 int uargc, rval, argpos;
1826 char cmdbuf[MAX_C_NAME];
1828 (void)strlcpy(cmdbuf, "mput", sizeof(cmdbuf));
1832 uargv[2] = uargv[3] = NULL;
1836 DPRINTF("auto_put: target `%s'\n", uploadserver);
1838 path = ftp_strdup(uploadserver);
1840 if (path[len - 1] != '/' && path[len - 1] != ':') {
1842 * make sure we always pass a directory to auto_fetch
1844 if (argc > 1) { /* more than one file to upload */
1845 len = strlen(uploadserver) + 2; /* path + "/" + "\0" */
1847 path = (char *)ftp_malloc(len);
1848 (void)strlcpy(path, uploadserver, len);
1849 (void)strlcat(path, "/", len);
1850 } else { /* single file to upload */
1851 (void)strlcpy(cmdbuf, "put", sizeof(cmdbuf));
1853 pathsep = strrchr(path, '/');
1854 if (pathsep == NULL) {
1855 pathsep = strrchr(path, ':');
1856 if (pathsep == NULL) {
1857 warnx("Invalid URL `%s'", path);
1858 goto cleanup_auto_put;
1861 uargv[2] = ftp_strdup(pathsep);
1864 uargv[2] = ftp_strdup(pathsep + 1);
1869 DPRINTF("auto_put: URL `%s' argv[2] `%s'\n",
1870 path, STRorNULL(uargv[2]));
1872 /* connect and cwd */
1873 rval = auto_fetch(1, &path);
1875 goto cleanup_auto_put;
1879 /* target filename provided; upload 1 file */
1880 /* XXX : is this the best way? */
1884 if ((code / 100) != COMPLETE)
1886 } else { /* otherwise a target dir: upload all files to it */
1887 for(argpos = 0; argv[argpos] != NULL; argpos++) {
1888 uargv[1] = argv[argpos];
1890 if ((code / 100) != COMPLETE) {