1 /* $NetBSD: main.c,v 1.109 2008/05/10 00:05:31 skd Exp $ */
4 * Copyright (c) 1996-2008 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.
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
33 * Copyright (c) 1985, 1989, 1993, 1994
34 * The Regents of the University of California. All rights reserved.
36 * Redistribution and use in source and binary forms, with or without
37 * modification, are permitted provided that the following conditions
39 * 1. Redistributions of source code must retain the above copyright
40 * notice, this list of conditions and the following disclaimer.
41 * 2. Redistributions in binary form must reproduce the above copyright
42 * notice, this list of conditions and the following disclaimer in the
43 * documentation and/or other materials provided with the distribution.
44 * 3. Neither the name of the University nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62 * Copyright (C) 1997 and 1998 WIDE Project.
63 * All rights reserved.
65 * Redistribution and use in source and binary forms, with or without
66 * modification, are permitted provided that the following conditions
68 * 1. Redistributions of source code must retain the above copyright
69 * notice, this list of conditions and the following disclaimer.
70 * 2. Redistributions in binary form must reproduce the above copyright
71 * notice, this list of conditions and the following disclaimer in the
72 * documentation and/or other materials provided with the distribution.
73 * 3. Neither the name of the project nor the names of its contributors
74 * may be used to endorse or promote products derived from this software
75 * without specific prior written permission.
77 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
78 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
81 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
82 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
83 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
84 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
85 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
86 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
90 #include <sys/cdefs.h>
92 __COPYRIGHT("@(#) Copyright (c) 1985, 1989, 1993, 1994\n\
93 The Regents of the University of California. All rights reserved.\n");
98 static char sccsid[] = "@(#)main.c 8.6 (Berkeley) 10/9/94";
100 __RCSID("$NetBSD: main.c,v 1.109 2008/05/10 00:05:31 skd Exp $");
102 #endif /* not lint */
105 * FTP User Program -- Command Interface.
107 #include <sys/types.h>
108 #include <sys/socket.h>
123 #define GLOBAL /* force GLOBAL decls in ftp_var.h to be declared */
126 #define FTP_PROXY "ftp_proxy" /* env var with FTP proxy location */
127 #define HTTP_PROXY "http_proxy" /* env var with HTTP proxy location */
128 #define NO_PROXY "no_proxy" /* env var with list of non-proxied
129 * hosts, comma or space separated */
131 static void setupoption(char *, char *, char *);
132 int main(int, char *[]);
135 main(int volatile argc, char **volatile argv)
139 char *cp, *ep, *anonuser, *anonpass, *upload_path, *src_addr;
140 int dumbterm, s, isupload;
145 setlocale(LC_ALL, "");
146 setprogname(argv[0]);
153 cp = getenv("FTPSERVERPORT");
157 gateport = "ftpgate";
169 restartautofetch = 0;
170 #ifndef NO_EDITCOMPLETE
178 rate_get_incr = DEFAULTINCR;
180 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 to determine default socket sizes");
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 = ftp_sl_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:Rs:tT: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;
388 char *targv[6], *oac;
390 /* look for `dir,max[,incr]' */
392 targv[targc++] = "-T";
393 oac = ftp_strdup(optarg);
395 while ((cp = strsep(&oac, ",")) != NULL) {
397 warnx("Bad throttle value `%s'",
406 if (parserate(targc, targv, 1) == -1)
416 upload_path = ftp_strdup(optarg);
422 progress = verbose = 1;
426 progress = verbose = 0;
433 /* set line buffering on ttyout */
434 setvbuf(ttyout, NULL, _IOLBF, 0);
438 cpend = 0; /* no pending replies */
439 proxy = 0; /* proxy not active */
440 crflag = 1; /* strip c.r. on ascii gets */
441 sendport = -1; /* not using ports */
443 if (src_addr != NULL) {
444 struct addrinfo hints;
447 memset(&hints, 0, sizeof(hints));
448 hints.ai_family = family;
449 hints.ai_socktype = SOCK_STREAM;
450 hints.ai_flags = AI_PASSIVE;
451 error = getaddrinfo(src_addr, NULL, &hints, &bindai);
453 errx(1, "Can't lookup `%s': %s", src_addr,
454 (error == EAI_SYSTEM) ? strerror(errno)
455 : gai_strerror(error));
460 * Cache the user name and home directory.
464 anonuser = "anonymous";
466 if (! EMPTYSTRING(cp))
467 localhome = ftp_strdup(cp);
473 pw = getpwuid(getuid());
475 if (localhome == NULL && !EMPTYSTRING(pw->pw_dir))
476 localhome = ftp_strdup(pw->pw_dir);
477 localname = ftp_strdup(pw->pw_name);
478 anonuser = localname;
480 if (netrc[0] == '\0' && localhome != NULL) {
481 if (strlcpy(netrc, localhome, sizeof(netrc)) >= sizeof(netrc) ||
482 strlcat(netrc, "/.netrc", sizeof(netrc)) >= sizeof(netrc)) {
483 warnx("%s/.netrc: %s", localhome,
484 strerror(ENAMETOOLONG));
488 if (localhome == NULL)
489 localhome = ftp_strdup("/");
492 * Every anonymous FTP server I've encountered will accept the
493 * string "username@", and will append the hostname itself. We
494 * do this by default since many servers are picky about not
495 * having a FQDN in the anonymous password.
496 * - thorpej@NetBSD.org
498 len = strlen(anonuser) + 2;
499 anonpass = ftp_malloc(len);
500 (void)strlcpy(anonpass, anonuser, len);
501 (void)strlcat(anonpass, "@", len);
504 * set all the defaults for options defined in
505 * struct option optiontab[] declared in cmdtab.c
507 setupoption("anonpass", getenv("FTPANONPASS"), anonpass);
508 setupoption("ftp_proxy", getenv(FTP_PROXY), "");
509 setupoption("http_proxy", getenv(HTTP_PROXY), "");
510 setupoption("no_proxy", getenv(NO_PROXY), "");
511 setupoption("pager", getenv("PAGER"), DEFAULTPAGER);
512 setupoption("prompt", getenv("FTPPROMPT"), DEFAULTPROMPT);
513 setupoption("rprompt", getenv("FTPRPROMPT"), DEFAULTRPROMPT);
519 (void)xsignal(SIGINFO, psummary);
521 (void)xsignal(SIGQUIT, psummary);
522 (void)xsignal(SIGUSR1, crankrate);
523 (void)xsignal(SIGUSR2, crankrate);
524 (void)xsignal(SIGWINCH, setttywidth);
528 rval = auto_put(argc, argv, upload_path);
531 (void)xsignal(SIGINT, SIG_DFL);
535 } else if (strchr(argv[0], ':') != NULL
536 && ! isipv6addr(argv[0])) {
537 rval = auto_fetch(argc, argv);
538 if (rval >= 0) /* -1 == connected and cd-ed */
539 goto sigint_or_rval_exit;
541 char *xargv[4], *user, *host;
543 if ((rval = sigsetjmp(toplevel, 1)))
544 goto sigint_or_rval_exit;
545 (void)xsignal(SIGINT, intr);
546 (void)xsignal(SIGPIPE, lostpeer);
549 cp = strchr(host, '@');
555 /* XXX discards const */
556 xargv[0] = (char *)getprogname();
563 oautologin = autologin;
568 setpeer(argc+1, xargv);
569 autologin = oautologin;
570 if (connected == 1 && user != NULL)
571 (void)ftp_login(host, user, NULL);
577 "Retrying in %d seconds...\n",
579 sleep(retry_connect);
581 } while (!connected);
582 retry_connect = 0; /* connected, stop hiding msgs */
588 #ifndef NO_EDITCOMPLETE
590 #endif /* !NO_EDITCOMPLETE */
592 (void)sigsetjmp(toplevel, 1);
593 (void)xsignal(SIGINT, intr);
594 (void)xsignal(SIGPIPE, lostpeer);
605 static char **prompt;
606 static char buf[MAXPATHLEN];
608 if (prompt == NULL) {
611 o = getoption("prompt");
613 errx(1, "prompt: no such option `prompt'");
614 prompt = &(o->value);
616 formatbuf(buf, sizeof(buf), *prompt ? *prompt : DEFAULTPROMPT);
621 * Generate an rprompt
626 static char **rprompt;
627 static char buf[MAXPATHLEN];
629 if (rprompt == NULL) {
632 o = getoption("rprompt");
634 errx(1, "rprompt: no such option `rprompt'");
635 rprompt = &(o->value);
637 formatbuf(buf, sizeof(buf), *rprompt ? *rprompt : DEFAULTRPROMPT);
649 #ifndef NO_EDITCOMPLETE
655 #ifndef NO_EDITCOMPLETE
657 #endif /* !NO_EDITCOMPLETE */
659 fputs(prompt(), ttyout);
662 fprintf(ttyout, "%s ", p);
664 (void)fflush(ttyout);
665 num = getline(stdin, line, sizeof(line), NULL);
673 case -3: /* too long; try again */
674 fputs("Sorry, input line is too long.\n",
677 case 0: /* empty; try again */
679 default: /* all ok */
682 #ifndef NO_EDITCOMPLETE
688 buf = el_gets(el, &ch);
690 if (buf == NULL || num == 0) {
695 if (num >= sizeof(line)) {
696 fputs("Sorry, input line is too long.\n",
700 memcpy(line, buf, num);
701 if (line[--num] == '\n') {
706 history(hist, &ev, H_ENTER, buf);
708 #endif /* !NO_EDITCOMPLETE */
713 c = getcmd(margv[0]);
714 if (c == (struct cmd *)-1) {
715 fputs("?Ambiguous command.\n", ttyout);
719 #if !defined(NO_EDITCOMPLETE)
721 * attempt to el_parse() unknown commands.
722 * any command containing a ':' would be parsed
723 * as "[prog:]cmd ...", and will result in a
724 * false positive if prog != "ftp", so treat
725 * such commands as invalid.
727 if (strchr(margv[0], ':') != NULL ||
729 el_parse(el, margc, (const char **)margv) != 0)
730 #endif /* !NO_EDITCOMPLETE */
731 fputs("?Invalid command.\n", ttyout);
734 if (c->c_conn && !connected) {
735 fputs("Not connected.\n", ttyout);
739 margv[0] = c->c_name;
740 (*c->c_handler)(margc, margv);
741 if (bell && c->c_bell)
742 (void)putc('\007', ttyout);
743 if (c->c_handler != help)
746 (void)xsignal(SIGINT, intr);
747 (void)xsignal(SIGPIPE, lostpeer);
751 getcmd(const char *name)
754 struct cmd *c, *found;
755 int nmatches, longest;
763 for (c = cmdtab; (p = c->c_name) != NULL; c++) {
764 for (q = name; *q == *p++; q++)
765 if (*q == 0) /* exact match? */
767 if (!*q) { /* the name was a prefix */
768 if (q - name > longest) {
772 } else if (q - name == longest)
777 return ((struct cmd *)-1);
782 * Slice a string up into argc/argv.
792 stringbase = line; /* scan from first of buffer */
793 argbase = argbuf; /* store from first of buffer */
795 marg_sl->sl_cur = 0; /* reset to start of marg_sl */
796 for (margc = 0; ; margc++) {
797 argp = slurpstring();
798 ftp_sl_add(marg_sl, argp);
802 #ifndef NO_EDITCOMPLETE
803 if (cursor_pos == line) {
806 } else if (cursor_pos != NULL) {
808 cursor_argo = strlen(margv[margc-1]);
810 #endif /* !NO_EDITCOMPLETE */
813 #ifdef NO_EDITCOMPLETE
814 #define INC_CHKCURSOR(x) (x)++
815 #else /* !NO_EDITCOMPLETE */
816 #define INC_CHKCURSOR(x) { (x)++ ; \
817 if (x == cursor_pos) { \
818 cursor_argc = margc; \
819 cursor_argo = ap-argbase; \
823 #endif /* !NO_EDITCOMPLETE */
826 * Parse string into argbuf;
827 * implemented with FSM to
828 * handle quoting and strings
834 char *sb = stringbase;
836 char *tmp = argbase; /* will return this if token found */
838 if (*sb == '!' || *sb == '$') { /* recognize ! as a token for shell */
839 switch (slrflag) { /* and $ as token for macro invoke */
842 INC_CHKCURSOR(stringbase);
843 return ((*sb == '!') ? "!" : "$");
886 goto OUT; /* end of token */
890 goto S2; /* slurp next character */
894 goto S3; /* slurp quoted string */
897 *ap = *sb; /* add character to token */
939 argbase = ap; /* update storage pointer */
940 stringbase = sb; /* update scan pointer */
959 * Help/usage command.
960 * Call each command handler with argc == 0 and argv[0] == name.
963 help(int argc, char *argv[])
966 char *nargv[1], *p, *cmd;
970 isusage = (strcmp(cmd, "usage") == 0);
971 if (argc == 0 || (isusage && argc == 1)) {
972 UPRINTF("usage: %s [command [...]]\n", cmd);
980 "%sommands may be abbreviated. Commands are:\n\n",
981 proxy ? "Proxy c" : "C");
982 for (c = cmdtab; (p = c->c_name) != NULL; c++)
983 if (!proxy || c->c_proxy)
990 #define HELPINDENT ((int) sizeof("disconnect"))
997 if (c == (struct cmd *)-1)
998 fprintf(ttyout, "?Ambiguous %s command `%s'\n",
1001 fprintf(ttyout, "?Invalid %s command `%s'\n",
1005 nargv[0] = c->c_name;
1006 (*c->c_handler)(0, nargv);
1008 fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
1009 c->c_name, c->c_help);
1015 getoption(const char *name)
1022 for (c = optiontab; (p = c->name) != NULL; c++) {
1023 if (strcasecmp(p, name) == 0)
1030 getoptionvalue(const char *name)
1035 errx(1, "getoptionvalue: invoked with NULL name");
1036 c = getoption(name);
1039 errx(1, "getoptionvalue: invoked with unknown option `%s'", name);
1044 setupoption(char *name, char *value, char *defaultvalue)
1049 nargv[0] = "setupoption()";
1051 nargv[2] = (value ? value : defaultvalue);
1054 setoption(3, nargv);
1061 const char *progname = getprogname();
1063 (void)fprintf(stderr,
1064 "usage: %s [-46AadefginpRtVv] [-N netrc] [-o outfile] [-P port] [-q quittime]\n"
1065 " [-r retry] [-s srcaddr] [-T dir,max[,inc]]\n"
1066 " [[user@]host [port]] [host:path[/]] [file:///file]\n"
1067 " [ftp://[user[:pass]@]host[:port]/path[/]]\n"
1068 " [http://[user[:pass]@]host[:port]/path] [...]\n"
1069 " %s -u URL file [...]\n", progname, progname);