ChannelForwardedTcpip.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Threading;
  5. using Renci.SshNet.Abstractions;
  6. using Renci.SshNet.Common;
  7. using Renci.SshNet.Messages.Connection;
  8. namespace Renci.SshNet.Channels
  9. {
  10. /// <summary>
  11. /// Implements "forwarded-tcpip" SSH channel.
  12. /// </summary>
  13. internal class ChannelForwardedTcpip : ServerChannel, IChannelForwardedTcpip
  14. {
  15. private readonly object _socketShutdownAndCloseLock = new object();
  16. private Socket _socket;
  17. private IForwardedPort _forwardedPort;
  18. /// <summary>
  19. /// Initializes a new <see cref="ChannelForwardedTcpip"/> instance.
  20. /// </summary>
  21. /// <param name="session">The session.</param>
  22. /// <param name="localChannelNumber">The local channel number.</param>
  23. /// <param name="localWindowSize">Size of the window.</param>
  24. /// <param name="localPacketSize">Size of the packet.</param>
  25. /// <param name="remoteChannelNumber">The remote channel number.</param>
  26. /// <param name="remoteWindowSize">The window size of the remote party.</param>
  27. /// <param name="remotePacketSize">The maximum size of a data packet that we can send to the remote party.</param>
  28. internal ChannelForwardedTcpip(ISession session, uint localChannelNumber, uint localWindowSize, uint localPacketSize, uint remoteChannelNumber, uint remoteWindowSize, uint remotePacketSize)
  29. : base(session, localChannelNumber, localWindowSize, localPacketSize, remoteChannelNumber, remoteWindowSize, remotePacketSize)
  30. {
  31. }
  32. /// <summary>
  33. /// Gets the type of the channel.
  34. /// </summary>
  35. /// <value>
  36. /// The type of the channel.
  37. /// </value>
  38. public override ChannelTypes ChannelType
  39. {
  40. get { return ChannelTypes.ForwardedTcpip; }
  41. }
  42. /// <summary>
  43. /// Binds the channel to the specified endpoint.
  44. /// </summary>
  45. /// <param name="remoteEndpoint">The endpoint to connect to.</param>
  46. /// <param name="forwardedPort">The forwarded port for which the channel is opened.</param>
  47. public void Bind(IPEndPoint remoteEndpoint, IForwardedPort forwardedPort)
  48. {
  49. if (!IsConnected)
  50. {
  51. throw new SshException("Session is not connected.");
  52. }
  53. _forwardedPort = forwardedPort;
  54. _forwardedPort.Closing += ForwardedPort_Closing;
  55. // Try to connect to the socket
  56. try
  57. {
  58. _socket = SocketAbstraction.Connect(remoteEndpoint, ConnectionInfo.Timeout);
  59. // send channel open confirmation message
  60. SendMessage(new ChannelOpenConfirmationMessage(RemoteChannelNumber, LocalWindowSize, LocalPacketSize, LocalChannelNumber));
  61. }
  62. catch (Exception exp)
  63. {
  64. // send channel open failure message
  65. SendMessage(new ChannelOpenFailureMessage(RemoteChannelNumber, exp.ToString(), ChannelOpenFailureMessage.ConnectFailed, "en"));
  66. throw;
  67. }
  68. var buffer = new byte[RemotePacketSize];
  69. SocketAbstraction.ReadContinuous(_socket, buffer, 0, buffer.Length, SendData);
  70. }
  71. protected override void OnErrorOccured(Exception exp)
  72. {
  73. base.OnErrorOccured(exp);
  74. // signal to the server that we will not send anything anymore; this will also interrupt the
  75. // blocking receive in Bind if the server sends FIN/ACK in time
  76. //
  77. // if the FIN/ACK is not sent in time, the socket will be closed in Close(bool)
  78. ShutdownSocket(SocketShutdown.Send);
  79. }
  80. /// <summary>
  81. /// Occurs as the forwarded port is being stopped.
  82. /// </summary>
  83. private void ForwardedPort_Closing(object sender, EventArgs eventArgs)
  84. {
  85. #if DEBUG_GERT
  86. Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelForwardedTcpip.ForwardedPort_Closing");
  87. #endif // DEBUG_GERT
  88. // signal to the server that we will not send anything anymore; this will also interrupt the
  89. // blocking receive in Bind if the server sends FIN/ACK in time
  90. //
  91. // if the FIN/ACK is not sent in time, the socket will be closed in Close(bool)
  92. ShutdownSocket(SocketShutdown.Send);
  93. }
  94. /// <summary>
  95. /// Shuts down the socket.
  96. /// </summary>
  97. /// <param name="how">One of the <see cref="SocketShutdown"/> values that specifies the operation that will no longer be allowed.</param>
  98. private void ShutdownSocket(SocketShutdown how)
  99. {
  100. #if DEBUG_GERT
  101. Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelForwardedTcpip.ShutdownSocket");
  102. #endif // DEBUG_GERT
  103. if (_socket == null || !_socket.Connected)
  104. return;
  105. lock (_socketShutdownAndCloseLock)
  106. {
  107. var socket = _socket;
  108. if (socket == null || !socket.Connected)
  109. return;
  110. socket.Shutdown(how);
  111. }
  112. }
  113. /// <summary>
  114. /// Closes the socket, hereby interrupting the blocking receive in <see cref="Bind(IPEndPoint,IForwardedPort)"/>.
  115. /// </summary>
  116. private void CloseSocket()
  117. {
  118. if (_socket == null)
  119. return;
  120. lock (_socketShutdownAndCloseLock)
  121. {
  122. #if DEBUG_GERT
  123. Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelForwardedTcpip.CloseSocket");
  124. #endif // DEBUG_GERT
  125. var socket = _socket;
  126. if (socket != null)
  127. {
  128. // closing a socket actually disposes the socket, so we can safely dereference
  129. // the field to avoid entering the lock again later
  130. socket.Dispose();
  131. _socket = null;
  132. }
  133. }
  134. }
  135. /// <summary>
  136. /// Closes the channel, optionally waiting for the SSH_MSG_CHANNEL_CLOSE message to
  137. /// be received from the server.
  138. /// </summary>
  139. /// <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>
  140. protected override void Close(bool wait)
  141. {
  142. #if DEBUG_GERT
  143. Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | ChannelForwardedTcpip.Close");
  144. #endif // DEBUG_GERT
  145. var forwardedPort = _forwardedPort;
  146. if (forwardedPort != null)
  147. {
  148. forwardedPort.Closing -= ForwardedPort_Closing;
  149. _forwardedPort = null;
  150. }
  151. // signal to the server that we will not send anything anymore; this will also interrupt the
  152. // blocking receive in Bind if the server sends FIN/ACK in time
  153. //
  154. // if the FIN/ACK is not sent in time, the socket will be closed after the channel is closed
  155. ShutdownSocket(SocketShutdown.Send);
  156. // close the SSH channel, and mark the channel closed
  157. base.Close(wait);
  158. // close the socket
  159. CloseSocket();
  160. }
  161. #if DEBUG_GERT
  162. protected override void OnClose()
  163. {
  164. base.OnClose();
  165. Console.WriteLine("ID: " + Thread.CurrentThread.ManagedThreadId + " | OnClose");
  166. }
  167. #endif // DEBUG_GERT
  168. /// <summary>
  169. /// Called when channel data is received.
  170. /// </summary>
  171. /// <param name="data">The data.</param>
  172. protected override void OnData(byte[] data)
  173. {
  174. base.OnData(data);
  175. var socket = _socket;
  176. if (socket != null && socket.Connected)
  177. {
  178. SocketAbstraction.Send(socket, data, 0, data.Length);
  179. }
  180. }
  181. }
  182. }