1 /* $NetBSD: main.c,v 1.120 2011/12/10 05:53:58 lukem 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.120 2011/12/10 05:53:58 lukem 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 __dead static void usage(void);
133 static void setupoption(const char *, const char *, const 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, isupload;
146 setlocale(LC_ALL, "");
147 setprogname(argv[0]);
154 cp = getenv("FTPSERVERPORT");
158 gateport = "ftpgate";
170 restartautofetch = 0;
171 #ifndef NO_EDITCOMPLETE
179 rate_get_incr = DEFAULTINCR;
181 rate_put_incr = DEFAULTINCR;
194 reply_callback = NULL;
198 family = AF_INET; /* force AF_INET if no INET6 support */
202 cp = getenv("NETRC");
203 if (cp != NULL && strlcpy(netrc, cp, sizeof(netrc)) >= sizeof(netrc))
204 errx(1, "$NETRC `%s': %s", cp, strerror(ENAMETOOLONG));
206 marg_sl = ftp_sl_init();
207 if ((tmpdir = getenv("TMPDIR")) == NULL)
210 /* Set default operation mode based on FTPMODE environment variable */
211 if ((cp = getenv("FTPMODE")) != NULL) {
212 if (strcasecmp(cp, "passive") == 0) {
215 } else if (strcasecmp(cp, "active") == 0) {
218 } else if (strcasecmp(cp, "gate") == 0) {
220 } else if (strcasecmp(cp, "auto") == 0) {
224 warnx("Unknown $FTPMODE `%s'; using defaults", cp);
227 if (strcmp(getprogname(), "pftp") == 0) {
230 } else if (strcmp(getprogname(), "gate-ftp") == 0)
233 gateserver = getenv("FTPSERVER");
234 if (gateserver == NULL || *gateserver == '\0')
235 gateserver = GATE_SERVER;
237 if (*gateserver == '\0') {
239 "Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp");
245 if (cp == NULL || strcmp(cp, "dumb") == 0)
249 fromatty = isatty(fileno(stdin));
251 if (isatty(fileno(ttyout))) {
252 verbose = 1; /* verbose if to a tty */
254 #ifndef NO_EDITCOMPLETE
255 if (fromatty) /* editing mode on if tty is usable */
259 if (foregroundproc())
260 progress = 1; /* progress bar on if fg */
265 while ((ch = getopt(argc, argv, "46AadefginN:o:pP:q:r:Rs:tT:u:vV")) != -1) {
275 warnx("INET6 support is not available; ignoring -6");
294 #ifndef NO_EDITCOMPLETE
316 if (strlcpy(netrc, optarg, sizeof(netrc))
318 errx(1, "%s: %s", optarg,
319 strerror(ENAMETOOLONG));
324 if (strcmp(outfile, "-") == 0)
338 quit_time = strtol(optarg, &ep, 10);
339 if (quit_time < 1 || *ep != '\0')
340 errx(1, "Bad quit value: %s", optarg);
344 retry_connect = strtol(optarg, &ep, 10);
345 if (retry_connect < 1 || *ep != '\0')
346 errx(1, "Bad retry value: %s", optarg);
350 restartautofetch = 1;
364 char *targv[6], *oac;
365 char cmdbuf[MAX_C_NAME];
367 /* look for `dir,max[,incr]' */
369 (void)strlcpy(cmdbuf, "-T", sizeof(cmdbuf));
370 targv[targc++] = cmdbuf;
371 oac = ftp_strdup(optarg);
373 while ((cp = strsep(&oac, ",")) != NULL) {
375 warnx("Bad throttle value `%s'",
384 if (parserate(targc, targv, 1) == -1)
394 upload_path = ftp_strdup(optarg);
400 progress = verbose = 1;
404 progress = verbose = 0;
411 /* set line buffering on ttyout */
412 setvbuf(ttyout, NULL, _IOLBF, 0);
416 cpend = 0; /* no pending replies */
417 proxy = 0; /* proxy not active */
418 crflag = 1; /* strip c.r. on ascii gets */
419 sendport = -1; /* not using ports */
421 if (src_addr != NULL) {
422 struct addrinfo hints;
425 memset(&hints, 0, sizeof(hints));
426 hints.ai_family = family;
427 hints.ai_socktype = SOCK_STREAM;
428 hints.ai_flags = AI_PASSIVE;
429 error = getaddrinfo(src_addr, NULL, &hints, &bindai);
431 errx(1, "Can't lookup `%s': %s", src_addr,
432 (error == EAI_SYSTEM) ? strerror(errno)
433 : gai_strerror(error));
438 * Cache the user name and home directory.
442 anonuser = "anonymous";
444 if (! EMPTYSTRING(cp))
445 localhome = ftp_strdup(cp);
451 pw = getpwuid(getuid());
453 if (localhome == NULL && !EMPTYSTRING(pw->pw_dir))
454 localhome = ftp_strdup(pw->pw_dir);
455 localname = ftp_strdup(pw->pw_name);
456 anonuser = localname;
458 if (netrc[0] == '\0' && localhome != NULL) {
459 if (strlcpy(netrc, localhome, sizeof(netrc)) >= sizeof(netrc) ||
460 strlcat(netrc, "/.netrc", sizeof(netrc)) >= sizeof(netrc)) {
461 warnx("%s/.netrc: %s", localhome,
462 strerror(ENAMETOOLONG));
466 if (localhome == NULL)
467 localhome = ftp_strdup("/");
470 * Every anonymous FTP server I've encountered will accept the
471 * string "username@", and will append the hostname itself. We
472 * do this by default since many servers are picky about not
473 * having a FQDN in the anonymous password.
474 * - thorpej@NetBSD.org
476 len = strlen(anonuser) + 2;
477 anonpass = ftp_malloc(len);
478 (void)strlcpy(anonpass, anonuser, len);
479 (void)strlcat(anonpass, "@", len);
482 * set all the defaults for options defined in
483 * struct option optiontab[] declared in cmdtab.c
485 setupoption("anonpass", getenv("FTPANONPASS"), anonpass);
486 setupoption("ftp_proxy", getenv(FTP_PROXY), "");
487 setupoption("http_proxy", getenv(HTTP_PROXY), "");
488 setupoption("no_proxy", getenv(NO_PROXY), "");
489 setupoption("pager", getenv("PAGER"), DEFAULTPAGER);
490 setupoption("prompt", getenv("FTPPROMPT"), DEFAULTPROMPT);
491 setupoption("rprompt", getenv("FTPRPROMPT"), DEFAULTRPROMPT);
497 (void)xsignal(SIGINFO, psummary);
499 (void)xsignal(SIGQUIT, psummary);
500 (void)xsignal(SIGUSR1, crankrate);
501 (void)xsignal(SIGUSR2, crankrate);
502 (void)xsignal(SIGWINCH, setttywidth);
506 rval = auto_put(argc, argv, upload_path);
509 (void)xsignal(SIGINT, SIG_DFL);
513 } else if (strchr(argv[0], ':') != NULL
514 && ! isipv6addr(argv[0])) {
515 rval = auto_fetch(argc, argv);
516 if (rval >= 0) /* -1 == connected and cd-ed */
517 goto sigint_or_rval_exit;
519 char *xargv[4], *uuser, *host;
520 char cmdbuf[MAXPATHLEN];
522 if ((rval = sigsetjmp(toplevel, 1)))
523 goto sigint_or_rval_exit;
524 (void)xsignal(SIGINT, intr);
525 (void)xsignal(SIGPIPE, lostpeer);
528 cp = strchr(host, '@');
534 (void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
542 oautologin = autologin;
547 setpeer(argc+1, xargv);
548 autologin = oautologin;
549 if (connected == 1 && uuser != NULL)
550 (void)ftp_login(host, uuser, NULL);
556 "Retrying in %d seconds...\n",
558 sleep(retry_connect);
560 } while (!connected);
561 retry_connect = 0; /* connected, stop hiding msgs */
567 #ifndef NO_EDITCOMPLETE
569 #endif /* !NO_EDITCOMPLETE */
571 (void)sigsetjmp(toplevel, 1);
572 (void)xsignal(SIGINT, intr);
573 (void)xsignal(SIGPIPE, lostpeer);
584 static char **promptopt;
585 static char buf[MAXPATHLEN];
587 if (promptopt == NULL) {
590 o = getoption("prompt");
592 errx(1, "prompt: no such option `prompt'");
593 promptopt = &(o->value);
595 formatbuf(buf, sizeof(buf), *promptopt ? *promptopt : DEFAULTPROMPT);
600 * Generate an rprompt
605 static char **rpromptopt;
606 static char buf[MAXPATHLEN];
608 if (rpromptopt == NULL) {
611 o = getoption("rprompt");
613 errx(1, "rprompt: no such option `rprompt'");
614 rpromptopt = &(o->value);
616 formatbuf(buf, sizeof(buf), *rpromptopt ? *rpromptopt : DEFAULTRPROMPT);
628 #ifndef NO_EDITCOMPLETE
633 char cmdbuf[MAX_C_NAME];
636 #ifndef NO_EDITCOMPLETE
638 #endif /* !NO_EDITCOMPLETE */
640 fputs(prompt(), ttyout);
643 fprintf(ttyout, "%s ", p);
645 (void)fflush(ttyout);
646 len = get_line(stdin, line, sizeof(line), NULL);
654 case -3: /* too long; try again */
655 fputs("Sorry, input line is too long.\n",
658 case 0: /* empty; try again */
660 default: /* all ok */
663 #ifndef NO_EDITCOMPLETE
669 buf = el_gets(el, &ch);
671 if (buf == NULL || num == 0) {
676 if (num >= sizeof(line)) {
677 fputs("Sorry, input line is too long.\n",
681 memcpy(line, buf, num);
682 if (line[--num] == '\n') {
687 history(hist, &ev, H_ENTER, buf);
689 #endif /* !NO_EDITCOMPLETE */
694 c = getcmd(margv[0]);
695 if (c == (struct cmd *)-1) {
696 fputs("?Ambiguous command.\n", ttyout);
700 #if !defined(NO_EDITCOMPLETE)
702 * attempt to el_parse() unknown commands.
703 * any command containing a ':' would be parsed
704 * as "[prog:]cmd ...", and will result in a
705 * false positive if prog != "ftp", so treat
706 * such commands as invalid.
708 if (strchr(margv[0], ':') != NULL ||
710 el_parse(el, margc, (void *)margv) != 0)
711 #endif /* !NO_EDITCOMPLETE */
712 fputs("?Invalid command.\n", ttyout);
715 if (c->c_conn && !connected) {
716 fputs("Not connected.\n", ttyout);
720 (void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf));
722 (*c->c_handler)(margc, margv);
723 if (bell && c->c_bell)
724 (void)putc('\007', ttyout);
725 if (c->c_handler != help)
728 (void)xsignal(SIGINT, intr);
729 (void)xsignal(SIGPIPE, lostpeer);
733 getcmd(const char *name)
736 struct cmd *c, *found;
737 int nmatches, longest;
745 for (c = cmdtab; (p = c->c_name) != NULL; c++) {
746 for (q = name; *q == *p++; q++)
747 if (*q == 0) /* exact match? */
749 if (!*q) { /* the name was a prefix */
750 if (q - name > longest) {
754 } else if (q - name == longest)
759 return ((struct cmd *)-1);
764 * Slice a string up into argc/argv.
774 stringbase = line; /* scan from first of buffer */
775 argbase = argbuf; /* store from first of buffer */
777 marg_sl->sl_cur = 0; /* reset to start of marg_sl */
778 for (margc = 0; ; margc++) {
779 argp = slurpstring();
780 ftp_sl_add(marg_sl, argp);
784 #ifndef NO_EDITCOMPLETE
785 if (cursor_pos == line) {
788 } else if (cursor_pos != NULL) {
790 cursor_argo = strlen(margv[margc-1]);
792 #endif /* !NO_EDITCOMPLETE */
795 #ifdef NO_EDITCOMPLETE
796 #define INC_CHKCURSOR(x) (x)++
797 #else /* !NO_EDITCOMPLETE */
798 #define INC_CHKCURSOR(x) { (x)++ ; \
799 if (x == cursor_pos) { \
800 cursor_argc = margc; \
801 cursor_argo = ap-argbase; \
805 #endif /* !NO_EDITCOMPLETE */
808 * Parse string into argbuf;
809 * implemented with FSM to
810 * handle quoting and strings
815 static char bangstr[2] = { '!', '\0' };
816 static char dollarstr[2] = { '$', '\0' };
818 char *sb = stringbase;
820 char *tmp = argbase; /* will return this if token found */
822 if (*sb == '!' || *sb == '$') { /* recognize ! as a token for shell */
823 switch (slrflag) { /* and $ as token for macro invoke */
826 INC_CHKCURSOR(stringbase);
827 return ((*sb == '!') ? bangstr : dollarstr);
870 goto OUT; /* end of token */
874 goto S2; /* slurp next character */
878 goto S3; /* slurp quoted string */
881 *ap = *sb; /* add character to token */
923 argbase = ap; /* update storage pointer */
924 stringbase = sb; /* update scan pointer */
943 * Help/usage command.
944 * Call each command handler with argc == 0 and argv[0] == name.
947 help(int argc, char *argv[])
950 char *nargv[1], *cmd;
955 isusage = (strcmp(cmd, "usage") == 0);
956 if (argc == 0 || (isusage && argc == 1)) {
957 UPRINTF("usage: %s [command [...]]\n", cmd);
965 "%sommands may be abbreviated. Commands are:\n\n",
966 proxy ? "Proxy c" : "C");
967 for (c = cmdtab; (p = c->c_name) != NULL; c++)
968 if (!proxy || c->c_proxy)
969 ftp_sl_add(buf, ftp_strdup(p));
975 #define HELPINDENT ((int) sizeof("disconnect"))
979 char cmdbuf[MAX_C_NAME];
983 if (c == (struct cmd *)-1)
984 fprintf(ttyout, "?Ambiguous %s command `%s'\n",
987 fprintf(ttyout, "?Invalid %s command `%s'\n",
991 (void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf));
993 (*c->c_handler)(0, nargv);
995 fprintf(ttyout, "%-*s\t%s\n", HELPINDENT,
996 c->c_name, c->c_help);
1002 getoption(const char *name)
1009 for (c = optiontab; (p = c->name) != NULL; c++) {
1010 if (strcasecmp(p, name) == 0)
1017 getoptionvalue(const char *name)
1022 errx(1, "getoptionvalue: invoked with NULL name");
1023 c = getoption(name);
1026 errx(1, "getoptionvalue: invoked with unknown option `%s'", name);
1031 setupoption(const char *name, const char *value, const char *defaultvalue)
1033 set_option(name, value ? value : defaultvalue, 0);
1039 const char *progname = getprogname();
1041 (void)fprintf(stderr,
1042 "usage: %s [-46AadefginpRtVv] [-N netrc] [-o outfile] [-P port] [-q quittime]\n"
1043 " [-r retry] [-s srcaddr] [-T dir,max[,inc]]\n"
1044 " [[user@]host [port]] [host:path[/]] [file:///file]\n"
1045 " [ftp://[user[:pass]@]host[:port]/path[/]]\n"
1046 " [http://[user[:pass]@]host[:port]/path] [...]\n"
1047 " %s -u URL file [...]\n", progname, progname);