From badcf4052c2408c9ff9af078741bb240bc2f474e Mon Sep 17 00:00:00 2001 From: olegkap_cp Date: Thu, 7 Mar 2013 21:35:37 +0000 Subject: [PATCH] Fix and remove orphan threads when using port forwarding. --- Renci.SshClient/Renci.SshNet/Channels/Channel.cs | 12 ++++++++++++ .../Renci.SshNet/Channels/ChannelDirectTcpip.cs | 16 ++++++++++++++++ .../Renci.SshNet/ForwardedPortLocal.NET.cs | 13 +++++++++++++ 3 files changed, 41 insertions(+) diff --git a/Renci.SshClient/Renci.SshNet/Channels/Channel.cs b/Renci.SshClient/Renci.SshNet/Channels/Channel.cs index 7b6b97c4..21e3bb75 100644 --- a/Renci.SshClient/Renci.SshNet/Channels/Channel.cs +++ b/Renci.SshClient/Renci.SshNet/Channels/Channel.cs @@ -519,8 +519,18 @@ namespace Renci.SshNet.Channels } } + protected virtual void OnDisconnected() + { + } + + protected virtual void OnErrorOccured(Exception exp) + { + } + private void Session_Disconnected(object sender, EventArgs e) { + this.OnDisconnected(); + // If objected is disposed or being disposed don't handle this event if (this._isDisposed) return; @@ -530,6 +540,8 @@ namespace Renci.SshNet.Channels private void Session_ErrorOccured(object sender, ExceptionEventArgs e) { + this.OnErrorOccured(e.Exception); + // If objected is disposed or being disposed don't handle this event if (this._isDisposed) return; diff --git a/Renci.SshClient/Renci.SshNet/Channels/ChannelDirectTcpip.cs b/Renci.SshClient/Renci.SshNet/Channels/ChannelDirectTcpip.cs index 99181d0e..baf12803 100644 --- a/Renci.SshClient/Renci.SshNet/Channels/ChannelDirectTcpip.cs +++ b/Renci.SshClient/Renci.SshNet/Channels/ChannelDirectTcpip.cs @@ -194,6 +194,22 @@ namespace Renci.SshNet.Channels this._channelEof.Set(); } + protected override void OnErrorOccured(Exception exp) + { + base.OnErrorOccured(exp); + + // If error occured, no more data can be received + this._channelEof.Set(); + } + + protected override void OnDisconnected() + { + base.OnDisconnected(); + + // If disconnected, no more data can be received + this._channelEof.Set(); + } + partial void ExecuteThread(Action action); partial void InternalSocketReceive(byte[] buffer, ref int read); diff --git a/Renci.SshClient/Renci.SshNet/ForwardedPortLocal.NET.cs b/Renci.SshClient/Renci.SshNet/ForwardedPortLocal.NET.cs index 3320ded1..386d1866 100644 --- a/Renci.SshClient/Renci.SshNet/ForwardedPortLocal.NET.cs +++ b/Renci.SshClient/Renci.SshNet/ForwardedPortLocal.NET.cs @@ -27,6 +27,9 @@ namespace Renci.SshNet this._listener = new TcpListener(ep); this._listener.Start(); + this.Session.ErrorOccured += Session_ErrorOccured; + this.Session.Disconnected += Session_Disconnected; + this._listenerTaskCompleted = new ManualResetEvent(false); this.ExecuteThread(() => { @@ -102,5 +105,15 @@ namespace Renci.SshNet this.IsStarted = false; } + + private void Session_ErrorOccured(object sender, Common.ExceptionEventArgs e) + { + this._listener.Stop(); + } + + private void Session_Disconnected(object sender, EventArgs e) + { + this._listener.Stop(); + } } }