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