ChannelDirectTcpip.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 "direct-tcpip" SSH channel.
  12. /// </summary>
  13. internal partial class ChannelDirectTcpip : ClientChannel, IChannelDirectTcpip
  14. {
  15. private readonly object _socketLock = new object();
  16. private EventWaitHandle _channelOpen = new AutoResetEvent(false);
  17. private EventWaitHandle _channelData = new AutoResetEvent(false);
  18. private IForwardedPort _forwardedPort;
  19. private Socket _socket;
  20. /// <summary>
  21. /// Initializes a new <see cref="ChannelDirectTcpip"/> instance.
  22. /// </summary>
  23. /// <param name="session">The session.</param>
  24. /// <param name="localChannelNumber">The local channel number.</param>
  25. /// <param name="localWindowSize">Size of the window.</param>
  26. /// <param name="localPacketSize">Size of the packet.</param>
  27. public ChannelDirectTcpip(ISession session, uint localChannelNumber, uint localWindowSize, uint localPacketSize)
  28. : base(session, localChannelNumber, localWindowSize, localPacketSize)
  29. {
  30. }
  31. /// <summary>
  32. /// Gets the type of the channel.
  33. /// </summary>
  34. /// <value>
  35. /// The type of the channel.
  36. /// </value>
  37. public override ChannelTypes ChannelType
  38. {
  39. get { return ChannelTypes.DirectTcpip; }
  40. }
  41. public void Open(string remoteHost, uint port, IForwardedPort forwardedPort, Socket socket)
  42. {
  43. if (IsOpen)
  44. throw new SshException("Channel is already open.");
  45. if (!IsConnected)
  46. throw new SshException("Session is not connected.");
  47. _socket = socket;
  48. _forwardedPort = forwardedPort;
  49. _forwardedPort.Closing += ForwardedPort_Closing;
  50. var ep = socket.RemoteEndPoint as IPEndPoint;
  51. // open channel
  52. SendMessage(new ChannelOpenMessage(LocalChannelNumber, LocalWindowSize, LocalPacketSize,
  53. new DirectTcpipChannelInfo(remoteHost, port, ep.Address.ToString(), (uint) ep.Port)));
  54. // Wait for channel to open
  55. WaitOnHandle(_channelOpen);
  56. }
  57. /// <summary>
  58. /// Occurs as the forwarded port is being stopped.
  59. /// </summary>
  60. private void ForwardedPort_Closing(object sender, EventArgs eventArgs)
  61. {
  62. // signal to the client that we will not send anything anymore; this will also interrupt the
  63. // blocking receive in Bind if the client sends FIN/ACK in time
  64. //
  65. // if the FIN/ACK is not sent in time, the socket will be closed in Close(bool)
  66. ShutdownSocket(SocketShutdown.Send);
  67. }
  68. /// <summary>
  69. /// Binds channel to remote host.
  70. /// </summary>
  71. public void Bind()
  72. {
  73. // Cannot bind if channel is not open
  74. if (!IsOpen)
  75. return;
  76. var buffer = new byte[RemotePacketSize];
  77. while (_socket != null && _socket.Connected)
  78. {
  79. try
  80. {
  81. var read = SocketAbstraction.Read(_socket, buffer, 0, buffer.Length, ConnectionInfo.Timeout);
  82. if (read > 0)
  83. {
  84. #if TUNING
  85. SendData(buffer, 0, read);
  86. #else
  87. SendMessage(new ChannelDataMessage(RemoteChannelNumber, buffer.Take(read).ToArray()));
  88. #endif
  89. }
  90. else
  91. {
  92. // client shut down the socket (but the server may still send data or an EOF)
  93. break;
  94. }
  95. }
  96. catch (SocketException exp)
  97. {
  98. switch (exp.SocketErrorCode)
  99. {
  100. case SocketError.WouldBlock:
  101. case SocketError.IOPending:
  102. case SocketError.NoBufferSpaceAvailable:
  103. // socket buffer is probably empty, wait and try again
  104. ThreadAbstraction.Sleep(30);
  105. break;
  106. case SocketError.ConnectionAborted:
  107. case SocketError.ConnectionReset:
  108. // connection was closed after receiving SSH_MSG_CHANNEL_CLOSE message
  109. break;
  110. case SocketError.Interrupted:
  111. // connection was closed because FIN/ACK was not received in time after
  112. // shutting down the (send part of the) socket
  113. break;
  114. default:
  115. throw; // throw any other error
  116. }
  117. }
  118. }
  119. // even though the client has disconnected, we still want to properly close the
  120. // channel
  121. //
  122. // we'll do this in in Close(bool) that way we have a single place from which we
  123. // send an SSH_MSG_CHANNEL_EOF message and wait for the SSH_MSG_CHANNEL_CLOSE
  124. // message
  125. }
  126. /// <summary>
  127. /// Closes the socket, hereby interrupting the blocking receive in <see cref="Bind()"/>.
  128. /// </summary>
  129. private void CloseSocket()
  130. {
  131. if (_socket == null)
  132. return;
  133. lock (_socketLock)
  134. {
  135. if (_socket == null)
  136. return;
  137. // closing a socket actually disposes the socket, so we can safely dereference
  138. // the field to avoid entering the lock again later
  139. _socket.Dispose();
  140. _socket = null;
  141. }
  142. }
  143. /// <summary>
  144. /// Shuts down the socket.
  145. /// </summary>
  146. /// <param name="how">One of the <see cref="SocketShutdown"/> values that specifies the operation that will no longer be allowed.</param>
  147. private void ShutdownSocket(SocketShutdown how)
  148. {
  149. if (_socket == null)
  150. return;
  151. lock (_socketLock)
  152. {
  153. if (_socket == null || !_socket.Connected)
  154. return;
  155. _socket.Shutdown(how);
  156. }
  157. }
  158. /// <summary>
  159. /// Closes the channel, optionally waiting for the SSH_MSG_CHANNEL_CLOSE message to
  160. /// be received from the server.
  161. /// </summary>
  162. /// <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>
  163. protected override void Close(bool wait)
  164. {
  165. if (_forwardedPort != null)
  166. {
  167. _forwardedPort.Closing -= ForwardedPort_Closing;
  168. _forwardedPort = null;
  169. }
  170. // signal to the client that we will not send anything anymore; this will also interrupt the
  171. // blocking receive in Bind if the client sends FIN/ACK in time
  172. //
  173. // if the FIN/ACK is not sent in time, the socket will be closed after the channel is closed
  174. ShutdownSocket(SocketShutdown.Send);
  175. // close the SSH channel, and mark the channel closed
  176. base.Close(wait);
  177. // close the socket
  178. CloseSocket();
  179. }
  180. /// <summary>
  181. /// Called when channel data is received.
  182. /// </summary>
  183. /// <param name="data">The data.</param>
  184. protected override void OnData(byte[] data)
  185. {
  186. base.OnData(data);
  187. if (_socket != null && _socket.Connected)
  188. {
  189. lock (_socketLock)
  190. {
  191. if (_socket != null && _socket.Connected)
  192. {
  193. SocketAbstraction.Send(_socket, data, 0, data.Length);
  194. }
  195. }
  196. }
  197. }
  198. /// <summary>
  199. /// Called when channel is opened by the server.
  200. /// </summary>
  201. /// <param name="remoteChannelNumber">The remote channel number.</param>
  202. /// <param name="initialWindowSize">Initial size of the window.</param>
  203. /// <param name="maximumPacketSize">Maximum size of the packet.</param>
  204. protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initialWindowSize, uint maximumPacketSize)
  205. {
  206. base.OnOpenConfirmation(remoteChannelNumber, initialWindowSize, maximumPacketSize);
  207. _channelOpen.Set();
  208. }
  209. protected override void OnOpenFailure(uint reasonCode, string description, string language)
  210. {
  211. base.OnOpenFailure(reasonCode, description, language);
  212. _channelOpen.Set();
  213. }
  214. /// <summary>
  215. /// Called when channel has no more data to receive.
  216. /// </summary>
  217. protected override void OnEof()
  218. {
  219. base.OnEof();
  220. // the channel will send no more data, and hence it does not make sense to receive
  221. // any more data from the client to send to the remote party (and we surely won't
  222. // send anything anymore)
  223. //
  224. // this will also interrupt the blocking receive in Bind()
  225. ShutdownSocket(SocketShutdown.Send);
  226. }
  227. /// <summary>
  228. /// Called whenever an unhandled <see cref="Exception"/> occurs in <see cref="Session"/> causing
  229. /// the message loop to be interrupted, or when an exception occurred processing a channel message.
  230. /// </summary>
  231. protected override void OnErrorOccured(Exception exp)
  232. {
  233. base.OnErrorOccured(exp);
  234. // signal to the client that we will not send anything anymore; this will also interrupt the
  235. // blocking receive in Bind if the client sends FIN/ACK in time
  236. //
  237. // if the FIN/ACK is not sent in time, the socket will be closed in Close(bool)
  238. ShutdownSocket(SocketShutdown.Send);
  239. }
  240. /// <summary>
  241. /// Called when the server wants to terminate the connection immmediately.
  242. /// </summary>
  243. /// <remarks>
  244. /// The sender MUST NOT send or receive any data after this message, and
  245. /// the recipient MUST NOT accept any data after receiving this message.
  246. /// </remarks>
  247. protected override void OnDisconnected()
  248. {
  249. base.OnDisconnected();
  250. // the channel will accept or send no more data, and hence it does not make sense
  251. // to accept any more data from the client (and we surely won't send anything
  252. // anymore)
  253. //
  254. //
  255. // so lets signal to the client that we will not send or receive anything anymore
  256. // this will also interrupt the blocking receive in Bind()
  257. ShutdownSocket(SocketShutdown.Both);
  258. }
  259. protected override void Dispose(bool disposing)
  260. {
  261. // make sure we've unsubscribed from all session events and closed the channel
  262. // before we starting disposing
  263. base.Dispose(disposing);
  264. if (disposing)
  265. {
  266. if (_socket != null)
  267. {
  268. lock (_socketLock)
  269. {
  270. if (_socket != null)
  271. {
  272. _socket.Dispose();
  273. _socket = null;
  274. }
  275. }
  276. }
  277. if (_channelOpen != null)
  278. {
  279. _channelOpen.Dispose();
  280. _channelOpen = null;
  281. }
  282. if (_channelData != null)
  283. {
  284. _channelData.Dispose();
  285. _channelData = null;
  286. }
  287. }
  288. }
  289. }
  290. }