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 */
5 * Copyright (c) 1996-2009 The NetBSD Foundation, Inc.
8 * This code is derived from software contributed to The NetBSD Foundation
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
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.
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.
34 * Copyright (c) 1985, 1989, 1993, 1994
35 * The Regents of the University of California. All rights reserved.
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
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.
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
63 * Copyright (C) 1997 and 1998 WIDE Project.
64 * All rights reserved.
66 * Redistribution and use in source and binary forms, with or without
67 * modification, are permitted provided that the following conditions
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.
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
95 #include <sys/cdefs.h>
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 */
104 static char sccsid[] = "@(#)main.c 8.6 (Berkeley) 10/9/94";
106 __RCSID(" NetBSD: main.c,v 1.117 2009/07/13 19:05:41 roy Exp ");
108 #endif /* not lint */
111 * FTP User Program -- Command Interface.
113 #include <sys/types.h>
114 #include <sys/socket.h>
131 #define GLOBAL /* force GLOBAL decls in ftp_var.h to be declared */
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 */
139 static void setupoption(const char *, const char *, const char *);
140 int main(int, char *[]);
143 main(int volatile argc, char **volatile argv)
147 char *cp, *ep, *anonpass, *upload_path, *src_addr;
148 const char *anonuser;
149 int dumbterm, isupload;
153 #if 0 /* tnftp */ /* XXX */
154 setlocale(LC_ALL, "");
156 setprogname(argv[0]);
163 cp = getenv("FTPSERVERPORT");
167 gateport = "ftpgate";
179 restartautofetch = 0;
180 #ifndef NO_EDITCOMPLETE
188 rate_get_incr = DEFAULTINCR;
190 rate_put_incr = DEFAULTINCR;
203 reply_callback = NULL;
207 family = AF_INET; /* force AF_INET if no INET6 support */
211 cp = getenv("NETRC");
212 if (cp != NULL && strlcpy(netrc, cp, sizeof(netrc)) >= sizeof(netrc))
213 errx(1, "$NETRC `%s': %s", cp, strerror(ENAMETOOLONG));
215 marg_sl = ftp_sl_init();
216 if ((tmpdir = getenv("TMPDIR")) == NULL)
219 /* Set default operation mode based on FTPMODE environment variable */
220 if ((cp = getenv("FTPMODE")) != NULL) {
221 if (strcasecmp(cp, "passive") == 0) {
224 } else if (strcasecmp(cp, "active") == 0) {
227 } else if (strcasecmp(cp, "gate") == 0) {
229 } else if (strcasecmp(cp, "auto") == 0) {
233 warnx("Unknown $FTPMODE `%s'; using defaults", cp);
236 if (strcmp(getprogname(), "pftp") == 0) {
239 } else if (strcmp(getprogname(), "gate-ftp") == 0)
242 gateserver = getenv("FTPSERVER");
243 if (gateserver == NULL || *gateserver == '\0')
244 gateserver = GATE_SERVER;
246 if (*gateserver == '\0') {
248 "Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp");
254 if (cp == NULL || strcmp(cp, "dumb") == 0)
258 fromatty = isatty(fileno(stdin));
260 if (isatty(fileno(ttyout))) {
261 verbose = 1; /* verbose if to a tty */
263 #ifndef NO_EDITCOMPLETE
264 if (fromatty) /* editing mode on if tty is usable */
268 if (foregroundproc())
269 progress = 1; /* progress bar on if fg */
274 while ((ch = getopt(argc, argv, "46AadefginN:o:pP:q:r:Rs:tT:u:vV")) != -1) {
284 warnx("INET6 support is not available; ignoring -6");
303 #ifndef NO_EDITCOMPLETE
325 if (strlcpy(netrc, optarg, sizeof(netrc))
327 errx(1, "%s: %s", optarg,
328 strerror(ENAMETOOLONG));
333 if (strcmp(outfile, "-") == 0)
347 quit_time = strtol(optarg, &ep, 10);
348 if (quit_time < 1 || *ep != '\0')
349 errx(1, "Bad quit value: %s", optarg);
353 retry_connect = strtol(optarg, &ep, 10);
354 if (retry_connect < 1 || *ep != '\0')
355 errx(1, "Bad retry value: %s", optarg);
359 restartautofetch = 1;
373 char *targv[6], *oac;
374 char cmdbuf[MAX_C_NAME];
376 /* look for `dir,max[,incr]' */
378 (void)strlcpy(cmdbuf, "-T", sizeof(cmdbuf));
379 targv[targc++] = cmdbuf;
380 oac = ftp_strdup(optarg);
382 while ((cp = strsep(&oac, ",")) != NULL) {
384 warnx("Bad throttle value `%s'",
393 if (parserate(targc, targv, 1) == -1)
403 upload_path = ftp_strdup(optarg);
409 progress = verbose = 1;
413 progress = verbose = 0;
420 /* set line buffering on ttyout */
421 setvbuf(ttyout, NULL, _IOLBF, 0);
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 */
430 if (src_addr != NULL) {
431 struct addrinfo hints;
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);
440 errx(1, "Can't lookup `%s': %s", src_addr,
441 (error == EAI_SYSTEM) ? strerror(errno)
442 : gai_strerror(error));
447 * Cache the user name and home directory.
451 anonuser = "anonymous";
453 if (! EMPTYSTRING(cp))
454 localhome = ftp_strdup(cp);
460 pw = getpwuid(getuid());
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;
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));
475 if (localhome == NULL)
476 localhome = ftp_strdup("/");
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
485 len = strlen(anonuser) + 2;
486 anonpass = ftp_malloc(len);
487 (void)strlcpy(anonpass, anonuser, len);
488 (void)strlcat(anonpass, "@", len);
491 * set all the defaults for options defined in
492 * struct option optiontab[] declared in cmdtab.c
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);
506 (void)xsignal(SIGINFO, psummary);
508 (void)xsignal(SIGQUIT, psummary);
509 (void)xsignal(SIGUSR1, crankrate);
510 (void)xsignal(SIGUSR2, crankrate);
511 (void)xsignal(SIGWINCH, setttywidth);
515 rval = auto_put(argc, argv, upload_path);
518 (void)xsignal(SIGINT, SIG_DFL);
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;
528 char *xargv[4], *uuser, *host;
529 char cmdbuf[MAXPATHLEN];
531 if ((rval = sigsetjmp(toplevel, 1)))
532 goto sigint_or_rval_exit;
533 (void)xsignal(SIGINT, intr);
534 (void)xsignal(SIGPIPE, lostpeer);
537 cp = strchr(host, '@');
543 (void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
551 oautologin = autologin;
556 setpeer(argc+1, xargv);
557 autologin = oautologin;
558 if (connected == 1 && uuser != NULL)
559 (void)ftp_login(host, uuser, NULL);
565 "Retrying in %d seconds...\n",
567 sleep(retry_connect);
569 } while (!connected);
570 retry_connect = 0; /* connected, stop hiding msgs */
576 #ifndef NO_EDITCOMPLETE
578 #endif /* !NO_EDITCOMPLETE */
580 (void)sigsetjmp(toplevel, 1);
581 (void)xsignal(SIGINT, intr);
582 (void)xsignal(SIGPIPE, lostpeer);
593 static char **promptopt;
594 static char buf[MAXPATHLEN];
596 if (promptopt == NULL) {
599 o = getoption("prompt");
601 errx(1, "prompt: no such option `prompt'");
602 promptopt = &(o->value);
604 formatbuf(buf, sizeof(buf), *promptopt ? *promptopt : DEFAULTPROMPT);
609 * Generate an rprompt
614 static char **rpromptopt;
615 static char buf[MAXPATHLEN];
617 if (rpromptopt == NULL) {
620 o = getoption("rprompt");
622 errx(1, "rprompt: no such option `rprompt'");
623 rpromptopt = &(o->value);
625 formatbuf(buf, sizeof(buf), *rpromptopt ? *rpromptopt : DEFAULTRPROMPT);
637 #ifndef NO_EDITCOMPLETE
642 char cmdbuf[MAX_C_NAME];
645 #ifndef NO_EDITCOMPLETE
647 #endif /* !NO_EDITCOMPLETE */
649 fputs(prompt(), ttyout);
652 fprintf(ttyout, "%s ", p);
654 (void)fflush(ttyout);
655 len = get_line(stdin, line, sizeof(line), NULL);
663 case -3: /* too long; try again */
664 fputs("Sorry, input line is too long.\n",
667 case 0: /* empty; try again */
669 default: /* all ok */
672 #ifndef NO_EDITCOMPLETE
678 buf = el_gets(el, &ch);
680 if (buf == NULL || num == 0) {
685 if (num >= sizeof(line)) {
686 fputs("Sorry, input line is too long.\n",
690 memcpy(line, buf, num);
691 if (line[--num] == '\n') {
696 history(hist, &ev, H_ENTER, buf);
698 #endif /* !NO_EDITCOMPLETE */
703 c = getcmd(margv[0]);
704 if (c == (struct cmd *)-1) {
705 fputs("?Ambiguous command.\n", ttyout);
709 #if !defined(NO_EDITCOMPLETE)
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.
717 if (strchr(margv[0], ':') != NULL ||
719 el_parse(el, margc, (const char **)margv) != 0)
720 #endif /* !NO_EDITCOMPLETE */
721 fputs("?Invalid command.\n", ttyout);
724 if (c->c_conn && !connected) {
725 fputs("Not connected.\n", ttyout);
729 (void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf));
731 (*c->c_handler)(margc, margv);
732 if (bell && c->c_bell)
733 (void)putc('\007', ttyout);
734 if (c->c_handler != help)
737 (void)xsignal(SIGINT, intr);
738 (void)xsignal(SIGPIPE, lostpeer);
742 getcmd(const char *name)
745 struct cmd *c, *found;
746 int nmatches, longest;
754 for (c = cmdtab; (p = c->c_name) != NULL; c++) {
755 for (q = name; *q == *p++; q++)
756 if (*q == 0) /* exact match? */
758 if (!*q) { /* the name was a prefix */
759 if (q - name > longest) {
763 } else if (q - name == longest)
768 return ((struct cmd *)-1);
773 * Slice a string up into argc/argv.
783 stringbase = line; /* scan from first of buffer */
784 argbase = argbuf; /* store from first of buffer */
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);
793 #ifndef NO_EDITCOMPLETE
794 if (cursor_pos == line) {
797 } else if (cursor_pos != NULL) {
799 cursor_argo = strlen(margv[margc-1]);
801 #endif /* !NO_EDITCOMPLETE */
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; \
814 #endif /* !NO_EDITCOMPLETE */
817 * Parse string into argbuf;
818 * implemented with FSM to
819 * handle quoting and strings
824 static char bangstr[2] = { '!', '\0' };
825 static char dollarstr[2] = { '$', '\0' };
827 char *sb = stringbase;
829 char *tmp = argbase; /* will return this if token found */
831 if (*sb == '!' || *sb == '$') { /* recognize ! as a token for shell */
832 switch (slrflag) { /* and $ as token for macro invoke */
835 INC_CHKCURSOR(stringbase);
836 return ((*sb == '!') ? bangstr : dollarstr);
879 goto OUT; /* end of token */
883 goto S2; /* slurp next character */
887 goto S3; /* slurp quoted string */
890 *ap = *sb; /* add character to token */
932 argbase = ap; /* update storage pointer */
933 stringbase = sb; /* update scan pointer */
952 * Help/usage command.
953 * Call each command handler with argc == 0 and argv[0] == name.
956 help(int argc, char *argv[])
959 char *nargv[1], *cmd;
964 isusage = (strcmp(cmd, "usage") == 0);
965 if (argc == 0 || (isusage && argc == 1)) {
966 UPRINTF("usage: %s [command [...]]\n", cmd);
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));
984 #define HELPINDENT ((int) sizeof("disconnect"))
988 char cmdbuf[MAX_C_NAME];
992 if (c == (struct cmd *)-1)
993 fprintf(ttyout, "?Ambiguous %s command `%s'\n",
996 fprintf(ttyout, "?Invalid %s command `%s'\n",
1000 (void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf));
1002 (*c->c_handler)(0, nargv);
1004 fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
1005 c->c_name, c->c_help);
1011 getoption(const char *name)
1018 for (c = optiontab; (p = c->name) != NULL; c++) {
1019 if (strcasecmp(p, name) == 0)
1026 getoptionvalue(const char *name)
1031 errx(1, "getoptionvalue: invoked with NULL name");
1032 c = getoption(name);
1035 errx(1, "getoptionvalue: invoked with unknown option `%s'", name);
1040 setupoption(const char *name, const char *value, const char *defaultvalue)
1042 set_option(name, value ? value : defaultvalue, 0);
1048 const char *progname = getprogname();
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);