1 /* $NetBSD: main.c,v 1.123 2015/04/23 23:31:23 lukem Exp $ */
4 * Copyright (c) 1996-2015 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-2015 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.123 2015/04/23 23:31:23 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 HTTPS_PROXY "https_proxy" /* env var with HTTPS proxy location */
130 #define NO_PROXY "no_proxy" /* env var with list of non-proxied
131 * hosts, comma or space separated */
133 __dead
static void usage(void);
134 static void setupoption(const char *, const char *, const char *);
137 main(int volatile argc
, char **volatile argv
)
141 char *cp
, *ep
, *anonpass
, *upload_path
, *src_addr
;
142 const char *anonuser
;
143 int dumbterm
, isupload
;
147 setlocale(LC_ALL
, "");
148 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
;
198 reply_callback
= NULL
;
202 family
= AF_INET
; /* force AF_INET if no INET6 support */
206 cp
= getenv("NETRC");
207 if (cp
!= NULL
&& strlcpy(netrc
, cp
, sizeof(netrc
)) >= sizeof(netrc
))
208 errx(1, "$NETRC `%s': %s", cp
, strerror(ENAMETOOLONG
));
210 marg_sl
= ftp_sl_init();
211 if ((tmpdir
= getenv("TMPDIR")) == NULL
)
214 /* Set default operation mode based on FTPMODE environment variable */
215 if ((cp
= getenv("FTPMODE")) != NULL
) {
216 if (strcasecmp(cp
, "passive") == 0) {
219 } else if (strcasecmp(cp
, "active") == 0) {
222 } else if (strcasecmp(cp
, "gate") == 0) {
224 } else if (strcasecmp(cp
, "auto") == 0) {
228 warnx("Unknown $FTPMODE `%s'; using defaults", cp
);
231 if (strcmp(getprogname(), "pftp") == 0) {
234 } else if (strcmp(getprogname(), "gate-ftp") == 0)
237 gateserver
= getenv("FTPSERVER");
238 if (gateserver
== NULL
|| *gateserver
== '\0')
239 gateserver
= GATE_SERVER
;
241 if (*gateserver
== '\0') {
243 "Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp");
249 if (cp
== NULL
|| strcmp(cp
, "dumb") == 0)
253 fromatty
= isatty(fileno(stdin
));
255 if (isatty(fileno(ttyout
))) {
256 verbose
= 1; /* verbose if to a tty */
258 #ifndef NO_EDITCOMPLETE
259 if (fromatty
) /* editing mode on if tty is usable */
263 if (foregroundproc())
264 progress
= 1; /* progress bar on if fg */
269 while ((ch
= getopt(argc
, argv
, "46AadefginN:o:pP:q:r:Rs:tT:u:vVx:")) != -1) {
279 warnx("INET6 support is not available; ignoring -6");
298 #ifndef NO_EDITCOMPLETE
320 if (strlcpy(netrc
, optarg
, sizeof(netrc
))
322 errx(1, "%s: %s", optarg
,
323 strerror(ENAMETOOLONG
));
328 if (strcmp(outfile
, "-") == 0)
342 quit_time
= strtol(optarg
, &ep
, 10);
343 if (quit_time
< 1 || *ep
!= '\0')
344 errx(1, "Bad quit value: %s", optarg
);
348 retry_connect
= strtol(optarg
, &ep
, 10);
349 if (retry_connect
< 1 || *ep
!= '\0')
350 errx(1, "Bad retry value: %s", optarg
);
354 restartautofetch
= 1;
368 char *targv
[6], *oac
;
369 char cmdbuf
[MAX_C_NAME
];
371 /* look for `dir,max[,incr]' */
373 (void)strlcpy(cmdbuf
, "-T", sizeof(cmdbuf
));
374 targv
[targc
++] = cmdbuf
;
375 oac
= ftp_strdup(optarg
);
377 while ((cp
= strsep(&oac
, ",")) != NULL
) {
379 warnx("Bad throttle value `%s'",
388 if (parserate(targc
, targv
, 1) == -1)
398 upload_path
= ftp_strdup(optarg
);
404 progress
= verbose
= 1;
408 progress
= verbose
= 0;
412 sndbuf_size
= strsuftoi(optarg
);
414 errx(1, "Bad xferbuf value: %s", optarg
);
415 rcvbuf_size
= sndbuf_size
;
422 /* set line buffering on ttyout */
423 setvbuf(ttyout
, NULL
, _IOLBF
, 0);
427 cpend
= 0; /* no pending replies */
428 proxy
= 0; /* proxy not active */
429 crflag
= 1; /* strip c.r. on ascii gets */
430 sendport
= -1; /* not using ports */
432 if (src_addr
!= NULL
) {
433 struct addrinfo hints
;
436 memset(&hints
, 0, sizeof(hints
));
437 hints
.ai_family
= family
;
438 hints
.ai_socktype
= SOCK_STREAM
;
439 hints
.ai_flags
= AI_PASSIVE
;
440 error
= getaddrinfo(src_addr
, NULL
, &hints
, &bindai
);
442 errx(1, "Can't lookup `%s': %s", src_addr
,
443 (error
== EAI_SYSTEM
) ? strerror(errno
)
444 : gai_strerror(error
));
449 * Cache the user name and home directory.
453 anonuser
= "anonymous";
455 if (! EMPTYSTRING(cp
))
456 localhome
= ftp_strdup(cp
);
462 pw
= getpwuid(getuid());
464 if (localhome
== NULL
&& !EMPTYSTRING(pw
->pw_dir
))
465 localhome
= ftp_strdup(pw
->pw_dir
);
466 localname
= ftp_strdup(pw
->pw_name
);
467 anonuser
= localname
;
469 if (netrc
[0] == '\0' && localhome
!= NULL
) {
470 if (strlcpy(netrc
, localhome
, sizeof(netrc
)) >= sizeof(netrc
) ||
471 strlcat(netrc
, "/.netrc", sizeof(netrc
)) >= sizeof(netrc
)) {
472 warnx("%s/.netrc: %s", localhome
,
473 strerror(ENAMETOOLONG
));
477 if (localhome
== NULL
)
478 localhome
= ftp_strdup("/");
481 * Every anonymous FTP server I've encountered will accept the
482 * string "username@", and will append the hostname itself. We
483 * do this by default since many servers are picky about not
484 * having a FQDN in the anonymous password.
485 * - thorpej@NetBSD.org
487 len
= strlen(anonuser
) + 2;
488 anonpass
= ftp_malloc(len
);
489 (void)strlcpy(anonpass
, anonuser
, len
);
490 (void)strlcat(anonpass
, "@", len
);
493 * set all the defaults for options defined in
494 * struct option optiontab[] declared in cmdtab.c
496 setupoption("anonpass", getenv("FTPANONPASS"), anonpass
);
497 setupoption("ftp_proxy", getenv(FTP_PROXY
), "");
498 setupoption("http_proxy", getenv(HTTP_PROXY
), "");
499 setupoption("https_proxy", getenv(HTTPS_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
);
518 rval
= auto_put(argc
, argv
, upload_path
);
521 (void)xsignal(SIGINT
, SIG_DFL
);
525 } else if (strchr(argv
[0], ':') != NULL
526 && ! isipv6addr(argv
[0])) {
527 rval
= auto_fetch(argc
, argv
);
528 if (rval
>= 0) /* -1 == connected and cd-ed */
529 goto sigint_or_rval_exit
;
531 char *xargv
[4], *uuser
, *host
;
532 char cmdbuf
[MAXPATHLEN
];
534 if ((rval
= sigsetjmp(toplevel
, 1)))
535 goto sigint_or_rval_exit
;
536 (void)xsignal(SIGINT
, intr
);
537 (void)xsignal(SIGPIPE
, lostpeer
);
540 cp
= strchr(host
, '@');
546 (void)strlcpy(cmdbuf
, getprogname(), sizeof(cmdbuf
));
554 oautologin
= autologin
;
559 setpeer(argc
+1, xargv
);
560 autologin
= oautologin
;
561 if (connected
== 1 && uuser
!= NULL
)
562 (void)ftp_login(host
, uuser
, NULL
);
568 "Retrying in %d seconds...\n",
570 sleep(retry_connect
);
572 } while (!connected
);
573 retry_connect
= 0; /* connected, stop hiding msgs */
579 #ifndef NO_EDITCOMPLETE
581 #endif /* !NO_EDITCOMPLETE */
583 (void)sigsetjmp(toplevel
, 1);
584 (void)xsignal(SIGINT
, intr
);
585 (void)xsignal(SIGPIPE
, lostpeer
);
596 static char **promptopt
;
597 static char buf
[MAXPATHLEN
];
599 if (promptopt
== NULL
) {
602 o
= getoption("prompt");
604 errx(1, "prompt: no such option `prompt'");
605 promptopt
= &(o
->value
);
607 formatbuf(buf
, sizeof(buf
), *promptopt
? *promptopt
: DEFAULTPROMPT
);
612 * Generate an rprompt
617 static char **rpromptopt
;
618 static char buf
[MAXPATHLEN
];
620 if (rpromptopt
== NULL
) {
623 o
= getoption("rprompt");
625 errx(1, "rprompt: no such option `rprompt'");
626 rpromptopt
= &(o
->value
);
628 formatbuf(buf
, sizeof(buf
), *rpromptopt
? *rpromptopt
: DEFAULTRPROMPT
);
640 #ifndef NO_EDITCOMPLETE
645 char cmdbuf
[MAX_C_NAME
];
648 #ifndef NO_EDITCOMPLETE
650 #endif /* !NO_EDITCOMPLETE */
652 fputs(prompt(), ttyout
);
655 fprintf(ttyout
, "%s ", p
);
657 (void)fflush(ttyout
);
658 len
= get_line(stdin
, line
, sizeof(line
), NULL
);
666 case -3: /* too long; try again */
667 fputs("Sorry, input line is too long.\n",
670 case 0: /* empty; try again */
672 default: /* all ok */
675 #ifndef NO_EDITCOMPLETE
681 buf
= el_gets(el
, &ch
);
683 if (buf
== NULL
|| num
== 0) {
688 if (num
>= sizeof(line
)) {
689 fputs("Sorry, input line is too long.\n",
693 memcpy(line
, buf
, num
);
694 if (line
[--num
] == '\n') {
699 history(hist
, &ev
, H_ENTER
, buf
);
701 #endif /* !NO_EDITCOMPLETE */
706 c
= getcmd(margv
[0]);
707 if (c
== (struct cmd
*)-1) {
708 fputs("?Ambiguous command.\n", ttyout
);
712 #if !defined(NO_EDITCOMPLETE)
714 * attempt to el_parse() unknown commands.
715 * any command containing a ':' would be parsed
716 * as "[prog:]cmd ...", and will result in a
717 * false positive if prog != "ftp", so treat
718 * such commands as invalid.
720 if (strchr(margv
[0], ':') != NULL
||
722 el_parse(el
, margc
, (void *)margv
) != 0)
723 #endif /* !NO_EDITCOMPLETE */
724 fputs("?Invalid command.\n", ttyout
);
727 if (c
->c_conn
&& !connected
) {
728 fputs("Not connected.\n", ttyout
);
732 (void)strlcpy(cmdbuf
, c
->c_name
, sizeof(cmdbuf
));
734 (*c
->c_handler
)(margc
, margv
);
735 if (bell
&& c
->c_bell
)
736 (void)putc('\007', ttyout
);
737 if (c
->c_handler
!= help
)
740 (void)xsignal(SIGINT
, intr
);
741 (void)xsignal(SIGPIPE
, lostpeer
);
745 getcmd(const char *name
)
748 struct cmd
*c
, *found
;
749 int nmatches
, longest
;
757 for (c
= cmdtab
; (p
= c
->c_name
) != NULL
; c
++) {
758 for (q
= name
; *q
== *p
++; q
++)
759 if (*q
== 0) /* exact match? */
761 if (!*q
) { /* the name was a prefix */
762 if (q
- name
> longest
) {
766 } else if (q
- name
== longest
)
771 return ((struct cmd
*)-1);
776 * Slice a string up into argc/argv.
786 stringbase
= line
; /* scan from first of buffer */
787 argbase
= argbuf
; /* store from first of buffer */
789 marg_sl
->sl_cur
= 0; /* reset to start of marg_sl */
790 for (margc
= 0; ; margc
++) {
791 argp
= slurpstring();
792 ftp_sl_add(marg_sl
, argp
);
796 #ifndef NO_EDITCOMPLETE
797 if (cursor_pos
== line
) {
800 } else if (cursor_pos
!= NULL
) {
802 cursor_argo
= strlen(margv
[margc
-1]);
804 #endif /* !NO_EDITCOMPLETE */
807 #ifdef NO_EDITCOMPLETE
808 #define INC_CHKCURSOR(x) (x)++
809 #else /* !NO_EDITCOMPLETE */
810 #define INC_CHKCURSOR(x) { (x)++ ; \
811 if (x == cursor_pos) { \
812 cursor_argc = margc; \
813 cursor_argo = ap-argbase; \
817 #endif /* !NO_EDITCOMPLETE */
820 * Parse string into argbuf;
821 * implemented with FSM to
822 * handle quoting and strings
827 static char bangstr
[2] = { '!', '\0' };
828 static char dollarstr
[2] = { '$', '\0' };
830 char *sb
= stringbase
;
832 char *tmp
= argbase
; /* will return this if token found */
834 if (*sb
== '!' || *sb
== '$') { /* recognize ! as a token for shell */
835 switch (slrflag
) { /* and $ as token for macro invoke */
838 INC_CHKCURSOR(stringbase
);
839 return ((*sb
== '!') ? bangstr
: dollarstr
);
882 goto OUT
; /* end of token */
886 goto S2
; /* slurp next character */
890 goto S3
; /* slurp quoted string */
893 *ap
= *sb
; /* add character to token */
935 argbase
= ap
; /* update storage pointer */
936 stringbase
= sb
; /* update scan pointer */
955 * Help/usage command.
956 * Call each command handler with argc == 0 and argv[0] == name.
959 help(int argc
, char *argv
[])
962 char *nargv
[1], *cmd
;
967 isusage
= (strcmp(cmd
, "usage") == 0);
968 if (argc
== 0 || (isusage
&& argc
== 1)) {
969 UPRINTF("usage: %s [command [...]]\n", cmd
);
977 "%sommands may be abbreviated. Commands are:\n\n",
978 proxy
? "Proxy c" : "C");
979 for (c
= cmdtab
; (p
= c
->c_name
) != NULL
; c
++)
980 if (!proxy
|| c
->c_proxy
)
981 ftp_sl_add(buf
, ftp_strdup(p
));
987 #define HELPINDENT ((int) sizeof("disconnect"))
991 char cmdbuf
[MAX_C_NAME
];
995 if (c
== (struct cmd
*)-1)
996 fprintf(ttyout
, "?Ambiguous %s command `%s'\n",
999 fprintf(ttyout
, "?Invalid %s command `%s'\n",
1003 (void)strlcpy(cmdbuf
, c
->c_name
, sizeof(cmdbuf
));
1005 (*c
->c_handler
)(0, nargv
);
1007 fprintf(ttyout
, "%-*s\t%s\n", HELPINDENT
,
1008 c
->c_name
, c
->c_help
);
1014 getoption(const char *name
)
1021 for (c
= optiontab
; (p
= c
->name
) != NULL
; c
++) {
1022 if (strcasecmp(p
, name
) == 0)
1029 getoptionvalue(const char *name
)
1034 errx(1, "getoptionvalue: invoked with NULL name");
1035 c
= getoption(name
);
1038 errx(1, "getoptionvalue: invoked with unknown option `%s'", name
);
1043 setupoption(const char *name
, const char *value
, const char *defaultvalue
)
1045 set_option(name
, value
? value
: defaultvalue
, 0);
1051 const char *progname
= getprogname();
1053 (void)fprintf(stderr
,
1054 "usage: %s [-46AadefginpRtVv] [-N netrc] [-o outfile] [-P port] [-q quittime]\n"
1055 " [-r retry] [-s srcaddr] [-T dir,max[,inc]] [-x xferbufsize]\n"
1056 " [[user@]host [port]] [host:path[/]] [file:///file]\n"
1057 " [ftp://[user[:pass]@]host[:port]/path[/]]\n"
1058 " [http://[user[:pass]@]host[:port]/path] [...]\n"
1060 " [https://[user[:pass]@]host[:port]/path] [...]\n"
1062 " %s -u URL file [...]\n", progname
, progname
);