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