xref: /netbsd-src/usr.bin/ftp/main.c (revision b0d1725196a7921d003d2c66a14f186abda4176b)
1 /*	$NetBSD: main.c,v 1.129 2023/02/25 12:07:25 mlelstv Exp $	*/
2 
3 /*-
4  * Copyright (c) 1996-2023 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.129 2023/02/25 12:07:25 mlelstv 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 			warnx("-%c: unknown option", optopt);
424 			return usage();
425 
426 		case ':':
427 			warnx("-%c: missing argument", optopt);
428 			return usage();
429 
430 		default:
431 			errx(1, "unimplemented option -%c", ch);
432 		}
433 	}
434 			/* set line buffering on ttyout */
435 	setvbuf(ttyout, NULL, _IOLBF, 0);
436 	argc -= optind;
437 	argv += optind;
438 
439 	cpend = 0;	/* no pending replies */
440 	proxy = 0;	/* proxy not active */
441 	crflag = 1;	/* strip c.r. on ascii gets */
442 	sendport = -1;	/* not using ports */
443 
444 	if (src_addr != NULL) {
445 		struct addrinfo hints;
446 		int error;
447 
448 		memset(&hints, 0, sizeof(hints));
449 		hints.ai_family = family;
450 		hints.ai_socktype = SOCK_STREAM;
451 		hints.ai_flags = AI_PASSIVE;
452 		error = getaddrinfo(src_addr, NULL, &hints, &bindai);
453 		if (error) {
454 		    	errx(1, "Can't lookup `%s': %s", src_addr,
455 			    (error == EAI_SYSTEM) ? strerror(errno)
456 						  : gai_strerror(error));
457 		}
458 	}
459 
460 	/*
461 	 * Cache the user name and home directory.
462 	 */
463 	localhome = NULL;
464 	localname = NULL;
465 	anonuser = "anonymous";
466 	cp = getenv("HOME");
467 	if (! EMPTYSTRING(cp))
468 		localhome = ftp_strdup(cp);
469 	pw = NULL;
470 	cp = getlogin();
471 	if (cp != NULL)
472 		pw = getpwnam(cp);
473 	if (pw == NULL)
474 		pw = getpwuid(getuid());
475 	if (pw != NULL) {
476 		if (localhome == NULL && !EMPTYSTRING(pw->pw_dir))
477 			localhome = ftp_strdup(pw->pw_dir);
478 		localname = ftp_strdup(pw->pw_name);
479 	}
480 	if (netrc[0] == '\0' && localhome != NULL) {
481 		if (strlcpy(netrc, localhome, sizeof(netrc)) >= sizeof(netrc) ||
482 		    strlcat(netrc, "/.netrc", sizeof(netrc)) >= sizeof(netrc)) {
483 			warnx("%s/.netrc: %s", localhome,
484 			    strerror(ENAMETOOLONG));
485 			netrc[0] = '\0';
486 		}
487 	}
488 	if (localhome == NULL)
489 		localhome = ftp_strdup("/");
490 
491 	/*
492 	 * Every anonymous FTP server I've encountered will accept the
493 	 * string "username@", and will append the hostname itself. We
494 	 * do this by default since many servers are picky about not
495 	 * having a FQDN in the anonymous password.
496 	 * - thorpej@NetBSD.org
497 	 */
498 	len = strlen(anonuser) + 2;
499 	anonpass = ftp_malloc(len);
500 	(void)strlcpy(anonpass, anonuser, len);
501 	(void)strlcat(anonpass, "@",	  len);
502 
503 			/*
504 			 * set all the defaults for options defined in
505 			 * struct option optiontab[]  declared in cmdtab.c
506 			 */
507 	setupoption("anonpass",		getenv("FTPANONPASS"),	anonpass);
508 	setupoption("ftp_proxy",	getenv(FTP_PROXY),	"");
509 	setupoption("http_proxy",	getenv(HTTP_PROXY),	"");
510 	setupoption("https_proxy",	getenv(HTTPS_PROXY),	"");
511 	setupoption("no_proxy",		getenv(NO_PROXY),	"");
512 	setupoption("pager",		getenv("PAGER"),	DEFAULTPAGER);
513 	setupoption("prompt",		getenv("FTPPROMPT"),	DEFAULTPROMPT);
514 	setupoption("rprompt",		getenv("FTPRPROMPT"),	DEFAULTRPROMPT);
515 	setupoption("sslnoverify",   	getenv("FTPSSLNOVERIFY"),	"");
516 
517 	free(anonpass);
518 
519 	setttywidth(0);
520 #ifdef SIGINFO
521 	(void)xsignal(SIGINFO, psummary);
522 #endif
523 	(void)xsignal(SIGQUIT, psummary);
524 	(void)xsignal(SIGUSR1, crankrate);
525 	(void)xsignal(SIGUSR2, crankrate);
526 	(void)xsignal(SIGWINCH, setttywidth);
527 
528 	if (argc > 0) {
529 		if (isupload) {
530 			rval = auto_put(argc, argv, upload_path);
531  sigint_or_rval_exit:
532 			if (sigint_raised) {
533 				(void)xsignal(SIGINT, SIG_DFL);
534 				raise(SIGINT);
535 			}
536 			exit(rval);
537 		} else if (strchr(argv[0], ':') != NULL
538 			    && ! isipv6addr(argv[0])) {
539 			rval = auto_fetch(argc, argv);
540 			if (rval >= 0)		/* -1 == connected and cd-ed */
541 				goto sigint_or_rval_exit;
542 		} else {
543 			char *xargv[4], *uuser, *host;
544 			char cmdbuf[MAXPATHLEN];
545 
546 			if ((rval = sigsetjmp(toplevel, 1)))
547 				goto sigint_or_rval_exit;
548 			(void)xsignal(SIGINT, intr);
549 			(void)xsignal(SIGPIPE, lostpeer);
550 			uuser = NULL;
551 			host = argv[0];
552 			cp = strchr(host, '@');
553 			if (cp) {
554 				*cp = '\0';
555 				uuser = host;
556 				host = cp + 1;
557 			}
558 			(void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
559 			xargv[0] = cmdbuf;
560 			xargv[1] = host;
561 			xargv[2] = argv[1];
562 			xargv[3] = NULL;
563 			do {
564 				int oautologin;
565 
566 				oautologin = autologin;
567 				if (uuser != NULL) {
568 					anonftp = 0;
569 					autologin = 0;
570 				}
571 				setpeer(argc+1, xargv);
572 				autologin = oautologin;
573 				if (connected == 1 && uuser != NULL)
574 					(void)ftp_login(host, uuser, NULL);
575 				if (!retry_connect)
576 					break;
577 				if (!connected) {
578 					macnum = 0;
579 					fprintf(ttyout,
580 					    "Retrying in %d seconds...\n",
581 					    retry_connect);
582 					sleep(retry_connect);
583 				}
584 			} while (!connected);
585 			retry_connect = 0; /* connected, stop hiding msgs */
586 		}
587 	}
588 	if (isupload) {
589 		return usage();
590 	}
591 
592 #ifndef NO_EDITCOMPLETE
593 	controlediting();
594 #endif /* !NO_EDITCOMPLETE */
595 
596 	(void)sigsetjmp(toplevel, 1);
597 	(void)xsignal(SIGINT, intr);
598 	(void)xsignal(SIGPIPE, lostpeer);
599 	for (;;)
600 		cmdscanner();
601 }
602 
603 /*
604  * Generate a prompt
605  */
606 char *
607 prompt(void)
608 {
609 	static char	**promptopt;
610 	static char	  buf[MAXPATHLEN];
611 
612 	if (promptopt == NULL) {
613 		struct option *o;
614 
615 		o = getoption("prompt");
616 		if (o == NULL)
617 			errx(1, "prompt: no such option `prompt'");
618 		promptopt = &(o->value);
619 	}
620 	formatbuf(buf, sizeof(buf), *promptopt ? *promptopt : DEFAULTPROMPT);
621 	return (buf);
622 }
623 
624 /*
625  * Generate an rprompt
626  */
627 char *
628 rprompt(void)
629 {
630 	static char	**rpromptopt;
631 	static char	  buf[MAXPATHLEN];
632 
633 	if (rpromptopt == NULL) {
634 		struct option *o;
635 
636 		o = getoption("rprompt");
637 		if (o == NULL)
638 			errx(1, "rprompt: no such option `rprompt'");
639 		rpromptopt = &(o->value);
640 	}
641 	formatbuf(buf, sizeof(buf), *rpromptopt ? *rpromptopt : DEFAULTRPROMPT);
642 	return (buf);
643 }
644 
645 /*
646  * Command parser.
647  */
648 void
649 cmdscanner(void)
650 {
651 	struct cmd	*c;
652 	char		*p;
653 #ifndef NO_EDITCOMPLETE
654 	int		 ch;
655 	size_t		 num;
656 #endif
657 	int		 len;
658 	char		 cmdbuf[MAX_C_NAME];
659 
660 	for (;;) {
661 #ifndef NO_EDITCOMPLETE
662 		if (!editing) {
663 #endif /* !NO_EDITCOMPLETE */
664 			if (fromatty) {
665 				fputs(prompt(), ttyout);
666 				p = rprompt();
667 				if (*p)
668 					fprintf(ttyout, "%s ", p);
669 			}
670 			(void)fflush(ttyout);
671 			len = get_line(stdin, line, sizeof(line), NULL);
672 			switch (len) {
673 			case -1:	/* EOF */
674 			case -2:	/* error */
675 				if (fromatty)
676 					putc('\n', ttyout);
677 				justquit();
678 				/* NOTREACHED */
679 			case -3:	/* too long; try again */
680 				fputs("Sorry, input line is too long.\n",
681 				    ttyout);
682 				continue;
683 			case 0:		/* empty; try again */
684 				continue;
685 			default:	/* all ok */
686 				break;
687 			}
688 #ifndef NO_EDITCOMPLETE
689 		} else {
690 			const char *buf;
691 			HistEvent ev;
692 			cursor_pos = NULL;
693 
694 			buf = el_gets(el, &ch);
695 			num = ch;
696 			if (buf == NULL || num == 0) {
697 				if (fromatty)
698 					putc('\n', ttyout);
699 				justquit();
700 			}
701 			if (num >= sizeof(line)) {
702 				fputs("Sorry, input line is too long.\n",
703 				    ttyout);
704 				break;
705 			}
706 			memcpy(line, buf, num);
707 			if (line[--num] == '\n') {
708 				line[num] = '\0';
709 				if (num == 0)
710 					break;
711 			}
712 			history(hist, &ev, H_ENTER, buf);
713 		}
714 #endif /* !NO_EDITCOMPLETE */
715 
716 		makeargv();
717 		if (margc == 0)
718 			continue;
719 		c = getcmd(margv[0]);
720 		if (c == (struct cmd *)-1) {
721 			fputs("?Ambiguous command.\n", ttyout);
722 			continue;
723 		}
724 		if (c == NULL) {
725 #if !defined(NO_EDITCOMPLETE)
726 			/*
727 			 * attempt to el_parse() unknown commands.
728 			 * any command containing a ':' would be parsed
729 			 * as "[prog:]cmd ...", and will result in a
730 			 * false positive if prog != "ftp", so treat
731 			 * such commands as invalid.
732 			 */
733 			if (strchr(margv[0], ':') != NULL ||
734 			    !editing ||
735 			    el_parse(el, margc, (void *)margv) != 0)
736 #endif /* !NO_EDITCOMPLETE */
737 				fputs("?Invalid command.\n", ttyout);
738 			continue;
739 		}
740 		if (c->c_conn && !connected) {
741 			fputs("Not connected.\n", ttyout);
742 			continue;
743 		}
744 		confirmrest = 0;
745 		(void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf));
746 		margv[0] = cmdbuf;
747 		(*c->c_handler)(margc, margv);
748 		if (bell && c->c_bell)
749 			(void)putc('\007', ttyout);
750 		if (c->c_handler != help)
751 			break;
752 	}
753 	(void)xsignal(SIGINT, intr);
754 	(void)xsignal(SIGPIPE, lostpeer);
755 }
756 
757 struct cmd *
758 getcmd(const char *name)
759 {
760 	const char *p, *q;
761 	struct cmd *c, *found;
762 	int nmatches, longest;
763 
764 	if (name == NULL)
765 		return (0);
766 
767 	longest = 0;
768 	nmatches = 0;
769 	found = 0;
770 	for (c = cmdtab; (p = c->c_name) != NULL; c++) {
771 		for (q = name; *q == *p++; q++)
772 			if (*q == 0)		/* exact match? */
773 				return (c);
774 		if (!*q) {			/* the name was a prefix */
775 			if (q - name > longest) {
776 				longest = q - name;
777 				nmatches = 1;
778 				found = c;
779 			} else if (q - name == longest)
780 				nmatches++;
781 		}
782 	}
783 	if (nmatches > 1)
784 		return ((struct cmd *)-1);
785 	return (found);
786 }
787 
788 /*
789  * Slice a string up into argc/argv.
790  */
791 
792 int slrflag;
793 
794 void
795 makeargv(void)
796 {
797 	char *argp;
798 
799 	stringbase = line;		/* scan from first of buffer */
800 	argbase = argbuf;		/* store from first of buffer */
801 	slrflag = 0;
802 	marg_sl->sl_cur = 0;		/* reset to start of marg_sl */
803 	for (margc = 0; ; margc++) {
804 		argp = slurpstring();
805 		ftp_sl_add(marg_sl, argp);
806 		if (argp == NULL)
807 			break;
808 	}
809 #ifndef NO_EDITCOMPLETE
810 	if (cursor_pos == line) {
811 		cursor_argc = 0;
812 		cursor_argo = 0;
813 	} else if (cursor_pos != NULL) {
814 		cursor_argc = margc;
815 		cursor_argo = strlen(margv[margc-1]);
816 	}
817 #endif /* !NO_EDITCOMPLETE */
818 }
819 
820 #ifdef NO_EDITCOMPLETE
821 #define	INC_CHKCURSOR(x)	(x)++
822 #else  /* !NO_EDITCOMPLETE */
823 #define	INC_CHKCURSOR(x)	{ (x)++ ; \
824 				if (x == cursor_pos) { \
825 					cursor_argc = margc; \
826 					cursor_argo = ap-argbase; \
827 					cursor_pos = NULL; \
828 				} }
829 
830 #endif /* !NO_EDITCOMPLETE */
831 
832 /*
833  * Parse string into argbuf;
834  * implemented with FSM to
835  * handle quoting and strings
836  */
837 char *
838 slurpstring(void)
839 {
840 	static char bangstr[2] = { '!', '\0' };
841 	static char dollarstr[2] = { '$', '\0' };
842 	int got_one = 0;
843 	char *sb = stringbase;
844 	char *ap = argbase;
845 	char *tmp = argbase;		/* will return this if token found */
846 
847 	if (*sb == '!' || *sb == '$') {	/* recognize ! as a token for shell */
848 		switch (slrflag) {	/* and $ as token for macro invoke */
849 			case 0:
850 				slrflag++;
851 				INC_CHKCURSOR(stringbase);
852 				return ((*sb == '!') ? bangstr : dollarstr);
853 			case 1:
854 				slrflag++;
855 				altarg = stringbase;
856 				break;
857 			default:
858 				break;
859 		}
860 	}
861 
862 S0:
863 	switch (*sb) {
864 
865 	case '\0':
866 		goto OUT;
867 
868 	case ' ':
869 	case '\t':
870 		INC_CHKCURSOR(sb);
871 		goto S0;
872 
873 	default:
874 		switch (slrflag) {
875 			case 0:
876 				slrflag++;
877 				break;
878 			case 1:
879 				slrflag++;
880 				altarg = sb;
881 				break;
882 			default:
883 				break;
884 		}
885 		goto S1;
886 	}
887 
888 S1:
889 	switch (*sb) {
890 
891 	case ' ':
892 	case '\t':
893 	case '\0':
894 		goto OUT;	/* end of token */
895 
896 	case '\\':
897 		INC_CHKCURSOR(sb);
898 		goto S2;	/* slurp next character */
899 
900 	case '"':
901 		INC_CHKCURSOR(sb);
902 		goto S3;	/* slurp quoted string */
903 
904 	default:
905 		*ap = *sb;	/* add character to token */
906 		ap++;
907 		INC_CHKCURSOR(sb);
908 		got_one = 1;
909 		goto S1;
910 	}
911 
912 S2:
913 	switch (*sb) {
914 
915 	case '\0':
916 		goto OUT;
917 
918 	default:
919 		*ap = *sb;
920 		ap++;
921 		INC_CHKCURSOR(sb);
922 		got_one = 1;
923 		goto S1;
924 	}
925 
926 S3:
927 	switch (*sb) {
928 
929 	case '\0':
930 		goto OUT;
931 
932 	case '"':
933 		INC_CHKCURSOR(sb);
934 		goto S1;
935 
936 	default:
937 		*ap = *sb;
938 		ap++;
939 		INC_CHKCURSOR(sb);
940 		got_one = 1;
941 		goto S3;
942 	}
943 
944 OUT:
945 	if (got_one)
946 		*ap++ = '\0';
947 	argbase = ap;			/* update storage pointer */
948 	stringbase = sb;		/* update scan pointer */
949 	if (got_one) {
950 		return (tmp);
951 	}
952 	switch (slrflag) {
953 		case 0:
954 			slrflag++;
955 			break;
956 		case 1:
957 			slrflag++;
958 			altarg = NULL;
959 			break;
960 		default:
961 			break;
962 	}
963 	return (NULL);
964 }
965 
966 /*
967  * Help/usage command.
968  * Call each command handler with argc == 0 and argv[0] == name.
969  */
970 void
971 help(int argc, char *argv[])
972 {
973 	struct cmd *c;
974 	char *nargv[1], *cmd;
975 	const char *p;
976 	int isusage;
977 
978 	cmd = argv[0];
979 	isusage = (strcmp(cmd, "usage") == 0);
980 	if (argc == 0 || (isusage && argc == 1)) {
981 		UPRINTF("usage: %s [command ...]\n", cmd);
982 		return;
983 	}
984 	if (argc == 1) {
985 		StringList *buf;
986 
987 		buf = ftp_sl_init();
988 		fprintf(ttyout,
989 		    "%sommands may be abbreviated.  Commands are:\n\n",
990 		    proxy ? "Proxy c" : "C");
991 		for (c = cmdtab; (p = c->c_name) != NULL; c++)
992 			if (!proxy || c->c_proxy)
993 				ftp_sl_add(buf, ftp_strdup(p));
994 		list_vertical(buf);
995 		sl_free(buf, 1);
996 		return;
997 	}
998 
999 #define	HELPINDENT ((int) sizeof("disconnect"))
1000 
1001 	while (--argc > 0) {
1002 		char *arg;
1003 		char cmdbuf[MAX_C_NAME];
1004 
1005 		arg = *++argv;
1006 		c = getcmd(arg);
1007 		if (c == (struct cmd *)-1)
1008 			fprintf(ttyout, "?Ambiguous %s command `%s'\n",
1009 			    cmd, arg);
1010 		else if (c == NULL)
1011 			fprintf(ttyout, "?Invalid %s command `%s'\n",
1012 			    cmd, arg);
1013 		else {
1014 			if (isusage) {
1015 				(void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf));
1016 				nargv[0] = cmdbuf;
1017 				(*c->c_handler)(0, nargv);
1018 			} else
1019 				fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
1020 				    c->c_name, c->c_help);
1021 		}
1022 	}
1023 }
1024 
1025 struct option *
1026 getoption(const char *name)
1027 {
1028 	const char *p;
1029 	struct option *c;
1030 
1031 	if (name == NULL)
1032 		return (NULL);
1033 	for (c = optiontab; (p = c->name) != NULL; c++) {
1034 		if (strcasecmp(p, name) == 0)
1035 			return (c);
1036 	}
1037 	return (NULL);
1038 }
1039 
1040 char *
1041 getoptionvalue(const char *name)
1042 {
1043 	struct option *c;
1044 
1045 	if (name == NULL)
1046 		errx(1, "getoptionvalue: invoked with NULL name");
1047 	c = getoption(name);
1048 	if (c != NULL)
1049 		return (c->value);
1050 	errx(1, "getoptionvalue: invoked with unknown option `%s'", name);
1051 	/* NOTREACHED */
1052 }
1053 
1054 static void
1055 setupoption(const char *name, const char *value, const char *defaultvalue)
1056 {
1057 	set_option(name, value ? value : defaultvalue, 0);
1058 }
1059 
1060 static void
1061 synopsis(FILE * stream)
1062 {
1063 	const char * progname = getprogname();
1064 
1065 	fprintf(stream,
1066 "usage: %s [-46AadefginpRtVv] [-N NETRC] [-o OUTPUT] [-P PORT] [-q QUITTIME]\n"
1067 "           [-r RETRY] [-s SRCADDR] [-T DIR,MAX[,INC]] [-x XFERSIZE]\n"
1068 "           [[USER@]HOST [PORT]]\n"
1069 "           [[USER@]HOST:[PATH][/]]\n"
1070 "           [file:///PATH]\n"
1071 "           [ftp://[USER[:PASSWORD]@]HOST[:PORT]/PATH[/][;type=TYPE]]\n"
1072 "           [http://[USER[:PASSWORD]@]HOST[:PORT]/PATH]\n"
1073 #ifdef WITH_SSL
1074 "           [https://[USER[:PASSWORD]@]HOST[:PORT]/PATH]\n"
1075 #endif
1076 "           ...\n"
1077 "       %s -u URL FILE ...\n"
1078 "       %s -?\n",
1079 		progname, progname, progname);
1080 }
1081 
1082 static int
1083 usage_help(void)
1084 {
1085 	synopsis(stdout);
1086 #ifndef NO_USAGE
1087 	printf(
1088 "  -4            Only use IPv4 addresses\n"
1089 "  -6            Only use IPv6 addresses\n"
1090 "  -A            Force active mode\n"
1091 "  -a            Use anonymous login\n"
1092 "  -d            Enable debugging\n"
1093 "  -e            Disable command-line editing\n"
1094 "  -f            Force cache reload for FTP or HTTP proxy transfers\n"
1095 "  -g            Disable file name globbing\n"
1096 "  -i            Disable interactive prompt during multiple file transfers\n"
1097 "  -N NETRC      Use NETRC instead of ~/.netrc\n"
1098 "  -n            Disable auto-login\n"
1099 "  -o OUTPUT     Save auto-fetched files to OUTPUT\n"
1100 "  -P PORT       Use port PORT\n"
1101 "  -p            Force passive mode\n"
1102 "  -q QUITTIME   Quit if connection stalls for QUITTIME seconds\n"
1103 "  -R            Restart non-proxy auto-fetch\n"
1104 "  -r RETRY      Retry failed connection attempts after RETRY seconds\n"
1105 "  -s SRCADDR    Use source address SRCADDR\n"
1106 "  -t            Enable packet tracing\n"
1107 "  -T DIR,MAX[,INC]\n"
1108 "                Set maximum transfer rate for direction DIR to MAX bytes/s,\n"
1109 "                with optional increment INC bytes/s\n"
1110 "  -u URL        URL to upload file arguments to\n"
1111 "  -V            Disable verbose and progress\n"
1112 "  -v            Enable verbose and progress\n"
1113 "  -x XFERSIZE   Set socket send and receive size to XFERSIZE\n"
1114 "  -?            Display this help and exit\n"
1115 		);
1116 #endif
1117 	return EXIT_SUCCESS;
1118 }
1119 
1120 static int
1121 usage(void)
1122 {
1123 	synopsis(stderr);
1124 	return EXIT_FAILURE;
1125 }
1126