Skip to main content

matter_kit/bdx/
message.rs

1//! The ten BDX messages of §11.22.5 and §11.22.6, on the wire.
2//!
3//! None of them is TLV. BDX is a byte protocol with a TLV *tail* — the optional metadata on
4//! the four negotiation messages — so every field here is a fixed-width little-endian scalar
5//! read straight out of the payload, and the message id lives in the exchange's protocol
6//! header rather than in the payload at all.
7
8use super::{Rejected, StatusCode};
9use crate::error::{Error, ErrorCode, Result};
10
11/// The protocol version this crate speaks (§11.22.5.1.1: "The first version, as of Matter
12/// specification 1.0 is BDX Version 0").
13pub const VERSION: u8 = 0;
14
15/// §11.22.3.1's protocol opcodes, under [`ProtocolId::BDX`](crate::msg::ProtocolId::BDX).
16///
17/// Exhaustive on purpose: the specification closes this set, and the gaps in it (`0x03`,
18/// `0x06`..=`0x0F`) are reserved, so an unknown opcode is a peer speaking something else.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20#[repr(u8)]
21pub enum MessageType {
22    /// The Initiator wants to *send* — an upload (§11.22.5.1).
23    SendInit = 0x01,
24    /// The Responder accepts an upload (§11.22.5.2).
25    SendAccept = 0x02,
26    /// The Initiator wants to *receive* — a download (§11.22.5.1).
27    ReceiveInit = 0x04,
28    /// The Responder accepts a download (§11.22.5.3).
29    ReceiveAccept = 0x05,
30    /// A driving Receiver asks for the next block (§11.22.6.2).
31    BlockQuery = 0x10,
32    /// One block of data (§11.22.6.4).
33    Block = 0x11,
34    /// The last block, which may be empty (§11.22.6.5).
35    BlockEof = 0x12,
36    /// A Receiver acknowledges a block (§11.22.6.6).
37    BlockAck = 0x13,
38    /// A Receiver acknowledges the last block, ending the session (§11.22.6.7).
39    BlockAckEof = 0x14,
40    /// A driving Receiver seeks forward and asks for the next block (§11.22.6.3).
41    BlockQueryWithSkip = 0x15,
42}
43
44impl MessageType {
45    /// Reads an opcode from a protocol header.
46    ///
47    /// Rejects the reserved values rather than mapping them onto the nearest known one:
48    /// §11.22.3.1 leaves `0x03` and `0x06`..=`0x0F` for future use, and guessing at one would
49    /// put the transfer into a state neither end agreed to.
50    pub const fn from_u8(value: u8) -> Rejected<Self> {
51        Ok(match value {
52            0x01 => Self::SendInit,
53            0x02 => Self::SendAccept,
54            0x04 => Self::ReceiveInit,
55            0x05 => Self::ReceiveAccept,
56            0x10 => Self::BlockQuery,
57            0x11 => Self::Block,
58            0x12 => Self::BlockEof,
59            0x13 => Self::BlockAck,
60            0x14 => Self::BlockAckEof,
61            0x15 => Self::BlockQueryWithSkip,
62            _ => return Err(StatusCode::UnexpectedMessage),
63        })
64    }
65
66    /// The opcode as it appears in the protocol header.
67    #[must_use]
68    pub const fn value(self) -> u8 {
69        self as u8
70    }
71}
72
73/// The Transfer Control octet: a version and the transfer modes (§11.22.5.1.1, §11.22.5.4.1).
74///
75/// The same octet is `PTC` in an Init, where the bits are everything the Initiator *can* do,
76/// and `TC` in an Accept, where exactly one drive bit is what the Responder *chose*.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
78pub struct TransferControl {
79    /// `[VERSION]`, the low four bits.
80    pub version: u8,
81    /// `[SENDER_DRIVE]`: the Sender paces the transfer with Block messages.
82    pub sender_drive: bool,
83    /// `[RECEIVER_DRIVE]`: the Receiver paces it with BlockQuery messages.
84    pub receiver_drive: bool,
85    /// `[ASYNC]`: no driver, flow control left to the transport.
86    ///
87    /// Provisional in 1.6, and §11.22.5.4.1 is explicit that a Responder "SHALL not" choose it
88    /// — so [`negotiate`](super::negotiate) never does.
89    pub asynchronous: bool,
90}
91
92impl TransferControl {
93    const VERSION_MASK: u8 = 0x0F;
94    const SENDER_DRIVE: u8 = 1 << 4;
95    const RECEIVER_DRIVE: u8 = 1 << 5;
96    const ASYNC: u8 = 1 << 6;
97
98    /// Proposes synchronous Sender drive and Receiver drive at [`VERSION`], which is what an
99    /// initiator that can do either should offer (§11.22.5.1.1).
100    #[must_use]
101    pub const fn proposal() -> Self {
102        Self {
103            version: VERSION,
104            sender_drive: true,
105            receiver_drive: true,
106            asynchronous: false,
107        }
108    }
109
110    /// Reads the octet.
111    ///
112    /// Bit 7 is RFU and is ignored rather than refused: the version field is how BDX makes a
113    /// breaking change, so a spare bit in a message a future version sends is not this
114    /// version's business.
115    #[must_use]
116    pub const fn from_u8(value: u8) -> Self {
117        Self {
118            version: value & Self::VERSION_MASK,
119            sender_drive: value & Self::SENDER_DRIVE != 0,
120            receiver_drive: value & Self::RECEIVER_DRIVE != 0,
121            asynchronous: value & Self::ASYNC != 0,
122        }
123    }
124
125    /// Writes the octet.
126    #[must_use]
127    pub const fn to_u8(self) -> u8 {
128        let mut out = self.version & Self::VERSION_MASK;
129        if self.sender_drive {
130            out |= Self::SENDER_DRIVE;
131        }
132        if self.receiver_drive {
133            out |= Self::RECEIVER_DRIVE;
134        }
135        if self.asynchronous {
136            out |= Self::ASYNC;
137        }
138        out
139    }
140
141    /// Whether exactly one drive mode is named, which is what an Accept must carry.
142    ///
143    /// §11.22.5.4.1: "exactly one mode SHALL be chosen for this transfer", and the two bits are
144    /// mutually exclusive — "if this is set, TC\[RECEIVER_DRIVE\] SHALL be 0".
145    #[must_use]
146    pub const fn is_decided(self) -> bool {
147        self.sender_drive ^ self.receiver_drive
148    }
149}
150
151/// The Range Control octet: which of the optional offset and length fields are present, and
152/// how wide they are (§11.22.5.1.2, §11.22.5.4.2).
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
154struct RangeControl {
155    definite_length: bool,
156    start_offset: bool,
157    wide_range: bool,
158}
159
160impl RangeControl {
161    const DEFLEN: u8 = 1 << 0;
162    const STARTOFS: u8 = 1 << 1;
163    const WIDERANGE: u8 = 1 << 4;
164
165    const fn from_u8(value: u8) -> Self {
166        Self {
167            definite_length: value & Self::DEFLEN != 0,
168            start_offset: value & Self::STARTOFS != 0,
169            wide_range: value & Self::WIDERANGE != 0,
170        }
171    }
172
173    const fn to_u8(self) -> u8 {
174        let mut out = 0;
175        if self.definite_length {
176            out |= Self::DEFLEN;
177        }
178        if self.start_offset {
179            out |= Self::STARTOFS;
180        }
181        if self.wide_range {
182            out |= Self::WIDERANGE;
183        }
184        out
185    }
186
187    /// The width in octets of each present range field.
188    const fn width(self) -> usize {
189        if self.wide_range { 8 } else { 4 }
190    }
191}
192
193/// Whether a value needs the 64-bit encoding.
194///
195/// `RC[WIDERANGE]` is one bit covering *both* range fields, so it is set when either of them
196/// does not fit in 32 bits and cleared otherwise — the same "narrowest encoding that holds
197/// the value" rule §A.7.1 states for TLV, applied to the only place BDX has a choice.
198const fn needs_wide(value: u64) -> bool {
199    value > u32::MAX as u64
200}
201
202/// A `SendInit` or `ReceiveInit` message (§11.22.5.1).
203///
204/// The two share a format exactly; which one it is decides who sends the data, and that is the
205/// opcode, not a field. Everything here is a *proposal*: the Responder answers with the
206/// parameters it will actually use.
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub struct Init<'a> {
209    /// Proposed Transfer Control: version and the modes the Initiator supports.
210    pub control: TransferControl,
211    /// Proposed Max Block Size, "exclusive of block header fields, such as a block counter".
212    pub max_block_size: u16,
213    /// Where in the file to start, when the Initiator asks for part of it.
214    pub start_offset: Option<u64>,
215    /// The size the Initiator commits to, or expects. `None` is §11.22.5.1.5's indefinite
216    /// length, and so is a length of zero — the two are the same thing on the wire.
217    pub definite_length: Option<u64>,
218    /// The File Designator: whatever names the payload to the two ends.
219    pub file_designator: &'a [u8],
220    /// Optional application metadata, TLV, running to the end of the payload.
221    pub metadata: &'a [u8],
222}
223
224impl<'a> Init<'a> {
225    /// A proposal to transfer `file_designator` whole, in blocks of `max_block_size`.
226    #[must_use]
227    pub const fn new(file_designator: &'a [u8], max_block_size: u16) -> Self {
228        Self {
229            control: TransferControl::proposal(),
230            max_block_size,
231            start_offset: None,
232            definite_length: None,
233            file_designator,
234            metadata: &[],
235        }
236    }
237
238    /// The Range Control this message's optional fields imply.
239    fn range(&self) -> RangeControl {
240        let offset = self.start_offset.unwrap_or(0);
241        let length = self.definite_length.unwrap_or(0);
242        RangeControl {
243            definite_length: self.definite_length.is_some_and(|len| len != 0),
244            start_offset: self.start_offset.is_some(),
245            wide_range: needs_wide(offset) || needs_wide(length),
246        }
247    }
248
249    /// Writes the payload, and says how long it is.
250    pub fn encode(&self, buf: &mut [u8]) -> Result<usize> {
251        let range = self.range();
252        let mut w = Writer::new(buf);
253        w.u8(self.control.to_u8())?;
254        w.u8(range.to_u8())?;
255        w.u16(self.max_block_size)?;
256        if range.start_offset {
257            w.uint(self.start_offset.unwrap_or(0), range.width())?;
258        }
259        if range.definite_length {
260            w.uint(self.definite_length.unwrap_or(0), range.width())?;
261        }
262        let designator_len = u16::try_from(self.file_designator.len())
263            .map_err(|_| Error::new(ErrorCode::NoSpace))?;
264        w.u16(designator_len)?;
265        w.bytes(self.file_designator)?;
266        w.bytes(self.metadata)?;
267        Ok(w.written())
268    }
269
270    /// Reads the payload.
271    pub fn decode(payload: &'a [u8]) -> Rejected<Self> {
272        let mut r = Reader::new(payload);
273        let control = TransferControl::from_u8(r.u8()?);
274        let range = RangeControl::from_u8(r.u8()?);
275        let max_block_size = r.u16()?;
276        let start_offset = if range.start_offset {
277            Some(r.uint(range.width())?)
278        } else {
279            None
280        };
281        let definite_length = if range.definite_length {
282            // §11.22.5.1.5: "A length of 0 or a missing length field signifies an indefinite
283            // length", so the two spellings collapse to one value here.
284            Some(r.uint(range.width())?).filter(|len| *len != 0)
285        } else {
286            None
287        };
288        let designator_len = usize::from(r.u16()?);
289        let file_designator = r.bytes(designator_len)?;
290        Ok(Self {
291            control,
292            max_block_size,
293            start_offset,
294            definite_length,
295            file_designator,
296            metadata: r.rest(),
297        })
298    }
299}
300
301/// A `SendAccept` message (§11.22.5.2): the Responder will receive an upload.
302#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303pub struct SendAccept<'a> {
304    /// The one transfer mode and version chosen.
305    pub control: TransferControl,
306    /// The Max Block Size that will be used; §11.22.5.4.3 requires it be `<= PMBS`.
307    pub max_block_size: u16,
308    /// Optional application metadata, TLV.
309    pub metadata: &'a [u8],
310}
311
312impl<'a> SendAccept<'a> {
313    /// Writes the payload, and says how long it is.
314    pub fn encode(&self, buf: &mut [u8]) -> Result<usize> {
315        let mut w = Writer::new(buf);
316        w.u8(self.control.to_u8())?;
317        w.u16(self.max_block_size)?;
318        w.bytes(self.metadata)?;
319        Ok(w.written())
320    }
321
322    /// Reads the payload.
323    pub fn decode(payload: &'a [u8]) -> Rejected<Self> {
324        let mut r = Reader::new(payload);
325        let control = TransferControl::from_u8(r.u8()?);
326        let max_block_size = r.u16()?;
327        Ok(Self {
328            control,
329            max_block_size,
330            metadata: r.rest(),
331        })
332    }
333}
334
335/// A `ReceiveAccept` message (§11.22.5.3): the Responder will send a download.
336///
337/// The extra field over [`SendAccept`] is the one that matters: the Responder is the Sender
338/// here, so it is the end that knows how big the file actually is.
339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
340pub struct ReceiveAccept<'a> {
341    /// The one transfer mode and version chosen.
342    pub control: TransferControl,
343    /// The Max Block Size that will be used.
344    pub max_block_size: u16,
345    /// The length of the transfer, when the Sender knows it. `None` is indefinite.
346    pub length: Option<u64>,
347    /// Optional application metadata, TLV.
348    pub metadata: &'a [u8],
349}
350
351impl<'a> ReceiveAccept<'a> {
352    fn range(&self) -> RangeControl {
353        let length = self.length.unwrap_or(0);
354        RangeControl {
355            definite_length: self.length.is_some_and(|len| len != 0),
356            start_offset: false,
357            wide_range: needs_wide(length),
358        }
359    }
360
361    /// Writes the payload, and says how long it is.
362    pub fn encode(&self, buf: &mut [u8]) -> Result<usize> {
363        let range = self.range();
364        let mut w = Writer::new(buf);
365        w.u8(self.control.to_u8())?;
366        w.u8(range.to_u8())?;
367        w.u16(self.max_block_size)?;
368        if range.definite_length {
369            w.uint(self.length.unwrap_or(0), range.width())?;
370        }
371        w.bytes(self.metadata)?;
372        Ok(w.written())
373    }
374
375    /// Reads the payload.
376    pub fn decode(payload: &'a [u8]) -> Rejected<Self> {
377        let mut r = Reader::new(payload);
378        let control = TransferControl::from_u8(r.u8()?);
379        let range = RangeControl::from_u8(r.u8()?);
380        let max_block_size = r.u16()?;
381        let length = if range.definite_length {
382            Some(r.uint(range.width())?).filter(|len| *len != 0)
383        } else {
384            None
385        };
386        Ok(Self {
387            control,
388            max_block_size,
389            length,
390            metadata: r.rest(),
391        })
392    }
393}
394
395/// A `Block` or `BlockEOF` message (§11.22.6.4, §11.22.6.5).
396#[derive(Debug, Clone, Copy, PartialEq, Eq)]
397pub struct Block<'a> {
398    /// The block counter, ascending and sequential from zero (§11.22.6.1).
399    pub counter: u32,
400    /// The data. "The data field's length is that of the remainder of the message payload
401    /// after the Block Counter field, since Matter messages have definite length."
402    pub data: &'a [u8],
403}
404
405impl<'a> Block<'a> {
406    /// Writes the payload, and says how long it is.
407    pub fn encode(&self, buf: &mut [u8]) -> Result<usize> {
408        let mut w = Writer::new(buf);
409        w.u32(self.counter)?;
410        w.bytes(self.data)?;
411        Ok(w.written())
412    }
413
414    /// Reads the payload.
415    pub fn decode(payload: &'a [u8]) -> Rejected<Self> {
416        let mut r = Reader::new(payload);
417        let counter = r.u32()?;
418        Ok(Self {
419            counter,
420            data: r.rest(),
421        })
422    }
423}
424
425/// A bare block counter: `BlockQuery`, `BlockAck` and `BlockAckEOF` are all just this
426/// (§11.22.6.2, §11.22.6.6, §11.22.6.7).
427#[derive(Debug, Clone, Copy, PartialEq, Eq)]
428pub struct Counter {
429    /// The block being asked for, or acknowledged.
430    pub counter: u32,
431}
432
433impl Counter {
434    /// Writes the payload, and says how long it is.
435    pub fn encode(&self, buf: &mut [u8]) -> Result<usize> {
436        let mut w = Writer::new(buf);
437        w.u32(self.counter)?;
438        Ok(w.written())
439    }
440
441    /// Reads the payload.
442    ///
443    /// Trailing octets are refused: unlike a Block, these messages have no variable field, so
444    /// anything after the counter means the sender and this reader disagree about the format.
445    pub fn decode(payload: &[u8]) -> Rejected<Self> {
446        let mut r = Reader::new(payload);
447        let counter = r.u32()?;
448        r.end()?;
449        Ok(Self { counter })
450    }
451}
452
453/// A `BlockQueryWithSkip` message (§11.22.6.3): the next block, from `bytes_to_skip` further
454/// on.
455#[derive(Debug, Clone, Copy, PartialEq, Eq)]
456pub struct BlockQueryWithSkip {
457    /// The block counter, which advances by one exactly as a plain query's does.
458    pub counter: u32,
459    /// How far to move the Sender's cursor before reading the next block. Skipping past the
460    /// end is not an error: the answer is an empty `BlockEOF`.
461    pub bytes_to_skip: u64,
462}
463
464impl BlockQueryWithSkip {
465    /// Writes the payload, and says how long it is.
466    pub fn encode(&self, buf: &mut [u8]) -> Result<usize> {
467        let mut w = Writer::new(buf);
468        w.u32(self.counter)?;
469        w.uint(self.bytes_to_skip, 8)?;
470        Ok(w.written())
471    }
472
473    /// Reads the payload.
474    pub fn decode(payload: &[u8]) -> Rejected<Self> {
475        let mut r = Reader::new(payload);
476        let counter = r.u32()?;
477        let bytes_to_skip = r.uint(8)?;
478        r.end()?;
479        Ok(Self {
480            counter,
481            bytes_to_skip,
482        })
483    }
484}
485
486// --- Little-endian scalars ------------------------------------------------------------
487
488/// Reads fixed-width little-endian fields out of a payload.
489///
490/// Every shortfall is [`StatusCode::BadMessageContents`], which is what §11.22.3.2 says to
491/// answer a malformed message with, so the caller never has to translate.
492struct Reader<'a> {
493    rest: &'a [u8],
494}
495
496impl<'a> Reader<'a> {
497    const fn new(payload: &'a [u8]) -> Self {
498        Self { rest: payload }
499    }
500
501    fn bytes(&mut self, len: usize) -> Rejected<&'a [u8]> {
502        let (head, tail) = self
503            .rest
504            .split_at_checked(len)
505            .ok_or(StatusCode::BadMessageContents)?;
506        self.rest = tail;
507        Ok(head)
508    }
509
510    fn u8(&mut self) -> Rejected<u8> {
511        let bytes = self.bytes(1)?;
512        bytes.first().copied().ok_or(StatusCode::BadMessageContents)
513    }
514
515    fn u16(&mut self) -> Rejected<u16> {
516        let bytes =
517            <[u8; 2]>::try_from(self.bytes(2)?).map_err(|_| StatusCode::BadMessageContents)?;
518        Ok(u16::from_le_bytes(bytes))
519    }
520
521    fn u32(&mut self) -> Rejected<u32> {
522        let bytes =
523            <[u8; 4]>::try_from(self.bytes(4)?).map_err(|_| StatusCode::BadMessageContents)?;
524        Ok(u32::from_le_bytes(bytes))
525    }
526
527    /// A 4- or 8-octet little-endian unsigned value, widened.
528    fn uint(&mut self, width: usize) -> Rejected<u64> {
529        let mut out = [0u8; 8];
530        let bytes = self.bytes(width)?;
531        let slot = out.get_mut(..width).ok_or(StatusCode::BadMessageContents)?;
532        slot.copy_from_slice(bytes);
533        Ok(u64::from_le_bytes(out))
534    }
535
536    const fn rest(&self) -> &'a [u8] {
537        self.rest
538    }
539
540    fn end(&self) -> Rejected<()> {
541        if self.rest.is_empty() {
542            Ok(())
543        } else {
544            Err(StatusCode::BadMessageContents)
545        }
546    }
547}
548
549/// Writes fixed-width little-endian fields into a payload buffer.
550struct Writer<'a> {
551    buf: &'a mut [u8],
552    at: usize,
553}
554
555impl<'a> Writer<'a> {
556    const fn new(buf: &'a mut [u8]) -> Self {
557        Self { buf, at: 0 }
558    }
559
560    const fn written(&self) -> usize {
561        self.at
562    }
563
564    fn bytes(&mut self, bytes: &[u8]) -> Result<()> {
565        let end = self
566            .at
567            .checked_add(bytes.len())
568            .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
569        let slot = self
570            .buf
571            .get_mut(self.at..end)
572            .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
573        slot.copy_from_slice(bytes);
574        self.at = end;
575        Ok(())
576    }
577
578    fn u8(&mut self, value: u8) -> Result<()> {
579        self.bytes(&[value])
580    }
581
582    fn u16(&mut self, value: u16) -> Result<()> {
583        self.bytes(&value.to_le_bytes())
584    }
585
586    fn u32(&mut self, value: u32) -> Result<()> {
587        self.bytes(&value.to_le_bytes())
588    }
589
590    fn uint(&mut self, value: u64, width: usize) -> Result<()> {
591        let bytes = value.to_le_bytes();
592        let slot = bytes
593            .get(..width)
594            .ok_or(Error::new(ErrorCode::InvalidArgument))?;
595        self.bytes(slot)
596    }
597}