Home | History | Annotate | Line # | Download | only in ftp
fetch.c revision 1.62
      1 /*	$NetBSD: fetch.c,v 1.62 1999/07/06 22:11:37 tron 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.62 1999/07/06 22:11:37 tron 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) + 1;		/* user + ":" + pass */
    177 	clear = (char *)xmalloc(len + 1);
    178 	snprintf(clear, len, "%s:%s", user, pass);
    179 	if (gpass == NULL)
    180 		memset(pass, '\0', strlen(pass));
    181 
    182 						/* scheme + " " + enc */
    183 	len = strlen(scheme) + 1 + (len + 2) * 4 / 3;
    184 	*response = (char *)xmalloc(len + 1);
    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>]/<url-path>
    256  * Returns -1 if a parse error occurred, otherwise 0.
    257  * Only permit [<user>[:<password>@]] for ftp:// URLs
    258  * It's the caller's responsibility to url_decode() the returned
    259  * user, pass and path.
    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  * XXX: this is not totally RFC 1738 compliant; path will have the
    265  * leading `/' unless it's an ftp:// URL, as this makes things easier
    266  * for file:// and http:// URLs. ftp:// URLs have the `/' between the
    267  * host and the url-path removed, but any additional leading slashes
    268  * in the url-path are retained (because they imply that we should
    269  * later do "CWD" with a null argument).
    270  *
    271  * Examples:
    272  *	 input url			 output path
    273  *	 ---------			 -----------
    274  *	"http://host"			NULL
    275  *	"http://host/"			"/"
    276  *	"http://host/dir/file"		"/dir/file"
    277  *	"ftp://host/dir/file"		"dir/file"
    278  *	"ftp://host//dir/file"		"/dir/file"
    279  */
    280 static int
    281 parse_url(url, desc, type, user, pass, host, port, path)
    282 	const char	 *url;
    283 	const char	 *desc;
    284 	url_t		 *type;
    285 	char		**user;
    286 	char		**pass;
    287 	char		**host;
    288 	char		**port;
    289 	char		**path;
    290 {
    291 	char *cp, *ep, *thost;
    292 	size_t len;
    293 
    294 	if (url == NULL || desc == NULL || type == NULL || user == NULL
    295 	    || pass == NULL || host == NULL || port == NULL || path == NULL)
    296 		errx(1, "parse_url: invoked with NULL argument!");
    297 
    298 	*type = UNKNOWN_URL_T;
    299 	*user = *pass = *host = *path = NULL;
    300 	*port = NULL;
    301 
    302 	if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) {
    303 		url += sizeof(HTTP_URL) - 1;
    304 		*type = HTTP_URL_T;
    305 		*port = strdup(httpport);
    306 	} else if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
    307 		url += sizeof(FTP_URL) - 1;
    308 		*type = FTP_URL_T;
    309 		*port = strdup(ftpport);
    310 	} else if (strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
    311 		url += sizeof(FILE_URL) - 1;
    312 		*type = FILE_URL_T;
    313 	} else {
    314 		warnx("Invalid %s `%s'", desc, url);
    315 cleanup_parse_url:
    316 		FREEPTR(*user);
    317 		FREEPTR(*pass);
    318 		FREEPTR(*host);
    319 		FREEPTR(*port);
    320 		FREEPTR(*path);
    321 		return (-1);
    322 	}
    323 
    324 	if (*url == '\0')
    325 		return (0);
    326 
    327 			/* find [user[:pass]@]host[:port] */
    328 	ep = strchr(url, '/');
    329 	if (ep == NULL)
    330 		thost = xstrdup(url);
    331 	else {
    332 		len = ep - url;
    333 		thost = (char *)xmalloc(len + 1);
    334 		strncpy(thost, url, len);
    335 		thost[len] = '\0';
    336 		if (*type == FTP_URL_T)	/* skip first / for ftp URLs */
    337 			ep++;
    338 		*path = xstrdup(ep);
    339 	}
    340 
    341 	cp = strchr(thost, '@');
    342 					/* look for user[:pass]@ in URLs */
    343 	if (cp != NULL) {
    344 		if (*type == FTP_URL_T)
    345 			anonftp = 0;	/* disable anonftp */
    346 		*user = thost;
    347 		*cp = '\0';
    348 		*host = xstrdup(cp + 1);
    349 		cp = strchr(*user, ':');
    350 		if (cp != NULL) {
    351 			*cp = '\0';
    352 			*pass = xstrdup(cp + 1);
    353 		}
    354 	} else
    355 		*host = thost;
    356 
    357 	/* look for IPv6 address URL */
    358 	if (*thost == '[' && (cp = strrchr(thost, ']'))) {
    359 		size_t len = cp - thost - 1 ;
    360 		*host = (char *)xmalloc(len + 1);
    361 		strncpy(*host, thost + 1, len);
    362 		(*host)[len] = '\0';
    363 		cp = strrchr(++cp, ':');
    364 	} else if ((cp = strrchr(thost, ':')) != NULL) {
    365 		size_t len = cp - thost;
    366 		*host = (char *)xmalloc(len + 1);
    367 		strncpy(*host, thost, len);
    368 		(*host)[len] = '\0';
    369 	} else {
    370 		*host = xstrdup(thost);
    371 		cp = NULL;
    372 	}
    373 
    374 			/* look for [:port] */
    375 	if (cp != NULL) {
    376 		long nport;
    377 
    378 		*cp = '\0';
    379 		nport = strtol(cp + 1, &ep, 10);
    380 		if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0') {
    381 			warnx("Invalid port `%s' in %s `%s'", cp, desc, url);
    382 			goto cleanup_parse_url;
    383 		}
    384 		*port = (char *)xmalloc(6);	/* large enough for "65535\0" */
    385 		snprintf(*port, 6, "%ld", nport);
    386 	}
    387 
    388 	if (debug)
    389 		fprintf(ttyout,
    390 		    "parse_url: user `%s' pass `%s' host %s:%s path `%s'\n",
    391 		    *user ? *user : "<null>", *pass ? *pass : "<null>",
    392 		    *host ? *host : "<null>", *port ? *port : "<null>",
    393 		    *path ? *path : "<null>");
    394 
    395 	return (0);
    396 }
    397 
    398 
    399 jmp_buf	httpabort;
    400 
    401 /*
    402  * Retrieve URL, via a proxy if necessary, using HTTP.
    403  * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
    404  * http_proxy as appropriate.
    405  * Supports HTTP redirects.
    406  * Returns -1 on failure, 0 on completed xfer, 1 if ftp connection
    407  * is still open (e.g, ftp xfer with trailing /)
    408  */
    409 static int
    410 fetch_url(url, proxyenv, proxyauth, wwwauth)
    411 	const char	*url;
    412 	const char	*proxyenv;
    413 	char		*proxyauth;
    414 	char		*wwwauth;
    415 {
    416 	struct addrinfo		hints, *res;
    417 	volatile sig_t		oldintr, oldintp;
    418 	volatile int		s;
    419 	int 			ischunked, isproxy, rval, hcode;
    420 	size_t			len;
    421 	char			*cp, *ep, *buf, *savefile;
    422 	char			*auth, *location, *message;
    423 	char			*user, *pass, *host, *path, *decodedpath;
    424 	char			*puser, *ppass;
    425 	off_t			hashbytes;
    426 	int			 (*closefunc) __P((FILE *));
    427 	FILE			*fin, *fout;
    428 	time_t			mtime;
    429 	url_t			urltype;
    430 	in_port_t		portnum;
    431 	char			*port;
    432 	int			error;
    433 
    434 	closefunc = NULL;
    435 	fin = fout = NULL;
    436 	s = -1;
    437 	buf = savefile = NULL;
    438 	auth = location = message = NULL;
    439 	ischunked = isproxy = hcode = 0;
    440 	rval = 1;
    441 	user = pass = host = path = decodedpath = puser = ppass = NULL;
    442 
    443 #ifdef __GNUC__			/* shut up gcc warnings */
    444 	(void)&closefunc;
    445 	(void)&fin;
    446 	(void)&fout;
    447 	(void)&buf;
    448 	(void)&savefile;
    449 	(void)&rval;
    450 	(void)&isproxy;
    451 	(void)&hcode;
    452 	(void)&ischunked;
    453 	(void)&message;
    454 	(void)&location;
    455 	(void)&auth;
    456 	(void)&decodedpath;
    457 #endif
    458 
    459 	if (parse_url(url, "URL", &urltype, &user, &pass, &host, &port, &path)
    460 	    == -1)
    461 		goto cleanup_fetch_url;
    462 	portnum = strtol(port, NULL, 10);
    463 
    464 	if (urltype == FILE_URL_T && ! EMPTYSTRING(host)
    465 	    && strcasecmp(host, "localhost") != 0) {
    466 		warnx("No support for non local file URL `%s'", url);
    467 		goto cleanup_fetch_url;
    468 	}
    469 
    470 	if (EMPTYSTRING(path)) {
    471 		if (urltype == FTP_URL_T) {
    472 			rval = fetch_ftp(url);
    473 			goto cleanup_fetch_url;
    474 		}
    475 		if (urltype != HTTP_URL_T || outfile == NULL)  {
    476 			warnx("Invalid URL (no file after host) `%s'", url);
    477 			goto cleanup_fetch_url;
    478 		}
    479 	}
    480 
    481 	decodedpath = xstrdup(path);
    482 	url_decode(decodedpath);
    483 
    484 	if (outfile)
    485 		savefile = xstrdup(outfile);
    486 	else {
    487 		cp = strrchr(decodedpath, '/');		/* find savefile */
    488 		if (cp != NULL)
    489 			savefile = xstrdup(cp + 1);
    490 		else
    491 			savefile = xstrdup(decodedpath);
    492 	}
    493 	if (EMPTYSTRING(savefile)) {
    494 		if (urltype == FTP_URL_T) {
    495 			rval = fetch_ftp(url);
    496 			goto cleanup_fetch_url;
    497 		}
    498 		warnx("Invalid URL (no file after directory) `%s'", url);
    499 		goto cleanup_fetch_url;
    500 	} else {
    501 		if (debug)
    502 			fprintf(ttyout, "got savefile as `%s'\n", savefile);
    503 	}
    504 
    505 	filesize = -1;
    506 	mtime = -1;
    507 	if (urltype == FILE_URL_T) {		/* file:// URLs */
    508 		struct stat sb;
    509 
    510 		direction = "copied";
    511 		fin = fopen(decodedpath, "r");
    512 		if (fin == NULL) {
    513 			warn("Cannot open file `%s'", decodedpath);
    514 			goto cleanup_fetch_url;
    515 		}
    516 		if (fstat(fileno(fin), &sb) == 0) {
    517 			mtime = sb.st_mtime;
    518 			filesize = sb.st_size;
    519 		}
    520 		if (verbose)
    521 			fprintf(ttyout, "Copying %s\n", decodedpath);
    522 	} else {				/* ftp:// or http:// URLs */
    523 		if (proxyenv == NULL) {
    524 			if (urltype == HTTP_URL_T)
    525 				proxyenv = httpproxy;
    526 			else if (urltype == FTP_URL_T)
    527 				proxyenv = ftpproxy;
    528 		}
    529 		direction = "retrieved";
    530 		if (proxyenv != NULL) {				/* use proxy */
    531 			url_t purltype;
    532 			char *phost, *ppath;
    533 			char *pport;
    534 
    535 			isproxy = 1;
    536 
    537 				/* check URL against list of no_proxied sites */
    538 			if (no_proxy != NULL) {
    539 				char *np, *np_copy;
    540 				long np_port;
    541 				size_t hlen, plen;
    542 
    543 				np_copy = xstrdup(no_proxy);
    544 				hlen = strlen(host);
    545 				while ((cp = strsep(&np_copy, " ,")) != NULL) {
    546 					if (*cp == '\0')
    547 						continue;
    548 					if ((np = strrchr(cp, ':')) != NULL) {
    549 						*np = '\0';
    550 						np_port =
    551 						    strtol(np + 1, &ep, 10);
    552 						if (*ep != '\0')
    553 							continue;
    554 						if (portnum !=
    555 						    htons((in_port_t)np_port))
    556 							continue;
    557 					}
    558 					plen = strlen(cp);
    559 					if (strncasecmp(host + hlen - plen,
    560 					    cp, plen) == 0) {
    561 						isproxy = 0;
    562 						break;
    563 					}
    564 				}
    565 				FREEPTR(np_copy);
    566 			}
    567 
    568 			if (isproxy) {
    569 				if (parse_url(proxyenv, "proxy URL", &purltype,
    570 				    &puser, &ppass, &phost, &pport, &ppath)
    571 				    == -1)
    572 					goto cleanup_fetch_url;
    573 
    574 				if ((purltype != HTTP_URL_T
    575 				     && purltype != FTP_URL_T) ||
    576 				    EMPTYSTRING(phost) ||
    577 				    (! EMPTYSTRING(ppath)
    578 				     && strcmp(ppath, "/") != 0)) {
    579 					warnx("Malformed proxy URL `%s'",
    580 					    proxyenv);
    581 					FREEPTR(phost);
    582 					FREEPTR(pport);
    583 					FREEPTR(ppath);
    584 					goto cleanup_fetch_url;
    585 				}
    586 
    587 				FREEPTR(host);
    588 				host = phost;
    589 				FREEPTR(port);
    590 				port = pport;
    591 				FREEPTR(path);
    592 				path = xstrdup(url);
    593 				FREEPTR(ppath);
    594 			}
    595 		} /* proxyenv != NULL */
    596 
    597 #if 0
    598 		memset(&sin, 0, sizeof(sin));
    599 		sin.sin_family = AF_INET;
    600 
    601 		if (isdigit((unsigned char)host[0])) {
    602 			if (inet_aton(host, &sin.sin_addr) == 0) {
    603 				warnx("Invalid IP address `%s'", host);
    604 				goto cleanup_fetch_url;
    605 			}
    606 		} else {
    607 			hp = gethostbyname(host);
    608 			if (hp == NULL) {
    609 				warnx("%s: %s", host, hstrerror(h_errno));
    610 				goto cleanup_fetch_url;
    611 			}
    612 			if (hp->h_addrtype != AF_INET) {
    613 				warnx("`%s': not an Internet address?", host);
    614 				goto cleanup_fetch_url;
    615 			}
    616 			memcpy(&sin.sin_addr, hp->h_addr, hp->h_length);
    617 		}
    618 
    619 		if (port == NULL) {
    620 			warnx("Unknown port for URL `%s'", url);
    621 			goto cleanup_fetch_url;
    622 		}
    623 		sin.sin_port = port;
    624 
    625 		s = socket(AF_INET, SOCK_STREAM, 0);
    626 		if (s == -1) {
    627 			warn("Can't create socket");
    628 			goto cleanup_fetch_url;
    629 		}
    630 
    631 		while (xconnect(s, (struct sockaddr *)&sin,
    632 		    sizeof(sin)) == -1) {
    633 			if (errno == EINTR)
    634 				continue;
    635 			if (hp && hp->h_addr_list[1]) {
    636 				int oerrno = errno;
    637 				char *ia;
    638 
    639 				ia = inet_ntoa(sin.sin_addr);
    640 				errno = oerrno;
    641 				warn("Connect to address `%s'", ia);
    642 				hp->h_addr_list++;
    643 				memcpy(&sin.sin_addr, hp->h_addr_list[0],
    644 				    (size_t)hp->h_length);
    645 				if (verbose)
    646 					fprintf(ttyout, "Trying %s...\n",
    647 					    inet_ntoa(sin.sin_addr));
    648 				(void)close(s);
    649 				s = socket(AF_INET, SOCK_STREAM, 0);
    650 				if (s < 0) {
    651 					warn("Can't create socket");
    652 					goto cleanup_fetch_url;
    653 				}
    654 				continue;
    655 			}
    656 			warn("Can't connect to `%s'", host);
    657 			goto cleanup_fetch_url;
    658 		}
    659 #else
    660 		memset(&hints, 0, sizeof(hints));
    661 		hints.ai_flags = AI_CANONNAME;
    662 		hints.ai_family = AF_UNSPEC;
    663 		hints.ai_socktype = SOCK_STREAM;
    664 		hints.ai_protocol = 0;
    665 		error = getaddrinfo(host, port, &hints, &res);
    666 		if (error) {
    667 			warn(gai_strerror(error));
    668 			goto cleanup_fetch_url;
    669 		}
    670 		if (res->ai_canonname)
    671 			host = res->ai_canonname;
    672 
    673 		while (1) {
    674 			s = socket(res->ai_family,
    675 				   res->ai_socktype, res->ai_protocol);
    676 			if (s < 0) {
    677 				warn("Can't create socket");
    678 				goto cleanup_fetch_url;
    679 			}
    680 
    681 			if (xconnect(s, res->ai_addr, res->ai_addrlen) < 0) {
    682 				char hbuf[MAXHOSTNAMELEN];
    683 				getnameinfo(res->ai_addr, res->ai_addrlen,
    684 					hbuf, sizeof(hbuf), NULL, 0,
    685 					NI_NUMERICHOST);
    686 				warn("Connect to address `%s'", hbuf);
    687 				close(s);
    688 				res = res->ai_next;
    689 				if (res) {
    690 					getnameinfo(res->ai_addr, res->ai_addrlen,
    691 						hbuf, sizeof(hbuf), NULL, 0,
    692 						NI_NUMERICHOST);
    693 					if (verbose)
    694 						fprintf(ttyout, "Trying %s...\n", hbuf);
    695 					continue;
    696 				}
    697 				warn("Can't connect to %s", host);
    698 				goto cleanup_fetch_url;
    699 			}
    700 
    701 			break;
    702 		}
    703 #endif
    704 
    705 
    706 		fin = fdopen(s, "r+");
    707 		/*
    708 		 * Construct and send the request.
    709 		 * Proxy requests don't want leading /.
    710 		 */
    711 		if (isproxy) {
    712 			if (verbose)
    713 				fprintf(ttyout, "Requesting %s\n  (via %s)\n",
    714 				    url, proxyenv);
    715 			fprintf(fin, "GET %s HTTP/1.0\r\n", path);
    716 			if (flushcache)
    717 				fprintf(fin, "Pragma: no-cache\r\n");
    718 		} else {
    719 			struct utsname unam;
    720 
    721 			if (verbose)
    722 				fprintf(ttyout, "Requesting %s\n", url);
    723 			fprintf(fin, "GET %s HTTP/1.1\r\n", path);
    724 			fprintf(fin, "Host: %s:%s\r\n", host, port);
    725 			fprintf(fin, "Accept: */*\r\n");
    726 			if (uname(&unam) != -1) {
    727 				fprintf(fin, "User-Agent: %s-%s/ftp\r\n",
    728 				    unam.sysname, unam.release);
    729 			}
    730 			fprintf(fin, "Connection: close\r\n");
    731 			if (flushcache)
    732 				fprintf(fin, "Cache-Control: no-cache\r\n");
    733 		}
    734 		if (wwwauth) {
    735 			if (verbose)
    736 				fprintf(ttyout, "  (with authorization)\n");
    737 			fprintf(fin, "Authorization: %s\r\n", wwwauth);
    738 		}
    739 		if (proxyauth) {
    740 			if (verbose)
    741 				fprintf(ttyout,
    742 				    "  (with proxy authorization)\n");
    743 			fprintf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
    744 		}
    745 		fprintf(fin, "\r\n");
    746 		if (fflush(fin) == EOF) {
    747 			warn("Writing HTTP request");
    748 			goto cleanup_fetch_url;
    749 		}
    750 
    751 				/* Read the response */
    752 		if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
    753 			warn("Receiving HTTP reply");
    754 			goto cleanup_fetch_url;
    755 		}
    756 		while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
    757 			buf[--len] = '\0';
    758 		if (debug)
    759 			fprintf(ttyout, "received `%s'\n", buf);
    760 
    761 				/* Determine HTTP response code */
    762 		cp = strchr(buf, ' ');
    763 		if (cp == NULL)
    764 			goto improper;
    765 		else
    766 			cp++;
    767 		hcode = strtol(cp, &ep, 10);
    768 		if (*ep != '\0' && !isspace((unsigned char)*ep))
    769 			goto improper;
    770 		message = xstrdup(cp);
    771 
    772 				/* Read the rest of the header. */
    773 		FREEPTR(buf);
    774 		while (1) {
    775 			if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0))
    776 			    == NULL) {
    777 				warn("Receiving HTTP reply");
    778 				goto cleanup_fetch_url;
    779 			}
    780 			while (len > 0 &&
    781 			    (buf[len-1] == '\r' || buf[len-1] == '\n'))
    782 				buf[--len] = '\0';
    783 			if (len == 0)
    784 				break;
    785 			if (debug)
    786 				fprintf(ttyout, "received `%s'\n", buf);
    787 
    788 				/* Look for some headers */
    789 			cp = buf;
    790 
    791 #define CONTENTLEN "Content-Length: "
    792 			if (strncasecmp(cp, CONTENTLEN,
    793 					sizeof(CONTENTLEN) - 1) == 0) {
    794 				cp += sizeof(CONTENTLEN) - 1;
    795 				filesize = strtol(cp, &ep, 10);
    796 				if (filesize < 1 || *ep != '\0')
    797 					goto improper;
    798 				if (debug)
    799 					fprintf(ttyout,
    800 #ifndef NO_QUAD
    801 					    "parsed length as: %qd\n",
    802 					    (long long)filesize);
    803 #else
    804 					    "parsed length as: %ld\n",
    805 					    (long)filesize);
    806 #endif
    807 
    808 #define LASTMOD "Last-Modified: "
    809 			} else if (strncasecmp(cp, LASTMOD,
    810 						sizeof(LASTMOD) - 1) == 0) {
    811 				struct tm parsed;
    812 				char *t;
    813 
    814 				cp += sizeof(LASTMOD) - 1;
    815 							/* RFC 1123 */
    816 				if ((t = strptime(cp,
    817 						"%a, %d %b %Y %H:%M:%S GMT",
    818 						&parsed))
    819 							/* RFC 850 */
    820 				    || (t = strptime(cp,
    821 						"%a, %d-%b-%y %H:%M:%S GMT",
    822 						&parsed))
    823 							/* asctime */
    824 				    || (t = strptime(cp,
    825 						"%a, %b %d %H:%M:%S %Y",
    826 						&parsed))) {
    827 					parsed.tm_isdst = -1;
    828 					if (*t == '\0')
    829 						mtime = mkgmtime(&parsed);
    830 					if (debug && mtime != -1) {
    831 						fprintf(ttyout,
    832 						    "parsed date as: %s",
    833 						    ctime(&mtime));
    834 					}
    835 				}
    836 
    837 #define LOCATION "Location: "
    838 			} else if (strncasecmp(cp, LOCATION,
    839 						sizeof(LOCATION) - 1) == 0) {
    840 				cp += sizeof(LOCATION) - 1;
    841 				location = xstrdup(cp);
    842 				if (debug)
    843 					fprintf(ttyout,
    844 					    "parsed location as: %s\n", cp);
    845 
    846 #define TRANSENC "Transfer-Encoding: "
    847 			} else if (strncasecmp(cp, TRANSENC,
    848 						sizeof(TRANSENC) - 1) == 0) {
    849 				cp += sizeof(TRANSENC) - 1;
    850 				if (strcasecmp(cp, "chunked") != 0) {
    851 					warnx(
    852 				    "Unsupported transfer encoding - `%s'",
    853 					    cp);
    854 					goto cleanup_fetch_url;
    855 				}
    856 				ischunked++;
    857 				if (debug)
    858 					fprintf(ttyout,
    859 					    "using chunked encoding\n");
    860 
    861 #define PROXYAUTH "Proxy-Authenticate: "
    862 			} else if (strncasecmp(cp, PROXYAUTH,
    863 						sizeof(PROXYAUTH) - 1) == 0) {
    864 				cp += sizeof(PROXYAUTH) - 1;
    865 				FREEPTR(auth);
    866 				auth = xstrdup(cp);
    867 				if (debug)
    868 					fprintf(ttyout,
    869 					    "parsed proxy-auth as: %s\n", cp);
    870 
    871 #define WWWAUTH	"WWW-Authenticate: "
    872 			} else if (strncasecmp(cp, WWWAUTH,
    873 			    sizeof(WWWAUTH) - 1) == 0) {
    874 				cp += sizeof(WWWAUTH) - 1;
    875 				FREEPTR(auth);
    876 				auth = xstrdup(cp);
    877 				if (debug)
    878 					fprintf(ttyout,
    879 					    "parsed www-auth as: %s\n", cp);
    880 
    881 			}
    882 
    883 		}
    884 				/* finished parsing header */
    885 		FREEPTR(buf);
    886 
    887 		switch (hcode) {
    888 		case 200:
    889 			break;
    890 		case 300:
    891 		case 301:
    892 		case 302:
    893 		case 303:
    894 		case 305:
    895 			if (EMPTYSTRING(location)) {
    896 				warnx(
    897 				"No redirection Location provided by server");
    898 				goto cleanup_fetch_url;
    899 			}
    900 			if (redirect_loop++ > 5) {
    901 				warnx("Too many redirections requested");
    902 				goto cleanup_fetch_url;
    903 			}
    904 			if (hcode == 305) {
    905 				if (verbose)
    906 					fprintf(ttyout, "Redirected via %s\n",
    907 					    location);
    908 				rval = fetch_url(url, location,
    909 				    proxyauth, wwwauth);
    910 			} else {
    911 				if (verbose)
    912 					fprintf(ttyout, "Redirected to %s\n",
    913 					    location);
    914 				rval = go_fetch(location);
    915 			}
    916 			goto cleanup_fetch_url;
    917 		case 401:
    918 		case 407:
    919 		    {
    920 			char **authp;
    921 			char *auser, *apass;
    922 
    923 			fprintf(ttyout, "%s\n", message);
    924 			if (EMPTYSTRING(auth)) {
    925 				warnx(
    926 			    "No authentication challenge provided by server");
    927 				goto cleanup_fetch_url;
    928 			}
    929 			if (hcode == 401) {
    930 				authp = &wwwauth;
    931 				auser = user;
    932 				apass = pass;
    933 			} else {
    934 				authp = &proxyauth;
    935 				auser = puser;
    936 				apass = ppass;
    937 			}
    938 			if (*authp != NULL) {
    939 				char reply[10];
    940 
    941 				fprintf(ttyout,
    942 				    "Authorization failed. Retry (y/n)? ");
    943 				if (fgets(reply, sizeof(reply), stdin) != NULL
    944 				    && tolower(reply[0]) != 'y')
    945 					goto cleanup_fetch_url;
    946 				auser = NULL;
    947 				apass = NULL;
    948 			}
    949 			if (auth_url(auth, authp, auser, apass) == 0) {
    950 				rval = fetch_url(url, proxyenv,
    951 				    proxyauth, wwwauth);
    952 				memset(*authp, '\0', strlen(*authp));
    953 				FREEPTR(*authp);
    954 			}
    955 			goto cleanup_fetch_url;
    956 		    }
    957 		default:
    958 			if (message)
    959 				warnx("Error retrieving file - `%s'", message);
    960 			else
    961 				warnx("Unknown error retrieving file");
    962 			goto cleanup_fetch_url;
    963 		}
    964 	}		/* end of ftp:// or http:// specific setup */
    965 
    966 	oldintr = oldintp = NULL;
    967 
    968 			/* Open the output file. */
    969 	if (strcmp(savefile, "-") == 0) {
    970 		fout = stdout;
    971 	} else if (*savefile == '|') {
    972 		oldintp = signal(SIGPIPE, SIG_IGN);
    973 		fout = popen(savefile + 1, "w");
    974 		if (fout == NULL) {
    975 			warn("Can't run `%s'", savefile + 1);
    976 			goto cleanup_fetch_url;
    977 		}
    978 		closefunc = pclose;
    979 	} else {
    980 		fout = fopen(savefile, "w");
    981 		if (fout == NULL) {
    982 			warn("Can't open `%s'", savefile);
    983 			goto cleanup_fetch_url;
    984 		}
    985 		closefunc = fclose;
    986 	}
    987 
    988 			/* Trap signals */
    989 	if (setjmp(httpabort)) {
    990 		if (oldintr)
    991 			(void)signal(SIGINT, oldintr);
    992 		if (oldintp)
    993 			(void)signal(SIGPIPE, oldintp);
    994 		goto cleanup_fetch_url;
    995 	}
    996 	oldintr = signal(SIGINT, aborthttp);
    997 
    998 	bytes = 0;
    999 	hashbytes = mark;
   1000 	progressmeter(-1);
   1001 
   1002 			/* Finally, suck down the file. */
   1003 	buf = xmalloc(BUFSIZ + 1);
   1004 	do {
   1005 		ssize_t chunksize;
   1006 
   1007 		chunksize = 0;
   1008 					/* read chunksize */
   1009 		if (ischunked) {
   1010 			if (fgets(buf, BUFSIZ, fin) == NULL) {
   1011 				warnx("Unexpected EOF reading chunksize");
   1012 				goto cleanup_fetch_url;
   1013 			}
   1014 			chunksize = strtol(buf, &ep, 16);
   1015 			if (strcmp(ep, "\r\n") != 0) {
   1016 				warnx("Unexpected data following chunksize");
   1017 				goto cleanup_fetch_url;
   1018 			}
   1019 			if (debug)
   1020 				fprintf(ttyout,
   1021 #ifndef NO_QUAD
   1022 				    "got chunksize of %qd\n",
   1023 				    (long long)chunksize);
   1024 #else
   1025 				    "got chunksize of %ld\n",
   1026 				    (long)chunksize);
   1027 #endif
   1028 			if (chunksize == 0)
   1029 				break;
   1030 		}
   1031 					/* transfer file or chunk */
   1032 		while (1) {
   1033 			struct timeval then, now, td;
   1034 			off_t bufrem;
   1035 
   1036 			(void)gettimeofday(&then, NULL);
   1037 			bufrem = rate_get ? rate_get : BUFSIZ;
   1038 			while (bufrem > 0) {
   1039 				len = fread(buf, sizeof(char),
   1040 				    ischunked ? MIN(chunksize, bufrem) : BUFSIZ,
   1041 				    fin);
   1042 				if (len <= 0)
   1043 					goto chunkdone;
   1044 				bytes += len;
   1045 				bufrem -= len;
   1046 				if (fwrite(buf, sizeof(char), len, fout)
   1047 				    != len) {
   1048 					warn("Writing `%s'", savefile);
   1049 					goto cleanup_fetch_url;
   1050 				}
   1051 			}
   1052 			if (hash && !progress) {
   1053 				while (bytes >= hashbytes) {
   1054 					(void)putc('#', ttyout);
   1055 					hashbytes += mark;
   1056 				}
   1057 				(void)fflush(ttyout);
   1058 			}
   1059 			if (ischunked) {
   1060 				chunksize -= len;
   1061 				if (chunksize <= 0)
   1062 					goto chunkdone;
   1063 			}
   1064 			if (rate_get) {
   1065 				while (1) {
   1066 					(void)gettimeofday(&now, NULL);
   1067 					timersub(&now, &then, &td);
   1068 					if (td.tv_sec > 0)
   1069 						break;
   1070 					usleep(1000000 - td.tv_usec);
   1071 				}
   1072 			}
   1073 		}
   1074 					/* read CRLF after chunk*/
   1075  chunkdone:
   1076 		if (ischunked) {
   1077 			if (fgets(buf, BUFSIZ, fin) == NULL)
   1078 				break;
   1079 			if (strcmp(buf, "\r\n") != 0) {
   1080 				warnx("Unexpected data following chunk");
   1081 				goto cleanup_fetch_url;
   1082 			}
   1083 		}
   1084 	} while (ischunked);
   1085 	if (hash && !progress && bytes > 0) {
   1086 		if (bytes < mark)
   1087 			(void)putc('#', ttyout);
   1088 		(void)putc('\n', ttyout);
   1089 	}
   1090 	if (ferror(fin)) {
   1091 		warn("Reading file");
   1092 		goto cleanup_fetch_url;
   1093 	}
   1094 	progressmeter(1);
   1095 	(void)fflush(fout);
   1096 	(void)signal(SIGINT, oldintr);
   1097 	if (oldintp)
   1098 		(void)signal(SIGPIPE, oldintp);
   1099 	if (closefunc == fclose && mtime != -1) {
   1100 		struct timeval tval[2];
   1101 
   1102 		(void)gettimeofday(&tval[0], NULL);
   1103 		tval[1].tv_sec = mtime;
   1104 		tval[1].tv_usec = 0;
   1105 		(*closefunc)(fout);
   1106 		fout = NULL;
   1107 
   1108 		if (utimes(savefile, tval) == -1) {
   1109 			fprintf(ttyout,
   1110 			    "Can't change modification time to %s",
   1111 			    asctime(localtime(&mtime)));
   1112 		}
   1113 	}
   1114 	if (bytes > 0)
   1115 		ptransfer(0);
   1116 
   1117 	rval = 0;
   1118 	goto cleanup_fetch_url;
   1119 
   1120 improper:
   1121 	warnx("Improper response from `%s'", host);
   1122 
   1123 cleanup_fetch_url:
   1124 	resetsockbufsize();
   1125 	if (fin != NULL)
   1126 		fclose(fin);
   1127 	else if (s != -1)
   1128 		close(s);
   1129 	if (closefunc != NULL && fout != NULL)
   1130 		(*closefunc)(fout);
   1131 	FREEPTR(savefile);
   1132 	FREEPTR(user);
   1133 	FREEPTR(pass);
   1134 	FREEPTR(host);
   1135 	FREEPTR(port);
   1136 	FREEPTR(path);
   1137 	FREEPTR(decodedpath);
   1138 	FREEPTR(puser);
   1139 	FREEPTR(ppass);
   1140 	FREEPTR(buf);
   1141 	FREEPTR(auth);
   1142 	FREEPTR(location);
   1143 	FREEPTR(message);
   1144 	return (rval);
   1145 }
   1146 
   1147 /*
   1148  * Abort a HTTP retrieval
   1149  */
   1150 void
   1151 aborthttp(notused)
   1152 	int notused;
   1153 {
   1154 
   1155 	alarmtimer(0);
   1156 	fputs("\nHTTP fetch aborted.\n", ttyout);
   1157 	longjmp(httpabort, 1);
   1158 }
   1159 
   1160 /*
   1161  * Retrieve ftp URL or classic ftp argument using FTP.
   1162  * Returns -1 on failure, 0 on completed xfer, 1 if ftp connection
   1163  * is still open (e.g, ftp xfer with trailing /)
   1164  */
   1165 static int
   1166 fetch_ftp(url)
   1167 	const char *url;
   1168 {
   1169 	char		*cp, *xargv[5], rempath[MAXPATHLEN];
   1170 	char		*host, *path, *dir, *file, *user, *pass;
   1171 	char		*port;
   1172 	int		dirhasglob, filehasglob, oautologin, rval, type, xargc;
   1173 	url_t		urltype;
   1174 
   1175 	host = path = dir = file = user = pass = NULL;
   1176 	port = NULL;
   1177 	rval = 1;
   1178 	type = TYPE_I;
   1179 
   1180 	if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
   1181 		if ((parse_url(url, "URL", &urltype, &user, &pass,
   1182 		    &host, &port, &path) == -1) ||
   1183 		    (user != NULL && *user == '\0') ||
   1184 		    (pass != NULL && *pass == '\0') ||
   1185 		    EMPTYSTRING(host)) {
   1186 			warnx("Invalid URL `%s'", url);
   1187 			goto cleanup_fetch_ftp;
   1188 		}
   1189 		url_decode(user);
   1190 		url_decode(pass);
   1191 		/*
   1192 		 * Note: Don't url_decode(path) here.  We need to keep the
   1193 		 * distinction between "/" and "%2F" until later.
   1194 		 */
   1195 
   1196 					/* check for trailing ';type=[aid]' */
   1197 		if (path != NULL && (cp = strrchr(path, ';')) != NULL) {
   1198 			if (strcasecmp(cp, ";type=a") == 0)
   1199 				type = TYPE_A;
   1200 			else if (strcasecmp(cp, ";type=i") == 0)
   1201 				type = TYPE_I;
   1202 			else if (strcasecmp(cp, ";type=d") == 0) {
   1203 				warnx(
   1204 			    "Directory listing via a URL is not supported");
   1205 				goto cleanup_fetch_ftp;
   1206 			} else {
   1207 				warnx("Invalid suffix `%s' in URL `%s'", cp,
   1208 				    url);
   1209 				goto cleanup_fetch_ftp;
   1210 			}
   1211 			*cp = 0;
   1212 		}
   1213 	} else {			/* classic style `host:file' */
   1214 		urltype = CLASSIC_URL_T;
   1215 		host = xstrdup(url);
   1216 		cp = strchr(host, ':');
   1217 		if (cp != NULL) {
   1218 			*cp = '\0';
   1219 			path = xstrdup(cp + 1);
   1220 		}
   1221 	}
   1222 	if (EMPTYSTRING(host))
   1223 		goto cleanup_fetch_ftp;
   1224 
   1225 			/* Extract the file and (if present) directory name. */
   1226 	dir = path;
   1227 	if (! EMPTYSTRING(dir)) {
   1228 		/*
   1229 		 * If we are dealing with classic `host:path' syntax,
   1230 		 * then a path of the form `/file' (resulting from
   1231 		 * input of the form `host:/file') means that we should
   1232 		 * do "CWD /" before retreiving the file.  So we set
   1233 		 * dir="/" and file="file".
   1234 		 *
   1235 		 * But if we are dealing with URLs like
   1236 		 * `ftp://host/path' then a path of the form `/file'
   1237 		 * (resulting from a URL of the form `ftp://host//file')
   1238 		 * means that we should do `CWD ' (with an empty
   1239 		 * argument) before retrieving the file.  So we set
   1240 		 * dir="" and file="file".
   1241 		 *
   1242 		 * If the path does not contain / at all, we set
   1243 		 * dir=NULL.  (We get a path without any slashes if
   1244 		 * we are dealing with classic `host:file' or URL
   1245 		 * `ftp://host/file'.)
   1246 		 *
   1247 		 * In all other cases, we set dir to a string that does
   1248 		 * not include the final '/' that separates the dir part
   1249 		 * from the file part of the path.  (This will be the
   1250 		 * empty string if and only if we are dealing with a
   1251 		 * path of the form `/file' resulting from an URL of the
   1252 		 * form `ftp://host//file'.)
   1253 		 */
   1254 		cp = strrchr(dir, '/');
   1255 		if (cp == dir && urltype == CLASSIC_URL_T) {
   1256 			file = cp + 1;
   1257 			dir = "/";
   1258 		} else if (cp != NULL) {
   1259 			*cp++ = '\0';
   1260 			file = cp;
   1261 		} else {
   1262 			file = dir;
   1263 			dir = NULL;
   1264 		}
   1265 	}
   1266 	if (urltype == FTP_URL_T && file != NULL) {
   1267 		url_decode(file);
   1268 		/* but still don't url_decode(dir) */
   1269 	}
   1270 	if (debug)
   1271 		fprintf(ttyout,
   1272     "fetch_ftp: user `%s' pass `%s' host %s:%s path `%s' dir `%s' file `%s'\n",
   1273 		    user ? user : "<null>", pass ? pass : "<null>",
   1274 		    host ? host : "<null>", port ? port : "<null>",
   1275 		    path ? path : "<null>",
   1276 		    dir ? dir : "<null>", file ? file : "<null>");
   1277 
   1278 	dirhasglob = filehasglob = 0;
   1279 	if (doglob && urltype == CLASSIC_URL_T) {
   1280 		if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
   1281 			dirhasglob = 1;
   1282 		if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
   1283 			filehasglob = 1;
   1284 	}
   1285 
   1286 			/* Set up the connection */
   1287 	if (connected)
   1288 		disconnect(0, NULL);
   1289 	xargv[0] = __progname;
   1290 	xargv[1] = host;
   1291 	xargv[2] = NULL;
   1292 	xargc = 2;
   1293 	if (port) {
   1294 		xargv[2] = port;
   1295 		xargv[3] = NULL;
   1296 		xargc = 3;
   1297 	}
   1298 	oautologin = autologin;
   1299 	if (user != NULL)
   1300 		autologin = 0;
   1301 	setpeer(xargc, xargv);
   1302 	autologin = oautologin;
   1303 	if ((connected == 0) || ((connected == 1)
   1304 	    && !ftp_login(host, user, pass))) {
   1305 		warnx("Can't connect or login to host `%s'", host);
   1306 		goto cleanup_fetch_ftp;
   1307 	}
   1308 
   1309 	switch (type) {
   1310 	case TYPE_A:
   1311 		setascii(0, NULL);
   1312 		break;
   1313 	case TYPE_I:
   1314 		setbinary(0, NULL);
   1315 		break;
   1316 	default:
   1317 		errx(1, "fetch_ftp: unknown transfer type %d\n", type);
   1318 	}
   1319 
   1320 			/*
   1321 			 * Change directories, if necessary.
   1322 			 *
   1323 			 * Note: don't use EMPTYSTRING(dir) below, because
   1324 			 * dir="" means something different from dir=NULL.
   1325 			 */
   1326 	if (dir != NULL && !dirhasglob) {
   1327 		char *nextpart;
   1328 
   1329 		/*
   1330 		 * If we are dealing with a classic `host:path' (urltype
   1331 		 * is CLASSIC_URL_T) then we have a raw directory
   1332 		 * name (not encoded in any way) and we can change
   1333 		 * directories in one step.
   1334 		 *
   1335 		 * If we are dealing with an `ftp://host/path' URL
   1336 		 * (urltype is FTP_URL_T), then RFC 1738 says we need to
   1337 		 * send a separate CWD command for each unescaped "/"
   1338 		 * in the path, and we have to interpret %hex escaping
   1339 		 * *after* we find the slashes.  It's possible to get
   1340 		 * empty components here, (from multiple adjacent
   1341 		 * slashes in the path) and RFC 1738 says that we should
   1342 		 * still do `CWD ' (with a null argument) in such cases.
   1343 		 *
   1344 		 * XXX: many ftp servers don't support `CWD ', so we
   1345 		 * just skip the empty components.
   1346 		 *
   1347 		 * Examples:
   1348 		 *
   1349 		 * host:file			dir=NULL, urltype=CLASSIC_URL_T
   1350 		 *		"RETR file"
   1351 		 * ftp://host/file		dir=NULL, urltype=FTP_URL_T
   1352 		 *		"RETR file"
   1353 		 * ftp://host//file		dir="", urltype=FTP_URL_T
   1354 		 *		(no-op), "RETR file"
   1355 		 * host:/file			dir="/", urltype=CLASSIC_URL_T
   1356 		 *		"CWD /", "RETR file"
   1357 		 * ftp://host///file		dir="/", urltype=FTP_URL_T
   1358 		 *		(no-op), (no-op), "RETR file"
   1359 		 * ftp://host/%2F/file		dir="%2F", urltype=FTP_URL_T
   1360 		 *		"CWD /", "RETR file"
   1361 		 * ftp://host/foo/file		dir="foo", urltype=FTP_URL_T
   1362 		 *		"CWD foo", "RETR file"
   1363 		 * ftp://host/foo/bar/file	dir="foo/bar"
   1364 		 *		"CWD foo", "CWD bar", "RETR file"
   1365 		 * ftp://host//foo/bar/file	dir="/foo/bar"
   1366 		 *		(no-op), "CWD foo", "CWD bar", "RETR file"
   1367 		 * ftp://host/foo//bar/file	dir="foo//bar"
   1368 		 *		"CWD foo", (no-op), "CWD bar", "RETR file"
   1369 		 * ftp://host/%2F/foo/bar/file	dir="%2F/foo/bar"
   1370 		 *		"CWD /", "CWD foo", "CWD bar", "RETR file"
   1371 		 * ftp://host/%2Ffoo/bar/file	dir="%2Ffoo/bar"
   1372 		 *		"CWD /foo", "CWD bar", "RETR file"
   1373 		 * ftp://host/%2Ffoo%2Fbar/file	dir="%2Ffoo%2Fbar"
   1374 		 *		"CWD /foo/bar", "RETR file"
   1375 		 * ftp://host/%2Ffoo%2Fbar%2Ffile	dir=NULL
   1376 		 *		"RETR /foo/bar/file"
   1377 		 *
   1378 		 * Note that we don't need `dir' after this point.
   1379 		 */
   1380 		do {
   1381 			if (urltype == FTP_URL_T) {
   1382 				nextpart = strchr(dir, '/');
   1383 				if (nextpart) {
   1384 					*nextpart = '\0';
   1385 					nextpart++;
   1386 				}
   1387 				url_decode(dir);
   1388 			} else
   1389 				nextpart = NULL;
   1390 			if (debug)
   1391 				fprintf(ttyout, "dir `%s', nextpart `%s'\n",
   1392 				    dir ? dir : "<null>",
   1393 				    nextpart ? nextpart : "<null>");
   1394 			if (*dir != '\0') {
   1395 				xargv[0] = "cd";
   1396 				xargv[1] = dir;
   1397 				xargv[2] = NULL;
   1398 				dirchange = 0;
   1399 				cd(2, xargv);
   1400 				if (! dirchange)
   1401 					goto cleanup_fetch_ftp;
   1402 			}
   1403 			dir = nextpart;
   1404 		} while (dir != NULL);
   1405 	}
   1406 
   1407 	if (EMPTYSTRING(file)) {
   1408 		rval = -1;
   1409 		goto cleanup_fetch_ftp;
   1410 	}
   1411 
   1412 	if (dirhasglob) {
   1413 		snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
   1414 		file = rempath;
   1415 	}
   1416 
   1417 			/* Fetch the file(s). */
   1418 	xargc = 2;
   1419 	xargv[0] = "get";
   1420 	xargv[1] = file;
   1421 	xargv[2] = NULL;
   1422 	if (dirhasglob || filehasglob) {
   1423 		int ointeractive;
   1424 
   1425 		ointeractive = interactive;
   1426 		interactive = 0;
   1427 		xargv[0] = "mget";
   1428 		mget(xargc, xargv);
   1429 		interactive = ointeractive;
   1430 	} else {
   1431 		if (outfile == NULL) {
   1432 			cp = strrchr(file, '/');	/* find savefile */
   1433 			if (cp != NULL)
   1434 				outfile = cp + 1;
   1435 			else
   1436 				outfile = file;
   1437 		}
   1438 		xargv[2] = (char *)outfile;
   1439 		xargv[3] = NULL;
   1440 		xargc++;
   1441 		if (restartautofetch)
   1442 			reget(xargc, xargv);
   1443 		else
   1444 			get(xargc, xargv);
   1445 	}
   1446 
   1447 	if ((code / 100) == COMPLETE)
   1448 		rval = 0;
   1449 
   1450 cleanup_fetch_ftp:
   1451 	FREEPTR(host);
   1452 	FREEPTR(path);
   1453 	FREEPTR(user);
   1454 	FREEPTR(pass);
   1455 	return (rval);
   1456 }
   1457 
   1458 int
   1459 isurl(p)
   1460 	const char *p;
   1461 {
   1462 	if (strncasecmp(p, FTP_URL, sizeof(FTP_URL) - 1) == 0
   1463 	 || strncasecmp(p, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) {
   1464 		return 1;
   1465 	}
   1466 	return 0;
   1467 }
   1468 
   1469 /*
   1470  * Retrieve the given file to outfile.
   1471  * Supports arguments of the form:
   1472  *	"host:path", "ftp://host/path"	if $ftpproxy, call fetch_url() else
   1473  *					call fetch_ftp()
   1474  *	"http://host/path"		call fetch_url() to use HTTP
   1475  *	"file:///path"			call fetch_url() to copy
   1476  *	"about:..."			print a message
   1477  *
   1478  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
   1479  * is still open (e.g, ftp xfer with trailing /)
   1480  */
   1481 static int
   1482 go_fetch(url)
   1483 	const char *url;
   1484 {
   1485 
   1486 #ifndef NO_ABOUT
   1487 	/*
   1488 	 * Check for about:*
   1489 	 */
   1490 	if (strncasecmp(url, ABOUT_URL, sizeof(ABOUT_URL) - 1) == 0) {
   1491 		url += sizeof(ABOUT_URL) -1;
   1492 		if (strcasecmp(url, "ftp") == 0) {
   1493 			fprintf(ttyout, "%s\n%s\n",
   1494 "This version of ftp has been enhanced by Luke Mewburn <lukem (at) netbsd.org>.",
   1495 "Execute `man ftp' for more details");
   1496 		} else if (strcasecmp(url, "netbsd") == 0) {
   1497 			fprintf(ttyout, "%s\n%s\n",
   1498 "NetBSD is a freely available and redistributable UNIX-like operating system.",
   1499 "For more information, see http://www.netbsd.org/index.html");
   1500 		} else {
   1501 			fprintf(ttyout, "`%s' is an interesting topic.\n", url);
   1502 		}
   1503 		return (0);
   1504 	}
   1505 #endif /* NO_ABOUT */
   1506 
   1507 	/*
   1508 	 * Check for file:// and http:// URLs.
   1509 	 */
   1510 	if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
   1511 	    strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0)
   1512 		return (fetch_url(url, NULL, NULL, NULL));
   1513 
   1514 	/*
   1515 	 * Try FTP URL-style and host:file arguments next.
   1516 	 * If ftpproxy is set with an FTP URL, use fetch_url()
   1517 	 * Othewise, use fetch_ftp().
   1518 	 */
   1519 	if (ftpproxy && strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0)
   1520 		return (fetch_url(url, NULL, NULL, NULL));
   1521 
   1522 	return (fetch_ftp(url));
   1523 }
   1524 
   1525 /*
   1526  * Retrieve multiple files from the command line,
   1527  * calling go_fetch() for each file.
   1528  *
   1529  * If an ftp path has a trailing "/", the path will be cd-ed into and
   1530  * the connection remains open, and the function will return -1
   1531  * (to indicate the connection is alive).
   1532  * If an error occurs the return value will be the offset+1 in
   1533  * argv[] of the file that caused a problem (i.e, argv[x]
   1534  * returns x+1)
   1535  * Otherwise, 0 is returned if all files retrieved successfully.
   1536  */
   1537 int
   1538 auto_fetch(argc, argv)
   1539 	int argc;
   1540 	char *argv[];
   1541 {
   1542 	volatile int	argpos;
   1543 	int		rval;
   1544 
   1545 	argpos = 0;
   1546 
   1547 	if (setjmp(toplevel)) {
   1548 		if (connected)
   1549 			disconnect(0, NULL);
   1550 		return (argpos + 1);
   1551 	}
   1552 	(void)signal(SIGINT, (sig_t)intr);
   1553 	(void)signal(SIGPIPE, (sig_t)lostpeer);
   1554 
   1555 	/*
   1556 	 * Loop through as long as there's files to fetch.
   1557 	 */
   1558 	for (rval = 0; (rval == 0) && (argpos < argc); argpos++) {
   1559 		if (strchr(argv[argpos], ':') == NULL)
   1560 			break;
   1561 		redirect_loop = 0;
   1562 		anonftp = 1;		/* Handle "automatic" transfers. */
   1563 		rval = go_fetch(argv[argpos]);
   1564 		if (outfile != NULL && strcmp(outfile, "-") != 0
   1565 		    && outfile[0] != '|')
   1566 			outfile = NULL;
   1567 		if (rval > 0)
   1568 			rval = argpos + 1;
   1569 	}
   1570 
   1571 	if (connected && rval != -1)
   1572 		disconnect(0, NULL);
   1573 	return (rval);
   1574 }
   1575