1 /* $NetBSD: main.c,v 1.104 2007/04/17 05:52:03 lukem Exp $ */
4 * Copyright (c) 1996-2005 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.104 2007/04/17 05:52:03 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 volatile argc, char **volatile argv)
145 char *cp, *ep, *anonuser, *anonpass, *upload_path, *src_addr;
146 int dumbterm, s, isupload;
150 setlocale(LC_ALL, "");
151 setprogname(argv[0]);
158 cp = getenv("FTPSERVERPORT");
162 gateport = "ftpgate";
174 restartautofetch = 0;
175 #ifndef NO_EDITCOMPLETE
183 rate_get_incr = DEFAULTINCR;
185 rate_put_incr = DEFAULTINCR;
195 reply_callback = NULL;
199 cp = getenv("NETRC");
200 if (cp != NULL && strlcpy(netrc, cp, sizeof(netrc)) >= sizeof(netrc))
201 errx(1, "$NETRC `%s': %s", cp, strerror(ENAMETOOLONG));
204 * Get the default socket buffer sizes if we don't already have them.
205 * It doesn't matter which socket we do this to, because on the first
206 * call no socket buffer sizes will have been modified, so we are
207 * guaranteed to get the system defaults.
209 s = socket(AF_INET, SOCK_STREAM, 0);
211 err(1, "Can't create socket to determine default socket sizes");
212 slen = sizeof(rcvbuf_size);
213 if (getsockopt(s, SOL_SOCKET, SO_RCVBUF,
214 (void *)&rcvbuf_size, &slen) == -1)
215 err(1, "Unable to get default rcvbuf size");
216 slen = sizeof(sndbuf_size);
217 if (getsockopt(s, SOL_SOCKET, SO_SNDBUF,
218 (void *)&sndbuf_size, &slen) == -1)
219 err(1, "Unable to get default sndbuf size");
221 /* sanity check returned buffer sizes */
222 if (rcvbuf_size <= 0)
223 rcvbuf_size = 8 * 1024;
224 if (sndbuf_size <= 0)
225 sndbuf_size = 8 * 1024;
227 if (sndbuf_size > 8 * 1024 * 1024)
228 sndbuf_size = 8 * 1024 * 1024;
229 if (rcvbuf_size > 8 * 1024 * 1024)
230 rcvbuf_size = 8 * 1024 * 1024;
232 marg_sl = ftp_sl_init();
233 if ((tmpdir = getenv("TMPDIR")) == NULL)
236 /* Set default operation mode based on FTPMODE environment variable */
237 if ((cp = getenv("FTPMODE")) != NULL) {
238 if (strcasecmp(cp, "passive") == 0) {
241 } else if (strcasecmp(cp, "active") == 0) {
244 } else if (strcasecmp(cp, "gate") == 0) {
246 } else if (strcasecmp(cp, "auto") == 0) {
250 warnx("Unknown $FTPMODE `%s'; using defaults", cp);
253 if (strcmp(getprogname(), "pftp") == 0) {
256 } else if (strcmp(getprogname(), "gate-ftp") == 0)
259 gateserver = getenv("FTPSERVER");
260 if (gateserver == NULL || *gateserver == '\0')
261 gateserver = GATE_SERVER;
263 if (*gateserver == '\0') {
265 "Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp");
271 if (cp == NULL || strcmp(cp, "dumb") == 0)
275 fromatty = isatty(fileno(stdin));
277 if (isatty(fileno(ttyout))) {
278 verbose = 1; /* verbose if to a tty */
280 #ifndef NO_EDITCOMPLETE
281 if (fromatty) /* editing mode on if tty is usable */
285 if (foregroundproc())
286 progress = 1; /* progress bar on if fg */
291 while ((ch = getopt(argc, argv, "46AadefginN:o:pP:q:r:Rs:tT:u:vV")) != -1) {
301 warnx("INET6 support is not available; ignoring -6");
320 #ifndef NO_EDITCOMPLETE
342 if (strlcpy(netrc, optarg, sizeof(netrc))
344 errx(1, "%s: %s", optarg,
345 strerror(ENAMETOOLONG));
350 if (strcmp(outfile, "-") == 0)
364 quit_time = strtol(optarg, &ep, 10);
365 if (quit_time < 1 || *ep != '\0')
366 errx(1, "Bad quit value: %s", optarg);
370 retry_connect = strtol(optarg, &ep, 10);
371 if (retry_connect < 1 || *ep != '\0')
372 errx(1, "Bad retry value: %s", optarg);
376 restartautofetch = 1;
390 char *targv[6], *oac;
392 /* look for `dir,max[,incr]' */
394 targv[targc++] = "-T";
395 oac = ftp_strdup(optarg);
397 while ((cp = strsep(&oac, ",")) != NULL) {
399 warnx("Bad throttle value `%s'",
408 if (parserate(targc, targv, 1) == -1)
418 upload_path = ftp_strdup(optarg);
424 progress = verbose = 1;
428 progress = verbose = 0;
435 /* set line buffering on ttyout */
436 setvbuf(ttyout, NULL, _IOLBF, 0);
440 cpend = 0; /* no pending replies */
441 proxy = 0; /* proxy not active */
442 crflag = 1; /* strip c.r. on ascii gets */
443 sendport = -1; /* not using ports */
445 if (src_addr != NULL) {
446 struct addrinfo hints;
449 memset(&hints, 0, sizeof(hints));
450 hints.ai_family = family;
451 hints.ai_socktype = SOCK_STREAM;
452 hints.ai_flags = AI_PASSIVE;
453 error = getaddrinfo(src_addr, NULL, &hints, &bindai);
455 errx(1, "Can't lookup `%s': %s", src_addr,
456 (error == EAI_SYSTEM) ? strerror(errno)
457 : gai_strerror(error));
462 * Cache the user name and home directory.
466 anonuser = "anonymous";
468 if (! EMPTYSTRING(cp))
469 localhome = ftp_strdup(cp);
475 pw = getpwuid(getuid());
477 if (localhome == NULL && !EMPTYSTRING(pw->pw_dir))
478 localhome = ftp_strdup(pw->pw_dir);
479 localname = ftp_strdup(pw->pw_name);
480 anonuser = localname;
482 if (netrc[0] == '\0' && localhome != NULL) {
483 if (strlcpy(netrc, localhome, sizeof(netrc)) >= sizeof(netrc) ||
484 strlcat(netrc, "/.netrc", sizeof(netrc)) >= sizeof(netrc)) {
485 warnx("%s/.netrc: %s", localhome,
486 strerror(ENAMETOOLONG));
490 if (localhome == NULL)
491 localhome = ftp_strdup("/");
494 * Every anonymous FTP server I've encountered will accept the
495 * string "username@", and will append the hostname itself. We
496 * do this by default since many servers are picky about not
497 * having a FQDN in the anonymous password.
498 * - thorpej@NetBSD.org
500 len = strlen(anonuser) + 2;
501 anonpass = ftp_malloc(len);
502 (void)strlcpy(anonpass, anonuser, len);
503 (void)strlcat(anonpass, "@", len);
506 * set all the defaults for options defined in
507 * struct option optiontab[] declared in cmdtab.c
509 setupoption("anonpass", getenv("FTPANONPASS"), anonpass);
510 setupoption("ftp_proxy", getenv(FTP_PROXY), "");
511 setupoption("http_proxy", getenv(HTTP_PROXY), "");
512 setupoption("no_proxy", getenv(NO_PROXY), "");
513 setupoption("pager", getenv("PAGER"), DEFAULTPAGER);
514 setupoption("prompt", getenv("FTPPROMPT"), DEFAULTPROMPT);
515 setupoption("rprompt", getenv("FTPRPROMPT"), DEFAULTRPROMPT);
521 (void)xsignal(SIGINFO, psummary);
523 (void)xsignal(SIGQUIT, psummary);
524 (void)xsignal(SIGUSR1, crankrate);
525 (void)xsignal(SIGUSR2, crankrate);
526 (void)xsignal(SIGWINCH, setttywidth);
530 rval = auto_put(argc, argv, upload_path);
533 (void)xsignal(SIGINT, SIG_DFL);
537 } else if (strchr(argv[0], ':') != NULL
538 && ! isipv6addr(argv[0])) {
539 rval = auto_fetch(argc, argv);
540 if (rval >= 0) /* -1 == connected and cd-ed */
541 goto sigint_or_rval_exit;
543 char *xargv[4], *user, *host;
545 if ((rval = sigsetjmp(toplevel, 1)))
546 goto sigint_or_rval_exit;
547 (void)xsignal(SIGINT, intr);
548 (void)xsignal(SIGPIPE, lostpeer);
551 cp = strchr(host, '@');
557 /* XXX discards const */
558 xargv[0] = (char *)getprogname();
565 oautologin = autologin;
570 setpeer(argc+1, xargv);
571 autologin = oautologin;
572 if (connected == 1 && user != NULL)
573 (void)ftp_login(host, user, NULL);
579 "Retrying in %d seconds...\n",
581 sleep(retry_connect);
583 } while (!connected);
584 retry_connect = 0; /* connected, stop hiding msgs */
590 #ifndef NO_EDITCOMPLETE
592 #endif /* !NO_EDITCOMPLETE */
594 (void)sigsetjmp(toplevel, 1);
595 (void)xsignal(SIGINT, intr);
596 (void)xsignal(SIGPIPE, lostpeer);
607 static char **prompt;
608 static char buf[MAXPATHLEN];
610 if (prompt == NULL) {
613 o = getoption("prompt");
615 errx(1, "prompt: no such option `prompt'");
616 prompt = &(o->value);
618 formatbuf(buf, sizeof(buf), *prompt ? *prompt : DEFAULTPROMPT);
623 * Generate an rprompt
628 static char **rprompt;
629 static char buf[MAXPATHLEN];
631 if (rprompt == NULL) {
634 o = getoption("rprompt");
636 errx(1, "rprompt: no such option `rprompt'");
637 rprompt = &(o->value);
639 formatbuf(buf, sizeof(buf), *rprompt ? *rprompt : DEFAULTRPROMPT);
651 #ifndef NO_EDITCOMPLETE
657 #ifndef NO_EDITCOMPLETE
659 #endif /* !NO_EDITCOMPLETE */
661 fputs(prompt(), ttyout);
664 fprintf(ttyout, "%s ", p);
666 (void)fflush(ttyout);
667 num = getline(stdin, line, sizeof(line), NULL);
675 case -3: /* too long; try again */
676 fputs("Sorry, input line is too long.\n",
679 case 0: /* empty; try again */
681 default: /* all ok */
684 #ifndef NO_EDITCOMPLETE
690 buf = el_gets(el, &ch);
692 if (buf == NULL || num == 0) {
697 if (num >= sizeof(line)) {
698 fputs("Sorry, input line is too long.\n",
702 memcpy(line, buf, num);
703 if (line[--num] == '\n') {
708 history(hist, &ev, H_ENTER, buf);
710 #endif /* !NO_EDITCOMPLETE */
715 c = getcmd(margv[0]);
716 if (c == (struct cmd *)-1) {
717 fputs("?Ambiguous command.\n", ttyout);
721 #if !defined(NO_EDITCOMPLETE)
723 * attempt to el_parse() unknown commands.
724 * any command containing a ':' would be parsed
725 * as "[prog:]cmd ...", and will result in a
726 * false positive if prog != "ftp", so treat
727 * such commands as invalid.
729 if (strchr(margv[0], ':') != NULL ||
730 el_parse(el, margc, (const char **)margv) != 0)
731 #endif /* !NO_EDITCOMPLETE */
732 fputs("?Invalid command.\n", ttyout);
735 if (c->c_conn && !connected) {
736 fputs("Not connected.\n", ttyout);
740 margv[0] = c->c_name;
741 (*c->c_handler)(margc, margv);
742 if (bell && c->c_bell)
743 (void)putc('\007', ttyout);
744 if (c->c_handler != help)
747 (void)xsignal(SIGINT, intr);
748 (void)xsignal(SIGPIPE, lostpeer);
752 getcmd(const char *name)
755 struct cmd *c, *found;
756 int nmatches, longest;
764 for (c = cmdtab; (p = c->c_name) != NULL; c++) {
765 for (q = name; *q == *p++; q++)
766 if (*q == 0) /* exact match? */
768 if (!*q) { /* the name was a prefix */
769 if (q - name > longest) {
773 } else if (q - name == longest)
778 return ((struct cmd *)-1);
783 * Slice a string up into argc/argv.
793 stringbase = line; /* scan from first of buffer */
794 argbase = argbuf; /* store from first of buffer */
796 marg_sl->sl_cur = 0; /* reset to start of marg_sl */
797 for (margc = 0; ; margc++) {
798 argp = slurpstring();
799 ftp_sl_add(marg_sl, argp);
803 #ifndef NO_EDITCOMPLETE
804 if (cursor_pos == line) {
807 } else if (cursor_pos != NULL) {
809 cursor_argo = strlen(margv[margc-1]);
811 #endif /* !NO_EDITCOMPLETE */
814 #ifdef NO_EDITCOMPLETE
815 #define INC_CHKCURSOR(x) (x)++
816 #else /* !NO_EDITCOMPLETE */
817 #define INC_CHKCURSOR(x) { (x)++ ; \
818 if (x == cursor_pos) { \
819 cursor_argc = margc; \
820 cursor_argo = ap-argbase; \
824 #endif /* !NO_EDITCOMPLETE */
827 * Parse string into argbuf;
828 * implemented with FSM to
829 * handle quoting and strings
835 char *sb = stringbase;
837 char *tmp = argbase; /* will return this if token found */
839 if (*sb == '!' || *sb == '$') { /* recognize ! as a token for shell */
840 switch (slrflag) { /* and $ as token for macro invoke */
843 INC_CHKCURSOR(stringbase);
844 return ((*sb == '!') ? "!" : "$");
887 goto OUT; /* end of token */
891 goto S2; /* slurp next character */
895 goto S3; /* slurp quoted string */
898 *ap = *sb; /* add character to token */
940 argbase = ap; /* update storage pointer */
941 stringbase = sb; /* update scan pointer */
960 * Help/usage command.
961 * Call each command handler with argc == 0 and argv[0] == name.
964 help(int argc, char *argv[])
967 char *nargv[1], *p, *cmd;
971 isusage = (strcmp(cmd, "usage") == 0);
972 if (argc == 0 || (isusage && argc == 1)) {
973 UPRINTF("usage: %s [command [...]]\n", cmd);
981 "%sommands may be abbreviated. Commands are:\n\n",
982 proxy ? "Proxy c" : "C");
983 for (c = cmdtab; (p = c->c_name) != NULL; c++)
984 if (!proxy || c->c_proxy)
991 #define HELPINDENT ((int) sizeof("disconnect"))
998 if (c == (struct cmd *)-1)
999 fprintf(ttyout, "?Ambiguous %s command `%s'\n",
1002 fprintf(ttyout, "?Invalid %s command `%s'\n",
1006 nargv[0] = c->c_name;
1007 (*c->c_handler)(0, nargv);
1009 fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
1010 c->c_name, c->c_help);
1016 getoption(const char *name)
1023 for (c = optiontab; (p = c->name) != NULL; c++) {
1024 if (strcasecmp(p, name) == 0)
1031 getoptionvalue(const char *name)
1036 errx(1, "getoptionvalue: invoked with NULL name");
1037 c = getoption(name);
1040 errx(1, "getoptionvalue: invoked with unknown option `%s'", name);
1045 setupoption(char *name, char *value, char *defaultvalue)
1050 nargv[0] = "setupoption()";
1052 nargv[2] = (value ? value : defaultvalue);
1055 setoption(3, nargv);
1062 const char *progname = getprogname();
1064 (void)fprintf(stderr,
1065 "usage: %s [-46AadefginpRtvV] [-N netrc] [-o outfile] [-P port] [-q quittime]\n"
1066 " [-r retry] [-s srcaddr] [-T dir,max[,inc]]\n"
1067 " [[user@]host [port]] [host:path[/]] [file:///file]\n"
1068 " [ftp://[user[:pass]@]host[:port]/path[/]]\n"
1069 " [http://[user[:pass]@]host[:port]/path] [...]\n"
1070 " %s -u URL file [...]\n", progname, progname);