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