Home | History | Annotate | Line # | Download | only in ftp
fetch.c revision 1.217
      1 /*	$NetBSD: fetch.c,v 1.217 2015/12/17 17:08:45 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.217 2015/12/17 17:08:45 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 __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 static void
    817 print_connect(FETCH *fin, const struct urlinfo *ui)
    818 {
    819 	char hname[NI_MAXHOST], *p;
    820 	const char *h;
    821 
    822 	if (isipv6addr(ui->host)) {
    823 		/*
    824 		 * strip off IPv6 scope identifier,
    825 		 * since it is local to the node
    826 		 */
    827 		if ((p = strchr(ui->host, '%')) == NULL)
    828 			snprintf(hname, sizeof(hname), "[%s]", ui->host);
    829 		else
    830 			snprintf(hname, sizeof(hname), "[%.*s]",
    831 			    (int)(p - ui->host), ui->host);
    832 		h = hname;
    833 	} else
    834 		h = ui->host;
    835 
    836 	fetch_printf(fin, "CONNECT %s:%s HTTP/1.1\r\n", h, ui->port);
    837 	fetch_printf(fin, "Host: %s:%s\r\n", h, ui->port);
    838 }
    839 
    840 #define C_OK 0
    841 #define C_CLEANUP 1
    842 #define C_IMPROPER 2
    843 #define C_PROXY 3
    844 #define C_NOPROXY 4
    845 
    846 static int
    847 getresponseline(FETCH *fin, char *buf, size_t buflen, int *len)
    848 {
    849 	const char *errormsg;
    850 
    851 	alarmtimer(quit_time ? quit_time : 60);
    852 	*len = fetch_getline(fin, buf, buflen, &errormsg);
    853 	alarmtimer(0);
    854 	if (*len < 0) {
    855 		if (*errormsg == '\n')
    856 			errormsg++;
    857 		warnx("Receiving HTTP reply: %s", errormsg);
    858 		return C_CLEANUP;
    859 	}
    860 	while (*len > 0 && (ISLWS(buf[*len-1])))
    861 		buf[--*len] = '\0';
    862 
    863 	if (*len)
    864 		DPRINTF("%s: received `%s'\n", __func__, buf);
    865 	return C_OK;
    866 }
    867 
    868 static int
    869 getresponse(FETCH *fin, char **cp, size_t buflen, int *hcode)
    870 {
    871 	int len, rv;
    872 	char *ep, *buf = *cp;
    873 
    874 	*hcode = 0;
    875 	if ((rv = getresponseline(fin, buf, buflen, &len)) != C_OK)
    876 		return rv;
    877 
    878 	/* Determine HTTP response code */
    879 	*cp = strchr(buf, ' ');
    880 	if (*cp == NULL)
    881 		return C_IMPROPER;
    882 
    883 	(*cp)++;
    884 
    885 	*hcode = strtol(*cp, &ep, 10);
    886 	if (*ep != '\0' && !isspace((unsigned char)*ep))
    887 		return C_IMPROPER;
    888 
    889 	return C_OK;
    890 }
    891 
    892 static int
    893 negotiate_connection(FETCH *fin, const char *url, const char *penv,
    894     off_t *rangestart, off_t *rangeend, off_t *entitylen,
    895     time_t *mtime, struct authinfo *wauth, struct authinfo *pauth,
    896     int *rval, int *ischunked, char **auth)
    897 {
    898 	int			len, hcode, rv;
    899 	char			buf[FTPBUFLEN], *ep;
    900 	const char		*cp, *token;
    901 	char 			*location, *message;
    902 
    903 	*auth = message = location = NULL;
    904 
    905 	/* Read the response */
    906 	ep = buf;
    907 	switch (getresponse(fin, &ep, sizeof(buf), &hcode)) {
    908 	case C_CLEANUP:
    909 		goto cleanup_fetch_url;
    910 	case C_IMPROPER:
    911 		goto improper;
    912 	case C_OK:
    913 		message = ftp_strdup(ep);
    914 		break;
    915 	}
    916 
    917 	/* Read the rest of the header. */
    918 
    919 	for (;;) {
    920 		if ((rv = getresponseline(fin, buf, sizeof(buf), &len)) != C_OK)
    921 			goto cleanup_fetch_url;
    922 		if (len == 0)
    923 			break;
    924 
    925 	/*
    926 	 * Look for some headers
    927 	 */
    928 
    929 		cp = buf;
    930 
    931 		if (match_token(&cp, "Content-Length:")) {
    932 			filesize = STRTOLL(cp, &ep, 10);
    933 			if (filesize < 0 || *ep != '\0')
    934 				goto improper;
    935 			DPRINTF("%s: parsed len as: " LLF "\n",
    936 			    __func__, (LLT)filesize);
    937 
    938 		} else if (match_token(&cp, "Content-Range:")) {
    939 			if (! match_token(&cp, "bytes"))
    940 				goto improper;
    941 
    942 			if (*cp == '*')
    943 				cp++;
    944 			else {
    945 				*rangestart = STRTOLL(cp, &ep, 10);
    946 				if (*rangestart < 0 || *ep != '-')
    947 					goto improper;
    948 				cp = ep + 1;
    949 				*rangeend = STRTOLL(cp, &ep, 10);
    950 				if (*rangeend < 0 || *rangeend < *rangestart)
    951 					goto improper;
    952 				cp = ep;
    953 			}
    954 			if (*cp != '/')
    955 				goto improper;
    956 			cp++;
    957 			if (*cp == '*')
    958 				cp++;
    959 			else {
    960 				*entitylen = STRTOLL(cp, &ep, 10);
    961 				if (*entitylen < 0)
    962 					goto improper;
    963 				cp = ep;
    964 			}
    965 			if (*cp != '\0')
    966 				goto improper;
    967 
    968 #ifndef NO_DEBUG
    969 			if (ftp_debug) {
    970 				fprintf(ttyout, "parsed range as: ");
    971 				if (*rangestart == -1)
    972 					fprintf(ttyout, "*");
    973 				else
    974 					fprintf(ttyout, LLF "-" LLF,
    975 					    (LLT)*rangestart,
    976 					    (LLT)*rangeend);
    977 				fprintf(ttyout, "/" LLF "\n", (LLT)*entitylen);
    978 			}
    979 #endif
    980 			if (! restart_point) {
    981 				warnx(
    982 			    "Received unexpected Content-Range header");
    983 				goto cleanup_fetch_url;
    984 			}
    985 
    986 		} else if (match_token(&cp, "Last-Modified:")) {
    987 			getmtime(cp, mtime);
    988 
    989 		} else if (match_token(&cp, "Location:")) {
    990 			location = ftp_strdup(cp);
    991 			DPRINTF("%s: parsed location as `%s'\n",
    992 			    __func__, cp);
    993 
    994 		} else if (match_token(&cp, "Transfer-Encoding:")) {
    995 			if (match_token(&cp, "binary")) {
    996 				warnx(
    997 		"Bogus transfer encoding `binary' (fetching anyway)");
    998 				continue;
    999 			}
   1000 			if (! (token = match_token(&cp, "chunked"))) {
   1001 				warnx(
   1002 			    "Unsupported transfer encoding `%s'",
   1003 				    token);
   1004 				goto cleanup_fetch_url;
   1005 			}
   1006 			(*ischunked)++;
   1007 			DPRINTF("%s: using chunked encoding\n",
   1008 			    __func__);
   1009 
   1010 		} else if (match_token(&cp, "Proxy-Authenticate:")
   1011 			|| match_token(&cp, "WWW-Authenticate:")) {
   1012 			if (! (token = match_token(&cp, "Basic"))) {
   1013 				DPRINTF("%s: skipping unknown auth "
   1014 				    "scheme `%s'\n", __func__, token);
   1015 				continue;
   1016 			}
   1017 			FREEPTR(*auth);
   1018 			*auth = ftp_strdup(token);
   1019 			DPRINTF("%s: parsed auth as `%s'\n",
   1020 			    __func__, cp);
   1021 		}
   1022 
   1023 	}
   1024 			/* finished parsing header */
   1025 
   1026 	switch (hcode) {
   1027 	case 200:
   1028 		break;
   1029 	case 206:
   1030 		if (! restart_point) {
   1031 			warnx("Not expecting partial content header");
   1032 			goto cleanup_fetch_url;
   1033 		}
   1034 		break;
   1035 	case 300:
   1036 	case 301:
   1037 	case 302:
   1038 	case 303:
   1039 	case 305:
   1040 	case 307:
   1041 		if (EMPTYSTRING(location)) {
   1042 			warnx(
   1043 			"No redirection Location provided by server");
   1044 			goto cleanup_fetch_url;
   1045 		}
   1046 		if (redirect_loop++ > 5) {
   1047 			warnx("Too many redirections requested");
   1048 			goto cleanup_fetch_url;
   1049 		}
   1050 		if (hcode == 305) {
   1051 			if (verbose)
   1052 				fprintf(ttyout, "Redirected via %s\n",
   1053 				    location);
   1054 			*rval = fetch_url(url, location,
   1055 			    pauth->auth, wauth->auth);
   1056 		} else {
   1057 			if (verbose)
   1058 				fprintf(ttyout, "Redirected to %s\n",
   1059 				    location);
   1060 			*rval = go_fetch(location);
   1061 		}
   1062 		goto cleanup_fetch_url;
   1063 #ifndef NO_AUTH
   1064 	case 401:
   1065 	case 407:
   1066 	    {
   1067 		struct  authinfo aauth;
   1068 		char **authp;
   1069 
   1070 		if (hcode == 401)
   1071 			aauth = *wauth;
   1072 		else
   1073 			aauth = *pauth;
   1074 
   1075 		if (verbose || aauth.auth == NULL ||
   1076 		    aauth.user == NULL || aauth.pass == NULL)
   1077 			fprintf(ttyout, "%s\n", message);
   1078 		if (EMPTYSTRING(*auth)) {
   1079 			warnx(
   1080 		    "No authentication challenge provided by server");
   1081 			goto cleanup_fetch_url;
   1082 		}
   1083 
   1084 		if (aauth.auth != NULL) {
   1085 			char reply[10];
   1086 
   1087 			fprintf(ttyout,
   1088 			    "Authorization failed. Retry (y/n)? ");
   1089 			if (get_line(stdin, reply, sizeof(reply), NULL)
   1090 			    < 0) {
   1091 				goto cleanup_fetch_url;
   1092 			}
   1093 			if (tolower((unsigned char)reply[0]) != 'y')
   1094 				goto cleanup_fetch_url;
   1095 			aauth.user = NULL;
   1096 			aauth.pass = NULL;
   1097 		}
   1098 
   1099 		authp = &aauth.auth;
   1100 		if (auth_url(*auth, authp, &aauth) == 0) {
   1101 			*rval = fetch_url(url, penv,
   1102 			    pauth->auth, wauth->auth);
   1103 			memset(*authp, 0, strlen(*authp));
   1104 			FREEPTR(*authp);
   1105 		}
   1106 		goto cleanup_fetch_url;
   1107 	    }
   1108 #endif
   1109 	default:
   1110 		if (message)
   1111 			warnx("Error retrieving file `%s'", message);
   1112 		else
   1113 			warnx("Unknown error retrieving file");
   1114 		goto cleanup_fetch_url;
   1115 	}
   1116 	rv = C_OK;
   1117 	goto out;
   1118 
   1119 cleanup_fetch_url:
   1120 	rv = C_CLEANUP;
   1121 	goto out;
   1122 improper:
   1123 	rv = C_IMPROPER;
   1124 	goto out;
   1125 out:
   1126 	FREEPTR(message);
   1127 	FREEPTR(location);
   1128 	return rv;
   1129 }		/* end of ftp:// or http:// specific setup */
   1130 
   1131 #ifdef WITH_SSL
   1132 static int
   1133 connectmethod(int s, FETCH *fin, struct urlinfo *oui, struct urlinfo *ui,
   1134     struct authinfo *pauth, char **auth, int *hasleading)
   1135 {
   1136 	void *ssl;
   1137 	int hcode, rv;
   1138 	const char *cp;
   1139 	char buf[FTPBUFLEN], *ep;
   1140 	char *message = NULL;
   1141 
   1142 	print_connect(fin, oui);
   1143 
   1144 	print_agent(fin);
   1145 	*hasleading = print_proxy(fin, *hasleading, NULL, pauth->auth);
   1146 
   1147 	if (verbose && *hasleading)
   1148 		fputs(")\n", ttyout);
   1149 	*hasleading = 0;
   1150 
   1151 	fetch_printf(fin, "\r\n");
   1152 	if (fetch_flush(fin) == EOF) {
   1153 		warn("Writing HTTP request");
   1154 		alarmtimer(0);
   1155 		goto cleanup_fetch_url;
   1156 	}
   1157 	alarmtimer(0);
   1158 
   1159 	/* Read the response */
   1160 	ep = buf;
   1161 	switch (getresponse(fin, &ep, sizeof(buf), &hcode)) {
   1162 	case C_CLEANUP:
   1163 		goto cleanup_fetch_url;
   1164 	case C_IMPROPER:
   1165 		goto improper;
   1166 	case C_OK:
   1167 		message = ftp_strdup(ep);
   1168 		break;
   1169 	}
   1170 
   1171 	for (;;) {
   1172 		int len;
   1173 		if (getresponseline(fin, buf, sizeof(buf), &len) != C_OK)
   1174 			goto cleanup_fetch_url;
   1175 		if (len == 0)
   1176 			break;
   1177 		if (match_token(&cp, "Proxy-Authenticate:")) {
   1178 			const char *token;
   1179 			if (!(token = match_token(&cp, "Basic"))) {
   1180 				DPRINTF(
   1181 				    "%s: skipping unknown auth scheme `%s'\n",
   1182 				    __func__, token);
   1183 				continue;
   1184 			}
   1185 			FREEPTR(*auth);
   1186 			*auth = ftp_strdup(token);
   1187 			DPRINTF("%s: parsed auth as " "`%s'\n", __func__, cp);
   1188 		}
   1189 	}
   1190 
   1191 	/* finished parsing header */
   1192 	switch (hcode) {
   1193 	case 200:
   1194 		break;
   1195 	default:
   1196 		if (message)
   1197 			warnx("Error proxy connect " "`%s'", message);
   1198 		else
   1199 			warnx("Unknown error proxy " "connect");
   1200 		goto cleanup_fetch_url;
   1201 	}
   1202 
   1203 	if ((ssl = fetch_start_ssl(s, oui->host)) == NULL)
   1204 		goto cleanup_fetch_url;
   1205 	fetch_set_ssl(fin, ssl);
   1206 
   1207 	rv = C_OK;
   1208 	goto out;
   1209 improper:
   1210 	rv = C_IMPROPER;
   1211 	goto out;
   1212 cleanup_fetch_url:
   1213 	rv = C_CLEANUP;
   1214 	goto out;
   1215 out:
   1216 	FREEPTR(message);
   1217 	return rv;
   1218 }
   1219 #endif
   1220 
   1221 /*
   1222  * Retrieve URL, via a proxy if necessary, using HTTP.
   1223  * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
   1224  * http_proxy/https_proxy as appropriate.
   1225  * Supports HTTP redirects.
   1226  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
   1227  * is still open (e.g, ftp xfer with trailing /)
   1228  */
   1229 static int
   1230 fetch_url(const char *url, const char *proxyenv, char *proxyauth, char *wwwauth)
   1231 {
   1232 	sigfunc volatile	oldint;
   1233 	sigfunc volatile	oldpipe;
   1234 	sigfunc volatile	oldalrm;
   1235 	sigfunc volatile	oldquit;
   1236 	int volatile		s;
   1237 	struct stat		sb;
   1238 	int volatile		isproxy;
   1239 	int 			rval, ischunked;
   1240 	size_t			flen;
   1241 	static size_t		bufsize;
   1242 	static char		*xferbuf;
   1243 	const char		*cp;
   1244 	char			*ep;
   1245 	char			*auth;
   1246 	char			*volatile savefile;
   1247 	char			*volatile location;
   1248 	char			*volatile message;
   1249 	char			*volatile decodedpath;
   1250 	struct authinfo 	wauth, pauth;
   1251 	off_t			hashbytes, rangestart, rangeend, entitylen;
   1252 	int			(*volatile closefunc)(FILE *);
   1253 	FETCH			*volatile fin;
   1254 	FILE			*volatile fout;
   1255 	const char		*volatile penv = proxyenv;
   1256 	struct urlinfo		ui, oui;
   1257 	time_t			mtime;
   1258 	void			*ssl = NULL;
   1259 
   1260 	DPRINTF("%s: `%s' proxyenv `%s'\n", __func__, url, STRorNULL(penv));
   1261 
   1262 	oldquit = oldalrm = oldint = oldpipe = NULL;
   1263 	closefunc = NULL;
   1264 	fin = NULL;
   1265 	fout = NULL;
   1266 	s = -1;
   1267 	savefile = NULL;
   1268 	auth = location = message = NULL;
   1269 	ischunked = isproxy = 0;
   1270 	rval = 1;
   1271 
   1272 	initurlinfo(&ui);
   1273 	initauthinfo(&wauth, wwwauth);
   1274 	initauthinfo(&pauth, proxyauth);
   1275 
   1276 	decodedpath = NULL;
   1277 
   1278 	if (sigsetjmp(httpabort, 1))
   1279 		goto cleanup_fetch_url;
   1280 
   1281 	if (parse_url(url, "URL", &ui, &wauth) == -1)
   1282 		goto cleanup_fetch_url;
   1283 
   1284 	copyurlinfo(&oui, &ui);
   1285 
   1286 	if (ui.utype == FILE_URL_T && ! EMPTYSTRING(ui.host)
   1287 	    && strcasecmp(ui.host, "localhost") != 0) {
   1288 		warnx("No support for non local file URL `%s'", url);
   1289 		goto cleanup_fetch_url;
   1290 	}
   1291 
   1292 	if (EMPTYSTRING(ui.path)) {
   1293 		if (ui.utype == FTP_URL_T) {
   1294 			rval = fetch_ftp(url);
   1295 			goto cleanup_fetch_url;
   1296 		}
   1297 		if (!IS_HTTP_TYPE(ui.utype) || outfile == NULL)  {
   1298 			warnx("Invalid URL (no file after host) `%s'", url);
   1299 			goto cleanup_fetch_url;
   1300 		}
   1301 	}
   1302 
   1303 	decodedpath = ftp_strdup(ui.path);
   1304 	url_decode(decodedpath);
   1305 
   1306 	if (outfile)
   1307 		savefile = outfile;
   1308 	else {
   1309 		cp = strrchr(decodedpath, '/');		/* find savefile */
   1310 		if (cp != NULL)
   1311 			savefile = ftp_strdup(cp + 1);
   1312 		else
   1313 			savefile = ftp_strdup(decodedpath);
   1314 	}
   1315 	DPRINTF("%s: savefile `%s'\n", __func__, savefile);
   1316 	if (EMPTYSTRING(savefile)) {
   1317 		if (ui.utype == FTP_URL_T) {
   1318 			rval = fetch_ftp(url);
   1319 			goto cleanup_fetch_url;
   1320 		}
   1321 		warnx("No file after directory (you must specify an "
   1322 		    "output file) `%s'", url);
   1323 		goto cleanup_fetch_url;
   1324 	}
   1325 
   1326 	restart_point = 0;
   1327 	filesize = -1;
   1328 	rangestart = rangeend = entitylen = -1;
   1329 	mtime = -1;
   1330 	if (restartautofetch) {
   1331 		if (stat(savefile, &sb) == 0)
   1332 			restart_point = sb.st_size;
   1333 	}
   1334 	if (ui.utype == FILE_URL_T) {		/* file:// URLs */
   1335 		direction = "copied";
   1336 		fin = fetch_open(decodedpath, "r");
   1337 		if (fin == NULL) {
   1338 			warn("Can't open `%s'", decodedpath);
   1339 			goto cleanup_fetch_url;
   1340 		}
   1341 		if (fstat(fetch_fileno(fin), &sb) == 0) {
   1342 			mtime = sb.st_mtime;
   1343 			filesize = sb.st_size;
   1344 		}
   1345 		if (restart_point) {
   1346 			if (lseek(fetch_fileno(fin), restart_point, SEEK_SET) < 0) {
   1347 				warn("Can't seek to restart `%s'",
   1348 				    decodedpath);
   1349 				goto cleanup_fetch_url;
   1350 			}
   1351 		}
   1352 		if (verbose) {
   1353 			fprintf(ttyout, "Copying %s", decodedpath);
   1354 			if (restart_point)
   1355 				fprintf(ttyout, " (restarting at " LLF ")",
   1356 				    (LLT)restart_point);
   1357 			fputs("\n", ttyout);
   1358 		}
   1359 		if (0 == rcvbuf_size) {
   1360 			rcvbuf_size = 8 * 1024; /* XXX */
   1361 		}
   1362 	} else {				/* ftp:// or http:// URLs */
   1363 		int hasleading;
   1364 
   1365 		if (penv == NULL) {
   1366 #ifdef WITH_SSL
   1367 			if (ui.utype == HTTPS_URL_T)
   1368 				penv = getoptionvalue("https_proxy");
   1369 #endif
   1370 			if (penv == NULL && IS_HTTP_TYPE(ui.utype))
   1371 				penv = getoptionvalue("http_proxy");
   1372 			else if (ui.utype == FTP_URL_T)
   1373 				penv = getoptionvalue("ftp_proxy");
   1374 		}
   1375 		direction = "retrieved";
   1376 		if (! EMPTYSTRING(penv)) {			/* use proxy */
   1377 
   1378 			isproxy = handle_noproxy(ui.host, ui.portnum);
   1379 
   1380 			if (isproxy == 0 && ui.utype == FTP_URL_T) {
   1381 				rval = fetch_ftp(url);
   1382 				goto cleanup_fetch_url;
   1383 			}
   1384 
   1385 			if (isproxy) {
   1386 				if (restart_point) {
   1387 					warnx(
   1388 					    "Can't restart via proxy URL `%s'",
   1389 					    penv);
   1390 					goto cleanup_fetch_url;
   1391 				}
   1392 				if (handle_proxy(url, penv, &ui, &pauth) < 0)
   1393 					goto cleanup_fetch_url;
   1394 			}
   1395 		} /* ! EMPTYSTRING(penv) */
   1396 
   1397 		s = ftp_socket(&ui, &ssl);
   1398 		if (s < 0) {
   1399 			warnx("Can't connect to `%s:%s'", ui.host, ui.port);
   1400 			goto cleanup_fetch_url;
   1401 		}
   1402 
   1403 		oldalrm = xsignal(SIGALRM, timeouthttp);
   1404 		alarmtimer(quit_time ? quit_time : 60);
   1405 		fin = fetch_fdopen(s, "r+");
   1406 		fetch_set_ssl(fin, ssl);
   1407 		alarmtimer(0);
   1408 
   1409 		alarmtimer(quit_time ? quit_time : 60);
   1410 		/*
   1411 		 * Construct and send the request.
   1412 		 */
   1413 		if (verbose)
   1414 			fprintf(ttyout, "Requesting %s\n", url);
   1415 
   1416 		hasleading = 0;
   1417 #ifdef WITH_SSL
   1418 		if (isproxy && oui.utype == HTTPS_URL_T) {
   1419 			switch (connectmethod(s, fin, &oui, &ui, &pauth, &auth,
   1420 			    &hasleading)) {
   1421 			case C_CLEANUP:
   1422 				goto cleanup_fetch_url;
   1423 			case C_IMPROPER:
   1424 				goto improper;
   1425 			case C_OK:
   1426 				break;
   1427 			default:
   1428 				abort();
   1429 			}
   1430 		}
   1431 #endif
   1432 
   1433 		hasleading = print_get(fin, hasleading, isproxy, &oui, &ui);
   1434 
   1435 		if (flushcache)
   1436 			print_cache(fin, isproxy);
   1437 
   1438 		print_agent(fin);
   1439 		hasleading = print_proxy(fin, hasleading, wauth.auth,
   1440 		     auth ? NULL : pauth.auth);
   1441 		if (hasleading) {
   1442 			hasleading = 0;
   1443 			if (verbose)
   1444 				fputs(")\n", ttyout);
   1445 		}
   1446 
   1447 		fetch_printf(fin, "\r\n");
   1448 		if (fetch_flush(fin) == EOF) {
   1449 			warn("Writing HTTP request");
   1450 			alarmtimer(0);
   1451 			goto cleanup_fetch_url;
   1452 		}
   1453 		alarmtimer(0);
   1454 
   1455 		switch (negotiate_connection(fin, url, penv,
   1456 		    &rangestart, &rangeend, &entitylen,
   1457 		    &mtime, &wauth, &pauth, &rval, &ischunked, &auth)) {
   1458 		case C_OK:
   1459 			break;
   1460 		case C_CLEANUP:
   1461 			goto cleanup_fetch_url;
   1462 		case C_IMPROPER:
   1463 			goto improper;
   1464 		default:
   1465 			abort();
   1466 		}
   1467 	}
   1468 
   1469 	/* Open the output file. */
   1470 
   1471 	/*
   1472 	 * Only trust filenames with special meaning if they came from
   1473 	 * the command line
   1474 	 */
   1475 	if (outfile == savefile) {
   1476 		if (strcmp(savefile, "-") == 0) {
   1477 			fout = stdout;
   1478 		} else if (*savefile == '|') {
   1479 			oldpipe = xsignal(SIGPIPE, SIG_IGN);
   1480 			fout = popen(savefile + 1, "w");
   1481 			if (fout == NULL) {
   1482 				warn("Can't execute `%s'", savefile + 1);
   1483 				goto cleanup_fetch_url;
   1484 			}
   1485 			closefunc = pclose;
   1486 		}
   1487 	}
   1488 	if (fout == NULL) {
   1489 		if ((rangeend != -1 && rangeend <= restart_point) ||
   1490 		    (rangestart == -1 && filesize != -1 && filesize <= restart_point)) {
   1491 			/* already done */
   1492 			if (verbose)
   1493 				fprintf(ttyout, "already done\n");
   1494 			rval = 0;
   1495 			goto cleanup_fetch_url;
   1496 		}
   1497 		if (restart_point && rangestart != -1) {
   1498 			if (entitylen != -1)
   1499 				filesize = entitylen;
   1500 			if (rangestart != restart_point) {
   1501 				warnx(
   1502 				    "Size of `%s' differs from save file `%s'",
   1503 				    url, savefile);
   1504 				goto cleanup_fetch_url;
   1505 			}
   1506 			fout = fopen(savefile, "a");
   1507 		} else
   1508 			fout = fopen(savefile, "w");
   1509 		if (fout == NULL) {
   1510 			warn("Can't open `%s'", savefile);
   1511 			goto cleanup_fetch_url;
   1512 		}
   1513 		closefunc = fclose;
   1514 	}
   1515 
   1516 			/* Trap signals */
   1517 	oldquit = xsignal(SIGQUIT, psummary);
   1518 	oldint = xsignal(SIGINT, aborthttp);
   1519 
   1520 	assert(rcvbuf_size > 0);
   1521 	if ((size_t)rcvbuf_size > bufsize) {
   1522 		if (xferbuf)
   1523 			(void)free(xferbuf);
   1524 		bufsize = rcvbuf_size;
   1525 		xferbuf = ftp_malloc(bufsize);
   1526 	}
   1527 
   1528 	bytes = 0;
   1529 	hashbytes = mark;
   1530 	if (oldalrm) {
   1531 		(void)xsignal(SIGALRM, oldalrm);
   1532 		oldalrm = NULL;
   1533 	}
   1534 	progressmeter(-1);
   1535 
   1536 			/* Finally, suck down the file. */
   1537 	do {
   1538 		long chunksize;
   1539 		short lastchunk;
   1540 
   1541 		chunksize = 0;
   1542 		lastchunk = 0;
   1543 					/* read chunk-size */
   1544 		if (ischunked) {
   1545 			if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
   1546 				warnx("Unexpected EOF reading chunk-size");
   1547 				goto cleanup_fetch_url;
   1548 			}
   1549 			errno = 0;
   1550 			chunksize = strtol(xferbuf, &ep, 16);
   1551 			if (ep == xferbuf) {
   1552 				warnx("Invalid chunk-size");
   1553 				goto cleanup_fetch_url;
   1554 			}
   1555 			if (errno == ERANGE || chunksize < 0) {
   1556 				errno = ERANGE;
   1557 				warn("Chunk-size `%.*s'",
   1558 				    (int)(ep-xferbuf), xferbuf);
   1559 				goto cleanup_fetch_url;
   1560 			}
   1561 
   1562 				/*
   1563 				 * XXX:	Work around bug in Apache 1.3.9 and
   1564 				 *	1.3.11, which incorrectly put trailing
   1565 				 *	space after the chunk-size.
   1566 				 */
   1567 			while (*ep == ' ')
   1568 				ep++;
   1569 
   1570 					/* skip [ chunk-ext ] */
   1571 			if (*ep == ';') {
   1572 				while (*ep && *ep != '\r')
   1573 					ep++;
   1574 			}
   1575 
   1576 			if (strcmp(ep, "\r\n") != 0) {
   1577 				warnx("Unexpected data following chunk-size");
   1578 				goto cleanup_fetch_url;
   1579 			}
   1580 			DPRINTF("%s: got chunk-size of " LLF "\n", __func__,
   1581 			    (LLT)chunksize);
   1582 			if (chunksize == 0) {
   1583 				lastchunk = 1;
   1584 				goto chunkdone;
   1585 			}
   1586 		}
   1587 					/* transfer file or chunk */
   1588 		while (1) {
   1589 			struct timeval then, now, td;
   1590 			volatile off_t bufrem;
   1591 
   1592 			if (rate_get)
   1593 				(void)gettimeofday(&then, NULL);
   1594 			bufrem = rate_get ? rate_get : (off_t)bufsize;
   1595 			if (ischunked)
   1596 				bufrem = MIN(chunksize, bufrem);
   1597 			while (bufrem > 0) {
   1598 				flen = fetch_read(xferbuf, sizeof(char),
   1599 				    MIN((off_t)bufsize, bufrem), fin);
   1600 				if (flen <= 0)
   1601 					goto chunkdone;
   1602 				bytes += flen;
   1603 				bufrem -= flen;
   1604 				if (fwrite(xferbuf, sizeof(char), flen, fout)
   1605 				    != flen) {
   1606 					warn("Writing `%s'", savefile);
   1607 					goto cleanup_fetch_url;
   1608 				}
   1609 				if (hash && !progress) {
   1610 					while (bytes >= hashbytes) {
   1611 						(void)putc('#', ttyout);
   1612 						hashbytes += mark;
   1613 					}
   1614 					(void)fflush(ttyout);
   1615 				}
   1616 				if (ischunked) {
   1617 					chunksize -= flen;
   1618 					if (chunksize <= 0)
   1619 						break;
   1620 				}
   1621 			}
   1622 			if (rate_get) {
   1623 				while (1) {
   1624 					(void)gettimeofday(&now, NULL);
   1625 					timersub(&now, &then, &td);
   1626 					if (td.tv_sec > 0)
   1627 						break;
   1628 					usleep(1000000 - td.tv_usec);
   1629 				}
   1630 			}
   1631 			if (ischunked && chunksize <= 0)
   1632 				break;
   1633 		}
   1634 					/* read CRLF after chunk*/
   1635  chunkdone:
   1636 		if (ischunked) {
   1637 			if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
   1638 				alarmtimer(0);
   1639 				warnx("Unexpected EOF reading chunk CRLF");
   1640 				goto cleanup_fetch_url;
   1641 			}
   1642 			if (strcmp(xferbuf, "\r\n") != 0) {
   1643 				warnx("Unexpected data following chunk");
   1644 				goto cleanup_fetch_url;
   1645 			}
   1646 			if (lastchunk)
   1647 				break;
   1648 		}
   1649 	} while (ischunked);
   1650 
   1651 /* XXX: deal with optional trailer & CRLF here? */
   1652 
   1653 	if (hash && !progress && bytes > 0) {
   1654 		if (bytes < mark)
   1655 			(void)putc('#', ttyout);
   1656 		(void)putc('\n', ttyout);
   1657 	}
   1658 	if (fetch_error(fin)) {
   1659 		warn("Reading file");
   1660 		goto cleanup_fetch_url;
   1661 	}
   1662 	progressmeter(1);
   1663 	(void)fflush(fout);
   1664 	if (closefunc == fclose && mtime != -1) {
   1665 		struct timeval tval[2];
   1666 
   1667 		(void)gettimeofday(&tval[0], NULL);
   1668 		tval[1].tv_sec = mtime;
   1669 		tval[1].tv_usec = 0;
   1670 		(*closefunc)(fout);
   1671 		fout = NULL;
   1672 
   1673 		if (utimes(savefile, tval) == -1) {
   1674 			fprintf(ttyout,
   1675 			    "Can't change modification time to %s",
   1676 			    rfc2822time(localtime(&mtime)));
   1677 		}
   1678 	}
   1679 	if (bytes > 0)
   1680 		ptransfer(0);
   1681 	bytes = 0;
   1682 
   1683 	rval = 0;
   1684 	goto cleanup_fetch_url;
   1685 
   1686  improper:
   1687 	warnx("Improper response from `%s:%s'", ui.host, ui.port);
   1688 
   1689  cleanup_fetch_url:
   1690 	if (oldint)
   1691 		(void)xsignal(SIGINT, oldint);
   1692 	if (oldpipe)
   1693 		(void)xsignal(SIGPIPE, oldpipe);
   1694 	if (oldalrm)
   1695 		(void)xsignal(SIGALRM, oldalrm);
   1696 	if (oldquit)
   1697 		(void)xsignal(SIGQUIT, oldpipe);
   1698 	if (fin != NULL)
   1699 		fetch_close(fin);
   1700 	else if (s != -1)
   1701 		close(s);
   1702 	if (closefunc != NULL && fout != NULL)
   1703 		(*closefunc)(fout);
   1704 	if (savefile != outfile)
   1705 		FREEPTR(savefile);
   1706 	freeurlinfo(&ui);
   1707 	freeurlinfo(&oui);
   1708 	freeauthinfo(&wauth);
   1709 	freeauthinfo(&pauth);
   1710 	FREEPTR(decodedpath);
   1711 	FREEPTR(auth);
   1712 	FREEPTR(location);
   1713 	FREEPTR(message);
   1714 	return (rval);
   1715 }
   1716 
   1717 /*
   1718  * Abort a HTTP retrieval
   1719  */
   1720 static void
   1721 aborthttp(int notused)
   1722 {
   1723 	char msgbuf[100];
   1724 	int len;
   1725 
   1726 	sigint_raised = 1;
   1727 	alarmtimer(0);
   1728 	if (fromatty) {
   1729 		len = snprintf(msgbuf, sizeof(msgbuf),
   1730 		    "\n%s: HTTP fetch aborted.\n", getprogname());
   1731 		if (len > 0)
   1732 			write(fileno(ttyout), msgbuf, len);
   1733 	}
   1734 	siglongjmp(httpabort, 1);
   1735 }
   1736 
   1737 static void
   1738 timeouthttp(int notused)
   1739 {
   1740 	char msgbuf[100];
   1741 	int len;
   1742 
   1743 	alarmtimer(0);
   1744 	if (fromatty) {
   1745 		len = snprintf(msgbuf, sizeof(msgbuf),
   1746 		    "\n%s: HTTP fetch timeout.\n", getprogname());
   1747 		if (len > 0)
   1748 			write(fileno(ttyout), msgbuf, len);
   1749 	}
   1750 	siglongjmp(httpabort, 1);
   1751 }
   1752 
   1753 /*
   1754  * Retrieve ftp URL or classic ftp argument using FTP.
   1755  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
   1756  * is still open (e.g, ftp xfer with trailing /)
   1757  */
   1758 static int
   1759 fetch_ftp(const char *url)
   1760 {
   1761 	char		*cp, *xargv[5], rempath[MAXPATHLEN];
   1762 	char		*dir, *file;
   1763 	char		 cmdbuf[MAXPATHLEN];
   1764 	char		 dirbuf[4];
   1765 	int		 dirhasglob, filehasglob, rval, transtype, xargc;
   1766 	int		 oanonftp, oautologin;
   1767 	struct authinfo  auth;
   1768 	struct urlinfo	 ui;
   1769 
   1770 	DPRINTF("fetch_ftp: `%s'\n", url);
   1771 	dir = file = NULL;
   1772 	rval = 1;
   1773 	transtype = TYPE_I;
   1774 
   1775 	initurlinfo(&ui);
   1776 	initauthinfo(&auth, NULL);
   1777 
   1778 	if (STRNEQUAL(url, FTP_URL)) {
   1779 		if ((parse_url(url, "URL", &ui, &auth) == -1) ||
   1780 		    (auth.user != NULL && *auth.user == '\0') ||
   1781 		    EMPTYSTRING(ui.host)) {
   1782 			warnx("Invalid URL `%s'", url);
   1783 			goto cleanup_fetch_ftp;
   1784 		}
   1785 		/*
   1786 		 * Note: Don't url_decode(path) here.  We need to keep the
   1787 		 * distinction between "/" and "%2F" until later.
   1788 		 */
   1789 
   1790 					/* check for trailing ';type=[aid]' */
   1791 		if (! EMPTYSTRING(ui.path) && (cp = strrchr(ui.path, ';')) != NULL) {
   1792 			if (strcasecmp(cp, ";type=a") == 0)
   1793 				transtype = TYPE_A;
   1794 			else if (strcasecmp(cp, ";type=i") == 0)
   1795 				transtype = TYPE_I;
   1796 			else if (strcasecmp(cp, ";type=d") == 0) {
   1797 				warnx(
   1798 			    "Directory listing via a URL is not supported");
   1799 				goto cleanup_fetch_ftp;
   1800 			} else {
   1801 				warnx("Invalid suffix `%s' in URL `%s'", cp,
   1802 				    url);
   1803 				goto cleanup_fetch_ftp;
   1804 			}
   1805 			*cp = 0;
   1806 		}
   1807 	} else {			/* classic style `[user@]host:[file]' */
   1808 		ui.utype = CLASSIC_URL_T;
   1809 		ui.host = ftp_strdup(url);
   1810 		cp = strchr(ui.host, '@');
   1811 		if (cp != NULL) {
   1812 			*cp = '\0';
   1813 			auth.user = ui.host;
   1814 			anonftp = 0;	/* disable anonftp */
   1815 			ui.host = ftp_strdup(cp + 1);
   1816 		}
   1817 		cp = strchr(ui.host, ':');
   1818 		if (cp != NULL) {
   1819 			*cp = '\0';
   1820 			ui.path = ftp_strdup(cp + 1);
   1821 		}
   1822 	}
   1823 	if (EMPTYSTRING(ui.host))
   1824 		goto cleanup_fetch_ftp;
   1825 
   1826 			/* Extract the file and (if present) directory name. */
   1827 	dir = ui.path;
   1828 	if (! EMPTYSTRING(dir)) {
   1829 		/*
   1830 		 * If we are dealing with classic `[user@]host:[path]' syntax,
   1831 		 * then a path of the form `/file' (resulting from input of the
   1832 		 * form `host:/file') means that we should do "CWD /" before
   1833 		 * retrieving the file.  So we set dir="/" and file="file".
   1834 		 *
   1835 		 * But if we are dealing with URLs like `ftp://host/path' then
   1836 		 * a path of the form `/file' (resulting from a URL of the form
   1837 		 * `ftp://host//file') means that we should do `CWD ' (with an
   1838 		 * empty argument) before retrieving the file.  So we set
   1839 		 * dir="" and file="file".
   1840 		 *
   1841 		 * If the path does not contain / at all, we set dir=NULL.
   1842 		 * (We get a path without any slashes if we are dealing with
   1843 		 * classic `[user@]host:[file]' or URL `ftp://host/file'.)
   1844 		 *
   1845 		 * In all other cases, we set dir to a string that does not
   1846 		 * include the final '/' that separates the dir part from the
   1847 		 * file part of the path.  (This will be the empty string if
   1848 		 * and only if we are dealing with a path of the form `/file'
   1849 		 * resulting from an URL of the form `ftp://host//file'.)
   1850 		 */
   1851 		cp = strrchr(dir, '/');
   1852 		if (cp == dir && ui.utype == CLASSIC_URL_T) {
   1853 			file = cp + 1;
   1854 			(void)strlcpy(dirbuf, "/", sizeof(dirbuf));
   1855 			dir = dirbuf;
   1856 		} else if (cp != NULL) {
   1857 			*cp++ = '\0';
   1858 			file = cp;
   1859 		} else {
   1860 			file = dir;
   1861 			dir = NULL;
   1862 		}
   1863 	} else
   1864 		dir = NULL;
   1865 	if (ui.utype == FTP_URL_T && file != NULL) {
   1866 		url_decode(file);
   1867 		/* but still don't url_decode(dir) */
   1868 	}
   1869 	DPRINTF("fetch_ftp: user `%s' pass `%s' host %s port %s "
   1870 	    "path `%s' dir `%s' file `%s'\n",
   1871 	    STRorNULL(auth.user), STRorNULL(auth.pass),
   1872 	    STRorNULL(ui.host), STRorNULL(ui.port),
   1873 	    STRorNULL(ui.path), STRorNULL(dir), STRorNULL(file));
   1874 
   1875 	dirhasglob = filehasglob = 0;
   1876 	if (doglob && ui.utype == CLASSIC_URL_T) {
   1877 		if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
   1878 			dirhasglob = 1;
   1879 		if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
   1880 			filehasglob = 1;
   1881 	}
   1882 
   1883 			/* Set up the connection */
   1884 	oanonftp = anonftp;
   1885 	if (connected)
   1886 		disconnect(0, NULL);
   1887 	anonftp = oanonftp;
   1888 	(void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
   1889 	xargv[0] = cmdbuf;
   1890 	xargv[1] = ui.host;
   1891 	xargv[2] = NULL;
   1892 	xargc = 2;
   1893 	if (ui.port) {
   1894 		xargv[2] = ui.port;
   1895 		xargv[3] = NULL;
   1896 		xargc = 3;
   1897 	}
   1898 	oautologin = autologin;
   1899 		/* don't autologin in setpeer(), use ftp_login() below */
   1900 	autologin = 0;
   1901 	setpeer(xargc, xargv);
   1902 	autologin = oautologin;
   1903 	if ((connected == 0) ||
   1904 	    (connected == 1 && !ftp_login(ui.host, auth.user, auth.pass))) {
   1905 		warnx("Can't connect or login to host `%s:%s'",
   1906 			ui.host, ui.port ? ui.port : "?");
   1907 		goto cleanup_fetch_ftp;
   1908 	}
   1909 
   1910 	switch (transtype) {
   1911 	case TYPE_A:
   1912 		setascii(1, xargv);
   1913 		break;
   1914 	case TYPE_I:
   1915 		setbinary(1, xargv);
   1916 		break;
   1917 	default:
   1918 		errx(1, "fetch_ftp: unknown transfer type %d", transtype);
   1919 	}
   1920 
   1921 		/*
   1922 		 * Change directories, if necessary.
   1923 		 *
   1924 		 * Note: don't use EMPTYSTRING(dir) below, because
   1925 		 * dir=="" means something different from dir==NULL.
   1926 		 */
   1927 	if (dir != NULL && !dirhasglob) {
   1928 		char *nextpart;
   1929 
   1930 		/*
   1931 		 * If we are dealing with a classic `[user@]host:[path]'
   1932 		 * (urltype is CLASSIC_URL_T) then we have a raw directory
   1933 		 * name (not encoded in any way) and we can change
   1934 		 * directories in one step.
   1935 		 *
   1936 		 * If we are dealing with an `ftp://host/path' URL
   1937 		 * (urltype is FTP_URL_T), then RFC 3986 says we need to
   1938 		 * send a separate CWD command for each unescaped "/"
   1939 		 * in the path, and we have to interpret %hex escaping
   1940 		 * *after* we find the slashes.  It's possible to get
   1941 		 * empty components here, (from multiple adjacent
   1942 		 * slashes in the path) and RFC 3986 says that we should
   1943 		 * still do `CWD ' (with a null argument) in such cases.
   1944 		 *
   1945 		 * Many ftp servers don't support `CWD ', so if there's an
   1946 		 * error performing that command, bail out with a descriptive
   1947 		 * message.
   1948 		 *
   1949 		 * Examples:
   1950 		 *
   1951 		 * host:			dir="", urltype=CLASSIC_URL_T
   1952 		 *		logged in (to default directory)
   1953 		 * host:file			dir=NULL, urltype=CLASSIC_URL_T
   1954 		 *		"RETR file"
   1955 		 * host:dir/			dir="dir", urltype=CLASSIC_URL_T
   1956 		 *		"CWD dir", logged in
   1957 		 * ftp://host/			dir="", urltype=FTP_URL_T
   1958 		 *		logged in (to default directory)
   1959 		 * ftp://host/dir/		dir="dir", urltype=FTP_URL_T
   1960 		 *		"CWD dir", logged in
   1961 		 * ftp://host/file		dir=NULL, urltype=FTP_URL_T
   1962 		 *		"RETR file"
   1963 		 * ftp://host//file		dir="", urltype=FTP_URL_T
   1964 		 *		"CWD ", "RETR file"
   1965 		 * host:/file			dir="/", urltype=CLASSIC_URL_T
   1966 		 *		"CWD /", "RETR file"
   1967 		 * ftp://host///file		dir="/", urltype=FTP_URL_T
   1968 		 *		"CWD ", "CWD ", "RETR file"
   1969 		 * ftp://host/%2F/file		dir="%2F", urltype=FTP_URL_T
   1970 		 *		"CWD /", "RETR file"
   1971 		 * ftp://host/foo/file		dir="foo", urltype=FTP_URL_T
   1972 		 *		"CWD foo", "RETR file"
   1973 		 * ftp://host/foo/bar/file	dir="foo/bar"
   1974 		 *		"CWD foo", "CWD bar", "RETR file"
   1975 		 * ftp://host//foo/bar/file	dir="/foo/bar"
   1976 		 *		"CWD ", "CWD foo", "CWD bar", "RETR file"
   1977 		 * ftp://host/foo//bar/file	dir="foo//bar"
   1978 		 *		"CWD foo", "CWD ", "CWD bar", "RETR file"
   1979 		 * ftp://host/%2F/foo/bar/file	dir="%2F/foo/bar"
   1980 		 *		"CWD /", "CWD foo", "CWD bar", "RETR file"
   1981 		 * ftp://host/%2Ffoo/bar/file	dir="%2Ffoo/bar"
   1982 		 *		"CWD /foo", "CWD bar", "RETR file"
   1983 		 * ftp://host/%2Ffoo%2Fbar/file	dir="%2Ffoo%2Fbar"
   1984 		 *		"CWD /foo/bar", "RETR file"
   1985 		 * ftp://host/%2Ffoo%2Fbar%2Ffile	dir=NULL
   1986 		 *		"RETR /foo/bar/file"
   1987 		 *
   1988 		 * Note that we don't need `dir' after this point.
   1989 		 */
   1990 		do {
   1991 			if (ui.utype == FTP_URL_T) {
   1992 				nextpart = strchr(dir, '/');
   1993 				if (nextpart) {
   1994 					*nextpart = '\0';
   1995 					nextpart++;
   1996 				}
   1997 				url_decode(dir);
   1998 			} else
   1999 				nextpart = NULL;
   2000 			DPRINTF("fetch_ftp: dir `%s', nextpart `%s'\n",
   2001 			    STRorNULL(dir), STRorNULL(nextpart));
   2002 			if (ui.utype == FTP_URL_T || *dir != '\0') {
   2003 				(void)strlcpy(cmdbuf, "cd", sizeof(cmdbuf));
   2004 				xargv[0] = cmdbuf;
   2005 				xargv[1] = dir;
   2006 				xargv[2] = NULL;
   2007 				dirchange = 0;
   2008 				cd(2, xargv);
   2009 				if (! dirchange) {
   2010 					if (*dir == '\0' && code == 500)
   2011 						fprintf(stderr,
   2012 "\n"
   2013 "ftp: The `CWD ' command (without a directory), which is required by\n"
   2014 "     RFC 3986 to support the empty directory in the URL pathname (`//'),\n"
   2015 "     conflicts with the server's conformance to RFC 959.\n"
   2016 "     Try the same URL without the `//' in the URL pathname.\n"
   2017 "\n");
   2018 					goto cleanup_fetch_ftp;
   2019 				}
   2020 			}
   2021 			dir = nextpart;
   2022 		} while (dir != NULL);
   2023 	}
   2024 
   2025 	if (EMPTYSTRING(file)) {
   2026 		rval = -1;
   2027 		goto cleanup_fetch_ftp;
   2028 	}
   2029 
   2030 	if (dirhasglob) {
   2031 		(void)strlcpy(rempath, dir,	sizeof(rempath));
   2032 		(void)strlcat(rempath, "/",	sizeof(rempath));
   2033 		(void)strlcat(rempath, file,	sizeof(rempath));
   2034 		file = rempath;
   2035 	}
   2036 
   2037 			/* Fetch the file(s). */
   2038 	xargc = 2;
   2039 	(void)strlcpy(cmdbuf, "get", sizeof(cmdbuf));
   2040 	xargv[0] = cmdbuf;
   2041 	xargv[1] = file;
   2042 	xargv[2] = NULL;
   2043 	if (dirhasglob || filehasglob) {
   2044 		int ointeractive;
   2045 
   2046 		ointeractive = interactive;
   2047 		interactive = 0;
   2048 		if (restartautofetch)
   2049 			(void)strlcpy(cmdbuf, "mreget", sizeof(cmdbuf));
   2050 		else
   2051 			(void)strlcpy(cmdbuf, "mget", sizeof(cmdbuf));
   2052 		xargv[0] = cmdbuf;
   2053 		mget(xargc, xargv);
   2054 		interactive = ointeractive;
   2055 	} else {
   2056 		if (outfile == NULL) {
   2057 			cp = strrchr(file, '/');	/* find savefile */
   2058 			if (cp != NULL)
   2059 				outfile = cp + 1;
   2060 			else
   2061 				outfile = file;
   2062 		}
   2063 		xargv[2] = (char *)outfile;
   2064 		xargv[3] = NULL;
   2065 		xargc++;
   2066 		if (restartautofetch)
   2067 			reget(xargc, xargv);
   2068 		else
   2069 			get(xargc, xargv);
   2070 	}
   2071 
   2072 	if ((code / 100) == COMPLETE)
   2073 		rval = 0;
   2074 
   2075  cleanup_fetch_ftp:
   2076 	freeurlinfo(&ui);
   2077 	freeauthinfo(&auth);
   2078 	return (rval);
   2079 }
   2080 
   2081 /*
   2082  * Retrieve the given file to outfile.
   2083  * Supports arguments of the form:
   2084  *	"host:path", "ftp://host/path"	if $ftpproxy, call fetch_url() else
   2085  *					call fetch_ftp()
   2086  *	"http://host/path"		call fetch_url() to use HTTP
   2087  *	"file:///path"			call fetch_url() to copy
   2088  *	"about:..."			print a message
   2089  *
   2090  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
   2091  * is still open (e.g, ftp xfer with trailing /)
   2092  */
   2093 static int
   2094 go_fetch(const char *url)
   2095 {
   2096 	char *proxyenv;
   2097 	char *p;
   2098 
   2099 #ifndef NO_ABOUT
   2100 	/*
   2101 	 * Check for about:*
   2102 	 */
   2103 	if (STRNEQUAL(url, ABOUT_URL)) {
   2104 		url += sizeof(ABOUT_URL) -1;
   2105 		if (strcasecmp(url, "ftp") == 0 ||
   2106 		    strcasecmp(url, "tnftp") == 0) {
   2107 			fputs(
   2108 "This version of ftp has been enhanced by Luke Mewburn <lukem (at) NetBSD.org>\n"
   2109 "for the NetBSD project.  Execute `man ftp' for more details.\n", ttyout);
   2110 		} else if (strcasecmp(url, "lukem") == 0) {
   2111 			fputs(
   2112 "Luke Mewburn is the author of most of the enhancements in this ftp client.\n"
   2113 "Please email feedback to <lukem (at) NetBSD.org>.\n", ttyout);
   2114 		} else if (strcasecmp(url, "netbsd") == 0) {
   2115 			fputs(
   2116 "NetBSD is a freely available and redistributable UNIX-like operating system.\n"
   2117 "For more information, see http://www.NetBSD.org/\n", ttyout);
   2118 		} else if (strcasecmp(url, "version") == 0) {
   2119 			fprintf(ttyout, "Version: %s %s%s\n",
   2120 			    FTP_PRODUCT, FTP_VERSION,
   2121 #ifdef INET6
   2122 			    ""
   2123 #else
   2124 			    " (-IPv6)"
   2125 #endif
   2126 			);
   2127 		} else {
   2128 			fprintf(ttyout, "`%s' is an interesting topic.\n", url);
   2129 		}
   2130 		fputs("\n", ttyout);
   2131 		return (0);
   2132 	}
   2133 #endif
   2134 
   2135 	/*
   2136 	 * Check for file:// and http:// URLs.
   2137 	 */
   2138 	if (STRNEQUAL(url, HTTP_URL)
   2139 #ifdef WITH_SSL
   2140 	    || STRNEQUAL(url, HTTPS_URL)
   2141 #endif
   2142 	    || STRNEQUAL(url, FILE_URL))
   2143 		return (fetch_url(url, NULL, NULL, NULL));
   2144 
   2145 	/*
   2146 	 * If it contains "://" but does not begin with ftp://
   2147 	 * or something that was already handled, then it's
   2148 	 * unsupported.
   2149 	 *
   2150 	 * If it contains ":" but not "://" then we assume the
   2151 	 * part before the colon is a host name, not an URL scheme,
   2152 	 * so we don't try to match that here.
   2153 	 */
   2154 	if ((p = strstr(url, "://")) != NULL && ! STRNEQUAL(url, FTP_URL))
   2155 		errx(1, "Unsupported URL scheme `%.*s'", (int)(p - url), url);
   2156 
   2157 	/*
   2158 	 * Try FTP URL-style and host:file arguments next.
   2159 	 * If ftpproxy is set with an FTP URL, use fetch_url()
   2160 	 * Othewise, use fetch_ftp().
   2161 	 */
   2162 	proxyenv = getoptionvalue("ftp_proxy");
   2163 	if (!EMPTYSTRING(proxyenv) && STRNEQUAL(url, FTP_URL))
   2164 		return (fetch_url(url, NULL, NULL, NULL));
   2165 
   2166 	return (fetch_ftp(url));
   2167 }
   2168 
   2169 /*
   2170  * Retrieve multiple files from the command line,
   2171  * calling go_fetch() for each file.
   2172  *
   2173  * If an ftp path has a trailing "/", the path will be cd-ed into and
   2174  * the connection remains open, and the function will return -1
   2175  * (to indicate the connection is alive).
   2176  * If an error occurs the return value will be the offset+1 in
   2177  * argv[] of the file that caused a problem (i.e, argv[x]
   2178  * returns x+1)
   2179  * Otherwise, 0 is returned if all files retrieved successfully.
   2180  */
   2181 int
   2182 auto_fetch(int argc, char *argv[])
   2183 {
   2184 	volatile int	argpos, rval;
   2185 
   2186 	argpos = rval = 0;
   2187 
   2188 	if (sigsetjmp(toplevel, 1)) {
   2189 		if (connected)
   2190 			disconnect(0, NULL);
   2191 		if (rval > 0)
   2192 			rval = argpos + 1;
   2193 		return (rval);
   2194 	}
   2195 	(void)xsignal(SIGINT, intr);
   2196 	(void)xsignal(SIGPIPE, lostpeer);
   2197 
   2198 	/*
   2199 	 * Loop through as long as there's files to fetch.
   2200 	 */
   2201 	for (; (rval == 0) && (argpos < argc); argpos++) {
   2202 		if (strchr(argv[argpos], ':') == NULL)
   2203 			break;
   2204 		redirect_loop = 0;
   2205 		if (!anonftp)
   2206 			anonftp = 2;	/* Handle "automatic" transfers. */
   2207 		rval = go_fetch(argv[argpos]);
   2208 		if (outfile != NULL && strcmp(outfile, "-") != 0
   2209 		    && outfile[0] != '|')
   2210 			outfile = NULL;
   2211 		if (rval > 0)
   2212 			rval = argpos + 1;
   2213 	}
   2214 
   2215 	if (connected && rval != -1)
   2216 		disconnect(0, NULL);
   2217 	return (rval);
   2218 }
   2219 
   2220 
   2221 /*
   2222  * Upload multiple files from the command line.
   2223  *
   2224  * If an error occurs the return value will be the offset+1 in
   2225  * argv[] of the file that caused a problem (i.e, argv[x]
   2226  * returns x+1)
   2227  * Otherwise, 0 is returned if all files uploaded successfully.
   2228  */
   2229 int
   2230 auto_put(int argc, char **argv, const char *uploadserver)
   2231 {
   2232 	char	*uargv[4], *path, *pathsep;
   2233 	int	 uargc, rval, argpos;
   2234 	size_t	 len;
   2235 	char	 cmdbuf[MAX_C_NAME];
   2236 
   2237 	(void)strlcpy(cmdbuf, "mput", sizeof(cmdbuf));
   2238 	uargv[0] = cmdbuf;
   2239 	uargv[1] = argv[0];
   2240 	uargc = 2;
   2241 	uargv[2] = uargv[3] = NULL;
   2242 	pathsep = NULL;
   2243 	rval = 1;
   2244 
   2245 	DPRINTF("auto_put: target `%s'\n", uploadserver);
   2246 
   2247 	path = ftp_strdup(uploadserver);
   2248 	len = strlen(path);
   2249 	if (path[len - 1] != '/' && path[len - 1] != ':') {
   2250 			/*
   2251 			 * make sure we always pass a directory to auto_fetch
   2252 			 */
   2253 		if (argc > 1) {		/* more than one file to upload */
   2254 			len = strlen(uploadserver) + 2;	/* path + "/" + "\0" */
   2255 			free(path);
   2256 			path = (char *)ftp_malloc(len);
   2257 			(void)strlcpy(path, uploadserver, len);
   2258 			(void)strlcat(path, "/", len);
   2259 		} else {		/* single file to upload */
   2260 			(void)strlcpy(cmdbuf, "put", sizeof(cmdbuf));
   2261 			uargv[0] = cmdbuf;
   2262 			pathsep = strrchr(path, '/');
   2263 			if (pathsep == NULL) {
   2264 				pathsep = strrchr(path, ':');
   2265 				if (pathsep == NULL) {
   2266 					warnx("Invalid URL `%s'", path);
   2267 					goto cleanup_auto_put;
   2268 				}
   2269 				pathsep++;
   2270 				uargv[2] = ftp_strdup(pathsep);
   2271 				pathsep[0] = '/';
   2272 			} else
   2273 				uargv[2] = ftp_strdup(pathsep + 1);
   2274 			pathsep[1] = '\0';
   2275 			uargc++;
   2276 		}
   2277 	}
   2278 	DPRINTF("auto_put: URL `%s' argv[2] `%s'\n",
   2279 	    path, STRorNULL(uargv[2]));
   2280 
   2281 			/* connect and cwd */
   2282 	rval = auto_fetch(1, &path);
   2283 	if(rval >= 0)
   2284 		goto cleanup_auto_put;
   2285 
   2286 	rval = 0;
   2287 
   2288 			/* target filename provided; upload 1 file */
   2289 			/* XXX : is this the best way? */
   2290 	if (uargc == 3) {
   2291 		uargv[1] = argv[0];
   2292 		put(uargc, uargv);
   2293 		if ((code / 100) != COMPLETE)
   2294 			rval = 1;
   2295 	} else {	/* otherwise a target dir: upload all files to it */
   2296 		for(argpos = 0; argv[argpos] != NULL; argpos++) {
   2297 			uargv[1] = argv[argpos];
   2298 			mput(uargc, uargv);
   2299 			if ((code / 100) != COMPLETE) {
   2300 				rval = argpos + 1;
   2301 				break;
   2302 			}
   2303 		}
   2304 	}
   2305 
   2306  cleanup_auto_put:
   2307 	free(path);
   2308 	FREEPTR(uargv[2]);
   2309 	return (rval);
   2310 }
   2311