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