Files
clash-verge-rev/src-tauri/src/feat/backup.rs
T

578 lines
21 KiB
Rust

use crate::{
config::{
Config, IClashTemp, IProfiles, IVerge, profile_storage,
profiles::{load_profiles_unlocked, validate_profile_file},
},
core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
process::AsyncHandler,
utils::{
dirs::{
PROFILE_YAML, PROFILES_DIR, PathBufExec as _, VERGE_CONFIG, app_home_dir, local_backup_dir, verge_path,
},
help,
},
};
use anyhow::{Context as _, Result, anyhow};
use chrono::Utc;
use clash_verge_backup_archive::{BackupArchive, StagedBackup};
use clash_verge_draft::DraftConflict;
use clash_verge_logging::{Type, logging};
use clash_verge_profile_store::RECOVERY_ENTRY_NAMES;
use reqwest_dav::list_cmd::ListFile;
use serde::Serialize;
use std::{
fs::File,
path::{Path, PathBuf},
};
use tokio::fs;
use tristr::alias::String;
#[derive(Debug, Serialize, specta::Type)]
pub struct LocalBackupFile {
pub filename: String,
pub path: String,
pub last_modified: String,
pub content_length: u64,
}
async fn apply_backup(archive: BackupArchive<File>) -> Result<()> {
let _profile_write = crate::config::profiles::PROFILE_WRITE_LOCK.lock().await;
let config_write = Config::lock_config_write().await;
let verge_draft = Config::verge().await;
let live = verge_draft.latest_arc();
let profiles_draft = Config::profiles().await;
let mut profile_guard = None;
let restored = {
let guard = &mut profile_guard;
let draft = &profiles_draft;
profiles_draft
.with_data_modify(|_| async move {
let (io_guard, retry) = profile_storage::write_for_restore().await?;
*guard = Some(io_guard);
let (profiles, mut restored) = restore_files(archive, retry).await?;
restored.webdav_url.clone_from(&live.webdav_url);
restored.webdav_username.clone_from(&live.webdav_username);
restored.webdav_password.clone_from(&live.webdav_password);
restored
.save_file()
.await
.context("backup files were restored, but the live WebDAV settings could not be saved")
.inspect_err(profile_storage::block_restore)?;
draft.discard();
Ok((profiles, restored))
})
.await
.inspect_err(|error: &anyhow::Error| {
if error.is::<DraftConflict>() {
profile_storage::block_restore(error);
}
})?
};
let restored_clash = IClashTemp::new().await;
let clash_draft = Config::clash().await;
clash_draft.edit_draft(|d| {
*d = restored_clash;
});
clash_draft.apply();
verge_draft.edit_draft(|d| {
*d = restored;
});
verge_draft.apply();
if let Some(guard) = &profile_guard {
profile_storage::finish_restore(guard);
}
drop(profile_guard);
let restored = verge_draft.data_arc();
auto_backup::publish_settings(&restored);
// Turn it off here; a failing core side effect below would otherwise skip this step.
if !restored.enable_system_proxy.unwrap_or_default() {
let result = async {
let _lifecycle = CoreManager::global().lifecycle_lock.lock().await;
proxy_control::apply().await?;
proxy_control::refresh_guard().await
}
.await;
if let Err(err) = result {
logging!(error, Type::Backup, "Failed to turn the system proxy off: {err:#}");
if SystemProxyStateUnknown::is_in(&err) {
return Err(err);
}
}
}
let applied = super::config::apply_verge_patch_locked(&config_write, &restored, true).await;
drop(config_write);
if let Err(err) = applied {
logging!(error, Type::Backup, "Failed to apply restored verge config: {err:#}");
// Propagate unknown proxy state; ordinary side-effect failures stay logged.
if SystemProxyStateUnknown::is_in(&err) {
return Err(err);
}
} else if restored.enable_tun_mode.is_some() {
super::reconcile_tun_availability().await;
}
Ok(())
}
#[tracing::instrument(skip_all, level = "info")]
pub async fn create_backup_and_upload_webdav() -> Result<()> {
let (file_name, temp_file_path) = backup::create_backup().await.map_err(|err| {
logging!(error, Type::Backup, "Failed to create backup: {err:#}");
err
})?;
if let Err(err) = backup::WebDavClient::global()
.upload(temp_file_path.clone(), file_name)
.await
{
logging!(error, Type::Backup, "Failed to upload to WebDAV: {err:#}");
backup::WebDavClient::global().reset();
return Err(err);
}
if let Err(err) = temp_file_path.remove_if_exists().await {
logging!(warn, Type::Backup, "Failed to remove temp file: {err:#}");
}
Ok(())
}
pub async fn list_wevdav_backup() -> Result<Vec<ListFile>> {
backup::WebDavClient::global().list().await.map_err(|err| {
logging!(error, Type::Backup, "Failed to list WebDAV backup files: {err:#}");
err
})
}
pub async fn delete_webdav_backup(filename: String) -> Result<()> {
let name = filename.clone();
backup::WebDavClient::global().delete(filename).await.map_err(|err| {
logging!(
error,
Type::Backup,
"Failed to delete WebDAV backup file {name}: {err:#}"
);
err
})
}
async fn restore_input_path(staged: &Path, name: &str, fallback: Option<&Path>) -> Result<PathBuf> {
let path = staged.join(name);
if let Some(dir) = fallback
&& !fs::try_exists(&path).await?
{
return Ok(dir.join(name));
}
Ok(path)
}
async fn validate_restore(archive: BackupArchive<File>, home_dir: &Path, retry: bool) -> Result<StagedBackup> {
let staging_root = home_dir.to_owned();
let staged = AsyncHandler::spawn_blocking(move || archive.stage(&staging_root))
.await
.map_err(|join| anyhow!("backup staging task failed: {join}"))??;
if let Err(error) = validate_restore_inputs(staged.path(), home_dir, retry).await {
AsyncHandler::spawn_blocking(move || drop(staged)).await?;
return Err(error);
}
Ok(staged)
}
async fn validate_restore_inputs(staged: &Path, home_dir: &Path, retry: bool) -> Result<()> {
let fallback = (!retry).then_some(home_dir);
let verge = restore_input_path(staged, VERGE_CONFIG, fallback).await?;
let profiles_path = restore_input_path(staged, PROFILE_YAML, fallback).await?;
help::read_yaml::<IVerge>(&verge).await?;
let profiles: IProfiles = help::read_yaml(&profiles_path).await?;
// A previous partial restore may have left an omitted runtime setting unreadable.
let existing_settings = retry.then_some(home_dir);
let clash = restore_input_path(staged, crate::utils::dirs::CLASH_CONFIG, existing_settings).await?;
if fs::try_exists(&clash).await? {
help::read_mapping(&clash).await?;
}
let dns = restore_input_path(staged, crate::constants::files::DNS_CONFIG, existing_settings).await?;
if fs::try_exists(&dns).await? {
help::read_yaml::<serde_yaml_ng::Mapping>(&dns).await?;
}
let staged_bodies = staged.join(PROFILES_DIR);
let live_bodies = home_dir.join(PROFILES_DIR);
for file in profiles.items.iter().flatten().filter_map(|item| item.file.as_deref()) {
let file = if !retry && let Ok(relative) = Path::new(file).strip_prefix(".") {
relative.to_str().context("invalid profile filename")?
} else {
file
};
validate_profile_file(file)?;
let body = restore_input_path(&staged_bodies, file, (!retry).then_some(live_bodies.as_path())).await?;
if body.parent() == Some(&live_bodies) {
anyhow::ensure!(
fs::symlink_metadata(&live_bodies).await?.is_dir(),
"live profiles path is not a directory"
);
}
let metadata = fs::symlink_metadata(&body)
.await
.with_context(|| format!("failed to inspect backup profile body {file}"))?;
anyhow::ensure!(metadata.is_file(), "backup profile body {file} is not a file");
}
Ok(())
}
async fn restore_files(archive: BackupArchive<File>, retry: bool) -> Result<(IProfiles, IVerge)> {
let home_dir = app_home_dir()?;
let staged = validate_restore(archive, &home_dir, retry)
.await
.context("backup staging failed before live files were changed")?;
let installed = AsyncHandler::spawn_blocking(move || staged.install(&home_dir))
.await
.context("backup installation task stopped unexpectedly")
.inspect_err(profile_storage::block_restore)?;
if let Err(error) = installed {
if !error.live_changed {
return Err(error).context("backup installation failed before live files were changed");
}
let error = anyhow::Error::from(error)
.context("backup restore failed while writing live files; a complete restore may be required");
profile_storage::block_restore(&error);
return Err(error);
}
async {
let verge = help::read_yaml::<IVerge>(&verge_path()?).await?;
let profiles = load_profiles_unlocked().await?;
Ok::<_, anyhow::Error>((profiles, verge))
}
.await
.context("backup files were restored, but the restored settings could not be loaded")
.inspect_err(profile_storage::block_restore)
}
/// Backup creation strips the WebDAV credentials, so the live ones are kept.
async fn restore_backup_archive(file: File) -> Result<()> {
let archive = AsyncHandler::spawn_blocking(move || BackupArchive::open(file, RECOVERY_ENTRY_NAMES))
.await
.map_err(|join| anyhow!("backup preflight task failed: {join}"))??;
tokio::spawn(apply_backup(archive)).await?
}
#[tracing::instrument(skip_all, level = "info", fields(filename = %filename))]
pub async fn restore_webdav_backup(filename: String) -> Result<()> {
tokio::spawn(async move {
let archive_dir = tempfile::tempdir()?;
let archive = archive_dir.path().join("backup.zip");
let name = filename.clone();
backup::WebDavClient::global()
.download(filename, archive.clone())
.await
.map_err(|err| {
logging!(
error,
Type::Backup,
"Failed to download WebDAV backup file {name}: {err:#}"
);
err
})?;
let file = fs::File::open(archive).await?.into_std().await;
let result = restore_backup_archive(file).await;
drop(archive_dir);
result
})
.await?
}
pub async fn create_local_backup() -> Result<()> {
create_local_backup_with_namer(|name| name.to_string().into())
.await
.map(|_| ())
}
pub async fn create_local_backup_with_namer<F>(namer: F) -> Result<String>
where
F: FnOnce(&str) -> String,
{
let (file_name, temp_file_path) = backup::create_backup().await.map_err(|err| {
logging!(error, Type::Backup, "Failed to create local backup: {err:#}");
err
})?;
let backup_dir = local_backup_dir()?;
let final_name = namer(file_name.as_str());
let target_path = backup_dir.join(final_name.as_str());
if let Err(err) = move_file(temp_file_path.clone(), target_path.clone()).await {
logging!(
error,
Type::Backup,
"Failed to move local backup file to {}: {err:#}",
target_path.display()
);
if let Err(clean_err) = temp_file_path.remove_if_exists().await {
logging!(
warn,
Type::Backup,
"Failed to remove temp backup file after move error: {clean_err:#}"
);
}
return Err(err);
}
Ok(final_name)
}
#[tracing::instrument(skip_all, level = "info", fields(source = %source))]
pub async fn import_local_backup(source: String) -> Result<String> {
let source_path = PathBuf::from(source.as_str());
if !source_path.exists() {
return Err(anyhow!("Backup file not found: {source}"));
}
if !source_path.is_file() {
return Err(anyhow!("Backup path is not a file: {source}"));
}
let ext = source_path
.extension()
.and_then(|ext| ext.to_str())
.map_or_default(|ext| ext.to_ascii_lowercase());
if ext != "zip" {
return Err(anyhow!("Only .zip backup files are supported"));
}
let file_name = source_path
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| anyhow!("Invalid backup file name"))?;
let backup_dir = local_backup_dir()?;
let target_path = backup_dir.join(file_name);
if target_path == source_path {
return Ok(file_name.to_string().into());
}
if let Some(parent) = target_path.parent() {
fs::create_dir_all(parent).await?;
}
if target_path.exists() {
return Err(anyhow!("Backup file already exists: {file_name}"));
}
fs::copy(&source_path, &target_path)
.await
.map_err(|err| anyhow!("Failed to import backup file: {err:#}"))?;
Ok(file_name.to_string().into())
}
async fn move_file(from: PathBuf, to: PathBuf) -> Result<()> {
if let Some(parent) = to.parent() {
fs::create_dir_all(parent).await?;
}
match fs::rename(&from, &to).await {
Ok(_) => Ok(()),
Err(rename_err) => {
// Rename can fail across filesystems; fall back to copy then remove.
logging!(
warn,
Type::Backup,
"Failed to rename backup file directly, fallback to copy/remove: {rename_err}"
);
fs::copy(&from, &to)
.await
.map_err(|err| anyhow!("Failed to copy backup file: {err:#}"))?;
fs::remove_file(&from)
.await
.map_err(|err| anyhow!("Failed to remove temp backup file: {err:#}"))?;
Ok(())
}
}
}
pub async fn list_local_backup() -> Result<Vec<LocalBackupFile>> {
let backup_dir = local_backup_dir()?;
if !backup_dir.exists() {
return Ok(vec![]);
}
let mut backups = Vec::new();
let mut dir = fs::read_dir(&backup_dir).await?;
while let Some(entry) = dir.next_entry().await? {
let path = entry.path();
let metadata = entry.metadata().await?;
if !metadata.is_file() {
continue;
}
let file_name = match path.file_name().and_then(|name| name.to_str()) {
Some(name) => name,
None => continue,
};
let last_modified = metadata
.modified()
.map_or_default(|time| chrono::DateTime::<Utc>::from(time).to_rfc3339());
backups.push(LocalBackupFile {
filename: file_name.into(),
path: path.to_string_lossy().into(),
last_modified: last_modified.into(),
content_length: metadata.len(),
});
}
backups.sort_by(|a, b| b.filename.cmp(&a.filename));
Ok(backups)
}
pub async fn delete_local_backup(filename: String) -> Result<()> {
let backup_dir = local_backup_dir()?;
let target_path = backup_dir.join(filename.as_str());
if !target_path.exists() {
logging!(debug, Type::Backup, "Local backup file not found: {}", filename);
return Ok(());
}
target_path.remove_if_exists().await?;
Ok(())
}
fn snapshot_local_backup(path: &Path) -> Result<File> {
// Header checks and staging must read the same bytes even if the local ZIP changes during restore.
let mut snapshot = tempfile::tempfile()?;
std::io::copy(&mut File::open(path)?, &mut snapshot)?;
Ok(snapshot)
}
#[tracing::instrument(skip_all, level = "info", fields(filename = %filename))]
pub async fn restore_local_backup(filename: String) -> Result<()> {
let backup_dir = local_backup_dir()?;
let target_path = backup_dir.join(filename.as_str());
if !target_path.exists() {
return Err(anyhow!("Backup file not found: {}", filename));
}
let snapshot = AsyncHandler::spawn_blocking(move || snapshot_local_backup(&target_path)).await??;
restore_backup_archive(snapshot).await
}
#[tracing::instrument(skip_all, level = "info", fields(filename = %filename, destination = %destination))]
pub async fn export_local_backup(filename: String, destination: String) -> Result<()> {
let backup_dir = local_backup_dir()?;
let source_path = backup_dir.join(filename.as_str());
if !source_path.exists() {
return Err(anyhow!("Backup file not found: {}", filename));
}
let dest_path = PathBuf::from(destination.as_str());
if let Some(parent) = dest_path.parent() {
fs::create_dir_all(parent).await?;
}
fs::copy(&source_path, &dest_path)
.await
.map(|_| ())
.map_err(|err| anyhow!("Failed to export backup file: {err:#}"))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use clash_verge_backup_archive::BackupWriter;
use std::io::Write as _;
#[test]
fn local_restore_reads_the_same_archive_after_the_source_changes() -> Result<()> {
let source = tempfile::NamedTempFile::new()?;
let mut writer = BackupWriter::new(source.reopen()?)?;
writer.start_file(PROFILE_YAML)?.write_all(b"items: []")?;
writer.finish()?;
let snapshot = snapshot_local_backup(source.path())?;
std::fs::write(source.path(), b"replaced")?;
let staging = tempfile::tempdir()?;
BackupArchive::open(snapshot, RECOVERY_ENTRY_NAMES)?
.stage(staging.path())?
.install(staging.path())?;
assert_eq!(std::fs::read(staging.path().join(PROFILE_YAML))?, b"items: []");
Ok(())
}
#[tokio::test]
async fn rejects_malformed_runtime_settings_in_staging() -> Result<()> {
let home = tempfile::tempdir()?;
fs::write(home.path().join(PROFILE_YAML), b"items: []").await?;
fs::write(home.path().join(VERGE_CONFIG), b"{}").await?;
for name in [crate::utils::dirs::CLASH_CONFIG, crate::constants::files::DNS_CONFIG] {
fs::write(home.path().join(name), b"key: original").await?;
let mut writer = BackupWriter::new(tempfile::tempfile()?)?;
writer.start_file(name)?.write_all(b"[invalid")?;
let archive = BackupArchive::open(writer.finish()?, RECOVERY_ENTRY_NAMES)?;
assert!(validate_restore(archive, home.path(), false).await.is_err(), "{name}");
assert_eq!(fs::read(home.path().join(name)).await?, b"key: original");
fs::write(home.path().join(name), b"[invalid").await?;
let mut writer = BackupWriter::new(tempfile::tempfile()?)?;
writer.start_file(VERGE_CONFIG)?.write_all(b"{}")?;
writer.start_file(PROFILE_YAML)?.write_all(b"items: []")?;
let archive = BackupArchive::open(writer.finish()?, RECOVERY_ENTRY_NAMES)?;
assert!(validate_restore(archive, home.path(), true).await.is_err(), "{name}");
fs::remove_file(home.path().join(name)).await?;
}
Ok(())
}
#[tokio::test]
async fn validates_config_before_replacing_live_files() -> Result<()> {
let home = tempfile::tempdir()?;
let path = home.path().join(PROFILE_YAML);
let live = b"items: []\n";
fs::write(&path, live).await?;
fs::write(home.path().join(VERGE_CONFIG), b"{}\n").await?;
let open_backup = |index: Option<&[u8]>, include_body: bool| -> Result<_> {
let file = tempfile::tempfile()?;
let mut writer = BackupWriter::new(file)?;
writer.start_file(VERGE_CONFIG)?.write_all(b"{}\n")?;
if let Some(index) = index {
writer.start_file(PROFILE_YAML)?.write_all(index)?;
}
if include_body {
writer.start_profile("r.yaml")?.write_all(b"proxies: []\n")?;
}
Ok(BackupArchive::open(writer.finish()?, RECOVERY_ENTRY_NAMES)?)
};
let invalid = open_backup(Some(b"items: invalid\n"), false)?;
assert!(validate_restore(invalid, home.path(), false).await.is_err());
assert_eq!(fs::read(&path).await?, live);
validate_restore(open_backup(None, false)?, home.path(), false).await?;
assert!(
validate_restore(open_backup(None, false)?, home.path(), true)
.await
.is_err()
);
let index = b"items: [{uid: r, type: remote, file: r.yaml}]\n";
assert!(
validate_restore(open_backup(Some(index), false)?, home.path(), true)
.await
.is_err()
);
assert!(
validate_restore(open_backup(Some(index), false)?, home.path(), false)
.await
.is_err()
);
assert_eq!(fs::read(&path).await?, live);
fs::create_dir(home.path().join(PROFILES_DIR)).await?;
fs::write(home.path().join(PROFILES_DIR).join("r.yaml"), b"old body").await?;
validate_restore(open_backup(Some(index), false)?, home.path(), false).await?;
assert!(
validate_restore(open_backup(Some(index), false)?, home.path(), true)
.await
.is_err()
);
validate_restore(open_backup(Some(index), true)?, home.path(), true).await?;
let old_index = b"items: [{uid: r, type: remote, file: ./r.yaml}]";
validate_restore(open_backup(Some(old_index), true)?, home.path(), false).await?;
Ok(())
}
}