ant_quic/
shared.rs

1// Copyright 2024 Saorsa Labs Ltd.
2//
3// This Saorsa Network Software is licensed under the General Public License (GPL), version 3.
4// Please see the file LICENSE-GPL, or visit <http://www.gnu.org/licenses/> for the full text.
5//
6// Full details available at https://saorsalabs.com/licenses
7
8use std::{fmt, net::SocketAddr};
9
10use bytes::{Buf, BufMut, BytesMut};
11
12use crate::{Instant, MAX_CID_SIZE, ResetToken, coding::BufExt, packet::PartialDecode};
13
14/// Events sent from an Endpoint to a Connection
15#[derive(Debug)]
16pub struct ConnectionEvent(pub(crate) ConnectionEventInner);
17
18#[derive(Debug)]
19pub(crate) enum ConnectionEventInner {
20    /// A datagram has been received for the Connection
21    Datagram(DatagramConnectionEvent),
22    /// New connection identifiers have been issued for the Connection
23    NewIdentifiers(Vec<IssuedCid>, Instant),
24    /// Queue an ADD_ADDRESS frame for transmission
25    QueueAddAddress(crate::frame::AddAddress),
26    /// Queue a PUNCH_ME_NOW frame for transmission
27    QueuePunchMeNow(crate::frame::PunchMeNow),
28}
29
30/// Variant of [`ConnectionEventInner`].
31#[derive(Debug)]
32pub(crate) struct DatagramConnectionEvent {
33    pub(crate) now: Instant,
34    pub(crate) remote: SocketAddr,
35    pub(crate) ecn: Option<EcnCodepoint>,
36    pub(crate) first_decode: PartialDecode,
37    pub(crate) remaining: Option<BytesMut>,
38}
39
40/// Events sent from a Connection to an Endpoint
41#[derive(Debug)]
42pub struct EndpointEvent(pub(crate) EndpointEventInner);
43
44impl EndpointEvent {
45    /// Construct an event that indicating that a `Connection` will no longer emit events
46    ///
47    /// Useful for notifying an `Endpoint` that a `Connection` has been destroyed outside of the
48    /// usual state machine flow, e.g. when being dropped by the user.
49    pub fn drained() -> Self {
50        Self(EndpointEventInner::Drained)
51    }
52
53    /// Determine whether this is the last event a `Connection` will emit
54    ///
55    /// Useful for determining when connection-related event loop state can be freed.
56    pub fn is_drained(&self) -> bool {
57        self.0 == EndpointEventInner::Drained
58    }
59}
60
61#[derive(Clone, Debug, Eq, PartialEq)]
62
63pub(crate) enum EndpointEventInner {
64    /// The connection has been drained
65    Drained,
66    /// The reset token and/or address eligible for generating resets has been updated
67    ResetToken(SocketAddr, ResetToken),
68    /// The connection needs connection identifiers
69    NeedIdentifiers(Instant, u64),
70    /// Stop routing connection ID for this sequence number to the connection
71    /// When `bool == true`, a new connection ID will be issued to peer
72    RetireConnectionId(Instant, u64, bool),
73    /// Request to relay a PunchMeNow frame to a target peer
74    RelayPunchMeNow([u8; 32], crate::frame::PunchMeNow),
75    /// Request to send an AddAddress frame to the peer
76    #[allow(dead_code)]
77    SendAddressFrame(crate::frame::AddAddress),
78    /// NAT traversal candidate validation succeeded
79    #[allow(dead_code)]
80    NatCandidateValidated { address: SocketAddr, challenge: u64 },
81}
82
83/// Protocol-level identifier for a connection.
84///
85/// Mainly useful for identifying this connection's packets on the wire with tools like Wireshark.
86#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
87pub struct ConnectionId {
88    /// length of CID
89    len: u8,
90    /// CID in byte array
91    bytes: [u8; MAX_CID_SIZE],
92}
93
94impl ConnectionId {
95    /// Construct cid from byte array
96    pub fn new(bytes: &[u8]) -> Self {
97        debug_assert!(bytes.len() <= MAX_CID_SIZE);
98        let mut res = Self {
99            len: bytes.len() as u8,
100            bytes: [0; MAX_CID_SIZE],
101        };
102        res.bytes[..bytes.len()].copy_from_slice(bytes);
103        res
104    }
105
106    /// Constructs cid by reading `len` bytes from a `Buf`
107    ///
108    /// Callers need to assure that `buf.remaining() >= len`
109    pub fn from_buf(buf: &mut (impl Buf + ?Sized), len: usize) -> Self {
110        debug_assert!(len <= MAX_CID_SIZE);
111        let mut res = Self {
112            len: len as u8,
113            bytes: [0; MAX_CID_SIZE],
114        };
115        buf.copy_to_slice(&mut res[..len]);
116        res
117    }
118
119    /// Decode from long header format
120    pub(crate) fn decode_long(buf: &mut impl Buf) -> Option<Self> {
121        let len = buf.get::<u8>().ok()? as usize;
122        match len > MAX_CID_SIZE || buf.remaining() < len {
123            false => Some(Self::from_buf(buf, len)),
124            true => None,
125        }
126    }
127
128    /// Encode in long header format
129    pub(crate) fn encode_long(&self, buf: &mut impl BufMut) {
130        buf.put_u8(self.len() as u8);
131        buf.put_slice(self);
132    }
133}
134
135impl ::std::ops::Deref for ConnectionId {
136    type Target = [u8];
137    fn deref(&self) -> &[u8] {
138        &self.bytes[0..self.len as usize]
139    }
140}
141
142impl ::std::ops::DerefMut for ConnectionId {
143    fn deref_mut(&mut self) -> &mut [u8] {
144        &mut self.bytes[0..self.len as usize]
145    }
146}
147
148impl fmt::Debug for ConnectionId {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        self.bytes[0..self.len as usize].fmt(f)
151    }
152}
153
154impl fmt::Display for ConnectionId {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        for byte in self.iter() {
157            write!(f, "{byte:02x}")?;
158        }
159        Ok(())
160    }
161}
162
163/// Explicit congestion notification codepoint
164#[repr(u8)]
165#[derive(Debug, Copy, Clone, Eq, PartialEq)]
166pub enum EcnCodepoint {
167    /// The ECT(0) codepoint, indicating that an endpoint is ECN-capable
168    Ect0 = 0b10,
169    /// The ECT(1) codepoint, indicating that an endpoint is ECN-capable
170    Ect1 = 0b01,
171    /// The CE codepoint, signalling that congestion was experienced
172    Ce = 0b11,
173}
174
175impl EcnCodepoint {
176    /// Create new object from the given bits
177    pub fn from_bits(x: u8) -> Option<Self> {
178        use EcnCodepoint::*;
179        Some(match x & 0b11 {
180            0b10 => Ect0,
181            0b01 => Ect1,
182            0b11 => Ce,
183            _ => {
184                return None;
185            }
186        })
187    }
188
189    /// Returns whether the codepoint is a CE, signalling that congestion was experienced
190    pub fn is_ce(self) -> bool {
191        matches!(self, Self::Ce)
192    }
193}
194
195#[derive(Debug, Copy, Clone)]
196pub(crate) struct IssuedCid {
197    pub(crate) sequence: u64,
198    pub(crate) id: ConnectionId,
199    pub(crate) reset_token: ResetToken,
200}