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