Index: stable/12/contrib/tnftp/src/cmds.c =================================================================== --- stable/12/contrib/tnftp/src/cmds.c (revision 362507) +++ stable/12/contrib/tnftp/src/cmds.c (revision 362508) @@ -1,2796 +1,2800 @@ /* $NetBSD: cmds.c,v 1.17 2010/01/12 06:55:47 lukem Exp $ */ /* from NetBSD: cmds.c,v 1.130 2009/07/13 19:05:41 roy Exp */ /*- * Copyright (c) 1996-2009 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Luke Mewburn. * * This code is derived from software contributed to The NetBSD Foundation * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility, * NASA Ames Research Center. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1985, 1989, 1993, 1994 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Copyright (C) 1997 and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "tnftp.h" #if 0 /* tnftp */ #include #ifndef lint #if 0 static char sccsid[] = "@(#)cmds.c 8.6 (Berkeley) 10/9/94"; #else __RCSID(" NetBSD: cmds.c,v 1.130 2009/07/13 19:05:41 roy Exp "); #endif #endif /* not lint */ /* * FTP User Program -- Command Routines. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #endif /* tnftp */ #include "ftp_var.h" #include "version.h" static struct types { const char *t_name; const char *t_mode; int t_type; const char *t_arg; } types[] = { { "ascii", "A", TYPE_A, 0 }, { "binary", "I", TYPE_I, 0 }, { "image", "I", TYPE_I, 0 }, { "ebcdic", "E", TYPE_E, 0 }, { "tenex", "L", TYPE_L, bytename }, { NULL, NULL, 0, NULL } }; static sigjmp_buf jabort; static int confirm(const char *, const char *); static void mintr(int); static void mabort(const char *); static void set_type(const char *); static const char *doprocess(char *, size_t, const char *, int, int, int); static const char *domap(char *, size_t, const char *); static const char *docase(char *, size_t, const char *); static const char *dotrans(char *, size_t, const char *); /* * Confirm if "cmd" is to be performed upon "file". * If "file" is NULL, generate a "Continue with" prompt instead. */ static int confirm(const char *cmd, const char *file) { const char *errormsg; char cline[BUFSIZ]; const char *promptleft, *promptright; if (!interactive || confirmrest) return (1); if (file == NULL) { promptleft = "Continue with"; promptright = cmd; } else { promptleft = cmd; promptright = file; } while (1) { fprintf(ttyout, "%s %s [anpqy?]? ", promptleft, promptright); (void)fflush(ttyout); if (get_line(stdin, cline, sizeof(cline), &errormsg) < 0) { mflag = 0; fprintf(ttyout, "%s; %s aborted\n", errormsg, cmd); return (0); } switch (tolower((unsigned char)*cline)) { case 'a': confirmrest = 1; fprintf(ttyout, "Prompting off for duration of %s.\n", cmd); break; case 'p': interactive = 0; fputs("Interactive mode: off.\n", ttyout); break; case 'q': mflag = 0; fprintf(ttyout, "%s aborted.\n", cmd); /* FALLTHROUGH */ case 'n': return (0); case '?': fprintf(ttyout, " confirmation options:\n" "\ta answer `yes' for the duration of %s\n" "\tn answer `no' for this file\n" "\tp turn off `prompt' mode\n" "\tq stop the current %s\n" "\ty answer `yes' for this file\n" "\t? this help list\n", cmd, cmd); continue; /* back to while(1) */ } return (1); } /* NOTREACHED */ } /* * Set transfer type. */ void settype(int argc, char *argv[]) { struct types *p; if (argc == 0 || argc > 2) { const char *sep; UPRINTF("usage: %s [", argv[0]); sep = " "; for (p = types; p->t_name; p++) { fprintf(ttyout, "%s%s", sep, p->t_name); sep = " | "; } fputs(" ]\n", ttyout); code = -1; return; } if (argc < 2) { fprintf(ttyout, "Using %s mode to transfer files.\n", typename); code = 0; return; } set_type(argv[1]); } void set_type(const char *ttype) { struct types *p; int comret; for (p = types; p->t_name; p++) if (strcmp(ttype, p->t_name) == 0) break; if (p->t_name == 0) { fprintf(ttyout, "%s: unknown mode.\n", ttype); code = -1; return; } if ((p->t_arg != NULL) && (*(p->t_arg) != '\0')) comret = command("TYPE %s %s", p->t_mode, p->t_arg); else comret = command("TYPE %s", p->t_mode); if (comret == COMPLETE) { (void)strlcpy(typename, p->t_name, sizeof(typename)); curtype = type = p->t_type; } } /* * Internal form of settype; changes current type in use with server * without changing our notion of the type for data transfers. * Used to change to and from ascii for listings. */ void changetype(int newtype, int show) { struct types *p; int comret, oldverbose = verbose; if (newtype == 0) newtype = TYPE_I; if (newtype == curtype) return; if (ftp_debug == 0 && show == 0) verbose = 0; for (p = types; p->t_name; p++) if (newtype == p->t_type) break; if (p->t_name == 0) { errx(1, "changetype: unknown type %d", newtype); } if (newtype == TYPE_L && bytename[0] != '\0') comret = command("TYPE %s %s", p->t_mode, bytename); else comret = command("TYPE %s", p->t_mode); if (comret == COMPLETE) curtype = newtype; verbose = oldverbose; } /* * Set binary transfer type. */ /*VARARGS*/ void setbinary(int argc, char *argv[]) { if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } set_type("binary"); } /* * Set ascii transfer type. */ /*VARARGS*/ void setascii(int argc, char *argv[]) { if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } set_type("ascii"); } /* * Set tenex transfer type. */ /*VARARGS*/ void settenex(int argc, char *argv[]) { if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } set_type("tenex"); } /* * Set file transfer mode. */ /*ARGSUSED*/ void setftmode(int argc, char *argv[]) { if (argc != 2) { UPRINTF("usage: %s mode-name\n", argv[0]); code = -1; return; } fprintf(ttyout, "We only support %s mode, sorry.\n", modename); code = -1; } /* * Set file transfer format. */ /*ARGSUSED*/ void setform(int argc, char *argv[]) { if (argc != 2) { UPRINTF("usage: %s format\n", argv[0]); code = -1; return; } fprintf(ttyout, "We only support %s format, sorry.\n", formname); code = -1; } /* * Set file transfer structure. */ /*ARGSUSED*/ void setstruct(int argc, char *argv[]) { if (argc != 2) { UPRINTF("usage: %s struct-mode\n", argv[0]); code = -1; return; } fprintf(ttyout, "We only support %s structure, sorry.\n", structname); code = -1; } /* * Send a single file. */ void put(int argc, char *argv[]) { char buf[MAXPATHLEN]; const char *cmd; int loc = 0; char *locfile; const char *remfile; if (argc == 2) { argc++; argv[2] = argv[1]; loc++; } if (argc == 0 || (argc == 1 && !another(&argc, &argv, "local-file"))) goto usage; if ((argc < 3 && !another(&argc, &argv, "remote-file")) || argc > 3) { usage: UPRINTF("usage: %s local-file [remote-file]\n", argv[0]); code = -1; return; } if ((locfile = globulize(argv[1])) == NULL) { code = -1; return; } remfile = argv[2]; if (loc) /* If argv[2] is a copy of the old argv[1], update it */ remfile = locfile; cmd = (argv[0][0] == 'a') ? "APPE" : ((sunique) ? "STOU" : "STOR"); remfile = doprocess(buf, sizeof(buf), remfile, 0, loc && ntflag, loc && mapflag); sendrequest(cmd, locfile, remfile, locfile != argv[1] || remfile != argv[2]); free(locfile); } static const char * doprocess(char *dst, size_t dlen, const char *src, int casef, int transf, int mapf) { if (casef) src = docase(dst, dlen, src); if (transf) src = dotrans(dst, dlen, src); if (mapf) src = domap(dst, dlen, src); return src; } /* * Send multiple files. */ void mput(int argc, char *argv[]) { int i; sigfunc oldintr; int ointer; const char *tp; if (argc == 0 || (argc == 1 && !another(&argc, &argv, "local-files"))) { UPRINTF("usage: %s local-files\n", argv[0]); code = -1; return; } mflag = 1; oldintr = xsignal(SIGINT, mintr); if (sigsetjmp(jabort, 1)) mabort(argv[0]); if (proxy) { char *cp; while ((cp = remglob(argv, 0, NULL)) != NULL) { if (*cp == '\0' || !connected) { mflag = 0; continue; } if (mflag && confirm(argv[0], cp)) { char buf[MAXPATHLEN]; tp = doprocess(buf, sizeof(buf), cp, mcase, ntflag, mapflag); sendrequest((sunique) ? "STOU" : "STOR", cp, tp, cp != tp || !interactive); if (!mflag && fromatty) { ointer = interactive; interactive = 1; if (confirm(argv[0], NULL)) { mflag++; } interactive = ointer; } } } goto cleanupmput; } for (i = 1; i < argc && connected; i++) { char **cpp; glob_t gl; int flags; if (!doglob) { if (mflag && confirm(argv[0], argv[i])) { char buf[MAXPATHLEN]; tp = doprocess(buf, sizeof(buf), argv[i], 0, ntflag, mapflag); sendrequest((sunique) ? "STOU" : "STOR", argv[i], tp, tp != argv[i] || !interactive); if (!mflag && fromatty) { ointer = interactive; interactive = 1; if (confirm(argv[0], NULL)) { mflag++; } interactive = ointer; } } continue; } memset(&gl, 0, sizeof(gl)); flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE; if (glob(argv[i], flags, NULL, &gl) || gl.gl_pathc == 0) { warnx("Glob pattern `%s' not found", argv[i]); globfree(&gl); continue; } for (cpp = gl.gl_pathv; cpp && *cpp != NULL && connected; cpp++) { if (mflag && confirm(argv[0], *cpp)) { char buf[MAXPATHLEN]; tp = *cpp; tp = doprocess(buf, sizeof(buf), *cpp, 0, ntflag, mapflag); sendrequest((sunique) ? "STOU" : "STOR", *cpp, tp, *cpp != tp || !interactive); if (!mflag && fromatty) { ointer = interactive; interactive = 1; if (confirm(argv[0], NULL)) { mflag++; } interactive = ointer; } } } globfree(&gl); } cleanupmput: (void)xsignal(SIGINT, oldintr); mflag = 0; } void reget(int argc, char *argv[]) { (void)getit(argc, argv, 1, "r+"); } void get(int argc, char *argv[]) { (void)getit(argc, argv, 0, restart_point ? "r+" : "w" ); } /* * Receive one file. * If restartit is 1, restart the xfer always. * If restartit is -1, restart the xfer only if the remote file is newer. */ int getit(int argc, char *argv[], int restartit, const char *gmode) { int loc, rval; char *remfile, *olocfile; const char *locfile; char buf[MAXPATHLEN]; loc = rval = 0; if (argc == 2) { argc++; argv[2] = argv[1]; loc++; } if (argc == 0 || (argc == 1 && !another(&argc, &argv, "remote-file"))) goto usage; if ((argc < 3 && !another(&argc, &argv, "local-file")) || argc > 3) { usage: UPRINTF("usage: %s remote-file [local-file]\n", argv[0]); code = -1; return (0); } remfile = argv[1]; if ((olocfile = globulize(argv[2])) == NULL) { code = -1; return (0); } locfile = doprocess(buf, sizeof(buf), olocfile, loc && mcase, loc && ntflag, loc && mapflag); if (restartit) { struct stat stbuf; int ret; if (! features[FEAT_REST_STREAM]) { fprintf(ttyout, "Restart is not supported by the remote server.\n"); return (0); } ret = stat(locfile, &stbuf); if (restartit == 1) { if (ret < 0) { warn("Can't stat `%s'", locfile); goto freegetit; } restart_point = stbuf.st_size; } else { if (ret == 0) { time_t mtime; mtime = remotemodtime(argv[1], 0); if (mtime == -1) goto freegetit; if (stbuf.st_mtime >= mtime) { rval = 1; goto freegetit; } } } } recvrequest("RETR", locfile, remfile, gmode, remfile != argv[1] || locfile != argv[2], loc); restart_point = 0; freegetit: (void)free(olocfile); return (rval); } /* ARGSUSED */ static void mintr(int signo) { alarmtimer(0); if (fromatty) write(fileno(ttyout), "\n", 1); siglongjmp(jabort, 1); } static void mabort(const char *cmd) { int ointer, oconf; if (mflag && fromatty) { ointer = interactive; oconf = confirmrest; interactive = 1; confirmrest = 0; if (confirm(cmd, NULL)) { interactive = ointer; confirmrest = oconf; return; } interactive = ointer; confirmrest = oconf; } mflag = 0; } /* * Get multiple files. */ void mget(int argc, char *argv[]) { sigfunc oldintr; int ointer; char *cp; const char *tp; int volatile restartit; if (argc == 0 || (argc == 1 && !another(&argc, &argv, "remote-files"))) { UPRINTF("usage: %s remote-files\n", argv[0]); code = -1; return; } mflag = 1; restart_point = 0; restartit = 0; if (strcmp(argv[0], "mreget") == 0) { if (! features[FEAT_REST_STREAM]) { fprintf(ttyout, "Restart is not supported by the remote server.\n"); return; } restartit = 1; } oldintr = xsignal(SIGINT, mintr); if (sigsetjmp(jabort, 1)) mabort(argv[0]); while ((cp = remglob(argv, proxy, NULL)) != NULL) { char buf[MAXPATHLEN]; if (*cp == '\0' || !connected) { mflag = 0; continue; } if (! mflag) continue; if (! fileindir(cp, localcwd)) { fprintf(ttyout, "Skipping non-relative filename `%s'\n", cp); continue; } if (!confirm(argv[0], cp)) continue; tp = doprocess(buf, sizeof(buf), cp, mcase, ntflag, mapflag); if (restartit) { struct stat stbuf; if (stat(tp, &stbuf) == 0) restart_point = stbuf.st_size; else warn("Can't stat `%s'", tp); } recvrequest("RETR", tp, cp, restart_point ? "r+" : "w", tp != cp || !interactive, 1); restart_point = 0; if (!mflag && fromatty) { ointer = interactive; interactive = 1; if (confirm(argv[0], NULL)) mflag++; interactive = ointer; } } (void)xsignal(SIGINT, oldintr); mflag = 0; } /* * Read list of filenames from a local file and get those */ void fget(int argc, char *argv[]) { const char *gmode; FILE *fp; char buf[MAXPATHLEN], cmdbuf[MAX_C_NAME]; if (argc != 2) { UPRINTF("usage: %s localfile\n", argv[0]); code = -1; return; } fp = fopen(argv[1], "r"); if (fp == NULL) { fprintf(ttyout, "Can't open source file %s\n", argv[1]); code = -1; return; } (void)strlcpy(cmdbuf, "get", sizeof(cmdbuf)); argv[0] = cmdbuf; gmode = restart_point ? "r+" : "w"; while (get_line(fp, buf, sizeof(buf), NULL) >= 0) { if (buf[0] == '\0') continue; argv[1] = buf; (void)getit(argc, argv, 0, gmode); } fclose(fp); } const char * onoff(int val) { return (val ? "on" : "off"); } /* * Show status. */ /*ARGSUSED*/ void status(int argc, char *argv[]) { if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } #ifndef NO_STATUS if (connected) fprintf(ttyout, "Connected %sto %s.\n", connected == -1 ? "and logged in" : "", hostname); else fputs("Not connected.\n", ttyout); if (!proxy) { pswitch(1); if (connected) { fprintf(ttyout, "Connected for proxy commands to %s.\n", hostname); } else { fputs("No proxy connection.\n", ttyout); } pswitch(0); } fprintf(ttyout, "Gate ftp: %s, server %s, port %s.\n", onoff(gatemode), *gateserver ? gateserver : "(none)", gateport); fprintf(ttyout, "Passive mode: %s; fallback to active mode: %s.\n", onoff(passivemode), onoff(activefallback)); fprintf(ttyout, "Mode: %s; Type: %s; Form: %s; Structure: %s.\n", modename, typename, formname, structname); fprintf(ttyout, "Verbose: %s; Bell: %s; Prompting: %s; Globbing: %s.\n", onoff(verbose), onoff(bell), onoff(interactive), onoff(doglob)); fprintf(ttyout, "Store unique: %s; Receive unique: %s.\n", onoff(sunique), onoff(runique)); fprintf(ttyout, "Preserve modification times: %s.\n", onoff(preserve)); fprintf(ttyout, "Case: %s; CR stripping: %s.\n", onoff(mcase), onoff(crflag)); if (ntflag) { fprintf(ttyout, "Ntrans: (in) %s (out) %s\n", ntin, ntout); } else { fputs("Ntrans: off.\n", ttyout); } if (mapflag) { fprintf(ttyout, "Nmap: (in) %s (out) %s\n", mapin, mapout); } else { fputs("Nmap: off.\n", ttyout); } fprintf(ttyout, "Hash mark printing: %s; Mark count: %d; Progress bar: %s.\n", onoff(hash), mark, onoff(progress)); fprintf(ttyout, "Get transfer rate throttle: %s; maximum: %d; increment %d.\n", onoff(rate_get), rate_get, rate_get_incr); fprintf(ttyout, "Put transfer rate throttle: %s; maximum: %d; increment %d.\n", onoff(rate_put), rate_put, rate_put_incr); fprintf(ttyout, "Socket buffer sizes: send %d, receive %d.\n", sndbuf_size, rcvbuf_size); fprintf(ttyout, "Use of PORT cmds: %s.\n", onoff(sendport)); fprintf(ttyout, "Use of EPSV/EPRT cmds for IPv4: %s%s.\n", onoff(epsv4), epsv4bad ? " (disabled for this connection)" : ""); fprintf(ttyout, "Use of EPSV/EPRT cmds for IPv6: %s%s.\n", onoff(epsv6), epsv6bad ? " (disabled for this connection)" : ""); fprintf(ttyout, "Command line editing: %s.\n", #ifdef NO_EDITCOMPLETE "support not compiled in" #else /* !def NO_EDITCOMPLETE */ onoff(editing) #endif /* !def NO_EDITCOMPLETE */ ); if (macnum > 0) { int i; fputs("Macros:\n", ttyout); for (i=0; i 3) { UPRINTF( "usage: %s [ on | off | gateserver [port] ]\n", argv[0]); code = -1; return; } else if (argc < 2) { gatemode = !gatemode; } else { if (argc == 2 && strcasecmp(argv[1], "on") == 0) gatemode = 1; else if (argc == 2 && strcasecmp(argv[1], "off") == 0) gatemode = 0; else { if (argc == 3) gateport = ftp_strdup(argv[2]); (void)strlcpy(gsbuf, argv[1], sizeof(gsbuf)); gateserver = gsbuf; gatemode = 1; } } if (gatemode && (gateserver == NULL || *gateserver == '\0')) { fprintf(ttyout, "Disabling gate-ftp mode - no gate-ftp server defined.\n"); gatemode = 0; } else { fprintf(ttyout, "Gate ftp: %s, server %s, port %s.\n", onoff(gatemode), *gateserver ? gateserver : "(none)", gateport); } code = gatemode; } /* * Toggle metacharacter interpretation on local file names. */ /*VARARGS*/ void setglob(int argc, char *argv[]) { code = togglevar(argc, argv, &doglob, "Globbing"); } /* * Toggle preserving modification times on retrieved files. */ /*VARARGS*/ void setpreserve(int argc, char *argv[]) { code = togglevar(argc, argv, &preserve, "Preserve modification times"); } /* * Set debugging mode on/off and/or set level of debugging. */ /*VARARGS*/ void setdebug(int argc, char *argv[]) { if (argc == 0 || argc > 2) { UPRINTF("usage: %s [ on | off | debuglevel ]\n", argv[0]); code = -1; return; } else if (argc == 2) { if (strcasecmp(argv[1], "on") == 0) ftp_debug = 1; else if (strcasecmp(argv[1], "off") == 0) ftp_debug = 0; else { int val; val = strsuftoi(argv[1]); if (val < 0) { fprintf(ttyout, "%s: bad debugging value.\n", argv[1]); code = -1; return; } ftp_debug = val; } } else ftp_debug = !ftp_debug; if (ftp_debug) options |= SO_DEBUG; else options &= ~SO_DEBUG; fprintf(ttyout, "Debugging %s (ftp_debug=%d).\n", onoff(ftp_debug), ftp_debug); code = ftp_debug > 0; } /* * Set current working directory on remote machine. */ void cd(int argc, char *argv[]) { int r; if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "remote-directory"))) { UPRINTF("usage: %s remote-directory\n", argv[0]); code = -1; return; } r = command("CWD %s", argv[1]); if (r == ERROR && code == 500) { if (verbose) fputs("CWD command not recognized, trying XCWD.\n", ttyout); r = command("XCWD %s", argv[1]); } if (r == COMPLETE) { dirchange = 1; updateremotecwd(); } } /* * Set current working directory on local machine. */ void lcd(int argc, char *argv[]) { char *locdir; code = -1; if (argc == 1) { argc++; argv[1] = localhome; } if (argc != 2) { UPRINTF("usage: %s [local-directory]\n", argv[0]); return; } if ((locdir = globulize(argv[1])) == NULL) return; if (chdir(locdir) == -1) warn("Can't chdir `%s'", locdir); else { updatelocalcwd(); if (localcwd[0]) { fprintf(ttyout, "Local directory now: %s\n", localcwd); code = 0; } else { fprintf(ttyout, "Unable to determine local directory\n"); } } (void)free(locdir); } /* * Delete a single file. */ void delete(int argc, char *argv[]) { if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "remote-file"))) { UPRINTF("usage: %s remote-file\n", argv[0]); code = -1; return; } if (command("DELE %s", argv[1]) == COMPLETE) dirchange = 1; } /* * Delete multiple files. */ void mdelete(int argc, char *argv[]) { sigfunc oldintr; int ointer; char *cp; if (argc == 0 || (argc == 1 && !another(&argc, &argv, "remote-files"))) { UPRINTF("usage: %s [remote-files]\n", argv[0]); code = -1; return; } mflag = 1; oldintr = xsignal(SIGINT, mintr); if (sigsetjmp(jabort, 1)) mabort(argv[0]); while ((cp = remglob(argv, 0, NULL)) != NULL) { if (*cp == '\0') { mflag = 0; continue; } if (mflag && confirm(argv[0], cp)) { if (command("DELE %s", cp) == COMPLETE) dirchange = 1; if (!mflag && fromatty) { ointer = interactive; interactive = 1; if (confirm(argv[0], NULL)) { mflag++; } interactive = ointer; } } } (void)xsignal(SIGINT, oldintr); mflag = 0; } /* * Rename a remote file. */ void renamefile(int argc, char *argv[]) { if (argc == 0 || (argc == 1 && !another(&argc, &argv, "from-name"))) goto usage; if ((argc < 3 && !another(&argc, &argv, "to-name")) || argc > 3) { usage: UPRINTF("usage: %s from-name to-name\n", argv[0]); code = -1; return; } if (command("RNFR %s", argv[1]) == CONTINUE && command("RNTO %s", argv[2]) == COMPLETE) dirchange = 1; } /* * Get a directory listing of remote files. * Supports being invoked as: * cmd runs * --- ---- * dir, ls LIST * mlsd MLSD * nlist NLST * pdir, pls LIST |$PAGER * pmlsd MLSD |$PAGER */ void ls(int argc, char *argv[]) { const char *cmd; char *remdir, *locbuf; const char *locfile; int pagecmd, mlsdcmd; remdir = NULL; locbuf = NULL; locfile = "-"; pagecmd = mlsdcmd = 0; /* * the only commands that start with `p' are * the `pager' versions. */ if (argv[0][0] == 'p') pagecmd = 1; if (strcmp(argv[0] + pagecmd , "mlsd") == 0) { if (! features[FEAT_MLST]) { fprintf(ttyout, "MLSD is not supported by the remote server.\n"); return; } mlsdcmd = 1; } if (argc == 0) goto usage; if (mlsdcmd) cmd = "MLSD"; else if (strcmp(argv[0] + pagecmd, "nlist") == 0) cmd = "NLST"; else cmd = "LIST"; if (argc > 1) remdir = argv[1]; if (argc > 2) locfile = argv[2]; if (argc > 3 || ((pagecmd | mlsdcmd) && argc > 2)) { usage: if (pagecmd || mlsdcmd) UPRINTF("usage: %s [remote-path]\n", argv[0]); else UPRINTF("usage: %s [remote-path [local-file]]\n", argv[0]); code = -1; goto freels; } if (pagecmd) { const char *p; size_t len; p = getoptionvalue("pager"); if (EMPTYSTRING(p)) p = DEFAULTPAGER; len = strlen(p) + 2; locbuf = ftp_malloc(len); locbuf[0] = '|'; (void)strlcpy(locbuf + 1, p, len - 1); locfile = locbuf; } else if ((strcmp(locfile, "-") != 0) && *locfile != '|') { if ((locbuf = globulize(locfile)) == NULL || !confirm("output to local-file:", locbuf)) { code = -1; goto freels; } locfile = locbuf; } recvrequest(cmd, locfile, remdir, "w", 0, 0); freels: if (locbuf) (void)free(locbuf); } /* * Get a directory listing of multiple remote files. */ void mls(int argc, char *argv[]) { sigfunc oldintr; int ointer, i; int volatile dolist; char * volatile dest, *odest; const char *lmode; if (argc == 0) goto usage; if (argc < 2 && !another(&argc, &argv, "remote-files")) goto usage; if (argc < 3 && !another(&argc, &argv, "local-file")) { usage: UPRINTF("usage: %s remote-files local-file\n", argv[0]); code = -1; return; } odest = dest = argv[argc - 1]; argv[argc - 1] = NULL; if (strcmp(dest, "-") && *dest != '|') if (((dest = globulize(dest)) == NULL) || !confirm("output to local-file:", dest)) { code = -1; return; } dolist = strcmp(argv[0], "mls"); mflag = 1; oldintr = xsignal(SIGINT, mintr); if (sigsetjmp(jabort, 1)) mabort(argv[0]); for (i = 1; mflag && i < argc-1 && connected; i++) { lmode = (i == 1) ? "w" : "a"; recvrequest(dolist ? "LIST" : "NLST", dest, argv[i], lmode, 0, 0); if (!mflag && fromatty) { ointer = interactive; interactive = 1; if (confirm(argv[0], NULL)) { mflag++; } interactive = ointer; } } (void)xsignal(SIGINT, oldintr); mflag = 0; if (dest != odest) /* free up after globulize() */ free(dest); } /* * Do a shell escape */ /*ARGSUSED*/ void shell(int argc, char *argv[]) { pid_t pid; sigfunc oldintr; char shellnam[MAXPATHLEN]; const char *shellp, *namep; int wait_status; if (argc == 0) { UPRINTF("usage: %s [command [args]]\n", argv[0]); code = -1; return; } oldintr = xsignal(SIGINT, SIG_IGN); if ((pid = fork()) == 0) { (void)closefrom(3); (void)xsignal(SIGINT, SIG_DFL); shellp = getenv("SHELL"); if (shellp == NULL) shellp = _PATH_BSHELL; namep = strrchr(shellp, '/'); if (namep == NULL) namep = shellp; else namep++; (void)strlcpy(shellnam, namep, sizeof(shellnam)); if (ftp_debug) { fputs(shellp, ttyout); putc('\n', ttyout); } if (argc > 1) { execl(shellp, shellnam, "-c", altarg, (char *)0); } else { execl(shellp, shellnam, (char *)0); } warn("Can't execute `%s'", shellp); code = -1; exit(1); } if (pid > 0) while (wait(&wait_status) != pid) ; (void)xsignal(SIGINT, oldintr); if (pid == -1) { warn("Can't fork a subshell; try again later"); code = -1; } else code = 0; } /* * Send new user information (re-login) */ void user(int argc, char *argv[]) { char *password; char emptypass[] = ""; int n, aflag = 0; if (argc == 0) goto usage; if (argc < 2) (void)another(&argc, &argv, "username"); if (argc < 2 || argc > 4) { usage: UPRINTF("usage: %s username [password [account]]\n", argv[0]); code = -1; return; } n = command("USER %s", argv[1]); if (n == CONTINUE) { if (argc < 3) { password = getpass("Password: "); if (password == NULL) password = emptypass; } else { password = argv[2]; } n = command("PASS %s", password); memset(password, 0, strlen(password)); } if (n == CONTINUE) { aflag++; if (argc < 4) { password = getpass("Account: "); if (password == NULL) password = emptypass; } else { password = argv[3]; } n = command("ACCT %s", password); memset(password, 0, strlen(password)); } if (n != COMPLETE) { fputs("Login failed.\n", ttyout); return; } if (!aflag && argc == 4) { password = argv[3]; (void)command("ACCT %s", password); memset(password, 0, strlen(password)); } connected = -1; getremoteinfo(); } /* * Print working directory on remote machine. */ /*VARARGS*/ void pwd(int argc, char *argv[]) { code = -1; if (argc != 1) { UPRINTF("usage: %s\n", argv[0]); return; } if (! remotecwd[0]) updateremotecwd(); if (! remotecwd[0]) fprintf(ttyout, "Unable to determine remote directory\n"); else { fprintf(ttyout, "Remote directory: %s\n", remotecwd); code = 0; } } /* * Print working directory on local machine. */ void lpwd(int argc, char *argv[]) { code = -1; if (argc != 1) { UPRINTF("usage: %s\n", argv[0]); return; } if (! localcwd[0]) updatelocalcwd(); if (! localcwd[0]) fprintf(ttyout, "Unable to determine local directory\n"); else { fprintf(ttyout, "Local directory: %s\n", localcwd); code = 0; } } /* * Make a directory. */ void makedir(int argc, char *argv[]) { int r; if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "directory-name"))) { UPRINTF("usage: %s directory-name\n", argv[0]); code = -1; return; } r = command("MKD %s", argv[1]); if (r == ERROR && code == 500) { if (verbose) fputs("MKD command not recognized, trying XMKD.\n", ttyout); r = command("XMKD %s", argv[1]); } if (r == COMPLETE) dirchange = 1; } /* * Remove a directory. */ void removedir(int argc, char *argv[]) { int r; if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "directory-name"))) { UPRINTF("usage: %s directory-name\n", argv[0]); code = -1; return; } r = command("RMD %s", argv[1]); if (r == ERROR && code == 500) { if (verbose) fputs("RMD command not recognized, trying XRMD.\n", ttyout); r = command("XRMD %s", argv[1]); } if (r == COMPLETE) dirchange = 1; } /* * Send a line, verbatim, to the remote machine. */ void quote(int argc, char *argv[]) { if (argc == 0 || (argc == 1 && !another(&argc, &argv, "command line to send"))) { UPRINTF("usage: %s line-to-send\n", argv[0]); code = -1; return; } quote1("", argc, argv); } /* * Send a SITE command to the remote machine. The line * is sent verbatim to the remote machine, except that the * word "SITE" is added at the front. */ void site(int argc, char *argv[]) { if (argc == 0 || (argc == 1 && !another(&argc, &argv, "arguments to SITE command"))){ UPRINTF("usage: %s line-to-send\n", argv[0]); code = -1; return; } quote1("SITE ", argc, argv); } /* * Turn argv[1..argc) into a space-separated string, then prepend initial text. * Send the result as a one-line command and get response. */ void quote1(const char *initial, int argc, char *argv[]) { int i; char buf[BUFSIZ]; /* must be >= sizeof(line) */ (void)strlcpy(buf, initial, sizeof(buf)); for (i = 1; i < argc; i++) { (void)strlcat(buf, argv[i], sizeof(buf)); if (i < (argc - 1)) (void)strlcat(buf, " ", sizeof(buf)); } if (command("%s", buf) == PRELIM) { while (getreply(0) == PRELIM) continue; } dirchange = 1; } void do_chmod(int argc, char *argv[]) { if (argc == 0 || (argc == 1 && !another(&argc, &argv, "mode"))) goto usage; if ((argc < 3 && !another(&argc, &argv, "remote-file")) || argc > 3) { usage: UPRINTF("usage: %s mode remote-file\n", argv[0]); code = -1; return; } (void)command("SITE CHMOD %s %s", argv[1], argv[2]); } #define COMMAND_1ARG(argc, argv, cmd) \ if (argc == 1) \ command(cmd); \ else \ command(cmd " %s", argv[1]) void do_umask(int argc, char *argv[]) { int oldverbose = verbose; if (argc == 0) { UPRINTF("usage: %s [umask]\n", argv[0]); code = -1; return; } verbose = 1; COMMAND_1ARG(argc, argv, "SITE UMASK"); verbose = oldverbose; } void idlecmd(int argc, char *argv[]) { int oldverbose = verbose; if (argc < 1 || argc > 2) { UPRINTF("usage: %s [seconds]\n", argv[0]); code = -1; return; } verbose = 1; COMMAND_1ARG(argc, argv, "SITE IDLE"); verbose = oldverbose; } /* * Ask the other side for help. */ void rmthelp(int argc, char *argv[]) { int oldverbose = verbose; if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } verbose = 1; COMMAND_1ARG(argc, argv, "HELP"); verbose = oldverbose; } /* * Terminate session and exit. * May be called with 0, NULL. */ /*VARARGS*/ void quit(int argc, char *argv[]) { /* this may be called with argc == 0, argv == NULL */ if (argc == 0 && argv != NULL) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } if (connected) disconnect(0, NULL); pswitch(1); if (connected) disconnect(0, NULL); exit(0); } /* * Terminate session, but don't exit. * May be called with 0, NULL. */ void disconnect(int argc, char *argv[]) { /* this may be called with argc == 0, argv == NULL */ if (argc == 0 && argv != NULL) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } if (!connected) return; (void)command("QUIT"); cleanuppeer(); } void account(int argc, char *argv[]) { char *ap; char emptypass[] = ""; if (argc == 0 || argc > 2) { UPRINTF("usage: %s [password]\n", argv[0]); code = -1; return; } else if (argc == 2) ap = argv[1]; else { ap = getpass("Account:"); if (ap == NULL) ap = emptypass; } (void)command("ACCT %s", ap); memset(ap, 0, strlen(ap)); } sigjmp_buf abortprox; void proxabort(int notused) { sigint_raised = 1; alarmtimer(0); if (!proxy) { pswitch(1); } if (connected) { proxflag = 1; } else { proxflag = 0; } pswitch(0); siglongjmp(abortprox, 1); } void doproxy(int argc, char *argv[]) { struct cmd *c; int cmdpos; sigfunc oldintr; char cmdbuf[MAX_C_NAME]; if (argc == 0 || (argc == 1 && !another(&argc, &argv, "command"))) { UPRINTF("usage: %s command\n", argv[0]); code = -1; return; } c = getcmd(argv[1]); if (c == (struct cmd *) -1) { fputs("?Ambiguous command.\n", ttyout); code = -1; return; } if (c == 0) { fputs("?Invalid command.\n", ttyout); code = -1; return; } if (!c->c_proxy) { fputs("?Invalid proxy command.\n", ttyout); code = -1; return; } if (sigsetjmp(abortprox, 1)) { code = -1; return; } oldintr = xsignal(SIGINT, proxabort); pswitch(1); if (c->c_conn && !connected) { fputs("Not connected.\n", ttyout); pswitch(0); (void)xsignal(SIGINT, oldintr); code = -1; return; } cmdpos = strcspn(line, " \t"); if (cmdpos > 0) /* remove leading "proxy " from input buffer */ memmove(line, line + cmdpos + 1, strlen(line) - cmdpos + 1); (void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf)); argv[1] = cmdbuf; (*c->c_handler)(argc-1, argv+1); if (connected) { proxflag = 1; } else { proxflag = 0; } pswitch(0); (void)xsignal(SIGINT, oldintr); } void setcase(int argc, char *argv[]) { code = togglevar(argc, argv, &mcase, "Case mapping"); } /* * convert the given name to lower case if it's all upper case, into * a static buffer which is returned to the caller */ static const char * docase(char *dst, size_t dlen, const char *src) { size_t i; int dochange = 1; for (i = 0; src[i] != '\0' && i < dlen - 1; i++) { dst[i] = src[i]; if (islower((unsigned char)dst[i])) dochange = 0; } dst[i] = '\0'; if (dochange) { for (i = 0; dst[i] != '\0'; i++) if (isupper((unsigned char)dst[i])) dst[i] = tolower((unsigned char)dst[i]); } return dst; } void setcr(int argc, char *argv[]) { code = togglevar(argc, argv, &crflag, "Carriage Return stripping"); } void setntrans(int argc, char *argv[]) { if (argc == 0 || argc > 3) { UPRINTF("usage: %s [inchars [outchars]]\n", argv[0]); code = -1; return; } if (argc == 1) { ntflag = 0; fputs("Ntrans off.\n", ttyout); code = ntflag; return; } ntflag++; code = ntflag; (void)strlcpy(ntin, argv[1], sizeof(ntin)); if (argc == 2) { ntout[0] = '\0'; return; } (void)strlcpy(ntout, argv[2], sizeof(ntout)); } static const char * dotrans(char *dst, size_t dlen, const char *src) { const char *cp1; char *cp2 = dst; size_t i, ostop; for (ostop = 0; *(ntout + ostop) && ostop < 16; ostop++) continue; for (cp1 = src; *cp1; cp1++) { int found = 0; for (i = 0; *(ntin + i) && i < 16; i++) { if (*cp1 == *(ntin + i)) { found++; if (i < ostop) { *cp2++ = *(ntout + i); if (cp2 - dst >= (ptrdiff_t)(dlen - 1)) goto out; } break; } } if (!found) { *cp2++ = *cp1; } } out: *cp2 = '\0'; return dst; } void setnmap(int argc, char *argv[]) { char *cp; if (argc == 1) { mapflag = 0; fputs("Nmap off.\n", ttyout); code = mapflag; return; } if (argc == 0 || (argc < 3 && !another(&argc, &argv, "mapout")) || argc > 3) { UPRINTF("usage: %s [mapin mapout]\n", argv[0]); code = -1; return; } mapflag = 1; code = 1; cp = strchr(altarg, ' '); if (proxy) { while(*++cp == ' ') continue; altarg = cp; cp = strchr(altarg, ' '); } *cp = '\0'; (void)strlcpy(mapin, altarg, MAXPATHLEN); while (*++cp == ' ') continue; (void)strlcpy(mapout, cp, MAXPATHLEN); } static const char * domap(char *dst, size_t dlen, const char *src) { const char *cp1 = src; char *cp2 = mapin; const char *tp[9], *te[9]; int i, toks[9], toknum = 0, match = 1; for (i=0; i < 9; ++i) { toks[i] = 0; } while (match && *cp1 && *cp2) { switch (*cp2) { case '\\': if (*++cp2 != *cp1) { match = 0; } break; case '$': if (*(cp2+1) >= '1' && (*cp2+1) <= '9') { if (*cp1 != *(++cp2+1)) { toks[toknum = *cp2 - '1']++; tp[toknum] = cp1; while (*++cp1 && *(cp2+1) != *cp1); te[toknum] = cp1; } cp2++; break; } /* FALLTHROUGH */ default: if (*cp2 != *cp1) { match = 0; } break; } if (match && *cp1) { cp1++; } if (match && *cp2) { cp2++; } } if (!match && *cp1) /* last token mismatch */ { toks[toknum] = 0; } cp2 = dst; *cp2 = '\0'; cp1 = mapout; while (*cp1) { match = 0; switch (*cp1) { case '\\': if (*(cp1 + 1)) { *cp2++ = *++cp1; } break; case '[': LOOP: if (*++cp1 == '$' && isdigit((unsigned char)*(cp1+1))) { if (*++cp1 == '0') { const char *cp3 = src; while (*cp3) { *cp2++ = *cp3++; } match = 1; } else if (toks[toknum = *cp1 - '1']) { const char *cp3 = tp[toknum]; while (cp3 != te[toknum]) { *cp2++ = *cp3++; } match = 1; } } else { while (*cp1 && *cp1 != ',' && *cp1 != ']') { if (*cp1 == '\\') { cp1++; } else if (*cp1 == '$' && isdigit((unsigned char)*(cp1+1))) { if (*++cp1 == '0') { const char *cp3 = src; while (*cp3) { *cp2++ = *cp3++; } } else if (toks[toknum = *cp1 - '1']) { const char *cp3=tp[toknum]; while (cp3 != te[toknum]) { *cp2++ = *cp3++; } } } else if (*cp1) { *cp2++ = *cp1++; } } if (!*cp1) { fputs( "nmap: unbalanced brackets.\n", ttyout); return (src); } match = 1; cp1--; } if (match) { while (*++cp1 && *cp1 != ']') { if (*cp1 == '\\' && *(cp1 + 1)) { cp1++; } } if (!*cp1) { fputs( "nmap: unbalanced brackets.\n", ttyout); return (src); } break; } switch (*++cp1) { case ',': goto LOOP; case ']': break; default: cp1--; goto LOOP; } break; case '$': if (isdigit((unsigned char)*(cp1 + 1))) { if (*++cp1 == '0') { const char *cp3 = src; while (*cp3) { *cp2++ = *cp3++; } } else if (toks[toknum = *cp1 - '1']) { const char *cp3 = tp[toknum]; while (cp3 != te[toknum]) { *cp2++ = *cp3++; } } break; } /* intentional drop through */ default: *cp2++ = *cp1; break; } cp1++; } *cp2 = '\0'; return *dst ? dst : src; } void setpassive(int argc, char *argv[]) { if (argc == 1) { passivemode = !passivemode; activefallback = passivemode; } else if (argc != 2) { passiveusage: UPRINTF("usage: %s [ on | off | auto ]\n", argv[0]); code = -1; return; } else if (strcasecmp(argv[1], "on") == 0) { passivemode = 1; activefallback = 0; } else if (strcasecmp(argv[1], "off") == 0) { passivemode = 0; activefallback = 0; } else if (strcasecmp(argv[1], "auto") == 0) { passivemode = 1; activefallback = 1; } else goto passiveusage; fprintf(ttyout, "Passive mode: %s; fallback to active mode: %s.\n", onoff(passivemode), onoff(activefallback)); code = passivemode; } void setepsv4(int argc, char *argv[]) { code = togglevar(argc, argv, &epsv4, verbose ? "EPSV/EPRT on IPv4" : NULL); epsv4bad = 0; } void setepsv6(int argc, char *argv[]) { code = togglevar(argc, argv, &epsv6, verbose ? "EPSV/EPRT on IPv6" : NULL); epsv6bad = 0; } void setepsv(int argc, char*argv[]) { setepsv4(argc,argv); setepsv6(argc,argv); } void setsunique(int argc, char *argv[]) { code = togglevar(argc, argv, &sunique, "Store unique"); } void setrunique(int argc, char *argv[]) { code = togglevar(argc, argv, &runique, "Receive unique"); } int parserate(int argc, char *argv[], int cmdlineopt) { int dir, max, incr, showonly; sigfunc oldusr1, oldusr2; if (argc > 4 || (argc < (cmdlineopt ? 3 : 2))) { usage: if (cmdlineopt) UPRINTF( "usage: %s (all|get|put),maximum-bytes[,increment-bytes]]\n", argv[0]); else UPRINTF( "usage: %s (all|get|put) [maximum-bytes [increment-bytes]]\n", argv[0]); return -1; } dir = max = incr = showonly = 0; #define RATE_GET 1 #define RATE_PUT 2 #define RATE_ALL (RATE_GET | RATE_PUT) if (strcasecmp(argv[1], "all") == 0) dir = RATE_ALL; else if (strcasecmp(argv[1], "get") == 0) dir = RATE_GET; else if (strcasecmp(argv[1], "put") == 0) dir = RATE_PUT; else goto usage; if (argc >= 3) { if ((max = strsuftoi(argv[2])) < 0) goto usage; } else showonly = 1; if (argc == 4) { if ((incr = strsuftoi(argv[3])) <= 0) goto usage; } else incr = DEFAULTINCR; oldusr1 = xsignal(SIGUSR1, SIG_IGN); oldusr2 = xsignal(SIGUSR2, SIG_IGN); if (dir & RATE_GET) { if (!showonly) { rate_get = max; rate_get_incr = incr; } if (!cmdlineopt || verbose) fprintf(ttyout, "Get transfer rate throttle: %s; maximum: %d; increment %d.\n", onoff(rate_get), rate_get, rate_get_incr); } if (dir & RATE_PUT) { if (!showonly) { rate_put = max; rate_put_incr = incr; } if (!cmdlineopt || verbose) fprintf(ttyout, "Put transfer rate throttle: %s; maximum: %d; increment %d.\n", onoff(rate_put), rate_put, rate_put_incr); } (void)xsignal(SIGUSR1, oldusr1); (void)xsignal(SIGUSR2, oldusr2); return 0; } void setrate(int argc, char *argv[]) { code = parserate(argc, argv, 0); } /* change directory to parent directory */ void cdup(int argc, char *argv[]) { int r; if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } r = command("CDUP"); if (r == ERROR && code == 500) { if (verbose) fputs("CDUP command not recognized, trying XCUP.\n", ttyout); r = command("XCUP"); } if (r == COMPLETE) { dirchange = 1; updateremotecwd(); } } /* * Restart transfer at specific point */ void restart(int argc, char *argv[]) { if (argc == 0 || argc > 2) { UPRINTF("usage: %s [restart-point]\n", argv[0]); code = -1; return; } if (! features[FEAT_REST_STREAM]) { fprintf(ttyout, "Restart is not supported by the remote server.\n"); return; } if (argc == 2) { off_t rp; char *ep; rp = STRTOLL(argv[1], &ep, 10); if (rp < 0 || *ep != '\0') fprintf(ttyout, "restart: Invalid offset `%s'\n", argv[1]); else restart_point = rp; } if (restart_point == 0) fputs("No restart point defined.\n", ttyout); else fprintf(ttyout, "Restarting at " LLF " for next get, put or append\n", (LLT)restart_point); } /* * Show remote system type */ void syst(int argc, char *argv[]) { int oldverbose = verbose; if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } verbose = 1; /* If we aren't verbose, this doesn't do anything! */ (void)command("SYST"); verbose = oldverbose; } void macdef(int argc, char *argv[]) { char *tmp; int c; if (argc == 0) goto usage; if (macnum == 16) { fputs("Limit of 16 macros have already been defined.\n", ttyout); code = -1; return; } if ((argc < 2 && !another(&argc, &argv, "macro name")) || argc > 2) { usage: UPRINTF("usage: %s macro_name\n", argv[0]); code = -1; return; } if (interactive) fputs( "Enter macro line by line, terminating it with a null line.\n", ttyout); (void)strlcpy(macros[macnum].mac_name, argv[1], sizeof(macros[macnum].mac_name)); if (macnum == 0) macros[macnum].mac_start = macbuf; else macros[macnum].mac_start = macros[macnum - 1].mac_end + 1; tmp = macros[macnum].mac_start; while (tmp != macbuf+4096) { if ((c = getchar()) == EOF) { fputs("macdef: end of file encountered.\n", ttyout); code = -1; return; } if ((*tmp = c) == '\n') { if (tmp == macros[macnum].mac_start) { macros[macnum++].mac_end = tmp; code = 0; return; } if (*(tmp-1) == '\0') { macros[macnum++].mac_end = tmp - 1; code = 0; return; } *tmp = '\0'; } tmp++; } while (1) { while ((c = getchar()) != '\n' && c != EOF) /* LOOP */; if (c == EOF || getchar() == '\n') { fputs("Macro not defined - 4K buffer exceeded.\n", ttyout); code = -1; return; } } } /* * Get size of file on remote machine */ void sizecmd(int argc, char *argv[]) { off_t size; if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "remote-file"))) { UPRINTF("usage: %s remote-file\n", argv[0]); code = -1; return; } size = remotesize(argv[1], 1); if (size != -1) fprintf(ttyout, "%s\t" LLF "\n", argv[1], (LLT)size); code = (size > 0); } /* * Get last modification time of file on remote machine */ void modtime(int argc, char *argv[]) { time_t mtime; if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "remote-file"))) { UPRINTF("usage: %s remote-file\n", argv[0]); code = -1; return; } mtime = remotemodtime(argv[1], 1); if (mtime != -1) fprintf(ttyout, "%s\t%s", argv[1], rfc2822time(localtime(&mtime))); code = (mtime > 0); } /* * Show status on remote machine */ void rmtstatus(int argc, char *argv[]) { if (argc == 0) { UPRINTF("usage: %s [remote-file]\n", argv[0]); code = -1; return; } COMMAND_1ARG(argc, argv, "STAT"); } /* * Get file if modtime is more recent than current file */ void newer(int argc, char *argv[]) { if (getit(argc, argv, -1, "w")) fprintf(ttyout, "Local file \"%s\" is newer than remote file \"%s\".\n", argv[2], argv[1]); } /* * Display one local file through $PAGER. */ void lpage(int argc, char *argv[]) { size_t len; const char *p; char *pager, *locfile; if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "local-file"))) { UPRINTF("usage: %s local-file\n", argv[0]); code = -1; return; } if ((locfile = globulize(argv[1])) == NULL) { code = -1; return; } p = getoptionvalue("pager"); if (EMPTYSTRING(p)) p = DEFAULTPAGER; len = strlen(p) + strlen(locfile) + 2; pager = ftp_malloc(len); (void)strlcpy(pager, p, len); (void)strlcat(pager, " ", len); (void)strlcat(pager, locfile, len); system(pager); code = 0; (void)free(pager); (void)free(locfile); } /* * Display one remote file through $PAGER. */ void page(int argc, char *argv[]) { int ohash, orestart_point, overbose; size_t len; const char *p; char *pager; if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "remote-file"))) { UPRINTF("usage: %s remote-file\n", argv[0]); code = -1; return; } p = getoptionvalue("pager"); if (EMPTYSTRING(p)) p = DEFAULTPAGER; len = strlen(p) + 2; pager = ftp_malloc(len); pager[0] = '|'; (void)strlcpy(pager + 1, p, len - 1); ohash = hash; orestart_point = restart_point; overbose = verbose; hash = restart_point = verbose = 0; recvrequest("RETR", pager, argv[1], "r+", 1, 0); hash = ohash; restart_point = orestart_point; verbose = overbose; (void)free(pager); } /* * Set the socket send or receive buffer size. */ void setxferbuf(int argc, char *argv[]) { int size, dir; if (argc != 2) { usage: UPRINTF("usage: %s size\n", argv[0]); code = -1; return; } if (strcasecmp(argv[0], "sndbuf") == 0) dir = RATE_PUT; else if (strcasecmp(argv[0], "rcvbuf") == 0) dir = RATE_GET; else if (strcasecmp(argv[0], "xferbuf") == 0) dir = RATE_ALL; else goto usage; if ((size = strsuftoi(argv[1])) == -1) goto usage; if (size == 0) { fprintf(ttyout, "%s: size must be positive.\n", argv[0]); goto usage; } - if (dir & RATE_PUT) + if (dir & RATE_PUT) { sndbuf_size = size; - if (dir & RATE_GET) + auto_sndbuf = 0; + } + if (dir & RATE_GET) { rcvbuf_size = size; + auto_rcvbuf = 0; + } fprintf(ttyout, "Socket buffer sizes: send %d, receive %d.\n", sndbuf_size, rcvbuf_size); code = 0; } /* * Set or display options (defaults are provided by various env vars) */ void setoption(int argc, char *argv[]) { struct option *o; code = -1; if (argc == 0 || (argc != 1 && argc != 3)) { UPRINTF("usage: %s [option value]\n", argv[0]); return; } #define OPTIONINDENT ((int) sizeof("http_proxy")) if (argc == 1) { for (o = optiontab; o->name != NULL; o++) { fprintf(ttyout, "%-*s\t%s\n", OPTIONINDENT, o->name, o->value ? o->value : ""); } } else { set_option(argv[1], argv[2], 1); } code = 0; } void set_option(const char * option, const char * value, int doverbose) { struct option *o; o = getoption(option); if (o == NULL) { fprintf(ttyout, "No such option `%s'.\n", option); return; } FREEPTR(o->value); o->value = ftp_strdup(value); if (verbose && doverbose) fprintf(ttyout, "Setting `%s' to `%s'.\n", o->name, o->value); } /* * Unset an option */ void unsetoption(int argc, char *argv[]) { struct option *o; code = -1; if (argc == 0 || argc != 2) { UPRINTF("usage: %s option\n", argv[0]); return; } o = getoption(argv[1]); if (o == NULL) { fprintf(ttyout, "No such option `%s'.\n", argv[1]); return; } FREEPTR(o->value); fprintf(ttyout, "Unsetting `%s'.\n", o->name); code = 0; } /* * Display features supported by the remote host. */ void feat(int argc, char *argv[]) { int oldverbose = verbose; if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } if (! features[FEAT_FEAT]) { fprintf(ttyout, "FEAT is not supported by the remote server.\n"); return; } verbose = 1; /* If we aren't verbose, this doesn't do anything! */ (void)command("FEAT"); verbose = oldverbose; } void mlst(int argc, char *argv[]) { int oldverbose = verbose; if (argc < 1 || argc > 2) { UPRINTF("usage: %s [remote-path]\n", argv[0]); code = -1; return; } if (! features[FEAT_MLST]) { fprintf(ttyout, "MLST is not supported by the remote server.\n"); return; } verbose = 1; /* If we aren't verbose, this doesn't do anything! */ COMMAND_1ARG(argc, argv, "MLST"); verbose = oldverbose; } void opts(int argc, char *argv[]) { int oldverbose = verbose; if (argc < 2 || argc > 3) { UPRINTF("usage: %s command [options]\n", argv[0]); code = -1; return; } if (! features[FEAT_FEAT]) { fprintf(ttyout, "OPTS is not supported by the remote server.\n"); return; } verbose = 1; /* If we aren't verbose, this doesn't do anything! */ if (argc == 2) command("OPTS %s", argv[1]); else command("OPTS %s %s", argv[1], argv[2]); verbose = oldverbose; } Index: stable/12/contrib/tnftp/src/ftp_var.h =================================================================== --- stable/12/contrib/tnftp/src/ftp_var.h (revision 362507) +++ stable/12/contrib/tnftp/src/ftp_var.h (revision 362508) @@ -1,355 +1,357 @@ /* $NetBSD: ftp_var.h,v 1.10 2009/05/20 12:53:47 lukem Exp $ */ /* from NetBSD: ftp_var.h,v 1.81 2009/04/12 10:18:52 lukem Exp */ /*- * Copyright (c) 1996-2009 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Luke Mewburn. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1985, 1989, 1993, 1994 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)ftp_var.h 8.4 (Berkeley) 10/9/94 */ /* * Copyright (C) 1997 and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * FTP global variables. */ #ifdef SMALL #undef NO_EDITCOMPLETE #define NO_EDITCOMPLETE #undef NO_PROGRESS #define NO_PROGRESS #endif #if 0 /* tnftp */ #include #include #include #include #include #include #endif /* tnftp */ #ifndef NO_EDITCOMPLETE #include #endif /* !NO_EDITCOMPLETE */ #include "extern.h" #include "progressbar.h" /* * Format of command table. */ struct cmd { const char *c_name; /* name of command */ const char *c_help; /* help string */ char c_bell; /* give bell when command completes */ char c_conn; /* must be connected to use command */ char c_proxy; /* proxy server may execute */ #ifndef NO_EDITCOMPLETE const char *c_complete; /* context sensitive completion list */ #endif /* !NO_EDITCOMPLETE */ void (*c_handler)(int, char **); /* function to call */ }; #define MAX_C_NAME 12 /* maximum length of cmd.c_name */ /* * Format of macro table */ struct macel { char mac_name[9]; /* macro name */ char *mac_start; /* start of macro in macbuf */ char *mac_end; /* end of macro in macbuf */ }; /* * Format of option table */ struct option { const char *name; char *value; }; /* * Indices to features[]; an array containing status of remote server * features; -1 not known (FEAT failed), 0 absent, 1 present. */ enum { FEAT_FEAT = 0, /* FEAT, OPTS */ FEAT_MDTM, /* MDTM */ FEAT_MLST, /* MLSD, MLST */ FEAT_REST_STREAM, /* RESTart STREAM */ FEAT_SIZE, /* SIZE */ FEAT_TVFS, /* TVFS (not used) */ FEAT_max }; /* * Global defines */ #define FTPBUFLEN MAXPATHLEN + 200 #define MAX_IN_PORT_T 0xffffU #define HASHBYTES 1024 /* default mark for `hash' command */ #define DEFAULTINCR 1024 /* default increment for `rate' command */ #define FTP_PORT 21 /* default if ! getservbyname("ftp/tcp") */ #define HTTP_PORT 80 /* default if ! getservbyname("http/tcp") */ #ifndef GATE_PORT #define GATE_PORT 21 /* default if ! getservbyname("ftpgate/tcp") */ #endif #ifndef GATE_SERVER #define GATE_SERVER "" /* default server */ #endif #define DEFAULTPAGER "less" /* default pager if $PAGER isn't set */ #define DEFAULTPROMPT "ftp> " /* default prompt if `set prompt' is empty */ #define DEFAULTRPROMPT "" /* default rprompt if `set rprompt' is empty */ #define TMPFILE "ftpXXXXXXXXXX" #ifndef GLOBAL #define GLOBAL extern #endif /* * Options and other state info. */ GLOBAL int trace; /* trace packets exchanged */ GLOBAL int hash; /* print # for each buffer transferred */ GLOBAL int mark; /* number of bytes between hashes */ GLOBAL int sendport; /* use PORT/LPRT cmd for each data connection */ GLOBAL int connected; /* 1 = connected to server, -1 = logged in */ GLOBAL int interactive; /* interactively prompt on m* cmds */ GLOBAL int confirmrest; /* confirm rest of current m* cmd */ GLOBAL int ftp_debug; /* debugging level */ GLOBAL int bell; /* ring bell on cmd completion */ GLOBAL int doglob; /* glob local file names */ GLOBAL int autologin; /* establish user account on connection */ GLOBAL int proxy; /* proxy server connection active */ GLOBAL int proxflag; /* proxy connection exists */ GLOBAL int gatemode; /* use gate-ftp */ GLOBAL const char *gateserver; /* server to use for gate-ftp */ GLOBAL int sunique; /* store files on server with unique name */ GLOBAL int runique; /* store local files with unique name */ GLOBAL int mcase; /* map upper to lower case for mget names */ GLOBAL int ntflag; /* use ntin ntout tables for name translation */ GLOBAL int mapflag; /* use mapin mapout templates on file names */ GLOBAL int preserve; /* preserve modification time on files */ GLOBAL int code; /* return/reply code for ftp command */ GLOBAL int crflag; /* if 1, strip car. rets. on ascii gets */ GLOBAL int passivemode; /* passive mode enabled */ GLOBAL int activefallback; /* fall back to active mode if passive fails */ GLOBAL char *altarg; /* argv[1] with no shell-like preprocessing */ GLOBAL char ntin[17]; /* input translation table */ GLOBAL char ntout[17]; /* output translation table */ GLOBAL char mapin[MAXPATHLEN]; /* input map template */ GLOBAL char mapout[MAXPATHLEN]; /* output map template */ GLOBAL char typename[32]; /* name of file transfer type */ GLOBAL int type; /* requested file transfer type */ GLOBAL int curtype; /* current file transfer type */ GLOBAL char structname[32]; /* name of file transfer structure */ GLOBAL int stru; /* file transfer structure */ GLOBAL char formname[32]; /* name of file transfer format */ GLOBAL int form; /* file transfer format */ GLOBAL char modename[32]; /* name of file transfer mode */ GLOBAL int mode; /* file transfer mode */ GLOBAL char bytename[32]; /* local byte size in ascii */ GLOBAL int bytesize; /* local byte size in binary */ GLOBAL int anonftp; /* automatic anonymous login */ GLOBAL int dirchange; /* remote directory changed by cd command */ GLOBAL int flushcache; /* set HTTP cache flush headers with request */ GLOBAL int rate_get; /* maximum get xfer rate */ GLOBAL int rate_get_incr; /* increment for get xfer rate */ GLOBAL int rate_put; /* maximum put xfer rate */ GLOBAL int rate_put_incr; /* increment for put xfer rate */ GLOBAL int retry_connect; /* seconds between retrying connection */ GLOBAL const char *tmpdir; /* temporary directory */ GLOBAL int epsv4; /* use EPSV/EPRT on IPv4 connections */ GLOBAL int epsv4bad; /* EPSV doesn't work on the current server */ GLOBAL int epsv6; /* use EPSV/EPRT on IPv6 connections */ GLOBAL int epsv6bad; /* EPSV doesn't work on the current server */ GLOBAL int editing; /* command line editing enabled */ GLOBAL int features[FEAT_max]; /* remote FEATures supported */ #ifndef NO_EDITCOMPLETE GLOBAL EditLine *el; /* editline(3) status structure */ GLOBAL History *hist; /* editline(3) history structure */ GLOBAL char *cursor_pos; /* cursor position we're looking for */ GLOBAL size_t cursor_argc; /* location of cursor in margv */ GLOBAL size_t cursor_argo; /* offset of cursor in margv[cursor_argc] */ #endif /* !NO_EDITCOMPLETE */ GLOBAL char *hostname; /* name of host connected to */ GLOBAL int unix_server; /* server is unix, can use binary for ascii */ GLOBAL int unix_proxy; /* proxy is unix, can use binary for ascii */ GLOBAL char localcwd[MAXPATHLEN]; /* local dir */ GLOBAL char remotecwd[MAXPATHLEN]; /* remote dir */ GLOBAL char *username; /* name of user logged in as. (dynamic) */ GLOBAL sa_family_t family; /* address family to use for connections */ GLOBAL const char *ftpport; /* port number to use for FTP connections */ GLOBAL const char *httpport; /* port number to use for HTTP connections */ GLOBAL const char *gateport; /* port number to use for gateftp connections */ GLOBAL struct addrinfo *bindai; /* local address to bind as */ GLOBAL char *outfile; /* filename to output URLs to */ GLOBAL int restartautofetch; /* restart auto-fetch */ GLOBAL char line[FTPBUFLEN]; /* input line buffer */ GLOBAL char *stringbase; /* current scan point in line buffer */ GLOBAL char argbuf[FTPBUFLEN]; /* argument storage buffer */ GLOBAL char *argbase; /* current storage point in arg buffer */ GLOBAL StringList *marg_sl; /* stringlist containing margv */ GLOBAL int margc; /* count of arguments on input line */ #define margv (marg_sl->sl_str) /* args parsed from input line */ GLOBAL int cpend; /* flag: if != 0, then pending server reply */ GLOBAL int mflag; /* flag: if != 0, then active multi command */ GLOBAL int options; /* used during socket creation */ GLOBAL int sndbuf_size; /* socket send buffer size */ GLOBAL int rcvbuf_size; /* socket receive buffer size */ +GLOBAL int auto_sndbuf; /* flag: if != 0 then use auto sndbuf size */ +GLOBAL int auto_rcvbuf; /* flag: if != 0 then use auto rcvbuf size */ GLOBAL int macnum; /* number of defined macros */ GLOBAL struct macel macros[16]; GLOBAL char macbuf[4096]; GLOBAL char *localhome; /* local home directory */ GLOBAL char *localname; /* local user name */ GLOBAL char netrc[MAXPATHLEN]; /* path to .netrc file */ GLOBAL char reply_string[BUFSIZ]; /* first line of previous reply */ GLOBAL void (*reply_callback)(const char *); /* * function to call for each line in * the server's reply except for the * first (`xxx-') and last (`xxx ') */ GLOBAL volatile sig_atomic_t sigint_raised; GLOBAL FILE *cin; GLOBAL FILE *cout; GLOBAL int data; extern struct cmd cmdtab[]; extern struct option optiontab[]; #define EMPTYSTRING(x) ((x) == NULL || (*(x) == '\0')) #define FREEPTR(x) if ((x) != NULL) { free(x); (x) = NULL; } #ifdef BSD4_4 # define HAVE_STRUCT_SOCKADDR_IN_SIN_LEN 1 #endif #ifdef NO_LONG_LONG # define STRTOLL(x,y,z) strtol(x,y,z) #else # define STRTOLL(x,y,z) strtoll(x,y,z) #endif #ifdef NO_DEBUG #define DPRINTF(...) #define DWARN(...) #else #define DPRINTF(...) if (ftp_debug) (void)fprintf(ttyout, __VA_ARGS__) #define DWARN(...) if (ftp_debug) warn(__VA_ARGS__) #endif #define STRorNULL(s) ((s) ? (s) : "") #ifdef NO_USAGE void xusage(void); #define UPRINTF(...) xusage() #else #define UPRINTF(...) (void)fprintf(ttyout, __VA_ARGS__) #endif Index: stable/12/contrib/tnftp/src/main.c =================================================================== --- stable/12/contrib/tnftp/src/main.c (revision 362507) +++ stable/12/contrib/tnftp/src/main.c (revision 362508) @@ -1,1058 +1,1068 @@ /* $NetBSD: main.c,v 1.17 2009/11/15 10:12:37 lukem Exp $ */ /* from NetBSD: main.c,v 1.117 2009/07/13 19:05:41 roy Exp */ /*- * Copyright (c) 1996-2009 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Luke Mewburn. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1985, 1989, 1993, 1994 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Copyright (C) 1997 and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "tnftp.h" #if 0 /* tnftp */ #include #ifndef lint __COPYRIGHT("@(#) Copyright (c) 1985, 1989, 1993, 1994\ The Regents of the University of California. All rights reserved.\ Copyright 1996-2008 The NetBSD Foundation, Inc. All rights reserved"); #endif /* not lint */ #ifndef lint #if 0 static char sccsid[] = "@(#)main.c 8.6 (Berkeley) 10/9/94"; #else __RCSID(" NetBSD: main.c,v 1.117 2009/07/13 19:05:41 roy Exp "); #endif #endif /* not lint */ /* * FTP User Program -- Command Interface. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #endif /* tnftp */ +#ifdef __FreeBSD__ +#include +#endif #define GLOBAL /* force GLOBAL decls in ftp_var.h to be declared */ #include "ftp_var.h" #define FTP_PROXY "ftp_proxy" /* env var with FTP proxy location */ #define HTTP_PROXY "http_proxy" /* env var with HTTP proxy location */ #define NO_PROXY "no_proxy" /* env var with list of non-proxied * hosts, comma or space separated */ static void setupoption(const char *, const char *, const char *); int main(int, char *[]); int main(int volatile argc, char **volatile argv) { int ch, rval; struct passwd *pw; char *cp, *ep, *anonpass, *upload_path, *src_addr; const char *anonuser; int dumbterm, isupload; size_t len; tzset(); #if 0 /* tnftp */ /* XXX */ setlocale(LC_ALL, ""); #endif /* tnftp */ setprogname(argv[0]); sigint_raised = 0; ftpport = "ftp"; httpport = "http"; gateport = NULL; cp = getenv("FTPSERVERPORT"); if (cp != NULL) gateport = cp; else gateport = "ftpgate"; doglob = 1; interactive = 1; autologin = 1; passivemode = 1; activefallback = 1; preserve = 1; verbose = 0; progress = 0; gatemode = 0; data = -1; outfile = NULL; restartautofetch = 0; #ifndef NO_EDITCOMPLETE editing = 0; el = NULL; hist = NULL; #endif bytes = 0; mark = HASHBYTES; rate_get = 0; rate_get_incr = DEFAULTINCR; rate_put = 0; rate_put_incr = DEFAULTINCR; #ifdef INET6 epsv4 = 1; epsv6 = 1; #else epsv4 = 0; epsv6 = 0; #endif epsv4bad = 0; epsv6bad = 0; src_addr = NULL; upload_path = NULL; isupload = 0; reply_callback = NULL; #ifdef INET6 family = AF_UNSPEC; #else family = AF_INET; /* force AF_INET if no INET6 support */ #endif netrc[0] = '\0'; cp = getenv("NETRC"); if (cp != NULL && strlcpy(netrc, cp, sizeof(netrc)) >= sizeof(netrc)) errx(1, "$NETRC `%s': %s", cp, strerror(ENAMETOOLONG)); marg_sl = ftp_sl_init(); if ((tmpdir = getenv("TMPDIR")) == NULL) tmpdir = _PATH_TMP; /* Set default operation mode based on FTPMODE environment variable */ if ((cp = getenv("FTPMODE")) != NULL) { if (strcasecmp(cp, "passive") == 0) { passivemode = 1; activefallback = 0; } else if (strcasecmp(cp, "active") == 0) { passivemode = 0; activefallback = 0; } else if (strcasecmp(cp, "gate") == 0) { gatemode = 1; } else if (strcasecmp(cp, "auto") == 0) { passivemode = 1; activefallback = 1; } else warnx("Unknown $FTPMODE `%s'; using defaults", cp); } if (strcmp(getprogname(), "pftp") == 0) { passivemode = 1; activefallback = 0; } else if (strcmp(getprogname(), "gate-ftp") == 0) gatemode = 1; gateserver = getenv("FTPSERVER"); if (gateserver == NULL || *gateserver == '\0') gateserver = GATE_SERVER; if (gatemode) { if (*gateserver == '\0') { warnx( "Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp"); gatemode = 0; } } cp = getenv("TERM"); if (cp == NULL || strcmp(cp, "dumb") == 0) dumbterm = 1; else dumbterm = 0; fromatty = isatty(fileno(stdin)); ttyout = stdout; if (isatty(fileno(ttyout))) { verbose = 1; /* verbose if to a tty */ if (! dumbterm) { #ifndef NO_EDITCOMPLETE if (fromatty) /* editing mode on if tty is usable */ editing = 1; #endif #ifndef NO_PROGRESS if (foregroundproc()) progress = 1; /* progress bar on if fg */ #endif } } while ((ch = getopt(argc, argv, "46AadefginN:o:pP:q:r:Rs:tT:u:vV")) != -1) { switch (ch) { case '4': family = AF_INET; break; case '6': #ifdef INET6 family = AF_INET6; #else warnx("INET6 support is not available; ignoring -6"); #endif break; case 'A': activefallback = 0; passivemode = 0; break; case 'a': anonftp = 1; break; case 'd': options |= SO_DEBUG; ftp_debug++; break; case 'e': #ifndef NO_EDITCOMPLETE editing = 0; #endif break; case 'f': flushcache = 1; break; case 'g': doglob = 0; break; case 'i': interactive = 0; break; case 'n': autologin = 0; break; case 'N': if (strlcpy(netrc, optarg, sizeof(netrc)) >= sizeof(netrc)) errx(1, "%s: %s", optarg, strerror(ENAMETOOLONG)); break; case 'o': outfile = optarg; if (strcmp(outfile, "-") == 0) ttyout = stderr; break; case 'p': passivemode = 1; activefallback = 0; break; case 'P': ftpport = optarg; break; case 'q': quit_time = strtol(optarg, &ep, 10); if (quit_time < 1 || *ep != '\0') errx(1, "Bad quit value: %s", optarg); break; case 'r': retry_connect = strtol(optarg, &ep, 10); if (retry_connect < 1 || *ep != '\0') errx(1, "Bad retry value: %s", optarg); break; case 'R': restartautofetch = 1; break; case 's': src_addr = optarg; break; case 't': trace = 1; break; case 'T': { int targc; char *targv[6], *oac; char cmdbuf[MAX_C_NAME]; /* look for `dir,max[,incr]' */ targc = 0; (void)strlcpy(cmdbuf, "-T", sizeof(cmdbuf)); targv[targc++] = cmdbuf; oac = ftp_strdup(optarg); while ((cp = strsep(&oac, ",")) != NULL) { if (*cp == '\0') { warnx("Bad throttle value `%s'", optarg); usage(); /* NOTREACHED */ } targv[targc++] = cp; if (targc >= 5) break; } if (parserate(targc, targv, 1) == -1) usage(); free(oac); break; } case 'u': { isupload = 1; interactive = 0; upload_path = ftp_strdup(optarg); break; } case 'v': progress = verbose = 1; break; case 'V': progress = verbose = 0; break; default: usage(); } } /* set line buffering on ttyout */ setvbuf(ttyout, NULL, _IOLBF, 0); argc -= optind; argv += optind; cpend = 0; /* no pending replies */ proxy = 0; /* proxy not active */ crflag = 1; /* strip c.r. on ascii gets */ sendport = -1; /* not using ports */ if (src_addr != NULL) { struct addrinfo hints; int error; memset(&hints, 0, sizeof(hints)); hints.ai_family = family; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; error = getaddrinfo(src_addr, NULL, &hints, &bindai); if (error) { errx(1, "Can't lookup `%s': %s", src_addr, (error == EAI_SYSTEM) ? strerror(errno) : gai_strerror(error)); } } /* * Cache the user name and home directory. */ localhome = NULL; localname = NULL; anonuser = "anonymous"; cp = getenv("HOME"); if (! EMPTYSTRING(cp)) localhome = ftp_strdup(cp); pw = NULL; cp = getlogin(); if (cp != NULL) pw = getpwnam(cp); if (pw == NULL) pw = getpwuid(getuid()); if (pw != NULL) { if (localhome == NULL && !EMPTYSTRING(pw->pw_dir)) localhome = ftp_strdup(pw->pw_dir); localname = ftp_strdup(pw->pw_name); anonuser = localname; } if (netrc[0] == '\0' && localhome != NULL) { if (strlcpy(netrc, localhome, sizeof(netrc)) >= sizeof(netrc) || strlcat(netrc, "/.netrc", sizeof(netrc)) >= sizeof(netrc)) { warnx("%s/.netrc: %s", localhome, strerror(ENAMETOOLONG)); netrc[0] = '\0'; } } if (localhome == NULL) localhome = ftp_strdup("/"); /* * Every anonymous FTP server I've encountered will accept the * string "username@", and will append the hostname itself. We * do this by default since many servers are picky about not * having a FQDN in the anonymous password. * - thorpej@NetBSD.org */ len = strlen(anonuser) + 2; anonpass = ftp_malloc(len); (void)strlcpy(anonpass, anonuser, len); (void)strlcat(anonpass, "@", len); /* * set all the defaults for options defined in * struct option optiontab[] declared in cmdtab.c */ setupoption("anonpass", getenv("FTPANONPASS"), anonpass); setupoption("ftp_proxy", getenv(FTP_PROXY), ""); setupoption("http_proxy", getenv(HTTP_PROXY), ""); setupoption("no_proxy", getenv(NO_PROXY), ""); setupoption("pager", getenv("PAGER"), DEFAULTPAGER); setupoption("prompt", getenv("FTPPROMPT"), DEFAULTPROMPT); setupoption("rprompt", getenv("FTPRPROMPT"), DEFAULTRPROMPT); free(anonpass); setttywidth(0); #ifdef SIGINFO (void)xsignal(SIGINFO, psummary); #endif (void)xsignal(SIGQUIT, psummary); (void)xsignal(SIGUSR1, crankrate); (void)xsignal(SIGUSR2, crankrate); (void)xsignal(SIGWINCH, setttywidth); + + auto_rcvbuf = ((sysctlbyname("net.inet.tcp.recvbuf_auto", + &auto_rcvbuf, &(size_t []){[0] = sizeof(int)}[0], NULL, 0) == 0) && + auto_rcvbuf == 1); + auto_sndbuf = ((sysctlbyname("net.inet.tcp.sendbuf_auto", + &auto_sndbuf, &(size_t []){[0] = sizeof(int)}[0], NULL, 0) == 0) && + auto_sndbuf == 1); if (argc > 0) { if (isupload) { rval = auto_put(argc, argv, upload_path); sigint_or_rval_exit: if (sigint_raised) { (void)xsignal(SIGINT, SIG_DFL); raise(SIGINT); } exit(rval); } else if (strchr(argv[0], ':') != NULL && ! isipv6addr(argv[0])) { rval = auto_fetch(argc, argv); if (rval >= 0) /* -1 == connected and cd-ed */ goto sigint_or_rval_exit; } else { char *xargv[4], *uuser, *host; char cmdbuf[MAXPATHLEN]; if ((rval = sigsetjmp(toplevel, 1))) goto sigint_or_rval_exit; (void)xsignal(SIGINT, intr); (void)xsignal(SIGPIPE, lostpeer); uuser = NULL; host = argv[0]; cp = strchr(host, '@'); if (cp) { *cp = '\0'; uuser = host; host = cp + 1; } (void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf)); xargv[0] = cmdbuf; xargv[1] = host; xargv[2] = argv[1]; xargv[3] = NULL; do { int oautologin; oautologin = autologin; if (uuser != NULL) { anonftp = 0; autologin = 0; } setpeer(argc+1, xargv); autologin = oautologin; if (connected == 1 && uuser != NULL) (void)ftp_login(host, uuser, NULL); if (!retry_connect) break; if (!connected) { macnum = 0; fprintf(ttyout, "Retrying in %d seconds...\n", retry_connect); sleep(retry_connect); } } while (!connected); retry_connect = 0; /* connected, stop hiding msgs */ } } if (isupload) usage(); #ifndef NO_EDITCOMPLETE controlediting(); #endif /* !NO_EDITCOMPLETE */ (void)sigsetjmp(toplevel, 1); (void)xsignal(SIGINT, intr); (void)xsignal(SIGPIPE, lostpeer); for (;;) cmdscanner(); } /* * Generate a prompt */ char * prompt(void) { static char **promptopt; static char buf[MAXPATHLEN]; if (promptopt == NULL) { struct option *o; o = getoption("prompt"); if (o == NULL) errx(1, "prompt: no such option `prompt'"); promptopt = &(o->value); } formatbuf(buf, sizeof(buf), *promptopt ? *promptopt : DEFAULTPROMPT); return (buf); } /* * Generate an rprompt */ char * rprompt(void) { static char **rpromptopt; static char buf[MAXPATHLEN]; if (rpromptopt == NULL) { struct option *o; o = getoption("rprompt"); if (o == NULL) errx(1, "rprompt: no such option `rprompt'"); rpromptopt = &(o->value); } formatbuf(buf, sizeof(buf), *rpromptopt ? *rpromptopt : DEFAULTRPROMPT); return (buf); } /* * Command parser. */ void cmdscanner(void) { struct cmd *c; char *p; #ifndef NO_EDITCOMPLETE int ch; size_t num; #endif int len; char cmdbuf[MAX_C_NAME]; for (;;) { #ifndef NO_EDITCOMPLETE if (!editing) { #endif /* !NO_EDITCOMPLETE */ if (fromatty) { fputs(prompt(), ttyout); p = rprompt(); if (*p) fprintf(ttyout, "%s ", p); } (void)fflush(ttyout); len = get_line(stdin, line, sizeof(line), NULL); switch (len) { case -1: /* EOF */ case -2: /* error */ if (fromatty) putc('\n', ttyout); quit(0, NULL); /* NOTREACHED */ case -3: /* too long; try again */ fputs("Sorry, input line is too long.\n", ttyout); continue; case 0: /* empty; try again */ continue; default: /* all ok */ break; } #ifndef NO_EDITCOMPLETE } else { const char *buf; HistEvent ev; cursor_pos = NULL; buf = el_gets(el, &ch); num = ch; if (buf == NULL || num == 0) { if (fromatty) putc('\n', ttyout); quit(0, NULL); } if (num >= sizeof(line)) { fputs("Sorry, input line is too long.\n", ttyout); break; } memcpy(line, buf, num); if (line[--num] == '\n') { line[num] = '\0'; if (num == 0) break; } history(hist, &ev, H_ENTER, buf); } #endif /* !NO_EDITCOMPLETE */ makeargv(); if (margc == 0) continue; c = getcmd(margv[0]); if (c == (struct cmd *)-1) { fputs("?Ambiguous command.\n", ttyout); continue; } if (c == NULL) { #if !defined(NO_EDITCOMPLETE) /* * attempt to el_parse() unknown commands. * any command containing a ':' would be parsed * as "[prog:]cmd ...", and will result in a * false positive if prog != "ftp", so treat * such commands as invalid. */ if (strchr(margv[0], ':') != NULL || !editing || el_parse(el, margc, (const char **)margv) != 0) #endif /* !NO_EDITCOMPLETE */ fputs("?Invalid command.\n", ttyout); continue; } if (c->c_conn && !connected) { fputs("Not connected.\n", ttyout); continue; } confirmrest = 0; (void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf)); margv[0] = cmdbuf; (*c->c_handler)(margc, margv); if (bell && c->c_bell) (void)putc('\007', ttyout); if (c->c_handler != help) break; } (void)xsignal(SIGINT, intr); (void)xsignal(SIGPIPE, lostpeer); } struct cmd * getcmd(const char *name) { const char *p, *q; struct cmd *c, *found; int nmatches, longest; if (name == NULL) return (0); longest = 0; nmatches = 0; found = 0; for (c = cmdtab; (p = c->c_name) != NULL; c++) { for (q = name; *q == *p++; q++) if (*q == 0) /* exact match? */ return (c); if (!*q) { /* the name was a prefix */ if (q - name > longest) { longest = q - name; nmatches = 1; found = c; } else if (q - name == longest) nmatches++; } } if (nmatches > 1) return ((struct cmd *)-1); return (found); } /* * Slice a string up into argc/argv. */ int slrflag; void makeargv(void) { char *argp; stringbase = line; /* scan from first of buffer */ argbase = argbuf; /* store from first of buffer */ slrflag = 0; marg_sl->sl_cur = 0; /* reset to start of marg_sl */ for (margc = 0; ; margc++) { argp = slurpstring(); ftp_sl_add(marg_sl, argp); if (argp == NULL) break; } #ifndef NO_EDITCOMPLETE if (cursor_pos == line) { cursor_argc = 0; cursor_argo = 0; } else if (cursor_pos != NULL) { cursor_argc = margc; cursor_argo = strlen(margv[margc-1]); } #endif /* !NO_EDITCOMPLETE */ } #ifdef NO_EDITCOMPLETE #define INC_CHKCURSOR(x) (x)++ #else /* !NO_EDITCOMPLETE */ #define INC_CHKCURSOR(x) { (x)++ ; \ if (x == cursor_pos) { \ cursor_argc = margc; \ cursor_argo = ap-argbase; \ cursor_pos = NULL; \ } } #endif /* !NO_EDITCOMPLETE */ /* * Parse string into argbuf; * implemented with FSM to * handle quoting and strings */ char * slurpstring(void) { static char bangstr[2] = { '!', '\0' }; static char dollarstr[2] = { '$', '\0' }; int got_one = 0; char *sb = stringbase; char *ap = argbase; char *tmp = argbase; /* will return this if token found */ if (*sb == '!' || *sb == '$') { /* recognize ! as a token for shell */ switch (slrflag) { /* and $ as token for macro invoke */ case 0: slrflag++; INC_CHKCURSOR(stringbase); return ((*sb == '!') ? bangstr : dollarstr); /* NOTREACHED */ case 1: slrflag++; altarg = stringbase; break; default: break; } } S0: switch (*sb) { case '\0': goto OUT; case ' ': case '\t': INC_CHKCURSOR(sb); goto S0; default: switch (slrflag) { case 0: slrflag++; break; case 1: slrflag++; altarg = sb; break; default: break; } goto S1; } S1: switch (*sb) { case ' ': case '\t': case '\0': goto OUT; /* end of token */ case '\\': INC_CHKCURSOR(sb); goto S2; /* slurp next character */ case '"': INC_CHKCURSOR(sb); goto S3; /* slurp quoted string */ default: *ap = *sb; /* add character to token */ ap++; INC_CHKCURSOR(sb); got_one = 1; goto S1; } S2: switch (*sb) { case '\0': goto OUT; default: *ap = *sb; ap++; INC_CHKCURSOR(sb); got_one = 1; goto S1; } S3: switch (*sb) { case '\0': goto OUT; case '"': INC_CHKCURSOR(sb); goto S1; default: *ap = *sb; ap++; INC_CHKCURSOR(sb); got_one = 1; goto S3; } OUT: if (got_one) *ap++ = '\0'; argbase = ap; /* update storage pointer */ stringbase = sb; /* update scan pointer */ if (got_one) { return (tmp); } switch (slrflag) { case 0: slrflag++; break; case 1: slrflag++; altarg = NULL; break; default: break; } return (NULL); } /* * Help/usage command. * Call each command handler with argc == 0 and argv[0] == name. */ void help(int argc, char *argv[]) { struct cmd *c; char *nargv[1], *cmd; const char *p; int isusage; cmd = argv[0]; isusage = (strcmp(cmd, "usage") == 0); if (argc == 0 || (isusage && argc == 1)) { UPRINTF("usage: %s [command [...]]\n", cmd); return; } if (argc == 1) { StringList *buf; buf = ftp_sl_init(); fprintf(ttyout, "%sommands may be abbreviated. Commands are:\n\n", proxy ? "Proxy c" : "C"); for (c = cmdtab; (p = c->c_name) != NULL; c++) if (!proxy || c->c_proxy) ftp_sl_add(buf, ftp_strdup(p)); list_vertical(buf); sl_free(buf, 1); return; } #define HELPINDENT ((int) sizeof("disconnect")) while (--argc > 0) { char *arg; char cmdbuf[MAX_C_NAME]; arg = *++argv; c = getcmd(arg); if (c == (struct cmd *)-1) fprintf(ttyout, "?Ambiguous %s command `%s'\n", cmd, arg); else if (c == NULL) fprintf(ttyout, "?Invalid %s command `%s'\n", cmd, arg); else { if (isusage) { (void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf)); nargv[0] = cmdbuf; (*c->c_handler)(0, nargv); } else fprintf(ttyout, "%-*s\t%s\n", HELPINDENT, c->c_name, c->c_help); } } } struct option * getoption(const char *name) { const char *p; struct option *c; if (name == NULL) return (NULL); for (c = optiontab; (p = c->name) != NULL; c++) { if (strcasecmp(p, name) == 0) return (c); } return (NULL); } char * getoptionvalue(const char *name) { struct option *c; if (name == NULL) errx(1, "getoptionvalue: invoked with NULL name"); c = getoption(name); if (c != NULL) return (c->value); errx(1, "getoptionvalue: invoked with unknown option `%s'", name); /* NOTREACHED */ } static void setupoption(const char *name, const char *value, const char *defaultvalue) { set_option(name, value ? value : defaultvalue, 0); } void usage(void) { const char *progname = getprogname(); (void)fprintf(stderr, "usage: %s [-46AadefginpRtVv] [-N netrc] [-o outfile] [-P port] [-q quittime]\n" " [-r retry] [-s srcaddr] [-T dir,max[,inc]]\n" " [[user@]host [port]] [host:path[/]] [file:///file]\n" " [ftp://[user[:pass]@]host[:port]/path[/]]\n" " [http://[user[:pass]@]host[:port]/path] [...]\n" " %s -u URL file [...]\n", progname, progname); exit(1); } Index: stable/12/contrib/tnftp/src/util.c =================================================================== --- stable/12/contrib/tnftp/src/util.c (revision 362507) +++ stable/12/contrib/tnftp/src/util.c (revision 362508) @@ -1,1580 +1,1594 @@ /* $NetBSD: util.c,v 1.21 2009/11/15 10:12:37 lukem Exp $ */ /* from NetBSD: util.c,v 1.152 2009/07/13 19:05:41 roy Exp */ /*- * Copyright (c) 1997-2009 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Luke Mewburn. * * This code is derived from software contributed to The NetBSD Foundation * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility, * NASA Ames Research Center. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1985, 1989, 1993, 1994 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "tnftp.h" #if 0 /* tnftp */ #include #ifndef lint __RCSID(" NetBSD: util.c,v 1.152 2009/07/13 19:05:41 roy Exp "); #endif /* not lint */ /* * FTP User Program -- Misc support routines */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #endif /* tnftp */ #include "ftp_var.h" /* * Connect to peer server and auto-login, if possible. */ void setpeer(int argc, char *argv[]) { char *host; const char *port; if (argc == 0) goto usage; if (connected) { fprintf(ttyout, "Already connected to %s, use close first.\n", hostname); code = -1; return; } if (argc < 2) (void)another(&argc, &argv, "to"); if (argc < 2 || argc > 3) { usage: UPRINTF("usage: %s host-name [port]\n", argv[0]); code = -1; return; } if (gatemode) port = gateport; else port = ftpport; if (argc > 2) port = argv[2]; if (gatemode) { if (gateserver == NULL || *gateserver == '\0') errx(1, "main: gateserver not defined"); host = hookup(gateserver, port); } else host = hookup(argv[1], port); if (host) { if (gatemode && verbose) { fprintf(ttyout, "Connecting via pass-through server %s\n", gateserver); } connected = 1; /* * Set up defaults for FTP. */ (void)strlcpy(typename, "ascii", sizeof(typename)); type = TYPE_A; curtype = TYPE_A; (void)strlcpy(formname, "non-print", sizeof(formname)); form = FORM_N; (void)strlcpy(modename, "stream", sizeof(modename)); mode = MODE_S; (void)strlcpy(structname, "file", sizeof(structname)); stru = STRU_F; (void)strlcpy(bytename, "8", sizeof(bytename)); bytesize = 8; if (autologin) (void)ftp_login(argv[1], NULL, NULL); } } static void parse_feat(const char *fline) { /* * work-around broken ProFTPd servers that can't * even obey RFC2389. */ while (*fline && isspace((int)*fline)) fline++; if (strcasecmp(fline, "MDTM") == 0) features[FEAT_MDTM] = 1; else if (strncasecmp(fline, "MLST", sizeof("MLST") - 1) == 0) { features[FEAT_MLST] = 1; } else if (strcasecmp(fline, "REST STREAM") == 0) features[FEAT_REST_STREAM] = 1; else if (strcasecmp(fline, "SIZE") == 0) features[FEAT_SIZE] = 1; else if (strcasecmp(fline, "TVFS") == 0) features[FEAT_TVFS] = 1; } /* * Determine the remote system type (SYST) and features (FEAT). * Call after a successful login (i.e, connected = -1) */ void getremoteinfo(void) { int overbose, i; overbose = verbose; if (ftp_debug == 0) verbose = -1; /* determine remote system type */ if (command("SYST") == COMPLETE) { if (overbose) { char *cp, c; c = 0; cp = strchr(reply_string + 4, ' '); if (cp == NULL) cp = strchr(reply_string + 4, '\r'); if (cp) { if (cp[-1] == '.') cp--; c = *cp; *cp = '\0'; } fprintf(ttyout, "Remote system type is %s.\n", reply_string + 4); if (cp) *cp = c; } if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) { if (proxy) unix_proxy = 1; else unix_server = 1; /* * Set type to 0 (not specified by user), * meaning binary by default, but don't bother * telling server. We can use binary * for text files unless changed by the user. */ type = 0; (void)strlcpy(typename, "binary", sizeof(typename)); if (overbose) fprintf(ttyout, "Using %s mode to transfer files.\n", typename); } else { if (proxy) unix_proxy = 0; else unix_server = 0; if (overbose && !strncmp(reply_string, "215 TOPS20", 10)) fputs( "Remember to set tenex mode when transferring binary files from this machine.\n", ttyout); } } /* determine features (if any) */ for (i = 0; i < FEAT_max; i++) features[i] = -1; reply_callback = parse_feat; if (command("FEAT") == COMPLETE) { for (i = 0; i < FEAT_max; i++) { if (features[i] == -1) features[i] = 0; } features[FEAT_FEAT] = 1; } else features[FEAT_FEAT] = 0; #ifndef NO_DEBUG if (ftp_debug) { #define DEBUG_FEAT(x) fprintf(ttyout, "features[" #x "] = %d\n", features[(x)]) DEBUG_FEAT(FEAT_FEAT); DEBUG_FEAT(FEAT_MDTM); DEBUG_FEAT(FEAT_MLST); DEBUG_FEAT(FEAT_REST_STREAM); DEBUG_FEAT(FEAT_SIZE); DEBUG_FEAT(FEAT_TVFS); #undef DEBUG_FEAT } #endif reply_callback = NULL; verbose = overbose; } /* * Reset the various variables that indicate connection state back to * disconnected settings. * The caller is responsible for issuing any commands to the remote server * to perform a clean shutdown before this is invoked. */ void cleanuppeer(void) { if (cout) (void)fclose(cout); cout = NULL; connected = 0; unix_server = 0; unix_proxy = 0; /* * determine if anonftp was specifically set with -a * (1), or implicitly set by auto_fetch() (2). in the * latter case, disable after the current xfer */ if (anonftp == 2) anonftp = 0; data = -1; epsv4bad = 0; epsv6bad = 0; if (username) free(username); username = NULL; if (!proxy) macnum = 0; } /* * Top-level signal handler for interrupted commands. */ void intr(int signo) { sigint_raised = 1; alarmtimer(0); if (fromatty) write(fileno(ttyout), "\n", 1); siglongjmp(toplevel, 1); } /* * Signal handler for lost connections; cleanup various elements of * the connection state, and call cleanuppeer() to finish it off. */ void lostpeer(int dummy) { int oerrno = errno; alarmtimer(0); if (connected) { if (cout != NULL) { (void)shutdown(fileno(cout), 1+1); (void)fclose(cout); cout = NULL; } if (data >= 0) { (void)shutdown(data, 1+1); (void)close(data); data = -1; } connected = 0; } pswitch(1); if (connected) { if (cout != NULL) { (void)shutdown(fileno(cout), 1+1); (void)fclose(cout); cout = NULL; } connected = 0; } proxflag = 0; pswitch(0); cleanuppeer(); errno = oerrno; } /* * Login to remote host, using given username & password if supplied. * Return non-zero if successful. */ int ftp_login(const char *host, const char *luser, const char *lpass) { char tmp[80]; char *fuser, *pass, *facct, *p; char emptypass[] = ""; const char *errormsg; int n, aflag, rval, nlen; aflag = rval = 0; fuser = pass = facct = NULL; if (luser) fuser = ftp_strdup(luser); if (lpass) pass = ftp_strdup(lpass); DPRINTF("ftp_login: user `%s' pass `%s' host `%s'\n", STRorNULL(fuser), STRorNULL(pass), STRorNULL(host)); /* * Set up arguments for an anonymous FTP session, if necessary. */ if (anonftp) { FREEPTR(fuser); fuser = ftp_strdup("anonymous"); /* as per RFC1635 */ FREEPTR(pass); pass = ftp_strdup(getoptionvalue("anonpass")); } if (ruserpass(host, &fuser, &pass, &facct) < 0) { code = -1; goto cleanup_ftp_login; } while (fuser == NULL) { if (localname) fprintf(ttyout, "Name (%s:%s): ", host, localname); else fprintf(ttyout, "Name (%s): ", host); errormsg = NULL; nlen = get_line(stdin, tmp, sizeof(tmp), &errormsg); if (nlen < 0) { fprintf(ttyout, "%s; %s aborted.\n", errormsg, "login"); code = -1; goto cleanup_ftp_login; } else if (nlen == 0) { fuser = ftp_strdup(localname); } else { fuser = ftp_strdup(tmp); } } if (gatemode) { char *nuser; size_t len; len = strlen(fuser) + 1 + strlen(host) + 1; nuser = ftp_malloc(len); (void)strlcpy(nuser, fuser, len); (void)strlcat(nuser, "@", len); (void)strlcat(nuser, host, len); FREEPTR(fuser); fuser = nuser; } n = command("USER %s", fuser); if (n == CONTINUE) { if (pass == NULL) { p = getpass("Password: "); if (p == NULL) p = emptypass; pass = ftp_strdup(p); memset(p, 0, strlen(p)); } n = command("PASS %s", pass); memset(pass, 0, strlen(pass)); } if (n == CONTINUE) { aflag++; if (facct == NULL) { p = getpass("Account: "); if (p == NULL) p = emptypass; facct = ftp_strdup(p); memset(p, 0, strlen(p)); } if (facct[0] == '\0') { warnx("Login failed"); goto cleanup_ftp_login; } n = command("ACCT %s", facct); memset(facct, 0, strlen(facct)); } if ((n != COMPLETE) || (!aflag && facct != NULL && command("ACCT %s", facct) != COMPLETE)) { warnx("Login failed"); goto cleanup_ftp_login; } rval = 1; username = ftp_strdup(fuser); if (proxy) goto cleanup_ftp_login; connected = -1; getremoteinfo(); for (n = 0; n < macnum; ++n) { if (!strcmp("init", macros[n].mac_name)) { (void)strlcpy(line, "$init", sizeof(line)); makeargv(); domacro(margc, margv); break; } } updatelocalcwd(); updateremotecwd(); cleanup_ftp_login: FREEPTR(fuser); if (pass != NULL) memset(pass, 0, strlen(pass)); FREEPTR(pass); if (facct != NULL) memset(facct, 0, strlen(facct)); FREEPTR(facct); return (rval); } /* * `another' gets another argument, and stores the new argc and argv. * It reverts to the top level (via intr()) on EOF/error. * * Returns false if no new arguments have been added. */ int another(int *pargc, char ***pargv, const char *aprompt) { const char *errormsg; int ret, nlen; size_t len; len = strlen(line); if (len >= sizeof(line) - 3) { fputs("Sorry, arguments too long.\n", ttyout); intr(0); } fprintf(ttyout, "(%s) ", aprompt); line[len++] = ' '; errormsg = NULL; nlen = get_line(stdin, line + len, sizeof(line)-len, &errormsg); if (nlen < 0) { fprintf(ttyout, "%s; %s aborted.\n", errormsg, "operation"); intr(0); } len += nlen; makeargv(); ret = margc > *pargc; *pargc = margc; *pargv = margv; return (ret); } /* * glob files given in argv[] from the remote server. * if errbuf isn't NULL, store error messages there instead * of writing to the screen. */ char * remglob(char *argv[], int doswitch, const char **errbuf) { static char buf[MAXPATHLEN]; static FILE *ftemp = NULL; static char **args; char temp[MAXPATHLEN]; int oldverbose, oldhash, oldprogress, fd; char *cp; const char *rmode; size_t len; if (!mflag || !connected) { if (!doglob) args = NULL; else { if (ftemp) { (void)fclose(ftemp); ftemp = NULL; } } return (NULL); } if (!doglob) { if (args == NULL) args = argv; if ((cp = *++args) == NULL) args = NULL; return (cp); } if (ftemp == NULL) { len = strlcpy(temp, tmpdir, sizeof(temp)); if (temp[len - 1] != '/') (void)strlcat(temp, "/", sizeof(temp)); (void)strlcat(temp, TMPFILE, sizeof(temp)); if ((fd = mkstemp(temp)) < 0) { warn("Unable to create temporary file `%s'", temp); return (NULL); } close(fd); oldverbose = verbose; verbose = (errbuf != NULL) ? -1 : 0; oldhash = hash; oldprogress = progress; hash = 0; progress = 0; if (doswitch) pswitch(!proxy); for (rmode = "w"; *++argv != NULL; rmode = "a") recvrequest("NLST", temp, *argv, rmode, 0, 0); if ((code / 100) != COMPLETE) { if (errbuf != NULL) *errbuf = reply_string; } if (doswitch) pswitch(!proxy); verbose = oldverbose; hash = oldhash; progress = oldprogress; ftemp = fopen(temp, "r"); (void)unlink(temp); if (ftemp == NULL) { if (errbuf == NULL) warnx("Can't find list of remote files"); else *errbuf = "Can't find list of remote files"; return (NULL); } } if (fgets(buf, sizeof(buf), ftemp) == NULL) { (void)fclose(ftemp); ftemp = NULL; return (NULL); } if ((cp = strchr(buf, '\n')) != NULL) *cp = '\0'; return (buf); } /* * Glob a local file name specification with the expectation of a single * return value. Can't control multiple values being expanded from the * expression, we return only the first. * Returns NULL on error, or a pointer to a buffer containing the filename * that's the caller's responsiblity to free(3) when finished with. */ char * globulize(const char *pattern) { glob_t gl; int flags; char *p; if (!doglob) return (ftp_strdup(pattern)); flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE; memset(&gl, 0, sizeof(gl)); if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) { warnx("Glob pattern `%s' not found", pattern); globfree(&gl); return (NULL); } p = ftp_strdup(gl.gl_pathv[0]); globfree(&gl); return (p); } /* * determine size of remote file */ off_t remotesize(const char *file, int noisy) { int overbose, r; off_t size; overbose = verbose; size = -1; if (ftp_debug == 0) verbose = -1; if (! features[FEAT_SIZE]) { if (noisy) fprintf(ttyout, "SIZE is not supported by remote server.\n"); goto cleanup_remotesize; } r = command("SIZE %s", file); if (r == COMPLETE) { char *cp, *ep; cp = strchr(reply_string, ' '); if (cp != NULL) { cp++; size = STRTOLL(cp, &ep, 10); if (*ep != '\0' && !isspace((unsigned char)*ep)) size = -1; } } else { if (r == ERROR && code == 500 && features[FEAT_SIZE] == -1) features[FEAT_SIZE] = 0; if (noisy && ftp_debug == 0) { fputs(reply_string, ttyout); putc('\n', ttyout); } } cleanup_remotesize: verbose = overbose; return (size); } /* * determine last modification time (in GMT) of remote file */ time_t remotemodtime(const char *file, int noisy) { int overbose, ocode, r; time_t rtime; overbose = verbose; ocode = code; rtime = -1; if (ftp_debug == 0) verbose = -1; if (! features[FEAT_MDTM]) { if (noisy) fprintf(ttyout, "MDTM is not supported by remote server.\n"); goto cleanup_parse_time; } r = command("MDTM %s", file); if (r == COMPLETE) { struct tm timebuf; char *timestr, *frac; /* * time-val = 14DIGIT [ "." 1*DIGIT ] * YYYYMMDDHHMMSS[.sss] * mdtm-response = "213" SP time-val CRLF / error-response */ timestr = reply_string + 4; /* * parse fraction. * XXX: ignored for now */ frac = strchr(timestr, '\r'); if (frac != NULL) *frac = '\0'; frac = strchr(timestr, '.'); if (frac != NULL) *frac++ = '\0'; if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) { /* * XXX: Workaround for lame ftpd's that return * `19100' instead of `2000' */ fprintf(ttyout, "Y2K warning! Incorrect time-val `%s' received from server.\n", timestr); timestr++; timestr[0] = '2'; timestr[1] = '0'; fprintf(ttyout, "Converted to `%s'\n", timestr); } memset(&timebuf, 0, sizeof(timebuf)); if (strlen(timestr) != 14 || (strptime(timestr, "%Y%m%d%H%M%S", &timebuf) == NULL)) { bad_parse_time: fprintf(ttyout, "Can't parse time `%s'.\n", timestr); goto cleanup_parse_time; } timebuf.tm_isdst = -1; rtime = timegm(&timebuf); if (rtime == -1) { if (noisy || ftp_debug != 0) goto bad_parse_time; else goto cleanup_parse_time; } else { DPRINTF("remotemodtime: parsed date `%s' as " LLF ", %s", timestr, (LLT)rtime, rfc2822time(localtime(&rtime))); } } else { if (r == ERROR && code == 500 && features[FEAT_MDTM] == -1) features[FEAT_MDTM] = 0; if (noisy && ftp_debug == 0) { fputs(reply_string, ttyout); putc('\n', ttyout); } } cleanup_parse_time: verbose = overbose; if (rtime == -1) code = ocode; return (rtime); } /* * Format tm in an RFC2822 compatible manner, with a trailing \n. * Returns a pointer to a static string containing the result. */ const char * rfc2822time(const struct tm *tm) { static char result[50]; if (strftime(result, sizeof(result), "%a, %d %b %Y %H:%M:%S %z\n", tm) == 0) errx(1, "Can't convert RFC2822 time: buffer too small"); return result; } /* * Update global `localcwd', which contains the state of the local cwd */ void updatelocalcwd(void) { if (getcwd(localcwd, sizeof(localcwd)) == NULL) localcwd[0] = '\0'; DPRINTF("updatelocalcwd: got `%s'\n", localcwd); } /* * Update global `remotecwd', which contains the state of the remote cwd */ void updateremotecwd(void) { int overbose, ocode; size_t i; char *cp; overbose = verbose; ocode = code; if (ftp_debug == 0) verbose = -1; if (command("PWD") != COMPLETE) goto badremotecwd; cp = strchr(reply_string, ' '); if (cp == NULL || cp[0] == '\0' || cp[1] != '"') goto badremotecwd; cp += 2; for (i = 0; *cp && i < sizeof(remotecwd) - 1; i++, cp++) { if (cp[0] == '"') { if (cp[1] == '"') cp++; else break; } remotecwd[i] = *cp; } remotecwd[i] = '\0'; DPRINTF("updateremotecwd: got `%s'\n", remotecwd); goto cleanupremotecwd; badremotecwd: remotecwd[0]='\0'; cleanupremotecwd: verbose = overbose; code = ocode; } /* * Ensure file is in or under dir. * Returns 1 if so, 0 if not (or an error occurred). */ int fileindir(const char *file, const char *dir) { char parentdirbuf[PATH_MAX+1], *parentdir; char realdir[PATH_MAX+1]; size_t dirlen; /* determine parent directory of file */ (void)strlcpy(parentdirbuf, file, sizeof(parentdirbuf)); parentdir = dirname(parentdirbuf); if (strcmp(parentdir, ".") == 0) return 1; /* current directory is ok */ /* find the directory */ if (realpath(parentdir, realdir) == NULL) { warn("Unable to determine real path of `%s'", parentdir); return 0; } if (realdir[0] != '/') /* relative result is ok */ return 1; dirlen = strlen(dir); if (strncmp(realdir, dir, dirlen) == 0 && (realdir[dirlen] == '/' || realdir[dirlen] == '\0')) return 1; return 0; } /* * List words in stringlist, vertically arranged */ void list_vertical(StringList *sl) { size_t i, j; size_t columns, lines; char *p; size_t w, width; width = 0; for (i = 0 ; i < sl->sl_cur ; i++) { w = strlen(sl->sl_str[i]); if (w > width) width = w; } width = (width + 8) &~ 7; columns = ttywidth / width; if (columns == 0) columns = 1; lines = (sl->sl_cur + columns - 1) / columns; for (i = 0; i < lines; i++) { for (j = 0; j < columns; j++) { p = sl->sl_str[j * lines + i]; if (p) fputs(p, ttyout); if (j * lines + i + lines >= sl->sl_cur) { putc('\n', ttyout); break; } if (p) { w = strlen(p); while (w < width) { w = (w + 8) &~ 7; (void)putc('\t', ttyout); } } } } } /* * Update the global ttywidth value, using TIOCGWINSZ. */ void setttywidth(int a) { struct winsize winsize; int oerrno = errno; if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 && winsize.ws_col != 0) ttywidth = winsize.ws_col; else ttywidth = 80; errno = oerrno; } /* * Change the rate limit up (SIGUSR1) or down (SIGUSR2) */ void crankrate(int sig) { switch (sig) { case SIGUSR1: if (rate_get) rate_get += rate_get_incr; if (rate_put) rate_put += rate_put_incr; break; case SIGUSR2: if (rate_get && rate_get > rate_get_incr) rate_get -= rate_get_incr; if (rate_put && rate_put > rate_put_incr) rate_put -= rate_put_incr; break; default: err(1, "crankrate invoked with unknown signal: %d", sig); } } /* * Setup or cleanup EditLine structures */ #ifndef NO_EDITCOMPLETE void controlediting(void) { if (editing && el == NULL && hist == NULL) { HistEvent ev; int editmode; el = el_init(getprogname(), stdin, ttyout, stderr); /* init editline */ hist = history_init(); /* init the builtin history */ history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */ el_set(el, EL_HIST, history, hist); /* use history */ el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */ el_set(el, EL_PROMPT, prompt); /* set the prompt functions */ el_set(el, EL_RPROMPT, rprompt); /* add local file completion, bind to TAB */ el_set(el, EL_ADDFN, "ftp-complete", "Context sensitive argument completion", complete); el_set(el, EL_BIND, "^I", "ftp-complete", NULL); el_source(el, NULL); /* read ~/.editrc */ if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0) editing = 0; /* the user doesn't want editing, * so disable, and let statement * below cleanup */ else el_set(el, EL_SIGNAL, 1); } if (!editing) { if (hist) { history_end(hist); hist = NULL; } if (el) { el_end(el); el = NULL; } } } #endif /* !NO_EDITCOMPLETE */ /* * Convert the string `arg' to an int, which may have an optional SI suffix * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise. */ int strsuftoi(const char *arg) { char *cp; long val; if (!isdigit((unsigned char)arg[0])) return (-1); val = strtol(arg, &cp, 10); if (cp != NULL) { if (cp[0] != '\0' && cp[1] != '\0') return (-1); switch (tolower((unsigned char)cp[0])) { case '\0': case 'b': break; case 'k': val <<= 10; break; case 'm': val <<= 20; break; case 'g': val <<= 30; break; default: return (-1); } } if (val < 0 || val > INT_MAX) return (-1); return (val); } /* * Set up socket buffer sizes before a connection is made. */ void setupsockbufsize(int sock) { socklen_t slen; if (0 == rcvbuf_size) { slen = sizeof(rcvbuf_size); if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbuf_size, &slen) == -1) err(1, "Unable to determine rcvbuf size"); if (rcvbuf_size <= 0) rcvbuf_size = 8 * 1024; if (rcvbuf_size > 8 * 1024 * 1024) rcvbuf_size = 8 * 1024 * 1024; DPRINTF("setupsockbufsize: rcvbuf_size determined as %d\n", rcvbuf_size); } if (0 == sndbuf_size) { slen = sizeof(sndbuf_size); if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *)&sndbuf_size, &slen) == -1) err(1, "Unable to determine sndbuf size"); if (sndbuf_size <= 0) sndbuf_size = 8 * 1024; if (sndbuf_size > 8 * 1024 * 1024) sndbuf_size = 8 * 1024 * 1024; DPRINTF("setupsockbufsize: sndbuf_size determined as %d\n", sndbuf_size); } +#ifdef __FreeBSD__ + DPRINTF("auto_rcvbuf = %d\n", auto_rcvbuf); + if (auto_sndbuf == 0) { +#endif if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *)&sndbuf_size, sizeof(sndbuf_size)) == -1) warn("Unable to set sndbuf size %d", sndbuf_size); +#ifdef __FreeBSD__ + } +#endif +#ifdef __FreeBSD__ + DPRINTF("auto_sndbuf = %d\n", auto_sndbuf); + if (auto_rcvbuf == 0) { +#endif if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbuf_size, sizeof(rcvbuf_size)) == -1) warn("Unable to set rcvbuf size %d", rcvbuf_size); +#ifdef __FreeBSD__ + } +#endif } /* * Copy characters from src into dst, \ quoting characters that require it */ void ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen) { size_t di, si; for (di = si = 0; src[si] != '\0' && di < dstlen && si < srclen; di++, si++) { switch (src[si]) { case '\\': case ' ': case '\t': case '\r': case '\n': case '"': dst[di++] = '\\'; if (di >= dstlen) break; /* FALLTHROUGH */ default: dst[di] = src[si]; } } dst[di] = '\0'; } /* * Copy src into buf (which is len bytes long), expanding % sequences. */ void formatbuf(char *buf, size_t len, const char *src) { const char *p, *p2, *q; size_t i; int op, updirs, pdirs; #define ADDBUF(x) do { \ if (i >= len - 1) \ goto endbuf; \ buf[i++] = (x); \ } while (0) p = src; for (i = 0; *p; p++) { if (*p != '%') { ADDBUF(*p); continue; } p++; switch (op = *p) { case '/': case '.': case 'c': p2 = connected ? remotecwd : ""; updirs = pdirs = 0; /* option to determine fixed # of dirs from path */ if (op == '.' || op == 'c') { int skip; q = p2; while (*p2) /* calc # of /'s */ if (*p2++ == '/') updirs++; if (p[1] == '0') { /* print or ... */ pdirs = 1; p++; } if (p[1] >= '1' && p[1] <= '9') { /* calc # to skip */ skip = p[1] - '0'; p++; } else skip = 1; updirs -= skip; while (skip-- > 0) { while ((p2 > q) && (*p2 != '/')) p2--; /* back up */ if (skip && p2 > q) p2--; } if (*p2 == '/' && p2 != q) p2++; } if (updirs > 0 && pdirs) { if (i >= len - 5) break; if (op == '.') { ADDBUF('.'); ADDBUF('.'); ADDBUF('.'); } else { ADDBUF('/'); ADDBUF('<'); if (updirs > 9) { ADDBUF('9'); ADDBUF('+'); } else ADDBUF('0' + updirs); ADDBUF('>'); } } for (; *p2; p2++) ADDBUF(*p2); break; case 'M': case 'm': for (p2 = connected && hostname ? hostname : "-"; *p2 ; p2++) { if (op == 'm' && *p2 == '.') break; ADDBUF(*p2); } break; case 'n': for (p2 = connected ? username : "-"; *p2 ; p2++) ADDBUF(*p2); break; case '%': ADDBUF('%'); break; default: /* display unknown codes literally */ ADDBUF('%'); ADDBUF(op); break; } } endbuf: buf[i] = '\0'; } /* * Determine if given string is an IPv6 address or not. * Return 1 for yes, 0 for no */ int isipv6addr(const char *addr) { int rv = 0; #ifdef INET6 struct addrinfo hints, *res; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET6; hints.ai_socktype = SOCK_DGRAM; /*dummy*/ hints.ai_flags = AI_NUMERICHOST; if (getaddrinfo(addr, "0", &hints, &res) != 0) rv = 0; else { rv = 1; freeaddrinfo(res); } DPRINTF("isipv6addr: got %d for %s\n", rv, addr); #endif return (rv == 1) ? 1 : 0; } /* * Read a line from the FILE stream into buf/buflen using fgets(), so up * to buflen-1 chars will be read and the result will be NUL terminated. * If the line has a trailing newline it will be removed. * If the line is too long, excess characters will be read until * newline/EOF/error. * If EOF/error occurs or a too-long line is encountered and errormsg * isn't NULL, it will be changed to a description of the problem. * (The EOF message has a leading \n for cosmetic purposes). * Returns: * >=0 length of line (excluding trailing newline) if all ok * -1 error occurred * -2 EOF encountered * -3 line was too long */ int get_line(FILE *stream, char *buf, size_t buflen, const char **errormsg) { int rv, ch; size_t len; if (fgets(buf, buflen, stream) == NULL) { if (feof(stream)) { /* EOF */ rv = -2; if (errormsg) *errormsg = "\nEOF received"; } else { /* error */ rv = -1; if (errormsg) *errormsg = "Error encountered"; } clearerr(stream); return rv; } len = strlen(buf); if (buf[len-1] == '\n') { /* clear any trailing newline */ buf[--len] = '\0'; } else if (len == buflen-1) { /* line too long */ while ((ch = getchar()) != '\n' && ch != EOF) continue; if (errormsg) *errormsg = "Input line is too long"; clearerr(stream); return -3; } if (errormsg) *errormsg = NULL; return len; } /* * Internal version of connect(2); sets socket buffer sizes, * binds to a specific local address (if set), and * supports a connection timeout using a non-blocking connect(2) with * a poll(2). * Socket fcntl flags are temporarily updated to include O_NONBLOCK; * these will not be reverted on connection failure. * Returns 0 on success, or -1 upon failure (with an appropriate * error message displayed.) */ int ftp_connect(int sock, const struct sockaddr *name, socklen_t namelen) { int flags, rv, timeout, error; socklen_t slen; struct timeval endtime, now, td; struct pollfd pfd[1]; char hname[NI_MAXHOST]; char sname[NI_MAXSERV]; setupsockbufsize(sock); if (getnameinfo(name, namelen, hname, sizeof(hname), sname, sizeof(sname), NI_NUMERICHOST | NI_NUMERICSERV) != 0) { strlcpy(hname, "?", sizeof(hname)); strlcpy(sname, "?", sizeof(sname)); } if (bindai != NULL) { /* bind to specific addr */ struct addrinfo *ai; for (ai = bindai; ai != NULL; ai = ai->ai_next) { if (ai->ai_family == name->sa_family) break; } if (ai == NULL) ai = bindai; if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) { char bname[NI_MAXHOST]; int saveerr; saveerr = errno; if (getnameinfo(ai->ai_addr, ai->ai_addrlen, bname, sizeof(bname), NULL, 0, NI_NUMERICHOST) != 0) strlcpy(bname, "?", sizeof(bname)); errno = saveerr; warn("Can't bind to `%s'", bname); return -1; } } /* save current socket flags */ if ((flags = fcntl(sock, F_GETFL, 0)) == -1) { warn("Can't %s socket flags for connect to `%s:%s'", "save", hname, sname); return -1; } /* set non-blocking connect */ if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1) { warn("Can't set socket non-blocking for connect to `%s:%s'", hname, sname); return -1; } /* NOTE: we now must restore socket flags on successful exit */ pfd[0].fd = sock; pfd[0].events = POLLIN|POLLOUT; if (quit_time > 0) { /* want a non default timeout */ (void)gettimeofday(&endtime, NULL); endtime.tv_sec += quit_time; /* determine end time */ } rv = connect(sock, name, namelen); /* inititate the connection */ if (rv == -1) { /* connection error */ if (errno != EINPROGRESS) { /* error isn't "please wait" */ connecterror: warn("Can't connect to `%s:%s'", hname, sname); return -1; } /* connect EINPROGRESS; wait */ do { if (quit_time > 0) { /* determine timeout */ (void)gettimeofday(&now, NULL); timersub(&endtime, &now, &td); timeout = td.tv_sec * 1000 + td.tv_usec/1000; if (timeout < 0) timeout = 0; } else { timeout = INFTIM; } pfd[0].revents = 0; rv = ftp_poll(pfd, 1, timeout); /* loop until poll ! EINTR */ } while (rv == -1 && errno == EINTR); if (rv == 0) { /* poll (connect) timed out */ errno = ETIMEDOUT; goto connecterror; } if (rv == -1) { /* poll error */ goto connecterror; } else if (pfd[0].revents & (POLLIN|POLLOUT)) { slen = sizeof(error); /* OK, or pending error */ if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &slen) == -1) { /* Solaris pending error */ goto connecterror; } else if (error != 0) { errno = error; /* BSD pending error */ goto connecterror; } } else { errno = EBADF; /* this shouldn't happen ... */ goto connecterror; } } if (fcntl(sock, F_SETFL, flags) == -1) { /* restore socket flags */ warn("Can't %s socket flags for connect to `%s:%s'", "restore", hname, sname); return -1; } return 0; } /* * Internal version of listen(2); sets socket buffer sizes first. */ int ftp_listen(int sock, int backlog) { setupsockbufsize(sock); return (listen(sock, backlog)); } /* * Internal version of poll(2), to allow reimplementation by select(2) * on platforms without the former. */ int ftp_poll(struct pollfd *fds, int nfds, int timeout) { #if defined(HAVE_POLL) return poll(fds, nfds, timeout); #elif defined(HAVE_SELECT) /* implement poll(2) using select(2) */ fd_set rset, wset, xset; const int rsetflags = POLLIN | POLLRDNORM; const int wsetflags = POLLOUT | POLLWRNORM; const int xsetflags = POLLRDBAND; struct timeval tv, *ptv; int i, max, rv; FD_ZERO(&rset); /* build list of read & write events */ FD_ZERO(&wset); FD_ZERO(&xset); max = 0; for (i = 0; i < nfds; i++) { if (fds[i].fd > FD_SETSIZE) { warnx("can't select fd %d", fds[i].fd); errno = EINVAL; return -1; } else if (fds[i].fd > max) max = fds[i].fd; if (fds[i].events & rsetflags) FD_SET(fds[i].fd, &rset); if (fds[i].events & wsetflags) FD_SET(fds[i].fd, &wset); if (fds[i].events & xsetflags) FD_SET(fds[i].fd, &xset); } ptv = &tv; /* determine timeout */ if (timeout == -1) { /* wait forever */ ptv = NULL; } else if (timeout == 0) { /* poll once */ ptv->tv_sec = 0; ptv->tv_usec = 0; } else if (timeout != 0) { /* wait timeout milliseconds */ ptv->tv_sec = timeout / 1000; ptv->tv_usec = (timeout % 1000) * 1000; } rv = select(max + 1, &rset, &wset, &xset, ptv); if (rv <= 0) /* -1 == error, 0 == timeout */ return rv; for (i = 0; i < nfds; i++) { /* determine results */ if (FD_ISSET(fds[i].fd, &rset)) fds[i].revents |= (fds[i].events & rsetflags); if (FD_ISSET(fds[i].fd, &wset)) fds[i].revents |= (fds[i].events & wsetflags); if (FD_ISSET(fds[i].fd, &xset)) fds[i].revents |= (fds[i].events & xsetflags); } return rv; #else # error no way to implement xpoll #endif } /* * malloc() with inbuilt error checking */ void * ftp_malloc(size_t size) { void *p; p = malloc(size); if (p == NULL) err(1, "Unable to allocate %ld bytes of memory", (long)size); return (p); } /* * sl_init() with inbuilt error checking */ StringList * ftp_sl_init(void) { StringList *p; p = sl_init(); if (p == NULL) err(1, "Unable to allocate memory for stringlist"); return (p); } /* * sl_add() with inbuilt error checking */ void ftp_sl_add(StringList *sl, char *i) { if (sl_add(sl, i) == -1) err(1, "Unable to add `%s' to stringlist", i); } /* * strdup() with inbuilt error checking */ char * ftp_strdup(const char *str) { char *s; if (str == NULL) errx(1, "ftp_strdup: called with NULL argument"); s = strdup(str); if (s == NULL) err(1, "Unable to allocate memory for string copy"); return (s); } Index: stable/12 =================================================================== --- stable/12 (revision 362507) +++ stable/12 (revision 362508) Property changes on: stable/12 ___________________________________________________________________ Modified: svn:mergeinfo ## -0,0 +0,1 ## Merged /head:r358405