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