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