xref: /openbsd-src/usr.bin/ftp/fetch.c (revision b725ae7711052a2233e31a66fefb8a752c388d7a)
1 /*	$OpenBSD: fetch.c,v 1.49 2004/02/28 20:08:38 krw 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  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *        This product includes software developed by the NetBSD
22  *        Foundation, Inc. and its contributors.
23  * 4. Neither the name of The NetBSD Foundation nor the names of its
24  *    contributors may be used to endorse or promote products derived
25  *    from this software without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGE.
38  */
39 
40 #if !defined(lint) && !defined(SMALL)
41 static char rcsid[] = "$OpenBSD: fetch.c,v 1.49 2004/02/28 20:08:38 krw Exp $";
42 #endif /* not lint and not SMALL */
43 
44 /*
45  * FTP User Program -- Command line file retrieval
46  */
47 
48 #include <sys/types.h>
49 #include <sys/param.h>
50 #include <sys/socket.h>
51 #include <sys/stat.h>
52 
53 #include <netinet/in.h>
54 
55 #include <arpa/ftp.h>
56 #include <arpa/inet.h>
57 
58 #include <ctype.h>
59 #include <err.h>
60 #include <libgen.h>
61 #include <netdb.h>
62 #include <fcntl.h>
63 #include <signal.h>
64 #include <stdio.h>
65 #include <errno.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <unistd.h>
69 #include <util.h>
70 
71 #include "ftp_var.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 
79 #define	FTP_URL		"ftp://"	/* ftp URL prefix */
80 #define	HTTP_URL	"http://"	/* http URL prefix */
81 #define	FILE_URL	"file:"		/* file URL prefix */
82 #define FTP_PROXY	"ftp_proxy"	/* env var with ftp proxy location */
83 #define HTTP_PROXY	"http_proxy"	/* env var with http proxy location */
84 
85 
86 #define EMPTYSTRING(x)	((x) == NULL || (*(x) == '\0'))
87 
88 static const char *at_encoding_warning =
89    "Extra `@' characters in usernames and passwords should be encoded as %%40";
90 
91 jmp_buf	httpabort;
92 
93 /*
94  * Retrieve URL, via the proxy in $proxyvar if necessary.
95  * Modifies the string argument given.
96  * Returns -1 on failure, 0 on success
97  */
98 static int
99 url_get(origline, proxyenv, outfile)
100 	const char *origline;
101 	const char *proxyenv;
102 	const char *outfile;
103 {
104 	struct addrinfo hints, *res0, *res;
105 	int error;
106 	int i, isftpurl, isfileurl, isredirect;
107 	volatile int s, out;
108 	size_t len;
109 	char *cp, *ep, *portnum, *path;
110 	char pbuf[NI_MAXSERV], hbuf[NI_MAXHOST];
111 	const char * volatile savefile;
112 	char *line, *host, *port, *buf;
113 	char * volatile proxy;
114 	char *hosttail;
115 	volatile sig_t oldintr;
116 	off_t hashbytes;
117 	char *cause = "unknown";
118 	FILE *fin;
119 	int rval;
120 
121 	s = -1;
122 	proxy = NULL;
123 	fin = NULL;
124 	buf = NULL;
125 	isftpurl = 0;
126 	isfileurl = 0;
127 	isredirect = 0;
128 	rval = -1;
129 
130 	line = strdup(origline);
131 	if (line == NULL)
132 		errx(1, "Can't allocate memory to parse URL");
133 	if (strncasecmp(line, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
134 		host = line + sizeof(HTTP_URL) - 1;
135 	else if (strncasecmp(line, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
136 		host = line + sizeof(FTP_URL) - 1;
137 		isftpurl = 1;
138 	} else if (strncasecmp(line, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
139 		host = line + sizeof(FILE_URL) - 1;
140 		isfileurl = 1;
141 	} else
142 		errx(1, "url_get: Invalid URL '%s'", line);
143 
144 	if (isfileurl) {
145 		path = host;
146 	} else {
147 		path = strchr(host, '/');		/* find path */
148 		if (EMPTYSTRING(path)) {
149 			if (isftpurl)
150 				goto noftpautologin;
151 			warnx("Invalid URL (no `/' after host): %s", origline);
152 			goto cleanup_url_get;
153 		}
154 		*path++ = '\0';
155 		if (EMPTYSTRING(path)) {
156 			if (isftpurl)
157 				goto noftpautologin;
158 			warnx("Invalid URL (no file after host): %s", origline);
159 			goto cleanup_url_get;
160 		}
161 	}
162 
163 	if (outfile)
164 		savefile = outfile;
165 	else
166 		savefile = basename(path);
167 
168 	if (EMPTYSTRING(savefile)) {
169 		if (isftpurl)
170 			goto noftpautologin;
171 		warnx("Invalid URL (no file after directory): %s", origline);
172 		goto cleanup_url_get;
173 	}
174 
175 	if (proxyenv != NULL) {				/* use proxy */
176 		proxy = strdup(proxyenv);
177 		if (proxy == NULL)
178 			errx(1, "Can't allocate memory for proxy URL.");
179 		if (strncasecmp(proxy, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
180 			host = proxy + sizeof(HTTP_URL) - 1;
181 		else if (strncasecmp(proxy, FTP_URL, sizeof(FTP_URL) - 1) == 0)
182 			host = proxy + sizeof(FTP_URL) - 1;
183 		else {
184 			warnx("Malformed proxy URL: %s", proxyenv);
185 			goto cleanup_url_get;
186 		}
187 		if (EMPTYSTRING(host)) {
188 			warnx("Malformed proxy URL: %s", proxyenv);
189 			goto cleanup_url_get;
190 		}
191 		*--path = '/';			/* add / back to real path */
192 		path = strchr(host, '/');	/* remove trailing / on host */
193 		if (!EMPTYSTRING(path))
194 			*path++ = '\0';
195 		path = line;
196 	}
197 
198 	if (isfileurl) {
199 		struct stat st;
200 
201 		s = open(path, O_RDONLY);
202 		if (s == -1) {
203 			warn("Can't open file %s", path);
204 			goto cleanup_url_get;
205 		}
206 
207 		if (fstat(s, &st) == -1)
208 			filesize = -1;
209 		else
210 			filesize = st.st_size;
211 
212 		/* Open the output file.  */
213 		if (strcmp(savefile, "-") != 0) {
214 			out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
215 			if (out < 0) {
216 				warn("Can't open %s", savefile);
217 				goto cleanup_url_get;
218 			}
219 		} else
220 			out = fileno(stdout);
221 
222 		/* Trap signals */
223 		oldintr = NULL;
224 		if (setjmp(httpabort)) {
225 			if (oldintr)
226 				(void)signal(SIGINT, oldintr);
227 			goto cleanup_url_get;
228 		}
229 		oldintr = signal(SIGINT, abortfile);
230 
231 		bytes = 0;
232 		hashbytes = mark;
233 		progressmeter(-1);
234 
235 		if ((buf = malloc(4096)) == NULL)
236 			errx(1, "Can't allocate memory for transfer buffer");
237 
238 		/* Finally, suck down the file. */
239 		i = 0;
240 		while ((len = read(s, buf, 4096)) > 0) {
241 			bytes += len;
242 			for (cp = buf; len > 0; len -= i, cp += i) {
243 				if ((i = write(out, cp, len)) == -1) {
244 					warn("Writing %s", savefile);
245 					goto cleanup_url_get;
246 				}
247 				else if (i == 0)
248 					break;
249 			}
250 			if (hash && !progress) {
251 				while (bytes >= hashbytes) {
252 					(void)putc('#', ttyout);
253 					hashbytes += mark;
254 				}
255 				(void)fflush(ttyout);
256 			}
257 		}
258 		if (hash && !progress && bytes > 0) {
259 			if (bytes < mark)
260 				(void)putc('#', ttyout);
261 			(void)putc('\n', ttyout);
262 			(void)fflush(ttyout);
263 		}
264 		if (len != 0) {
265 			warn("Reading from file");
266 			goto cleanup_url_get;
267 		}
268 		progressmeter(1);
269 		if (verbose)
270 			fputs("Successfully retrieved file.\n", ttyout);
271 		(void)signal(SIGINT, oldintr);
272 
273 		rval = 0;
274 		goto cleanup_url_get;
275 	}
276 
277 	if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
278 	    (hosttail[1] == '\0' || hosttail[1] == ':')) {
279 		host++;
280 		*hosttail++ = '\0';
281 	} else
282 		hosttail = host;
283 
284 	portnum = strrchr(hosttail, ':');		/* find portnum */
285 	if (portnum != NULL)
286 		*portnum++ = '\0';
287 
288 	if (debug)
289 		fprintf(ttyout, "host %s, port %s, path %s, save as %s.\n",
290 		    host, portnum, path, savefile);
291 
292 	memset(&hints, 0, sizeof(hints));
293 	hints.ai_family = family;
294 	hints.ai_socktype = SOCK_STREAM;
295 	port = portnum ? portnum : httpport;
296 	error = getaddrinfo(host, port, &hints, &res0);
297 	if (error == EAI_SERVICE && port == httpport) {
298 		/*
299 		 * If the services file is corrupt/missing, fall back
300 		 * on our hard-coded defines.
301 		 */
302 		snprintf(pbuf, sizeof(pbuf), "%d", HTTP_PORT);
303 		error = getaddrinfo(host, pbuf, &hints, &res0);
304 	}
305 	if (error) {
306 		warnx("%s: %s", gai_strerror(error), host);
307 		goto cleanup_url_get;
308 	}
309 
310 	s = -1;
311 	for (res = res0; res; res = res->ai_next) {
312 		if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
313 		    sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0)
314 			strlcpy(hbuf, "(unknown)", sizeof(hbuf));
315 		if (verbose)
316 			fprintf(ttyout, "Trying %s...\n", hbuf);
317 
318 		s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
319 		if (s == -1) {
320 			cause = "socket";
321 			continue;
322 		}
323 
324 again:
325 		if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
326 			if (errno == EINTR)
327 				goto again;
328 			close(s);
329 			s = -1;
330 			cause = "connect";
331 			continue;
332 		}
333 
334 		/* get port in numeric */
335 		if (getnameinfo(res->ai_addr, res->ai_addrlen, NULL, 0,
336 		    pbuf, sizeof(pbuf), NI_NUMERICSERV) == 0)
337 			port = pbuf;
338 		else
339 			port = NULL;
340 
341 		break;
342 	}
343 	freeaddrinfo(res0);
344 	if (s < 0) {
345 		warn("%s", cause);
346 		goto cleanup_url_get;
347 	}
348 
349 	fin = fdopen(s, "r+");
350 
351 	/*
352 	 * Construct and send the request. Proxy requests don't want leading /.
353 	 */
354 	if (proxy) {
355 		/*
356 		 * Host: directive must use the destination host address for
357 		 * the original URI (path).  We do not attach it at this moment.
358 		 */
359 		if (verbose)
360 			fprintf(ttyout, "Requesting %s (via %s)\n",
361 			    origline, proxyenv);
362 		fprintf(fin, "GET %s HTTP/1.0\r\n%s\r\n\r\n", path, HTTP_USER_AGENT);
363 	} else {
364 		if (verbose)
365 			fprintf(ttyout, "Requesting %s\n", origline);
366 		if (strchr(host, ':')) {
367 			char *h, *p;
368 
369 			/* strip off scoped address portion, since it's local to node */
370 			h = strdup(host);
371 			if (h == NULL)
372 				errx(1, "Can't allocate memory.");
373 			if ((p = strchr(h, '%')) != NULL)
374 				*p = '\0';
375 			/*
376 			 * Send port number only if it's specified and does not equal
377 			 * 80. Some broken HTTP servers get confused if you explicitly
378 			 * send them the port number.
379 			 */
380 			if (port && strcmp(port, "80") != 0)
381 				fprintf(fin,
382 				    "GET /%s HTTP/1.0\r\nHost: [%s]:%s\r\n%s\r\n\r\n",
383 				    path, h, port, HTTP_USER_AGENT);
384 			else
385 				fprintf(fin,
386 				    "GET /%s HTTP/1.0\r\nHost: [%s]\r\n%s\r\n\r\n",
387 				    path, h, HTTP_USER_AGENT);
388 			free(h);
389 		} else {
390 			if (port && strcmp(port, "80") != 0)
391 				fprintf(fin,
392 				    "GET /%s HTTP/1.0\r\nHost: %s:%s\r\n%s\r\n\r\n",
393 				    path, host, port, HTTP_USER_AGENT);
394 			else
395 				fprintf(fin,
396 				    "GET /%s HTTP/1.0\r\nHost: %s\r\n%s\r\n\r\n",
397 				    path, host, HTTP_USER_AGENT);
398 		}
399 	}
400 	if (fflush(fin) == EOF) {
401 		warn("Writing HTTP request");
402 		goto cleanup_url_get;
403 	}
404 
405 	if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
406 		warn("Receiving HTTP reply");
407 		goto cleanup_url_get;
408 	}
409 
410 	while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
411 		buf[--len] = '\0';
412 	if (debug)
413 		fprintf(ttyout, "received '%s'\n", buf);
414 
415 	cp = strchr(buf, ' ');
416 	if (cp == NULL)
417 		goto improper;
418 	else
419 		cp++;
420 	if (strncmp(cp, "301", 3) == 0 || strncmp(cp, "302", 3) == 0) {
421 		isredirect++;
422 	} else if (strncmp(cp, "200", 3)) {
423 		warnx("Error retrieving file: %s", cp);
424 		goto cleanup_url_get;
425 	}
426 
427 	/*
428 	 * Read the rest of the header.
429 	 */
430 	free(buf);
431 	filesize = -1;
432 
433 	while (1) {
434 		if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
435 			warn("Receiving HTTP reply");
436 			goto cleanup_url_get;
437 		}
438 		while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
439 			buf[--len] = '\0';
440 		if (len == 0)
441 			break;
442 		if (debug)
443 			fprintf(ttyout, "received '%s'\n", buf);
444 
445 		/* Look for some headers */
446 		cp = buf;
447 #define CONTENTLEN "Content-Length: "
448 		if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) {
449 			cp += sizeof(CONTENTLEN) - 1;
450 			filesize = strtol(cp, &ep, 10);
451 			if (filesize < 1 || *ep != '\0')
452 				goto improper;
453 #define LOCATION "Location: "
454 		} else if (isredirect &&
455 		    strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) {
456 			cp += sizeof(LOCATION) - 1;
457 			if (verbose)
458 				fprintf(ttyout, "Redirected to %s\n", cp);
459 			if (fin != NULL)
460 				fclose(fin);
461 			else if (s != -1)
462 				close(s);
463 			if (proxy)
464 				free(proxy);
465 			free(line);
466 			rval = url_get(cp, proxyenv, outfile);
467 			if (buf)
468 				free(buf);
469 			return (rval);
470 		}
471 	}
472 
473 	/* Open the output file.  */
474 	if (strcmp(savefile, "-") != 0) {
475 		out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
476 		if (out < 0) {
477 			warn("Can't open %s", savefile);
478 			goto cleanup_url_get;
479 		}
480 	} else
481 		out = fileno(stdout);
482 
483 	/* Trap signals */
484 	oldintr = NULL;
485 	if (setjmp(httpabort)) {
486 		if (oldintr)
487 			(void)signal(SIGINT, oldintr);
488 		goto cleanup_url_get;
489 	}
490 	oldintr = signal(SIGINT, aborthttp);
491 
492 	bytes = 0;
493 	hashbytes = mark;
494 	progressmeter(-1);
495 
496 	free(buf);
497 
498 	/* Finally, suck down the file. */
499 	if ((buf = malloc(4096)) == NULL)
500 		errx(1, "Can't allocate memory for transfer buffer");
501 	i = 0;
502 	while ((len = fread(buf, sizeof(char), 4096, fin)) > 0) {
503 		bytes += len;
504 		for (cp = buf; len > 0; len -= i, cp += i) {
505 			if ((i = write(out, cp, len)) == -1) {
506 				warn("Writing %s", savefile);
507 				goto cleanup_url_get;
508 			}
509 			else if (i == 0)
510 				break;
511 		}
512 		if (hash && !progress) {
513 			while (bytes >= hashbytes) {
514 				(void)putc('#', ttyout);
515 				hashbytes += mark;
516 			}
517 			(void)fflush(ttyout);
518 		}
519 	}
520 	if (hash && !progress && bytes > 0) {
521 		if (bytes < mark)
522 			(void)putc('#', ttyout);
523 		(void)putc('\n', ttyout);
524 		(void)fflush(ttyout);
525 	}
526 	if (len != 0) {
527 		warn("Reading from socket");
528 		goto cleanup_url_get;
529 	}
530 	progressmeter(1);
531 	if (filesize != -1 && len == 0 && bytes != filesize) {
532 		if (verbose)
533 			fputs("Read short file.\n", ttyout);
534 		goto cleanup_url_get;
535 	}
536 
537 	if (verbose)
538 		fputs("Successfully retrieved file.\n", ttyout);
539 	(void)signal(SIGINT, oldintr);
540 
541 	rval = 0;
542 	goto cleanup_url_get;
543 
544 noftpautologin:
545 	warnx(
546 	    "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
547 	goto cleanup_url_get;
548 
549 improper:
550 	warnx("Improper response from %s", host);
551 
552 cleanup_url_get:
553 	if (fin != NULL)
554 		fclose(fin);
555 	else if (s != -1)
556 		close(s);
557 	if (buf)
558 		free(buf);
559 	if (proxy)
560 		free(proxy);
561 	free(line);
562 	return (rval);
563 }
564 
565 /*
566  * Abort a http retrieval
567  */
568 void
569 aborthttp(notused)
570 	int notused;
571 {
572 
573 	alarmtimer(0);
574 	fputs("\nhttp fetch aborted.\n", ttyout);
575 	(void)fflush(ttyout);
576 	longjmp(httpabort, 1);
577 }
578 
579 /*
580  * Abort a http retrieval
581  */
582 void
583 abortfile(notused)
584 	int notused;
585 {
586 
587 	alarmtimer(0);
588 	fputs("\nfile fetch aborted.\n", ttyout);
589 	(void)fflush(ttyout);
590 	longjmp(httpabort, 1);
591 }
592 
593 /*
594  * Retrieve multiple files from the command line, transferring
595  * files of the form "host:path", "ftp://host/path" using the
596  * ftp protocol, and files of the form "http://host/path" using
597  * the http protocol.
598  * If path has a trailing "/", then return (-1);
599  * the path will be cd-ed into and the connection remains open,
600  * and the function will return -1 (to indicate the connection
601  * is alive).
602  * If an error occurs the return value will be the offset+1 in
603  * argv[] of the file that caused a problem (i.e, argv[x]
604  * returns x+1)
605  * Otherwise, 0 is returned if all files retrieved successfully.
606  */
607 int
608 auto_fetch(argc, argv, outfile)
609 	int argc;
610 	char *argv[];
611 	char *outfile;
612 {
613 	char *xargv[5];
614 	char *cp, *line, *host, *dir, *file, *portnum;
615 	char *user, *pass;
616 	char *ftpproxy, *httpproxy;
617 	int rval, xargc;
618 	volatile int argpos;
619 	int dirhasglob, filehasglob, oautologin;
620 	char rempath[MAXPATHLEN];
621 
622 	argpos = 0;
623 
624 	if (setjmp(toplevel)) {
625 		if (connected)
626 			disconnect(0, NULL);
627 		return (argpos + 1);
628 	}
629 	(void)signal(SIGINT, (sig_t)intr);
630 	(void)signal(SIGPIPE, (sig_t)lostpeer);
631 
632 	if ((ftpproxy = getenv(FTP_PROXY)) != NULL && *ftpproxy == '\0')
633 		ftpproxy = NULL;
634 	if ((httpproxy = getenv(HTTP_PROXY)) != NULL && *httpproxy == '\0')
635 		httpproxy = NULL;
636 
637 	/*
638 	 * Loop through as long as there's files to fetch.
639 	 */
640 	for (rval = 0; (rval == 0) && (argpos < argc); free(line), argpos++) {
641 		if (strchr(argv[argpos], ':') == NULL)
642 			break;
643 		host = dir = file = portnum = user = pass = NULL;
644 
645 		/*
646 		 * We muck with the string, so we make a copy.
647 		 */
648 		line = strdup(argv[argpos]);
649 		if (line == NULL)
650 			errx(1, "Can't allocate memory for auto-fetch.");
651 
652 		/*
653 		 * Try HTTP URL-style arguments first.
654 		 */
655 		if (strncasecmp(line, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
656 		    strncasecmp(line, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
657 			if (url_get(line, httpproxy, outfile) == -1)
658 				rval = argpos + 1;
659 			continue;
660 		}
661 
662 		/*
663 		 * Try FTP URL-style arguments next. If ftpproxy is
664 		 * set, use url_get() instead of standard ftp.
665 		 * Finally, try host:file.
666 		 */
667 		host = line;
668 		if (strncasecmp(line, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
669 			char *passend, *passagain, *userend;
670 
671 			if (ftpproxy) {
672 				if (url_get(line, ftpproxy, outfile) == -1)
673 					rval = argpos + 1;
674 				continue;
675 			}
676 			host += sizeof(FTP_URL) - 1;
677 			dir = strchr(host, '/');
678 
679 			/* Look for [user:pass@]host[:port] */
680 
681 			/* check if we have "user:pass@" */
682 			userend = strchr(host, ':');
683 			passend = strchr(host, '@');
684 			if (passend && userend && userend < passend &&
685 			    (!dir || passend < dir)) {
686 				user = host;
687 				pass = userend + 1;
688 				host = passend + 1;
689 				*userend = *passend = '\0';
690 				passagain = strchr(host, '@');
691 				if (strchr(pass, '@') != NULL ||
692 				    (passagain != NULL && passagain < dir)) {
693 					warnx(at_encoding_warning);
694 					goto bad_ftp_url;
695 				}
696 
697 				if (EMPTYSTRING(user) || EMPTYSTRING(pass)) {
698 bad_ftp_url:
699 					warnx("Invalid URL: %s", argv[argpos]);
700 					rval = argpos + 1;
701 					continue;
702 				}
703 				user = urldecode(user);
704 				pass = urldecode(pass);
705 			}
706 
707 #ifdef INET6
708 			/* check [host]:port, or [host] */
709 			if (host[0] == '[') {
710 				cp = strchr(host, ']');
711 				if (cp && (!dir || cp < dir)) {
712 					if (cp + 1 == dir || cp[1] == ':') {
713 						host++;
714 						*cp++ = '\0';
715 					} else
716 						cp = NULL;
717 				} else
718 					cp = host;
719 			} else
720 				cp = host;
721 #else
722 			cp = host;
723 #endif
724 
725 			/* split off host[:port] if there is */
726 			if (cp) {
727 				portnum = strchr(cp, ':');
728 				if (!portnum)
729 					;
730 				else {
731 					if (!dir)
732 						;
733 					else if (portnum + 1 < dir) {
734 						*portnum++ = '\0';
735 						/*
736 						 * XXX should check if portnum
737 						 * is decimal number
738 						 */
739 					} else {
740 						/* empty portnum */
741 						goto bad_ftp_url;
742 					}
743 				}
744 			} else
745 				portnum = NULL;
746 		} else {			/* classic style `host:file' */
747 			dir = strchr(host, ':');
748 		}
749 		if (EMPTYSTRING(host)) {
750 			rval = argpos + 1;
751 			continue;
752 		}
753 
754 		/*
755 		 * If dir is NULL, the file wasn't specified
756 		 * (URL looked something like ftp://host)
757 		 */
758 		if (dir != NULL)
759 			*dir++ = '\0';
760 
761 		/*
762 		 * Extract the file and (if present) directory name.
763 		 */
764 		if (!EMPTYSTRING(dir)) {
765 			cp = strrchr(dir, '/');
766 			if (cp != NULL) {
767 				*cp++ = '\0';
768 				file = cp;
769 			} else {
770 				file = dir;
771 				dir = NULL;
772 			}
773 		}
774 		if (debug)
775 			fprintf(ttyout,
776 			    "user %s:%s host %s port %s dir %s file %s\n",
777 			    user, pass, host, portnum, dir, file);
778 
779 		/*
780 		 * Set up the connection.
781 		 */
782 		if (connected)
783 			disconnect(0, NULL);
784 		xargv[0] = __progname;
785 		xargv[1] = host;
786 		xargv[2] = NULL;
787 		xargc = 2;
788 		if (!EMPTYSTRING(portnum)) {
789 			xargv[2] = portnum;
790 			xargv[3] = NULL;
791 			xargc = 3;
792 		}
793 		oautologin = autologin;
794 		if (user != NULL)
795 			autologin = 0;
796 		setpeer(xargc, xargv);
797 		autologin = oautologin;
798 		if ((connected == 0) ||
799 		    ((connected == 1) && !ftp_login(host, user, pass))) {
800 			warnx("Can't connect or login to host `%s'", host);
801 			rval = argpos + 1;
802 			continue;
803 		}
804 
805 		/* Always use binary transfers. */
806 		setbinary(0, NULL);
807 
808 		dirhasglob = filehasglob = 0;
809 		if (doglob) {
810 			if (!EMPTYSTRING(dir) &&
811 			    strpbrk(dir, "*?[]{}") != NULL)
812 				dirhasglob = 1;
813 			if (!EMPTYSTRING(file) &&
814 			    strpbrk(file, "*?[]{}") != NULL)
815 				filehasglob = 1;
816 		}
817 
818 		/* Change directories, if necessary. */
819 		if (!EMPTYSTRING(dir) && !dirhasglob) {
820 			xargv[0] = "cd";
821 			xargv[1] = dir;
822 			xargv[2] = NULL;
823 			cd(2, xargv);
824 			if (!dirchange) {
825 				rval = argpos + 1;
826 				continue;
827 			}
828 		}
829 
830 		if (EMPTYSTRING(file)) {
831 			rval = -1;
832 			continue;
833 		}
834 
835 		if (verbose)
836 			fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file);
837 
838 		if (dirhasglob) {
839 			snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
840 			file = rempath;
841 		}
842 
843 		/* Fetch the file(s). */
844 		xargc = 2;
845 		xargv[0] = "get";
846 		xargv[1] = file;
847 		xargv[2] = NULL;
848 		if (dirhasglob || filehasglob) {
849 			int ointeractive;
850 
851 			ointeractive = interactive;
852 			interactive = 0;
853 			xargv[0] = "mget";
854 			mget(xargc, xargv);
855 			interactive = ointeractive;
856 		} else {
857 			if (outfile != NULL) {
858 				xargv[2] = outfile;
859 				xargv[3] = NULL;
860 				xargc++;
861 			}
862 			get(xargc, xargv);
863 		}
864 
865 		if ((code / 100) != COMPLETE)
866 			rval = argpos + 1;
867 	}
868 	if (connected && rval != -1)
869 		disconnect(0, NULL);
870 	return (rval);
871 }
872 
873 char *
874 urldecode(str)
875         const char *str;
876 {
877         char *ret;
878         char c;
879         int i, reallen;
880 
881         if (str == NULL)
882                 return NULL;
883         if ((ret = malloc(strlen(str)+1)) == NULL)
884                 err(1, "Can't allocate memory for URL decoding");
885         for (i = 0, reallen = 0; str[i] != '\0'; i++, reallen++, ret++) {
886                 c = str[i];
887                 if (c == '+') {
888                         *ret = ' ';
889                         continue;
890                 }
891                 /* Can't use strtol here because next char after %xx may be
892                  * a digit. */
893                 if (c == '%' && isxdigit(str[i+1]) && isxdigit(str[i+2])) {
894                         *ret = hextochar(&str[i+1]);
895                         i+=2;
896                         continue;
897                 }
898                 *ret = c;
899         }
900         *ret = '\0';
901 
902         return ret-reallen;
903 }
904 
905 char
906 hextochar(str)
907         const char *str;
908 {
909         char c, ret;
910 
911         c = str[0];
912         ret = c;
913         if (isalpha(c))
914                 ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
915         else
916                 ret -= '0';
917         ret *= 16;
918 
919         c = str[1];
920         ret += c;
921         if (isalpha(c))
922                 ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
923         else
924                 ret -= '0';
925         return ret;
926 }
927 
928 int
929 isurl(p)
930 	const char *p;
931 {
932 
933 	if (strncasecmp(p, FTP_URL, sizeof(FTP_URL) - 1) == 0 ||
934 	    strncasecmp(p, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
935 	    strncasecmp(p, FILE_URL, sizeof(FILE_URL) - 1) == 0 ||
936 	    strstr(p, ":/"))
937 		return (1);
938 	return (0);
939 }
940