ForwardedPortRemote.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. using System;
  2. using System.Threading;
  3. using Renci.SshNet.Channels;
  4. using Renci.SshNet.Messages.Connection;
  5. using Renci.SshNet.Common;
  6. using System.Diagnostics;
  7. using System.Globalization;
  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. /// <summary>
  18. /// Starts remote port forwarding.
  19. /// </summary>
  20. public override void Start()
  21. {
  22. base.Start();
  23. // If port already started don't start it again
  24. if (this.IsStarted)
  25. return;
  26. this.Session.RegisterMessage("SSH_MSG_REQUEST_FAILURE");
  27. this.Session.RegisterMessage("SSH_MSG_REQUEST_SUCCESS");
  28. this.Session.RegisterMessage("SSH_MSG_CHANNEL_OPEN");
  29. this.Session.RequestSuccessReceived += Session_RequestSuccess;
  30. this.Session.RequestFailureReceived += Session_RequestFailure;
  31. this.Session.ChannelOpenReceived += Session_ChannelOpening;
  32. // Send global request to start direct tcpip
  33. this.Session.SendMessage(new GlobalRequestMessage(GlobalRequestName.TcpIpForward, true, this.BoundHost, this.BoundPort));
  34. this.Session.WaitHandle(this._globalRequestResponse);
  35. if (!this._requestStatus)
  36. {
  37. // If request failed don't handle channel opening for this request
  38. this.Session.ChannelOpenReceived -= Session_ChannelOpening;
  39. throw new SshException(string.Format(CultureInfo.CurrentCulture, "Port forwarding for '{0}' port '{1}' failed to start.", this.Host, this.Port));
  40. }
  41. else
  42. {
  43. this.IsStarted = true;
  44. }
  45. }
  46. /// <summary>
  47. /// Stops remote port forwarding.
  48. /// </summary>
  49. public override void Stop()
  50. {
  51. base.Stop();
  52. // If port not started you cant stop it
  53. if (!this.IsStarted)
  54. return;
  55. // Send global request to cancel direct tcpip
  56. this.Session.SendMessage(new GlobalRequestMessage(GlobalRequestName.CancelTcpIpForward, true, this.BoundHost, this.BoundPort));
  57. this.Session.WaitHandle(this._globalRequestResponse);
  58. this.Session.RequestSuccessReceived -= Session_RequestSuccess;
  59. this.Session.RequestFailureReceived -= Session_RequestFailure;
  60. this.Session.ChannelOpenReceived -= Session_ChannelOpening;
  61. this.IsStarted = false;
  62. }
  63. private void Session_ChannelOpening(object sender, MessageEventArgs<ChannelOpenMessage> e)
  64. {
  65. // Ensure that this is corresponding request
  66. var info = e.Message.Info as ForwardedTcpipChannelInfo;
  67. if (info != null)
  68. {
  69. if (info.ConnectedAddress == this.BoundHost && info.ConnectedPort == this.BoundPort)
  70. {
  71. this.ExecuteThread(() =>
  72. {
  73. try
  74. {
  75. this.RaiseRequestReceived(info.OriginatorAddress, info.OriginatorPort);
  76. var channel = this.Session.CreateChannel<ChannelForwardedTcpip>(e.Message.LocalChannelNumber, e.Message.InitialWindowSize, e.Message.MaximumPacketSize);
  77. channel.Bind(this.Host, this.Port);
  78. }
  79. catch (Exception exp)
  80. {
  81. this.RaiseExceptionEvent(exp);
  82. }
  83. });
  84. }
  85. }
  86. }
  87. private void Session_RequestFailure(object sender, System.EventArgs e)
  88. {
  89. this._requestStatus = false;
  90. this._globalRequestResponse.Set();
  91. }
  92. private void Session_RequestSuccess(object sender, MessageEventArgs<RequestSuccessMessage> e)
  93. {
  94. this._requestStatus = true;
  95. if (this.BoundPort == 0)
  96. {
  97. this.BoundPort = (e.Message.BoundPort == null) ? 0 : e.Message.BoundPort.Value;
  98. }
  99. this._globalRequestResponse.Set();
  100. }
  101. partial void ExecuteThread(Action action);
  102. #region IDisposable Members
  103. private bool _isDisposed = false;
  104. /// <summary>
  105. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  106. /// </summary>
  107. public void Dispose()
  108. {
  109. Dispose(true);
  110. GC.SuppressFinalize(this);
  111. }
  112. /// <summary>
  113. /// Releases unmanaged and - optionally - managed resources
  114. /// </summary>
  115. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  116. protected virtual void Dispose(bool disposing)
  117. {
  118. // Check to see if Dispose has already been called.
  119. if (!this._isDisposed)
  120. {
  121. // If disposing equals true, dispose all managed
  122. // and unmanaged resources.
  123. if (disposing)
  124. {
  125. // Dispose managed resources.
  126. if (this._globalRequestResponse != null)
  127. {
  128. this._globalRequestResponse.Dispose();
  129. this._globalRequestResponse = null;
  130. }
  131. }
  132. // Note disposing has been done.
  133. _isDisposed = true;
  134. }
  135. }
  136. /// <summary>
  137. /// Releases unmanaged resources and performs other cleanup operations before the
  138. /// <see cref="ForwardedPortRemote"/> is reclaimed by garbage collection.
  139. /// </summary>
  140. ~ForwardedPortRemote()
  141. {
  142. // Do not re-create Dispose clean-up code here.
  143. // Calling Dispose(false) is optimal in terms of
  144. // readability and maintainability.
  145. Dispose(false);
  146. }
  147. #endregion
  148. }
  149. }