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