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