forked from cloudflare/quiche
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream.rs
2322 lines (1838 loc) · 70.9 KB
/
stream.rs
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) 2018-2019, Cloudflare, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use std::cmp;
use std::collections::hash_map;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use crate::Error;
use crate::Result;
use crate::ranges;
const MAX_WRITE_SIZE: usize = 1000;
/// Keeps track of QUIC streams and enforces stream limits.
#[derive(Default)]
pub struct StreamMap {
/// Map of streams indexed by stream ID.
streams: HashMap<u64, Stream>,
/// Set of streams that were completed and garbage collected.
///
/// Instead of keeping the full stream state forever, we collect completed
/// streams to save memory, but we still need to keep track of previously
/// created streams, to prevent peers from re-creating them.
collected: HashSet<u64>,
/// Peer's maximum bidirectional stream count limit.
peer_max_streams_bidi: u64,
/// Peer's maximum unidirectional stream count limit.
peer_max_streams_uni: u64,
/// The total number of bidirectional streams opened by the peer.
peer_opened_streams_bidi: u64,
/// The total number of unidirectional streams opened by the peer.
peer_opened_streams_uni: u64,
/// Local maximum bidirectional stream count limit.
local_max_streams_bidi: u64,
local_max_streams_bidi_next: u64,
/// Local maximum unidirectional stream count limit.
local_max_streams_uni: u64,
local_max_streams_uni_next: u64,
/// The total number of bidirectional streams opened by the local endpoint.
local_opened_streams_bidi: u64,
/// The total number of unidirectional streams opened by the local endpoint.
local_opened_streams_uni: u64,
/// Queue of stream IDs corresponding to streams that have buffered data
/// ready to be sent to the peer. This also implies that the stream has
/// enough flow control credits to send at least some of that data.
///
/// Streams are added to the back of the list, and removed from the front.
flushable: VecDeque<u64>,
/// Set of stream IDs corresponding to streams that have outstanding data
/// to read. This is used to generate a `StreamIter` of streams without
/// having to iterate over the full list of streams.
readable: HashSet<u64>,
/// Set of stream IDs corresponding to streams that have enough flow control
/// capacity to be written to, and is not finished. This is used to generate
/// a `StreamIter` of streams without having to iterate over the full list
/// of streams.
writable: HashSet<u64>,
/// Set of stream IDs corresponding to streams that are almost out of flow
/// control credit and need to send MAX_STREAM_DATA. This is used to
/// generate a `StreamIter` of streams without having to iterate over the
/// full list of streams.
almost_full: HashSet<u64>,
/// Set of stream IDs corresponding to streams that are blocked. The value
/// of the map elements represents the offset of the stream at which the
/// blocking occurred.
blocked: HashMap<u64, u64>,
}
impl StreamMap {
pub fn new(max_streams_bidi: u64, max_streams_uni: u64) -> StreamMap {
StreamMap {
local_max_streams_bidi: max_streams_bidi,
local_max_streams_bidi_next: max_streams_bidi,
local_max_streams_uni: max_streams_uni,
local_max_streams_uni_next: max_streams_uni,
..StreamMap::default()
}
}
/// Returns the stream with the given ID if it exists.
pub fn get(&self, id: u64) -> Option<&Stream> {
self.streams.get(&id)
}
/// Returns the mutable stream with the given ID if it exists.
pub fn get_mut(&mut self, id: u64) -> Option<&mut Stream> {
self.streams.get_mut(&id)
}
/// Returns the mutable stream with the given ID if it exists, or creates
/// a new one otherwise.
///
/// The `local` parameter indicates whether the stream's creation was
/// requested by the local application rather than the peer, and is
/// used to validate the requested stream ID, and to select the initial
/// flow control values from the local and remote transport parameters
/// (also passed as arguments).
///
/// This also takes care of enforcing both local and the peer's stream
/// count limits. If one of these limits is violated, the `StreamLimit`
/// error is returned.
pub(crate) fn get_or_create(
&mut self, id: u64, local_params: &crate::TransportParams,
peer_params: &crate::TransportParams, local: bool, is_server: bool,
) -> Result<&mut Stream> {
let stream = match self.streams.entry(id) {
hash_map::Entry::Vacant(v) => {
if local != is_local(id, is_server) {
return Err(Error::InvalidStreamState);
}
// Stream has already been closed and garbage collected.
if self.collected.contains(&id) {
return Err(Error::Done);
}
let (max_rx_data, max_tx_data) = match (local, is_bidi(id)) {
// Locally-initiated bidirectional stream.
(true, true) => (
local_params.initial_max_stream_data_bidi_local,
peer_params.initial_max_stream_data_bidi_remote,
),
// Locally-initiated unidirectional stream.
(true, false) => (0, peer_params.initial_max_stream_data_uni),
// Remotely-initiated bidirectional stream.
(false, true) => (
local_params.initial_max_stream_data_bidi_remote,
peer_params.initial_max_stream_data_bidi_local,
),
// Remotely-initiated unidirectional stream.
(false, false) =>
(local_params.initial_max_stream_data_uni, 0),
};
// Enforce stream count limits.
match (is_local(id, is_server), is_bidi(id)) {
(true, true) => {
if self.local_opened_streams_bidi >=
self.peer_max_streams_bidi
{
return Err(Error::StreamLimit);
}
self.local_opened_streams_bidi += 1;
},
(true, false) => {
if self.local_opened_streams_uni >=
self.peer_max_streams_uni
{
return Err(Error::StreamLimit);
}
self.local_opened_streams_uni += 1;
},
(false, true) => {
if self.peer_opened_streams_bidi >=
self.local_max_streams_bidi
{
return Err(Error::StreamLimit);
}
self.peer_opened_streams_bidi += 1;
},
(false, false) => {
if self.peer_opened_streams_uni >=
self.local_max_streams_uni
{
return Err(Error::StreamLimit);
}
self.peer_opened_streams_uni += 1;
},
};
let s = Stream::new(max_rx_data, max_tx_data, is_bidi(id), local);
v.insert(s)
},
hash_map::Entry::Occupied(v) => v.into_mut(),
};
// Stream might already be writable due to initial flow control limits.
if stream.is_writable() {
self.writable.insert(id);
}
Ok(stream)
}
/// Pushes the stream ID to the back of the flushable streams queue.
///
/// Note that the caller is responsible for checking that the specified
/// stream ID was not in the queue already before calling this.
///
/// Queueing a stream multiple times simultaneously means that it might be
/// unfairly scheduled more often than other streams, and might also cause
/// spurious cycles through the queue, so it should be avoided.
pub fn push_flushable(&mut self, stream_id: u64) {
self.flushable.push_back(stream_id);
}
/// Removes and returns the first stream ID from the flushable streams
/// queue.
///
/// Note that if the stream is still flushable after sending some of its
/// outstanding data, it needs to be added back to the queu.
pub fn pop_flushable(&mut self) -> Option<u64> {
self.flushable.pop_front()
}
/// Adds or removes the stream ID to/from the readable streams set.
///
/// If the stream was already in the list, this does nothing.
pub fn mark_readable(&mut self, stream_id: u64, readable: bool) {
if readable {
self.readable.insert(stream_id);
} else {
self.readable.remove(&stream_id);
}
}
/// Adds or removes the stream ID to/from the writable streams set.
///
/// This should also be called anytime a new stream is created, in addition
/// to when an existing stream becomes writable (or stops being writable).
///
/// If the stream was already in the list, this does nothing.
pub fn mark_writable(&mut self, stream_id: u64, writable: bool) {
if writable {
self.writable.insert(stream_id);
} else {
self.writable.remove(&stream_id);
}
}
/// Adds or removes the stream ID to/from the almost full streams set.
///
/// If the stream was already in the list, this does nothing.
pub fn mark_almost_full(&mut self, stream_id: u64, almost_full: bool) {
if almost_full {
self.almost_full.insert(stream_id);
} else {
self.almost_full.remove(&stream_id);
}
}
/// Adds or removes the stream ID to/from the blocked streams set with the
/// given offset value.
///
/// If the stream was already in the list, this does nothing.
pub fn mark_blocked(&mut self, stream_id: u64, blocked: bool, off: u64) {
if blocked {
self.blocked.insert(stream_id, off);
} else {
self.blocked.remove(&stream_id);
}
}
/// Updates the peer's maximum bidirectional stream count limit.
pub fn update_peer_max_streams_bidi(&mut self, v: u64) {
self.peer_max_streams_bidi = cmp::max(self.peer_max_streams_bidi, v);
}
/// Updates the peer's maximum unidirectional stream count limit.
pub fn update_peer_max_streams_uni(&mut self, v: u64) {
self.peer_max_streams_uni = cmp::max(self.peer_max_streams_uni, v);
}
/// Commits the new max_streams_bidi limit.
pub fn update_max_streams_bidi(&mut self) {
self.local_max_streams_bidi = self.local_max_streams_bidi_next;
}
/// Returns the new max_streams_bidi limit.
pub fn max_streams_bidi_next(&mut self) -> u64 {
self.local_max_streams_bidi_next
}
/// Commits the new max_streams_uni limit.
pub fn update_max_streams_uni(&mut self) {
self.local_max_streams_uni = self.local_max_streams_uni_next;
}
/// Returns the new max_streams_uni limit.
pub fn max_streams_uni_next(&mut self) -> u64 {
self.local_max_streams_uni_next
}
/// Drops completed stream.
///
/// This should only be called when Stream::is_complete() returns true for
/// the given stream.
pub fn collect(&mut self, stream_id: u64, local: bool) {
if !local {
// If the stream was created by the peer, give back a max streams
// credit.
if is_bidi(stream_id) {
self.local_max_streams_bidi_next =
self.local_max_streams_bidi_next.saturating_add(1);
} else {
self.local_max_streams_uni_next =
self.local_max_streams_uni_next.saturating_add(1);
}
}
self.streams.remove(&stream_id);
self.collected.insert(stream_id);
}
/// Creates an iterator over streams that have outstanding data to read.
pub fn readable(&self) -> StreamIter {
StreamIter::from(&self.readable)
}
/// Creates an iterator over streams that can be written to.
pub fn writable(&self) -> StreamIter {
StreamIter::from(&self.writable)
}
/// Creates an iterator over streams that need to send MAX_STREAM_DATA.
pub fn almost_full(&self) -> StreamIter {
StreamIter::from(&self.almost_full)
}
/// Creates an iterator over streams that need to send STREAM_DATA_BLOCKED.
pub fn blocked(&self) -> hash_map::Iter<u64, u64> {
self.blocked.iter()
}
/// Returns true if there are any streams that have data to write.
pub fn has_flushable(&self) -> bool {
!self.flushable.is_empty()
}
/// Returns true if there are any streams that need to update the local
/// flow control limit.
pub fn has_almost_full(&self) -> bool {
!self.almost_full.is_empty()
}
/// Returns true if there are any streams that are blocked.
pub fn has_blocked(&self) -> bool {
!self.blocked.is_empty()
}
/// Returns true if the max bidirectional streams count needs to be updated
/// by sending a MAX_STREAMS frame to the peer.
pub fn should_update_max_streams_bidi(&self) -> bool {
self.local_max_streams_bidi_next != self.local_max_streams_bidi &&
self.local_max_streams_bidi_next / 2 >
self.local_max_streams_bidi - self.peer_opened_streams_bidi
}
/// Returns true if the max unidirectional streams count needs to be updated
/// by sending a MAX_STREAMS frame to the peer.
pub fn should_update_max_streams_uni(&self) -> bool {
self.local_max_streams_uni_next != self.local_max_streams_uni &&
self.local_max_streams_uni_next / 2 >
self.local_max_streams_uni - self.peer_opened_streams_uni
}
/// Returns the number of active streams in the map.
#[cfg(test)]
pub fn len(&self) -> usize {
self.streams.len()
}
}
/// A QUIC stream.
#[derive(Default)]
pub struct Stream {
/// Receive-side stream buffer.
pub recv: RecvBuf,
/// Send-side stream buffer.
pub send: SendBuf,
/// Whether the stream is bidirectional.
pub bidi: bool,
/// Whether the stream was created by the local endpoint.
pub local: bool,
/// Application data.
pub data: Option<Box<dyn Send + std::any::Any>>,
}
impl Stream {
/// Creates a new stream with the given flow control limits.
pub fn new(
max_rx_data: u64, max_tx_data: u64, bidi: bool, local: bool,
) -> Stream {
Stream {
recv: RecvBuf::new(max_rx_data),
send: SendBuf::new(max_tx_data),
bidi,
local,
data: None,
}
}
/// Returns true if the stream has data to read.
pub fn is_readable(&self) -> bool {
self.recv.ready()
}
/// Returns true if the stream has enough flow control capacity to be
/// written to, and is not finished.
pub fn is_writable(&self) -> bool {
!self.send.shutdown &&
!self.send.is_fin() &&
self.send.off < self.send.max_data
}
/// Returns true if the stream has data to send and is allowed to send at
/// least some of it.
pub fn is_flushable(&self) -> bool {
self.send.ready() && self.send.off_front() < self.send.max_data
}
/// Returns true if the stream is complete.
///
/// For bidirectional streams this happens when both the receive and send
/// sides are complete. That is when all incoming data has been read by the
/// application, and when all outgoing data has been acked by the peer.
///
/// For unidirectional streams this happens when either the receive or send
/// side is complete, depending on whether the stream was created locally
/// or not.
pub fn is_complete(&self) -> bool {
match (self.bidi, self.local) {
// For bidirectional streams we need to check both receive and send
// sides for completion.
(true, _) => self.recv.is_fin() && self.send.is_complete(),
// For unidirectional streams generated locally, we only need to
// check the send side for completion.
(false, true) => self.send.is_complete(),
// For unidirectional streams generated by the peer, we only need
// to check the receive side for completion.
(false, false) => self.recv.is_fin(),
}
}
}
/// Returns true if the stream was created locally.
pub fn is_local(stream_id: u64, is_server: bool) -> bool {
(stream_id & 0x1) == (is_server as u64)
}
/// Returns true if the stream is bidirectional.
pub fn is_bidi(stream_id: u64) -> bool {
(stream_id & 0x2) == 0
}
/// An iterator over QUIC streams.
#[derive(Default)]
pub struct StreamIter {
streams: Vec<u64>,
}
impl StreamIter {
fn from(streams: &HashSet<u64>) -> Self {
StreamIter {
streams: streams.iter().copied().collect(),
}
}
}
impl Iterator for StreamIter {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
self.streams.pop()
}
}
impl ExactSizeIterator for StreamIter {
fn len(&self) -> usize {
self.streams.len()
}
}
/// Receive-side stream buffer.
///
/// Stream data received by the peer is buffered in a list of data chunks
/// ordered by offset in ascending order. Contiguous data can then be read
/// into a slice.
#[derive(Default)]
pub struct RecvBuf {
/// Chunks of data received from the peer that have not yet been read by
/// the application, ordered by offset.
data: BinaryHeap<RangeBuf>,
/// The lowest data offset that has yet to be read by the application.
off: u64,
/// The total length of data received on this stream.
len: u64,
/// The maximum offset the peer is allowed to send us.
max_data: u64,
/// The updated maximum offset the peer is allowed to send us.
max_data_next: u64,
/// The final stream offset received from the peer, if any.
fin_off: Option<u64>,
/// Whether incoming data is validated but not buffered.
drain: bool,
}
impl RecvBuf {
/// Creates a new receive buffer.
fn new(max_data: u64) -> RecvBuf {
RecvBuf {
max_data,
max_data_next: max_data,
..RecvBuf::default()
}
}
/// Inserts the given chunk of data in the buffer.
///
/// This also takes care of enforcing stream flow control limits, as well
/// as handling incoming data that overlaps data that is already in the
/// buffer.
pub fn push(&mut self, buf: RangeBuf) -> Result<()> {
if buf.max_off() > self.max_data {
return Err(Error::FlowControl);
}
if let Some(fin_off) = self.fin_off {
// Stream's size is known, forbid data beyond that point.
if buf.max_off() > fin_off {
return Err(Error::FinalSize);
}
// Stream's size is already known, forbid changing it.
if buf.fin() && fin_off != buf.max_off() {
return Err(Error::FinalSize);
}
}
// Stream's known size is lower than data already received.
if buf.fin() && buf.max_off() < self.len {
return Err(Error::FinalSize);
}
// We already saved the final offset, so there's nothing else we
// need to keep from the RangeBuf if it's empty.
if self.fin_off.is_some() && buf.is_empty() {
return Ok(());
}
// No need to process an empty buffer with the fin flag, if we already
// know the final size.
if buf.fin() && buf.is_empty() && self.fin_off.is_some() {
return Ok(());
}
if buf.fin() {
self.fin_off = Some(buf.max_off());
}
// No need to store empty buffer that doesn't carry the fin flag.
if !buf.fin() && buf.is_empty() {
return Ok(());
}
// Check if data is fully duplicate, that is the buffer's max offset is
// lower or equal to the offset already stored in the recv buffer.
if self.off >= buf.max_off() {
// An exception is applied to empty range buffers, because an empty
// buffer's max offset matches the max offset of the recv buffer.
//
// By this point all spurious empty buffers should have already been
// discarded, so allowing empty buffers here should be safe.
if !buf.is_empty() {
return Ok(());
}
}
if self.drain {
return Ok(());
}
let mut tmp_buf = Some(buf);
while let Some(mut buf) = tmp_buf {
tmp_buf = None;
// Discard incoming data below current stream offset. Bytes up to
// `self.off` have already been received so we should not buffer
// them again. This is also important to make sure `ready()` doesn't
// get stuck when a buffer with lower offset than the stream's is
// buffered.
if self.off > buf.off() {
buf = buf.split_off((self.off - buf.off()) as usize);
}
for b in &self.data {
// New buffer is fully contained in existing buffer.
if buf.off() >= b.off() && buf.max_off() <= b.max_off() {
return Ok(());
}
// New buffer's start overlaps existing buffer.
if buf.off() >= b.off() && buf.off() < b.max_off() {
buf = buf.split_off((b.max_off() - buf.off()) as usize);
}
// New buffer's end overlaps existing buffer.
if buf.off() < b.off() && buf.max_off() > b.off() {
tmp_buf = Some(buf.split_off((b.off() - buf.off()) as usize));
}
}
self.len = cmp::max(self.len, buf.max_off());
self.data.push(buf);
}
Ok(())
}
/// Writes data from the receive buffer into the given output buffer.
///
/// Only contiguous data is written to the output buffer, starting from
/// offset 0. The offset is incremented as data is read out of the receive
/// buffer into the application buffer. If there is no data at the expected
/// read offset, the `Done` error is returned.
///
/// On success the amount of data read, and a flag indicating if there is
/// no more data in the buffer, are returned as a tuple.
pub fn pop(&mut self, out: &mut [u8]) -> Result<(usize, bool)> {
let mut len = 0;
let mut cap = out.len();
if !self.ready() {
return Err(Error::Done);
}
while cap > 0 && self.ready() {
let mut buf = match self.data.pop() {
Some(v) => v,
None => break,
};
if buf.len() > cap {
let new_buf = RangeBuf {
data: buf.data.split_off(cap),
off: buf.off + cap as u64,
fin: buf.fin,
};
buf.fin = false;
self.data.push(new_buf);
}
out[len..len + buf.len()].copy_from_slice(&buf.data);
self.off += buf.len() as u64;
len += buf.len();
cap -= buf.len();
}
self.max_data_next = self.max_data_next.saturating_add(len as u64);
Ok((len, self.is_fin()))
}
/// Resets the stream at the given offset.
pub fn reset(&mut self, final_size: u64) -> Result<usize> {
// Stream's size is already known, forbid changing it.
if let Some(fin_off) = self.fin_off {
if fin_off != final_size {
return Err(Error::FinalSize);
}
}
// Stream's known size is lower than data already received.
if final_size < self.len {
return Err(Error::FinalSize);
}
self.fin_off = Some(final_size);
// Return how many bytes need to be removed from the connection flow
// control.
Ok((final_size - self.len) as usize)
}
/// Commits the new max_data limit.
pub fn update_max_data(&mut self) {
self.max_data = self.max_data_next;
}
/// Return the new max_data limit.
pub fn max_data_next(&mut self) -> u64 {
self.max_data_next
}
/// Shuts down receiving data.
pub fn shutdown(&mut self) -> Result<()> {
if self.drain {
return Err(Error::Done);
}
self.drain = true;
self.data.clear();
Ok(())
}
/// Returns the largest offset of data buffered.
#[allow(dead_code)]
pub fn off_back(&self) -> u64 {
self.off
}
/// Returns true if we need to update the local flow control limit.
pub fn almost_full(&self) -> bool {
// Send MAX_STREAM_DATA when the new limit is at least double the
// amount of data that can be received before blocking.
self.fin_off.is_none() &&
self.max_data_next != self.max_data &&
self.max_data_next / 2 > self.max_data - self.len
}
/// Returns true if the receive-side of the stream is complete.
///
/// This happens when the stream's receive final size is known, and the
/// application has read all data from the stream.
pub fn is_fin(&self) -> bool {
if self.fin_off == Some(self.off) {
return true;
}
false
}
/// Returns true if the stream has data to be read.
fn ready(&self) -> bool {
let buf = match self.data.peek() {
Some(v) => v,
None => return false,
};
buf.off == self.off
}
}
/// Send-side stream buffer.
///
/// Stream data scheduled to be sent to the peer is buffered in a list of data
/// chunks ordered by offset in ascending order. Contiguous data can then be
/// read into a slice.
///
/// By default, new data is appended at the end of the stream, but data can be
/// inserted at the start of the buffer (this is to allow data that needs to be
/// retransmitted to be re-buffered).
#[derive(Default)]
pub struct SendBuf {
/// Chunks of data to be sent, ordered by offset.
data: BinaryHeap<RangeBuf>,
/// The maximum offset of data buffered in the stream.
off: u64,
/// The amount of data that was ever written to this stream.
len: u64,
/// The maximum offset we are allowed to send to the peer.
max_data: u64,
/// The final stream offset written to the stream, if any.
fin_off: Option<u64>,
/// Whether the stream's send-side has been shut down.
shutdown: bool,
/// Ranges of data offsets that have been acked.
acked: ranges::RangeSet,
}
impl SendBuf {
/// Creates a new send buffer.
fn new(max_data: u64) -> SendBuf {
SendBuf {
max_data,
..SendBuf::default()
}
}
/// Inserts the given slice of data at the end of the buffer.
///
/// The number of bytes that were actually stored in the buffer is returned
/// (this may be lower than the size of the input buffer, in case of partial
/// writes).
pub fn push_slice(
&mut self, mut data: &[u8], mut fin: bool,
) -> Result<usize> {
let mut len = 0;
if self.shutdown {
// Since we won't write any more data anyway, pretend that we sent
// all data that was passed in.
return Ok(data.len());
}
if data.is_empty() {
// Create a dummy range buffer, in order to propagate the `fin` flag
// into `RangeBuf::push()`. This will be discarded later on.
let buf = RangeBuf::from(&[], self.off, fin);
return self.push(buf).map(|_| 0);
}
if data.len() > self.cap() {
// Truncate the input buffer according to the stream's capacity.
let len = self.cap();
data = &data[..len];
// We are not buffering the full input, so clear the fin flag.
fin = false;
}
// Split the input buffer into multiple RangeBufs. Otherwise a big
// buffer would need to be split later on when popping data, which
// would cause a partial copy of the buffer.
for chunk in data.chunks(MAX_WRITE_SIZE) {
len += chunk.len();
let fin = len == data.len() && fin;
let buf = RangeBuf::from(chunk, self.off, fin);
self.push(buf)?;
self.off += chunk.len() as u64;
}
Ok(data.len())
}
/// Inserts the given chunk of data in the buffer.
pub fn push(&mut self, buf: RangeBuf) -> Result<()> {
if let Some(fin_off) = self.fin_off {
// Can't write past final offset.
if buf.max_off() > fin_off {
return Err(Error::FinalSize);
}
// Can't "undo" final offset.
if buf.max_off() == fin_off && !buf.fin() {
return Err(Error::FinalSize);
}
}
if self.shutdown {
return Ok(());
}
if buf.fin() {
self.fin_off = Some(buf.max_off());
}
// Don't queue data that was already fully acked.
if self.ack_off() >= buf.max_off() {
return Ok(());
}
self.len += buf.len() as u64;
// We already recorded the final offset, so we can just discard the
// empty buffer now.
if buf.is_empty() {
return Ok(());
}
self.data.push(buf);
Ok(())
}
/// Returns contiguous data from the send buffer as a single `RangeBuf`.
pub fn pop(&mut self, max_data: usize) -> Result<RangeBuf> {
let mut out = RangeBuf::default();
out.data =
Vec::with_capacity(cmp::min(max_data as u64, self.len) as usize);
out.off = self.off;
let mut out_len = max_data;
let mut out_off = self.data.peek().map_or_else(|| out.off, RangeBuf::off);
while out_len > 0 &&
self.ready() &&
self.off_front() == out_off &&
self.off_front() < self.max_data
{
let mut buf = match self.data.pop() {
Some(v) => v,
None => break,
};
if buf.len() > out_len || buf.max_off() > self.max_data {
let new_len =
cmp::min(out_len, (self.max_data - buf.off()) as usize);
let new_buf = buf.split_off(new_len);
self.data.push(new_buf);
}
if out.is_empty() {
out.off = buf.off;
}
self.len -= buf.len() as u64;
out_len -= buf.len();
out_off = buf.max_off();
out.data.extend_from_slice(&buf.data);
}
// Override the `fin` flag set for the output buffer by matching the
// buffer's maximum offset against the stream's final offset (if known).
//
// This is more efficient than tracking `fin` using the range buffers
// themselves, and lets us avoid queueing empty buffers just so we can
// propagate the final size.
out.fin = self.fin_off == Some(out.max_off());
Ok(out)
}
/// Updates the max_data limit to the given value.
pub fn update_max_data(&mut self, max_data: u64) {
self.max_data = cmp::max(self.max_data, max_data);
}
/// Increments the acked data offset.