Class SftpSubsystem
- All Implemented Interfaces:
Closeable,AutoCloseable,Runnable,FileSystemAware,SessionContextHolder,SessionHolder<ServerSession>,ExecutorServiceCarrier,ChannelDataReceiver,ServerChannelSessionHolder,AsyncCommand,AsyncCommandErrorStreamAware,AsyncCommandInputStreamAware,AsyncCommandOutputStreamAware,AsyncCommandStreamsAware,Command,CommandDirectErrorStreamAware,CommandDirectInputStreamAware,CommandDirectOutputStreamAware,CommandDirectStreamsAware,CommandLifecycle,ServerSessionHolder,SftpErrorStatusDataHandlerProvider,SftpEventListenerManager,SftpFileSystemAccessorProvider,SftpSubsystemEnvironment,SftpSubsystemProxy,SftpUnsupportedAttributePolicyProvider
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected final Bufferprotected ExitCallbackprotected static final Bufferprotected final AtomicBooleanprotected Pathprotected Environmentprotected CloseableExecutorServiceprotected intprotected FileSystemprotected intprotected intprotected IoOutputStreamprotected Future<?> protected Randomprotected final BlockingQueue<Buffer> protected final AtomicLongprivate final ServerSessionprotected intprotected byte[]Fields inherited from class org.apache.sshd.sftp.server.AbstractSftpSubsystemHelper
DEFAULT_ACL_SUPPORTED_MASK, DEFAULT_OPEN_SSH_EXTENSIONS, DEFAULT_OPEN_SSH_EXTENSIONS_NAMES, DEFAULT_SUPPORTED_CLIENT_EXTENSIONSFields inherited from class org.apache.sshd.common.util.logging.AbstractLoggingBean
logFields inherited from interface org.apache.sshd.sftp.server.SftpSubsystemEnvironment
ALL_SFTP_IMPL, HIGHER_SFTP_IMPL, LOWER_SFTP_IMPL, SUPPORTED_SFTP_VERSIONS -
Constructor Summary
ConstructorsConstructorDescriptionSftpSubsystem(ChannelSession channel, SftpSubsystemConfigurator configurator) -
Method Summary
Modifier and TypeMethodDescriptionvoidclose()protected voidprotected voidcreateLink(int id, String existingPath, String linkPath, boolean symLink) intdata(ChannelSession channel, byte[] buf, int start, int len) Called when the server receives additional bytes from the client.voiddestroy(ChannelSession channel) This method is called by the SSH server to destroy the command because the client has disconnected somehow.protected voidprotected voiddoCheckFileHash(int id, String targetType, String target, Collection<String> algos, long startOffset, long length, int blockSize, Buffer buffer) protected voidprotected voiddoCopyData(int id, String readHandle, long readOffset, long readLength, String writeHandle, long writeOffset) protected voiddoFSetStat(int id, String handle, Map<String, ?> attrs) protected voidprotected byte[]doMD5Hash(int id, String targetType, String target, long startOffset, long length, byte[] quickCheckHash) protected Stringprotected StringdoOpenDir(int id, String path, Path dir, LinkOption... options) protected voiddoOpenSSHFsync(int id, String handle) protected voidprotected intdoRead(int id, String handle, long offset, int length, byte[] data, int doff, AtomicReference<Boolean> eof) protected voidprotected voiddoTextSeek(int id, String handle, long line) protected voidprotected voiddoVersionSelect(Buffer buffer, int id, String proposed) protected voidprotected StringgenerateFileHandle(Path file) Generates a file handle, which is used as key in aMapto record open file handles across requests.intprotected voidinitializeSessionRelatedMember(ServerSession session, ChannelSession channel) protected BufferprepareReply(Buffer buffer) protected ChannelDataReceiverresolveErrorDataChannelReceiver(ChannelSession channelSession, ChannelDataReceiver receiver) voidrun()protected voidvoidSet the error stream that can be used by the shell to write its errors.voidsetExitCallback(ExitCallback callback) Set the callback that the shell has to call when it is closed.voidsetFileSystem(FileSystem fileSystem) Set the file system in which this shell will be executed.voidSet the input stream that can be used by the shell to read input.voidSet the error stream that can be used by the shell to write its errors.voidSet the input stream that can be used by the shell to read input.voidSet the output stream that can be used by the shell to write its output.voidSet the output stream that can be used by the shell to write its output.voidstart(ChannelSession channel, Environment env) Starts the command execution.Methods inherited from class org.apache.sshd.sftp.server.AbstractSftpSubsystemHelper
addMissingAttribute, addSftpEventListener, appendAclSupportedExtension, appendExtensions, appendNewlineExtension, appendOpenSSHExtensions, appendSupported2Extension, appendSupportedExtension, appendVendorIdExtension, appendVersionsExtension, checkSymlinkState, checkVersionCompatibility, doBlock, doCheckFileHash, doCheckFileHash, doClose, doCopyData, doCopyFile, doCopyFile, doCopyFile, doExtended, doFSetStat, doFStat, doLink, doLink, doLStat, doLStat, doMakeDirectory, doMakeDirectory, doMD5Hash, doMD5Hash, doOpen, doOpenDir, doOpenSSHFsync, doOpenSSHHardLink, doOpenSSHHardLink, doOpenSSHLimits, doPosixRename, doRead, doReadDir, doReadLink, doReadLink, doRealPath, doRealPathV345, doRealPathV6, doRemove, doRemove, doRemoveDirectory, doRemoveDirectory, doRemoveFile, doRename, doRename, doRename, doSetAttributes, doSetStat, doSetStat, doSpaceAvailable, doSpaceAvailable, doStat, doStat, doSymLink, doSymLink, doTextSeek, doUnblock, doUnsupported, doUnsupportedExtension, doVersionSelect, doWrite, executeExtendedCommand, getAttributes, getAttributes, getErrorStatusDataHandler, getFileSystemAccessor, getLongName, getLongName, getLongName, getLongName, getOpenSSHLimitsExtensionInfo, getPathResolutionLinkOption, getServerChannelSession, getSftpEventListenerProxy, getShortName, getSupportedClientExtensions, getUnsupportedAttributePolicy, handleReadFileAttributesException, handleSetFileAttributeFailure, handleUnknownStatusFileAttributes, handleUnsupportedAttributes, handleUserPrincipalLookupServiceException, normalize, process, readAttrs, readFileAttributes, removeSftpEventListener, resolveAclSupportedCapabilities, resolveFile, resolveFileAttributes, resolveMissingFileAttributes, resolveMissingFileAttributeValue, resolveNewlineValue, resolveNormalizedLocation, resolveOpenSSHExtensions, resolvePathResolutionFollowLinks, resolveReportedFileAttributes, sendAttrs, sendHandle, sendLink, sendPath, sendStatus, sendStatus, sendStatus, setFileAccessControl, setFileAttribute, setFileAttributes, setFileExtensions, setFileOwnership, setFilePermissions, setFileRawViewAttribute, setFileTime, signalOpenFailure, signalRemovalPreConditionFailure, toGroup, toUser, validateHandle, validateParentExistWithNoSymlinksIfNeverFollowSymlinks, validateProposedVersion, validateRealPath, writeAttrs, writeDirEntry, writeDirEntryMethods inherited from class org.apache.sshd.common.util.logging.AbstractLoggingBean
debug, debug, debug, debug, debug, error, error, error, error, error, getSimplifiedLogger, info, info, warn, warn, warn, warn, warn, warn, warn, warnMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.apache.sshd.common.file.FileSystemAware
setFileSystemFactoryMethods inherited from interface org.apache.sshd.common.session.SessionHolder
getSessionContextMethods inherited from interface org.apache.sshd.sftp.server.SftpSubsystemEnvironment
getSession
-
Field Details
-
CLOSE
-
closed
-
requestsCount
-
extensions
-
handles
-
buffer
-
requests
-
callback
-
out
-
env
-
randomizer
-
maxHandleCount
protected int maxHandleCount -
unusedHandles
-
fileHandleSize
protected int fileHandleSize -
maxFileHandleRounds
protected int maxFileHandleRounds -
pendingFuture
-
workBuf
protected byte[] workBuf -
fileSystem
-
defaultDir
-
version
protected int version -
executorService
-
serverSession
-
-
Constructor Details
-
SftpSubsystem
- Parameters:
channel- TheChannelSessionthrough which the command was receivedconfigurator- TheSftpSubsystemConfiguratorto use
-
-
Method Details
-
resolveErrorDataChannelReceiver
protected ChannelDataReceiver resolveErrorDataChannelReceiver(ChannelSession channelSession, ChannelDataReceiver receiver) -
getVersion
public int getVersion()- Specified by:
getVersionin interfaceSftpSubsystemEnvironment- Returns:
- The negotiated version
-
getDefaultDirectory
- Specified by:
getDefaultDirectoryin interfaceSftpSubsystemEnvironment- Returns:
- The default root directory used to resolve relative paths - a.k.a. the
chrootlocation
-
getExecutorService
- Specified by:
getExecutorServicein interfaceExecutorServiceCarrier- Returns:
- The
CloseableExecutorServiceto use
-
initializeSessionRelatedMember
-
getServerSession
- Specified by:
getServerSessionin interfaceServerSessionHolder- Returns:
- The underlying
ServerSessionused
-
setFileSystem
Description copied from interface:FileSystemAwareSet the file system in which this shell will be executed.- Specified by:
setFileSystemin interfaceFileSystemAware- Parameters:
fileSystem- the file system
-
setExitCallback
Description copied from interface:CommandSet the callback that the shell has to call when it is closed.- Specified by:
setExitCallbackin interfaceCommand- Parameters:
callback- TheExitCallbackto call when shell is closed
-
setInputStream
Description copied from interface:CommandDirectInputStreamAwareSet the input stream that can be used by the shell to read input.- Specified by:
setInputStreamin interfaceCommandDirectInputStreamAware- Parameters:
in- TheInputStreamused by the shell to read input.
-
setOutputStream
Description copied from interface:CommandDirectOutputStreamAwareSet the output stream that can be used by the shell to write its output.- Specified by:
setOutputStreamin interfaceCommandDirectOutputStreamAware- Parameters:
out- TheOutputStreamused by the shell to write its output
-
setErrorStream
Description copied from interface:CommandDirectErrorStreamAwareSet the error stream that can be used by the shell to write its errors.- Specified by:
setErrorStreamin interfaceCommandDirectErrorStreamAware- Parameters:
err- TheOutputStreamused by the shell to write its errors
-
setIoInputStream
Description copied from interface:AsyncCommandInputStreamAwareSet the input stream that can be used by the shell to read input.- Specified by:
setIoInputStreamin interfaceAsyncCommandInputStreamAware- Parameters:
in- TheIoInputStreamused by the shell to read input
-
setIoOutputStream
Description copied from interface:AsyncCommandOutputStreamAwareSet the output stream that can be used by the shell to write its output.- Specified by:
setIoOutputStreamin interfaceAsyncCommandOutputStreamAware- Parameters:
out- TheIoOutputStreamused by the shell to write its output
-
setIoErrorStream
Description copied from interface:AsyncCommandErrorStreamAwareSet the error stream that can be used by the shell to write its errors.- Specified by:
setIoErrorStreamin interfaceAsyncCommandErrorStreamAware- Parameters:
err- TheIoOutputStreamused by the shell to write its errors
-
start
Description copied from interface:CommandLifecycleStarts the command execution. All streams must have been set before calling this method. The command should implementRunnable, and this method should spawn a new thread like:Thread(this).start();- Specified by:
startin interfaceCommandLifecycle- Parameters:
channel- TheChannelSessionthrough which the command has been receivedenv- TheEnvironment- Throws:
IOException- If failed to start
-
data
Description copied from interface:ChannelDataReceiverCalled when the server receives additional bytes from the client. When
Closeable.close()-d then indicates EOF - The client will no longer send us any more data.SSH channels use the windowing mechanism to perform flow control, much like TCP does. The server gives the client the initial window size, which represents the number of bytes the client can send to the server. As the server receives data, it can send a message to the client to allow it to send more data.
The return value from this method is used to control this behaviour. Intuitively speaking, the callee returns the number of bytes consumed by this method, by the time this method returns. Picture a one-way long bridge (for example Golden Gate Bridge) with toll plazas on both sides. The window size is the maximum number of cars allowed on the bridge. Here we are on the receiving end, so our job here is to count the number of cars as it leaves the bridge, and if enough of them left, we'll signal the sending end that they can let in more cars. The return value of this method counts the number of cars that are leaving in this batch.
In simple cases, where the callee has consumed the bytes before it returns, the return value must be the same value as the 'len' parameter given.
On the other hand, if the callee is queueing up the received bytes somewhere to be consumed later (for example by another thread), then this method should return 0, for the bytes aren't really consumed yet. And when at some later point the bytes are actually used, then you'll invoke
channel.getLocalWindow().consumeAndCheck(len)to let the channel know that bytes are consumed.This behaviour will result in a better flow control, as the server will not allow the SSH client to overflow its buffer. If instead you always return the value passed in the 'len' parameter, the place where you are queueing up bytes may overflow.
In either case, the callee must account for every bytes it receives in this method. Returning 0 and failing to call back
channel.getLocalWindow().consumeAndCheck(len)later will dry up the window size, and eventually the client will stop sending you any data.In the SSH protocol, this method invocation is triggered by a SSH_MSG_CHANNEL_DATA message.
- Specified by:
datain interfaceChannelDataReceiver- Parameters:
channel- The caller to which thisChannelDataReceiveris assigned. Never null.buf- Holds the bytes received. This buffer belongs to the caller, and it might get reused by the caller as soon as this method returns.start- buf[start] is the first byte that received from the client.len- the length of the bytes received. Can be zero.- Returns:
- The number of bytes consumed, for the purpose of the flow control. For a simple use case, you return the value given by the 'len' parameter. See the method javadoc for more details.
- Throws:
IOException- if failed to consume the data
-
run
public void run() -
close
- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Throws:
IOException
-
doProcess
- Overrides:
doProcessin classAbstractSftpSubsystemHelper- Throws:
IOException
-
createLink
protected void createLink(int id, String existingPath, String linkPath, boolean symLink) throws IOException - Specified by:
createLinkin classAbstractSftpSubsystemHelper- Throws:
IOException
-
doTextSeek
- Specified by:
doTextSeekin classAbstractSftpSubsystemHelper- Throws:
IOException
-
doOpenSSHFsync
- Specified by:
doOpenSSHFsyncin classAbstractSftpSubsystemHelper- Throws:
IOException
-
doCheckFileHash
protected void doCheckFileHash(int id, String targetType, String target, Collection<String> algos, long startOffset, long length, int blockSize, Buffer buffer) throws Exception - Specified by:
doCheckFileHashin classAbstractSftpSubsystemHelper- Throws:
Exception
-
doMD5Hash
protected byte[] doMD5Hash(int id, String targetType, String target, long startOffset, long length, byte[] quickCheckHash) throws Exception - Specified by:
doMD5Hashin classAbstractSftpSubsystemHelper- Throws:
Exception
-
doVersionSelect
- Specified by:
doVersionSelectin classAbstractSftpSubsystemHelper- Throws:
IOException
-
doBlock
protected void doBlock(int id, String handle, long offset, long length, int mask) throws IOException - Specified by:
doBlockin classAbstractSftpSubsystemHelper- Throws:
IOException
-
doUnblock
- Specified by:
doUnblockin classAbstractSftpSubsystemHelper- Throws:
IOException
-
doCopyData
protected void doCopyData(int id, String readHandle, long readOffset, long readLength, String writeHandle, long writeOffset) throws IOException - Specified by:
doCopyDatain classAbstractSftpSubsystemHelper- Throws:
IOException
-
doReadDir
- Specified by:
doReadDirin classAbstractSftpSubsystemHelper- Throws:
IOException
-
doOpenDir
- Specified by:
doOpenDirin classAbstractSftpSubsystemHelper- Throws:
IOException
-
doFSetStat
- Specified by:
doFSetStatin classAbstractSftpSubsystemHelper- Throws:
IOException
-
doFStat
- Specified by:
doFStatin classAbstractSftpSubsystemHelper- Throws:
IOException
-
doWrite
protected void doWrite(int id, String handle, long offset, int length, byte[] data, int doff, int remaining) throws IOException - Specified by:
doWritein classAbstractSftpSubsystemHelper- Throws:
IOException
-
doRead
protected int doRead(int id, String handle, long offset, int length, byte[] data, int doff, AtomicReference<Boolean> eof) throws IOException - Specified by:
doReadin classAbstractSftpSubsystemHelper- Throws:
IOException
-
doClose
- Specified by:
doClosein classAbstractSftpSubsystemHelper- Throws:
IOException
-
doOpen
protected String doOpen(int id, String path, int pflags, int access, Map<String, Object> attrs) throws IOException- Specified by:
doOpenin classAbstractSftpSubsystemHelper- Parameters:
id- Request idpath- Pathpflags- Open mode flags - seeSSH_FXF_XXXflagsaccess- Access mode flags - seeACE4_XXXflagsattrs- Requested attributes- Returns:
- The assigned (opaque) handle
- Throws:
IOException- if failed to execute
-
generateFileHandle
Generates a file handle, which is used as key in aMapto record open file handles across requests. For historical reasons, the handle is returned as aString, and other APIs also useStringfor handles, so we're kind of stuck with that.As of version 2.10.1, the result must be encoded using
StandardCharsets.ISO_8859_1, and it must not have more than 256 IOS-8859-1 characters (i.e., bytes).This method is called with the monitor on the
handlesMapheld.- Parameters:
file- to generate a handle for- Returns:
- the file handle
- Throws:
IOException- if no handle could be generated
-
doInit
- Specified by:
doInitin classAbstractSftpSubsystemHelper- Throws:
IOException
-
prepareReply
- Specified by:
prepareReplyin classAbstractSftpSubsystemHelper
-
send
- Specified by:
sendin classAbstractSftpSubsystemHelper- Throws:
IOException
-
destroy
Description copied from interface:CommandLifecycleThis method is called by the SSH server to destroy the command because the client has disconnected somehow.- Specified by:
destroyin interfaceCommandLifecycle- Parameters:
channel- TheChannelSessionthrough which the command has been received
-
closeAllHandles
protected void closeAllHandles()
-