main.c revision 1.88 1 /* $NetBSD: main.c,v 1.88 2004/07/09 12:12:27 wiz Exp $ */
2
3 /*-
4 * Copyright (c) 1996-2002 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Luke Mewburn.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39 /*
40 * Copyright (c) 1985, 1989, 1993, 1994
41 * The Regents of the University of California. All rights reserved.
42 *
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. Neither the name of the University nor the names of its contributors
52 * may be used to endorse or promote products derived from this software
53 * without specific prior written permission.
54 *
55 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65 * SUCH DAMAGE.
66 */
67
68 /*
69 * Copyright (C) 1997 and 1998 WIDE Project.
70 * All rights reserved.
71 *
72 * Redistribution and use in source and binary forms, with or without
73 * modification, are permitted provided that the following conditions
74 * are met:
75 * 1. Redistributions of source code must retain the above copyright
76 * notice, this list of conditions and the following disclaimer.
77 * 2. Redistributions in binary form must reproduce the above copyright
78 * notice, this list of conditions and the following disclaimer in the
79 * documentation and/or other materials provided with the distribution.
80 * 3. Neither the name of the project nor the names of its contributors
81 * may be used to endorse or promote products derived from this software
82 * without specific prior written permission.
83 *
84 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
85 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
86 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
87 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
88 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
89 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
90 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
91 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
92 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
93 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
94 * SUCH DAMAGE.
95 */
96
97 #include <sys/cdefs.h>
98 #ifndef lint
99 __COPYRIGHT("@(#) Copyright (c) 1985, 1989, 1993, 1994\n\
100 The Regents of the University of California. All rights reserved.\n");
101 #endif /* not lint */
102
103 #ifndef lint
104 #if 0
105 static char sccsid[] = "@(#)main.c 8.6 (Berkeley) 10/9/94";
106 #else
107 __RCSID("$NetBSD: main.c,v 1.88 2004/07/09 12:12:27 wiz Exp $");
108 #endif
109 #endif /* not lint */
110
111 /*
112 * FTP User Program -- Command Interface.
113 */
114 #include <sys/types.h>
115 #include <sys/socket.h>
116
117 #include <err.h>
118 #include <errno.h>
119 #include <netdb.h>
120 #include <paths.h>
121 #include <pwd.h>
122 #include <stdio.h>
123 #include <stdlib.h>
124 #include <string.h>
125 #include <unistd.h>
126 #include <locale.h>
127
128 #define GLOBAL /* force GLOBAL decls in ftp_var.h to be declared */
129 #include "ftp_var.h"
130
131 #define FTP_PROXY "ftp_proxy" /* env var with FTP proxy location */
132 #define HTTP_PROXY "http_proxy" /* env var with HTTP proxy location */
133 #define NO_PROXY "no_proxy" /* env var with list of non-proxied
134 * hosts, comma or space separated */
135
136 static void setupoption(char *, char *, char *);
137 int main(int, char *[]);
138
139 int
140 main(int argc, char *argv[])
141 {
142 int ch, rval;
143 struct passwd *pw;
144 char *cp, *ep, *anonuser, *anonpass, *upload_path;
145 int dumbterm, s, len, isupload;
146
147 setlocale(LC_ALL, "");
148 setprogname(argv[0]);
149
150 ftpport = "ftp";
151 httpport = "http";
152 gateport = NULL;
153 cp = getenv("FTPSERVERPORT");
154 if (cp != NULL)
155 gateport = cp;
156 else
157 gateport = "ftpgate";
158 doglob = 1;
159 interactive = 1;
160 autologin = 1;
161 passivemode = 1;
162 activefallback = 1;
163 preserve = 1;
164 verbose = 0;
165 progress = 0;
166 gatemode = 0;
167 data = -1;
168 outfile = NULL;
169 restartautofetch = 0;
170 #ifndef NO_EDITCOMPLETE
171 editing = 0;
172 el = NULL;
173 hist = NULL;
174 #endif
175 bytes = 0;
176 mark = HASHBYTES;
177 rate_get = 0;
178 rate_get_incr = DEFAULTINCR;
179 rate_put = 0;
180 rate_put_incr = DEFAULTINCR;
181 #ifdef INET6
182 epsv4 = 1;
183 #else
184 epsv4 = 0;
185 #endif
186 epsv4bad = 0;
187 upload_path = NULL;
188 isupload = 0;
189 reply_callback = NULL;
190 family = AF_UNSPEC;
191
192 netrc[0] = '\0';
193 cp = getenv("NETRC");
194 if (cp != NULL && strlcpy(netrc, cp, sizeof(netrc)) >= sizeof(netrc))
195 errx(1, "$NETRC `%s': %s", cp, strerror(ENAMETOOLONG));
196
197 /*
198 * Get the default socket buffer sizes if we don't already have them.
199 * It doesn't matter which socket we do this to, because on the first
200 * call no socket buffer sizes will have been modified, so we are
201 * guaranteed to get the system defaults.
202 */
203 s = socket(AF_INET, SOCK_STREAM, 0);
204 if (s == -1)
205 err(1, "can't create socket");
206 len = sizeof(rcvbuf_size);
207 if (getsockopt(s, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size, &len)
208 < 0)
209 err(1, "unable to get default rcvbuf size");
210 len = sizeof(sndbuf_size);
211 if (getsockopt(s, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size, &len)
212 < 0)
213 err(1, "unable to get default sndbuf size");
214 (void)close(s);
215 /* sanity check returned buffer sizes */
216 if (rcvbuf_size <= 0)
217 rcvbuf_size = 8 * 1024;
218 if (sndbuf_size <= 0)
219 sndbuf_size = 8 * 1024;
220
221 if (sndbuf_size > 8 * 1024 * 1024)
222 sndbuf_size = 8 * 1024 * 1024;
223 if (rcvbuf_size > 8 * 1024 * 1024)
224 rcvbuf_size = 8 * 1024 * 1024;
225
226 marg_sl = xsl_init();
227 if ((tmpdir = getenv("TMPDIR")) == NULL)
228 tmpdir = _PATH_TMP;
229
230 /* Set default operation mode based on FTPMODE environment variable */
231 if ((cp = getenv("FTPMODE")) != NULL) {
232 if (strcasecmp(cp, "passive") == 0) {
233 passivemode = 1;
234 activefallback = 0;
235 } else if (strcasecmp(cp, "active") == 0) {
236 passivemode = 0;
237 activefallback = 0;
238 } else if (strcasecmp(cp, "gate") == 0) {
239 gatemode = 1;
240 } else if (strcasecmp(cp, "auto") == 0) {
241 passivemode = 1;
242 activefallback = 1;
243 } else
244 warnx("unknown $FTPMODE '%s'; using defaults", cp);
245 }
246
247 if (strcmp(getprogname(), "pftp") == 0) {
248 passivemode = 1;
249 activefallback = 0;
250 } else if (strcmp(getprogname(), "gate-ftp") == 0)
251 gatemode = 1;
252
253 gateserver = getenv("FTPSERVER");
254 if (gateserver == NULL || *gateserver == '\0')
255 gateserver = GATE_SERVER;
256 if (gatemode) {
257 if (*gateserver == '\0') {
258 warnx(
259 "Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp");
260 gatemode = 0;
261 }
262 }
263
264 cp = getenv("TERM");
265 if (cp == NULL || strcmp(cp, "dumb") == 0)
266 dumbterm = 1;
267 else
268 dumbterm = 0;
269 fromatty = isatty(fileno(stdin));
270 ttyout = stdout;
271 if (isatty(fileno(ttyout))) {
272 verbose = 1; /* verbose if to a tty */
273 if (! dumbterm) {
274 #ifndef NO_EDITCOMPLETE
275 if (fromatty) /* editing mode on if tty is usable */
276 editing = 1;
277 #endif
278 #ifndef NO_PROGRESS
279 if (foregroundproc())
280 progress = 1; /* progress bar on if fg */
281 #endif
282 }
283 }
284
285 while ((ch = getopt(argc, argv, "46AadefginN:o:pP:q:r:RtT:u:vV")) != -1) {
286 switch (ch) {
287 case '4':
288 family = AF_INET;
289 break;
290
291 case '6':
292 #ifdef INET6
293 family = AF_INET6;
294 #else
295 warnx("INET6 support is not available; ignoring -6");
296 #endif
297 break;
298
299 case 'A':
300 activefallback = 0;
301 passivemode = 0;
302 break;
303
304 case 'a':
305 anonftp = 1;
306 break;
307
308 case 'd':
309 options |= SO_DEBUG;
310 debug++;
311 break;
312
313 case 'e':
314 #ifndef NO_EDITCOMPLETE
315 editing = 0;
316 #endif
317 break;
318
319 case 'f':
320 flushcache = 1;
321 break;
322
323 case 'g':
324 doglob = 0;
325 break;
326
327 case 'i':
328 interactive = 0;
329 break;
330
331 case 'n':
332 autologin = 0;
333 break;
334
335 case 'N':
336 if (strlcpy(netrc, optarg, sizeof(netrc))
337 >= sizeof(netrc))
338 errx(1, "%s: %s", optarg,
339 strerror(ENAMETOOLONG));
340 break;
341
342 case 'o':
343 outfile = optarg;
344 if (strcmp(outfile, "-") == 0)
345 ttyout = stderr;
346 break;
347
348 case 'p':
349 passivemode = 1;
350 activefallback = 0;
351 break;
352
353 case 'P':
354 ftpport = optarg;
355 break;
356
357 case 'q':
358 quit_time = strtol(optarg, &ep, 10);
359 if (quit_time < 1 || *ep != '\0')
360 errx(1, "bad quit value: %s", optarg);
361 break;
362
363 case 'r':
364 retry_connect = strtol(optarg, &ep, 10);
365 if (retry_connect < 1 || *ep != '\0')
366 errx(1, "bad retry value: %s", optarg);
367 break;
368
369 case 'R':
370 restartautofetch = 1;
371 break;
372
373 case 't':
374 trace = 1;
375 break;
376
377 case 'T':
378 {
379 int targc;
380 char *targv[6], *oac;
381
382 /* look for `dir,max[,incr]' */
383 targc = 0;
384 targv[targc++] = "-T";
385 oac = xstrdup(optarg);
386
387 while ((cp = strsep(&oac, ",")) != NULL) {
388 if (*cp == '\0') {
389 warnx("bad throttle value: %s", optarg);
390 usage();
391 /* NOTREACHED */
392 }
393 targv[targc++] = cp;
394 if (targc >= 5)
395 break;
396 }
397 if (parserate(targc, targv, 1) == -1)
398 usage();
399 free(oac);
400 break;
401 }
402
403 case 'u':
404 {
405 isupload = 1;
406 interactive = 0;
407 upload_path = xstrdup(optarg);
408
409 break;
410 }
411
412 case 'v':
413 progress = verbose = 1;
414 break;
415
416 case 'V':
417 progress = verbose = 0;
418 break;
419
420 default:
421 usage();
422 }
423 }
424 /* set line buffering on ttyout */
425 setvbuf(ttyout, NULL, _IOLBF, 0);
426 argc -= optind;
427 argv += optind;
428
429 cpend = 0; /* no pending replies */
430 proxy = 0; /* proxy not active */
431 crflag = 1; /* strip c.r. on ascii gets */
432 sendport = -1; /* not using ports */
433
434 /*
435 * Cache the user name and home directory.
436 */
437 localhome = NULL;
438 localname = NULL;
439 anonuser = "anonymous";
440 cp = getenv("HOME");
441 if (! EMPTYSTRING(cp))
442 localhome = xstrdup(cp);
443 pw = NULL;
444 cp = getlogin();
445 if (cp != NULL)
446 pw = getpwnam(cp);
447 if (pw == NULL)
448 pw = getpwuid(getuid());
449 if (pw != NULL) {
450 if (localhome == NULL && !EMPTYSTRING(pw->pw_dir))
451 localhome = xstrdup(pw->pw_dir);
452 localname = xstrdup(pw->pw_name);
453 anonuser = localname;
454 }
455 if (netrc[0] == '\0' && localhome != NULL) {
456 if (strlcpy(netrc, localhome, sizeof(netrc)) >= sizeof(netrc) ||
457 strlcat(netrc, "/.netrc", sizeof(netrc)) >= sizeof(netrc)) {
458 warnx("%s/.netrc: %s", localhome,
459 strerror(ENAMETOOLONG));
460 netrc[0] = '\0';
461 }
462 }
463 if (localhome == NULL)
464 localhome = xstrdup("/");
465
466 /*
467 * Every anonymous FTP server I've encountered will accept the
468 * string "username@", and will append the hostname itself. We
469 * do this by default since many servers are picky about not
470 * having a FQDN in the anonymous password.
471 * - thorpej (at) NetBSD.org
472 */
473 len = strlen(anonuser) + 2;
474 anonpass = xmalloc(len);
475 (void)strlcpy(anonpass, anonuser, len);
476 (void)strlcat(anonpass, "@", len);
477
478 /*
479 * set all the defaults for options defined in
480 * struct option optiontab[] declared in cmdtab.c
481 */
482 setupoption("anonpass", getenv("FTPANONPASS"), anonpass);
483 setupoption("ftp_proxy", getenv(FTP_PROXY), "");
484 setupoption("http_proxy", getenv(HTTP_PROXY), "");
485 setupoption("no_proxy", getenv(NO_PROXY), "");
486 setupoption("pager", getenv("PAGER"), DEFAULTPAGER);
487 setupoption("prompt", getenv("FTPPROMPT"), DEFAULTPROMPT);
488 setupoption("rprompt", getenv("FTPRPROMPT"), DEFAULTRPROMPT);
489
490 free(anonpass);
491
492 setttywidth(0);
493 #ifdef SIGINFO
494 (void)xsignal(SIGINFO, psummary);
495 #endif
496 (void)xsignal(SIGQUIT, psummary);
497 (void)xsignal(SIGUSR1, crankrate);
498 (void)xsignal(SIGUSR2, crankrate);
499 (void)xsignal(SIGWINCH, setttywidth);
500
501 #ifdef __GNUC__ /* to shut up gcc warnings */
502 (void)&argc;
503 (void)&argv;
504 #endif
505
506 if (argc > 0) {
507 if (isupload) {
508 rval = auto_put(argc, argv, upload_path);
509 exit(rval);
510 } else if (strchr(argv[0], ':') != NULL
511 && ! isipv6addr(argv[0])) {
512 rval = auto_fetch(argc, argv);
513 if (rval >= 0) /* -1 == connected and cd-ed */
514 exit(rval);
515 } else {
516 char *xargv[4], *user, *host;
517
518 if (sigsetjmp(toplevel, 1))
519 exit(0);
520 (void)xsignal(SIGINT, intr);
521 (void)xsignal(SIGPIPE, lostpeer);
522 user = NULL;
523 host = argv[0];
524 cp = strchr(host, '@');
525 if (cp) {
526 *cp = '\0';
527 user = host;
528 host = cp + 1;
529 }
530 /* XXX discards const */
531 xargv[0] = (char *)getprogname();
532 xargv[1] = host;
533 xargv[2] = argv[1];
534 xargv[3] = NULL;
535 do {
536 int oautologin;
537
538 oautologin = autologin;
539 if (user != NULL) {
540 anonftp = 0;
541 autologin = 0;
542 }
543 setpeer(argc+1, xargv);
544 autologin = oautologin;
545 if (connected == 1 && user != NULL)
546 (void)ftp_login(host, user, NULL);
547 if (!retry_connect)
548 break;
549 if (!connected) {
550 macnum = 0;
551 fprintf(ttyout,
552 "Retrying in %d seconds...\n",
553 retry_connect);
554 sleep(retry_connect);
555 }
556 } while (!connected);
557 retry_connect = 0; /* connected, stop hiding msgs */
558 }
559 }
560 if (isupload)
561 usage();
562
563 #ifndef NO_EDITCOMPLETE
564 controlediting();
565 #endif /* !NO_EDITCOMPLETE */
566
567 (void)sigsetjmp(toplevel, 1);
568 (void)xsignal(SIGINT, intr);
569 (void)xsignal(SIGPIPE, lostpeer);
570 for (;;)
571 cmdscanner();
572 }
573
574 /*
575 * Generate a prompt
576 */
577 char *
578 prompt(void)
579 {
580 static char **prompt;
581 static char buf[MAXPATHLEN];
582
583 if (prompt == NULL) {
584 struct option *o;
585
586 o = getoption("prompt");
587 if (o == NULL)
588 errx(1, "no such option `prompt'");
589 prompt = &(o->value);
590 }
591 formatbuf(buf, sizeof(buf), *prompt ? *prompt : DEFAULTPROMPT);
592 return (buf);
593 }
594
595 /*
596 * Generate an rprompt
597 */
598 char *
599 rprompt(void)
600 {
601 static char **rprompt;
602 static char buf[MAXPATHLEN];
603
604 if (rprompt == NULL) {
605 struct option *o;
606
607 o = getoption("rprompt");
608 if (o == NULL)
609 errx(1, "no such option `rprompt'");
610 rprompt = &(o->value);
611 }
612 formatbuf(buf, sizeof(buf), *rprompt ? *rprompt : DEFAULTRPROMPT);
613 return (buf);
614 }
615
616 /*
617 * Command parser.
618 */
619 void
620 cmdscanner(void)
621 {
622 struct cmd *c;
623 char *p;
624 int num;
625
626 for (;;) {
627 #ifndef NO_EDITCOMPLETE
628 if (!editing) {
629 #endif /* !NO_EDITCOMPLETE */
630 if (fromatty) {
631 fputs(prompt(), ttyout);
632 p = rprompt();
633 if (*p)
634 fprintf(ttyout, "%s ", p);
635 (void)fflush(ttyout);
636 }
637 if (fgets(line, sizeof(line), stdin) == NULL) {
638 if (fromatty)
639 putc('\n', ttyout);
640 quit(0, NULL);
641 }
642 num = strlen(line);
643 if (num == 0)
644 break;
645 if (line[--num] == '\n') {
646 if (num == 0)
647 break;
648 line[num] = '\0';
649 } else if (num == sizeof(line) - 2) {
650 fputs("sorry, input line too long.\n", ttyout);
651 while ((num = getchar()) != '\n' && num != EOF)
652 /* void */;
653 break;
654 } /* else it was a line without a newline */
655 #ifndef NO_EDITCOMPLETE
656 } else {
657 const char *buf;
658 HistEvent ev;
659 cursor_pos = NULL;
660
661 if ((buf = el_gets(el, &num)) == NULL || num == 0) {
662 if (fromatty)
663 putc('\n', ttyout);
664 quit(0, NULL);
665 }
666 if (buf[--num] == '\n') {
667 if (num == 0)
668 break;
669 } else if (num >= sizeof(line)) {
670 fputs("sorry, input line too long.\n", ttyout);
671 break;
672 }
673 memcpy(line, buf, num);
674 line[num] = '\0';
675 history(hist, &ev, H_ENTER, buf);
676 }
677 #endif /* !NO_EDITCOMPLETE */
678
679 makeargv();
680 if (margc == 0)
681 continue;
682 c = getcmd(margv[0]);
683 if (c == (struct cmd *)-1) {
684 fputs("?Ambiguous command.\n", ttyout);
685 continue;
686 }
687 if (c == NULL) {
688 #if !defined(NO_EDITCOMPLETE)
689 /*
690 * attempt to el_parse() unknown commands.
691 * any command containing a ':' would be parsed
692 * as "[prog:]cmd ...", and will result in a
693 * false positive if prog != "ftp", so treat
694 * such commands as invalid.
695 */
696 if (strchr(margv[0], ':') != NULL ||
697 el_parse(el, margc, (const char **)margv) != 0)
698 #endif /* !NO_EDITCOMPLETE */
699 fputs("?Invalid command.\n", ttyout);
700 continue;
701 }
702 if (c->c_conn && !connected) {
703 fputs("Not connected.\n", ttyout);
704 continue;
705 }
706 confirmrest = 0;
707 margv[0] = c->c_name;
708 (*c->c_handler)(margc, margv);
709 if (bell && c->c_bell)
710 (void)putc('\007', ttyout);
711 if (c->c_handler != help)
712 break;
713 }
714 (void)xsignal(SIGINT, intr);
715 (void)xsignal(SIGPIPE, lostpeer);
716 }
717
718 struct cmd *
719 getcmd(const char *name)
720 {
721 const char *p, *q;
722 struct cmd *c, *found;
723 int nmatches, longest;
724
725 if (name == NULL)
726 return (0);
727
728 longest = 0;
729 nmatches = 0;
730 found = 0;
731 for (c = cmdtab; (p = c->c_name) != NULL; c++) {
732 for (q = name; *q == *p++; q++)
733 if (*q == 0) /* exact match? */
734 return (c);
735 if (!*q) { /* the name was a prefix */
736 if (q - name > longest) {
737 longest = q - name;
738 nmatches = 1;
739 found = c;
740 } else if (q - name == longest)
741 nmatches++;
742 }
743 }
744 if (nmatches > 1)
745 return ((struct cmd *)-1);
746 return (found);
747 }
748
749 /*
750 * Slice a string up into argc/argv.
751 */
752
753 int slrflag;
754
755 void
756 makeargv(void)
757 {
758 char *argp;
759
760 stringbase = line; /* scan from first of buffer */
761 argbase = argbuf; /* store from first of buffer */
762 slrflag = 0;
763 marg_sl->sl_cur = 0; /* reset to start of marg_sl */
764 for (margc = 0; ; margc++) {
765 argp = slurpstring();
766 xsl_add(marg_sl, argp);
767 if (argp == NULL)
768 break;
769 }
770 #ifndef NO_EDITCOMPLETE
771 if (cursor_pos == line) {
772 cursor_argc = 0;
773 cursor_argo = 0;
774 } else if (cursor_pos != NULL) {
775 cursor_argc = margc;
776 cursor_argo = strlen(margv[margc-1]);
777 }
778 #endif /* !NO_EDITCOMPLETE */
779 }
780
781 #ifdef NO_EDITCOMPLETE
782 #define INC_CHKCURSOR(x) (x)++
783 #else /* !NO_EDITCOMPLETE */
784 #define INC_CHKCURSOR(x) { (x)++ ; \
785 if (x == cursor_pos) { \
786 cursor_argc = margc; \
787 cursor_argo = ap-argbase; \
788 cursor_pos = NULL; \
789 } }
790
791 #endif /* !NO_EDITCOMPLETE */
792
793 /*
794 * Parse string into argbuf;
795 * implemented with FSM to
796 * handle quoting and strings
797 */
798 char *
799 slurpstring(void)
800 {
801 int got_one = 0;
802 char *sb = stringbase;
803 char *ap = argbase;
804 char *tmp = argbase; /* will return this if token found */
805
806 if (*sb == '!' || *sb == '$') { /* recognize ! as a token for shell */
807 switch (slrflag) { /* and $ as token for macro invoke */
808 case 0:
809 slrflag++;
810 INC_CHKCURSOR(stringbase);
811 return ((*sb == '!') ? "!" : "$");
812 /* NOTREACHED */
813 case 1:
814 slrflag++;
815 altarg = stringbase;
816 break;
817 default:
818 break;
819 }
820 }
821
822 S0:
823 switch (*sb) {
824
825 case '\0':
826 goto OUT;
827
828 case ' ':
829 case '\t':
830 INC_CHKCURSOR(sb);
831 goto S0;
832
833 default:
834 switch (slrflag) {
835 case 0:
836 slrflag++;
837 break;
838 case 1:
839 slrflag++;
840 altarg = sb;
841 break;
842 default:
843 break;
844 }
845 goto S1;
846 }
847
848 S1:
849 switch (*sb) {
850
851 case ' ':
852 case '\t':
853 case '\0':
854 goto OUT; /* end of token */
855
856 case '\\':
857 INC_CHKCURSOR(sb);
858 goto S2; /* slurp next character */
859
860 case '"':
861 INC_CHKCURSOR(sb);
862 goto S3; /* slurp quoted string */
863
864 default:
865 *ap = *sb; /* add character to token */
866 ap++;
867 INC_CHKCURSOR(sb);
868 got_one = 1;
869 goto S1;
870 }
871
872 S2:
873 switch (*sb) {
874
875 case '\0':
876 goto OUT;
877
878 default:
879 *ap = *sb;
880 ap++;
881 INC_CHKCURSOR(sb);
882 got_one = 1;
883 goto S1;
884 }
885
886 S3:
887 switch (*sb) {
888
889 case '\0':
890 goto OUT;
891
892 case '"':
893 INC_CHKCURSOR(sb);
894 goto S1;
895
896 default:
897 *ap = *sb;
898 ap++;
899 INC_CHKCURSOR(sb);
900 got_one = 1;
901 goto S3;
902 }
903
904 OUT:
905 if (got_one)
906 *ap++ = '\0';
907 argbase = ap; /* update storage pointer */
908 stringbase = sb; /* update scan pointer */
909 if (got_one) {
910 return (tmp);
911 }
912 switch (slrflag) {
913 case 0:
914 slrflag++;
915 break;
916 case 1:
917 slrflag++;
918 altarg = NULL;
919 break;
920 default:
921 break;
922 }
923 return (NULL);
924 }
925
926 /*
927 * Help/usage command.
928 * Call each command handler with argc == 0 and argv[0] == name.
929 */
930 void
931 help(int argc, char *argv[])
932 {
933 struct cmd *c;
934 char *nargv[1], *p, *cmd;
935 int isusage;
936
937 cmd = argv[0];
938 isusage = (strcmp(cmd, "usage") == 0);
939 if (argc == 0 || (isusage && argc == 1)) {
940 fprintf(ttyout, "usage: %s [command [...]]\n", cmd);
941 return;
942 }
943 if (argc == 1) {
944 StringList *buf;
945
946 buf = xsl_init();
947 fprintf(ttyout,
948 "%sommands may be abbreviated. Commands are:\n\n",
949 proxy ? "Proxy c" : "C");
950 for (c = cmdtab; (p = c->c_name) != NULL; c++)
951 if (!proxy || c->c_proxy)
952 xsl_add(buf, p);
953 list_vertical(buf);
954 sl_free(buf, 0);
955 return;
956 }
957
958 #define HELPINDENT ((int) sizeof("disconnect"))
959
960 while (--argc > 0) {
961 char *arg;
962
963 arg = *++argv;
964 c = getcmd(arg);
965 if (c == (struct cmd *)-1)
966 fprintf(ttyout, "?Ambiguous %s command `%s'\n",
967 cmd, arg);
968 else if (c == NULL)
969 fprintf(ttyout, "?Invalid %s command `%s'\n",
970 cmd, arg);
971 else {
972 if (isusage) {
973 nargv[0] = c->c_name;
974 (*c->c_handler)(0, nargv);
975 } else
976 fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
977 c->c_name, c->c_help);
978 }
979 }
980 }
981
982 struct option *
983 getoption(const char *name)
984 {
985 const char *p;
986 struct option *c;
987
988 if (name == NULL)
989 return (NULL);
990 for (c = optiontab; (p = c->name) != NULL; c++) {
991 if (strcasecmp(p, name) == 0)
992 return (c);
993 }
994 return (NULL);
995 }
996
997 char *
998 getoptionvalue(const char *name)
999 {
1000 struct option *c;
1001
1002 if (name == NULL)
1003 errx(1, "getoptionvalue() invoked with NULL name");
1004 c = getoption(name);
1005 if (c != NULL)
1006 return (c->value);
1007 errx(1, "getoptionvalue() invoked with unknown option `%s'", name);
1008 /* NOTREACHED */
1009 }
1010
1011 static void
1012 setupoption(char *name, char *value, char *defaultvalue)
1013 {
1014 char *nargv[3];
1015 int overbose;
1016
1017 nargv[0] = "setupoption()";
1018 nargv[1] = name;
1019 nargv[2] = (value ? value : defaultvalue);
1020 overbose = verbose;
1021 verbose = 0;
1022 setoption(3, nargv);
1023 verbose = overbose;
1024 }
1025
1026 void
1027 usage(void)
1028 {
1029 const char *progname = getprogname();
1030
1031 (void)fprintf(stderr,
1032 "usage: %s [-46AadefginpRtvV] [-N netrc] [-o outfile] [-P port] [-q quittime]\n"
1033 " [-r retry] [-T dir,max[,inc][[user@]host [port]]] [host:path[/]]\n"
1034 " [file:///file] [ftp://[user[:pass]@]host[:port]/path[/]]\n"
1035 " [http://[user[:pass]@]host[:port]/path] [...]\n"
1036 " %s -u URL file [...]\n", progname, progname);
1037 exit(1);
1038 }
1039