Home | History | Annotate | Line # | Download | only in ftp
main.c revision 1.67
      1 /*	$NetBSD: main.c,v 1.67 1999/11/12 02:50:38 lukem Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1996-1999 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.67 1999/11/12 02:50:38 lukem 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 
    131 #define	GLOBAL		/* force GLOBAL decls in ftp_var.h to be declared */
    132 #include "ftp_var.h"
    133 
    134 #define	FTP_PROXY	"ftp_proxy"	/* env var with FTP proxy location */
    135 #define	HTTP_PROXY	"http_proxy"	/* env var with HTTP proxy location */
    136 #define	NO_PROXY	"no_proxy"	/* env var with list of non-proxied
    137 					 * hosts, comma or space separated */
    138 
    139 static void	setupoption __P((char *, char *, char *));
    140 int		main __P((int, char **));
    141 
    142 int
    143 main(argc, argv)
    144 	int argc;
    145 	char *argv[];
    146 {
    147 	int ch, rval;
    148 	struct passwd *pw = NULL;
    149 	char *cp, *ep, *anonuser, *anonpass;
    150 	int dumbterm, s, len;
    151 
    152 	ftpport = "ftp";
    153 	httpport = "http";
    154 	gateport = NULL;
    155 	cp = getenv("FTPSERVERPORT");
    156 	if (cp != NULL)
    157 		gateport = cp;
    158 	else
    159 		gateport = "ftpgate";
    160 	doglob = 1;
    161 	interactive = 1;
    162 	autologin = 1;
    163 	passivemode = 1;
    164 	activefallback = 1;
    165 	preserve = 1;
    166 	verbose = 0;
    167 	progress = 0;
    168 	gatemode = 0;
    169 	data = -1;
    170 	outfile = NULL;
    171 	restartautofetch = 0;
    172 #ifndef NO_EDITCOMPLETE
    173 	editing = 0;
    174 	el = NULL;
    175 	hist = NULL;
    176 #endif
    177 	bytes = 0;
    178 	mark = HASHBYTES;
    179 	rate_get = 0;
    180 	rate_get_incr = DEFAULTINCR;
    181 	rate_put = 0;
    182 	rate_put_incr = DEFAULTINCR;
    183 #ifdef INET6
    184 	epsv4 = 1;
    185 #else
    186 	epsv4 = 0;
    187 #endif
    188 	epsv4bad = 0;
    189 
    190 	/*
    191 	 * Get the default socket buffer sizes if we don't already have them.
    192 	 * It doesn't matter which socket we do this to, because on the first
    193 	 * call no socket buffer sizes will have been modified, so we are
    194 	 * guaranteed to get the system defaults.
    195 	 */
    196 	s = socket(AF_INET, SOCK_STREAM, 0);
    197 	if (s == -1)
    198 		err(1, "can't create socket");
    199 	len = sizeof(rcvbuf_size);
    200 	if (getsockopt(s, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size, &len)
    201 	    < 0)
    202 		err(1, "unable to get default rcvbuf size");
    203 	len = sizeof(sndbuf_size);
    204 	if (getsockopt(s, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size, &len)
    205 	    < 0)
    206 		err(1, "unable to get default sndbuf size");
    207 	(void)close(s);
    208 					/* sanity check returned buffer sizes */
    209 	if (rcvbuf_size <= 0)
    210 		rcvbuf_size = 8192;
    211 	if (sndbuf_size <= 0)
    212 		sndbuf_size = 8192;
    213 
    214 	marg_sl = sl_init();
    215 	if ((tmpdir = getenv("TMPDIR")) == NULL)
    216 		tmpdir = _PATH_TMP;
    217 
    218 	/* Set default operation mode based on FTPMODE environment variable */
    219 	if ((cp = getenv("FTPMODE")) != NULL) {
    220 		if (strcasecmp(cp, "passive") == 0) {
    221 			passivemode = 1;
    222 			activefallback = 0;
    223 		} else if (strcasecmp(cp, "active") == 0) {
    224 			passivemode = 0;
    225 			activefallback = 0;
    226 		} else if (strcasecmp(cp, "gate") == 0) {
    227 			gatemode = 1;
    228 		} else if (strcasecmp(cp, "auto") == 0) {
    229 			passivemode = 1;
    230 			activefallback = 1;
    231 		} else
    232 			warnx("unknown $FTPMODE '%s'; using defaults", cp);
    233 	}
    234 
    235 	if (strcmp(__progname, "pftp") == 0) {
    236 		passivemode = 1;
    237 		activefallback = 0;
    238 	} else if (strcmp(__progname, "gate-ftp") == 0)
    239 		gatemode = 1;
    240 
    241 	gateserver = getenv("FTPSERVER");
    242 	if (gateserver == NULL || *gateserver == '\0')
    243 		gateserver = GATE_SERVER;
    244 	if (gatemode) {
    245 		if (*gateserver == '\0') {
    246 			warnx(
    247 "Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp");
    248 			gatemode = 0;
    249 		}
    250 	}
    251 
    252 	cp = getenv("TERM");
    253 	if (cp == NULL || strcmp(cp, "dumb") == 0)
    254 		dumbterm = 1;
    255 	else
    256 		dumbterm = 0;
    257 	fromatty = isatty(fileno(stdin));
    258 	ttyout = stdout;
    259 	if (isatty(fileno(ttyout))) {
    260 		verbose = 1;		/* verbose if to a tty */
    261 		if (! dumbterm) {
    262 #ifndef NO_EDITCOMPLETE
    263 			if (fromatty)	/* editing mode on if tty is usable */
    264 				editing = 1;
    265 #endif
    266 #ifndef NO_PROGRESS
    267 			if (foregroundproc())
    268 				progress = 1;	/* progress bar on if fg */
    269 #endif
    270 		}
    271 	}
    272 
    273 	while ((ch = getopt(argc, argv, "Aadefgino:pP:r:RtT:vV")) != -1) {
    274 		switch (ch) {
    275 		case 'A':
    276 			activefallback = 0;
    277 			passivemode = 0;
    278 			break;
    279 
    280 		case 'a':
    281 			anonftp = 1;
    282 			break;
    283 
    284 		case 'd':
    285 			options |= SO_DEBUG;
    286 			debug++;
    287 			break;
    288 
    289 		case 'e':
    290 #ifndef NO_EDITCOMPLETE
    291 			editing = 0;
    292 #endif
    293 			break;
    294 
    295 		case 'f':
    296 			flushcache = 1;
    297 			break;
    298 
    299 		case 'g':
    300 			doglob = 0;
    301 			break;
    302 
    303 		case 'i':
    304 			interactive = 0;
    305 			break;
    306 
    307 		case 'n':
    308 			autologin = 0;
    309 			break;
    310 
    311 		case 'o':
    312 			outfile = optarg;
    313 			if (strcmp(outfile, "-") == 0)
    314 				ttyout = stderr;
    315 			break;
    316 
    317 		case 'p':
    318 			passivemode = 1;
    319 			activefallback = 0;
    320 			break;
    321 
    322 		case 'P':
    323 			ftpport = optarg;
    324 			break;
    325 
    326 		case 'r':
    327 			retry_connect = strtol(optarg, &ep, 10);
    328 			if (retry_connect < 1 || *ep != '\0')
    329 				errx(1, "bad retry value: %s", optarg);
    330 			break;
    331 
    332 		case 'R':
    333 			restartautofetch = 1;
    334 			break;
    335 
    336 		case 't':
    337 			trace = 1;
    338 			break;
    339 
    340 		case 'T':
    341 		{
    342 			int targc;
    343 			char *targv[6], *oac;
    344 
    345 				/* look for `dir,max[,incr]' */
    346 			targc = 0;
    347 			targv[targc++] = "-T";
    348 			oac = xstrdup(optarg);
    349 
    350 			while ((cp = strsep(&oac, ",")) != NULL) {
    351 				if (*cp == '\0') {
    352 					warnx("bad throttle value: %s", optarg);
    353 					usage();
    354 					/* NOTREACHED */
    355 				}
    356 				targv[targc++] = cp;
    357 				if (targc >= 5)
    358 					break;
    359 			}
    360 			if (parserate(targc, targv, 1) == -1)
    361 				usage();
    362 			free(oac);
    363 			break;
    364 		}
    365 
    366 		case 'v':
    367 			progress = verbose = 1;
    368 			break;
    369 
    370 		case 'V':
    371 			progress = verbose = 0;
    372 			break;
    373 
    374 		default:
    375 			usage();
    376 		}
    377 	}
    378 			/* set line buffering on ttyout */
    379 	setvbuf(ttyout, NULL, _IOLBF, 0);
    380 	argc -= optind;
    381 	argv += optind;
    382 
    383 	cpend = 0;	/* no pending replies */
    384 	proxy = 0;	/* proxy not active */
    385 	crflag = 1;	/* strip c.r. on ascii gets */
    386 	sendport = -1;	/* not using ports */
    387 	/*
    388 	 * Set up the home directory in case we're globbing.
    389 	 */
    390 	cp = getlogin();
    391 	if (cp != NULL)
    392 		pw = getpwnam(cp);
    393 	if (pw == NULL)
    394 		pw = getpwuid(getuid());
    395 	if (pw != NULL) {
    396 		(void)strlcpy(home, pw->pw_dir, sizeof(home));
    397 		anonuser = pw->pw_name;
    398 	} else {
    399 		(void)strlcpy(home, "/", sizeof(home));
    400 		anonuser = "anonymous";
    401 	}
    402 
    403 	/*
    404 	 * Every anonymous FTP server I've encountered will accept the
    405 	 * string "username@", and will append the hostname itself. We
    406 	 * do this by default since many servers are picky about not
    407 	 * having a FQDN in the anonymous password.
    408 	 * - thorpej (at) netbsd.org
    409 	 */
    410 	len = strlen(anonuser) + 2;
    411 	anonpass = xmalloc(len);
    412 	(void)strlcpy(anonpass, anonuser, len);
    413 	(void)strlcat(anonpass, "@",	  len);
    414 
    415 			/*
    416 			 * set all the defaults for options defined in
    417 			 * struct option optiontab[]  declared in cmdtab.c
    418 			 */
    419 	setupoption("anonpass",		getenv("FTPANONPASS"),	anonpass);
    420 	setupoption("ftp_proxy",	getenv(FTP_PROXY),	"");
    421 	setupoption("http_proxy",	getenv(HTTP_PROXY),	"");
    422 	setupoption("no_proxy",		getenv(NO_PROXY),	"");
    423 	setupoption("pager",		getenv("PAGER"),	DEFAULTPAGER);
    424 	setupoption("prompt",		getenv("FTPPROMPT"),	DEFAULTPROMPT);
    425 	setupoption("rprompt",		getenv("FTPRPROMPT"),	DEFAULTRPROMPT);
    426 
    427 	free(anonpass);
    428 
    429 	setttywidth(0);
    430 #ifdef SIGINFO
    431 	(void)xsignal(SIGINFO, psummary);
    432 #endif
    433 	(void)xsignal(SIGQUIT, psummary);
    434 	(void)xsignal(SIGUSR1, crankrate);
    435 	(void)xsignal(SIGUSR2, crankrate);
    436 	(void)xsignal(SIGWINCH, setttywidth);
    437 
    438 #ifdef __GNUC__			/* to shut up gcc warnings */
    439 	(void)&argc;
    440 	(void)&argv;
    441 #endif
    442 
    443 	if (argc > 0) {
    444 		if (strchr(argv[0], ':') != NULL && ! isipv6addr(argv[0])) {
    445 			rval = auto_fetch(argc, argv);
    446 			if (rval >= 0)		/* -1 == connected and cd-ed */
    447 				exit(rval);
    448 		} else {
    449 			char *xargv[5];
    450 
    451 			if (sigsetjmp(toplevel, 1))
    452 				exit(0);
    453 			(void)xsignal(SIGINT, intr);
    454 			(void)xsignal(SIGPIPE, lostpeer);
    455 			xargv[0] = __progname;
    456 			xargv[1] = argv[0];
    457 			xargv[2] = argv[1];
    458 			xargv[3] = argv[2];
    459 			xargv[4] = NULL;
    460 			do {
    461 				setpeer(argc+1, xargv);
    462 				if (!retry_connect)
    463 					break;
    464 				if (!connected) {
    465 					macnum = 0;
    466 					fprintf(ttyout,
    467 					    "Retrying in %d seconds...\n",
    468 					    retry_connect);
    469 					sleep(retry_connect);
    470 				}
    471 			} while (!connected);
    472 			retry_connect = 0; /* connected, stop hiding msgs */
    473 		}
    474 	}
    475 #ifndef NO_EDITCOMPLETE
    476 	controlediting();
    477 #endif /* !NO_EDITCOMPLETE */
    478 
    479 	(void)sigsetjmp(toplevel, 1);
    480 	(void)xsignal(SIGINT, intr);
    481 	(void)xsignal(SIGPIPE, lostpeer);
    482 	for (;;)
    483 		cmdscanner();
    484 }
    485 
    486 /*
    487  * Generate a prompt
    488  */
    489 char *
    490 prompt()
    491 {
    492 	static char	**prompt;
    493 	static char	  buf[MAXPATHLEN];
    494 
    495 	if (prompt == NULL) {
    496 		struct option *o;
    497 
    498 		o = getoption("prompt");
    499 		if (o == NULL)
    500 			errx(1, "no such option `prompt'");
    501 		prompt = &(o->value);
    502 	}
    503 	formatbuf(buf, sizeof(buf), *prompt ? *prompt : DEFAULTPROMPT);
    504 	return (buf);
    505 }
    506 
    507 /*
    508  * Generate an rprompt
    509  */
    510 char *
    511 rprompt()
    512 {
    513 	static char	**rprompt;
    514 	static char	  buf[MAXPATHLEN];
    515 
    516 	if (rprompt == NULL) {
    517 		struct option *o;
    518 
    519 		o = getoption("rprompt");
    520 		if (o == NULL)
    521 			errx(1, "no such option `rprompt'");
    522 		rprompt = &(o->value);
    523 	}
    524 	formatbuf(buf, sizeof(buf), *rprompt ? *rprompt : DEFAULTRPROMPT);
    525 	return (buf);
    526 }
    527 
    528 /*
    529  * Command parser.
    530  */
    531 void
    532 cmdscanner()
    533 {
    534 	struct cmd	*c;
    535 	char		*p;
    536 	int		 num;
    537 
    538 	for (;;) {
    539 #ifndef NO_EDITCOMPLETE
    540 		if (!editing) {
    541 #endif /* !NO_EDITCOMPLETE */
    542 			if (fromatty) {
    543 				fputs(prompt(), ttyout);
    544 				p = rprompt();
    545 				if (*p)
    546 					fprintf(ttyout, "%s ", p);
    547 				(void)fflush(ttyout);
    548 			}
    549 			if (fgets(line, sizeof(line), stdin) == NULL) {
    550 				if (fromatty)
    551 					putc('\n', ttyout);
    552 				quit(0, 0);
    553 			}
    554 			num = strlen(line);
    555 			if (num == 0)
    556 				break;
    557 			if (line[--num] == '\n') {
    558 				if (num == 0)
    559 					break;
    560 				line[num] = '\0';
    561 			} else if (num == sizeof(line) - 2) {
    562 				fputs("sorry, input line too long.\n", ttyout);
    563 				while ((num = getchar()) != '\n' && num != EOF)
    564 					/* void */;
    565 				break;
    566 			} /* else it was a line without a newline */
    567 #ifndef NO_EDITCOMPLETE
    568 		} else {
    569 			const char *buf;
    570 			HistEvent ev;
    571 			cursor_pos = NULL;
    572 
    573 			if ((buf = el_gets(el, &num)) == NULL || num == 0) {
    574 				if (fromatty)
    575 					putc('\n', ttyout);
    576 				quit(0, 0);
    577 			}
    578 			if (buf[--num] == '\n') {
    579 				if (num == 0)
    580 					break;
    581 			} else if (num >= sizeof(line)) {
    582 				fputs("sorry, input line too long.\n", ttyout);
    583 				break;
    584 			}
    585 			memcpy(line, buf, num);
    586 			line[num] = '\0';
    587 			history(hist, &ev, H_ENTER, buf);
    588 		}
    589 #endif /* !NO_EDITCOMPLETE */
    590 
    591 		makeargv();
    592 		if (margc == 0)
    593 			continue;
    594 		c = getcmd(margv[0]);
    595 		if (c == (struct cmd *)-1) {
    596 			fputs("?Ambiguous command.\n", ttyout);
    597 			continue;
    598 		}
    599 		if (c == NULL) {
    600 #if !defined(NO_EDITCOMPLETE)
    601 			/*
    602 			 * attempt to el_parse() unknown commands.
    603 			 * any command containing a ':' would be parsed
    604 			 * as "[prog:]cmd ...", and will result in a
    605 			 * false positive if prog != "ftp", so treat
    606 			 * such commands as invalid.
    607 			 */
    608 			if (strchr(margv[0], ':') != NULL ||
    609 			    el_parse(el, margc, margv) != 0)
    610 #endif /* !NO_EDITCOMPLETE */
    611 				fputs("?Invalid command.\n", ttyout);
    612 			continue;
    613 		}
    614 		if (c->c_conn && !connected) {
    615 			fputs("Not connected.\n", ttyout);
    616 			continue;
    617 		}
    618 		confirmrest = 0;
    619 		(*c->c_handler)(margc, margv);
    620 		if (bell && c->c_bell)
    621 			(void)putc('\007', ttyout);
    622 		if (c->c_handler != help)
    623 			break;
    624 	}
    625 	(void)xsignal(SIGINT, intr);
    626 	(void)xsignal(SIGPIPE, lostpeer);
    627 }
    628 
    629 struct cmd *
    630 getcmd(name)
    631 	const char *name;
    632 {
    633 	const char *p, *q;
    634 	struct cmd *c, *found;
    635 	int nmatches, longest;
    636 
    637 	if (name == NULL)
    638 		return (0);
    639 
    640 	longest = 0;
    641 	nmatches = 0;
    642 	found = 0;
    643 	for (c = cmdtab; (p = c->c_name) != NULL; c++) {
    644 		for (q = name; *q == *p++; q++)
    645 			if (*q == 0)		/* exact match? */
    646 				return (c);
    647 		if (!*q) {			/* the name was a prefix */
    648 			if (q - name > longest) {
    649 				longest = q - name;
    650 				nmatches = 1;
    651 				found = c;
    652 			} else if (q - name == longest)
    653 				nmatches++;
    654 		}
    655 	}
    656 	if (nmatches > 1)
    657 		return ((struct cmd *)-1);
    658 	return (found);
    659 }
    660 
    661 /*
    662  * Slice a string up into argc/argv.
    663  */
    664 
    665 int slrflag;
    666 
    667 void
    668 makeargv()
    669 {
    670 	char *argp;
    671 
    672 	stringbase = line;		/* scan from first of buffer */
    673 	argbase = argbuf;		/* store from first of buffer */
    674 	slrflag = 0;
    675 	marg_sl->sl_cur = 0;		/* reset to start of marg_sl */
    676 	for (margc = 0; ; margc++) {
    677 		argp = slurpstring();
    678 		sl_add(marg_sl, argp);
    679 		if (argp == NULL)
    680 			break;
    681 	}
    682 #ifndef NO_EDITCOMPLETE
    683 	if (cursor_pos == line) {
    684 		cursor_argc = 0;
    685 		cursor_argo = 0;
    686 	} else if (cursor_pos != NULL) {
    687 		cursor_argc = margc;
    688 		cursor_argo = strlen(margv[margc-1]);
    689 	}
    690 #endif /* !NO_EDITCOMPLETE */
    691 }
    692 
    693 #ifdef NO_EDITCOMPLETE
    694 #define	INC_CHKCURSOR(x)	(x)++
    695 #else  /* !NO_EDITCOMPLETE */
    696 #define	INC_CHKCURSOR(x)	{ (x)++ ; \
    697 				if (x == cursor_pos) { \
    698 					cursor_argc = margc; \
    699 					cursor_argo = ap-argbase; \
    700 					cursor_pos = NULL; \
    701 				} }
    702 
    703 #endif /* !NO_EDITCOMPLETE */
    704 
    705 /*
    706  * Parse string into argbuf;
    707  * implemented with FSM to
    708  * handle quoting and strings
    709  */
    710 char *
    711 slurpstring()
    712 {
    713 	int got_one = 0;
    714 	char *sb = stringbase;
    715 	char *ap = argbase;
    716 	char *tmp = argbase;		/* will return this if token found */
    717 
    718 	if (*sb == '!' || *sb == '$') {	/* recognize ! as a token for shell */
    719 		switch (slrflag) {	/* and $ as token for macro invoke */
    720 			case 0:
    721 				slrflag++;
    722 				INC_CHKCURSOR(stringbase);
    723 				return ((*sb == '!') ? "!" : "$");
    724 				/* NOTREACHED */
    725 			case 1:
    726 				slrflag++;
    727 				altarg = stringbase;
    728 				break;
    729 			default:
    730 				break;
    731 		}
    732 	}
    733 
    734 S0:
    735 	switch (*sb) {
    736 
    737 	case '\0':
    738 		goto OUT;
    739 
    740 	case ' ':
    741 	case '\t':
    742 		INC_CHKCURSOR(sb);
    743 		goto S0;
    744 
    745 	default:
    746 		switch (slrflag) {
    747 			case 0:
    748 				slrflag++;
    749 				break;
    750 			case 1:
    751 				slrflag++;
    752 				altarg = sb;
    753 				break;
    754 			default:
    755 				break;
    756 		}
    757 		goto S1;
    758 	}
    759 
    760 S1:
    761 	switch (*sb) {
    762 
    763 	case ' ':
    764 	case '\t':
    765 	case '\0':
    766 		goto OUT;	/* end of token */
    767 
    768 	case '\\':
    769 		INC_CHKCURSOR(sb);
    770 		goto S2;	/* slurp next character */
    771 
    772 	case '"':
    773 		INC_CHKCURSOR(sb);
    774 		goto S3;	/* slurp quoted string */
    775 
    776 	default:
    777 		*ap = *sb;	/* add character to token */
    778 		ap++;
    779 		INC_CHKCURSOR(sb);
    780 		got_one = 1;
    781 		goto S1;
    782 	}
    783 
    784 S2:
    785 	switch (*sb) {
    786 
    787 	case '\0':
    788 		goto OUT;
    789 
    790 	default:
    791 		*ap = *sb;
    792 		ap++;
    793 		INC_CHKCURSOR(sb);
    794 		got_one = 1;
    795 		goto S1;
    796 	}
    797 
    798 S3:
    799 	switch (*sb) {
    800 
    801 	case '\0':
    802 		goto OUT;
    803 
    804 	case '"':
    805 		INC_CHKCURSOR(sb);
    806 		goto S1;
    807 
    808 	default:
    809 		*ap = *sb;
    810 		ap++;
    811 		INC_CHKCURSOR(sb);
    812 		got_one = 1;
    813 		goto S3;
    814 	}
    815 
    816 OUT:
    817 	if (got_one)
    818 		*ap++ = '\0';
    819 	argbase = ap;			/* update storage pointer */
    820 	stringbase = sb;		/* update scan pointer */
    821 	if (got_one) {
    822 		return (tmp);
    823 	}
    824 	switch (slrflag) {
    825 		case 0:
    826 			slrflag++;
    827 			break;
    828 		case 1:
    829 			slrflag++;
    830 			altarg = NULL;
    831 			break;
    832 		default:
    833 			break;
    834 	}
    835 	return (NULL);
    836 }
    837 
    838 /*
    839  * Help/usage command.
    840  * Call each command handler with argc == 0 and argv[0] == name.
    841  */
    842 void
    843 help(argc, argv)
    844 	int argc;
    845 	char *argv[];
    846 {
    847 	struct cmd *c;
    848 	char *nargv[1], *p, *cmd;
    849 	int isusage;
    850 
    851 	cmd = argv[0];
    852 	isusage = (strcmp(cmd, "usage") == 0);
    853 	if (argc == 0 || (isusage && argc == 1)) {
    854 		fprintf(ttyout, "usage: %s [command [...]]\n", cmd);
    855 		return;
    856 	}
    857 	if (argc == 1) {
    858 		StringList *buf;
    859 
    860 		buf = sl_init();
    861 		fprintf(ttyout,
    862 		    "%sommands may be abbreviated.  Commands are:\n\n",
    863 		    proxy ? "Proxy c" : "C");
    864 		for (c = cmdtab; (p = c->c_name) != NULL; c++)
    865 			if (!proxy || c->c_proxy)
    866 				sl_add(buf, p);
    867 		list_vertical(buf);
    868 		sl_free(buf, 0);
    869 		return;
    870 	}
    871 
    872 #define	HELPINDENT ((int) sizeof("disconnect"))
    873 
    874 	while (--argc > 0) {
    875 		char *arg;
    876 
    877 		arg = *++argv;
    878 		c = getcmd(arg);
    879 		if (c == (struct cmd *)-1)
    880 			fprintf(ttyout, "?Ambiguous %s command `%s'\n",
    881 			    cmd, arg);
    882 		else if (c == NULL)
    883 			fprintf(ttyout, "?Invalid %s command `%s'\n",
    884 			    cmd, arg);
    885 		else {
    886 			if (isusage) {
    887 				nargv[0] = arg;
    888 				(*c->c_handler)(0, nargv);
    889 			} else
    890 				fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
    891 				    c->c_name, c->c_help);
    892 		}
    893 	}
    894 }
    895 
    896 struct option *
    897 getoption(name)
    898 	const char *name;
    899 {
    900 	const char *p;
    901 	struct option *c;
    902 
    903 	if (name == NULL)
    904 		return (NULL);
    905 	for (c = optiontab; (p = c->name) != NULL; c++) {
    906 		if (strcasecmp(p, name) == 0)
    907 			return (c);
    908 	}
    909 	return (NULL);
    910 }
    911 
    912 char *
    913 getoptionvalue(name)
    914 	const char *name;
    915 {
    916 	struct option *c;
    917 
    918 	if (name == NULL)
    919 		errx(1, "getoptionvalue() invoked with NULL name");
    920 	c = getoption(name);
    921 	if (c != NULL)
    922 		return (c->value);
    923 	errx(1, "getoptionvalue() invoked with unknown option `%s'", name);
    924 }
    925 
    926 static void
    927 setupoption(name, value, defaultvalue)
    928 	char *name, *value, *defaultvalue;
    929 {
    930 	char *nargv[3];
    931 	int overbose;
    932 
    933 	nargv[0] = "setupoption()";
    934 	nargv[1] = name;
    935 	nargv[2] = (value ? value : defaultvalue);
    936 	overbose = verbose;
    937 	verbose = 0;
    938 	setoption(3, nargv);
    939 	verbose = overbose;
    940 }
    941 
    942 void
    943 usage()
    944 {
    945 	(void)fprintf(stderr,
    946 "usage: %s [-AadefginpRtvV] [-r retry] [-o outfile] [-P port] [-T dir,max[,inc]\n"
    947 "       [host [port]] [file:///file] [ftp://[user[:pass]@]host[:port]/path[/]]\n"
    948 "       [http://[user[:pass]@]host[:port]/path] [host:path[/]]\n", __progname);
    949 	exit(1);
    950 }
    951