-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
HttpProtocol.cs
1587 lines (1339 loc) · 55.3 KB
/
HttpProtocol.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
{
internal abstract partial class HttpProtocol : IHttpResponseControl
{
private static readonly byte[] _bytesConnectionClose = Encoding.ASCII.GetBytes("\r\nConnection: close");
private static readonly byte[] _bytesConnectionKeepAlive = Encoding.ASCII.GetBytes("\r\nConnection: keep-alive");
private static readonly byte[] _bytesTransferEncodingChunked = Encoding.ASCII.GetBytes("\r\nTransfer-Encoding: chunked");
private static readonly byte[] _bytesServer = Encoding.ASCII.GetBytes("\r\nServer: " + Constants.ServerName);
protected BodyControl _bodyControl;
private Stack<KeyValuePair<Func<object, Task>, object>> _onStarting;
private Stack<KeyValuePair<Func<object, Task>, object>> _onCompleted;
private readonly object _abortLock = new object();
private volatile bool _connectionAborted;
private bool _preventRequestAbortedCancellation;
private CancellationTokenSource _abortedCts;
private CancellationToken? _manuallySetRequestAbortToken;
protected RequestProcessingStatus _requestProcessingStatus;
// Keep-alive is default for HTTP/1.1 and HTTP/2; parsing and errors will change its value
// volatile, see: https://msdn.microsoft.com/en-us/library/x13ttww7.aspx
protected volatile bool _keepAlive = true;
// _canWriteResponseBody is set in CreateResponseHeaders.
// If we are writing with GetMemory/Advance before calling StartAsync, assume we can write and throw away contents if we can't.
private bool _canWriteResponseBody = true;
private bool _hasAdvanced;
private bool _isLeasedMemoryInvalid = true;
private bool _autoChunk;
protected Exception _applicationException;
private BadHttpRequestException _requestRejectedException;
protected HttpVersion _httpVersion;
private string _requestId;
private int _requestHeadersParsed;
private long _responseBytesWritten;
private readonly HttpConnectionContext _context;
private RouteValueDictionary _routeValues;
private Endpoint _endpoint;
protected string _methodText = null;
private string _scheme = null;
private Stream _requestStreamInternal;
private Stream _responseStreamInternal;
public HttpProtocol(HttpConnectionContext context)
{
_context = context;
ServerOptions = ServiceContext.ServerOptions;
HttpRequestHeaders = new HttpRequestHeaders(reuseHeaderValues: !ServerOptions.DisableStringReuse);
HttpResponseControl = this;
}
public IHttpResponseControl HttpResponseControl { get; set; }
public ServiceContext ServiceContext => _context.ServiceContext;
private IPEndPoint LocalEndPoint => _context.LocalEndPoint;
private IPEndPoint RemoteEndPoint => _context.RemoteEndPoint;
public ITimeoutControl TimeoutControl => _context.TimeoutControl;
public IFeatureCollection ConnectionFeatures => _context.ConnectionFeatures;
public IHttpOutputProducer Output { get; protected set; }
protected IKestrelTrace Log => ServiceContext.Log;
private DateHeaderValueManager DateHeaderValueManager => ServiceContext.DateHeaderValueManager;
// Hold direct reference to ServerOptions since this is used very often in the request processing path
protected KestrelServerOptions ServerOptions { get; }
protected string ConnectionId => _context.ConnectionId;
public string ConnectionIdFeature { get; set; }
public bool HasStartedConsumingRequestBody { get; set; }
public long? MaxRequestBodySize { get; set; }
public MinDataRate MinRequestBodyDataRate { get; set; }
public bool AllowSynchronousIO { get; set; }
/// <summary>
/// The request id. <seealso cref="HttpContext.TraceIdentifier"/>
/// </summary>
public string TraceIdentifier
{
set => _requestId = value;
get
{
// don't generate an ID until it is requested
if (_requestId == null)
{
_requestId = CreateRequestId();
}
return _requestId;
}
}
public bool IsUpgradableRequest { get; private set; }
public bool IsUpgraded { get; set; }
public IPAddress RemoteIpAddress { get; set; }
public int RemotePort { get; set; }
public IPAddress LocalIpAddress { get; set; }
public int LocalPort { get; set; }
public string Scheme { get; set; }
public HttpMethod Method { get; set; }
public string PathBase { get; set; }
protected string _parsedPath = null;
public string Path { get; set; }
protected string _parsedQueryString = null;
public string QueryString { get; set; }
protected string _parsedRawTarget = null;
public string RawTarget { get; set; }
public string HttpVersion
{
get
{
if (_httpVersion == Http.HttpVersion.Http11)
{
return HttpUtilities.Http11Version;
}
if (_httpVersion == Http.HttpVersion.Http10)
{
return HttpUtilities.Http10Version;
}
if (_httpVersion == Http.HttpVersion.Http2)
{
return HttpUtilities.Http2Version;
}
return string.Empty;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set
{
// GetKnownVersion returns versions which ReferenceEquals interned string
// As most common path, check for this only in fast-path and inline
if (ReferenceEquals(value, HttpUtilities.Http11Version))
{
_httpVersion = Http.HttpVersion.Http11;
}
else if (ReferenceEquals(value, HttpUtilities.Http10Version))
{
_httpVersion = Http.HttpVersion.Http10;
}
else if (ReferenceEquals(value, HttpUtilities.Http2Version))
{
_httpVersion = Http.HttpVersion.Http2;
}
else
{
HttpVersionSetSlow(value);
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void HttpVersionSetSlow(string value)
{
if (value == HttpUtilities.Http11Version)
{
_httpVersion = Http.HttpVersion.Http11;
}
else if (value == HttpUtilities.Http10Version)
{
_httpVersion = Http.HttpVersion.Http10;
}
else if (value == HttpUtilities.Http2Version)
{
_httpVersion = Http.HttpVersion.Http2;
}
else
{
_httpVersion = Http.HttpVersion.Unknown;
}
}
public IHeaderDictionary RequestHeaders { get; set; }
public IHeaderDictionary RequestTrailers { get; } = new HeaderDictionary();
public bool RequestTrailersAvailable { get; set; }
public Stream RequestBody { get; set; }
public PipeReader RequestBodyPipeReader { get; set; }
public HttpResponseTrailers ResponseTrailers { get; set; }
private int _statusCode;
public int StatusCode
{
get => _statusCode;
set
{
if (HasResponseStarted)
{
ThrowResponseAlreadyStartedException(nameof(StatusCode));
}
_statusCode = value;
}
}
private string _reasonPhrase;
public string ReasonPhrase
{
get => _reasonPhrase;
set
{
if (HasResponseStarted)
{
ThrowResponseAlreadyStartedException(nameof(ReasonPhrase));
}
_reasonPhrase = value;
}
}
public IHeaderDictionary ResponseHeaders { get; set; }
public Stream ResponseBody { get; set; }
public PipeWriter ResponseBodyPipeWriter { get; set; }
public CancellationToken RequestAborted
{
get
{
// If a request abort token was previously explicitly set, return it.
if (_manuallySetRequestAbortToken.HasValue)
{
return _manuallySetRequestAbortToken.Value;
}
lock (_abortLock)
{
if (_preventRequestAbortedCancellation)
{
return new CancellationToken(false);
}
if (_connectionAborted)
{
return new CancellationToken(true);
}
if (_abortedCts == null)
{
_abortedCts = new CancellationTokenSource();
}
return _abortedCts.Token;
}
}
set
{
// Set an abort token, overriding one we create internally. This setter and associated
// field exist purely to support IHttpRequestLifetimeFeature.set_RequestAborted.
_manuallySetRequestAbortToken = value;
}
}
public bool HasResponseStarted => _requestProcessingStatus >= RequestProcessingStatus.HeadersCommitted;
public bool HasFlushedHeaders => _requestProcessingStatus >= RequestProcessingStatus.HeadersFlushed;
public bool HasResponseCompleted => _requestProcessingStatus == RequestProcessingStatus.ResponseCompleted;
protected HttpRequestHeaders HttpRequestHeaders { get; }
protected HttpResponseHeaders HttpResponseHeaders { get; } = new HttpResponseHeaders();
public void InitializeBodyControl(MessageBody messageBody)
{
if (_bodyControl == null)
{
_bodyControl = new BodyControl(bodyControl: this, this);
}
(RequestBody, ResponseBody, RequestBodyPipeReader, ResponseBodyPipeWriter) = _bodyControl.Start(messageBody);
_requestStreamInternal = RequestBody;
_responseStreamInternal = ResponseBody;
}
// For testing
internal void ResetState()
{
_requestProcessingStatus = RequestProcessingStatus.RequestPending;
}
public void Reset()
{
_onStarting?.Clear();
_onCompleted?.Clear();
_routeValues?.Clear();
_requestProcessingStatus = RequestProcessingStatus.RequestPending;
_autoChunk = false;
_applicationException = null;
_requestRejectedException = null;
ResetFeatureCollection();
HasStartedConsumingRequestBody = false;
MaxRequestBodySize = ServerOptions.Limits.MaxRequestBodySize;
MinRequestBodyDataRate = ServerOptions.Limits.MinRequestBodyDataRate;
AllowSynchronousIO = ServerOptions.AllowSynchronousIO;
TraceIdentifier = null;
Method = HttpMethod.None;
_methodText = null;
_endpoint = null;
PathBase = null;
Path = null;
RawTarget = null;
QueryString = null;
_httpVersion = Http.HttpVersion.Unknown;
_statusCode = StatusCodes.Status200OK;
_reasonPhrase = null;
var remoteEndPoint = RemoteEndPoint;
RemoteIpAddress = remoteEndPoint?.Address;
RemotePort = remoteEndPoint?.Port ?? 0;
var localEndPoint = LocalEndPoint;
LocalIpAddress = localEndPoint?.Address;
LocalPort = localEndPoint?.Port ?? 0;
ConnectionIdFeature = ConnectionId;
HttpRequestHeaders.Reset();
HttpResponseHeaders.Reset();
RequestHeaders = HttpRequestHeaders;
ResponseHeaders = HttpResponseHeaders;
RequestTrailers.Clear();
RequestTrailersAvailable = false;
_isLeasedMemoryInvalid = true;
_hasAdvanced = false;
_canWriteResponseBody = true;
if (_scheme == null)
{
var tlsFeature = ConnectionFeatures?[typeof(ITlsConnectionFeature)];
_scheme = tlsFeature != null ? "https" : "http";
}
Scheme = _scheme;
_manuallySetRequestAbortToken = null;
// Lock to prevent CancelRequestAbortedToken from attempting to cancel a disposed CTS.
CancellationTokenSource localAbortCts = null;
lock (_abortLock)
{
_preventRequestAbortedCancellation = false;
localAbortCts = _abortedCts;
_abortedCts = null;
}
localAbortCts?.Dispose();
Output?.Reset();
_requestHeadersParsed = 0;
_responseBytesWritten = 0;
OnReset();
}
protected abstract void OnReset();
protected abstract void ApplicationAbort();
protected virtual void OnRequestProcessingEnding()
{
}
protected virtual void OnRequestProcessingEnded()
{
}
protected virtual void BeginRequestProcessing()
{
}
protected virtual void OnErrorAfterResponseStarted()
{
}
protected virtual bool BeginRead(out ValueTask<ReadResult> awaitable)
{
awaitable = default;
return false;
}
protected abstract string CreateRequestId();
protected abstract MessageBody CreateMessageBody();
protected abstract bool TryParseRequest(ReadResult result, out bool endConnection);
private void CancelRequestAbortedToken()
{
try
{
CancellationTokenSource localAbortCts = null;
lock (_abortLock)
{
if (_abortedCts != null && !_preventRequestAbortedCancellation)
{
localAbortCts = _abortedCts;
_abortedCts = null;
}
}
// If we cancel the cts, we don't dispose as people may still be using
// the cts. It also isn't necessary to dispose a canceled cts.
localAbortCts?.Cancel();
}
catch (Exception ex)
{
Log.ApplicationError(ConnectionId, TraceIdentifier, ex);
}
}
protected void AbortRequest()
{
var shouldScheduleCancellation = false;
lock (_abortLock)
{
if (_connectionAborted)
{
return;
}
shouldScheduleCancellation = _abortedCts != null && !_preventRequestAbortedCancellation;
_connectionAborted = true;
}
if (shouldScheduleCancellation)
{
// Potentially calling user code. CancelRequestAbortedToken logs any exceptions.
ServiceContext.Scheduler.Schedule(state => ((HttpProtocol)state).CancelRequestAbortedToken(), this);
}
}
protected void PoisonRequestBodyStream(Exception abortReason)
{
_bodyControl?.Abort(abortReason);
}
// Prevents the RequestAborted token from firing for the duration of the request.
private void PreventRequestAbortedCancellation()
{
lock (_abortLock)
{
if (_connectionAborted)
{
return;
}
_preventRequestAbortedCancellation = true;
}
}
public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
{
_requestHeadersParsed++;
if (_requestHeadersParsed > ServerOptions.Limits.MaxRequestHeaderCount)
{
BadHttpRequestException.Throw(RequestRejectionReason.TooManyHeaders);
}
HttpRequestHeaders.Append(name, value);
}
public void OnTrailer(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
{
// Trailers still count towards the limit.
_requestHeadersParsed++;
if (_requestHeadersParsed > ServerOptions.Limits.MaxRequestHeaderCount)
{
BadHttpRequestException.Throw(RequestRejectionReason.TooManyHeaders);
}
string key = name.GetHeaderName();
var valueStr = value.GetAsciiOrUTF8StringNonNullCharacters();
RequestTrailers.Append(key, valueStr);
}
public void OnHeadersComplete()
{
HttpRequestHeaders.OnHeadersComplete();
}
public void OnTrailersComplete()
{
RequestTrailersAvailable = true;
}
public async Task ProcessRequestsAsync<TContext>(IHttpApplication<TContext> application)
{
try
{
await ProcessRequests(application);
}
catch (BadHttpRequestException ex)
{
// Handle BadHttpRequestException thrown during request line or header parsing.
// SetBadRequestState logs the error.
SetBadRequestState(ex);
}
catch (ConnectionResetException ex)
{
// Don't log ECONNRESET errors made between requests. Browsers like IE will reset connections regularly.
if (_requestProcessingStatus != RequestProcessingStatus.RequestPending)
{
Log.RequestProcessingError(ConnectionId, ex);
}
}
catch (IOException ex)
{
Log.RequestProcessingError(ConnectionId, ex);
}
catch (ConnectionAbortedException ex)
{
Log.RequestProcessingError(ConnectionId, ex);
}
catch (Exception ex)
{
Log.LogWarning(0, ex, CoreStrings.RequestProcessingEndError);
}
finally
{
try
{
await TryProduceInvalidRequestResponse();
}
catch (Exception ex)
{
Log.LogWarning(0, ex, CoreStrings.ConnectionShutdownError);
}
finally
{
OnRequestProcessingEnded();
}
}
}
private async Task ProcessRequests<TContext>(IHttpApplication<TContext> application)
{
while (_keepAlive)
{
BeginRequestProcessing();
var result = default(ReadResult);
var endConnection = false;
do
{
if (BeginRead(out var awaitable))
{
result = await awaitable;
}
} while (!TryParseRequest(result, out endConnection));
if (endConnection)
{
// Connection finished, stop processing requests
return;
}
var messageBody = CreateMessageBody();
if (!messageBody.RequestKeepAlive)
{
_keepAlive = false;
}
IsUpgradableRequest = messageBody.RequestUpgrade;
InitializeBodyControl(messageBody);
var context = application.CreateContext(this);
try
{
KestrelEventSource.Log.RequestStart(this);
// Run the application code for this request
await application.ProcessRequestAsync(context);
// 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?.Count > 0)
{
await FireOnStarting();
}
if (!_connectionAborted && !VerifyResponseContentLength(out var lengthException))
{
ReportApplicationError(lengthException);
}
}
catch (BadHttpRequestException ex)
{
// Capture BadHttpRequestException for further processing
// This has to be caught here so StatusCode is set properly before disposing the HttpContext
// (DisposeContext logs StatusCode).
SetBadRequestState(ex);
ReportApplicationError(ex);
}
catch (Exception ex)
{
ReportApplicationError(ex);
}
KestrelEventSource.Log.RequestStop(this);
// At this point all user code that needs use to the request or response streams has completed.
// Using these streams in the OnCompleted callback is not allowed.
try
{
await _bodyControl.StopAsync();
}
catch (Exception ex)
{
// BodyControl.StopAsync() can throw if the PipeWriter was completed prior to the application writing
// enough bytes to satisfy the specified Content-Length. This risks double-logging the exception,
// but this scenario generally indicates an app bug, so I don't want to risk not logging it.
ReportApplicationError(ex);
}
// 4XX responses are written by TryProduceInvalidRequestResponse during connection tear down.
if (_requestRejectedException == null)
{
if (!_connectionAborted)
{
// Call ProduceEnd() before consuming the rest of the request body to prevent
// delaying clients waiting for the chunk terminator:
//
// https://github.com/dotnet/corefx/issues/17330#issuecomment-288248663
//
// This also prevents the 100 Continue response from being sent if the app
// never tried to read the body.
// https://github.com/aspnet/KestrelHttpServer/issues/2102
//
// 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;
}
}
if (_onCompleted?.Count > 0)
{
await FireOnCompleted();
}
application.DisposeContext(context, _applicationException);
// Even for non-keep-alive requests, try to consume the entire body to avoid RSTs.
if (!_connectionAborted && _requestRejectedException == null && !messageBody.IsEmpty)
{
await messageBody.ConsumeAsync();
}
if (HasStartedConsumingRequestBody)
{
await messageBody.StopAsync();
}
}
}
public void OnStarting(Func<object, Task> callback, object state)
{
if (HasResponseStarted)
{
ThrowResponseAlreadyStartedException(nameof(OnStarting));
}
if (_onStarting == null)
{
_onStarting = new Stack<KeyValuePair<Func<object, Task>, object>>();
}
_onStarting.Push(new KeyValuePair<Func<object, Task>, object>(callback, state));
}
public void OnCompleted(Func<object, Task> callback, object state)
{
if (_onCompleted == null)
{
_onCompleted = new Stack<KeyValuePair<Func<object, Task>, object>>();
}
_onCompleted.Push(new KeyValuePair<Func<object, Task>, object>(callback, state));
}
protected Task FireOnStarting()
{
var onStarting = _onStarting;
if (onStarting == null || onStarting.Count == 0)
{
return Task.CompletedTask;
}
else
{
return FireOnStartingMayAwait(onStarting);
}
}
private Task FireOnStartingMayAwait(Stack<KeyValuePair<Func<object, Task>, object>> onStarting)
{
try
{
while (onStarting.TryPop(out var entry))
{
var task = entry.Key.Invoke(entry.Value);
if (!task.IsCompletedSuccessfully)
{
return FireOnStartingAwaited(task, onStarting);
}
}
}
catch (Exception ex)
{
ReportApplicationError(ex);
}
return Task.CompletedTask;
}
private async Task FireOnStartingAwaited(Task currentTask, Stack<KeyValuePair<Func<object, Task>, object>> onStarting)
{
try
{
await currentTask;
while (onStarting.TryPop(out var entry))
{
await entry.Key.Invoke(entry.Value);
}
}
catch (Exception ex)
{
ReportApplicationError(ex);
}
}
protected Task FireOnCompleted()
{
var onCompleted = _onCompleted;
if (onCompleted == null || onCompleted.Count == 0)
{
return Task.CompletedTask;
}
return FireOnCompletedMayAwait(onCompleted);
}
private Task FireOnCompletedMayAwait(Stack<KeyValuePair<Func<object, Task>, object>> onCompleted)
{
while (onCompleted.TryPop(out var entry))
{
try
{
var task = entry.Key.Invoke(entry.Value);
if (!task.IsCompletedSuccessfully)
{
return FireOnCompletedAwaited(task, onCompleted);
}
}
catch (Exception ex)
{
ReportApplicationError(ex);
}
}
return Task.CompletedTask;
}
private async Task FireOnCompletedAwaited(Task currentTask, Stack<KeyValuePair<Func<object, Task>, object>> onCompleted)
{
try
{
await currentTask;
}
catch (Exception ex)
{
Log.ApplicationError(ConnectionId, TraceIdentifier, ex);
}
while (onCompleted.TryPop(out var entry))
{
try
{
await entry.Key.Invoke(entry.Value);
}
catch (Exception ex)
{
Log.ApplicationError(ConnectionId, TraceIdentifier, ex);
}
}
}
private void VerifyAndUpdateWrite(int count)
{
var responseHeaders = HttpResponseHeaders;
if (responseHeaders != null &&
!responseHeaders.HasTransferEncoding &&
responseHeaders.ContentLength.HasValue &&
_responseBytesWritten + count > responseHeaders.ContentLength.Value)
{
_keepAlive = false;
ThrowTooManyBytesWritten(count);
}
_responseBytesWritten += count;
}
[StackTraceHidden]
private void ThrowTooManyBytesWritten(int count)
{
throw GetTooManyBytesWrittenException(count);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private InvalidOperationException GetTooManyBytesWrittenException(int count)
{
var responseHeaders = HttpResponseHeaders;
return new InvalidOperationException(
CoreStrings.FormatTooManyBytesWritten(_responseBytesWritten + count, responseHeaders.ContentLength.Value));
}
private void CheckLastWrite()
{
var responseHeaders = HttpResponseHeaders;
// Prevent firing request aborted token if this is the last write, to avoid
// aborting the request if the app is still running when the client receives
// the final bytes of the response and gracefully closes the connection.
//
// Called after VerifyAndUpdateWrite(), so _responseBytesWritten has already been updated.
if (responseHeaders != null &&
!responseHeaders.HasTransferEncoding &&
responseHeaders.ContentLength.HasValue &&
_responseBytesWritten == responseHeaders.ContentLength.Value)
{
PreventRequestAbortedCancellation();
}
}
protected bool VerifyResponseContentLength(out Exception ex)
{
var responseHeaders = HttpResponseHeaders;
if (Method != HttpMethod.Head &&
StatusCode != StatusCodes.Status304NotModified &&
!responseHeaders.HasTransferEncoding &&
responseHeaders.ContentLength.HasValue &&
_responseBytesWritten < responseHeaders.ContentLength.Value)
{
// We need to close the connection if any bytes were written since the client
// cannot be certain of how many bytes it will receive.
if (_responseBytesWritten > 0)
{
_keepAlive = false;
}
ex = new InvalidOperationException(
CoreStrings.FormatTooFewBytesWritten(_responseBytesWritten, responseHeaders.ContentLength.Value));
return false;
}
ex = null;
return true;
}
public void ProduceContinue()
{
if (HasResponseStarted)
{
return;
}
if (_httpVersion != Http.HttpVersion.Http10 &&
RequestHeaders.TryGetValue(HeaderNames.Expect, out var expect) &&
(expect.FirstOrDefault() ?? "").Equals("100-continue", StringComparison.OrdinalIgnoreCase))
{
Output.Write100ContinueAsync().GetAwaiter().GetResult();
}
}
public Task InitializeResponseAsync(int firstWriteByteCount)
{
var startingTask = FireOnStarting();
if (!startingTask.IsCompletedSuccessfully)
{
return InitializeResponseAwaited(startingTask, firstWriteByteCount);
}
VerifyInitializeState(firstWriteByteCount);
ProduceStart(appCompleted: false);
return Task.CompletedTask;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public async Task InitializeResponseAwaited(Task startingTask, int firstWriteByteCount)
{
await startingTask;
VerifyInitializeState(firstWriteByteCount);
ProduceStart(appCompleted: false);
}
private HttpResponseHeaders InitializeResponseFirstWrite(int firstWriteByteCount)
{
VerifyInitializeState(firstWriteByteCount);
var responseHeaders = CreateResponseHeaders(appCompleted: false);
// InitializeResponse can only be called if we are just about to Flush the headers
_requestProcessingStatus = RequestProcessingStatus.HeadersFlushed;
return responseHeaders;
}
private void ProduceStart(bool appCompleted)
{
if (HasResponseStarted)
{
return;
}
_isLeasedMemoryInvalid = true;
_requestProcessingStatus = RequestProcessingStatus.HeadersCommitted;
var responseHeaders = CreateResponseHeaders(appCompleted);
Output.WriteResponseHeaders(StatusCode, ReasonPhrase, responseHeaders, _autoChunk, appCompleted);
}
private void VerifyInitializeState(int firstWriteByteCount)
{
if (_applicationException != null)
{
ThrowResponseAbortedException();
}
VerifyAndUpdateWrite(firstWriteByteCount);
}
protected Task TryProduceInvalidRequestResponse()
{
// If _requestAborted is set, the connection has already been closed.
if (_requestRejectedException != null && !_connectionAborted)
{
return ProduceEnd();
}