Skip to main content

trillium_http/h3/
error.rs

1use std::borrow::Cow;
2
3/// H3 error codes per RFC 9114 §8.1.
4///
5/// Used when closing connections or resetting streams.
6/// Unknown error codes are mapped to `NoError` per spec.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
8#[non_exhaustive]
9pub enum H3ErrorCode {
10    /// No error. Used when closing without an error to signal.
11    #[error("No error. Used when closing without an error to signal.")]
12    NoError = 0x0100,
13
14    /// Peer violated protocol requirements.
15    #[error("Peer violated protocol requirements.")]
16    GeneralProtocolError = 0x0101,
17
18    /// An internal error in the HTTP stack.
19    #[error("An internal error in the HTTP stack.")]
20    InternalError = 0x0102,
21
22    /// Peer created a stream that will not be accepted.
23    #[error("Peer created a stream that will not be accepted.")]
24    StreamCreationError = 0x0103,
25
26    /// A required stream was closed or reset.
27    #[error("A required stream was closed or reset.")]
28    ClosedCriticalStream = 0x0104,
29
30    /// A frame was not permitted in the current state or stream.
31    #[error("A frame was not permitted in the current state or stream.")]
32    FrameUnexpected = 0x0105,
33
34    /// A frame fails layout requirements or has an invalid size.
35    #[error("A frame fails layout requirements or has an invalid size.")]
36    FrameError = 0x0106,
37
38    /// Peer is generating excessive load.
39    #[error("Peer is generating excessive load.")]
40    ExcessiveLoad = 0x0107,
41
42    /// A stream ID or push ID was used incorrectly.
43    #[error("A stream ID or push ID was used incorrectly.")]
44    IdError = 0x0108,
45
46    /// Error in the payload of a SETTINGS frame.
47    #[error("Error in the payload of a SETTINGS frame.")]
48    SettingsError = 0x0109,
49
50    /// No SETTINGS frame at the beginning of the control stream.
51    #[error("No SETTINGS frame at the beginning of the control stream.")]
52    MissingSettings = 0x010a,
53
54    /// Server rejected a request without application processing.
55    #[error("Server rejected a request without application processing.")]
56    RequestRejected = 0x010b,
57
58    /// Request or response (including pushed) is cancelled.
59    #[error("Request or response (including pushed) is cancelled.")]
60    RequestCancelled = 0x010c,
61
62    /// Client stream terminated without a fully formed request.
63    #[error("Client stream terminated without a fully formed request.")]
64    RequestIncomplete = 0x010d,
65
66    /// HTTP message was malformed.
67    #[error("HTTP message was malformed.")]
68    MessageError = 0x010e,
69
70    /// TCP connection for CONNECT was reset or abnormally closed.
71    #[error("TCP connection for CONNECT was reset or abnormally closed.")]
72    ConnectError = 0x010f,
73
74    /// Requested operation cannot be served over HTTP/3.
75    #[error("Requested operation cannot be served over HTTP/3.")]
76    VersionFallback = 0x0110,
77
78    // -- WebTransport error codes (draft-ietf-webtrans-http3) --
79    /// WebTransport data stream rejected due to lack of associated session.
80    #[error("WebTransport data stream rejected due to lack of associated session.")]
81    WebTransportBufferedStreamRejected = 0x3994_bd84,
82
83    /// WebTransport data stream or session closed because the associated session is gone.
84    #[error("WebTransport session gone.")]
85    WebTransportSessionGone = 0x170d_7b68,
86
87    /// WebTransport session flow control error.
88    #[error("WebTransport flow control error.")]
89    WebTransportFlowControlError = 0x045d_4487,
90
91    /// WebTransport application protocol negotiation failed.
92    #[error("WebTransport ALPN error.")]
93    WebTransportAlpnError = 0x0817_b3dd,
94
95    /// Required WebTransport settings or transport parameters not met.
96    #[error("WebTransport requirements not met.")]
97    WebTransportRequirementsNotMet = 0x212c_0d48,
98}
99
100impl H3ErrorCode {
101    /// A "reason phrase" per rfc9000 §19.19
102    pub fn reason(&self) -> Cow<'static, str> {
103        // eventually this probably should either be &'static str or callsite-specific
104        Cow::Owned(format!("{self}"))
105    }
106
107    /// Returns `true` if this error code represents a connection-level error that requires
108    /// closing the entire QUIC connection (via `CONNECTION_CLOSE`).
109    ///
110    /// Returns `false` for stream-level errors such as [`Self::MessageError`] or
111    /// [`Self::RequestIncomplete`], which should reset the individual stream rather than
112    /// tear down the whole connection.
113    pub fn is_connection_error(&self) -> bool {
114        matches!(
115            self,
116            Self::GeneralProtocolError
117                | Self::InternalError
118                | Self::ClosedCriticalStream
119                | Self::FrameUnexpected
120                | Self::FrameError
121                | Self::ExcessiveLoad
122                | Self::IdError
123                | Self::SettingsError
124                | Self::MissingSettings
125        )
126    }
127}
128
129impl From<u64> for H3ErrorCode {
130    /// All unknown error codes are treated as equivalent to `NoError`
131    /// per RFC 9114 §9.
132    fn from(value: u64) -> Self {
133        match value {
134            0x0101 => Self::GeneralProtocolError,
135            0x0102 => Self::InternalError,
136            0x0103 => Self::StreamCreationError,
137            0x0104 => Self::ClosedCriticalStream,
138            0x0105 => Self::FrameUnexpected,
139            0x0106 => Self::FrameError,
140            0x0107 => Self::ExcessiveLoad,
141            0x0108 => Self::IdError,
142            0x0109 => Self::SettingsError,
143            0x010a => Self::MissingSettings,
144            0x010b => Self::RequestRejected,
145            0x010c => Self::RequestCancelled,
146            0x010d => Self::RequestIncomplete,
147            0x010e => Self::MessageError,
148            0x010f => Self::ConnectError,
149            0x0110 => Self::VersionFallback,
150            0x3994_bd84 => Self::WebTransportBufferedStreamRejected,
151            0x170d_7b68 => Self::WebTransportSessionGone,
152            0x045d_4487 => Self::WebTransportFlowControlError,
153            0x0817_b3dd => Self::WebTransportAlpnError,
154            0x212c_0d48 => Self::WebTransportRequirementsNotMet,
155            _ => Self::NoError,
156        }
157    }
158}
159
160impl From<H3ErrorCode> for u64 {
161    /// Encodes the error code. `NoError` emits a random GREASE value
162    /// (`0x1f * N + 0x21`) per RFC 9114 §8.1 to exercise peer handling
163    /// of unknown codes.
164    fn from(code: H3ErrorCode) -> u64 {
165        match code {
166            H3ErrorCode::NoError => {
167                let n = u64::from(fastrand::u16(..));
168                0x1f * n + 0x21
169            }
170            other => other as u64,
171        }
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    #[test]
180    fn known_codes_roundtrip() {
181        for code in [
182            H3ErrorCode::GeneralProtocolError,
183            H3ErrorCode::InternalError,
184            H3ErrorCode::StreamCreationError,
185            H3ErrorCode::ClosedCriticalStream,
186            H3ErrorCode::FrameUnexpected,
187            H3ErrorCode::FrameError,
188            H3ErrorCode::ExcessiveLoad,
189            H3ErrorCode::IdError,
190            H3ErrorCode::SettingsError,
191            H3ErrorCode::MissingSettings,
192            H3ErrorCode::RequestRejected,
193            H3ErrorCode::RequestCancelled,
194            H3ErrorCode::RequestIncomplete,
195            H3ErrorCode::MessageError,
196            H3ErrorCode::ConnectError,
197            H3ErrorCode::VersionFallback,
198            H3ErrorCode::WebTransportBufferedStreamRejected,
199            H3ErrorCode::WebTransportSessionGone,
200            H3ErrorCode::WebTransportFlowControlError,
201            H3ErrorCode::WebTransportAlpnError,
202            H3ErrorCode::WebTransportRequirementsNotMet,
203        ] {
204            let wire: u64 = code.into();
205            let decoded = H3ErrorCode::from(wire);
206            assert_eq!(decoded, code, "roundtrip failed for {code:?}");
207        }
208    }
209
210    #[test]
211    fn no_error_encodes_as_grease() {
212        for _ in 0..100 {
213            let wire: u64 = H3ErrorCode::NoError.into();
214            assert_ne!(wire, 0x0100, "should emit GREASE, not literal NoError");
215            assert_eq!(
216                (wire - 0x21) % 0x1f,
217                0,
218                "{wire:#x} is not a valid GREASE value"
219            );
220        }
221    }
222
223    #[test]
224    fn grease_decodes_as_no_error() {
225        for n in [0u64, 1, 100, 0xFFFF] {
226            let grease = 0x1f * n + 0x21;
227            assert_eq!(H3ErrorCode::from(grease), H3ErrorCode::NoError);
228        }
229    }
230
231    #[test]
232    fn unknown_non_grease_decodes_as_no_error() {
233        assert_eq!(H3ErrorCode::from(0xDEAD), H3ErrorCode::NoError);
234        assert_eq!(H3ErrorCode::from(0), H3ErrorCode::NoError);
235        assert_eq!(H3ErrorCode::from(u64::MAX), H3ErrorCode::NoError);
236    }
237}