ch.ethz.ssh2
Class SFTPv3Client

java.lang.Object
  extended by ch.ethz.ssh2.SFTPv3Client

public class SFTPv3Client
extends Object

A SFTPv3Client represents a SFTP (protocol version 3) client connection tunnelled over a SSH-2 connection. This is a very simple (synchronous) implementation.

Basically, most methods in this class map directly to one of the packet types described in draft-ietf-secsh-filexfer-02.txt.

Note: this is experimental code.

Error handling: the methods of this class throw IOExceptions. However, unless there is catastrophic failure, exceptions of the type SFTPv3Client will be thrown (a subclass of IOException). Therefore, you can implement more verbose behavior by checking if a thrown exception if of this type. If yes, then you can cast the exception and access detailed information about the failure.

Notes about file names, directory names and paths, copy-pasted from the specs:

If you are still not tired then please go on and read the comment for setCharset(String).

Version:
$Id$
Author:
Christian Plattner, plattner@inf.ethz.ch

Field Summary
static int SSH_FXF_APPEND
          Force all writes to append data at the end of the file.
static int SSH_FXF_CREAT
          If this flag is specified, then a new file will be created if one does not alread exist (if O_TRUNC is specified, the new file will be truncated to zero length if it previously exists).
static int SSH_FXF_EXCL
          Causes the request to fail if the named file already exists.
static int SSH_FXF_READ
          Open the file for reading.
static int SSH_FXF_TRUNC
          Forces an existing file with the same name to be truncated to zero length when creating a file by specifying SSH_FXF_CREAT.
static int SSH_FXF_WRITE
          Open the file for writing.
 
Constructor Summary
SFTPv3Client(Connection conn)
          Create a SFTP v3 client.
SFTPv3Client(Connection conn, PacketListener listener)
          Create a SFTP v3 client.
 
Method Summary
 String canonicalPath(String path)
          Have the server canonicalize any given path name to an absolute path.
 void close()
          Close this SFTP session.
 void closeFile(SFTPv3FileHandle handle)
          Close a file.
 SFTPv3FileHandle createFile(String fileName)
          Create a file and open it for reading and writing.
 SFTPv3FileHandle createFile(String fileName, SFTPv3FileAttributes attr)
          Create a file and open it for reading and writing.
 SFTPv3FileHandle createFileTruncate(String fileName)
          Create a file (truncate it if it already exists) and open it for writing.
 SFTPv3FileHandle createFileTruncate(String fileName, SFTPv3FileAttributes attr)
          reate a file (truncate it if it already exists) and open it for writing.
 void createSymlink(String src, String target)
          Create a symbolic link on the server.
 void fsetstat(SFTPv3FileHandle handle, SFTPv3FileAttributes attr)
          Modify the attributes of a file.
 SFTPv3FileAttributes fstat(SFTPv3FileHandle handle)
          Retrieve the file attributes of an open file.
 String getCharset()
          The currently used charset for filename encoding/decoding.
 int getProtocolVersion()
          Returns the negotiated SFTP protocol version between the client and the server.
 boolean isConnected()
          Queries the channel state
 List<SFTPv3DirectoryEntry> ls(String dirName)
          List the contents of a directory.
 SFTPv3FileAttributes lstat(String path)
          Retrieve the file attributes of a file.
 void mkdir(String dirName, int posixPermissions)
          Create a new directory.
 void mv(String oldPath, String newPath)
          Move a file or directory.
 SFTPv3FileHandle openDirectory(String path)
           
 SFTPv3FileHandle openFile(String fileName, int flags, SFTPv3FileAttributes attr)
           
 SFTPv3FileHandle openFileRO(String fileName)
          Open a file for reading.
 SFTPv3FileHandle openFileRW(String fileName)
          Open a file for reading and writing.
 SFTPv3FileHandle openFileRWAppend(String fileName)
          Open a file in append mode.
 SFTPv3FileHandle openFileWAppend(String fileName)
          Open a file in append mode.
 int read(SFTPv3FileHandle handle, long fileOffset, byte[] dst, int dstoff, int len)
          Read bytes from a file in a parallel fashion.
 String readLink(String path)
          Read the target of a symbolic link.
 void rm(String fileName)
          Remove a file.
 void rmdir(String dirName)
          Remove an empty directory.
 void setCharset(String charset)
          Set the charset used to convert between Java Unicode Strings and byte encodings used by the server for paths and file names.
 void setRequestParallelism(int parallelism)
           
 void setstat(String path, SFTPv3FileAttributes attr)
          Modify the attributes of a file.
 SFTPv3FileAttributes stat(String path)
          Retrieve the file attributes of a file.
 void write(SFTPv3FileHandle handle, long fileOffset, byte[] src, int srcoff, int len)
          Write bytes to a file.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

SSH_FXF_READ

public static final int SSH_FXF_READ
Open the file for reading.

See Also:
Constant Field Values

SSH_FXF_WRITE

public static final int SSH_FXF_WRITE
Open the file for writing. If both this and SSH_FXF_READ are specified, the file is opened for both reading and writing.

See Also:
Constant Field Values

SSH_FXF_APPEND

public static final int SSH_FXF_APPEND
Force all writes to append data at the end of the file.

See Also:
Constant Field Values

SSH_FXF_CREAT

public static final int SSH_FXF_CREAT
If this flag is specified, then a new file will be created if one does not alread exist (if O_TRUNC is specified, the new file will be truncated to zero length if it previously exists).

See Also:
Constant Field Values

SSH_FXF_TRUNC

public static final int SSH_FXF_TRUNC
Forces an existing file with the same name to be truncated to zero length when creating a file by specifying SSH_FXF_CREAT. SSH_FXF_CREAT MUST also be specified if this flag is used.

See Also:
Constant Field Values

SSH_FXF_EXCL

public static final int SSH_FXF_EXCL
Causes the request to fail if the named file already exists.

See Also:
Constant Field Values
Constructor Detail

SFTPv3Client

public SFTPv3Client(Connection conn,
                    PacketListener listener)
             throws IOException
Create a SFTP v3 client.

Parameters:
conn - The underlying SSH-2 connection to be used.
Throws:
IOException

SFTPv3Client

public SFTPv3Client(Connection conn)
             throws IOException
Create a SFTP v3 client.

Parameters:
conn - The underlying SSH-2 connection to be used.
Throws:
IOException
Method Detail

setCharset

public void setCharset(String charset)
                throws IOException
Set the charset used to convert between Java Unicode Strings and byte encodings used by the server for paths and file names. Unfortunately, the SFTP v3 draft says NOTHING about such conversions (well, with the exception of error messages which have to be in UTF-8). Newer drafts specify to use UTF-8 for file names (if I remember correctly). However, a quick test using OpenSSH serving a EXT-3 filesystem has shown that UTF-8 seems to be a bad choice for SFTP v3 (tested with filenames containing german umlauts). "windows-1252" seems to work better for Europe. Luckily, "windows-1252" is the platform default in my case =).

If you don't set anything, then the platform default will be used (this is the default behavior).

Parameters:
charset - the name of the charset to be used or null to use the platform's default encoding.
Throws:
IOException
See Also:
getCharset()

getCharset

public String getCharset()
The currently used charset for filename encoding/decoding.

Returns:
The name of the charset (null if the platform's default charset is being used)
See Also:
setCharset(String)

fstat

public SFTPv3FileAttributes fstat(SFTPv3FileHandle handle)
                           throws IOException
Retrieve the file attributes of an open file.

Parameters:
handle - a SFTPv3FileHandle handle.
Returns:
a SFTPv3FileAttributes object.
Throws:
IOException

stat

public SFTPv3FileAttributes stat(String path)
                          throws IOException
Retrieve the file attributes of a file. This method follows symbolic links on the server.

Parameters:
path - See the comment for the class for more details.
Returns:
a SFTPv3FileAttributes object.
Throws:
IOException
See Also:
lstat(String)

lstat

public SFTPv3FileAttributes lstat(String path)
                           throws IOException
Retrieve the file attributes of a file. This method does NOT follow symbolic links on the server.

Parameters:
path - See the comment for the class for more details.
Returns:
a SFTPv3FileAttributes object.
Throws:
IOException
See Also:
stat(String)

readLink

public String readLink(String path)
                throws IOException
Read the target of a symbolic link. Note: OpenSSH (as of version 4.4) gets very upset (SSH_FX_BAD_MESSAGE error) if you want to read the target of a file that is not a symbolic link. Better check first with lstat(String).

Parameters:
path - See the comment for the class for more details.
Returns:
The target of the link.
Throws:
IOException

setstat

public void setstat(String path,
                    SFTPv3FileAttributes attr)
             throws IOException
Modify the attributes of a file. Used for operations such as changing the ownership, permissions or access times, as well as for truncating a file.

Parameters:
path - See the comment for the class for more details.
attr - A SFTPv3FileAttributes object. Specifies the modifications to be made to the attributes of the file. Empty fields will be ignored.
Throws:
IOException

fsetstat

public void fsetstat(SFTPv3FileHandle handle,
                     SFTPv3FileAttributes attr)
              throws IOException
Modify the attributes of a file. Used for operations such as changing the ownership, permissions or access times, as well as for truncating a file.

Parameters:
handle - a SFTPv3FileHandle handle
attr - A SFTPv3FileAttributes object. Specifies the modifications to be made to the attributes of the file. Empty fields will be ignored.
Throws:
IOException

createSymlink

public void createSymlink(String src,
                          String target)
                   throws IOException
Create a symbolic link on the server. Creates a link "src" that points to "target".

Parameters:
src - See the comment for the class for more details.
target - See the comment for the class for more details.
Throws:
IOException

canonicalPath

public String canonicalPath(String path)
                     throws IOException
Have the server canonicalize any given path name to an absolute path. This is useful for converting path names containing ".." components or relative pathnames without a leading slash into absolute paths.

Parameters:
path - See the comment for the class for more details.
Returns:
An absolute path.
Throws:
IOException

openDirectory

public final SFTPv3FileHandle openDirectory(String path)
                                     throws IOException
Throws:
IOException

getProtocolVersion

public int getProtocolVersion()
Returns the negotiated SFTP protocol version between the client and the server.

Returns:
SFTP protocol version, i.e., "3".

isConnected

public boolean isConnected()
Queries the channel state

Returns:
True if the underlying session is in open state

close

public void close()
Close this SFTP session. NEVER forget to call this method to free up resources - even if you got an exception from one of the other methods. Sometimes these other methods may throw an exception, saying that the underlying channel is closed (this can happen, e.g., if the other server sent a close message.) However, as long as you have not called the close() method, you are likely wasting resources.


ls

public List<SFTPv3DirectoryEntry> ls(String dirName)
                              throws IOException
List the contents of a directory.

Parameters:
dirName - See the comment for the class for more details.
Returns:
A Vector containing SFTPv3DirectoryEntry objects.
Throws:
IOException

mkdir

public void mkdir(String dirName,
                  int posixPermissions)
           throws IOException
Create a new directory.

Parameters:
dirName - See the comment for the class for more details.
posixPermissions - the permissions for this directory, e.g., "0700" (remember that this is octal noation). The server will likely apply a umask.
Throws:
IOException

rm

public void rm(String fileName)
        throws IOException
Remove a file.

Parameters:
fileName - See the comment for the class for more details.
Throws:
IOException

rmdir

public void rmdir(String dirName)
           throws IOException
Remove an empty directory.

Parameters:
dirName - See the comment for the class for more details.
Throws:
IOException

mv

public void mv(String oldPath,
               String newPath)
        throws IOException
Move a file or directory.

Parameters:
oldPath - See the comment for the class for more details.
newPath - See the comment for the class for more details.
Throws:
IOException

openFileRO

public SFTPv3FileHandle openFileRO(String fileName)
                            throws IOException
Open a file for reading.

Parameters:
fileName - See the comment for the class for more details.
Returns:
a SFTPv3FileHandle handle
Throws:
IOException

openFileRW

public SFTPv3FileHandle openFileRW(String fileName)
                            throws IOException
Open a file for reading and writing.

Parameters:
fileName - See the comment for the class for more details.
Returns:
a SFTPv3FileHandle handle
Throws:
IOException

openFileRWAppend

public SFTPv3FileHandle openFileRWAppend(String fileName)
                                  throws IOException
Open a file in append mode. The SFTP v3 draft says nothing but assuming normal POSIX behavior, all writes will be appendend to the end of the file, no matter which offset one specifies.

A side note for the curious: OpenSSH does an lseek() to the specified writing offset before each write(), even for writes to files opened in O_APPEND mode. However, bear in mind that when working in the O_APPEND mode, each write() includes an implicit lseek() to the end of the file (well, this is what the newsgroups say).

Parameters:
fileName - See the comment for the class for more details.
Returns:
a SFTPv3FileHandle handle
Throws:
IOException

openFileWAppend

public SFTPv3FileHandle openFileWAppend(String fileName)
                                 throws IOException
Open a file in append mode. The SFTP v3 draft says nothing but assuming normal POSIX behavior, all writes will be appendend to the end of the file, no matter which offset one specifies.

A side note for the curious: OpenSSH does an lseek() to the specified writing offset before each write(), even for writes to files opened in O_APPEND mode. However, bear in mind that when working in the O_APPEND mode, each write() includes an implicit lseek() to the end of the file (well, this is what the newsgroups say).

Parameters:
fileName - See the comment for the class for more details.
Returns:
a SFTPv3FileHandle handle
Throws:
IOException

createFile

public SFTPv3FileHandle createFile(String fileName)
                            throws IOException
Create a file and open it for reading and writing. Same as createFile(fileName, null).

Parameters:
fileName - See the comment for the class for more details.
Returns:
a SFTPv3FileHandle handle
Throws:
IOException

createFile

public SFTPv3FileHandle createFile(String fileName,
                                   SFTPv3FileAttributes attr)
                            throws IOException
Create a file and open it for reading and writing. You can specify the default attributes of the file (the server may or may not respect your wishes).

Parameters:
fileName - See the comment for the class for more details.
attr - may be null to use server defaults. Probably only the uid, gid and permissions (remember the server may apply a umask) entries of the SFTPv3FileHandle structure make sense. You need only to set those fields where you want to override the server's defaults.
Returns:
a SFTPv3FileHandle handle
Throws:
IOException

createFileTruncate

public SFTPv3FileHandle createFileTruncate(String fileName)
                                    throws IOException
Create a file (truncate it if it already exists) and open it for writing. Same as createFileTruncate(fileName, null).

Parameters:
fileName - See the comment for the class for more details.
Returns:
a SFTPv3FileHandle handle
Throws:
IOException

createFileTruncate

public SFTPv3FileHandle createFileTruncate(String fileName,
                                           SFTPv3FileAttributes attr)
                                    throws IOException
reate a file (truncate it if it already exists) and open it for writing. You can specify the default attributes of the file (the server may or may not respect your wishes).

Parameters:
fileName - See the comment for the class for more details.
attr - may be null to use server defaults. Probably only the uid, gid and permissions (remember the server may apply a umask) entries of the SFTPv3FileHandle structure make sense. You need only to set those fields where you want to override the server's defaults.
Returns:
a SFTPv3FileHandle handle
Throws:
IOException

openFile

public SFTPv3FileHandle openFile(String fileName,
                                 int flags,
                                 SFTPv3FileAttributes attr)
                          throws IOException
Throws:
IOException

setRequestParallelism

public void setRequestParallelism(int parallelism)
Parameters:
parallelism -

read

public int read(SFTPv3FileHandle handle,
                long fileOffset,
                byte[] dst,
                int dstoff,
                int len)
         throws IOException
Read bytes from a file in a parallel fashion. As many bytes as you want will be read.

Parameters:
handle - a SFTPv3FileHandle handle
fileOffset - offset (in bytes) in the file
dst - the destination byte array
dstoff - offset in the destination byte array
len - how many bytes to read, 0 < len
Returns:
the number of bytes that could be read, may be less than requested if the end of the file is reached, -1 is returned in case of EOF
Throws:
IOException

write

public void write(SFTPv3FileHandle handle,
                  long fileOffset,
                  byte[] src,
                  int srcoff,
                  int len)
           throws IOException
Write bytes to a file. If len > 32768, then the write operation will be split into multiple writes.

Parameters:
handle - a SFTPv3FileHandle handle.
fileOffset - offset (in bytes) in the file.
src - the source byte array.
srcoff - offset in the source byte array.
len - how many bytes to write.
Throws:
IOException

closeFile

public void closeFile(SFTPv3FileHandle handle)
               throws IOException
Close a file.

Parameters:
handle - a SFTPv3FileHandle handle
Throws:
IOException


Copyright © 2011. All Rights Reserved.