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