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