xref: /netbsd-src/usr.bin/ftp/main.c (revision 466a16a118933bd295a8a104f095714fadf9cf68)
1 /*	$NetBSD: main.c,v 1.113 2008/09/09 00:48:28 gmcgarry Exp $	*/
2 
3 /*-
4  * Copyright (c) 1996-2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Luke Mewburn.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c) 1985, 1989, 1993, 1994
34  *	The Regents of the University of California.  All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 3. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  */
60 
61 /*
62  * Copyright (C) 1997 and 1998 WIDE Project.
63  * All rights reserved.
64  *
65  * Redistribution and use in source and binary forms, with or without
66  * modification, are permitted provided that the following conditions
67  * are met:
68  * 1. Redistributions of source code must retain the above copyright
69  *    notice, this list of conditions and the following disclaimer.
70  * 2. Redistributions in binary form must reproduce the above copyright
71  *    notice, this list of conditions and the following disclaimer in the
72  *    documentation and/or other materials provided with the distribution.
73  * 3. Neither the name of the project nor the names of its contributors
74  *    may be used to endorse or promote products derived from this software
75  *    without specific prior written permission.
76  *
77  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
78  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
81  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
82  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
83  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
84  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
85  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
86  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
87  * SUCH DAMAGE.
88  */
89 
90 #include <sys/cdefs.h>
91 #ifndef lint
92 __COPYRIGHT("@(#) Copyright (c) 1985, 1989, 1993, 1994\
93  The Regents of the University of California.  All rights reserved.\
94   Copyright 1996-2008 The NetBSD Foundation, Inc.  All rights reserved");
95 #endif /* not lint */
96 
97 #ifndef lint
98 #if 0
99 static char sccsid[] = "@(#)main.c	8.6 (Berkeley) 10/9/94";
100 #else
101 __RCSID("$NetBSD: main.c,v 1.113 2008/09/09 00:48:28 gmcgarry Exp $");
102 #endif
103 #endif /* not lint */
104 
105 /*
106  * FTP User Program -- Command Interface.
107  */
108 #include <sys/types.h>
109 #include <sys/socket.h>
110 
111 #include <err.h>
112 #include <errno.h>
113 #include <netdb.h>
114 #include <paths.h>
115 #include <pwd.h>
116 #include <signal.h>
117 #include <stdio.h>
118 #include <stdlib.h>
119 #include <string.h>
120 #include <time.h>
121 #include <unistd.h>
122 #include <locale.h>
123 
124 #define	GLOBAL		/* force GLOBAL decls in ftp_var.h to be declared */
125 #include "ftp_var.h"
126 
127 #define	FTP_PROXY	"ftp_proxy"	/* env var with FTP proxy location */
128 #define	HTTP_PROXY	"http_proxy"	/* env var with HTTP proxy location */
129 #define	NO_PROXY	"no_proxy"	/* env var with list of non-proxied
130 					 * hosts, comma or space separated */
131 
132 static void	setupoption(char *, char *, char *);
133 int		main(int, char *[]);
134 
135 int
136 main(int volatile argc, char **volatile argv)
137 {
138 	int ch, rval;
139 	struct passwd *pw;
140 	char *cp, *ep, *anonuser, *anonpass, *upload_path, *src_addr;
141 	int dumbterm, s, isupload;
142 	size_t len;
143 	socklen_t slen;
144 
145 	tzset();
146 	setlocale(LC_ALL, "");
147 	setprogname(argv[0]);
148 
149 	sigint_raised = 0;
150 
151 	ftpport = "ftp";
152 	httpport = "http";
153 	gateport = NULL;
154 	cp = getenv("FTPSERVERPORT");
155 	if (cp != NULL)
156 		gateport = cp;
157 	else
158 		gateport = "ftpgate";
159 	doglob = 1;
160 	interactive = 1;
161 	autologin = 1;
162 	passivemode = 1;
163 	activefallback = 1;
164 	preserve = 1;
165 	verbose = 0;
166 	progress = 0;
167 	gatemode = 0;
168 	data = -1;
169 	outfile = NULL;
170 	restartautofetch = 0;
171 #ifndef NO_EDITCOMPLETE
172 	editing = 0;
173 	el = NULL;
174 	hist = NULL;
175 #endif
176 	bytes = 0;
177 	mark = HASHBYTES;
178 	rate_get = 0;
179 	rate_get_incr = DEFAULTINCR;
180 	rate_put = 0;
181 	rate_put_incr = DEFAULTINCR;
182 #ifdef INET6
183 	epsv4 = 1;
184 	epsv6 = 1;
185 #else
186 	epsv4 = 0;
187 	epsv6 = 0;
188 #endif
189 	epsv4bad = 0;
190 	epsv6bad = 0;
191 	src_addr = NULL;
192 	upload_path = NULL;
193 	isupload = 0;
194 	reply_callback = NULL;
195 #ifdef INET6
196 	family = AF_UNSPEC;
197 #else
198 	family = AF_INET;	/* force AF_INET if no INET6 support */
199 #endif
200 
201 	netrc[0] = '\0';
202 	cp = getenv("NETRC");
203 	if (cp != NULL && strlcpy(netrc, cp, sizeof(netrc)) >= sizeof(netrc))
204 		errx(1, "$NETRC `%s': %s", cp, strerror(ENAMETOOLONG));
205 
206 	/*
207 	 * Get the default socket buffer sizes if we don't already have them.
208 	 * It doesn't matter which socket we do this to, because on the first
209 	 * call no socket buffer sizes will have been modified, so we are
210 	 * guaranteed to get the system defaults.
211 	 */
212 	s = socket(AF_INET, SOCK_STREAM, 0);
213 	if (s == -1)
214 		err(1, "Can't create socket to determine default socket sizes");
215 	slen = sizeof(rcvbuf_size);
216 	if (getsockopt(s, SOL_SOCKET, SO_RCVBUF,
217 	    (void *)&rcvbuf_size, &slen) == -1)
218 		err(1, "Unable to get default rcvbuf size");
219 	slen = sizeof(sndbuf_size);
220 	if (getsockopt(s, SOL_SOCKET, SO_SNDBUF,
221 	    (void *)&sndbuf_size, &slen) == -1)
222 		err(1, "Unable to get default sndbuf size");
223 	(void)close(s);
224 					/* sanity check returned buffer sizes */
225 	if (rcvbuf_size <= 0)
226 		rcvbuf_size = 8 * 1024;
227 	if (sndbuf_size <= 0)
228 		sndbuf_size = 8 * 1024;
229 
230 	if (sndbuf_size > 8 * 1024 * 1024)
231 		sndbuf_size = 8 * 1024 * 1024;
232 	if (rcvbuf_size > 8 * 1024 * 1024)
233 		rcvbuf_size = 8 * 1024 * 1024;
234 
235 	marg_sl = ftp_sl_init();
236 	if ((tmpdir = getenv("TMPDIR")) == NULL)
237 		tmpdir = _PATH_TMP;
238 
239 	/* Set default operation mode based on FTPMODE environment variable */
240 	if ((cp = getenv("FTPMODE")) != NULL) {
241 		if (strcasecmp(cp, "passive") == 0) {
242 			passivemode = 1;
243 			activefallback = 0;
244 		} else if (strcasecmp(cp, "active") == 0) {
245 			passivemode = 0;
246 			activefallback = 0;
247 		} else if (strcasecmp(cp, "gate") == 0) {
248 			gatemode = 1;
249 		} else if (strcasecmp(cp, "auto") == 0) {
250 			passivemode = 1;
251 			activefallback = 1;
252 		} else
253 			warnx("Unknown $FTPMODE `%s'; using defaults", cp);
254 	}
255 
256 	if (strcmp(getprogname(), "pftp") == 0) {
257 		passivemode = 1;
258 		activefallback = 0;
259 	} else if (strcmp(getprogname(), "gate-ftp") == 0)
260 		gatemode = 1;
261 
262 	gateserver = getenv("FTPSERVER");
263 	if (gateserver == NULL || *gateserver == '\0')
264 		gateserver = GATE_SERVER;
265 	if (gatemode) {
266 		if (*gateserver == '\0') {
267 			warnx(
268 "Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp");
269 			gatemode = 0;
270 		}
271 	}
272 
273 	cp = getenv("TERM");
274 	if (cp == NULL || strcmp(cp, "dumb") == 0)
275 		dumbterm = 1;
276 	else
277 		dumbterm = 0;
278 	fromatty = isatty(fileno(stdin));
279 	ttyout = stdout;
280 	if (isatty(fileno(ttyout))) {
281 		verbose = 1;		/* verbose if to a tty */
282 		if (! dumbterm) {
283 #ifndef NO_EDITCOMPLETE
284 			if (fromatty)	/* editing mode on if tty is usable */
285 				editing = 1;
286 #endif
287 #ifndef NO_PROGRESS
288 			if (foregroundproc())
289 				progress = 1;	/* progress bar on if fg */
290 #endif
291 		}
292 	}
293 
294 	while ((ch = getopt(argc, argv, "46AadefginN:o:pP:q:r:Rs:tT:u:vV")) != -1) {
295 		switch (ch) {
296 		case '4':
297 			family = AF_INET;
298 			break;
299 
300 		case '6':
301 #ifdef INET6
302 			family = AF_INET6;
303 #else
304 			warnx("INET6 support is not available; ignoring -6");
305 #endif
306 			break;
307 
308 		case 'A':
309 			activefallback = 0;
310 			passivemode = 0;
311 			break;
312 
313 		case 'a':
314 			anonftp = 1;
315 			break;
316 
317 		case 'd':
318 			options |= SO_DEBUG;
319 			ftp_debug++;
320 			break;
321 
322 		case 'e':
323 #ifndef NO_EDITCOMPLETE
324 			editing = 0;
325 #endif
326 			break;
327 
328 		case 'f':
329 			flushcache = 1;
330 			break;
331 
332 		case 'g':
333 			doglob = 0;
334 			break;
335 
336 		case 'i':
337 			interactive = 0;
338 			break;
339 
340 		case 'n':
341 			autologin = 0;
342 			break;
343 
344 		case 'N':
345 			if (strlcpy(netrc, optarg, sizeof(netrc))
346 			    >= sizeof(netrc))
347 				errx(1, "%s: %s", optarg,
348 				    strerror(ENAMETOOLONG));
349 			break;
350 
351 		case 'o':
352 			outfile = optarg;
353 			if (strcmp(outfile, "-") == 0)
354 				ttyout = stderr;
355 			break;
356 
357 		case 'p':
358 			passivemode = 1;
359 			activefallback = 0;
360 			break;
361 
362 		case 'P':
363 			ftpport = optarg;
364 			break;
365 
366 		case 'q':
367 			quit_time = strtol(optarg, &ep, 10);
368 			if (quit_time < 1 || *ep != '\0')
369 				errx(1, "Bad quit value: %s", optarg);
370 			break;
371 
372 		case 'r':
373 			retry_connect = strtol(optarg, &ep, 10);
374 			if (retry_connect < 1 || *ep != '\0')
375 				errx(1, "Bad retry value: %s", optarg);
376 			break;
377 
378 		case 'R':
379 			restartautofetch = 1;
380 			break;
381 
382 		case 's':
383 			src_addr = optarg;
384 			break;
385 
386 		case 't':
387 			trace = 1;
388 			break;
389 
390 		case 'T':
391 		{
392 			int targc;
393 			char *targv[6], *oac;
394 
395 				/* look for `dir,max[,incr]' */
396 			targc = 0;
397 			targv[targc++] = "-T";
398 			oac = ftp_strdup(optarg);
399 
400 			while ((cp = strsep(&oac, ",")) != NULL) {
401 				if (*cp == '\0') {
402 					warnx("Bad throttle value `%s'",
403 					    optarg);
404 					usage();
405 					/* NOTREACHED */
406 				}
407 				targv[targc++] = cp;
408 				if (targc >= 5)
409 					break;
410 			}
411 			if (parserate(targc, targv, 1) == -1)
412 				usage();
413 			free(oac);
414 			break;
415 		}
416 
417 		case 'u':
418 		{
419 			isupload = 1;
420 			interactive = 0;
421 			upload_path = ftp_strdup(optarg);
422 
423 			break;
424 		}
425 
426 		case 'v':
427 			progress = verbose = 1;
428 			break;
429 
430 		case 'V':
431 			progress = verbose = 0;
432 			break;
433 
434 		default:
435 			usage();
436 		}
437 	}
438 			/* set line buffering on ttyout */
439 	setvbuf(ttyout, NULL, _IOLBF, 0);
440 	argc -= optind;
441 	argv += optind;
442 
443 	cpend = 0;	/* no pending replies */
444 	proxy = 0;	/* proxy not active */
445 	crflag = 1;	/* strip c.r. on ascii gets */
446 	sendport = -1;	/* not using ports */
447 
448 	if (src_addr != NULL) {
449 		struct addrinfo hints;
450 		int error;
451 
452 		memset(&hints, 0, sizeof(hints));
453 		hints.ai_family = family;
454 		hints.ai_socktype = SOCK_STREAM;
455 		hints.ai_flags = AI_PASSIVE;
456 		error = getaddrinfo(src_addr, NULL, &hints, &bindai);
457 		if (error) {
458 		    	errx(1, "Can't lookup `%s': %s", src_addr,
459 			    (error == EAI_SYSTEM) ? strerror(errno)
460 						  : gai_strerror(error));
461 		}
462 	}
463 
464 	/*
465 	 * Cache the user name and home directory.
466 	 */
467 	localhome = NULL;
468 	localname = NULL;
469 	anonuser = "anonymous";
470 	cp = getenv("HOME");
471 	if (! EMPTYSTRING(cp))
472 		localhome = ftp_strdup(cp);
473 	pw = NULL;
474 	cp = getlogin();
475 	if (cp != NULL)
476 		pw = getpwnam(cp);
477 	if (pw == NULL)
478 		pw = getpwuid(getuid());
479 	if (pw != NULL) {
480 		if (localhome == NULL && !EMPTYSTRING(pw->pw_dir))
481 			localhome = ftp_strdup(pw->pw_dir);
482 		localname = ftp_strdup(pw->pw_name);
483 		anonuser = localname;
484 	}
485 	if (netrc[0] == '\0' && localhome != NULL) {
486 		if (strlcpy(netrc, localhome, sizeof(netrc)) >= sizeof(netrc) ||
487 		    strlcat(netrc, "/.netrc", sizeof(netrc)) >= sizeof(netrc)) {
488 			warnx("%s/.netrc: %s", localhome,
489 			    strerror(ENAMETOOLONG));
490 			netrc[0] = '\0';
491 		}
492 	}
493 	if (localhome == NULL)
494 		localhome = ftp_strdup("/");
495 
496 	/*
497 	 * Every anonymous FTP server I've encountered will accept the
498 	 * string "username@", and will append the hostname itself. We
499 	 * do this by default since many servers are picky about not
500 	 * having a FQDN in the anonymous password.
501 	 * - thorpej@NetBSD.org
502 	 */
503 	len = strlen(anonuser) + 2;
504 	anonpass = ftp_malloc(len);
505 	(void)strlcpy(anonpass, anonuser, len);
506 	(void)strlcat(anonpass, "@",	  len);
507 
508 			/*
509 			 * set all the defaults for options defined in
510 			 * struct option optiontab[]  declared in cmdtab.c
511 			 */
512 	setupoption("anonpass",		getenv("FTPANONPASS"),	anonpass);
513 	setupoption("ftp_proxy",	getenv(FTP_PROXY),	"");
514 	setupoption("http_proxy",	getenv(HTTP_PROXY),	"");
515 	setupoption("no_proxy",		getenv(NO_PROXY),	"");
516 	setupoption("pager",		getenv("PAGER"),	DEFAULTPAGER);
517 	setupoption("prompt",		getenv("FTPPROMPT"),	DEFAULTPROMPT);
518 	setupoption("rprompt",		getenv("FTPRPROMPT"),	DEFAULTRPROMPT);
519 
520 	free(anonpass);
521 
522 	setttywidth(0);
523 #ifdef SIGINFO
524 	(void)xsignal(SIGINFO, psummary);
525 #endif
526 	(void)xsignal(SIGQUIT, psummary);
527 	(void)xsignal(SIGUSR1, crankrate);
528 	(void)xsignal(SIGUSR2, crankrate);
529 	(void)xsignal(SIGWINCH, setttywidth);
530 
531 	if (argc > 0) {
532 		if (isupload) {
533 			rval = auto_put(argc, argv, upload_path);
534  sigint_or_rval_exit:
535 			if (sigint_raised) {
536 				(void)xsignal(SIGINT, SIG_DFL);
537 				raise(SIGINT);
538 			}
539 			exit(rval);
540 		} else if (strchr(argv[0], ':') != NULL
541 			    && ! isipv6addr(argv[0])) {
542 			rval = auto_fetch(argc, argv);
543 			if (rval >= 0)		/* -1 == connected and cd-ed */
544 				goto sigint_or_rval_exit;
545 		} else {
546 			char *xargv[4], *user, *host;
547 
548 			if ((rval = sigsetjmp(toplevel, 1)))
549 				goto sigint_or_rval_exit;
550 			(void)xsignal(SIGINT, intr);
551 			(void)xsignal(SIGPIPE, lostpeer);
552 			user = NULL;
553 			host = argv[0];
554 			cp = strchr(host, '@');
555 			if (cp) {
556 				*cp = '\0';
557 				user = host;
558 				host = cp + 1;
559 			}
560 			/* XXX discards const */
561 			xargv[0] = (char *)getprogname();
562 			xargv[1] = host;
563 			xargv[2] = argv[1];
564 			xargv[3] = NULL;
565 			do {
566 				int oautologin;
567 
568 				oautologin = autologin;
569 				if (user != NULL) {
570 					anonftp = 0;
571 					autologin = 0;
572 				}
573 				setpeer(argc+1, xargv);
574 				autologin = oautologin;
575 				if (connected == 1 && user != NULL)
576 					(void)ftp_login(host, user, NULL);
577 				if (!retry_connect)
578 					break;
579 				if (!connected) {
580 					macnum = 0;
581 					fprintf(ttyout,
582 					    "Retrying in %d seconds...\n",
583 					    retry_connect);
584 					sleep(retry_connect);
585 				}
586 			} while (!connected);
587 			retry_connect = 0; /* connected, stop hiding msgs */
588 		}
589 	}
590 	if (isupload)
591 		usage();
592 
593 #ifndef NO_EDITCOMPLETE
594 	controlediting();
595 #endif /* !NO_EDITCOMPLETE */
596 
597 	(void)sigsetjmp(toplevel, 1);
598 	(void)xsignal(SIGINT, intr);
599 	(void)xsignal(SIGPIPE, lostpeer);
600 	for (;;)
601 		cmdscanner();
602 }
603 
604 /*
605  * Generate a prompt
606  */
607 char *
608 prompt(void)
609 {
610 	static char	**prompt;
611 	static char	  buf[MAXPATHLEN];
612 
613 	if (prompt == NULL) {
614 		struct option *o;
615 
616 		o = getoption("prompt");
617 		if (o == NULL)
618 			errx(1, "prompt: no such option `prompt'");
619 		prompt = &(o->value);
620 	}
621 	formatbuf(buf, sizeof(buf), *prompt ? *prompt : DEFAULTPROMPT);
622 	return (buf);
623 }
624 
625 /*
626  * Generate an rprompt
627  */
628 char *
629 rprompt(void)
630 {
631 	static char	**rprompt;
632 	static char	  buf[MAXPATHLEN];
633 
634 	if (rprompt == NULL) {
635 		struct option *o;
636 
637 		o = getoption("rprompt");
638 		if (o == NULL)
639 			errx(1, "rprompt: no such option `rprompt'");
640 		rprompt = &(o->value);
641 	}
642 	formatbuf(buf, sizeof(buf), *rprompt ? *rprompt : DEFAULTRPROMPT);
643 	return (buf);
644 }
645 
646 /*
647  * Command parser.
648  */
649 void
650 cmdscanner(void)
651 {
652 	struct cmd	*c;
653 	char		*p;
654 #ifndef NO_EDITCOMPLETE
655 	int		 ch;
656 	size_t		 num;
657 #endif
658 	int		 len;
659 
660 	for (;;) {
661 #ifndef NO_EDITCOMPLETE
662 		if (!editing) {
663 #endif /* !NO_EDITCOMPLETE */
664 			if (fromatty) {
665 				fputs(prompt(), ttyout);
666 				p = rprompt();
667 				if (*p)
668 					fprintf(ttyout, "%s ", p);
669 			}
670 			(void)fflush(ttyout);
671 			len = getline(stdin, line, sizeof(line), NULL);
672 			switch (len) {
673 			case -1:	/* EOF */
674 			case -2:	/* error */
675 				if (fromatty)
676 					putc('\n', ttyout);
677 				quit(0, NULL);
678 				/* NOTREACHED */
679 			case -3:	/* too long; try again */
680 				fputs("Sorry, input line is too long.\n",
681 				    ttyout);
682 				continue;
683 			case 0:		/* empty; try again */
684 				continue;
685 			default:	/* all ok */
686 				break;
687 			}
688 #ifndef NO_EDITCOMPLETE
689 		} else {
690 			const char *buf;
691 			HistEvent ev;
692 			cursor_pos = NULL;
693 
694 			buf = el_gets(el, &ch);
695 			num = ch;
696 			if (buf == NULL || num == 0) {
697 				if (fromatty)
698 					putc('\n', ttyout);
699 				quit(0, NULL);
700 			}
701 			if (num >= sizeof(line)) {
702 				fputs("Sorry, input line is too long.\n",
703 				    ttyout);
704 				break;
705 			}
706 			memcpy(line, buf, num);
707 			if (line[--num] == '\n') {
708 				line[num] = '\0';
709 				if (num == 0)
710 					break;
711 			}
712 			history(hist, &ev, H_ENTER, buf);
713 		}
714 #endif /* !NO_EDITCOMPLETE */
715 
716 		makeargv();
717 		if (margc == 0)
718 			continue;
719 		c = getcmd(margv[0]);
720 		if (c == (struct cmd *)-1) {
721 			fputs("?Ambiguous command.\n", ttyout);
722 			continue;
723 		}
724 		if (c == NULL) {
725 #if !defined(NO_EDITCOMPLETE)
726 			/*
727 			 * attempt to el_parse() unknown commands.
728 			 * any command containing a ':' would be parsed
729 			 * as "[prog:]cmd ...", and will result in a
730 			 * false positive if prog != "ftp", so treat
731 			 * such commands as invalid.
732 			 */
733 			if (strchr(margv[0], ':') != NULL ||
734 			    !editing ||
735 			    el_parse(el, margc, (const char **)margv) != 0)
736 #endif /* !NO_EDITCOMPLETE */
737 				fputs("?Invalid command.\n", ttyout);
738 			continue;
739 		}
740 		if (c->c_conn && !connected) {
741 			fputs("Not connected.\n", ttyout);
742 			continue;
743 		}
744 		confirmrest = 0;
745 		margv[0] = c->c_name;
746 		(*c->c_handler)(margc, margv);
747 		if (bell && c->c_bell)
748 			(void)putc('\007', ttyout);
749 		if (c->c_handler != help)
750 			break;
751 	}
752 	(void)xsignal(SIGINT, intr);
753 	(void)xsignal(SIGPIPE, lostpeer);
754 }
755 
756 struct cmd *
757 getcmd(const char *name)
758 {
759 	const char *p, *q;
760 	struct cmd *c, *found;
761 	int nmatches, longest;
762 
763 	if (name == NULL)
764 		return (0);
765 
766 	longest = 0;
767 	nmatches = 0;
768 	found = 0;
769 	for (c = cmdtab; (p = c->c_name) != NULL; c++) {
770 		for (q = name; *q == *p++; q++)
771 			if (*q == 0)		/* exact match? */
772 				return (c);
773 		if (!*q) {			/* the name was a prefix */
774 			if (q - name > longest) {
775 				longest = q - name;
776 				nmatches = 1;
777 				found = c;
778 			} else if (q - name == longest)
779 				nmatches++;
780 		}
781 	}
782 	if (nmatches > 1)
783 		return ((struct cmd *)-1);
784 	return (found);
785 }
786 
787 /*
788  * Slice a string up into argc/argv.
789  */
790 
791 int slrflag;
792 
793 void
794 makeargv(void)
795 {
796 	char *argp;
797 
798 	stringbase = line;		/* scan from first of buffer */
799 	argbase = argbuf;		/* store from first of buffer */
800 	slrflag = 0;
801 	marg_sl->sl_cur = 0;		/* reset to start of marg_sl */
802 	for (margc = 0; ; margc++) {
803 		argp = slurpstring();
804 		ftp_sl_add(marg_sl, argp);
805 		if (argp == NULL)
806 			break;
807 	}
808 #ifndef NO_EDITCOMPLETE
809 	if (cursor_pos == line) {
810 		cursor_argc = 0;
811 		cursor_argo = 0;
812 	} else if (cursor_pos != NULL) {
813 		cursor_argc = margc;
814 		cursor_argo = strlen(margv[margc-1]);
815 	}
816 #endif /* !NO_EDITCOMPLETE */
817 }
818 
819 #ifdef NO_EDITCOMPLETE
820 #define	INC_CHKCURSOR(x)	(x)++
821 #else  /* !NO_EDITCOMPLETE */
822 #define	INC_CHKCURSOR(x)	{ (x)++ ; \
823 				if (x == cursor_pos) { \
824 					cursor_argc = margc; \
825 					cursor_argo = ap-argbase; \
826 					cursor_pos = NULL; \
827 				} }
828 
829 #endif /* !NO_EDITCOMPLETE */
830 
831 /*
832  * Parse string into argbuf;
833  * implemented with FSM to
834  * handle quoting and strings
835  */
836 char *
837 slurpstring(void)
838 {
839 	int got_one = 0;
840 	char *sb = stringbase;
841 	char *ap = argbase;
842 	char *tmp = argbase;		/* will return this if token found */
843 
844 	if (*sb == '!' || *sb == '$') {	/* recognize ! as a token for shell */
845 		switch (slrflag) {	/* and $ as token for macro invoke */
846 			case 0:
847 				slrflag++;
848 				INC_CHKCURSOR(stringbase);
849 				return ((*sb == '!') ? "!" : "$");
850 				/* NOTREACHED */
851 			case 1:
852 				slrflag++;
853 				altarg = stringbase;
854 				break;
855 			default:
856 				break;
857 		}
858 	}
859 
860 S0:
861 	switch (*sb) {
862 
863 	case '\0':
864 		goto OUT;
865 
866 	case ' ':
867 	case '\t':
868 		INC_CHKCURSOR(sb);
869 		goto S0;
870 
871 	default:
872 		switch (slrflag) {
873 			case 0:
874 				slrflag++;
875 				break;
876 			case 1:
877 				slrflag++;
878 				altarg = sb;
879 				break;
880 			default:
881 				break;
882 		}
883 		goto S1;
884 	}
885 
886 S1:
887 	switch (*sb) {
888 
889 	case ' ':
890 	case '\t':
891 	case '\0':
892 		goto OUT;	/* end of token */
893 
894 	case '\\':
895 		INC_CHKCURSOR(sb);
896 		goto S2;	/* slurp next character */
897 
898 	case '"':
899 		INC_CHKCURSOR(sb);
900 		goto S3;	/* slurp quoted string */
901 
902 	default:
903 		*ap = *sb;	/* add character to token */
904 		ap++;
905 		INC_CHKCURSOR(sb);
906 		got_one = 1;
907 		goto S1;
908 	}
909 
910 S2:
911 	switch (*sb) {
912 
913 	case '\0':
914 		goto OUT;
915 
916 	default:
917 		*ap = *sb;
918 		ap++;
919 		INC_CHKCURSOR(sb);
920 		got_one = 1;
921 		goto S1;
922 	}
923 
924 S3:
925 	switch (*sb) {
926 
927 	case '\0':
928 		goto OUT;
929 
930 	case '"':
931 		INC_CHKCURSOR(sb);
932 		goto S1;
933 
934 	default:
935 		*ap = *sb;
936 		ap++;
937 		INC_CHKCURSOR(sb);
938 		got_one = 1;
939 		goto S3;
940 	}
941 
942 OUT:
943 	if (got_one)
944 		*ap++ = '\0';
945 	argbase = ap;			/* update storage pointer */
946 	stringbase = sb;		/* update scan pointer */
947 	if (got_one) {
948 		return (tmp);
949 	}
950 	switch (slrflag) {
951 		case 0:
952 			slrflag++;
953 			break;
954 		case 1:
955 			slrflag++;
956 			altarg = NULL;
957 			break;
958 		default:
959 			break;
960 	}
961 	return (NULL);
962 }
963 
964 /*
965  * Help/usage command.
966  * Call each command handler with argc == 0 and argv[0] == name.
967  */
968 void
969 help(int argc, char *argv[])
970 {
971 	struct cmd *c;
972 	char *nargv[1], *p, *cmd;
973 	int isusage;
974 
975 	cmd = argv[0];
976 	isusage = (strcmp(cmd, "usage") == 0);
977 	if (argc == 0 || (isusage && argc == 1)) {
978 		UPRINTF("usage: %s [command [...]]\n", cmd);
979 		return;
980 	}
981 	if (argc == 1) {
982 		StringList *buf;
983 
984 		buf = ftp_sl_init();
985 		fprintf(ttyout,
986 		    "%sommands may be abbreviated.  Commands are:\n\n",
987 		    proxy ? "Proxy c" : "C");
988 		for (c = cmdtab; (p = c->c_name) != NULL; c++)
989 			if (!proxy || c->c_proxy)
990 				ftp_sl_add(buf, p);
991 		list_vertical(buf);
992 		sl_free(buf, 0);
993 		return;
994 	}
995 
996 #define	HELPINDENT ((int) sizeof("disconnect"))
997 
998 	while (--argc > 0) {
999 		char *arg;
1000 
1001 		arg = *++argv;
1002 		c = getcmd(arg);
1003 		if (c == (struct cmd *)-1)
1004 			fprintf(ttyout, "?Ambiguous %s command `%s'\n",
1005 			    cmd, arg);
1006 		else if (c == NULL)
1007 			fprintf(ttyout, "?Invalid %s command `%s'\n",
1008 			    cmd, arg);
1009 		else {
1010 			if (isusage) {
1011 				nargv[0] = c->c_name;
1012 				(*c->c_handler)(0, nargv);
1013 			} else
1014 				fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
1015 				    c->c_name, c->c_help);
1016 		}
1017 	}
1018 }
1019 
1020 struct option *
1021 getoption(const char *name)
1022 {
1023 	const char *p;
1024 	struct option *c;
1025 
1026 	if (name == NULL)
1027 		return (NULL);
1028 	for (c = optiontab; (p = c->name) != NULL; c++) {
1029 		if (strcasecmp(p, name) == 0)
1030 			return (c);
1031 	}
1032 	return (NULL);
1033 }
1034 
1035 char *
1036 getoptionvalue(const char *name)
1037 {
1038 	struct option *c;
1039 
1040 	if (name == NULL)
1041 		errx(1, "getoptionvalue: invoked with NULL name");
1042 	c = getoption(name);
1043 	if (c != NULL)
1044 		return (c->value);
1045 	errx(1, "getoptionvalue: invoked with unknown option `%s'", name);
1046 	/* NOTREACHED */
1047 }
1048 
1049 static void
1050 setupoption(char *name, char *value, char *defaultvalue)
1051 {
1052 	char *nargv[3];
1053 	int overbose;
1054 
1055 	nargv[0] = "setupoption()";
1056 	nargv[1] = name;
1057 	nargv[2] = (value ? value : defaultvalue);
1058 	overbose = verbose;
1059 	verbose = 0;
1060 	setoption(3, nargv);
1061 	verbose = overbose;
1062 }
1063 
1064 void
1065 usage(void)
1066 {
1067 	const char *progname = getprogname();
1068 
1069 	(void)fprintf(stderr,
1070 "usage: %s [-46AadefginpRtVv] [-N netrc] [-o outfile] [-P port] [-q quittime]\n"
1071 "           [-r retry] [-s srcaddr] [-T dir,max[,inc]]\n"
1072 "           [[user@]host [port]] [host:path[/]] [file:///file]\n"
1073 "           [ftp://[user[:pass]@]host[:port]/path[/]]\n"
1074 "           [http://[user[:pass]@]host[:port]/path] [...]\n"
1075 "       %s -u URL file [...]\n", progname, progname);
1076 	exit(1);
1077 }
1078