Skip to main content

zigbee_host/
ota.rs

1//! Zigbee OTA upgrade images and a directory of them.
2//!
3//! An OTA file (Zigbee OTA Upgrade cluster specification, section 11.4)
4//! starts with a header naming the manufacturer, image type and file
5//! version; a device downloads the whole file, header included, in blocks.
6//! Some vendors wrap the file in a prefix of their own, so the header is
7//! looked for in the first [`MAX_PREFIX`] bytes.
8//!
9//! [`OtaStore`] indexes a directory of such files by header only and reads
10//! blocks from disk as devices ask for them, so an image never sits in
11//! memory whole.
12
13use std::path::{Path, PathBuf};
14
15use zigbee_primitives::wire::{Reader, Truncated};
16use zigbee_primitives::Ieee;
17
18/// The OTA file identifier.
19pub const MAGIC: u32 = 0x0BEE_F11E;
20/// How far into a file the header may start.
21pub const MAX_PREFIX: usize = 4096;
22/// The largest image accepted.
23pub const MAX_IMAGE: u32 = 16 * 1024 * 1024;
24
25/// The OTA cluster.
26pub const CLUSTER: u16 = 0x0019;
27
28/// OTA cluster command ids.
29pub mod command {
30    /// Server to client: an image may be available.
31    pub const IMAGE_NOTIFY: u8 = 0x00;
32    /// Client to server.
33    pub const QUERY_NEXT_IMAGE_REQUEST: u8 = 0x01;
34    /// Server to client.
35    pub const QUERY_NEXT_IMAGE_RESPONSE: u8 = 0x02;
36    /// Client to server.
37    pub const IMAGE_BLOCK_REQUEST: u8 = 0x03;
38    /// Client to server.
39    pub const IMAGE_PAGE_REQUEST: u8 = 0x04;
40    /// Server to client.
41    pub const IMAGE_BLOCK_RESPONSE: u8 = 0x05;
42    /// Client to server.
43    pub const UPGRADE_END_REQUEST: u8 = 0x06;
44    /// Server to client.
45    pub const UPGRADE_END_RESPONSE: u8 = 0x07;
46}
47
48/// OTA status codes.
49pub mod status {
50    /// Success.
51    pub const SUCCESS: u8 = 0x00;
52    /// Abort the download.
53    pub const ABORT: u8 = 0x95;
54    /// No image for this device.
55    pub const NO_IMAGE_AVAILABLE: u8 = 0x98;
56}
57
58/// An OTA file header.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct OtaHeader {
61    /// Header version (0x0100).
62    pub header_version: u16,
63    /// Header length.
64    pub header_length: u16,
65    /// Field control: which optional fields follow.
66    pub field_control: u16,
67    /// Manufacturer code.
68    pub manufacturer: u16,
69    /// Image type.
70    pub image_type: u16,
71    /// File version.
72    pub file_version: u32,
73    /// Zigbee stack version.
74    pub stack_version: u16,
75    /// Header string (free text).
76    pub header_string: String,
77    /// The whole image's size, header included.
78    pub total_size: u32,
79    /// Only for this device, if set.
80    pub destination: Option<Ieee>,
81    /// Hardware versions it fits, if set.
82    pub hardware: Option<(u16, u16)>,
83}
84
85/// An OTA file did not parse.
86#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
87pub enum OtaError {
88    /// No OTA header in the first [`MAX_PREFIX`] bytes.
89    #[error("no OTA header")]
90    NoHeader,
91    /// The header is cut short.
92    #[error("OTA header: {0}")]
93    Truncated(#[from] Truncated),
94    /// The header's sizes do not add up.
95    #[error("OTA header: {0}")]
96    Invalid(String),
97}
98
99impl OtaHeader {
100    /// Find and parse the header in the start of a file. Returns where the
101    /// image starts (the header's offset) and the header.
102    pub fn find(bytes: &[u8]) -> Result<(usize, OtaHeader), OtaError> {
103        let magic = MAGIC.to_le_bytes();
104        let window = bytes
105            .get(..bytes.len().min(MAX_PREFIX + 4))
106            .unwrap_or(bytes);
107        let start = window
108            .windows(4)
109            .position(|w| w == magic)
110            .ok_or(OtaError::NoHeader)?;
111        let header = OtaHeader::parse(bytes.get(start..).unwrap_or(&[]))?;
112        Ok((start, header))
113    }
114
115    /// Parse a header at the start of `bytes`.
116    pub fn parse(bytes: &[u8]) -> Result<OtaHeader, OtaError> {
117        let mut r = Reader::new(bytes);
118        if r.u32()? != MAGIC {
119            return Err(OtaError::NoHeader);
120        }
121        let header_version = r.u16()?;
122        let header_length = r.u16()?;
123        let field_control = r.u16()?;
124        let manufacturer = r.u16()?;
125        let image_type = r.u16()?;
126        let file_version = r.u32()?;
127        let stack_version = r.u16()?;
128        let header_string = r
129            .bytes(32)?
130            .iter()
131            .take_while(|b| **b != 0)
132            .map(|b| {
133                if b.is_ascii_graphic() || *b == b' ' {
134                    *b as char
135                } else {
136                    '?'
137                }
138            })
139            .collect::<String>()
140            .trim()
141            .to_string();
142        let total_size = r.u32()?;
143        if field_control & 0x0001 != 0 {
144            let _security_credential_version = r.u8()?;
145        }
146        let destination = if field_control & 0x0002 != 0 {
147            Some(r.ieee()?)
148        } else {
149            None
150        };
151        let hardware = if field_control & 0x0004 != 0 {
152            Some((r.u16()?, r.u16()?))
153        } else {
154            None
155        };
156        if usize::from(header_length) < r.position() {
157            return Err(OtaError::Invalid(format!(
158                "header length {header_length} is shorter than its fields"
159            )));
160        }
161        if total_size < u32::from(header_length) || total_size > MAX_IMAGE {
162            return Err(OtaError::Invalid(format!("image size {total_size}")));
163        }
164        Ok(OtaHeader {
165            header_version,
166            header_length,
167            field_control,
168            manufacturer,
169            image_type,
170            file_version,
171            stack_version,
172            header_string,
173            total_size,
174            destination,
175            hardware,
176        })
177    }
178
179    /// Whether this image is for a device with this identity.
180    pub fn fits(
181        &self,
182        manufacturer: u16,
183        image_type: u16,
184        hardware: Option<u16>,
185        ieee: Ieee,
186    ) -> bool {
187        self.manufacturer == manufacturer
188            && self.image_type == image_type
189            && self.destination.is_none_or(|d| d == ieee)
190            && match (self.hardware, hardware) {
191                (Some((min, max)), Some(hw)) => (min..=max).contains(&hw),
192                _ => true,
193            }
194    }
195}
196
197/// One image file in the store.
198#[derive(Debug, Clone, PartialEq, Eq)]
199pub struct OtaImage {
200    /// Its header.
201    pub header: OtaHeader,
202    /// The file.
203    pub path: PathBuf,
204    /// Where the image starts in the file (after any vendor prefix).
205    pub offset: u64,
206}
207
208impl OtaImage {
209    /// Read an image file's header.
210    pub fn open(path: &Path) -> std::io::Result<Result<OtaImage, OtaError>> {
211        use std::io::Read;
212        let mut head = Vec::with_capacity(MAX_PREFIX + 128);
213        std::fs::File::open(path)?
214            .take((MAX_PREFIX + 128) as u64)
215            .read_to_end(&mut head)?;
216        let len = std::fs::metadata(path)?.len();
217        Ok(OtaHeader::find(&head).and_then(|(offset, header)| {
218            if offset as u64 + u64::from(header.total_size) > len {
219                return Err(OtaError::Invalid(format!(
220                    "the file is shorter than its image size {}",
221                    header.total_size
222                )));
223            }
224            Ok(OtaImage {
225                header,
226                path: path.to_path_buf(),
227                offset: offset as u64,
228            })
229        }))
230    }
231
232    /// Read `len` bytes of the image at `offset` (cut at the image's end).
233    pub async fn read(&self, offset: u32, len: usize) -> std::io::Result<Vec<u8>> {
234        use tokio::io::{AsyncReadExt, AsyncSeekExt};
235        let end = self
236            .header
237            .total_size
238            .min(offset.saturating_add(len as u32));
239        let n = end.saturating_sub(offset) as usize;
240        let mut file = tokio::fs::File::open(&self.path).await?;
241        file.seek(std::io::SeekFrom::Start(self.offset + u64::from(offset)))
242            .await?;
243        let mut buf = vec![0u8; n];
244        file.read_exact(&mut buf).await?;
245        Ok(buf)
246    }
247}
248
249/// A directory of OTA files (`*.ota`, `*.zigbee`, `*.bin`, `*.ota.signed`,
250/// or anything else with an OTA header).
251#[derive(Debug, Clone)]
252pub struct OtaStore {
253    dir: PathBuf,
254}
255
256impl OtaStore {
257    /// A store over `dir`.
258    pub fn new(dir: impl Into<PathBuf>) -> OtaStore {
259        OtaStore { dir: dir.into() }
260    }
261
262    /// The directory.
263    pub fn dir(&self) -> &Path {
264        &self.dir
265    }
266
267    /// Every image in the directory. Files that are not OTA images are
268    /// skipped.
269    pub fn images(&self) -> Vec<OtaImage> {
270        let Ok(entries) = std::fs::read_dir(&self.dir) else {
271            return Vec::new();
272        };
273        entries
274            .filter_map(Result::ok)
275            .filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
276            .filter_map(|e| match OtaImage::open(&e.path()) {
277                Ok(Ok(image)) => Some(image),
278                Ok(Err(err)) => {
279                    tracing::debug!(path = %e.path().display(), error = %err, "not an OTA image");
280                    None
281                }
282                Err(err) => {
283                    tracing::warn!(path = %e.path().display(), error = %err, "reading an OTA image");
284                    None
285                }
286            })
287            .collect()
288    }
289
290    /// The newest image for a device newer than `current`.
291    pub fn newer(
292        &self,
293        manufacturer: u16,
294        image_type: u16,
295        current: u32,
296        hardware: Option<u16>,
297        ieee: Ieee,
298    ) -> Option<OtaImage> {
299        self.images()
300            .into_iter()
301            .filter(|i| i.header.fits(manufacturer, image_type, hardware, ieee))
302            .filter(|i| i.header.file_version > current)
303            .max_by_key(|i| i.header.file_version)
304    }
305}
306
307/// Build an OTA file: a header for `manufacturer`, `image_type` and
308/// `file_version`, then `body`. For tests and tools.
309pub fn build(manufacturer: u16, image_type: u16, file_version: u32, body: &[u8]) -> Vec<u8> {
310    let header_length: u16 = 56;
311    let total = u32::from(header_length) + body.len() as u32;
312    let mut out = Vec::with_capacity(total as usize);
313    out.extend_from_slice(&MAGIC.to_le_bytes());
314    out.extend_from_slice(&0x0100u16.to_le_bytes());
315    out.extend_from_slice(&header_length.to_le_bytes());
316    out.extend_from_slice(&0u16.to_le_bytes());
317    out.extend_from_slice(&manufacturer.to_le_bytes());
318    out.extend_from_slice(&image_type.to_le_bytes());
319    out.extend_from_slice(&file_version.to_le_bytes());
320    out.extend_from_slice(&2u16.to_le_bytes());
321    let mut text = [0u8; 32];
322    for (d, s) in text.iter_mut().zip(b"zigbee-bridge test image") {
323        *d = *s;
324    }
325    out.extend_from_slice(&text);
326    out.extend_from_slice(&total.to_le_bytes());
327    out.extend_from_slice(body);
328    out
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334
335    #[test]
336    fn finds_a_header_after_a_vendor_prefix() {
337        let image = build(0x1234, 7, 0x0102_0304, &[9; 100]);
338        let mut file = vec![0xAA; 70];
339        file.extend_from_slice(&image);
340        let (offset, h) = OtaHeader::find(&file).unwrap();
341        assert_eq!(offset, 70);
342        assert_eq!(
343            (h.manufacturer, h.image_type, h.file_version),
344            (0x1234, 7, 0x0102_0304)
345        );
346        assert_eq!(h.total_size, 156);
347        assert_eq!(h.header_string, "zigbee-bridge test image");
348        assert!(h.fits(0x1234, 7, Some(3), Ieee(1)));
349        assert!(!h.fits(0x1234, 8, None, Ieee(1)));
350    }
351
352    #[test]
353    fn rejects_bad_headers() {
354        assert_eq!(OtaHeader::find(&[0; 64]), Err(OtaError::NoHeader));
355        let mut image = build(1, 1, 1, &[]);
356        image[52..56].copy_from_slice(&10u32.to_le_bytes());
357        assert!(matches!(
358            OtaHeader::parse(&image),
359            Err(OtaError::Invalid(_))
360        ));
361        assert!(OtaHeader::parse(&image[..20]).is_err());
362    }
363}