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 #include <sys/sysctl.h>
134 #define GLOBAL /* force GLOBAL decls in ftp_var.h to be declared */
137 #define FTP_PROXY "ftp_proxy" /* env var with FTP proxy location */
138 #define HTTP_PROXY "http_proxy" /* env var with HTTP proxy location */
139 #define NO_PROXY "no_proxy" /* env var with list of non-proxied
140 * hosts, comma or space separated */
142 static void setupoption(const char *, const char *, const char *);
143 int main(int, char *[]);
146 main(int volatile argc, char **volatile argv)
150 char *cp, *ep, *anonpass, *upload_path, *src_addr;
151 const char *anonuser;
152 int dumbterm, isupload;
156 #if 0 /* tnftp */ /* XXX */
157 setlocale(LC_ALL, "");
159 setprogname(argv[0]);
166 cp = getenv("FTPSERVERPORT");
170 gateport = "ftpgate";
182 restartautofetch = 0;
183 #ifndef NO_EDITCOMPLETE
191 rate_get_incr = DEFAULTINCR;
193 rate_put_incr = DEFAULTINCR;
206 reply_callback = NULL;
210 family = AF_INET; /* force AF_INET if no INET6 support */
214 cp = getenv("NETRC");
215 if (cp != NULL && strlcpy(netrc, cp, sizeof(netrc)) >= sizeof(netrc))
216 errx(1, "$NETRC `%s': %s", cp, strerror(ENAMETOOLONG));
218 marg_sl = ftp_sl_init();
219 if ((tmpdir = getenv("TMPDIR")) == NULL)
222 /* Set default operation mode based on FTPMODE environment variable */
223 if ((cp = getenv("FTPMODE")) != NULL) {
224 if (strcasecmp(cp, "passive") == 0) {
227 } else if (strcasecmp(cp, "active") == 0) {
230 } else if (strcasecmp(cp, "gate") == 0) {
232 } else if (strcasecmp(cp, "auto") == 0) {
236 warnx("Unknown $FTPMODE `%s'; using defaults", cp);
239 if (strcmp(getprogname(), "pftp") == 0) {
242 } else if (strcmp(getprogname(), "gate-ftp") == 0)
245 gateserver = getenv("FTPSERVER");
246 if (gateserver == NULL || *gateserver == '\0')
247 gateserver = GATE_SERVER;
249 if (*gateserver == '\0') {
251 "Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp");
257 if (cp == NULL || strcmp(cp, "dumb") == 0)
261 fromatty = isatty(fileno(stdin));
263 if (isatty(fileno(ttyout))) {
264 verbose = 1; /* verbose if to a tty */
266 #ifndef NO_EDITCOMPLETE
267 if (fromatty) /* editing mode on if tty is usable */
271 if (foregroundproc())
272 progress = 1; /* progress bar on if fg */
277 while ((ch = getopt(argc, argv, "46AadefginN:o:pP:q:r:Rs:tT:u:vV")) != -1) {
287 warnx("INET6 support is not available; ignoring -6");
306 #ifndef NO_EDITCOMPLETE
328 if (strlcpy(netrc, optarg, sizeof(netrc))
330 errx(1, "%s: %s", optarg,
331 strerror(ENAMETOOLONG));
336 if (strcmp(outfile, "-") == 0)
350 quit_time = strtol(optarg, &ep, 10);
351 if (quit_time < 1 || *ep != '\0')
352 errx(1, "Bad quit value: %s", optarg);
356 retry_connect = strtol(optarg, &ep, 10);
357 if (retry_connect < 1 || *ep != '\0')
358 errx(1, "Bad retry value: %s", optarg);
362 restartautofetch = 1;
376 char *targv[6], *oac;
377 char cmdbuf[MAX_C_NAME];
379 /* look for `dir,max[,incr]' */
381 (void)strlcpy(cmdbuf, "-T", sizeof(cmdbuf));
382 targv[targc++] = cmdbuf;
383 oac = ftp_strdup(optarg);
385 while ((cp = strsep(&oac, ",")) != NULL) {
387 warnx("Bad throttle value `%s'",
396 if (parserate(targc, targv, 1) == -1)
406 upload_path = ftp_strdup(optarg);
412 progress = verbose = 1;
416 progress = verbose = 0;
423 /* set line buffering on ttyout */
424 setvbuf(ttyout, NULL, _IOLBF, 0);
428 cpend = 0; /* no pending replies */
429 proxy = 0; /* proxy not active */
430 crflag = 1; /* strip c.r. on ascii gets */
431 sendport = -1; /* not using ports */
433 if (src_addr != NULL) {
434 struct addrinfo hints;
437 memset(&hints, 0, sizeof(hints));
438 hints.ai_family = family;
439 hints.ai_socktype = SOCK_STREAM;
440 hints.ai_flags = AI_PASSIVE;
441 error = getaddrinfo(src_addr, NULL, &hints, &bindai);
443 errx(1, "Can't lookup `%s': %s", src_addr,
444 (error == EAI_SYSTEM) ? strerror(errno)
445 : gai_strerror(error));
450 * Cache the user name and home directory.
454 anonuser = "anonymous";
456 if (! EMPTYSTRING(cp))
457 localhome = ftp_strdup(cp);
463 pw = getpwuid(getuid());
465 if (localhome == NULL && !EMPTYSTRING(pw->pw_dir))
466 localhome = ftp_strdup(pw->pw_dir);
467 localname = ftp_strdup(pw->pw_name);
468 anonuser = localname;
470 if (netrc[0] == '\0' && localhome != NULL) {
471 if (strlcpy(netrc, localhome, sizeof(netrc)) >= sizeof(netrc) ||
472 strlcat(netrc, "/.netrc", sizeof(netrc)) >= sizeof(netrc)) {
473 warnx("%s/.netrc: %s", localhome,
474 strerror(ENAMETOOLONG));
478 if (localhome == NULL)
479 localhome = ftp_strdup("/");
482 * Every anonymous FTP server I've encountered will accept the
483 * string "username@", and will append the hostname itself. We
484 * do this by default since many servers are picky about not
485 * having a FQDN in the anonymous password.
486 * - thorpej@NetBSD.org
488 len = strlen(anonuser) + 2;
489 anonpass = ftp_malloc(len);
490 (void)strlcpy(anonpass, anonuser, len);
491 (void)strlcat(anonpass, "@", len);
494 * set all the defaults for options defined in
495 * struct option optiontab[] declared in cmdtab.c
497 setupoption("anonpass", getenv("FTPANONPASS"), anonpass);
498 setupoption("ftp_proxy", getenv(FTP_PROXY), "");
499 setupoption("http_proxy", getenv(HTTP_PROXY), "");
500 setupoption("no_proxy", getenv(NO_PROXY), "");
501 setupoption("pager", getenv("PAGER"), DEFAULTPAGER);
502 setupoption("prompt", getenv("FTPPROMPT"), DEFAULTPROMPT);
503 setupoption("rprompt", getenv("FTPRPROMPT"), DEFAULTRPROMPT);
509 (void)xsignal(SIGINFO, psummary);
511 (void)xsignal(SIGQUIT, psummary);
512 (void)xsignal(SIGUSR1, crankrate);
513 (void)xsignal(SIGUSR2, crankrate);
514 (void)xsignal(SIGWINCH, setttywidth);
516 auto_rcvbuf = ((sysctlbyname("net.inet.tcp.recvbuf_auto",
517 &auto_rcvbuf, &(size_t []){[0] = sizeof(int)}[0], NULL, 0) == 0) &&
519 auto_sndbuf = ((sysctlbyname("net.inet.tcp.sendbuf_auto",
520 &auto_sndbuf, &(size_t []){[0] = sizeof(int)}[0], NULL, 0) == 0) &&
525 rval = auto_put(argc, argv, upload_path);
528 (void)xsignal(SIGINT, SIG_DFL);
532 } else if (strchr(argv[0], ':') != NULL
533 && ! isipv6addr(argv[0])) {
534 rval = auto_fetch(argc, argv);
535 if (rval >= 0) /* -1 == connected and cd-ed */
536 goto sigint_or_rval_exit;
538 char *xargv[4], *uuser, *host;
539 char cmdbuf[MAXPATHLEN];
541 if ((rval = sigsetjmp(toplevel, 1)))
542 goto sigint_or_rval_exit;
543 (void)xsignal(SIGINT, intr);
544 (void)xsignal(SIGPIPE, lostpeer);
547 cp = strchr(host, '@');
553 (void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
561 oautologin = autologin;
566 setpeer(argc+1, xargv);
567 autologin = oautologin;
568 if (connected == 1 && uuser != NULL)
569 (void)ftp_login(host, uuser, NULL);
575 "Retrying in %d seconds...\n",
577 sleep(retry_connect);
579 } while (!connected);
580 retry_connect = 0; /* connected, stop hiding msgs */
586 #ifndef NO_EDITCOMPLETE
588 #endif /* !NO_EDITCOMPLETE */
590 (void)sigsetjmp(toplevel, 1);
591 (void)xsignal(SIGINT, intr);
592 (void)xsignal(SIGPIPE, lostpeer);
603 static char **promptopt;
604 static char buf[MAXPATHLEN];
606 if (promptopt == NULL) {
609 o = getoption("prompt");
611 errx(1, "prompt: no such option `prompt'");
612 promptopt = &(o->value);
614 formatbuf(buf, sizeof(buf), *promptopt ? *promptopt : DEFAULTPROMPT);
619 * Generate an rprompt
624 static char **rpromptopt;
625 static char buf[MAXPATHLEN];
627 if (rpromptopt == NULL) {
630 o = getoption("rprompt");
632 errx(1, "rprompt: no such option `rprompt'");
633 rpromptopt = &(o->value);
635 formatbuf(buf, sizeof(buf), *rpromptopt ? *rpromptopt : DEFAULTRPROMPT);
647 #ifndef NO_EDITCOMPLETE
652 char cmdbuf[MAX_C_NAME];
655 #ifndef NO_EDITCOMPLETE
657 #endif /* !NO_EDITCOMPLETE */
659 fputs(prompt(), ttyout);
662 fprintf(ttyout, "%s ", p);
664 (void)fflush(ttyout);
665 len = get_line(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 (void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf));
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
834 static char bangstr[2] = { '!', '\0' };
835 static char dollarstr[2] = { '$', '\0' };
837 char *sb = stringbase;
839 char *tmp = argbase; /* will return this if token found */
841 if (*sb == '!' || *sb == '$') { /* recognize ! as a token for shell */
842 switch (slrflag) { /* and $ as token for macro invoke */
845 INC_CHKCURSOR(stringbase);
846 return ((*sb == '!') ? bangstr : dollarstr);
889 goto OUT; /* end of token */
893 goto S2; /* slurp next character */
897 goto S3; /* slurp quoted string */
900 *ap = *sb; /* add character to token */
942 argbase = ap; /* update storage pointer */
943 stringbase = sb; /* update scan pointer */
962 * Help/usage command.
963 * Call each command handler with argc == 0 and argv[0] == name.
966 help(int argc, char *argv[])
969 char *nargv[1], *cmd;
974 isusage = (strcmp(cmd, "usage") == 0);
975 if (argc == 0 || (isusage && argc == 1)) {
976 UPRINTF("usage: %s [command [...]]\n", cmd);
984 "%sommands may be abbreviated. Commands are:\n\n",
985 proxy ? "Proxy c" : "C");
986 for (c = cmdtab; (p = c->c_name) != NULL; c++)
987 if (!proxy || c->c_proxy)
988 ftp_sl_add(buf, ftp_strdup(p));
994 #define HELPINDENT ((int) sizeof("disconnect"))
998 char cmdbuf[MAX_C_NAME];
1002 if (c == (struct cmd *)-1)
1003 fprintf(ttyout, "?Ambiguous %s command `%s'\n",
1006 fprintf(ttyout, "?Invalid %s command `%s'\n",
1010 (void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf));
1012 (*c->c_handler)(0, nargv);
1014 fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
1015 c->c_name, c->c_help);
1021 getoption(const char *name)
1028 for (c = optiontab; (p = c->name) != NULL; c++) {
1029 if (strcasecmp(p, name) == 0)
1036 getoptionvalue(const char *name)
1041 errx(1, "getoptionvalue: invoked with NULL name");
1042 c = getoption(name);
1045 errx(1, "getoptionvalue: invoked with unknown option `%s'", name);
1050 setupoption(const char *name, const char *value, const char *defaultvalue)
1052 set_option(name, value ? value : defaultvalue, 0);
1058 const char *progname = getprogname();
1060 (void)fprintf(stderr,
1061 "usage: %s [-46AadefginpRtVv] [-N netrc] [-o outfile] [-P port] [-q quittime]\n"
1062 " [-r retry] [-s srcaddr] [-T dir,max[,inc]]\n"
1063 " [[user@]host [port]] [host:path[/]] [file:///file]\n"
1064 " [ftp://[user[:pass]@]host[:port]/path[/]]\n"
1065 " [http://[user[:pass]@]host[:port]/path] [...]\n"
1066 " %s -u URL file [...]\n", progname, progname);