1use std::{
2 collections::{HashMap, hash_map},
3 convert::TryFrom,
4 fmt, mem,
5 net::{IpAddr, SocketAddr},
6 ops::{Index, IndexMut},
7 sync::Arc,
8};
9
10use bytes::{Buf, BufMut, Bytes, BytesMut};
11use rand::{Rng, RngExt, SeedableRng, rngs::StdRng};
12use rustc_hash::FxHashMap;
13use slab::Slab;
14use thiserror::Error;
15use tracing::{debug, error, trace, warn};
16
17use crate::{
18 Duration, FourTuple, INITIAL_MTU, Instant, MAX_CID_SIZE, MIN_INITIAL_SIZE, PathId,
19 RESET_TOKEN_SIZE, ResetToken, Side, Transmit, TransportConfig, TransportError,
20 cid_generator::ConnectionIdGenerator,
21 coding::{BufMutExt, Decodable, Encodable, UnexpectedEnd},
22 config::{ClientConfig, EndpointConfig, ServerConfig},
23 connection::{Connection, ConnectionError, SideArgs},
24 crypto::{self, Keys, UnsupportedVersion},
25 frame,
26 packet::{
27 FixedLengthConnectionIdParser, Header, InitialHeader, InitialPacket, PacketDecodeError,
28 PacketNumber, PartialDecode, ProtectedInitialHeader,
29 },
30 shared::{
31 ConnectionEvent, ConnectionEventInner, ConnectionId, DatagramConnectionEvent, EcnCodepoint,
32 EndpointEvent, EndpointEventInner, IssuedCid,
33 },
34 token::{IncomingToken, InvalidRetryTokenError, Token, TokenPayload},
35 transport_parameters::{PreferredAddress, TransportParameters},
36};
37
38pub struct Endpoint {
43 rng: StdRng,
44 index: ConnectionIndex,
45 connections: Slab<ConnectionMeta>,
46 local_cid_generator: Box<dyn ConnectionIdGenerator>,
47 config: Arc<EndpointConfig>,
48 server_config: Option<Arc<ServerConfig>>,
49 allow_mtud: bool,
51 last_stateless_reset: Option<Instant>,
53 incoming_buffers: Slab<IncomingBuffer>,
55 all_incoming_buffers_total_bytes: u64,
56}
57
58impl Endpoint {
59 pub fn new(
65 config: Arc<EndpointConfig>,
66 server_config: Option<Arc<ServerConfig>>,
67 allow_mtud: bool,
68 ) -> Self {
69 Self {
70 rng: config
71 .rng_seed
72 .map_or_else(|| StdRng::from_rng(&mut rand::rng()), StdRng::from_seed),
73 index: ConnectionIndex::default(),
74 connections: Slab::new(),
75 local_cid_generator: (config.connection_id_generator_factory.as_ref())(),
76 config,
77 server_config,
78 allow_mtud,
79 last_stateless_reset: None,
80 incoming_buffers: Slab::new(),
81 all_incoming_buffers_total_bytes: 0,
82 }
83 }
84
85 pub fn set_server_config(&mut self, server_config: Option<Arc<ServerConfig>>) {
87 self.server_config = server_config;
88 }
89
90 pub fn handle_event(
94 &mut self,
95 ch: ConnectionHandle,
96 event: EndpointEvent,
97 ) -> Option<ConnectionEvent> {
98 use EndpointEventInner::*;
99 match event.0 {
100 NeedIdentifiers(path_id, now, n) => {
101 return Some(self.send_new_identifiers(path_id, now, ch, n));
102 }
103 ResetToken(path_id, remote, token) => {
104 if let Some(old) = self.connections[ch]
105 .reset_token
106 .insert(path_id, (remote, token))
107 {
108 self.index.connection_reset_tokens.remove(old.0, old.1);
109 }
110 if self.index.connection_reset_tokens.insert(remote, token, ch) {
111 warn!("duplicate reset token");
112 }
113 }
114 RetireResetToken(path_id) => {
115 if let Some(old) = self.connections[ch].reset_token.remove(&path_id) {
116 self.index.connection_reset_tokens.remove(old.0, old.1);
117 }
118 }
119 RetireConnectionId(now, path_id, seq, allow_more_cids) => {
120 if let Some(cid) = self.connections[ch]
121 .local_cids
122 .get_mut(&path_id)
123 .and_then(|pcid| pcid.cids.remove(&seq))
124 {
125 trace!(%path_id, "local CID retired {}: {}", seq, cid);
126 self.index.retire(cid);
127 if allow_more_cids {
128 return Some(self.send_new_identifiers(path_id, now, ch, 1));
129 }
130 }
131 }
132 Draining => {
133 }
135 Drained => {
136 if let Some(conn) = self.connections.try_remove(ch.0) {
137 self.index.remove(&conn);
138 } else {
139 error!(id = ch.0, "unknown connection drained");
143 }
144 }
145 }
146 None
147 }
148
149 pub fn handle(
151 &mut self,
152 now: Instant,
153 network_path: FourTuple,
154 ecn: Option<EcnCodepoint>,
155 data: BytesMut,
156 buf: &mut Vec<u8>,
157 ) -> Option<DatagramEvent> {
158 let datagram_len = data.len();
160 let mut event = match PartialDecode::new(
161 data,
162 &FixedLengthConnectionIdParser::new(self.local_cid_generator.cid_len()),
163 &self.config.supported_versions,
164 self.config.grease_quic_bit,
165 ) {
166 Ok((first_decode, remaining)) => DatagramConnectionEvent {
167 now,
168 network_path,
169 path_id: PathId::ZERO, ecn,
171 first_decode,
172 remaining,
173 },
174 Err(PacketDecodeError::UnsupportedVersion {
175 src_cid,
176 dst_cid,
177 version,
178 }) => {
179 if self.server_config.is_none() {
180 debug!("dropping packet with unsupported version");
181 return None;
182 }
183 trace!("sending version negotiation");
184 Header::VersionNegotiate {
186 random: self.rng.random::<u8>() | 0x40,
187 src_cid: dst_cid,
188 dst_cid: src_cid,
189 }
190 .encode(buf);
191 buf.write::<u32>(match version {
193 0x0a1a_2a3a => 0x0a1a_2a4a,
194 _ => 0x0a1a_2a3a,
195 });
196 for &version in &self.config.supported_versions {
197 buf.write(version);
198 }
199 return Some(DatagramEvent::Response(Transmit {
200 destination: network_path.remote,
201 ecn: None,
202 size: buf.len(),
203 segment_size: None,
204 src_ip: network_path.local_ip,
205 }));
206 }
207 Err(e) => {
208 trace!("malformed header: {}", e);
209 return None;
210 }
211 };
212
213 let dst_cid = event.first_decode.dst_cid();
214
215 if let Some(route_to) = self.index.get(&network_path, &event.first_decode) {
216 event.path_id = match route_to {
217 RouteDatagramTo::Incoming(_) => PathId::ZERO,
218 RouteDatagramTo::Connection(_, path_id) => path_id,
219 };
220 match route_to {
221 RouteDatagramTo::Incoming(incoming_idx) => {
222 let incoming_buffer = &mut self.incoming_buffers[incoming_idx];
223 let config = &self.server_config.as_ref().unwrap();
224
225 if incoming_buffer
226 .total_bytes
227 .checked_add(datagram_len as u64)
228 .is_some_and(|n| n <= config.incoming_buffer_size)
229 && self
230 .all_incoming_buffers_total_bytes
231 .checked_add(datagram_len as u64)
232 .is_some_and(|n| n <= config.incoming_buffer_size_total)
233 {
234 incoming_buffer.datagrams.push(event);
235 incoming_buffer.total_bytes += datagram_len as u64;
236 self.all_incoming_buffers_total_bytes += datagram_len as u64;
237 }
238
239 None
240 }
241 RouteDatagramTo::Connection(ch, _path_id) => Some(DatagramEvent::ConnectionEvent(
242 ch,
243 ConnectionEvent(ConnectionEventInner::Datagram(event)),
244 )),
245 }
246 } else if event.first_decode.initial_header().is_some() {
247 self.handle_first_packet(datagram_len, event, network_path, buf)
250 } else if event.first_decode.has_long_header() {
251 debug!(
252 "ignoring non-initial packet for unknown connection {}",
253 dst_cid
254 );
255 None
256 } else if !event.first_decode.is_initial()
257 && self.local_cid_generator.validate(dst_cid).is_err()
258 {
259 debug!("dropping packet with invalid CID");
260 None
261 } else if dst_cid.is_empty() {
262 trace!("dropping unrecognized short packet without ID");
263 None
264 } else {
265 self.stateless_reset(now, datagram_len, network_path, dst_cid, buf)
268 .map(DatagramEvent::Response)
269 }
270 }
271
272 fn stateless_reset(
274 &mut self,
275 now: Instant,
276 inciting_dgram_len: usize,
277 network_path: FourTuple,
278 dst_cid: ConnectionId,
279 buf: &mut Vec<u8>,
280 ) -> Option<Transmit> {
281 if self
282 .last_stateless_reset
283 .is_some_and(|last| last + self.config.min_reset_interval > now)
284 {
285 debug!("ignoring unexpected packet within minimum stateless reset interval");
286 return None;
287 }
288
289 const MIN_PADDING_LEN: usize = 5;
291
292 let max_padding_len = match inciting_dgram_len.checked_sub(RESET_TOKEN_SIZE) {
295 Some(headroom) if headroom > MIN_PADDING_LEN => headroom - 1,
296 _ => {
297 debug!(
298 "ignoring unexpected {} byte packet: not larger than minimum stateless reset size",
299 inciting_dgram_len
300 );
301 return None;
302 }
303 };
304
305 debug!(%dst_cid, %network_path.remote, "sending stateless reset");
306 self.last_stateless_reset = Some(now);
307 const IDEAL_MIN_PADDING_LEN: usize = MIN_PADDING_LEN + MAX_CID_SIZE;
309 let padding_len = if max_padding_len <= IDEAL_MIN_PADDING_LEN {
310 max_padding_len
311 } else {
312 self.rng
313 .random_range(IDEAL_MIN_PADDING_LEN..max_padding_len)
314 };
315 buf.reserve(padding_len + RESET_TOKEN_SIZE);
316 buf.resize(padding_len, 0);
317 self.rng.fill_bytes(&mut buf[0..padding_len]);
318 buf[0] = 0b0100_0000 | (buf[0] >> 2);
319 buf.extend_from_slice(&ResetToken::new(&*self.config.reset_key, dst_cid));
320
321 debug_assert!(buf.len() < inciting_dgram_len);
322
323 Some(Transmit {
324 destination: network_path.remote,
325 ecn: None,
326 size: buf.len(),
327 segment_size: None,
328 src_ip: network_path.local_ip,
329 })
330 }
331
332 pub fn connect(
334 &mut self,
335 now: Instant,
336 config: ClientConfig,
337 remote: SocketAddr,
338 server_name: &str,
339 ) -> Result<(ConnectionHandle, Connection), ConnectError> {
340 if self.cids_exhausted() {
341 return Err(ConnectError::CidsExhausted);
342 }
343 if remote.port() == 0 || remote.ip().is_unspecified() {
344 return Err(ConnectError::InvalidRemoteAddress(remote));
345 }
346 if !self.config.supported_versions.contains(&config.version) {
347 return Err(ConnectError::UnsupportedVersion);
348 }
349
350 let remote_id = (config.initial_dst_cid_provider)();
351 trace!(initial_dcid = %remote_id);
352
353 let ch = ConnectionHandle(self.connections.vacant_key());
354 let local_cid = self.new_cid(ch, PathId::ZERO);
355 let params = TransportParameters::new(
356 &config.transport,
357 &self.config,
358 self.local_cid_generator.as_ref(),
359 local_cid,
360 None,
361 &mut self.rng,
362 );
363 let tls = config
364 .crypto
365 .start_session(config.version, server_name, ¶ms)?;
366
367 let conn = self.add_connection(
368 ch,
369 config.version,
370 remote_id,
371 local_cid,
372 remote_id,
373 FourTuple {
374 remote,
375 local_ip: None,
376 },
377 now,
378 tls,
379 config.transport,
380 SideArgs::Client {
381 token_store: config.token_store,
382 server_name: server_name.into(),
383 },
384 ¶ms,
385 );
386 Ok((ch, conn))
387 }
388
389 fn send_new_identifiers(
391 &mut self,
392 path_id: PathId,
393 now: Instant,
394 ch: ConnectionHandle,
395 num: u64,
396 ) -> ConnectionEvent {
397 let mut ids = vec![];
398 for _ in 0..num {
399 let id = self.new_cid(ch, path_id);
400 let cid_meta = self.connections[ch].local_cids.entry(path_id).or_default();
401 let sequence = cid_meta.issued;
402 cid_meta.issued += 1;
403 cid_meta.cids.insert(sequence, id);
404 ids.push(IssuedCid {
405 path_id,
406 sequence,
407 id,
408 reset_token: ResetToken::new(&*self.config.reset_key, id),
409 });
410 }
411 ConnectionEvent(ConnectionEventInner::NewIdentifiers(
412 ids,
413 now,
414 self.local_cid_generator.cid_len(),
415 self.local_cid_generator.cid_lifetime(),
416 ))
417 }
418
419 fn new_cid(&mut self, ch: ConnectionHandle, path_id: PathId) -> ConnectionId {
421 loop {
422 let cid = self.local_cid_generator.generate_cid();
423 if cid.is_empty() {
424 debug_assert_eq!(self.local_cid_generator.cid_len(), 0);
426 return cid;
427 }
428 if let hash_map::Entry::Vacant(e) = self.index.connection_ids.entry(cid) {
429 e.insert((ch, path_id));
430 break cid;
431 }
432 }
433 }
434
435 fn handle_first_packet(
436 &mut self,
437 datagram_len: usize,
438 event: DatagramConnectionEvent,
439 network_path: FourTuple,
440 buf: &mut Vec<u8>,
441 ) -> Option<DatagramEvent> {
442 let dst_cid = event.first_decode.dst_cid();
443 let header = event.first_decode.initial_header().unwrap();
444
445 let Some(server_config) = &self.server_config else {
446 debug!("packet for unrecognized connection {}", dst_cid);
447 return self
448 .stateless_reset(event.now, datagram_len, network_path, dst_cid, buf)
449 .map(DatagramEvent::Response);
450 };
451
452 if datagram_len < MIN_INITIAL_SIZE as usize {
453 debug!("ignoring short initial for connection {}", dst_cid);
454 return None;
455 }
456
457 if self.cids_exhausted() || self.incoming_buffers.len() >= server_config.max_incoming {
460 debug!(
461 "ignoring initial for connection {} due to saturation",
462 dst_cid
463 );
464 return None;
465 }
466
467 let crypto = match server_config.crypto.initial_keys(header.version, dst_cid) {
468 Ok(keys) => keys,
469 Err(UnsupportedVersion) => {
470 debug!(
473 "ignoring initial packet version {:#x} unsupported by cryptographic layer",
474 header.version
475 );
476 return None;
477 }
478 };
479
480 if let Err(reason) = self.early_validate_first_packet(header) {
481 return Some(DatagramEvent::Response(self.initial_close(
482 header.version,
483 network_path,
484 &crypto,
485 header.src_cid,
486 reason,
487 buf,
488 )));
489 }
490
491 let packet = match event.first_decode.finish(Some(&*crypto.header.remote)) {
492 Ok(packet) => packet,
493 Err(e) => {
494 trace!("unable to decode initial packet: {}", e);
495 return None;
496 }
497 };
498
499 if !packet.reserved_bits_valid() {
500 debug!("dropping connection attempt with invalid reserved bits");
501 return None;
502 }
503
504 let Header::Initial(header) = packet.header else {
505 panic!("non-initial packet in handle_first_packet()");
506 };
507
508 let server_config = self.server_config.as_ref().unwrap().clone();
509
510 let token = match IncomingToken::from_header(&header, &server_config, network_path.remote) {
511 Ok(token) => token,
512 Err(InvalidRetryTokenError) => {
513 debug!("rejecting invalid retry token");
514 return Some(DatagramEvent::Response(self.initial_close(
515 header.version,
516 network_path,
517 &crypto,
518 header.src_cid,
519 TransportError::INVALID_TOKEN(""),
520 buf,
521 )));
522 }
523 };
524
525 let incoming_idx = self.incoming_buffers.insert(IncomingBuffer::default());
526 self.index
527 .insert_initial_incoming(header.dst_cid, incoming_idx);
528
529 Some(DatagramEvent::NewConnection(Incoming {
530 received_at: event.now,
531 network_path,
532 ecn: event.ecn,
533 packet: InitialPacket {
534 header,
535 header_data: packet.header_data,
536 payload: packet.payload,
537 },
538 rest: event.remaining,
539 crypto,
540 token,
541 incoming_idx,
542 improper_drop_warner: IncomingImproperDropWarner,
543 }))
544 }
545
546 pub fn accept(
549 &mut self,
550 mut incoming: Incoming,
551 now: Instant,
552 buf: &mut Vec<u8>,
553 server_config: Option<Arc<ServerConfig>>,
554 ) -> Result<(ConnectionHandle, Connection), Box<AcceptError>> {
555 let remote_address_validated = incoming.remote_address_validated();
556 incoming.improper_drop_warner.dismiss();
557 let incoming_buffer = self.incoming_buffers.remove(incoming.incoming_idx);
558 self.all_incoming_buffers_total_bytes -= incoming_buffer.total_bytes;
559
560 let packet_number = incoming.packet.header.number.expand(0);
561 let InitialHeader {
562 src_cid,
563 dst_cid,
564 version,
565 ..
566 } = incoming.packet.header;
567 let server_config =
568 server_config.unwrap_or_else(|| self.server_config.as_ref().unwrap().clone());
569
570 if server_config
571 .transport
572 .max_idle_timeout
573 .is_some_and(|timeout| {
574 incoming.received_at + Duration::from_millis(timeout.into()) <= now
575 })
576 {
577 debug!("abandoning accept of stale initial");
578 self.index.remove_initial(dst_cid);
579 return Err(Box::new(AcceptError {
580 cause: ConnectionError::TimedOut,
581 response: None,
582 }));
583 }
584
585 if self.cids_exhausted() {
586 debug!("refusing connection");
587 self.index.remove_initial(dst_cid);
588 return Err(Box::new(AcceptError {
589 cause: ConnectionError::CidsExhausted,
590 response: Some(self.initial_close(
591 version,
592 incoming.network_path,
593 &incoming.crypto,
594 src_cid,
595 TransportError::CONNECTION_REFUSED(""),
596 buf,
597 )),
598 }));
599 }
600
601 if incoming
602 .crypto
603 .packet
604 .remote
605 .decrypt(
606 PathId::ZERO,
607 packet_number,
608 &incoming.packet.header_data,
609 &mut incoming.packet.payload,
610 )
611 .is_err()
612 {
613 debug!(packet_number, "failed to authenticate initial packet");
614 self.index.remove_initial(dst_cid);
615 return Err(Box::new(AcceptError {
616 cause: TransportError::PROTOCOL_VIOLATION("authentication failed").into(),
617 response: None,
618 }));
619 };
620
621 let ch = ConnectionHandle(self.connections.vacant_key());
622 let local_cid = self.new_cid(ch, PathId::ZERO);
623 let mut params = TransportParameters::new(
624 &server_config.transport,
625 &self.config,
626 self.local_cid_generator.as_ref(),
627 local_cid,
628 Some(&server_config),
629 &mut self.rng,
630 );
631 params.stateless_reset_token = Some(ResetToken::new(&*self.config.reset_key, local_cid));
632 params.original_dst_cid = Some(incoming.token.orig_dst_cid);
633 params.retry_src_cid = incoming.token.retry_src_cid;
634 let mut pref_addr_cid = None;
635 if server_config.has_preferred_address() {
636 let cid = self.new_cid(ch, PathId::ZERO);
637 pref_addr_cid = Some(cid);
638 params.preferred_address = Some(PreferredAddress {
639 address_v4: server_config.preferred_address_v4,
640 address_v6: server_config.preferred_address_v6,
641 connection_id: cid,
642 stateless_reset_token: ResetToken::new(&*self.config.reset_key, cid),
643 });
644 }
645
646 let tls = server_config.crypto.start_session(version, ¶ms);
647 let transport_config = server_config.transport.clone();
648 let mut conn = self.add_connection(
649 ch,
650 version,
651 dst_cid,
652 local_cid,
653 src_cid,
654 incoming.network_path,
655 incoming.received_at,
656 tls,
657 transport_config,
658 SideArgs::Server {
659 server_config,
660 pref_addr_cid,
661 path_validated: remote_address_validated,
662 },
663 ¶ms,
664 );
665 self.index.insert_initial(dst_cid, ch);
666
667 match conn.handle_first_packet(
668 incoming.received_at,
669 incoming.network_path,
670 incoming.ecn,
671 packet_number,
672 incoming.packet,
673 incoming.rest,
674 ) {
675 Ok(()) => {
676 trace!(
677 id = ch.0,
678 icid = %dst_cid,
679 network_path = %incoming.network_path,
680 "new connection",
681 );
682
683 for event in incoming_buffer.datagrams {
684 conn.handle_event(ConnectionEvent(ConnectionEventInner::Datagram(event)))
685 }
686
687 Ok((ch, conn))
688 }
689 Err(e) => {
690 debug!("handshake failed: {}", e);
691 self.handle_event(ch, EndpointEvent(EndpointEventInner::Drained));
692 let response = match e {
693 ConnectionError::TransportError(ref e) => Some(self.initial_close(
694 version,
695 incoming.network_path,
696 &incoming.crypto,
697 src_cid,
698 e.clone(),
699 buf,
700 )),
701 _ => None,
702 };
703 Err(Box::new(AcceptError { cause: e, response }))
704 }
705 }
706 }
707
708 fn early_validate_first_packet(
710 &mut self,
711 header: &ProtectedInitialHeader,
712 ) -> Result<(), TransportError> {
713 if header.dst_cid.len() < 8
718 && (header.token_pos.is_empty()
719 || header.dst_cid.len() != self.local_cid_generator.cid_len())
720 {
721 debug!(
722 "rejecting connection due to invalid DCID length {}",
723 header.dst_cid.len()
724 );
725 return Err(TransportError::PROTOCOL_VIOLATION(
726 "invalid destination CID length",
727 ));
728 }
729
730 Ok(())
731 }
732
733 pub fn refuse(&mut self, incoming: Incoming, buf: &mut Vec<u8>) -> Transmit {
735 self.clean_up_incoming(&incoming);
736 incoming.improper_drop_warner.dismiss();
737
738 trace!(?incoming.network_path, "refusing incoming");
739
740 self.initial_close(
741 incoming.packet.header.version,
742 incoming.network_path,
743 &incoming.crypto,
744 incoming.packet.header.src_cid,
745 TransportError::CONNECTION_REFUSED(""),
746 buf,
747 )
748 }
749
750 pub fn retry(&mut self, incoming: Incoming, buf: &mut Vec<u8>) -> Result<Transmit, RetryError> {
754 if !incoming.may_retry() {
755 trace!(
756 ?incoming.network_path,
757 "not responding retry on incoming due to missing src CID"
758 );
759 return Err(RetryError(Box::new(incoming)));
760 }
761
762 trace!(?incoming.network_path, "responding retry on incoming");
763
764 self.clean_up_incoming(&incoming);
765 incoming.improper_drop_warner.dismiss();
766
767 let server_config = self.server_config.as_ref().unwrap();
768
769 let local_cid = self.local_cid_generator.generate_cid();
776
777 let payload = TokenPayload::Retry {
778 address: incoming.network_path.remote,
779 orig_dst_cid: incoming.packet.header.dst_cid,
780 issued: server_config.time_source.now(),
781 };
782 let token = Token::new(payload, &mut self.rng).encode(&*server_config.token_key);
783
784 let header = Header::Retry {
785 src_cid: local_cid,
786 dst_cid: incoming.packet.header.src_cid,
787 version: incoming.packet.header.version,
788 };
789
790 let encode = header.encode(buf);
791 buf.put_slice(&token);
792 buf.extend_from_slice(&server_config.crypto.retry_tag(
793 incoming.packet.header.version,
794 incoming.packet.header.dst_cid,
795 buf,
796 ));
797 encode.finish(buf, &*incoming.crypto.header.local, None);
798
799 Ok(Transmit {
800 destination: incoming.network_path.remote,
801 ecn: None,
802 size: buf.len(),
803 segment_size: None,
804 src_ip: incoming.network_path.local_ip,
805 })
806 }
807
808 pub fn ignore(&mut self, incoming: Incoming) {
813 self.clean_up_incoming(&incoming);
814 incoming.improper_drop_warner.dismiss();
815
816 trace!(?incoming.network_path, "ignoring incoming");
817 }
818
819 fn clean_up_incoming(&mut self, incoming: &Incoming) {
821 self.index.remove_initial(incoming.packet.header.dst_cid);
822 let incoming_buffer = self.incoming_buffers.remove(incoming.incoming_idx);
823 self.all_incoming_buffers_total_bytes -= incoming_buffer.total_bytes;
824 }
825
826 fn add_connection(
827 &mut self,
828 ch: ConnectionHandle,
829 version: u32,
830 init_cid: ConnectionId,
831 local_cid: ConnectionId,
832 remote_cid: ConnectionId,
833 network_path: FourTuple,
834 now: Instant,
835 tls: Box<dyn crypto::Session>,
836 transport_config: Arc<TransportConfig>,
837 side_args: SideArgs,
838 params: &TransportParameters,
840 ) -> Connection {
841 let mut rng_seed = [0; 32];
842 self.rng.fill_bytes(&mut rng_seed);
843 let side = side_args.side();
844 let pref_addr_cid = side_args.pref_addr_cid();
845
846 let qlog =
847 transport_config.create_qlog_sink(side_args.side(), network_path.remote, init_cid, now);
848
849 qlog.emit_connection_started(
850 now,
851 local_cid,
852 remote_cid,
853 network_path.remote,
854 network_path.local_ip,
855 params,
856 );
857
858 let conn = Connection::new(
859 self.config.clone(),
860 transport_config,
861 init_cid,
862 local_cid,
863 remote_cid,
864 network_path,
865 tls,
866 self.local_cid_generator.as_ref(),
867 now,
868 version,
869 self.allow_mtud,
870 rng_seed,
871 side_args,
872 qlog,
873 );
874
875 let mut path_cids = PathLocalCids::default();
876 path_cids.cids.insert(path_cids.issued, local_cid);
877 path_cids.issued += 1;
878
879 if let Some(cid) = pref_addr_cid {
880 debug_assert_eq!(path_cids.issued, 1, "preferred address cid seq must be 1");
881 path_cids.cids.insert(path_cids.issued, cid);
882 path_cids.issued += 1;
883 }
884
885 let id = self.connections.insert(ConnectionMeta {
886 init_cid,
887 local_cids: FxHashMap::from_iter([(PathId::ZERO, path_cids)]),
888 network_path,
889 side,
890 reset_token: Default::default(),
891 });
892 debug_assert_eq!(id, ch.0, "connection handle allocation out of sync");
893
894 self.index.insert_conn(network_path, local_cid, ch, side);
895
896 conn
897 }
898
899 fn initial_close(
900 &mut self,
901 version: u32,
902 network_path: FourTuple,
903 crypto: &Keys,
904 remote_id: ConnectionId,
905 reason: TransportError,
906 buf: &mut Vec<u8>,
907 ) -> Transmit {
908 let local_id = self.local_cid_generator.generate_cid();
912 let number = PacketNumber::U8(0);
913 let header = Header::Initial(InitialHeader {
914 dst_cid: remote_id,
915 src_cid: local_id,
916 number,
917 token: Bytes::new(),
918 version,
919 });
920
921 let partial_encode = header.encode(buf);
922 let max_len =
923 INITIAL_MTU as usize - partial_encode.header_len - crypto.packet.local.tag_len();
924 frame::Close::from(reason).encoder(max_len).encode(buf);
925 buf.resize(buf.len() + crypto.packet.local.tag_len(), 0);
926 partial_encode.finish(
927 buf,
928 &*crypto.header.local,
929 Some((0, Default::default(), &*crypto.packet.local)),
930 );
931 Transmit {
932 destination: network_path.remote,
933 ecn: None,
934 size: buf.len(),
935 segment_size: None,
936 src_ip: network_path.local_ip,
937 }
938 }
939
940 pub fn config(&self) -> &EndpointConfig {
942 &self.config
943 }
944
945 pub fn open_connections(&self) -> usize {
947 self.connections.len()
948 }
949
950 pub fn incoming_buffer_bytes(&self) -> u64 {
953 self.all_incoming_buffers_total_bytes
954 }
955
956 #[cfg(test)]
957 pub(crate) fn known_connections(&self) -> usize {
958 let x = self.connections.len();
959 debug_assert_eq!(x, self.index.connection_ids_initial.len());
960 debug_assert!(x >= self.index.connection_reset_tokens.0.len());
962 debug_assert!(x >= self.index.incoming_connection_remotes.len());
964 debug_assert!(x >= self.index.outgoing_connection_remotes.len());
965 x
966 }
967
968 #[cfg(test)]
969 pub(crate) fn known_cids(&self) -> usize {
970 self.index.connection_ids.len()
971 }
972
973 fn cids_exhausted(&self) -> bool {
978 let cid_len = self.local_cid_generator.cid_len();
979 if cid_len == 0 || cid_len > 4 {
980 return false;
981 }
982
983 let bits = (cid_len * 8) as u32;
985 let space = 1u64 << bits;
986 let reserve = 1u64 << (bits - 2);
987 let len = self.index.connection_ids.len() as u64;
988
989 len > (space - reserve)
990 }
991}
992
993impl fmt::Debug for Endpoint {
994 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
995 fmt.debug_struct("Endpoint")
996 .field("rng", &self.rng)
997 .field("index", &self.index)
998 .field("connections", &self.connections)
999 .field("config", &self.config)
1000 .field("server_config", &self.server_config)
1001 .field("incoming_buffers.len", &self.incoming_buffers.len())
1003 .field(
1004 "all_incoming_buffers_total_bytes",
1005 &self.all_incoming_buffers_total_bytes,
1006 )
1007 .finish()
1008 }
1009}
1010
1011#[derive(Default)]
1013struct IncomingBuffer {
1014 datagrams: Vec<DatagramConnectionEvent>,
1015 total_bytes: u64,
1016}
1017
1018#[derive(Copy, Clone, Debug)]
1020enum RouteDatagramTo {
1021 Incoming(usize),
1022 Connection(ConnectionHandle, PathId),
1023}
1024
1025#[derive(Default, Debug)]
1027struct ConnectionIndex {
1028 connection_ids_initial: HashMap<ConnectionId, RouteDatagramTo>,
1034 connection_ids: FxHashMap<ConnectionId, (ConnectionHandle, PathId)>,
1038 incoming_connection_remotes: HashMap<FourTuple, ConnectionHandle>,
1042 outgoing_connection_remotes: HashMap<SocketAddr, ConnectionHandle>,
1053 connection_reset_tokens: ResetTokenTable,
1058}
1059
1060impl ConnectionIndex {
1061 fn insert_initial_incoming(&mut self, dst_cid: ConnectionId, incoming_key: usize) {
1063 if dst_cid.is_empty() {
1064 return;
1065 }
1066 self.connection_ids_initial
1067 .insert(dst_cid, RouteDatagramTo::Incoming(incoming_key));
1068 }
1069
1070 fn remove_initial(&mut self, dst_cid: ConnectionId) {
1072 if dst_cid.is_empty() {
1073 return;
1074 }
1075 let removed = self.connection_ids_initial.remove(&dst_cid);
1076 debug_assert!(removed.is_some());
1077 }
1078
1079 fn insert_initial(&mut self, dst_cid: ConnectionId, connection: ConnectionHandle) {
1081 if dst_cid.is_empty() {
1082 return;
1083 }
1084 self.connection_ids_initial.insert(
1085 dst_cid,
1086 RouteDatagramTo::Connection(connection, PathId::ZERO),
1087 );
1088 }
1089
1090 fn insert_conn(
1093 &mut self,
1094 network_path: FourTuple,
1095 dst_cid: ConnectionId,
1096 connection: ConnectionHandle,
1097 side: Side,
1098 ) {
1099 match dst_cid.len() {
1100 0 => match side {
1101 Side::Server => {
1102 self.incoming_connection_remotes
1103 .insert(network_path, connection);
1104 }
1105 Side::Client => {
1106 self.outgoing_connection_remotes
1107 .insert(network_path.remote, connection);
1108 }
1109 },
1110 _ => {
1111 self.connection_ids
1112 .insert(dst_cid, (connection, PathId::ZERO));
1113 }
1114 }
1115 }
1116
1117 fn retire(&mut self, dst_cid: ConnectionId) {
1119 self.connection_ids.remove(&dst_cid);
1120 }
1121
1122 fn remove(&mut self, conn: &ConnectionMeta) {
1124 if conn.side.is_server() {
1125 self.remove_initial(conn.init_cid);
1126 }
1127 for cid in conn
1128 .local_cids
1129 .values()
1130 .flat_map(|pcids| pcids.cids.values())
1131 {
1132 self.connection_ids.remove(cid);
1133 }
1134 self.incoming_connection_remotes.remove(&conn.network_path);
1135 self.outgoing_connection_remotes
1136 .remove(&conn.network_path.remote);
1137 for (remote, token) in conn.reset_token.values() {
1138 self.connection_reset_tokens.remove(*remote, *token);
1139 }
1140 }
1141
1142 fn get(&self, network_path: &FourTuple, datagram: &PartialDecode) -> Option<RouteDatagramTo> {
1144 if !datagram.dst_cid().is_empty()
1145 && let Some(&(ch, path_id)) = self.connection_ids.get(&datagram.dst_cid())
1146 {
1147 return Some(RouteDatagramTo::Connection(ch, path_id));
1148 }
1149 if (datagram.is_initial() || datagram.is_0rtt())
1150 && let Some(&ch) = self.connection_ids_initial.get(&datagram.dst_cid())
1151 {
1152 return Some(ch);
1153 }
1154 if datagram.dst_cid().is_empty() {
1155 if let Some(&ch) = self.incoming_connection_remotes.get(network_path) {
1156 return Some(RouteDatagramTo::Connection(ch, PathId::ZERO));
1159 }
1160 if let Some(&ch) = self.outgoing_connection_remotes.get(&network_path.remote) {
1161 return Some(RouteDatagramTo::Connection(ch, PathId::ZERO));
1163 }
1164 }
1165 let data = datagram.data();
1166 if data.len() < RESET_TOKEN_SIZE {
1167 return None;
1168 }
1169 self.connection_reset_tokens
1172 .get(network_path.remote, &data[data.len() - RESET_TOKEN_SIZE..])
1173 .cloned()
1174 .map(|ch| RouteDatagramTo::Connection(ch, PathId::ZERO))
1175 }
1176}
1177
1178#[derive(Debug)]
1179pub(crate) struct ConnectionMeta {
1180 init_cid: ConnectionId,
1181 local_cids: FxHashMap<PathId, PathLocalCids>,
1183 network_path: FourTuple,
1188 side: Side,
1189 reset_token: FxHashMap<PathId, (SocketAddr, ResetToken)>,
1200}
1201
1202#[derive(Debug, Default)]
1204struct PathLocalCids {
1205 issued: u64,
1209 cids: FxHashMap<u64, ConnectionId>,
1211}
1212
1213#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
1215pub struct ConnectionHandle(pub usize);
1216
1217impl From<ConnectionHandle> for usize {
1218 fn from(x: ConnectionHandle) -> Self {
1219 x.0
1220 }
1221}
1222
1223impl Index<ConnectionHandle> for Slab<ConnectionMeta> {
1224 type Output = ConnectionMeta;
1225 fn index(&self, ch: ConnectionHandle) -> &ConnectionMeta {
1226 &self[ch.0]
1227 }
1228}
1229
1230impl IndexMut<ConnectionHandle> for Slab<ConnectionMeta> {
1231 fn index_mut(&mut self, ch: ConnectionHandle) -> &mut ConnectionMeta {
1232 &mut self[ch.0]
1233 }
1234}
1235
1236pub enum DatagramEvent {
1238 ConnectionEvent(ConnectionHandle, ConnectionEvent),
1240 NewConnection(Incoming),
1242 Response(Transmit),
1244}
1245
1246#[derive(derive_more::Debug)]
1248pub struct Incoming {
1249 #[debug(skip)]
1250 received_at: Instant,
1251 network_path: FourTuple,
1252 ecn: Option<EcnCodepoint>,
1253 #[debug(skip)]
1254 packet: InitialPacket,
1255 #[debug(skip)]
1256 rest: Option<BytesMut>,
1257 #[debug(skip)]
1258 crypto: Keys,
1259 token: IncomingToken,
1260 incoming_idx: usize,
1261 #[debug(skip)]
1262 improper_drop_warner: IncomingImproperDropWarner,
1263}
1264
1265impl Incoming {
1266 pub fn local_ip(&self) -> Option<IpAddr> {
1268 self.network_path.local_ip
1269 }
1270
1271 pub fn remote_address(&self) -> SocketAddr {
1273 self.network_path.remote
1274 }
1275
1276 pub fn remote_address_validated(&self) -> bool {
1284 self.token.validated
1285 }
1286
1287 pub fn may_retry(&self) -> bool {
1292 self.token.retry_src_cid.is_none()
1293 }
1294
1295 pub fn orig_dst_cid(&self) -> ConnectionId {
1297 self.token.orig_dst_cid
1298 }
1299
1300 pub fn decrypt(&self) -> Option<DecryptedInitial> {
1306 let packet_number = self.packet.header.number.expand(0);
1307 let mut payload = self.packet.payload.clone();
1308 self.crypto
1309 .packet
1310 .remote
1311 .decrypt(
1312 PathId::ZERO,
1313 packet_number,
1314 &self.packet.header_data,
1315 &mut payload,
1316 )
1317 .ok()?;
1318 Some(DecryptedInitial(payload.freeze()))
1319 }
1320}
1321
1322pub struct DecryptedInitial(Bytes);
1327
1328impl DecryptedInitial {
1329 pub fn alpns(&self) -> Option<IncomingAlpns> {
1335 let frames = frame::Iter::new(self.0.clone()).ok()?;
1336 let mut first = None;
1337 let mut rest = Vec::new();
1338 for frame in frames {
1339 match frame {
1340 Ok(frame::Frame::Crypto(crypto)) => match first {
1341 None => first = Some(crypto),
1342 Some(_) => rest.push(crypto),
1343 },
1344 Err(_) => return None,
1345 _ => {}
1346 }
1347 }
1348 let first = first?;
1349
1350 if rest.is_empty() && first.offset == 0 {
1352 let data = find_alpn_data(&first.data).ok()?;
1353 return Some(IncomingAlpns { data, pos: 0 });
1354 }
1355
1356 rest.push(first);
1358 let source = assemble_crypto_frames(&mut rest)?;
1359 let data = find_alpn_data(&source).ok()?;
1360 Some(IncomingAlpns { data, pos: 0 })
1361 }
1362}
1363
1364const TLS_HANDSHAKE_TYPE_CLIENT_HELLO: u8 = 0x01;
1367const TLS_EXTENSION_TYPE_ALPN: u16 = 0x0010;
1370const TLS_CLIENT_HELLO_FIXED_LEN: usize = 2 + 32;
1373
1374pub struct IncomingAlpns {
1379 data: Bytes,
1380 pos: usize,
1381}
1382
1383impl Iterator for IncomingAlpns {
1384 type Item = Result<Bytes, UnexpectedEnd>;
1385
1386 fn next(&mut self) -> Option<Self::Item> {
1387 if self.pos >= self.data.len() {
1388 return None;
1389 }
1390 let len = self.data[self.pos] as usize;
1391 self.pos += 1;
1392 if self.pos + len > self.data.len() {
1393 return Some(Err(UnexpectedEnd));
1394 }
1395 let proto = self.data.slice(self.pos..self.pos + len);
1396 self.pos += len;
1397 Some(Ok(proto))
1398 }
1399}
1400
1401fn assemble_crypto_frames(frames: &mut [frame::Crypto]) -> Option<Bytes> {
1405 frames.sort_by_key(|f| f.offset);
1406 let capacity = frames.iter().map(|f| f.data.len()).sum();
1407 let mut buf = Vec::with_capacity(capacity);
1408 for f in frames.iter() {
1409 let start = f.offset as usize;
1410 if start > buf.len() {
1411 return None;
1412 }
1413 let end = start + f.data.len();
1414 if end > buf.len() {
1415 buf.extend_from_slice(&f.data[buf.len() - start..]);
1416 }
1417 }
1418 Some(Bytes::from(buf))
1419}
1420
1421fn find_alpn_data(source: &Bytes) -> Result<Bytes, UnexpectedEnd> {
1427 let mut r = &**source;
1428
1429 if u8::decode(&mut r)? != TLS_HANDSHAKE_TYPE_CLIENT_HELLO {
1430 return Err(UnexpectedEnd);
1431 }
1432
1433 let len = decode_u24(&mut r)?;
1435 let mut body = take(&mut r, len)?;
1436
1437 skip(&mut body, TLS_CLIENT_HELLO_FIXED_LEN)?;
1439
1440 skip_u8_prefixed(&mut body)?;
1442 skip_u16_prefixed(&mut body)?;
1443 skip_u8_prefixed(&mut body)?;
1444
1445 let mut exts = take_u16_prefixed(&mut body)?;
1447 while exts.has_remaining() {
1448 let ext_type = u16::decode(&mut exts)?;
1449 let ext_data = take_u16_prefixed(&mut exts)?;
1450 if ext_type == TLS_EXTENSION_TYPE_ALPN {
1451 let list = take_u16_prefixed(&mut &*ext_data)?;
1452 return Ok(source.slice_ref(list));
1453 }
1454 }
1455 Err(UnexpectedEnd)
1456}
1457
1458fn decode_u24(r: &mut &[u8]) -> Result<usize, UnexpectedEnd> {
1460 let a = u8::decode(r)?;
1461 let b = u8::decode(r)?;
1462 let c = u8::decode(r)?;
1463 Ok(u32::from_be_bytes([0, a, b, c]) as usize)
1464}
1465
1466fn take<'a>(r: &mut &'a [u8], len: usize) -> Result<&'a [u8], UnexpectedEnd> {
1468 if r.remaining() < len {
1469 return Err(UnexpectedEnd);
1470 }
1471 let data = &r[..len];
1472 r.advance(len);
1473 Ok(data)
1474}
1475
1476fn take_u16_prefixed<'a>(r: &mut &'a [u8]) -> Result<&'a [u8], UnexpectedEnd> {
1478 let len = u16::decode(r)? as usize;
1479 take(r, len)
1480}
1481
1482fn skip(r: &mut &[u8], len: usize) -> Result<(), UnexpectedEnd> {
1484 take(r, len)?;
1485 Ok(())
1486}
1487
1488fn skip_u8_prefixed(r: &mut &[u8]) -> Result<(), UnexpectedEnd> {
1490 let len = u8::decode(r)? as usize;
1491 skip(r, len)
1492}
1493
1494fn skip_u16_prefixed(r: &mut &[u8]) -> Result<(), UnexpectedEnd> {
1496 let len = u16::decode(r)? as usize;
1497 skip(r, len)
1498}
1499
1500struct IncomingImproperDropWarner;
1501
1502impl IncomingImproperDropWarner {
1503 fn dismiss(self) {
1504 mem::forget(self);
1505 }
1506}
1507
1508impl Drop for IncomingImproperDropWarner {
1509 fn drop(&mut self) {
1510 warn!(
1511 "noq_proto::Incoming dropped without passing to Endpoint::accept/refuse/retry/ignore \
1512 (may cause memory leak and eventual inability to accept new connections)"
1513 );
1514 }
1515}
1516
1517#[derive(Debug, Error, Clone, PartialEq, Eq)]
1521pub enum ConnectError {
1522 #[error("endpoint stopping")]
1526 EndpointStopping,
1527 #[error("CIDs exhausted")]
1531 CidsExhausted,
1532 #[error("invalid server name: {0}")]
1534 InvalidServerName(String),
1535 #[error("invalid remote address: {0}")]
1539 InvalidRemoteAddress(SocketAddr),
1540 #[error("no default client config")]
1544 NoDefaultClientConfig,
1545 #[error("unsupported QUIC version")]
1547 UnsupportedVersion,
1548}
1549
1550#[derive(Debug)]
1552pub struct AcceptError {
1553 pub cause: ConnectionError,
1555 pub response: Option<Transmit>,
1557}
1558
1559#[derive(Debug, Error)]
1561#[error("retry() with validated Incoming")]
1562pub struct RetryError(Box<Incoming>);
1563
1564impl RetryError {
1565 pub fn into_incoming(self) -> Incoming {
1567 *self.0
1568 }
1569}
1570
1571#[derive(Default, Debug)]
1576struct ResetTokenTable(HashMap<SocketAddr, HashMap<ResetToken, ConnectionHandle>>);
1577
1578impl ResetTokenTable {
1579 fn insert(&mut self, remote: SocketAddr, token: ResetToken, ch: ConnectionHandle) -> bool {
1580 self.0
1581 .entry(remote)
1582 .or_default()
1583 .insert(token, ch)
1584 .is_some()
1585 }
1586
1587 fn remove(&mut self, remote: SocketAddr, token: ResetToken) {
1588 use std::collections::hash_map::Entry;
1589 match self.0.entry(remote) {
1590 Entry::Vacant(_) => {}
1591 Entry::Occupied(mut e) => {
1592 e.get_mut().remove(&token);
1593 if e.get().is_empty() {
1594 e.remove_entry();
1595 }
1596 }
1597 }
1598 }
1599
1600 fn get(&self, remote: SocketAddr, token: &[u8]) -> Option<&ConnectionHandle> {
1601 let token = ResetToken::from(<[u8; RESET_TOKEN_SIZE]>::try_from(token).ok()?);
1602 self.0.get(&remote)?.get(&token)
1603 }
1604}
1605
1606#[cfg(test)]
1607mod tests {
1608 use super::*;
1609
1610 #[test]
1611 fn assemble_contiguous() {
1612 let data = b"hello world";
1613 let mut frames = vec![
1614 frame::Crypto {
1615 offset: 0,
1616 data: Bytes::from_static(&data[..5]),
1617 },
1618 frame::Crypto {
1619 offset: 5,
1620 data: Bytes::from_static(&data[5..]),
1621 },
1622 ];
1623 assert_eq!(&assemble_crypto_frames(&mut frames).unwrap()[..], &data[..]);
1624 }
1625
1626 #[test]
1627 fn assemble_out_of_order() {
1628 let data = b"hello world";
1629 let mut frames = vec![
1630 frame::Crypto {
1631 offset: 5,
1632 data: Bytes::from_static(&data[5..]),
1633 },
1634 frame::Crypto {
1635 offset: 0,
1636 data: Bytes::from_static(&data[..5]),
1637 },
1638 ];
1639 assert_eq!(&assemble_crypto_frames(&mut frames).unwrap()[..], &data[..]);
1640 }
1641
1642 #[test]
1643 fn assemble_with_overlap() {
1644 let data = b"hello world";
1645 let mut frames = vec![
1646 frame::Crypto {
1647 offset: 0,
1648 data: Bytes::from_static(&data[..7]),
1649 },
1650 frame::Crypto {
1651 offset: 5,
1652 data: Bytes::from_static(&data[5..]),
1653 },
1654 ];
1655 assert_eq!(&assemble_crypto_frames(&mut frames).unwrap()[..], &data[..]);
1656 }
1657
1658 #[test]
1659 fn assemble_with_gap() {
1660 let mut frames = vec![frame::Crypto {
1661 offset: 10,
1662 data: Bytes::from_static(b"world"),
1663 }];
1664 assert!(assemble_crypto_frames(&mut frames).is_none());
1665 }
1666}