Home | History | Annotate | Line # | Download | only in ftp
fetch.c revision 1.227
      1 /*	$NetBSD: fetch.c,v 1.227 2017/01/31 21:05:35 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1997-2015 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Luke Mewburn.
      9  *
     10  * This code is derived from software contributed to The NetBSD Foundation
     11  * by Scott Aaron Bamford.
     12  *
     13  * This code is derived from software contributed to The NetBSD Foundation
     14  * by Thomas Klausner.
     15  *
     16  * Redistribution and use in source and binary forms, with or without
     17  * modification, are permitted provided that the following conditions
     18  * are met:
     19  * 1. Redistributions of source code must retain the above copyright
     20  *    notice, this list of conditions and the following disclaimer.
     21  * 2. Redistributions in binary form must reproduce the above copyright
     22  *    notice, this list of conditions and the following disclaimer in the
     23  *    documentation and/or other materials provided with the distribution.
     24  *
     25  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     26  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     27  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     28  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     29  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     30  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     32  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     33  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     34  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     35  * POSSIBILITY OF SUCH DAMAGE.
     36  */
     37 
     38 #include <sys/cdefs.h>
     39 #ifndef lint
     40 __RCSID("$NetBSD: fetch.c,v 1.227 2017/01/31 21:05:35 christos Exp $");
     41 #endif /* not lint */
     42 
     43 /*
     44  * FTP User Program -- Command line file retrieval
     45  */
     46 
     47 #include <sys/types.h>
     48 #include <sys/param.h>
     49 #include <sys/socket.h>
     50 #include <sys/stat.h>
     51 #include <sys/time.h>
     52 
     53 #include <netinet/in.h>
     54 
     55 #include <arpa/ftp.h>
     56 #include <arpa/inet.h>
     57 
     58 #include <assert.h>
     59 #include <ctype.h>
     60 #include <err.h>
     61 #include <errno.h>
     62 #include <netdb.h>
     63 #include <fcntl.h>
     64 #include <stdio.h>
     65 #include <stdlib.h>
     66 #include <string.h>
     67 #include <unistd.h>
     68 #include <time.h>
     69 
     70 #include "ssl.h"
     71 #include "ftp_var.h"
     72 #include "version.h"
     73 
     74 typedef enum {
     75 	UNKNOWN_URL_T=-1,
     76 	HTTP_URL_T,
     77 	HTTPS_URL_T,
     78 	FTP_URL_T,
     79 	FILE_URL_T,
     80 	CLASSIC_URL_T
     81 } url_t;
     82 
     83 struct authinfo {
     84 	char *auth;
     85 	char *user;
     86 	char *pass;
     87 };
     88 
     89 struct urlinfo {
     90 	char *host;
     91 	char *port;
     92 	char *path;
     93 	url_t utype;
     94 	in_port_t portnum;
     95 };
     96 
     97 struct posinfo {
     98 	off_t rangestart;
     99 	off_t rangeend;
    100 	off_t entitylen;
    101 };
    102 
    103 __dead static void	aborthttp(int);
    104 __dead static void	timeouthttp(int);
    105 #ifndef NO_AUTH
    106 static int	auth_url(const char *, char **, const struct authinfo *);
    107 static void	base64_encode(const unsigned char *, size_t, unsigned char *);
    108 #endif
    109 static int	go_fetch(const char *);
    110 static int	fetch_ftp(const char *);
    111 static int	fetch_url(const char *, const char *, char *, char *);
    112 static const char *match_token(const char **, const char *);
    113 static int	parse_url(const char *, const char *, struct urlinfo *,
    114     struct authinfo *);
    115 static void	url_decode(char *);
    116 static void	freeauthinfo(struct authinfo *);
    117 static void	freeurlinfo(struct urlinfo *);
    118 
    119 static int	redirect_loop;
    120 
    121 
    122 #define	STRNEQUAL(a,b)	(strncasecmp((a), (b), sizeof((b))-1) == 0)
    123 #define	ISLWS(x)	((x)=='\r' || (x)=='\n' || (x)==' ' || (x)=='\t')
    124 #define	SKIPLWS(x)	do { while (ISLWS((*x))) x++; } while (0)
    125 
    126 
    127 #define	ABOUT_URL	"about:"	/* propaganda */
    128 #define	FILE_URL	"file://"	/* file URL prefix */
    129 #define	FTP_URL		"ftp://"	/* ftp URL prefix */
    130 #define	HTTP_URL	"http://"	/* http URL prefix */
    131 #ifdef WITH_SSL
    132 #define	HTTPS_URL	"https://"	/* https URL prefix */
    133 
    134 #define	IS_HTTP_TYPE(urltype) \
    135 	(((urltype) == HTTP_URL_T) || ((urltype) == HTTPS_URL_T))
    136 #else
    137 #define	IS_HTTP_TYPE(urltype) \
    138 	((urltype) == HTTP_URL_T)
    139 #endif
    140 
    141 /*
    142  * Determine if token is the next word in buf (case insensitive).
    143  * If so, advance buf past the token and any trailing LWS, and
    144  * return a pointer to the token (in buf).  Otherwise, return NULL.
    145  * token may be preceded by LWS.
    146  * token must be followed by LWS or NUL.  (I.e, don't partial match).
    147  */
    148 static const char *
    149 match_token(const char **buf, const char *token)
    150 {
    151 	const char	*p, *orig;
    152 	size_t		tlen;
    153 
    154 	tlen = strlen(token);
    155 	p = *buf;
    156 	SKIPLWS(p);
    157 	orig = p;
    158 	if (strncasecmp(p, token, tlen) != 0)
    159 		return NULL;
    160 	p += tlen;
    161 	if (*p != '\0' && !ISLWS(*p))
    162 		return NULL;
    163 	SKIPLWS(p);
    164 	orig = *buf;
    165 	*buf = p;
    166 	return orig;
    167 }
    168 
    169 static void
    170 initposinfo(struct posinfo *pi)
    171 {
    172 	pi->rangestart = pi->rangeend = pi->entitylen = -1;
    173 }
    174 
    175 static void
    176 initauthinfo(struct authinfo *ai, char *auth)
    177 {
    178 	ai->auth = auth;
    179 	ai->user = ai->pass = 0;
    180 }
    181 
    182 static void
    183 freeauthinfo(struct authinfo *a)
    184 {
    185 	FREEPTR(a->user);
    186 	if (a->pass != NULL)
    187 		memset(a->pass, 0, strlen(a->pass));
    188 	FREEPTR(a->pass);
    189 }
    190 
    191 static void
    192 initurlinfo(struct urlinfo *ui)
    193 {
    194 	ui->host = ui->port = ui->path = 0;
    195 	ui->utype = UNKNOWN_URL_T;
    196 	ui->portnum = 0;
    197 }
    198 
    199 static void
    200 copyurlinfo(struct urlinfo *dui, struct urlinfo *sui)
    201 {
    202 	dui->host = ftp_strdup(sui->host);
    203 	dui->port = ftp_strdup(sui->port);
    204 	dui->path = ftp_strdup(sui->path);
    205 	dui->utype = sui->utype;
    206 	dui->portnum = sui->portnum;
    207 }
    208 
    209 static void
    210 freeurlinfo(struct urlinfo *ui)
    211 {
    212 	FREEPTR(ui->host);
    213 	FREEPTR(ui->port);
    214 	FREEPTR(ui->path);
    215 }
    216 
    217 #ifndef NO_AUTH
    218 /*
    219  * Generate authorization response based on given authentication challenge.
    220  * Returns -1 if an error occurred, otherwise 0.
    221  * Sets response to a malloc(3)ed string; caller should free.
    222  */
    223 static int
    224 auth_url(const char *challenge, char **response, const struct authinfo *auth)
    225 {
    226 	const char	*cp, *scheme, *errormsg;
    227 	char		*ep, *clear, *realm;
    228 	char		 uuser[BUFSIZ], *gotpass;
    229 	const char	*upass;
    230 	int		 rval;
    231 	size_t		 len, clen, rlen;
    232 
    233 	*response = NULL;
    234 	clear = realm = NULL;
    235 	rval = -1;
    236 	cp = challenge;
    237 	scheme = "Basic";	/* only support Basic authentication */
    238 	gotpass = NULL;
    239 
    240 	DPRINTF("auth_url: challenge `%s'\n", challenge);
    241 
    242 	if (! match_token(&cp, scheme)) {
    243 		warnx("Unsupported authentication challenge `%s'",
    244 		    challenge);
    245 		goto cleanup_auth_url;
    246 	}
    247 
    248 #define	REALM "realm=\""
    249 	if (STRNEQUAL(cp, REALM))
    250 		cp += sizeof(REALM) - 1;
    251 	else {
    252 		warnx("Unsupported authentication challenge `%s'",
    253 		    challenge);
    254 		goto cleanup_auth_url;
    255 	}
    256 /* XXX: need to improve quoted-string parsing to support \ quoting, etc. */
    257 	if ((ep = strchr(cp, '\"')) != NULL) {
    258 		len = ep - cp;
    259 		realm = (char *)ftp_malloc(len + 1);
    260 		(void)strlcpy(realm, cp, len + 1);
    261 	} else {
    262 		warnx("Unsupported authentication challenge `%s'",
    263 		    challenge);
    264 		goto cleanup_auth_url;
    265 	}
    266 
    267 	fprintf(ttyout, "Username for `%s': ", realm);
    268 	if (auth->user != NULL) {
    269 		(void)strlcpy(uuser, auth->user, sizeof(uuser));
    270 		fprintf(ttyout, "%s\n", uuser);
    271 	} else {
    272 		(void)fflush(ttyout);
    273 		if (get_line(stdin, uuser, sizeof(uuser), &errormsg) < 0) {
    274 			warnx("%s; can't authenticate", errormsg);
    275 			goto cleanup_auth_url;
    276 		}
    277 	}
    278 	if (auth->pass != NULL)
    279 		upass = auth->pass;
    280 	else {
    281 		gotpass = getpass("Password: ");
    282 		if (gotpass == NULL) {
    283 			warnx("Can't read password");
    284 			goto cleanup_auth_url;
    285 		}
    286 		upass = gotpass;
    287 	}
    288 
    289 	clen = strlen(uuser) + strlen(upass) + 2;	/* user + ":" + pass + "\0" */
    290 	clear = (char *)ftp_malloc(clen);
    291 	(void)strlcpy(clear, uuser, clen);
    292 	(void)strlcat(clear, ":", clen);
    293 	(void)strlcat(clear, upass, clen);
    294 	if (gotpass)
    295 		memset(gotpass, 0, strlen(gotpass));
    296 
    297 						/* scheme + " " + enc + "\0" */
    298 	rlen = strlen(scheme) + 1 + (clen + 2) * 4 / 3 + 1;
    299 	*response = ftp_malloc(rlen);
    300 	(void)strlcpy(*response, scheme, rlen);
    301 	len = strlcat(*response, " ", rlen);
    302 			/* use  `clen - 1'  to not encode the trailing NUL */
    303 	base64_encode((unsigned char *)clear, clen - 1,
    304 	    (unsigned char *)*response + len);
    305 	memset(clear, 0, clen);
    306 	rval = 0;
    307 
    308  cleanup_auth_url:
    309 	FREEPTR(clear);
    310 	FREEPTR(realm);
    311 	return (rval);
    312 }
    313 
    314 /*
    315  * Encode len bytes starting at clear using base64 encoding into encoded,
    316  * which should be at least ((len + 2) * 4 / 3 + 1) in size.
    317  */
    318 static void
    319 base64_encode(const unsigned char *clear, size_t len, unsigned char *encoded)
    320 {
    321 	static const unsigned char enc[] =
    322 	    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    323 	unsigned char	*cp;
    324 	size_t	 i;
    325 
    326 	cp = encoded;
    327 	for (i = 0; i < len; i += 3) {
    328 		*(cp++) = enc[((clear[i + 0] >> 2))];
    329 		*(cp++) = enc[((clear[i + 0] << 4) & 0x30)
    330 			    | ((clear[i + 1] >> 4) & 0x0f)];
    331 		*(cp++) = enc[((clear[i + 1] << 2) & 0x3c)
    332 			    | ((clear[i + 2] >> 6) & 0x03)];
    333 		*(cp++) = enc[((clear[i + 2]     ) & 0x3f)];
    334 	}
    335 	*cp = '\0';
    336 	while (i-- > len)
    337 		*(--cp) = '=';
    338 }
    339 #endif
    340 
    341 /*
    342  * Decode %xx escapes in given string, `in-place'.
    343  */
    344 static void
    345 url_decode(char *url)
    346 {
    347 	unsigned char *p, *q;
    348 
    349 	if (EMPTYSTRING(url))
    350 		return;
    351 	p = q = (unsigned char *)url;
    352 
    353 #define	HEXTOINT(x) (x - (isdigit(x) ? '0' : (islower(x) ? 'a' : 'A') - 10))
    354 	while (*p) {
    355 		if (p[0] == '%'
    356 		    && p[1] && isxdigit((unsigned char)p[1])
    357 		    && p[2] && isxdigit((unsigned char)p[2])) {
    358 			*q++ = HEXTOINT(p[1]) * 16 + HEXTOINT(p[2]);
    359 			p+=3;
    360 		} else
    361 			*q++ = *p++;
    362 	}
    363 	*q = '\0';
    364 }
    365 
    366 
    367 /*
    368  * Parse URL of form (per RFC 3986):
    369  *	<type>://[<user>[:<password>]@]<host>[:<port>][/<path>]
    370  * Returns -1 if a parse error occurred, otherwise 0.
    371  * It's the caller's responsibility to url_decode() the returned
    372  * user, pass and path.
    373  *
    374  * Sets type to url_t, each of the given char ** pointers to a
    375  * malloc(3)ed strings of the relevant section, and port to
    376  * the number given, or ftpport if ftp://, or httpport if http://.
    377  *
    378  * XXX: this is not totally RFC 3986 compliant; <path> will have the
    379  * leading `/' unless it's an ftp:// URL, as this makes things easier
    380  * for file:// and http:// URLs.  ftp:// URLs have the `/' between the
    381  * host and the URL-path removed, but any additional leading slashes
    382  * in the URL-path are retained (because they imply that we should
    383  * later do "CWD" with a null argument).
    384  *
    385  * Examples:
    386  *	 input URL			 output path
    387  *	 ---------			 -----------
    388  *	"http://host"			"/"
    389  *	"http://host/"			"/"
    390  *	"http://host/path"		"/path"
    391  *	"file://host/dir/file"		"dir/file"
    392  *	"ftp://host"			""
    393  *	"ftp://host/"			""
    394  *	"ftp://host//"			"/"
    395  *	"ftp://host/dir/file"		"dir/file"
    396  *	"ftp://host//dir/file"		"/dir/file"
    397  */
    398 
    399 static int
    400 parse_url(const char *url, const char *desc, struct urlinfo *ui,
    401     struct authinfo *auth)
    402 {
    403 	const char	*origurl, *tport;
    404 	char		*cp, *ep, *thost;
    405 	size_t		 len;
    406 
    407 	if (url == NULL || desc == NULL || ui == NULL || auth == NULL)
    408 		errx(1, "parse_url: invoked with NULL argument!");
    409 	DPRINTF("parse_url: %s `%s'\n", desc, url);
    410 
    411 	origurl = url;
    412 	tport = NULL;
    413 
    414 	if (STRNEQUAL(url, HTTP_URL)) {
    415 		url += sizeof(HTTP_URL) - 1;
    416 		ui->utype = HTTP_URL_T;
    417 		ui->portnum = HTTP_PORT;
    418 		tport = httpport;
    419 	} else if (STRNEQUAL(url, FTP_URL)) {
    420 		url += sizeof(FTP_URL) - 1;
    421 		ui->utype = FTP_URL_T;
    422 		ui->portnum = FTP_PORT;
    423 		tport = ftpport;
    424 	} else if (STRNEQUAL(url, FILE_URL)) {
    425 		url += sizeof(FILE_URL) - 1;
    426 		ui->utype = FILE_URL_T;
    427 		tport = "";
    428 #ifdef WITH_SSL
    429 	} else if (STRNEQUAL(url, HTTPS_URL)) {
    430 		url += sizeof(HTTPS_URL) - 1;
    431 		ui->utype = HTTPS_URL_T;
    432 		ui->portnum = HTTPS_PORT;
    433 		tport = httpsport;
    434 #endif
    435 	} else {
    436 		warnx("Invalid %s `%s'", desc, url);
    437  cleanup_parse_url:
    438 		freeauthinfo(auth);
    439 		freeurlinfo(ui);
    440 		return (-1);
    441 	}
    442 
    443 	if (*url == '\0')
    444 		return (0);
    445 
    446 			/* find [user[:pass]@]host[:port] */
    447 	ep = strchr(url, '/');
    448 	if (ep == NULL)
    449 		thost = ftp_strdup(url);
    450 	else {
    451 		len = ep - url;
    452 		thost = (char *)ftp_malloc(len + 1);
    453 		(void)strlcpy(thost, url, len + 1);
    454 		if (ui->utype == FTP_URL_T)	/* skip first / for ftp URLs */
    455 			ep++;
    456 		ui->path = ftp_strdup(ep);
    457 	}
    458 
    459 	cp = strchr(thost, '@');	/* look for user[:pass]@ in URLs */
    460 	if (cp != NULL) {
    461 		if (ui->utype == FTP_URL_T)
    462 			anonftp = 0;	/* disable anonftp */
    463 		auth->user = thost;
    464 		*cp = '\0';
    465 		thost = ftp_strdup(cp + 1);
    466 		cp = strchr(auth->user, ':');
    467 		if (cp != NULL) {
    468 			*cp = '\0';
    469 			auth->pass = ftp_strdup(cp + 1);
    470 		}
    471 		url_decode(auth->user);
    472 		if (auth->pass)
    473 			url_decode(auth->pass);
    474 	}
    475 
    476 #ifdef INET6
    477 			/*
    478 			 * Check if thost is an encoded IPv6 address, as per
    479 			 * RFC 3986:
    480 			 *	`[' ipv6-address ']'
    481 			 */
    482 	if (*thost == '[') {
    483 		cp = thost + 1;
    484 		if ((ep = strchr(cp, ']')) == NULL ||
    485 		    (ep[1] != '\0' && ep[1] != ':')) {
    486 			warnx("Invalid address `%s' in %s `%s'",
    487 			    thost, desc, origurl);
    488 			goto cleanup_parse_url;
    489 		}
    490 		len = ep - cp;		/* change `[xyz]' -> `xyz' */
    491 		memmove(thost, thost + 1, len);
    492 		thost[len] = '\0';
    493 		if (! isipv6addr(thost)) {
    494 			warnx("Invalid IPv6 address `%s' in %s `%s'",
    495 			    thost, desc, origurl);
    496 			goto cleanup_parse_url;
    497 		}
    498 		cp = ep + 1;
    499 		if (*cp == ':')
    500 			cp++;
    501 		else
    502 			cp = NULL;
    503 	} else
    504 #endif /* INET6 */
    505 		if ((cp = strchr(thost, ':')) != NULL)
    506 			*cp++ = '\0';
    507 	ui->host = thost;
    508 
    509 			/* look for [:port] */
    510 	if (cp != NULL) {
    511 		unsigned long	nport;
    512 
    513 		nport = strtoul(cp, &ep, 10);
    514 		if (*cp == '\0' || *ep != '\0' ||
    515 		    nport < 1 || nport > MAX_IN_PORT_T) {
    516 			warnx("Unknown port `%s' in %s `%s'",
    517 			    cp, desc, origurl);
    518 			goto cleanup_parse_url;
    519 		}
    520 		ui->portnum = nport;
    521 		tport = cp;
    522 	}
    523 
    524 	if (tport != NULL)
    525 		ui->port = ftp_strdup(tport);
    526 	if (ui->path == NULL) {
    527 		const char *emptypath = "/";
    528 		if (ui->utype == FTP_URL_T)	/* skip first / for ftp URLs */
    529 			emptypath++;
    530 		ui->path = ftp_strdup(emptypath);
    531 	}
    532 
    533 	DPRINTF("parse_url: user `%s' pass `%s' host %s port %s(%d) "
    534 	    "path `%s'\n",
    535 	    STRorNULL(auth->user), STRorNULL(auth->pass),
    536 	    STRorNULL(ui->host), STRorNULL(ui->port),
    537 	    ui->portnum ? ui->portnum : -1, STRorNULL(ui->path));
    538 
    539 	return (0);
    540 }
    541 
    542 sigjmp_buf	httpabort;
    543 
    544 static int
    545 ftp_socket(const struct urlinfo *ui, void **ssl)
    546 {
    547 	struct addrinfo	hints, *res, *res0 = NULL;
    548 	int error;
    549 	int s;
    550 	const char *host = ui->host;
    551 	const char *port = ui->port;
    552 
    553 	if (ui->utype != HTTPS_URL_T)
    554 		ssl = NULL;
    555 
    556 	memset(&hints, 0, sizeof(hints));
    557 	hints.ai_flags = 0;
    558 	hints.ai_family = family;
    559 	hints.ai_socktype = SOCK_STREAM;
    560 	hints.ai_protocol = 0;
    561 
    562 	error = getaddrinfo(host, port, &hints, &res0);
    563 	if (error) {
    564 		warnx("Can't LOOKUP `%s:%s': %s", host, port,
    565 		    (error == EAI_SYSTEM) ? strerror(errno)
    566 					  : gai_strerror(error));
    567 		return -1;
    568 	}
    569 
    570 	if (res0->ai_canonname)
    571 		host = res0->ai_canonname;
    572 
    573 	s = -1;
    574 	if (ssl)
    575 		*ssl = NULL;
    576 	for (res = res0; res; res = res->ai_next) {
    577 		char	hname[NI_MAXHOST], sname[NI_MAXSERV];
    578 
    579 		ai_unmapped(res);
    580 		if (getnameinfo(res->ai_addr, res->ai_addrlen,
    581 		    hname, sizeof(hname), sname, sizeof(sname),
    582 		    NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
    583 			strlcpy(hname, "?", sizeof(hname));
    584 			strlcpy(sname, "?", sizeof(sname));
    585 		}
    586 
    587 		if (verbose && res0->ai_next) {
    588 #ifdef INET6
    589 			if(res->ai_family == AF_INET6) {
    590 				fprintf(ttyout, "Trying [%s]:%s ...\n",
    591 				    hname, sname);
    592 			} else {
    593 #endif
    594 				fprintf(ttyout, "Trying %s:%s ...\n",
    595 				    hname, sname);
    596 #ifdef INET6
    597 			}
    598 #endif
    599 		}
    600 
    601 		s = socket(res->ai_family, SOCK_STREAM, res->ai_protocol);
    602 		if (s < 0) {
    603 			warn(
    604 			    "Can't create socket for connection to "
    605 			    "`%s:%s'", hname, sname);
    606 			continue;
    607 		}
    608 
    609 		if (ftp_connect(s, res->ai_addr, res->ai_addrlen,
    610 		    verbose || !res->ai_next) < 0) {
    611 			close(s);
    612 			s = -1;
    613 			continue;
    614 		}
    615 
    616 #ifdef WITH_SSL
    617 		if (ssl) {
    618 			if ((*ssl = fetch_start_ssl(s, host)) == NULL) {
    619 				close(s);
    620 				s = -1;
    621 				continue;
    622 			}
    623 		}
    624 #endif
    625 		break;
    626 	}
    627 	if (res0)
    628 		freeaddrinfo(res0);
    629 	return s;
    630 }
    631 
    632 static int
    633 handle_noproxy(const char *host, in_port_t portnum)
    634 {
    635 
    636 	char *cp, *ep, *np, *np_copy, *np_iter, *no_proxy;
    637 	unsigned long np_port;
    638 	size_t hlen, plen;
    639 	int isproxy = 1;
    640 
    641 	/* check URL against list of no_proxied sites */
    642 	no_proxy = getoptionvalue("no_proxy");
    643 	if (EMPTYSTRING(no_proxy))
    644 		return isproxy;
    645 
    646 	np_iter = np_copy = ftp_strdup(no_proxy);
    647 	hlen = strlen(host);
    648 	while ((cp = strsep(&np_iter, " ,")) != NULL) {
    649 		if (*cp == '\0')
    650 			continue;
    651 		if ((np = strrchr(cp, ':')) != NULL) {
    652 			*np++ =  '\0';
    653 			np_port = strtoul(np, &ep, 10);
    654 			if (*np == '\0' || *ep != '\0')
    655 				continue;
    656 			if (np_port != portnum)
    657 				continue;
    658 		}
    659 		plen = strlen(cp);
    660 		if (hlen < plen)
    661 			continue;
    662 		if (strncasecmp(host + hlen - plen, cp, plen) == 0) {
    663 			isproxy = 0;
    664 			break;
    665 		}
    666 	}
    667 	FREEPTR(np_copy);
    668 	return isproxy;
    669 }
    670 
    671 static int
    672 handle_proxy(const char *url, const char *penv, struct urlinfo *ui,
    673     struct authinfo *pauth)
    674 {
    675 	struct urlinfo pui;
    676 
    677 	if (isipv6addr(ui->host) && strchr(ui->host, '%') != NULL) {
    678 		warnx("Scoped address notation `%s' disallowed via web proxy",
    679 		    ui->host);
    680 		return -1;
    681 	}
    682 
    683 	initurlinfo(&pui);
    684 	if (parse_url(penv, "proxy URL", &pui, pauth) == -1)
    685 		return -1;
    686 
    687 	if ((!IS_HTTP_TYPE(pui.utype) && pui.utype != FTP_URL_T) ||
    688 	    EMPTYSTRING(pui.host) ||
    689 	    (! EMPTYSTRING(pui.path) && strcmp(pui.path, "/") != 0)) {
    690 		warnx("Malformed proxy URL `%s'", penv);
    691 		freeurlinfo(&pui);
    692 		return -1;
    693 	}
    694 
    695 	FREEPTR(pui.path);
    696 	pui.path = ftp_strdup(url);
    697 
    698 	freeurlinfo(ui);
    699 	*ui = pui;
    700 
    701 	return 0;
    702 }
    703 
    704 static void
    705 print_host(FETCH *fin, const struct urlinfo *ui)
    706 {
    707 	char *h, *p;
    708 
    709 	if (strchr(ui->host, ':') == NULL) {
    710 		fetch_printf(fin, "Host: %s", ui->host);
    711 	} else {
    712 		/*
    713 		 * strip off IPv6 scope identifier, since it is
    714 		 * local to the node
    715 		 */
    716 		h = ftp_strdup(ui->host);
    717 		if (isipv6addr(h) && (p = strchr(h, '%')) != NULL)
    718 			*p = '\0';
    719 
    720 		fetch_printf(fin, "Host: [%s]", h);
    721 		free(h);
    722 	}
    723 
    724 	if ((ui->utype == HTTP_URL_T && ui->portnum != HTTP_PORT) ||
    725 	    (ui->utype == HTTPS_URL_T && ui->portnum != HTTPS_PORT))
    726 		fetch_printf(fin, ":%u", ui->portnum);
    727 	fetch_printf(fin, "\r\n");
    728 }
    729 
    730 static void
    731 print_agent(FETCH *fin)
    732 {
    733 	const char *useragent;
    734 	if ((useragent = getenv("FTPUSERAGENT")) != NULL) {
    735 		fetch_printf(fin, "User-Agent: %s\r\n", useragent);
    736 	} else {
    737 		fetch_printf(fin, "User-Agent: %s/%s\r\n",
    738 		    FTP_PRODUCT, FTP_VERSION);
    739 	}
    740 }
    741 
    742 static void
    743 print_cache(FETCH *fin, int isproxy)
    744 {
    745 	fetch_printf(fin, isproxy ?
    746 	    "Pragma: no-cache\r\n" :
    747 	    "Cache-Control: no-cache\r\n");
    748 }
    749 
    750 static int
    751 print_get(FETCH *fin, int hasleading, int isproxy, const struct urlinfo *oui,
    752     const struct urlinfo *ui)
    753 {
    754 	const char *leading = hasleading ? ", " : "  (";
    755 
    756 	if (isproxy) {
    757 		if (verbose) {
    758 			fprintf(ttyout, "%svia %s:%u", leading,
    759 			    ui->host, ui->portnum);
    760 			leading = ", ";
    761 			hasleading++;
    762 		}
    763 		fetch_printf(fin, "GET %s HTTP/1.0\r\n", ui->path);
    764 		print_host(fin, oui);
    765 		return hasleading;
    766 	}
    767 
    768 	fetch_printf(fin, "GET %s HTTP/1.1\r\n", ui->path);
    769 	print_host(fin, ui);
    770 	fetch_printf(fin, "Accept: */*\r\n");
    771 	fetch_printf(fin, "Connection: close\r\n");
    772 	if (restart_point) {
    773 		fputs(leading, ttyout);
    774 		fetch_printf(fin, "Range: bytes=" LLF "-\r\n",
    775 		    (LLT)restart_point);
    776 		fprintf(ttyout, "restarting at " LLF, (LLT)restart_point);
    777 		hasleading++;
    778 	}
    779 	return hasleading;
    780 }
    781 
    782 static void
    783 getmtime(const char *cp, time_t *mtime)
    784 {
    785 	struct tm parsed;
    786 	const char *t;
    787 
    788 	memset(&parsed, 0, sizeof(parsed));
    789 	t = parse_rfc2616time(&parsed, cp);
    790 
    791 	if (t == NULL)
    792 		return;
    793 
    794 	parsed.tm_isdst = -1;
    795 	if (*t == '\0')
    796 		*mtime = timegm(&parsed);
    797 
    798 #ifndef NO_DEBUG
    799 	if (ftp_debug && *mtime != -1) {
    800 		fprintf(ttyout, "parsed time as: %s",
    801 		    rfc2822time(localtime(mtime)));
    802 	}
    803 #endif
    804 }
    805 
    806 static int
    807 print_proxy(FETCH *fin, int hasleading, const char *wwwauth,
    808     const char *proxyauth)
    809 {
    810 	const char *leading = hasleading ? ", " : "  (";
    811 
    812 	if (wwwauth) {
    813 		if (verbose) {
    814 			fprintf(ttyout, "%swith authorization", leading);
    815 			hasleading++;
    816 		}
    817 		fetch_printf(fin, "Authorization: %s\r\n", wwwauth);
    818 	}
    819 	if (proxyauth) {
    820 		if (verbose) {
    821 			fprintf(ttyout, "%swith proxy authorization", leading);
    822 			hasleading++;
    823 		}
    824 		fetch_printf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
    825 	}
    826 	return hasleading;
    827 }
    828 
    829 #ifdef WITH_SSL
    830 static void
    831 print_connect(FETCH *fin, const struct urlinfo *ui)
    832 {
    833 	char hname[NI_MAXHOST], *p;
    834 	const char *h;
    835 
    836 	if (isipv6addr(ui->host)) {
    837 		/*
    838 		 * strip off IPv6 scope identifier,
    839 		 * since it is local to the node
    840 		 */
    841 		if ((p = strchr(ui->host, '%')) == NULL)
    842 			snprintf(hname, sizeof(hname), "[%s]", ui->host);
    843 		else
    844 			snprintf(hname, sizeof(hname), "[%.*s]",
    845 			    (int)(p - ui->host), ui->host);
    846 		h = hname;
    847 	} else
    848 		h = ui->host;
    849 
    850 	fetch_printf(fin, "CONNECT %s:%d HTTP/1.1\r\n", h, ui->portnum);
    851 	fetch_printf(fin, "Host: %s:%d\r\n", h, ui->portnum);
    852 }
    853 #endif
    854 
    855 #define C_OK 0
    856 #define C_CLEANUP 1
    857 #define C_IMPROPER 2
    858 #define C_RESTART 3
    859 
    860 static int
    861 getresponseline(FETCH *fin, char *buf, size_t buflen, int *len)
    862 {
    863 	const char *errormsg;
    864 
    865 	alarmtimer(quit_time ? quit_time : 60);
    866 	*len = fetch_getline(fin, buf, buflen, &errormsg);
    867 	alarmtimer(0);
    868 	if (*len < 0) {
    869 		if (*errormsg == '\n')
    870 			errormsg++;
    871 		warnx("Receiving HTTP reply: %s", errormsg);
    872 		return C_CLEANUP;
    873 	}
    874 	while (*len > 0 && (ISLWS(buf[*len-1])))
    875 		buf[--*len] = '\0';
    876 
    877 	if (*len)
    878 		DPRINTF("%s: received `%s'\n", __func__, buf);
    879 	return C_OK;
    880 }
    881 
    882 static int
    883 getresponse(FETCH *fin, char **cp, size_t buflen, int *hcode)
    884 {
    885 	int len, rv;
    886 	char *ep, *buf = *cp;
    887 
    888 	*hcode = 0;
    889 	if ((rv = getresponseline(fin, buf, buflen, &len)) != C_OK)
    890 		return rv;
    891 
    892 	/* Determine HTTP response code */
    893 	*cp = strchr(buf, ' ');
    894 	if (*cp == NULL)
    895 		return C_IMPROPER;
    896 
    897 	(*cp)++;
    898 
    899 	*hcode = strtol(*cp, &ep, 10);
    900 	if (*ep != '\0' && !isspace((unsigned char)*ep))
    901 		return C_IMPROPER;
    902 
    903 	return C_OK;
    904 }
    905 
    906 static int
    907 parse_posinfo(const char **cp, struct posinfo *pi)
    908 {
    909 	char *ep;
    910 	if (!match_token(cp, "bytes"))
    911 		return -1;
    912 
    913 	if (**cp == '*')
    914 		(*cp)++;
    915 	else {
    916 		pi->rangestart = STRTOLL(*cp, &ep, 10);
    917 		if (pi->rangestart < 0 || *ep != '-')
    918 			return -1;
    919 		*cp = ep + 1;
    920 		pi->rangeend = STRTOLL(*cp, &ep, 10);
    921 		if (pi->rangeend < 0 || pi->rangeend < pi->rangestart)
    922 			return -1;
    923 		*cp = ep;
    924 	}
    925 	if (**cp != '/')
    926 		return -1;
    927 	(*cp)++;
    928 	if (**cp == '*')
    929 		(*cp)++;
    930 	else {
    931 		pi->entitylen = STRTOLL(*cp, &ep, 10);
    932 		if (pi->entitylen < 0)
    933 			return -1;
    934 		*cp = ep;
    935 	}
    936 	if (**cp != '\0')
    937 		return -1;
    938 
    939 #ifndef NO_DEBUG
    940 	if (ftp_debug) {
    941 		fprintf(ttyout, "parsed range as: ");
    942 		if (pi->rangestart == -1)
    943 			fprintf(ttyout, "*");
    944 		else
    945 			fprintf(ttyout, LLF "-" LLF, (LLT)pi->rangestart,
    946 			    (LLT)pi->rangeend);
    947 		fprintf(ttyout, "/" LLF "\n", (LLT)pi->entitylen);
    948 	}
    949 #endif
    950 	return 0;
    951 }
    952 
    953 static int
    954 negotiate_connection(FETCH *fin, const char *url, const char *penv,
    955     struct posinfo *pi, time_t *mtime, struct authinfo *wauth,
    956     struct authinfo *pauth, volatile int *rval, volatile int *ischunked,
    957     char **auth)
    958 {
    959 	int			len, hcode, rv;
    960 	char			buf[FTPBUFLEN], *ep;
    961 	const char		*cp, *token;
    962 	char 			*location, *message;
    963 
    964 	*auth = message = location = NULL;
    965 
    966 	/* Read the response */
    967 	ep = buf;
    968 	switch (getresponse(fin, &ep, sizeof(buf), &hcode)) {
    969 	case C_CLEANUP:
    970 		goto cleanup_fetch_url;
    971 	case C_IMPROPER:
    972 		goto improper;
    973 	case C_OK:
    974 		message = ftp_strdup(ep);
    975 		break;
    976 	}
    977 
    978 	/* Read the rest of the header. */
    979 
    980 	for (;;) {
    981 		if ((rv = getresponseline(fin, buf, sizeof(buf), &len)) != C_OK)
    982 			goto cleanup_fetch_url;
    983 		if (len == 0)
    984 			break;
    985 
    986 	/*
    987 	 * Look for some headers
    988 	 */
    989 
    990 		cp = buf;
    991 
    992 		if (match_token(&cp, "Content-Length:")) {
    993 			filesize = STRTOLL(cp, &ep, 10);
    994 			if (filesize < 0 || *ep != '\0')
    995 				goto improper;
    996 			DPRINTF("%s: parsed len as: " LLF "\n",
    997 			    __func__, (LLT)filesize);
    998 
    999 		} else if (match_token(&cp, "Content-Range:")) {
   1000 			if (parse_posinfo(&cp, pi) == -1)
   1001 				goto improper;
   1002 			if (! restart_point) {
   1003 				warnx(
   1004 			    "Received unexpected Content-Range header");
   1005 				goto cleanup_fetch_url;
   1006 			}
   1007 
   1008 		} else if (match_token(&cp, "Last-Modified:")) {
   1009 			getmtime(cp, mtime);
   1010 
   1011 		} else if (match_token(&cp, "Location:")) {
   1012 			location = ftp_strdup(cp);
   1013 			DPRINTF("%s: parsed location as `%s'\n",
   1014 			    __func__, cp);
   1015 
   1016 		} else if (match_token(&cp, "Transfer-Encoding:")) {
   1017 			if (match_token(&cp, "binary")) {
   1018 				warnx(
   1019 		"Bogus transfer encoding `binary' (fetching anyway)");
   1020 				continue;
   1021 			}
   1022 			if (! (token = match_token(&cp, "chunked"))) {
   1023 				warnx(
   1024 			    "Unsupported transfer encoding `%s'",
   1025 				    token);
   1026 				goto cleanup_fetch_url;
   1027 			}
   1028 			(*ischunked)++;
   1029 			DPRINTF("%s: using chunked encoding\n",
   1030 			    __func__);
   1031 
   1032 		} else if (match_token(&cp, "Proxy-Authenticate:")
   1033 			|| match_token(&cp, "WWW-Authenticate:")) {
   1034 			if (! (token = match_token(&cp, "Basic"))) {
   1035 				DPRINTF("%s: skipping unknown auth "
   1036 				    "scheme `%s'\n", __func__, token);
   1037 				continue;
   1038 			}
   1039 			FREEPTR(*auth);
   1040 			*auth = ftp_strdup(token);
   1041 			DPRINTF("%s: parsed auth as `%s'\n",
   1042 			    __func__, cp);
   1043 		}
   1044 
   1045 	}
   1046 			/* finished parsing header */
   1047 
   1048 	switch (hcode) {
   1049 	case 200:
   1050 		break;
   1051 	case 206:
   1052 		if (! restart_point) {
   1053 			warnx("Not expecting partial content header");
   1054 			goto cleanup_fetch_url;
   1055 		}
   1056 		break;
   1057 	case 300:
   1058 	case 301:
   1059 	case 302:
   1060 	case 303:
   1061 	case 305:
   1062 	case 307:
   1063 		if (EMPTYSTRING(location)) {
   1064 			warnx(
   1065 			"No redirection Location provided by server");
   1066 			goto cleanup_fetch_url;
   1067 		}
   1068 		if (redirect_loop++ > 5) {
   1069 			warnx("Too many redirections requested");
   1070 			goto cleanup_fetch_url;
   1071 		}
   1072 		if (hcode == 305) {
   1073 			if (verbose)
   1074 				fprintf(ttyout, "Redirected via %s\n",
   1075 				    location);
   1076 			*rval = fetch_url(url, location,
   1077 			    pauth->auth, wauth->auth);
   1078 		} else {
   1079 			if (verbose)
   1080 				fprintf(ttyout, "Redirected to %s\n",
   1081 				    location);
   1082 			*rval = go_fetch(location);
   1083 		}
   1084 		goto cleanup_fetch_url;
   1085 #ifndef NO_AUTH
   1086 	case 401:
   1087 	case 407:
   1088 	    {
   1089 		struct authinfo aauth;
   1090 		char **authp;
   1091 
   1092 		if (hcode == 401)
   1093 			aauth = *wauth;
   1094 		else
   1095 			aauth = *pauth;
   1096 
   1097 		if (verbose || aauth.auth == NULL ||
   1098 		    aauth.user == NULL || aauth.pass == NULL)
   1099 			fprintf(ttyout, "%s\n", message);
   1100 		if (EMPTYSTRING(*auth)) {
   1101 			warnx(
   1102 		    "No authentication challenge provided by server");
   1103 			goto cleanup_fetch_url;
   1104 		}
   1105 
   1106 		if (aauth.auth != NULL) {
   1107 			char reply[10];
   1108 
   1109 			fprintf(ttyout,
   1110 			    "Authorization failed. Retry (y/n)? ");
   1111 			if (get_line(stdin, reply, sizeof(reply), NULL)
   1112 			    < 0) {
   1113 				goto cleanup_fetch_url;
   1114 			}
   1115 			if (tolower((unsigned char)reply[0]) != 'y')
   1116 				goto cleanup_fetch_url;
   1117 			aauth.user = NULL;
   1118 			aauth.pass = NULL;
   1119 		}
   1120 
   1121 		authp = &aauth.auth;
   1122 		if (auth_url(*auth, authp, &aauth) == 0) {
   1123 			*rval = fetch_url(url, penv,
   1124 			    hcode == 401 ? pauth->auth : aauth.auth,
   1125 			    hcode == 401 ? aauth.auth : wauth->auth);
   1126 			memset(*authp, 0, strlen(*authp));
   1127 			FREEPTR(*authp);
   1128 		}
   1129 		goto cleanup_fetch_url;
   1130 	    }
   1131 #endif
   1132 	default:
   1133 		if (message)
   1134 			warnx("Error retrieving file `%s'", message);
   1135 		else
   1136 			warnx("Unknown error retrieving file");
   1137 		goto cleanup_fetch_url;
   1138 	}
   1139 	rv = C_OK;
   1140 	goto out;
   1141 
   1142 cleanup_fetch_url:
   1143 	rv = C_CLEANUP;
   1144 	goto out;
   1145 improper:
   1146 	rv = C_IMPROPER;
   1147 	goto out;
   1148 out:
   1149 	FREEPTR(message);
   1150 	FREEPTR(location);
   1151 	return rv;
   1152 }		/* end of ftp:// or http:// specific setup */
   1153 
   1154 #ifdef WITH_SSL
   1155 static int
   1156 connectmethod(int s, FETCH *fin, struct urlinfo *oui, struct urlinfo *ui,
   1157     struct authinfo *pauth, char **auth, int *hasleading)
   1158 {
   1159 	void *ssl;
   1160 	int hcode, rv;
   1161 	const char *cp;
   1162 	char buf[FTPBUFLEN], *ep;
   1163 	char *message = NULL;
   1164 
   1165 	print_connect(fin, oui);
   1166 
   1167 	print_agent(fin);
   1168 	*hasleading = print_proxy(fin, *hasleading, NULL, pauth->auth);
   1169 
   1170 	if (verbose && *hasleading)
   1171 		fputs(")\n", ttyout);
   1172 	*hasleading = 0;
   1173 
   1174 	fetch_printf(fin, "\r\n");
   1175 	if (fetch_flush(fin) == EOF) {
   1176 		warn("Writing HTTP request");
   1177 		alarmtimer(0);
   1178 		goto cleanup_fetch_url;
   1179 	}
   1180 	alarmtimer(0);
   1181 
   1182 	/* Read the response */
   1183 	ep = buf;
   1184 	switch (getresponse(fin, &ep, sizeof(buf), &hcode)) {
   1185 	case C_CLEANUP:
   1186 		goto cleanup_fetch_url;
   1187 	case C_IMPROPER:
   1188 		goto improper;
   1189 	case C_OK:
   1190 		message = ftp_strdup(ep);
   1191 		break;
   1192 	}
   1193 
   1194 	for (;;) {
   1195 		int len;
   1196 		if (getresponseline(fin, buf, sizeof(buf), &len) != C_OK)
   1197 			goto cleanup_fetch_url;
   1198 		if (len == 0)
   1199 			break;
   1200 
   1201 		cp = buf;
   1202 		if (match_token(&cp, "Proxy-Authenticate:")) {
   1203 			const char *token;
   1204 			if (!(token = match_token(&cp, "Basic"))) {
   1205 				DPRINTF(
   1206 				    "%s: skipping unknown auth scheme `%s'\n",
   1207 				    __func__, token);
   1208 				continue;
   1209 			}
   1210 			FREEPTR(*auth);
   1211 			*auth = ftp_strdup(token);
   1212 			DPRINTF("%s: parsed auth as " "`%s'\n", __func__, cp);
   1213 		}
   1214 	}
   1215 
   1216 	/* finished parsing header */
   1217 	switch (hcode) {
   1218 	case 200:
   1219 		break;
   1220 #ifndef NO_AUTH
   1221 	case 407:
   1222 		if (verbose || pauth->auth == NULL ||
   1223 		    pauth->user == NULL || pauth->pass == NULL)
   1224 			fprintf(ttyout, "%s\n", message);
   1225 		if (EMPTYSTRING(*auth)) {
   1226 			warnx("No authentication challenge provided by server");
   1227 			goto cleanup_fetch_url;
   1228 		}
   1229 
   1230 		if (pauth->auth != NULL) {
   1231 			char reply[10];
   1232 
   1233 			fprintf(ttyout, "Authorization failed. Retry (y/n)? ");
   1234 			if (get_line(stdin, reply, sizeof(reply), NULL)
   1235 			    < 0) {
   1236 				goto cleanup_fetch_url;
   1237 			}
   1238 			if (tolower((unsigned char)reply[0]) != 'y')
   1239 				goto cleanup_fetch_url;
   1240 			pauth->user = NULL;
   1241 			pauth->pass = NULL;
   1242 		}
   1243 
   1244 		if (auth_url(*auth, &pauth->auth, pauth) == 0)
   1245 			goto restart_fetch_url;
   1246 		goto cleanup_fetch_url;
   1247 #endif
   1248 	default:
   1249 		if (message)
   1250 			warnx("Error proxy connect " "`%s'", message);
   1251 		else
   1252 			warnx("Unknown error proxy " "connect");
   1253 		goto cleanup_fetch_url;
   1254 	}
   1255 
   1256 	if ((ssl = fetch_start_ssl(s, oui->host)) == NULL)
   1257 		goto cleanup_fetch_url;
   1258 	fetch_set_ssl(fin, ssl);
   1259 
   1260 	rv = C_OK;
   1261 	goto out;
   1262 improper:
   1263 	rv = C_IMPROPER;
   1264 	goto out;
   1265 cleanup_fetch_url:
   1266 	rv = C_CLEANUP;
   1267 	goto out;
   1268 restart_fetch_url:
   1269 	rv = C_RESTART;
   1270 	goto out;
   1271 out:
   1272 	FREEPTR(message);
   1273 	return rv;
   1274 }
   1275 #endif
   1276 
   1277 /*
   1278  * Retrieve URL, via a proxy if necessary, using HTTP.
   1279  * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
   1280  * http_proxy/https_proxy as appropriate.
   1281  * Supports HTTP redirects.
   1282  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
   1283  * is still open (e.g, ftp xfer with trailing /)
   1284  */
   1285 static int
   1286 fetch_url(const char *url, const char *proxyenv, char *proxyauth, char *wwwauth)
   1287 {
   1288 	sigfunc volatile	oldint;
   1289 	sigfunc volatile	oldpipe;
   1290 	sigfunc volatile	oldalrm;
   1291 	sigfunc volatile	oldquit;
   1292 	int volatile		s;
   1293 	struct stat		sb;
   1294 	int volatile		isproxy;
   1295 	int volatile 		rval, ischunked;
   1296 	size_t			flen;
   1297 	static size_t		bufsize;
   1298 	static char		*xferbuf;
   1299 	const char		*cp;
   1300 	char			*ep;
   1301 	char			*auth;
   1302 	char			*volatile savefile;
   1303 	char			*volatile location;
   1304 	char			*volatile message;
   1305 	char			*volatile decodedpath;
   1306 	struct authinfo 	wauth, pauth;
   1307 	struct posinfo		pi;
   1308 	off_t			hashbytes;
   1309 	int			(*volatile closefunc)(FILE *);
   1310 	FETCH			*volatile fin;
   1311 	FILE			*volatile fout;
   1312 	const char		*volatile penv = proxyenv;
   1313 	struct urlinfo		ui, oui;
   1314 	time_t			mtime;
   1315 	void			*ssl = NULL;
   1316 
   1317 	DPRINTF("%s: `%s' proxyenv `%s'\n", __func__, url, STRorNULL(penv));
   1318 
   1319 	oldquit = oldalrm = oldint = oldpipe = NULL;
   1320 	closefunc = NULL;
   1321 	fin = NULL;
   1322 	fout = NULL;
   1323 	s = -1;
   1324 	savefile = NULL;
   1325 	auth = location = message = NULL;
   1326 	ischunked = isproxy = 0;
   1327 	rval = 1;
   1328 
   1329 	initurlinfo(&ui);
   1330 	initurlinfo(&oui);
   1331 	initauthinfo(&wauth, wwwauth);
   1332 	initauthinfo(&pauth, proxyauth);
   1333 
   1334 	decodedpath = NULL;
   1335 
   1336 	if (sigsetjmp(httpabort, 1))
   1337 		goto cleanup_fetch_url;
   1338 
   1339 	if (parse_url(url, "URL", &ui, &wauth) == -1)
   1340 		goto cleanup_fetch_url;
   1341 
   1342 	copyurlinfo(&oui, &ui);
   1343 
   1344 	if (ui.utype == FILE_URL_T && ! EMPTYSTRING(ui.host)
   1345 	    && strcasecmp(ui.host, "localhost") != 0) {
   1346 		warnx("No support for non local file URL `%s'", url);
   1347 		goto cleanup_fetch_url;
   1348 	}
   1349 
   1350 	if (EMPTYSTRING(ui.path)) {
   1351 		if (ui.utype == FTP_URL_T) {
   1352 			rval = fetch_ftp(url);
   1353 			goto cleanup_fetch_url;
   1354 		}
   1355 		if (!IS_HTTP_TYPE(ui.utype) || outfile == NULL)  {
   1356 			warnx("Invalid URL (no file after host) `%s'", url);
   1357 			goto cleanup_fetch_url;
   1358 		}
   1359 	}
   1360 
   1361 	decodedpath = ftp_strdup(ui.path);
   1362 	url_decode(decodedpath);
   1363 
   1364 	if (outfile)
   1365 		savefile = outfile;
   1366 	else {
   1367 		cp = strrchr(decodedpath, '/');		/* find savefile */
   1368 		if (cp != NULL)
   1369 			savefile = ftp_strdup(cp + 1);
   1370 		else
   1371 			savefile = ftp_strdup(decodedpath);
   1372 		/*
   1373 		 * Use the first URL we requested not the name after a
   1374 		 * possible redirect, but careful to save it because our
   1375 		 * "safety" check is the match to outfile.
   1376 		 */
   1377 		outfile = ftp_strdup(savefile);
   1378 	}
   1379 	DPRINTF("%s: savefile `%s'\n", __func__, savefile);
   1380 	if (EMPTYSTRING(savefile)) {
   1381 		if (ui.utype == FTP_URL_T) {
   1382 			rval = fetch_ftp(url);
   1383 			goto cleanup_fetch_url;
   1384 		}
   1385 		warnx("No file after directory (you must specify an "
   1386 		    "output file) `%s'", url);
   1387 		goto cleanup_fetch_url;
   1388 	}
   1389 
   1390 	restart_point = 0;
   1391 	filesize = -1;
   1392 	initposinfo(&pi);
   1393 	mtime = -1;
   1394 	if (restartautofetch) {
   1395 		if (stat(savefile, &sb) == 0)
   1396 			restart_point = sb.st_size;
   1397 	}
   1398 	if (ui.utype == FILE_URL_T) {		/* file:// URLs */
   1399 		direction = "copied";
   1400 		fin = fetch_open(decodedpath, "r");
   1401 		if (fin == NULL) {
   1402 			warn("Can't open `%s'", decodedpath);
   1403 			goto cleanup_fetch_url;
   1404 		}
   1405 		if (fstat(fetch_fileno(fin), &sb) == 0) {
   1406 			mtime = sb.st_mtime;
   1407 			filesize = sb.st_size;
   1408 		}
   1409 		if (restart_point) {
   1410 			if (lseek(fetch_fileno(fin), restart_point, SEEK_SET) < 0) {
   1411 				warn("Can't seek to restart `%s'",
   1412 				    decodedpath);
   1413 				goto cleanup_fetch_url;
   1414 			}
   1415 		}
   1416 		if (verbose) {
   1417 			fprintf(ttyout, "Copying %s", decodedpath);
   1418 			if (restart_point)
   1419 				fprintf(ttyout, " (restarting at " LLF ")",
   1420 				    (LLT)restart_point);
   1421 			fputs("\n", ttyout);
   1422 		}
   1423 		if (0 == rcvbuf_size) {
   1424 			rcvbuf_size = 8 * 1024; /* XXX */
   1425 		}
   1426 	} else {				/* ftp:// or http:// URLs */
   1427 		int hasleading;
   1428 
   1429 		if (penv == NULL) {
   1430 #ifdef WITH_SSL
   1431 			if (ui.utype == HTTPS_URL_T)
   1432 				penv = getoptionvalue("https_proxy");
   1433 #endif
   1434 			if (penv == NULL && IS_HTTP_TYPE(ui.utype))
   1435 				penv = getoptionvalue("http_proxy");
   1436 			else if (ui.utype == FTP_URL_T)
   1437 				penv = getoptionvalue("ftp_proxy");
   1438 		}
   1439 		direction = "retrieved";
   1440 		if (! EMPTYSTRING(penv)) {			/* use proxy */
   1441 
   1442 			isproxy = handle_noproxy(ui.host, ui.portnum);
   1443 
   1444 			if (isproxy == 0 && ui.utype == FTP_URL_T) {
   1445 				rval = fetch_ftp(url);
   1446 				goto cleanup_fetch_url;
   1447 			}
   1448 
   1449 			if (isproxy) {
   1450 				if (restart_point) {
   1451 					warnx(
   1452 					    "Can't restart via proxy URL `%s'",
   1453 					    penv);
   1454 					goto cleanup_fetch_url;
   1455 				}
   1456 				if (handle_proxy(url, penv, &ui, &pauth) < 0)
   1457 					goto cleanup_fetch_url;
   1458 			}
   1459 		} /* ! EMPTYSTRING(penv) */
   1460 
   1461 		s = ftp_socket(&ui, &ssl);
   1462 		if (s < 0) {
   1463 			warnx("Can't connect to `%s:%s'", ui.host, ui.port);
   1464 			goto cleanup_fetch_url;
   1465 		}
   1466 
   1467 		oldalrm = xsignal(SIGALRM, timeouthttp);
   1468 		alarmtimer(quit_time ? quit_time : 60);
   1469 		fin = fetch_fdopen(s, "r+");
   1470 		fetch_set_ssl(fin, ssl);
   1471 		alarmtimer(0);
   1472 
   1473 		alarmtimer(quit_time ? quit_time : 60);
   1474 		/*
   1475 		 * Construct and send the request.
   1476 		 */
   1477 		if (verbose)
   1478 			fprintf(ttyout, "Requesting %s\n", url);
   1479 
   1480 		hasleading = 0;
   1481 #ifdef WITH_SSL
   1482 		if (isproxy && oui.utype == HTTPS_URL_T) {
   1483 			switch (connectmethod(s, fin, &oui, &ui, &pauth, &auth,
   1484 			    &hasleading)) {
   1485 			case C_RESTART:
   1486 				rval = fetch_url(url, penv, pauth.auth,
   1487 				    wauth.auth);
   1488 				/*FALLTHROUGH*/
   1489 			case C_CLEANUP:
   1490 				goto cleanup_fetch_url;
   1491 			case C_IMPROPER:
   1492 				goto improper;
   1493 			case C_OK:
   1494 				break;
   1495 			default:
   1496 				abort();
   1497 			}
   1498 		}
   1499 #endif
   1500 
   1501 		hasleading = print_get(fin, hasleading, isproxy, &oui, &ui);
   1502 
   1503 		if (flushcache)
   1504 			print_cache(fin, isproxy);
   1505 
   1506 		print_agent(fin);
   1507 		hasleading = print_proxy(fin, hasleading, wauth.auth,
   1508 		     auth ? NULL : pauth.auth);
   1509 		if (hasleading) {
   1510 			hasleading = 0;
   1511 			if (verbose)
   1512 				fputs(")\n", ttyout);
   1513 		}
   1514 
   1515 		fetch_printf(fin, "\r\n");
   1516 		if (fetch_flush(fin) == EOF) {
   1517 			warn("Writing HTTP request");
   1518 			alarmtimer(0);
   1519 			goto cleanup_fetch_url;
   1520 		}
   1521 		alarmtimer(0);
   1522 
   1523 		switch (negotiate_connection(fin, url, penv, &pi,
   1524 		    &mtime, &wauth, &pauth, &rval, &ischunked, &auth)) {
   1525 		case C_OK:
   1526 			break;
   1527 		case C_CLEANUP:
   1528 			goto cleanup_fetch_url;
   1529 		case C_IMPROPER:
   1530 			goto improper;
   1531 		default:
   1532 			abort();
   1533 		}
   1534 	}
   1535 
   1536 	/* Open the output file. */
   1537 
   1538 	/*
   1539 	 * Only trust filenames with special meaning if they came from
   1540 	 * the command line
   1541 	 */
   1542 	if (outfile == savefile) {
   1543 		if (strcmp(savefile, "-") == 0) {
   1544 			fout = stdout;
   1545 		} else if (*savefile == '|') {
   1546 			oldpipe = xsignal(SIGPIPE, SIG_IGN);
   1547 			fout = popen(savefile + 1, "w");
   1548 			if (fout == NULL) {
   1549 				warn("Can't execute `%s'", savefile + 1);
   1550 				goto cleanup_fetch_url;
   1551 			}
   1552 			closefunc = pclose;
   1553 		}
   1554 	}
   1555 	if (fout == NULL) {
   1556 		if ((pi.rangeend != -1 && pi.rangeend <= restart_point) ||
   1557 		    (pi.rangestart == -1 &&
   1558 		    filesize != -1 && filesize <= restart_point)) {
   1559 			/* already done */
   1560 			if (verbose)
   1561 				fprintf(ttyout, "already done\n");
   1562 			rval = 0;
   1563 			goto cleanup_fetch_url;
   1564 		}
   1565 		if (restart_point && pi.rangestart != -1) {
   1566 			if (pi.entitylen != -1)
   1567 				filesize = pi.entitylen;
   1568 			if (pi.rangestart != restart_point) {
   1569 				warnx(
   1570 				    "Size of `%s' differs from save file `%s'",
   1571 				    url, savefile);
   1572 				goto cleanup_fetch_url;
   1573 			}
   1574 			fout = fopen(savefile, "a");
   1575 		} else
   1576 			fout = fopen(savefile, "w");
   1577 		if (fout == NULL) {
   1578 			warn("Can't open `%s'", savefile);
   1579 			goto cleanup_fetch_url;
   1580 		}
   1581 		closefunc = fclose;
   1582 	}
   1583 
   1584 			/* Trap signals */
   1585 	oldquit = xsignal(SIGQUIT, psummary);
   1586 	oldint = xsignal(SIGINT, aborthttp);
   1587 
   1588 	assert(rcvbuf_size > 0);
   1589 	if ((size_t)rcvbuf_size > bufsize) {
   1590 		if (xferbuf)
   1591 			(void)free(xferbuf);
   1592 		bufsize = rcvbuf_size;
   1593 		xferbuf = ftp_malloc(bufsize);
   1594 	}
   1595 
   1596 	bytes = 0;
   1597 	hashbytes = mark;
   1598 	if (oldalrm) {
   1599 		(void)xsignal(SIGALRM, oldalrm);
   1600 		oldalrm = NULL;
   1601 	}
   1602 	progressmeter(-1);
   1603 
   1604 			/* Finally, suck down the file. */
   1605 	do {
   1606 		long chunksize;
   1607 		short lastchunk;
   1608 
   1609 		chunksize = 0;
   1610 		lastchunk = 0;
   1611 					/* read chunk-size */
   1612 		if (ischunked) {
   1613 			if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
   1614 				warnx("Unexpected EOF reading chunk-size");
   1615 				goto cleanup_fetch_url;
   1616 			}
   1617 			errno = 0;
   1618 			chunksize = strtol(xferbuf, &ep, 16);
   1619 			if (ep == xferbuf) {
   1620 				warnx("Invalid chunk-size");
   1621 				goto cleanup_fetch_url;
   1622 			}
   1623 			if (errno == ERANGE || chunksize < 0) {
   1624 				errno = ERANGE;
   1625 				warn("Chunk-size `%.*s'",
   1626 				    (int)(ep-xferbuf), xferbuf);
   1627 				goto cleanup_fetch_url;
   1628 			}
   1629 
   1630 				/*
   1631 				 * XXX:	Work around bug in Apache 1.3.9 and
   1632 				 *	1.3.11, which incorrectly put trailing
   1633 				 *	space after the chunk-size.
   1634 				 */
   1635 			while (*ep == ' ')
   1636 				ep++;
   1637 
   1638 					/* skip [ chunk-ext ] */
   1639 			if (*ep == ';') {
   1640 				while (*ep && *ep != '\r')
   1641 					ep++;
   1642 			}
   1643 
   1644 			if (strcmp(ep, "\r\n") != 0) {
   1645 				warnx("Unexpected data following chunk-size");
   1646 				goto cleanup_fetch_url;
   1647 			}
   1648 			DPRINTF("%s: got chunk-size of " LLF "\n", __func__,
   1649 			    (LLT)chunksize);
   1650 			if (chunksize == 0) {
   1651 				lastchunk = 1;
   1652 				goto chunkdone;
   1653 			}
   1654 		}
   1655 					/* transfer file or chunk */
   1656 		while (1) {
   1657 			struct timeval then, now, td;
   1658 			volatile off_t bufrem;
   1659 
   1660 			if (rate_get)
   1661 				(void)gettimeofday(&then, NULL);
   1662 			bufrem = rate_get ? rate_get : (off_t)bufsize;
   1663 			if (ischunked)
   1664 				bufrem = MIN(chunksize, bufrem);
   1665 			while (bufrem > 0) {
   1666 				flen = fetch_read(xferbuf, sizeof(char),
   1667 				    MIN((off_t)bufsize, bufrem), fin);
   1668 				if (flen <= 0)
   1669 					goto chunkdone;
   1670 				bytes += flen;
   1671 				bufrem -= flen;
   1672 				if (fwrite(xferbuf, sizeof(char), flen, fout)
   1673 				    != flen) {
   1674 					warn("Writing `%s'", savefile);
   1675 					goto cleanup_fetch_url;
   1676 				}
   1677 				if (hash && !progress) {
   1678 					while (bytes >= hashbytes) {
   1679 						(void)putc('#', ttyout);
   1680 						hashbytes += mark;
   1681 					}
   1682 					(void)fflush(ttyout);
   1683 				}
   1684 				if (ischunked) {
   1685 					chunksize -= flen;
   1686 					if (chunksize <= 0)
   1687 						break;
   1688 				}
   1689 			}
   1690 			if (rate_get) {
   1691 				while (1) {
   1692 					(void)gettimeofday(&now, NULL);
   1693 					timersub(&now, &then, &td);
   1694 					if (td.tv_sec > 0)
   1695 						break;
   1696 					usleep(1000000 - td.tv_usec);
   1697 				}
   1698 			}
   1699 			if (ischunked && chunksize <= 0)
   1700 				break;
   1701 		}
   1702 					/* read CRLF after chunk*/
   1703  chunkdone:
   1704 		if (ischunked) {
   1705 			if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
   1706 				alarmtimer(0);
   1707 				warnx("Unexpected EOF reading chunk CRLF");
   1708 				goto cleanup_fetch_url;
   1709 			}
   1710 			if (strcmp(xferbuf, "\r\n") != 0) {
   1711 				warnx("Unexpected data following chunk");
   1712 				goto cleanup_fetch_url;
   1713 			}
   1714 			if (lastchunk)
   1715 				break;
   1716 		}
   1717 	} while (ischunked);
   1718 
   1719 /* XXX: deal with optional trailer & CRLF here? */
   1720 
   1721 	if (hash && !progress && bytes > 0) {
   1722 		if (bytes < mark)
   1723 			(void)putc('#', ttyout);
   1724 		(void)putc('\n', ttyout);
   1725 	}
   1726 	if (fetch_error(fin)) {
   1727 		warn("Reading file");
   1728 		goto cleanup_fetch_url;
   1729 	}
   1730 	progressmeter(1);
   1731 	(void)fflush(fout);
   1732 	if (closefunc == fclose && mtime != -1) {
   1733 		struct timeval tval[2];
   1734 
   1735 		(void)gettimeofday(&tval[0], NULL);
   1736 		tval[1].tv_sec = mtime;
   1737 		tval[1].tv_usec = 0;
   1738 		(*closefunc)(fout);
   1739 		fout = NULL;
   1740 
   1741 		if (utimes(savefile, tval) == -1) {
   1742 			fprintf(ttyout,
   1743 			    "Can't change modification time to %s",
   1744 			    rfc2822time(localtime(&mtime)));
   1745 		}
   1746 	}
   1747 	if (bytes > 0)
   1748 		ptransfer(0);
   1749 	bytes = 0;
   1750 
   1751 	rval = 0;
   1752 	goto cleanup_fetch_url;
   1753 
   1754  improper:
   1755 	warnx("Improper response from `%s:%s'", ui.host, ui.port);
   1756 
   1757  cleanup_fetch_url:
   1758 	if (oldint)
   1759 		(void)xsignal(SIGINT, oldint);
   1760 	if (oldpipe)
   1761 		(void)xsignal(SIGPIPE, oldpipe);
   1762 	if (oldalrm)
   1763 		(void)xsignal(SIGALRM, oldalrm);
   1764 	if (oldquit)
   1765 		(void)xsignal(SIGQUIT, oldpipe);
   1766 	if (fin != NULL)
   1767 		fetch_close(fin);
   1768 	else if (s != -1)
   1769 		close(s);
   1770 	if (closefunc != NULL && fout != NULL)
   1771 		(*closefunc)(fout);
   1772 	if (savefile != outfile)
   1773 		FREEPTR(savefile);
   1774 	freeurlinfo(&ui);
   1775 	freeurlinfo(&oui);
   1776 	freeauthinfo(&wauth);
   1777 	freeauthinfo(&pauth);
   1778 	FREEPTR(decodedpath);
   1779 	FREEPTR(auth);
   1780 	FREEPTR(location);
   1781 	FREEPTR(message);
   1782 	return (rval);
   1783 }
   1784 
   1785 /*
   1786  * Abort a HTTP retrieval
   1787  */
   1788 static void
   1789 aborthttp(int notused)
   1790 {
   1791 	char msgbuf[100];
   1792 	int len;
   1793 
   1794 	sigint_raised = 1;
   1795 	alarmtimer(0);
   1796 	if (fromatty) {
   1797 		len = snprintf(msgbuf, sizeof(msgbuf),
   1798 		    "\n%s: HTTP fetch aborted.\n", getprogname());
   1799 		if (len > 0)
   1800 			write(fileno(ttyout), msgbuf, len);
   1801 	}
   1802 	siglongjmp(httpabort, 1);
   1803 }
   1804 
   1805 static void
   1806 timeouthttp(int notused)
   1807 {
   1808 	char msgbuf[100];
   1809 	int len;
   1810 
   1811 	alarmtimer(0);
   1812 	if (fromatty) {
   1813 		len = snprintf(msgbuf, sizeof(msgbuf),
   1814 		    "\n%s: HTTP fetch timeout.\n", getprogname());
   1815 		if (len > 0)
   1816 			write(fileno(ttyout), msgbuf, len);
   1817 	}
   1818 	siglongjmp(httpabort, 1);
   1819 }
   1820 
   1821 /*
   1822  * Retrieve ftp URL or classic ftp argument using FTP.
   1823  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
   1824  * is still open (e.g, ftp xfer with trailing /)
   1825  */
   1826 static int
   1827 fetch_ftp(const char *url)
   1828 {
   1829 	char		*cp, *xargv[5], rempath[MAXPATHLEN];
   1830 	char		*dir, *file;
   1831 	char		 cmdbuf[MAXPATHLEN];
   1832 	char		 dirbuf[4];
   1833 	int		 dirhasglob, filehasglob, rval, transtype, xargc;
   1834 	int		 oanonftp, oautologin;
   1835 	struct authinfo  auth;
   1836 	struct urlinfo	 ui;
   1837 
   1838 	DPRINTF("fetch_ftp: `%s'\n", url);
   1839 	dir = file = NULL;
   1840 	rval = 1;
   1841 	transtype = TYPE_I;
   1842 
   1843 	initurlinfo(&ui);
   1844 	initauthinfo(&auth, NULL);
   1845 
   1846 	if (STRNEQUAL(url, FTP_URL)) {
   1847 		if ((parse_url(url, "URL", &ui, &auth) == -1) ||
   1848 		    (auth.user != NULL && *auth.user == '\0') ||
   1849 		    EMPTYSTRING(ui.host)) {
   1850 			warnx("Invalid URL `%s'", url);
   1851 			goto cleanup_fetch_ftp;
   1852 		}
   1853 		/*
   1854 		 * Note: Don't url_decode(path) here.  We need to keep the
   1855 		 * distinction between "/" and "%2F" until later.
   1856 		 */
   1857 
   1858 					/* check for trailing ';type=[aid]' */
   1859 		if (! EMPTYSTRING(ui.path) && (cp = strrchr(ui.path, ';')) != NULL) {
   1860 			if (strcasecmp(cp, ";type=a") == 0)
   1861 				transtype = TYPE_A;
   1862 			else if (strcasecmp(cp, ";type=i") == 0)
   1863 				transtype = TYPE_I;
   1864 			else if (strcasecmp(cp, ";type=d") == 0) {
   1865 				warnx(
   1866 			    "Directory listing via a URL is not supported");
   1867 				goto cleanup_fetch_ftp;
   1868 			} else {
   1869 				warnx("Invalid suffix `%s' in URL `%s'", cp,
   1870 				    url);
   1871 				goto cleanup_fetch_ftp;
   1872 			}
   1873 			*cp = 0;
   1874 		}
   1875 	} else {			/* classic style `[user@]host:[file]' */
   1876 		ui.utype = CLASSIC_URL_T;
   1877 		ui.host = ftp_strdup(url);
   1878 		cp = strchr(ui.host, '@');
   1879 		if (cp != NULL) {
   1880 			*cp = '\0';
   1881 			auth.user = ui.host;
   1882 			anonftp = 0;	/* disable anonftp */
   1883 			ui.host = ftp_strdup(cp + 1);
   1884 		}
   1885 		cp = strchr(ui.host, ':');
   1886 		if (cp != NULL) {
   1887 			*cp = '\0';
   1888 			ui.path = ftp_strdup(cp + 1);
   1889 		}
   1890 	}
   1891 	if (EMPTYSTRING(ui.host))
   1892 		goto cleanup_fetch_ftp;
   1893 
   1894 			/* Extract the file and (if present) directory name. */
   1895 	dir = ui.path;
   1896 	if (! EMPTYSTRING(dir)) {
   1897 		/*
   1898 		 * If we are dealing with classic `[user@]host:[path]' syntax,
   1899 		 * then a path of the form `/file' (resulting from input of the
   1900 		 * form `host:/file') means that we should do "CWD /" before
   1901 		 * retrieving the file.  So we set dir="/" and file="file".
   1902 		 *
   1903 		 * But if we are dealing with URLs like `ftp://host/path' then
   1904 		 * a path of the form `/file' (resulting from a URL of the form
   1905 		 * `ftp://host//file') means that we should do `CWD ' (with an
   1906 		 * empty argument) before retrieving the file.  So we set
   1907 		 * dir="" and file="file".
   1908 		 *
   1909 		 * If the path does not contain / at all, we set dir=NULL.
   1910 		 * (We get a path without any slashes if we are dealing with
   1911 		 * classic `[user@]host:[file]' or URL `ftp://host/file'.)
   1912 		 *
   1913 		 * In all other cases, we set dir to a string that does not
   1914 		 * include the final '/' that separates the dir part from the
   1915 		 * file part of the path.  (This will be the empty string if
   1916 		 * and only if we are dealing with a path of the form `/file'
   1917 		 * resulting from an URL of the form `ftp://host//file'.)
   1918 		 */
   1919 		cp = strrchr(dir, '/');
   1920 		if (cp == dir && ui.utype == CLASSIC_URL_T) {
   1921 			file = cp + 1;
   1922 			(void)strlcpy(dirbuf, "/", sizeof(dirbuf));
   1923 			dir = dirbuf;
   1924 		} else if (cp != NULL) {
   1925 			*cp++ = '\0';
   1926 			file = cp;
   1927 		} else {
   1928 			file = dir;
   1929 			dir = NULL;
   1930 		}
   1931 	} else
   1932 		dir = NULL;
   1933 	if (ui.utype == FTP_URL_T && file != NULL) {
   1934 		url_decode(file);
   1935 		/* but still don't url_decode(dir) */
   1936 	}
   1937 	DPRINTF("fetch_ftp: user `%s' pass `%s' host %s port %s "
   1938 	    "path `%s' dir `%s' file `%s'\n",
   1939 	    STRorNULL(auth.user), STRorNULL(auth.pass),
   1940 	    STRorNULL(ui.host), STRorNULL(ui.port),
   1941 	    STRorNULL(ui.path), STRorNULL(dir), STRorNULL(file));
   1942 
   1943 	dirhasglob = filehasglob = 0;
   1944 	if (doglob &&
   1945 	    (ui.utype == CLASSIC_URL_T || ui.utype == FTP_URL_T)) {
   1946 		if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
   1947 			dirhasglob = 1;
   1948 		if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
   1949 			filehasglob = 1;
   1950 	}
   1951 
   1952 			/* Set up the connection */
   1953 	oanonftp = anonftp;
   1954 	if (connected)
   1955 		disconnect(0, NULL);
   1956 	anonftp = oanonftp;
   1957 	(void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
   1958 	xargv[0] = cmdbuf;
   1959 	xargv[1] = ui.host;
   1960 	xargv[2] = NULL;
   1961 	xargc = 2;
   1962 	if (ui.port) {
   1963 		xargv[2] = ui.port;
   1964 		xargv[3] = NULL;
   1965 		xargc = 3;
   1966 	}
   1967 	oautologin = autologin;
   1968 		/* don't autologin in setpeer(), use ftp_login() below */
   1969 	autologin = 0;
   1970 	setpeer(xargc, xargv);
   1971 	autologin = oautologin;
   1972 	if ((connected == 0) ||
   1973 	    (connected == 1 && !ftp_login(ui.host, auth.user, auth.pass))) {
   1974 		warnx("Can't connect or login to host `%s:%s'",
   1975 			ui.host, ui.port ? ui.port : "?");
   1976 		goto cleanup_fetch_ftp;
   1977 	}
   1978 
   1979 	switch (transtype) {
   1980 	case TYPE_A:
   1981 		setascii(1, xargv);
   1982 		break;
   1983 	case TYPE_I:
   1984 		setbinary(1, xargv);
   1985 		break;
   1986 	default:
   1987 		errx(1, "fetch_ftp: unknown transfer type %d", transtype);
   1988 	}
   1989 
   1990 		/*
   1991 		 * Change directories, if necessary.
   1992 		 *
   1993 		 * Note: don't use EMPTYSTRING(dir) below, because
   1994 		 * dir=="" means something different from dir==NULL.
   1995 		 */
   1996 	if (dir != NULL && !dirhasglob) {
   1997 		char *nextpart;
   1998 
   1999 		/*
   2000 		 * If we are dealing with a classic `[user@]host:[path]'
   2001 		 * (urltype is CLASSIC_URL_T) then we have a raw directory
   2002 		 * name (not encoded in any way) and we can change
   2003 		 * directories in one step.
   2004 		 *
   2005 		 * If we are dealing with an `ftp://host/path' URL
   2006 		 * (urltype is FTP_URL_T), then RFC 3986 says we need to
   2007 		 * send a separate CWD command for each unescaped "/"
   2008 		 * in the path, and we have to interpret %hex escaping
   2009 		 * *after* we find the slashes.  It's possible to get
   2010 		 * empty components here, (from multiple adjacent
   2011 		 * slashes in the path) and RFC 3986 says that we should
   2012 		 * still do `CWD ' (with a null argument) in such cases.
   2013 		 *
   2014 		 * Many ftp servers don't support `CWD ', so if there's an
   2015 		 * error performing that command, bail out with a descriptive
   2016 		 * message.
   2017 		 *
   2018 		 * Examples:
   2019 		 *
   2020 		 * host:			dir="", urltype=CLASSIC_URL_T
   2021 		 *		logged in (to default directory)
   2022 		 * host:file			dir=NULL, urltype=CLASSIC_URL_T
   2023 		 *		"RETR file"
   2024 		 * host:dir/			dir="dir", urltype=CLASSIC_URL_T
   2025 		 *		"CWD dir", logged in
   2026 		 * ftp://host/			dir="", urltype=FTP_URL_T
   2027 		 *		logged in (to default directory)
   2028 		 * ftp://host/dir/		dir="dir", urltype=FTP_URL_T
   2029 		 *		"CWD dir", logged in
   2030 		 * ftp://host/file		dir=NULL, urltype=FTP_URL_T
   2031 		 *		"RETR file"
   2032 		 * ftp://host//file		dir="", urltype=FTP_URL_T
   2033 		 *		"CWD ", "RETR file"
   2034 		 * host:/file			dir="/", urltype=CLASSIC_URL_T
   2035 		 *		"CWD /", "RETR file"
   2036 		 * ftp://host///file		dir="/", urltype=FTP_URL_T
   2037 		 *		"CWD ", "CWD ", "RETR file"
   2038 		 * ftp://host/%2F/file		dir="%2F", urltype=FTP_URL_T
   2039 		 *		"CWD /", "RETR file"
   2040 		 * ftp://host/foo/file		dir="foo", urltype=FTP_URL_T
   2041 		 *		"CWD foo", "RETR file"
   2042 		 * ftp://host/foo/bar/file	dir="foo/bar"
   2043 		 *		"CWD foo", "CWD bar", "RETR file"
   2044 		 * ftp://host//foo/bar/file	dir="/foo/bar"
   2045 		 *		"CWD ", "CWD foo", "CWD bar", "RETR file"
   2046 		 * ftp://host/foo//bar/file	dir="foo//bar"
   2047 		 *		"CWD foo", "CWD ", "CWD bar", "RETR file"
   2048 		 * ftp://host/%2F/foo/bar/file	dir="%2F/foo/bar"
   2049 		 *		"CWD /", "CWD foo", "CWD bar", "RETR file"
   2050 		 * ftp://host/%2Ffoo/bar/file	dir="%2Ffoo/bar"
   2051 		 *		"CWD /foo", "CWD bar", "RETR file"
   2052 		 * ftp://host/%2Ffoo%2Fbar/file	dir="%2Ffoo%2Fbar"
   2053 		 *		"CWD /foo/bar", "RETR file"
   2054 		 * ftp://host/%2Ffoo%2Fbar%2Ffile	dir=NULL
   2055 		 *		"RETR /foo/bar/file"
   2056 		 *
   2057 		 * Note that we don't need `dir' after this point.
   2058 		 */
   2059 		do {
   2060 			if (ui.utype == FTP_URL_T) {
   2061 				nextpart = strchr(dir, '/');
   2062 				if (nextpart) {
   2063 					*nextpart = '\0';
   2064 					nextpart++;
   2065 				}
   2066 				url_decode(dir);
   2067 			} else
   2068 				nextpart = NULL;
   2069 			DPRINTF("fetch_ftp: dir `%s', nextpart `%s'\n",
   2070 			    STRorNULL(dir), STRorNULL(nextpart));
   2071 			if (ui.utype == FTP_URL_T || *dir != '\0') {
   2072 				(void)strlcpy(cmdbuf, "cd", sizeof(cmdbuf));
   2073 				xargv[0] = cmdbuf;
   2074 				xargv[1] = dir;
   2075 				xargv[2] = NULL;
   2076 				dirchange = 0;
   2077 				cd(2, xargv);
   2078 				if (! dirchange) {
   2079 					if (*dir == '\0' && code == 500)
   2080 						fprintf(stderr,
   2081 "\n"
   2082 "ftp: The `CWD ' command (without a directory), which is required by\n"
   2083 "     RFC 3986 to support the empty directory in the URL pathname (`//'),\n"
   2084 "     conflicts with the server's conformance to RFC 959.\n"
   2085 "     Try the same URL without the `//' in the URL pathname.\n"
   2086 "\n");
   2087 					goto cleanup_fetch_ftp;
   2088 				}
   2089 			}
   2090 			dir = nextpart;
   2091 		} while (dir != NULL);
   2092 	}
   2093 
   2094 	if (EMPTYSTRING(file)) {
   2095 		rval = -1;
   2096 		goto cleanup_fetch_ftp;
   2097 	}
   2098 
   2099 	if (dirhasglob) {
   2100 		(void)strlcpy(rempath, dir,	sizeof(rempath));
   2101 		(void)strlcat(rempath, "/",	sizeof(rempath));
   2102 		(void)strlcat(rempath, file,	sizeof(rempath));
   2103 		file = rempath;
   2104 	}
   2105 
   2106 			/* Fetch the file(s). */
   2107 	xargc = 2;
   2108 	(void)strlcpy(cmdbuf, "get", sizeof(cmdbuf));
   2109 	xargv[0] = cmdbuf;
   2110 	xargv[1] = file;
   2111 	xargv[2] = NULL;
   2112 	if (dirhasglob || filehasglob) {
   2113 		int ointeractive;
   2114 
   2115 		ointeractive = interactive;
   2116 		interactive = 0;
   2117 		if (restartautofetch)
   2118 			(void)strlcpy(cmdbuf, "mreget", sizeof(cmdbuf));
   2119 		else
   2120 			(void)strlcpy(cmdbuf, "mget", sizeof(cmdbuf));
   2121 		xargv[0] = cmdbuf;
   2122 		mget(xargc, xargv);
   2123 		interactive = ointeractive;
   2124 	} else {
   2125 		if (outfile == NULL) {
   2126 			cp = strrchr(file, '/');	/* find savefile */
   2127 			if (cp != NULL)
   2128 				outfile = cp + 1;
   2129 			else
   2130 				outfile = file;
   2131 		}
   2132 		xargv[2] = (char *)outfile;
   2133 		xargv[3] = NULL;
   2134 		xargc++;
   2135 		if (restartautofetch)
   2136 			reget(xargc, xargv);
   2137 		else
   2138 			get(xargc, xargv);
   2139 	}
   2140 
   2141 	if ((code / 100) == COMPLETE)
   2142 		rval = 0;
   2143 
   2144  cleanup_fetch_ftp:
   2145 	freeurlinfo(&ui);
   2146 	freeauthinfo(&auth);
   2147 	return (rval);
   2148 }
   2149 
   2150 /*
   2151  * Retrieve the given file to outfile.
   2152  * Supports arguments of the form:
   2153  *	"host:path", "ftp://host/path"	if $ftpproxy, call fetch_url() else
   2154  *					call fetch_ftp()
   2155  *	"http://host/path"		call fetch_url() to use HTTP
   2156  *	"file:///path"			call fetch_url() to copy
   2157  *	"about:..."			print a message
   2158  *
   2159  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
   2160  * is still open (e.g, ftp xfer with trailing /)
   2161  */
   2162 static int
   2163 go_fetch(const char *url)
   2164 {
   2165 	char *proxyenv;
   2166 	char *p;
   2167 
   2168 #ifndef NO_ABOUT
   2169 	/*
   2170 	 * Check for about:*
   2171 	 */
   2172 	if (STRNEQUAL(url, ABOUT_URL)) {
   2173 		url += sizeof(ABOUT_URL) -1;
   2174 		if (strcasecmp(url, "ftp") == 0 ||
   2175 		    strcasecmp(url, "tnftp") == 0) {
   2176 			fputs(
   2177 "This version of ftp has been enhanced by Luke Mewburn <lukem (at) NetBSD.org>\n"
   2178 "for the NetBSD project.  Execute `man ftp' for more details.\n", ttyout);
   2179 		} else if (strcasecmp(url, "lukem") == 0) {
   2180 			fputs(
   2181 "Luke Mewburn is the author of most of the enhancements in this ftp client.\n"
   2182 "Please email feedback to <lukem (at) NetBSD.org>.\n", ttyout);
   2183 		} else if (strcasecmp(url, "netbsd") == 0) {
   2184 			fputs(
   2185 "NetBSD is a freely available and redistributable UNIX-like operating system.\n"
   2186 "For more information, see http://www.NetBSD.org/\n", ttyout);
   2187 		} else if (strcasecmp(url, "version") == 0) {
   2188 			fprintf(ttyout, "Version: %s %s%s\n",
   2189 			    FTP_PRODUCT, FTP_VERSION,
   2190 #ifdef INET6
   2191 			    ""
   2192 #else
   2193 			    " (-IPv6)"
   2194 #endif
   2195 			);
   2196 		} else {
   2197 			fprintf(ttyout, "`%s' is an interesting topic.\n", url);
   2198 		}
   2199 		fputs("\n", ttyout);
   2200 		return (0);
   2201 	}
   2202 #endif
   2203 
   2204 	/*
   2205 	 * Check for file:// and http:// URLs.
   2206 	 */
   2207 	if (STRNEQUAL(url, HTTP_URL)
   2208 #ifdef WITH_SSL
   2209 	    || STRNEQUAL(url, HTTPS_URL)
   2210 #endif
   2211 	    || STRNEQUAL(url, FILE_URL))
   2212 		return (fetch_url(url, NULL, NULL, NULL));
   2213 
   2214 	/*
   2215 	 * If it contains "://" but does not begin with ftp://
   2216 	 * or something that was already handled, then it's
   2217 	 * unsupported.
   2218 	 *
   2219 	 * If it contains ":" but not "://" then we assume the
   2220 	 * part before the colon is a host name, not an URL scheme,
   2221 	 * so we don't try to match that here.
   2222 	 */
   2223 	if ((p = strstr(url, "://")) != NULL && ! STRNEQUAL(url, FTP_URL))
   2224 		errx(1, "Unsupported URL scheme `%.*s'", (int)(p - url), url);
   2225 
   2226 	/*
   2227 	 * Try FTP URL-style and host:file arguments next.
   2228 	 * If ftpproxy is set with an FTP URL, use fetch_url()
   2229 	 * Othewise, use fetch_ftp().
   2230 	 */
   2231 	proxyenv = getoptionvalue("ftp_proxy");
   2232 	if (!EMPTYSTRING(proxyenv) && STRNEQUAL(url, FTP_URL))
   2233 		return (fetch_url(url, NULL, NULL, NULL));
   2234 
   2235 	return (fetch_ftp(url));
   2236 }
   2237 
   2238 /*
   2239  * Retrieve multiple files from the command line,
   2240  * calling go_fetch() for each file.
   2241  *
   2242  * If an ftp path has a trailing "/", the path will be cd-ed into and
   2243  * the connection remains open, and the function will return -1
   2244  * (to indicate the connection is alive).
   2245  * If an error occurs the return value will be the offset+1 in
   2246  * argv[] of the file that caused a problem (i.e, argv[x]
   2247  * returns x+1)
   2248  * Otherwise, 0 is returned if all files retrieved successfully.
   2249  */
   2250 int
   2251 auto_fetch(int argc, char *argv[])
   2252 {
   2253 	volatile int	argpos, rval;
   2254 
   2255 	argpos = rval = 0;
   2256 
   2257 	if (sigsetjmp(toplevel, 1)) {
   2258 		if (connected)
   2259 			disconnect(0, NULL);
   2260 		if (rval > 0)
   2261 			rval = argpos + 1;
   2262 		return (rval);
   2263 	}
   2264 	(void)xsignal(SIGINT, intr);
   2265 	(void)xsignal(SIGPIPE, lostpeer);
   2266 
   2267 	/*
   2268 	 * Loop through as long as there's files to fetch.
   2269 	 */
   2270 	for (; (rval == 0) && (argpos < argc); argpos++) {
   2271 		if (strchr(argv[argpos], ':') == NULL)
   2272 			break;
   2273 		redirect_loop = 0;
   2274 		if (!anonftp)
   2275 			anonftp = 2;	/* Handle "automatic" transfers. */
   2276 		rval = go_fetch(argv[argpos]);
   2277 		if (outfile != NULL && strcmp(outfile, "-") != 0
   2278 		    && outfile[0] != '|')
   2279 			outfile = NULL;
   2280 		if (rval > 0)
   2281 			rval = argpos + 1;
   2282 	}
   2283 
   2284 	if (connected && rval != -1)
   2285 		disconnect(0, NULL);
   2286 	return (rval);
   2287 }
   2288 
   2289 
   2290 /*
   2291  * Upload multiple files from the command line.
   2292  *
   2293  * If an error occurs the return value will be the offset+1 in
   2294  * argv[] of the file that caused a problem (i.e, argv[x]
   2295  * returns x+1)
   2296  * Otherwise, 0 is returned if all files uploaded successfully.
   2297  */
   2298 int
   2299 auto_put(int argc, char **argv, const char *uploadserver)
   2300 {
   2301 	char	*uargv[4], *path, *pathsep;
   2302 	int	 uargc, rval, argpos;
   2303 	size_t	 len;
   2304 	char	 cmdbuf[MAX_C_NAME];
   2305 
   2306 	(void)strlcpy(cmdbuf, "mput", sizeof(cmdbuf));
   2307 	uargv[0] = cmdbuf;
   2308 	uargv[1] = argv[0];
   2309 	uargc = 2;
   2310 	uargv[2] = uargv[3] = NULL;
   2311 	pathsep = NULL;
   2312 	rval = 1;
   2313 
   2314 	DPRINTF("auto_put: target `%s'\n", uploadserver);
   2315 
   2316 	path = ftp_strdup(uploadserver);
   2317 	len = strlen(path);
   2318 	if (path[len - 1] != '/' && path[len - 1] != ':') {
   2319 			/*
   2320 			 * make sure we always pass a directory to auto_fetch
   2321 			 */
   2322 		if (argc > 1) {		/* more than one file to upload */
   2323 			len = strlen(uploadserver) + 2;	/* path + "/" + "\0" */
   2324 			free(path);
   2325 			path = (char *)ftp_malloc(len);
   2326 			(void)strlcpy(path, uploadserver, len);
   2327 			(void)strlcat(path, "/", len);
   2328 		} else {		/* single file to upload */
   2329 			(void)strlcpy(cmdbuf, "put", sizeof(cmdbuf));
   2330 			uargv[0] = cmdbuf;
   2331 			pathsep = strrchr(path, '/');
   2332 			if (pathsep == NULL) {
   2333 				pathsep = strrchr(path, ':');
   2334 				if (pathsep == NULL) {
   2335 					warnx("Invalid URL `%s'", path);
   2336 					goto cleanup_auto_put;
   2337 				}
   2338 				pathsep++;
   2339 				uargv[2] = ftp_strdup(pathsep);
   2340 				pathsep[0] = '/';
   2341 			} else
   2342 				uargv[2] = ftp_strdup(pathsep + 1);
   2343 			pathsep[1] = '\0';
   2344 			uargc++;
   2345 		}
   2346 	}
   2347 	DPRINTF("auto_put: URL `%s' argv[2] `%s'\n",
   2348 	    path, STRorNULL(uargv[2]));
   2349 
   2350 			/* connect and cwd */
   2351 	rval = auto_fetch(1, &path);
   2352 	if(rval >= 0)
   2353 		goto cleanup_auto_put;
   2354 
   2355 	rval = 0;
   2356 
   2357 			/* target filename provided; upload 1 file */
   2358 			/* XXX : is this the best way? */
   2359 	if (uargc == 3) {
   2360 		uargv[1] = argv[0];
   2361 		put(uargc, uargv);
   2362 		if ((code / 100) != COMPLETE)
   2363 			rval = 1;
   2364 	} else {	/* otherwise a target dir: upload all files to it */
   2365 		for(argpos = 0; argv[argpos] != NULL; argpos++) {
   2366 			uargv[1] = argv[argpos];
   2367 			mput(uargc, uargv);
   2368 			if ((code / 100) != COMPLETE) {
   2369 				rval = argpos + 1;
   2370 				break;
   2371 			}
   2372 		}
   2373 	}
   2374 
   2375  cleanup_auto_put:
   2376 	free(path);
   2377 	FREEPTR(uargv[2]);
   2378 	return (rval);
   2379 }
   2380