Files
clash-verge-rev/crates/clash-verge-backup-archive/src/lib.rs
T

135 lines
5.0 KiB
Rust

mod error;
pub use error::ArchiveError;
use std::{
io::{self, Read, Seek, Write},
path::{Component, Path},
};
use zip::{CompressionMethod, ZipArchive, ZipWriter, write::SimpleFileOptions};
pub struct BackupWriter<W: Write + Seek> {
zip: ZipWriter<W>,
options: SimpleFileOptions,
}
impl<W: Write + Seek> BackupWriter<W> {
pub fn new(target: W) -> Result<Self, ArchiveError> {
let mut zip = ZipWriter::new(target);
zip.add_directory("profiles/", SimpleFileOptions::default())?;
let options = SimpleFileOptions::default().compression_method(CompressionMethod::Stored);
Ok(Self { zip, options })
}
pub fn start_profile<'a>(&'a mut self, filename: &str) -> Result<impl Write + use<'a, W>, ArchiveError> {
self.start_file(&format!("profiles/{filename}"))
}
pub fn start_file<'a>(&'a mut self, name: &str) -> Result<impl Write + use<'a, W>, ArchiveError> {
self.zip.start_file_with_options(self.options.name(name.as_bytes()))?;
Ok(&mut self.zip)
}
pub fn finish(self) -> Result<W, ArchiveError> {
Ok(self.zip.finish()?)
}
}
pub struct BackupArchive<R: Read + Seek> {
zip: ZipArchive<R>,
}
impl<R: Read + Seek> BackupArchive<R> {
/// Checks entry paths and lengths. Extract into staging to verify stored file checksums before restore.
pub fn open(source: R, reserved_names: &[&str]) -> Result<Self, ArchiveError> {
let mut zip = ZipArchive::new(source)?;
for index in 0..zip.len() {
let mut entry = zip.by_index(index)?;
if entry.is_symlink() {
return Err(ArchiveError::Symlink);
}
let path = entry.enclosed_name().ok_or(ArchiveError::InvalidPath)?;
for component in path.components() {
let Component::Normal(name) = component else {
continue;
};
let name = name.to_string_lossy();
if reserved_names
.iter()
.any(|reserved| name.eq_ignore_ascii_case(reserved))
{
return Err(ArchiveError::ReservedEntry);
}
}
// Extraction skips directory payloads and permits a decoded file shorter than its declared size.
let size = if entry.is_dir() || entry.compression() != CompressionMethod::Stored {
io::copy(&mut entry, &mut io::sink())?
} else {
entry.compressed_size()
};
if size != entry.size() {
return Err(ArchiveError::SizeMismatch);
}
}
Ok(Self { zip })
}
pub fn extract_to(&mut self, destination: &Path) -> Result<(), ArchiveError> {
self.zip.extract(destination)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[test]
fn rejects_entries_shorter_than_their_declared_size() -> Result<(), ArchiveError> {
for name in ["profiles/example.yaml", "profiles/"] {
for method in [CompressionMethod::Stored, CompressionMethod::Deflated] {
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
writer.start_file(name, SimpleFileOptions::default().compression_method(method))?;
writer.write_all(b"abc")?;
let mut bytes = writer.finish()?.into_inner();
let directory = ZipArchive::new(Cursor::new(&bytes))?.central_directory_start() as usize;
// Both ZIP headers agree on a size one byte larger than the actual payload.
bytes[22..26].copy_from_slice(&4u32.to_le_bytes());
bytes[directory + 24..directory + 28].copy_from_slice(&4u32.to_le_bytes());
assert!(
BackupArchive::open(Cursor::new(bytes), &[]).is_err(),
"{name} {method:?}"
);
}
}
Ok(())
}
#[test]
fn writes_and_validates_the_backup_layout() -> Result<(), ArchiveError> {
let mut writer = BackupWriter::new(Cursor::new(Vec::new()))?;
writer.start_profile("example.yaml")?.write_all(b"proxies: []\n")?;
writer.start_file("profiles.yaml")?.write_all(b"items: []\n")?;
let source = writer.finish()?;
let mut zip = ZipArchive::new(source.clone())?;
assert_eq!(zip.len(), 3);
assert_eq!(zip.by_index(0)?.name()?, "profiles/");
let profile_time = {
let mut entry = zip.by_index(1)?;
assert_eq!(entry.name()?, "profiles/example.yaml");
assert_eq!(entry.compression(), CompressionMethod::Stored);
let mut contents = Vec::new();
entry.read_to_end(&mut contents)?;
assert_eq!(contents, b"proxies: []\n");
entry.last_modified()
};
let index = zip.by_index(2)?;
assert_eq!(index.name()?, "profiles.yaml");
assert_eq!(index.last_modified(), profile_time);
BackupArchive::open(source, &[".profile-refresh", ".profile-refresh.lock"])?;
Ok(())
}
}