📄 ftpconnection.java
字号:
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */package net.sf.jftp.net;//***now all config files are importedimport net.sf.jftp.config.*;import net.sf.jftp.util.Log;import net.sf.jftp.util.StringUtils;import java.io.*;import java.net.*;import java.util.*;/** * All control transactions are made here. * See doc/FtpDownload.java for examples and note * that this class is event-driven and not Exception-based! * You might want to take a look at ConnectionListener, too. * * @author David Hansmann, hansmann.d@debitel.net * @version 1.30+, June 2003 */public class FtpConnection implements BasicConnection, FtpConstants{ private static final boolean TESTMODE = false; // everything starting with this will be treated // as a negative response private final static String NEGATIVE = "5"; private final static String NEGATIVE2 = "4"; // everything starting with this will be treated // as a positive response private final static String POSITIVE = "2"; // for resuming private final static String PROCEED = "3"; //"350"; private final static char MORE_LINES_APPENDED = '-'; /** Internal download constant */ public final static String DOWNLOAD = "DOWNLOAD"; /** Internal upload constant */ public final static String UPLOAD = "UPLOAD"; /** Internal abort command constant */ public final static String ABOR = "ABOR"; //*** 1.44: if LIST is not set, then load it from advanced settings //*** And if the file for it is not found, then create it //*** with LIST -laL as the default public static String LIST_DEFAULT = "LIST -laL"; public static String LIST = "default"; public final static String ASCII = "A"; public final static String BINARY = "I"; public final static String EBCDIC = "E"; public final static String L8 = "L 8"; public final static String STREAM = "S"; public final static String BLOCKED = "B"; public final static String COMPRESSED = "C"; private static boolean useStream = true; private static boolean useBlocked = true; private static boolean useCompressed = true; //*** /** * Used to determine the type of transfer. */ public boolean hasUploaded = false; public boolean work = true; private boolean msg = true; private boolean ok = true; private String pwd = ""; private String initCWD = Settings.defaultDir; private String[] loginAck = new String[] { FTP331_USER_OK_NEED_PASSWORD, FTP230_LOGGED_IN }; private String osType; private String dataType; private FtpTransfer lastTransfer = null; private boolean modeStreamSet = false; private DataConnection dcon = null; private Vector listeners = new Vector(); private ConnectionHandler handler = new ConnectionHandler(); // directory downloaded to private String localPath = null; // active ftp ports private int porta = 5; // 5 * 256 + 1 = 1281 private int portb = 1; /** the host */ private String host = ""; /** the user */ private String username; /** the password */ private String password; /** the port */ private int port = 21; /** the InputStream of the control connection */ private BufferedReader in; /** the OutputStream of the control connection */ private JConnection jcon; /** we are disconnected */ private boolean connected = false; private boolean shortProgress = false; private boolean isDirUpload = false; private String baseFile; private int fileCount; private String typeNow = ""; /** * May contain date listing */ public Vector dateVector = new Vector(); /** * Create an instance with a given host * * @param host The host to connect to */ public FtpConnection(String host) { this.host = host; File f = new File("."); setLocalPath(f.getAbsolutePath()); } /** * Create an instance with a given host, port and initial remote working directory * * @param host The host to connect to * @param port The port used for the control connection, usually 21 * @param initCWD The initial remote working directory */ public FtpConnection(String host, int port, String initCWD) { this.host = host; this.port = port; this.initCWD = initCWD; File f = new File("."); setLocalPath(f.getAbsolutePath()); } /** * Connect to the server an log in. * * Does also fire directory update and connection initialized event if successful or * connection failed event if failed. * * @param username The username * @param password The password * @return WRONG_LOGIN_DATA, OFFLINE, GENERIC_FAILED or LOGIN_OK status code */ public int login(String username, String password) { this.username = username; this.password = password; int status = LOGIN_OK; if(msg) { Log.debug("Connecting to " + host); } jcon = new JConnection(host, port); if(jcon.isThere()) { in = jcon.getReader(); if(getLine(FTP220_SERVICE_READY) == null) { ok = false; Log.debug("Server closed Connection, maybe too many users..."); status = OFFLINE; } if(msg) { Log.debug("Connection established..."); } jcon.send(USER + " " + username); if(!getLine(loginAck).startsWith(FTP230_LOGGED_IN)) { jcon.send(PASS + " " + password); if(success(FTP230_LOGGED_IN)) { if(msg) { Log.debug("Logged in..."); } } else { Log.debug("Wrong password!"); ok = false; status = WRONG_LOGIN_DATA; } } // end if(jcon)... } else { if(msg) { Log.debug("FTP not available!"); ok = false; status = GENERIC_FAILED; } } if(ok) { connected = true; system(); binary(); if(initCWD.trim().equals(Settings.defaultDir) || !chdirNoRefresh(initCWD)) { //System.out.println("default dir..."); //if(!chdirNoRefresh(getPWD())) //{ //System.out.println("FtpConnection should not do this..."); // if(!chdirNoRefresh("~")) // { // chdirNoRefresh("/"); // } //} updatePWD(); } //Array of length 6 created, as that is maximum LoadSet size (need //public variable with that constant there for it to refer to?) String[] advSettings = new String[6]; if(LIST.equals("default")) { //just get the first item (somehow it knows first is the //FTP list command) advSettings = LoadSet.loadSet(Settings.adv_settings); //*** IF FILE NOT FOUND, CREATE IT AND SET IT TO LIST_DEFAULT if(advSettings == null) { LIST = LIST_DEFAULT; SaveSet s = new SaveSet(Settings.adv_settings, LIST); } else { LIST = advSettings[0]; if(LIST == null) { LIST = LIST_DEFAULT; } } } //*** fireDirectoryUpdate(this); fireConnectionInitialized(this); } else { fireConnectionFailed(this, new Integer(status).toString()); } return status; } /** * Sort the filesizes an return an array. * * The Array should be in sync with the other sort*-Methods * * @param file The file containing the raw server listing, usually Settings.ls_out * @return An String-array of sizes containing the size or -1 if failed or 0 for directories */ public String[] sortSize(String file) { BufferedReader in = null; PrintStream out = null; int length = 0; if(TESTMODE) { file = "/home/cdemon/sampleos2"; } try { in = new BufferedReader(new FileReader(file)); out = new PrintStream(new FileOutputStream(Settings.sortsize_out)); while(true) { String tmp = in.readLine(); if(tmp == null) { Log.debug("end size"); break; } length++; // ------------- VMS override ------------------- if(getOsType().indexOf("VMS") >= 0) { if(tmp.indexOf(";") < 0) { length--; continue; } out.println("-1"); continue; } // ------------------------------------------------ else if(getOsType().indexOf("WINDOW") >= 0) { StringTokenizer to = new StringTokenizer(tmp, " ", false); if(to.countTokens() >= 4) { to.nextToken(); to.nextToken(); String size = to.nextToken(); if(size.equals("<DIR>")) { out.println("0"); } else { try { Long.parseLong(size); out.println(size); } catch(Exception ex) { out.println("-1"); Log.out("WARNING: filesize can not be determined - value is " + size); } } } } // ------------------------------------------------ else if(getOsType().indexOf("OS/2") >= 0) { StringTokenizer to = new StringTokenizer(tmp, " ", false); tmp = giveSize(to, 0); Log.out("OS/2 parser (size): " + tmp); out.println(tmp); } else { //Log.out("\n\nparser\n\n"); StringTokenizer to = new StringTokenizer(tmp, " ", false); if(to.countTokens() >= 8) // unix { tmp = giveSize(to, 4); out.println(tmp); //Log.out(tmp); } else if(to.countTokens() == 7) // unix, too { Log.out("WARNING: 7 token backup size parser activated!"); tmp = giveSize(to, 4); out.println(tmp); } else { Log.debug("cannot parse line: " + tmp); length--; } } } } catch(Exception ex) { Log.debug(ex.toString() + " @FtpConnection::sortSize#1"); } try { in = new BufferedReader(new FileReader(Settings.sortsize_out)); String[] files = new String[length]; for(int i = 0; i < length; i++) { files[i] = in.readLine(); //System.out.println(files[i]); //Log.debug(files[i]); } return files; } catch(Exception ex) { Log.debug(ex.toString() + " @FtpConnection::sortSize#2"); } return new String[0]; } /** * Sort the permissions an return an array. * * The Array should be in sync with the other sort*-Methods * * @param file The file containing the raw server listing, usually Settings.ls_out * @return An int-array of sizes containing W, R or DENIED for each file */ public int[] getPermissions(String file) { BufferedReader in = null; PrintStream out = null; int length = 0; if(TESTMODE) { file = "/home/cdemon/sampleos2"; } try { in = new BufferedReader(new FileReader(file)); out = new PrintStream(new FileOutputStream(Settings.permissions_out)); while(true) { String tmp = in.readLine(); if(tmp == null) { break; } // ------------- VMS override ------------------- if(getOsType().indexOf("VMS") >= 0) { if(tmp.indexOf(";") < 0) { continue; } out.println("r"); length++; continue; } // ------------------------------------------------ length++; StringTokenizer to = new StringTokenizer(tmp.trim(), " ", false); if(!(to.countTokens() > 3) || (tmp.startsWith("/") && (tmp.indexOf("denied") > 0))) { length--; continue; } tmp = to.nextToken(); if(tmp.length() != 10) { //System.out.println(tmp + " - e"); return null; // exotic bug, hardlinks are not found or something ("/bin/ls: dir: no such file or directy" in ls output) - we have no permissions then }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -