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