use crate::core::decoder::{DecompressOptions, decompress_with_options};
use crate::core::encoder::{CompressOptions, compress};
use crate::{Error, Result};
use std::path::{Path, PathBuf};
pub const ARCHIVE_MAGIC: [u8; 4] = *b"ZEXA";
pub const ARCHIVE_VERSION: u16 = 1;
#[derive(Debug, Clone)]
pub struct ArchiveEntry {
pub name: String,
pub data: Vec<u8>,
}
pub fn create_archive(entries: &[ArchiveEntry], opts: &CompressOptions) -> Result<Vec<u8>> {
if entries.len() > u32::MAX as usize {
return Err(Error::InvalidParameter("too many archive entries".into()));
}
let mut out = Vec::new();
out.extend_from_slice(&ARCHIVE_MAGIC);
out.extend_from_slice(&ARCHIVE_VERSION.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(&(entries.len() as u32).to_le_bytes());
for e in entries {
if e.name.is_empty() || e.name.contains('\0') {
return Err(Error::InvalidParameter(format!(
"bad entry name {:?}",
e.name
)));
}
if e.name.len() > u16::MAX as usize {
return Err(Error::InvalidParameter("entry name too long".into()));
}
let frame = compress(&e.data, opts)?;
out.extend_from_slice(&(e.name.len() as u16).to_le_bytes());
out.extend_from_slice(e.name.as_bytes());
out.extend_from_slice(&(e.data.len() as u64).to_le_bytes());
out.extend_from_slice(&(frame.len() as u64).to_le_bytes());
out.extend_from_slice(&frame);
}
Ok(out)
}
#[derive(Debug, Clone)]
pub struct ArchiveListItem {
pub name: String,
pub uncompressed_size: u64,
pub frame_size: u64,
}
pub fn list_archive(data: &[u8]) -> Result<Vec<ArchiveListItem>> {
let mut ip = 0usize;
parse_header(data, &mut ip)?;
let count = read_u32(data, &mut ip)? as usize;
let mut items = Vec::with_capacity(count);
for _ in 0..count {
let name = read_name(data, &mut ip)?;
let unc = read_u64(data, &mut ip)?;
let flen = read_u64(data, &mut ip)?;
if ip + flen as usize > data.len() {
return Err(Error::CorruptBlock("archive frame truncated".into()));
}
ip += flen as usize;
items.push(ArchiveListItem {
name,
uncompressed_size: unc,
frame_size: flen,
});
}
Ok(items)
}
pub fn extract_archive(data: &[u8], dopts: &DecompressOptions) -> Result<Vec<ArchiveEntry>> {
let mut ip = 0usize;
parse_header(data, &mut ip)?;
let count = read_u32(data, &mut ip)? as usize;
let mut entries = Vec::with_capacity(count);
for _ in 0..count {
let name = read_name(data, &mut ip)?;
let unc = read_u64(data, &mut ip)?;
let flen = read_u64(data, &mut ip)? as usize;
if ip + flen > data.len() {
return Err(Error::CorruptBlock("archive frame truncated".into()));
}
let frame = &data[ip..ip + flen];
ip += flen;
let plain = decompress_with_options(frame, dopts)?;
if plain.len() as u64 != unc {
return Err(Error::SizeMismatch {
expected: unc,
actual: plain.len() as u64,
});
}
entries.push(ArchiveEntry { name, data: plain });
}
Ok(entries)
}
pub fn create_from_paths(paths: &[PathBuf], opts: &CompressOptions) -> Result<Vec<u8>> {
let mut entries = Vec::new();
for p in paths {
let data = std::fs::read(p).map_err(Error::Io)?;
let name = p
.file_name()
.and_then(|s| s.to_str())
.ok_or_else(|| Error::InvalidParameter(format!("bad path {}", p.display())))?
.to_string();
entries.push(ArchiveEntry { name, data });
}
create_archive(&entries, opts)
}
pub fn extract_to_dir(data: &[u8], dest: &Path, dopts: &DecompressOptions) -> Result<Vec<String>> {
std::fs::create_dir_all(dest).map_err(Error::Io)?;
let entries = extract_archive(data, dopts)?;
let mut names = Vec::new();
for e in entries {
let safe = sanitize_name(&e.name)?;
let out_path = dest.join(&safe);
if let Some(parent) = out_path.parent() {
std::fs::create_dir_all(parent).map_err(Error::Io)?;
}
std::fs::write(&out_path, &e.data).map_err(Error::Io)?;
names.push(safe);
}
Ok(names)
}
fn sanitize_name(name: &str) -> Result<String> {
if name.is_empty() || name.contains('\0') {
return Err(Error::InvalidParameter("empty archive name".into()));
}
if name.contains("..") || name.starts_with('/') || name.starts_with('\\') {
return Err(Error::InvalidParameter(format!(
"refusing unsafe archive path {name:?}"
)));
}
let p = Path::new(name);
if p.is_absolute() {
return Err(Error::InvalidParameter("absolute paths not allowed".into()));
}
Ok(name.replace('\\', "/"))
}
fn parse_header(data: &[u8], ip: &mut usize) -> Result<()> {
if data.len() < 12 {
return Err(Error::InvalidHeader("archive too short".into()));
}
if data[*ip..*ip + 4] != ARCHIVE_MAGIC {
return Err(Error::InvalidHeader("not a ZEXA archive".into()));
}
*ip += 4;
let ver = read_u16(data, ip)?;
if ver != ARCHIVE_VERSION {
return Err(Error::UnsupportedVersion {
found: ver,
supported: ARCHIVE_VERSION,
});
}
let _flags = read_u16(data, ip)?;
Ok(())
}
fn read_u16(data: &[u8], ip: &mut usize) -> Result<u16> {
if *ip + 2 > data.len() {
return Err(Error::CorruptBlock("archive truncated u16".into()));
}
let v = u16::from_le_bytes([data[*ip], data[*ip + 1]]);
*ip += 2;
Ok(v)
}
fn read_u32(data: &[u8], ip: &mut usize) -> Result<u32> {
if *ip + 4 > data.len() {
return Err(Error::CorruptBlock("archive truncated u32".into()));
}
let v = u32::from_le_bytes(data[*ip..*ip + 4].try_into().unwrap());
*ip += 4;
Ok(v)
}
fn read_u64(data: &[u8], ip: &mut usize) -> Result<u64> {
if *ip + 8 > data.len() {
return Err(Error::CorruptBlock("archive truncated u64".into()));
}
let v = u64::from_le_bytes(data[*ip..*ip + 8].try_into().unwrap());
*ip += 8;
Ok(v)
}
fn read_name(data: &[u8], ip: &mut usize) -> Result<String> {
let n = read_u16(data, ip)? as usize;
if *ip + n > data.len() {
return Err(Error::CorruptBlock("archive name truncated".into()));
}
let s = std::str::from_utf8(&data[*ip..*ip + n])
.map_err(|_| Error::CorruptBlock("archive name not utf-8".into()))?
.to_string();
*ip += n;
Ok(s)
}
pub fn is_archive(data: &[u8]) -> bool {
data.len() >= 4 && data[..4] == ARCHIVE_MAGIC
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::encoder::CompressOptions;
#[test]
fn archive_roundtrip() {
let entries = vec![
ArchiveEntry {
name: "a.txt".into(),
data: b"hello archive a".to_vec(),
},
ArchiveEntry {
name: "b/bin.dat".into(),
data: vec![1, 2, 3, 4, 5, 5, 5, 5],
},
];
let arc = create_archive(&entries, &CompressOptions::default().level(3)).unwrap();
assert!(is_archive(&arc));
let list = list_archive(&arc).unwrap();
assert_eq!(list.len(), 2);
assert_eq!(list[0].name, "a.txt");
let out = extract_archive(&arc, &DecompressOptions::default()).unwrap();
assert_eq!(out[0].data, entries[0].data);
assert_eq!(out[1].data, entries[1].data);
}
#[test]
fn rejects_path_traversal() {
let entries = vec![ArchiveEntry {
name: "../etc/passwd".into(),
data: b"x".to_vec(),
}];
let arc = create_archive(&entries, &CompressOptions::default()).unwrap();
let dir = tempfile::tempdir().unwrap();
assert!(extract_to_dir(&arc, dir.path(), &DecompressOptions::default()).is_err());
}
}