xref: /openbsd-src/usr.bin/ftp/fetch.c (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
1 /*	$OpenBSD: fetch.c,v 1.199 2021/01/01 17:39:54 chrisz 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 	case 308:	/* Permanent Redirect (RFC 7538) */
847 		isredirect++;
848 		if (redirect_loop++ > 10) {
849 			warnx("Too many redirections requested");
850 			goto cleanup_url_get;
851 		}
852 		break;
853 #ifndef SMALL
854 	case 416:	/* Requested Range Not Satisfiable */
855 		warnx("File is already fully retrieved.");
856 		goto cleanup_url_get;
857 #endif /* !SMALL */
858 	case 503:
859 		isunavail = 1;
860 		break;
861 	default:
862 		strnvis(gerror, cp, sizeof gerror, VIS_SAFE);
863 		warnx("Error retrieving %s: %s", origline, gerror);
864 		goto cleanup_url_get;
865 	}
866 
867 	/*
868 	 * Read the rest of the header.
869 	 */
870 	free(buf);
871 	filesize = -1;
872 
873 	for (;;) {
874 		if ((buf = ftp_readline(fin, &len)) == NULL) {
875 			warnx("Receiving HTTP reply: %s", sockerror(tls));
876 			goto cleanup_url_get;
877 		}
878 
879 		while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
880 			buf[--len] = '\0';
881 		if (len == 0)
882 			break;
883 #ifndef SMALL
884 		if (debug)
885 			fprintf(ttyout, "received '%s'\n", buf);
886 #endif /* !SMALL */
887 
888 		/* Look for some headers */
889 		cp = buf;
890 #define CONTENTLEN "Content-Length: "
891 		if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) {
892 			size_t s;
893 			cp += sizeof(CONTENTLEN) - 1;
894 			if ((s = strcspn(cp, " \t")))
895 				*(cp+s) = 0;
896 			filesize = strtonum(cp, 0, LLONG_MAX, &errstr);
897 			if (errstr != NULL)
898 				goto improper;
899 #ifndef SMALL
900 			if (restart_point)
901 				filesize += restart_point;
902 #endif /* !SMALL */
903 #define LOCATION "Location: "
904 		} else if (isredirect &&
905 		    strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) {
906 			cp += sizeof(LOCATION) - 1;
907 			/*
908 			 * If there is a colon before the first slash, this URI
909 			 * is not relative. RFC 3986 4.2
910 			 */
911 			if (cp[strcspn(cp, ":/")] != ':') {
912 #ifdef SMALL
913 				errx(1, "Relative redirect not supported");
914 #else /* SMALL */
915 				/* XXX doesn't handle protocol-relative URIs */
916 				if (*cp == '/') {
917 					locbase = NULL;
918 					cp++;
919 				} else {
920 					locbase = strdup(path);
921 					if (locbase == NULL)
922 						errx(1, "Can't allocate memory"
923 						    " for location base");
924 					loctail = strchr(locbase, '#');
925 					if (loctail != NULL)
926 						*loctail = '\0';
927 					loctail = strchr(locbase, '?');
928 					if (loctail != NULL)
929 						*loctail = '\0';
930 					loctail = strrchr(locbase, '/');
931 					if (loctail == NULL) {
932 						free(locbase);
933 						locbase = NULL;
934 					} else
935 						loctail[1] = '\0';
936 				}
937 				/* Contruct URL from relative redirect */
938 				if (asprintf(&redirurl, "%s%s%s%s/%s%s",
939 				    scheme, full_host,
940 				    portnum ? ":" : "",
941 				    portnum ? portnum : "",
942 				    locbase ? locbase : "",
943 				    cp) == -1)
944 					errx(1, "Cannot build "
945 					    "redirect URL");
946 				free(locbase);
947 #endif /* SMALL */
948 			} else if ((redirurl = strdup(cp)) == NULL)
949 				errx(1, "Cannot allocate memory for URL");
950 			loctail = strchr(redirurl, '#');
951 			if (loctail != NULL)
952 				*loctail = '\0';
953 			if (verbose)
954 				fprintf(ttyout, "Redirected to %s\n", redirurl);
955 			ftp_close(&fin, &tls, &fd);
956 			rval = url_get(redirurl, proxyenv, savefile, lastfile);
957 			free(redirurl);
958 			goto cleanup_url_get;
959 #define RETRYAFTER "Retry-After: "
960 		} else if (isunavail &&
961 		    strncasecmp(cp, RETRYAFTER, sizeof(RETRYAFTER) - 1) == 0) {
962 			size_t s;
963 			cp += sizeof(RETRYAFTER) - 1;
964 			if ((s = strcspn(cp, " \t")))
965 				cp[s] = '\0';
966 			retryafter = strtonum(cp, 0, 0, &errstr);
967 			if (errstr != NULL)
968 				retryafter = -1;
969 #define TRANSFER_ENCODING "Transfer-Encoding: "
970 		} else if (strncasecmp(cp, TRANSFER_ENCODING,
971 			    sizeof(TRANSFER_ENCODING) - 1) == 0) {
972 			cp += sizeof(TRANSFER_ENCODING) - 1;
973 			cp[strcspn(cp, " \t")] = '\0';
974 			if (strcasecmp(cp, "chunked") == 0)
975 				chunked = 1;
976 		}
977 		free(buf);
978 	}
979 
980 	/* Content-Length should be ignored for Transfer-Encoding: chunked */
981 	if (chunked)
982 		filesize = -1;
983 
984 	if (isunavail) {
985 		if (retried || retryafter != 0)
986 			warnx("Error retrieving %s: 503 Service Unavailable",
987 			    origline);
988 		else {
989 			if (verbose)
990 				fprintf(ttyout, "Retrying %s\n", origline);
991 			retried = 1;
992 			ftp_close(&fin, &tls, &fd);
993 			rval = url_get(origline, proxyenv, savefile, lastfile);
994 		}
995 		goto cleanup_url_get;
996 	}
997 
998 	/* Open the output file.  */
999 	if (!pipeout) {
1000 #ifndef SMALL
1001 		if (resume)
1002 			out = open(savefile, O_CREAT | O_WRONLY | O_APPEND,
1003 				0666);
1004 		else
1005 #endif /* !SMALL */
1006 			out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC,
1007 				0666);
1008 		if (out == -1) {
1009 			warn("Can't open %s", savefile);
1010 			goto cleanup_url_get;
1011 		}
1012 	} else {
1013 		out = fileno(stdout);
1014 #ifdef SMALL
1015 		if (lastfile) {
1016 			if (pledge("stdio tty", NULL) == -1)
1017 				err(1, "pledge");
1018 		}
1019 #endif
1020 	}
1021 
1022 	free(buf);
1023 	if ((buf = malloc(buflen)) == NULL)
1024 		errx(1, "Can't allocate memory for transfer buffer");
1025 
1026 	/* Trap signals */
1027 	oldintr = NULL;
1028 	oldinti = NULL;
1029 	if (setjmp(httpabort)) {
1030 		if (oldintr)
1031 			(void)signal(SIGINT, oldintr);
1032 		if (oldinti)
1033 			(void)signal(SIGINFO, oldinti);
1034 		goto cleanup_url_get;
1035 	}
1036 	oldintr = signal(SIGINT, aborthttp);
1037 
1038 	bytes = 0;
1039 	hashbytes = mark;
1040 	progressmeter(-1, path);
1041 
1042 	/* Finally, suck down the file. */
1043 	oldinti = signal(SIGINFO, psummary);
1044 	if (chunked) {
1045 		error = save_chunked(fin, tls, out, buf, buflen);
1046 		signal(SIGINT, oldintr);
1047 		signal(SIGINFO, oldinti);
1048 		if (error == -1)
1049 			goto cleanup_url_get;
1050 	} else {
1051 		while ((len = fread(buf, 1, buflen, fin)) > 0) {
1052 			bytes += len;
1053 			for (cp = buf; len > 0; len -= wlen, cp += wlen) {
1054 				if ((wlen = write(out, cp, len)) == -1) {
1055 					warn("Writing %s", savefile);
1056 					signal(SIGINT, oldintr);
1057 					signal(SIGINFO, oldinti);
1058 					goto cleanup_url_get;
1059 				}
1060 			}
1061 			if (hash && !progress) {
1062 				while (bytes >= hashbytes) {
1063 					(void)putc('#', ttyout);
1064 					hashbytes += mark;
1065 				}
1066 				(void)fflush(ttyout);
1067 			}
1068 		}
1069 		save_errno = errno;
1070 		signal(SIGINT, oldintr);
1071 		signal(SIGINFO, oldinti);
1072 		if (hash && !progress && bytes > 0) {
1073 			if (bytes < mark)
1074 				(void)putc('#', ttyout);
1075 			(void)putc('\n', ttyout);
1076 			(void)fflush(ttyout);
1077 		}
1078 		if (len == 0 && ferror(fin)) {
1079 			errno = save_errno;
1080 			warnx("Reading from socket: %s", sockerror(tls));
1081 			goto cleanup_url_get;
1082 		}
1083 	}
1084 	progressmeter(1, NULL);
1085 	if (
1086 #ifndef SMALL
1087 		!resume &&
1088 #endif /* !SMALL */
1089 		filesize != -1 && len == 0 && bytes != filesize) {
1090 		if (verbose)
1091 			fputs("Read short file.\n", ttyout);
1092 		goto cleanup_url_get;
1093 	}
1094 
1095 	if (verbose)
1096 		ptransfer(0);
1097 
1098 	rval = 0;
1099 	goto cleanup_url_get;
1100 
1101 noftpautologin:
1102 	warnx(
1103 	    "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
1104 	goto cleanup_url_get;
1105 
1106 improper:
1107 	warnx("Improper response from %s", host);
1108 
1109 cleanup_url_get:
1110 #ifndef SMALL
1111 	free(full_host);
1112 #endif /* !SMALL */
1113 #ifndef NOSSL
1114 	free(sslhost);
1115 #endif /* !NOSSL */
1116 	ftp_close(&fin, &tls, &fd);
1117 	if (out >= 0 && out != fileno(stdout))
1118 		close(out);
1119 	free(buf);
1120 	free(pathbuf);
1121 	free(proxyhost);
1122 	free(proxyurl);
1123 	free(newline);
1124 	free(credentials);
1125 	free(proxy_credentials);
1126 	return (rval);
1127 }
1128 
1129 static int
1130 save_chunked(FILE *fin, struct tls *tls, int out, char *buf, size_t buflen)
1131 {
1132 
1133 	char			*header, *end, *cp;
1134 	unsigned long		chunksize;
1135 	size_t			hlen, rlen, wlen;
1136 	ssize_t			written;
1137 	char			cr, lf;
1138 
1139 	for (;;) {
1140 		header = ftp_readline(fin, &hlen);
1141 		if (header == NULL)
1142 			break;
1143 		/* strip CRLF and any optional chunk extension */
1144 		header[strcspn(header, ";\r\n")] = '\0';
1145 		errno = 0;
1146 		chunksize = strtoul(header, &end, 16);
1147 		if (errno || header[0] == '\0' || *end != '\0' ||
1148 		    chunksize > INT_MAX) {
1149 			warnx("Invalid chunk size '%s'", header);
1150 			free(header);
1151 			return -1;
1152 		}
1153 		free(header);
1154 
1155 		if (chunksize == 0) {
1156 			/* We're done.  Ignore optional trailer. */
1157 			return 0;
1158 		}
1159 
1160 		for (written = 0; chunksize != 0; chunksize -= rlen) {
1161 			rlen = (chunksize < buflen) ? chunksize : buflen;
1162 			rlen = fread(buf, 1, rlen, fin);
1163 			if (rlen == 0)
1164 				break;
1165 			bytes += rlen;
1166 			for (cp = buf, wlen = rlen; wlen > 0;
1167 			    wlen -= written, cp += written) {
1168 				if ((written = write(out, cp, wlen)) == -1) {
1169 					warn("Writing output file");
1170 					return -1;
1171 				}
1172 			}
1173 		}
1174 
1175 		if (rlen == 0 ||
1176 		    fread(&cr, 1, 1, fin) != 1 ||
1177 		    fread(&lf, 1, 1, fin) != 1)
1178 			break;
1179 
1180 		if (cr != '\r' || lf != '\n') {
1181 			warnx("Invalid chunked encoding");
1182 			return -1;
1183 		}
1184 	}
1185 
1186 	if (ferror(fin))
1187 		warnx("Error while reading from socket: %s", sockerror(tls));
1188 	else
1189 		warnx("Invalid chunked encoding: short read");
1190 
1191 	return -1;
1192 }
1193 
1194 /*
1195  * Abort a http retrieval
1196  */
1197 /* ARGSUSED */
1198 static void
1199 aborthttp(int signo)
1200 {
1201 	const char errmsg[] = "\nfetch aborted.\n";
1202 
1203 	alarmtimer(0);
1204 	write(fileno(ttyout), errmsg, sizeof(errmsg) - 1);
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