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