ChannelDirectTcpip.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 _socketShutdownAndCloseLock = new object();
  16. private EventWaitHandle _channelEof = new AutoResetEvent(false);
  17. private EventWaitHandle _channelOpen = new AutoResetEvent(false);
  18. private EventWaitHandle _channelData = new AutoResetEvent(false);
  19. /// <summary>
  20. /// An <see cref="EventWaitHandle"/> that is signaled when the blocking receive is cancelled because the
  21. /// forwarded port is closing.
  22. /// </summary>
  23. private EventWaitHandle _channelInterrupted = new ManualResetEvent(false);
  24. private IForwardedPort _forwardedPort;
  25. private Socket _socket;
  26. /// <summary>
  27. /// Holds a value indicating whether the SSH_MSG_CHANNEL_EOF has been sent to the server.
  28. /// </summary>
  29. /// <value>
  30. /// <c>0</c> when the SSH_MSG_CHANNEL_EOF message has not been sent to the server, and
  31. /// <c>1</c> when this message was already sent.
  32. /// </value>
  33. private int _sentEof;
  34. /// <summary>
  35. /// Gets the type of the channel.
  36. /// </summary>
  37. /// <value>
  38. /// The type of the channel.
  39. /// </value>
  40. public override ChannelTypes ChannelType
  41. {
  42. get { return ChannelTypes.DirectTcpip; }
  43. }
  44. public void Open(string remoteHost, uint port, IForwardedPort forwardedPort, Socket socket)
  45. {
  46. if (IsOpen)
  47. throw new SshException("Channel is already open.");
  48. if (!IsConnected)
  49. throw new SshException("Session is not connected.");
  50. _socket = socket;
  51. _forwardedPort = forwardedPort;
  52. _forwardedPort.Closing += ForwardedPort_Closing;
  53. _sentEof = 0;
  54. var ep = socket.RemoteEndPoint as IPEndPoint;
  55. // open channel
  56. SendMessage(new ChannelOpenMessage(LocalChannelNumber, LocalWindowSize, LocalPacketSize,
  57. new DirectTcpipChannelInfo(remoteHost, port, ep.Address.ToString(), (uint) ep.Port)));
  58. // Wait for channel to open
  59. WaitOnHandle(_channelOpen);
  60. }
  61. /// <summary>
  62. /// Occurs as the forwarded port is being stopped.
  63. /// </summary>
  64. private void ForwardedPort_Closing(object sender, EventArgs eventArgs)
  65. {
  66. CloseSocket();
  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. SendMessage(new ChannelDataMessage(RemoteChannelNumber, buffer.Take(read).ToArray()));
  86. }
  87. else
  88. {
  89. // client quit sending (but the server may still send data or an EOF)
  90. if (Interlocked.CompareExchange(ref _sentEof, 1, 0) == 0)
  91. {
  92. // inform server that we won't be sending anything anymore if we
  93. // haven't already sent a SSH_MSG_CHANNEL_EOF message
  94. //
  95. // note that we'll still wait for a SSH_MSG_CHANNEL_EOF or
  96. // SSH_MSG_CHANNEL_CLOSE message once we've broken the receive
  97. // loop
  98. SendEof();
  99. }
  100. break;
  101. }
  102. }
  103. catch (SocketException exp)
  104. {
  105. switch (exp.SocketErrorCode)
  106. {
  107. case SocketError.WouldBlock:
  108. case SocketError.IOPending:
  109. case SocketError.NoBufferSpaceAvailable:
  110. // socket buffer is probably empty, wait and try again
  111. Thread.Sleep(30);
  112. break;
  113. case SocketError.ConnectionAborted:
  114. case SocketError.ConnectionReset:
  115. // connection was closed after receiving SSH_MSG_CHANNEL_CLOSE message
  116. // in which case the _channelEof waithandle is also set
  117. break;
  118. case SocketError.Interrupted:
  119. // connection was interrupted as part of closing the forwarded port
  120. _channelInterrupted.Set();
  121. break;
  122. default:
  123. throw; // throw any other error
  124. }
  125. }
  126. }
  127. WaitHandle.WaitAny(new WaitHandle[] {_channelEof, _channelInterrupted});
  128. }
  129. /// <summary>
  130. /// Closes the socket, hereby interrupting the blocking receive in <see cref="Bind()"/>.
  131. /// </summary>
  132. private void CloseSocket()
  133. {
  134. if (_socket == null || !_socket.Connected)
  135. return;
  136. lock (_socketShutdownAndCloseLock)
  137. {
  138. if (_socket == null || !_socket.Connected)
  139. return;
  140. _socket.Shutdown(SocketShutdown.Both);
  141. _socket.Close();
  142. }
  143. }
  144. private void ShutdownSocket(SocketShutdown how)
  145. {
  146. if (_socket == null || !_socket.Connected)
  147. return;
  148. lock (_socketShutdownAndCloseLock)
  149. {
  150. if (_socket == null || !_socket.Connected)
  151. return;
  152. _socket.Shutdown(how);
  153. }
  154. }
  155. /// <summary>
  156. /// Closes the channel, optionally waiting for the SSH_MSG_CHANNEL_CLOSE message to
  157. /// be received from the server.
  158. /// </summary>
  159. /// <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>
  160. protected override void Close(bool wait)
  161. {
  162. if (_forwardedPort != null)
  163. {
  164. _forwardedPort.Closing -= ForwardedPort_Closing;
  165. _forwardedPort = null;
  166. }
  167. // close the socket, hereby interrupting the blocking receive in Bind()
  168. CloseSocket();
  169. // send EOF message first when channel needs to be closed
  170. if (IsOpen && Interlocked.CompareExchange(ref _sentEof, 1, 0) == 0)
  171. {
  172. SendEof();
  173. }
  174. base.Close(wait);
  175. }
  176. /// <summary>
  177. /// Called when channel data is received.
  178. /// </summary>
  179. /// <param name="data">The data.</param>
  180. protected override void OnData(byte[] data)
  181. {
  182. base.OnData(data);
  183. if (_socket != null && _socket.Connected)
  184. InternalSocketSend(data);
  185. }
  186. /// <summary>
  187. /// Called when channel is opened by the server.
  188. /// </summary>
  189. /// <param name="remoteChannelNumber">The remote channel number.</param>
  190. /// <param name="initialWindowSize">Initial size of the window.</param>
  191. /// <param name="maximumPacketSize">Maximum size of the packet.</param>
  192. protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initialWindowSize, uint maximumPacketSize)
  193. {
  194. base.OnOpenConfirmation(remoteChannelNumber, initialWindowSize, maximumPacketSize);
  195. _channelOpen.Set();
  196. }
  197. protected override void OnOpenFailure(uint reasonCode, string description, string language)
  198. {
  199. base.OnOpenFailure(reasonCode, description, language);
  200. _channelOpen.Set();
  201. }
  202. /// <summary>
  203. /// Called when channel has no more data to receive.
  204. /// </summary>
  205. protected override void OnEof()
  206. {
  207. base.OnEof();
  208. // the channel will send no more data, so signal to the client that
  209. // we won't be sending anything anymore
  210. ShutdownSocket(SocketShutdown.Send);
  211. var channelEof = _channelEof;
  212. if (channelEof != null)
  213. channelEof.Set();
  214. }
  215. protected override void OnClose()
  216. {
  217. base.OnClose();
  218. // the channel will send no more data, so signal to the client that
  219. // we won't be sending anything anymore
  220. //
  221. // we need to do this here in case the server sends the SSH_MSG_CHANNEL_CLOSE
  222. // message without first sending SSH_MSG_CHANNEL_EOF
  223. ShutdownSocket(SocketShutdown.Send);
  224. var channelEof = _channelEof;
  225. if (channelEof != null)
  226. channelEof.Set();
  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. // close the socket, hereby interrupting the blocking receive in Bind()
  236. CloseSocket();
  237. // if error occured, no more data can be received
  238. var channelEof = _channelEof;
  239. if (channelEof != null)
  240. channelEof.Set();
  241. }
  242. /// <summary>
  243. /// Called when the server wants to terminate the connection immmediately.
  244. /// </summary>
  245. /// <remarks>
  246. /// The sender MUST NOT send or receive any data after this message, and
  247. /// the recipient MUST NOT accept any data after receiving this message.
  248. /// </remarks>
  249. protected override void OnDisconnected()
  250. {
  251. base.OnDisconnected();
  252. // close the socket, hereby interrupting the blocking receive in Bind()
  253. CloseSocket();
  254. // If disconnected, no more data can be received
  255. var channelEof = _channelEof;
  256. if (channelEof != null)
  257. channelEof.Set();
  258. }
  259. partial void InternalSocketReceive(byte[] buffer, ref int read);
  260. partial void InternalSocketSend(byte[] data);
  261. protected override void Dispose(bool disposing)
  262. {
  263. // make sure we've unsubscribed from all session events before we starting disposing
  264. base.Dispose(disposing);
  265. if (_forwardedPort != null)
  266. {
  267. _forwardedPort.Closing -= ForwardedPort_Closing;
  268. _forwardedPort = null;
  269. }
  270. if (_socket != null)
  271. {
  272. _socket.Dispose();
  273. _socket = null;
  274. }
  275. if (_channelEof != null)
  276. {
  277. _channelEof.Dispose();
  278. _channelEof = null;
  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. if (_channelInterrupted != null)
  291. {
  292. _channelInterrupted.Dispose();
  293. _channelInterrupted = null;
  294. }
  295. }
  296. }
  297. }