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, s, isupload;
154 #if 0 /* tnftp */ /* XXX */
155 setlocale(LC_ALL, "");
157 setprogname(argv[0]);
164 cp = getenv("FTPSERVERPORT");
168 gateport = "ftpgate";
180 restartautofetch = 0;
181 #ifndef NO_EDITCOMPLETE
189 rate_get_incr = DEFAULTINCR;
191 rate_put_incr = DEFAULTINCR;
204 reply_callback = NULL;
208 family = AF_INET; /* force AF_INET if no INET6 support */
212 cp = getenv("NETRC");
213 if (cp != NULL && strlcpy(netrc, cp, sizeof(netrc)) >= sizeof(netrc))
214 errx(1, "$NETRC `%s': %s", cp, strerror(ENAMETOOLONG));
217 * Get the default socket buffer sizes if we don't already have them.
218 * It doesn't matter which socket we do this to, because on the first
219 * call no socket buffer sizes will have been modified, so we are
220 * guaranteed to get the system defaults.
222 s = socket(AF_INET, SOCK_STREAM, 0);
224 err(1, "Can't create socket to determine default socket sizes");
225 slen = sizeof(rcvbuf_size);
226 if (getsockopt(s, SOL_SOCKET, SO_RCVBUF,
227 (void *)&rcvbuf_size, &slen) == -1)
228 err(1, "Unable to get default rcvbuf size");
229 slen = sizeof(sndbuf_size);
230 if (getsockopt(s, SOL_SOCKET, SO_SNDBUF,
231 (void *)&sndbuf_size, &slen) == -1)
232 err(1, "Unable to get default sndbuf size");
234 /* sanity check returned buffer sizes */
235 if (rcvbuf_size <= 0)
236 rcvbuf_size = 8 * 1024;
237 if (sndbuf_size <= 0)
238 sndbuf_size = 8 * 1024;
240 if (sndbuf_size > 8 * 1024 * 1024)
241 sndbuf_size = 8 * 1024 * 1024;
242 if (rcvbuf_size > 8 * 1024 * 1024)
243 rcvbuf_size = 8 * 1024 * 1024;
245 marg_sl = ftp_sl_init();
246 if ((tmpdir = getenv("TMPDIR")) == NULL)
249 /* Set default operation mode based on FTPMODE environment variable */
250 if ((cp = getenv("FTPMODE")) != NULL) {
251 if (strcasecmp(cp, "passive") == 0) {
254 } else if (strcasecmp(cp, "active") == 0) {
257 } else if (strcasecmp(cp, "gate") == 0) {
259 } else if (strcasecmp(cp, "auto") == 0) {
263 warnx("Unknown $FTPMODE `%s'; using defaults", cp);
266 if (strcmp(getprogname(), "pftp") == 0) {
269 } else if (strcmp(getprogname(), "gate-ftp") == 0)
272 gateserver = getenv("FTPSERVER");
273 if (gateserver == NULL || *gateserver == '\0')
274 gateserver = GATE_SERVER;
276 if (*gateserver == '\0') {
278 "Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp");
284 if (cp == NULL || strcmp(cp, "dumb") == 0)
288 fromatty = isatty(fileno(stdin));
290 if (isatty(fileno(ttyout))) {
291 verbose = 1; /* verbose if to a tty */
293 #ifndef NO_EDITCOMPLETE
294 if (fromatty) /* editing mode on if tty is usable */
298 if (foregroundproc())
299 progress = 1; /* progress bar on if fg */
304 while ((ch = getopt(argc, argv, "46AadefginN:o:pP:q:r:Rs:tT:u:vV")) != -1) {
314 warnx("INET6 support is not available; ignoring -6");
333 #ifndef NO_EDITCOMPLETE
355 if (strlcpy(netrc, optarg, sizeof(netrc))
357 errx(1, "%s: %s", optarg,
358 strerror(ENAMETOOLONG));
363 if (strcmp(outfile, "-") == 0)
377 quit_time = strtol(optarg, &ep, 10);
378 if (quit_time < 1 || *ep != '\0')
379 errx(1, "Bad quit value: %s", optarg);
383 retry_connect = strtol(optarg, &ep, 10);
384 if (retry_connect < 1 || *ep != '\0')
385 errx(1, "Bad retry value: %s", optarg);
389 restartautofetch = 1;
403 char *targv[6], *oac;
404 char cmdbuf[MAX_C_NAME];
406 /* look for `dir,max[,incr]' */
408 (void)strlcpy(cmdbuf, "-T", sizeof(cmdbuf));
409 targv[targc++] = cmdbuf;
410 oac = ftp_strdup(optarg);
412 while ((cp = strsep(&oac, ",")) != NULL) {
414 warnx("Bad throttle value `%s'",
423 if (parserate(targc, targv, 1) == -1)
433 upload_path = ftp_strdup(optarg);
439 progress = verbose = 1;
443 progress = verbose = 0;
450 /* set line buffering on ttyout */
451 setvbuf(ttyout, NULL, _IOLBF, 0);
455 cpend = 0; /* no pending replies */
456 proxy = 0; /* proxy not active */
457 crflag = 1; /* strip c.r. on ascii gets */
458 sendport = -1; /* not using ports */
460 if (src_addr != NULL) {
461 struct addrinfo hints;
464 memset(&hints, 0, sizeof(hints));
465 hints.ai_family = family;
466 hints.ai_socktype = SOCK_STREAM;
467 hints.ai_flags = AI_PASSIVE;
468 error = getaddrinfo(src_addr, NULL, &hints, &bindai);
470 errx(1, "Can't lookup `%s': %s", src_addr,
471 (error == EAI_SYSTEM) ? strerror(errno)
472 : gai_strerror(error));
477 * Cache the user name and home directory.
481 anonuser = "anonymous";
483 if (! EMPTYSTRING(cp))
484 localhome = ftp_strdup(cp);
490 pw = getpwuid(getuid());
492 if (localhome == NULL && !EMPTYSTRING(pw->pw_dir))
493 localhome = ftp_strdup(pw->pw_dir);
494 localname = ftp_strdup(pw->pw_name);
495 anonuser = localname;
497 if (netrc[0] == '\0' && localhome != NULL) {
498 if (strlcpy(netrc, localhome, sizeof(netrc)) >= sizeof(netrc) ||
499 strlcat(netrc, "/.netrc", sizeof(netrc)) >= sizeof(netrc)) {
500 warnx("%s/.netrc: %s", localhome,
501 strerror(ENAMETOOLONG));
505 if (localhome == NULL)
506 localhome = ftp_strdup("/");
509 * Every anonymous FTP server I've encountered will accept the
510 * string "username@", and will append the hostname itself. We
511 * do this by default since many servers are picky about not
512 * having a FQDN in the anonymous password.
513 * - thorpej@NetBSD.org
515 len = strlen(anonuser) + 2;
516 anonpass = ftp_malloc(len);
517 (void)strlcpy(anonpass, anonuser, len);
518 (void)strlcat(anonpass, "@", len);
521 * set all the defaults for options defined in
522 * struct option optiontab[] declared in cmdtab.c
524 setupoption("anonpass", getenv("FTPANONPASS"), anonpass);
525 setupoption("ftp_proxy", getenv(FTP_PROXY), "");
526 setupoption("http_proxy", getenv(HTTP_PROXY), "");
527 setupoption("no_proxy", getenv(NO_PROXY), "");
528 setupoption("pager", getenv("PAGER"), DEFAULTPAGER);
529 setupoption("prompt", getenv("FTPPROMPT"), DEFAULTPROMPT);
530 setupoption("rprompt", getenv("FTPRPROMPT"), DEFAULTRPROMPT);
536 (void)xsignal(SIGINFO, psummary);
538 (void)xsignal(SIGQUIT, psummary);
539 (void)xsignal(SIGUSR1, crankrate);
540 (void)xsignal(SIGUSR2, crankrate);
541 (void)xsignal(SIGWINCH, setttywidth);
545 rval = auto_put(argc, argv, upload_path);
548 (void)xsignal(SIGINT, SIG_DFL);
552 } else if (strchr(argv[0], ':') != NULL
553 && ! isipv6addr(argv[0])) {
554 rval = auto_fetch(argc, argv);
555 if (rval >= 0) /* -1 == connected and cd-ed */
556 goto sigint_or_rval_exit;
558 char *xargv[4], *uuser, *host;
559 char cmdbuf[MAXPATHLEN];
561 if ((rval = sigsetjmp(toplevel, 1)))
562 goto sigint_or_rval_exit;
563 (void)xsignal(SIGINT, intr);
564 (void)xsignal(SIGPIPE, lostpeer);
567 cp = strchr(host, '@');
573 (void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
581 oautologin = autologin;
586 setpeer(argc+1, xargv);
587 autologin = oautologin;
588 if (connected == 1 && uuser != NULL)
589 (void)ftp_login(host, uuser, NULL);
595 "Retrying in %d seconds...\n",
597 sleep(retry_connect);
599 } while (!connected);
600 retry_connect = 0; /* connected, stop hiding msgs */
606 #ifndef NO_EDITCOMPLETE
608 #endif /* !NO_EDITCOMPLETE */
610 (void)sigsetjmp(toplevel, 1);
611 (void)xsignal(SIGINT, intr);
612 (void)xsignal(SIGPIPE, lostpeer);
623 static char **promptopt;
624 static char buf[MAXPATHLEN];
626 if (promptopt == NULL) {
629 o = getoption("prompt");
631 errx(1, "prompt: no such option `prompt'");
632 promptopt = &(o->value);
634 formatbuf(buf, sizeof(buf), *promptopt ? *promptopt : DEFAULTPROMPT);
639 * Generate an rprompt
644 static char **rpromptopt;
645 static char buf[MAXPATHLEN];
647 if (rpromptopt == NULL) {
650 o = getoption("rprompt");
652 errx(1, "rprompt: no such option `rprompt'");
653 rpromptopt = &(o->value);
655 formatbuf(buf, sizeof(buf), *rpromptopt ? *rpromptopt : DEFAULTRPROMPT);
667 #ifndef NO_EDITCOMPLETE
672 char cmdbuf[MAX_C_NAME];
675 #ifndef NO_EDITCOMPLETE
677 #endif /* !NO_EDITCOMPLETE */
679 fputs(prompt(), ttyout);
682 fprintf(ttyout, "%s ", p);
684 (void)fflush(ttyout);
685 len = get_line(stdin, line, sizeof(line), NULL);
693 case -3: /* too long; try again */
694 fputs("Sorry, input line is too long.\n",
697 case 0: /* empty; try again */
699 default: /* all ok */
702 #ifndef NO_EDITCOMPLETE
708 buf = el_gets(el, &ch);
710 if (buf == NULL || num == 0) {
715 if (num >= sizeof(line)) {
716 fputs("Sorry, input line is too long.\n",
720 memcpy(line, buf, num);
721 if (line[--num] == '\n') {
726 history(hist, &ev, H_ENTER, buf);
728 #endif /* !NO_EDITCOMPLETE */
733 c = getcmd(margv[0]);
734 if (c == (struct cmd *)-1) {
735 fputs("?Ambiguous command.\n", ttyout);
739 #if !defined(NO_EDITCOMPLETE)
741 * attempt to el_parse() unknown commands.
742 * any command containing a ':' would be parsed
743 * as "[prog:]cmd ...", and will result in a
744 * false positive if prog != "ftp", so treat
745 * such commands as invalid.
747 if (strchr(margv[0], ':') != NULL ||
749 el_parse(el, margc, (const char **)margv) != 0)
750 #endif /* !NO_EDITCOMPLETE */
751 fputs("?Invalid command.\n", ttyout);
754 if (c->c_conn && !connected) {
755 fputs("Not connected.\n", ttyout);
759 (void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf));
761 (*c->c_handler)(margc, margv);
762 if (bell && c->c_bell)
763 (void)putc('\007', ttyout);
764 if (c->c_handler != help)
767 (void)xsignal(SIGINT, intr);
768 (void)xsignal(SIGPIPE, lostpeer);
772 getcmd(const char *name)
775 struct cmd *c, *found;
776 int nmatches, longest;
784 for (c = cmdtab; (p = c->c_name) != NULL; c++) {
785 for (q = name; *q == *p++; q++)
786 if (*q == 0) /* exact match? */
788 if (!*q) { /* the name was a prefix */
789 if (q - name > longest) {
793 } else if (q - name == longest)
798 return ((struct cmd *)-1);
803 * Slice a string up into argc/argv.
813 stringbase = line; /* scan from first of buffer */
814 argbase = argbuf; /* store from first of buffer */
816 marg_sl->sl_cur = 0; /* reset to start of marg_sl */
817 for (margc = 0; ; margc++) {
818 argp = slurpstring();
819 ftp_sl_add(marg_sl, argp);
823 #ifndef NO_EDITCOMPLETE
824 if (cursor_pos == line) {
827 } else if (cursor_pos != NULL) {
829 cursor_argo = strlen(margv[margc-1]);
831 #endif /* !NO_EDITCOMPLETE */
834 #ifdef NO_EDITCOMPLETE
835 #define INC_CHKCURSOR(x) (x)++
836 #else /* !NO_EDITCOMPLETE */
837 #define INC_CHKCURSOR(x) { (x)++ ; \
838 if (x == cursor_pos) { \
839 cursor_argc = margc; \
840 cursor_argo = ap-argbase; \
844 #endif /* !NO_EDITCOMPLETE */
847 * Parse string into argbuf;
848 * implemented with FSM to
849 * handle quoting and strings
854 static char bangstr[2] = { '!', '\0' };
855 static char dollarstr[2] = { '$', '\0' };
857 char *sb = stringbase;
859 char *tmp = argbase; /* will return this if token found */
861 if (*sb == '!' || *sb == '$') { /* recognize ! as a token for shell */
862 switch (slrflag) { /* and $ as token for macro invoke */
865 INC_CHKCURSOR(stringbase);
866 return ((*sb == '!') ? bangstr : dollarstr);
909 goto OUT; /* end of token */
913 goto S2; /* slurp next character */
917 goto S3; /* slurp quoted string */
920 *ap = *sb; /* add character to token */
962 argbase = ap; /* update storage pointer */
963 stringbase = sb; /* update scan pointer */
982 * Help/usage command.
983 * Call each command handler with argc == 0 and argv[0] == name.
986 help(int argc, char *argv[])
989 char *nargv[1], *cmd;
994 isusage = (strcmp(cmd, "usage") == 0);
995 if (argc == 0 || (isusage && argc == 1)) {
996 UPRINTF("usage: %s [command [...]]\n", cmd);
1002 buf = ftp_sl_init();
1004 "%sommands may be abbreviated. Commands are:\n\n",
1005 proxy ? "Proxy c" : "C");
1006 for (c = cmdtab; (p = c->c_name) != NULL; c++)
1007 if (!proxy || c->c_proxy)
1008 ftp_sl_add(buf, ftp_strdup(p));
1014 #define HELPINDENT ((int) sizeof("disconnect"))
1016 while (--argc > 0) {
1018 char cmdbuf[MAX_C_NAME];
1022 if (c == (struct cmd *)-1)
1023 fprintf(ttyout, "?Ambiguous %s command `%s'\n",
1026 fprintf(ttyout, "?Invalid %s command `%s'\n",
1030 (void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf));
1032 (*c->c_handler)(0, nargv);
1034 fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
1035 c->c_name, c->c_help);
1041 getoption(const char *name)
1048 for (c = optiontab; (p = c->name) != NULL; c++) {
1049 if (strcasecmp(p, name) == 0)
1056 getoptionvalue(const char *name)
1061 errx(1, "getoptionvalue: invoked with NULL name");
1062 c = getoption(name);
1065 errx(1, "getoptionvalue: invoked with unknown option `%s'", name);
1070 setupoption(const char *name, const char *value, const char *defaultvalue)
1072 set_option(name, value ? value : defaultvalue, 0);
1078 const char *progname = getprogname();
1080 (void)fprintf(stderr,
1081 "usage: %s [-46AadefginpRtVv] [-N netrc] [-o outfile] [-P port] [-q quittime]\n"
1082 " [-r retry] [-s srcaddr] [-T dir,max[,inc]]\n"
1083 " [[user@]host [port]] [host:path[/]] [file:///file]\n"
1084 " [ftp://[user[:pass]@]host[:port]/path[/]]\n"
1085 " [http://[user[:pass]@]host[:port]/path] [...]\n"
1086 " %s -u URL file [...]\n", progname, progname);