Home | History | Annotate | Line # | Download | only in ftp
main.c revision 1.83
      1 /*	$NetBSD: main.c,v 1.83 2002/08/27 13:11:02 christos 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.83 2002/08/27 13:11:02 christos 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:q: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 'q':
    357 			quit_time = strtol(optarg, &ep, 10);
    358 			if (quit_time < 1 || *ep != '\0')
    359 				errx(1, "bad quit value: %s", optarg);
    360 			break;
    361 
    362 		case 'r':
    363 			retry_connect = strtol(optarg, &ep, 10);
    364 			if (retry_connect < 1 || *ep != '\0')
    365 				errx(1, "bad retry value: %s", optarg);
    366 			break;
    367 
    368 		case 'R':
    369 			restartautofetch = 1;
    370 			break;
    371 
    372 		case 't':
    373 			trace = 1;
    374 			break;
    375 
    376 		case 'T':
    377 		{
    378 			int targc;
    379 			char *targv[6], *oac;
    380 
    381 				/* look for `dir,max[,incr]' */
    382 			targc = 0;
    383 			targv[targc++] = "-T";
    384 			oac = xstrdup(optarg);
    385 
    386 			while ((cp = strsep(&oac, ",")) != NULL) {
    387 				if (*cp == '\0') {
    388 					warnx("bad throttle value: %s", optarg);
    389 					usage();
    390 					/* NOTREACHED */
    391 				}
    392 				targv[targc++] = cp;
    393 				if (targc >= 5)
    394 					break;
    395 			}
    396 			if (parserate(targc, targv, 1) == -1)
    397 				usage();
    398 			free(oac);
    399 			break;
    400 		}
    401 
    402 		case 'u':
    403 		{
    404 			isupload = 1;
    405 			interactive = 0;
    406 			upload_path = xstrdup(optarg);
    407 
    408 			break;
    409 		}
    410 
    411 		case 'v':
    412 			progress = verbose = 1;
    413 			break;
    414 
    415 		case 'V':
    416 			progress = verbose = 0;
    417 			break;
    418 
    419 		default:
    420 			usage();
    421 		}
    422 	}
    423 			/* set line buffering on ttyout */
    424 	setvbuf(ttyout, NULL, _IOLBF, 0);
    425 	argc -= optind;
    426 	argv += optind;
    427 
    428 	cpend = 0;	/* no pending replies */
    429 	proxy = 0;	/* proxy not active */
    430 	crflag = 1;	/* strip c.r. on ascii gets */
    431 	sendport = -1;	/* not using ports */
    432 
    433 	/*
    434 	 * Cache the user name and home directory.
    435 	 */
    436 	localhome = NULL;
    437 	localname = NULL;
    438 	anonuser = "anonymous";
    439 	cp = getenv("HOME");
    440 	if (! EMPTYSTRING(cp))
    441 		localhome = xstrdup(cp);
    442 	pw = NULL;
    443 	cp = getlogin();
    444 	if (cp != NULL)
    445 		pw = getpwnam(cp);
    446 	if (pw == NULL)
    447 		pw = getpwuid(getuid());
    448 	if (pw != NULL) {
    449 		if (localhome == NULL && !EMPTYSTRING(pw->pw_dir))
    450 			localhome = xstrdup(pw->pw_dir);
    451 		localname = xstrdup(pw->pw_name);
    452 		anonuser = localname;
    453 	}
    454 	if (netrc[0] == '\0' && localhome != NULL) {
    455 		if (strlcpy(netrc, localhome, sizeof(netrc)) >= sizeof(netrc) ||
    456 	    	    strlcat(netrc, "/.netrc", sizeof(netrc)) >= sizeof(netrc)) {
    457 			warnx("%s/.netrc: %s", localhome,
    458 			    strerror(ENAMETOOLONG));
    459 			netrc[0] = '\0';
    460 		}
    461 	}
    462 	if (localhome == NULL)
    463 		localhome = xstrdup("/");
    464 
    465 	/*
    466 	 * Every anonymous FTP server I've encountered will accept the
    467 	 * string "username@", and will append the hostname itself. We
    468 	 * do this by default since many servers are picky about not
    469 	 * having a FQDN in the anonymous password.
    470 	 * - thorpej (at) netbsd.org
    471 	 */
    472 	len = strlen(anonuser) + 2;
    473 	anonpass = xmalloc(len);
    474 	(void)strlcpy(anonpass, anonuser, len);
    475 	(void)strlcat(anonpass, "@",	  len);
    476 
    477 			/*
    478 			 * set all the defaults for options defined in
    479 			 * struct option optiontab[]  declared in cmdtab.c
    480 			 */
    481 	setupoption("anonpass",		getenv("FTPANONPASS"),	anonpass);
    482 	setupoption("ftp_proxy",	getenv(FTP_PROXY),	"");
    483 	setupoption("http_proxy",	getenv(HTTP_PROXY),	"");
    484 	setupoption("no_proxy",		getenv(NO_PROXY),	"");
    485 	setupoption("pager",		getenv("PAGER"),	DEFAULTPAGER);
    486 	setupoption("prompt",		getenv("FTPPROMPT"),	DEFAULTPROMPT);
    487 	setupoption("rprompt",		getenv("FTPRPROMPT"),	DEFAULTRPROMPT);
    488 
    489 	free(anonpass);
    490 
    491 	setttywidth(0);
    492 #ifdef SIGINFO
    493 	(void)xsignal(SIGINFO, psummary);
    494 #endif
    495 	(void)xsignal(SIGQUIT, psummary);
    496 	(void)xsignal(SIGUSR1, crankrate);
    497 	(void)xsignal(SIGUSR2, crankrate);
    498 	(void)xsignal(SIGWINCH, setttywidth);
    499 
    500 #ifdef __GNUC__			/* to shut up gcc warnings */
    501 	(void)&argc;
    502 	(void)&argv;
    503 #endif
    504 
    505 	if (argc > 0) {
    506 		if (isupload) {
    507 			rval = auto_put(argc, argv, upload_path);
    508 			exit(rval);
    509 		} else if (strchr(argv[0], ':') != NULL
    510 			    && ! isipv6addr(argv[0])) {
    511 			rval = auto_fetch(argc, argv);
    512 			if (rval >= 0)		/* -1 == connected and cd-ed */
    513 				exit(rval);
    514 		} else {
    515 			char *xargv[4], *user, *host;
    516 
    517 			if (sigsetjmp(toplevel, 1))
    518 				exit(0);
    519 			(void)xsignal(SIGINT, intr);
    520 			(void)xsignal(SIGPIPE, lostpeer);
    521 			user = NULL;
    522 			host = argv[0];
    523 			cp = strchr(host, '@');
    524 			if (cp) {
    525 				*cp = '\0';
    526 				user = host;
    527 				host = cp + 1;
    528 			}
    529 			/* XXX discards const */
    530 			xargv[0] = (char *)getprogname();
    531 			xargv[1] = host;
    532 			xargv[2] = argv[1];
    533 			xargv[3] = NULL;
    534 			do {
    535 				int oautologin;
    536 
    537 				oautologin = autologin;
    538 				if (user != NULL) {
    539 					anonftp = 0;
    540 					autologin = 0;
    541 				}
    542 				setpeer(argc+1, xargv);
    543 				autologin = oautologin;
    544 				if (connected == 1 && user != NULL)
    545 					(void)ftp_login(host, user, NULL);
    546 				if (!retry_connect)
    547 					break;
    548 				if (!connected) {
    549 					macnum = 0;
    550 					fprintf(ttyout,
    551 					    "Retrying in %d seconds...\n",
    552 					    retry_connect);
    553 					sleep(retry_connect);
    554 				}
    555 			} while (!connected);
    556 			retry_connect = 0; /* connected, stop hiding msgs */
    557 		}
    558 	}
    559 	if (isupload)
    560 		usage();
    561 
    562 #ifndef NO_EDITCOMPLETE
    563 	controlediting();
    564 #endif /* !NO_EDITCOMPLETE */
    565 
    566 	(void)sigsetjmp(toplevel, 1);
    567 	(void)xsignal(SIGINT, intr);
    568 	(void)xsignal(SIGPIPE, lostpeer);
    569 	for (;;)
    570 		cmdscanner();
    571 }
    572 
    573 /*
    574  * Generate a prompt
    575  */
    576 char *
    577 prompt(void)
    578 {
    579 	static char	**prompt;
    580 	static char	  buf[MAXPATHLEN];
    581 
    582 	if (prompt == NULL) {
    583 		struct option *o;
    584 
    585 		o = getoption("prompt");
    586 		if (o == NULL)
    587 			errx(1, "no such option `prompt'");
    588 		prompt = &(o->value);
    589 	}
    590 	formatbuf(buf, sizeof(buf), *prompt ? *prompt : DEFAULTPROMPT);
    591 	return (buf);
    592 }
    593 
    594 /*
    595  * Generate an rprompt
    596  */
    597 char *
    598 rprompt(void)
    599 {
    600 	static char	**rprompt;
    601 	static char	  buf[MAXPATHLEN];
    602 
    603 	if (rprompt == NULL) {
    604 		struct option *o;
    605 
    606 		o = getoption("rprompt");
    607 		if (o == NULL)
    608 			errx(1, "no such option `rprompt'");
    609 		rprompt = &(o->value);
    610 	}
    611 	formatbuf(buf, sizeof(buf), *rprompt ? *rprompt : DEFAULTRPROMPT);
    612 	return (buf);
    613 }
    614 
    615 /*
    616  * Command parser.
    617  */
    618 void
    619 cmdscanner(void)
    620 {
    621 	struct cmd	*c;
    622 	char		*p;
    623 	int		 num;
    624 
    625 	for (;;) {
    626 #ifndef NO_EDITCOMPLETE
    627 		if (!editing) {
    628 #endif /* !NO_EDITCOMPLETE */
    629 			if (fromatty) {
    630 				fputs(prompt(), ttyout);
    631 				p = rprompt();
    632 				if (*p)
    633 					fprintf(ttyout, "%s ", p);
    634 				(void)fflush(ttyout);
    635 			}
    636 			if (fgets(line, sizeof(line), stdin) == NULL) {
    637 				if (fromatty)
    638 					putc('\n', ttyout);
    639 				quit(0, NULL);
    640 			}
    641 			num = strlen(line);
    642 			if (num == 0)
    643 				break;
    644 			if (line[--num] == '\n') {
    645 				if (num == 0)
    646 					break;
    647 				line[num] = '\0';
    648 			} else if (num == sizeof(line) - 2) {
    649 				fputs("sorry, input line too long.\n", ttyout);
    650 				while ((num = getchar()) != '\n' && num != EOF)
    651 					/* void */;
    652 				break;
    653 			} /* else it was a line without a newline */
    654 #ifndef NO_EDITCOMPLETE
    655 		} else {
    656 			const char *buf;
    657 			HistEvent ev;
    658 			cursor_pos = NULL;
    659 
    660 			if ((buf = el_gets(el, &num)) == NULL || num == 0) {
    661 				if (fromatty)
    662 					putc('\n', ttyout);
    663 				quit(0, NULL);
    664 			}
    665 			if (buf[--num] == '\n') {
    666 				if (num == 0)
    667 					break;
    668 			} else if (num >= sizeof(line)) {
    669 				fputs("sorry, input line too long.\n", ttyout);
    670 				break;
    671 			}
    672 			memcpy(line, buf, num);
    673 			line[num] = '\0';
    674 			history(hist, &ev, H_ENTER, buf);
    675 		}
    676 #endif /* !NO_EDITCOMPLETE */
    677 
    678 		makeargv();
    679 		if (margc == 0)
    680 			continue;
    681 		c = getcmd(margv[0]);
    682 		if (c == (struct cmd *)-1) {
    683 			fputs("?Ambiguous command.\n", ttyout);
    684 			continue;
    685 		}
    686 		if (c == NULL) {
    687 #if !defined(NO_EDITCOMPLETE)
    688 			/*
    689 			 * attempt to el_parse() unknown commands.
    690 			 * any command containing a ':' would be parsed
    691 			 * as "[prog:]cmd ...", and will result in a
    692 			 * false positive if prog != "ftp", so treat
    693 			 * such commands as invalid.
    694 			 */
    695 			if (strchr(margv[0], ':') != NULL ||
    696 			    el_parse(el, margc, (const char **)margv) != 0)
    697 #endif /* !NO_EDITCOMPLETE */
    698 				fputs("?Invalid command.\n", ttyout);
    699 			continue;
    700 		}
    701 		if (c->c_conn && !connected) {
    702 			fputs("Not connected.\n", ttyout);
    703 			continue;
    704 		}
    705 		confirmrest = 0;
    706 		margv[0] = c->c_name;
    707 		(*c->c_handler)(margc, margv);
    708 		if (bell && c->c_bell)
    709 			(void)putc('\007', ttyout);
    710 		if (c->c_handler != help)
    711 			break;
    712 	}
    713 	(void)xsignal(SIGINT, intr);
    714 	(void)xsignal(SIGPIPE, lostpeer);
    715 }
    716 
    717 struct cmd *
    718 getcmd(const char *name)
    719 {
    720 	const char *p, *q;
    721 	struct cmd *c, *found;
    722 	int nmatches, longest;
    723 
    724 	if (name == NULL)
    725 		return (0);
    726 
    727 	longest = 0;
    728 	nmatches = 0;
    729 	found = 0;
    730 	for (c = cmdtab; (p = c->c_name) != NULL; c++) {
    731 		for (q = name; *q == *p++; q++)
    732 			if (*q == 0)		/* exact match? */
    733 				return (c);
    734 		if (!*q) {			/* the name was a prefix */
    735 			if (q - name > longest) {
    736 				longest = q - name;
    737 				nmatches = 1;
    738 				found = c;
    739 			} else if (q - name == longest)
    740 				nmatches++;
    741 		}
    742 	}
    743 	if (nmatches > 1)
    744 		return ((struct cmd *)-1);
    745 	return (found);
    746 }
    747 
    748 /*
    749  * Slice a string up into argc/argv.
    750  */
    751 
    752 int slrflag;
    753 
    754 void
    755 makeargv(void)
    756 {
    757 	char *argp;
    758 
    759 	stringbase = line;		/* scan from first of buffer */
    760 	argbase = argbuf;		/* store from first of buffer */
    761 	slrflag = 0;
    762 	marg_sl->sl_cur = 0;		/* reset to start of marg_sl */
    763 	for (margc = 0; ; margc++) {
    764 		argp = slurpstring();
    765 		xsl_add(marg_sl, argp);
    766 		if (argp == NULL)
    767 			break;
    768 	}
    769 #ifndef NO_EDITCOMPLETE
    770 	if (cursor_pos == line) {
    771 		cursor_argc = 0;
    772 		cursor_argo = 0;
    773 	} else if (cursor_pos != NULL) {
    774 		cursor_argc = margc;
    775 		cursor_argo = strlen(margv[margc-1]);
    776 	}
    777 #endif /* !NO_EDITCOMPLETE */
    778 }
    779 
    780 #ifdef NO_EDITCOMPLETE
    781 #define	INC_CHKCURSOR(x)	(x)++
    782 #else  /* !NO_EDITCOMPLETE */
    783 #define	INC_CHKCURSOR(x)	{ (x)++ ; \
    784 				if (x == cursor_pos) { \
    785 					cursor_argc = margc; \
    786 					cursor_argo = ap-argbase; \
    787 					cursor_pos = NULL; \
    788 				} }
    789 
    790 #endif /* !NO_EDITCOMPLETE */
    791 
    792 /*
    793  * Parse string into argbuf;
    794  * implemented with FSM to
    795  * handle quoting and strings
    796  */
    797 char *
    798 slurpstring(void)
    799 {
    800 	int got_one = 0;
    801 	char *sb = stringbase;
    802 	char *ap = argbase;
    803 	char *tmp = argbase;		/* will return this if token found */
    804 
    805 	if (*sb == '!' || *sb == '$') {	/* recognize ! as a token for shell */
    806 		switch (slrflag) {	/* and $ as token for macro invoke */
    807 			case 0:
    808 				slrflag++;
    809 				INC_CHKCURSOR(stringbase);
    810 				return ((*sb == '!') ? "!" : "$");
    811 				/* NOTREACHED */
    812 			case 1:
    813 				slrflag++;
    814 				altarg = stringbase;
    815 				break;
    816 			default:
    817 				break;
    818 		}
    819 	}
    820 
    821 S0:
    822 	switch (*sb) {
    823 
    824 	case '\0':
    825 		goto OUT;
    826 
    827 	case ' ':
    828 	case '\t':
    829 		INC_CHKCURSOR(sb);
    830 		goto S0;
    831 
    832 	default:
    833 		switch (slrflag) {
    834 			case 0:
    835 				slrflag++;
    836 				break;
    837 			case 1:
    838 				slrflag++;
    839 				altarg = sb;
    840 				break;
    841 			default:
    842 				break;
    843 		}
    844 		goto S1;
    845 	}
    846 
    847 S1:
    848 	switch (*sb) {
    849 
    850 	case ' ':
    851 	case '\t':
    852 	case '\0':
    853 		goto OUT;	/* end of token */
    854 
    855 	case '\\':
    856 		INC_CHKCURSOR(sb);
    857 		goto S2;	/* slurp next character */
    858 
    859 	case '"':
    860 		INC_CHKCURSOR(sb);
    861 		goto S3;	/* slurp quoted string */
    862 
    863 	default:
    864 		*ap = *sb;	/* add character to token */
    865 		ap++;
    866 		INC_CHKCURSOR(sb);
    867 		got_one = 1;
    868 		goto S1;
    869 	}
    870 
    871 S2:
    872 	switch (*sb) {
    873 
    874 	case '\0':
    875 		goto OUT;
    876 
    877 	default:
    878 		*ap = *sb;
    879 		ap++;
    880 		INC_CHKCURSOR(sb);
    881 		got_one = 1;
    882 		goto S1;
    883 	}
    884 
    885 S3:
    886 	switch (*sb) {
    887 
    888 	case '\0':
    889 		goto OUT;
    890 
    891 	case '"':
    892 		INC_CHKCURSOR(sb);
    893 		goto S1;
    894 
    895 	default:
    896 		*ap = *sb;
    897 		ap++;
    898 		INC_CHKCURSOR(sb);
    899 		got_one = 1;
    900 		goto S3;
    901 	}
    902 
    903 OUT:
    904 	if (got_one)
    905 		*ap++ = '\0';
    906 	argbase = ap;			/* update storage pointer */
    907 	stringbase = sb;		/* update scan pointer */
    908 	if (got_one) {
    909 		return (tmp);
    910 	}
    911 	switch (slrflag) {
    912 		case 0:
    913 			slrflag++;
    914 			break;
    915 		case 1:
    916 			slrflag++;
    917 			altarg = NULL;
    918 			break;
    919 		default:
    920 			break;
    921 	}
    922 	return (NULL);
    923 }
    924 
    925 /*
    926  * Help/usage command.
    927  * Call each command handler with argc == 0 and argv[0] == name.
    928  */
    929 void
    930 help(int argc, char *argv[])
    931 {
    932 	struct cmd *c;
    933 	char *nargv[1], *p, *cmd;
    934 	int isusage;
    935 
    936 	cmd = argv[0];
    937 	isusage = (strcmp(cmd, "usage") == 0);
    938 	if (argc == 0 || (isusage && argc == 1)) {
    939 		fprintf(ttyout, "usage: %s [command [...]]\n", cmd);
    940 		return;
    941 	}
    942 	if (argc == 1) {
    943 		StringList *buf;
    944 
    945 		buf = xsl_init();
    946 		fprintf(ttyout,
    947 		    "%sommands may be abbreviated.  Commands are:\n\n",
    948 		    proxy ? "Proxy c" : "C");
    949 		for (c = cmdtab; (p = c->c_name) != NULL; c++)
    950 			if (!proxy || c->c_proxy)
    951 				xsl_add(buf, p);
    952 		list_vertical(buf);
    953 		sl_free(buf, 0);
    954 		return;
    955 	}
    956 
    957 #define	HELPINDENT ((int) sizeof("disconnect"))
    958 
    959 	while (--argc > 0) {
    960 		char *arg;
    961 
    962 		arg = *++argv;
    963 		c = getcmd(arg);
    964 		if (c == (struct cmd *)-1)
    965 			fprintf(ttyout, "?Ambiguous %s command `%s'\n",
    966 			    cmd, arg);
    967 		else if (c == NULL)
    968 			fprintf(ttyout, "?Invalid %s command `%s'\n",
    969 			    cmd, arg);
    970 		else {
    971 			if (isusage) {
    972 				nargv[0] = c->c_name;
    973 				(*c->c_handler)(0, nargv);
    974 			} else
    975 				fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
    976 				    c->c_name, c->c_help);
    977 		}
    978 	}
    979 }
    980 
    981 struct option *
    982 getoption(const char *name)
    983 {
    984 	const char *p;
    985 	struct option *c;
    986 
    987 	if (name == NULL)
    988 		return (NULL);
    989 	for (c = optiontab; (p = c->name) != NULL; c++) {
    990 		if (strcasecmp(p, name) == 0)
    991 			return (c);
    992 	}
    993 	return (NULL);
    994 }
    995 
    996 char *
    997 getoptionvalue(const char *name)
    998 {
    999 	struct option *c;
   1000 
   1001 	if (name == NULL)
   1002 		errx(1, "getoptionvalue() invoked with NULL name");
   1003 	c = getoption(name);
   1004 	if (c != NULL)
   1005 		return (c->value);
   1006 	errx(1, "getoptionvalue() invoked with unknown option `%s'", name);
   1007 	/* NOTREACHED */
   1008 }
   1009 
   1010 static void
   1011 setupoption(char *name, char *value, char *defaultvalue)
   1012 {
   1013 	char *nargv[3];
   1014 	int overbose;
   1015 
   1016 	nargv[0] = "setupoption()";
   1017 	nargv[1] = name;
   1018 	nargv[2] = (value ? value : defaultvalue);
   1019 	overbose = verbose;
   1020 	verbose = 0;
   1021 	setoption(3, nargv);
   1022 	verbose = overbose;
   1023 }
   1024 
   1025 void
   1026 usage(void)
   1027 {
   1028 	const char *progname = getprogname();
   1029 
   1030 	(void)fprintf(stderr,
   1031 "usage: %s [-46AadefginpRtvV] [-N netrc] [-o outfile] [-P port] [-r retry]\n"
   1032 "           [-T dir,max[,inc][[user@]host [port]]] [host:path[/]]\n"
   1033 "           [file:///file] [ftp://[user[:pass]@]host[:port]/path[/]]\n"
   1034 "           [http://[user[:pass]@]host[:port]/path] [...]\n"
   1035 "       %s -u url file [...]\n", progname, progname);
   1036 	exit(1);
   1037 }
   1038