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