Class SessionHelper
- java.lang.Object
-
- org.apache.sshd.common.util.logging.AbstractLoggingBean
-
- org.apache.sshd.common.util.closeable.IoBaseCloseable
-
- org.apache.sshd.common.util.closeable.AbstractCloseable
-
- org.apache.sshd.common.util.closeable.AbstractInnerCloseable
-
- org.apache.sshd.common.kex.AbstractKexFactoryManager
-
- org.apache.sshd.common.session.helpers.SessionHelper
-
- All Implemented Interfaces:
java.io.Closeable
,java.lang.AutoCloseable
,java.nio.channels.Channel
,AttributeRepository
,AttributeStore
,MutableUserHolder
,UsernameHolder
,ChannelListenerManager
,ChannelStreamWriterResolver
,ChannelStreamWriterResolverManager
,Closeable
,FactoryManagerHolder
,PortForwardingEventListenerManager
,PortForwardingInformationProvider
,KexExtensionHandlerManager
,KexFactoryManager
,PropertyResolver
,ReservedSessionMessagesManager
,Session
,SessionContext
,SessionDisconnectHandlerManager
,SessionHeartbeatController
,SessionListenerManager
,UnknownChannelReferenceHandlerManager
,SignatureFactoriesHolder
,SignatureFactoriesManager
,ConnectionEndpointsIndicator
- Direct Known Subclasses:
AbstractSession
public abstract class SessionHelper extends AbstractKexFactoryManager implements Session
Contains split code in order to makeAbstractSession
class smaller
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class org.apache.sshd.common.util.closeable.AbstractCloseable
AbstractCloseable.State
-
Nested classes/interfaces inherited from interface org.apache.sshd.common.AttributeRepository
AttributeRepository.AttributeKey<T>
-
Nested classes/interfaces inherited from interface org.apache.sshd.common.session.SessionHeartbeatController
SessionHeartbeatController.HeartbeatType
-
-
Field Summary
Fields Modifier and Type Field Description private java.util.Map<AttributeRepository.AttributeKey<?>,java.lang.Object>
attributes
Session specific attributesprivate boolean
authed
Boolean indicating if this session has been authenticated or notprotected java.time.Instant
authStart
private ChannelStreamWriterResolver
channelStreamPacketWriterResolver
protected java.time.Instant
idleStart
private IoSession
ioSession
The underlying network sessionprivate java.util.Map<java.lang.String,java.lang.Object>
properties
The session specific propertiesprivate ReservedSessionMessagesHandler
reservedSessionMessagesHandler
private boolean
serverSession
Client or server sideprivate SessionDisconnectHandler
sessionDisconnectHandler
protected java.lang.Object
sessionLock
Session level lock for regulating access to sensitive dataprivate java.util.concurrent.atomic.AtomicReference<TimeoutIndicator>
timeoutStatus
private UnknownChannelReferenceHandler
unknownChannelReferenceHandler
private java.lang.String
username
The name of the authenticated user-
Fields inherited from class org.apache.sshd.common.util.closeable.AbstractCloseable
closeFuture, futureLock, state
-
Fields inherited from class org.apache.sshd.common.util.logging.AbstractLoggingBean
log
-
Fields inherited from interface org.apache.sshd.common.channel.throttle.ChannelStreamWriterResolver
NONE
-
Fields inherited from interface org.apache.sshd.common.PropertyResolver
EMPTY
-
Fields inherited from interface org.apache.sshd.common.session.SessionContext
DEFAULT_SSH_VERSION_PREFIX, FALLBACK_SSH_VERSION_PREFIX, MAX_VERSION_LINE_LENGTH
-
-
Constructor Summary
Constructors Modifier Constructor Description protected
SessionHelper(boolean serverSession, FactoryManager factoryManager, IoSession ioSession)
Create a new session.
-
Method Summary
All Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description java.util.Collection<AttributeRepository.AttributeKey<?>>
attributeKeys()
protected long
calculateNextIgnorePacketCount(Random r, long freq, int variance)
protected TimeoutIndicator
checkAuthenticationTimeout(java.time.Instant now, java.time.Duration authTimeout)
Checks if authentication timeout expiredprotected TimeoutIndicator
checkForTimeouts()
Checks whether the session has timed out (both authentication and idle timeouts are checked).protected TimeoutIndicator
checkIdleTimeout(java.time.Instant now, java.time.Duration idleTimeout)
Checks if idle timeout expiredvoid
clearAttributes()
Removes all currently stored user-defined attributes<T> T
computeAttributeIfAbsent(AttributeRepository.AttributeKey<T> key, java.util.function.Function<? super AttributeRepository.AttributeKey<T>,? extends T> resolver)
If the specified key is not already associated with a value (or is mapped tonull
), attempts to compute its value using the given mapping function and enters it into this map unlessnull
.protected java.util.Map<KexProposalOption,java.lang.String>
createProposal(java.lang.String hostKeyTypes)
Create our proposal for SSH negotiationvoid
disconnect(int reason, java.lang.String msg)
Send a disconnect packet with the given reason and message.protected void
doInvokeDebugMessageHandler(Buffer buffer)
Invoked byhandleDebug(Buffer)
after validating that the buffer structure seems well-formed and also resetting the idle timeout.protected void
doInvokeIgnoreMessageHandler(Buffer buffer)
Invoked byhandleDebug(Buffer)
after validating that the buffer structure seems well-formed and also resetting the idle timeout.protected boolean
doInvokeUnimplementedMessageHandler(int cmd, Buffer buffer)
protected java.util.List<java.lang.String>
doReadIdentification(Buffer buffer, boolean server)
Read the remote identification from this buffer.void
exceptionCaught(java.lang.Throwable t)
Handle any exceptions that occurred on this session.<T> T
getAttribute(AttributeRepository.AttributeKey<T> key)
Returns the value of the user-defined attribute.int
getAttributesCount()
java.time.Duration
getAuthTimeout()
java.time.Instant
getAuthTimeoutStart()
java.util.List<SshdSocketAddress>
getBoundLocalPortForwards(int port)
SshdSocketAddress
getBoundRemotePortForward(int port)
ChannelStreamWriterResolver
getChannelStreamWriterResolver()
protected abstract ConnectionService
getConnectionService()
FactoryManager
getFactoryManager()
protected Forwarder
getForwarder()
java.time.Duration
getIdleTimeout()
java.time.Instant
getIdleTimeoutStart()
IoSession
getIoSession()
java.util.List<java.util.Map.Entry<SshdSocketAddress,SshdSocketAddress>>
getLocalForwardsBindings()
PropertyResolver
getParentPropertyResolver()
java.util.Map<java.lang.String,java.lang.Object>
getProperties()
A map of properties that can be used to configure the SSH server or client.java.util.List<java.util.Map.Entry<java.lang.Integer,SshdSocketAddress>>
getRemoteForwardsBindings()
ReservedSessionMessagesHandler
getReservedSessionMessagesHandler()
SessionDisconnectHandler
getSessionDisconnectHandler()
java.util.List<SshdSocketAddress>
getStartedLocalPortForwards()
java.util.NavigableSet<java.lang.Integer>
getStartedRemotePortForwards()
TimeoutIndicator
getTimeoutStatus()
Check if timeout has occurred.UnknownChannelReferenceHandler
getUnknownChannelReferenceHandler()
java.lang.String
getUsername()
protected void
handleDebug(Buffer buffer)
protected void
handleDisconnect(int code, java.lang.String msg, java.lang.String lang, Buffer buffer)
protected void
handleDisconnect(Buffer buffer)
protected void
handleIgnore(Buffer buffer)
protected void
handleUnimplemented(Buffer buffer)
protected void
invokeSessionSignaller(Invoker<SessionListener,java.lang.Void> invoker)
boolean
isAuthenticated()
boolean
isLocalPortForwardingStartedForPort(int port)
Test if local port forwarding is startedboolean
isRemotePortForwardingStartedForPort(int port)
Test if remote port forwarding is startedboolean
isServerSession()
Quick indication if this is a server or client session (instead of having to askinstanceof
).protected java.util.Map<KexProposalOption,java.lang.String>
mergeProposals(java.util.Map<KexProposalOption,java.lang.String> current, java.util.Map<KexProposalOption,java.lang.String> proposal)
protected Buffer
preProcessEncodeBuffer(int cmd, Buffer buffer)
Invoked by the session before encoding the buffer in order to make sure that it is at least of sizeSSH_PACKET_HEADER_LEN
.<T> T
removeAttribute(AttributeRepository.AttributeKey<T> key)
Removes the user-defined attributejava.time.Instant
resetAuthTimeout()
Re-start the authentication timeout timerjava.time.Instant
resetIdleTimeout()
Re-start idle timeout timerprotected byte[]
resizeKey(byte[] e, int kdfSize, Digest hash, byte[] k, byte[] h)
Method used while putting new keys into use that will resize the key used to initialize the cipher to the needed length.ChannelStreamWriterResolver
resolveChannelStreamWriterResolver()
protected java.lang.String
resolveIdentificationString(java.lang.String configPropName)
Resolves the identification to send to the peer session by consulting the associatedFactoryManager
.protected java.net.SocketAddress
resolvePeerAddress(java.net.SocketAddress knownAddress)
protected ReservedSessionMessagesHandler
resolveReservedSessionMessagesHandler()
protected java.lang.String
resolveSessionKexProposal(java.lang.String hostKeyTypes)
UnknownChannelReferenceHandler
resolveUnknownChannelReferenceHandler()
Check if current manager has a specific handler set for it - if not, try and resolve one from the "parent" container (if any)IoWriteFuture
sendDebugMessage(boolean display, java.lang.Object msg, java.lang.String lang)
Sends anSSH_MSG_DEBUG
to the peer sessionprotected IoWriteFuture
sendIdentification(java.lang.String ident)
Send our identification.IoWriteFuture
sendIgnoreMessage(byte... data)
Sends anSSH_MSG_IGNORE
to the peer sessionprotected IoWriteFuture
sendNotImplemented(long seqNoValue)
Sends aSSH_MSG_UNIMPLEMENTED
message<T> T
setAttribute(AttributeRepository.AttributeKey<T> key, T value)
Sets a user-defined attribute.void
setAuthenticated()
void
setChannelStreamWriterResolver(ChannelStreamWriterResolver resolver)
void
setReservedSessionMessagesHandler(ReservedSessionMessagesHandler handler)
void
setSessionDisconnectHandler(SessionDisconnectHandler sessionDisconnectHandler)
void
setUnknownChannelReferenceHandler(UnknownChannelReferenceHandler unknownChannelReferenceHandler)
void
setUsername(java.lang.String username)
protected void
signalDisconnect(int code, java.lang.String msg, java.lang.String lang, boolean initiator)
protected void
signalDisconnect(SessionListener listener, int code, java.lang.String msg, java.lang.String lang, boolean initiator)
protected void
signalExceptionCaught(java.lang.Throwable t)
protected void
signalExceptionCaught(SessionListener listener, java.lang.Throwable t)
protected void
signalNegotiationEnd(java.util.Map<KexProposalOption,java.lang.String> c2sOptions, java.util.Map<KexProposalOption,java.lang.String> s2cOptions, java.util.Map<KexProposalOption,java.lang.String> negotiatedGuess, java.lang.Throwable reason)
protected void
signalNegotiationEnd(SessionListener listener, java.util.Map<KexProposalOption,java.lang.String> c2sOptions, java.util.Map<KexProposalOption,java.lang.String> s2cOptions, java.util.Map<KexProposalOption,java.lang.String> negotiatedGuess, java.lang.Throwable reason)
protected void
signalNegotiationStart(java.util.Map<KexProposalOption,java.lang.String> c2sOptions, java.util.Map<KexProposalOption,java.lang.String> s2cOptions)
protected void
signalNegotiationStart(SessionListener listener, java.util.Map<KexProposalOption,java.lang.String> c2sOptions, java.util.Map<KexProposalOption,java.lang.String> s2cOptions)
protected void
signalPeerIdentificationReceived(java.lang.String version, java.util.List<java.lang.String> extraLines)
protected void
signalPeerIdentificationReceived(SessionListener listener, java.lang.String version, java.util.List<java.lang.String> extraLines)
protected void
signalSessionClosed()
protected void
signalSessionClosed(SessionListener listener)
protected void
signalSessionCreated(IoSession ioSession)
protected void
signalSessionCreated(SessionListener listener)
protected void
signalSessionEstablished(IoSession ioSession)
protected void
signalSessionEstablished(SessionListener listener)
protected void
signalSessionEvent(SessionListener.Event event)
Sends a session event to all currently registered session listenersprotected void
signalSessionEvent(SessionListener listener, SessionListener.Event event)
java.lang.String
toString()
IoWriteFuture
writePacket(Buffer buffer, long timeout, java.util.concurrent.TimeUnit unit)
Encode and send the given buffer with the specified timeout.-
Methods inherited from class org.apache.sshd.common.kex.AbstractKexFactoryManager
getCipherFactories, getCompressionFactories, getDelegate, getKexExtensionHandler, getKeyExchangeFactories, getMacFactories, getSignatureFactories, resolveEffectiveFactories, resolveEffectiveProvider, setCipherFactories, setCompressionFactories, setKexExtensionHandler, setKeyExchangeFactories, setMacFactories, setSignatureFactories
-
Methods inherited from class org.apache.sshd.common.util.closeable.AbstractInnerCloseable
doCloseGracefully, doCloseImmediately, getInnerCloseable
-
Methods inherited from class org.apache.sshd.common.util.closeable.AbstractCloseable
addCloseFutureListener, builder, close, getFutureLock, isClosed, isClosing, preClose, removeCloseFutureListener
-
Methods 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, warn
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface org.apache.sshd.common.channel.ChannelListenerManager
addChannelListener, getChannelListenerProxy, removeChannelListener
-
Methods inherited from interface org.apache.sshd.common.channel.throttle.ChannelStreamWriterResolverManager
resolveChannelStreamWriter
-
Methods inherited from interface org.apache.sshd.common.Closeable
addCloseFutureListener, close, close, isClosed, isClosing, isOpen, removeCloseFutureListener
-
Methods inherited from interface org.apache.sshd.common.kex.extension.KexExtensionHandlerManager
getKexExtensionHandler, setKexExtensionHandler
-
Methods inherited from interface org.apache.sshd.common.kex.KexFactoryManager
getCipherFactories, getCipherFactoriesNameList, getCipherFactoriesNames, getCompressionFactories, getCompressionFactoriesNameList, getCompressionFactoriesNames, getKeyExchangeFactories, getMacFactories, getMacFactoriesNameList, getMacFactoriesNames, setCipherFactories, setCipherFactoriesNameList, setCipherFactoriesNames, setCipherFactoriesNames, setCompressionFactories, setCompressionFactoriesNameList, setCompressionFactoriesNames, setCompressionFactoriesNames, setKeyExchangeFactories, setMacFactories, setMacFactoriesNameList, setMacFactoriesNames, setMacFactoriesNames
-
Methods inherited from interface org.apache.sshd.common.forward.PortForwardingEventListenerManager
addPortForwardingEventListener, getPortForwardingEventListenerProxy, removePortForwardingEventListener
-
Methods inherited from interface org.apache.sshd.common.PropertyResolver
getBoolean, getBooleanProperty, getCharset, getInteger, getIntProperty, getLong, getLongProperty, getObject, getString, getStringProperty
-
Methods inherited from interface org.apache.sshd.common.session.Session
createBuffer, createBuffer, getKex, getLocalAddress, getRemoteAddress, getService, prepareBuffer, reExchangeKeys, request, request, request, resolveAttribute, startService, writePacket, writePacket, writePacket
-
Methods inherited from interface org.apache.sshd.common.session.SessionContext
getCipherInformation, getClientKexProposals, getClientVersion, getCompressionInformation, getKexNegotiationResult, getKexState, getMacInformation, getNegotiatedKexParameter, getServerKexProposals, getServerVersion, getSessionId
-
Methods inherited from interface org.apache.sshd.common.session.SessionHeartbeatController
disableSessionHeartbeat, getSessionHeartbeatInterval, getSessionHeartbeatType, setSessionHeartbeat, setSessionHeartbeat
-
Methods inherited from interface org.apache.sshd.common.session.SessionListenerManager
addSessionListener, getSessionListenerProxy, removeSessionListener
-
Methods inherited from interface org.apache.sshd.common.signature.SignatureFactoriesHolder
getSignatureFactories, getSignatureFactoriesNameList, getSignatureFactoriesNames
-
Methods inherited from interface org.apache.sshd.common.signature.SignatureFactoriesManager
setSignatureFactories, setSignatureFactoriesNameList, setSignatureFactoriesNames, setSignatureFactoriesNames
-
-
-
-
Field Detail
-
sessionLock
protected final java.lang.Object sessionLock
Session level lock for regulating access to sensitive data
-
authStart
protected java.time.Instant authStart
-
idleStart
protected java.time.Instant idleStart
-
serverSession
private final boolean serverSession
Client or server side
-
ioSession
private final IoSession ioSession
The underlying network session
-
properties
private final java.util.Map<java.lang.String,java.lang.Object> properties
The session specific properties
-
attributes
private final java.util.Map<AttributeRepository.AttributeKey<?>,java.lang.Object> attributes
Session specific attributes
-
timeoutStatus
private final java.util.concurrent.atomic.AtomicReference<TimeoutIndicator> timeoutStatus
-
reservedSessionMessagesHandler
private ReservedSessionMessagesHandler reservedSessionMessagesHandler
-
sessionDisconnectHandler
private SessionDisconnectHandler sessionDisconnectHandler
-
unknownChannelReferenceHandler
private UnknownChannelReferenceHandler unknownChannelReferenceHandler
-
channelStreamPacketWriterResolver
private ChannelStreamWriterResolver channelStreamPacketWriterResolver
-
username
private volatile java.lang.String username
The name of the authenticated user
-
authed
private volatile boolean authed
Boolean indicating if this session has been authenticated or not
-
-
Constructor Detail
-
SessionHelper
protected SessionHelper(boolean serverSession, FactoryManager factoryManager, IoSession ioSession)
Create a new session.- Parameters:
serverSession
-true
if this is a server session,false
if client onefactoryManager
- the factory managerioSession
- the underlying I/O session
-
-
Method Detail
-
getIoSession
public IoSession getIoSession()
- Specified by:
getIoSession
in interfaceSession
- Returns:
- The
IoSession
associated to this session
-
isServerSession
public boolean isServerSession()
Description copied from interface:SessionContext
Quick indication if this is a server or client session (instead of having to askinstanceof
).- Specified by:
isServerSession
in interfaceSessionContext
- Returns:
true
if this is a server session
-
getFactoryManager
public FactoryManager getFactoryManager()
- Specified by:
getFactoryManager
in interfaceFactoryManagerHolder
- Returns:
- The currently associated
FactoryManager
-
getParentPropertyResolver
public PropertyResolver getParentPropertyResolver()
- Specified by:
getParentPropertyResolver
in interfacePropertyResolver
- Returns:
- The parent resolver that can be used to query for missing properties -
null
if no parent
-
getProperties
public java.util.Map<java.lang.String,java.lang.Object> getProperties()
Description copied from interface:PropertyResolver
A map of properties that can be used to configure the SSH server or client. This map will never be changed by either the server or client and is not supposed to be changed at runtime (changes are not bound to have any effect on a running client or server), though it may affect the creation of sessions later as these values are usually not cached.
Note: the type of the mapped property should match the expected configuration value type -
Long, Integer, Boolean, String
, etc.... If it doesn't, thetoString()
result of the mapped value is used to convert it to the required type. E.g., if the mapped value is the string "1234" and the expected value is along
then it will be parsed into one. Also, if the mapped value is anInteger
but along
is expected, then it will be converted into one.- Specified by:
getProperties
in interfacePropertyResolver
- Returns:
- a valid
Map
containing configuration values, nevernull
. Note: may be immutable.
-
getAttributesCount
public int getAttributesCount()
- Specified by:
getAttributesCount
in interfaceAttributeRepository
- Returns:
- Current number of user-defined attributes stored in the repository
-
getAttribute
public <T> T getAttribute(AttributeRepository.AttributeKey<T> key)
Description copied from interface:AttributeRepository
Returns the value of the user-defined attribute.- Specified by:
getAttribute
in interfaceAttributeRepository
- Type Parameters:
T
- The generic attribute type- Parameters:
key
- The key of the attribute; must not benull
.- Returns:
null
if there is no value associated with the specified key
-
attributeKeys
public java.util.Collection<AttributeRepository.AttributeKey<?>> attributeKeys()
- Specified by:
attributeKeys
in interfaceAttributeRepository
- Returns:
- A
Collection
snapshot of all the currently registered attributes in the repository
-
computeAttributeIfAbsent
public <T> T computeAttributeIfAbsent(AttributeRepository.AttributeKey<T> key, java.util.function.Function<? super AttributeRepository.AttributeKey<T>,? extends T> resolver)
Description copied from interface:AttributeStore
If the specified key is not already associated with a value (or is mapped tonull
), attempts to compute its value using the given mapping function and enters it into this map unlessnull
.- Specified by:
computeAttributeIfAbsent
in interfaceAttributeStore
- Type Parameters:
T
- The generic attribute type- Parameters:
key
- The key of the attribute; must not benull
.resolver
- The (nevernull
) mapping function to use if value not already mapped. If returnsnull
then value is not mapped to the provided key.- Returns:
- The resolved value -
null
if value not mapped and resolver did not return a non-null
value for it
-
setAttribute
public <T> T setAttribute(AttributeRepository.AttributeKey<T> key, T value)
Description copied from interface:AttributeStore
Sets a user-defined attribute.- Specified by:
setAttribute
in interfaceAttributeStore
- Type Parameters:
T
- The generic attribute type- Parameters:
key
- The key of the attribute; must not benull
.value
- The value of the attribute; must not benull
.- Returns:
- The old value of the attribute;
null
if it is new.
-
removeAttribute
public <T> T removeAttribute(AttributeRepository.AttributeKey<T> key)
Description copied from interface:AttributeStore
Removes the user-defined attribute- Specified by:
removeAttribute
in interfaceAttributeStore
- Type Parameters:
T
- The generic attribute type- Parameters:
key
- The key of the attribute; must not benull
.- Returns:
- The removed value;
null
if no previous value
-
clearAttributes
public void clearAttributes()
Description copied from interface:AttributeStore
Removes all currently stored user-defined attributes- Specified by:
clearAttributes
in interfaceAttributeStore
-
getUsername
public java.lang.String getUsername()
- Specified by:
getUsername
in interfaceUsernameHolder
- Returns:
- The attached username - may be
null
/empty if holder not yet initialized
-
setUsername
public void setUsername(java.lang.String username)
- Specified by:
setUsername
in interfaceMutableUserHolder
-
isAuthenticated
public boolean isAuthenticated()
- Specified by:
isAuthenticated
in interfaceSessionContext
- Returns:
true
if session has successfully completed the authentication phase
-
setAuthenticated
public void setAuthenticated() throws java.io.IOException
- Specified by:
setAuthenticated
in interfaceSession
- Throws:
java.io.IOException
-
checkForTimeouts
protected TimeoutIndicator checkForTimeouts() throws java.io.IOException
Checks whether the session has timed out (both authentication and idle timeouts are checked). If the session has timed out, a DISCONNECT message will be sent.- Returns:
- An indication whether timeout has been detected
- Throws:
java.io.IOException
- If failed to check- See Also:
checkAuthenticationTimeout(Instant, Duration)
,checkIdleTimeout(Instant, Duration)
-
getAuthTimeoutStart
public java.time.Instant getAuthTimeoutStart()
- Specified by:
getAuthTimeoutStart
in interfaceSession
- Returns:
- The timestamp value (milliseconds since EPOCH) when timer was started
-
resetAuthTimeout
public java.time.Instant resetAuthTimeout()
Description copied from interface:Session
Re-start the authentication timeout timer- Specified by:
resetAuthTimeout
in interfaceSession
- Returns:
- The timestamp value (milliseconds since EPOCH) when timer was started
- See Also:
Session.getAuthTimeoutStart()
-
checkAuthenticationTimeout
protected TimeoutIndicator checkAuthenticationTimeout(java.time.Instant now, java.time.Duration authTimeout)
Checks if authentication timeout expired- Parameters:
now
- The current time in millisauthTimeout
- The configured timeout - if non-positive then no timeout- Returns:
- A
TimeoutIndicator
specifying the timeout status and disconnect reason message if timeout expired,null
orNoTimeout
if no timeout occurred - See Also:
getAuthTimeout()
-
getIdleTimeoutStart
public java.time.Instant getIdleTimeoutStart()
- Specified by:
getIdleTimeoutStart
in interfaceSession
- Returns:
- The timestamp value (milliseconds since EPOCH) when timer was started
-
checkIdleTimeout
protected TimeoutIndicator checkIdleTimeout(java.time.Instant now, java.time.Duration idleTimeout)
Checks if idle timeout expired- Parameters:
now
- The current time in millisidleTimeout
- The configured timeout - if non-positive then no timeout- Returns:
- A
TimeoutIndicator
specifying the timeout status and disconnect reason message if timeout expired,null
orNoTimeout
if no timeout occurred - See Also:
getIdleTimeout()
-
resetIdleTimeout
public java.time.Instant resetIdleTimeout()
Description copied from interface:Session
Re-start idle timeout timer- Specified by:
resetIdleTimeout
in interfaceSession
- Returns:
- The timestamp value (milliseconds since EPOCH) when timer was started
- See Also:
Session.getIdleTimeoutStart()
-
getTimeoutStatus
public TimeoutIndicator getTimeoutStatus()
Description copied from interface:Session
Check if timeout has occurred.- Specified by:
getTimeoutStatus
in interfaceSession
- Returns:
- the timeout status - never
null
-
getReservedSessionMessagesHandler
public ReservedSessionMessagesHandler getReservedSessionMessagesHandler()
- Specified by:
getReservedSessionMessagesHandler
in interfaceReservedSessionMessagesManager
- Returns:
- The currently registered
ReservedSessionMessagesHandler
- may benull
-
setReservedSessionMessagesHandler
public void setReservedSessionMessagesHandler(ReservedSessionMessagesHandler handler)
- Specified by:
setReservedSessionMessagesHandler
in interfaceReservedSessionMessagesManager
- Parameters:
handler
- TheReservedSessionMessagesHandler
to use - may benull
-
getSessionDisconnectHandler
public SessionDisconnectHandler getSessionDisconnectHandler()
- Specified by:
getSessionDisconnectHandler
in interfaceSessionDisconnectHandlerManager
-
setSessionDisconnectHandler
public void setSessionDisconnectHandler(SessionDisconnectHandler sessionDisconnectHandler)
- Specified by:
setSessionDisconnectHandler
in interfaceSessionDisconnectHandlerManager
-
handleIgnore
protected void handleIgnore(Buffer buffer) throws java.lang.Exception
- Throws:
java.lang.Exception
-
doInvokeIgnoreMessageHandler
protected void doInvokeIgnoreMessageHandler(Buffer buffer) throws java.lang.Exception
Invoked byhandleDebug(Buffer)
after validating that the buffer structure seems well-formed and also resetting the idle timeout. By default, retrieves theReservedSessionMessagesHandler
and invokes itshandleIgnoreMessage
method.- Parameters:
buffer
- The inputBuffer
- Throws:
java.lang.Exception
- if failed to handle the message
-
sendNotImplemented
protected IoWriteFuture sendNotImplemented(long seqNoValue) throws java.io.IOException
Sends aSSH_MSG_UNIMPLEMENTED
message- Parameters:
seqNoValue
- The referenced sequence number- Returns:
- An
IoWriteFuture
that can be used to wait for packet write completion - Throws:
java.io.IOException
- if an error occurred sending the packet
-
handleUnimplemented
protected void handleUnimplemented(Buffer buffer) throws java.lang.Exception
- Throws:
java.lang.Exception
-
doInvokeUnimplementedMessageHandler
protected boolean doInvokeUnimplementedMessageHandler(int cmd, Buffer buffer) throws java.lang.Exception
- Parameters:
cmd
- The unimplemented commandbuffer
- The inputBuffer
- Returns:
- Result of invoking
handleUnimplementedMessage
- Throws:
java.lang.Exception
- if failed to handle the message
-
sendDebugMessage
public IoWriteFuture sendDebugMessage(boolean display, java.lang.Object msg, java.lang.String lang) throws java.io.IOException
Description copied from interface:Session
Sends anSSH_MSG_DEBUG
to the peer session- Specified by:
sendDebugMessage
in interfaceSession
- Parameters:
display
-true
if OK to display the message at the peer as-ismsg
- The message object whosetoString()
value to be used - ifnull
then the "null" string is sentlang
- The language -null
/empty if some pre-agreed default is used- Returns:
- An
IoWriteFuture
that can be used to check when the packet has actually been sent - Throws:
java.io.IOException
- if an error occurred when encoding or sending the packet- See Also:
- RFC 4253 - section 11.3
-
handleDebug
protected void handleDebug(Buffer buffer) throws java.lang.Exception
- Throws:
java.lang.Exception
-
doInvokeDebugMessageHandler
protected void doInvokeDebugMessageHandler(Buffer buffer) throws java.lang.Exception
Invoked byhandleDebug(Buffer)
after validating that the buffer structure seems well-formed and also resetting the idle timeout. By default, retrieves theReservedSessionMessagesHandler
and invokes itshandleDebugMessage
method.- Parameters:
buffer
- The inputBuffer
- Throws:
java.lang.Exception
- if failed to handle the message
-
resolveReservedSessionMessagesHandler
protected ReservedSessionMessagesHandler resolveReservedSessionMessagesHandler()
-
getUnknownChannelReferenceHandler
public UnknownChannelReferenceHandler getUnknownChannelReferenceHandler()
- Specified by:
getUnknownChannelReferenceHandler
in interfaceUnknownChannelReferenceHandlerManager
- Returns:
- The
UnknownChannelReferenceHandlerManager
to use - ifnull
then any reference to unknown channel causes anSshChannelNotFoundException
-
setUnknownChannelReferenceHandler
public void setUnknownChannelReferenceHandler(UnknownChannelReferenceHandler unknownChannelReferenceHandler)
- Specified by:
setUnknownChannelReferenceHandler
in interfaceUnknownChannelReferenceHandlerManager
- Parameters:
unknownChannelReferenceHandler
- TheUnknownChannelReferenceHandlerManager
to use - ifnull
then any reference to unknown channel causes anSshChannelNotFoundException
-
resolveUnknownChannelReferenceHandler
public UnknownChannelReferenceHandler resolveUnknownChannelReferenceHandler()
Description copied from interface:UnknownChannelReferenceHandlerManager
Check if current manager has a specific handler set for it - if not, try and resolve one from the "parent" container (if any)- Specified by:
resolveUnknownChannelReferenceHandler
in interfaceUnknownChannelReferenceHandlerManager
- Returns:
- The resolved handler instance
-
getChannelStreamWriterResolver
public ChannelStreamWriterResolver getChannelStreamWriterResolver()
- Specified by:
getChannelStreamWriterResolver
in interfaceChannelStreamWriterResolverManager
-
setChannelStreamWriterResolver
public void setChannelStreamWriterResolver(ChannelStreamWriterResolver resolver)
- Specified by:
setChannelStreamWriterResolver
in interfaceChannelStreamWriterResolverManager
-
resolveChannelStreamWriterResolver
public ChannelStreamWriterResolver resolveChannelStreamWriterResolver()
- Specified by:
resolveChannelStreamWriterResolver
in interfaceChannelStreamWriterResolverManager
-
sendIgnoreMessage
public IoWriteFuture sendIgnoreMessage(byte... data) throws java.io.IOException
Description copied from interface:Session
Sends anSSH_MSG_IGNORE
to the peer session- Specified by:
sendIgnoreMessage
in interfaceSession
- Parameters:
data
- The message data- Returns:
- An
IoWriteFuture
that can be used to check when the packet has actually been sent - Throws:
java.io.IOException
- if an error occurred when encoding or sending the packet- See Also:
- RFC 4253 - section 11.2
-
writePacket
public IoWriteFuture writePacket(Buffer buffer, long timeout, java.util.concurrent.TimeUnit unit) throws java.io.IOException
Description copied from interface:Session
Encode and send the given buffer with the specified timeout. If the buffer could not be written before the timeout elapses, the returnedIoWriteFuture
will be set with aTimeoutException
exception to indicate a timeout.- Specified by:
writePacket
in interfaceSession
- Parameters:
buffer
- the buffer to encode and spendtimeout
- the timeoutunit
- the time unit of the timeout parameter- Returns:
- a future that can be used to check when the packet has actually been sent
- Throws:
java.io.IOException
- if an error occurred when encoding or sending the packet
-
signalSessionEstablished
protected void signalSessionEstablished(IoSession ioSession) throws java.lang.Exception
- Throws:
java.lang.Exception
-
signalSessionEstablished
protected void signalSessionEstablished(SessionListener listener)
-
signalSessionCreated
protected void signalSessionCreated(IoSession ioSession) throws java.lang.Exception
- Throws:
java.lang.Exception
-
signalSessionCreated
protected void signalSessionCreated(SessionListener listener)
-
signalPeerIdentificationReceived
protected void signalPeerIdentificationReceived(java.lang.String version, java.util.List<java.lang.String> extraLines) throws java.lang.Exception
- Throws:
java.lang.Exception
-
signalPeerIdentificationReceived
protected void signalPeerIdentificationReceived(SessionListener listener, java.lang.String version, java.util.List<java.lang.String> extraLines)
-
signalSessionEvent
protected void signalSessionEvent(SessionListener.Event event) throws java.io.IOException
Sends a session event to all currently registered session listeners- Parameters:
event
- The event to send- Throws:
java.io.IOException
- If any of the registered listeners threw an exception.
-
signalSessionEvent
protected void signalSessionEvent(SessionListener listener, SessionListener.Event event) throws java.io.IOException
- Throws:
java.io.IOException
-
invokeSessionSignaller
protected void invokeSessionSignaller(Invoker<SessionListener,java.lang.Void> invoker) throws java.lang.Throwable
- Throws:
java.lang.Throwable
-
resizeKey
protected byte[] resizeKey(byte[] e, int kdfSize, Digest hash, byte[] k, byte[] h) throws java.lang.Exception
Method used while putting new keys into use that will resize the key used to initialize the cipher to the needed length.- Parameters:
e
- the key to resizekdfSize
- the cipher key-derivation-factor (in bytes)hash
- the hash algorithmk
- the key exchange k parameterh
- the key exchange h parameter- Returns:
- the resized key
- Throws:
java.lang.Exception
- if a problem occur while resizing the key
-
resolvePeerAddress
protected java.net.SocketAddress resolvePeerAddress(java.net.SocketAddress knownAddress)
- Parameters:
knownAddress
- Any externally set peer address - e.g., due to some proxy mechanism meta-data- Returns:
- The external address if not
null
otherwise, theIoSession
peer address
-
calculateNextIgnorePacketCount
protected long calculateNextIgnorePacketCount(Random r, long freq, int variance)
-
resolveIdentificationString
protected java.lang.String resolveIdentificationString(java.lang.String configPropName)
Resolves the identification to send to the peer session by consulting the associatedFactoryManager
. If a value is set, then it is appended to the standardSessionContext.DEFAULT_SSH_VERSION_PREFIX
. Otherwise a default value is returned consisting of the prefix and the core artifact name + version in uppercase - e.g.,' "SSH-2.0-APACHE-SSHD-1.2.3.4"- Parameters:
configPropName
- The property used to query the factory manager- Returns:
- The resolved identification value
-
sendIdentification
protected IoWriteFuture sendIdentification(java.lang.String ident) throws java.io.IOException
Send our identification.- Parameters:
ident
- our identification to send- Returns:
IoWriteFuture
that can be used to wait for notification that identification has been send- Throws:
java.io.IOException
- If failed to send the packet
-
doReadIdentification
protected java.util.List<java.lang.String> doReadIdentification(Buffer buffer, boolean server) throws java.io.IOException
Read the remote identification from this buffer. If more data is needed, the buffer will be reset to its original state and anull
value will be returned. Else the identification string will be returned and the data read will be consumed from the buffer.- Parameters:
buffer
- the buffer containing the identification stringserver
-true
if it is called by the server session,false
if by the client session- Returns:
- A
List
of all received remote identification lines until the version line was read ornull
if more data is needed. The identification line is the last one in the list - Throws:
java.io.IOException
- if malformed identification found
-
resolveSessionKexProposal
protected java.lang.String resolveSessionKexProposal(java.lang.String hostKeyTypes) throws java.io.IOException
- Throws:
java.io.IOException
-
createProposal
protected java.util.Map<KexProposalOption,java.lang.String> createProposal(java.lang.String hostKeyTypes) throws java.io.IOException
Create our proposal for SSH negotiation- Parameters:
hostKeyTypes
- The comma-separated list of supported host key types- Returns:
- The proposal
Map
- Throws:
java.io.IOException
- If internal problem - e.g., KEX extensions negotiation issue
-
mergeProposals
protected java.util.Map<KexProposalOption,java.lang.String> mergeProposals(java.util.Map<KexProposalOption,java.lang.String> current, java.util.Map<KexProposalOption,java.lang.String> proposal)
-
signalNegotiationStart
protected void signalNegotiationStart(java.util.Map<KexProposalOption,java.lang.String> c2sOptions, java.util.Map<KexProposalOption,java.lang.String> s2cOptions)
-
signalNegotiationStart
protected void signalNegotiationStart(SessionListener listener, java.util.Map<KexProposalOption,java.lang.String> c2sOptions, java.util.Map<KexProposalOption,java.lang.String> s2cOptions)
-
signalNegotiationEnd
protected void signalNegotiationEnd(java.util.Map<KexProposalOption,java.lang.String> c2sOptions, java.util.Map<KexProposalOption,java.lang.String> s2cOptions, java.util.Map<KexProposalOption,java.lang.String> negotiatedGuess, java.lang.Throwable reason)
-
signalNegotiationEnd
protected void signalNegotiationEnd(SessionListener listener, java.util.Map<KexProposalOption,java.lang.String> c2sOptions, java.util.Map<KexProposalOption,java.lang.String> s2cOptions, java.util.Map<KexProposalOption,java.lang.String> negotiatedGuess, java.lang.Throwable reason)
-
preProcessEncodeBuffer
protected Buffer preProcessEncodeBuffer(int cmd, Buffer buffer) throws java.io.IOException
Invoked by the session before encoding the buffer in order to make sure that it is at least of sizeSSH_PACKET_HEADER_LEN
. This is required in order to efficiently handle the encoding. If necessary, it re-allocates a new buffer and returns it instead.- Parameters:
cmd
- The command stored in the bufferbuffer
- The originalBuffer
- assumed to be properly formatted and be of at least the required minimum length.- Returns:
- The adjusted
Buffer
. Note: users may use this method to totally alter the contents of the buffer being sent but it is highly discouraged as it may have unexpected results. - Throws:
java.io.IOException
- If failed to process the buffer
-
disconnect
public void disconnect(int reason, java.lang.String msg) throws java.io.IOException
Description copied from interface:Session
Send a disconnect packet with the given reason and message. Once the packet has been sent, the session will be closed asynchronously.- Specified by:
disconnect
in interfaceSession
- Parameters:
reason
- the reason code for this disconnectmsg
- the text message- Throws:
java.io.IOException
- if an error occurred sending the packet
-
handleDisconnect
protected void handleDisconnect(Buffer buffer) throws java.lang.Exception
- Throws:
java.lang.Exception
-
handleDisconnect
protected void handleDisconnect(int code, java.lang.String msg, java.lang.String lang, Buffer buffer) throws java.lang.Exception
- Throws:
java.lang.Exception
-
signalDisconnect
protected void signalDisconnect(int code, java.lang.String msg, java.lang.String lang, boolean initiator)
-
signalDisconnect
protected void signalDisconnect(SessionListener listener, int code, java.lang.String msg, java.lang.String lang, boolean initiator)
-
exceptionCaught
public void exceptionCaught(java.lang.Throwable t)
Handle any exceptions that occurred on this session. The session will be closed and a disconnect packet will be sent before if the given exception is anSshException
.- Specified by:
exceptionCaught
in interfaceSession
- Parameters:
t
- the exception to process
-
signalExceptionCaught
protected void signalExceptionCaught(java.lang.Throwable t)
-
signalExceptionCaught
protected void signalExceptionCaught(SessionListener listener, java.lang.Throwable t)
-
signalSessionClosed
protected void signalSessionClosed()
-
signalSessionClosed
protected void signalSessionClosed(SessionListener listener)
-
getConnectionService
protected abstract ConnectionService getConnectionService()
-
getForwarder
protected Forwarder getForwarder()
-
getLocalForwardsBindings
public java.util.List<java.util.Map.Entry<SshdSocketAddress,SshdSocketAddress>> getLocalForwardsBindings()
- Specified by:
getLocalForwardsBindings
in interfacePortForwardingInformationProvider
- Returns:
- A snapshot of the currently bound forwarded local ports as "pairs" of local/remote
SshdSocketAddress
-es
-
isLocalPortForwardingStartedForPort
public boolean isLocalPortForwardingStartedForPort(int port)
Description copied from interface:PortForwardingInformationProvider
Test if local port forwarding is started- Specified by:
isLocalPortForwardingStartedForPort
in interfacePortForwardingInformationProvider
- Parameters:
port
- The local port- Returns:
true
if local port forwarding is started- See Also:
getBoundLocalPortForwards
-
getStartedLocalPortForwards
public java.util.List<SshdSocketAddress> getStartedLocalPortForwards()
- Specified by:
getStartedLocalPortForwards
in interfacePortForwardingInformationProvider
- Returns:
- A
List
snapshot of the currently started local port forward bindings
-
getBoundLocalPortForwards
public java.util.List<SshdSocketAddress> getBoundLocalPortForwards(int port)
- Specified by:
getBoundLocalPortForwards
in interfacePortForwardingInformationProvider
- Parameters:
port
- The port number- Returns:
- The local bound
SshdSocketAddress
-es for the port - See Also:
isLocalPortForwardingStartedForPort
,PortForwardingInformationProvider.getStartedLocalPortForwards()
-
getRemoteForwardsBindings
public java.util.List<java.util.Map.Entry<java.lang.Integer,SshdSocketAddress>> getRemoteForwardsBindings()
- Specified by:
getRemoteForwardsBindings
in interfacePortForwardingInformationProvider
- Returns:
- A snapshot of the currently bound forwarded remote ports as "pairs" of port + bound
SshdSocketAddress
-
isRemotePortForwardingStartedForPort
public boolean isRemotePortForwardingStartedForPort(int port)
Description copied from interface:PortForwardingInformationProvider
Test if remote port forwarding is started- Specified by:
isRemotePortForwardingStartedForPort
in interfacePortForwardingInformationProvider
- Parameters:
port
- The remote port- Returns:
true
if remote port forwarding is started- See Also:
getBoundRemotePortForward
-
getStartedRemotePortForwards
public java.util.NavigableSet<java.lang.Integer> getStartedRemotePortForwards()
- Specified by:
getStartedRemotePortForwards
in interfacePortForwardingInformationProvider
- Returns:
- A
NavigableSet
snapshot of the currently started remote port forwards
-
getBoundRemotePortForward
public SshdSocketAddress getBoundRemotePortForward(int port)
- Specified by:
getBoundRemotePortForward
in interfacePortForwardingInformationProvider
- Parameters:
port
- The port number- Returns:
- The remote bound
SshdSocketAddress
for the port -null
if none bound - See Also:
isRemotePortForwardingStartedForPort
,PortForwardingInformationProvider.getStartedRemotePortForwards()
-
getAuthTimeout
public java.time.Duration getAuthTimeout()
- Specified by:
getAuthTimeout
in interfaceSession
- Returns:
- Timeout value in milliseconds for authentication stage
-
getIdleTimeout
public java.time.Duration getIdleTimeout()
- Specified by:
getIdleTimeout
in interfaceSession
- Returns:
- Timeout value in milliseconds for communication
-
toString
public java.lang.String toString()
- Overrides:
toString
in classjava.lang.Object
-
-