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