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