diff --git a/eng/Dependencies.props b/eng/Dependencies.props
index 24a51f35c23d..c7eb8b903136 100644
--- a/eng/Dependencies.props
+++ b/eng/Dependencies.props
@@ -200,6 +200,7 @@ and are generated based on the last package release.
+
diff --git a/eng/Versions.props b/eng/Versions.props
index fa088883126d..dcc63e67ff9e 100644
--- a/eng/Versions.props
+++ b/eng/Versions.props
@@ -302,6 +302,7 @@
2.13.4
2.13.4
2.13.4
+ 0.3.46-beta
$(MessagePackVersion)
4.10.0
0.11.2
diff --git a/src/Servers/HttpSys/HttpSysServer.slnf b/src/Servers/HttpSys/HttpSysServer.slnf
index f8072017e440..492b2dfc1077 100644
--- a/src/Servers/HttpSys/HttpSysServer.slnf
+++ b/src/Servers/HttpSys/HttpSysServer.slnf
@@ -2,6 +2,7 @@
"solution": {
"path": "..\\..\\..\\AspNetCore.sln",
"projects": [
+ "src\\Antiforgery\\src\\Microsoft.AspNetCore.Antiforgery.csproj",
"src\\DataProtection\\Abstractions\\src\\Microsoft.AspNetCore.DataProtection.Abstractions.csproj",
"src\\DataProtection\\Cryptography.Internal\\src\\Microsoft.AspNetCore.Cryptography.Internal.csproj",
"src\\DataProtection\\DataProtection\\src\\Microsoft.AspNetCore.DataProtection.csproj",
diff --git a/src/Servers/HttpSys/perf/Microbenchmarks/RequestHeaderBenchmarks.cs b/src/Servers/HttpSys/perf/Microbenchmarks/RequestHeaderBenchmarks.cs
index 50b62ec61f2d..848354b30bc3 100644
--- a/src/Servers/HttpSys/perf/Microbenchmarks/RequestHeaderBenchmarks.cs
+++ b/src/Servers/HttpSys/perf/Microbenchmarks/RequestHeaderBenchmarks.cs
@@ -6,6 +6,8 @@
using System.Text;
using BenchmarkDotNet.Attributes;
using Microsoft.AspNetCore.HttpSys.Internal;
+using Windows.Win32.Foundation;
+using Windows.Win32.Networking.HttpServer;
using RequestHeaders = Microsoft.AspNetCore.HttpSys.Internal.RequestHeaders;
[SimpleJob, MemoryDiagnoser]
@@ -54,7 +56,7 @@ private unsafe RequestHeaders CreateRequestHeader(int unknowHeaderCount)
var nativeContext = new NativeRequestContext(MemoryPool.Shared, null, 0, false);
var nativeMemory = new Span(nativeContext.NativeRequest, (int)nativeContext.Size + 8);
- var requestStructure = new HttpApiTypes.HTTP_REQUEST();
+ var requestStructure = new HTTP_REQUEST_V1();
var remainingMemory = SetUnknownHeaders(nativeMemory, ref requestStructure, GenerateUnknownHeaders(unknowHeaderCount));
SetHostHeader(remainingMemory, ref requestStructure);
MemoryMarshal.Write(nativeMemory, in requestStructure);
@@ -64,15 +66,15 @@ private unsafe RequestHeaders CreateRequestHeader(int unknowHeaderCount)
return requestHeaders;
}
- private unsafe Span SetHostHeader(Span nativeMemory, ref HttpApiTypes.HTTP_REQUEST requestStructure)
+ private unsafe Span SetHostHeader(Span nativeMemory, ref HTTP_REQUEST_V1 requestStructure)
{
// Writing localhost to Host header
- var dataDestination = nativeMemory.Slice(Marshal.SizeOf());
- int length = Encoding.ASCII.GetBytes("localhost:5001", dataDestination);
+ var dataDestination = nativeMemory[Marshal.SizeOf()..];
+ var length = Encoding.ASCII.GetBytes("localhost:5001", dataDestination);
fixed (byte* address = &MemoryMarshal.GetReference(dataDestination))
{
- requestStructure.Headers.KnownHeaders_29.pRawValue = address;
- requestStructure.Headers.KnownHeaders_29.RawValueLength = (ushort)length;
+ requestStructure.Headers.KnownHeaders._28.pRawValue = (PCSTR)address;
+ requestStructure.Headers.KnownHeaders._28.RawValueLength = (ushort)length;
}
return dataDestination;
}
@@ -80,48 +82,48 @@ private unsafe Span SetHostHeader(Span nativeMemory, ref HttpApiType
///
/// Writes an array HTTP_UNKNOWN_HEADER and an array of header key-value pairs to nativeMemory. Pointers in the HTTP_UNKNOWN_HEADER structure points to the corresponding key-value pair.
///
- private unsafe Span SetUnknownHeaders(Span nativeMemory, ref HttpApiTypes.HTTP_REQUEST requestStructure, IReadOnlyCollection<(string Key, string Value)> headerNames)
+ private unsafe Span SetUnknownHeaders(Span nativeMemory, ref HTTP_REQUEST_V1 requestStructure, IReadOnlyCollection<(string Key, string Value)> headerNames)
{
- var unknownHeaderStructureDestination = nativeMemory.Slice(Marshal.SizeOf());
+ var unknownHeaderStructureDestination = nativeMemory[Marshal.SizeOf()..];
fixed (byte* address = &MemoryMarshal.GetReference(unknownHeaderStructureDestination))
{
- requestStructure.Headers.pUnknownHeaders = (HttpApiTypes.HTTP_UNKNOWN_HEADER*)address;
+ requestStructure.Headers.pUnknownHeaders = (HTTP_UNKNOWN_HEADER*)address;
}
requestStructure.Headers.UnknownHeaderCount += (ushort)headerNames.Count;
- var unknownHeadersSize = Marshal.SizeOf();
- var dataDestination = unknownHeaderStructureDestination.Slice(unknownHeadersSize * headerNames.Count);
- foreach (var headerName in headerNames)
+ var unknownHeadersSize = Marshal.SizeOf();
+ var dataDestination = unknownHeaderStructureDestination[(unknownHeadersSize * headerNames.Count)..];
+ foreach (var (headerKey, headerValue) in headerNames)
{
- var unknownHeaderStructure = new HttpApiTypes.HTTP_UNKNOWN_HEADER();
- int nameLength = Encoding.ASCII.GetBytes(headerName.Key, dataDestination);
+ var unknownHeaderStructure = new HTTP_UNKNOWN_HEADER();
+ var nameLength = Encoding.ASCII.GetBytes(headerKey, dataDestination);
fixed (byte* address = &MemoryMarshal.GetReference(dataDestination))
{
- unknownHeaderStructure.pName = address;
+ unknownHeaderStructure.pName = (PCSTR)address;
unknownHeaderStructure.NameLength = (ushort)nameLength;
}
- dataDestination = dataDestination.Slice(nameLength);
+ dataDestination = dataDestination[nameLength..];
- if (!string.IsNullOrEmpty(headerName.Value))
+ if (!string.IsNullOrEmpty(headerValue))
{
- int valueLength = Encoding.ASCII.GetBytes(headerName.Value, dataDestination);
+ var valueLength = Encoding.ASCII.GetBytes(headerValue, dataDestination);
fixed (byte* address = &MemoryMarshal.GetReference(dataDestination))
{
- unknownHeaderStructure.pRawValue = address;
+ unknownHeaderStructure.pRawValue = (PCSTR)address;
unknownHeaderStructure.RawValueLength = (ushort)valueLength;
}
- dataDestination = dataDestination.Slice(nameLength);
+ dataDestination = dataDestination[nameLength..];
}
MemoryMarshal.Write(unknownHeaderStructureDestination, in unknownHeaderStructure);
- unknownHeaderStructureDestination = unknownHeaderStructureDestination.Slice(unknownHeadersSize);
+ unknownHeaderStructureDestination = unknownHeaderStructureDestination[unknownHeadersSize..];
}
return dataDestination;
}
- private IReadOnlyCollection<(string, string)> GenerateUnknownHeaders(int count)
+ private static List<(string, string)> GenerateUnknownHeaders(int count)
{
var result = new List<(string, string)>();
- for (int i = 0; i < count; i++)
+ for (var i = 0; i < count; i++)
{
result.Add(($"X-Custom-{i}", $"Value-{i}"));
}
diff --git a/src/Servers/HttpSys/samples/TestClient/Program.cs b/src/Servers/HttpSys/samples/TestClient/Program.cs
index 16155fd98b4d..82f4bf1af6c1 100644
--- a/src/Servers/HttpSys/samples/TestClient/Program.cs
+++ b/src/Servers/HttpSys/samples/TestClient/Program.cs
@@ -1,94 +1,89 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using System;
-using System.Net;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-namespace TestClient
+namespace TestClient;
+
+public class Program
{
- public class Program
+ private const string Address =
+ "http://localhost:5000/public/1kb.txt";
+ // "https://localhost:9090/public/1kb.txt";
+
+ public static void Main(string[] args)
{
- private const string Address =
- "http://localhost:5000/public/1kb.txt";
- // "https://localhost:9090/public/1kb.txt";
+ Console.WriteLine("Ready");
+ Console.ReadKey();
- public static void Main(string[] args)
- {
- Console.WriteLine("Ready");
- Console.ReadKey();
+ var handler = new HttpClientHandler();
+ handler.MaxConnectionsPerServer = 500;
+ handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
+ // handler.UseDefaultCredentials = true;
+ HttpClient client = new HttpClient(handler);
- var handler = new HttpClientHandler();
- handler.MaxConnectionsPerServer = 500;
- handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
- // handler.UseDefaultCredentials = true;
- HttpClient client = new HttpClient(handler);
+ RunParallelRequests(client);
- RunParallelRequests(client);
+ // RunManualRequests(client);
- // RunManualRequests(client);
+ // RunWebSocketClient().Wait();
- // RunWebSocketClient().Wait();
+ Console.WriteLine("Done");
+ // Console.ReadKey();
+ }
- Console.WriteLine("Done");
- // Console.ReadKey();
+ private static void RunManualRequests(HttpClient client)
+ {
+ while (true)
+ {
+ Console.WriteLine("Press any key to send request");
+ Console.ReadKey();
+ var result = client.GetAsync(Address).Result;
+ Console.WriteLine(result);
}
+ }
- private static void RunManualRequests(HttpClient client)
+ private static void RunParallelRequests(HttpClient client)
+ {
+ int completionCount = 0;
+ int iterations = 100000;
+ for (int i = 0; i < iterations; i++)
{
- while (true)
- {
- Console.WriteLine("Press any key to send request");
- Console.ReadKey();
- var result = client.GetAsync(Address).Result;
- Console.WriteLine(result);
- }
+ client.GetAsync(Address)
+ .ContinueWith(t => Interlocked.Increment(ref completionCount));
}
- private static void RunParallelRequests(HttpClient client)
+ while (completionCount < iterations)
{
- int completionCount = 0;
- int iterations = 100000;
- for (int i = 0; i < iterations; i++)
- {
- client.GetAsync(Address)
- .ContinueWith(t => Interlocked.Increment(ref completionCount));
- }
-
- while (completionCount < iterations)
- {
- Thread.Sleep(10);
- }
+ Thread.Sleep(10);
}
+ }
+
+ public static async Task RunWebSocketClient()
+ {
+ ClientWebSocket websocket = new ClientWebSocket();
+
+ string url = "ws://localhost:5000/";
+ Console.WriteLine("Connecting to: " + url);
+ await websocket.ConnectAsync(new Uri(url), CancellationToken.None);
- public static async Task RunWebSocketClient()
+ string message = "Hello World";
+ Console.WriteLine("Sending message: " + message);
+ byte[] messageBytes = Encoding.UTF8.GetBytes(message);
+ await websocket.SendAsync(new ArraySegment(messageBytes), WebSocketMessageType.Text, true, CancellationToken.None);
+
+ byte[] incomingData = new byte[1024];
+ WebSocketReceiveResult result = await websocket.ReceiveAsync(new ArraySegment(incomingData), CancellationToken.None);
+
+ if (result.CloseStatus.HasValue)
+ {
+ Console.WriteLine("Closed; Status: " + result.CloseStatus + ", " + result.CloseStatusDescription);
+ }
+ else
{
- ClientWebSocket websocket = new ClientWebSocket();
-
- string url = "ws://localhost:5000/";
- Console.WriteLine("Connecting to: " + url);
- await websocket.ConnectAsync(new Uri(url), CancellationToken.None);
-
- string message = "Hello World";
- Console.WriteLine("Sending message: " + message);
- byte[] messageBytes = Encoding.UTF8.GetBytes(message);
- await websocket.SendAsync(new ArraySegment(messageBytes), WebSocketMessageType.Text, true, CancellationToken.None);
-
- byte[] incomingData = new byte[1024];
- WebSocketReceiveResult result = await websocket.ReceiveAsync(new ArraySegment(incomingData), CancellationToken.None);
-
- if (result.CloseStatus.HasValue)
- {
- Console.WriteLine("Closed; Status: " + result.CloseStatus + ", " + result.CloseStatusDescription);
- }
- else
- {
- Console.WriteLine("Received message: " + Encoding.UTF8.GetString(incomingData, 0, result.Count));
- }
+ Console.WriteLine("Received message: " + Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
diff --git a/src/Servers/HttpSys/src/AsyncAcceptContext.cs b/src/Servers/HttpSys/src/AsyncAcceptContext.cs
index 72131695aed6..945428ab1da8 100644
--- a/src/Servers/HttpSys/src/AsyncAcceptContext.cs
+++ b/src/Servers/HttpSys/src/AsyncAcceptContext.cs
@@ -3,7 +3,6 @@
using System.Diagnostics;
using System.Threading.Tasks.Sources;
-using Microsoft.AspNetCore.HttpSys.Internal;
namespace Microsoft.AspNetCore.Server.HttpSys;
@@ -39,9 +38,9 @@ internal ValueTask AcceptAsync()
AllocateNativeRequest();
- uint statusCode = QueueBeginGetContext();
- if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS &&
- statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING)
+ var statusCode = QueueBeginGetContext();
+ if (statusCode != ErrorCodes.ERROR_SUCCESS &&
+ statusCode != ErrorCodes.ERROR_IO_PENDING)
{
// some other bad error, possible(?) return values are:
// ERROR_INVALID_HANDLE, ERROR_INSUFFICIENT_BUFFER, ERROR_OPERATION_ABORTED
@@ -55,8 +54,8 @@ private void IOCompleted(uint errorCode, uint numBytes)
{
try
{
- if (errorCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS &&
- errorCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_MORE_DATA)
+ if (errorCode != ErrorCodes.ERROR_SUCCESS &&
+ errorCode != ErrorCodes.ERROR_MORE_DATA)
{
_mrvts.SetException(new HttpSysException((int)errorCode));
return;
@@ -64,7 +63,7 @@ private void IOCompleted(uint errorCode, uint numBytes)
Debug.Assert(_requestContext != null);
- if (errorCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS)
+ if (errorCode == ErrorCodes.ERROR_SUCCESS)
{
var requestContext = _requestContext;
// It's important that we clear the request context before we set the result
@@ -79,10 +78,10 @@ private void IOCompleted(uint errorCode, uint numBytes)
AllocateNativeRequest(numBytes, _requestContext.RequestId);
// We need to issue a new request, either because auth failed, or because our buffer was too small the first time.
- uint statusCode = QueueBeginGetContext();
+ var statusCode = QueueBeginGetContext();
- if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS &&
- statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING)
+ if (statusCode != ErrorCodes.ERROR_SUCCESS &&
+ statusCode != ErrorCodes.ERROR_IO_PENDING)
{
// someother bad error, possible(?) return values are:
// ERROR_INVALID_HANDLE, ERROR_INSUFFICIENT_BUFFER, ERROR_OPERATION_ABORTED
@@ -117,14 +116,14 @@ private uint QueueBeginGetContext()
_requestContext.RequestId,
// Small perf impact by not using HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY
// if the request sends header+body in a single TCP packet
- (uint)HttpApiTypes.HTTP_FLAGS.NONE,
+ 0u,
_requestContext.NativeRequest,
_requestContext.Size,
&bytesTransferred,
_overlapped);
- if ((statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_CONNECTION_INVALID
- || statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_INVALID_PARAMETER)
+ if ((statusCode == ErrorCodes.ERROR_CONNECTION_INVALID
+ || statusCode == ErrorCodes.ERROR_INVALID_PARAMETER)
&& _requestContext.RequestId != 0)
{
// ERROR_CONNECTION_INVALID:
@@ -139,7 +138,7 @@ private uint QueueBeginGetContext()
_requestContext.RequestId = 0;
retry = true;
}
- else if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_MORE_DATA)
+ else if (statusCode == ErrorCodes.ERROR_MORE_DATA)
{
// the buffer was not big enough to fit the headers, we need
// to read the RequestId returned, allocate a new buffer of the required size
@@ -147,7 +146,7 @@ private uint QueueBeginGetContext()
AllocateNativeRequest(bytesTransferred);
retry = true;
}
- else if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS
+ else if (statusCode == ErrorCodes.ERROR_SUCCESS
&& HttpSysListener.SkipIOCPCallbackOnSuccess)
{
// IO operation completed synchronously - callback won't be called to signal completion.
diff --git a/src/Servers/HttpSys/src/AuthenticationManager.cs b/src/Servers/HttpSys/src/AuthenticationManager.cs
index dc4f88b7d93e..7bf734d6ffa8 100644
--- a/src/Servers/HttpSys/src/AuthenticationManager.cs
+++ b/src/Servers/HttpSys/src/AuthenticationManager.cs
@@ -4,9 +4,9 @@
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
-using Microsoft.AspNetCore.HttpSys.Internal;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
+using Windows.Win32.Networking.HttpServer;
namespace Microsoft.AspNetCore.Server.HttpSys;
@@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys;
public sealed class AuthenticationManager
{
private static readonly int AuthInfoSize =
- Marshal.SizeOf();
+ Marshal.SizeOf();
private UrlGroup? _urlGroup;
private AuthenticationSchemes _authSchemes;
@@ -78,14 +78,12 @@ private unsafe void SetUrlGroupSecurity()
return;
}
- HttpApiTypes.HTTP_SERVER_AUTHENTICATION_INFO authInfo =
- new HttpApiTypes.HTTP_SERVER_AUTHENTICATION_INFO();
+ var authInfo = new HTTP_SERVER_AUTHENTICATION_INFO();
+ authInfo.Flags = HttpApi.HTTP_PROPERTY_FLAGS_PRESENT;
- authInfo.Flags = HttpApiTypes.HTTP_FLAGS.HTTP_PROPERTY_FLAG_PRESENT;
- var authSchemes = (HttpApiTypes.HTTP_AUTH_TYPES)_authSchemes;
- if (authSchemes != HttpApiTypes.HTTP_AUTH_TYPES.NONE)
+ if (_authSchemes != AuthenticationSchemes.None)
{
- authInfo.AuthSchemes = authSchemes;
+ authInfo.AuthSchemes = (uint)_authSchemes;
// TODO:
// NTLM auth sharing (on by default?) DisableNTLMCredentialCaching
@@ -97,7 +95,7 @@ private unsafe void SetUrlGroupSecurity()
IntPtr infoptr = new IntPtr(&authInfo);
_urlGroup.SetProperty(
- HttpApiTypes.HTTP_SERVER_PROPERTY.HttpServerAuthenticationProperty,
+ HTTP_SERVER_PROPERTY.HttpServerAuthenticationProperty,
infoptr, (uint)AuthInfoSize);
}
}
diff --git a/src/Servers/HttpSys/src/HttpSysListener.cs b/src/Servers/HttpSys/src/HttpSysListener.cs
index 2b7924491d32..81d333e027ff 100644
--- a/src/Servers/HttpSys/src/HttpSysListener.cs
+++ b/src/Servers/HttpSys/src/HttpSysListener.cs
@@ -6,6 +6,9 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpSys.Internal;
using Microsoft.Extensions.Logging;
+using Windows.Win32;
+using Windows.Win32.Foundation;
+using Windows.Win32.Networking.HttpServer;
namespace Microsoft.AspNetCore.Server.HttpSys;
@@ -50,8 +53,6 @@ public HttpSysListener(HttpSysOptions options, ILoggerFactory loggerFactory)
throw new PlatformNotSupportedException();
}
- Debug.Assert(HttpApi.ApiVersion == HttpApiTypes.HTTP_API_VERSION.Version20, "Invalid Http api version");
-
Options = options;
Logger = loggerFactory.CreateLogger();
@@ -304,10 +305,12 @@ internal bool ValidateRequest(NativeRequestContext requestMemory)
internal unsafe void SendError(ulong requestId, int httpStatusCode, IList? authChallenges = null)
{
- HttpApiTypes.HTTP_RESPONSE_V2 httpResponse = new HttpApiTypes.HTTP_RESPONSE_V2();
- httpResponse.Response_V1.Version = new HttpApiTypes.HTTP_VERSION();
- httpResponse.Response_V1.Version.MajorVersion = (ushort)1;
- httpResponse.Response_V1.Version.MinorVersion = (ushort)1;
+ var httpResponse = new HTTP_RESPONSE_V2();
+ httpResponse.Base.Version = new()
+ {
+ MajorVersion = 1,
+ MinorVersion = 1
+ };
using UnmanagedBufferAllocator allocator = new();
@@ -317,29 +320,29 @@ internal unsafe void SendError(ulong requestId, int httpStatusCode, IList 0)
{
- HttpApiTypes.HTTP_RESPONSE_INFO* knownHeaderInfo = allocator.AllocAsPointer(1);
+ var knownHeaderInfo = allocator.AllocAsPointer(1);
httpResponse.pResponseInfo = knownHeaderInfo;
- knownHeaderInfo[httpResponse.ResponseInfoCount].Type = HttpApiTypes.HTTP_RESPONSE_INFO_TYPE.HttpResponseInfoTypeMultipleKnownHeaders;
+ knownHeaderInfo[httpResponse.ResponseInfoCount].Type = HTTP_RESPONSE_INFO_TYPE.HttpResponseInfoTypeMultipleKnownHeaders;
knownHeaderInfo[httpResponse.ResponseInfoCount].Length =
- (uint)sizeof(HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS);
+ (uint)sizeof(HTTP_MULTIPLE_KNOWN_HEADERS);
- HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS* header = allocator.AllocAsPointer(1);
+ var header = allocator.AllocAsPointer(1);
- header->HeaderId = HttpApiTypes.HTTP_RESPONSE_HEADER_ID.Enum.HttpHeaderWwwAuthenticate;
- header->Flags = HttpApiTypes.HTTP_RESPONSE_INFO_FLAGS.PreserveOrder; // The docs say this is for www-auth only.
+ header->HeaderId = HTTP_HEADER_ID.HttpHeaderWwwAuthenticate;
+ header->Flags = PInvoke.HTTP_RESPONSE_INFO_FLAGS_PRESERVE_ORDER; // The docs say this is for www-auth only.
header->KnownHeaderCount = 0;
- HttpApiTypes.HTTP_KNOWN_HEADER* nativeHeaderValues = allocator.AllocAsPointer(authChallenges.Count);
+ var nativeHeaderValues = allocator.AllocAsPointer(authChallenges.Count);
header->KnownHeaders = nativeHeaderValues;
- for (int headerValueIndex = 0; headerValueIndex < authChallenges.Count; headerValueIndex++)
+ for (var headerValueIndex = 0; headerValueIndex < authChallenges.Count; headerValueIndex++)
{
// Add Value
- string headerValue = authChallenges[headerValueIndex];
+ var headerValue = authChallenges[headerValueIndex];
bytes = allocator.GetHeaderEncodedBytes(headerValue, out bytesLength);
nativeHeaderValues[header->KnownHeaderCount].RawValueLength = checked((ushort)bytesLength);
- nativeHeaderValues[header->KnownHeaderCount].pRawValue = bytes;
+ nativeHeaderValues[header->KnownHeaderCount].pRawValue = (PCSTR)bytes;
header->KnownHeaderCount++;
}
@@ -348,40 +351,38 @@ internal unsafe void SendError(ulong requestId, int httpStatusCode, IList(contentLengthLength + 1);
+ var pContentLength = allocator.AllocAsPointer(contentLengthLength + 1);
pContentLength[0] = (byte)'0';
pContentLength[1] = 0; // null terminator
- (&httpResponse.Response_V1.Headers.KnownHeaders)[(int)HttpSysResponseHeader.ContentLength].pRawValue = pContentLength;
- (&httpResponse.Response_V1.Headers.KnownHeaders)[(int)HttpSysResponseHeader.ContentLength].RawValueLength = contentLengthLength;
- httpResponse.Response_V1.Headers.UnknownHeaderCount = 0;
-
- statusCode =
- HttpApi.HttpSendHttpResponse(
- _requestQueue.Handle,
- requestId,
- 0,
- &httpResponse,
- null,
- &dataWritten,
- IntPtr.Zero,
- 0,
- SafeNativeOverlapped.Zero,
- IntPtr.Zero);
- if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS)
+ var knownHeaders = httpResponse.Base.Headers.KnownHeaders.AsSpan();
+ knownHeaders[(int)HttpSysResponseHeader.ContentLength].pRawValue = (PCSTR)pContentLength;
+ knownHeaders[(int)HttpSysResponseHeader.ContentLength].RawValueLength = contentLengthLength;
+ httpResponse.Base.Headers.UnknownHeaderCount = 0;
+
+ statusCode = PInvoke.HttpSendHttpResponse(
+ _requestQueue.Handle,
+ requestId,
+ 0,
+ httpResponse,
+ null,
+ &dataWritten,
+ null,
+ null);
+ if (statusCode != ErrorCodes.ERROR_SUCCESS)
{
// if we fail to send a 401 something's seriously wrong, abort the request
- HttpApi.HttpCancelHttpRequest(_requestQueue.Handle, requestId, IntPtr.Zero);
+ PInvoke.HttpCancelHttpRequest(_requestQueue.Handle, requestId, default);
}
}
diff --git a/src/Servers/HttpSys/src/Microsoft.AspNetCore.Server.HttpSys.csproj b/src/Servers/HttpSys/src/Microsoft.AspNetCore.Server.HttpSys.csproj
index 60b4e3c5a3e4..d210084f3f66 100644
--- a/src/Servers/HttpSys/src/Microsoft.AspNetCore.Server.HttpSys.csproj
+++ b/src/Servers/HttpSys/src/Microsoft.AspNetCore.Server.HttpSys.csproj
@@ -9,7 +9,6 @@
aspnetcore;weblistener;httpsys
false
true
-
$(NoWarn);CA1416
@@ -23,7 +22,7 @@
-
+
@@ -31,11 +30,19 @@
+
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers
+
diff --git a/src/Servers/HttpSys/src/NativeInterop/DisconnectListener.cs b/src/Servers/HttpSys/src/NativeInterop/DisconnectListener.cs
index 26f95d13674d..f4dc688f3478 100644
--- a/src/Servers/HttpSys/src/NativeInterop/DisconnectListener.cs
+++ b/src/Servers/HttpSys/src/NativeInterop/DisconnectListener.cs
@@ -3,7 +3,6 @@
using System.Collections.Concurrent;
using System.ComponentModel;
-using Microsoft.AspNetCore.HttpSys.Internal;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Server.HttpSys;
@@ -95,8 +94,8 @@ private unsafe CancellationToken CreateDisconnectToken(ulong connectionId)
Log.CreateDisconnectTokenError(_logger, exception);
}
- if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING &&
- statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS)
+ if (statusCode != ErrorCodes.ERROR_IO_PENDING &&
+ statusCode != ErrorCodes.ERROR_SUCCESS)
{
// We got an unknown result, assume the connection has been closed.
boundHandle.FreeNativeOverlapped(nativeOverlapped);
@@ -105,7 +104,7 @@ private unsafe CancellationToken CreateDisconnectToken(ulong connectionId)
cts.Cancel();
}
- if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && HttpSysListener.SkipIOCPCallbackOnSuccess)
+ if (statusCode == ErrorCodes.ERROR_SUCCESS && HttpSysListener.SkipIOCPCallbackOnSuccess)
{
// IO operation completed synchronously - callback won't be called to signal completion
boundHandle.FreeNativeOverlapped(nativeOverlapped);
diff --git a/src/Servers/HttpSys/src/NativeInterop/ErrorCodes.cs b/src/Servers/HttpSys/src/NativeInterop/ErrorCodes.cs
new file mode 100644
index 000000000000..d66397390430
--- /dev/null
+++ b/src/Servers/HttpSys/src/NativeInterop/ErrorCodes.cs
@@ -0,0 +1,23 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+namespace Microsoft.AspNetCore.Server.HttpSys;
+
+// Only the useful subset of WIN32_ERROR
+internal static class ErrorCodes
+{
+ internal const uint ERROR_SUCCESS = 0;
+ internal const uint ERROR_FILE_NOT_FOUND = 2;
+ internal const uint ERROR_ACCESS_DENIED = 5;
+ internal const uint ERROR_SHARING_VIOLATION = 32;
+ internal const uint ERROR_HANDLE_EOF = 38;
+ internal const uint ERROR_NOT_SUPPORTED = 50;
+ internal const uint ERROR_INVALID_PARAMETER = 87;
+ internal const uint ERROR_INVALID_NAME = 123;
+ internal const uint ERROR_ALREADY_EXISTS = 183;
+ internal const uint ERROR_MORE_DATA = 234;
+ internal const uint ERROR_OPERATION_ABORTED = 995;
+ internal const uint ERROR_IO_PENDING = 997;
+ internal const uint ERROR_NOT_FOUND = 1168;
+ internal const uint ERROR_CONNECTION_INVALID = 1229;
+}
diff --git a/src/Servers/HttpSys/src/NativeInterop/HttpApi.cs b/src/Servers/HttpSys/src/NativeInterop/HttpApi.cs
index 575ebc259d25..1fec2ffea7e6 100644
--- a/src/Servers/HttpSys/src/NativeInterop/HttpApi.cs
+++ b/src/Servers/HttpSys/src/NativeInterop/HttpApi.cs
@@ -3,149 +3,63 @@
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
-using Microsoft.AspNetCore.HttpSys.Internal;
-using static Microsoft.AspNetCore.HttpSys.Internal.HttpApiTypes;
+using Windows.Win32;
+using Windows.Win32.Networking.HttpServer;
namespace Microsoft.AspNetCore.Server.HttpSys;
-internal static unsafe partial class HttpApi
+internal static partial class HttpApi
{
+ private const string api_ms_win_core_io_LIB = "api-ms-win-core-io-l1-1-0.dll";
private const string HTTPAPI = "httpapi.dll";
- [LibraryImport(HTTPAPI, SetLastError = true)]
- internal static partial uint HttpInitialize(HTTPAPI_VERSION version, uint flags, void* pReserved);
-
[LibraryImport(HTTPAPI, SetLastError = true)]
internal static partial uint HttpReceiveRequestEntityBody(SafeHandle requestQueueHandle, ulong requestId, uint flags, IntPtr pEntityBuffer, uint entityBufferLength, out uint bytesReturned, SafeNativeOverlapped pOverlapped);
[LibraryImport(HTTPAPI, SetLastError = true)]
- internal static partial uint HttpReceiveClientCertificate(SafeHandle requestQueueHandle, ulong connectionId, uint flags, HTTP_SSL_CLIENT_CERT_INFO* pSslClientCertInfo, uint sslClientCertInfoSize, uint* pBytesReceived, SafeNativeOverlapped pOverlapped);
-
- [LibraryImport(HTTPAPI, SetLastError = true)]
- internal static partial uint HttpReceiveClientCertificate(SafeHandle requestQueueHandle, ulong connectionId, uint flags, byte* pSslClientCertInfo, uint sslClientCertInfoSize, uint* pBytesReceived, SafeNativeOverlapped pOverlapped);
-
- [LibraryImport(HTTPAPI, SetLastError = true)]
- internal static partial uint HttpReceiveHttpRequest(SafeHandle requestQueueHandle, ulong requestId, uint flags, HTTP_REQUEST* pRequestBuffer, uint requestBufferLength, uint* pBytesReturned, NativeOverlapped* pOverlapped);
-
- [LibraryImport(HTTPAPI, SetLastError = true)]
- internal static partial uint HttpSendHttpResponse(SafeHandle requestQueueHandle, ulong requestId, uint flags, HTTP_RESPONSE_V2* pHttpResponse, HTTP_CACHE_POLICY* pCachePolicy, uint* pBytesSent, IntPtr pReserved1, uint Reserved2, SafeNativeOverlapped pOverlapped, IntPtr pLogData);
-
- [LibraryImport(HTTPAPI, SetLastError = true)]
- internal static partial uint HttpSendResponseEntityBody(SafeHandle requestQueueHandle, ulong requestId, uint flags, ushort entityChunkCount, HTTP_DATA_CHUNK* pEntityChunks, uint* pBytesSent, IntPtr pReserved1, uint Reserved2, SafeNativeOverlapped pOverlapped, IntPtr pLogData);
-
- [LibraryImport(HTTPAPI, SetLastError = true)]
- internal static partial uint HttpCancelHttpRequest(SafeHandle requestQueueHandle, ulong requestId, IntPtr pOverlapped);
-
- [LibraryImport(HTTPAPI, SetLastError = true)]
- internal static partial uint HttpWaitForDisconnectEx(SafeHandle requestQueueHandle, ulong connectionId, uint reserved, NativeOverlapped* overlapped);
-
- [LibraryImport(HTTPAPI, SetLastError = true)]
- internal static partial uint HttpCreateServerSession(HTTPAPI_VERSION version, ulong* serverSessionId, uint reserved);
-
- [LibraryImport(HTTPAPI, SetLastError = true)]
- internal static partial uint HttpCreateUrlGroup(ulong serverSessionId, ulong* urlGroupId, uint reserved);
-
- [LibraryImport(HTTPAPI, SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
- internal static partial uint HttpFindUrlGroupId(string pFullyQualifiedUrl, SafeHandle requestQueueHandle, ulong* urlGroupId);
-
- [LibraryImport(HTTPAPI, SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
- internal static partial uint HttpAddUrlToUrlGroup(ulong urlGroupId, string pFullyQualifiedUrl, ulong context, uint pReserved);
-
- [LibraryImport(HTTPAPI, SetLastError = true)]
- internal static partial uint HttpSetUrlGroupProperty(ulong urlGroupId, HTTP_SERVER_PROPERTY serverProperty, IntPtr pPropertyInfo, uint propertyInfoLength);
-
- [LibraryImport(HTTPAPI, SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
- internal static partial uint HttpRemoveUrlFromUrlGroup(ulong urlGroupId, string pFullyQualifiedUrl, uint flags);
-
- [LibraryImport(HTTPAPI, SetLastError = true)]
- internal static partial uint HttpCloseServerSession(ulong serverSessionId);
+ internal static unsafe partial uint HttpReceiveClientCertificate(SafeHandle requestQueueHandle, ulong connectionId, uint flags, Windows.Win32.Networking.HttpServer.HTTP_SSL_CLIENT_CERT_INFO* pSslClientCertInfo, uint sslClientCertInfoSize, uint* pBytesReceived, SafeNativeOverlapped pOverlapped);
[LibraryImport(HTTPAPI, SetLastError = true)]
- internal static partial uint HttpCloseUrlGroup(ulong urlGroupId);
+ internal static unsafe partial uint HttpReceiveHttpRequest(SafeHandle requestQueueHandle, ulong requestId, uint flags, Windows.Win32.Networking.HttpServer.HTTP_REQUEST_V1* pRequestBuffer, uint requestBufferLength, uint* pBytesReturned, NativeOverlapped* pOverlapped);
[LibraryImport(HTTPAPI, SetLastError = true)]
- internal static partial uint HttpSetRequestQueueProperty(SafeHandle requestQueueHandle, HTTP_SERVER_PROPERTY serverProperty, IntPtr pPropertyInfo, uint propertyInfoLength, uint reserved, IntPtr pReserved);
-
- [LibraryImport(HTTPAPI, SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
- internal static unsafe partial uint HttpCreateRequestQueue(HTTPAPI_VERSION version, string? pName,
- IntPtr pSecurityAttributes, HTTP_CREATE_REQUEST_QUEUE_FLAG flags, out HttpRequestQueueV2Handle pReqQueueHandle);
+ internal static unsafe partial uint HttpSendHttpResponse(SafeHandle requestQueueHandle, ulong requestId, uint flags, Windows.Win32.Networking.HttpServer.HTTP_RESPONSE_V2* pHttpResponse, Windows.Win32.Networking.HttpServer.HTTP_CACHE_POLICY* pCachePolicy, uint* pBytesSent, IntPtr pReserved1, uint Reserved2, SafeNativeOverlapped pOverlapped, IntPtr pLogData);
[LibraryImport(HTTPAPI, SetLastError = true)]
- internal static unsafe partial uint HttpCloseRequestQueue(IntPtr pReqQueueHandle);
+ internal static unsafe partial uint HttpWaitForDisconnectEx(SafeHandle requestQueueHandle, ulong connectionId, uint reserved, NativeOverlapped* overlapped);
[LibraryImport(HTTPAPI, SetLastError = true)]
- [return: MarshalAs(UnmanagedType.Bool)]
- internal static partial bool HttpIsFeatureSupported(HTTP_FEATURE_ID feature);
+ internal static unsafe partial uint HttpSendResponseEntityBody(SafeHandle requestQueueHandle, ulong requestId, uint flags, ushort entityChunkCount, Windows.Win32.Networking.HttpServer.HTTP_DATA_CHUNK* pEntityChunks, uint* pBytesSent, IntPtr pReserved1, uint Reserved2, SafeNativeOverlapped pOverlapped, IntPtr pLogData);
- [LibraryImport(HTTPAPI, SetLastError = true)]
- internal static unsafe partial uint HttpDelegateRequestEx(SafeHandle pReqQueueHandle, SafeHandle pDelegateQueueHandle, ulong requestId,
- ulong delegateUrlGroupId, uint propertyInfoSetSize, HTTP_DELEGATE_REQUEST_PROPERTY_INFO* pRequestPropertyBuffer);
+ [LibraryImport(api_ms_win_core_io_LIB, SetLastError = true)]
+ internal static partial uint CancelIoEx(SafeHandle handle, SafeNativeOverlapped overlapped);
- internal delegate uint HttpGetRequestPropertyInvoker(SafeHandle requestQueueHandle, ulong requestId, HTTP_REQUEST_PROPERTY propertyId,
+ internal unsafe delegate uint HttpGetRequestPropertyInvoker(SafeHandle requestQueueHandle, ulong requestId, HTTP_REQUEST_PROPERTY propertyId,
void* qualifier, uint qualifierSize, void* output, uint outputSize, uint* bytesReturned, IntPtr overlapped);
- internal delegate uint HttpSetRequestPropertyInvoker(SafeHandle requestQueueHandle, ulong requestId, HTTP_REQUEST_PROPERTY propertyId, void* input, uint inputSize, IntPtr overlapped);
-
- private static HTTPAPI_VERSION version;
-
- // This property is used by HttpListener to pass the version structure to the native layer in API
- // calls.
+ internal unsafe delegate uint HttpSetRequestPropertyInvoker(SafeHandle requestQueueHandle, ulong requestId, HTTP_REQUEST_PROPERTY propertyId, void* input, uint inputSize, IntPtr overlapped);
- internal static HTTPAPI_VERSION Version
- {
- get
- {
- return version;
- }
- }
-
- // This property is used by HttpListener to get the Api version in use so that it uses appropriate
- // Http APIs.
-
- internal static HTTP_API_VERSION ApiVersion
- {
- get
- {
- if (version.HttpApiMajorVersion == 2 && version.HttpApiMinorVersion == 0)
- {
- return HTTP_API_VERSION.Version20;
- }
- else if (version.HttpApiMajorVersion == 1 && version.HttpApiMinorVersion == 0)
- {
- return HTTP_API_VERSION.Version10;
- }
- else
- {
- return HTTP_API_VERSION.Invalid;
- }
- }
- }
-
- internal static SafeLibraryHandle? HttpApiModule { get; private set; }
- internal static HttpGetRequestPropertyInvoker? HttpGetRequestProperty { get; private set; }
- internal static HttpSetRequestPropertyInvoker? HttpSetRequestProperty { get; private set; }
+ // HTTP_PROPERTY_FLAGS.Present (1)
+ internal static HTTP_PROPERTY_FLAGS HTTP_PROPERTY_FLAGS_PRESENT { get; } = new() { _bitfield = 0x00000001 };
+ // This property is used by HttpListener to pass the version structure to the native layer in API calls.
+ internal static HTTPAPI_VERSION Version { get; } = new () { HttpApiMajorVersion = 2 };
+ internal static SafeLibraryHandle? HttpApiModule { get; }
+ internal static HttpGetRequestPropertyInvoker? HttpGetRequestProperty { get; }
+ internal static HttpSetRequestPropertyInvoker? HttpSetRequestProperty { get; }
[MemberNotNullWhen(true, nameof(HttpSetRequestProperty))]
- internal static bool SupportsTrailers { get; private set; }
+ internal static bool SupportsTrailers { get; }
[MemberNotNullWhen(true, nameof(HttpSetRequestProperty))]
- internal static bool SupportsReset { get; private set; }
- internal static bool SupportsDelegation { get; private set; }
-
- static HttpApi()
- {
- InitHttpApi(2, 0);
- }
+ internal static bool SupportsReset { get; }
+ internal static bool SupportsDelegation { get; }
+ internal static bool Supported { get; }
- private static void InitHttpApi(ushort majorVersion, ushort minorVersion)
+ static unsafe HttpApi()
{
- version.HttpApiMajorVersion = majorVersion;
- version.HttpApiMinorVersion = minorVersion;
-
- var statusCode = HttpInitialize(version, (uint)(HTTP_FLAGS.HTTP_INITIALIZE_SERVER | HTTP_FLAGS.HTTP_INITIALIZE_CONFIG), null);
+ var statusCode = PInvoke.HttpInitialize(Version, HTTP_INITIALIZE.HTTP_INITIALIZE_SERVER | HTTP_INITIALIZE.HTTP_INITIALIZE_CONFIG);
- supported = statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS;
-
- if (supported)
+ if (statusCode == ErrorCodes.ERROR_SUCCESS)
{
+ Supported = true;
HttpApiModule = SafeLibraryHandle.Open(HTTPAPI);
HttpGetRequestProperty = HttpApiModule.GetProcAddress("HttpQueryRequestProperty", throwIfNotFound: false);
HttpSetRequestProperty = HttpApiModule.GetProcAddress("HttpSetRequestProperty", throwIfNotFound: false);
@@ -155,20 +69,11 @@ private static void InitHttpApi(ushort majorVersion, ushort minorVersion)
}
}
- private static volatile bool supported;
- internal static bool Supported
- {
- get
- {
- return supported;
- }
- }
-
private static bool IsFeatureSupported(HTTP_FEATURE_ID feature)
{
try
{
- return HttpIsFeatureSupported(feature);
+ return PInvoke.HttpIsFeatureSupported(feature);
}
catch (EntryPointNotFoundException) { }
diff --git a/src/Servers/HttpSys/src/NativeInterop/HttpRequestQueueV2Handle.cs b/src/Servers/HttpSys/src/NativeInterop/HttpRequestQueueV2Handle.cs
deleted file mode 100644
index d792748c8934..000000000000
--- a/src/Servers/HttpSys/src/NativeInterop/HttpRequestQueueV2Handle.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using Microsoft.AspNetCore.HttpSys.Internal;
-using Microsoft.Win32.SafeHandles;
-
-namespace Microsoft.AspNetCore.Server.HttpSys;
-
-// This class is a wrapper for Http.sys V2 request queue handle.
-internal sealed class HttpRequestQueueV2Handle : SafeHandleZeroOrMinusOneIsInvalid
-{
- public HttpRequestQueueV2Handle()
- : base(true)
- {
- }
-
- protected override bool ReleaseHandle()
- {
- return (HttpApi.HttpCloseRequestQueue(handle) ==
- UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS);
- }
-}
diff --git a/src/Servers/HttpSys/src/NativeInterop/HttpServerSessionHandle.cs b/src/Servers/HttpSys/src/NativeInterop/HttpServerSessionHandle.cs
index 3fda8c736137..1cf4a687e349 100644
--- a/src/Servers/HttpSys/src/NativeInterop/HttpServerSessionHandle.cs
+++ b/src/Servers/HttpSys/src/NativeInterop/HttpServerSessionHandle.cs
@@ -1,8 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using Microsoft.AspNetCore.HttpSys.Internal;
using Microsoft.Win32.SafeHandles;
+using Windows.Win32;
namespace Microsoft.AspNetCore.Server.HttpSys;
@@ -34,8 +34,8 @@ protected override bool ReleaseHandle()
if (Interlocked.Increment(ref disposed) == 1)
{
// Closing server session also closes all open url groups under that server session.
- return (HttpApi.HttpCloseServerSession(serverSessionId) ==
- UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS);
+ return PInvoke.HttpCloseServerSession(serverSessionId) ==
+ ErrorCodes.ERROR_SUCCESS;
}
}
return true;
diff --git a/src/Servers/HttpSys/src/NativeInterop/IntPtrHelper.cs b/src/Servers/HttpSys/src/NativeInterop/IntPtrHelper.cs
deleted file mode 100644
index 30abb9b8c234..000000000000
--- a/src/Servers/HttpSys/src/NativeInterop/IntPtrHelper.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-namespace Microsoft.AspNetCore.Server.HttpSys;
-
-internal static class IntPtrHelper
-{
- internal static IntPtr Add(IntPtr a, int b)
- {
- return (IntPtr)((long)a + (long)b);
- }
-
- internal static long Subtract(IntPtr a, IntPtr b)
- {
- return ((long)a - (long)b);
- }
-}
diff --git a/src/Servers/HttpSys/src/NativeInterop/RequestQueue.cs b/src/Servers/HttpSys/src/NativeInterop/RequestQueue.cs
index 4330f40f8620..810bdcce3c57 100644
--- a/src/Servers/HttpSys/src/NativeInterop/RequestQueue.cs
+++ b/src/Servers/HttpSys/src/NativeInterop/RequestQueue.cs
@@ -3,8 +3,9 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
-using Microsoft.AspNetCore.HttpSys.Internal;
using Microsoft.Extensions.Logging;
+using Windows.Win32;
+using Windows.Win32.Networking.HttpServer;
namespace Microsoft.AspNetCore.Server.HttpSys;
@@ -28,58 +29,58 @@ private RequestQueue(string? requestQueueName, RequestQueueMode mode, ILogger lo
_mode = mode;
_logger = logger;
- var flags = HttpApiTypes.HTTP_CREATE_REQUEST_QUEUE_FLAG.None;
+ var flags = 0u;
Created = true;
if (_mode == RequestQueueMode.Attach)
{
- flags = HttpApiTypes.HTTP_CREATE_REQUEST_QUEUE_FLAG.OpenExisting;
+ flags = PInvoke.HTTP_CREATE_REQUEST_QUEUE_FLAG_OPEN_EXISTING;
Created = false;
if (receiver)
{
- flags |= HttpApiTypes.HTTP_CREATE_REQUEST_QUEUE_FLAG.Delegation;
+ flags |= PInvoke.HTTP_CREATE_REQUEST_QUEUE_FLAG_DELEGATION;
}
}
- var statusCode = HttpApi.HttpCreateRequestQueue(
+ var statusCode = PInvoke.HttpCreateRequestQueue(
HttpApi.Version,
requestQueueName,
- IntPtr.Zero,
+ default,
flags,
out var requestQueueHandle);
- if (_mode == RequestQueueMode.CreateOrAttach && statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_ALREADY_EXISTS)
+ if (_mode == RequestQueueMode.CreateOrAttach && statusCode == ErrorCodes.ERROR_ALREADY_EXISTS)
{
// Tried to create, but it already exists so attach to it instead.
Created = false;
- flags = HttpApiTypes.HTTP_CREATE_REQUEST_QUEUE_FLAG.OpenExisting;
- statusCode = HttpApi.HttpCreateRequestQueue(
+ flags = PInvoke.HTTP_CREATE_REQUEST_QUEUE_FLAG_OPEN_EXISTING;
+ statusCode = PInvoke.HttpCreateRequestQueue(
HttpApi.Version,
requestQueueName,
- IntPtr.Zero,
+ default,
flags,
out requestQueueHandle);
}
- if (flags.HasFlag(HttpApiTypes.HTTP_CREATE_REQUEST_QUEUE_FLAG.OpenExisting) && statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_FILE_NOT_FOUND)
+ if ((flags & PInvoke.HTTP_CREATE_REQUEST_QUEUE_FLAG_OPEN_EXISTING) != 0 && statusCode == ErrorCodes.ERROR_FILE_NOT_FOUND)
{
throw new HttpSysException((int)statusCode, $"Failed to attach to the given request queue '{requestQueueName}', the queue could not be found.");
}
- else if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_INVALID_NAME)
+ else if (statusCode == ErrorCodes.ERROR_INVALID_NAME)
{
throw new HttpSysException((int)statusCode, $"The given request queue name '{requestQueueName}' is invalid.");
}
- else if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS)
+ else if (statusCode != ErrorCodes.ERROR_SUCCESS)
{
throw new HttpSysException((int)statusCode);
}
// Disabling callbacks when IO operation completes synchronously (returns ErrorCodes.ERROR_SUCCESS)
if (HttpSysListener.SkipIOCPCallbackOnSuccess &&
- !UnsafeNclNativeMethods.SetFileCompletionNotificationModes(
+ !PInvoke.SetFileCompletionNotificationModes(
requestQueueHandle,
- UnsafeNclNativeMethods.FileCompletionNotificationModes.SkipCompletionPortOnSuccess |
- UnsafeNclNativeMethods.FileCompletionNotificationModes.SkipSetEventOnHandle))
+ (byte)(PInvoke.FILE_SKIP_COMPLETION_PORT_ON_SUCCESS |
+ PInvoke.FILE_SKIP_SET_EVENT_ON_HANDLE)))
{
requestQueueHandle.Dispose();
throw new HttpSysException(Marshal.GetLastWin32Error());
@@ -108,9 +109,9 @@ internal unsafe void SetLengthLimit(long length)
Debug.Assert(Created);
CheckDisposed();
- var result = HttpApi.HttpSetRequestQueueProperty(Handle,
- HttpApiTypes.HTTP_SERVER_PROPERTY.HttpServerQueueLengthProperty,
- new IntPtr((void*)&length), (uint)Marshal.SizeOf(), 0, IntPtr.Zero);
+ var result = PInvoke.HttpSetRequestQueueProperty(Handle,
+ HTTP_SERVER_PROPERTY.HttpServerQueueLengthProperty,
+ &length, (uint)Marshal.SizeOf());
if (result != 0)
{
@@ -124,9 +125,9 @@ internal unsafe void SetRejectionVerbosity(Http503VerbosityLevel verbosity)
Debug.Assert(Created);
CheckDisposed();
- var result = HttpApi.HttpSetRequestQueueProperty(Handle,
- HttpApiTypes.HTTP_SERVER_PROPERTY.HttpServer503VerbosityProperty,
- new IntPtr((void*)&verbosity), (uint)Marshal.SizeOf(), 0, IntPtr.Zero);
+ var result = PInvoke.HttpSetRequestQueueProperty(Handle,
+ HTTP_SERVER_PROPERTY.HttpServer503VerbosityProperty,
+ &verbosity, (uint)Marshal.SizeOf());
if (result != 0)
{
diff --git a/src/Shared/HttpSys/NativeInterop/SafeNativeOverlapped.cs b/src/Servers/HttpSys/src/NativeInterop/SafeNativeOverlapped.cs
similarity index 78%
rename from src/Shared/HttpSys/NativeInterop/SafeNativeOverlapped.cs
rename to src/Servers/HttpSys/src/NativeInterop/SafeNativeOverlapped.cs
index df975315c305..a7a05623d8ce 100644
--- a/src/Shared/HttpSys/NativeInterop/SafeNativeOverlapped.cs
+++ b/src/Servers/HttpSys/src/NativeInterop/SafeNativeOverlapped.cs
@@ -1,18 +1,19 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
-using System.Threading;
-namespace Microsoft.AspNetCore.HttpSys.Internal;
+namespace Microsoft.AspNetCore.Server.HttpSys;
internal sealed class SafeNativeOverlapped : SafeHandle
{
internal static readonly SafeNativeOverlapped Zero = new SafeNativeOverlapped();
private readonly ThreadPoolBoundHandle? _boundHandle;
+ private static bool HasShutdownStarted => Environment.HasShutdownStarted
+ || AppDomain.CurrentDomain.IsFinalizingForUnload();
+
public SafeNativeOverlapped()
: base(IntPtr.Zero, true)
{
@@ -35,9 +36,9 @@ protected override bool ReleaseHandle()
Debug.Assert(_boundHandle != null, "ReleaseHandle can't be called on SafeNativeOverlapped.Zero.");
IntPtr oldHandle = Interlocked.Exchange(ref handle, IntPtr.Zero);
- // Do not call free durring AppDomain shutdown, there may be an outstanding operation.
+ // Do not call free during AppDomain shutdown, there may be an outstanding operation.
// Overlapped will take care calling free when the native callback completes.
- if (oldHandle != IntPtr.Zero && !NclUtilities.HasShutdownStarted)
+ if (oldHandle != IntPtr.Zero && !HasShutdownStarted)
{
unsafe
{
diff --git a/src/Servers/HttpSys/src/NativeInterop/ServerSession.cs b/src/Servers/HttpSys/src/NativeInterop/ServerSession.cs
index a1cff3fc396e..9e19f5994d28 100644
--- a/src/Servers/HttpSys/src/NativeInterop/ServerSession.cs
+++ b/src/Servers/HttpSys/src/NativeInterop/ServerSession.cs
@@ -1,8 +1,8 @@
-// Licensed to the .NET Foundation under one or more agreements.
+// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
-using Microsoft.AspNetCore.HttpSys.Internal;
+using Windows.Win32;
namespace Microsoft.AspNetCore.Server.HttpSys;
@@ -11,10 +11,10 @@ internal sealed class ServerSession : IDisposable
internal unsafe ServerSession()
{
ulong serverSessionId = 0;
- var statusCode = HttpApi.HttpCreateServerSession(
+ var statusCode = PInvoke.HttpCreateServerSession(
HttpApi.Version, &serverSessionId, 0);
- if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS)
+ if (statusCode != ErrorCodes.ERROR_SUCCESS)
{
throw new HttpSysException((int)statusCode);
}
diff --git a/src/Servers/HttpSys/src/NativeInterop/TokenBindingUtil.cs b/src/Servers/HttpSys/src/NativeInterop/TokenBindingUtil.cs
deleted file mode 100644
index 67364726dc89..000000000000
--- a/src/Servers/HttpSys/src/NativeInterop/TokenBindingUtil.cs
+++ /dev/null
@@ -1,80 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-using System.Runtime.InteropServices;
-using Microsoft.AspNetCore.HttpSys.Internal;
-using static Microsoft.AspNetCore.HttpSys.Internal.HttpApiTypes;
-using static Microsoft.AspNetCore.HttpSys.Internal.UnsafeNclNativeMethods.TokenBinding;
-
-namespace Microsoft.AspNetCore.Server.HttpSys;
-
-///
-/// Contains helpers for dealing with TLS token binding.
-///
-// TODO: https://github.com/aspnet/HttpSysServer/issues/231
-internal static unsafe class TokenBindingUtil
-{
- private static byte[] ExtractIdentifierBlob(TOKENBINDING_RESULT_DATA* pTokenBindingResultData)
- {
- // Per http://tools.ietf.org/html/draft-ietf-tokbind-protocol-00, Sec. 4,
- // the identifier is a tuple which contains (token binding type, hash algorithm
- // signature algorithm, key data). We'll strip off the token binding type and
- // return the remainder (starting with the hash algorithm) as an opaque blob.
- byte[] retVal = new byte[checked(pTokenBindingResultData->identifierSize - 1)];
- Marshal.Copy((IntPtr)(&pTokenBindingResultData->identifierData->hashAlgorithm), retVal, 0, retVal.Length);
- return retVal;
- }
-
- ///
- /// Returns the 'provided' token binding identifier, optionally also returning the
- /// 'referred' token binding identifier. Returns null on failure.
- ///
- public static byte[]? GetProvidedTokenIdFromBindingInfo(HTTP_REQUEST_TOKEN_BINDING_INFO* pTokenBindingInfo, out byte[]? referredId)
- {
- byte[]? providedId = null;
- referredId = null;
-
- HeapAllocHandle? handle = null;
- int status = UnsafeNclNativeMethods.TokenBindingVerifyMessage(
- pTokenBindingInfo->TokenBinding,
- pTokenBindingInfo->TokenBindingSize,
- pTokenBindingInfo->KeyType,
- pTokenBindingInfo->TlsUnique,
- pTokenBindingInfo->TlsUniqueSize,
- out handle);
-
- // No match found or there was an error?
- if (status != 0 || handle == null || handle.IsInvalid)
- {
- return null;
- }
-
- using (handle)
- {
- // Find the first 'provided' and 'referred' types.
- TOKENBINDING_RESULT_LIST* pResultList = (TOKENBINDING_RESULT_LIST*)handle.DangerousGetHandle();
- for (int i = 0; i < pResultList->resultCount; i++)
- {
- TOKENBINDING_RESULT_DATA* pThisResultData = &pResultList->resultData[i];
- if (pThisResultData->identifierData->bindingType == TOKENBINDING_TYPE.TOKENBINDING_TYPE_PROVIDED)
- {
- if (providedId != null)
- {
- return null; // It is invalid to have more than one 'provided' identifier.
- }
- providedId = ExtractIdentifierBlob(pThisResultData);
- }
- else if (pThisResultData->identifierData->bindingType == TOKENBINDING_TYPE.TOKENBINDING_TYPE_REFERRED)
- {
- if (referredId != null)
- {
- return null; // It is invalid to have more than one 'referred' identifier.
- }
- referredId = ExtractIdentifierBlob(pThisResultData);
- }
- }
- }
-
- return providedId;
- }
-}
diff --git a/src/Servers/HttpSys/src/NativeInterop/UrlGroup.cs b/src/Servers/HttpSys/src/NativeInterop/UrlGroup.cs
index dbde24640ef5..9dfc3ce9a9de 100644
--- a/src/Servers/HttpSys/src/NativeInterop/UrlGroup.cs
+++ b/src/Servers/HttpSys/src/NativeInterop/UrlGroup.cs
@@ -3,19 +3,21 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
-using Microsoft.AspNetCore.HttpSys.Internal;
using Microsoft.Extensions.Logging;
+using Windows.Win32;
+using Windows.Win32.Foundation;
+using Windows.Win32.Networking.HttpServer;
namespace Microsoft.AspNetCore.Server.HttpSys;
internal sealed partial class UrlGroup : IDisposable
{
private static readonly int BindingInfoSize =
- Marshal.SizeOf();
+ Marshal.SizeOf();
private static readonly int QosInfoSize =
- Marshal.SizeOf();
+ Marshal.SizeOf();
private static readonly int RequestPropertyInfoSize =
- Marshal.SizeOf();
+ Marshal.SizeOf();
private readonly ILogger _logger;
@@ -30,12 +32,10 @@ internal unsafe UrlGroup(ServerSession serverSession, RequestQueue requestQueue,
_requestQueue = requestQueue;
_logger = logger;
- ulong urlGroupId = 0;
_created = true;
- var statusCode = HttpApi.HttpCreateUrlGroup(
- _serverSession.Id.DangerousGetServerSessionId(), &urlGroupId, 0);
+ var statusCode = PInvoke.HttpCreateUrlGroup(_serverSession.Id.DangerousGetServerSessionId(), out var urlGroupId);
- if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS)
+ if (statusCode != ErrorCodes.ERROR_SUCCESS)
{
throw new HttpSysException((int)statusCode);
}
@@ -48,43 +48,50 @@ internal unsafe UrlGroup(ServerSession serverSession, RequestQueue requestQueue,
internal unsafe void SetMaxConnections(long maxConnections)
{
- var connectionLimit = new HttpApiTypes.HTTP_CONNECTION_LIMIT_INFO();
- connectionLimit.Flags = HttpApiTypes.HTTP_FLAGS.HTTP_PROPERTY_FLAG_PRESENT;
- connectionLimit.MaxConnections = (uint)maxConnections;
+ var connectionLimit = new HTTP_CONNECTION_LIMIT_INFO
+ {
+ Flags = HttpApi.HTTP_PROPERTY_FLAGS_PRESENT,
+ MaxConnections = (uint)maxConnections
+ };
- var qosSettings = new HttpApiTypes.HTTP_QOS_SETTING_INFO();
- qosSettings.QosType = HttpApiTypes.HTTP_QOS_SETTING_TYPE.HttpQosSettingTypeConnectionLimit;
- qosSettings.QosSetting = new IntPtr(&connectionLimit);
+ var qosSettings = new HTTP_QOS_SETTING_INFO
+ {
+ QosType = HTTP_QOS_SETTING_TYPE.HttpQosSettingTypeConnectionLimit,
+ QosSetting = &connectionLimit
+ };
- SetProperty(HttpApiTypes.HTTP_SERVER_PROPERTY.HttpServerQosProperty, new IntPtr(&qosSettings), (uint)QosInfoSize);
+ SetProperty(HTTP_SERVER_PROPERTY.HttpServerQosProperty, new IntPtr(&qosSettings), (uint)QosInfoSize);
}
internal unsafe void SetDelegationProperty(RequestQueue destination)
{
- var propertyInfo = new HttpApiTypes.HTTP_BINDING_INFO();
- propertyInfo.Flags = HttpApiTypes.HTTP_FLAGS.HTTP_PROPERTY_FLAG_PRESENT;
- propertyInfo.RequestQueueHandle = destination.Handle.DangerousGetHandle();
+ var propertyInfo = new HTTP_BINDING_INFO
+ {
+ Flags = HttpApi.HTTP_PROPERTY_FLAGS_PRESENT,
+ RequestQueueHandle = (HANDLE)destination.Handle.DangerousGetHandle()
+ };
- SetProperty(HttpApiTypes.HTTP_SERVER_PROPERTY.HttpServerDelegationProperty, new IntPtr(&propertyInfo), (uint)RequestPropertyInfoSize);
+ SetProperty(HTTP_SERVER_PROPERTY.HttpServerDelegationProperty, new IntPtr(&propertyInfo), (uint)RequestPropertyInfoSize);
}
internal unsafe void UnSetDelegationProperty(RequestQueue destination, bool throwOnError = true)
{
- var propertyInfo = new HttpApiTypes.HTTP_BINDING_INFO();
- propertyInfo.Flags = HttpApiTypes.HTTP_FLAGS.NONE;
- propertyInfo.RequestQueueHandle = destination.Handle.DangerousGetHandle();
+ var propertyInfo = new HTTP_BINDING_INFO
+ {
+ RequestQueueHandle = (HANDLE)destination.Handle.DangerousGetHandle()
+ };
- SetProperty(HttpApiTypes.HTTP_SERVER_PROPERTY.HttpServerDelegationProperty, new IntPtr(&propertyInfo), (uint)RequestPropertyInfoSize, throwOnError);
+ SetProperty(HTTP_SERVER_PROPERTY.HttpServerDelegationProperty, new IntPtr(&propertyInfo), (uint)RequestPropertyInfoSize, throwOnError);
}
- internal void SetProperty(HttpApiTypes.HTTP_SERVER_PROPERTY property, IntPtr info, uint infosize, bool throwOnError = true)
+ internal unsafe void SetProperty(HTTP_SERVER_PROPERTY property, IntPtr info, uint infosize, bool throwOnError = true)
{
Debug.Assert(info != IntPtr.Zero, "SetUrlGroupProperty called with invalid pointer");
CheckDisposed();
- var statusCode = HttpApi.HttpSetUrlGroupProperty(Id, property, info, infosize);
+ var statusCode = PInvoke.HttpSetUrlGroupProperty(Id, property, info.ToPointer(), infosize);
- if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS)
+ if (statusCode != ErrorCodes.ERROR_SUCCESS)
{
var exception = new HttpSysException((int)statusCode);
Log.SetUrlPropertyError(_logger, exception);
@@ -101,13 +108,15 @@ internal unsafe void AttachToQueue()
// Set the association between request queue and url group. After this, requests for registered urls will
// get delivered to this request queue.
- var info = new HttpApiTypes.HTTP_BINDING_INFO();
- info.Flags = HttpApiTypes.HTTP_FLAGS.HTTP_PROPERTY_FLAG_PRESENT;
- info.RequestQueueHandle = _requestQueue.Handle.DangerousGetHandle();
+ var info = new HTTP_BINDING_INFO
+ {
+ Flags = HttpApi.HTTP_PROPERTY_FLAGS_PRESENT,
+ RequestQueueHandle = (HANDLE)_requestQueue.Handle.DangerousGetHandle()
+ };
var infoptr = new IntPtr(&info);
- SetProperty(HttpApiTypes.HTTP_SERVER_PROPERTY.HttpServerBindingProperty,
+ SetProperty(HTTP_SERVER_PROPERTY.HttpServerBindingProperty,
infoptr, (uint)BindingInfoSize);
}
@@ -120,13 +129,10 @@ internal unsafe void DetachFromQueue()
// is fine since http.sys allows to set HttpServerBindingProperty multiple times for valid
// Url groups.
- var info = new HttpApiTypes.HTTP_BINDING_INFO();
- info.Flags = HttpApiTypes.HTTP_FLAGS.NONE;
- info.RequestQueueHandle = IntPtr.Zero;
-
+ var info = new HTTP_BINDING_INFO();
var infoptr = new IntPtr(&info);
- SetProperty(HttpApiTypes.HTTP_SERVER_PROPERTY.HttpServerBindingProperty,
+ SetProperty(HTTP_SERVER_PROPERTY.HttpServerBindingProperty,
infoptr, (uint)BindingInfoSize, throwOnError: false);
}
@@ -134,11 +140,10 @@ internal void RegisterPrefix(string uriPrefix, int contextId)
{
Log.RegisteringPrefix(_logger, uriPrefix);
CheckDisposed();
- var statusCode = HttpApi.HttpAddUrlToUrlGroup(Id, uriPrefix, (ulong)contextId, 0);
-
- if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS)
+ var statusCode = PInvoke.HttpAddUrlToUrlGroup(Id, uriPrefix, (ulong)contextId);
+ if (statusCode != ErrorCodes.ERROR_SUCCESS)
{
- if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_ALREADY_EXISTS)
+ if (statusCode == ErrorCodes.ERROR_ALREADY_EXISTS)
{
// If we didn't create the queue and the uriPrefix already exists, confirm it exists for the
// queue we attached to, if so we are all good, otherwise throw an already registered error.
@@ -146,9 +151,8 @@ internal void RegisterPrefix(string uriPrefix, int contextId)
{
unsafe
{
- ulong urlGroupId;
- var findUrlStatusCode = HttpApi.HttpFindUrlGroupId(uriPrefix, _requestQueue.Handle, &urlGroupId);
- if (findUrlStatusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS)
+ var findUrlStatusCode = PInvoke.HttpFindUrlGroupId(uriPrefix, _requestQueue.Handle, out var _);
+ if (findUrlStatusCode == ErrorCodes.ERROR_SUCCESS)
{
// Already registered for the desired queue, all good
return;
@@ -158,7 +162,7 @@ internal void RegisterPrefix(string uriPrefix, int contextId)
throw new HttpSysException((int)statusCode, Resources.FormatException_PrefixAlreadyRegistered(uriPrefix));
}
- if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_ACCESS_DENIED)
+ if (statusCode == ErrorCodes.ERROR_ACCESS_DENIED)
{
throw new HttpSysException((int)statusCode, Resources.FormatException_AccessDenied(uriPrefix, Environment.UserDomainName + @"\" + Environment.UserName));
}
@@ -171,7 +175,7 @@ internal void UnregisterPrefix(string uriPrefix)
Log.UnregisteringPrefix(_logger, uriPrefix);
CheckDisposed();
- HttpApi.HttpRemoveUrlFromUrlGroup(Id, uriPrefix, 0);
+ PInvoke.HttpRemoveUrlFromUrlGroup(Id, uriPrefix, 0);
}
public void Dispose()
@@ -188,9 +192,9 @@ public void Dispose()
Debug.Assert(Id != 0, "HttpCloseUrlGroup called with invalid url group id");
- uint statusCode = HttpApi.HttpCloseUrlGroup(Id);
+ var statusCode = PInvoke.HttpCloseUrlGroup(Id);
- if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS)
+ if (statusCode != ErrorCodes.ERROR_SUCCESS)
{
Log.CloseUrlGroupError(_logger, statusCode);
}
diff --git a/src/Servers/HttpSys/src/NativeMethods.txt b/src/Servers/HttpSys/src/NativeMethods.txt
new file mode 100644
index 000000000000..548306dfeade
--- /dev/null
+++ b/src/Servers/HttpSys/src/NativeMethods.txt
@@ -0,0 +1,58 @@
+// https://github.com/microsoft/cswin32
+// Listing specific types reduces the size of the final dll.
+// Uncomment the next line to import all definitions during development.
+// Windows.Win32.Networking.HttpServer
+CloseHandle
+FILE_SKIP_COMPLETION_PORT_ON_SUCCESS
+FILE_SKIP_SET_EVENT_ON_HANDLE
+HTTP_AUTH_STATUS
+HTTP_BINDING_INFO
+HTTP_CACHE_POLICY
+HTTP_CONNECTION_LIMIT_INFO
+HTTP_COOKED_URL
+HTTP_CREATE_REQUEST_QUEUE_FLAG_*
+HTTP_DATA_CHUNK
+HTTP_FEATURE_ID
+HTTP_HEADER_ID
+HTTP_KNOWN_HEADER
+HTTP_MULTIPLE_KNOWN_HEADERS
+HTTP_PROPERTY_FLAGS
+HTTP_QOS_SETTING_INFO
+HTTP_REQUEST_AUTH_INFO
+HTTP_REQUEST_AUTH_TYPE
+HTTP_REQUEST_FLAG_*
+HTTP_REQUEST_PROPERTY
+HTTP_REQUEST_PROPERTY_SNI
+HTTP_REQUEST_PROPERTY_SNI_HOST_MAX_LENGTH
+HTTP_REQUEST_PROPERTY_STREAM_ERROR
+HTTP_REQUEST_V1
+HTTP_REQUEST_V2
+HTTP_RESPONSE_INFO
+HTTP_RESPONSE_INFO_FLAGS_PRESERVE_ORDER
+HTTP_RESPONSE_INFO_TYPE
+HTTP_RESPONSE_V2
+HTTP_SEND_RESPONSE_FLAG_*
+HTTP_SERVER_AUTHENTICATION_INFO
+HTTP_SERVER_PROPERTY
+HTTP_SSL_PROTOCOL_INFO
+HTTP_TIMEOUT_LIMIT_INFO
+HttpAddUrlToUrlGroup
+HTTPAPI_VERSION
+HttpCancelHttpRequest
+HttpCloseServerSession
+HttpCloseUrlGroup
+HttpCreateRequestQueue
+HttpCreateServerSession
+HttpCreateUrlGroup
+HttpDelegateRequestEx
+HttpFindUrlGroupId
+HttpInitialize
+HttpIsFeatureSupported
+HttpReceiveRequestEntityBody
+HttpRemoveUrlFromUrlGroup
+HttpSendHttpResponse
+HttpSendResponseEntityBody
+HttpSetRequestQueueProperty
+HttpSetUrlGroupProperty
+HttpSetUrlGroupProperty
+SetFileCompletionNotificationModes
diff --git a/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.cs b/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.cs
index 63ae12d19015..56a5ae4f8fe7 100644
--- a/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.cs
+++ b/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.cs
@@ -1,16 +1,13 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
-using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
-using Microsoft.AspNetCore.HttpSys.Internal;
-using Microsoft.Extensions.Logging;
+using Windows.Win32.Networking.HttpServer;
namespace Microsoft.AspNetCore.Server.HttpSys;
@@ -18,14 +15,12 @@ namespace Microsoft.AspNetCore.Server.HttpSys;
// failures are handled internally and reported via ClientCertException or ClientCertError.
internal sealed unsafe partial class ClientCertLoader : IAsyncResult, IDisposable
{
- private const uint CertBoblSize = 1500;
+ private const uint CertBlobSize = 1500;
private static readonly IOCompletionCallback IOCallback = new IOCompletionCallback(WaitCallback);
- private static readonly int RequestChannelBindStatusSize =
- Marshal.SizeOf();
private SafeNativeOverlapped? _overlapped;
private byte[]? _backingBuffer;
- private HttpApiTypes.HTTP_SSL_CLIENT_CERT_INFO* _memoryBlob;
+ private HTTP_SSL_CLIENT_CERT_INFO* _memoryBlob;
private uint _size;
private readonly TaskCompletionSource
diff --git a/src/Shared/test/Shared.Tests/NativeMethods.txt b/src/Shared/test/Shared.Tests/NativeMethods.txt
new file mode 100644
index 000000000000..268b666b0111
--- /dev/null
+++ b/src/Shared/test/Shared.Tests/NativeMethods.txt
@@ -0,0 +1,2 @@
+// https://github.com/microsoft/cswin32
+Windows.Win32.Networking.HttpServer