org.apache.sshd.common.session
Class AbstractSession

java.lang.Object
  extended by org.apache.sshd.common.session.AbstractSession
All Implemented Interfaces:
Session
Direct Known Subclasses:
ClientSessionImpl, ServerSession

public abstract class AbstractSession
extends Object
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) method, which is dependant on the state and side of this session. TODO: if there is any very big packet, decoderBuffer and uncompressBuffer will get quite big and they won't be resized down at any time. Though the packet size is really limited by the channel max packet size

Author:
Apache MINA SSHD Project

Nested Class Summary
 
Nested classes/interfaces inherited from interface org.apache.sshd.common.Session
Session.AttributeKey<T>
 
Field Summary
protected  Map<Session.AttributeKey<?>,Object> attributes
           
protected  boolean authed
          Boolean indicating if this session has been authenticated or not
protected  Map<Integer,Channel> channels
          Map of channels keyed by the identifier
protected  String[] clientProposal
           
protected  String clientVersion
           
protected  CloseFuture closeFuture
          A future that will be set 'closed' when the connection is closed.
protected  boolean closing
          The session is being closed
protected  Object decodeLock
           
protected  Buffer decoderBuffer
           
protected  int decoderLength
           
protected  int decoderState
           
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  Cipher inCipher
           
protected  int inCipherSize
           
protected  Compression inCompression
           
protected  Mac inMac
           
protected  byte[] inMacResult
           
protected  org.apache.mina.core.session.IoSession ioSession
          The underlying MINA session
protected  KeyExchange kex
           
protected  List<SessionListener> listeners
          Session listener
protected  Object lock
          Lock object for this session state
protected  org.slf4j.Logger log
          Our logger
protected  String[] negociated
           
protected  int nextChannelId
          Next channel identifier
protected  Cipher outCipher
           
protected  int outCipherSize
           
protected  Compression outCompression
           
protected  Mac outMac
           
protected  Random random
          The pseudo random generator
protected  long seqi
           
protected  long seqo
           
protected  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  Buffer uncompressBuffer
           
protected  String username
           
 
Constructor Summary
AbstractSession(FactoryManager factoryManager, org.apache.mina.core.session.IoSession ioSession)
          Create a new session.
 
Method Summary
 void addListener(SessionListener listener)
          Add a session |listener|.
static void attachSession(org.apache.mina.core.session.IoSession ioSession, AbstractSession session)
          Attach a session to the MINA session
protected  void channelClose(Buffer buffer)
          Close a channel due to a close packet received
protected  void channelData(Buffer buffer)
          Process incoming data on a channel
protected  void channelEof(Buffer buffer)
          Process end of file on a channel
protected  void channelExtendedData(Buffer buffer)
          Process incoming extended data on a channel
protected  void channelFailure(Buffer buffer)
          Process a failure on a channel
protected  void channelOpenConfirmation(Buffer buffer)
           
protected  void channelOpenFailure(Buffer buffer)
           
protected  void channelRequest(Buffer buffer)
          Service a request on a channel
protected  void channelWindowAdjust(Buffer buffer)
          Process a window adjust packet on a channel
 CloseFuture close(boolean immediately)
          Close this session.
 Buffer createBuffer(SshConstants.Message cmd, int len)
          Create a new buffer for the specified SSH packet and reserve the needed space (5 bytes) for the packet header.
protected  String[] createProposal(String hostKeyTypes)
          Create our proposal for SSH negociation
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  String doReadIdentification(Buffer buffer)
          Read the remote identification from this buffer.
 void exceptionCaught(Throwable t)
          Handle any exceptions that occured on this session.
<T> T
getAttribute(Session.AttributeKey<T> key)
          Returns the value of the user-defined attribute of this session.
protected  Channel getChannel(Buffer buffer)
          Retrieve the channel designated by the given packet
 FactoryManager getFactoryManager()
          Retrieve the factory manager
 int getIntProperty(String name, int defaultValue)
          Retrieve a configuration property as an integer
 org.apache.mina.core.session.IoSession getIoSession()
          Retrieve the mina session
protected  int getNextChannelId()
           
static AbstractSession getSession(org.apache.mina.core.session.IoSession ioSession)
          Retrieve the session from the MINA session.
static AbstractSession getSession(org.apache.mina.core.session.IoSession ioSession, boolean allowNull)
          Retrieve the session from the MINA session.
 String getUsername()
          Retrieve the name of the user authenticated on this session or null if the session has not been authenticated yet.
protected abstract  void handleMessage(Buffer buffer)
          Abstract method for processing incoming decoded packets.
 void messageReceived(org.apache.mina.core.buffer.IoBuffer buffer)
          Main input point for the MINA framework.
protected  void negociate()
          Compute the negociated 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  byte[] receiveKexInit(Buffer buffer, String[] proposal)
          Receive the remote key exchange init message.
protected  void receiveNewKeys(boolean isServer)
          Put new keys into use.
 int registerChannel(Channel channel)
          Register a newly created channel with a new unique identifier
 void removeListener(SessionListener listener)
          Remove a session |listener|.
protected  void sendIdentification(String ident)
          Send our identification.
protected  byte[] sendKexInit(String[] proposal)
          Send the key exchange initialization packet.
protected  void sendNewKeys()
          Send a message to put new keys into use.
<T,E extends T>
T
setAttribute(Session.AttributeKey<T> key, E value)
          Sets a user-defined attribute.
 void unregisterChannel(Channel channel)
          Remove this channel from the list of managed channels
 org.apache.mina.core.future.WriteFuture writePacket(Buffer buffer)
          Encode and send the given buffer.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

SESSION

public static final String SESSION
Name of the property where this session is stored in the attributes of the underlying MINA session. See getSession(IoSession, boolean) and attachSession(IoSession, AbstractSession).

See Also:
Constant Field Values

log

protected final org.slf4j.Logger log
Our logger


factoryManager

protected final FactoryManager factoryManager
The factory manager used to retrieve factories of Ciphers, Macs and other objects


ioSession

protected final org.apache.mina.core.session.IoSession ioSession
The underlying MINA session


random

protected final Random random
The pseudo random generator


lock

protected final Object lock
Lock object for this session state


closeFuture

protected final CloseFuture closeFuture
A future that will be set 'closed' when the connection is closed.


closing

protected volatile boolean closing
The session is being closed


authed

protected boolean authed
Boolean indicating if this session has been authenticated or not


channels

protected final Map<Integer,Channel> channels
Map of channels keyed by the identifier


nextChannelId

protected int nextChannelId
Next channel identifier


listeners

protected final List<SessionListener> listeners
Session listener


sessionId

protected byte[] sessionId

serverVersion

protected String serverVersion

clientVersion

protected String clientVersion

serverProposal

protected String[] serverProposal

clientProposal

protected String[] clientProposal

negociated

protected String[] negociated

I_C

protected byte[] I_C

I_S

protected byte[] I_S

kex

protected KeyExchange kex

outCipher

protected Cipher outCipher

inCipher

protected Cipher inCipher

outCipherSize

protected int outCipherSize

inCipherSize

protected int inCipherSize

outMac

protected Mac outMac

inMac

protected Mac inMac

inMacResult

protected byte[] inMacResult

outCompression

protected Compression outCompression

inCompression

protected Compression inCompression

seqi

protected long seqi

seqo

protected long seqo

decoderBuffer

protected Buffer decoderBuffer

uncompressBuffer

protected Buffer uncompressBuffer

decoderState

protected int decoderState

decoderLength

protected int decoderLength

encodeLock

protected final Object encodeLock

decodeLock

protected final Object decodeLock

attributes

protected final Map<Session.AttributeKey<?>,Object> attributes

username

protected String username
Constructor Detail

AbstractSession

public AbstractSession(FactoryManager factoryManager,
                       org.apache.mina.core.session.IoSession ioSession)
Create a new session.

Parameters:
factoryManager - the factory manager
ioSession - the underlying MINA session
Method Detail

getSession

public static final AbstractSession getSession(org.apache.mina.core.session.IoSession ioSession)
Retrieve the session from the MINA session. If the session has not been attached, an IllegalStateException will be thrown

Parameters:
ioSession - the MINA session
Returns:
the session attached to the MINA session

getSession

public static final AbstractSession getSession(org.apache.mina.core.session.IoSession ioSession,
                                               boolean allowNull)
Retrieve the session from the MINA session. If the session has not been attached and allowNull is false, an IllegalStateException will be thrown, else a null will be returned

Parameters:
ioSession - the MINA session
allowNull - if true, a null value may be returned if no session is attached
Returns:
the session attached to the MINA session or null

attachSession

public static final void attachSession(org.apache.mina.core.session.IoSession ioSession,
                                       AbstractSession session)
Attach a session to the MINA session

Parameters:
ioSession - the MINA session
session - the session to attach

getIoSession

public org.apache.mina.core.session.IoSession getIoSession()
Retrieve the mina session

Returns:
the mina session

getFactoryManager

public FactoryManager getFactoryManager()
Retrieve the factory manager

Specified by:
getFactoryManager in interface Session
Returns:
the factory manager for this session

messageReceived

public void messageReceived(org.apache.mina.core.buffer.IoBuffer 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.

Parameters:
buffer - the new buffer received
Throws:
Exception - if an error occurs while decoding or handling the data

handleMessage

protected abstract void handleMessage(Buffer buffer)
                               throws Exception
Abstract method for processing incoming decoded packets. The given buffer will hold the decoded packet, starting from the command byte at the read position. Packets must be processed within this call or be copied because the given buffer is meant to be changed and updated when this method returns.

Parameters:
buffer - the buffer containing the packet
Throws:
Exception - if an exeption occurs while handling this packet.

exceptionCaught

public void exceptionCaught(Throwable t)
Handle any exceptions that occured on this session. The session will be closed and a disconnect packet will be sent before if the given exception is an SshException.

Specified by:
exceptionCaught in interface Session
Parameters:
t - the exception to process
Throws:
IOException

close

public CloseFuture close(boolean immediately)
Close this session. This method will close all channels, then close the underlying MINA session. The call will not block until the mina session is actually closed.


writePacket

public org.apache.mina.core.future.WriteFuture writePacket(Buffer buffer)
                                                    throws IOException
Encode and send the given buffer. The buffer has to have 5 bytes free at the beginning to allow the encoding to take place. Also, the write position of the buffer has to be set to the position of the last byte to write.

Specified by:
writePacket in interface Session
Parameters:
buffer - the buffer to encode and send
Returns:
a future that can be used to check when the packet has actually been sent
Throws:
IOException - if an error occured when encoding sending the packet

createBuffer

public Buffer createBuffer(SshConstants.Message cmd,
                           int len)
Create a new buffer for the specified SSH packet and reserve the needed space (5 bytes) for the packet header.

Specified by:
createBuffer in interface Session
Parameters:
cmd - the SSH command
len - estimated number of bytes the buffer will hold, 0 if unknown.
Returns:
a new buffer ready for write

decode

protected void decode()
               throws Exception
Decode the incoming buffer and handle packets as needed.

Throws:
Exception

sendIdentification

protected void sendIdentification(String ident)
Send our identification.

Parameters:
ident - our identification to send

readIdentification

protected abstract boolean readIdentification(Buffer buffer)
                                       throws IOException
Read the other side identification. This method is specific to the client or server side, but both should call doReadIdentification(org.apache.sshd.common.util.Buffer) and store the result in the needed property.

Parameters:
buffer - the buffer containing the remote identification
Returns:
true if the identification has been fully read or false if more data is needed
Throws:
IOException - if an error occurs such as a bad protocol version

doReadIdentification

protected String doReadIdentification(Buffer buffer)
Read the remote identification from this buffer. If more data is needed, the buffer will be reset to its original state and a null 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 string
Returns:
the remote identification or null if more data is needed

createProposal

protected String[] createProposal(String hostKeyTypes)
Create our proposal for SSH negociation

Parameters:
hostKeyTypes - the list of supported host key types
Returns:
an array of 10 strings holding this proposal

sendKexInit

protected byte[] sendKexInit(String[] proposal)
                      throws IOException
Send the key exchange initialization packet. This packet contains random data along with our proposal.

Parameters:
proposal - our proposal for key exchange negociation
Returns:
the sent packet which must be kept for later use
Throws:
IOException - if an error occured sending the packet

receiveKexInit

protected byte[] receiveKexInit(Buffer buffer,
                                String[] proposal)
Receive the remote key exchange init message. The packet data is returned for later use.

Parameters:
buffer - the buffer containing the key exchange init packet
proposal - the remote proposal to fill
Returns:
the packet data

sendNewKeys

protected void sendNewKeys()
                    throws IOException
Send a message to put new keys into use.

Throws:
IOException - if an error occurs sending the message

receiveNewKeys

protected void receiveNewKeys(boolean isServer)
                       throws Exception
Put new keys into use. This method will intialize the ciphers, digests, macs and compression according to the negociated server and client proposals.

Parameters:
isServer - boolean indicating if this session is on the server or the client side
Throws:
Exception - if an error occurs

disconnect

public void disconnect(int reason,
                       String msg)
                throws IOException
Send a disconnect packet with the given reason and message. Once the packet has been sent, the session will be closed asynchronously.

Parameters:
reason - the reason code for this disconnect
msg - the text message
Throws:
IOException - if an error occured sending the packet

notImplemented

protected void notImplemented()
                       throws IOException
Send an unimplemented packet. This packet should contain the sequence id of the usupported packet: this number is assumed to be the last packet received.

Throws:
IOException - if an error occured sending the packet

negociate

protected void negociate()
Compute the negociated proposals by merging the client and server proposal. The negocatiated proposal will be stored in the negociated property.


getNextChannelId

protected int getNextChannelId()

registerChannel

public int registerChannel(Channel channel)
                    throws Exception
Description copied from interface: Session
Register a newly created channel with a new unique identifier

Specified by:
registerChannel in interface Session
Parameters:
channel - the channel to register
Returns:
the id of this channel
Throws:
Exception

channelOpenConfirmation

protected void channelOpenConfirmation(Buffer buffer)
                                throws IOException
Throws:
IOException

channelOpenFailure

protected void channelOpenFailure(Buffer buffer)
                           throws IOException
Throws:
IOException

channelData

protected void channelData(Buffer buffer)
                    throws Exception
Process incoming data on a channel

Parameters:
buffer - the buffer containing the data
Throws:
Exception - if an error occurs

channelExtendedData

protected void channelExtendedData(Buffer buffer)
                            throws Exception
Process incoming extended data on a channel

Parameters:
buffer - the buffer containing the data
Throws:
Exception - if an error occurs

channelWindowAdjust

protected void channelWindowAdjust(Buffer buffer)
                            throws Exception
Process a window adjust packet on a channel

Parameters:
buffer - the buffer containing the window adjustement parameters
Throws:
Exception - if an error occurs

channelEof

protected void channelEof(Buffer buffer)
                   throws Exception
Process end of file on a channel

Parameters:
buffer - the buffer containing the packet
Throws:
Exception - if an error occurs

channelClose

protected void channelClose(Buffer buffer)
                     throws Exception
Close a channel due to a close packet received

Parameters:
buffer - the buffer containing the packet
Throws:
Exception - if an error occurs

unregisterChannel

public void unregisterChannel(Channel channel)
Remove this channel from the list of managed channels

Specified by:
unregisterChannel in interface Session
Parameters:
channel - the channel

channelRequest

protected void channelRequest(Buffer buffer)
                       throws IOException
Service a request on a channel

Parameters:
buffer - the buffer containing the request
Throws:
Exception - if an error occurs
IOException

channelFailure

protected void channelFailure(Buffer buffer)
                       throws Exception
Process a failure on a channel

Parameters:
buffer - the buffer containing the packet
Throws:
Exception - if an error occurs

getChannel

protected Channel getChannel(Buffer buffer)
                      throws IOException
Retrieve the channel designated by the given packet

Parameters:
buffer - the incoming packet
Returns:
the target channel
Throws:
IOException - if the channel does not exists

getIntProperty

public int getIntProperty(String name,
                          int defaultValue)
Retrieve a configuration property as an integer

Specified by:
getIntProperty in interface Session
Parameters:
name - the name of the property
defaultValue - the default value
Returns:
the value of the configuration property or the default value if not found

getAttribute

public <T> T getAttribute(Session.AttributeKey<T> key)
Returns the value of the user-defined attribute of this session.

Specified by:
getAttribute in interface Session
Parameters:
key - the key of the attribute; must not be null.
Returns:
null if there is no attribute with the specified key

setAttribute

public <T,E extends T> T setAttribute(Session.AttributeKey<T> key,
                                      E value)
Sets a user-defined attribute.

Specified by:
setAttribute in interface Session
Parameters:
key - the key of the attribute; must not be null.
value - the value of the attribute; must not be null.
Returns:
The old value of the attribute. null if it is new.

getUsername

public String getUsername()
Description copied from interface: Session
Retrieve the name of the user authenticated on this session or null if the session has not been authenticated yet.

Specified by:
getUsername in interface Session
Returns:
the user name.

addListener

public void addListener(SessionListener listener)
Add a session |listener|.

Specified by:
addListener in interface Session
Parameters:
listener - the session listener to add

removeListener

public void removeListener(SessionListener listener)
Remove a session |listener|.

Specified by:
removeListener in interface Session
Parameters:
listener - the session listener to remove


Copyright © 2008-2012 Apache Software Foundation. All Rights Reserved.