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