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