xref: /netbsd-src/usr.bin/ftp/main.c (revision bada23909e740596d0a3785a73bd3583a9807fb8)
1 /*	$NetBSD: main.c,v 1.39 1999/03/22 07:36:41 lukem Exp $	*/
2 
3 /*
4  * Copyright (c) 1985, 1989, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #ifndef lint
38 __COPYRIGHT("@(#) Copyright (c) 1985, 1989, 1993, 1994\n\
39 	The Regents of the University of California.  All rights reserved.\n");
40 #endif /* not lint */
41 
42 #ifndef lint
43 #if 0
44 static char sccsid[] = "@(#)main.c	8.6 (Berkeley) 10/9/94";
45 #else
46 __RCSID("$NetBSD: main.c,v 1.39 1999/03/22 07:36:41 lukem Exp $");
47 #endif
48 #endif /* not lint */
49 
50 /*
51  * FTP User Program -- Command Interface.
52  */
53 #include <sys/types.h>
54 #include <sys/socket.h>
55 
56 #include <err.h>
57 #include <netdb.h>
58 #include <pwd.h>
59 #include <signal.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64 
65 #include "ftp_var.h"
66 #include "pathnames.h"
67 
68 #define FTP_PROXY	"ftp_proxy"	/* env var with FTP proxy location */
69 #define HTTP_PROXY	"http_proxy"	/* env var with HTTP proxy location */
70 #define NO_PROXY	"no_proxy"	/* env var with list of non-proxied
71 					 * hosts, comma or space separated */
72 
73 int main __P((int, char **));
74 
75 int
76 main(argc, argv)
77 	int argc;
78 	char *argv[];
79 {
80 	struct servent *sp;
81 	int ch, top, rval;
82 	long port;
83 	struct passwd *pw = NULL;
84 	char *cp, *ep, homedir[MAXPATHLEN];
85 	int dumbterm;
86 
87 	sp = getservbyname("ftp", "tcp");
88 	if (sp == 0)
89 		ftpport = htons(FTP_PORT);	/* good fallback */
90 	else
91 		ftpport = sp->s_port;
92 	sp = getservbyname("http", "tcp");
93 	if (sp == 0)
94 		httpport = htons(HTTP_PORT);	/* good fallback */
95 	else
96 		httpport = sp->s_port;
97 	ftpproxy = getenv(FTP_PROXY);
98 	httpproxy = getenv(HTTP_PROXY);
99 	no_proxy = getenv(NO_PROXY);
100 	gateport = 0;
101 	cp = getenv("FTPSERVERPORT");
102 	if (cp != NULL) {
103 		port = strtol(cp, &ep, 10);
104 		if (port < 1 || port > MAX_IN_PORT_T || *ep != '\0')
105 			warnx("bad $FTPSERVERPORT port number: %s (ignored)",
106 			    cp);
107 		else
108 			gateport = htons(port);
109 	}
110 	if (gateport == 0) {
111 		sp = getservbyname("ftpgate", "tcp");
112 		if (sp == 0)
113 			gateport = htons(GATE_PORT);
114 		else
115 			gateport = sp->s_port;
116 	}
117 	doglob = 1;
118 	interactive = 1;
119 	autologin = 1;
120 	passivemode = 1;
121 	activefallback = 1;
122 	preserve = 1;
123 	verbose = 0;
124 	progress = 0;
125 	gatemode = 0;
126 	outfile = NULL;
127 	restartautofetch = 0;
128 #ifndef SMALL
129 	editing = 0;
130 	el = NULL;
131 	hist = NULL;
132 #endif
133 	mark = HASHBYTES;
134 	marg_sl = sl_init();
135 	if ((tmpdir = getenv("TMPDIR")) == NULL)
136 		tmpdir = _PATH_TMP;
137 
138 	/* Set default operation mode based on FTPMODE environment variable */
139 	if ((cp = getenv("FTPMODE")) != NULL) {
140 		if (strcmp(cp, "passive") == 0) {
141 			passivemode = 1;
142 			activefallback = 0;
143 		} else if (strcmp(cp, "active") == 0) {
144 			passivemode = 0;
145 			activefallback = 0;
146 		} else if (strcmp(cp, "gate") == 0) {
147 			gatemode = 1;
148 		} else if (strcmp(cp, "auto") == 0) {
149 			passivemode = 1;
150 			activefallback = 1;
151 		} else
152 			warnx("unknown $FTPMODE '%s'; using defaults", cp);
153 	}
154 
155 	if (strcmp(__progname, "pftp") == 0) {
156 		passivemode = 1;
157 		activefallback = 0;
158 	} else if (strcmp(__progname, "gate-ftp") == 0)
159 		gatemode = 1;
160 
161 	gateserver = getenv("FTPSERVER");
162 	if (gateserver == NULL || *gateserver == '\0')
163 		gateserver = GATE_SERVER;
164 	if (gatemode) {
165 		if (*gateserver == '\0') {
166 			warnx(
167 "Neither $FTPSERVER nor $GATE_SERVER is defined; disabling gate-ftp");
168 			gatemode = 0;
169 		}
170 	}
171 
172 	cp = getenv("TERM");
173 	if (cp == NULL || strcmp(cp, "dumb") == 0)
174 		dumbterm = 1;
175 	else
176 		dumbterm = 0;
177 	fromatty = isatty(fileno(stdin));
178 	ttyout = stdout;
179 	if (isatty(fileno(ttyout))) {
180 		verbose = 1;		/* verbose if from a tty */
181 #ifndef SMALL
182 		if (! dumbterm) {
183 			editing = 1;	/* editing mode on if tty is usable */
184 			if (foregroundproc())
185 				progress = 1;	/* progress bar on if fg */
186 		}
187 #endif
188 	}
189 
190 	while ((ch = getopt(argc, argv, "Aadefgino:pP:r:RtvV")) != -1) {
191 		switch (ch) {
192 		case 'A':
193 			activefallback = 0;
194 			passivemode = 0;
195 			break;
196 
197 		case 'a':
198 			anonftp = 1;
199 			break;
200 
201 		case 'd':
202 			options |= SO_DEBUG;
203 			debug++;
204 			break;
205 
206 		case 'e':
207 #ifndef SMALL
208 			editing = 0;
209 #endif
210 			break;
211 
212 		case 'f':
213 			flushcache = 1;
214 			break;
215 
216 		case 'g':
217 			doglob = 0;
218 			break;
219 
220 		case 'i':
221 			interactive = 0;
222 			break;
223 
224 		case 'n':
225 			autologin = 0;
226 			break;
227 
228 		case 'o':
229 			outfile = optarg;
230 			if (strcmp(outfile, "-") == 0)
231 				ttyout = stderr;
232 			break;
233 
234 		case 'p':
235 			passivemode = 1;
236 			activefallback = 0;
237 			break;
238 
239 		case 'P':
240 			port = strtol(optarg, &ep, 10);
241 			if (port < 1 || port > MAX_IN_PORT_T || *ep != '\0')
242 				warnx("bad port number: %s (ignored)", optarg);
243 			else
244 				ftpport = htons((in_port_t)port);
245 			break;
246 
247 		case 'r':
248 			retry_connect = strtol(optarg, &ep, 10);
249 			if (retry_connect < 1 || *ep != '\0')
250 				errx(1, "bad retry value: %s", optarg);
251 			break;
252 
253 		case 'R':
254 			restartautofetch = 1;
255 			break;
256 
257 		case 't':
258 			trace = 1;
259 			break;
260 
261 		case 'v':
262 			progress = verbose = 1;
263 			break;
264 
265 		case 'V':
266 			progress = verbose = 0;
267 			break;
268 
269 		default:
270 			usage();
271 		}
272 	}
273 			/* set line buffering on ttyout */
274 	setvbuf(ttyout, NULL, _IOLBF, 0);
275 	argc -= optind;
276 	argv += optind;
277 
278 	cpend = 0;	/* no pending replies */
279 	proxy = 0;	/* proxy not active */
280 	crflag = 1;	/* strip c.r. on ascii gets */
281 	sendport = -1;	/* not using ports */
282 	/*
283 	 * Set up the home directory in case we're globbing.
284 	 */
285 	cp = getlogin();
286 	if (cp != NULL) {
287 		pw = getpwnam(cp);
288 	}
289 	if (pw == NULL)
290 		pw = getpwuid(getuid());
291 	if (pw != NULL) {
292 		home = homedir;
293 		(void)strcpy(home, pw->pw_dir);
294 	}
295 
296 	setttywidth(0);
297 	(void)xsignal(SIGWINCH, setttywidth);
298 
299 #ifdef __GNUC__			/* to shut up gcc warnings */
300 	(void)&argc;
301 	(void)&argv;
302 #endif
303 
304 	if (argc > 0) {
305 		if (strchr(argv[0], ':') != NULL) {
306 			rval = auto_fetch(argc, argv);
307 			if (rval >= 0)		/* -1 == connected and cd-ed */
308 				exit(rval);
309 		} else {
310 			char *xargv[5];
311 
312 			if (setjmp(toplevel))
313 				exit(0);
314 			(void)signal(SIGINT, (sig_t)intr);
315 			(void)signal(SIGPIPE, (sig_t)lostpeer);
316 			xargv[0] = __progname;
317 			xargv[1] = argv[0];
318 			xargv[2] = argv[1];
319 			xargv[3] = argv[2];
320 			xargv[4] = NULL;
321 			do {
322 				setpeer(argc+1, xargv);
323 				if (!retry_connect)
324 					break;
325 				if (!connected) {
326 					macnum = 0;
327 					fprintf(ttyout,
328 					    "Retrying in %d seconds...\n",
329 					    retry_connect);
330 					sleep(retry_connect);
331 				}
332 			} while (!connected);
333 			retry_connect = 0; /* connected, stop hiding msgs */
334 		}
335 	}
336 #ifndef SMALL
337 	controlediting();
338 #endif /* !SMALL */
339 	top = setjmp(toplevel) == 0;
340 	if (top) {
341 		(void)signal(SIGINT, (sig_t)intr);
342 		(void)signal(SIGPIPE, (sig_t)lostpeer);
343 	}
344 	for (;;) {
345 		cmdscanner(top);
346 		top = 1;
347 	}
348 }
349 
350 void
351 intr()
352 {
353 
354 	alarmtimer(0);
355 	longjmp(toplevel, 1);
356 }
357 
358 void
359 lostpeer()
360 {
361 
362 	alarmtimer(0);
363 	if (connected) {
364 		if (cout != NULL) {
365 			(void)shutdown(fileno(cout), 1+1);
366 			(void)fclose(cout);
367 			cout = NULL;
368 		}
369 		if (data >= 0) {
370 			(void)shutdown(data, 1+1);
371 			(void)close(data);
372 			data = -1;
373 		}
374 		connected = 0;
375 	}
376 	pswitch(1);
377 	if (connected) {
378 		if (cout != NULL) {
379 			(void)shutdown(fileno(cout), 1+1);
380 			(void)fclose(cout);
381 			cout = NULL;
382 		}
383 		connected = 0;
384 	}
385 	proxflag = 0;
386 	pswitch(0);
387 }
388 
389 /*
390  * Generate a prompt
391  */
392 char *
393 prompt()
394 {
395 	return ("ftp> ");
396 }
397 
398 /*
399  * Command parser.
400  */
401 void
402 cmdscanner(top)
403 	int top;
404 {
405 	struct cmd *c;
406 	int num;
407 
408 	if (!top
409 #ifndef SMALL
410 	    && !editing
411 #endif /* !SMALL */
412 	    )
413 		(void)putc('\n', ttyout);
414 	for (;;) {
415 #ifndef SMALL
416 		if (!editing) {
417 #endif /* !SMALL */
418 			if (fromatty) {
419 				fputs(prompt(), ttyout);
420 				(void)fflush(ttyout);
421 			}
422 			if (fgets(line, sizeof(line), stdin) == NULL)
423 				quit(0, 0);
424 			num = strlen(line);
425 			if (num == 0)
426 				break;
427 			if (line[--num] == '\n') {
428 				if (num == 0)
429 					break;
430 				line[num] = '\0';
431 			} else if (num == sizeof(line) - 2) {
432 				fputs("sorry, input line too long.\n", ttyout);
433 				while ((num = getchar()) != '\n' && num != EOF)
434 					/* void */;
435 				break;
436 			} /* else it was a line without a newline */
437 #ifndef SMALL
438 		} else {
439 			const char *buf;
440 			HistEvent ev;
441 			cursor_pos = NULL;
442 
443 			if ((buf = el_gets(el, &num)) == NULL || num == 0)
444 				quit(0, 0);
445 			if (line[--num] == '\n') {
446 				if (num == 0)
447 					break;
448 			} else if (num >= sizeof(line)) {
449 				fputs("sorry, input line too long.\n", ttyout);
450 				break;
451 			}
452 			memcpy(line, buf, num);
453 			line[num] = '\0';
454 			history(hist, &ev, H_ENTER, buf);
455 		}
456 #endif /* !SMALL */
457 
458 		makeargv();
459 		if (margc == 0)
460 			continue;
461 		c = getcmd(margv[0]);
462 		if (c == (struct cmd *)-1) {
463 			fputs("?Ambiguous command.\n", ttyout);
464 			continue;
465 		}
466 		if (c == NULL) {
467 #if !defined(SMALL)
468 			/*
469 			 * attempt to el_parse() unknown commands.
470 			 * any command containing a ':' would be parsed
471 			 * as "[prog:]cmd ...", and will result in a
472 			 * false positive if prog != "ftp", so treat
473 			 * such commands as invalid.
474 			 */
475 			if (strchr(margv[0], ':') != NULL ||
476 			    el_parse(el, margc, margv) != 0)
477 #endif /* !SMALL */
478 				fputs("?Invalid command.\n", ttyout);
479 			continue;
480 		}
481 		if (c->c_conn && !connected) {
482 			fputs("Not connected.\n", ttyout);
483 			continue;
484 		}
485 		confirmrest = 0;
486 		(*c->c_handler)(margc, margv);
487 		if (bell && c->c_bell)
488 			(void)putc('\007', ttyout);
489 		if (c->c_handler != help)
490 			break;
491 	}
492 	(void)signal(SIGINT, (sig_t)intr);
493 	(void)signal(SIGPIPE, (sig_t)lostpeer);
494 }
495 
496 struct cmd *
497 getcmd(name)
498 	const char *name;
499 {
500 	const char *p, *q;
501 	struct cmd *c, *found;
502 	int nmatches, longest;
503 
504 	if (name == NULL)
505 		return (0);
506 
507 	longest = 0;
508 	nmatches = 0;
509 	found = 0;
510 	for (c = cmdtab; (p = c->c_name) != NULL; c++) {
511 		for (q = name; *q == *p++; q++)
512 			if (*q == 0)		/* exact match? */
513 				return (c);
514 		if (!*q) {			/* the name was a prefix */
515 			if (q - name > longest) {
516 				longest = q - name;
517 				nmatches = 1;
518 				found = c;
519 			} else if (q - name == longest)
520 				nmatches++;
521 		}
522 	}
523 	if (nmatches > 1)
524 		return ((struct cmd *)-1);
525 	return (found);
526 }
527 
528 /*
529  * Slice a string up into argc/argv.
530  */
531 
532 int slrflag;
533 
534 void
535 makeargv()
536 {
537 	char *argp;
538 
539 	stringbase = line;		/* scan from first of buffer */
540 	argbase = argbuf;		/* store from first of buffer */
541 	slrflag = 0;
542 	marg_sl->sl_cur = 0;		/* reset to start of marg_sl */
543 	for (margc = 0; ; margc++) {
544 		argp = slurpstring();
545 		sl_add(marg_sl, argp);
546 		if (argp == NULL)
547 			break;
548 	}
549 #ifndef SMALL
550 	if (cursor_pos == line) {
551 		cursor_argc = 0;
552 		cursor_argo = 0;
553 	} else if (cursor_pos != NULL) {
554 		cursor_argc = margc;
555 		cursor_argo = strlen(margv[margc-1]);
556 	}
557 #endif /* !SMALL */
558 }
559 
560 #ifdef SMALL
561 #define INC_CHKCURSOR(x)	(x)++
562 #else  /* !SMALL */
563 #define INC_CHKCURSOR(x)	{ (x)++ ; \
564 				if (x == cursor_pos) { \
565 					cursor_argc = margc; \
566 					cursor_argo = ap-argbase; \
567 					cursor_pos = NULL; \
568 				} }
569 
570 #endif /* !SMALL */
571 
572 /*
573  * Parse string into argbuf;
574  * implemented with FSM to
575  * handle quoting and strings
576  */
577 char *
578 slurpstring()
579 {
580 	int got_one = 0;
581 	char *sb = stringbase;
582 	char *ap = argbase;
583 	char *tmp = argbase;		/* will return this if token found */
584 
585 	if (*sb == '!' || *sb == '$') {	/* recognize ! as a token for shell */
586 		switch (slrflag) {	/* and $ as token for macro invoke */
587 			case 0:
588 				slrflag++;
589 				INC_CHKCURSOR(stringbase);
590 				return ((*sb == '!') ? "!" : "$");
591 				/* NOTREACHED */
592 			case 1:
593 				slrflag++;
594 				altarg = stringbase;
595 				break;
596 			default:
597 				break;
598 		}
599 	}
600 
601 S0:
602 	switch (*sb) {
603 
604 	case '\0':
605 		goto OUT;
606 
607 	case ' ':
608 	case '\t':
609 		INC_CHKCURSOR(sb);
610 		goto S0;
611 
612 	default:
613 		switch (slrflag) {
614 			case 0:
615 				slrflag++;
616 				break;
617 			case 1:
618 				slrflag++;
619 				altarg = sb;
620 				break;
621 			default:
622 				break;
623 		}
624 		goto S1;
625 	}
626 
627 S1:
628 	switch (*sb) {
629 
630 	case ' ':
631 	case '\t':
632 	case '\0':
633 		goto OUT;	/* end of token */
634 
635 	case '\\':
636 		INC_CHKCURSOR(sb);
637 		goto S2;	/* slurp next character */
638 
639 	case '"':
640 		INC_CHKCURSOR(sb);
641 		goto S3;	/* slurp quoted string */
642 
643 	default:
644 		*ap = *sb;	/* add character to token */
645 		ap++;
646 		INC_CHKCURSOR(sb);
647 		got_one = 1;
648 		goto S1;
649 	}
650 
651 S2:
652 	switch (*sb) {
653 
654 	case '\0':
655 		goto OUT;
656 
657 	default:
658 		*ap = *sb;
659 		ap++;
660 		INC_CHKCURSOR(sb);
661 		got_one = 1;
662 		goto S1;
663 	}
664 
665 S3:
666 	switch (*sb) {
667 
668 	case '\0':
669 		goto OUT;
670 
671 	case '"':
672 		INC_CHKCURSOR(sb);
673 		goto S1;
674 
675 	default:
676 		*ap = *sb;
677 		ap++;
678 		INC_CHKCURSOR(sb);
679 		got_one = 1;
680 		goto S3;
681 	}
682 
683 OUT:
684 	if (got_one)
685 		*ap++ = '\0';
686 	argbase = ap;			/* update storage pointer */
687 	stringbase = sb;		/* update scan pointer */
688 	if (got_one) {
689 		return (tmp);
690 	}
691 	switch (slrflag) {
692 		case 0:
693 			slrflag++;
694 			break;
695 		case 1:
696 			slrflag++;
697 			altarg = NULL;
698 			break;
699 		default:
700 			break;
701 	}
702 	return (NULL);
703 }
704 
705 /*
706  * Help command.
707  * Call each command handler with argc == 0 and argv[0] == name.
708  */
709 void
710 help(argc, argv)
711 	int argc;
712 	char *argv[];
713 {
714 	struct cmd *c;
715 
716 	if (argc == 1) {
717 		StringList *buf;
718 
719 		buf = sl_init();
720 		fprintf(ttyout,
721 		    "%sommands may be abbreviated.  Commands are:\n\n",
722 		    proxy ? "Proxy c" : "C");
723 		for (c = cmdtab; c < &cmdtab[NCMDS]; c++)
724 			if (c->c_name && (!proxy || c->c_proxy))
725 				sl_add(buf, c->c_name);
726 		list_vertical(buf);
727 		sl_free(buf, 0);
728 		return;
729 	}
730 
731 #define HELPINDENT ((int) sizeof("disconnect"))
732 
733 	while (--argc > 0) {
734 		char *arg;
735 
736 		arg = *++argv;
737 		c = getcmd(arg);
738 		if (c == (struct cmd *)-1)
739 			fprintf(ttyout, "?Ambiguous help command %s\n", arg);
740 		else if (c == NULL)
741 			fprintf(ttyout, "?Invalid help command %s\n", arg);
742 		else
743 			fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
744 				c->c_name, c->c_help);
745 	}
746 }
747 
748 void
749 usage()
750 {
751 	(void)fprintf(stderr,
752 "usage: %s [-AadeginptvV] [-r retry] [-P port] [host [port]]\n"
753 "       %s [-f] [-o outfile] file:///file\n"
754 "       %s [-fR] [-o outfile] ftp://[user[:pass]@]host[:port]/path[/]\n"
755 "       %s [-f] [-o outfile] http://host[:port]/path\n"
756 "       %s [-fR] [-o outfile] host:path[/]\n",
757 	    __progname, __progname, __progname, __progname, __progname);
758 	exit(1);
759 }
760