| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | using System.IO; |
| | | 6 | | using System.Net.Quic; |
| | | 7 | | using System.Net.Security; |
| | | 8 | | using System.Net.Sockets; |
| | | 9 | | using System.Runtime.Versioning; |
| | | 10 | | using System.Security.Authentication; |
| | | 11 | | using System.Security.Cryptography.X509Certificates; |
| | | 12 | | using System.Threading; |
| | | 13 | | using System.Threading.Tasks; |
| | | 14 | | |
| | | 15 | | namespace System.Net.Http |
| | | 16 | | { |
| | | 17 | | internal static class ConnectHelper |
| | | 18 | | { |
| | | 19 | | /// <summary> |
| | | 20 | | /// Helper type used by HttpClientHandler when wrapping SocketsHttpHandler to map its |
| | | 21 | | /// certificate validation callback to the one used by SslStream. |
| | | 22 | | /// </summary> |
| | | 23 | | internal sealed class CertificateCallbackMapper |
| | | 24 | | { |
| | | 25 | | public readonly Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> FromHttpClien |
| | | 26 | | public readonly RemoteCertificateValidationCallback ForSocketsHttpHandler; |
| | | 27 | | |
| | 0 | 28 | | public CertificateCallbackMapper(Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bo |
| | 0 | 29 | | { |
| | 0 | 30 | | FromHttpClientHandler = fromHttpClientHandler; |
| | 0 | 31 | | ForSocketsHttpHandler = (object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors |
| | 0 | 32 | | FromHttpClientHandler((HttpRequestMessage)sender, certificate as X509Certificate2, chain, sslPolicyE |
| | 0 | 33 | | } |
| | | 34 | | } |
| | | 35 | | |
| | | 36 | | private static SslClientAuthenticationOptions SetUpRemoteCertificateValidationCallback(SslClientAuthenticationOp |
| | 0 | 37 | | { |
| | | 38 | | // If there's a cert validation callback, and if it came from HttpClientHandler, |
| | | 39 | | // wrap the original delegate in order to change the sender to be the request message (expected by HttpClien |
| | 0 | 40 | | RemoteCertificateValidationCallback? callback = sslOptions.RemoteCertificateValidationCallback; |
| | 0 | 41 | | if (callback != null && callback.Target is CertificateCallbackMapper mapper) |
| | 0 | 42 | | { |
| | 0 | 43 | | sslOptions = sslOptions.ShallowClone(); // Clone as we're about to mutate it and don't want to affect th |
| | 0 | 44 | | Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> localFromHttpClientHandle |
| | 0 | 45 | | HttpRequestMessage localRequest = request; |
| | 0 | 46 | | sslOptions.RemoteCertificateValidationCallback = (object sender, X509Certificate? certificate, X509Chain |
| | 0 | 47 | | { |
| | 0 | 48 | | Debug.Assert(localRequest != null); |
| | 0 | 49 | | bool result = localFromHttpClientHandler(localRequest, certificate as X509Certificate2, chain, sslPo |
| | 0 | 50 | | localRequest = null!; // ensure the SslOptions and this callback don't keep the first HttpRequestMes |
| | 0 | 51 | | return result; |
| | 0 | 52 | | }; |
| | 0 | 53 | | } |
| | | 54 | | |
| | 0 | 55 | | return sslOptions; |
| | 0 | 56 | | } |
| | | 57 | | |
| | | 58 | | public static async ValueTask<SslStream> EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, |
| | 0 | 59 | | { |
| | 0 | 60 | | sslOptions = SetUpRemoteCertificateValidationCallback(sslOptions, request); |
| | | 61 | | |
| | 0 | 62 | | SslStream sslStream = new SslStream(stream); |
| | | 63 | | |
| | | 64 | | try |
| | 0 | 65 | | { |
| | 0 | 66 | | if (async) |
| | 0 | 67 | | { |
| | 0 | 68 | | await sslStream.AuthenticateAsClientAsync(sslOptions, cancellationToken).ConfigureAwait(false); |
| | 0 | 69 | | } |
| | | 70 | | else |
| | 0 | 71 | | { |
| | 0 | 72 | | using (cancellationToken.UnsafeRegister(static s => ((Stream)s!).Dispose(), stream)) |
| | 0 | 73 | | { |
| | 0 | 74 | | sslStream.AuthenticateAsClient(sslOptions); |
| | 0 | 75 | | } |
| | 0 | 76 | | } |
| | 0 | 77 | | } |
| | 0 | 78 | | catch (Exception e) |
| | 0 | 79 | | { |
| | 0 | 80 | | sslStream.Dispose(); |
| | | 81 | | |
| | 0 | 82 | | if (e is OperationCanceledException) |
| | 0 | 83 | | { |
| | 0 | 84 | | throw; |
| | | 85 | | } |
| | | 86 | | |
| | 0 | 87 | | if (CancellationHelper.ShouldWrapInOperationCanceledException(e, cancellationToken)) |
| | 0 | 88 | | { |
| | 0 | 89 | | throw CancellationHelper.CreateOperationCanceledException(e, cancellationToken); |
| | | 90 | | } |
| | | 91 | | |
| | 0 | 92 | | HttpRequestException ex = new HttpRequestException(HttpRequestError.SecureConnectionError, SR.net_http_s |
| | 0 | 93 | | if (request.IsExtendedConnectRequest) |
| | 0 | 94 | | { |
| | | 95 | | // Extended connect request is negotiating strictly for ALPN = "h2" because HttpClient is unaware of |
| | | 96 | | // At this point, SSL connection for HTTP / 2 failed, and the exception should indicate the reason f |
| | 0 | 97 | | ex.Data["HTTP2_ENABLED"] = false; |
| | 0 | 98 | | } |
| | 0 | 99 | | throw ex; |
| | | 100 | | } |
| | | 101 | | |
| | | 102 | | // Handle race condition if cancellation happens after SSL auth completes but before the registration is dis |
| | 0 | 103 | | if (cancellationToken.IsCancellationRequested) |
| | 0 | 104 | | { |
| | 0 | 105 | | sslStream.Dispose(); |
| | 0 | 106 | | throw CancellationHelper.CreateOperationCanceledException(null, cancellationToken); |
| | | 107 | | } |
| | | 108 | | |
| | 0 | 109 | | return sslStream; |
| | 0 | 110 | | } |
| | | 111 | | |
| | | 112 | | [SupportedOSPlatform("linux")] |
| | | 113 | | [SupportedOSPlatform("macos")] |
| | | 114 | | [SupportedOSPlatform("windows")] |
| | | 115 | | public static async ValueTask<QuicConnection> ConnectQuicAsync(HttpRequestMessage request, DnsEndPoint endPoint, |
| | 0 | 116 | | { |
| | 0 | 117 | | clientAuthenticationOptions = SetUpRemoteCertificateValidationCallback(clientAuthenticationOptions, request) |
| | | 118 | | |
| | | 119 | | try |
| | 0 | 120 | | { |
| | 0 | 121 | | return await QuicConnection.ConnectAsync(new QuicClientConnectionOptions() |
| | 0 | 122 | | { |
| | 0 | 123 | | MaxInboundBidirectionalStreams = 0, // Client doesn't support inbound streams: https://www.rfc-edito |
| | 0 | 124 | | MaxInboundUnidirectionalStreams = 5, // Minimum is 3: https://www.rfc-editor.org/rfc/rfc9114.html#un |
| | 0 | 125 | | IdleTimeout = idleTimeout, |
| | 0 | 126 | | DefaultStreamErrorCode = (long)Http3ErrorCode.RequestCancelled, |
| | 0 | 127 | | DefaultCloseErrorCode = (long)Http3ErrorCode.NoError, |
| | 0 | 128 | | RemoteEndPoint = endPoint, |
| | 0 | 129 | | ClientAuthenticationOptions = clientAuthenticationOptions, |
| | 0 | 130 | | StreamCapacityCallback = streamCapacityCallback, |
| | 0 | 131 | | }, cancellationToken).ConfigureAwait(false); |
| | | 132 | | } |
| | 0 | 133 | | catch (Exception ex) when (ex is not OperationCanceledException) |
| | 0 | 134 | | { |
| | 0 | 135 | | throw CreateWrappedException(ex, endPoint.Host, endPoint.Port, cancellationToken); |
| | | 136 | | } |
| | 0 | 137 | | } |
| | | 138 | | |
| | | 139 | | internal static Exception CreateWrappedException(Exception exception, string host, int port, CancellationToken c |
| | 0 | 140 | | { |
| | 0 | 141 | | return CancellationHelper.ShouldWrapInOperationCanceledException(exception, cancellationToken) ? |
| | 0 | 142 | | CancellationHelper.CreateOperationCanceledException(exception, cancellationToken) : |
| | 0 | 143 | | new HttpRequestException(DeduceError(exception), $"{exception.Message} ({host}:{port})", exception, Requ |
| | | 144 | | |
| | | 145 | | static HttpRequestError DeduceError(Exception exception) |
| | 0 | 146 | | { |
| | 0 | 147 | | if (exception is AuthenticationException) |
| | 0 | 148 | | { |
| | 0 | 149 | | return HttpRequestError.SecureConnectionError; |
| | | 150 | | } |
| | | 151 | | |
| | | 152 | | // Resolving a non-existent hostname often leads to EAI_AGAIN/TryAgain on Linux, indicating a non-author |
| | | 153 | | // Getting EAGAIN/TryAgain from a TCP connect() is not possible on Windows or Mac according to the docs |
| | | 154 | | // which should be a very rare error in practice. As a result, mapping SocketError.TryAgain to HttpReque |
| | | 155 | | // leads to a more reliable distinction between NameResolutionError and ConnectionError. |
| | 0 | 156 | | if (exception is SocketException socketException && |
| | 0 | 157 | | socketException.SocketErrorCode is SocketError.HostNotFound or SocketError.TryAgain) |
| | 0 | 158 | | { |
| | 0 | 159 | | return HttpRequestError.NameResolutionError; |
| | | 160 | | } |
| | | 161 | | |
| | 0 | 162 | | return HttpRequestError.ConnectionError; |
| | 0 | 163 | | } |
| | 0 | 164 | | } |
| | | 165 | | } |
| | | 166 | | } |