Skip to content

SocketsHttpHandler: do not use DualMode sockets in default connection logic #45614

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

Closed
Closed
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
using System.Net.Quic.Implementations;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -15,6 +17,125 @@ namespace System.Net.Http
{
internal static class ConnectHelper
{
public static ValueTask<Stream> ConnectAsync(string host, int port, bool async, CancellationToken cancellationToken)
{
return async ? ConnectAsync(host, port, cancellationToken) : new ValueTask<Stream>(Connect(host, port, cancellationToken));
}

private static async ValueTask<Stream> ConnectAsync(string host, int port, CancellationToken cancellationToken)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is all concerning to me. The premise of the SocketsHttpHandler.ConnectCallback's design (and not exposing the default implementation of how a socket is created or the default connect logic) was that it's just a couple of lines of code to emulate the default behavior... now it's over a 100 lines?
cc: @geoffkizer

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're going to introduce an easy mode static Socket.ConnectAsync API, so it'll go back to a 5 liner.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then shouldn't we add that and then use it here rather than doing it this way? I don't see why we're putting back this connect helper logic. If the concern is being able to more easily backport, that same static API can just be added as an internal SocketEx static in the backport or something like that.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with @stephentoub here

{
// We use the static Socket.ConnectAsync with a SocketAsyncEventArgs, because this approach is:
// 1. Cancellable
// 2. Does not create Dual-stack sockets, which are unavailable in certain environments,
// see https://github.com/dotnet/runtime/issues/44686.
var saea = new ConnectEventArgs();
try
{
saea.Initialize(cancellationToken);

// Configure which server to which to connect.
saea.RemoteEndPoint = new DnsEndPoint(host, port);

// Initiate the connection.
if (Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, saea))
{
// Connect completing asynchronously. Enable it to be canceled and wait for it.
using (cancellationToken.UnsafeRegister(static s => Socket.CancelConnectAsync((SocketAsyncEventArgs)s!), saea))
{
await saea.Builder.Task.ConfigureAwait(false);
}
}
else if (saea.SocketError != SocketError.Success)
{
// Connect completed synchronously but unsuccessfully.
throw new SocketException((int)saea.SocketError);
}

Debug.Assert(saea.SocketError == SocketError.Success, $"Expected Success, got {saea.SocketError}.");
Debug.Assert(saea.ConnectSocket != null, "Expected non-null socket");

// Configure the socket and return a stream for it.
Socket socket = saea.ConnectSocket;
socket.NoDelay = true;
return new NetworkStream(socket, ownsSocket: true);
}
catch (Exception error) when (!(error is OperationCanceledException))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit:

Suggested change
catch (Exception error) when (!(error is OperationCanceledException))
catch (Exception error) when (error is not OperationCanceledException)

Reads a bit nicer.

Copy link
Member Author

@antonfirsov antonfirsov Dec 10, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer to not do refactors in this PR and keep ConnectHelper.ConnectAsync as it was in it's original 628d99b state, there are way too many thinks we may want to fix.

{
throw CreateWrappedException(error, host, port, cancellationToken);
}
finally
{
saea.Dispose();
}
}

private static Stream Connect(string host, int port, CancellationToken cancellationToken)
{
// For synchronous connections, we can just create a socket and make the connection.
cancellationToken.ThrowIfCancellationRequested();
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't this creating a dual-mode socket?

Copy link
Member Author

@antonfirsov antonfirsov Dec 10, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah ... I dont like this inconsistence either, just took the state at the commit I mentioned. (Note that there was no sync in 3.1)

The bad thing is that the ony alternatives I see is to either do sync over async or implement a sync version of DnsConnect within System.Net.Http

try
{
socket.NoDelay = true;
using (cancellationToken.UnsafeRegister(static s => ((Socket)s!).Dispose(), socket))
{
socket.Connect(new DnsEndPoint(host, port));
}

return new NetworkStream(socket, ownsSocket: true);
}
catch (Exception e)
{
socket.Dispose();
throw CreateWrappedException(e, host, port, cancellationToken);
}
}

/// <summary>SocketAsyncEventArgs that carries with it additional state for a Task builder and a CancellationToken.</summary>
private sealed class ConnectEventArgs : SocketAsyncEventArgs
{
internal ConnectEventArgs() :
// The OnCompleted callback serves just to complete a task that's awaited in ConnectAsync,
// so we don't need to also flow ExecutionContext again into the OnCompleted callback.
base(unsafeSuppressExecutionContextFlow: true)
{
}

public AsyncTaskMethodBuilder Builder { get; private set; }
public CancellationToken CancellationToken { get; private set; }

public void Initialize(CancellationToken cancellationToken)
{
CancellationToken = cancellationToken;
AsyncTaskMethodBuilder b = default;
_ = b.Task; // force initialization
Builder = b;
}

protected override void OnCompleted(SocketAsyncEventArgs _)
{
switch (SocketError)
{
case SocketError.Success:
Builder.SetResult();
break;

case SocketError.OperationAborted:
case SocketError.ConnectionAborted:
if (CancellationToken.IsCancellationRequested)
{
Builder.SetException(ExceptionDispatchInfo.SetCurrentStackTrace(CancellationHelper.CreateOperationCanceledException(null, CancellationToken)));
break;
}
goto default;

default:
Builder.SetException(ExceptionDispatchInfo.SetCurrentStackTrace(new SocketException((int)SocketError)));
break;
}
}
}

/// <summary>
/// Helper type used by HttpClientHandler when wrapping SocketsHttpHandler to map its
/// certificate validation callback to the one used by SslStream.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1278,10 +1278,10 @@ private async ValueTask<Stream> ConnectToTcpHostAsync(string host, int port, Htt

var endPoint = new DnsEndPoint(host, port);
Socket? socket = null;
try
// If a ConnectCallback was supplied, use that to establish the connection.
if (Settings._connectCallback != null)
{
// If a ConnectCallback was supplied, use that to establish the connection.
if (Settings._connectCallback != null)
try
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The old try catch wrapped both the ConnectCallback case as well as the default case. This one only wraps the ConnectCallback case. Why the change?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is an equivalent catch block in ConnectHelper.ConnectAsync:

catch (Exception error) when (!(error is OperationCanceledException))
{
throw CreateWrappedException(error, host, port, cancellationToken);
}

internal static Exception CreateWrappedException(Exception error, string host, int port, CancellationToken cancellationToken)
{
return CancellationHelper.ShouldWrapInOperationCanceledException(error, cancellationToken) ?
CancellationHelper.CreateOperationCanceledException(error, cancellationToken) :
new HttpRequestException($"{error.Message} ({host}:{port})", error, RequestRetryType.RetryOnNextProxy);
}

{
ValueTask<Stream> streamTask = Settings._connectCallback(new SocketsHttpConnectionContext(endPoint, initialRequest), cancellationToken);

Expand All @@ -1296,32 +1296,18 @@ private async ValueTask<Stream> ConnectToTcpHostAsync(string host, int port, Htt

return await streamTask.ConfigureAwait(false) ?? throw new HttpRequestException(SR.net_http_null_from_connect_callback);
}
else
catch (Exception ex)
{
// Otherwise, create and connect a socket using default settings.
socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };

if (async)
{
await socket.ConnectAsync(endPoint, cancellationToken).ConfigureAwait(false);
}
else
{
using (cancellationToken.UnsafeRegister(static s => ((Socket)s!).Dispose(), socket))
{
socket.Connect(endPoint);
}
}

return new NetworkStream(socket, ownsSocket: true);
socket?.Dispose();
throw ex is OperationCanceledException oce && oce.CancellationToken == cancellationToken ?
CancellationHelper.CreateOperationCanceledException(innerException: null, cancellationToken) :
ConnectHelper.CreateWrappedException(ex, endPoint.Host, endPoint.Port, cancellationToken);
}
}
catch (Exception ex)
else
{
socket?.Dispose();
throw ex is OperationCanceledException oce && oce.CancellationToken == cancellationToken ?
CancellationHelper.CreateOperationCanceledException(innerException: null, cancellationToken) :
ConnectHelper.CreateWrappedException(ex, endPoint.Host, endPoint.Port, cancellationToken);
// Otherwise, create and connect a socket using default settings.
return await ConnectHelper.ConnectAsync(host, port, async, cancellationToken).ConfigureAwait(false);
}
}

Expand Down