Merge pull request dotnet/corefx#3199 from justinvp/winhttphandler_parseresponseheaders

Reduce allocations when parsing response headers in WinHttpHandler

Commit migrated from https://github.com/dotnet/corefx/commit/35f7ef05a8022358ec435152e7099d8263a4422a
This commit is contained in:
David Shulman committed 2016-02-18 15:52:45 -08:00
commit 52476494de
19 files changed
+1177 -247

No files matched your search

@@ -14,7 +14,11 @@
<CompileItem Include="$(CommonPath)\Interop\Windows\winhttp\Interop.winhttp_types.cs" />
<CompileItem Include="$(CommonPath)\Interop\Windows\winhttp\Interop.winhttp.cs" />
<CompileItem Include="$(CommonPath)\Microsoft\Win32\SafeHandles\SafeHandleZeroOrMinusOneIsInvalid.cs" />
<CompileItem Include="$(CommonPath)\System\CharArrayHelpers.cs" />
<CompileItem Include="$(CommonPath)\System\StringExtensions.cs" />
<CompileItem Include="$(CommonPath)\System\Net\HttpKnownHeaderNames.cs" />
<CompileItem Include="$(CommonPath)\System\Net\HttpKnownHeaderNames.TryGetHeaderName.cs" />
<CompileItem Include="$(CommonPath)\System\Net\HttpStatusDescription.cs" />
<CompileItem Include="$(CommonPath)\System\Net\HttpVersion.cs" />
<CompileItem Include="$(CommonPath)\System\Net\UriScheme.cs" />
<CompileItem Include="$(CommonPath)\System\Net\SecurityProtocol.cs" />
@@ -30,6 +34,7 @@
<CompileItem Include="$(MSBuildThisFileDirectory)\System\Net\Http\WinHttpRequestCallback.cs" />
<CompileItem Include="$(MSBuildThisFileDirectory)\System\Net\Http\WinHttpRequestState.cs" />
<CompileItem Include="$(MSBuildThisFileDirectory)\System\Net\Http\WinHttpRequestStream.cs" />
<CompileItem Include="$(MSBuildThisFileDirectory)\System\Net\Http\WinHttpResponseHeaderReader.cs" />
<CompileItem Include="$(MSBuildThisFileDirectory)\System\Net\Http\WinHttpResponseParser.cs" />
<CompileItem Include="$(MSBuildThisFileDirectory)\System\Net\Http\WinHttpResponseStream.cs" />
<CompileItem Include="$(MSBuildThisFileDirectory)\System\Net\Http\WinHttpTraceHelper.cs" />
@@ -19,16 +19,17 @@ namespace System.Net.Http
HttpRequestMessage request = state.RequestMessage;
SafeWinHttpHandle requestHandle = state.RequestHandle;
CookieContainer cookieContainer = state.Handler.CookieContainer;
Debug.Assert(state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer);
Debug.Assert(cookieContainer != null);
// Get 'Set-Cookie' headers from response.
List<string> cookieHeaders =
WinHttpResponseParser.GetResponseHeaders(requestHandle, Interop.WinHttp.WINHTTP_QUERY_SET_COOKIE);
char[] buffer = null;
uint index = 0;
string cookieHeader;
WinHttpTraceHelper.Trace("WINHTTP_QUERY_SET_COOKIE");
foreach (string cookieHeader in cookieHeaders)
while (WinHttpResponseParser.GetResponseHeader(
requestHandle, Interop.WinHttp.WINHTTP_QUERY_SET_COOKIE, ref buffer, ref index, out cookieHeader))
{
WinHttpTraceHelper.Trace(cookieHeader);
try
@@ -41,9 +42,9 @@ namespace System.Net.Http
// We ignore malformed cookies in the response.
WinHttpTraceHelper.Trace("Ignoring invalid cookie: {0}", cookieHeader);
}
}
}
}
public static void ResetCookieRequestHeaders(WinHttpRequestState state, Uri redirectUri)
{
SafeWinHttpHandle requestHandle = state.RequestHandle;
@@ -0,0 +1,161 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Net.Http
{
/// <summary>
/// Used to read header lines of an HTTP response, where each line is separated by "\r\n".
/// </summary>
internal struct WinHttpResponseHeaderReader
{
private const string Gzip = "gzip";
private const string Deflate = "deflate";
private readonly char[] _buffer;
private readonly int _length;
private int _position;
public WinHttpResponseHeaderReader(char[] buffer, int startIndex, int length)
{
CharArrayHelpers.DebugAssertArrayInputs(buffer, startIndex, length);
_buffer = buffer;
_position = startIndex;
_length = length;
}
/// <summary>
/// Reads a header line.
/// Empty header lines are skipped, as are malformed header lines that are missing a colon character.
/// </summary>
/// <returns>true if the next header was read successfully, or false if all characters have been read.</returns>
public bool ReadHeader(out string name, out string value)
{
int startIndex;
int length;
while (ReadLine(out startIndex, out length))
{
// Skip empty lines.
if (length == 0)
{
continue;
}
int colonIndex = Array.IndexOf(_buffer, ':', startIndex, length);
// Skip malformed header lines that are missing the colon character.
if (colonIndex == -1)
{
continue;
}
int nameLength = colonIndex - startIndex;
// If it's a known header name, use the known name instead of allocating a new string.
if (!HttpKnownHeaderNames.TryGetHeaderName(_buffer, startIndex, nameLength, out name))
{
name = new string(_buffer, startIndex, nameLength);
}
// Normalize header value by trimming white space.
int valueStartIndex = colonIndex + 1;
int valueLength = startIndex + length - colonIndex - 1;
CharArrayHelpers.Trim(_buffer, ref valueStartIndex, ref valueLength);
value = GetHeaderValue(name, _buffer, valueStartIndex, valueLength);
return true;
}
name = null;
value = null;
return false;
}
/// <summary>
/// Reads lines separated by "\r\n".
/// </summary>
/// <returns>true if the next line was read successfully, or false if all characters have been read.</returns>
public bool ReadLine()
{
int startIndex;
int length;
return ReadLine(out startIndex, out length);
}
/// <summary>
/// Reads lines separated by "\r\n".
/// </summary>
/// <param name="startIndex">The start of the line segment.</param>
/// <param name="length">The length of the line segment.</param>
/// <returns>true if the next line was read successfully, or false if all characters have been read.</returns>
private bool ReadLine(out int startIndex, out int length)
{
Debug.Assert(_buffer != null);
int i = _position;
while (i < _length)
{
char ch = _buffer[i];
if (ch == '\r')
{
int next = i + 1;
if (next < _length && _buffer[next] == '\n')
{
startIndex = _position;
length = i - _position;
_position = i + 2;
return true;
}
}
i++;
}
if (i > _position)
{
startIndex = _position;
length = i - _position;
_position = i;
return true;
}
startIndex = 0;
length = 0;
return false;
}
private static string GetHeaderValue(string name, char[] array, int startIndex, int length)
{
Debug.Assert(name != null);
CharArrayHelpers.DebugAssertArrayInputs(array, startIndex, length);
if (length == 0)
{
return string.Empty;
}
// If it's a known header value, use the known value instead of allocating a new string.
// Do a really quick reference equals check to see if name is the same object as
// HttpKnownHeaderNames.ContentEncoding, in which case the value is very likely to
// be either "gzip" or "deflate".
if (object.ReferenceEquals(name, HttpKnownHeaderNames.ContentEncoding))
{
if (CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase(Gzip, array, startIndex, length))
{
return Gzip;
}
else if (CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase(Deflate, array, startIndex, length))
{
return Deflate;
}
}
return new string(array, startIndex, length);
}
}
}
@@ -2,12 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Text;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
@@ -17,10 +16,6 @@ namespace System.Net.Http
{
private const string EncodingNameDeflate = "DEFLATE";
private const string EncodingNameGzip = "GZIP";
private const string HeaderNameContentEncoding = "Content-Encoding";
private const string HeaderNameContentLength = "Content-Length";
private const string HeaderNameSetCookie = "Set-Cookie";
private static readonly string[] s_HttpHeadersSeparator = { "\r\n" };
public static HttpResponseMessage CreateResponseMessage(
WinHttpRequestState state,
@@ -33,27 +28,29 @@ namespace System.Net.Http
var response = new HttpResponseMessage();
bool stripEncodingHeaders = false;
// Create a single buffer to use for all subsequent WinHttpQueryHeaders string interop calls.
// This buffer is the length needed for WINHTTP_QUERY_RAW_HEADERS_CRLF, which includes the status line
// and all headers separated by CRLF, so it should be large enough for any individual status line or header queries.
int bufferLength = GetResponseHeaderCharBufferLength(requestHandle, Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF);
char[] buffer = new char[bufferLength];
// Get HTTP version, status code, reason phrase from the response headers.
string version = GetResponseHeaderStringInfo(requestHandle, Interop.WinHttp.WINHTTP_QUERY_VERSION);
if (string.Compare("HTTP/1.1", version, StringComparison.OrdinalIgnoreCase) == 0)
{
response.Version = HttpVersion.Version11;
}
else if (string.Compare("HTTP/1.0", version, StringComparison.OrdinalIgnoreCase) == 0)
{
response.Version = HttpVersion.Version10;
}
else
{
response.Version = HttpVersion.Unknown;
}
int versionLength = GetResponseHeader(requestHandle, Interop.WinHttp.WINHTTP_QUERY_VERSION, buffer);
response.Version =
CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase("HTTP/1.1", buffer, 0, versionLength) ? HttpVersion.Version11 :
CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase("HTTP/1.0", buffer, 0, versionLength) ? HttpVersion.Version10 :
HttpVersion.Unknown;
response.StatusCode = (HttpStatusCode)GetResponseHeaderNumberInfo(
requestHandle,
Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE);
response.ReasonPhrase = GetResponseHeaderStringInfo(
requestHandle,
Interop.WinHttp.WINHTTP_QUERY_STATUS_TEXT);
int reasonPhraseLength = GetResponseHeader(requestHandle, Interop.WinHttp.WINHTTP_QUERY_STATUS_TEXT, buffer);
if (reasonPhraseLength > 0)
{
response.ReasonPhrase = GetReasonPhrase(response.StatusCode, buffer, reasonPhraseLength);
}
// Create response stream and wrap it in a StreamContent object.
var responseStream = new WinHttpResponseStream(state);
@@ -61,21 +58,28 @@ namespace System.Net.Http
if (doManualDecompressionCheck)
{
string contentEncoding = GetResponseHeaderStringInfo(
int contentEncodingStartIndex = 0;
int contentEncodingLength = GetResponseHeader(
requestHandle,
Interop.WinHttp.WINHTTP_QUERY_CONTENT_ENCODING);
if (!string.IsNullOrEmpty(contentEncoding))
Interop.WinHttp.WINHTTP_QUERY_CONTENT_ENCODING,
buffer);
CharArrayHelpers.Trim(buffer, ref contentEncodingStartIndex, ref contentEncodingLength);
if (contentEncodingLength > 0)
{
if (contentEncoding.IndexOf(EncodingNameDeflate, StringComparison.OrdinalIgnoreCase) > -1)
{
decompressedStream = new DeflateStream(responseStream, CompressionMode.Decompress);
stripEncodingHeaders = true;
}
else if (contentEncoding.IndexOf(EncodingNameGzip, StringComparison.OrdinalIgnoreCase) > -1)
if (CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase(
EncodingNameGzip, buffer, contentEncodingStartIndex, contentEncodingLength))
{
decompressedStream = new GZipStream(responseStream, CompressionMode.Decompress);
stripEncodingHeaders = true;
}
else if (CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase(
EncodingNameDeflate, buffer, contentEncodingStartIndex, contentEncodingLength))
{
decompressedStream = new DeflateStream(responseStream, CompressionMode.Decompress);
stripEncodingHeaders = true;
}
}
}
@@ -85,12 +89,14 @@ namespace System.Net.Http
response.RequestMessage = request;
// Parse raw response headers and place them into response message.
ParseResponseHeaders(requestHandle, response, stripEncodingHeaders);
ParseResponseHeaders(requestHandle, response, buffer, stripEncodingHeaders);
return response;
}
// Returns the first header or throws if header isn't found.
/// <summary>
/// Returns the first header or throws if the header isn't found.
/// </summary>
public static uint GetResponseHeaderNumberInfo(SafeWinHttpHandle requestHandle, uint infoLevel)
{
uint result = 0;
@@ -110,58 +116,104 @@ namespace System.Net.Http
return result;
}
// Returns the first header or null if header isn't found.
public static string GetResponseHeaderStringInfo(SafeWinHttpHandle requestHandle, uint infoLevel)
{
uint index = 0;
return GetResponseHeaderStringHelper(requestHandle, infoLevel, ref index);
}
// Returns all headers or an empty list if header isn't found.
public static List<string> GetResponseHeaders(SafeWinHttpHandle requestHandle, uint infoLevel)
{
uint index = 0;
var headerList = new List<string>();
string header;
while (true)
{
header = GetResponseHeaderStringHelper(requestHandle, infoLevel, ref index);
if (header == null)
{
break;
}
headerList.Add(header);
}
return headerList;
}
private static string GetResponseHeaderStringHelper(
public unsafe static bool GetResponseHeader(
SafeWinHttpHandle requestHandle,
uint infoLevel,
ref uint index)
ref char[] buffer,
ref uint index,
out string headerValue)
{
uint bytesNeeded = 0;
bool results = false;
const int StackLimit = 128;
// Call WinHttpQueryHeaders once to obtain the size of the buffer needed. The size is returned in
// bytes but the API actually returns Unicode characters.
if (!Interop.WinHttp.WinHttpQueryHeaders(
requestHandle,
infoLevel,
Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX,
null,
ref bytesNeeded,
ref index))
Debug.Assert(buffer == null || (buffer != null && buffer.Length > StackLimit));
int bufferLength;
if (buffer == null)
{
bufferLength = StackLimit;
char* pBuffer = stackalloc char[bufferLength];
if (QueryHeaders(requestHandle, infoLevel, pBuffer, ref bufferLength, ref index))
{
headerValue = new string(pBuffer, 0, bufferLength);
return true;
}
}
else
{
bufferLength = buffer.Length;
fixed (char* pBuffer = buffer)
{
if (QueryHeaders(requestHandle, infoLevel, pBuffer, ref bufferLength, ref index))
{
headerValue = new string(pBuffer, 0, bufferLength);
return true;
}
}
}
int lastError = Marshal.GetLastWin32Error();
if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
{
headerValue = null;
return false;
}
if (lastError == Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER)
{
buffer = new char[bufferLength];
return GetResponseHeader(requestHandle, infoLevel, ref buffer, ref index, out headerValue);
}
throw WinHttpException.CreateExceptionUsingError(lastError);
}
/// <summary>
/// Fills the buffer with the header value and returns the length, or returns 0 if the header isn't found.
/// </summary>
private unsafe static int GetResponseHeader(SafeWinHttpHandle requestHandle, uint infoLevel, char[] buffer)
{
Debug.Assert(buffer != null, "buffer must not be null.");
Debug.Assert(buffer.Length > 0, "buffer must not be empty.");
int bufferLength = buffer.Length;
uint index = 0;
fixed (char* pBuffer = buffer)
{
if (!QueryHeaders(requestHandle, infoLevel, pBuffer, ref bufferLength, ref index))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
{
return 0;
}
Debug.Assert(lastError != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER, "buffer must be of sufficient size.");
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
return bufferLength;
}
/// <summary>
/// Returns the size of the char array buffer.
/// </summary>
private unsafe static int GetResponseHeaderCharBufferLength(SafeWinHttpHandle requestHandle, uint infoLevel)
{
char* buffer = null;
int bufferLength = 0;
uint index = 0;
if (!QueryHeaders(requestHandle, infoLevel, buffer, ref bufferLength, ref index))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
{
return null;
}
Debug.Assert(lastError != Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND);
if (lastError != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER)
{
@@ -169,77 +221,93 @@ namespace System.Net.Http
}
}
// Allocate space for the buffer.
int charsNeeded = (int)bytesNeeded / sizeof(char);
var buffer = new StringBuilder(charsNeeded, charsNeeded);
return bufferLength;
}
results = Interop.WinHttp.WinHttpQueryHeaders(
private unsafe static bool QueryHeaders(
SafeWinHttpHandle requestHandle,
uint infoLevel,
char* buffer,
ref int bufferLength,
ref uint index)
{
Debug.Assert(bufferLength >= 0, "bufferLength must not be negative.");
// Convert the char buffer length to the length in bytes.
uint bufferLengthInBytes = (uint)bufferLength * sizeof(char);
// The WinHttpQueryHeaders buffer length is in bytes,
// but the API actually returns Unicode characters.
bool result = Interop.WinHttp.WinHttpQueryHeaders(
requestHandle,
infoLevel,
Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX,
buffer,
ref bytesNeeded,
new IntPtr(buffer),
ref bufferLengthInBytes,
ref index);
if (!results)
{
WinHttpException.ThrowExceptionUsingLastError();
}
return buffer.ToString();
// Convert the byte buffer length back to the length in chars.
bufferLength = (int)bufferLengthInBytes / sizeof(char);
return result;
}
private static string GetReasonPhrase(HttpStatusCode statusCode, char[] buffer, int bufferLength)
{
CharArrayHelpers.DebugAssertArrayInputs(buffer, 0, bufferLength);
Debug.Assert(bufferLength > 0);
// If it's a known reason phrase, use the known reason phrase instead of allocating a new string.
string knownReasonPhrase = HttpStatusDescription.Get(statusCode);
return (knownReasonPhrase != null && CharArrayHelpers.EqualsOrdinal(knownReasonPhrase, buffer, 0, bufferLength)) ?
knownReasonPhrase :
new string(buffer, 0, bufferLength);
}
private static void ParseResponseHeaders(
SafeWinHttpHandle requestHandle,
HttpResponseMessage response,
char[] buffer,
bool stripEncodingHeaders)
{
string rawResponseHeaders = GetResponseHeaderStringInfo(
HttpResponseHeaders responseHeaders = response.Headers;
HttpContentHeaders contentHeaders = response.Content.Headers;
int bufferLength = GetResponseHeader(
requestHandle,
Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF);
string[] responseHeaderArray = rawResponseHeaders.Split(
s_HttpHeadersSeparator,
StringSplitOptions.RemoveEmptyEntries);
Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF,
buffer);
var reader = new WinHttpResponseHeaderReader(buffer, 0, bufferLength);
// Skip the first line which contains status code, etc. information that we already parsed.
reader.ReadLine();
// Parse the array of headers and split them between Content headers and Response headers.
// Skip the first line which contains status code, etc. information that we already parsed.
for (int i = 1; i < responseHeaderArray.Length; i++)
string headerName;
string headerValue;
while (reader.ReadHeader(out headerName, out headerValue))
{
int colonIndex = responseHeaderArray[i].IndexOf(':');
// Skip malformed header lines that are missing the colon character.
if (colonIndex > 0)
if (!responseHeaders.TryAddWithoutValidation(headerName, headerValue))
{
string headerName = responseHeaderArray[i].Substring(0, colonIndex);
string headerValue = responseHeaderArray[i].SubstringTrim(colonIndex + 1); // Normalize header value by trimming white space.
if (!response.Headers.TryAddWithoutValidation(headerName, headerValue))
if (stripEncodingHeaders)
{
if (stripEncodingHeaders)
// Remove Content-Length and Content-Encoding headers if we are
// decompressing the response stream in the handler (due to
// WINHTTP not supporting it in a particular downlevel platform).
// This matches the behavior of WINHTTP when it does decompression itself.
if (string.Equals(HttpKnownHeaderNames.ContentLength, headerName, StringComparison.OrdinalIgnoreCase) ||
string.Equals(HttpKnownHeaderNames.ContentEncoding, headerName, StringComparison.OrdinalIgnoreCase))
{
// Remove Content-Length and Content-Encoding headers if we are
// decompressing the response stream in the handler (due to
// WINHTTP not supporting it in a particular downlevel platform).
// This matches the behavior of WINHTTP when it does decompression iself.
if (string.Equals(
HeaderNameContentLength,
headerName,
StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (string.Equals(
HeaderNameContentEncoding,
headerName,
StringComparison.OrdinalIgnoreCase))
{
continue;
}
continue;
}
// TODO: Issue #2165. Should we log if there is an error here?
response.Content.Headers.TryAddWithoutValidation(headerName, headerValue);
}
// TODO: Issue #2165. Should we log if there is an error here?
contentHeaders.TryAddWithoutValidation(headerName, headerValue);
}
}
}
@@ -258,7 +258,7 @@ internal static partial class Interop
public static bool WinHttpQueryHeaders(
SafeWinHttpHandle requestHandle,
uint infoLevel, string name,
StringBuilder buffer,
IntPtr buffer,
ref uint bufferLength,
ref uint index)
{
@@ -273,42 +273,20 @@ internal static partial class Interop
if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_VERSION)
{
if (buffer == null)
{
bufferLength = ((uint)httpVersion.Length + 1) * 2;
TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER;
return false;
}
buffer.Append(httpVersion);
return true;
return CopyToBufferOrFailIfInsufficientBufferLength(httpVersion, buffer, ref bufferLength);
}
if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_STATUS_TEXT)
{
if (buffer == null)
{
bufferLength = ((uint)statusText.Length + 1) * 2;
TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER;
return false;
}
buffer.Append(statusText);
return true;
return CopyToBufferOrFailIfInsufficientBufferLength(statusText, buffer, ref bufferLength);
}
if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_CONTENT_ENCODING)
{
string compression = null;
if (TestServer.ResponseHeaders.Contains("Content-Encoding: deflate"))
{
compression = "deflate";
}
else if (TestServer.ResponseHeaders.Contains("Content-Encoding: gzip"))
{
compression = "gzip";
}
string compression =
TestServer.ResponseHeaders.Contains("Content-Encoding: deflate") ? "deflate" :
TestServer.ResponseHeaders.Contains("Content-Encoding: gzip") ? "gzip" :
null;
if (compression == null)
{
@@ -316,33 +294,39 @@ internal static partial class Interop
return false;
}
if (buffer == null)
{
bufferLength = ((uint)compression.Length + 1) * 2;
TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER;
return false;
}
buffer.Append(compression);
return true;
return CopyToBufferOrFailIfInsufficientBufferLength(compression, buffer, ref bufferLength);
}
if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF)
{
if (buffer == null)
{
bufferLength = ((uint)TestServer.ResponseHeaders.Length + 1) * 2;
TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER;
return false;
}
buffer.Append(TestServer.ResponseHeaders);
return true;
return CopyToBufferOrFailIfInsufficientBufferLength(TestServer.ResponseHeaders, buffer, ref bufferLength);
}
return false;
}
private static bool CopyToBufferOrFailIfInsufficientBufferLength(string value, IntPtr buffer, ref uint bufferLength)
{
// The length of the string (plus terminating null char) in bytes.
uint bufferLengthNeeded = ((uint)value.Length + 1) * sizeof(char);
if (buffer == IntPtr.Zero || bufferLength < bufferLengthNeeded)
{
bufferLength = bufferLengthNeeded;
TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER;
return false;
}
// Copy the string to the buffer.
char[] temp = new char[value.Length + 1]; // null terminated.
value.CopyTo(0, temp, 0, value.Length);
Marshal.Copy(temp, 0, buffer, temp.Length);
// The length in bytes, minus the length of the null char at the end.
bufferLength = (uint)value.Length * sizeof(char);
return true;
}
public static bool WinHttpQueryHeaders(
SafeWinHttpHandle requestHandle,
uint infoLevel,
@@ -41,9 +41,21 @@
<Compile Include="$(CommonPath)\Microsoft\Win32\SafeHandles\SafeHandleZeroOrMinusOneIsInvalid.cs">
<Link>Common\Microsoft\Win32\SafeHandles\SafeHandleZeroOrMinusOneIsInvalid.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\CharArrayHelpers.cs">
<Link>Common\System\CharArrayHelpers.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\StringExtensions.cs">
<Link>Common\System\StringExtensions.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\HttpKnownHeaderNames.cs">
<Link>Common\System\Net\HttpKnownHeaderNames.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\HttpKnownHeaderNames.TryGetHeaderName.cs">
<Link>Common\System\Net\HttpKnownHeaderNames.TryGetHeaderName.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\HttpStatusDescription.cs">
<Link>Common\System\Net\HttpStatusDescription.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\HttpVersion.cs">
<Link>Common\System\Net\HttpVersion.cs</Link>
</Compile>
@@ -89,6 +101,9 @@
<Compile Include="..\..\src\System\Net\Http\WinHttpRequestStream.cs">
<Link>ProductionCode\WinHttpRequestStream.cs</Link>
</Compile>
<Compile Include="..\..\src\System\Net\Http\WinHttpResponseHeaderReader.cs">
<Link>ProductionCode\WinHttpResponseHeaderReader.cs</Link>
</Compile>
<Compile Include="..\..\src\System\Net\Http\WinHttpResponseParser.cs">
<Link>ProductionCode\WinHttpResponseParser.cs</Link>
</Compile>
@@ -118,6 +133,7 @@
<Compile Include="TestControl.cs" />
<Compile Include="WinHttpHandlerTest.cs" />
<Compile Include="WinHttpRequestStreamTest.cs" />
<Compile Include="WinHttpResponseHeaderReaderTest.cs" />
<Compile Include="WinHttpResponseStreamTest.cs" />
<Compile Include="XunitTestAssemblyAtrributes.cs" />
</ItemGroup>
@@ -0,0 +1,183 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Net.Http.WinHttpHandlerUnitTests
{
public class WinHttpResponseHeaderReaderTest
{
private static readonly KeyValuePair<string, string>[] s_emptyHeaders = Array.Empty<KeyValuePair<string, string>>();
[Fact]
public void ReadHeader_WithStatusLine_CanSkipStatusLineAndReadHeader()
{
char[] array = "HTTP/1.0 200 OK\r\nServer: Apache".ToCharArray();
var reader = new WinHttpResponseHeaderReader(array, 0, array.Length);
Assert.True(reader.ReadLine());
string name;
string value;
Assert.True(reader.ReadHeader(out name, out value));
Assert.Equal("Server", name);
Assert.Equal("Apache", value);
}
[Fact]
public void ReadHeader_KnownHeaderName_SameKnownHeaderNameObjectReturned()
{
char[] array = "Server: Apache".ToCharArray();
var reader = new WinHttpResponseHeaderReader(array, 0, array.Length);
string name;
string value;
Assert.True(reader.ReadHeader(out name, out value));
Assert.Same(HttpKnownHeaderNames.Server, name);
}
[Theory]
[InlineData("Content-Encoding: gzip")]
[InlineData("Content-Encoding: deflate")]
public void ReadHeader_KnownHeaderValue_SameHeaderValueObjectReturned(string header)
{
char[] array = (header + "\r\n" + header).ToCharArray();
var reader = new WinHttpResponseHeaderReader(array, 0, array.Length);
string name1;
string value1;
Assert.True(reader.ReadHeader(out name1, out value1));
string name2;
string value2;
Assert.True(reader.ReadHeader(out name2, out value2));
Assert.Same(value1, value2);
}
[Theory]
[MemberData("HeaderData")]
public void ReadHeader_VariousInputs_MatchesExpectedBehavior(string raw, KeyValuePair<string, string>[] expectedHeaders)
{
char[] array = raw.ToCharArray();
var reader = new WinHttpResponseHeaderReader(array, 0, array.Length);
string name;
string value;
for (int i = 0; i < expectedHeaders.Length; i++)
{
string expectedName = expectedHeaders[i].Key;
string expectedValue = expectedHeaders[i].Value;
Assert.True(reader.ReadHeader(out name, out value));
Assert.Equal(expectedName, name);
Assert.Equal(expectedValue, value);
}
Assert.False(reader.ReadHeader(out name, out value));
Assert.Null(name);
Assert.Null(value);
}
public static object[][] HeaderData =
{
new object[] { "", s_emptyHeaders },
new object[] { " ", s_emptyHeaders },
new object[] { "\t", s_emptyHeaders },
new object[] { "\r\n", s_emptyHeaders },
new object[] { "\r\n\r\n", s_emptyHeaders },
new object[] { "\r\n\r\n\r\n", s_emptyHeaders },
new object[] { "Content-Length: 50", new[] { CreateHeader("Content-Length", "50") } },
new object[] { "X-Custom-Header: Foo", new[] { CreateHeader("X-Custom-Header", "Foo") } },
new object[]
{
"Content-Length: 50\r\n" +
"Content-Encoding: gzip\r\n" +
"X-Powered-By: .NET",
new[]
{
CreateHeader("Content-Length", "50"),
CreateHeader("Content-Encoding", "gzip"),
CreateHeader("X-Powered-By", ".NET")
}
},
// No colon in a line, should be skipped
new object[]
{
"Content-Length: 50\r\n" +
"no colon, should be skipped\r\n" +
"X-Powered-By: .NET",
new[]
{
CreateHeader("Content-Length", "50"),
CreateHeader("X-Powered-By", ".NET")
}
},
// Empty lines (middle line) should be skipped
new object[]
{
"Content-Length: 50\r\n" +
"\r\n" +
"X-Powered-By: .NET",
new[]
{
CreateHeader("Content-Length", "50"),
CreateHeader("X-Powered-By", ".NET")
}
},
new object[]
{
"Content-Length: 50\r\n" +
"" +
"X-Powered-By: .NET",
new[]
{
CreateHeader("Content-Length", "50"),
CreateHeader("X-Powered-By", ".NET")
}
},
// Empty lines (last line) should be skipped
new object[]
{
"Content-Length: 50\r\n" +
"Content-Encoding: deflate\r\n" +
"X-Powered-By: .NET\r\n",
new[]
{
CreateHeader("Content-Length", "50"),
CreateHeader("Content-Encoding", "deflate"),
CreateHeader("X-Powered-By", ".NET")
}
},
// Values should be trimmed
new object[]
{
"Content-Length: 50 \r\n" +
"Content-Encoding: brotli \r\n" +
"X-Powered-By: .NET ",
new[]
{
CreateHeader("Content-Length", "50"),
CreateHeader("Content-Encoding", "brotli"),
CreateHeader("X-Powered-By", ".NET")
}
}
};
private static KeyValuePair<string, string> CreateHeader(string name, string value)
{
return new KeyValuePair<string, string>(name, value);
}
}
}