Skip to main content

matter_kit/msg/
header.rs

1//! The Matter message frame (Core §4.4).
2//!
3//! Two headers, one inside the other. The **message header** is what the message layer
4//! reads — session, counter, who it is from and to — and it is outside the encryption, so
5//! a receiver can find the key before it can decrypt anything. The **protocol header** is
6//! the first thing *inside* the encrypted payload: which exchange, which protocol, which
7//! opcode, and what is being acknowledged.
8//!
9//! ```text
10//! ┌── message header ─────────────────────────┐┌── payload (encrypted) ──┐┌ footer ┐
11//! │ flags │ session │ sec │ counter │ src │ dst││ protocol header │ app   ││  MIC   │
12//! └───────────────────────────────────────────┘└─────────────────────────┘└────────┘
13//! ```
14//!
15//! "All multi-byte integer fields are transmitted in little-endian byte order unless
16//! otherwise noted" (§4.4).
17
18use bitflags::bitflags;
19
20use super::ids::{ExchangeId, GroupId, NodeId, ProtocolId, SessionId, VendorId};
21use crate::bytes::Cursor;
22use crate::error::{Error, ErrorCode, Result, bail};
23
24/// The Matter message format version this crate speaks (§4.4.1.1).
25///
26/// "0 — Matter Message Format version 1.0". Everything else is reserved, and a message
27/// carrying one "SHALL be dropped without sending a message-layer acknowledgement".
28pub const MESSAGE_FORMAT_VERSION: u8 = 0;
29
30bitflags! {
31    /// The Message Flags octet (§4.4.1.1).
32    ///
33    /// Bits 4–7 are the version, bit 2 the source-present flag, bits 0–1 the `DSIZ` field.
34    /// Bit 3 is unused: "All unused bits … are reserved and SHALL be set to zero on
35    /// transmission and SHALL be silently ignored on reception."
36    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37    pub struct MessageFlags: u8 {
38        /// The Source Node ID field is present.
39        const SOURCE_PRESENT = 0b0000_0100;
40        /// `DSIZ` bit 0.
41        const DSIZ_0 = 0b0000_0001;
42        /// `DSIZ` bit 1.
43        const DSIZ_1 = 0b0000_0010;
44        /// The version field.
45        const VERSION = 0b1111_0000;
46    }
47}
48
49bitflags! {
50    /// The Security Flags octet (§4.4.1.3).
51    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52    pub struct SecurityFlags: u8 {
53        /// Privacy: the message is encoded with the privacy enhancements of §4.9.3.
54        const PRIVACY = 0b1000_0000;
55        /// Control message: uses the control message counter for its nonce (§4.8.1.1).
56        const CONTROL = 0b0100_0000;
57        /// Message Extensions present. "Version 1.0 Nodes SHALL set this flag to zero."
58        const MESSAGE_EXTENSIONS = 0b0010_0000;
59        /// Session type bit 0.
60        const SESSION_TYPE_0 = 0b0000_0001;
61        /// Session type bit 1.
62        const SESSION_TYPE_1 = 0b0000_0010;
63    }
64}
65
66bitflags! {
67    /// The Exchange Flags octet (§4.4.3.1).
68    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
69    pub struct ExchangeFlags: u8 {
70        /// **I** — the message was sent by the initiator of the exchange.
71        const INITIATOR = 0b0000_0001;
72        /// **A** — the message acknowledges an earlier one; the Acknowledged Message
73        /// Counter field is present.
74        const ACKNOWLEDGEMENT = 0b0000_0010;
75        /// **R** — the sender wants an acknowledgement (MRP, §4.12).
76        const RELIABILITY = 0b0000_0100;
77        /// **SX** — Secured Extensions present. "Version 1.0 Nodes SHALL set this flag to
78        /// zero."
79        const SECURED_EXTENSIONS = 0b0000_1000;
80        /// **V** — the Protocol Vendor ID field is present.
81        const VENDOR = 0b0001_0000;
82    }
83}
84
85/// The kind of session a message belongs to (§4.4.1.3).
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
87pub enum SessionType {
88    /// A one-to-one session. With session id 0 this is the *unsecured* session, which
89    /// "SHALL have no encryption, privacy, or message integrity checking".
90    #[default]
91    Unicast,
92    /// A group session, addressed by Group ID.
93    Group,
94}
95
96impl SessionType {
97    const fn bits(self) -> u8 {
98        match self {
99            Self::Unicast => 0,
100            Self::Group => 1,
101        }
102    }
103
104    const fn from_bits(bits: u8) -> Result<Self> {
105        match bits & 0b11 {
106            0 => Ok(Self::Unicast),
107            1 => Ok(Self::Group),
108            // "Messages with Session Type set to reserved values are not valid and SHALL
109            // be dropped without sending a message-layer acknowledgement."
110            _ => Err(Error::new(ErrorCode::MessageReserved)),
111        }
112    }
113}
114
115/// The Destination Node ID field, whose size and meaning the `DSIZ` field sets
116/// (§4.4.1.1, §4.4.1.6).
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
118pub enum Destination {
119    /// `DSIZ` 0 — the field is absent.
120    #[default]
121    None,
122    /// `DSIZ` 1 — a 64-bit Node ID.
123    Node(NodeId),
124    /// `DSIZ` 2 — a 16-bit Group ID.
125    Group(GroupId),
126}
127
128impl Destination {
129    const fn dsiz(self) -> u8 {
130        match self {
131            Self::None => 0,
132            Self::Node(_) => 1,
133            Self::Group(_) => 2,
134        }
135    }
136
137    const fn encoded_len(self) -> usize {
138        match self {
139            Self::None => 0,
140            Self::Node(_) => 8,
141            Self::Group(_) => 2,
142        }
143    }
144}
145
146/// The unencrypted header every Matter message starts with (§4.4.1).
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub struct MessageHeader {
149    /// Which session — and so which key — this message belongs to.
150    pub session_id: SessionId,
151    /// Unicast or group.
152    pub session_type: SessionType,
153    /// Whether privacy processing (§4.9) was applied.
154    pub privacy: bool,
155    /// Whether this is a control message, which counts on its own counter (§4.8.1.1).
156    pub control: bool,
157    /// The sender's monotonically increasing counter for this key (§4.4.1.4).
158    pub message_counter: u32,
159    /// The sender, when it chose to say (§4.4.1.5).
160    pub source: Option<NodeId>,
161    /// The recipient (§4.4.1.6).
162    pub destination: Destination,
163}
164
165impl Default for MessageHeader {
166    fn default() -> Self {
167        Self {
168            session_id: SessionId::UNSECURED,
169            session_type: SessionType::Unicast,
170            privacy: false,
171            control: false,
172            message_counter: 0,
173            source: None,
174            destination: Destination::None,
175        }
176    }
177}
178
179impl MessageHeader {
180    /// Whether this is the unsecured session: unicast, session id zero (§4.4.1.3).
181    ///
182    /// "The Unsecured Session SHALL have no encryption, privacy, or message integrity
183    /// checking" — so a message on it carries no MIC.
184    #[must_use]
185    pub const fn is_unsecured(&self) -> bool {
186        matches!(self.session_type, SessionType::Unicast) && self.session_id.0 == 0
187    }
188
189    /// How many octets this header occupies.
190    #[must_use]
191    pub const fn encoded_len(&self) -> usize {
192        // flags(1) + session(2) + security(1) + counter(4)
193        const BASE: usize = 8;
194        let src = if self.source.is_some() { 8 } else { 0 };
195        BASE.saturating_add(src)
196            .saturating_add(self.destination.encoded_len())
197    }
198
199    /// Writes the header into `out`, returning how many octets it used.
200    pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
201        let mut w = Cursor::writer(out);
202
203        let mut flags = MessageFlags::from_bits_retain(MESSAGE_FORMAT_VERSION << 4);
204        if self.source.is_some() {
205            flags |= MessageFlags::SOURCE_PRESENT;
206        }
207        flags = MessageFlags::from_bits_retain(flags.bits() | self.destination.dsiz());
208        w.u8(flags.bits())?;
209        w.u16(self.session_id.0)?;
210
211        let mut security = SecurityFlags::from_bits_retain(self.session_type.bits());
212        if self.privacy {
213            security |= SecurityFlags::PRIVACY;
214        }
215        if self.control {
216            security |= SecurityFlags::CONTROL;
217        }
218        w.u8(security.bits())?;
219        w.u32(self.message_counter)?;
220
221        if let Some(source) = self.source {
222            w.u64(source.0)?;
223        }
224        match self.destination {
225            Destination::None => {}
226            Destination::Node(n) => w.u64(n.0)?,
227            Destination::Group(g) => w.u16(g.0)?,
228        }
229        Ok(w.position())
230    }
231
232    /// Reads a header from the front of `buf`, returning it and the rest of the message.
233    pub fn decode(buf: &[u8]) -> Result<(Self, &[u8])> {
234        let mut r = Cursor::reader(buf, ErrorCode::MessageTruncated);
235
236        let flags = MessageFlags::from_bits_retain(r.read_u8()?);
237        let version = (flags.bits() & MessageFlags::VERSION.bits()) >> 4;
238        if version != MESSAGE_FORMAT_VERSION {
239            // §4.4.1.1: "Messages with version field set to reserved values SHALL be
240            // dropped without sending a message-layer acknowledgement."
241            bail!(UnsupportedVersion)
242        }
243
244        let session_id = SessionId(r.read_u16()?);
245        let security = SecurityFlags::from_bits_retain(r.read_u8()?);
246        let session_type = SessionType::from_bits(security.bits())?;
247        let message_counter = r.read_u32()?;
248
249        let source = if flags.contains(MessageFlags::SOURCE_PRESENT) {
250            Some(NodeId(r.read_u64()?))
251        } else {
252            None
253        };
254
255        let dsiz = flags.bits() & 0b11;
256        let destination = match dsiz {
257            0 => Destination::None,
258            1 => Destination::Node(NodeId(r.read_u64()?)),
259            2 => Destination::Group(GroupId(r.read_u16()?)),
260            // §4.4.1.1: "Messages with DSIZ field set to reserved values SHALL be dropped".
261            _ => bail!(MessageReserved),
262        };
263
264        // §4.4.1.7: the Message Extensions block is present only when MX is set, and
265        // "Version 1.0 Nodes SHALL ignore the contents of the Message Extensions payload,
266        // by skipping it, to access the Message Payload."
267        if security.contains(SecurityFlags::MESSAGE_EXTENSIONS) {
268            let len = usize::from(r.read_u16()?);
269            r.skip(len)?;
270        }
271
272        let header = Self {
273            session_id,
274            session_type,
275            privacy: security.contains(SecurityFlags::PRIVACY),
276            control: security.contains(SecurityFlags::CONTROL),
277            message_counter,
278            source,
279            destination,
280        };
281        Ok((header, r.rest()))
282    }
283}
284
285/// The header at the start of a message's payload (§4.4.3).
286#[derive(Debug, Clone, Copy, PartialEq, Eq)]
287pub struct ProtocolHeader {
288    /// Whether this message came from the exchange's initiator.
289    pub initiator: bool,
290    /// The counter this message acknowledges, when it acknowledges one (§4.12.1).
291    pub acknowledged_counter: Option<u32>,
292    /// Whether the sender wants an acknowledgement — the MRP **R** flag.
293    pub reliability: bool,
294    /// Which conversation this message belongs to.
295    pub exchange_id: ExchangeId,
296    /// Which protocol, and whose.
297    pub protocol: ProtocolId,
298    /// What kind of message, within that protocol.
299    pub opcode: u8,
300}
301
302impl Default for ProtocolHeader {
303    fn default() -> Self {
304        Self {
305            initiator: false,
306            acknowledged_counter: None,
307            reliability: false,
308            exchange_id: ExchangeId(0),
309            protocol: ProtocolId::SECURE_CHANNEL,
310            opcode: 0,
311        }
312    }
313}
314
315impl ProtocolHeader {
316    /// How many octets this header occupies.
317    #[must_use]
318    pub const fn encoded_len(&self) -> usize {
319        // flags(1) + opcode(1) + exchange(2) + protocol(2)
320        const BASE: usize = 6;
321        let vendor = if self.protocol.is_common() { 0 } else { 2 };
322        let ack = if self.acknowledged_counter.is_some() {
323            4
324        } else {
325            0
326        };
327        BASE.saturating_add(vendor).saturating_add(ack)
328    }
329
330    /// Writes the header into `out`, returning how many octets it used.
331    pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
332        let mut w = Cursor::writer(out);
333
334        let mut flags = ExchangeFlags::empty();
335        if self.initiator {
336            flags |= ExchangeFlags::INITIATOR;
337        }
338        if self.acknowledged_counter.is_some() {
339            flags |= ExchangeFlags::ACKNOWLEDGEMENT;
340        }
341        if self.reliability {
342            flags |= ExchangeFlags::RELIABILITY;
343        }
344        if !self.protocol.is_common() {
345            flags |= ExchangeFlags::VENDOR;
346        }
347        w.u8(flags.bits())?;
348        w.u8(self.opcode)?;
349        w.u16(self.exchange_id.0)?;
350        if !self.protocol.is_common() {
351            w.u16(self.protocol.vendor.0)?;
352        }
353        w.u16(self.protocol.id)?;
354        if let Some(ack) = self.acknowledged_counter {
355            w.u32(ack)?;
356        }
357        Ok(w.position())
358    }
359
360    /// Reads a header from the front of `buf`, returning it and the application payload.
361    pub fn decode(buf: &[u8]) -> Result<(Self, &[u8])> {
362        let mut r = Cursor::reader(buf, ErrorCode::MessageTruncated);
363
364        let flags = ExchangeFlags::from_bits_retain(r.read_u8()?);
365        let opcode = r.read_u8()?;
366        let exchange_id = ExchangeId(r.read_u16()?);
367        let vendor = if flags.contains(ExchangeFlags::VENDOR) {
368            VendorId(r.read_u16()?)
369        } else {
370            VendorId::COMMON
371        };
372        let protocol = ProtocolId {
373            vendor,
374            id: r.read_u16()?,
375        };
376        let acknowledged_counter = if flags.contains(ExchangeFlags::ACKNOWLEDGEMENT) {
377            Some(r.read_u32()?)
378        } else {
379            None
380        };
381
382        // §4.4.3.7: Secured Extensions, present only when SX is set. Skipped like the
383        // message extensions above.
384        if flags.contains(ExchangeFlags::SECURED_EXTENSIONS) {
385            let len = usize::from(r.read_u16()?);
386            r.skip(len)?;
387        }
388
389        let header = Self {
390            initiator: flags.contains(ExchangeFlags::INITIATOR),
391            acknowledged_counter,
392            reliability: flags.contains(ExchangeFlags::RELIABILITY),
393            exchange_id,
394            protocol,
395            opcode,
396        };
397        Ok((header, r.rest()))
398    }
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404
405    fn round_trip(header: &MessageHeader) {
406        let mut buf = [0u8; 64];
407        let n = header.encode(&mut buf).expect("encode");
408        assert_eq!(n, header.encoded_len(), "encoded_len disagrees with encode");
409        let (decoded, rest) = MessageHeader::decode(&buf[..n]).expect("decode");
410        assert_eq!(&decoded, header);
411        assert!(rest.is_empty());
412    }
413
414    #[test]
415    fn message_header_round_trips() {
416        round_trip(&MessageHeader::default());
417        round_trip(&MessageHeader {
418            session_id: SessionId(0x1234),
419            session_type: SessionType::Unicast,
420            message_counter: 0xDEAD_BEEF,
421            source: Some(NodeId(0x0102_0304_0506_0708)),
422            destination: Destination::Node(NodeId(1)),
423            ..MessageHeader::default()
424        });
425        round_trip(&MessageHeader {
426            session_id: SessionId(5),
427            session_type: SessionType::Group,
428            destination: Destination::Group(GroupId(0x4242)),
429            control: true,
430            privacy: true,
431            ..MessageHeader::default()
432        });
433    }
434
435    #[test]
436    fn the_wire_layout_is_little_endian_and_in_order() {
437        let header = MessageHeader {
438            session_id: SessionId(0x1234),
439            message_counter: 0x0A0B_0C0D,
440            source: Some(NodeId(0x1122_3344_5566_7788)),
441            destination: Destination::Group(GroupId(0xABCD)),
442            ..MessageHeader::default()
443        };
444        let mut buf = [0u8; 64];
445        let n = header.encode(&mut buf).expect("encode");
446        assert_eq!(
447            &buf[..n],
448            &[
449                // flags: version 0, S set (0x04), DSIZ 2 (group)
450                0x06, //
451                // session id, little-endian
452                0x34, 0x12, //
453                // security flags: unicast session type, nothing else
454                0x00, //
455                // message counter, little-endian
456                0x0D, 0x0C, 0x0B, 0x0A, //
457                // source node id, little-endian
458                0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, //
459                // destination group id, little-endian
460                0xCD, 0xAB,
461            ]
462        );
463    }
464
465    #[test]
466    fn a_reserved_version_is_dropped() {
467        // §4.4.1.1.
468        let buf = [0x10, 0, 0, 0, 0, 0, 0, 0];
469        assert_eq!(
470            MessageHeader::decode(&buf).unwrap_err().code(),
471            ErrorCode::UnsupportedVersion
472        );
473    }
474
475    #[test]
476    fn a_reserved_dsiz_is_dropped() {
477        // DSIZ 3 is "Reserved for future use".
478        let buf = [0x03, 0, 0, 0, 0, 0, 0, 0];
479        assert_eq!(
480            MessageHeader::decode(&buf).unwrap_err().code(),
481            ErrorCode::MessageReserved
482        );
483    }
484
485    #[test]
486    fn a_reserved_session_type_is_dropped() {
487        // Session type 2 is "Reserved for future use".
488        let buf = [0x00, 0, 0, 0x02, 0, 0, 0, 0];
489        assert_eq!(
490            MessageHeader::decode(&buf).unwrap_err().code(),
491            ErrorCode::MessageReserved
492        );
493    }
494
495    #[test]
496    fn truncation_at_every_length_is_an_error_not_a_panic() {
497        let header = MessageHeader {
498            source: Some(NodeId(7)),
499            destination: Destination::Node(NodeId(8)),
500            ..MessageHeader::default()
501        };
502        let mut buf = [0u8; 64];
503        let n = header.encode(&mut buf).expect("encode");
504        for cut in 0..n {
505            assert!(
506                MessageHeader::decode(&buf[..cut]).is_err(),
507                "a {cut}-octet header should not decode"
508            );
509        }
510    }
511
512    #[test]
513    fn a_too_small_buffer_is_an_error() {
514        let header = MessageHeader {
515            source: Some(NodeId(7)),
516            ..MessageHeader::default()
517        };
518        let mut buf = [0u8; 4];
519        assert!(header.encode(&mut buf).is_err());
520    }
521
522    #[test]
523    fn message_extensions_are_skipped() {
524        // §4.4.1.7: MX set, a 3-octet payload, then the real payload.
525        let buf = [
526            0x00, // flags
527            0x00, 0x00, // session
528            0x20, // security: MX
529            0x00, 0x00, 0x00, 0x00, // counter
530            0x03, 0x00, // extensions length
531            0xAA, 0xBB, 0xCC, // extensions payload, ignored
532            0x99, // the payload that follows
533        ];
534        let (header, rest) = MessageHeader::decode(&buf).expect("decode");
535        assert_eq!(header.message_counter, 0);
536        assert_eq!(rest, &[0x99]);
537    }
538
539    #[test]
540    fn a_lying_extension_length_is_an_error() {
541        let buf = [0x00, 0, 0, 0x20, 0, 0, 0, 0, 0xFF, 0xFF, 0xAA];
542        assert_eq!(
543            MessageHeader::decode(&buf).unwrap_err().code(),
544            ErrorCode::MessageTruncated
545        );
546    }
547
548    fn protocol_round_trip(header: &ProtocolHeader) {
549        let mut buf = [0u8; 32];
550        let n = header.encode(&mut buf).expect("encode");
551        assert_eq!(n, header.encoded_len(), "encoded_len disagrees with encode");
552        let (decoded, rest) = ProtocolHeader::decode(&buf[..n]).expect("decode");
553        assert_eq!(&decoded, header);
554        assert!(rest.is_empty());
555    }
556
557    #[test]
558    fn protocol_header_round_trips() {
559        protocol_round_trip(&ProtocolHeader::default());
560        protocol_round_trip(&ProtocolHeader {
561            initiator: true,
562            reliability: true,
563            acknowledged_counter: Some(0x1234_5678),
564            exchange_id: ExchangeId(0xBEEF),
565            protocol: ProtocolId::INTERACTION_MODEL,
566            opcode: 0x02,
567        });
568        protocol_round_trip(&ProtocolHeader {
569            protocol: ProtocolId {
570                vendor: VendorId::TEST_1,
571                id: 0x0042,
572            },
573            ..ProtocolHeader::default()
574        });
575    }
576
577    #[test]
578    fn a_vendor_protocol_carries_its_vendor_id() {
579        let common = ProtocolHeader::default();
580        let vendor = ProtocolHeader {
581            protocol: ProtocolId {
582                vendor: VendorId::TEST_1,
583                id: 1,
584            },
585            ..ProtocolHeader::default()
586        };
587        assert_eq!(
588            vendor.encoded_len(),
589            common.encoded_len() + 2,
590            "the V flag adds exactly the Protocol Vendor ID field"
591        );
592    }
593
594    #[test]
595    fn payload_follows_the_protocol_header() {
596        let header = ProtocolHeader {
597            exchange_id: ExchangeId(1),
598            protocol: ProtocolId::INTERACTION_MODEL,
599            opcode: 5,
600            ..ProtocolHeader::default()
601        };
602        let mut buf = [0u8; 32];
603        let n = header.encode(&mut buf).expect("encode");
604        buf[n] = 0xAB;
605        let (decoded, payload) = ProtocolHeader::decode(&buf[..=n]).expect("decode");
606        assert_eq!(decoded.opcode, 5);
607        assert_eq!(payload, &[0xAB]);
608    }
609
610    #[test]
611    fn protocol_truncation_is_an_error_not_a_panic() {
612        let header = ProtocolHeader {
613            acknowledged_counter: Some(1),
614            protocol: ProtocolId {
615                vendor: VendorId::TEST_1,
616                id: 1,
617            },
618            ..ProtocolHeader::default()
619        };
620        let mut buf = [0u8; 32];
621        let n = header.encode(&mut buf).expect("encode");
622        for cut in 0..n {
623            assert!(ProtocolHeader::decode(&buf[..cut]).is_err(), "cut {cut}");
624        }
625    }
626}