-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
IISHttpServer.cs
306 lines (257 loc) · 11 KB
/
IISHttpServer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Server.IIS.Core;
internal sealed class IISHttpServer : IServer
{
private const string WebSocketVersionString = "WEBSOCKET_VERSION";
private IISContextFactory? _iisContextFactory;
private readonly MemoryPool<byte> _memoryPool = new PinnedBlockMemoryPool();
private GCHandle _httpServerHandle;
private readonly IHostApplicationLifetime _applicationLifetime;
private readonly ILogger<IISHttpServer> _logger;
private readonly IISServerOptions _options;
private readonly IISNativeApplication _nativeApplication;
private readonly ServerAddressesFeature _serverAddressesFeature;
private readonly string? _virtualPath;
private readonly TaskCompletionSource _shutdownSignal = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
private bool? _websocketAvailable;
private CancellationTokenRegistration _cancellationTokenRegistration;
private bool _disposed;
public IFeatureCollection Features { get; } = new FeatureCollection();
// TODO: Remove pInProcessHandler argument
public bool IsWebSocketAvailable(NativeSafeHandle pInProcessHandler)
{
// Check if the Http upgrade feature is available in IIS.
// To check this, we can look at the server variable WEBSOCKET_VERSION
// And see if there is a version. Same check that Katana did:
// https://github.com/aspnet/AspNetKatana/blob/9f6e09af6bf203744feb5347121fe25f6eec06d8/src/Microsoft.Owin.Host.SystemWeb/OwinAppContext.cs#L125
// Actively not locking here as acquiring a lock on every request will hurt perf more than checking the
// server variables a few extra times if a bunch of requests hit the server at the same time.
if (!_websocketAvailable.HasValue)
{
_websocketAvailable = NativeMethods.HttpTryGetServerVariable(pInProcessHandler, WebSocketVersionString, out var webSocketsSupported)
&& !string.IsNullOrEmpty(webSocketsSupported);
}
return _websocketAvailable.Value;
}
public IISHttpServer(
IISNativeApplication nativeApplication,
IHostApplicationLifetime applicationLifetime,
IAuthenticationSchemeProvider authentication,
IConfiguration configuration,
IOptions<IISServerOptions> options,
ILogger<IISHttpServer> logger
)
{
_nativeApplication = nativeApplication;
_applicationLifetime = applicationLifetime;
_logger = logger;
_options = options.Value;
_serverAddressesFeature = new ServerAddressesFeature();
var iisConfigData = NativeMethods.HttpGetApplicationProperties();
_virtualPath = iisConfigData.pwzVirtualApplicationPath;
if (_options.ForwardWindowsAuthentication)
{
authentication.AddScheme(new AuthenticationScheme(IISServerDefaults.AuthenticationScheme, _options.AuthenticationDisplayName, typeof(IISServerAuthenticationHandlerInternal)));
}
Features.Set<IServerAddressesFeature>(_serverAddressesFeature);
if (IISEnvironmentFeature.TryCreate(configuration, out var iisEnvFeature))
{
Features.Set<IIISEnvironmentFeature>(iisEnvFeature);
}
if (_options.MaxRequestBodySize > _options.IisMaxRequestSizeLimit)
{
_logger.LogWarning(CoreStrings.MaxRequestLimitWarning);
}
}
public string? VirtualPath => _virtualPath;
public unsafe Task StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken) where TContext : notnull
{
_httpServerHandle = GCHandle.Alloc(this);
_iisContextFactory = new IISContextFactory<TContext>(_memoryPool, application, _options, this, _logger);
_nativeApplication.RegisterCallbacks(
&HandleRequest,
&HandleShutdown,
&OnDisconnect,
&OnAsyncCompletion,
&OnRequestsDrained,
(IntPtr)_httpServerHandle,
(IntPtr)_httpServerHandle);
_serverAddressesFeature.Addresses = _options.ServerAddresses;
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_nativeApplication.StopIncomingRequests();
_cancellationTokenRegistration = cancellationToken.Register((shutdownSignal) =>
{
((TaskCompletionSource)shutdownSignal!).TrySetResult();
},
_shutdownSignal);
return _shutdownSignal.Task;
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
// Block any more calls into managed from native as we are unloading.
_nativeApplication.StopCallsIntoManaged();
_shutdownSignal.TrySetResult();
if (_httpServerHandle.IsAllocated)
{
_httpServerHandle.Free();
}
_memoryPool.Dispose();
_nativeApplication.Dispose();
}
[UnmanagedCallersOnly]
private static NativeMethods.REQUEST_NOTIFICATION_STATUS HandleRequest(IntPtr pInProcessHandler, IntPtr pvRequestContext)
{
IISHttpServer? server = null;
try
{
// Unwrap the server so we can create an http context and process the request
server = (IISHttpServer?)GCHandle.FromIntPtr(pvRequestContext).Target;
// server can be null if ungraceful shutdown.
if (server == null)
{
return NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_FINISH_REQUEST;
}
var safehandle = new NativeSafeHandle(pInProcessHandler);
Debug.Assert(server._iisContextFactory != null, "StartAsync must be called first.");
var context = server._iisContextFactory.CreateHttpContext(safehandle);
ThreadPool.UnsafeQueueUserWorkItem(context, preferLocal: false);
return NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_PENDING;
}
catch (Exception ex)
{
server?._logger.LogError(0, ex, $"Unexpected exception in static {nameof(IISHttpServer)}.{nameof(HandleRequest)}.");
return NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_FINISH_REQUEST;
}
}
[UnmanagedCallersOnly]
private static int HandleShutdown(IntPtr pvRequestContext)
{
IISHttpServer? server = null;
try
{
server = (IISHttpServer?)GCHandle.FromIntPtr(pvRequestContext).Target;
// server can be null if ungraceful shutdown.
if (server == null)
{
// return value isn't checked.
return 1;
}
server._applicationLifetime.StopApplication();
}
catch (Exception ex)
{
server?._logger.LogError(0, ex, $"Unexpected exception in {nameof(IISHttpServer)}.{nameof(HandleShutdown)}.");
}
return 1;
}
[UnmanagedCallersOnly]
private static void OnDisconnect(IntPtr pvManagedHttpContext)
{
IISHttpContext? context = null;
try
{
context = (IISHttpContext?)GCHandle.FromIntPtr(pvManagedHttpContext).Target;
// Context can be null if ungraceful shutdown.
if (context == null)
{
return;
}
context.AbortIO(clientDisconnect: true);
}
catch (Exception ex)
{
context?.Server._logger.LogError(0, ex, $"Unexpected exception in {nameof(IISHttpServer)}.{nameof(OnDisconnect)}.");
}
}
[UnmanagedCallersOnly]
private static NativeMethods.REQUEST_NOTIFICATION_STATUS OnAsyncCompletion(IntPtr pvManagedHttpContext, int hr, int bytes)
{
IISHttpContext? context = null;
try
{
context = (IISHttpContext?)GCHandle.FromIntPtr(pvManagedHttpContext).Target;
// Context can be null if ungraceful shutdown.
if (context == null)
{
return NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_FINISH_REQUEST;
}
context.OnAsyncCompletion(hr, bytes);
return NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_PENDING;
}
catch (Exception ex)
{
context?.Server._logger.LogError(0, ex, $"Unexpected exception in {nameof(IISHttpServer)}.{nameof(OnAsyncCompletion)}.");
return NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_FINISH_REQUEST;
}
}
[UnmanagedCallersOnly]
private static void OnRequestsDrained(IntPtr serverContext)
{
IISHttpServer? server = null;
try
{
server = (IISHttpServer?)GCHandle.FromIntPtr(serverContext).Target;
// server can be null if ungraceful shutdown.
if (server == null)
{
return;
}
server._nativeApplication.StopCallsIntoManaged();
server._shutdownSignal.TrySetResult();
server._cancellationTokenRegistration.Dispose();
}
catch (Exception ex)
{
server?._logger.LogError(0, ex, $"Unexpected exception in {nameof(IISHttpServer)}.{nameof(OnRequestsDrained)}.");
}
}
private sealed class IISContextFactory<T> : IISContextFactory where T : notnull
{
private const string Latin1Suppport = "Microsoft.AspNetCore.Server.IIS.Latin1RequestHeaders";
private readonly IHttpApplication<T> _application;
private readonly MemoryPool<byte> _memoryPool;
private readonly IISServerOptions _options;
private readonly IISHttpServer _server;
private readonly ILogger _logger;
private readonly bool _useLatin1;
public IISContextFactory(MemoryPool<byte> memoryPool, IHttpApplication<T> application, IISServerOptions options, IISHttpServer server, ILogger logger)
{
_application = application;
_memoryPool = memoryPool;
_options = options;
_server = server;
_logger = logger;
AppContext.TryGetSwitch(Latin1Suppport, out _useLatin1);
}
public IISHttpContext CreateHttpContext(NativeSafeHandle pInProcessHandler)
{
return new IISHttpContextOfT<T>(_memoryPool, _application, pInProcessHandler, _options, _server, _logger, _useLatin1);
}
}
}
// Over engineering to avoid allocations...
internal interface IISContextFactory
{
IISHttpContext CreateHttpContext(NativeSafeHandle pInProcessHandler);
}