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