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