ForwardedPortRemote.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. using System;
  2. using System.Threading;
  3. using Renci.SshNet.Messages.Connection;
  4. using Renci.SshNet.Common;
  5. using System.Globalization;
  6. using System.Net;
  7. using Renci.SshNet.Abstractions;
  8. namespace Renci.SshNet
  9. {
  10. /// <summary>
  11. /// Provides functionality for remote port forwarding
  12. /// </summary>
  13. public class ForwardedPortRemote : ForwardedPort, IDisposable
  14. {
  15. private bool _requestStatus;
  16. private EventWaitHandle _globalRequestResponse = new AutoResetEvent(false);
  17. private int _pendingRequests;
  18. private bool _isStarted;
  19. /// <summary>
  20. /// Gets or sets a value indicating whether port forwarding is started.
  21. /// </summary>
  22. /// <value>
  23. /// <c>true</c> if port forwarding is started; otherwise, <c>false</c>.
  24. /// </value>
  25. public override bool IsStarted
  26. {
  27. get { return _isStarted; }
  28. }
  29. /// <summary>
  30. /// Gets the bound host.
  31. /// </summary>
  32. public IPAddress BoundHostAddress { get; private set; }
  33. /// <summary>
  34. /// Gets the bound host.
  35. /// </summary>
  36. public string BoundHost
  37. {
  38. get
  39. {
  40. return BoundHostAddress.ToString();
  41. }
  42. }
  43. /// <summary>
  44. /// Gets the bound port.
  45. /// </summary>
  46. public uint BoundPort { get; private set; }
  47. /// <summary>
  48. /// Gets the forwarded host.
  49. /// </summary>
  50. public IPAddress HostAddress { get; private set; }
  51. /// <summary>
  52. /// Gets the forwarded host.
  53. /// </summary>
  54. public string Host
  55. {
  56. get
  57. {
  58. return HostAddress.ToString();
  59. }
  60. }
  61. /// <summary>
  62. /// Gets the forwarded port.
  63. /// </summary>
  64. public uint Port { get; private set; }
  65. /// <summary>
  66. /// Initializes a new instance of the <see cref="ForwardedPortRemote" /> class.
  67. /// </summary>
  68. /// <param name="boundHostAddress">The bound host address.</param>
  69. /// <param name="boundPort">The bound port.</param>
  70. /// <param name="hostAddress">The host address.</param>
  71. /// <param name="port">The port.</param>
  72. /// <exception cref="ArgumentNullException"><paramref name="boundHostAddress"/> is <c>null</c>.</exception>
  73. /// <exception cref="ArgumentNullException"><paramref name="hostAddress"/> is <c>null</c>.</exception>
  74. /// <exception cref="ArgumentOutOfRangeException"><paramref name="boundPort" /> is greater than <see cref="F:System.Net.IPEndPoint.MaxPort" />.</exception>
  75. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port" /> is greater than <see cref="F:System.Net.IPEndPoint.MaxPort" />.</exception>
  76. public ForwardedPortRemote(IPAddress boundHostAddress, uint boundPort, IPAddress hostAddress, uint port)
  77. {
  78. if (boundHostAddress == null)
  79. throw new ArgumentNullException("boundHostAddress");
  80. if (hostAddress == null)
  81. throw new ArgumentNullException("hostAddress");
  82. boundPort.ValidatePort("boundPort");
  83. port.ValidatePort("port");
  84. BoundHostAddress = boundHostAddress;
  85. BoundPort = boundPort;
  86. HostAddress = hostAddress;
  87. Port = port;
  88. }
  89. /// <summary>
  90. /// Initializes a new instance of the <see cref="ForwardedPortRemote"/> class.
  91. /// </summary>
  92. /// <param name="boundPort">The bound port.</param>
  93. /// <param name="host">The host.</param>
  94. /// <param name="port">The port.</param>
  95. /// <example>
  96. /// <code source="..\..\Renci.SshNet.Tests\Classes\ForwardedPortRemoteTest.cs" region="Example SshClient AddForwardedPort Start Stop ForwardedPortRemote" language="C#" title="Remote port forwarding" />
  97. /// </example>
  98. public ForwardedPortRemote(uint boundPort, string host, uint port)
  99. : this(string.Empty, boundPort, host, port)
  100. {
  101. }
  102. /// <summary>
  103. /// Initializes a new instance of the <see cref="ForwardedPortRemote"/> class.
  104. /// </summary>
  105. /// <param name="boundHost">The bound host.</param>
  106. /// <param name="boundPort">The bound port.</param>
  107. /// <param name="host">The host.</param>
  108. /// <param name="port">The port.</param>
  109. public ForwardedPortRemote(string boundHost, uint boundPort, string host, uint port)
  110. : this(DnsAbstraction.GetHostAddresses(boundHost)[0],
  111. boundPort,
  112. DnsAbstraction.GetHostAddresses(host)[0],
  113. port)
  114. {
  115. }
  116. /// <summary>
  117. /// Starts remote port forwarding.
  118. /// </summary>
  119. protected override void StartPort()
  120. {
  121. Session.RegisterMessage("SSH_MSG_REQUEST_FAILURE");
  122. Session.RegisterMessage("SSH_MSG_REQUEST_SUCCESS");
  123. Session.RegisterMessage("SSH_MSG_CHANNEL_OPEN");
  124. Session.RequestSuccessReceived += Session_RequestSuccess;
  125. Session.RequestFailureReceived += Session_RequestFailure;
  126. Session.ChannelOpenReceived += Session_ChannelOpening;
  127. // send global request to start direct tcpip
  128. Session.SendMessage(new GlobalRequestMessage(GlobalRequestName.TcpIpForward, true, BoundHost, BoundPort));
  129. // wat for response on global request to start direct tcpip
  130. Session.WaitOnHandle(_globalRequestResponse);
  131. if (!_requestStatus)
  132. {
  133. // when the request to start port forward was rejected, then we're no longer
  134. // interested in these events
  135. Session.RequestSuccessReceived -= Session_RequestSuccess;
  136. Session.RequestFailureReceived -= Session_RequestFailure;
  137. Session.ChannelOpenReceived -= Session_ChannelOpening;
  138. throw new SshException(string.Format(CultureInfo.CurrentCulture, "Port forwarding for '{0}' port '{1}' failed to start.", Host, Port));
  139. }
  140. _isStarted = true;
  141. }
  142. /// <summary>
  143. /// Stops remote port forwarding.
  144. /// </summary>
  145. /// <param name="timeout">The maximum amount of time to wait for pending requests to finish processing.</param>
  146. protected override void StopPort(TimeSpan timeout)
  147. {
  148. // if the port not started, then there's nothing to stop
  149. if (!IsStarted)
  150. return;
  151. // mark forwarded port stopped, this also causes open of new channels to be rejected
  152. _isStarted = false;
  153. base.StopPort(timeout);
  154. // send global request to cancel direct tcpip
  155. Session.SendMessage(new GlobalRequestMessage(GlobalRequestName.CancelTcpIpForward, true, BoundHost, BoundPort));
  156. // wait for response on global request to cancel direct tcpip or completion of message
  157. // listener loop (in which case response on global request can never be received)
  158. WaitHandle.WaitAny(new[] { _globalRequestResponse, Session.MessageListenerCompleted }, timeout);
  159. // unsubscribe from session events as either the tcpip forward is cancelled at the
  160. // server, or our session message loop has completed
  161. Session.RequestSuccessReceived -= Session_RequestSuccess;
  162. Session.RequestFailureReceived -= Session_RequestFailure;
  163. Session.ChannelOpenReceived -= Session_ChannelOpening;
  164. var startWaiting = DateTime.Now;
  165. while (true)
  166. {
  167. // break out of loop when all pending requests have been processed
  168. if (Interlocked.CompareExchange(ref _pendingRequests, 0, 0) == 0)
  169. break;
  170. // determine time elapsed since waiting for pending requests to finish
  171. var elapsed = DateTime.Now - startWaiting;
  172. // break out of loop when specified timeout has elapsed
  173. if (elapsed >= timeout && timeout != SshNet.Session.InfiniteTimeSpan)
  174. break;
  175. // give channels time to process pending requests
  176. ThreadAbstraction.Sleep(50);
  177. }
  178. }
  179. /// <summary>
  180. /// Ensures the current instance is not disposed.
  181. /// </summary>
  182. /// <exception cref="ObjectDisposedException">The current instance is disposed.</exception>
  183. protected override void CheckDisposed()
  184. {
  185. if (_isDisposed)
  186. throw new ObjectDisposedException(GetType().FullName);
  187. }
  188. private void Session_ChannelOpening(object sender, MessageEventArgs<ChannelOpenMessage> e)
  189. {
  190. var channelOpenMessage = e.Message;
  191. var info = channelOpenMessage.Info as ForwardedTcpipChannelInfo;
  192. if (info != null)
  193. {
  194. // Ensure this is the corresponding request
  195. if (info.ConnectedAddress == BoundHost && info.ConnectedPort == BoundPort)
  196. {
  197. if (!_isStarted)
  198. {
  199. Session.SendMessage(new ChannelOpenFailureMessage(channelOpenMessage.LocalChannelNumber, "", ChannelOpenFailureMessage.AdministrativelyProhibited));
  200. return;
  201. }
  202. ThreadAbstraction.ExecuteThread(() =>
  203. {
  204. Interlocked.Increment(ref _pendingRequests);
  205. try
  206. {
  207. RaiseRequestReceived(info.OriginatorAddress, info.OriginatorPort);
  208. using (var channel = Session.CreateChannelForwardedTcpip(channelOpenMessage.LocalChannelNumber, channelOpenMessage.InitialWindowSize, channelOpenMessage.MaximumPacketSize))
  209. {
  210. channel.Exception += Channel_Exception;
  211. channel.Bind(new IPEndPoint(HostAddress, (int) Port), this);
  212. channel.Close();
  213. }
  214. }
  215. catch (Exception exp)
  216. {
  217. RaiseExceptionEvent(exp);
  218. }
  219. finally
  220. {
  221. Interlocked.Decrement(ref _pendingRequests);
  222. }
  223. });
  224. }
  225. }
  226. }
  227. private void Channel_Exception(object sender, ExceptionEventArgs exceptionEventArgs)
  228. {
  229. RaiseExceptionEvent(exceptionEventArgs.Exception);
  230. }
  231. private void Session_RequestFailure(object sender, EventArgs e)
  232. {
  233. _requestStatus = false;
  234. _globalRequestResponse.Set();
  235. }
  236. private void Session_RequestSuccess(object sender, MessageEventArgs<RequestSuccessMessage> e)
  237. {
  238. _requestStatus = true;
  239. if (BoundPort == 0)
  240. {
  241. BoundPort = (e.Message.BoundPort == null) ? 0 : e.Message.BoundPort.Value;
  242. }
  243. _globalRequestResponse.Set();
  244. }
  245. #region IDisposable Members
  246. private bool _isDisposed;
  247. /// <summary>
  248. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  249. /// </summary>
  250. public void Dispose()
  251. {
  252. Dispose(true);
  253. GC.SuppressFinalize(this);
  254. }
  255. /// <summary>
  256. /// Releases unmanaged and - optionally - managed resources
  257. /// </summary>
  258. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  259. protected override void Dispose(bool disposing)
  260. {
  261. if (!_isDisposed)
  262. {
  263. base.Dispose(disposing);
  264. if (disposing)
  265. {
  266. if (Session != null)
  267. {
  268. Session.RequestSuccessReceived -= Session_RequestSuccess;
  269. Session.RequestFailureReceived -= Session_RequestFailure;
  270. Session.ChannelOpenReceived -= Session_ChannelOpening;
  271. Session = null;
  272. }
  273. if (_globalRequestResponse != null)
  274. {
  275. _globalRequestResponse.Dispose();
  276. _globalRequestResponse = null;
  277. }
  278. }
  279. _isDisposed = true;
  280. }
  281. }
  282. /// <summary>
  283. /// Releases unmanaged resources and performs other cleanup operations before the
  284. /// <see cref="ForwardedPortRemote"/> is reclaimed by garbage collection.
  285. /// </summary>
  286. ~ForwardedPortRemote()
  287. {
  288. // Do not re-create Dispose clean-up code here.
  289. // Calling Dispose(false) is optimal in terms of
  290. // readability and maintainability.
  291. Dispose(false);
  292. }
  293. #endregion
  294. }
  295. }