Skip to content

Commit

Permalink
Fix hung dispose caused by infinite socket timeout
Browse files Browse the repository at this point in the history
Co-authored-by: Rob Hague <[email protected]>
  • Loading branch information
jkillingsworth and Rob-Hague committed Dec 26, 2023
1 parent b0d01df commit 347d289
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/Renci.SshNet/Session.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1788,22 +1788,40 @@ internal static string ToHex(byte[] bytes)
/// when the value of <see cref="Socket.Available"/> is obtained. To workaround this issue
/// we synchronize reads from the <see cref="Socket"/>.
/// </para>
/// <para>
/// We assume the socket is still connected if the read lock cannot be acquired immediately.
/// In this case, we just return <see langword="true"/> without actually waiting to acquire
/// the lock. We don't want to wait for the read lock if another thread already has it because
/// there are cases where the other thread holding the lock can be waiting indefinitely for
/// a socket read operation to complete.
/// </para>
/// </remarks>
private bool IsSocketConnected()
{
#pragma warning disable S2222 // Locks should be released on all paths
lock (_socketDisposeLock)
{
if (!_socket.IsConnected())
{
return false;
}

lock (_socketReadLock)
if (!Monitor.TryEnter(_socketReadLock))
{
return true;
}

try
{
var connectionClosedOrDataAvailable = _socket.Poll(0, SelectMode.SelectRead);
return !(connectionClosedOrDataAvailable && _socket.Available == 0);
}
finally
{
Monitor.Exit(_socketReadLock);
}
}
#pragma warning restore S2222 // Locks should be released on all paths
}

/// <summary>
Expand Down

0 comments on commit 347d289

Please sign in to comment.