Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.apache.commons.net.ftp;
 
 
 import  org.apache.commons.net.util.Base64;
 import  org.apache.commons.net.util.SSLContextUtils;
 import  org.apache.commons.net.util.TrustManagerUtils;

FTP over SSL processing. If desired, the JVM property -Djavax.net.debug=all can be used to see wire-level SSL details.

Version:
$Id: FTPSClient.java 1489533 2013-06-04 17:49:00Z sebb $
Since:
2.0
 
 public class FTPSClient extends FTPClient {
 
 // From http://www.iana.org/assignments/port-numbers
 
 //    ftps-data   989/tcp    ftp protocol, data, over TLS/SSL
 //    ftps-data   989/udp    ftp protocol, data, over TLS/SSL
 //    ftps        990/tcp    ftp protocol, control, over TLS/SSL
 //    ftps        990/udp    ftp protocol, control, over TLS/SSL
 
     public static final int DEFAULT_FTPS_DATA_PORT = 989;
     public static final int DEFAULT_FTPS_PORT = 990;

    
The value that I can set in PROT command (C = Clear, P = Protected)
 
     private static final String[] PROT_COMMAND_VALUE = {"C","E","S","P"};
    
Default PROT Command
 
     private static final String DEFAULT_PROT = "C";
    
Default secure socket protocol name, i.e. TLS
 
     private static final String DEFAULT_PROTOCOL = "TLS";

    
The AUTH (Authentication/Security Mechanism) command.
 
     private static final String CMD_AUTH = "AUTH";
    
The ADAT (Authentication/Security Data) command.
 
     private static final String CMD_ADAT = "ADAT";
    
The PROT (Data Channel Protection Level) command.
 
     private static final String CMD_PROT = "PROT";
    
The PBSZ (Protection Buffer Size) command.
 
     private static final String CMD_PBSZ = "PBSZ";
    
The MIC (Integrity Protected Command) command.
 
     private static final String CMD_MIC = "MIC";
    
The CONF (Confidentiality Protected Command) command.
 
     private static final String CMD_CONF = "CONF";
    
The ENC (Privacy Protected Command) command.
 
     private static final String CMD_ENC = "ENC";
    
The CCC (Clear Command Channel) command.
 
     private static final String CMD_CCC = "CCC";

    
The security mode. (True - Implicit Mode / False - Explicit Mode)
 
     private final boolean isImplicit;
    
The secure socket protocol to be used, e.g. SSL/TLS.
 
     private final String protocol;
    
The AUTH Command value
 
     private String auth = ;
    
The context object.
 
     private SSLContext context;
    
The socket object.
 
     private Socket plainSocket;
    
Controls whether a new SSL session may be established by this socket. Default true.
 
     private boolean isCreation = true;
    
The use client mode flag.
 
     private boolean isClientMode = true;
    
The need client auth flag.
 
     private boolean isNeedClientAuth = false;
    
The want client auth flag.
 
     private boolean isWantClientAuth = false;
    
The cipher suites
 
     private String[] suites = null;
    
The protocol versions
    private String[] protocols = null;

    
The FTPS TrustManager implementation, default validate only: TrustManagerUtils.getValidateServerCertificateTrustManager().
    private TrustManager trustManager = TrustManagerUtils.getValidateServerCertificateTrustManager();

    
The KeyManager, default null (i.e. use system default).
    private KeyManager keyManager = null;

    
Constructor for FTPSClient, calls FTPSClient(String, boolean). Sets protocol to DEFAULT_PROTOCOL - i.e. TLS - and security mode to explicit (isImplicit = false)
    public FTPSClient() {
        this(false);
    }

    
Constructor for FTPSClient, using DEFAULT_PROTOCOL - i.e. TLS Calls FTPSClient(String, boolean)

Parameters:
isImplicit The security mode (Implicit/Explicit).
    public FTPSClient(boolean isImplicit) {
        this(isImplicit);
    }

    
Constructor for FTPSClient, using explict mode, calls FTPSClient(String, boolean).

Parameters:
protocol the protocol to use
    public FTPSClient(String protocol) {
        this(protocolfalse);
    }

    
Constructor for FTPSClient allowing specification of protocol and security mode. If isImplicit is true, the port is set to DEFAULT_FTPS_PORT i.e. 990. The default TrustManager is set from TrustManagerUtils.getValidateServerCertificateTrustManager()

Parameters:
protocol the protocol
isImplicit The security mode(Implicit/Explicit).
    public FTPSClient(String protocolboolean isImplicit) {
        super();
        this. = protocol;
        this. = isImplicit;
        if (isImplicit) {
            setDefaultPort();
        }
    }

    
Constructor for FTPSClient, using DEFAULT_PROTOCOL - i.e. TLS The default TrustManager is set from TrustManagerUtils.getValidateServerCertificateTrustManager()

Parameters:
isImplicit The security mode(Implicit/Explicit).
context A pre-configured SSL Context
    public FTPSClient(boolean isImplicitSSLContext context) {
        this(isImplicit);
        this. = context;
    }

    
Constructor for FTPSClient, using DEFAULT_PROTOCOL - i.e. TLS and isImplicit false Calls FTPSClient(boolean, SSLContext)

Parameters:
context A pre-configured SSL Context
    public FTPSClient(SSLContext context) {
        this(falsecontext);
    }


    
Set AUTH command use value. This processing is done before connected processing.

Parameters:
auth AUTH command use value.
    public void setAuthValue(String auth) {
        this. = auth;
    }

    
Return AUTH command use value.

Returns:
AUTH command use value.
    public String getAuthValue() {
        return this.;
    }


    
Because there are so many connect() methods, the _connectAction_() method is provided as a means of performing some action immediately after establishing a connection, rather than reimplementing all of the connect() methods.

Throws:
IOException If it throw by _connectAction_.
See also:
org.apache.commons.net.SocketClient._connectAction_()
    @Override
    protected void _connectAction_() throws IOException {
        // Implicit mode.
        if () {
            sslNegotiation();
        }
        super._connectAction_();
        // Explicit mode.
        if (!) {
            execAUTH();
            sslNegotiation();
        }
    }

    
AUTH command.

Throws:
SSLException If it server reply code not equal "234" and "334".
IOException If an I/O error occurs while either sending the command.
    protected void execAUTH() throws SSLExceptionIOException {
        int replyCode = sendCommand();
        if (. == replyCode) {
            // replyCode = 334
            // I carry out an ADAT command.
        } else if (. != replyCode) {
            throw new SSLException(getReplyString());
        }
    }

    
Performs a lazy init of the SSL context

Throws:
IOException
    private void initSslContext() throws IOException {
        if ( == null) {
             = SSLContextUtils.createSSLContext(getKeyManager(), getTrustManager());
        }
    }

    
SSL/TLS negotiation. Acquires an SSL socket of a control connection and carries out handshake processing.

Throws:
IOException If server negotiation fails
    protected void sslNegotiation() throws IOException {
         = _socket_;
        initSslContext();
        SSLSocketFactory ssf = .getSocketFactory();
        String ip = _socket_.getInetAddress().getHostAddress();
        int port = _socket_.getPort();
        SSLSocket socket =
            (SSLSocketssf.createSocket(_socket_, ipportfalse);
        socket.setEnableSessionCreation();
        socket.setUseClientMode();
        // server mode
        if (!) {
            socket.setNeedClientAuth();
            socket.setWantClientAuth();
        }
        if ( != null) {
            socket.setEnabledProtocols();
        }
        if ( != null) {
            socket.setEnabledCipherSuites();
        }
        socket.startHandshake();
        _socket_ = socket;
         = new BufferedReader(new InputStreamReader(
                socket .getInputStream(), getControlEncoding()));
                socket.getOutputStream(), getControlEncoding()));
    }

    
Get the KeyManager instance.

Returns:
The KeyManager instance
    private KeyManager getKeyManager() {
        return ;
    }

    
Set a KeyManager to use

Parameters:
keyManager The KeyManager implementation to set.
See also:
org.apache.commons.net.util.KeyManagerUtils
    public void setKeyManager(KeyManager keyManager) {
        this. = keyManager;
    }

    
Controls whether a new SSL session may be established by this socket.

Parameters:
isCreation The established socket flag.
    public void setEnabledSessionCreation(boolean isCreation) {
        this. = isCreation;
    }

    
Returns true if new SSL sessions may be established by this socket. When the underlying Socket instance is not SSL-enabled (i.e. an instance of SSLSocket with SSLSocketgetEnableSessionCreation()) enabled, this returns False.

Returns:
true - Indicates that sessions may be created; this is the default. false - indicates that an existing session must be resumed.
    public boolean getEnableSessionCreation() {
        if (_socket_ instanceof SSLSocket) {
            return ((SSLSocket)_socket_).getEnableSessionCreation();
        }
        return false;
    }

    
Configures the socket to require client authentication.

Parameters:
isNeedClientAuth The need client auth flag.
    public void setNeedClientAuth(boolean isNeedClientAuth) {
        this. = isNeedClientAuth;
    }

    
Returns true if the socket will require client authentication. When the underlying Socket is not an SSLSocket instance, returns false.

Returns:
true - If the server mode socket should request that the client authenticate itself.
    public boolean getNeedClientAuth() {
        if (_socket_ instanceof SSLSocket) {
            return ((SSLSocket)_socket_).getNeedClientAuth();
        }
        return false;
    }

    
Configures the socket to request client authentication, but only if such a request is appropriate to the cipher suite negotiated.

Parameters:
isWantClientAuth The want client auth flag.
    public void setWantClientAuth(boolean isWantClientAuth) {
        this. = isWantClientAuth;
    }

    
Returns true if the socket will request client authentication. When the underlying Socket is not an SSLSocket instance, returns false.

Returns:
true - If the server mode socket should request that the client authenticate itself.
    public boolean getWantClientAuth() {
        if (_socket_ instanceof SSLSocket) {
            return ((SSLSocket)_socket_).getWantClientAuth();
        }
        return false;
    }

    
Configures the socket to use client (or server) mode in its first handshake.

Parameters:
isClientMode The use client mode flag.
    public void setUseClientMode(boolean isClientMode) {
        this. = isClientMode;
    }

    
Returns true if the socket is set to use client mode in its first handshake. When the underlying Socket is not an SSLSocket instance, returns false.

Returns:
true - If the socket should start its first handshake in "client" mode.
    public boolean getUseClientMode() {
        if (_socket_ instanceof SSLSocket) {
            return ((SSLSocket)_socket_).getUseClientMode();
        }
        return false;
    }

    
Controls which particular cipher suites are enabled for use on this connection. Called before server negotiation.

Parameters:
cipherSuites The cipher suites.
    public void setEnabledCipherSuites(String[] cipherSuites) {
         = new String[cipherSuites.length];
        System.arraycopy(cipherSuites, 0, , 0, cipherSuites.length);
    }

    
Returns the names of the cipher suites which could be enabled for use on this connection. When the underlying Socket is not an SSLSocket instance, returns null.

Returns:
An array of cipher suite names, or null
    public String[] getEnabledCipherSuites() {
        if (_socket_ instanceof SSLSocket) {
            return ((SSLSocket)_socket_).getEnabledCipherSuites();
        }
        return null;
    }

    
Controls which particular protocol versions are enabled for use on this connection. I perform setting before a server negotiation.

Parameters:
protocolVersions The protocol versions.
    public void setEnabledProtocols(String[] protocolVersions) {
         = new String[protocolVersions.length];
        System.arraycopy(protocolVersions, 0, , 0, protocolVersions.length);
    }

    
Returns the names of the protocol versions which are currently enabled for use on this connection. When the underlying Socket is not an SSLSocket instance, returns null.

Returns:
An array of protocols, or null
    public String[] getEnabledProtocols() {
        if (_socket_ instanceof SSLSocket) {
            return ((SSLSocket)_socket_).getEnabledProtocols();
        }
        return null;
    }

    
PBSZ command. pbsz value: 0 to (2^32)-1 decimal integer.

Parameters:
pbsz Protection Buffer Size.
Throws:
SSLException If the server reply code does not equal "200".
IOException If an I/O error occurs while sending the command.
See also:
parsePBSZ(long)
    public void execPBSZ(long pbszthrows SSLExceptionIOException {
        if (pbsz < 0 || 4294967295L < pbsz) { // 32-bit unsigned number
            throw new IllegalArgumentException();
        }
        int status = sendCommand(, String.valueOf(pbsz));
        if (. != status) {
            throw new SSLException(getReplyString());
        }
    }

    
PBSZ command. pbsz value: 0 to (2^32)-1 decimal integer. Issues the command and parses the response to return the negotiated value.

Parameters:
pbsz Protection Buffer Size.
Returns:
the negotiated value.
Throws:
SSLException If the server reply code does not equal "200".
IOException If an I/O error occurs while sending the command.
Since:
3.0
See also:
execPBSZ(long)
    public long parsePBSZ(long pbszthrows SSLExceptionIOException {
        execPBSZ(pbsz);
        long minvalue = pbsz;
        String remainder = extractPrefixedData("PBSZ="getReplyString());
        if (remainder != null) {
            long replysz = Long.parseLong(remainder);
            if (replysz < minvalue) {
                minvalue = replysz;
            }
        }
        return minvalue;
    }

    
PROT command.
  • C - Clear
  • S - Safe(SSL protocol only)
  • E - Confidential(SSL protocol only)
  • P - Private
N.B. the method calls setSocketFactory(javax.net.SocketFactory) and setServerSocketFactory(javax.net.ServerSocketFactory)

Parameters:
prot Data Channel Protection Level, if null, use DEFAULT_PROT.
Throws:
SSLException If the server reply code does not equal 200.
IOException If an I/O error occurs while sending the command.
    public void execPROT(String protthrows SSLExceptionIOException {
        if (prot == null) {
            prot = ;
        }
        if (!checkPROTValue(prot)) {
            throw new IllegalArgumentException();
        }
        if (. != sendCommand(prot)) {
            throw new SSLException(getReplyString());
        }
        if (.equals(prot)) {
            setSocketFactory(null);
            setServerSocketFactory(null);
        } else {
            setSocketFactory(new FTPSSocketFactory());
            initSslContext();
        }
    }

    
Check the value that can be set in PROT Command value.

Parameters:
prot Data Channel Protection Level.
Returns:
True - A set point is right / False - A set point is not right
    private boolean checkPROTValue(String prot) {
        for (String element : )
        {
            if (element.equals(prot)) {
                return true;
            }
        }
        return false;
    }

    
Send an FTP command. A successful CCC (Clear Command Channel) command causes the underlying SSLSocket instance to be assigned to a plain Socket

Parameters:
command The FTP command.
Returns:
server reply.
Throws:
IOException If an I/O error occurs while sending the command.
SSLException if a CCC command fails
See also:
org.apache.commons.net.ftp.FTP.sendCommand(java.lang.String)
    // Would like to remove this method, but that will break any existing clients that are using CCC
    @Override
    public int sendCommand(String commandString argsthrows IOException {
        int repCode = super.sendCommand(commandargs);
        /* If CCC is issued, restore socket i/o streams to unsecured versions */
        if (.equals(command)) {
            if (. == repCode) {
                _socket_.close();
                _socket_ = ;
                 = new BufferedReader(
                    new InputStreamReader(
                        _socket_ .getInputStream(), getControlEncoding()));
                 = new BufferedWriter(
                    new OutputStreamWriter(
                        _socket_.getOutputStream(), getControlEncoding()));
            } else {
                throw new SSLException(getReplyString());
            }
        }
        return repCode;
    }

    
Returns a socket of the data connection. Wrapped as an SSLSocket, which carries out handshake processing.

Deprecated:
(3.3) Use _openDataConnection_(FTPCmd, String) instead
Parameters:
command The int representation of the FTP command to send.
arg The arguments to the FTP command. If this parameter is set to null, then the command is sent with no arguments.
Returns:
corresponding to the established data connection. Null is returned if an FTP protocol error is reported at any point during the establishment and initialization of the connection.
Throws:
IOException If there is any problem with the connection.
See also:
FTPClient._openDataConnection_(int, String)
    @Override
    // Strictly speaking this is not needed, but it works round a Clirr bug
    // So rather than invoke the parent code, we do it here
    @Deprecated
    protected Socket _openDataConnection_(int commandString arg)
            throws IOException {
        return _openDataConnection_(FTPCommand.getCommand(command), arg);
    }

   
Returns a socket of the data connection. Wrapped as an SSLSocket, which carries out handshake processing.

Parameters:
command The textual representation of the FTP command to send.
arg The arguments to the FTP command. If this parameter is set to null, then the command is sent with no arguments.
Returns:
corresponding to the established data connection. Null is returned if an FTP protocol error is reported at any point during the establishment and initialization of the connection.
Throws:
IOException If there is any problem with the connection.
Since:
3.2
See also:
FTPClient._openDataConnection_(int, String)
    @Override
    protected Socket _openDataConnection_(String commandString arg)
            throws IOException {
        Socket socket = super._openDataConnection_(commandarg);
        _prepareDataSocket_(socket);
        if (socket instanceof SSLSocket) {
            SSLSocket sslSocket = (SSLSocket)socket;
            sslSocket.setUseClientMode();
            sslSocket.setEnableSessionCreation();
            // server mode
            if (!) {
                sslSocket.setNeedClientAuth();
                sslSocket.setWantClientAuth();
            }
            if ( != null) {
                sslSocket.setEnabledCipherSuites();
            }
            if ( != null) {
                sslSocket.setEnabledProtocols();
            }
            sslSocket.startHandshake();
        }
        return socket;
    }

    
Performs any custom initialization for a newly created SSLSocket (before the SSL handshake happens). Called by _openDataConnection_(int, String) immediately after creating the socket. The default implementation is a no-op

Throws:
IOException
Since:
3.1
    protected void _prepareDataSocket_(Socket socket)
            throws IOException {
    }

    
Get the currently configured TrustManager.

Returns:
A TrustManager instance.
    public TrustManager getTrustManager() {
        return ;
    }

    
Override the default TrustManager to use; if set to null, the default TrustManager from the JVM will be used.

Parameters:
trustManager The TrustManager implementation to set, may be null
See also:
org.apache.commons.net.util.TrustManagerUtils
    public void setTrustManager(TrustManager trustManager) {
        this. = trustManager;
    }

    
Closes the connection to the FTP server and restores connection parameters to the default values.

Calls setSocketFactory(null) and setServerSocketFactory(null) to reset the factories that may have been changed during the session, e.g. by execPROT(String)

Throws:
IOException If an error occurs while disconnecting.
Since:
3.0
    @Override
    public void disconnect() throws IOException
    {
        super.disconnect();
        setSocketFactory(null);
        setServerSocketFactory(null);
    }

    
Send the AUTH command with the specified mechanism.

Parameters:
mechanism The mechanism name to send with the command.
Returns:
server reply.
Throws:
IOException If an I/O error occurs while sending the command.
Since:
3.0
    public int execAUTH(String mechanismthrows IOException
    {
        return sendCommand(mechanism);
    }

    
Send the ADAT command with the specified authentication data.

Parameters:
data The data to send with the command.
Returns:
server reply.
Throws:
IOException If an I/O error occurs while sending the command.
Since:
3.0
    public int execADAT(byte[] datathrows IOException
    {
        if (data != null)
        {
            return sendCommand(, Base64.encodeBase64StringUnChunked(data));
        }
        else
        {
            return sendCommand();
        }
    }

    
Send the CCC command to the server. The CCC (Clear Command Channel) command causes the underlying SSLSocket instance to be assigned to a plain Socket instances

Returns:
server reply.
Throws:
IOException If an I/O error occurs while sending the command.
Since:
3.0
    public int execCCC() throws IOException
    {
        int repCode = sendCommand();
// This will be performed by sendCommand(String, String)
//        if (FTPReply.isPositiveCompletion(repCode)) {
//            _socket_.close();
//            _socket_ = plainSocket;
//            _controlInput_ = new BufferedReader(
//                new InputStreamReader(
//                    _socket_.getInputStream(), getControlEncoding()));
//            _controlOutput_ = new BufferedWriter(
//                new OutputStreamWriter(
//                    _socket_.getOutputStream(), getControlEncoding()));
//        }
        return repCode;
    }

    
Send the MIC command with the specified data.

Parameters:
data The data to send with the command.
Returns:
server reply.
Throws:
IOException If an I/O error occurs while sending the command.
Since:
3.0
    public int execMIC(byte[] datathrows IOException
    {
        if (data != null)
        {
            return sendCommand(, Base64.encodeBase64StringUnChunked(data));
        }
        else
        {
            return sendCommand(""); // perhaps "=" or just sendCommand(String)?
        }
    }

    
Send the CONF command with the specified data.

Parameters:
data The data to send with the command.
Returns:
server reply.
Throws:
IOException If an I/O error occurs while sending the command.
Since:
3.0
    public int execCONF(byte[] datathrows IOException
    {
        if (data != null)
        {
            return sendCommand(, Base64.encodeBase64StringUnChunked(data));
        }
        else
        {
            return sendCommand(""); // perhaps "=" or just sendCommand(String)?
        }
    }

    
Send the ENC command with the specified data.

Parameters:
data The data to send with the command.
Returns:
server reply.
Throws:
IOException If an I/O error occurs while sending the command.
Since:
3.0
    public int execENC(byte[] datathrows IOException
    {
        if (data != null)
        {
            return sendCommand(, Base64.encodeBase64StringUnChunked(data));
        }
        else
        {
            return sendCommand(""); // perhaps "=" or just sendCommand(String)?
        }
    }

    
Parses the given ADAT response line and base64-decodes the data.

Parameters:
reply The ADAT reply to parse.
Returns:
the data in the reply, base64-decoded.
Since:
3.0
    public byte[] parseADATReply(String reply)
    {
        if (reply == null) {
            return null;
        } else {
            return Base64.decodeBase64(extractPrefixedData("ADAT="reply));
        }
    }

    
Extract the data from a reply with a prefix, e.g. PBSZ=1234 => 1234

Parameters:
prefix the prefix to find
reply where to find the prefix
Returns:
the remainder of the string after the prefix, or null if the prefix was not present.
    private String extractPrefixedData(String prefixString reply) {
        int idx = reply.indexOf(prefix);
        if (idx == -1) {
            return null;
        }
        // N.B. Cannot use trim before substring as leading space would affect the offset.
        return reply.substring(idx+prefix.length()).trim();
    }
    // DEPRECATED - for API compatibility only - DO NOT USE

    

Deprecated:
- not used - may be removed in a future release
    @Deprecated
    public static String KEYSTORE_ALGORITHM;

    

Deprecated:
- not used - may be removed in a future release
    @Deprecated
    public static String TRUSTSTORE_ALGORITHM;

    

Deprecated:
- not used - may be removed in a future release
    @Deprecated
    public static String PROVIDER;

    

Deprecated:
- not used - may be removed in a future release
    @Deprecated
    public static String STORE_TYPE;
/* kate: indent-width 4; replace-tabs on; */
New to GrepCode? Check out our FAQ X