1 /* $NetBSD: main.c,v 1.101 2006/01/31 20:05:36 christos Exp $ */
4 * Copyright (c) 1996-2005 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>
99 __COPYRIGHT("@(#) Copyright (c) 1985, 1989, 1993, 1994\n\
100 The Regents of the University of California. All rights reserved.\n");
101 #endif /* not lint */
105 static char sccsid
[] = "@(#)main.c 8.6 (Berkeley) 10/9/94";
107 __RCSID("$NetBSD: main.c,v 1.101 2006/01/31 20:05:36 christos Exp $");
109 #endif /* not lint */
112 * FTP User Program -- Command Interface.
114 #include <sys/types.h>
115 #include <sys/socket.h>
129 #define GLOBAL /* force GLOBAL decls in ftp_var.h to be declared */
132 #define FTP_PROXY "ftp_proxy" /* env var with FTP proxy location */
133 #define HTTP_PROXY "http_proxy" /* env var with HTTP proxy location */
134 #define NO_PROXY "no_proxy" /* env var with list of non-proxied
135 * hosts, comma or space separated */
137 static void setupoption(char *, char *, char *);
138 int main(int, char *[]);
141 main(int argc
, char *argv
[])
145 char *cp
, *ep
, *anonuser
, *anonpass
, *upload_path
;
146 int dumbterm
, s
, isupload
;
150 setlocale(LC_ALL
, "");
151 setprogname(argv
[0]);
158 cp
= getenv("FTPSERVERPORT");
162 gateport
= "ftpgate";
174 restartautofetch
= 0;
175 #ifndef NO_EDITCOMPLETE
183 rate_get_incr
= DEFAULTINCR
;
185 rate_put_incr
= DEFAULTINCR
;
194 reply_callback
= NULL
;
198 cp
= getenv("NETRC");
199 if (cp
!= NULL
&& strlcpy(netrc
, cp
, sizeof(netrc
)) >= sizeof(netrc
))
200 errx(1, "$NETRC `%s': %s", cp
, strerror(ENAMETOOLONG
));
203 * Get the default socket buffer sizes if we don't already have them.
204 * It doesn't matter which socket we do this to, because on the first
205 * call no socket buffer sizes will have been modified, so we are
206 * guaranteed to get the system defaults.
208 s
= socket(AF_INET
, SOCK_STREAM
, 0);
210 err(1, "can't create socket");
211 slen
= sizeof(rcvbuf_size
);
212 if (getsockopt(s
, SOL_SOCKET
, SO_RCVBUF
,
213 (void *)&rcvbuf_size
, &slen
) == -1)
214 err(1, "unable to get default rcvbuf size");
215 slen
= sizeof(sndbuf_size
);
216 if (getsockopt(s
, SOL_SOCKET
, SO_SNDBUF
,
217 (void *)&sndbuf_size
, &slen
) == -1)
218 err(1, "unable to get default sndbuf size");
220 /* sanity check returned buffer sizes */
221 if (rcvbuf_size
<= 0)
222 rcvbuf_size
= 8 * 1024;
223 if (sndbuf_size
<= 0)
224 sndbuf_size
= 8 * 1024;
226 if (sndbuf_size
> 8 * 1024 * 1024)
227 sndbuf_size
= 8 * 1024 * 1024;
228 if (rcvbuf_size
> 8 * 1024 * 1024)
229 rcvbuf_size
= 8 * 1024 * 1024;
231 marg_sl
= ftp_sl_init();
232 if ((tmpdir
= getenv("TMPDIR")) == NULL
)
235 /* Set default operation mode based on FTPMODE environment variable */
236 if ((cp
= getenv("FTPMODE")) != NULL
) {
237 if (strcasecmp(cp
, "passive") == 0) {
240 } else if (strcasecmp(cp
, "active") == 0) {
243 } else if (strcasecmp(cp
, "gate") == 0) {
245 } else if (strcasecmp(cp
, "auto") == 0) {
249 warnx("unknown $FTPMODE '%s'; using defaults", cp
);
252 if (strcmp(getprogname(), "pftp") == 0) {
255 } else if (strcmp(getprogname(), "gate-ftp") == 0)
258 gateserver
= getenv("FTPSERVER");
259 if (gateserver
== NULL
|| *gateserver
== '\0')
260 gateserver
= GATE_SERVER
;
262 if (*gateserver
== '\0') {
264 "Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp");
270 if (cp
== NULL
|| strcmp(cp
, "dumb") == 0)
274 fromatty
= isatty(fileno(stdin
));
276 if (isatty(fileno(ttyout
))) {
277 verbose
= 1; /* verbose if to a tty */
279 #ifndef NO_EDITCOMPLETE
280 if (fromatty
) /* editing mode on if tty is usable */
284 if (foregroundproc())
285 progress
= 1; /* progress bar on if fg */
290 while ((ch
= getopt(argc
, argv
, "46AadefginN:o:pP:q:r:RtT:u:vV")) != -1) {
300 warnx("INET6 support is not available; ignoring -6");
319 #ifndef NO_EDITCOMPLETE
341 if (strlcpy(netrc
, optarg
, sizeof(netrc
))
343 errx(1, "%s: %s", optarg
,
344 strerror(ENAMETOOLONG
));
349 if (strcmp(outfile
, "-") == 0)
363 quit_time
= strtol(optarg
, &ep
, 10);
364 if (quit_time
< 1 || *ep
!= '\0')
365 errx(1, "bad quit value: %s", optarg
);
369 retry_connect
= strtol(optarg
, &ep
, 10);
370 if (retry_connect
< 1 || *ep
!= '\0')
371 errx(1, "bad retry value: %s", optarg
);
375 restartautofetch
= 1;
385 char *targv
[6], *oac
;
387 /* look for `dir,max[,incr]' */
389 targv
[targc
++] = "-T";
390 oac
= ftp_strdup(optarg
);
392 while ((cp
= strsep(&oac
, ",")) != NULL
) {
394 warnx("bad throttle value: %s", optarg
);
402 if (parserate(targc
, targv
, 1) == -1)
412 upload_path
= ftp_strdup(optarg
);
418 progress
= verbose
= 1;
422 progress
= verbose
= 0;
429 /* set line buffering on ttyout */
430 setvbuf(ttyout
, NULL
, _IOLBF
, 0);
434 cpend
= 0; /* no pending replies */
435 proxy
= 0; /* proxy not active */
436 crflag
= 1; /* strip c.r. on ascii gets */
437 sendport
= -1; /* not using ports */
440 * Cache the user name and home directory.
444 anonuser
= "anonymous";
446 if (! EMPTYSTRING(cp
))
447 localhome
= ftp_strdup(cp
);
453 pw
= getpwuid(getuid());
455 if (localhome
== NULL
&& !EMPTYSTRING(pw
->pw_dir
))
456 localhome
= ftp_strdup(pw
->pw_dir
);
457 localname
= ftp_strdup(pw
->pw_name
);
458 anonuser
= localname
;
460 if (netrc
[0] == '\0' && localhome
!= NULL
) {
461 if (strlcpy(netrc
, localhome
, sizeof(netrc
)) >= sizeof(netrc
) ||
462 strlcat(netrc
, "/.netrc", sizeof(netrc
)) >= sizeof(netrc
)) {
463 warnx("%s/.netrc: %s", localhome
,
464 strerror(ENAMETOOLONG
));
468 if (localhome
== NULL
)
469 localhome
= ftp_strdup("/");
472 * Every anonymous FTP server I've encountered will accept the
473 * string "username@", and will append the hostname itself. We
474 * do this by default since many servers are picky about not
475 * having a FQDN in the anonymous password.
476 * - thorpej@NetBSD.org
478 len
= strlen(anonuser
) + 2;
479 anonpass
= ftp_malloc(len
);
480 (void)strlcpy(anonpass
, anonuser
, len
);
481 (void)strlcat(anonpass
, "@", len
);
484 * set all the defaults for options defined in
485 * struct option optiontab[] declared in cmdtab.c
487 setupoption("anonpass", getenv("FTPANONPASS"), anonpass
);
488 setupoption("ftp_proxy", getenv(FTP_PROXY
), "");
489 setupoption("http_proxy", getenv(HTTP_PROXY
), "");
490 setupoption("no_proxy", getenv(NO_PROXY
), "");
491 setupoption("pager", getenv("PAGER"), DEFAULTPAGER
);
492 setupoption("prompt", getenv("FTPPROMPT"), DEFAULTPROMPT
);
493 setupoption("rprompt", getenv("FTPRPROMPT"), DEFAULTRPROMPT
);
499 (void)xsignal(SIGINFO
, psummary
);
501 (void)xsignal(SIGQUIT
, psummary
);
502 (void)xsignal(SIGUSR1
, crankrate
);
503 (void)xsignal(SIGUSR2
, crankrate
);
504 (void)xsignal(SIGWINCH
, setttywidth
);
506 #ifdef __GNUC__ /* to shut up gcc warnings */
513 rval
= auto_put(argc
, argv
, upload_path
);
516 (void)xsignal(SIGINT
, SIG_DFL
);
520 } else if (strchr(argv
[0], ':') != NULL
521 && ! isipv6addr(argv
[0])) {
522 rval
= auto_fetch(argc
, argv
);
523 if (rval
>= 0) /* -1 == connected and cd-ed */
524 goto sigint_or_rval_exit
;
526 char *xargv
[4], *user
, *host
;
528 if ((rval
= sigsetjmp(toplevel
, 1)))
529 goto sigint_or_rval_exit
;
530 (void)xsignal(SIGINT
, intr
);
531 (void)xsignal(SIGPIPE
, lostpeer
);
534 cp
= strchr(host
, '@');
540 /* XXX discards const */
541 xargv
[0] = (char *)getprogname();
548 oautologin
= autologin
;
553 setpeer(argc
+1, xargv
);
554 autologin
= oautologin
;
555 if (connected
== 1 && user
!= NULL
)
556 (void)ftp_login(host
, user
, NULL
);
562 "Retrying in %d seconds...\n",
564 sleep(retry_connect
);
566 } while (!connected
);
567 retry_connect
= 0; /* connected, stop hiding msgs */
573 #ifndef NO_EDITCOMPLETE
575 #endif /* !NO_EDITCOMPLETE */
577 (void)sigsetjmp(toplevel
, 1);
578 (void)xsignal(SIGINT
, intr
);
579 (void)xsignal(SIGPIPE
, lostpeer
);
590 static char **prompt
;
591 static char buf
[MAXPATHLEN
];
593 if (prompt
== NULL
) {
596 o
= getoption("prompt");
598 errx(1, "no such option `prompt'");
599 prompt
= &(o
->value
);
601 formatbuf(buf
, sizeof(buf
), *prompt
? *prompt
: DEFAULTPROMPT
);
606 * Generate an rprompt
611 static char **rprompt
;
612 static char buf
[MAXPATHLEN
];
614 if (rprompt
== NULL
) {
617 o
= getoption("rprompt");
619 errx(1, "no such option `rprompt'");
620 rprompt
= &(o
->value
);
622 formatbuf(buf
, sizeof(buf
), *rprompt
? *rprompt
: DEFAULTRPROMPT
);
634 #ifndef NO_EDITCOMPLETE
640 #ifndef NO_EDITCOMPLETE
642 #endif /* !NO_EDITCOMPLETE */
644 fputs(prompt(), ttyout
);
647 fprintf(ttyout
, "%s ", p
);
648 (void)fflush(ttyout
);
650 num
= getline(stdin
, line
, sizeof(line
), NULL
);
658 case -3: /* too long; try again */
659 fputs("Sorry, input line is too long.\n",
662 case 0: /* empty; try again */
664 default: /* all ok */
667 #ifndef NO_EDITCOMPLETE
673 buf
= el_gets(el
, &ch
);
675 if (buf
== NULL
|| num
== 0) {
680 if (num
>= sizeof(line
)) {
681 fputs("Sorry, input line is too long.\n",
685 memcpy(line
, buf
, num
);
686 if (line
[--num
] == '\n') {
691 history(hist
, &ev
, H_ENTER
, buf
);
693 #endif /* !NO_EDITCOMPLETE */
698 c
= getcmd(margv
[0]);
699 if (c
== (struct cmd
*)-1) {
700 fputs("?Ambiguous command.\n", ttyout
);
704 #if !defined(NO_EDITCOMPLETE)
706 * attempt to el_parse() unknown commands.
707 * any command containing a ':' would be parsed
708 * as "[prog:]cmd ...", and will result in a
709 * false positive if prog != "ftp", so treat
710 * such commands as invalid.
712 if (strchr(margv
[0], ':') != NULL
||
713 el_parse(el
, margc
, (const char **)margv
) != 0)
714 #endif /* !NO_EDITCOMPLETE */
715 fputs("?Invalid command.\n", ttyout
);
718 if (c
->c_conn
&& !connected
) {
719 fputs("Not connected.\n", ttyout
);
723 margv
[0] = c
->c_name
;
724 (*c
->c_handler
)(margc
, margv
);
725 if (bell
&& c
->c_bell
)
726 (void)putc('\007', ttyout
);
727 if (c
->c_handler
!= help
)
730 (void)xsignal(SIGINT
, intr
);
731 (void)xsignal(SIGPIPE
, lostpeer
);
735 getcmd(const char *name
)
738 struct cmd
*c
, *found
;
739 int nmatches
, longest
;
747 for (c
= cmdtab
; (p
= c
->c_name
) != NULL
; c
++) {
748 for (q
= name
; *q
== *p
++; q
++)
749 if (*q
== 0) /* exact match? */
751 if (!*q
) { /* the name was a prefix */
752 if (q
- name
> longest
) {
756 } else if (q
- name
== longest
)
761 return ((struct cmd
*)-1);
766 * Slice a string up into argc/argv.
776 stringbase
= line
; /* scan from first of buffer */
777 argbase
= argbuf
; /* store from first of buffer */
779 marg_sl
->sl_cur
= 0; /* reset to start of marg_sl */
780 for (margc
= 0; ; margc
++) {
781 argp
= slurpstring();
782 ftp_sl_add(marg_sl
, argp
);
786 #ifndef NO_EDITCOMPLETE
787 if (cursor_pos
== line
) {
790 } else if (cursor_pos
!= NULL
) {
792 cursor_argo
= strlen(margv
[margc
-1]);
794 #endif /* !NO_EDITCOMPLETE */
797 #ifdef NO_EDITCOMPLETE
798 #define INC_CHKCURSOR(x) (x)++
799 #else /* !NO_EDITCOMPLETE */
800 #define INC_CHKCURSOR(x) { (x)++ ; \
801 if (x == cursor_pos) { \
802 cursor_argc = margc; \
803 cursor_argo = ap-argbase; \
807 #endif /* !NO_EDITCOMPLETE */
810 * Parse string into argbuf;
811 * implemented with FSM to
812 * handle quoting and strings
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
== '!') ? "!" : "$");
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], *p
, *cmd
;
954 isusage
= (strcmp(cmd
, "usage") == 0);
955 if (argc
== 0 || (isusage
&& argc
== 1)) {
956 UPRINTF("usage: %s [command [...]]\n", cmd
);
964 "%sommands may be abbreviated. Commands are:\n\n",
965 proxy
? "Proxy c" : "C");
966 for (c
= cmdtab
; (p
= c
->c_name
) != NULL
; c
++)
967 if (!proxy
|| c
->c_proxy
)
974 #define HELPINDENT ((int) sizeof("disconnect"))
981 if (c
== (struct cmd
*)-1)
982 fprintf(ttyout
, "?Ambiguous %s command `%s'\n",
985 fprintf(ttyout
, "?Invalid %s command `%s'\n",
989 nargv
[0] = c
->c_name
;
990 (*c
->c_handler
)(0, nargv
);
992 fprintf(ttyout
, "%-*s\t%s\n", HELPINDENT
,
993 c
->c_name
, c
->c_help
);
999 getoption(const char *name
)
1006 for (c
= optiontab
; (p
= c
->name
) != NULL
; c
++) {
1007 if (strcasecmp(p
, name
) == 0)
1014 getoptionvalue(const char *name
)
1019 errx(1, "getoptionvalue() invoked with NULL name");
1020 c
= getoption(name
);
1023 errx(1, "getoptionvalue() invoked with unknown option `%s'", name
);
1028 setupoption(char *name
, char *value
, char *defaultvalue
)
1033 nargv
[0] = "setupoption()";
1035 nargv
[2] = (value
? value
: defaultvalue
);
1038 setoption(3, nargv
);
1045 const char *progname
= getprogname();
1047 (void)fprintf(stderr
,
1048 "usage: %s [-46AadefginpRtvV] [-N netrc] [-o outfile] [-P port] [-q quittime]\n"
1049 " [-r retry] [-T dir,max[,inc][[user@]host [port]]] [host:path[/]]\n"
1050 " [file:///file] [ftp://[user[:pass]@]host[:port]/path[/]]\n"
1051 " [http://[user[:pass]@]host[:port]/path] [...]\n"
1052 " %s -u URL file [...]\n", progname
, progname
);