Skip to main content

matter_kit/clusters/
ota_provider.rs

1//! OTA Software Update Provider, cluster `0x0029` (Core §11.20.6).
2//!
3//! > This cluster implements the Provider role in the OTA process.
4//!
5//! A node that hands out firmware. An OTA Requestor asks "is there a newer image for this
6//! vendor, product and version?", and the provider answers with a URI, a version and a token —
7//! or with `NotAvailable`, or with `Busy` and a time to come back.
8//!
9//! # The provider decides, and the requestor obeys the delay
10//!
11//! §11.20.6.5's `DelayedActionTime` is the whole flow-control mechanism. A provider serving a
12//! fleet cannot have every device download at once, and this is how it spreads them:
13//!
14//! > This field, if provided, SHALL convey the minimum time to wait, in seconds from the time
15//! > of this response, before sending another QueryImage command or beginning a download.
16//!
17//! The same field appears in `ApplyUpdateResponse`, where it delays the *reboot* — which is
18//! what stops every light in a house going dark at the same moment.
19//!
20//! # The image itself is not here
21//!
22//! A `QueryImageResponse` carries a URI, not bytes. §11.20.6.5's `bdx:` scheme names the node
23//! and the file, and the transfer belongs to [`bdx`](crate::bdx) — a separate protocol on a
24//! separate exchange. So a provider built on this cluster answers the query, and then
25//! [`bdx::Sender`](crate::bdx::Sender) moves the image.
26//!
27//! [`ImageUri`] builds and parses the `bdx:` form, because §11.20.6.5 spends a page on its
28//! syntax and gets specific about why: "the format constraints simplify the extraction of the
29//! necessary data", and a requestor is entitled to rely on that.
30
31use crate::clusters::generated::ota_software_update_provider as spec_ota;
32use crate::dm::spec::{Conforming, Optional};
33use crate::dm::{Resolved, ResolvedCommand};
34use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
35use crate::msg::{NodeId, VendorId};
36use crate::tlv::{Tag, TlvWriter, ToTlv};
37
38use super::Cluster;
39
40pub use spec_ota::command::{
41    APPLY_UPDATE_REQUEST, APPLY_UPDATE_RESPONSE, NOTIFY_UPDATE_APPLIED, QUERY_IMAGE,
42    QUERY_IMAGE_RESPONSE,
43};
44pub use spec_ota::{ApplyUpdateActionEnum, DownloadProtocolEnum, ID, PICS, REVISION, StatusEnum};
45
46/// §11.20.6.5's constraint on `UpdateToken`: "8 to 32".
47pub const TOKEN_MIN: usize = 8;
48/// The other end of it.
49pub const TOKEN_MAX: usize = 32;
50
51/// §11.20.6.5's constraint on `ImageURI`: "max 256".
52pub const URI_MAX: usize = 256;
53
54/// §11.20.6.5's constraint on `SoftwareVersionString`: "1 to 64".
55pub const VERSION_STRING_MAX: usize = 64;
56
57/// §11.20.6.5's ceiling on a useful `DelayedActionTime`.
58///
59/// > If this field has a value higher than 86400 seconds (24 hours), then the OTA Requestor MAY
60/// > assume a value of 86400.
61pub const MAX_USEFUL_DELAY_S: u32 = 86_400;
62
63/// Which node is asking, and for what.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct Query {
66    /// The requestor's `VendorID`, which §11.20.6.5 requires to match its Basic Information.
67    pub vendor_id: VendorId,
68    /// Its `ProductID`.
69    pub product_id: u16,
70    /// The version it is running now.
71    pub software_version: u32,
72    /// Its `HardwareVersion`, when it told us.
73    pub hardware_version: Option<u16>,
74    /// Whether the requestor can ask a person before applying an update.
75    ///
76    /// §11.20.3.4: a provider that requires consent may only set `UserConsentNeeded` when the
77    /// requestor said it can obtain it — otherwise the update would stall for ever waiting for
78    /// a confirmation nothing can give.
79    pub requestor_can_consent: bool,
80    /// Whether the requestor can take a synchronous BDX transfer.
81    ///
82    /// §11.20.6.5: "BDX Synchronous transfer mode SHALL always be supported by an OTA
83    /// Provider", so a requestor that does not offer it is offering something else entirely.
84    pub supports_bdx: bool,
85    /// Whether it offered HTTPS.
86    pub supports_https: bool,
87}
88
89/// What the provider has for a requestor.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum Answer<'a> {
92    /// §11.20.6.4's `UpdateAvailable`: here it is.
93    Available {
94        /// Where to get it. `bdx:` names this provider and a file (§11.20.6.5).
95        uri: &'a str,
96        /// The version the image carries.
97        software_version: u32,
98        /// Its human-readable form, 1 to 64 characters.
99        software_version_string: &'a str,
100        /// §11.20.3.6.1's `UpdateToken`, 8 to 32 octets — the provider's handle on this
101        /// particular update, which comes back in `ApplyUpdateRequest`.
102        update_token: &'a [u8],
103        /// Whether a person must confirm before the requestor applies it.
104        user_consent_needed: bool,
105    },
106    /// `Busy`: there may be one, but not yet. Come back after `delay_s`.
107    Busy {
108        /// Seconds to wait, which §11.20.6.5 makes mandatory for this status.
109        delay_s: u32,
110    },
111    /// `NotAvailable`: "there is definitely no update currently available".
112    NotAvailable,
113    /// `DownloadProtocolNotSupported`: there is an image, but not one this requestor can fetch.
114    ProtocolNotSupported,
115}
116
117/// What the provider decides about a requestor that is ready to reboot.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub struct ApplyDecision {
120    /// Go ahead, wait, or give up.
121    pub action: ApplyUpdateActionEnum,
122    /// How long to wait first, in seconds.
123    ///
124    /// This is what staggers a fleet: a hundred lights told to reboot at once is a hundred
125    /// lights dark at once.
126    pub delay_s: u32,
127}
128
129impl ApplyDecision {
130    /// Apply it now.
131    #[must_use]
132    pub const fn proceed() -> Self {
133        Self {
134            action: ApplyUpdateActionEnum::Proceed,
135            delay_s: 0,
136        }
137    }
138
139    /// Wait `delay_s` seconds, then ask again.
140    #[must_use]
141    pub const fn wait(delay_s: u32) -> Self {
142        Self {
143            action: ApplyUpdateActionEnum::AwaitNextAction,
144            delay_s,
145        }
146    }
147
148    /// §11.20.6.4's `Discontinue` — "a desire to rescind a previously provided Software Image".
149    #[must_use]
150    pub const fn discontinue() -> Self {
151        Self {
152            action: ApplyUpdateActionEnum::Discontinue,
153            delay_s: 0,
154        }
155    }
156}
157
158/// What the product knows about the images it has.
159pub trait OtaProviderHooks {
160    /// §11.20.6.5's `QueryImage`: is there something newer for this device?
161    ///
162    /// The whole selection policy — which images exist, which hardware they suit, how a fleet
163    /// is staggered — is the provider's, and none of it is derivable from the cluster.
164    fn query(&self, query: &Query) -> Answer<'_>;
165
166    /// §11.20.6.5's `ApplyUpdateRequest`: the requestor has the image and is ready to reboot.
167    ///
168    /// > The OTA Provider SHALL NOT refer to previously stored state about any download
169    /// > progress to reply.
170    ///
171    /// The default proceeds, which is right for a provider with one device to update and wrong
172    /// for one with a hundred.
173    fn apply(&self, update_token: &[u8], new_version: u32) -> ApplyDecision {
174        let _ = (update_token, new_version);
175        ApplyDecision::proceed()
176    }
177
178    /// §11.20.6.5's `NotifyUpdateApplied` — it worked.
179    ///
180    /// > An OTA Provider SHALL NOT expect every OTA Requestor to invoke this command for
181    /// > correct operation.
182    ///
183    /// A device that updated and then fell off the network never sends it, so a provider that
184    /// waited for one would wait for ever.
185    fn applied(&self, update_token: &[u8], software_version: u32) {
186        let _ = (update_token, software_version);
187    }
188}
189
190/// A `bdx:` image URI (§11.20.6.5).
191///
192/// §11.20.6.5 fixes the syntax hard — exactly 16 uppercase hexadecimal digits for the node id,
193/// no user, no port, no query, no fragment — and then explains why: "the format constraints
194/// simplify the extraction of the necessary data to reach the BDX server". A requestor is
195/// entitled to parse it by position, so a provider that emitted `bdx://99AABBCCDDEE77/...`
196/// with a leading zero dropped would produce a URI the specification's own worked example
197/// calls invalid.
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199pub struct ImageUri<'a> {
200    /// The node to fetch from, which §11.20.6.5 requires to be the provider itself.
201    pub node_id: NodeId,
202    /// The file designator — "the path as received verbatim, after the first '/' following the
203    /// host", with percent-escapes *not* decoded.
204    pub file: &'a str,
205}
206
207impl<'a> ImageUri<'a> {
208    /// The shortest valid `bdx:` URI: `bdx://` plus sixteen digits, a slash and one character.
209    pub const MIN_LEN: usize = 24;
210
211    /// Writes the URI into `buf`, returning the text.
212    ///
213    /// Refuses a file designator that would take the URI past §11.20.6.5's "max 256".
214    pub fn write<'b>(&self, buf: &'b mut [u8]) -> crate::error::Result<&'b str> {
215        let needed = 6usize
216            .saturating_add(16)
217            .saturating_add(1)
218            .saturating_add(self.file.len());
219        if needed > URI_MAX || needed > buf.len() {
220            return Err(crate::Error::new(crate::ErrorCode::BufferTooSmall));
221        }
222        let mut at = 0usize;
223        let mut put = |bytes: &[u8], at: &mut usize| {
224            for byte in bytes {
225                if let Some(slot) = buf.get_mut(*at) {
226                    *slot = *byte;
227                }
228                *at = at.saturating_add(1);
229            }
230        };
231        put(b"bdx://", &mut at);
232        // "exactly 16 characters to encode the network byte order value of the NodeID", in
233        // uppercase — §11.20.6.5's own invalid example is one with the leading zeros omitted.
234        for shift in (0..16u32).rev().map(|nibble| nibble.saturating_mul(4)) {
235            let nibble = u8::try_from((self.node_id.0 >> shift) & 0xF).unwrap_or(0);
236            let digit = match nibble {
237                0..=9 => b'0'.saturating_add(nibble),
238                _ => b'A'.saturating_add(nibble.saturating_sub(10)),
239            };
240            put(&[digit], &mut at);
241        }
242        put(b"/", &mut at);
243        put(self.file.as_bytes(), &mut at);
244        let written = buf
245            .get(..at)
246            .ok_or_else(|| crate::Error::new(crate::ErrorCode::BufferTooSmall))?;
247        core::str::from_utf8(written)
248            .map_err(|_| crate::Error::new(crate::ErrorCode::InvalidArgument))
249    }
250
251    /// Reads §11.20.6.5's `bdx:` form, following its own worked procedure.
252    pub fn parse(uri: &'a str) -> crate::error::Result<Self> {
253        let invalid = || crate::Error::new(crate::ErrorCode::InvalidArgument);
254        if uri.len() < Self::MIN_LEN {
255            return Err(invalid());
256        }
257        let rest = uri.strip_prefix("bdx://").ok_or_else(invalid)?;
258        let (host, file) = rest.split_at_checked(16).ok_or_else(invalid)?;
259        let mut node = 0u64;
260        for byte in host.bytes() {
261            let nibble = match byte {
262                b'0'..=b'9' => byte.saturating_sub(b'0'),
263                // Uppercase only: §11.20.6.5 says "uppercase hexadecimal format", and a
264                // requestor parsing by position has no reason to accept anything else.
265                b'A'..=b'F' => byte.saturating_sub(b'A').saturating_add(10),
266                _ => return Err(invalid()),
267            };
268            node = node
269                .checked_mul(16)
270                .and_then(|n| n.checked_add(u64::from(nibble)))
271                .ok_or_else(invalid)?;
272        }
273        let file = file.strip_prefix('/').ok_or_else(invalid)?;
274        if file.is_empty() || file.contains('?') || file.contains('#') {
275            // "The URI SHALL NOT contain a query field" and "SHALL NOT contain a fragment".
276            return Err(invalid());
277        }
278        Ok(Self {
279            node_id: NodeId(node),
280            file,
281        })
282    }
283}
284
285/// OTA Software Update Provider over a store of images.
286#[derive(Debug)]
287pub struct OtaProvider<'a, H: OtaProviderHooks> {
288    hooks: &'a H,
289}
290
291impl<'a, H: OtaProviderHooks> OtaProvider<'a, H> {
292    /// A provider over `hooks`.
293    #[must_use]
294    pub const fn new(hooks: &'a H) -> Self {
295        Self { hooks }
296    }
297
298    /// The descriptor for an instance, derived from the specification's tables.
299    ///
300    /// §11.20.6.2 puts this cluster's scope at *node*, not endpoint — a provider is a role the
301    /// node plays, not a thing one of its endpoints is.
302    pub fn conforming(
303        feature_map: u32,
304        optional: &Optional<'_>,
305    ) -> crate::error::Result<Conforming<0, 3, 2, 0>> {
306        Conforming::new(&spec_ota::CLUSTER, feature_map, optional)
307    }
308}
309
310impl<H: OtaProviderHooks> ClusterHandler for OtaProvider<'_, H> {
311    fn read(
312        &self,
313        _resolved: &Resolved<'_>,
314        _ctx: &InteractionContext<'_>,
315        _w: &mut TlvWriter<'_>,
316        _tag: Tag,
317    ) -> Result<(), Status> {
318        // §11.20.6 defines no attributes: a provider is all commands. Everything a client
319        // could want to know is the answer to a query it has to make anyway.
320        Err(Status::UnsupportedAttribute)
321    }
322
323    fn invoke(
324        &self,
325        resolved: &ResolvedCommand<'_>,
326        fields: Option<&[u8]>,
327        _ctx: &InteractionContext<'_>,
328        w: &mut TlvWriter<'_>,
329        tag: Tag,
330    ) -> Result<Option<CommandId>, StatusIb> {
331        let payload = || fields.ok_or(StatusIb::from(Status::InvalidCommand));
332        let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
333        match resolved.command.id {
334            QUERY_IMAGE => {
335                let decoded: spec_ota::QueryImageFields<'_> = super::decode_fields(payload()?)?;
336                let mut supports_bdx = false;
337                let mut supports_https = false;
338                for protocol in decoded.protocols_supported.iter() {
339                    // §7.19.2: a protocol this revision does not define is one the provider
340                    // cannot serve, which is not an error in the *request* — the requestor may
341                    // legitimately know a newer one.
342                    match protocol {
343                        Ok(DownloadProtocolEnum::BDXSynchronous)
344                        | Ok(DownloadProtocolEnum::BDXAsynchronous) => supports_bdx = true,
345                        Ok(DownloadProtocolEnum::HTTPS) => supports_https = true,
346                        _ => {}
347                    }
348                }
349                let query = Query {
350                    vendor_id: decoded.vendor_id,
351                    product_id: decoded.product_id,
352                    software_version: decoded.software_version,
353                    hardware_version: decoded.hardware_version,
354                    requestor_can_consent: decoded.requestor_can_consent.unwrap_or(false),
355                    supports_bdx,
356                    supports_https,
357                };
358                let answer = self.hooks.query(&query);
359                let response = Self::response(&answer, &query)?;
360                full(response.to_tlv(w, tag))?;
361                Ok(Some(QUERY_IMAGE_RESPONSE))
362            }
363            APPLY_UPDATE_REQUEST => {
364                let decoded: spec_ota::ApplyUpdateRequestFields<'_> =
365                    super::decode_fields(payload()?)?;
366                // §11.20.6.5's constraint on `UpdateToken` is "8 to 32". A token outside it is
367                // not one this provider ever issued.
368                if !(TOKEN_MIN..=TOKEN_MAX).contains(&decoded.update_token.len()) {
369                    return Err(Status::ConstraintError.into());
370                }
371                let decision = self.hooks.apply(decoded.update_token, decoded.new_version);
372                full(
373                    spec_ota::ApplyUpdateResponseFields {
374                        action: decision.action,
375                        // §11.20.6.5: a requestor "MAY assume a value of 86400" for anything
376                        // larger, so sending more is asking for a delay that will be ignored.
377                        delayed_action_time: decision.delay_s.min(MAX_USEFUL_DELAY_S),
378                    }
379                    .to_tlv(w, tag),
380                )?;
381                Ok(Some(APPLY_UPDATE_RESPONSE))
382            }
383            NOTIFY_UPDATE_APPLIED => {
384                let decoded: spec_ota::NotifyUpdateAppliedFields<'_> =
385                    super::decode_fields(payload()?)?;
386                if !(TOKEN_MIN..=TOKEN_MAX).contains(&decoded.update_token.len()) {
387                    return Err(Status::ConstraintError.into());
388                }
389                self.hooks
390                    .applied(decoded.update_token, decoded.software_version);
391                // §11.20.6.5 gives it no response command: "An OTA Provider receiving an
392                // invocation of this command MAY log it internally", and that is all.
393                Ok(None)
394            }
395            _ => Err(Status::UnsupportedCommand.into()),
396        }
397    }
398}
399
400impl<H: OtaProviderHooks> OtaProvider<'_, H> {
401    /// Builds `QueryImageResponse` from an [`Answer`], enforcing §11.20.6.5's conditional
402    /// conformance.
403    fn response<'r>(
404        answer: &Answer<'r>,
405        query: &Query,
406    ) -> Result<spec_ota::QueryImageResponseFields<'r>, StatusIb> {
407        let empty = spec_ota::QueryImageResponseFields {
408            status: StatusEnum::NotAvailable,
409            delayed_action_time: None,
410            image_uri: None,
411            software_version: None,
412            software_version_string: None,
413            update_token: None,
414            user_consent_needed: None,
415            metadata_for_requestor: None,
416        };
417        Ok(match *answer {
418            Answer::NotAvailable => empty,
419            Answer::ProtocolNotSupported => spec_ota::QueryImageResponseFields {
420                status: StatusEnum::DownloadProtocolNotSupported,
421                ..empty
422            },
423            Answer::Busy { delay_s } => spec_ota::QueryImageResponseFields {
424                status: StatusEnum::Busy,
425                // §11.20.6.5 makes it mandatory for `Busy`: without it the requestor has no
426                // idea when to come back and will hammer the provider.
427                delayed_action_time: Some(delay_s.min(MAX_USEFUL_DELAY_S)),
428                ..empty
429            },
430            Answer::Available {
431                uri,
432                software_version,
433                software_version_string,
434                update_token,
435                user_consent_needed,
436            } => {
437                if uri.len() > URI_MAX
438                    || software_version_string.is_empty()
439                    || software_version_string.len() > VERSION_STRING_MAX
440                    || !(TOKEN_MIN..=TOKEN_MAX).contains(&update_token.len())
441                {
442                    return Err(Status::Failure.into());
443                }
444                // §11.20.3.4: consent may only be demanded of a requestor that said it can
445                // obtain it. Demanding it of one that cannot stalls the update for ever waiting
446                // for a confirmation nothing can give.
447                let consent = user_consent_needed && query.requestor_can_consent;
448                spec_ota::QueryImageResponseFields {
449                    status: StatusEnum::UpdateAvailable,
450                    delayed_action_time: None,
451                    image_uri: Some(uri),
452                    software_version: Some(software_version),
453                    software_version_string: Some(software_version_string),
454                    update_token: Some(update_token),
455                    user_consent_needed: Some(consent),
456                    metadata_for_requestor: None,
457                }
458            }
459        })
460    }
461}
462
463/// So a tuple of clusters can dispatch to it by id.
464impl<H: OtaProviderHooks> Cluster for OtaProvider<'_, H> {
465    const ID: ClusterId = ID;
466}