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