Home | History | Annotate | Line # | Download | only in ftp
fetch.c revision 1.71
      1 /*	$NetBSD: fetch.c,v 1.71 1999/09/21 13:17:22 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.71 1999/09/21 13:17:22 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;
    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 	len = strlen(user) + strlen(pass) + 2;	/* user + ":" + pass + "\0" */
    177 	clear = (char *)xmalloc(len);
    178 	snprintf(clear, len, "%s:%s", user, pass);
    179 	if (gpass == NULL)
    180 		memset(pass, '\0', strlen(pass));
    181 
    182 						/* scheme + " " + enc + "\0" */
    183 	len = strlen(scheme) + 1 + (len + 2) * 4 / 3 + 1;
    184 	*response = (char *)xmalloc(len);
    185 	len = snprintf(*response, len, "%s ", scheme);
    186 	base64_encode(clear, strlen(clear), *response + len);
    187 	memset(clear, '\0', strlen(clear));
    188 	rval = 0;
    189 
    190 cleanup_auth_url:
    191 	FREEPTR(clear);
    192 	FREEPTR(line);
    193 	FREEPTR(realm);
    194 	return (rval);
    195 }
    196 
    197 /*
    198  * Encode len bytes starting at clear using base64 encoding into encoded,
    199  * which should be at least ((len + 2) * 4 / 3 + 1) in size.
    200  */
    201 void
    202 base64_encode(clear, len, encoded)
    203 	const char	*clear;
    204 	size_t		 len;
    205 	char		*encoded;
    206 {
    207 	static const char enc[] =
    208 	    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    209 	char *cp;
    210 	int i;
    211 
    212 	cp = encoded;
    213 	for (i = 0; i < len; i += 3) {
    214 		*(cp++) = enc[((clear[i + 0] >> 2))];
    215 		*(cp++) = enc[((clear[i + 0] << 4) & 0x30)
    216 			    | ((clear[i + 1] >> 4) & 0x0f)];
    217 		*(cp++) = enc[((clear[i + 1] << 2) & 0x3c)
    218 			    | ((clear[i + 2] >> 6) & 0x03)];
    219 		*(cp++) = enc[((clear[i + 2]     ) & 0x3f)];
    220 	}
    221 	*cp = '\0';
    222 	while (i-- > len)
    223 		*(--cp) = '=';
    224 }
    225 
    226 /*
    227  * Decode %xx escapes in given string, `in-place'.
    228  */
    229 static void
    230 url_decode(url)
    231 	char *url;
    232 {
    233 	unsigned char *p, *q;
    234 
    235 	if (EMPTYSTRING(url))
    236 		return;
    237 	p = q = url;
    238 
    239 #define HEXTOINT(x) (x - (isdigit(x) ? '0' : (islower(x) ? 'a' : 'A') - 10))
    240 	while (*p) {
    241 		if (p[0] == '%'
    242 		    && p[1] && isxdigit((unsigned char)p[1])
    243 		    && p[2] && isxdigit((unsigned char)p[2])) {
    244 			*q++ = HEXTOINT(p[1]) * 16 + HEXTOINT(p[2]);
    245 			p+=3;
    246 		} else
    247 			*q++ = *p++;
    248 	}
    249 	*q = '\0';
    250 }
    251 
    252 
    253 /*
    254  * Parse URL of form:
    255  *	<type>://[<user>[:<password>@]]<host>[:<port>][/<path>]
    256  * Returns -1 if a parse error occurred, otherwise 0.
    257  * It's the caller's responsibility to url_decode() the returned
    258  * user, pass and path.
    259  *
    260  * Sets type to url_t, each of the given char ** pointers to a
    261  * malloc(3)ed strings of the relevant section, and port to
    262  * the number given, or ftpport if ftp://, or httpport if http://.
    263  *
    264  * If <host> is surrounded by `[' and ']', it's parsed as an
    265  * IPv6 address (as per draft-ietf-ipngwg-url-literal-01.txt).
    266  *
    267  * XXX: this is not totally RFC 1738 compliant; <path> will have the
    268  * leading `/' unless it's an ftp:// URL, as this makes things easier
    269  * for file:// and http:// URLs. ftp:// URLs have the `/' between the
    270  * host and the url-path removed, but any additional leading slashes
    271  * in the url-path are retained (because they imply that we should
    272  * later do "CWD" with a null argument).
    273  *
    274  * Examples:
    275  *	 input url			 output path
    276  *	 ---------			 -----------
    277  *	"ftp://host"			NULL
    278  *	"http://host/"			NULL
    279  *	"file://host/dir/file"		"dir/file"
    280  *	"ftp://host/"			""
    281  *	"ftp://host//"			NULL
    282  *	"ftp://host//dir/file"		"/dir/file"
    283  */
    284 static int
    285 parse_url(url, desc, type, user, pass, host, port, path)
    286 	const char	 *url;
    287 	const char	 *desc;
    288 	url_t		 *type;
    289 	char		**user;
    290 	char		**pass;
    291 	char		**host;
    292 	char		**port;
    293 	char		**path;
    294 {
    295 	char *cp, *ep, *thost, *tport;
    296 	size_t len;
    297 
    298 	if (url == NULL || desc == NULL || type == NULL || user == NULL
    299 	    || pass == NULL || host == NULL || port == NULL || path == NULL)
    300 		errx(1, "parse_url: invoked with NULL argument!");
    301 
    302 	*type = UNKNOWN_URL_T;
    303 	*user = *pass = *host = *port = *path = NULL;
    304 	tport = NULL;
    305 
    306 	if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) {
    307 		url += sizeof(HTTP_URL) - 1;
    308 		*type = HTTP_URL_T;
    309 		tport = httpport;
    310 	} else if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
    311 		url += sizeof(FTP_URL) - 1;
    312 		*type = FTP_URL_T;
    313 		tport = ftpport;
    314 	} else if (strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
    315 		url += sizeof(FILE_URL) - 1;
    316 		*type = FILE_URL_T;
    317 	} else {
    318 		warnx("Invalid %s `%s'", desc, url);
    319 cleanup_parse_url:
    320 		FREEPTR(*user);
    321 		FREEPTR(*pass);
    322 		FREEPTR(*host);
    323 		FREEPTR(*port);
    324 		FREEPTR(*path);
    325 		return (-1);
    326 	}
    327 
    328 	if (*url == '\0')
    329 		return (0);
    330 
    331 			/* find [user[:pass]@]host[:port] */
    332 	ep = strchr(url, '/');
    333 	if (ep == NULL)
    334 		thost = xstrdup(url);
    335 	else {
    336 		len = ep - url;
    337 		thost = (char *)xmalloc(len + 1);
    338 		strncpy(thost, url, len);
    339 		thost[len] = '\0';
    340 		if (*type == FTP_URL_T)	/* skip first / for ftp URLs */
    341 			ep++;
    342 		*path = xstrdup(ep);
    343 	}
    344 
    345 	cp = strchr(thost, '@');	/* look for user[:pass]@ in URLs */
    346 	if (cp != NULL) {
    347 		if (*type == FTP_URL_T)
    348 			anonftp = 0;	/* disable anonftp */
    349 		*user = thost;
    350 		*cp = '\0';
    351 		thost = xstrdup(cp + 1);
    352 		cp = strchr(*user, ':');
    353 		if (cp != NULL) {
    354 			*cp = '\0';
    355 			*pass = xstrdup(cp + 1);
    356 		}
    357 	}
    358 
    359 #ifdef INET6
    360 			/*
    361 			 * Check if thost is an encoded IPv6 address, as per
    362 			 * draft-ietf-ipngwg-url-literal-01.txt:
    363 			 *	`[' ipv6-address ']'
    364 			 */
    365 	if (*thost == '[') {
    366 		cp = thost + 1;
    367 		if ((ep = strchr(cp, ']')) == NULL ||
    368 		    (ep[1] != '\0' && ep[1] != '\0')) {
    369 			warnx("Invalid address `%s' in %s `%s'",
    370 			    thost, desc, url);
    371 			goto cleanup_parse_url;
    372 		}
    373 		len = ep - cp;		/* change `[xxx]' -> `xxx' */
    374 		memmove(thost, thost + 1, len);
    375 		thost[len] = '\0';
    376 		if (! isipv6addr(thost)) {
    377 			warnx("Invalid IPv6 address `%s' in %s `%s'",
    378 			    thost, desc, url);
    379 			goto cleanup_parse_url;
    380 		}
    381 		cp = ep + 1;
    382 		if (*cp == ':')
    383 			cp++;
    384 		else
    385 			cp = NULL;
    386 	} else
    387 #endif /* INET6 */
    388 	    if ((cp = strchr(thost, ':')) != NULL)
    389 		*cp++ =  '\0';
    390 	*host = thost;
    391 
    392 			/* look for [:port] */
    393 	if (cp != NULL) {
    394 		long nport;
    395 
    396 		nport = strtol(cp, &ep, 10);
    397 		if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0') {
    398 			warnx("Invalid port `%s' in %s `%s'", cp, desc, url);
    399 			goto cleanup_parse_url;
    400 		}
    401 		tport = cp;
    402 	}
    403 	if (tport != NULL);
    404 		*port = xstrdup(tport);
    405 
    406 	if (debug)
    407 		fprintf(ttyout,
    408 		    "parse_url: user `%s' pass `%s' host %s:%s path `%s'\n",
    409 		    *user ? *user : "<null>", *pass ? *pass : "<null>",
    410 		    *host ? *host : "<null>", *port ? *port : "<null>",
    411 		    *path ? *path : "<null>");
    412 
    413 	return (0);
    414 }
    415 
    416 
    417 jmp_buf	httpabort;
    418 
    419 /*
    420  * Retrieve URL, via a proxy if necessary, using HTTP.
    421  * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
    422  * http_proxy as appropriate.
    423  * Supports HTTP redirects.
    424  * Returns -1 on failure, 0 on completed xfer, 1 if ftp connection
    425  * is still open (e.g, ftp xfer with trailing /)
    426  */
    427 static int
    428 fetch_url(url, proxyenv, proxyauth, wwwauth)
    429 	const char	*url;
    430 	const char	*proxyenv;
    431 	char		*proxyauth;
    432 	char		*wwwauth;
    433 {
    434 #ifdef NI_NUMERICHOST
    435 	struct addrinfo		hints, *res = NULL;
    436 	int			error;
    437 #else
    438 	struct sockaddr_in	sin;
    439 	struct hostent		*hp = NULL;
    440 #endif
    441 	volatile sig_t		oldintr, oldintp;
    442 	volatile int		s;
    443 	int 			ischunked, isproxy, rval, hcode;
    444 	size_t			len;
    445 	char			*cp, *ep, *buf, *savefile;
    446 	char			*auth, *location, *message;
    447 	char			*user, *pass, *host, *port, *path, *decodedpath;
    448 	char			*puser, *ppass;
    449 	off_t			hashbytes;
    450 	int			 (*closefunc) __P((FILE *));
    451 	FILE			*fin, *fout;
    452 	time_t			mtime;
    453 	url_t			urltype;
    454 	in_port_t		portnum;
    455 
    456 	closefunc = NULL;
    457 	fin = fout = NULL;
    458 	s = -1;
    459 	buf = savefile = NULL;
    460 	auth = location = message = NULL;
    461 	ischunked = isproxy = hcode = 0;
    462 	rval = 1;
    463 	user = pass = host = path = decodedpath = puser = ppass = NULL;
    464 
    465 #ifdef __GNUC__			/* shut up gcc warnings */
    466 	(void)&closefunc;
    467 	(void)&fin;
    468 	(void)&fout;
    469 	(void)&buf;
    470 	(void)&savefile;
    471 	(void)&rval;
    472 	(void)&isproxy;
    473 	(void)&hcode;
    474 	(void)&ischunked;
    475 	(void)&message;
    476 	(void)&location;
    477 	(void)&auth;
    478 	(void)&decodedpath;
    479 #endif
    480 
    481 	if (parse_url(url, "URL", &urltype, &user, &pass, &host, &port, &path)
    482 	    == -1)
    483 		goto cleanup_fetch_url;
    484 	portnum = strtol(port, &ep, 10);
    485 	if (*ep || port == ep) {
    486 		struct servent *svp = getservbyname(port, "tcp");
    487 		if (svp != NULL)
    488 			portnum = ntohs(svp->s_port);
    489 	}
    490 
    491 	if (urltype == FILE_URL_T && ! EMPTYSTRING(host)
    492 	    && strcasecmp(host, "localhost") != 0) {
    493 		warnx("No support for non local file URL `%s'", url);
    494 		goto cleanup_fetch_url;
    495 	}
    496 
    497 	if (EMPTYSTRING(path)) {
    498 		if (urltype == FTP_URL_T) {
    499 			rval = fetch_ftp(url);
    500 			goto cleanup_fetch_url;
    501 		}
    502 		if (urltype != HTTP_URL_T || outfile == NULL)  {
    503 			warnx("Invalid URL (no file after host) `%s'", url);
    504 			goto cleanup_fetch_url;
    505 		}
    506 	}
    507 
    508 	decodedpath = xstrdup(path);
    509 	url_decode(decodedpath);
    510 
    511 	if (outfile)
    512 		savefile = xstrdup(outfile);
    513 	else {
    514 		cp = strrchr(decodedpath, '/');		/* find savefile */
    515 		if (cp != NULL)
    516 			savefile = xstrdup(cp + 1);
    517 		else
    518 			savefile = xstrdup(decodedpath);
    519 	}
    520 	if (EMPTYSTRING(savefile)) {
    521 		if (urltype == FTP_URL_T) {
    522 			rval = fetch_ftp(url);
    523 			goto cleanup_fetch_url;
    524 		}
    525 		warnx("Invalid URL (no file after directory) `%s'", url);
    526 		goto cleanup_fetch_url;
    527 	} else {
    528 		if (debug)
    529 			fprintf(ttyout, "got savefile as `%s'\n", savefile);
    530 	}
    531 
    532 	filesize = -1;
    533 	mtime = -1;
    534 	if (urltype == FILE_URL_T) {		/* file:// URLs */
    535 		struct stat sb;
    536 
    537 		direction = "copied";
    538 		fin = fopen(decodedpath, "r");
    539 		if (fin == NULL) {
    540 			warn("Cannot open file `%s'", decodedpath);
    541 			goto cleanup_fetch_url;
    542 		}
    543 		if (fstat(fileno(fin), &sb) == 0) {
    544 			mtime = sb.st_mtime;
    545 			filesize = sb.st_size;
    546 		}
    547 		if (verbose)
    548 			fprintf(ttyout, "Copying %s\n", decodedpath);
    549 	} else {				/* ftp:// or http:// URLs */
    550 		char *leading;
    551 		int hasleading;
    552 
    553 		if (proxyenv == NULL) {
    554 			if (urltype == HTTP_URL_T)
    555 				proxyenv = httpproxy;
    556 			else if (urltype == FTP_URL_T)
    557 				proxyenv = ftpproxy;
    558 		}
    559 		direction = "retrieved";
    560 		if (proxyenv != NULL) {				/* use proxy */
    561 			url_t purltype;
    562 			char *phost, *ppath;
    563 			char *pport;
    564 
    565 			isproxy = 1;
    566 
    567 				/* check URL against list of no_proxied sites */
    568 			if (no_proxy != NULL) {
    569 				char *np, *np_copy;
    570 				long np_port;
    571 				size_t hlen, plen;
    572 
    573 				np_copy = xstrdup(no_proxy);
    574 				hlen = strlen(host);
    575 				while ((cp = strsep(&np_copy, " ,")) != NULL) {
    576 					if (*cp == '\0')
    577 						continue;
    578 					if ((np = strrchr(cp, ':')) != NULL) {
    579 						*np = '\0';
    580 						np_port =
    581 						    strtol(np + 1, &ep, 10);
    582 						if (*ep != '\0')
    583 							continue;
    584 						if (portnum !=
    585 						    htons((in_port_t)np_port))
    586 							continue;
    587 					}
    588 					plen = strlen(cp);
    589 					if (strncasecmp(host + hlen - plen,
    590 					    cp, plen) == 0) {
    591 						isproxy = 0;
    592 						break;
    593 					}
    594 				}
    595 				FREEPTR(np_copy);
    596 			}
    597 
    598 			if (isproxy) {
    599 				if (parse_url(proxyenv, "proxy URL", &purltype,
    600 				    &puser, &ppass, &phost, &pport, &ppath)
    601 				    == -1)
    602 					goto cleanup_fetch_url;
    603 
    604 				if ((purltype != HTTP_URL_T
    605 				     && purltype != FTP_URL_T) ||
    606 				    EMPTYSTRING(phost) ||
    607 				    (! EMPTYSTRING(ppath)
    608 				     && strcmp(ppath, "/") != 0)) {
    609 					warnx("Malformed proxy URL `%s'",
    610 					    proxyenv);
    611 					FREEPTR(phost);
    612 					FREEPTR(pport);
    613 					FREEPTR(ppath);
    614 					goto cleanup_fetch_url;
    615 				}
    616 
    617 				FREEPTR(host);
    618 				host = phost;
    619 				FREEPTR(port);
    620 				port = pport;
    621 				FREEPTR(path);
    622 				path = xstrdup(url);
    623 				FREEPTR(ppath);
    624 			}
    625 		} /* proxyenv != NULL */
    626 
    627 #ifndef NI_NUMERICHOST
    628 		memset(&sin, 0, sizeof(sin));
    629 		sin.sin_family = AF_INET;
    630 
    631 		if (isdigit((unsigned char)host[0])) {
    632 			if (inet_aton(host, &sin.sin_addr) == 0) {
    633 				warnx("Invalid IP address `%s'", host);
    634 				goto cleanup_fetch_url;
    635 			}
    636 		} else {
    637 			hp = gethostbyname(host);
    638 			if (hp == NULL) {
    639 				warnx("%s: %s", host, hstrerror(h_errno));
    640 				goto cleanup_fetch_url;
    641 			}
    642 			if (hp->h_addrtype != AF_INET) {
    643 				warnx("`%s': not an Internet address?", host);
    644 				goto cleanup_fetch_url;
    645 			}
    646 			if (hp->h_length > sizeof(sin.sin_addr))
    647 				hp->h_length = sizeof(sin.sin_addr);
    648 			memcpy(&sin.sin_addr, hp->h_addr, hp->h_length);
    649 		}
    650 
    651 		if (port == NULL) {
    652 			warnx("Unknown port for URL `%s'", url);
    653 			goto cleanup_fetch_url;
    654 		}
    655 		portnum = strtol(port, &ep, 10);
    656 		if (*ep || port == ep) {
    657 			struct servent *svp = getservbyname(port, "tcp");
    658 			if (svp != NULL)
    659 				portnum = ntohs(svp->s_port);
    660 		}
    661 		sin.sin_port = portnum;
    662 
    663 		s = socket(AF_INET, SOCK_STREAM, 0);
    664 		if (s == -1) {
    665 			warn("Can't create socket");
    666 			goto cleanup_fetch_url;
    667 		}
    668 
    669 		while (xconnect(s, (struct sockaddr *)&sin,
    670 		    sizeof(sin)) == -1) {
    671 			if (errno == EINTR)
    672 				continue;
    673 			if (hp && hp->h_addr_list[1]) {
    674 				int oerrno = errno;
    675 				char *ia;
    676 
    677 				ia = inet_ntoa(sin.sin_addr);
    678 				errno = oerrno;
    679 				warn("Connect to address `%s'", ia);
    680 				hp->h_addr_list++;
    681 				memcpy(&sin.sin_addr, hp->h_addr_list[0],
    682 				    (size_t)hp->h_length);
    683 				if (verbose)
    684 					fprintf(ttyout, "Trying %s...\n",
    685 					    inet_ntoa(sin.sin_addr));
    686 				(void)close(s);
    687 				s = socket(AF_INET, SOCK_STREAM, 0);
    688 				if (s < 0) {
    689 					warn("Can't create socket");
    690 					goto cleanup_fetch_url;
    691 				}
    692 				continue;
    693 			}
    694 			warn("Can't connect to `%s'", host);
    695 			goto cleanup_fetch_url;
    696 		}
    697 #else
    698 		memset(&hints, 0, sizeof(hints));
    699 		hints.ai_flags = 0;
    700 		hints.ai_family = AF_UNSPEC;
    701 		hints.ai_socktype = SOCK_STREAM;
    702 		hints.ai_protocol = 0;
    703 		error = getaddrinfo(host, port, &hints, &res);
    704 		if (error) {
    705 			warnx(gai_strerror(error));
    706 			goto cleanup_fetch_url;
    707 		}
    708 
    709 		while (1) {
    710 			s = socket(res->ai_family,
    711 				   res->ai_socktype, res->ai_protocol);
    712 			if (s < 0) {
    713 				warn("Can't create socket");
    714 				goto cleanup_fetch_url;
    715 			}
    716 
    717 			if (xconnect(s, res->ai_addr, res->ai_addrlen) < 0) {
    718 				char hbuf[MAXHOSTNAMELEN];
    719 				getnameinfo(res->ai_addr, res->ai_addrlen,
    720 					hbuf, sizeof(hbuf), NULL, 0,
    721 					NI_NUMERICHOST);
    722 				warn("Connect to address `%s'", hbuf);
    723 				close(s);
    724 				res = res->ai_next;
    725 				if (res) {
    726 					getnameinfo(res->ai_addr,
    727 					    res->ai_addrlen, hbuf, sizeof(hbuf),
    728 					    NULL, 0, NI_NUMERICHOST);
    729 					if (verbose)
    730 						fprintf(ttyout,
    731 						    "Trying %s...\n", hbuf);
    732 					continue;
    733 				}
    734 				warn("Can't connect to %s", host);
    735 				goto cleanup_fetch_url;
    736 			}
    737 
    738 			break;
    739 		}
    740 #endif
    741 
    742 
    743 		fin = fdopen(s, "r+");
    744 		/*
    745 		 * Construct and send the request.
    746 		 */
    747 		if (verbose)
    748 			fprintf(ttyout, "Requesting %s\n", url);
    749 		leading = "  (";
    750 		hasleading = 0;
    751 		if (isproxy) {
    752 			if (verbose) {
    753 				fprintf(ttyout, "%svia %s:%s", leading,
    754 				    host, port);
    755 				leading = ", ";
    756 				hasleading++;
    757 			}
    758 			fprintf(fin, "GET %s HTTP/1.0\r\n", path);
    759 			if (flushcache)
    760 				fprintf(fin, "Pragma: no-cache\r\n");
    761 		} else {
    762 			struct utsname unam;
    763 
    764 			fprintf(fin, "GET %s HTTP/1.1\r\n", path);
    765 			fprintf(fin, "Host: %s:%s\r\n", host, port);
    766 			fprintf(fin, "Accept: */*\r\n");
    767 			if (uname(&unam) != -1) {
    768 				fprintf(fin, "User-Agent: %s-%s/ftp\r\n",
    769 				    unam.sysname, unam.release);
    770 			}
    771 			fprintf(fin, "Connection: close\r\n");
    772 			if (flushcache)
    773 				fprintf(fin, "Cache-Control: no-cache\r\n");
    774 		}
    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: %qd\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 = mkgmtime(&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) != NULL
    994 				    && tolower(reply[0]) != 'y')
    995 					goto cleanup_fetch_url;
    996 				auser = NULL;
    997 				apass = NULL;
    998 			}
    999 			if (auth_url(auth, authp, auser, apass) == 0) {
   1000 				rval = fetch_url(url, proxyenv,
   1001 				    proxyauth, wwwauth);
   1002 				memset(*authp, '\0', strlen(*authp));
   1003 				FREEPTR(*authp);
   1004 			}
   1005 			goto cleanup_fetch_url;
   1006 		    }
   1007 		default:
   1008 			if (message)
   1009 				warnx("Error retrieving file - `%s'", message);
   1010 			else
   1011 				warnx("Unknown error retrieving file");
   1012 			goto cleanup_fetch_url;
   1013 		}
   1014 	}		/* end of ftp:// or http:// specific setup */
   1015 
   1016 	oldintr = oldintp = NULL;
   1017 
   1018 			/* Open the output file. */
   1019 	if (strcmp(savefile, "-") == 0) {
   1020 		fout = stdout;
   1021 	} else if (*savefile == '|') {
   1022 		oldintp = signal(SIGPIPE, SIG_IGN);
   1023 		fout = popen(savefile + 1, "w");
   1024 		if (fout == NULL) {
   1025 			warn("Can't run `%s'", savefile + 1);
   1026 			goto cleanup_fetch_url;
   1027 		}
   1028 		closefunc = pclose;
   1029 	} else {
   1030 		fout = fopen(savefile, "w");
   1031 		if (fout == NULL) {
   1032 			warn("Can't open `%s'", savefile);
   1033 			goto cleanup_fetch_url;
   1034 		}
   1035 		closefunc = fclose;
   1036 	}
   1037 
   1038 			/* Trap signals */
   1039 	if (setjmp(httpabort)) {
   1040 		if (oldintr)
   1041 			(void)signal(SIGINT, oldintr);
   1042 		if (oldintp)
   1043 			(void)signal(SIGPIPE, oldintp);
   1044 		goto cleanup_fetch_url;
   1045 	}
   1046 	oldintr = signal(SIGINT, aborthttp);
   1047 
   1048 	bytes = 0;
   1049 	hashbytes = mark;
   1050 	progressmeter(-1);
   1051 
   1052 			/* Finally, suck down the file. */
   1053 	buf = xmalloc(BUFSIZ + 1);
   1054 	do {
   1055 		ssize_t chunksize;
   1056 
   1057 		chunksize = 0;
   1058 					/* read chunksize */
   1059 		if (ischunked) {
   1060 			if (fgets(buf, BUFSIZ, fin) == NULL) {
   1061 				warnx("Unexpected EOF reading chunksize");
   1062 				goto cleanup_fetch_url;
   1063 			}
   1064 			chunksize = strtol(buf, &ep, 16);
   1065 			if (strcmp(ep, "\r\n") != 0) {
   1066 				warnx("Unexpected data following chunksize");
   1067 				goto cleanup_fetch_url;
   1068 			}
   1069 			if (debug)
   1070 				fprintf(ttyout,
   1071 #ifndef NO_QUAD
   1072 				    "got chunksize of %qd\n",
   1073 				    (long long)chunksize);
   1074 #else
   1075 				    "got chunksize of %ld\n",
   1076 				    (long)chunksize);
   1077 #endif
   1078 			if (chunksize == 0)
   1079 				break;
   1080 		}
   1081 					/* transfer file or chunk */
   1082 		while (1) {
   1083 			struct timeval then, now, td;
   1084 			off_t bufrem;
   1085 
   1086 			if (rate_get)
   1087 				(void)gettimeofday(&then, NULL);
   1088 			bufrem = rate_get ? rate_get : BUFSIZ;
   1089 			while (bufrem > 0) {
   1090 				len = fread(buf, sizeof(char),
   1091 				    ischunked ? MIN(chunksize, bufrem) : BUFSIZ,
   1092 				    fin);
   1093 				if (len <= 0)
   1094 					goto chunkdone;
   1095 				bytes += len;
   1096 				bufrem -= len;
   1097 				if (fwrite(buf, sizeof(char), len, fout)
   1098 				    != len) {
   1099 					warn("Writing `%s'", savefile);
   1100 					goto cleanup_fetch_url;
   1101 				}
   1102 			}
   1103 			if (hash && !progress) {
   1104 				while (bytes >= hashbytes) {
   1105 					(void)putc('#', ttyout);
   1106 					hashbytes += mark;
   1107 				}
   1108 				(void)fflush(ttyout);
   1109 			}
   1110 			if (ischunked) {
   1111 				chunksize -= len;
   1112 				if (chunksize <= 0)
   1113 					goto chunkdone;
   1114 			}
   1115 			if (rate_get) {
   1116 				while (1) {
   1117 					(void)gettimeofday(&now, NULL);
   1118 					timersub(&now, &then, &td);
   1119 					if (td.tv_sec > 0)
   1120 						break;
   1121 					usleep(1000000 - td.tv_usec);
   1122 				}
   1123 			}
   1124 		}
   1125 					/* read CRLF after chunk*/
   1126  chunkdone:
   1127 		if (ischunked) {
   1128 			if (fgets(buf, BUFSIZ, fin) == NULL)
   1129 				break;
   1130 			if (strcmp(buf, "\r\n") != 0) {
   1131 				warnx("Unexpected data following chunk");
   1132 				goto cleanup_fetch_url;
   1133 			}
   1134 		}
   1135 	} while (ischunked);
   1136 	if (hash && !progress && bytes > 0) {
   1137 		if (bytes < mark)
   1138 			(void)putc('#', ttyout);
   1139 		(void)putc('\n', ttyout);
   1140 	}
   1141 	if (ferror(fin)) {
   1142 		warn("Reading file");
   1143 		goto cleanup_fetch_url;
   1144 	}
   1145 	progressmeter(1);
   1146 	(void)fflush(fout);
   1147 	(void)signal(SIGINT, oldintr);
   1148 	if (oldintp)
   1149 		(void)signal(SIGPIPE, oldintp);
   1150 	if (closefunc == fclose && mtime != -1) {
   1151 		struct timeval tval[2];
   1152 
   1153 		(void)gettimeofday(&tval[0], NULL);
   1154 		tval[1].tv_sec = mtime;
   1155 		tval[1].tv_usec = 0;
   1156 		(*closefunc)(fout);
   1157 		fout = NULL;
   1158 
   1159 		if (utimes(savefile, tval) == -1) {
   1160 			fprintf(ttyout,
   1161 			    "Can't change modification time to %s",
   1162 			    asctime(localtime(&mtime)));
   1163 		}
   1164 	}
   1165 	if (bytes > 0)
   1166 		ptransfer(0);
   1167 
   1168 	rval = 0;
   1169 	goto cleanup_fetch_url;
   1170 
   1171 improper:
   1172 	warnx("Improper response from `%s'", host);
   1173 
   1174 cleanup_fetch_url:
   1175 	resetsockbufsize();
   1176 	if (fin != NULL)
   1177 		fclose(fin);
   1178 	else if (s != -1)
   1179 		close(s);
   1180 	if (closefunc != NULL && fout != NULL)
   1181 		(*closefunc)(fout);
   1182 #ifdef NI_NUMERICHOST
   1183 	if (res != NULL)
   1184 		freeaddrinfo(res);
   1185 #endif
   1186 	FREEPTR(savefile);
   1187 	FREEPTR(user);
   1188 	FREEPTR(pass);
   1189 	FREEPTR(host);
   1190 	FREEPTR(port);
   1191 	FREEPTR(path);
   1192 	FREEPTR(decodedpath);
   1193 	FREEPTR(puser);
   1194 	FREEPTR(ppass);
   1195 	FREEPTR(buf);
   1196 	FREEPTR(auth);
   1197 	FREEPTR(location);
   1198 	FREEPTR(message);
   1199 	return (rval);
   1200 }
   1201 
   1202 /*
   1203  * Abort a HTTP retrieval
   1204  */
   1205 void
   1206 aborthttp(notused)
   1207 	int notused;
   1208 {
   1209 
   1210 	alarmtimer(0);
   1211 	fputs("\nHTTP fetch aborted.\n", ttyout);
   1212 	longjmp(httpabort, 1);
   1213 }
   1214 
   1215 /*
   1216  * Retrieve ftp URL or classic ftp argument using FTP.
   1217  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
   1218  * is still open (e.g, ftp xfer with trailing /)
   1219  */
   1220 static int
   1221 fetch_ftp(url)
   1222 	const char *url;
   1223 {
   1224 	char		*cp, *xargv[5], rempath[MAXPATHLEN];
   1225 	char		*host, *path, *dir, *file, *user, *pass;
   1226 	char		*port;
   1227 	int		dirhasglob, filehasglob, oautologin, rval, type, xargc;
   1228 	url_t		urltype;
   1229 
   1230 	host = path = dir = file = user = pass = NULL;
   1231 	port = NULL;
   1232 	rval = 1;
   1233 	type = TYPE_I;
   1234 
   1235 	if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
   1236 		if ((parse_url(url, "URL", &urltype, &user, &pass,
   1237 		    &host, &port, &path) == -1) ||
   1238 		    (user != NULL && *user == '\0') ||
   1239 		    (pass != NULL && *pass == '\0') ||
   1240 		    EMPTYSTRING(host)) {
   1241 			warnx("Invalid URL `%s'", url);
   1242 			goto cleanup_fetch_ftp;
   1243 		}
   1244 		url_decode(user);
   1245 		url_decode(pass);
   1246 		/*
   1247 		 * Note: Don't url_decode(path) here.  We need to keep the
   1248 		 * distinction between "/" and "%2F" until later.
   1249 		 */
   1250 
   1251 					/* check for trailing ';type=[aid]' */
   1252 		if (! EMPTYSTRING(path) && (cp = strrchr(path, ';')) != NULL) {
   1253 			if (strcasecmp(cp, ";type=a") == 0)
   1254 				type = TYPE_A;
   1255 			else if (strcasecmp(cp, ";type=i") == 0)
   1256 				type = TYPE_I;
   1257 			else if (strcasecmp(cp, ";type=d") == 0) {
   1258 				warnx(
   1259 			    "Directory listing via a URL is not supported");
   1260 				goto cleanup_fetch_ftp;
   1261 			} else {
   1262 				warnx("Invalid suffix `%s' in URL `%s'", cp,
   1263 				    url);
   1264 				goto cleanup_fetch_ftp;
   1265 			}
   1266 			*cp = 0;
   1267 		}
   1268 	} else {			/* classic style `host:file' */
   1269 		urltype = CLASSIC_URL_T;
   1270 		host = xstrdup(url);
   1271 		cp = strchr(host, ':');
   1272 		if (cp != NULL) {
   1273 			*cp = '\0';
   1274 			path = xstrdup(cp + 1);
   1275 		}
   1276 	}
   1277 	if (EMPTYSTRING(host))
   1278 		goto cleanup_fetch_ftp;
   1279 
   1280 			/* Extract the file and (if present) directory name. */
   1281 	dir = path;
   1282 	if (! EMPTYSTRING(dir)) {
   1283 		/*
   1284 		 * If we are dealing with classic `host:path' syntax,
   1285 		 * then a path of the form `/file' (resulting from
   1286 		 * input of the form `host:/file') means that we should
   1287 		 * do "CWD /" before retrieving the file.  So we set
   1288 		 * dir="/" and file="file".
   1289 		 *
   1290 		 * But if we are dealing with URLs like
   1291 		 * `ftp://host/path' then a path of the form `/file'
   1292 		 * (resulting from a URL of the form `ftp://host//file')
   1293 		 * means that we should do `CWD ' (with an empty
   1294 		 * argument) before retrieving the file.  So we set
   1295 		 * dir="" and file="file".
   1296 		 *
   1297 		 * If the path does not contain / at all, we set
   1298 		 * dir=NULL.  (We get a path without any slashes if
   1299 		 * we are dealing with classic `host:file' or URL
   1300 		 * `ftp://host/file'.)
   1301 		 *
   1302 		 * In all other cases, we set dir to a string that does
   1303 		 * not include the final '/' that separates the dir part
   1304 		 * from the file part of the path.  (This will be the
   1305 		 * empty string if and only if we are dealing with a
   1306 		 * path of the form `/file' resulting from an URL of the
   1307 		 * form `ftp://host//file'.)
   1308 		 */
   1309 		cp = strrchr(dir, '/');
   1310 		if (cp == dir && urltype == CLASSIC_URL_T) {
   1311 			file = cp + 1;
   1312 			dir = "/";
   1313 		} else if (cp != NULL) {
   1314 			*cp++ = '\0';
   1315 			file = cp;
   1316 		} else {
   1317 			file = dir;
   1318 			dir = NULL;
   1319 		}
   1320 	} else
   1321 		dir = NULL;
   1322 	if (urltype == FTP_URL_T && file != NULL) {
   1323 		url_decode(file);
   1324 		/* but still don't url_decode(dir) */
   1325 	}
   1326 	if (debug)
   1327 		fprintf(ttyout,
   1328     "fetch_ftp: user `%s' pass `%s' host %s:%s path `%s' dir `%s' file `%s'\n",
   1329 		    user ? user : "<null>", pass ? pass : "<null>",
   1330 		    host ? host : "<null>", port ? port : "<null>",
   1331 		    path ? path : "<null>",
   1332 		    dir ? dir : "<null>", file ? file : "<null>");
   1333 
   1334 	dirhasglob = filehasglob = 0;
   1335 	if (doglob && urltype == CLASSIC_URL_T) {
   1336 		if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
   1337 			dirhasglob = 1;
   1338 		if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
   1339 			filehasglob = 1;
   1340 	}
   1341 
   1342 			/* Set up the connection */
   1343 	if (connected)
   1344 		disconnect(0, NULL);
   1345 	xargv[0] = __progname;
   1346 	xargv[1] = host;
   1347 	xargv[2] = NULL;
   1348 	xargc = 2;
   1349 	if (port) {
   1350 		xargv[2] = port;
   1351 		xargv[3] = NULL;
   1352 		xargc = 3;
   1353 	}
   1354 	oautologin = autologin;
   1355 	if (user != NULL)
   1356 		autologin = 0;
   1357 	setpeer(xargc, xargv);
   1358 	autologin = oautologin;
   1359 	if ((connected == 0) || ((connected == 1)
   1360 	    && !ftp_login(host, user, pass))) {
   1361 		warnx("Can't connect or login to host `%s'", host);
   1362 		goto cleanup_fetch_ftp;
   1363 	}
   1364 
   1365 	switch (type) {
   1366 	case TYPE_A:
   1367 		setascii(0, NULL);
   1368 		break;
   1369 	case TYPE_I:
   1370 		setbinary(0, NULL);
   1371 		break;
   1372 	default:
   1373 		errx(1, "fetch_ftp: unknown transfer type %d\n", type);
   1374 	}
   1375 
   1376 		/*
   1377 		 * Change directories, if necessary.
   1378 		 *
   1379 		 * Note: don't use EMPTYSTRING(dir) below, because
   1380 		 * dir=="" means something different from dir==NULL.
   1381 		 */
   1382 	if (dir != NULL && !dirhasglob) {
   1383 		char *nextpart;
   1384 
   1385 		/*
   1386 		 * If we are dealing with a classic `host:path' (urltype
   1387 		 * is CLASSIC_URL_T) then we have a raw directory
   1388 		 * name (not encoded in any way) and we can change
   1389 		 * directories in one step.
   1390 		 *
   1391 		 * If we are dealing with an `ftp://host/path' URL
   1392 		 * (urltype is FTP_URL_T), then RFC 1738 says we need to
   1393 		 * send a separate CWD command for each unescaped "/"
   1394 		 * in the path, and we have to interpret %hex escaping
   1395 		 * *after* we find the slashes.  It's possible to get
   1396 		 * empty components here, (from multiple adjacent
   1397 		 * slashes in the path) and RFC 1738 says that we should
   1398 		 * still do `CWD ' (with a null argument) in such cases.
   1399 		 *
   1400 		 * Many ftp servers don't support `CWD ', so if there's an
   1401 		 * error performing that command, bail out with a descriptive
   1402 		 * message.
   1403 		 *
   1404 		 * Examples:
   1405 		 *
   1406 		 * host:			dir="", urltype=CLASSIC_URL_T
   1407 		 *		logged in (to default directory)
   1408 		 * host:file			dir=NULL, urltype=CLASSIC_URL_T
   1409 		 *		"RETR file"
   1410 		 * host:dir/			dir="dir", urltype=CLASSIC_URL_T
   1411 		 *		"CWD dir", logged in
   1412 		 * ftp://host/			dir="", urltype=FTP_URL_T
   1413 		 *		logged in (to default directory)
   1414 		 * ftp://host/dir/		dir="dir", urltype=FTP_URL_T
   1415 		 *		"CWD dir", logged in
   1416 		 * ftp://host/file		dir=NULL, urltype=FTP_URL_T
   1417 		 *		"RETR file"
   1418 		 * ftp://host//file		dir="", urltype=FTP_URL_T
   1419 		 *		"CWD ", "RETR file"
   1420 		 * host:/file			dir="/", urltype=CLASSIC_URL_T
   1421 		 *		"CWD /", "RETR file"
   1422 		 * ftp://host///file		dir="/", urltype=FTP_URL_T
   1423 		 *		"CWD ", "CWD ", "RETR file"
   1424 		 * ftp://host/%2F/file		dir="%2F", urltype=FTP_URL_T
   1425 		 *		"CWD /", "RETR file"
   1426 		 * ftp://host/foo/file		dir="foo", urltype=FTP_URL_T
   1427 		 *		"CWD foo", "RETR file"
   1428 		 * ftp://host/foo/bar/file	dir="foo/bar"
   1429 		 *		"CWD foo", "CWD bar", "RETR file"
   1430 		 * ftp://host//foo/bar/file	dir="/foo/bar"
   1431 		 *		"CWD ", "CWD foo", "CWD bar", "RETR file"
   1432 		 * ftp://host/foo//bar/file	dir="foo//bar"
   1433 		 *		"CWD foo", "CWD ", "CWD bar", "RETR file"
   1434 		 * ftp://host/%2F/foo/bar/file	dir="%2F/foo/bar"
   1435 		 *		"CWD /", "CWD foo", "CWD bar", "RETR file"
   1436 		 * ftp://host/%2Ffoo/bar/file	dir="%2Ffoo/bar"
   1437 		 *		"CWD /foo", "CWD bar", "RETR file"
   1438 		 * ftp://host/%2Ffoo%2Fbar/file	dir="%2Ffoo%2Fbar"
   1439 		 *		"CWD /foo/bar", "RETR file"
   1440 		 * ftp://host/%2Ffoo%2Fbar%2Ffile	dir=NULL
   1441 		 *		"RETR /foo/bar/file"
   1442 		 *
   1443 		 * Note that we don't need `dir' after this point.
   1444 		 */
   1445 		do {
   1446 			if (urltype == FTP_URL_T) {
   1447 				nextpart = strchr(dir, '/');
   1448 				if (nextpart) {
   1449 					*nextpart = '\0';
   1450 					nextpart++;
   1451 				}
   1452 				url_decode(dir);
   1453 			} else
   1454 				nextpart = NULL;
   1455 			if (debug)
   1456 				fprintf(ttyout, "dir `%s', nextpart `%s'\n",
   1457 				    dir ? dir : "<null>",
   1458 				    nextpart ? nextpart : "<null>");
   1459 			if (urltype == FTP_URL_T || *dir != '\0') {
   1460 				xargv[0] = "cd";
   1461 				xargv[1] = dir;
   1462 				xargv[2] = NULL;
   1463 				dirchange = 0;
   1464 				cd(2, xargv);
   1465 				if (! dirchange) {
   1466 					if (*dir == '\0' && code == 500)
   1467 						fprintf(stderr,
   1468 "\n"
   1469 "ftp: The `CWD ' command (without a directory), which is required by\n"
   1470 "     RFC 1738 to support the empty directory in the URL pathname (`//'),\n"
   1471 "     conflicts with the server's conformance to RFC 959.\n"
   1472 "     Try the same URL without the `//' in the URL pathname.\n"
   1473 "\n");
   1474 					goto cleanup_fetch_ftp;
   1475 				}
   1476 			}
   1477 			dir = nextpart;
   1478 		} while (dir != NULL);
   1479 	}
   1480 
   1481 	if (EMPTYSTRING(file)) {
   1482 		rval = -1;
   1483 		goto cleanup_fetch_ftp;
   1484 	}
   1485 
   1486 	if (dirhasglob) {
   1487 		snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
   1488 		file = rempath;
   1489 	}
   1490 
   1491 			/* Fetch the file(s). */
   1492 	xargc = 2;
   1493 	xargv[0] = "get";
   1494 	xargv[1] = file;
   1495 	xargv[2] = NULL;
   1496 	if (dirhasglob || filehasglob) {
   1497 		int ointeractive;
   1498 
   1499 		ointeractive = interactive;
   1500 		interactive = 0;
   1501 		xargv[0] = "mget";
   1502 		mget(xargc, xargv);
   1503 		interactive = ointeractive;
   1504 	} else {
   1505 		if (outfile == NULL) {
   1506 			cp = strrchr(file, '/');	/* find savefile */
   1507 			if (cp != NULL)
   1508 				outfile = cp + 1;
   1509 			else
   1510 				outfile = file;
   1511 		}
   1512 		xargv[2] = (char *)outfile;
   1513 		xargv[3] = NULL;
   1514 		xargc++;
   1515 		if (restartautofetch)
   1516 			reget(xargc, xargv);
   1517 		else
   1518 			get(xargc, xargv);
   1519 	}
   1520 
   1521 	if ((code / 100) == COMPLETE)
   1522 		rval = 0;
   1523 
   1524 cleanup_fetch_ftp:
   1525 	FREEPTR(host);
   1526 	FREEPTR(path);
   1527 	FREEPTR(user);
   1528 	FREEPTR(pass);
   1529 	return (rval);
   1530 }
   1531 
   1532 /*
   1533  * Retrieve the given file to outfile.
   1534  * Supports arguments of the form:
   1535  *	"host:path", "ftp://host/path"	if $ftpproxy, call fetch_url() else
   1536  *					call fetch_ftp()
   1537  *	"http://host/path"		call fetch_url() to use HTTP
   1538  *	"file:///path"			call fetch_url() to copy
   1539  *	"about:..."			print a message
   1540  *
   1541  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
   1542  * is still open (e.g, ftp xfer with trailing /)
   1543  */
   1544 static int
   1545 go_fetch(url)
   1546 	const char *url;
   1547 {
   1548 
   1549 #ifndef NO_ABOUT
   1550 	/*
   1551 	 * Check for about:*
   1552 	 */
   1553 	if (strncasecmp(url, ABOUT_URL, sizeof(ABOUT_URL) - 1) == 0) {
   1554 		url += sizeof(ABOUT_URL) -1;
   1555 		if (strcasecmp(url, "ftp") == 0) {
   1556 			fprintf(ttyout, "%s\n%s\n",
   1557 "This version of ftp has been enhanced by Luke Mewburn <lukem (at) netbsd.org>.",
   1558 "Execute `man ftp' for more details.");
   1559 		} else if (strcasecmp(url, "netbsd") == 0) {
   1560 			fprintf(ttyout, "%s\n%s\n",
   1561 "NetBSD is a freely available and redistributable UNIX-like operating system.",
   1562 "For more information, see http://www.netbsd.org/index.html");
   1563 		} else {
   1564 			fprintf(ttyout, "`%s' is an interesting topic.\n", url);
   1565 		}
   1566 		return (0);
   1567 	}
   1568 #endif /* NO_ABOUT */
   1569 
   1570 	/*
   1571 	 * Check for file:// and http:// URLs.
   1572 	 */
   1573 	if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
   1574 	    strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0)
   1575 		return (fetch_url(url, NULL, NULL, NULL));
   1576 
   1577 	/*
   1578 	 * Try FTP URL-style and host:file arguments next.
   1579 	 * If ftpproxy is set with an FTP URL, use fetch_url()
   1580 	 * Othewise, use fetch_ftp().
   1581 	 */
   1582 	if (ftpproxy && strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0)
   1583 		return (fetch_url(url, NULL, NULL, NULL));
   1584 
   1585 	return (fetch_ftp(url));
   1586 }
   1587 
   1588 /*
   1589  * Retrieve multiple files from the command line,
   1590  * calling go_fetch() for each file.
   1591  *
   1592  * If an ftp path has a trailing "/", the path will be cd-ed into and
   1593  * the connection remains open, and the function will return -1
   1594  * (to indicate the connection is alive).
   1595  * If an error occurs the return value will be the offset+1 in
   1596  * argv[] of the file that caused a problem (i.e, argv[x]
   1597  * returns x+1)
   1598  * Otherwise, 0 is returned if all files retrieved successfully.
   1599  */
   1600 int
   1601 auto_fetch(argc, argv)
   1602 	int argc;
   1603 	char *argv[];
   1604 {
   1605 	volatile int	argpos;
   1606 	int		rval;
   1607 
   1608 	argpos = 0;
   1609 
   1610 	if (setjmp(toplevel)) {
   1611 		if (connected)
   1612 			disconnect(0, NULL);
   1613 		return (argpos + 1);
   1614 	}
   1615 	(void)signal(SIGINT, (sig_t)intr);
   1616 	(void)signal(SIGPIPE, (sig_t)lostpeer);
   1617 
   1618 	/*
   1619 	 * Loop through as long as there's files to fetch.
   1620 	 */
   1621 	for (rval = 0; (rval == 0) && (argpos < argc); argpos++) {
   1622 		if (strchr(argv[argpos], ':') == NULL)
   1623 			break;
   1624 		redirect_loop = 0;
   1625 		anonftp = 1;		/* Handle "automatic" transfers. */
   1626 		rval = go_fetch(argv[argpos]);
   1627 		if (outfile != NULL && strcmp(outfile, "-") != 0
   1628 		    && outfile[0] != '|')
   1629 			outfile = NULL;
   1630 		if (rval > 0)
   1631 			rval = argpos + 1;
   1632 	}
   1633 
   1634 	if (connected && rval != -1)
   1635 		disconnect(0, NULL);
   1636 	return (rval);
   1637 }
   1638