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