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 Drained => {
133 if let Some(conn) = self.connections.try_remove(ch.0) {
134 self.index.remove(&conn);
135 } else {
136 error!(id = ch.0, "unknown connection drained");
140 }
141 }
142 }
143 None
144 }
145
146 pub fn handle(
148 &mut self,
149 now: Instant,
150 network_path: FourTuple,
151 ecn: Option<EcnCodepoint>,
152 data: BytesMut,
153 buf: &mut Vec<u8>,
154 ) -> Option<DatagramEvent> {
155 let datagram_len = data.len();
157 let mut event = match PartialDecode::new(
158 data,
159 &FixedLengthConnectionIdParser::new(self.local_cid_generator.cid_len()),
160 &self.config.supported_versions,
161 self.config.grease_quic_bit,
162 ) {
163 Ok((first_decode, remaining)) => DatagramConnectionEvent {
164 now,
165 network_path,
166 path_id: PathId::ZERO, ecn,
168 first_decode,
169 remaining,
170 },
171 Err(PacketDecodeError::UnsupportedVersion {
172 src_cid,
173 dst_cid,
174 version,
175 }) => {
176 if self.server_config.is_none() {
177 debug!("dropping packet with unsupported version");
178 return None;
179 }
180 trace!("sending version negotiation");
181 Header::VersionNegotiate {
183 random: self.rng.random::<u8>() | 0x40,
184 src_cid: dst_cid,
185 dst_cid: src_cid,
186 }
187 .encode(buf);
188 buf.write::<u32>(match version {
190 0x0a1a_2a3a => 0x0a1a_2a4a,
191 _ => 0x0a1a_2a3a,
192 });
193 for &version in &self.config.supported_versions {
194 buf.write(version);
195 }
196 return Some(DatagramEvent::Response(Transmit {
197 destination: network_path.remote,
198 ecn: None,
199 size: buf.len(),
200 segment_size: None,
201 src_ip: network_path.local_ip,
202 }));
203 }
204 Err(e) => {
205 trace!("malformed header: {}", e);
206 return None;
207 }
208 };
209
210 let dst_cid = event.first_decode.dst_cid();
211
212 if let Some(route_to) = self.index.get(&network_path, &event.first_decode) {
213 event.path_id = match route_to {
214 RouteDatagramTo::Incoming(_) => PathId::ZERO,
215 RouteDatagramTo::Connection(_, path_id) => path_id,
216 };
217 match route_to {
218 RouteDatagramTo::Incoming(incoming_idx) => {
219 let incoming_buffer = &mut self.incoming_buffers[incoming_idx];
220 let config = &self.server_config.as_ref().unwrap();
221
222 if incoming_buffer
223 .total_bytes
224 .checked_add(datagram_len as u64)
225 .is_some_and(|n| n <= config.incoming_buffer_size)
226 && self
227 .all_incoming_buffers_total_bytes
228 .checked_add(datagram_len as u64)
229 .is_some_and(|n| n <= config.incoming_buffer_size_total)
230 {
231 incoming_buffer.datagrams.push(event);
232 incoming_buffer.total_bytes += datagram_len as u64;
233 self.all_incoming_buffers_total_bytes += datagram_len as u64;
234 }
235
236 None
237 }
238 RouteDatagramTo::Connection(ch, _path_id) => Some(DatagramEvent::ConnectionEvent(
239 ch,
240 ConnectionEvent(ConnectionEventInner::Datagram(event)),
241 )),
242 }
243 } else if event.first_decode.initial_header().is_some() {
244 self.handle_first_packet(datagram_len, event, network_path, buf)
247 } else if event.first_decode.has_long_header() {
248 debug!(
249 "ignoring non-initial packet for unknown connection {}",
250 dst_cid
251 );
252 None
253 } else if !event.first_decode.is_initial()
254 && self.local_cid_generator.validate(dst_cid).is_err()
255 {
256 debug!("dropping packet with invalid CID");
257 None
258 } else if dst_cid.is_empty() {
259 trace!("dropping unrecognized short packet without ID");
260 None
261 } else {
262 self.stateless_reset(now, datagram_len, network_path, dst_cid, buf)
265 .map(DatagramEvent::Response)
266 }
267 }
268
269 fn stateless_reset(
271 &mut self,
272 now: Instant,
273 inciting_dgram_len: usize,
274 network_path: FourTuple,
275 dst_cid: ConnectionId,
276 buf: &mut Vec<u8>,
277 ) -> Option<Transmit> {
278 if self
279 .last_stateless_reset
280 .is_some_and(|last| last + self.config.min_reset_interval > now)
281 {
282 debug!("ignoring unexpected packet within minimum stateless reset interval");
283 return None;
284 }
285
286 const MIN_PADDING_LEN: usize = 5;
288
289 let max_padding_len = match inciting_dgram_len.checked_sub(RESET_TOKEN_SIZE) {
292 Some(headroom) if headroom > MIN_PADDING_LEN => headroom - 1,
293 _ => {
294 debug!(
295 "ignoring unexpected {} byte packet: not larger than minimum stateless reset size",
296 inciting_dgram_len
297 );
298 return None;
299 }
300 };
301
302 debug!(%dst_cid, %network_path.remote, "sending stateless reset");
303 self.last_stateless_reset = Some(now);
304 const IDEAL_MIN_PADDING_LEN: usize = MIN_PADDING_LEN + MAX_CID_SIZE;
306 let padding_len = if max_padding_len <= IDEAL_MIN_PADDING_LEN {
307 max_padding_len
308 } else {
309 self.rng
310 .random_range(IDEAL_MIN_PADDING_LEN..max_padding_len)
311 };
312 buf.reserve(padding_len + RESET_TOKEN_SIZE);
313 buf.resize(padding_len, 0);
314 self.rng.fill_bytes(&mut buf[0..padding_len]);
315 buf[0] = 0b0100_0000 | (buf[0] >> 2);
316 buf.extend_from_slice(&ResetToken::new(&*self.config.reset_key, dst_cid));
317
318 debug_assert!(buf.len() < inciting_dgram_len);
319
320 Some(Transmit {
321 destination: network_path.remote,
322 ecn: None,
323 size: buf.len(),
324 segment_size: None,
325 src_ip: network_path.local_ip,
326 })
327 }
328
329 pub fn connect(
331 &mut self,
332 now: Instant,
333 config: ClientConfig,
334 remote: SocketAddr,
335 server_name: &str,
336 ) -> Result<(ConnectionHandle, Connection), ConnectError> {
337 if self.cids_exhausted() {
338 return Err(ConnectError::CidsExhausted);
339 }
340 if remote.port() == 0 || remote.ip().is_unspecified() {
341 return Err(ConnectError::InvalidRemoteAddress(remote));
342 }
343 if !self.config.supported_versions.contains(&config.version) {
344 return Err(ConnectError::UnsupportedVersion);
345 }
346
347 let remote_id = (config.initial_dst_cid_provider)();
348 trace!(initial_dcid = %remote_id);
349
350 let ch = ConnectionHandle(self.connections.vacant_key());
351 let local_cid = self.new_cid(ch, PathId::ZERO);
352 let params = TransportParameters::new(
353 &config.transport,
354 &self.config,
355 self.local_cid_generator.as_ref(),
356 local_cid,
357 None,
358 &mut self.rng,
359 );
360 let tls = config
361 .crypto
362 .start_session(config.version, server_name, ¶ms)?;
363
364 let conn = self.add_connection(
365 ch,
366 config.version,
367 remote_id,
368 local_cid,
369 remote_id,
370 FourTuple {
371 remote,
372 local_ip: None,
373 },
374 now,
375 tls,
376 config.transport,
377 SideArgs::Client {
378 token_store: config.token_store,
379 server_name: server_name.into(),
380 },
381 ¶ms,
382 );
383 Ok((ch, conn))
384 }
385
386 fn send_new_identifiers(
388 &mut self,
389 path_id: PathId,
390 now: Instant,
391 ch: ConnectionHandle,
392 num: u64,
393 ) -> ConnectionEvent {
394 let mut ids = vec![];
395 for _ in 0..num {
396 let id = self.new_cid(ch, path_id);
397 let cid_meta = self.connections[ch].local_cids.entry(path_id).or_default();
398 let sequence = cid_meta.issued;
399 cid_meta.issued += 1;
400 cid_meta.cids.insert(sequence, id);
401 ids.push(IssuedCid {
402 path_id,
403 sequence,
404 id,
405 reset_token: ResetToken::new(&*self.config.reset_key, id),
406 });
407 }
408 ConnectionEvent(ConnectionEventInner::NewIdentifiers(
409 ids,
410 now,
411 self.local_cid_generator.cid_len(),
412 self.local_cid_generator.cid_lifetime(),
413 ))
414 }
415
416 fn new_cid(&mut self, ch: ConnectionHandle, path_id: PathId) -> ConnectionId {
418 loop {
419 let cid = self.local_cid_generator.generate_cid();
420 if cid.is_empty() {
421 debug_assert_eq!(self.local_cid_generator.cid_len(), 0);
423 return cid;
424 }
425 if let hash_map::Entry::Vacant(e) = self.index.connection_ids.entry(cid) {
426 e.insert((ch, path_id));
427 break cid;
428 }
429 }
430 }
431
432 fn handle_first_packet(
433 &mut self,
434 datagram_len: usize,
435 event: DatagramConnectionEvent,
436 network_path: FourTuple,
437 buf: &mut Vec<u8>,
438 ) -> Option<DatagramEvent> {
439 let dst_cid = event.first_decode.dst_cid();
440 let header = event.first_decode.initial_header().unwrap();
441
442 let Some(server_config) = &self.server_config else {
443 debug!("packet for unrecognized connection {}", dst_cid);
444 return self
445 .stateless_reset(event.now, datagram_len, network_path, dst_cid, buf)
446 .map(DatagramEvent::Response);
447 };
448
449 if datagram_len < MIN_INITIAL_SIZE as usize {
450 debug!("ignoring short initial for connection {}", dst_cid);
451 return None;
452 }
453
454 let crypto = match server_config.crypto.initial_keys(header.version, dst_cid) {
455 Ok(keys) => keys,
456 Err(UnsupportedVersion) => {
457 debug!(
460 "ignoring initial packet version {:#x} unsupported by cryptographic layer",
461 header.version
462 );
463 return None;
464 }
465 };
466
467 if let Err(reason) = self.early_validate_first_packet(header) {
468 return Some(DatagramEvent::Response(self.initial_close(
469 header.version,
470 network_path,
471 &crypto,
472 header.src_cid,
473 reason,
474 buf,
475 )));
476 }
477
478 let packet = match event.first_decode.finish(Some(&*crypto.header.remote)) {
479 Ok(packet) => packet,
480 Err(e) => {
481 trace!("unable to decode initial packet: {}", e);
482 return None;
483 }
484 };
485
486 if !packet.reserved_bits_valid() {
487 debug!("dropping connection attempt with invalid reserved bits");
488 return None;
489 }
490
491 let Header::Initial(header) = packet.header else {
492 panic!("non-initial packet in handle_first_packet()");
493 };
494
495 let server_config = self.server_config.as_ref().unwrap().clone();
496
497 let token = match IncomingToken::from_header(&header, &server_config, network_path.remote) {
498 Ok(token) => token,
499 Err(InvalidRetryTokenError) => {
500 debug!("rejecting invalid retry token");
501 return Some(DatagramEvent::Response(self.initial_close(
502 header.version,
503 network_path,
504 &crypto,
505 header.src_cid,
506 TransportError::INVALID_TOKEN(""),
507 buf,
508 )));
509 }
510 };
511
512 let incoming_idx = self.incoming_buffers.insert(IncomingBuffer::default());
513 self.index
514 .insert_initial_incoming(header.dst_cid, incoming_idx);
515
516 Some(DatagramEvent::NewConnection(Incoming {
517 received_at: event.now,
518 network_path,
519 ecn: event.ecn,
520 packet: InitialPacket {
521 header,
522 header_data: packet.header_data,
523 payload: packet.payload,
524 },
525 rest: event.remaining,
526 crypto,
527 token,
528 incoming_idx,
529 improper_drop_warner: IncomingImproperDropWarner,
530 }))
531 }
532
533 pub fn accept(
536 &mut self,
537 mut incoming: Incoming,
538 now: Instant,
539 buf: &mut Vec<u8>,
540 server_config: Option<Arc<ServerConfig>>,
541 ) -> Result<(ConnectionHandle, Connection), Box<AcceptError>> {
542 let remote_address_validated = incoming.remote_address_validated();
543 incoming.improper_drop_warner.dismiss();
544 let incoming_buffer = self.incoming_buffers.remove(incoming.incoming_idx);
545 self.all_incoming_buffers_total_bytes -= incoming_buffer.total_bytes;
546
547 let packet_number = incoming.packet.header.number.expand(0);
548 let InitialHeader {
549 src_cid,
550 dst_cid,
551 version,
552 ..
553 } = incoming.packet.header;
554 let server_config =
555 server_config.unwrap_or_else(|| self.server_config.as_ref().unwrap().clone());
556
557 if server_config
558 .transport
559 .max_idle_timeout
560 .is_some_and(|timeout| {
561 incoming.received_at + Duration::from_millis(timeout.into()) <= now
562 })
563 {
564 debug!("abandoning accept of stale initial");
565 self.index.remove_initial(dst_cid);
566 return Err(Box::new(AcceptError {
567 cause: ConnectionError::TimedOut,
568 response: None,
569 }));
570 }
571
572 if self.cids_exhausted() {
573 debug!("refusing connection");
574 self.index.remove_initial(dst_cid);
575 return Err(Box::new(AcceptError {
576 cause: ConnectionError::CidsExhausted,
577 response: Some(self.initial_close(
578 version,
579 incoming.network_path,
580 &incoming.crypto,
581 src_cid,
582 TransportError::CONNECTION_REFUSED(""),
583 buf,
584 )),
585 }));
586 }
587
588 if incoming
589 .crypto
590 .packet
591 .remote
592 .decrypt(
593 PathId::ZERO,
594 packet_number,
595 &incoming.packet.header_data,
596 &mut incoming.packet.payload,
597 )
598 .is_err()
599 {
600 debug!(packet_number, "failed to authenticate initial packet");
601 self.index.remove_initial(dst_cid);
602 return Err(Box::new(AcceptError {
603 cause: TransportError::PROTOCOL_VIOLATION("authentication failed").into(),
604 response: None,
605 }));
606 };
607
608 let ch = ConnectionHandle(self.connections.vacant_key());
609 let local_cid = self.new_cid(ch, PathId::ZERO);
610 let mut params = TransportParameters::new(
611 &server_config.transport,
612 &self.config,
613 self.local_cid_generator.as_ref(),
614 local_cid,
615 Some(&server_config),
616 &mut self.rng,
617 );
618 params.stateless_reset_token = Some(ResetToken::new(&*self.config.reset_key, local_cid));
619 params.original_dst_cid = Some(incoming.token.orig_dst_cid);
620 params.retry_src_cid = incoming.token.retry_src_cid;
621 let mut pref_addr_cid = None;
622 if server_config.has_preferred_address() {
623 let cid = self.new_cid(ch, PathId::ZERO);
624 pref_addr_cid = Some(cid);
625 params.preferred_address = Some(PreferredAddress {
626 address_v4: server_config.preferred_address_v4,
627 address_v6: server_config.preferred_address_v6,
628 connection_id: cid,
629 stateless_reset_token: ResetToken::new(&*self.config.reset_key, cid),
630 });
631 }
632
633 let tls = server_config.crypto.start_session(version, ¶ms);
634 let transport_config = server_config.transport.clone();
635 let mut conn = self.add_connection(
636 ch,
637 version,
638 dst_cid,
639 local_cid,
640 src_cid,
641 incoming.network_path,
642 incoming.received_at,
643 tls,
644 transport_config,
645 SideArgs::Server {
646 server_config,
647 pref_addr_cid,
648 path_validated: remote_address_validated,
649 },
650 ¶ms,
651 );
652 self.index.insert_initial(dst_cid, ch);
653
654 match conn.handle_first_packet(
655 incoming.received_at,
656 incoming.network_path,
657 incoming.ecn,
658 packet_number,
659 incoming.packet,
660 incoming.rest,
661 ) {
662 Ok(()) => {
663 trace!(id = ch.0, icid = %dst_cid, "new connection");
664
665 for event in incoming_buffer.datagrams {
666 conn.handle_event(ConnectionEvent(ConnectionEventInner::Datagram(event)))
667 }
668
669 Ok((ch, conn))
670 }
671 Err(e) => {
672 debug!("handshake failed: {}", e);
673 self.handle_event(ch, EndpointEvent(EndpointEventInner::Drained));
674 let response = match e {
675 ConnectionError::TransportError(ref e) => Some(self.initial_close(
676 version,
677 incoming.network_path,
678 &incoming.crypto,
679 src_cid,
680 e.clone(),
681 buf,
682 )),
683 _ => None,
684 };
685 Err(Box::new(AcceptError { cause: e, response }))
686 }
687 }
688 }
689
690 fn early_validate_first_packet(
692 &mut self,
693 header: &ProtectedInitialHeader,
694 ) -> Result<(), TransportError> {
695 let config = &self.server_config.as_ref().unwrap();
696 if self.cids_exhausted() || self.incoming_buffers.len() >= config.max_incoming {
697 return Err(TransportError::CONNECTION_REFUSED(""));
698 }
699
700 if header.dst_cid.len() < 8
705 && (header.token_pos.is_empty()
706 || header.dst_cid.len() != self.local_cid_generator.cid_len())
707 {
708 debug!(
709 "rejecting connection due to invalid DCID length {}",
710 header.dst_cid.len()
711 );
712 return Err(TransportError::PROTOCOL_VIOLATION(
713 "invalid destination CID length",
714 ));
715 }
716
717 Ok(())
718 }
719
720 pub fn refuse(&mut self, incoming: Incoming, buf: &mut Vec<u8>) -> Transmit {
722 self.clean_up_incoming(&incoming);
723 incoming.improper_drop_warner.dismiss();
724
725 self.initial_close(
726 incoming.packet.header.version,
727 incoming.network_path,
728 &incoming.crypto,
729 incoming.packet.header.src_cid,
730 TransportError::CONNECTION_REFUSED(""),
731 buf,
732 )
733 }
734
735 pub fn retry(&mut self, incoming: Incoming, buf: &mut Vec<u8>) -> Result<Transmit, RetryError> {
739 if !incoming.may_retry() {
740 return Err(RetryError(Box::new(incoming)));
741 }
742
743 self.clean_up_incoming(&incoming);
744 incoming.improper_drop_warner.dismiss();
745
746 let server_config = self.server_config.as_ref().unwrap();
747
748 let local_cid = self.local_cid_generator.generate_cid();
755
756 let payload = TokenPayload::Retry {
757 address: incoming.network_path.remote,
758 orig_dst_cid: incoming.packet.header.dst_cid,
759 issued: server_config.time_source.now(),
760 };
761 let token = Token::new(payload, &mut self.rng).encode(&*server_config.token_key);
762
763 let header = Header::Retry {
764 src_cid: local_cid,
765 dst_cid: incoming.packet.header.src_cid,
766 version: incoming.packet.header.version,
767 };
768
769 let encode = header.encode(buf);
770 buf.put_slice(&token);
771 buf.extend_from_slice(&server_config.crypto.retry_tag(
772 incoming.packet.header.version,
773 incoming.packet.header.dst_cid,
774 buf,
775 ));
776 encode.finish(buf, &*incoming.crypto.header.local, None);
777
778 Ok(Transmit {
779 destination: incoming.network_path.remote,
780 ecn: None,
781 size: buf.len(),
782 segment_size: None,
783 src_ip: incoming.network_path.local_ip,
784 })
785 }
786
787 pub fn ignore(&mut self, incoming: Incoming) {
792 self.clean_up_incoming(&incoming);
793 incoming.improper_drop_warner.dismiss();
794 }
795
796 fn clean_up_incoming(&mut self, incoming: &Incoming) {
798 self.index.remove_initial(incoming.packet.header.dst_cid);
799 let incoming_buffer = self.incoming_buffers.remove(incoming.incoming_idx);
800 self.all_incoming_buffers_total_bytes -= incoming_buffer.total_bytes;
801 }
802
803 fn add_connection(
804 &mut self,
805 ch: ConnectionHandle,
806 version: u32,
807 init_cid: ConnectionId,
808 local_cid: ConnectionId,
809 remote_cid: ConnectionId,
810 network_path: FourTuple,
811 now: Instant,
812 tls: Box<dyn crypto::Session>,
813 transport_config: Arc<TransportConfig>,
814 side_args: SideArgs,
815 params: &TransportParameters,
817 ) -> Connection {
818 let mut rng_seed = [0; 32];
819 self.rng.fill_bytes(&mut rng_seed);
820 let side = side_args.side();
821 let pref_addr_cid = side_args.pref_addr_cid();
822
823 let qlog =
824 transport_config.create_qlog_sink(side_args.side(), network_path.remote, init_cid, now);
825
826 qlog.emit_connection_started(
827 now,
828 local_cid,
829 remote_cid,
830 network_path.remote,
831 network_path.local_ip,
832 params,
833 );
834
835 let conn = Connection::new(
836 self.config.clone(),
837 transport_config,
838 init_cid,
839 local_cid,
840 remote_cid,
841 network_path,
842 tls,
843 self.local_cid_generator.as_ref(),
844 now,
845 version,
846 self.allow_mtud,
847 rng_seed,
848 side_args,
849 qlog,
850 );
851
852 let mut path_cids = PathLocalCids::default();
853 path_cids.cids.insert(path_cids.issued, local_cid);
854 path_cids.issued += 1;
855
856 if let Some(cid) = pref_addr_cid {
857 debug_assert_eq!(path_cids.issued, 1, "preferred address cid seq must be 1");
858 path_cids.cids.insert(path_cids.issued, cid);
859 path_cids.issued += 1;
860 }
861
862 let id = self.connections.insert(ConnectionMeta {
863 init_cid,
864 local_cids: FxHashMap::from_iter([(PathId::ZERO, path_cids)]),
865 network_path,
866 side,
867 reset_token: Default::default(),
868 });
869 debug_assert_eq!(id, ch.0, "connection handle allocation out of sync");
870
871 self.index.insert_conn(network_path, local_cid, ch, side);
872
873 conn
874 }
875
876 fn initial_close(
877 &mut self,
878 version: u32,
879 network_path: FourTuple,
880 crypto: &Keys,
881 remote_id: ConnectionId,
882 reason: TransportError,
883 buf: &mut Vec<u8>,
884 ) -> Transmit {
885 let local_id = self.local_cid_generator.generate_cid();
889 let number = PacketNumber::U8(0);
890 let header = Header::Initial(InitialHeader {
891 dst_cid: remote_id,
892 src_cid: local_id,
893 number,
894 token: Bytes::new(),
895 version,
896 });
897
898 let partial_encode = header.encode(buf);
899 let max_len =
900 INITIAL_MTU as usize - partial_encode.header_len - crypto.packet.local.tag_len();
901 frame::Close::from(reason).encoder(max_len).encode(buf);
902 buf.resize(buf.len() + crypto.packet.local.tag_len(), 0);
903 partial_encode.finish(
904 buf,
905 &*crypto.header.local,
906 Some((0, Default::default(), &*crypto.packet.local)),
907 );
908 Transmit {
909 destination: network_path.remote,
910 ecn: None,
911 size: buf.len(),
912 segment_size: None,
913 src_ip: network_path.local_ip,
914 }
915 }
916
917 pub fn config(&self) -> &EndpointConfig {
919 &self.config
920 }
921
922 pub fn open_connections(&self) -> usize {
924 self.connections.len()
925 }
926
927 pub fn incoming_buffer_bytes(&self) -> u64 {
930 self.all_incoming_buffers_total_bytes
931 }
932
933 #[cfg(test)]
934 pub(crate) fn known_connections(&self) -> usize {
935 let x = self.connections.len();
936 debug_assert_eq!(x, self.index.connection_ids_initial.len());
937 debug_assert!(x >= self.index.connection_reset_tokens.0.len());
939 debug_assert!(x >= self.index.incoming_connection_remotes.len());
941 debug_assert!(x >= self.index.outgoing_connection_remotes.len());
942 x
943 }
944
945 #[cfg(test)]
946 pub(crate) fn known_cids(&self) -> usize {
947 self.index.connection_ids.len()
948 }
949
950 fn cids_exhausted(&self) -> bool {
955 let cid_len = self.local_cid_generator.cid_len();
956 if cid_len == 0 || cid_len > 4 {
957 return false;
958 }
959
960 let bits = (cid_len * 8) as u32;
962 let space = 1u64 << bits;
963 let reserve = 1u64 << (bits - 2);
964 let len = self.index.connection_ids.len() as u64;
965
966 len > (space - reserve)
967 }
968}
969
970impl fmt::Debug for Endpoint {
971 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
972 fmt.debug_struct("Endpoint")
973 .field("rng", &self.rng)
974 .field("index", &self.index)
975 .field("connections", &self.connections)
976 .field("config", &self.config)
977 .field("server_config", &self.server_config)
978 .field("incoming_buffers.len", &self.incoming_buffers.len())
980 .field(
981 "all_incoming_buffers_total_bytes",
982 &self.all_incoming_buffers_total_bytes,
983 )
984 .finish()
985 }
986}
987
988#[derive(Default)]
990struct IncomingBuffer {
991 datagrams: Vec<DatagramConnectionEvent>,
992 total_bytes: u64,
993}
994
995#[derive(Copy, Clone, Debug)]
997enum RouteDatagramTo {
998 Incoming(usize),
999 Connection(ConnectionHandle, PathId),
1000}
1001
1002#[derive(Default, Debug)]
1004struct ConnectionIndex {
1005 connection_ids_initial: HashMap<ConnectionId, RouteDatagramTo>,
1011 connection_ids: FxHashMap<ConnectionId, (ConnectionHandle, PathId)>,
1015 incoming_connection_remotes: HashMap<FourTuple, ConnectionHandle>,
1019 outgoing_connection_remotes: HashMap<SocketAddr, ConnectionHandle>,
1029 connection_reset_tokens: ResetTokenTable,
1034}
1035
1036impl ConnectionIndex {
1037 fn insert_initial_incoming(&mut self, dst_cid: ConnectionId, incoming_key: usize) {
1039 if dst_cid.is_empty() {
1040 return;
1041 }
1042 self.connection_ids_initial
1043 .insert(dst_cid, RouteDatagramTo::Incoming(incoming_key));
1044 }
1045
1046 fn remove_initial(&mut self, dst_cid: ConnectionId) {
1048 if dst_cid.is_empty() {
1049 return;
1050 }
1051 let removed = self.connection_ids_initial.remove(&dst_cid);
1052 debug_assert!(removed.is_some());
1053 }
1054
1055 fn insert_initial(&mut self, dst_cid: ConnectionId, connection: ConnectionHandle) {
1057 if dst_cid.is_empty() {
1058 return;
1059 }
1060 self.connection_ids_initial.insert(
1061 dst_cid,
1062 RouteDatagramTo::Connection(connection, PathId::ZERO),
1063 );
1064 }
1065
1066 fn insert_conn(
1069 &mut self,
1070 network_path: FourTuple,
1071 dst_cid: ConnectionId,
1072 connection: ConnectionHandle,
1073 side: Side,
1074 ) {
1075 match dst_cid.len() {
1076 0 => match side {
1077 Side::Server => {
1078 self.incoming_connection_remotes
1079 .insert(network_path, connection);
1080 }
1081 Side::Client => {
1082 self.outgoing_connection_remotes
1083 .insert(network_path.remote, connection);
1084 }
1085 },
1086 _ => {
1087 self.connection_ids
1088 .insert(dst_cid, (connection, PathId::ZERO));
1089 }
1090 }
1091 }
1092
1093 fn retire(&mut self, dst_cid: ConnectionId) {
1095 self.connection_ids.remove(&dst_cid);
1096 }
1097
1098 fn remove(&mut self, conn: &ConnectionMeta) {
1100 if conn.side.is_server() {
1101 self.remove_initial(conn.init_cid);
1102 }
1103 for cid in conn
1104 .local_cids
1105 .values()
1106 .flat_map(|pcids| pcids.cids.values())
1107 {
1108 self.connection_ids.remove(cid);
1109 }
1110 self.incoming_connection_remotes.remove(&conn.network_path);
1111 self.outgoing_connection_remotes
1112 .remove(&conn.network_path.remote);
1113 for (remote, token) in conn.reset_token.values() {
1114 self.connection_reset_tokens.remove(*remote, *token);
1115 }
1116 }
1117
1118 fn get(&self, network_path: &FourTuple, datagram: &PartialDecode) -> Option<RouteDatagramTo> {
1120 if !datagram.dst_cid().is_empty()
1121 && let Some(&(ch, path_id)) = self.connection_ids.get(&datagram.dst_cid())
1122 {
1123 return Some(RouteDatagramTo::Connection(ch, path_id));
1124 }
1125 if (datagram.is_initial() || datagram.is_0rtt())
1126 && let Some(&ch) = self.connection_ids_initial.get(&datagram.dst_cid())
1127 {
1128 return Some(ch);
1129 }
1130 if datagram.dst_cid().is_empty() {
1131 if let Some(&ch) = self.incoming_connection_remotes.get(network_path) {
1132 return Some(RouteDatagramTo::Connection(ch, PathId::ZERO));
1135 }
1136 if let Some(&ch) = self.outgoing_connection_remotes.get(&network_path.remote) {
1137 return Some(RouteDatagramTo::Connection(ch, PathId::ZERO));
1139 }
1140 }
1141 let data = datagram.data();
1142 if data.len() < RESET_TOKEN_SIZE {
1143 return None;
1144 }
1145 self.connection_reset_tokens
1148 .get(network_path.remote, &data[data.len() - RESET_TOKEN_SIZE..])
1149 .cloned()
1150 .map(|ch| RouteDatagramTo::Connection(ch, PathId::ZERO))
1151 }
1152}
1153
1154#[derive(Debug)]
1155pub(crate) struct ConnectionMeta {
1156 init_cid: ConnectionId,
1157 local_cids: FxHashMap<PathId, PathLocalCids>,
1159 network_path: FourTuple,
1164 side: Side,
1165 reset_token: FxHashMap<PathId, (SocketAddr, ResetToken)>,
1175}
1176
1177#[derive(Debug, Default)]
1179struct PathLocalCids {
1180 issued: u64,
1184 cids: FxHashMap<u64, ConnectionId>,
1186}
1187
1188#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
1190pub struct ConnectionHandle(pub usize);
1191
1192impl From<ConnectionHandle> for usize {
1193 fn from(x: ConnectionHandle) -> Self {
1194 x.0
1195 }
1196}
1197
1198impl Index<ConnectionHandle> for Slab<ConnectionMeta> {
1199 type Output = ConnectionMeta;
1200 fn index(&self, ch: ConnectionHandle) -> &ConnectionMeta {
1201 &self[ch.0]
1202 }
1203}
1204
1205impl IndexMut<ConnectionHandle> for Slab<ConnectionMeta> {
1206 fn index_mut(&mut self, ch: ConnectionHandle) -> &mut ConnectionMeta {
1207 &mut self[ch.0]
1208 }
1209}
1210
1211pub enum DatagramEvent {
1213 ConnectionEvent(ConnectionHandle, ConnectionEvent),
1215 NewConnection(Incoming),
1217 Response(Transmit),
1219}
1220
1221#[derive(derive_more::Debug)]
1223pub struct Incoming {
1224 #[debug(skip)]
1225 received_at: Instant,
1226 network_path: FourTuple,
1227 ecn: Option<EcnCodepoint>,
1228 #[debug(skip)]
1229 packet: InitialPacket,
1230 #[debug(skip)]
1231 rest: Option<BytesMut>,
1232 #[debug(skip)]
1233 crypto: Keys,
1234 token: IncomingToken,
1235 incoming_idx: usize,
1236 #[debug(skip)]
1237 improper_drop_warner: IncomingImproperDropWarner,
1238}
1239
1240impl Incoming {
1241 pub fn local_ip(&self) -> Option<IpAddr> {
1243 self.network_path.local_ip
1244 }
1245
1246 pub fn remote_address(&self) -> SocketAddr {
1248 self.network_path.remote
1249 }
1250
1251 pub fn remote_address_validated(&self) -> bool {
1259 self.token.validated
1260 }
1261
1262 pub fn may_retry(&self) -> bool {
1267 self.token.retry_src_cid.is_none()
1268 }
1269
1270 pub fn orig_dst_cid(&self) -> ConnectionId {
1272 self.token.orig_dst_cid
1273 }
1274
1275 pub fn decrypt(&self) -> Option<DecryptedInitial> {
1280 let packet_number = self.packet.header.number.expand(0);
1281 let mut payload = self.packet.payload.clone();
1282 self.crypto
1283 .packet
1284 .remote
1285 .decrypt(
1286 PathId::ZERO,
1287 packet_number,
1288 &self.packet.header_data,
1289 &mut payload,
1290 )
1291 .ok()?;
1292 Some(DecryptedInitial(payload.freeze()))
1293 }
1294}
1295
1296pub struct DecryptedInitial(Bytes);
1301
1302impl DecryptedInitial {
1303 pub fn alpns(&self) -> Option<IncomingAlpns> {
1309 let frames = frame::Iter::new(self.0.clone()).ok()?;
1310 let mut first = None;
1311 let mut rest = Vec::new();
1312 for frame in frames {
1313 match frame {
1314 Ok(frame::Frame::Crypto(crypto)) => match first {
1315 None => first = Some(crypto),
1316 Some(_) => rest.push(crypto),
1317 },
1318 Err(_) => return None,
1319 _ => {}
1320 }
1321 }
1322 let first = first?;
1323
1324 if rest.is_empty() && first.offset == 0 {
1326 let data = find_alpn_data(&first.data).ok()?;
1327 return Some(IncomingAlpns { data, pos: 0 });
1328 }
1329
1330 rest.push(first);
1332 let source = assemble_crypto_frames(&mut rest)?;
1333 let data = find_alpn_data(&source).ok()?;
1334 Some(IncomingAlpns { data, pos: 0 })
1335 }
1336}
1337
1338const TLS_HANDSHAKE_TYPE_CLIENT_HELLO: u8 = 0x01;
1341const TLS_EXTENSION_TYPE_ALPN: u16 = 0x0010;
1344const TLS_CLIENT_HELLO_FIXED_LEN: usize = 2 + 32;
1347
1348pub struct IncomingAlpns {
1353 data: Bytes,
1354 pos: usize,
1355}
1356
1357impl Iterator for IncomingAlpns {
1358 type Item = Result<Bytes, UnexpectedEnd>;
1359
1360 fn next(&mut self) -> Option<Self::Item> {
1361 if self.pos >= self.data.len() {
1362 return None;
1363 }
1364 let len = self.data[self.pos] as usize;
1365 self.pos += 1;
1366 if self.pos + len > self.data.len() {
1367 return Some(Err(UnexpectedEnd));
1368 }
1369 let proto = self.data.slice(self.pos..self.pos + len);
1370 self.pos += len;
1371 Some(Ok(proto))
1372 }
1373}
1374
1375fn assemble_crypto_frames(frames: &mut [frame::Crypto]) -> Option<Bytes> {
1379 frames.sort_by_key(|f| f.offset);
1380 let capacity = frames.iter().map(|f| f.data.len()).sum();
1381 let mut buf = Vec::with_capacity(capacity);
1382 for f in frames.iter() {
1383 let start = f.offset as usize;
1384 if start > buf.len() {
1385 return None;
1386 }
1387 let end = start + f.data.len();
1388 if end > buf.len() {
1389 buf.extend_from_slice(&f.data[buf.len() - start..]);
1390 }
1391 }
1392 Some(Bytes::from(buf))
1393}
1394
1395fn find_alpn_data(source: &Bytes) -> Result<Bytes, UnexpectedEnd> {
1401 let mut r = &**source;
1402
1403 if u8::decode(&mut r)? != TLS_HANDSHAKE_TYPE_CLIENT_HELLO {
1404 return Err(UnexpectedEnd);
1405 }
1406
1407 let len = decode_u24(&mut r)?;
1409 let mut body = take(&mut r, len)?;
1410
1411 skip(&mut body, TLS_CLIENT_HELLO_FIXED_LEN)?;
1413
1414 skip_u8_prefixed(&mut body)?;
1416 skip_u16_prefixed(&mut body)?;
1417 skip_u8_prefixed(&mut body)?;
1418
1419 let mut exts = take_u16_prefixed(&mut body)?;
1421 while exts.has_remaining() {
1422 let ext_type = u16::decode(&mut exts)?;
1423 let ext_data = take_u16_prefixed(&mut exts)?;
1424 if ext_type == TLS_EXTENSION_TYPE_ALPN {
1425 let list = take_u16_prefixed(&mut &*ext_data)?;
1426 return Ok(source.slice_ref(list));
1427 }
1428 }
1429 Err(UnexpectedEnd)
1430}
1431
1432fn decode_u24(r: &mut &[u8]) -> Result<usize, UnexpectedEnd> {
1434 let a = u8::decode(r)?;
1435 let b = u8::decode(r)?;
1436 let c = u8::decode(r)?;
1437 Ok(u32::from_be_bytes([0, a, b, c]) as usize)
1438}
1439
1440fn take<'a>(r: &mut &'a [u8], len: usize) -> Result<&'a [u8], UnexpectedEnd> {
1442 if r.remaining() < len {
1443 return Err(UnexpectedEnd);
1444 }
1445 let data = &r[..len];
1446 r.advance(len);
1447 Ok(data)
1448}
1449
1450fn take_u16_prefixed<'a>(r: &mut &'a [u8]) -> Result<&'a [u8], UnexpectedEnd> {
1452 let len = u16::decode(r)? as usize;
1453 take(r, len)
1454}
1455
1456fn skip(r: &mut &[u8], len: usize) -> Result<(), UnexpectedEnd> {
1458 take(r, len)?;
1459 Ok(())
1460}
1461
1462fn skip_u8_prefixed(r: &mut &[u8]) -> Result<(), UnexpectedEnd> {
1464 let len = u8::decode(r)? as usize;
1465 skip(r, len)
1466}
1467
1468fn skip_u16_prefixed(r: &mut &[u8]) -> Result<(), UnexpectedEnd> {
1470 let len = u16::decode(r)? as usize;
1471 skip(r, len)
1472}
1473
1474struct IncomingImproperDropWarner;
1475
1476impl IncomingImproperDropWarner {
1477 fn dismiss(self) {
1478 mem::forget(self);
1479 }
1480}
1481
1482impl Drop for IncomingImproperDropWarner {
1483 fn drop(&mut self) {
1484 warn!(
1485 "noq_proto::Incoming dropped without passing to Endpoint::accept/refuse/retry/ignore \
1486 (may cause memory leak and eventual inability to accept new connections)"
1487 );
1488 }
1489}
1490
1491#[derive(Debug, Error, Clone, PartialEq, Eq)]
1495pub enum ConnectError {
1496 #[error("endpoint stopping")]
1500 EndpointStopping,
1501 #[error("CIDs exhausted")]
1505 CidsExhausted,
1506 #[error("invalid server name: {0}")]
1508 InvalidServerName(String),
1509 #[error("invalid remote address: {0}")]
1513 InvalidRemoteAddress(SocketAddr),
1514 #[error("no default client config")]
1518 NoDefaultClientConfig,
1519 #[error("unsupported QUIC version")]
1521 UnsupportedVersion,
1522}
1523
1524#[derive(Debug)]
1526pub struct AcceptError {
1527 pub cause: ConnectionError,
1529 pub response: Option<Transmit>,
1531}
1532
1533#[derive(Debug, Error)]
1535#[error("retry() with validated Incoming")]
1536pub struct RetryError(Box<Incoming>);
1537
1538impl RetryError {
1539 pub fn into_incoming(self) -> Incoming {
1541 *self.0
1542 }
1543}
1544
1545#[derive(Default, Debug)]
1550struct ResetTokenTable(HashMap<SocketAddr, HashMap<ResetToken, ConnectionHandle>>);
1551
1552impl ResetTokenTable {
1553 fn insert(&mut self, remote: SocketAddr, token: ResetToken, ch: ConnectionHandle) -> bool {
1554 self.0
1555 .entry(remote)
1556 .or_default()
1557 .insert(token, ch)
1558 .is_some()
1559 }
1560
1561 fn remove(&mut self, remote: SocketAddr, token: ResetToken) {
1562 use std::collections::hash_map::Entry;
1563 match self.0.entry(remote) {
1564 Entry::Vacant(_) => {}
1565 Entry::Occupied(mut e) => {
1566 e.get_mut().remove(&token);
1567 if e.get().is_empty() {
1568 e.remove_entry();
1569 }
1570 }
1571 }
1572 }
1573
1574 fn get(&self, remote: SocketAddr, token: &[u8]) -> Option<&ConnectionHandle> {
1575 let token = ResetToken::from(<[u8; RESET_TOKEN_SIZE]>::try_from(token).ok()?);
1576 self.0.get(&remote)?.get(&token)
1577 }
1578}
1579
1580#[cfg(test)]
1581mod tests {
1582 use super::*;
1583
1584 #[test]
1585 fn assemble_contiguous() {
1586 let data = b"hello world";
1587 let mut frames = vec![
1588 frame::Crypto {
1589 offset: 0,
1590 data: Bytes::from_static(&data[..5]),
1591 },
1592 frame::Crypto {
1593 offset: 5,
1594 data: Bytes::from_static(&data[5..]),
1595 },
1596 ];
1597 assert_eq!(&assemble_crypto_frames(&mut frames).unwrap()[..], &data[..]);
1598 }
1599
1600 #[test]
1601 fn assemble_out_of_order() {
1602 let data = b"hello world";
1603 let mut frames = vec![
1604 frame::Crypto {
1605 offset: 5,
1606 data: Bytes::from_static(&data[5..]),
1607 },
1608 frame::Crypto {
1609 offset: 0,
1610 data: Bytes::from_static(&data[..5]),
1611 },
1612 ];
1613 assert_eq!(&assemble_crypto_frames(&mut frames).unwrap()[..], &data[..]);
1614 }
1615
1616 #[test]
1617 fn assemble_with_overlap() {
1618 let data = b"hello world";
1619 let mut frames = vec![
1620 frame::Crypto {
1621 offset: 0,
1622 data: Bytes::from_static(&data[..7]),
1623 },
1624 frame::Crypto {
1625 offset: 5,
1626 data: Bytes::from_static(&data[5..]),
1627 },
1628 ];
1629 assert_eq!(&assemble_crypto_frames(&mut frames).unwrap()[..], &data[..]);
1630 }
1631
1632 #[test]
1633 fn assemble_with_gap() {
1634 let mut frames = vec![frame::Crypto {
1635 offset: 10,
1636 data: Bytes::from_static(b"world"),
1637 }];
1638 assert!(assemble_crypto_frames(&mut frames).is_none());
1639 }
1640}