-
Notifications
You must be signed in to change notification settings - Fork 662
Expand file tree
/
Copy pathspinquic.cpp
More file actions
1818 lines (1667 loc) · 64.9 KB
/
spinquic.cpp
File metadata and controls
1818 lines (1667 loc) · 64.9 KB
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.
--*/
#include <time.h>
#include <stdio.h>
#include <vector>
#include <map>
#include <mutex>
#include <algorithm>
#define QUIC_TEST_APIS 1 // Needed for self signed cert API
#define QUIC_API_ENABLE_INSECURE_FEATURES 1 // Needed for disabling 1-RTT encryption
#define QUIC_API_ENABLE_PREVIEW_FEATURES // Needed for VN
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "msquichelper.h"
#define ASSERT_ON_FAILURE(x) \
do { \
QUIC_STATUS _STATUS; \
CXPLAT_FRE_ASSERT(QUIC_SUCCEEDED((_STATUS = x))); \
} while (0)
#define ASSERT_ON_NOT(x) CXPLAT_FRE_ASSERT(x)
QUIC_GLOBAL_EXECUTION_CONFIG* ExecConfig = nullptr;
uint32_t ExecConfigSize = 0;
class FuzzingData {
const uint8_t* data;
size_t size;
std::vector<size_t> EachSize;
std::mutex mux;
// TODO: support bit level pointers
std::vector<size_t> Ptrs;
std::vector<size_t> NumIterated;
bool Cyclic;
bool CheckBoundary(uint16_t ThreadId, size_t Adding) {
// TODO: efficient cyclic access
if (EachSize[ThreadId] < Ptrs[ThreadId] + Adding) {
if (!Cyclic) {
return false;
}
Ptrs[ThreadId] = 0;
NumIterated[ThreadId]++;
}
return true;
}
public:
// 128 for main data, 20 for callback's issue workaround
static const size_t MinDataSize = 148;
static const size_t UtilityDataSize = 20;
// hard code for determinisity
static const uint16_t NumSpinThread = 2;
FuzzingData() : data(nullptr), size(0), Ptrs({}), NumIterated({}), Cyclic(true) {}
FuzzingData(const uint8_t* data, size_t size) : data(data), size(size - UtilityDataSize), Ptrs({}), NumIterated({}), Cyclic(true) {}
bool Initialize() {
// TODO: support non divisible size
if (size % (size_t)NumSpinThread != 0 || size < (size_t)NumSpinThread * 8) {
return false;
}
EachSize.resize(NumSpinThread + 1);
std::fill(EachSize.begin(), EachSize.end(), size / (size_t)NumSpinThread);
EachSize.back() = UtilityDataSize;
Ptrs.resize(NumSpinThread + 1);
std::fill(Ptrs.begin(), Ptrs.end(), 0);
NumIterated.resize(NumSpinThread + 1);
std::fill(NumIterated.begin(), NumIterated.end(), 0);
return true;
}
bool TryGetByte(uint8_t* Val, uint16_t ThreadId = 0) {
if (!CheckBoundary(ThreadId, 1)) {
return false;
}
*Val = data[Ptrs[ThreadId]++ + EachSize[ThreadId] * ThreadId];
return true;
}
bool TryGetBool(bool* Flag, uint16_t ThreadId = 0) {
uint8_t Val = 0;
if (TryGetByte(&Val, ThreadId)) {
*Flag = (bool)(Val & 0b1);
return true;
}
return false;
}
template<typename T>
bool TryGetRandom(T UpperBound, T* Val, uint16_t ThreadId = 0) {
if (ThreadId == NumSpinThread) {
// utility area access from Connection/Stream callbacks
mux.lock();
}
int type_size = sizeof(T);
if (!CheckBoundary(ThreadId, type_size)) {
return false;
}
memcpy(Val, &data[Ptrs[ThreadId]] + EachSize[ThreadId] * ThreadId, type_size);
*Val = (T)(*Val % UpperBound);
Ptrs[ThreadId] += type_size;
if (ThreadId == NumSpinThread) {
mux.unlock();
}
return true;
}
size_t GetIterateCount(uint16_t ThreadId) {
return NumIterated[ThreadId];
}
};
static FuzzingData* FuzzData = nullptr;
template<typename T>
T GetRandom(T UpperBound, uint16_t ThreadID = UINT16_MAX) {
if (!FuzzData || ThreadID == UINT16_MAX) {
return (T)(rand() % (int)UpperBound);
}
uint64_t out = 0;
if ((uint64_t)UpperBound <= 0xff) {
(void)FuzzData->TryGetRandom((uint8_t)UpperBound, (uint8_t*)&out, ThreadID);
} else if ((uint64_t)UpperBound <= 0xffff) {
(void)FuzzData->TryGetRandom((uint16_t)UpperBound, (uint16_t*)&out, ThreadID);
} else if ((uint64_t)UpperBound <= 0xffffffff) {
(void)FuzzData->TryGetRandom((uint32_t)UpperBound, (uint32_t*)&out, ThreadID);
} else {
(void)FuzzData->TryGetRandom((uint64_t)UpperBound, &out, ThreadID);
}
return (T)out;
}
#define GetRandom(UpperBound) GetRandom(UpperBound, ThreadID)
template<typename T>
T& GetRandomFromVector(std::vector<T> &vec, uint16_t ThreadID) {
return vec.at(GetRandom(vec.size()));
}
#define GetRandomFromVector(Vec) GetRandomFromVector(Vec, ThreadID)
template<typename T>
class LockableVector : public std::vector<T>, public std::mutex {
uint16_t ThreadID = UINT16_MAX;
public:
T TryGetRandom(bool Erase = false) {
std::lock_guard<std::mutex> Lock(*this);
if (this->size() > 0) {
auto idx = GetRandom(this->size());
auto obj = this->at(idx);
if (Erase) {
this->erase(this->begin() + idx);
}
return obj;
}
return nullptr;
}
void SetThreadID(uint16_t threadID) {
ThreadID = threadID;
}
};
//
// The amount of extra time (in milliseconds) to give the watchdog before
// actually firing.
//
#define WATCHDOG_WIGGLE_ROOM 10000
class SpinQuicWatchdog {
CXPLAT_THREAD WatchdogThread;
CXPLAT_EVENT ShutdownEvent;
uint32_t TimeoutMs;
CXPLAT_THREAD_ID OriginThread;
static
CXPLAT_THREAD_CALLBACK(WatchdogThreadCallback, Context) {
auto This = (SpinQuicWatchdog*)Context;
if (!CxPlatEventWaitWithTimeout(This->ShutdownEvent, This->TimeoutMs)) {
printf("Watchdog timeout fired while waiting on thread 0x%x!\n", (int)This->OriginThread);
CXPLAT_FRE_ASSERTMSG(FALSE, "Watchdog timeout fired!");
}
CXPLAT_THREAD_RETURN(0);
}
public:
SpinQuicWatchdog(uint32_t WatchdogTimeoutMs) :
TimeoutMs(WatchdogTimeoutMs), OriginThread(CxPlatCurThreadID()) {
CxPlatEventInitialize(&ShutdownEvent, TRUE, FALSE);
CXPLAT_THREAD_CONFIG Config = { 0 };
Config.Name = "spin_watchdog";
Config.Callback = WatchdogThreadCallback;
Config.Context = this;
ASSERT_ON_FAILURE(CxPlatThreadCreate(&Config, &WatchdogThread));
}
~SpinQuicWatchdog() {
CxPlatEventSet(ShutdownEvent);
CxPlatThreadWait(&WatchdogThread);
CxPlatThreadDelete(&WatchdogThread);
CxPlatEventUninitialize(ShutdownEvent);
}
};
static QUIC_API_TABLE MsQuic;
// This locks MsQuicOpen2 in RunThread when statically linked with libmsquic
CXPLAT_LOCK RunThreadLock;
const uint32_t MaxBufferSizes[] = { 0, 1, 2, 32, 50, 256, 500, 1000, 1024, 1400, 5000, 10000, 64000, 10000000 };
static const size_t BufferCount = ARRAYSIZE(MaxBufferSizes);
struct SpinQuicGlobals {
uint64_t StartTimeMs;
const QUIC_API_TABLE* MsQuic {nullptr};
HQUIC Registration {nullptr};
HQUIC ServerConfiguration {nullptr};
std::vector<HQUIC> ClientConfigurations;
QUIC_BUFFER* Alpns {nullptr};
uint32_t AlpnCount {0};
const size_t SendBufferSize { MaxBufferSizes[BufferCount - 1] + UINT8_MAX };
std::vector<uint8_t> SendBuffer;
SpinQuicGlobals() : SendBuffer(SendBufferSize) {
for (size_t i = 0; i < SendBuffer.size(); i++) {
SendBuffer[i] = (uint8_t)i;
}
}
~SpinQuicGlobals() {
while (ClientConfigurations.size() > 0) {
auto Configuration = ClientConfigurations.back();
ClientConfigurations.pop_back();
MsQuic->ConfigurationClose(Configuration);
}
if (Alpns) {
for (uint32_t j = 0; j < AlpnCount; j++) {
free(Alpns[j].Buffer);
}
free(Alpns);
}
if (Registration) {
if (rand() % 2 == 0) {
CXPLAT_EVENT CloseComplete;
CxPlatEventInitialize(&CloseComplete, TRUE, FALSE);
MsQuic->RegistrationClose2(
Registration,
[](void* Context) -> void {
CxPlatEventSet(*(CXPLAT_EVENT*)Context);
},
&CloseComplete);
CxPlatEventWaitForever(CloseComplete);
CxPlatEventUninitialize(CloseComplete);
} else {
MsQuic->RegistrationClose(Registration);
}
}
if (MsQuic) {
#ifndef FUZZING
DumpMsQuicPerfCounters(MsQuic);
#endif
MsQuicClose(MsQuic);
}
}
};
typedef SpinQuicGlobals Gbs;
typedef enum {
SpinQuicAPICallConnectionOpen = 0,
SpinQuicAPICallConnectionStart,
SpinQuicAPICallConnectionShutdown,
SpinQuicAPICallConnectionClose,
SpinQuicAPICallStreamOpen,
SpinQuicAPICallStreamStart,
SpinQuicAPICallStreamSend,
SpinQuicAPICallStreamShutdown,
SpinQuicAPICallStreamClose,
SpinQuicAPICallSetParamConnection,
SpinQuicAPICallGetParamConnection,
SpinQuicAPICallSetParamStream,
SpinQuicAPICallGetParamStream,
SpinQuicAPICallDatagramSend,
SpinQuicAPICallCompleteTicketValidation,
SpinQuicAPICallCompleteCertificateValidation,
SpinQuicAPICallStreamReceiveSetEnabled,
SpinQuicAPICallStreamReceiveComplete,
SpinQuicAPICallConnectionPoolCreate,
SpinQuicAPICallStreamProvideReceiveBuffers,
SpinQuicAPICallCount // Always the last element
} SpinQuicAPICall;
struct SpinQuicStream {
struct SpinQuicConnection& Connection;
HQUIC Handle;
uint8_t SendOffset {0};
bool Deleting {false};
uint64_t PendingRecvLength {UINT64_MAX}; // UINT64_MAX means no pending receive
std::vector<uint8_t> RecvBuffer;
SpinQuicStream(SpinQuicConnection& Connection, HQUIC Handle = nullptr) :
Connection(Connection), Handle(Handle) {}
~SpinQuicStream() { Deleting = true; MsQuic.StreamClose(Handle); }
static SpinQuicStream* Get(HQUIC Stream) {
return (SpinQuicStream*)MsQuic.GetContext(Stream);
}
void EnsureRecvBuffer(size_t Size) {
if (RecvBuffer.size() < Size) {
RecvBuffer.resize(Size);
}
}
};
struct SpinQuicConnection {
public:
std::mutex Lock;
HQUIC Connection = nullptr;
std::vector<HQUIC> Streams;
bool IsShutdownComplete = false;
bool IsDeleting = false;
uint16_t ThreadID;
static SpinQuicConnection* Get(HQUIC Connection) {
return (SpinQuicConnection*)MsQuic.GetContext(Connection);
}
SpinQuicConnection(uint16_t threadID) : ThreadID(threadID) { }
SpinQuicConnection(HQUIC Connection, uint16_t threadID) : ThreadID(threadID) {
Set(Connection);
}
~SpinQuicConnection() {
bool CloseStreamsNow;
{
std::lock_guard<std::mutex> LockScope(Lock);
CloseStreamsNow = IsShutdownComplete; // Already shutdown complete, so clean up now.
IsDeleting = true;
}
if (CloseStreamsNow) CloseStreams();
MsQuic.ConnectionClose(Connection);
}
void Set(HQUIC _Connection) {
Connection = _Connection;
MsQuic.SetContext(Connection, this);
}
void OnShutdownComplete() {
bool CloseStreamsNow;
{
std::lock_guard<std::mutex> LockScope(Lock);
CloseStreamsNow = IsDeleting; // This is happening as a result of deleting, so clean up now.
IsShutdownComplete = true;
}
if (CloseStreamsNow) CloseStreams();
}
void CloseStreams() {
std::vector<HQUIC> StreamsCopy;
{
std::lock_guard<std::mutex> LockScope(Lock);
StreamsCopy = Streams;
Streams.clear();
}
while (StreamsCopy.size() > 0) {
HQUIC Stream = StreamsCopy.back();
StreamsCopy.pop_back();
delete SpinQuicStream::Get(Stream);
}
}
void AddStream(HQUIC Stream) {
std::lock_guard<std::mutex> LockScope(Lock);
Streams.push_back(Stream);
}
// Requires Lock to be held
HQUIC TryGetStream(bool Remove = false) {
if (Streams.size() != 0) {
auto idx = GetRandom(Streams.size());
HQUIC Stream = Streams[idx];
if (Remove) {
Streams.erase(Streams.begin() + idx);
}
return Stream;
}
return nullptr;
}
};
static struct {
bool RunServer {false};
bool RunClient {false};
uint32_t SessionCount {4};
uint64_t RunTimeMs;
uint64_t MaxOperationCount;
uint64_t MaxFuzzIterationCount;
const char* AlpnPrefix;
std::vector<uint16_t> Ports;
const char* ServerName;
uint8_t LossPercent;
int32_t AllocFailDenominator;
uint32_t RepeatCount;
} SpinSettings;
void SpinQuicGetRandomParam(HQUIC Handle, uint16_t ThreadID);
void SpinQuicSetRandomStreamParam(HQUIC Stream, uint16_t ThreadID);
QUIC_STATUS QUIC_API SpinQuicHandleStreamEvent(HQUIC Stream, void* , QUIC_STREAM_EVENT *Event)
{
auto ctx = SpinQuicStream::Get(Stream);
auto ThreadID = ctx->Connection.ThreadID;
if (GetRandom(5) == 0) {
SpinQuicGetRandomParam(Stream, ThreadID);
}
if (GetRandom(10) == 0) {
SpinQuicSetRandomStreamParam(Stream, ThreadID);
}
if (!ctx->Deleting && GetRandom(20) == 0) {
MsQuic.StreamShutdown(Stream, (QUIC_STREAM_SHUTDOWN_FLAGS)GetRandom(16), 0);
goto Exit;
}
switch (Event->Type) {
case QUIC_STREAM_EVENT_PEER_SEND_SHUTDOWN:
MsQuic.StreamShutdown(Stream, (QUIC_STREAM_SHUTDOWN_FLAGS)GetRandom(16), 0);
break;
case QUIC_STREAM_EVENT_PEER_SEND_ABORTED: {
std::lock_guard<std::mutex> Lock(ctx->Connection.Lock);
ctx->PendingRecvLength = UINT64_MAX;
break;
}
case QUIC_STREAM_EVENT_RECEIVE: {
if (Event->RECEIVE.TotalBufferLength == 0) {
ctx->PendingRecvLength = UINT64_MAX; // TODO - Add more complex handling
break;
}
auto Offset = Event->RECEIVE.AbsoluteOffset;
for (uint32_t i = 0; i < Event->RECEIVE.BufferCount; ++i) {
for (uint32_t j = 0; j < Event->RECEIVE.Buffers[i].Length; ++j) {
if (Event->RECEIVE.Buffers[i].Buffer[j] != (uint8_t)(Offset + j)) {
CXPLAT_FRE_ASSERT(FALSE); // Value is corrupt!
}
}
Offset += Event->RECEIVE.Buffers[i].Length;
}
int Random = GetRandom(5);
std::lock_guard<std::mutex> Lock(ctx->Connection.Lock);
CXPLAT_DBG_ASSERT(ctx->PendingRecvLength == UINT64_MAX);
if (Random == 0) {
ctx->PendingRecvLength = Event->RECEIVE.TotalBufferLength;
return QUIC_STATUS_PENDING; // Pend the receive, to be completed later.
} else if (Random == 1 && Event->RECEIVE.TotalBufferLength > 0) {
Event->RECEIVE.TotalBufferLength = GetRandom(Event->RECEIVE.TotalBufferLength + 1); // Partially (or fully) consume the data.
if (GetRandom(10) == 0) {
return QUIC_STATUS_CONTINUE; // Don't pause receive callbacks.
}
}
break;
}
default:
break;
}
Exit:
if (Event->Type == QUIC_STREAM_EVENT_SEND_COMPLETE) {
delete (QUIC_BUFFER*)Event->SEND_COMPLETE.ClientContext;
}
return QUIC_STATUS_SUCCESS;
}
QUIC_STATUS QUIC_API SpinQuicHandleConnectionEvent(HQUIC Connection, void* , QUIC_CONNECTION_EVENT *Event)
{
auto ctx = SpinQuicConnection::Get(Connection);
auto ThreadID = ctx->ThreadID;
switch (Event->Type) {
case QUIC_CONNECTION_EVENT_CONNECTED: {
int Selector = GetRandom(3);
uint16_t DataLength = 0;
uint8_t* Data = nullptr;
if (Selector == 1) {
//
// Send ticket with some data
//
DataLength = (uint16_t)(GetRandom(999) + 1);
} else if (Selector == 2) {
//
// Send ticket with too much data
//
DataLength = QUIC_MAX_RESUMPTION_APP_DATA_LENGTH + 1;
} else {
//
// Send ticket with no app data (no-op)
//
}
if (DataLength) {
Data = (uint8_t*)malloc(DataLength);
if (Data == nullptr) {
DataLength = 0;
}
}
QUIC_SEND_RESUMPTION_FLAGS Flags = (GetRandom(2) == 0) ? QUIC_SEND_RESUMPTION_FLAG_NONE : QUIC_SEND_RESUMPTION_FLAG_FINAL;
MsQuic.ConnectionSendResumptionTicket(Connection, Flags, DataLength, Data);
free(Data);
break;
}
case QUIC_CONNECTION_EVENT_SHUTDOWN_COMPLETE:
SpinQuicConnection::Get(Connection)->OnShutdownComplete();
break;
case QUIC_CONNECTION_EVENT_PEER_STREAM_STARTED: {
if (GetRandom(10) == 0) {
return QUIC_STATUS_NOT_SUPPORTED;
}
if (GetRandom(10) == 0) {
MsQuic.StreamClose(Event->PEER_STREAM_STARTED.Stream);
return QUIC_STATUS_SUCCESS;
}
if (GetRandom(2) == 0) {
Event->PEER_STREAM_STARTED.Flags |= QUIC_STREAM_OPEN_FLAG_DELAY_ID_FC_UPDATES;
}
if (GetRandom(5) == 0) {
Event->PEER_STREAM_STARTED.Flags |= QUIC_STREAM_OPEN_FLAG_APP_OWNED_BUFFERS;
}
auto StreamCtx = new SpinQuicStream(*ctx, Event->PEER_STREAM_STARTED.Stream);
MsQuic.SetCallbackHandler(Event->PEER_STREAM_STARTED.Stream, (void *)SpinQuicHandleStreamEvent, StreamCtx);
if (Event->PEER_STREAM_STARTED.Flags & QUIC_STREAM_OPEN_FLAG_APP_OWNED_BUFFERS) {
uint32_t BufCount = GetRandom(3) + 1; // 1-3 buffers
std::vector<QUIC_BUFFER> Buffers(BufCount);
size_t TotalSize = 0;
for (uint32_t i = 0; i < BufCount; i++) {
Buffers[i].Length = MaxBufferSizes[GetRandom(BufferCount)];
TotalSize += Buffers[i].Length;
}
StreamCtx->EnsureRecvBuffer(TotalSize);
size_t Offset = 0;
for (uint32_t i = 0; i < BufCount; i++) {
Buffers[i].Buffer = StreamCtx->RecvBuffer.data() + Offset;
Offset += Buffers[i].Length;
}
MsQuic.StreamProvideReceiveBuffers(Event->PEER_STREAM_STARTED.Stream, BufCount, Buffers.data());
}
ctx->AddStream(Event->PEER_STREAM_STARTED.Stream);
break;
}
case QUIC_CONNECTION_EVENT_DATAGRAM_SEND_STATE_CHANGED:
if (QUIC_DATAGRAM_SEND_STATE_IS_FINAL(Event->DATAGRAM_SEND_STATE_CHANGED.State)) {
delete (QUIC_BUFFER*)Event->DATAGRAM_SEND_STATE_CHANGED.ClientContext;
}
break;
default:
break;
}
return QUIC_STATUS_SUCCESS;
}
struct ListenerContext {
HQUIC ServerConfiguration;
LockableVector<HQUIC>* Connections;
uint16_t ThreadID;
};
QUIC_STATUS QUIC_API SpinQuicServerHandleListenerEvent(HQUIC /* Listener */, void* Context , QUIC_LISTENER_EVENT* Event)
{
HQUIC ServerConfiguration = ((ListenerContext*)Context)->ServerConfiguration;
auto& Connections = *((ListenerContext*)Context)->Connections;
uint16_t ThreadID = ((ListenerContext*)Context)->ThreadID;
switch (Event->Type) {
case QUIC_LISTENER_EVENT_NEW_CONNECTION: {
if (!GetRandom(20)) {
return QUIC_STATUS_CONNECTION_REFUSED;
}
MsQuic.SetCallbackHandler(Event->NEW_CONNECTION.Connection, (void*)SpinQuicHandleConnectionEvent, &((ListenerContext*)Context)->ThreadID);
QUIC_STATUS Status =
MsQuic.ConnectionSetConfiguration(
Event->NEW_CONNECTION.Connection,
ServerConfiguration);
if (QUIC_FAILED(Status)) {
return Status;
}
auto ctx = new SpinQuicConnection(Event->NEW_CONNECTION.Connection, ThreadID);
if (ctx == nullptr) {
return QUIC_STATUS_OUT_OF_MEMORY;
}
{
std::lock_guard<std::mutex> Lock(Connections);
Connections.push_back(Event->NEW_CONNECTION.Connection);
}
break;
}
default:
break;
}
return QUIC_STATUS_SUCCESS;
}
struct SetParamHelper {
union {
uint64_t u64;
uint32_t u32;
uint16_t u16;
uint8_t u8;
const void *ptr;
} Param;
bool IsPtr;
uint32_t Size = 0;
int Type;
SetParamHelper() {
Param.u64 = 0;
IsPtr = false;
Size = 0;
Type = -1;
}
void SetPtr(uint32_t _Type, const void* _Ptr, uint32_t _Size) {
Type = _Type; Param.ptr = _Ptr; Size = _Size; IsPtr = true;
}
void SetUint8(uint32_t _Type, uint8_t Value) {
Type = _Type; Param.u8 = Value; Size = sizeof(Value);
}
void SetUint16(uint32_t _Type, uint16_t Value) {
Type = _Type; Param.u16 = Value; Size = sizeof(Value);
}
void SetUint32(uint32_t _Type, uint32_t Value) {
Type = _Type; Param.u32= Value; Size = sizeof(Value);
}
void SetUint64(uint32_t _Type, uint64_t Value) {
Type = _Type; Param.u64 = Value; Size = sizeof(Value);
}
void Apply(HQUIC Handle) {
if (Type != -1) {
MsQuic.SetParam(Handle, Type, Size, IsPtr ? Param.ptr : &Param);
}
}
};
void SpinQuicRandomizeSettings(QUIC_SETTINGS& Settings, uint16_t ThreadID)
{
switch (GetRandom(38)) {
case 0:
//Settings.MaxBytesPerKey = GetRandom(UINT64_MAX);
//Settings.IsSet.MaxBytesPerKey = TRUE;
break;
case 1:
//Settings.HandshakeIdleTimeoutMs = GetRandom(UINT64_MAX);
//Settings.IsSet.HandshakeIdleTimeoutMs = TRUE;
break;
case 2:
//Settings.IdleTimeoutMs = GetRandom(UINT64_MAX);
//Settings.IsSet.IdleTimeoutMs = TRUE;
break;
case 3:
//Settings.MtuDiscoverySearchCompleteTimeoutUs = GetRandom(UINT64_MAX);
//Settings.IsSet.MtuDiscoverySearchCompleteTimeoutUs = TRUE;
break;
case 4:
//Settings.TlsClientMaxSendBuffer = GetRandom(UINT32_MAX);
//Settings.IsSet.TlsClientMaxSendBuffer = TRUE;
break;
case 5:
//Settings.TlsServerMaxSendBuffer = GetRandom(UINT32_MAX);
//Settings.IsSet.TlsServerMaxSendBuffer = TRUE;
break;
case 6:
//Settings.StreamRecvWindowDefault = GetRandom(UINT32_MAX);
//Settings.IsSet.StreamRecvWindowDefault = TRUE;
break;
case 7:
//Settings.StreamRecvBufferDefault = GetRandom(UINT32_MAX);
//Settings.IsSet.StreamRecvBufferDefault = TRUE;
break;
case 8:
//Settings.ConnFlowControlWindow = GetRandom(UINT32_MAX);
//Settings.IsSet.ConnFlowControlWindow = TRUE;
break;
case 9:
//Settings.MaxWorkerQueueDelayUs = GetRandom(UINT32_MAX);
//Settings.IsSet.MaxWorkerQueueDelayUs = TRUE;
break;
case 10:
//Settings.MaxStatelessOperations = GetRandom(UINT32_MAX);
//Settings.IsSet.MaxStatelessOperations = TRUE;
break;
case 11:
//Settings.InitialWindowPackets = GetRandom(UINT32_MAX);
//Settings.IsSet.InitialWindowPackets = TRUE;
break;
case 12:
//Settings.SendIdleTimeoutMs = GetRandom(UINT32_MAX);
//Settings.IsSet.SendIdleTimeoutMs = TRUE;
break;
case 13:
//Settings.InitialRttMs = GetRandom(UINT32_MAX);
//Settings.IsSet.InitialRttMs = TRUE;
break;
case 14:
//Settings.MaxAckDelayMs = GetRandom(UINT32_MAX);
//Settings.IsSet.MaxAckDelayMs = TRUE;
break;
case 15:
//Settings.DisconnectTimeoutMs = GetRandom(UINT32_MAX);
//Settings.IsSet.DisconnectTimeoutMs = TRUE;
break;
case 16:
//Settings.KeepAliveIntervalMs = GetRandom(UINT32_MAX);
//Settings.IsSet.KeepAliveIntervalMs = TRUE;
break;
case 17:
Settings.CongestionControlAlgorithm = GetRandom((uint16_t)QUIC_CONGESTION_CONTROL_ALGORITHM_MAX);
Settings.IsSet.CongestionControlAlgorithm = TRUE;
break;
case 18:
//Settings.PeerBidiStreamCount = GetRandom(UINT16_MAX);
//Settings.IsSet.PeerBidiStreamCount = TRUE;
break;
case 19:
//Settings.PeerUnidiStreamCount = GetRandom(UINT16_MAX);
//Settings.IsSet.PeerUnidiStreamCount = TRUE;
break;
case 20:
//Settings.MaxBindingStatelessOperations = GetRandom(UINT16_MAX);
//Settings.IsSet.MaxBindingStatelessOperations = TRUE;
break;
case 21:
//Settings.StatelessOperationExpirationMs = GetRandom(UINT16_MAX);
//Settings.IsSet.StatelessOperationExpirationMs = TRUE;
break;
case 22:
//Settings.MinimumMtu = GetRandom(UINT16_MAX);
//Settings.IsSet.MinimumMtu = TRUE;
break;
case 23:
//Settings.MaximumMtu = GetRandom(UINT16_MAX);
//Settings.IsSet.MaximumMtu = TRUE;
break;
case 24:
//Settings.SendBufferingEnabled = GetRandom((uint8_t)1);
//Settings.IsSet.SendBufferingEnabled = TRUE;
break;
case 25:
Settings.PacingEnabled = GetRandom((uint8_t)1);
Settings.IsSet.PacingEnabled = TRUE;
break;
case 26:
Settings.MigrationEnabled = GetRandom((uint8_t)1);
Settings.IsSet.MigrationEnabled = TRUE;
break;
case 27:
Settings.DatagramReceiveEnabled = GetRandom((uint8_t)1);
Settings.IsSet.DatagramReceiveEnabled = TRUE;
break;
case 28:
Settings.ServerResumptionLevel = GetRandom((uint8_t)3);
Settings.IsSet.ServerResumptionLevel = TRUE;
break;
case 29:
Settings.GreaseQuicBitEnabled = GetRandom((uint8_t)1);
Settings.IsSet.GreaseQuicBitEnabled = TRUE;
break;
case 30:
Settings.EcnEnabled = GetRandom((uint8_t)1);
Settings.IsSet.EcnEnabled = TRUE;
break;
case 31:
//Settings.MaxOperationsPerDrain = GetRandom(UINT8_MAX);
//Settings.IsSet.MaxOperationsPerDrain = TRUE;
break;
case 32:
//Settings.MtuDiscoveryMissingProbeCount = GetRandom(UINT8_MAX);
//Settings.IsSet.MtuDiscoveryMissingProbeCount = TRUE;
break;
case 33:
//Settings.DestCidUpdateIdleTimeoutMs = GetRandom(UINT32_MAX);
//Settings.IsSet.DestCidUpdateIdleTimeoutMs = TRUE;
break;
case 34:
Settings.HyStartEnabled = GetRandom((uint8_t)1);
Settings.IsSet.HyStartEnabled = TRUE;
break;
case 35:
Settings.EncryptionOffloadAllowed = GetRandom((uint8_t)1);
Settings.IsSet.EncryptionOffloadAllowed = TRUE;
break;
case 36:
Settings.ReliableResetEnabled = GetRandom((uint8_t)1);
Settings.IsSet.ReliableResetEnabled = TRUE;
break;
case 37:
Settings.OneWayDelayEnabled = GetRandom((uint8_t)1);
Settings.IsSet.OneWayDelayEnabled = TRUE;
break;
default:
break;
}
}
void SpinQuicSetRandomConnectionParam(HQUIC Connection, uint16_t ThreadID)
{
uint8_t RandomBuffer[8];
QUIC_SETTINGS Settings = {0};
SetParamHelper Helper;
switch (0x05000000 | (GetRandom(24))) {
case QUIC_PARAM_CONN_QUIC_VERSION: // uint32_t
// QUIC_VERSION is get-only
break;
case QUIC_PARAM_CONN_LOCAL_ADDRESS: // QUIC_ADDR
break; // TODO - Add support here
case QUIC_PARAM_CONN_REMOTE_ADDRESS: // QUIC_ADDR
break; // Get Only
case QUIC_PARAM_CONN_IDEAL_PROCESSOR: // uint16_t
break; // Get Only
case QUIC_PARAM_CONN_SETTINGS: // QUIC_SETTINGS
SpinQuicRandomizeSettings(Settings, ThreadID);
Helper.SetPtr(QUIC_PARAM_CONN_SETTINGS, &Settings, sizeof(Settings));
break;
case QUIC_PARAM_CONN_STATISTICS: // QUIC_STATISTICS
break; // Get Only
case QUIC_PARAM_CONN_STATISTICS_PLAT: // QUIC_STATISTICS
break; // Get Only
case QUIC_PARAM_CONN_SHARE_UDP_BINDING: // uint8_t (BOOLEAN)
Helper.SetUint8(QUIC_PARAM_CONN_SHARE_UDP_BINDING, (uint8_t)GetRandom(2));
break;
case QUIC_PARAM_CONN_LOCAL_BIDI_STREAM_COUNT: // uint16_t
break; // Get Only
case QUIC_PARAM_CONN_LOCAL_UNIDI_STREAM_COUNT: // uint16_t
break; // Get Only
case QUIC_PARAM_CONN_MAX_STREAM_IDS: // uint64_t[4]
break; // Get Only
case QUIC_PARAM_CONN_CLOSE_REASON_PHRASE: // char[]
Helper.SetPtr(QUIC_PARAM_CONN_CLOSE_REASON_PHRASE, "ABCDEFGHI\x00\x00\x00\x00\x00", 10);
break;
case QUIC_PARAM_CONN_STREAM_SCHEDULING_SCHEME: // QUIC_STREAM_SCHEDULING_SCHEME
Helper.SetUint32(QUIC_PARAM_CONN_STREAM_SCHEDULING_SCHEME, GetRandom(QUIC_STREAM_SCHEDULING_SCHEME_COUNT));
break;
case QUIC_PARAM_CONN_DATAGRAM_RECEIVE_ENABLED: // uint8_t (BOOLEAN)
Helper.SetUint8(QUIC_PARAM_CONN_DATAGRAM_RECEIVE_ENABLED, (uint8_t)GetRandom(2));
break;
case QUIC_PARAM_CONN_DATAGRAM_SEND_ENABLED: // uint8_t (BOOLEAN)
break; // Get Only
//case QUIC_PARAM_CONN_DISABLE_1RTT_ENCRYPTION: // uint8_t (BOOLEAN)
// Helper.SetUint8(QUIC_PARAM_CONN_DISABLE_1RTT_ENCRYPTION, (uint8_t)GetRandom(2));
// break;
case QUIC_PARAM_CONN_RESUMPTION_TICKET: // uint8_t[]
// TODO
break;
case QUIC_PARAM_CONN_PEER_CERTIFICATE_VALID: // uint8_t (BOOLEAN)
Helper.SetUint8(QUIC_PARAM_CONN_PEER_CERTIFICATE_VALID, (uint8_t)GetRandom(2));
break;
case QUIC_PARAM_CONN_LOCAL_INTERFACE: // uint32_t
// TODO
break;
case QUIC_PARAM_CONN_TLS_SECRETS: // QUIC_TLS_SECRETS
// TODO
break;
case QUIC_PARAM_CONN_VERSION_SETTINGS: // uint32_t[]
break; // Get-only
case QUIC_PARAM_CONN_CIBIR_ID: // bytes[]
if (FuzzData) {
// assume 8 byte buffer for now
uint64_t Buffer = GetRandom(UINT64_MAX);
memcpy(RandomBuffer, &Buffer, sizeof(RandomBuffer));
} else {
CxPlatRandom(sizeof(RandomBuffer), RandomBuffer);
}
Helper.SetPtr(QUIC_PARAM_CONN_CIBIR_ID, RandomBuffer, 1 + (uint8_t)GetRandom(sizeof(RandomBuffer)));
break;
case QUIC_PARAM_CONN_STATISTICS_V2: // QUIC_STATISTICS_V2
break; // Get Only
case QUIC_PARAM_CONN_STATISTICS_V2_PLAT: // QUIC_STATISTICS_V2
break; // Get Only
case QUIC_PARAM_CONN_CLOSE_ASYNC: // uint8_t (BOOLEAN)
// Do not set: this test does not implement async close waiting.
break;
default:
break;
}
Helper.Apply(Connection);
}
void SpinQuicSetRandomStreamParam(HQUIC Stream, uint16_t ThreadID)
{
SetParamHelper Helper;
switch (0x08000000 | (GetRandom(6))) {
case QUIC_PARAM_STREAM_ID: // QUIC_UINT62
break; // Get Only
case QUIC_PARAM_STREAM_0RTT_LENGTH: // QUIC_ADDR
break; // Get Only
case QUIC_PARAM_STREAM_IDEAL_SEND_BUFFER_SIZE: // QUIC_ADDR
break; // Get Only
case QUIC_PARAM_STREAM_PRIORITY: // uint16_t
Helper.SetUint16(QUIC_PARAM_STREAM_PRIORITY, (uint16_t)GetRandom(UINT16_MAX));
break;
case QUIC_PARAM_STREAM_STATISTICS:
break; // Get Only
case QUIC_PARAM_STREAM_RELIABLE_OFFSET:
Helper.SetUint64(QUIC_PARAM_STREAM_RELIABLE_OFFSET, (uint64_t)GetRandom(UINT64_MAX));
default:
break;
}
Helper.Apply(Stream);
}
const uint32_t ParamCounts[] = {
QUIC_PARAM_GLOBAL_LIBRARY_GIT_HASH + 1,
0,
QUIC_PARAM_CONFIGURATION_SCHANNEL_CREDENTIAL_ATTRIBUTE_W + 1,
QUIC_PARAM_LISTENER_PARTITION_INDEX + 1,
QUIC_PARAM_CONN_CLOSE_ASYNC + 1,
QUIC_PARAM_TLS_NEGOTIATED_ALPN + 1,
#ifdef WIN32 // Schannel specific TLS parameters
QUIC_PARAM_TLS_SCHANNEL_SECURITY_CONTEXT_TOKEN + 1,
#else
0,
#endif
QUIC_PARAM_STREAM_STATISTICS + 1
};
#define GET_PARAM_LOOP_COUNT 10
void SpinQuicGetRandomParam(HQUIC Handle, uint16_t ThreadID)
{
for (uint32_t i = 0; i < GET_PARAM_LOOP_COUNT; ++i) {
uint32_t Level = (uint32_t)GetRandom(ARRAYSIZE(ParamCounts));
uint32_t Param = (uint32_t)GetRandom(((ParamCounts[Level] & 0xFFFFFFF)) + 1);
uint32_t Combined = ((Level+1) << 28) + Param;
Combined &= ~QUIC_PARAM_HIGH_PRIORITY; // TODO: enable high priority GetParam
uint8_t OutBuffer[200];
uint32_t OutBufferLength = (uint32_t)GetRandom(sizeof(OutBuffer) + 1);
MsQuic.GetParam(
(GetRandom(10) == 0) ? nullptr : Handle,
Combined,
&OutBufferLength,
(GetRandom(10) == 0) ? nullptr : OutBuffer);
}
}
void Spin(Gbs& Gb, LockableVector<HQUIC>& Connections, std::vector<HQUIC>* Listeners = nullptr, uint16_t ThreadID = UINT16_MAX)
{
Connections.SetThreadID(ThreadID);
bool IsServer = Listeners != nullptr;
uint64_t OpCount = 0;
while (++OpCount != SpinSettings.MaxOperationCount &&
#ifdef FUZZING
(SpinSettings.MaxFuzzIterationCount != FuzzData->GetIterateCount(ThreadID)) &&
#endif
CxPlatTimeDiff64(Gb.StartTimeMs, CxPlatTimeMs64()) < SpinSettings.RunTimeMs) {
if (Listeners) {
auto Value = GetRandom(100);
if (Value >= 90) {
for (auto &Listener : *Listeners) {
MsQuic.ListenerStop(Listener);
}
} else if (Value >= 40) {
for (auto &Listener : *Listeners) {
QUIC_ADDR sockAddr = { 0 };
QuicAddrSetFamily(&sockAddr, GetRandom(2) ? QUIC_ADDRESS_FAMILY_INET : QUIC_ADDRESS_FAMILY_UNSPEC);
QuicAddrSetPort(&sockAddr, GetRandomFromVector(SpinSettings.Ports));
MsQuic.ListenerStart(Listener, &Gb.Alpns[GetRandom(Gb.AlpnCount)], 1, &sockAddr);
}
} else {
for (auto &Listener : *Listeners) {
SpinQuicGetRandomParam(Listener, ThreadID);
}
}
}
#define BAIL_ON_NULL_CONNECTION(Connection) \
if (Connection == nullptr) { \
if (IsServer) { \
CxPlatSleep(100); \
} \
continue; \
}
switch (GetRandom(SpinQuicAPICallCount)) {
case SpinQuicAPICallConnectionOpen:
if (!IsServer) {
auto ctx = new SpinQuicConnection(ThreadID);
if (ctx == nullptr) continue;
HQUIC Connection;
QUIC_STATUS Status = MsQuic.ConnectionOpen(Gb.Registration, SpinQuicHandleConnectionEvent, &ThreadID, &Connection);
if (QUIC_SUCCEEDED(Status)) {
ctx->Set(Connection);
Connections.push_back(Connection);
} else {
delete ctx;
}
}
break;
case SpinQuicAPICallConnectionStart: {
auto Connection = Connections.TryGetRandom();
BAIL_ON_NULL_CONNECTION(Connection);
HQUIC Configuration = GetRandomFromVector(Gb.ClientConfigurations);
MsQuic.ConnectionStart(Connection, Configuration, QUIC_ADDRESS_FAMILY_INET, SpinSettings.ServerName, GetRandomFromVector(SpinSettings.Ports));
break;
}
case SpinQuicAPICallConnectionShutdown: {
auto Connection = Connections.TryGetRandom();