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