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