2
0

ForwardedPortRemote.cs 12 KB

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