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