use std::fmt;
use crate::error::{Error, Result};
use super::reader::{read_bytes, slice};
const DER_SEQUENCE: u8 = 0x30;
const DER_IA5_STRING: u8 = 0x16;
const DER_OCTET_STRING: u8 = 0x04;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Container {
Img4,
Im4p,
}
impl fmt::Display for Container {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Img4 => "IMG4",
Self::Im4p => "IM4P",
})
}
}
pub(super) fn unwrap(data: &[u8]) -> Result<Option<(Container, &[u8])>> {
if data.first() != Some(&DER_SEQUENCE) {
return Ok(None);
}
let (name, fields) = open_sequence(data)?;
match name {
b"IMG4" => {
let im4p = Tlv::parse(fields)?;
let (name, fields) = open_sequence(im4p.encoded)?;
if name != b"IM4P" {
return Err(Error::parse(0, "expected IMG4 or IM4P identifier"));
}
Ok(Some((Container::Img4, im4p_payload(fields)?)))
}
b"IM4P" => Ok(Some((Container::Im4p, im4p_payload(fields)?))),
_ => Err(Error::parse(0, "expected IMG4 or IM4P identifier")),
}
}
fn open_sequence(data: &[u8]) -> Result<(&[u8], &[u8])> {
let sequence = Tlv::parse(data)?;
if sequence.tag != DER_SEQUENCE || !sequence.rest.is_empty() {
return Err(Error::parse(0, "expected IMG4 or IM4P DER sequence"));
}
let name = Tlv::parse(sequence.value)?;
if name.tag != DER_IA5_STRING {
return Err(Error::parse(0, "missing IMG4/IM4P identifier"));
}
Ok((name.value, name.rest))
}
fn im4p_payload(fields: &[u8]) -> Result<&[u8]> {
let kind = Tlv::parse(fields)?;
if kind.tag != DER_IA5_STRING || !matches!(kind.value, b"krnl" | b"rkrn") {
return Err(Error::parse(0, "IM4P payload is not a kernel (krnl/rkrn)"));
}
let description = Tlv::parse(kind.rest)?;
if description.tag != DER_IA5_STRING {
return Err(Error::parse(0, "missing IM4P description"));
}
let payload = Tlv::parse(description.rest)?;
if payload.tag != DER_OCTET_STRING {
return Err(Error::parse(0, "missing IM4P payload octet string"));
}
Ok(payload.value)
}
struct Tlv<'a> {
tag: u8,
value: &'a [u8],
encoded: &'a [u8],
rest: &'a [u8],
}
impl<'a> Tlv<'a> {
fn parse(data: &'a [u8]) -> Result<Self> {
let [tag, length] = read_bytes(data, 0)?;
let (len, value_start) = if length & 0x80 == 0 {
(usize::from(length), 2)
} else {
let count = usize::from(length & 0x7f);
if !(1..=4).contains(&count) {
return Err(Error::parse(1, "unsupported DER length"));
}
let len = slice(data, 2, count)?
.iter()
.fold(0, |len, &byte| (len << 8) | usize::from(byte));
(len, 2 + count)
};
let value = slice(data, value_start, len)?;
let end = value_start + len;
Ok(Self {
tag,
value,
encoded: &data[..end],
rest: &data[end..],
})
}
}