ChannelDirectTcpip.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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 "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 = 0;
  82. InternalSocketReceive(buffer, ref read);
  83. if (read > 0)
  84. {
  85. #if TUNING
  86. SendData(buffer, 0, read);
  87. #else
  88. SendMessage(new ChannelDataMessage(RemoteChannelNumber, buffer.Take(read).ToArray()));
  89. #endif
  90. }
  91. else
  92. {
  93. // client shut down the socket (but the server may still send data or an EOF)
  94. break;
  95. }
  96. }
  97. catch (SocketException exp)
  98. {
  99. switch (exp.SocketErrorCode)
  100. {
  101. case SocketError.WouldBlock:
  102. case SocketError.IOPending:
  103. case SocketError.NoBufferSpaceAvailable:
  104. // socket buffer is probably empty, wait and try again
  105. Thread.Sleep(30);
  106. break;
  107. case SocketError.ConnectionAborted:
  108. case SocketError.ConnectionReset:
  109. // connection was closed after receiving SSH_MSG_CHANNEL_CLOSE message
  110. break;
  111. case SocketError.Interrupted:
  112. // connection was closed because FIN/ACK was not received in time after
  113. // shutting down the (send part of the) socket
  114. break;
  115. default:
  116. throw; // throw any other error
  117. }
  118. }
  119. }
  120. // even though the client has disconnected, we still want to properly close the
  121. // channel
  122. //
  123. // we'll do this in in Close(bool) that way we have a single place from which we
  124. // send an SSH_MSG_CHANNEL_EOF message and wait for the SSH_MSG_CHANNEL_CLOSE
  125. // message
  126. }
  127. /// <summary>
  128. /// Closes the socket, hereby interrupting the blocking receive in <see cref="Bind()"/>.
  129. /// </summary>
  130. private void CloseSocket()
  131. {
  132. if (_socket == null)
  133. return;
  134. lock (_socketLock)
  135. {
  136. if (_socket == null)
  137. return;
  138. // closing a socket actually disposes the socket, so we can safely dereference
  139. // the field to avoid entering the lock again later
  140. _socket.Close();
  141. _socket = null;
  142. }
  143. }
  144. /// <summary>
  145. /// Shuts down the socket.
  146. /// </summary>
  147. /// <param name="how">One of the <see cref="SocketShutdown"/> values that specifies the operation that will no longer be allowed.</param>
  148. private void ShutdownSocket(SocketShutdown how)
  149. {
  150. if (_socket == null)
  151. return;
  152. lock (_socketLock)
  153. {
  154. if (_socket == null || !_socket.Connected)
  155. return;
  156. _socket.Shutdown(how);
  157. }
  158. }
  159. /// <summary>
  160. /// Closes the channel, optionally waiting for the SSH_MSG_CHANNEL_CLOSE message to
  161. /// be received from the server.
  162. /// </summary>
  163. /// <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>
  164. protected override void Close(bool wait)
  165. {
  166. if (_forwardedPort != null)
  167. {
  168. _forwardedPort.Closing -= ForwardedPort_Closing;
  169. _forwardedPort = null;
  170. }
  171. // signal to the client that we will not send anything anymore; this will also interrupt the
  172. // blocking receive in Bind if the client sends FIN/ACK in time
  173. //
  174. // if the FIN/ACK is not sent in time, the socket will be closed after the channel is closed
  175. ShutdownSocket(SocketShutdown.Send);
  176. // close the SSH channel, and mark the channel closed
  177. base.Close(wait);
  178. // close the socket
  179. CloseSocket();
  180. }
  181. /// <summary>
  182. /// Called when channel data is received.
  183. /// </summary>
  184. /// <param name="data">The data.</param>
  185. protected override void OnData(byte[] data)
  186. {
  187. base.OnData(data);
  188. if (_socket != null && _socket.Connected)
  189. {
  190. lock (_socketLock)
  191. {
  192. if (_socket != null && _socket.Connected)
  193. {
  194. InternalSocketSend(data);
  195. }
  196. }
  197. }
  198. }
  199. /// <summary>
  200. /// Called when channel is opened by the server.
  201. /// </summary>
  202. /// <param name="remoteChannelNumber">The remote channel number.</param>
  203. /// <param name="initialWindowSize">Initial size of the window.</param>
  204. /// <param name="maximumPacketSize">Maximum size of the packet.</param>
  205. protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initialWindowSize, uint maximumPacketSize)
  206. {
  207. base.OnOpenConfirmation(remoteChannelNumber, initialWindowSize, maximumPacketSize);
  208. _channelOpen.Set();
  209. }
  210. protected override void OnOpenFailure(uint reasonCode, string description, string language)
  211. {
  212. base.OnOpenFailure(reasonCode, description, language);
  213. _channelOpen.Set();
  214. }
  215. /// <summary>
  216. /// Called when channel has no more data to receive.
  217. /// </summary>
  218. protected override void OnEof()
  219. {
  220. base.OnEof();
  221. // the channel will send no more data, and hence it does not make sense to receive
  222. // any more data from the client to send to the remote party (and we surely won't
  223. // send anything anymore)
  224. //
  225. // this will also interrupt the blocking receive in Bind()
  226. ShutdownSocket(SocketShutdown.Send);
  227. }
  228. /// <summary>
  229. /// Called whenever an unhandled <see cref="Exception"/> occurs in <see cref="Session"/> causing
  230. /// the message loop to be interrupted, or when an exception occurred processing a channel message.
  231. /// </summary>
  232. protected override void OnErrorOccured(Exception exp)
  233. {
  234. base.OnErrorOccured(exp);
  235. // signal to the client that we will not send anything anymore; this will also interrupt the
  236. // blocking receive in Bind if the client sends FIN/ACK in time
  237. //
  238. // if the FIN/ACK is not sent in time, the socket will be closed in Close(bool)
  239. ShutdownSocket(SocketShutdown.Send);
  240. }
  241. /// <summary>
  242. /// Called when the server wants to terminate the connection immmediately.
  243. /// </summary>
  244. /// <remarks>
  245. /// The sender MUST NOT send or receive any data after this message, and
  246. /// the recipient MUST NOT accept any data after receiving this message.
  247. /// </remarks>
  248. protected override void OnDisconnected()
  249. {
  250. base.OnDisconnected();
  251. // the channel will accept or send no more data, and hence it does not make sense
  252. // to accept any more data from the client (and we surely won't send anything
  253. // anymore)
  254. //
  255. //
  256. // so lets signal to the client that we will not send or receive anything anymore
  257. // this will also interrupt the blocking receive in Bind()
  258. ShutdownSocket(SocketShutdown.Both);
  259. }
  260. partial void InternalSocketReceive(byte[] buffer, ref int read);
  261. partial void InternalSocketSend(byte[] data);
  262. protected override void Dispose(bool disposing)
  263. {
  264. // make sure we've unsubscribed from all session events and closed the channel
  265. // before we starting disposing
  266. base.Dispose(disposing);
  267. if (disposing)
  268. {
  269. if (_socket != null)
  270. {
  271. lock (_socketLock)
  272. {
  273. if (_socket != null)
  274. {
  275. _socket.Dispose();
  276. _socket = null;
  277. }
  278. }
  279. }
  280. if (_channelOpen != null)
  281. {
  282. _channelOpen.Dispose();
  283. _channelOpen = null;
  284. }
  285. if (_channelData != null)
  286. {
  287. _channelData.Dispose();
  288. _channelData = null;
  289. }
  290. }
  291. }
  292. }
  293. }