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