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