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