mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-04 21:30:06 +08:00
fix(backup): restore files from the validated staging directory
This commit is contained in:
Generated
+112
-1
@@ -98,6 +98,12 @@ version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
||||
|
||||
[[package]]
|
||||
name = "ambient-authority"
|
||||
version = "0.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b"
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.5"
|
||||
@@ -907,6 +913,48 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cap-fs-ext"
|
||||
version = "4.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "56ff379b70af8e08307a8f65e7040c7301cb4a572538ade16b4984f0da77847f"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"cap-std",
|
||||
"io-lifetimes 3.0.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cap-primitives"
|
||||
version = "4.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18"
|
||||
dependencies = [
|
||||
"ambient-authority",
|
||||
"fs-set-times",
|
||||
"io-extras",
|
||||
"io-lifetimes 3.0.2",
|
||||
"ipnet",
|
||||
"maybe-owned",
|
||||
"rustix 1.1.4",
|
||||
"rustix-linux-procfs",
|
||||
"windows-sys 0.61.2",
|
||||
"winx",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cap-std"
|
||||
version = "4.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1ec78e242cfa2cfe276807ac2ecc00315a6c97786977414bcd1c3963b6c91b8"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"io-extras",
|
||||
"io-lifetimes 3.0.2",
|
||||
"rustix 1.1.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cargo-platform"
|
||||
version = "0.3.3"
|
||||
@@ -1196,7 +1244,11 @@ dependencies = [
|
||||
name = "clash-verge-backup-archive"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"cap-fs-ext",
|
||||
"cap-primitives",
|
||||
"tempfile",
|
||||
"thiserror 2.0.20",
|
||||
"windows-sys 0.101.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
@@ -2193,7 +2245,7 @@ dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users 0.5.2",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.101.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2639,6 +2691,17 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs-set-times"
|
||||
version = "0.20.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7faf4684e58845f735514afb09ff7404ab7c26faf9f4d84dbc783a691256ee07"
|
||||
dependencies = [
|
||||
"io-lifetimes 2.0.4",
|
||||
"rustix 1.1.4",
|
||||
"windows-sys 0.101.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs_extra"
|
||||
version = "1.3.0"
|
||||
@@ -3710,6 +3773,28 @@ version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4275b20e6057cd7733fd8df8a5a31701e4fe44497dad0f3fa0e1c4fb971506be"
|
||||
|
||||
[[package]]
|
||||
name = "io-extras"
|
||||
version = "0.19.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "174362052ac8354d7e0c8be593872c476f204f83e6c4987d9ba760a3d801de26"
|
||||
dependencies = [
|
||||
"io-lifetimes 3.0.2",
|
||||
"windows-sys 0.101.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "io-lifetimes"
|
||||
version = "2.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"
|
||||
|
||||
[[package]]
|
||||
name = "io-lifetimes"
|
||||
version = "3.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b28156deaa5fb6c0f06c23351eefb194a4bc8e3a0e934c3cb13ff8496aa30481"
|
||||
|
||||
[[package]]
|
||||
name = "ipnet"
|
||||
version = "2.12.0"
|
||||
@@ -4304,6 +4389,12 @@ version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
||||
|
||||
[[package]]
|
||||
name = "maybe-owned"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.10.6"
|
||||
@@ -6223,6 +6314,16 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix-linux-procfs"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"rustix 1.1.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.47"
|
||||
@@ -10061,6 +10162,16 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winx"
|
||||
version = "0.36.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "18e241e21bf0690cf99541caedf959c02c24f36f0bafec8f142ed4e6505ba774"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"windows-sys 0.101.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
<details>
|
||||
<summary><strong> 🐞 修复问题 </strong></summary>
|
||||
|
||||
- 优化本地与 WebDAV 备份恢复,复用已校验的文件,减少重复解压
|
||||
- 修复订阅更新覆盖下载期间修改的设置,以及更新失败后遗留增强配置
|
||||
- 修复手动更新订阅时错误提示缺失或重复,显示订阅名称和失败原因
|
||||
- 优化订阅恢复失败提示,显示受影响的订阅名称
|
||||
|
||||
@@ -4,8 +4,14 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
cap-primitives = "4.0.3"
|
||||
cap-fs-ext = "4.0.3"
|
||||
tempfile = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { workspace = true, features = ["Win32_System_SystemServices"] }
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
mod error;
|
||||
mod staged;
|
||||
|
||||
pub use error::ArchiveError;
|
||||
pub use staged::{InstallError, StagedBackup};
|
||||
|
||||
use std::{
|
||||
io::{self, Read, Seek, Write},
|
||||
@@ -37,12 +39,14 @@ impl<W: Write + Seek> BackupWriter<W> {
|
||||
|
||||
pub struct BackupArchive<R: Read + Seek> {
|
||||
zip: ZipArchive<R>,
|
||||
entries: Vec<staged::Entry>,
|
||||
}
|
||||
|
||||
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)?;
|
||||
let mut entries = Vec::with_capacity(zip.len());
|
||||
for index in 0..zip.len() {
|
||||
let mut entry = zip.by_index(index)?;
|
||||
if entry.is_symlink() {
|
||||
@@ -67,16 +71,25 @@ impl<R: Read + Seek> BackupArchive<R> {
|
||||
} else {
|
||||
entry.compressed_size()
|
||||
};
|
||||
entries.push(staged::Entry {
|
||||
path,
|
||||
directory: entry.is_dir(),
|
||||
mode: entry.unix_mode(),
|
||||
});
|
||||
if size != entry.size() {
|
||||
return Err(ArchiveError::SizeMismatch);
|
||||
}
|
||||
}
|
||||
Ok(Self { zip })
|
||||
Ok(Self { zip, entries })
|
||||
}
|
||||
|
||||
pub fn extract_to(&mut self, destination: &Path) -> Result<(), ArchiveError> {
|
||||
self.zip.extract(destination)?;
|
||||
Ok(())
|
||||
pub fn stage(mut self, home: &Path) -> Result<StagedBackup, ArchiveError> {
|
||||
let files = tempfile::tempdir_in(home)?;
|
||||
self.zip.extract(files.path())?;
|
||||
Ok(StagedBackup {
|
||||
files,
|
||||
entries: self.entries,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,6 +119,58 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn installs_restricted_entries_and_preserves_omitted_files() -> Result<(), Box<dyn std::error::Error>> {
|
||||
use std::{fs, os::unix::fs::PermissionsExt as _};
|
||||
let home = tempfile::tempdir()?;
|
||||
let implicit = home.path().join("implicit");
|
||||
fs::create_dir(&implicit)?;
|
||||
std::os::unix::fs::symlink("implicit", home.path().join("link"))?;
|
||||
fs::set_permissions(&implicit, fs::Permissions::from_mode(0o750))?;
|
||||
fs::write(implicit.join("omitted"), "keep")?;
|
||||
fs::write(implicit.join("replace"), "old")?;
|
||||
fs::hard_link(implicit.join("replace"), implicit.join("peer"))?;
|
||||
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
|
||||
writer.add_directory("private/", SimpleFileOptions::default().unix_permissions(0))?;
|
||||
writer.start_file("private/body", SimpleFileOptions::default().unix_permissions(0o200))?;
|
||||
writer.write_all(b"restricted")?;
|
||||
writer.start_file("link/replace", SimpleFileOptions::default())?;
|
||||
writer.write_all(b"new")?;
|
||||
let staged = BackupArchive::open(writer.finish()?, &[])?.stage(home.path())?;
|
||||
staged.install(home.path())?;
|
||||
let private = home.path().join("private");
|
||||
assert_eq!(fs::metadata(&private)?.permissions().mode() & 0o777, 0);
|
||||
fs::set_permissions(&private, fs::Permissions::from_mode(0o700))?;
|
||||
assert_eq!(fs::metadata(private.join("body"))?.permissions().mode() & 0o777, 0o200);
|
||||
fs::set_permissions(private.join("body"), fs::Permissions::from_mode(0o600))?;
|
||||
assert_eq!(fs::read(private.join("body"))?, b"restricted");
|
||||
assert_eq!(fs::read(implicit.join("replace"))?, b"new");
|
||||
assert_eq!(fs::read(implicit.join("peer"))?, b"old");
|
||||
assert_eq!(fs::read(implicit.join("omitted"))?, b"keep");
|
||||
assert_eq!(fs::metadata(implicit)?.permissions().mode() & 0o777, 0o750);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_install_failure_by_preceding_live_changes() -> Result<(), Box<dyn std::error::Error>> {
|
||||
for partial in [false, true] {
|
||||
let home = tempfile::tempdir()?;
|
||||
std::fs::create_dir(home.path().join("conflict"))?;
|
||||
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
|
||||
if partial {
|
||||
writer.start_file("first", SimpleFileOptions::default())?;
|
||||
writer.write_all(b"installed")?;
|
||||
}
|
||||
writer.start_file("conflict", SimpleFileOptions::default())?;
|
||||
let staged = BackupArchive::open(writer.finish()?, &[])?.stage(home.path())?;
|
||||
let error = staged.install(home.path()).unwrap_err();
|
||||
assert_eq!(error.live_changed, partial);
|
||||
assert_eq!(home.path().join("first").exists(), partial);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_and_validates_the_backup_layout() -> Result<(), ArchiveError> {
|
||||
let mut writer = BackupWriter::new(Cursor::new(Vec::new()))?;
|
||||
|
||||
@@ -0,0 +1,458 @@
|
||||
use cap_fs_ext::{MetadataExt as _, OpenOptionsFollowExt as _, OpenOptionsMaybeDirExt as _, OpenOptionsSyncExt as _};
|
||||
use cap_primitives::fs as cap;
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
fs::{self, File},
|
||||
io::{self, ErrorKind},
|
||||
path::{Component, Path, PathBuf},
|
||||
};
|
||||
|
||||
pub(super) struct Entry {
|
||||
pub path: PathBuf,
|
||||
pub directory: bool,
|
||||
pub mode: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("{source}")]
|
||||
pub struct InstallError {
|
||||
pub live_changed: bool,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
}
|
||||
|
||||
pub struct StagedBackup {
|
||||
pub(super) files: tempfile::TempDir,
|
||||
pub(super) entries: Vec<Entry>,
|
||||
}
|
||||
|
||||
impl StagedBackup {
|
||||
pub fn path(&self) -> &Path {
|
||||
self.files.path()
|
||||
}
|
||||
|
||||
pub fn install(self, destination: &Path) -> Result<(), InstallError> {
|
||||
let mut live_changed = false;
|
||||
self.install_files(destination, &mut live_changed)
|
||||
.map_err(|source| InstallError { live_changed, source })
|
||||
}
|
||||
|
||||
fn install_files(&self, destination: &Path, changed: &mut bool) -> io::Result<()> {
|
||||
let destination = destination.canonicalize()?;
|
||||
let staging = self.path().canonicalize()?;
|
||||
let staged_dir = cap::open_ambient_dir(&staging, cap_primitives::ambient_authority())?;
|
||||
let staged_dir = cap::Metadata::from_file(&staged_dir)?;
|
||||
let root = cap::open_ambient_dir(&destination, cap_primitives::ambient_authority())?;
|
||||
let mut modes = BTreeMap::new();
|
||||
for entry in &self.entries {
|
||||
if entry.path.as_os_str().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let relative = resolve(&destination, &entry.path, &staging, &mut 40, true)?;
|
||||
if relative.as_os_str().is_empty() {
|
||||
return Err(invalid_target());
|
||||
}
|
||||
let parent = open_dirs(
|
||||
&root,
|
||||
relative.parent().ok_or_else(invalid_target)?,
|
||||
&staged_dir,
|
||||
changed,
|
||||
)?;
|
||||
let name = Path::new(relative.file_name().ok_or_else(invalid_target)?);
|
||||
if entry.directory {
|
||||
open_child_dir(&parent.dir, name, &staged_dir, changed)?;
|
||||
} else {
|
||||
let source = staging.join(&entry.path);
|
||||
copy_file(&staging, &source, &parent.dir, name, entry.mode, changed)?;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
let mode = fs::metadata(staging.join(&entry.path))?
|
||||
.permissions()
|
||||
.readonly()
|
||||
.then_some(0o444);
|
||||
#[cfg(not(windows))]
|
||||
let mode = entry.mode;
|
||||
if let Some(mode) = mode {
|
||||
modes.insert(relative, mode);
|
||||
} else if !entry.directory {
|
||||
modes.remove(&relative);
|
||||
}
|
||||
}
|
||||
for (path, mode) in modes.into_iter().rev() {
|
||||
let parent = open_dirs(&root, path.parent().ok_or_else(invalid_target)?, &staged_dir, changed)?;
|
||||
let name = Path::new(path.file_name().ok_or_else(invalid_target)?);
|
||||
set_mode(&parent.dir, name, mode)?;
|
||||
*changed = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid_target() -> io::Error {
|
||||
io::Error::new(ErrorKind::PermissionDenied, "invalid backup installation target")
|
||||
}
|
||||
|
||||
fn relative_link<'a>(home: &Path, target: &'a Path) -> io::Result<&'a Path> {
|
||||
if let Ok(relative) = target.strip_prefix(home) {
|
||||
return Ok(relative);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::path::Prefix;
|
||||
let volume = |prefix| match prefix {
|
||||
Prefix::Disk(drive) | Prefix::VerbatimDisk(drive) => Prefix::Disk(drive.to_ascii_uppercase()),
|
||||
Prefix::VerbatimUNC(server, share) => Prefix::UNC(server, share),
|
||||
other => other,
|
||||
};
|
||||
let mut home = home.components();
|
||||
let mut target = target.components();
|
||||
if let (Some(Component::Prefix(base)), Some(Component::Prefix(link))) = (home.next(), target.next())
|
||||
&& volume(base.kind()) == volume(link.kind())
|
||||
{
|
||||
return target
|
||||
.as_path()
|
||||
.strip_prefix(home.as_path())
|
||||
.map_err(|_| invalid_target());
|
||||
}
|
||||
}
|
||||
Err(invalid_target())
|
||||
}
|
||||
|
||||
// Resolve existing links within the home, then reopen the resolved components without following links.
|
||||
// A file entry replaces its leaf link only after its target has passed the same containment check.
|
||||
fn resolve(home: &Path, path: &Path, staging: &Path, hops: &mut u8, keep_leaf: bool) -> io::Result<PathBuf> {
|
||||
let mut out = PathBuf::new();
|
||||
let mut components = path.components().peekable();
|
||||
let mut missing = false;
|
||||
while let Some(component) = components.next() {
|
||||
match component {
|
||||
Component::Normal(name) => out.push(name),
|
||||
Component::CurDir => continue,
|
||||
Component::ParentDir if !missing && out.pop() => continue,
|
||||
_ => return Err(invalid_target()),
|
||||
}
|
||||
let full = home.join(&out);
|
||||
if full.starts_with(staging) {
|
||||
return Err(invalid_target());
|
||||
}
|
||||
match fs::symlink_metadata(&full) {
|
||||
Ok(meta) if meta.is_symlink() => {
|
||||
*hops = hops.checked_sub(1).ok_or_else(invalid_target)?;
|
||||
let link = fs::read_link(&full)?;
|
||||
let target = if link.is_absolute() {
|
||||
relative_link(home, &link)?.to_owned()
|
||||
} else {
|
||||
out.parent().ok_or_else(invalid_target)?.join(link)
|
||||
};
|
||||
let checked = resolve(home, &target, staging, hops, false)?;
|
||||
if !keep_leaf || components.peek().is_some() {
|
||||
missing |= !home.join(&checked).try_exists()?;
|
||||
out = checked;
|
||||
}
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => missing = true,
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
struct PinnedDir {
|
||||
dir: File,
|
||||
#[cfg(windows)]
|
||||
ancestors: Vec<File>,
|
||||
}
|
||||
|
||||
fn is_staging_directory(dir: &File, staging: &cap::Metadata) -> io::Result<bool> {
|
||||
let meta = cap::Metadata::from_file(dir)?;
|
||||
Ok(meta.dev() == staging.dev() && meta.ino() == staging.ino())
|
||||
}
|
||||
|
||||
fn open_dirs(root: &File, path: &Path, staging: &cap::Metadata, changed: &mut bool) -> io::Result<PinnedDir> {
|
||||
let mut parent = PinnedDir {
|
||||
dir: root.try_clone()?,
|
||||
#[cfg(windows)]
|
||||
ancestors: Vec::new(),
|
||||
};
|
||||
for component in path.components() {
|
||||
let Component::Normal(name) = component else {
|
||||
return Err(invalid_target());
|
||||
};
|
||||
let child = open_child_dir(&parent.dir, Path::new(name), staging, changed)?;
|
||||
#[cfg(windows)]
|
||||
parent.ancestors.push(parent.dir);
|
||||
parent.dir = child;
|
||||
}
|
||||
Ok(parent)
|
||||
}
|
||||
|
||||
fn open_child_dir(parent: &File, name: &Path, staging: &cap::Metadata, changed: &mut bool) -> io::Result<File> {
|
||||
#[cfg(unix)]
|
||||
let options = cap::DirBuilderExt::mode(&mut cap::DirOptions::new(), 0o700).clone();
|
||||
#[cfg(not(unix))]
|
||||
let options = cap::DirOptions::new();
|
||||
match cap::create_dir(parent, name, &options) {
|
||||
Ok(()) => *changed = true,
|
||||
Err(error) if error.kind() == ErrorKind::AlreadyExists => {}
|
||||
#[cfg(windows)]
|
||||
Err(error)
|
||||
if error.kind() == ErrorKind::PermissionDenied
|
||||
&& cap::stat(parent, name, cap::FollowSymlinks::No).is_ok() => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use cap::OpenOptionsExt as _;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
|
||||
let mut opts = cap::OpenOptions::new();
|
||||
opts.read(true)
|
||||
.maybe_dir(true)
|
||||
.follow(cap::FollowSymlinks::No)
|
||||
.share_mode(FILE_SHARE_READ);
|
||||
let dir = cap::open(parent, name, &opts)?;
|
||||
let meta = dir.metadata()?;
|
||||
check_storage_filter(&dir)?;
|
||||
if !meta.is_dir() || is_staging_directory(&dir, staging)? {
|
||||
return Err(invalid_target());
|
||||
}
|
||||
Ok(dir)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let dir = cap::open_dir_nofollow(parent, name)?;
|
||||
if is_staging_directory(&dir, staging)? {
|
||||
return Err(invalid_target());
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
let mode = dir.metadata()?.permissions().mode();
|
||||
if mode & 0o700 != 0o700 {
|
||||
cap::set_permissions(&dir, Path::new("."), cap::PermissionsExt::from_mode(mode | 0o700))?;
|
||||
*changed = true;
|
||||
}
|
||||
}
|
||||
Ok(dir)
|
||||
}
|
||||
}
|
||||
|
||||
fn open_source(staging: &Path, source: &Path) -> io::Result<File> {
|
||||
match File::open(source) {
|
||||
#[cfg(unix)]
|
||||
Err(error) if error.kind() == ErrorKind::PermissionDenied => {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
// Staging has the final archive modes, including unreadable files and directories.
|
||||
let mut path = staging.to_owned();
|
||||
for component in source.strip_prefix(staging).map_err(|_| invalid_target())?.components() {
|
||||
path.push(component);
|
||||
let meta = path.symlink_metadata()?;
|
||||
let needed = if meta.is_dir() { 0o700 } else { 0o400 };
|
||||
let mode = meta.permissions().mode();
|
||||
if mode & needed != needed {
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(mode | needed))?;
|
||||
}
|
||||
}
|
||||
File::open(source)
|
||||
}
|
||||
result => {
|
||||
let _ = staging;
|
||||
result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_file(
|
||||
staging: &Path,
|
||||
source: &Path,
|
||||
parent: &File,
|
||||
name: &Path,
|
||||
mode: Option<u32>,
|
||||
changed: &mut bool,
|
||||
) -> io::Result<()> {
|
||||
let mut input = open_source(staging, source)?;
|
||||
|
||||
let mut options = cap::OpenOptions::new();
|
||||
options.write(true).follow(cap::FollowSymlinks::No).nonblock(true);
|
||||
#[cfg(windows)]
|
||||
cap::OpenOptionsExt::share_mode(&mut options, windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ);
|
||||
#[cfg(unix)]
|
||||
cap::OpenOptionsExt::mode(&mut options, if mode.is_some() { 0o600 } else { 0o666 });
|
||||
#[cfg(not(unix))]
|
||||
let _ = mode;
|
||||
match cap::stat(parent, name, cap::FollowSymlinks::No) {
|
||||
Ok(metadata) => {
|
||||
let replace = metadata.is_symlink() || metadata.is_file() && metadata.nlink() > 1;
|
||||
#[cfg(windows)]
|
||||
let replace = {
|
||||
let mut replace = replace;
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
FILE_ATTRIBUTE_OFFLINE, FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS, FILE_ATTRIBUTE_RECALL_ON_OPEN,
|
||||
FILE_ATTRIBUTE_REPARSE_POINT, FILE_READ_ATTRIBUTES,
|
||||
};
|
||||
let attrs = cap::MetadataExt::file_attributes(&metadata);
|
||||
if !metadata.is_symlink() && attrs & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
|
||||
let mut query = cap::OpenOptions::new();
|
||||
cap::OpenOptionsExt::access_mode(&mut query, FILE_READ_ATTRIBUTES);
|
||||
let pinned = cap::open(parent, name, query.follow(cap::FollowSymlinks::No))?;
|
||||
check_storage_filter(&pinned)?;
|
||||
replace |= attrs
|
||||
& (FILE_ATTRIBUTE_OFFLINE
|
||||
| FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS
|
||||
| FILE_ATTRIBUTE_RECALL_ON_OPEN)
|
||||
!= 0;
|
||||
}
|
||||
replace
|
||||
};
|
||||
if replace {
|
||||
#[cfg(windows)]
|
||||
if cap::MetadataExt::file_attributes(&metadata)
|
||||
& windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_DIRECTORY
|
||||
!= 0
|
||||
{
|
||||
cap::remove_dir(parent, name)?;
|
||||
} else {
|
||||
cap::remove_file(parent, name)?;
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
cap::remove_file(parent, name)?;
|
||||
*changed = true;
|
||||
} else if !metadata.is_file() {
|
||||
return Err(invalid_target());
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
let mut output = match cap::open(parent, name, &options) {
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => {
|
||||
let file = cap::open(parent, name, options.create_new(true))?;
|
||||
*changed = true;
|
||||
file
|
||||
}
|
||||
result => result?,
|
||||
};
|
||||
let meta = cap::Metadata::from_file(&output)?;
|
||||
if !meta.is_file() || meta.nlink() != 1 {
|
||||
return Err(invalid_target());
|
||||
}
|
||||
#[cfg(windows)]
|
||||
check_storage_filter(&output)?;
|
||||
output.set_len(0)?;
|
||||
*changed = true;
|
||||
io::copy(&mut input, &mut output)?;
|
||||
output.set_modified(input.metadata()?.modified()?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_mode(parent: &File, name: &Path, mode: u32) -> io::Result<()> {
|
||||
let mut options = cap::OpenOptions::new();
|
||||
options
|
||||
.read(true)
|
||||
.follow(cap::FollowSymlinks::No)
|
||||
.maybe_dir(true)
|
||||
.nonblock(true);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows_sys::Win32::Storage::FileSystem::{FILE_READ_ATTRIBUTES, FILE_SHARE_READ, FILE_WRITE_ATTRIBUTES};
|
||||
cap::OpenOptionsExt::access_mode(&mut options, FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES);
|
||||
cap::OpenOptionsExt::share_mode(&mut options, FILE_SHARE_READ);
|
||||
}
|
||||
let file = match cap::open(parent, name, &options) {
|
||||
#[cfg(unix)]
|
||||
Err(error) if error.kind() == ErrorKind::PermissionDenied => {
|
||||
cap::open(parent, name, options.read(false).write(true))?
|
||||
}
|
||||
result => result?,
|
||||
};
|
||||
let meta = cap::Metadata::from_file(&file)?;
|
||||
if !(meta.is_dir() || meta.is_file() && meta.nlink() == 1) {
|
||||
return Err(invalid_target());
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
file.set_permissions(fs::Permissions::from_mode(mode))
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
check_storage_filter(&file)?;
|
||||
let mut permissions = file.metadata()?.permissions();
|
||||
permissions.set_readonly(mode & 0o222 == 0);
|
||||
file.set_permissions(permissions)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn check_storage_filter(file: &File) -> io::Result<()> {
|
||||
use std::os::windows::{fs::MetadataExt as _, io::AsRawHandle as _};
|
||||
use windows_sys::Win32::{
|
||||
Storage::FileSystem::{
|
||||
FILE_ATTRIBUTE_REPARSE_POINT, FILE_ATTRIBUTE_TAG_INFO, FileAttributeTagInfo, GetFileInformationByHandleEx,
|
||||
},
|
||||
System::SystemServices::{
|
||||
IO_REPARSE_TAG_CLOUD, IO_REPARSE_TAG_CLOUD_MASK, IO_REPARSE_TAG_DEDUP, IO_REPARSE_TAG_FILE_PLACEHOLDER,
|
||||
IO_REPARSE_TAG_HSM, IO_REPARSE_TAG_HSM2, IO_REPARSE_TAG_ONEDRIVE, IO_REPARSE_TAG_SIS,
|
||||
IO_REPARSE_TAG_STORAGE_SYNC, IO_REPARSE_TAG_WOF,
|
||||
},
|
||||
};
|
||||
|
||||
if file.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let mut info = FILE_ATTRIBUTE_TAG_INFO::default();
|
||||
// Inspect the pinned object, so a pathname swap cannot change which filter is classified.
|
||||
if unsafe {
|
||||
GetFileInformationByHandleEx(
|
||||
file.as_raw_handle(),
|
||||
FileAttributeTagInfo,
|
||||
(&raw mut info).cast(),
|
||||
size_of::<FILE_ATTRIBUTE_TAG_INFO>() as u32,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let tag = info.ReparseTag;
|
||||
if tag & !IO_REPARSE_TAG_CLOUD_MASK == IO_REPARSE_TAG_CLOUD
|
||||
|| matches!(
|
||||
tag,
|
||||
IO_REPARSE_TAG_ONEDRIVE
|
||||
| IO_REPARSE_TAG_FILE_PLACEHOLDER
|
||||
| IO_REPARSE_TAG_WOF
|
||||
| IO_REPARSE_TAG_DEDUP
|
||||
| IO_REPARSE_TAG_STORAGE_SYNC
|
||||
| 0x9000_0027
|
||||
| IO_REPARSE_TAG_HSM2
|
||||
| IO_REPARSE_TAG_HSM
|
||||
| IO_REPARSE_TAG_SIS
|
||||
| 0xC000_0014
|
||||
)
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(invalid_target())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, windows))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn absolute_links_may_use_an_ordinary_prefix_for_the_same_home() {
|
||||
let drive = Path::new(r"\\?\C:\home");
|
||||
let share = Path::new(r"\\?\UNC\server\share\home");
|
||||
assert_eq!(
|
||||
relative_link(drive, Path::new(r"c:\home\data")).ok(),
|
||||
Some(Path::new("data"))
|
||||
);
|
||||
assert_eq!(
|
||||
relative_link(share, Path::new(r"\\server\share\home\data")).ok(),
|
||||
Some(Path::new("data"))
|
||||
);
|
||||
assert!(relative_link(drive, Path::new(r"D:\home\data")).is_err());
|
||||
assert!(relative_link(share, Path::new(r"\\server\other\home\data")).is_err());
|
||||
assert!(relative_link(drive, Path::new(r"C:\home-other\data")).is_err());
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ use crate::{
|
||||
};
|
||||
use anyhow::{Context as _, Result, anyhow};
|
||||
use chrono::Utc;
|
||||
use clash_verge_backup_archive::BackupArchive;
|
||||
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;
|
||||
@@ -168,75 +168,76 @@ async fn restore_input_path(staged: &Path, name: &str, fallback: Option<&Path>)
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
async fn validate_restore(
|
||||
mut archive: BackupArchive<File>,
|
||||
home_dir: &Path,
|
||||
retry: bool,
|
||||
) -> Result<BackupArchive<File>> {
|
||||
async fn validate_restore(archive: BackupArchive<File>, home_dir: &Path, retry: bool) -> Result<StagedBackup> {
|
||||
let staging_root = home_dir.to_owned();
|
||||
let (staged, archive) = AsyncHandler::spawn_blocking(move || -> Result<_> {
|
||||
let staged = tempfile::tempdir_in(staging_root)?;
|
||||
archive.extract_to(staged.path())?;
|
||||
Ok((staged, archive))
|
||||
})
|
||||
.await
|
||||
.map_err(|join| anyhow!("backup staging task failed: {join}"))??;
|
||||
let validated: Result<()> = async {
|
||||
let fallback = (!retry).then_some(home_dir);
|
||||
let verge = restore_input_path(staged.path(), VERGE_CONFIG, fallback).await?;
|
||||
let profiles_path = restore_input_path(staged.path(), 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.path(), 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.path(), 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.path().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(())
|
||||
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);
|
||||
}
|
||||
.await;
|
||||
AsyncHandler::spawn_blocking(move || drop(staged)).await?;
|
||||
validated?;
|
||||
Ok(archive)
|
||||
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 mut archive = validate_restore(archive, &home_dir, retry)
|
||||
let staged = validate_restore(archive, &home_dir, retry)
|
||||
.await
|
||||
.context("backup staging failed before live files were changed")?;
|
||||
AsyncHandler::spawn_blocking(move || archive.extract_to(&home_dir))
|
||||
let installed = AsyncHandler::spawn_blocking(move || staged.install(&home_dir))
|
||||
.await
|
||||
.map_err(anyhow::Error::from)
|
||||
.and_then(|extracted| extracted.map_err(Into::into))
|
||||
.context("backup restore failed while writing live files; a complete restore may be required")
|
||||
.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?;
|
||||
@@ -435,7 +436,7 @@ pub async fn delete_local_backup(filename: String) -> Result<()> {
|
||||
}
|
||||
|
||||
fn snapshot_local_backup(path: &Path) -> Result<File> {
|
||||
// Both extractions must read the same bytes even if the local ZIP changes during restore.
|
||||
// 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)
|
||||
@@ -488,7 +489,9 @@ mod tests {
|
||||
let snapshot = snapshot_local_backup(source.path())?;
|
||||
std::fs::write(source.path(), b"replaced")?;
|
||||
let staging = tempfile::tempdir()?;
|
||||
BackupArchive::open(snapshot, RECOVERY_ENTRY_NAMES)?.extract_to(staging.path())?;
|
||||
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(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user