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