/
Http2Connection.cs
2091 lines (1712 loc) · 87.7 KB
/
Http2Connection.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
// 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.Binary;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net.Http.Headers;
using System.Net.Http.HPack;
using System.Net.Security;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace System.Net.Http
{
internal sealed partial class Http2Connection : HttpConnectionBase
{
private readonly HttpConnectionPool _pool;
private readonly Stream _stream;
// NOTE: These are mutable structs; do not make these readonly.
private ArrayBuffer _incomingBuffer;
private ArrayBuffer _outgoingBuffer;
/// <summary>Reusable array used to get the values for each header being written to the wire.</summary>
[ThreadStatic]
private static string[]? t_headerValues;
private readonly HPackDecoder _hpackDecoder;
private readonly Dictionary<int, Http2Stream> _httpStreams;
private readonly CreditManager _connectionWindow;
private RttEstimator _rttEstimator;
private int _nextStream;
private bool _expectingSettingsAck;
private int _initialServerStreamWindowSize;
private int _pendingWindowUpdate;
private long _idleSinceTickCount;
private uint _maxConcurrentStreams;
private uint _streamsInUse;
private TaskCompletionSource<bool>? _availableStreamsWaiter;
private readonly Channel<WriteQueueEntry> _writeChannel;
private bool _lastPendingWriterShouldFlush;
// This flag indicates that the connection is shutting down and cannot accept new requests, because of one of the following conditions:
// (1) We received a GOAWAY frame from the server
// (2) We have exhaustead StreamIds (i.e. _nextStream == MaxStreamId)
// (3) A connection-level error occurred, in which case _abortException below is set.
private bool _shutdown;
private TaskCompletionSource? _shutdownWaiter;
// If this is set, the connection is aborting due to an IO failure (IOException) or a protocol violation (Http2ProtocolException).
// _shutdown above is true, and requests in flight have been (or are being) failed.
private Exception? _abortException;
// This means that the user (i.e. the connection pool) has disposed us and will not submit further requests.
// Requests currently in flight will continue to be processed.
// When all requests have completed, the connection will be torn down.
private bool _disposed;
private const int TelemetryStatus_Opened = 1;
private const int TelemetryStatus_Closed = 2;
private int _markedByTelemetryStatus;
private const int MaxStreamId = int.MaxValue;
// Temporary workaround for request burst handling on connection start.
private const int InitialMaxConcurrentStreams = 100;
private static readonly byte[] s_http2ConnectionPreface = Encoding.ASCII.GetBytes("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
#if DEBUG
// In debug builds, start with a very small buffer to induce buffer growing logic.
private const int InitialConnectionBufferSize = 4;
#else
private const int InitialConnectionBufferSize = 4096;
#endif
// The default initial window size for streams and connections according to the RFC:
// https://datatracker.ietf.org/doc/html/rfc7540#section-5.2.1
// Unlike HttpHandlerDefaults.DefaultInitialHttp2StreamWindowSize, this value should never be changed.
internal const int DefaultInitialWindowSize = 65535;
// We don't really care about limiting control flow at the connection level.
// We limit it per stream, and the user controls how many streams are created.
// So set the connection window size to a large value.
private const int ConnectionWindowSize = 64 * 1024 * 1024;
// We hold off on sending WINDOW_UPDATE until we hit the minimum threshold.
// This value is somewhat arbitrary; the intent is to ensure it is much smaller than
// the window size itself, or we risk stalling the server because it runs out of window space.
// If we want to further reduce the frequency of WINDOW_UPDATEs, it's probably better to
// increase the window size (and thus increase the threshold proportionally)
// rather than just increase the threshold.
private const int ConnectionWindowUpdateRatio = 8;
private const int ConnectionWindowThreshold = ConnectionWindowSize / ConnectionWindowUpdateRatio;
// When buffering outgoing writes, we will automatically buffer up to this number of bytes.
// Single writes that are larger than the buffer can cause the buffer to expand beyond
// this value, so this is not a hard maximum size.
private const int UnflushedOutgoingBufferSize = 32 * 1024;
// Channel options for creating _writeChannel
private static readonly UnboundedChannelOptions s_channelOptions = new UnboundedChannelOptions() { SingleReader = true };
internal enum KeepAliveState
{
None,
PingSent
}
private readonly long _keepAlivePingDelay;
private readonly long _keepAlivePingTimeout;
private readonly HttpKeepAlivePingPolicy _keepAlivePingPolicy;
private long _keepAlivePingPayload;
private long _nextPingRequestTimestamp;
private long _keepAlivePingTimeoutTimestamp;
private volatile KeepAliveState _keepAliveState;
public Http2Connection(HttpConnectionPool pool, Stream stream)
{
_pool = pool;
_stream = stream;
_incomingBuffer = new ArrayBuffer(InitialConnectionBufferSize);
_outgoingBuffer = new ArrayBuffer(InitialConnectionBufferSize);
_hpackDecoder = new HPackDecoder(maxHeadersLength: pool.Settings._maxResponseHeadersLength * 1024);
_httpStreams = new Dictionary<int, Http2Stream>();
_connectionWindow = new CreditManager(this, nameof(_connectionWindow), DefaultInitialWindowSize);
_rttEstimator = RttEstimator.Create();
_writeChannel = Channel.CreateUnbounded<WriteQueueEntry>(s_channelOptions);
_nextStream = 1;
_initialServerStreamWindowSize = DefaultInitialWindowSize;
_maxConcurrentStreams = InitialMaxConcurrentStreams;
_streamsInUse = 0;
_pendingWindowUpdate = 0;
_idleSinceTickCount = Environment.TickCount64;
_keepAlivePingDelay = TimeSpanToMs(_pool.Settings._keepAlivePingDelay);
_keepAlivePingTimeout = TimeSpanToMs(_pool.Settings._keepAlivePingTimeout);
_nextPingRequestTimestamp = Environment.TickCount64 + _keepAlivePingDelay;
_keepAlivePingPolicy = _pool.Settings._keepAlivePingPolicy;
if (HttpTelemetry.Log.IsEnabled())
{
HttpTelemetry.Log.Http20ConnectionEstablished();
_markedByTelemetryStatus = TelemetryStatus_Opened;
}
if (NetEventSource.Log.IsEnabled()) TraceConnection(_stream);
static long TimeSpanToMs(TimeSpan value) {
double milliseconds = value.TotalMilliseconds;
return (long)(milliseconds > int.MaxValue ? int.MaxValue : milliseconds);
}
}
~Http2Connection() => Dispose();
private object SyncObject => _httpStreams;
public async ValueTask SetupAsync()
{
try
{
_outgoingBuffer.EnsureAvailableSpace(s_http2ConnectionPreface.Length +
FrameHeader.Size + FrameHeader.SettingLength +
FrameHeader.Size + FrameHeader.WindowUpdateLength);
// Send connection preface
s_http2ConnectionPreface.AsSpan().CopyTo(_outgoingBuffer.AvailableSpan);
_outgoingBuffer.Commit(s_http2ConnectionPreface.Length);
// Send SETTINGS frame. Disable push promise & set initial window size.
FrameHeader.WriteTo(_outgoingBuffer.AvailableSpan, 2 * FrameHeader.SettingLength, FrameType.Settings, FrameFlags.None, streamId: 0);
_outgoingBuffer.Commit(FrameHeader.Size);
BinaryPrimitives.WriteUInt16BigEndian(_outgoingBuffer.AvailableSpan, (ushort)SettingId.EnablePush);
_outgoingBuffer.Commit(2);
BinaryPrimitives.WriteUInt32BigEndian(_outgoingBuffer.AvailableSpan, 0);
_outgoingBuffer.Commit(4);
BinaryPrimitives.WriteUInt16BigEndian(_outgoingBuffer.AvailableSpan, (ushort)SettingId.InitialWindowSize);
_outgoingBuffer.Commit(2);
BinaryPrimitives.WriteUInt32BigEndian(_outgoingBuffer.AvailableSpan, (uint)_pool.Settings._initialHttp2StreamWindowSize);
_outgoingBuffer.Commit(4);
// The connection-level window size can not be initialized by SETTINGS frames:
// https://datatracker.ietf.org/doc/html/rfc7540#section-6.9.2
// Send an initial connection-level WINDOW_UPDATE to setup the desired ConnectionWindowSize:
uint windowUpdateAmount = ConnectionWindowSize - DefaultInitialWindowSize;
if (NetEventSource.Log.IsEnabled()) Trace($"Initial connection-level WINDOW_UPDATE, windowUpdateAmount={windowUpdateAmount}");
FrameHeader.WriteTo(_outgoingBuffer.AvailableSpan, FrameHeader.WindowUpdateLength, FrameType.WindowUpdate, FrameFlags.None, streamId: 0);
_outgoingBuffer.Commit(FrameHeader.Size);
BinaryPrimitives.WriteUInt32BigEndian(_outgoingBuffer.AvailableSpan, windowUpdateAmount);
_outgoingBuffer.Commit(4);
await _stream.WriteAsync(_outgoingBuffer.ActiveMemory).ConfigureAwait(false);
_rttEstimator.OnInitialSettingsSent();
_outgoingBuffer.Discard(_outgoingBuffer.ActiveLength);
_expectingSettingsAck = true;
}
catch (Exception e)
{
Dispose();
throw new IOException(SR.net_http_http2_connection_not_established, e);
}
_ = ProcessIncomingFramesAsync();
_ = ProcessOutgoingFramesAsync();
}
// This will complete when the connection begins to shut down and cannot be used anymore, or if it is disposed.
public ValueTask WaitForShutdownAsync()
{
lock (SyncObject)
{
if (_disposed)
{
Debug.Fail("As currently used, we don't expect to call this after disposing and we don't handle the ODE");
throw new ObjectDisposedException(nameof(Http2Connection));
}
if (_shutdown)
{
Debug.Assert(_shutdownWaiter is null);
return default;
}
_shutdownWaiter ??= new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
return new ValueTask(_shutdownWaiter.Task);
}
}
private void Shutdown()
{
if (NetEventSource.Log.IsEnabled()) Trace($"{nameof(_shutdown)}={_shutdown}, {nameof(_abortException)}={_abortException}");
Debug.Assert(Monitor.IsEntered(SyncObject));
SignalAvailableStreamsWaiter(false);
SignalShutdownWaiter();
// Note _shutdown could already be set, but that's fine.
_shutdown = true;
}
private void SignalShutdownWaiter()
{
if (NetEventSource.Log.IsEnabled()) Trace($"{nameof(_shutdownWaiter)}?={_shutdownWaiter is not null}");
Debug.Assert(Monitor.IsEntered(SyncObject));
if (_shutdownWaiter is not null)
{
Debug.Assert(!_disposed);
Debug.Assert(!_shutdown);
_shutdownWaiter.SetResult();
_shutdownWaiter = null;
}
}
public bool TryReserveStream()
{
lock (SyncObject)
{
if (_disposed)
{
Debug.Fail("As currently used, we don't expect to call this after disposing and we don't handle the ODE");
throw new ObjectDisposedException(nameof(Http2Connection));
}
if (_shutdown)
{
return false;
}
if (_streamsInUse < _maxConcurrentStreams)
{
_streamsInUse++;
return true;
}
}
return false;
}
// Can be called by the HttpConnectionPool after TryReserveStream if the stream doesn't end up being used.
// Otherwise, will be called when the request is complete and stream is closed.
public void ReleaseStream()
{
lock (SyncObject)
{
if (NetEventSource.Log.IsEnabled()) Trace($"{nameof(_streamsInUse)}={_streamsInUse}");
Debug.Assert(_availableStreamsWaiter is null || _streamsInUse >= _maxConcurrentStreams);
_streamsInUse--;
Debug.Assert(_streamsInUse >= _httpStreams.Count);
if (_streamsInUse < _maxConcurrentStreams)
{
SignalAvailableStreamsWaiter(true);
}
if (_streamsInUse == 0)
{
_idleSinceTickCount = Environment.TickCount64;
if (_disposed)
{
FinalTeardown();
}
}
}
}
// Returns true to indicate at least one stream is available
// Returns false to indicate that the connection is shutting down and cannot be used anymore
public ValueTask<bool> WaitForAvailableStreamsAsync()
{
lock (SyncObject)
{
if (_disposed)
{
Debug.Fail("As currently used, we don't expect to call this after disposing and we don't handle the ODE");
throw new ObjectDisposedException(nameof(Http2Connection));
}
Debug.Assert(_availableStreamsWaiter is null, "As used currently, shouldn't already have a waiter");
if (_shutdown)
{
return ValueTask.FromResult(false);
}
if (_streamsInUse < _maxConcurrentStreams)
{
return ValueTask.FromResult(true);
}
// Need to wait for streams to become available.
_availableStreamsWaiter = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
return new ValueTask<bool>(_availableStreamsWaiter.Task);
}
}
private void SignalAvailableStreamsWaiter(bool result)
{
if (NetEventSource.Log.IsEnabled()) Trace($"{nameof(result)}={result}, {nameof(_availableStreamsWaiter)}?={_availableStreamsWaiter is not null}");
Debug.Assert(Monitor.IsEntered(SyncObject));
if (_availableStreamsWaiter is not null)
{
Debug.Assert(!_disposed);
Debug.Assert(!_shutdown);
_availableStreamsWaiter.SetResult(result);
_availableStreamsWaiter = null;
}
}
private async Task FlushOutgoingBytesAsync()
{
if (NetEventSource.Log.IsEnabled()) Trace($"{nameof(_outgoingBuffer.ActiveLength)}={_outgoingBuffer.ActiveLength}");
if (_outgoingBuffer.ActiveLength > 0)
{
try
{
await _stream.WriteAsync(_outgoingBuffer.ActiveMemory).ConfigureAwait(false);
}
catch (Exception e)
{
Abort(e);
}
_lastPendingWriterShouldFlush = false;
_outgoingBuffer.Discard(_outgoingBuffer.ActiveLength);
}
}
private async ValueTask<FrameHeader> ReadFrameAsync(bool initialFrame = false)
{
if (NetEventSource.Log.IsEnabled()) Trace($"{nameof(initialFrame)}={initialFrame}");
// Ensure we've read enough data for the frame header.
if (_incomingBuffer.ActiveLength < FrameHeader.Size)
{
_incomingBuffer.EnsureAvailableSpace(FrameHeader.Size - _incomingBuffer.ActiveLength);
do
{
int bytesRead = await _stream.ReadAsync(_incomingBuffer.AvailableMemory).ConfigureAwait(false);
_incomingBuffer.Commit(bytesRead);
if (bytesRead == 0)
{
if (_incomingBuffer.ActiveLength == 0)
{
ThrowMissingFrame();
}
else
{
ThrowPrematureEOF(FrameHeader.Size);
}
}
}
while (_incomingBuffer.ActiveLength < FrameHeader.Size);
}
// Parse the frame header from our read buffer and validate it.
FrameHeader frameHeader = FrameHeader.ReadFrom(_incomingBuffer.ActiveSpan);
if (frameHeader.PayloadLength > FrameHeader.MaxPayloadLength)
{
if (initialFrame && NetEventSource.Log.IsEnabled())
{
string response = Encoding.ASCII.GetString(_incomingBuffer.ActiveSpan.Slice(0, Math.Min(20, _incomingBuffer.ActiveLength)));
Trace($"HTTP/2 handshake failed. Server returned {response}");
}
_incomingBuffer.Discard(FrameHeader.Size);
ThrowProtocolError(initialFrame ? Http2ProtocolErrorCode.ProtocolError : Http2ProtocolErrorCode.FrameSizeError);
}
_incomingBuffer.Discard(FrameHeader.Size);
// Ensure we've read the frame contents into our buffer.
if (_incomingBuffer.ActiveLength < frameHeader.PayloadLength)
{
_incomingBuffer.EnsureAvailableSpace(frameHeader.PayloadLength - _incomingBuffer.ActiveLength);
do
{
int bytesRead = await _stream.ReadAsync(_incomingBuffer.AvailableMemory).ConfigureAwait(false);
_incomingBuffer.Commit(bytesRead);
if (bytesRead == 0) ThrowPrematureEOF(frameHeader.PayloadLength);
}
while (_incomingBuffer.ActiveLength < frameHeader.PayloadLength);
}
// Return the read frame header.
return frameHeader;
void ThrowPrematureEOF(int requiredBytes) =>
throw new IOException(SR.Format(SR.net_http_invalid_response_premature_eof_bytecount, requiredBytes - _incomingBuffer.ActiveLength));
void ThrowMissingFrame() =>
throw new IOException(SR.net_http_invalid_response_missing_frame);
}
private async Task ProcessIncomingFramesAsync()
{
try
{
FrameHeader frameHeader;
try
{
// Read the initial settings frame.
frameHeader = await ReadFrameAsync(initialFrame: true).ConfigureAwait(false);
if (frameHeader.Type != FrameType.Settings || frameHeader.AckFlag)
{
ThrowProtocolError();
}
if (NetEventSource.Log.IsEnabled()) Trace($"Frame 0: {frameHeader}.");
// Process the initial SETTINGS frame. This will send an ACK.
ProcessSettingsFrame(frameHeader, initialFrame: true);
}
catch (IOException e)
{
throw new IOException(SR.net_http_http2_connection_not_established, e);
}
// Keep processing frames as they arrive.
for (long frameNum = 1; ; frameNum++)
{
// We could just call ReadFrameAsync here, but we add this code
// to avoid another state machine allocation in the relatively common case where we
// currently don't have enough data buffered and issuing a read for the frame header
// completes asynchronously, but that read ends up also reading enough data to fulfill
// the entire frame's needs (not just the header).
if (_incomingBuffer.ActiveLength < FrameHeader.Size)
{
_incomingBuffer.EnsureAvailableSpace(FrameHeader.Size - _incomingBuffer.ActiveLength);
do
{
int bytesRead = await _stream.ReadAsync(_incomingBuffer.AvailableMemory).ConfigureAwait(false);
Debug.Assert(bytesRead >= 0);
_incomingBuffer.Commit(bytesRead);
if (bytesRead == 0)
{
// ReadFrameAsync below will detect that the frame is incomplete and throw the appropriate error.
break;
}
}
while (_incomingBuffer.ActiveLength < FrameHeader.Size);
}
// Read the frame.
frameHeader = await ReadFrameAsync().ConfigureAwait(false);
if (NetEventSource.Log.IsEnabled()) Trace($"Frame {frameNum}: {frameHeader}.");
RefreshPingTimestamp();
// Process the frame.
switch (frameHeader.Type)
{
case FrameType.Headers:
await ProcessHeadersFrame(frameHeader).ConfigureAwait(false);
break;
case FrameType.Data:
ProcessDataFrame(frameHeader);
break;
case FrameType.Settings:
ProcessSettingsFrame(frameHeader);
break;
case FrameType.Priority:
ProcessPriorityFrame(frameHeader);
break;
case FrameType.Ping:
ProcessPingFrame(frameHeader);
break;
case FrameType.WindowUpdate:
ProcessWindowUpdateFrame(frameHeader);
break;
case FrameType.RstStream:
ProcessRstStreamFrame(frameHeader);
break;
case FrameType.GoAway:
ProcessGoAwayFrame(frameHeader);
break;
case FrameType.AltSvc:
ProcessAltSvcFrame(frameHeader);
break;
case FrameType.PushPromise: // Should not happen, since we disable this in our initial SETTINGS
case FrameType.Continuation: // Should only be received while processing headers in ProcessHeadersFrame
default:
ThrowProtocolError();
break;
}
}
}
catch (Exception e)
{
if (NetEventSource.Log.IsEnabled()) Trace($"{nameof(ProcessIncomingFramesAsync)}: {e.Message}");
Abort(e);
}
}
// Note, this will return null for a streamId that's no longer in use.
// Callers must check for this and send a RST_STREAM or ignore as appropriate.
// If the streamId is invalid or the stream is idle, calling this function
// will result in a connection level error.
private Http2Stream? GetStream(int streamId)
{
if (streamId <= 0 || streamId >= _nextStream)
{
ThrowProtocolError();
}
lock (SyncObject)
{
if (!_httpStreams.TryGetValue(streamId, out Http2Stream? http2Stream))
{
return null;
}
return http2Stream;
}
}
private async ValueTask ProcessHeadersFrame(FrameHeader frameHeader)
{
if (NetEventSource.Log.IsEnabled()) Trace($"{frameHeader}");
Debug.Assert(frameHeader.Type == FrameType.Headers);
bool endStream = frameHeader.EndStreamFlag;
int streamId = frameHeader.StreamId;
Http2Stream? http2Stream = GetStream(streamId);
IHttpHeadersHandler headersHandler;
if (http2Stream != null)
{
http2Stream.OnHeadersStart();
_rttEstimator.OnDataOrHeadersReceived(this);
headersHandler = http2Stream;
}
else
{
// http2Stream will be null if this is a closed stream. We will still process the headers,
// to ensure the header decoding state is up-to-date, but we will discard the decoded headers.
headersHandler = NopHeadersHandler.Instance;
}
_hpackDecoder.Decode(
GetFrameData(_incomingBuffer.ActiveSpan.Slice(0, frameHeader.PayloadLength), frameHeader.PaddedFlag, frameHeader.PriorityFlag),
frameHeader.EndHeadersFlag,
headersHandler);
_incomingBuffer.Discard(frameHeader.PayloadLength);
while (!frameHeader.EndHeadersFlag)
{
frameHeader = await ReadFrameAsync().ConfigureAwait(false);
if (frameHeader.Type != FrameType.Continuation ||
frameHeader.StreamId != streamId)
{
ThrowProtocolError();
}
_hpackDecoder.Decode(
_incomingBuffer.ActiveSpan.Slice(0, frameHeader.PayloadLength),
frameHeader.EndHeadersFlag,
headersHandler);
_incomingBuffer.Discard(frameHeader.PayloadLength);
}
_hpackDecoder.CompleteDecode();
http2Stream?.OnHeadersComplete(endStream);
}
/// <summary>Nop implementation of <see cref="IHttpHeadersHandler"/> used by <see cref="ProcessHeadersFrame"/>.</summary>
private sealed class NopHeadersHandler : IHttpHeadersHandler
{
public static readonly NopHeadersHandler Instance = new NopHeadersHandler();
void IHttpHeadersHandler.OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) { }
void IHttpHeadersHandler.OnHeadersComplete(bool endStream) { }
void IHttpHeadersHandler.OnStaticIndexedHeader(int index) { }
void IHttpHeadersHandler.OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value) { }
}
private ReadOnlySpan<byte> GetFrameData(ReadOnlySpan<byte> frameData, bool hasPad, bool hasPriority)
{
if (hasPad)
{
if (frameData.Length == 0)
{
ThrowProtocolError();
}
int padLength = frameData[0];
frameData = frameData.Slice(1);
if (frameData.Length < padLength)
{
ThrowProtocolError();
}
frameData = frameData.Slice(0, frameData.Length - padLength);
}
if (hasPriority)
{
if (frameData.Length < FrameHeader.PriorityInfoLength)
{
ThrowProtocolError();
}
// We ignore priority info.
frameData = frameData.Slice(FrameHeader.PriorityInfoLength);
}
return frameData;
}
/// <summary>
/// Parses an ALTSVC frame, defined by RFC 7838 Section 4.
/// </summary>
/// <remarks>
/// The RFC states that any parse errors should result in ignoring the frame.
/// </remarks>
private void ProcessAltSvcFrame(FrameHeader frameHeader)
{
if (NetEventSource.Log.IsEnabled()) Trace($"{frameHeader}");
Debug.Assert(frameHeader.Type == FrameType.AltSvc);
ReadOnlySpan<byte> span = _incomingBuffer.ActiveSpan.Slice(0, frameHeader.PayloadLength);
if (BinaryPrimitives.TryReadUInt16BigEndian(span, out ushort originLength))
{
span = span.Slice(2);
// Check that this ALTSVC frame is valid for our pool's origin. ALTSVC frames can come in one of two ways:
// - On stream 0, the origin will be specified. HTTP/2 can service multiple origins per connection, and so the server can report origins other than what our pool is using.
// - Otherwise, the origin is implicitly defined by the request stream and must be of length 0.
if ((frameHeader.StreamId != 0 && originLength == 0) || (frameHeader.StreamId == 0 && span.Length >= originLength && span.Slice(0, originLength).SequenceEqual(_pool.Http2AltSvcOriginUri)))
{
span = span.Slice(originLength);
// The span now contains a string with the same format as Alt-Svc headers.
string altSvcHeaderValue = Encoding.ASCII.GetString(span);
_pool.HandleAltSvc(new[] { altSvcHeaderValue }, null);
}
}
_incomingBuffer.Discard(frameHeader.PayloadLength);
}
private void ProcessDataFrame(FrameHeader frameHeader)
{
Debug.Assert(frameHeader.Type == FrameType.Data);
Http2Stream? http2Stream = GetStream(frameHeader.StreamId);
// Note, http2Stream will be null if this is a closed stream.
// Just ignore the frame in this case.
ReadOnlySpan<byte> frameData = GetFrameData(_incomingBuffer.ActiveSpan.Slice(0, frameHeader.PayloadLength), hasPad: frameHeader.PaddedFlag, hasPriority: false);
if (http2Stream != null)
{
bool endStream = frameHeader.EndStreamFlag;
http2Stream.OnResponseData(frameData, endStream);
if (!endStream && frameData.Length > 0)
{
_rttEstimator.OnDataOrHeadersReceived(this);
}
}
if (frameData.Length > 0)
{
ExtendWindow(frameData.Length);
}
_incomingBuffer.Discard(frameHeader.PayloadLength);
}
private void ProcessSettingsFrame(FrameHeader frameHeader, bool initialFrame = false)
{
Debug.Assert(frameHeader.Type == FrameType.Settings);
if (frameHeader.StreamId != 0)
{
ThrowProtocolError();
}
if (frameHeader.AckFlag)
{
if (frameHeader.PayloadLength != 0)
{
ThrowProtocolError(Http2ProtocolErrorCode.FrameSizeError);
}
if (!_expectingSettingsAck)
{
ThrowProtocolError();
}
// We only send SETTINGS once initially, so we don't need to do anything in response to the ACK.
// Just remember that we received one and we won't be expecting any more.
_expectingSettingsAck = false;
_rttEstimator.OnInitialSettingsAckReceived(this);
}
else
{
if ((frameHeader.PayloadLength % 6) != 0)
{
ThrowProtocolError(Http2ProtocolErrorCode.FrameSizeError);
}
// Parse settings and process the ones we care about.
ReadOnlySpan<byte> settings = _incomingBuffer.ActiveSpan.Slice(0, frameHeader.PayloadLength);
bool maxConcurrentStreamsReceived = false;
while (settings.Length > 0)
{
Debug.Assert((settings.Length % 6) == 0);
ushort settingId = BinaryPrimitives.ReadUInt16BigEndian(settings);
settings = settings.Slice(2);
uint settingValue = BinaryPrimitives.ReadUInt32BigEndian(settings);
settings = settings.Slice(4);
switch ((SettingId)settingId)
{
case SettingId.MaxConcurrentStreams:
ChangeMaxConcurrentStreams(settingValue);
maxConcurrentStreamsReceived = true;
break;
case SettingId.InitialWindowSize:
if (settingValue > 0x7FFFFFFF)
{
ThrowProtocolError(Http2ProtocolErrorCode.FlowControlError);
}
ChangeInitialWindowSize((int)settingValue);
break;
case SettingId.MaxFrameSize:
if (settingValue < 16384 || settingValue > 16777215)
{
ThrowProtocolError();
}
// We don't actually store this value; we always send frames of the minimum size (16K).
break;
default:
// All others are ignored because we don't care about them.
// Note, per RFC, unknown settings IDs should be ignored.
break;
}
}
if (initialFrame && !maxConcurrentStreamsReceived)
{
// Set to 'infinite' because MaxConcurrentStreams was not set on the initial SETTINGS frame.
ChangeMaxConcurrentStreams(int.MaxValue);
}
_incomingBuffer.Discard(frameHeader.PayloadLength);
// Send acknowledgement
// Don't wait for completion, which could happen asynchronously.
LogExceptions(SendSettingsAckAsync());
}
}
private void ChangeMaxConcurrentStreams(uint newValue)
{
lock (SyncObject)
{
if (NetEventSource.Log.IsEnabled()) Trace($"{nameof(newValue)}={newValue}, {nameof(_streamsInUse)}={_streamsInUse}, {nameof(_availableStreamsWaiter)}?={_availableStreamsWaiter is not null}");
Debug.Assert(_availableStreamsWaiter is null || _streamsInUse >= _maxConcurrentStreams);
_maxConcurrentStreams = newValue;
if (_streamsInUse < _maxConcurrentStreams)
{
SignalAvailableStreamsWaiter(true);
}
}
}
private void ChangeInitialWindowSize(int newSize)
{
if (NetEventSource.Log.IsEnabled()) Trace($"{nameof(newSize)}={newSize}");
Debug.Assert(newSize >= 0);
lock (SyncObject)
{
int delta = newSize - _initialServerStreamWindowSize;
_initialServerStreamWindowSize = newSize;
// Adjust existing streams
foreach (KeyValuePair<int, Http2Stream> kvp in _httpStreams)
{
kvp.Value.OnWindowUpdate(delta);
}
}
}
private void ProcessPriorityFrame(FrameHeader frameHeader)
{
Debug.Assert(frameHeader.Type == FrameType.Priority);
if (frameHeader.StreamId == 0 || frameHeader.PayloadLength != FrameHeader.PriorityInfoLength)
{
ThrowProtocolError();
}
// Ignore priority info.
_incomingBuffer.Discard(frameHeader.PayloadLength);
}
private void ProcessPingFrame(FrameHeader frameHeader)
{
Debug.Assert(frameHeader.Type == FrameType.Ping);
if (frameHeader.StreamId != 0)
{
ThrowProtocolError();
}
if (frameHeader.PayloadLength != FrameHeader.PingLength)
{
ThrowProtocolError(Http2ProtocolErrorCode.FrameSizeError);
}
// We don't wait for SendPingAckAsync to complete before discarding
// the incoming buffer, so we need to take a copy of the data. Read
// it as a big-endian integer here to avoid allocating an array.
Debug.Assert(sizeof(long) == FrameHeader.PingLength);
ReadOnlySpan<byte> pingContent = _incomingBuffer.ActiveSpan.Slice(0, FrameHeader.PingLength);
long pingContentLong = BinaryPrimitives.ReadInt64BigEndian(pingContent);
if (NetEventSource.Log.IsEnabled()) Trace($"Received PING frame, content:{pingContentLong} ack: {frameHeader.AckFlag}");
if (frameHeader.AckFlag)
{
ProcessPingAck(pingContentLong);
}
else
{
LogExceptions(SendPingAsync(pingContentLong, isAck: true));
}
_incomingBuffer.Discard(frameHeader.PayloadLength);
}
private void ProcessWindowUpdateFrame(FrameHeader frameHeader)
{
Debug.Assert(frameHeader.Type == FrameType.WindowUpdate);
if (frameHeader.PayloadLength != FrameHeader.WindowUpdateLength)
{
ThrowProtocolError(Http2ProtocolErrorCode.FrameSizeError);
}
int amount = BinaryPrimitives.ReadInt32BigEndian(_incomingBuffer.ActiveSpan) & 0x7FFFFFFF;
if (NetEventSource.Log.IsEnabled()) Trace($"{frameHeader}. {nameof(amount)}={amount}");
Debug.Assert(amount >= 0);
if (amount == 0)
{
ThrowProtocolError();
}
_incomingBuffer.Discard(frameHeader.PayloadLength);
if (frameHeader.StreamId == 0)
{
_connectionWindow.AdjustCredit(amount);
}
else
{
Http2Stream? http2Stream = GetStream(frameHeader.StreamId);
if (http2Stream == null)
{
// Ignore invalid stream ID, as per RFC
return;
}
http2Stream.OnWindowUpdate(amount);
}
}
private void ProcessRstStreamFrame(FrameHeader frameHeader)
{
Debug.Assert(frameHeader.Type == FrameType.RstStream);
if (frameHeader.PayloadLength != FrameHeader.RstStreamLength)
{
ThrowProtocolError(Http2ProtocolErrorCode.FrameSizeError);
}
if (frameHeader.StreamId == 0)
{
ThrowProtocolError();
}
Http2Stream? http2Stream = GetStream(frameHeader.StreamId);
if (http2Stream == null)
{
// Ignore invalid stream ID, as per RFC
_incomingBuffer.Discard(frameHeader.PayloadLength);
return;
}
var protocolError = (Http2ProtocolErrorCode)BinaryPrimitives.ReadInt32BigEndian(_incomingBuffer.ActiveSpan);
if (NetEventSource.Log.IsEnabled()) Trace(frameHeader.StreamId, $"{nameof(protocolError)}={protocolError}");
_incomingBuffer.Discard(frameHeader.PayloadLength);
if (protocolError == Http2ProtocolErrorCode.RefusedStream)
{
http2Stream.OnReset(new Http2StreamException(protocolError), resetStreamErrorCode: protocolError, canRetry: true);
}
else
{