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