Home | History | Annotate | Line # | Download | only in ftp
main.c revision 1.32
      1 /*	$NetBSD: main.c,v 1.32 1998/08/03 01:49:26 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.32 1998/08/03 01:49:26 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 <stdio.h>
     60 #include <stdlib.h>
     61 #include <string.h>
     62 #include <unistd.h>
     63 
     64 #include "ftp_var.h"
     65 #include "pathnames.h"
     66 
     67 int main __P((int, char **));
     68 
     69 int
     70 main(argc, argv)
     71 	int argc;
     72 	char *argv[];
     73 {
     74 	struct servent *sp;
     75 	int ch, top, rval;
     76 	long port;
     77 	struct passwd *pw = NULL;
     78 	char *cp, *ep, homedir[MAXPATHLEN];
     79 	char *outfile = NULL;
     80 	int dumbterm;
     81 
     82 	sp = getservbyname("ftp", "tcp");
     83 	if (sp == 0)
     84 		ftpport = htons(FTP_PORT);	/* good fallback */
     85 	else
     86 		ftpport = sp->s_port;
     87 	sp = getservbyname("http", "tcp");
     88 	if (sp == 0)
     89 		httpport = htons(HTTP_PORT);	/* good fallback */
     90 	else
     91 		httpport = sp->s_port;
     92 	gateport = 0;
     93 	cp = getenv("FTPSERVERPORT");
     94 	if (cp != NULL) {
     95 		port = strtol(cp, &ep, 10);
     96 		if (port < 1 || port > MAX_IN_PORT_T || *ep != '\0')
     97 			warnx("bad $FTPSERVERPORT port number: %s (ignored)",
     98 			    cp);
     99 		else
    100 			gateport = htons(port);
    101 	}
    102 	if (gateport == 0) {
    103 		sp = getservbyname("ftpgate", "tcp");
    104 		if (sp == 0)
    105 			gateport = htons(GATE_PORT);
    106 		else
    107 			gateport = sp->s_port;
    108 	}
    109 	doglob = 1;
    110 	interactive = 1;
    111 	autologin = 1;
    112 	passivemode = 1;
    113 	activefallback = 1;
    114 	preserve = 1;
    115 	verbose = 0;
    116 	progress = 0;
    117 	gatemode = 0;
    118 #ifndef SMALL
    119 	editing = 0;
    120 	el = NULL;
    121 	hist = NULL;
    122 #endif
    123 	mark = HASHBYTES;
    124 	marg_sl = sl_init();
    125 	if ((tmpdir = getenv("TMPDIR")) == NULL)
    126 		tmpdir = _PATH_TMP;
    127 
    128 	/* Set default operation mode based on FTPMODE environment variable */
    129 	if ((cp = getenv("FTPMODE")) != NULL) {
    130 		if (strcmp(cp, "passive") == 0) {
    131 			passivemode = 1;
    132 			activefallback = 0;
    133 		} else if (strcmp(cp, "active") == 0) {
    134 			passivemode = 0;
    135 			activefallback = 0;
    136 		} else if (strcmp(cp, "gate") == 0) {
    137 			gatemode = 1;
    138 		} else if (strcmp(cp, "auto") == 0) {
    139 			passivemode = 1;
    140 			activefallback = 1;
    141 		} else
    142 			warnx("unknown $FTPMODE '%s'; using defaults", cp);
    143 	}
    144 
    145 	if (strcmp(__progname, "pftp") == 0) {
    146 		passivemode = 1;
    147 		activefallback = 0;
    148 	} else if (strcmp(__progname, "gate-ftp") == 0)
    149 		gatemode = 1;
    150 
    151 	gateserver = getenv("FTPSERVER");
    152 	if (gateserver == NULL || *gateserver == '\0')
    153 		gateserver = GATE_SERVER;
    154 	if (gatemode) {
    155 		if (*gateserver == '\0') {
    156 			warnx(
    157 "Neither $FTPSERVER nor $GATE_SERVER is defined; disabling gate-ftp");
    158 			gatemode = 0;
    159 		}
    160 	}
    161 
    162 	cp = getenv("TERM");
    163 	if (cp == NULL || strcmp(cp, "dumb") == 0)
    164 		dumbterm = 1;
    165 	else
    166 		dumbterm = 0;
    167 	fromatty = isatty(fileno(stdin));
    168 	if (fromatty) {
    169 		verbose = 1;		/* verbose if from a tty */
    170 #ifndef SMALL
    171 		if (! dumbterm)
    172 			editing = 1;	/* editing mode on if tty is usable */
    173 #endif
    174 	}
    175 	ttyout = stdout;
    176 #ifndef SMALL
    177 	if (isatty(fileno(ttyout)) && !dumbterm && foregroundproc())
    178 		progress = 1;		/* progress bar on if tty is usable */
    179 #endif
    180 
    181 	while ((ch = getopt(argc, argv, "Aadegino:pP:r:tvV")) != -1) {
    182 		switch (ch) {
    183 		case 'A':
    184 			activefallback = 0;
    185 			passivemode = 0;
    186 			break;
    187 
    188 		case 'a':
    189 			anonftp = 1;
    190 			break;
    191 
    192 		case 'd':
    193 			options |= SO_DEBUG;
    194 			debug++;
    195 			break;
    196 
    197 		case 'e':
    198 #ifndef SMALL
    199 			editing = 0;
    200 #endif
    201 			break;
    202 
    203 		case 'g':
    204 			doglob = 0;
    205 			break;
    206 
    207 		case 'i':
    208 			interactive = 0;
    209 			break;
    210 
    211 		case 'n':
    212 			autologin = 0;
    213 			break;
    214 
    215 		case 'o':
    216 			outfile = optarg;
    217 			if (strcmp(outfile, "-") == 0)
    218 				ttyout = stderr;
    219 			break;
    220 
    221 		case 'p':
    222 			passivemode = 1;
    223 			activefallback = 0;
    224 			break;
    225 
    226 		case 'P':
    227 			port = strtol(optarg, &ep, 10);
    228 			if (port < 1 || port > MAX_IN_PORT_T || *ep != '\0')
    229 				warnx("bad port number: %s (ignored)", optarg);
    230 			else
    231 				ftpport = htons((in_port_t)port);
    232 			break;
    233 
    234 		case 'r':
    235 			retry_connect = strtol(optarg, &ep, 10);
    236 			if (retry_connect < 1 || retry_connect > MAX_IN_PORT_T
    237 			    || *ep != '\0')
    238 				errx(1, "bad retry value: %s", optarg);
    239 			break;
    240 
    241 		case 't':
    242 			trace = 1;
    243 			break;
    244 
    245 		case 'v':
    246 			verbose = 1;
    247 			break;
    248 
    249 		case 'V':
    250 			verbose = 0;
    251 			break;
    252 
    253 		default:
    254 			usage();
    255 		}
    256 	}
    257 	argc -= optind;
    258 	argv += optind;
    259 
    260 	cpend = 0;	/* no pending replies */
    261 	proxy = 0;	/* proxy not active */
    262 	crflag = 1;	/* strip c.r. on ascii gets */
    263 	sendport = -1;	/* not using ports */
    264 	/*
    265 	 * Set up the home directory in case we're globbing.
    266 	 */
    267 	cp = getlogin();
    268 	if (cp != NULL) {
    269 		pw = getpwnam(cp);
    270 	}
    271 	if (pw == NULL)
    272 		pw = getpwuid(getuid());
    273 	if (pw != NULL) {
    274 		home = homedir;
    275 		(void)strcpy(home, pw->pw_dir);
    276 	}
    277 
    278 	setttywidth(0);
    279 	(void)signal(SIGWINCH, setttywidth);
    280 
    281 #ifdef __GNUC__			/* to shut up gcc warnings */
    282 	(void)&argc;
    283 	(void)&argv;
    284 #endif
    285 
    286 	if (argc > 0) {
    287 		if (strchr(argv[0], ':') != NULL) {
    288 			anonftp = 1;	/* Handle "automatic" transfers. */
    289 			rval = auto_fetch(argc, argv, outfile);
    290 			if (rval >= 0)		/* -1 == connected and cd-ed */
    291 				exit(rval);
    292 		} else {
    293 			char *xargv[5];
    294 
    295 			if (setjmp(toplevel))
    296 				exit(0);
    297 			(void)signal(SIGINT, (sig_t)intr);
    298 			(void)signal(SIGPIPE, (sig_t)lostpeer);
    299 			xargv[0] = __progname;
    300 			xargv[1] = argv[0];
    301 			xargv[2] = argv[1];
    302 			xargv[3] = argv[2];
    303 			xargv[4] = NULL;
    304 			do {
    305 				setpeer(argc+1, xargv);
    306 				if (!retry_connect)
    307 					break;
    308 				if (!connected) {
    309 					macnum = 0;
    310 					fprintf(ttyout,
    311 					    "Retrying in %d seconds...\n",
    312 					    retry_connect);
    313 					sleep(retry_connect);
    314 				}
    315 			} while (!connected);
    316 			retry_connect = 0; /* connected, stop hiding msgs */
    317 		}
    318 	}
    319 #ifndef SMALL
    320 	controlediting();
    321 #endif /* !SMALL */
    322 	top = setjmp(toplevel) == 0;
    323 	if (top) {
    324 		(void)signal(SIGINT, (sig_t)intr);
    325 		(void)signal(SIGPIPE, (sig_t)lostpeer);
    326 	}
    327 	for (;;) {
    328 		cmdscanner(top);
    329 		top = 1;
    330 	}
    331 }
    332 
    333 void
    334 intr()
    335 {
    336 
    337 	alarmtimer(0);
    338 	longjmp(toplevel, 1);
    339 }
    340 
    341 void
    342 lostpeer()
    343 {
    344 
    345 	alarmtimer(0);
    346 	if (connected) {
    347 		if (cout != NULL) {
    348 			(void)shutdown(fileno(cout), 1+1);
    349 			(void)fclose(cout);
    350 			cout = NULL;
    351 		}
    352 		if (data >= 0) {
    353 			(void)shutdown(data, 1+1);
    354 			(void)close(data);
    355 			data = -1;
    356 		}
    357 		connected = 0;
    358 	}
    359 	pswitch(1);
    360 	if (connected) {
    361 		if (cout != NULL) {
    362 			(void)shutdown(fileno(cout), 1+1);
    363 			(void)fclose(cout);
    364 			cout = NULL;
    365 		}
    366 		connected = 0;
    367 	}
    368 	proxflag = 0;
    369 	pswitch(0);
    370 }
    371 
    372 /*
    373  * Generate a prompt
    374  */
    375 char *
    376 prompt()
    377 {
    378 	return ("ftp> ");
    379 }
    380 
    381 /*
    382  * Command parser.
    383  */
    384 void
    385 cmdscanner(top)
    386 	int top;
    387 {
    388 	struct cmd *c;
    389 	int num;
    390 
    391 	if (!top
    392 #ifndef SMALL
    393 	    && !editing
    394 #endif /* !SMALL */
    395 	    )
    396 		(void)putc('\n', ttyout);
    397 	for (;;) {
    398 #ifndef SMALL
    399 		if (!editing) {
    400 #endif /* !SMALL */
    401 			if (fromatty) {
    402 				fputs(prompt(), ttyout);
    403 				(void)fflush(ttyout);
    404 			}
    405 			if (fgets(line, sizeof(line), stdin) == NULL)
    406 				quit(0, 0);
    407 			num = strlen(line);
    408 			if (num == 0)
    409 				break;
    410 			if (line[--num] == '\n') {
    411 				if (num == 0)
    412 					break;
    413 				line[num] = '\0';
    414 			} else if (num == sizeof(line) - 2) {
    415 				fputs("sorry, input line too long.\n", ttyout);
    416 				while ((num = getchar()) != '\n' && num != EOF)
    417 					/* void */;
    418 				break;
    419 			} /* else it was a line without a newline */
    420 #ifndef SMALL
    421 		} else {
    422 			const char *buf;
    423 			HistEvent ev;
    424 			cursor_pos = NULL;
    425 
    426 			if ((buf = el_gets(el, &num)) == NULL || num == 0)
    427 				quit(0, 0);
    428 			if (line[--num] == '\n') {
    429 				if (num == 0)
    430 					break;
    431 			} else if (num >= sizeof(line)) {
    432 				fputs("sorry, input line too long.\n", ttyout);
    433 				break;
    434 			}
    435 			memcpy(line, buf, num);
    436 			line[num] = '\0';
    437 			history(hist, &ev, H_ENTER, buf);
    438 		}
    439 #endif /* !SMALL */
    440 
    441 		makeargv();
    442 		if (margc == 0)
    443 			continue;
    444 		c = getcmd(margv[0]);
    445 		if (c == (struct cmd *)-1) {
    446 			fputs("?Ambiguous command.\n", ttyout);
    447 			continue;
    448 		}
    449 		if (c == NULL) {
    450 #if !defined(SMALL)
    451 			/*
    452 			 * attempt to el_parse() unknown commands.
    453 			 * any command containing a ':' would be parsed
    454 			 * as "[prog:]cmd ...", and will result in a
    455 			 * false positive if prog != "ftp", so treat
    456 			 * such commands as invalid.
    457 			 */
    458 			if (strchr(margv[0], ':') != NULL ||
    459 			    el_parse(el, margc, margv) != 0)
    460 #endif /* !SMALL */
    461 				fputs("?Invalid command.\n", ttyout);
    462 			continue;
    463 		}
    464 		if (c->c_conn && !connected) {
    465 			fputs("Not connected.\n", ttyout);
    466 			continue;
    467 		}
    468 		confirmrest = 0;
    469 		(*c->c_handler)(margc, margv);
    470 		if (bell && c->c_bell)
    471 			(void)putc('\007', ttyout);
    472 		if (c->c_handler != help)
    473 			break;
    474 	}
    475 	(void)signal(SIGINT, (sig_t)intr);
    476 	(void)signal(SIGPIPE, (sig_t)lostpeer);
    477 }
    478 
    479 struct cmd *
    480 getcmd(name)
    481 	const char *name;
    482 {
    483 	const char *p, *q;
    484 	struct cmd *c, *found;
    485 	int nmatches, longest;
    486 
    487 	if (name == NULL)
    488 		return (0);
    489 
    490 	longest = 0;
    491 	nmatches = 0;
    492 	found = 0;
    493 	for (c = cmdtab; (p = c->c_name) != NULL; c++) {
    494 		for (q = name; *q == *p++; q++)
    495 			if (*q == 0)		/* exact match? */
    496 				return (c);
    497 		if (!*q) {			/* the name was a prefix */
    498 			if (q - name > longest) {
    499 				longest = q - name;
    500 				nmatches = 1;
    501 				found = c;
    502 			} else if (q - name == longest)
    503 				nmatches++;
    504 		}
    505 	}
    506 	if (nmatches > 1)
    507 		return ((struct cmd *)-1);
    508 	return (found);
    509 }
    510 
    511 /*
    512  * Slice a string up into argc/argv.
    513  */
    514 
    515 int slrflag;
    516 
    517 void
    518 makeargv()
    519 {
    520 	char *argp;
    521 
    522 	stringbase = line;		/* scan from first of buffer */
    523 	argbase = argbuf;		/* store from first of buffer */
    524 	slrflag = 0;
    525 	marg_sl->sl_cur = 0;		/* reset to start of marg_sl */
    526 	for (margc = 0; ; margc++) {
    527 		argp = slurpstring();
    528 		sl_add(marg_sl, argp);
    529 		if (argp == NULL)
    530 			break;
    531 	}
    532 #ifndef SMALL
    533 	if (cursor_pos == line) {
    534 		cursor_argc = 0;
    535 		cursor_argo = 0;
    536 	} else if (cursor_pos != NULL) {
    537 		cursor_argc = margc;
    538 		cursor_argo = strlen(margv[margc-1]);
    539 	}
    540 #endif /* !SMALL */
    541 }
    542 
    543 #ifdef SMALL
    544 #define INC_CHKCURSOR(x)	(x)++
    545 #else  /* !SMALL */
    546 #define INC_CHKCURSOR(x)	{ (x)++ ; \
    547 				if (x == cursor_pos) { \
    548 					cursor_argc = margc; \
    549 					cursor_argo = ap-argbase; \
    550 					cursor_pos = NULL; \
    551 				} }
    552 
    553 #endif /* !SMALL */
    554 
    555 /*
    556  * Parse string into argbuf;
    557  * implemented with FSM to
    558  * handle quoting and strings
    559  */
    560 char *
    561 slurpstring()
    562 {
    563 	int got_one = 0;
    564 	char *sb = stringbase;
    565 	char *ap = argbase;
    566 	char *tmp = argbase;		/* will return this if token found */
    567 
    568 	if (*sb == '!' || *sb == '$') {	/* recognize ! as a token for shell */
    569 		switch (slrflag) {	/* and $ as token for macro invoke */
    570 			case 0:
    571 				slrflag++;
    572 				INC_CHKCURSOR(stringbase);
    573 				return ((*sb == '!') ? "!" : "$");
    574 				/* NOTREACHED */
    575 			case 1:
    576 				slrflag++;
    577 				altarg = stringbase;
    578 				break;
    579 			default:
    580 				break;
    581 		}
    582 	}
    583 
    584 S0:
    585 	switch (*sb) {
    586 
    587 	case '\0':
    588 		goto OUT;
    589 
    590 	case ' ':
    591 	case '\t':
    592 		INC_CHKCURSOR(sb);
    593 		goto S0;
    594 
    595 	default:
    596 		switch (slrflag) {
    597 			case 0:
    598 				slrflag++;
    599 				break;
    600 			case 1:
    601 				slrflag++;
    602 				altarg = sb;
    603 				break;
    604 			default:
    605 				break;
    606 		}
    607 		goto S1;
    608 	}
    609 
    610 S1:
    611 	switch (*sb) {
    612 
    613 	case ' ':
    614 	case '\t':
    615 	case '\0':
    616 		goto OUT;	/* end of token */
    617 
    618 	case '\\':
    619 		INC_CHKCURSOR(sb);
    620 		goto S2;	/* slurp next character */
    621 
    622 	case '"':
    623 		INC_CHKCURSOR(sb);
    624 		goto S3;	/* slurp quoted string */
    625 
    626 	default:
    627 		*ap = *sb;	/* add character to token */
    628 		ap++;
    629 		INC_CHKCURSOR(sb);
    630 		got_one = 1;
    631 		goto S1;
    632 	}
    633 
    634 S2:
    635 	switch (*sb) {
    636 
    637 	case '\0':
    638 		goto OUT;
    639 
    640 	default:
    641 		*ap = *sb;
    642 		ap++;
    643 		INC_CHKCURSOR(sb);
    644 		got_one = 1;
    645 		goto S1;
    646 	}
    647 
    648 S3:
    649 	switch (*sb) {
    650 
    651 	case '\0':
    652 		goto OUT;
    653 
    654 	case '"':
    655 		INC_CHKCURSOR(sb);
    656 		goto S1;
    657 
    658 	default:
    659 		*ap = *sb;
    660 		ap++;
    661 		INC_CHKCURSOR(sb);
    662 		got_one = 1;
    663 		goto S3;
    664 	}
    665 
    666 OUT:
    667 	if (got_one)
    668 		*ap++ = '\0';
    669 	argbase = ap;			/* update storage pointer */
    670 	stringbase = sb;		/* update scan pointer */
    671 	if (got_one) {
    672 		return (tmp);
    673 	}
    674 	switch (slrflag) {
    675 		case 0:
    676 			slrflag++;
    677 			break;
    678 		case 1:
    679 			slrflag++;
    680 			altarg = NULL;
    681 			break;
    682 		default:
    683 			break;
    684 	}
    685 	return (NULL);
    686 }
    687 
    688 /*
    689  * Help command.
    690  * Call each command handler with argc == 0 and argv[0] == name.
    691  */
    692 void
    693 help(argc, argv)
    694 	int argc;
    695 	char *argv[];
    696 {
    697 	struct cmd *c;
    698 
    699 	if (argc == 1) {
    700 		StringList *buf;
    701 
    702 		buf = sl_init();
    703 		fprintf(ttyout,
    704 		    "%sommands may be abbreviated.  Commands are:\n\n",
    705 		    proxy ? "Proxy c" : "C");
    706 		for (c = cmdtab; c < &cmdtab[NCMDS]; c++)
    707 			if (c->c_name && (!proxy || c->c_proxy))
    708 				sl_add(buf, c->c_name);
    709 		list_vertical(buf);
    710 		sl_free(buf, 0);
    711 		return;
    712 	}
    713 
    714 #define HELPINDENT ((int) sizeof("disconnect"))
    715 
    716 	while (--argc > 0) {
    717 		char *arg;
    718 
    719 		arg = *++argv;
    720 		c = getcmd(arg);
    721 		if (c == (struct cmd *)-1)
    722 			fprintf(ttyout, "?Ambiguous help command %s\n", arg);
    723 		else if (c == NULL)
    724 			fprintf(ttyout, "?Invalid help command %s\n", arg);
    725 		else
    726 			fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
    727 				c->c_name, c->c_help);
    728 	}
    729 }
    730 
    731 void
    732 usage()
    733 {
    734 	(void)fprintf(stderr,
    735 	    "usage: %s [-AadeginptvV] [-r retry] [-P port] [host [port]]\n"
    736 	    "       %s [-o outfile] host:path[/]\n"
    737 	    "       %s [-o outfile] ftp://host[:port]/path[/]\n"
    738 	    "       %s [-o outfile] http://host[:port]/file\n",
    739 	    __progname, __progname, __progname, __progname);
    740 	exit(1);
    741 }
    742