| | | 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.Buffers; |
| | | 5 | | using System.Buffers.Text; |
| | | 6 | | using System.Diagnostics; |
| | | 7 | | using System.Globalization; |
| | | 8 | | using System.IO; |
| | | 9 | | using System.Net.Http.Headers; |
| | | 10 | | using System.Net.Sockets; |
| | | 11 | | using System.Runtime.CompilerServices; |
| | | 12 | | using System.Text; |
| | | 13 | | using System.Threading; |
| | | 14 | | using System.Threading.Tasks; |
| | | 15 | | |
| | | 16 | | namespace System.Net.Http |
| | | 17 | | { |
| | | 18 | | internal sealed partial class HttpConnection : HttpConnectionBase |
| | | 19 | | { |
| | | 20 | | /// <summary>Default size of the read buffer used for the connection.</summary> |
| | | 21 | | private const int InitialReadBufferSize = |
| | | 22 | | #if DEBUG |
| | | 23 | | 10; |
| | | 24 | | #else |
| | | 25 | | 4096; |
| | | 26 | | #endif |
| | | 27 | | /// <summary>Default size of the write buffer used for the connection.</summary> |
| | | 28 | | private const int InitialWriteBufferSize = InitialReadBufferSize; |
| | | 29 | | /// <summary> |
| | | 30 | | /// Size after which we'll close the connection rather than send the payload in response |
| | | 31 | | /// to final error status code sent by the server when using Expect: 100-continue. |
| | | 32 | | /// </summary> |
| | | 33 | | private const int Expect100ErrorSendThreshold = 1024; |
| | | 34 | | /// <summary>How long a chunk indicator is allowed to be.</summary> |
| | | 35 | | /// <remarks> |
| | | 36 | | /// While most chunks indicators will contain no more than ulong.MaxValue.ToString("X").Length characters, |
| | | 37 | | /// "chunk extensions" are allowed. We place a limit on how long a line can be to avoid OOM issues if an |
| | | 38 | | /// infinite chunk length is sent. This value is arbitrary and can be changed as needed. |
| | | 39 | | /// </remarks> |
| | | 40 | | private const int MaxChunkBytesAllowed = 16 * 1024; |
| | | 41 | | |
| | 0 | 42 | | private static readonly ulong s_http10Bytes = BitConverter.ToUInt64("HTTP/1.0"u8); |
| | 0 | 43 | | private static readonly ulong s_http11Bytes = BitConverter.ToUInt64("HTTP/1.1"u8); |
| | | 44 | | |
| | | 45 | | internal readonly Stream _stream; |
| | | 46 | | private readonly TransportContext? _transportContext; |
| | | 47 | | |
| | | 48 | | private HttpRequestMessage? _currentRequest; |
| | | 49 | | private ArrayBuffer _writeBuffer; |
| | | 50 | | private int _allowedReadLineBytes; |
| | | 51 | | |
| | | 52 | | /// <summary>Reusable array used to get the values for each header being written to the wire.</summary> |
| | | 53 | | [ThreadStatic] |
| | | 54 | | private static string[]? t_headerValues; |
| | | 55 | | |
| | | 56 | | private const int ReadAheadTask_NotStarted = 0; |
| | | 57 | | private const int ReadAheadTask_Started = 1; |
| | | 58 | | private const int ReadAheadTask_CompletionReserved = 2; |
| | | 59 | | private const int ReadAheadTask_Completed = 3; |
| | | 60 | | private int _readAheadTaskStatus; |
| | | 61 | | private ValueTask<int> _readAheadTask; |
| | | 62 | | private ArrayBuffer _readBuffer; |
| | | 63 | | |
| | | 64 | | private int _keepAliveTimeoutSeconds; // 0 == no timeout |
| | | 65 | | private bool _inUse; |
| | | 66 | | private bool _detachedFromPool; |
| | | 67 | | private bool _canRetry; |
| | | 68 | | private bool _connectionClose; // Connection: close was seen on last response |
| | | 69 | | |
| | | 70 | | private volatile bool _disposed; |
| | | 71 | | |
| | | 72 | | public HttpConnection( |
| | | 73 | | HttpConnectionPool pool, |
| | | 74 | | Stream stream, |
| | | 75 | | TransportContext? transportContext, |
| | | 76 | | Activity? connectionSetupActivity, |
| | | 77 | | IPEndPoint? remoteEndPoint) |
| | 0 | 78 | | : base(pool, connectionSetupActivity, remoteEndPoint) |
| | 0 | 79 | | { |
| | 0 | 80 | | Debug.Assert(stream != null); |
| | | 81 | | |
| | 0 | 82 | | _stream = stream; |
| | | 83 | | |
| | 0 | 84 | | _transportContext = transportContext; |
| | | 85 | | |
| | 0 | 86 | | _writeBuffer = new ArrayBuffer(InitialWriteBufferSize, usePool: false); |
| | 0 | 87 | | _readBuffer = new ArrayBuffer(InitialReadBufferSize, usePool: false); |
| | | 88 | | |
| | 0 | 89 | | if (NetEventSource.Log.IsEnabled()) TraceConnection(_stream); |
| | 0 | 90 | | } |
| | | 91 | | |
| | 0 | 92 | | ~HttpConnection() => Dispose(disposing: false); |
| | | 93 | | |
| | 0 | 94 | | public override void Dispose() => Dispose(disposing: true); |
| | | 95 | | |
| | | 96 | | private void Dispose(bool disposing) |
| | 0 | 97 | | { |
| | | 98 | | // Ensure we're only disposed once. Dispose could be called concurrently, for example, |
| | | 99 | | // if the request and the response were running concurrently and both incurred an exception. |
| | 0 | 100 | | if (!Interlocked.Exchange(ref _disposed, true)) |
| | 0 | 101 | | { |
| | 0 | 102 | | if (NetEventSource.Log.IsEnabled()) Trace("Connection closing."); |
| | | 103 | | |
| | 0 | 104 | | MarkConnectionAsClosed(); |
| | | 105 | | |
| | 0 | 106 | | if (!_detachedFromPool) |
| | 0 | 107 | | { |
| | 0 | 108 | | _pool.InvalidateHttp11Connection(this, disposing); |
| | 0 | 109 | | } |
| | | 110 | | |
| | 0 | 111 | | if (disposing) |
| | 0 | 112 | | { |
| | 0 | 113 | | GC.SuppressFinalize(this); |
| | 0 | 114 | | _stream.Dispose(); |
| | 0 | 115 | | } |
| | 0 | 116 | | } |
| | 0 | 117 | | } |
| | | 118 | | |
| | | 119 | | private bool ReadAheadTaskHasStarted => |
| | 0 | 120 | | _readAheadTaskStatus != ReadAheadTask_NotStarted; |
| | | 121 | | |
| | | 122 | | /// <summary>Prepare an idle connection to be used for a new request. |
| | | 123 | | /// The caller MUST call SendAsync afterwards if this method returns true, or dispose the connection if it retur |
| | | 124 | | /// <param name="async">Indicates whether the coming request will be sync or async.</param> |
| | | 125 | | /// <returns>True if connection can be used, false if it is invalid due to a timeout or receiving EOF or unexpec |
| | | 126 | | public bool PrepareForReuse(bool async) |
| | 0 | 127 | | { |
| | 0 | 128 | | if (CheckKeepAliveTimeoutExceeded()) |
| | 0 | 129 | | { |
| | 0 | 130 | | return false; |
| | | 131 | | } |
| | | 132 | | |
| | | 133 | | // We may already have a read-ahead task if we did a previous scavenge and haven't used the connection since |
| | | 134 | | // If the read-ahead task is completed, then we've received either EOF or erroneous data the connection, so |
| | 0 | 135 | | if (ReadAheadTaskHasStarted) |
| | 0 | 136 | | { |
| | 0 | 137 | | Debug.Assert(_readAheadTaskStatus is ReadAheadTask_Started or ReadAheadTask_Completed); |
| | | 138 | | |
| | 0 | 139 | | return Interlocked.Exchange(ref _readAheadTaskStatus, ReadAheadTask_CompletionReserved) == ReadAheadTask |
| | | 140 | | } |
| | | 141 | | |
| | | 142 | | // Check to see if we've received anything on the connection; if we have, that's |
| | | 143 | | // either erroneous data (we shouldn't have received anything yet) or the connection |
| | | 144 | | // has been closed; either way, we can't use it. |
| | 0 | 145 | | if (!async && _stream is NetworkStream networkStream) |
| | 0 | 146 | | { |
| | | 147 | | // Directly poll the socket rather than doing an async read, so that we can |
| | | 148 | | // issue an appropriate sync read when we actually need it. |
| | | 149 | | try |
| | 0 | 150 | | { |
| | 0 | 151 | | return !networkStream.Socket.Poll(0, SelectMode.SelectRead); |
| | | 152 | | } |
| | 0 | 153 | | catch (Exception e) when (e is SocketException || e is ObjectDisposedException) |
| | 0 | 154 | | { |
| | | 155 | | // Poll can throw when used on a closed socket. |
| | 0 | 156 | | return false; |
| | | 157 | | } |
| | | 158 | | } |
| | | 159 | | else |
| | 0 | 160 | | { |
| | 0 | 161 | | Debug.Assert(_readAheadTaskStatus == ReadAheadTask_NotStarted); |
| | 0 | 162 | | _readAheadTaskStatus = ReadAheadTask_CompletionReserved; |
| | | 163 | | |
| | | 164 | | // Perform an async read on the stream, since we're going to need to read from it |
| | | 165 | | // anyway, and in doing so we can avoid the extra syscall. |
| | | 166 | | try |
| | 0 | 167 | | { |
| | | 168 | | #pragma warning disable CA2012 // we're very careful to ensure the ValueTask is only consumed once, even though it's sto |
| | 0 | 169 | | _readAheadTask = _stream.ReadAsync(_readBuffer.AvailableMemory); |
| | | 170 | | #pragma warning restore CA2012 |
| | | 171 | | |
| | | 172 | | // If the read-ahead task already completed, we can't reuse the connection. |
| | | 173 | | // We're still responsible for observing potential exceptions thrown by the read-ahead task to avoid |
| | 0 | 174 | | if (_readAheadTask.IsCompleted) |
| | 0 | 175 | | { |
| | 0 | 176 | | LogExceptions(_readAheadTask.AsTask()); |
| | 0 | 177 | | return false; |
| | | 178 | | } |
| | | 179 | | |
| | 0 | 180 | | return true; |
| | | 181 | | } |
| | 0 | 182 | | catch (Exception error) |
| | 0 | 183 | | { |
| | | 184 | | // If reading throws, eat the error and don't reuse the connection. |
| | 0 | 185 | | if (NetEventSource.Log.IsEnabled()) Trace($"Error performing read ahead: {error}"); |
| | 0 | 186 | | return false; |
| | | 187 | | } |
| | | 188 | | } |
| | 0 | 189 | | } |
| | | 190 | | |
| | | 191 | | /// <summary>Takes ownership of the scavenging task completion if it was started. |
| | | 192 | | /// The caller MUST call either SendAsync or return the completion ownership afterwards if this method returns t |
| | | 193 | | public bool TryOwnScavengingTaskCompletion() |
| | 0 | 194 | | { |
| | 0 | 195 | | Debug.Assert(_readAheadTaskStatus != ReadAheadTask_CompletionReserved); |
| | | 196 | | |
| | 0 | 197 | | return !ReadAheadTaskHasStarted |
| | 0 | 198 | | || Interlocked.Exchange(ref _readAheadTaskStatus, ReadAheadTask_CompletionReserved) == ReadAheadTask_Sta |
| | 0 | 199 | | } |
| | | 200 | | |
| | | 201 | | /// <summary>Returns ownership of the scavenging task completion if it was started. |
| | | 202 | | /// The caller MUST Dispose the connection afterwards if this method returns false.</summary> |
| | | 203 | | public bool TryReturnScavengingTaskCompletionOwnership() |
| | 0 | 204 | | { |
| | 0 | 205 | | Debug.Assert(_readAheadTaskStatus != ReadAheadTask_Started); |
| | | 206 | | |
| | 0 | 207 | | if (!ReadAheadTaskHasStarted || |
| | 0 | 208 | | Interlocked.Exchange(ref _readAheadTaskStatus, ReadAheadTask_Started) == ReadAheadTask_CompletionReserve |
| | 0 | 209 | | { |
| | 0 | 210 | | return true; |
| | | 211 | | } |
| | | 212 | | |
| | | 213 | | // The read-ahead task has started, and we failed to transition back to Started. |
| | | 214 | | // This means that the read-ahead task has completed, and we can't reuse the connection. The caller must dis |
| | | 215 | | // We're still responsible for observing potential exceptions thrown by the read-ahead task to avoid leaking |
| | 0 | 216 | | LogExceptions(_readAheadTask.AsTask()); |
| | 0 | 217 | | return false; |
| | 0 | 218 | | } |
| | | 219 | | |
| | | 220 | | /// <summary>Check whether a currently idle connection is still usable, or should be scavenged.</summary> |
| | | 221 | | /// <returns>True if connection can be used, false if it is invalid due to a timeout or receiving EOF or unexpec |
| | | 222 | | public override bool CheckUsabilityOnScavenge() |
| | 0 | 223 | | { |
| | 0 | 224 | | if (CheckKeepAliveTimeoutExceeded()) |
| | 0 | 225 | | { |
| | 0 | 226 | | return false; |
| | | 227 | | } |
| | | 228 | | |
| | | 229 | | // We may already have a read-ahead task if we did a previous scavenge and haven't used the connection since |
| | 0 | 230 | | if (!ReadAheadTaskHasStarted) |
| | 0 | 231 | | { |
| | 0 | 232 | | Debug.Assert(_readAheadTask == default); |
| | | 233 | | |
| | 0 | 234 | | _readAheadTaskStatus = ReadAheadTask_Started; |
| | | 235 | | |
| | | 236 | | #pragma warning disable CA2012 // we're very careful to ensure the ValueTask is only consumed once, even though it's sto |
| | 0 | 237 | | _readAheadTask = ReadAheadWithZeroByteReadAsync(); |
| | | 238 | | #pragma warning restore CA2012 |
| | 0 | 239 | | } |
| | | 240 | | |
| | | 241 | | // If the read-ahead task is completed, then we've received either EOF or erroneous data the connection, so |
| | 0 | 242 | | return !_readAheadTask.IsCompleted; |
| | | 243 | | |
| | | 244 | | async ValueTask<int> ReadAheadWithZeroByteReadAsync() |
| | 0 | 245 | | { |
| | 0 | 246 | | Debug.Assert(_readAheadTask == default); |
| | 0 | 247 | | Debug.Assert(_readBuffer.ActiveLength == 0); |
| | | 248 | | |
| | | 249 | | try |
| | 0 | 250 | | { |
| | | 251 | | // Issue a zero-byte read. |
| | | 252 | | // If the underlying stream supports it, this will not complete until the stream has data available, |
| | | 253 | | // which will avoid pinning the connection's read buffer (and possibly allow us to release it to the |
| | | 254 | | // If not, it will complete immediately. |
| | 0 | 255 | | await _stream.ReadAsync(Memory<byte>.Empty).ConfigureAwait(false); |
| | | 256 | | |
| | | 257 | | // We don't know for sure that the stream actually has data available, so we need to issue a real re |
| | 0 | 258 | | int read = await _stream.ReadAsync(_readBuffer.AvailableMemory).ConfigureAwait(false); |
| | | 259 | | |
| | | 260 | | // PrepareForReuse will check TryOwnReadAheadTaskCompletion before calling into SendAsync. |
| | | 261 | | // If we can own the completion from within the read-ahead task, it means that PrepareForReuse hasn' |
| | | 262 | | // In that case we've received EOF/erroneous data before we sent the request headers, and the connec |
| | 0 | 263 | | if (TransitionToCompletedAndTryOwnCompletion()) |
| | 0 | 264 | | { |
| | 0 | 265 | | if (NetEventSource.Log.IsEnabled()) Trace("Read-ahead task observed data before the request was |
| | 0 | 266 | | } |
| | | 267 | | |
| | 0 | 268 | | return read; |
| | | 269 | | } |
| | 0 | 270 | | catch (Exception error) when (TransitionToCompletedAndTryOwnCompletion()) |
| | 0 | 271 | | { |
| | 0 | 272 | | if (NetEventSource.Log.IsEnabled()) Trace($"Error performing read ahead: {error}"); |
| | | 273 | | |
| | 0 | 274 | | return 0; |
| | | 275 | | } |
| | | 276 | | |
| | | 277 | | bool TransitionToCompletedAndTryOwnCompletion() |
| | 0 | 278 | | { |
| | 0 | 279 | | Debug.Assert(_readAheadTaskStatus is ReadAheadTask_Started or ReadAheadTask_CompletionReserved); |
| | | 280 | | |
| | 0 | 281 | | return Interlocked.Exchange(ref _readAheadTaskStatus, ReadAheadTask_Completed) == ReadAheadTask_Star |
| | 0 | 282 | | } |
| | 0 | 283 | | } |
| | 0 | 284 | | } |
| | | 285 | | |
| | | 286 | | private bool CheckKeepAliveTimeoutExceeded() |
| | 0 | 287 | | { |
| | | 288 | | // We intentionally honor the Keep-Alive timeout on all HTTP/1.X versions, not just 1.0. This is to maximize |
| | | 289 | | // servers that use a lower idle timeout than the client, but give us a hint in the form of a Keep-Alive tim |
| | | 290 | | // If _keepAliveTimeoutSeconds is 0, no timeout has been set. |
| | 0 | 291 | | return _keepAliveTimeoutSeconds != 0 && |
| | 0 | 292 | | GetIdleTicks(Environment.TickCount64) >= _keepAliveTimeoutSeconds * 1000; |
| | 0 | 293 | | } |
| | | 294 | | |
| | 0 | 295 | | public TransportContext? TransportContext => _transportContext; |
| | | 296 | | |
| | 0 | 297 | | public HttpConnectionKind Kind => _pool.Kind; |
| | | 298 | | |
| | 0 | 299 | | private int ReadBufferSize => _readBuffer.Capacity; |
| | | 300 | | |
| | 0 | 301 | | private ReadOnlyMemory<byte> RemainingBuffer => _readBuffer.ActiveMemory; |
| | | 302 | | |
| | | 303 | | private void ConsumeFromRemainingBuffer(int bytesToConsume) |
| | 0 | 304 | | { |
| | 0 | 305 | | Debug.Assert(bytesToConsume <= _readBuffer.ActiveLength); |
| | 0 | 306 | | _readBuffer.Discard(bytesToConsume); |
| | 0 | 307 | | } |
| | | 308 | | |
| | | 309 | | private void WriteHeaders(HttpRequestMessage request) |
| | 0 | 310 | | { |
| | 0 | 311 | | Debug.Assert(request.RequestUri is not null); |
| | | 312 | | |
| | | 313 | | // Write the request line |
| | 0 | 314 | | WriteBytes(request.Method.Http1EncodedBytes); |
| | | 315 | | |
| | 0 | 316 | | if (request.Method.IsConnect) |
| | 0 | 317 | | { |
| | | 318 | | // RFC 7231 #section-4.3.6. |
| | | 319 | | // Write only CONNECT foo.com:345 HTTP/1.1 |
| | 0 | 320 | | if (!request.HasHeaders || request.Headers.Host is not string host) |
| | 0 | 321 | | { |
| | 0 | 322 | | throw new HttpRequestException(SR.net_http_request_no_host); |
| | | 323 | | } |
| | | 324 | | |
| | 0 | 325 | | WriteAsciiString(host); |
| | 0 | 326 | | } |
| | | 327 | | else |
| | 0 | 328 | | { |
| | 0 | 329 | | if (Kind == HttpConnectionKind.Proxy) |
| | 0 | 330 | | { |
| | | 331 | | // Proxied requests contain full URL |
| | 0 | 332 | | Debug.Assert(request.RequestUri.Scheme == Uri.UriSchemeHttp); |
| | 0 | 333 | | WriteBytes("http://"u8); |
| | 0 | 334 | | WriteHost(request.RequestUri); |
| | 0 | 335 | | } |
| | | 336 | | |
| | 0 | 337 | | WriteAsciiString(request.RequestUri.PathAndQuery); |
| | 0 | 338 | | } |
| | | 339 | | |
| | | 340 | | // Fall back to 1.1 for all versions other than 1.0 |
| | 0 | 341 | | Debug.Assert(request.Version.Major >= 0 && request.Version.Minor >= 0); // guaranteed by Version class |
| | 0 | 342 | | bool isHttp10 = request.Version.Minor == 0 && request.Version.Major == 1; |
| | 0 | 343 | | WriteBytes(isHttp10 ? " HTTP/1.0\r\n"u8 : " HTTP/1.1\r\n"u8); |
| | | 344 | | |
| | | 345 | | // Write special additional headers. If a host isn't in the headers list, then a Host header |
| | | 346 | | // wasn't set, so as it's required by HTTP 1.1 spec, send one based on the Request Uri. |
| | 0 | 347 | | if (!request.HasHeaders || request.Headers.Host is null) |
| | 0 | 348 | | { |
| | 0 | 349 | | if (_pool.HostHeaderLineBytes is byte[] hostHeaderLineBytes) |
| | 0 | 350 | | { |
| | 0 | 351 | | Debug.Assert(Kind != HttpConnectionKind.Proxy); |
| | 0 | 352 | | WriteBytes(hostHeaderLineBytes); |
| | 0 | 353 | | } |
| | | 354 | | else |
| | 0 | 355 | | { |
| | 0 | 356 | | Debug.Assert(Kind == HttpConnectionKind.Proxy); |
| | 0 | 357 | | WriteBytes(KnownHeaders.Host.AsciiBytesWithColonSpace); |
| | 0 | 358 | | WriteHost(request.RequestUri); |
| | 0 | 359 | | WriteCRLF(); |
| | 0 | 360 | | } |
| | 0 | 361 | | } |
| | | 362 | | |
| | | 363 | | // Determine cookies to send |
| | 0 | 364 | | string? cookiesFromContainer = null; |
| | 0 | 365 | | if (_pool.Settings._useCookies) |
| | 0 | 366 | | { |
| | 0 | 367 | | cookiesFromContainer = _pool.Settings._cookieContainer!.GetCookieHeader(request.RequestUri); |
| | 0 | 368 | | if (cookiesFromContainer == "") |
| | 0 | 369 | | { |
| | 0 | 370 | | cookiesFromContainer = null; |
| | 0 | 371 | | } |
| | 0 | 372 | | } |
| | | 373 | | |
| | | 374 | | // Write request headers |
| | 0 | 375 | | if (request.HasHeaders || cookiesFromContainer is not null) |
| | 0 | 376 | | { |
| | 0 | 377 | | WriteHeaderCollection(request.Headers, cookiesFromContainer); |
| | 0 | 378 | | } |
| | | 379 | | |
| | | 380 | | // Write content headers |
| | 0 | 381 | | if (request.Content is HttpContent content) |
| | 0 | 382 | | { |
| | 0 | 383 | | WriteHeaderCollection(content.Headers); |
| | 0 | 384 | | } |
| | | 385 | | else |
| | 0 | 386 | | { |
| | | 387 | | // Write out Content-Length: 0 header to indicate no body, |
| | | 388 | | // unless this is a method that never has a body. |
| | 0 | 389 | | if (request.Method.MustHaveRequestBody) |
| | 0 | 390 | | { |
| | 0 | 391 | | WriteBytes("Content-Length: 0\r\n"u8); |
| | 0 | 392 | | } |
| | 0 | 393 | | } |
| | | 394 | | |
| | | 395 | | // CRLF for end of headers. |
| | 0 | 396 | | WriteCRLF(); |
| | | 397 | | |
| | | 398 | | void WriteHost(Uri requestUri) |
| | 0 | 399 | | { |
| | | 400 | | // Uri.IdnHost is missing '[', ']' characters around IPv6 address |
| | | 401 | | // and it also contains ScopeID for Link-Local addresses |
| | 0 | 402 | | string host = requestUri.HostNameType == UriHostNameType.IPv6 ? requestUri.Host : requestUri.IdnHost; |
| | 0 | 403 | | WriteAsciiString(host); |
| | | 404 | | |
| | 0 | 405 | | if (!requestUri.IsDefaultPort) |
| | 0 | 406 | | { |
| | 0 | 407 | | _writeBuffer.EnsureAvailableSpace(6); |
| | 0 | 408 | | Span<byte> buffer = _writeBuffer.AvailableSpan; |
| | 0 | 409 | | buffer[0] = (byte)':'; |
| | 0 | 410 | | bool success = ((uint)requestUri.Port).TryFormat(buffer.Slice(1), out int bytesWritten); |
| | 0 | 411 | | Debug.Assert(success); |
| | 0 | 412 | | _writeBuffer.Commit(bytesWritten + 1); |
| | 0 | 413 | | } |
| | 0 | 414 | | } |
| | 0 | 415 | | } |
| | | 416 | | |
| | | 417 | | private void WriteHeaderCollection(HttpHeaders headers, string? cookiesFromContainer = null) |
| | 0 | 418 | | { |
| | 0 | 419 | | Debug.Assert(_currentRequest is not null); |
| | | 420 | | |
| | 0 | 421 | | HeaderEncodingSelector<HttpRequestMessage>? encodingSelector = _pool.Settings._requestHeaderEncodingSelector |
| | 0 | 422 | | ref string[]? headerValues = ref t_headerValues; |
| | | 423 | | |
| | 0 | 424 | | foreach (HeaderEntry header in headers.GetEntries()) |
| | 0 | 425 | | { |
| | 0 | 426 | | if (header.Key.KnownHeader is KnownHeader knownHeader) |
| | 0 | 427 | | { |
| | 0 | 428 | | WriteBytes(knownHeader.AsciiBytesWithColonSpace); |
| | 0 | 429 | | } |
| | | 430 | | else |
| | 0 | 431 | | { |
| | 0 | 432 | | WriteAsciiString(header.Key.Name); |
| | 0 | 433 | | WriteBytes(": "u8); |
| | 0 | 434 | | } |
| | | 435 | | |
| | 0 | 436 | | int headerValuesCount = HttpHeaders.GetStoreValuesIntoStringArray(header.Key, header.Value, ref headerVa |
| | 0 | 437 | | Debug.Assert(headerValuesCount > 0, "No values for header??"); |
| | | 438 | | |
| | 0 | 439 | | Encoding? valueEncoding = encodingSelector?.Invoke(header.Key.Name, _currentRequest); |
| | | 440 | | |
| | 0 | 441 | | WriteString(headerValues[0], valueEncoding); |
| | | 442 | | |
| | 0 | 443 | | if (cookiesFromContainer is not null && header.Key.Equals(KnownHeaders.Cookie)) |
| | 0 | 444 | | { |
| | 0 | 445 | | WriteBytes("; "u8); // Cookies use "; " as the separator |
| | 0 | 446 | | WriteString(cookiesFromContainer, valueEncoding); |
| | 0 | 447 | | cookiesFromContainer = null; |
| | 0 | 448 | | } |
| | | 449 | | |
| | | 450 | | // Some headers such as User-Agent and Server use space as a separator (see: ProductInfoHeaderParser) |
| | 0 | 451 | | if (headerValuesCount > 1) |
| | 0 | 452 | | { |
| | 0 | 453 | | byte[] separator = header.Key.SeparatorBytes; |
| | | 454 | | |
| | 0 | 455 | | for (int i = 1; i < headerValuesCount; i++) |
| | 0 | 456 | | { |
| | 0 | 457 | | WriteBytes(separator); |
| | 0 | 458 | | WriteString(headerValues[i], valueEncoding); |
| | 0 | 459 | | } |
| | 0 | 460 | | } |
| | | 461 | | |
| | 0 | 462 | | WriteCRLF(); |
| | 0 | 463 | | } |
| | | 464 | | |
| | 0 | 465 | | if (cookiesFromContainer is not null) |
| | 0 | 466 | | { |
| | 0 | 467 | | WriteBytes(KnownHeaders.Cookie.AsciiBytesWithColonSpace); |
| | 0 | 468 | | WriteString(cookiesFromContainer, encodingSelector?.Invoke(HttpKnownHeaderNames.Cookie, _currentRequest) |
| | 0 | 469 | | WriteCRLF(); |
| | 0 | 470 | | } |
| | 0 | 471 | | } |
| | | 472 | | |
| | | 473 | | private void WriteCRLF() |
| | 0 | 474 | | { |
| | 0 | 475 | | _writeBuffer.EnsureAvailableSpace(2); |
| | 0 | 476 | | Span<byte> buffer = _writeBuffer.AvailableSpan; |
| | 0 | 477 | | buffer[1] = (byte)'\n'; |
| | 0 | 478 | | buffer[0] = (byte)'\r'; |
| | 0 | 479 | | _writeBuffer.Commit(2); |
| | 0 | 480 | | } |
| | | 481 | | |
| | | 482 | | private void WriteBytes(ReadOnlySpan<byte> bytes) |
| | 0 | 483 | | { |
| | 0 | 484 | | _writeBuffer.EnsureAvailableSpace(bytes.Length); |
| | 0 | 485 | | bytes.CopyTo(_writeBuffer.AvailableSpan); |
| | 0 | 486 | | _writeBuffer.Commit(bytes.Length); |
| | 0 | 487 | | } |
| | | 488 | | |
| | | 489 | | private void WriteAsciiString(string s) |
| | 0 | 490 | | { |
| | 0 | 491 | | Debug.Assert(Ascii.IsValid(s)); |
| | | 492 | | |
| | 0 | 493 | | _writeBuffer.EnsureAvailableSpace(s.Length); |
| | | 494 | | |
| | 0 | 495 | | OperationStatus status = Ascii.FromUtf16(s, _writeBuffer.AvailableSpan, out int bytesWritten); |
| | 0 | 496 | | Debug.Assert(status == OperationStatus.Done); |
| | 0 | 497 | | Debug.Assert(bytesWritten == s.Length); |
| | | 498 | | |
| | 0 | 499 | | _writeBuffer.Commit(s.Length); |
| | 0 | 500 | | } |
| | | 501 | | |
| | | 502 | | private void WriteString(string s, Encoding? encoding) |
| | 0 | 503 | | { |
| | 0 | 504 | | if (encoding is null) |
| | 0 | 505 | | { |
| | 0 | 506 | | _writeBuffer.EnsureAvailableSpace(s.Length); |
| | 0 | 507 | | Span<byte> buffer = _writeBuffer.AvailableSpan; |
| | | 508 | | |
| | 0 | 509 | | OperationStatus status = Ascii.FromUtf16(s, buffer, out int bytesWritten); |
| | | 510 | | |
| | 0 | 511 | | if (status == OperationStatus.InvalidData) |
| | 0 | 512 | | { |
| | 0 | 513 | | ThrowForInvalidCharEncoding(); |
| | 0 | 514 | | } |
| | | 515 | | |
| | 0 | 516 | | Debug.Assert(status == OperationStatus.Done); |
| | 0 | 517 | | Debug.Assert(bytesWritten == s.Length); |
| | | 518 | | |
| | 0 | 519 | | _writeBuffer.Commit(s.Length); |
| | 0 | 520 | | } |
| | | 521 | | else |
| | 0 | 522 | | { |
| | 0 | 523 | | _writeBuffer.EnsureAvailableSpace(encoding.GetMaxByteCount(s.Length)); |
| | 0 | 524 | | int length = encoding.GetBytes(s, _writeBuffer.AvailableSpan); |
| | 0 | 525 | | _writeBuffer.Commit(length); |
| | 0 | 526 | | } |
| | | 527 | | |
| | | 528 | | static void ThrowForInvalidCharEncoding() => |
| | 0 | 529 | | throw new HttpRequestException(SR.net_http_request_invalid_char_encoding); |
| | 0 | 530 | | } |
| | | 531 | | |
| | | 532 | | public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, bool async, CancellationToken cance |
| | 0 | 533 | | { |
| | 0 | 534 | | Debug.Assert(_currentRequest == null, $"Expected null {nameof(_currentRequest)}."); |
| | 0 | 535 | | Debug.Assert(_readBuffer.ActiveLength == 0, "Unexpected data in read buffer"); |
| | 0 | 536 | | Debug.Assert(_readAheadTaskStatus != ReadAheadTask_Started, |
| | 0 | 537 | | "The caller should have called PrepareForReuse or TryOwnScavengingTaskCompletion if the connection was i |
| | | 538 | | |
| | 0 | 539 | | MarkConnectionAsNotIdle(); |
| | | 540 | | |
| | 0 | 541 | | TaskCompletionSource<bool>? allowExpect100ToContinue = null; |
| | 0 | 542 | | Task? sendRequestContentTask = null; |
| | | 543 | | |
| | 0 | 544 | | _currentRequest = request; |
| | | 545 | | |
| | 0 | 546 | | _canRetry = false; |
| | | 547 | | |
| | | 548 | | // Send the request. |
| | 0 | 549 | | if (NetEventSource.Log.IsEnabled()) Trace($"Sending request: {request}"); |
| | 0 | 550 | | if (ConnectionSetupActivity is not null) ConnectionSetupDistributedTracing.AddConnectionLinkToRequestActivit |
| | 0 | 551 | | CancellationTokenRegistration cancellationRegistration = RegisterCancellation(cancellationToken); |
| | | 552 | | try |
| | 0 | 553 | | { |
| | 0 | 554 | | if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.RequestHeadersStart(Id); |
| | | 555 | | |
| | 0 | 556 | | WriteHeaders(request); |
| | | 557 | | |
| | 0 | 558 | | if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.RequestHeadersStop(); |
| | | 559 | | |
| | 0 | 560 | | if (request.Content == null) |
| | 0 | 561 | | { |
| | | 562 | | // We have nothing more to send, so flush out any headers we haven't yet sent. |
| | 0 | 563 | | await FlushAsync(async).ConfigureAwait(false); |
| | 0 | 564 | | } |
| | | 565 | | else |
| | 0 | 566 | | { |
| | 0 | 567 | | bool hasExpectContinueHeader = request.HasHeaders && request.Headers.ExpectContinue == true; |
| | 0 | 568 | | if (NetEventSource.Log.IsEnabled()) Trace($"Request content is not null, start processing it. hasExp |
| | | 569 | | |
| | | 570 | | // Send the body if there is one. We prefer to serialize the sending of the content before |
| | | 571 | | // we try to receive any response, but if ExpectContinue has been set, we allow the sending |
| | | 572 | | // to run concurrently until we receive the final status line, at which point we wait for it. |
| | 0 | 573 | | if (!hasExpectContinueHeader) |
| | 0 | 574 | | { |
| | 0 | 575 | | await SendRequestContentAsync(request, CreateRequestContentStream(request), async, cancellationT |
| | 0 | 576 | | } |
| | | 577 | | else |
| | 0 | 578 | | { |
| | | 579 | | // We're sending an Expect: 100-continue header. We need to flush headers so that the server rec |
| | | 580 | | // all of them, and we need to do so before initiating the send, as once we do that, it effectiv |
| | | 581 | | // owns the right to write, and we don't want to concurrently be accessing the write buffer. |
| | 0 | 582 | | await FlushAsync(async).ConfigureAwait(false); |
| | | 583 | | |
| | | 584 | | // Create a TCS we'll use to block the request content from being sent, and create a timer that' |
| | | 585 | | // as a fail-safe to unblock the request content if we don't hear back from the server in a time |
| | | 586 | | // Then kick off the request. The TCS' result indicates whether content should be sent or not. |
| | 0 | 587 | | allowExpect100ToContinue = new TaskCompletionSource<bool>(); |
| | 0 | 588 | | var expect100Timer = new Timer( |
| | | 589 | | static s => ((TaskCompletionSource<bool>)s!).TrySetResult(true), |
| | 0 | 590 | | allowExpect100ToContinue, _pool.Settings._expect100ContinueTimeout, Timeout.InfiniteTimeSpan |
| | | 591 | | #pragma warning disable CA2025 |
| | 0 | 592 | | sendRequestContentTask = SendRequestContentWithExpect100ContinueAsync( |
| | 0 | 593 | | request, allowExpect100ToContinue.Task, CreateRequestContentStream(request), expect100Timer, |
| | | 594 | | #pragma warning restore |
| | 0 | 595 | | } |
| | 0 | 596 | | } |
| | | 597 | | |
| | | 598 | | // Start to read response. |
| | 0 | 599 | | _allowedReadLineBytes = _pool.Settings.MaxResponseHeadersByteLength; |
| | | 600 | | |
| | | 601 | | // We should not have any buffered data here; if there was, it should have been treated as an error |
| | | 602 | | // by the previous request handling. (Note we do not support HTTP pipelining.) |
| | 0 | 603 | | Debug.Assert(_readBuffer.ActiveLength == 0); |
| | | 604 | | |
| | | 605 | | // When the connection was taken out of the pool, a pre-emptive read was performed |
| | | 606 | | // into the read buffer. We need to consume that read prior to issuing another read. |
| | 0 | 607 | | if (ReadAheadTaskHasStarted) |
| | 0 | 608 | | { |
| | | 609 | | // If the read-ahead task completed synchronously, it would have claimed ownership of its completion |
| | | 610 | | // meaning that PrepareForReuse would have failed, and we wouldn't have called SendAsync. |
| | | 611 | | // The task therefore shouldn't be 'default', as it's representing an async operation that had to yi |
| | 0 | 612 | | Debug.Assert(_readAheadTask != default); |
| | 0 | 613 | | Debug.Assert(_readAheadTaskStatus is ReadAheadTask_CompletionReserved or ReadAheadTask_Completed); |
| | | 614 | | |
| | | 615 | | // Handle the pre-emptive read. For the async==false case, hopefully the read has |
| | | 616 | | // already completed and this will be a nop, but if it hasn't, the caller will be forced to block |
| | | 617 | | // waiting for the async operation to complete. We will only hit this case for proxied HTTPS |
| | | 618 | | // requests that use a pooled connection, as in that case we don't have a Socket we |
| | | 619 | | // can poll and are forced to issue an async read. |
| | 0 | 620 | | ValueTask<int> vt = _readAheadTask; |
| | 0 | 621 | | _readAheadTask = default; |
| | | 622 | | |
| | | 623 | | int bytesRead; |
| | 0 | 624 | | if (vt.IsCompleted) |
| | 0 | 625 | | { |
| | 0 | 626 | | bytesRead = vt.Result; |
| | 0 | 627 | | } |
| | | 628 | | else |
| | 0 | 629 | | { |
| | 0 | 630 | | if (NetEventSource.Log.IsEnabled() && !async) |
| | 0 | 631 | | { |
| | 0 | 632 | | Trace($"Pre-emptive read completed asynchronously for a synchronous request."); |
| | 0 | 633 | | } |
| | | 634 | | |
| | 0 | 635 | | bytesRead = await vt.ConfigureAwait(false); |
| | 0 | 636 | | } |
| | | 637 | | |
| | 0 | 638 | | _readBuffer.Commit(bytesRead); |
| | | 639 | | |
| | 0 | 640 | | if (NetEventSource.Log.IsEnabled()) Trace($"Received {bytesRead} bytes."); |
| | | 641 | | |
| | 0 | 642 | | _readAheadTaskStatus = ReadAheadTask_NotStarted; |
| | 0 | 643 | | } |
| | | 644 | | else |
| | 0 | 645 | | { |
| | | 646 | | // No read-ahead, so issue a read ourselves. We will check below for EOF. |
| | 0 | 647 | | await InitialFillAsync(async).ConfigureAwait(false); |
| | 0 | 648 | | } |
| | | 649 | | |
| | 0 | 650 | | if (_readBuffer.ActiveLength == 0) |
| | 0 | 651 | | { |
| | | 652 | | // The server shutdown the connection on their end, likely because of an idle timeout. |
| | | 653 | | // If we haven't started sending the request body yet (or there is no request body), |
| | | 654 | | // then we allow the request to be retried. |
| | 0 | 655 | | if (request.Content is null || allowExpect100ToContinue is not null) |
| | 0 | 656 | | { |
| | 0 | 657 | | _canRetry = true; |
| | 0 | 658 | | } |
| | | 659 | | |
| | 0 | 660 | | throw new HttpIOException(HttpRequestError.ResponseEnded, SR.net_http_invalid_response_premature_eof |
| | | 661 | | } |
| | | 662 | | |
| | | 663 | | |
| | | 664 | | // Parse the response status line. |
| | 0 | 665 | | var response = new HttpResponseMessage() { RequestMessage = request, Content = new HttpConnectionRespons |
| | | 666 | | |
| | 0 | 667 | | while (!ParseStatusLine(response)) |
| | 0 | 668 | | { |
| | 0 | 669 | | await FillForHeadersAsync(async).ConfigureAwait(false); |
| | 0 | 670 | | } |
| | | 671 | | |
| | 0 | 672 | | if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.ResponseHeadersStart(); |
| | | 673 | | |
| | | 674 | | // Multiple 1xx responses handling. |
| | | 675 | | // RFC 7231: A client MUST be able to parse one or more 1xx responses received prior to a final response |
| | | 676 | | // even if the client does not expect one. A user agent MAY ignore unexpected 1xx responses. |
| | | 677 | | // In .NET Core, apart from 100 Continue, and 101 Switching Protocols, we will treat all other 1xx respo |
| | | 678 | | // as unknown, and will discard them. |
| | 0 | 679 | | while ((uint)(response.StatusCode - 100) <= 199 - 100) |
| | 0 | 680 | | { |
| | | 681 | | // If other 1xx responses come before an expected 100 continue, we will wait for the 100 response be |
| | | 682 | | // sending request body (if any). |
| | 0 | 683 | | if (allowExpect100ToContinue != null && response.StatusCode == HttpStatusCode.Continue) |
| | 0 | 684 | | { |
| | 0 | 685 | | allowExpect100ToContinue.TrySetResult(true); |
| | 0 | 686 | | allowExpect100ToContinue = null; |
| | 0 | 687 | | } |
| | 0 | 688 | | else if (response.StatusCode == HttpStatusCode.SwitchingProtocols) |
| | 0 | 689 | | { |
| | | 690 | | // 101 Upgrade is a final response as it's used to switch protocols with WebSockets handshake. |
| | | 691 | | // Will return a response object with status 101 and a raw connection stream later. |
| | | 692 | | // RFC 7230: If a server receives both an Upgrade and an Expect header field with the "100-conti |
| | | 693 | | // the server MUST send a 100 (Continue) response before sending a 101 (Switching Protocols) res |
| | | 694 | | // If server doesn't follow RFC, we treat 101 as a final response and stop waiting for 100 conti |
| | | 695 | | // never sends a 100-continue. The request body will be sent after expect100Timer expires. |
| | 0 | 696 | | break; |
| | | 697 | | } |
| | | 698 | | |
| | | 699 | | // In case read hangs which eventually leads to connection timeout. |
| | 0 | 700 | | if (NetEventSource.Log.IsEnabled()) Trace($"Current {response.StatusCode} response is an interim res |
| | | 701 | | |
| | | 702 | | // Discard headers that come with the interim 1xx responses. |
| | 0 | 703 | | while (!ParseHeaders(response: null, isFromTrailer: false)) |
| | 0 | 704 | | { |
| | 0 | 705 | | await FillForHeadersAsync(async).ConfigureAwait(false); |
| | 0 | 706 | | } |
| | | 707 | | |
| | | 708 | | // Parse the status line for next response. |
| | 0 | 709 | | while (!ParseStatusLine(response)) |
| | 0 | 710 | | { |
| | 0 | 711 | | await FillForHeadersAsync(async).ConfigureAwait(false); |
| | 0 | 712 | | } |
| | 0 | 713 | | } |
| | | 714 | | |
| | | 715 | | // Parse the response headers. Logic after this point depends on being able to examine headers in the r |
| | 0 | 716 | | while (!ParseHeaders(response, isFromTrailer: false)) |
| | 0 | 717 | | { |
| | 0 | 718 | | await FillForHeadersAsync(async).ConfigureAwait(false); |
| | 0 | 719 | | } |
| | | 720 | | |
| | 0 | 721 | | if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.ResponseHeadersStop((int)response.StatusCode); |
| | | 722 | | |
| | 0 | 723 | | if (allowExpect100ToContinue != null) |
| | 0 | 724 | | { |
| | | 725 | | // If we sent an Expect: 100-continue header, and didn't receive a 100-continue. Handle the final re |
| | | 726 | | // Note that the developer may have added an Expect: 100-continue header even if there is no Content |
| | 0 | 727 | | if ((int)response.StatusCode >= 300 && |
| | 0 | 728 | | request.Content != null && |
| | 0 | 729 | | (request.Content.Headers.ContentLength == null || request.Content.Headers.ContentLength.GetValue |
| | 0 | 730 | | !AuthenticationHelper.IsSessionAuthenticationChallenge(response)) |
| | 0 | 731 | | { |
| | | 732 | | // For error final status codes, try to avoid sending the payload if its size is unknown or if i |
| | | 733 | | // If we already sent a header detailing the size of the payload, if we then don't send that pay |
| | | 734 | | // for it and assume that the next request on the connection is actually this request's payload. |
| | | 735 | | // to be closed. However, we may have also lost a race condition with the Expect: 100-continue |
| | | 736 | | // we've already started sending the payload (we weren't able to cancel it), then we don't need |
| | | 737 | | // We also must not clone connection if we do NTLM or Negotiate authentication. |
| | 0 | 738 | | allowExpect100ToContinue.TrySetResult(false); |
| | | 739 | | |
| | 0 | 740 | | if (!allowExpect100ToContinue.Task.Result) // if Result is true, the timeout already expired and |
| | 0 | 741 | | { |
| | 0 | 742 | | _connectionClose = true; |
| | 0 | 743 | | } |
| | 0 | 744 | | } |
| | | 745 | | else |
| | 0 | 746 | | { |
| | | 747 | | // For any success status codes, for errors when the request content length is known to be small |
| | | 748 | | // or for session-based authentication challenges, send the payload |
| | | 749 | | // (if there is one... if there isn't, Content is null and thus allowExpect100ToContinue is also |
| | 0 | 750 | | allowExpect100ToContinue.TrySetResult(true); |
| | 0 | 751 | | } |
| | 0 | 752 | | } |
| | | 753 | | |
| | | 754 | | // Determine whether we need to force close the connection when the request/response has completed. |
| | 0 | 755 | | if (response.Headers.ConnectionClose.GetValueOrDefault()) |
| | 0 | 756 | | { |
| | 0 | 757 | | _connectionClose = true; |
| | 0 | 758 | | } |
| | | 759 | | |
| | | 760 | | // Now that we've received our final status line, wait for the request content to fully send. |
| | | 761 | | // In most common scenarios, the server won't send back a response until all of the request |
| | | 762 | | // content has been received, so this task should generally already be complete. |
| | 0 | 763 | | if (sendRequestContentTask != null) |
| | 0 | 764 | | { |
| | 0 | 765 | | Task sendTask = sendRequestContentTask; |
| | 0 | 766 | | sendRequestContentTask = null; |
| | 0 | 767 | | await sendTask.ConfigureAwait(false); |
| | 0 | 768 | | } |
| | | 769 | | |
| | | 770 | | // Now we are sure that the request was fully sent. |
| | 0 | 771 | | if (NetEventSource.Log.IsEnabled()) Trace("Request is fully sent."); |
| | | 772 | | |
| | | 773 | | // We're about to create the response stream, at which point responsibility for canceling |
| | | 774 | | // the remainder of the response lies with the stream. Thus we dispose of our registration |
| | | 775 | | // here (if an exception has occurred or does occur while creating/returning the stream, |
| | | 776 | | // we'll still dispose of it in the catch below as part of Dispose'ing the connection). |
| | 0 | 777 | | cancellationRegistration.Dispose(); |
| | 0 | 778 | | CancellationHelper.ThrowIfCancellationRequested(cancellationToken); // in case cancellation may have dis |
| | | 779 | | |
| | | 780 | | // Create the response stream. |
| | | 781 | | Stream responseStream; |
| | 0 | 782 | | if (request.Method.IsConnect && response.IsSuccessStatusCode) |
| | 0 | 783 | | { |
| | | 784 | | // Successful response to CONNECT does not have body. |
| | | 785 | | // What ever comes next should be opaque. |
| | 0 | 786 | | responseStream = new RawConnectionStream(this); |
| | | 787 | | |
| | | 788 | | // Don't put connection back to the pool if we upgraded to tunnel. |
| | | 789 | | // We cannot use it for normal HTTP requests any more. |
| | 0 | 790 | | _connectionClose = true; |
| | | 791 | | |
| | 0 | 792 | | _pool.InvalidateHttp11Connection(this); |
| | 0 | 793 | | _detachedFromPool = true; |
| | 0 | 794 | | } |
| | 0 | 795 | | else if (request.Method.IsHead || response.StatusCode is HttpStatusCode.NoContent or HttpStatusCode.NotM |
| | 0 | 796 | | { |
| | 0 | 797 | | responseStream = EmptyReadStream.Instance; |
| | 0 | 798 | | CompleteResponse(); |
| | 0 | 799 | | } |
| | 0 | 800 | | else if (response.StatusCode == HttpStatusCode.SwitchingProtocols) |
| | 0 | 801 | | { |
| | 0 | 802 | | responseStream = new RawConnectionStream(this); |
| | | 803 | | |
| | | 804 | | // Don't put connection back to the pool if we switched protocols. |
| | | 805 | | // We cannot use it for normal HTTP requests any more. |
| | 0 | 806 | | _connectionClose = true; |
| | | 807 | | |
| | 0 | 808 | | _pool.InvalidateHttp11Connection(this); |
| | 0 | 809 | | _detachedFromPool = true; |
| | 0 | 810 | | } |
| | 0 | 811 | | else if (response.Headers.TransferEncodingChunked == true) |
| | 0 | 812 | | { |
| | 0 | 813 | | responseStream = new ChunkedEncodingReadStream(this, response); |
| | 0 | 814 | | } |
| | 0 | 815 | | else if (response.Content.Headers.ContentLength != null) |
| | 0 | 816 | | { |
| | 0 | 817 | | long contentLength = response.Content.Headers.ContentLength.GetValueOrDefault(); |
| | 0 | 818 | | if (contentLength <= 0) |
| | 0 | 819 | | { |
| | 0 | 820 | | responseStream = EmptyReadStream.Instance; |
| | 0 | 821 | | CompleteResponse(); |
| | 0 | 822 | | } |
| | | 823 | | else |
| | 0 | 824 | | { |
| | 0 | 825 | | responseStream = new ContentLengthReadStream(this, (ulong)contentLength); |
| | 0 | 826 | | } |
| | 0 | 827 | | } |
| | | 828 | | else |
| | 0 | 829 | | { |
| | 0 | 830 | | responseStream = new ConnectionCloseReadStream(this); |
| | 0 | 831 | | } |
| | 0 | 832 | | ((HttpConnectionResponseContent)response.Content).SetStream(responseStream); |
| | | 833 | | |
| | 0 | 834 | | if (NetEventSource.Log.IsEnabled()) Trace($"Received response: {response}"); |
| | | 835 | | |
| | | 836 | | // Process Set-Cookie headers. |
| | 0 | 837 | | if (_pool.Settings._useCookies) |
| | 0 | 838 | | { |
| | 0 | 839 | | CookieHelper.ProcessReceivedCookies(response, _pool.Settings._cookieContainer!); |
| | 0 | 840 | | } |
| | | 841 | | |
| | 0 | 842 | | return response; |
| | | 843 | | } |
| | 0 | 844 | | catch (Exception error) |
| | 0 | 845 | | { |
| | | 846 | | // Clean up the cancellation registration in case we're still registered. |
| | 0 | 847 | | cancellationRegistration.Dispose(); |
| | | 848 | | |
| | | 849 | | // Make sure to complete the allowExpect100ToContinue task if it exists. |
| | 0 | 850 | | if (allowExpect100ToContinue is not null && !allowExpect100ToContinue.TrySetResult(false)) |
| | 0 | 851 | | { |
| | | 852 | | // allowExpect100ToContinue was already signaled and we may have started sending the request body. |
| | 0 | 853 | | _canRetry = false; |
| | 0 | 854 | | } |
| | | 855 | | |
| | 0 | 856 | | if (_readAheadTask != default) |
| | 0 | 857 | | { |
| | 0 | 858 | | Debug.Assert(_readAheadTaskStatus is ReadAheadTask_CompletionReserved or ReadAheadTask_Completed); |
| | | 859 | | |
| | 0 | 860 | | LogExceptions(_readAheadTask.AsTask()); |
| | 0 | 861 | | } |
| | | 862 | | |
| | 0 | 863 | | if (NetEventSource.Log.IsEnabled()) Trace($"Error sending request: {error}"); |
| | | 864 | | |
| | | 865 | | // In the rare case where Expect: 100-continue was used and then processing |
| | | 866 | | // of the response headers encountered an error such that we weren't able to |
| | | 867 | | // wait for the sending to complete, it's possible the sending also encountered |
| | | 868 | | // an exception or potentially is still going and will encounter an exception |
| | | 869 | | // (we're about to Dispose for the connection). In such cases, we don't want any |
| | | 870 | | // exception in that sending task to become unobserved and raise alarm bells, so we |
| | | 871 | | // hook up a continuation that will log it. |
| | 0 | 872 | | if (sendRequestContentTask != null && !sendRequestContentTask.IsCompletedSuccessfully) |
| | 0 | 873 | | { |
| | | 874 | | // In case the connection is disposed, it's most probable that |
| | | 875 | | // expect100Continue timer expired and request content sending failed. |
| | | 876 | | // We're awaiting the task to propagate the exception in this case. |
| | 0 | 877 | | if (_disposed) |
| | 0 | 878 | | { |
| | | 879 | | try |
| | 0 | 880 | | { |
| | 0 | 881 | | await sendRequestContentTask.ConfigureAwait(false); |
| | 0 | 882 | | } |
| | | 883 | | // Map the exception the same way as we normally do. |
| | 0 | 884 | | catch (Exception ex) when (MapSendException(ex, cancellationToken, out Exception mappedEx)) |
| | 0 | 885 | | { |
| | 0 | 886 | | throw mappedEx; |
| | | 887 | | } |
| | 0 | 888 | | } |
| | 0 | 889 | | LogExceptions(sendRequestContentTask); |
| | 0 | 890 | | } |
| | | 891 | | |
| | | 892 | | // Now clean up the connection. |
| | 0 | 893 | | Dispose(); |
| | | 894 | | |
| | | 895 | | // At this point, we're going to throw an exception; we just need to |
| | | 896 | | // determine which exception to throw. |
| | 0 | 897 | | if (MapSendException(error, cancellationToken, out Exception mappedException)) |
| | 0 | 898 | | { |
| | 0 | 899 | | throw mappedException; |
| | | 900 | | } |
| | | 901 | | // Otherwise, just allow the original exception to propagate. |
| | 0 | 902 | | throw; |
| | | 903 | | } |
| | 0 | 904 | | } |
| | | 905 | | |
| | | 906 | | private bool MapSendException(Exception exception, CancellationToken cancellationToken, out Exception mappedExce |
| | 0 | 907 | | { |
| | 0 | 908 | | if (CancellationHelper.ShouldWrapInOperationCanceledException(exception, cancellationToken)) |
| | 0 | 909 | | { |
| | | 910 | | // Cancellation was requested, so assume that the failure is due to |
| | | 911 | | // the cancellation request. This is a bit unorthodox, as usually we'd |
| | | 912 | | // prioritize a non-OperationCanceledException over a cancellation |
| | | 913 | | // request to avoid losing potentially pertinent information. But given |
| | | 914 | | // the cancellation design where we tear down the underlying connection upon |
| | | 915 | | // a cancellation request, which can then result in a myriad of different |
| | | 916 | | // exceptions (argument exceptions, object disposed exceptions, socket exceptions, |
| | | 917 | | // etc.), as a middle ground we treat it as cancellation, but still propagate the |
| | | 918 | | // original information as the inner exception, for diagnostic purposes. |
| | 0 | 919 | | mappedException = CancellationHelper.CreateOperationCanceledException(exception, cancellationToken); |
| | 0 | 920 | | return true; |
| | | 921 | | } |
| | | 922 | | |
| | 0 | 923 | | if (exception is InvalidOperationException) |
| | 0 | 924 | | { |
| | | 925 | | // For consistency with other handlers we wrap the exception in an HttpRequestException. |
| | 0 | 926 | | mappedException = new HttpRequestException(SR.net_http_client_execution_error, exception); |
| | 0 | 927 | | return true; |
| | | 928 | | } |
| | | 929 | | |
| | 0 | 930 | | if (exception is IOException ioe) |
| | 0 | 931 | | { |
| | | 932 | | // For consistency with other handlers we wrap the exception in an HttpRequestException. |
| | | 933 | | // If the request is retryable, indicate that on the exception. |
| | 0 | 934 | | HttpRequestError error = ioe is HttpIOException httpIoe ? httpIoe.HttpRequestError : HttpRequestError.Un |
| | 0 | 935 | | mappedException = new HttpRequestException(error, SR.net_http_client_execution_error, ioe, _canRetry ? R |
| | 0 | 936 | | return true; |
| | | 937 | | } |
| | | 938 | | |
| | | 939 | | // Otherwise, just allow the original exception to propagate. |
| | 0 | 940 | | mappedException = exception; |
| | 0 | 941 | | return false; |
| | 0 | 942 | | } |
| | | 943 | | |
| | | 944 | | private HttpContentWriteStream CreateRequestContentStream(HttpRequestMessage request) |
| | 0 | 945 | | { |
| | 0 | 946 | | Debug.Assert(request.Content is not null); |
| | 0 | 947 | | bool requestTransferEncodingChunked = request.HasHeaders && request.Headers.TransferEncodingChunked == true; |
| | 0 | 948 | | HttpContentWriteStream requestContentStream = requestTransferEncodingChunked ? (HttpContentWriteStream) |
| | 0 | 949 | | new ChunkedEncodingWriteStream(this) : |
| | 0 | 950 | | new ContentLengthWriteStream(this, request.Content.Headers.ContentLength.GetValueOrDefault()); |
| | 0 | 951 | | return requestContentStream; |
| | 0 | 952 | | } |
| | | 953 | | |
| | | 954 | | private CancellationTokenRegistration RegisterCancellation(CancellationToken cancellationToken) |
| | 0 | 955 | | { |
| | | 956 | | // Cancellation design: |
| | | 957 | | // - We register with the SendAsync CancellationToken for the duration of the SendAsync operation. |
| | | 958 | | // - We register with the Read/Write/CopyToAsync methods on the response stream for each such individual ope |
| | | 959 | | // - The registration disposes of the connection, tearing it down and causing any pending operations to wake |
| | | 960 | | // - Because such a tear down can result in a variety of different exception types, we check for a cancellat |
| | | 961 | | // request and prioritize that over other exceptions, wrapping the actual exception as an inner of an OCE. |
| | 0 | 962 | | return cancellationToken.Register(static s => |
| | 0 | 963 | | { |
| | 0 | 964 | | var connection = (HttpConnection)s!; |
| | 0 | 965 | | if (NetEventSource.Log.IsEnabled()) connection.Trace("Cancellation requested. Disposing of the connectio |
| | 0 | 966 | | connection.Dispose(); |
| | 0 | 967 | | }, this); |
| | 0 | 968 | | } |
| | | 969 | | |
| | | 970 | | private async ValueTask SendRequestContentAsync(HttpRequestMessage request, HttpContentWriteStream stream, bool |
| | 0 | 971 | | { |
| | 0 | 972 | | Debug.Assert(stream.BytesWritten == 0); |
| | 0 | 973 | | if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.RequestContentStart(); |
| | | 974 | | |
| | | 975 | | // Copy all of the data to the server. |
| | 0 | 976 | | if (async) |
| | 0 | 977 | | { |
| | 0 | 978 | | await request.Content!.CopyToAsync(stream, _transportContext, cancellationToken).ConfigureAwait(false); |
| | 0 | 979 | | } |
| | | 980 | | else |
| | 0 | 981 | | { |
| | 0 | 982 | | request.Content!.CopyTo(stream, _transportContext, cancellationToken); |
| | 0 | 983 | | } |
| | | 984 | | |
| | | 985 | | // Finish the content; with a chunked upload, this includes writing the terminating chunk. |
| | 0 | 986 | | await stream.FinishAsync(async).ConfigureAwait(false); |
| | | 987 | | |
| | | 988 | | // Flush any content that might still be buffered. |
| | 0 | 989 | | await FlushAsync(async).ConfigureAwait(false); |
| | | 990 | | |
| | 0 | 991 | | if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.RequestContentStop(stream.BytesWritten); |
| | | 992 | | |
| | 0 | 993 | | if (NetEventSource.Log.IsEnabled()) Trace("Finished sending request content."); |
| | 0 | 994 | | } |
| | | 995 | | |
| | | 996 | | private async Task SendRequestContentWithExpect100ContinueAsync( |
| | | 997 | | HttpRequestMessage request, Task<bool> allowExpect100ToContinueTask, |
| | | 998 | | HttpContentWriteStream stream, Timer expect100Timer, bool async, CancellationToken cancellationToken) |
| | 0 | 999 | | { |
| | | 1000 | | // Wait until we receive a trigger notification that it's ok to continue sending content. |
| | | 1001 | | // This will come either when the timer fires or when we receive a response status line from the server. |
| | 0 | 1002 | | bool sendRequestContent = await allowExpect100ToContinueTask.ConfigureAwait(false); |
| | | 1003 | | |
| | | 1004 | | // Clean up the timer; it's no longer needed. |
| | 0 | 1005 | | expect100Timer.Dispose(); |
| | | 1006 | | |
| | | 1007 | | // Send the content if we're supposed to. Otherwise, we're done. |
| | 0 | 1008 | | if (sendRequestContent) |
| | 0 | 1009 | | { |
| | 0 | 1010 | | if (NetEventSource.Log.IsEnabled()) Trace($"Sending request content for Expect: 100-continue."); |
| | | 1011 | | try |
| | 0 | 1012 | | { |
| | 0 | 1013 | | await SendRequestContentAsync(request, stream, async, cancellationToken).ConfigureAwait(false); |
| | 0 | 1014 | | } |
| | 0 | 1015 | | catch |
| | 0 | 1016 | | { |
| | | 1017 | | // Tear down the connection if called from the timer thread because caller's thread will wait for se |
| | | 1018 | | // or till HttpClient.Timeout tear the connection itself. |
| | 0 | 1019 | | Dispose(); |
| | 0 | 1020 | | throw; |
| | | 1021 | | } |
| | 0 | 1022 | | } |
| | | 1023 | | else |
| | 0 | 1024 | | { |
| | 0 | 1025 | | if (NetEventSource.Log.IsEnabled()) Trace($"Canceling request content for Expect: 100-continue."); |
| | 0 | 1026 | | } |
| | 0 | 1027 | | } |
| | | 1028 | | |
| | | 1029 | | private bool ParseStatusLine(HttpResponseMessage response) |
| | 0 | 1030 | | { |
| | 0 | 1031 | | Span<byte> buffer = _readBuffer.ActiveSpan; |
| | | 1032 | | |
| | 0 | 1033 | | int lineFeedIndex = buffer.IndexOf((byte)'\n'); |
| | 0 | 1034 | | if (lineFeedIndex >= 0) |
| | 0 | 1035 | | { |
| | 0 | 1036 | | int bytesConsumed = lineFeedIndex + 1; |
| | 0 | 1037 | | _readBuffer.Discard(bytesConsumed); |
| | 0 | 1038 | | _allowedReadLineBytes -= bytesConsumed; |
| | | 1039 | | |
| | 0 | 1040 | | int carriageReturnIndex = lineFeedIndex - 1; |
| | 0 | 1041 | | int length = (uint)carriageReturnIndex < (uint)buffer.Length && buffer[carriageReturnIndex] == '\r' |
| | 0 | 1042 | | ? carriageReturnIndex |
| | 0 | 1043 | | : lineFeedIndex; |
| | | 1044 | | |
| | 0 | 1045 | | ParseStatusLineCore(buffer.Slice(0, length), response); |
| | 0 | 1046 | | return true; |
| | | 1047 | | } |
| | | 1048 | | else |
| | 0 | 1049 | | { |
| | 0 | 1050 | | if (_allowedReadLineBytes <= buffer.Length) |
| | 0 | 1051 | | { |
| | 0 | 1052 | | ThrowExceededAllowedReadLineBytes(); |
| | 0 | 1053 | | } |
| | 0 | 1054 | | return false; |
| | | 1055 | | } |
| | 0 | 1056 | | } |
| | | 1057 | | |
| | | 1058 | | private static void ParseStatusLineCore(Span<byte> line, HttpResponseMessage response) |
| | 0 | 1059 | | { |
| | | 1060 | | // We sent the request version as either 1.0 or 1.1. |
| | | 1061 | | // We expect a response version of the form 1.X, where X is a single digit as per RFC. |
| | | 1062 | | |
| | | 1063 | | // Validate the beginning of the status line and set the response version. |
| | | 1064 | | const int MinStatusLineLength = 12; // "HTTP/1.x 123" |
| | 0 | 1065 | | if (line.Length < MinStatusLineLength || line[8] != ' ') |
| | 0 | 1066 | | { |
| | 0 | 1067 | | throw new HttpRequestException(HttpRequestError.InvalidResponse, SR.Format(SR.net_http_invalid_response_ |
| | | 1068 | | } |
| | | 1069 | | |
| | 0 | 1070 | | ulong first8Bytes = BitConverter.ToUInt64(line); |
| | 0 | 1071 | | if (first8Bytes == s_http11Bytes) |
| | 0 | 1072 | | { |
| | 0 | 1073 | | response.SetVersionWithoutValidation(HttpVersion.Version11); |
| | 0 | 1074 | | } |
| | 0 | 1075 | | else if (first8Bytes == s_http10Bytes) |
| | 0 | 1076 | | { |
| | 0 | 1077 | | response.SetVersionWithoutValidation(HttpVersion.Version10); |
| | 0 | 1078 | | } |
| | | 1079 | | else |
| | 0 | 1080 | | { |
| | 0 | 1081 | | byte minorVersion = line[7]; |
| | 0 | 1082 | | if (IsDigit(minorVersion) && line.StartsWith("HTTP/1."u8)) |
| | 0 | 1083 | | { |
| | 0 | 1084 | | response.SetVersionWithoutValidation(new Version(1, minorVersion - '0')); |
| | 0 | 1085 | | } |
| | | 1086 | | else |
| | 0 | 1087 | | { |
| | 0 | 1088 | | throw new HttpRequestException(HttpRequestError.InvalidResponse, SR.Format(SR.net_http_invalid_respo |
| | | 1089 | | } |
| | 0 | 1090 | | } |
| | | 1091 | | |
| | | 1092 | | // Set the status code |
| | 0 | 1093 | | byte status1 = line[9], status2 = line[10], status3 = line[11]; |
| | 0 | 1094 | | if (!IsDigit(status1) || !IsDigit(status2) || !IsDigit(status3)) |
| | 0 | 1095 | | { |
| | 0 | 1096 | | throw new HttpRequestException(HttpRequestError.InvalidResponse, SR.Format(SR.net_http_invalid_response_ |
| | | 1097 | | } |
| | 0 | 1098 | | response.SetStatusCodeWithoutValidation((HttpStatusCode)(100 * (status1 - '0') + 10 * (status2 - '0') + (sta |
| | | 1099 | | |
| | | 1100 | | // Parse (optional) reason phrase |
| | 0 | 1101 | | if (line.Length == MinStatusLineLength) |
| | 0 | 1102 | | { |
| | 0 | 1103 | | response.SetReasonPhraseWithoutValidation(string.Empty); |
| | 0 | 1104 | | } |
| | 0 | 1105 | | else if (line[MinStatusLineLength] == ' ') |
| | 0 | 1106 | | { |
| | 0 | 1107 | | ReadOnlySpan<byte> reasonBytes = line.Slice(MinStatusLineLength + 1); |
| | 0 | 1108 | | string? knownReasonPhrase = HttpStatusDescription.Get(response.StatusCode); |
| | 0 | 1109 | | if (knownReasonPhrase != null && Ascii.Equals(reasonBytes, knownReasonPhrase)) |
| | 0 | 1110 | | { |
| | 0 | 1111 | | response.SetReasonPhraseWithoutValidation(knownReasonPhrase); |
| | 0 | 1112 | | } |
| | | 1113 | | else |
| | 0 | 1114 | | { |
| | | 1115 | | try |
| | 0 | 1116 | | { |
| | 0 | 1117 | | response.ReasonPhrase = HttpRuleParser.DefaultHttpEncoding.GetString(reasonBytes); |
| | 0 | 1118 | | } |
| | 0 | 1119 | | catch (FormatException formatEx) |
| | 0 | 1120 | | { |
| | 0 | 1121 | | throw new HttpRequestException(HttpRequestError.InvalidResponse, SR.Format(SR.net_http_invalid_r |
| | | 1122 | | } |
| | 0 | 1123 | | } |
| | 0 | 1124 | | } |
| | | 1125 | | else |
| | 0 | 1126 | | { |
| | 0 | 1127 | | throw new HttpRequestException(HttpRequestError.InvalidResponse, SR.Format(SR.net_http_invalid_response_ |
| | | 1128 | | } |
| | 0 | 1129 | | } |
| | | 1130 | | |
| | | 1131 | | private bool ParseHeaders(HttpResponseMessage? response, bool isFromTrailer) |
| | 0 | 1132 | | { |
| | 0 | 1133 | | Span<byte> buffer = _readBuffer.ActiveSpan; |
| | | 1134 | | |
| | 0 | 1135 | | (bool finished, int bytesConsumed) = ParseHeadersCore(buffer, response, isFromTrailer); |
| | | 1136 | | |
| | 0 | 1137 | | int bytesScanned = finished ? bytesConsumed : buffer.Length; |
| | 0 | 1138 | | if (_allowedReadLineBytes < bytesScanned) |
| | 0 | 1139 | | { |
| | 0 | 1140 | | ThrowExceededAllowedReadLineBytes(); |
| | 0 | 1141 | | } |
| | | 1142 | | |
| | 0 | 1143 | | _readBuffer.Discard(bytesConsumed); |
| | 0 | 1144 | | _allowedReadLineBytes -= bytesConsumed; |
| | 0 | 1145 | | Debug.Assert(_allowedReadLineBytes >= 0); |
| | | 1146 | | |
| | 0 | 1147 | | return finished; |
| | 0 | 1148 | | } |
| | | 1149 | | |
| | | 1150 | | private (bool finished, int bytesConsumed) ParseHeadersCore(Span<byte> buffer, HttpResponseMessage? response, bo |
| | 0 | 1151 | | { |
| | 0 | 1152 | | int originalBufferLength = buffer.Length; |
| | | 1153 | | |
| | 0 | 1154 | | while (true) |
| | 0 | 1155 | | { |
| | 0 | 1156 | | int colIdx = buffer.IndexOfAny((byte)':', (byte)'\n'); |
| | 0 | 1157 | | if (colIdx < 0) |
| | 0 | 1158 | | { |
| | 0 | 1159 | | return (finished: false, bytesConsumed: originalBufferLength - buffer.Length); |
| | | 1160 | | } |
| | | 1161 | | |
| | 0 | 1162 | | if (buffer[colIdx] == '\n') |
| | 0 | 1163 | | { |
| | 0 | 1164 | | if ((colIdx == 1 && buffer[0] == '\r') || colIdx == 0) |
| | 0 | 1165 | | { |
| | 0 | 1166 | | return (finished: true, bytesConsumed: originalBufferLength - buffer.Length + colIdx + 1); |
| | | 1167 | | } |
| | | 1168 | | |
| | 0 | 1169 | | ThrowForInvalidHeaderLine(buffer, colIdx); |
| | 0 | 1170 | | } |
| | | 1171 | | |
| | 0 | 1172 | | int valueStartIdx = colIdx + 1; |
| | 0 | 1173 | | if ((uint)valueStartIdx >= (uint)buffer.Length) |
| | 0 | 1174 | | { |
| | 0 | 1175 | | return (finished: false, bytesConsumed: originalBufferLength - buffer.Length); |
| | | 1176 | | } |
| | | 1177 | | |
| | | 1178 | | // Iterate over the value and handle any line folds (new lines followed by SP/HTAB). |
| | | 1179 | | // valueIterator refers to the remainder of the buffer that we can still scan for new lines. |
| | 0 | 1180 | | Span<byte> valueIterator = buffer.Slice(valueStartIdx); |
| | | 1181 | | |
| | 0 | 1182 | | while (true) |
| | 0 | 1183 | | { |
| | 0 | 1184 | | int lfIdx = valueIterator.IndexOf((byte)'\n'); |
| | 0 | 1185 | | if ((uint)lfIdx >= (uint)valueIterator.Length) |
| | 0 | 1186 | | { |
| | 0 | 1187 | | return (finished: false, bytesConsumed: originalBufferLength - buffer.Length); |
| | | 1188 | | } |
| | | 1189 | | |
| | 0 | 1190 | | int crIdx = lfIdx - 1; |
| | 0 | 1191 | | int crOrLfIdx = (uint)crIdx < (uint)valueIterator.Length && valueIterator[crIdx] == '\r' |
| | 0 | 1192 | | ? crIdx |
| | 0 | 1193 | | : lfIdx; |
| | | 1194 | | |
| | 0 | 1195 | | int spIdx = lfIdx + 1; |
| | 0 | 1196 | | if ((uint)spIdx >= (uint)valueIterator.Length) |
| | 0 | 1197 | | { |
| | 0 | 1198 | | return (finished: false, bytesConsumed: originalBufferLength - buffer.Length); |
| | | 1199 | | } |
| | | 1200 | | |
| | 0 | 1201 | | if (valueIterator[spIdx] is not (byte)'\t' and not (byte)' ') |
| | 0 | 1202 | | { |
| | | 1203 | | // Found the end of the header value. |
| | | 1204 | | |
| | 0 | 1205 | | if (response is not null) |
| | 0 | 1206 | | { |
| | 0 | 1207 | | ReadOnlySpan<byte> headerName = buffer.Slice(0, valueStartIdx - 1); |
| | 0 | 1208 | | ReadOnlySpan<byte> headerValue = buffer.Slice(valueStartIdx, buffer.Length - valueIterator.L |
| | 0 | 1209 | | AddResponseHeader(headerName, headerValue, response, isFromTrailer); |
| | 0 | 1210 | | } |
| | | 1211 | | |
| | 0 | 1212 | | buffer = buffer.Slice(buffer.Length - valueIterator.Length + spIdx); |
| | 0 | 1213 | | break; |
| | | 1214 | | } |
| | | 1215 | | |
| | | 1216 | | // Found an obs-fold (CRLFHT/CRLFSP). |
| | | 1217 | | // Replace the CRLF with SPSP and keep looking for the final newline. |
| | 0 | 1218 | | valueIterator[crOrLfIdx] = (byte)' '; |
| | 0 | 1219 | | valueIterator[lfIdx] = (byte)' '; |
| | | 1220 | | |
| | 0 | 1221 | | valueIterator = valueIterator.Slice(spIdx + 1); |
| | 0 | 1222 | | } |
| | 0 | 1223 | | } |
| | | 1224 | | |
| | | 1225 | | static void ThrowForInvalidHeaderLine(ReadOnlySpan<byte> buffer, int newLineIndex) => |
| | 0 | 1226 | | throw new HttpRequestException(HttpRequestError.InvalidResponse, SR.Format(SR.net_http_invalid_response_ |
| | 0 | 1227 | | } |
| | | 1228 | | |
| | | 1229 | | private void AddResponseHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value, HttpResponseMessage response, |
| | 0 | 1230 | | { |
| | | 1231 | | // Skip trailing whitespace and check for empty length. |
| | 0 | 1232 | | while (true) |
| | 0 | 1233 | | { |
| | 0 | 1234 | | int spIdx = name.Length - 1; |
| | | 1235 | | |
| | 0 | 1236 | | if ((uint)spIdx < (uint)name.Length) |
| | 0 | 1237 | | { |
| | 0 | 1238 | | if (name[spIdx] != ' ') |
| | 0 | 1239 | | { |
| | | 1240 | | // hot path |
| | 0 | 1241 | | break; |
| | | 1242 | | } |
| | | 1243 | | |
| | 0 | 1244 | | name = name.Slice(0, spIdx); |
| | 0 | 1245 | | } |
| | | 1246 | | else |
| | 0 | 1247 | | { |
| | 0 | 1248 | | ThrowForEmptyHeaderName(); |
| | 0 | 1249 | | } |
| | 0 | 1250 | | } |
| | | 1251 | | |
| | | 1252 | | // Skip leading OWS for value. |
| | | 1253 | | // hot path: loop body runs only once. |
| | 0 | 1254 | | while (value.Length != 0 && value[0] is (byte)' ' or (byte)'\t') |
| | 0 | 1255 | | { |
| | 0 | 1256 | | value = value.Slice(1); |
| | 0 | 1257 | | } |
| | | 1258 | | |
| | | 1259 | | // Skip trailing OWS for value. |
| | 0 | 1260 | | while (true) |
| | 0 | 1261 | | { |
| | 0 | 1262 | | int spIdx = value.Length - 1; |
| | | 1263 | | |
| | 0 | 1264 | | if ((uint)spIdx >= (uint)value.Length || !(value[spIdx] is (byte)' ' or (byte)'\t')) |
| | 0 | 1265 | | { |
| | | 1266 | | // hot path |
| | 0 | 1267 | | break; |
| | | 1268 | | } |
| | | 1269 | | |
| | 0 | 1270 | | value = value.Slice(0, spIdx); |
| | 0 | 1271 | | } |
| | | 1272 | | |
| | 0 | 1273 | | if (!HeaderDescriptor.TryGet(name, out HeaderDescriptor descriptor)) |
| | 0 | 1274 | | { |
| | 0 | 1275 | | ThrowForInvalidHeaderName(name); |
| | 0 | 1276 | | } |
| | | 1277 | | |
| | 0 | 1278 | | Encoding? valueEncoding = _pool.Settings._responseHeaderEncodingSelector?.Invoke(descriptor.Name, _currentRe |
| | | 1279 | | |
| | 0 | 1280 | | HttpHeaderType headerType = descriptor.HeaderType; |
| | | 1281 | | |
| | | 1282 | | // Request headers returned on the response must be treated as custom headers. |
| | 0 | 1283 | | if ((headerType & HttpHeaderType.Request) != 0) |
| | 0 | 1284 | | { |
| | 0 | 1285 | | descriptor = descriptor.AsCustomHeader(); |
| | 0 | 1286 | | } |
| | | 1287 | | |
| | | 1288 | | string headerValue; |
| | | 1289 | | HttpHeaders headers; |
| | | 1290 | | |
| | 0 | 1291 | | if (isFromTrailer) |
| | 0 | 1292 | | { |
| | 0 | 1293 | | if ((headerType & HttpHeaderType.NonTrailing) != 0) |
| | 0 | 1294 | | { |
| | | 1295 | | // Disallowed trailer fields. |
| | | 1296 | | // A recipient MUST ignore fields that are forbidden to be sent in a trailer. |
| | 0 | 1297 | | return; |
| | | 1298 | | } |
| | | 1299 | | |
| | 0 | 1300 | | headerValue = descriptor.GetHeaderValue(value, valueEncoding); |
| | 0 | 1301 | | headers = response.TrailingHeaders; |
| | 0 | 1302 | | } |
| | 0 | 1303 | | else if ((headerType & HttpHeaderType.Content) != 0) |
| | 0 | 1304 | | { |
| | 0 | 1305 | | headerValue = descriptor.GetHeaderValue(value, valueEncoding); |
| | 0 | 1306 | | headers = response.Content!.Headers; |
| | 0 | 1307 | | } |
| | | 1308 | | else |
| | 0 | 1309 | | { |
| | 0 | 1310 | | headerValue = GetResponseHeaderValueWithCaching(descriptor, value, valueEncoding); |
| | 0 | 1311 | | headers = response.Headers; |
| | | 1312 | | |
| | 0 | 1313 | | if (descriptor.Equals(KnownHeaders.KeepAlive)) |
| | 0 | 1314 | | { |
| | | 1315 | | // We are intentionally going against RFC to honor the Keep-Alive header even if |
| | | 1316 | | // we haven't received a Keep-Alive connection token to maximize compat with servers. |
| | 0 | 1317 | | ProcessKeepAliveHeader(headerValue); |
| | 0 | 1318 | | } |
| | 0 | 1319 | | } |
| | | 1320 | | |
| | 0 | 1321 | | bool added = headers.TryAddWithoutValidation(descriptor, headerValue); |
| | 0 | 1322 | | Debug.Assert(added); |
| | | 1323 | | |
| | | 1324 | | static void ThrowForEmptyHeaderName() => |
| | 0 | 1325 | | throw new HttpRequestException(HttpRequestError.InvalidResponse, SR.Format(SR.net_http_invalid_response_ |
| | | 1326 | | |
| | | 1327 | | static void ThrowForInvalidHeaderName(ReadOnlySpan<byte> name) => |
| | 0 | 1328 | | throw new HttpRequestException(HttpRequestError.InvalidResponse, SR.Format(SR.net_http_invalid_response_ |
| | 0 | 1329 | | } |
| | | 1330 | | |
| | | 1331 | | private void ThrowExceededAllowedReadLineBytes() => |
| | 0 | 1332 | | throw new HttpRequestException(HttpRequestError.ConfigurationLimitExceeded, SR.Format(SR.net_http_response_h |
| | | 1333 | | |
| | | 1334 | | private void ProcessKeepAliveHeader(string keepAlive) |
| | 0 | 1335 | | { |
| | 0 | 1336 | | var parsedValues = new UnvalidatedObjectCollection<NameValueHeaderValue>(); |
| | | 1337 | | |
| | 0 | 1338 | | if (NameValueHeaderValue.GetNameValueListLength(keepAlive, 0, ',', parsedValues) == keepAlive.Length) |
| | 0 | 1339 | | { |
| | 0 | 1340 | | foreach (NameValueHeaderValue nameValue in parsedValues) |
| | 0 | 1341 | | { |
| | | 1342 | | // The HTTP/1.1 spec does not define any parameters for the Keep-Alive header, so we are using the d |
| | 0 | 1343 | | if (string.Equals(nameValue.Name, "timeout", StringComparison.OrdinalIgnoreCase)) |
| | 0 | 1344 | | { |
| | 0 | 1345 | | if (!string.IsNullOrEmpty(nameValue.Value) && |
| | 0 | 1346 | | HeaderUtilities.TryParseInt32(nameValue.Value, out int timeout) && |
| | 0 | 1347 | | timeout >= 0) |
| | 0 | 1348 | | { |
| | | 1349 | | // Some servers are very strict with closing the connection exactly at the timeout. |
| | | 1350 | | // Avoid using the connection if it is about to exceed the timeout to avoid resulting reques |
| | | 1351 | | const int OffsetSeconds = 1; |
| | | 1352 | | |
| | 0 | 1353 | | if (timeout <= OffsetSeconds) |
| | 0 | 1354 | | { |
| | 0 | 1355 | | _connectionClose = true; |
| | 0 | 1356 | | } |
| | | 1357 | | else |
| | 0 | 1358 | | { |
| | 0 | 1359 | | _keepAliveTimeoutSeconds = timeout - OffsetSeconds; |
| | 0 | 1360 | | } |
| | 0 | 1361 | | } |
| | 0 | 1362 | | } |
| | 0 | 1363 | | else if (string.Equals(nameValue.Name, "max", StringComparison.OrdinalIgnoreCase)) |
| | 0 | 1364 | | { |
| | 0 | 1365 | | if (nameValue.Value == "0") |
| | 0 | 1366 | | { |
| | 0 | 1367 | | _connectionClose = true; |
| | 0 | 1368 | | } |
| | 0 | 1369 | | } |
| | 0 | 1370 | | } |
| | 0 | 1371 | | } |
| | 0 | 1372 | | } |
| | | 1373 | | |
| | | 1374 | | private void WriteToBuffer(ReadOnlySpan<byte> source) |
| | 0 | 1375 | | { |
| | 0 | 1376 | | Debug.Assert(source.Length <= _writeBuffer.AvailableLength); |
| | 0 | 1377 | | source.CopyTo(_writeBuffer.AvailableSpan); |
| | 0 | 1378 | | _writeBuffer.Commit(source.Length); |
| | 0 | 1379 | | } |
| | | 1380 | | |
| | | 1381 | | private void Write(ReadOnlySpan<byte> source) |
| | 0 | 1382 | | { |
| | 0 | 1383 | | int remaining = _writeBuffer.AvailableLength; |
| | | 1384 | | |
| | 0 | 1385 | | if (source.Length <= remaining) |
| | 0 | 1386 | | { |
| | | 1387 | | // Fits in current write buffer. Just copy and return. |
| | 0 | 1388 | | WriteToBuffer(source); |
| | 0 | 1389 | | return; |
| | | 1390 | | } |
| | | 1391 | | |
| | 0 | 1392 | | if (_writeBuffer.ActiveLength != 0) |
| | 0 | 1393 | | { |
| | | 1394 | | // Fit what we can in the current write buffer and flush it. |
| | 0 | 1395 | | WriteToBuffer(source.Slice(0, remaining)); |
| | 0 | 1396 | | source = source.Slice(remaining); |
| | 0 | 1397 | | Flush(); |
| | 0 | 1398 | | } |
| | | 1399 | | |
| | 0 | 1400 | | if (source.Length >= _writeBuffer.Capacity) |
| | 0 | 1401 | | { |
| | | 1402 | | // Large write. No sense buffering this. Write directly to stream. |
| | 0 | 1403 | | WriteToStream(source); |
| | 0 | 1404 | | } |
| | | 1405 | | else |
| | 0 | 1406 | | { |
| | | 1407 | | // Copy remainder into buffer |
| | 0 | 1408 | | WriteToBuffer(source); |
| | 0 | 1409 | | } |
| | 0 | 1410 | | } |
| | | 1411 | | |
| | | 1412 | | private ValueTask WriteAsync(ReadOnlyMemory<byte> source) |
| | 0 | 1413 | | { |
| | 0 | 1414 | | int remaining = _writeBuffer.AvailableLength; |
| | | 1415 | | |
| | 0 | 1416 | | if (source.Length <= remaining) |
| | 0 | 1417 | | { |
| | | 1418 | | // Fits in current write buffer. Just copy and return. |
| | 0 | 1419 | | WriteToBuffer(source.Span); |
| | 0 | 1420 | | return default; |
| | | 1421 | | } |
| | | 1422 | | |
| | 0 | 1423 | | if (_writeBuffer.ActiveLength != 0) |
| | 0 | 1424 | | { |
| | | 1425 | | // Fit what we can in the current write buffer and flush it. |
| | 0 | 1426 | | WriteToBuffer(source.Span.Slice(0, remaining)); |
| | 0 | 1427 | | source = source.Slice(remaining); |
| | | 1428 | | |
| | 0 | 1429 | | ValueTask flushTask = FlushAsync(async: true); |
| | | 1430 | | |
| | 0 | 1431 | | if (flushTask.IsCompletedSuccessfully) |
| | 0 | 1432 | | { |
| | 0 | 1433 | | flushTask.GetAwaiter().GetResult(); |
| | | 1434 | | |
| | 0 | 1435 | | if (source.Length <= _writeBuffer.Capacity) |
| | 0 | 1436 | | { |
| | 0 | 1437 | | WriteToBuffer(source.Span); |
| | 0 | 1438 | | return default; |
| | | 1439 | | } |
| | | 1440 | | |
| | | 1441 | | // Fall-through to WriteToStreamAsync |
| | 0 | 1442 | | } |
| | | 1443 | | else |
| | 0 | 1444 | | { |
| | 0 | 1445 | | return AwaitFlushAndWriteAsync(flushTask, source); |
| | | 1446 | | } |
| | 0 | 1447 | | } |
| | | 1448 | | |
| | | 1449 | | // Large write. No sense buffering this. Write directly to stream. |
| | 0 | 1450 | | return WriteToStreamAsync(source, async: true); |
| | | 1451 | | |
| | | 1452 | | async ValueTask AwaitFlushAndWriteAsync(ValueTask flushTask, ReadOnlyMemory<byte> source) |
| | 0 | 1453 | | { |
| | 0 | 1454 | | await flushTask.ConfigureAwait(false); |
| | | 1455 | | |
| | 0 | 1456 | | if (source.Length <= _writeBuffer.Capacity) |
| | 0 | 1457 | | { |
| | 0 | 1458 | | WriteToBuffer(source.Span); |
| | 0 | 1459 | | } |
| | | 1460 | | else |
| | 0 | 1461 | | { |
| | 0 | 1462 | | await WriteToStreamAsync(source, async: true).ConfigureAwait(false); |
| | 0 | 1463 | | } |
| | 0 | 1464 | | } |
| | 0 | 1465 | | } |
| | | 1466 | | |
| | | 1467 | | private void WriteWithoutBuffering(ReadOnlySpan<byte> source) |
| | 0 | 1468 | | { |
| | 0 | 1469 | | if (_writeBuffer.ActiveLength != 0) |
| | 0 | 1470 | | { |
| | 0 | 1471 | | if (source.Length <= _writeBuffer.AvailableLength) |
| | 0 | 1472 | | { |
| | | 1473 | | // There's something already in the write buffer, but the content |
| | | 1474 | | // we're writing can also fit after it in the write buffer. Copy |
| | | 1475 | | // the content to the write buffer and then flush it, so that we |
| | | 1476 | | // can do a single send rather than two. |
| | 0 | 1477 | | WriteToBuffer(source); |
| | 0 | 1478 | | Flush(); |
| | 0 | 1479 | | return; |
| | | 1480 | | } |
| | | 1481 | | |
| | | 1482 | | // There's data in the write buffer and the data we're writing doesn't fit after it. |
| | | 1483 | | // Do two writes, one to flush the buffer and then another to write the supplied content. |
| | 0 | 1484 | | Flush(); |
| | 0 | 1485 | | } |
| | | 1486 | | |
| | 0 | 1487 | | WriteToStream(source); |
| | 0 | 1488 | | } |
| | | 1489 | | |
| | | 1490 | | private ValueTask WriteWithoutBufferingAsync(ReadOnlyMemory<byte> source, bool async) |
| | 0 | 1491 | | { |
| | 0 | 1492 | | if (_writeBuffer.ActiveLength == 0) |
| | 0 | 1493 | | { |
| | | 1494 | | // There's nothing in the write buffer we need to flush. |
| | | 1495 | | // Just write the supplied data out to the stream. |
| | 0 | 1496 | | return WriteToStreamAsync(source, async); |
| | | 1497 | | } |
| | | 1498 | | |
| | 0 | 1499 | | if (source.Length <= _writeBuffer.AvailableLength) |
| | 0 | 1500 | | { |
| | | 1501 | | // There's something already in the write buffer, but the content |
| | | 1502 | | // we're writing can also fit after it in the write buffer. Copy |
| | | 1503 | | // the content to the write buffer and then flush it, so that we |
| | | 1504 | | // can do a single send rather than two. |
| | 0 | 1505 | | WriteToBuffer(source.Span); |
| | 0 | 1506 | | return FlushAsync(async); |
| | | 1507 | | } |
| | | 1508 | | |
| | | 1509 | | // There's data in the write buffer and the data we're writing doesn't fit after it. |
| | | 1510 | | // Do two writes, one to flush the buffer and then another to write the supplied content. |
| | 0 | 1511 | | return FlushThenWriteWithoutBufferingAsync(source, async); |
| | 0 | 1512 | | } |
| | | 1513 | | |
| | | 1514 | | private async ValueTask FlushThenWriteWithoutBufferingAsync(ReadOnlyMemory<byte> source, bool async) |
| | 0 | 1515 | | { |
| | 0 | 1516 | | await FlushAsync(async).ConfigureAwait(false); |
| | 0 | 1517 | | await WriteToStreamAsync(source, async).ConfigureAwait(false); |
| | 0 | 1518 | | } |
| | | 1519 | | |
| | | 1520 | | private ValueTask WriteHexInt32Async(int value, bool async) |
| | 0 | 1521 | | { |
| | | 1522 | | // Try to format into our output buffer directly. |
| | 0 | 1523 | | if (value.TryFormat(_writeBuffer.AvailableSpan, out int bytesWritten, "X")) |
| | 0 | 1524 | | { |
| | 0 | 1525 | | _writeBuffer.Commit(bytesWritten); |
| | 0 | 1526 | | return default; |
| | | 1527 | | } |
| | | 1528 | | |
| | | 1529 | | // If we don't have enough room, do it the slow way. |
| | 0 | 1530 | | if (async) |
| | 0 | 1531 | | { |
| | 0 | 1532 | | Span<byte> temp = stackalloc byte[8]; // max length of Int32 as hex |
| | 0 | 1533 | | bool formatted = value.TryFormat(temp, out bytesWritten, "X"); |
| | 0 | 1534 | | Debug.Assert(formatted); |
| | 0 | 1535 | | return WriteAsync(temp.Slice(0, bytesWritten).ToArray()); |
| | | 1536 | | } |
| | | 1537 | | else |
| | 0 | 1538 | | { |
| | | 1539 | | // We should have enough capacity to write any hex-encoded int after flushing the buffer. |
| | 0 | 1540 | | Debug.Assert(_writeBuffer.Capacity >= 8); |
| | | 1541 | | |
| | 0 | 1542 | | Flush(); |
| | 0 | 1543 | | return WriteHexInt32Async(value, async: false); |
| | | 1544 | | } |
| | 0 | 1545 | | } |
| | | 1546 | | |
| | | 1547 | | private void Flush() |
| | 0 | 1548 | | { |
| | 0 | 1549 | | ReadOnlySpan<byte> bytes = _writeBuffer.ActiveSpan; |
| | 0 | 1550 | | if (bytes.Length > 0) |
| | 0 | 1551 | | { |
| | 0 | 1552 | | _writeBuffer.Discard(bytes.Length); |
| | 0 | 1553 | | WriteToStream(bytes); |
| | 0 | 1554 | | } |
| | 0 | 1555 | | } |
| | | 1556 | | |
| | | 1557 | | private ValueTask FlushAsync(bool async) |
| | 0 | 1558 | | { |
| | 0 | 1559 | | ReadOnlyMemory<byte> bytes = _writeBuffer.ActiveMemory; |
| | 0 | 1560 | | if (bytes.Length > 0) |
| | 0 | 1561 | | { |
| | 0 | 1562 | | _writeBuffer.Discard(bytes.Length); |
| | 0 | 1563 | | return WriteToStreamAsync(bytes, async); |
| | | 1564 | | } |
| | 0 | 1565 | | return default; |
| | 0 | 1566 | | } |
| | | 1567 | | |
| | | 1568 | | private void WriteToStream(ReadOnlySpan<byte> source) |
| | 0 | 1569 | | { |
| | 0 | 1570 | | if (NetEventSource.Log.IsEnabled()) Trace($"Writing {source.Length} bytes."); |
| | 0 | 1571 | | _stream.Write(source); |
| | 0 | 1572 | | } |
| | | 1573 | | |
| | | 1574 | | private ValueTask WriteToStreamAsync(ReadOnlyMemory<byte> source, bool async) |
| | 0 | 1575 | | { |
| | 0 | 1576 | | if (NetEventSource.Log.IsEnabled()) Trace($"Writing {source.Length} bytes."); |
| | | 1577 | | |
| | 0 | 1578 | | if (async) |
| | 0 | 1579 | | { |
| | 0 | 1580 | | return _stream.WriteAsync(source); |
| | | 1581 | | } |
| | | 1582 | | else |
| | 0 | 1583 | | { |
| | 0 | 1584 | | _stream.Write(source.Span); |
| | 0 | 1585 | | return default; |
| | | 1586 | | } |
| | 0 | 1587 | | } |
| | | 1588 | | |
| | | 1589 | | private bool TryReadNextChunkedLine(out ReadOnlySpan<byte> line) |
| | 0 | 1590 | | { |
| | 0 | 1591 | | ReadOnlySpan<byte> buffer = _readBuffer.ActiveReadOnlySpan; |
| | | 1592 | | |
| | 0 | 1593 | | int lineFeedIndex = buffer.IndexOf((byte)'\n'); |
| | 0 | 1594 | | if (lineFeedIndex < 0) |
| | 0 | 1595 | | { |
| | 0 | 1596 | | if (buffer.Length < MaxChunkBytesAllowed) |
| | 0 | 1597 | | { |
| | 0 | 1598 | | line = default; |
| | 0 | 1599 | | return false; |
| | | 1600 | | } |
| | 0 | 1601 | | } |
| | | 1602 | | else |
| | 0 | 1603 | | { |
| | 0 | 1604 | | int bytesConsumed = lineFeedIndex + 1; |
| | 0 | 1605 | | if (bytesConsumed <= MaxChunkBytesAllowed) |
| | 0 | 1606 | | { |
| | 0 | 1607 | | _readBuffer.Discard(bytesConsumed); |
| | | 1608 | | |
| | 0 | 1609 | | int carriageReturnIndex = lineFeedIndex - 1; |
| | | 1610 | | |
| | 0 | 1611 | | int length = (uint)carriageReturnIndex < (uint)buffer.Length && buffer[carriageReturnIndex] == '\r' |
| | 0 | 1612 | | ? carriageReturnIndex |
| | 0 | 1613 | | : lineFeedIndex; |
| | | 1614 | | |
| | 0 | 1615 | | line = buffer.Slice(0, length); |
| | 0 | 1616 | | return true; |
| | | 1617 | | } |
| | 0 | 1618 | | } |
| | | 1619 | | |
| | 0 | 1620 | | throw new HttpRequestException(SR.net_http_chunk_too_large); |
| | 0 | 1621 | | } |
| | | 1622 | | |
| | | 1623 | | // Does not throw on EOF. Also assumes there is no buffered data. |
| | | 1624 | | private async ValueTask InitialFillAsync(bool async) |
| | 0 | 1625 | | { |
| | 0 | 1626 | | Debug.Assert(!ReadAheadTaskHasStarted); |
| | 0 | 1627 | | Debug.Assert(_readBuffer.AvailableLength == _readBuffer.Capacity); |
| | 0 | 1628 | | Debug.Assert(_readBuffer.AvailableLength >= InitialReadBufferSize); |
| | | 1629 | | |
| | 0 | 1630 | | int bytesRead = async ? |
| | 0 | 1631 | | await _stream.ReadAsync(_readBuffer.AvailableMemory).ConfigureAwait(false) : |
| | 0 | 1632 | | _stream.Read(_readBuffer.AvailableSpan); |
| | | 1633 | | |
| | 0 | 1634 | | _readBuffer.Commit(bytesRead); |
| | | 1635 | | |
| | 0 | 1636 | | if (NetEventSource.Log.IsEnabled()) Trace($"Received {bytesRead} bytes."); |
| | 0 | 1637 | | } |
| | | 1638 | | |
| | | 1639 | | // Throws IOException on EOF. This is only called when we expect more data. |
| | | 1640 | | private async ValueTask FillAsync(bool async) |
| | 0 | 1641 | | { |
| | 0 | 1642 | | Debug.Assert(_readAheadTask == default); |
| | | 1643 | | |
| | 0 | 1644 | | _readBuffer.EnsureAvailableSpace(1); |
| | | 1645 | | |
| | 0 | 1646 | | int bytesRead = async ? |
| | 0 | 1647 | | await _stream.ReadAsync(_readBuffer.AvailableMemory).ConfigureAwait(false) : |
| | 0 | 1648 | | _stream.Read(_readBuffer.AvailableSpan); |
| | | 1649 | | |
| | 0 | 1650 | | _readBuffer.Commit(bytesRead); |
| | | 1651 | | |
| | 0 | 1652 | | if (NetEventSource.Log.IsEnabled()) Trace($"Received {bytesRead} bytes."); |
| | 0 | 1653 | | if (bytesRead == 0) |
| | 0 | 1654 | | { |
| | 0 | 1655 | | throw new HttpIOException(HttpRequestError.ResponseEnded, SR.net_http_invalid_response_premature_eof); |
| | | 1656 | | } |
| | 0 | 1657 | | } |
| | | 1658 | | |
| | | 1659 | | private ValueTask FillForHeadersAsync(bool async) |
| | 0 | 1660 | | { |
| | | 1661 | | // If the start offset is 0, it means we haven't consumed any data since the last FillAsync. |
| | | 1662 | | // If so, read until we either find the next new line or we hit the MaxResponseHeadersLength limit. |
| | 0 | 1663 | | return _readBuffer.ActiveStartOffset == 0 |
| | 0 | 1664 | | ? ReadUntilEndOfHeaderAsync(async) |
| | 0 | 1665 | | : FillAsync(async); |
| | | 1666 | | |
| | | 1667 | | // This method guarantees that the next call to ParseHeaders will consume at least one header. |
| | | 1668 | | // This is the slow path, but guarantees O(n) worst-case parsing complexity. |
| | | 1669 | | async ValueTask ReadUntilEndOfHeaderAsync(bool async) |
| | 0 | 1670 | | { |
| | 0 | 1671 | | int searchOffset = _readBuffer.ActiveLength; |
| | 0 | 1672 | | if (searchOffset > 0) |
| | 0 | 1673 | | { |
| | | 1674 | | // The last character we've buffered could be a new line, |
| | | 1675 | | // we just haven't checked the byte following it to see if it's a space or tab. |
| | 0 | 1676 | | searchOffset--; |
| | 0 | 1677 | | } |
| | | 1678 | | |
| | 0 | 1679 | | while (true) |
| | 0 | 1680 | | { |
| | 0 | 1681 | | await FillAsync(async).ConfigureAwait(false); |
| | 0 | 1682 | | Debug.Assert(_readBuffer.ActiveStartOffset == 0); |
| | 0 | 1683 | | Debug.Assert(_readBuffer.ActiveLength > searchOffset); |
| | | 1684 | | |
| | | 1685 | | // There's no need to search the whole buffer, only look through the new bytes we just read. |
| | 0 | 1686 | | if (TryFindEndOfLine(_readBuffer.ActiveReadOnlySpan.Slice(searchOffset), out int offset)) |
| | 0 | 1687 | | { |
| | 0 | 1688 | | break; |
| | | 1689 | | } |
| | | 1690 | | |
| | 0 | 1691 | | searchOffset += offset; |
| | | 1692 | | |
| | 0 | 1693 | | int readLength = _readBuffer.ActiveLength; |
| | 0 | 1694 | | if (searchOffset != readLength) |
| | 0 | 1695 | | { |
| | 0 | 1696 | | Debug.Assert(searchOffset == readLength - 1 && _readBuffer.ActiveReadOnlySpan[searchOffset] == ' |
| | 0 | 1697 | | if (readLength <= 2) |
| | 0 | 1698 | | { |
| | | 1699 | | // There are no headers - we start off with a new line. |
| | | 1700 | | // This is reachable from ChunkedEncodingReadStream if the buffers allign just right and the |
| | 0 | 1701 | | break; |
| | | 1702 | | } |
| | 0 | 1703 | | } |
| | | 1704 | | |
| | 0 | 1705 | | if (readLength >= _allowedReadLineBytes) |
| | 0 | 1706 | | { |
| | 0 | 1707 | | ThrowExceededAllowedReadLineBytes(); |
| | 0 | 1708 | | } |
| | 0 | 1709 | | } |
| | | 1710 | | |
| | | 1711 | | static bool TryFindEndOfLine(ReadOnlySpan<byte> buffer, out int searchOffset) |
| | 0 | 1712 | | { |
| | 0 | 1713 | | Debug.Assert(buffer.Length > 0); |
| | | 1714 | | |
| | 0 | 1715 | | int originalBufferLength = buffer.Length; |
| | | 1716 | | |
| | 0 | 1717 | | while (true) |
| | 0 | 1718 | | { |
| | 0 | 1719 | | int newLineOffset = buffer.IndexOf((byte)'\n'); |
| | 0 | 1720 | | if (newLineOffset < 0) |
| | 0 | 1721 | | { |
| | 0 | 1722 | | searchOffset = originalBufferLength; |
| | 0 | 1723 | | return false; |
| | | 1724 | | } |
| | | 1725 | | |
| | 0 | 1726 | | int tabOrSpaceIndex = newLineOffset + 1; |
| | 0 | 1727 | | if (tabOrSpaceIndex == buffer.Length) |
| | 0 | 1728 | | { |
| | | 1729 | | // The new line is the last character, read again to make sure it doesn't continue with spac |
| | 0 | 1730 | | searchOffset = originalBufferLength - 1; |
| | 0 | 1731 | | return false; |
| | | 1732 | | } |
| | | 1733 | | |
| | 0 | 1734 | | if (buffer[tabOrSpaceIndex] is not (byte)'\t' and not (byte)' ') |
| | 0 | 1735 | | { |
| | 0 | 1736 | | searchOffset = 0; |
| | 0 | 1737 | | return true; |
| | | 1738 | | } |
| | | 1739 | | |
| | 0 | 1740 | | buffer = buffer.Slice(tabOrSpaceIndex + 1); |
| | 0 | 1741 | | } |
| | 0 | 1742 | | } |
| | 0 | 1743 | | } |
| | 0 | 1744 | | } |
| | | 1745 | | |
| | | 1746 | | private int ReadFromBuffer(Span<byte> buffer) |
| | 0 | 1747 | | { |
| | 0 | 1748 | | ReadOnlySpan<byte> available = _readBuffer.ActiveSpan; |
| | 0 | 1749 | | int toCopy = Math.Min(available.Length, buffer.Length); |
| | | 1750 | | |
| | 0 | 1751 | | available.Slice(0, toCopy).CopyTo(buffer); |
| | 0 | 1752 | | _readBuffer.Discard(toCopy); |
| | | 1753 | | |
| | 0 | 1754 | | return toCopy; |
| | 0 | 1755 | | } |
| | | 1756 | | |
| | | 1757 | | private int Read(Span<byte> destination) |
| | 0 | 1758 | | { |
| | | 1759 | | // This is called when reading the response body. |
| | | 1760 | | |
| | 0 | 1761 | | if (_readBuffer.ActiveLength > 0) |
| | 0 | 1762 | | { |
| | | 1763 | | // We have data in the read buffer. Return it to the caller. |
| | 0 | 1764 | | return ReadFromBuffer(destination); |
| | | 1765 | | } |
| | | 1766 | | |
| | | 1767 | | // No data in read buffer. |
| | | 1768 | | // Do an unbuffered read directly against the underlying stream. |
| | 0 | 1769 | | Debug.Assert(_readAheadTask == default, "Read ahead task should have been consumed as part of the headers.") |
| | 0 | 1770 | | int count = _stream.Read(destination); |
| | 0 | 1771 | | if (NetEventSource.Log.IsEnabled()) Trace($"Received {count} bytes."); |
| | 0 | 1772 | | return count; |
| | 0 | 1773 | | } |
| | | 1774 | | |
| | | 1775 | | private ValueTask<int> ReadAsync(Memory<byte> destination) |
| | 0 | 1776 | | { |
| | | 1777 | | // This is called when reading the response body. |
| | | 1778 | | |
| | 0 | 1779 | | if (_readBuffer.ActiveLength > 0) |
| | 0 | 1780 | | { |
| | | 1781 | | // We have data in the read buffer. Return it to the caller. |
| | 0 | 1782 | | return new ValueTask<int>(ReadFromBuffer(destination.Span)); |
| | | 1783 | | } |
| | | 1784 | | |
| | | 1785 | | // No data in read buffer. |
| | | 1786 | | // Do an unbuffered read directly against the underlying stream. |
| | 0 | 1787 | | Debug.Assert(_readAheadTask == default, "Read ahead task should have been consumed as part of the headers.") |
| | | 1788 | | |
| | 0 | 1789 | | return NetEventSource.Log.IsEnabled() |
| | 0 | 1790 | | ? ReadAndLogBytesReadAsync(destination) |
| | 0 | 1791 | | : _stream.ReadAsync(destination); |
| | | 1792 | | |
| | | 1793 | | async ValueTask<int> ReadAndLogBytesReadAsync(Memory<byte> destination) |
| | 0 | 1794 | | { |
| | 0 | 1795 | | int count = await _stream.ReadAsync(destination).ConfigureAwait(false); |
| | 0 | 1796 | | if (NetEventSource.Log.IsEnabled()) Trace($"Received {count} bytes."); |
| | 0 | 1797 | | return count; |
| | 0 | 1798 | | } |
| | 0 | 1799 | | } |
| | | 1800 | | |
| | | 1801 | | private int ReadBuffered(Span<byte> destination) |
| | 0 | 1802 | | { |
| | | 1803 | | // This is called when reading the response body. |
| | | 1804 | | |
| | 0 | 1805 | | if (_readBuffer.ActiveLength == 0) |
| | 0 | 1806 | | { |
| | | 1807 | | // Do a buffered read directly against the underlying stream. |
| | 0 | 1808 | | Debug.Assert(_readAheadTask == default, "Read ahead task should have been consumed as part of the header |
| | | 1809 | | |
| | 0 | 1810 | | if (destination.Length == 0) |
| | 0 | 1811 | | { |
| | 0 | 1812 | | return _stream.Read(Array.Empty<byte>()); |
| | | 1813 | | } |
| | | 1814 | | |
| | 0 | 1815 | | Debug.Assert(_readBuffer.AvailableLength == _readBuffer.Capacity); |
| | 0 | 1816 | | int bytesRead = _stream.Read(_readBuffer.AvailableSpan); |
| | 0 | 1817 | | _readBuffer.Commit(bytesRead); |
| | | 1818 | | |
| | 0 | 1819 | | if (NetEventSource.Log.IsEnabled()) Trace($"Received {bytesRead} bytes."); |
| | 0 | 1820 | | } |
| | | 1821 | | |
| | | 1822 | | // Hand back as much data as we can fit. |
| | 0 | 1823 | | return ReadFromBuffer(destination); |
| | 0 | 1824 | | } |
| | | 1825 | | |
| | | 1826 | | private ValueTask<int> ReadBufferedAsync(Memory<byte> destination) |
| | 0 | 1827 | | { |
| | | 1828 | | // If the caller provided buffer, and thus the amount of data desired to be read, |
| | | 1829 | | // is larger than the internal buffer, there's no point going through the internal |
| | | 1830 | | // buffer, so just do an unbuffered read. |
| | | 1831 | | // Also avoid avoid using the internal buffer if the user requested a zero-byte read to allow |
| | | 1832 | | // underlying streams to efficiently handle such a read (e.g. SslStream defering buffer allocation). |
| | 0 | 1833 | | return destination.Length >= _readBuffer.Capacity || destination.Length == 0 ? |
| | 0 | 1834 | | ReadAsync(destination) : |
| | 0 | 1835 | | ReadBufferedAsyncCore(destination); |
| | 0 | 1836 | | } |
| | | 1837 | | |
| | | 1838 | | [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))] |
| | | 1839 | | private async ValueTask<int> ReadBufferedAsyncCore(Memory<byte> destination) |
| | 0 | 1840 | | { |
| | | 1841 | | // This is called when reading the response body. |
| | | 1842 | | |
| | 0 | 1843 | | if (_readBuffer.ActiveLength == 0) |
| | 0 | 1844 | | { |
| | | 1845 | | // Do a buffered read directly against the underlying stream. |
| | 0 | 1846 | | Debug.Assert(_readAheadTask == default, "Read ahead task should have been consumed as part of the header |
| | | 1847 | | |
| | 0 | 1848 | | Debug.Assert(_readBuffer.AvailableLength == _readBuffer.Capacity); |
| | 0 | 1849 | | int bytesRead = await _stream.ReadAsync(_readBuffer.AvailableMemory).ConfigureAwait(false); |
| | 0 | 1850 | | _readBuffer.Commit(bytesRead); |
| | | 1851 | | |
| | 0 | 1852 | | if (NetEventSource.Log.IsEnabled()) Trace($"Received {bytesRead} bytes."); |
| | 0 | 1853 | | } |
| | | 1854 | | |
| | | 1855 | | // Hand back as much data as we can fit. |
| | 0 | 1856 | | return ReadFromBuffer(destination.Span); |
| | 0 | 1857 | | } |
| | | 1858 | | |
| | | 1859 | | private ValueTask CopyFromBufferAsync(Stream destination, bool async, int count, CancellationToken cancellationT |
| | 0 | 1860 | | { |
| | 0 | 1861 | | Debug.Assert(count <= _readBuffer.ActiveLength); |
| | | 1862 | | |
| | 0 | 1863 | | if (NetEventSource.Log.IsEnabled()) Trace($"Copying {count} bytes to stream."); |
| | | 1864 | | |
| | 0 | 1865 | | ReadOnlyMemory<byte> source = _readBuffer.ActiveMemory.Slice(0, count); |
| | 0 | 1866 | | _readBuffer.Discard(count); |
| | | 1867 | | |
| | 0 | 1868 | | if (async) |
| | 0 | 1869 | | { |
| | 0 | 1870 | | return destination.WriteAsync(source, cancellationToken); |
| | | 1871 | | } |
| | | 1872 | | else |
| | 0 | 1873 | | { |
| | 0 | 1874 | | destination.Write(source.Span); |
| | 0 | 1875 | | return default; |
| | | 1876 | | } |
| | 0 | 1877 | | } |
| | | 1878 | | |
| | | 1879 | | private Task CopyToUntilEofAsync(Stream destination, bool async, int bufferSize, CancellationToken cancellationT |
| | 0 | 1880 | | { |
| | 0 | 1881 | | Debug.Assert(destination != null); |
| | | 1882 | | |
| | 0 | 1883 | | if (_readBuffer.ActiveLength > 0) |
| | 0 | 1884 | | { |
| | 0 | 1885 | | return CopyToUntilEofWithExistingBufferedDataAsync(destination, async, bufferSize, cancellationToken); |
| | | 1886 | | } |
| | | 1887 | | |
| | 0 | 1888 | | if (async) |
| | 0 | 1889 | | { |
| | 0 | 1890 | | return _stream.CopyToAsync(destination, bufferSize, cancellationToken); |
| | | 1891 | | } |
| | | 1892 | | |
| | 0 | 1893 | | _stream.CopyTo(destination, bufferSize); |
| | 0 | 1894 | | return Task.CompletedTask; |
| | 0 | 1895 | | } |
| | | 1896 | | |
| | | 1897 | | private async Task CopyToUntilEofWithExistingBufferedDataAsync(Stream destination, bool async, int bufferSize, C |
| | 0 | 1898 | | { |
| | 0 | 1899 | | int remaining = _readBuffer.ActiveLength; |
| | 0 | 1900 | | Debug.Assert(remaining > 0); |
| | | 1901 | | |
| | 0 | 1902 | | await CopyFromBufferAsync(destination, async, remaining, cancellationToken).ConfigureAwait(false); |
| | | 1903 | | |
| | 0 | 1904 | | if (async) |
| | 0 | 1905 | | { |
| | 0 | 1906 | | await _stream.CopyToAsync(destination, bufferSize, cancellationToken).ConfigureAwait(false); |
| | 0 | 1907 | | } |
| | | 1908 | | else |
| | 0 | 1909 | | { |
| | 0 | 1910 | | _stream.CopyTo(destination, bufferSize); |
| | 0 | 1911 | | } |
| | 0 | 1912 | | } |
| | | 1913 | | |
| | | 1914 | | // Copy *exactly* [length] bytes into destination; throws on end of stream. |
| | | 1915 | | private async Task CopyToContentLengthAsync(Stream destination, bool async, ulong length, int bufferSize, Cancel |
| | 0 | 1916 | | { |
| | 0 | 1917 | | Debug.Assert(destination != null); |
| | 0 | 1918 | | Debug.Assert(length > 0); |
| | | 1919 | | |
| | | 1920 | | // Copy any data left in the connection's buffer to the destination. |
| | 0 | 1921 | | int remaining = _readBuffer.ActiveLength; |
| | 0 | 1922 | | if (remaining > 0) |
| | 0 | 1923 | | { |
| | 0 | 1924 | | if ((ulong)remaining > length) |
| | 0 | 1925 | | { |
| | 0 | 1926 | | remaining = (int)length; |
| | 0 | 1927 | | } |
| | 0 | 1928 | | await CopyFromBufferAsync(destination, async, remaining, cancellationToken).ConfigureAwait(false); |
| | | 1929 | | |
| | 0 | 1930 | | length -= (ulong)remaining; |
| | 0 | 1931 | | if (length == 0) |
| | 0 | 1932 | | { |
| | 0 | 1933 | | return; |
| | | 1934 | | } |
| | | 1935 | | |
| | 0 | 1936 | | Debug.Assert(_readBuffer.ActiveLength == 0, "HttpConnection's buffer should have been empty."); |
| | 0 | 1937 | | } |
| | | 1938 | | |
| | | 1939 | | // Repeatedly read into HttpConnection's buffer and write that buffer to the destination |
| | | 1940 | | // stream. If after doing so, we find that we filled the whole connection's buffer (which |
| | | 1941 | | // is sized mainly for HTTP headers rather than large payloads), grow the connection's |
| | | 1942 | | // read buffer to the requested buffer size to use for the remainder of the operation. We |
| | | 1943 | | // use a temporary buffer from the ArrayPool so that the connection doesn't hog large |
| | | 1944 | | // buffers from the pool for extended durations, especially if it's going to sit in the |
| | | 1945 | | // connection pool for a prolonged period. |
| | 0 | 1946 | | byte[]? origReadBuffer = null; |
| | | 1947 | | try |
| | 0 | 1948 | | { |
| | 0 | 1949 | | while (true) |
| | 0 | 1950 | | { |
| | 0 | 1951 | | await FillAsync(async).ConfigureAwait(false); |
| | | 1952 | | |
| | 0 | 1953 | | remaining = (int)Math.Min((ulong)_readBuffer.ActiveLength, length); |
| | 0 | 1954 | | await CopyFromBufferAsync(destination, async, remaining, cancellationToken).ConfigureAwait(false); |
| | | 1955 | | |
| | 0 | 1956 | | length -= (ulong)remaining; |
| | 0 | 1957 | | if (length == 0) |
| | 0 | 1958 | | { |
| | 0 | 1959 | | return; |
| | | 1960 | | } |
| | | 1961 | | |
| | | 1962 | | // If we haven't yet grown the buffer (if we previously grew it, then it's sufficiently large), and |
| | | 1963 | | // if we filled the read buffer while doing the last read (which is at least one indication that the |
| | | 1964 | | // data arrival rate is fast enough to warrant a larger buffer), and if the buffer size we'd want is |
| | | 1965 | | // larger than the one we already have, then grow the connection's read buffer to that size. |
| | 0 | 1966 | | if (origReadBuffer is null) |
| | 0 | 1967 | | { |
| | 0 | 1968 | | int currentCapacity = _readBuffer.Capacity; |
| | 0 | 1969 | | if (remaining == currentCapacity) |
| | 0 | 1970 | | { |
| | 0 | 1971 | | int desiredBufferSize = (int)Math.Min((ulong)bufferSize, length); |
| | 0 | 1972 | | if (desiredBufferSize > currentCapacity) |
| | 0 | 1973 | | { |
| | 0 | 1974 | | origReadBuffer = _readBuffer.DangerousGetUnderlyingBuffer(); |
| | 0 | 1975 | | byte[] pooledBuffer = ArrayPool<byte>.Shared.Rent(desiredBufferSize); |
| | 0 | 1976 | | _readBuffer = new ArrayBuffer(pooledBuffer); |
| | 0 | 1977 | | } |
| | 0 | 1978 | | } |
| | 0 | 1979 | | } |
| | 0 | 1980 | | } |
| | | 1981 | | } |
| | | 1982 | | finally |
| | 0 | 1983 | | { |
| | 0 | 1984 | | if (origReadBuffer is not null) |
| | 0 | 1985 | | { |
| | 0 | 1986 | | Debug.Assert(origReadBuffer.Length > 0); |
| | | 1987 | | |
| | | 1988 | | // We don't care how much remaining data there was, just if there was any. |
| | | 1989 | | // Subsequent code is going to check whether the receive buffer is empty |
| | | 1990 | | // and then force the connection closed if it's not. |
| | 0 | 1991 | | bool anyDataAvailable = _readBuffer.ActiveLength > 0; |
| | | 1992 | | |
| | 0 | 1993 | | byte[] pooledBuffer = _readBuffer.DangerousGetUnderlyingBuffer(); |
| | 0 | 1994 | | _readBuffer = new ArrayBuffer(origReadBuffer); |
| | 0 | 1995 | | ArrayPool<byte>.Shared.Return(pooledBuffer); |
| | | 1996 | | |
| | 0 | 1997 | | if (anyDataAvailable) |
| | 0 | 1998 | | { |
| | 0 | 1999 | | _readBuffer.Commit(1); |
| | 0 | 2000 | | } |
| | 0 | 2001 | | } |
| | 0 | 2002 | | } |
| | 0 | 2003 | | } |
| | | 2004 | | |
| | | 2005 | | internal void Acquire() |
| | 0 | 2006 | | { |
| | 0 | 2007 | | Debug.Assert(_currentRequest == null); |
| | 0 | 2008 | | Debug.Assert(!_inUse); |
| | | 2009 | | |
| | 0 | 2010 | | _inUse = true; |
| | 0 | 2011 | | } |
| | | 2012 | | |
| | | 2013 | | internal void Release() |
| | 0 | 2014 | | { |
| | 0 | 2015 | | Debug.Assert(_inUse); |
| | | 2016 | | |
| | 0 | 2017 | | _inUse = false; |
| | | 2018 | | |
| | | 2019 | | // If the last request already completed (because the response had no content), return the connection to the |
| | | 2020 | | // Otherwise, it will be returned when the response has been consumed and CompleteResponse below is called. |
| | 0 | 2021 | | if (_currentRequest == null) |
| | 0 | 2022 | | { |
| | 0 | 2023 | | ReturnConnectionToPool(); |
| | 0 | 2024 | | } |
| | 0 | 2025 | | } |
| | | 2026 | | |
| | | 2027 | | /// <summary> |
| | | 2028 | | /// Detach the connection from the pool, so it is no longer counted against the connection limit. |
| | | 2029 | | /// This is used when we are creating a replacement connection for NT auth challenges. |
| | | 2030 | | /// </summary> |
| | | 2031 | | internal void DetachFromPool() |
| | 0 | 2032 | | { |
| | 0 | 2033 | | Debug.Assert(_inUse); |
| | | 2034 | | |
| | 0 | 2035 | | _detachedFromPool = true; |
| | 0 | 2036 | | } |
| | | 2037 | | |
| | | 2038 | | private void CompleteResponse() |
| | 0 | 2039 | | { |
| | 0 | 2040 | | Debug.Assert(_currentRequest != null, "Expected the connection to be associated with a request."); |
| | 0 | 2041 | | Debug.Assert(_writeBuffer.ActiveLength == 0, "Everything in write buffer should have been flushed."); |
| | | 2042 | | |
| | | 2043 | | // Disassociate the connection from a request. |
| | 0 | 2044 | | _currentRequest = null; |
| | | 2045 | | |
| | | 2046 | | // If we have extraneous data in the read buffer, don't reuse the connection; |
| | | 2047 | | // otherwise we'd interpret this as part of the next response. Plus, we may |
| | | 2048 | | // have been using a temporary buffer to read this erroneous data, and thus |
| | | 2049 | | // may not even have it any more. |
| | 0 | 2050 | | if (_readBuffer.ActiveLength > 0) |
| | 0 | 2051 | | { |
| | 0 | 2052 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 2053 | | { |
| | 0 | 2054 | | Trace("Unexpected data on connection after response read."); |
| | 0 | 2055 | | } |
| | | 2056 | | |
| | 0 | 2057 | | _readBuffer.Discard(_readBuffer.ActiveLength); |
| | 0 | 2058 | | _connectionClose = true; |
| | 0 | 2059 | | } |
| | | 2060 | | |
| | | 2061 | | // If the connection is no longer in use (i.e. for NT authentication), then we can |
| | | 2062 | | // return it to the pool now; otherwise, it will be returned by the Release method later. |
| | | 2063 | | // The cancellation logic in HTTP/1.1 response stream reading methods is prone to race conditions |
| | | 2064 | | // where CancellationTokenRegistration callbacks may dispose the connection without the disposal |
| | | 2065 | | // leading to an actual cancellation of the response reading methods by an OperationCanceledException. |
| | | 2066 | | // To guard against these cases, it is necessary to check if the connection is disposed before |
| | | 2067 | | // attempting to return it to the pool. |
| | 0 | 2068 | | if (!_inUse && !_disposed) |
| | 0 | 2069 | | { |
| | 0 | 2070 | | ReturnConnectionToPool(); |
| | 0 | 2071 | | } |
| | 0 | 2072 | | } |
| | | 2073 | | |
| | | 2074 | | public async ValueTask DrainResponseAsync(HttpResponseMessage response, CancellationToken cancellationToken) |
| | 0 | 2075 | | { |
| | 0 | 2076 | | Debug.Assert(_inUse); |
| | | 2077 | | |
| | 0 | 2078 | | if (_connectionClose) |
| | 0 | 2079 | | { |
| | 0 | 2080 | | throw new HttpRequestException(HttpRequestError.UserAuthenticationError, SR.net_http_authconnectionfailu |
| | | 2081 | | } |
| | | 2082 | | |
| | 0 | 2083 | | Debug.Assert(response.Content != null); |
| | 0 | 2084 | | Stream stream = response.Content.ReadAsStream(cancellationToken); |
| | 0 | 2085 | | HttpContentReadStream? responseStream = stream as HttpContentReadStream; |
| | | 2086 | | |
| | 0 | 2087 | | Debug.Assert(responseStream != null || stream is EmptyReadStream); |
| | | 2088 | | |
| | 0 | 2089 | | if (responseStream != null && responseStream.NeedsDrain) |
| | 0 | 2090 | | { |
| | 0 | 2091 | | Debug.Assert(response.RequestMessage == _currentRequest); |
| | | 2092 | | |
| | 0 | 2093 | | if (!await responseStream.DrainAsync(_pool.Settings._maxResponseDrainSize).ConfigureAwait(false) || |
| | 0 | 2094 | | _connectionClose) // Draining may have set this |
| | 0 | 2095 | | { |
| | 0 | 2096 | | throw new HttpRequestException(HttpRequestError.UserAuthenticationError, SR.net_http_authconnectionf |
| | | 2097 | | } |
| | 0 | 2098 | | } |
| | | 2099 | | |
| | 0 | 2100 | | Debug.Assert(_currentRequest == null); |
| | | 2101 | | |
| | 0 | 2102 | | response.Dispose(); |
| | 0 | 2103 | | } |
| | | 2104 | | |
| | | 2105 | | private void ReturnConnectionToPool() |
| | 0 | 2106 | | { |
| | 0 | 2107 | | Debug.Assert(!_disposed, "Connection should not be disposed."); |
| | 0 | 2108 | | Debug.Assert(_currentRequest == null, "Connection should no longer be associated with a request."); |
| | 0 | 2109 | | Debug.Assert(_readAheadTask == default, "Expected a previous initial read to already be consumed."); |
| | 0 | 2110 | | Debug.Assert(_readAheadTaskStatus == ReadAheadTask_NotStarted, "Expected SendAsync to reset the read-ahead t |
| | 0 | 2111 | | Debug.Assert(_readBuffer.ActiveLength == 0, "Unexpected data in connection read buffer."); |
| | | 2112 | | |
| | | 2113 | | // If we decided not to reuse the connection (either because the server sent Connection: close, |
| | | 2114 | | // or there was some other problem while processing the request that makes the connection unusable), |
| | | 2115 | | // don't put the connection back in the pool. |
| | 0 | 2116 | | if (_connectionClose) |
| | 0 | 2117 | | { |
| | 0 | 2118 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 2119 | | { |
| | 0 | 2120 | | Trace("Connection will not be reused."); |
| | 0 | 2121 | | } |
| | | 2122 | | |
| | | 2123 | | // We're not putting the connection back in the pool. Dispose it. |
| | 0 | 2124 | | Dispose(); |
| | 0 | 2125 | | } |
| | | 2126 | | else |
| | 0 | 2127 | | { |
| | 0 | 2128 | | Debug.Assert(!_detachedFromPool, "Should not be detached from pool unless _connectionClose is true"); |
| | | 2129 | | |
| | | 2130 | | // Put connection back in the pool. |
| | 0 | 2131 | | _pool.RecycleHttp11Connection(this); |
| | 0 | 2132 | | } |
| | 0 | 2133 | | } |
| | | 2134 | | |
| | 0 | 2135 | | public sealed override string ToString() => $"{nameof(HttpConnection)}({_pool})"; // Description for diagnostic |
| | | 2136 | | |
| | | 2137 | | public sealed override void Trace(string message, [CallerMemberName] string? memberName = null) => |
| | 0 | 2138 | | NetEventSource.Log.HandlerMessage( |
| | 0 | 2139 | | _pool?.GetHashCode() ?? 0, // pool ID |
| | 0 | 2140 | | GetHashCode(), // connection ID |
| | 0 | 2141 | | _currentRequest?.GetHashCode() ?? 0, // request ID |
| | 0 | 2142 | | memberName, // method name |
| | 0 | 2143 | | message); // message |
| | | 2144 | | } |
| | | 2145 | | } |