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