1 /* $NetBSD: main.c,v 1.94 2005/05/13 05:03:49 lukem Exp $ */
4 * Copyright (c) 1996-2004 The NetBSD Foundation, Inc.
7 * This code is derived from software contributed to The NetBSD Foundation
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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.
40 * Copyright (c) 1985, 1989, 1993, 1994
41 * The Regents of the University of California. All rights reserved.
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
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.
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
69 * Copyright (C) 1997 and 1998 WIDE Project.
70 * All rights reserved.
72 * Redistribution and use in source and binary forms, with or without
73 * modification, are permitted provided that the following conditions
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.
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
97 #include <sys/cdefs.h>
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 */
105 static char sccsid[] = "@(#)main.c 8.6 (Berkeley) 10/9/94";
107 __RCSID("$NetBSD: main.c,v 1.94 2005/05/13 05:03:49 lukem Exp $");
109 #endif /* not lint */
112 * FTP User Program -- Command Interface.
114 #include <sys/types.h>
115 #include <sys/socket.h>
129 #define GLOBAL /* force GLOBAL decls in ftp_var.h to be declared */
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 */
137 static void setupoption(char *, char *, char *);
138 int main(int, char *[]);
141 main(int argc, char *argv[])
145 char *cp, *ep, *anonuser, *anonpass, *upload_path;
146 int dumbterm, s, len, isupload;
149 setlocale(LC_ALL, "");
150 setprogname(argv[0]);
157 cp = getenv("FTPSERVERPORT");
161 gateport = "ftpgate";
173 restartautofetch = 0;
174 #ifndef NO_EDITCOMPLETE
182 rate_get_incr = DEFAULTINCR;
184 rate_put_incr = DEFAULTINCR;
193 reply_callback = NULL;
197 cp = getenv("NETRC");
198 if (cp != NULL && strlcpy(netrc, cp, sizeof(netrc)) >= sizeof(netrc))
199 errx(1, "$NETRC `%s': %s", cp, strerror(ENAMETOOLONG));
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.
207 s = socket(AF_INET, SOCK_STREAM, 0);
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");
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;
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;
230 marg_sl = xsl_init();
231 if ((tmpdir = getenv("TMPDIR")) == NULL)
234 /* Set default operation mode based on FTPMODE environment variable */
235 if ((cp = getenv("FTPMODE")) != NULL) {
236 if (strcasecmp(cp, "passive") == 0) {
239 } else if (strcasecmp(cp, "active") == 0) {
242 } else if (strcasecmp(cp, "gate") == 0) {
244 } else if (strcasecmp(cp, "auto") == 0) {
248 warnx("unknown $FTPMODE '%s'; using defaults", cp);
251 if (strcmp(getprogname(), "pftp") == 0) {
254 } else if (strcmp(getprogname(), "gate-ftp") == 0)
257 gateserver = getenv("FTPSERVER");
258 if (gateserver == NULL || *gateserver == '\0')
259 gateserver = GATE_SERVER;
261 if (*gateserver == '\0') {
263 "Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp");
269 if (cp == NULL || strcmp(cp, "dumb") == 0)
273 fromatty = isatty(fileno(stdin));
275 if (isatty(fileno(ttyout))) {
276 verbose = 1; /* verbose if to a tty */
278 #ifndef NO_EDITCOMPLETE
279 if (fromatty) /* editing mode on if tty is usable */
283 if (foregroundproc())
284 progress = 1; /* progress bar on if fg */
289 while ((ch = getopt(argc, argv, "46AadefginN:o:pP:q:r:RtT:u:vV")) != -1) {
299 warnx("INET6 support is not available; ignoring -6");
318 #ifndef NO_EDITCOMPLETE
340 if (strlcpy(netrc, optarg, sizeof(netrc))
342 errx(1, "%s: %s", optarg,
343 strerror(ENAMETOOLONG));
348 if (strcmp(outfile, "-") == 0)
362 quit_time = strtol(optarg, &ep, 10);
363 if (quit_time < 1 || *ep != '\0')
364 errx(1, "bad quit value: %s", optarg);
368 retry_connect = strtol(optarg, &ep, 10);
369 if (retry_connect < 1 || *ep != '\0')
370 errx(1, "bad retry value: %s", optarg);
374 restartautofetch = 1;
384 char *targv[6], *oac;
386 /* look for `dir,max[,incr]' */
388 targv[targc++] = "-T";
389 oac = xstrdup(optarg);
391 while ((cp = strsep(&oac, ",")) != NULL) {
393 warnx("bad throttle value: %s", optarg);
401 if (parserate(targc, targv, 1) == -1)
411 upload_path = xstrdup(optarg);
417 progress = verbose = 1;
421 progress = verbose = 0;
428 /* set line buffering on ttyout */
429 setvbuf(ttyout, NULL, _IOLBF, 0);
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 */
439 * Cache the user name and home directory.
443 anonuser = "anonymous";
445 if (! EMPTYSTRING(cp))
446 localhome = xstrdup(cp);
452 pw = getpwuid(getuid());
454 if (localhome == NULL && !EMPTYSTRING(pw->pw_dir))
455 localhome = xstrdup(pw->pw_dir);
456 localname = xstrdup(pw->pw_name);
457 anonuser = localname;
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));
467 if (localhome == NULL)
468 localhome = xstrdup("/");
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
477 len = strlen(anonuser) + 2;
478 anonpass = xmalloc(len);
479 (void)strlcpy(anonpass, anonuser, len);
480 (void)strlcat(anonpass, "@", len);
483 * set all the defaults for options defined in
484 * struct option optiontab[] declared in cmdtab.c
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);
498 (void)xsignal(SIGINFO, psummary);
500 (void)xsignal(SIGQUIT, psummary);
501 (void)xsignal(SIGUSR1, crankrate);
502 (void)xsignal(SIGUSR2, crankrate);
503 (void)xsignal(SIGWINCH, setttywidth);
505 #ifdef __GNUC__ /* to shut up gcc warnings */
512 rval = auto_put(argc, argv, upload_path);
515 (void)xsignal(SIGINT, SIG_DFL);
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;
525 char *xargv[4], *user, *host;
527 if ((rval = sigsetjmp(toplevel, 1)))
528 goto sigint_or_rval_exit;
529 (void)xsignal(SIGINT, intr);
530 (void)xsignal(SIGPIPE, lostpeer);
533 cp = strchr(host, '@');
539 /* XXX discards const */
540 xargv[0] = (char *)getprogname();
547 oautologin = autologin;
552 setpeer(argc+1, xargv);
553 autologin = oautologin;
554 if (connected == 1 && user != NULL)
555 (void)ftp_login(host, user, NULL);
561 "Retrying in %d seconds...\n",
563 sleep(retry_connect);
565 } while (!connected);
566 retry_connect = 0; /* connected, stop hiding msgs */
572 #ifndef NO_EDITCOMPLETE
574 #endif /* !NO_EDITCOMPLETE */
576 (void)sigsetjmp(toplevel, 1);
577 (void)xsignal(SIGINT, intr);
578 (void)xsignal(SIGPIPE, lostpeer);
589 static char **prompt;
590 static char buf[MAXPATHLEN];
592 if (prompt == NULL) {
595 o = getoption("prompt");
597 errx(1, "no such option `prompt'");
598 prompt = &(o->value);
600 formatbuf(buf, sizeof(buf), *prompt ? *prompt : DEFAULTPROMPT);
605 * Generate an rprompt
610 static char **rprompt;
611 static char buf[MAXPATHLEN];
613 if (rprompt == NULL) {
616 o = getoption("rprompt");
618 errx(1, "no such option `rprompt'");
619 rprompt = &(o->value);
621 formatbuf(buf, sizeof(buf), *rprompt ? *rprompt : DEFAULTRPROMPT);
636 #ifndef NO_EDITCOMPLETE
638 #endif /* !NO_EDITCOMPLETE */
640 fputs(prompt(), ttyout);
643 fprintf(ttyout, "%s ", p);
644 (void)fflush(ttyout);
646 if (fgets(line, sizeof(line), stdin) == NULL) {
654 if (line[--num] == '\n') {
658 } else if (num == sizeof(line) - 2) {
659 fputs("Sorry, input line is too long.\n",
661 while ((num = getchar()) != '\n' && num != EOF)
664 } /* else it was a line without a newline */
665 #ifndef NO_EDITCOMPLETE
671 buf = el_gets(el, &num);
672 if (buf == NULL || num == 0) {
677 if (num >= sizeof(line)) {
678 fputs("Sorry, input line is too long.\n",
682 memcpy(line, buf, num);
683 if (line[--num] == '\n') {
688 history(hist, &ev, H_ENTER, buf);
690 #endif /* !NO_EDITCOMPLETE */
695 c = getcmd(margv[0]);
696 if (c == (struct cmd *)-1) {
697 fputs("?Ambiguous command.\n", ttyout);
701 #if !defined(NO_EDITCOMPLETE)
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.
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);
715 if (c->c_conn && !connected) {
716 fputs("Not connected.\n", ttyout);
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)
727 (void)xsignal(SIGINT, intr);
728 (void)xsignal(SIGPIPE, lostpeer);
732 getcmd(const char *name)
735 struct cmd *c, *found;
736 int nmatches, longest;
744 for (c = cmdtab; (p = c->c_name) != NULL; c++) {
745 for (q = name; *q == *p++; q++)
746 if (*q == 0) /* exact match? */
748 if (!*q) { /* the name was a prefix */
749 if (q - name > longest) {
753 } else if (q - name == longest)
758 return ((struct cmd *)-1);
763 * Slice a string up into argc/argv.
773 stringbase = line; /* scan from first of buffer */
774 argbase = argbuf; /* store from first of buffer */
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);
783 #ifndef NO_EDITCOMPLETE
784 if (cursor_pos == line) {
787 } else if (cursor_pos != NULL) {
789 cursor_argo = strlen(margv[margc-1]);
791 #endif /* !NO_EDITCOMPLETE */
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; \
804 #endif /* !NO_EDITCOMPLETE */
807 * Parse string into argbuf;
808 * implemented with FSM to
809 * handle quoting and strings
815 char *sb = stringbase;
817 char *tmp = argbase; /* will return this if token found */
819 if (*sb == '!' || *sb == '$') { /* recognize ! as a token for shell */
820 switch (slrflag) { /* and $ as token for macro invoke */
823 INC_CHKCURSOR(stringbase);
824 return ((*sb == '!') ? "!" : "$");
867 goto OUT; /* end of token */
871 goto S2; /* slurp next character */
875 goto S3; /* slurp quoted string */
878 *ap = *sb; /* add character to token */
920 argbase = ap; /* update storage pointer */
921 stringbase = sb; /* update scan pointer */
940 * Help/usage command.
941 * Call each command handler with argc == 0 and argv[0] == name.
944 help(int argc, char *argv[])
947 char *nargv[1], *p, *cmd;
951 isusage = (strcmp(cmd, "usage") == 0);
952 if (argc == 0 || (isusage && argc == 1)) {
953 fprintf(ttyout, "usage: %s [command [...]]\n", cmd);
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)
971 #define HELPINDENT ((int) sizeof("disconnect"))
978 if (c == (struct cmd *)-1)
979 fprintf(ttyout, "?Ambiguous %s command `%s'\n",
982 fprintf(ttyout, "?Invalid %s command `%s'\n",
986 nargv[0] = c->c_name;
987 (*c->c_handler)(0, nargv);
989 fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
990 c->c_name, c->c_help);
996 getoption(const char *name)
1003 for (c = optiontab; (p = c->name) != NULL; c++) {
1004 if (strcasecmp(p, name) == 0)
1011 getoptionvalue(const char *name)
1016 errx(1, "getoptionvalue() invoked with NULL name");
1017 c = getoption(name);
1020 errx(1, "getoptionvalue() invoked with unknown option `%s'", name);
1025 setupoption(char *name, char *value, char *defaultvalue)
1030 nargv[0] = "setupoption()";
1032 nargv[2] = (value ? value : defaultvalue);
1035 setoption(3, nargv);
1042 const char *progname = getprogname();
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);