xref: /netbsd-src/usr.bin/ftp/fetch.c (revision 4439cfd0acf9c7dc90625e5cd83b2317a9ab8967)
1 /*	$NetBSD: fetch.c,v 1.241 2024/09/25 16:55:39 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.241 2024/09/25 16:55:39 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, *ep, *scheme, *errormsg;
265 	char		*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 = (in_port_t)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 static 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 	struct entry *np;
869 
870 	if (isproxy) {
871 		if (verbose) {
872 			fprintf(ttyout, "%svia %s:%u", leading,
873 			    ui->host, ui->portnum);
874 			leading = ", ";
875 			hasleading++;
876 		}
877 		fetch_printf(fin, "GET %s HTTP/1.0\r\n", ui->path);
878 		print_host(fin, oui);
879 		return hasleading;
880 	}
881 
882 	fetch_printf(fin, "GET %s HTTP/1.1\r\n", ui->path);
883 	print_host(fin, ui);
884 	fetch_printf(fin, "Accept: */*\r\n");
885 	fetch_printf(fin, "Connection: close\r\n");
886 	SLIST_FOREACH(np, &custom_headers, entries) {
887 		fetch_printf(fin, "%s\r\n", np->header);
888 	}
889 
890 	if (restart_point) {
891 		fputs(leading, ttyout);
892 		fetch_printf(fin, "Range: bytes=" LLF "-\r\n",
893 		    (LLT)restart_point);
894 		fprintf(ttyout, "restarting at " LLF, (LLT)restart_point);
895 		hasleading++;
896 	}
897 	return hasleading;
898 }
899 
900 static void
901 getmtime(const char *cp, time_t *mtime)
902 {
903 	struct tm parsed;
904 	const char *t;
905 
906 	memset(&parsed, 0, sizeof(parsed));
907 	t = parse_rfc2616time(&parsed, cp);
908 
909 	if (t == NULL)
910 		return;
911 
912 	parsed.tm_isdst = -1;
913 	if (*t == '\0')
914 		*mtime = timegm(&parsed);
915 
916 #ifndef NO_DEBUG
917 	if (ftp_debug && *mtime != -1) {
918 		fprintf(ttyout, "parsed time as: %s",
919 		    rfc2822time(localtime(mtime)));
920 	}
921 #endif
922 }
923 
924 static int
925 print_proxy(FETCH *fin, int hasleading, const char *wwwauth,
926     const char *proxyauth)
927 {
928 	const char *leading = hasleading ? ", " : "  (";
929 
930 	if (wwwauth) {
931 		if (verbose) {
932 			fprintf(ttyout, "%swith authorization", leading);
933 			hasleading++;
934 		}
935 		fetch_printf(fin, "Authorization: %s\r\n", wwwauth);
936 	}
937 	if (proxyauth) {
938 		if (verbose) {
939 			fprintf(ttyout, "%swith proxy authorization", leading);
940 			hasleading++;
941 		}
942 		fetch_printf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
943 	}
944 	return hasleading;
945 }
946 
947 #ifdef WITH_SSL
948 static void
949 print_connect(FETCH *fin, const struct urlinfo *ui)
950 {
951 	char hname[NI_MAXHOST], *p;
952 	const char *h;
953 
954 	if (isipv6addr(ui->host)) {
955 		/*
956 		 * strip off IPv6 scope identifier,
957 		 * since it is local to the node
958 		 */
959 		if ((p = strchr(ui->host, '%')) == NULL)
960 			snprintf(hname, sizeof(hname), "[%s]", ui->host);
961 		else
962 			snprintf(hname, sizeof(hname), "[%.*s]",
963 			    (int)(p - ui->host), ui->host);
964 		h = hname;
965 	} else
966 		h = ui->host;
967 
968 	fetch_printf(fin, "CONNECT %s:%d HTTP/1.1\r\n", h, ui->portnum);
969 	fetch_printf(fin, "Host: %s:%d\r\n", h, ui->portnum);
970 }
971 #endif
972 
973 #define	C_OK 0
974 #define	C_CLEANUP 1
975 #define	C_IMPROPER 2
976 
977 static int
978 getresponseline(FETCH *fin, char *buf, size_t buflen, int *len)
979 {
980 	const char *errormsg;
981 
982 	alarmtimer(quit_time ? quit_time : 60);
983 	*len = fetch_getline(fin, buf, buflen, &errormsg);
984 	alarmtimer(0);
985 	if (*len < 0) {
986 		if (*errormsg == '\n')
987 			errormsg++;
988 		warnx("Receiving HTTP reply: %s", errormsg);
989 		return C_CLEANUP;
990 	}
991 	while (*len > 0 && (ISLWS(buf[*len-1])))
992 		buf[--*len] = '\0';
993 
994 	if (*len)
995 		DPRINTF("%s: received `%s'\n", __func__, buf);
996 	return C_OK;
997 }
998 
999 static int
1000 getresponse(FETCH *fin, char **cp, size_t buflen, int *hcode)
1001 {
1002 	int len, rv;
1003 	char *ep, *buf = *cp;
1004 
1005 	*hcode = 0;
1006 	if ((rv = getresponseline(fin, buf, buflen, &len)) != C_OK)
1007 		return rv;
1008 
1009 	/* Determine HTTP response code */
1010 	*cp = strchr(buf, ' ');
1011 	if (*cp == NULL)
1012 		return C_IMPROPER;
1013 
1014 	(*cp)++;
1015 
1016 	*hcode = strtol(*cp, &ep, 10);
1017 	if (*ep != '\0' && !isspace((unsigned char)*ep))
1018 		return C_IMPROPER;
1019 
1020 	return C_OK;
1021 }
1022 
1023 static int
1024 parse_posinfo(const char **cp, struct posinfo *pi)
1025 {
1026 	char *ep;
1027 	if (!match_token(cp, "bytes"))
1028 		return -1;
1029 
1030 	if (**cp == '*')
1031 		(*cp)++;
1032 	else {
1033 		pi->rangestart = STRTOLL(*cp, &ep, 10);
1034 		if (pi->rangestart < 0 || *ep != '-')
1035 			return -1;
1036 		*cp = ep + 1;
1037 		pi->rangeend = STRTOLL(*cp, &ep, 10);
1038 		if (pi->rangeend < 0 || pi->rangeend < pi->rangestart)
1039 			return -1;
1040 		*cp = ep;
1041 	}
1042 	if (**cp != '/')
1043 		return -1;
1044 	(*cp)++;
1045 	if (**cp == '*')
1046 		(*cp)++;
1047 	else {
1048 		pi->entitylen = STRTOLL(*cp, &ep, 10);
1049 		if (pi->entitylen < 0)
1050 			return -1;
1051 		*cp = ep;
1052 	}
1053 	if (**cp != '\0')
1054 		return -1;
1055 
1056 #ifndef NO_DEBUG
1057 	if (ftp_debug) {
1058 		fprintf(ttyout, "parsed range as: ");
1059 		if (pi->rangestart == -1)
1060 			fprintf(ttyout, "*");
1061 		else
1062 			fprintf(ttyout, LLF "-" LLF, (LLT)pi->rangestart,
1063 			    (LLT)pi->rangeend);
1064 		fprintf(ttyout, "/" LLF "\n", (LLT)pi->entitylen);
1065 	}
1066 #endif
1067 	return 0;
1068 }
1069 
1070 #ifndef NO_AUTH
1071 static void
1072 do_auth(int hcode, const char *url, const char *penv, struct authinfo *wauth,
1073     struct authinfo *pauth, char **auth, const char *message,
1074     volatile int *rval, struct urlinfo *ui)
1075 {
1076 	struct authinfo aauth;
1077 	char *response;
1078 
1079 	if (hcode == 401)
1080 		aauth = *wauth;
1081 	else
1082 		aauth = *pauth;
1083 
1084 	if (verbose || aauth.auth == NULL ||
1085 	    aauth.user == NULL || aauth.pass == NULL)
1086 		fprintf(ttyout, "%s\n", message);
1087 	if (EMPTYSTRING(*auth)) {
1088 		warnx("No authentication challenge provided by server");
1089 		return;
1090 	}
1091 
1092 	if (aauth.auth != NULL) {
1093 		char reply[10];
1094 
1095 		fprintf(ttyout, "Authorization failed. Retry (y/n)? ");
1096 		if (get_line(stdin, reply, sizeof(reply), NULL) < 0) {
1097 			return;
1098 		}
1099 		if (tolower((unsigned char)reply[0]) != 'y')
1100 			return;
1101 
1102 		aauth.user = NULL;
1103 		aauth.pass = NULL;
1104 	}
1105 
1106 	if (auth_url(*auth, &response, &aauth) == 0) {
1107 		*rval = fetch_url(url, penv,
1108 		    hcode == 401 ? pauth->auth : response,
1109 		    hcode == 401 ? response : wauth->auth,
1110 		    ui);
1111 		memset(response, 0, strlen(response));
1112 		FREEPTR(response);
1113 	}
1114 }
1115 #endif
1116 
1117 static int
1118 negotiate_connection(FETCH *fin, const char *url, const char *penv,
1119     struct posinfo *pi, time_t *mtime, struct authinfo *wauth,
1120     struct authinfo *pauth, volatile int *rval, volatile int *ischunked,
1121     char **auth, struct urlinfo *ui)
1122 {
1123 	int			len, hcode, rv;
1124 	char			*buf = NULL, *ep;
1125 	const char		*cp, *token;
1126 	char			*location, *message;
1127 
1128 	*auth = message = location = NULL;
1129 
1130 	buf = ftp_malloc(ftp_buflen);
1131 
1132 	/* Read the response */
1133 	ep = buf;
1134 	switch (getresponse(fin, &ep, ftp_buflen, &hcode)) {
1135 	case C_CLEANUP:
1136 		goto cleanup_fetch_url;
1137 	case C_IMPROPER:
1138 		goto improper;
1139 	case C_OK:
1140 		message = ftp_strdup(ep);
1141 		break;
1142 	}
1143 
1144 	/* Read the rest of the header. */
1145 
1146 	for (;;) {
1147 		if ((rv = getresponseline(fin, buf, ftp_buflen, &len)) != C_OK)
1148 			goto cleanup_fetch_url;
1149 		if (len == 0)
1150 			break;
1151 
1152 	/*
1153 	 * Look for some headers
1154 	 */
1155 
1156 		cp = buf;
1157 
1158 		if (match_token(&cp, "Content-Length:")) {
1159 			filesize = STRTOLL(cp, &ep, 10);
1160 			if (filesize < 0 || *ep != '\0')
1161 				goto improper;
1162 			DPRINTF("%s: parsed len as: " LLF "\n",
1163 			    __func__, (LLT)filesize);
1164 
1165 		} else if (match_token(&cp, "Content-Range:")) {
1166 			if (parse_posinfo(&cp, pi) == -1)
1167 				goto improper;
1168 			if (! restart_point) {
1169 				warnx(
1170 			    "Received unexpected Content-Range header");
1171 				goto cleanup_fetch_url;
1172 			}
1173 
1174 		} else if (match_token(&cp, "Last-Modified:")) {
1175 			getmtime(cp, mtime);
1176 
1177 		} else if (match_token(&cp, "Location:")) {
1178 			location = ftp_strdup(cp);
1179 			DPRINTF("%s: parsed location as `%s'\n",
1180 			    __func__, cp);
1181 
1182 		} else if (match_token(&cp, "Transfer-Encoding:")) {
1183 			if (match_token(&cp, "binary")) {
1184 				warnx(
1185 		"Bogus transfer encoding `binary' (fetching anyway)");
1186 				continue;
1187 			}
1188 			if (! (token = match_token(&cp, "chunked"))) {
1189 				warnx(
1190 			    "Unsupported transfer encoding `%s'",
1191 				    token);
1192 				goto cleanup_fetch_url;
1193 			}
1194 			(*ischunked)++;
1195 			DPRINTF("%s: using chunked encoding\n",
1196 			    __func__);
1197 
1198 		} else if (match_token(&cp, "Proxy-Authenticate:")
1199 			|| match_token(&cp, "WWW-Authenticate:")) {
1200 			if (! (token = match_token(&cp, "Basic"))) {
1201 				DPRINTF("%s: skipping unknown auth "
1202 				    "scheme `%s'\n", __func__, token);
1203 				continue;
1204 			}
1205 			FREEPTR(*auth);
1206 			*auth = ftp_strdup(token);
1207 			DPRINTF("%s: parsed auth as `%s'\n",
1208 			    __func__, cp);
1209 		}
1210 
1211 	}
1212 			/* finished parsing header */
1213 
1214 	switch (hcode) {
1215 	case 200:
1216 		break;
1217 	case 206:
1218 		if (! restart_point) {
1219 			warnx("Not expecting partial content header");
1220 			goto cleanup_fetch_url;
1221 		}
1222 		break;
1223 	case 300:
1224 	case 301:
1225 	case 302:
1226 	case 303:
1227 	case 305:
1228 	case 307:
1229 		if (EMPTYSTRING(location)) {
1230 			warnx(
1231 			"No redirection Location provided by server");
1232 			goto cleanup_fetch_url;
1233 		}
1234 		if (redirect_loop++ > 5) {
1235 			warnx("Too many redirections requested");
1236 			goto cleanup_fetch_url;
1237 		}
1238 		if (hcode == 305) {
1239 			if (verbose)
1240 				fprintf(ttyout, "Redirected via %s\n",
1241 				    location);
1242 			*rval = fetch_url(url, location,
1243 			    pauth->auth, wauth->auth, ui);
1244 		} else {
1245 			if (verbose)
1246 				fprintf(ttyout, "Redirected to %s\n",
1247 				    location);
1248 			*rval = go_fetch(location, ui);
1249 		}
1250 		goto cleanup_fetch_url;
1251 #ifndef NO_AUTH
1252 	case 401:
1253 	case 407:
1254 		do_auth(hcode, url, penv, wauth, pauth, auth, message, rval,
1255 		    ui);
1256 		goto cleanup_fetch_url;
1257 #endif
1258 	default:
1259 		if (message)
1260 			warnx("Error retrieving file `%s'", message);
1261 		else
1262 			warnx("Unknown error retrieving file");
1263 		goto cleanup_fetch_url;
1264 	}
1265 	rv = C_OK;
1266 	goto out;
1267 
1268 cleanup_fetch_url:
1269 	rv = C_CLEANUP;
1270 	goto out;
1271 improper:
1272 	rv = C_IMPROPER;
1273 	goto out;
1274 out:
1275 	FREEPTR(buf);
1276 	FREEPTR(message);
1277 	FREEPTR(location);
1278 	return rv;
1279 }		/* end of ftp:// or http:// specific setup */
1280 
1281 #ifdef WITH_SSL
1282 static int
1283 connectmethod(FETCH *fin, const char *url, const char *penv,
1284     struct urlinfo *oui, struct urlinfo *ui, struct authinfo *wauth,
1285     struct authinfo *pauth, char **auth, int *hasleading, volatile int *rval)
1286 {
1287 	void *ssl;
1288 	int hcode, rv;
1289 	const char *cp;
1290 	char *buf = NULL, *ep;
1291 	char *message = NULL;
1292 
1293 	print_connect(fin, oui);
1294 
1295 	print_agent(fin);
1296 	*hasleading = print_proxy(fin, *hasleading, NULL, pauth->auth);
1297 
1298 	if (verbose && *hasleading)
1299 		fputs(")\n", ttyout);
1300 	*hasleading = 0;
1301 
1302 	fetch_printf(fin, "\r\n");
1303 	if (fetch_flush(fin) == EOF) {
1304 		warn("Writing HTTP request");
1305 		alarmtimer(0);
1306 		goto cleanup_fetch_url;
1307 	}
1308 	alarmtimer(0);
1309 
1310 	buf = ftp_malloc(ftp_buflen);
1311 
1312 	/* Read the response */
1313 	ep = buf;
1314 	switch (getresponse(fin, &ep, ftp_buflen, &hcode)) {
1315 	case C_CLEANUP:
1316 		goto cleanup_fetch_url;
1317 	case C_IMPROPER:
1318 		goto improper;
1319 	case C_OK:
1320 		message = ftp_strdup(ep);
1321 		break;
1322 	}
1323 
1324 	for (;;) {
1325 		int len;
1326 		if (getresponseline(fin, buf, ftp_buflen, &len) != C_OK)
1327 			goto cleanup_fetch_url;
1328 		if (len == 0)
1329 			break;
1330 
1331 		cp = buf;
1332 		if (match_token(&cp, "Proxy-Authenticate:")) {
1333 			const char *token;
1334 			if (!(token = match_token(&cp, "Basic"))) {
1335 				DPRINTF(
1336 				    "%s: skipping unknown auth scheme `%s'\n",
1337 				    __func__, token);
1338 				continue;
1339 			}
1340 			FREEPTR(*auth);
1341 			*auth = ftp_strdup(token);
1342 			DPRINTF("%s: parsed auth as " "`%s'\n", __func__, cp);
1343 		}
1344 	}
1345 
1346 	/* finished parsing header */
1347 	switch (hcode) {
1348 	case 200:
1349 		break;
1350 #ifndef NO_AUTH
1351 	case 407:
1352 		do_auth(hcode, url, penv, wauth, pauth, auth, message, rval,
1353 		    ui);
1354 		goto cleanup_fetch_url;
1355 #endif
1356 	default:
1357 		if (message)
1358 			warnx("Error proxy connect " "`%s'", message);
1359 		else
1360 			warnx("Unknown error proxy " "connect");
1361 		goto cleanup_fetch_url;
1362 	}
1363 
1364 	if ((ssl = fetch_start_ssl(fetch_fileno(fin), oui->host)) == NULL)
1365 		goto cleanup_fetch_url;
1366 	fetch_set_ssl(fin, ssl);
1367 
1368 	rv = C_OK;
1369 	goto out;
1370 improper:
1371 	rv = C_IMPROPER;
1372 	goto out;
1373 cleanup_fetch_url:
1374 	rv = C_CLEANUP;
1375 	goto out;
1376 out:
1377 	FREEPTR(buf);
1378 	FREEPTR(message);
1379 	return rv;
1380 }
1381 #endif
1382 
1383 /*
1384  * Retrieve URL, via a proxy if necessary, using HTTP.
1385  * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
1386  * http_proxy/https_proxy as appropriate.
1387  * Supports HTTP redirects.
1388  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1389  * is still open (e.g, ftp xfer with trailing /)
1390  */
1391 static int
1392 fetch_url(const char *url, const char *proxyenv, char *proxyauth,
1393     char *wwwauth, struct urlinfo *rui)
1394 {
1395 	sigfunc volatile	oldint;
1396 	sigfunc volatile	oldpipe;
1397 	sigfunc volatile	oldalrm;
1398 	sigfunc volatile	oldquit;
1399 	int volatile		s;
1400 	struct stat		sb;
1401 	int volatile		isproxy;
1402 	int volatile		rval, ischunked;
1403 	size_t			flen;
1404 	static size_t		bufsize;
1405 	static char		*xferbuf;
1406 	const char		*cp;
1407 	char			*ep;
1408 	char			*volatile auth;
1409 	char			*volatile savefile;
1410 	char			*volatile location;
1411 	char			*volatile message;
1412 	char			*volatile decodedpath;
1413 	struct authinfo		wauth, pauth;
1414 	struct posinfo		pi;
1415 	off_t			hashbytes;
1416 	int			(*volatile closefunc)(FILE *);
1417 	FETCH			*volatile fin;
1418 	FILE			*volatile fout;
1419 	const char		*volatile penv = proxyenv;
1420 	struct urlinfo		ui, oui;
1421 	time_t			mtime;
1422 	void			*ssl = NULL;
1423 
1424 	DPRINTF("%s: `%s' proxyenv `%s'\n", __func__, url, STRorNULL(penv));
1425 
1426 	oldquit = oldalrm = oldint = oldpipe = SIG_ERR;
1427 	closefunc = NULL;
1428 	fin = NULL;
1429 	fout = NULL;
1430 	s = -1;
1431 	savefile = NULL;
1432 	auth = location = message = NULL;
1433 	ischunked = isproxy = 0;
1434 	rval = 1;
1435 
1436 	initurlinfo(&ui);
1437 	initurlinfo(&oui);
1438 	initauthinfo(&wauth, wwwauth);
1439 	initauthinfo(&pauth, proxyauth);
1440 
1441 	decodedpath = NULL;
1442 
1443 	if (sigsetjmp(httpabort, 1))
1444 		goto cleanup_fetch_url;
1445 
1446 	if (parse_url(url, "URL", &ui, &wauth, rui) == -1)
1447 		goto cleanup_fetch_url;
1448 
1449 	copyurlinfo(&oui, &ui);
1450 
1451 	if (ui.utype == FILE_URL_T && ! EMPTYSTRING(ui.host)
1452 	    && strcasecmp(ui.host, "localhost") != 0) {
1453 		warnx("No support for non local file URL `%s'", url);
1454 		goto cleanup_fetch_url;
1455 	}
1456 
1457 	if (EMPTYSTRING(ui.path)) {
1458 		if (ui.utype == FTP_URL_T) {
1459 			rval = fetch_ftp(url);
1460 			goto cleanup_fetch_url;
1461 		}
1462 		if (!IS_HTTP_TYPE(ui.utype) || outfile == NULL)	 {
1463 			warnx("Invalid URL (no file after host) `%s'", url);
1464 			goto cleanup_fetch_url;
1465 		}
1466 	}
1467 
1468 	decodedpath = ftp_strdup(ui.path);
1469 	url_decode(decodedpath);
1470 
1471 	if (outfile)
1472 		savefile = outfile;
1473 	else {
1474 		cp = strrchr(decodedpath, '/');		/* find savefile */
1475 		if (cp != NULL)
1476 			savefile = ftp_strdup(cp + 1);
1477 		else
1478 			savefile = ftp_strdup(decodedpath);
1479 		/*
1480 		 * Use the first URL we requested not the name after a
1481 		 * possible redirect, but careful to save it because our
1482 		 * "safety" check is the match to outfile.
1483 		 */
1484 		outfile = ftp_strdup(savefile);
1485 	}
1486 	DPRINTF("%s: savefile `%s'\n", __func__, savefile);
1487 	if (EMPTYSTRING(savefile)) {
1488 		if (ui.utype == FTP_URL_T) {
1489 			rval = fetch_ftp(url);
1490 			goto cleanup_fetch_url;
1491 		}
1492 		warnx("No file after directory (you must specify an "
1493 		    "output file) `%s'", url);
1494 		goto cleanup_fetch_url;
1495 	}
1496 
1497 	restart_point = 0;
1498 	filesize = -1;
1499 	initposinfo(&pi);
1500 	mtime = -1;
1501 	if (restartautofetch) {
1502 		if (stat(savefile, &sb) == 0)
1503 			restart_point = sb.st_size;
1504 	}
1505 	if (ui.utype == FILE_URL_T) {		/* file:// URLs */
1506 		direction = "copied";
1507 		fin = fetch_open(decodedpath, "r");
1508 		if (fin == NULL) {
1509 			warn("Can't open `%s'", decodedpath);
1510 			goto cleanup_fetch_url;
1511 		}
1512 		if (fstat(fetch_fileno(fin), &sb) == 0) {
1513 			mtime = sb.st_mtime;
1514 			filesize = sb.st_size;
1515 		}
1516 		if (restart_point) {
1517 			if (lseek(fetch_fileno(fin), restart_point, SEEK_SET)
1518 			    < 0) {
1519 				warn("Can't seek to restart `%s'",
1520 				    decodedpath);
1521 				goto cleanup_fetch_url;
1522 			}
1523 		}
1524 		if (verbose) {
1525 			fprintf(ttyout, "Copying %s", decodedpath);
1526 			if (restart_point)
1527 				fprintf(ttyout, " (restarting at " LLF ")",
1528 				    (LLT)restart_point);
1529 			fputs("\n", ttyout);
1530 		}
1531 		if (0 == rcvbuf_size) {
1532 			rcvbuf_size = 8 * 1024; /* XXX */
1533 		}
1534 	} else {				/* ftp:// or http:// URLs */
1535 		int hasleading;
1536 		static char hostnamebuf[MAXHOSTNAMELEN];
1537 
1538 		(void)strlcpy(hostnamebuf, ui.host, sizeof(hostnamebuf));
1539 		hostname = hostnamebuf;
1540 
1541 		if (penv == NULL) {
1542 #ifdef WITH_SSL
1543 			if (ui.utype == HTTPS_URL_T)
1544 				penv = getoptionvalue("https_proxy");
1545 #endif
1546 			if (penv == NULL && IS_HTTP_TYPE(ui.utype))
1547 				penv = getoptionvalue("http_proxy");
1548 			else if (ui.utype == FTP_URL_T)
1549 				penv = getoptionvalue("ftp_proxy");
1550 		}
1551 		direction = "retrieved";
1552 		if (! EMPTYSTRING(penv)) {			/* use proxy */
1553 
1554 			isproxy = handle_noproxy(ui.host, ui.portnum);
1555 
1556 			if (isproxy == 0 && ui.utype == FTP_URL_T) {
1557 				rval = fetch_ftp(url);
1558 				goto cleanup_fetch_url;
1559 			}
1560 
1561 			if (isproxy) {
1562 				if (restart_point) {
1563 					warnx(
1564 					    "Can't restart via proxy URL `%s'",
1565 					    penv);
1566 					goto cleanup_fetch_url;
1567 				}
1568 				if (handle_proxy(url, penv, &ui, &pauth) < 0)
1569 					goto cleanup_fetch_url;
1570 			}
1571 		} /* ! EMPTYSTRING(penv) */
1572 
1573 		s = ftp_socket(&ui, &ssl, &wauth);
1574 		if (s < 0) {
1575 			warnx("Can't connect to `%s:%s'", ui.host, ui.port);
1576 			goto cleanup_fetch_url;
1577 		}
1578 
1579 		oldalrm = xsignal(SIGALRM, timeouthttp);
1580 		alarmtimer(quit_time ? quit_time : 60);
1581 		fin = fetch_fdopen(s, "r+");
1582 		fetch_set_ssl(fin, ssl);
1583 		alarmtimer(0);
1584 
1585 		alarmtimer(quit_time ? quit_time : 60);
1586 		/*
1587 		 * Construct and send the request.
1588 		 */
1589 		if (verbose)
1590 			fprintf(ttyout, "Requesting %s\n", url);
1591 
1592 		hasleading = 0;
1593 #ifdef WITH_SSL
1594 		if (isproxy && oui.utype == HTTPS_URL_T) {
1595 			switch (connectmethod(fin, url, penv, &oui, &ui,
1596 			    &wauth, &pauth, __UNVOLATILE(&auth), &hasleading,
1597 			    &rval)) {
1598 			case C_CLEANUP:
1599 				goto cleanup_fetch_url;
1600 			case C_IMPROPER:
1601 				goto improper;
1602 			case C_OK:
1603 				break;
1604 			default:
1605 				abort();
1606 			}
1607 		}
1608 #endif
1609 
1610 		hasleading = print_get(fin, hasleading, isproxy, &oui, &ui);
1611 
1612 		if (flushcache)
1613 			print_cache(fin, isproxy);
1614 
1615 		print_agent(fin);
1616 		hasleading = print_proxy(fin, hasleading, wauth.auth,
1617 		     auth ? NULL : pauth.auth);
1618 		if (hasleading) {
1619 			hasleading = 0;
1620 			if (verbose)
1621 				fputs(")\n", ttyout);
1622 		}
1623 
1624 		fetch_printf(fin, "\r\n");
1625 		if (fetch_flush(fin) == EOF) {
1626 			warn("Writing HTTP request");
1627 			alarmtimer(0);
1628 			goto cleanup_fetch_url;
1629 		}
1630 		alarmtimer(0);
1631 
1632 		switch (negotiate_connection(fin, url, penv, &pi,
1633 		    &mtime, &wauth, &pauth, &rval, &ischunked,
1634 		    __UNVOLATILE(&auth), &ui)) {
1635 		case C_OK:
1636 			break;
1637 		case C_CLEANUP:
1638 			goto cleanup_fetch_url;
1639 		case C_IMPROPER:
1640 			goto improper;
1641 		default:
1642 			abort();
1643 		}
1644 	}
1645 
1646 	/* Open the output file. */
1647 
1648 	/*
1649 	 * Only trust filenames with special meaning if they came from
1650 	 * the command line
1651 	 */
1652 	if (outfile == savefile) {
1653 		if (strcmp(savefile, "-") == 0) {
1654 			fout = stdout;
1655 		} else if (*savefile == '|') {
1656 			oldpipe = xsignal(SIGPIPE, SIG_IGN);
1657 			fout = popen(savefile + 1, "w");
1658 			if (fout == NULL) {
1659 				warn("Can't execute `%s'", savefile + 1);
1660 				goto cleanup_fetch_url;
1661 			}
1662 			closefunc = pclose;
1663 		}
1664 	}
1665 	if (fout == NULL) {
1666 		if (restart_point && (
1667 		    (pi.rangeend != -1 && pi.rangeend <= restart_point) ||
1668 		    (pi.rangestart == -1 &&
1669 		    filesize != -1 && filesize <= restart_point))) {
1670 			/* already done */
1671 			if (verbose)
1672 				fprintf(ttyout, "already done\n");
1673 			rval = 0;
1674 			goto cleanup_fetch_url;
1675 		}
1676 		if (restart_point && pi.rangestart != -1) {
1677 			if (pi.entitylen != -1)
1678 				filesize = pi.entitylen;
1679 			if (pi.rangestart != restart_point) {
1680 				warnx(
1681 				    "Size of `%s' differs from save file `%s'",
1682 				    url, savefile);
1683 				goto cleanup_fetch_url;
1684 			}
1685 			fout = fopen(savefile, "a");
1686 		} else
1687 			fout = fopen(savefile, "w");
1688 		if (fout == NULL) {
1689 			warn("Can't open `%s'", savefile);
1690 			goto cleanup_fetch_url;
1691 		}
1692 		closefunc = fclose;
1693 	}
1694 
1695 			/* Trap signals */
1696 	oldquit = xsignal(SIGQUIT, psummary);
1697 	oldint = xsignal(SIGINT, aborthttp);
1698 
1699 	assert(rcvbuf_size > 0);
1700 	if ((size_t)rcvbuf_size > bufsize) {
1701 		if (xferbuf)
1702 			(void)free(xferbuf);
1703 		bufsize = rcvbuf_size;
1704 		xferbuf = ftp_malloc(bufsize);
1705 	}
1706 
1707 	bytes = 0;
1708 	hashbytes = mark;
1709 	if (oldalrm != SIG_ERR) {
1710 		(void)xsignal(SIGALRM, oldalrm);
1711 		oldalrm = SIG_ERR;
1712 	}
1713 	progressmeter(-1);
1714 
1715 			/* Finally, suck down the file. */
1716 	do {
1717 		long chunksize;
1718 		short lastchunk;
1719 
1720 		chunksize = 0;
1721 		lastchunk = 0;
1722 					/* read chunk-size */
1723 		if (ischunked) {
1724 			if (fetch_getln(xferbuf, (int)bufsize, fin) == NULL) {
1725 				warnx("Unexpected EOF reading chunk-size");
1726 				goto cleanup_fetch_url;
1727 			}
1728 			errno = 0;
1729 			chunksize = strtol(xferbuf, &ep, 16);
1730 			if (ep == xferbuf) {
1731 				warnx("Invalid chunk-size");
1732 				goto cleanup_fetch_url;
1733 			}
1734 			if (errno == ERANGE || chunksize < 0) {
1735 				errno = ERANGE;
1736 				warn("Chunk-size `%.*s'",
1737 				    (int)(ep-xferbuf), xferbuf);
1738 				goto cleanup_fetch_url;
1739 			}
1740 
1741 				/*
1742 				 * XXX: Work around bug in Apache 1.3.9 and
1743 				 *	1.3.11, which incorrectly put trailing
1744 				 *	space after the chunk-size.
1745 				 */
1746 			while (*ep == ' ')
1747 				ep++;
1748 
1749 					/* skip [ chunk-ext ] */
1750 			if (*ep == ';') {
1751 				while (*ep && *ep != '\r')
1752 					ep++;
1753 			}
1754 
1755 			if (strcmp(ep, "\r\n") != 0) {
1756 				warnx("Unexpected data following chunk-size");
1757 				goto cleanup_fetch_url;
1758 			}
1759 			DPRINTF("%s: got chunk-size of " LLF "\n", __func__,
1760 			    (LLT)chunksize);
1761 			if (chunksize == 0) {
1762 				lastchunk = 1;
1763 				goto chunkdone;
1764 			}
1765 		}
1766 					/* transfer file or chunk */
1767 		for (;;) {
1768 			struct timeval then, now, td;
1769 			volatile off_t bufrem;
1770 
1771 			if (rate_get)
1772 				(void)gettimeofday(&then, NULL);
1773 			bufrem = rate_get ? rate_get : (off_t)bufsize;
1774 			if (ischunked)
1775 				bufrem = MIN(chunksize, bufrem);
1776 			while (bufrem > 0) {
1777 				size_t nr = MIN((off_t)bufsize, bufrem);
1778 				flen = fetch_read(xferbuf, sizeof(char),
1779 				    nr, fin);
1780 				if (flen == 0) {
1781 					if (fetch_error(fin))
1782 						goto chunkerror;
1783 					goto chunkdone;
1784 				}
1785 				bytes += flen;
1786 				bufrem -= flen;
1787 				if (maxwrite(xferbuf, sizeof(char), flen, fout)
1788 				    != flen) {
1789 					warn("Writing `%s'", savefile);
1790 					goto cleanup_fetch_url;
1791 				}
1792 				if (hash && !progress) {
1793 					while (bytes >= hashbytes) {
1794 						(void)putc('#', ttyout);
1795 						hashbytes += mark;
1796 					}
1797 					(void)fflush(ttyout);
1798 				}
1799 				if (ischunked) {
1800 					chunksize -= flen;
1801 					if (chunksize <= 0)
1802 						break;
1803 				}
1804 			}
1805 			if (rate_get) {
1806 				for (;;) {
1807 					(void)gettimeofday(&now, NULL);
1808 					timersub(&now, &then, &td);
1809 					if (td.tv_sec > 0)
1810 						break;
1811 					usleep(1000000 - td.tv_usec);
1812 				}
1813 			}
1814 			if (ischunked && chunksize <= 0)
1815 				break;
1816 		}
1817 					/* read CRLF after chunk*/
1818  chunkdone:
1819 		if (ischunked) {
1820 			if (fetch_getln(xferbuf, (int)bufsize, fin) == NULL) {
1821 				alarmtimer(0);
1822 				warnx("Unexpected EOF reading chunk CRLF");
1823 				goto cleanup_fetch_url;
1824 			}
1825 			if (strcmp(xferbuf, "\r\n") != 0) {
1826 				warnx("Unexpected data following chunk");
1827 				goto cleanup_fetch_url;
1828 			}
1829 			if (lastchunk)
1830 				break;
1831 		}
1832 	} while (ischunked);
1833 
1834 /* XXX: deal with optional trailer & CRLF here? */
1835 chunkerror:
1836 	if (hash && !progress && bytes > 0) {
1837 		if (bytes < mark)
1838 			(void)putc('#', ttyout);
1839 		(void)putc('\n', ttyout);
1840 	}
1841 	if (fetch_error(fin)) {
1842 		warn("Reading file");
1843 		goto cleanup_fetch_url;
1844 	}
1845 	progressmeter(1);
1846 	(void)fflush(fout);
1847 	if (closefunc == fclose && mtime != -1) {
1848 		struct timeval tval[2];
1849 
1850 		(void)gettimeofday(&tval[0], NULL);
1851 		tval[1].tv_sec = mtime;
1852 		tval[1].tv_usec = 0;
1853 		(*closefunc)(fout);
1854 		fout = NULL;
1855 
1856 		if (utimes(savefile, tval) == -1) {
1857 			fprintf(ttyout,
1858 			    "Can't change modification time to %s",
1859 			    rfc2822time(localtime(&mtime)));
1860 		}
1861 	}
1862 	if (bytes > 0)
1863 		ptransfer(0);
1864 	bytes = 0;
1865 
1866 	rval = 0;
1867 	goto cleanup_fetch_url;
1868 
1869  improper:
1870 	warnx("Improper response from `%s:%s'", ui.host, ui.port);
1871 
1872  cleanup_fetch_url:
1873 	if (oldint != SIG_ERR)
1874 		(void)xsignal(SIGINT, oldint);
1875 	if (oldpipe != SIG_ERR)
1876 		(void)xsignal(SIGPIPE, oldpipe);
1877 	if (oldalrm != SIG_ERR)
1878 		(void)xsignal(SIGALRM, oldalrm);
1879 	if (oldquit != SIG_ERR)
1880 		(void)xsignal(SIGQUIT, oldquit);
1881 	if (fin != NULL)
1882 		fetch_close(fin);
1883 	else if (s != -1)
1884 		close(s);
1885 	if (closefunc != NULL && fout != NULL)
1886 		(*closefunc)(fout);
1887 	if (savefile != outfile)
1888 		FREEPTR(savefile);
1889 	freeurlinfo(&ui);
1890 	freeurlinfo(&oui);
1891 	freeauthinfo(&wauth);
1892 	freeauthinfo(&pauth);
1893 	FREEPTR(decodedpath);
1894 	FREEPTR(auth);
1895 	FREEPTR(location);
1896 	FREEPTR(message);
1897 	return (rval);
1898 }
1899 
1900 /*
1901  * Abort a HTTP retrieval
1902  */
1903 static void
1904 aborthttp(int notused __unused)
1905 {
1906 	char msgbuf[100];
1907 	int len;
1908 
1909 	sigint_raised = 1;
1910 	alarmtimer(0);
1911 	if (fromatty) {
1912 		len = snprintf(msgbuf, sizeof(msgbuf),
1913 		    "\n%s: HTTP fetch aborted.\n", getprogname());
1914 		if (len > 0)
1915 			write(fileno(ttyout), msgbuf, len);
1916 	}
1917 	siglongjmp(httpabort, 1);
1918 }
1919 
1920 static void
1921 timeouthttp(int notused __unused)
1922 {
1923 	char msgbuf[100];
1924 	int len;
1925 
1926 	alarmtimer(0);
1927 	if (fromatty) {
1928 		len = snprintf(msgbuf, sizeof(msgbuf),
1929 		    "\n%s: HTTP fetch timeout.\n", getprogname());
1930 		if (len > 0)
1931 			write(fileno(ttyout), msgbuf, len);
1932 	}
1933 	siglongjmp(httpabort, 1);
1934 }
1935 
1936 /*
1937  * Retrieve ftp URL or classic ftp argument using FTP.
1938  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1939  * is still open (e.g, ftp xfer with trailing /)
1940  */
1941 static int
1942 fetch_ftp(const char *url)
1943 {
1944 	char		*cp, *xargv[5], rempath[MAXPATHLEN];
1945 	char		*dir, *file;
1946 	char		 cmdbuf[MAXPATHLEN];
1947 	char		 dirbuf[4];
1948 	int		 dirhasglob, filehasglob, rval, transtype, xargc;
1949 	int		 oanonftp, oautologin;
1950 	struct authinfo	 auth;
1951 	struct urlinfo	 ui;
1952 
1953 	DPRINTF("%s: `%s'\n", __func__, url);
1954 	dir = file = NULL;
1955 	rval = 1;
1956 	transtype = TYPE_I;
1957 
1958 	initurlinfo(&ui);
1959 	initauthinfo(&auth, NULL);
1960 
1961 	if (STRNEQUAL(url, FTP_URL)) {
1962 		if ((parse_url(url, "URL", &ui, &auth, NULL) == -1) ||
1963 		    (auth.user != NULL && *auth.user == '\0') ||
1964 		    EMPTYSTRING(ui.host)) {
1965 			warnx("Invalid URL `%s'", url);
1966 			goto cleanup_fetch_ftp;
1967 		}
1968 		/*
1969 		 * Note: Don't url_decode(path) here.  We need to keep the
1970 		 * distinction between "/" and "%2F" until later.
1971 		 */
1972 
1973 					/* check for trailing ';type=[aid]' */
1974 		if (! EMPTYSTRING(ui.path)
1975 		    && (cp = strrchr(ui.path, ';')) != NULL) {
1976 			if (strcasecmp(cp, ";type=a") == 0)
1977 				transtype = TYPE_A;
1978 			else if (strcasecmp(cp, ";type=i") == 0)
1979 				transtype = TYPE_I;
1980 			else if (strcasecmp(cp, ";type=d") == 0) {
1981 				warnx(
1982 			    "Directory listing via a URL is not supported");
1983 				goto cleanup_fetch_ftp;
1984 			} else {
1985 				warnx("Invalid suffix `%s' in URL `%s'", cp,
1986 				    url);
1987 				goto cleanup_fetch_ftp;
1988 			}
1989 			*cp = 0;
1990 		}
1991 	} else {			/* classic style `[user@]host:[file]' */
1992 		ui.utype = CLASSIC_URL_T;
1993 		ui.host = ftp_strdup(url);
1994 		cp = strchr(ui.host, '@');
1995 		if (cp != NULL) {
1996 			*cp = '\0';
1997 			auth.user = ui.host;
1998 			anonftp = 0;	/* disable anonftp */
1999 			ui.host = ftp_strdup(cp + 1);
2000 		}
2001 		cp = strchr(ui.host, ':');
2002 		if (cp != NULL) {
2003 			*cp = '\0';
2004 			ui.path = ftp_strdup(cp + 1);
2005 		}
2006 	}
2007 	if (EMPTYSTRING(ui.host))
2008 		goto cleanup_fetch_ftp;
2009 
2010 			/* Extract the file and (if present) directory name. */
2011 	dir = ui.path;
2012 	if (! EMPTYSTRING(dir)) {
2013 		/*
2014 		 * If we are dealing with classic `[user@]host:[path]' syntax,
2015 		 * then a path of the form `/file' (resulting from input of the
2016 		 * form `host:/file') means that we should do "CWD /" before
2017 		 * retrieving the file.	 So we set dir="/" and file="file".
2018 		 *
2019 		 * But if we are dealing with URLs like `ftp://host/path' then
2020 		 * a path of the form `/file' (resulting from a URL of the form
2021 		 * `ftp://host//file') means that we should do `CWD ' (with an
2022 		 * empty argument) before retrieving the file.	So we set
2023 		 * dir="" and file="file".
2024 		 *
2025 		 * If the path does not contain / at all, we set dir=NULL.
2026 		 * (We get a path without any slashes if we are dealing with
2027 		 * classic `[user@]host:[file]' or URL `ftp://host/file'.)
2028 		 *
2029 		 * In all other cases, we set dir to a string that does not
2030 		 * include the final '/' that separates the dir part from the
2031 		 * file part of the path.  (This will be the empty string if
2032 		 * and only if we are dealing with a path of the form `/file'
2033 		 * resulting from an URL of the form `ftp://host//file'.)
2034 		 */
2035 		cp = strrchr(dir, '/');
2036 		if (cp == dir && ui.utype == CLASSIC_URL_T) {
2037 			file = cp + 1;
2038 			(void)strlcpy(dirbuf, "/", sizeof(dirbuf));
2039 			dir = dirbuf;
2040 		} else if (cp != NULL) {
2041 			*cp++ = '\0';
2042 			file = cp;
2043 		} else {
2044 			file = dir;
2045 			dir = NULL;
2046 		}
2047 	} else
2048 		dir = NULL;
2049 	if (ui.utype == FTP_URL_T && file != NULL) {
2050 		url_decode(file);
2051 		/* but still don't url_decode(dir) */
2052 	}
2053 	DPRINTF("%s: user `%s' pass `%s' host %s port %s "
2054 	    "path `%s' dir `%s' file `%s'\n", __func__,
2055 	    STRorNULL(auth.user), STRorNULL(auth.pass),
2056 	    STRorNULL(ui.host), STRorNULL(ui.port),
2057 	    STRorNULL(ui.path), STRorNULL(dir), STRorNULL(file));
2058 
2059 	dirhasglob = filehasglob = 0;
2060 	if (doglob &&
2061 	    (ui.utype == CLASSIC_URL_T || ui.utype == FTP_URL_T)) {
2062 		if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
2063 			dirhasglob = 1;
2064 		if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
2065 			filehasglob = 1;
2066 	}
2067 
2068 			/* Set up the connection */
2069 	oanonftp = anonftp;
2070 	if (connected)
2071 		disconnect(0, NULL);
2072 	anonftp = oanonftp;
2073 	(void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
2074 	xargv[0] = cmdbuf;
2075 	xargv[1] = ui.host;
2076 	xargv[2] = NULL;
2077 	xargc = 2;
2078 	if (ui.port) {
2079 		xargv[2] = ui.port;
2080 		xargv[3] = NULL;
2081 		xargc = 3;
2082 	}
2083 	oautologin = autologin;
2084 		/* don't autologin in setpeer(), use ftp_login() below */
2085 	autologin = 0;
2086 	setpeer(xargc, xargv);
2087 	autologin = oautologin;
2088 	if ((connected == 0) ||
2089 	    (connected == 1 && !ftp_login(ui.host, auth.user, auth.pass))) {
2090 		warnx("Can't connect or login to host `%s:%s'",
2091 			ui.host, ui.port ? ui.port : "?");
2092 		goto cleanup_fetch_ftp;
2093 	}
2094 
2095 	switch (transtype) {
2096 	case TYPE_A:
2097 		setascii(1, xargv);
2098 		break;
2099 	case TYPE_I:
2100 		setbinary(1, xargv);
2101 		break;
2102 	default:
2103 		errx(1, "%s: unknown transfer type %d", __func__, transtype);
2104 	}
2105 
2106 		/*
2107 		 * Change directories, if necessary.
2108 		 *
2109 		 * Note: don't use EMPTYSTRING(dir) below, because
2110 		 * dir=="" means something different from dir==NULL.
2111 		 */
2112 	if (dir != NULL && !dirhasglob) {
2113 		char *nextpart;
2114 
2115 		/*
2116 		 * If we are dealing with a classic `[user@]host:[path]'
2117 		 * (urltype is CLASSIC_URL_T) then we have a raw directory
2118 		 * name (not encoded in any way) and we can change
2119 		 * directories in one step.
2120 		 *
2121 		 * If we are dealing with an `ftp://host/path' URL
2122 		 * (urltype is FTP_URL_T), then RFC 3986 says we need to
2123 		 * send a separate CWD command for each unescaped "/"
2124 		 * in the path, and we have to interpret %hex escaping
2125 		 * *after* we find the slashes.	 It's possible to get
2126 		 * empty components here, (from multiple adjacent
2127 		 * slashes in the path) and RFC 3986 says that we should
2128 		 * still do `CWD ' (with a null argument) in such cases.
2129 		 *
2130 		 * Many ftp servers don't support `CWD ', so if there's an
2131 		 * error performing that command, bail out with a descriptive
2132 		 * message.
2133 		 *
2134 		 * Examples:
2135 		 *
2136 		 * host:			dir="", urltype=CLASSIC_URL_T
2137 		 *		logged in (to default directory)
2138 		 * host:file			dir=NULL, urltype=CLASSIC_URL_T
2139 		 *		"RETR file"
2140 		 * host:dir/			dir="dir", urltype=CLASSIC_URL_T
2141 		 *		"CWD dir", logged in
2142 		 * ftp://host/			dir="", urltype=FTP_URL_T
2143 		 *		logged in (to default directory)
2144 		 * ftp://host/dir/		dir="dir", urltype=FTP_URL_T
2145 		 *		"CWD dir", logged in
2146 		 * ftp://host/file		dir=NULL, urltype=FTP_URL_T
2147 		 *		"RETR file"
2148 		 * ftp://host//file		dir="", urltype=FTP_URL_T
2149 		 *		"CWD ", "RETR file"
2150 		 * host:/file			dir="/", urltype=CLASSIC_URL_T
2151 		 *		"CWD /", "RETR file"
2152 		 * ftp://host///file		dir="/", urltype=FTP_URL_T
2153 		 *		"CWD ", "CWD ", "RETR file"
2154 		 * ftp://host/%2F/file		dir="%2F", urltype=FTP_URL_T
2155 		 *		"CWD /", "RETR file"
2156 		 * ftp://host/foo/file		dir="foo", urltype=FTP_URL_T
2157 		 *		"CWD foo", "RETR file"
2158 		 * ftp://host/foo/bar/file	dir="foo/bar"
2159 		 *		"CWD foo", "CWD bar", "RETR file"
2160 		 * ftp://host//foo/bar/file	dir="/foo/bar"
2161 		 *		"CWD ", "CWD foo", "CWD bar", "RETR file"
2162 		 * ftp://host/foo//bar/file	dir="foo//bar"
2163 		 *		"CWD foo", "CWD ", "CWD bar", "RETR file"
2164 		 * ftp://host/%2F/foo/bar/file	dir="%2F/foo/bar"
2165 		 *		"CWD /", "CWD foo", "CWD bar", "RETR file"
2166 		 * ftp://host/%2Ffoo/bar/file	dir="%2Ffoo/bar"
2167 		 *		"CWD /foo", "CWD bar", "RETR file"
2168 		 * ftp://host/%2Ffoo%2Fbar/file dir="%2Ffoo%2Fbar"
2169 		 *		"CWD /foo/bar", "RETR file"
2170 		 * ftp://host/%2Ffoo%2Fbar%2Ffile	dir=NULL
2171 		 *		"RETR /foo/bar/file"
2172 		 *
2173 		 * Note that we don't need `dir' after this point.
2174 		 */
2175 		do {
2176 			if (ui.utype == FTP_URL_T) {
2177 				nextpart = strchr(dir, '/');
2178 				if (nextpart) {
2179 					*nextpart = '\0';
2180 					nextpart++;
2181 				}
2182 				url_decode(dir);
2183 			} else
2184 				nextpart = NULL;
2185 			DPRINTF("%s: dir `%s', nextpart `%s'\n", __func__,
2186 			    STRorNULL(dir), STRorNULL(nextpart));
2187 			if (ui.utype == FTP_URL_T || *dir != '\0') {
2188 				(void)strlcpy(cmdbuf, "cd", sizeof(cmdbuf));
2189 				xargv[0] = cmdbuf;
2190 				xargv[1] = dir;
2191 				xargv[2] = NULL;
2192 				dirchange = 0;
2193 				cd(2, xargv);
2194 				if (! dirchange) {
2195 					if (*dir == '\0' && code == 500)
2196 						fprintf(stderr,
2197 "\n"
2198 "ftp: The `CWD ' command (without a directory), which is required by\n"
2199 "     RFC 3986 to support the empty directory in the URL pathname (`//'),\n"
2200 "     conflicts with the server's conformance to RFC 959.\n"
2201 "     Try the same URL without the `//' in the URL pathname.\n"
2202 "\n");
2203 					goto cleanup_fetch_ftp;
2204 				}
2205 			}
2206 			dir = nextpart;
2207 		} while (dir != NULL);
2208 	}
2209 
2210 	if (EMPTYSTRING(file)) {
2211 		rval = -1;
2212 		goto cleanup_fetch_ftp;
2213 	}
2214 
2215 	if (dirhasglob) {
2216 		(void)strlcpy(rempath, dir,	sizeof(rempath));
2217 		(void)strlcat(rempath, "/",	sizeof(rempath));
2218 		(void)strlcat(rempath, file,	sizeof(rempath));
2219 		file = rempath;
2220 	}
2221 
2222 			/* Fetch the file(s). */
2223 	xargc = 2;
2224 	(void)strlcpy(cmdbuf, "get", sizeof(cmdbuf));
2225 	xargv[0] = cmdbuf;
2226 	xargv[1] = file;
2227 	xargv[2] = NULL;
2228 	if (dirhasglob || filehasglob) {
2229 		int ointeractive;
2230 
2231 		ointeractive = interactive;
2232 		interactive = 0;
2233 		if (restartautofetch)
2234 			(void)strlcpy(cmdbuf, "mreget", sizeof(cmdbuf));
2235 		else
2236 			(void)strlcpy(cmdbuf, "mget", sizeof(cmdbuf));
2237 		xargv[0] = cmdbuf;
2238 		mget(xargc, xargv);
2239 		interactive = ointeractive;
2240 	} else {
2241 		char *destfile = outfile;
2242 		if (destfile == NULL) {
2243 			cp = strrchr(file, '/');	/* find savefile */
2244 			if (cp != NULL)
2245 				destfile = cp + 1;
2246 			else
2247 				destfile = file;
2248 		}
2249 		xargv[2] = (char *)destfile;
2250 		xargv[3] = NULL;
2251 		xargc++;
2252 		if (restartautofetch)
2253 			reget(xargc, xargv);
2254 		else
2255 			get(xargc, xargv);
2256 	}
2257 
2258 	if ((code / 100) == COMPLETE)
2259 		rval = 0;
2260 
2261  cleanup_fetch_ftp:
2262 	freeurlinfo(&ui);
2263 	freeauthinfo(&auth);
2264 	return (rval);
2265 }
2266 
2267 /*
2268  * Retrieve the given file to outfile.
2269  * Supports arguments of the form:
2270  *	"host:path", "ftp://host/path"	if $ftpproxy, call fetch_url() else
2271  *					call fetch_ftp()
2272  *	"http://host/path"		call fetch_url() to use HTTP
2273  *	"file:///path"			call fetch_url() to copy
2274  *	"about:..."			print a message
2275  *
2276  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
2277  * is still open (e.g, ftp xfer with trailing /)
2278  */
2279 static int
2280 go_fetch(const char *url, struct urlinfo *rui)
2281 {
2282 	char *proxyenv;
2283 	const char *p;
2284 
2285 #ifndef NO_ABOUT
2286 	/*
2287 	 * Check for about:*
2288 	 */
2289 	if (STRNEQUAL(url, ABOUT_URL)) {
2290 		url += sizeof(ABOUT_URL) -1;
2291 		if (strcasecmp(url, "ftp") == 0 ||
2292 		    strcasecmp(url, "tnftp") == 0) {
2293 			fputs(
2294 "This version of ftp has been enhanced by Luke Mewburn <lukem@NetBSD.org>\n"
2295 "for the NetBSD project.  Execute `man ftp' for more details.\n", ttyout);
2296 		} else if (strcasecmp(url, "lukem") == 0) {
2297 			fputs(
2298 "Luke Mewburn is the author of most of the enhancements in this ftp client.\n"
2299 "Please email feedback to <lukem@NetBSD.org>.\n", ttyout);
2300 		} else if (strcasecmp(url, "netbsd") == 0) {
2301 			fputs(
2302 "NetBSD is a freely available and redistributable UNIX-like operating system.\n"
2303 "For more information, see http://www.NetBSD.org/\n", ttyout);
2304 		} else if (strcasecmp(url, "version") == 0) {
2305 			fprintf(ttyout, "Version: %s %s%s\n",
2306 			    FTP_PRODUCT, FTP_VERSION,
2307 #ifdef INET6
2308 			    ""
2309 #else
2310 			    " (-IPv6)"
2311 #endif
2312 			);
2313 		} else {
2314 			fprintf(ttyout, "`%s' is an interesting topic.\n", url);
2315 		}
2316 		fputs("\n", ttyout);
2317 		return (0);
2318 	}
2319 #endif
2320 
2321 	/*
2322 	 * Check for file:// and http:// URLs.
2323 	 */
2324 	if (STRNEQUAL(url, HTTP_URL)
2325 #ifdef WITH_SSL
2326 	    || STRNEQUAL(url, HTTPS_URL)
2327 #endif
2328 	    || STRNEQUAL(url, FILE_URL))
2329 		return (fetch_url(url, NULL, NULL, NULL, rui));
2330 
2331 	/*
2332 	 * If it contains "://" but does not begin with ftp://
2333 	 * or something that was already handled, then it's
2334 	 * unsupported.
2335 	 *
2336 	 * If it contains ":" but not "://" then we assume the
2337 	 * part before the colon is a host name, not an URL scheme,
2338 	 * so we don't try to match that here.
2339 	 */
2340 	if ((p = strstr(url, "://")) != NULL && ! STRNEQUAL(url, FTP_URL))
2341 		errx(1, "Unsupported URL scheme `%.*s'", (int)(p - url), url);
2342 
2343 	/*
2344 	 * Refer to previous urlinfo if provided. This makes relative
2345 	 * redirects work.
2346 	 */
2347 	if (use_relative(rui))
2348 	    return fetch_url(url, NULL, NULL, NULL, rui);
2349 
2350 	/*
2351 	 * Try FTP URL-style and host:file arguments next.
2352 	 * If ftpproxy is set with an FTP URL, use fetch_url()
2353 	 * Otherwise, use fetch_ftp().
2354 	 */
2355 	proxyenv = getoptionvalue("ftp_proxy");
2356 	if (!EMPTYSTRING(proxyenv) && STRNEQUAL(url, FTP_URL))
2357 		return (fetch_url(url, NULL, NULL, NULL, rui));
2358 
2359 	return (fetch_ftp(url));
2360 }
2361 
2362 /*
2363  * Retrieve multiple files from the command line,
2364  * calling go_fetch() for each file.
2365  *
2366  * If an ftp path has a trailing "/", the path will be cd-ed into and
2367  * the connection remains open, and the function will return -1
2368  * (to indicate the connection is alive).
2369  * If an error occurs the return value will be the offset+1 in
2370  * argv[] of the file that caused a problem (i.e, argv[x]
2371  * returns x+1)
2372  * Otherwise, 0 is returned if all files retrieved successfully.
2373  */
2374 int
2375 auto_fetch(int argc, char *argv[])
2376 {
2377 	volatile int	argpos, rval;
2378 
2379 	argpos = rval = 0;
2380 
2381 	if (sigsetjmp(toplevel, 1)) {
2382 		if (connected)
2383 			disconnect(0, NULL);
2384 		if (rval > 0)
2385 			rval = argpos + 1;
2386 		return (rval);
2387 	}
2388 	(void)xsignal(SIGINT, intr);
2389 	(void)xsignal(SIGPIPE, lostpeer);
2390 
2391 	/*
2392 	 * Loop through as long as there's files to fetch.
2393 	 */
2394 	for (; (rval == 0) && (argpos < argc); argpos++) {
2395 		if (strchr(argv[argpos], ':') == NULL)
2396 			break;
2397 		redirect_loop = 0;
2398 		if (!anonftp)
2399 			anonftp = 2;	/* Handle "automatic" transfers. */
2400 		rval = go_fetch(argv[argpos], NULL);
2401 		if (outfile != NULL && strcmp(outfile, "-") != 0
2402 		    && outfile[0] != '|') {
2403 			FREEPTR(outfile);
2404 		}
2405 		if (rval > 0)
2406 			rval = argpos + 1;
2407 	}
2408 
2409 	if (connected && rval != -1)
2410 		disconnect(0, NULL);
2411 	return (rval);
2412 }
2413 
2414 
2415 /*
2416  * Upload multiple files from the command line.
2417  *
2418  * If an error occurs the return value will be the offset+1 in
2419  * argv[] of the file that caused a problem (i.e, argv[x]
2420  * returns x+1)
2421  * Otherwise, 0 is returned if all files uploaded successfully.
2422  */
2423 int
2424 auto_put(int argc, char **argv, const char *uploadserver)
2425 {
2426 	char	*uargv[4], *path, *pathsep;
2427 	int	 uargc, rval, argpos;
2428 	size_t	 len;
2429 	char	 cmdbuf[MAX_C_NAME];
2430 
2431 	(void)strlcpy(cmdbuf, "mput", sizeof(cmdbuf));
2432 	uargv[0] = cmdbuf;
2433 	uargv[1] = argv[0];
2434 	uargc = 2;
2435 	uargv[2] = uargv[3] = NULL;
2436 	pathsep = NULL;
2437 	rval = 1;
2438 
2439 	DPRINTF("%s: target `%s'\n", __func__, uploadserver);
2440 
2441 	path = ftp_strdup(uploadserver);
2442 	len = strlen(path);
2443 	if (path[len - 1] != '/' && path[len - 1] != ':') {
2444 			/*
2445 			 * make sure we always pass a directory to auto_fetch
2446 			 */
2447 		if (argc > 1) {		/* more than one file to upload */
2448 			len = strlen(uploadserver) + 2; /* path + "/" + "\0" */
2449 			free(path);
2450 			path = (char *)ftp_malloc(len);
2451 			(void)strlcpy(path, uploadserver, len);
2452 			(void)strlcat(path, "/", len);
2453 		} else {		/* single file to upload */
2454 			(void)strlcpy(cmdbuf, "put", sizeof(cmdbuf));
2455 			uargv[0] = cmdbuf;
2456 			pathsep = strrchr(path, '/');
2457 			if (pathsep == NULL) {
2458 				pathsep = strrchr(path, ':');
2459 				if (pathsep == NULL) {
2460 					warnx("Invalid URL `%s'", path);
2461 					goto cleanup_auto_put;
2462 				}
2463 				pathsep++;
2464 				uargv[2] = ftp_strdup(pathsep);
2465 				pathsep[0] = '/';
2466 			} else
2467 				uargv[2] = ftp_strdup(pathsep + 1);
2468 			pathsep[1] = '\0';
2469 			uargc++;
2470 		}
2471 	}
2472 	DPRINTF("%s: URL `%s' argv[2] `%s'\n", __func__,
2473 	    path, STRorNULL(uargv[2]));
2474 
2475 			/* connect and cwd */
2476 	rval = auto_fetch(1, &path);
2477 	if(rval >= 0)
2478 		goto cleanup_auto_put;
2479 
2480 	rval = 0;
2481 
2482 			/* target filename provided; upload 1 file */
2483 			/* XXX : is this the best way? */
2484 	if (uargc == 3) {
2485 		uargv[1] = argv[0];
2486 		put(uargc, uargv);
2487 		if ((code / 100) != COMPLETE)
2488 			rval = 1;
2489 	} else {	/* otherwise a target dir: upload all files to it */
2490 		for(argpos = 0; argv[argpos] != NULL; argpos++) {
2491 			uargv[1] = argv[argpos];
2492 			mput(uargc, uargv);
2493 			if ((code / 100) != COMPLETE) {
2494 				rval = argpos + 1;
2495 				break;
2496 			}
2497 		}
2498 	}
2499 
2500  cleanup_auto_put:
2501 	free(path);
2502 	FREEPTR(uargv[2]);
2503 	return (rval);
2504 }
2505