xref: /netbsd-src/usr.bin/ftp/fetch.c (revision 8e33eff89e26cf71871ead62f0d5063e1313c33a)
1 /*	$NetBSD: fetch.c,v 1.239 2024/02/18 22:29:56 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1997-2015 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  * This code is derived from software contributed to The NetBSD Foundation
14  * by Thomas Klausner.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
26  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
29  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35  * POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 #include <sys/cdefs.h>
39 #ifndef lint
40 __RCSID("$NetBSD: fetch.c,v 1.239 2024/02/18 22:29:56 christos Exp $");
41 #endif /* not lint */
42 
43 /*
44  * FTP User Program -- Command line file retrieval
45  */
46 
47 #include <sys/types.h>
48 #include <sys/param.h>
49 #include <sys/socket.h>
50 #include <sys/stat.h>
51 #include <sys/time.h>
52 
53 #include <netinet/in.h>
54 
55 #include <arpa/ftp.h>
56 #include <arpa/inet.h>
57 
58 #include <assert.h>
59 #include <ctype.h>
60 #include <err.h>
61 #include <errno.h>
62 #include <netdb.h>
63 #include <fcntl.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
68 #include <time.h>
69 
70 #include "ssl.h"
71 #include "ftp_var.h"
72 #include "version.h"
73 
74 typedef enum {
75 	UNKNOWN_URL_T=-1,
76 	HTTP_URL_T,
77 	HTTPS_URL_T,
78 	FTP_URL_T,
79 	FILE_URL_T,
80 	CLASSIC_URL_T
81 } url_t;
82 
83 struct authinfo {
84 	char *auth;
85 	char *user;
86 	char *pass;
87 };
88 
89 struct urlinfo {
90 	char *host;
91 	char *port;
92 	char *path;
93 	url_t utype;
94 	in_port_t portnum;
95 };
96 
97 struct posinfo {
98 	off_t rangestart;
99 	off_t rangeend;
100 	off_t entitylen;
101 };
102 
103 __dead static void	aborthttp(int);
104 __dead static void	timeouthttp(int);
105 #ifndef NO_AUTH
106 static int	auth_url(const char *, char **, const struct authinfo *);
107 static void	base64_encode(const unsigned char *, size_t, unsigned char *);
108 #endif
109 static int	go_fetch(const char *, struct urlinfo *);
110 static int	fetch_ftp(const char *);
111 static int	fetch_url(const char *, const char *, char *, char *,
112     struct urlinfo *);
113 static const char *match_token(const char **, const char *);
114 static int	parse_url(const char *, const char *, struct urlinfo *,
115     struct authinfo *, struct urlinfo *);
116 static void	url_decode(char *);
117 static void	freeauthinfo(struct authinfo *);
118 static void	freeurlinfo(struct urlinfo *);
119 
120 static int	redirect_loop;
121 
122 
123 #define	STRNEQUAL(a,b)	(strncasecmp((a), (b), sizeof((b))-1) == 0)
124 #define	ISLWS(x)	((x)=='\r' || (x)=='\n' || (x)==' ' || (x)=='\t')
125 #define	SKIPLWS(x)	do { while (ISLWS((*x))) x++; } while (0)
126 
127 
128 #define	ABOUT_URL	"about:"	/* propaganda */
129 #define	FILE_URL	"file://"	/* file URL prefix */
130 #define	FTP_URL		"ftp://"	/* ftp URL prefix */
131 #define	HTTP_URL	"http://"	/* http URL prefix */
132 #ifdef WITH_SSL
133 #define	HTTPS_URL	"https://"	/* https URL prefix */
134 
135 #define	IS_HTTP_TYPE(urltype) \
136 	(((urltype) == HTTP_URL_T) || ((urltype) == HTTPS_URL_T))
137 #else
138 #define	IS_HTTP_TYPE(urltype) \
139 	((urltype) == HTTP_URL_T)
140 #endif
141 
142 /**
143  * fwrite(3) replacement that just uses write(2). Many stdio implementations
144  * don't handle interrupts properly and corrupt the output. We are taking
145  * alarm interrupts because of the progress bar.
146  *
147  * Assumes `fp' is pristine with no prior I/O calls on it.
148  */
149 static size_t
150 maxwrite(const void *buf, size_t size, size_t nmemb, FILE *fp)
151 {
152 	const char *p = buf;
153 	ssize_t nwr = 0;
154 	ssize_t n;
155 	int fd = fileno(fp);
156 
157 	size *= nmemb;	/* assume no overflow */
158 
159 	while (size > 0) {
160 		if ((n = write(fd, p, size)) == -1) {
161 			switch (errno) {
162 			case EINTR:
163 			case EAGAIN:
164 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
165 			case EWOULDBLOCK:
166 #endif
167 				continue;
168 			default:
169 				return nwr;
170 			}
171 		}
172 		p += n;
173 		nwr += n;
174 		size -= n;
175 	}
176 	return nwr;
177 }
178 
179 /*
180  * Determine if token is the next word in buf (case insensitive).
181  * If so, advance buf past the token and any trailing LWS, and
182  * return a pointer to the token (in buf).  Otherwise, return NULL.
183  * token may be preceded by LWS.
184  * token must be followed by LWS or NUL.  (I.e, don't partial match).
185  */
186 static const char *
187 match_token(const char **buf, const char *token)
188 {
189 	const char	*p, *orig;
190 	size_t		tlen;
191 
192 	tlen = strlen(token);
193 	p = *buf;
194 	SKIPLWS(p);
195 	orig = p;
196 	if (strncasecmp(p, token, tlen) != 0)
197 		return NULL;
198 	p += tlen;
199 	if (*p != '\0' && !ISLWS(*p))
200 		return NULL;
201 	SKIPLWS(p);
202 	orig = *buf;
203 	*buf = p;
204 	return orig;
205 }
206 
207 static void
208 initposinfo(struct posinfo *pi)
209 {
210 	pi->rangestart = pi->rangeend = pi->entitylen = -1;
211 }
212 
213 static void
214 initauthinfo(struct authinfo *ai, char *auth)
215 {
216 	ai->auth = auth;
217 	ai->user = ai->pass = 0;
218 }
219 
220 static void
221 freeauthinfo(struct authinfo *a)
222 {
223 	FREEPTR(a->user);
224 	if (a->pass != NULL)
225 		memset(a->pass, 0, strlen(a->pass));
226 	FREEPTR(a->pass);
227 }
228 
229 static void
230 initurlinfo(struct urlinfo *ui)
231 {
232 	ui->host = ui->port = ui->path = 0;
233 	ui->utype = UNKNOWN_URL_T;
234 	ui->portnum = 0;
235 }
236 
237 static void
238 copyurlinfo(struct urlinfo *dui, struct urlinfo *sui)
239 {
240 	dui->host = ftp_strdup(sui->host);
241 	dui->port = ftp_strdup(sui->port);
242 	dui->path = ftp_strdup(sui->path);
243 	dui->utype = sui->utype;
244 	dui->portnum = sui->portnum;
245 }
246 
247 static void
248 freeurlinfo(struct urlinfo *ui)
249 {
250 	FREEPTR(ui->host);
251 	FREEPTR(ui->port);
252 	FREEPTR(ui->path);
253 }
254 
255 #ifndef NO_AUTH
256 /*
257  * Generate authorization response based on given authentication challenge.
258  * Returns -1 if an error occurred, otherwise 0.
259  * Sets response to a malloc(3)ed string; caller should free.
260  */
261 static int
262 auth_url(const char *challenge, char **response, const struct authinfo *auth)
263 {
264 	const char	*cp, *scheme, *errormsg;
265 	char		*ep, *clear, *realm;
266 	char		 uuser[BUFSIZ], *gotpass;
267 	const char	*upass;
268 	int		 rval;
269 	size_t		 len, clen, rlen;
270 
271 	*response = NULL;
272 	clear = realm = NULL;
273 	rval = -1;
274 	cp = challenge;
275 	scheme = "Basic";	/* only support Basic authentication */
276 	gotpass = NULL;
277 
278 	DPRINTF("%s: challenge `%s'\n", __func__, challenge);
279 
280 	if (! match_token(&cp, scheme)) {
281 		warnx("Unsupported authentication challenge `%s'",
282 		    challenge);
283 		goto cleanup_auth_url;
284 	}
285 
286 #define	REALM "realm=\""
287 	if (STRNEQUAL(cp, REALM))
288 		cp += sizeof(REALM) - 1;
289 	else {
290 		warnx("Unsupported authentication challenge `%s'",
291 		    challenge);
292 		goto cleanup_auth_url;
293 	}
294 /* XXX: need to improve quoted-string parsing to support \ quoting, etc. */
295 	if ((ep = strchr(cp, '\"')) != NULL) {
296 		len = ep - cp;
297 		realm = (char *)ftp_malloc(len + 1);
298 		(void)strlcpy(realm, cp, len + 1);
299 	} else {
300 		warnx("Unsupported authentication challenge `%s'",
301 		    challenge);
302 		goto cleanup_auth_url;
303 	}
304 
305 	fprintf(ttyout, "Username for `%s': ", realm);
306 	if (auth->user != NULL) {
307 		(void)strlcpy(uuser, auth->user, sizeof(uuser));
308 		fprintf(ttyout, "%s\n", uuser);
309 	} else {
310 		(void)fflush(ttyout);
311 		if (get_line(stdin, uuser, sizeof(uuser), &errormsg) < 0) {
312 			warnx("%s; can't authenticate", errormsg);
313 			goto cleanup_auth_url;
314 		}
315 	}
316 	if (auth->pass != NULL)
317 		upass = auth->pass;
318 	else {
319 		gotpass = getpass("Password: ");
320 		if (gotpass == NULL) {
321 			warnx("Can't read password");
322 			goto cleanup_auth_url;
323 		}
324 		upass = gotpass;
325 	}
326 
327 	clen = strlen(uuser) + strlen(upass) + 2;	/* user + ":" + pass + "\0" */
328 	clear = (char *)ftp_malloc(clen);
329 	(void)strlcpy(clear, uuser, clen);
330 	(void)strlcat(clear, ":", clen);
331 	(void)strlcat(clear, upass, clen);
332 	if (gotpass)
333 		memset(gotpass, 0, strlen(gotpass));
334 
335 						/* scheme + " " + enc + "\0" */
336 	rlen = strlen(scheme) + 1 + (clen + 2) * 4 / 3 + 1;
337 	*response = ftp_malloc(rlen);
338 	(void)strlcpy(*response, scheme, rlen);
339 	len = strlcat(*response, " ", rlen);
340 			/* use	`clen - 1'  to not encode the trailing NUL */
341 	base64_encode((unsigned char *)clear, clen - 1,
342 	    (unsigned char *)*response + len);
343 	memset(clear, 0, clen);
344 	rval = 0;
345 
346  cleanup_auth_url:
347 	FREEPTR(clear);
348 	FREEPTR(realm);
349 	return (rval);
350 }
351 
352 /*
353  * Encode len bytes starting at clear using base64 encoding into encoded,
354  * which should be at least ((len + 2) * 4 / 3 + 1) in size.
355  */
356 static void
357 base64_encode(const unsigned char *clear, size_t len, unsigned char *encoded)
358 {
359 	static const unsigned char enc[] =
360 	    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
361 	unsigned char	*cp;
362 	size_t	 i;
363 
364 	cp = encoded;
365 	for (i = 0; i < len; i += 3) {
366 		*(cp++) = enc[((clear[i + 0] >> 2))];
367 		*(cp++) = enc[((clear[i + 0] << 4) & 0x30)
368 			    | ((clear[i + 1] >> 4) & 0x0f)];
369 		*(cp++) = enc[((clear[i + 1] << 2) & 0x3c)
370 			    | ((clear[i + 2] >> 6) & 0x03)];
371 		*(cp++) = enc[((clear[i + 2]	 ) & 0x3f)];
372 	}
373 	*cp = '\0';
374 	while (i-- > len)
375 		*(--cp) = '=';
376 }
377 #endif
378 
379 /*
380  * Decode %xx escapes in given string, `in-place'.
381  */
382 static void
383 url_decode(char *url)
384 {
385 	unsigned char *p, *q;
386 
387 	if (EMPTYSTRING(url))
388 		return;
389 	p = q = (unsigned char *)url;
390 
391 #define	HEXTOINT(x) (x - (isdigit(x) ? '0' : (islower(x) ? 'a' : 'A') - 10))
392 	while (*p) {
393 		if (p[0] == '%'
394 		    && p[1] && isxdigit((unsigned char)p[1])
395 		    && p[2] && isxdigit((unsigned char)p[2])) {
396 			*q++ = HEXTOINT(p[1]) * 16 + HEXTOINT(p[2]);
397 			p+=3;
398 		} else
399 			*q++ = *p++;
400 	}
401 	*q = '\0';
402 }
403 
404 static const char *
405 get_port(const struct urlinfo *ui)
406 {
407 
408 	switch(ui->utype) {
409 	case HTTP_URL_T:
410 		return httpport;
411 	case FTP_URL_T:
412 		return ftpport;
413 	case FILE_URL_T:
414 		return "";
415 #ifdef WITH_SSL
416 	case HTTPS_URL_T:
417 		return httpsport;
418 #endif
419 	default:
420 		return NULL;
421 	}
422 }
423 
424 static int
425 use_relative(const struct urlinfo *ui)
426 {
427 	if (ui == NULL)
428 		return 0;
429 	switch (ui->utype) {
430 	case HTTP_URL_T:
431 	case FILE_URL_T:
432 #ifdef WITH_SSL
433 	case HTTPS_URL_T:
434 #endif
435 		return 1;
436 	default:
437 		return 0;
438 	}
439 }
440 
441 /*
442  * Parse URL of form (per RFC 3986):
443  *	<type>://[<user>[:<password>]@]<host>[:<port>][/<path>]
444  * Returns -1 if a parse error occurred, otherwise 0.
445  * It's the caller's responsibility to url_decode() the returned
446  * user, pass and path.
447  *
448  * Sets type to url_t, each of the given char ** pointers to a
449  * malloc(3)ed strings of the relevant section, and port to
450  * the number given, or ftpport if ftp://, or httpport if http://.
451  *
452  * XXX: this is not totally RFC 3986 compliant; <path> will have the
453  * leading `/' unless it's an ftp:// URL, as this makes things easier
454  * for file:// and http:// URLs.  ftp:// URLs have the `/' between the
455  * host and the URL-path removed, but any additional leading slashes
456  * in the URL-path are retained (because they imply that we should
457  * later do "CWD" with a null argument).
458  *
459  * Examples:
460  *	 input URL			 output path
461  *	 ---------			 -----------
462  *	"http://host"			"/"
463  *	"http://host/"			"/"
464  *	"http://host/path"		"/path"
465  *	"file://host/dir/file"		"dir/file"
466  *	"ftp://host"			""
467  *	"ftp://host/"			""
468  *	"ftp://host//"			"/"
469  *	"ftp://host/dir/file"		"dir/file"
470  *	"ftp://host//dir/file"		"/dir/file"
471  */
472 
473 static int
474 parse_url(const char *url, const char *desc, struct urlinfo *ui,
475     struct authinfo *auth, struct urlinfo *rui)
476 {
477 	const char	*origurl, *tport;
478 	char		*cp, *ep, *thost;
479 	size_t		 len;
480 
481 	if (url == NULL || desc == NULL || ui == NULL || auth == NULL)
482 		errx(1, "parse_url: invoked with NULL argument!");
483 	DPRINTF("parse_url: %s `%s'\n", desc, url);
484 
485 	origurl = url;
486 
487 	if (STRNEQUAL(url, HTTP_URL)) {
488 		url += sizeof(HTTP_URL) - 1;
489 		ui->utype = HTTP_URL_T;
490 		ui->portnum = HTTP_PORT;
491 	} else if (STRNEQUAL(url, FTP_URL)) {
492 		url += sizeof(FTP_URL) - 1;
493 		ui->utype = FTP_URL_T;
494 		ui->portnum = FTP_PORT;
495 	} else if (STRNEQUAL(url, FILE_URL)) {
496 		url += sizeof(FILE_URL) - 1;
497 		ui->utype = FILE_URL_T;
498 #ifdef WITH_SSL
499 	} else if (STRNEQUAL(url, HTTPS_URL)) {
500 		url += sizeof(HTTPS_URL) - 1;
501 		ui->utype = HTTPS_URL_T;
502 		ui->portnum = HTTPS_PORT;
503 #endif
504 	} else if (rui != NULL) {
505 		copyurlinfo(ui, rui);
506 	} else {
507 		warnx("Invalid %s `%s'", desc, url);
508  cleanup_parse_url:
509 		freeauthinfo(auth);
510 		freeurlinfo(ui);
511 		return (-1);
512 	}
513 
514 
515 	if (*url == '\0')
516 		return (0);
517 
518 			/* find [user[:pass]@]host[:port] */
519 	ep = strchr(url, '/');
520 	if (ep == NULL)
521 		thost = ftp_strdup(url);
522 	else {
523 		len = ep - url;
524 		thost = (char *)ftp_malloc(len + 1);
525 		(void)strlcpy(thost, url, len + 1);
526 		if (ui->utype == FTP_URL_T)	/* skip first / for ftp URLs */
527 			ep++;
528 		ui->path = ftp_strdup(ep);
529 	}
530 
531 	cp = strchr(thost, '@');	/* look for user[:pass]@ in URLs */
532 	if (cp != NULL) {
533 		if (ui->utype == FTP_URL_T)
534 			anonftp = 0;	/* disable anonftp */
535 		auth->user = thost;
536 		*cp = '\0';
537 		thost = ftp_strdup(cp + 1);
538 		cp = strchr(auth->user, ':');
539 		if (cp != NULL) {
540 			*cp = '\0';
541 			auth->pass = ftp_strdup(cp + 1);
542 		}
543 		url_decode(auth->user);
544 		if (auth->pass)
545 			url_decode(auth->pass);
546 	}
547 
548 #ifdef INET6
549 			/*
550 			 * Check if thost is an encoded IPv6 address, as per
551 			 * RFC 3986:
552 			 *	`[' ipv6-address ']'
553 			 */
554 	if (*thost == '[') {
555 		cp = thost + 1;
556 		if ((ep = strchr(cp, ']')) == NULL ||
557 		    (ep[1] != '\0' && ep[1] != ':')) {
558 			warnx("Invalid address `%s' in %s `%s'",
559 			    thost, desc, origurl);
560 			goto cleanup_parse_url;
561 		}
562 		len = ep - cp;		/* change `[xyz]' -> `xyz' */
563 		memmove(thost, thost + 1, len);
564 		thost[len] = '\0';
565 		if (! isipv6addr(thost)) {
566 			warnx("Invalid IPv6 address `%s' in %s `%s'",
567 			    thost, desc, origurl);
568 			goto cleanup_parse_url;
569 		}
570 		cp = ep + 1;
571 		if (*cp == ':')
572 			cp++;
573 		else
574 			cp = NULL;
575 	} else
576 #endif /* INET6 */
577 		if ((cp = strchr(thost, ':')) != NULL)
578 			*cp++ = '\0';
579 	if (*thost != '\0')
580 		ui->host = thost;
581 
582 			/* look for [:port] */
583 	if (cp != NULL) {
584 		unsigned long	nport;
585 
586 		nport = strtoul(cp, &ep, 10);
587 		if (*cp == '\0' || *ep != '\0' ||
588 		    nport < 1 || nport > MAX_IN_PORT_T) {
589 			warnx("Unknown port `%s' in %s `%s'",
590 			    cp, desc, origurl);
591 			goto cleanup_parse_url;
592 		}
593 		ui->portnum = nport;
594 		tport = cp;
595 	} else
596 		tport = get_port(ui);
597 
598 
599 	if (tport != NULL)
600 		ui->port = ftp_strdup(tport);
601 	if (ui->path == NULL) {
602 		const char *emptypath = "/";
603 		if (ui->utype == FTP_URL_T)	/* skip first / for ftp URLs */
604 			emptypath++;
605 		ui->path = ftp_strdup(emptypath);
606 	}
607 
608 	DPRINTF("%s: user `%s' pass `%s' host %s port %s(%d) "
609 	    "path `%s'\n", __func__,
610 	    STRorNULL(auth->user), STRorNULL(auth->pass),
611 	    STRorNULL(ui->host), STRorNULL(ui->port),
612 	    ui->portnum ? ui->portnum : -1, STRorNULL(ui->path));
613 
614 	return (0);
615 }
616 
617 sigjmp_buf	httpabort;
618 
619 static int
620 ftp_socket(const struct urlinfo *ui, void **ssl, struct authinfo *auth)
621 {
622 	struct addrinfo hints, *res, *res0 = NULL;
623 	int error;
624 	int s;
625 	const char *host = ui->host;
626 	const char *port = ui->port;
627 	char *fuser = NULL, *pass = NULL, *facct = NULL;
628 	int n;
629 
630 	if (ui->utype != HTTPS_URL_T)
631 		ssl = NULL;
632 
633 	memset(&hints, 0, sizeof(hints));
634 	hints.ai_flags = 0;
635 	hints.ai_family = family;
636 	hints.ai_socktype = SOCK_STREAM;
637 	hints.ai_protocol = 0;
638 
639 	error = getaddrinfo(host, port, &hints, &res0);
640 	if (error) {
641 		warnx("Can't LOOKUP `%s:%s': %s", host, port,
642 		    (error == EAI_SYSTEM) ? strerror(errno)
643 					  : gai_strerror(error));
644 		return -1;
645 	}
646 
647 	if (res0->ai_canonname)
648 		host = res0->ai_canonname;
649 
650 	s = -1;
651 	if (ssl)
652 		*ssl = NULL;
653 	for (res = res0; res; res = res->ai_next) {
654 		char	hname[NI_MAXHOST], sname[NI_MAXSERV];
655 
656 		ai_unmapped(res);
657 		if (getnameinfo(res->ai_addr, res->ai_addrlen,
658 		    hname, sizeof(hname), sname, sizeof(sname),
659 		    NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
660 			strlcpy(hname, "?", sizeof(hname));
661 			strlcpy(sname, "?", sizeof(sname));
662 		}
663 
664 		if (verbose && res0->ai_next) {
665 #ifdef INET6
666 			if(res->ai_family == AF_INET6) {
667 				fprintf(ttyout, "Trying [%s]:%s ...\n",
668 				    hname, sname);
669 			} else {
670 #endif
671 				fprintf(ttyout, "Trying %s:%s ...\n",
672 				    hname, sname);
673 #ifdef INET6
674 			}
675 #endif
676 		}
677 
678 		s = socket(res->ai_family, SOCK_STREAM, res->ai_protocol);
679 		if (s < 0) {
680 			warn(
681 			    "Can't create socket for connection to "
682 			    "`%s:%s'", hname, sname);
683 			continue;
684 		}
685 
686 		if (ftp_connect(s, res->ai_addr, res->ai_addrlen,
687 		    verbose || !res->ai_next) < 0) {
688 			close(s);
689 			s = -1;
690 			continue;
691 		}
692 
693 		if (ruserpass("", &fuser, &pass, &facct) < 0) {
694 			close(s);
695 			s = -1;
696 			continue;
697 		}
698 
699 		if (autologin) {
700 			if (fuser != NULL && auth->user == NULL)
701 				auth->user = ftp_strdup(fuser);
702 			if (pass != NULL && auth->pass == NULL)
703 				auth->pass = ftp_strdup(pass);
704 		}
705 
706 		for (n = 0; n < macnum; ++n) {
707 			if (!strcmp("init", macros[n].mac_name)) {
708 				(void)strlcpy(line, "$init", sizeof(line));
709 				makeargv();
710 				domacro(margc, margv);
711 				break;
712 			}
713 		}
714 
715 #ifdef WITH_SSL
716 		if (ssl) {
717 			if ((*ssl = fetch_start_ssl(s, host)) == NULL) {
718 				close(s);
719 				s = -1;
720 				continue;
721 			}
722 		}
723 #endif
724 		break;
725 	}
726 
727 	FREEPTR(fuser);
728 	if (pass != NULL)
729 		memset(pass, 0, strlen(pass));
730 	FREEPTR(pass);
731 	if (facct != NULL)
732 		memset(facct, 0, strlen(facct));
733 	FREEPTR(facct);
734 
735 	if (res0)
736 		freeaddrinfo(res0);
737 	return s;
738 }
739 
740 static int
741 handle_noproxy(const char *host, in_port_t portnum)
742 {
743 
744 	char *cp, *ep, *np, *np_copy, *np_iter, *no_proxy;
745 	unsigned long np_port;
746 	size_t hlen, plen;
747 	int isproxy = 1;
748 
749 	/* check URL against list of no_proxied sites */
750 	no_proxy = getoptionvalue("no_proxy");
751 	if (EMPTYSTRING(no_proxy))
752 		return isproxy;
753 
754 	np_iter = np_copy = ftp_strdup(no_proxy);
755 	hlen = strlen(host);
756 	while ((cp = strsep(&np_iter, " ,")) != NULL) {
757 		if (*cp == '\0')
758 			continue;
759 		if ((np = strrchr(cp, ':')) != NULL) {
760 			*np++ =	 '\0';
761 			np_port = strtoul(np, &ep, 10);
762 			if (*np == '\0' || *ep != '\0')
763 				continue;
764 			if (np_port != portnum)
765 				continue;
766 		}
767 		plen = strlen(cp);
768 		if (hlen < plen)
769 			continue;
770 		if (strncasecmp(host + hlen - plen, cp, plen) == 0) {
771 			isproxy = 0;
772 			break;
773 		}
774 	}
775 	FREEPTR(np_copy);
776 	return isproxy;
777 }
778 
779 static int
780 handle_proxy(const char *url, const char *penv, struct urlinfo *ui,
781     struct authinfo *pauth)
782 {
783 	struct urlinfo pui;
784 
785 	if (isipv6addr(ui->host) && strchr(ui->host, '%') != NULL) {
786 		warnx("Scoped address notation `%s' disallowed via web proxy",
787 		    ui->host);
788 		return -1;
789 	}
790 
791 	initurlinfo(&pui);
792 	if (parse_url(penv, "proxy URL", &pui, pauth, NULL) == -1)
793 		return -1;
794 
795 	if ((!IS_HTTP_TYPE(pui.utype) && pui.utype != FTP_URL_T) ||
796 	    EMPTYSTRING(pui.host) ||
797 	    (! EMPTYSTRING(pui.path) && strcmp(pui.path, "/") != 0)) {
798 		warnx("Malformed proxy URL `%s'", penv);
799 		freeurlinfo(&pui);
800 		return -1;
801 	}
802 
803 	FREEPTR(pui.path);
804 #ifdef WITH_SSL
805 	if (ui->utype == HTTPS_URL_T)
806 		pui.path = ftp_strdup(ui->path);
807 	else
808 #endif
809 		pui.path = ftp_strdup(url);
810 
811 	freeurlinfo(ui);
812 	*ui = pui;
813 
814 	return 0;
815 }
816 
817 static void
818 print_host(FETCH *fin, const struct urlinfo *ui)
819 {
820 	char *h, *p;
821 
822 	if (strchr(ui->host, ':') == NULL) {
823 		fetch_printf(fin, "Host: %s", ui->host);
824 	} else {
825 		/*
826 		 * strip off IPv6 scope identifier, since it is
827 		 * local to the node
828 		 */
829 		h = ftp_strdup(ui->host);
830 		if (isipv6addr(h) && (p = strchr(h, '%')) != NULL)
831 			*p = '\0';
832 
833 		fetch_printf(fin, "Host: [%s]", h);
834 		free(h);
835 	}
836 
837 	if ((ui->utype == HTTP_URL_T && ui->portnum != HTTP_PORT) ||
838 	    (ui->utype == HTTPS_URL_T && ui->portnum != HTTPS_PORT))
839 		fetch_printf(fin, ":%u", ui->portnum);
840 	fetch_printf(fin, "\r\n");
841 }
842 
843 static void
844 print_agent(FETCH *fin)
845 {
846 	const char *useragent;
847 	if ((useragent = getenv("FTPUSERAGENT")) != NULL) {
848 		fetch_printf(fin, "User-Agent: %s\r\n", useragent);
849 	} else {
850 		fetch_printf(fin, "User-Agent: %s/%s\r\n",
851 		    FTP_PRODUCT, FTP_VERSION);
852 	}
853 }
854 
855 static void
856 print_cache(FETCH *fin, int isproxy)
857 {
858 	fetch_printf(fin, isproxy ?
859 	    "Pragma: no-cache\r\n" :
860 	    "Cache-Control: no-cache\r\n");
861 }
862 
863 static int
864 print_get(FETCH *fin, int hasleading, int isproxy, const struct urlinfo *oui,
865     const struct urlinfo *ui)
866 {
867 	const char *leading = hasleading ? ", " : "  (";
868 
869 	if (isproxy) {
870 		if (verbose) {
871 			fprintf(ttyout, "%svia %s:%u", leading,
872 			    ui->host, ui->portnum);
873 			leading = ", ";
874 			hasleading++;
875 		}
876 		fetch_printf(fin, "GET %s HTTP/1.0\r\n", ui->path);
877 		print_host(fin, oui);
878 		return hasleading;
879 	}
880 
881 	fetch_printf(fin, "GET %s HTTP/1.1\r\n", ui->path);
882 	print_host(fin, ui);
883 	fetch_printf(fin, "Accept: */*\r\n");
884 	fetch_printf(fin, "Connection: close\r\n");
885 	if (restart_point) {
886 		fputs(leading, ttyout);
887 		fetch_printf(fin, "Range: bytes=" LLF "-\r\n",
888 		    (LLT)restart_point);
889 		fprintf(ttyout, "restarting at " LLF, (LLT)restart_point);
890 		hasleading++;
891 	}
892 	return hasleading;
893 }
894 
895 static void
896 getmtime(const char *cp, time_t *mtime)
897 {
898 	struct tm parsed;
899 	const char *t;
900 
901 	memset(&parsed, 0, sizeof(parsed));
902 	t = parse_rfc2616time(&parsed, cp);
903 
904 	if (t == NULL)
905 		return;
906 
907 	parsed.tm_isdst = -1;
908 	if (*t == '\0')
909 		*mtime = timegm(&parsed);
910 
911 #ifndef NO_DEBUG
912 	if (ftp_debug && *mtime != -1) {
913 		fprintf(ttyout, "parsed time as: %s",
914 		    rfc2822time(localtime(mtime)));
915 	}
916 #endif
917 }
918 
919 static int
920 print_proxy(FETCH *fin, int hasleading, const char *wwwauth,
921     const char *proxyauth)
922 {
923 	const char *leading = hasleading ? ", " : "  (";
924 
925 	if (wwwauth) {
926 		if (verbose) {
927 			fprintf(ttyout, "%swith authorization", leading);
928 			hasleading++;
929 		}
930 		fetch_printf(fin, "Authorization: %s\r\n", wwwauth);
931 	}
932 	if (proxyauth) {
933 		if (verbose) {
934 			fprintf(ttyout, "%swith proxy authorization", leading);
935 			hasleading++;
936 		}
937 		fetch_printf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
938 	}
939 	return hasleading;
940 }
941 
942 #ifdef WITH_SSL
943 static void
944 print_connect(FETCH *fin, const struct urlinfo *ui)
945 {
946 	char hname[NI_MAXHOST], *p;
947 	const char *h;
948 
949 	if (isipv6addr(ui->host)) {
950 		/*
951 		 * strip off IPv6 scope identifier,
952 		 * since it is local to the node
953 		 */
954 		if ((p = strchr(ui->host, '%')) == NULL)
955 			snprintf(hname, sizeof(hname), "[%s]", ui->host);
956 		else
957 			snprintf(hname, sizeof(hname), "[%.*s]",
958 			    (int)(p - ui->host), ui->host);
959 		h = hname;
960 	} else
961 		h = ui->host;
962 
963 	fetch_printf(fin, "CONNECT %s:%d HTTP/1.1\r\n", h, ui->portnum);
964 	fetch_printf(fin, "Host: %s:%d\r\n", h, ui->portnum);
965 }
966 #endif
967 
968 #define	C_OK 0
969 #define	C_CLEANUP 1
970 #define	C_IMPROPER 2
971 
972 static int
973 getresponseline(FETCH *fin, char *buf, size_t buflen, int *len)
974 {
975 	const char *errormsg;
976 
977 	alarmtimer(quit_time ? quit_time : 60);
978 	*len = fetch_getline(fin, buf, buflen, &errormsg);
979 	alarmtimer(0);
980 	if (*len < 0) {
981 		if (*errormsg == '\n')
982 			errormsg++;
983 		warnx("Receiving HTTP reply: %s", errormsg);
984 		return C_CLEANUP;
985 	}
986 	while (*len > 0 && (ISLWS(buf[*len-1])))
987 		buf[--*len] = '\0';
988 
989 	if (*len)
990 		DPRINTF("%s: received `%s'\n", __func__, buf);
991 	return C_OK;
992 }
993 
994 static int
995 getresponse(FETCH *fin, char **cp, size_t buflen, int *hcode)
996 {
997 	int len, rv;
998 	char *ep, *buf = *cp;
999 
1000 	*hcode = 0;
1001 	if ((rv = getresponseline(fin, buf, buflen, &len)) != C_OK)
1002 		return rv;
1003 
1004 	/* Determine HTTP response code */
1005 	*cp = strchr(buf, ' ');
1006 	if (*cp == NULL)
1007 		return C_IMPROPER;
1008 
1009 	(*cp)++;
1010 
1011 	*hcode = strtol(*cp, &ep, 10);
1012 	if (*ep != '\0' && !isspace((unsigned char)*ep))
1013 		return C_IMPROPER;
1014 
1015 	return C_OK;
1016 }
1017 
1018 static int
1019 parse_posinfo(const char **cp, struct posinfo *pi)
1020 {
1021 	char *ep;
1022 	if (!match_token(cp, "bytes"))
1023 		return -1;
1024 
1025 	if (**cp == '*')
1026 		(*cp)++;
1027 	else {
1028 		pi->rangestart = STRTOLL(*cp, &ep, 10);
1029 		if (pi->rangestart < 0 || *ep != '-')
1030 			return -1;
1031 		*cp = ep + 1;
1032 		pi->rangeend = STRTOLL(*cp, &ep, 10);
1033 		if (pi->rangeend < 0 || pi->rangeend < pi->rangestart)
1034 			return -1;
1035 		*cp = ep;
1036 	}
1037 	if (**cp != '/')
1038 		return -1;
1039 	(*cp)++;
1040 	if (**cp == '*')
1041 		(*cp)++;
1042 	else {
1043 		pi->entitylen = STRTOLL(*cp, &ep, 10);
1044 		if (pi->entitylen < 0)
1045 			return -1;
1046 		*cp = ep;
1047 	}
1048 	if (**cp != '\0')
1049 		return -1;
1050 
1051 #ifndef NO_DEBUG
1052 	if (ftp_debug) {
1053 		fprintf(ttyout, "parsed range as: ");
1054 		if (pi->rangestart == -1)
1055 			fprintf(ttyout, "*");
1056 		else
1057 			fprintf(ttyout, LLF "-" LLF, (LLT)pi->rangestart,
1058 			    (LLT)pi->rangeend);
1059 		fprintf(ttyout, "/" LLF "\n", (LLT)pi->entitylen);
1060 	}
1061 #endif
1062 	return 0;
1063 }
1064 
1065 #ifndef NO_AUTH
1066 static void
1067 do_auth(int hcode, const char *url, const char *penv, struct authinfo *wauth,
1068     struct authinfo *pauth, char **auth, const char *message,
1069     volatile int *rval, struct urlinfo *ui)
1070 {
1071 	struct authinfo aauth;
1072 	char *response;
1073 
1074 	if (hcode == 401)
1075 		aauth = *wauth;
1076 	else
1077 		aauth = *pauth;
1078 
1079 	if (verbose || aauth.auth == NULL ||
1080 	    aauth.user == NULL || aauth.pass == NULL)
1081 		fprintf(ttyout, "%s\n", message);
1082 	if (EMPTYSTRING(*auth)) {
1083 		warnx("No authentication challenge provided by server");
1084 		return;
1085 	}
1086 
1087 	if (aauth.auth != NULL) {
1088 		char reply[10];
1089 
1090 		fprintf(ttyout, "Authorization failed. Retry (y/n)? ");
1091 		if (get_line(stdin, reply, sizeof(reply), NULL) < 0) {
1092 			return;
1093 		}
1094 		if (tolower((unsigned char)reply[0]) != 'y')
1095 			return;
1096 
1097 		aauth.user = NULL;
1098 		aauth.pass = NULL;
1099 	}
1100 
1101 	if (auth_url(*auth, &response, &aauth) == 0) {
1102 		*rval = fetch_url(url, penv,
1103 		    hcode == 401 ? pauth->auth : response,
1104 		    hcode == 401 ? response : wauth->auth,
1105 		    ui);
1106 		memset(response, 0, strlen(response));
1107 		FREEPTR(response);
1108 	}
1109 }
1110 #endif
1111 
1112 static int
1113 negotiate_connection(FETCH *fin, const char *url, const char *penv,
1114     struct posinfo *pi, time_t *mtime, struct authinfo *wauth,
1115     struct authinfo *pauth, volatile int *rval, volatile int *ischunked,
1116     char **auth, struct urlinfo *ui)
1117 {
1118 	int			len, hcode, rv;
1119 	char			*buf = NULL, *ep;
1120 	const char		*cp, *token;
1121 	char			*location, *message;
1122 
1123 	*auth = message = location = NULL;
1124 
1125 	buf = ftp_malloc(ftp_buflen);
1126 
1127 	/* Read the response */
1128 	ep = buf;
1129 	switch (getresponse(fin, &ep, ftp_buflen, &hcode)) {
1130 	case C_CLEANUP:
1131 		goto cleanup_fetch_url;
1132 	case C_IMPROPER:
1133 		goto improper;
1134 	case C_OK:
1135 		message = ftp_strdup(ep);
1136 		break;
1137 	}
1138 
1139 	/* Read the rest of the header. */
1140 
1141 	for (;;) {
1142 		if ((rv = getresponseline(fin, buf, ftp_buflen, &len)) != C_OK)
1143 			goto cleanup_fetch_url;
1144 		if (len == 0)
1145 			break;
1146 
1147 	/*
1148 	 * Look for some headers
1149 	 */
1150 
1151 		cp = buf;
1152 
1153 		if (match_token(&cp, "Content-Length:")) {
1154 			filesize = STRTOLL(cp, &ep, 10);
1155 			if (filesize < 0 || *ep != '\0')
1156 				goto improper;
1157 			DPRINTF("%s: parsed len as: " LLF "\n",
1158 			    __func__, (LLT)filesize);
1159 
1160 		} else if (match_token(&cp, "Content-Range:")) {
1161 			if (parse_posinfo(&cp, pi) == -1)
1162 				goto improper;
1163 			if (! restart_point) {
1164 				warnx(
1165 			    "Received unexpected Content-Range header");
1166 				goto cleanup_fetch_url;
1167 			}
1168 
1169 		} else if (match_token(&cp, "Last-Modified:")) {
1170 			getmtime(cp, mtime);
1171 
1172 		} else if (match_token(&cp, "Location:")) {
1173 			location = ftp_strdup(cp);
1174 			DPRINTF("%s: parsed location as `%s'\n",
1175 			    __func__, cp);
1176 
1177 		} else if (match_token(&cp, "Transfer-Encoding:")) {
1178 			if (match_token(&cp, "binary")) {
1179 				warnx(
1180 		"Bogus transfer encoding `binary' (fetching anyway)");
1181 				continue;
1182 			}
1183 			if (! (token = match_token(&cp, "chunked"))) {
1184 				warnx(
1185 			    "Unsupported transfer encoding `%s'",
1186 				    token);
1187 				goto cleanup_fetch_url;
1188 			}
1189 			(*ischunked)++;
1190 			DPRINTF("%s: using chunked encoding\n",
1191 			    __func__);
1192 
1193 		} else if (match_token(&cp, "Proxy-Authenticate:")
1194 			|| match_token(&cp, "WWW-Authenticate:")) {
1195 			if (! (token = match_token(&cp, "Basic"))) {
1196 				DPRINTF("%s: skipping unknown auth "
1197 				    "scheme `%s'\n", __func__, token);
1198 				continue;
1199 			}
1200 			FREEPTR(*auth);
1201 			*auth = ftp_strdup(token);
1202 			DPRINTF("%s: parsed auth as `%s'\n",
1203 			    __func__, cp);
1204 		}
1205 
1206 	}
1207 			/* finished parsing header */
1208 
1209 	switch (hcode) {
1210 	case 200:
1211 		break;
1212 	case 206:
1213 		if (! restart_point) {
1214 			warnx("Not expecting partial content header");
1215 			goto cleanup_fetch_url;
1216 		}
1217 		break;
1218 	case 300:
1219 	case 301:
1220 	case 302:
1221 	case 303:
1222 	case 305:
1223 	case 307:
1224 		if (EMPTYSTRING(location)) {
1225 			warnx(
1226 			"No redirection Location provided by server");
1227 			goto cleanup_fetch_url;
1228 		}
1229 		if (redirect_loop++ > 5) {
1230 			warnx("Too many redirections requested");
1231 			goto cleanup_fetch_url;
1232 		}
1233 		if (hcode == 305) {
1234 			if (verbose)
1235 				fprintf(ttyout, "Redirected via %s\n",
1236 				    location);
1237 			*rval = fetch_url(url, location,
1238 			    pauth->auth, wauth->auth, ui);
1239 		} else {
1240 			if (verbose)
1241 				fprintf(ttyout, "Redirected to %s\n",
1242 				    location);
1243 			*rval = go_fetch(location, ui);
1244 		}
1245 		goto cleanup_fetch_url;
1246 #ifndef NO_AUTH
1247 	case 401:
1248 	case 407:
1249 		do_auth(hcode, url, penv, wauth, pauth, auth, message, rval,
1250 		    ui);
1251 		goto cleanup_fetch_url;
1252 #endif
1253 	default:
1254 		if (message)
1255 			warnx("Error retrieving file `%s'", message);
1256 		else
1257 			warnx("Unknown error retrieving file");
1258 		goto cleanup_fetch_url;
1259 	}
1260 	rv = C_OK;
1261 	goto out;
1262 
1263 cleanup_fetch_url:
1264 	rv = C_CLEANUP;
1265 	goto out;
1266 improper:
1267 	rv = C_IMPROPER;
1268 	goto out;
1269 out:
1270 	FREEPTR(buf);
1271 	FREEPTR(message);
1272 	FREEPTR(location);
1273 	return rv;
1274 }		/* end of ftp:// or http:// specific setup */
1275 
1276 #ifdef WITH_SSL
1277 static int
1278 connectmethod(FETCH *fin, const char *url, const char *penv,
1279     struct urlinfo *oui, struct urlinfo *ui, struct authinfo *wauth,
1280     struct authinfo *pauth, char **auth, int *hasleading, volatile int *rval)
1281 {
1282 	void *ssl;
1283 	int hcode, rv;
1284 	const char *cp;
1285 	char *buf = NULL, *ep;
1286 	char *message = NULL;
1287 
1288 	print_connect(fin, oui);
1289 
1290 	print_agent(fin);
1291 	*hasleading = print_proxy(fin, *hasleading, NULL, pauth->auth);
1292 
1293 	if (verbose && *hasleading)
1294 		fputs(")\n", ttyout);
1295 	*hasleading = 0;
1296 
1297 	fetch_printf(fin, "\r\n");
1298 	if (fetch_flush(fin) == EOF) {
1299 		warn("Writing HTTP request");
1300 		alarmtimer(0);
1301 		goto cleanup_fetch_url;
1302 	}
1303 	alarmtimer(0);
1304 
1305 	buf = ftp_malloc(ftp_buflen);
1306 
1307 	/* Read the response */
1308 	ep = buf;
1309 	switch (getresponse(fin, &ep, ftp_buflen, &hcode)) {
1310 	case C_CLEANUP:
1311 		goto cleanup_fetch_url;
1312 	case C_IMPROPER:
1313 		goto improper;
1314 	case C_OK:
1315 		message = ftp_strdup(ep);
1316 		break;
1317 	}
1318 
1319 	for (;;) {
1320 		int len;
1321 		if (getresponseline(fin, buf, ftp_buflen, &len) != C_OK)
1322 			goto cleanup_fetch_url;
1323 		if (len == 0)
1324 			break;
1325 
1326 		cp = buf;
1327 		if (match_token(&cp, "Proxy-Authenticate:")) {
1328 			const char *token;
1329 			if (!(token = match_token(&cp, "Basic"))) {
1330 				DPRINTF(
1331 				    "%s: skipping unknown auth scheme `%s'\n",
1332 				    __func__, token);
1333 				continue;
1334 			}
1335 			FREEPTR(*auth);
1336 			*auth = ftp_strdup(token);
1337 			DPRINTF("%s: parsed auth as " "`%s'\n", __func__, cp);
1338 		}
1339 	}
1340 
1341 	/* finished parsing header */
1342 	switch (hcode) {
1343 	case 200:
1344 		break;
1345 #ifndef NO_AUTH
1346 	case 407:
1347 		do_auth(hcode, url, penv, wauth, pauth, auth, message, rval,
1348 		    ui);
1349 		goto cleanup_fetch_url;
1350 #endif
1351 	default:
1352 		if (message)
1353 			warnx("Error proxy connect " "`%s'", message);
1354 		else
1355 			warnx("Unknown error proxy " "connect");
1356 		goto cleanup_fetch_url;
1357 	}
1358 
1359 	if ((ssl = fetch_start_ssl(fetch_fileno(fin), oui->host)) == NULL)
1360 		goto cleanup_fetch_url;
1361 	fetch_set_ssl(fin, ssl);
1362 
1363 	rv = C_OK;
1364 	goto out;
1365 improper:
1366 	rv = C_IMPROPER;
1367 	goto out;
1368 cleanup_fetch_url:
1369 	rv = C_CLEANUP;
1370 	goto out;
1371 out:
1372 	FREEPTR(buf);
1373 	FREEPTR(message);
1374 	return rv;
1375 }
1376 #endif
1377 
1378 /*
1379  * Retrieve URL, via a proxy if necessary, using HTTP.
1380  * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
1381  * http_proxy/https_proxy as appropriate.
1382  * Supports HTTP redirects.
1383  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1384  * is still open (e.g, ftp xfer with trailing /)
1385  */
1386 static int
1387 fetch_url(const char *url, const char *proxyenv, char *proxyauth,
1388     char *wwwauth, struct urlinfo *rui)
1389 {
1390 	sigfunc volatile	oldint;
1391 	sigfunc volatile	oldpipe;
1392 	sigfunc volatile	oldalrm;
1393 	sigfunc volatile	oldquit;
1394 	int volatile		s;
1395 	struct stat		sb;
1396 	int volatile		isproxy;
1397 	int volatile		rval, ischunked;
1398 	size_t			flen;
1399 	static size_t		bufsize;
1400 	static char		*xferbuf;
1401 	const char		*cp;
1402 	char			*ep;
1403 	char			*volatile auth;
1404 	char			*volatile savefile;
1405 	char			*volatile location;
1406 	char			*volatile message;
1407 	char			*volatile decodedpath;
1408 	struct authinfo		wauth, pauth;
1409 	struct posinfo		pi;
1410 	off_t			hashbytes;
1411 	int			(*volatile closefunc)(FILE *);
1412 	FETCH			*volatile fin;
1413 	FILE			*volatile fout;
1414 	const char		*volatile penv = proxyenv;
1415 	struct urlinfo		ui, oui;
1416 	time_t			mtime;
1417 	void			*ssl = NULL;
1418 
1419 	DPRINTF("%s: `%s' proxyenv `%s'\n", __func__, url, STRorNULL(penv));
1420 
1421 	oldquit = oldalrm = oldint = oldpipe = SIG_ERR;
1422 	closefunc = NULL;
1423 	fin = NULL;
1424 	fout = NULL;
1425 	s = -1;
1426 	savefile = NULL;
1427 	auth = location = message = NULL;
1428 	ischunked = isproxy = 0;
1429 	rval = 1;
1430 
1431 	initurlinfo(&ui);
1432 	initurlinfo(&oui);
1433 	initauthinfo(&wauth, wwwauth);
1434 	initauthinfo(&pauth, proxyauth);
1435 
1436 	decodedpath = NULL;
1437 
1438 	if (sigsetjmp(httpabort, 1))
1439 		goto cleanup_fetch_url;
1440 
1441 	if (parse_url(url, "URL", &ui, &wauth, rui) == -1)
1442 		goto cleanup_fetch_url;
1443 
1444 	copyurlinfo(&oui, &ui);
1445 
1446 	if (ui.utype == FILE_URL_T && ! EMPTYSTRING(ui.host)
1447 	    && strcasecmp(ui.host, "localhost") != 0) {
1448 		warnx("No support for non local file URL `%s'", url);
1449 		goto cleanup_fetch_url;
1450 	}
1451 
1452 	if (EMPTYSTRING(ui.path)) {
1453 		if (ui.utype == FTP_URL_T) {
1454 			rval = fetch_ftp(url);
1455 			goto cleanup_fetch_url;
1456 		}
1457 		if (!IS_HTTP_TYPE(ui.utype) || outfile == NULL)	 {
1458 			warnx("Invalid URL (no file after host) `%s'", url);
1459 			goto cleanup_fetch_url;
1460 		}
1461 	}
1462 
1463 	decodedpath = ftp_strdup(ui.path);
1464 	url_decode(decodedpath);
1465 
1466 	if (outfile)
1467 		savefile = outfile;
1468 	else {
1469 		cp = strrchr(decodedpath, '/');		/* find savefile */
1470 		if (cp != NULL)
1471 			savefile = ftp_strdup(cp + 1);
1472 		else
1473 			savefile = ftp_strdup(decodedpath);
1474 		/*
1475 		 * Use the first URL we requested not the name after a
1476 		 * possible redirect, but careful to save it because our
1477 		 * "safety" check is the match to outfile.
1478 		 */
1479 		outfile = ftp_strdup(savefile);
1480 	}
1481 	DPRINTF("%s: savefile `%s'\n", __func__, savefile);
1482 	if (EMPTYSTRING(savefile)) {
1483 		if (ui.utype == FTP_URL_T) {
1484 			rval = fetch_ftp(url);
1485 			goto cleanup_fetch_url;
1486 		}
1487 		warnx("No file after directory (you must specify an "
1488 		    "output file) `%s'", url);
1489 		goto cleanup_fetch_url;
1490 	}
1491 
1492 	restart_point = 0;
1493 	filesize = -1;
1494 	initposinfo(&pi);
1495 	mtime = -1;
1496 	if (restartautofetch) {
1497 		if (stat(savefile, &sb) == 0)
1498 			restart_point = sb.st_size;
1499 	}
1500 	if (ui.utype == FILE_URL_T) {		/* file:// URLs */
1501 		direction = "copied";
1502 		fin = fetch_open(decodedpath, "r");
1503 		if (fin == NULL) {
1504 			warn("Can't open `%s'", decodedpath);
1505 			goto cleanup_fetch_url;
1506 		}
1507 		if (fstat(fetch_fileno(fin), &sb) == 0) {
1508 			mtime = sb.st_mtime;
1509 			filesize = sb.st_size;
1510 		}
1511 		if (restart_point) {
1512 			if (lseek(fetch_fileno(fin), restart_point, SEEK_SET)
1513 			    < 0) {
1514 				warn("Can't seek to restart `%s'",
1515 				    decodedpath);
1516 				goto cleanup_fetch_url;
1517 			}
1518 		}
1519 		if (verbose) {
1520 			fprintf(ttyout, "Copying %s", decodedpath);
1521 			if (restart_point)
1522 				fprintf(ttyout, " (restarting at " LLF ")",
1523 				    (LLT)restart_point);
1524 			fputs("\n", ttyout);
1525 		}
1526 		if (0 == rcvbuf_size) {
1527 			rcvbuf_size = 8 * 1024; /* XXX */
1528 		}
1529 	} else {				/* ftp:// or http:// URLs */
1530 		int hasleading;
1531 		static char hostnamebuf[MAXHOSTNAMELEN];
1532 
1533 		(void)strlcpy(hostnamebuf, ui.host, sizeof(hostnamebuf));
1534 		hostname = hostnamebuf;
1535 
1536 		if (penv == NULL) {
1537 #ifdef WITH_SSL
1538 			if (ui.utype == HTTPS_URL_T)
1539 				penv = getoptionvalue("https_proxy");
1540 #endif
1541 			if (penv == NULL && IS_HTTP_TYPE(ui.utype))
1542 				penv = getoptionvalue("http_proxy");
1543 			else if (ui.utype == FTP_URL_T)
1544 				penv = getoptionvalue("ftp_proxy");
1545 		}
1546 		direction = "retrieved";
1547 		if (! EMPTYSTRING(penv)) {			/* use proxy */
1548 
1549 			isproxy = handle_noproxy(ui.host, ui.portnum);
1550 
1551 			if (isproxy == 0 && ui.utype == FTP_URL_T) {
1552 				rval = fetch_ftp(url);
1553 				goto cleanup_fetch_url;
1554 			}
1555 
1556 			if (isproxy) {
1557 				if (restart_point) {
1558 					warnx(
1559 					    "Can't restart via proxy URL `%s'",
1560 					    penv);
1561 					goto cleanup_fetch_url;
1562 				}
1563 				if (handle_proxy(url, penv, &ui, &pauth) < 0)
1564 					goto cleanup_fetch_url;
1565 			}
1566 		} /* ! EMPTYSTRING(penv) */
1567 
1568 		s = ftp_socket(&ui, &ssl, &wauth);
1569 		if (s < 0) {
1570 			warnx("Can't connect to `%s:%s'", ui.host, ui.port);
1571 			goto cleanup_fetch_url;
1572 		}
1573 
1574 		oldalrm = xsignal(SIGALRM, timeouthttp);
1575 		alarmtimer(quit_time ? quit_time : 60);
1576 		fin = fetch_fdopen(s, "r+");
1577 		fetch_set_ssl(fin, ssl);
1578 		alarmtimer(0);
1579 
1580 		alarmtimer(quit_time ? quit_time : 60);
1581 		/*
1582 		 * Construct and send the request.
1583 		 */
1584 		if (verbose)
1585 			fprintf(ttyout, "Requesting %s\n", url);
1586 
1587 		hasleading = 0;
1588 #ifdef WITH_SSL
1589 		if (isproxy && oui.utype == HTTPS_URL_T) {
1590 			switch (connectmethod(fin, url, penv, &oui, &ui,
1591 			    &wauth, &pauth, __UNVOLATILE(&auth), &hasleading,
1592 			    &rval)) {
1593 			case C_CLEANUP:
1594 				goto cleanup_fetch_url;
1595 			case C_IMPROPER:
1596 				goto improper;
1597 			case C_OK:
1598 				break;
1599 			default:
1600 				abort();
1601 			}
1602 		}
1603 #endif
1604 
1605 		hasleading = print_get(fin, hasleading, isproxy, &oui, &ui);
1606 
1607 		if (flushcache)
1608 			print_cache(fin, isproxy);
1609 
1610 		print_agent(fin);
1611 		hasleading = print_proxy(fin, hasleading, wauth.auth,
1612 		     auth ? NULL : pauth.auth);
1613 		if (hasleading) {
1614 			hasleading = 0;
1615 			if (verbose)
1616 				fputs(")\n", ttyout);
1617 		}
1618 
1619 		fetch_printf(fin, "\r\n");
1620 		if (fetch_flush(fin) == EOF) {
1621 			warn("Writing HTTP request");
1622 			alarmtimer(0);
1623 			goto cleanup_fetch_url;
1624 		}
1625 		alarmtimer(0);
1626 
1627 		switch (negotiate_connection(fin, url, penv, &pi,
1628 		    &mtime, &wauth, &pauth, &rval, &ischunked,
1629 		    __UNVOLATILE(&auth), &ui)) {
1630 		case C_OK:
1631 			break;
1632 		case C_CLEANUP:
1633 			goto cleanup_fetch_url;
1634 		case C_IMPROPER:
1635 			goto improper;
1636 		default:
1637 			abort();
1638 		}
1639 	}
1640 
1641 	/* Open the output file. */
1642 
1643 	/*
1644 	 * Only trust filenames with special meaning if they came from
1645 	 * the command line
1646 	 */
1647 	if (outfile == savefile) {
1648 		if (strcmp(savefile, "-") == 0) {
1649 			fout = stdout;
1650 		} else if (*savefile == '|') {
1651 			oldpipe = xsignal(SIGPIPE, SIG_IGN);
1652 			fout = popen(savefile + 1, "w");
1653 			if (fout == NULL) {
1654 				warn("Can't execute `%s'", savefile + 1);
1655 				goto cleanup_fetch_url;
1656 			}
1657 			closefunc = pclose;
1658 		}
1659 	}
1660 	if (fout == NULL) {
1661 		if (restart_point && (
1662 		    (pi.rangeend != -1 && pi.rangeend <= restart_point) ||
1663 		    (pi.rangestart == -1 &&
1664 		    filesize != -1 && filesize <= restart_point))) {
1665 			/* already done */
1666 			if (verbose)
1667 				fprintf(ttyout, "already done\n");
1668 			rval = 0;
1669 			goto cleanup_fetch_url;
1670 		}
1671 		if (restart_point && pi.rangestart != -1) {
1672 			if (pi.entitylen != -1)
1673 				filesize = pi.entitylen;
1674 			if (pi.rangestart != restart_point) {
1675 				warnx(
1676 				    "Size of `%s' differs from save file `%s'",
1677 				    url, savefile);
1678 				goto cleanup_fetch_url;
1679 			}
1680 			fout = fopen(savefile, "a");
1681 		} else
1682 			fout = fopen(savefile, "w");
1683 		if (fout == NULL) {
1684 			warn("Can't open `%s'", savefile);
1685 			goto cleanup_fetch_url;
1686 		}
1687 		closefunc = fclose;
1688 	}
1689 
1690 			/* Trap signals */
1691 	oldquit = xsignal(SIGQUIT, psummary);
1692 	oldint = xsignal(SIGINT, aborthttp);
1693 
1694 	assert(rcvbuf_size > 0);
1695 	if ((size_t)rcvbuf_size > bufsize) {
1696 		if (xferbuf)
1697 			(void)free(xferbuf);
1698 		bufsize = rcvbuf_size;
1699 		xferbuf = ftp_malloc(bufsize);
1700 	}
1701 
1702 	bytes = 0;
1703 	hashbytes = mark;
1704 	if (oldalrm != SIG_ERR) {
1705 		(void)xsignal(SIGALRM, oldalrm);
1706 		oldalrm = SIG_ERR;
1707 	}
1708 	progressmeter(-1);
1709 
1710 			/* Finally, suck down the file. */
1711 	do {
1712 		long chunksize;
1713 		short lastchunk;
1714 
1715 		chunksize = 0;
1716 		lastchunk = 0;
1717 					/* read chunk-size */
1718 		if (ischunked) {
1719 			if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
1720 				warnx("Unexpected EOF reading chunk-size");
1721 				goto cleanup_fetch_url;
1722 			}
1723 			errno = 0;
1724 			chunksize = strtol(xferbuf, &ep, 16);
1725 			if (ep == xferbuf) {
1726 				warnx("Invalid chunk-size");
1727 				goto cleanup_fetch_url;
1728 			}
1729 			if (errno == ERANGE || chunksize < 0) {
1730 				errno = ERANGE;
1731 				warn("Chunk-size `%.*s'",
1732 				    (int)(ep-xferbuf), xferbuf);
1733 				goto cleanup_fetch_url;
1734 			}
1735 
1736 				/*
1737 				 * XXX: Work around bug in Apache 1.3.9 and
1738 				 *	1.3.11, which incorrectly put trailing
1739 				 *	space after the chunk-size.
1740 				 */
1741 			while (*ep == ' ')
1742 				ep++;
1743 
1744 					/* skip [ chunk-ext ] */
1745 			if (*ep == ';') {
1746 				while (*ep && *ep != '\r')
1747 					ep++;
1748 			}
1749 
1750 			if (strcmp(ep, "\r\n") != 0) {
1751 				warnx("Unexpected data following chunk-size");
1752 				goto cleanup_fetch_url;
1753 			}
1754 			DPRINTF("%s: got chunk-size of " LLF "\n", __func__,
1755 			    (LLT)chunksize);
1756 			if (chunksize == 0) {
1757 				lastchunk = 1;
1758 				goto chunkdone;
1759 			}
1760 		}
1761 					/* transfer file or chunk */
1762 		while (1) {
1763 			struct timeval then, now, td;
1764 			volatile off_t bufrem;
1765 
1766 			if (rate_get)
1767 				(void)gettimeofday(&then, NULL);
1768 			bufrem = rate_get ? rate_get : (off_t)bufsize;
1769 			if (ischunked)
1770 				bufrem = MIN(chunksize, bufrem);
1771 			while (bufrem > 0) {
1772 				size_t nr = MIN((off_t)bufsize, bufrem);
1773 				flen = fetch_read(xferbuf, sizeof(char),
1774 				    nr, fin);
1775 				if (flen == 0) {
1776 					if (fetch_error(fin))
1777 						goto chunkerror;
1778 					goto chunkdone;
1779 				}
1780 				bytes += flen;
1781 				bufrem -= flen;
1782 				if (maxwrite(xferbuf, sizeof(char), flen, fout)
1783 				    != flen) {
1784 					warn("Writing `%s'", savefile);
1785 					goto cleanup_fetch_url;
1786 				}
1787 				if (hash && !progress) {
1788 					while (bytes >= hashbytes) {
1789 						(void)putc('#', ttyout);
1790 						hashbytes += mark;
1791 					}
1792 					(void)fflush(ttyout);
1793 				}
1794 				if (ischunked) {
1795 					chunksize -= flen;
1796 					if (chunksize <= 0)
1797 						break;
1798 				}
1799 			}
1800 			if (rate_get) {
1801 				while (1) {
1802 					(void)gettimeofday(&now, NULL);
1803 					timersub(&now, &then, &td);
1804 					if (td.tv_sec > 0)
1805 						break;
1806 					usleep(1000000 - td.tv_usec);
1807 				}
1808 			}
1809 			if (ischunked && chunksize <= 0)
1810 				break;
1811 		}
1812 					/* read CRLF after chunk*/
1813  chunkdone:
1814 		if (ischunked) {
1815 			if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
1816 				alarmtimer(0);
1817 				warnx("Unexpected EOF reading chunk CRLF");
1818 				goto cleanup_fetch_url;
1819 			}
1820 			if (strcmp(xferbuf, "\r\n") != 0) {
1821 				warnx("Unexpected data following chunk");
1822 				goto cleanup_fetch_url;
1823 			}
1824 			if (lastchunk)
1825 				break;
1826 		}
1827 	} while (ischunked);
1828 
1829 /* XXX: deal with optional trailer & CRLF here? */
1830 chunkerror:
1831 	if (hash && !progress && bytes > 0) {
1832 		if (bytes < mark)
1833 			(void)putc('#', ttyout);
1834 		(void)putc('\n', ttyout);
1835 	}
1836 	if (fetch_error(fin)) {
1837 		warn("Reading file");
1838 		goto cleanup_fetch_url;
1839 	}
1840 	progressmeter(1);
1841 	(void)fflush(fout);
1842 	if (closefunc == fclose && mtime != -1) {
1843 		struct timeval tval[2];
1844 
1845 		(void)gettimeofday(&tval[0], NULL);
1846 		tval[1].tv_sec = mtime;
1847 		tval[1].tv_usec = 0;
1848 		(*closefunc)(fout);
1849 		fout = NULL;
1850 
1851 		if (utimes(savefile, tval) == -1) {
1852 			fprintf(ttyout,
1853 			    "Can't change modification time to %s",
1854 			    rfc2822time(localtime(&mtime)));
1855 		}
1856 	}
1857 	if (bytes > 0)
1858 		ptransfer(0);
1859 	bytes = 0;
1860 
1861 	rval = 0;
1862 	goto cleanup_fetch_url;
1863 
1864  improper:
1865 	warnx("Improper response from `%s:%s'", ui.host, ui.port);
1866 
1867  cleanup_fetch_url:
1868 	if (oldint != SIG_ERR)
1869 		(void)xsignal(SIGINT, oldint);
1870 	if (oldpipe != SIG_ERR)
1871 		(void)xsignal(SIGPIPE, oldpipe);
1872 	if (oldalrm != SIG_ERR)
1873 		(void)xsignal(SIGALRM, oldalrm);
1874 	if (oldquit != SIG_ERR)
1875 		(void)xsignal(SIGQUIT, oldquit);
1876 	if (fin != NULL)
1877 		fetch_close(fin);
1878 	else if (s != -1)
1879 		close(s);
1880 	if (closefunc != NULL && fout != NULL)
1881 		(*closefunc)(fout);
1882 	if (savefile != outfile)
1883 		FREEPTR(savefile);
1884 	freeurlinfo(&ui);
1885 	freeurlinfo(&oui);
1886 	freeauthinfo(&wauth);
1887 	freeauthinfo(&pauth);
1888 	FREEPTR(decodedpath);
1889 	FREEPTR(auth);
1890 	FREEPTR(location);
1891 	FREEPTR(message);
1892 	return (rval);
1893 }
1894 
1895 /*
1896  * Abort a HTTP retrieval
1897  */
1898 static void
1899 aborthttp(int notused)
1900 {
1901 	char msgbuf[100];
1902 	int len;
1903 
1904 	sigint_raised = 1;
1905 	alarmtimer(0);
1906 	if (fromatty) {
1907 		len = snprintf(msgbuf, sizeof(msgbuf),
1908 		    "\n%s: HTTP fetch aborted.\n", getprogname());
1909 		if (len > 0)
1910 			write(fileno(ttyout), msgbuf, len);
1911 	}
1912 	siglongjmp(httpabort, 1);
1913 }
1914 
1915 static void
1916 timeouthttp(int notused)
1917 {
1918 	char msgbuf[100];
1919 	int len;
1920 
1921 	alarmtimer(0);
1922 	if (fromatty) {
1923 		len = snprintf(msgbuf, sizeof(msgbuf),
1924 		    "\n%s: HTTP fetch timeout.\n", getprogname());
1925 		if (len > 0)
1926 			write(fileno(ttyout), msgbuf, len);
1927 	}
1928 	siglongjmp(httpabort, 1);
1929 }
1930 
1931 /*
1932  * Retrieve ftp URL or classic ftp argument using FTP.
1933  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1934  * is still open (e.g, ftp xfer with trailing /)
1935  */
1936 static int
1937 fetch_ftp(const char *url)
1938 {
1939 	char		*cp, *xargv[5], rempath[MAXPATHLEN];
1940 	char		*dir, *file;
1941 	char		 cmdbuf[MAXPATHLEN];
1942 	char		 dirbuf[4];
1943 	int		 dirhasglob, filehasglob, rval, transtype, xargc;
1944 	int		 oanonftp, oautologin;
1945 	struct authinfo	 auth;
1946 	struct urlinfo	 ui;
1947 
1948 	DPRINTF("%s: `%s'\n", __func__, url);
1949 	dir = file = NULL;
1950 	rval = 1;
1951 	transtype = TYPE_I;
1952 
1953 	initurlinfo(&ui);
1954 	initauthinfo(&auth, NULL);
1955 
1956 	if (STRNEQUAL(url, FTP_URL)) {
1957 		if ((parse_url(url, "URL", &ui, &auth, NULL) == -1) ||
1958 		    (auth.user != NULL && *auth.user == '\0') ||
1959 		    EMPTYSTRING(ui.host)) {
1960 			warnx("Invalid URL `%s'", url);
1961 			goto cleanup_fetch_ftp;
1962 		}
1963 		/*
1964 		 * Note: Don't url_decode(path) here.  We need to keep the
1965 		 * distinction between "/" and "%2F" until later.
1966 		 */
1967 
1968 					/* check for trailing ';type=[aid]' */
1969 		if (! EMPTYSTRING(ui.path)
1970 		    && (cp = strrchr(ui.path, ';')) != NULL) {
1971 			if (strcasecmp(cp, ";type=a") == 0)
1972 				transtype = TYPE_A;
1973 			else if (strcasecmp(cp, ";type=i") == 0)
1974 				transtype = TYPE_I;
1975 			else if (strcasecmp(cp, ";type=d") == 0) {
1976 				warnx(
1977 			    "Directory listing via a URL is not supported");
1978 				goto cleanup_fetch_ftp;
1979 			} else {
1980 				warnx("Invalid suffix `%s' in URL `%s'", cp,
1981 				    url);
1982 				goto cleanup_fetch_ftp;
1983 			}
1984 			*cp = 0;
1985 		}
1986 	} else {			/* classic style `[user@]host:[file]' */
1987 		ui.utype = CLASSIC_URL_T;
1988 		ui.host = ftp_strdup(url);
1989 		cp = strchr(ui.host, '@');
1990 		if (cp != NULL) {
1991 			*cp = '\0';
1992 			auth.user = ui.host;
1993 			anonftp = 0;	/* disable anonftp */
1994 			ui.host = ftp_strdup(cp + 1);
1995 		}
1996 		cp = strchr(ui.host, ':');
1997 		if (cp != NULL) {
1998 			*cp = '\0';
1999 			ui.path = ftp_strdup(cp + 1);
2000 		}
2001 	}
2002 	if (EMPTYSTRING(ui.host))
2003 		goto cleanup_fetch_ftp;
2004 
2005 			/* Extract the file and (if present) directory name. */
2006 	dir = ui.path;
2007 	if (! EMPTYSTRING(dir)) {
2008 		/*
2009 		 * If we are dealing with classic `[user@]host:[path]' syntax,
2010 		 * then a path of the form `/file' (resulting from input of the
2011 		 * form `host:/file') means that we should do "CWD /" before
2012 		 * retrieving the file.	 So we set dir="/" and file="file".
2013 		 *
2014 		 * But if we are dealing with URLs like `ftp://host/path' then
2015 		 * a path of the form `/file' (resulting from a URL of the form
2016 		 * `ftp://host//file') means that we should do `CWD ' (with an
2017 		 * empty argument) before retrieving the file.	So we set
2018 		 * dir="" and file="file".
2019 		 *
2020 		 * If the path does not contain / at all, we set dir=NULL.
2021 		 * (We get a path without any slashes if we are dealing with
2022 		 * classic `[user@]host:[file]' or URL `ftp://host/file'.)
2023 		 *
2024 		 * In all other cases, we set dir to a string that does not
2025 		 * include the final '/' that separates the dir part from the
2026 		 * file part of the path.  (This will be the empty string if
2027 		 * and only if we are dealing with a path of the form `/file'
2028 		 * resulting from an URL of the form `ftp://host//file'.)
2029 		 */
2030 		cp = strrchr(dir, '/');
2031 		if (cp == dir && ui.utype == CLASSIC_URL_T) {
2032 			file = cp + 1;
2033 			(void)strlcpy(dirbuf, "/", sizeof(dirbuf));
2034 			dir = dirbuf;
2035 		} else if (cp != NULL) {
2036 			*cp++ = '\0';
2037 			file = cp;
2038 		} else {
2039 			file = dir;
2040 			dir = NULL;
2041 		}
2042 	} else
2043 		dir = NULL;
2044 	if (ui.utype == FTP_URL_T && file != NULL) {
2045 		url_decode(file);
2046 		/* but still don't url_decode(dir) */
2047 	}
2048 	DPRINTF("%s: user `%s' pass `%s' host %s port %s "
2049 	    "path `%s' dir `%s' file `%s'\n", __func__,
2050 	    STRorNULL(auth.user), STRorNULL(auth.pass),
2051 	    STRorNULL(ui.host), STRorNULL(ui.port),
2052 	    STRorNULL(ui.path), STRorNULL(dir), STRorNULL(file));
2053 
2054 	dirhasglob = filehasglob = 0;
2055 	if (doglob &&
2056 	    (ui.utype == CLASSIC_URL_T || ui.utype == FTP_URL_T)) {
2057 		if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
2058 			dirhasglob = 1;
2059 		if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
2060 			filehasglob = 1;
2061 	}
2062 
2063 			/* Set up the connection */
2064 	oanonftp = anonftp;
2065 	if (connected)
2066 		disconnect(0, NULL);
2067 	anonftp = oanonftp;
2068 	(void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
2069 	xargv[0] = cmdbuf;
2070 	xargv[1] = ui.host;
2071 	xargv[2] = NULL;
2072 	xargc = 2;
2073 	if (ui.port) {
2074 		xargv[2] = ui.port;
2075 		xargv[3] = NULL;
2076 		xargc = 3;
2077 	}
2078 	oautologin = autologin;
2079 		/* don't autologin in setpeer(), use ftp_login() below */
2080 	autologin = 0;
2081 	setpeer(xargc, xargv);
2082 	autologin = oautologin;
2083 	if ((connected == 0) ||
2084 	    (connected == 1 && !ftp_login(ui.host, auth.user, auth.pass))) {
2085 		warnx("Can't connect or login to host `%s:%s'",
2086 			ui.host, ui.port ? ui.port : "?");
2087 		goto cleanup_fetch_ftp;
2088 	}
2089 
2090 	switch (transtype) {
2091 	case TYPE_A:
2092 		setascii(1, xargv);
2093 		break;
2094 	case TYPE_I:
2095 		setbinary(1, xargv);
2096 		break;
2097 	default:
2098 		errx(1, "%s: unknown transfer type %d", __func__, transtype);
2099 	}
2100 
2101 		/*
2102 		 * Change directories, if necessary.
2103 		 *
2104 		 * Note: don't use EMPTYSTRING(dir) below, because
2105 		 * dir=="" means something different from dir==NULL.
2106 		 */
2107 	if (dir != NULL && !dirhasglob) {
2108 		char *nextpart;
2109 
2110 		/*
2111 		 * If we are dealing with a classic `[user@]host:[path]'
2112 		 * (urltype is CLASSIC_URL_T) then we have a raw directory
2113 		 * name (not encoded in any way) and we can change
2114 		 * directories in one step.
2115 		 *
2116 		 * If we are dealing with an `ftp://host/path' URL
2117 		 * (urltype is FTP_URL_T), then RFC 3986 says we need to
2118 		 * send a separate CWD command for each unescaped "/"
2119 		 * in the path, and we have to interpret %hex escaping
2120 		 * *after* we find the slashes.	 It's possible to get
2121 		 * empty components here, (from multiple adjacent
2122 		 * slashes in the path) and RFC 3986 says that we should
2123 		 * still do `CWD ' (with a null argument) in such cases.
2124 		 *
2125 		 * Many ftp servers don't support `CWD ', so if there's an
2126 		 * error performing that command, bail out with a descriptive
2127 		 * message.
2128 		 *
2129 		 * Examples:
2130 		 *
2131 		 * host:			dir="", urltype=CLASSIC_URL_T
2132 		 *		logged in (to default directory)
2133 		 * host:file			dir=NULL, urltype=CLASSIC_URL_T
2134 		 *		"RETR file"
2135 		 * host:dir/			dir="dir", urltype=CLASSIC_URL_T
2136 		 *		"CWD dir", logged in
2137 		 * ftp://host/			dir="", urltype=FTP_URL_T
2138 		 *		logged in (to default directory)
2139 		 * ftp://host/dir/		dir="dir", urltype=FTP_URL_T
2140 		 *		"CWD dir", logged in
2141 		 * ftp://host/file		dir=NULL, urltype=FTP_URL_T
2142 		 *		"RETR file"
2143 		 * ftp://host//file		dir="", urltype=FTP_URL_T
2144 		 *		"CWD ", "RETR file"
2145 		 * host:/file			dir="/", urltype=CLASSIC_URL_T
2146 		 *		"CWD /", "RETR file"
2147 		 * ftp://host///file		dir="/", urltype=FTP_URL_T
2148 		 *		"CWD ", "CWD ", "RETR file"
2149 		 * ftp://host/%2F/file		dir="%2F", urltype=FTP_URL_T
2150 		 *		"CWD /", "RETR file"
2151 		 * ftp://host/foo/file		dir="foo", urltype=FTP_URL_T
2152 		 *		"CWD foo", "RETR file"
2153 		 * ftp://host/foo/bar/file	dir="foo/bar"
2154 		 *		"CWD foo", "CWD bar", "RETR file"
2155 		 * ftp://host//foo/bar/file	dir="/foo/bar"
2156 		 *		"CWD ", "CWD foo", "CWD bar", "RETR file"
2157 		 * ftp://host/foo//bar/file	dir="foo//bar"
2158 		 *		"CWD foo", "CWD ", "CWD bar", "RETR file"
2159 		 * ftp://host/%2F/foo/bar/file	dir="%2F/foo/bar"
2160 		 *		"CWD /", "CWD foo", "CWD bar", "RETR file"
2161 		 * ftp://host/%2Ffoo/bar/file	dir="%2Ffoo/bar"
2162 		 *		"CWD /foo", "CWD bar", "RETR file"
2163 		 * ftp://host/%2Ffoo%2Fbar/file dir="%2Ffoo%2Fbar"
2164 		 *		"CWD /foo/bar", "RETR file"
2165 		 * ftp://host/%2Ffoo%2Fbar%2Ffile	dir=NULL
2166 		 *		"RETR /foo/bar/file"
2167 		 *
2168 		 * Note that we don't need `dir' after this point.
2169 		 */
2170 		do {
2171 			if (ui.utype == FTP_URL_T) {
2172 				nextpart = strchr(dir, '/');
2173 				if (nextpart) {
2174 					*nextpart = '\0';
2175 					nextpart++;
2176 				}
2177 				url_decode(dir);
2178 			} else
2179 				nextpart = NULL;
2180 			DPRINTF("%s: dir `%s', nextpart `%s'\n", __func__,
2181 			    STRorNULL(dir), STRorNULL(nextpart));
2182 			if (ui.utype == FTP_URL_T || *dir != '\0') {
2183 				(void)strlcpy(cmdbuf, "cd", sizeof(cmdbuf));
2184 				xargv[0] = cmdbuf;
2185 				xargv[1] = dir;
2186 				xargv[2] = NULL;
2187 				dirchange = 0;
2188 				cd(2, xargv);
2189 				if (! dirchange) {
2190 					if (*dir == '\0' && code == 500)
2191 						fprintf(stderr,
2192 "\n"
2193 "ftp: The `CWD ' command (without a directory), which is required by\n"
2194 "     RFC 3986 to support the empty directory in the URL pathname (`//'),\n"
2195 "     conflicts with the server's conformance to RFC 959.\n"
2196 "     Try the same URL without the `//' in the URL pathname.\n"
2197 "\n");
2198 					goto cleanup_fetch_ftp;
2199 				}
2200 			}
2201 			dir = nextpart;
2202 		} while (dir != NULL);
2203 	}
2204 
2205 	if (EMPTYSTRING(file)) {
2206 		rval = -1;
2207 		goto cleanup_fetch_ftp;
2208 	}
2209 
2210 	if (dirhasglob) {
2211 		(void)strlcpy(rempath, dir,	sizeof(rempath));
2212 		(void)strlcat(rempath, "/",	sizeof(rempath));
2213 		(void)strlcat(rempath, file,	sizeof(rempath));
2214 		file = rempath;
2215 	}
2216 
2217 			/* Fetch the file(s). */
2218 	xargc = 2;
2219 	(void)strlcpy(cmdbuf, "get", sizeof(cmdbuf));
2220 	xargv[0] = cmdbuf;
2221 	xargv[1] = file;
2222 	xargv[2] = NULL;
2223 	if (dirhasglob || filehasglob) {
2224 		int ointeractive;
2225 
2226 		ointeractive = interactive;
2227 		interactive = 0;
2228 		if (restartautofetch)
2229 			(void)strlcpy(cmdbuf, "mreget", sizeof(cmdbuf));
2230 		else
2231 			(void)strlcpy(cmdbuf, "mget", sizeof(cmdbuf));
2232 		xargv[0] = cmdbuf;
2233 		mget(xargc, xargv);
2234 		interactive = ointeractive;
2235 	} else {
2236 		char *destfile = outfile;
2237 		if (destfile == NULL) {
2238 			cp = strrchr(file, '/');	/* find savefile */
2239 			if (cp != NULL)
2240 				destfile = cp + 1;
2241 			else
2242 				destfile = file;
2243 		}
2244 		xargv[2] = (char *)destfile;
2245 		xargv[3] = NULL;
2246 		xargc++;
2247 		if (restartautofetch)
2248 			reget(xargc, xargv);
2249 		else
2250 			get(xargc, xargv);
2251 	}
2252 
2253 	if ((code / 100) == COMPLETE)
2254 		rval = 0;
2255 
2256  cleanup_fetch_ftp:
2257 	freeurlinfo(&ui);
2258 	freeauthinfo(&auth);
2259 	return (rval);
2260 }
2261 
2262 /*
2263  * Retrieve the given file to outfile.
2264  * Supports arguments of the form:
2265  *	"host:path", "ftp://host/path"	if $ftpproxy, call fetch_url() else
2266  *					call fetch_ftp()
2267  *	"http://host/path"		call fetch_url() to use HTTP
2268  *	"file:///path"			call fetch_url() to copy
2269  *	"about:..."			print a message
2270  *
2271  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
2272  * is still open (e.g, ftp xfer with trailing /)
2273  */
2274 static int
2275 go_fetch(const char *url, struct urlinfo *rui)
2276 {
2277 	char *proxyenv;
2278 	char *p;
2279 
2280 #ifndef NO_ABOUT
2281 	/*
2282 	 * Check for about:*
2283 	 */
2284 	if (STRNEQUAL(url, ABOUT_URL)) {
2285 		url += sizeof(ABOUT_URL) -1;
2286 		if (strcasecmp(url, "ftp") == 0 ||
2287 		    strcasecmp(url, "tnftp") == 0) {
2288 			fputs(
2289 "This version of ftp has been enhanced by Luke Mewburn <lukem@NetBSD.org>\n"
2290 "for the NetBSD project.  Execute `man ftp' for more details.\n", ttyout);
2291 		} else if (strcasecmp(url, "lukem") == 0) {
2292 			fputs(
2293 "Luke Mewburn is the author of most of the enhancements in this ftp client.\n"
2294 "Please email feedback to <lukem@NetBSD.org>.\n", ttyout);
2295 		} else if (strcasecmp(url, "netbsd") == 0) {
2296 			fputs(
2297 "NetBSD is a freely available and redistributable UNIX-like operating system.\n"
2298 "For more information, see http://www.NetBSD.org/\n", ttyout);
2299 		} else if (strcasecmp(url, "version") == 0) {
2300 			fprintf(ttyout, "Version: %s %s%s\n",
2301 			    FTP_PRODUCT, FTP_VERSION,
2302 #ifdef INET6
2303 			    ""
2304 #else
2305 			    " (-IPv6)"
2306 #endif
2307 			);
2308 		} else {
2309 			fprintf(ttyout, "`%s' is an interesting topic.\n", url);
2310 		}
2311 		fputs("\n", ttyout);
2312 		return (0);
2313 	}
2314 #endif
2315 
2316 	/*
2317 	 * Check for file:// and http:// URLs.
2318 	 */
2319 	if (STRNEQUAL(url, HTTP_URL)
2320 #ifdef WITH_SSL
2321 	    || STRNEQUAL(url, HTTPS_URL)
2322 #endif
2323 	    || STRNEQUAL(url, FILE_URL))
2324 		return (fetch_url(url, NULL, NULL, NULL, rui));
2325 
2326 	/*
2327 	 * If it contains "://" but does not begin with ftp://
2328 	 * or something that was already handled, then it's
2329 	 * unsupported.
2330 	 *
2331 	 * If it contains ":" but not "://" then we assume the
2332 	 * part before the colon is a host name, not an URL scheme,
2333 	 * so we don't try to match that here.
2334 	 */
2335 	if ((p = strstr(url, "://")) != NULL && ! STRNEQUAL(url, FTP_URL))
2336 		errx(1, "Unsupported URL scheme `%.*s'", (int)(p - url), url);
2337 
2338 	/*
2339 	 * Refer to previous urlinfo if provided. This makes relative
2340 	 * redirects work.
2341 	 */
2342 	if (use_relative(rui))
2343 	    return fetch_url(url, NULL, NULL, NULL, rui);
2344 
2345 	/*
2346 	 * Try FTP URL-style and host:file arguments next.
2347 	 * If ftpproxy is set with an FTP URL, use fetch_url()
2348 	 * Otherwise, use fetch_ftp().
2349 	 */
2350 	proxyenv = getoptionvalue("ftp_proxy");
2351 	if (!EMPTYSTRING(proxyenv) && STRNEQUAL(url, FTP_URL))
2352 		return (fetch_url(url, NULL, NULL, NULL, rui));
2353 
2354 	return (fetch_ftp(url));
2355 }
2356 
2357 /*
2358  * Retrieve multiple files from the command line,
2359  * calling go_fetch() for each file.
2360  *
2361  * If an ftp path has a trailing "/", the path will be cd-ed into and
2362  * the connection remains open, and the function will return -1
2363  * (to indicate the connection is alive).
2364  * If an error occurs the return value will be the offset+1 in
2365  * argv[] of the file that caused a problem (i.e, argv[x]
2366  * returns x+1)
2367  * Otherwise, 0 is returned if all files retrieved successfully.
2368  */
2369 int
2370 auto_fetch(int argc, char *argv[])
2371 {
2372 	volatile int	argpos, rval;
2373 
2374 	argpos = rval = 0;
2375 
2376 	if (sigsetjmp(toplevel, 1)) {
2377 		if (connected)
2378 			disconnect(0, NULL);
2379 		if (rval > 0)
2380 			rval = argpos + 1;
2381 		return (rval);
2382 	}
2383 	(void)xsignal(SIGINT, intr);
2384 	(void)xsignal(SIGPIPE, lostpeer);
2385 
2386 	/*
2387 	 * Loop through as long as there's files to fetch.
2388 	 */
2389 	for (; (rval == 0) && (argpos < argc); argpos++) {
2390 		if (strchr(argv[argpos], ':') == NULL)
2391 			break;
2392 		redirect_loop = 0;
2393 		if (!anonftp)
2394 			anonftp = 2;	/* Handle "automatic" transfers. */
2395 		rval = go_fetch(argv[argpos], NULL);
2396 		if (outfile != NULL && strcmp(outfile, "-") != 0
2397 		    && outfile[0] != '|') {
2398 			FREEPTR(outfile);
2399 		}
2400 		if (rval > 0)
2401 			rval = argpos + 1;
2402 	}
2403 
2404 	if (connected && rval != -1)
2405 		disconnect(0, NULL);
2406 	return (rval);
2407 }
2408 
2409 
2410 /*
2411  * Upload multiple files from the command line.
2412  *
2413  * If an error occurs the return value will be the offset+1 in
2414  * argv[] of the file that caused a problem (i.e, argv[x]
2415  * returns x+1)
2416  * Otherwise, 0 is returned if all files uploaded successfully.
2417  */
2418 int
2419 auto_put(int argc, char **argv, const char *uploadserver)
2420 {
2421 	char	*uargv[4], *path, *pathsep;
2422 	int	 uargc, rval, argpos;
2423 	size_t	 len;
2424 	char	 cmdbuf[MAX_C_NAME];
2425 
2426 	(void)strlcpy(cmdbuf, "mput", sizeof(cmdbuf));
2427 	uargv[0] = cmdbuf;
2428 	uargv[1] = argv[0];
2429 	uargc = 2;
2430 	uargv[2] = uargv[3] = NULL;
2431 	pathsep = NULL;
2432 	rval = 1;
2433 
2434 	DPRINTF("%s: target `%s'\n", __func__, uploadserver);
2435 
2436 	path = ftp_strdup(uploadserver);
2437 	len = strlen(path);
2438 	if (path[len - 1] != '/' && path[len - 1] != ':') {
2439 			/*
2440 			 * make sure we always pass a directory to auto_fetch
2441 			 */
2442 		if (argc > 1) {		/* more than one file to upload */
2443 			len = strlen(uploadserver) + 2; /* path + "/" + "\0" */
2444 			free(path);
2445 			path = (char *)ftp_malloc(len);
2446 			(void)strlcpy(path, uploadserver, len);
2447 			(void)strlcat(path, "/", len);
2448 		} else {		/* single file to upload */
2449 			(void)strlcpy(cmdbuf, "put", sizeof(cmdbuf));
2450 			uargv[0] = cmdbuf;
2451 			pathsep = strrchr(path, '/');
2452 			if (pathsep == NULL) {
2453 				pathsep = strrchr(path, ':');
2454 				if (pathsep == NULL) {
2455 					warnx("Invalid URL `%s'", path);
2456 					goto cleanup_auto_put;
2457 				}
2458 				pathsep++;
2459 				uargv[2] = ftp_strdup(pathsep);
2460 				pathsep[0] = '/';
2461 			} else
2462 				uargv[2] = ftp_strdup(pathsep + 1);
2463 			pathsep[1] = '\0';
2464 			uargc++;
2465 		}
2466 	}
2467 	DPRINTF("%s: URL `%s' argv[2] `%s'\n", __func__,
2468 	    path, STRorNULL(uargv[2]));
2469 
2470 			/* connect and cwd */
2471 	rval = auto_fetch(1, &path);
2472 	if(rval >= 0)
2473 		goto cleanup_auto_put;
2474 
2475 	rval = 0;
2476 
2477 			/* target filename provided; upload 1 file */
2478 			/* XXX : is this the best way? */
2479 	if (uargc == 3) {
2480 		uargv[1] = argv[0];
2481 		put(uargc, uargv);
2482 		if ((code / 100) != COMPLETE)
2483 			rval = 1;
2484 	} else {	/* otherwise a target dir: upload all files to it */
2485 		for(argpos = 0; argv[argpos] != NULL; argpos++) {
2486 			uargv[1] = argv[argpos];
2487 			mput(uargc, uargv);
2488 			if ((code / 100) != COMPLETE) {
2489 				rval = argpos + 1;
2490 				break;
2491 			}
2492 		}
2493 	}
2494 
2495  cleanup_auto_put:
2496 	free(path);
2497 	FREEPTR(uargv[2]);
2498 	return (rval);
2499 }
2500