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