mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-01 10:40:14 +08:00
refactor(backup): extract the backup archive crate
This commit is contained in:
Generated
+9
@@ -1091,6 +1091,7 @@ dependencies = [
|
||||
"base64 0.23.1",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"clash-verge-backup-archive",
|
||||
"clash-verge-config-render",
|
||||
"clash-verge-draft",
|
||||
"clash-verge-i18n",
|
||||
@@ -1173,6 +1174,14 @@ dependencies = [
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-backup-archive"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"thiserror 2.0.20",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-config-render"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -16,6 +16,7 @@ members = [
|
||||
"crates/clash-verge-proxy-view",
|
||||
"crates/clash-verge-profile",
|
||||
"crates/clash-verge-profile-store",
|
||||
"crates/clash-verge-backup-archive",
|
||||
]
|
||||
resolver = "2"
|
||||
|
||||
@@ -73,6 +74,7 @@ clash-verge-runtime-bundle = { path = "crates/clash-verge-runtime-bundle" }
|
||||
clash-verge-proxy-view = { path = "crates/clash-verge-proxy-view" }
|
||||
clash-verge-profile = { path = "crates/clash-verge-profile" }
|
||||
clash-verge-profile-store = { path = "crates/clash-verge-profile-store" }
|
||||
clash-verge-backup-archive = { path = "crates/clash-verge-backup-archive" }
|
||||
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", default-features = false }
|
||||
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
|
||||
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
|
||||
@@ -83,6 +85,7 @@ tauri-plugin-clipboard-manager = "2.5.0"
|
||||
parking_lot = "0.13.0"
|
||||
anyhow = "1.0.105"
|
||||
thiserror = "2.0.20"
|
||||
zip = "9.9.0"
|
||||
boa_engine = "0.22.0"
|
||||
futures = "0.3.34"
|
||||
chrono = "0.4.45"
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "clash-verge-backup-archive"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
thiserror = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,13 @@
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ArchiveError {
|
||||
#[error(transparent)]
|
||||
Zip(#[from] zip::result::ZipError),
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("backup contains a symbolic link")]
|
||||
Symlink,
|
||||
#[error("backup contains an invalid path")]
|
||||
InvalidPath,
|
||||
#[error("archive contains profile recovery data")]
|
||||
ReservedEntry,
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
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 ValidatedBackup<R: Read + Seek> {
|
||||
zip: ZipArchive<R>,
|
||||
}
|
||||
|
||||
impl<R: Read + Seek> ValidatedBackup<R> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
io::copy(&mut entry, &mut io::sink())?;
|
||||
}
|
||||
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 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);
|
||||
ValidatedBackup::open(source, &[".profile-refresh", ".profile-refresh.lock"])?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,7 @@ clash-verge-config-render = { workspace = true }
|
||||
clash-verge-profile-script = { workspace = true }
|
||||
clash-verge-proxy-view = { workspace = true }
|
||||
clash-verge-profile = { workspace = true }
|
||||
clash-verge-backup-archive = { workspace = true }
|
||||
tauri-plugin-clash-verge-sysinfo = { workspace = true }
|
||||
tauri-plugin-clipboard-manager = { workspace = true }
|
||||
tauri = { workspace = true, features = [
|
||||
@@ -83,7 +84,6 @@ tauri-plugin-dialog = "2.8.4"
|
||||
tauri-plugin-fs = "2.7.1"
|
||||
tauri-plugin-deep-link = "2.6.3"
|
||||
tauri-plugin-window-state = "2.5.0"
|
||||
zip = "9.9.0"
|
||||
flate2 = "1.1.11"
|
||||
reqwest_dav = "0.4.0"
|
||||
aes-gcm = { version = "0.11.1" }
|
||||
@@ -146,6 +146,7 @@ objc2-app-kit = { version = "0.3.2", features = [
|
||||
] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
zip = { workspace = true }
|
||||
deelevate = { workspace = true }
|
||||
quick-xml = "0.42.0"
|
||||
runas = "=1.2.0"
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::{config::Config, process::AsyncHandler, utils::dirs};
|
||||
use anyhow::Error;
|
||||
use arc_swap::{ArcSwap, ArcSwapOption};
|
||||
use backon::{ConstantBuilder, Retryable as _};
|
||||
use clash_verge_backup_archive::BackupWriter;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus};
|
||||
use std::{
|
||||
@@ -15,7 +16,6 @@ use std::{
|
||||
};
|
||||
use tokio::{fs, time::timeout};
|
||||
use tristr::alias::String;
|
||||
use zip::write::SimpleFileOptions;
|
||||
|
||||
const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
@@ -275,9 +275,7 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
|
||||
|
||||
let value = zip_path.clone();
|
||||
let file = AsyncHandler::spawn_blocking(move || std::fs::File::create(&value)).await??;
|
||||
let mut zip = zip::ZipWriter::new(file);
|
||||
zip.add_directory("profiles/", SimpleFileOptions::default())?;
|
||||
let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||
let mut archive = BackupWriter::new(file)?;
|
||||
|
||||
let profile_guard = crate::config::profile_storage::read().await?;
|
||||
let mut entries = fs::read_dir(dirs::app_profiles_dir()?).await?;
|
||||
@@ -288,17 +286,17 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
|
||||
let file_name = file_name_os
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
|
||||
let backup_path = format!("profiles/{}", file_name);
|
||||
zip.start_file(backup_path, options)?;
|
||||
let mut entry = archive.start_profile(file_name)?;
|
||||
let file_content = fs::read(&path).await?;
|
||||
zip.write_all(&file_content)?;
|
||||
entry.write_all(&file_content)?;
|
||||
}
|
||||
}
|
||||
let profile_index = fs::read(dirs::profiles_path()?).await?;
|
||||
drop(profile_guard);
|
||||
|
||||
zip.start_file(dirs::CLASH_CONFIG, options)?;
|
||||
zip.write_all(fs::read(dirs::clash_path()?).await?.as_slice())?;
|
||||
archive
|
||||
.start_file(dirs::CLASH_CONFIG)?
|
||||
.write_all(&fs::read(dirs::clash_path()?).await?)?;
|
||||
|
||||
let verge_text = fs::read_to_string(dirs::verge_path()?).await?;
|
||||
let mut verge_config: serde_json::Value = serde_yaml_ng::from_str(&verge_text)?;
|
||||
@@ -307,17 +305,18 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
|
||||
obj.remove("webdav_password");
|
||||
obj.remove("webdav_url");
|
||||
}
|
||||
zip.start_file(dirs::VERGE_CONFIG, options)?;
|
||||
zip.write_all(serde_yaml_ng::to_string(&verge_config)?.as_bytes())?;
|
||||
archive
|
||||
.start_file(dirs::VERGE_CONFIG)?
|
||||
.write_all(serde_yaml_ng::to_string(&verge_config)?.as_bytes())?;
|
||||
|
||||
let dns_config_path = dirs::app_home_dir()?.join(DNS_CONFIG);
|
||||
if dns_config_path.exists() {
|
||||
zip.start_file(DNS_CONFIG, options)?;
|
||||
zip.write_all(fs::read(&dns_config_path).await?.as_slice())?;
|
||||
archive
|
||||
.start_file(DNS_CONFIG)?
|
||||
.write_all(&fs::read(&dns_config_path).await?)?;
|
||||
}
|
||||
|
||||
zip.start_file(dirs::PROFILE_YAML, options)?;
|
||||
zip.write_all(&profile_index)?;
|
||||
zip.finish()?;
|
||||
archive.start_file(dirs::PROFILE_YAML)?.write_all(&profile_index)?;
|
||||
archive.finish()?;
|
||||
Ok((zip_file_name, zip_path))
|
||||
}
|
||||
|
||||
@@ -9,17 +9,13 @@ use crate::{
|
||||
};
|
||||
use anyhow::{Result, anyhow};
|
||||
use chrono::Utc;
|
||||
use clash_verge_backup_archive::ValidatedBackup;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use reqwest_dav::list_cmd::ListFile;
|
||||
use serde::Serialize;
|
||||
use std::{
|
||||
fs::File,
|
||||
io,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use std::{fs::File, path::PathBuf};
|
||||
use tokio::fs;
|
||||
use tristr::alias::String;
|
||||
use zip::ZipArchive;
|
||||
|
||||
#[derive(Debug, Serialize, specta::Type)]
|
||||
pub struct LocalBackupFile {
|
||||
@@ -34,7 +30,7 @@ async fn finalize_restored_verge_config(
|
||||
webdav_url: Option<String>,
|
||||
webdav_username: Option<String>,
|
||||
webdav_password: Option<String>,
|
||||
archive: ZipArchive<File>,
|
||||
archive: ValidatedBackup<File>,
|
||||
) -> Result<()> {
|
||||
let config_write = Config::lock_config_write().await;
|
||||
let profiles_draft = Config::profiles().await;
|
||||
@@ -145,33 +141,10 @@ pub async fn delete_webdav_backup(filename: String) -> Result<()> {
|
||||
})
|
||||
}
|
||||
|
||||
fn prepare_restore_archive(path: &Path) -> Result<ZipArchive<File>> {
|
||||
let mut archive = ZipArchive::new(File::open(path)?)?;
|
||||
for i in 0..archive.len() {
|
||||
let mut entry = archive.by_index(i)?;
|
||||
anyhow::ensure!(!entry.is_symlink(), "backup contains a symbolic link");
|
||||
let path = entry
|
||||
.enclosed_name()
|
||||
.ok_or_else(|| anyhow!("backup contains an invalid path"))?;
|
||||
for component in path.components() {
|
||||
if let std::path::Component::Normal(name) = component {
|
||||
let name = name.to_string_lossy();
|
||||
anyhow::ensure!(
|
||||
!name.eq_ignore_ascii_case(".profile-refresh")
|
||||
&& !name.eq_ignore_ascii_case(".profile-refresh.lock"),
|
||||
"archive contains profile recovery data"
|
||||
);
|
||||
}
|
||||
}
|
||||
io::copy(&mut entry, &mut io::sink())?;
|
||||
}
|
||||
Ok(archive)
|
||||
}
|
||||
|
||||
async fn restore_files(mut archive: ZipArchive<File>) -> Result<(crate::config::IProfiles, IVerge)> {
|
||||
async fn restore_files(archive: ValidatedBackup<File>) -> Result<(crate::config::IProfiles, IVerge)> {
|
||||
let home_dir = app_home_dir()?;
|
||||
AsyncHandler::spawn_blocking(move || -> Result<()> {
|
||||
let extracted = archive.extract(&home_dir).map_err(anyhow::Error::from);
|
||||
let extracted = archive.extract_to(&home_dir).map_err(anyhow::Error::from);
|
||||
if let Err(error) = &extracted {
|
||||
crate::config::profile_storage::block(error);
|
||||
}
|
||||
@@ -194,9 +167,14 @@ async fn restore_files(mut archive: ZipArchive<File>) -> Result<(crate::config::
|
||||
/// Backup creation strips the WebDAV credentials, so the live ones are kept.
|
||||
async fn restore_backup_archive(path: PathBuf) -> Result<()> {
|
||||
crate::config::profile_storage::check()?;
|
||||
let archive = AsyncHandler::spawn_blocking(move || prepare_restore_archive(&path))
|
||||
.await
|
||||
.map_err(|join| anyhow!("backup preflight task failed: {join}"))??;
|
||||
let archive = AsyncHandler::spawn_blocking(move || -> Result<_> {
|
||||
Ok(ValidatedBackup::open(
|
||||
File::open(path)?,
|
||||
&[".profile-refresh", ".profile-refresh.lock"],
|
||||
)?)
|
||||
})
|
||||
.await
|
||||
.map_err(|join| anyhow!("backup preflight task failed: {join}"))??;
|
||||
let (webdav_url, webdav_username, webdav_password) = {
|
||||
let verge = Config::verge().await;
|
||||
let verge = verge.latest_arc();
|
||||
|
||||
Reference in New Issue
Block a user