1use std::io::{Read, Seek, SeekFrom};
10use std::path::{Path, PathBuf};
11
12use rs_matter::clusters::ota_prov::{
13 OtaApplyOutcome, OtaImageMeta, OtaImages, OtaImagesRegistry, OtaQueryOutcome, OtaRequestorId,
14};
15use rs_matter::error::{Error as MatterError, ErrorCode};
16use rs_matter::ota::OtaImageHeader;
17use serde::Serialize;
18
19use crate::controller::EventBus;
20use crate::{Event, OtaStep};
21
22const MAX_HEADER: u64 = 1024;
25
26const MAX_NAME: usize = 96;
29
30#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
32pub struct OtaImage {
33 pub file: String,
35 pub vendor_id: u16,
37 pub product_id: u16,
39 pub version: u32,
41 pub version_str: String,
43 #[serde(skip_serializing_if = "Option::is_none")]
45 pub min_applicable_version: Option<u32>,
46 #[serde(skip_serializing_if = "Option::is_none")]
48 pub max_applicable_version: Option<u32>,
49 pub size: u64,
51 #[serde(skip)]
52 digest: Vec<u8>,
53}
54
55impl OtaImage {
56 pub fn is_update_for(&self, vendor_id: u16, product_id: u16, version: u32) -> bool {
59 (self.vendor_id == 0 || self.vendor_id == vendor_id)
60 && (self.product_id == 0 || self.product_id == product_id)
61 && self.version > version
62 && self.min_applicable_version.is_none_or(|v| version >= v)
63 && self.max_applicable_version.is_none_or(|v| version <= v)
64 }
65
66 fn update_token(&self) -> Vec<u8> {
69 let mut token = self.version.to_be_bytes().to_vec();
70 token.extend(self.digest.iter().take(12));
71 token.resize(token.len().max(8), 0);
72 token
73 }
74}
75
76fn valid_name(name: &str) -> bool {
79 !name.is_empty()
80 && name.len() <= MAX_NAME
81 && !name.starts_with('.')
82 && name
83 .bytes()
84 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
85}
86
87fn read_image(path: &Path) -> Option<OtaImage> {
90 let file = path.file_name()?.to_str()?.to_string();
91 if !valid_name(&file) {
92 return None;
93 }
94 let f = std::fs::File::open(path).ok()?;
95 let size = f.metadata().ok()?.len();
96 let mut head = Vec::new();
97 f.take(MAX_HEADER).read_to_end(&mut head).ok()?;
98 let (header, payload_offset) = OtaImageHeader::decode(&head).ok()?;
99 if (payload_offset as u64).checked_add(header.payload_size) != Some(size) {
100 return None;
101 }
102 Some(OtaImage {
103 file,
104 vendor_id: header.vendor_id,
105 product_id: header.product_id,
106 version: header.software_version,
107 version_str: header.software_version_str.to_string(),
108 min_applicable_version: header.min_applicable_software_version,
109 max_applicable_version: header.max_applicable_software_version,
110 size,
111 digest: header.image_digest.0.to_vec(),
112 })
113}
114
115pub fn list(dir: &Path) -> Result<Vec<OtaImage>, crate::Error> {
118 let mut images: Vec<OtaImage> = match std::fs::read_dir(dir) {
119 Ok(entries) => entries
120 .filter_map(|e| e.ok())
121 .filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
122 .filter_map(|e| read_image(&e.path()))
123 .collect(),
124 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
125 Err(e) => return Err(e.into()),
126 };
127 images.sort_by(|a, b| a.file.cmp(&b.file));
128 Ok(images)
129}
130
131pub fn best(
134 images: &[OtaImage],
135 vendor_id: u16,
136 product_id: u16,
137 version: u32,
138) -> Option<&OtaImage> {
139 images
140 .iter()
141 .filter(|i| i.is_update_for(vendor_id, product_id, version))
142 .max_by_key(|i| i.version)
143}
144
145pub(crate) struct OtaDir {
147 dir: PathBuf,
148 events: EventBus,
149}
150
151impl OtaDir {
152 pub(crate) fn new(dir: PathBuf, events: EventBus) -> Self {
153 Self { dir, events }
154 }
155
156 fn path(&self, designator: &[u8]) -> Option<PathBuf> {
157 let name = std::str::from_utf8(designator).ok()?;
158 valid_name(name).then(|| self.dir.join(name))
159 }
160}
161
162fn lend<'b>(buf: &'b mut [u8], bytes: &[u8]) -> Option<(&'b [u8], &'b mut [u8])> {
164 let (head, rest) = buf.split_at_mut_checked(bytes.len())?;
165 head.copy_from_slice(bytes);
166 Some((head, rest))
167}
168
169impl OtaImagesRegistry for OtaDir {
170 async fn query<'b>(
171 &self,
172 requestor: OtaRequestorId,
173 vendor_id: u16,
174 product_id: u16,
175 current_version: u32,
176 _requestor_can_consent: bool,
177 buf: &'b mut [u8],
178 ) -> OtaQueryOutcome<'b> {
179 let images = match list(&self.dir) {
180 Ok(images) => images,
181 Err(e) => {
182 log::warn!("OTA: cannot list {}: {e}", self.dir.display());
183 return OtaQueryOutcome::NotAvailable;
184 }
185 };
186 let Some(image) = best(&images, vendor_id, product_id, current_version) else {
187 log::debug!(
188 "OTA: nothing newer than {current_version} for node {:016X} ({vendor_id:#06x}/{product_id:#06x})",
189 requestor.node_id
190 );
191 return OtaQueryOutcome::NotAvailable;
192 };
193
194 let token = image.update_token();
195 let lent = lend(buf, image.version_str.as_bytes()).and_then(|(version_str, buf)| {
196 let (file, buf) = lend(buf, image.file.as_bytes())?;
197 let (token, _) = lend(buf, &token)?;
198 Some((version_str, file, token))
199 });
200 let Some((Ok(version_str), Ok(file_designator), update_token)) =
202 lent.map(|(v, f, t)| (std::str::from_utf8(v), std::str::from_utf8(f), t))
203 else {
204 log::warn!("OTA: {} does not fit an offer", image.file);
205 return OtaQueryOutcome::NotAvailable;
206 };
207
208 log::info!(
209 "OTA: offering {} ({}) to node {:016X}",
210 image.file,
211 image.version_str,
212 requestor.node_id
213 );
214 self.events.send(Event::Ota {
215 node: requestor.node_id,
216 step: OtaStep::Offered,
217 version: image.version,
218 });
219 OtaQueryOutcome::Available(OtaImageMeta {
220 version: image.version,
221 version_str,
222 file_designator,
223 update_token,
224 user_consent_needed: false,
225 })
226 }
227
228 async fn apply(
229 &self,
230 requestor: OtaRequestorId,
231 _update_token: &[u8],
232 new_version: u32,
233 ) -> OtaApplyOutcome {
234 self.events.send(Event::Ota {
235 node: requestor.node_id,
236 step: OtaStep::Applying,
237 version: new_version,
238 });
239 OtaApplyOutcome::Proceed { delay_secs: 0 }
240 }
241
242 async fn applied(
243 &self,
244 requestor: OtaRequestorId,
245 _update_token: &[u8],
246 software_version: u32,
247 ) {
248 self.events.send(Event::Ota {
249 node: requestor.node_id,
250 step: OtaStep::Applied,
251 version: software_version,
252 });
253 }
254}
255
256impl OtaImages for OtaDir {
257 async fn size(&self, designator: &[u8]) -> Option<u64> {
258 let path = self.path(designator)?;
259 read_image(&path).map(|i| i.size)
260 }
261
262 async fn read(
263 &self,
264 designator: &[u8],
265 offset: u64,
266 buf: &mut [u8],
267 ) -> Result<usize, MatterError> {
268 let path = self.path(designator).ok_or(ErrorCode::NotFound)?;
269 let mut f = std::fs::File::open(path).map_err(|_| ErrorCode::NotFound)?;
270 f.seek(SeekFrom::Start(offset))
271 .map_err(|_| ErrorCode::Invalid)?;
272 Ok(f.read(buf).map_err(|_| ErrorCode::Invalid)?)
273 }
274}
275
276#[cfg(test)]
277mod tests {
278 use super::*;
279 use rs_matter::ota::OTA_IMAGE_DIGEST_SHA256;
280 use rs_matter::tlv::OctetStr;
281
282 pub(crate) fn image(vid: u16, pid: u16, version: u32, payload: &[u8]) -> Vec<u8> {
284 let version_str = format!("v{version}");
285 let digest = [0xA5u8; 32];
286 let header = OtaImageHeader {
287 vendor_id: vid,
288 product_id: pid,
289 software_version: version,
290 software_version_str: &version_str,
291 payload_size: payload.len() as u64,
292 min_applicable_software_version: None,
293 max_applicable_software_version: None,
294 release_notes_url: None,
295 image_digest_type: OTA_IMAGE_DIGEST_SHA256,
296 image_digest: OctetStr::new(&digest),
297 };
298 let mut buf = vec![0; 512];
299 let n = header.encode(&mut buf).unwrap();
300 buf.truncate(n);
301 buf.extend_from_slice(payload);
302 buf
303 }
304
305 #[test]
306 fn picks_the_newest_applicable_image() {
307 let dir = tempfile::tempdir().unwrap();
308 std::fs::write(dir.path().join("a-2.ota"), image(0xFFF1, 0x8001, 2, b"two")).unwrap();
309 std::fs::write(
310 dir.path().join("a-3.ota"),
311 image(0xFFF1, 0x8001, 3, b"three"),
312 )
313 .unwrap();
314 std::fs::write(
315 dir.path().join("b-9.ota"),
316 image(0xFFF1, 0x8002, 9, b"other"),
317 )
318 .unwrap();
319 std::fs::write(dir.path().join("notes.txt"), b"not an image").unwrap();
320 let mut truncated = image(0xFFF1, 0x8001, 4, b"four");
321 truncated.pop();
322 std::fs::write(dir.path().join("a-4.ota"), truncated).unwrap();
323
324 let images = list(dir.path()).unwrap();
325 assert_eq!(
326 images.iter().map(|i| i.file.as_str()).collect::<Vec<_>>(),
327 ["a-2.ota", "a-3.ota", "b-9.ota"]
328 );
329 assert_eq!(best(&images, 0xFFF1, 0x8001, 1).unwrap().file, "a-3.ota");
330 assert_eq!(best(&images, 0xFFF1, 0x8001, 3), None);
331 assert_eq!(best(&images, 0xFFF2, 0x8001, 1), None);
332 let token = images[1].update_token();
333 assert!((8..=32).contains(&token.len()));
334 }
335
336 #[test]
337 fn designators_stay_in_the_directory() {
338 for bad in [
339 "",
340 "../x.ota",
341 "a/b.ota",
342 ".hidden",
343 "a b.ota",
344 &"x".repeat(MAX_NAME + 1),
345 ] {
346 assert!(!valid_name(bad), "{bad:?}");
347 }
348 assert!(valid_name("light-1.2.3_rc1.ota"));
349 }
350}