Home | History | Annotate | Line # | Download | only in ftp
fetch.c revision 1.176
      1 /*	$NetBSD: fetch.c,v 1.176 2007/05/10 12:22:04 lukem Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1997-2007 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  * Redistribution and use in source and binary forms, with or without
     14  * modification, are permitted provided that the following conditions
     15  * are met:
     16  * 1. Redistributions of source code must retain the above copyright
     17  *    notice, this list of conditions and the following disclaimer.
     18  * 2. Redistributions in binary form must reproduce the above copyright
     19  *    notice, this list of conditions and the following disclaimer in the
     20  *    documentation and/or other materials provided with the distribution.
     21  * 3. All advertising materials mentioning features or use of this software
     22  *    must display the following acknowledgement:
     23  *	This product includes software developed by the NetBSD
     24  *	Foundation, Inc. and its contributors.
     25  * 4. Neither the name of The NetBSD Foundation nor the names of its
     26  *    contributors may be used to endorse or promote products derived
     27  *    from this software without specific prior written permission.
     28  *
     29  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     30  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     31  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     32  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     33  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     34  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     35  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     36  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     37  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     39  * POSSIBILITY OF SUCH DAMAGE.
     40  */
     41 
     42 #include <sys/cdefs.h>
     43 #ifndef lint
     44 __RCSID("$NetBSD: fetch.c,v 1.176 2007/05/10 12:22:04 lukem Exp $");
     45 #endif /* not lint */
     46 
     47 /*
     48  * FTP User Program -- Command line file retrieval
     49  */
     50 
     51 #include <sys/types.h>
     52 #include <sys/param.h>
     53 #include <sys/socket.h>
     54 #include <sys/stat.h>
     55 #include <sys/time.h>
     56 
     57 #include <netinet/in.h>
     58 
     59 #include <arpa/ftp.h>
     60 #include <arpa/inet.h>
     61 
     62 #include <ctype.h>
     63 #include <err.h>
     64 #include <errno.h>
     65 #include <netdb.h>
     66 #include <fcntl.h>
     67 #include <stdio.h>
     68 #include <stdlib.h>
     69 #include <string.h>
     70 #include <unistd.h>
     71 #include <time.h>
     72 
     73 #include "ftp_var.h"
     74 #include "version.h"
     75 
     76 typedef enum {
     77 	UNKNOWN_URL_T=-1,
     78 	HTTP_URL_T,
     79 	FTP_URL_T,
     80 	FILE_URL_T,
     81 	CLASSIC_URL_T
     82 } url_t;
     83 
     84 void		aborthttp(int);
     85 #ifndef NO_AUTH
     86 static int	auth_url(const char *, char **, const char *, const char *);
     87 static void	base64_encode(const unsigned char *, size_t, unsigned char *);
     88 #endif
     89 static int	go_fetch(const char *);
     90 static int	fetch_ftp(const char *);
     91 static int	fetch_url(const char *, const char *, char *, char *);
     92 static const char *match_token(const char **, const char *);
     93 static int	parse_url(const char *, const char *, url_t *, char **,
     94 			    char **, char **, char **, in_port_t *, char **);
     95 static void	url_decode(char *);
     96 
     97 static int	redirect_loop;
     98 
     99 
    100 #define	STRNEQUAL(a,b)	(strncasecmp((a), (b), sizeof((b))-1) == 0)
    101 #define	ISLWS(x)	((x)=='\r' || (x)=='\n' || (x)==' ' || (x)=='\t')
    102 #define	SKIPLWS(x)	do { while (ISLWS((*x))) x++; } while (0)
    103 
    104 
    105 #define	ABOUT_URL	"about:"	/* propaganda */
    106 #define	FILE_URL	"file://"	/* file URL prefix */
    107 #define	FTP_URL		"ftp://"	/* ftp URL prefix */
    108 #define	HTTP_URL	"http://"	/* http URL prefix */
    109 
    110 
    111 /*
    112  * Determine if token is the next word in buf (case insensitive).
    113  * If so, advance buf past the token and any trailing LWS, and
    114  * return a pointer to the token (in buf).  Otherwise, return NULL.
    115  * token may be preceded by LWS.
    116  * token must be followed by LWS or NUL.  (I.e, don't partial match).
    117  */
    118 static const char *
    119 match_token(const char **buf, const char *token)
    120 {
    121 	const char	*p, *orig;
    122 	size_t		tlen;
    123 
    124 	tlen = strlen(token);
    125 	p = *buf;
    126 	SKIPLWS(p);
    127 	orig = p;
    128 	if (strncasecmp(p, token, tlen) != 0)
    129 		return NULL;
    130 	p += tlen;
    131 	if (*p != '\0' && !ISLWS(*p))
    132 		return NULL;
    133 	SKIPLWS(p);
    134 	orig = *buf;
    135 	*buf = p;
    136 	return orig;
    137 }
    138 
    139 #ifndef NO_AUTH
    140 /*
    141  * Generate authorization response based on given authentication challenge.
    142  * Returns -1 if an error occurred, otherwise 0.
    143  * Sets response to a malloc(3)ed string; caller should free.
    144  */
    145 static int
    146 auth_url(const char *challenge, char **response, const char *guser,
    147 	const char *gpass)
    148 {
    149 	const char	*cp, *scheme, *errormsg;
    150 	char		*ep, *clear, *realm;
    151 	char		 user[BUFSIZ], *pass;
    152 	int		 rval;
    153 	size_t		 len, clen, rlen;
    154 
    155 	*response = NULL;
    156 	clear = realm = NULL;
    157 	rval = -1;
    158 	cp = challenge;
    159 	scheme = "Basic";	/* only support Basic authentication */
    160 
    161 	DPRINTF("auth_url: challenge `%s'\n", challenge);
    162 
    163 	if (! match_token(&cp, scheme)) {
    164 		warnx("Unsupported authentication challenge `%s'",
    165 		    challenge);
    166 		goto cleanup_auth_url;
    167 	}
    168 
    169 #define	REALM "realm=\""
    170 	if (STRNEQUAL(cp, REALM))
    171 		cp += sizeof(REALM) - 1;
    172 	else {
    173 		warnx("Unsupported authentication challenge `%s'",
    174 		    challenge);
    175 		goto cleanup_auth_url;
    176 	}
    177 /* XXX: need to improve quoted-string parsing to support \ quoting, etc. */
    178 	if ((ep = strchr(cp, '\"')) != NULL) {
    179 		size_t len = ep - cp;
    180 
    181 		realm = (char *)ftp_malloc(len + 1);
    182 		(void)strlcpy(realm, cp, len + 1);
    183 	} else {
    184 		warnx("Unsupported authentication challenge `%s'",
    185 		    challenge);
    186 		goto cleanup_auth_url;
    187 	}
    188 
    189 	fprintf(ttyout, "Username for `%s': ", realm);
    190 	if (guser != NULL) {
    191 		(void)strlcpy(user, guser, sizeof(user));
    192 		fprintf(ttyout, "%s\n", user);
    193 	} else {
    194 		(void)fflush(ttyout);
    195 		if (getline(stdin, user, sizeof(user), &errormsg) < 0) {
    196 			warnx("%s; can't authenticate", errormsg);
    197 			goto cleanup_auth_url;
    198 		}
    199 	}
    200 	if (gpass != NULL)
    201 		pass = (char *)gpass;
    202 	else {
    203 		pass = getpass("Password: ");
    204 		if (pass == NULL) {
    205 			warnx("Can't read password");
    206 			goto cleanup_auth_url;
    207 		}
    208 	}
    209 
    210 	clen = strlen(user) + strlen(pass) + 2;	/* user + ":" + pass + "\0" */
    211 	clear = (char *)ftp_malloc(clen);
    212 	(void)strlcpy(clear, user, clen);
    213 	(void)strlcat(clear, ":", clen);
    214 	(void)strlcat(clear, pass, clen);
    215 	if (gpass == NULL)
    216 		memset(pass, 0, strlen(pass));
    217 
    218 						/* scheme + " " + enc + "\0" */
    219 	rlen = strlen(scheme) + 1 + (clen + 2) * 4 / 3 + 1;
    220 	*response = (char *)ftp_malloc(rlen);
    221 	(void)strlcpy(*response, scheme, rlen);
    222 	len = strlcat(*response, " ", rlen);
    223 			/* use  `clen - 1'  to not encode the trailing NUL */
    224 	base64_encode((unsigned char *)clear, clen - 1,
    225 	    (unsigned char *)*response + len);
    226 	memset(clear, 0, clen);
    227 	rval = 0;
    228 
    229  cleanup_auth_url:
    230 	FREEPTR(clear);
    231 	FREEPTR(realm);
    232 	return (rval);
    233 }
    234 
    235 /*
    236  * Encode len bytes starting at clear using base64 encoding into encoded,
    237  * which should be at least ((len + 2) * 4 / 3 + 1) in size.
    238  */
    239 static void
    240 base64_encode(const unsigned char *clear, size_t len, unsigned char *encoded)
    241 {
    242 	static const unsigned char enc[] =
    243 	    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    244 	unsigned char	*cp;
    245 	int	 i;
    246 
    247 	cp = encoded;
    248 	for (i = 0; i < len; i += 3) {
    249 		*(cp++) = enc[((clear[i + 0] >> 2))];
    250 		*(cp++) = enc[((clear[i + 0] << 4) & 0x30)
    251 			    | ((clear[i + 1] >> 4) & 0x0f)];
    252 		*(cp++) = enc[((clear[i + 1] << 2) & 0x3c)
    253 			    | ((clear[i + 2] >> 6) & 0x03)];
    254 		*(cp++) = enc[((clear[i + 2]     ) & 0x3f)];
    255 	}
    256 	*cp = '\0';
    257 	while (i-- > len)
    258 		*(--cp) = '=';
    259 }
    260 #endif
    261 
    262 /*
    263  * Decode %xx escapes in given string, `in-place'.
    264  */
    265 static void
    266 url_decode(char *url)
    267 {
    268 	unsigned char *p, *q;
    269 
    270 	if (EMPTYSTRING(url))
    271 		return;
    272 	p = q = (unsigned char *)url;
    273 
    274 #define	HEXTOINT(x) (x - (isdigit(x) ? '0' : (islower(x) ? 'a' : 'A') - 10))
    275 	while (*p) {
    276 		if (p[0] == '%'
    277 		    && p[1] && isxdigit((unsigned char)p[1])
    278 		    && p[2] && isxdigit((unsigned char)p[2])) {
    279 			*q++ = HEXTOINT(p[1]) * 16 + HEXTOINT(p[2]);
    280 			p+=3;
    281 		} else
    282 			*q++ = *p++;
    283 	}
    284 	*q = '\0';
    285 }
    286 
    287 
    288 /*
    289  * Parse URL of form:
    290  *	<type>://[<user>[:<password>]@]<host>[:<port>][/<path>]
    291  * Returns -1 if a parse error occurred, otherwise 0.
    292  * It's the caller's responsibility to url_decode() the returned
    293  * user, pass and path.
    294  *
    295  * Sets type to url_t, each of the given char ** pointers to a
    296  * malloc(3)ed strings of the relevant section, and port to
    297  * the number given, or ftpport if ftp://, or httpport if http://.
    298  *
    299  * If <host> is surrounded by `[' and ']', it's parsed as an
    300  * IPv6 address (as per RFC 2732).
    301  *
    302  * XXX: this is not totally RFC 1738 compliant; <path> will have the
    303  * leading `/' unless it's an ftp:// URL, as this makes things easier
    304  * for file:// and http:// URLs. ftp:// URLs have the `/' between the
    305  * host and the URL-path removed, but any additional leading slashes
    306  * in the URL-path are retained (because they imply that we should
    307  * later do "CWD" with a null argument).
    308  *
    309  * Examples:
    310  *	 input URL			 output path
    311  *	 ---------			 -----------
    312  *	"ftp://host"			NULL
    313  *	"http://host/"			NULL
    314  *	"file://host/dir/file"		"dir/file"
    315  *	"ftp://host/"			""
    316  *	"ftp://host//"			NULL
    317  *	"ftp://host//dir/file"		"/dir/file"
    318  */
    319 static int
    320 parse_url(const char *url, const char *desc, url_t *type,
    321 		char **user, char **pass, char **host, char **port,
    322 		in_port_t *portnum, char **path)
    323 {
    324 	const char	*origurl;
    325 	char		*cp, *ep, *thost, *tport;
    326 	size_t		 len;
    327 
    328 	if (url == NULL || desc == NULL || type == NULL || user == NULL
    329 	    || pass == NULL || host == NULL || port == NULL || portnum == NULL
    330 	    || path == NULL)
    331 		errx(1, "parse_url: invoked with NULL argument!");
    332 
    333 	origurl = url;
    334 	*type = UNKNOWN_URL_T;
    335 	*user = *pass = *host = *port = *path = NULL;
    336 	*portnum = 0;
    337 	tport = NULL;
    338 
    339 	if (STRNEQUAL(url, HTTP_URL)) {
    340 		url += sizeof(HTTP_URL) - 1;
    341 		*type = HTTP_URL_T;
    342 		*portnum = HTTP_PORT;
    343 		tport = httpport;
    344 	} else if (STRNEQUAL(url, FTP_URL)) {
    345 		url += sizeof(FTP_URL) - 1;
    346 		*type = FTP_URL_T;
    347 		*portnum = FTP_PORT;
    348 		tport = ftpport;
    349 	} else if (STRNEQUAL(url, FILE_URL)) {
    350 		url += sizeof(FILE_URL) - 1;
    351 		*type = FILE_URL_T;
    352 	} else {
    353 		warnx("Invalid %s `%s'", desc, url);
    354  cleanup_parse_url:
    355 		FREEPTR(*user);
    356 		if (*pass != NULL)
    357 			memset(*pass, 0, strlen(*pass));
    358 		FREEPTR(*pass);
    359 		FREEPTR(*host);
    360 		FREEPTR(*port);
    361 		FREEPTR(*path);
    362 		return (-1);
    363 	}
    364 
    365 	if (*url == '\0')
    366 		return (0);
    367 
    368 			/* find [user[:pass]@]host[:port] */
    369 	ep = strchr(url, '/');
    370 	if (ep == NULL)
    371 		thost = ftp_strdup(url);
    372 	else {
    373 		len = ep - url;
    374 		thost = (char *)ftp_malloc(len + 1);
    375 		(void)strlcpy(thost, url, len + 1);
    376 		if (*type == FTP_URL_T)	/* skip first / for ftp URLs */
    377 			ep++;
    378 		*path = ftp_strdup(ep);
    379 	}
    380 
    381 	cp = strchr(thost, '@');	/* look for user[:pass]@ in URLs */
    382 	if (cp != NULL) {
    383 		if (*type == FTP_URL_T)
    384 			anonftp = 0;	/* disable anonftp */
    385 		*user = thost;
    386 		*cp = '\0';
    387 		thost = ftp_strdup(cp + 1);
    388 		cp = strchr(*user, ':');
    389 		if (cp != NULL) {
    390 			*cp = '\0';
    391 			*pass = ftp_strdup(cp + 1);
    392 		}
    393 		url_decode(*user);
    394 		if (*pass)
    395 			url_decode(*pass);
    396 	}
    397 
    398 #ifdef INET6
    399 			/*
    400 			 * Check if thost is an encoded IPv6 address, as per
    401 			 * RFC 2732:
    402 			 *	`[' ipv6-address ']'
    403 			 */
    404 	if (*thost == '[') {
    405 		cp = thost + 1;
    406 		if ((ep = strchr(cp, ']')) == NULL ||
    407 		    (ep[1] != '\0' && ep[1] != ':')) {
    408 			warnx("Invalid address `%s' in %s `%s'",
    409 			    thost, desc, origurl);
    410 			goto cleanup_parse_url;
    411 		}
    412 		len = ep - cp;		/* change `[xyz]' -> `xyz' */
    413 		memmove(thost, thost + 1, len);
    414 		thost[len] = '\0';
    415 		if (! isipv6addr(thost)) {
    416 			warnx("Invalid IPv6 address `%s' in %s `%s'",
    417 			    thost, desc, origurl);
    418 			goto cleanup_parse_url;
    419 		}
    420 		cp = ep + 1;
    421 		if (*cp == ':')
    422 			cp++;
    423 		else
    424 			cp = NULL;
    425 	} else
    426 #endif /* INET6 */
    427 	    if ((cp = strchr(thost, ':')) != NULL)
    428 		*cp++ =  '\0';
    429 	*host = thost;
    430 
    431 			/* look for [:port] */
    432 	if (cp != NULL) {
    433 		long	nport;
    434 
    435 		nport = parseport(cp, -1);
    436 		if (nport == -1) {
    437 			warnx("Unknown port `%s' in %s `%s'",
    438 			    cp, desc, origurl);
    439 			goto cleanup_parse_url;
    440 		}
    441 		*portnum = nport;
    442 		tport = cp;
    443 	}
    444 
    445 	if (tport != NULL)
    446 		*port = ftp_strdup(tport);
    447 	if (*path == NULL)
    448 		*path = ftp_strdup("/");
    449 
    450 	DPRINTF("parse_url: user `%s' pass `%s' host %s port %s(%d) "
    451 	    "path `%s'\n",
    452 	    *user ? *user : "<null>", *pass ? *pass : "<null>",
    453 	    *host ? *host : "<null>", *port ? *port : "<null>",
    454 	    *portnum ? *portnum : -1, *path ? *path : "<null>");
    455 
    456 	return (0);
    457 }
    458 
    459 sigjmp_buf	httpabort;
    460 
    461 /*
    462  * Retrieve URL, via a proxy if necessary, using HTTP.
    463  * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
    464  * http_proxy as appropriate.
    465  * Supports HTTP redirects.
    466  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
    467  * is still open (e.g, ftp xfer with trailing /)
    468  */
    469 static int
    470 fetch_url(const char *url, const char *proxyenv, char *proxyauth, char *wwwauth)
    471 {
    472 	struct addrinfo		hints, *res, *res0 = NULL;
    473 	int			error;
    474 	char			hbuf[NI_MAXHOST];
    475 	sigfunc volatile	oldintr;
    476 	sigfunc volatile	oldintp;
    477 	int volatile		s;
    478 	struct stat		sb;
    479 	int volatile		ischunked;
    480 	int volatile		isproxy;
    481 	int volatile		rval;
    482 	int volatile		hcode;
    483 	size_t			len;
    484 	static size_t		bufsize;
    485 	static char		*xferbuf;
    486 	const char		*cp, *token;
    487 	char			*ep;
    488 	char			buf[FTPBUFLEN];
    489 	const char		*errormsg;
    490 	char			*volatile savefile;
    491 	char			*volatile auth;
    492 	char			*volatile location;
    493 	char			*volatile message;
    494 	char			*user, *pass, *host, *port, *path;
    495 	char			*volatile decodedpath;
    496 	char			*puser, *ppass, *useragent;
    497 	off_t			hashbytes, rangestart, rangeend, entitylen;
    498 	int			(*volatile closefunc)(FILE *);
    499 	FILE			*volatile fin;
    500 	FILE			*volatile fout;
    501 	time_t			mtime;
    502 	url_t			urltype;
    503 	in_port_t		portnum;
    504 
    505 	oldintr = oldintp = NULL;
    506 	closefunc = NULL;
    507 	fin = fout = NULL;
    508 	s = -1;
    509 	savefile = NULL;
    510 	auth = location = message = NULL;
    511 	ischunked = isproxy = hcode = 0;
    512 	rval = 1;
    513 	user = pass = host = path = decodedpath = puser = ppass = NULL;
    514 
    515 	if (parse_url(url, "URL", &urltype, &user, &pass, &host, &port,
    516 	    &portnum, &path) == -1)
    517 		goto cleanup_fetch_url;
    518 
    519 	if (urltype == FILE_URL_T && ! EMPTYSTRING(host)
    520 	    && strcasecmp(host, "localhost") != 0) {
    521 		warnx("No support for non local file URL `%s'", url);
    522 		goto cleanup_fetch_url;
    523 	}
    524 
    525 	if (EMPTYSTRING(path)) {
    526 		if (urltype == FTP_URL_T) {
    527 			rval = fetch_ftp(url);
    528 			goto cleanup_fetch_url;
    529 		}
    530 		if (urltype != HTTP_URL_T || outfile == NULL)  {
    531 			warnx("Invalid URL (no file after host) `%s'", url);
    532 			goto cleanup_fetch_url;
    533 		}
    534 	}
    535 
    536 	decodedpath = ftp_strdup(path);
    537 	url_decode(decodedpath);
    538 
    539 	if (outfile)
    540 		savefile = ftp_strdup(outfile);
    541 	else {
    542 		cp = strrchr(decodedpath, '/');		/* find savefile */
    543 		if (cp != NULL)
    544 			savefile = ftp_strdup(cp + 1);
    545 		else
    546 			savefile = ftp_strdup(decodedpath);
    547 	}
    548 	if (EMPTYSTRING(savefile)) {
    549 		if (urltype == FTP_URL_T) {
    550 			rval = fetch_ftp(url);
    551 			goto cleanup_fetch_url;
    552 		}
    553 		warnx("No file after directory (you must specify an "
    554 		    "output file) `%s'", url);
    555 		goto cleanup_fetch_url;
    556 	} else {
    557 		DPRINTF("savefile `%s'\n", savefile);
    558 	}
    559 
    560 	restart_point = 0;
    561 	filesize = -1;
    562 	rangestart = rangeend = entitylen = -1;
    563 	mtime = -1;
    564 	if (restartautofetch) {
    565 		if (strcmp(savefile, "-") != 0 && *savefile != '|' &&
    566 		    stat(savefile, &sb) == 0)
    567 			restart_point = sb.st_size;
    568 	}
    569 	if (urltype == FILE_URL_T) {		/* file:// URLs */
    570 		direction = "copied";
    571 		fin = fopen(decodedpath, "r");
    572 		if (fin == NULL) {
    573 			warn("Can't open `%s'", decodedpath);
    574 			goto cleanup_fetch_url;
    575 		}
    576 		if (fstat(fileno(fin), &sb) == 0) {
    577 			mtime = sb.st_mtime;
    578 			filesize = sb.st_size;
    579 		}
    580 		if (restart_point) {
    581 			if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
    582 				warn("Can't seek to restart `%s'",
    583 				    decodedpath);
    584 				goto cleanup_fetch_url;
    585 			}
    586 		}
    587 		if (verbose) {
    588 			fprintf(ttyout, "Copying %s", decodedpath);
    589 			if (restart_point)
    590 				fprintf(ttyout, " (restarting at " LLF ")",
    591 				    (LLT)restart_point);
    592 			fputs("\n", ttyout);
    593 		}
    594 	} else {				/* ftp:// or http:// URLs */
    595 		char *leading;
    596 		int hasleading;
    597 
    598 		if (proxyenv == NULL) {
    599 			if (urltype == HTTP_URL_T)
    600 				proxyenv = getoptionvalue("http_proxy");
    601 			else if (urltype == FTP_URL_T)
    602 				proxyenv = getoptionvalue("ftp_proxy");
    603 		}
    604 		direction = "retrieved";
    605 		if (! EMPTYSTRING(proxyenv)) {			/* use proxy */
    606 			url_t purltype;
    607 			char *phost, *ppath;
    608 			char *pport, *no_proxy;
    609 
    610 			isproxy = 1;
    611 
    612 				/* check URL against list of no_proxied sites */
    613 			no_proxy = getoptionvalue("no_proxy");
    614 			if (! EMPTYSTRING(no_proxy)) {
    615 				char *np, *np_copy, *np_iter;
    616 				long np_port;
    617 				size_t hlen, plen;
    618 
    619 				np_iter = np_copy = ftp_strdup(no_proxy);
    620 				hlen = strlen(host);
    621 				while ((cp = strsep(&np_iter, " ,")) != NULL) {
    622 					if (*cp == '\0')
    623 						continue;
    624 					if ((np = strrchr(cp, ':')) != NULL) {
    625 						*np = '\0';
    626 						np_port =
    627 						    strtol(np + 1, &ep, 10);
    628 						if (*ep != '\0')
    629 							continue;
    630 						if (np_port != portnum)
    631 							continue;
    632 					}
    633 					plen = strlen(cp);
    634 					if (hlen < plen)
    635 						continue;
    636 					if (strncasecmp(host + hlen - plen,
    637 					    cp, plen) == 0) {
    638 						isproxy = 0;
    639 						break;
    640 					}
    641 				}
    642 				FREEPTR(np_copy);
    643 				if (isproxy == 0 && urltype == FTP_URL_T) {
    644 					rval = fetch_ftp(url);
    645 					goto cleanup_fetch_url;
    646 				}
    647 			}
    648 
    649 			if (isproxy) {
    650 				if (parse_url(proxyenv, "proxy URL", &purltype,
    651 				    &puser, &ppass, &phost, &pport, &portnum,
    652 				    &ppath) == -1)
    653 					goto cleanup_fetch_url;
    654 
    655 				if ((purltype != HTTP_URL_T
    656 				     && purltype != FTP_URL_T) ||
    657 				    EMPTYSTRING(phost) ||
    658 				    (! EMPTYSTRING(ppath)
    659 				     && strcmp(ppath, "/") != 0)) {
    660 					warnx("Malformed proxy URL `%s'",
    661 					    proxyenv);
    662 					FREEPTR(phost);
    663 					FREEPTR(pport);
    664 					FREEPTR(ppath);
    665 					goto cleanup_fetch_url;
    666 				}
    667 				if (isipv6addr(host) &&
    668 				    strchr(host, '%') != NULL) {
    669 					warnx(
    670 "Scoped address notation `%s' disallowed via web proxy",
    671 					    host);
    672 					FREEPTR(phost);
    673 					FREEPTR(pport);
    674 					FREEPTR(ppath);
    675 					goto cleanup_fetch_url;
    676 				}
    677 
    678 				FREEPTR(host);
    679 				host = phost;
    680 				FREEPTR(port);
    681 				port = pport;
    682 				FREEPTR(path);
    683 				path = ftp_strdup(url);
    684 				FREEPTR(ppath);
    685 			}
    686 		} /* ! EMPTYSTRING(proxyenv) */
    687 
    688 		memset(&hints, 0, sizeof(hints));
    689 		hints.ai_flags = 0;
    690 		hints.ai_family = family;
    691 		hints.ai_socktype = SOCK_STREAM;
    692 		hints.ai_protocol = 0;
    693 		error = getaddrinfo(host, NULL, &hints, &res0);
    694 		if (error) {
    695 			warnx("Can't lookup `%s': %s", host,
    696 			    (error == EAI_SYSTEM) ? strerror(errno)
    697 						  : gai_strerror(error));
    698 			goto cleanup_fetch_url;
    699 		}
    700 		if (res0->ai_canonname)
    701 			host = res0->ai_canonname;
    702 
    703 		s = -1;
    704 		for (res = res0; res; res = res->ai_next) {
    705 			ai_unmapped(res);
    706 			if (getnameinfo(res->ai_addr, res->ai_addrlen,
    707 			    hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0)
    708 				strlcpy(hbuf, "?", sizeof(hbuf));
    709 
    710 			if (verbose && res0->ai_next) {
    711 				fprintf(ttyout, "Trying %s...\n", hbuf);
    712 			}
    713 
    714 			((struct sockaddr_in *)res->ai_addr)->sin_port =
    715 			    htons(portnum);
    716 			s = socket(res->ai_family, SOCK_STREAM,
    717 			    res->ai_protocol);
    718 			if (s < 0) {
    719 				warn(
    720 				  "Can't create socket for connection to `%s'",
    721 				    hbuf);
    722 				continue;
    723 			}
    724 
    725 			if (ftp_connect(s, res->ai_addr, res->ai_addrlen) < 0) {
    726 				close(s);
    727 				s = -1;
    728 				continue;
    729 			}
    730 
    731 			/* success */
    732 			break;
    733 		}
    734 
    735 		if (s < 0) {
    736 			warnx("Can't connect to `%s'", host);
    737 			goto cleanup_fetch_url;
    738 		}
    739 
    740 		fin = fdopen(s, "r+");
    741 		/*
    742 		 * Construct and send the request.
    743 		 */
    744 		if (verbose)
    745 			fprintf(ttyout, "Requesting %s\n", url);
    746 		leading = "  (";
    747 		hasleading = 0;
    748 		if (isproxy) {
    749 			if (verbose) {
    750 				fprintf(ttyout, "%svia %s:%s", leading,
    751 				    host, port);
    752 				leading = ", ";
    753 				hasleading++;
    754 			}
    755 			fprintf(fin, "GET %s HTTP/1.0\r\n", path);
    756 			if (flushcache)
    757 				fprintf(fin, "Pragma: no-cache\r\n");
    758 		} else {
    759 			fprintf(fin, "GET %s HTTP/1.1\r\n", path);
    760 			if (strchr(host, ':')) {
    761 				char *h, *p;
    762 
    763 				/*
    764 				 * strip off IPv6 scope identifier, since it is
    765 				 * local to the node
    766 				 */
    767 				h = ftp_strdup(host);
    768 				if (isipv6addr(h) &&
    769 				    (p = strchr(h, '%')) != NULL) {
    770 					*p = '\0';
    771 				}
    772 				fprintf(fin, "Host: [%s]", h);
    773 				free(h);
    774 			} else
    775 				fprintf(fin, "Host: %s", host);
    776 			if (portnum != HTTP_PORT)
    777 				fprintf(fin, ":%u", portnum);
    778 			fprintf(fin, "\r\n");
    779 			fprintf(fin, "Accept: */*\r\n");
    780 			fprintf(fin, "Connection: close\r\n");
    781 			if (restart_point) {
    782 				fputs(leading, ttyout);
    783 				fprintf(fin, "Range: bytes=" LLF "-\r\n",
    784 				    (LLT)restart_point);
    785 				fprintf(ttyout, "restarting at " LLF,
    786 				    (LLT)restart_point);
    787 				leading = ", ";
    788 				hasleading++;
    789 			}
    790 			if (flushcache)
    791 				fprintf(fin, "Cache-Control: no-cache\r\n");
    792 		}
    793 		if ((useragent=getenv("FTPUSERAGENT")) != NULL) {
    794 			fprintf(fin, "User-Agent: %s\r\n", useragent);
    795 		} else {
    796 			fprintf(fin, "User-Agent: %s/%s\r\n",
    797 			    FTP_PRODUCT, FTP_VERSION);
    798 		}
    799 		if (wwwauth) {
    800 			if (verbose) {
    801 				fprintf(ttyout, "%swith authorization",
    802 				    leading);
    803 				leading = ", ";
    804 				hasleading++;
    805 			}
    806 			fprintf(fin, "Authorization: %s\r\n", wwwauth);
    807 		}
    808 		if (proxyauth) {
    809 			if (verbose) {
    810 				fprintf(ttyout,
    811 				    "%swith proxy authorization", leading);
    812 				leading = ", ";
    813 				hasleading++;
    814 			}
    815 			fprintf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
    816 		}
    817 		if (verbose && hasleading)
    818 			fputs(")\n", ttyout);
    819 		fprintf(fin, "\r\n");
    820 		if (fflush(fin) == EOF) {
    821 			warn("Writing HTTP request");
    822 			goto cleanup_fetch_url;
    823 		}
    824 
    825 				/* Read the response */
    826 		len = getline(fin, buf, sizeof(buf), &errormsg);
    827 		if (len < 0) {
    828 			if (*errormsg == '\n')
    829 				errormsg++;
    830 			warnx("Receiving HTTP reply: %s", errormsg);
    831 			goto cleanup_fetch_url;
    832 		}
    833 		while (len > 0 && (ISLWS(buf[len-1])))
    834 			buf[--len] = '\0';
    835 		DPRINTF("received `%s'\n", buf);
    836 
    837 				/* Determine HTTP response code */
    838 		cp = strchr(buf, ' ');
    839 		if (cp == NULL)
    840 			goto improper;
    841 		else
    842 			cp++;
    843 		hcode = strtol(cp, &ep, 10);
    844 		if (*ep != '\0' && !isspace((unsigned char)*ep))
    845 			goto improper;
    846 		message = ftp_strdup(cp);
    847 
    848 				/* Read the rest of the header. */
    849 		while (1) {
    850 			len = getline(fin, buf, sizeof(buf), &errormsg);
    851 			if (len < 0) {
    852 				if (*errormsg == '\n')
    853 					errormsg++;
    854 				warnx("Receiving HTTP reply: %s", errormsg);
    855 				goto cleanup_fetch_url;
    856 			}
    857 			while (len > 0 && (ISLWS(buf[len-1])))
    858 				buf[--len] = '\0';
    859 			if (len == 0)
    860 				break;
    861 			DPRINTF("received `%s'\n", buf);
    862 
    863 		/*
    864 		 * Look for some headers
    865 		 */
    866 
    867 			cp = buf;
    868 
    869 			if (match_token(&cp, "Content-Length:")) {
    870 				filesize = STRTOLL(cp, &ep, 10);
    871 				if (filesize < 0 || *ep != '\0')
    872 					goto improper;
    873 				DPRINTF("parsed len as: " LLF "\n",
    874 				    (LLT)filesize);
    875 
    876 			} else if (match_token(&cp, "Content-Range:")) {
    877 				if (! match_token(&cp, "bytes"))
    878 					goto improper;
    879 
    880 				if (*cp == '*')
    881 					cp++;
    882 				else {
    883 					rangestart = STRTOLL(cp, &ep, 10);
    884 					if (rangestart < 0 || *ep != '-')
    885 						goto improper;
    886 					cp = ep + 1;
    887 					rangeend = STRTOLL(cp, &ep, 10);
    888 					if (rangeend < 0 || rangeend < rangestart)
    889 						goto improper;
    890 					cp = ep;
    891 				}
    892 				if (*cp != '/')
    893 					goto improper;
    894 				cp++;
    895 				if (*cp == '*')
    896 					cp++;
    897 				else {
    898 					entitylen = STRTOLL(cp, &ep, 10);
    899 					if (entitylen < 0)
    900 						goto improper;
    901 					cp = ep;
    902 				}
    903 				if (*cp != '\0')
    904 					goto improper;
    905 
    906 #ifndef NO_DEBUG
    907 				if (ftp_debug) {
    908 					fprintf(ttyout, "parsed range as: ");
    909 					if (rangestart == -1)
    910 						fprintf(ttyout, "*");
    911 					else
    912 						fprintf(ttyout, LLF "-" LLF,
    913 						    (LLT)rangestart,
    914 						    (LLT)rangeend);
    915 					fprintf(ttyout, "/" LLF "\n", (LLT)entitylen);
    916 				}
    917 #endif
    918 				if (! restart_point) {
    919 					warnx(
    920 				    "Received unexpected Content-Range header");
    921 					goto cleanup_fetch_url;
    922 				}
    923 
    924 			} else if (match_token(&cp, "Last-Modified:")) {
    925 				struct tm parsed;
    926 				char *t;
    927 
    928 							/* RFC 1123 */
    929 				if ((t = strptime(cp,
    930 						"%a, %d %b %Y %H:%M:%S GMT",
    931 						&parsed))
    932 							/* RFC 850 */
    933 				    || (t = strptime(cp,
    934 						"%a, %d-%b-%y %H:%M:%S GMT",
    935 						&parsed))
    936 							/* asctime */
    937 				    || (t = strptime(cp,
    938 						"%a, %b %d %H:%M:%S %Y",
    939 						&parsed))) {
    940 					parsed.tm_isdst = -1;
    941 					if (*t == '\0')
    942 						mtime = timegm(&parsed);
    943 #ifndef NO_DEBUG
    944 					if (ftp_debug && mtime != -1) {
    945 						fprintf(ttyout,
    946 						    "parsed date as: %s",
    947 						    ctime(&mtime));
    948 					}
    949 #endif
    950 				}
    951 
    952 			} else if (match_token(&cp, "Location:")) {
    953 				location = ftp_strdup(cp);
    954 				DPRINTF("parsed location as `%s'\n", cp);
    955 
    956 			} else if (match_token(&cp, "Transfer-Encoding:")) {
    957 				if (match_token(&cp, "binary")) {
    958 					warnx(
    959 			"Bogus transfer encoding `binary' (fetching anyway)");
    960 					continue;
    961 				}
    962 				if (! (token = match_token(&cp, "chunked"))) {
    963 					warnx(
    964 				    "Unsupported transfer encoding `%s'",
    965 					    token);
    966 					goto cleanup_fetch_url;
    967 				}
    968 				ischunked++;
    969 				DPRINTF("using chunked encoding\n");
    970 
    971 			} else if (match_token(&cp, "Proxy-Authenticate:")
    972 				|| match_token(&cp, "WWW-Authenticate:")) {
    973 				if (! (token = match_token(&cp, "Basic"))) {
    974 					DPRINTF(
    975 				"skipping unknown auth scheme `%s'\n",
    976 						    token);
    977 					continue;
    978 				}
    979 				FREEPTR(auth);
    980 				auth = ftp_strdup(token);
    981 				DPRINTF("parsed auth as `%s'\n", cp);
    982 			}
    983 
    984 		}
    985 				/* finished parsing header */
    986 
    987 		switch (hcode) {
    988 		case 200:
    989 			break;
    990 		case 206:
    991 			if (! restart_point) {
    992 				warnx("Not expecting partial content header");
    993 				goto cleanup_fetch_url;
    994 			}
    995 			break;
    996 		case 300:
    997 		case 301:
    998 		case 302:
    999 		case 303:
   1000 		case 305:
   1001 		case 307:
   1002 			if (EMPTYSTRING(location)) {
   1003 				warnx(
   1004 				"No redirection Location provided by server");
   1005 				goto cleanup_fetch_url;
   1006 			}
   1007 			if (redirect_loop++ > 5) {
   1008 				warnx("Too many redirections requested");
   1009 				goto cleanup_fetch_url;
   1010 			}
   1011 			if (hcode == 305) {
   1012 				if (verbose)
   1013 					fprintf(ttyout, "Redirected via %s\n",
   1014 					    location);
   1015 				rval = fetch_url(url, location,
   1016 				    proxyauth, wwwauth);
   1017 			} else {
   1018 				if (verbose)
   1019 					fprintf(ttyout, "Redirected to %s\n",
   1020 					    location);
   1021 				rval = go_fetch(location);
   1022 			}
   1023 			goto cleanup_fetch_url;
   1024 #ifndef NO_AUTH
   1025 		case 401:
   1026 		case 407:
   1027 		    {
   1028 			char **authp;
   1029 			char *auser, *apass;
   1030 
   1031 			if (hcode == 401) {
   1032 				authp = &wwwauth;
   1033 				auser = user;
   1034 				apass = pass;
   1035 			} else {
   1036 				authp = &proxyauth;
   1037 				auser = puser;
   1038 				apass = ppass;
   1039 			}
   1040 			if (verbose || *authp == NULL ||
   1041 			    auser == NULL || apass == NULL)
   1042 				fprintf(ttyout, "%s\n", message);
   1043 			if (EMPTYSTRING(auth)) {
   1044 				warnx(
   1045 			    "No authentication challenge provided by server");
   1046 				goto cleanup_fetch_url;
   1047 			}
   1048 			if (*authp != NULL) {
   1049 				char reply[10];
   1050 
   1051 				fprintf(ttyout,
   1052 				    "Authorization failed. Retry (y/n)? ");
   1053 				if (getline(stdin, reply, sizeof(reply), NULL)
   1054 				    < 0) {
   1055 					goto cleanup_fetch_url;
   1056 				}
   1057 				if (tolower((unsigned char)reply[0]) != 'y')
   1058 					goto cleanup_fetch_url;
   1059 				auser = NULL;
   1060 				apass = NULL;
   1061 			}
   1062 			if (auth_url(auth, authp, auser, apass) == 0) {
   1063 				rval = fetch_url(url, proxyenv,
   1064 				    proxyauth, wwwauth);
   1065 				memset(*authp, 0, strlen(*authp));
   1066 				FREEPTR(*authp);
   1067 			}
   1068 			goto cleanup_fetch_url;
   1069 		    }
   1070 #endif
   1071 		default:
   1072 			if (message)
   1073 				warnx("Error retrieving file `%s'", message);
   1074 			else
   1075 				warnx("Unknown error retrieving file");
   1076 			goto cleanup_fetch_url;
   1077 		}
   1078 	}		/* end of ftp:// or http:// specific setup */
   1079 
   1080 			/* Open the output file. */
   1081 	if (strcmp(savefile, "-") == 0) {
   1082 		fout = stdout;
   1083 	} else if (*savefile == '|') {
   1084 		oldintp = xsignal(SIGPIPE, SIG_IGN);
   1085 		fout = popen(savefile + 1, "w");
   1086 		if (fout == NULL) {
   1087 			warn("Can't execute `%s'", savefile + 1);
   1088 			goto cleanup_fetch_url;
   1089 		}
   1090 		closefunc = pclose;
   1091 	} else {
   1092 		if ((rangeend != -1 && rangeend <= restart_point) ||
   1093 		    (rangestart == -1 && filesize != -1 && filesize <= restart_point)) {
   1094 			/* already done */
   1095 			if (verbose)
   1096 				fprintf(ttyout, "already done\n");
   1097 			rval = 0;
   1098 			goto cleanup_fetch_url;
   1099 		}
   1100 		if (restart_point && rangestart != -1) {
   1101 			if (entitylen != -1)
   1102 				filesize = entitylen;
   1103 			if (rangestart != restart_point) {
   1104 				warnx(
   1105 				    "Size of `%s' differs from save file `%s'",
   1106 				    url, savefile);
   1107 				goto cleanup_fetch_url;
   1108 			}
   1109 			fout = fopen(savefile, "a");
   1110 		} else
   1111 			fout = fopen(savefile, "w");
   1112 		if (fout == NULL) {
   1113 			warn("Can't open `%s'", savefile);
   1114 			goto cleanup_fetch_url;
   1115 		}
   1116 		closefunc = fclose;
   1117 	}
   1118 
   1119 			/* Trap signals */
   1120 	if (sigsetjmp(httpabort, 1))
   1121 		goto cleanup_fetch_url;
   1122 	(void)xsignal(SIGQUIT, psummary);
   1123 	oldintr = xsignal(SIGINT, aborthttp);
   1124 
   1125 	if (rcvbuf_size > bufsize) {
   1126 		if (xferbuf)
   1127 			(void)free(xferbuf);
   1128 		bufsize = rcvbuf_size;
   1129 		xferbuf = ftp_malloc(bufsize);
   1130 	}
   1131 
   1132 	bytes = 0;
   1133 	hashbytes = mark;
   1134 	progressmeter(-1);
   1135 
   1136 			/* Finally, suck down the file. */
   1137 	do {
   1138 		long chunksize;
   1139 
   1140 		chunksize = 0;
   1141 					/* read chunksize */
   1142 		if (ischunked) {
   1143 			if (fgets(xferbuf, bufsize, fin) == NULL) {
   1144 				warnx("Unexpected EOF reading chunksize");
   1145 				goto cleanup_fetch_url;
   1146 			}
   1147 			chunksize = strtol(xferbuf, &ep, 16);
   1148 
   1149 				/*
   1150 				 * XXX:	Work around bug in Apache 1.3.9 and
   1151 				 *	1.3.11, which incorrectly put trailing
   1152 				 *	space after the chunksize.
   1153 				 */
   1154 			while (*ep == ' ')
   1155 				ep++;
   1156 
   1157 			if (strcmp(ep, "\r\n") != 0) {
   1158 				warnx("Unexpected data following chunksize");
   1159 				goto cleanup_fetch_url;
   1160 			}
   1161 			DPRINTF("got chunksize of " LLF "\n", (LLT)chunksize);
   1162 			if (chunksize == 0)
   1163 				break;
   1164 		}
   1165 					/* transfer file or chunk */
   1166 		while (1) {
   1167 			struct timeval then, now, td;
   1168 			off_t bufrem;
   1169 
   1170 			if (rate_get)
   1171 				(void)gettimeofday(&then, NULL);
   1172 			bufrem = rate_get ? rate_get : bufsize;
   1173 			if (ischunked)
   1174 				bufrem = MIN(chunksize, bufrem);
   1175 			while (bufrem > 0) {
   1176 				len = fread(xferbuf, sizeof(char),
   1177 				    MIN(bufsize, bufrem), fin);
   1178 				if (len <= 0)
   1179 					goto chunkdone;
   1180 				bytes += len;
   1181 				bufrem -= len;
   1182 				if (fwrite(xferbuf, sizeof(char), len, fout)
   1183 				    != len) {
   1184 					warn("Writing `%s'", savefile);
   1185 					goto cleanup_fetch_url;
   1186 				}
   1187 				if (hash && !progress) {
   1188 					while (bytes >= hashbytes) {
   1189 						(void)putc('#', ttyout);
   1190 						hashbytes += mark;
   1191 					}
   1192 					(void)fflush(ttyout);
   1193 				}
   1194 				if (ischunked) {
   1195 					chunksize -= len;
   1196 					if (chunksize <= 0)
   1197 						break;
   1198 				}
   1199 			}
   1200 			if (rate_get) {
   1201 				while (1) {
   1202 					(void)gettimeofday(&now, NULL);
   1203 					timersub(&now, &then, &td);
   1204 					if (td.tv_sec > 0)
   1205 						break;
   1206 					usleep(1000000 - td.tv_usec);
   1207 				}
   1208 			}
   1209 			if (ischunked && chunksize <= 0)
   1210 				break;
   1211 		}
   1212 					/* read CRLF after chunk*/
   1213  chunkdone:
   1214 		if (ischunked) {
   1215 			if (fgets(xferbuf, bufsize, fin) == NULL)
   1216 				break;
   1217 			if (strcmp(xferbuf, "\r\n") != 0) {
   1218 				warnx("Unexpected data following chunk");
   1219 				goto cleanup_fetch_url;
   1220 			}
   1221 		}
   1222 	} while (ischunked);
   1223 	if (hash && !progress && bytes > 0) {
   1224 		if (bytes < mark)
   1225 			(void)putc('#', ttyout);
   1226 		(void)putc('\n', ttyout);
   1227 	}
   1228 	if (ferror(fin)) {
   1229 		warn("Reading file");
   1230 		goto cleanup_fetch_url;
   1231 	}
   1232 	progressmeter(1);
   1233 	(void)fflush(fout);
   1234 	if (closefunc == fclose && mtime != -1) {
   1235 		struct timeval tval[2];
   1236 
   1237 		(void)gettimeofday(&tval[0], NULL);
   1238 		tval[1].tv_sec = mtime;
   1239 		tval[1].tv_usec = 0;
   1240 		(*closefunc)(fout);
   1241 		fout = NULL;
   1242 
   1243 		if (utimes(savefile, tval) == -1) {
   1244 			fprintf(ttyout,
   1245 			    "Can't change modification time to %s",
   1246 			    asctime(localtime(&mtime)));
   1247 		}
   1248 	}
   1249 	if (bytes > 0)
   1250 		ptransfer(0);
   1251 	bytes = 0;
   1252 
   1253 	rval = 0;
   1254 	goto cleanup_fetch_url;
   1255 
   1256  improper:
   1257 	warnx("Improper response from `%s'", host);
   1258 
   1259  cleanup_fetch_url:
   1260 	if (oldintr)
   1261 		(void)xsignal(SIGINT, oldintr);
   1262 	if (oldintp)
   1263 		(void)xsignal(SIGPIPE, oldintp);
   1264 	if (fin != NULL)
   1265 		fclose(fin);
   1266 	else if (s != -1)
   1267 		close(s);
   1268 	if (closefunc != NULL && fout != NULL)
   1269 		(*closefunc)(fout);
   1270 	if (res0)
   1271 		freeaddrinfo(res0);
   1272 	FREEPTR(savefile);
   1273 	FREEPTR(user);
   1274 	if (pass != NULL)
   1275 		memset(pass, 0, strlen(pass));
   1276 	FREEPTR(pass);
   1277 	FREEPTR(host);
   1278 	FREEPTR(port);
   1279 	FREEPTR(path);
   1280 	FREEPTR(decodedpath);
   1281 	FREEPTR(puser);
   1282 	if (ppass != NULL)
   1283 		memset(ppass, 0, strlen(ppass));
   1284 	FREEPTR(ppass);
   1285 	FREEPTR(auth);
   1286 	FREEPTR(location);
   1287 	FREEPTR(message);
   1288 	return (rval);
   1289 }
   1290 
   1291 /*
   1292  * Abort a HTTP retrieval
   1293  */
   1294 void
   1295 aborthttp(int notused)
   1296 {
   1297 	char msgbuf[100];
   1298 	size_t len;
   1299 
   1300 	sigint_raised = 1;
   1301 	alarmtimer(0);
   1302 	len = strlcpy(msgbuf, "\nHTTP fetch aborted.\n", sizeof(msgbuf));
   1303 	write(fileno(ttyout), msgbuf, len);
   1304 	siglongjmp(httpabort, 1);
   1305 }
   1306 
   1307 /*
   1308  * Retrieve ftp URL or classic ftp argument using FTP.
   1309  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
   1310  * is still open (e.g, ftp xfer with trailing /)
   1311  */
   1312 static int
   1313 fetch_ftp(const char *url)
   1314 {
   1315 	char		*cp, *xargv[5], rempath[MAXPATHLEN];
   1316 	char		*host, *path, *dir, *file, *user, *pass;
   1317 	char		*port;
   1318 	int		 dirhasglob, filehasglob, rval, type, xargc;
   1319 	int		 oanonftp, oautologin;
   1320 	in_port_t	 portnum;
   1321 	url_t		 urltype;
   1322 
   1323 	host = path = dir = file = user = pass = NULL;
   1324 	port = NULL;
   1325 	rval = 1;
   1326 	type = TYPE_I;
   1327 
   1328 	if (STRNEQUAL(url, FTP_URL)) {
   1329 		if ((parse_url(url, "URL", &urltype, &user, &pass,
   1330 		    &host, &port, &portnum, &path) == -1) ||
   1331 		    (user != NULL && *user == '\0') ||
   1332 		    EMPTYSTRING(host)) {
   1333 			warnx("Invalid URL `%s'", url);
   1334 			goto cleanup_fetch_ftp;
   1335 		}
   1336 		/*
   1337 		 * Note: Don't url_decode(path) here.  We need to keep the
   1338 		 * distinction between "/" and "%2F" until later.
   1339 		 */
   1340 
   1341 					/* check for trailing ';type=[aid]' */
   1342 		if (! EMPTYSTRING(path) && (cp = strrchr(path, ';')) != NULL) {
   1343 			if (strcasecmp(cp, ";type=a") == 0)
   1344 				type = TYPE_A;
   1345 			else if (strcasecmp(cp, ";type=i") == 0)
   1346 				type = TYPE_I;
   1347 			else if (strcasecmp(cp, ";type=d") == 0) {
   1348 				warnx(
   1349 			    "Directory listing via a URL is not supported");
   1350 				goto cleanup_fetch_ftp;
   1351 			} else {
   1352 				warnx("Invalid suffix `%s' in URL `%s'", cp,
   1353 				    url);
   1354 				goto cleanup_fetch_ftp;
   1355 			}
   1356 			*cp = 0;
   1357 		}
   1358 	} else {			/* classic style `[user@]host:[file]' */
   1359 		urltype = CLASSIC_URL_T;
   1360 		host = ftp_strdup(url);
   1361 		cp = strchr(host, '@');
   1362 		if (cp != NULL) {
   1363 			*cp = '\0';
   1364 			user = host;
   1365 			anonftp = 0;	/* disable anonftp */
   1366 			host = ftp_strdup(cp + 1);
   1367 		}
   1368 		cp = strchr(host, ':');
   1369 		if (cp != NULL) {
   1370 			*cp = '\0';
   1371 			path = ftp_strdup(cp + 1);
   1372 		}
   1373 	}
   1374 	if (EMPTYSTRING(host))
   1375 		goto cleanup_fetch_ftp;
   1376 
   1377 			/* Extract the file and (if present) directory name. */
   1378 	dir = path;
   1379 	if (! EMPTYSTRING(dir)) {
   1380 		/*
   1381 		 * If we are dealing with classic `[user@]host:[path]' syntax,
   1382 		 * then a path of the form `/file' (resulting from input of the
   1383 		 * form `host:/file') means that we should do "CWD /" before
   1384 		 * retrieving the file.  So we set dir="/" and file="file".
   1385 		 *
   1386 		 * But if we are dealing with URLs like `ftp://host/path' then
   1387 		 * a path of the form `/file' (resulting from a URL of the form
   1388 		 * `ftp://host//file') means that we should do `CWD ' (with an
   1389 		 * empty argument) before retrieving the file.  So we set
   1390 		 * dir="" and file="file".
   1391 		 *
   1392 		 * If the path does not contain / at all, we set dir=NULL.
   1393 		 * (We get a path without any slashes if we are dealing with
   1394 		 * classic `[user@]host:[file]' or URL `ftp://host/file'.)
   1395 		 *
   1396 		 * In all other cases, we set dir to a string that does not
   1397 		 * include the final '/' that separates the dir part from the
   1398 		 * file part of the path.  (This will be the empty string if
   1399 		 * and only if we are dealing with a path of the form `/file'
   1400 		 * resulting from an URL of the form `ftp://host//file'.)
   1401 		 */
   1402 		cp = strrchr(dir, '/');
   1403 		if (cp == dir && urltype == CLASSIC_URL_T) {
   1404 			file = cp + 1;
   1405 			dir = "/";
   1406 		} else if (cp != NULL) {
   1407 			*cp++ = '\0';
   1408 			file = cp;
   1409 		} else {
   1410 			file = dir;
   1411 			dir = NULL;
   1412 		}
   1413 	} else
   1414 		dir = NULL;
   1415 	if (urltype == FTP_URL_T && file != NULL) {
   1416 		url_decode(file);
   1417 		/* but still don't url_decode(dir) */
   1418 	}
   1419 	DPRINTF("fetch_ftp: user `%s' pass `%s' host %s port %s "
   1420 	    "path `%s' dir `%s' file `%s'\n",
   1421 	    user ? user : "<null>", pass ? pass : "<null>",
   1422 	    host ? host : "<null>", port ? port : "<null>",
   1423 	    path ? path : "<null>",
   1424 	    dir ? dir : "<null>", file ? file : "<null>");
   1425 
   1426 	dirhasglob = filehasglob = 0;
   1427 	if (doglob && urltype == CLASSIC_URL_T) {
   1428 		if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
   1429 			dirhasglob = 1;
   1430 		if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
   1431 			filehasglob = 1;
   1432 	}
   1433 
   1434 			/* Set up the connection */
   1435 	oanonftp = anonftp;
   1436 	if (connected)
   1437 		disconnect(0, NULL);
   1438 	anonftp = oanonftp;
   1439 	xargv[0] = (char *)getprogname();	/* XXX discards const */
   1440 	xargv[1] = host;
   1441 	xargv[2] = NULL;
   1442 	xargc = 2;
   1443 	if (port) {
   1444 		xargv[2] = port;
   1445 		xargv[3] = NULL;
   1446 		xargc = 3;
   1447 	}
   1448 	oautologin = autologin;
   1449 		/* don't autologin in setpeer(), use ftp_login() below */
   1450 	autologin = 0;
   1451 	setpeer(xargc, xargv);
   1452 	autologin = oautologin;
   1453 	if ((connected == 0) ||
   1454 	    (connected == 1 && !ftp_login(host, user, pass))) {
   1455 		warnx("Can't connect or login to host `%s'", host);
   1456 		goto cleanup_fetch_ftp;
   1457 	}
   1458 
   1459 	switch (type) {
   1460 	case TYPE_A:
   1461 		setascii(1, xargv);
   1462 		break;
   1463 	case TYPE_I:
   1464 		setbinary(1, xargv);
   1465 		break;
   1466 	default:
   1467 		errx(1, "fetch_ftp: unknown transfer type %d", type);
   1468 	}
   1469 
   1470 		/*
   1471 		 * Change directories, if necessary.
   1472 		 *
   1473 		 * Note: don't use EMPTYSTRING(dir) below, because
   1474 		 * dir=="" means something different from dir==NULL.
   1475 		 */
   1476 	if (dir != NULL && !dirhasglob) {
   1477 		char *nextpart;
   1478 
   1479 		/*
   1480 		 * If we are dealing with a classic `[user@]host:[path]'
   1481 		 * (urltype is CLASSIC_URL_T) then we have a raw directory
   1482 		 * name (not encoded in any way) and we can change
   1483 		 * directories in one step.
   1484 		 *
   1485 		 * If we are dealing with an `ftp://host/path' URL
   1486 		 * (urltype is FTP_URL_T), then RFC 1738 says we need to
   1487 		 * send a separate CWD command for each unescaped "/"
   1488 		 * in the path, and we have to interpret %hex escaping
   1489 		 * *after* we find the slashes.  It's possible to get
   1490 		 * empty components here, (from multiple adjacent
   1491 		 * slashes in the path) and RFC 1738 says that we should
   1492 		 * still do `CWD ' (with a null argument) in such cases.
   1493 		 *
   1494 		 * Many ftp servers don't support `CWD ', so if there's an
   1495 		 * error performing that command, bail out with a descriptive
   1496 		 * message.
   1497 		 *
   1498 		 * Examples:
   1499 		 *
   1500 		 * host:			dir="", urltype=CLASSIC_URL_T
   1501 		 *		logged in (to default directory)
   1502 		 * host:file			dir=NULL, urltype=CLASSIC_URL_T
   1503 		 *		"RETR file"
   1504 		 * host:dir/			dir="dir", urltype=CLASSIC_URL_T
   1505 		 *		"CWD dir", logged in
   1506 		 * ftp://host/			dir="", urltype=FTP_URL_T
   1507 		 *		logged in (to default directory)
   1508 		 * ftp://host/dir/		dir="dir", urltype=FTP_URL_T
   1509 		 *		"CWD dir", logged in
   1510 		 * ftp://host/file		dir=NULL, urltype=FTP_URL_T
   1511 		 *		"RETR file"
   1512 		 * ftp://host//file		dir="", urltype=FTP_URL_T
   1513 		 *		"CWD ", "RETR file"
   1514 		 * host:/file			dir="/", urltype=CLASSIC_URL_T
   1515 		 *		"CWD /", "RETR file"
   1516 		 * ftp://host///file		dir="/", urltype=FTP_URL_T
   1517 		 *		"CWD ", "CWD ", "RETR file"
   1518 		 * ftp://host/%2F/file		dir="%2F", urltype=FTP_URL_T
   1519 		 *		"CWD /", "RETR file"
   1520 		 * ftp://host/foo/file		dir="foo", urltype=FTP_URL_T
   1521 		 *		"CWD foo", "RETR file"
   1522 		 * ftp://host/foo/bar/file	dir="foo/bar"
   1523 		 *		"CWD foo", "CWD bar", "RETR file"
   1524 		 * ftp://host//foo/bar/file	dir="/foo/bar"
   1525 		 *		"CWD ", "CWD foo", "CWD bar", "RETR file"
   1526 		 * ftp://host/foo//bar/file	dir="foo//bar"
   1527 		 *		"CWD foo", "CWD ", "CWD bar", "RETR file"
   1528 		 * ftp://host/%2F/foo/bar/file	dir="%2F/foo/bar"
   1529 		 *		"CWD /", "CWD foo", "CWD bar", "RETR file"
   1530 		 * ftp://host/%2Ffoo/bar/file	dir="%2Ffoo/bar"
   1531 		 *		"CWD /foo", "CWD bar", "RETR file"
   1532 		 * ftp://host/%2Ffoo%2Fbar/file	dir="%2Ffoo%2Fbar"
   1533 		 *		"CWD /foo/bar", "RETR file"
   1534 		 * ftp://host/%2Ffoo%2Fbar%2Ffile	dir=NULL
   1535 		 *		"RETR /foo/bar/file"
   1536 		 *
   1537 		 * Note that we don't need `dir' after this point.
   1538 		 */
   1539 		do {
   1540 			if (urltype == FTP_URL_T) {
   1541 				nextpart = strchr(dir, '/');
   1542 				if (nextpart) {
   1543 					*nextpart = '\0';
   1544 					nextpart++;
   1545 				}
   1546 				url_decode(dir);
   1547 			} else
   1548 				nextpart = NULL;
   1549 			DPRINTF("dir `%s', nextpart `%s'\n",
   1550 			    dir ? dir : "<null>",
   1551 			    nextpart ? nextpart : "<null>");
   1552 			if (urltype == FTP_URL_T || *dir != '\0') {
   1553 				xargv[0] = "cd";
   1554 				xargv[1] = dir;
   1555 				xargv[2] = NULL;
   1556 				dirchange = 0;
   1557 				cd(2, xargv);
   1558 				if (! dirchange) {
   1559 					if (*dir == '\0' && code == 500)
   1560 						fprintf(stderr,
   1561 "\n"
   1562 "ftp: The `CWD ' command (without a directory), which is required by\n"
   1563 "     RFC 1738 to support the empty directory in the URL pathname (`//'),\n"
   1564 "     conflicts with the server's conformance to RFC 959.\n"
   1565 "     Try the same URL without the `//' in the URL pathname.\n"
   1566 "\n");
   1567 					goto cleanup_fetch_ftp;
   1568 				}
   1569 			}
   1570 			dir = nextpart;
   1571 		} while (dir != NULL);
   1572 	}
   1573 
   1574 	if (EMPTYSTRING(file)) {
   1575 		rval = -1;
   1576 		goto cleanup_fetch_ftp;
   1577 	}
   1578 
   1579 	if (dirhasglob) {
   1580 		(void)strlcpy(rempath, dir,	sizeof(rempath));
   1581 		(void)strlcat(rempath, "/",	sizeof(rempath));
   1582 		(void)strlcat(rempath, file,	sizeof(rempath));
   1583 		file = rempath;
   1584 	}
   1585 
   1586 			/* Fetch the file(s). */
   1587 	xargc = 2;
   1588 	xargv[0] = "get";
   1589 	xargv[1] = file;
   1590 	xargv[2] = NULL;
   1591 	if (dirhasglob || filehasglob) {
   1592 		int ointeractive;
   1593 
   1594 		ointeractive = interactive;
   1595 		interactive = 0;
   1596 		if (restartautofetch)
   1597 			xargv[0] = "mreget";
   1598 		else
   1599 			xargv[0] = "mget";
   1600 		mget(xargc, xargv);
   1601 		interactive = ointeractive;
   1602 	} else {
   1603 		if (outfile == NULL) {
   1604 			cp = strrchr(file, '/');	/* find savefile */
   1605 			if (cp != NULL)
   1606 				outfile = cp + 1;
   1607 			else
   1608 				outfile = file;
   1609 		}
   1610 		xargv[2] = (char *)outfile;
   1611 		xargv[3] = NULL;
   1612 		xargc++;
   1613 		if (restartautofetch)
   1614 			reget(xargc, xargv);
   1615 		else
   1616 			get(xargc, xargv);
   1617 	}
   1618 
   1619 	if ((code / 100) == COMPLETE)
   1620 		rval = 0;
   1621 
   1622  cleanup_fetch_ftp:
   1623 	FREEPTR(port);
   1624 	FREEPTR(host);
   1625 	FREEPTR(path);
   1626 	FREEPTR(user);
   1627 	if (pass)
   1628 		memset(pass, 0, strlen(pass));
   1629 	FREEPTR(pass);
   1630 	return (rval);
   1631 }
   1632 
   1633 /*
   1634  * Retrieve the given file to outfile.
   1635  * Supports arguments of the form:
   1636  *	"host:path", "ftp://host/path"	if $ftpproxy, call fetch_url() else
   1637  *					call fetch_ftp()
   1638  *	"http://host/path"		call fetch_url() to use HTTP
   1639  *	"file:///path"			call fetch_url() to copy
   1640  *	"about:..."			print a message
   1641  *
   1642  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
   1643  * is still open (e.g, ftp xfer with trailing /)
   1644  */
   1645 static int
   1646 go_fetch(const char *url)
   1647 {
   1648 	char *proxy;
   1649 
   1650 #ifndef NO_ABOUT
   1651 	/*
   1652 	 * Check for about:*
   1653 	 */
   1654 	if (STRNEQUAL(url, ABOUT_URL)) {
   1655 		url += sizeof(ABOUT_URL) -1;
   1656 		if (strcasecmp(url, "ftp") == 0 ||
   1657 		    strcasecmp(url, "tnftp") == 0) {
   1658 			fputs(
   1659 "This version of ftp has been enhanced by Luke Mewburn <lukem (at) NetBSD.org>\n"
   1660 "for the NetBSD project.  Execute `man ftp' for more details.\n", ttyout);
   1661 		} else if (strcasecmp(url, "lukem") == 0) {
   1662 			fputs(
   1663 "Luke Mewburn is the author of most of the enhancements in this ftp client.\n"
   1664 "Please email feedback to <lukem (at) NetBSD.org>.\n", ttyout);
   1665 		} else if (strcasecmp(url, "netbsd") == 0) {
   1666 			fputs(
   1667 "NetBSD is a freely available and redistributable UNIX-like operating system.\n"
   1668 "For more information, see http://www.NetBSD.org/\n", ttyout);
   1669 		} else if (strcasecmp(url, "version") == 0) {
   1670 			fprintf(ttyout, "Version: %s %s%s\n",
   1671 			    FTP_PRODUCT, FTP_VERSION,
   1672 #ifdef INET6
   1673 			    ""
   1674 #else
   1675 			    " (-IPv6)"
   1676 #endif
   1677 			);
   1678 		} else {
   1679 			fprintf(ttyout, "`%s' is an interesting topic.\n", url);
   1680 		}
   1681 		fputs("\n", ttyout);
   1682 		return (0);
   1683 	}
   1684 #endif
   1685 
   1686 	/*
   1687 	 * Check for file:// and http:// URLs.
   1688 	 */
   1689 	if (STRNEQUAL(url, HTTP_URL) || STRNEQUAL(url, FILE_URL))
   1690 		return (fetch_url(url, NULL, NULL, NULL));
   1691 
   1692 	/*
   1693 	 * Try FTP URL-style and host:file arguments next.
   1694 	 * If ftpproxy is set with an FTP URL, use fetch_url()
   1695 	 * Othewise, use fetch_ftp().
   1696 	 */
   1697 	proxy = getoptionvalue("ftp_proxy");
   1698 	if (!EMPTYSTRING(proxy) && STRNEQUAL(url, FTP_URL))
   1699 		return (fetch_url(url, NULL, NULL, NULL));
   1700 
   1701 	return (fetch_ftp(url));
   1702 }
   1703 
   1704 /*
   1705  * Retrieve multiple files from the command line,
   1706  * calling go_fetch() for each file.
   1707  *
   1708  * If an ftp path has a trailing "/", the path will be cd-ed into and
   1709  * the connection remains open, and the function will return -1
   1710  * (to indicate the connection is alive).
   1711  * If an error occurs the return value will be the offset+1 in
   1712  * argv[] of the file that caused a problem (i.e, argv[x]
   1713  * returns x+1)
   1714  * Otherwise, 0 is returned if all files retrieved successfully.
   1715  */
   1716 int
   1717 auto_fetch(int argc, char *argv[])
   1718 {
   1719 	volatile int	argpos, rval;
   1720 
   1721 	argpos = rval = 0;
   1722 
   1723 	if (sigsetjmp(toplevel, 1)) {
   1724 		if (connected)
   1725 			disconnect(0, NULL);
   1726 		if (rval > 0)
   1727 			rval = argpos + 1;
   1728 		return (rval);
   1729 	}
   1730 	(void)xsignal(SIGINT, intr);
   1731 	(void)xsignal(SIGPIPE, lostpeer);
   1732 
   1733 	/*
   1734 	 * Loop through as long as there's files to fetch.
   1735 	 */
   1736 	for (; (rval == 0) && (argpos < argc); argpos++) {
   1737 		if (strchr(argv[argpos], ':') == NULL)
   1738 			break;
   1739 		redirect_loop = 0;
   1740 		if (!anonftp)
   1741 			anonftp = 2;	/* Handle "automatic" transfers. */
   1742 		rval = go_fetch(argv[argpos]);
   1743 		if (outfile != NULL && strcmp(outfile, "-") != 0
   1744 		    && outfile[0] != '|')
   1745 			outfile = NULL;
   1746 		if (rval > 0)
   1747 			rval = argpos + 1;
   1748 	}
   1749 
   1750 	if (connected && rval != -1)
   1751 		disconnect(0, NULL);
   1752 	return (rval);
   1753 }
   1754 
   1755 
   1756 /*
   1757  * Upload multiple files from the command line.
   1758  *
   1759  * If an error occurs the return value will be the offset+1 in
   1760  * argv[] of the file that caused a problem (i.e, argv[x]
   1761  * returns x+1)
   1762  * Otherwise, 0 is returned if all files uploaded successfully.
   1763  */
   1764 int
   1765 auto_put(int argc, char **argv, const char *uploadserver)
   1766 {
   1767 	char	*uargv[4], *path, *pathsep;
   1768 	int	 uargc, rval, argpos;
   1769 	size_t	 len;
   1770 
   1771 	uargc = 0;
   1772 	uargv[uargc++] = "mput";
   1773 	uargv[uargc++] = argv[0];
   1774 	uargv[2] = uargv[3] = NULL;
   1775 	pathsep = NULL;
   1776 	rval = 1;
   1777 
   1778 	DPRINTF("auto_put: target `%s'\n", uploadserver);
   1779 
   1780 	path = ftp_strdup(uploadserver);
   1781 	len = strlen(path);
   1782 	if (path[len - 1] != '/' && path[len - 1] != ':') {
   1783 			/*
   1784 			 * make sure we always pass a directory to auto_fetch
   1785 			 */
   1786 		if (argc > 1) {		/* more than one file to upload */
   1787 			len = strlen(uploadserver) + 2;	/* path + "/" + "\0" */
   1788 			free(path);
   1789 			path = (char *)ftp_malloc(len);
   1790 			(void)strlcpy(path, uploadserver, len);
   1791 			(void)strlcat(path, "/", len);
   1792 		} else {		/* single file to upload */
   1793 			uargv[0] = "put";
   1794 			pathsep = strrchr(path, '/');
   1795 			if (pathsep == NULL) {
   1796 				pathsep = strrchr(path, ':');
   1797 				if (pathsep == NULL) {
   1798 					warnx("Invalid URL `%s'", path);
   1799 					goto cleanup_auto_put;
   1800 				}
   1801 				pathsep++;
   1802 				uargv[2] = ftp_strdup(pathsep);
   1803 				pathsep[0] = '/';
   1804 			} else
   1805 				uargv[2] = ftp_strdup(pathsep + 1);
   1806 			pathsep[1] = '\0';
   1807 			uargc++;
   1808 		}
   1809 	}
   1810 	DPRINTF("auto_put: URL `%s' argv[2] `%s'\n",
   1811 	    path, uargv[2] ? uargv[2] : "<null>");
   1812 
   1813 			/* connect and cwd */
   1814 	rval = auto_fetch(1, &path);
   1815 	if(rval >= 0)
   1816 		goto cleanup_auto_put;
   1817 
   1818 	rval = 0;
   1819 
   1820 			/* target filename provided; upload 1 file */
   1821 			/* XXX : is this the best way? */
   1822 	if (uargc == 3) {
   1823 		uargv[1] = argv[0];
   1824 		put(uargc, uargv);
   1825 		if ((code / 100) != COMPLETE)
   1826 			rval = 1;
   1827 	} else {	/* otherwise a target dir: upload all files to it */
   1828 		for(argpos = 0; argv[argpos] != NULL; argpos++) {
   1829 			uargv[1] = argv[argpos];
   1830 			mput(uargc, uargv);
   1831 			if ((code / 100) != COMPLETE) {
   1832 				rval = argpos + 1;
   1833 				break;
   1834 			}
   1835 		}
   1836 	}
   1837 
   1838  cleanup_auto_put:
   1839 	free(path);
   1840 	FREEPTR(uargv[2]);
   1841 	return (rval);
   1842 }
   1843