Class SFTPv3Client
- java.lang.Object
-
- com.trilead.ssh2.SFTPv3Client
-
public class SFTPv3Client extends java.lang.ObjectASFTPv3Clientrepresents 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
SFTPv3Clientwill 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:
- SFTP v3 represents file names as strings. File names are assumed to use the slash ('/') character as a directory separator.
- File names starting with a slash are "absolute", and are relative to the root of the file system. Names starting with any other character are relative to the user's default directory (home directory).
- Servers SHOULD interpret a path name component ".." as referring to the parent directory, and "." as referring to the current directory. If the server implementation limits access to certain parts of the file system, it must be extra careful in parsing file names when enforcing such restrictions. There have been numerous reported security bugs where a ".." in a path name has allowed access outside the intended area.
- An empty path name is valid, and it refers to the user's default directory (usually the user's home directory).
If you are still not tired then please go on and read the comment for
setCharset(String).- Version:
- $Id: SFTPv3Client.java,v 1.3 2008/04/01 12:38:09 cplattne Exp $
-
-
Field Summary
Fields Modifier and Type Field Description (package private) java.lang.StringcharsetName(package private) Connectionconn(package private) java.io.PrintStreamdebug(package private) booleanflag_closed(package private) java.io.InputStreamis(package private) intnext_request_id(package private) java.io.OutputStreamos(package private) intprotocol_version(package private) java.util.HashMapserver_extensions(package private) Sessionsess
-
Constructor Summary
Constructors Constructor Description SFTPv3Client(Connection conn)Create a SFTP v3 client.SFTPv3Client(Connection conn, java.io.PrintStream debug)Deprecated.this constructor (debug version) will disappear in the future, useSFTPv3Client(Connection)instead.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description SFTPv3FileAttributes_stat(java.lang.String path)Gracefulstat(String)that returns null if the path doesn't exist.java.lang.StringcanonicalPath(java.lang.String path)Have the server canonicalize any given path name to an absolute path.private voidcheckHandleValidAndOpen(SFTPv3FileHandle handle)voidchmod(java.lang.String path, int permissions)voidclose()Close this SFTP session.voidcloseFile(SFTPv3FileHandle handle)Close a file.private voidcloseHandle(byte[] handle)private byte[]createAttrs(SFTPv3FileAttributes attr)SFTPv3FileHandlecreateFile(java.lang.String fileName)Create a file and open it for reading and writing.SFTPv3FileHandlecreateFile(java.lang.String fileName, SFTPv3FileAttributes attr)Create a file and open it for reading and writing.SFTPv3FileHandlecreateFileTruncate(java.lang.String fileName)Create a file (truncate it if it already exists) and open it for reading and writing.SFTPv3FileHandlecreateFileTruncate(java.lang.String fileName, SFTPv3FileAttributes attr)reate a file (truncate it if it already exists) and open it for reading and writing.voidcreateSymlink(java.lang.String src, java.lang.String target)Create a symbolic link on the server.booleanexists(java.lang.String path)Checks if the given path exists.private java.lang.StringexpandString(byte[] b, int off, int len)private voidexpectStatusOKMessage(int id)voidfsetstat(SFTPv3FileHandle handle, SFTPv3FileAttributes attr)Modify the attributes of a file.SFTPv3FileAttributesfstat(SFTPv3FileHandle handle)Retrieve the file attributes of an open file.private intgenerateNextRequestID()java.lang.StringgetCharset()The currently used charset for filename encoding/decoding.intgetProtocolVersion()Returns the negotiated SFTP protocol version between the client and the server.private voidinit()java.util.Vectorls(java.lang.String dirName)List the contents of a directory.SFTPv3FileAttributeslstat(java.lang.String path)Retrieve the file attributes of a file.voidmkdir(java.lang.String dirName, int posixPermissions)Create a new directory.voidmkdirs(java.lang.String path, int posixPermission)Makes sure that the directory exists, by creating it if necessary.voidmv(java.lang.String oldPath, java.lang.String newPath)Move a file or directory.private byte[]openDirectory(java.lang.String path)private SFTPv3FileHandleopenFile(java.lang.String fileName, int flags, SFTPv3FileAttributes attr)SFTPv3FileHandleopenFileRO(java.lang.String fileName)Open a file for reading.SFTPv3FileHandleopenFileRW(java.lang.String fileName)Open a file for reading and writing.intread(SFTPv3FileHandle handle, long fileOffset, byte[] dst, int dstoff, int len)Read bytes from a file.java.io.InputStreamread(java.lang.String file)private SFTPv3FileAttributesreadAttrs(TypesReader tr)private voidreadBytes(byte[] buff, int pos, int len)java.lang.StringreadLink(java.lang.String path)Read the target of a symbolic link.private byte[]receiveMessage(int maxlen)Read a message and guarantee that the contents is not larger thanmaxlenbytes.voidrm(java.lang.String fileName)Remove a file.voidrmdir(java.lang.String dirName)Remove an empty directory.private java.util.VectorscanDirectory(byte[] handle)private voidsendMessage(int type, int requestId, byte[] msg)private voidsendMessage(int type, int requestId, byte[] msg, int off, int len)voidsetCharset(java.lang.String charset)Set the charset used to convert between Java Unicode Strings and byte encodings used by the server for paths and file names.voidsetstat(java.lang.String path, SFTPv3FileAttributes attr)Modify the attributes of a file.SFTPv3FileAttributesstat(java.lang.String path)Retrieve the file attributes of a file.private SFTPv3FileAttributesstatBoth(java.lang.String path, int statMethod)voidwrite(SFTPv3FileHandle handle, long fileOffset, byte[] src, int srcoff, int len)Write bytes to a file.java.io.OutputStreamwriteToFile(java.lang.String path)Creates a new file and writes to it.
-
-
-
Field Detail
-
conn
final Connection conn
-
sess
final Session sess
-
debug
final java.io.PrintStream debug
-
flag_closed
boolean flag_closed
-
is
java.io.InputStream is
-
os
java.io.OutputStream os
-
protocol_version
int protocol_version
-
server_extensions
java.util.HashMap server_extensions
-
next_request_id
int next_request_id
-
charsetName
java.lang.String charsetName
-
-
Constructor Detail
-
SFTPv3Client
public SFTPv3Client(Connection conn, java.io.PrintStream debug) throws java.io.IOException
Deprecated.this constructor (debug version) will disappear in the future, useSFTPv3Client(Connection)instead.Create a SFTP v3 client.- Parameters:
conn- The underlying SSH-2 connection to be used.debug-- Throws:
java.io.IOException
-
SFTPv3Client
public SFTPv3Client(Connection conn) throws java.io.IOException
Create a SFTP v3 client.- Parameters:
conn- The underlying SSH-2 connection to be used.- Throws:
java.io.IOException
-
-
Method Detail
-
setCharset
public void setCharset(java.lang.String charset) throws java.io.IOExceptionSet 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 ornullto use the platform's default encoding.- Throws:
java.io.IOException- See Also:
getCharset()
-
getCharset
public java.lang.String getCharset()
The currently used charset for filename encoding/decoding.- Returns:
- The name of the charset (
nullif the platform's default charset is being used) - See Also:
setCharset(String)
-
checkHandleValidAndOpen
private final void checkHandleValidAndOpen(SFTPv3FileHandle handle) throws java.io.IOException
- Throws:
java.io.IOException
-
sendMessage
private final void sendMessage(int type, int requestId, byte[] msg, int off, int len) throws java.io.IOException- Throws:
java.io.IOException
-
sendMessage
private final void sendMessage(int type, int requestId, byte[] msg) throws java.io.IOException- Throws:
java.io.IOException
-
readBytes
private final void readBytes(byte[] buff, int pos, int len) throws java.io.IOException- Throws:
java.io.IOException
-
receiveMessage
private final byte[] receiveMessage(int maxlen) throws java.io.IOExceptionRead a message and guarantee that the contents is not larger thanmaxlenbytes.Note: receiveMessage(34000) actually means that the message may be up to 34004 bytes (the length attribute preceeding the contents is 4 bytes).
- Parameters:
maxlen-- Returns:
- the message contents
- Throws:
java.io.IOException
-
generateNextRequestID
private final int generateNextRequestID()
-
closeHandle
private final void closeHandle(byte[] handle) throws java.io.IOException- Throws:
java.io.IOException
-
readAttrs
private SFTPv3FileAttributes readAttrs(TypesReader tr) throws java.io.IOException
- Throws:
java.io.IOException
-
fstat
public SFTPv3FileAttributes fstat(SFTPv3FileHandle handle) throws java.io.IOException
Retrieve the file attributes of an open file.- Parameters:
handle- a SFTPv3FileHandle handle.- Returns:
- a SFTPv3FileAttributes object.
- Throws:
java.io.IOException
-
statBoth
private SFTPv3FileAttributes statBoth(java.lang.String path, int statMethod) throws java.io.IOException
- Throws:
java.io.IOException
-
stat
public SFTPv3FileAttributes stat(java.lang.String path) throws java.io.IOException
Retrieve the file attributes of a file. This method follows symbolic links on the server.- Parameters:
path- See thecommentfor the class for more details.- Returns:
- a SFTPv3FileAttributes object.
- Throws:
java.io.IOException- See Also:
lstat(String)
-
lstat
public SFTPv3FileAttributes lstat(java.lang.String path) throws java.io.IOException
Retrieve the file attributes of a file. This method does NOT follow symbolic links on the server.- Parameters:
path- See thecommentfor the class for more details.- Returns:
- a SFTPv3FileAttributes object.
- Throws:
java.io.IOException- See Also:
stat(String)
-
readLink
public java.lang.String readLink(java.lang.String path) throws java.io.IOExceptionRead the target of a symbolic link.- Parameters:
path- See thecommentfor the class for more details.- Returns:
- The target of the link.
- Throws:
java.io.IOException
-
expectStatusOKMessage
private void expectStatusOKMessage(int id) throws java.io.IOException- Throws:
java.io.IOException
-
setstat
public void setstat(java.lang.String path, SFTPv3FileAttributes attr) throws java.io.IOExceptionModify 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 thecommentfor 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:
java.io.IOException
-
fsetstat
public void fsetstat(SFTPv3FileHandle handle, SFTPv3FileAttributes attr) throws java.io.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 handleattr- A SFTPv3FileAttributes object. Specifies the modifications to be made to the attributes of the file. Empty fields will be ignored.- Throws:
java.io.IOException
-
createSymlink
public void createSymlink(java.lang.String src, java.lang.String target) throws java.io.IOExceptionCreate a symbolic link on the server. Creates a link "src" that points to "target".
-
canonicalPath
public java.lang.String canonicalPath(java.lang.String path) throws java.io.IOExceptionHave 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 thecommentfor the class for more details.- Returns:
- An absolute path.
- Throws:
java.io.IOException
-
scanDirectory
private final java.util.Vector scanDirectory(byte[] handle) throws java.io.IOException- Throws:
java.io.IOException
-
openDirectory
private final byte[] openDirectory(java.lang.String path) throws java.io.IOException- Throws:
java.io.IOException
-
expandString
private final java.lang.String expandString(byte[] b, int off, int len)
-
init
private void init() throws java.io.IOException- Throws:
java.io.IOException
-
getProtocolVersion
public int getProtocolVersion()
Returns the negotiated SFTP protocol version between the client and the server.- Returns:
- SFTP protocol version, i.e., "3".
-
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 theclose()method, you are likely wasting resources.
-
ls
public java.util.Vector ls(java.lang.String dirName) throws java.io.IOExceptionList the contents of a directory.- Parameters:
dirName- See thecommentfor the class for more details.- Returns:
- A Vector containing
SFTPv3DirectoryEntryobjects. - Throws:
java.io.IOException
-
mkdir
public void mkdir(java.lang.String dirName, int posixPermissions) throws java.io.IOExceptionCreate a new directory.- Parameters:
dirName- See thecommentfor 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:
java.io.IOException
-
rm
public void rm(java.lang.String fileName) throws java.io.IOExceptionRemove a file.- Parameters:
fileName- See thecommentfor the class for more details.- Throws:
java.io.IOException
-
rmdir
public void rmdir(java.lang.String dirName) throws java.io.IOExceptionRemove an empty directory.- Parameters:
dirName- See thecommentfor the class for more details.- Throws:
java.io.IOException
-
mv
public void mv(java.lang.String oldPath, java.lang.String newPath) throws java.io.IOExceptionMove a file or directory.
-
openFileRO
public SFTPv3FileHandle openFileRO(java.lang.String fileName) throws java.io.IOException
Open a file for reading.- Parameters:
fileName- See thecommentfor the class for more details.- Returns:
- a SFTPv3FileHandle handle
- Throws:
java.io.IOException
-
openFileRW
public SFTPv3FileHandle openFileRW(java.lang.String fileName) throws java.io.IOException
Open a file for reading and writing.- Parameters:
fileName- See thecommentfor the class for more details.- Returns:
- a SFTPv3FileHandle handle
- Throws:
java.io.IOException
-
createFile
public SFTPv3FileHandle createFile(java.lang.String fileName) throws java.io.IOException
Create a file and open it for reading and writing. Same ascreateFile(fileName, null).- Parameters:
fileName- See thecommentfor the class for more details.- Returns:
- a SFTPv3FileHandle handle
- Throws:
java.io.IOException
-
createFile
public SFTPv3FileHandle createFile(java.lang.String fileName, SFTPv3FileAttributes attr) throws java.io.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 thecommentfor the class for more details.attr- may benullto use server defaults. Probably only theuid,gidandpermissions(remember the server may apply a umask) entries of theSFTPv3FileHandlestructure make sense. You need only to set those fields where you want to override the server's defaults.- Returns:
- a SFTPv3FileHandle handle
- Throws:
java.io.IOException
-
createFileTruncate
public SFTPv3FileHandle createFileTruncate(java.lang.String fileName) throws java.io.IOException
Create a file (truncate it if it already exists) and open it for reading and writing. Same ascreateFileTruncate(fileName, null).- Parameters:
fileName- See thecommentfor the class for more details.- Returns:
- a SFTPv3FileHandle handle
- Throws:
java.io.IOException
-
createFileTruncate
public SFTPv3FileHandle createFileTruncate(java.lang.String fileName, SFTPv3FileAttributes attr) throws java.io.IOException
reate a file (truncate it if it already exists) 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 thecommentfor the class for more details.attr- may benullto use server defaults. Probably only theuid,gidandpermissions(remember the server may apply a umask) entries of theSFTPv3FileHandlestructure make sense. You need only to set those fields where you want to override the server's defaults.- Returns:
- a SFTPv3FileHandle handle
- Throws:
java.io.IOException
-
createAttrs
private byte[] createAttrs(SFTPv3FileAttributes attr)
-
openFile
private SFTPv3FileHandle openFile(java.lang.String fileName, int flags, SFTPv3FileAttributes attr) throws java.io.IOException
- Throws:
java.io.IOException
-
read
public int read(SFTPv3FileHandle handle, long fileOffset, byte[] dst, int dstoff, int len) throws java.io.IOException
Read bytes from a file. No more than 32768 bytes may be read at once. Be aware that the semantics of read() are different than for Java streams.- The server will read as many bytes as it can from the file (up to
len), and return them. - If EOF is encountered before reading any data,
-1is returned. - If an error occurs, an exception is thrown .
- For normal disk files, it is guaranteed that the server will return the specified number of bytes, or up to end of file. For, e.g., device files this may return fewer bytes than requested.
- Parameters:
handle- a SFTPv3FileHandle handlefileOffset- offset (in bytes) in the filedst- the destination byte arraydstoff- offset in the destination byte arraylen- how many bytes to read, 0 < len <= 32768 bytes- 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:
java.io.IOException
- The server will read as many bytes as it can from the file (up to
-
write
public void write(SFTPv3FileHandle handle, long fileOffset, byte[] src, int srcoff, int len) throws java.io.IOException
Write bytes to a file. Iflen> 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:
java.io.IOException
-
closeFile
public void closeFile(SFTPv3FileHandle handle) throws java.io.IOException
Close a file.- Parameters:
handle- a SFTPv3FileHandle handle- Throws:
java.io.IOException
-
exists
public boolean exists(java.lang.String path) throws java.io.IOExceptionChecks if the given path exists.- Throws:
java.io.IOException
-
_stat
public SFTPv3FileAttributes _stat(java.lang.String path) throws java.io.IOException
Gracefulstat(String)that returns null if the path doesn't exist.- Throws:
java.io.IOException
-
mkdirs
public void mkdirs(java.lang.String path, int posixPermission) throws java.io.IOExceptionMakes sure that the directory exists, by creating it if necessary.- Throws:
java.io.IOException
-
writeToFile
public java.io.OutputStream writeToFile(java.lang.String path) throws java.io.IOExceptionCreates a new file and writes to it.- Throws:
java.io.IOException
-
read
public java.io.InputStream read(java.lang.String file) throws java.io.IOException- Throws:
java.io.IOException
-
chmod
public void chmod(java.lang.String path, int permissions) throws java.io.IOException- Throws:
java.io.IOException
-
-