use std::path::{Path, PathBuf};
use zigbee_primitives::wire::{Reader, Truncated};
use zigbee_primitives::Ieee;
pub const MAGIC: u32 = 0x0BEE_F11E;
pub const MAX_PREFIX: usize = 4096;
pub const MAX_IMAGE: u32 = 16 * 1024 * 1024;
pub const CLUSTER: u16 = 0x0019;
pub mod command {
pub const IMAGE_NOTIFY: u8 = 0x00;
pub const QUERY_NEXT_IMAGE_REQUEST: u8 = 0x01;
pub const QUERY_NEXT_IMAGE_RESPONSE: u8 = 0x02;
pub const IMAGE_BLOCK_REQUEST: u8 = 0x03;
pub const IMAGE_PAGE_REQUEST: u8 = 0x04;
pub const IMAGE_BLOCK_RESPONSE: u8 = 0x05;
pub const UPGRADE_END_REQUEST: u8 = 0x06;
pub const UPGRADE_END_RESPONSE: u8 = 0x07;
}
pub mod status {
pub const SUCCESS: u8 = 0x00;
pub const ABORT: u8 = 0x95;
pub const NO_IMAGE_AVAILABLE: u8 = 0x98;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OtaHeader {
pub header_version: u16,
pub header_length: u16,
pub field_control: u16,
pub manufacturer: u16,
pub image_type: u16,
pub file_version: u32,
pub stack_version: u16,
pub header_string: String,
pub total_size: u32,
pub destination: Option<Ieee>,
pub hardware: Option<(u16, u16)>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum OtaError {
#[error("no OTA header")]
NoHeader,
#[error("OTA header: {0}")]
Truncated(#[from] Truncated),
#[error("OTA header: {0}")]
Invalid(String),
}
impl OtaHeader {
pub fn find(bytes: &[u8]) -> Result<(usize, OtaHeader), OtaError> {
let magic = MAGIC.to_le_bytes();
let window = bytes
.get(..bytes.len().min(MAX_PREFIX + 4))
.unwrap_or(bytes);
let start = window
.windows(4)
.position(|w| w == magic)
.ok_or(OtaError::NoHeader)?;
let header = OtaHeader::parse(bytes.get(start..).unwrap_or(&[]))?;
Ok((start, header))
}
pub fn parse(bytes: &[u8]) -> Result<OtaHeader, OtaError> {
let mut r = Reader::new(bytes);
if r.u32()? != MAGIC {
return Err(OtaError::NoHeader);
}
let header_version = r.u16()?;
let header_length = r.u16()?;
let field_control = r.u16()?;
let manufacturer = r.u16()?;
let image_type = r.u16()?;
let file_version = r.u32()?;
let stack_version = r.u16()?;
let header_string = r
.bytes(32)?
.iter()
.take_while(|b| **b != 0)
.map(|b| {
if b.is_ascii_graphic() || *b == b' ' {
*b as char
} else {
'?'
}
})
.collect::<String>()
.trim()
.to_string();
let total_size = r.u32()?;
if field_control & 0x0001 != 0 {
let _security_credential_version = r.u8()?;
}
let destination = if field_control & 0x0002 != 0 {
Some(r.ieee()?)
} else {
None
};
let hardware = if field_control & 0x0004 != 0 {
Some((r.u16()?, r.u16()?))
} else {
None
};
if usize::from(header_length) < r.position() {
return Err(OtaError::Invalid(format!(
"header length {header_length} is shorter than its fields"
)));
}
if total_size < u32::from(header_length) || total_size > MAX_IMAGE {
return Err(OtaError::Invalid(format!("image size {total_size}")));
}
Ok(OtaHeader {
header_version,
header_length,
field_control,
manufacturer,
image_type,
file_version,
stack_version,
header_string,
total_size,
destination,
hardware,
})
}
pub fn fits(
&self,
manufacturer: u16,
image_type: u16,
hardware: Option<u16>,
ieee: Ieee,
) -> bool {
self.manufacturer == manufacturer
&& self.image_type == image_type
&& self.destination.is_none_or(|d| d == ieee)
&& match (self.hardware, hardware) {
(Some((min, max)), Some(hw)) => (min..=max).contains(&hw),
_ => true,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OtaImage {
pub header: OtaHeader,
pub path: PathBuf,
pub offset: u64,
}
impl OtaImage {
pub fn open(path: &Path) -> std::io::Result<Result<OtaImage, OtaError>> {
use std::io::Read;
let mut head = Vec::with_capacity(MAX_PREFIX + 128);
std::fs::File::open(path)?
.take((MAX_PREFIX + 128) as u64)
.read_to_end(&mut head)?;
let len = std::fs::metadata(path)?.len();
Ok(OtaHeader::find(&head).and_then(|(offset, header)| {
if offset as u64 + u64::from(header.total_size) > len {
return Err(OtaError::Invalid(format!(
"the file is shorter than its image size {}",
header.total_size
)));
}
Ok(OtaImage {
header,
path: path.to_path_buf(),
offset: offset as u64,
})
}))
}
pub async fn read(&self, offset: u32, len: usize) -> std::io::Result<Vec<u8>> {
use tokio::io::{AsyncReadExt, AsyncSeekExt};
let end = self
.header
.total_size
.min(offset.saturating_add(len as u32));
let n = end.saturating_sub(offset) as usize;
let mut file = tokio::fs::File::open(&self.path).await?;
file.seek(std::io::SeekFrom::Start(self.offset + u64::from(offset)))
.await?;
let mut buf = vec![0u8; n];
file.read_exact(&mut buf).await?;
Ok(buf)
}
}
#[derive(Debug, Clone)]
pub struct OtaStore {
dir: PathBuf,
}
impl OtaStore {
pub fn new(dir: impl Into<PathBuf>) -> OtaStore {
OtaStore { dir: dir.into() }
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn images(&self) -> Vec<OtaImage> {
let Ok(entries) = std::fs::read_dir(&self.dir) else {
return Vec::new();
};
entries
.filter_map(Result::ok)
.filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
.filter_map(|e| match OtaImage::open(&e.path()) {
Ok(Ok(image)) => Some(image),
Ok(Err(err)) => {
tracing::debug!(path = %e.path().display(), error = %err, "not an OTA image");
None
}
Err(err) => {
tracing::warn!(path = %e.path().display(), error = %err, "reading an OTA image");
None
}
})
.collect()
}
pub fn newer(
&self,
manufacturer: u16,
image_type: u16,
current: u32,
hardware: Option<u16>,
ieee: Ieee,
) -> Option<OtaImage> {
self.images()
.into_iter()
.filter(|i| i.header.fits(manufacturer, image_type, hardware, ieee))
.filter(|i| i.header.file_version > current)
.max_by_key(|i| i.header.file_version)
}
}
pub fn build(manufacturer: u16, image_type: u16, file_version: u32, body: &[u8]) -> Vec<u8> {
let header_length: u16 = 56;
let total = u32::from(header_length) + body.len() as u32;
let mut out = Vec::with_capacity(total as usize);
out.extend_from_slice(&MAGIC.to_le_bytes());
out.extend_from_slice(&0x0100u16.to_le_bytes());
out.extend_from_slice(&header_length.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&manufacturer.to_le_bytes());
out.extend_from_slice(&image_type.to_le_bytes());
out.extend_from_slice(&file_version.to_le_bytes());
out.extend_from_slice(&2u16.to_le_bytes());
let mut text = [0u8; 32];
for (d, s) in text.iter_mut().zip(b"zigbee-bridge test image") {
*d = *s;
}
out.extend_from_slice(&text);
out.extend_from_slice(&total.to_le_bytes());
out.extend_from_slice(body);
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_a_header_after_a_vendor_prefix() {
let image = build(0x1234, 7, 0x0102_0304, &[9; 100]);
let mut file = vec![0xAA; 70];
file.extend_from_slice(&image);
let (offset, h) = OtaHeader::find(&file).unwrap();
assert_eq!(offset, 70);
assert_eq!(
(h.manufacturer, h.image_type, h.file_version),
(0x1234, 7, 0x0102_0304)
);
assert_eq!(h.total_size, 156);
assert_eq!(h.header_string, "zigbee-bridge test image");
assert!(h.fits(0x1234, 7, Some(3), Ieee(1)));
assert!(!h.fits(0x1234, 8, None, Ieee(1)));
}
#[test]
fn rejects_bad_headers() {
assert_eq!(OtaHeader::find(&[0; 64]), Err(OtaError::NoHeader));
let mut image = build(1, 1, 1, &[]);
image[52..56].copy_from_slice(&10u32.to_le_bytes());
assert!(matches!(
OtaHeader::parse(&image),
Err(OtaError::Invalid(_))
));
assert!(OtaHeader::parse(&image[..20]).is_err());
}
}