Skip to content

Sshclient deadlock/freeze on disconnect #355

Closed

Description

@gary-holland

Hi,

My code is locking when attempting to call the Disconnect function.

This snippet is an example of what is locking:

SshClient client = new SshClient("server", "user", "pass");
client.Connect();
client.Disconnect(); # freezes here

I'm connecting to a ssh connection running on a QNAP NAS server, with the server version listed as "SSH-2.0-OpenSSH_7.6".

This is on OSX (High Sierra). I just tried in Windows, and the issue doesn't exist there.

Any help would be much appreciated.

Thanks.

Activity

  1. keyant commented on Dec 18, 2017

    @keyant

    I also encountered the same problem ( on OSX High Sierra, too).

    I found the code is locked by this line: _messageListenerCompleted.WaitOne(); in the method Disconnect() of Session.cs.

  2. oktinaut commented on Jan 3, 2018

    @oktinaut

    The problem occurs on Sierra as well (using .NET Core 2.0).

  3. HalfLegend commented on Jan 11, 2018

    @HalfLegend

    Same issue, also OSX High Sierra
    Not only sshClient, scpClient also have the issue.

    Any update?

  4. HalfLegend commented on Jan 11, 2018

    @HalfLegend

    Now I am using the following code to avoid the issue:

                    Task.Factory.StartNew(() => {
                        sshClient.Dispose();
                    });

    and kill these threads later.

    Though the threads are blocked, the socket resources are in fact freed successfully before _messageListenerCompleted.WaitOne() is called.

  5. JulianRooze commented on Jan 18, 2018

    @JulianRooze

    We run into the same issue, but on Linux. Can confirm that it's waiting on _messageListenerCompleted.WaitOne() inside Disconnect.

    We have a wrapper class around the SshClient and we worked around the issue by disconnecting the socket through reflection if necessary after a 2 second delay and setting the waithandle. The dispose method of our wrapper class:

    public void Dispose()
    {
      if (_client == null) return;
    
      Task.Run(() =>
      {
    	_log.Debug("Disposing _client");
    
    	var timer = new System.Timers.Timer();
    
    	timer.Interval = 2000;
    	timer.AutoReset = false;
    
    	timer.Elapsed += (s, e) =>
    	{
    	  try
    	  {
    		var sessionField = _client.GetType().GetProperty("Session", BindingFlags.NonPublic | BindingFlags.Instance);
    
    		if (sessionField != null)
    		{
    		  var session = sessionField.GetValue(_client);
    
    		  if (session != null)
    		  {
    			var socketField = session.GetType().GetField("_socket", BindingFlags.NonPublic | BindingFlags.Instance);
    
    			if (socketField != null)
    			{
    			  var socket = (Socket)socketField.GetValue(session);
    
    			  if (socket != null)
    			  {
    				_log.Debug($"Socket state: Connected = {socket.Connected}, Blocking = {socket.Blocking}, Available = {socket.Available}, LocalEndPoint = {socket.LocalEndPoint}, RemoteEndPoint = {socket.RemoteEndPoint}");
    
    				_log.Debug("Set _socket to null");
    
    				try
    				{
    				  socket.Dispose();
    				}
    				catch (Exception ex)
    				{
    				  _log.Debug("Exception disposing _socket", ex);
    				}
    
    				socketField.SetValue(session, null);
    			  }
    			  else
    			  {
    				_log.Debug("_socket was null");
    			  }
    			}
    
    			var messageListenerCompletedField = session.GetType().GetField("_messageListenerCompleted", BindingFlags.NonPublic | BindingFlags.Instance);
    
    			var messageListenerCompleted = (EventWaitHandle)messageListenerCompletedField.GetValue(session);
    
    			if (messageListenerCompleted != null)
    			{
    			  var waitHandleSet = messageListenerCompleted.WaitOne(0);
    
    			  _log.Debug($"_messageListenerCompleted was set = {waitHandleSet}");
    
    			  if (!waitHandleSet)
    			  {
    				_log.Debug($"Calling Set()");
    				messageListenerCompleted.Set();
    			  }
    			}
    			else
    			{
    			  _log.Debug("_messageListenerCompleted was null");
    			}
    		  }
    		  else
    		  {
    			_log.Debug("Session was null");
    		  }
    		}
    	  }
    	  catch (Exception ex)
    	  {
    		_log.Debug($"Exception in Timer event handler", ex);
    	  }
    	};
    
    	timer.Start();
    
    	_client.Dispose();
    
    	_log.Info("Disposed _client");
      });
    }

    A typical log when it fails to disconnect:

    image

    But it usually disconnects just fine, not disconnecting is the exception. The ratios are 20 failures for 700 successful disconnects in about 12 hours.

  6. JulianRooze commented on Jan 19, 2018

    @JulianRooze

    I should add that it happens much more often that _socket is already null when disconnecting hangs, and only _messageListenerCompleted.Set() wasn't called yet. So the log usually says this when the disconnect fails:

    image

    So the _socket still being connected is the exception.

  7. bloudraak commented on Jan 27, 2018

    @bloudraak

    I have the same issue using .NET Core 2.0 on macOS Sierra 10.12.6 (16G1212)

    using (var client = new SshClient(host, username, password))
                    {
    
                        client.Connect();
                        var command = client.CreateCommand("df -H");
                        var result = command.Execute();
                        Console.WriteLine(result);
                        client.Disconnect();
                    }
    
  8. neseih commented on Jun 5, 2018

    @neseih

    Just ran into the same issue on Ubuntu 16.04, dotnet core 2.1

  9. jolosimeon commented on Jun 25, 2018

    @jolosimeon

    Ran into the same problem on macOS High Sierra, 10.13.5, dotnet core version 2.1.300
    It fails to disconnect and also hangs at the end of "using (var client = new SftpClient(...))"

  10. drieseng commented on Jun 26, 2018

    @drieseng
    Member

    What version of SSH.NET are you using?
    Can you easily reproduce this issue, or does it only happen on some occasion?

  11. JulianRooze commented on Jun 27, 2018

    @JulianRooze

    @drieseng We use the latest (2016.1.0). From our logs, in about 4% of cases it hasn't set the waithandle (see our workaround code above) so it would wait indefinitely. Ever since upgrading to .NET Core 2.1 we haven't seen the cases where the socket was still connected, so I think that's solved by that upgrade, but it was really rare before so it might be a coincidence. I think the occurrence of the issue is more or less random and probably a timing thing.

  12. HalfLegend commented on Jul 16, 2018

    @HalfLegend

    @drieseng Any update?
    It could be easily reproduced on mac os. Just open a ssh client and close it

  13. cravall commented on Jul 19, 2018

    @cravall

    @drieseng - Getting it on macOS High Sierra dotnet core v2.1.301. Using the latest nuget package 2016.1.0. Easily reproducible... just open a connection and try to call Disconnect.

  14. drieseng commented on Jul 19, 2018

    @drieseng
    Member

    I don't have a mac :(
    Can you reproduce it on Linux?

  15. cravall commented on Jul 19, 2018

    @cravall

    Just tried to reproduce it in docker and couldn't... which I guess is a good thing because that's what we're using outside of our dev environments.

    Still, would be good to have it fixed for dev purposes. I'll see if I can have a crack at fixing but honestly, I wouldn't know where to start 😄

  16. 108 remaining items

  17. aberbegall commented on Jun 13, 2022

    @aberbegall

    Is this issue fixed with 2020.0.1 and .NET 5.0 or shall I simply avoid calling Disconnect() method and just Dispose() the connection?
    Asking because I don't see that Shutdown(SocketShutdown.Both) was finally implemented into any latest SSH.NET release.
    Thanks

  18. ilqvya commented on Jun 13, 2022

    @ilqvya

    Better use the Process.Start to call the native to windows "ssh" program and pass args to it. The project is a mess of multithreading issues

  19. aberbegall commented on Jun 13, 2022

    @aberbegall

    @effolkronium thanks for the tip, but my code needs to support Win Server 2012 and 2016 too where no windows native ssh exists (I would need to install PuTTY Plink or similar 3rd party)

  20. oguzhantopcu commented on Jun 13, 2022

    @oguzhantopcu
  21. aberbegall commented on Jun 13, 2022

    @aberbegall

    @oguzhantopcu Is this the update your fork contains or is there anything else to consider?
    Thanks

  22. oguzhantopcu commented on Jun 13, 2022

    @oguzhantopcu

    Yeah, that one line code fixes that hang problem. My app makes thousands of sftp connections everyday without any problem.

  23. erik-wramner commented on Jul 1, 2022

    @erik-wramner

    Then perhaps we could get that line into the official version?

  24. oguzhantopcu commented on Dec 30, 2023

    @oguzhantopcu

    is there anyone that still faces this issue? i want to ditch my custom code and use the original one. maybe it is fixed in .net core side.

    @drieseng btw why we are not using SocketShutdown.Both instead of SocketShutdown.Send?

    as like here OctopusDeploy@7e8bf58

  25. Kalyxt commented on Feb 1, 2024

    @Kalyxt

    Yes its still issue for me, If I connect to remote client, and I lost connection, it hangs on Disconnect.

  26. oguzhantopcu commented on Feb 1, 2024

    @oguzhantopcu

    Yes its still issue for me, If I connect to remote client, and I lost connection, it hangs on Disconnect.

    .net core version?

  27. Kalyxt commented on Feb 1, 2024

    @Kalyxt

    I am trying in on .NET Framework 4.7.2 project.

    I can easily test it in this order:

    • Create SSH connection to remote machine
    • Sudo reboot on remote machine
    • It hangs in Disconnect calling from Dispose at _ = _messageListenerCompleted.WaitOne();
    public void Disconnect()
    {
        DiagnosticAbstraction.Log(string.Format("[{0}] Disconnecting session.", ToHex(SessionId)));
    
        // send SSH_MSG_DISCONNECT message, clear socket read buffer and dispose it
        Disconnect(DisconnectReason.ByApplication, "Connection terminated by the client.");
    
        // at this point, we are sure that the listener thread will stop as we've
        // disconnected the socket, so lets wait until the message listener thread
        // has completed
        if (_messageListenerCompleted != null)
        {
            _ = _messageListenerCompleted.WaitOne();
        }
    }
    

    I fixed it by adding _ = _messageListenerCompleted.WaitOne(1000);
    and _ = _messageListenerCompleted?.Set(); in MessageListener.

  28. VanIseghemThomas commented on Sep 25, 2025

    @VanIseghemThomas

    Stil an issue for me when used in the Unity engine on 2025.0.0. Narrowed it down to the SshClient.Disconnect & SshClient.Dispose call.

  29. ilqvya commented on Sep 25, 2025

    @ilqvya

    Just use built in ssh cmd tool instead. The project is very buggy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions