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    pub fn decode(buf: &'a [u8]) -> Result<Self> {
234        let (Some(general), Some(protocol), Some(code), Some(data)) =
235            (buf.get(..2), buf.get(2..6), buf.get(6..8), buf.get(8..))
236        else {
237            bail!(MessageTruncated)
238        };
239        let (Ok(general), Ok(protocol), Ok(code)) = (
240            <[u8; 2]>::try_from(general),
241            <[u8; 4]>::try_from(protocol),
242            <[u8; 2]>::try_from(code),
243        ) else {
244            bail!(MessageTruncated)
245        };
246        let qualified = u32::from_le_bytes(protocol);
247        Ok(Self {
248            general: GeneralCode::from_u16(u16::from_le_bytes(general))?,
249            protocol: ProtocolId {
250                vendor: VendorId((qualified >> 16) as u16),
251                id: qualified as u16,
252            },
253            protocol_code: u16::from_le_bytes(code),
254            data,
255        })
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    #[test]
264    fn the_specs_worked_example_encodes_exactly() {
265        // Appendix D.4: StatusReport(GeneralCode: FAILURE, ProtocolId: BDX, ProtocolCode:
266        // START_OFFSET_NOT_SUPPORTED) "Encodes as: 01 00 02 00 00 00 52 00".
267        let report = StatusReport {
268            general: GeneralCode::Failure,
269            protocol: ProtocolId::BDX,
270            protocol_code: 0x0052,
271            data: &[],
272        };
273        let mut buf = [0u8; 16];
274        let n = report.encode(&mut buf).expect("encode");
275        assert_eq!(&buf[..n], &[0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x52, 0x00]);
276        assert_eq!(StatusReport::decode(&buf[..n]).expect("decode"), report);
277    }
278
279    #[test]
280    fn a_vendor_protocol_id_keeps_its_vendor() {
281        let report = StatusReport {
282            general: GeneralCode::Failure,
283            protocol: ProtocolId {
284                vendor: VendorId(0xFFF1),
285                id: 0x0042,
286            },
287            protocol_code: 7,
288            data: &[],
289        };
290        let mut buf = [0u8; 16];
291        let n = report.encode(&mut buf).expect("encode");
292        // The 32-bit value is 0xFFF1_0042, little-endian.
293        assert_eq!(&buf[2..6], &[0x42, 0x00, 0xF1, 0xFF]);
294        assert_eq!(StatusReport::decode(&buf[..n]).expect("decode"), report);
295    }
296
297    #[test]
298    fn pake_finished_is_a_success_report() {
299        // §4.14.1's PakeFinished: SUCCESS / SECURE_CHANNEL / SESSION_ESTABLISHMENT_SUCCESS.
300        let report = StatusReport::secure_channel(SecureChannelCode::SessionEstablishmentSuccess);
301        assert_eq!(report.general, GeneralCode::Success);
302        assert!(report.is_success());
303        assert_eq!(
304            report.secure_channel_code(),
305            Some(SecureChannelCode::SessionEstablishmentSuccess)
306        );
307
308        let mut buf = [0u8; 16];
309        let n = report.encode(&mut buf).expect("encode");
310        assert_eq!(&buf[..n], &[0, 0, 0, 0, 0, 0, 0, 0]);
311    }
312
313    #[test]
314    fn each_secure_channel_code_carries_the_general_code_table_19_pairs_it_with() {
315        // A SUCCESS status carrying a failure code would be read as success.
316        assert_eq!(
317            SecureChannelCode::SessionEstablishmentSuccess.general(),
318            GeneralCode::Success
319        );
320        assert_eq!(
321            SecureChannelCode::InvalidParameter.general(),
322            GeneralCode::Failure
323        );
324        assert_eq!(
325            SecureChannelCode::NoSharedTrustRoots.general(),
326            GeneralCode::Failure
327        );
328        assert_eq!(
329            SecureChannelCode::CloseSession.general(),
330            GeneralCode::Success
331        );
332        assert_eq!(SecureChannelCode::Busy.general(), GeneralCode::Busy);
333    }
334
335    #[test]
336    fn only_close_session_must_be_encrypted() {
337        assert!(SecureChannelCode::CloseSession.requires_encryption());
338        for code in [
339            SecureChannelCode::SessionEstablishmentSuccess,
340            SecureChannelCode::NoSharedTrustRoots,
341            SecureChannelCode::InvalidParameter,
342            SecureChannelCode::Busy,
343        ] {
344            assert!(
345                !code.requires_encryption(),
346                "{code:?} is sent before a session exists"
347            );
348        }
349    }
350
351    #[test]
352    fn protocol_data_round_trips() {
353        let report = StatusReport {
354            general: GeneralCode::Busy,
355            protocol: ProtocolId::SECURE_CHANNEL,
356            protocol_code: SecureChannelCode::Busy as u16,
357            // §4.11.1.5's minimum wait time.
358            data: &[0xF4, 0x01],
359        };
360        let mut buf = [0u8; 16];
361        let n = report.encode(&mut buf).expect("encode");
362        assert_eq!(n, 10);
363        let decoded = StatusReport::decode(&buf[..n]).expect("decode");
364        assert_eq!(decoded.data, &[0xF4, 0x01]);
365    }
366
367    #[test]
368    fn a_reserved_general_code_is_refused() {
369        let buf = [0xFF, 0x00, 0, 0, 0, 0, 0, 0];
370        assert_eq!(
371            StatusReport::decode(&buf).unwrap_err().code(),
372            ErrorCode::MessageReserved
373        );
374    }
375
376    #[test]
377    fn truncation_at_every_length_is_an_error_not_a_panic() {
378        let buf = [0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x52, 0x00];
379        for cut in 0..buf.len() {
380            assert!(StatusReport::decode(&buf[..cut]).is_err(), "cut {cut}");
381        }
382        assert!(StatusReport::decode(&buf).is_ok());
383    }
384
385    #[test]
386    fn a_too_small_buffer_is_an_error() {
387        let report = StatusReport::secure_channel(SecureChannelCode::InvalidParameter);
388        let mut buf = [0u8; 7];
389        assert_eq!(
390            report.encode(&mut buf).unwrap_err().code(),
391            ErrorCode::BufferTooSmall
392        );
393    }
394
395    #[test]
396    fn general_codes_round_trip_through_their_numbers() {
397        for (value, code) in [
398            (0u16, GeneralCode::Success),
399            (1, GeneralCode::Failure),
400            (8, GeneralCode::Busy),
401            (10, GeneralCode::Continue),
402            (17, GeneralCode::MessageTooLarge),
403        ] {
404            assert_eq!(GeneralCode::from_u16(value).expect("known"), code);
405            assert_eq!(code as u16, value);
406        }
407        assert!(GeneralCode::from_u16(18).is_err());
408    }
409
410    #[test]
411    fn continue_counts_as_success() {
412        assert!(GeneralCode::Continue.is_success());
413        assert!(GeneralCode::Success.is_success());
414        assert!(!GeneralCode::Failure.is_success());
415        assert!(!GeneralCode::Busy.is_success());
416    }
417}