xref: /openbsd-src/usr.bin/ftp/fetch.c (revision d2c5a4743fb945f45b034a3a830a96f7e1bc695d)
1 /*	$OpenBSD: fetch.c,v 1.198 2020/10/18 20:35:18 naddy Exp $	*/
2 /*	$NetBSD: fetch.c,v 1.14 1997/08/18 10:20:20 lukem Exp $	*/
3 
4 /*-
5  * Copyright (c) 1997 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Jason Thorpe and Luke Mewburn.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * FTP User Program -- Command line file retrieval
35  */
36 
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <sys/stat.h>
40 
41 #include <netinet/in.h>
42 
43 #include <arpa/ftp.h>
44 #include <arpa/inet.h>
45 
46 #include <ctype.h>
47 #include <err.h>
48 #include <libgen.h>
49 #include <netdb.h>
50 #include <fcntl.h>
51 #include <signal.h>
52 #include <vis.h>
53 #include <stdio.h>
54 #include <stdarg.h>
55 #include <errno.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <unistd.h>
59 #include <util.h>
60 #include <resolv.h>
61 
62 #ifndef NOSSL
63 #include <tls.h>
64 #else /* !NOSSL */
65 struct tls;
66 #endif /* !NOSSL */
67 
68 #include "ftp_var.h"
69 #include "cmds.h"
70 
71 static int	file_get(const char *, const char *);
72 static int	url_get(const char *, const char *, const char *, int);
73 static int	save_chunked(FILE *, struct tls *, int , char *, size_t);
74 static void	aborthttp(int);
75 static char	hextochar(const char *);
76 static char	*urldecode(const char *);
77 static char	*recode_credentials(const char *_userinfo);
78 static char	*ftp_readline(FILE *, size_t *);
79 static void	ftp_close(FILE **, struct tls **, int *);
80 static const char *sockerror(struct tls *);
81 #ifdef SMALL
82 #define 	ftp_printf(fp, ...) fprintf(fp, __VA_ARGS__)
83 #else
84 static int	ftp_printf(FILE *, const char *, ...);
85 #endif /* SMALL */
86 #ifndef NOSSL
87 static int	proxy_connect(int, char *, char *);
88 static int	stdio_tls_write_wrapper(void *, const char *, int);
89 static int	stdio_tls_read_wrapper(void *, char *, int);
90 #endif /* !NOSSL */
91 
92 #define	FTP_URL		"ftp://"	/* ftp URL prefix */
93 #define	HTTP_URL	"http://"	/* http URL prefix */
94 #define	HTTPS_URL	"https://"	/* https URL prefix */
95 #define	FILE_URL	"file:"		/* file URL prefix */
96 #define FTP_PROXY	"ftp_proxy"	/* env var with ftp proxy location */
97 #define HTTP_PROXY	"http_proxy"	/* env var with http proxy location */
98 
99 #define EMPTYSTRING(x)	((x) == NULL || (*(x) == '\0'))
100 
101 static const char at_encoding_warning[] =
102     "Extra `@' characters in usernames and passwords should be encoded as %%40";
103 
104 static jmp_buf	httpabort;
105 
106 static int	redirect_loop;
107 static int	retried;
108 
109 /*
110  * Determine whether the character needs encoding, per RFC1738:
111  *	- No corresponding graphic US-ASCII.
112  *	- Unsafe characters.
113  */
114 static int
115 unsafe_char(const char *c0)
116 {
117 	const char *unsafe_chars = " <>\"#{}|\\^~[]`";
118 	const unsigned char *c = (const unsigned char *)c0;
119 
120 	/*
121 	 * No corresponding graphic US-ASCII.
122 	 * Control characters and octets not used in US-ASCII.
123 	 */
124 	return (iscntrl(*c) || !isascii(*c) ||
125 
126 	    /*
127 	     * Unsafe characters.
128 	     * '%' is also unsafe, if is not followed by two
129 	     * hexadecimal digits.
130 	     */
131 	    strchr(unsafe_chars, *c) != NULL ||
132 	    (*c == '%' && (!isxdigit(*++c) || !isxdigit(*++c))));
133 }
134 
135 /*
136  * Encode given URL, per RFC1738.
137  * Allocate and return string to the caller.
138  */
139 static char *
140 url_encode(const char *path)
141 {
142 	size_t i, length, new_length;
143 	char *epath, *epathp;
144 
145 	length = new_length = strlen(path);
146 
147 	/*
148 	 * First pass:
149 	 * Count unsafe characters, and determine length of the
150 	 * final URL.
151 	 */
152 	for (i = 0; i < length; i++)
153 		if (unsafe_char(path + i))
154 			new_length += 2;
155 
156 	epath = epathp = malloc(new_length + 1);	/* One more for '\0'. */
157 	if (epath == NULL)
158 		err(1, "Can't allocate memory for URL encoding");
159 
160 	/*
161 	 * Second pass:
162 	 * Encode, and copy final URL.
163 	 */
164 	for (i = 0; i < length; i++)
165 		if (unsafe_char(path + i)) {
166 			snprintf(epathp, 4, "%%" "%02x",
167 			    (unsigned char)path[i]);
168 			epathp += 3;
169 		} else
170 			*(epathp++) = path[i];
171 
172 	*epathp = '\0';
173 	return (epath);
174 }
175 
176 /* ARGSUSED */
177 static void
178 tooslow(int signo)
179 {
180 	dprintf(STDERR_FILENO, "%s: connect taking too long\n", __progname);
181 	_exit(2);
182 }
183 
184 /*
185  * Copy a local file (used by the OpenBSD installer).
186  * Returns -1 on failure, 0 on success
187  */
188 static int
189 file_get(const char *path, const char *outfile)
190 {
191 	struct stat	 st;
192 	int		 fd, out = -1, rval = -1, save_errno;
193 	volatile sig_t	 oldintr, oldinti;
194 	const char	*savefile;
195 	char		*buf = NULL, *cp, *pathbuf = NULL;
196 	const size_t	 buflen = 128 * 1024;
197 	off_t		 hashbytes;
198 	ssize_t		 len, wlen;
199 
200 	direction = "received";
201 
202 	fd = open(path, O_RDONLY);
203 	if (fd == -1) {
204 		warn("Can't open file %s", path);
205 		return -1;
206 	}
207 
208 	if (fstat(fd, &st) == -1)
209 		filesize = -1;
210 	else
211 		filesize = st.st_size;
212 
213 	if (outfile != NULL)
214 		savefile = outfile;
215 	else {
216 		if (path[strlen(path) - 1] == '/')	/* Consider no file */
217 			savefile = NULL;		/* after dir invalid. */
218 		else {
219 			pathbuf = strdup(path);
220 			if (pathbuf == NULL)
221 				errx(1, "Can't allocate memory for filename");
222 			savefile = basename(pathbuf);
223 		}
224 	}
225 
226 	if (EMPTYSTRING(savefile)) {
227 		warnx("No filename after directory (use -o): %s", path);
228 		goto cleanup_copy;
229 	}
230 
231 	/* Open the output file.  */
232 	if (!pipeout) {
233 		out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
234 		if (out == -1) {
235 			warn("Can't open %s", savefile);
236 			goto cleanup_copy;
237 		}
238 	} else
239 		out = fileno(stdout);
240 
241 	if ((buf = malloc(buflen)) == NULL)
242 		errx(1, "Can't allocate memory for transfer buffer");
243 
244 	/* Trap signals */
245 	oldintr = NULL;
246 	oldinti = NULL;
247 	if (setjmp(httpabort)) {
248 		if (oldintr)
249 			(void)signal(SIGINT, oldintr);
250 		if (oldinti)
251 			(void)signal(SIGINFO, oldinti);
252 		goto cleanup_copy;
253 	}
254 	oldintr = signal(SIGINT, aborthttp);
255 
256 	bytes = 0;
257 	hashbytes = mark;
258 	progressmeter(-1, path);
259 
260 	/* Finally, suck down the file. */
261 	oldinti = signal(SIGINFO, psummary);
262 	while ((len = read(fd, buf, buflen)) > 0) {
263 		bytes += len;
264 		for (cp = buf; len > 0; len -= wlen, cp += wlen) {
265 			if ((wlen = write(out, cp, len)) == -1) {
266 				warn("Writing %s", savefile);
267 				signal(SIGINT, oldintr);
268 				signal(SIGINFO, oldinti);
269 				goto cleanup_copy;
270 			}
271 		}
272 		if (hash && !progress) {
273 			while (bytes >= hashbytes) {
274 				(void)putc('#', ttyout);
275 				hashbytes += mark;
276 			}
277 			(void)fflush(ttyout);
278 		}
279 	}
280 	save_errno = errno;
281 	signal(SIGINT, oldintr);
282 	signal(SIGINFO, oldinti);
283 	if (hash && !progress && bytes > 0) {
284 		if (bytes < mark)
285 			(void)putc('#', ttyout);
286 		(void)putc('\n', ttyout);
287 		(void)fflush(ttyout);
288 	}
289 	if (len == -1) {
290 		warnc(save_errno, "Reading from file");
291 		goto cleanup_copy;
292 	}
293 	progressmeter(1, NULL);
294 	if (verbose)
295 		ptransfer(0);
296 
297 	rval = 0;
298 
299 cleanup_copy:
300 	free(buf);
301 	free(pathbuf);
302 	if (out >= 0 && out != fileno(stdout))
303 		close(out);
304 	close(fd);
305 
306 	return rval;
307 }
308 
309 /*
310  * Retrieve URL, via the proxy in $proxyvar if necessary.
311  * Returns -1 on failure, 0 on success
312  */
313 static int
314 url_get(const char *origline, const char *proxyenv, const char *outfile, int lastfile)
315 {
316 	char pbuf[NI_MAXSERV], hbuf[NI_MAXHOST], *cp, *portnum, *path, ststr[4];
317 	char *hosttail, *cause = "unknown", *newline, *host, *port, *buf = NULL;
318 	char *epath, *redirurl, *loctail, *h, *p, gerror[200];
319 	int error, isftpurl = 0, isredirect = 0, rval = -1;
320 	int isunavail = 0, retryafter = -1;
321 	struct addrinfo hints, *res0, *res;
322 	const char *savefile;
323 	char *pathbuf = NULL;
324 	char *proxyurl = NULL;
325 	char *credentials = NULL, *proxy_credentials = NULL;
326 	int fd = -1, out = -1;
327 	volatile sig_t oldintr, oldinti;
328 	FILE *fin = NULL;
329 	off_t hashbytes;
330 	const char *errstr;
331 	ssize_t len, wlen;
332 	char *proxyhost = NULL;
333 #ifndef NOSSL
334 	char *sslpath = NULL, *sslhost = NULL;
335 	int ishttpsurl = 0;
336 #endif /* !NOSSL */
337 #ifndef SMALL
338 	char *full_host = NULL;
339 	const char *scheme;
340 	char *locbase;
341 	struct addrinfo *ares = NULL;
342 #endif /* !SMALL */
343 	struct tls *tls = NULL;
344 	int status;
345 	int save_errno;
346 	const size_t buflen = 128 * 1024;
347 	int chunked = 0;
348 
349 	direction = "received";
350 
351 	newline = strdup(origline);
352 	if (newline == NULL)
353 		errx(1, "Can't allocate memory to parse URL");
354 	if (strncasecmp(newline, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) {
355 		host = newline + sizeof(HTTP_URL) - 1;
356 #ifndef SMALL
357 		scheme = HTTP_URL;
358 #endif /* !SMALL */
359 	} else if (strncasecmp(newline, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
360 		host = newline + sizeof(FTP_URL) - 1;
361 		isftpurl = 1;
362 #ifndef SMALL
363 		scheme = FTP_URL;
364 #endif /* !SMALL */
365 	} else if (strncasecmp(newline, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0) {
366 #ifndef NOSSL
367 		host = newline + sizeof(HTTPS_URL) - 1;
368 		ishttpsurl = 1;
369 #else
370 		errx(1, "%s: No HTTPS support", newline);
371 #endif /* !NOSSL */
372 #ifndef SMALL
373 		scheme = HTTPS_URL;
374 #endif /* !SMALL */
375 	} else
376 		errx(1, "%s: URL not permitted", newline);
377 
378 	path = strchr(host, '/');		/* Find path */
379 
380 	/*
381 	 * Look for auth header in host.
382 	 * Basic auth from RFC 2617, valid characters for path are in
383 	 * RFC 3986 section 3.3.
384 	 */
385 	if (!isftpurl) {
386 		p = strchr(host, '@');
387 		if (p != NULL && (path == NULL || p < path)) {
388 			*p++ = '\0';
389 			credentials = recode_credentials(host);
390 
391 			/* Overwrite userinfo */
392 			memmove(host, p, strlen(p) + 1);
393 			path = strchr(host, '/');
394 		}
395 	}
396 
397 	if (EMPTYSTRING(path)) {
398 		if (outfile) {				/* No slash, but */
399 			path = strchr(host,'\0');	/* we have outfile. */
400 			goto noslash;
401 		}
402 		if (isftpurl)
403 			goto noftpautologin;
404 		warnx("No `/' after host (use -o): %s", origline);
405 		goto cleanup_url_get;
406 	}
407 	*path++ = '\0';
408 	if (EMPTYSTRING(path) && !outfile) {
409 		if (isftpurl)
410 			goto noftpautologin;
411 		warnx("No filename after host (use -o): %s", origline);
412 		goto cleanup_url_get;
413 	}
414 
415 noslash:
416 	if (outfile)
417 		savefile = outfile;
418 	else {
419 		if (path[strlen(path) - 1] == '/')	/* Consider no file */
420 			savefile = NULL;		/* after dir invalid. */
421 		else {
422 			pathbuf = strdup(path);
423 			if (pathbuf == NULL)
424 				errx(1, "Can't allocate memory for filename");
425 			savefile = basename(pathbuf);
426 		}
427 	}
428 
429 	if (EMPTYSTRING(savefile)) {
430 		if (isftpurl)
431 			goto noftpautologin;
432 		warnx("No filename after directory (use -o): %s", origline);
433 		goto cleanup_url_get;
434 	}
435 
436 #ifndef SMALL
437 	if (resume && pipeout) {
438 		warnx("can't append to stdout");
439 		goto cleanup_url_get;
440 	}
441 #endif /* !SMALL */
442 
443 	if (proxyenv != NULL) {		/* use proxy */
444 #ifndef NOSSL
445 		if (ishttpsurl) {
446 			sslpath = strdup(path);
447 			sslhost = strdup(host);
448 			if (! sslpath || ! sslhost)
449 				errx(1, "Can't allocate memory for https path/host.");
450 		}
451 #endif /* !NOSSL */
452 		proxyhost = strdup(host);
453 		if (proxyhost == NULL)
454 			errx(1, "Can't allocate memory for proxy host.");
455 		proxyurl = strdup(proxyenv);
456 		if (proxyurl == NULL)
457 			errx(1, "Can't allocate memory for proxy URL.");
458 		if (strncasecmp(proxyurl, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
459 			host = proxyurl + sizeof(HTTP_URL) - 1;
460 		else if (strncasecmp(proxyurl, FTP_URL, sizeof(FTP_URL) - 1) == 0)
461 			host = proxyurl + sizeof(FTP_URL) - 1;
462 		else {
463 			warnx("Malformed proxy URL: %s", proxyenv);
464 			goto cleanup_url_get;
465 		}
466 		if (EMPTYSTRING(host)) {
467 			warnx("Malformed proxy URL: %s", proxyenv);
468 			goto cleanup_url_get;
469 		}
470 		if (*--path == '\0')
471 			*path = '/';		/* add / back to real path */
472 		path = strchr(host, '/');	/* remove trailing / on host */
473 		if (!EMPTYSTRING(path))
474 			*path++ = '\0';		/* i guess this ++ is useless */
475 
476 		path = strchr(host, '@');	/* look for credentials in proxy */
477 		if (!EMPTYSTRING(path)) {
478 			*path = '\0';
479 			if (strchr(host, ':') == NULL) {
480 				warnx("Malformed proxy URL: %s", proxyenv);
481 				goto cleanup_url_get;
482 			}
483 			proxy_credentials = recode_credentials(host);
484 			*path = '@'; /* restore @ in proxyurl */
485 
486 			/*
487 			 * This removes the password from proxyurl,
488 			 * filling with stars
489 			 */
490 			for (host = 1 + strchr(proxyurl + 5, ':');  *host != '@';
491 			    host++)
492 				*host = '*';
493 
494 			host = path + 1;
495 		}
496 
497 		path = newline;
498 	}
499 
500 	if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
501 	    (hosttail[1] == '\0' || hosttail[1] == ':')) {
502 		host++;
503 		*hosttail++ = '\0';
504 #ifndef SMALL
505 		if (asprintf(&full_host, "[%s]", host) == -1)
506 			errx(1, "Cannot allocate memory for hostname");
507 #endif /* !SMALL */
508 	} else
509 		hosttail = host;
510 
511 	portnum = strrchr(hosttail, ':');		/* find portnum */
512 	if (portnum != NULL)
513 		*portnum++ = '\0';
514 #ifndef NOSSL
515 	port = portnum ? portnum : (ishttpsurl ? httpsport : httpport);
516 #else /* !NOSSL */
517 	port = portnum ? portnum : httpport;
518 #endif /* !NOSSL */
519 
520 #ifndef SMALL
521 	if (full_host == NULL)
522 		if ((full_host = strdup(host)) == NULL)
523 			errx(1, "Cannot allocate memory for hostname");
524 	if (debug)
525 		fprintf(ttyout, "host %s, port %s, path %s, "
526 		    "save as %s, auth %s.\n", host, port, path,
527 		    savefile, credentials ? credentials : "none");
528 #endif /* !SMALL */
529 
530 	memset(&hints, 0, sizeof(hints));
531 	hints.ai_family = family;
532 	hints.ai_socktype = SOCK_STREAM;
533 	error = getaddrinfo(host, port, &hints, &res0);
534 	/*
535 	 * If the services file is corrupt/missing, fall back
536 	 * on our hard-coded defines.
537 	 */
538 	if (error == EAI_SERVICE && port == httpport) {
539 		snprintf(pbuf, sizeof(pbuf), "%d", HTTP_PORT);
540 		error = getaddrinfo(host, pbuf, &hints, &res0);
541 #ifndef NOSSL
542 	} else if (error == EAI_SERVICE && port == httpsport) {
543 		snprintf(pbuf, sizeof(pbuf), "%d", HTTPS_PORT);
544 		error = getaddrinfo(host, pbuf, &hints, &res0);
545 #endif /* !NOSSL */
546 	}
547 	if (error) {
548 		warnx("%s: %s", host, gai_strerror(error));
549 		goto cleanup_url_get;
550 	}
551 
552 #ifndef SMALL
553 	if (srcaddr) {
554 		hints.ai_flags |= AI_NUMERICHOST;
555 		error = getaddrinfo(srcaddr, NULL, &hints, &ares);
556 		if (error) {
557 			warnx("%s: %s", srcaddr, gai_strerror(error));
558 			goto cleanup_url_get;
559 		}
560 	}
561 #endif /* !SMALL */
562 
563 	/* ensure consistent order of the output */
564 	if (verbose)
565 		setvbuf(ttyout, NULL, _IOLBF, 0);
566 
567 	fd = -1;
568 	for (res = res0; res; res = res->ai_next) {
569 		if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
570 		    sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0)
571 			strlcpy(hbuf, "(unknown)", sizeof(hbuf));
572 		if (verbose)
573 			fprintf(ttyout, "Trying %s...\n", hbuf);
574 
575 		fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
576 		if (fd == -1) {
577 			cause = "socket";
578 			continue;
579 		}
580 
581 #ifndef SMALL
582 		if (srcaddr) {
583 			if (ares->ai_family != res->ai_family) {
584 				close(fd);
585 				fd = -1;
586 				errno = EINVAL;
587 				cause = "bind";
588 				continue;
589 			}
590 			if (bind(fd, ares->ai_addr, ares->ai_addrlen) == -1) {
591 				save_errno = errno;
592 				close(fd);
593 				errno = save_errno;
594 				fd = -1;
595 				cause = "bind";
596 				continue;
597 			}
598 		}
599 #endif /* !SMALL */
600 
601 		if (connect_timeout) {
602 			(void)signal(SIGALRM, tooslow);
603 			alarmtimer(connect_timeout);
604 		}
605 
606 		for (error = connect(fd, res->ai_addr, res->ai_addrlen);
607 		    error != 0 && errno == EINTR; error = connect_wait(fd))
608 			continue;
609 		if (error != 0) {
610 			save_errno = errno;
611 			close(fd);
612 			errno = save_errno;
613 			fd = -1;
614 			cause = "connect";
615 			continue;
616 		}
617 
618 		/* get port in numeric */
619 		if (getnameinfo(res->ai_addr, res->ai_addrlen, NULL, 0,
620 		    pbuf, sizeof(pbuf), NI_NUMERICSERV) == 0)
621 			port = pbuf;
622 		else
623 			port = NULL;
624 
625 #ifndef NOSSL
626 		if (proxyenv && sslhost)
627 			proxy_connect(fd, sslhost, proxy_credentials);
628 #endif /* !NOSSL */
629 		break;
630 	}
631 	freeaddrinfo(res0);
632 #ifndef SMALL
633 	if (srcaddr)
634 		freeaddrinfo(ares);
635 #endif /* !SMALL */
636 	if (fd < 0) {
637 		warn("%s", cause);
638 		goto cleanup_url_get;
639 	}
640 
641 #ifndef NOSSL
642 	if (ishttpsurl) {
643 		ssize_t ret;
644 		if (proxyenv && sslpath) {
645 			ishttpsurl = 0;
646 			proxyurl = NULL;
647 			path = sslpath;
648 		}
649 		if (sslhost == NULL) {
650 			sslhost = strdup(host);
651 			if (sslhost == NULL)
652 				errx(1, "Can't allocate memory for https host.");
653 		}
654 		if ((tls = tls_client()) == NULL) {
655 			fprintf(ttyout, "failed to create SSL client\n");
656 			goto cleanup_url_get;
657 		}
658 		if (tls_configure(tls, tls_config) != 0) {
659 			fprintf(ttyout, "TLS configuration failure: %s\n",
660 			    tls_error(tls));
661 			goto cleanup_url_get;
662 		}
663 		if (tls_connect_socket(tls, fd, sslhost) != 0) {
664 			fprintf(ttyout, "TLS connect failure: %s\n", tls_error(tls));
665 			goto cleanup_url_get;
666 		}
667 		do {
668 			ret = tls_handshake(tls);
669 		} while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
670 		if (ret != 0) {
671 			fprintf(ttyout, "TLS handshake failure: %s\n", tls_error(tls));
672 			goto cleanup_url_get;
673 		}
674 		fin = funopen(tls, stdio_tls_read_wrapper,
675 		    stdio_tls_write_wrapper, NULL, NULL);
676 	} else {
677 		fin = fdopen(fd, "r+");
678 		fd = -1;
679 	}
680 #else /* !NOSSL */
681 	fin = fdopen(fd, "r+");
682 	fd = -1;
683 #endif /* !NOSSL */
684 
685 #ifdef SMALL
686 	if (lastfile) {
687 		if (pipeout) {
688 			if (pledge("stdio rpath inet dns tty",  NULL) == -1)
689 				err(1, "pledge");
690 		} else {
691 			if (pledge("stdio rpath wpath cpath inet dns tty", NULL) == -1)
692 				err(1, "pledge");
693 		}
694 	}
695 #endif
696 
697 	if (connect_timeout) {
698 		signal(SIGALRM, SIG_DFL);
699 		alarmtimer(0);
700 	}
701 
702 	/*
703 	 * Construct and send the request. Proxy requests don't want leading /.
704 	 */
705 #ifndef NOSSL
706 	cookie_get(host, path, ishttpsurl, &buf);
707 #endif /* !NOSSL */
708 
709 	epath = url_encode(path);
710 	if (proxyurl) {
711 		if (verbose) {
712 			fprintf(ttyout, "Requesting %s (via %s)\n",
713 			    origline, proxyurl);
714 		}
715 		/*
716 		 * Host: directive must use the destination host address for
717 		 * the original URI (path).
718 		 */
719 		ftp_printf(fin, "GET %s HTTP/1.1\r\n"
720 		    "Connection: close\r\n"
721 		    "Host: %s\r\n%s%s\r\n",
722 		    epath, proxyhost, buf ? buf : "", httpuseragent);
723 		if (credentials)
724 			ftp_printf(fin, "Authorization: Basic %s\r\n",
725 			    credentials);
726 		if (proxy_credentials)
727 			ftp_printf(fin, "Proxy-Authorization: Basic %s\r\n",
728 			    proxy_credentials);
729 		ftp_printf(fin, "\r\n");
730 	} else {
731 		if (verbose)
732 			fprintf(ttyout, "Requesting %s\n", origline);
733 #ifndef SMALL
734 		if (resume) {
735 			struct stat stbuf;
736 
737 			if (stat(savefile, &stbuf) == 0)
738 				restart_point = stbuf.st_size;
739 			else
740 				restart_point = 0;
741 		}
742 #endif	/* SMALL */
743 		ftp_printf(fin,
744 		    "GET /%s HTTP/1.1\r\n"
745 		    "Connection: close\r\n"
746 		    "Host: ", epath);
747 		if (proxyhost) {
748 			ftp_printf(fin, "%s", proxyhost);
749 			port = NULL;
750 		} else if (strchr(host, ':')) {
751 			/*
752 			 * strip off scoped address portion, since it's
753 			 * local to node
754 			 */
755 			h = strdup(host);
756 			if (h == NULL)
757 				errx(1, "Can't allocate memory.");
758 			if ((p = strchr(h, '%')) != NULL)
759 				*p = '\0';
760 			ftp_printf(fin, "[%s]", h);
761 			free(h);
762 		} else
763 			ftp_printf(fin, "%s", host);
764 
765 		/*
766 		 * Send port number only if it's specified and does not equal
767 		 * 80. Some broken HTTP servers get confused if you explicitly
768 		 * send them the port number.
769 		 */
770 #ifndef NOSSL
771 		if (port && strcmp(port, (ishttpsurl ? "443" : "80")) != 0)
772 			ftp_printf(fin, ":%s", port);
773 		if (restart_point)
774 			ftp_printf(fin, "\r\nRange: bytes=%lld-",
775 				(long long)restart_point);
776 #else /* !NOSSL */
777 		if (port && strcmp(port, "80") != 0)
778 			ftp_printf(fin, ":%s", port);
779 #endif /* !NOSSL */
780 		ftp_printf(fin, "\r\n%s%s\r\n",
781 		    buf ? buf : "", httpuseragent);
782 		if (credentials)
783 			ftp_printf(fin, "Authorization: Basic %s\r\n",
784 			    credentials);
785 		ftp_printf(fin, "\r\n");
786 	}
787 	free(epath);
788 
789 #ifndef NOSSL
790 	free(buf);
791 #endif /* !NOSSL */
792 	buf = NULL;
793 
794 	if (fflush(fin) == EOF) {
795 		warnx("Writing HTTP request: %s", sockerror(tls));
796 		goto cleanup_url_get;
797 	}
798 	if ((buf = ftp_readline(fin, &len)) == NULL) {
799 		warnx("Receiving HTTP reply: %s", sockerror(tls));
800 		goto cleanup_url_get;
801 	}
802 
803 	while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
804 		buf[--len] = '\0';
805 #ifndef SMALL
806 	if (debug)
807 		fprintf(ttyout, "received '%s'\n", buf);
808 #endif /* !SMALL */
809 
810 	cp = strchr(buf, ' ');
811 	if (cp == NULL)
812 		goto improper;
813 	else
814 		cp++;
815 
816 	strlcpy(ststr, cp, sizeof(ststr));
817 	status = strtonum(ststr, 200, 503, &errstr);
818 	if (errstr) {
819 		strnvis(gerror, cp, sizeof gerror, VIS_SAFE);
820 		warnx("Error retrieving %s: %s", origline, gerror);
821 		goto cleanup_url_get;
822 	}
823 
824 	switch (status) {
825 	case 200:	/* OK */
826 #ifndef SMALL
827 		/*
828 		 * When we request a partial file, and we receive an HTTP 200
829 		 * it is a good indication that the server doesn't support
830 		 * range requests, and is about to send us the entire file.
831 		 * If the restart_point == 0, then we are not actually
832 		 * requesting a partial file, and an HTTP 200 is appropriate.
833 		 */
834 		if (resume && restart_point != 0) {
835 			warnx("Server does not support resume.");
836 			restart_point = resume = 0;
837 		}
838 		/* FALLTHROUGH */
839 	case 206:	/* Partial Content */
840 #endif /* !SMALL */
841 		break;
842 	case 301:	/* Moved Permanently */
843 	case 302:	/* Found */
844 	case 303:	/* See Other */
845 	case 307:	/* Temporary Redirect */
846 		isredirect++;
847 		if (redirect_loop++ > 10) {
848 			warnx("Too many redirections requested");
849 			goto cleanup_url_get;
850 		}
851 		break;
852 #ifndef SMALL
853 	case 416:	/* Requested Range Not Satisfiable */
854 		warnx("File is already fully retrieved.");
855 		goto cleanup_url_get;
856 #endif /* !SMALL */
857 	case 503:
858 		isunavail = 1;
859 		break;
860 	default:
861 		strnvis(gerror, cp, sizeof gerror, VIS_SAFE);
862 		warnx("Error retrieving %s: %s", origline, gerror);
863 		goto cleanup_url_get;
864 	}
865 
866 	/*
867 	 * Read the rest of the header.
868 	 */
869 	free(buf);
870 	filesize = -1;
871 
872 	for (;;) {
873 		if ((buf = ftp_readline(fin, &len)) == NULL) {
874 			warnx("Receiving HTTP reply: %s", sockerror(tls));
875 			goto cleanup_url_get;
876 		}
877 
878 		while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
879 			buf[--len] = '\0';
880 		if (len == 0)
881 			break;
882 #ifndef SMALL
883 		if (debug)
884 			fprintf(ttyout, "received '%s'\n", buf);
885 #endif /* !SMALL */
886 
887 		/* Look for some headers */
888 		cp = buf;
889 #define CONTENTLEN "Content-Length: "
890 		if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) {
891 			size_t s;
892 			cp += sizeof(CONTENTLEN) - 1;
893 			if ((s = strcspn(cp, " \t")))
894 				*(cp+s) = 0;
895 			filesize = strtonum(cp, 0, LLONG_MAX, &errstr);
896 			if (errstr != NULL)
897 				goto improper;
898 #ifndef SMALL
899 			if (restart_point)
900 				filesize += restart_point;
901 #endif /* !SMALL */
902 #define LOCATION "Location: "
903 		} else if (isredirect &&
904 		    strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) {
905 			cp += sizeof(LOCATION) - 1;
906 			/*
907 			 * If there is a colon before the first slash, this URI
908 			 * is not relative. RFC 3986 4.2
909 			 */
910 			if (cp[strcspn(cp, ":/")] != ':') {
911 #ifdef SMALL
912 				errx(1, "Relative redirect not supported");
913 #else /* SMALL */
914 				/* XXX doesn't handle protocol-relative URIs */
915 				if (*cp == '/') {
916 					locbase = NULL;
917 					cp++;
918 				} else {
919 					locbase = strdup(path);
920 					if (locbase == NULL)
921 						errx(1, "Can't allocate memory"
922 						    " for location base");
923 					loctail = strchr(locbase, '#');
924 					if (loctail != NULL)
925 						*loctail = '\0';
926 					loctail = strchr(locbase, '?');
927 					if (loctail != NULL)
928 						*loctail = '\0';
929 					loctail = strrchr(locbase, '/');
930 					if (loctail == NULL) {
931 						free(locbase);
932 						locbase = NULL;
933 					} else
934 						loctail[1] = '\0';
935 				}
936 				/* Contruct URL from relative redirect */
937 				if (asprintf(&redirurl, "%s%s%s%s/%s%s",
938 				    scheme, full_host,
939 				    portnum ? ":" : "",
940 				    portnum ? portnum : "",
941 				    locbase ? locbase : "",
942 				    cp) == -1)
943 					errx(1, "Cannot build "
944 					    "redirect URL");
945 				free(locbase);
946 #endif /* SMALL */
947 			} else if ((redirurl = strdup(cp)) == NULL)
948 				errx(1, "Cannot allocate memory for URL");
949 			loctail = strchr(redirurl, '#');
950 			if (loctail != NULL)
951 				*loctail = '\0';
952 			if (verbose)
953 				fprintf(ttyout, "Redirected to %s\n", redirurl);
954 			ftp_close(&fin, &tls, &fd);
955 			rval = url_get(redirurl, proxyenv, savefile, lastfile);
956 			free(redirurl);
957 			goto cleanup_url_get;
958 #define RETRYAFTER "Retry-After: "
959 		} else if (isunavail &&
960 		    strncasecmp(cp, RETRYAFTER, sizeof(RETRYAFTER) - 1) == 0) {
961 			size_t s;
962 			cp += sizeof(RETRYAFTER) - 1;
963 			if ((s = strcspn(cp, " \t")))
964 				cp[s] = '\0';
965 			retryafter = strtonum(cp, 0, 0, &errstr);
966 			if (errstr != NULL)
967 				retryafter = -1;
968 #define TRANSFER_ENCODING "Transfer-Encoding: "
969 		} else if (strncasecmp(cp, TRANSFER_ENCODING,
970 			    sizeof(TRANSFER_ENCODING) - 1) == 0) {
971 			cp += sizeof(TRANSFER_ENCODING) - 1;
972 			cp[strcspn(cp, " \t")] = '\0';
973 			if (strcasecmp(cp, "chunked") == 0)
974 				chunked = 1;
975 		}
976 		free(buf);
977 	}
978 
979 	/* Content-Length should be ignored for Transfer-Encoding: chunked */
980 	if (chunked)
981 		filesize = -1;
982 
983 	if (isunavail) {
984 		if (retried || retryafter != 0)
985 			warnx("Error retrieving %s: 503 Service Unavailable",
986 			    origline);
987 		else {
988 			if (verbose)
989 				fprintf(ttyout, "Retrying %s\n", origline);
990 			retried = 1;
991 			ftp_close(&fin, &tls, &fd);
992 			rval = url_get(origline, proxyenv, savefile, lastfile);
993 		}
994 		goto cleanup_url_get;
995 	}
996 
997 	/* Open the output file.  */
998 	if (!pipeout) {
999 #ifndef SMALL
1000 		if (resume)
1001 			out = open(savefile, O_CREAT | O_WRONLY | O_APPEND,
1002 				0666);
1003 		else
1004 #endif /* !SMALL */
1005 			out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC,
1006 				0666);
1007 		if (out == -1) {
1008 			warn("Can't open %s", savefile);
1009 			goto cleanup_url_get;
1010 		}
1011 	} else {
1012 		out = fileno(stdout);
1013 #ifdef SMALL
1014 		if (lastfile) {
1015 			if (pledge("stdio tty", NULL) == -1)
1016 				err(1, "pledge");
1017 		}
1018 #endif
1019 	}
1020 
1021 	free(buf);
1022 	if ((buf = malloc(buflen)) == NULL)
1023 		errx(1, "Can't allocate memory for transfer buffer");
1024 
1025 	/* Trap signals */
1026 	oldintr = NULL;
1027 	oldinti = NULL;
1028 	if (setjmp(httpabort)) {
1029 		if (oldintr)
1030 			(void)signal(SIGINT, oldintr);
1031 		if (oldinti)
1032 			(void)signal(SIGINFO, oldinti);
1033 		goto cleanup_url_get;
1034 	}
1035 	oldintr = signal(SIGINT, aborthttp);
1036 
1037 	bytes = 0;
1038 	hashbytes = mark;
1039 	progressmeter(-1, path);
1040 
1041 	/* Finally, suck down the file. */
1042 	oldinti = signal(SIGINFO, psummary);
1043 	if (chunked) {
1044 		error = save_chunked(fin, tls, out, buf, buflen);
1045 		signal(SIGINT, oldintr);
1046 		signal(SIGINFO, oldinti);
1047 		if (error == -1)
1048 			goto cleanup_url_get;
1049 	} else {
1050 		while ((len = fread(buf, 1, buflen, fin)) > 0) {
1051 			bytes += len;
1052 			for (cp = buf; len > 0; len -= wlen, cp += wlen) {
1053 				if ((wlen = write(out, cp, len)) == -1) {
1054 					warn("Writing %s", savefile);
1055 					signal(SIGINT, oldintr);
1056 					signal(SIGINFO, oldinti);
1057 					goto cleanup_url_get;
1058 				}
1059 			}
1060 			if (hash && !progress) {
1061 				while (bytes >= hashbytes) {
1062 					(void)putc('#', ttyout);
1063 					hashbytes += mark;
1064 				}
1065 				(void)fflush(ttyout);
1066 			}
1067 		}
1068 		save_errno = errno;
1069 		signal(SIGINT, oldintr);
1070 		signal(SIGINFO, oldinti);
1071 		if (hash && !progress && bytes > 0) {
1072 			if (bytes < mark)
1073 				(void)putc('#', ttyout);
1074 			(void)putc('\n', ttyout);
1075 			(void)fflush(ttyout);
1076 		}
1077 		if (len == 0 && ferror(fin)) {
1078 			errno = save_errno;
1079 			warnx("Reading from socket: %s", sockerror(tls));
1080 			goto cleanup_url_get;
1081 		}
1082 	}
1083 	progressmeter(1, NULL);
1084 	if (
1085 #ifndef SMALL
1086 		!resume &&
1087 #endif /* !SMALL */
1088 		filesize != -1 && len == 0 && bytes != filesize) {
1089 		if (verbose)
1090 			fputs("Read short file.\n", ttyout);
1091 		goto cleanup_url_get;
1092 	}
1093 
1094 	if (verbose)
1095 		ptransfer(0);
1096 
1097 	rval = 0;
1098 	goto cleanup_url_get;
1099 
1100 noftpautologin:
1101 	warnx(
1102 	    "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
1103 	goto cleanup_url_get;
1104 
1105 improper:
1106 	warnx("Improper response from %s", host);
1107 
1108 cleanup_url_get:
1109 #ifndef SMALL
1110 	free(full_host);
1111 #endif /* !SMALL */
1112 #ifndef NOSSL
1113 	free(sslhost);
1114 #endif /* !NOSSL */
1115 	ftp_close(&fin, &tls, &fd);
1116 	if (out >= 0 && out != fileno(stdout))
1117 		close(out);
1118 	free(buf);
1119 	free(pathbuf);
1120 	free(proxyhost);
1121 	free(proxyurl);
1122 	free(newline);
1123 	free(credentials);
1124 	free(proxy_credentials);
1125 	return (rval);
1126 }
1127 
1128 static int
1129 save_chunked(FILE *fin, struct tls *tls, int out, char *buf, size_t buflen)
1130 {
1131 
1132 	char			*header, *end, *cp;
1133 	unsigned long		chunksize;
1134 	size_t			hlen, rlen, wlen;
1135 	ssize_t			written;
1136 	char			cr, lf;
1137 
1138 	for (;;) {
1139 		header = ftp_readline(fin, &hlen);
1140 		if (header == NULL)
1141 			break;
1142 		/* strip CRLF and any optional chunk extension */
1143 		header[strcspn(header, ";\r\n")] = '\0';
1144 		errno = 0;
1145 		chunksize = strtoul(header, &end, 16);
1146 		if (errno || header[0] == '\0' || *end != '\0' ||
1147 		    chunksize > INT_MAX) {
1148 			warnx("Invalid chunk size '%s'", header);
1149 			free(header);
1150 			return -1;
1151 		}
1152 		free(header);
1153 
1154 		if (chunksize == 0) {
1155 			/* We're done.  Ignore optional trailer. */
1156 			return 0;
1157 		}
1158 
1159 		for (written = 0; chunksize != 0; chunksize -= rlen) {
1160 			rlen = (chunksize < buflen) ? chunksize : buflen;
1161 			rlen = fread(buf, 1, rlen, fin);
1162 			if (rlen == 0)
1163 				break;
1164 			bytes += rlen;
1165 			for (cp = buf, wlen = rlen; wlen > 0;
1166 			    wlen -= written, cp += written) {
1167 				if ((written = write(out, cp, wlen)) == -1) {
1168 					warn("Writing output file");
1169 					return -1;
1170 				}
1171 			}
1172 		}
1173 
1174 		if (rlen == 0 ||
1175 		    fread(&cr, 1, 1, fin) != 1 ||
1176 		    fread(&lf, 1, 1, fin) != 1)
1177 			break;
1178 
1179 		if (cr != '\r' || lf != '\n') {
1180 			warnx("Invalid chunked encoding");
1181 			return -1;
1182 		}
1183 	}
1184 
1185 	if (ferror(fin))
1186 		warnx("Error while reading from socket: %s", sockerror(tls));
1187 	else
1188 		warnx("Invalid chunked encoding: short read");
1189 
1190 	return -1;
1191 }
1192 
1193 /*
1194  * Abort a http retrieval
1195  */
1196 /* ARGSUSED */
1197 static void
1198 aborthttp(int signo)
1199 {
1200 	const char errmsg[] = "\nfetch aborted.\n";
1201 
1202 	alarmtimer(0);
1203 	write(fileno(ttyout), errmsg, sizeof(errmsg) - 1);
1204 	longjmp(httpabort, 1);
1205 }
1206 
1207 /*
1208  * Retrieve multiple files from the command line, transferring
1209  * files of the form "host:path", "ftp://host/path" using the
1210  * ftp protocol, and files of the form "http://host/path" using
1211  * the http protocol.
1212  * If path has a trailing "/", then return (-1);
1213  * the path will be cd-ed into and the connection remains open,
1214  * and the function will return -1 (to indicate the connection
1215  * is alive).
1216  * If an error occurs the return value will be the offset+1 in
1217  * argv[] of the file that caused a problem (i.e, argv[x]
1218  * returns x+1)
1219  * Otherwise, 0 is returned if all files retrieved successfully.
1220  */
1221 int
1222 auto_fetch(int argc, char *argv[], char *outfile)
1223 {
1224 	char *xargv[5];
1225 	char *cp, *url, *host, *dir, *file, *portnum;
1226 	char *username, *pass, *pathstart;
1227 	char *ftpproxy, *httpproxy;
1228 	int rval, xargc, lastfile;
1229 	volatile int argpos;
1230 	int dirhasglob, filehasglob, oautologin;
1231 	char rempath[PATH_MAX];
1232 
1233 	argpos = 0;
1234 
1235 	if (setjmp(toplevel)) {
1236 		if (connected)
1237 			disconnect(0, NULL);
1238 		return (argpos + 1);
1239 	}
1240 	(void)signal(SIGINT, (sig_t)intr);
1241 	(void)signal(SIGPIPE, (sig_t)lostpeer);
1242 
1243 	if ((ftpproxy = getenv(FTP_PROXY)) != NULL && *ftpproxy == '\0')
1244 		ftpproxy = NULL;
1245 	if ((httpproxy = getenv(HTTP_PROXY)) != NULL && *httpproxy == '\0')
1246 		httpproxy = NULL;
1247 
1248 	/*
1249 	 * Loop through as long as there's files to fetch.
1250 	 */
1251 	username = pass = NULL;
1252 	for (rval = 0; (rval == 0) && (argpos < argc); free(url), argpos++) {
1253 		if (strchr(argv[argpos], ':') == NULL)
1254 			break;
1255 
1256 		free(username);
1257 		free(pass);
1258 		host = dir = file = portnum = username = pass = NULL;
1259 
1260 		lastfile = (argv[argpos+1] == NULL);
1261 
1262 		/*
1263 		 * We muck with the string, so we make a copy.
1264 		 */
1265 		url = strdup(argv[argpos]);
1266 		if (url == NULL)
1267 			errx(1, "Can't allocate memory for auto-fetch.");
1268 
1269 		if (strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
1270 			if (file_get(url + sizeof(FILE_URL) - 1, outfile) == -1)
1271 				rval = argpos + 1;
1272 			continue;
1273 		}
1274 
1275 		/*
1276 		 * Try HTTP URL-style arguments next.
1277 		 */
1278 		if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1279 		    strncasecmp(url, HTTPS_URL, sizeof(HTTPS_URL) -1) == 0) {
1280 			redirect_loop = 0;
1281 			retried = 0;
1282 			if (url_get(url, httpproxy, outfile, lastfile) == -1)
1283 				rval = argpos + 1;
1284 			continue;
1285 		}
1286 
1287 		/*
1288 		 * Try FTP URL-style arguments next. If ftpproxy is
1289 		 * set, use url_get() instead of standard ftp.
1290 		 * Finally, try host:file.
1291 		 */
1292 		host = url;
1293 		if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
1294 			char *passend, *passagain, *userend;
1295 
1296 			if (ftpproxy) {
1297 				if (url_get(url, ftpproxy, outfile, lastfile) == -1)
1298 					rval = argpos + 1;
1299 				continue;
1300 			}
1301 			host += sizeof(FTP_URL) - 1;
1302 			dir = strchr(host, '/');
1303 
1304 			/* Look for [user:pass@]host[:port] */
1305 
1306 			/* check if we have "user:pass@" */
1307 			userend = strchr(host, ':');
1308 			passend = strchr(host, '@');
1309 			if (passend && userend && userend < passend &&
1310 			    (!dir || passend < dir)) {
1311 				username = host;
1312 				pass = userend + 1;
1313 				host = passend + 1;
1314 				*userend = *passend = '\0';
1315 				passagain = strchr(host, '@');
1316 				if (strchr(pass, '@') != NULL ||
1317 				    (passagain != NULL && passagain < dir)) {
1318 					warnx(at_encoding_warning);
1319 					username = pass = NULL;
1320 					goto bad_ftp_url;
1321 				}
1322 
1323 				if (EMPTYSTRING(username)) {
1324 bad_ftp_url:
1325 					warnx("Invalid URL: %s", argv[argpos]);
1326 					rval = argpos + 1;
1327 					username = pass = NULL;
1328 					continue;
1329 				}
1330 				username = urldecode(username);
1331 				pass = urldecode(pass);
1332 			}
1333 
1334 			/* check [host]:port, or [host] */
1335 			if (host[0] == '[') {
1336 				cp = strchr(host, ']');
1337 				if (cp && (!dir || cp < dir)) {
1338 					if (cp + 1 == dir || cp[1] == ':') {
1339 						host++;
1340 						*cp++ = '\0';
1341 					} else
1342 						cp = NULL;
1343 				} else
1344 					cp = host;
1345 			} else
1346 				cp = host;
1347 
1348 			/* split off host[:port] if there is */
1349 			if (cp) {
1350 				portnum = strchr(cp, ':');
1351 				pathstart = strchr(cp, '/');
1352 				/* : in path is not a port # indicator */
1353 				if (portnum && pathstart &&
1354 				    pathstart < portnum)
1355 					portnum = NULL;
1356 
1357 				if (!portnum)
1358 					;
1359 				else {
1360 					if (!dir)
1361 						;
1362 					else if (portnum + 1 < dir) {
1363 						*portnum++ = '\0';
1364 						/*
1365 						 * XXX should check if portnum
1366 						 * is decimal number
1367 						 */
1368 					} else {
1369 						/* empty portnum */
1370 						goto bad_ftp_url;
1371 					}
1372 				}
1373 			} else
1374 				portnum = NULL;
1375 		} else {			/* classic style `host:file' */
1376 			dir = strchr(host, ':');
1377 		}
1378 		if (EMPTYSTRING(host)) {
1379 			rval = argpos + 1;
1380 			continue;
1381 		}
1382 
1383 		/*
1384 		 * If dir is NULL, the file wasn't specified
1385 		 * (URL looked something like ftp://host)
1386 		 */
1387 		if (dir != NULL)
1388 			*dir++ = '\0';
1389 
1390 		/*
1391 		 * Extract the file and (if present) directory name.
1392 		 */
1393 		if (!EMPTYSTRING(dir)) {
1394 			cp = strrchr(dir, '/');
1395 			if (cp != NULL) {
1396 				*cp++ = '\0';
1397 				file = cp;
1398 			} else {
1399 				file = dir;
1400 				dir = NULL;
1401 			}
1402 		}
1403 #ifndef SMALL
1404 		if (debug)
1405 			fprintf(ttyout,
1406 			    "user %s:%s host %s port %s dir %s file %s\n",
1407 			    username, pass ? "XXXX" : NULL, host, portnum,
1408 			    dir, file);
1409 #endif /* !SMALL */
1410 
1411 		/*
1412 		 * Set up the connection.
1413 		 */
1414 		if (connected)
1415 			disconnect(0, NULL);
1416 		xargv[0] = __progname;
1417 		xargv[1] = host;
1418 		xargv[2] = NULL;
1419 		xargc = 2;
1420 		if (!EMPTYSTRING(portnum)) {
1421 			xargv[2] = portnum;
1422 			xargv[3] = NULL;
1423 			xargc = 3;
1424 		}
1425 		oautologin = autologin;
1426 		if (username == NULL)
1427 			anonftp = 1;
1428 		else {
1429 			anonftp = 0;
1430 			autologin = 0;
1431 		}
1432 		setpeer(xargc, xargv);
1433 		autologin = oautologin;
1434 		if (connected == 0 ||
1435 		    (connected == 1 && autologin && (username == NULL ||
1436 		    !ftp_login(host, username, pass)))) {
1437 			warnx("Can't connect or login to host `%s'", host);
1438 			rval = argpos + 1;
1439 			continue;
1440 		}
1441 
1442 		/* Always use binary transfers. */
1443 		setbinary(0, NULL);
1444 
1445 		dirhasglob = filehasglob = 0;
1446 		if (doglob) {
1447 			if (!EMPTYSTRING(dir) &&
1448 			    strpbrk(dir, "*?[]{}") != NULL)
1449 				dirhasglob = 1;
1450 			if (!EMPTYSTRING(file) &&
1451 			    strpbrk(file, "*?[]{}") != NULL)
1452 				filehasglob = 1;
1453 		}
1454 
1455 		/* Change directories, if necessary. */
1456 		if (!EMPTYSTRING(dir) && !dirhasglob) {
1457 			xargv[0] = "cd";
1458 			xargv[1] = dir;
1459 			xargv[2] = NULL;
1460 			cd(2, xargv);
1461 			if (!dirchange) {
1462 				rval = argpos + 1;
1463 				continue;
1464 			}
1465 		}
1466 
1467 		if (EMPTYSTRING(file)) {
1468 #ifndef SMALL
1469 			rval = -1;
1470 #else /* !SMALL */
1471 			recvrequest("NLST", "-", NULL, "w", 0, 0);
1472 			rval = 0;
1473 #endif /* !SMALL */
1474 			continue;
1475 		}
1476 
1477 		if (verbose)
1478 			fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file);
1479 
1480 		if (dirhasglob) {
1481 			snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
1482 			file = rempath;
1483 		}
1484 
1485 		/* Fetch the file(s). */
1486 		xargc = 2;
1487 		xargv[0] = "get";
1488 		xargv[1] = file;
1489 		xargv[2] = NULL;
1490 		if (dirhasglob || filehasglob) {
1491 			int ointeractive;
1492 
1493 			ointeractive = interactive;
1494 			interactive = 0;
1495 			xargv[0] = "mget";
1496 #ifndef SMALL
1497 			if (resume) {
1498 				xargc = 3;
1499 				xargv[1] = "-c";
1500 				xargv[2] = file;
1501 				xargv[3] = NULL;
1502 			}
1503 #endif /* !SMALL */
1504 			mget(xargc, xargv);
1505 			interactive = ointeractive;
1506 		} else {
1507 			if (outfile != NULL) {
1508 				xargv[2] = outfile;
1509 				xargv[3] = NULL;
1510 				xargc++;
1511 			}
1512 #ifndef SMALL
1513 			if (resume)
1514 				reget(xargc, xargv);
1515 			else
1516 #endif /* !SMALL */
1517 				get(xargc, xargv);
1518 		}
1519 
1520 		if ((code / 100) != COMPLETE)
1521 			rval = argpos + 1;
1522 	}
1523 	if (connected && rval != -1)
1524 		disconnect(0, NULL);
1525 	return (rval);
1526 }
1527 
1528 char *
1529 urldecode(const char *str)
1530 {
1531 	char *ret, c;
1532 	int i, reallen;
1533 
1534 	if (str == NULL)
1535 		return NULL;
1536 	if ((ret = malloc(strlen(str)+1)) == NULL)
1537 		err(1, "Can't allocate memory for URL decoding");
1538 	for (i = 0, reallen = 0; str[i] != '\0'; i++, reallen++, ret++) {
1539 		c = str[i];
1540 		if (c == '+') {
1541 			*ret = ' ';
1542 			continue;
1543 		}
1544 
1545 		/* Cannot use strtol here because next char
1546 		 * after %xx may be a digit.
1547 		 */
1548 		if (c == '%' && isxdigit((unsigned char)str[i+1]) &&
1549 		    isxdigit((unsigned char)str[i+2])) {
1550 			*ret = hextochar(&str[i+1]);
1551 			i+=2;
1552 			continue;
1553 		}
1554 		*ret = c;
1555 	}
1556 	*ret = '\0';
1557 
1558 	return ret-reallen;
1559 }
1560 
1561 static char *
1562 recode_credentials(const char *userinfo)
1563 {
1564 	char *ui, *creds;
1565 	size_t ulen, credsize;
1566 
1567 	/* url-decode the user and pass */
1568 	ui = urldecode(userinfo);
1569 
1570 	ulen = strlen(ui);
1571 	credsize = (ulen + 2) / 3 * 4 + 1;
1572 	creds = malloc(credsize);
1573 	if (creds == NULL)
1574 		errx(1, "out of memory");
1575 	if (b64_ntop(ui, ulen, creds, credsize) == -1)
1576 		errx(1, "error in base64 encoding");
1577 	free(ui);
1578 	return (creds);
1579 }
1580 
1581 static char
1582 hextochar(const char *str)
1583 {
1584 	unsigned char c, ret;
1585 
1586 	c = str[0];
1587 	ret = c;
1588 	if (isalpha(c))
1589 		ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
1590 	else
1591 		ret -= '0';
1592 	ret *= 16;
1593 
1594 	c = str[1];
1595 	ret += c;
1596 	if (isalpha(c))
1597 		ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
1598 	else
1599 		ret -= '0';
1600 	return ret;
1601 }
1602 
1603 int
1604 isurl(const char *p)
1605 {
1606 
1607 	if (strncasecmp(p, FTP_URL, sizeof(FTP_URL) - 1) == 0 ||
1608 	    strncasecmp(p, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1609 #ifndef NOSSL
1610 	    strncasecmp(p, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0 ||
1611 #endif /* !NOSSL */
1612 	    strncasecmp(p, FILE_URL, sizeof(FILE_URL) - 1) == 0 ||
1613 	    strstr(p, ":/"))
1614 		return (1);
1615 	return (0);
1616 }
1617 
1618 static char *
1619 ftp_readline(FILE *fp, size_t *lenp)
1620 {
1621 	return fparseln(fp, lenp, NULL, "\0\0\0", 0);
1622 }
1623 
1624 #ifndef SMALL
1625 static int
1626 ftp_printf(FILE *fp, const char *fmt, ...)
1627 {
1628 	va_list	ap;
1629 	int	ret;
1630 
1631 	va_start(ap, fmt);
1632 	ret = vfprintf(fp, fmt, ap);
1633 	va_end(ap);
1634 
1635 	if (debug) {
1636 		va_start(ap, fmt);
1637 		vfprintf(ttyout, fmt, ap);
1638 		va_end(ap);
1639 	}
1640 
1641 	return ret;
1642 }
1643 #endif /* !SMALL */
1644 
1645 static void
1646 ftp_close(FILE **fin, struct tls **tls, int *fd)
1647 {
1648 #ifndef NOSSL
1649 	int	ret;
1650 
1651 	if (*tls != NULL) {
1652 		if (tls_session_fd != -1)
1653 			dprintf(STDERR_FILENO, "tls session resumed: %s\n",
1654 			    tls_conn_session_resumed(*tls) ? "yes" : "no");
1655 		do {
1656 			ret = tls_close(*tls);
1657 		} while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
1658 		tls_free(*tls);
1659 		*tls = NULL;
1660 	}
1661 	if (*fd != -1) {
1662 		close(*fd);
1663 		*fd = -1;
1664 	}
1665 #endif
1666 	if (*fin != NULL) {
1667 		fclose(*fin);
1668 		*fin = NULL;
1669 	}
1670 }
1671 
1672 static const char *
1673 sockerror(struct tls *tls)
1674 {
1675 	int	save_errno = errno;
1676 #ifndef NOSSL
1677 	if (tls != NULL) {
1678 		const char *tlserr = tls_error(tls);
1679 		if (tlserr != NULL)
1680 			return tlserr;
1681 	}
1682 #endif
1683 	return strerror(save_errno);
1684 }
1685 
1686 #ifndef NOSSL
1687 static int
1688 proxy_connect(int socket, char *host, char *cookie)
1689 {
1690 	int l;
1691 	char buf[1024];
1692 	char *connstr, *hosttail, *port;
1693 
1694 	if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
1695 		(hosttail[1] == '\0' || hosttail[1] == ':')) {
1696 		host++;
1697 		*hosttail++ = '\0';
1698 	} else
1699 		hosttail = host;
1700 
1701 	port = strrchr(hosttail, ':');		/* find portnum */
1702 	if (port != NULL)
1703 		*port++ = '\0';
1704 	if (!port)
1705 		port = "443";
1706 
1707 	if (cookie) {
1708 		l = asprintf(&connstr, "CONNECT %s:%s HTTP/1.1\r\n"
1709 			"Proxy-Authorization: Basic %s\r\n%s\r\n\r\n",
1710 			host, port, cookie, HTTP_USER_AGENT);
1711 	} else {
1712 		l = asprintf(&connstr, "CONNECT %s:%s HTTP/1.1\r\n%s\r\n\r\n",
1713 			host, port, HTTP_USER_AGENT);
1714 	}
1715 
1716 	if (l == -1)
1717 		errx(1, "Could not allocate memory to assemble connect string!");
1718 #ifndef SMALL
1719 	if (debug)
1720 		printf("%s", connstr);
1721 #endif /* !SMALL */
1722 	if (write(socket, connstr, l) != l)
1723 		err(1, "Could not send connect string");
1724 	read(socket, &buf, sizeof(buf)); /* only proxy header XXX: error handling? */
1725 	free(connstr);
1726 	return(200);
1727 }
1728 
1729 static int
1730 stdio_tls_write_wrapper(void *arg, const char *buf, int len)
1731 {
1732 	struct tls *tls = arg;
1733 	ssize_t ret;
1734 
1735 	do {
1736 		ret = tls_write(tls, buf, len);
1737 	} while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
1738 
1739 	return ret;
1740 }
1741 
1742 static int
1743 stdio_tls_read_wrapper(void *arg, char *buf, int len)
1744 {
1745 	struct tls *tls = arg;
1746 	ssize_t ret;
1747 
1748 	do {
1749 		ret = tls_read(tls, buf, len);
1750 	} while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
1751 
1752 	return ret;
1753 }
1754 #endif /* !NOSSL */
1755