1 /* $NetBSD: main.c,v 1.117 2009/07/13 19:05:41 roy Exp $ */
4 * Copyright (c) 1996-2009 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\
93 The Regents of the University of California. All rights reserved.\
94 Copyright 1996-2008 The NetBSD Foundation, Inc. All rights reserved");
99 static char sccsid[] = "@(#)main.c 8.6 (Berkeley) 10/9/94";
101 __RCSID("$NetBSD: main.c,v 1.117 2009/07/13 19:05:41 roy Exp $");
103 #endif /* not lint */
106 * FTP User Program -- Command Interface.
108 #include <sys/types.h>
109 #include <sys/socket.h>
124 #define GLOBAL /* force GLOBAL decls in ftp_var.h to be declared */
127 #define FTP_PROXY "ftp_proxy" /* env var with FTP proxy location */
128 #define HTTP_PROXY "http_proxy" /* env var with HTTP proxy location */
129 #define NO_PROXY "no_proxy" /* env var with list of non-proxied
130 * hosts, comma or space separated */
132 static void setupoption(const char *, const char *, const char *);
133 int main(int, char *[]);
136 main(int volatile argc, char **volatile argv)
140 char *cp, *ep, *anonpass, *upload_path, *src_addr;
141 const char *anonuser;
142 int dumbterm, s, isupload;
147 setlocale(LC_ALL, "");
148 setprogname(argv[0]);
155 cp = getenv("FTPSERVERPORT");
159 gateport = "ftpgate";
171 restartautofetch = 0;
172 #ifndef NO_EDITCOMPLETE
180 rate_get_incr = DEFAULTINCR;
182 rate_put_incr = DEFAULTINCR;
195 reply_callback = NULL;
199 family = AF_INET; /* force AF_INET if no INET6 support */
203 cp = getenv("NETRC");
204 if (cp != NULL && strlcpy(netrc, cp, sizeof(netrc)) >= sizeof(netrc))
205 errx(1, "$NETRC `%s': %s", cp, strerror(ENAMETOOLONG));
208 * Get the default socket buffer sizes if we don't already have them.
209 * It doesn't matter which socket we do this to, because on the first
210 * call no socket buffer sizes will have been modified, so we are
211 * guaranteed to get the system defaults.
213 s = socket(AF_INET, SOCK_STREAM, 0);
215 err(1, "Can't create socket to determine default socket sizes");
216 slen = sizeof(rcvbuf_size);
217 if (getsockopt(s, SOL_SOCKET, SO_RCVBUF,
218 (void *)&rcvbuf_size, &slen) == -1)
219 err(1, "Unable to get default rcvbuf size");
220 slen = sizeof(sndbuf_size);
221 if (getsockopt(s, SOL_SOCKET, SO_SNDBUF,
222 (void *)&sndbuf_size, &slen) == -1)
223 err(1, "Unable to get default sndbuf size");
225 /* sanity check returned buffer sizes */
226 if (rcvbuf_size <= 0)
227 rcvbuf_size = 8 * 1024;
228 if (sndbuf_size <= 0)
229 sndbuf_size = 8 * 1024;
231 if (sndbuf_size > 8 * 1024 * 1024)
232 sndbuf_size = 8 * 1024 * 1024;
233 if (rcvbuf_size > 8 * 1024 * 1024)
234 rcvbuf_size = 8 * 1024 * 1024;
236 marg_sl = ftp_sl_init();
237 if ((tmpdir = getenv("TMPDIR")) == NULL)
240 /* Set default operation mode based on FTPMODE environment variable */
241 if ((cp = getenv("FTPMODE")) != NULL) {
242 if (strcasecmp(cp, "passive") == 0) {
245 } else if (strcasecmp(cp, "active") == 0) {
248 } else if (strcasecmp(cp, "gate") == 0) {
250 } else if (strcasecmp(cp, "auto") == 0) {
254 warnx("Unknown $FTPMODE `%s'; using defaults", cp);
257 if (strcmp(getprogname(), "pftp") == 0) {
260 } else if (strcmp(getprogname(), "gate-ftp") == 0)
263 gateserver = getenv("FTPSERVER");
264 if (gateserver == NULL || *gateserver == '\0')
265 gateserver = GATE_SERVER;
267 if (*gateserver == '\0') {
269 "Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp");
275 if (cp == NULL || strcmp(cp, "dumb") == 0)
279 fromatty = isatty(fileno(stdin));
281 if (isatty(fileno(ttyout))) {
282 verbose = 1; /* verbose if to a tty */
284 #ifndef NO_EDITCOMPLETE
285 if (fromatty) /* editing mode on if tty is usable */
289 if (foregroundproc())
290 progress = 1; /* progress bar on if fg */
295 while ((ch = getopt(argc, argv, "46AadefginN:o:pP:q:r:Rs:tT:u:vV")) != -1) {
305 warnx("INET6 support is not available; ignoring -6");
324 #ifndef NO_EDITCOMPLETE
346 if (strlcpy(netrc, optarg, sizeof(netrc))
348 errx(1, "%s: %s", optarg,
349 strerror(ENAMETOOLONG));
354 if (strcmp(outfile, "-") == 0)
368 quit_time = strtol(optarg, &ep, 10);
369 if (quit_time < 1 || *ep != '\0')
370 errx(1, "Bad quit value: %s", optarg);
374 retry_connect = strtol(optarg, &ep, 10);
375 if (retry_connect < 1 || *ep != '\0')
376 errx(1, "Bad retry value: %s", optarg);
380 restartautofetch = 1;
394 char *targv[6], *oac;
395 char cmdbuf[MAX_C_NAME];
397 /* look for `dir,max[,incr]' */
399 (void)strlcpy(cmdbuf, "-T", sizeof(cmdbuf));
400 targv[targc++] = cmdbuf;
401 oac = ftp_strdup(optarg);
403 while ((cp = strsep(&oac, ",")) != NULL) {
405 warnx("Bad throttle value `%s'",
414 if (parserate(targc, targv, 1) == -1)
424 upload_path = ftp_strdup(optarg);
430 progress = verbose = 1;
434 progress = verbose = 0;
441 /* set line buffering on ttyout */
442 setvbuf(ttyout, NULL, _IOLBF, 0);
446 cpend = 0; /* no pending replies */
447 proxy = 0; /* proxy not active */
448 crflag = 1; /* strip c.r. on ascii gets */
449 sendport = -1; /* not using ports */
451 if (src_addr != NULL) {
452 struct addrinfo hints;
455 memset(&hints, 0, sizeof(hints));
456 hints.ai_family = family;
457 hints.ai_socktype = SOCK_STREAM;
458 hints.ai_flags = AI_PASSIVE;
459 error = getaddrinfo(src_addr, NULL, &hints, &bindai);
461 errx(1, "Can't lookup `%s': %s", src_addr,
462 (error == EAI_SYSTEM) ? strerror(errno)
463 : gai_strerror(error));
468 * Cache the user name and home directory.
472 anonuser = "anonymous";
474 if (! EMPTYSTRING(cp))
475 localhome = ftp_strdup(cp);
481 pw = getpwuid(getuid());
483 if (localhome == NULL && !EMPTYSTRING(pw->pw_dir))
484 localhome = ftp_strdup(pw->pw_dir);
485 localname = ftp_strdup(pw->pw_name);
486 anonuser = localname;
488 if (netrc[0] == '\0' && localhome != NULL) {
489 if (strlcpy(netrc, localhome, sizeof(netrc)) >= sizeof(netrc) ||
490 strlcat(netrc, "/.netrc", sizeof(netrc)) >= sizeof(netrc)) {
491 warnx("%s/.netrc: %s", localhome,
492 strerror(ENAMETOOLONG));
496 if (localhome == NULL)
497 localhome = ftp_strdup("/");
500 * Every anonymous FTP server I've encountered will accept the
501 * string "username@", and will append the hostname itself. We
502 * do this by default since many servers are picky about not
503 * having a FQDN in the anonymous password.
504 * - thorpej@NetBSD.org
506 len = strlen(anonuser) + 2;
507 anonpass = ftp_malloc(len);
508 (void)strlcpy(anonpass, anonuser, len);
509 (void)strlcat(anonpass, "@", len);
512 * set all the defaults for options defined in
513 * struct option optiontab[] declared in cmdtab.c
515 setupoption("anonpass", getenv("FTPANONPASS"), anonpass);
516 setupoption("ftp_proxy", getenv(FTP_PROXY), "");
517 setupoption("http_proxy", getenv(HTTP_PROXY), "");
518 setupoption("no_proxy", getenv(NO_PROXY), "");
519 setupoption("pager", getenv("PAGER"), DEFAULTPAGER);
520 setupoption("prompt", getenv("FTPPROMPT"), DEFAULTPROMPT);
521 setupoption("rprompt", getenv("FTPRPROMPT"), DEFAULTRPROMPT);
527 (void)xsignal(SIGINFO, psummary);
529 (void)xsignal(SIGQUIT, psummary);
530 (void)xsignal(SIGUSR1, crankrate);
531 (void)xsignal(SIGUSR2, crankrate);
532 (void)xsignal(SIGWINCH, setttywidth);
536 rval = auto_put(argc, argv, upload_path);
539 (void)xsignal(SIGINT, SIG_DFL);
543 } else if (strchr(argv[0], ':') != NULL
544 && ! isipv6addr(argv[0])) {
545 rval = auto_fetch(argc, argv);
546 if (rval >= 0) /* -1 == connected and cd-ed */
547 goto sigint_or_rval_exit;
549 char *xargv[4], *uuser, *host;
550 char cmdbuf[MAXPATHLEN];
552 if ((rval = sigsetjmp(toplevel, 1)))
553 goto sigint_or_rval_exit;
554 (void)xsignal(SIGINT, intr);
555 (void)xsignal(SIGPIPE, lostpeer);
558 cp = strchr(host, '@');
564 (void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
572 oautologin = autologin;
577 setpeer(argc+1, xargv);
578 autologin = oautologin;
579 if (connected == 1 && uuser != NULL)
580 (void)ftp_login(host, uuser, NULL);
586 "Retrying in %d seconds...\n",
588 sleep(retry_connect);
590 } while (!connected);
591 retry_connect = 0; /* connected, stop hiding msgs */
597 #ifndef NO_EDITCOMPLETE
599 #endif /* !NO_EDITCOMPLETE */
601 (void)sigsetjmp(toplevel, 1);
602 (void)xsignal(SIGINT, intr);
603 (void)xsignal(SIGPIPE, lostpeer);
614 static char **promptopt;
615 static char buf[MAXPATHLEN];
617 if (promptopt == NULL) {
620 o = getoption("prompt");
622 errx(1, "prompt: no such option `prompt'");
623 promptopt = &(o->value);
625 formatbuf(buf, sizeof(buf), *promptopt ? *promptopt : DEFAULTPROMPT);
630 * Generate an rprompt
635 static char **rpromptopt;
636 static char buf[MAXPATHLEN];
638 if (rpromptopt == NULL) {
641 o = getoption("rprompt");
643 errx(1, "rprompt: no such option `rprompt'");
644 rpromptopt = &(o->value);
646 formatbuf(buf, sizeof(buf), *rpromptopt ? *rpromptopt : DEFAULTRPROMPT);
658 #ifndef NO_EDITCOMPLETE
663 char cmdbuf[MAX_C_NAME];
666 #ifndef NO_EDITCOMPLETE
668 #endif /* !NO_EDITCOMPLETE */
670 fputs(prompt(), ttyout);
673 fprintf(ttyout, "%s ", p);
675 (void)fflush(ttyout);
676 len = get_line(stdin, line, sizeof(line), NULL);
684 case -3: /* too long; try again */
685 fputs("Sorry, input line is too long.\n",
688 case 0: /* empty; try again */
690 default: /* all ok */
693 #ifndef NO_EDITCOMPLETE
699 buf = el_gets(el, &ch);
701 if (buf == NULL || num == 0) {
706 if (num >= sizeof(line)) {
707 fputs("Sorry, input line is too long.\n",
711 memcpy(line, buf, num);
712 if (line[--num] == '\n') {
717 history(hist, &ev, H_ENTER, buf);
719 #endif /* !NO_EDITCOMPLETE */
724 c = getcmd(margv[0]);
725 if (c == (struct cmd *)-1) {
726 fputs("?Ambiguous command.\n", ttyout);
730 #if !defined(NO_EDITCOMPLETE)
732 * attempt to el_parse() unknown commands.
733 * any command containing a ':' would be parsed
734 * as "[prog:]cmd ...", and will result in a
735 * false positive if prog != "ftp", so treat
736 * such commands as invalid.
738 if (strchr(margv[0], ':') != NULL ||
740 el_parse(el, margc, (const char **)margv) != 0)
741 #endif /* !NO_EDITCOMPLETE */
742 fputs("?Invalid command.\n", ttyout);
745 if (c->c_conn && !connected) {
746 fputs("Not connected.\n", ttyout);
750 (void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf));
752 (*c->c_handler)(margc, margv);
753 if (bell && c->c_bell)
754 (void)putc('\007', ttyout);
755 if (c->c_handler != help)
758 (void)xsignal(SIGINT, intr);
759 (void)xsignal(SIGPIPE, lostpeer);
763 getcmd(const char *name)
766 struct cmd *c, *found;
767 int nmatches, longest;
775 for (c = cmdtab; (p = c->c_name) != NULL; c++) {
776 for (q = name; *q == *p++; q++)
777 if (*q == 0) /* exact match? */
779 if (!*q) { /* the name was a prefix */
780 if (q - name > longest) {
784 } else if (q - name == longest)
789 return ((struct cmd *)-1);
794 * Slice a string up into argc/argv.
804 stringbase = line; /* scan from first of buffer */
805 argbase = argbuf; /* store from first of buffer */
807 marg_sl->sl_cur = 0; /* reset to start of marg_sl */
808 for (margc = 0; ; margc++) {
809 argp = slurpstring();
810 ftp_sl_add(marg_sl, argp);
814 #ifndef NO_EDITCOMPLETE
815 if (cursor_pos == line) {
818 } else if (cursor_pos != NULL) {
820 cursor_argo = strlen(margv[margc-1]);
822 #endif /* !NO_EDITCOMPLETE */
825 #ifdef NO_EDITCOMPLETE
826 #define INC_CHKCURSOR(x) (x)++
827 #else /* !NO_EDITCOMPLETE */
828 #define INC_CHKCURSOR(x) { (x)++ ; \
829 if (x == cursor_pos) { \
830 cursor_argc = margc; \
831 cursor_argo = ap-argbase; \
835 #endif /* !NO_EDITCOMPLETE */
838 * Parse string into argbuf;
839 * implemented with FSM to
840 * handle quoting and strings
845 static char bangstr[2] = { '!', '\0' };
846 static char dollarstr[2] = { '$', '\0' };
848 char *sb = stringbase;
850 char *tmp = argbase; /* will return this if token found */
852 if (*sb == '!' || *sb == '$') { /* recognize ! as a token for shell */
853 switch (slrflag) { /* and $ as token for macro invoke */
856 INC_CHKCURSOR(stringbase);
857 return ((*sb == '!') ? bangstr : dollarstr);
900 goto OUT; /* end of token */
904 goto S2; /* slurp next character */
908 goto S3; /* slurp quoted string */
911 *ap = *sb; /* add character to token */
953 argbase = ap; /* update storage pointer */
954 stringbase = sb; /* update scan pointer */
973 * Help/usage command.
974 * Call each command handler with argc == 0 and argv[0] == name.
977 help(int argc, char *argv[])
980 char *nargv[1], *cmd;
985 isusage = (strcmp(cmd, "usage") == 0);
986 if (argc == 0 || (isusage && argc == 1)) {
987 UPRINTF("usage: %s [command [...]]\n", cmd);
995 "%sommands may be abbreviated. Commands are:\n\n",
996 proxy ? "Proxy c" : "C");
997 for (c = cmdtab; (p = c->c_name) != NULL; c++)
998 if (!proxy || c->c_proxy)
999 ftp_sl_add(buf, ftp_strdup(p));
1005 #define HELPINDENT ((int) sizeof("disconnect"))
1007 while (--argc > 0) {
1009 char cmdbuf[MAX_C_NAME];
1013 if (c == (struct cmd *)-1)
1014 fprintf(ttyout, "?Ambiguous %s command `%s'\n",
1017 fprintf(ttyout, "?Invalid %s command `%s'\n",
1021 (void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf));
1023 (*c->c_handler)(0, nargv);
1025 fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
1026 c->c_name, c->c_help);
1032 getoption(const char *name)
1039 for (c = optiontab; (p = c->name) != NULL; c++) {
1040 if (strcasecmp(p, name) == 0)
1047 getoptionvalue(const char *name)
1052 errx(1, "getoptionvalue: invoked with NULL name");
1053 c = getoption(name);
1056 errx(1, "getoptionvalue: invoked with unknown option `%s'", name);
1061 setupoption(const char *name, const char *value, const char *defaultvalue)
1063 set_option(name, value ? value : defaultvalue, 0);
1069 const char *progname = getprogname();
1071 (void)fprintf(stderr,
1072 "usage: %s [-46AadefginpRtVv] [-N netrc] [-o outfile] [-P port] [-q quittime]\n"
1073 " [-r retry] [-s srcaddr] [-T dir,max[,inc]]\n"
1074 " [[user@]host [port]] [host:path[/]] [file:///file]\n"
1075 " [ftp://[user[:pass]@]host[:port]/path[/]]\n"
1076 " [http://[user[:pass]@]host[:port]/path] [...]\n"
1077 " %s -u URL file [...]\n", progname, progname);