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