SSH.NET icon indicating copy to clipboard operation
SSH.NET copied to clipboard

Sshclient deadlock/freeze on disconnect

Open gary-holland opened this issue 8 years ago • 128 comments

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.

gary-holland avatar Dec 13 '17 02:12 gary-holland

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.

keyant avatar Dec 18 '17 17:12 keyant

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

oktinaut avatar Jan 03 '18 15:01 oktinaut

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

Any update?

HalfLegend avatar Jan 11 '18 09:01 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.

HalfLegend avatar Jan 11 '18 09:01 HalfLegend

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.

JulianRooze avatar Jan 18 '18 11:01 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.

JulianRooze avatar Jan 19 '18 10:01 JulianRooze

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();
                }

bloudraak avatar Jan 27 '18 22:01 bloudraak

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

neseih avatar Jun 05 '18 11:06 neseih

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(...))"

jolosimeon avatar Jun 25 '18 06:06 jolosimeon

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

drieseng avatar Jun 26 '18 17:06 drieseng

@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.

JulianRooze avatar Jun 27 '18 10:06 JulianRooze

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

HalfLegend avatar Jul 16 '18 01:07 HalfLegend

@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.

cravall avatar Jul 19 '18 04:07 cravall

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

drieseng avatar Jul 19 '18 19:07 drieseng

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 😄

cravall avatar Jul 19 '18 21:07 cravall

So when I slowly step through the code it doesn't hang... I changed all the bunch of DiagnosticAbstraction.Log to simple Console.WriteLine and got the following.

This is when it does hang: screen shot 2018-07-20 at 10 02 25 am

This is when it does NOT hang: screen shot 2018-07-20 at 10 00 42 am

cravall avatar Jul 19 '18 22:07 cravall

And this is from the docker container (which doesn't hang): screen shot 2018-07-20 at 10 47 07 am

cravall avatar Jul 19 '18 22:07 cravall

Hi, I need some help : I can connect correctly but any command sent, hang indefinitely. I tried access via putty and it works fine. I tried to set a sleep between connection and command but result is the same. If anyone has a clue it would be nice. Renci.Ssh.net version 1.0.1.0 Thanks KeyboardInteractiveAuthenticationMethod kauth = new KeyboardInteractiveAuthenticationMethod("integrator"); kauth.AuthenticationPrompt += new EventHandler<Renci.SshNet.Common.AuthenticationPromptEventArgs>(HandleKeyEvent); PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod("integrator", "myPassword"); ConnectionInfo connectionInfo = new ConnectionInfo("10.2.112.00", 22, "integrator", pauth, kauth); SshClient sshClient = new SshClient(connectionInfo); SshCommand cmd = sshClient.CreateCommand($"xFeedback register /Status/Audio"); string s =cmd.Execute(); // <-- hangs here for ever sshClient.Disconnect();

it fails here in SshCommand.cs private void WaitOnHandle(WaitHandle waitHandle) { var waitHandles = new[] { _sessionErrorOccuredWaitHandle, waitHandle };

        switch (WaitHandle.WaitAny(waitHandles, CommandTimeout))  **// WaitHandle nerver raised**
        {
            case 0:
                throw _exception;
            case WaitHandle.WaitTimeout:
                throw new SshOperationTimeoutException(string.Format(CultureInfo.CurrentCulture, "Command '{0}' has timed out.", CommandText));
        }
    }

Spica92 avatar Jul 23 '18 12:07 Spica92

@Spica92 Please create a separate issue for this problem. Include as much details as possible (OS, SSH server, exact version of SSH.NET, …).

drieseng avatar Jul 23 '18 20:07 drieseng

@cvallance From your traces, it looks as if .NET Core doesn't break out of the Socket.Select(IList checkRead, IList checkWrite, IList checkError, int microSeconds) call in Session.MessageListener() when the socket is disposed. I'll try to have a closer look tomorrow.

You can always add some CWLs before and after the Socket.Select(IList checkRead, IList checkWrite, IList checkError, int microSeconds) call, and in the finally block.

drieseng avatar Jul 23 '18 20:07 drieseng