iroh_quinn_proto/
transport_error.rs

1use std::{fmt, sync::Arc};
2
3use bytes::{Buf, BufMut};
4
5use crate::{
6    VarInt,
7    coding::{self, BufExt, BufMutExt},
8    frame,
9};
10
11/// Transport-level errors occur when a peer violates the protocol specification
12///
13/// # Note
14///
15/// The `PartialEq` implementation for this type performs comparison on the `code` field only
16#[derive(Debug, Clone)]
17#[non_exhaustive]
18pub struct Error {
19    /// Type of error
20    pub code: Code,
21    /// Frame type that triggered the error
22    pub frame: Option<frame::FrameType>,
23    /// Human-readable explanation of the reason
24    pub reason: String,
25    /// An underlying crypto (e.g. TLS) layer error
26    pub crypto: Option<Arc<dyn std::error::Error + Send + Sync>>,
27}
28
29impl Error {
30    /// Construct an error with a code and a reason
31    pub fn new(code: Code, reason: String) -> Self {
32        Self {
33            code,
34            frame: None,
35            reason,
36            crypto: None,
37        }
38    }
39}
40
41impl PartialEq for Error {
42    fn eq(&self, other: &Self) -> bool {
43        self.code == other.code
44    }
45}
46
47impl Eq for Error {}
48
49impl fmt::Display for Error {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        self.code.fmt(f)?;
52        if let Some(frame) = self.frame {
53            write!(f, " in {frame}")?;
54        }
55        if !self.reason.is_empty() {
56            write!(f, ": {}", self.reason)?;
57        }
58        Ok(())
59    }
60}
61
62impl std::error::Error for Error {}
63
64/// Transport-level error code
65#[derive(Copy, Clone, Eq, PartialEq)]
66pub struct Code(u64);
67
68impl Code {
69    /// Create QUIC error code from TLS alert code
70    pub fn crypto(code: u8) -> Self {
71        Self(0x100 | u64::from(code))
72    }
73}
74
75impl coding::Codec for Code {
76    fn decode<B: Buf>(buf: &mut B) -> coding::Result<Self> {
77        Ok(Self(buf.get_var()?))
78    }
79    fn encode<B: BufMut>(&self, buf: &mut B) {
80        buf.write_var(self.0)
81    }
82}
83
84impl From<Code> for u64 {
85    fn from(x: Code) -> Self {
86        x.0
87    }
88}
89
90impl From<VarInt> for Code {
91    fn from(value: VarInt) -> Self {
92        Self(value.0)
93    }
94}
95
96impl From<Code> for VarInt {
97    fn from(value: Code) -> Self {
98        Self(value.0)
99    }
100}
101
102macro_rules! errors {
103    {$($name:ident($val:expr) $desc:expr;)*} => {
104        #[allow(non_snake_case, unused)]
105        impl Error {
106            $(
107            pub(crate) fn $name<T>(reason: T) -> Self where T: Into<String> {
108                Self::new(Code::$name, reason.into())
109            }
110            )*
111        }
112
113        impl Code {
114            $(#[doc = $desc] pub const $name: Self = Code($val);)*
115        }
116
117        impl fmt::Debug for Code {
118            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119                match self.0 {
120                    $($val => f.write_str(stringify!($name)),)*
121                    x if (0x100..0x200).contains(&x) => write!(f, "Code::crypto({:02x})", self.0 as u8),
122                    _ => write!(f, "Code({:x})", self.0),
123                }
124            }
125        }
126
127        impl fmt::Display for Code {
128            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129                match self.0 {
130                    $($val => f.write_str($desc),)*
131                    // We're trying to be abstract over the crypto protocol, so human-readable descriptions here is tricky.
132                    _ if self.0 >= 0x100 && self.0 < 0x200 => write!(f, "the cryptographic handshake failed: error {}", self.0 & 0xFF),
133                    _ => f.write_str("unknown error"),
134                }
135            }
136        }
137    }
138}
139
140errors! {
141    NO_ERROR(0x0) "the connection is being closed abruptly in the absence of any error";
142    INTERNAL_ERROR(0x1) "the endpoint encountered an internal error and cannot continue with the connection";
143    CONNECTION_REFUSED(0x2) "the server refused to accept a new connection";
144    FLOW_CONTROL_ERROR(0x3) "received more data than permitted in advertised data limits";
145    STREAM_LIMIT_ERROR(0x4) "received a frame for a stream identifier that exceeded advertised the stream limit for the corresponding stream type";
146    STREAM_STATE_ERROR(0x5) "received a frame for a stream that was not in a state that permitted that frame";
147    FINAL_SIZE_ERROR(0x6) "received a STREAM frame or a RESET_STREAM frame containing a different final size to the one already established";
148    FRAME_ENCODING_ERROR(0x7) "received a frame that was badly formatted";
149    TRANSPORT_PARAMETER_ERROR(0x8) "received transport parameters that were badly formatted, included an invalid value, was absent even though it is mandatory, was present though it is forbidden, or is otherwise in error";
150    CONNECTION_ID_LIMIT_ERROR(0x9) "the number of connection IDs provided by the peer exceeds the advertised active_connection_id_limit";
151    PROTOCOL_VIOLATION(0xA) "detected an error with protocol compliance that was not covered by more specific error codes";
152    INVALID_TOKEN(0xB) "received an invalid Retry Token in a client Initial";
153    APPLICATION_ERROR(0xC) "the application or application protocol caused the connection to be closed during the handshake";
154    CRYPTO_BUFFER_EXCEEDED(0xD) "received more data in CRYPTO frames than can be buffered";
155    KEY_UPDATE_ERROR(0xE) "key update error";
156    AEAD_LIMIT_REACHED(0xF) "the endpoint has reached the confidentiality or integrity limit for the AEAD algorithm";
157    NO_VIABLE_PATH(0x10) "no viable network path exists";
158    APPLICATION_ABANDON_PATH(0x004150504142414e) "Path abandoned at the application's request";
159    PATH_RESOURCE_LIMIT_REACHED(0x0052534c494d4954) "Path abandoned due to resource limitations in the transport";
160    PATH_UNSTABLE_OR_POOR(0x00554e5f494e5446) "Path abandoned due to unstable interfaces";
161    NO_CID_AVAILABLE_FOR_PATH(0x004e4f5f4349445f) "Path abandoned due to no available connection IDs for the path";
162}