mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-04 21:30:06 +08:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74b815db59 | ||
|
|
e2ae9feb2a | ||
|
|
99def2004b | ||
|
|
084f8d36a7 | ||
|
|
112c5f0e13 | ||
|
|
0cba206e13 | ||
|
|
72c3653a8a | ||
|
|
6f81fb91b3 | ||
|
|
c6c963e9da | ||
|
|
287752daff |
@@ -265,14 +265,6 @@ jobs:
|
||||
node-version: '26.14.0'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Pnpm install and check
|
||||
run: |
|
||||
pnpm i
|
||||
pnpm run prebuild ${{ matrix.target }}
|
||||
|
||||
- name: Release ${{ env.TAG_CHANNEL }} Version
|
||||
run: pnpm release-version autobuild-latest
|
||||
|
||||
- name: 'Setup for linux'
|
||||
run: |-
|
||||
sudo ls -lR /etc/apt/
|
||||
@@ -317,6 +309,14 @@ jobs:
|
||||
gcc-arm-linux-gnueabihf \
|
||||
g++-arm-linux-gnueabihf
|
||||
|
||||
- name: Pnpm install and check
|
||||
run: |
|
||||
pnpm i
|
||||
pnpm run prebuild ${{ matrix.target }}
|
||||
|
||||
- name: Release ${{ env.TAG_CHANNEL }} Version
|
||||
run: pnpm release-version autobuild-latest
|
||||
|
||||
- name: Tauri Build for Linux
|
||||
run: |
|
||||
export PKG_CONFIG_ALLOW_CROSS=1
|
||||
|
||||
@@ -107,6 +107,14 @@ jobs:
|
||||
node-version: '26.14.0'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Add Rust Target
|
||||
if: github.event.inputs[matrix.input] == 'true'
|
||||
run: |
|
||||
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
|
||||
rustup target add ${{ matrix.target }} --toolchain 1.100.1 || rustup target add ${{ matrix.target }}
|
||||
rustup target list --installed
|
||||
echo "Rust target ${{ matrix.target }} installed."
|
||||
|
||||
- name: Pnpm install and check
|
||||
if: github.event.inputs[matrix.input] == 'true'
|
||||
run: |
|
||||
@@ -117,14 +125,6 @@ jobs:
|
||||
if: github.event.inputs[matrix.input] == 'true'
|
||||
run: pnpm release-version ${{ env.TAG_NAME }}
|
||||
|
||||
- name: Add Rust Target
|
||||
if: github.event.inputs[matrix.input] == 'true'
|
||||
run: |
|
||||
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
|
||||
rustup target add ${{ matrix.target }} --toolchain 1.100.1 || rustup target add ${{ matrix.target }}
|
||||
rustup target list --installed
|
||||
echo "Rust target ${{ matrix.target }} installed."
|
||||
|
||||
- name: Tauri build
|
||||
if: github.event.inputs[matrix.input] == 'true'
|
||||
uses: tauri-apps/tauri-action@v1
|
||||
|
||||
@@ -333,11 +333,6 @@ jobs:
|
||||
node-version: '26.14.0'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Pnpm install and check
|
||||
run: |
|
||||
pnpm i
|
||||
pnpm run prebuild ${{ matrix.target }}
|
||||
|
||||
- name: 'Setup for linux'
|
||||
run: |-
|
||||
sudo ls -lR /etc/apt/
|
||||
@@ -382,6 +377,11 @@ jobs:
|
||||
gcc-arm-linux-gnueabihf \
|
||||
g++-arm-linux-gnueabihf
|
||||
|
||||
- name: Pnpm install and check
|
||||
run: |
|
||||
pnpm i
|
||||
pnpm run prebuild ${{ matrix.target }}
|
||||
|
||||
- name: Build for Linux
|
||||
run: |
|
||||
export PKG_CONFIG_ALLOW_CROSS=1
|
||||
|
||||
Generated
+5
-142
@@ -98,12 +98,6 @@ 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"
|
||||
@@ -913,48 +907,6 @@ 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"
|
||||
@@ -1165,7 +1117,6 @@ dependencies = [
|
||||
"clash-verge-media-unlock",
|
||||
"clash-verge-profile",
|
||||
"clash-verge-profile-script",
|
||||
"clash-verge-profile-store",
|
||||
"clash-verge-proxy-view",
|
||||
"clash-verge-runtime-bundle",
|
||||
"clash-verge-signal",
|
||||
@@ -1225,7 +1176,6 @@ dependencies = [
|
||||
"tauri-plugin-wdio-webdriver",
|
||||
"tauri-plugin-window-state",
|
||||
"tauri-specta",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tokio-util",
|
||||
@@ -1244,11 +1194,7 @@ 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",
|
||||
]
|
||||
|
||||
@@ -1342,20 +1288,6 @@ dependencies = [
|
||||
"tristr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-profile-store"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"clash-verge-profile",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yaml_ng",
|
||||
"sha2 0.11.2",
|
||||
"tempfile",
|
||||
"thiserror 2.0.20",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-proxy-view"
|
||||
version = "0.1.0"
|
||||
@@ -1410,8 +1342,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clash_verge_service_ipc"
|
||||
version = "2.8.2"
|
||||
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?branch=main#3e06ff153e9cb19ae20e0a61f861b371d3f7b2aa"
|
||||
version = "2.8.3"
|
||||
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?rev=fd00f5af2363517e67de57a7ead67737175ac376#fd00f5af2363517e67de57a7ead67737175ac376"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"kode-bridge",
|
||||
@@ -2245,7 +2177,7 @@ dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users 0.5.2",
|
||||
"windows-sys 0.101.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2691,17 +2623,6 @@ 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"
|
||||
@@ -3773,28 +3694,6 @@ 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"
|
||||
@@ -4096,9 +3995,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "kode-bridge"
|
||||
version = "0.6.0"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b17456ae84ba9c0da0f189bf00d13019805b89563ba846cd15ccd8c4bd6a2713"
|
||||
checksum = "e125a6b7f2e7ce5d560ce9517083e27549345a6492ca68194cd96b42e3b27acb"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures",
|
||||
@@ -4106,7 +4005,6 @@ dependencies = [
|
||||
"httparse",
|
||||
"libc",
|
||||
"parking_lot 0.13.0",
|
||||
"path-tree",
|
||||
"pin-project-lite",
|
||||
"rand 0.10.2",
|
||||
"serde",
|
||||
@@ -4389,12 +4287,6 @@ 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"
|
||||
@@ -5264,15 +5156,6 @@ version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
|
||||
|
||||
[[package]]
|
||||
name = "path-tree"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a97453bc21a968f722df730bfe11bd08745cb50d1300b0df2bda131dece136"
|
||||
dependencies = [
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pathsearch"
|
||||
version = "0.2.0"
|
||||
@@ -6314,16 +6197,6 @@ 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"
|
||||
@@ -10162,16 +10035,6 @@ 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"
|
||||
|
||||
+1
-4
@@ -15,7 +15,6 @@ members = [
|
||||
"crates/clash-verge-profile-script",
|
||||
"crates/clash-verge-proxy-view",
|
||||
"crates/clash-verge-profile",
|
||||
"crates/clash-verge-profile-store",
|
||||
"crates/clash-verge-backup-archive",
|
||||
]
|
||||
resolver = "2"
|
||||
@@ -74,9 +73,8 @@ clash-verge-subscription = { path = "crates/clash-verge-subscription" }
|
||||
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 }
|
||||
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", rev = "fd00f5af2363517e67de57a7ead67737175ac376", version = "2.8.3", 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" }
|
||||
tracing = "0.1.44"
|
||||
@@ -115,7 +113,6 @@ tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849
|
||||
serde_json = { version = "1.0.154" }
|
||||
serde_yaml_ng = { version = "0.10.0" }
|
||||
sha2 = "0.11.2"
|
||||
tempfile = "3.27.0"
|
||||
specta = "=2.0.0-rc.26"
|
||||
socket2 = "0.6.5"
|
||||
|
||||
|
||||
+2
-4
@@ -23,15 +23,12 @@
|
||||
GitHub, so they never reach users. -->
|
||||
## v2.6.0
|
||||
|
||||
- 使用 2.6.x 服务模式时请安装随附的服务,2.5.x 客户端无法使用新版服务
|
||||
- **Mihomo 内核升级至 v1.19.34**
|
||||
|
||||
<details>
|
||||
<summary><strong> 🐞 修复问题 </strong></summary>
|
||||
|
||||
- 优化本地与 WebDAV 备份恢复,复用已校验的文件,减少重复解压
|
||||
- 修复订阅更新覆盖下载期间修改的设置,以及更新失败后遗留增强配置
|
||||
- 修复手动更新订阅时错误提示缺失或重复,显示订阅名称和失败原因
|
||||
- 优化订阅恢复失败提示,显示受影响的订阅名称
|
||||
- 修复「外部控制器」复制成功的提示一闪而过
|
||||
- 修复订阅的规则、代理组、节点编辑器快速连续操作时条目可能重复或错位
|
||||
- 修复检测更新后又发布新版时,应用内更新失败
|
||||
@@ -53,6 +50,7 @@
|
||||
|
||||
**🖥️ Windows**
|
||||
|
||||
- 修复 Windows 服务启动失败后自动切换内核,现显示原因并等待用户选择
|
||||
- 修复 Windows 普通用户因权限不足无法开启「开机自启」
|
||||
|
||||
**🍎 macOS**
|
||||
|
||||
@@ -4,14 +4,8 @@ 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"] }
|
||||
|
||||
@@ -4,12 +4,4 @@ pub enum ArchiveError {
|
||||
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,
|
||||
#[error("backup entry length differs from its declared size")]
|
||||
SizeMismatch,
|
||||
}
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
mod error;
|
||||
mod staged;
|
||||
|
||||
pub use error::ArchiveError;
|
||||
pub use staged::{InstallError, StagedBackup};
|
||||
|
||||
use std::{
|
||||
io::{self, Read, Seek, Write},
|
||||
path::{Component, Path},
|
||||
};
|
||||
use zip::{CompressionMethod, ZipArchive, ZipWriter, write::SimpleFileOptions};
|
||||
use std::io::{Seek, Write};
|
||||
use zip::{CompressionMethod, ZipWriter, write::SimpleFileOptions};
|
||||
|
||||
pub struct BackupWriter<W: Write + Seek> {
|
||||
zip: ZipWriter<W>,
|
||||
@@ -24,7 +19,7 @@ impl<W: Write + Seek> BackupWriter<W> {
|
||||
}
|
||||
|
||||
pub fn start_profile<'a>(&'a mut self, filename: &str) -> Result<impl Write + use<'a, W>, ArchiveError> {
|
||||
self.start_file(&["profiles/", filename].concat())
|
||||
self.start_file(&format!("profiles/{filename}"))
|
||||
}
|
||||
|
||||
pub fn start_file<'a>(&'a mut self, name: &str) -> Result<impl Write + use<'a, W>, ArchiveError> {
|
||||
@@ -37,148 +32,20 @@ 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() {
|
||||
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()
|
||||
};
|
||||
entries.push(staged::Entry {
|
||||
path,
|
||||
directory: entry.is_dir(),
|
||||
mode: entry.unix_mode(),
|
||||
});
|
||||
if size != entry.size() {
|
||||
return Err(ArchiveError::SizeMismatch);
|
||||
}
|
||||
}
|
||||
Ok(Self { zip, entries })
|
||||
}
|
||||
|
||||
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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Cursor;
|
||||
use std::io::{Cursor, Read as _};
|
||||
use zip::ZipArchive;
|
||||
|
||||
#[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(())
|
||||
}
|
||||
|
||||
#[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> {
|
||||
fn writes_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())?;
|
||||
let mut zip = ZipArchive::new(source)?;
|
||||
assert_eq!(zip.len(), 3);
|
||||
assert_eq!(zip.by_index(0)?.name()?, "profiles/");
|
||||
let profile_time = {
|
||||
@@ -193,7 +60,6 @@ mod tests {
|
||||
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(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,458 +0,0 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fn main() {
|
||||
println!("cargo::rerun-if-changed=locales");
|
||||
}
|
||||
@@ -85,6 +85,3 @@ tray:
|
||||
systemProxy: وكيل النظام
|
||||
tun: TUN
|
||||
profile: ملف تعريفي
|
||||
profileRecovery:
|
||||
named: يجب استعادة الاشتراك «{name}». راجع سجل التطبيق للاطلاع على التفاصيل.
|
||||
unknown: يجب استعادة أحد الاشتراكات، لكن تعذّر تحديده. راجع سجل التطبيق للاطلاع على التفاصيل.
|
||||
|
||||
@@ -85,6 +85,3 @@ tray:
|
||||
systemProxy: Systemproxy
|
||||
tun: TUN
|
||||
profile: Profil
|
||||
profileRecovery:
|
||||
named: Das Abonnement „{name}“ muss wiederhergestellt werden. Details stehen im Anwendungsprotokoll.
|
||||
unknown: Ein Abonnement muss wiederhergestellt werden, konnte aber nicht identifiziert werden. Details stehen im Anwendungsprotokoll.
|
||||
|
||||
@@ -85,6 +85,3 @@ tray:
|
||||
systemProxy: System Proxy
|
||||
tun: TUN
|
||||
profile: Profile
|
||||
profileRecovery:
|
||||
named: Subscription “{name}” needs recovery. See the application log for details.
|
||||
unknown: Subscription recovery is required. The affected subscription could not be identified. See the application log for details.
|
||||
|
||||
@@ -85,6 +85,3 @@ tray:
|
||||
systemProxy: Proxy del sistema
|
||||
tun: TUN
|
||||
profile: Perfil
|
||||
profileRecovery:
|
||||
named: Hay que recuperar la suscripción «{name}». Consulta el registro de la aplicación para más detalles.
|
||||
unknown: Hay que recuperar una suscripción, pero no se pudo identificar cuál. Consulta el registro de la aplicación para más detalles.
|
||||
|
||||
@@ -85,6 +85,3 @@ tray:
|
||||
systemProxy: پروکسی سیستم
|
||||
tun: TUN
|
||||
profile: پروفایل
|
||||
profileRecovery:
|
||||
named: اشتراک «{name}» باید بازیابی شود. برای جزئیات، گزارش برنامه را ببینید.
|
||||
unknown: بازیابی اشتراک لازم است، اما اشتراک موردنظر شناسایی نشد. برای جزئیات، گزارش برنامه را ببینید.
|
||||
|
||||
@@ -85,6 +85,3 @@ tray:
|
||||
systemProxy: Proksi Sistem
|
||||
tun: TUN
|
||||
profile: Profil
|
||||
profileRecovery:
|
||||
named: Langganan “{name}” perlu dipulihkan. Lihat log aplikasi untuk detailnya.
|
||||
unknown: Langganan perlu dipulihkan, tetapi langganan yang terdampak tidak dapat diidentifikasi. Lihat log aplikasi untuk detailnya.
|
||||
|
||||
@@ -85,6 +85,3 @@ tray:
|
||||
systemProxy: システムプロキシ
|
||||
tun: TUN
|
||||
profile: プロファイル
|
||||
profileRecovery:
|
||||
named: サブスクリプション「{name}」の復旧が必要です。詳細はアプリのログを確認してください。
|
||||
unknown: サブスクリプションの復旧が必要ですが、対象を特定できません。詳細はアプリのログを確認してください。
|
||||
|
||||
@@ -85,6 +85,3 @@ tray:
|
||||
systemProxy: 시스템 프록시
|
||||
tun: TUN
|
||||
profile: 프로필
|
||||
profileRecovery:
|
||||
named: “{name}” 구독을 복구해야 합니다. 자세한 내용은 앱 로그를 확인하세요.
|
||||
unknown: 구독을 복구해야 하지만 해당 구독을 식별할 수 없습니다. 자세한 내용은 앱 로그를 확인하세요.
|
||||
|
||||
@@ -85,6 +85,3 @@ tray:
|
||||
systemProxy: Proxy do sistema
|
||||
tun: TUN
|
||||
profile: Perfil
|
||||
profileRecovery:
|
||||
named: É necessário recuperar a assinatura “{name}”. Consulte o registro do aplicativo para mais detalhes.
|
||||
unknown: É necessário recuperar uma assinatura, mas não foi possível identificá-la. Consulte o registro do aplicativo para mais detalhes.
|
||||
|
||||
@@ -85,6 +85,3 @@ tray:
|
||||
systemProxy: Системный прокси
|
||||
tun: TUN
|
||||
profile: Профиль
|
||||
profileRecovery:
|
||||
named: Подписку «{name}» нужно восстановить. Подробности в журнале приложения.
|
||||
unknown: Не удалось определить, какую подписку необходимо восстановить. Подробности в журнале приложения.
|
||||
|
||||
@@ -85,6 +85,3 @@ tray:
|
||||
systemProxy: Sistem Vekil'i
|
||||
tun: TUN
|
||||
profile: Profil
|
||||
profileRecovery:
|
||||
named: “{name}” aboneliğinin kurtarılması gerekiyor. Ayrıntılar için uygulama günlüğüne bakın.
|
||||
unknown: Kurtarılması gereken abonelik belirlenemedi. Ayrıntılar için uygulama günlüğüne bakın.
|
||||
|
||||
@@ -85,6 +85,3 @@ tray:
|
||||
systemProxy: Системалы прокси
|
||||
tun: TUN
|
||||
profile: Профиль
|
||||
profileRecovery:
|
||||
named: «{name}» язылуын торгызырга кирәк. Тулырак мәгълүмат кушымта журналында.
|
||||
unknown: Кайсы язылуны торгызырга кирәклеген билгеләп булмады. Тулырак мәгълүмат кушымта журналында.
|
||||
|
||||
@@ -85,6 +85,3 @@ tray:
|
||||
systemProxy: 系统代理
|
||||
tun: TUN
|
||||
profile: 订阅
|
||||
profileRecovery:
|
||||
named: 订阅「{name}」需要恢复,详情请查看应用日志。
|
||||
unknown: 订阅需要恢复,但无法识别受影响的订阅。详情请查看应用日志。
|
||||
|
||||
@@ -85,6 +85,3 @@ tray:
|
||||
systemProxy: 系統代理
|
||||
tun: 虛擬網路介面卡
|
||||
profile: 訂閱
|
||||
profileRecovery:
|
||||
named: 訂閱「{name}」需要復原,詳情請查看應用程式記錄。
|
||||
unknown: 訂閱需要復原,但無法識別受影響的訂閱。詳情請查看應用程式記錄。
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
[package]
|
||||
name = "clash-verge-profile-store"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[features]
|
||||
test-support = []
|
||||
|
||||
[dependencies]
|
||||
thiserror = { workspace = true }
|
||||
clash-verge-profile = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
serde_yaml_ng = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = { workspace = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61.2", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_System_WindowsProgramming",
|
||||
] }
|
||||
@@ -1,78 +0,0 @@
|
||||
use std::{io, path::PathBuf};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum StoreError {
|
||||
#[error("could not recover subscription “{name}”: {source}")]
|
||||
NamedRecovery { name: String, source: Box<Self> },
|
||||
#[error(transparent)]
|
||||
Io(#[from] io::Error),
|
||||
#[error("{operation} {}", path.display())]
|
||||
PathIo {
|
||||
operation: &'static str,
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
#[error(transparent)]
|
||||
IndexYaml(#[from] serde_yaml_ng::Error),
|
||||
#[error(transparent)]
|
||||
SerializeDecision(#[from] serde_json::Error),
|
||||
#[error("invalid refresh decision")]
|
||||
InvalidDecision(#[source] serde_json::Error),
|
||||
#[error(transparent)]
|
||||
ProfileNotFound(#[from] clash_verge_profile::ProfileNotFound),
|
||||
#[error("index and body must share a filesystem")]
|
||||
DifferentVolumes,
|
||||
#[cfg(windows)]
|
||||
#[error("profile recovery requires a supported NTFS volume")]
|
||||
UnsupportedVolume,
|
||||
#[error("profile UID is shared")]
|
||||
SharedUid,
|
||||
#[error("profile is missing from the on-disk index")]
|
||||
ProfileMissingFromDisk,
|
||||
#[error("profile source is ambiguous")]
|
||||
AmbiguousProfile,
|
||||
#[error("profile must be remote")]
|
||||
NotRemote,
|
||||
#[error("body filename changed")]
|
||||
FilenameChanged,
|
||||
#[error("body filename is shared")]
|
||||
SharedFilename,
|
||||
#[error("new body path already exists")]
|
||||
ExistingBodyPath,
|
||||
#[error("decision is oversized")]
|
||||
OversizedDecision,
|
||||
#[error("unknown refresh decision version")]
|
||||
UnknownDecisionVersion,
|
||||
#[error("refresh decision target does not match the staged index")]
|
||||
DecisionTargetMismatch,
|
||||
#[error("staged content checksum mismatch")]
|
||||
StagedChecksumMismatch,
|
||||
#[error("refresh marker is missing for an inconsistent pair")]
|
||||
InconsistentUnmarkedPair,
|
||||
#[error("journal is not a directory")]
|
||||
InvalidJournal,
|
||||
#[error("decision is not a regular file")]
|
||||
InvalidDecisionFile,
|
||||
#[error("invalid profile filename")]
|
||||
InvalidFilename,
|
||||
#[cfg(windows)]
|
||||
#[error("invalid Windows profile filename")]
|
||||
InvalidWindowsFilename,
|
||||
#[error("missing profile filename")]
|
||||
MissingFilename,
|
||||
#[error("UID or filename is shared")]
|
||||
SharedUidOrFilename,
|
||||
#[error("profile body is hard linked")]
|
||||
HardLinkedBody,
|
||||
#[error("profile file has a filesystem alias")]
|
||||
AliasedBody,
|
||||
#[error("live content changed outside the refresh transaction: {}", .0.display())]
|
||||
LiveContentChanged(PathBuf),
|
||||
#[error("expected directory {}", .0.display())]
|
||||
ExpectedDirectory(PathBuf),
|
||||
#[error("expected regular file {}", .0.display())]
|
||||
ExpectedRegularFile(PathBuf),
|
||||
#[error("missing {}", .0.display())]
|
||||
MissingFile(PathBuf),
|
||||
}
|
||||
@@ -1,820 +0,0 @@
|
||||
//! Recoverable replacement of one subscription body and the profile index.
|
||||
#![cfg(any(unix, windows))]
|
||||
|
||||
mod error;
|
||||
mod platform;
|
||||
|
||||
pub use error::StoreError;
|
||||
|
||||
use clash_verge_profile::IProfiles;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest as _, Sha256};
|
||||
use std::{
|
||||
fs::{self, File, Permissions},
|
||||
io::{self, Write as _},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
pub const RECOVERY_JOURNAL_NAME: &str = ".profile-refresh";
|
||||
pub const RECOVERY_ENTRY_NAMES: &[&str] = &[RECOVERY_JOURNAL_NAME, RECOVERY_LOCK_NAME];
|
||||
|
||||
const RECOVERY_LOCK_NAME: &str = ".profile-refresh.lock";
|
||||
const DECISION: &str = "decision";
|
||||
const MAX_DECISION_BYTES: u64 = 4096;
|
||||
const PROFILES: &str = "profiles";
|
||||
const INDEX: &str = "profiles.yaml";
|
||||
const BODY_NEXT: &str = "body.next";
|
||||
const INDEX_NEXT: &str = "index.next";
|
||||
const DECISION_NEXT: &str = "decision.next";
|
||||
const DECISION_BUILDING: &str = "decision.building";
|
||||
const APPLY: &str = "body.apply";
|
||||
const MAX_COMPANIONS: usize = 5;
|
||||
|
||||
type Result<T> = std::result::Result<T, StoreError>;
|
||||
|
||||
type Checkpoint<'a> = dyn FnMut(&'static str) -> Result<()> + 'a;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum CommitOutcome {
|
||||
Committed,
|
||||
CommittedCleanupPending(StoreError),
|
||||
Retryable(StoreError),
|
||||
RetryCleanupFailed(StoreError),
|
||||
NeedsRecovery(StoreError),
|
||||
}
|
||||
|
||||
enum InstallOutcome {
|
||||
Installed,
|
||||
Reverted(StoreError),
|
||||
}
|
||||
|
||||
pub struct Session {
|
||||
root: PathBuf,
|
||||
_lock: File,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Decision {
|
||||
version: u32,
|
||||
uid: String,
|
||||
file: String,
|
||||
old_body_digest: Option<[u8; 32]>,
|
||||
old_index_digest: [u8; 32],
|
||||
body_digest: [u8; 32],
|
||||
index_digest: [u8; 32],
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
companions: Vec<Companion>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Companion {
|
||||
uid: String,
|
||||
digest: [u8; 32],
|
||||
}
|
||||
|
||||
fn companion_file<'a>(profiles: &'a IProfiles, parent: &str, uid: &str) -> Result<&'a str> {
|
||||
let item = profiles.get_item(uid)?;
|
||||
let options = profiles
|
||||
.get_item(parent)?
|
||||
.option
|
||||
.as_ref()
|
||||
.ok_or(StoreError::DecisionTargetMismatch)?;
|
||||
let reference = match item.itype.as_deref() {
|
||||
Some("merge") => &options.merge,
|
||||
Some("script") => &options.script,
|
||||
Some("rules") => &options.rules,
|
||||
Some("proxies") => &options.proxies,
|
||||
Some("groups") => &options.groups,
|
||||
_ => return Err(StoreError::DecisionTargetMismatch),
|
||||
};
|
||||
let file = item.file.as_deref().ok_or(StoreError::MissingFilename)?;
|
||||
validate_filename(file)?;
|
||||
if reference.as_deref() != Some(uid)
|
||||
|| profiles
|
||||
.items
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|other| other.uid.as_deref() == Some(uid) || other.file.as_deref() == Some(file))
|
||||
.count()
|
||||
!= 1
|
||||
{
|
||||
return Err(StoreError::DecisionTargetMismatch);
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn open(root: &Path) -> Result<Self> {
|
||||
Self::open_with_checkpoint(root, &mut |_| Ok(()))
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-support")]
|
||||
#[doc(hidden)]
|
||||
pub fn open_observed(root: &Path, checkpoint: &mut Checkpoint<'_>) -> Result<Self> {
|
||||
Self::open_with_checkpoint(root, checkpoint)
|
||||
}
|
||||
|
||||
fn open_with_checkpoint(root: &Path, checkpoint: &mut Checkpoint<'_>) -> Result<Self> {
|
||||
let root = root.canonicalize()?;
|
||||
let root_metadata = directory(&root)?;
|
||||
let profiles = root.join(PROFILES);
|
||||
let profile_metadata = directory(&profiles)?;
|
||||
if platform::volume(&root, &root_metadata)? != platform::volume(&profiles, &profile_metadata)? {
|
||||
return Err(StoreError::DifferentVolumes);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if !platform::supports_redo(&root)? {
|
||||
let source = StoreError::UnsupportedVolume;
|
||||
return Err(match pending_refresh_name(&root) {
|
||||
Some(name) => StoreError::NamedRecovery {
|
||||
name,
|
||||
source: Box::new(source),
|
||||
},
|
||||
None => source,
|
||||
});
|
||||
}
|
||||
let lock = platform::open_lock(&root.join(RECOVERY_LOCK_NAME))?;
|
||||
lock.lock()?;
|
||||
let session = Self { root, _lock: lock };
|
||||
session
|
||||
.recover(checkpoint)
|
||||
.map_err(|error| match refresh_name(&session.root) {
|
||||
Some(name) => StoreError::NamedRecovery {
|
||||
name,
|
||||
source: Box::new(error),
|
||||
},
|
||||
None => error,
|
||||
})?;
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
fn journal(&self) -> PathBuf {
|
||||
self.root.join(RECOVERY_JOURNAL_NAME)
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-support")]
|
||||
#[doc(hidden)]
|
||||
pub fn snapshot(&self, uid: &str) -> Result<(IProfiles, Vec<u8>)> {
|
||||
let profiles = serde_yaml_ng::from_slice(&fs::read(self.root.join(INDEX))?)?;
|
||||
let file = body_filename(&profiles, uid)?;
|
||||
let body = fs::read(self.root.join(PROFILES).join(file))?;
|
||||
Ok((profiles, body))
|
||||
}
|
||||
|
||||
pub fn commit_refresh(self, uid: &str, candidate: &IProfiles, body: &[u8]) -> CommitOutcome {
|
||||
let outcome = self.commit_with_checkpoint(uid, candidate, body, &mut |_| Ok(()));
|
||||
self.finish_commit(outcome)
|
||||
}
|
||||
|
||||
fn finish_commit(&self, outcome: CommitOutcome) -> CommitOutcome {
|
||||
match outcome {
|
||||
CommitOutcome::Retryable(error) => match self.recover(&mut |_| Ok(())) {
|
||||
Ok(()) => CommitOutcome::Retryable(error),
|
||||
Err(cleanup) => CommitOutcome::RetryCleanupFailed(cleanup),
|
||||
},
|
||||
CommitOutcome::CommittedCleanupPending(error) => match self.recover(&mut |_| Ok(())) {
|
||||
Ok(()) => CommitOutcome::Committed,
|
||||
Err(_) => CommitOutcome::CommittedCleanupPending(error),
|
||||
},
|
||||
outcome => outcome,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-support")]
|
||||
#[doc(hidden)]
|
||||
pub fn commit_observed(
|
||||
self,
|
||||
uid: &str,
|
||||
candidate: &IProfiles,
|
||||
body: &[u8],
|
||||
checkpoint: &mut Checkpoint<'_>,
|
||||
) -> CommitOutcome {
|
||||
self.commit_with_checkpoint(uid, candidate, body, checkpoint)
|
||||
}
|
||||
|
||||
fn commit_with_checkpoint(
|
||||
&self,
|
||||
uid: &str,
|
||||
candidate: &IProfiles,
|
||||
body: &[u8],
|
||||
checkpoint: &mut Checkpoint<'_>,
|
||||
) -> CommitOutcome {
|
||||
let before = self.prepare(uid, candidate, body, checkpoint);
|
||||
if let Err(error) = before {
|
||||
return CommitOutcome::Retryable(error);
|
||||
}
|
||||
let journal = self.journal();
|
||||
if let Err(error) = fs::hard_link(journal.join(DECISION_NEXT), journal.join(DECISION)) {
|
||||
return CommitOutcome::Retryable(error.into());
|
||||
}
|
||||
let published = (|| {
|
||||
checkpoint("decision-created")?;
|
||||
platform::sync_dir(&journal)?;
|
||||
checkpoint("decision-synced")?;
|
||||
self.install(checkpoint)
|
||||
})();
|
||||
let installed = match published {
|
||||
Ok(installed) => installed,
|
||||
Err(error) => return CommitOutcome::NeedsRecovery(error),
|
||||
};
|
||||
match (installed, self.disarm_and_clean(checkpoint)) {
|
||||
(InstallOutcome::Installed, Ok(())) => CommitOutcome::Committed,
|
||||
(InstallOutcome::Installed, Err(error)) => CommitOutcome::CommittedCleanupPending(error),
|
||||
(InstallOutcome::Reverted(rejection), Ok(())) => CommitOutcome::Retryable(rejection),
|
||||
(InstallOutcome::Reverted(_), Err(error)) => CommitOutcome::NeedsRecovery(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare(&self, uid: &str, candidate: &IProfiles, body: &[u8], checkpoint: &mut Checkpoint<'_>) -> Result<()> {
|
||||
// Check directory flush access before creating a Windows journal.
|
||||
#[cfg(windows)]
|
||||
{
|
||||
platform::sync_dir(&self.root)?;
|
||||
platform::sync_dir(&self.root.join(PROFILES))?;
|
||||
}
|
||||
let index_path = self.root.join(INDEX);
|
||||
let old_index = fs::read(&index_path)?;
|
||||
let current: IProfiles = serde_yaml_ng::from_slice(&old_index)?;
|
||||
let file = body_filename(candidate, uid)?;
|
||||
let mut exact = current
|
||||
.items
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|item| item.uid.as_deref() == Some(uid));
|
||||
let old_item = if let Some(item) = exact.next() {
|
||||
if exact.next().is_some() {
|
||||
return Err(StoreError::SharedUid);
|
||||
}
|
||||
item
|
||||
} else {
|
||||
// Loading an old index may assign a UID without rewriting the file.
|
||||
let new_item = candidate.get_item(uid)?;
|
||||
let mut legacy = current.items.iter().flatten().filter(|item| {
|
||||
item.uid.is_none()
|
||||
&& item.itype.as_deref() == Some("remote")
|
||||
&& item.url == new_item.url
|
||||
&& item.file.as_deref().is_none_or(|old| old == file)
|
||||
});
|
||||
let item = legacy.next().ok_or(StoreError::ProfileMissingFromDisk)?;
|
||||
if legacy.next().is_some() {
|
||||
return Err(StoreError::AmbiguousProfile);
|
||||
}
|
||||
item
|
||||
};
|
||||
if old_item.itype.as_deref() != Some("remote") {
|
||||
return Err(StoreError::NotRemote);
|
||||
}
|
||||
if let Some(old_file) = old_item.file.as_deref()
|
||||
&& old_file != file
|
||||
{
|
||||
return Err(StoreError::FilenameChanged);
|
||||
}
|
||||
if !current
|
||||
.items
|
||||
.iter()
|
||||
.flatten()
|
||||
.all(|item| std::ptr::eq(item, old_item) || item.file.as_deref() != Some(file))
|
||||
{
|
||||
return Err(StoreError::SharedFilename);
|
||||
}
|
||||
let profiles_dir = self.root.join(PROFILES);
|
||||
let metadata = unshared_body(&profiles_dir, ¤t, file, 1)?;
|
||||
unshared_body(&profiles_dir, candidate, file, 1)?;
|
||||
let index_permissions = regular(&index_path)?.permissions();
|
||||
let old_body_digest = optional_file_digest(&profiles_dir.join(file))?;
|
||||
if old_item.file.is_none() && old_body_digest.is_some() {
|
||||
return Err(StoreError::ExistingBodyPath);
|
||||
}
|
||||
let mut index = b"# Profiles Config for Clash Verge\n\n".to_vec();
|
||||
serde_yaml_ng::to_writer(&mut index, candidate)?;
|
||||
let mut companions = Vec::new();
|
||||
let mut templates = Vec::new();
|
||||
for item in candidate.items.iter().flatten() {
|
||||
let Some(data) = &item.file_data else { continue };
|
||||
let id = item.uid.as_deref().ok_or(StoreError::DecisionTargetMismatch)?;
|
||||
let file = companion_file(candidate, uid, id)?;
|
||||
if current
|
||||
.items
|
||||
.iter()
|
||||
.flatten()
|
||||
.any(|old| old.uid.as_deref() == Some(id) || old.file.as_deref() == Some(file))
|
||||
|| optional_regular(&profiles_dir.join(file))?.is_some()
|
||||
{
|
||||
return Err(StoreError::ExistingBodyPath);
|
||||
}
|
||||
let bytes = data.as_bytes();
|
||||
companions.push(Companion {
|
||||
uid: id.to_owned(),
|
||||
digest: Sha256::digest(bytes).into(),
|
||||
});
|
||||
templates.push(bytes);
|
||||
}
|
||||
if companions.len() > MAX_COMPANIONS {
|
||||
return Err(StoreError::DecisionTargetMismatch);
|
||||
}
|
||||
let decision = Decision {
|
||||
version: if companions.is_empty() { 1 } else { 2 },
|
||||
companions,
|
||||
uid: uid.into(),
|
||||
file: file.into(),
|
||||
old_body_digest,
|
||||
old_index_digest: Sha256::digest(&old_index).into(),
|
||||
body_digest: Sha256::digest(body).into(),
|
||||
index_digest: Sha256::digest(&index).into(),
|
||||
};
|
||||
|
||||
let decision = serde_json::to_vec(&decision)?;
|
||||
if decision.len() as u64 > MAX_DECISION_BYTES {
|
||||
return Err(StoreError::OversizedDecision);
|
||||
}
|
||||
let journal = self.journal();
|
||||
platform::create_dir(&journal)?;
|
||||
platform::sync_dir(&self.root)?;
|
||||
checkpoint("journal-created")?;
|
||||
write_new(&journal.join(BODY_NEXT), body, metadata.map(|meta| meta.permissions()))?;
|
||||
checkpoint("body-staged")?;
|
||||
for (slot, bytes) in templates.into_iter().enumerate() {
|
||||
write_new(&journal.join(format!("companion.{slot}")), bytes, None)?;
|
||||
}
|
||||
write_new(&journal.join(INDEX_NEXT), &index, Some(index_permissions))?;
|
||||
checkpoint("index-staged")?;
|
||||
write_new(&journal.join(DECISION_BUILDING), &decision, None)?;
|
||||
platform::replace(journal.join(DECISION_BUILDING), journal.join(DECISION_NEXT))?;
|
||||
// A decision that survives interruption must only reference already-synced inputs.
|
||||
platform::sync_dir(&journal)?;
|
||||
checkpoint("prepared")
|
||||
}
|
||||
|
||||
fn install(&self, checkpoint: &mut Checkpoint<'_>) -> Result<InstallOutcome> {
|
||||
let journal = self.journal();
|
||||
let decision = read_decision(&journal.join(DECISION))?;
|
||||
let index_next = journal.join(INDEX_NEXT);
|
||||
let (index, index_permissions) = verified(&index_next, decision.index_digest)?;
|
||||
let candidate: IProfiles = serde_yaml_ng::from_slice(&index)?;
|
||||
if body_filename(&candidate, &decision.uid)? != decision.file {
|
||||
return Err(StoreError::DecisionTargetMismatch);
|
||||
}
|
||||
|
||||
let profiles_dir = self.root.join(PROFILES);
|
||||
let body_path = profiles_dir.join(&decision.file);
|
||||
let index_path = self.root.join(INDEX);
|
||||
let apply = journal.join(APPLY);
|
||||
let body_installed = verify_live(&body_path, decision.old_body_digest, decision.body_digest)?;
|
||||
let index_installed = verify_live(&index_path, Some(decision.old_index_digest), decision.index_digest)?;
|
||||
let can_revert_new_body = decision.old_body_digest.is_none()
|
||||
&& (!index_installed || decision.old_index_digest == decision.index_digest);
|
||||
if !can_revert_new_body {
|
||||
unshared_body(&profiles_dir, &candidate, &decision.file, 1)?;
|
||||
}
|
||||
|
||||
let body_next = journal.join(BODY_NEXT);
|
||||
if body_installed {
|
||||
if file_digest(&body_next)? != decision.body_digest {
|
||||
return Err(StoreError::StagedChecksumMismatch);
|
||||
}
|
||||
// Equality alone does not establish durability of a prior in-place edit.
|
||||
platform::sync_file(&body_path)?;
|
||||
} else {
|
||||
remove_file_if_exists(&apply)?;
|
||||
copy_verified(&body_next, &apply, decision.body_digest)?;
|
||||
platform::replace(&apply, &body_path).map_err(|source| StoreError::PathIo {
|
||||
operation: "replace",
|
||||
path: body_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
checkpoint("body-replaced")?;
|
||||
if can_revert_new_body {
|
||||
// Native aliases of a missing file only resolve once the file exists.
|
||||
let check = (|| {
|
||||
unshared_body(&profiles_dir, &candidate, &decision.file, 1)?;
|
||||
if !index_installed {
|
||||
let (index, _) = verified(&index_path, decision.old_index_digest)?;
|
||||
let current = serde_yaml_ng::from_slice(&index)?;
|
||||
unshared_body(&profiles_dir, ¤t, &decision.file, 1)?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(error) = check {
|
||||
match error {
|
||||
StoreError::AliasedBody | StoreError::InvalidFilename => {}
|
||||
#[cfg(windows)]
|
||||
StoreError::InvalidWindowsFilename => {}
|
||||
_ => return Err(error),
|
||||
}
|
||||
fs::remove_file(&body_path)?;
|
||||
platform::sync_dir(&profiles_dir)?;
|
||||
return Ok(InstallOutcome::Reverted(error));
|
||||
}
|
||||
}
|
||||
let old_companion_index: Option<IProfiles> = if !index_installed && !decision.companions.is_empty() {
|
||||
let (index, _) = verified(&index_path, decision.old_index_digest)?;
|
||||
Some(serde_yaml_ng::from_slice(&index)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
for (slot, companion) in decision.companions.iter().enumerate() {
|
||||
let file = companion_file(&candidate, &decision.uid, &companion.uid)?;
|
||||
let staged = journal.join(format!("companion.{slot}"));
|
||||
if file_digest(&staged)? != companion.digest {
|
||||
return Err(StoreError::StagedChecksumMismatch);
|
||||
}
|
||||
let target = profiles_dir.join(file);
|
||||
match fs::hard_link(&staged, &target) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
|
||||
if platform::file_identity(&target, ®ular(&target)?)?
|
||||
!= platform::file_identity(&staged, ®ular(&staged)?)?
|
||||
{
|
||||
return Err(StoreError::LiveContentChanged(target));
|
||||
}
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
unshared_body(&profiles_dir, &candidate, file, 2)?;
|
||||
if let Some(old) = &old_companion_index {
|
||||
unshared_body(&profiles_dir, old, file, 2)?;
|
||||
}
|
||||
checkpoint("companion-installed")?;
|
||||
}
|
||||
if index_installed {
|
||||
platform::sync_file(&index_path)?;
|
||||
} else {
|
||||
// The body rename consumed the scratch file. Replay can discard it at either step.
|
||||
remove_file_if_exists(&apply)?;
|
||||
write_new(&apply, &index, Some(index_permissions))?;
|
||||
platform::replace(&apply, &index_path).map_err(|source| StoreError::PathIo {
|
||||
operation: "replace",
|
||||
path: index_path,
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
checkpoint("index-replaced")?;
|
||||
platform::sync_dir(&profiles_dir)?;
|
||||
checkpoint("body-synced")?;
|
||||
platform::sync_dir(&self.root)?;
|
||||
checkpoint("index-synced")?;
|
||||
Ok(InstallOutcome::Installed)
|
||||
}
|
||||
|
||||
fn disarm_and_clean(&self, checkpoint: &mut Checkpoint<'_>) -> Result<()> {
|
||||
let journal = self.journal();
|
||||
fs::remove_file(journal.join(DECISION))?;
|
||||
checkpoint("decision-removed")?;
|
||||
platform::sync_dir(&journal)?;
|
||||
checkpoint("disarmed")?;
|
||||
self.remove_journal()?;
|
||||
checkpoint("journal-removed")
|
||||
}
|
||||
|
||||
fn remove_journal(&self) -> Result<()> {
|
||||
let journal = self.journal();
|
||||
for name in [
|
||||
DECISION_NEXT,
|
||||
DECISION_BUILDING,
|
||||
BODY_NEXT,
|
||||
INDEX_NEXT,
|
||||
APPLY,
|
||||
"index.apply", // Older v1 journals used a separate scratch file for the index.
|
||||
] {
|
||||
remove_file_if_exists(&journal.join(name))?;
|
||||
}
|
||||
match fs::remove_dir(&journal) {
|
||||
Err(error) if error.kind() == io::ErrorKind::DirectoryNotEmpty => {
|
||||
for slot in 0..MAX_COMPANIONS {
|
||||
remove_file_if_exists(&journal.join(format!("companion.{slot}")))?;
|
||||
}
|
||||
fs::remove_dir(&journal)?;
|
||||
}
|
||||
result => result?,
|
||||
}
|
||||
Ok(platform::sync_dir(&self.root)?)
|
||||
}
|
||||
|
||||
fn check_unmarked_pair(&self, intent: &Decision) -> Result<()> {
|
||||
let body = optional_file_digest(&self.root.join(PROFILES).join(&intent.file))?;
|
||||
let index = file_digest(&self.root.join(INDEX))?;
|
||||
let old_pair = body == intent.old_body_digest && index == intent.old_index_digest;
|
||||
let new_pair = body == Some(intent.body_digest) && index == intent.index_digest;
|
||||
if !old_pair && !new_pair {
|
||||
return Err(StoreError::InconsistentUnmarkedPair);
|
||||
}
|
||||
if new_pair && !intent.companions.is_empty() {
|
||||
let (bytes, _) = verified(&self.root.join(INDEX), intent.index_digest)?;
|
||||
let candidate = serde_yaml_ng::from_slice(&bytes)?;
|
||||
for companion in &intent.companions {
|
||||
let file = companion_file(&candidate, &intent.uid, &companion.uid)?;
|
||||
let path = self.root.join(PROFILES).join(file);
|
||||
if optional_file_digest(&path)? != Some(companion.digest) {
|
||||
return Err(StoreError::LiveContentChanged(path));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn recover(&self, checkpoint: &mut Checkpoint<'_>) -> Result<()> {
|
||||
let journal = self.journal();
|
||||
match fs::symlink_metadata(&journal) {
|
||||
Ok(metadata) => {
|
||||
if !metadata.is_dir() || platform::is_reparse(&metadata) {
|
||||
return Err(StoreError::InvalidJournal);
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
match fs::symlink_metadata(journal.join(DECISION)) {
|
||||
Ok(metadata) => {
|
||||
if !metadata.is_file() || platform::is_reparse(&metadata) {
|
||||
return Err(StoreError::InvalidDecisionFile);
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
// A previous process may have unlinked the decision before its directory sync.
|
||||
platform::sync_dir(&journal)?;
|
||||
let intent = journal.join(DECISION_NEXT);
|
||||
match fs::symlink_metadata(&intent) {
|
||||
Ok(_) => self.check_unmarked_pair(&read_decision(&intent)?)?,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => (),
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
return self.remove_journal();
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
// A visible decision may have survived a process interruption before its directory sync.
|
||||
platform::sync_dir(&journal)?;
|
||||
self.install(checkpoint)?;
|
||||
self.disarm_and_clean(checkpoint)
|
||||
}
|
||||
}
|
||||
|
||||
fn read_decision(path: &Path) -> Result<Decision> {
|
||||
if regular(path)?.len() > MAX_DECISION_BYTES {
|
||||
return Err(StoreError::OversizedDecision);
|
||||
}
|
||||
let decision: Decision = serde_json::from_slice(&fs::read(path)?).map_err(StoreError::InvalidDecision)?;
|
||||
if !matches!(
|
||||
(decision.version, decision.companions.len()),
|
||||
(1, 0) | (2, 1..=MAX_COMPANIONS)
|
||||
) {
|
||||
return Err(StoreError::UnknownDecisionVersion);
|
||||
}
|
||||
validate_filename(&decision.file)?;
|
||||
Ok(decision)
|
||||
}
|
||||
|
||||
fn validate_filename(file: &str) -> Result<()> {
|
||||
if file.is_empty()
|
||||
|| matches!(file, "." | "..")
|
||||
|| file.contains(['/', '\\', '\0'])
|
||||
|| (cfg!(windows) && file.contains(':'))
|
||||
{
|
||||
return Err(StoreError::InvalidFilename);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let stem = file
|
||||
.split('.')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.trim_end_matches(' ')
|
||||
.to_ascii_uppercase();
|
||||
let is_port_device = ["COM", "LPT"].iter().any(|prefix| {
|
||||
stem.strip_prefix(prefix).is_some_and(|suffix| {
|
||||
matches!(
|
||||
suffix,
|
||||
"1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
|
||||
)
|
||||
})
|
||||
});
|
||||
if file.ends_with([' ', '.'])
|
||||
|| file.contains(['<', '>', '"', '|', '?', '*'])
|
||||
|| file.bytes().any(|byte| byte < 32)
|
||||
|| matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$")
|
||||
|| is_port_device
|
||||
{
|
||||
return Err(StoreError::InvalidWindowsFilename);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn body_filename<'a>(profiles: &'a IProfiles, uid: &str) -> Result<&'a str> {
|
||||
let item = profiles.get_item(uid)?;
|
||||
if item.itype.as_deref() != Some("remote") {
|
||||
return Err(StoreError::NotRemote);
|
||||
}
|
||||
let file = item.file.as_deref().ok_or(StoreError::MissingFilename)?;
|
||||
validate_filename(file)?;
|
||||
let owners = profiles
|
||||
.items
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|item| item.uid.as_deref() == Some(uid) || item.file.as_deref() == Some(file))
|
||||
.count();
|
||||
if owners != 1 {
|
||||
return Err(StoreError::SharedUidOrFilename);
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
fn unshared_body(dir: &Path, profiles: &IProfiles, file: &str, expected_links: u64) -> Result<Option<fs::Metadata>> {
|
||||
let mut path = dir.join(file);
|
||||
let target = optional_regular(&path)?;
|
||||
let identity = target
|
||||
.as_ref()
|
||||
.map(|metadata| platform::file_identity(&path, metadata))
|
||||
.transpose()?;
|
||||
if identity
|
||||
.as_ref()
|
||||
.is_some_and(|identity| identity.links != expected_links)
|
||||
{
|
||||
return Err(StoreError::HardLinkedBody);
|
||||
}
|
||||
for other in profiles.items.iter().flatten().filter_map(|item| item.file.as_deref()) {
|
||||
if other == file {
|
||||
continue;
|
||||
}
|
||||
// Other entries may use native filenames, but they must stay in this directory.
|
||||
let mut components = Path::new(other).components();
|
||||
if !matches!(
|
||||
(components.next(), components.next()),
|
||||
(Some(std::path::Component::Normal(name)), None) if name == other
|
||||
) || other.contains('\0')
|
||||
{
|
||||
return Err(StoreError::InvalidFilename);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
validate_filename(other)?;
|
||||
path.set_file_name(other);
|
||||
match fs::metadata(&path) {
|
||||
Ok(metadata) => {
|
||||
if let Some(identity) = &identity
|
||||
&& platform::file_identity(&path, &metadata)? == *identity
|
||||
{
|
||||
return Err(StoreError::AliasedBody);
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => (),
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
}
|
||||
Ok(target)
|
||||
}
|
||||
|
||||
fn file_digest(path: &Path) -> Result<[u8; 32]> {
|
||||
regular(path)?;
|
||||
transfer_digest(File::open(path)?, io::sink())
|
||||
}
|
||||
|
||||
fn optional_file_digest(path: &Path) -> Result<Option<[u8; 32]>> {
|
||||
optional_regular(path)?
|
||||
.map(|_| transfer_digest(File::open(path)?, io::sink()))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn transfer_digest(mut input: impl io::Read, mut output: impl io::Write) -> Result<[u8; 32]> {
|
||||
let mut digest = Sha256::new();
|
||||
let mut buffer = [0; 16 * 1024];
|
||||
loop {
|
||||
let len = match input.read(&mut buffer) {
|
||||
Ok(0) => return Ok(digest.finalize().into()),
|
||||
Ok(len) => len,
|
||||
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
digest.update(&buffer[..len]);
|
||||
output.write_all(&buffer[..len])?;
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_verified(from: &Path, to: &Path, expected: [u8; 32]) -> Result<()> {
|
||||
let permissions = regular(from)?.permissions();
|
||||
let mut output = platform::create_new(to)?;
|
||||
let actual = transfer_digest(File::open(from)?, &mut output)?;
|
||||
if actual != expected {
|
||||
return Err(StoreError::StagedChecksumMismatch);
|
||||
}
|
||||
output.set_permissions(permissions)?;
|
||||
output.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_live(path: &Path, old: Option<[u8; 32]>, new: [u8; 32]) -> Result<bool> {
|
||||
let actual = optional_file_digest(path)?;
|
||||
if actual != old && actual != Some(new) {
|
||||
return Err(StoreError::LiveContentChanged(path.to_owned()));
|
||||
}
|
||||
Ok(actual == Some(new))
|
||||
}
|
||||
|
||||
fn verified(path: &Path, digest: [u8; 32]) -> Result<(Vec<u8>, Permissions)> {
|
||||
let permissions = regular(path)?.permissions();
|
||||
let bytes = fs::read(path)?;
|
||||
let actual: [u8; 32] = Sha256::digest(&bytes).into();
|
||||
if actual != digest {
|
||||
return Err(StoreError::StagedChecksumMismatch);
|
||||
}
|
||||
Ok((bytes, permissions))
|
||||
}
|
||||
|
||||
fn directory(path: &Path) -> Result<fs::Metadata> {
|
||||
let metadata = fs::symlink_metadata(path).map_err(|source| StoreError::PathIo {
|
||||
operation: "inspect",
|
||||
path: path.to_owned(),
|
||||
source,
|
||||
})?;
|
||||
if !metadata.is_dir() || platform::is_reparse(&metadata) {
|
||||
return Err(StoreError::ExpectedDirectory(path.to_owned()));
|
||||
}
|
||||
Ok(metadata)
|
||||
}
|
||||
|
||||
fn regular(path: &Path) -> Result<fs::Metadata> {
|
||||
optional_regular(path)?.ok_or_else(|| StoreError::MissingFile(path.to_owned()))
|
||||
}
|
||||
|
||||
fn optional_regular(path: &Path) -> Result<Option<fs::Metadata>> {
|
||||
match fs::symlink_metadata(path) {
|
||||
Ok(metadata) => {
|
||||
if !metadata.is_file() || platform::is_reparse(&metadata) {
|
||||
return Err(StoreError::ExpectedRegularFile(path.to_owned()));
|
||||
}
|
||||
Ok(Some(metadata))
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(source) => Err(StoreError::PathIo {
|
||||
operation: "inspect",
|
||||
path: path.to_owned(),
|
||||
source,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_new(path: &Path, bytes: &[u8], permissions: Option<Permissions>) -> Result<()> {
|
||||
let mut file = platform::create_new(path).map_err(|source| StoreError::PathIo {
|
||||
operation: "create",
|
||||
path: path.to_owned(),
|
||||
source,
|
||||
})?;
|
||||
file.write_all(bytes)?;
|
||||
if let Some(permissions) = permissions {
|
||||
file.set_permissions(permissions)?;
|
||||
}
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_file_if_exists(path: &Path) -> Result<()> {
|
||||
match fs::remove_file(path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_name(root: &Path) -> Option<String> {
|
||||
let journal = root.join(RECOVERY_JOURNAL_NAME);
|
||||
directory(&journal).ok()?;
|
||||
let marker = match optional_regular(&journal.join(DECISION)).ok()? {
|
||||
Some(_) => DECISION,
|
||||
None => DECISION_NEXT,
|
||||
};
|
||||
let decision = read_decision(&journal.join(marker)).ok()?;
|
||||
let (index, _) = verified(&journal.join(INDEX_NEXT), decision.index_digest).ok()?;
|
||||
let profiles: IProfiles = serde_yaml_ng::from_slice(&index).ok()?;
|
||||
if body_filename(&profiles, &decision.uid).ok()? != decision.file {
|
||||
return None;
|
||||
}
|
||||
let item = profiles.get_item(&decision.uid).ok()?;
|
||||
item.name
|
||||
.as_deref()
|
||||
.filter(|name| !name.trim().is_empty())
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
/// Identifies a pending transaction when this build or volume cannot replay it.
|
||||
#[cfg(windows)]
|
||||
pub fn pending_refresh_name(root: &Path) -> Option<String> {
|
||||
let lock = File::open(root.join(RECOVERY_LOCK_NAME)).ok()?;
|
||||
lock.try_lock_shared().ok()?;
|
||||
refresh_name(root)
|
||||
}
|
||||
|
||||
/// Replays a saved decision before the application creates or loads its index.
|
||||
pub fn recover_pending(root: &Path) -> Result<()> {
|
||||
match fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)) {
|
||||
Ok(_) => Session::open(root).map(drop),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn supports_redo(root: &Path) -> Result<bool> {
|
||||
Ok(platform::supports_redo(root)?)
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
#[cfg(windows)]
|
||||
pub(crate) use native::supports_redo;
|
||||
pub(crate) use native::{create_dir, create_new, file_identity, is_reparse, open_lock, sync_dir, sync_file, volume};
|
||||
pub(crate) use std::fs::rename as replace;
|
||||
|
||||
pub(crate) struct FileIdentity {
|
||||
volume: u64,
|
||||
id: u64,
|
||||
pub(crate) links: u64,
|
||||
}
|
||||
|
||||
impl PartialEq for FileIdentity {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.volume == other.volume && self.id == other.id
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
mod native {
|
||||
use super::FileIdentity;
|
||||
use std::{
|
||||
fs::{DirBuilder, File, Metadata, OpenOptions},
|
||||
io,
|
||||
os::unix::fs::{DirBuilderExt as _, MetadataExt as _, OpenOptionsExt as _},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
#[expect(clippy::unnecessary_wraps, reason = "The corresponding Windows operation can fail")]
|
||||
pub(crate) fn volume(_: &Path, metadata: &Metadata) -> io::Result<u64> {
|
||||
Ok(metadata.dev())
|
||||
}
|
||||
|
||||
#[expect(clippy::unnecessary_wraps, reason = "The corresponding Windows operation can fail")]
|
||||
pub(crate) fn file_identity(_: &Path, metadata: &Metadata) -> io::Result<FileIdentity> {
|
||||
Ok(FileIdentity {
|
||||
volume: metadata.dev(),
|
||||
id: metadata.ino(),
|
||||
links: metadata.nlink(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) const fn is_reparse(_: &Metadata) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn create_dir(path: &Path) -> io::Result<()> {
|
||||
DirBuilder::new().mode(0o700).create(path)
|
||||
}
|
||||
|
||||
pub(crate) fn open_lock(path: &Path) -> io::Result<File> {
|
||||
OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
}
|
||||
|
||||
pub(crate) fn create_new(path: &Path) -> io::Result<File> {
|
||||
OpenOptions::new().write(true).create_new(true).mode(0o600).open(path)
|
||||
}
|
||||
|
||||
pub(crate) fn sync_dir(path: &Path) -> io::Result<()> {
|
||||
File::open(path)?.sync_all()
|
||||
}
|
||||
|
||||
pub(crate) fn sync_file(path: &Path) -> io::Result<()> {
|
||||
File::open(path)?.sync_all()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod native {
|
||||
use super::FileIdentity;
|
||||
use std::{
|
||||
fs::{self, File, Metadata, OpenOptions},
|
||||
io,
|
||||
os::windows::{
|
||||
ffi::OsStrExt as _,
|
||||
fs::{MetadataExt as _, OpenOptionsExt as _},
|
||||
io::AsRawHandle as _,
|
||||
},
|
||||
path::Path,
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Storage::FileSystem::{
|
||||
BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS,
|
||||
FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES, GetDriveTypeW, GetFileInformationByHandle,
|
||||
GetVolumeInformationByHandleW, GetVolumePathNameW,
|
||||
},
|
||||
System::WindowsProgramming::DRIVE_FIXED,
|
||||
};
|
||||
|
||||
fn path_wide(path: &Path) -> io::Result<Vec<u16>> {
|
||||
let mut wide: Vec<_> = path.as_os_str().encode_wide().collect();
|
||||
if wide.contains(&0) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "path contains a NUL"));
|
||||
}
|
||||
wide.push(0);
|
||||
Ok(wide)
|
||||
}
|
||||
|
||||
fn open_attributes(path: &Path) -> io::Result<File> {
|
||||
// Follow a named alias for identity checks. Managed paths are separately checked with symlink_metadata.
|
||||
OpenOptions::new()
|
||||
.access_mode(FILE_READ_ATTRIBUTES)
|
||||
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
|
||||
.open(path)
|
||||
}
|
||||
|
||||
fn file_info(path: &Path) -> io::Result<BY_HANDLE_FILE_INFORMATION> {
|
||||
let file = open_attributes(path)?;
|
||||
let mut info = BY_HANDLE_FILE_INFORMATION::default();
|
||||
// The output buffer and file handle remain valid for the call.
|
||||
let ok = unsafe { GetFileInformationByHandle(file.as_raw_handle(), &raw mut info) };
|
||||
if ok == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
pub(crate) fn volume(path: &Path, _: &Metadata) -> io::Result<u64> {
|
||||
Ok(u64::from(file_info(path)?.dwVolumeSerialNumber))
|
||||
}
|
||||
|
||||
pub(crate) fn file_identity(path: &Path, _: &Metadata) -> io::Result<FileIdentity> {
|
||||
let info = file_info(path)?;
|
||||
// The full NTFS file ID fits in 64 bits. ReFS is excluded by supports_redo.
|
||||
Ok(FileIdentity {
|
||||
volume: u64::from(info.dwVolumeSerialNumber),
|
||||
id: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
|
||||
links: u64::from(info.nNumberOfLinks),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn is_reparse(metadata: &Metadata) -> bool {
|
||||
metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
|
||||
}
|
||||
|
||||
pub(crate) fn supports_redo(root: &Path) -> io::Result<bool> {
|
||||
let path = path_wide(root)?;
|
||||
let mut volume = vec![0u16; 32_768];
|
||||
// The input is NUL-terminated and the output buffer is writable for the stated length.
|
||||
let ok = unsafe { GetVolumePathNameW(path.as_ptr(), volume.as_mut_ptr(), volume.len() as u32) };
|
||||
if ok == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
// GetVolumePathNameW returned a NUL-terminated volume root.
|
||||
if unsafe { GetDriveTypeW(volume.as_ptr()) } != DRIVE_FIXED {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let file = open_attributes(root)?;
|
||||
let mut filesystem = [0u16; 16];
|
||||
// The handle remains live. Optional outputs are omitted, except for the writable filesystem buffer.
|
||||
let ok = unsafe {
|
||||
GetVolumeInformationByHandleW(
|
||||
file.as_raw_handle(),
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
filesystem.as_mut_ptr(),
|
||||
filesystem.len() as u32,
|
||||
)
|
||||
};
|
||||
if ok == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
// MS-FSA 2.1.5.7 documents directory persistence on NTFS. Other filesystems can silently succeed.
|
||||
Ok(filesystem.starts_with(&[u16::from(b'N'), u16::from(b'T'), u16::from(b'F'), u16::from(b'S'), 0]))
|
||||
}
|
||||
|
||||
pub(crate) fn create_dir(path: &Path) -> io::Result<()> {
|
||||
fs::create_dir(path)
|
||||
}
|
||||
|
||||
pub(crate) fn open_lock(path: &Path) -> io::Result<File> {
|
||||
OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)
|
||||
}
|
||||
|
||||
pub(crate) fn create_new(path: &Path) -> io::Result<File> {
|
||||
OpenOptions::new().write(true).create_new(true).open(path)
|
||||
}
|
||||
|
||||
pub(crate) fn sync_dir(path: &Path) -> io::Result<()> {
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)?
|
||||
.sync_all()
|
||||
}
|
||||
|
||||
pub(crate) fn sync_file(path: &Path) -> io::Result<()> {
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)?
|
||||
.sync_all()
|
||||
}
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
#![cfg(any(unix, windows))]
|
||||
|
||||
use clash_verge_profile::IProfiles;
|
||||
use clash_verge_profile_store::{CommitOutcome, Session};
|
||||
use std::fs;
|
||||
|
||||
#[test]
|
||||
fn refresh_creates_missing_body_for_legacy_index() -> Result<(), clash_verge_profile_store::StoreError> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let root = dir.path();
|
||||
fs::create_dir(root.join("profiles"))?;
|
||||
fs::write(
|
||||
root.join("profiles.yaml"),
|
||||
"items:\n- {type: remote, url: 'https://example.invalid/sub'}\n",
|
||||
)?;
|
||||
let candidate = serde_yaml_ng::from_str(
|
||||
"items:\n- {uid: assigned, type: remote, url: 'https://example.invalid/sub', file: 'Rnew.yaml', updated: 42}\n",
|
||||
)?;
|
||||
let body = b"# preserve comments\nproxies: []\n";
|
||||
let outcome = Session::open(root)?.commit_refresh("assigned", &candidate, body);
|
||||
assert!(matches!(outcome, CommitOutcome::Committed), "{outcome:?}");
|
||||
|
||||
let index: IProfiles = serde_yaml_ng::from_slice(&fs::read(root.join("profiles.yaml"))?)?;
|
||||
let stored_body = fs::read(root.join("profiles/Rnew.yaml"))?;
|
||||
assert_eq!(index.get_item("assigned")?.updated, Some(42));
|
||||
assert_eq!(index.get_item("assigned")?.file.as_deref(), Some("Rnew.yaml"));
|
||||
assert_eq!(stored_body, body);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn refresh_preserves_native_unix_filenames() -> Result<(), clash_verge_profile_store::StoreError> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let root = dir.path();
|
||||
fs::create_dir(root.join("profiles"))?;
|
||||
fs::write(root.join("profiles/remote:old.yaml"), b"old")?;
|
||||
fs::write(root.join("profiles/office:old.yaml"), b"local")?;
|
||||
let old = "items:\n- {uid: r, type: remote, file: 'remote:old.yaml', updated: 1}\n- {uid: l, type: local, file: 'office:old.yaml'}\n";
|
||||
fs::write(root.join("profiles.yaml"), old)?;
|
||||
let candidate = serde_yaml_ng::from_str(&old.replace("updated: 1", "updated: 2"))?;
|
||||
|
||||
let outcome = Session::open(root)?.commit_refresh("r", &candidate, b"new");
|
||||
assert!(matches!(outcome, CommitOutcome::Committed), "{outcome:?}");
|
||||
assert_eq!(fs::read(root.join("profiles/remote:old.yaml"))?, b"new");
|
||||
assert_eq!(fs::read(root.join("profiles/office:old.yaml"))?, b"local");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_rejects_legacy_path_alias_before_creating_body() -> Result<(), clash_verge_profile_store::StoreError> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let root = dir.path();
|
||||
fs::create_dir(root.join("profiles"))?;
|
||||
let old = "items:\n- {uid: r, type: remote, file: r.yaml, updated: 1}\n- {uid: l, type: local, file: './r.yaml'}\n";
|
||||
fs::write(root.join("profiles.yaml"), old)?;
|
||||
let candidate = serde_yaml_ng::from_str(&old.replace("updated: 1", "updated: 2"))?;
|
||||
|
||||
let outcome = Session::open(root)?.commit_refresh("r", &candidate, b"new");
|
||||
assert!(matches!(
|
||||
outcome,
|
||||
CommitOutcome::Retryable(clash_verge_profile_store::StoreError::InvalidFilename)
|
||||
));
|
||||
assert!(!root.join("profiles/r.yaml").exists());
|
||||
assert!(!root.join(clash_verge_profile_store::RECOVERY_JOURNAL_NAME).exists());
|
||||
assert_eq!(fs::read_to_string(root.join("profiles.yaml"))?, old);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(unix, feature = "test-support"))]
|
||||
#[test]
|
||||
fn interrupted_creation_reverts_an_aliased_body() -> Result<(), clash_verge_profile_store::StoreError> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let root = dir.path();
|
||||
fs::create_dir(root.join("profiles"))?;
|
||||
std::os::unix::fs::symlink("r.yaml", root.join("profiles/alias.yaml"))?;
|
||||
let old = "items:\n- {uid: r, type: remote, file: r.yaml, updated: 1}\n- {uid: l, type: local, file: alias.yaml}\n";
|
||||
fs::write(root.join("profiles.yaml"), old)?;
|
||||
let candidate = serde_yaml_ng::from_str(&old.replace("updated: 1", "updated: 2"))?;
|
||||
let outcome = Session::open(root)?.commit_observed("r", &candidate, b"new", &mut |phase| {
|
||||
if phase == "body-replaced" {
|
||||
return Err(std::io::Error::other("interrupted after body replacement").into());
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
assert!(matches!(outcome, CommitOutcome::NeedsRecovery(_)), "{outcome:?}");
|
||||
assert_eq!(fs::read(root.join("profiles/r.yaml"))?, b"new");
|
||||
let session = Session::open(root)?;
|
||||
assert!(!root.join("profiles/r.yaml").exists());
|
||||
assert!(!root.join(clash_verge_profile_store::RECOVERY_JOURNAL_NAME).exists());
|
||||
assert_eq!(fs::read_to_string(root.join("profiles.yaml"))?, old);
|
||||
let outcome = session.commit_refresh("r", &candidate, b"new");
|
||||
assert!(matches!(
|
||||
outcome,
|
||||
CommitOutcome::Retryable(clash_verge_profile_store::StoreError::AliasedBody)
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-support")]
|
||||
#[test]
|
||||
fn recovery_identifies_the_interrupted_subscription_from_its_verified_index()
|
||||
-> Result<(), clash_verge_profile_store::StoreError> {
|
||||
use clash_verge_profile_store::{StoreError, recover_pending};
|
||||
|
||||
let home = tempfile::tempdir()?;
|
||||
let root = home.path();
|
||||
fs::create_dir(root.join("profiles"))?;
|
||||
let index = "current: other\nitems:\n- {uid: other, name: Home, type: remote, file: other.yaml}\n- {uid: opaque, name: 工作线路, type: remote, file: target.yaml}\n";
|
||||
fs::write(root.join("profiles.yaml"), index)?;
|
||||
let candidate = serde_yaml_ng::from_str(index)?;
|
||||
let outcome = Session::open(root)?.commit_observed("opaque", &candidate, b"new", &mut |phase| {
|
||||
if phase == "decision-created" {
|
||||
return Err(std::io::Error::other("interrupted").into());
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
assert!(matches!(outcome, CommitOutcome::NeedsRecovery(_)));
|
||||
fs::write(root.join("profiles/target.yaml"), b"changed outside the refresh")?;
|
||||
let error = recover_pending(root).unwrap_err();
|
||||
assert!(
|
||||
matches!(error, StoreError::NamedRecovery { name, source } if name == "工作线路" && matches!(*source, StoreError::LiveContentChanged(_)))
|
||||
);
|
||||
let journal = root.join(clash_verge_profile_store::RECOVERY_JOURNAL_NAME);
|
||||
fs::write(journal.join("index.next"), index.replace("工作线路", "Wrong"))?;
|
||||
assert!(matches!(recover_pending(root), Err(StoreError::StagedChecksumMismatch)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-support")]
|
||||
#[test]
|
||||
fn legacy_companions_follow_the_refresh_decision() -> Result<(), clash_verge_profile_store::StoreError> {
|
||||
for phase in ["prepared", "companion-installed", "decision-removed"] {
|
||||
let home = tempfile::tempdir()?;
|
||||
let root = home.path();
|
||||
let profiles = root.join("profiles");
|
||||
fs::create_dir(&profiles)?;
|
||||
let old = "items: [{uid: r, type: remote, file: r.yaml}]";
|
||||
fs::write(root.join("profiles.yaml"), old)?;
|
||||
fs::write(profiles.join("r.yaml"), b"old")?;
|
||||
let mut candidate: IProfiles = serde_yaml_ng::from_str(
|
||||
"items: [{uid: r, type: remote, file: r.yaml, option: {script: s}}, {uid: s, type: script, file: s.js}]",
|
||||
)?;
|
||||
candidate.get_item_mut("s")?.file_data = Some("template".into());
|
||||
let result = Session::open(root)?.commit_observed("r", &candidate, b"new", &mut |checkpoint| {
|
||||
if checkpoint == phase {
|
||||
return Err(std::io::Error::other("interrupted").into());
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
if phase == "decision-removed" {
|
||||
assert!(matches!(result, CommitOutcome::CommittedCleanupPending(_)));
|
||||
fs::write(profiles.join("s.js"), b"edited")?;
|
||||
assert!(clash_verge_profile_store::recover_pending(root).is_err());
|
||||
assert_eq!(fs::read(profiles.join("s.js"))?, b"edited");
|
||||
assert!(root.join(clash_verge_profile_store::RECOVERY_JOURNAL_NAME).exists());
|
||||
continue;
|
||||
}
|
||||
assert_eq!(fs::read_to_string(root.join("profiles.yaml"))?, old);
|
||||
if phase == "prepared" {
|
||||
assert!(matches!(result, CommitOutcome::Retryable(_)));
|
||||
clash_verge_profile_store::recover_pending(root)?;
|
||||
assert!(!profiles.join("s.js").exists());
|
||||
assert_eq!(fs::read(profiles.join("r.yaml"))?, b"old");
|
||||
} else {
|
||||
assert!(matches!(result, CommitOutcome::NeedsRecovery(_)));
|
||||
clash_verge_profile_store::recover_pending(root)?;
|
||||
let stored: IProfiles = serde_yaml_ng::from_slice(&fs::read(root.join("profiles.yaml"))?)?;
|
||||
assert_eq!(stored.get_item("s")?.file.as_deref(), Some("s.js"));
|
||||
assert_eq!(fs::read(profiles.join("r.yaml"))?, b"new");
|
||||
assert_eq!(fs::read(profiles.join("s.js"))?, b"template");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
+20
-17
@@ -9,7 +9,7 @@ import AdmZip from 'adm-zip'
|
||||
import { HttpsProxyAgent } from 'https-proxy-agent'
|
||||
import { extract } from 'tar'
|
||||
|
||||
import { resolveServiceRelease } from './service-release.mjs'
|
||||
import { resolveServiceBundle as serviceBundleFromMetadata } from './service-release.mjs'
|
||||
import { log_debug, log_error, log_info, log_success } from './utils.mjs'
|
||||
|
||||
/** Prepares platform resources, caching versions and unchanged files unless `--force` is used. */
|
||||
@@ -581,23 +581,30 @@ async function resolveServiceBundle() {
|
||||
}
|
||||
})
|
||||
|
||||
const cargoManifest = await fsp.readFile(
|
||||
path.join(cwd, 'src-tauri', 'Cargo.toml'),
|
||||
'utf8',
|
||||
const metadata = JSON.parse(
|
||||
execFileSync(
|
||||
'cargo',
|
||||
[
|
||||
'metadata',
|
||||
'--locked',
|
||||
'--format-version',
|
||||
'1',
|
||||
'--filter-platform',
|
||||
SIDECAR_HOST,
|
||||
],
|
||||
{ cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
|
||||
),
|
||||
)
|
||||
const serviceDependency = cargoManifest
|
||||
.split(/\r?\n/)
|
||||
.find((line) => line.trimStart().startsWith('clash_verge_service_ipc ='))
|
||||
const sourcePath = serviceDependency?.match(/\bpath\s*=\s*"([^"]+)"/)?.[1]
|
||||
if (sourcePath) {
|
||||
const manifest = path.resolve(cwd, 'src-tauri', sourcePath, 'Cargo.toml')
|
||||
const bundle = serviceBundleFromMetadata(metadata, SIDECAR_HOST, platform)
|
||||
if (bundle.manifest) {
|
||||
const targetDirectory = path.join(cwd, 'target', 'bundled-service')
|
||||
execFileSync(
|
||||
'cargo',
|
||||
[
|
||||
'build',
|
||||
'--locked',
|
||||
'--manifest-path',
|
||||
manifest,
|
||||
bundle.manifest,
|
||||
'--target-dir',
|
||||
targetDirectory,
|
||||
'--target',
|
||||
@@ -605,7 +612,7 @@ async function resolveServiceBundle() {
|
||||
'--release',
|
||||
'--features',
|
||||
'standalone,client',
|
||||
'--bins',
|
||||
...SERVICE_BINARIES.flatMap((name) => ['--bin', name]),
|
||||
],
|
||||
{ stdio: 'inherit' },
|
||||
)
|
||||
@@ -620,11 +627,7 @@ async function resolveServiceBundle() {
|
||||
}
|
||||
return
|
||||
}
|
||||
const { archiveFile, downloadURL } = resolveServiceRelease(
|
||||
cargoManifest,
|
||||
SIDECAR_HOST,
|
||||
platform,
|
||||
)
|
||||
const { archiveFile, downloadURL } = bundle
|
||||
const tempDir = path.join(TEMP_DIR, 'clash-verge-service-ipc')
|
||||
const tempArchive = path.join(tempDir, archiveFile)
|
||||
|
||||
|
||||
+24
-11
@@ -1,22 +1,35 @@
|
||||
const SERVICE_URL_PREFIX =
|
||||
'https://github.com/clash-verge-rev/clash-verge-service-ipc/releases/download'
|
||||
|
||||
export function resolveServiceRelease(cargoManifest, host, platform) {
|
||||
const dependency = cargoManifest
|
||||
.split(/\r?\n/)
|
||||
.find((line) => line.trimStart().startsWith('clash_verge_service_ipc ='))
|
||||
const packageVersion = dependency?.match(/\bversion\s*=\s*"([^"]+)"/)?.[1]
|
||||
if (!packageVersion) {
|
||||
throw new Error(
|
||||
'clash_verge_service_ipc dependency must declare an inline version',
|
||||
)
|
||||
export function resolveServiceBundle(metadata, host, platform) {
|
||||
const app = metadata.packages.find(
|
||||
(pkg) =>
|
||||
pkg.name === 'clash-verge' && metadata.workspace_members.includes(pkg.id),
|
||||
)
|
||||
const dependency = app?.dependencies.find(
|
||||
(dep) => dep.name === 'clash_verge_service_ipc',
|
||||
)
|
||||
const edge = metadata.resolve.nodes
|
||||
.find((node) => node.id === app?.id)
|
||||
?.deps.find((dep) => dep.name === 'clash_verge_service_ipc')
|
||||
const service = metadata.packages.find((pkg) => pkg.id === edge?.pkg)
|
||||
if (!service || !dependency) {
|
||||
throw new Error('Cargo did not resolve the desktop IPC client dependency')
|
||||
}
|
||||
if (!service.source || new URL(service.source).searchParams.has('rev')) {
|
||||
return { manifest: service.manifest_path }
|
||||
}
|
||||
|
||||
const version = `v${packageVersion}`
|
||||
const declared = dependency.req.replace(/^[=^]/, '')
|
||||
if (declared !== service.version) {
|
||||
throw new Error(
|
||||
`Service release version ${declared} differs from the resolved IPC client ${service.version}`,
|
||||
)
|
||||
}
|
||||
const version = `v${declared}`
|
||||
const archiveExt = platform === 'win32' ? 'zip' : 'tar.gz'
|
||||
const archiveFile = `clash-verge-service-ipc-${version}-${host}.${archiveExt}`
|
||||
return {
|
||||
version,
|
||||
archiveFile,
|
||||
downloadURL: `${SERVICE_URL_PREFIX}/${version}/${archiveFile}`,
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ tokio-trace = ["clash-verge-logging/tokio-trace"]
|
||||
chrome-trace = ["clash-verge-logging/chrome-trace"]
|
||||
clippy = ["tauri/test"]
|
||||
perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
|
||||
profile-store-windows = []
|
||||
|
||||
[package.metadata.bundle]
|
||||
identifier = "io.github.clash-verge-rev.clash-verge-rev"
|
||||
@@ -31,7 +30,6 @@ identifier = "io.github.clash-verge-rev.clash-verge-rev"
|
||||
tauri-build = { version = "2.8.0", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tempfile = { workspace = true }
|
||||
clash-verge-draft = { workspace = true }
|
||||
clash-verge-task = { workspace = true }
|
||||
clash-verge-media-unlock = { workspace = true }
|
||||
@@ -83,6 +81,7 @@ tauri-plugin-dialog = { version = "2.9.0", default-features = false, features =
|
||||
tauri-plugin-fs = "2.8.0"
|
||||
tauri-plugin-deep-link = "2.6.3"
|
||||
tauri-plugin-window-state = "2.5.1"
|
||||
zip = { workspace = true }
|
||||
flate2 = "1.1.11"
|
||||
reqwest_dav = "0.4.0"
|
||||
aes-gcm = { version = "0.11.1" }
|
||||
@@ -110,9 +109,6 @@ specta = { workspace = true, features = ["derive", "function", "serde_json"] }
|
||||
tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] }
|
||||
specta-typescript = "=0.0.13"
|
||||
|
||||
[target.'cfg(any(unix, windows))'.dependencies]
|
||||
clash-verge-profile-store = { workspace = true }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2.191"
|
||||
|
||||
@@ -150,7 +146,6 @@ 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"
|
||||
|
||||
@@ -34,23 +34,10 @@ fn profile_import_error(err: &anyhow::Error) -> std::string::String {
|
||||
format!("导入订阅失败: {err:#}")
|
||||
}
|
||||
|
||||
fn profile_command_error(error: anyhow::Error, fallback: Option<&str>) -> super::CommandFailure {
|
||||
if error.is::<crate::config::profile_storage::RecoveryRequired>() {
|
||||
coded_error("PROFILE_RECOVERY_REQUIRED", format_args!("{error:#}"))
|
||||
} else if let Some(code) = fallback {
|
||||
coded_error(code, format_args!("{error:#}"))
|
||||
} else {
|
||||
super::CommandFailure::plain(error)
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn get_profiles() -> CmdResult<SharedDraft<IProfiles>> {
|
||||
let draft = Config::profiles().await;
|
||||
let _guard = crate::config::profile_storage::read()
|
||||
.await
|
||||
.map_err(|error| profile_command_error(error, None))?;
|
||||
let data = draft.data_arc();
|
||||
Ok(data)
|
||||
}
|
||||
@@ -155,10 +142,13 @@ pub async fn create_profile(item: ProfileCreate, file_data: Option<std::string::
|
||||
#[specta::specta]
|
||||
pub async fn update_profile(index: std::string::String, option: Option<PrfOption>) -> CmdResult {
|
||||
let index: String = index.into();
|
||||
feat::update_profile(&index, option.as_ref(), true)
|
||||
.await
|
||||
.inspect_err(|e| logging!(error, Type::Cmd, "update profile failed: {e:#}"))
|
||||
.map_err(|error| profile_command_error(error, Some("PROFILE_UPDATE_FAILED")))
|
||||
match feat::update_profile(&index, option.as_ref(), true).await {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => {
|
||||
logging!(error, Type::Cmd, "update profile failed: {e:#}");
|
||||
Err(coded_error("PROFILE_UPDATE_FAILED", e))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -166,11 +156,8 @@ pub async fn update_profile(index: std::string::String, option: Option<PrfOption
|
||||
pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
||||
let index: String = index.into();
|
||||
let profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
|
||||
crate::config::profile_storage::check().stringify_err()?;
|
||||
|
||||
let profiles = Config::profiles().await;
|
||||
let mut storage_guard = None;
|
||||
let slot = &mut storage_guard;
|
||||
let result = profiles
|
||||
.with_data_modify::<_, _, _, anyhow::Error>(|mut candidate| async move {
|
||||
let original = candidate.clone();
|
||||
@@ -189,13 +176,11 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
||||
None
|
||||
};
|
||||
let current = candidate.current.clone();
|
||||
*slot = Some(crate::config::profile_storage::write().await?);
|
||||
cleanup_profile_files(plan.files).await;
|
||||
Ok((candidate, Ok((should_update, current, guard))))
|
||||
})
|
||||
.await
|
||||
.with_error_code("PROFILE_DELETE_FAILED")?;
|
||||
drop(storage_guard);
|
||||
let (should_update, current, config_update_guard) = match result {
|
||||
Ok(result) => result,
|
||||
Err(outcome) => {
|
||||
@@ -228,9 +213,10 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
||||
|
||||
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
|
||||
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
|
||||
commit_current_profile(&Config::profiles().await, Some(prev_profile.clone()))
|
||||
Config::profiles()
|
||||
.await
|
||||
.stringify_err()?;
|
||||
.edit_draft(|d| d.patch_current(Some(prev_profile)));
|
||||
Config::profiles().await.apply();
|
||||
crate::process::AsyncHandler::spawn(|| async move {
|
||||
if let Err(e) = save_committed_profiles().await {
|
||||
logging!(warn, Type::Cmd, "异步保存恢复配置文件失败: {e:#}");
|
||||
@@ -404,7 +390,6 @@ pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<Vali
|
||||
CURRENT_SWITCHING_PROFILE.store(false, Ordering::Release);
|
||||
});
|
||||
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
|
||||
crate::config::profile_storage::check().stringify_err()?;
|
||||
|
||||
let target_profile = profiles.current.as_ref();
|
||||
|
||||
@@ -472,7 +457,6 @@ pub async fn patch_profile(index: std::string::String, profile: ProfilePatch) ->
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn view_profile(index: std::string::String) -> CmdResult {
|
||||
let _guard = crate::config::profile_storage::read().await.stringify_err()?;
|
||||
let profiles = Config::profiles().await;
|
||||
let profiles_ref = profiles.latest_arc();
|
||||
let file = profiles_ref
|
||||
@@ -498,7 +482,6 @@ pub async fn view_profile(index: std::string::String) -> CmdResult {
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::string::String> {
|
||||
let _guard = crate::config::profile_storage::read().await.stringify_err()?;
|
||||
let file = {
|
||||
let profiles = Config::profiles().await;
|
||||
let profiles_ref = profiles.latest_arc();
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::CmdResult;
|
||||
use crate::{
|
||||
cmd::StringifyErr as _,
|
||||
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
|
||||
config::{Config, IProfiles, profile_storage, profiles::PROFILE_WRITE_LOCK, read_profile_item_file},
|
||||
config::{Config, IProfiles, read_profile_item_file},
|
||||
core::auto_backup::{self, AutoBackupTrigger},
|
||||
core::{
|
||||
CoreManager, handle,
|
||||
@@ -34,9 +34,6 @@ pub async fn save_profile_file(
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let _profile_write = PROFILE_WRITE_LOCK.lock().await;
|
||||
let profile_guard = profile_storage::write().await.stringify_err()?;
|
||||
|
||||
// 在异步操作前获取必要元数据并释放锁
|
||||
let (rel_path, is_merge_file, is_script_file, affects_runtime) = {
|
||||
let profiles = Config::profiles().await;
|
||||
@@ -51,6 +48,7 @@ pub async fn save_profile_file(
|
||||
|
||||
let profiles_dir = dirs::app_profiles_dir().stringify_err()?;
|
||||
let file_path = profiles_dir.join(rel_path.as_str());
|
||||
let file_path_str = file_path.to_string_lossy().to_string();
|
||||
|
||||
// 读取原始内容(在释放profiles_guard后进行)
|
||||
let original_existed = fs::try_exists(&file_path).await.map_err(|err| {
|
||||
@@ -60,22 +58,24 @@ pub async fn save_profile_file(
|
||||
))
|
||||
})?;
|
||||
let original_content = if original_existed {
|
||||
Some(read_profile_item_file(Some(rel_path.as_str())).await.stringify_err()?)
|
||||
read_profile_item_file(Some(rel_path.as_str())).await.stringify_err()?
|
||||
} else {
|
||||
None
|
||||
String::new()
|
||||
};
|
||||
|
||||
// 保存新的配置文件
|
||||
fs::write(&file_path, &file_data).await.stringify_err()?;
|
||||
drop(profile_guard);
|
||||
|
||||
let original = OriginalProfileFile {
|
||||
content: original_content.as_deref(),
|
||||
written: &file_data,
|
||||
};
|
||||
|
||||
let changes_applied =
|
||||
validate_and_apply_profile(&file_path, &original, is_merge_file, is_script_file, affects_runtime).await?;
|
||||
let changes_applied = handle_saved_profile_file(
|
||||
&file_path_str,
|
||||
&file_path,
|
||||
&original_content,
|
||||
original_existed,
|
||||
is_merge_file,
|
||||
is_script_file,
|
||||
affects_runtime,
|
||||
)
|
||||
.await?;
|
||||
|
||||
if changes_applied.is_valid()
|
||||
&& let Some(trigger) = backup_trigger
|
||||
@@ -86,18 +86,13 @@ pub async fn save_profile_file(
|
||||
Ok(changes_applied)
|
||||
}
|
||||
|
||||
struct OriginalProfileFile<'a> {
|
||||
content: Option<&'a str>,
|
||||
written: &'a str,
|
||||
}
|
||||
|
||||
async fn restore_original(file_path: &std::path::Path, original: &OriginalProfileFile<'_>) -> CmdResult<()> {
|
||||
let _guard = profile_storage::write().await.stringify_err()?;
|
||||
if fs::read(file_path).await.stringify_err()? != original.written.as_bytes() {
|
||||
return Err("profile file changed during validation".into());
|
||||
}
|
||||
if let Some(content) = original.content {
|
||||
fs::write(file_path, content).await.stringify_err()
|
||||
async fn restore_original(
|
||||
file_path: &std::path::Path,
|
||||
original_content: &str,
|
||||
original_existed: bool,
|
||||
) -> CmdResult<()> {
|
||||
if original_existed {
|
||||
fs::write(file_path, original_content).await.stringify_err()
|
||||
} else {
|
||||
fs::remove_file(file_path).await.stringify_err()
|
||||
}
|
||||
@@ -124,9 +119,11 @@ fn profile_affects_runtime(profiles: &IProfiles, index: &str) -> bool {
|
||||
.contains(&index)
|
||||
}
|
||||
|
||||
async fn validate_and_apply_profile(
|
||||
async fn handle_saved_profile_file(
|
||||
file_path_str: &str,
|
||||
file_path: &std::path::Path,
|
||||
original: &OriginalProfileFile<'_>,
|
||||
original_content: &str,
|
||||
original_existed: bool,
|
||||
is_merge_file: bool,
|
||||
is_script_file: bool,
|
||||
affects_runtime: bool,
|
||||
@@ -139,17 +136,17 @@ async fn validate_and_apply_profile(
|
||||
(ValidationNoticeTarget::Runtime, "YAML配置文件")
|
||||
};
|
||||
|
||||
match CoreConfigValidator::validate_config_file_outcome(&file_path.to_string_lossy(), Some(is_merge_file)).await {
|
||||
match CoreConfigValidator::validate_config_file_outcome(file_path_str, Some(is_merge_file)).await {
|
||||
Ok(outcome) if outcome.is_valid() => {}
|
||||
Ok(outcome) => {
|
||||
logging!(warn, Type::Config, "[cmd配置save] 文件验证失败: {}", outcome);
|
||||
restore_original(file_path, original).await?;
|
||||
restore_original(file_path, original_content, original_existed).await?;
|
||||
handle_validation_notice(&outcome, target, file_type);
|
||||
return Ok(outcome);
|
||||
}
|
||||
Err(e) => {
|
||||
logging!(error, Type::Config, "[cmd配置save] 验证过程发生错误: {e:#}");
|
||||
restore_original(file_path, original).await?;
|
||||
restore_original(file_path, original_content, original_existed).await?;
|
||||
return Err(e.to_string().into());
|
||||
}
|
||||
}
|
||||
@@ -170,13 +167,13 @@ async fn validate_and_apply_profile(
|
||||
}
|
||||
Ok(outcome) => {
|
||||
logging!(warn, Type::Config, "[cmd配置save] 运行时配置应用失败: {}", outcome);
|
||||
restore_original(file_path, original).await?;
|
||||
restore_original(file_path, original_content, original_existed).await?;
|
||||
handle_validation_notice(&outcome, ValidationNoticeTarget::Runtime, "运行时配置");
|
||||
Ok(outcome)
|
||||
}
|
||||
Err(err) => {
|
||||
logging!(error, Type::Config, "[cmd配置save] 运行时配置应用错误: {err:#}");
|
||||
restore_original(file_path, original).await?;
|
||||
restore_original(file_path, original_content, original_existed).await?;
|
||||
Err(err.to_string().into())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,17 +8,7 @@ use crate::{
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, serde::Serialize, specta::Type)]
|
||||
#[serde(tag = "status", rename_all = "camelCase")]
|
||||
pub enum ServiceInstallOutcome {
|
||||
Installed,
|
||||
#[cfg_attr(not(any(windows, test)), allow(dead_code))]
|
||||
Sidecar {
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str) -> CmdResult<ServiceInstallOutcome> {
|
||||
async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str) -> CmdResult {
|
||||
let manager = CoreManager::global();
|
||||
let result = {
|
||||
let _lifecycle = manager.lifecycle_lock.lock().await;
|
||||
@@ -33,56 +23,12 @@ async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str)
|
||||
}
|
||||
SERVICE_MANAGER.handle_service_status(status).await
|
||||
};
|
||||
#[cfg(windows)]
|
||||
return finish_service_installation(result, error_code, async |reason| {
|
||||
manager.continue_with_sidecar(Some(reason)).await
|
||||
})
|
||||
.await;
|
||||
|
||||
#[cfg(not(windows))]
|
||||
result
|
||||
.map(|()| ServiceInstallOutcome::Installed)
|
||||
.map_err(|error| proxy_aware_coded_error(&error, error_code))
|
||||
}
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
async fn finish_service_installation<Fallback>(
|
||||
installation: anyhow::Result<()>,
|
||||
error_code: &str,
|
||||
fallback: Fallback,
|
||||
) -> CmdResult<ServiceInstallOutcome>
|
||||
where
|
||||
Fallback: AsyncFnOnce(&str) -> anyhow::Result<()>,
|
||||
{
|
||||
let Err(error) = installation else {
|
||||
return Ok(ServiceInstallOutcome::Installed);
|
||||
};
|
||||
let Some(failure) = error.downcast_ref::<clash_verge_service_ipc::management::InstallationVerificationError>()
|
||||
else {
|
||||
return Err(proxy_aware_coded_error(&error, error_code));
|
||||
};
|
||||
let reasons = failure
|
||||
.status
|
||||
.cores
|
||||
.iter()
|
||||
.filter_map(|core| match &core.availability {
|
||||
clash_verge_service_ipc::CoreAvailability::Rejected { reason } => Some(format!("{}: {reason}", core.name)),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if reasons.is_empty() {
|
||||
return Err(proxy_aware_coded_error(&error, error_code));
|
||||
}
|
||||
let reason = reasons.join("\n");
|
||||
fallback(reason.as_str())
|
||||
.await
|
||||
.map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED"))?;
|
||||
Ok(ServiceInstallOutcome::Sidecar { reason })
|
||||
result.map_err(|error| proxy_aware_coded_error(&error, error_code))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn install_service() -> CmdResult<ServiceInstallOutcome> {
|
||||
pub async fn install_service() -> CmdResult {
|
||||
execute_service_operation_sync(ServiceStatus::InstallRequired, "SERVICE_INSTALL_FAILED").await
|
||||
}
|
||||
|
||||
@@ -97,13 +43,13 @@ pub async fn uninstall_service() -> CmdResult {
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn reinstall_service() -> CmdResult<ServiceInstallOutcome> {
|
||||
pub async fn reinstall_service() -> CmdResult {
|
||||
execute_service_operation_sync(ServiceStatus::ReinstallRequired, "SERVICE_REINSTALL_FAILED").await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn repair_service() -> CmdResult<ServiceInstallOutcome> {
|
||||
pub async fn repair_service() -> CmdResult {
|
||||
execute_service_operation_sync(ServiceStatus::ForceReinstallRequired, "SERVICE_REPAIR_FAILED").await
|
||||
}
|
||||
|
||||
@@ -111,7 +57,7 @@ pub async fn repair_service() -> CmdResult<ServiceInstallOutcome> {
|
||||
#[specta::specta]
|
||||
pub async fn continue_with_sidecar() -> CmdResult {
|
||||
crate::core::CoreManager::global()
|
||||
.continue_with_sidecar(None)
|
||||
.continue_with_sidecar()
|
||||
.await
|
||||
.map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED"))
|
||||
}
|
||||
@@ -122,12 +68,6 @@ pub fn get_sidecar_failure() -> crate::core::notification::SidecarFailureSnapsho
|
||||
crate::core::notification::sidecar_failure_snapshot()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn take_service_fallback_notice() -> Option<crate::core::service::ServiceFallbackNotice> {
|
||||
crate::core::service::take_service_fallback_notice()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn get_core_startup_error() -> Option<crate::core::manager::CoreFailure> {
|
||||
@@ -153,72 +93,3 @@ pub fn sync_runtime_providers() {
|
||||
request_runtime_provider_sync(timing::RUNTIME_PROVIDER_SETTLE);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
|
||||
mod tests {
|
||||
use super::{ServiceInstallOutcome, finish_service_installation};
|
||||
use clash_verge_service_ipc::{
|
||||
CoreAvailability, CoreInspection, InstallationStatus, ProtocolInfo, management::InstallationVerificationError,
|
||||
};
|
||||
use std::cell::Cell;
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejected_installation_reports_sidecar_only_after_successful_continuation() {
|
||||
let reason = "core path C:\\ is writable by Everyone";
|
||||
for (availability, fallback_ready) in [
|
||||
(None, false),
|
||||
(Some(CoreAvailability::Missing), false),
|
||||
(Some(CoreAvailability::DigestMismatch), false),
|
||||
(Some(CoreAvailability::Rejected { reason: reason.into() }), false),
|
||||
(Some(CoreAvailability::Rejected { reason: reason.into() }), true),
|
||||
] {
|
||||
let fallback_called = Cell::new(false);
|
||||
let rejected = matches!(&availability, Some(CoreAvailability::Rejected { .. }));
|
||||
let error = match availability {
|
||||
Some(availability) => anyhow::Error::new(InstallationVerificationError {
|
||||
status: InstallationStatus {
|
||||
service_sha256: String::new(),
|
||||
protocol: ProtocolInfo::current(),
|
||||
cores: vec![CoreInspection {
|
||||
name: "verge-mihomo.exe".into(),
|
||||
availability,
|
||||
}],
|
||||
core_busy: false,
|
||||
},
|
||||
}),
|
||||
None => anyhow::anyhow!("{reason}"),
|
||||
}
|
||||
.context("install service failed");
|
||||
let result = finish_service_installation(Err(error), "SERVICE_INSTALL_FAILED", async |_| {
|
||||
fallback_called.set(true);
|
||||
anyhow::ensure!(fallback_ready, "another core is running");
|
||||
Ok(())
|
||||
})
|
||||
.await;
|
||||
|
||||
assert_eq!(fallback_called.get(), rejected);
|
||||
if rejected && fallback_ready {
|
||||
assert_eq!(
|
||||
result,
|
||||
Ok(ServiceInstallOutcome::Sidecar {
|
||||
reason: format!("verge-mihomo.exe: {reason}")
|
||||
})
|
||||
);
|
||||
} else {
|
||||
let error = result.expect_err("an unavailable fallback must remain an error");
|
||||
assert_eq!(
|
||||
error.code.as_deref(),
|
||||
Some(if rejected {
|
||||
"SERVICE_SIDECAR_FAILED"
|
||||
} else {
|
||||
"SERVICE_INSTALL_FAILED"
|
||||
})
|
||||
);
|
||||
if rejected {
|
||||
assert!(error.detail.contains("another core is running"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,12 +22,10 @@ pub async fn save_webdav_config(
|
||||
webdav_password: Some(password),
|
||||
..IVerge::default()
|
||||
};
|
||||
let _config_write = Config::lock_config_write().await;
|
||||
let verge = Config::verge().await;
|
||||
verge.edit_draft(|e| e.patch_config(&patch));
|
||||
verge.apply();
|
||||
Config::verge().await.edit_draft(|e| e.patch_config(&patch));
|
||||
Config::verge().await.apply();
|
||||
|
||||
let verge_data = verge.data_arc();
|
||||
let verge_data = Config::verge().await.data_arc();
|
||||
verge_data.save_file().await.stringify_err()?;
|
||||
core::backup::WebDavClient::global().reset();
|
||||
Ok(())
|
||||
|
||||
@@ -3,8 +3,7 @@ use crate::core::notify::NoticeStatus;
|
||||
use crate::{
|
||||
config::{
|
||||
prfitem::{build_merge_profile, build_script_profile},
|
||||
profile_storage,
|
||||
profiles::{append_to_profile_index, load_profiles, save_profiles_unlocked},
|
||||
profiles::{append_to_profile_index, load_profiles, save_profiles},
|
||||
runtime::IRuntime,
|
||||
},
|
||||
constants::{files, timing},
|
||||
@@ -85,7 +84,6 @@ impl Config {
|
||||
}
|
||||
|
||||
pub async fn init_config_before_window() -> Result<()> {
|
||||
profile_storage::check()?;
|
||||
Self::ensure_default_profile_items().await?;
|
||||
|
||||
let verge = Self::verge().await.latest_arc();
|
||||
@@ -247,24 +245,12 @@ impl Config {
|
||||
}
|
||||
|
||||
pub async fn generate() -> Result<()> {
|
||||
let profiles = Self::profiles().await;
|
||||
let inputs = {
|
||||
let _guard = profile_storage::read().await?;
|
||||
enhance::collect_render_inputs(&profiles.latest_arc()).await?
|
||||
};
|
||||
Self::generate_from_inputs(inputs).await
|
||||
let profiles = Self::profiles().await.latest_arc();
|
||||
Self::generate_with_profiles(&profiles).await
|
||||
}
|
||||
|
||||
pub(crate) async fn generate_with_profiles(profiles: &IProfiles) -> Result<()> {
|
||||
let inputs = {
|
||||
let _guard = profile_storage::read().await?;
|
||||
enhance::collect_render_inputs(profiles).await?
|
||||
};
|
||||
Self::generate_from_inputs(inputs).await
|
||||
}
|
||||
|
||||
async fn generate_from_inputs(inputs: enhance::ProfileRenderInputs) -> Result<()> {
|
||||
let (mut config, exists_keys, logs, dns_override) = enhance::render_runtime_config(inputs).await;
|
||||
let (mut config, exists_keys, logs, dns_override) = enhance::render_runtime_config(profiles).await?;
|
||||
|
||||
resolve_provider_path_conflicts(&mut config, &dirs::app_home_dir()?)?;
|
||||
sanitize_tunnels_proxy(&mut config);
|
||||
@@ -327,20 +313,8 @@ impl Config {
|
||||
let save_profiles_task = AsyncHandler::spawn(|| async {
|
||||
let _profile_write = super::profiles::PROFILE_WRITE_LOCK.lock().await;
|
||||
let profiles = Self::profiles().await;
|
||||
let mut storage_guard = None;
|
||||
let slot = &mut storage_guard;
|
||||
let draft = &profiles;
|
||||
let result = profiles
|
||||
.with_data_modify(|_| async move {
|
||||
*slot = Some(profile_storage::write().await?);
|
||||
let candidate = (**draft.latest_arc()).clone();
|
||||
let saved = save_profiles_unlocked(&candidate).await;
|
||||
draft.discard();
|
||||
Ok((candidate, saved))
|
||||
})
|
||||
.await;
|
||||
drop(storage_guard);
|
||||
logging_error!(Type::Config, result.and_then(std::convert::identity));
|
||||
profiles.apply();
|
||||
logging_error!(Type::Config, save_profiles(&profiles.data_arc()).await);
|
||||
});
|
||||
|
||||
let _ = tokio::join!(save_clash_task, save_verge_task, save_profiles_task);
|
||||
|
||||
@@ -7,7 +7,6 @@ pub(crate) mod mihomo_yaml;
|
||||
mod mixed_port;
|
||||
mod port;
|
||||
mod prfitem;
|
||||
pub(crate) mod profile_storage;
|
||||
pub mod profiles;
|
||||
pub mod runtime;
|
||||
pub(crate) mod snapshot;
|
||||
@@ -15,7 +14,7 @@ mod verge;
|
||||
|
||||
pub(crate) use self::config::Config;
|
||||
pub(crate) use self::prfitem::{
|
||||
build_remote_profile, download_subscription, read_profile_item_file, subscription_proxy,
|
||||
build_remote_profile, download_subscription, prepare_remote_refresh, read_profile_item_file, subscription_proxy,
|
||||
};
|
||||
pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*};
|
||||
pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected};
|
||||
|
||||
@@ -44,26 +44,15 @@ pub(super) async fn build_profile(item: &PrfItem, file_data: Option<String>) ->
|
||||
}
|
||||
}
|
||||
|
||||
fn missing_companions(options: &mut PrfOption) -> Vec<PrfItem> {
|
||||
let mut companions = Vec::new();
|
||||
for (reference, build) in [
|
||||
(&mut options.merge, (|| build_merge_profile(None)) as fn() -> PrfItem),
|
||||
(&mut options.script, || build_script_profile(None)),
|
||||
(&mut options.rules, from_rules),
|
||||
(&mut options.proxies, from_proxies),
|
||||
(&mut options.groups, from_groups),
|
||||
] {
|
||||
if reference.is_none() {
|
||||
let item = build();
|
||||
*reference = item.uid.clone();
|
||||
companions.push(item);
|
||||
}
|
||||
}
|
||||
companions
|
||||
async fn append_companion_item(item: &mut PrfItem) -> Result<String> {
|
||||
profiles::append_profile(item).await?;
|
||||
item.uid
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow::anyhow!("appended companion item has no uid"))
|
||||
}
|
||||
|
||||
fn creation_options(source: Option<&PrfOption>) -> PrfOption {
|
||||
PrfOption {
|
||||
async fn prepare_profile_options(source: Option<&PrfOption>) -> Result<PrfOption> {
|
||||
let mut options = PrfOption {
|
||||
update_interval: source.and_then(|options| options.update_interval),
|
||||
merge: source.and_then(|options| options.merge.clone()),
|
||||
script: source.and_then(|options| options.script.clone()),
|
||||
@@ -71,14 +60,23 @@ fn creation_options(source: Option<&PrfOption>) -> PrfOption {
|
||||
proxies: source.and_then(|options| options.proxies.clone()),
|
||||
groups: source.and_then(|options| options.groups.clone()),
|
||||
..PrfOption::default()
|
||||
};
|
||||
if options.merge.is_none() {
|
||||
options.merge = Some(append_companion_item(&mut build_merge_profile(None)).await?);
|
||||
}
|
||||
}
|
||||
|
||||
async fn append_companions(companions: Vec<PrfItem>) -> Result<()> {
|
||||
for mut item in companions {
|
||||
profiles::append_profile(&mut item).await?;
|
||||
if options.script.is_none() {
|
||||
options.script = Some(append_companion_item(&mut build_script_profile(None)).await?);
|
||||
}
|
||||
Ok(())
|
||||
if options.rules.is_none() {
|
||||
options.rules = Some(append_companion_item(&mut from_rules()).await?);
|
||||
}
|
||||
if options.proxies.is_none() {
|
||||
options.proxies = Some(append_companion_item(&mut from_proxies()).await?);
|
||||
}
|
||||
if options.groups.is_none() {
|
||||
options.groups = Some(append_companion_item(&mut from_groups()).await?);
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
async fn from_local(
|
||||
@@ -89,8 +87,7 @@ async fn from_local(
|
||||
) -> Result<PrfItem> {
|
||||
let uid = help::get_uid("L").into();
|
||||
let file = format!("{uid}.yaml").into();
|
||||
let mut options = creation_options(option);
|
||||
append_companions(missing_companions(&mut options)).await?;
|
||||
let options = prepare_profile_options(option).await?;
|
||||
Ok(PrfItem {
|
||||
uid: Some(uid),
|
||||
itype: Some("local".into()),
|
||||
@@ -116,16 +113,12 @@ pub(crate) struct DownloadedSubscription {
|
||||
body: String,
|
||||
}
|
||||
|
||||
impl DownloadedSubscription {
|
||||
pub(super) fn apply(self, item: &mut PrfItem) -> (String, Vec<PrfItem>) {
|
||||
let option = item.option.get_or_insert_with(PrfOption::default);
|
||||
option.update_interval = option.update_interval.or(self.update_interval_minutes);
|
||||
option.allow_auto_update.get_or_insert(true);
|
||||
item.home = self.home;
|
||||
item.extra = self.extra;
|
||||
item.updated = Some(chrono::Local::now().timestamp() as usize);
|
||||
(self.body, missing_companions(option))
|
||||
}
|
||||
pub(crate) struct RemoteProfileRefresh {
|
||||
pub(super) extra: Option<PrfExtra>,
|
||||
pub(super) home: Option<String>,
|
||||
pub(super) updated: usize,
|
||||
pub(super) option: PrfOption,
|
||||
pub(super) body: String,
|
||||
}
|
||||
|
||||
pub(crate) async fn build_remote_profile(
|
||||
@@ -142,22 +135,28 @@ pub(crate) async fn build_remote_profile(
|
||||
.or_else(|| downloaded.suggested_name.take().map(Into::into))
|
||||
.unwrap_or_else(|| "Remote File".into());
|
||||
let url = downloaded.url.as_str().into();
|
||||
let mut options = creation_options(option);
|
||||
options.allow_auto_update = option.and_then(|value| value.allow_auto_update);
|
||||
let mut item = PrfItem {
|
||||
let RemoteProfileRefresh {
|
||||
extra,
|
||||
home,
|
||||
updated,
|
||||
option,
|
||||
body,
|
||||
} = prepare_remote_refresh(downloaded, option).await?;
|
||||
|
||||
Ok(PrfItem {
|
||||
uid: Some(uid),
|
||||
itype: Some("remote".into()),
|
||||
name: Some(name),
|
||||
desc: desc.cloned(),
|
||||
file: Some(file),
|
||||
url: Some(url),
|
||||
option: Some(options),
|
||||
..Default::default()
|
||||
};
|
||||
let (body, companions) = downloaded.apply(&mut item);
|
||||
append_companions(companions).await?;
|
||||
item.file_data = Some(body);
|
||||
Ok(item)
|
||||
selected: None,
|
||||
extra,
|
||||
option: Some(option),
|
||||
home,
|
||||
updated: Some(updated),
|
||||
file_data: Some(body),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn subscription_proxy(options: Option<&PrfOption>) -> ProxyType {
|
||||
@@ -213,6 +212,22 @@ pub(crate) async fn download_subscription(
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn prepare_remote_refresh(
|
||||
downloaded: DownloadedSubscription,
|
||||
option: Option<&PrfOption>,
|
||||
) -> Result<RemoteProfileRefresh> {
|
||||
let mut options = prepare_profile_options(option).await?;
|
||||
options.update_interval = options.update_interval.or(downloaded.update_interval_minutes);
|
||||
options.allow_auto_update = Some(option.and_then(|options| options.allow_auto_update).unwrap_or(true));
|
||||
Ok(RemoteProfileRefresh {
|
||||
extra: downloaded.extra,
|
||||
home: downloaded.home,
|
||||
updated: chrono::Local::now().timestamp() as usize,
|
||||
option: options,
|
||||
body: downloaded.body,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn build_merge_profile(uid: Option<String>) -> PrfItem {
|
||||
let (id, template) = if let Some(uid) = uid {
|
||||
(uid, tmpl::ITEM_MERGE.into())
|
||||
@@ -365,14 +380,7 @@ mod tests {
|
||||
..option
|
||||
};
|
||||
let downloaded = download_subscription(&url, Some(&refresh_option), ProxyType::None).await?;
|
||||
let mut refresh = PrfItem {
|
||||
option: Some(PrfOption {
|
||||
groups: None,
|
||||
..refresh_option.clone()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let (body, companions) = downloaded.apply(&mut refresh);
|
||||
let refresh = prepare_remote_refresh(downloaded, Some(&refresh_option)).await?;
|
||||
server.await??;
|
||||
assert_eq!(item.itype.as_deref(), Some("remote"));
|
||||
assert_eq!(item.name.as_deref(), Some("remote.yaml"));
|
||||
@@ -385,19 +393,16 @@ mod tests {
|
||||
assert_eq!(fetched_option.update_interval, Some(0));
|
||||
assert_eq!(fetched_option.allow_auto_update, Some(false));
|
||||
|
||||
assert_eq!(body.as_str(), BODY);
|
||||
assert_eq!(refresh.body.as_str(), BODY);
|
||||
assert_eq!(refresh.home, item.home);
|
||||
let usage = refresh.extra.context("expected refresh usage")?;
|
||||
assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4));
|
||||
assert_eq!(companions.len(), 1);
|
||||
assert_eq!(companions[0].itype.as_deref(), Some("groups"));
|
||||
assert_eq!(
|
||||
refresh.option,
|
||||
Some(PrfOption {
|
||||
PrfOption {
|
||||
update_interval: Some(120),
|
||||
groups: companions[0].uid.clone(),
|
||||
..refresh_option
|
||||
})
|
||||
..fetched_option
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,342 +0,0 @@
|
||||
use anyhow::{Result, anyhow};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_profile_store::RECOVERY_JOURNAL_NAME;
|
||||
use parking_lot::Mutex;
|
||||
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||
|
||||
static PROFILE_IO: RwLock<()> = RwLock::const_new(());
|
||||
static BLOCKED: Mutex<Option<StorageBlock>> = Mutex::new(None);
|
||||
|
||||
enum StorageBlock {
|
||||
Transaction(RecoveryRequired),
|
||||
Restore(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct RecoveryRequired(Option<String>);
|
||||
|
||||
impl std::fmt::Display for RecoveryRequired {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&match self.0.as_deref() {
|
||||
Some(name) => clash_verge_i18n::t!("profileRecovery.named", name = name),
|
||||
None => clash_verge_i18n::t!("profileRecovery.unknown"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RecoveryRequired {}
|
||||
|
||||
pub(crate) fn check() -> Result<()> {
|
||||
match BLOCKED.lock().as_ref() {
|
||||
Some(StorageBlock::Transaction(recovery)) => Err(recovery.clone().into()),
|
||||
Some(StorageBlock::Restore(reason)) => Err(anyhow!("Profile storage requires recovery before use: {reason}")),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn block(name: Option<&str>, error: &anyhow::Error) -> anyhow::Error {
|
||||
logging!(error, Type::Config, "Profile recovery required: {error:#}");
|
||||
let mut blocked = BLOCKED.lock();
|
||||
if let Some(StorageBlock::Transaction(recovery)) = blocked.as_ref() {
|
||||
return recovery.clone().into();
|
||||
}
|
||||
let recovery = RecoveryRequired(name.filter(|name| !name.trim().is_empty()).map(str::to_owned));
|
||||
*blocked = Some(StorageBlock::Transaction(recovery.clone()));
|
||||
drop(blocked);
|
||||
recovery.into()
|
||||
}
|
||||
|
||||
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
|
||||
fn block_store(error: clash_verge_profile_store::StoreError) -> anyhow::Error {
|
||||
match error {
|
||||
clash_verge_profile_store::StoreError::NamedRecovery { name, source } => {
|
||||
block(Some(&name), &anyhow::Error::from(*source))
|
||||
}
|
||||
error => block(None, &error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn block_restore(error: &anyhow::Error) {
|
||||
let mut blocked = BLOCKED.lock();
|
||||
if !matches!(*blocked, Some(StorageBlock::Transaction(_))) {
|
||||
*blocked = Some(StorageBlock::Restore(format!("{error:#}")));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn write_for_restore() -> Result<(RwLockWriteGuard<'static, ()>, bool)> {
|
||||
let guard = PROFILE_IO.write().await;
|
||||
let retry = match BLOCKED.lock().as_ref() {
|
||||
Some(StorageBlock::Transaction(reason)) => {
|
||||
return Err(reason.clone().into());
|
||||
}
|
||||
Some(StorageBlock::Restore(_)) => true,
|
||||
None => false,
|
||||
};
|
||||
Ok((guard, retry))
|
||||
}
|
||||
|
||||
pub(crate) fn finish_restore(_guard: &RwLockWriteGuard<'_, ()>) {
|
||||
let mut blocked = BLOCKED.lock();
|
||||
if matches!(*blocked, Some(StorageBlock::Restore(_))) {
|
||||
*blocked = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn read() -> Result<RwLockReadGuard<'static, ()>> {
|
||||
let guard = PROFILE_IO.read().await;
|
||||
check()?;
|
||||
Ok(guard)
|
||||
}
|
||||
|
||||
pub(crate) async fn write() -> Result<RwLockWriteGuard<'static, ()>> {
|
||||
let guard = PROFILE_IO.write().await;
|
||||
check()?;
|
||||
Ok(guard)
|
||||
}
|
||||
|
||||
pub(crate) async fn recover_at_startup() -> Result<()> {
|
||||
let _guard = write().await?;
|
||||
let root = crate::utils::dirs::app_home_dir().map_err(|error| block(None, &error))?;
|
||||
if !journal_exists(&root).await.map_err(|error| block(None, &error))? {
|
||||
return Ok(());
|
||||
}
|
||||
tokio::task::spawn_blocking(move || {
|
||||
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
|
||||
return clash_verge_profile_store::recover_pending(&root).map_err(block_store);
|
||||
#[cfg(all(windows, not(feature = "profile-store-windows")))]
|
||||
return Err(block(
|
||||
clash_verge_profile_store::pending_refresh_name(&root).as_deref(),
|
||||
&anyhow!("restore the pending profile transaction with redo support enabled"),
|
||||
));
|
||||
})
|
||||
.await
|
||||
.map_err(|error| block(None, &error.into()))?
|
||||
}
|
||||
|
||||
async fn journal_exists(root: &std::path::Path) -> Result<bool> {
|
||||
match tokio::fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)).await {
|
||||
Ok(_) => Ok(true),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn commit_refresh(
|
||||
uid: String,
|
||||
candidate: super::IProfiles,
|
||||
body: tristr::alias::String,
|
||||
) -> Result<super::IProfiles> {
|
||||
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
|
||||
let mut candidate = commit_recoverable_refresh(uid, candidate, body).await?;
|
||||
#[cfg(not(any(unix, all(windows, feature = "profile-store-windows"))))]
|
||||
let mut candidate = {
|
||||
write_legacy_refresh(&crate::utils::dirs::app_home_dir()?, &uid, &candidate, body.as_bytes()).await?;
|
||||
candidate
|
||||
};
|
||||
for item in candidate.items.iter_mut().flatten() {
|
||||
item.file_data = None;
|
||||
}
|
||||
Ok(candidate)
|
||||
}
|
||||
|
||||
#[cfg(any(not(unix), test))]
|
||||
async fn write_legacy_refresh(
|
||||
root: &std::path::Path,
|
||||
uid: &str,
|
||||
candidate: &super::IProfiles,
|
||||
body: &[u8],
|
||||
) -> Result<()> {
|
||||
use anyhow::Context as _;
|
||||
|
||||
let file = candidate
|
||||
.get_item(uid)?
|
||||
.file
|
||||
.as_deref()
|
||||
.context("missing profile filename")?;
|
||||
let path = root.join(crate::utils::dirs::PROFILES_DIR).join(file);
|
||||
let mut target = tokio::fs::File::create(path)
|
||||
.await
|
||||
.with_context(|| format!("failed to write to file \"{file}\""))?;
|
||||
use tokio::io::AsyncWriteExt as _;
|
||||
async {
|
||||
target.write_all(body).await?;
|
||||
target.flush().await
|
||||
}
|
||||
.await
|
||||
.with_context(|| format!("profile body {file} may be incomplete; the index was not updated"))?;
|
||||
drop(target);
|
||||
let mut created = Vec::new();
|
||||
let result: Result<()> = async {
|
||||
for item in candidate.items.iter().flatten() {
|
||||
let Some(data) = &item.file_data else { continue };
|
||||
let name = item.file.as_deref().context("missing companion filename")?;
|
||||
super::profiles::validate_profile_file(name)?;
|
||||
let path = root.join(crate::utils::dirs::PROFILES_DIR).join(name);
|
||||
let mut options = tokio::fs::OpenOptions::new();
|
||||
options.create_new(true).write(true);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows_sys::Win32::Storage::FileSystem::{DELETE, FILE_GENERIC_WRITE, FILE_SHARE_READ};
|
||||
options
|
||||
.access_mode(FILE_GENERIC_WRITE | DELETE)
|
||||
.share_mode(FILE_SHARE_READ);
|
||||
}
|
||||
let mut file = options.open(&path).await?;
|
||||
let written = async {
|
||||
file.write_all(data.as_bytes()).await?;
|
||||
file.flush().await
|
||||
}
|
||||
.await;
|
||||
created.push((path, file));
|
||||
written?;
|
||||
}
|
||||
super::profiles::save_profile_index(&root.join(crate::utils::dirs::PROFILE_YAML), candidate).await
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
let mut error = error;
|
||||
for (path, file) in created {
|
||||
#[cfg(windows)]
|
||||
let cleanup = {
|
||||
use std::os::windows::io::AsRawHandle as _;
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
FILE_DISPOSITION_INFO, FileDispositionInfo, SetFileInformationByHandle,
|
||||
};
|
||||
let disposition = FILE_DISPOSITION_INFO { DeleteFile: 1 };
|
||||
// Remove only the file this refresh created, even if its parent has been renamed.
|
||||
let deleted = unsafe {
|
||||
SetFileInformationByHandle(
|
||||
file.as_raw_handle(),
|
||||
FileDispositionInfo,
|
||||
(&raw const disposition).cast(),
|
||||
std::mem::size_of::<FILE_DISPOSITION_INFO>() as u32,
|
||||
)
|
||||
};
|
||||
if deleted == 0 {
|
||||
Err(std::io::Error::last_os_error())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let cleanup = {
|
||||
drop(file);
|
||||
tokio::fs::remove_file(&path).await
|
||||
};
|
||||
if let Err(cleanup) = cleanup {
|
||||
error = error.context(format!("failed to clean up {}: {cleanup}", path.display()));
|
||||
}
|
||||
}
|
||||
return Err(error)
|
||||
.with_context(|| format!("profile body was written to {file}, but the index was not updated"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
|
||||
async fn commit_recoverable_refresh(
|
||||
uid: String,
|
||||
candidate: super::IProfiles,
|
||||
body: tristr::alias::String,
|
||||
) -> Result<super::IProfiles> {
|
||||
use clash_verge_profile_store::{CommitOutcome, Session};
|
||||
|
||||
let root = crate::utils::dirs::app_home_dir()?;
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let probe_root = root.clone();
|
||||
let supported =
|
||||
tokio::task::spawn_blocking(move || clash_verge_profile_store::supports_redo(&probe_root)).await??;
|
||||
if !supported {
|
||||
if journal_exists(&root).await? {
|
||||
let error = anyhow!("Profile refresh journal requires a supported NTFS volume");
|
||||
return Err(block(
|
||||
clash_verge_profile_store::pending_refresh_name(&root).as_deref(),
|
||||
&error,
|
||||
));
|
||||
}
|
||||
write_legacy_refresh(&root, &uid, &candidate, body.as_bytes()).await?;
|
||||
return Ok(candidate);
|
||||
}
|
||||
}
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let session = Session::open(&root).map_err(|error| {
|
||||
match std::fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)) {
|
||||
Err(status) if status.kind() == std::io::ErrorKind::NotFound => error.into(),
|
||||
_ => block_store(error),
|
||||
}
|
||||
})?;
|
||||
let item = candidate.get_item(&uid)?;
|
||||
if let Some(file) = item.file.as_deref()
|
||||
&& !file.contains(['/', '\\', '\0'])
|
||||
&& (!cfg!(windows) || !file.contains(':'))
|
||||
&& !matches!(file, "" | "." | "..")
|
||||
{
|
||||
let path = root.join("profiles").join(file);
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Ok(metadata) if metadata.is_file() => {
|
||||
std::fs::OpenOptions::new().write(true).open(&path)?;
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
}
|
||||
match session.commit_refresh(&uid, &candidate, body.as_bytes()) {
|
||||
CommitOutcome::Committed => Ok(candidate),
|
||||
CommitOutcome::CommittedCleanupPending(error) => {
|
||||
let _ = block(item.name.as_deref(), &error.into());
|
||||
Ok(candidate)
|
||||
}
|
||||
CommitOutcome::Retryable(error) => {
|
||||
Err(anyhow::Error::from(error).context("profile refresh stopped before commit"))
|
||||
}
|
||||
CommitOutcome::RetryCleanupFailed(error) => {
|
||||
let error = anyhow::Error::from(error);
|
||||
Err(block(item.name.as_deref(), &error).context("failed to discard the incomplete profile refresh"))
|
||||
}
|
||||
CommitOutcome::NeedsRecovery(error) => {
|
||||
let error = anyhow::Error::from(error);
|
||||
Err(block(item.name.as_deref(), &error))
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
match result {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
let error = anyhow::Error::from(error).context("profile storage worker stopped unexpectedly");
|
||||
Err(block(None, &error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recovery_message_identifies_the_subscription_in_the_active_language() {
|
||||
let named = RecoveryRequired(Some("工作线路".into())).to_string();
|
||||
assert!(named.contains("工作线路"));
|
||||
let unknown = RecoveryRequired(None).to_string();
|
||||
assert!(!unknown.contains("工作线路"));
|
||||
assert_ne!(unknown, "profileRecovery.unknown");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_refresh_reports_a_written_body_when_index_replace_fails() -> Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let root = home.path();
|
||||
std::fs::create_dir(root.join("profiles"))?;
|
||||
std::fs::create_dir(root.join("profiles.yaml"))?;
|
||||
let mut profiles: super::super::IProfiles =
|
||||
serde_yaml_ng::from_str("items: [{uid: r, file: old.yaml}, {uid: s, type: script, file: s.js}]")?;
|
||||
profiles.get_item_mut("s")?.file_data = Some("template".into());
|
||||
let result = write_legacy_refresh(root, "r", &profiles, b"new body").await;
|
||||
assert_eq!(std::fs::read(root.join("profiles/old.yaml"))?, b"new body");
|
||||
assert!(result.unwrap_err().to_string().contains("body was written"));
|
||||
assert!(!root.join("profiles/s.js").exists());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
use super::{
|
||||
PrfItem, PrfOption, PrfSelected, patch_opt_field,
|
||||
prfitem::{DownloadedSubscription, build_profile},
|
||||
profile_storage,
|
||||
prfitem::{RemoteProfileRefresh, build_profile},
|
||||
};
|
||||
use crate::core::notify::{Refresh, announce};
|
||||
use crate::{
|
||||
@@ -71,62 +70,58 @@ pub(crate) async fn cleanup_profile_files(files: Vec<String>) {
|
||||
}
|
||||
|
||||
pub(crate) async fn load_profiles() -> IProfiles {
|
||||
match load_profiles_checked().await {
|
||||
Ok(profiles) => profiles,
|
||||
Err(error) => {
|
||||
logging!(error, Type::Config, "failed to load profiles: {error:#}");
|
||||
let path = match dirs::profiles_path() {
|
||||
Ok(p) => p,
|
||||
Err(err) => {
|
||||
logging!(error, Type::Config, "failed to get profiles path: {err:#}");
|
||||
return IProfiles::default();
|
||||
}
|
||||
};
|
||||
|
||||
match help::read_yaml::<IProfiles>(&path).await {
|
||||
Ok(mut profiles) => {
|
||||
let items = profiles.items.get_or_insert_with(Vec::new);
|
||||
let mut home_changed = false;
|
||||
for item in items.iter_mut() {
|
||||
if item.uid.is_none() {
|
||||
item.uid = Some(help::get_uid("d").into());
|
||||
}
|
||||
if item.itype.as_deref() == Some("remote") {
|
||||
item.option
|
||||
.get_or_insert_with(PrfOption::default)
|
||||
.allow_auto_update
|
||||
.get_or_insert(true);
|
||||
}
|
||||
|
||||
if item
|
||||
.home
|
||||
.as_deref()
|
||||
.is_some_and(|home| normalize_profile_home_url(home).is_none())
|
||||
{
|
||||
item.home = None;
|
||||
home_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if home_changed && let Err(err) = save_profiles(&profiles).await {
|
||||
logging!(error, Type::Config, "无法保存已清理的 profiles.yaml: {err:#}");
|
||||
}
|
||||
profiles
|
||||
}
|
||||
Err(err) => {
|
||||
logging!(error, Type::Config, "failed to read profiles.yaml: {err:#}");
|
||||
IProfiles::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn load_profiles_checked() -> Result<IProfiles> {
|
||||
profile_storage::check()?;
|
||||
load_profiles_unlocked().await
|
||||
}
|
||||
|
||||
pub(crate) async fn load_profiles_unlocked() -> Result<IProfiles> {
|
||||
let mut profiles: IProfiles = help::read_yaml(&dirs::profiles_path()?).await?;
|
||||
let items = profiles.items.get_or_insert_with(Vec::new);
|
||||
let mut home_changed = false;
|
||||
for item in items.iter_mut() {
|
||||
if item.uid.is_none() {
|
||||
item.uid = Some(help::get_uid("d").into());
|
||||
}
|
||||
if item.itype.as_deref() == Some("remote") {
|
||||
item.option
|
||||
.get_or_insert_with(PrfOption::default)
|
||||
.allow_auto_update
|
||||
.get_or_insert(true);
|
||||
}
|
||||
|
||||
if item
|
||||
.home
|
||||
.as_deref()
|
||||
.is_some_and(|home| normalize_profile_home_url(home).is_none())
|
||||
{
|
||||
item.home = None;
|
||||
home_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if home_changed && let Err(err) = save_profiles_unlocked(&profiles).await {
|
||||
logging!(error, Type::Config, "无法保存已清理的 profiles.yaml: {err:#}");
|
||||
}
|
||||
Ok(profiles)
|
||||
}
|
||||
|
||||
pub(crate) async fn save_profiles(profiles: &IProfiles) -> Result<()> {
|
||||
let _guard = profile_storage::write().await?;
|
||||
save_profiles_unlocked(profiles).await
|
||||
}
|
||||
|
||||
pub(crate) async fn save_profiles_unlocked(profiles: &IProfiles) -> Result<()> {
|
||||
save_profile_index(&dirs::profiles_path()?, profiles).await
|
||||
}
|
||||
|
||||
pub(super) async fn save_profile_index(path: &Path, profiles: &IProfiles) -> Result<()> {
|
||||
help::save_yaml(path, profiles, Some("# Profiles Config for Clash Verge")).await
|
||||
help::save_yaml(
|
||||
&dirs::profiles_path()?,
|
||||
profiles,
|
||||
Some("# Profiles Config for Clash Verge"),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn append_item(profiles: &mut IProfiles, item: &mut PrfItem) -> Result<()> {
|
||||
@@ -182,7 +177,7 @@ async fn patch_item(profiles: &mut IProfiles, uid: &str, item: &PrfItem) -> Resu
|
||||
bail!("failed to find the profile item \"uid:{uid}\"")
|
||||
}
|
||||
|
||||
pub(crate) fn validate_profile_file(file: &str) -> Result<()> {
|
||||
fn validate_profile_file(file: &str) -> Result<()> {
|
||||
let mut components = Path::new(file).components();
|
||||
if file.is_empty()
|
||||
|| file.contains('/')
|
||||
@@ -266,7 +261,6 @@ pub(crate) async fn append_profile(item: &mut PrfItem) -> Result<()> {
|
||||
pub(super) async fn append_to_profile_index(profiles: &Draft<IProfiles>, item: &mut PrfItem) -> Result<()> {
|
||||
profiles
|
||||
.with_data_modify(|mut profiles| async move {
|
||||
let _guard = profile_storage::write().await?;
|
||||
append_item(&mut profiles, item).await?;
|
||||
Ok((profiles, ()))
|
||||
})
|
||||
@@ -295,62 +289,28 @@ pub(crate) async fn save_committed_profiles() -> Result<()> {
|
||||
with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await
|
||||
}
|
||||
|
||||
fn check_refresh_source(current: &PrfItem, url: &str, file: Option<&String>) -> Result<()> {
|
||||
anyhow::ensure!(
|
||||
current.itype.as_deref() == Some("remote")
|
||||
&& current.url.as_deref() == Some(url)
|
||||
&& current.file.as_ref() == file,
|
||||
"profile source or filename changed during refresh"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn save_remote_refresh(
|
||||
uid: &str,
|
||||
url: String,
|
||||
file: Option<String>,
|
||||
downloaded: DownloadedSubscription,
|
||||
) -> Result<()> {
|
||||
let uid = uid.to_owned();
|
||||
// Dropping the caller must not separate an issued disk write from its Draft publication.
|
||||
tokio::spawn(async move {
|
||||
let _profile_write = PROFILE_WRITE_LOCK.lock().await;
|
||||
anyhow::ensure!(!handle::Handle::global().is_exiting(), "application is exiting");
|
||||
let draft = Config::profiles().await;
|
||||
let mut name = None;
|
||||
let mut storage_guard = None;
|
||||
let mut persisted = false;
|
||||
let result = {
|
||||
let storage_guard = &mut storage_guard;
|
||||
let persisted = &mut persisted;
|
||||
let name = &mut name;
|
||||
draft
|
||||
.with_data_modify(|mut candidate| async move {
|
||||
*storage_guard = Some(profile_storage::write().await?);
|
||||
let profile = candidate.get_item_mut(&uid)?;
|
||||
check_refresh_source(profile, &url, file.as_ref())?;
|
||||
*name = profile.name.clone();
|
||||
let (body, companions) = downloaded.apply(profile);
|
||||
profile
|
||||
.file
|
||||
.get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into());
|
||||
candidate.items.get_or_insert_with(Vec::new).extend(companions);
|
||||
let candidate = profile_storage::commit_refresh(uid, candidate, body).await?;
|
||||
*persisted = true;
|
||||
Ok((candidate, ()))
|
||||
})
|
||||
.await
|
||||
};
|
||||
if let Err(error) = &result
|
||||
&& persisted
|
||||
{
|
||||
return Err(profile_storage::block(name.as_deref(), error).context("Profile refresh was saved"));
|
||||
}
|
||||
drop(storage_guard);
|
||||
result?;
|
||||
profile_storage::check().context("Profile refresh was saved")
|
||||
pub(crate) async fn save_remote_refresh(uid: &str, url: &str, refresh: RemoteProfileRefresh) -> Result<()> {
|
||||
with_profiles_edit(|mut profiles| async move {
|
||||
let profile = profiles.get_item_mut(uid)?;
|
||||
anyhow::ensure!(
|
||||
profile.itype.as_deref() == Some("remote") && profile.url.as_deref() == Some(url),
|
||||
"profile source changed during refresh"
|
||||
);
|
||||
profile.extra = refresh.extra;
|
||||
profile.updated = Some(refresh.updated);
|
||||
profile.home = refresh.home;
|
||||
profile.option = PrfOption::merge(profile.option.as_ref(), Some(&refresh.option));
|
||||
let file = profile
|
||||
.file
|
||||
.get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into());
|
||||
let path = dirs::app_profiles_dir()?.join(file.as_str());
|
||||
fs::write(&path, refresh.body.as_bytes())
|
||||
.await
|
||||
.with_context(|| format!("failed to write to file \"{file}\""))?;
|
||||
save_profiles(&profiles).await?;
|
||||
Ok(profiles)
|
||||
})
|
||||
.await?
|
||||
.await
|
||||
}
|
||||
|
||||
fn selected_group<'a>(snapshot: &'a Proxies, name: &str) -> Option<SelectedGroup<'a>> {
|
||||
|
||||
@@ -277,22 +277,20 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
|
||||
let file = AsyncHandler::spawn_blocking(move || std::fs::File::create(&value)).await??;
|
||||
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?;
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
let path = entry.path();
|
||||
if path.is_file() {
|
||||
let file_name_os = entry.file_name();
|
||||
let file_name = file_name_os
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
|
||||
let mut entry = archive.start_profile(file_name)?;
|
||||
let file_content = fs::read(&path).await?;
|
||||
entry.write_all(&file_content)?;
|
||||
if let Ok(mut entries) = fs::read_dir(dirs::app_profiles_dir()?).await {
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
let path = entry.path();
|
||||
if path.is_file() {
|
||||
let file_name_os = entry.file_name();
|
||||
let file_name = file_name_os
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
|
||||
let mut entry = archive.start_profile(file_name)?;
|
||||
let file_content = fs::read(&path).await?;
|
||||
entry.write_all(&file_content)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let profile_index = fs::read(dirs::profiles_path()?).await?;
|
||||
drop(profile_guard);
|
||||
|
||||
archive
|
||||
.start_file(dirs::CLASH_CONFIG)?
|
||||
@@ -316,7 +314,9 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
|
||||
.write_all(&fs::read(&dns_config_path).await?)?;
|
||||
}
|
||||
|
||||
archive.start_file(dirs::PROFILE_YAML)?.write_all(&profile_index)?;
|
||||
archive
|
||||
.start_file(dirs::PROFILE_YAML)?
|
||||
.write_all(&fs::read(dirs::profiles_path()?).await?)?;
|
||||
archive.finish()?;
|
||||
Ok((zip_file_name, zip_path))
|
||||
}
|
||||
|
||||
@@ -88,8 +88,8 @@ fn plan_config_application(attempt: &StageAttempt) -> ConfigApplication {
|
||||
}
|
||||
}
|
||||
|
||||
async fn ask_to_stage(path: &std::path::Path) -> StageAttempt {
|
||||
match crate::core::service::stage_runtime_by_service(path).await {
|
||||
async fn ask_to_stage(path: &std::path::Path, session: &clash_verge_service_ipc::OwnerSessionProof) -> StageAttempt {
|
||||
match crate::core::service::stage_runtime_by_service(path, session).await {
|
||||
Ok(StageRequest::Answered(outcome)) => StageAttempt::Answered(outcome),
|
||||
Ok(StageRequest::Refused { code, message }) => {
|
||||
let message = message.into();
|
||||
@@ -433,10 +433,10 @@ impl CoreManager {
|
||||
}
|
||||
|
||||
async fn attempt_staging(&self, path: &std::path::Path) -> StageAttempt {
|
||||
if !crate::core::service::active_service_supports_runtime_staging() {
|
||||
let Ok(session) = crate::core::service::active_service_session() else {
|
||||
return StageAttempt::Unsupported;
|
||||
}
|
||||
stage_with_confirmation(timing::STAGE_CONFIRM_TIMEOUT, || ask_to_stage(path)).await
|
||||
};
|
||||
stage_with_confirmation(timing::STAGE_CONFIRM_TIMEOUT, || ask_to_stage(path, &session)).await
|
||||
}
|
||||
|
||||
/// Reload the Core from `path`, and replace the Core if it will not take it.
|
||||
|
||||
@@ -188,48 +188,6 @@ where
|
||||
apply_proxy().await
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
async fn run_service_start_with_sidecar_fallback<Start, StartFuture, Check, CheckFuture, Fallback, FallbackFuture>(
|
||||
start_service: Start,
|
||||
confirm_idle: Check,
|
||||
start_sidecar: Fallback,
|
||||
record_unavailable: impl FnOnce(std::string::String),
|
||||
) -> Result<()>
|
||||
where
|
||||
Start: FnOnce() -> StartFuture,
|
||||
StartFuture: std::future::Future<Output = Result<()>>,
|
||||
Check: FnOnce() -> CheckFuture,
|
||||
CheckFuture: std::future::Future<Output = Result<()>>,
|
||||
Fallback: FnOnce(anyhow::Error) -> FallbackFuture,
|
||||
FallbackFuture: std::future::Future<Output = Result<()>>,
|
||||
{
|
||||
let Err(error) = start_service().await else {
|
||||
return Ok(());
|
||||
};
|
||||
let refusal = error.downcast_ref::<crate::core::service::ServiceStartRefusal>();
|
||||
let location_refused = refusal.is_some_and(|refusal| {
|
||||
refusal.code == clash_verge_service_ipc::ServiceErrorCode::InvalidInstallLocation as u16
|
||||
});
|
||||
if refusal.is_some() && !location_refused {
|
||||
return Err(error);
|
||||
}
|
||||
// A lost start response can hide a running core; the shared check must resolve occupancy.
|
||||
if let Err(probe_error) = confirm_idle().await {
|
||||
let error = error.context(format!("Sidecar fallback was not safe: {probe_error:#}"));
|
||||
record_unavailable(format!("{error:#}"));
|
||||
return Err(error);
|
||||
}
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"Service could not start the core; falling back to Sidecar: {error:#}"
|
||||
);
|
||||
let reason = format!("{error:#}");
|
||||
start_sidecar(error)
|
||||
.await
|
||||
.map_err(|error| error.context(format!("Sidecar fallback failed after Service failure: {reason}")))
|
||||
}
|
||||
|
||||
async fn run_sidecar_termination_transition<Clear, ClearFuture, Terminate, TerminateFuture>(
|
||||
clear_proxy: Clear,
|
||||
terminate_sidecar: Terminate,
|
||||
@@ -326,11 +284,7 @@ where
|
||||
start_sidecar().await
|
||||
}
|
||||
|
||||
fn report_sidecar_failure(error: anyhow::Error, service_rejection: Option<&str>) -> anyhow::Error {
|
||||
let error = match service_rejection {
|
||||
Some(reason) => error.context(format!("Service core rejected: {reason}; Sidecar fallback failed")),
|
||||
None => error,
|
||||
};
|
||||
fn report_sidecar_failure(error: anyhow::Error) -> anyhow::Error {
|
||||
// Proxy failures have their own pending state and recovery dialog.
|
||||
if SysproxyFailure::from_chain(&error).is_none() {
|
||||
crate::core::notification::record_sidecar_failure(format!("{error:#}").into());
|
||||
@@ -368,12 +322,11 @@ impl CoreManager {
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, level = "info", fields(status = tracing::field::Empty, tun_disabled = false, readiness_generation = tracing::field::Empty))]
|
||||
pub async fn continue_with_sidecar(&self, service_rejection: Option<&str>) -> Result<()> {
|
||||
pub async fn continue_with_sidecar(&self) -> Result<()> {
|
||||
if !self.try_start_config_update() {
|
||||
return Err(report_sidecar_failure(
|
||||
anyhow::anyhow!("configuration update is already running"),
|
||||
service_rejection,
|
||||
));
|
||||
return Err(report_sidecar_failure(anyhow::anyhow!(
|
||||
"configuration update is already running"
|
||||
)));
|
||||
}
|
||||
let _config_update = DropGuard::new((), |()| {
|
||||
self.finish_config_update();
|
||||
@@ -390,11 +343,8 @@ impl CoreManager {
|
||||
if !can_allow_sidecar_for_session(&mode, &status) {
|
||||
anyhow::bail!("Sidecar continuation is not allowed from {mode:?} / {status:?}");
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
if matches!(*mode, RunningMode::NotRunning) {
|
||||
clash_verge_service_ipc::execution::check_sidecar_available()
|
||||
.await
|
||||
.map_err(super::state::explain_core_occupancy)?;
|
||||
crate::core::service::release_service_core_for_sidecar().await?;
|
||||
}
|
||||
if !matches!(status, ServiceStatus::SidecarAllowed) {
|
||||
SERVICE_MANAGER.allow_sidecar_for_session()?;
|
||||
@@ -447,7 +397,7 @@ impl CoreManager {
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
result.map_err(|error| report_sidecar_failure(error, service_rejection))
|
||||
result.map_err(report_sidecar_failure)
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, level = "info", fields(readiness_generation = tracing::field::Empty))]
|
||||
@@ -463,6 +413,7 @@ impl CoreManager {
|
||||
let _life = self.lifecycle_lock.lock().await;
|
||||
|
||||
self.controlled_stop_core_inner().await?;
|
||||
crate::core::service::release_service_core_for_sidecar().await?;
|
||||
|
||||
let result = run_uninstall_transition(
|
||||
|| async {
|
||||
@@ -638,8 +589,6 @@ impl CoreManager {
|
||||
self.rollback_failed_start().await;
|
||||
#[cfg(target_os = "macos")]
|
||||
crate::utils::resolve::dns::sync_public_dns().await;
|
||||
#[cfg(target_os = "windows")]
|
||||
self.try_sidecar_after_service_unavailable().await?;
|
||||
return Ok(());
|
||||
}
|
||||
if Handle::global().is_exiting() {
|
||||
@@ -648,27 +597,15 @@ impl CoreManager {
|
||||
}
|
||||
|
||||
let result = match startup {
|
||||
StartupDecision::Service => {
|
||||
#[cfg(target_os = "windows")]
|
||||
StartupDecision::Service => self.start_core_by_service().await.inspect_err(|error| {
|
||||
if error
|
||||
.downcast_ref::<crate::core::service::ServiceStartRefusal>()
|
||||
.is_none()
|
||||
{
|
||||
run_service_start_with_sidecar_fallback(
|
||||
|| self.start_core_by_service(),
|
||||
|| async {
|
||||
clash_verge_service_ipc::execution::check_sidecar_available()
|
||||
.await
|
||||
.map_err(super::state::explain_core_occupancy)
|
||||
},
|
||||
|error| self.start_sidecar_after_service_failure(error),
|
||||
|reason| {
|
||||
crate::core::runstate::RUN_STATE
|
||||
.observe(crate::core::runstate::ServiceHealth::Unavailable(reason));
|
||||
},
|
||||
)
|
||||
.await
|
||||
crate::core::runstate::RUN_STATE
|
||||
.observe(crate::core::runstate::ServiceHealth::Unavailable(format!("{error:#}")));
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
self.start_core_by_service().await
|
||||
}
|
||||
}),
|
||||
StartupDecision::Sidecar => self.start_core_by_sidecar().await,
|
||||
StartupDecision::Wait => Ok(()),
|
||||
};
|
||||
@@ -684,53 +621,6 @@ impl CoreManager {
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
async fn try_sidecar_after_service_unavailable(&self) -> Result<()> {
|
||||
use crate::core::runstate::{RUN_STATE, ServiceHealth};
|
||||
|
||||
let state = RUN_STATE.state();
|
||||
if state.pending.is_some() || state.op_in_flight || Handle::global().is_exiting() {
|
||||
return Ok(());
|
||||
}
|
||||
let reason = match state.health {
|
||||
ServiceHealth::Unavailable(reason) => reason,
|
||||
ServiceHealth::VersionMismatch => "registered service is unavailable or incompatible".to_owned(),
|
||||
_ => return Ok(()),
|
||||
};
|
||||
if let Err(error) = clash_verge_service_ipc::execution::check_sidecar_available()
|
||||
.await
|
||||
.map_err(super::state::explain_core_occupancy)
|
||||
{
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"Service unavailable ({reason}); Sidecar fallback withheld: {error:#}"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
self.start_sidecar_after_service_failure(anyhow::anyhow!(reason)).await
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
async fn start_sidecar_after_service_failure(&self, error: anyhow::Error) -> Result<()> {
|
||||
use crate::core::runstate::RUN_STATE;
|
||||
|
||||
if Handle::global().is_exiting() {
|
||||
return Err(error.context("application exited before Sidecar fallback"));
|
||||
}
|
||||
let reason = format!("{error:#}");
|
||||
RUN_STATE.allow_sidecar_after_service_refusal(reason.clone())?;
|
||||
logging!(warn, Type::Core, "Starting Sidecar with Service unavailable: {reason}");
|
||||
let result = self.start_core_by_sidecar().await;
|
||||
if result.is_err() {
|
||||
SERVICE_MANAGER.withdraw_sidecar_allowance();
|
||||
self.rollback_failed_start().await;
|
||||
} else {
|
||||
crate::core::service::notify_service_fallback(&reason);
|
||||
}
|
||||
result.map_err(|error| error.context(format!("Service failure before Sidecar startup: {reason}")))
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, level = "info", fields(mode = ?*self.get_running_mode()))]
|
||||
pub async fn stop_core(&self) -> Result<()> {
|
||||
let _life = self.lifecycle_lock.lock().await;
|
||||
@@ -846,13 +736,6 @@ impl CoreManager {
|
||||
let is_admin = is_current_app_handle_admin(Handle::app_handle());
|
||||
|
||||
if !should_wait_for_service(tun_enabled, service_ready, is_admin) {
|
||||
if tun_enabled && !service_ready && is_admin {
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
"service unavailable while app is elevated; starting sidecar immediately"
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -865,8 +748,6 @@ impl CoreManager {
|
||||
return;
|
||||
}
|
||||
|
||||
// Failing to become ready is not fatal here: the caller falls back to Sidecar, and a
|
||||
// transient transport failure must not overwrite the last confirmed install state.
|
||||
let attempts = (timing::SERVICE_WAIT_MAX.as_millis() / timing::SERVICE_WAIT_INTERVAL.as_millis()) as usize;
|
||||
let wait = crate::core::runstate::RUN_STATE.await_ready(attempts, timing::SERVICE_WAIT_INTERVAL);
|
||||
let _ = tokio::time::timeout(timing::SERVICE_WAIT_MAX, wait).await;
|
||||
@@ -1410,46 +1291,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn blocked_windows_fallback_records_failure_without_starting_sidecar() {
|
||||
use crate::core::runstate::{FakeEnv, RunStateStore, ServiceHealth};
|
||||
|
||||
for idle in [false, true] {
|
||||
let store = RunStateStore::new(FakeEnv::new());
|
||||
store.observe(ServiceHealth::Ready);
|
||||
let started = AtomicBool::new(false);
|
||||
let result = super::run_service_start_with_sidecar_fallback(
|
||||
|| async {
|
||||
Err(crate::core::service::ServiceStartRefusal {
|
||||
code: clash_verge_service_ipc::ServiceErrorCode::InvalidInstallLocation as u16,
|
||||
core_path: "verge-mihomo.exe".into(),
|
||||
message: "no administrator-approved copy is installed".into(),
|
||||
}
|
||||
.into())
|
||||
},
|
||||
|| async move {
|
||||
anyhow::ensure!(idle, "another core is running");
|
||||
Ok(())
|
||||
},
|
||||
|_| async {
|
||||
started.store(true, Ordering::SeqCst);
|
||||
Ok(())
|
||||
},
|
||||
|reason| store.observe(ServiceHealth::Unavailable(reason)),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(started.load(Ordering::SeqCst), idle);
|
||||
assert_eq!(result.is_ok(), idle);
|
||||
assert!(!store.state().sidecar_allowed);
|
||||
if !idle {
|
||||
assert!(store.state().service_needs_attention());
|
||||
assert!(!store.state().service_usable());
|
||||
assert!(result.is_err_and(|error| format!("{error:#}").contains("another core is running")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_service_install_can_continue_with_an_existing_sidecar() {
|
||||
assert!(can_allow_sidecar_for_session(
|
||||
|
||||
@@ -231,8 +231,6 @@ impl CoreManager {
|
||||
pub async fn init(&self) -> Result<bool> {
|
||||
const MAX_PORT_FALLBACK_RETRIES: usize = 3;
|
||||
|
||||
crate::config::profile_storage::check()?;
|
||||
|
||||
if let Some(reason) = crate::config::Config::startup_core_block_reason() {
|
||||
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
|
||||
}
|
||||
|
||||
@@ -11,27 +11,14 @@ use crate::{
|
||||
use anyhow::{Context as _, Result};
|
||||
use clash_verge_logging::Type;
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
||||
use futures::{
|
||||
FutureExt as _,
|
||||
future::{Map, Shared},
|
||||
};
|
||||
use futures::{FutureExt as _, future::Shared};
|
||||
use log::Level;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use tauri_plugin_mihomo::MihomoExt as _;
|
||||
use tauri_plugin_shell::ShellExt as _;
|
||||
use tauri_plugin_shell::process::CommandChild;
|
||||
use tokio::task::{JoinError, JoinHandle};
|
||||
|
||||
pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error {
|
||||
let detail = error.to_string();
|
||||
if detail.starts_with("process verge-mihomo") && detail.ends_with("; refusing a second core") {
|
||||
error.context(clash_verge_i18n::t!("core.alreadyRunning").into_owned())
|
||||
} else {
|
||||
error
|
||||
}
|
||||
}
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
|
||||
@@ -146,18 +133,10 @@ fn should_clear_terminated_sidecar(
|
||||
matches!(running_mode, RunningMode::Sidecar) && current_generation == Some(terminated_generation)
|
||||
}
|
||||
|
||||
type ShareExitResult = fn(Result<(), JoinError>) -> Result<(), Arc<JoinError>>;
|
||||
type SidecarExit = Shared<Map<JoinHandle<()>, ShareExitResult>>;
|
||||
|
||||
fn share_exit(exit: JoinHandle<()>) -> SidecarExit {
|
||||
let share_error: ShareExitResult = |result| result.map_err(Arc::new);
|
||||
exit.map(share_error).shared()
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct SidecarSession {
|
||||
process: Option<SidecarProcess>,
|
||||
exit: Option<SidecarExit>,
|
||||
exit: Option<Shared<oneshot::Receiver<()>>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -195,10 +174,7 @@ impl CoreManager {
|
||||
#[tracing::instrument(skip_all, level = "info", fields(pid = tracing::field::Empty))]
|
||||
pub(super) async fn start_core_by_sidecar(&self) -> Result<()> {
|
||||
self.wait_for_sidecar_exit().await?;
|
||||
let execution = clash_verge_service_ipc::execution::reserve_sidecar()
|
||||
.await
|
||||
.inspect_err(service::record_residual_service)
|
||||
.map_err(explain_core_occupancy)?;
|
||||
service::require_service_core_released()?;
|
||||
self.core_stopped();
|
||||
|
||||
let sidecar_ipc = dirs::sidecar_ipc_path()?;
|
||||
@@ -221,13 +197,11 @@ impl CoreManager {
|
||||
#[cfg(unix)]
|
||||
discard_unwritable_core_cache(&config_dir);
|
||||
|
||||
#[cfg(unix)]
|
||||
let previous_mask = unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(0o077) };
|
||||
let command = app_handle
|
||||
.shell()
|
||||
.sidecar(clash_core.as_str())
|
||||
.map_err(|error| anyhow::anyhow!("failed to build sidecar command for core {clash_core:?}: {error:#}"))?;
|
||||
let command = command.args([
|
||||
let command = command.kill_on_drop(true).args([
|
||||
"-d",
|
||||
dirs::path_to_str(&config_dir)?,
|
||||
"-f",
|
||||
@@ -244,6 +218,13 @@ impl CoreManager {
|
||||
"LISTEN_NAMEDPIPE_SDDL",
|
||||
crate::core::owner_identity::current_user_pipe_sddl()?,
|
||||
);
|
||||
#[cfg(unix)]
|
||||
let restore_mask = std::mem::DropGuard::new(
|
||||
unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(0o077) },
|
||||
|mask| {
|
||||
unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(mask) };
|
||||
},
|
||||
);
|
||||
let (mut rx, child) = command.spawn().map_err(|error| {
|
||||
anyhow::anyhow!(
|
||||
"failed to start sidecar core {clash_core:?} with config {} and data directory {}: {error:#}",
|
||||
@@ -251,35 +232,10 @@ impl CoreManager {
|
||||
config_dir.display()
|
||||
)
|
||||
})?;
|
||||
let (terminated, termination) = tokio::sync::oneshot::channel();
|
||||
let exit = execution.release_after_exit(child.pid(), termination);
|
||||
self.sidecar.lock().exit = Some(share_exit(exit));
|
||||
#[cfg(target_os = "windows")]
|
||||
let job = {
|
||||
match create_and_assign_sidecar_job(child.pid()) {
|
||||
Ok(job) => job,
|
||||
Err(job_error) => {
|
||||
let pid = child.pid();
|
||||
|
||||
let error = match child.kill() {
|
||||
Ok(()) => job_error,
|
||||
Err(kill_error) => anyhow::anyhow!(
|
||||
"failed to configure Job Object for sidecar PID {pid}: \
|
||||
{job_error:#}; failed to terminate child: {kill_error:#}"
|
||||
),
|
||||
};
|
||||
|
||||
logging!(error, Type::Core, "Failed to start sidecar: {error:#}");
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
unsafe {
|
||||
tauri_plugin_clash_verge_sysinfo::libc::umask(previous_mask)
|
||||
};
|
||||
|
||||
drop(restore_mask);
|
||||
let (terminated, termination) = oneshot::channel();
|
||||
self.sidecar.lock().exit = Some(termination.shared());
|
||||
let pid = child.pid();
|
||||
tracing::Span::current().record("pid", pid);
|
||||
|
||||
@@ -317,6 +273,30 @@ impl CoreManager {
|
||||
}
|
||||
});
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
let job = {
|
||||
match create_and_assign_sidecar_job(child.pid()) {
|
||||
Ok(job) => job,
|
||||
Err(job_error) => {
|
||||
let pid = child.pid();
|
||||
|
||||
let error = match child.kill() {
|
||||
Ok(()) => {
|
||||
self.sidecar.lock().exit.take();
|
||||
job_error
|
||||
}
|
||||
Err(kill_error) => anyhow::anyhow!(
|
||||
"failed to configure Job Object for sidecar PID {pid}: \
|
||||
{job_error:#}; failed to terminate child: {kill_error:#}"
|
||||
),
|
||||
};
|
||||
|
||||
logging!(error, Type::Core, "Failed to start sidecar: {error:#}");
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let readiness = poll_sidecar_readiness(SIDECAR_READINESS_ATTEMPTS, SIDECAR_READINESS_INTERVAL, || async {
|
||||
tokio::time::timeout(SIDECAR_READINESS_PROBE_TIMEOUT, async {
|
||||
handle::Handle::mihomo().get_version().await
|
||||
@@ -330,7 +310,10 @@ impl CoreManager {
|
||||
proxy_control::stop_guard().await;
|
||||
self.core_stopped();
|
||||
return match child.kill() {
|
||||
Ok(()) => Err(readiness_error),
|
||||
Ok(()) => {
|
||||
self.sidecar.lock().exit.take();
|
||||
Err(readiness_error)
|
||||
}
|
||||
Err(kill_error) => Err(anyhow::anyhow!(
|
||||
"{readiness_error:#}; failed to terminate unready sidecar PID {pid}: {kill_error:#}"
|
||||
)),
|
||||
@@ -358,8 +341,11 @@ impl CoreManager {
|
||||
#[cfg(target_os = "windows")]
|
||||
drop(process.job);
|
||||
|
||||
if let Err(error) = process.child.kill() {
|
||||
logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}");
|
||||
match process.child.kill() {
|
||||
Ok(()) => {
|
||||
self.sidecar.lock().exit.take();
|
||||
}
|
||||
Err(error) => logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}"),
|
||||
}
|
||||
}
|
||||
let result = self.wait_for_sidecar_exit().await;
|
||||
@@ -393,12 +379,13 @@ impl CoreManager {
|
||||
|
||||
#[tracing::instrument(skip_all, level = "info", fields(config_file = %config_file.display()))]
|
||||
pub(super) async fn start_core_by_service_with_config(&self, config_file: &Path) -> Result<()> {
|
||||
// 交接时等待 sidecar 释放 ext-controller 通道。
|
||||
self.wait_for_sidecar_exit().await?;
|
||||
let start = tokio::sync::OnceCell::new();
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use crate::constants::timing;
|
||||
retry_service_start(timing::SERVICE_START_RETRIES, timing::SERVICE_START_RETRY_DELAY, || {
|
||||
service::run_core_by_service(config_file)
|
||||
service::run_core_by_service(config_file, &start)
|
||||
})
|
||||
.await?;
|
||||
self.mark_core_ready();
|
||||
@@ -410,7 +397,7 @@ impl CoreManager {
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
service::run_core_by_service(config_file).await?;
|
||||
service::run_core_by_service(config_file, &start).await?;
|
||||
self.mark_core_ready();
|
||||
self.core_started(RunningMode::Service);
|
||||
self.restore_selected_nodes().await;
|
||||
@@ -556,20 +543,6 @@ mod readiness_tests {
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn core_occupancy_explanation_preserves_the_original_error() {
|
||||
for detail in [
|
||||
"process verge-mihomo remains after IPC failure; refusing a second core",
|
||||
"process verge-mihomo-alpha.exe (PID 123) is still running; refusing a second core",
|
||||
] {
|
||||
let error = super::explain_core_occupancy(anyhow::anyhow!(detail));
|
||||
assert_eq!(error.to_string(), clash_verge_i18n::t!("core.alreadyRunning"));
|
||||
assert_eq!(error.root_cause().to_string(), detail);
|
||||
}
|
||||
let error = super::explain_core_occupancy(anyhow::anyhow!("could not inspect remaining cores"));
|
||||
assert_eq!(error.to_string(), "could not inspect remaining cores");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sidecar_readiness_poll_is_bounded_and_accepts_a_real_api_response() -> anyhow::Result<()> {
|
||||
let attempts = Arc::new(AtomicUsize::new(0));
|
||||
@@ -730,6 +703,65 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forced_parent_exit_releases_the_sidecar_job() -> Result<()> {
|
||||
use std::io::{BufRead as _, BufReader, Write as _};
|
||||
use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _, OwnedHandle};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT},
|
||||
System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject},
|
||||
};
|
||||
|
||||
const HELPER: &str = "CVR_TEST_SIDECAR_JOB_PARENT";
|
||||
if std::env::var_os(HELPER).is_some() {
|
||||
let mut child = spawn_long_lived()?;
|
||||
let _job = create_and_assign_sidecar_job(child.id()).inspect_err(|_| {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
})?;
|
||||
println!("\nSIDECAR_PID={}", child.id());
|
||||
std::io::stdout().flush()?;
|
||||
std::io::stdin().read_line(&mut String::new())?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut parent = std::mem::DropGuard::new(
|
||||
Command::new(std::env::current_exe()?)
|
||||
.args(["forced_parent_exit_releases_the_sidecar_job", "--nocapture"])
|
||||
.env(HELPER, "1")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()?,
|
||||
|mut parent| {
|
||||
let _ = parent.kill();
|
||||
let _ = parent.wait();
|
||||
},
|
||||
);
|
||||
let stdout = parent
|
||||
.stdout
|
||||
.take()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing helper stdout"))?;
|
||||
let mut pid = None;
|
||||
for line in BufReader::new(stdout).lines() {
|
||||
if let Some(value) = line?.strip_prefix("SIDECAR_PID=") {
|
||||
pid = Some(value.parse()?);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let pid = pid.ok_or_else(|| anyhow::anyhow!("helper did not report its child"))?;
|
||||
let raw = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) };
|
||||
anyhow::ensure!(!raw.is_null(), "could not open helper child {pid}");
|
||||
let child = unsafe { OwnedHandle::from_raw_handle(raw) };
|
||||
assert_eq!(unsafe { WaitForSingleObject(child.as_raw_handle(), 0) }, WAIT_TIMEOUT);
|
||||
parent.kill()?;
|
||||
parent.wait()?;
|
||||
assert_eq!(
|
||||
unsafe { WaitForSingleObject(child.as_raw_handle(), 5000) },
|
||||
WAIT_OBJECT_0
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_err_for_invalid_pid() {
|
||||
// Windows PIDs are multiples of four; this one is effectively impossible.
|
||||
|
||||
@@ -19,9 +19,6 @@ pub enum NoticeStatus {
|
||||
ServiceCoreRepairRequired,
|
||||
#[serde(rename = "service_core::app_data_not_owned")]
|
||||
ServiceCoreAppDataNotOwned,
|
||||
#[serde(rename = "service_core::sidecar_fallback")]
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
ServiceCoreSidecarFallback,
|
||||
#[serde(rename = "dns_override::auto_disabled")]
|
||||
DnsOverrideAutoDisabled,
|
||||
#[serde(rename = "enhance::discarded_keys")]
|
||||
@@ -36,6 +33,8 @@ pub enum NoticeStatus {
|
||||
AppQuitCoreStopFailed,
|
||||
#[serde(rename = "update_with_clash_proxy")]
|
||||
UpdateWithClashProxy,
|
||||
#[serde(rename = "update_failed_even_with_clash")]
|
||||
UpdateFailedEvenWithClash,
|
||||
#[serde(rename = "reactivate_profiles::error")]
|
||||
ReactivateProfilesError,
|
||||
#[serde(rename = "update_failed")]
|
||||
@@ -86,7 +85,6 @@ impl NoticeStatus {
|
||||
Self::CoreStartError,
|
||||
Self::ServiceCoreRepairRequired,
|
||||
Self::ServiceCoreAppDataNotOwned,
|
||||
Self::ServiceCoreSidecarFallback,
|
||||
Self::DnsOverrideAutoDisabled,
|
||||
Self::EnhanceDiscardedKeys,
|
||||
Self::TunModeAutoDisabled,
|
||||
@@ -94,6 +92,7 @@ impl NoticeStatus {
|
||||
Self::AppRestartCoreStopFailed,
|
||||
Self::AppQuitCoreStopFailed,
|
||||
Self::UpdateWithClashProxy,
|
||||
Self::UpdateFailedEvenWithClash,
|
||||
Self::ReactivateProfilesError,
|
||||
Self::UpdateFailed,
|
||||
Self::ConfigValidateBootError,
|
||||
@@ -129,7 +128,6 @@ mod tests {
|
||||
"core_start::error",
|
||||
"service_core::repair_required",
|
||||
"service_core::app_data_not_owned",
|
||||
"service_core::sidecar_fallback",
|
||||
"dns_override::auto_disabled",
|
||||
"enhance::discarded_keys",
|
||||
"tun_mode::auto_disabled",
|
||||
@@ -137,6 +135,7 @@ mod tests {
|
||||
"app_restart::core_stop_failed",
|
||||
"app_quit::core_stop_failed",
|
||||
"update_with_clash_proxy",
|
||||
"update_failed_even_with_clash",
|
||||
"reactivate_profiles::error",
|
||||
"update_failed",
|
||||
"config_validate::boot_error",
|
||||
|
||||
@@ -390,10 +390,10 @@ fn service_proxy_config(verge: &IVerge, mixed_port: u16, pac_port: u16) -> Resul
|
||||
/// the write's, so it stays a failure.
|
||||
fn service_apply_result(requested: &MacosProxyConfig, outcome: ProxyApplyOutcome) -> Result<()> {
|
||||
match outcome {
|
||||
ProxyApplyOutcome::Applied | ProxyApplyOutcome::NotRequested => Ok(()),
|
||||
ProxyApplyOutcome::Applied => Ok(()),
|
||||
// Direct fallback satisfies a disable request.
|
||||
ProxyApplyOutcome::DirectFallback { .. } if matches!(requested, MacosProxyConfig::Disabled) => Ok(()),
|
||||
// Older helpers encode a failed service lookup as fallback even when no OS write occurred.
|
||||
// The service reports a missing network service as fallback before any OS write.
|
||||
#[cfg(target_os = "macos")]
|
||||
ProxyApplyOutcome::DirectFallback { message }
|
||||
if message == sysproxy::Error::NoActiveNetworkService.to_string() =>
|
||||
|
||||
@@ -67,17 +67,9 @@ impl RunStateEnv for RealEnv {
|
||||
}
|
||||
|
||||
async fn trusted_install_evidence(&self) -> Result<bool> {
|
||||
let registered = tokio::task::spawn_blocking(crate::core::service::trusted_service_evidence)
|
||||
tokio::task::spawn_blocking(crate::core::service::trusted_service_evidence)
|
||||
.await
|
||||
.context("service registration probe did not finish")??;
|
||||
// A helper that outlived its registration is a broken Service, not an absent one.
|
||||
#[cfg(unix)]
|
||||
if !registered && let Err(error) = clash_verge_service_ipc::execution::check_sidecar_available().await {
|
||||
return Ok(error
|
||||
.downcast_ref::<clash_verge_service_ipc::execution::ResidualServiceError>()
|
||||
.is_some());
|
||||
}
|
||||
Ok(registered)
|
||||
.context("service registration probe did not finish")?
|
||||
}
|
||||
|
||||
fn is_elevated(&self) -> bool {
|
||||
|
||||
@@ -24,7 +24,7 @@ pub use env::FakeEnv;
|
||||
pub use env::{RealEnv, RunStateEnv};
|
||||
pub use health::{PendingAction, RunState, RunStateView, ServiceHealth};
|
||||
pub use owner::{OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch};
|
||||
pub use probe::{CORE_REJECTED_PREFIX, ServiceVersionCheck, ServiceVersionReply, classify_service_version_reply};
|
||||
pub use probe::{ServiceVersionCheck, ServiceVersionReply, classify_service_version_reply};
|
||||
|
||||
use crate::core::manager::RunningMode;
|
||||
use health::StoredService;
|
||||
@@ -336,21 +336,6 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn allow_sidecar_after_service_refusal(&self, reason: String) -> Result<()> {
|
||||
let mut state = self.service.lock();
|
||||
if state.operation_running || state.service.pending.is_some() {
|
||||
bail!("cannot fall back while a service operation is pending");
|
||||
}
|
||||
// Publish the refusal and allowance together so it never asks the UI for a repair.
|
||||
state.service.health = ServiceHealth::Unavailable(reason);
|
||||
state.service.allow_sidecar();
|
||||
state.bump();
|
||||
drop(state);
|
||||
self.announce();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Requests installation only for a confirmed absent Service.
|
||||
pub fn require_install_for_session(&self) -> Result<()> {
|
||||
let mut state = self.service.lock();
|
||||
|
||||
+188
-164
@@ -10,8 +10,8 @@ use crate::{
|
||||
owner_identity::current_owner_credentials,
|
||||
proxy_control,
|
||||
runstate::{
|
||||
CORE_REJECTED_PREFIX, OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch, PendingAction, RUN_STATE,
|
||||
ReadyWaitError, RunState, RunStateEnv, RunStateStore, ServiceHealth,
|
||||
OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch, PendingAction, RUN_STATE, ReadyWaitError,
|
||||
RunState, RunStateEnv, RunStateStore, ServiceHealth,
|
||||
},
|
||||
tray::Tray,
|
||||
},
|
||||
@@ -22,9 +22,9 @@ use clash_verge_draft::Draft;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of};
|
||||
use clash_verge_service_ipc::{
|
||||
MacosProxyConfig, OwnerCredentials, OwnerIdentity, OwnerSessionProof, ProtocolInfo, ProxyApplyOutcome,
|
||||
RemoteProvider, RuntimeAsset, RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode,
|
||||
ServiceStatusSnapshot, StageRuntimeOutcome, StartClashRequest, WriterConfig,
|
||||
MacosProxyConfig, OwnerCredentials, OwnerIdentity, OwnerSessionProof, ProxyApplyOutcome, RemoteProvider,
|
||||
RuntimeAsset, RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
|
||||
StageRuntimeOutcome, StartClashRequest, WriterConfig,
|
||||
};
|
||||
use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask};
|
||||
use clash_verge_task::watch_task;
|
||||
@@ -44,45 +44,21 @@ use std::{
|
||||
use tokio::{sync::watch, time::Instant};
|
||||
|
||||
static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
static ACTIVE_SERVICE_SESSION: Mutex<Option<ActiveServiceSession>> = Mutex::new(None);
|
||||
static PENDING_SERVICE_FALLBACK_NOTICE: Mutex<Option<String>> = Mutex::new(None);
|
||||
static PENDING_SERVICE_START: Mutex<Option<PendingServiceStart>> = Mutex::new(None);
|
||||
static ACTIVE_SERVICE_SESSION: Mutex<Option<Arc<OwnerSessionProof>>> = Mutex::new(None);
|
||||
static PENDING_SERVICE_REPAIR_NOTICE: AtomicBool = AtomicBool::new(false);
|
||||
static PENDING_SERVICE_OWNER_NOTICE: Mutex<Option<String>> = Mutex::new(None);
|
||||
|
||||
/// Why the Service was unavailable when the core fell back to Sidecar.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, specta::Type)]
|
||||
#[serde(tag = "kind", content = "reason", rename_all = "camelCase")]
|
||||
pub enum ServiceFallbackNotice {
|
||||
Unavailable,
|
||||
CoreRejected(String),
|
||||
NotAutoStarted,
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
/// The release installer registers AutoStart.
|
||||
const SERVICE_NOT_AUTO_STARTED: &str = "the Windows service is stopped and no longer starts with Windows";
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn is_not_auto_started(reason: &str) -> bool {
|
||||
// Detection prefixes its own context to the reason.
|
||||
reason.contains(SERVICE_NOT_AUTO_STARTED)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub(crate) fn notify_service_fallback(reason: &str) {
|
||||
*PENDING_SERVICE_FALLBACK_NOTICE.lock() = Some(reason.to_owned());
|
||||
Handle::notice(NoticeStatus::ServiceCoreSidecarFallback, "");
|
||||
}
|
||||
|
||||
pub(crate) fn take_service_fallback_notice() -> Option<ServiceFallbackNotice> {
|
||||
let reason = PENDING_SERVICE_FALLBACK_NOTICE.lock().take()?;
|
||||
Some(if reason.starts_with(CORE_REJECTED_PREFIX) {
|
||||
ServiceFallbackNotice::CoreRejected(reason)
|
||||
} else if is_not_auto_started(&reason) {
|
||||
ServiceFallbackNotice::NotAutoStarted
|
||||
} else {
|
||||
ServiceFallbackNotice::Unavailable
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn take_service_repair_notice() -> bool {
|
||||
PENDING_SERVICE_REPAIR_NOTICE.swap(false, Ordering::Relaxed)
|
||||
}
|
||||
@@ -100,14 +76,27 @@ fn app_data_owner_command(credentials: &OwnerCredentials) -> Option<String> {
|
||||
Some(format!("sudo chown -R {uid}:{gid} '{path}'"))
|
||||
}
|
||||
|
||||
/// Capabilities of the service session that owns the running Core.
|
||||
/// They are discarded with that session rather than cached across service upgrades.
|
||||
#[derive(Clone)]
|
||||
struct ActiveServiceSession {
|
||||
proof: Arc<OwnerSessionProof>,
|
||||
supports_runtime_staging: bool,
|
||||
supports_runtime_file_read: bool,
|
||||
supports_runtime_geo_read: bool,
|
||||
struct PendingServiceStart {
|
||||
token: String,
|
||||
service_replaced: bool,
|
||||
}
|
||||
|
||||
impl PendingServiceStart {
|
||||
const fn new(token: String) -> Self {
|
||||
Self {
|
||||
token,
|
||||
service_replaced: false,
|
||||
}
|
||||
}
|
||||
|
||||
const fn released_after_repair(&self, status: &ServiceStatusSnapshot) -> bool {
|
||||
self.service_replaced
|
||||
&& !status.is_active
|
||||
&& status.active_generation.is_none()
|
||||
&& status.core_pid.is_none()
|
||||
&& !status.desired_core_should_be_running
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_service_session_token() -> Result<String> {
|
||||
@@ -125,89 +114,14 @@ fn generate_service_session_token() -> Result<String> {
|
||||
pub(crate) fn active_service_session() -> Result<Arc<OwnerSessionProof>> {
|
||||
ACTIVE_SERVICE_SESSION
|
||||
.lock()
|
||||
.as_ref()
|
||||
.map(|session| Arc::clone(&session.proof))
|
||||
.clone()
|
||||
.context("service owner session is not active")
|
||||
}
|
||||
|
||||
/// Returns false unless the active service session explicitly supports in-place staging.
|
||||
pub(crate) fn active_service_supports_runtime_staging() -> bool {
|
||||
ACTIVE_SERVICE_SESSION
|
||||
.lock()
|
||||
.as_ref()
|
||||
.is_some_and(|session| session.supports_runtime_staging)
|
||||
}
|
||||
|
||||
pub(crate) fn active_service_supports_runtime_file_read() -> bool {
|
||||
ACTIVE_SERVICE_SESSION
|
||||
.lock()
|
||||
.as_ref()
|
||||
.is_some_and(|session| session.supports_runtime_file_read)
|
||||
}
|
||||
|
||||
fn active_service_supports_runtime_geo_read() -> bool {
|
||||
ACTIVE_SERVICE_SESSION
|
||||
.lock()
|
||||
.as_ref()
|
||||
.is_some_and(|session| session.supports_runtime_geo_read)
|
||||
}
|
||||
|
||||
pub(crate) fn clear_active_service_session() {
|
||||
ACTIVE_SERVICE_SESSION.lock().take();
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct ServiceCapabilities {
|
||||
runtime_staging: bool,
|
||||
runtime_file_read: bool,
|
||||
runtime_geo_read: bool,
|
||||
}
|
||||
|
||||
impl ServiceCapabilities {
|
||||
const fn of(info: &ProtocolInfo) -> Self {
|
||||
Self {
|
||||
runtime_staging: info.supports_runtime_staging(),
|
||||
runtime_file_read: info.supports_runtime_file_read(),
|
||||
runtime_geo_read: info.supports_runtime_geo_read(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Failed capability probes must not block startup.
|
||||
#[tracing::instrument(skip_all, level = "info", fields(supported = tracing::field::Empty))]
|
||||
async fn probe_service_capabilities() -> ServiceCapabilities {
|
||||
match clash_verge_service_ipc::get_version().await {
|
||||
Ok(response) if response.code == 0 => {
|
||||
let capabilities = response
|
||||
.data
|
||||
.as_ref()
|
||||
.map_or_else(ServiceCapabilities::default, ServiceCapabilities::of);
|
||||
tracing::Span::current().record("supported", capabilities.runtime_staging);
|
||||
capabilities
|
||||
}
|
||||
Ok(response) => {
|
||||
tracing::Span::current().record("supported", false);
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"服务协议查询返回 {}: {};配置变更将走重启路径",
|
||||
response.code,
|
||||
response.message
|
||||
);
|
||||
ServiceCapabilities::default()
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::Span::current().record("supported", false);
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"无法查询服务协议版本: {error:#};配置变更将走重启路径"
|
||||
);
|
||||
ServiceCapabilities::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn session_matches_status(proof: &OwnerSessionProof, is_active: bool, active_generation: Option<u64>) -> bool {
|
||||
is_active && active_generation == Some(proof.generation)
|
||||
}
|
||||
@@ -600,7 +514,26 @@ pub(crate) fn run_privileged_service_action(action: PendingAction) -> Result<()>
|
||||
PendingAction::Reinstall => (reinstall_service, "reinstall service"),
|
||||
PendingAction::ForceReinstall => (force_reinstall_service, "force reinstall service"),
|
||||
};
|
||||
tokio::task::block_in_place(operation).with_context(|| format!("{label} failed"))
|
||||
tokio::task::block_in_place(|| {
|
||||
let pending_token = match action {
|
||||
PendingAction::Reinstall | PendingAction::ForceReinstall => PENDING_SERVICE_START
|
||||
.lock()
|
||||
.as_ref()
|
||||
.map(|pending| pending.token.clone()),
|
||||
PendingAction::Install | PendingAction::Uninstall => None,
|
||||
};
|
||||
operation().with_context(|| format!("{label} failed"))?;
|
||||
// Full repair acquires the stopped-service guard before replacing the daemon.
|
||||
if let Some(token) = pending_token
|
||||
&& let Some(pending) = PENDING_SERVICE_START
|
||||
.lock()
|
||||
.as_mut()
|
||||
.filter(|pending| pending.token == token)
|
||||
{
|
||||
pending.service_replaced = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds the same runtime bundle description for both service start and staging.
|
||||
@@ -648,12 +581,11 @@ impl StageRequest {
|
||||
}
|
||||
|
||||
/// Requests in-place staging. `Err` means no answer; refusals are returned for caller policy.
|
||||
pub(super) async fn stage_runtime_by_service(config_file: &Path) -> Result<StageRequest> {
|
||||
let session = active_service_session()?;
|
||||
pub(super) async fn stage_runtime_by_service(config_file: &Path, session: &OwnerSessionProof) -> Result<StageRequest> {
|
||||
let credentials = current_owner_credentials()?;
|
||||
let runtime = collect_service_runtime_bundle(config_file).await?;
|
||||
|
||||
let response = clash_verge_service_ipc::stage_runtime(&credentials, &session, &runtime)
|
||||
let response = clash_verge_service_ipc::stage_runtime(&credentials, session, &runtime)
|
||||
.await
|
||||
.context("无法连接到Clash Verge Service")?;
|
||||
if response.code > 0 {
|
||||
@@ -700,27 +632,86 @@ fn record_service_start_refusal<E: RunStateEnv>(
|
||||
refusal.into()
|
||||
}
|
||||
|
||||
/// Sidecar stays blocked until a reinstall replaces the residual helper, so ask for repair.
|
||||
pub(super) fn record_residual_service(error: &anyhow::Error) {
|
||||
if let Some(residual) = error.downcast_ref::<clash_verge_service_ipc::execution::ResidualServiceError>() {
|
||||
RUN_STATE.observe(ServiceHealth::Unavailable(residual.to_string()));
|
||||
pub(super) fn require_service_core_released() -> Result<()> {
|
||||
anyhow::ensure!(
|
||||
PENDING_SERVICE_START.lock().is_none() && ACTIVE_SERVICE_SESSION.lock().is_none(),
|
||||
"the previous Service core has not confirmed exit"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn release_service_core_for_sidecar() -> Result<()> {
|
||||
let pending = PENDING_SERVICE_START.lock().clone();
|
||||
if pending.is_none() {
|
||||
if active_service_session().is_ok() {
|
||||
return stop_core_by_service().await;
|
||||
}
|
||||
if matches!(RUN_STATE.state().health, ServiceHealth::NotInstalled) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let credentials = current_owner_credentials()?;
|
||||
let status = tokio::time::timeout(
|
||||
Duration::from_secs(2),
|
||||
clash_verge_service_ipc::get_status(&credentials),
|
||||
)
|
||||
.await
|
||||
.context("timed out confirming the previous Service core exited")??;
|
||||
anyhow::ensure!(status.code == 0, "Service status failed: {}", status.message);
|
||||
let status = status.data.context("Service omitted owner status")?;
|
||||
let Some(pending) = pending else {
|
||||
anyhow::ensure!(
|
||||
!status.is_active || (status.core_pid.is_none() && !status.desired_core_should_be_running),
|
||||
"the Service is running or recovering this owner's core; stop it before switching"
|
||||
);
|
||||
return Ok(());
|
||||
};
|
||||
if pending.released_after_repair(&status) {
|
||||
PENDING_SERVICE_START.lock().take();
|
||||
clear_active_service_session();
|
||||
return Ok(());
|
||||
}
|
||||
// A lost Start reply may have committed. Only its proposed token can stop that generation.
|
||||
let generation = status
|
||||
.active_generation
|
||||
.context("the previous Service start has not confirmed exit; repair the Service before switching")?;
|
||||
let stopped = clash_verge_service_ipc::stop_clash(
|
||||
&credentials,
|
||||
&OwnerSessionProof {
|
||||
generation,
|
||||
token: pending.token,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
anyhow::ensure!(
|
||||
stopped.code == 0,
|
||||
"could not confirm Service core exit: {}",
|
||||
stopped.message
|
||||
);
|
||||
PENDING_SERVICE_START.lock().take();
|
||||
clear_active_service_session();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 尝试使用服务启动core
|
||||
#[tracing::instrument(skip_all, level = "info", fields(generation = tracing::field::Empty, staging = tracing::field::Empty, code = tracing::field::Empty, outcome = tracing::field::Empty))]
|
||||
pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()> {
|
||||
clear_active_service_session();
|
||||
|
||||
#[tracing::instrument(skip_all, level = "info", fields(generation = tracing::field::Empty, code = tracing::field::Empty, outcome = tracing::field::Empty))]
|
||||
async fn start_with_existing_service(
|
||||
config_file: &Path,
|
||||
start: &tokio::sync::OnceCell<StartClashRequest>,
|
||||
) -> Result<()> {
|
||||
let credentials = current_owner_credentials()?;
|
||||
let runtime = collect_service_runtime_bundle(config_file).await?;
|
||||
let request = StartClashRequest {
|
||||
runtime,
|
||||
proposed_session_token: generate_service_session_token()?,
|
||||
macos_proxy: None,
|
||||
};
|
||||
|
||||
let response = match clash_verge_service_ipc::start_clash(&credentials, &request).await {
|
||||
let request = start
|
||||
.get_or_try_init(|| async {
|
||||
Ok::<_, anyhow::Error>(StartClashRequest {
|
||||
runtime: collect_service_runtime_bundle(config_file).await?,
|
||||
proposed_session_token: generate_service_session_token()?,
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
let previous = PENDING_SERVICE_START
|
||||
.lock()
|
||||
.replace(PendingServiceStart::new(request.proposed_session_token.clone()));
|
||||
let response = match clash_verge_service_ipc::start_clash(&credentials, request).await {
|
||||
Ok(response) => response,
|
||||
Err(error) => {
|
||||
tracing::Span::current().record("outcome", "ipc-unreachable");
|
||||
@@ -732,6 +723,16 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()
|
||||
if response.code > 0 {
|
||||
tracing::Span::current().record("code", response.code);
|
||||
tracing::Span::current().record("outcome", "refused");
|
||||
if matches!(response.code,
|
||||
code if code == ServiceErrorCode::InvalidInstallLocation as u16
|
||||
|| code == ServiceErrorCode::InvalidRuntimeAsset as u16
|
||||
|| code == ServiceErrorCode::AppDataRootNotOwned as u16
|
||||
|| code == ServiceErrorCode::UnauthorizedOwner as u16
|
||||
|| code == ServiceErrorCode::ProtocolMismatch as u16
|
||||
|| code == ServiceErrorCode::ProxyClearFailed as u16
|
||||
) {
|
||||
*PENDING_SERVICE_START.lock() = previous;
|
||||
}
|
||||
let err_msg = response.message;
|
||||
logging!(
|
||||
error,
|
||||
@@ -754,43 +755,39 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()
|
||||
&RUN_STATE,
|
||||
ServiceStartRefusal {
|
||||
code: response.code,
|
||||
core_path: request.runtime.core_path,
|
||||
core_path: request.runtime.core_path.clone(),
|
||||
message: err_msg,
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
let result = response.data.context("Clash Verge Service 未返回会话信息")?;
|
||||
tracing::Span::current().record("generation", result.session.generation);
|
||||
let capabilities = probe_service_capabilities().await;
|
||||
tracing::Span::current().record("staging", capabilities.runtime_staging);
|
||||
*ACTIVE_SERVICE_SESSION.lock() = Some(ActiveServiceSession {
|
||||
proof: Arc::new(OwnerSessionProof {
|
||||
generation: result.session.generation,
|
||||
token: request.proposed_session_token,
|
||||
}),
|
||||
supports_runtime_staging: capabilities.runtime_staging,
|
||||
supports_runtime_file_read: capabilities.runtime_file_read,
|
||||
supports_runtime_geo_read: capabilities.runtime_geo_read,
|
||||
});
|
||||
tracing::Span::current().record("generation", result.generation);
|
||||
*ACTIVE_SERVICE_SESSION.lock() = Some(Arc::new(OwnerSessionProof {
|
||||
generation: result.generation,
|
||||
token: request.proposed_session_token.clone(),
|
||||
}));
|
||||
|
||||
PENDING_SERVICE_START.lock().take();
|
||||
// PAC follows the Running Mode; the caller opens it via `core_started(Service)`.
|
||||
start_owner_monitor();
|
||||
tracing::Span::current().record("outcome", "started");
|
||||
PENDING_SERVICE_FALLBACK_NOTICE.lock().take();
|
||||
PENDING_SERVICE_REPAIR_NOTICE.store(false, Ordering::Relaxed);
|
||||
PENDING_SERVICE_OWNER_NOTICE.lock().take();
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
"服务成功启动核心 (session generation {})",
|
||||
result.session.generation
|
||||
result.generation
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 以服务启动core
|
||||
pub(super) async fn run_core_by_service(config_file: &Path) -> Result<()> {
|
||||
pub(super) async fn run_core_by_service(
|
||||
config_file: &Path,
|
||||
start: &tokio::sync::OnceCell<StartClashRequest>,
|
||||
) -> Result<()> {
|
||||
SERVICE_MANAGER.refresh().await?;
|
||||
|
||||
let status = SERVICE_MANAGER.current().await;
|
||||
@@ -799,7 +796,7 @@ pub(super) async fn run_core_by_service(config_file: &Path) -> Result<()> {
|
||||
}
|
||||
|
||||
logging!(info, Type::Service, "服务已运行且版本匹配,直接使用");
|
||||
start_with_existing_service(config_file).await
|
||||
start_with_existing_service(config_file, start).await
|
||||
}
|
||||
|
||||
async fn capture_generation_before<F, Fut, T>(generation: &AtomicU64, operation: F) -> (u64, T)
|
||||
@@ -956,11 +953,10 @@ type ProviderLoadTimes = HashMap<(&'static str, String), Option<u64>>;
|
||||
|
||||
#[tracing::instrument(level = "info", fields(synced = tracing::field::Empty, pending = tracing::field::Empty))]
|
||||
async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
||||
if !active_service_supports_runtime_file_read() {
|
||||
let Ok(session) = active_service_session() else {
|
||||
return Ok(ProviderSync::default());
|
||||
}
|
||||
};
|
||||
let credentials = current_owner_credentials()?;
|
||||
let session = active_service_session()?;
|
||||
let app_dir = dirs::app_home_dir()?;
|
||||
let runtime = Config::runtime().await;
|
||||
let mut outcome = ProviderSync::default();
|
||||
@@ -1046,14 +1042,10 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
||||
|
||||
/// Pulls geo databases the service core rewrote, because validation reads the app dir.
|
||||
pub(crate) async fn sync_runtime_geo_by_service() {
|
||||
if !active_service_supports_runtime_geo_read() {
|
||||
let Ok(session) = active_service_session() else {
|
||||
return;
|
||||
}
|
||||
let (Ok(credentials), Ok(session), Ok(app_dir)) = (
|
||||
current_owner_credentials(),
|
||||
active_service_session(),
|
||||
dirs::app_home_dir(),
|
||||
) else {
|
||||
};
|
||||
let (Ok(credentials), Ok(app_dir)) = (current_owner_credentials(), dirs::app_home_dir()) else {
|
||||
return;
|
||||
};
|
||||
for asset in GEO_ASSETS {
|
||||
@@ -1641,7 +1633,7 @@ fn session_matches_active_status(is_active: bool, active_generation: Option<u64>
|
||||
ACTIVE_SERVICE_SESSION
|
||||
.lock()
|
||||
.as_ref()
|
||||
.is_some_and(|session| session_matches_status(&session.proof, is_active, active_generation))
|
||||
.is_some_and(|session| session_matches_status(session, is_active, active_generation))
|
||||
}
|
||||
|
||||
fn cancel_owner_monitors() {
|
||||
@@ -1709,6 +1701,11 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) {
|
||||
if policy.reset_system_proxy {
|
||||
clear_proxy_after_owner_loss().await;
|
||||
}
|
||||
if matches!(reason, OwnerRecoveryReason::TransportFailure)
|
||||
&& let Ok(session) = active_service_session()
|
||||
{
|
||||
*PENDING_SERVICE_START.lock() = Some(PendingServiceStart::new(session.token.clone()));
|
||||
}
|
||||
clear_active_service_session();
|
||||
CoreManager::global().core_stopped();
|
||||
// A displaced Service may still run TUN for its new owner, and DNS settings are system-wide.
|
||||
@@ -1995,6 +1992,33 @@ mod tests {
|
||||
ServiceStatus::from_run_state(&store.settled().await)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_idle_snapshot_releases_an_ambiguous_start_only_after_repair() {
|
||||
let mut pending = super::PendingServiceStart::new("lost-reply".into());
|
||||
let mut status = clash_verge_service_ipc::ServiceStatusSnapshot {
|
||||
is_active: false,
|
||||
active_generation: None,
|
||||
core_pid: None,
|
||||
desired_core_should_be_running: false,
|
||||
service_state: clash_verge_service_ipc::ServiceLifecycleState::Running,
|
||||
core_started_at: None,
|
||||
last_core_exit_reason: None,
|
||||
restart_count: 0,
|
||||
last_recovery_at: None,
|
||||
desired_generation: 0,
|
||||
desired_updated_at: 0,
|
||||
desired_persistence_error: None,
|
||||
};
|
||||
assert!(!pending.released_after_repair(&status));
|
||||
pending.service_replaced = true;
|
||||
assert!(pending.released_after_repair(&status));
|
||||
status.active_generation = Some(1);
|
||||
assert!(!pending.released_after_repair(&status));
|
||||
status.active_generation = None;
|
||||
status.desired_core_should_be_running = true;
|
||||
assert!(!pending.released_after_repair(&status));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mismatched_active_generation_displaces_local_session() {
|
||||
let proof = OwnerSessionProof {
|
||||
|
||||
@@ -132,7 +132,7 @@ async fn get_config_values(profile_uid: &str) -> ConfigValues {
|
||||
|
||||
#[allow(clippy::cognitive_complexity)]
|
||||
async fn collect_profile_items(profiles: &IProfiles) -> Result<RenderProfile> {
|
||||
let current_profile_uid = match profiles.current.as_deref() {
|
||||
let current_profile_uid = match profiles.current.clone() {
|
||||
Some(uid) => uid,
|
||||
None => return Ok(default_profile()),
|
||||
};
|
||||
@@ -141,18 +141,27 @@ async fn collect_profile_items(profiles: &IProfiles) -> Result<RenderProfile> {
|
||||
.await
|
||||
.with_context(|| format!("failed to read current profile \"{current_profile_uid}\""))?;
|
||||
|
||||
let current_item = match profiles.get_item(current_profile_uid) {
|
||||
let current_item = match profiles.get_item(¤t_profile_uid) {
|
||||
Ok(item) => item,
|
||||
Err(err) => {
|
||||
return Err(err).with_context(|| format!("failed to get current profile \"{current_profile_uid}\""));
|
||||
}
|
||||
};
|
||||
|
||||
let merge_uid = current_item.current_merge().map_or("Merge", String::as_str);
|
||||
let script_uid = current_item.current_script().map_or("Script", String::as_str);
|
||||
let rules_uid = current_item.current_rules().map_or("Rules", String::as_str);
|
||||
let proxies_uid = current_item.current_proxies().map_or("Proxies", String::as_str);
|
||||
let groups_uid = current_item.current_groups().map_or("Groups", String::as_str);
|
||||
let merge_uid = current_item.current_merge().cloned().unwrap_or_else(|| "Merge".into());
|
||||
let script_uid = current_item
|
||||
.current_script()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "Script".into());
|
||||
let rules_uid = current_item.current_rules().cloned().unwrap_or_else(|| "Rules".into());
|
||||
let proxies_uid = current_item
|
||||
.current_proxies()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "Proxies".into());
|
||||
let groups_uid = current_item
|
||||
.current_groups()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "Groups".into());
|
||||
|
||||
let name = current_item.name.clone().unwrap_or_default();
|
||||
|
||||
@@ -168,11 +177,11 @@ async fn collect_profile_items(profiles: &IProfiles) -> Result<RenderProfile> {
|
||||
} = default_profile();
|
||||
|
||||
let (merge_item, script_item, rules_item, proxies_item, groups_item, global_merge, global_script) = tokio::join!(
|
||||
chain_item_or_default(profiles.get_item(merge_uid).ok(), || default_merge,),
|
||||
chain_item_or_default(profiles.get_item(script_uid).ok(), || default_script,),
|
||||
chain_item_or_default(profiles.get_item(rules_uid).ok(), || default_rules,),
|
||||
chain_item_or_default(profiles.get_item(proxies_uid).ok(), || default_proxies,),
|
||||
chain_item_or_default(profiles.get_item(groups_uid).ok(), || default_groups,),
|
||||
chain_item_or_default(profiles.get_item(&merge_uid).ok(), || default_merge,),
|
||||
chain_item_or_default(profiles.get_item(&script_uid).ok(), || default_script,),
|
||||
chain_item_or_default(profiles.get_item(&rules_uid).ok(), || default_rules,),
|
||||
chain_item_or_default(profiles.get_item(&proxies_uid).ok(), || default_proxies,),
|
||||
chain_item_or_default(profiles.get_item(&groups_uid).ok(), || default_groups,),
|
||||
chain_item_or_default(profiles.get_item("Merge").ok(), || default_global_merge,),
|
||||
chain_item_or_default(profiles.get_item("Script").ok(), || default_global_script,),
|
||||
);
|
||||
@@ -235,14 +244,10 @@ async fn read_dns_settings(enabled: bool) -> Option<Mapping> {
|
||||
serde_yaml_ng::from_str(&yaml).ok()
|
||||
}
|
||||
|
||||
pub(crate) struct ProfileRenderInputs {
|
||||
profile: RenderProfile,
|
||||
settings: RenderSettings,
|
||||
dns_config: Option<Mapping>,
|
||||
dns_override: DnsOverrideState,
|
||||
}
|
||||
|
||||
pub(crate) async fn collect_render_inputs(profiles: &IProfiles) -> Result<ProfileRenderInputs> {
|
||||
/// Returns the enhanced profile, its original keys, script logs, and DNS override decision.
|
||||
pub async fn render_runtime_config(
|
||||
profiles: &IProfiles,
|
||||
) -> Result<(Mapping, HashSet<String>, HashMap<String, ResultLog>, DnsOverrideState)> {
|
||||
let profile_uid = profiles.current.as_deref().unwrap_or_default();
|
||||
let settings = get_config_values(profile_uid).await;
|
||||
let profile = collect_profile_items(profiles).await?;
|
||||
@@ -253,30 +258,19 @@ pub(crate) async fn collect_render_inputs(profiles: &IProfiles) -> Result<Profil
|
||||
settings.dns_override_confirmation,
|
||||
);
|
||||
let dns_config = read_dns_settings(dns_override.enabled).await;
|
||||
Ok(ProfileRenderInputs {
|
||||
profile,
|
||||
settings: settings.render,
|
||||
dns_config,
|
||||
dns_override,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the enhanced profile, its original keys, script logs, and DNS override decision.
|
||||
pub(crate) async fn render_runtime_config(
|
||||
inputs: ProfileRenderInputs,
|
||||
) -> (Mapping, HashSet<String>, HashMap<String, ResultLog>, DnsOverrideState) {
|
||||
let RenderedConfig {
|
||||
config,
|
||||
exists_keys,
|
||||
logs,
|
||||
discarded_keys,
|
||||
} = render(
|
||||
inputs.profile,
|
||||
inputs.settings,
|
||||
inputs.dns_config,
|
||||
profile,
|
||||
settings.render,
|
||||
dns_config,
|
||||
clash_verge_profile_script::execute,
|
||||
)
|
||||
.await;
|
||||
notify_discarded_keys(discarded_keys);
|
||||
(config, exists_keys, logs, inputs.dns_override)
|
||||
|
||||
Ok((config, exists_keys, logs, dns_override))
|
||||
}
|
||||
|
||||
+75
-285
@@ -1,29 +1,18 @@
|
||||
use crate::{
|
||||
config::{
|
||||
Config, IClashTemp, IProfiles, IVerge, profile_storage,
|
||||
profiles::{load_profiles_unlocked, validate_profile_file},
|
||||
},
|
||||
config::{Config, IClashTemp, IVerge, profiles::load_profiles},
|
||||
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,
|
||||
},
|
||||
dirs::{PathBufExec as _, app_home_dir, local_backup_dir, verge_path},
|
||||
help,
|
||||
},
|
||||
};
|
||||
use anyhow::{Context as _, Result, anyhow};
|
||||
use anyhow::{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 std::path::PathBuf;
|
||||
use tokio::fs;
|
||||
use tristr::alias::String;
|
||||
|
||||
@@ -35,39 +24,21 @@ pub struct LocalBackupFile {
|
||||
pub content_length: u64,
|
||||
}
|
||||
|
||||
async fn apply_backup(archive: BackupArchive<File>) -> Result<()> {
|
||||
let _profile_write = crate::config::profiles::PROFILE_WRITE_LOCK.lock().await;
|
||||
/// Reloads restored configs into memory while preserving WebDAV credentials.
|
||||
async fn finalize_restored_verge_config(
|
||||
webdav_url: Option<String>,
|
||||
webdav_username: Option<String>,
|
||||
webdav_password: Option<String>,
|
||||
) -> Result<()> {
|
||||
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);
|
||||
}
|
||||
})?
|
||||
};
|
||||
|
||||
// A broken restored `verge.yaml` is a restore failure, not a reason to load defaults.
|
||||
let mut restored = help::read_yaml::<IVerge>(&verge_path()?).await?;
|
||||
restored.webdav_url = webdav_url;
|
||||
restored.webdav_username = webdav_username;
|
||||
restored.webdav_password = webdav_password;
|
||||
restored.save_file().await?;
|
||||
|
||||
let restored_clash = IClashTemp::new().await;
|
||||
let clash_draft = Config::clash().await;
|
||||
clash_draft.edit_draft(|d| {
|
||||
@@ -75,16 +46,19 @@ async fn apply_backup(archive: BackupArchive<File>) -> Result<()> {
|
||||
});
|
||||
clash_draft.apply();
|
||||
|
||||
let restored_profiles = load_profiles().await;
|
||||
let profiles_draft = Config::profiles().await;
|
||||
profiles_draft.edit_draft(|d| {
|
||||
*d = restored_profiles;
|
||||
});
|
||||
profiles_draft.apply();
|
||||
|
||||
let verge_draft = Config::verge().await;
|
||||
verge_draft.edit_draft(|d| {
|
||||
*d = restored;
|
||||
*d = restored.clone();
|
||||
});
|
||||
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);
|
||||
auto_backup::publish_settings(&verge_draft.data_arc());
|
||||
|
||||
// Turn it off here; a failing core side effect below would otherwise skip this step.
|
||||
if !restored.enable_system_proxy.unwrap_or_default() {
|
||||
@@ -102,16 +76,16 @@ async fn apply_backup(archive: BackupArchive<File>) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
let applied = super::config::apply_verge_patch_locked(&config_write, &restored, true).await;
|
||||
// `patch_verge` re-acquires the configuration write lock.
|
||||
drop(config_write);
|
||||
if let Err(err) = applied {
|
||||
|
||||
// Run configuration side effects without rewriting the already-restored file.
|
||||
if let Err(err) = super::patch_verge(&restored, true).await {
|
||||
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(())
|
||||
}
|
||||
@@ -158,127 +132,53 @@ pub async fn delete_webdav_backup(filename: String) -> Result<()> {
|
||||
})
|
||||
}
|
||||
|
||||
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?
|
||||
async fn restore_backup_archive(path: PathBuf) -> Result<()> {
|
||||
let (webdav_url, webdav_username, webdav_password) = {
|
||||
let verge = Config::verge().await;
|
||||
let verge = verge.latest_arc();
|
||||
(
|
||||
verge.webdav_url.clone(),
|
||||
verge.webdav_username.clone(),
|
||||
verge.webdav_password.clone(),
|
||||
)
|
||||
};
|
||||
|
||||
let home_dir = app_home_dir()?;
|
||||
AsyncHandler::spawn_blocking(move || -> Result<()> {
|
||||
let file = std::fs::File::open(&path)?;
|
||||
let mut zip = zip::ZipArchive::new(file)?;
|
||||
zip.extract(&home_dir)?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|join| anyhow!("backup extraction task failed: {join}"))??;
|
||||
|
||||
let _profile_write = crate::config::profiles::PROFILE_WRITE_LOCK.lock().await;
|
||||
finalize_restored_verge_config(webdav_url, webdav_username, webdav_password).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?
|
||||
let backup_storage_path = app_home_dir()
|
||||
.map_err(|e| anyhow::anyhow!("Failed to get app home dir: {e}"))?
|
||||
.join(filename.as_str());
|
||||
let name = filename.clone();
|
||||
backup::WebDavClient::global()
|
||||
.download(filename, backup_storage_path.clone())
|
||||
.await
|
||||
.map_err(|err| {
|
||||
logging!(
|
||||
error,
|
||||
Type::Backup,
|
||||
"Failed to download WebDAV backup file {name}: {err:#}"
|
||||
);
|
||||
err
|
||||
})?;
|
||||
|
||||
let res = restore_backup_archive(backup_storage_path.clone()).await;
|
||||
let _ = backup_storage_path.remove_if_exists().await;
|
||||
res
|
||||
}
|
||||
|
||||
pub async fn create_local_backup() -> Result<()> {
|
||||
@@ -435,13 +335,6 @@ pub async fn delete_local_backup(filename: String) -> Result<()> {
|
||||
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()?;
|
||||
@@ -450,8 +343,7 @@ pub async fn restore_local_backup(filename: String) -> Result<()> {
|
||||
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
|
||||
restore_backup_archive(target_path).await
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, level = "info", fields(filename = %filename, destination = %destination))]
|
||||
@@ -473,105 +365,3 @@ pub async fn export_local_backup(filename: String, destination: String) -> Resul
|
||||
.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(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,13 +34,10 @@ pub async fn set_dns_override(
|
||||
profiles.current.as_ref() == Some(&profile_uid),
|
||||
"The active profile changed; retry the DNS setting"
|
||||
);
|
||||
let source = {
|
||||
let _guard = crate::config::profile_storage::read().await?;
|
||||
dns_override_source(
|
||||
profiles.current.as_deref().unwrap_or_default(),
|
||||
¤t_mapping(&profiles).await?,
|
||||
)?
|
||||
};
|
||||
let source = dns_override_source(
|
||||
profiles.current.as_deref().unwrap_or_default(),
|
||||
¤t_mapping(&profiles).await?,
|
||||
)?;
|
||||
if enabled && let Some(source) = source.as_ref().filter(|source| Some(*source) != confirmation.as_ref()) {
|
||||
return Ok(DnsOverrideOutcome::ConfirmationRequired { source: source.clone() });
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use crate::{
|
||||
config::{
|
||||
Config, PrfOption, download_subscription, profile_storage, profiles::save_remote_refresh, subscription_proxy,
|
||||
Config, PrfOption, download_subscription, prepare_remote_refresh, profiles::save_remote_refresh,
|
||||
subscription_proxy,
|
||||
},
|
||||
core::{
|
||||
CoreManager, handle,
|
||||
@@ -16,46 +17,57 @@ use anyhow::{Result, bail};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use tristr::alias::String;
|
||||
|
||||
struct RefreshSource {
|
||||
name: Option<String>,
|
||||
url: String,
|
||||
file: Option<String>,
|
||||
option: Option<PrfOption>,
|
||||
}
|
||||
|
||||
async fn refresh_source(uid: &str, ignore_auto_update: bool) -> Result<Option<RefreshSource>> {
|
||||
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
|
||||
let profiles = Config::profiles().await;
|
||||
let _guard = profile_storage::read().await?;
|
||||
let profiles = profiles.latest_arc();
|
||||
let item = profiles.get_item(uid)?;
|
||||
if item.itype.as_deref() != Some("remote") {
|
||||
let is_remote = item.itype.as_ref().is_some_and(|s| s == "remote");
|
||||
|
||||
if !is_remote {
|
||||
logging!(info, Type::Config, "[订阅更新] 不是远程订阅,跳过更新");
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(url) = &item.url else {
|
||||
Ok(None)
|
||||
} else if item.url.is_none() {
|
||||
logging!(warn, Type::Config, "[订阅更新] 缺少URL,无法更新");
|
||||
bail!("failed to get the profile item url");
|
||||
};
|
||||
if !ignore_auto_update && !item.option.as_ref().and_then(|o| o.allow_auto_update).unwrap_or(true) {
|
||||
} else if !ignore_auto_update && !item.option.as_ref().and_then(|o| o.allow_auto_update).unwrap_or(true) {
|
||||
logging!(info, Type::Config, "[订阅更新] 禁止自动更新,跳过更新");
|
||||
return Ok(None);
|
||||
Ok(None)
|
||||
} else {
|
||||
logging!(
|
||||
info,
|
||||
Type::Config,
|
||||
"[订阅更新] 远程订阅,URL: {}",
|
||||
mask_url(
|
||||
item.url
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?
|
||||
)
|
||||
);
|
||||
Ok(Some((
|
||||
item.url.clone().ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?,
|
||||
item.option.clone(),
|
||||
)))
|
||||
}
|
||||
logging!(info, Type::Config, "[订阅更新] 远程订阅,URL: {}", mask_url(url));
|
||||
Ok(Some(RefreshSource {
|
||||
name: item.name.clone(),
|
||||
url: url.clone(),
|
||||
file: item.file.clone(),
|
||||
option: item.option.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))]
|
||||
async fn perform_profile_update(uid: &str, source: RefreshSource, overrides: Option<&PrfOption>) -> Result<()> {
|
||||
let url = source.url.as_str();
|
||||
let options = PrfOption::merge(source.option.as_ref(), overrides);
|
||||
let download_options = options.as_ref();
|
||||
let configured_proxy = subscription_proxy(download_options);
|
||||
let profile_name = source.name.as_deref().unwrap_or("UnKnown Profile");
|
||||
async fn perform_profile_update(
|
||||
uid: &str,
|
||||
url: &str,
|
||||
profile_options: Option<&PrfOption>,
|
||||
overrides: Option<&PrfOption>,
|
||||
is_manual_trigger: bool,
|
||||
) -> Result<()> {
|
||||
let options = PrfOption::merge(profile_options, overrides);
|
||||
let options = options.as_ref();
|
||||
let configured_proxy = subscription_proxy(options);
|
||||
let profiles = Config::profiles().await;
|
||||
let profiles_arc = profiles.latest_arc();
|
||||
let profile_name = profiles_arc
|
||||
.get_item(uid)
|
||||
.ok()
|
||||
.and_then(|item| item.name.clone())
|
||||
.unwrap_or_else(|| String::from("UnKnown Profile"));
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Strategy {
|
||||
@@ -93,7 +105,7 @@ async fn perform_profile_update(uid: &str, source: RefreshSource, overrides: Opt
|
||||
};
|
||||
tracing::Span::current().record("strategy", name);
|
||||
let started = std::time::Instant::now();
|
||||
let result = download_subscription(url, download_options, proxy).await;
|
||||
let result = download_subscription(url, options, proxy).await;
|
||||
tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed()));
|
||||
match &result {
|
||||
Ok(_) => logging!(info, Type::Config, "{success}"),
|
||||
@@ -108,22 +120,43 @@ async fn perform_profile_update(uid: &str, source: RefreshSource, overrides: Opt
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let (strategy, downloaded) = result.map_err(|err| anyhow::anyhow!(mask_err(&format!("{err:#}"))))?;
|
||||
// A persistence error must not replay a successful download with another transport.
|
||||
save_remote_refresh(uid, source.url, source.file, downloaded).await?;
|
||||
if !matches!(strategy, Strategy::Configured) {
|
||||
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name);
|
||||
let last_err = match result {
|
||||
Ok((strategy, downloaded)) => {
|
||||
// A persistence error must not replay a successful download with another transport.
|
||||
let profiles = Config::profiles().await;
|
||||
let snapshot = profiles.latest_arc();
|
||||
let current = snapshot.get_item(uid)?;
|
||||
anyhow::ensure!(
|
||||
current.itype.as_deref() == Some("remote") && current.url.as_deref() == Some(url),
|
||||
"profile source changed during refresh"
|
||||
);
|
||||
let refresh = prepare_remote_refresh(downloaded, options).await?;
|
||||
save_remote_refresh(uid, url, refresh).await?;
|
||||
if !matches!(strategy, Strategy::Configured) {
|
||||
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str());
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Err(error) => error,
|
||||
};
|
||||
|
||||
let last_err = mask_err(&last_err.to_string());
|
||||
if is_manual_trigger {
|
||||
handle::Handle::notice(
|
||||
NoticeStatus::UpdateFailedEvenWithClash,
|
||||
format!("{profile_name} - {last_err}"),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
bail!(last_err)
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_manual_trigger))]
|
||||
pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_trigger: bool) -> Result<()> {
|
||||
let subscription = refresh_source(uid, is_manual_trigger).await?;
|
||||
let subscription = should_update_profile(uid, is_manual_trigger).await?;
|
||||
|
||||
let profile_persisted = match subscription {
|
||||
Some(source) => {
|
||||
perform_profile_update(uid, source, option).await?;
|
||||
Some((url, profile_options)) => {
|
||||
perform_profile_update(uid, &url, profile_options.as_ref(), option, is_manual_trigger).await?;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
@@ -151,9 +184,7 @@ pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_tri
|
||||
message
|
||||
};
|
||||
logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message);
|
||||
if !is_manual_trigger {
|
||||
handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str());
|
||||
}
|
||||
handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str());
|
||||
bail!(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
cmd::apply_dns_config,
|
||||
cmd::set_dns_override,
|
||||
cmd::take_dns_override_notice,
|
||||
cmd::take_service_fallback_notice,
|
||||
cmd::get_core_startup_error,
|
||||
cmd::take_service_repair_notice,
|
||||
cmd::take_service_owner_notice,
|
||||
|
||||
@@ -21,7 +21,6 @@ pub static BACKUP_DIR: &str = "clash-verge-rev-backup-dev";
|
||||
pub static CLASH_CONFIG: &str = "config.yaml";
|
||||
pub static VERGE_CONFIG: &str = "verge.yaml";
|
||||
pub static PROFILE_YAML: &str = "profiles.yaml";
|
||||
pub static PROFILES_DIR: &str = "profiles";
|
||||
/// Marks that the one-shot raise of too-short auto-update intervals has already run.
|
||||
pub static UPDATE_INTERVAL_MIGRATED: &str = ".update-interval-migrated";
|
||||
|
||||
@@ -49,7 +48,7 @@ pub fn app_resources_dir() -> Result<PathBuf> {
|
||||
}
|
||||
|
||||
pub fn app_profiles_dir() -> Result<PathBuf> {
|
||||
Ok(app_home_dir()?.join(PROFILES_DIR))
|
||||
Ok(app_home_dir()?.join("profiles"))
|
||||
}
|
||||
|
||||
pub fn app_icons_dir() -> Result<PathBuf> {
|
||||
|
||||
@@ -470,8 +470,7 @@ async fn initialize_config_files() -> Result<()> {
|
||||
logging!(info, Type::Setup, "Created verge config at {:?}", path);
|
||||
}
|
||||
|
||||
if crate::config::profile_storage::check().is_ok()
|
||||
&& let Ok(path) = dirs::profiles_path()
|
||||
if let Ok(path) = dirs::profiles_path()
|
||||
&& !path.exists()
|
||||
{
|
||||
let template = IProfiles::default();
|
||||
@@ -490,10 +489,6 @@ async fn initialize_config_files() -> Result<()> {
|
||||
|
||||
/// Initializes configuration required before Tauri setup.
|
||||
pub async fn init_config() -> Result<()> {
|
||||
if let Err(error) = crate::config::profile_storage::recover_at_startup().await {
|
||||
logging!(error, Type::Config, "Profile recovery failed: {error:#}");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
migrate_legacy_macos_logs().await?;
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ import { useNavigate } from 'react-router'
|
||||
|
||||
import { useAppRefreshers } from '@/providers/app-data-context'
|
||||
import { updateProfile } from '@/services/cmds'
|
||||
import { mutate } from '@/services/mutate'
|
||||
import { showNotice } from '@/services/notice-service'
|
||||
import { isValidUrl } from '@/utils/network'
|
||||
import { openExternalUrl } from '@/utils/open-external-url'
|
||||
@@ -278,11 +279,19 @@ export const HomeProfileCard = ({
|
||||
|
||||
setUpdating(true)
|
||||
try {
|
||||
if (!(await updateProfile(current))) return
|
||||
await mutate(
|
||||
() => updateProfile(current.uid!, current.option ?? undefined),
|
||||
{
|
||||
id: `update-profile:${current.uid}`,
|
||||
errorNotice: false,
|
||||
},
|
||||
)
|
||||
onProfileUpdated?.()
|
||||
|
||||
// 刷新首页数据
|
||||
refreshAll()
|
||||
} catch (err) {
|
||||
showNotice.error(err, 3000)
|
||||
} finally {
|
||||
setUpdating(false)
|
||||
}
|
||||
|
||||
@@ -60,34 +60,20 @@ it.each([
|
||||
},
|
||||
)
|
||||
|
||||
it('reports the permission refusal and finishes after installation falls back to Sidecar', async () => {
|
||||
store.runState = {
|
||||
service: 'notInstalled',
|
||||
mode: 'NotRunning',
|
||||
} as unknown as RunState
|
||||
const reason = 'core path C:\\ is writable by Everyone'
|
||||
vi.mocked(installService).mockResolvedValue({ status: 'sidecar', reason })
|
||||
vi.mocked(getRuntimeState).mockResolvedValue({
|
||||
service: 'unavailable',
|
||||
mode: 'Sidecar',
|
||||
sidecarAllowed: true,
|
||||
serviceNeedsAttention: false,
|
||||
} as RunState)
|
||||
|
||||
const dialog = ServiceMigrationDialog()
|
||||
dialog.props.onOk()
|
||||
await vi.waitFor(() => {
|
||||
expect(showNotice.warning).toHaveBeenCalledWith(
|
||||
'settings.feedback.notifications.clashService.permissionFallback',
|
||||
{ reason },
|
||||
0,
|
||||
)
|
||||
})
|
||||
it('leaves the choice open when installation fails', async () => {
|
||||
store.runState = { service: 'notInstalled', mode: 'NotRunning' } as RunState
|
||||
const error = new Error('core path is writable by Everyone')
|
||||
vi.mocked(installService).mockRejectedValue(error)
|
||||
vi.mocked(getRuntimeState).mockResolvedValue(store.runState)
|
||||
|
||||
ServiceMigrationDialog().props.onOk()
|
||||
await vi.waitFor(() => expect(getRuntimeState).toHaveBeenCalled())
|
||||
expect(showNotice.error).toHaveBeenCalledWith(
|
||||
'layout.components.serviceMigration.errors.actionFailed',
|
||||
error,
|
||||
)
|
||||
expect(restartCore).not.toHaveBeenCalled()
|
||||
expect(showNotice.error).not.toHaveBeenCalled()
|
||||
expect(showNotice.success).not.toHaveBeenCalled()
|
||||
expect(vi.mocked(useState).mock.results[2].value[1]).toHaveBeenLastCalledWith(
|
||||
expect(vi.mocked(useState).mock.results[2].value[1]).not.toHaveBeenCalledWith(
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
reinstallService,
|
||||
repairService,
|
||||
restartCore,
|
||||
type ServiceInstallOutcome,
|
||||
} from '@/services/cmds'
|
||||
import { mutate } from '@/services/mutate'
|
||||
import { showNotice } from '@/services/notice-service'
|
||||
@@ -70,26 +69,26 @@ export const ServiceMigrationDialog = () => {
|
||||
const handleServiceAction = async () => {
|
||||
setLoading(true)
|
||||
setWorkflowIncomplete(true)
|
||||
let outcome: ServiceInstallOutcome | undefined
|
||||
let installed = false
|
||||
try {
|
||||
if (remedy === 'install') {
|
||||
const result = await mutate(() => installService(), {
|
||||
id: 'install-service',
|
||||
errorNotice: false,
|
||||
})
|
||||
if (result.ok) outcome = result.value
|
||||
installed = result.ok
|
||||
} else if (remedy === 'repair') {
|
||||
const result = await mutate(() => repairService(), {
|
||||
id: 'repair-service',
|
||||
errorNotice: false,
|
||||
})
|
||||
if (result.ok) outcome = result.value
|
||||
installed = result.ok
|
||||
} else {
|
||||
const result = await mutate(() => reinstallService(), {
|
||||
id: 'reinstall-service',
|
||||
errorNotice: false,
|
||||
})
|
||||
if (result.ok) outcome = result.value
|
||||
installed = result.ok
|
||||
}
|
||||
} catch (error) {
|
||||
showNotice.error(
|
||||
@@ -108,21 +107,10 @@ export const ServiceMigrationDialog = () => {
|
||||
error,
|
||||
)
|
||||
}
|
||||
if (!outcome || !initialRefreshSucceeded) {
|
||||
if (!installed || !initialRefreshSucceeded) {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
if (outcome.status === 'sidecar') {
|
||||
setWorkflowIncomplete(false)
|
||||
setLoading(false)
|
||||
showNotice.warning(
|
||||
'settings.feedback.notifications.clashService.permissionFallback',
|
||||
{ reason: outcome.reason },
|
||||
0,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
let restartSucceeded = false
|
||||
try {
|
||||
const result = await mutate(() => restartCore(), {
|
||||
@@ -214,6 +202,9 @@ export const ServiceMigrationDialog = () => {
|
||||
? 'layout.components.serviceMigration.message'
|
||||
: 'layout.components.serviceMigration.unavailableMessage',
|
||||
)}
|
||||
{!showCheckingMessage && runState?.serviceUnavailableReason && (
|
||||
<div>{runState.serviceUnavailableReason}</div>
|
||||
)}
|
||||
</Alert>
|
||||
</BaseDialog>
|
||||
)
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
restartCore,
|
||||
type FailedOperation,
|
||||
type PendingFailure,
|
||||
type ServiceInstallOutcome,
|
||||
} from '@/services/cmds'
|
||||
import { mutate } from '@/services/mutate'
|
||||
import { showNotice } from '@/services/notice-service'
|
||||
@@ -23,7 +22,6 @@ import {
|
||||
type ServiceRequestReason,
|
||||
} from '@/services/service-request'
|
||||
import { useAppReads } from '@/store/app-store-context'
|
||||
import getSystem from '@/utils/get-system'
|
||||
|
||||
type Remedy = 'installAndRestart' | 'reinstallAndRestart' | 'restartOnly'
|
||||
|
||||
@@ -105,30 +103,20 @@ export const SysproxyPrivilegeDialog = () => {
|
||||
|
||||
const handleFix = async () => {
|
||||
try {
|
||||
let outcome: ServiceInstallOutcome | undefined
|
||||
if (remedy === 'reinstallAndRestart') {
|
||||
setStep('installing')
|
||||
const result = await mutate(() => reinstallService(), {
|
||||
id: 'reinstall-service',
|
||||
errorNotice: false,
|
||||
})
|
||||
if (result.ok) outcome = result.value
|
||||
if (!result.ok) return
|
||||
} else if (remedy === 'installAndRestart') {
|
||||
setStep('installing')
|
||||
const result = await mutate(() => installService(), {
|
||||
id: 'install-service',
|
||||
errorNotice: false,
|
||||
})
|
||||
if (result.ok) outcome = result.value
|
||||
}
|
||||
if (outcome?.status === 'sidecar') {
|
||||
showNotice.warning(
|
||||
'settings.feedback.notifications.clashService.permissionFallback',
|
||||
{ reason: outcome.reason },
|
||||
0,
|
||||
)
|
||||
close()
|
||||
return
|
||||
if (!result.ok) return
|
||||
}
|
||||
setStep('restarting')
|
||||
await mutate(() => restartCore(), {
|
||||
@@ -137,14 +125,7 @@ export const SysproxyPrivilegeDialog = () => {
|
||||
})
|
||||
|
||||
const runState = await readRunState()
|
||||
const usingAdminFallback =
|
||||
remedy !== 'reinstallAndRestart' &&
|
||||
getSystem() === 'windows' &&
|
||||
runState.mode === 'Sidecar' &&
|
||||
runState.isAdmin &&
|
||||
runState.sidecarAllowed &&
|
||||
runState.service === 'unavailable'
|
||||
if (runState.mode === 'Service' || usingAdminFallback) {
|
||||
if (runState.mode === 'Service') {
|
||||
if (restoring !== undefined) {
|
||||
setStep('applying')
|
||||
await mutate(() => patchVergeConfig(restoring), {
|
||||
@@ -152,15 +133,13 @@ export const SysproxyPrivilegeDialog = () => {
|
||||
errorNotice: false,
|
||||
})
|
||||
}
|
||||
if (!usingAdminFallback) {
|
||||
showNotice.success(
|
||||
remedy === 'reinstallAndRestart'
|
||||
? 'layout.components.serviceMigration.success'
|
||||
: restoring === undefined
|
||||
? 'settings.sections.proxyControl.messages.installedCheckProxy'
|
||||
: 'settings.sections.proxyControl.messages.installedProxyRestored',
|
||||
)
|
||||
}
|
||||
showNotice.success(
|
||||
remedy === 'reinstallAndRestart'
|
||||
? 'layout.components.serviceMigration.success'
|
||||
: restoring === undefined
|
||||
? 'settings.sections.proxyControl.messages.installedCheckProxy'
|
||||
: 'settings.sections.proxyControl.messages.installedProxyRestored',
|
||||
)
|
||||
close()
|
||||
} else {
|
||||
showNotice.error(
|
||||
|
||||
@@ -425,7 +425,13 @@ const ProfileItemBase = (props: ProfileItemProps) => {
|
||||
|
||||
try {
|
||||
const payload = Object.keys(option).length > 0 ? option : undefined
|
||||
if (await updateProfile(itemData, payload)) void mutateProfiles()
|
||||
await mutate(() => updateProfile(itemData.uid!, payload), {
|
||||
id: `update-profile:${itemData.uid}`,
|
||||
errorNotice: false,
|
||||
})
|
||||
|
||||
void mutateProfiles()
|
||||
} catch {
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
|
||||
@@ -33,14 +33,6 @@ export const useServiceInstaller = () => {
|
||||
'settings.statuses.clashService.installing',
|
||||
)
|
||||
if (!installResult.ok) return
|
||||
if (installResult.value.status === 'sidecar') {
|
||||
showNotice.warning(
|
||||
'settings.feedback.notifications.clashService.permissionFallback',
|
||||
{ reason: installResult.value.reason },
|
||||
0,
|
||||
)
|
||||
return
|
||||
}
|
||||
showNotice.success(
|
||||
'settings.feedback.notifications.clashService.installSuccess',
|
||||
)
|
||||
|
||||
@@ -701,7 +701,8 @@
|
||||
"uninstallSuccess": "تم إلغاء تثبيت الخدمة بنجاح"
|
||||
},
|
||||
"updater": {
|
||||
"withClashProxySuccess": "Update with Clash proxy successfully"
|
||||
"withClashProxySuccess": "Update with Clash proxy successfully",
|
||||
"withClashProxyFailed": "Update failed even with Clash proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -701,7 +701,8 @@
|
||||
"uninstallSuccess": "Service erfolgreich deinstalliert"
|
||||
},
|
||||
"updater": {
|
||||
"withClashProxySuccess": "Aktualisierung mit Clash-Proxy erfolgreich"
|
||||
"withClashProxySuccess": "Aktualisierung mit Clash-Proxy erfolgreich",
|
||||
"withClashProxyFailed": "Aktualisierung auch mit Clash-Proxy fehlgeschlagen"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -701,7 +701,8 @@
|
||||
"uninstallSuccess": "Service Uninstalled Successfully"
|
||||
},
|
||||
"updater": {
|
||||
"withClashProxySuccess": "Update with Clash proxy successfully"
|
||||
"withClashProxySuccess": "Update with Clash proxy successfully",
|
||||
"withClashProxyFailed": "Update failed even with Clash proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -701,7 +701,8 @@
|
||||
"uninstallSuccess": "Servicio desinstalado con éxito"
|
||||
},
|
||||
"updater": {
|
||||
"withClashProxySuccess": "Actualización con el proxy de Clash exitosa"
|
||||
"withClashProxySuccess": "Actualización con el proxy de Clash exitosa",
|
||||
"withClashProxyFailed": "Error al actualizar incluso con el proxy de Clash"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -701,7 +701,8 @@
|
||||
"uninstallSuccess": "سرویس با موفقیت حذف نصب شد"
|
||||
},
|
||||
"updater": {
|
||||
"withClashProxySuccess": "با موفقیت با پروکسی کلش بهروزرسانی شد"
|
||||
"withClashProxySuccess": "با موفقیت با پروکسی کلش بهروزرسانی شد",
|
||||
"withClashProxyFailed": "بهروزرسانی حتی با پروکسی کلش هم انجام نشد"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -701,7 +701,8 @@
|
||||
"uninstallSuccess": "Layanan Berhasil Dicopot"
|
||||
},
|
||||
"updater": {
|
||||
"withClashProxySuccess": "Update with Clash proxy successfully"
|
||||
"withClashProxySuccess": "Update with Clash proxy successfully",
|
||||
"withClashProxyFailed": "Update failed even with Clash proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -701,7 +701,8 @@
|
||||
"uninstallSuccess": "サービスのアンインストールに成功しました。"
|
||||
},
|
||||
"updater": {
|
||||
"withClashProxySuccess": "Clashプロキシを使用して更新に成功しました。"
|
||||
"withClashProxySuccess": "Clashプロキシを使用して更新に成功しました。",
|
||||
"withClashProxyFailed": "Clashプロキシを使用しても更新に失敗しました。"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -701,7 +701,8 @@
|
||||
"uninstallSuccess": "서비스가 제거되었습니다"
|
||||
},
|
||||
"updater": {
|
||||
"withClashProxySuccess": "Clash 프록시로 업데이트 성공"
|
||||
"withClashProxySuccess": "Clash 프록시로 업데이트 성공",
|
||||
"withClashProxyFailed": "Clash 프록시로도 업데이트 실패"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -701,7 +701,8 @@
|
||||
"uninstallSuccess": "Serviço Desinstalado com Sucesso"
|
||||
},
|
||||
"updater": {
|
||||
"withClashProxySuccess": "Atualização com o proxy do Clash concluída com sucesso"
|
||||
"withClashProxySuccess": "Atualização com o proxy do Clash concluída com sucesso",
|
||||
"withClashProxyFailed": "A atualização falhou mesmo com o proxy do Clash"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -701,7 +701,8 @@
|
||||
"uninstallSuccess": "Служба успешно удалена"
|
||||
},
|
||||
"updater": {
|
||||
"withClashProxySuccess": "Обновление через Clash proxy выполнено успешно"
|
||||
"withClashProxySuccess": "Обновление через Clash proxy выполнено успешно",
|
||||
"withClashProxyFailed": "Обновление не удалось даже через Clash proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -701,7 +701,8 @@
|
||||
"uninstallSuccess": "Hizmet Başarıyla Kaldırıldı"
|
||||
},
|
||||
"updater": {
|
||||
"withClashProxySuccess": "Clash vekil ile güncelleme başarılı"
|
||||
"withClashProxySuccess": "Clash vekil ile güncelleme başarılı",
|
||||
"withClashProxyFailed": "Clash vekil ile bile güncelleme başarısız oldu"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -701,7 +701,8 @@
|
||||
"uninstallSuccess": "Сервис уңышлы салдырылды"
|
||||
},
|
||||
"updater": {
|
||||
"withClashProxySuccess": "Update with Clash proxy successfully"
|
||||
"withClashProxySuccess": "Update with Clash proxy successfully",
|
||||
"withClashProxyFailed": "Update failed even with Clash proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -701,7 +701,8 @@
|
||||
"uninstallSuccess": "已成功卸载服务"
|
||||
},
|
||||
"updater": {
|
||||
"withClashProxySuccess": "使用 Clash 代理更新成功"
|
||||
"withClashProxySuccess": "使用 Clash 代理更新成功",
|
||||
"withClashProxyFailed": "使用 Clash 代理更新失败"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -701,7 +701,8 @@
|
||||
"uninstallSuccess": "已成功解除安裝服務"
|
||||
},
|
||||
"updater": {
|
||||
"withClashProxySuccess": "使用 Clash 代理更新成功"
|
||||
"withClashProxySuccess": "使用 Clash 代理更新成功",
|
||||
"withClashProxyFailed": "使用 Clash 代理更新也失敗"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
+29
-31
@@ -16,15 +16,7 @@ import {
|
||||
RefreshRounded,
|
||||
TextSnippetOutlined,
|
||||
} from '@mui/icons-material'
|
||||
import {
|
||||
Alert,
|
||||
Box,
|
||||
Button,
|
||||
Divider,
|
||||
Grid,
|
||||
IconButton,
|
||||
Stack,
|
||||
} from '@mui/material'
|
||||
import { Box, Button, Divider, Grid, IconButton, Stack } from '@mui/material'
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window'
|
||||
import { readText } from '@tauri-apps/plugin-clipboard-manager'
|
||||
import { readTextFile } from '@tauri-apps/plugin-fs'
|
||||
@@ -58,7 +50,7 @@ import {
|
||||
updateProfile,
|
||||
} from '@/services/cmds'
|
||||
import { mutate } from '@/services/mutate'
|
||||
import { errorDetail, failureCode, showNotice } from '@/services/notice-service'
|
||||
import { errorDetail, showNotice } from '@/services/notice-service'
|
||||
import { revalidateQuery, useQuery } from '@/services/query-client'
|
||||
import { useThemeMode } from '@/services/states'
|
||||
import {
|
||||
@@ -545,43 +537,52 @@ const ProfilePage = () => {
|
||||
const setLoadingProfiles = useSetProfileLoading()
|
||||
|
||||
const runProfileUpdates = useCallback(
|
||||
async (items: IProfileItem[]) => {
|
||||
if (items.length === 0) return
|
||||
async (uids: string[]) => {
|
||||
if (uids.length === 0) return
|
||||
|
||||
const throttleMutate = throttle(mutateProfiles, 2000, {
|
||||
trailing: true,
|
||||
})
|
||||
let cursor = 0
|
||||
|
||||
const updateOne = async (uid: string) => {
|
||||
try {
|
||||
// Per-uid id: the worker pool must not dedupe distinct subscriptions.
|
||||
await mutate(() => updateProfile(uid), {
|
||||
id: `update-profile:${uid}`,
|
||||
errorNotice: false,
|
||||
})
|
||||
throttleMutate()
|
||||
} catch (err: any) {
|
||||
console.error(`更新订阅 ${uid} 失败:`, err)
|
||||
}
|
||||
}
|
||||
|
||||
const worker = async () => {
|
||||
while (cursor < items.length) {
|
||||
if (await updateProfile(items[cursor++])) throttleMutate()
|
||||
while (cursor < uids.length) {
|
||||
const uid = uids[cursor++]
|
||||
await updateOne(uid)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const active = Math.min(PROFILE_UPDATE_WORKER_LIMIT, items.length)
|
||||
const active = Math.min(PROFILE_UPDATE_WORKER_LIMIT, uids.length)
|
||||
await Promise.allSettled(Array.from({ length: active }, worker))
|
||||
} finally {
|
||||
setLoadingProfiles(
|
||||
items.map((item) => item.uid!),
|
||||
false,
|
||||
)
|
||||
setLoadingProfiles(uids, false)
|
||||
void mutateProfiles()
|
||||
}
|
||||
},
|
||||
[mutateProfiles, setLoadingProfiles],
|
||||
)
|
||||
const onUpdateAll = useLockFn(async () => {
|
||||
const items = profileItems.filter(
|
||||
(item) =>
|
||||
item.type === 'remote' && item.uid && !loadingCache.has(item.uid),
|
||||
)
|
||||
setLoadingProfiles(
|
||||
items.map((item) => item.uid!),
|
||||
true,
|
||||
)
|
||||
await runProfileUpdates(items)
|
||||
const items = profileItems.filter((e) => e.type === 'remote')
|
||||
const target = items
|
||||
.map((item) => item.uid!)
|
||||
.filter((uid) => !loadingCache.has(uid))
|
||||
|
||||
setLoadingProfiles(target, true)
|
||||
await runProfileUpdates(target)
|
||||
})
|
||||
|
||||
const onCopyLink = async () => {
|
||||
@@ -830,9 +831,6 @@ const ProfilePage = () => {
|
||||
</Box>
|
||||
}
|
||||
>
|
||||
{failureCode(error) === 'PROFILE_RECOVERY_REQUIRED' && (
|
||||
<Alert severity="error">{errorDetail(error)}</Alert>
|
||||
)}
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={1}
|
||||
|
||||
@@ -44,12 +44,10 @@ export const commands = {
|
||||
getSidecarFailure: () =>
|
||||
__TAURI_INVOKE<SidecarFailureSnapshot_Serialize>('get_sidecar_failure'),
|
||||
entryLightweightMode: () => __TAURI_INVOKE<null>('entry_lightweight_mode'),
|
||||
installService: () =>
|
||||
__TAURI_INVOKE<ServiceInstallOutcome>('install_service'),
|
||||
installService: () => __TAURI_INVOKE<null>('install_service'),
|
||||
uninstallService: () => __TAURI_INVOKE<null>('uninstall_service'),
|
||||
reinstallService: () =>
|
||||
__TAURI_INVOKE<ServiceInstallOutcome>('reinstall_service'),
|
||||
repairService: () => __TAURI_INVOKE<ServiceInstallOutcome>('repair_service'),
|
||||
reinstallService: () => __TAURI_INVOKE<null>('reinstall_service'),
|
||||
repairService: () => __TAURI_INVOKE<null>('repair_service'),
|
||||
continueWithSidecar: () => __TAURI_INVOKE<null>('continue_with_sidecar'),
|
||||
syncRuntimeProviders: () => __TAURI_INVOKE<void>('sync_runtime_providers'),
|
||||
getClashInfo: () => __TAURI_INVOKE<ClashInfo_Serialize>('get_clash_info'),
|
||||
@@ -99,10 +97,6 @@ export const commands = {
|
||||
}),
|
||||
takeDnsOverrideNotice: () =>
|
||||
__TAURI_INVOKE<boolean>('take_dns_override_notice'),
|
||||
takeServiceFallbackNotice: () =>
|
||||
__TAURI_INVOKE<ServiceFallbackNotice | null>(
|
||||
'take_service_fallback_notice',
|
||||
),
|
||||
getCoreStartupError: () =>
|
||||
__TAURI_INVOKE<CoreFailure | null>('get_core_startup_error'),
|
||||
takeServiceRepairNotice: () =>
|
||||
@@ -627,7 +621,6 @@ export type NoticeStatus =
|
||||
| 'core_start::error'
|
||||
| 'service_core::repair_required'
|
||||
| 'service_core::app_data_not_owned'
|
||||
| 'service_core::sidecar_fallback'
|
||||
| 'dns_override::auto_disabled'
|
||||
| 'enhance::discarded_keys'
|
||||
| 'tun_mode::auto_disabled'
|
||||
@@ -635,6 +628,7 @@ export type NoticeStatus =
|
||||
| 'app_restart::core_stop_failed'
|
||||
| 'app_quit::core_stop_failed'
|
||||
| 'update_with_clash_proxy'
|
||||
| 'update_failed_even_with_clash'
|
||||
| 'reactivate_profiles::error'
|
||||
| 'update_failed'
|
||||
| 'config_validate::boot_error'
|
||||
@@ -1039,12 +1033,6 @@ export type SaveProxyPortsOutcome =
|
||||
| { status: 'saved' }
|
||||
| { status: 'conflict'; port: number; transport: ListenerTransport }
|
||||
|
||||
/** Why the Service was unavailable when the core fell back to Sidecar. */
|
||||
export type ServiceFallbackNotice =
|
||||
| { kind: 'unavailable' }
|
||||
| { kind: 'coreRejected'; reason: string }
|
||||
| { kind: 'notAutoStarted' }
|
||||
|
||||
export type ServiceHealthKind =
|
||||
| 'unknown'
|
||||
| 'ready'
|
||||
@@ -1052,10 +1040,6 @@ export type ServiceHealthKind =
|
||||
| 'versionMismatch'
|
||||
| 'unavailable'
|
||||
|
||||
export type ServiceInstallOutcome =
|
||||
| { status: 'installed' }
|
||||
| { status: 'sidecar'; reason: string }
|
||||
|
||||
/** A removal has a revision too, so a delayed read cannot restore a resolved failure. */
|
||||
export type SidecarFailureSnapshot =
|
||||
| SidecarFailureSnapshot_Serialize
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
type RunState,
|
||||
getCoreStartupError,
|
||||
takeDnsOverrideNotice,
|
||||
takeServiceFallbackNotice,
|
||||
takeServiceRepairNotice,
|
||||
} from '@/services/cmds'
|
||||
import { showNotice } from '@/services/notice-service'
|
||||
@@ -24,7 +23,6 @@ vi.mock('@/services/cmds', () => ({
|
||||
getPendingFailures: vi.fn().mockResolvedValue([]),
|
||||
takeDiscardedKeysNotice: vi.fn().mockResolvedValue(null),
|
||||
takeDnsOverrideNotice: vi.fn().mockResolvedValue(false),
|
||||
takeServiceFallbackNotice: vi.fn().mockResolvedValue(null),
|
||||
takeServiceRepairNotice: vi.fn().mockResolvedValue(false),
|
||||
takeServiceOwnerNotice: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
@@ -179,22 +177,3 @@ it('offers service reinstallation for a startup path refusal even before listene
|
||||
reason: 'serviceLocationRefused',
|
||||
})
|
||||
})
|
||||
|
||||
it('explains a startup core rejection instead of the generic fallback notice', async () => {
|
||||
const reason =
|
||||
'approved core was rejected: core path "C:\\" has an untrusted write ACE'
|
||||
vi.mocked(takeServiceFallbackNotice)
|
||||
.mockResolvedValueOnce({ kind: 'coreRejected', reason })
|
||||
.mockResolvedValue(null)
|
||||
|
||||
const bus = await mountBus()
|
||||
bus.onSubscribed()
|
||||
bus.handlers['verge://notice-message'](['service_core::sidecar_fallback', ''])
|
||||
await flush()
|
||||
|
||||
expect(showNotice.warning).toHaveBeenCalledExactlyOnceWith(
|
||||
'settings.feedback.notifications.clashService.permissionFallback',
|
||||
{ reason },
|
||||
0,
|
||||
)
|
||||
})
|
||||
|
||||
@@ -92,7 +92,6 @@ export const createEventBus = (deps: BusHandlerDeps) => {
|
||||
deps.readPendingFailures()
|
||||
deps.handleNotice(['dns_override::auto_disabled', ''])
|
||||
deps.handleNotice(['enhance::discarded_keys', ''])
|
||||
deps.handleNotice(['service_core::sidecar_fallback', ''])
|
||||
deps.handleNotice(['service_core::repair_required', ''])
|
||||
deps.handleNotice(['service_core::app_data_not_owned', ''])
|
||||
deps.handleNotice(['core_start::error', ''])
|
||||
|
||||
+3
-31
@@ -1,8 +1,7 @@
|
||||
import { Channel } from '@tauri-apps/api/core'
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
import { mutate } from '@/services/mutate'
|
||||
import { errorDetail, failureCode, showNotice } from '@/services/notice-service'
|
||||
import { showNotice } from '@/services/notice-service'
|
||||
import { debugLog } from '@/utils/debug'
|
||||
|
||||
import { commands } from './bindings'
|
||||
@@ -24,7 +23,6 @@ export type {
|
||||
FailedOperation,
|
||||
PendingFailure,
|
||||
SidecarFailureSnapshot,
|
||||
ServiceInstallOutcome,
|
||||
ProxyPortSettings,
|
||||
ListenerTransport,
|
||||
ListenerProbe,
|
||||
@@ -83,30 +81,8 @@ export async function reorderProfile(activeId: string, overId: string) {
|
||||
return commands.reorderProfile(activeId, overId)
|
||||
}
|
||||
|
||||
export async function updateProfile(
|
||||
item: IProfileItem,
|
||||
option?: IProfileOption,
|
||||
) {
|
||||
if (!item.uid) return false
|
||||
const uid = item.uid
|
||||
try {
|
||||
await mutate(() => commands.updateProfile(uid, option ?? null), {
|
||||
id: `update-profile:${uid}`,
|
||||
errorNotice: false,
|
||||
})
|
||||
return true
|
||||
} catch (error) {
|
||||
if (failureCode(error) === 'PROFILE_RECOVERY_REQUIRED') {
|
||||
showNotice.error(error)
|
||||
return false
|
||||
}
|
||||
const detail = errorDetail(error)
|
||||
showNotice.error(
|
||||
'profiles.page.feedback.errors.updateFailed',
|
||||
item.name?.trim() ? `${item.name} - ${detail}` : detail,
|
||||
)
|
||||
return false
|
||||
}
|
||||
export async function updateProfile(index: string, option?: IProfileOption) {
|
||||
return commands.updateProfile(index, option ?? null)
|
||||
}
|
||||
|
||||
export async function deleteProfile(index: string) {
|
||||
@@ -257,10 +233,6 @@ export async function takeDnsOverrideNotice() {
|
||||
return commands.takeDnsOverrideNotice()
|
||||
}
|
||||
|
||||
export async function takeServiceFallbackNotice() {
|
||||
return commands.takeServiceFallbackNotice()
|
||||
}
|
||||
|
||||
export async function getCoreStartupError() {
|
||||
return commands.getCoreStartupError()
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
getCoreStartupError,
|
||||
takeDiscardedKeysNotice,
|
||||
takeDnsOverrideNotice,
|
||||
takeServiceFallbackNotice,
|
||||
takeServiceOwnerNotice,
|
||||
takeServiceRepairNotice,
|
||||
} from '@/services/cmds'
|
||||
@@ -111,30 +110,6 @@ const handlers: Record<
|
||||
console.error('Failed to read the pending service owner notice', error)
|
||||
})
|
||||
},
|
||||
'service_core::sidecar_fallback': () => {
|
||||
void takeServiceFallbackNotice()
|
||||
.then((notice) => {
|
||||
if (notice?.kind === 'coreRejected') {
|
||||
showNotice.warning(
|
||||
'settings.feedback.notifications.clashService.permissionFallback',
|
||||
{ reason: notice.reason },
|
||||
0,
|
||||
)
|
||||
} else if (notice?.kind === 'notAutoStarted') {
|
||||
requestService({ reason: 'serviceNotAutoStarted' })
|
||||
} else if (notice) {
|
||||
showNotice.warning(
|
||||
'settings.feedback.notifications.clashService.sidecarFallback',
|
||||
)
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(
|
||||
'Failed to read the pending service fallback notice',
|
||||
error,
|
||||
)
|
||||
})
|
||||
},
|
||||
'dns_override::auto_disabled': () => {
|
||||
void takeDnsOverrideNotice()
|
||||
.then((pending) => {
|
||||
@@ -182,6 +157,11 @@ const handlers: Record<
|
||||
'settings.feedback.notifications.updater.withClashProxySuccess',
|
||||
msg,
|
||||
),
|
||||
update_failed_even_with_clash: (msg) =>
|
||||
showNotice.error(
|
||||
'settings.feedback.notifications.updater.withClashProxyFailed',
|
||||
msg,
|
||||
),
|
||||
'reactivate_profiles::error': (msg) => showNotice.error(msg),
|
||||
update_failed: (msg) => showNotice.error(msg),
|
||||
'config_validate::boot_error': (msg) =>
|
||||
|
||||
@@ -481,7 +481,7 @@ const baseShowNotice = (
|
||||
return id
|
||||
}
|
||||
|
||||
export function failureCode(input: unknown): string | undefined {
|
||||
function failureCode(input: unknown): string | undefined {
|
||||
return isCommandFailure(input) ? input.code! : undefined
|
||||
}
|
||||
|
||||
|
||||
@@ -860,6 +860,7 @@ export const translationKeys = [
|
||||
'settings.feedback.notifications.clashService.sidecarFallback',
|
||||
'settings.feedback.notifications.clashService.uninstallSuccess',
|
||||
'settings.feedback.notifications.updater.withClashProxySuccess',
|
||||
'settings.feedback.notifications.updater.withClashProxyFailed',
|
||||
'settings.statuses.clash.stopping',
|
||||
'settings.statuses.clash.restarting',
|
||||
'settings.statuses.clashService.installing',
|
||||
|
||||
@@ -898,6 +898,7 @@ export interface TranslationResources {
|
||||
uninstallSuccess: string
|
||||
}
|
||||
updater: {
|
||||
withClashProxyFailed: string
|
||||
withClashProxySuccess: string
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user