use std::io::{Read, Seek, SeekFrom};
use anyhow::{Context, bail, ensure};
use flate2::read::ZlibDecoder;
const MAGIC: &[u8; 4] = b"xar!";
const MAX_SIZE: u64 = 16 * 1024 * 1024;
#[derive(Debug, Default, PartialEq)]
struct Entry {
offset: u64,
length: u64,
size: u64,
compressed: bool,
}
pub(crate) fn read_file<R: Read + Seek>(file: &mut R, name: &str) -> anyhow::Result<Vec<u8>> {
file.seek(SeekFrom::Start(0))?;
let mut header = [0u8; 28];
file.read_exact(&mut header)
.context("the file is too short for a xar archive")?;
ensure!(&header[..4] == MAGIC, "not a xar archive");
let header_size = u16::from_be_bytes([header[4], header[5]]) as u64;
let toc_compressed = u64::from_be_bytes(header[8..16].try_into().expect("8 bytes"));
let toc_size = u64::from_be_bytes(header[16..24].try_into().expect("8 bytes"));
ensure!(header_size >= 28, "malformed xar header");
ensure!(
toc_compressed <= MAX_SIZE && toc_size <= MAX_SIZE,
"the xar table of contents is too large"
);
file.seek(SeekFrom::Start(header_size))?;
let mut compressed = vec![0u8; toc_compressed as usize];
file.read_exact(&mut compressed)
.context("read the xar table of contents")?;
let mut toc = String::new();
ZlibDecoder::new(compressed.as_slice())
.take(toc_size)
.read_to_string(&mut toc)
.context("inflate the xar table of contents")?;
let entry = find(&toc, name)?.with_context(|| format!("the archive has no file {name}"))?;
ensure!(
entry.length <= MAX_SIZE && entry.size <= MAX_SIZE,
"{name} is too large"
);
let heap = header_size + toc_compressed;
file.seek(SeekFrom::Start(
heap.checked_add(entry.offset).context("bad xar offset")?,
))?;
let mut data = vec![0u8; entry.length as usize];
file.read_exact(&mut data)
.with_context(|| format!("read {name}"))?;
if !entry.compressed {
return Ok(data);
}
let mut out = Vec::new();
ZlibDecoder::new(data.as_slice())
.take(entry.size)
.read_to_end(&mut out)
.with_context(|| format!("inflate {name}"))?;
Ok(out)
}
fn find(toc: &str, name: &str) -> anyhow::Result<Option<Entry>> {
use quick_xml::events::Event;
let mut reader = quick_xml::Reader::from_str(toc);
let mut path: Vec<String> = Vec::new();
let mut current: Option<(String, Entry)> = None;
let mut found = None;
let mut text = String::new();
loop {
match reader
.read_event()
.context("read the xar table of contents")?
{
Event::Start(e) => {
let tag = e.name().as_ref().to_owned();
encoding(&e, &path, current.as_mut())?;
if tag == "file" && path.len() == 2 {
current = Some((String::new(), Entry::default()));
}
path.push(tag);
text.clear();
}
Event::Empty(e) => encoding(&e, &path, current.as_mut())?,
Event::Text(t) => text.push_str(&t.xml10_content()),
Event::End(_) => {
let tag = path.pop().unwrap_or_default();
let depth = path.len();
if let Some((file_name, entry)) = current.as_mut() {
let value = || text.trim().parse::<u64>();
let in_data = depth == 4 && path[3] == "data";
match (depth, tag.as_str()) {
(3, "name") => *file_name = text.trim().to_owned(),
(4, "offset") if in_data => entry.offset = value()?,
(4, "length") if in_data => entry.length = value()?,
(4, "size") if in_data => entry.size = value()?,
_ => {}
}
}
if depth == 2
&& tag == "file"
&& let Some((file_name, entry)) = current.take()
&& file_name == name
{
found = Some(entry);
}
text.clear();
}
Event::Eof => break,
_ => {}
}
}
Ok(found)
}
fn encoding(
element: &quick_xml::events::BytesStart<'_>,
path: &[String],
current: Option<&mut (String, Entry)>,
) -> anyhow::Result<()> {
if element.name().as_ref() != "encoding" || path.len() != 4 || path[3] != "data" {
return Ok(());
}
let (Some((_, entry)), Some(style)) = (current, element.try_get_attribute("style")?) else {
return Ok(());
};
let style = style.normalized_value(quick_xml::XmlVersion::Implicit1_0)?;
entry.compressed = match style.as_ref() {
"application/x-gzip" => true,
"application/octet-stream" => false,
other => bail!("unsupported xar encoding {other}"),
};
Ok(())
}
#[cfg(test)]
mod tests {
use std::io::{Cursor, Write};
use flate2::{Compression, write::ZlibEncoder};
use super::*;
fn zlib(bytes: &[u8]) -> Vec<u8> {
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
encoder.write_all(bytes).unwrap();
encoder.finish().unwrap()
}
fn archive(distribution: &[u8]) -> Vec<u8> {
let nested = b"nested";
let stored = zlib(distribution);
let toc = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<xar><toc><checksum style="sha1"><offset>0</offset><size>20</size></checksum>
<file id="1"><name>app.pkg</name><type>directory</type>
<file id="2"><name>Distribution</name><type>file</type><data>
<encoding style="application/octet-stream"/><size>6</size><offset>20</offset><length>6</length></data></file>
</file>
<file id="3"><name>Distribution</name><type>file</type>
<ea id="0"><name>com.apple.quarantine</name><offset>9999</offset><size>1</size><length>1</length>
<encoding style="application/octet-stream"/></ea>
<data>
<archived-checksum style="sha1">00</archived-checksum>
<encoding style="application/x-gzip"></encoding><size>{}</size><offset>26</offset><length>{}</length></data></file>
</toc></xar>"#,
distribution.len(),
stored.len()
);
let toc = zlib(toc.as_bytes());
let mut out = Vec::new();
out.extend_from_slice(MAGIC);
out.extend_from_slice(&28u16.to_be_bytes());
out.extend_from_slice(&1u16.to_be_bytes());
out.extend_from_slice(&(toc.len() as u64).to_be_bytes());
out.extend_from_slice(&(10_000u64).to_be_bytes());
out.extend_from_slice(&1u32.to_be_bytes());
out.extend_from_slice(&toc);
out.extend_from_slice(&[0u8; 20]); out.extend_from_slice(nested);
out.extend_from_slice(&stored);
out
}
#[test]
fn reads_a_top_level_file() {
let bytes = archive(b"<installer-gui-script/>");
let read = read_file(&mut Cursor::new(bytes), "Distribution").unwrap();
assert_eq!(read, b"<installer-gui-script/>");
}
#[test]
fn refuses_what_is_not_a_xar_archive_or_lacks_the_file() {
assert!(read_file(&mut Cursor::new(b"PK\x03\x04".to_vec()), "Distribution").is_err());
let bytes = archive(b"x");
let error = read_file(&mut Cursor::new(bytes), "PackageInfo").unwrap_err();
assert_eq!(error.to_string(), "the archive has no file PackageInfo");
}
}