ChannelDirectTcpip.cs 12 KB

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