public abstract class AbstractSession extends CloseableUtils.AbstractInnerCloseable implements Session
The AbstractSession handles all the basic SSH protocol such as key exchange, authentication,
encoding and decoding. Both server side and client side sessions should inherit from this
abstract class. Some basic packet processing methods are defined but the actual call to these
methods should be done from the handleMessage(org.apache.sshd.common.util.buffer.Buffer)
method, which is dependent on the state and side of this session.
CloseableUtils.AbstractCloseable.StateSession.AttributeKey<T>, Session.TimeoutStatus| Modifier and Type | Field and Description |
|---|---|
protected Map<Session.AttributeKey<?>,Object> |
attributes |
protected boolean |
authed
Boolean indicating if this session has been authenticated or not
|
protected long |
authTimeoutMs |
protected long |
authTimeoutTimestamp |
protected Map<KexProposalOption,String> |
clientProposal |
protected String |
clientVersion |
protected Service |
currentService |
protected Object |
decodeLock |
protected Buffer |
decoderBuffer |
protected int |
decoderLength |
protected int |
decoderState |
static String |
DEFAULT_SSH_VERSION_PREFIX |
protected long |
disconnectTimeoutMs |
protected Object |
encodeLock |
protected FactoryManager |
factoryManager
The factory manager used to retrieve factories of Ciphers, Macs and other objects
|
protected byte[] |
i_c |
protected byte[] |
i_s |
protected long |
idleTimeoutMs |
protected long |
idleTimeoutTimestamp |
protected AtomicLong |
inBytesCount |
protected Cipher |
inCipher |
protected int |
inCipherSize |
protected Compression |
inCompression |
protected Mac |
inMac |
protected byte[] |
inMacResult |
protected AtomicLong |
inPacketsCount |
protected IoSession |
ioSession
The underlying MINA session
|
protected boolean |
isServer
Client or server side
|
protected KeyExchange |
kex |
protected AtomicReference<KexState> |
kexState |
protected AtomicLong |
lastKeyTimeValue |
protected List<SessionListener> |
listeners
Session listeners container
|
protected Map<KexProposalOption,String> |
negotiationResult |
protected AtomicLong |
outBytesCount |
protected Cipher |
outCipher |
protected int |
outCipherSize |
protected Compression |
outCompression |
protected Mac |
outMac |
protected AtomicLong |
outPacketsCount |
protected Queue<PendingWriteFuture> |
pendingPackets |
protected Random |
random
The pseudo random generator
|
protected DefaultSshFuture |
reexchangeFuture |
protected Object |
requestLock |
protected AtomicReference<Buffer> |
requestResult |
protected long |
seqi |
protected long |
seqo |
protected Map<KexProposalOption,String> |
serverProposal |
protected String |
serverVersion |
static String |
SESSION
Name of the property where this session is stored in the attributes of the
underlying MINA session.
|
protected byte[] |
sessionId |
protected SessionListener |
sessionListenerProxy |
protected AtomicReference<Session.TimeoutStatus> |
timeoutStatus |
protected Buffer |
uncompressBuffer |
protected String |
username
The name of the authenticated user
|
closeFuture, lock, statelog| Constructor and Description |
|---|
AbstractSession(boolean isServer,
FactoryManager factoryManager,
IoSession ioSession)
Create a new session.
|
| Modifier and Type | Method and Description |
|---|---|
void |
addListener(SessionListener listener)
Add a session |listener|.
|
static void |
attachSession(IoSession ioSession,
AbstractSession session)
Attach a session to the MINA session
|
protected void |
checkForTimeouts()
Checks whether the session has timed out (both auth and idle timeouts are checked).
|
protected abstract void |
checkKeys() |
protected void |
checkRekey() |
Buffer |
createBuffer(byte cmd)
Create a new buffer for the specified SSH packet and reserve the needed space
(5 bytes) for the packet header.
|
Buffer |
createBuffer(byte cmd,
int len)
Create a new buffer for the specified SSH packet and reserve the needed space
(5 bytes) for the packet header.
|
protected Map<KexProposalOption,String> |
createProposal(String hostKeyTypes)
Create our proposal for SSH negotiation
|
protected void |
decode()
Decode the incoming buffer and handle packets as needed.
|
void |
disconnect(int reason,
String msg)
Send a disconnect packet with the given reason and message.
|
protected void |
doCloseImmediately()
doCloseImmediately is called once and only once
with state == Immediate
|
protected void |
doHandleMessage(Buffer buffer) |
protected String |
doReadIdentification(Buffer buffer,
boolean server)
Read the remote identification from this buffer.
|
protected IoWriteFuture |
doWritePacket(Buffer buffer) |
void |
exceptionCaught(Throwable t)
Handle any exceptions that occurred on this session.
|
<T> T |
getAttribute(Session.AttributeKey<T> key)
Returns the value of the user-defined attribute of this session.
|
long |
getAuthTimeout()
What is timeout value in milliseconds for authentication stage
|
String |
getClientVersion()
Retrieve the client version for this session.
|
FactoryManager |
getFactoryManager() |
long |
getIdleTimeout()
What is timeout value in milliseconds for communication
|
protected Closeable |
getInnerCloseable() |
int |
getIntProperty(String name,
int defaultValue)
Retrieve a configuration property as an integer
|
IoSession |
getIoSession() |
KeyExchange |
getKex() |
Object |
getLock() |
long |
getLongProperty(String name,
long defaultValue) |
String |
getNegotiatedKexParameter(KexProposalOption paramType)
Retrieve one of the negotiated values during the KEX stage
|
String |
getServerVersion()
Retrieve the server version for this session.
|
<T extends Service> |
getService(Class<T> clazz)
Get the service of the specified type.
|
protected Service[] |
getServices() |
static AbstractSession |
getSession(IoSession ioSession)
Retrieve the session from the MINA session.
|
static AbstractSession |
getSession(IoSession ioSession,
boolean allowNull)
Retrieve the session from the MINA session.
|
byte[] |
getSessionId() |
Session.TimeoutStatus |
getTimeoutStatus()
Check if timeout has occurred.
|
String |
getUsername()
Retrieve the name of the user authenticated on this session
or null if the session has not been authenticated yet.
|
protected void |
handleMessage(Buffer buffer)
Abstract method for processing incoming decoded packets.
|
boolean |
isAuthenticated() |
protected Map<KexProposalOption,String> |
mergeProposals(Map<KexProposalOption,String> current,
Map<KexProposalOption,String> proposal) |
void |
messageReceived(Readable buffer)
Main input point for the MINA framework.
|
protected Map<KexProposalOption,String> |
negotiate()
Compute the negotiated proposals by merging the client and
server proposal.
|
protected void |
notImplemented()
Send an unimplemented packet.
|
protected abstract boolean |
readIdentification(Buffer buffer)
Read the other side identification.
|
protected void |
receiveKexInit(Buffer buffer) |
protected byte[] |
receiveKexInit(Buffer buffer,
Map<KexProposalOption,String> proposal)
Receive the remote key exchange init message.
|
protected abstract void |
receiveKexInit(Map<KexProposalOption,String> proposal,
byte[] seed) |
protected void |
receiveNewKeys()
Put new keys into use.
|
SshFuture |
reExchangeKeys()
Initiate a new key exchange.
|
void |
removeListener(SessionListener listener)
Remove a session |listener|.
|
Buffer |
request(Buffer buffer)
Send a global request and wait for the response.
|
protected void |
requestFailure(Buffer buffer) |
protected void |
requestSuccess(Buffer buffer) |
void |
resetIdleTimeout() |
protected String |
resolveAvailableSignaturesProposal() |
protected abstract String |
resolveAvailableSignaturesProposal(FactoryManager manager) |
protected void |
sendEvent(SessionListener.Event event) |
protected void |
sendIdentification(String ident)
Send our identification.
|
protected byte[] |
sendKexInit() |
protected byte[] |
sendKexInit(Map<KexProposalOption,String> proposal)
Send the key exchange initialization packet.
|
protected void |
sendNewKeys()
Send a message to put new keys into use.
|
protected void |
serviceAccept() |
<T,E extends T> |
setAttribute(Session.AttributeKey<T> key,
E value)
Sets a user-defined attribute.
|
void |
setAuthenticated() |
protected abstract void |
setKexSeed(byte... seed) |
protected Map<KexProposalOption,String> |
setNegotiationResult(Map<KexProposalOption,String> guess) |
void |
setUsername(String username) |
String |
toString() |
protected void |
validateKexState(int cmd,
KexState expected) |
IoWriteFuture |
writePacket(Buffer buffer)
Encode and send the given buffer.
|
IoWriteFuture |
writePacket(Buffer buffer,
long timeout,
TimeUnit unit)
Encode and send the given buffer with the specified timeout.
|
doCloseGracefullybuilder, close, isClosed, isClosing, preCloseclose, isOpenclone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitstartServicepublic static final String DEFAULT_SSH_VERSION_PREFIX
public static final String SESSION
getSession(IoSession, boolean)
and attachSession(IoSession, AbstractSession).protected final boolean isServer
protected final FactoryManager factoryManager
protected final IoSession ioSession
protected final Random random
protected boolean authed
protected String username
protected final List<SessionListener> listeners
protected final SessionListener sessionListenerProxy
protected byte[] sessionId
protected String serverVersion
protected String clientVersion
protected final Map<KexProposalOption,String> serverProposal
protected final Map<KexProposalOption,String> clientProposal
protected final Map<KexProposalOption,String> negotiationResult
protected byte[] i_c
protected byte[] i_s
protected KeyExchange kex
protected final AtomicReference<KexState> kexState
protected DefaultSshFuture reexchangeFuture
protected Cipher outCipher
protected Cipher inCipher
protected int outCipherSize
protected int inCipherSize
protected Mac outMac
protected Mac inMac
protected byte[] inMacResult
protected Compression outCompression
protected Compression inCompression
protected long seqi
protected long seqo
protected Buffer decoderBuffer
protected Buffer uncompressBuffer
protected int decoderState
protected int decoderLength
protected final Object encodeLock
protected final Object decodeLock
protected final Object requestLock
protected final AtomicReference<Buffer> requestResult
protected final Map<Session.AttributeKey<?>,Object> attributes
protected long authTimeoutTimestamp
protected long idleTimeoutTimestamp
protected long authTimeoutMs
protected long idleTimeoutMs
protected long disconnectTimeoutMs
protected final AtomicReference<Session.TimeoutStatus> timeoutStatus
protected final AtomicLong inPacketsCount
protected final AtomicLong outPacketsCount
protected final AtomicLong inBytesCount
protected final AtomicLong outBytesCount
protected final AtomicLong lastKeyTimeValue
protected final Queue<PendingWriteFuture> pendingPackets
protected Service currentService
public AbstractSession(boolean isServer,
FactoryManager factoryManager,
IoSession ioSession)
isServer - true if this is a server session, false if client onefactoryManager - the factory managerioSession - the underlying MINA sessionpublic static AbstractSession getSession(IoSession ioSession)
ioSession - the MINA sessionpublic static AbstractSession getSession(IoSession ioSession, boolean allowNull)
false,
an IllegalStateException will be thrown, else a null will
be returnedioSession - the MINA sessionallowNull - if true, a null value may be
returned if no session is attachednullpublic static void attachSession(IoSession ioSession, AbstractSession session)
ioSession - the MINA sessionsession - the session to attachpublic String getServerVersion()
SessiongetServerVersion in interface Sessionpublic String getClientVersion()
SessiongetClientVersion in interface Sessionpublic KeyExchange getKex()
public byte[] getSessionId()
getSessionId in interface Sessionpublic IoSession getIoSession()
getIoSession in interface SessionIoSession associated to this sessionpublic FactoryManager getFactoryManager()
getFactoryManager in interface SessionFactoryManager that has created this session, can not be nullpublic String getNegotiatedKexParameter(KexProposalOption paramType)
SessiongetNegotiatedKexParameter in interface SessionparamType - The request KexProposalOption value - ignored
if nullnull if invalid
parameter or no negotiated valuepublic boolean isAuthenticated()
isAuthenticated in interface Sessionpublic void setAuthenticated()
throws IOException
setAuthenticated in interface SessionIOExceptionpublic void messageReceived(Readable buffer) throws Exception
Main input point for the MINA framework.
This method will be called each time new data is received on
the socket and will append it to the input buffer before
calling the decode() method.
buffer - the new buffer receivedException - if an error occurs while decoding or handling the dataprotected void handleMessage(Buffer buffer) throws Exception
buffer - the buffer containing the packetException - if an exeption occurs while handling this packet.protected void validateKexState(int cmd,
KexState expected)
public void exceptionCaught(Throwable t)
SshException.exceptionCaught in interface Sessiont - the exception to processprotected Closeable getInnerCloseable()
getInnerCloseable in class CloseableUtils.AbstractInnerCloseableprotected void doCloseImmediately()
CloseableUtils.AbstractCloseabledoCloseImmediately is called once and only once with state == Immediate
Overriding methods should always call the base implementation. It may be called concurrently while preClose() or doCloseGracefully is executing
doCloseImmediately in class CloseableUtils.AbstractInnerCloseableprotected Service[] getServices()
public <T extends Service> T getService(Class<T> clazz)
SessiongetService in interface SessionT - The generic service typeclazz - The service classpublic IoWriteFuture writePacket(Buffer buffer) throws IOException
writePacket in interface Sessionbuffer - the buffer to encode and sendIOException - if an error occured when encoding sending the packetpublic IoWriteFuture writePacket(Buffer buffer, long timeout, TimeUnit unit) throws IOException
SessionIoWriteFuture will be set with a
TimeoutException exception to indicate a timeout.writePacket in interface Sessionbuffer - the buffer to encode and spendtimeout - the timeoutunit - the time unit of the timeout parameterIOException - if an error occurred when encoding sending the packetprotected IoWriteFuture doWritePacket(Buffer buffer) throws IOException
IOExceptionpublic Buffer request(Buffer buffer) throws IOException
request in interface Sessionbuffer - the buffer containing the global requesttrue if the request was successful, false otherwise.IOException - if an error occured when encoding sending the packetpublic Buffer createBuffer(byte cmd)
SessioncreateBuffer in interface Sessioncmd - the SSH commandpublic Buffer createBuffer(byte cmd, int len)
createBuffer in interface Sessioncmd - the SSH commandlen - estimated number of bytes the buffer will hold, 0 if unknown.protected void decode()
throws Exception
Exception - If failed to decodeprotected void sendIdentification(String ident)
ident - our identification to sendprotected abstract boolean readIdentification(Buffer buffer) throws IOException
doReadIdentification(org.apache.sshd.common.util.buffer.Buffer, boolean) and
store the result in the needed property.buffer - the buffer containing the remote identificationtrue if the identification has been fully read or
false if more data is neededIOException - if an error occurs such as a bad protocol versionprotected String doReadIdentification(Buffer buffer, boolean server)
null value will be returned. Else the identification
string will be returned and the data read will be consumed from the buffer.buffer - the buffer containing the identification stringserver - true if it is called by the server session,
false if by the client sessionnull if more data is neededprotected Map<KexProposalOption,String> createProposal(String hostKeyTypes)
hostKeyTypes - The comma-separated list of supported host key typesMapprotected byte[] sendKexInit(Map<KexProposalOption,String> proposal) throws IOException
proposal - our proposal for key exchange negotiationIOException - if an error occurred sending the packetprotected byte[] receiveKexInit(Buffer buffer, Map<KexProposalOption,String> proposal)
buffer - the buffer containing the key exchange init packetproposal - the remote proposal to fillprotected void sendNewKeys()
throws IOException
IOException - if an error occurs sending the messageprotected void receiveNewKeys()
throws Exception
Exception - if an error occurspublic void disconnect(int reason,
String msg)
throws IOException
Sessiondisconnect in interface Sessionreason - the reason code for this disconnectmsg - the text messageIOException - if an error occurred sending the packetprotected void notImplemented()
throws IOException
IOException - if an error occurred sending the packetprotected Map<KexProposalOption,String> negotiate()
negotiationResult property.Mapprotected Map<KexProposalOption,String> setNegotiationResult(Map<KexProposalOption,String> guess)
public int getIntProperty(String name, int defaultValue)
getIntProperty in interface Sessionname - the name of the propertydefaultValue - the default valuepublic long getLongProperty(String name, long defaultValue)
public <T> T getAttribute(Session.AttributeKey<T> key)
getAttribute in interface SessionT - The generic attribute typekey - the key of the attribute; must not be null.public <T,E extends T> T setAttribute(Session.AttributeKey<T> key, E value)
setAttribute in interface SessionT - The generic attribute typeE - The generic value typekey - the key of the attribute; must not be null.value - the value of the attribute; must not be null.public String getUsername()
SessiongetUsername in interface Sessionpublic void setUsername(String username)
setUsername in interface Sessionpublic Object getLock()
public void addListener(SessionListener listener)
SessionaddListener in interface Sessionlistener - the session listener to addpublic void removeListener(SessionListener listener)
SessionremoveListener in interface Sessionlistener - the session listener to removeprotected void sendEvent(SessionListener.Event event) throws IOException
IOExceptionpublic SshFuture reExchangeKeys() throws IOException
SessionreExchangeKeys in interface SessionSshFuture for awaiting the completion of the exchangeIOException - If failed to negotiate keysprotected void checkRekey()
throws IOException
IOExceptionprotected byte[] sendKexInit()
throws IOException
IOExceptionprotected abstract void setKexSeed(byte... seed)
seed - The result of the KEXINIT handshake - required for correct
session key establishmentprotected String resolveAvailableSignaturesProposal()
null/empty if no proposalgetFactoryManager(),
resolveAvailableSignaturesProposal(FactoryManager)protected abstract String resolveAvailableSignaturesProposal(FactoryManager manager)
manager - The FactoryManagernull/empty if no proposalprotected abstract void checkKeys()
throws IOException
IOExceptionprotected void receiveKexInit(Buffer buffer) throws IOException
IOExceptionprotected abstract void receiveKexInit(Map<KexProposalOption,String> proposal, byte[] seed) throws IOException
IOExceptionprotected Map<KexProposalOption,String> mergeProposals(Map<KexProposalOption,String> current, Map<KexProposalOption,String> proposal)
protected void serviceAccept()
throws IOException
IOExceptionprotected void checkForTimeouts()
throws IOException
IOException - If failed to checkpublic void resetIdleTimeout()
resetIdleTimeout in interface Sessionpublic Session.TimeoutStatus getTimeoutStatus()
getTimeoutStatus in interface SessionTimeoutStatuspublic long getAuthTimeout()
getAuthTimeout in interface Sessionpublic long getIdleTimeout()
getIdleTimeout in interface SessionCopyright © 2008–2015 The Apache Software Foundation. All rights reserved.