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