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