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