-
-
Notifications
You must be signed in to change notification settings - Fork 400
/
endpoint.rs
1290 lines (1178 loc) · 44.8 KB
/
endpoint.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::{
collections::{hash_map, HashMap},
convert::TryFrom,
fmt, mem,
net::{IpAddr, SocketAddr},
ops::{Index, IndexMut},
sync::Arc,
time::{Instant, SystemTime},
};
use bytes::{BufMut, Bytes, BytesMut};
use rand::{rngs::StdRng, Rng, RngCore, SeedableRng};
use rustc_hash::FxHashMap;
use slab::Slab;
use thiserror::Error;
use tracing::{debug, error, trace, warn};
use crate::{
cid_generator::{ConnectionIdGenerator, RandomConnectionIdGenerator},
coding::BufMutExt,
config::{ClientConfig, EndpointConfig, ServerConfig},
connection::{Connection, ConnectionError},
crypto::{self, Keys, UnsupportedVersion},
frame,
packet::{
Header, InitialHeader, InitialPacket, Packet, PacketDecodeError, PacketNumber,
PartialDecode, PlainInitialHeader,
},
shared::{
ConnectionEvent, ConnectionEventInner, ConnectionId, DatagramConnectionEvent, EcnCodepoint,
EndpointEvent, EndpointEventInner, IssuedCid,
},
token::TokenDecodeError,
transport_parameters::{PreferredAddress, TransportParameters},
ResetToken, RetryToken, Transmit, TransportConfig, TransportError, INITIAL_MTU, MAX_CID_SIZE,
MIN_INITIAL_SIZE, RESET_TOKEN_SIZE,
};
/// The main entry point to the library
///
/// This object performs no I/O whatsoever. Instead, it consumes incoming packets and
/// connection-generated events via `handle` and `handle_event`.
pub struct Endpoint {
rng: StdRng,
index: ConnectionIndex,
connections: Slab<ConnectionMeta>,
local_cid_generator: Box<dyn ConnectionIdGenerator>,
config: Arc<EndpointConfig>,
server_config: Option<Arc<ServerConfig>>,
/// Whether the underlying UDP socket promises not to fragment packets
allow_mtud: bool,
/// Time at which a stateless reset was most recently sent
last_stateless_reset: Option<Instant>,
/// Buffered Initial and 0-RTT messages for pending incoming connections
incoming_buffers: Slab<IncomingBuffer>,
all_incoming_buffers_total_bytes: u64,
}
impl Endpoint {
/// Create a new endpoint
///
/// `allow_mtud` enables path MTU detection when requested by `Connection` configuration for
/// better performance. This requires that outgoing packets are never fragmented, which can be
/// achieved via e.g. the `IPV6_DONTFRAG` socket option.
pub fn new(
config: Arc<EndpointConfig>,
server_config: Option<Arc<ServerConfig>>,
allow_mtud: bool,
rng_seed: Option<[u8; 32]>,
) -> Self {
Self {
rng: rng_seed.map_or(StdRng::from_entropy(), StdRng::from_seed),
index: ConnectionIndex::default(),
connections: Slab::new(),
local_cid_generator: (config.connection_id_generator_factory.as_ref())(),
config,
server_config,
allow_mtud,
last_stateless_reset: None,
incoming_buffers: Slab::new(),
all_incoming_buffers_total_bytes: 0,
}
}
/// Replace the server configuration, affecting new incoming connections only
pub fn set_server_config(&mut self, server_config: Option<Arc<ServerConfig>>) {
self.server_config = server_config;
}
/// Process `EndpointEvent`s emitted from related `Connection`s
///
/// In turn, processing this event may return a `ConnectionEvent` for the same `Connection`.
pub fn handle_event(
&mut self,
ch: ConnectionHandle,
event: EndpointEvent,
) -> Option<ConnectionEvent> {
use EndpointEventInner::*;
match event.0 {
NeedIdentifiers(now, n) => {
return Some(self.send_new_identifiers(now, ch, n));
}
ResetToken(remote, token) => {
if let Some(old) = self.connections[ch].reset_token.replace((remote, token)) {
self.index.connection_reset_tokens.remove(old.0, old.1);
}
if self.index.connection_reset_tokens.insert(remote, token, ch) {
warn!("duplicate reset token");
}
}
RetireConnectionId(now, seq, allow_more_cids) => {
if let Some(cid) = self.connections[ch].loc_cids.remove(&seq) {
trace!("peer retired CID {}: {}", seq, cid);
self.index.retire(&cid);
if allow_more_cids {
return Some(self.send_new_identifiers(now, ch, 1));
}
}
}
Drained => {
if let Some(conn) = self.connections.try_remove(ch.0) {
self.index.remove(&conn);
} else {
// This indicates a bug in downstream code, which could cause spurious
// connection loss instead of this error if the CID was (re)allocated prior to
// the illegal call.
error!(id = ch.0, "unknown connection drained");
}
}
}
None
}
/// Process an incoming UDP datagram
pub fn handle(
&mut self,
now: Instant,
remote: SocketAddr,
local_ip: Option<IpAddr>,
ecn: Option<EcnCodepoint>,
data: BytesMut,
buf: &mut Vec<u8>,
) -> Option<DatagramEvent> {
let datagram_len = data.len();
let (first_decode, remaining) = match PartialDecode::new(
data,
self.local_cid_generator.cid_len(),
&self.config.supported_versions,
self.config.grease_quic_bit,
) {
Ok(x) => x,
Err(PacketDecodeError::UnsupportedVersion {
src_cid,
dst_cid,
version,
}) => {
if self.server_config.is_none() {
debug!("dropping packet with unsupported version");
return None;
}
trace!("sending version negotiation");
// Negotiate versions
Header::VersionNegotiate {
random: self.rng.gen::<u8>() | 0x40,
src_cid: dst_cid,
dst_cid: src_cid,
}
.encode(buf);
// Grease with a reserved version
if version != 0x0a1a_2a3a {
buf.write::<u32>(0x0a1a_2a3a);
} else {
buf.write::<u32>(0x0a1a_2a4a);
}
for &version in &self.config.supported_versions {
buf.write(version);
}
return Some(DatagramEvent::Response(Transmit {
destination: remote,
ecn: None,
size: buf.len(),
segment_size: None,
src_ip: local_ip,
}));
}
Err(e) => {
trace!("malformed header: {}", e);
return None;
}
};
//
// Handle packet on existing connection, if any
//
let addresses = FourTuple { remote, local_ip };
if let Some(route_to) = self.index.get(&addresses, &first_decode) {
let event = DatagramConnectionEvent {
now,
remote: addresses.remote,
ecn,
first_decode,
remaining,
};
match route_to {
RouteDatagramTo::Incoming(incoming_idx) => {
let incoming_buffer = &mut self.incoming_buffers[incoming_idx];
let config = &self.server_config.as_ref().unwrap();
if incoming_buffer
.total_bytes
.checked_add(datagram_len as u64)
.map_or(false, |n| n <= config.incoming_buffer_size)
&& self
.all_incoming_buffers_total_bytes
.checked_add(datagram_len as u64)
.map_or(false, |n| n <= config.incoming_buffer_size_total)
{
incoming_buffer.datagrams.push(event);
incoming_buffer.total_bytes += datagram_len as u64;
self.all_incoming_buffers_total_bytes += datagram_len as u64;
}
return None;
}
RouteDatagramTo::Connection(ch) => {
return Some(DatagramEvent::ConnectionEvent(
ch,
ConnectionEvent(ConnectionEventInner::Datagram(event)),
))
}
}
}
//
// Potentially create a new connection
//
let dst_cid = first_decode.dst_cid();
let server_config = match &self.server_config {
Some(config) => config,
None => {
debug!("packet for unrecognized connection {}", dst_cid);
return self
.stateless_reset(now, datagram_len, addresses, dst_cid, buf)
.map(DatagramEvent::Response);
}
};
if let Some(header) = first_decode.initial_header() {
if datagram_len < MIN_INITIAL_SIZE as usize {
debug!("ignoring short initial for connection {}", dst_cid);
return None;
}
let crypto = match server_config.crypto.initial_keys(header.version, dst_cid) {
Ok(keys) => keys,
Err(UnsupportedVersion) => {
// This probably indicates that the user set supported_versions incorrectly in
// `EndpointConfig`.
debug!(
"ignoring initial packet version {:#x} unsupported by cryptographic layer",
header.version
);
return None;
}
};
if let Err(reason) = self.early_validate_first_packet(header) {
return Some(DatagramEvent::Response(self.initial_close(
header.version,
addresses,
&crypto,
&header.src_cid,
reason,
buf,
)));
}
return match first_decode.finish(Some(&*crypto.header.remote)) {
Ok(packet) => {
self.handle_first_packet(addresses, ecn, packet, remaining, crypto, buf)
}
Err(e) => {
trace!("unable to decode initial packet: {}", e);
None
}
};
} else if first_decode.has_long_header() {
debug!(
"ignoring non-initial packet for unknown connection {}",
dst_cid
);
return None;
}
//
// If we got this far, we're a server receiving a seemingly valid packet for an unknown
// connection. Send a stateless reset if possible.
//
if !first_decode.is_initial()
&& self
.local_cid_generator
.validate(first_decode.dst_cid())
.is_err()
{
debug!("dropping packet with invalid CID");
return None;
}
if !dst_cid.is_empty() {
return self
.stateless_reset(now, datagram_len, addresses, dst_cid, buf)
.map(DatagramEvent::Response);
}
trace!("dropping unrecognized short packet without ID");
None
}
fn stateless_reset(
&mut self,
now: Instant,
inciting_dgram_len: usize,
addresses: FourTuple,
dst_cid: &ConnectionId,
buf: &mut Vec<u8>,
) -> Option<Transmit> {
if self
.last_stateless_reset
.map_or(false, |last| last + self.config.min_reset_interval > now)
{
debug!("ignoring unexpected packet within minimum stateless reset interval");
return None;
}
/// Minimum amount of padding for the stateless reset to look like a short-header packet
const MIN_PADDING_LEN: usize = 5;
// Prevent amplification attacks and reset loops by ensuring we pad to at most 1 byte
// smaller than the inciting packet.
let max_padding_len = match inciting_dgram_len.checked_sub(RESET_TOKEN_SIZE) {
Some(headroom) if headroom > MIN_PADDING_LEN => headroom - 1,
_ => {
debug!("ignoring unexpected {} byte packet: not larger than minimum stateless reset size", inciting_dgram_len);
return None;
}
};
debug!(
"sending stateless reset for {} to {}",
dst_cid, addresses.remote
);
self.last_stateless_reset = Some(now);
// Resets with at least this much padding can't possibly be distinguished from real packets
const IDEAL_MIN_PADDING_LEN: usize = MIN_PADDING_LEN + MAX_CID_SIZE;
let padding_len = if max_padding_len <= IDEAL_MIN_PADDING_LEN {
max_padding_len
} else {
self.rng.gen_range(IDEAL_MIN_PADDING_LEN..max_padding_len)
};
buf.reserve(padding_len + RESET_TOKEN_SIZE);
buf.resize(padding_len, 0);
self.rng.fill_bytes(&mut buf[0..padding_len]);
buf[0] = 0b0100_0000 | buf[0] >> 2;
buf.extend_from_slice(&ResetToken::new(&*self.config.reset_key, dst_cid));
debug_assert!(buf.len() < inciting_dgram_len);
Some(Transmit {
destination: addresses.remote,
ecn: None,
size: buf.len(),
segment_size: None,
src_ip: addresses.local_ip,
})
}
/// Initiate a connection
pub fn connect(
&mut self,
now: Instant,
config: ClientConfig,
remote: SocketAddr,
server_name: &str,
) -> Result<(ConnectionHandle, Connection), ConnectError> {
if self.cids_exhausted() {
return Err(ConnectError::CidsExhausted);
}
if remote.port() == 0 || remote.ip().is_unspecified() {
return Err(ConnectError::InvalidRemoteAddress(remote));
}
if !self.config.supported_versions.contains(&config.version) {
return Err(ConnectError::UnsupportedVersion);
}
let remote_id = RandomConnectionIdGenerator::new(MAX_CID_SIZE).generate_cid();
trace!(initial_dcid = %remote_id);
let ch = ConnectionHandle(self.connections.vacant_key());
let loc_cid = self.new_cid(ch);
let params = TransportParameters::new(
&config.transport,
&self.config,
self.local_cid_generator.as_ref(),
loc_cid,
None,
);
let tls = config
.crypto
.start_session(config.version, server_name, ¶ms)?;
let conn = self.add_connection(
ch,
config.version,
remote_id,
loc_cid,
remote_id,
None,
FourTuple {
remote,
local_ip: None,
},
now,
tls,
None,
config.transport,
true,
);
Ok((ch, conn))
}
fn send_new_identifiers(
&mut self,
now: Instant,
ch: ConnectionHandle,
num: u64,
) -> ConnectionEvent {
let mut ids = vec![];
for _ in 0..num {
let id = self.new_cid(ch);
let meta = &mut self.connections[ch];
let sequence = meta.cids_issued;
meta.cids_issued += 1;
meta.loc_cids.insert(sequence, id);
ids.push(IssuedCid {
sequence,
id,
reset_token: ResetToken::new(&*self.config.reset_key, &id),
});
}
ConnectionEvent(ConnectionEventInner::NewIdentifiers(ids, now))
}
/// Generate a connection ID for `ch`
fn new_cid(&mut self, ch: ConnectionHandle) -> ConnectionId {
loop {
let cid = self.local_cid_generator.generate_cid();
if let hash_map::Entry::Vacant(e) = self.index.connection_ids.entry(cid) {
e.insert(ch);
break cid;
}
assert!(self.local_cid_generator.cid_len() > 0);
}
}
fn handle_first_packet(
&mut self,
addresses: FourTuple,
ecn: Option<EcnCodepoint>,
packet: Packet,
rest: Option<BytesMut>,
crypto: Keys,
buf: &mut Vec<u8>,
) -> Option<DatagramEvent> {
if !packet.reserved_bits_valid() {
debug!("dropping connection attempt with invalid reserved bits");
return None;
}
let Header::Initial(header) = packet.header else {
panic!("non-initial packet in handle_first_packet()");
};
let server_config = self.server_config.as_ref().unwrap().clone();
let (retry_src_cid, orig_dst_cid) = if header.token.is_empty() {
(None, header.dst_cid)
} else {
match RetryToken::from_bytes(
&*server_config.token_key,
&addresses.remote,
&header.dst_cid,
&header.token,
) {
Ok(token)
if token.issued + server_config.retry_token_lifetime > SystemTime::now() =>
{
(Some(header.dst_cid), token.orig_dst_cid)
}
Err(TokenDecodeError::UnknownToken) => {
// Token may have been generated by an incompatible endpoint, e.g. a
// different version or a neighbor behind the same load balancer. We
// can't interpret it, so we proceed as if there was no token.
(None, header.dst_cid)
}
_ => {
debug!("rejecting invalid stateless retry token");
return Some(DatagramEvent::Response(self.initial_close(
header.version,
addresses,
&crypto,
&header.src_cid,
TransportError::INVALID_TOKEN(""),
buf,
)));
}
}
};
let incoming_idx = self.incoming_buffers.insert(IncomingBuffer::default());
self.index
.insert_initial_incoming(orig_dst_cid, incoming_idx);
Some(DatagramEvent::NewConnection(Incoming {
addresses,
ecn,
packet: InitialPacket {
header,
header_data: packet.header_data,
payload: packet.payload,
},
rest,
crypto,
retry_src_cid,
orig_dst_cid,
incoming_idx,
improper_drop_warner: IncomingImproperDropWarner,
}))
}
/// Attempt to accept this incoming connection (an error may still occur)
pub fn accept(
&mut self,
mut incoming: Incoming,
now: Instant,
buf: &mut Vec<u8>,
server_config: Option<Arc<ServerConfig>>,
) -> Result<(ConnectionHandle, Connection), AcceptError> {
let remote_address_validated = incoming.remote_address_validated();
incoming.improper_drop_warner.dismiss();
let incoming_buffer = self.incoming_buffers.remove(incoming.incoming_idx);
self.all_incoming_buffers_total_bytes -= incoming_buffer.total_bytes;
let packet_number = incoming.packet.header.number.expand(0);
let InitialHeader {
src_cid,
dst_cid,
version,
..
} = incoming.packet.header;
if self.cids_exhausted() {
debug!("refusing connection");
self.index.remove_initial(incoming.orig_dst_cid);
return Err(AcceptError {
cause: ConnectionError::CidsExhausted,
response: Some(self.initial_close(
version,
incoming.addresses,
&incoming.crypto,
&src_cid,
TransportError::CONNECTION_REFUSED(""),
buf,
)),
});
}
let server_config =
server_config.unwrap_or_else(|| self.server_config.as_ref().unwrap().clone());
if incoming
.crypto
.packet
.remote
.decrypt(
packet_number,
&incoming.packet.header_data,
&mut incoming.packet.payload,
)
.is_err()
{
debug!(packet_number, "failed to authenticate initial packet");
self.index.remove_initial(incoming.orig_dst_cid);
return Err(AcceptError {
cause: TransportError::PROTOCOL_VIOLATION("authentication failed").into(),
response: None,
});
};
let ch = ConnectionHandle(self.connections.vacant_key());
let loc_cid = self.new_cid(ch);
let mut params = TransportParameters::new(
&server_config.transport,
&self.config,
self.local_cid_generator.as_ref(),
loc_cid,
Some(&server_config),
);
params.stateless_reset_token = Some(ResetToken::new(&*self.config.reset_key, &loc_cid));
params.original_dst_cid = Some(incoming.orig_dst_cid);
params.retry_src_cid = incoming.retry_src_cid;
let mut pref_addr_cid = None;
if server_config.preferred_address_v4.is_some()
|| server_config.preferred_address_v6.is_some()
{
let cid = self.new_cid(ch);
pref_addr_cid = Some(cid);
params.preferred_address = Some(PreferredAddress {
address_v4: server_config.preferred_address_v4,
address_v6: server_config.preferred_address_v6,
connection_id: cid,
stateless_reset_token: ResetToken::new(&*self.config.reset_key, &cid),
});
}
let tls = server_config.crypto.clone().start_session(version, ¶ms);
let transport_config = server_config.transport.clone();
let mut conn = self.add_connection(
ch,
version,
dst_cid,
loc_cid,
src_cid,
pref_addr_cid,
incoming.addresses,
now,
tls,
Some(server_config),
transport_config,
remote_address_validated,
);
if dst_cid.len() != 0 {
self.index.insert_initial(dst_cid, ch);
}
match conn.handle_first_packet(
now,
incoming.addresses.remote,
incoming.ecn,
packet_number,
incoming.packet,
incoming.rest,
) {
Ok(()) => {
trace!(id = ch.0, icid = %dst_cid, "new connection");
for event in incoming_buffer.datagrams {
conn.handle_event(ConnectionEvent(ConnectionEventInner::Datagram(event)))
}
Ok((ch, conn))
}
Err(e) => {
debug!("handshake failed: {}", e);
self.handle_event(ch, EndpointEvent(EndpointEventInner::Drained));
let response = match e {
ConnectionError::TransportError(ref e) => Some(self.initial_close(
version,
incoming.addresses,
&incoming.crypto,
&src_cid,
e.clone(),
buf,
)),
_ => None,
};
Err(AcceptError { cause: e, response })
}
}
}
/// Check if we should refuse a connection attempt regardless of the packet's contents
fn early_validate_first_packet(
&mut self,
header: &PlainInitialHeader,
) -> Result<(), TransportError> {
let config = &self.server_config.as_ref().unwrap();
if self.cids_exhausted() || self.incoming_buffers.len() >= config.max_incoming {
return Err(TransportError::CONNECTION_REFUSED(""));
}
// RFC9000 §7.2 dictates that initial (client-chosen) destination CIDs must be at least 8
// bytes. If this is a Retry packet, then the length must instead match our usual CID
// length. If we ever issue non-Retry address validation tokens via `NEW_TOKEN`, then we'll
// also need to validate CID length for those after decoding the token.
if header.dst_cid.len() < 8
&& (!header.token_pos.is_empty()
&& header.dst_cid.len() != self.local_cid_generator.cid_len())
{
debug!(
"rejecting connection due to invalid DCID length {}",
header.dst_cid.len()
);
return Err(TransportError::PROTOCOL_VIOLATION(
"invalid destination CID length",
));
}
Ok(())
}
/// Reject this incoming connection attempt
pub fn refuse(&mut self, incoming: Incoming, buf: &mut Vec<u8>) -> Transmit {
self.clean_up_incoming(&incoming);
incoming.improper_drop_warner.dismiss();
self.initial_close(
incoming.packet.header.version,
incoming.addresses,
&incoming.crypto,
&incoming.packet.header.src_cid,
TransportError::CONNECTION_REFUSED(""),
buf,
)
}
/// Respond with a retry packet, requiring the client to retry with address validation
///
/// Errors if `incoming.remote_address_validated()` is true.
pub fn retry(&mut self, incoming: Incoming, buf: &mut Vec<u8>) -> Result<Transmit, RetryError> {
if incoming.remote_address_validated() {
return Err(RetryError(incoming));
}
self.clean_up_incoming(&incoming);
incoming.improper_drop_warner.dismiss();
let server_config = self.server_config.as_ref().unwrap();
// First Initial
// The peer will use this as the DCID of its following Initials. Initial DCIDs are
// looked up separately from Handshake/Data DCIDs, so there is no risk of collision
// with established connections. In the unlikely event that a collision occurs
// between two connections in the initial phase, both will fail fast and may be
// retried by the application layer.
let loc_cid = self.local_cid_generator.generate_cid();
let token = RetryToken {
orig_dst_cid: incoming.packet.header.dst_cid,
issued: SystemTime::now(),
}
.encode(
&*server_config.token_key,
&incoming.addresses.remote,
&loc_cid,
);
let header = Header::Retry {
src_cid: loc_cid,
dst_cid: incoming.packet.header.src_cid,
version: incoming.packet.header.version,
};
let encode = header.encode(buf);
buf.put_slice(&token);
buf.extend_from_slice(&server_config.crypto.retry_tag(
incoming.packet.header.version,
&incoming.packet.header.dst_cid,
buf,
));
encode.finish(buf, &*incoming.crypto.header.local, None);
Ok(Transmit {
destination: incoming.addresses.remote,
ecn: None,
size: buf.len(),
segment_size: None,
src_ip: incoming.addresses.local_ip,
})
}
/// Ignore this incoming connection attempt, not sending any packet in response
///
/// Doing this actively, rather than merely dropping the [`Incoming`], is necessary to prevent
/// memory leaks due to state within [`Endpoint`] tracking the incoming connection.
pub fn ignore(&mut self, incoming: Incoming) {
self.clean_up_incoming(&incoming);
incoming.improper_drop_warner.dismiss();
}
/// Clean up endpoint data structures associated with an `Incoming`.
fn clean_up_incoming(&mut self, incoming: &Incoming) {
self.index.remove_initial(incoming.orig_dst_cid);
let incoming_buffer = self.incoming_buffers.remove(incoming.incoming_idx);
self.all_incoming_buffers_total_bytes -= incoming_buffer.total_bytes;
}
fn add_connection(
&mut self,
ch: ConnectionHandle,
version: u32,
init_cid: ConnectionId,
loc_cid: ConnectionId,
rem_cid: ConnectionId,
pref_addr_cid: Option<ConnectionId>,
addresses: FourTuple,
now: Instant,
tls: Box<dyn crypto::Session>,
server_config: Option<Arc<ServerConfig>>,
transport_config: Arc<TransportConfig>,
path_validated: bool,
) -> Connection {
let mut rng_seed = [0; 32];
self.rng.fill_bytes(&mut rng_seed);
let conn = Connection::new(
self.config.clone(),
server_config,
transport_config,
init_cid,
loc_cid,
rem_cid,
pref_addr_cid,
addresses.remote,
addresses.local_ip,
tls,
self.local_cid_generator.as_ref(),
now,
version,
self.allow_mtud,
rng_seed,
path_validated,
);
let mut cids_issued = 0;
let mut loc_cids = FxHashMap::default();
loc_cids.insert(cids_issued, loc_cid);
cids_issued += 1;
if let Some(cid) = pref_addr_cid {
debug_assert_eq!(cids_issued, 1, "preferred address cid seq must be 1");
loc_cids.insert(cids_issued, cid);
cids_issued += 1;
}
let id = self.connections.insert(ConnectionMeta {
init_cid,
cids_issued,
loc_cids,
addresses,
reset_token: None,
});
debug_assert_eq!(id, ch.0, "connection handle allocation out of sync");
self.index.insert_conn(addresses, loc_cid, ch);
conn
}
fn initial_close(
&mut self,
version: u32,
addresses: FourTuple,
crypto: &Keys,
remote_id: &ConnectionId,
reason: TransportError,
buf: &mut Vec<u8>,
) -> Transmit {
// We don't need to worry about CID collisions in initial closes because the peer
// shouldn't respond, and if it does, and the CID collides, we'll just drop the
// unexpected response.
let local_id = self.local_cid_generator.generate_cid();
let number = PacketNumber::U8(0);
let header = Header::Initial(InitialHeader {
dst_cid: *remote_id,
src_cid: local_id,
number,
token: Bytes::new(),
version,
});
let partial_encode = header.encode(buf);
let max_len =
INITIAL_MTU as usize - partial_encode.header_len - crypto.packet.local.tag_len();
frame::Close::from(reason).encode(buf, max_len);
buf.resize(buf.len() + crypto.packet.local.tag_len(), 0);
partial_encode.finish(buf, &*crypto.header.local, Some((0, &*crypto.packet.local)));
Transmit {
destination: addresses.remote,
ecn: None,
size: buf.len(),
segment_size: None,
src_ip: addresses.local_ip,
}
}
/// Access the configuration used by this endpoint
pub fn config(&self) -> &EndpointConfig {
&self.config
}
/// Number of connections that are currently open
pub fn open_connections(&self) -> usize {
self.connections.len()
}
#[cfg(test)]
pub(crate) fn known_connections(&self) -> usize {
let x = self.connections.len();
debug_assert_eq!(x, self.index.connection_ids_initial.len());
// Not all connections have known reset tokens
debug_assert!(x >= self.index.connection_reset_tokens.0.len());
// Not all connections have unique remotes, and 0-length CIDs might not be in use.
debug_assert!(x >= self.index.connection_remotes.len());
x
}
#[cfg(test)]
pub(crate) fn known_cids(&self) -> usize {
self.index.connection_ids.len()
}
/// Whether we've used up 3/4 of the available CID space
///
/// We leave some space unused so that `new_cid` can be relied upon to finish quickly. We don't
/// bother to check when CID longer than 4 bytes are used because 2^40 connections is a lot.
fn cids_exhausted(&self) -> bool {
self.local_cid_generator.cid_len() <= 4
&& self.local_cid_generator.cid_len() != 0
&& (2usize.pow(self.local_cid_generator.cid_len() as u32 * 8)
- self.index.connection_ids.len())
< 2usize.pow(self.local_cid_generator.cid_len() as u32 * 8 - 2)
}
}
impl fmt::Debug for Endpoint {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("Endpoint")
.field("rng", &self.rng)
.field("index", &self.index)
.field("connections", &self.connections)
.field("config", &self.config)
.field("server_config", &self.server_config)
// incoming_buffers too large
.field("incoming_buffers.len", &self.incoming_buffers.len())
.field(
"all_incoming_buffers_total_bytes",
&self.all_incoming_buffers_total_bytes,
)
.finish()
}
}
/// Buffered Initial and 0-RTT messages for a pending incoming connection
#[derive(Default)]
struct IncomingBuffer {
datagrams: Vec<DatagramConnectionEvent>,
total_bytes: u64,
}
/// Part of protocol state incoming datagrams can be routed to
#[derive(Copy, Clone, Debug)]
enum RouteDatagramTo {
Incoming(usize),
Connection(ConnectionHandle),
}
/// Maps packets to existing connections
#[derive(Default, Debug)]
struct ConnectionIndex {
/// Identifies connections based on the initial DCID the peer utilized
///
/// Uses a standard `HashMap` to protect against hash collision attacks.
connection_ids_initial: HashMap<ConnectionId, RouteDatagramTo>,
/// Identifies connections based on locally created CIDs
///
/// Uses a cheaper hash function since keys are locally created
connection_ids: FxHashMap<ConnectionId, ConnectionHandle>,
/// Identifies connections with zero-length CIDs
///
/// Uses a standard `HashMap` to protect against hash collision attacks.
connection_remotes: HashMap<FourTuple, ConnectionHandle>,
/// Reset tokens provided by the peer for the CID each connection is currently sending to
///
/// Incoming stateless resets do not have correct CIDs, so we need this to identify the correct
/// recipient, if any.
connection_reset_tokens: ResetTokenTable,
}
impl ConnectionIndex {
/// Associate an incoming connection with its initial destination CID
fn insert_initial_incoming(&mut self, dst_cid: ConnectionId, incoming_key: usize) {
self.connection_ids_initial
.insert(dst_cid, RouteDatagramTo::Incoming(incoming_key));
}
/// Remove an association with an initial destination CID
fn remove_initial(&mut self, dst_cid: ConnectionId) {