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