Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #1275. Hung Dispose() caused by infinite socket timeout #1280

Merged
merged 1 commit into from
Dec 28, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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