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