-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathStreams.cpp
More file actions
2073 lines (1820 loc) · 65.5 KB
/
Streams.cpp
File metadata and controls
2073 lines (1820 loc) · 65.5 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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "Logging.h"
#include "MozQuic.h"
#include "MozQuicInternal.h"
#include "Sender.h"
#include "Streams.h"
#include "assert.h"
#include "stdlib.h"
#include "unistd.h"
#include <algorithm>
namespace mozquic {
#define StreamLog1(...) Log::sDoLog(Log::STREAM, 1, mMozQuic, __VA_ARGS__);
#define StreamLog2(...) Log::sDoLog(Log::STREAM, 2, mMozQuic, __VA_ARGS__);
#define StreamLog3(...) Log::sDoLog(Log::STREAM, 3, mMozQuic, __VA_ARGS__);
#define StreamLog4(...) Log::sDoLog(Log::STREAM, 4, mMozQuic, __VA_ARGS__);
#define StreamLog5(...) Log::sDoLog(Log::STREAM, 5, mMozQuic, __VA_ARGS__);
#define StreamLog6(...) Log::sDoLog(Log::STREAM, 6, mMozQuic, __VA_ARGS__);
#define StreamLog7(...) Log::sDoLog(Log::STREAM, 7, mMozQuic, __VA_ARGS__);
#define StreamLog8(...) Log::sDoLog(Log::STREAM, 8, mMozQuic, __VA_ARGS__);
#define StreamLog9(...) Log::sDoLog(Log::STREAM, 9, mMozQuic, __VA_ARGS__);
#define StreamLog10(...) Log::sDoLog(Log::STREAM, 10, mMozQuic, __VA_ARGS__);
uint32_t
StreamState::StartNewStream(StreamPair **outStream, StreamType streamType,
bool no_replay, const void *data, uint32_t amount,
bool fin)
{
if ((mMozQuic->GetConnectionState() != CLIENT_STATE_CONNECTED) &&
(mMozQuic->GetConnectionState() != CLIENT_STATE_0RTT) &&
(mMozQuic->GetConnectionState() != SERVER_STATE_CONNECTED)) {
return MOZQUIC_ERR_IO;
}
if (mNextStreamID[streamType] > mPeerMaxStreamID[streamType]) {
if (!mMaxStreamIDBlocked[streamType]) {
mMaxStreamIDBlocked[streamType] = true;
StreamLog3("new stream BLOCKED on stream id flow control %d\n",
mPeerMaxStreamID[streamType]);
std::unique_ptr<ReliableData> tmp(new ReliableData(0, 0, nullptr, 0, 0));
tmp->MakeStreamIDBlocked(mPeerMaxStreamID[streamType]);
ConnectionWrite(tmp);
}
return MOZQUIC_ERR_IO;
}
std::shared_ptr<StreamPair> tmp(new StreamPair(mNextStreamID[streamType], mMozQuic, this,
mPeerMaxStreamData, mLocalMaxStreamData, no_replay));
mStreams.insert( { mNextStreamID[streamType], tmp } );
*outStream = tmp.get();
mNextStreamID[streamType] += 4;
if ( amount || fin) {
return (*outStream)->Write((const unsigned char *)data, amount, fin);
}
return MOZQUIC_OK;
}
bool
StreamState::IsAllAcked()
{
return (!AnyUnackedPackets()) && mConnUnWritten.empty();
}
uint32_t
StreamState::MakeSureStreamCreated(uint32_t streamID)
{
StreamType streamType = GetStreamType(streamID);
// is this a stream that should be initiated by the peer?
if (IsPeerStream(streamID)) {
// Open a new stream and implicitly open all streams with ID smaller than
// streamID that are not already opened, but only open uni=orbidirectional
// streams depending on the stream type.
if (streamID > mLocalMaxStreamID[streamType]) {
mMozQuic->Shutdown(STREAM_ID_ERROR, "recv stream id too high\n");
mMozQuic->RaiseError(MOZQUIC_ERR_IO, "need stream id %d but peer only allowed %d\n",
streamID, mLocalMaxStreamID[streamType]);
return MOZQUIC_ERR_IO;
}
bool addedStream = false;
while (streamID >= mNextRecvStreamIDUsed[streamType]) {
StreamLog5("Add new %s stream %d\n",
(streamType == BIDI_STREAM) ? "bidi" : "uni",
mNextRecvStreamIDUsed[streamType]);
addedStream = true;
std::shared_ptr<StreamPair> tmp(new StreamPair(mNextRecvStreamIDUsed[streamType],
mMozQuic, this,
mPeerMaxStreamData, mLocalMaxStreamData,
false));
mStreams.insert( { mNextRecvStreamIDUsed[streamType], tmp } );
mNextRecvStreamIDUsed[streamType] += 4;
}
if (addedStream && !mMozQuic->mBackPressure) {
if (mNextRecvStreamIDUsed[streamType] >= mLocalMaxStreamID[streamType] ||
(mLocalMaxStreamID[streamType] - mNextRecvStreamIDUsed[streamType] < 512)) {
mLocalMaxStreamID[streamType] += 1024;
StreamLog5("Increasing Peer's Max StreamID to %d\n", mLocalMaxStreamID[streamType]);
std::unique_ptr<ReliableData> tmp(new ReliableData(0, 0, nullptr, 0, 0));
tmp->MakeMaxStreamID(mLocalMaxStreamID[streamType]);
ConnectionWrite(tmp);
}
}
} else { // stream should have been intiated by this end
if (streamID >= mNextStreamID[streamType]) {
assert(mStreams.find(streamID) == mStreams.end());
mMozQuic->Shutdown(STREAM_STATE_ERROR, "recvd frame on stream this peer should have started");
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "recvd frame on stream this peer should have started");
return MOZQUIC_ERR_GENERAL;
}
}
return MOZQUIC_OK;
}
uint32_t
StreamState::FindStream(uint32_t streamID, std::unique_ptr<ReliableData> &d)
{
assert(IsBidiStream(streamID) || IsPeerStream(streamID));
uint32_t rv = MakeSureStreamCreated(streamID);
if (rv != MOZQUIC_OK) {
return rv;
}
auto i = mStreams.find(streamID);
if (i == mStreams.end()) {
StreamLog4("Stream %d already closed.\n", streamID);
// this stream is already closed and deleted. Discharge frame.
d.reset();
return MOZQUIC_ERR_ALREADY_FINISHED;
}
std::shared_ptr<StreamPair> deleteProtector((*i).second);
(*i).second->Supply(d);
while (!(*i).second->Empty() && !(*i).second->mIn->Done() && mMozQuic->mConnEventCB) {
uint64_t offset = (*i).second->mIn->mOffset;
mMozQuic->mConnEventCB(mMozQuic->mClosure, MOZQUIC_EVENT_NEW_STREAM_DATA, (*i).second.get());
if (offset == (*i).second->mIn->mOffset) {
break;
}
}
return MOZQUIC_OK;
}
void
StreamState::DeleteDoneStreams()
{
auto i = mStreams.begin();
while (i != mStreams.end()) {
if ((*i).second->Done()) {
StreamLog5("Delete stream %lu\n", (*i).second->mStreamID);
i = mStreams.erase(i);
} else {
i++;
}
}
}
bool
StreamState::MaybeDeleteStream(uint32_t streamID)
{
if (mMozQuic->GetConnectionState() == CLIENT_STATE_0RTT) {
// Do not delete streams during 0RTT, maybe we need to restart them.
return false;
}
auto i = mStreams.find(streamID);
if (i == mStreams.end()) {
return false;
}
if ((*i).second->Done()) {
StreamLog5("Delete stream %lu\n", streamID);
mStreams.erase(i);
return true;
}
return false;
}
uint32_t
StreamState::HandleStreamFrame(FrameHeaderData *result, bool fromCleartext,
const unsigned char *pkt, const unsigned char *endpkt,
uint32_t &_ptr)
{
StreamLog5("recv stream %lu len=%lu offset=%lu fin=%d\n",
result->u.mStream.mStreamID,
result->u.mStream.mDataLen,
result->u.mStream.mOffset,
result->u.mStream.mFinBit);
if (!result->u.mStream.mStreamID && result->u.mStream.mFinBit) {
if (!fromCleartext) {
mMozQuic->Shutdown(PROTOCOL_VIOLATION, "fin not allowed on stream 0\n");
}
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "fin not allowed on stream 0\n");
return MOZQUIC_ERR_GENERAL;
}
if (IsSendOnlyStream(result->u.mStream.mStreamID)) {
mMozQuic->Shutdown(PROTOCOL_VIOLATION, "received data on a local uni-stream.\n");
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "received data on a local uni-stream.\n");
return MOZQUIC_ERR_GENERAL;
}
// todo, ultimately the stream chunk could hold references to
// the packet buffer and _ptr into it for zero copy
// parser checked for this, but jic
assert(pkt + _ptr + result->u.mStream.mDataLen <= endpkt);
std::unique_ptr<ReliableData>
tmp(new ReliableData(result->u.mStream.mStreamID,
result->u.mStream.mOffset,
pkt + _ptr,
result->u.mStream.mDataLen,
result->u.mStream.mFinBit));
uint32_t rv = MOZQUIC_OK;
if (!result->u.mStream.mStreamID) {
mStream0->Supply(tmp);
} else {
if (fromCleartext) {
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "cleartext non 0 stream id\n");
return MOZQUIC_ERR_GENERAL;
}
rv = FindStream(result->u.mStream.mStreamID, tmp);
}
_ptr += result->u.mStream.mDataLen;
return rv;
}
uint32_t
StreamState::HandleMaxStreamDataFrame(FrameHeaderData *result, bool fromCleartext,
const unsigned char *pkt, const unsigned char *endpkt,
uint32_t &_ptr)
{
if (fromCleartext) {
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "max stream data frames not allowed in cleartext\n");
return MOZQUIC_ERR_GENERAL;
}
uint32_t streamID = result->u.mMaxStreamData.mStreamID;
if (IsRecvOnlyStream(result->u.mMaxStreamData.mStreamID)) {
mMozQuic->Shutdown(PROTOCOL_VIOLATION, "received maxstreamdata on a recv only stream.\n");
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "received maxstreamdata on a recv only stream.\n");
return MOZQUIC_ERR_GENERAL;
}
if (IsSendOnlyStream(result->u.mMaxStreamData.mStreamID) &&
result->u.mMaxStreamData.mStreamID >= mNextStreamID[1]) {
mMozQuic->Shutdown(PROTOCOL_VIOLATION, "received maxstreamdata on unopened sendonly stream.\n");
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "received maxstreamdata on unopened sendonly stream.\n");
return MOZQUIC_ERR_GENERAL;
}
uint32_t rv = MakeSureStreamCreated(streamID);
if (rv != MOZQUIC_OK) {
return rv;
}
auto i = mStreams.find(streamID);
if (i == mStreams.end()) {
StreamLog4("cannot find streamid %d for max stream data frame. pehaps closed.\n",
streamID);
return MOZQUIC_OK;
}
StreamLog5("recvd max stream data id=%X offset=%ld current limit=%ld\n",
streamID,
result->u.mMaxStreamData.mMaximumStreamData,
i->second->mOut->mFlowControlLimit);
if (i->second->mOut->mFlowControlLimit < result->u.mMaxStreamData.mMaximumStreamData) {
i->second->mOut->mFlowControlLimit = result->u.mMaxStreamData.mMaximumStreamData;
if (i->second->mOut->mBlocked) {
StreamLog5("stream %X has blocked, unblocke it.\n", streamID);
// The stream was blocked on the flow control, unblocked it and continue
// writing if there are data to write.
i->second->mOut->mBlocked = false;
if (!i->second->mOut->mStreamUnWritten.empty()) {
i->second->mOut->mWriter->SignalReadyToWrite(i->second->mOut.get());
}
}
}
return MOZQUIC_OK;
}
uint32_t
StreamState::HandleMaxDataFrame(FrameHeaderData *result, bool fromCleartext,
const unsigned char *pkt, const unsigned char *endpkt,
uint32_t &_ptr)
{
if (fromCleartext) {
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "max data frames not allowed in cleartext\n");
return MOZQUIC_ERR_GENERAL;
}
StreamLog5("recvd max data current %ld new %ld\n",
mPeerMaxData, result->u.mMaxData.mMaximumData);
if (result->u.mMaxData.mMaximumData > mPeerMaxData) {
mPeerMaxData = result->u.mMaxData.mMaximumData;
if (mMaxDataBlocked) {
StreamLog5("conn was blocked by the flow control. Check if there were "
"streams that wants to write new data.\n");
mMaxDataBlocked = false;
FlowControlPromotion();
}
}
return MOZQUIC_OK;
}
uint32_t
StreamState::HandleMaxStreamIDFrame(FrameHeaderData *result, bool fromCleartext,
const unsigned char *pkt, const unsigned char *endpkt,
uint32_t &_ptr)
{
if (fromCleartext) {
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "max stream id frames not allowed in cleartext\n");
return MOZQUIC_ERR_GENERAL;
}
StreamType streamType = GetStreamType(result->u.mMaxStreamID.mMaximumStreamID);
StreamLog5("recvd max %s stream id current %d new %d\n",
(streamType == BIDI_STREAM) ? "bidi" : "uni",
mPeerMaxStreamID[streamType],
result->u.mMaxStreamID.mMaximumStreamID);
if (!IsLocalStream(result->u.mMaxStreamID.mMaximumStreamID)) {
mMozQuic->Shutdown(FRAME_ERROR_MASK | FRAME_TYPE_MAX_STREAM_ID, "remote max stream id\n");
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "remote max stream id\n");
return MOZQUIC_ERR_GENERAL;
}
if (result->u.mMaxStreamID.mMaximumStreamID > mPeerMaxStreamID[streamType]) {
mPeerMaxStreamID[streamType] = result->u.mMaxStreamID.mMaximumStreamID;
mMaxStreamIDBlocked[streamType] = false;
}
return MOZQUIC_OK;
}
uint32_t
StreamState::HandleStreamBlockedFrame(FrameHeaderData *result, bool fromCleartext,
const unsigned char *pkt, const unsigned char *endpkt,
uint32_t &_ptr)
{
if (fromCleartext) {
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "stream blocked frames not allowed in cleartext\n");
return MOZQUIC_ERR_GENERAL;
}
uint32_t streamID = result->u.mStreamBlocked.mStreamID;
if (IsSendOnlyStream(result->u.mStreamBlocked.mStreamID)) {
mMozQuic->Shutdown(PROTOCOL_VIOLATION, "received streamblocked on a local uni-stream.\n");
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "received streamblocked on a local uni-stream.\n");
return MOZQUIC_ERR_GENERAL;
}
StreamLog2("recvd stream blocked id=%X\n", streamID);
return MOZQUIC_OK;
}
uint32_t
StreamState::HandleBlockedFrame(FrameHeaderData *result, bool fromCleartext,
const unsigned char *pkt, const unsigned char *endpkt,
uint32_t &_ptr)
{
if (fromCleartext) {
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "blocked frames not allowed in cleartext\n");
return MOZQUIC_ERR_GENERAL;
}
StreamLog2("recvd connection blocked\n");
return MOZQUIC_OK;
}
uint32_t
StreamState::HandleStreamIDBlockedFrame(FrameHeaderData *result, bool fromCleartext,
const unsigned char *pkt, const unsigned char *endpkt,
uint32_t &_ptr)
{
if (fromCleartext) {
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "streamidblocked frames not allowed in cleartext\n");
return MOZQUIC_ERR_GENERAL;
}
StreamLog2("recvd streamidblocked\n");
return MOZQUIC_OK;
}
uint32_t
StreamState::HandleResetStreamFrame(FrameHeaderData *result, bool fromCleartext,
const unsigned char *pkt, const unsigned char *endpkt,
uint32_t &)
{
if (fromCleartext) {
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "rst_stream frames not allowed in cleartext\n");
return MOZQUIC_ERR_GENERAL;
}
StreamLog5("recvd rst_stream id=%X err=%X, offset=%ld\n",
result->u.mRstStream.mStreamID, result->u.mRstStream.mErrorCode,
result->u.mRstStream.mFinalOffset);
if (!result->u.mRstStream.mStreamID) {
mMozQuic->Shutdown(PROTOCOL_VIOLATION, "rst_stream frames not allowed on stream 0\n");
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "rst_stream frames not allowed on stream 0\n");
return MOZQUIC_ERR_GENERAL;
}
if (IsSendOnlyStream(result->u.mRstStream.mStreamID)) {
mMozQuic->Shutdown(PROTOCOL_VIOLATION, "rst_stream frames not allowed on send only stream\n");
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "rst_stream not allowed on send only stream\n");
return MOZQUIC_ERR_GENERAL;
}
uint32_t rv = MakeSureStreamCreated(result->u.mRstStream.mStreamID);
if (rv != MOZQUIC_OK) {
return rv;
}
auto i = mStreams.find(result->u.mRstStream.mStreamID);
if (i == mStreams.end()) {
StreamLog4("StreamState::HandleResetStreamFrame %d not found.\n",
result->u.mRstStream.mStreamID);
return MOZQUIC_ERR_GENERAL;
}
StreamPair *sp = (*i).second.get();
sp->mIn->HandleResetStream(result->u.mRstStream.mFinalOffset);
return MOZQUIC_OK;
}
uint32_t
StreamIn::HandleResetStream(uint64_t finalOffset)
{
if (mFinalOffset && (mFinalOffset != finalOffset)) {
StreamLog1("stream %d recvd rst with finoffset of %ld expected %ld\n",
mStreamID, finalOffset, mFinalOffset);
mMozQuic->Shutdown(FINAL_OFFSET_ERROR, "offset too large");
return MOZQUIC_ERR_IO;
}
mFinalOffset = finalOffset;
mFinRecvd = true;
mRstRecvd = true;
mOffset = mFinalOffset;
return ScrubUnRead();
}
uint32_t
StreamState::HandleStopSendingFrame(FrameHeaderData *result, bool fromCleartext,
const unsigned char *pkt, const unsigned char *endpkt,
uint32_t &)
{
if (fromCleartext) {
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "stop_sending frames not allowed in cleartext\n");
return MOZQUIC_ERR_GENERAL;
}
if (IsRecvOnlyStream(result->u.mStopSending.mStreamID)) {
mMozQuic->Shutdown(PROTOCOL_VIOLATION, "received stopSending on wrong uni-stream.\n");
mMozQuic->RaiseError(MOZQUIC_ERR_GENERAL, (char *) "received stopSending on wrong uni-stream.\n");
return MOZQUIC_ERR_GENERAL;
}
StreamLog4("recvd stop sending %ld %lx\n",
result->u.mStopSending.mStreamID, result->u.mStopSending.mErrorCode);
RstStream(result->u.mStopSending.mStreamID, result->u.mStopSending.mErrorCode);
return MOZQUIC_OK;
}
uint32_t
StreamState::GeneratePathResponse(uint64_t data)
{
std::unique_ptr<ReliableData> tmp(new ReliableData(0, 0, nullptr, 0, 0));
tmp->MakePathResponse(data);
ConnectionWrite(tmp);
return MOZQUIC_OK;
}
uint32_t
StreamState::RstStream(uint32_t streamID, uint16_t code)
{
auto i = mStreams.find(streamID);
if (i == mStreams.end()) {
StreamLog4("StreamState::RstStream %d not found.\n", streamID);
return MOZQUIC_ERR_GENERAL;
}
return (*i).second->RstStream(code);
}
uint32_t
StreamState::ScrubUnWritten(uint32_t streamID)
{
bool foundDataPkt = false; // this is just for testing that we do not write on uni-stream from a peer.
for (auto iter = mConnUnWritten.begin(); iter != mConnUnWritten.end();) {
auto chunk = (*iter).get();
if (chunk->mStreamID == streamID && chunk->mType != ReliableData::kRstStream) {
iter = mConnUnWritten.erase(iter);
StreamLog6("scrubbing chunk %p of unwritten id %d\n",
chunk, streamID);
foundDataPkt = true;
} else {
iter++;
}
}
for (auto packetIter = mUnAckedPackets.begin(); packetIter != mUnAckedPackets.end(); packetIter++) {
for (auto frameIter = (*packetIter)->mFrameList.begin();
frameIter != (*packetIter)->mFrameList.end(); ) {
if ((*frameIter)->mStreamID == streamID &&
(*frameIter)->mType != ReliableData::kRstStream) {
frameIter = (*packetIter)->mFrameList.erase(frameIter);
StreamLog5("scrubbing frame of unacked id %d\n", streamID);
foundDataPkt = true;
} else {
frameIter++;
}
}
}
if (IsRecvOnlyStream(streamID)) {
assert(!foundDataPkt);
}
mStreamsReadyToWrite.remove(streamID);
return MOZQUIC_OK;
}
void
StreamState::Reset0RTTData()
{
// We will go through the mUnAckedPackets data first then through the
// mConnUnWritten data.
// We also start with the oldest sent(easier to delete data without
// a revert-iterator to iterator conversion).
auto iter1 = mUnAckedPackets.begin();
while (iter1 != mUnAckedPackets.end()) {
auto iter2 = (*iter1).get()->mFrameList.begin();
while (iter2 != (*iter1).get()->mFrameList.end()) {
if ((*iter2)->mType == ReliableData::kStream && (*iter2)->mStreamID) {
auto i = mStreams.find((*iter2)->mStreamID);
assert (i != mStreams.end());
mMozQuic->mSendState->Dismissed0RTTPackets((*iter2)->mLen);
std::unique_ptr<ReliableData> x(std::move((*iter2)));
iter2 = (*iter1).get()->mFrameList.erase(iter2);
if ((*i).second->mOut->mStreamUnWritten.empty()) {
(*i).second->mOut->mStreamUnWritten.push_front(std::move(x));
} else {
auto data = (*i).second->mOut->mStreamUnWritten.rbegin();
while ((data != (*i).second->mOut->mStreamUnWritten.rend()) &&
(*data)->mOffset > x->mOffset) {
data++;
}
// A bit of a strange conversion from reverse-iterator to normal one.
(*i).second->mOut->mStreamUnWritten.insert(data.base(), std::move(x));
}
(*i).second->mOut->mOffsetChargedToConnFlowControl = 0;
(*i).second->mOut->mBlocked = false;
} else {
iter2++;
}
}
if ((*iter1).get()->mFrameList.empty()) {
iter1 = mUnAckedPackets.erase(iter1);
} else {
iter1++;
}
}
auto iter3 = mConnUnWritten.begin();
while (iter3 != mConnUnWritten.end()) {
if ((*iter3)->mType == ReliableData::kStream && (*iter3)->mStreamID) {
auto i = mStreams.find((*iter3)->mStreamID);
assert (i != mStreams.end());
std::unique_ptr<ReliableData> x(std::move(*iter3));
iter3 = mConnUnWritten.erase(iter3);
if ((*i).second->mOut->mStreamUnWritten.empty()) {
(*i).second->mOut->mStreamUnWritten.push_front(std::move(x));
} else {
auto data = (*i).second->mOut->mStreamUnWritten.rbegin();
while ((data != (*i).second->mOut->mStreamUnWritten.rend()) &&
(*data)->mOffset > x->mOffset) {
data++;
}
// A bit of a strange conversion from reverse-iterator to normal one.
(*i).second->mOut->mStreamUnWritten.insert(data.base(), std::move(x));
}
(*i).second->mOut->mOffsetChargedToConnFlowControl = 0;
(*i).second->mOut->mBlocked = false;
} else {
iter3++;
}
}
mStreamsReadyToWrite.clear();
// Delete "no_replay" streams and renumber the rest.
for (int type = 0; type < 2; type++) {
uint32_t nextStreamID = !type ? 4 : 2;
for (uint32_t streamID = nextStreamID; streamID < mNextStreamID[type]; streamID += 4) {
auto streamPair = mStreams[streamID];
assert(streamPair->mStreamID == streamID);
if (streamPair->mNoReplay) {
// raise error.
if (mMozQuic->mClosure) {
mMozQuic->mConnEventCB(mMozQuic->mClosure, MOZQUIC_EVENT_STREAM_NO_REPLAY_ERROR, streamPair.get());
}
mStreams.erase(streamID);
} else {
if (nextStreamID != streamID) {
streamPair->ChangeStreamID(nextStreamID);
mStreams.insert( { nextStreamID, streamPair } );
mStreams.erase(streamID);
}
mStreamsReadyToWrite.push_back(nextStreamID);
nextStreamID += 4;
}
}
mNextStreamID[type] = nextStreamID;
}
}
uint64_t
StreamState::CalculateConnectionCharge(ReliableData *data, StreamOut *out)
{
uint64_t newConnectionCharge = 0;
if (data->mStreamID &&
(data->mOffset + data->mLen > out->mOffsetChargedToConnFlowControl)) {
newConnectionCharge = data->mOffset + data->mLen - out->mOffsetChargedToConnFlowControl;
}
return newConnectionCharge;
}
uint32_t
StreamState::FlowControlPromotionForStreamPair(StreamOut *out)
{
for (auto iBuffer = out->mStreamUnWritten.begin();
iBuffer != out->mStreamUnWritten.end(); ) {
uint64_t newConnectionCharge = 0;
if ((*iBuffer)->mLen) {
newConnectionCharge = CalculateConnectionCharge((*iBuffer).get(), out);
if (newConnectionCharge) {
if (mMaxDataSent >= mPeerMaxData) {
if (!mMaxDataBlocked) {
mMaxDataBlocked = true;
StreamLog2("BLOCKED by connection window id=%lX (sent %d peer limit %d)\n",
(*iBuffer)->mStreamID, mMaxDataSent, mPeerMaxData);
std::unique_ptr<ReliableData> tmp(new ReliableData(0, 0, nullptr, 0, 0));
tmp->MakeBlocked(mPeerMaxData);
ConnectionWrite(tmp);
}
iBuffer++;
continue;
}
if (mMaxDataSent + newConnectionCharge > mPeerMaxData) {
// split buffer
uint64_t minCharge = 1; // for hypothetical 1 byte frame
if ((*iBuffer)->mOffset + 1 > out->mOffsetChargedToConnFlowControl) {
minCharge = (*iBuffer)->mOffset + 1 - out->mOffsetChargedToConnFlowControl;
}
if (mMaxDataSent + minCharge > mPeerMaxData) {
if (!mMaxDataBlocked) {
mMaxDataBlocked = true;
StreamLog2("BLOCKED by connection window 2\n");
std::unique_ptr<ReliableData> tmp(new ReliableData(0, 0, nullptr, 0, 0));
tmp->MakeBlocked(mPeerMaxData);
ConnectionWrite(tmp);
}
iBuffer++;
continue;
}
uint64_t maxCharge = mPeerMaxData - mMaxDataSent;
uint64_t room = maxCharge - minCharge + 1;
assert (room < (*iBuffer)->mLen);
std::unique_ptr<ReliableData>
tmp(new ReliableData((*iBuffer)->mStreamID,
(*iBuffer)->mOffset + room,
(*iBuffer)->mData.get() + room,
(*iBuffer)->mLen - room,
(*iBuffer)->mFin));
(*iBuffer)->mLen = room;
(*iBuffer)->mFin = false;
StreamLog7("FlowControlPromotionForStreamPair ConnWindow splitting chunk into "
"%ld.%d and %ld.%d\n",
(*iBuffer)->mOffset, (*iBuffer)->mLen,
tmp->mOffset, tmp->mLen);
auto iterReg = iBuffer++;
out->mStreamUnWritten.insert(iBuffer, std::move(tmp));
iBuffer = iterReg;
newConnectionCharge = CalculateConnectionCharge((*iBuffer).get(), out);
}
}
if ((*iBuffer)->mOffset >= out->mFlowControlLimit) {
if (!out->mBlocked) {
StreamLog2("Stream %d BLOCKED flow control\n", (*iBuffer)->mStreamID);
out->mBlocked = true;
std::unique_ptr<ReliableData> tmp(new ReliableData((*iBuffer)->mStreamID, 0, nullptr, 0, 0));
tmp->MakeStreamBlocked(out->mFlowControlLimit);
ConnectionWrite(tmp);
}
iBuffer++;
continue;
}
if ((*iBuffer)->mOffset + (*iBuffer)->mLen > out->mFlowControlLimit) {
// need to split it!
uint64_t room = out->mFlowControlLimit - (*iBuffer)->mOffset;
std::unique_ptr<ReliableData>
tmp(new ReliableData((*iBuffer)->mStreamID,
(*iBuffer)->mOffset + room,
(*iBuffer)->mData.get() + room,
(*iBuffer)->mLen - room,
(*iBuffer)->mFin));
(*iBuffer)->mLen = room;
(*iBuffer)->mFin = false;
StreamLog7("FlowControlPromotionForStreamPair StreamWindow splitting chunk into "
"%ld.%d and %ld.%d\n",
(*iBuffer)->mOffset, (*iBuffer)->mLen,
tmp->mOffset, tmp->mLen);
auto iterReg = iBuffer++;
out->mStreamUnWritten.insert(iBuffer, std::move(tmp));
iBuffer = iterReg;
newConnectionCharge = CalculateConnectionCharge((*iBuffer).get(), out);
}
}
assert((*iBuffer)->mOffset + (*iBuffer)->mLen <= out->mFlowControlLimit);
out->mOffsetChargedToConnFlowControl += newConnectionCharge;
mMaxDataSent += newConnectionCharge;
assert(mMaxDataSent <= mPeerMaxData);
uint64_t pmd = mPeerMaxData; // will trunc, but just for logging
uint64_t mds = mMaxDataSent; // will trunc, but just for logging
StreamLog6("promoting chunk stream %d %ld.%d [stream limit=%ld] [conn limit %llu of %lld]\n",
(*iBuffer)->mStreamID, (*iBuffer)->mOffset, (*iBuffer)->mLen,
out->mFlowControlLimit, mds, pmd);
assert((*iBuffer)->mOffset + (*iBuffer)->mLen <= out->mFlowControlLimit);
std::unique_ptr<ReliableData> x(std::move(*iBuffer));
mConnUnWritten.push_back(std::move(x));
iBuffer = out->mStreamUnWritten.erase(iBuffer);
}
return MOZQUIC_OK;
}
// This fx() is called when the connection flow control is unblocked.
// It goes through the list of the streams that are waiting to write data
// and promotes mStreamUnWritten buffers to the connection scoped
// mConnUnWritten.
uint32_t
StreamState::FlowControlPromotion()
{
while (!mStreamsReadyToWrite.empty()) {
auto streamID = mStreamsReadyToWrite.front();
if (!streamID) {
FlowControlPromotionForStreamPair(mStream0.get()->mOut.get());
if (mStream0->mOut->mStreamUnWritten.empty()) {
mStreamsReadyToWrite.pop_front();
}
} else {
assert(IsBidiStream(streamID) || IsLocalStream(streamID)); // We cannot write to a peer's uni stream.
auto streamPair = mStreams[streamID];
FlowControlPromotionForStreamPair(streamPair.get()->mOut.get());
if (MaybeDeleteStream(streamPair->mStreamID) ||
streamPair->mOut->mBlocked || streamPair->mOut->mStreamUnWritten.empty()) {
mStreamsReadyToWrite.pop_front();
}
}
if (mMaxDataBlocked) {
return MOZQUIC_OK;
}
}
return MOZQUIC_OK;
}
void
StreamState::MaybeIssueFlowControlCredit()
{
// todo something better than polling
ConnectionReadBytes(0);
if (mStream0) {
mStream0->mIn->MaybeIssueFlowControlCredit();
}
for (auto iStreamPair = mStreams.begin(); iStreamPair != mStreams.end(); iStreamPair++) {
if (IsBidiStream(iStreamPair->second->mStreamID) ||
IsPeerStream(iStreamPair->second->mStreamID)) {
iStreamPair->second->mIn->MaybeIssueFlowControlCredit();
}
}
for (int i = 0 ; i < 2; i++) {
if (mNextRecvStreamIDUsed[i] >= mLocalMaxStreamID[i] ||
(mLocalMaxStreamID[i] - mNextRecvStreamIDUsed[i] < 512)) {
mLocalMaxStreamID[i] += 1024;
StreamLog5("Increasing Peer's Max StreamID to %d\n", mLocalMaxStreamID[i]);
std::unique_ptr<ReliableData> tmp(new ReliableData(0, 0, nullptr, 0, 0));
tmp->MakeMaxStreamID(mLocalMaxStreamID[i]);
ConnectionWrite(tmp);
}
}
}
uint32_t
StreamState::CreateFrames(unsigned char *&aFramePtr, const unsigned char *endpkt, bool justZero,
TransmittedPacket *transmittedPacket)
{
auto iter = mConnUnWritten.begin();
while (iter != mConnUnWritten.end()) {
unsigned char *framePtr = aFramePtr;
if (framePtr == endpkt) {
break;
}
if (justZero && (((*iter)->mType != ReliableData::kStream)|| (*iter)->mStreamID)) {
iter++;
continue;
}
if ((*iter)->mType == ReliableData::kRstStream) {
if (CreateRstStreamFrame(framePtr, endpkt, (*iter).get()) != MOZQUIC_OK) {
break;
}
} else if ((*iter)->mType == ReliableData::kMaxStreamData) {
if (CreateMaxStreamDataFrame(framePtr, endpkt, (*iter).get()) != MOZQUIC_OK) {
// this one sometimes fails and we should just delete the info and move on
// as the stream no longer needs flow control
iter = mConnUnWritten.erase(iter);
continue;
}
} else if ((*iter)->mType == ReliableData::kStopSending) {
if (CreateStopSendingFrame(framePtr, endpkt, (*iter).get()) != MOZQUIC_OK) {
break;
}
} else if ((*iter)->mType == ReliableData::kMaxData) {
if (CreateMaxDataFrame(framePtr, endpkt, (*iter).get()) != MOZQUIC_OK) {
break;
}
} else if ((*iter)->mType == ReliableData::kMaxStreamID) {
if (CreateMaxStreamIDFrame(framePtr, endpkt, (*iter).get()) != MOZQUIC_OK) {
break;
}
} else if ((*iter)->mType == ReliableData::kStreamBlocked) {
if (CreateStreamBlockedFrame(framePtr, endpkt, (*iter).get()) != MOZQUIC_OK) {
break;
}
} else if ((*iter)->mType == ReliableData::kBlocked) {
if (CreateBlockedFrame(framePtr, endpkt, (*iter).get()) != MOZQUIC_OK) {
break;
}
} else if ((*iter)->mType == ReliableData::kStreamIDBlocked) {
bool toRemove = false;
if (CreateStreamIDBlockedFrame(framePtr, endpkt, (*iter).get(), toRemove) != MOZQUIC_OK) {
if (toRemove) {
iter = mConnUnWritten.erase(iter);
continue;
}
break;
}
} else if ((*iter)->mType == ReliableData::kPathResponse) {
if ((*iter)->mCloned) {
// don't retransmit path response
iter = mConnUnWritten.erase(iter);
continue;
}
if (CreatePathResponseFrame(framePtr, endpkt, (*iter).get()) != MOZQUIC_OK) {
break;
}
} else {
assert ((*iter)->mType == ReliableData::kStream);
uint32_t used = 0;
auto typeBytePtr = framePtr; // used to fill in fin bit later
framePtr[0] = FRAME_TYPE_STREAM | STREAM_LEN_BIT;
if ((*iter)->mOffset) {
framePtr[0] |= STREAM_OFF_BIT;
}
framePtr++;
if (MozQuic::EncodeVarint((*iter)->mStreamID, framePtr, (endpkt - framePtr), used) != MOZQUIC_OK) {
return MOZQUIC_ERR_GENERAL;
}
framePtr += used;
if ((*iter)->mOffset) {
if (MozQuic::EncodeVarint((*iter)->mOffset, framePtr, (endpkt - framePtr), used) != MOZQUIC_OK) {
return MOZQUIC_ERR_GENERAL;
}
framePtr += used;
}
// calc assumes 2 byte length encoding
uint32_t room = (endpkt - framePtr) - 2;
if (room < ((*iter)->mLen)) {
// we need to split this chunk. its too big
// todo iterate on them all instead of doing this n^2
// as there is a copy involved
std::unique_ptr<ReliableData>
tmp(new ReliableData((*iter)->mStreamID,
(*iter)->mOffset + room,
(*iter)->mData.get() + room,
(*iter)->mLen - room,
(*iter)->mFin));
(*iter)->mLen = room;
(*iter)->mFin = false;
tmp->mFromRTO = (*iter)->mFromRTO;
auto iterReg = iter++;
mConnUnWritten.insert(iter, std::move(tmp));
iter = iterReg;
}
assert(room >= (*iter)->mLen);
assert((*iter)->mLen <= (1 << 14)); // check 2 byte assumption
// set the len and fin bit after any potential frame split
if (MozQuic::EncodeVarint((*iter)->mLen, framePtr, (endpkt - framePtr), used) != MOZQUIC_OK) {
return MOZQUIC_ERR_GENERAL;
}
assert(used <= 2);
framePtr += used;
if ((*iter)->mFin) {
*typeBytePtr = *typeBytePtr | STREAM_FIN_BIT;
}
memcpy(framePtr, (*iter)->mData.get(), (*iter)->mLen);
StreamLog5("writing a stream %d frame %d @ offset %d [fin=%d] in packet %lX\n",
(*iter)->mStreamID, (*iter)->mLen, (*iter)->mOffset, (*iter)->mFin,
mMozQuic->mNextTransmitPacketNumber);
framePtr += (*iter)->mLen;
}
if ((mMozQuic->GetConnectionState() == CLIENT_STATE_CONNECTED) ||
(mMozQuic->GetConnectionState() == SERVER_STATE_CONNECTED) ||
(mMozQuic->GetConnectionState() == CLIENT_STATE_0RTT)) {
(*iter)->mTransmitKeyPhase = keyPhase1Rtt;
} else {
(*iter)->mTransmitKeyPhase = keyPhaseUnprotected;
}
if ((*iter)->mFromRTO) {
transmittedPacket->mFromRTO = true;
}
if ((*iter)->mQueueOnTransmit) {
transmittedPacket->mQueueOnTransmit = true;
}
// move it to the unacked list
transmittedPacket->mFrameList.push_back(std::move(*iter));
iter = mConnUnWritten.erase(iter);
aFramePtr = framePtr;
}
return MOZQUIC_OK;
}
uint32_t
StreamState::FlushOnce(bool forceAck, bool forceFrame, bool &outWritten)
{
outWritten = false;
if (mMozQuic->GetConnectionState() != SERVER_STATE_CONNECTED) {
mMozQuic->FlushStream0(forceAck);
}
if (mConnUnWritten.empty() && !forceAck) {
return MOZQUIC_OK;
}
unsigned char plainPkt[kMaxMTU];
uint32_t headerLen;
uint32_t mtu = mMozQuic->mMTU;
assert(mtu <= kMaxMTU);
unsigned char *payloadLenPtr = nullptr;
unsigned char *pnPtr = nullptr;
if (mMozQuic->GetConnectionState() == CLIENT_STATE_0RTT) {
mMozQuic->Create0RTTLongPacketHeader(plainPkt, mtu - kTagLen, headerLen,
&payloadLenPtr, &pnPtr);
} else if ((mMozQuic->GetConnectionState() != SERVER_STATE_CONNECTED) &&
(mMozQuic->GetConnectionState() != SERVER_STATE_0RTT) &&