ForwardedPortRemote.cs 12 KB

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