|
| 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.Diagnostics.CodeAnalysis; |
| 6 | +using System.IO.Pipelines; |
| 7 | +using System.Net; |
| 8 | +using System.Net.Security; |
| 9 | +using Microsoft.AspNetCore.Connections; |
| 10 | +using Microsoft.AspNetCore.Hosting; |
| 11 | +using Microsoft.AspNetCore.Http.Features; |
| 12 | +using Microsoft.AspNetCore.Server.Kestrel.Core.Internal; |
| 13 | +using Microsoft.AspNetCore.Server.Kestrel.Https; |
| 14 | +using Microsoft.AspNetCore.Server.Kestrel.Https.Internal; |
| 15 | +using Microsoft.Extensions.Hosting; |
| 16 | +using Microsoft.Extensions.Logging; |
| 17 | + |
| 18 | +namespace Microsoft.AspNetCore.Server.Kestrel.Core; |
| 19 | + |
| 20 | +/// <inheritdoc /> |
| 21 | +internal sealed class HttpsConfigurationService : IHttpsConfigurationService |
| 22 | +{ |
| 23 | + private readonly IInitializer? _initializer; |
| 24 | + private bool _isInitialized; |
| 25 | + |
| 26 | + private TlsConfigurationLoader? _tlsConfigurationLoader; |
| 27 | + private Action<FeatureCollection, ListenOptions>? _populateMultiplexedTransportFeatures; |
| 28 | + private Func<ListenOptions, ListenOptions>? _useHttpsWithDefaults; |
| 29 | + |
| 30 | + /// <summary> |
| 31 | + /// Create an uninitialized <see cref="HttpsConfigurationService"/>. |
| 32 | + /// To initialize it later, call <see cref="Initialize"/>. |
| 33 | + /// </summary> |
| 34 | + public HttpsConfigurationService() |
| 35 | + { |
| 36 | + } |
| 37 | + |
| 38 | + /// <summary> |
| 39 | + /// Create an initialized <see cref="HttpsConfigurationService"/>. |
| 40 | + /// </summary> |
| 41 | + /// <remarks> |
| 42 | + /// In practice, <see cref="Initialize"/> won't be called until it's needed. |
| 43 | + /// </remarks> |
| 44 | + public HttpsConfigurationService(IInitializer initializer) |
| 45 | + { |
| 46 | + _initializer = initializer; |
| 47 | + } |
| 48 | + |
| 49 | + /// <inheritdoc /> |
| 50 | + // If there's an initializer, it *can* be initialized, even though it might not be yet. |
| 51 | + // Use explicit interface implentation so we don't accidentally call it within this class. |
| 52 | + bool IHttpsConfigurationService.IsInitialized => _isInitialized || _initializer is not null; |
| 53 | + |
| 54 | + /// <inheritdoc/> |
| 55 | + public void Initialize( |
| 56 | + IHostEnvironment hostEnvironment, |
| 57 | + ILogger<KestrelServer> serverLogger, |
| 58 | + ILogger<HttpsConnectionMiddleware> httpsLogger) |
| 59 | + { |
| 60 | + if (_isInitialized) |
| 61 | + { |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + _isInitialized = true; |
| 66 | + |
| 67 | + _tlsConfigurationLoader = new TlsConfigurationLoader(hostEnvironment, serverLogger, httpsLogger); |
| 68 | + _populateMultiplexedTransportFeatures = PopulateMultiplexedTransportFeaturesWorker; |
| 69 | + _useHttpsWithDefaults = UseHttpsWithDefaultsWorker; |
| 70 | + } |
| 71 | + |
| 72 | + /// <inheritdoc/> |
| 73 | + public void ApplyHttpsConfiguration( |
| 74 | + HttpsConnectionAdapterOptions httpsOptions, |
| 75 | + EndpointConfig endpoint, |
| 76 | + KestrelServerOptions serverOptions, |
| 77 | + CertificateConfig? defaultCertificateConfig, |
| 78 | + ConfigurationReader configurationReader) |
| 79 | + { |
| 80 | + EnsureInitialized(CoreStrings.NeedHttpsConfigurationToApplyHttpsConfiguration); |
| 81 | + _tlsConfigurationLoader.ApplyHttpsConfiguration(httpsOptions, endpoint, serverOptions, defaultCertificateConfig, configurationReader); |
| 82 | + } |
| 83 | + |
| 84 | + /// <inheritdoc/> |
| 85 | + public ListenOptions UseHttpsWithSni(ListenOptions listenOptions, HttpsConnectionAdapterOptions httpsOptions, EndpointConfig endpoint) |
| 86 | + { |
| 87 | + // This doesn't get a distinct string since it won't actually throw - it's always called after ApplyHttpsConfiguration |
| 88 | + EnsureInitialized(CoreStrings.NeedHttpsConfigurationToApplyHttpsConfiguration); |
| 89 | + return _tlsConfigurationLoader.UseHttpsWithSni(listenOptions, httpsOptions, endpoint); |
| 90 | + } |
| 91 | + |
| 92 | + /// <inheritdoc/> |
| 93 | + public CertificateAndConfig? LoadDefaultCertificate(ConfigurationReader configurationReader) |
| 94 | + { |
| 95 | + EnsureInitialized(CoreStrings.NeedHttpsConfigurationToLoadDefaultCertificate); |
| 96 | + return _tlsConfigurationLoader.LoadDefaultCertificate(configurationReader); |
| 97 | + } |
| 98 | + |
| 99 | + /// <inheritdoc/> |
| 100 | + public void PopulateMultiplexedTransportFeatures(FeatureCollection features, ListenOptions listenOptions) |
| 101 | + { |
| 102 | + EnsureInitialized(CoreStrings.NeedHttpsConfigurationToUseHttp3); |
| 103 | + _populateMultiplexedTransportFeatures.Invoke(features, listenOptions); |
| 104 | + } |
| 105 | + |
| 106 | + /// <inheritdoc/> |
| 107 | + public ListenOptions UseHttpsWithDefaults(ListenOptions listenOptions) |
| 108 | + { |
| 109 | + EnsureInitialized(CoreStrings.NeedHttpsConfigurationToBindHttpsAddresses); |
| 110 | + return _useHttpsWithDefaults.Invoke(listenOptions); |
| 111 | + } |
| 112 | + |
| 113 | + /// <summary> |
| 114 | + /// If this instance has not been initialized, initialize it if possible and throw otherwise. |
| 115 | + /// </summary> |
| 116 | + /// <exception cref="InvalidOperationException">If initialization is not possible.</exception> |
| 117 | + [MemberNotNull(nameof(_useHttpsWithDefaults), nameof(_tlsConfigurationLoader), nameof(_populateMultiplexedTransportFeatures))] |
| 118 | + private void EnsureInitialized(string uninitializedError) |
| 119 | + { |
| 120 | + if (!_isInitialized) |
| 121 | + { |
| 122 | + if (_initializer is not null) |
| 123 | + { |
| 124 | + _initializer.Initialize(this); |
| 125 | + } |
| 126 | + else |
| 127 | + { |
| 128 | + throw new InvalidOperationException(uninitializedError); |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + Debug.Assert(_useHttpsWithDefaults is not null); |
| 133 | + Debug.Assert(_tlsConfigurationLoader is not null); |
| 134 | + Debug.Assert(_populateMultiplexedTransportFeatures is not null); |
| 135 | + } |
| 136 | + |
| 137 | + /// <summary> |
| 138 | + /// The initialized implementation of <see cref="PopulateMultiplexedTransportFeatures"/>. |
| 139 | + /// </summary> |
| 140 | + internal static void PopulateMultiplexedTransportFeaturesWorker(FeatureCollection features, ListenOptions listenOptions) |
| 141 | + { |
| 142 | + // HttpsOptions or HttpsCallbackOptions should always be set in production, but it's not set for InMemory tests. |
| 143 | + // The QUIC transport will check if TlsConnectionCallbackOptions is missing. |
| 144 | + if (listenOptions.HttpsOptions != null) |
| 145 | + { |
| 146 | + var sslServerAuthenticationOptions = HttpsConnectionMiddleware.CreateHttp3Options(listenOptions.HttpsOptions); |
| 147 | + features.Set(new TlsConnectionCallbackOptions |
| 148 | + { |
| 149 | + ApplicationProtocols = sslServerAuthenticationOptions.ApplicationProtocols ?? new List<SslApplicationProtocol> { SslApplicationProtocol.Http3 }, |
| 150 | + OnConnection = (context, cancellationToken) => ValueTask.FromResult(sslServerAuthenticationOptions), |
| 151 | + OnConnectionState = null, |
| 152 | + }); |
| 153 | + } |
| 154 | + else if (listenOptions.HttpsCallbackOptions != null) |
| 155 | + { |
| 156 | + features.Set(new TlsConnectionCallbackOptions |
| 157 | + { |
| 158 | + ApplicationProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http3 }, |
| 159 | + OnConnection = (context, cancellationToken) => |
| 160 | + { |
| 161 | + return listenOptions.HttpsCallbackOptions.OnConnection(new TlsHandshakeCallbackContext |
| 162 | + { |
| 163 | + ClientHelloInfo = context.ClientHelloInfo, |
| 164 | + CancellationToken = cancellationToken, |
| 165 | + State = context.State, |
| 166 | + Connection = new ConnectionContextAdapter(context.Connection), |
| 167 | + }); |
| 168 | + }, |
| 169 | + OnConnectionState = listenOptions.HttpsCallbackOptions.OnConnectionState, |
| 170 | + }); |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + /// <summary> |
| 175 | + /// The initialized implementation of <see cref="UseHttpsWithDefaults"/>. |
| 176 | + /// </summary> |
| 177 | + internal static ListenOptions UseHttpsWithDefaultsWorker(ListenOptions listenOptions) |
| 178 | + { |
| 179 | + return listenOptions.UseHttps(); |
| 180 | + } |
| 181 | + |
| 182 | + /// <summary> |
| 183 | + /// TlsHandshakeCallbackContext.Connection is ConnectionContext but QUIC connection only implements BaseConnectionContext. |
| 184 | + /// </summary> |
| 185 | + private sealed class ConnectionContextAdapter : ConnectionContext |
| 186 | + { |
| 187 | + private readonly BaseConnectionContext _inner; |
| 188 | + |
| 189 | + public ConnectionContextAdapter(BaseConnectionContext inner) => _inner = inner; |
| 190 | + |
| 191 | + public override IDuplexPipe Transport |
| 192 | + { |
| 193 | + get => throw new NotSupportedException("Not supported by HTTP/3 connections."); |
| 194 | + set => throw new NotSupportedException("Not supported by HTTP/3 connections."); |
| 195 | + } |
| 196 | + public override string ConnectionId |
| 197 | + { |
| 198 | + get => _inner.ConnectionId; |
| 199 | + set => _inner.ConnectionId = value; |
| 200 | + } |
| 201 | + public override IFeatureCollection Features => _inner.Features; |
| 202 | + public override IDictionary<object, object?> Items |
| 203 | + { |
| 204 | + get => _inner.Items; |
| 205 | + set => _inner.Items = value; |
| 206 | + } |
| 207 | + public override EndPoint? LocalEndPoint |
| 208 | + { |
| 209 | + get => _inner.LocalEndPoint; |
| 210 | + set => _inner.LocalEndPoint = value; |
| 211 | + } |
| 212 | + public override EndPoint? RemoteEndPoint |
| 213 | + { |
| 214 | + get => _inner.RemoteEndPoint; |
| 215 | + set => _inner.RemoteEndPoint = value; |
| 216 | + } |
| 217 | + public override CancellationToken ConnectionClosed |
| 218 | + { |
| 219 | + get => _inner.ConnectionClosed; |
| 220 | + set => _inner.ConnectionClosed = value; |
| 221 | + } |
| 222 | + public override ValueTask DisposeAsync() => _inner.DisposeAsync(); |
| 223 | + } |
| 224 | + |
| 225 | + /// <summary> |
| 226 | + /// Register an instance of this type to initialize registered instances of <see cref="HttpsConfigurationService"/>. |
| 227 | + /// </summary> |
| 228 | + internal interface IInitializer |
| 229 | + { |
| 230 | + /// <summary> |
| 231 | + /// Invokes <see cref="IHttpsConfigurationService.Initialize"/>, passing appropriate arguments. |
| 232 | + /// </summary> |
| 233 | + void Initialize(IHttpsConfigurationService httpsConfigurationService); |
| 234 | + } |
| 235 | + |
| 236 | + /// <inheritdoc/> |
| 237 | + internal sealed class Initializer : IInitializer |
| 238 | + { |
| 239 | + private readonly IHostEnvironment _hostEnvironment; |
| 240 | + private readonly ILogger<KestrelServer> _serverLogger; |
| 241 | + private readonly ILogger<HttpsConnectionMiddleware> _httpsLogger; |
| 242 | + |
| 243 | + public Initializer( |
| 244 | + IHostEnvironment hostEnvironment, |
| 245 | + ILogger<KestrelServer> serverLogger, |
| 246 | + ILogger<HttpsConnectionMiddleware> httpsLogger) |
| 247 | + { |
| 248 | + _hostEnvironment = hostEnvironment; |
| 249 | + _serverLogger = serverLogger; |
| 250 | + _httpsLogger = httpsLogger; |
| 251 | + } |
| 252 | + |
| 253 | + /// <inheritdoc/> |
| 254 | + public void Initialize(IHttpsConfigurationService httpsConfigurationService) |
| 255 | + { |
| 256 | + httpsConfigurationService.Initialize(_hostEnvironment, _serverLogger, _httpsLogger); |
| 257 | + } |
| 258 | + } |
| 259 | +} |
| 260 | + |
0 commit comments