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