com.maverick.sftp
Class SftpSubsystemChannel

java.lang.Object
  extended bycom.maverick.ssh.SubsystemChannel
      extended bycom.maverick.sftp.SftpSubsystemChannel

public class SftpSubsystemChannel
extends SubsystemChannel

This class implements the SFTP protocol which is executed as an SSH subsystem. The basic initialization procedure is as follows:

 // Create an SshClient
 SshConnector con = SshConnector.getInstance();

 // Connect and authenticate an SshClient
 SshClient ssh = con.connect(....);
 ....

 // Create and initialize an SftpSubsystemChannel
 SshSession session = ssh.openSessionChannel();
 if(session instanceof Ssh2Session)
    ((Ssh2Session)session).startSubsystem("sftp");
 else
    session.executeCommand("/usr/sbin/sftp-server");
 SftpSubsystemChannel sftp = new SftpSubsystemChannel(session);
 sftp.initialize();
 
The above example demonstrates how to execute subsystem on both SSH1 and SSH2 connections. There is no subsystem support within SSH1 which requires that the command is executed directly.

Author:
Lee David Painter

Field Summary
static int OPEN_APPEND
          File open flag, forces all writes to append data at the end of the file.
static int OPEN_CREATE
          File open flag, if specified a new file will be created if one does not already exist.
static int OPEN_EXCLUSIVE
          File open flag, causes an open request to fail if the named file already exists.
static int OPEN_READ
          File open flag, opens the file for reading.
static int OPEN_TEXT
          File open flag, causes the file to be opened in text mode.
static int OPEN_TRUNCATE
          File open flag, forces an existing file with the same name to be truncated to zero length when creating a file by specifying OPEN_CREATE.
static int OPEN_WRITE
          File open flag, opens the file for writing.
 
Constructor Summary
SftpSubsystemChannel(SshSession session)
          Constructs an uninitialized sftp channel with an unitialized session channel
 
Method Summary
 void changePermissions(SftpFile file, int permissions)
          Change the permissions of a file.
 void changePermissions(java.lang.String filename, int permissions)
          Change the permissions of a file.
 void changePermissions(java.lang.String filename, java.lang.String permissions)
          Change the permissions of a file.
 void closeFile(SftpFile file)
          Close a file or directory.
 void createSymbolicLink(java.lang.String targetpath, java.lang.String linkpath)
          Create a symbolic link.
 java.lang.String getAbsolutePath(SftpFile file)
          Get the absolute path of a file.
 java.lang.String getAbsolutePath(java.lang.String path)
          Get the absolute path of a file.
 SftpFileAttributes getAttributes(SftpFile file)
          Get the attributes of a file.
 SftpFileAttributes getAttributes(java.lang.String path)
          Get the attributes of a file.
 java.lang.String getCanonicalNewline()
          Returns the canonical newline convention in use when reading/writing text files.
 java.lang.String getCharsetEncoding()
          Get the current encoding being used for filename Strings.
 java.lang.String getDefaultDirectory()
          Gets the users default directory.
 java.lang.String getExtension(java.lang.String name)
          Get the data value of a supported SFTP extension.
 SftpFile getFile(java.lang.String path)
          Utility method to obtain an SftpFile instance for a given path.
 void getOKRequestStatus(com.maverick.crypto.io.UnsignedInteger32 requestId)
          Verify that an OK status has been returned for a request id.
 int getServerVersion()
          Version 4 of the SFTP protocol allows the server to return its maximum supported version instead of the actual version to be used.
 java.lang.String getSymbolicLinkTarget(java.lang.String linkpath)
          Get the target path of a symbolic link.
 int getVersion()
          When called after the initialize method this will return the version in operation for this sftp session.
 void initialize()
          Initializes the sftp subsystem and negotiates a version with the server.
 int listChildren(SftpFile file, java.util.Vector children)
          List the children of a directory.
 void makeDirectory(java.lang.String path)
          Make a directory.
 void makeDirectory(java.lang.String path, SftpFileAttributes attrs)
          Make a directory.
 SftpFile openDirectory(java.lang.String path)
          Open a directory.
 SftpFile openFile(java.lang.String absolutePath, int flags)
          Open a file.
 SftpFile openFile(java.lang.String absolutePath, int flags, SftpFileAttributes attrs)
          Open a file.
 void performOptimizedRead(byte[] handle, long length, int blocksize, java.io.OutputStream out, int outstandingRequests, FileTransferProgress progress)
          Performs an optimized read of a file through use of asynchronous messages.
 void performOptimizedRead(byte[] handle, long length, int blocksize, java.io.OutputStream out, int outstandingRequests, FileTransferProgress progress, long position)
          Performs an optimized read of a file through use of asynchronous messages.
 void performOptimizedWrite(byte[] handle, int blocksize, int outstandingRequests, java.io.InputStream in, int buffersize, FileTransferProgress progress)
          Performs an optimized write of a file through asynchronous messaging and through buffering the local file into memory.
 void performOptimizedWrite(byte[] handle, int blocksize, int outstandingRequests, java.io.InputStream in, int buffersize, FileTransferProgress progress, long position)
          Performs an optimized write of a file through asynchronous messaging and through buffering the local file into memory.
 com.maverick.crypto.io.UnsignedInteger32 postReadRequest(byte[] handle, long offset, int len)
          Post a read request to the server and return the request id; this is used to optimize file downloads.
 com.maverick.crypto.io.UnsignedInteger32 postWriteRequest(byte[] handle, long position, byte[] data, int off, int len)
          Send a write request for an open file but do not wait for the response from the server.
 int readFile(byte[] handle, com.maverick.crypto.io.UnsignedInteger64 offset, byte[] output, int off, int len)
          Read a block of data from an open file.
 void recurseMakeDirectory(java.lang.String path)
          Recurse through a hierarchy of directories creating them as necersary.
 void removeDirectory(java.lang.String path)
          Remove an empty directory.
 void removeFile(java.lang.String filename)
          Remove a file.
 void renameFile(java.lang.String oldpath, java.lang.String newpath)
          Rename an existing file.
 SftpMessage sendExtensionMessage(java.lang.String request, byte[] requestData)
          Send an extension message and return the response.
 void setAttributes(SftpFile file, SftpFileAttributes attrs)
          Sets the attributes of a file.
 void setAttributes(java.lang.String path, SftpFileAttributes attrs)
          Sets the attributes of a file.
 void setCharsetEncoding(java.lang.String charset)
          Allows the default character encoding to be overriden for filename strings.
 boolean supportsExtension(java.lang.String name)
          Does the server support an SFTP extension? This checks the extensions returned by the server during the SFTP version negotiation.
 void writeFile(byte[] handle, com.maverick.crypto.io.UnsignedInteger64 offset, byte[] data, int off, int len)
          Write a block of data to an open file.
 
Methods inherited from class com.maverick.ssh.SubsystemChannel
close, createPacket, isClosed, nextMessage, sendMessage, sendMessage
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

OPEN_READ

public static final int OPEN_READ
File open flag, opens the file for reading.

See Also:
Constant Field Values

OPEN_WRITE

public static final int OPEN_WRITE
File open flag, opens the file for writing.

See Also:
Constant Field Values

OPEN_APPEND

public static final int OPEN_APPEND
File open flag, forces all writes to append data at the end of the file.

See Also:
Constant Field Values

OPEN_CREATE

public static final int OPEN_CREATE
File open flag, if specified a new file will be created if one does not already exist.

See Also:
Constant Field Values

OPEN_TRUNCATE

public static final int OPEN_TRUNCATE
File open flag, forces an existing file with the same name to be truncated to zero length when creating a file by specifying OPEN_CREATE.

See Also:
Constant Field Values

OPEN_EXCLUSIVE

public static final int OPEN_EXCLUSIVE
File open flag, causes an open request to fail if the named file already exists. OPEN_CREATE must also be specified if this flag is used.

See Also:
Constant Field Values

OPEN_TEXT

public static final int OPEN_TEXT
File open flag, causes the file to be opened in text mode. This instructs the server to convert the text file to the canonical newline convention in use. Any files retrieved using this mode should then be converted from the canonical newline convention to that of the clients.

See Also:
Constant Field Values
Constructor Detail

SftpSubsystemChannel

public SftpSubsystemChannel(SshSession session)
                     throws SshException
Constructs an uninitialized sftp channel with an unitialized session channel

Throws:
SshException
Method Detail

getVersion

public int getVersion()
When called after the initialize method this will return the version in operation for this sftp session.

Returns:

getCanonicalNewline

public java.lang.String getCanonicalNewline()
                                     throws SftpStatusException
Returns the canonical newline convention in use when reading/writing text files.

Returns:
String
Throws:
SftpStatusException

initialize

public void initialize()
                throws SshException,
                       java.io.UnsupportedEncodingException
Initializes the sftp subsystem and negotiates a version with the server. This method must be the first method called after the channel has been opened. This implementation current supports SFTP protocol version 4 and below.

Throws:
SshException
java.io.UnsupportedEncodingException

setCharsetEncoding

public void setCharsetEncoding(java.lang.String charset)
                        throws SshException,
                               java.io.UnsupportedEncodingException
Allows the default character encoding to be overriden for filename strings. This method should only be called once the channel has been initialized, if the version of the protocol is less than or equal to 3 the encoding is defaulted to latin1 as no encoding is specified by the protocol. If the version is greater than 3 the default encoding will be UTF-8.

Parameters:
charset -
Throws:
java.io.UnsupportedEncodingException
SshException

getServerVersion

public int getServerVersion()
Version 4 of the SFTP protocol allows the server to return its maximum supported version instead of the actual version to be used. This method returns the value provided by the server, if the servers version is less than or equal to 3 then this method will return the protocol number in use, otherwise it returns the maximum version supported by the server.

Returns:
int

getCharsetEncoding

public java.lang.String getCharsetEncoding()
Get the current encoding being used for filename Strings.

Returns:

supportsExtension

public boolean supportsExtension(java.lang.String name)
Does the server support an SFTP extension? This checks the extensions returned by the server during the SFTP version negotiation.

Parameters:
name - String
Returns:
boolean

getExtension

public java.lang.String getExtension(java.lang.String name)
Get the data value of a supported SFTP extension. Call supportsExtension(String) before calling this method to determine if the extension is available.

Parameters:
name - String
Returns:
String

sendExtensionMessage

public SftpMessage sendExtensionMessage(java.lang.String request,
                                        byte[] requestData)
                                 throws SshException,
                                        SftpStatusException
Send an extension message and return the response. This is for advanced use only.

Parameters:
request - String
requestData - byte[]
Returns:
byte[]
Throws:
SshException
SftpStatusException

changePermissions

public void changePermissions(SftpFile file,
                              int permissions)
                       throws SftpStatusException,
                              SshException
Change the permissions of a file.

Parameters:
file - the file
permissions - an integer value containing a file permissions mask
Throws:
SshException
SftpStatusException

changePermissions

public void changePermissions(java.lang.String filename,
                              int permissions)
                       throws SftpStatusException,
                              SshException
Change the permissions of a file.

Parameters:
filename - the path to the file.
permissions - an integer value containing a file permissions mask.
Throws:
SshException
SftpStatusException

changePermissions

public void changePermissions(java.lang.String filename,
                              java.lang.String permissions)
                       throws SftpStatusException,
                              SshException
Change the permissions of a file.

Parameters:
filename - the path to the file.
permissions - a string containing the permissions, for example "rw-r--r--"
Throws:
SshException
SftpStatusException

setAttributes

public void setAttributes(java.lang.String path,
                          SftpFileAttributes attrs)
                   throws SftpStatusException,
                          SshException
Sets the attributes of a file.

Parameters:
path - the path to the file.
attrs - the file attributes.
Throws:
SshException
SftpStatusException

setAttributes

public void setAttributes(SftpFile file,
                          SftpFileAttributes attrs)
                   throws SftpStatusException,
                          SshException
Sets the attributes of a file.

Parameters:
file - the file object.
attrs - the new attributes.
Throws:
SshException
SftpStatusException

postWriteRequest

public com.maverick.crypto.io.UnsignedInteger32 postWriteRequest(byte[] handle,
                                                                 long position,
                                                                 byte[] data,
                                                                 int off,
                                                                 int len)
                                                          throws SftpStatusException,
                                                                 SshException
Send a write request for an open file but do not wait for the response from the server.

Parameters:
handle -
position -
data -
off -
len -
Returns:
Throws:
SshException
SftpStatusException

writeFile

public void writeFile(byte[] handle,
                      com.maverick.crypto.io.UnsignedInteger64 offset,
                      byte[] data,
                      int off,
                      int len)
               throws SftpStatusException,
                      SshException
Write a block of data to an open file.

Parameters:
handle - the open file handle.
offset - the offset in the file to start writing
data - a buffer containing the data to write
off - the offset to start in the buffer
len - the lenght of data to write (setting to false will increase file transfer but may miss errors)
Throws:
SshException
SftpStatusException

performOptimizedWrite

public void performOptimizedWrite(byte[] handle,
                                  int blocksize,
                                  int outstandingRequests,
                                  java.io.InputStream in,
                                  int buffersize,
                                  FileTransferProgress progress)
                           throws SftpStatusException,
                                  SshException,
                                  TransferCancelledException
Performs an optimized write of a file through asynchronous messaging and through buffering the local file into memory.

Parameters:
handle - the open file handle to write to
blocksize - the block size to send data, should be between 4096 and 65535
outstandingRequests - the maximum number of requests that can be outstanding at any one time
in - the InputStream to read from
buffersize - the size of the temporary buffer to read from the InputStream. Data is buffered into a temporary buffer so that the number of local filesystem reads is reducted to a minimum. This increases performance and so the buffer size should be as high as possible. The default operation, if buffersize <= 0 is to allocate a buffer the same size as the blocksize, meaning no buffer optimization is performed.
progress - provides progress information, may be null.
Throws:
SshException
SftpStatusException
TransferCancelledException

performOptimizedWrite

public void performOptimizedWrite(byte[] handle,
                                  int blocksize,
                                  int outstandingRequests,
                                  java.io.InputStream in,
                                  int buffersize,
                                  FileTransferProgress progress,
                                  long position)
                           throws SftpStatusException,
                                  SshException,
                                  TransferCancelledException
Performs an optimized write of a file through asynchronous messaging and through buffering the local file into memory.

Parameters:
handle - the open file handle to write to
blocksize - the block size to send data, should be between 4096 and 65535
outstandingRequests - the maximum number of requests that can be outstanding at any one time
in - the InputStream to read from
buffersize - the size of the temporary buffer to read from the InputStream. Data is buffered into a temporary buffer so that the number of local filesystem reads is reducted to a minimum. This increases performance and so the buffer size should be as high as possible. The default operation, if buffersize <= 0 is to allocate a buffer the same size as the blocksize, meaning no buffer optimization is performed.
progress - provides progress information, may be null.
position - the position in the file to start writing to.
Throws:
SshException
SftpStatusException
TransferCancelledException

performOptimizedRead

public void performOptimizedRead(byte[] handle,
                                 long length,
                                 int blocksize,
                                 java.io.OutputStream out,
                                 int outstandingRequests,
                                 FileTransferProgress progress)
                          throws SftpStatusException,
                                 SshException,
                                 TransferCancelledException
Performs an optimized read of a file through use of asynchronous messages. The total number of outstanding read requests is configurable. This should be safe on file objects as the SSH protocol states that file read operations should return the exact number of bytes requested in each request. However the server is not required to return the exact number of bytes on device files and so this method should not be used for device files.

Parameters:
handle - the open files handle
length - the length of the file
blocksize - the blocksize to read
out - an OutputStream to output the file into
outstandingRequests - the maximum number of read requests to
progress -
Throws:
SshException
SftpStatusException
TransferCancelledException

performOptimizedRead

public void performOptimizedRead(byte[] handle,
                                 long length,
                                 int blocksize,
                                 java.io.OutputStream out,
                                 int outstandingRequests,
                                 FileTransferProgress progress,
                                 long position)
                          throws SftpStatusException,
                                 SshException,
                                 TransferCancelledException
Performs an optimized read of a file through use of asynchronous messages. The total number of outstanding read requests is configurable. This should be safe on file objects as the SSH protocol states that file read operations should return the exact number of bytes requested in each request. However the server is not required to return the exact number of bytes on device files and so this method should not be used for device files.

Parameters:
handle - the open files handle
length - the length of the file
blocksize - the blocksize to read
out - an OutputStream to output the file into
outstandingRequests - the maximum number of read requests to
progress -
position - the postition from which to start reading the file
Throws:
SshException
SftpStatusException
TransferCancelledException

postReadRequest

public com.maverick.crypto.io.UnsignedInteger32 postReadRequest(byte[] handle,
                                                                long offset,
                                                                int len)
                                                         throws SftpStatusException,
                                                                SshException
Post a read request to the server and return the request id; this is used to optimize file downloads. In normal operation the files are transfered by using a synchronous set of requests, however this slows the download as the client has to wait for the servers response before sending another request.

Parameters:
handle -
offset -
len -
Returns:
Throws:
SshException
SftpStatusException

readFile

public int readFile(byte[] handle,
                    com.maverick.crypto.io.UnsignedInteger64 offset,
                    byte[] output,
                    int off,
                    int len)
             throws SftpStatusException,
                    SshException
Read a block of data from an open file.

Parameters:
handle - the open file handle
offset - the offset to start reading in the file
output - a buffer to write the returned data to
off - the starting offset in the output buffer
len - the length of data to read
Returns:
Throws:
SshException
SftpStatusException

getFile

public SftpFile getFile(java.lang.String path)
                 throws SftpStatusException,
                        SshException
Utility method to obtain an SftpFile instance for a given path.

Parameters:
path -
Returns:
Throws:
SftpStatusException
SshException

getAbsolutePath

public java.lang.String getAbsolutePath(SftpFile file)
                                 throws SftpStatusException,
                                        SshException
Get the absolute path of a file.

Parameters:
file -
Returns:
Throws:
SshException
SftpStatusException

createSymbolicLink

public void createSymbolicLink(java.lang.String targetpath,
                               java.lang.String linkpath)
                        throws SftpStatusException,
                               SshException
Create a symbolic link.

Parameters:
targetpath - the symbolic link to create
linkpath - the path to which the symbolic link points
Throws:
SshException - if the remote SFTP version is < 3 an exception is thrown as this feature is not supported by previous versions of the protocol.
SftpStatusException

getSymbolicLinkTarget

public java.lang.String getSymbolicLinkTarget(java.lang.String linkpath)
                                       throws SftpStatusException,
                                              SshException
Get the target path of a symbolic link.

Parameters:
linkpath -
Returns:
Throws:
SshException - if the remote SFTP version is < 3 an exception is thrown as this feature is not supported by previous versions of the protocol.
SftpStatusException

getDefaultDirectory

public java.lang.String getDefaultDirectory()
                                     throws SftpStatusException,
                                            SshException
Gets the users default directory.

Returns:
Throws:
SshException
SftpStatusException

getAbsolutePath

public java.lang.String getAbsolutePath(java.lang.String path)
                                 throws SftpStatusException,
                                        SshException
Get the absolute path of a file.

Parameters:
path -
Returns:
Throws:
SshException
SftpStatusException

listChildren

public int listChildren(SftpFile file,
                        java.util.Vector children)
                 throws SftpStatusException,
                        SshException

List the children of a directory.

To use this method first open a directory with the openDirectory method and then create a Vector to store the results. To retreive the results keep calling this method unitll it returns -1 which indicates no more results will be returned.

 SftpFile dir = sftp.openDirectory("code/foobar");
 Vector results = new Vector();
 while(sftp.listChildren(dir, results) > -1);
 sftp.closeFile(dir);
 

Parameters:
file -
children -
Returns:
Throws:
SshException
SftpStatusException

recurseMakeDirectory

public void recurseMakeDirectory(java.lang.String path)
                          throws SftpStatusException,
                                 SshException
Recurse through a hierarchy of directories creating them as necersary.

Parameters:
path -
Throws:
SshException
SftpStatusException

openFile

public SftpFile openFile(java.lang.String absolutePath,
                         int flags)
                  throws SftpStatusException,
                         SshException
Open a file.

Parameters:
absolutePath -
flags -
Returns:
Throws:
SshException
SftpStatusException

openFile

public SftpFile openFile(java.lang.String absolutePath,
                         int flags,
                         SftpFileAttributes attrs)
                  throws SftpStatusException,
                         SshException
Open a file.

Parameters:
absolutePath -
flags -
attrs -
Returns:
Throws:
SshException
SftpStatusException

openDirectory

public SftpFile openDirectory(java.lang.String path)
                       throws SftpStatusException,
                              SshException
Open a directory.

Parameters:
path -
Returns:
Throws:
SshException
SftpStatusException

closeFile

public void closeFile(SftpFile file)
               throws SftpStatusException,
                      SshException
Close a file or directory.

Parameters:
file -
Throws:
SshException
SftpStatusException

removeDirectory

public void removeDirectory(java.lang.String path)
                     throws SftpStatusException,
                            SshException
Remove an empty directory.

Parameters:
path -
Throws:
SshException
SftpStatusException

removeFile

public void removeFile(java.lang.String filename)
                throws SftpStatusException,
                       SshException
Remove a file.

Parameters:
filename -
Throws:
SshException
SftpStatusException

renameFile

public void renameFile(java.lang.String oldpath,
                       java.lang.String newpath)
                throws SftpStatusException,
                       SshException
Rename an existing file.

Parameters:
oldpath -
newpath -
Throws:
SshException
SftpStatusException

getAttributes

public SftpFileAttributes getAttributes(java.lang.String path)
                                 throws SftpStatusException,
                                        SshException
Get the attributes of a file.

Parameters:
path -
Returns:
Throws:
SshException
SftpStatusException

getAttributes

public SftpFileAttributes getAttributes(SftpFile file)
                                 throws SftpStatusException,
                                        SshException
Get the attributes of a file.

Parameters:
file -
Returns:
Throws:
SshException
SftpStatusException

makeDirectory

public void makeDirectory(java.lang.String path)
                   throws SftpStatusException,
                          SshException
Make a directory. If the directory exists this method will throw an exception.

Parameters:
path -
Throws:
SshException
SftpStatusException

makeDirectory

public void makeDirectory(java.lang.String path,
                          SftpFileAttributes attrs)
                   throws SftpStatusException,
                          SshException
Make a directory. If the directory exists this method will throw an exception.

Parameters:
path -
attrs -
Throws:
SshException
SftpStatusException

getOKRequestStatus

public void getOKRequestStatus(com.maverick.crypto.io.UnsignedInteger32 requestId)
                        throws SftpStatusException,
                               SshException
Verify that an OK status has been returned for a request id.

Parameters:
requestId -
Throws:
SshException
SftpStatusException


Copyright © 2003 3SP LTD. All Rights Reserved.