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