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