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