1 /* $NetBSD: main.c,v 1.94 2005/05/13 05:03:49 lukem Exp $ */
4 * Copyright (c) 1996-2004 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>
100 * FTP User Program -- Command Interface.
102 #include <sys/types.h>
103 #include <sys/socket.h>
117 #define GLOBAL /* force GLOBAL decls in ftp_var.h to be declared */
120 #define FTP_PROXY "ftp_proxy" /* env var with FTP proxy location */
121 #define HTTP_PROXY "http_proxy" /* env var with HTTP proxy location */
122 #define NO_PROXY "no_proxy" /* env var with list of non-proxied
123 * hosts, comma or space separated */
125 static void setupoption(char *, char *, char *);
126 int main(int, char *[]);
129 main(int argc
, char *argv
[])
133 char *cp
, *ep
, *anonuser
, *anonpass
, *upload_path
;
134 int dumbterm
, s
, len
, isupload
;
137 setlocale(LC_ALL
, "");
138 setprogname(argv
[0]);
145 cp
= getenv("FTPSERVERPORT");
149 gateport
= "ftpgate";
161 restartautofetch
= 0;
162 #ifndef NO_EDITCOMPLETE
170 rate_get_incr
= DEFAULTINCR
;
172 rate_put_incr
= DEFAULTINCR
;
181 reply_callback
= NULL
;
185 cp
= getenv("NETRC");
186 if (cp
!= NULL
&& strlcpy(netrc
, cp
, sizeof(netrc
)) >= sizeof(netrc
))
187 errx(1, "$NETRC `%s': %s", cp
, strerror(ENAMETOOLONG
));
190 * Get the default socket buffer sizes if we don't already have them.
191 * It doesn't matter which socket we do this to, because on the first
192 * call no socket buffer sizes will have been modified, so we are
193 * guaranteed to get the system defaults.
195 s
= socket(AF_INET
, SOCK_STREAM
, 0);
197 err(1, "can't create socket");
198 slen
= sizeof(rcvbuf_size
);
199 if (getsockopt(s
, SOL_SOCKET
, SO_RCVBUF
,
200 (void *)&rcvbuf_size
, &slen
) == -1)
201 err(1, "unable to get default rcvbuf size");
202 slen
= sizeof(sndbuf_size
);
203 if (getsockopt(s
, SOL_SOCKET
, SO_SNDBUF
,
204 (void *)&sndbuf_size
, &slen
) == -1)
205 err(1, "unable to get default sndbuf size");
207 /* sanity check returned buffer sizes */
208 if (rcvbuf_size
<= 0)
209 rcvbuf_size
= 8 * 1024;
210 if (sndbuf_size
<= 0)
211 sndbuf_size
= 8 * 1024;
213 if (sndbuf_size
> 8 * 1024 * 1024)
214 sndbuf_size
= 8 * 1024 * 1024;
215 if (rcvbuf_size
> 8 * 1024 * 1024)
216 rcvbuf_size
= 8 * 1024 * 1024;
218 marg_sl
= xsl_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:RtT: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;
372 char *targv
[6], *oac
;
374 /* look for `dir,max[,incr]' */
376 targv
[targc
++] = "-T";
377 oac
= xstrdup(optarg
);
379 while ((cp
= strsep(&oac
, ",")) != NULL
) {
381 warnx("bad throttle value: %s", optarg
);
389 if (parserate(targc
, targv
, 1) == -1)
399 upload_path
= xstrdup(optarg
);
405 progress
= verbose
= 1;
409 progress
= verbose
= 0;
416 /* set line buffering on ttyout */
417 setvbuf(ttyout
, NULL
, _IOLBF
, 0);
421 cpend
= 0; /* no pending replies */
422 proxy
= 0; /* proxy not active */
423 crflag
= 1; /* strip c.r. on ascii gets */
424 sendport
= -1; /* not using ports */
427 * Cache the user name and home directory.
431 anonuser
= "anonymous";
433 if (! EMPTYSTRING(cp
))
434 localhome
= xstrdup(cp
);
440 pw
= getpwuid(getuid());
442 if (localhome
== NULL
&& !EMPTYSTRING(pw
->pw_dir
))
443 localhome
= xstrdup(pw
->pw_dir
);
444 localname
= xstrdup(pw
->pw_name
);
445 anonuser
= localname
;
447 if (netrc
[0] == '\0' && localhome
!= NULL
) {
448 if (strlcpy(netrc
, localhome
, sizeof(netrc
)) >= sizeof(netrc
) ||
449 strlcat(netrc
, "/.netrc", sizeof(netrc
)) >= sizeof(netrc
)) {
450 warnx("%s/.netrc: %s", localhome
,
451 strerror(ENAMETOOLONG
));
455 if (localhome
== NULL
)
456 localhome
= xstrdup("/");
459 * Every anonymous FTP server I've encountered will accept the
460 * string "username@", and will append the hostname itself. We
461 * do this by default since many servers are picky about not
462 * having a FQDN in the anonymous password.
463 * - thorpej@NetBSD.org
465 len
= strlen(anonuser
) + 2;
466 anonpass
= xmalloc(len
);
467 (void)strlcpy(anonpass
, anonuser
, len
);
468 (void)strlcat(anonpass
, "@", len
);
471 * set all the defaults for options defined in
472 * struct option optiontab[] declared in cmdtab.c
474 setupoption("anonpass", getenv("FTPANONPASS"), anonpass
);
475 setupoption("ftp_proxy", getenv(FTP_PROXY
), "");
476 setupoption("http_proxy", getenv(HTTP_PROXY
), "");
477 setupoption("no_proxy", getenv(NO_PROXY
), "");
478 setupoption("pager", getenv("PAGER"), DEFAULTPAGER
);
479 setupoption("prompt", getenv("FTPPROMPT"), DEFAULTPROMPT
);
480 setupoption("rprompt", getenv("FTPRPROMPT"), DEFAULTRPROMPT
);
486 (void)xsignal(SIGINFO
, psummary
);
488 (void)xsignal(SIGQUIT
, psummary
);
489 (void)xsignal(SIGUSR1
, crankrate
);
490 (void)xsignal(SIGUSR2
, crankrate
);
491 (void)xsignal(SIGWINCH
, setttywidth
);
493 #ifdef __GNUC__ /* to shut up gcc warnings */
500 rval
= auto_put(argc
, argv
, upload_path
);
503 (void)xsignal(SIGINT
, SIG_DFL
);
507 } else if (strchr(argv
[0], ':') != NULL
508 && ! isipv6addr(argv
[0])) {
509 rval
= auto_fetch(argc
, argv
);
510 if (rval
>= 0) /* -1 == connected and cd-ed */
511 goto sigint_or_rval_exit
;
513 char *xargv
[4], *user
, *host
;
515 if ((rval
= sigsetjmp(toplevel
, 1)))
516 goto sigint_or_rval_exit
;
517 (void)xsignal(SIGINT
, intr
);
518 (void)xsignal(SIGPIPE
, lostpeer
);
521 cp
= strchr(host
, '@');
527 /* XXX discards const */
528 xargv
[0] = (char *)getprogname();
535 oautologin
= autologin
;
540 setpeer(argc
+1, xargv
);
541 autologin
= oautologin
;
542 if (connected
== 1 && user
!= NULL
)
543 (void)ftp_login(host
, user
, NULL
);
549 "Retrying in %d seconds...\n",
551 sleep(retry_connect
);
553 } while (!connected
);
554 retry_connect
= 0; /* connected, stop hiding msgs */
560 #ifndef NO_EDITCOMPLETE
562 #endif /* !NO_EDITCOMPLETE */
564 (void)sigsetjmp(toplevel
, 1);
565 (void)xsignal(SIGINT
, intr
);
566 (void)xsignal(SIGPIPE
, lostpeer
);
577 static char **prompt
;
578 static char buf
[MAXPATHLEN
];
580 if (prompt
== NULL
) {
583 o
= getoption("prompt");
585 errx(1, "no such option `prompt'");
586 prompt
= &(o
->value
);
588 formatbuf(buf
, sizeof(buf
), *prompt
? *prompt
: DEFAULTPROMPT
);
593 * Generate an rprompt
598 static char **rprompt
;
599 static char buf
[MAXPATHLEN
];
601 if (rprompt
== NULL
) {
604 o
= getoption("rprompt");
606 errx(1, "no such option `rprompt'");
607 rprompt
= &(o
->value
);
609 formatbuf(buf
, sizeof(buf
), *rprompt
? *rprompt
: DEFAULTRPROMPT
);
624 #ifndef NO_EDITCOMPLETE
626 #endif /* !NO_EDITCOMPLETE */
628 fputs(prompt(), ttyout
);
631 fprintf(ttyout
, "%s ", p
);
632 (void)fflush(ttyout
);
634 if (fgets(line
, sizeof(line
), stdin
) == NULL
) {
642 if (line
[--num
] == '\n') {
646 } else if (num
== sizeof(line
) - 2) {
647 fputs("Sorry, input line is too long.\n",
649 while ((num
= getchar()) != '\n' && num
!= EOF
)
652 } /* else it was a line without a newline */
653 #ifndef NO_EDITCOMPLETE
659 buf
= el_gets(el
, &num
);
660 if (buf
== NULL
|| num
== 0) {
665 if (num
>= sizeof(line
)) {
666 fputs("Sorry, input line is too long.\n",
670 memcpy(line
, buf
, num
);
671 if (line
[--num
] == '\n') {
676 history(hist
, &ev
, H_ENTER
, buf
);
678 #endif /* !NO_EDITCOMPLETE */
683 c
= getcmd(margv
[0]);
684 if (c
== (struct cmd
*)-1) {
685 fputs("?Ambiguous command.\n", ttyout
);
689 #if !defined(NO_EDITCOMPLETE)
691 * attempt to el_parse() unknown commands.
692 * any command containing a ':' would be parsed
693 * as "[prog:]cmd ...", and will result in a
694 * false positive if prog != "ftp", so treat
695 * such commands as invalid.
697 if (strchr(margv
[0], ':') != NULL
||
698 el_parse(el
, margc
, (const char **)margv
) != 0)
699 #endif /* !NO_EDITCOMPLETE */
700 fputs("?Invalid command.\n", ttyout
);
703 if (c
->c_conn
&& !connected
) {
704 fputs("Not connected.\n", ttyout
);
708 margv
[0] = c
->c_name
;
709 (*c
->c_handler
)(margc
, margv
);
710 if (bell
&& c
->c_bell
)
711 (void)putc('\007', ttyout
);
712 if (c
->c_handler
!= help
)
715 (void)xsignal(SIGINT
, intr
);
716 (void)xsignal(SIGPIPE
, lostpeer
);
720 getcmd(const char *name
)
723 struct cmd
*c
, *found
;
724 int nmatches
, longest
;
732 for (c
= cmdtab
; (p
= c
->c_name
) != NULL
; c
++) {
733 for (q
= name
; *q
== *p
++; q
++)
734 if (*q
== 0) /* exact match? */
736 if (!*q
) { /* the name was a prefix */
737 if (q
- name
> longest
) {
741 } else if (q
- name
== longest
)
746 return ((struct cmd
*)-1);
751 * Slice a string up into argc/argv.
761 stringbase
= line
; /* scan from first of buffer */
762 argbase
= argbuf
; /* store from first of buffer */
764 marg_sl
->sl_cur
= 0; /* reset to start of marg_sl */
765 for (margc
= 0; ; margc
++) {
766 argp
= slurpstring();
767 xsl_add(marg_sl
, argp
);
771 #ifndef NO_EDITCOMPLETE
772 if (cursor_pos
== line
) {
775 } else if (cursor_pos
!= NULL
) {
777 cursor_argo
= strlen(margv
[margc
-1]);
779 #endif /* !NO_EDITCOMPLETE */
782 #ifdef NO_EDITCOMPLETE
783 #define INC_CHKCURSOR(x) (x)++
784 #else /* !NO_EDITCOMPLETE */
785 #define INC_CHKCURSOR(x) { (x)++ ; \
786 if (x == cursor_pos) { \
787 cursor_argc = margc; \
788 cursor_argo = ap-argbase; \
792 #endif /* !NO_EDITCOMPLETE */
795 * Parse string into argbuf;
796 * implemented with FSM to
797 * handle quoting and strings
803 char *sb
= stringbase
;
805 char *tmp
= argbase
; /* will return this if token found */
807 if (*sb
== '!' || *sb
== '$') { /* recognize ! as a token for shell */
808 switch (slrflag
) { /* and $ as token for macro invoke */
811 INC_CHKCURSOR(stringbase
);
812 return ((*sb
== '!') ? "!" : "$");
855 goto OUT
; /* end of token */
859 goto S2
; /* slurp next character */
863 goto S3
; /* slurp quoted string */
866 *ap
= *sb
; /* add character to token */
908 argbase
= ap
; /* update storage pointer */
909 stringbase
= sb
; /* update scan pointer */
928 * Help/usage command.
929 * Call each command handler with argc == 0 and argv[0] == name.
932 help(int argc
, char *argv
[])
935 char *nargv
[1], *p
, *cmd
;
939 isusage
= (strcmp(cmd
, "usage") == 0);
940 if (argc
== 0 || (isusage
&& argc
== 1)) {
941 fprintf(ttyout
, "usage: %s [command [...]]\n", cmd
);
949 "%sommands may be abbreviated. Commands are:\n\n",
950 proxy
? "Proxy c" : "C");
951 for (c
= cmdtab
; (p
= c
->c_name
) != NULL
; c
++)
952 if (!proxy
|| c
->c_proxy
)
959 #define HELPINDENT ((int) sizeof("disconnect"))
966 if (c
== (struct cmd
*)-1)
967 fprintf(ttyout
, "?Ambiguous %s command `%s'\n",
970 fprintf(ttyout
, "?Invalid %s command `%s'\n",
974 nargv
[0] = c
->c_name
;
975 (*c
->c_handler
)(0, nargv
);
977 fprintf(ttyout
, "%-*s\t%s\n", HELPINDENT
,
978 c
->c_name
, c
->c_help
);
984 getoption(const char *name
)
991 for (c
= optiontab
; (p
= c
->name
) != NULL
; c
++) {
992 if (strcasecmp(p
, name
) == 0)
999 getoptionvalue(const char *name
)
1004 errx(1, "getoptionvalue() invoked with NULL name");
1005 c
= getoption(name
);
1008 errx(1, "getoptionvalue() invoked with unknown option `%s'", name
);
1013 setupoption(char *name
, char *value
, char *defaultvalue
)
1018 nargv
[0] = "setupoption()";
1020 nargv
[2] = (value
? value
: defaultvalue
);
1023 setoption(3, nargv
);
1030 const char *progname
= getprogname();
1032 (void)fprintf(stderr
,
1033 "usage: %s [-46AadefginpRtvV] [-N netrc] [-o outfile] [-P port] [-q quittime]\n"
1034 " [-r retry] [-T dir,max[,inc][[user@]host [port]]] [host:path[/]]\n"
1035 " [file:///file] [ftp://[user[:pass]@]host[:port]/path[/]]\n"
1036 " [http://[user[:pass]@]host[:port]/path] [...]\n"
1037 " %s -u URL file [...]\n", progname
, progname
);