xref: /netbsd-src/usr.bin/ftp/main.c (revision 627f7eb200a4419d89b531d55fccd2ee3ffdcde0)
1 /*	$NetBSD: main.c,v 1.127 2020/07/18 03:00:37 lukem Exp $	*/
2 
3 /*-
4  * Copyright (c) 1996-2015 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.127 2020/07/18 03:00:37 lukem Exp $");
102 #endif
103 #endif /* not lint */
104 
105 /*
106  * FTP User Program -- Command Interface.
107  */
108 #include <sys/types.h>
109 #include <sys/socket.h>
110 
111 #include <err.h>
112 #include <errno.h>
113 #include <netdb.h>
114 #include <paths.h>
115 #include <pwd.h>
116 #include <signal.h>
117 #include <stdio.h>
118 #include <stdlib.h>
119 #include <string.h>
120 #include <time.h>
121 #include <unistd.h>
122 #include <locale.h>
123 
124 #define	GLOBAL		/* force GLOBAL decls in ftp_var.h to be declared */
125 #include "ftp_var.h"
126 
127 #define	FTP_PROXY	"ftp_proxy"	/* env var with FTP proxy location */
128 #define	HTTP_PROXY	"http_proxy"	/* env var with HTTP proxy location */
129 #define	HTTPS_PROXY	"https_proxy"	/* env var with HTTPS proxy location */
130 #define	NO_PROXY	"no_proxy"	/* env var with list of non-proxied
131 					 * hosts, comma or space separated */
132 
133 static int	usage(void);
134 static int	usage_help(void);
135 static void	setupoption(const char *, const char *, const char *);
136 
137 int
138 main(int volatile argc, char **volatile argv)
139 {
140 	int ch, rval;
141 	struct passwd *pw;
142 	char *cp, *ep, *anonpass, *upload_path, *src_addr;
143 	const char *anonuser;
144 	int dumbterm, isupload;
145 	size_t len;
146 
147 	tzset();
148 	setlocale(LC_ALL, "");
149 	setprogname(argv[0]);
150 
151 	sigint_raised = 0;
152 
153 	ftpport = "ftp";
154 	httpport = "http";
155 #ifdef WITH_SSL
156 	httpsport = "https";
157 #endif
158 	gateport = NULL;
159 	cp = getenv("FTPSERVERPORT");
160 	if (cp != NULL)
161 		gateport = cp;
162 	else
163 		gateport = "ftpgate";
164 	doglob = 1;
165 	interactive = 1;
166 	autologin = 1;
167 	passivemode = 1;
168 	activefallback = 1;
169 	preserve = 1;
170 	verbose = 0;
171 	progress = 0;
172 	gatemode = 0;
173 	data = -1;
174 	outfile = NULL;
175 	restartautofetch = 0;
176 #ifndef NO_EDITCOMPLETE
177 	editing = 0;
178 	el = NULL;
179 	hist = NULL;
180 #endif
181 	bytes = 0;
182 	mark = HASHBYTES;
183 	rate_get = 0;
184 	rate_get_incr = DEFAULTINCR;
185 	rate_put = 0;
186 	rate_put_incr = DEFAULTINCR;
187 #ifdef INET6
188 	epsv4 = 1;
189 	epsv6 = 1;
190 #else
191 	epsv4 = 0;
192 	epsv6 = 0;
193 #endif
194 	epsv4bad = 0;
195 	epsv6bad = 0;
196 	src_addr = NULL;
197 	upload_path = NULL;
198 	isupload = 0;
199 	reply_callback = NULL;
200 #ifdef INET6
201 	family = AF_UNSPEC;
202 #else
203 	family = AF_INET;	/* force AF_INET if no INET6 support */
204 #endif
205 
206 	netrc[0] = '\0';
207 	cp = getenv("NETRC");
208 	if (cp != NULL && strlcpy(netrc, cp, sizeof(netrc)) >= sizeof(netrc))
209 		errx(1, "$NETRC `%s': %s", cp, strerror(ENAMETOOLONG));
210 
211 	marg_sl = ftp_sl_init();
212 	if ((tmpdir = getenv("TMPDIR")) == NULL)
213 		tmpdir = _PATH_TMP;
214 
215 	/* Set default operation mode based on FTPMODE environment variable */
216 	if ((cp = getenv("FTPMODE")) != NULL) {
217 		if (strcasecmp(cp, "passive") == 0) {
218 			passivemode = 1;
219 			activefallback = 0;
220 		} else if (strcasecmp(cp, "active") == 0) {
221 			passivemode = 0;
222 			activefallback = 0;
223 		} else if (strcasecmp(cp, "gate") == 0) {
224 			gatemode = 1;
225 		} else if (strcasecmp(cp, "auto") == 0) {
226 			passivemode = 1;
227 			activefallback = 1;
228 		} else
229 			warnx("Unknown $FTPMODE `%s'; using defaults", cp);
230 	}
231 
232 	if (strcmp(getprogname(), "pftp") == 0) {
233 		passivemode = 1;
234 		activefallback = 0;
235 	} else if (strcmp(getprogname(), "gate-ftp") == 0)
236 		gatemode = 1;
237 
238 	gateserver = getenv("FTPSERVER");
239 	if (gateserver == NULL || *gateserver == '\0')
240 		gateserver = GATE_SERVER;
241 	if (gatemode) {
242 		if (*gateserver == '\0') {
243 			warnx(
244 "Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp");
245 			gatemode = 0;
246 		}
247 	}
248 
249 	cp = getenv("TERM");
250 	if (cp == NULL || strcmp(cp, "dumb") == 0)
251 		dumbterm = 1;
252 	else
253 		dumbterm = 0;
254 	fromatty = isatty(fileno(stdin));
255 	ttyout = stdout;
256 	if (isatty(fileno(ttyout))) {
257 		verbose = 1;		/* verbose if to a tty */
258 		if (! dumbterm) {
259 #ifndef NO_EDITCOMPLETE
260 			if (fromatty)	/* editing mode on if tty is usable */
261 				editing = 1;
262 #endif
263 #ifndef NO_PROGRESS
264 			if (foregroundproc())
265 				progress = 1;	/* progress bar on if fg */
266 #endif
267 		}
268 	}
269 
270 	while ((ch = getopt(argc, argv, "?46AadefginN:o:pP:q:r:Rs:tT:u:vVx:")) != -1) {
271 		switch (ch) {
272 		case '4':
273 			family = AF_INET;
274 			break;
275 
276 		case '6':
277 #ifdef INET6
278 			family = AF_INET6;
279 #else
280 			warnx("INET6 support is not available; ignoring -6");
281 #endif
282 			break;
283 
284 		case 'A':
285 			activefallback = 0;
286 			passivemode = 0;
287 			break;
288 
289 		case 'a':
290 			anonftp = 1;
291 			break;
292 
293 		case 'd':
294 			options |= SO_DEBUG;
295 			ftp_debug++;
296 			break;
297 
298 		case 'e':
299 #ifndef NO_EDITCOMPLETE
300 			editing = 0;
301 #endif
302 			break;
303 
304 		case 'f':
305 			flushcache = 1;
306 			break;
307 
308 		case 'g':
309 			doglob = 0;
310 			break;
311 
312 		case 'i':
313 			interactive = 0;
314 			break;
315 
316 		case 'n':
317 			autologin = 0;
318 			break;
319 
320 		case 'N':
321 			if (strlcpy(netrc, optarg, sizeof(netrc))
322 			    >= sizeof(netrc))
323 				errx(1, "%s: %s", optarg,
324 				    strerror(ENAMETOOLONG));
325 			break;
326 
327 		case 'o':
328 			outfile = ftp_strdup(optarg);
329 			if (strcmp(outfile, "-") == 0)
330 				ttyout = stderr;
331 			break;
332 
333 		case 'p':
334 			passivemode = 1;
335 			activefallback = 0;
336 			break;
337 
338 		case 'P':
339 			ftpport = optarg;
340 			break;
341 
342 		case 'q':
343 			quit_time = strtol(optarg, &ep, 10);
344 			if (quit_time < 1 || *ep != '\0')
345 				errx(1, "Bad quit value: %s", optarg);
346 			break;
347 
348 		case 'r':
349 			retry_connect = strtol(optarg, &ep, 10);
350 			if (retry_connect < 1 || *ep != '\0')
351 				errx(1, "Bad retry value: %s", optarg);
352 			break;
353 
354 		case 'R':
355 			restartautofetch = 1;
356 			break;
357 
358 		case 's':
359 			src_addr = optarg;
360 			break;
361 
362 		case 't':
363 			trace = 1;
364 			break;
365 
366 		case 'T':
367 		{
368 			int targc;
369 			char *targv[6], *oac;
370 			char cmdbuf[MAX_C_NAME];
371 
372 				/* look for `dir,max[,incr]' */
373 			targc = 0;
374 			(void)strlcpy(cmdbuf, "-T", sizeof(cmdbuf));
375 			targv[targc++] = cmdbuf;
376 			oac = ftp_strdup(optarg);
377 
378 			while ((cp = strsep(&oac, ",")) != NULL) {
379 				if (*cp == '\0') {
380 					warnx("Bad throttle value `%s'",
381 					    optarg);
382 					return usage();
383 				}
384 				targv[targc++] = cp;
385 				if (targc >= 5)
386 					break;
387 			}
388 			if (parserate(targc, targv, 1) == -1) {
389 				return usage();
390 			}
391 			free(oac);
392 			break;
393 		}
394 
395 		case 'u':
396 		{
397 			isupload = 1;
398 			interactive = 0;
399 			upload_path = ftp_strdup(optarg);
400 
401 			break;
402 		}
403 
404 		case 'v':
405 			progress = verbose = 1;
406 			break;
407 
408 		case 'V':
409 			progress = verbose = 0;
410 			break;
411 
412 		case 'x':
413 			sndbuf_size = strsuftoi(optarg);
414 			if (sndbuf_size < 1)
415 				errx(1, "Bad xferbuf value: %s", optarg);
416 			rcvbuf_size = sndbuf_size;
417 			break;
418 
419 		case '?':
420 			if (optopt == '?') {
421 				return usage_help();
422 			}
423 			return usage();
424 
425 		default:
426 			errx(1, "unimplemented option -%c", ch);
427 		}
428 	}
429 			/* set line buffering on ttyout */
430 	setvbuf(ttyout, NULL, _IOLBF, 0);
431 	argc -= optind;
432 	argv += optind;
433 
434 	cpend = 0;	/* no pending replies */
435 	proxy = 0;	/* proxy not active */
436 	crflag = 1;	/* strip c.r. on ascii gets */
437 	sendport = -1;	/* not using ports */
438 
439 	if (src_addr != NULL) {
440 		struct addrinfo hints;
441 		int error;
442 
443 		memset(&hints, 0, sizeof(hints));
444 		hints.ai_family = family;
445 		hints.ai_socktype = SOCK_STREAM;
446 		hints.ai_flags = AI_PASSIVE;
447 		error = getaddrinfo(src_addr, NULL, &hints, &bindai);
448 		if (error) {
449 		    	errx(1, "Can't lookup `%s': %s", src_addr,
450 			    (error == EAI_SYSTEM) ? strerror(errno)
451 						  : gai_strerror(error));
452 		}
453 	}
454 
455 	/*
456 	 * Cache the user name and home directory.
457 	 */
458 	localhome = NULL;
459 	localname = NULL;
460 	anonuser = "anonymous";
461 	cp = getenv("HOME");
462 	if (! EMPTYSTRING(cp))
463 		localhome = ftp_strdup(cp);
464 	pw = NULL;
465 	cp = getlogin();
466 	if (cp != NULL)
467 		pw = getpwnam(cp);
468 	if (pw == NULL)
469 		pw = getpwuid(getuid());
470 	if (pw != NULL) {
471 		if (localhome == NULL && !EMPTYSTRING(pw->pw_dir))
472 			localhome = ftp_strdup(pw->pw_dir);
473 		localname = ftp_strdup(pw->pw_name);
474 	}
475 	if (netrc[0] == '\0' && localhome != NULL) {
476 		if (strlcpy(netrc, localhome, sizeof(netrc)) >= sizeof(netrc) ||
477 		    strlcat(netrc, "/.netrc", sizeof(netrc)) >= sizeof(netrc)) {
478 			warnx("%s/.netrc: %s", localhome,
479 			    strerror(ENAMETOOLONG));
480 			netrc[0] = '\0';
481 		}
482 	}
483 	if (localhome == NULL)
484 		localhome = ftp_strdup("/");
485 
486 	/*
487 	 * Every anonymous FTP server I've encountered will accept the
488 	 * string "username@", and will append the hostname itself. We
489 	 * do this by default since many servers are picky about not
490 	 * having a FQDN in the anonymous password.
491 	 * - thorpej@NetBSD.org
492 	 */
493 	len = strlen(anonuser) + 2;
494 	anonpass = ftp_malloc(len);
495 	(void)strlcpy(anonpass, anonuser, len);
496 	(void)strlcat(anonpass, "@",	  len);
497 
498 			/*
499 			 * set all the defaults for options defined in
500 			 * struct option optiontab[]  declared in cmdtab.c
501 			 */
502 	setupoption("anonpass",		getenv("FTPANONPASS"),	anonpass);
503 	setupoption("ftp_proxy",	getenv(FTP_PROXY),	"");
504 	setupoption("http_proxy",	getenv(HTTP_PROXY),	"");
505 	setupoption("https_proxy",	getenv(HTTPS_PROXY),	"");
506 	setupoption("no_proxy",		getenv(NO_PROXY),	"");
507 	setupoption("pager",		getenv("PAGER"),	DEFAULTPAGER);
508 	setupoption("prompt",		getenv("FTPPROMPT"),	DEFAULTPROMPT);
509 	setupoption("rprompt",		getenv("FTPRPROMPT"),	DEFAULTRPROMPT);
510 
511 	free(anonpass);
512 
513 	setttywidth(0);
514 #ifdef SIGINFO
515 	(void)xsignal(SIGINFO, psummary);
516 #endif
517 	(void)xsignal(SIGQUIT, psummary);
518 	(void)xsignal(SIGUSR1, crankrate);
519 	(void)xsignal(SIGUSR2, crankrate);
520 	(void)xsignal(SIGWINCH, setttywidth);
521 
522 	if (argc > 0) {
523 		if (isupload) {
524 			rval = auto_put(argc, argv, upload_path);
525  sigint_or_rval_exit:
526 			if (sigint_raised) {
527 				(void)xsignal(SIGINT, SIG_DFL);
528 				raise(SIGINT);
529 			}
530 			exit(rval);
531 		} else if (strchr(argv[0], ':') != NULL
532 			    && ! isipv6addr(argv[0])) {
533 			rval = auto_fetch(argc, argv);
534 			if (rval >= 0)		/* -1 == connected and cd-ed */
535 				goto sigint_or_rval_exit;
536 		} else {
537 			char *xargv[4], *uuser, *host;
538 			char cmdbuf[MAXPATHLEN];
539 
540 			if ((rval = sigsetjmp(toplevel, 1)))
541 				goto sigint_or_rval_exit;
542 			(void)xsignal(SIGINT, intr);
543 			(void)xsignal(SIGPIPE, lostpeer);
544 			uuser = NULL;
545 			host = argv[0];
546 			cp = strchr(host, '@');
547 			if (cp) {
548 				*cp = '\0';
549 				uuser = host;
550 				host = cp + 1;
551 			}
552 			(void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
553 			xargv[0] = cmdbuf;
554 			xargv[1] = host;
555 			xargv[2] = argv[1];
556 			xargv[3] = NULL;
557 			do {
558 				int oautologin;
559 
560 				oautologin = autologin;
561 				if (uuser != NULL) {
562 					anonftp = 0;
563 					autologin = 0;
564 				}
565 				setpeer(argc+1, xargv);
566 				autologin = oautologin;
567 				if (connected == 1 && uuser != NULL)
568 					(void)ftp_login(host, uuser, NULL);
569 				if (!retry_connect)
570 					break;
571 				if (!connected) {
572 					macnum = 0;
573 					fprintf(ttyout,
574 					    "Retrying in %d seconds...\n",
575 					    retry_connect);
576 					sleep(retry_connect);
577 				}
578 			} while (!connected);
579 			retry_connect = 0; /* connected, stop hiding msgs */
580 		}
581 	}
582 	if (isupload) {
583 		return usage();
584 	}
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 				justquit();
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 				justquit();
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, (void *)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 			case 1:
848 				slrflag++;
849 				altarg = stringbase;
850 				break;
851 			default:
852 				break;
853 		}
854 	}
855 
856 S0:
857 	switch (*sb) {
858 
859 	case '\0':
860 		goto OUT;
861 
862 	case ' ':
863 	case '\t':
864 		INC_CHKCURSOR(sb);
865 		goto S0;
866 
867 	default:
868 		switch (slrflag) {
869 			case 0:
870 				slrflag++;
871 				break;
872 			case 1:
873 				slrflag++;
874 				altarg = sb;
875 				break;
876 			default:
877 				break;
878 		}
879 		goto S1;
880 	}
881 
882 S1:
883 	switch (*sb) {
884 
885 	case ' ':
886 	case '\t':
887 	case '\0':
888 		goto OUT;	/* end of token */
889 
890 	case '\\':
891 		INC_CHKCURSOR(sb);
892 		goto S2;	/* slurp next character */
893 
894 	case '"':
895 		INC_CHKCURSOR(sb);
896 		goto S3;	/* slurp quoted string */
897 
898 	default:
899 		*ap = *sb;	/* add character to token */
900 		ap++;
901 		INC_CHKCURSOR(sb);
902 		got_one = 1;
903 		goto S1;
904 	}
905 
906 S2:
907 	switch (*sb) {
908 
909 	case '\0':
910 		goto OUT;
911 
912 	default:
913 		*ap = *sb;
914 		ap++;
915 		INC_CHKCURSOR(sb);
916 		got_one = 1;
917 		goto S1;
918 	}
919 
920 S3:
921 	switch (*sb) {
922 
923 	case '\0':
924 		goto OUT;
925 
926 	case '"':
927 		INC_CHKCURSOR(sb);
928 		goto S1;
929 
930 	default:
931 		*ap = *sb;
932 		ap++;
933 		INC_CHKCURSOR(sb);
934 		got_one = 1;
935 		goto S3;
936 	}
937 
938 OUT:
939 	if (got_one)
940 		*ap++ = '\0';
941 	argbase = ap;			/* update storage pointer */
942 	stringbase = sb;		/* update scan pointer */
943 	if (got_one) {
944 		return (tmp);
945 	}
946 	switch (slrflag) {
947 		case 0:
948 			slrflag++;
949 			break;
950 		case 1:
951 			slrflag++;
952 			altarg = NULL;
953 			break;
954 		default:
955 			break;
956 	}
957 	return (NULL);
958 }
959 
960 /*
961  * Help/usage command.
962  * Call each command handler with argc == 0 and argv[0] == name.
963  */
964 void
965 help(int argc, char *argv[])
966 {
967 	struct cmd *c;
968 	char *nargv[1], *cmd;
969 	const char *p;
970 	int isusage;
971 
972 	cmd = argv[0];
973 	isusage = (strcmp(cmd, "usage") == 0);
974 	if (argc == 0 || (isusage && argc == 1)) {
975 		UPRINTF("usage: %s [command ...]\n", cmd);
976 		return;
977 	}
978 	if (argc == 1) {
979 		StringList *buf;
980 
981 		buf = ftp_sl_init();
982 		fprintf(ttyout,
983 		    "%sommands may be abbreviated.  Commands are:\n\n",
984 		    proxy ? "Proxy c" : "C");
985 		for (c = cmdtab; (p = c->c_name) != NULL; c++)
986 			if (!proxy || c->c_proxy)
987 				ftp_sl_add(buf, ftp_strdup(p));
988 		list_vertical(buf);
989 		sl_free(buf, 1);
990 		return;
991 	}
992 
993 #define	HELPINDENT ((int) sizeof("disconnect"))
994 
995 	while (--argc > 0) {
996 		char *arg;
997 		char cmdbuf[MAX_C_NAME];
998 
999 		arg = *++argv;
1000 		c = getcmd(arg);
1001 		if (c == (struct cmd *)-1)
1002 			fprintf(ttyout, "?Ambiguous %s command `%s'\n",
1003 			    cmd, arg);
1004 		else if (c == NULL)
1005 			fprintf(ttyout, "?Invalid %s command `%s'\n",
1006 			    cmd, arg);
1007 		else {
1008 			if (isusage) {
1009 				(void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf));
1010 				nargv[0] = cmdbuf;
1011 				(*c->c_handler)(0, nargv);
1012 			} else
1013 				fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
1014 				    c->c_name, c->c_help);
1015 		}
1016 	}
1017 }
1018 
1019 struct option *
1020 getoption(const char *name)
1021 {
1022 	const char *p;
1023 	struct option *c;
1024 
1025 	if (name == NULL)
1026 		return (NULL);
1027 	for (c = optiontab; (p = c->name) != NULL; c++) {
1028 		if (strcasecmp(p, name) == 0)
1029 			return (c);
1030 	}
1031 	return (NULL);
1032 }
1033 
1034 char *
1035 getoptionvalue(const char *name)
1036 {
1037 	struct option *c;
1038 
1039 	if (name == NULL)
1040 		errx(1, "getoptionvalue: invoked with NULL name");
1041 	c = getoption(name);
1042 	if (c != NULL)
1043 		return (c->value);
1044 	errx(1, "getoptionvalue: invoked with unknown option `%s'", name);
1045 	/* NOTREACHED */
1046 }
1047 
1048 static void
1049 setupoption(const char *name, const char *value, const char *defaultvalue)
1050 {
1051 	set_option(name, value ? value : defaultvalue, 0);
1052 }
1053 
1054 static void
1055 synopsis(FILE * stream)
1056 {
1057 	const char * progname = getprogname();
1058 
1059 	fprintf(stream,
1060 "usage: %s [-46AadefginpRtVv] [-N NETRC] [-o OUTPUT] [-P PORT] [-q QUITTIME]\n"
1061 "           [-r RETRY] [-s SRCADDR] [-T DIR,MAX[,INC]] [-x XFERSIZE]\n"
1062 "           [[USER@]HOST [PORT]]\n"
1063 "           [[USER@]HOST:[PATH][/]]\n"
1064 "           [file:///PATH]\n"
1065 "           [ftp://[USER[:PASSWORD]@]HOST[:PORT]/PATH[/][;type=TYPE]]\n"
1066 "           [http://[USER[:PASSWORD]@]HOST[:PORT]/PATH]\n"
1067 #ifdef WITH_SSL
1068 "           [https://[USER[:PASSWORD]@]HOST[:PORT]/PATH]\n"
1069 #endif
1070 "           ...\n"
1071 "       %s -u URL FILE ...\n"
1072 "       %s -?\n",
1073 		progname, progname, progname);
1074 }
1075 
1076 static int
1077 usage_help(void)
1078 {
1079 	synopsis(stdout);
1080 #ifndef NO_USAGE
1081 	printf(
1082 "  -4            Only use IPv4 addresses\n"
1083 "  -6            Only use IPv6 addresses\n"
1084 "  -A            Force active mode\n"
1085 "  -a            Use anonymous login\n"
1086 "  -d            Enable debugging\n"
1087 "  -e            Disable command-line editing\n"
1088 "  -f            Force cache reload for FTP or HTTP proxy transfers\n"
1089 "  -g            Disable file name globbing\n"
1090 "  -i            Disable interactive prompt during multiple file transfers\n"
1091 "  -N NETRC      Use NETRC instead of ~/.netrc\n"
1092 "  -n            Disable auto-login\n"
1093 "  -o OUTPUT     Save auto-fetched files to OUTPUT\n"
1094 "  -P PORT       Use port PORT\n"
1095 "  -p            Force passive mode\n"
1096 "  -q QUITTIME   Quit if connection stalls for QUITTIME seconds\n"
1097 "  -R            Restart non-proxy auto-fetch\n"
1098 "  -r RETRY      Retry failed connection attempts after RETRY seconds\n"
1099 "  -s SRCADDR    Use source address SRCADDR\n"
1100 "  -t            Enable packet tracing\n"
1101 "  -T DIR,MAX[,INC]\n"
1102 "                Set maximum transfer rate for direction DIR to MAX bytes/s,\n"
1103 "                with optional increment INC bytes/s\n"
1104 "  -u URL        URL to upload file arguments to\n"
1105 "  -V            Disable verbose and progress\n"
1106 "  -v            Enable verbose and progress\n"
1107 "  -x XFERSIZE   Set socket send and receive size to XFERSIZE\n"
1108 "  -?            Display this help and exit\n"
1109 		);
1110 #endif
1111 	return EXIT_SUCCESS;
1112 }
1113 
1114 static int
1115 usage(void)
1116 {
1117 	synopsis(stderr);
1118 	return EXIT_FAILURE;
1119 }
1120