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 makeAbstractSessionclass 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>attributesSession specific attributesprivate booleanauthedBoolean indicating if this session has been authenticated or notprotected java.time.InstantauthStartprivate ChannelStreamWriterResolverchannelStreamPacketWriterResolverprotected java.time.InstantidleStartprotected java.util.Map<KexProposalOption,java.lang.String>initialKexProposalStores the initial KEX proposal after it has been run through the hooks allowing client code to modify it; seegetKexProposal().private IoSessionioSessionThe underlying network sessionprivate java.util.Map<java.lang.String,java.lang.Object>propertiesThe session specific propertiesprivate ReservedSessionMessagesHandlerreservedSessionMessagesHandlerprivate booleanserverSessionClient or server sideprivate SessionDisconnectHandlersessionDisconnectHandlerprivate java.util.concurrent.atomic.AtomicReference<TimeoutIndicator>timeoutStatusprivate UnknownChannelReferenceHandlerunknownChannelReferenceHandlerprivate java.lang.StringusernameThe 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 protectedSessionHelper(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 longcalculateNextIgnorePacketCount(Random r, long freq, int variance)protected TimeoutIndicatorcheckAuthenticationTimeout(java.time.Instant now, java.time.Duration authTimeout)Checks if authentication timeout expiredprotected TimeoutIndicatorcheckForTimeouts()Checks whether the session has timed out (both authentication and idle timeouts are checked).protected TimeoutIndicatorcheckIdleTimeout(java.time.Instant now, java.time.Duration idleTimeout)Checks if idle timeout expiredvoidclearAttributes()Removes all currently stored user-defined attributes<T> TcomputeAttributeIfAbsent(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 negotiationvoiddisconnect(int reason, java.lang.String msg)Send a disconnect packet with the given reason and message.protected voiddoInvokeDebugMessageHandler(Buffer buffer)Invoked byhandleDebug(Buffer)after validating that the buffer structure seems well-formed and also resetting the idle timeout.protected voiddoInvokeIgnoreMessageHandler(Buffer buffer)Invoked byhandleDebug(Buffer)after validating that the buffer structure seems well-formed and also resetting the idle timeout.protected booleandoInvokeUnimplementedMessageHandler(int cmd, Buffer buffer)protected java.util.List<java.lang.String>doReadIdentification(Buffer buffer, boolean server)Read the remote identification from this buffer.voidexceptionCaught(java.lang.Throwable t)Handle any exceptions that occurred on this session.<T> TgetAttribute(AttributeRepository.AttributeKey<T> key)Returns the value of the user-defined attribute.intgetAttributesCount()java.time.DurationgetAuthTimeout()java.time.InstantgetAuthTimeoutStart()java.util.List<SshdSocketAddress>getBoundLocalPortForwards(int port)SshdSocketAddressgetBoundRemotePortForward(int port)ChannelStreamWriterResolvergetChannelStreamWriterResolver()protected abstract ConnectionServicegetConnectionService()FactoryManagergetFactoryManager()protected ForwardergetForwarder()java.time.DurationgetIdleTimeout()java.time.InstantgetIdleTimeoutStart()IoSessiongetIoSession()protected java.util.Map<KexProposalOption,java.lang.String>getKexProposal()Retrieves this side's initial proposal for KEX negotiation.java.util.List<java.util.Map.Entry<SshdSocketAddress,SshdSocketAddress>>getLocalForwardsBindings()PropertyResolvergetParentPropertyResolver()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()ReservedSessionMessagesHandlergetReservedSessionMessagesHandler()SessionDisconnectHandlergetSessionDisconnectHandler()java.util.List<SshdSocketAddress>getStartedLocalPortForwards()java.util.NavigableSet<java.lang.Integer>getStartedRemotePortForwards()TimeoutIndicatorgetTimeoutStatus()Check if timeout has occurred.UnknownChannelReferenceHandlergetUnknownChannelReferenceHandler()java.lang.StringgetUsername()protected voidhandleDebug(Buffer buffer)protected voidhandleDisconnect(int code, java.lang.String msg, java.lang.String lang, Buffer buffer)protected voidhandleDisconnect(Buffer buffer)protected voidhandleIgnore(Buffer buffer)protected voidhandleUnimplemented(Buffer buffer)protected voidinvokeSessionSignaller(Invoker<SessionListener,java.lang.Void> invoker)booleanisAuthenticated()booleanisLocalPortForwardingStartedForPort(int port)Test if local port forwarding is startedbooleanisRemotePortForwardingStartedForPort(int port)Test if remote port forwarding is startedbooleanisServerSession()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 BufferpreProcessEncodeBuffer(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> TremoveAttribute(AttributeRepository.AttributeKey<T> key)Removes the user-defined attributejava.time.InstantresetAuthTimeout()Re-start the authentication timeout timerjava.time.InstantresetIdleTimeout()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.protected java.lang.StringresolveAvailableSignaturesProposal()Computes the list of available host key signature algorithms supported.protected abstract java.lang.StringresolveAvailableSignaturesProposal(FactoryManager manager)Computes the list of available host key signature algorithms supported.ChannelStreamWriterResolverresolveChannelStreamWriterResolver()protected java.lang.StringresolveIdentificationString(java.lang.String configPropName)Resolves the identification to send to the peer session by consulting the associatedFactoryManager.protected java.net.SocketAddressresolvePeerAddress(java.net.SocketAddress knownAddress)protected ReservedSessionMessagesHandlerresolveReservedSessionMessagesHandler()protected java.lang.StringresolveSessionKexProposal(java.lang.String hostKeyTypes)UnknownChannelReferenceHandlerresolveUnknownChannelReferenceHandler()Check if current manager has a specific handler set for it - if not, try and resolve one from the "parent" container (if any)IoWriteFuturesendDebugMessage(boolean display, java.lang.Object msg, java.lang.String lang)Sends anSSH_MSG_DEBUGto the peer sessionprotected IoWriteFuturesendIdentification(java.lang.String version, java.util.List<java.lang.String> extraLines)Send our identification.IoWriteFuturesendIgnoreMessage(byte... data)Sends anSSH_MSG_IGNOREto the peer sessionprotected IoWriteFuturesendNotImplemented(long seqNoValue)Sends aSSH_MSG_UNIMPLEMENTEDmessage<T> TsetAttribute(AttributeRepository.AttributeKey<T> key, T value)Sets a user-defined attribute.voidsetAuthenticated()voidsetChannelStreamWriterResolver(ChannelStreamWriterResolver resolver)voidsetReservedSessionMessagesHandler(ReservedSessionMessagesHandler handler)voidsetSessionDisconnectHandler(SessionDisconnectHandler sessionDisconnectHandler)voidsetUnknownChannelReferenceHandler(UnknownChannelReferenceHandler unknownChannelReferenceHandler)voidsetUsername(java.lang.String username)protected voidsignalDisconnect(int code, java.lang.String msg, java.lang.String lang, boolean initiator)protected voidsignalDisconnect(SessionListener listener, int code, java.lang.String msg, java.lang.String lang, boolean initiator)protected voidsignalExceptionCaught(java.lang.Throwable t)protected voidsignalExceptionCaught(SessionListener listener, java.lang.Throwable t)protected voidsignalNegotiationEnd(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 voidsignalNegotiationEnd(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 voidsignalNegotiationOptionsCreated(java.util.Map<KexProposalOption,java.lang.String> proposal)protected voidsignalNegotiationOptionsCreated(SessionListener listener, java.util.Map<KexProposalOption,java.lang.String> proposal)protected voidsignalNegotiationStart(java.util.Map<KexProposalOption,java.lang.String> c2sOptions, java.util.Map<KexProposalOption,java.lang.String> s2cOptions)protected voidsignalNegotiationStart(SessionListener listener, java.util.Map<KexProposalOption,java.lang.String> c2sOptions, java.util.Map<KexProposalOption,java.lang.String> s2cOptions)protected voidsignalPeerIdentificationReceived(java.lang.String version, java.util.List<java.lang.String> extraLines)protected voidsignalPeerIdentificationReceived(SessionListener listener, java.lang.String version, java.util.List<java.lang.String> extraLines)protected voidsignalReadPeerIdentificationLine(java.lang.String line, java.util.List<java.lang.String> extraLines)protected voidsignalReadPeerIdentificationLine(SessionListener listener, java.lang.String version, java.util.List<java.lang.String> extraLines)protected voidsignalSendIdentification(java.lang.String version, java.util.List<java.lang.String> extraLines)protected voidsignalSendIdentification(SessionListener listener, java.lang.String version, java.util.List<java.lang.String> extraLines)protected voidsignalSessionClosed()protected voidsignalSessionClosed(SessionListener listener)protected voidsignalSessionCreated(IoSession ioSession)protected voidsignalSessionCreated(SessionListener listener)protected voidsignalSessionEstablished(IoSession ioSession)protected voidsignalSessionEstablished(SessionListener listener)protected voidsignalSessionEvent(SessionListener.Event event)Sends a session event to all currently registered session listenersprotected voidsignalSessionEvent(SessionListener listener, SessionListener.Event event)java.lang.StringtoString()-
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, isEmpty
-
Methods inherited from interface org.apache.sshd.common.session.Session
createBuffer, createBuffer, getKex, getLocalAddress, getRemoteAddress, getService, prepareBuffer, reExchangeKeys, request, request, request, request, resolveAttribute, startService, writePacket, 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
-
authStart
protected java.time.Instant authStart
-
idleStart
protected java.time.Instant idleStart
-
initialKexProposal
protected java.util.Map<KexProposalOption,java.lang.String> initialKexProposal
Stores the initial KEX proposal after it has been run through the hooks allowing client code to modify it; seegetKexProposal(). The same proposal is then used for the initial KEX and for any re-KEX.
-
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-trueif this is a server session,falseif client onefactoryManager- the factory managerioSession- the underlying I/O session
-
-
Method Detail
-
getIoSession
public IoSession getIoSession()
- Specified by:
getIoSessionin interfaceSession- Returns:
- The
IoSessionassociated to this session
-
isServerSession
public boolean isServerSession()
Description copied from interface:SessionContextQuick indication if this is a server or client session (instead of having to askinstanceof).- Specified by:
isServerSessionin interfaceSessionContext- Returns:
trueif this is a server session
-
getFactoryManager
public FactoryManager getFactoryManager()
- Specified by:
getFactoryManagerin interfaceFactoryManagerHolder- Returns:
- The currently associated
FactoryManager
-
getParentPropertyResolver
public PropertyResolver getParentPropertyResolver()
- Specified by:
getParentPropertyResolverin interfacePropertyResolver- Returns:
- The parent resolver that can be used to query for missing properties -
nullif no parent
-
getProperties
public java.util.Map<java.lang.String,java.lang.Object> getProperties()
Description copied from interface:PropertyResolverA 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 alongthen it will be parsed into one. Also, if the mapped value is anIntegerbut alongis expected, then it will be converted into one.- Specified by:
getPropertiesin interfacePropertyResolver- Returns:
- a valid
Mapcontaining configuration values, nevernull. Note: may be immutable.
-
getAttributesCount
public int getAttributesCount()
- Specified by:
getAttributesCountin 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:AttributeRepositoryReturns the value of the user-defined attribute.- Specified by:
getAttributein interfaceAttributeRepository- Type Parameters:
T- The generic attribute type- Parameters:
key- The key of the attribute; must not benull.- Returns:
nullif there is no value associated with the specified key
-
attributeKeys
public java.util.Collection<AttributeRepository.AttributeKey<?>> attributeKeys()
- Specified by:
attributeKeysin interfaceAttributeRepository- Returns:
- A
Collectionsnapshot 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:AttributeStoreIf 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:
computeAttributeIfAbsentin 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 returnsnullthen value is not mapped to the provided key.- Returns:
- The resolved value -
nullif value not mapped and resolver did not return a non-nullvalue for it
-
setAttribute
public <T> T setAttribute(AttributeRepository.AttributeKey<T> key, T value)
Description copied from interface:AttributeStoreSets a user-defined attribute.- Specified by:
setAttributein 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;
nullif it is new.
-
removeAttribute
public <T> T removeAttribute(AttributeRepository.AttributeKey<T> key)
Description copied from interface:AttributeStoreRemoves the user-defined attribute- Specified by:
removeAttributein interfaceAttributeStore- Type Parameters:
T- The generic attribute type- Parameters:
key- The key of the attribute; must not benull.- Returns:
- The removed value;
nullif no previous value
-
clearAttributes
public void clearAttributes()
Description copied from interface:AttributeStoreRemoves all currently stored user-defined attributes- Specified by:
clearAttributesin interfaceAttributeStore
-
getUsername
public java.lang.String getUsername()
- Specified by:
getUsernamein interfaceUsernameHolder- Returns:
- The attached username - may be
null/empty if holder not yet initialized
-
setUsername
public void setUsername(java.lang.String username)
- Specified by:
setUsernamein interfaceMutableUserHolder
-
isAuthenticated
public boolean isAuthenticated()
- Specified by:
isAuthenticatedin interfaceSessionContext- Returns:
trueif session has successfully completed the authentication phase
-
setAuthenticated
public void setAuthenticated() throws java.io.IOException- Specified by:
setAuthenticatedin 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:
getAuthTimeoutStartin interfaceSession- Returns:
- The timestamp value (milliseconds since EPOCH) when timer was started
-
resetAuthTimeout
public java.time.Instant resetAuthTimeout()
Description copied from interface:SessionRe-start the authentication timeout timer- Specified by:
resetAuthTimeoutin 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
TimeoutIndicatorspecifying the timeout status and disconnect reason message if timeout expired,nullorNoTimeoutif no timeout occurred - See Also:
getAuthTimeout()
-
getIdleTimeoutStart
public java.time.Instant getIdleTimeoutStart()
- Specified by:
getIdleTimeoutStartin 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
TimeoutIndicatorspecifying the timeout status and disconnect reason message if timeout expired,nullorNoTimeoutif no timeout occurred - See Also:
getIdleTimeout()
-
resetIdleTimeout
public java.time.Instant resetIdleTimeout()
Description copied from interface:SessionRe-start idle timeout timer- Specified by:
resetIdleTimeoutin interfaceSession- Returns:
- The timestamp value (milliseconds since EPOCH) when timer was started
- See Also:
Session.getIdleTimeoutStart()
-
getTimeoutStatus
public TimeoutIndicator getTimeoutStatus()
Description copied from interface:SessionCheck if timeout has occurred.- Specified by:
getTimeoutStatusin interfaceSession- Returns:
- the timeout status - never
null
-
getReservedSessionMessagesHandler
public ReservedSessionMessagesHandler getReservedSessionMessagesHandler()
- Specified by:
getReservedSessionMessagesHandlerin interfaceReservedSessionMessagesManager- Returns:
- The currently registered
ReservedSessionMessagesHandler- may benull
-
setReservedSessionMessagesHandler
public void setReservedSessionMessagesHandler(ReservedSessionMessagesHandler handler)
- Specified by:
setReservedSessionMessagesHandlerin interfaceReservedSessionMessagesManager- Parameters:
handler- TheReservedSessionMessagesHandlerto use - may benull
-
getSessionDisconnectHandler
public SessionDisconnectHandler getSessionDisconnectHandler()
- Specified by:
getSessionDisconnectHandlerin interfaceSessionDisconnectHandlerManager
-
setSessionDisconnectHandler
public void setSessionDisconnectHandler(SessionDisconnectHandler sessionDisconnectHandler)
- Specified by:
setSessionDisconnectHandlerin 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 theReservedSessionMessagesHandlerand invokes itshandleIgnoreMessagemethod.- 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_UNIMPLEMENTEDmessage- Parameters:
seqNoValue- The referenced sequence number- Returns:
- An
IoWriteFuturethat 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:SessionSends anSSH_MSG_DEBUGto the peer session- Specified by:
sendDebugMessagein interfaceSession- Parameters:
display-trueif OK to display the message at the peer as-ismsg- The message object whosetoString()value to be used - ifnullthen the "null" string is sentlang- The language -null/empty if some pre-agreed default is used- Returns:
- An
IoWriteFuturethat 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 theReservedSessionMessagesHandlerand invokes itshandleDebugMessagemethod.- Parameters:
buffer- The inputBuffer- Throws:
java.lang.Exception- if failed to handle the message
-
resolveReservedSessionMessagesHandler
protected ReservedSessionMessagesHandler resolveReservedSessionMessagesHandler()
-
getUnknownChannelReferenceHandler
public UnknownChannelReferenceHandler getUnknownChannelReferenceHandler()
- Specified by:
getUnknownChannelReferenceHandlerin interfaceUnknownChannelReferenceHandlerManager- Returns:
- The
UnknownChannelReferenceHandlerManagerto use - ifnullthen any reference to unknown channel causes anSshChannelNotFoundException
-
setUnknownChannelReferenceHandler
public void setUnknownChannelReferenceHandler(UnknownChannelReferenceHandler unknownChannelReferenceHandler)
- Specified by:
setUnknownChannelReferenceHandlerin interfaceUnknownChannelReferenceHandlerManager- Parameters:
unknownChannelReferenceHandler- TheUnknownChannelReferenceHandlerManagerto use - ifnullthen any reference to unknown channel causes anSshChannelNotFoundException
-
resolveUnknownChannelReferenceHandler
public UnknownChannelReferenceHandler resolveUnknownChannelReferenceHandler()
Description copied from interface:UnknownChannelReferenceHandlerManagerCheck if current manager has a specific handler set for it - if not, try and resolve one from the "parent" container (if any)- Specified by:
resolveUnknownChannelReferenceHandlerin interfaceUnknownChannelReferenceHandlerManager- Returns:
- The resolved handler instance
-
getChannelStreamWriterResolver
public ChannelStreamWriterResolver getChannelStreamWriterResolver()
- Specified by:
getChannelStreamWriterResolverin interfaceChannelStreamWriterResolverManager
-
setChannelStreamWriterResolver
public void setChannelStreamWriterResolver(ChannelStreamWriterResolver resolver)
- Specified by:
setChannelStreamWriterResolverin interfaceChannelStreamWriterResolverManager
-
resolveChannelStreamWriterResolver
public ChannelStreamWriterResolver resolveChannelStreamWriterResolver()
- Specified by:
resolveChannelStreamWriterResolverin interfaceChannelStreamWriterResolverManager
-
sendIgnoreMessage
public IoWriteFuture sendIgnoreMessage(byte... data) throws java.io.IOException
Description copied from interface:SessionSends anSSH_MSG_IGNOREto the peer session- Specified by:
sendIgnoreMessagein interfaceSession- Parameters:
data- The message data- Returns:
- An
IoWriteFuturethat 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
-
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)
-
signalSendIdentification
protected void signalSendIdentification(java.lang.String version, java.util.List<java.lang.String> extraLines) throws java.lang.Exception- Throws:
java.lang.Exception
-
signalSendIdentification
protected void signalSendIdentification(SessionListener listener, java.lang.String version, java.util.List<java.lang.String> extraLines)
-
signalReadPeerIdentificationLine
protected void signalReadPeerIdentificationLine(java.lang.String line, java.util.List<java.lang.String> extraLines) throws java.lang.Exception- Throws:
java.lang.Exception
-
signalReadPeerIdentificationLine
protected void signalReadPeerIdentificationLine(SessionListener listener, java.lang.String version, java.util.List<java.lang.String> extraLines)
-
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.lang.Exception
Sends a session event to all currently registered session listeners- Parameters:
event- The event to send- Throws:
java.lang.Exception- 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.ExceptionMethod 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
nullotherwise, theIoSessionpeer 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 version, java.util.List<java.lang.String> extraLines) throws java.lang.Exception
Send our identification.- Parameters:
version- our identification to sendextraLines- Extra lines to send - used only by server sessions- Returns:
IoWriteFuturethat can be used to wait for notification that identification has been send- Throws:
java.lang.Exception- If failed to send the packet
-
doReadIdentification
protected java.util.List<java.lang.String> doReadIdentification(Buffer buffer, boolean server) throws java.lang.Exception
Read the remote identification from this buffer. If more data is needed, the buffer will be reset to its original state and anullvalue 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-trueif it is called by the server session,falseif by the client session- Returns:
- A
Listof all received remote identification lines until the version line was read ornullif more data is needed. The identification line is the last one in the list - Throws:
java.lang.Exception- if malformed identification found
-
resolveSessionKexProposal
protected java.lang.String resolveSessionKexProposal(java.lang.String hostKeyTypes) throws java.io.IOException- Throws:
java.io.IOException
-
resolveAvailableSignaturesProposal
protected java.lang.String resolveAvailableSignaturesProposal() throws java.io.IOException, java.security.GeneralSecurityExceptionComputes the list of available host key signature algorithms supported.- Returns:
- A comma-separated list of all the signature protocols to be included in the
proposal -
null/empty if no proposal - Throws:
java.io.IOException- If failed to read/parse the keys datajava.security.GeneralSecurityException- If failed to generate the keys- See Also:
getFactoryManager(),resolveAvailableSignaturesProposal(FactoryManager)
-
resolveAvailableSignaturesProposal
protected abstract java.lang.String resolveAvailableSignaturesProposal(FactoryManager manager) throws java.io.IOException, java.security.GeneralSecurityException
Computes the list of available host key signature algorithms supported.- Parameters:
manager- TheFactoryManager- Returns:
- A comma-separated list of all the signature protocols to be included in the
proposal -
null/empty if no proposal - Throws:
java.io.IOException- If failed to read/parse the keys datajava.security.GeneralSecurityException- If failed to generate the keys
-
getKexProposal
protected java.util.Map<KexProposalOption,java.lang.String> getKexProposal() throws java.lang.Exception
Retrieves this side's initial proposal for KEX negotiation. If no proposal exists yet, one is created and passed though theKexExtensionHandlerand theSessionListenerfor customization, otherwise the previously created proposal for the session is returned.- Returns:
- the proposal
Map - Throws:
java.lang.Exception- when no proposal can be created
-
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)
-
signalNegotiationOptionsCreated
protected void signalNegotiationOptionsCreated(java.util.Map<KexProposalOption,java.lang.String> proposal)
-
signalNegotiationOptionsCreated
protected void signalNegotiationOptionsCreated(SessionListener listener, 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.IOExceptionDescription copied from interface:SessionSend a disconnect packet with the given reason and message. Once the packet has been sent, the session will be closed asynchronously.- Specified by:
disconnectin 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:
exceptionCaughtin 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:
getLocalForwardsBindingsin 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:PortForwardingInformationProviderTest if local port forwarding is started- Specified by:
isLocalPortForwardingStartedForPortin interfacePortForwardingInformationProvider- Parameters:
port- The local port- Returns:
trueif local port forwarding is started- See Also:
getBoundLocalPortForwards
-
getStartedLocalPortForwards
public java.util.List<SshdSocketAddress> getStartedLocalPortForwards()
- Specified by:
getStartedLocalPortForwardsin interfacePortForwardingInformationProvider- Returns:
- A
Listsnapshot of the currently started local port forward bindings
-
getBoundLocalPortForwards
public java.util.List<SshdSocketAddress> getBoundLocalPortForwards(int port)
- Specified by:
getBoundLocalPortForwardsin 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:
getRemoteForwardsBindingsin 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:PortForwardingInformationProviderTest if remote port forwarding is started- Specified by:
isRemotePortForwardingStartedForPortin interfacePortForwardingInformationProvider- Parameters:
port- The remote port- Returns:
trueif remote port forwarding is started- See Also:
getBoundRemotePortForward
-
getStartedRemotePortForwards
public java.util.NavigableSet<java.lang.Integer> getStartedRemotePortForwards()
- Specified by:
getStartedRemotePortForwardsin interfacePortForwardingInformationProvider- Returns:
- A
NavigableSetsnapshot of the currently started remote port forwards
-
getBoundRemotePortForward
public SshdSocketAddress getBoundRemotePortForward(int port)
- Specified by:
getBoundRemotePortForwardin interfacePortForwardingInformationProvider- Parameters:
port- The port number- Returns:
- The remote bound
SshdSocketAddressfor the port -nullif none bound - See Also:
isRemotePortForwardingStartedForPort,PortForwardingInformationProvider.getStartedRemotePortForwards()
-
getAuthTimeout
public java.time.Duration getAuthTimeout()
- Specified by:
getAuthTimeoutin interfaceSession- Returns:
- Timeout value in milliseconds for authentication stage
-
getIdleTimeout
public java.time.Duration getIdleTimeout()
- Specified by:
getIdleTimeoutin interfaceSession- Returns:
- Timeout value in milliseconds for communication
-
toString
public java.lang.String toString()
- Overrides:
toStringin classjava.lang.Object
-
-