| | | 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.Collections.Generic; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.Globalization; |
| | | 7 | | using System.IO; |
| | | 8 | | using System.Net.Http.Headers; |
| | | 9 | | using System.Net.Http.Metrics; |
| | | 10 | | using System.Net.Quic; |
| | | 11 | | using System.Runtime.CompilerServices; |
| | | 12 | | using System.Runtime.Versioning; |
| | | 13 | | using System.Threading; |
| | | 14 | | using System.Threading.Tasks; |
| | | 15 | | |
| | | 16 | | namespace System.Net.Http |
| | | 17 | | { |
| | | 18 | | [SupportedOSPlatform("linux")] |
| | | 19 | | [SupportedOSPlatform("macos")] |
| | | 20 | | [SupportedOSPlatform("windows")] |
| | | 21 | | internal sealed class Http3Connection : HttpConnectionBase |
| | | 22 | | { |
| | | 23 | | private readonly HttpAuthority _authority; |
| | | 24 | | private readonly byte[]? _altUsedEncodedHeader; |
| | | 25 | | private QuicConnection? _connection; |
| | | 26 | | private Task? _connectionClosedTask; |
| | | 27 | | |
| | | 28 | | // Keep a collection of requests around so we can process GOAWAY. |
| | 0 | 29 | | private readonly Dictionary<QuicStream, Http3RequestStream> _activeRequests = new Dictionary<QuicStream, Http3Re |
| | | 30 | | |
| | | 31 | | // Set when GOAWAY is being processed, when aborting, or when disposing. |
| | 0 | 32 | | private long _firstRejectedStreamId = -1; |
| | | 33 | | |
| | | 34 | | // Our control stream. |
| | | 35 | | private QuicStream? _clientControl; |
| | | 36 | | private Task? _sendSettingsTask; |
| | | 37 | | |
| | | 38 | | // Server-advertised SETTINGS_MAX_FIELD_SECTION_SIZE |
| | | 39 | | // https://www.rfc-editor.org/rfc/rfc9114.html#section-7.2.4.1-2.2.1 |
| | 0 | 40 | | private uint _maxHeaderListSize = uint.MaxValue; // Defaults to infinite |
| | | 41 | | |
| | | 42 | | // Once the server's streams are received, these are set to true. Further receipt of these streams results in a |
| | | 43 | | private bool _haveServerControlStream; |
| | | 44 | | private bool _haveServerQpackDecodeStream; |
| | | 45 | | private bool _haveServerQpackEncodeStream; |
| | | 46 | | |
| | | 47 | | // A connection-level error will abort any future operations. |
| | | 48 | | private Exception? _abortException; |
| | | 49 | | |
| | 0 | 50 | | public HttpAuthority Authority => _authority; |
| | 0 | 51 | | public HttpConnectionPool Pool => _pool; |
| | 0 | 52 | | public uint MaxHeaderListSize => _maxHeaderListSize; |
| | 0 | 53 | | public byte[]? AltUsedEncodedHeaderBytes => _altUsedEncodedHeader; |
| | 0 | 54 | | public Exception? AbortException => Volatile.Read(ref _abortException); |
| | 0 | 55 | | private object SyncObj => _activeRequests; |
| | | 56 | | |
| | | 57 | | private int _availableRequestStreamsCount; |
| | | 58 | | private TaskCompletionSource<bool>? _availableStreamsWaiter; |
| | | 59 | | |
| | | 60 | | /// <summary> |
| | | 61 | | /// If true, we've received GOAWAY, are aborting due to a connection-level error, or are disposing due to pool l |
| | | 62 | | /// </summary> |
| | | 63 | | private bool ShuttingDown |
| | | 64 | | { |
| | | 65 | | get |
| | 0 | 66 | | { |
| | 0 | 67 | | Debug.Assert(Monitor.IsEntered(SyncObj)); |
| | 0 | 68 | | return _firstRejectedStreamId != -1; |
| | 0 | 69 | | } |
| | | 70 | | } |
| | | 71 | | |
| | | 72 | | public Http3Connection(HttpConnectionPool pool, HttpAuthority authority, bool includeAltUsedHeader) |
| | 0 | 73 | | : base(pool, GetNextConnectionId()) |
| | 0 | 74 | | { |
| | 0 | 75 | | _authority = authority; |
| | | 76 | | |
| | 0 | 77 | | if (includeAltUsedHeader) |
| | 0 | 78 | | { |
| | 0 | 79 | | bool altUsedDefaultPort = pool.Kind == HttpConnectionKind.Http && authority.Port == HttpConnectionPool.D |
| | 0 | 80 | | string altUsedValue = altUsedDefaultPort ? authority.IdnHost : string.Create(CultureInfo.InvariantCultur |
| | 0 | 81 | | _altUsedEncodedHeader = QPack.QPackEncoder.EncodeLiteralHeaderFieldWithoutNameReferenceToArray(KnownHead |
| | 0 | 82 | | } |
| | | 83 | | |
| | 0 | 84 | | uint maxHeaderListSize = _pool._lastSeenHttp3MaxHeaderListSize; |
| | 0 | 85 | | if (maxHeaderListSize > 0) |
| | 0 | 86 | | { |
| | | 87 | | // Previous connections to the same host advertised a limit. |
| | | 88 | | // Use this as an initial value before we receive the SETTINGS frame. |
| | 0 | 89 | | _maxHeaderListSize = maxHeaderListSize; |
| | 0 | 90 | | } |
| | 0 | 91 | | } |
| | | 92 | | |
| | | 93 | | public void InitQuicConnection(QuicConnection connection, Activity? connectionSetupActivity, DnsEndPoint connect |
| | 0 | 94 | | { |
| | | 95 | | // Report the exact DnsEndPoint used to establish the QUIC connection (Alt-Svc may point it at an authority |
| | | 96 | | // distinct from the pool's origin), consistent with the connection's RemoteEndPoint. |
| | 0 | 97 | | MarkConnectionAsEstablished(connectionSetupActivity: connectionSetupActivity, remoteEndPoint: connection.Rem |
| | | 98 | | |
| | 0 | 99 | | _connection = connection; |
| | | 100 | | |
| | | 101 | | // Avoid capturing the initial request's ExecutionContext for the entire lifetime of the new connection. |
| | 0 | 102 | | using (ExecutionContext.SuppressFlow()) |
| | 0 | 103 | | { |
| | | 104 | | // Errors are observed via Abort(). |
| | 0 | 105 | | _sendSettingsTask = SendSettingsAsync(); |
| | | 106 | | |
| | | 107 | | // This process is cleaned up when _connection is disposed, and errors are observed via Abort(). |
| | 0 | 108 | | _ = AcceptStreamsAsync(); |
| | 0 | 109 | | } |
| | 0 | 110 | | } |
| | | 111 | | |
| | | 112 | | /// <summary> |
| | | 113 | | /// Starts shutting down the <see cref="Http3Connection"/>. Final cleanup will happen when there are no more act |
| | | 114 | | /// </summary> |
| | | 115 | | public override void Dispose() |
| | 0 | 116 | | { |
| | 0 | 117 | | lock (SyncObj) |
| | 0 | 118 | | { |
| | 0 | 119 | | if (_firstRejectedStreamId == -1) |
| | 0 | 120 | | { |
| | 0 | 121 | | _firstRejectedStreamId = long.MaxValue; |
| | 0 | 122 | | CheckForShutdown(); |
| | 0 | 123 | | } |
| | 0 | 124 | | } |
| | 0 | 125 | | } |
| | | 126 | | |
| | | 127 | | /// <summary> |
| | | 128 | | /// Called when shutting down, this checks for when shutdown is complete (no more active requests) and does actu |
| | | 129 | | /// </summary> |
| | | 130 | | /// <remarks>Requires <see cref="SyncObj"/> to be locked.</remarks> |
| | | 131 | | private void CheckForShutdown() |
| | 0 | 132 | | { |
| | 0 | 133 | | Debug.Assert(Monitor.IsEntered(SyncObj)); |
| | 0 | 134 | | Debug.Assert(ShuttingDown); |
| | | 135 | | |
| | 0 | 136 | | if (_activeRequests.Count != 0) |
| | 0 | 137 | | { |
| | 0 | 138 | | return; |
| | | 139 | | } |
| | | 140 | | |
| | 0 | 141 | | if (_connection != null) |
| | 0 | 142 | | { |
| | | 143 | | // Close the QuicConnection in the background. |
| | | 144 | | |
| | 0 | 145 | | _availableStreamsWaiter?.SetResult(false); |
| | 0 | 146 | | _availableStreamsWaiter = null; |
| | | 147 | | |
| | 0 | 148 | | _connectionClosedTask ??= _connection.CloseAsync((long)Http3ErrorCode.NoError).AsTask(); |
| | | 149 | | |
| | 0 | 150 | | QuicConnection connection = _connection; |
| | 0 | 151 | | _connection = null; |
| | | 152 | | |
| | 0 | 153 | | _ = _connectionClosedTask.ContinueWith(async closeTask => |
| | 0 | 154 | | { |
| | 0 | 155 | | if (closeTask.IsFaulted && NetEventSource.Log.IsEnabled()) |
| | 0 | 156 | | { |
| | 0 | 157 | | Trace($"{nameof(QuicConnection)} failed to close: {closeTask.Exception!.InnerException}"); |
| | 0 | 158 | | } |
| | 0 | 159 | | |
| | 0 | 160 | | try |
| | 0 | 161 | | { |
| | 0 | 162 | | await connection.DisposeAsync().ConfigureAwait(false); |
| | 0 | 163 | | } |
| | 0 | 164 | | catch (Exception ex) |
| | 0 | 165 | | { |
| | 0 | 166 | | Trace($"{nameof(QuicConnection)} failed to dispose: {ex}"); |
| | 0 | 167 | | } |
| | 0 | 168 | | |
| | 0 | 169 | | if (_clientControl != null) |
| | 0 | 170 | | { |
| | 0 | 171 | | await _sendSettingsTask!.ConfigureAwait(false); |
| | 0 | 172 | | await _clientControl.DisposeAsync().ConfigureAwait(false); |
| | 0 | 173 | | _clientControl = null; |
| | 0 | 174 | | } |
| | 0 | 175 | | |
| | 0 | 176 | | }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); |
| | | 177 | | |
| | 0 | 178 | | MarkConnectionAsClosed(); |
| | 0 | 179 | | } |
| | 0 | 180 | | } |
| | | 181 | | |
| | | 182 | | /// <summary> |
| | | 183 | | /// When EnableMultipleHttp3Connections is false: always reserve a stream, return a bool indicating if the strea |
| | | 184 | | /// When EnableMultipleHttp3Connections is true: reserve a stream only if it's available meaning that the return |
| | | 185 | | /// </summary> |
| | | 186 | | public bool TryReserveStream() |
| | 0 | 187 | | { |
| | 0 | 188 | | bool singleConnection = !_pool.Settings.EnableMultipleHttp3Connections; |
| | | 189 | | |
| | 0 | 190 | | lock (SyncObj) |
| | 0 | 191 | | { |
| | | 192 | | // For the single connection case, we allow the counter to go below zero. |
| | 0 | 193 | | Debug.Assert(singleConnection || _availableRequestStreamsCount >= 0); |
| | | 194 | | |
| | 0 | 195 | | if (NetEventSource.Log.IsEnabled()) Trace($"_availableRequestStreamsCount = {_availableRequestStreamsCou |
| | | 196 | | |
| | 0 | 197 | | bool streamAvailable = _availableRequestStreamsCount > 0; |
| | | 198 | | |
| | | 199 | | // Do not let the counter to go below zero when EnableMultipleHttp3Connections is true. |
| | | 200 | | // This equivalent to an immediate ReleaseStream() for the case no stream is immediately available. |
| | 0 | 201 | | if (singleConnection || _availableRequestStreamsCount > 0) |
| | 0 | 202 | | { |
| | 0 | 203 | | --_availableRequestStreamsCount; |
| | 0 | 204 | | } |
| | | 205 | | |
| | 0 | 206 | | return streamAvailable; |
| | | 207 | | } |
| | 0 | 208 | | } |
| | | 209 | | |
| | | 210 | | public void ReleaseStream() |
| | 0 | 211 | | { |
| | 0 | 212 | | lock (SyncObj) |
| | 0 | 213 | | { |
| | 0 | 214 | | Debug.Assert(!_pool.Settings.EnableMultipleHttp3Connections || _availableRequestStreamsCount >= 0); |
| | | 215 | | |
| | 0 | 216 | | if (NetEventSource.Log.IsEnabled()) Trace($"_availableRequestStreamsCount = {_availableRequestStreamsCou |
| | 0 | 217 | | ++_availableRequestStreamsCount; |
| | | 218 | | |
| | 0 | 219 | | _availableStreamsWaiter?.SetResult(!ShuttingDown); |
| | 0 | 220 | | _availableStreamsWaiter = null; |
| | 0 | 221 | | } |
| | 0 | 222 | | } |
| | | 223 | | |
| | | 224 | | public void StreamCapacityCallback(QuicConnection connection, QuicStreamCapacityChangedArgs args) |
| | 0 | 225 | | { |
| | 0 | 226 | | Debug.Assert(_connection is null || connection == _connection); |
| | | 227 | | |
| | 0 | 228 | | lock (SyncObj) |
| | 0 | 229 | | { |
| | 0 | 230 | | Debug.Assert(_availableStreamsWaiter is null || _availableRequestStreamsCount >= 0); |
| | | 231 | | |
| | 0 | 232 | | if (NetEventSource.Log.IsEnabled()) Trace($"_availableRequestStreamsCount = {_availableRequestStreamsCou |
| | | 233 | | |
| | | 234 | | // Since _availableStreamsWaiter is only used in the multi-connection case, when _availableRequestStream |
| | | 235 | | // we don't need to check the value of _availableRequestStreamsCount here. |
| | 0 | 236 | | _availableRequestStreamsCount += args.BidirectionalIncrement; |
| | 0 | 237 | | _availableStreamsWaiter?.SetResult(!ShuttingDown); |
| | 0 | 238 | | _availableStreamsWaiter = null; |
| | 0 | 239 | | } |
| | 0 | 240 | | } |
| | | 241 | | |
| | | 242 | | public Task<bool> WaitForAvailableStreamsAsync() |
| | 0 | 243 | | { |
| | | 244 | | // In the single connection case, _availableStreamsWaiter notifications do not guarantee that _availableRequ |
| | 0 | 245 | | Debug.Assert(_pool.Settings.EnableMultipleHttp3Connections, "Calling WaitForAvailableStreamsAsync() is inval |
| | | 246 | | |
| | 0 | 247 | | lock (SyncObj) |
| | 0 | 248 | | { |
| | 0 | 249 | | Debug.Assert(_availableRequestStreamsCount >= 0); |
| | | 250 | | |
| | 0 | 251 | | if (ShuttingDown) |
| | 0 | 252 | | { |
| | 0 | 253 | | return Task.FromResult(false); |
| | | 254 | | } |
| | 0 | 255 | | if (_availableRequestStreamsCount > 0) |
| | 0 | 256 | | { |
| | 0 | 257 | | return Task.FromResult(true); |
| | | 258 | | } |
| | | 259 | | |
| | 0 | 260 | | Debug.Assert(_availableStreamsWaiter is null); |
| | 0 | 261 | | _availableStreamsWaiter = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronou |
| | 0 | 262 | | return _availableStreamsWaiter.Task; |
| | | 263 | | } |
| | 0 | 264 | | } |
| | | 265 | | |
| | | 266 | | public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, WaitForHttp3ConnectionActivity wait |
| | 0 | 267 | | { |
| | 0 | 268 | | request.ConnectionId = Id; |
| | | 269 | | |
| | | 270 | | // Allocate an active request |
| | 0 | 271 | | QuicStream? quicStream = null; |
| | 0 | 272 | | Http3RequestStream? requestStream = null; |
| | | 273 | | |
| | | 274 | | try |
| | 0 | 275 | | { |
| | 0 | 276 | | Exception? exception = null; |
| | | 277 | | try |
| | 0 | 278 | | { |
| | 0 | 279 | | QuicConnection? conn = _connection; |
| | 0 | 280 | | if (conn != null) |
| | 0 | 281 | | { |
| | | 282 | | // We found a connection in the pool, but it did not have available streams, OpenOutboundStreamA |
| | 0 | 283 | | if (!waitForConnectionActivity.Started && !streamAvailable) |
| | 0 | 284 | | { |
| | 0 | 285 | | waitForConnectionActivity.Start(); |
| | 0 | 286 | | } |
| | | 287 | | |
| | 0 | 288 | | quicStream = await conn.OpenOutboundStreamAsync(QuicStreamType.Bidirectional, cancellationToken) |
| | | 289 | | |
| | 0 | 290 | | requestStream = new Http3RequestStream(request, this, quicStream); |
| | 0 | 291 | | lock (SyncObj) |
| | 0 | 292 | | { |
| | 0 | 293 | | if (_activeRequests.Count == 0) |
| | 0 | 294 | | { |
| | 0 | 295 | | MarkConnectionAsNotIdle(); |
| | 0 | 296 | | } |
| | 0 | 297 | | _activeRequests.Add(quicStream, requestStream); |
| | 0 | 298 | | } |
| | 0 | 299 | | } |
| | 0 | 300 | | } |
| | | 301 | | // Swallow any exceptions caused by the connection being closed locally or even disposed due to a race. |
| | | 302 | | // Since quicStream will stay `null`, the code below will throw appropriate exception to retry the reque |
| | 0 | 303 | | catch (ObjectDisposedException e) |
| | 0 | 304 | | { |
| | 0 | 305 | | exception = e; |
| | 0 | 306 | | } |
| | 0 | 307 | | catch (QuicException e) when (e.QuicError != QuicError.OperationAborted) |
| | 0 | 308 | | { |
| | 0 | 309 | | exception = e; |
| | 0 | 310 | | } |
| | | 311 | | finally |
| | 0 | 312 | | { |
| | 0 | 313 | | waitForConnectionActivity.Stop(request, Pool, exception); |
| | 0 | 314 | | } |
| | | 315 | | |
| | 0 | 316 | | if (quicStream == null) |
| | 0 | 317 | | { |
| | 0 | 318 | | throw new HttpRequestException(HttpRequestError.Unknown, SR.net_http_request_aborted, null, RequestR |
| | | 319 | | } |
| | | 320 | | |
| | 0 | 321 | | requestStream!.StreamId = quicStream.Id; |
| | | 322 | | |
| | | 323 | | bool goAway; |
| | 0 | 324 | | lock (SyncObj) |
| | 0 | 325 | | { |
| | 0 | 326 | | goAway = _firstRejectedStreamId != -1 && requestStream.StreamId >= _firstRejectedStreamId; |
| | 0 | 327 | | } |
| | | 328 | | |
| | 0 | 329 | | if (goAway) |
| | 0 | 330 | | { |
| | 0 | 331 | | throw new HttpRequestException(HttpRequestError.Unknown, SR.net_http_request_aborted, null, RequestR |
| | | 332 | | } |
| | | 333 | | |
| | 0 | 334 | | waitForConnectionActivity.AssertActivityNotRunning(); |
| | 0 | 335 | | if (ConnectionSetupActivity is not null) ConnectionSetupDistributedTracing.AddConnectionLinkToRequestAct |
| | 0 | 336 | | if (NetEventSource.Log.IsEnabled()) Trace($"Sending request: {request}"); |
| | | 337 | | |
| | 0 | 338 | | Task<HttpResponseMessage> responseTask = requestStream.SendAsync(cancellationToken); |
| | | 339 | | |
| | | 340 | | // null out requestStream to avoid disposing in finally block. It is now in charge of disposing itself. |
| | 0 | 341 | | requestStream = null; |
| | | 342 | | |
| | 0 | 343 | | return await responseTask.ConfigureAwait(false); |
| | | 344 | | } |
| | 0 | 345 | | catch (QuicException ex) when (ex.QuicError == QuicError.OperationAborted) |
| | | 346 | | { |
| | | 347 | | // This will happen if we aborted _connection somewhere and we have pending OpenOutboundStreamAsync call |
| | | 348 | | // note that _abortException may be null if we closed the connection in response to a GOAWAY frame |
| | | 349 | | throw new HttpRequestException(HttpRequestError.Unknown, SR.net_http_client_execution_error, _abortExcep |
| | | 350 | | } |
| | | 351 | | finally |
| | 0 | 352 | | { |
| | 0 | 353 | | if (requestStream is not null) |
| | 0 | 354 | | { |
| | 0 | 355 | | await requestStream.DisposeAsync().ConfigureAwait(false); |
| | 0 | 356 | | } |
| | 0 | 357 | | } |
| | 0 | 358 | | } |
| | | 359 | | |
| | | 360 | | /// <summary> |
| | | 361 | | /// Aborts the connection with an error. |
| | | 362 | | /// </summary> |
| | | 363 | | /// <remarks> |
| | | 364 | | /// Used for e.g. I/O or connection-level frame parsing errors. |
| | | 365 | | /// </remarks> |
| | | 366 | | internal Exception Abort(Exception abortException) |
| | 0 | 367 | | { |
| | | 368 | | // Only observe the first exception we get. |
| | 0 | 369 | | Exception? firstException = Interlocked.CompareExchange(ref _abortException, abortException, null); |
| | | 370 | | |
| | 0 | 371 | | if (firstException != null) |
| | 0 | 372 | | { |
| | 0 | 373 | | if (NetEventSource.Log.IsEnabled() && !ReferenceEquals(firstException, abortException)) |
| | 0 | 374 | | { |
| | | 375 | | // Lost the race to set the field to another exception, so just trace this one. |
| | 0 | 376 | | Trace($"{nameof(abortException)}=={abortException}"); |
| | 0 | 377 | | } |
| | | 378 | | |
| | 0 | 379 | | return firstException; |
| | | 380 | | } |
| | | 381 | | |
| | | 382 | | // Stop sending requests to this connection. |
| | | 383 | | // Do not dispose the connection when invalidating as the rest of this method does exactly that: |
| | | 384 | | // set up _firstRejectedStreamId, close the connection with proper error code and CheckForShutdown. |
| | 0 | 385 | | _pool.InvalidateHttp3Connection(this, dispose: false); |
| | | 386 | | |
| | 0 | 387 | | long connectionResetErrorCode = (abortException as HttpProtocolException)?.ErrorCode ?? (long)Http3ErrorCode |
| | | 388 | | |
| | 0 | 389 | | lock (SyncObj) |
| | 0 | 390 | | { |
| | | 391 | | // Set _firstRejectedStreamId != -1 to make ShuttingDown = true. |
| | | 392 | | // It's possible GOAWAY is already being processed, in which case this would already be != -1. |
| | 0 | 393 | | if (_firstRejectedStreamId == -1) |
| | 0 | 394 | | { |
| | 0 | 395 | | _firstRejectedStreamId = long.MaxValue; |
| | 0 | 396 | | } |
| | | 397 | | |
| | | 398 | | // Abort the connection. This will cause all of our streams to abort on their next I/O. |
| | 0 | 399 | | if (_connection != null && _connectionClosedTask == null) |
| | 0 | 400 | | { |
| | 0 | 401 | | _connectionClosedTask = _connection.CloseAsync((long)connectionResetErrorCode).AsTask(); |
| | 0 | 402 | | } |
| | | 403 | | |
| | 0 | 404 | | CheckForShutdown(); |
| | 0 | 405 | | } |
| | | 406 | | |
| | 0 | 407 | | return abortException; |
| | 0 | 408 | | } |
| | | 409 | | |
| | | 410 | | private void OnServerGoAway(long firstRejectedStreamId) |
| | 0 | 411 | | { |
| | 0 | 412 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 413 | | { |
| | 0 | 414 | | Trace($"GOAWAY received. First rejected stream ID = {firstRejectedStreamId}"); |
| | 0 | 415 | | } |
| | | 416 | | |
| | | 417 | | // Stop sending requests to this connection. |
| | | 418 | | // Do not dispose the connection when invalidating as the rest of this method does exactly that: |
| | | 419 | | // set up _firstRejectedStreamId to the stream id from GO_AWAY frame and CheckForShutdown. |
| | 0 | 420 | | _pool.InvalidateHttp3Connection(this, dispose: false); |
| | | 421 | | |
| | 0 | 422 | | var streamsToGoAway = new List<Http3RequestStream>(); |
| | | 423 | | |
| | 0 | 424 | | lock (SyncObj) |
| | 0 | 425 | | { |
| | 0 | 426 | | if (_firstRejectedStreamId != -1 && firstRejectedStreamId > _firstRejectedStreamId) |
| | 0 | 427 | | { |
| | | 428 | | // Server can send multiple GOAWAY frames. |
| | | 429 | | // Spec says a server MUST NOT increase the stream ID in subsequent GOAWAYs, |
| | | 430 | | // but doesn't specify what client should do if that is violated. Ignore for now. |
| | 0 | 431 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 432 | | { |
| | 0 | 433 | | Trace("HTTP/3 server sent GOAWAY with increasing stream ID. Retried requests may have been doubl |
| | 0 | 434 | | } |
| | 0 | 435 | | return; |
| | | 436 | | } |
| | | 437 | | |
| | 0 | 438 | | _firstRejectedStreamId = firstRejectedStreamId; |
| | | 439 | | |
| | 0 | 440 | | foreach (KeyValuePair<QuicStream, Http3RequestStream> request in _activeRequests) |
| | 0 | 441 | | { |
| | 0 | 442 | | if (request.Value.StreamId >= firstRejectedStreamId) |
| | 0 | 443 | | { |
| | 0 | 444 | | streamsToGoAway.Add(request.Value); |
| | 0 | 445 | | } |
| | 0 | 446 | | } |
| | | 447 | | |
| | 0 | 448 | | CheckForShutdown(); |
| | 0 | 449 | | } |
| | | 450 | | |
| | | 451 | | // GOAWAY each stream outside of the lock, so they can acquire the lock to remove themselves from _activeReq |
| | 0 | 452 | | foreach (Http3RequestStream stream in streamsToGoAway) |
| | 0 | 453 | | { |
| | 0 | 454 | | stream.GoAway(); |
| | 0 | 455 | | } |
| | 0 | 456 | | } |
| | | 457 | | |
| | | 458 | | public void RemoveStream(QuicStream stream) |
| | 0 | 459 | | { |
| | 0 | 460 | | lock (SyncObj) |
| | 0 | 461 | | { |
| | 0 | 462 | | if (_activeRequests.Remove(stream)) |
| | 0 | 463 | | { |
| | 0 | 464 | | if (_activeRequests.Count == 0) |
| | 0 | 465 | | { |
| | 0 | 466 | | MarkConnectionAsIdle(); |
| | 0 | 467 | | } |
| | | 468 | | |
| | 0 | 469 | | if (ShuttingDown) |
| | 0 | 470 | | { |
| | 0 | 471 | | CheckForShutdown(); |
| | 0 | 472 | | } |
| | 0 | 473 | | } |
| | 0 | 474 | | } |
| | 0 | 475 | | } |
| | | 476 | | |
| | | 477 | | public override void Trace(string message, [CallerMemberName] string? memberName = null) => |
| | 0 | 478 | | Trace(0, _connection is not null ? $"{_connection} {message}" : message, memberName); |
| | | 479 | | |
| | | 480 | | internal void Trace(long streamId, string message, [CallerMemberName] string? memberName = null) => |
| | 0 | 481 | | NetEventSource.Log.HandlerMessage( |
| | 0 | 482 | | _pool?.GetHashCode() ?? 0, // pool ID |
| | 0 | 483 | | GetHashCode(), // connection ID |
| | 0 | 484 | | (int)streamId, // stream ID |
| | 0 | 485 | | memberName, // method name |
| | 0 | 486 | | message); // message |
| | | 487 | | |
| | | 488 | | private async Task SendSettingsAsync() |
| | 0 | 489 | | { |
| | | 490 | | try |
| | 0 | 491 | | { |
| | 0 | 492 | | _clientControl = await _connection!.OpenOutboundStreamAsync(QuicStreamType.Unidirectional).ConfigureAwai |
| | | 493 | | |
| | | 494 | | // Server MUST NOT abort our control stream, setup a continuation which will react accordingly |
| | 0 | 495 | | _ = _clientControl.WritesClosed.ContinueWith(t => |
| | 0 | 496 | | { |
| | 0 | 497 | | if (t.Exception?.InnerException is QuicException ex && ex.QuicError == QuicError.StreamAborted) |
| | 0 | 498 | | { |
| | 0 | 499 | | Abort(HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.ClosedCriticalStream)) |
| | 0 | 500 | | } |
| | 0 | 501 | | }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Current); |
| | | 502 | | |
| | 0 | 503 | | await _clientControl.WriteAsync(_pool.Settings.Http3SettingsFrame, CancellationToken.None).ConfigureAwai |
| | 0 | 504 | | } |
| | 0 | 505 | | catch (QuicException ex) when (ex.QuicError == QuicError.ConnectionAborted) |
| | 0 | 506 | | { |
| | 0 | 507 | | Debug.Assert(ex.ApplicationErrorCode.HasValue); |
| | 0 | 508 | | Http3ErrorCode code = (Http3ErrorCode)ex.ApplicationErrorCode.Value; |
| | | 509 | | |
| | 0 | 510 | | Abort(HttpProtocolException.CreateHttp3ConnectionException(code, SR.net_http_http3_connection_close)); |
| | 0 | 511 | | } |
| | 0 | 512 | | catch (Exception ex) |
| | 0 | 513 | | { |
| | 0 | 514 | | Abort(ex); |
| | 0 | 515 | | } |
| | 0 | 516 | | } |
| | | 517 | | |
| | | 518 | | public static unsafe byte[] BuildSettingsFrame(HttpConnectionSettings settings) |
| | 0 | 519 | | { |
| | 0 | 520 | | Span<byte> buffer = stackalloc byte[4 + VariableLengthIntegerHelper.MaximumEncodedLength]; |
| | | 521 | | |
| | 0 | 522 | | int integerLength = VariableLengthIntegerHelper.WriteInteger(buffer.Slice(4), settings.MaxResponseHeadersByt |
| | 0 | 523 | | int payloadLength = 1 + integerLength; // includes the setting ID and the integer value. |
| | 0 | 524 | | Debug.Assert(payloadLength <= VariableLengthIntegerHelper.OneByteLimit); |
| | | 525 | | |
| | 0 | 526 | | buffer[0] = (byte)Http3StreamType.Control; |
| | 0 | 527 | | buffer[1] = (byte)Http3FrameType.Settings; |
| | 0 | 528 | | buffer[2] = (byte)payloadLength; |
| | 0 | 529 | | buffer[3] = (byte)Http3SettingType.MaxHeaderListSize; |
| | | 530 | | |
| | 0 | 531 | | return buffer.Slice(0, 4 + integerLength).ToArray(); |
| | 0 | 532 | | } |
| | | 533 | | |
| | | 534 | | /// <summary> |
| | | 535 | | /// Accepts unidirectional streams (control, QPack, ...) from the server. |
| | | 536 | | /// </summary> |
| | | 537 | | private async Task AcceptStreamsAsync() |
| | 0 | 538 | | { |
| | | 539 | | try |
| | 0 | 540 | | { |
| | 0 | 541 | | while (true) |
| | 0 | 542 | | { |
| | | 543 | | ValueTask<QuicStream> streamTask; |
| | | 544 | | |
| | 0 | 545 | | lock (SyncObj) |
| | 0 | 546 | | { |
| | 0 | 547 | | if (ShuttingDown) |
| | 0 | 548 | | { |
| | 0 | 549 | | return; |
| | | 550 | | } |
| | | 551 | | |
| | | 552 | | // No cancellation token is needed here; we expect the operation to cancel itself when _connecti |
| | 0 | 553 | | streamTask = _connection!.AcceptInboundStreamAsync(CancellationToken.None); |
| | 0 | 554 | | } |
| | | 555 | | |
| | 0 | 556 | | QuicStream stream = await streamTask.ConfigureAwait(false); |
| | | 557 | | |
| | | 558 | | // This process is cleaned up when _connection is disposed, and errors are observed via Abort(). |
| | 0 | 559 | | _ = ProcessServerStreamAsync(stream); |
| | 0 | 560 | | } |
| | | 561 | | } |
| | 0 | 562 | | catch (QuicException ex) when (ex.QuicError == QuicError.OperationAborted) |
| | 0 | 563 | | { |
| | | 564 | | // Shutdown initiated by us, no need to abort. |
| | 0 | 565 | | } |
| | 0 | 566 | | catch (QuicException ex) when (ex.QuicError == QuicError.ConnectionAborted) |
| | 0 | 567 | | { |
| | 0 | 568 | | Debug.Assert(ex.ApplicationErrorCode.HasValue); |
| | 0 | 569 | | Http3ErrorCode code = (Http3ErrorCode)ex.ApplicationErrorCode.Value; |
| | | 570 | | |
| | 0 | 571 | | Abort(HttpProtocolException.CreateHttp3ConnectionException(code, SR.net_http_http3_connection_close)); |
| | 0 | 572 | | } |
| | 0 | 573 | | catch (Exception ex) |
| | 0 | 574 | | { |
| | 0 | 575 | | Abort(ex); |
| | 0 | 576 | | } |
| | 0 | 577 | | } |
| | | 578 | | |
| | | 579 | | /// <summary> |
| | | 580 | | /// Routes a stream to an appropriate stream-type-specific processor |
| | | 581 | | /// </summary> |
| | | 582 | | private async Task ProcessServerStreamAsync(QuicStream stream) |
| | 0 | 583 | | { |
| | 0 | 584 | | ArrayBuffer buffer = default; |
| | | 585 | | |
| | | 586 | | try |
| | 0 | 587 | | { |
| | 0 | 588 | | await using (stream.ConfigureAwait(false)) |
| | 0 | 589 | | { |
| | | 590 | | // Check if this is a bidirectional stream (which we don't support from the server). |
| | 0 | 591 | | if (stream.CanWrite) |
| | 0 | 592 | | { |
| | | 593 | | // Server initiated bidirectional streams are either push streams or extensions, and we support |
| | 0 | 594 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.StreamCreationError); |
| | | 595 | | } |
| | | 596 | | |
| | 0 | 597 | | buffer = new ArrayBuffer(initialSize: 32, usePool: true); |
| | | 598 | | |
| | | 599 | | // Read the stream type, which is a variable-length integer. |
| | | 600 | | // This may require multiple reads if the integer is encoded in multiple bytes. |
| | | 601 | | long streamType; |
| | 0 | 602 | | while (true) |
| | 0 | 603 | | { |
| | | 604 | | int bytesRead; |
| | | 605 | | try |
| | 0 | 606 | | { |
| | 0 | 607 | | bytesRead = await stream.ReadAsync(buffer.AvailableMemory, CancellationToken.None).Configure |
| | 0 | 608 | | } |
| | 0 | 609 | | catch (QuicException ex) when (ex.QuicError == QuicError.StreamAborted) |
| | 0 | 610 | | { |
| | | 611 | | // Treat identical to receiving 0. See below comment. |
| | 0 | 612 | | bytesRead = 0; |
| | 0 | 613 | | } |
| | | 614 | | |
| | 0 | 615 | | if (bytesRead == 0) |
| | 0 | 616 | | { |
| | | 617 | | // https://www.rfc-editor.org/rfc/rfc9114.html#name-unidirectional-streams |
| | | 618 | | // A sender can close or reset a unidirectional stream unless otherwise specified. A receive |
| | | 619 | | // tolerate unidirectional streams being closed or reset prior to the reception of the unidi |
| | | 620 | | // stream header. |
| | 0 | 621 | | return; |
| | | 622 | | } |
| | | 623 | | |
| | 0 | 624 | | buffer.Commit(bytesRead); |
| | | 625 | | |
| | 0 | 626 | | if (VariableLengthIntegerHelper.TryRead(buffer.ActiveSpan, out streamType, out int streamTypeLen |
| | 0 | 627 | | { |
| | | 628 | | // Successfully read the stream type. |
| | 0 | 629 | | buffer.Discard(streamTypeLength); |
| | 0 | 630 | | break; |
| | | 631 | | } |
| | 0 | 632 | | } |
| | | 633 | | |
| | 0 | 634 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 635 | | { |
| | 0 | 636 | | NetEventSource.Info(this, $"Received server-initiated unidirectional stream of type {streamType} |
| | 0 | 637 | | } |
| | | 638 | | |
| | | 639 | | // Process the stream based on its type. |
| | 0 | 640 | | switch ((Http3StreamType)streamType) |
| | | 641 | | { |
| | | 642 | | case Http3StreamType.Control: |
| | 0 | 643 | | if (Interlocked.Exchange(ref _haveServerControlStream, true)) |
| | 0 | 644 | | { |
| | | 645 | | // A second control stream has been received. |
| | 0 | 646 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.StreamCreation |
| | | 647 | | } |
| | | 648 | | |
| | | 649 | | // Ownership of buffer is transferred to ProcessServerControlStreamAsync. |
| | 0 | 650 | | ArrayBuffer bufferCopy = buffer; |
| | 0 | 651 | | buffer = default; |
| | | 652 | | |
| | 0 | 653 | | await ProcessServerControlStreamAsync(stream, bufferCopy).ConfigureAwait(false); |
| | 0 | 654 | | return; |
| | | 655 | | case Http3StreamType.QPackDecoder: |
| | 0 | 656 | | if (Interlocked.Exchange(ref _haveServerQpackDecodeStream, true)) |
| | 0 | 657 | | { |
| | | 658 | | // A second QPack decode stream has been received. |
| | 0 | 659 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.StreamCreation |
| | | 660 | | } |
| | | 661 | | |
| | | 662 | | // The stream must not be closed, but we aren't using QPACK right now -- ignore. |
| | 0 | 663 | | buffer.Dispose(); |
| | 0 | 664 | | await stream.CopyToAsync(Stream.Null).ConfigureAwait(false); |
| | 0 | 665 | | return; |
| | | 666 | | case Http3StreamType.QPackEncoder: |
| | 0 | 667 | | if (Interlocked.Exchange(ref _haveServerQpackEncodeStream, true)) |
| | 0 | 668 | | { |
| | | 669 | | // A second QPack encode stream has been received. |
| | 0 | 670 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.StreamCreation |
| | | 671 | | } |
| | | 672 | | |
| | | 673 | | // We haven't enabled QPack in our SETTINGS frame, so we shouldn't receive any meaningful da |
| | | 674 | | // However, the standard says the stream must not be closed for the lifetime of the connecti |
| | 0 | 675 | | buffer.Dispose(); |
| | 0 | 676 | | await stream.CopyToAsync(Stream.Null).ConfigureAwait(false); |
| | 0 | 677 | | return; |
| | | 678 | | case Http3StreamType.Push: |
| | | 679 | | // We don't support push streams. |
| | | 680 | | // Because no maximum push stream ID was negotiated via a MAX_PUSH_ID frame, server should n |
| | 0 | 681 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.IdError); |
| | | 682 | | default: |
| | | 683 | | // Unknown stream type. Per spec, these must be ignored and aborted but not be considered a |
| | 0 | 684 | | stream.Abort(QuicAbortDirection.Read, (long)Http3ErrorCode.StreamCreationError); |
| | 0 | 685 | | return; |
| | | 686 | | } |
| | | 687 | | } |
| | 0 | 688 | | } |
| | 0 | 689 | | catch (QuicException ex) when (ex.QuicError == QuicError.OperationAborted) |
| | | 690 | | { |
| | | 691 | | // ignore the exception, we have already closed the connection |
| | | 692 | | } |
| | 0 | 693 | | catch (QuicException ex) when (ex.QuicError == QuicError.ConnectionAborted) |
| | | 694 | | { |
| | | 695 | | Debug.Assert(ex.ApplicationErrorCode.HasValue); |
| | | 696 | | Http3ErrorCode code = (Http3ErrorCode)ex.ApplicationErrorCode.Value; |
| | | 697 | | |
| | | 698 | | Abort(HttpProtocolException.CreateHttp3ConnectionException(code, SR.net_http_http3_connection_close)); |
| | | 699 | | } |
| | 0 | 700 | | catch (Exception ex) |
| | 0 | 701 | | { |
| | 0 | 702 | | Abort(ex); |
| | 0 | 703 | | } |
| | | 704 | | finally |
| | 0 | 705 | | { |
| | 0 | 706 | | buffer.Dispose(); |
| | 0 | 707 | | } |
| | 0 | 708 | | } |
| | | 709 | | |
| | | 710 | | /// <summary> |
| | | 711 | | /// Reads the server's control stream. |
| | | 712 | | /// </summary> |
| | | 713 | | private async Task ProcessServerControlStreamAsync(QuicStream stream, ArrayBuffer buffer) |
| | 0 | 714 | | { |
| | | 715 | | try |
| | 0 | 716 | | { |
| | 0 | 717 | | using (buffer) |
| | 0 | 718 | | { |
| | | 719 | | // Read the first frame of the control stream. Per spec: |
| | | 720 | | // A SETTINGS frame MUST be sent as the first frame of each control stream. |
| | | 721 | | |
| | 0 | 722 | | (Http3FrameType? frameType, long payloadLength) = await ReadFrameEnvelopeAsync().ConfigureAwait(fals |
| | | 723 | | |
| | 0 | 724 | | if (frameType == null) |
| | 0 | 725 | | { |
| | | 726 | | // Connection closed prematurely, expected SETTINGS frame. |
| | 0 | 727 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.ClosedCriticalStream); |
| | | 728 | | } |
| | | 729 | | |
| | 0 | 730 | | if (frameType != Http3FrameType.Settings) |
| | 0 | 731 | | { |
| | 0 | 732 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.MissingSettings); |
| | | 733 | | } |
| | | 734 | | |
| | 0 | 735 | | await ProcessSettingsFrameAsync(payloadLength).ConfigureAwait(false); |
| | | 736 | | |
| | | 737 | | // Read subsequent frames. |
| | | 738 | | |
| | 0 | 739 | | while (true) |
| | 0 | 740 | | { |
| | 0 | 741 | | (frameType, payloadLength) = await ReadFrameEnvelopeAsync().ConfigureAwait(false); |
| | | 742 | | |
| | 0 | 743 | | switch (frameType) |
| | | 744 | | { |
| | | 745 | | case Http3FrameType.GoAway: |
| | 0 | 746 | | await ProcessGoAwayFrameAsync(payloadLength).ConfigureAwait(false); |
| | 0 | 747 | | break; |
| | | 748 | | case Http3FrameType.Settings: |
| | | 749 | | // If an endpoint receives a second SETTINGS frame on the control stream, the endpoint M |
| | 0 | 750 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.UnexpectedFram |
| | | 751 | | case Http3FrameType.Headers: // Servers should not send these frames to a control stream. |
| | | 752 | | case Http3FrameType.Data: |
| | | 753 | | case Http3FrameType.MaxPushId: |
| | | 754 | | case Http3FrameType.ReservedHttp2Priority: // These frames are explicitly reserved and must |
| | | 755 | | case Http3FrameType.ReservedHttp2Ping: |
| | | 756 | | case Http3FrameType.ReservedHttp2WindowUpdate: |
| | | 757 | | case Http3FrameType.ReservedHttp2Continuation: |
| | 0 | 758 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 759 | | { |
| | 0 | 760 | | Trace($"Received reserved frame: {frameType}"); |
| | 0 | 761 | | } |
| | 0 | 762 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.UnexpectedFram |
| | | 763 | | case Http3FrameType.PushPromise: |
| | | 764 | | case Http3FrameType.CancelPush: |
| | | 765 | | // Because we haven't sent any MAX_PUSH_ID frame, it is invalid to receive any push-rela |
| | 0 | 766 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.IdError); |
| | | 767 | | case null: |
| | | 768 | | // End of stream reached. If we're shutting down, stop looping. Otherwise, this is an er |
| | | 769 | | bool shuttingDown; |
| | 0 | 770 | | lock (SyncObj) |
| | 0 | 771 | | { |
| | 0 | 772 | | shuttingDown = ShuttingDown; |
| | 0 | 773 | | } |
| | 0 | 774 | | if (!shuttingDown) |
| | 0 | 775 | | { |
| | 0 | 776 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 777 | | { |
| | 0 | 778 | | Trace($"Control stream closed by the server."); |
| | 0 | 779 | | } |
| | 0 | 780 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.ClosedCrit |
| | | 781 | | } |
| | 0 | 782 | | return; |
| | | 783 | | default: |
| | 0 | 784 | | await SkipUnknownPayloadAsync(payloadLength).ConfigureAwait(false); |
| | 0 | 785 | | break; |
| | | 786 | | } |
| | 0 | 787 | | } |
| | | 788 | | } |
| | | 789 | | } |
| | 0 | 790 | | catch (QuicException ex) when (ex.QuicError == QuicError.StreamAborted) |
| | 0 | 791 | | { |
| | | 792 | | // Peers MUST NOT close the control stream |
| | 0 | 793 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.ClosedCriticalStream); |
| | | 794 | | } |
| | | 795 | | |
| | | 796 | | async ValueTask<(Http3FrameType? frameType, long payloadLength)> ReadFrameEnvelopeAsync() |
| | 0 | 797 | | { |
| | | 798 | | long frameType, payloadLength; |
| | | 799 | | int bytesRead; |
| | | 800 | | |
| | 0 | 801 | | while (!Http3Frame.TryReadIntegerPair(buffer.ActiveSpan, out frameType, out payloadLength, out bytesRead |
| | 0 | 802 | | { |
| | 0 | 803 | | buffer.EnsureAvailableSpace(VariableLengthIntegerHelper.MaximumEncodedLength * 2); |
| | 0 | 804 | | bytesRead = await stream.ReadAsync(buffer.AvailableMemory, CancellationToken.None).ConfigureAwait(fa |
| | | 805 | | |
| | 0 | 806 | | if (bytesRead != 0) |
| | 0 | 807 | | { |
| | 0 | 808 | | buffer.Commit(bytesRead); |
| | 0 | 809 | | } |
| | 0 | 810 | | else if (buffer.ActiveLength == 0) |
| | 0 | 811 | | { |
| | | 812 | | // End of stream. |
| | 0 | 813 | | return (null, 0); |
| | | 814 | | } |
| | | 815 | | else |
| | 0 | 816 | | { |
| | | 817 | | // Our buffer has partial frame data in it but not enough to complete the read: bail out. |
| | 0 | 818 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.FrameError); |
| | | 819 | | } |
| | 0 | 820 | | } |
| | | 821 | | |
| | 0 | 822 | | buffer.Discard(bytesRead); |
| | | 823 | | |
| | 0 | 824 | | return ((Http3FrameType)frameType, payloadLength); |
| | 0 | 825 | | } |
| | | 826 | | |
| | | 827 | | async ValueTask ProcessSettingsFrameAsync(long settingsPayloadLength) |
| | 0 | 828 | | { |
| | 0 | 829 | | while (settingsPayloadLength != 0) |
| | 0 | 830 | | { |
| | | 831 | | long settingId, settingValue; |
| | | 832 | | int bytesRead; |
| | | 833 | | |
| | 0 | 834 | | while (!Http3Frame.TryReadIntegerPair(buffer.ActiveSpan, out settingId, out settingValue, out bytesR |
| | 0 | 835 | | { |
| | 0 | 836 | | buffer.EnsureAvailableSpace(VariableLengthIntegerHelper.MaximumEncodedLength * 2); |
| | 0 | 837 | | bytesRead = await stream.ReadAsync(buffer.AvailableMemory, CancellationToken.None).ConfigureAwai |
| | | 838 | | |
| | 0 | 839 | | if (bytesRead != 0) |
| | 0 | 840 | | { |
| | 0 | 841 | | buffer.Commit(bytesRead); |
| | 0 | 842 | | } |
| | | 843 | | else |
| | 0 | 844 | | { |
| | | 845 | | // Our buffer has partial frame data in it but not enough to complete the read: bail out. |
| | 0 | 846 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.FrameError); |
| | | 847 | | } |
| | 0 | 848 | | } |
| | | 849 | | |
| | 0 | 850 | | settingsPayloadLength -= bytesRead; |
| | | 851 | | |
| | 0 | 852 | | if (settingsPayloadLength < 0) |
| | 0 | 853 | | { |
| | | 854 | | // An integer was encoded past the payload length. |
| | | 855 | | // A frame payload that contains additional bytes after the identified fields or a frame payload |
| | 0 | 856 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.FrameError); |
| | | 857 | | } |
| | | 858 | | |
| | 0 | 859 | | buffer.Discard(bytesRead); |
| | | 860 | | |
| | 0 | 861 | | if (NetEventSource.Log.IsEnabled()) Trace($"Applying setting {(Http3SettingType)settingId}={settingV |
| | | 862 | | |
| | 0 | 863 | | switch ((Http3SettingType)settingId) |
| | | 864 | | { |
| | | 865 | | case Http3SettingType.MaxHeaderListSize: |
| | 0 | 866 | | _maxHeaderListSize = (uint)Math.Min((ulong)settingValue, uint.MaxValue); |
| | 0 | 867 | | _pool._lastSeenHttp3MaxHeaderListSize = _maxHeaderListSize; |
| | 0 | 868 | | break; |
| | | 869 | | case Http3SettingType.ReservedHttp2EnablePush: |
| | | 870 | | case Http3SettingType.ReservedHttp2MaxConcurrentStreams: |
| | | 871 | | case Http3SettingType.ReservedHttp2InitialWindowSize: |
| | | 872 | | case Http3SettingType.ReservedHttp2MaxFrameSize: |
| | | 873 | | // Per https://tools.ietf.org/html/draft-ietf-quic-http-31#section-7.2.4.1 |
| | | 874 | | // these settings IDs are reserved and must never be sent. |
| | 0 | 875 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.SettingsError); |
| | | 876 | | } |
| | 0 | 877 | | } |
| | 0 | 878 | | } |
| | | 879 | | |
| | | 880 | | async ValueTask ProcessGoAwayFrameAsync(long goawayPayloadLength) |
| | 0 | 881 | | { |
| | | 882 | | long firstRejectedStreamId; |
| | | 883 | | int bytesRead; |
| | | 884 | | |
| | 0 | 885 | | while (!VariableLengthIntegerHelper.TryRead(buffer.ActiveSpan, out firstRejectedStreamId, out bytesRead) |
| | 0 | 886 | | { |
| | 0 | 887 | | buffer.EnsureAvailableSpace(VariableLengthIntegerHelper.MaximumEncodedLength); |
| | 0 | 888 | | bytesRead = await stream.ReadAsync(buffer.AvailableMemory, CancellationToken.None).ConfigureAwait(fa |
| | | 889 | | |
| | 0 | 890 | | if (bytesRead != 0) |
| | 0 | 891 | | { |
| | 0 | 892 | | buffer.Commit(bytesRead); |
| | 0 | 893 | | } |
| | | 894 | | else |
| | 0 | 895 | | { |
| | | 896 | | // Our buffer has partial frame data in it but not enough to complete the read: bail out. |
| | 0 | 897 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.FrameError); |
| | | 898 | | } |
| | 0 | 899 | | } |
| | | 900 | | |
| | 0 | 901 | | buffer.Discard(bytesRead); |
| | 0 | 902 | | if (bytesRead != goawayPayloadLength) |
| | 0 | 903 | | { |
| | | 904 | | // Frame contains unknown extra data after the integer. |
| | 0 | 905 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.FrameError); |
| | | 906 | | } |
| | | 907 | | |
| | 0 | 908 | | OnServerGoAway(firstRejectedStreamId); |
| | 0 | 909 | | } |
| | | 910 | | |
| | | 911 | | async ValueTask SkipUnknownPayloadAsync(long payloadLength) |
| | 0 | 912 | | { |
| | 0 | 913 | | while (payloadLength != 0) |
| | 0 | 914 | | { |
| | 0 | 915 | | if (buffer.ActiveLength == 0) |
| | 0 | 916 | | { |
| | 0 | 917 | | int bytesRead = await stream.ReadAsync(buffer.AvailableMemory, CancellationToken.None).Configure |
| | | 918 | | |
| | 0 | 919 | | if (bytesRead != 0) |
| | 0 | 920 | | { |
| | 0 | 921 | | buffer.Commit(bytesRead); |
| | 0 | 922 | | } |
| | | 923 | | else |
| | 0 | 924 | | { |
| | | 925 | | // Our buffer has partial frame data in it but not enough to complete the read: bail out. |
| | 0 | 926 | | throw HttpProtocolException.CreateHttp3ConnectionException(Http3ErrorCode.FrameError); |
| | | 927 | | } |
| | 0 | 928 | | } |
| | | 929 | | |
| | 0 | 930 | | long readLength = Math.Min(payloadLength, buffer.ActiveLength); |
| | 0 | 931 | | buffer.Discard((int)readLength); |
| | 0 | 932 | | payloadLength -= readLength; |
| | 0 | 933 | | } |
| | 0 | 934 | | } |
| | 0 | 935 | | } |
| | | 936 | | } |
| | | 937 | | |
| | | 938 | | /// <summary> |
| | | 939 | | /// Tracks telemetry signals associated with the time period an HTTP/3 request spends waiting for a usable HTTP/3 co |
| | | 940 | | /// the wait_for_connection Activity, the RequestLeftQueue EventSource event and the http.client.request.time_in_que |
| | | 941 | | /// </summary> |
| | | 942 | | internal struct WaitForHttp3ConnectionActivity |
| | | 943 | | { |
| | | 944 | | // The HttpConnectionSettings -> SocketsHttpHandlerMetrics indirection is needed for the trimmer. |
| | | 945 | | private HttpConnectionSettings _settings; |
| | | 946 | | private readonly HttpAuthority _authority; |
| | | 947 | | private Activity? _activity; |
| | | 948 | | private long _startTimestamp; |
| | | 949 | | |
| | | 950 | | public WaitForHttp3ConnectionActivity(HttpConnectionSettings settings, HttpAuthority authority) |
| | | 951 | | { |
| | | 952 | | _settings = settings; |
| | | 953 | | _authority = authority; |
| | | 954 | | } |
| | | 955 | | |
| | | 956 | | public bool Started { get; private set; } |
| | | 957 | | |
| | | 958 | | public void Start() |
| | | 959 | | { |
| | | 960 | | Debug.Assert(!Started); |
| | | 961 | | _startTimestamp = HttpTelemetry.Log.IsEnabled() || (GlobalHttpSettings.MetricsHandler.IsGloballyEnabled && _ |
| | | 962 | | _activity = ConnectionSetupDistributedTracing.StartWaitForConnectionActivity(_authority); |
| | | 963 | | Started = true; |
| | | 964 | | } |
| | | 965 | | |
| | | 966 | | public void Stop(HttpRequestMessage request, HttpConnectionPool pool, Exception? exception) |
| | | 967 | | { |
| | | 968 | | if (exception is not null) |
| | | 969 | | { |
| | | 970 | | ConnectionSetupDistributedTracing.ReportError(_activity, exception); |
| | | 971 | | } |
| | | 972 | | |
| | | 973 | | _activity?.Stop(); |
| | | 974 | | |
| | | 975 | | if (_startTimestamp != 0) |
| | | 976 | | { |
| | | 977 | | TimeSpan duration = Stopwatch.GetElapsedTime(_startTimestamp); |
| | | 978 | | |
| | | 979 | | if (GlobalHttpSettings.MetricsHandler.IsGloballyEnabled) |
| | | 980 | | { |
| | | 981 | | _settings._metrics!.RequestLeftQueue(request, pool, duration, versionMajor: 3); |
| | | 982 | | } |
| | | 983 | | if (HttpTelemetry.Log.IsEnabled()) |
| | | 984 | | { |
| | | 985 | | HttpTelemetry.Log.RequestLeftQueue(3, duration); |
| | | 986 | | } |
| | | 987 | | } |
| | | 988 | | } |
| | | 989 | | |
| | | 990 | | [Conditional("DEBUG")] |
| | | 991 | | public void AssertActivityNotRunning() |
| | | 992 | | { |
| | | 993 | | Debug.Assert(_activity?.IsStopped != false); |
| | | 994 | | } |
| | | 995 | | } |
| | | 996 | | } |
| | | 997 | | |