| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345 |
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- using Renci.SshNet.Abstractions;
- using Renci.SshNet.Common;
- using Renci.SshNet.Messages.Connection;
- namespace Renci.SshNet.Channels
- {
- /// <summary>
- /// Implements "direct-tcpip" SSH channel.
- /// </summary>
- internal class ChannelDirectTcpip : ClientChannel, IChannelDirectTcpip
- {
- private readonly object _socketLock = new object();
- private EventWaitHandle _channelOpen = new AutoResetEvent(false);
- private EventWaitHandle _channelData = new AutoResetEvent(false);
- private IForwardedPort _forwardedPort;
- private Socket _socket;
- /// <summary>
- /// Initializes a new <see cref="ChannelDirectTcpip"/> instance.
- /// </summary>
- /// <param name="session">The session.</param>
- /// <param name="localChannelNumber">The local channel number.</param>
- /// <param name="localWindowSize">Size of the window.</param>
- /// <param name="localPacketSize">Size of the packet.</param>
- public ChannelDirectTcpip(ISession session, uint localChannelNumber, uint localWindowSize, uint localPacketSize)
- : base(session, localChannelNumber, localWindowSize, localPacketSize)
- {
- }
- /// <summary>
- /// Gets the type of the channel.
- /// </summary>
- /// <value>
- /// The type of the channel.
- /// </value>
- public override ChannelTypes ChannelType
- {
- get { return ChannelTypes.DirectTcpip; }
- }
- public void Open(string remoteHost, uint port, IForwardedPort forwardedPort, Socket socket)
- {
- if (IsOpen)
- throw new SshException("Channel is already open.");
- if (!IsConnected)
- throw new SshException("Session is not connected.");
- _socket = socket;
- _forwardedPort = forwardedPort;
- _forwardedPort.Closing += ForwardedPort_Closing;
- var ep = (IPEndPoint) socket.RemoteEndPoint;
- #if DEBUG_GERT
- Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelOpenMessage send '" + LocalChannelNumber + "' | " + DateTime.Now.ToString("hh:mm:ss.fff"));
- #endif // DEBUG_GERT
- // open channel
- SendMessage(new ChannelOpenMessage(LocalChannelNumber, LocalWindowSize, LocalPacketSize,
- new DirectTcpipChannelInfo(remoteHost, port, ep.Address.ToString(), (uint) ep.Port)));
- #if DEBUG_GERT
- Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelOpenMessage sent '" + LocalChannelNumber + "' | " + DateTime.Now.ToString("hh:mm:ss.fff"));
- #endif // DEBUG_GERT
- // Wait for channel to open
- WaitOnHandle(_channelOpen);
- #if DEBUG_GERT
- Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelOpenMessage flagged '" + LocalChannelNumber + "' | " + DateTime.Now.ToString("hh:mm:ss.fff"));
- #endif // DEBUG_GERT
- }
- /// <summary>
- /// Occurs as the forwarded port is being stopped.
- /// </summary>
- private void ForwardedPort_Closing(object sender, EventArgs eventArgs)
- {
- // signal to the client that we will not send anything anymore; this will also interrupt the
- // blocking receive in Bind if the client sends FIN/ACK in time
- //
- // if the FIN/ACK is not sent in time, the socket will be closed in Close(bool)
- ShutdownSocket(SocketShutdown.Send);
- }
- /// <summary>
- /// Binds channel to remote host.
- /// </summary>
- public void Bind()
- {
- // Cannot bind if channel is not open
- if (!IsOpen)
- return;
- var buffer = new byte[RemotePacketSize];
- SocketAbstraction.ReadContinuous(_socket, buffer, 0, buffer.Length, SendData);
- #if DEBUG_GERT
- Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelDirectTcpip.Bind (after) '" + LocalChannelNumber + "' | " + DateTime.Now.ToString("hh:mm:ss.fff"));
- #endif // DEBUG_GERT
- // even though the client has disconnected, we still want to properly close the
- // channel
- //
- // we'll do this in in Close(bool) that way we have a single place from which we
- // send an SSH_MSG_CHANNEL_EOF message and wait for the SSH_MSG_CHANNEL_CLOSE
- // message
- }
- /// <summary>
- /// Closes the socket, hereby interrupting the blocking receive in <see cref="Bind()"/>.
- /// </summary>
- private void CloseSocket()
- {
- if (_socket == null)
- return;
- lock (_socketLock)
- {
- if (_socket == null)
- return;
- #if DEBUG_GERT
- Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelDirectTcpip.CloseSocket '" + LocalChannelNumber + "' | " + DateTime.Now.ToString("hh:mm:ss.fff"));
- #endif // DEBUG_GERT
- // closing a socket actually disposes the socket, so we can safely dereference
- // the field to avoid entering the lock again later
- _socket.Dispose();
- _socket = null;
- }
- }
- /// <summary>
- /// Shuts down the socket.
- /// </summary>
- /// <param name="how">One of the <see cref="SocketShutdown"/> values that specifies the operation that will no longer be allowed.</param>
- private void ShutdownSocket(SocketShutdown how)
- {
- if (_socket == null)
- return;
- lock (_socketLock)
- {
- #if DEBUG_GERT
- Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelDirectTcpip.ShutdownSocket '" + LocalChannelNumber + "' | " + DateTime.Now.ToString("hh:mm:ss.fff"));
- #endif // DEBUG_GERT
- if (_socket == null || !_socket.Connected)
- return;
- _socket.Shutdown(how);
- }
- }
- /// <summary>
- /// Closes the channel, optionally waiting for the SSH_MSG_CHANNEL_CLOSE message to
- /// be received from the server.
- /// </summary>
- /// <param name="wait"><c>true</c> to wait for the SSH_MSG_CHANNEL_CLOSE message to be received from the server; otherwise, <c>false</c>.</param>
- protected override void Close(bool wait)
- {
- #if DEBUG_GERT
- Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelDirectTcpip.Close(bool) '" + LocalChannelNumber + "' | " + DateTime.Now.ToString("hh:mm:ss.fff"));
- #endif // DEBUG_GERT
- var forwardedPort = _forwardedPort;
- if (forwardedPort != null)
- {
- forwardedPort.Closing -= ForwardedPort_Closing;
- _forwardedPort = null;
- }
- // signal to the client that we will not send anything anymore; this will also interrupt the
- // blocking receive in Bind if the client sends FIN/ACK in time
- //
- // if the FIN/ACK is not sent in time, the socket will be closed after the channel is closed
- ShutdownSocket(SocketShutdown.Send);
- // close the SSH channel, and mark the channel closed
- base.Close(wait);
- // close the socket
- CloseSocket();
- }
- /// <summary>
- /// Called when channel data is received.
- /// </summary>
- /// <param name="data">The data.</param>
- protected override void OnData(byte[] data)
- {
- base.OnData(data);
- if (_socket != null && _socket.Connected)
- {
- lock (_socketLock)
- {
- if (_socket != null && _socket.Connected)
- {
- SocketAbstraction.Send(_socket, data, 0, data.Length);
- }
- }
- }
- }
- /// <summary>
- /// Called when channel is opened by the server.
- /// </summary>
- /// <param name="remoteChannelNumber">The remote channel number.</param>
- /// <param name="initialWindowSize">Initial size of the window.</param>
- /// <param name="maximumPacketSize">Maximum size of the packet.</param>
- protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initialWindowSize, uint maximumPacketSize)
- {
- base.OnOpenConfirmation(remoteChannelNumber, initialWindowSize, maximumPacketSize);
- _channelOpen.Set();
- #if DEBUG_GERT
- Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelOpenMessage confirmed '" + LocalChannelNumber + "' | " + DateTime.Now.ToString("hh:mm:ss.fff"));
- #endif // DEBUG_GERT
- }
- protected override void OnOpenFailure(uint reasonCode, string description, string language)
- {
- base.OnOpenFailure(reasonCode, description, language);
- _channelOpen.Set();
- #if DEBUG_GERT
- Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelOpenMessage failure '" + LocalChannelNumber + "' | " + DateTime.Now.ToString("hh:mm:ss.fff"));
- #endif // DEBUG_GERT
- }
- /// <summary>
- /// Called when channel has no more data to receive.
- /// </summary>
- protected override void OnEof()
- {
- base.OnEof();
- #if DEBUG_GERT
- Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelDirectTcpip.OnEof '" + LocalChannelNumber + "' | " +
- DateTime.Now.ToString("hh:mm:ss"));
- #endif // DEBUG_GERT
- // the channel will send no more data, and hence it does not make sense to receive
- // any more data from the client to send to the remote party (and we surely won't
- // send anything anymore)
- //
- // this will also interrupt the blocking receive in Bind()
- ShutdownSocket(SocketShutdown.Send);
- }
- /// <summary>
- /// Called whenever an unhandled <see cref="Exception"/> occurs in <see cref="Session"/> causing
- /// the message loop to be interrupted, or when an exception occurred processing a channel message.
- /// </summary>
- protected override void OnErrorOccured(Exception exp)
- {
- base.OnErrorOccured(exp);
- #if DEBUG_GERT
- Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelDirectTcpip.OnErrorOccured '" + LocalChannelNumber + "' | " + DateTime.Now.ToString("hh:mm:ss"));
- #endif // DEBUG_GERT
- // signal to the client that we will not send anything anymore; this will also interrupt the
- // blocking receive in Bind if the client sends FIN/ACK in time
- //
- // if the FIN/ACK is not sent in time, the socket will be closed in Close(bool)
- ShutdownSocket(SocketShutdown.Send);
- }
- /// <summary>
- /// Called when the server wants to terminate the connection immmediately.
- /// </summary>
- /// <remarks>
- /// The sender MUST NOT send or receive any data after this message, and
- /// the recipient MUST NOT accept any data after receiving this message.
- /// </remarks>
- protected override void OnDisconnected()
- {
- base.OnDisconnected();
- #if DEBUG_GERT
- Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelDirectTcpip.OnDisconnected '" + LocalChannelNumber + "' | " + DateTime.Now.ToString("hh:mm:ss"));
- #endif // DEBUG_GERT
- // the channel will accept or send no more data, and hence it does not make sense
- // to accept any more data from the client (and we surely won't send anything
- // anymore)
- //
- //
- // so lets signal to the client that we will not send or receive anything anymore
- // this will also interrupt the blocking receive in Bind()
- ShutdownSocket(SocketShutdown.Both);
- }
- protected override void Dispose(bool disposing)
- {
- // make sure we've unsubscribed from all session events and closed the channel
- // before we starting disposing
- base.Dispose(disposing);
- if (disposing)
- {
- #if DEBUG_GERT
- Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | Dispose '" + LocalChannelNumber + "' | " + DateTime.Now.ToString("hh:mm:ss"));
- #endif // DEBUG_GERT
- if (_socket != null)
- {
- lock (_socketLock)
- {
- if (_socket != null)
- {
- _socket.Dispose();
- _socket = null;
- }
- }
- }
- var channelOpen = _channelOpen;
- if (channelOpen != null)
- {
- channelOpen.Dispose();
- _channelOpen = null;
- }
- var channelData = _channelData;
- if (channelData != null)
- {
- channelData.Dispose();
- _channelData = null;
- }
- }
- }
- }
- }
|