Package net.schmizz.sshj.transport
Class TransportImpl
- java.lang.Object
-
- net.schmizz.sshj.transport.TransportImpl
-
- All Implemented Interfaces:
RemoteAddressProvider,SSHPacketHandler,DisconnectListener,Transport
public final class TransportImpl extends java.lang.Object implements Transport, DisconnectListener
A thread-safeTransportimplementation.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description (package private) static classTransportImpl.ConnInfoprivate static classTransportImpl.NullService
-
Field Summary
Fields Modifier and Type Field Description private booleanauthedprivate java.lang.StringclientIDClient version identification stringprivate Event<TransportException>closeprivate Configconfigprivate TransportImpl.ConnInfoconnInfoprivate Decoderdecoderprivate DisconnectListenerdisconnectListenerprivate Encoderencoderprivate KeyAlgorithmhostKeyAlgorithmprivate KeyExchangerkexerprivate org.slf4j.Loggerlogprivate LoggerFactoryloggerFactoryprivate MessagemsgMessage identifier of last packet receivedprivate ServicenextServiceThe next service that will be activated, only set when sending an SSH_MSG_SERVICE_REQUESTprivate ServicenullServiceprivate Readerreaderprivate java.lang.StringserverIDServer version identification stringprivate ServiceserviceCurrently active service e.g.private Event<TransportException>serviceAcceptprivate inttimeoutMsprivate java.util.concurrent.locks.ReentrantLockwriteLock
-
Constructor Summary
Constructors Constructor Description TransportImpl(Config config)
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidaddAlgorithmsVerifier(AlgorithmsVerifier verifier)Adds the specified verifier.voidaddHostKeyVerifier(HostKeyVerifier hkv)Adds the specified verifier.voiddie(java.lang.Exception ex)Kill the transport in an exceptional way.voiddisconnect()Send a disconnection packet with reason asDisconnectReason.BY_APPLICATION, and closes this transport.voiddisconnect(DisconnectReason reason)Send a disconnect packet with the givenreason, and closes this transport.voiddisconnect(DisconnectReason reason, java.lang.String message)Send a disconnect packet with the givenreasonandmessage, and closes this transport.voiddoKex()Do key exchange and algorithm negotiation.private voidfinishOff()(package private) java.lang.StringgetClientID()java.util.List<KeyAlgorithm>getClientKeyAlgorithms(KeyType keyType)java.lang.StringgetClientVersion()ConfiggetConfig()(package private) TransportImpl.ConnInfogetConnInfo()(package private) DecodergetDecoder()DisconnectListenergetDisconnectListener()(package private) EncodergetEncoder()KeyAlgorithmgetHostKeyAlgorithm()java.lang.StringgetRemoteHost()intgetRemotePort()java.net.InetSocketAddressgetRemoteSocketAddress()Get Remote Socket Address using Connection Information(package private) java.lang.StringgetServerID()java.lang.StringgetServerVersion()Returns the version string as sent by the SSH server for identification purposes, e.g.ServicegetService()byte[]getSessionID()intgetTimeoutMs()(package private) java.util.concurrent.locks.ReentrantLockgetWriteLock()private voidgotDebug(SSHPacket buf)private voidgotDisconnect(SSHPacket buf)private voidgotServiceAccept()private voidgotUnimplemented(SSHPacket packet)Got an SSH_MSG_UNIMPLEMENTED, so lets see where we're at and act accordingly.voidhandle(Message msg, SSHPacket buf)This is where all incoming packets are handled.voidinit(java.lang.String remoteHost, int remotePort, java.io.InputStream in, java.io.OutputStream out)Sets the host information and the streams to be used by this transport.booleanisAuthenticated()booleanisKexDone()private static booleanisKexerPacket(Message msg)booleanisRunning()voidjoin()Joins the thread calling this method to the transport's death.voidjoin(int timeout, java.util.concurrent.TimeUnit unit)Joins the thread calling this method to the transport's death.voidnotifyDisconnect(DisconnectReason reason, java.lang.String message)TransportImpl implements its own default DisconnectListener.private java.lang.StringreadIdentification(Buffer.PlainBuffer buffer)Reads the identification string from the SSH server.private voidreceiveServerIdent()voidreqService(Service service)Request a SSH service represented by aServiceinstance.private voidsendClientIdent()Receive the server identification string.private voidsendDisconnect(DisconnectReason reason, java.lang.String message)private voidsendServiceRequest(java.lang.String serviceName)Sends a service request for the specified servicelongsendUnimplemented()Sends SSH_MSG_UNIMPLEMENTED in response to the last packet received.voidsetAuthenticated()Informs this transport that authentication has been completed.voidsetDisconnectListener(DisconnectListener listener)Specify alistenerthat will be notified upon disconnection.voidsetHostKeyAlgorithm(KeyAlgorithm keyAlgorithm)voidsetService(Service service)Sets the currently activeService.voidsetTimeoutMs(int timeoutMs)Set a timeout for methods that may block.longwrite(SSHPacket payload)Write a packet over this transport.
-
-
-
Field Detail
-
loggerFactory
private final LoggerFactory loggerFactory
-
log
private final org.slf4j.Logger log
-
nullService
private final Service nullService
-
config
private final Config config
-
kexer
private final KeyExchanger kexer
-
reader
private final Reader reader
-
encoder
private final Encoder encoder
-
decoder
private final Decoder decoder
-
hostKeyAlgorithm
private KeyAlgorithm hostKeyAlgorithm
-
serviceAccept
private final Event<TransportException> serviceAccept
-
close
private final Event<TransportException> close
-
clientID
private final java.lang.String clientID
Client version identification string
-
timeoutMs
private volatile int timeoutMs
-
authed
private volatile boolean authed
-
service
private volatile Service service
Currently active service e.g. UserAuthService, ConnectionService
-
nextService
private volatile Service nextService
The next service that will be activated, only set when sending an SSH_MSG_SERVICE_REQUEST
-
disconnectListener
private DisconnectListener disconnectListener
-
connInfo
private TransportImpl.ConnInfo connInfo
-
serverID
private java.lang.String serverID
Server version identification string
-
msg
private Message msg
Message identifier of last packet received
-
writeLock
private final java.util.concurrent.locks.ReentrantLock writeLock
-
-
Constructor Detail
-
TransportImpl
public TransportImpl(Config config)
-
-
Method Detail
-
init
public void init(java.lang.String remoteHost, int remotePort, java.io.InputStream in, java.io.OutputStream out) throws TransportExceptionDescription copied from interface:TransportSets the host information and the streams to be used by this transport. Identification information is exchanged with the server. ATransportExceptionis thrown in case of SSH protocol version incompatibility.- Specified by:
initin interfaceTransport- Parameters:
remoteHost- server's hostnameremotePort- server's portin- input stream for the connectionout- output stream for the connection- Throws:
TransportException- if there is an error during exchange of identification information
-
getRemoteSocketAddress
public java.net.InetSocketAddress getRemoteSocketAddress()
Get Remote Socket Address using Connection Information- Specified by:
getRemoteSocketAddressin interfaceRemoteAddressProvider- Returns:
- Remote Socket Address or null when not connected
-
notifyDisconnect
public void notifyDisconnect(DisconnectReason reason, java.lang.String message)
TransportImpl implements its own default DisconnectListener.- Specified by:
notifyDisconnectin interfaceDisconnectListener
-
receiveServerIdent
private void receiveServerIdent() throws java.io.IOException- Throws:
java.io.IOException
-
sendClientIdent
private void sendClientIdent() throws java.io.IOExceptionReceive the server identification string.- Throws:
java.io.IOException- If there was an error writing to the outputstream.
-
readIdentification
private java.lang.String readIdentification(Buffer.PlainBuffer buffer) throws java.io.IOException
Reads the identification string from the SSH server. This is the very first string that is sent upon connection by the server. It takes the form of, e.g. "SSH-2.0-OpenSSH_ver". Several concerns are taken care of here, e.g. verifying protocol version, correct line endings as specified in RFC and such. This is not efficient but is only done once.- Parameters:
buffer- The buffer to read from.- Returns:
- empty string if full ident string has not yet been received
- Throws:
java.io.IOException- Thrown when protocol version is not supported
-
addHostKeyVerifier
public void addHostKeyVerifier(HostKeyVerifier hkv)
Description copied from interface:TransportAdds the specified verifier.- Specified by:
addHostKeyVerifierin interfaceTransport- Parameters:
hkv- the host key verifier
-
addAlgorithmsVerifier
public void addAlgorithmsVerifier(AlgorithmsVerifier verifier)
Description copied from interface:TransportAdds the specified verifier.- Specified by:
addAlgorithmsVerifierin interfaceTransport- Parameters:
verifier- The verifier to call with negotiated algorithms
-
doKex
public void doKex() throws TransportExceptionDescription copied from interface:TransportDo key exchange and algorithm negotiation. This can be the initial one or for algorithm renegotiation.- Specified by:
doKexin interfaceTransport- Throws:
TransportException- if there was an error during key exchange
-
isKexDone
public boolean isKexDone()
-
getTimeoutMs
public int getTimeoutMs()
- Specified by:
getTimeoutMsin interfaceTransport- Returns:
- the timeout that is currently set for blocking operations.
-
setTimeoutMs
public void setTimeoutMs(int timeoutMs)
Description copied from interface:TransportSet a timeout for methods that may block.- Specified by:
setTimeoutMsin interfaceTransport- Parameters:
timeoutMs- the timeout in milliseconds
-
getRemoteHost
public java.lang.String getRemoteHost()
- Specified by:
getRemoteHostin interfaceTransport- Returns:
- the hostname to which this transport is connected.
-
getRemotePort
public int getRemotePort()
- Specified by:
getRemotePortin interfaceTransport- Returns:
- the port number on the remote host to which this transport is connected.
-
getClientVersion
public java.lang.String getClientVersion()
- Specified by:
getClientVersionin interfaceTransport- Returns:
- the version string used by this client to identify itself to an SSH server, e.g. "SSHJ_3_0"
-
getConfig
public Config getConfig()
-
getServerVersion
public java.lang.String getServerVersion()
Description copied from interface:TransportReturns the version string as sent by the SSH server for identification purposes, e.g. "OpenSSH_$version". If the transport has not yet been initialized viaTransport.init(java.lang.String, int, java.io.InputStream, java.io.OutputStream), it will benull.- Specified by:
getServerVersionin interfaceTransport- Returns:
- server's version string (may be
null)
-
getSessionID
public byte[] getSessionID()
- Specified by:
getSessionIDin interfaceTransport- Returns:
- the session identifier assigned by server
-
getService
public Service getService()
- Specified by:
getServicein interfaceTransport- Returns:
- the currently active
Serviceinstance.
-
setService
public void setService(Service service)
Description copied from interface:TransportSets the currently activeService. Handling of non-transport-layer packets isdelegatedto that service. For this method to be successful, at least one service request viaTransport.reqService(net.schmizz.sshj.Service)must have been successful (not necessarily for the service being set).- Specified by:
setServicein interfaceTransport- Parameters:
service- (null-ok) theService
-
reqService
public void reqService(Service service) throws TransportException
Description copied from interface:TransportRequest a SSH service represented by aServiceinstance. A separate call toTransport.setService(net.schmizz.sshj.Service)is not needed.- Specified by:
reqServicein interfaceTransport- Parameters:
service- the SSH service to be requested- Throws:
TransportException- if the request failed for any reason
-
sendServiceRequest
private void sendServiceRequest(java.lang.String serviceName) throws TransportExceptionSends a service request for the specified service- Parameters:
serviceName- name of the service being requested- Throws:
TransportException- if there is an error while sending the request
-
setAuthenticated
public void setAuthenticated()
Description copied from interface:TransportInforms this transport that authentication has been completed. This method must be called after successful authentication, so that delayed compression may become effective if applicable.- Specified by:
setAuthenticatedin interfaceTransport
-
isAuthenticated
public boolean isAuthenticated()
- Specified by:
isAuthenticatedin interfaceTransport- Returns:
- whether the transport thinks it is authenticated.
-
sendUnimplemented
public long sendUnimplemented() throws TransportExceptionDescription copied from interface:TransportSends SSH_MSG_UNIMPLEMENTED in response to the last packet received.- Specified by:
sendUnimplementedin interfaceTransport- Returns:
- the sequence number of the packet sent
- Throws:
TransportException- if an error occurred sending the packet
-
join
public void join() throws TransportExceptionDescription copied from interface:TransportJoins the thread calling this method to the transport's death.- Specified by:
joinin interfaceTransport- Throws:
TransportException- if the transport dies of an exception
-
join
public void join(int timeout, java.util.concurrent.TimeUnit unit) throws TransportExceptionDescription copied from interface:TransportJoins the thread calling this method to the transport's death.- Specified by:
joinin interfaceTransport- Throws:
TransportException- if the transport dies of an exception
-
isRunning
public boolean isRunning()
- Specified by:
isRunningin interfaceTransport- Returns:
- whether this transport is active.
The transport is considered to be running if it has been initialized without error via
Transport.init(java.lang.String, int, java.io.InputStream, java.io.OutputStream)and has not been disconnected.
-
disconnect
public void disconnect()
Description copied from interface:TransportSend a disconnection packet with reason asDisconnectReason.BY_APPLICATION, and closes this transport.- Specified by:
disconnectin interfaceTransport
-
disconnect
public void disconnect(DisconnectReason reason)
Description copied from interface:TransportSend a disconnect packet with the givenreason, and closes this transport.- Specified by:
disconnectin interfaceTransport- Parameters:
reason- reason for disconnecting
-
disconnect
public void disconnect(DisconnectReason reason, java.lang.String message)
Description copied from interface:TransportSend a disconnect packet with the givenreasonandmessage, and closes this transport.- Specified by:
disconnectin interfaceTransport- Parameters:
reason- the reason code for this disconnectmessage- the text message
-
setDisconnectListener
public void setDisconnectListener(DisconnectListener listener)
Description copied from interface:TransportSpecify alistenerthat will be notified upon disconnection.- Specified by:
setDisconnectListenerin interfaceTransport- Parameters:
listener- Disconnect Listener to be configured
-
getDisconnectListener
public DisconnectListener getDisconnectListener()
- Specified by:
getDisconnectListenerin interfaceTransport- Returns:
- the current disconnect listener.
-
write
public long write(SSHPacket payload) throws TransportException
Description copied from interface:TransportWrite a packet over this transport. ThepayloadSSHPacketshould have 5 bytes free at the beginning to avoid a performance penalty associated with making space for header bytes (packet length, padding length).- Specified by:
writein interfaceTransport- Parameters:
payload- theSSHPacketcontaining data to send- Returns:
- sequence number of the sent packet
- Throws:
TransportException- if an error occurred sending the packet
-
sendDisconnect
private void sendDisconnect(DisconnectReason reason, java.lang.String message)
-
handle
public void handle(Message msg, SSHPacket buf) throws SSHException
This is where all incoming packets are handled. If they pertain to the transport layer, they are handled here; otherwise they are delegated to the active service instance if any viaSSHPacketHandler.handle(net.schmizz.sshj.common.Message, net.schmizz.sshj.common.SSHPacket). Even among the transport layer specific packets, key exchange packets are delegated toKeyExchanger.handle(net.schmizz.sshj.common.Message, net.schmizz.sshj.common.SSHPacket). This method is called in the context of thereaderthread viaDecoder.received(byte[], int)when a full packet has been decoded.- Specified by:
handlein interfaceSSHPacketHandler- Parameters:
msg- the message identifierbuf- buffer containing rest of the packet- Throws:
SSHException- if an error occurs during handling (unrecoverable)
-
isKexerPacket
private static boolean isKexerPacket(Message msg)
-
gotDebug
private void gotDebug(SSHPacket buf) throws TransportException
- Throws:
TransportException
-
gotDisconnect
private void gotDisconnect(SSHPacket buf) throws TransportException
- Throws:
TransportException
-
gotServiceAccept
private void gotServiceAccept() throws TransportException- Throws:
TransportException
-
gotUnimplemented
private void gotUnimplemented(SSHPacket packet) throws SSHException
Got an SSH_MSG_UNIMPLEMENTED, so lets see where we're at and act accordingly.- Parameters:
packet- The 'unimplemented' packet received- Throws:
TransportException- Thrown when key exchange is ongoingSSHException
-
finishOff
private void finishOff()
-
die
public void die(java.lang.Exception ex)
Description copied from interface:TransportKill the transport in an exceptional way.
-
getClientID
java.lang.String getClientID()
-
getServerID
java.lang.String getServerID()
-
getEncoder
Encoder getEncoder()
-
getDecoder
Decoder getDecoder()
-
getWriteLock
java.util.concurrent.locks.ReentrantLock getWriteLock()
-
getConnInfo
TransportImpl.ConnInfo getConnInfo()
-
setHostKeyAlgorithm
public void setHostKeyAlgorithm(KeyAlgorithm keyAlgorithm)
-
getHostKeyAlgorithm
public KeyAlgorithm getHostKeyAlgorithm()
- Specified by:
getHostKeyAlgorithmin interfaceTransport
-
getClientKeyAlgorithms
public java.util.List<KeyAlgorithm> getClientKeyAlgorithms(KeyType keyType) throws TransportException
- Specified by:
getClientKeyAlgorithmsin interfaceTransport- Throws:
TransportException
-
-