ChannelDirectTcpip.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 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 = (IPEndPoint) socket.RemoteEndPoint;
  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 should also interrupt the
  63. // blocking receive in Bind if the client sends FIN/ACK in time
  64. ShutdownSocket(SocketShutdown.Send);
  65. // if the FIN/ACK is not sent in time by the remote client, then interrupt the blocking receive
  66. // by closing the socket
  67. CloseSocket();
  68. }
  69. /// <summary>
  70. /// Binds channel to remote host.
  71. /// </summary>
  72. public void Bind()
  73. {
  74. // Cannot bind if channel is not open
  75. if (!IsOpen)
  76. return;
  77. var buffer = new byte[RemotePacketSize];
  78. SocketAbstraction.ReadContinuous(_socket, buffer, 0, buffer.Length, SendData);
  79. // even though the client has disconnected, we still want to properly close the
  80. // channel
  81. //
  82. // we'll do this in in Close() - invoked through Dispose(bool) - that way we have
  83. // a single place from which we send an SSH_MSG_CHANNEL_EOF message and wait for
  84. // the SSH_MSG_CHANNEL_CLOSE message
  85. }
  86. /// <summary>
  87. /// Closes the socket, hereby interrupting the blocking receive in <see cref="Bind()"/>.
  88. /// </summary>
  89. private void CloseSocket()
  90. {
  91. if (_socket == null)
  92. return;
  93. lock (_socketLock)
  94. {
  95. if (_socket == null)
  96. return;
  97. // closing a socket actually disposes the socket, so we can safely dereference
  98. // the field to avoid entering the lock again later
  99. _socket.Dispose();
  100. _socket = null;
  101. }
  102. }
  103. /// <summary>
  104. /// Shuts down the socket.
  105. /// </summary>
  106. /// <param name="how">One of the <see cref="SocketShutdown"/> values that specifies the operation that will no longer be allowed.</param>
  107. private void ShutdownSocket(SocketShutdown how)
  108. {
  109. if (_socket == null)
  110. return;
  111. lock (_socketLock)
  112. {
  113. if (!_socket.IsConnected())
  114. return;
  115. _socket.Shutdown(how);
  116. }
  117. }
  118. /// <summary>
  119. /// Closes the channel, waiting for the SSH_MSG_CHANNEL_CLOSE message to be received from the server.
  120. /// </summary>
  121. protected override void Close()
  122. {
  123. var forwardedPort = _forwardedPort;
  124. if (forwardedPort != null)
  125. {
  126. forwardedPort.Closing -= ForwardedPort_Closing;
  127. _forwardedPort = null;
  128. }
  129. // signal to the client that we will not send anything anymore; this will also interrupt the
  130. // blocking receive in Bind if the client sends FIN/ACK in time
  131. //
  132. // if the FIN/ACK is not sent in time, the socket will be closed after the channel is closed
  133. ShutdownSocket(SocketShutdown.Send);
  134. // close the SSH channel
  135. base.Close();
  136. // close the socket
  137. CloseSocket();
  138. }
  139. /// <summary>
  140. /// Called when channel data is received.
  141. /// </summary>
  142. /// <param name="data">The data.</param>
  143. protected override void OnData(byte[] data)
  144. {
  145. base.OnData(data);
  146. if (_socket != null)
  147. {
  148. lock (_socketLock)
  149. {
  150. if (_socket.IsConnected())
  151. {
  152. SocketAbstraction.Send(_socket, data, 0, data.Length);
  153. }
  154. }
  155. }
  156. }
  157. /// <summary>
  158. /// Called when channel is opened by the server.
  159. /// </summary>
  160. /// <param name="remoteChannelNumber">The remote channel number.</param>
  161. /// <param name="initialWindowSize">Initial size of the window.</param>
  162. /// <param name="maximumPacketSize">Maximum size of the packet.</param>
  163. protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initialWindowSize, uint maximumPacketSize)
  164. {
  165. base.OnOpenConfirmation(remoteChannelNumber, initialWindowSize, maximumPacketSize);
  166. _channelOpen.Set();
  167. }
  168. protected override void OnOpenFailure(uint reasonCode, string description, string language)
  169. {
  170. base.OnOpenFailure(reasonCode, description, language);
  171. _channelOpen.Set();
  172. }
  173. /// <summary>
  174. /// Called when channel has no more data to receive.
  175. /// </summary>
  176. protected override void OnEof()
  177. {
  178. base.OnEof();
  179. // the channel will send no more data, and hence it does not make sense to receive
  180. // any more data from the client to send to the remote party (and we surely won't
  181. // send anything anymore)
  182. //
  183. // this will also interrupt the blocking receive in Bind()
  184. ShutdownSocket(SocketShutdown.Send);
  185. }
  186. /// <summary>
  187. /// Called whenever an unhandled <see cref="Exception"/> occurs in <see cref="Session"/> causing
  188. /// the message loop to be interrupted, or when an exception occurred processing a channel message.
  189. /// </summary>
  190. protected override void OnErrorOccured(Exception exp)
  191. {
  192. base.OnErrorOccured(exp);
  193. // signal to the client that we will not send anything anymore; this will also interrupt the
  194. // blocking receive in Bind if the client sends FIN/ACK in time
  195. //
  196. // if the FIN/ACK is not sent in time, the socket will be closed in Close(bool)
  197. ShutdownSocket(SocketShutdown.Send);
  198. }
  199. /// <summary>
  200. /// Called when the server wants to terminate the connection immmediately.
  201. /// </summary>
  202. /// <remarks>
  203. /// The sender MUST NOT send or receive any data after this message, and
  204. /// the recipient MUST NOT accept any data after receiving this message.
  205. /// </remarks>
  206. protected override void OnDisconnected()
  207. {
  208. base.OnDisconnected();
  209. // the channel will accept or send no more data, and hence it does not make sense
  210. // to accept any more data from the client (and we surely won't send anything
  211. // anymore)
  212. //
  213. // so lets signal to the client that we will not send or receive anything anymore
  214. // this will also interrupt the blocking receive in Bind()
  215. ShutdownSocket(SocketShutdown.Both);
  216. }
  217. protected override void Dispose(bool disposing)
  218. {
  219. // make sure we've unsubscribed from all session events and closed the channel
  220. // before we starting disposing
  221. base.Dispose(disposing);
  222. if (disposing)
  223. {
  224. if (_socket != null)
  225. {
  226. lock (_socketLock)
  227. {
  228. var socket = _socket;
  229. if (socket != null)
  230. {
  231. _socket = null;
  232. socket.Dispose();
  233. }
  234. }
  235. }
  236. var channelOpen = _channelOpen;
  237. if (channelOpen != null)
  238. {
  239. _channelOpen = null;
  240. channelOpen.Dispose();
  241. }
  242. var channelData = _channelData;
  243. if (channelData != null)
  244. {
  245. _channelData = null;
  246. channelData.Dispose();
  247. }
  248. }
  249. }
  250. }
  251. }