xref: /openbsd-src/usr.bin/ftp/fetch.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
1 /*	$OpenBSD: fetch.c,v 1.85 2009/04/27 21:37:13 deraadt Exp $	*/
2 /*	$NetBSD: fetch.c,v 1.14 1997/08/18 10:20:20 lukem Exp $	*/
3 
4 /*-
5  * Copyright (c) 1997 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Jason Thorpe and Luke Mewburn.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * FTP User Program -- Command line file retrieval
35  */
36 
37 #include <sys/types.h>
38 #include <sys/param.h>
39 #include <sys/socket.h>
40 #include <sys/stat.h>
41 
42 #include <netinet/in.h>
43 
44 #include <arpa/ftp.h>
45 #include <arpa/inet.h>
46 
47 #include <ctype.h>
48 #include <err.h>
49 #include <libgen.h>
50 #include <limits.h>
51 #include <netdb.h>
52 #include <fcntl.h>
53 #include <signal.h>
54 #include <stdio.h>
55 #include <stdarg.h>
56 #include <errno.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 #include <util.h>
61 #include <resolv.h>
62 
63 #ifndef SMALL
64 #include <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 
72 static int	url_get(const char *, const char *, const char *);
73 void		aborthttp(int);
74 void		abortfile(int);
75 char		hextochar(const char *);
76 char		*urldecode(const char *);
77 int		ftp_printf(FILE *, SSL *, const char *, ...) __attribute__((format(printf, 3, 4)));
78 char		*ftp_readline(FILE *, SSL *, size_t *);
79 size_t		ftp_read(FILE *, SSL *, char *, size_t);
80 #ifndef SMALL
81 int		proxy_connect(int, char *, char *);
82 int		SSL_vprintf(SSL *, const char *, va_list);
83 char		*SSL_readline(SSL *, size_t *);
84 #endif /* !SMALL */
85 
86 #define	FTP_URL		"ftp://"	/* ftp URL prefix */
87 #define	HTTP_URL	"http://"	/* http URL prefix */
88 #define	HTTPS_URL	"https://"	/* https URL prefix */
89 #define	FILE_URL	"file:"		/* file URL prefix */
90 #define FTP_PROXY	"ftp_proxy"	/* env var with ftp proxy location */
91 #define HTTP_PROXY	"http_proxy"	/* env var with http proxy location */
92 
93 #define COOKIE_MAX_LEN	42
94 
95 #define EMPTYSTRING(x)	((x) == NULL || (*(x) == '\0'))
96 
97 static const char *at_encoding_warning =
98     "Extra `@' characters in usernames and passwords should be encoded as %%40";
99 
100 jmp_buf	httpabort;
101 
102 static int	redirect_loop;
103 
104 /*
105  * Retrieve URL, via the proxy in $proxyvar if necessary.
106  * Modifies the string argument given.
107  * Returns -1 on failure, 0 on success
108  */
109 static int
110 url_get(const char *origline, const char *proxyenv, const char *outfile)
111 {
112 	char pbuf[NI_MAXSERV], hbuf[NI_MAXHOST], *cp, *portnum, *path, ststr[4];
113 	char *hosttail, *cause = "unknown", *newline, *host, *port, *buf = NULL;
114 	int error, i, isftpurl = 0, isfileurl = 0, isredirect = 0, rval = -1;
115 	struct addrinfo hints, *res0, *res;
116 	const char * volatile savefile;
117 	char * volatile proxyurl = NULL;
118 	char *cookie = NULL;
119 	volatile int s = -1, out;
120 	volatile sig_t oldintr;
121 	FILE *fin = NULL;
122 	off_t hashbytes;
123 	const char *errstr;
124 	size_t len, wlen;
125 #ifndef SMALL
126 	char *sslpath = NULL, *sslhost = NULL;
127 	int ishttpsurl = 0;
128 	SSL_CTX *ssl_ctx = NULL;
129 #endif /* !SMALL */
130 	SSL *ssl = NULL;
131 	int status;
132 
133 	newline = strdup(origline);
134 	if (newline == NULL)
135 		errx(1, "Can't allocate memory to parse URL");
136 	if (strncasecmp(newline, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
137 		host = newline + sizeof(HTTP_URL) - 1;
138 	else if (strncasecmp(newline, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
139 		host = newline + sizeof(FTP_URL) - 1;
140 		isftpurl = 1;
141 	} else if (strncasecmp(newline, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
142 		host = newline + sizeof(FILE_URL) - 1;
143 		isfileurl = 1;
144 #ifndef SMALL
145 	} else if (strncasecmp(newline, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0) {
146 		host = newline + sizeof(HTTPS_URL) - 1;
147 		ishttpsurl = 1;
148 #endif /* !SMALL */
149 	} else
150 		errx(1, "url_get: Invalid URL '%s'", newline);
151 
152 	if (isfileurl) {
153 		path = host;
154 	} else {
155 		path = strchr(host, '/');		/* find path */
156 		if (EMPTYSTRING(path)) {
157 			if (isftpurl)
158 				goto noftpautologin;
159 			warnx("Invalid URL (no `/' after host): %s", origline);
160 			goto cleanup_url_get;
161 		}
162 		*path++ = '\0';
163 		if (EMPTYSTRING(path)) {
164 			if (isftpurl)
165 				goto noftpautologin;
166 			warnx("Invalid URL (no file after host): %s", origline);
167 			goto cleanup_url_get;
168 		}
169 	}
170 
171 	if (outfile)
172 		savefile = outfile;
173 	else
174 		savefile = basename(path);
175 
176 #ifndef SMALL
177 	if (resume && (strcmp(savefile, "-") == 0)) {
178 		warnx("can't append to stdout");
179 		goto cleanup_url_get;
180 	}
181 #endif /* !SMALL */
182 
183 	if (EMPTYSTRING(savefile)) {
184 		if (isftpurl)
185 			goto noftpautologin;
186 		warnx("Invalid URL (no file after directory): %s", origline);
187 		goto cleanup_url_get;
188 	}
189 
190 	if (!isfileurl && proxyenv != NULL) {		/* use proxy */
191 #ifndef SMALL
192 		if (ishttpsurl) {
193 			sslpath = strdup(path);
194 			sslhost = strdup(host);
195 			if (! sslpath || ! sslhost)
196 				errx(1, "Can't allocate memory for https path/host.");
197 		}
198 #endif /* !SMALL */
199 		proxyurl = strdup(proxyenv);
200 		if (proxyurl == NULL)
201 			errx(1, "Can't allocate memory for proxy URL.");
202 		if (strncasecmp(proxyurl, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
203 			host = proxyurl + sizeof(HTTP_URL) - 1;
204 		else if (strncasecmp(proxyurl, FTP_URL, sizeof(FTP_URL) - 1) == 0)
205 			host = proxyurl + sizeof(FTP_URL) - 1;
206 		else {
207 			warnx("Malformed proxy URL: %s", proxyenv);
208 			goto cleanup_url_get;
209 		}
210 		if (EMPTYSTRING(host)) {
211 			warnx("Malformed proxy URL: %s", proxyenv);
212 			goto cleanup_url_get;
213 		}
214 		*--path = '/';			/* add / back to real path */
215 		path = strchr(host, '/');	/* remove trailing / on host */
216 		if (!EMPTYSTRING(path))
217 			*path++ = '\0';		/* i guess this ++ is useless */
218 
219 		path = strchr(host, '@');	/* look for credentials in proxy */
220 		if (!EMPTYSTRING(path)) {
221 			*path = '\0';
222 			cookie = strchr(host, ':');
223 			if (EMPTYSTRING(cookie)) {
224 				warnx("Malformed proxy URL: %s", proxyenv);
225 				goto cleanup_url_get;
226 			}
227 			cookie  = malloc(COOKIE_MAX_LEN);
228 			if (cookie == NULL)
229 				errx(1, "out of memory");
230 			if (b64_ntop(host, strlen(host), cookie, COOKIE_MAX_LEN) == -1)
231 				errx(1, "error in base64 encoding");
232 			*path = '@'; /* restore @ in proxyurl */
233 			/*
234 			 * This removes the password from proxyurl,
235 			 * filling with stars
236 			 */
237 			for (host = 1 + strchr(proxyurl + 5, ':');  *host != '@';
238 			     host++)
239 				*host = '*';
240 
241 			host = path + 1;
242 		}
243 		path = newline;
244 	}
245 
246 	if (isfileurl) {
247 		struct stat st;
248 
249 		s = open(path, O_RDONLY);
250 		if (s == -1) {
251 			warn("Can't open file %s", path);
252 			goto cleanup_url_get;
253 		}
254 
255 		if (fstat(s, &st) == -1)
256 			filesize = -1;
257 		else
258 			filesize = st.st_size;
259 
260 		/* Open the output file.  */
261 		if (strcmp(savefile, "-") != 0) {
262 #ifndef SMALL
263 			if (resume)
264 				out = open(savefile, O_CREAT | O_WRONLY |
265 					O_APPEND, 0666);
266 
267 			else
268 #endif /* !SMALL */
269 				out = open(savefile, O_CREAT | O_WRONLY |
270 					O_TRUNC, 0666);
271 			if (out < 0) {
272 				warn("Can't open %s", savefile);
273 				goto cleanup_url_get;
274 			}
275 		} else
276 			out = fileno(stdout);
277 
278 #ifndef SMALL
279 		if (resume) {
280 			if (fstat(out, &st) == -1) {
281 				warn("Can't fstat %s", savefile);
282 				goto cleanup_url_get;
283 			}
284 			if (lseek(s, st.st_size, SEEK_SET) == -1) {
285 				warn("Can't lseek %s", path);
286 				goto cleanup_url_get;
287 			}
288 			restart_point = st.st_size;
289 		}
290 #endif /* !SMALL */
291 
292 		/* Trap signals */
293 		oldintr = NULL;
294 		if (setjmp(httpabort)) {
295 			if (oldintr)
296 				(void)signal(SIGINT, oldintr);
297 			goto cleanup_url_get;
298 		}
299 		oldintr = signal(SIGINT, abortfile);
300 
301 		bytes = 0;
302 		hashbytes = mark;
303 		progressmeter(-1, path);
304 
305 		if ((buf = malloc(4096)) == NULL)
306 			errx(1, "Can't allocate memory for transfer buffer");
307 
308 		/* Finally, suck down the file. */
309 		i = 0;
310 		while ((len = read(s, buf, 4096)) > 0) {
311 			bytes += len;
312 			for (cp = buf; len > 0; len -= i, cp += i) {
313 				if ((i = write(out, cp, len)) == -1) {
314 					warn("Writing %s", savefile);
315 					goto cleanup_url_get;
316 				}
317 				else if (i == 0)
318 					break;
319 			}
320 			if (hash && !progress) {
321 				while (bytes >= hashbytes) {
322 					(void)putc('#', ttyout);
323 					hashbytes += mark;
324 				}
325 				(void)fflush(ttyout);
326 			}
327 		}
328 		if (hash && !progress && bytes > 0) {
329 			if (bytes < mark)
330 				(void)putc('#', ttyout);
331 			(void)putc('\n', ttyout);
332 			(void)fflush(ttyout);
333 		}
334 		if (len != 0) {
335 			warn("Reading from file");
336 			goto cleanup_url_get;
337 		}
338 		progressmeter(1, NULL);
339 		if (verbose)
340 			fputs("Successfully retrieved file.\n", ttyout);
341 		(void)signal(SIGINT, oldintr);
342 
343 		rval = 0;
344 		goto cleanup_url_get;
345 	}
346 
347 	if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
348 	    (hosttail[1] == '\0' || hosttail[1] == ':')) {
349 		host++;
350 		*hosttail++ = '\0';
351 	} else
352 		hosttail = host;
353 
354 	portnum = strrchr(hosttail, ':');		/* find portnum */
355 	if (portnum != NULL)
356 		*portnum++ = '\0';
357 
358 #ifndef SMALL
359 	if (debug)
360 		fprintf(ttyout, "host %s, port %s, path %s, save as %s.\n",
361 		    host, portnum, path, savefile);
362 #endif /* !SMALL */
363 
364 	memset(&hints, 0, sizeof(hints));
365 	hints.ai_family = family;
366 	hints.ai_socktype = SOCK_STREAM;
367 #ifndef SMALL
368 	port = portnum ? portnum : (ishttpsurl ? httpsport : httpport);
369 #else /* !SMALL */
370 	port = portnum ? portnum : httpport;
371 #endif /* !SMALL */
372 	error = getaddrinfo(host, port, &hints, &res0);
373 	/*
374 	 * If the services file is corrupt/missing, fall back
375 	 * on our hard-coded defines.
376 	 */
377 	if (error == EAI_SERVICE && port == httpport) {
378 		snprintf(pbuf, sizeof(pbuf), "%d", HTTP_PORT);
379 		error = getaddrinfo(host, pbuf, &hints, &res0);
380 #ifndef SMALL
381 	} else if (error == EAI_SERVICE && port == httpsport) {
382 		snprintf(pbuf, sizeof(pbuf), "%d", HTTPS_PORT);
383 		error = getaddrinfo(host, pbuf, &hints, &res0);
384 #endif /* !SMALL */
385 	}
386 	if (error) {
387 		warnx("%s: %s", gai_strerror(error), host);
388 		goto cleanup_url_get;
389 	}
390 
391 	s = -1;
392 	for (res = res0; res; res = res->ai_next) {
393 		if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
394 		    sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0)
395 			strlcpy(hbuf, "(unknown)", sizeof(hbuf));
396 		if (verbose)
397 			fprintf(ttyout, "Trying %s...\n", hbuf);
398 
399 		s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
400 		if (s == -1) {
401 			cause = "socket";
402 			continue;
403 		}
404 
405 again:
406 		if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
407 			int save_errno;
408 
409 			if (errno == EINTR)
410 				goto again;
411 			save_errno = errno;
412 			close(s);
413 			errno = save_errno;
414 			s = -1;
415 			cause = "connect";
416 			continue;
417 		}
418 
419 		/* get port in numeric */
420 		if (getnameinfo(res->ai_addr, res->ai_addrlen, NULL, 0,
421 		    pbuf, sizeof(pbuf), NI_NUMERICSERV) == 0)
422 			port = pbuf;
423 		else
424 			port = NULL;
425 
426 #ifndef SMALL
427 		if (proxyenv && sslhost)
428 			proxy_connect(s, sslhost, cookie);
429 #endif /* !SMALL */
430 		break;
431 	}
432 	freeaddrinfo(res0);
433 	if (s < 0) {
434 		warn("%s", cause);
435 		goto cleanup_url_get;
436 	}
437 
438 #ifndef SMALL
439 	if (ishttpsurl) {
440 		if (proxyenv && sslpath) {
441 			ishttpsurl = 0;
442 			proxyurl = NULL;
443 			path = sslpath;
444 		}
445 		SSL_library_init();
446 		SSL_load_error_strings();
447 		SSLeay_add_ssl_algorithms();
448 		ssl_ctx = SSL_CTX_new(SSLv23_client_method());
449 		ssl = SSL_new(ssl_ctx);
450 		if (ssl == NULL || ssl_ctx == NULL) {
451 			ERR_print_errors_fp(ttyout);
452 			goto cleanup_url_get;
453 		}
454 		if (SSL_set_fd(ssl, s) == 0) {
455 			ERR_print_errors_fp(ttyout);
456 			goto cleanup_url_get;
457 		}
458 		if (SSL_connect(ssl) <= 0) {
459 			ERR_print_errors_fp(ttyout);
460 			goto cleanup_url_get;
461 		}
462 	} else {
463 		fin = fdopen(s, "r+");
464 	}
465 #else /* !SMALL */
466 	fin = fdopen(s, "r+");
467 #endif /* !SMALL */
468 
469 	if (verbose)
470 		fprintf(ttyout, "Requesting %s", origline);
471 	/*
472 	 * Construct and send the request. Proxy requests don't want leading /.
473 	 */
474 #ifndef SMALL
475 	cookie_get(host, path, ishttpsurl, &buf);
476 #endif /* !SMALL */
477 	if (proxyurl) {
478 		if (verbose)
479 			fprintf(ttyout, " (via %s)\n", proxyurl);
480 		/*
481 		 * Host: directive must use the destination host address for
482 		 * the original URI (path).  We do not attach it at this moment.
483 		 */
484 		if (cookie)
485 			ftp_printf(fin, ssl, "GET %s HTTP/1.0\r\n"
486 			    "Proxy-Authorization: Basic %s%s\r\n%s\r\n\r\n",
487 			    path, cookie, buf ? buf : "", HTTP_USER_AGENT);
488 		else
489 			ftp_printf(fin, ssl, "GET %s HTTP/1.0\r\n%s%s\r\n\r\n",
490 			    path, buf ? buf : "", HTTP_USER_AGENT);
491 
492 	} else {
493 		ftp_printf(fin, ssl, "GET /%s %s\r\nHost: ", path,
494 #ifndef SMALL
495 			resume ? "HTTP/1.1" :
496 #endif /* !SMALL */
497 			"HTTP/1.0");
498 		if (strchr(host, ':')) {
499 			char *h, *p;
500 
501 			/*
502 			 * strip off scoped address portion, since it's
503 			 * local to node
504 			 */
505 			h = strdup(host);
506 			if (h == NULL)
507 				errx(1, "Can't allocate memory.");
508 			if ((p = strchr(h, '%')) != NULL)
509 				*p = '\0';
510 			ftp_printf(fin, ssl, "[%s]", h);
511 			free(h);
512 		} else
513 			ftp_printf(fin, ssl, "%s", host);
514 
515 		/*
516 		 * Send port number only if it's specified and does not equal
517 		 * 80. Some broken HTTP servers get confused if you explicitly
518 		 * send them the port number.
519 		 */
520 #ifndef SMALL
521 		if (port && strcmp(port, (ishttpsurl ? "443" : "80")) != 0)
522 			ftp_printf(fin, ssl, ":%s", port);
523 		if (resume) {
524 			int ret;
525 			struct stat stbuf;
526 
527 			ret = stat(savefile, &stbuf);
528 			if (ret < 0) {
529 				if (verbose)
530 					fprintf(ttyout, "\n");
531 				warn("Can't open %s", savefile);
532 				goto cleanup_url_get;
533 			}
534 			restart_point = stbuf.st_size;
535 			ftp_printf(fin, ssl, "\r\nRange: bytes=%lld-",
536 				(long long)restart_point);
537 		}
538 #else /* !SMALL */
539 		if (port && strcmp(port, "80") != 0)
540 			ftp_printf(fin, ssl, ":%s", port);
541 #endif /* !SMALL */
542 		ftp_printf(fin, ssl, "\r\n%s%s\r\n\r\n",
543 		    buf ? buf : "", HTTP_USER_AGENT);
544 		if (verbose)
545 			fprintf(ttyout, "\n");
546 	}
547 
548 
549 #ifndef SMALL
550 	free(buf);
551 #endif /* !SMALL */
552 	buf = NULL;
553 
554 	if (fin != NULL && fflush(fin) == EOF) {
555 		warn("Writing HTTP request");
556 		goto cleanup_url_get;
557 	}
558 	if ((buf = ftp_readline(fin, ssl, &len)) == NULL) {
559 		warn("Receiving HTTP reply");
560 		goto cleanup_url_get;
561 	}
562 
563 	while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
564 		buf[--len] = '\0';
565 #ifndef SMALL
566 	if (debug)
567 		fprintf(ttyout, "received '%s'\n", buf);
568 #endif /* !SMALL */
569 
570 	cp = strchr(buf, ' ');
571 	if (cp == NULL)
572 		goto improper;
573 	else
574 		cp++;
575 
576 	strlcpy(ststr, cp, sizeof(ststr));
577 	status = strtonum(ststr, 200, 416, &errstr);
578 	if (errstr) {
579 		warnx("Error retrieving file: %s", cp);
580 		goto cleanup_url_get;
581 	}
582 
583 	switch (status) {
584 	case 200:	/* OK */
585 #ifndef SMALL
586 	case 206:	/* Partial Content */
587 		break;
588 #endif /* !SMALL */
589 	case 301:	/* Moved Permanently */
590 	case 302:	/* Found */
591 	case 303:	/* See Other */
592 	case 307:	/* Temporary Redirect */
593 		isredirect++;
594 		if (redirect_loop++ > 10) {
595 			warnx("Too many redirections requested");
596 			goto cleanup_url_get;
597 		}
598 		break;
599 #ifndef SMALL
600 	case 416:	/* Requested Range Not Satisfiable */
601 		warnx("File is already fully retrieved.");
602 		goto cleanup_url_get;
603 #endif /* !SMALL */
604 	default:
605 		warnx("Error retrieving file: %s", cp);
606 		goto cleanup_url_get;
607 	}
608 
609 	/*
610 	 * Read the rest of the header.
611 	 */
612 	free(buf);
613 	filesize = -1;
614 
615 	for (;;) {
616 		if ((buf = ftp_readline(fin, ssl, &len)) == NULL) {
617 			warn("Receiving HTTP reply");
618 			goto cleanup_url_get;
619 		}
620 
621 		while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
622 			buf[--len] = '\0';
623 		if (len == 0)
624 			break;
625 #ifndef SMALL
626 		if (debug)
627 			fprintf(ttyout, "received '%s'\n", buf);
628 #endif /* !SMALL */
629 
630 		/* Look for some headers */
631 		cp = buf;
632 #define CONTENTLEN "Content-Length: "
633 		if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) {
634 			cp += sizeof(CONTENTLEN) - 1;
635 			filesize = strtonum(cp, 0, LLONG_MAX, &errstr);
636 			if (errstr != NULL)
637 				goto improper;
638 #ifndef SMALL
639 			if (resume)
640 				filesize += restart_point;
641 #endif /* !SMALL */
642 #define LOCATION "Location: "
643 		} else if (isredirect &&
644 		    strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) {
645 			cp += sizeof(LOCATION) - 1;
646 			if (verbose)
647 				fprintf(ttyout, "Redirected to %s\n", cp);
648 			if (fin != NULL)
649 				fclose(fin);
650 			else if (s != -1)
651 				close(s);
652 			free(proxyurl);
653 			free(newline);
654 			free(cookie);
655 			rval = url_get(cp, proxyenv, outfile);
656 			free(buf);
657 			return (rval);
658 		}
659 	}
660 
661 	/* Open the output file.  */
662 	if (strcmp(savefile, "-") != 0) {
663 #ifndef SMALL
664 		if (resume)
665 			out = open(savefile, O_CREAT | O_WRONLY | O_APPEND,
666 				0666);
667 		else
668 #endif /* !SMALL */
669 			out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC,
670 				0666);
671 		if (out < 0) {
672 			warn("Can't open %s", savefile);
673 			goto cleanup_url_get;
674 		}
675 	} else
676 		out = fileno(stdout);
677 
678 	/* Trap signals */
679 	oldintr = NULL;
680 	if (setjmp(httpabort)) {
681 		if (oldintr)
682 			(void)signal(SIGINT, oldintr);
683 		goto cleanup_url_get;
684 	}
685 	oldintr = signal(SIGINT, aborthttp);
686 
687 	bytes = 0;
688 	hashbytes = mark;
689 	progressmeter(-1, path);
690 
691 	free(buf);
692 
693 	/* Finally, suck down the file. */
694 	if ((buf = malloc(4096)) == NULL)
695 		errx(1, "Can't allocate memory for transfer buffer");
696 	i = 0;
697 	len = 1;
698 	while (len > 0) {
699 		len = ftp_read(fin, ssl, buf, 4096);
700 		bytes += len;
701 		for (cp = buf, wlen = len; wlen > 0; wlen -= i, cp += i) {
702 			if ((i = write(out, cp, wlen)) == -1) {
703 				warn("Writing %s", savefile);
704 				goto cleanup_url_get;
705 			}
706 			else if (i == 0)
707 				break;
708 		}
709 		if (hash && !progress) {
710 			while (bytes >= hashbytes) {
711 				(void)putc('#', ttyout);
712 				hashbytes += mark;
713 			}
714 			(void)fflush(ttyout);
715 		}
716 	}
717 	if (hash && !progress && bytes > 0) {
718 		if (bytes < mark)
719 			(void)putc('#', ttyout);
720 		(void)putc('\n', ttyout);
721 		(void)fflush(ttyout);
722 	}
723 	if (len != 0) {
724 		warn("Reading from socket");
725 		goto cleanup_url_get;
726 	}
727 	progressmeter(1, NULL);
728 	if (
729 #ifndef SMALL
730 		!resume &&
731 #endif /* !SMALL */
732 		filesize != -1 && len == 0 && bytes != filesize) {
733 		if (verbose)
734 			fputs("Read short file.\n", ttyout);
735 		goto cleanup_url_get;
736 	}
737 
738 	if (verbose)
739 		fputs("Successfully retrieved file.\n", ttyout);
740 	(void)signal(SIGINT, oldintr);
741 
742 	rval = 0;
743 	goto cleanup_url_get;
744 
745 noftpautologin:
746 	warnx(
747 	    "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
748 	goto cleanup_url_get;
749 
750 improper:
751 	warnx("Improper response from %s", host);
752 
753 cleanup_url_get:
754 #ifndef SMALL
755 	if (ssl) {
756 		SSL_shutdown(ssl);
757 		SSL_free(ssl);
758 	}
759 #endif /* !SMALL */
760 	if (fin != NULL)
761 		fclose(fin);
762 	else if (s != -1)
763 		close(s);
764 	free(buf);
765 	free(proxyurl);
766 	free(newline);
767 	free(cookie);
768 	return (rval);
769 }
770 
771 /*
772  * Abort a http retrieval
773  */
774 /* ARGSUSED */
775 void
776 aborthttp(int signo)
777 {
778 
779 	alarmtimer(0);
780 	fputs("\nhttp fetch aborted.\n", ttyout);
781 	(void)fflush(ttyout);
782 	longjmp(httpabort, 1);
783 }
784 
785 /*
786  * Abort a http retrieval
787  */
788 /* ARGSUSED */
789 void
790 abortfile(int signo)
791 {
792 
793 	alarmtimer(0);
794 	fputs("\nfile fetch aborted.\n", ttyout);
795 	(void)fflush(ttyout);
796 	longjmp(httpabort, 1);
797 }
798 
799 /*
800  * Retrieve multiple files from the command line, transferring
801  * files of the form "host:path", "ftp://host/path" using the
802  * ftp protocol, and files of the form "http://host/path" using
803  * the http protocol.
804  * If path has a trailing "/", then return (-1);
805  * the path will be cd-ed into and the connection remains open,
806  * and the function will return -1 (to indicate the connection
807  * is alive).
808  * If an error occurs the return value will be the offset+1 in
809  * argv[] of the file that caused a problem (i.e, argv[x]
810  * returns x+1)
811  * Otherwise, 0 is returned if all files retrieved successfully.
812  */
813 int
814 auto_fetch(int argc, char *argv[], char *outfile)
815 {
816 	char *xargv[5];
817 	char *cp, *url, *host, *dir, *file, *portnum;
818 	char *username, *pass, *pathstart;
819 	char *ftpproxy, *httpproxy;
820 	int rval, xargc;
821 	volatile int argpos;
822 	int dirhasglob, filehasglob, oautologin;
823 	char rempath[MAXPATHLEN];
824 
825 	argpos = 0;
826 
827 	if (setjmp(toplevel)) {
828 		if (connected)
829 			disconnect(0, NULL);
830 		return (argpos + 1);
831 	}
832 	(void)signal(SIGINT, (sig_t)intr);
833 	(void)signal(SIGPIPE, (sig_t)lostpeer);
834 
835 	if ((ftpproxy = getenv(FTP_PROXY)) != NULL && *ftpproxy == '\0')
836 		ftpproxy = NULL;
837 	if ((httpproxy = getenv(HTTP_PROXY)) != NULL && *httpproxy == '\0')
838 		httpproxy = NULL;
839 
840 	/*
841 	 * Loop through as long as there's files to fetch.
842 	 */
843 	for (rval = 0; (rval == 0) && (argpos < argc); free(url), argpos++) {
844 		if (strchr(argv[argpos], ':') == NULL)
845 			break;
846 		host = dir = file = portnum = username = pass = NULL;
847 
848 		/*
849 		 * We muck with the string, so we make a copy.
850 		 */
851 		url = strdup(argv[argpos]);
852 		if (url == NULL)
853 			errx(1, "Can't allocate memory for auto-fetch.");
854 
855 		/*
856 		 * Try HTTP URL-style arguments first.
857 		 */
858 		if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
859 #ifndef SMALL
860 		    /* even if we compiled without SSL, url_get will check */
861 		    strncasecmp(url, HTTPS_URL, sizeof(HTTPS_URL) -1) == 0 ||
862 #endif /* !SMALL */
863 		    strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
864 			redirect_loop = 0;
865 			if (url_get(url, httpproxy, outfile) == -1)
866 				rval = argpos + 1;
867 			continue;
868 		}
869 
870 		/*
871 		 * Try FTP URL-style arguments next. If ftpproxy is
872 		 * set, use url_get() instead of standard ftp.
873 		 * Finally, try host:file.
874 		 */
875 		host = url;
876 		if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
877 			char *passend, *passagain, *userend;
878 
879 			if (ftpproxy) {
880 				if (url_get(url, ftpproxy, outfile) == -1)
881 					rval = argpos + 1;
882 				continue;
883 			}
884 			host += sizeof(FTP_URL) - 1;
885 			dir = strchr(host, '/');
886 
887 			/* Look for [user:pass@]host[:port] */
888 
889 			/* check if we have "user:pass@" */
890 			userend = strchr(host, ':');
891 			passend = strchr(host, '@');
892 			if (passend && userend && userend < passend &&
893 			    (!dir || passend < dir)) {
894 				username = host;
895 				pass = userend + 1;
896 				host = passend + 1;
897 				*userend = *passend = '\0';
898 				passagain = strchr(host, '@');
899 				if (strchr(pass, '@') != NULL ||
900 				    (passagain != NULL && passagain < dir)) {
901 					warnx(at_encoding_warning);
902 					goto bad_ftp_url;
903 				}
904 
905 				if (EMPTYSTRING(username)) {
906 bad_ftp_url:
907 					warnx("Invalid URL: %s", argv[argpos]);
908 					rval = argpos + 1;
909 					continue;
910 				}
911 				username = urldecode(username);
912 				pass = urldecode(pass);
913 			}
914 
915 #ifdef INET6
916 			/* check [host]:port, or [host] */
917 			if (host[0] == '[') {
918 				cp = strchr(host, ']');
919 				if (cp && (!dir || cp < dir)) {
920 					if (cp + 1 == dir || cp[1] == ':') {
921 						host++;
922 						*cp++ = '\0';
923 					} else
924 						cp = NULL;
925 				} else
926 					cp = host;
927 			} else
928 				cp = host;
929 #else
930 			cp = host;
931 #endif
932 
933 			/* split off host[:port] if there is */
934 			if (cp) {
935 				portnum = strchr(cp, ':');
936 				pathstart = strchr(cp, '/');
937 				/* : in path is not a port # indicator */
938 				if (portnum && pathstart &&
939 				    pathstart < portnum)
940 					portnum = NULL;
941 
942 				if (!portnum)
943 					;
944 				else {
945 					if (!dir)
946 						;
947 					else if (portnum + 1 < dir) {
948 						*portnum++ = '\0';
949 						/*
950 						 * XXX should check if portnum
951 						 * is decimal number
952 						 */
953 					} else {
954 						/* empty portnum */
955 						goto bad_ftp_url;
956 					}
957 				}
958 			} else
959 				portnum = NULL;
960 		} else {			/* classic style `host:file' */
961 			dir = strchr(host, ':');
962 		}
963 		if (EMPTYSTRING(host)) {
964 			rval = argpos + 1;
965 			continue;
966 		}
967 
968 		/*
969 		 * If dir is NULL, the file wasn't specified
970 		 * (URL looked something like ftp://host)
971 		 */
972 		if (dir != NULL)
973 			*dir++ = '\0';
974 
975 		/*
976 		 * Extract the file and (if present) directory name.
977 		 */
978 		if (!EMPTYSTRING(dir)) {
979 			cp = strrchr(dir, '/');
980 			if (cp != NULL) {
981 				*cp++ = '\0';
982 				file = cp;
983 			} else {
984 				file = dir;
985 				dir = NULL;
986 			}
987 		}
988 #ifndef SMALL
989 		if (debug)
990 			fprintf(ttyout,
991 			    "user %s:%s host %s port %s dir %s file %s\n",
992 			    username, pass ? "XXXX" : NULL, host, portnum,
993 			    dir, file);
994 #endif /* !SMALL */
995 
996 		/*
997 		 * Set up the connection.
998 		 */
999 		if (connected)
1000 			disconnect(0, NULL);
1001 		xargv[0] = __progname;
1002 		xargv[1] = host;
1003 		xargv[2] = NULL;
1004 		xargc = 2;
1005 		if (!EMPTYSTRING(portnum)) {
1006 			xargv[2] = portnum;
1007 			xargv[3] = NULL;
1008 			xargc = 3;
1009 		}
1010 		oautologin = autologin;
1011 		if (username != NULL)
1012 			autologin = 0;
1013 		setpeer(xargc, xargv);
1014 		autologin = oautologin;
1015 		if ((connected == 0) ||
1016 		    ((connected == 1) && !ftp_login(host, username, pass))) {
1017 			warnx("Can't connect or login to host `%s'", host);
1018 			rval = argpos + 1;
1019 			continue;
1020 		}
1021 
1022 		/* Always use binary transfers. */
1023 		setbinary(0, NULL);
1024 
1025 		dirhasglob = filehasglob = 0;
1026 		if (doglob) {
1027 			if (!EMPTYSTRING(dir) &&
1028 			    strpbrk(dir, "*?[]{}") != NULL)
1029 				dirhasglob = 1;
1030 			if (!EMPTYSTRING(file) &&
1031 			    strpbrk(file, "*?[]{}") != NULL)
1032 				filehasglob = 1;
1033 		}
1034 
1035 		/* Change directories, if necessary. */
1036 		if (!EMPTYSTRING(dir) && !dirhasglob) {
1037 			xargv[0] = "cd";
1038 			xargv[1] = dir;
1039 			xargv[2] = NULL;
1040 			cd(2, xargv);
1041 			if (!dirchange) {
1042 				rval = argpos + 1;
1043 				continue;
1044 			}
1045 		}
1046 
1047 		if (EMPTYSTRING(file)) {
1048 			rval = -1;
1049 			continue;
1050 		}
1051 
1052 		if (verbose)
1053 			fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file);
1054 
1055 		if (dirhasglob) {
1056 			snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
1057 			file = rempath;
1058 		}
1059 
1060 		/* Fetch the file(s). */
1061 		xargc = 2;
1062 		xargv[0] = "get";
1063 		xargv[1] = file;
1064 		xargv[2] = NULL;
1065 		if (dirhasglob || filehasglob) {
1066 			int ointeractive;
1067 
1068 			ointeractive = interactive;
1069 			interactive = 0;
1070 			xargv[0] = "mget";
1071 #ifndef SMALL
1072 			if (resume) {
1073 				xargc = 3;
1074 				xargv[1] = "-c";
1075 				xargv[2] = file;
1076 				xargv[3] = NULL;
1077 			}
1078 #endif /* !SMALL */
1079 			mget(xargc, xargv);
1080 			interactive = ointeractive;
1081 		} else {
1082 			if (outfile != NULL) {
1083 				xargv[2] = outfile;
1084 				xargv[3] = NULL;
1085 				xargc++;
1086 			}
1087 #ifndef SMALL
1088 			if (resume)
1089 				reget(xargc, xargv);
1090 			else
1091 #endif /* !SMALL */
1092 				get(xargc, xargv);
1093 		}
1094 
1095 		if ((code / 100) != COMPLETE)
1096 			rval = argpos + 1;
1097 	}
1098 	if (connected && rval != -1)
1099 		disconnect(0, NULL);
1100 	return (rval);
1101 }
1102 
1103 char *
1104 urldecode(const char *str)
1105 {
1106 	char *ret, c;
1107 	int i, reallen;
1108 
1109 	if (str == NULL)
1110 		return NULL;
1111 	if ((ret = malloc(strlen(str)+1)) == NULL)
1112 		err(1, "Can't allocate memory for URL decoding");
1113 	for (i = 0, reallen = 0; str[i] != '\0'; i++, reallen++, ret++) {
1114 		c = str[i];
1115 		if (c == '+') {
1116 			*ret = ' ';
1117 			continue;
1118 		}
1119 
1120 		/* Cannot use strtol here because next char
1121 		 * after %xx may be a digit.
1122 		 */
1123 		if (c == '%' && isxdigit(str[i+1]) && isxdigit(str[i+2])) {
1124 			*ret = hextochar(&str[i+1]);
1125 			i+=2;
1126 			continue;
1127 		}
1128 		*ret = c;
1129 	}
1130 	*ret = '\0';
1131 
1132 	return ret-reallen;
1133 }
1134 
1135 char
1136 hextochar(const char *str)
1137 {
1138 	char c, ret;
1139 
1140 	c = str[0];
1141 	ret = c;
1142 	if (isalpha(c))
1143 		ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
1144 	else
1145 		ret -= '0';
1146 	ret *= 16;
1147 
1148 	c = str[1];
1149 	ret += c;
1150 	if (isalpha(c))
1151 		ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
1152 	else
1153 		ret -= '0';
1154 	return ret;
1155 }
1156 
1157 int
1158 isurl(const char *p)
1159 {
1160 
1161 	if (strncasecmp(p, FTP_URL, sizeof(FTP_URL) - 1) == 0 ||
1162 	    strncasecmp(p, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1163 #ifndef SMALL
1164 	    strncasecmp(p, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0 ||
1165 #endif /* !SMALL */
1166 	    strncasecmp(p, FILE_URL, sizeof(FILE_URL) - 1) == 0 ||
1167 	    strstr(p, ":/"))
1168 		return (1);
1169 	return (0);
1170 }
1171 
1172 char *
1173 ftp_readline(FILE *fp, SSL *ssl, size_t *lenp)
1174 {
1175 	if (fp != NULL)
1176 		return fparseln(fp, lenp, NULL, "\0\0\0", 0);
1177 #ifndef SMALL
1178 	else if (ssl != NULL)
1179 		return SSL_readline(ssl, lenp);
1180 #endif /* !SMALL */
1181 	else
1182 		return NULL;
1183 }
1184 
1185 size_t
1186 ftp_read(FILE *fp, SSL *ssl, char *buf, size_t len)
1187 {
1188 	size_t ret;
1189 	if (fp != NULL)
1190 		ret = fread(buf, sizeof(char), len, fp);
1191 #ifndef SMALL
1192 	else if (ssl != NULL) {
1193 		int nr;
1194 
1195 		if (len > INT_MAX)
1196 			len = INT_MAX;
1197 		if ((nr = SSL_read(ssl, buf, (int)len)) <= 0)
1198 			ret = 0;
1199 		else
1200 			ret = nr;
1201 	}
1202 #endif /* !SMALL */
1203 	else
1204 		ret = 0;
1205 	return (ret);
1206 }
1207 
1208 int
1209 ftp_printf(FILE *fp, SSL *ssl, const char *fmt, ...)
1210 {
1211 	int ret;
1212 	va_list ap;
1213 
1214 	va_start(ap, fmt);
1215 
1216 	if (fp != NULL)
1217 		ret = vfprintf(fp, fmt, ap);
1218 #ifndef SMALL
1219 	else if (ssl != NULL)
1220 		ret = SSL_vprintf((SSL*)ssl, fmt, ap);
1221 #endif /* !SMALL */
1222 	else
1223 		ret = NULL;
1224 
1225 	va_end(ap);
1226 	return (ret);
1227 }
1228 
1229 #ifndef SMALL
1230 int
1231 SSL_vprintf(SSL *ssl, const char *fmt, va_list ap)
1232 {
1233 	int ret;
1234 	char *string;
1235 
1236 	if ((ret = vasprintf(&string, fmt, ap)) == -1)
1237 		return ret;
1238 	ret = SSL_write(ssl, string, ret);
1239 	free(string);
1240 	return ret;
1241 }
1242 
1243 char *
1244 SSL_readline(SSL *ssl, size_t *lenp)
1245 {
1246 	size_t i, len;
1247 	char *buf, *q, c;
1248 
1249 	len = 128;
1250 	if ((buf = malloc(len)) == NULL)
1251 		errx(1, "Can't allocate memory for transfer buffer");
1252 	for (i = 0; ; i++) {
1253 		if (i >= len - 1) {
1254 			if ((q = realloc(buf, 2 * len)) == NULL)
1255 				errx(1, "Can't expand transfer buffer");
1256 			buf = q;
1257 			len *= 2;
1258 		}
1259 		if (SSL_read(ssl, &c, 1) <= 0)
1260 			break;
1261 		buf[i] = c;
1262 		if (c == '\n')
1263 			break;
1264 	}
1265 	*lenp = i;
1266 	return (buf);
1267 }
1268 
1269 int
1270 proxy_connect(int socket, char *host, char *cookie)
1271 {
1272 	int l;
1273 	char buf[1024];
1274 	char *connstr, *hosttail, *port;
1275 
1276 	if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
1277 		(hosttail[1] == '\0' || hosttail[1] == ':')) {
1278 		host++;
1279 		*hosttail++ = '\0';
1280 	} else
1281 		hosttail = host;
1282 
1283 	port = strrchr(hosttail, ':');               /* find portnum */
1284 	if (port != NULL)
1285 		*port++ = '\0';
1286 	if (!port)
1287 		port = "443";
1288 
1289 	if (cookie) {
1290 		l = asprintf(&connstr, "CONNECT %s:%s HTTP/1.1\r\n"
1291 			"Proxy-Authorization: Basic %s\r\n%s\r\n\r\n",
1292 			host, port, cookie, HTTP_USER_AGENT);
1293 	} else {
1294 		l = asprintf(&connstr, "CONNECT %s:%s HTTP/1.1\r\n%s\r\n\r\n",
1295 			host, port, HTTP_USER_AGENT);
1296 	}
1297 
1298 	if (l == -1)
1299 		errx(1, "Could not allocate memory to assemble connect string!");
1300 #ifndef SMALL
1301 	if (debug)
1302 		printf("%s", connstr);
1303 #endif /* !SMALL */
1304 	if (write(socket, connstr, l) != l)
1305 		err(1, "Could not send connect string");
1306 	read(socket, &buf, sizeof(buf)); /* only proxy header XXX: error handling? */
1307 	free(connstr);
1308 	return(200);
1309 }
1310 #endif /* !SMALL */
1311