Skip to content

improve SslStream exception after disposal #79329

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

Merged
merged 6 commits into from
Jan 6, 2023
Merged
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ private void CloseInternal()
// block potential future read and auth operations since SslStream is disposing.
// This leaves the _nestedRead = 1 and _nestedAuth = 1, but that's ok, since
// subsequent operations check the _exception sentinel first
if (Interlocked.Exchange(ref _nestedRead, 1) == 0 &&
Interlocked.Exchange(ref _nestedAuth, 1) == 0)
if (Interlocked.Exchange(ref _nestedRead, 2) == 0 &&
Interlocked.Exchange(ref _nestedAuth, 2) == 0)
{
_buffer.ReturnBuffer();
}
Expand Down Expand Up @@ -162,13 +162,15 @@ private async Task ReplyOnReAuthenticationAsync<TIOAdapter>(byte[]? buffer, Canc
private async Task RenegotiateAsync<TIOAdapter>(CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
if (Interlocked.Exchange(ref _nestedAuth, 1) == 1)
if (Interlocked.CompareExchange(ref _nestedAuth, 1, 0) != 0)
{
ObjectDisposedException.ThrowIf(_nestedAuth > 1, this);
throw new InvalidOperationException(SR.Format(SR.net_io_invalidnestedcall, "authenticate"));
}

if (Interlocked.Exchange(ref _nestedRead, 1) == 1)
if (Interlocked.CompareExchange(ref _nestedRead, 1, 0) != 0)
{
ObjectDisposedException.ThrowIf(_nestedRead > 1, this);
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "read"));
}

Expand Down Expand Up @@ -763,13 +765,16 @@ private SecurityStatusPal DecryptData(int frameSize)
private async ValueTask<int> ReadAsyncInternal<TIOAdapter>(Memory<byte> buffer, CancellationToken cancellationToken)
where TIOAdapter : IReadWriteAdapter
{
if (Interlocked.Exchange(ref _nestedRead, 1) == 1)
// Throw first if we already have exception.
// Check for disposal is not atomic so we will check again bellow.
ThrowIfExceptionalOrNotAuthenticated();

if (Interlocked.CompareExchange(ref _nestedRead, 1, 0) != 0)
{
ObjectDisposedException.ThrowIf(_nestedRead > 1, this);
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "read"));
}

ThrowIfExceptionalOrNotAuthenticated();

try
{
int processedLength = 0;
Expand Down