ChannelForwardedTcpip.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. using System;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Threading;
  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 partial class ChannelForwardedTcpip : ServerChannel, IChannelForwardedTcpip
  14. {
  15. private readonly object _socketShutdownAndCloseLock = new object();
  16. private Socket _socket;
  17. /// <summary>
  18. /// Holds a value indicating whether the SSH_MSG_CHANNEL_EOF has been sent to the client.
  19. /// </summary>
  20. /// <value>
  21. /// <c>0</c> when the SSH_MSG_CHANNEL_EOF message has not been sent to the client, and
  22. /// <c>1</c> when this message was already sent.
  23. /// </value>
  24. private int _sentEof;
  25. private IForwardedPort _forwardedPort;
  26. /// <summary>
  27. /// Gets the type of the channel.
  28. /// </summary>
  29. /// <value>
  30. /// The type of the channel.
  31. /// </value>
  32. public override ChannelTypes ChannelType
  33. {
  34. get { return ChannelTypes.ForwardedTcpip; }
  35. }
  36. /// <summary>
  37. /// Binds the channel to the specified endpoint.
  38. /// </summary>
  39. /// <param name="remoteEndpoint">The endpoint to connect to.</param>
  40. /// <param name="forwardedPort">The forwarded port for which the channel is opened.</param>
  41. public void Bind(IPEndPoint remoteEndpoint, IForwardedPort forwardedPort)
  42. {
  43. byte[] buffer;
  44. if (!IsConnected)
  45. {
  46. throw new SshException("Session is not connected.");
  47. }
  48. _forwardedPort = forwardedPort;
  49. _forwardedPort.Closing += ForwardedPort_Closing;
  50. // Try to connect to the socket
  51. try
  52. {
  53. // Get buffer in memory for data exchange
  54. buffer = new byte[RemotePacketSize];
  55. OpenSocket(remoteEndpoint);
  56. // send channel open confirmation message
  57. SendMessage(new ChannelOpenConfirmationMessage(RemoteChannelNumber, LocalWindowSize, LocalPacketSize, LocalChannelNumber));
  58. }
  59. catch (Exception exp)
  60. {
  61. // send channel open failure message
  62. SendMessage(new ChannelOpenFailureMessage(RemoteChannelNumber, exp.ToString(), 2));
  63. throw;
  64. }
  65. // Start reading data from the port and send to channel
  66. while (_socket != null && _socket.Connected)
  67. {
  68. try
  69. {
  70. var read = 0;
  71. InternalSocketReceive(buffer, ref read);
  72. if (read > 0)
  73. {
  74. SendMessage(new ChannelDataMessage(RemoteChannelNumber, buffer.Take(read).ToArray()));
  75. }
  76. else
  77. {
  78. // server quit sending
  79. break;
  80. }
  81. }
  82. catch (SocketException exp)
  83. {
  84. if (exp.SocketErrorCode == SocketError.WouldBlock ||
  85. exp.SocketErrorCode == SocketError.IOPending ||
  86. exp.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
  87. {
  88. // socket buffer is probably empty, wait and try again
  89. Thread.Sleep(30);
  90. }
  91. else if (exp.SocketErrorCode == SocketError.ConnectionAborted || exp.SocketErrorCode == SocketError.Interrupted)
  92. {
  93. break;
  94. }
  95. else
  96. throw; // throw any other error
  97. }
  98. }
  99. }
  100. protected override void OnErrorOccured(Exception exp)
  101. {
  102. base.OnErrorOccured(exp);
  103. // close the socket, hereby interrupting the blocking receive in Bind(IPEndPoint,IForwardedPort)
  104. CloseSocket();
  105. }
  106. /// <summary>
  107. /// Occurs as the forwarded port is being stopped.
  108. /// </summary>
  109. private void ForwardedPort_Closing(object sender, EventArgs eventArgs)
  110. {
  111. // close the socket, hereby interrupting the blocking receive in Bind(IPEndPoint,IForwardedPort)
  112. CloseSocket();
  113. }
  114. partial void OpenSocket(IPEndPoint remoteEndpoint);
  115. /// <summary>
  116. /// Closes the socket, hereby interrupting the blocking receive in <see cref="Bind(IPEndPoint,IForwardedPort)"/>.
  117. /// </summary>
  118. private void CloseSocket()
  119. {
  120. if (_socket == null || !_socket.Connected)
  121. return;
  122. lock (_socketShutdownAndCloseLock)
  123. {
  124. if (_socket == null || !_socket.Connected)
  125. return;
  126. _socket.Shutdown(SocketShutdown.Both);
  127. _socket.Close();
  128. }
  129. }
  130. /// <summary>
  131. /// Closes the channel, optionally waiting for the SSH_MSG_CHANNEL_CLOSE message to
  132. /// be received from the server.
  133. /// </summary>
  134. /// <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>
  135. protected override void Close(bool wait)
  136. {
  137. if (_forwardedPort != null)
  138. {
  139. _forwardedPort.Closing -= ForwardedPort_Closing;
  140. _forwardedPort = null;
  141. }
  142. // close the socket, hereby interrupting the blocking receive in Bind()
  143. CloseSocket();
  144. // send EOF message first when channel need to be closed
  145. if (IsOpen && Interlocked.CompareExchange(ref _sentEof, 1, 0) == 0)
  146. {
  147. SendEof();
  148. }
  149. base.Close(wait);
  150. }
  151. /// <summary>
  152. /// Called when channel data is received.
  153. /// </summary>
  154. /// <param name="data">The data.</param>
  155. protected override void OnData(byte[] data)
  156. {
  157. base.OnData(data);
  158. if (_socket != null && _socket.Connected)
  159. InternalSocketSend(data);
  160. }
  161. partial void InternalSocketSend(byte[] data);
  162. partial void InternalSocketReceive(byte[] buffer, ref int read);
  163. /// <summary>
  164. /// Releases unmanaged and - optionally - managed resources
  165. /// </summary>
  166. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  167. protected override void Dispose(bool disposing)
  168. {
  169. if (_forwardedPort != null)
  170. {
  171. _forwardedPort.Closing -= ForwardedPort_Closing;
  172. _forwardedPort = null;
  173. }
  174. if (_socket != null)
  175. {
  176. _socket.Dispose();
  177. _socket = null;
  178. }
  179. base.Dispose(disposing);
  180. }
  181. }
  182. }