1789N/A/*
3261N/A * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
1789N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1789N/A *
1789N/A * This code is free software; you can redistribute it and/or modify it
1789N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
1789N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
1789N/A *
1789N/A * This code is distributed in the hope that it will be useful, but WITHOUT
1789N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1789N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1789N/A * version 2 for more details (a copy is included in the LICENSE file that
1789N/A * accompanied this code).
1789N/A *
1789N/A * You should have received a copy of the GNU General Public License version
1789N/A * 2 along with this work; if not, write to the Free Software Foundation,
1789N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1789N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
1789N/A */
1789N/Apackage sun.net.ftp.impl;
1789N/A
1789N/Aimport java.net.*;
1789N/Aimport java.io.*;
1789N/Aimport java.security.AccessController;
1789N/Aimport java.security.PrivilegedAction;
6319N/Aimport java.security.PrivilegedExceptionAction;
1789N/Aimport java.text.DateFormat;
1789N/Aimport java.text.ParseException;
1789N/Aimport java.text.SimpleDateFormat;
1789N/Aimport java.util.ArrayList;
1789N/Aimport java.util.Calendar;
1789N/Aimport java.util.Date;
1789N/Aimport java.util.Iterator;
1789N/Aimport java.util.List;
1789N/Aimport java.util.TimeZone;
1789N/Aimport java.util.Vector;
1789N/Aimport java.util.regex.Matcher;
1789N/Aimport java.util.regex.Pattern;
1789N/Aimport javax.net.ssl.SSLSocket;
1789N/Aimport javax.net.ssl.SSLSocketFactory;
1789N/Aimport sun.misc.BASE64Decoder;
1789N/Aimport sun.misc.BASE64Encoder;
1789N/Aimport sun.net.ftp.*;
1789N/Aimport sun.util.logging.PlatformLogger;
1789N/A
1789N/A
1789N/Apublic class FtpClient extends sun.net.ftp.FtpClient {
1789N/A
1789N/A private static int defaultSoTimeout;
1789N/A private static int defaultConnectTimeout;
1789N/A private static final PlatformLogger logger =
1789N/A PlatformLogger.getLogger("sun.net.ftp.FtpClient");
1789N/A private Proxy proxy;
1789N/A private Socket server;
1789N/A private PrintStream out;
1789N/A private InputStream in;
1789N/A private int readTimeout = -1;
1789N/A private int connectTimeout = -1;
1789N/A
1789N/A /* Name of encoding to use for output */
1789N/A private static String encoding = "ISO8859_1";
1789N/A /** remember the ftp server name because we may need it */
1789N/A private InetSocketAddress serverAddr;
1789N/A private boolean replyPending = false;
1789N/A private boolean loggedIn = false;
1789N/A private boolean useCrypto = false;
1789N/A private SSLSocketFactory sslFact;
1789N/A private Socket oldSocket;
1789N/A /** Array of strings (usually 1 entry) for the last reply from the server. */
1789N/A private Vector<String> serverResponse = new Vector<String>(1);
1789N/A /** The last reply code from the ftp daemon. */
1789N/A private FtpReplyCode lastReplyCode = null;
1789N/A /** Welcome message from the server, if any. */
1789N/A private String welcomeMsg;
6319N/A /**
6319N/A * Only passive mode used in JDK. See Bug 8010784.
6319N/A */
6319N/A private final boolean passiveMode = true;
1789N/A private TransferType type = TransferType.BINARY;
1789N/A private long restartOffset = 0;
1789N/A private long lastTransSize = -1; // -1 means 'unknown size'
1789N/A private String lastFileName;
1789N/A /**
1789N/A * Static members used by the parser
1789N/A */
1789N/A private static String[] patStrings = {
1789N/A // drwxr-xr-x 1 user01 ftp 512 Jan 29 23:32 prog
1789N/A "([\\-ld](?:[r\\-][w\\-][x\\-]){3})\\s*\\d+ (\\w+)\\s*(\\w+)\\s*(\\d+)\\s*([A-Z][a-z][a-z]\\s*\\d+)\\s*(\\d\\d:\\d\\d)\\s*(\\p{Print}*)",
1789N/A // drwxr-xr-x 1 user01 ftp 512 Jan 29 1997 prog
1789N/A "([\\-ld](?:[r\\-][w\\-][x\\-]){3})\\s*\\d+ (\\w+)\\s*(\\w+)\\s*(\\d+)\\s*([A-Z][a-z][a-z]\\s*\\d+)\\s*(\\d{4})\\s*(\\p{Print}*)",
1789N/A // 04/28/2006 09:12a 3,563 genBuffer.sh
1789N/A "(\\d{2}/\\d{2}/\\d{4})\\s*(\\d{2}:\\d{2}[ap])\\s*((?:[0-9,]+)|(?:<DIR>))\\s*(\\p{Graph}*)",
1789N/A // 01-29-97 11:32PM <DIR> prog
1789N/A "(\\d{2}-\\d{2}-\\d{2})\\s*(\\d{2}:\\d{2}[AP]M)\\s*((?:[0-9,]+)|(?:<DIR>))\\s*(\\p{Graph}*)"
1789N/A };
1789N/A private static int[][] patternGroups = {
1789N/A // 0 - file, 1 - size, 2 - date, 3 - time, 4 - year, 5 - permissions,
1789N/A // 6 - user, 7 - group
1789N/A {7, 4, 5, 6, 0, 1, 2, 3},
1789N/A {7, 4, 5, 0, 6, 1, 2, 3},
1789N/A {4, 3, 1, 2, 0, 0, 0, 0},
1789N/A {4, 3, 1, 2, 0, 0, 0, 0}};
1789N/A private static Pattern[] patterns;
1789N/A private static Pattern linkp = Pattern.compile("(\\p{Print}+) \\-\\> (\\p{Print}+)$");
1789N/A private DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, java.util.Locale.US);
1789N/A
1789N/A static {
1789N/A final int vals[] = {0, 0};
1789N/A final String encs[] = {null};
1789N/A
1789N/A AccessController.doPrivileged(
1789N/A new PrivilegedAction<Object>() {
1789N/A
1789N/A public Object run() {
1789N/A vals[0] = Integer.getInteger("sun.net.client.defaultReadTimeout", 0).intValue();
1789N/A vals[1] = Integer.getInteger("sun.net.client.defaultConnectTimeout", 0).intValue();
1789N/A encs[0] = System.getProperty("file.encoding", "ISO8859_1");
1789N/A return null;
1789N/A }
1789N/A });
1789N/A if (vals[0] == 0) {
1789N/A defaultSoTimeout = -1;
1789N/A } else {
1789N/A defaultSoTimeout = vals[0];
1789N/A }
1789N/A
1789N/A if (vals[1] == 0) {
1789N/A defaultConnectTimeout = -1;
1789N/A } else {
1789N/A defaultConnectTimeout = vals[1];
1789N/A }
1789N/A
1789N/A encoding = encs[0];
1789N/A try {
1789N/A if (!isASCIISuperset(encoding)) {
1789N/A encoding = "ISO8859_1";
1789N/A }
1789N/A } catch (Exception e) {
1789N/A encoding = "ISO8859_1";
1789N/A }
1789N/A
1789N/A patterns = new Pattern[patStrings.length];
1789N/A for (int i = 0; i < patStrings.length; i++) {
1789N/A patterns[i] = Pattern.compile(patStrings[i]);
1789N/A }
1789N/A }
1789N/A
1789N/A /**
1789N/A * Test the named character encoding to verify that it converts ASCII
1789N/A * characters correctly. We have to use an ASCII based encoding, or else
1789N/A * the NetworkClients will not work correctly in EBCDIC based systems.
1789N/A * However, we cannot just use ASCII or ISO8859_1 universally, because in
1789N/A * Asian locales, non-ASCII characters may be embedded in otherwise
1789N/A * ASCII based protocols (eg. HTTP). The specifications (RFC2616, 2398)
1789N/A * are a little ambiguous in this matter. For instance, RFC2398 [part 2.1]
1789N/A * says that the HTTP request URI should be escaped using a defined
1789N/A * mechanism, but there is no way to specify in the escaped string what
1789N/A * the original character set is. It is not correct to assume that
1789N/A * UTF-8 is always used (as in URLs in HTML 4.0). For this reason,
1789N/A * until the specifications are updated to deal with this issue more
1789N/A * comprehensively, and more importantly, HTTP servers are known to
1789N/A * support these mechanisms, we will maintain the current behavior
1789N/A * where it is possible to send non-ASCII characters in their original
1789N/A * unescaped form.
1789N/A */
1789N/A private static boolean isASCIISuperset(String encoding) throws Exception {
1789N/A String chkS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
1789N/A "abcdefghijklmnopqrstuvwxyz-_.!~*'();/?:@&=+$,";
1789N/A
1789N/A // Expected byte sequence for string above
1789N/A byte[] chkB = {48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70, 71, 72,
1789N/A 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99,
1789N/A 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
1789N/A 115, 116, 117, 118, 119, 120, 121, 122, 45, 95, 46, 33, 126, 42, 39, 40, 41, 59,
1789N/A 47, 63, 58, 64, 38, 61, 43, 36, 44};
1789N/A
1789N/A byte[] b = chkS.getBytes(encoding);
1789N/A return java.util.Arrays.equals(b, chkB);
1789N/A }
1789N/A
1789N/A private class DefaultParser implements FtpDirParser {
1789N/A
1789N/A /**
1789N/A * Possible patterns:
1789N/A *
1789N/A * drwxr-xr-x 1 user01 ftp 512 Jan 29 23:32 prog
1789N/A * drwxr-xr-x 1 user01 ftp 512 Jan 29 1997 prog
1789N/A * drwxr-xr-x 1 1 1 512 Jan 29 23:32 prog
1789N/A * lrwxr-xr-x 1 user01 ftp 512 Jan 29 23:32 prog -> prog2000
1789N/A * drwxr-xr-x 1 username ftp 512 Jan 29 23:32 prog
1789N/A * -rw-r--r-- 1 jcc staff 105009 Feb 3 15:05 test.1
1789N/A *
1789N/A * 01-29-97 11:32PM <DIR> prog
1789N/A * 04/28/2006 09:12a 3,563 genBuffer.sh
1789N/A *
1789N/A * drwxr-xr-x folder 0 Jan 29 23:32 prog
1789N/A *
1789N/A * 0 DIR 01-29-97 23:32 PROG
1789N/A */
1789N/A private DefaultParser() {
1789N/A }
1789N/A
1789N/A public FtpDirEntry parseLine(String line) {
1789N/A String fdate = null;
1789N/A String fsize = null;
1789N/A String time = null;
1789N/A String filename = null;
1789N/A String permstring = null;
1789N/A String username = null;
1789N/A String groupname = null;
1789N/A boolean dir = false;
1789N/A Calendar now = Calendar.getInstance();
1789N/A int year = now.get(Calendar.YEAR);
1789N/A
1789N/A Matcher m = null;
1789N/A for (int j = 0; j < patterns.length; j++) {
1789N/A m = patterns[j].matcher(line);
1789N/A if (m.find()) {
1789N/A // 0 - file, 1 - size, 2 - date, 3 - time, 4 - year,
1789N/A // 5 - permissions, 6 - user, 7 - group
1789N/A filename = m.group(patternGroups[j][0]);
1789N/A fsize = m.group(patternGroups[j][1]);
1789N/A fdate = m.group(patternGroups[j][2]);
1789N/A if (patternGroups[j][4] > 0) {
1789N/A fdate += (", " + m.group(patternGroups[j][4]));
1789N/A } else if (patternGroups[j][3] > 0) {
1789N/A fdate += (", " + String.valueOf(year));
1789N/A }
1789N/A if (patternGroups[j][3] > 0) {
1789N/A time = m.group(patternGroups[j][3]);
1789N/A }
1789N/A if (patternGroups[j][5] > 0) {
1789N/A permstring = m.group(patternGroups[j][5]);
1789N/A dir = permstring.startsWith("d");
1789N/A }
1789N/A if (patternGroups[j][6] > 0) {
1789N/A username = m.group(patternGroups[j][6]);
1789N/A }
1789N/A if (patternGroups[j][7] > 0) {
1789N/A groupname = m.group(patternGroups[j][7]);
1789N/A }
1789N/A // Old DOS format
1789N/A if ("<DIR>".equals(fsize)) {
1789N/A dir = true;
1789N/A fsize = null;
1789N/A }
1789N/A }
1789N/A }
1789N/A
1789N/A if (filename != null) {
1789N/A Date d;
1789N/A try {
1789N/A d = df.parse(fdate);
1789N/A } catch (Exception e) {
1789N/A d = null;
1789N/A }
1789N/A if (d != null && time != null) {
1789N/A int c = time.indexOf(":");
1789N/A now.setTime(d);
1789N/A now.set(Calendar.HOUR, Integer.parseInt(time.substring(0, c)));
1789N/A now.set(Calendar.MINUTE, Integer.parseInt(time.substring(c + 1)));
1789N/A d = now.getTime();
1789N/A }
1789N/A // see if it's a symbolic link, i.e. the name if followed
1789N/A // by a -> and a path
1789N/A Matcher m2 = linkp.matcher(filename);
1789N/A if (m2.find()) {
1789N/A // Keep only the name then
1789N/A filename = m2.group(1);
1789N/A }
1789N/A boolean[][] perms = new boolean[3][3];
1789N/A for (int i = 0; i < 3; i++) {
1789N/A for (int j = 0; j < 3; j++) {
1789N/A perms[i][j] = (permstring.charAt((i * 3) + j) != '-');
1789N/A }
1789N/A }
1789N/A FtpDirEntry file = new FtpDirEntry(filename);
1789N/A file.setUser(username).setGroup(groupname);
1789N/A file.setSize(Long.parseLong(fsize)).setLastModified(d);
1789N/A file.setPermissions(perms);
1789N/A file.setType(dir ? FtpDirEntry.Type.DIR : (line.charAt(0) == 'l' ? FtpDirEntry.Type.LINK : FtpDirEntry.Type.FILE));
1789N/A return file;
1789N/A }
1789N/A return null;
1789N/A }
1789N/A }
1789N/A
1789N/A private class MLSxParser implements FtpDirParser {
1789N/A
1789N/A private SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
1789N/A
1789N/A public FtpDirEntry parseLine(String line) {
1789N/A String name = null;
1789N/A int i = line.lastIndexOf(";");
1789N/A if (i > 0) {
1789N/A name = line.substring(i + 1).trim();
1789N/A line = line.substring(0, i);
1789N/A } else {
1789N/A name = line.trim();
1789N/A line = "";
1789N/A }
1789N/A FtpDirEntry file = new FtpDirEntry(name);
1789N/A while (!line.isEmpty()) {
1789N/A String s;
1789N/A i = line.indexOf(";");
1789N/A if (i > 0) {
1789N/A s = line.substring(0, i);
1789N/A line = line.substring(i + 1);
1789N/A } else {
1789N/A s = line;
1789N/A line = "";
1789N/A }
1789N/A i = s.indexOf("=");
1789N/A if (i > 0) {
1789N/A String fact = s.substring(0, i);
1789N/A String value = s.substring(i + 1);
1789N/A file.addFact(fact, value);
1789N/A }
1789N/A }
1789N/A String s = file.getFact("Size");
1789N/A if (s != null) {
1789N/A file.setSize(Long.parseLong(s));
1789N/A }
1789N/A s = file.getFact("Modify");
1789N/A if (s != null) {
1789N/A Date d = null;
1789N/A try {
1789N/A d = df.parse(s);
1789N/A } catch (ParseException ex) {
1789N/A }
1789N/A if (d != null) {
1789N/A file.setLastModified(d);
1789N/A }
1789N/A }
1789N/A s = file.getFact("Create");
1789N/A if (s != null) {
1789N/A Date d = null;
1789N/A try {
1789N/A d = df.parse(s);
1789N/A } catch (ParseException ex) {
1789N/A }
1789N/A if (d != null) {
1789N/A file.setCreated(d);
1789N/A }
1789N/A }
1789N/A s = file.getFact("Type");
1789N/A if (s != null) {
1789N/A if (s.equalsIgnoreCase("file")) {
1789N/A file.setType(FtpDirEntry.Type.FILE);
1789N/A }
1789N/A if (s.equalsIgnoreCase("dir")) {
1789N/A file.setType(FtpDirEntry.Type.DIR);
1789N/A }
1789N/A if (s.equalsIgnoreCase("cdir")) {
1789N/A file.setType(FtpDirEntry.Type.CDIR);
1789N/A }
1789N/A if (s.equalsIgnoreCase("pdir")) {
1789N/A file.setType(FtpDirEntry.Type.PDIR);
1789N/A }
1789N/A }
1789N/A return file;
1789N/A }
1789N/A };
1789N/A private FtpDirParser parser = new DefaultParser();
1789N/A private FtpDirParser mlsxParser = new MLSxParser();
1789N/A private static Pattern transPat = null;
1789N/A
1789N/A private void getTransferSize() {
1789N/A lastTransSize = -1;
1789N/A /**
1789N/A * If it's a start of data transfer response, let's try to extract
1789N/A * the size from the response string. Usually it looks like that:
1789N/A *
1789N/A * 150 Opening BINARY mode data connection for foo (6701 bytes).
1789N/A */
1789N/A String response = getLastResponseString();
1789N/A if (transPat == null) {
1789N/A transPat = Pattern.compile("150 Opening .*\\((\\d+) bytes\\).");
1789N/A }
1789N/A Matcher m = transPat.matcher(response);
1789N/A if (m.find()) {
1789N/A String s = m.group(1);
1789N/A lastTransSize = Long.parseLong(s);
1789N/A }
1789N/A }
1789N/A
1789N/A /**
1789N/A * extract the created file name from the response string:
1789N/A * 226 Transfer complete (unique file name:toto.txt.1).
1789N/A * Usually happens when a STOU (store unique) command had been issued.
1789N/A */
1789N/A private void getTransferName() {
1789N/A lastFileName = null;
1789N/A String response = getLastResponseString();
1789N/A int i = response.indexOf("unique file name:");
1789N/A int e = response.lastIndexOf(')');
1789N/A if (i >= 0) {
1789N/A i += 17; // Length of "unique file name:"
1789N/A lastFileName = response.substring(i, e);
1789N/A }
1789N/A }
1789N/A
1789N/A /**
1789N/A * Pulls the response from the server and returns the code as a
1789N/A * number. Returns -1 on failure.
1789N/A */
1789N/A private int readServerResponse() throws IOException {
1789N/A StringBuffer replyBuf = new StringBuffer(32);
1789N/A int c;
1789N/A int continuingCode = -1;
1789N/A int code;
1789N/A String response;
1789N/A
1789N/A serverResponse.setSize(0);
1789N/A while (true) {
1789N/A while ((c = in.read()) != -1) {
1789N/A if (c == '\r') {
1789N/A if ((c = in.read()) != '\n') {
1789N/A replyBuf.append('\r');
1789N/A }
1789N/A }
1789N/A replyBuf.append((char) c);
1789N/A if (c == '\n') {
1789N/A break;
1789N/A }
1789N/A }
1789N/A response = replyBuf.toString();
1789N/A replyBuf.setLength(0);
1789N/A if (logger.isLoggable(PlatformLogger.FINEST)) {
1789N/A logger.finest("Server [" + serverAddr + "] --> " + response);
1789N/A }
1789N/A
1789N/A if (response.length() == 0) {
1789N/A code = -1;
1789N/A } else {
1789N/A try {
1789N/A code = Integer.parseInt(response.substring(0, 3));
1789N/A } catch (NumberFormatException e) {
1789N/A code = -1;
1789N/A } catch (StringIndexOutOfBoundsException e) {
1789N/A /* this line doesn't contain a response code, so
1789N/A we just completely ignore it */
1789N/A continue;
1789N/A }
1789N/A }
1789N/A serverResponse.addElement(response);
1789N/A if (continuingCode != -1) {
1789N/A /* we've seen a ###- sequence */
1789N/A if (code != continuingCode ||
1789N/A (response.length() >= 4 && response.charAt(3) == '-')) {
1789N/A continue;
1789N/A } else {
1789N/A /* seen the end of code sequence */
1789N/A continuingCode = -1;
1789N/A break;
1789N/A }
1789N/A } else if (response.length() >= 4 && response.charAt(3) == '-') {
1789N/A continuingCode = code;
1789N/A continue;
1789N/A } else {
1789N/A break;
1789N/A }
1789N/A }
1789N/A
1789N/A return code;
1789N/A }
1789N/A
1789N/A /** Sends command <i>cmd</i> to the server. */
1789N/A private void sendServer(String cmd) {
1789N/A out.print(cmd);
1789N/A if (logger.isLoggable(PlatformLogger.FINEST)) {
1789N/A logger.finest("Server [" + serverAddr + "] <-- " + cmd);
1789N/A }
1789N/A }
1789N/A
1789N/A /** converts the server response into a string. */
1789N/A private String getResponseString() {
1789N/A return serverResponse.elementAt(0);
1789N/A }
1789N/A
1789N/A /** Returns all server response strings. */
1789N/A private Vector<String> getResponseStrings() {
1789N/A return serverResponse;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Read the reply from the FTP server.
1789N/A *
1789N/A * @return <code>true</code> if the command was successful
1789N/A * @throws IOException if an error occured
1789N/A */
1789N/A private boolean readReply() throws IOException {
1789N/A lastReplyCode = FtpReplyCode.find(readServerResponse());
1789N/A
1789N/A if (lastReplyCode.isPositivePreliminary()) {
1789N/A replyPending = true;
1789N/A return true;
1789N/A }
1789N/A if (lastReplyCode.isPositiveCompletion() || lastReplyCode.isPositiveIntermediate()) {
1789N/A if (lastReplyCode == FtpReplyCode.CLOSING_DATA_CONNECTION) {
1789N/A getTransferName();
1789N/A }
1789N/A return true;
1789N/A }
1789N/A return false;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Sends a command to the FTP server and returns the error code
1789N/A * (which can be a "success") sent by the server.
1789N/A *
1789N/A * @param cmd
1789N/A * @return <code>true</code> if the command was successful
1789N/A * @throws IOException
1789N/A */
1789N/A private boolean issueCommand(String cmd) throws IOException {
1789N/A if (!isConnected()) {
1789N/A throw new IllegalStateException("Not connected");
1789N/A }
1789N/A if (replyPending) {
1789N/A try {
1789N/A completePending();
1789N/A } catch (sun.net.ftp.FtpProtocolException e) {
1789N/A // ignore...
1789N/A }
1789N/A }
1789N/A sendServer(cmd + "\r\n");
1789N/A return readReply();
1789N/A }
1789N/A
1789N/A /**
1789N/A * Send a command to the FTP server and check for success.
1789N/A *
1789N/A * @param cmd String containing the command
1789N/A *
1789N/A * @throws FtpProtocolException if an error occured
1789N/A */
1789N/A private void issueCommandCheck(String cmd) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A if (!issueCommand(cmd)) {
1789N/A throw new sun.net.ftp.FtpProtocolException(cmd + ":" + getResponseString(), getLastReplyCode());
1789N/A }
1789N/A }
1789N/A private static Pattern epsvPat = null;
1789N/A private static Pattern pasvPat = null;
1789N/A
1789N/A /**
1789N/A * Opens a "PASSIVE" connection with the server and returns the connected
1789N/A * <code>Socket</code>.
1789N/A *
1789N/A * @return the connected <code>Socket</code>
1789N/A * @throws IOException if the connection was unsuccessful.
1789N/A */
1789N/A private Socket openPassiveDataConnection(String cmd) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A String serverAnswer;
1789N/A int port;
1789N/A InetSocketAddress dest = null;
1789N/A
1789N/A /**
1789N/A * Here is the idea:
1789N/A *
1789N/A * - First we want to try the new (and IPv6 compatible) EPSV command
1789N/A * But since we want to be nice with NAT software, we'll issue the
1789N/A * EPSV ALL command first.
1789N/A * EPSV is documented in RFC2428
1789N/A * - If EPSV fails, then we fall back to the older, yet ok, PASV
1789N/A * - If PASV fails as well, then we throw an exception and the calling
1789N/A * method will have to try the EPRT or PORT command
1789N/A */
1789N/A if (issueCommand("EPSV ALL")) {
1789N/A // We can safely use EPSV commands
1789N/A issueCommandCheck("EPSV");
1789N/A serverAnswer = getResponseString();
1789N/A
1789N/A // The response string from a EPSV command will contain the port number
1789N/A // the format will be :
1789N/A // 229 Entering Extended PASSIVE Mode (|||58210|)
1789N/A //
1789N/A // So we'll use the regular expresions package to parse the output.
1789N/A
1789N/A if (epsvPat == null) {
1789N/A epsvPat = Pattern.compile("^229 .* \\(\\|\\|\\|(\\d+)\\|\\)");
1789N/A }
1789N/A Matcher m = epsvPat.matcher(serverAnswer);
1789N/A if (!m.find()) {
1789N/A throw new sun.net.ftp.FtpProtocolException("EPSV failed : " + serverAnswer);
1789N/A }
1789N/A // Yay! Let's extract the port number
1789N/A String s = m.group(1);
1789N/A port = Integer.parseInt(s);
1789N/A InetAddress add = server.getInetAddress();
1789N/A if (add != null) {
1789N/A dest = new InetSocketAddress(add, port);
1789N/A } else {
1789N/A // This means we used an Unresolved address to connect in
1789N/A // the first place. Most likely because the proxy is doing
1789N/A // the name resolution for us, so let's keep using unresolved
1789N/A // address.
1789N/A dest = InetSocketAddress.createUnresolved(serverAddr.getHostName(), port);
1789N/A }
1789N/A } else {
1789N/A // EPSV ALL failed, so Let's try the regular PASV cmd
1789N/A issueCommandCheck("PASV");
1789N/A serverAnswer = getResponseString();
1789N/A
1789N/A // Let's parse the response String to get the IP & port to connect
1789N/A // to. The String should be in the following format :
1789N/A //
1789N/A // 227 Entering PASSIVE Mode (A1,A2,A3,A4,p1,p2)
1789N/A //
1789N/A // Note that the two parenthesis are optional
1789N/A //
1789N/A // The IP address is A1.A2.A3.A4 and the port is p1 * 256 + p2
1789N/A //
1789N/A // The regular expression is a bit more complex this time, because
1789N/A // the parenthesis are optionals and we have to use 3 groups.
1789N/A
1789N/A if (pasvPat == null) {
1789N/A pasvPat = Pattern.compile("227 .* \\(?(\\d{1,3},\\d{1,3},\\d{1,3},\\d{1,3}),(\\d{1,3}),(\\d{1,3})\\)?");
1789N/A }
1789N/A Matcher m = pasvPat.matcher(serverAnswer);
1789N/A if (!m.find()) {
1789N/A throw new sun.net.ftp.FtpProtocolException("PASV failed : " + serverAnswer);
1789N/A }
1789N/A // Get port number out of group 2 & 3
1789N/A port = Integer.parseInt(m.group(3)) + (Integer.parseInt(m.group(2)) << 8);
1789N/A // IP address is simple
1789N/A String s = m.group(1).replace(',', '.');
1789N/A dest = new InetSocketAddress(s, port);
1789N/A }
1789N/A // Got everything, let's open the socket!
1789N/A Socket s;
1789N/A if (proxy != null) {
1789N/A if (proxy.type() == Proxy.Type.SOCKS) {
1789N/A s = AccessController.doPrivileged(
1789N/A new PrivilegedAction<Socket>() {
1789N/A
1789N/A public Socket run() {
1789N/A return new Socket(proxy);
1789N/A }
1789N/A });
1789N/A } else {
1789N/A s = new Socket(Proxy.NO_PROXY);
1789N/A }
1789N/A } else {
1789N/A s = new Socket();
1789N/A }
6319N/A
6319N/A InetAddress serverAddress = AccessController.doPrivileged(
6319N/A new PrivilegedAction<InetAddress>() {
6319N/A @Override
6319N/A public InetAddress run() {
6319N/A return server.getLocalAddress();
6319N/A }
6319N/A });
6319N/A
1789N/A // Bind the socket to the same address as the control channel. This
1789N/A // is needed in case of multi-homed systems.
6319N/A s.bind(new InetSocketAddress(serverAddress, 0));
6319N/A
1789N/A if (connectTimeout >= 0) {
1789N/A s.connect(dest, connectTimeout);
1789N/A } else {
1789N/A if (defaultConnectTimeout > 0) {
1789N/A s.connect(dest, defaultConnectTimeout);
1789N/A } else {
1789N/A s.connect(dest);
1789N/A }
1789N/A }
1789N/A if (readTimeout >= 0) {
1789N/A s.setSoTimeout(readTimeout);
1789N/A } else if (defaultSoTimeout > 0) {
1789N/A s.setSoTimeout(defaultSoTimeout);
1789N/A }
1789N/A if (useCrypto) {
1789N/A try {
1789N/A s = sslFact.createSocket(s, dest.getHostName(), dest.getPort(), true);
1789N/A } catch (Exception e) {
1789N/A throw new sun.net.ftp.FtpProtocolException("Can't open secure data channel: " + e);
1789N/A }
1789N/A }
1789N/A if (!issueCommand(cmd)) {
1789N/A s.close();
2111N/A if (getLastReplyCode() == FtpReplyCode.FILE_UNAVAILABLE) {
2111N/A // Ensure backward compatibility
2111N/A throw new FileNotFoundException(cmd);
2111N/A }
1789N/A throw new sun.net.ftp.FtpProtocolException(cmd + ":" + getResponseString(), getLastReplyCode());
1789N/A }
1789N/A return s;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Opens a data connection with the server according to the set mode
1789N/A * (ACTIVE or PASSIVE) then send the command passed as an argument.
1789N/A *
1789N/A * @param cmd the <code>String</code> containing the command to execute
1789N/A * @return the connected <code>Socket</code>
1789N/A * @throws IOException if the connection or command failed
1789N/A */
1789N/A private Socket openDataConnection(String cmd) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A Socket clientSocket;
1789N/A
1789N/A if (passiveMode) {
2111N/A try {
2111N/A return openPassiveDataConnection(cmd);
2111N/A } catch (sun.net.ftp.FtpProtocolException e) {
2111N/A // If Passive mode failed, fall back on PORT
2111N/A // Otherwise throw exception
2111N/A String errmsg = e.getMessage();
2111N/A if (!errmsg.startsWith("PASV") && !errmsg.startsWith("EPSV")) {
2111N/A throw e;
2111N/A }
2111N/A }
1789N/A }
1789N/A ServerSocket portSocket;
1789N/A InetAddress myAddress;
1789N/A String portCmd;
1789N/A
1789N/A if (proxy != null && proxy.type() == Proxy.Type.SOCKS) {
1789N/A // We're behind a firewall and the passive mode fail,
1789N/A // since we can't accept a connection through SOCKS (yet)
1789N/A // throw an exception
1789N/A throw new sun.net.ftp.FtpProtocolException("Passive mode failed");
1789N/A }
1789N/A // Bind the ServerSocket to the same address as the control channel
1789N/A // This is needed for multi-homed systems
1789N/A portSocket = new ServerSocket(0, 1, server.getLocalAddress());
1789N/A try {
1789N/A myAddress = portSocket.getInetAddress();
1789N/A if (myAddress.isAnyLocalAddress()) {
1789N/A myAddress = server.getLocalAddress();
1789N/A }
1789N/A // Let's try the new, IPv6 compatible EPRT command
1789N/A // See RFC2428 for specifics
1789N/A // Some FTP servers (like the one on Solaris) are bugged, they
1789N/A // will accept the EPRT command but then, the subsequent command
1789N/A // (e.g. RETR) will fail, so we have to check BOTH results (the
1789N/A // EPRT cmd then the actual command) to decide wether we should
1789N/A // fall back on the older PORT command.
1789N/A portCmd = "EPRT |" + ((myAddress instanceof Inet6Address) ? "2" : "1") + "|" +
1789N/A myAddress.getHostAddress() + "|" + portSocket.getLocalPort() + "|";
1789N/A if (!issueCommand(portCmd) || !issueCommand(cmd)) {
1789N/A // The EPRT command failed, let's fall back to good old PORT
1789N/A portCmd = "PORT ";
1789N/A byte[] addr = myAddress.getAddress();
1789N/A
1789N/A /* append host addr */
1789N/A for (int i = 0; i < addr.length; i++) {
1789N/A portCmd = portCmd + (addr[i] & 0xFF) + ",";
1789N/A }
1789N/A
1789N/A /* append port number */
1789N/A portCmd = portCmd + ((portSocket.getLocalPort() >>> 8) & 0xff) + "," + (portSocket.getLocalPort() & 0xff);
1789N/A issueCommandCheck(portCmd);
1789N/A issueCommandCheck(cmd);
1789N/A }
1789N/A // Either the EPRT or the PORT command was successful
1789N/A // Let's create the client socket
1789N/A if (connectTimeout >= 0) {
1789N/A portSocket.setSoTimeout(connectTimeout);
1789N/A } else {
1789N/A if (defaultConnectTimeout > 0) {
1789N/A portSocket.setSoTimeout(defaultConnectTimeout);
1789N/A }
1789N/A }
1789N/A clientSocket = portSocket.accept();
1789N/A if (readTimeout >= 0) {
1789N/A clientSocket.setSoTimeout(readTimeout);
1789N/A } else {
1789N/A if (defaultSoTimeout > 0) {
1789N/A clientSocket.setSoTimeout(defaultSoTimeout);
1789N/A }
1789N/A }
1789N/A } finally {
1789N/A portSocket.close();
1789N/A }
1789N/A if (useCrypto) {
1789N/A try {
1789N/A clientSocket = sslFact.createSocket(clientSocket, serverAddr.getHostName(), serverAddr.getPort(), true);
1789N/A } catch (Exception ex) {
1789N/A throw new IOException(ex.getLocalizedMessage());
1789N/A }
1789N/A }
1789N/A return clientSocket;
1789N/A }
1789N/A
1789N/A private InputStream createInputStream(InputStream in) {
1789N/A if (type == TransferType.ASCII) {
1789N/A return new sun.net.TelnetInputStream(in, false);
1789N/A }
1789N/A return in;
1789N/A }
1789N/A
1789N/A private OutputStream createOutputStream(OutputStream out) {
1789N/A if (type == TransferType.ASCII) {
1789N/A return new sun.net.TelnetOutputStream(out, false);
1789N/A }
1789N/A return out;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Creates an instance of FtpClient. The client is not connected to any
1789N/A * server yet.
1789N/A *
1789N/A */
1789N/A protected FtpClient() {
1789N/A }
1789N/A
1789N/A /**
1789N/A * Creates an instance of FtpClient. The client is not connected to any
1789N/A * server yet.
1789N/A *
1789N/A */
1789N/A public static sun.net.ftp.FtpClient create() {
1789N/A return new FtpClient();
1789N/A }
1789N/A
1789N/A /**
1789N/A * Set the transfer mode to <I>passive</I>. In that mode, data connections
1789N/A * are established by having the client connect to the server.
1789N/A * This is the recommended default mode as it will work best through
1789N/A * firewalls and NATs.
1789N/A *
1789N/A * @return This FtpClient
1789N/A * @see #setActiveMode()
1789N/A */
1789N/A public sun.net.ftp.FtpClient enablePassiveMode(boolean passive) {
6319N/A // Only passive mode used in JDK. See Bug 8010784.
6319N/A // passiveMode = passive;
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Gets the current transfer mode.
1789N/A *
1789N/A * @return the current <code>FtpTransferMode</code>
1789N/A */
1789N/A public boolean isPassiveModeEnabled() {
1789N/A return passiveMode;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Sets the timeout value to use when connecting to the server,
1789N/A *
1789N/A * @param timeout the timeout value, in milliseconds, to use for the connect
1789N/A * operation. A value of zero or less, means use the default timeout.
1789N/A *
1789N/A * @return This FtpClient
1789N/A */
1789N/A public sun.net.ftp.FtpClient setConnectTimeout(int timeout) {
1789N/A connectTimeout = timeout;
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Returns the current connection timeout value.
1789N/A *
1789N/A * @return the value, in milliseconds, of the current connect timeout.
1789N/A * @see #setConnectTimeout(int)
1789N/A */
1789N/A public int getConnectTimeout() {
1789N/A return connectTimeout;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Sets the timeout value to use when reading from the server,
1789N/A *
1789N/A * @param timeout the timeout value, in milliseconds, to use for the read
1789N/A * operation. A value of zero or less, means use the default timeout.
1789N/A * @return This FtpClient
1789N/A */
1789N/A public sun.net.ftp.FtpClient setReadTimeout(int timeout) {
1789N/A readTimeout = timeout;
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Returns the current read timeout value.
1789N/A *
1789N/A * @return the value, in milliseconds, of the current read timeout.
1789N/A * @see #setReadTimeout(int)
1789N/A */
1789N/A public int getReadTimeout() {
1789N/A return readTimeout;
1789N/A }
1789N/A
1789N/A public sun.net.ftp.FtpClient setProxy(Proxy p) {
1789N/A proxy = p;
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Get the proxy of this FtpClient
1789N/A *
1789N/A * @return the <code>Proxy</code>, this client is using, or <code>null</code>
1789N/A * if none is used.
1789N/A * @see #setProxy(Proxy)
1789N/A */
1789N/A public Proxy getProxy() {
1789N/A return proxy;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Connects to the specified destination.
1789N/A *
1789N/A * @param dest the <code>InetSocketAddress</code> to connect to.
1789N/A * @throws IOException if the connection fails.
1789N/A */
1789N/A private void tryConnect(InetSocketAddress dest, int timeout) throws IOException {
1789N/A if (isConnected()) {
1789N/A disconnect();
1789N/A }
1789N/A server = doConnect(dest, timeout);
1789N/A try {
1789N/A out = new PrintStream(new BufferedOutputStream(server.getOutputStream()),
1789N/A true, encoding);
1789N/A } catch (UnsupportedEncodingException e) {
1789N/A throw new InternalError(encoding + "encoding not found");
1789N/A }
1789N/A in = new BufferedInputStream(server.getInputStream());
1789N/A }
1789N/A
1789N/A private Socket doConnect(InetSocketAddress dest, int timeout) throws IOException {
1789N/A Socket s;
1789N/A if (proxy != null) {
1789N/A if (proxy.type() == Proxy.Type.SOCKS) {
1789N/A s = AccessController.doPrivileged(
1789N/A new PrivilegedAction<Socket>() {
1789N/A
1789N/A public Socket run() {
1789N/A return new Socket(proxy);
1789N/A }
1789N/A });
1789N/A } else {
1789N/A s = new Socket(Proxy.NO_PROXY);
1789N/A }
1789N/A } else {
1789N/A s = new Socket();
1789N/A }
1789N/A // Instance specific timeouts do have priority, that means
1789N/A // connectTimeout & readTimeout (-1 means not set)
1789N/A // Then global default timeouts
1789N/A // Then no timeout.
1789N/A if (timeout >= 0) {
1789N/A s.connect(dest, timeout);
1789N/A } else {
1789N/A if (connectTimeout >= 0) {
1789N/A s.connect(dest, connectTimeout);
1789N/A } else {
1789N/A if (defaultConnectTimeout > 0) {
1789N/A s.connect(dest, defaultConnectTimeout);
1789N/A } else {
1789N/A s.connect(dest);
1789N/A }
1789N/A }
1789N/A }
1789N/A if (readTimeout >= 0) {
1789N/A s.setSoTimeout(readTimeout);
1789N/A } else if (defaultSoTimeout > 0) {
1789N/A s.setSoTimeout(defaultSoTimeout);
1789N/A }
1789N/A return s;
1789N/A }
1789N/A
1789N/A private void disconnect() throws IOException {
1789N/A if (isConnected()) {
1789N/A server.close();
1789N/A }
1789N/A server = null;
1789N/A in = null;
1789N/A out = null;
1789N/A lastTransSize = -1;
1789N/A lastFileName = null;
1789N/A restartOffset = 0;
1789N/A welcomeMsg = null;
1789N/A lastReplyCode = null;
1789N/A serverResponse.setSize(0);
1789N/A }
1789N/A
1789N/A /**
1789N/A * Tests whether this client is connected or not to a server.
1789N/A *
1789N/A * @return <code>true</code> if the client is connected.
1789N/A */
1789N/A public boolean isConnected() {
1789N/A return server != null;
1789N/A }
1789N/A
1789N/A public SocketAddress getServerAddress() {
1789N/A return server == null ? null : server.getRemoteSocketAddress();
1789N/A }
1789N/A
1789N/A public sun.net.ftp.FtpClient connect(SocketAddress dest) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A return connect(dest, -1);
1789N/A }
1789N/A
1789N/A /**
1789N/A * Connects the FtpClient to the specified destination.
1789N/A *
1789N/A * @param dest the address of the destination server
1789N/A * @throws IOException if connection failed.
1789N/A */
1789N/A public sun.net.ftp.FtpClient connect(SocketAddress dest, int timeout) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A if (!(dest instanceof InetSocketAddress)) {
1789N/A throw new IllegalArgumentException("Wrong address type");
1789N/A }
1789N/A serverAddr = (InetSocketAddress) dest;
1789N/A tryConnect(serverAddr, timeout);
1789N/A if (!readReply()) {
1789N/A throw new sun.net.ftp.FtpProtocolException("Welcome message: " +
1789N/A getResponseString(), lastReplyCode);
1789N/A }
1789N/A welcomeMsg = getResponseString().substring(4);
1789N/A return this;
1789N/A }
1789N/A
1789N/A private void tryLogin(String user, char[] password) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("USER " + user);
1789N/A
1789N/A /*
1789N/A * Checks for "331 User name okay, need password." answer
1789N/A */
1789N/A if (lastReplyCode == FtpReplyCode.NEED_PASSWORD) {
1789N/A if ((password != null) && (password.length > 0)) {
1789N/A issueCommandCheck("PASS " + String.valueOf(password));
1789N/A }
1789N/A }
1789N/A }
1789N/A
1789N/A /**
1789N/A * Attempts to log on the server with the specified user name and password.
1789N/A *
1789N/A * @param user The user name
1789N/A * @param password The password for that user
1789N/A * @return <code>true</code> if the login was successful.
1789N/A * @throws IOException if an error occured during the transmission
1789N/A */
1789N/A public sun.net.ftp.FtpClient login(String user, char[] password) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A if (!isConnected()) {
1789N/A throw new sun.net.ftp.FtpProtocolException("Not connected yet", FtpReplyCode.BAD_SEQUENCE);
1789N/A }
1789N/A if (user == null || user.length() == 0) {
1789N/A throw new IllegalArgumentException("User name can't be null or empty");
1789N/A }
1789N/A tryLogin(user, password);
1789N/A
1789N/A // keep the welcome message around so we can
1789N/A // put it in the resulting HTML page.
1789N/A String l;
1789N/A StringBuffer sb = new StringBuffer();
1789N/A for (int i = 0; i < serverResponse.size(); i++) {
1789N/A l = serverResponse.elementAt(i);
1789N/A if (l != null) {
1789N/A if (l.length() >= 4 && l.startsWith("230")) {
1789N/A // get rid of the "230-" prefix
1789N/A l = l.substring(4);
1789N/A }
1789N/A sb.append(l);
1789N/A }
1789N/A }
1789N/A welcomeMsg = sb.toString();
1789N/A loggedIn = true;
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Attempts to log on the server with the specified user name, password and
1789N/A * account name.
1789N/A *
1789N/A * @param user The user name
1789N/A * @param password The password for that user.
1789N/A * @param account The account name for that user.
1789N/A * @return <code>true</code> if the login was successful.
1789N/A * @throws IOException if an error occurs during the transmission.
1789N/A */
1789N/A public sun.net.ftp.FtpClient login(String user, char[] password, String account) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A
1789N/A if (!isConnected()) {
1789N/A throw new sun.net.ftp.FtpProtocolException("Not connected yet", FtpReplyCode.BAD_SEQUENCE);
1789N/A }
1789N/A if (user == null || user.length() == 0) {
1789N/A throw new IllegalArgumentException("User name can't be null or empty");
1789N/A }
1789N/A tryLogin(user, password);
1789N/A
1789N/A /*
1789N/A * Checks for "332 Need account for login." answer
1789N/A */
1789N/A if (lastReplyCode == FtpReplyCode.NEED_ACCOUNT) {
1789N/A issueCommandCheck("ACCT " + account);
1789N/A }
1789N/A
1789N/A // keep the welcome message around so we can
1789N/A // put it in the resulting HTML page.
1789N/A StringBuffer sb = new StringBuffer();
1789N/A if (serverResponse != null) {
1789N/A for (String l : serverResponse) {
1789N/A if (l != null) {
1789N/A if (l.length() >= 4 && l.startsWith("230")) {
1789N/A // get rid of the "230-" prefix
1789N/A l = l.substring(4);
1789N/A }
1789N/A sb.append(l);
1789N/A }
1789N/A }
1789N/A }
1789N/A welcomeMsg = sb.toString();
1789N/A loggedIn = true;
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Logs out the current user. This is in effect terminates the current
1789N/A * session and the connection to the server will be closed.
1789N/A *
1789N/A */
1789N/A public void close() throws IOException {
1789N/A if (isConnected()) {
1789N/A issueCommand("QUIT");
1789N/A loggedIn = false;
1789N/A }
1789N/A disconnect();
1789N/A }
1789N/A
1789N/A /**
1789N/A * Checks whether the client is logged in to the server or not.
1789N/A *
1789N/A * @return <code>true</code> if the client has already completed a login.
1789N/A */
1789N/A public boolean isLoggedIn() {
1789N/A return loggedIn;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Changes to a specific directory on a remote FTP server
1789N/A *
1789N/A * @param remoteDirectory path of the directory to CD to.
1789N/A * @return <code>true</code> if the operation was successful.
1789N/A * @exception <code>FtpProtocolException</code>
1789N/A */
1789N/A public sun.net.ftp.FtpClient changeDirectory(String remoteDirectory) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A if (remoteDirectory == null || "".equals(remoteDirectory)) {
1789N/A throw new IllegalArgumentException("directory can't be null or empty");
1789N/A }
1789N/A
1789N/A issueCommandCheck("CWD " + remoteDirectory);
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Changes to the parent directory, sending the CDUP command to the server.
1789N/A *
1789N/A * @return <code>true</code> if the command was successful.
1789N/A * @throws IOException
1789N/A */
1789N/A public sun.net.ftp.FtpClient changeToParentDirectory() throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("CDUP");
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Returns the server current working directory, or <code>null</code> if
1789N/A * the PWD command failed.
1789N/A *
1789N/A * @return a <code>String</code> containing the current working directory,
1789N/A * or <code>null</code>
1789N/A * @throws IOException
1789N/A */
1789N/A public String getWorkingDirectory() throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("PWD");
1789N/A /*
1789N/A * answer will be of the following format :
1789N/A *
1789N/A * 257 "/" is current directory.
1789N/A */
1789N/A String answ = getResponseString();
1789N/A if (!answ.startsWith("257")) {
1789N/A return null;
1789N/A }
1789N/A return answ.substring(5, answ.lastIndexOf('"'));
1789N/A }
1789N/A
1789N/A /**
1789N/A * Sets the restart offset to the specified value. That value will be
1789N/A * sent through a <code>REST</code> command to server before a file
1789N/A * transfer and has the effect of resuming a file transfer from the
1789N/A * specified point. After a transfer the restart offset is set back to
1789N/A * zero.
1789N/A *
1789N/A * @param offset the offset in the remote file at which to start the next
1789N/A * transfer. This must be a value greater than or equal to zero.
1789N/A * @throws IllegalArgumentException if the offset is negative.
1789N/A */
1789N/A public sun.net.ftp.FtpClient setRestartOffset(long offset) {
1789N/A if (offset < 0) {
1789N/A throw new IllegalArgumentException("offset can't be negative");
1789N/A }
1789N/A restartOffset = offset;
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Retrieves a file from the ftp server and writes it to the specified
1789N/A * <code>OutputStream</code>.
1789N/A * If the restart offset was set, then a <code>REST</code> command will be
1789N/A * sent before the RETR in order to restart the tranfer from the specified
1789N/A * offset.
1789N/A * The <code>OutputStream</code> is not closed by this method at the end
1789N/A * of the transfer.
1789N/A *
1789N/A * @param name a <code>String<code> containing the name of the file to
1789N/A * retreive from the server.
1789N/A * @param local the <code>OutputStream</code> the file should be written to.
1789N/A * @throws IOException if the transfer fails.
1789N/A */
1789N/A public sun.net.ftp.FtpClient getFile(String name, OutputStream local) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A int mtu = 1500;
1789N/A if (restartOffset > 0) {
1789N/A Socket s;
1789N/A try {
1789N/A s = openDataConnection("REST " + restartOffset);
1789N/A } finally {
1789N/A restartOffset = 0;
1789N/A }
1789N/A issueCommandCheck("RETR " + name);
1789N/A getTransferSize();
1789N/A InputStream remote = createInputStream(s.getInputStream());
1789N/A byte[] buf = new byte[mtu * 10];
1789N/A int l;
1789N/A while ((l = remote.read(buf)) >= 0) {
1789N/A if (l > 0) {
1789N/A local.write(buf, 0, l);
1789N/A }
1789N/A }
1789N/A remote.close();
1789N/A } else {
1789N/A Socket s = openDataConnection("RETR " + name);
1789N/A getTransferSize();
1789N/A InputStream remote = createInputStream(s.getInputStream());
1789N/A byte[] buf = new byte[mtu * 10];
1789N/A int l;
1789N/A while ((l = remote.read(buf)) >= 0) {
1789N/A if (l > 0) {
1789N/A local.write(buf, 0, l);
1789N/A }
1789N/A }
1789N/A remote.close();
1789N/A }
1789N/A return completePending();
1789N/A }
1789N/A
1789N/A /**
1789N/A * Retrieves a file from the ftp server, using the RETR command, and
1789N/A * returns the InputStream from* the established data connection.
1789N/A * {@link #completePending()} <b>has</b> to be called once the application
1789N/A * is done reading from the returned stream.
1789N/A *
1789N/A * @param name the name of the remote file
1789N/A * @return the {@link java.io.InputStream} from the data connection, or
1789N/A * <code>null</code> if the command was unsuccessful.
1789N/A * @throws IOException if an error occured during the transmission.
1789N/A */
1789N/A public InputStream getFileStream(String name) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A Socket s;
1789N/A if (restartOffset > 0) {
1789N/A try {
1789N/A s = openDataConnection("REST " + restartOffset);
1789N/A } finally {
1789N/A restartOffset = 0;
1789N/A }
1789N/A if (s == null) {
1789N/A return null;
1789N/A }
1789N/A issueCommandCheck("RETR " + name);
1789N/A getTransferSize();
1789N/A return createInputStream(s.getInputStream());
1789N/A }
1789N/A
1789N/A s = openDataConnection("RETR " + name);
1789N/A if (s == null) {
1789N/A return null;
1789N/A }
1789N/A getTransferSize();
1789N/A return createInputStream(s.getInputStream());
1789N/A }
1789N/A
1789N/A /**
1789N/A * Transfers a file from the client to the server (aka a <I>put</I>)
1789N/A * by sending the STOR or STOU command, depending on the
1789N/A * <code>unique</code> argument, and returns the <code>OutputStream</code>
1789N/A * from the established data connection.
1789N/A * {@link #completePending()} <b>has</b> to be called once the application
1789N/A * is finished writing to the stream.
1789N/A *
1789N/A * A new file is created at the server site if the file specified does
1789N/A * not already exist.
1789N/A *
1789N/A * If <code>unique</code> is set to <code>true</code>, the resultant file
1789N/A * is to be created under a name unique to that directory, meaning
1789N/A * it will not overwrite an existing file, instead the server will
1789N/A * generate a new, unique, file name.
1789N/A * The name of the remote file can be retrieved, after completion of the
1789N/A * transfer, by calling {@link #getLastFileName()}.
1789N/A *
1789N/A * @param name the name of the remote file to write.
1789N/A * @param unique <code>true</code> if the remote files should be unique,
1789N/A * in which case the STOU command will be used.
1789N/A * @return the {@link java.io.OutputStream} from the data connection or
1789N/A * <code>null</code> if the command was unsuccessful.
1789N/A * @throws IOException if an error occured during the transmission.
1789N/A */
5865N/A public OutputStream putFileStream(String name, boolean unique)
5865N/A throws sun.net.ftp.FtpProtocolException, IOException
5865N/A {
1789N/A String cmd = unique ? "STOU " : "STOR ";
1789N/A Socket s = openDataConnection(cmd + name);
1789N/A if (s == null) {
1789N/A return null;
1789N/A }
5865N/A boolean bm = (type == TransferType.BINARY);
5865N/A return new sun.net.TelnetOutputStream(s.getOutputStream(), bm);
1789N/A }
1789N/A
1789N/A /**
1789N/A * Transfers a file from the client to the server (aka a <I>put</I>)
1789N/A * by sending the STOR command. The content of the <code>InputStream</code>
1789N/A * passed in argument is written into the remote file, overwriting any
1789N/A * existing data.
1789N/A *
1789N/A * A new file is created at the server site if the file specified does
1789N/A * not already exist.
1789N/A *
1789N/A * @param name the name of the remote file to write.
1789N/A * @param local the <code>InputStream</code> that points to the data to
1789N/A * transfer.
1789N/A * @param unique <code>true</code> if the remote file should be unique
1789N/A * (i.e. not already existing), <code>false</code> otherwise.
1789N/A * @return <code>true</code> if the transfer was successful.
1789N/A * @throws IOException if an error occured during the transmission.
1789N/A * @see #getLastFileName()
1789N/A */
1789N/A public sun.net.ftp.FtpClient putFile(String name, InputStream local, boolean unique) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A String cmd = unique ? "STOU " : "STOR ";
1789N/A int mtu = 1500;
1789N/A if (type == TransferType.BINARY) {
1789N/A Socket s = openDataConnection(cmd + name);
1789N/A OutputStream remote = createOutputStream(s.getOutputStream());
1789N/A byte[] buf = new byte[mtu * 10];
1789N/A int l;
1789N/A while ((l = local.read(buf)) >= 0) {
1789N/A if (l > 0) {
1789N/A remote.write(buf, 0, l);
1789N/A }
1789N/A }
1789N/A remote.close();
1789N/A }
1789N/A return completePending();
1789N/A }
1789N/A
1789N/A /**
1789N/A * Sends the APPE command to the server in order to transfer a data stream
1789N/A * passed in argument and append it to the content of the specified remote
1789N/A * file.
1789N/A *
1789N/A * @param name A <code>String</code> containing the name of the remote file
1789N/A * to append to.
1789N/A * @param local The <code>InputStream</code> providing access to the data
1789N/A * to be appended.
1789N/A * @return <code>true</code> if the transfer was successful.
1789N/A * @throws IOException if an error occured during the transmission.
1789N/A */
1789N/A public sun.net.ftp.FtpClient appendFile(String name, InputStream local) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A int mtu = 1500;
1789N/A Socket s = openDataConnection("APPE " + name);
1789N/A OutputStream remote = createOutputStream(s.getOutputStream());
1789N/A byte[] buf = new byte[mtu * 10];
1789N/A int l;
1789N/A while ((l = local.read(buf)) >= 0) {
1789N/A if (l > 0) {
1789N/A remote.write(buf, 0, l);
1789N/A }
1789N/A }
1789N/A remote.close();
1789N/A return completePending();
1789N/A }
1789N/A
1789N/A /**
1789N/A * Renames a file on the server.
1789N/A *
1789N/A * @param from the name of the file being renamed
1789N/A * @param to the new name for the file
1789N/A * @throws IOException if the command fails
1789N/A */
1789N/A public sun.net.ftp.FtpClient rename(String from, String to) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("RNFR " + from);
1789N/A issueCommandCheck("RNTO " + to);
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Deletes a file on the server.
1789N/A *
1789N/A * @param name a <code>String</code> containing the name of the file
1789N/A * to delete.
1789N/A * @return <code>true</code> if the command was successful
1789N/A * @throws IOException if an error occured during the exchange
1789N/A */
1789N/A public sun.net.ftp.FtpClient deleteFile(String name) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("DELE " + name);
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Creates a new directory on the server.
1789N/A *
1789N/A * @param name a <code>String</code> containing the name of the directory
1789N/A * to create.
1789N/A * @return <code>true</code> if the operation was successful.
1789N/A * @throws IOException if an error occured during the exchange
1789N/A */
1789N/A public sun.net.ftp.FtpClient makeDirectory(String name) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("MKD " + name);
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Removes a directory on the server.
1789N/A *
1789N/A * @param name a <code>String</code> containing the name of the directory
1789N/A * to remove.
1789N/A *
1789N/A * @return <code>true</code> if the operation was successful.
1789N/A * @throws IOException if an error occured during the exchange.
1789N/A */
1789N/A public sun.net.ftp.FtpClient removeDirectory(String name) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("RMD " + name);
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Sends a No-operation command. It's useful for testing the connection
1789N/A * status or as a <I>keep alive</I> mechanism.
1789N/A *
1789N/A * @throws FtpProtocolException if the command fails
1789N/A */
1789N/A public sun.net.ftp.FtpClient noop() throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("NOOP");
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Sends the STAT command to the server.
1789N/A * This can be used while a data connection is open to get a status
1789N/A * on the current transfer, in that case the parameter should be
1789N/A * <code>null</code>.
1789N/A * If used between file transfers, it may have a pathname as argument
1789N/A * in which case it will work as the LIST command except no data
1789N/A * connection will be created.
1789N/A *
1789N/A * @param name an optional <code>String</code> containing the pathname
1789N/A * the STAT command should apply to.
1789N/A * @return the response from the server or <code>null</code> if the
1789N/A * command failed.
1789N/A * @throws IOException if an error occured during the transmission.
1789N/A */
1789N/A public String getStatus(String name) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck((name == null ? "STAT" : "STAT " + name));
1789N/A /*
1789N/A * A typical response will be:
1789N/A * 213-status of t32.gif:
1789N/A * -rw-r--r-- 1 jcc staff 247445 Feb 17 1998 t32.gif
1789N/A * 213 End of Status
1789N/A *
1789N/A * or
1789N/A *
1789N/A * 211-jsn FTP server status:
1789N/A * Version wu-2.6.2+Sun
1789N/A * Connected to localhost (::1)
1789N/A * Logged in as jccollet
1789N/A * TYPE: ASCII, FORM: Nonprint; STRUcture: File; transfer MODE: Stream
1789N/A * No data connection
1789N/A * 0 data bytes received in 0 files
1789N/A * 0 data bytes transmitted in 0 files
1789N/A * 0 data bytes total in 0 files
1789N/A * 53 traffic bytes received in 0 transfers
1789N/A * 485 traffic bytes transmitted in 0 transfers
1789N/A * 587 traffic bytes total in 0 transfers
1789N/A * 211 End of status
1789N/A *
1789N/A * So we need to remove the 1st and last line
1789N/A */
1789N/A Vector<String> resp = getResponseStrings();
1789N/A StringBuffer sb = new StringBuffer();
1789N/A for (int i = 1; i < resp.size() - 1; i++) {
1789N/A sb.append(resp.get(i));
1789N/A }
1789N/A return sb.toString();
1789N/A }
1789N/A
1789N/A /**
1789N/A * Sends the FEAT command to the server and returns the list of supported
1789N/A * features in the form of strings.
1789N/A *
1789N/A * The features are the supported commands, like AUTH TLS, PROT or PASV.
1789N/A * See the RFCs for a complete list.
1789N/A *
1789N/A * Note that not all FTP servers support that command, in which case
1789N/A * the method will return <code>null</code>
1789N/A *
1789N/A * @return a <code>List</code> of <code>Strings</code> describing the
1789N/A * supported additional features, or <code>null</code>
1789N/A * if the command is not supported.
1789N/A * @throws IOException if an error occurs during the transmission.
1789N/A */
1789N/A public List<String> getFeatures() throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A /*
1789N/A * The FEAT command, when implemented will return something like:
1789N/A *
1789N/A * 211-Features:
1789N/A * AUTH TLS
1789N/A * PBSZ
1789N/A * PROT
1789N/A * EPSV
1789N/A * EPRT
1789N/A * PASV
1789N/A * REST STREAM
1789N/A * 211 END
1789N/A */
1789N/A ArrayList<String> features = new ArrayList<String>();
1789N/A issueCommandCheck("FEAT");
1789N/A Vector<String> resp = getResponseStrings();
1789N/A // Note that we start at index 1 to skip the 1st line (211-...)
1789N/A // and we stop before the last line.
1789N/A for (int i = 1; i < resp.size() - 1; i++) {
1789N/A String s = resp.get(i);
1789N/A // Get rid of leading space and trailing newline
1789N/A features.add(s.substring(1, s.length() - 1));
1789N/A }
1789N/A return features;
1789N/A }
1789N/A
1789N/A /**
1789N/A * sends the ABOR command to the server.
1789N/A * It tells the server to stop the previous command or transfer.
1789N/A *
1789N/A * @return <code>true</code> if the command was successful.
1789N/A * @throws IOException if an error occured during the transmission.
1789N/A */
1789N/A public sun.net.ftp.FtpClient abort() throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("ABOR");
1789N/A // TODO: Must check the ReplyCode:
1789N/A /*
1789N/A * From the RFC:
1789N/A * There are two cases for the server upon receipt of this
1789N/A * command: (1) the FTP service command was already completed,
1789N/A * or (2) the FTP service command is still in progress.
1789N/A * In the first case, the server closes the data connection
1789N/A * (if it is open) and responds with a 226 reply, indicating
1789N/A * that the abort command was successfully processed.
1789N/A * In the second case, the server aborts the FTP service in
1789N/A * progress and closes the data connection, returning a 426
1789N/A * reply to indicate that the service request terminated
1789N/A * abnormally. The server then sends a 226 reply,
1789N/A * indicating that the abort command was successfully
1789N/A * processed.
1789N/A */
1789N/A
1789N/A
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Some methods do not wait until completion before returning, so this
1789N/A * method can be called to wait until completion. This is typically the case
1789N/A * with commands that trigger a transfer like {@link #getFileStream(String)}.
1789N/A * So this method should be called before accessing information related to
1789N/A * such a command.
1789N/A * <p>This method will actually block reading on the command channel for a
1789N/A * notification from the server that the command is finished. Such a
1789N/A * notification often carries extra information concerning the completion
1789N/A * of the pending action (e.g. number of bytes transfered).</p>
1789N/A * <p>Note that this will return true immediately if no command or action
1789N/A * is pending</p>
1789N/A * <p>It should be also noted that most methods issuing commands to the ftp
1789N/A * server will call this method if a previous command is pending.
1789N/A * <p>Example of use:
1789N/A * <pre>
1789N/A * InputStream in = cl.getFileStream("file");
1789N/A * ...
1789N/A * cl.completePending();
1789N/A * long size = cl.getLastTransferSize();
1789N/A * </pre>
1789N/A * On the other hand, it's not necessary in a case like:
1789N/A * <pre>
1789N/A * InputStream in = cl.getFileStream("file");
1789N/A * // read content
1789N/A * ...
1789N/A * cl.logout();
1789N/A * </pre>
1789N/A * <p>Since {@link #logout()} will call completePending() if necessary.</p>
1789N/A * @return <code>true</code> if the completion was successful or if no
1789N/A * action was pending.
1789N/A * @throws IOException
1789N/A */
1789N/A public sun.net.ftp.FtpClient completePending() throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A while (replyPending) {
1789N/A replyPending = false;
1789N/A if (!readReply()) {
1789N/A throw new sun.net.ftp.FtpProtocolException(getLastResponseString(), lastReplyCode);
1789N/A }
1789N/A }
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Reinitializes the USER parameters on the FTP server
1789N/A *
1789N/A * @throws FtpProtocolException if the command fails
1789N/A */
1789N/A public sun.net.ftp.FtpClient reInit() throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("REIN");
1789N/A loggedIn = false;
1789N/A if (useCrypto) {
1789N/A if (server instanceof SSLSocket) {
1789N/A javax.net.ssl.SSLSession session = ((SSLSocket) server).getSession();
1789N/A session.invalidate();
1789N/A // Restore previous socket and streams
1789N/A server = oldSocket;
1789N/A oldSocket = null;
1789N/A try {
1789N/A out = new PrintStream(new BufferedOutputStream(server.getOutputStream()),
1789N/A true, encoding);
1789N/A } catch (UnsupportedEncodingException e) {
1789N/A throw new InternalError(encoding + "encoding not found");
1789N/A }
1789N/A in = new BufferedInputStream(server.getInputStream());
1789N/A }
1789N/A }
1789N/A useCrypto = false;
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Changes the transfer type (binary, ascii, ebcdic) and issue the
1789N/A * proper command (e.g. TYPE A) to the server.
1789N/A *
1789N/A * @param type the <code>FtpTransferType</code> to use.
1789N/A * @return This FtpClient
1789N/A * @throws IOException if an error occurs during transmission.
1789N/A */
1789N/A public sun.net.ftp.FtpClient setType(TransferType type) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A String cmd = "NOOP";
1789N/A
1789N/A this.type = type;
1789N/A if (type == TransferType.ASCII) {
1789N/A cmd = "TYPE A";
1789N/A }
1789N/A if (type == TransferType.BINARY) {
1789N/A cmd = "TYPE I";
1789N/A }
1789N/A if (type == TransferType.EBCDIC) {
1789N/A cmd = "TYPE E";
1789N/A }
1789N/A issueCommandCheck(cmd);
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Issues a LIST command to the server to get the current directory
1789N/A * listing, and returns the InputStream from the data connection.
1789N/A * {@link #completePending()} <b>has</b> to be called once the application
1789N/A * is finished writing to the stream.
1789N/A *
1789N/A * @param path the pathname of the directory to list, or <code>null</code>
1789N/A * for the current working directory.
1789N/A * @return the <code>InputStream</code> from the resulting data connection
1789N/A * @throws IOException if an error occurs during the transmission.
1789N/A * @see #changeDirectory(String)
1789N/A * @see #listFiles(String)
1789N/A */
1789N/A public InputStream list(String path) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A Socket s;
1789N/A s = openDataConnection(path == null ? "LIST" : "LIST " + path);
1789N/A if (s != null) {
1789N/A return createInputStream(s.getInputStream());
1789N/A }
1789N/A return null;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Issues a NLST path command to server to get the specified directory
1789N/A * content. It differs from {@link #list(String)} method by the fact that
1789N/A * it will only list the file names which would make the parsing of the
1789N/A * somewhat easier.
1789N/A *
1789N/A * {@link #completePending()} <b>has</b> to be called once the application
1789N/A * is finished writing to the stream.
1789N/A *
1789N/A * @param path a <code>String</code> containing the pathname of the
1789N/A * directory to list or <code>null</code> for the current working
1789N/A * directory.
1789N/A * @return the <code>InputStream</code> from the resulting data connection
1789N/A * @throws IOException if an error occurs during the transmission.
1789N/A */
1789N/A public InputStream nameList(String path) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A Socket s;
1789N/A s = openDataConnection("NLST " + path);
1789N/A if (s != null) {
1789N/A return createInputStream(s.getInputStream());
1789N/A }
1789N/A return null;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Issues the SIZE [path] command to the server to get the size of a
1789N/A * specific file on the server.
1789N/A * Note that this command may not be supported by the server. In which
1789N/A * case -1 will be returned.
1789N/A *
1789N/A * @param path a <code>String</code> containing the pathname of the
1789N/A * file.
1789N/A * @return a <code>long</code> containing the size of the file or -1 if
1789N/A * the server returned an error, which can be checked with
1789N/A * {@link #getLastReplyCode()}.
1789N/A * @throws IOException if an error occurs during the transmission.
1789N/A */
1789N/A public long getSize(String path) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A if (path == null || path.length() == 0) {
1789N/A throw new IllegalArgumentException("path can't be null or empty");
1789N/A }
1789N/A issueCommandCheck("SIZE " + path);
1789N/A if (lastReplyCode == FtpReplyCode.FILE_STATUS) {
1789N/A String s = getResponseString();
1789N/A s = s.substring(4, s.length() - 1);
1789N/A return Long.parseLong(s);
1789N/A }
1789N/A return -1;
1789N/A }
1789N/A private static String[] MDTMformats = {
1789N/A "yyyyMMddHHmmss.SSS",
1789N/A "yyyyMMddHHmmss"
1789N/A };
1789N/A private static SimpleDateFormat[] dateFormats = new SimpleDateFormat[MDTMformats.length];
1789N/A
1789N/A static {
1789N/A for (int i = 0; i < MDTMformats.length; i++) {
1789N/A dateFormats[i] = new SimpleDateFormat(MDTMformats[i]);
1789N/A dateFormats[i].setTimeZone(TimeZone.getTimeZone("GMT"));
1789N/A }
1789N/A }
1789N/A
1789N/A /**
1789N/A * Issues the MDTM [path] command to the server to get the modification
1789N/A * time of a specific file on the server.
1789N/A * Note that this command may not be supported by the server, in which
1789N/A * case <code>null</code> will be returned.
1789N/A *
1789N/A * @param path a <code>String</code> containing the pathname of the file.
1789N/A * @return a <code>Date</code> representing the last modification time
1789N/A * or <code>null</code> if the server returned an error, which
1789N/A * can be checked with {@link #getLastReplyCode()}.
1789N/A * @throws IOException if an error occurs during the transmission.
1789N/A */
1789N/A public Date getLastModified(String path) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("MDTM " + path);
1789N/A if (lastReplyCode == FtpReplyCode.FILE_STATUS) {
1789N/A String s = getResponseString().substring(4);
1789N/A Date d = null;
1789N/A for (SimpleDateFormat dateFormat : dateFormats) {
1789N/A try {
1789N/A d = dateFormat.parse(s);
1789N/A } catch (ParseException ex) {
1789N/A }
1789N/A if (d != null) {
1789N/A return d;
1789N/A }
1789N/A }
1789N/A }
1789N/A return null;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Sets the parser used to handle the directory output to the specified
1789N/A * one. By default the parser is set to one that can handle most FTP
1789N/A * servers output (Unix base mostly). However it may be necessary for
1789N/A * and application to provide its own parser due to some uncommon
1789N/A * output format.
1789N/A *
1789N/A * @param p The <code>FtpDirParser</code> to use.
1789N/A * @see #listFiles(String)
1789N/A */
1789N/A public sun.net.ftp.FtpClient setDirParser(FtpDirParser p) {
1789N/A parser = p;
1789N/A return this;
1789N/A }
1789N/A
1789N/A private class FtpFileIterator implements Iterator<FtpDirEntry>, Closeable {
1789N/A
1789N/A private BufferedReader in = null;
1789N/A private FtpDirEntry nextFile = null;
1789N/A private FtpDirParser fparser = null;
1789N/A private boolean eof = false;
1789N/A
1789N/A public FtpFileIterator(FtpDirParser p, BufferedReader in) {
1789N/A this.in = in;
1789N/A this.fparser = p;
1789N/A readNext();
1789N/A }
1789N/A
1789N/A private void readNext() {
1789N/A nextFile = null;
1789N/A if (eof) {
1789N/A return;
1789N/A }
1789N/A String line = null;
1789N/A try {
1789N/A do {
1789N/A line = in.readLine();
1789N/A if (line != null) {
1789N/A nextFile = fparser.parseLine(line);
1789N/A if (nextFile != null) {
1789N/A return;
1789N/A }
1789N/A }
1789N/A } while (line != null);
1789N/A in.close();
1789N/A } catch (IOException iOException) {
1789N/A }
1789N/A eof = true;
1789N/A }
1789N/A
1789N/A public boolean hasNext() {
1789N/A return nextFile != null;
1789N/A }
1789N/A
1789N/A public FtpDirEntry next() {
1789N/A FtpDirEntry ret = nextFile;
1789N/A readNext();
1789N/A return ret;
1789N/A }
1789N/A
1789N/A public void remove() {
1789N/A throw new UnsupportedOperationException("Not supported yet.");
1789N/A }
1789N/A
1789N/A public void close() throws IOException {
1789N/A if (in != null && !eof) {
1789N/A in.close();
1789N/A }
1789N/A eof = true;
1789N/A nextFile = null;
1789N/A }
1789N/A }
1789N/A
1789N/A /**
1789N/A * Issues a MLSD command to the server to get the specified directory
1789N/A * listing and applies the current parser to create an Iterator of
1789N/A * {@link java.net.ftp.FtpDirEntry}. Note that the Iterator returned is also a
1789N/A * {@link java.io.Closeable}.
1789N/A * If the server doesn't support the MLSD command, the LIST command is used
1789N/A * instead.
1789N/A *
1789N/A * {@link #completePending()} <b>has</b> to be called once the application
1789N/A * is finished iterating through the files.
1789N/A *
1789N/A * @param path the pathname of the directory to list or <code>null</code>
1789N/A * for the current working directoty.
1789N/A * @return a <code>Iterator</code> of files or <code>null</code> if the
1789N/A * command failed.
1789N/A * @throws IOException if an error occured during the transmission
1789N/A * @see #setDirParser(FtpDirParser)
1789N/A * @see #changeDirectory(String)
1789N/A */
1789N/A public Iterator<FtpDirEntry> listFiles(String path) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A Socket s = null;
1789N/A BufferedReader sin = null;
1789N/A try {
1789N/A s = openDataConnection(path == null ? "MLSD" : "MLSD " + path);
1789N/A } catch (sun.net.ftp.FtpProtocolException FtpException) {
1789N/A // The server doesn't understand new MLSD command, ignore and fall
1789N/A // back to LIST
1789N/A }
1789N/A
1789N/A if (s != null) {
1789N/A sin = new BufferedReader(new InputStreamReader(s.getInputStream()));
1789N/A return new FtpFileIterator(mlsxParser, sin);
1789N/A } else {
1789N/A s = openDataConnection(path == null ? "LIST" : "LIST " + path);
1789N/A if (s != null) {
1789N/A sin = new BufferedReader(new InputStreamReader(s.getInputStream()));
1789N/A return new FtpFileIterator(parser, sin);
1789N/A }
1789N/A }
1789N/A return null;
1789N/A }
1789N/A
1789N/A private boolean sendSecurityData(byte[] buf) throws IOException {
1789N/A BASE64Encoder encoder = new BASE64Encoder();
1789N/A String s = encoder.encode(buf);
1789N/A return issueCommand("ADAT " + s);
1789N/A }
1789N/A
1789N/A private byte[] getSecurityData() {
1789N/A String s = getLastResponseString();
1789N/A if (s.substring(4, 9).equalsIgnoreCase("ADAT=")) {
1789N/A BASE64Decoder decoder = new BASE64Decoder();
1789N/A try {
1789N/A // Need to get rid of the leading '315 ADAT='
1789N/A // and the trailing newline
1789N/A return decoder.decodeBuffer(s.substring(9, s.length() - 1));
1789N/A } catch (IOException e) {
1789N/A //
1789N/A }
1789N/A }
1789N/A return null;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Attempts to use Kerberos GSSAPI as an authentication mechanism with the
1789N/A * ftp server. This will issue an <code>AUTH GSSAPI</code> command, and if
1789N/A * it is accepted by the server, will followup with <code>ADAT</code>
1789N/A * command to exchange the various tokens until authentification is
1789N/A * successful. This conforms to Appendix I of RFC 2228.
1789N/A *
1789N/A * @return <code>true</code> if authentication was successful.
1789N/A * @throws IOException if an error occurs during the transmission.
1789N/A */
1789N/A public sun.net.ftp.FtpClient useKerberos() throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A /*
1789N/A * Comment out for the moment since it's not in use and would create
1789N/A * needless cross-package links.
1789N/A *
1789N/A issueCommandCheck("AUTH GSSAPI");
1789N/A if (lastReplyCode != FtpReplyCode.NEED_ADAT)
1789N/A throw new sun.net.ftp.FtpProtocolException("Unexpected reply from server");
1789N/A try {
1789N/A GSSManager manager = GSSManager.getInstance();
1789N/A GSSName name = manager.createName("SERVICE:ftp@"+
1789N/A serverAddr.getHostName(), null);
1789N/A GSSContext context = manager.createContext(name, null, null,
1789N/A GSSContext.DEFAULT_LIFETIME);
1789N/A context.requestMutualAuth(true);
1789N/A context.requestReplayDet(true);
1789N/A context.requestSequenceDet(true);
1789N/A context.requestCredDeleg(true);
1789N/A byte []inToken = new byte[0];
1789N/A while (!context.isEstablished()) {
1789N/A byte[] outToken
1789N/A = context.initSecContext(inToken, 0, inToken.length);
1789N/A // send the output token if generated
1789N/A if (outToken != null) {
1789N/A if (sendSecurityData(outToken)) {
1789N/A inToken = getSecurityData();
1789N/A }
1789N/A }
1789N/A }
1789N/A loggedIn = true;
1789N/A } catch (GSSException e) {
1789N/A
1789N/A }
1789N/A */
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Returns the Welcome string the server sent during initial connection.
1789N/A *
1789N/A * @return a <code>String</code> containing the message the server
1789N/A * returned during connection or <code>null</code>.
1789N/A */
1789N/A public String getWelcomeMsg() {
1789N/A return welcomeMsg;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Returns the last reply code sent by the server.
1789N/A *
1789N/A * @return the lastReplyCode
1789N/A */
1789N/A public FtpReplyCode getLastReplyCode() {
1789N/A return lastReplyCode;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Returns the last response string sent by the server.
1789N/A *
1789N/A * @return the message string, which can be quite long, last returned
1789N/A * by the server.
1789N/A */
1789N/A public String getLastResponseString() {
1789N/A StringBuffer sb = new StringBuffer();
1789N/A if (serverResponse != null) {
1789N/A for (String l : serverResponse) {
1789N/A if (l != null) {
1789N/A sb.append(l);
1789N/A }
1789N/A }
1789N/A }
1789N/A return sb.toString();
1789N/A }
1789N/A
1789N/A /**
1789N/A * Returns, when available, the size of the latest started transfer.
1789N/A * This is retreived by parsing the response string received as an initial
1789N/A * response to a RETR or similar request.
1789N/A *
1789N/A * @return the size of the latest transfer or -1 if either there was no
1789N/A * transfer or the information was unavailable.
1789N/A */
1789N/A public long getLastTransferSize() {
1789N/A return lastTransSize;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Returns, when available, the remote name of the last transfered file.
1789N/A * This is mainly useful for "put" operation when the unique flag was
1789N/A * set since it allows to recover the unique file name created on the
1789N/A * server which may be different from the one submitted with the command.
1789N/A *
1789N/A * @return the name the latest transfered file remote name, or
1789N/A * <code>null</code> if that information is unavailable.
1789N/A */
1789N/A public String getLastFileName() {
1789N/A return lastFileName;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Attempts to switch to a secure, encrypted connection. This is done by
1789N/A * sending the "AUTH TLS" command.
1789N/A * <p>See <a href="http://www.ietf.org/rfc/rfc4217.txt">RFC 4217</a></p>
1789N/A * If successful this will establish a secure command channel with the
1789N/A * server, it will also make it so that all other transfers (e.g. a RETR
1789N/A * command) will be done over an encrypted channel as well unless a
1789N/A * {@link #reInit()} command or a {@link #endSecureSession()} command is issued.
1789N/A *
1789N/A * @return <code>true</code> if the operation was successful.
1789N/A * @throws IOException if an error occured during the transmission.
1789N/A * @see #endSecureSession()
1789N/A */
1789N/A public sun.net.ftp.FtpClient startSecureSession() throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A if (!isConnected()) {
1789N/A throw new sun.net.ftp.FtpProtocolException("Not connected yet", FtpReplyCode.BAD_SEQUENCE);
1789N/A }
1789N/A if (sslFact == null) {
1789N/A try {
1789N/A sslFact = (SSLSocketFactory) SSLSocketFactory.getDefault();
1789N/A } catch (Exception e) {
1789N/A throw new IOException(e.getLocalizedMessage());
1789N/A }
1789N/A }
1789N/A issueCommandCheck("AUTH TLS");
1789N/A Socket s = null;
1789N/A try {
1789N/A s = sslFact.createSocket(server, serverAddr.getHostName(), serverAddr.getPort(), true);
1789N/A } catch (javax.net.ssl.SSLException ssle) {
1789N/A try {
1789N/A disconnect();
1789N/A } catch (Exception e) {
1789N/A }
1789N/A throw ssle;
1789N/A }
1789N/A // Remember underlying socket so we can restore it later
1789N/A oldSocket = server;
1789N/A server = s;
1789N/A try {
1789N/A out = new PrintStream(new BufferedOutputStream(server.getOutputStream()),
1789N/A true, encoding);
1789N/A } catch (UnsupportedEncodingException e) {
1789N/A throw new InternalError(encoding + "encoding not found");
1789N/A }
1789N/A in = new BufferedInputStream(server.getInputStream());
1789N/A
1789N/A issueCommandCheck("PBSZ 0");
1789N/A issueCommandCheck("PROT P");
1789N/A useCrypto = true;
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Sends a <code>CCC</code> command followed by a <code>PROT C</code>
1789N/A * command to the server terminating an encrypted session and reverting
1789N/A * back to a non crypted transmission.
1789N/A *
1789N/A * @return <code>true</code> if the operation was successful.
1789N/A * @throws IOException if an error occured during transmission.
1789N/A * @see #startSecureSession()
1789N/A */
1789N/A public sun.net.ftp.FtpClient endSecureSession() throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A if (!useCrypto) {
1789N/A return this;
1789N/A }
1789N/A
1789N/A issueCommandCheck("CCC");
1789N/A issueCommandCheck("PROT C");
1789N/A useCrypto = false;
1789N/A // Restore previous socket and streams
1789N/A server = oldSocket;
1789N/A oldSocket = null;
1789N/A try {
1789N/A out = new PrintStream(new BufferedOutputStream(server.getOutputStream()),
1789N/A true, encoding);
1789N/A } catch (UnsupportedEncodingException e) {
1789N/A throw new InternalError(encoding + "encoding not found");
1789N/A }
1789N/A in = new BufferedInputStream(server.getInputStream());
1789N/A
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Sends the "Allocate" (ALLO) command to the server telling it to
1789N/A * pre-allocate the specified number of bytes for the next transfer.
1789N/A *
1789N/A * @param size The number of bytes to allocate.
1789N/A * @return <code>true</code> if the operation was successful.
1789N/A * @throws IOException if an error occured during the transmission.
1789N/A */
1789N/A public sun.net.ftp.FtpClient allocate(long size) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("ALLO " + size);
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Sends the "Structure Mount" (SMNT) command to the server. This let the
1789N/A * user mount a different file system data structure without altering his
1789N/A * login or accounting information.
1789N/A *
1789N/A * @param struct a <code>String</code> containing the name of the
1789N/A * structure to mount.
1789N/A * @return <code>true</code> if the operation was successful.
1789N/A * @throws IOException if an error occured during the transmission.
1789N/A */
1789N/A public sun.net.ftp.FtpClient structureMount(String struct) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("SMNT " + struct);
1789N/A return this;
1789N/A }
1789N/A
1789N/A /**
1789N/A * Sends a SYST (System) command to the server and returns the String
1789N/A * sent back by the server describing the operating system at the
1789N/A * server.
1789N/A *
1789N/A * @return a <code>String</code> describing the OS, or <code>null</code>
1789N/A * if the operation was not successful.
1789N/A * @throws IOException if an error occured during the transmission.
1789N/A */
1789N/A public String getSystem() throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("SYST");
1789N/A /*
1789N/A * 215 UNIX Type: L8 Version: SUNOS
1789N/A */
1789N/A String resp = getResponseString();
1789N/A // Get rid of the leading code and blank
1789N/A return resp.substring(4);
1789N/A }
1789N/A
1789N/A /**
1789N/A * Sends the HELP command to the server, with an optional command, like
1789N/A * SITE, and returns the text sent back by the server.
1789N/A *
1789N/A * @param cmd the command for which the help is requested or
1789N/A * <code>null</code> for the general help
1789N/A * @return a <code>String</code> containing the text sent back by the
1789N/A * server, or <code>null</code> if the command failed.
1789N/A * @throws IOException if an error occured during transmission
1789N/A */
1789N/A public String getHelp(String cmd) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("HELP " + cmd);
1789N/A /**
1789N/A *
1789N/A * HELP
1789N/A * 214-The following commands are implemented.
1789N/A * USER EPRT STRU ALLO DELE SYST RMD MDTM ADAT
1789N/A * PASS EPSV MODE REST CWD STAT PWD PROT
1789N/A * QUIT LPRT RETR RNFR LIST HELP CDUP PBSZ
1789N/A * PORT LPSV STOR RNTO NLST NOOP STOU AUTH
1789N/A * PASV TYPE APPE ABOR SITE MKD SIZE CCC
1789N/A * 214 Direct comments to ftp-bugs@jsn.
1789N/A *
1789N/A * HELP SITE
1789N/A * 214-The following SITE commands are implemented.
1789N/A * UMASK HELP GROUPS
1789N/A * IDLE ALIAS CHECKMETHOD
1789N/A * CHMOD CDPATH CHECKSUM
1789N/A * 214 Direct comments to ftp-bugs@jsn.
1789N/A */
1789N/A Vector<String> resp = getResponseStrings();
1789N/A if (resp.size() == 1) {
1789N/A // Single line response
1789N/A return resp.get(0).substring(4);
1789N/A }
1789N/A // on multiple lines answers, like the ones above, remove 1st and last
1789N/A // line, concat the the others.
1789N/A StringBuffer sb = new StringBuffer();
1789N/A for (int i = 1; i < resp.size() - 1; i++) {
1789N/A sb.append(resp.get(i).substring(3));
1789N/A }
1789N/A return sb.toString();
1789N/A }
1789N/A
1789N/A /**
1789N/A * Sends the SITE command to the server. This is used by the server
1789N/A * to provide services specific to his system that are essential
1789N/A * to file transfer.
1789N/A *
1789N/A * @param cmd the command to be sent.
1789N/A * @return <code>true</code> if the command was successful.
1789N/A * @throws IOException if an error occured during transmission
1789N/A */
1789N/A public sun.net.ftp.FtpClient siteCmd(String cmd) throws sun.net.ftp.FtpProtocolException, IOException {
1789N/A issueCommandCheck("SITE " + cmd);
1789N/A return this;
1789N/A }
1789N/A}