matter_kit/bdx/mod.rs
1//! Bulk Data Exchange (Core §11.22): moving a file between two nodes.
2//!
3//! Matter's messages are small — §4.4.4 caps a datagram at 1280 octets — and a firmware image
4//! is not. BDX is how anything larger moves: a negotiation, then a run of numbered blocks, then
5//! an acknowledgement that ends the session. It is what an OTA image travels over, what
6//! `RetrieveLogsRequest` (§11.12) hands a diagnostic log to, and the reason
7//! [`ImageUri`](crate::clusters::ota_provider::ImageUri) spells `bdx://`.
8//!
9//! The protocol "has some semantic elements influenced by the Trivial File Transfer Protocol
10//! (TFTP) RFC 1350", with one large difference: BDX does not retransmit. §11.22.4 requires a
11//! reliable transport underneath — MRP, BTP or TCP — so `BlockAck` and `BlockQuery` are
12//! *flow control*, not reliability. That is what lets a battery-powered node pace a download
13//! it could not otherwise stay awake for.
14//!
15//! # Four roles, two of which are the same question
16//!
17//! §11.22.2 names the ends twice over. **Sender** and **Receiver** say which way the data
18//! goes; **Initiator** and **Responder** say who spoke first. A download — an OTA Requestor
19//! fetching an image — is an Initiator that is the Receiver, so it opens with `ReceiveInit`;
20//! an upload opens with `SendInit`. Either way, exactly one end is the **Driver**: it paces
21//! the transfer, and the other follows. [`Sender`] and [`Receiver`] are this module's two
22//! halves, and [`Parameters::control`] is what says which of them drives.
23//!
24//! # Errors are status codes, because that is what goes on the wire
25//!
26//! Everything that inspects a peer's message returns [`Rejected`], whose error is the
27//! [`StatusCode`] of §11.22.3.2 — `BAD_BLOCK_COUNTER` for a block out of order,
28//! `LENGTH_MISMATCH` for a transfer that ended short. [`report`] turns one into the
29//! `StatusReport` to send, and §11.22.3.2 is clear about what happens next: "the receiving peer
30//! SHALL terminate its processing of the transfer and invalidate the exchange." Encoding, which
31//! can only fail locally, keeps the crate's ordinary [`Error`].
32//!
33//! # A download, end to end
34//!
35//! ```
36//! use matter_kit::bdx::{
37//! Direction, Init, Limits, MessageType, Parameters, Receiver, Sender, negotiate,
38//! };
39//!
40//! // The Requestor proposes: whole file, 256-octet blocks, either drive mode.
41//! let mut proposal = Init::new(b"firmware.ota", 256);
42//! proposal.definite_length = Some(600);
43//!
44//! // The Provider answers with what it will actually do.
45//! let limits = Limits { available: Some(600), ..Limits::default() };
46//! let agreed = negotiate(Direction::Download, &proposal, &limits)?;
47//! assert!(agreed.sender_drives()); // §11.22.5.4.1 prefers it
48//!
49//! let accept = agreed.receive_accept(&[]);
50//! let mut provider = Sender::new(agreed);
51//! let mut requestor = Receiver::new(Parameters::from_receive_accept(&proposal, &accept)?);
52//!
53//! // 600 octets in blocks of 256: 256, 256, then an 88-octet BlockEOF.
54//! for (len, eof) in [(256, false), (256, false), (88, true)] {
55//! let counter = provider.block(len, eof)?;
56//! requestor.on_block(counter, len, eof)?;
57//! let (opcode, counter) = requestor.ack()?;
58//! provider.on_ack(counter, opcode == MessageType::BlockAckEof)?;
59//! }
60//! assert!(provider.is_complete() && requestor.is_complete());
61//! assert_eq!(requestor.received(), 600);
62//! # Ok::<(), matter_kit::bdx::StatusCode>(())
63//! ```
64
65pub mod message;
66pub mod transfer;
67
68pub use message::{
69 Block, BlockQueryWithSkip, Counter, Init, MessageType, ReceiveAccept, SendAccept,
70 TransferControl, VERSION,
71};
72pub use transfer::{
73 DEFAULT_MAX_BLOCK_SIZE, Direction, Limits, Parameters, Receiver, Sender, negotiate,
74};
75
76use crate::error::{Error, ErrorCode, Result};
77use crate::msg::ProtocolId;
78use crate::sc::status::{GeneralCode, StatusReport};
79
80/// The result of anything that judges a peer's message: the failure is the status code the
81/// peer must be told.
82///
83/// Not [`crate::Result`], and deliberately: §11.22.3.2's codes are the entire content of a BDX
84/// failure, and folding them into a general error would throw away the only thing the caller
85/// needs in order to answer.
86pub type Rejected<T> = core::result::Result<T, StatusCode>;
87
88/// §11.22.3.2's status codes, as they appear in a `StatusReport`'s ProtocolCode field.
89///
90/// Exhaustive: the specification closes the set.
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
92#[repr(u16)]
93pub enum StatusCode {
94 /// "Definite length too large to support. For example, trying to SendInit with too large
95 /// of a file."
96 LengthTooLarge = 0x0012,
97 /// "Definite length proposed for transfer is too short for the context based on the
98 /// responder's knowledge of expected size."
99 LengthTooShort = 0x0013,
100 /// "Pre-negotiated size of transfer was not fulfilled prior to BlockAckEOF."
101 LengthMismatch = 0x0014,
102 /// "Responder can only support proposed transfer if definite length is provided."
103 LengthRequired = 0x0015,
104 /// "Received a malformed protocol message."
105 BadMessageContents = 0x0016,
106 /// "Received block counter out of order from expectation."
107 BadBlockCounter = 0x0017,
108 /// "Received a well-formed message that was contextually inappropriate for the current
109 /// state of the transfer."
110 UnexpectedMessage = 0x0018,
111 /// "Responder is too busy to proceed with a new transfer at this moment." An Initiator
112 /// "SHOULD wait at least 60 seconds" before trying again.
113 ResponderBusy = 0x0019,
114 /// "Other error occurred, such as perhaps an input/output error occurring at one of the
115 /// peers."
116 TransferFailedUnknownError = 0x001F,
117 /// "Received a message that mismatches the current transfer mode."
118 TransferMethodNotSupported = 0x0050,
119 /// "Attempted to request a file whose designator is unknown to the responder."
120 FileDesignatorUnknown = 0x0051,
121 /// "Proposed transfer with explicit start offset is not supported in current context."
122 StartOffsetNotSupported = 0x0052,
123 /// "Could not find a common supported version between initiator and responder."
124 VersionNotSupported = 0x0053,
125 /// "Other unexpected error."
126 Unknown = 0x005F,
127}
128
129impl StatusCode {
130 /// The wire value.
131 #[must_use]
132 pub const fn value(self) -> u16 {
133 self as u16
134 }
135
136 /// Reads a ProtocolCode from a `StatusReport` that named the BDX protocol.
137 ///
138 /// An unrecognised code becomes [`Unknown`](Self::Unknown) rather than an error: §11.22.3.2
139 /// says "any other unexpected StatusReport" ends the transfer just the same, so the one
140 /// thing a caller must not do is keep going because it could not read the reason.
141 #[must_use]
142 pub const fn from_u16(value: u16) -> Self {
143 match value {
144 0x0012 => Self::LengthTooLarge,
145 0x0013 => Self::LengthTooShort,
146 0x0014 => Self::LengthMismatch,
147 0x0015 => Self::LengthRequired,
148 0x0016 => Self::BadMessageContents,
149 0x0017 => Self::BadBlockCounter,
150 0x0018 => Self::UnexpectedMessage,
151 0x0019 => Self::ResponderBusy,
152 0x001F => Self::TransferFailedUnknownError,
153 0x0050 => Self::TransferMethodNotSupported,
154 0x0051 => Self::FileDesignatorUnknown,
155 0x0052 => Self::StartOffsetNotSupported,
156 0x0053 => Self::VersionNotSupported,
157 _ => Self::Unknown,
158 }
159 }
160}
161
162impl From<StatusCode> for Error {
163 /// For a caller that has to hand a BDX failure back through the crate's own error type —
164 /// the transfer is over either way.
165 fn from(_: StatusCode) -> Self {
166 Self::new(ErrorCode::BdxAborted)
167 }
168}
169
170/// Writes the `StatusReport` that ends a transfer (§11.22.3.2).
171///
172/// "StatusReport(GeneralCode: FAILURE, ProtocolId: {VendorID=0x0000, ProtocolId=BDX},
173/// ProtocolCode: `<value>`)" — sent on the same exchange, which is then invalidated.
174pub fn report(status: StatusCode, buf: &mut [u8]) -> Result<&[u8]> {
175 let written = StatusReport {
176 general: GeneralCode::Failure,
177 protocol: ProtocolId::BDX,
178 protocol_code: status.value(),
179 data: &[],
180 }
181 .encode(buf)?;
182 buf.get(..written)
183 .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))
184}
185
186/// Reads a `StatusReport` that arrived on a BDX exchange.
187///
188/// Returns the reason the transfer ended, or [`None`] if the report is not a BDX failure — a
189/// `SUCCESS` report, or one belonging to another protocol, neither of which ends the transfer.
190pub fn read_report(payload: &[u8]) -> Result<Option<StatusCode>> {
191 let report = StatusReport::decode(payload)?;
192 if report.general == GeneralCode::Success || report.protocol != ProtocolId::BDX {
193 return Ok(None);
194 }
195 Ok(Some(StatusCode::from_u16(report.protocol_code)))
196}