Skip to main content

matter_kit/sc/
status.rs

1//! The StatusReport message (Core §4.11.1.2, Appendix D).
2//!
3//! One message format that every protocol uses to say how an operation went. It is *not*
4//! TLV — it is eight fixed octets and an optional tail — which is why it can be parsed
5//! before anything knows which protocol is speaking.
6//!
7//! ```text
8//! ┌────────────────┬──────────────────────────┬────────────────┬──────────────┐
9//! │ GeneralCode(2) │ ProtocolId(4)            │ ProtocolCode(2)│ ProtocolData │
10//! └────────────────┴──────────────────────────┴────────────────┴──────────────┘
11//! ```
12//!
13//! All three scalars are little-endian, and the `ProtocolId` is "a 32 bit value of Protocol
14//! Vendor ID (upper 16 bits) and Protocol ID under that Protocol Vendor ID (lower 16
15//! bits)".
16
17use crate::error::{Error, ErrorCode, Result, bail};
18use crate::msg::{ProtocolId, VendorId};
19
20/// The uniform status codes of Appendix D.3.1.
21///
22/// Exhaustive on purpose: the **specification** closes this set, so a `match` on it should
23/// be checked for completeness when a future revision adds one.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
25#[repr(u16)]
26pub enum GeneralCode {
27    /// Operation completed successfully.
28    Success = 0,
29    /// Generic failure; the protocol-specific code says more.
30    Failure = 1,
31    /// "Operation was rejected by the system because the system is in an invalid state."
32    BadPrecondition = 2,
33    /// A value was out of a required range.
34    OutOfRange = 3,
35    /// A request was unrecognized or malformed.
36    BadRequest = 4,
37    /// An unrecognized or unsupported request was received.
38    Unsupported = 5,
39    /// A request was not expected at this time.
40    Unexpected = 6,
41    /// Insufficient resources to process the given request.
42    ResourceExhausted = 7,
43    /// Device is busy and cannot handle this request at this time.
44    Busy = 8,
45    /// A timeout occurred.
46    Timeout = 9,
47    /// Context-specific signal to proceed.
48    Continue = 10,
49    /// Failure, may be due to a concurrency error.
50    Aborted = 11,
51    /// An invalid or unsupported argument was provided.
52    InvalidArgument = 12,
53    /// Some requested entity was not found.
54    NotFound = 13,
55    /// The sender attempted to create something that already exists.
56    AlreadyExists = 14,
57    /// The sender does not have sufficient permissions.
58    PermissionDenied = 15,
59    /// Unrecoverable data loss or corruption has occurred.
60    DataLoss = 16,
61    /// "Message size is larger than the recipient can handle" — what a node answers when a
62    /// peer announces a message above its Maximum Message Size (§4.15.2.3).
63    MessageTooLarge = 17,
64}
65
66impl GeneralCode {
67    /// Decodes the wire value.
68    pub const fn from_u16(value: u16) -> Result<Self> {
69        Ok(match value {
70            0 => Self::Success,
71            1 => Self::Failure,
72            2 => Self::BadPrecondition,
73            3 => Self::OutOfRange,
74            4 => Self::BadRequest,
75            5 => Self::Unsupported,
76            6 => Self::Unexpected,
77            7 => Self::ResourceExhausted,
78            8 => Self::Busy,
79            9 => Self::Timeout,
80            10 => Self::Continue,
81            11 => Self::Aborted,
82            12 => Self::InvalidArgument,
83            13 => Self::NotFound,
84            14 => Self::AlreadyExists,
85            15 => Self::PermissionDenied,
86            16 => Self::DataLoss,
87            17 => Self::MessageTooLarge,
88            _ => return Err(Error::new(ErrorCode::MessageReserved)),
89        })
90    }
91
92    /// Whether this code reports success.
93    ///
94    /// `Continue` counts: Appendix D.3.2 groups it with `Success` as the two codes for
95    /// which `ProtocolCode` 0 is a placeholder rather than a real code.
96    #[must_use]
97    pub const fn is_success(self) -> bool {
98        matches!(self, Self::Success | Self::Continue)
99    }
100}
101
102/// The Secure Channel protocol-specific codes of Core Table 19.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
104#[repr(u16)]
105pub enum SecureChannelCode {
106    /// "Indication that the last session establishment message was successfully processed."
107    SessionEstablishmentSuccess = 0x0000,
108    /// Failure to find a common set of shared roots.
109    NoSharedTrustRoots = 0x0001,
110    /// "Generic failure during session establishment."
111    InvalidParameter = 0x0002,
112    /// "Indication that the sender will close the current session."
113    CloseSession = 0x0003,
114    /// "Indication that the sender cannot currently fulfill the request", carrying a
115    /// minimum wait time in its protocol data (§4.11.1.5).
116    Busy = 0x0004,
117}
118
119impl SecureChannelCode {
120    /// The general code the specification pairs this one with (Table 19).
121    ///
122    /// Pairing them here rather than at each call site is what stops a `SUCCESS` status
123    /// from carrying a failure code, which a peer would read as success.
124    #[must_use]
125    pub const fn general(self) -> GeneralCode {
126        match self {
127            Self::SessionEstablishmentSuccess | Self::CloseSession => GeneralCode::Success,
128            Self::NoSharedTrustRoots | Self::InvalidParameter => GeneralCode::Failure,
129            Self::Busy => GeneralCode::Busy,
130        }
131    }
132
133    /// Whether the specification requires this status to be sent inside a secure session.
134    #[must_use]
135    pub const fn requires_encryption(self) -> bool {
136        // Table 19's "Encrypted" column: only CloseSession is Y — the others are what a
137        // node says *before* a session exists.
138        matches!(self, Self::CloseSession)
139    }
140}
141
142/// A StatusReport message.
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub struct StatusReport<'a> {
145    /// The uniform code.
146    pub general: GeneralCode,
147    /// Which protocol's code space `protocol_code` is in.
148    pub protocol: ProtocolId,
149    /// The protocol-specific code.
150    pub protocol_code: u16,
151    /// "all data beyond the ProtocolCode field", whose meaning depends on the protocol.
152    pub data: &'a [u8],
153}
154
155/// "ProtocolCode value 0xFFFF SHALL be reserved to indicate that no additional
156/// protocol-specific status code is available."
157pub const NO_PROTOCOL_CODE: u16 = 0xFFFF;
158
159impl<'a> StatusReport<'a> {
160    /// The fixed part: two, four and two octets.
161    pub const HEADER_LEN: usize = 8;
162
163    /// Builds a Secure Channel status report, taking the general code from Table 19.
164    #[must_use]
165    pub const fn secure_channel(code: SecureChannelCode) -> Self {
166        Self {
167            general: code.general(),
168            protocol: ProtocolId::SECURE_CHANNEL,
169            protocol_code: code as u16,
170            data: &[],
171        }
172    }
173
174    /// Whether this reports success.
175    #[must_use]
176    pub const fn is_success(&self) -> bool {
177        self.general.is_success()
178    }
179
180    /// The Secure Channel code, when this is a Secure Channel report.
181    #[must_use]
182    pub fn secure_channel_code(&self) -> Option<SecureChannelCode> {
183        if self.protocol != ProtocolId::SECURE_CHANNEL {
184            return None;
185        }
186        Some(match self.protocol_code {
187            0x0000 => SecureChannelCode::SessionEstablishmentSuccess,
188            0x0001 => SecureChannelCode::NoSharedTrustRoots,
189            0x0002 => SecureChannelCode::InvalidParameter,
190            0x0003 => SecureChannelCode::CloseSession,
191            0x0004 => SecureChannelCode::Busy,
192            _ => return None,
193        })
194    }
195
196    /// How many octets this encodes to.
197    #[must_use]
198    pub const fn encoded_len(&self) -> usize {
199        Self::HEADER_LEN.saturating_add(self.data.len())
200    }
201
202    /// Writes the message into `out`.
203    pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
204        let total = self.encoded_len();
205        let Some(dst) = out.get_mut(..total) else {
206            bail!(BufferTooSmall)
207        };
208        let Some(general) = dst.get_mut(..2) else {
209            bail!(BufferTooSmall)
210        };
211        general.copy_from_slice(&(self.general as u16).to_le_bytes());
212
213        // ProtocolId: vendor in the upper 16 bits, protocol in the lower.
214        let qualified = (u32::from(self.protocol.vendor.0) << 16) | u32::from(self.protocol.id);
215        let Some(slot) = dst.get_mut(2..6) else {
216            bail!(BufferTooSmall)
217        };
218        slot.copy_from_slice(&qualified.to_le_bytes());
219
220        let Some(slot) = dst.get_mut(6..8) else {
221            bail!(BufferTooSmall)
222        };
223        slot.copy_from_slice(&self.protocol_code.to_le_bytes());
224
225        let Some(slot) = dst.get_mut(8..) else {
226            bail!(BufferTooSmall)
227        };
228        slot.copy_from_slice(self.data);
229        Ok(total)
230    }
231
232    /// Reads a message from `buf`.
233    #[expect(
234        clippy::cast_possible_truncation,
235        reason = "Appendix D's ProtocolCode is the low 16 bits of the qualified value just decoded"
236    )]
237    pub fn decode(buf: &'a [u8]) -> Result<Self> {
238        let (Some(general), Some(protocol), Some(code), Some(data)) =
239            (buf.get(..2), buf.get(2..6), buf.get(6..8), buf.get(8..))
240        else {
241            bail!(MessageTruncated)
242        };
243        let (Ok(general), Ok(protocol), Ok(code)) = (
244            <[u8; 2]>::try_from(general),
245            <[u8; 4]>::try_from(protocol),
246            <[u8; 2]>::try_from(code),
247        ) else {
248            bail!(MessageTruncated)
249        };
250        let qualified = u32::from_le_bytes(protocol);
251        Ok(Self {
252            general: GeneralCode::from_u16(u16::from_le_bytes(general))?,
253            protocol: ProtocolId {
254                vendor: VendorId((qualified >> 16) as u16),
255                id: qualified as u16,
256            },
257            protocol_code: u16::from_le_bytes(code),
258            data,
259        })
260    }
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    #[test]
268    fn the_specs_worked_example_encodes_exactly() {
269        // Appendix D.4: StatusReport(GeneralCode: FAILURE, ProtocolId: BDX, ProtocolCode:
270        // START_OFFSET_NOT_SUPPORTED) "Encodes as: 01 00 02 00 00 00 52 00".
271        let report = StatusReport {
272            general: GeneralCode::Failure,
273            protocol: ProtocolId::BDX,
274            protocol_code: 0x0052,
275            data: &[],
276        };
277        let mut buf = [0u8; 16];
278        let n = report.encode(&mut buf).expect("encode");
279        assert_eq!(&buf[..n], &[0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x52, 0x00]);
280        assert_eq!(StatusReport::decode(&buf[..n]).expect("decode"), report);
281    }
282
283    #[test]
284    fn a_vendor_protocol_id_keeps_its_vendor() {
285        let report = StatusReport {
286            general: GeneralCode::Failure,
287            protocol: ProtocolId {
288                vendor: VendorId(0xFFF1),
289                id: 0x0042,
290            },
291            protocol_code: 7,
292            data: &[],
293        };
294        let mut buf = [0u8; 16];
295        let n = report.encode(&mut buf).expect("encode");
296        // The 32-bit value is 0xFFF1_0042, little-endian.
297        assert_eq!(&buf[2..6], &[0x42, 0x00, 0xF1, 0xFF]);
298        assert_eq!(StatusReport::decode(&buf[..n]).expect("decode"), report);
299    }
300
301    #[test]
302    fn pake_finished_is_a_success_report() {
303        // §4.14.1's PakeFinished: SUCCESS / SECURE_CHANNEL / SESSION_ESTABLISHMENT_SUCCESS.
304        let report = StatusReport::secure_channel(SecureChannelCode::SessionEstablishmentSuccess);
305        assert_eq!(report.general, GeneralCode::Success);
306        assert!(report.is_success());
307        assert_eq!(
308            report.secure_channel_code(),
309            Some(SecureChannelCode::SessionEstablishmentSuccess)
310        );
311
312        let mut buf = [0u8; 16];
313        let n = report.encode(&mut buf).expect("encode");
314        assert_eq!(&buf[..n], &[0, 0, 0, 0, 0, 0, 0, 0]);
315    }
316
317    #[test]
318    fn each_secure_channel_code_carries_the_general_code_table_19_pairs_it_with() {
319        // A SUCCESS status carrying a failure code would be read as success.
320        assert_eq!(
321            SecureChannelCode::SessionEstablishmentSuccess.general(),
322            GeneralCode::Success
323        );
324        assert_eq!(
325            SecureChannelCode::InvalidParameter.general(),
326            GeneralCode::Failure
327        );
328        assert_eq!(
329            SecureChannelCode::NoSharedTrustRoots.general(),
330            GeneralCode::Failure
331        );
332        assert_eq!(
333            SecureChannelCode::CloseSession.general(),
334            GeneralCode::Success
335        );
336        assert_eq!(SecureChannelCode::Busy.general(), GeneralCode::Busy);
337    }
338
339    #[test]
340    fn only_close_session_must_be_encrypted() {
341        assert!(SecureChannelCode::CloseSession.requires_encryption());
342        for code in [
343            SecureChannelCode::SessionEstablishmentSuccess,
344            SecureChannelCode::NoSharedTrustRoots,
345            SecureChannelCode::InvalidParameter,
346            SecureChannelCode::Busy,
347        ] {
348            assert!(
349                !code.requires_encryption(),
350                "{code:?} is sent before a session exists"
351            );
352        }
353    }
354
355    #[test]
356    fn protocol_data_round_trips() {
357        let report = StatusReport {
358            general: GeneralCode::Busy,
359            protocol: ProtocolId::SECURE_CHANNEL,
360            protocol_code: SecureChannelCode::Busy as u16,
361            // §4.11.1.5's minimum wait time.
362            data: &[0xF4, 0x01],
363        };
364        let mut buf = [0u8; 16];
365        let n = report.encode(&mut buf).expect("encode");
366        assert_eq!(n, 10);
367        let decoded = StatusReport::decode(&buf[..n]).expect("decode");
368        assert_eq!(decoded.data, &[0xF4, 0x01]);
369    }
370
371    #[test]
372    fn a_reserved_general_code_is_refused() {
373        let buf = [0xFF, 0x00, 0, 0, 0, 0, 0, 0];
374        assert_eq!(
375            StatusReport::decode(&buf).unwrap_err().code(),
376            ErrorCode::MessageReserved
377        );
378    }
379
380    #[test]
381    fn truncation_at_every_length_is_an_error_not_a_panic() {
382        let buf = [0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x52, 0x00];
383        for cut in 0..buf.len() {
384            assert!(StatusReport::decode(&buf[..cut]).is_err(), "cut {cut}");
385        }
386        assert!(StatusReport::decode(&buf).is_ok());
387    }
388
389    #[test]
390    fn a_too_small_buffer_is_an_error() {
391        let report = StatusReport::secure_channel(SecureChannelCode::InvalidParameter);
392        let mut buf = [0u8; 7];
393        assert_eq!(
394            report.encode(&mut buf).unwrap_err().code(),
395            ErrorCode::BufferTooSmall
396        );
397    }
398
399    #[test]
400    fn general_codes_round_trip_through_their_numbers() {
401        for (value, code) in [
402            (0u16, GeneralCode::Success),
403            (1, GeneralCode::Failure),
404            (8, GeneralCode::Busy),
405            (10, GeneralCode::Continue),
406            (17, GeneralCode::MessageTooLarge),
407        ] {
408            assert_eq!(GeneralCode::from_u16(value).expect("known"), code);
409            assert_eq!(code as u16, value);
410        }
411        assert!(GeneralCode::from_u16(18).is_err());
412    }
413
414    #[test]
415    fn continue_counts_as_success() {
416        assert!(GeneralCode::Continue.is_success());
417        assert!(GeneralCode::Success.is_success());
418        assert!(!GeneralCode::Failure.is_success());
419        assert!(!GeneralCode::Busy.is_success());
420    }
421}