matter_kit/error.rs
1//! One error type for the whole crate.
2//!
3//! Two things are true at once about a failure in a Matter stack: it has a *local* cause
4//! that a developer needs (a truncated TLV element, a nonce that did not fit) and it may
5//! have a *wire* meaning that a peer is owed (Core §8.10's `INVALID_ACTION`,
6//! `RESOURCE_EXHAUSTED`, …). Splitting those into two types means every layer converts
7//! between them and one of the conversions is always wrong, so [`Error`] carries both: an
8//! [`ErrorCode`] always, and an interaction-model status when one applies.
9//!
10//! Resource exhaustion is a value here, never an abort — a device that runs out of
11//! exchanges answers `BUSY` and stays on the network.
12
13use core::fmt;
14
15/// What went wrong, locally.
16///
17/// The set is closed by this crate rather than by the specification, so it is
18/// `#[non_exhaustive]`: new codes appear as layers land, and a consumer matching
19/// exhaustively should not break for that.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21#[non_exhaustive]
22pub enum ErrorCode {
23 // --- Encoding -------------------------------------------------------------------
24 /// A TLV element ended before its declared length.
25 TlvTruncated,
26 /// A control octet named a reserved element type or an illegal tag control.
27 TlvInvalidControl,
28 /// A container was not terminated by an end-of-container element, or one appeared
29 /// where no container was open.
30 TlvContainerMismatch,
31 /// The element is not of the type the reader was asked for.
32 TlvWrongType,
33 /// A UTF-8 string element held bytes that are not valid UTF-8.
34 TlvInvalidUtf8,
35 /// A structure member was anonymous, an array member was tagged, or a tag repeated
36 /// inside a structure — Core §A.5.
37 TlvInvalidTag,
38 /// Container nesting went deeper than the reader's fixed depth budget.
39 TlvDepthExceeded,
40 /// The value does not fit the requested Rust type (a `u64` read as `u8`, say).
41 TlvOutOfRange,
42 /// A required element was absent.
43 TlvNotFound,
44 /// Two members of one structure carried the same tag — Core §A.5.1: "All member elements
45 /// within a structure SHALL have a unique tag as compared to the other members".
46 TlvDuplicateTag,
47
48 // --- Message layer --------------------------------------------------------------
49 /// The message is shorter than its own header says it is.
50 MessageTruncated,
51 /// The message header version is not one this node speaks — Core §4.4.1.1.
52 UnsupportedVersion,
53 /// A reserved `DSIZ` or session-type value — Core §4.4.1.1, §4.4.1.3.
54 MessageReserved,
55 /// The message counter is outside the replay window, or repeats one already seen.
56 DuplicateMessage,
57 /// Decryption or the integrity check failed.
58 IntegrityCheckFailed,
59
60 // --- Exchanges and sessions -----------------------------------------------------
61 /// No exchange matches the message, and none could be created for it.
62 NoExchange,
63 /// No session matches the message's session id.
64 NoSession,
65 /// A reliable message was retransmitted `MRP_MAX_TRANSMISSIONS` times without an
66 /// acknowledgement — Core §4.12.
67 MrpRetransmitExhausted,
68
69 // --- Capacity and lifecycle -----------------------------------------------------
70 /// A fixed-capacity table sized by [`Config`](crate::Config) is full.
71 NoSpace,
72 /// The operation would block on a resource that is busy right now.
73 Busy,
74 /// A buffer given to this crate is too small for what was asked of it.
75 BufferTooSmall,
76 /// The argument is outside the range the specification allows.
77 InvalidArgument,
78 /// The call is not legal in the current state.
79 InvalidState,
80 /// The entry is already present and the operation does not replace it — the fabric
81 /// conflict of §11.18's `AddNOC`, for one.
82 AlreadyExists,
83 /// An interaction model action is malformed and must be answered with a
84 /// `StatusResponse` carrying `INVALID_ACTION` rather than its usual response
85 /// (Core §8.10).
86 ///
87 /// This is an *action*-level refusal, distinct from the per-path
88 /// [`Status`](crate::im::Status) a response carries: there is nothing well-formed enough
89 /// to report a path for.
90 InvalidAction,
91 /// A report does not fit in one message and must be chunked — Core §10.2.3.
92 ///
93 /// Not a failure so much as the wrong method: the read is perfectly servable, just not
94 /// in a single message.
95 /// [`Server::serve_chunk`](crate::im::Server::serve_chunk) serves it as the series of
96 /// messages §10.2.3 calls for. This exists so the one-message convenience can *refuse*
97 /// rather than emit a `MoreChunkedMessages` it has no way to honour, which would leave
98 /// the client waiting for a continuation that never comes.
99 ReportWouldChunk,
100
101 // --- Certificates ---------------------------------------------------------------
102 /// A Matter certificate violates one of the §6.5 encoding rules: an element out of
103 /// order, a value out of range, a distinguished name the certificate's type forbids.
104 CertInvalid,
105 /// A certificate chain does not validate — a signature that does not verify, an issuer
106 /// that does not match, a path longer than a `path-len-constraint` allows.
107 CertPathInvalid,
108 /// A certificate is being used outside its `not-before`/`not-after` window.
109 CertExpired,
110 /// The operation is defined but this build does not implement it.
111 Unsupported,
112 /// A DER encoding is malformed: a truncated element, a length that is not in DER's
113 /// shortest form, or a structure that is not what its context requires.
114 DerMalformed,
115
116 // --- Commissioning ---------------------------------------------------------------
117 /// §6.2.3's Device Attestation Procedure did not pass: a signature that does not verify,
118 /// a nonce the device did not echo back, or a chain that does not reach a trusted PAA.
119 ///
120 /// §5.5 step 10 makes this a *report*, not a verdict — "the Commissioner MAY choose to
121 /// either continue to the Commissioning, or terminate it, depending on
122 /// implementation-dependent policies" — so it reaches the caller rather than ending the
123 /// flow on its own.
124 AttestationFailed,
125 /// A commissioning command answered with an error: §11.10.5.1's `CommissioningErrorEnum`
126 /// or §11.18.5.1's `NodeOperationalCertStatusEnum`, neither of which is `OK`.
127 CommissioningFailed,
128
129 // --- Discovery ------------------------------------------------------------------
130 /// A DNS message ended inside a name, a record, or a header.
131 DnsTruncated,
132 /// A DNS message is malformed: a reserved label type, a compression pointer that does
133 /// not point strictly backwards, a name with more labels than a Matter record has.
134 DnsMalformed,
135
136 // --- Transports -----------------------------------------------------------------
137 /// A message on a stream transport announced a length past §4.15.2.3's Maximum Message
138 /// Size, or a length of zero.
139 ///
140 /// Fatal to the connection either way. §4.5's length prefix is the *only* message
141 /// boundary a stream has, so a receiver that cannot hold the message has also lost its
142 /// place: everything after it would be read as a header. §4.15.2.3 says to close, and
143 /// [`tcp::too_large`](crate::transport::tcp::too_large) is the report to send first.
144 MessageTooLarge,
145 /// A BDX transfer ended in failure, and the §11.22.3.2 status code said why.
146 ///
147 /// This is the code for a caller that had to widen a
148 /// [`bdx::StatusCode`](crate::bdx::StatusCode) into the crate's own error type; the
149 /// [`bdx`](crate::bdx) module's own API keeps the status code, because it is what has to
150 /// be sent back to the peer.
151 BdxAborted,
152 /// A BTP packet is malformed, or breaks one of §4.19.4.5's reassembly rules: an Ending
153 /// segment with no Beginning, a Beginning while another SDU is in flight, a reassembled
154 /// length that does not match the Message Length it was promised.
155 ///
156 /// Every one of these closes the BTP session. The protocol has no way to resynchronise,
157 /// so continuing would mean reassembling two messages into one.
158 BtpMalformed,
159 /// A BTP sequence number did not increment by one, or an acknowledgement named a packet
160 /// that was never sent or was already acknowledged — §4.19.4.6, §4.19.4.8. Also closes
161 /// the session.
162 BtpSequence,
163 /// A BTP acknowledgement did not arrive within `BTP_ACK_TIMEOUT` (§4.19.4.8). The timer
164 /// doubles as BTP's keep-alive, so this is also how a peer notices a remote stack that
165 /// has stopped answering.
166 BtpTimeout,
167 /// The platform reported a failure.
168 Platform,
169}
170
171impl ErrorCode {
172 /// A short, stable, human-readable name — the one that appears in logs.
173 #[must_use]
174 pub const fn as_str(self) -> &'static str {
175 match self {
176 Self::TlvTruncated => "tlv: truncated element",
177 Self::TlvInvalidControl => "tlv: reserved or invalid control octet",
178 Self::TlvContainerMismatch => "tlv: unbalanced container",
179 Self::TlvWrongType => "tlv: wrong element type",
180 Self::TlvInvalidUtf8 => "tlv: invalid utf-8 in string element",
181 Self::TlvInvalidTag => "tlv: tag not allowed in this container",
182 Self::TlvDepthExceeded => "tlv: nesting too deep",
183 Self::TlvOutOfRange => "tlv: value out of range for target type",
184 Self::TlvNotFound => "tlv: element not found",
185 Self::TlvDuplicateTag => "tlv: duplicate tag in a structure",
186 Self::MessageTruncated => "msg: truncated",
187 Self::UnsupportedVersion => "msg: unsupported version",
188 Self::MessageReserved => "msg: reserved field value",
189 Self::DuplicateMessage => "msg: duplicate or replayed counter",
190 Self::IntegrityCheckFailed => "msg: integrity check failed",
191 Self::NoExchange => "exchange: no matching exchange",
192 Self::NoSession => "session: no matching session",
193 Self::MrpRetransmitExhausted => "mrp: retransmissions exhausted",
194 Self::NoSpace => "no space",
195 Self::Busy => "busy",
196 Self::BufferTooSmall => "buffer too small",
197 Self::InvalidArgument => "invalid argument",
198 Self::AlreadyExists => "entry already exists",
199 Self::InvalidAction => "interaction model: invalid action",
200 Self::ReportWouldChunk => "report does not fit one message",
201 Self::AttestationFailed => "attestation: §6.2.3's procedure did not pass",
202 Self::CommissioningFailed => "commissioning: the device answered with an error",
203 Self::CertInvalid => "cert: violates the §6.5 encoding rules",
204 Self::CertPathInvalid => "cert: chain does not validate",
205 Self::CertExpired => "cert: outside its validity window",
206 Self::Unsupported => "unsupported",
207 Self::DerMalformed => "der: malformed encoding",
208 Self::DnsTruncated => "dns: truncated message",
209 Self::DnsMalformed => "dns: malformed message",
210 Self::MessageTooLarge => "transport: message past the stream's maximum size",
211 Self::BdxAborted => "bdx: transfer aborted",
212 Self::BtpMalformed => "btp: malformed packet or reassembly",
213 Self::BtpSequence => "btp: sequence or acknowledgement out of order",
214 Self::BtpTimeout => "btp: acknowledgement timeout",
215 Self::InvalidState => "invalid state",
216 Self::Platform => "platform error",
217 }
218 }
219}
220
221/// A failure, with its local cause and — when the specification gives it one — the status
222/// code a peer is owed.
223///
224/// The interaction-model status is filled in by the `im` module once that layer exists; the
225/// field is here from the start so that lower layers can already answer, for example,
226/// `RESOURCE_EXHAUSTED` for [`ErrorCode::NoSpace`] without a second error type.
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228pub struct Error {
229 code: ErrorCode,
230}
231
232impl Error {
233 /// Builds an error from its local cause.
234 #[must_use]
235 pub const fn new(code: ErrorCode) -> Self {
236 Self { code }
237 }
238
239 /// The local cause.
240 #[must_use]
241 pub const fn code(self) -> ErrorCode {
242 self.code
243 }
244}
245
246impl From<ErrorCode> for Error {
247 fn from(code: ErrorCode) -> Self {
248 Self::new(code)
249 }
250}
251
252impl fmt::Display for Error {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254 f.write_str(self.code.as_str())
255 }
256}
257
258impl fmt::Display for ErrorCode {
259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260 f.write_str(self.as_str())
261 }
262}
263
264#[cfg(feature = "std")]
265impl std::error::Error for Error {}
266
267/// The crate's result type.
268pub type Result<T, E = Error> = core::result::Result<T, E>;
269
270/// Builds an [`Err`] from an [`ErrorCode`] without the `Error::new` ceremony.
271macro_rules! bail {
272 ($code:ident) => {
273 return Err($crate::error::Error::new($crate::error::ErrorCode::$code))
274 };
275}
276pub(crate) use bail;
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281
282 #[test]
283 fn display_is_the_code_name() {
284 let e = Error::new(ErrorCode::TlvTruncated);
285 #[cfg(feature = "std")]
286 assert_eq!(std::format!("{e}"), "tlv: truncated element");
287 assert_eq!(e.code(), ErrorCode::TlvTruncated);
288 }
289
290 #[test]
291 fn every_code_has_a_name() {
292 // A code whose name is empty is a code somebody added without a message.
293 for code in [
294 ErrorCode::TlvTruncated,
295 ErrorCode::NoSpace,
296 ErrorCode::Busy,
297 ErrorCode::Platform,
298 ] {
299 assert!(!code.as_str().is_empty());
300 }
301 }
302}