This repository has been archived by the owner on Dec 18, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 528
/
FrameOfT.cs
233 lines (205 loc) · 10.3 KB
/
FrameOfT.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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Server.Kestrel.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.Internal.Networking;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Server.Kestrel.Internal.Http
{
public class Frame<TContext> : Frame
{
private readonly IHttpApplication<TContext> _application;
public Frame(IHttpApplication<TContext> application,
ConnectionContext context)
: base(context)
{
_application = application;
}
/// <summary>
/// Primary loop which consumes socket input, parses it for protocol framing, and invokes the
/// application delegate for as long as the socket is intended to remain open.
/// The resulting Task from this loop is preserved in a field which is used when the server needs
/// to drain and close all currently active connections.
/// </summary>
public override async Task RequestProcessingAsync()
{
var requestLineStatus = RequestLineStatus.Empty;
try
{
while (!_requestProcessingStopping)
{
ConnectionControl.SetTimeout(_keepAliveMilliseconds, TimeoutAction.CloseConnection);
while (!_requestProcessingStopping)
{
requestLineStatus = TakeStartLine(SocketInput);
if (requestLineStatus == RequestLineStatus.Done)
{
break;
}
if (SocketInput.CheckFinOrThrow())
{
// We need to attempt to consume start lines and headers even after
// SocketInput.RemoteIntakeFin is set to true to ensure we don't close a
// connection without giving the application a chance to respond to a request
// sent immediately before the a FIN from the client.
requestLineStatus = TakeStartLine(SocketInput);
if (requestLineStatus == RequestLineStatus.Empty)
{
return;
}
if (requestLineStatus != RequestLineStatus.Done)
{
RejectRequest(RequestRejectionReason.InvalidRequestLine, requestLineStatus.ToString());
}
break;
}
await SocketInput;
}
InitializeHeaders();
while (!_requestProcessingStopping && !TakeMessageHeaders(SocketInput, FrameRequestHeaders))
{
if (SocketInput.CheckFinOrThrow())
{
// We need to attempt to consume start lines and headers even after
// SocketInput.RemoteIntakeFin is set to true to ensure we don't close a
// connection without giving the application a chance to respond to a request
// sent immediately before the a FIN from the client.
if (!TakeMessageHeaders(SocketInput, FrameRequestHeaders))
{
RejectRequest(RequestRejectionReason.MalformedRequestInvalidHeaders);
}
break;
}
await SocketInput;
}
if (!_requestProcessingStopping)
{
var messageBody = MessageBody.For(_httpVersion, FrameRequestHeaders, this);
_keepAlive = messageBody.RequestKeepAlive;
_upgrade = messageBody.RequestUpgrade;
InitializeStreams(messageBody);
var context = _application.CreateContext(this);
try
{
try
{
await _application.ProcessRequestAsync(context).ConfigureAwait(false);
VerifyResponseContentLength();
}
catch (Exception ex)
{
ReportApplicationError(ex);
if (ex is BadHttpRequestException)
{
throw;
}
}
finally
{
// Trigger OnStarting if it hasn't been called yet and the app hasn't
// already failed. If an OnStarting callback throws we can go through
// our normal error handling in ProduceEnd.
// https://github.com/aspnet/KestrelHttpServer/issues/43
if (!HasResponseStarted && _applicationException == null && _onStarting != null)
{
await FireOnStarting();
}
PauseStreams();
if (_onCompleted != null)
{
await FireOnCompleted();
}
}
// If _requestAbort is set, the connection has already been closed.
if (Volatile.Read(ref _requestAborted) == 0)
{
ResumeStreams();
if (_keepAlive)
{
// Finish reading the request body in case the app did not.
await messageBody.Consume();
}
// ProduceEnd() must be called before _application.DisposeContext(), to ensure
// HttpContext.Response.StatusCode is correctly set when
// IHttpContextFactory.Dispose(HttpContext) is called.
await ProduceEnd();
}
else if (!HasResponseStarted)
{
// If the request was aborted and no response was sent, there's no
// meaningful status code to log.
StatusCode = 0;
}
}
catch (BadHttpRequestException ex)
{
// Handle BadHttpRequestException thrown during app execution or remaining message body consumption.
// This has to be caught here so StatusCode is set properly before disposing the HttpContext
// (DisposeContext logs StatusCode).
SetBadRequestState(ex);
}
finally
{
_application.DisposeContext(context, _applicationException);
// StopStreams should be called before the end of the "if (!_requestProcessingStopping)" block
// to ensure InitializeStreams has been called.
StopStreams();
}
}
if (!_keepAlive)
{
// End the connection for non keep alive as data incoming may have been thrown off
return;
}
// Don't reset frame state if we're exiting the loop. This avoids losing request rejection
// information (for 4xx response), and prevents ObjectDisposedException on HTTPS (ODEs
// will be thrown if PrepareRequest is not null and references objects disposed on connection
// close - see https://github.com/aspnet/KestrelHttpServer/issues/1103#issuecomment-250237677).
if (!_requestProcessingStopping)
{
Reset();
}
}
}
catch (BadHttpRequestException ex)
{
// Handle BadHttpRequestException thrown during request line or header parsing.
// SetBadRequestState logs the error.
SetBadRequestState(ex);
}
catch (IOException ex) when (ex.InnerException is UvException)
{
// Don't log ECONNRESET errors made between requests. Browsers like IE will reset connections regularly.
if (requestLineStatus != RequestLineStatus.Empty ||
((UvException)ex.InnerException).StatusCode != Constants.ECONNRESET)
{
Log.RequestProcessingError(ConnectionId, ex);
}
}
catch (Exception ex)
{
Log.LogWarning(0, ex, "Connection processing ended abnormally");
}
finally
{
try
{
// If _requestAborted is set, the connection has already been closed.
if (Volatile.Read(ref _requestAborted) == 0)
{
await TryProduceInvalidRequestResponse();
ConnectionControl.End(ProduceEndType.SocketShutdown);
}
}
catch (Exception ex)
{
Log.LogWarning(0, ex, "Connection shutdown abnormally");
}
}
}
}
}