-
-
Notifications
You must be signed in to change notification settings - Fork 423
/
Copy pathmod.rs
3269 lines (3023 loc) · 123 KB
/
mod.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
use std::{
cmp,
collections::{BTreeMap, VecDeque},
fmt, io, mem,
net::SocketAddr,
sync::Arc,
time::{Duration, Instant},
};
use bytes::{Bytes, BytesMut};
use rand::{rngs::StdRng, Rng, SeedableRng};
use thiserror::Error;
use tracing::{debug, error, trace, trace_span, warn};
use crate::{
cid_queue::CidQueue,
coding::BufMutExt,
config::{ServerConfig, TransportConfig},
crypto::{self, HeaderKey, KeyPair, Keys, PacketKey},
frame,
frame::{Close, Datagram, FrameStruct},
is_supported_version,
packet::{Header, LongType, Packet, PacketNumber, PartialDecode, PartialEncode, SpaceId},
range_set::RangeSet,
shared::{
ConnectionEvent, ConnectionEventInner, ConnectionId, EcnCodepoint, EndpointEvent,
EndpointEventInner, IssuedCid,
},
transport_parameters::TransportParameters,
Dir, Frame, Side, StreamId, Transmit, TransportError, TransportErrorCode, VarInt,
LOC_CID_COUNT, MAX_STREAM_COUNT, MIN_INITIAL_SIZE, MIN_MTU, RESET_TOKEN_SIZE,
TIMER_GRANULARITY,
};
mod assembler;
mod pacing;
mod paths;
use paths::PathData;
mod send_buffer;
mod spaces;
use spaces::{PacketSpace, Retransmits, SentPacket};
mod streams;
pub use streams::Streams;
pub use streams::{FinishError, ReadError, StreamEvent, UnknownStream, WriteError};
mod timer;
use timer::{Timer, TimerTable};
/// Protocol state and logic for a single QUIC connection
///
/// Objects of this type receive `ConnectionEvent`s and emit `EndpointEvents` and application
/// `Event`s to make progress. To handle timeouts, a `Connection` returns timer updates and
/// expects timeouts through various methods. A number of simple getter methods are exposed
/// to allow callers to inspect some of the connection state.
pub struct Connection<S>
where
S: crypto::Session,
{
server_config: Option<Arc<ServerConfig<S>>>,
config: Arc<TransportConfig>,
rng: StdRng,
crypto: S,
/// The CID we initially chose, for use during the handshake
handshake_cid: ConnectionId,
/// The destination CID we're currently sending to
///
/// The earliest value in a sliding window of CIDs issued by the peer.
rem_cid: ConnectionId,
/// The CID the peer initially chose, for use during the handshake
rem_handshake_cid: ConnectionId,
/// Sequence number of `rem_cid`
///
/// Exactly one prior to `self.rem_cids.offset` except during processing of certain
/// NEW_CONNECTION_ID frames.
rem_cid_seq: u64,
/// cid length used to decode short packet
local_cid_len: usize,
path: PathData,
prev_path: Option<PathData>,
state: State,
side: Side,
mtu: u16,
/// Whether or not 0-RTT was enabled during the handshake. Does not imply acceptance.
zero_rtt_enabled: bool,
/// Set if 0-RTT is supported, then cleared when no longer needed.
zero_rtt_crypto: Option<ZeroRttCrypto<S>>,
key_phase: bool,
/// Transport parameters set by the peer
peer_params: TransportParameters,
/// Source ConnectionId of the first packet received from the peer
orig_rem_cid: ConnectionId,
/// Destination ConnectionId sent by the client on the first Initial
initial_dst_cid: ConnectionId,
/// The value that the server included in the Source Connection ID field of a Retry packet, if
/// one was received
retry_src_cid: Option<ConnectionId>,
/// Total number of outgoing packets that have been deemed lost
lost_packets: u64,
events: VecDeque<Event>,
endpoint_events: VecDeque<EndpointEventInner>,
/// Number of local connection IDs that have been issued in NEW_CONNECTION_ID frames.
cids_issued: u64,
/// Whether the spin bit is in use for this connection
spin_enabled: bool,
/// Outgoing spin bit state
spin: bool,
/// Packet number spaces: initial, handshake, 1-RTT
spaces: [PacketSpace<S>; 3],
/// Highest usable packet number space
highest_space: SpaceId,
/// 1-RTT keys used prior to a key update
prev_crypto: Option<PrevCrypto<S::PacketKey>>,
/// 1-RTT keys to be used for the next key update
///
/// These are generated in advance to prevent timing attacks and/or DoS by third-party attackers
/// spoofing key updates.
next_crypto: Option<KeyPair<S::PacketKey>>,
accepted_0rtt: bool,
/// Whether the idle timer should be reset the next time an ack-eliciting packet is transmitted.
permit_idle_reset: bool,
/// Negotiated idle timeout
idle_timeout: Option<Duration>,
timers: TimerTable,
/// Number of packets received which could not be authenticated
authentication_failures: u64,
//
// Queued non-retransmittable 1-RTT data
//
path_response: Option<PathResponse>,
close: bool,
//
// Loss Detection
//
/// The number of times a PTO has been sent without receiving an ack.
pto_count: u32,
//
// Congestion Control
//
/// Summary statistics of packets that have been sent, but not yet acked or deemed lost
in_flight: InFlight,
/// Whether the most recently received packet had an ECN codepoint set
receiving_ecn: bool,
/// Whether the remote address used to initiate the connection has been validated. Not used for
/// validating migration; see path_challenge.
remote_validated: bool,
/// Total UDP datagram bytes received, tracked for handshake anti-amplification
total_recvd: u64,
/// Number of packets authenticated
total_authed_packets: u64,
total_sent: u64,
streams: Streams,
/// Surplus remote CIDs for future use on new paths
rem_cids: CidQueue,
/// State of the unreliable datagram extension
datagrams: DatagramState,
}
impl<S> Connection<S>
where
S: crypto::Session,
{
pub(crate) fn new(
server_config: Option<Arc<ServerConfig<S>>>,
config: Arc<TransportConfig>,
init_cid: ConnectionId,
loc_cid: ConnectionId,
rem_cid: ConnectionId,
remote: SocketAddr,
crypto: S,
now: Instant,
local_cid_len: usize,
) -> Self {
let side = if server_config.is_some() {
Side::Server
} else {
Side::Client
};
let initial_space = PacketSpace {
crypto: Some(S::initial_keys(&init_cid, side)),
..PacketSpace::new(now)
};
let state = State::Handshake(state::Handshake {
rem_cid_set: side.is_server(),
token: None,
client_hello: None,
});
let mut rng = StdRng::from_entropy();
let remote_validated = server_config
.as_ref()
.map_or(false, |c| c.use_stateless_retry);
let mut this = Self {
server_config,
crypto,
handshake_cid: loc_cid,
rem_cid,
rem_handshake_cid: rem_cid,
rem_cid_seq: 0,
local_cid_len,
path: PathData::new(
remote,
config.initial_rtt,
config.congestion_controller_factory.build(now),
now,
),
prev_path: None,
side,
state,
mtu: MIN_MTU,
zero_rtt_enabled: false,
zero_rtt_crypto: None,
key_phase: false,
peer_params: TransportParameters::default(),
orig_rem_cid: rem_cid,
initial_dst_cid: init_cid,
retry_src_cid: None,
lost_packets: 0,
events: VecDeque::new(),
endpoint_events: VecDeque::new(),
cids_issued: 0,
spin_enabled: config.allow_spin && rng.gen_ratio(7, 8),
spin: false,
spaces: [initial_space, PacketSpace::new(now), PacketSpace::new(now)],
highest_space: SpaceId::Initial,
prev_crypto: None,
next_crypto: None,
accepted_0rtt: false,
permit_idle_reset: true,
idle_timeout: config.max_idle_timeout,
timers: TimerTable::default(),
authentication_failures: 0,
path_response: None,
close: false,
pto_count: 0,
in_flight: InFlight::new(),
receiving_ecn: false,
remote_validated,
total_recvd: 0,
total_authed_packets: 0,
total_sent: 0,
streams: Streams::new(
side,
config.stream_window_uni,
config.stream_window_bidi,
config.send_window,
config.receive_window,
config.stream_receive_window,
),
datagrams: DatagramState::new(),
config,
rem_cids: CidQueue::new(1),
rng,
};
if side.is_client() {
// Kick off the connection
this.write_crypto();
this.init_0rtt();
}
this
}
/// Returns the next time at which `handle_timeout` should be called
///
/// The value returned may change after:
/// - the application performed some I/O on the connection
/// - a call was made to `handle_event`
/// - a call to `poll_transmit` returned `Some`
/// - a call was made to `handle_timeout`
pub fn poll_timeout(&mut self) -> Option<Instant> {
self.timers.next_timeout()
}
/// Returns application-facing events
///
/// Connections should be polled for events after:
/// - a call was made to `handle_event`
/// - a call was made to `handle_timeout`
pub fn poll(&mut self) -> Option<Event> {
if let Some(event) = self.streams.poll() {
return Some(Event::Stream(event));
}
if let Some(x) = self.events.pop_front() {
return Some(x);
}
None
}
/// Return endpoint-facing events
pub fn poll_endpoint_events(&mut self) -> Option<EndpointEvent> {
self.endpoint_events.pop_front().map(EndpointEvent)
}
/// Returns packets to transmit
///
/// Connections should be polled for transmit after:
/// - the application performed some I/O on the connection
/// - a call was made to `handle_event`
/// - a call was made to `handle_timeout`
pub fn poll_transmit(&mut self, now: Instant) -> Option<Transmit> {
if self.anti_amplification_blocked() {
trace!("blocked by anti-amplification");
return None;
}
// Send PATH_CHALLENGE for a previous path if necessary
if let Some(ref mut prev_path) = self.prev_path {
if prev_path.challenge_pending {
prev_path.challenge_pending = false;
let token = prev_path
.challenge
.expect("previous path challenge pending without token");
let destination = prev_path.remote;
debug_assert_eq!(
self.highest_space,
SpaceId::Data,
"PATH_CHALLENGE queued without 1-RTT keys"
);
let mut buf = Vec::with_capacity(self.mtu as usize);
let builder = self.begin_packet(now, SpaceId::Data, false, &mut buf)?;
trace!("validating previous path with PATH_CHALLENGE {:08x}", token);
builder.buffer.write(frame::Type::PATH_CHALLENGE);
builder.buffer.write(token);
self.finish_packet(builder);
return Some(Transmit {
destination,
contents: buf,
ecn: None,
});
}
}
// If we need to send a probe, make sure we have something to send.
for space in SpaceId::iter() {
if self.spaces[space].loss_probes != 0 {
self.ensure_probe_queued(space);
}
}
// Select the set of spaces that have data to send so we can try to coalesce them
let (spaces, close) = match self.state {
State::Drained => {
return None;
}
State::Draining | State::Closed(_) => {
if mem::replace(&mut self.close, false) {
(vec![self.highest_space], true)
} else {
return None;
}
}
_ => (
SpaceId::iter()
.filter(|&x| {
(self.spaces[x].crypto.is_some() && self.spaces[x].can_send())
|| (x == SpaceId::Data
&& ((self.spaces[x].crypto.is_some() && self.can_send_1rtt())
|| (self.zero_rtt_crypto.is_some()
&& self.side.is_client()
&& (self.spaces[x].can_send() || self.can_send_1rtt()))))
})
.collect(),
false,
),
};
let mut buf = Vec::with_capacity(self.mtu as usize);
let mut coalesce = spaces.len() > 1;
let pad_space = spaces.last().cloned().filter(|_| {
self.side.is_client() && spaces.first() == Some(&SpaceId::Initial)
|| self.path.challenge.is_some()
|| self.path_response.is_some()
});
for space_id in spaces {
let buf_start = buf.len();
let mut ack_eliciting =
!self.spaces[space_id].pending.is_empty() || self.spaces[space_id].ping_pending;
if space_id == SpaceId::Data {
ack_eliciting |= self.can_send_1rtt();
// Tail loss probes must not be blocked by congestion, or a deadlock could arise
if ack_eliciting && self.spaces[space_id].loss_probes == 0 {
if self.congestion_blocked() {
continue;
}
let smoothed_rtt = self.path.rtt.conservative();
let window = self.path.congestion.window();
if let Some(delay) = self.path.pacing.delay(smoothed_rtt, self.mtu, window, now)
{
self.timers.set(Timer::Pacing, delay);
continue;
}
}
}
//
// From here on, we've determined that a packet will definitely be sent.
//
if self.spaces[SpaceId::Initial].crypto.is_some()
&& space_id == SpaceId::Handshake
&& self.side.is_client()
{
// A client stops both sending and processing Initial packets when it
// sends its first Handshake packet.
self.discard_space(now, SpaceId::Initial);
}
if let Some(ref mut prev) = self.prev_crypto {
prev.update_unacked = false;
}
let mut builder =
self.begin_packet(now, space_id, pad_space == Some(space_id), &mut buf)?;
coalesce = coalesce && !builder.short_header;
let sent = if close {
trace!("sending CONNECTION_CLOSE");
match self.state {
State::Closed(state::Closed { ref reason }) => {
if space_id == SpaceId::Data {
reason.encode(&mut builder.buffer, builder.max_size)
} else {
frame::ConnectionClose {
error_code: TransportErrorCode::APPLICATION_ERROR,
frame_type: None,
reason: Bytes::new(),
}
.encode(&mut builder.buffer, builder.max_size)
}
}
State::Draining => frame::ConnectionClose {
error_code: TransportErrorCode::NO_ERROR,
frame_type: None,
reason: Bytes::new(),
}
.encode(&mut builder.buffer, builder.max_size),
_ => unreachable!(
"tried to make a close packet when the connection wasn't closed"
),
}
coalesce = false;
None
} else {
Some(self.populate_packet(space_id, &mut builder.buffer))
};
let exact_number = builder.exact_number;
let padded = self.finish_packet(builder);
if let Some(mut sent) = sent {
sent.padding = padded;
// If we sent any acks, don't immediately resend them. Setting this even if ack_only is
// false needlessly prevents us from ACKing the next packet if it's ACK-only, but saves
// the need for subtler logic to avoid double-transmitting acks all the time.
self.spaces[space_id].permit_ack_only &= sent.acks.is_empty();
self.on_packet_sent(
now,
space_id,
exact_number,
SentPacket {
acks: sent.acks,
time_sent: now,
size: if sent.padding || ack_eliciting {
(buf.len() - buf_start) as u16
} else {
0
},
ack_eliciting,
retransmits: sent.retransmits,
stream_frames: sent.stream_frames,
},
);
}
if !coalesce || buf.capacity() - buf.len() < MIN_PACKET_SPACE {
break;
}
}
if buf.is_empty() {
return None;
}
trace!("sending {} byte datagram", buf.len());
self.total_sent = self.total_sent.wrapping_add(buf.len() as u64);
Some(Transmit {
destination: self.path.remote,
contents: buf,
ecn: if self.path.sending_ecn {
Some(EcnCodepoint::ECT0)
} else {
None
},
})
}
/// Write a new packet header to `buffer` and determine the packet's properties
///
/// Marks the connection drained and returns `None` if the confidentiality limit would be
/// violated.
fn begin_packet<'a>(
&mut self,
now: Instant,
space_id: SpaceId,
initial_padding: bool,
buffer: &'a mut Vec<u8>,
) -> Option<PacketBuilder<'a>> {
// Initiate key update if we're approaching the confidentiality limit
let confidentiality_limit = self.spaces[space_id]
.crypto
.as_ref()
.map_or_else(
|| &self.zero_rtt_crypto.as_ref().unwrap().packet,
|keys| &keys.packet.local,
)
.confidentiality_limit();
let sent_with_keys = self.spaces[space_id].sent_with_keys;
if space_id == SpaceId::Data {
if sent_with_keys.saturating_add(KEY_UPDATE_MARGIN) >= confidentiality_limit {
self.initiate_key_update();
}
} else if sent_with_keys.saturating_add(1) == confidentiality_limit {
// We still have time to attempt a graceful close
self.close_inner(
now,
Close::Connection(frame::ConnectionClose {
error_code: TransportErrorCode::AEAD_LIMIT_REACHED,
frame_type: None,
reason: Bytes::from_static(b"confidentiality limit reached"),
}),
)
} else if sent_with_keys > confidentiality_limit {
// Confidentiality limited violated and there's nothing we can do
self.kill(TransportError::AEAD_LIMIT_REACHED("confidentiality limit reached").into());
return None;
}
let space = &mut self.spaces[space_id];
space.loss_probes = space.loss_probes.saturating_sub(1);
let exact_number = space.get_tx_number();
let span = trace_span!("send", space = ?space_id, pn = exact_number);
span.with_subscriber(|(id, dispatch)| dispatch.enter(id));
let number = PacketNumber::new(exact_number, space.largest_acked_packet.unwrap_or(0));
let header = match space_id {
SpaceId::Data if space.crypto.is_some() => Header::Short {
dst_cid: self.rem_cid,
number,
spin: if self.spin_enabled {
self.spin
} else {
self.rng.gen()
},
key_phase: self.key_phase,
},
SpaceId::Data => Header::Long {
ty: LongType::ZeroRtt,
src_cid: self.handshake_cid,
dst_cid: self.rem_cid,
number,
},
SpaceId::Handshake => Header::Long {
ty: LongType::Handshake,
src_cid: self.handshake_cid,
dst_cid: self.rem_cid,
number,
},
SpaceId::Initial => Header::Initial {
src_cid: self.handshake_cid,
dst_cid: self.rem_cid,
token: match self.state {
State::Handshake(ref state) => state.token.clone().unwrap_or_else(Bytes::new),
_ => Bytes::new(),
},
number,
},
};
let partial_encode = header.encode(buffer);
let (sample_size, tag_len) = if let Some(ref crypto) = space.crypto {
(
crypto.header.local.sample_size(),
crypto.packet.local.tag_len(),
)
} else if space_id == SpaceId::Data {
let zero_rtt = self.zero_rtt_crypto.as_ref().unwrap();
(zero_rtt.header.sample_size(), zero_rtt.packet.tag_len())
} else {
unreachable!("tried to send {:?} packet without keys", space_id);
};
let min_size = if initial_padding {
// Initial packet, must be padded to mitigate amplification attacks
MIN_INITIAL_SIZE - tag_len
} else {
// Regular packet, must be large enough for header protection sampling, i.e. the
// combined lengths of the encoded packet number and protected payload must be at
// least 4 bytes longer than the sample required for header protection
// pn_len + payload_len + tag_len >= sample_size + 4
// payload_len >= sample_size + 4 - pn_len - tag_len
buffer.len() + (sample_size + 4).saturating_sub(number.len() + tag_len)
};
let max_size =
buffer.capacity() - partial_encode.start - partial_encode.header_len - tag_len;
Some(PacketBuilder {
buffer,
space: space_id,
partial_encode,
exact_number,
short_header: header.is_short(),
min_size,
max_size,
span,
})
}
/// Encrypt packet, returning whether padding was added
fn finish_packet(&self, builder: PacketBuilder<'_>) -> bool {
let pad = builder.buffer.len() < builder.min_size;
if pad {
trace!("PADDING * {}", builder.min_size - builder.buffer.len());
builder.buffer.resize(builder.min_size, 0);
}
let space = &self.spaces[builder.space];
let (header_crypto, packet_crypto) = if let Some(ref crypto) = space.crypto {
(&crypto.header.local, &crypto.packet.local)
} else if builder.space == SpaceId::Data {
let zero_rtt = self.zero_rtt_crypto.as_ref().unwrap();
(&zero_rtt.header, &zero_rtt.packet)
} else {
unreachable!("tried to send {:?} packet without keys", builder.space);
};
builder
.buffer
.resize(builder.buffer.len() + packet_crypto.tag_len(), 0);
debug_assert!(builder.buffer.len() < self.mtu as usize);
let packet_buf = &mut builder.buffer[builder.partial_encode.start..];
builder.partial_encode.finish(
packet_buf,
header_crypto,
Some((builder.exact_number, packet_crypto)),
);
builder
.span
.with_subscriber(|(id, dispatch)| dispatch.exit(id));
pad
}
/// Indicates whether we're a server that hasn't validated the peer's address and hasn't
/// received enough data from the peer to permit additional sending
fn anti_amplification_blocked(&self) -> bool {
self.state.is_handshake()
&& !self.remote_validated
&& self.side.is_server()
&& self.total_recvd * 3 < self.total_sent + u64::from(self.mtu)
}
/// Process `ConnectionEvent`s generated by the associated `Endpoint`
///
/// Will execute protocol logic upon receipt of a connection event, in turn preparing signals
/// (including application `Event`s, `EndpointEvent`s and outgoing datagrams) that should be
/// extracted through the relevant methods.
pub fn handle_event(&mut self, event: ConnectionEvent) {
use self::ConnectionEventInner::*;
match event.0 {
Datagram {
now,
remote,
ecn,
first_decode,
remaining,
} => {
// If this packet could initiate a migration and we're a client or a server that
// forbids migration, drop the datagram. This could be relaxed to heuristically
// permit NAT-rebinding-like migration.
if remote != self.path.remote
&& self.server_config.as_ref().map_or(true, |x| !x.migration)
{
trace!("discarding packet from unrecognized peer {}", remote);
return;
}
self.total_recvd = self.total_recvd.wrapping_add(first_decode.len() as u64);
self.handle_decode(now, remote, ecn, first_decode);
if let Some(data) = remaining {
self.handle_coalesced(now, remote, ecn, data);
}
}
NewIdentifiers(ids) => {
ids.into_iter().rev().for_each(|frame| {
self.spaces[SpaceId::Data].pending.new_cids.push(frame);
});
}
}
}
/// Process timer expirations
///
/// Executes protocol logic, potentially preparing signals (including application `Event`s,
/// `EndpointEvent`s and outgoing datagrams) that should be extracted through the relevant
/// methods.
pub fn handle_timeout(&mut self, now: Instant) {
for &timer in &Timer::VALUES {
if !self.timers.is_expired(timer, now) {
continue;
}
self.timers.stop(timer);
trace!(timer = ?timer, "timeout");
match timer {
Timer::Close => {
self.state = State::Drained;
self.endpoint_events.push_back(EndpointEventInner::Drained);
}
Timer::Idle => {
self.kill(ConnectionError::TimedOut);
}
Timer::KeepAlive => {
trace!("sending keep-alive");
self.ping();
}
Timer::LossDetection => {
self.on_loss_detection_timeout(now);
}
Timer::KeyDiscard => {
self.zero_rtt_crypto = None;
self.prev_crypto = None;
}
Timer::PathValidation => {
debug!("path validation failed");
if let Some(prev) = self.prev_path.take() {
self.path = prev;
}
self.path.challenge = None;
self.path.challenge_pending = false;
}
Timer::Pacing => trace!("pacing timer expired"),
}
}
}
/// Close a connection immediately
///
/// This does not ensure delivery of outstanding data. It is the application's responsibility to
/// call this only when all important communications have been completed, e.g. by calling
/// [`Connection::finish`] on outstanding streams and waiting for the corresponding
/// [`StreamEvent::Finished`] event.
///
/// If [`Connection::send_streams`] returns 0, all outstanding stream data has been
/// delivered. There may still be data from the peer that has not been received.
///
/// [`StreamEvent::Finished`]: crate::StreamEvent::Finished
pub fn close(&mut self, now: Instant, error_code: VarInt, reason: Bytes) {
self.close_inner(
now,
Close::Application(frame::ApplicationClose { error_code, reason }),
)
}
fn close_inner(&mut self, now: Instant, reason: Close) {
let was_closed = self.state.is_closed();
if !was_closed {
self.close_common();
self.set_close_timer(now);
self.close = true;
self.state = State::Closed(state::Closed { reason });
}
}
/// Open a single stream if possible
///
/// Returns `None` if the streams in the given direction are currently exhausted.
pub fn open(&mut self, dir: Dir) -> Option<StreamId> {
if self.state.is_closed() {
return None;
}
// TODO: Queue STREAM_ID_BLOCKED if this fails
let id = self.streams.open(&self.peer_params, dir)?;
Some(id)
}
/// Accept a remotely initiated stream of a certain directionality, if possible
///
/// Returns `None` if there are no new incoming streams for this connection.
pub fn accept(&mut self, dir: Dir) -> Option<StreamId> {
let id = self.streams.accept(dir)?;
self.alloc_remote_stream(id.dir());
Some(id)
}
/// Read from the given recv stream, in undefined order
///
/// While stream data is typically processed by applications in-order, unordered reads improve
/// performance when packet loss occurs and data cannot be retransmitted before the flow control
/// window is filled. When in-order delivery is required, the sibling `read()` method should be
/// used.
///
/// The return value if `Ok` contains the bytes and their offset in the stream.
pub fn read_unordered(&mut self, id: StreamId) -> Result<Option<(Bytes, u64)>, ReadError> {
Ok(self.streams.read_unordered(id)?.map(|(buf, offset, more)| {
self.add_read_credits(id, more);
(buf, offset)
}))
}
/// Read from the given recv stream
pub fn read(&mut self, id: StreamId, buf: &mut [u8]) -> Result<Option<usize>, ReadError> {
Ok(self.streams.read(id, buf)?.map(|(len, more)| {
self.add_read_credits(id, more);
len
}))
}
/// Send data on the given stream
///
/// Returns the number of bytes successfully written.
pub fn write(&mut self, stream: StreamId, data: &[u8]) -> Result<usize, WriteError> {
assert!(stream.dir() == Dir::Bi || stream.initiator() == self.side);
if self.state.is_closed() {
trace!(%stream, "write blocked; connection draining");
return Err(WriteError::Blocked);
}
self.streams.write(stream, data)
}
/// Stop accepting data on the given receive stream
///
/// Discards unread data and notifies the peer to stop transmitting. Once stopped, a stream
/// cannot be read from any further.
pub fn stop(&mut self, id: StreamId, error_code: VarInt) -> Result<(), UnknownStream> {
assert!(
id.dir() == Dir::Bi || id.initiator() != self.side,
"only streams supporting incoming data may be stopped"
);
// Only bother if there's data we haven't received yet
if self.streams.stop(id)? {
let space = &mut self.spaces[SpaceId::Data];
space
.pending
.stop_sending
.push(frame::StopSending { id, error_code });
}
Ok(())
}
/// Check if this stream was stopped, get the reason if it was
pub fn stopped(&mut self, id: StreamId) -> Result<Option<VarInt>, UnknownStream> {
self.streams.stop_reason(id)
}
/// Finish a send stream, signalling that no more data will be sent.
///
/// If this fails, no [`StreamEvent::Finished`] will be generated.
///
/// [`StreamEvent::Finished`]: crate::StreamEvent::Finished
pub fn finish(&mut self, id: StreamId) -> Result<(), FinishError> {
self.streams.finish(id)?;
Ok(())
}
/// Prepare to transmit an unreliable, unordered datagram
///
/// The returned `DatagramSender` must be used to actually send a datagram. This allows the
/// caller to defer materializing a datagram until one can be sent immediately without redundant
/// checks
///
/// Returns `Err` iff a `len`-byte datagram cannot currently be sent
pub fn send_datagram(&mut self, data: Bytes) -> Result<(), SendDatagramError> {
if self.config.datagram_receive_buffer_size.is_none() {
return Err(SendDatagramError::Disabled);
}
let max = self
.max_datagram_size()
.ok_or(SendDatagramError::UnsupportedByPeer)?;
while self.datagrams.outgoing_total > self.config.datagram_send_buffer_size {
let prev = self
.datagrams
.outgoing
.pop_front()
.expect("datagrams.outgoing_total desynchronized");
trace!(len = prev.data.len(), "dropping outgoing datagram");
self.datagrams.outgoing_total -= prev.data.len();
}
if data.len() > max {
return Err(SendDatagramError::TooLarge);
}
self.datagrams.outgoing_total += data.len();
self.datagrams.outgoing.push_back(Datagram { data });
Ok(())
}
/// Receive an unreliable, unordered datagram
pub fn recv_datagram(&mut self) -> Option<Bytes> {
let x = self.datagrams.incoming.pop_front()?.data;
self.datagrams.recv_buffered -= x.len();
Some(x)
}
/// Compute the maximum size of datagrams that may passed to `send_datagram`
///
/// Returns `None` if datagrams are unsupported by the peer or disabled locally.
///
/// This may change over the lifetime of a connection according to variation in the path MTU
/// estimate. The peer can also enforce an arbitrarily small fixed limit, but if the peer's
/// limit is large this is guaranteed to be a little over a kilobyte at minimum.
///
/// Not necessarily the maximum size of received datagrams.
pub fn max_datagram_size(&self) -> Option<usize> {
// This is usually 1182 bytes, but we shouldn't document that without a doctest.
let max_size = self.mtu as usize
- 1 // flags byte
- self.rem_cid.len()
- 4 // worst-case packet number size
- self.spaces[SpaceId::Data].crypto.as_ref().map_or_else(|| &self.zero_rtt_crypto.as_ref().unwrap().packet, |x| &x.packet.local).tag_len()
- Datagram::SIZE_BOUND;
let limit = self.peer_params.max_datagram_frame_size?.into_inner();
Some(limit.min(max_size as u64) as usize)
}
/// Ping the remote endpoint
///
/// Causes an ACK-eliciting packet to be transmitted.
pub fn ping(&mut self) {
self.spaces[self.highest_space].ping_pending = true;
}
#[doc(hidden)]
pub fn initiate_key_update(&mut self) {
self.update_keys(None, false);
}
/// Get a session reference
pub fn crypto_session(&self) -> &S {
&self.crypto
}
/// The number of streams that may have unacknowledged data.
pub fn send_streams(&self) -> usize {
self.streams.send_streams()
}
/// Whether the connection is in the process of being established
///
/// If this returns `false`, the connection may be either established or closed, signaled by the
/// emission of a `Connected` or `ConnectionLost` message respectively.
pub fn is_handshaking(&self) -> bool {
self.state.is_handshake()
}
/// Whether the connection is closed
///
/// Closed connections cannot transport any further data. A connection becomes closed when
/// either peer application intentionally closes it, or when either transport layer detects an
/// error such as a time-out or certificate validation failure.
///
/// A `ConnectionLost` event is emitted with details when the connection becomes closed.
pub fn is_closed(&self) -> bool {
self.state.is_closed()
}
/// Whether there is no longer any need to keep the connection around
///
/// Closed connections become drained after a brief timeout to absorb any remaining in-flight
/// packets from the peer. All drained connections have been closed.
pub fn is_drained(&self) -> bool {
self.state.is_drained()
}
/// For clients, if the peer accepted the 0-RTT data packets
///
/// The value is meaningless until after the handshake completes.
pub fn accepted_0rtt(&self) -> bool {
self.accepted_0rtt
}
/// Whether 0-RTT is/was possible during the handshake
pub fn has_0rtt(&self) -> bool {
self.zero_rtt_enabled
}
/// Look up whether we're the client or server of this Connection
pub fn side(&self) -> Side {
self.side