forked from microsoft/msquic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.c
7387 lines (6492 loc) · 248 KB
/
connection.c
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) Microsoft Corporation.
Licensed under the MIT License.
Abstract:
The connection is the topmost structure that all connection-specific state
and logic is derived from. Connections are only ever processed by one
thread at a time. Other threads may queue operations on the connection, but
the operations are only drained and processed serially, by a single thread;
though the thread that does the draining may change over time. All
events/triggers/API calls are processed via operations.
The connection drains operations in the QuicConnDrainOperations function.
The only requirement here is that this function is not called in parallel
on multiple threads. The function will drain up to QUIC_SETTINGS_INTERNAL's
MaxOperationsPerDrain operations per call, so as to not starve any other
work.
While most of the connection specific work is managed by other modules,
the following things are managed in this file:
Connection Lifetime - Initialization, handshake and state changes, shutdown,
closure and cleanup are located here.
Receive Path - The per-connection packet receive path is here. This is the
logic that happens after the global receive callback has processed the
packet initially and done the necessary processing to pass the packet to
the correct connection.
--*/
#include "precomp.h"
#ifdef QUIC_CLOG
#include "connection.c.clog.h"
#endif
typedef struct QUIC_RECEIVE_PROCESSING_STATE {
BOOLEAN ResetIdleTimeout;
BOOLEAN UpdatePartitionId;
uint16_t PartitionIndex;
} QUIC_RECEIVE_PROCESSING_STATE;
_IRQL_requires_max_(PASSIVE_LEVEL)
BOOLEAN
QuicConnApplyNewSettings(
_In_ QUIC_CONNECTION* Connection,
_In_ BOOLEAN OverWrite,
_In_ const QUIC_SETTINGS_INTERNAL* NewSettings
);
_IRQL_requires_max_(DISPATCH_LEVEL)
_Must_inspect_result_
_Success_(return == QUIC_STATUS_SUCCESS)
QUIC_STATUS
QuicConnAlloc(
_In_ QUIC_REGISTRATION* Registration,
_In_opt_ const CXPLAT_RECV_DATA* const Datagram,
_Outptr_ _At_(*NewConnection, __drv_allocatesMem(Mem))
QUIC_CONNECTION** NewConnection
)
{
BOOLEAN IsServer = Datagram != NULL;
uint32_t CurProcIndex = CxPlatProcCurrentNumber();
*NewConnection = NULL;
QUIC_STATUS Status;
//
// For client, the datapath partitioning info is not known yet, so just use
// the current processor for now. Once the connection receives a packet the
// partition can be updated accordingly.
//
uint16_t BasePartitionId =
IsServer ?
(Datagram->PartitionIndex % MsQuicLib.PartitionCount) :
CurProcIndex % MsQuicLib.PartitionCount;
uint16_t PartitionId = QuicPartitionIdCreate(BasePartitionId);
CXPLAT_DBG_ASSERT(BasePartitionId == QuicPartitionIdGetIndex(PartitionId));
QUIC_CONNECTION* Connection =
CxPlatPoolAlloc(&MsQuicLib.PerProc[CurProcIndex].ConnectionPool);
if (Connection == NULL) {
QuicTraceEvent(
AllocFailure,
"Allocation of '%s' failed. (%llu bytes)",
"connection",
sizeof(QUIC_CONNECTION));
return QUIC_STATUS_OUT_OF_MEMORY;
}
CxPlatZeroMemory(Connection, sizeof(QUIC_CONNECTION));
#if DEBUG
InterlockedIncrement(&MsQuicLib.ConnectionCount);
#endif
QuicPerfCounterIncrement(QUIC_PERF_COUNTER_CONN_CREATED);
QuicPerfCounterIncrement(QUIC_PERF_COUNTER_CONN_ACTIVE);
Connection->Stats.CorrelationId =
InterlockedIncrement64((int64_t*)&MsQuicLib.ConnectionCorrelationId) - 1;
QuicTraceEvent(
ConnCreated,
"[conn][%p] Created, IsServer=%hhu, CorrelationId=%llu",
Connection,
IsServer,
Connection->Stats.CorrelationId);
Connection->RefCount = 1;
#if DEBUG
Connection->RefTypeCount[QUIC_CONN_REF_HANDLE_OWNER] = 1;
#endif
Connection->PartitionID = PartitionId;
Connection->State.Allocated = TRUE;
Connection->State.ShareBinding = IsServer;
Connection->Stats.Timing.Start = CxPlatTimeUs64();
Connection->SourceCidLimit = QUIC_ACTIVE_CONNECTION_ID_LIMIT;
Connection->AckDelayExponent = QUIC_ACK_DELAY_EXPONENT;
Connection->PacketTolerance = QUIC_MIN_ACK_SEND_NUMBER;
Connection->PeerPacketTolerance = QUIC_MIN_ACK_SEND_NUMBER;
Connection->PeerTransportParams.AckDelayExponent = QUIC_TP_ACK_DELAY_EXPONENT_DEFAULT;
Connection->ReceiveQueueTail = &Connection->ReceiveQueue;
QuicSettingsCopy(&Connection->Settings, &MsQuicLib.Settings);
Connection->Settings.IsSetFlags = 0; // Just grab the global values, not IsSet flags.
CxPlatDispatchLockInitialize(&Connection->ReceiveQueueLock);
CxPlatListInitializeHead(&Connection->DestCids);
QuicStreamSetInitialize(&Connection->Streams);
QuicSendBufferInitialize(&Connection->SendBuffer);
QuicOperationQueueInitialize(&Connection->OperQ);
QuicSendInitialize(&Connection->Send, &Connection->Settings);
QuicCongestionControlInitialize(&Connection->CongestionControl, &Connection->Settings);
QuicLossDetectionInitialize(&Connection->LossDetection);
QuicDatagramInitialize(&Connection->Datagram);
QuicRangeInitialize(
QUIC_MAX_RANGE_DECODE_ACKS,
&Connection->DecodedAckRanges);
for (uint32_t i = 0; i < ARRAYSIZE(Connection->Packets); i++) {
Status =
QuicPacketSpaceInitialize(
Connection,
(QUIC_ENCRYPT_LEVEL)i,
&Connection->Packets[i]);
if (QUIC_FAILED(Status)) {
goto Error;
}
}
QUIC_PATH* Path = &Connection->Paths[0];
QuicPathInitialize(Connection, Path);
Path->IsActive = TRUE;
Connection->PathsCount = 1;
for (uint32_t i = 0; i < ARRAYSIZE(Connection->Timers); i++) {
Connection->Timers[i].Type = (QUIC_CONN_TIMER_TYPE)i;
Connection->Timers[i].ExpirationTime = UINT64_MAX;
}
if (IsServer) {
const CXPLAT_RECV_PACKET* Packet =
CxPlatDataPathRecvDataToRecvPacket(Datagram);
Connection->Type = QUIC_HANDLE_TYPE_CONNECTION_SERVER;
if (MsQuicLib.Settings.LoadBalancingMode == QUIC_LOAD_BALANCING_SERVER_ID_IP) {
CxPlatRandom(1, Connection->ServerID); // Randomize the first byte.
if (QuicAddrGetFamily(&Datagram->Route->LocalAddress) == QUIC_ADDRESS_FAMILY_INET) {
CxPlatCopyMemory(
Connection->ServerID + 1,
&Datagram->Route->LocalAddress.Ipv4.sin_addr,
4);
} else {
CxPlatCopyMemory(
Connection->ServerID + 1,
((uint8_t*)&Datagram->Route->LocalAddress.Ipv6.sin6_addr) + 12,
4);
}
}
Connection->Stats.QuicVersion = Packet->Invariant->LONG_HDR.Version;
QuicConnOnQuicVersionSet(Connection);
QuicCopyRouteInfo(&Path->Route, Datagram->Route);
Connection->State.LocalAddressSet = TRUE;
Connection->State.RemoteAddressSet = TRUE;
QuicTraceEvent(
ConnLocalAddrAdded,
"[conn][%p] New Local IP: %!ADDR!",
Connection,
CASTED_CLOG_BYTEARRAY(sizeof(Path->Route.LocalAddress), &Path->Route.LocalAddress));
QuicTraceEvent(
ConnRemoteAddrAdded,
"[conn][%p] New Remote IP: %!ADDR!",
Connection,
CASTED_CLOG_BYTEARRAY(sizeof(Path->Route.RemoteAddress), &Path->Route.RemoteAddress));
Path->DestCid =
QuicCidNewDestination(Packet->SourceCidLen, Packet->SourceCid);
if (Path->DestCid == NULL) {
Status = QUIC_STATUS_OUT_OF_MEMORY;
goto Error;
}
QUIC_CID_SET_PATH(Connection, Path->DestCid, Path);
Path->DestCid->CID.UsedLocally = TRUE;
CxPlatListInsertTail(&Connection->DestCids, &Path->DestCid->Link);
QuicTraceEvent(
ConnDestCidAdded,
"[conn][%p] (SeqNum=%llu) New Destination CID: %!CID!",
Connection,
Path->DestCid->CID.SequenceNumber,
CASTED_CLOG_BYTEARRAY(Path->DestCid->CID.Length, Path->DestCid->CID.Data));
QUIC_CID_HASH_ENTRY* SourceCid =
QuicCidNewSource(Connection, Packet->DestCidLen, Packet->DestCid);
if (SourceCid == NULL) {
Status = QUIC_STATUS_OUT_OF_MEMORY;
goto Error;
}
SourceCid->CID.IsInitial = TRUE;
SourceCid->CID.UsedByPeer = TRUE;
CxPlatListPushEntry(&Connection->SourceCids, &SourceCid->Link);
QuicTraceEvent(
ConnSourceCidAdded,
"[conn][%p] (SeqNum=%llu) New Source CID: %!CID!",
Connection,
SourceCid->CID.SequenceNumber,
CASTED_CLOG_BYTEARRAY(SourceCid->CID.Length, SourceCid->CID.Data));
//
// Server lazily finishes initialization in response to first operation.
//
} else {
Connection->Type = QUIC_HANDLE_TYPE_CONNECTION_CLIENT;
Connection->State.ExternalOwner = TRUE;
Path->IsPeerValidated = TRUE;
Path->Allowance = UINT32_MAX;
Path->DestCid = QuicCidNewRandomDestination();
if (Path->DestCid == NULL) {
Status = QUIC_STATUS_OUT_OF_MEMORY;
goto Error;
}
QUIC_CID_SET_PATH(Connection, Path->DestCid, Path);
Path->DestCid->CID.UsedLocally = TRUE;
Connection->DestCidCount++;
CxPlatListInsertTail(&Connection->DestCids, &Path->DestCid->Link);
QuicTraceEvent(
ConnDestCidAdded,
"[conn][%p] (SeqNum=%llu) New Destination CID: %!CID!",
Connection,
Path->DestCid->CID.SequenceNumber,
CASTED_CLOG_BYTEARRAY(Path->DestCid->CID.Length, Path->DestCid->CID.Data));
Connection->State.Initialized = TRUE;
QuicTraceEvent(
ConnInitializeComplete,
"[conn][%p] Initialize complete",
Connection);
}
QuicPathValidate(Path);
if (!QuicConnRegister(Connection, Registration)) {
Status = QUIC_STATUS_INVALID_STATE;
goto Error;
}
*NewConnection = Connection;
return QUIC_STATUS_SUCCESS;
Error:
Connection->State.HandleClosed = TRUE;
Connection->State.Uninitialized = TRUE;
for (uint32_t i = 0; i < ARRAYSIZE(Connection->Packets); i++) {
if (Connection->Packets[i] != NULL) {
QuicPacketSpaceUninitialize(Connection->Packets[i]);
Connection->Packets[i] = NULL;
}
}
if (Datagram != NULL && Connection->SourceCids.Next != NULL) {
CXPLAT_FREE(
CXPLAT_CONTAINING_RECORD(
Connection->SourceCids.Next,
QUIC_CID_HASH_ENTRY,
Link),
QUIC_POOL_CIDHASH);
Connection->SourceCids.Next = NULL;
}
while (!CxPlatListIsEmpty(&Connection->DestCids)) {
QUIC_CID_LIST_ENTRY *CID =
CXPLAT_CONTAINING_RECORD(
CxPlatListRemoveHead(&Connection->DestCids),
QUIC_CID_LIST_ENTRY,
Link);
CXPLAT_FREE(CID, QUIC_POOL_CIDLIST);
}
QuicConnRelease(Connection, QUIC_CONN_REF_HANDLE_OWNER);
return Status;
}
_IRQL_requires_max_(DISPATCH_LEVEL)
void
QuicConnFree(
_In_ __drv_freesMem(Mem) QUIC_CONNECTION* Connection
)
{
CXPLAT_FRE_ASSERT(!Connection->State.Freed);
CXPLAT_TEL_ASSERT(Connection->RefCount == 0);
if (Connection->State.ExternalOwner) {
CXPLAT_TEL_ASSERT(Connection->State.HandleClosed);
CXPLAT_TEL_ASSERT(Connection->State.Uninitialized);
CXPLAT_DBG_ASSERT(!Connection->State.Registered);
}
CXPLAT_TEL_ASSERT(Connection->SourceCids.Next == NULL);
CXPLAT_TEL_ASSERT(CxPlatListIsEmpty(&Connection->Streams.ClosedStreams));
QuicLossDetectionUninitialize(&Connection->LossDetection);
QuicSendUninitialize(&Connection->Send);
//
// Free up packet space if it wasn't freed by QuicConnUninitialize
//
for (uint32_t i = 0; i < ARRAYSIZE(Connection->Packets); i++) {
if (Connection->Packets[i] != NULL) {
QuicPacketSpaceUninitialize(Connection->Packets[i]);
Connection->Packets[i] = NULL;
}
}
#if DEBUG
while (!CxPlatListIsEmpty(&Connection->Streams.AllStreams)) {
QUIC_STREAM *Stream =
CXPLAT_CONTAINING_RECORD(
CxPlatListRemoveHead(&Connection->Streams.AllStreams),
QUIC_STREAM,
AllStreamsLink);
CXPLAT_DBG_ASSERTMSG(Stream != NULL, "Stream was leaked!");
}
#endif
while (!CxPlatListIsEmpty(&Connection->DestCids)) {
QUIC_CID_LIST_ENTRY *CID =
CXPLAT_CONTAINING_RECORD(
CxPlatListRemoveHead(&Connection->DestCids),
QUIC_CID_LIST_ENTRY,
Link);
CXPLAT_FREE(CID, QUIC_POOL_CIDLIST);
}
if (Connection->State.Registered) {
CxPlatDispatchLockAcquire(&Connection->Registration->ConnectionLock);
CxPlatListEntryRemove(&Connection->RegistrationLink);
CxPlatDispatchLockRelease(&Connection->Registration->ConnectionLock);
Connection->State.Registered = FALSE;
QuicTraceEvent(
ConnUnregistered,
"[conn][%p] Unregistered from %p",
Connection,
Connection->Registration);
}
if (Connection->Worker != NULL) {
QuicOperationQueueClear(Connection->Worker, &Connection->OperQ);
}
if (Connection->ReceiveQueue != NULL) {
CXPLAT_RECV_DATA* Datagram = Connection->ReceiveQueue;
do {
Datagram->QueuedOnConnection = FALSE;
} while ((Datagram = Datagram->Next) != NULL);
CxPlatRecvDataReturn(Connection->ReceiveQueue);
Connection->ReceiveQueue = NULL;
}
QUIC_PATH* Path = &Connection->Paths[0];
if (Path->Binding != NULL) {
QuicLibraryReleaseBinding(Path->Binding);
Path->Binding = NULL;
}
CxPlatDispatchLockUninitialize(&Connection->ReceiveQueueLock);
QuicOperationQueueUninitialize(&Connection->OperQ);
QuicStreamSetUninitialize(&Connection->Streams);
QuicSendBufferUninitialize(&Connection->SendBuffer);
QuicDatagramUninitialize(&Connection->Datagram);
if (Connection->Configuration != NULL) {
QuicConfigurationRelease(Connection->Configuration);
Connection->Configuration = NULL;
}
if (Connection->RemoteServerName != NULL) {
CXPLAT_FREE(Connection->RemoteServerName, QUIC_POOL_SERVERNAME);
}
if (Connection->OrigDestCID != NULL) {
CXPLAT_FREE(Connection->OrigDestCID, QUIC_POOL_CID);
}
if (Connection->HandshakeTP != NULL) {
QuicCryptoTlsCleanupTransportParameters(Connection->HandshakeTP);
CxPlatPoolFree(
&MsQuicLib.PerProc[CxPlatProcCurrentNumber()].TransportParamPool,
Connection->HandshakeTP);
Connection->HandshakeTP = NULL;
}
QuicCryptoTlsCleanupTransportParameters(&Connection->PeerTransportParams);
QuicSettingsCleanup(&Connection->Settings);
if (Connection->State.Started && !Connection->State.Connected) {
QuicPerfCounterIncrement(QUIC_PERF_COUNTER_CONN_HANDSHAKE_FAIL);
}
if (Connection->State.Connected) {
QuicPerfCounterDecrement(QUIC_PERF_COUNTER_CONN_CONNECTED);
}
if (Connection->Registration != NULL) {
CxPlatRundownRelease(&Connection->Registration->Rundown);
}
Connection->State.Freed = TRUE;
QuicTraceEvent(
ConnDestroyed,
"[conn][%p] Destroyed",
Connection);
CxPlatPoolFree(
&MsQuicLib.PerProc[CxPlatProcCurrentNumber()].ConnectionPool,
Connection);
#if DEBUG
InterlockedDecrement(&MsQuicLib.ConnectionCount);
#endif
QuicPerfCounterDecrement(QUIC_PERF_COUNTER_CONN_ACTIVE);
}
_IRQL_requires_max_(PASSIVE_LEVEL)
void
QuicConnShutdown(
_In_ QUIC_CONNECTION* Connection,
_In_ uint32_t Flags,
_In_ QUIC_VAR_INT ErrorCode,
_In_ BOOLEAN ShutdownFromRegistration
)
{
if (ShutdownFromRegistration &&
!Connection->State.Started &&
QuicConnIsClient(Connection)) {
return;
}
uint32_t CloseFlags = QUIC_CLOSE_APPLICATION;
if (Flags & QUIC_CONNECTION_SHUTDOWN_FLAG_SILENT ||
(!Connection->State.Started && QuicConnIsClient(Connection))) {
CloseFlags |= QUIC_CLOSE_SILENT;
}
QuicConnCloseLocally(Connection, CloseFlags, ErrorCode, NULL);
}
_IRQL_requires_max_(PASSIVE_LEVEL)
void
QuicConnUninitialize(
_In_ QUIC_CONNECTION* Connection
)
{
CXPLAT_TEL_ASSERT(Connection->State.HandleClosed);
CXPLAT_TEL_ASSERT(!Connection->State.Uninitialized);
Connection->State.Uninitialized = TRUE;
Connection->State.UpdateWorker = FALSE;
//
// Ensure we are shut down.
//
QuicConnShutdown(
Connection,
QUIC_CONNECTION_SHUTDOWN_FLAG_SILENT,
QUIC_ERROR_NO_ERROR,
FALSE);
//
// Remove all entries in the binding's lookup tables so we don't get any
// more packets queued.
//
if (Connection->Paths[0].Binding != NULL) {
QuicBindingRemoveConnection(Connection->Paths[0].Binding, Connection);
}
//
// Clean up the packet space first, to return any deferred received
// packets back to the binding.
//
for (uint32_t i = 0; i < ARRAYSIZE(Connection->Packets); i++) {
if (Connection->Packets[i] != NULL) {
QuicPacketSpaceUninitialize(Connection->Packets[i]);
Connection->Packets[i] = NULL;
}
}
//
// Clean up the rest of the internal state.
//
QuicRangeUninitialize(&Connection->DecodedAckRanges);
QuicCryptoUninitialize(&Connection->Crypto);
QuicTimerWheelRemoveConnection(&Connection->Worker->TimerWheel, Connection);
QuicOperationQueueClear(Connection->Worker, &Connection->OperQ);
if (Connection->CloseReasonPhrase != NULL) {
CXPLAT_FREE(Connection->CloseReasonPhrase, QUIC_POOL_CLOSE_REASON);
}
}
_IRQL_requires_max_(DISPATCH_LEVEL)
void
QuicConnCloseHandle(
_In_ QUIC_CONNECTION* Connection
)
{
CXPLAT_TEL_ASSERT(!Connection->State.HandleClosed);
Connection->State.HandleClosed = TRUE;
QuicConnCloseLocally(
Connection,
QUIC_CLOSE_SILENT | QUIC_CLOSE_QUIC_STATUS,
(uint64_t)QUIC_STATUS_ABORTED,
NULL);
if (Connection->State.SendShutdownCompleteNotif) {
QuicConnOnShutdownComplete(Connection);
}
Connection->ClientCallbackHandler = NULL;
if (Connection->State.Registered) {
CxPlatDispatchLockAcquire(&Connection->Registration->ConnectionLock);
CxPlatListEntryRemove(&Connection->RegistrationLink);
CxPlatDispatchLockRelease(&Connection->Registration->ConnectionLock);
Connection->State.Registered = FALSE;
QuicTraceEvent(
ConnUnregistered,
"[conn][%p] Unregistered from %p",
Connection,
Connection->Registration);
}
QuicTraceEvent(
ConnHandleClosed,
"[conn][%p] Handle closed",
Connection);
}
_IRQL_requires_max_(DISPATCH_LEVEL)
_Must_inspect_result_
BOOLEAN
QuicConnRegister(
_Inout_ QUIC_CONNECTION* Connection,
_Inout_ QUIC_REGISTRATION* Registration
)
{
if (Connection->Registration != NULL) {
CxPlatDispatchLockAcquire(&Connection->Registration->ConnectionLock);
CxPlatListEntryRemove(&Connection->RegistrationLink);
CxPlatDispatchLockRelease(&Connection->Registration->ConnectionLock);
CxPlatRundownRelease(&Connection->Registration->Rundown);
QuicTraceEvent(
ConnUnregistered,
"[conn][%p] Unregistered from %p",
Connection,
Connection->Registration);
}
BOOLEAN Success = CxPlatRundownAcquire(&Registration->Rundown);
if (!Success) {
return FALSE;
}
Connection->State.Registered = TRUE;
Connection->Registration = Registration;
#ifdef CxPlatVerifierEnabledByAddr
Connection->State.IsVerifying = Registration->IsVerifying;
#endif
BOOLEAN RegistrationShuttingDown;
CxPlatDispatchLockAcquire(&Registration->ConnectionLock);
RegistrationShuttingDown = Registration->ShuttingDown;
if (!RegistrationShuttingDown) {
CxPlatListInsertTail(&Registration->Connections, &Connection->RegistrationLink);
}
CxPlatDispatchLockRelease(&Registration->ConnectionLock);
if (RegistrationShuttingDown) {
Connection->State.Registered = FALSE;
Connection->Registration = NULL;
CxPlatRundownRelease(&Registration->Rundown);
} else {
QuicTraceEvent(
ConnRegistered,
"[conn][%p] Registered with %p",
Connection,
Registration);
}
return !RegistrationShuttingDown;
}
_IRQL_requires_max_(DISPATCH_LEVEL)
void
QuicConnQueueTraceRundown(
_In_ QUIC_CONNECTION* Connection
)
{
QUIC_OPERATION* Oper;
if ((Oper = QuicOperationAlloc(Connection->Worker, QUIC_OPER_TYPE_TRACE_RUNDOWN)) != NULL) {
QuicConnQueueOper(Connection, Oper);
} else {
QuicTraceEvent(
AllocFailure,
"Allocation of '%s' failed. (%llu bytes)",
"trace rundown operation",
0);
}
}
_IRQL_requires_max_(PASSIVE_LEVEL)
void
QuicConnTraceRundownOper(
_In_ QUIC_CONNECTION* Connection
)
{
QuicTraceEvent(
ConnRundown,
"[conn][%p] Rundown, IsServer=%hu, CorrelationId=%llu",
Connection,
QuicConnIsServer(Connection),
Connection->Stats.CorrelationId);
QuicTraceEvent(
ConnAssignWorker,
"[conn][%p] Assigned worker: %p",
Connection,
Connection->Worker);
CXPLAT_DBG_ASSERT(Connection->Registration);
QuicTraceEvent(
ConnRegistered,
"[conn][%p] Registered with %p",
Connection,
Connection->Registration);
if (Connection->Stats.QuicVersion != 0) {
QuicTraceEvent(
ConnVersionSet,
"[conn][%p] QUIC Version: %u",
Connection,
Connection->Stats.QuicVersion);
}
if (Connection->State.Started) {
for (uint8_t i = 0; i < Connection->PathsCount; ++i) {
if (Connection->State.LocalAddressSet || i != 0) {
QuicTraceEvent(
ConnLocalAddrAdded,
"[conn][%p] New Local IP: %!ADDR!",
Connection,
CASTED_CLOG_BYTEARRAY(sizeof(Connection->Paths[i].Route.LocalAddress), &Connection->Paths[i].Route.LocalAddress));
}
if (Connection->State.RemoteAddressSet || i != 0) {
QuicTraceEvent(
ConnRemoteAddrAdded,
"[conn][%p] New Remote IP: %!ADDR!",
Connection,
CASTED_CLOG_BYTEARRAY(sizeof(Connection->Paths[i].Route.RemoteAddress), &Connection->Paths[i].Route.RemoteAddress));
}
}
for (CXPLAT_SLIST_ENTRY* Entry = Connection->SourceCids.Next;
Entry != NULL;
Entry = Entry->Next) {
const QUIC_CID_HASH_ENTRY* SourceCid =
CXPLAT_CONTAINING_RECORD(
Entry,
QUIC_CID_HASH_ENTRY,
Link);
UNREFERENCED_PARAMETER(SourceCid);
QuicTraceEvent(
ConnSourceCidAdded,
"[conn][%p] (SeqNum=%llu) New Source CID: %!CID!",
Connection,
SourceCid->CID.SequenceNumber,
CASTED_CLOG_BYTEARRAY(SourceCid->CID.Length, SourceCid->CID.Data));
}
for (CXPLAT_LIST_ENTRY* Entry = Connection->DestCids.Flink;
Entry != &Connection->DestCids;
Entry = Entry->Flink) {
const QUIC_CID_LIST_ENTRY* DestCid =
CXPLAT_CONTAINING_RECORD(
Entry,
QUIC_CID_LIST_ENTRY,
Link);
UNREFERENCED_PARAMETER(DestCid);
QuicTraceEvent(
ConnDestCidAdded,
"[conn][%p] (SeqNum=%llu) New Destination CID: %!CID!",
Connection,
DestCid->CID.SequenceNumber,
CASTED_CLOG_BYTEARRAY(DestCid->CID.Length, DestCid->CID.Data));
}
}
if (Connection->State.Connected) {
QuicTraceEvent(
ConnHandshakeComplete,
"[conn][%p] Handshake complete",
Connection);
}
if (Connection->State.HandleClosed) {
QuicTraceEvent(
ConnHandleClosed,
"[conn][%p] Handle closed",
Connection);
}
if (Connection->State.Started) {
QuicConnLogStatistics(Connection);
}
QuicStreamSetTraceRundown(&Connection->Streams);
}
_IRQL_requires_max_(PASSIVE_LEVEL)
QUIC_STATUS
QuicConnIndicateEvent(
_In_ QUIC_CONNECTION* Connection,
_Inout_ QUIC_CONNECTION_EVENT* Event
)
{
QUIC_STATUS Status;
if (Connection->ClientCallbackHandler != NULL) {
//
// MsQuic shouldn't indicate reentrancy to the app when at all possible.
// The general exception to this rule is when the connection is being
// closed because the API MUST block until all work is completed, so we
// have to execute the event callbacks inline.
//
CXPLAT_DBG_ASSERT(
!Connection->State.InlineApiExecution ||
Connection->State.HandleClosed);
Status =
Connection->ClientCallbackHandler(
(HQUIC)Connection,
Connection->ClientContext,
Event);
} else {
QUIC_CONN_VERIFY(
Connection,
Connection->State.HandleClosed ||
Connection->State.HandleShutdown ||
!Connection->State.ExternalOwner);
Status = QUIC_STATUS_INVALID_STATE;
QuicTraceLogConnWarning(
ApiEventNoHandler,
Connection,
"Event silently discarded (no handler).");
}
return Status;
}
_IRQL_requires_max_(DISPATCH_LEVEL)
void
QuicConnQueueOper(
_In_ QUIC_CONNECTION* Connection,
_In_ QUIC_OPERATION* Oper
)
{
#if DEBUG
if (!Connection->State.Initialized) {
CXPLAT_DBG_ASSERT(QuicConnIsServer(Connection));
CXPLAT_DBG_ASSERT(Connection->SourceCids.Next != NULL || CxPlatIsRandomMemoryFailureEnabled());
}
#endif
if (QuicOperationEnqueue(&Connection->OperQ, Oper)) {
//
// The connection needs to be queued on the worker because this was the
// first operation in our OperQ.
//
QuicWorkerQueueConnection(Connection->Worker, Connection);
}
}
_IRQL_requires_max_(DISPATCH_LEVEL)
void
QuicConnQueueHighestPriorityOper(
_In_ QUIC_CONNECTION* Connection,
_In_ QUIC_OPERATION* Oper
)
{
if (QuicOperationEnqueueFront(&Connection->OperQ, Oper)) {
//
// The connection needs to be queued on the worker because this was the
// first operation in our OperQ.
//
QuicWorkerQueueConnection(Connection->Worker, Connection);
}
}
_IRQL_requires_max_(PASSIVE_LEVEL)
void
QuicConnUpdateRtt(
_In_ QUIC_CONNECTION* Connection,
_In_ QUIC_PATH* Path,
_In_ uint32_t LatestRtt
)
{
BOOLEAN RttUpdated;
UNREFERENCED_PARAMETER(Connection);
if (LatestRtt == 0) {
//
// RTT cannot be zero or several loss recovery algorithms break down.
//
LatestRtt = 1;
}
Path->LatestRttSample = LatestRtt;
if (LatestRtt < Path->MinRtt) {
Path->MinRtt = LatestRtt;
}
if (LatestRtt > Path->MaxRtt) {
Path->MaxRtt = LatestRtt;
}
if (!Path->GotFirstRttSample) {
Path->GotFirstRttSample = TRUE;
Path->SmoothedRtt = LatestRtt;
Path->RttVariance = LatestRtt / 2;
RttUpdated = TRUE;
} else {
uint32_t PrevRtt = Path->SmoothedRtt;
if (Path->SmoothedRtt > LatestRtt) {
Path->RttVariance = (3 * Path->RttVariance + Path->SmoothedRtt - LatestRtt) / 4;
} else {
Path->RttVariance = (3 * Path->RttVariance + LatestRtt - Path->SmoothedRtt) / 4;
}
Path->SmoothedRtt = (7 * Path->SmoothedRtt + LatestRtt) / 8;
RttUpdated = PrevRtt != Path->SmoothedRtt;
}
if (RttUpdated) {
CXPLAT_DBG_ASSERT(Path->SmoothedRtt != 0);
QuicTraceLogConnVerbose(
RttUpdatedMsg,
Connection,
"Updated Rtt=%u.%03u ms, Var=%u.%03u",
Path->SmoothedRtt / 1000, Path->SmoothedRtt % 1000,
Path->RttVariance / 1000, Path->RttVariance % 1000);
}
}
_IRQL_requires_max_(PASSIVE_LEVEL)
QUIC_CID_HASH_ENTRY*
QuicConnGenerateNewSourceCid(
_In_ QUIC_CONNECTION* Connection,
_In_ BOOLEAN IsInitial
)
{
uint8_t TryCount = 0;
QUIC_CID_HASH_ENTRY* SourceCid;
if (!Connection->State.ShareBinding) {
//
// We aren't sharing the binding, therefore aren't actually using a CID.
// No need to generate a new one.
//
return NULL;
}
//
// Keep randomly generating new source CIDs until we find one that doesn't
// collide with an existing one.
//
do {
SourceCid =
QuicCidNewRandomSource(
Connection,
Connection->ServerID,
Connection->PartitionID,
Connection->CibirId[0],
Connection->CibirId+2);
if (SourceCid == NULL) {
QuicTraceEvent(
AllocFailure,
"Allocation of '%s' failed. (%llu bytes)",
"new Src CID",
sizeof(QUIC_CID_HASH_ENTRY) + MsQuicLib.CidTotalLength);
QuicConnFatalError(Connection, QUIC_STATUS_INTERNAL_ERROR, NULL);
return NULL;
}
if (!QuicBindingAddSourceConnectionID(Connection->Paths[0].Binding, SourceCid)) {
CXPLAT_FREE(SourceCid, QUIC_POOL_CIDHASH);
SourceCid = NULL;
if (++TryCount > QUIC_CID_MAX_COLLISION_RETRY) {
QuicTraceEvent(
ConnError,
"[conn][%p] ERROR, %s.",
Connection,
"Too many CID collisions");
QuicConnFatalError(Connection, QUIC_STATUS_INTERNAL_ERROR, NULL);
return NULL;
}
QuicTraceLogConnVerbose(
NewSrcCidNameCollision,
Connection,
"CID collision, trying again");
}
} while (SourceCid == NULL);
QuicTraceEvent(
ConnSourceCidAdded,
"[conn][%p] (SeqNum=%llu) New Source CID: %!CID!",
Connection,
SourceCid->CID.SequenceNumber,
CASTED_CLOG_BYTEARRAY(SourceCid->CID.Length, SourceCid->CID.Data));
SourceCid->CID.SequenceNumber = Connection->NextSourceCidSequenceNumber++;
if (SourceCid->CID.SequenceNumber > 0) {
SourceCid->CID.NeedsToSend = TRUE;
QuicSendSetSendFlag(&Connection->Send, QUIC_CONN_SEND_FLAG_NEW_CONNECTION_ID);
}
if (IsInitial) {
SourceCid->CID.IsInitial = TRUE;
CxPlatListPushEntry(&Connection->SourceCids, &SourceCid->Link);
} else {
CXPLAT_SLIST_ENTRY** Tail = &Connection->SourceCids.Next;
while (*Tail != NULL) {
Tail = &(*Tail)->Next;
}
*Tail = &SourceCid->Link;
SourceCid->Link.Next = NULL;
}
return SourceCid;
}
uint8_t
QuicConnSourceCidsCount(
_In_ const QUIC_CONNECTION* Connection
)
{
uint8_t Count = 0;
const CXPLAT_SLIST_ENTRY* Entry = Connection->SourceCids.Next;
while (Entry != NULL) {
++Count;
Entry = Entry->Next;
}
return Count;
}
//
// This generates new source CIDs for the peer to use to talk to us. If
// indicated, it invalidates all the existing ones, sets a a new retire prior to
// sequence number to send out and generates replacement CIDs.
//
_IRQL_requires_max_(PASSIVE_LEVEL)
void
QuicConnGenerateNewSourceCids(
_In_ QUIC_CONNECTION* Connection,
_In_ BOOLEAN ReplaceExistingCids
)
{
if (!Connection->State.ShareBinding) {
//
// Can't generate any new CIDs, so this is a no-op.
//
return;
}
//
// If we're replacing existing ones, then generate all new CIDs (up to the
// limit). Otherwise, just generate whatever number we need to hit the
// limit.
//
uint8_t NewCidCount;
if (ReplaceExistingCids) {
NewCidCount = Connection->SourceCidLimit;
CXPLAT_SLIST_ENTRY* Entry = Connection->SourceCids.Next;
while (Entry != NULL) {
QUIC_CID_HASH_ENTRY* SourceCid =
CXPLAT_CONTAINING_RECORD(Entry, QUIC_CID_HASH_ENTRY, Link);
SourceCid->CID.Retired = TRUE;
Entry = Entry->Next;
}
} else {
uint8_t CurrentCidCount = QuicConnSourceCidsCount(Connection);
CXPLAT_DBG_ASSERT(CurrentCidCount <= Connection->SourceCidLimit);
if (CurrentCidCount < Connection->SourceCidLimit) {
NewCidCount = Connection->SourceCidLimit - CurrentCidCount;
} else {
NewCidCount = 0;
}
}
for (uint8_t i = 0; i < NewCidCount; ++i) {
if (QuicConnGenerateNewSourceCid(Connection, FALSE) == NULL) {
break;
}
}
}
_IRQL_requires_max_(PASSIVE_LEVEL)
QUIC_CID_LIST_ENTRY*
QuicConnGetUnusedDestCid(
_In_ const QUIC_CONNECTION* Connection
)
{
for (CXPLAT_LIST_ENTRY* Entry = Connection->DestCids.Flink;