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

@@ -125,17 +125,7 @@ internal partial class Interop
SafeWinHttpHandle requestHandle,
uint infoLevel,
string name,
[Out] StringBuilder buffer,
ref uint bufferLength,
IntPtr index);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryHeaders(
SafeWinHttpHandle requestHandle,
uint infoLevel,
string name,
[Out] StringBuilder buffer,
IntPtr buffer,
ref uint bufferLength,
ref uint index);
@@ -0,0 +1,89 @@
// 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
{
internal static class CharArrayHelpers
{
internal static bool EqualsOrdinal(string left, char[] right, int rightStartIndex, int rightLength)
{
Debug.Assert(left != null);
DebugAssertArrayInputs(right, rightStartIndex, rightLength);
if (left.Length != rightLength)
{
return false;
}
for (int i = 0; i < left.Length; i++)
{
if (left[i] != right[rightStartIndex + i])
{
return false;
}
}
return true;
}
internal static bool EqualsOrdinalAsciiIgnoreCase(string left, char[] right, int rightStartIndex, int rightLength)
{
Debug.Assert(left != null);
DebugAssertArrayInputs(right, rightStartIndex, rightLength);
if (left.Length != rightLength)
{
return false;
}
for (int i = 0; i < left.Length; i++)
{
uint charA = left[i];
uint charB = right[rightStartIndex + i];
// We're only interested in ASCII characters here.
if ((charA - 'a') <= ('z' - 'a')) charA -= ('a' - 'A');
if ((charB - 'a') <= ('z' - 'a')) charB -= ('a' - 'A');
if (charA != charB)
{
return false;
}
}
return true;
}
internal static void Trim(char[] array, ref int startIndex, ref int length)
{
DebugAssertArrayInputs(array, startIndex, length);
int offset = 0;
while (offset < length && char.IsWhiteSpace(array[startIndex + offset]))
{
offset++;
}
int end = length - 1;
while (end >= offset && char.IsWhiteSpace(array[startIndex + end]))
{
end--;
}
startIndex += offset;
length = end - offset + 1;
}
[Conditional("DEBUG")]
internal static void DebugAssertArrayInputs(char[] array, int startIndex, int length)
{
Debug.Assert(array != null);
Debug.Assert(startIndex >= 0);
Debug.Assert(length >= 0);
Debug.Assert(startIndex <= array.Length - length);
}
}
}
@@ -0,0 +1,230 @@
// 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
{
internal static partial class HttpKnownHeaderNames
{
/// <summary>
/// Gets a known header name string from a matching char[] array segment, using an ordinal comparison.
/// Used to avoid allocating new strings for known header names.
/// </summary>
public static bool TryGetHeaderName(char[] key, int startIndex, int length, out string name)
{
CharArrayHelpers.DebugAssertArrayInputs(key, startIndex, length);
// When adding a new constant, add it to HttpKnownHeaderNames.cs as well.
// The lookup works as follows: first switch on the length of the passed-in char[] array segment.
//
// - If there is only one known header of that length and the char[] array segment matches that
// known header, set it as the out param and return true.
//
// - If there are more than one known headers of that length, switch on a unique char from that
// set of same-length known headers. Typically this will be the first char, but some sets of
// same-length known headers do not have unique chars in the first position, so a char in a
// position further in the strings is used. If the char[] array segment matches one of the
// known headers, set it as the out param and return true.
//
// - Otherwise, set the out param to null and return false.
switch (length)
{
case 2:
return TryMatch(TE, key, startIndex, length, out name); // TE
case 3:
switch (key[startIndex])
{
case 'A': return TryMatch(Age, key, startIndex, length, out name); // [A]ge
case 'P': return TryMatch(P3P, key, startIndex, length, out name); // [P]3P
case 'V': return TryMatch(Via, key, startIndex, length, out name); // [V]ia
}
break;
case 4:
switch (key[startIndex])
{
case 'D': return TryMatch(Date, key, startIndex, length, out name); // [D]ate
case 'E': return TryMatch(ETag, key, startIndex, length, out name); // [E]Tag
case 'F': return TryMatch(From, key, startIndex, length, out name); // [F]rom
case 'H': return TryMatch(Host, key, startIndex, length, out name); // [H]ost
case 'V': return TryMatch(Vary, key, startIndex, length, out name); // [V]ary
}
break;
case 5:
switch (key[startIndex])
{
case 'A': return TryMatch(Allow, key, startIndex, length, out name); // [A]llow
case 'R': return TryMatch(Range, key, startIndex, length, out name); // [R]ange
}
break;
case 6:
switch (key[startIndex])
{
case 'A': return TryMatch(Accept, key, startIndex, length, out name); // [A]ccept
case 'C': return TryMatch(Cookie, key, startIndex, length, out name); // [C]ookie
case 'E': return TryMatch(Expect, key, startIndex, length, out name); // [E]xpect
case 'O': return TryMatch(Origin, key, startIndex, length, out name); // [O]rigin
case 'P': return TryMatch(Pragma, key, startIndex, length, out name); // [P]ragma
case 'S': return TryMatch(Server, key, startIndex, length, out name); // [S]erver
}
break;
case 7:
switch (key[startIndex])
{
case 'C': return TryMatch(Cookie2, key, startIndex, length, out name); // [C]ookie2
case 'E': return TryMatch(Expires, key, startIndex, length, out name); // [E]xpires
case 'R': return TryMatch(Referer, key, startIndex, length, out name); // [R]eferer
case 'T': return TryMatch(Trailer, key, startIndex, length, out name); // [T]railer
case 'U': return TryMatch(Upgrade, key, startIndex, length, out name); // [U]pgrade
case 'W': return TryMatch(Warning, key, startIndex, length, out name); // [W]arning
}
break;
case 8:
switch (key[startIndex + 3])
{
case 'M': return TryMatch(IfMatch, key, startIndex, length, out name); // If-[M]atch
case 'R': return TryMatch(IfRange, key, startIndex, length, out name); // If-[R]ange
case 'a': return TryMatch(Location, key, startIndex, length, out name); // Loc[a]tion
}
break;
case 10:
switch (key[startIndex])
{
case 'C': return TryMatch(Connection, key, startIndex, length, out name); // [C]onnection
case 'K': return TryMatch(KeepAlive, key, startIndex, length, out name); // [K]eep-Alive
case 'S': return TryMatch(SetCookie, key, startIndex, length, out name); // [S]et-Cookie
case 'U': return TryMatch(UserAgent, key, startIndex, length, out name); // [U]ser-Agent
}
break;
case 11:
switch (key[startIndex])
{
case 'C': return TryMatch(ContentMD5, key, startIndex, length, out name); // [C]ontent-MD5
case 'R': return TryMatch(RetryAfter, key, startIndex, length, out name); // [R]etry-After
case 'S': return TryMatch(SetCookie2, key, startIndex, length, out name); // [S]et-Cookie2
}
break;
case 12:
switch (key[startIndex])
{
case 'C': return TryMatch(ContentType, key, startIndex, length, out name); // [C]ontent-Type
case 'M': return TryMatch(MaxForwards, key, startIndex, length, out name); // [M]ax-Forwards
case 'X': return TryMatch(XPoweredBy, key, startIndex, length, out name); // [X]-Powered-By
}
break;
case 13:
switch (key[startIndex + 6])
{
case '-': return TryMatch(AcceptRanges, key, startIndex, length, out name); // Accept[-]Ranges
case 'i': return TryMatch(Authorization, key, startIndex, length, out name); // Author[i]zation
case 'C': return TryMatch(CacheControl, key, startIndex, length, out name); // Cache-[C]ontrol
case 't': return TryMatch(ContentRange, key, startIndex, length, out name); // Conten[t]-Range
case 'e': return TryMatch(IfNoneMatch, key, startIndex, length, out name); // If-Non[e]-Match
case 'o': return TryMatch(LastModified, key, startIndex, length, out name); // Last-M[o]dified
}
break;
case 14:
switch (key[startIndex])
{
case 'A': return TryMatch(AcceptCharset, key, startIndex, length, out name); // [A]ccept-Charset
case 'C': return TryMatch(ContentLength, key, startIndex, length, out name); // [C]ontent-Length
}
break;
case 15:
switch (key[startIndex + 7])
{
case 'E': return TryMatch(AcceptEncoding, key, startIndex, length, out name); // Accept-[E]ncoding
case 'L': return TryMatch(AcceptLanguage, key, startIndex, length, out name); // Accept-[L]anguage
}
break;
case 16:
switch (key[startIndex + 11])
{
case 'o': return TryMatch(ContentEncoding, key, startIndex, length, out name); // Content-Enc[o]ding
case 'g': return TryMatch(ContentLanguage, key, startIndex, length, out name); // Content-Lan[g]uage
case 'a': return TryMatch(ContentLocation, key, startIndex, length, out name); // Content-Loc[a]tion
case 'c': return TryMatch(ProxyConnection, key, startIndex, length, out name); // Proxy-Conne[c]tion
case 'i': return TryMatch(WWWAuthenticate, key, startIndex, length, out name); // WWW-Authent[i]cate
case 'r': return TryMatch(XAspNetVersion, key, startIndex, length, out name); // X-AspNet-Ve[r]sion
}
break;
case 17:
switch (key[startIndex])
{
case 'I': return TryMatch(IfModifiedSince, key, startIndex, length, out name); // [I]f-Modified-Since
case 'S': return TryMatch(SecWebSocketKey, key, startIndex, length, out name); // [S]ec-WebSocket-Key
case 'T': return TryMatch(TransferEncoding, key, startIndex, length, out name); // [T]ransfer-Encoding
}
break;
case 18:
return TryMatch(ProxyAuthenticate, key, startIndex, length, out name); // Proxy-Authenticate
case 19:
switch (key[startIndex])
{
case 'C': return TryMatch(ContentDisposition, key, startIndex, length, out name); // [C]ontent-Disposition
case 'I': return TryMatch(IfUnmodifiedSince, key, startIndex, length, out name); // [I]f-Unmodified-Since
case 'P': return TryMatch(ProxyAuthorization, key, startIndex, length, out name); // [P]roxy-Authorization
}
break;
case 20:
return TryMatch(SecWebSocketAccept, key, startIndex, length, out name); // Sec-WebSocket-Accept
case 21:
return TryMatch(SecWebSocketVersion, key, startIndex, length, out name); // Sec-WebSocket-Version
case 22:
return TryMatch(SecWebSocketProtocol, key, startIndex, length, out name); // Sec-WebSocket-Protocol
case 24:
return TryMatch(SecWebSocketExtensions, key, startIndex, length, out name); // Sec-WebSocket-Extensions
}
name = null;
return false;
}
/// <summary>
/// Returns true if <paramref name="known"/> matches the <paramref name="key"/> char[] array segment,
/// using an ordinal comparison.
/// </summary>
private static bool TryMatch(string known, char[] key, int startIndex, int length, out string name)
{
Debug.Assert(known != null);
Debug.Assert(known.Length > 0);
CharArrayHelpers.DebugAssertArrayInputs(key, startIndex, length);
// The lengths should be equal because this method is only called
// from within a "switch (length) { ... }".
Debug.Assert(known.Length == length);
if (CharArrayHelpers.EqualsOrdinal(known, key, startIndex, length))
{
name = known;
return true;
}
name = null;
return false;
}
}
}
@@ -4,8 +4,10 @@
namespace System.Net
{
internal static class HttpKnownHeaderNames
internal static partial class HttpKnownHeaderNames
{
// When adding a new constant, add it to HttpKnownHeaderNames.TryGetHeaderName.cs as well.
public const string Accept = "Accept";
public const string AcceptCharset = "Accept-Charset";
public const string AcceptEncoding = "Accept-Encoding";
@@ -27,6 +27,9 @@
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\src\System\CharArrayHelpers.cs">
<Link>Common\System\CharArrayHelpers.cs</Link>
</Compile>
<Compile Include="..\src\System\StringExtensions.cs">
<Link>Common\System\StringExtensions.cs</Link>
</Compile>
@@ -42,9 +45,17 @@
<Compile Include="..\src\System\IO\StringParser.cs">
<Link>Common\System\IO\StringParser.cs</Link>
</Compile>
<Compile Include="..\src\System\Net\HttpKnownHeaderNames.cs">
<Link>Common\System\Net\HttpKnownHeaderNames.cs</Link>
</Compile>
<Compile Include="..\src\System\Net\HttpKnownHeaderNames.TryGetHeaderName.cs">
<Link>Common\System\Net\HttpKnownHeaderNames.TryGetHeaderName.cs</Link>
</Compile>
<Compile Include="Tests\System\IO\PathInternal_Unix_Tests.cs" />
<Compile Include="Tests\System\CharArrayHelpersTests.cs" />
<Compile Include="Tests\System\StringExtensions.Tests.cs" />
<Compile Include="Tests\System\IO\PathInternal.Tests.cs" />
<Compile Include="Tests\System\Net\HttpKnownHeaderNamesTests.cs" />
<Compile Include="$(CommonPath)\System\Runtime\InteropServices\SafeHeapHandle.cs">
<Link>Common\System\Runtime\InteropServices\SafeHeapHandle.cs</Link>
</Compile>
@@ -0,0 +1,92 @@
// 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;
using Xunit;
namespace Tests.System
{
public class CharArrayHelpersTests
{
[Theory]
[InlineData("Foo", "Foo", true)]
[InlineData("FOO", "FOO", true)]
[InlineData("fOO", "fOO", true)]
[InlineData("HTTP/", "HTTP/", true)]
[InlineData("http/", "http/", true)]
[InlineData("GZIP", "GZIP", true)]
[InlineData("gzip", "gzip", true)]
[InlineData("DEFLATE", "DEFLATE", true)]
[InlineData("deflate", "deflate", true)]
[InlineData("Content-Length", "Content-Length", true)]
[InlineData("content-length", "content-length", true)]
[InlineData("DEFLATE", "deflate", false)]
[InlineData("foo", "bar", false)]
[InlineData("GZIP", "DEFLATE", false)]
[InlineData("Content-Length", "content-length", false)]
public void EqualsOrdinal_ComparingVariousInputsBothWays_ReturnsExpected(string leftString, string rightString, bool expected)
{
char[] left = leftString.ToCharArray();
char[] right = rightString.ToCharArray();
Assert.Equal(expected, CharArrayHelpers.EqualsOrdinal(leftString, right, 0, right.Length));
Assert.Equal(expected, CharArrayHelpers.EqualsOrdinal(rightString, left, 0, left.Length));
}
[Theory]
[InlineData("Foo", "Foo", true)]
[InlineData("Foo", "FOO", true)]
[InlineData("Foo", "fOO", true)]
[InlineData("HTTP/", "http/", true)]
[InlineData("GZIP", "gzip", true)]
[InlineData("DEFLATE", "deflate", true)]
[InlineData("Content-Length", "content-length", true)]
[InlineData("foo", "bar", false)]
[InlineData("GZIP", "DEFLATE", false)]
public void EqualsOrdinalAsciiIgnoreCase_ComparingVariousInputsBothWays_ReturnsExpected(string leftString, string rightString, bool expected)
{
char[] left = leftString.ToCharArray();
char[] right = rightString.ToCharArray();
Assert.Equal(expected, CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase(leftString, right, 0, right.Length));
Assert.Equal(expected, CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase(rightString, left, 0, left.Length));
}
[Fact]
public void EqualsOrdinalAsciiIgnoreCase_ComparingLowerAndUpperCaseAsciiChars_ReturnsTrue()
{
for (char c = '\0'; c <= 127; c++)
{
string lowerString = c.ToString();
string upperString = char.ToUpperInvariant(c).ToString();
char[] lowerCharArray = new char[] { c };
char[] upperCharArray = new char[] { char.ToUpperInvariant(c) };
Assert.True(CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase(lowerString, lowerCharArray, 0, 1));
Assert.True(CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase(upperString, lowerCharArray, 0, 1));
Assert.True(CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase(lowerString, upperCharArray, 0, 1));
Assert.True(CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase(upperString, upperCharArray, 0, 1));
}
}
[Theory]
[InlineData(" Foo ", "Foo")]
[InlineData("Foo ", "Foo")]
[InlineData(" Foo", "Foo")]
[InlineData("\tBar\t", "Bar")]
[InlineData("Bar\t", "Bar")]
[InlineData("\tBar", "Bar")]
public void Trim_VariousInputs_ReturnsExpectedSubstring(string valueString, string expected)
{
char[] value = valueString.ToCharArray();
int startIndex = 0;
int length = value.Length;
CharArrayHelpers.Trim(value, ref startIndex, ref length);
Assert.Equal(expected, new string(value, startIndex, length));
}
}
}
@@ -0,0 +1,65 @@
// 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 System.Linq;
using System.Net;
using System.Reflection;
using Xunit;
namespace Tests.System.Net
{
public class HttpKnownHeaderNamesTests
{
[Theory]
[InlineData("")]
[InlineData("this should not be found")]
public void TryGetHeaderName_UnknownStrings_NotFound(string shouldNotBeFound)
{
char[] key = shouldNotBeFound.ToCharArray();
string name;
Assert.False(HttpKnownHeaderNames.TryGetHeaderName(key, 0, key.Length, out name));
Assert.Null(name);
}
[Theory]
[MemberData("HttpKnownHeaderNamesPublicStringConstants")]
public void TryGetHeaderName_AllHttpKnownHeaderNamesPublicStringConstants_Found(string constant)
{
char[] key = constant.ToCharArray();
string name1;
Assert.True(HttpKnownHeaderNames.TryGetHeaderName(key, 0, key.Length, out name1));
Assert.NotNull(name1);
Assert.Equal(constant, name1);
string name2;
Assert.True(HttpKnownHeaderNames.TryGetHeaderName(key, 0, key.Length, out name2));
Assert.NotNull(name2);
Assert.Equal(constant, name2);
Assert.Same(name1, name2);
}
public static IEnumerable<object[]> HttpKnownHeaderNamesPublicStringConstants
{
get
{
string[] constants = typeof(HttpKnownHeaderNames)
.GetTypeInfo()
.DeclaredFields
.Where(f => f.IsLiteral && f.IsStatic && f.IsPublic && f.FieldType == typeof(string))
.Select(f => (string)f.GetValue(null))
.ToArray();
Assert.NotEmpty(constants);
Assert.DoesNotContain(constants, c => string.IsNullOrEmpty(c));
return constants.Select(c => new object[] { c });
}
}
}
}
+1
View File
@@ -9,6 +9,7 @@
"System.IO.FileSystem": "4.0.0",
"System.IO.FileSystem.Primitives": "4.0.0",
"System.Linq": "4.0.0",
"System.Reflection": "4.0.10",
"System.Runtime": "4.0.20",
"System.Runtime.Extensions": "4.0.10",
"System.Runtime.Handles": "4.0.0",
@@ -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);
}
}
}
@@ -105,7 +105,6 @@
<Compile Include="System\Net\Http\Headers\WarningHeaderValue.cs" />
<!-- TODO #5715: Must be moved to the Common/System/Net folder -->
<Compile Include="Internal\ICloneable.cs" />
<Compile Include="Internal\HttpStatusDescription.cs" />
<Compile Include="Internal\MailAddress.cs" />
<Compile Include="Internal\Mail\DomainLiteralReader.cs" />
<Compile Include="Internal\Mail\DotAtomReader.cs" />
@@ -114,9 +113,6 @@
<Compile Include="Internal\Mail\QuotedPairReader.cs" />
<Compile Include="Internal\Mail\QuotedStringFormatReader.cs" />
<Compile Include="Internal\Mail\WhitespaceReader.cs" />
<Compile Include="$(CommonPath)\System\Net\HttpKnownHeaderNames.cs">
<Link>Common\System\Net\HttpKnownHeaderNames.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
<Link>Common\System\Net\Logging\LoggingHash.cs</Link>
</Compile>
@@ -218,6 +214,12 @@
<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\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>
@@ -308,6 +310,12 @@
<Compile Include="$(CommonPath)\System\Net\Http\HttpHandlerLoggingStrings.cs">
<Link>Common\System\Net\Http\HttpHandlerLoggingStrings.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\HttpKnownHeaderNames.cs">
<Link>Common\System\Net\HttpKnownHeaderNames.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>
@@ -32,12 +32,27 @@
<Compile Include="$(CommonPath)\System\StringExtensions.cs">
<Link>ProductionCode\Common\System\StringExtensions.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\HttpKnownHeaderNames.cs">
<Link>ProductionCode\Common\System\Net\HttpKnownHeaderNames.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\HttpStatusDescription.cs">
<Link>ProductionCode\Common\System\Net\HttpStatusDescription.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\HttpVersion.cs">
<Link>ProductionCode\Common\System\Net\HttpVersion.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
<Link>ProductionCode\Common\System\Net\Logging\LoggingHash.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\Logging\HttpEventSource.cs">
<Link>ProductionCode\Common\System\Net\Logging\HttpEventSource.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.cs">
<Link>ProductionCode\Common\System\Net\Logging\NetEventSource.cs</Link>
</Compile>
<Compile Include="$(CommonTestPath)\System\ShouldNotBeInvokedException.cs">
<Link>Common\System\ShouldNotBeInvokedException.cs</Link>
</Compile>
<Compile Include="..\..\src\Internal\HttpStatusDescription.cs">
<Link>ProductionCode\Internal\HttpStatusDescription.cs</Link>
</Compile>
<Compile Include="..\..\src\Internal\ICloneable.cs">
<Link>ProductionCode\Internal\ICloneable.cs</Link>
</Compile>
@@ -323,22 +338,6 @@
<Compile Include="HttpContentTest.cs" />
<Compile Include="HttpRuleParserTest.cs" />
<Compile Include="MockContent.cs" />
<Compile Include="$(CommonPath)\System\Net\HttpKnownHeaderNames.cs">
<Link>ProductionCode\HttpKnownHeaderNames.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\HttpVersion.cs">
<Link>Common\System\Net\HttpVersion.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
<Link>Common\System\Net\Logging\LoggingHash.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\Logging\HttpEventSource.cs">
<Link>Common\System\Net\Logging\HttpEventSource.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.cs">
<Link>Common\System\Net\Logging\NetEventSource.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="project.json" />
@@ -596,7 +596,7 @@ namespace System.Net.WebSockets
return;
}
_subProtocol = GetResponseHeaderStringInfo(HeaderNameWebSocketProtocol);
_subProtocol = GetResponseHeader(HeaderNameWebSocketProtocol);
}
private void AddRequestHeaders(Uri uri, ClientWebSocketOptions options)
@@ -669,49 +669,74 @@ namespace System.Net.WebSockets
return (HttpStatusCode)result;
}
private string GetResponseHeaderStringInfo(string headerName)
private unsafe string GetResponseHeader(string headerName, char[] buffer = null)
{
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(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_QUERY_CUSTOM,
headerName,
null,
ref bytesNeeded,
IntPtr.Zero))
Debug.Assert(buffer == null || (buffer != null && buffer.Length > StackLimit));
int bufferLength;
if (buffer == null)
{
int lastError = Marshal.GetLastWin32Error();
if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
bufferLength = StackLimit;
char* pBuffer = stackalloc char[bufferLength];
if (QueryHeaders(headerName, pBuffer, ref bufferLength))
{
return null;
return new string(pBuffer, 0, bufferLength);
}
if (lastError != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER)
}
else
{
bufferLength = buffer.Length;
fixed (char* pBuffer = buffer)
{
throw WinHttpException.CreateExceptionUsingError(lastError);
if (QueryHeaders(headerName, pBuffer, ref bufferLength))
{
return new string(pBuffer, 0, bufferLength);
}
}
}
int charsNeeded = (int)bytesNeeded / sizeof(char);
var buffer = new StringBuilder(charsNeeded, charsNeeded);
int lastError = Marshal.GetLastWin32Error();
results = Interop.WinHttp.WinHttpQueryHeaders(
if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
{
return null;
}
if (lastError == Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER)
{
buffer = new char[bufferLength];
return GetResponseHeader(headerName, buffer);
}
throw WinHttpException.CreateExceptionUsingError(lastError);
}
private unsafe bool QueryHeaders(string headerName, char* buffer, ref int bufferLength)
{
Debug.Assert(bufferLength >= 0, "bufferLength must not be negative.");
uint index = 0;
// 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(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_QUERY_CUSTOM,
headerName,
buffer,
ref bytesNeeded,
IntPtr.Zero);
if (!results)
{
WinHttpException.ThrowExceptionUsingLastError();
}
new IntPtr(buffer),
ref bufferLengthInBytes,
ref index);
return buffer.ToString();
// Convert the byte buffer length back to the length in chars.
bufferLength = (int)bufferLengthInBytes / sizeof(char);
return result;
}
public override void Dispose()