mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-03 20:30:11 +08:00
Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93a5528025 | ||
|
|
4b602e1436 | ||
|
|
171586d725 | ||
|
|
fe523dc34d | ||
|
|
bc5ed53a1b | ||
|
|
be8dd3b060 | ||
|
|
bc000a8e39 | ||
|
|
724f10fd33 | ||
|
|
5c05722f9a | ||
|
|
1450ad441c | ||
|
|
dbf252ed65 | ||
|
|
e575f4dda7 | ||
|
|
840de9c4d1 | ||
|
|
c5b74aa01d | ||
|
|
f50e52172c | ||
|
|
5d471d97aa | ||
|
|
fc9d5ce2a4 | ||
|
|
4142fb07fd | ||
|
|
177c73f6d7 | ||
|
|
9eea0c7ce1 | ||
|
|
a7b6b070b7 | ||
|
|
61bd24d788 | ||
|
|
7f4ed2c179 | ||
|
|
33ce830c01 | ||
|
|
25750ae001 | ||
|
|
1baa72c2f4 | ||
|
|
a0d4426f0a | ||
|
|
1c7bc3200b | ||
|
|
7b43bac198 | ||
|
|
1fa03291f3 |
Generated
+16
@@ -1117,6 +1117,7 @@ dependencies = [
|
|||||||
"clash-verge-media-unlock",
|
"clash-verge-media-unlock",
|
||||||
"clash-verge-profile",
|
"clash-verge-profile",
|
||||||
"clash-verge-profile-script",
|
"clash-verge-profile-script",
|
||||||
|
"clash-verge-profile-store",
|
||||||
"clash-verge-proxy-view",
|
"clash-verge-proxy-view",
|
||||||
"clash-verge-runtime-bundle",
|
"clash-verge-runtime-bundle",
|
||||||
"clash-verge-signal",
|
"clash-verge-signal",
|
||||||
@@ -1176,6 +1177,7 @@ dependencies = [
|
|||||||
"tauri-plugin-wdio-webdriver",
|
"tauri-plugin-wdio-webdriver",
|
||||||
"tauri-plugin-window-state",
|
"tauri-plugin-window-state",
|
||||||
"tauri-specta",
|
"tauri-specta",
|
||||||
|
"tempfile",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-rustls",
|
"tokio-rustls",
|
||||||
"tokio-util",
|
"tokio-util",
|
||||||
@@ -1289,6 +1291,20 @@ dependencies = [
|
|||||||
"tristr",
|
"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]]
|
[[package]]
|
||||||
name = "clash-verge-proxy-view"
|
name = "clash-verge-proxy-view"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ members = [
|
|||||||
"crates/clash-verge-profile-script",
|
"crates/clash-verge-profile-script",
|
||||||
"crates/clash-verge-proxy-view",
|
"crates/clash-verge-proxy-view",
|
||||||
"crates/clash-verge-profile",
|
"crates/clash-verge-profile",
|
||||||
|
"crates/clash-verge-profile-store",
|
||||||
"crates/clash-verge-backup-archive",
|
"crates/clash-verge-backup-archive",
|
||||||
]
|
]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
@@ -73,6 +74,7 @@ clash-verge-subscription = { path = "crates/clash-verge-subscription" }
|
|||||||
clash-verge-runtime-bundle = { path = "crates/clash-verge-runtime-bundle" }
|
clash-verge-runtime-bundle = { path = "crates/clash-verge-runtime-bundle" }
|
||||||
clash-verge-proxy-view = { path = "crates/clash-verge-proxy-view" }
|
clash-verge-proxy-view = { path = "crates/clash-verge-proxy-view" }
|
||||||
clash-verge-profile = { path = "crates/clash-verge-profile" }
|
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-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", branch = "main", version = "2.8.2", default-features = false }
|
||||||
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
|
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
|
||||||
@@ -113,6 +115,7 @@ tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849
|
|||||||
serde_json = { version = "1.0.154" }
|
serde_json = { version = "1.0.154" }
|
||||||
serde_yaml_ng = { version = "0.10.0" }
|
serde_yaml_ng = { version = "0.10.0" }
|
||||||
sha2 = "0.11.2"
|
sha2 = "0.11.2"
|
||||||
|
tempfile = "3.27.0"
|
||||||
specta = "=2.0.0-rc.26"
|
specta = "=2.0.0-rc.26"
|
||||||
socket2 = "0.6.5"
|
socket2 = "0.6.5"
|
||||||
|
|
||||||
|
|||||||
@@ -4,4 +4,10 @@ pub enum ArchiveError {
|
|||||||
Zip(#[from] zip::result::ZipError),
|
Zip(#[from] zip::result::ZipError),
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
Io(#[from] std::io::Error),
|
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,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,11 @@ mod error;
|
|||||||
|
|
||||||
pub use error::ArchiveError;
|
pub use error::ArchiveError;
|
||||||
|
|
||||||
use std::io::{Seek, Write};
|
use std::{
|
||||||
use zip::{CompressionMethod, ZipWriter, write::SimpleFileOptions};
|
io::{self, Read, Seek, Write},
|
||||||
|
path::{Component, Path},
|
||||||
|
};
|
||||||
|
use zip::{CompressionMethod, ZipArchive, ZipWriter, write::SimpleFileOptions};
|
||||||
|
|
||||||
pub struct BackupWriter<W: Write + Seek> {
|
pub struct BackupWriter<W: Write + Seek> {
|
||||||
zip: ZipWriter<W>,
|
zip: ZipWriter<W>,
|
||||||
@@ -32,20 +35,59 @@ impl<W: Write + Seek> BackupWriter<W> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct ValidatedBackup<R: Read + Seek> {
|
||||||
|
zip: ZipArchive<R>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<R: Read + Seek> ValidatedBackup<R> {
|
||||||
|
/// Checks the archive layout. Extract into staging to validate file contents before restore.
|
||||||
|
pub fn open(source: R, reserved_names: &[&str]) -> Result<Self, ArchiveError> {
|
||||||
|
let mut zip = ZipArchive::new(source)?;
|
||||||
|
for index in 0..zip.len() {
|
||||||
|
let mut entry = zip.by_index(index)?;
|
||||||
|
if entry.is_symlink() {
|
||||||
|
return Err(ArchiveError::Symlink);
|
||||||
|
}
|
||||||
|
let path = entry.enclosed_name().ok_or(ArchiveError::InvalidPath)?;
|
||||||
|
for component in path.components() {
|
||||||
|
let Component::Normal(name) = component else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let name = name.to_string_lossy();
|
||||||
|
if reserved_names
|
||||||
|
.iter()
|
||||||
|
.any(|reserved| name.eq_ignore_ascii_case(reserved))
|
||||||
|
{
|
||||||
|
return Err(ArchiveError::ReservedEntry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// ZIP extraction skips directory payloads.
|
||||||
|
if entry.is_dir() {
|
||||||
|
io::copy(&mut entry, &mut io::sink())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Self { zip })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn extract_to(&mut self, destination: &Path) -> Result<(), ArchiveError> {
|
||||||
|
self.zip.extract(destination)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::io::{Cursor, Read as _};
|
use std::io::Cursor;
|
||||||
use zip::ZipArchive;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn writes_the_backup_layout() -> Result<(), ArchiveError> {
|
fn writes_and_validates_the_backup_layout() -> Result<(), ArchiveError> {
|
||||||
let mut writer = BackupWriter::new(Cursor::new(Vec::new()))?;
|
let mut writer = BackupWriter::new(Cursor::new(Vec::new()))?;
|
||||||
writer.start_profile("example.yaml")?.write_all(b"proxies: []\n")?;
|
writer.start_profile("example.yaml")?.write_all(b"proxies: []\n")?;
|
||||||
writer.start_file("profiles.yaml")?.write_all(b"items: []\n")?;
|
writer.start_file("profiles.yaml")?.write_all(b"items: []\n")?;
|
||||||
let source = writer.finish()?;
|
let source = writer.finish()?;
|
||||||
|
|
||||||
let mut zip = ZipArchive::new(source)?;
|
let mut zip = ZipArchive::new(source.clone())?;
|
||||||
assert_eq!(zip.len(), 3);
|
assert_eq!(zip.len(), 3);
|
||||||
assert_eq!(zip.by_index(0)?.name()?, "profiles/");
|
assert_eq!(zip.by_index(0)?.name()?, "profiles/");
|
||||||
let profile_time = {
|
let profile_time = {
|
||||||
@@ -60,6 +102,7 @@ mod tests {
|
|||||||
let index = zip.by_index(2)?;
|
let index = zip.by_index(2)?;
|
||||||
assert_eq!(index.name()?, "profiles.yaml");
|
assert_eq!(index.name()?, "profiles.yaml");
|
||||||
assert_eq!(index.last_modified(), profile_time);
|
assert_eq!(index.last_modified(), profile_time);
|
||||||
|
ValidatedBackup::open(source, &[".profile-refresh", ".profile-refresh.lock"])?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
[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",
|
||||||
|
] }
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
use std::{io, path::PathBuf};
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum StoreError {
|
||||||
|
#[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),
|
||||||
|
}
|
||||||
@@ -0,0 +1,650 @@
|
|||||||
|
//! 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";
|
||||||
|
|
||||||
|
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],
|
||||||
|
}
|
||||||
|
|
||||||
|
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)? {
|
||||||
|
return Err(StoreError::UnsupportedVolume);
|
||||||
|
}
|
||||||
|
let lock = platform::open_lock(&root.join(RECOVERY_LOCK_NAME))?;
|
||||||
|
lock.lock()?;
|
||||||
|
let session = Self { root, _lock: lock };
|
||||||
|
session.recover(checkpoint)?;
|
||||||
|
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 new_item = candidate.get_item(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 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)?;
|
||||||
|
unshared_body(&profiles_dir, candidate, file)?;
|
||||||
|
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 index = format!(
|
||||||
|
"# Profiles Config for Clash Verge\n\n{}",
|
||||||
|
serde_yaml_ng::to_string(candidate)?
|
||||||
|
);
|
||||||
|
let decision = Decision {
|
||||||
|
version: 1,
|
||||||
|
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.as_bytes()).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")?;
|
||||||
|
write_new(&journal.join(INDEX_NEXT), index.as_bytes(), 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)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
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)?;
|
||||||
|
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)?;
|
||||||
|
}
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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))?;
|
||||||
|
}
|
||||||
|
fs::remove_dir(&journal)?;
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
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 decision.version != 1 {
|
||||||
|
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']) {
|
||||||
|
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) -> Result<Option<fs::Metadata>> {
|
||||||
|
let 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 != 1) {
|
||||||
|
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)?;
|
||||||
|
let other = dir.join(other);
|
||||||
|
match fs::metadata(&other) {
|
||||||
|
Ok(metadata) => {
|
||||||
|
if let Some(identity) = &identity
|
||||||
|
&& platform::file_identity(&other, &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()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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)?)
|
||||||
|
}
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
#[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()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
#![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_allows_an_unrelated_unix_filename() -> 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/r.yaml"), b"old")?;
|
||||||
|
fs::write(root.join("profiles/office:old.yaml"), b"local")?;
|
||||||
|
let old = "items:\n- {uid: r, type: remote, file: r.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/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(())
|
||||||
|
}
|
||||||
@@ -22,6 +22,7 @@ tokio-trace = ["clash-verge-logging/tokio-trace"]
|
|||||||
chrome-trace = ["clash-verge-logging/chrome-trace"]
|
chrome-trace = ["clash-verge-logging/chrome-trace"]
|
||||||
clippy = ["tauri/test"]
|
clippy = ["tauri/test"]
|
||||||
perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
|
perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
|
||||||
|
profile-store-windows = []
|
||||||
|
|
||||||
[package.metadata.bundle]
|
[package.metadata.bundle]
|
||||||
identifier = "io.github.clash-verge-rev.clash-verge-rev"
|
identifier = "io.github.clash-verge-rev.clash-verge-rev"
|
||||||
@@ -30,6 +31,7 @@ identifier = "io.github.clash-verge-rev.clash-verge-rev"
|
|||||||
tauri-build = { version = "2.8.0", features = [] }
|
tauri-build = { version = "2.8.0", features = [] }
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
tempfile = { workspace = true }
|
||||||
clash-verge-draft = { workspace = true }
|
clash-verge-draft = { workspace = true }
|
||||||
clash-verge-task = { workspace = true }
|
clash-verge-task = { workspace = true }
|
||||||
clash-verge-media-unlock = { workspace = true }
|
clash-verge-media-unlock = { workspace = true }
|
||||||
@@ -81,7 +83,6 @@ tauri-plugin-dialog = { version = "2.9.0", default-features = false, features =
|
|||||||
tauri-plugin-fs = "2.8.0"
|
tauri-plugin-fs = "2.8.0"
|
||||||
tauri-plugin-deep-link = "2.6.3"
|
tauri-plugin-deep-link = "2.6.3"
|
||||||
tauri-plugin-window-state = "2.5.1"
|
tauri-plugin-window-state = "2.5.1"
|
||||||
zip = { workspace = true }
|
|
||||||
flate2 = "1.1.11"
|
flate2 = "1.1.11"
|
||||||
reqwest_dav = "0.4.0"
|
reqwest_dav = "0.4.0"
|
||||||
aes-gcm = { version = "0.11.1" }
|
aes-gcm = { version = "0.11.1" }
|
||||||
@@ -109,6 +110,9 @@ specta = { workspace = true, features = ["derive", "function", "serde_json"] }
|
|||||||
tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] }
|
tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] }
|
||||||
specta-typescript = "=0.0.13"
|
specta-typescript = "=0.0.13"
|
||||||
|
|
||||||
|
[target.'cfg(any(unix, windows))'.dependencies]
|
||||||
|
clash-verge-profile-store = { workspace = true }
|
||||||
|
|
||||||
[target.'cfg(unix)'.dependencies]
|
[target.'cfg(unix)'.dependencies]
|
||||||
libc = "0.2.191"
|
libc = "0.2.191"
|
||||||
|
|
||||||
@@ -146,6 +150,7 @@ objc2-app-kit = { version = "0.3.2", features = [
|
|||||||
] }
|
] }
|
||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
|
zip = { workspace = true }
|
||||||
deelevate = { workspace = true }
|
deelevate = { workspace = true }
|
||||||
quick-xml = "0.42.0"
|
quick-xml = "0.42.0"
|
||||||
runas = "=1.2.0"
|
runas = "=1.2.0"
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ fn profile_import_error(err: &anyhow::Error) -> std::string::String {
|
|||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn get_profiles() -> CmdResult<SharedDraft<IProfiles>> {
|
pub async fn get_profiles() -> CmdResult<SharedDraft<IProfiles>> {
|
||||||
let draft = Config::profiles().await;
|
let draft = Config::profiles().await;
|
||||||
|
let _guard = crate::config::profile_storage::read().await.stringify_err()?;
|
||||||
let data = draft.data_arc();
|
let data = draft.data_arc();
|
||||||
Ok(data)
|
Ok(data)
|
||||||
}
|
}
|
||||||
@@ -156,8 +157,11 @@ pub async fn update_profile(index: std::string::String, option: Option<PrfOption
|
|||||||
pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
||||||
let index: String = index.into();
|
let index: String = index.into();
|
||||||
let profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
|
let profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
|
||||||
|
crate::config::profile_storage::check().stringify_err()?;
|
||||||
|
|
||||||
let profiles = Config::profiles().await;
|
let profiles = Config::profiles().await;
|
||||||
|
let mut storage_guard = None;
|
||||||
|
let slot = &mut storage_guard;
|
||||||
let result = profiles
|
let result = profiles
|
||||||
.with_data_modify::<_, _, _, anyhow::Error>(|mut candidate| async move {
|
.with_data_modify::<_, _, _, anyhow::Error>(|mut candidate| async move {
|
||||||
let original = candidate.clone();
|
let original = candidate.clone();
|
||||||
@@ -176,11 +180,13 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
let current = candidate.current.clone();
|
let current = candidate.current.clone();
|
||||||
|
*slot = Some(crate::config::profile_storage::write().await?);
|
||||||
cleanup_profile_files(plan.files).await;
|
cleanup_profile_files(plan.files).await;
|
||||||
Ok((candidate, Ok((should_update, current, guard))))
|
Ok((candidate, Ok((should_update, current, guard))))
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.with_error_code("PROFILE_DELETE_FAILED")?;
|
.with_error_code("PROFILE_DELETE_FAILED")?;
|
||||||
|
drop(storage_guard);
|
||||||
let (should_update, current, config_update_guard) = match result {
|
let (should_update, current, config_update_guard) = match result {
|
||||||
Ok(result) => result,
|
Ok(result) => result,
|
||||||
Err(outcome) => {
|
Err(outcome) => {
|
||||||
@@ -213,10 +219,9 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
|||||||
|
|
||||||
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
|
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
|
||||||
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
|
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
|
||||||
Config::profiles()
|
commit_current_profile(&Config::profiles().await, Some(prev_profile.clone()))
|
||||||
.await
|
.await
|
||||||
.edit_draft(|d| d.patch_current(Some(prev_profile)));
|
.stringify_err()?;
|
||||||
Config::profiles().await.apply();
|
|
||||||
crate::process::AsyncHandler::spawn(|| async move {
|
crate::process::AsyncHandler::spawn(|| async move {
|
||||||
if let Err(e) = save_committed_profiles().await {
|
if let Err(e) = save_committed_profiles().await {
|
||||||
logging!(warn, Type::Cmd, "异步保存恢复配置文件失败: {e:#}");
|
logging!(warn, Type::Cmd, "异步保存恢复配置文件失败: {e:#}");
|
||||||
@@ -390,6 +395,7 @@ pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<Vali
|
|||||||
CURRENT_SWITCHING_PROFILE.store(false, Ordering::Release);
|
CURRENT_SWITCHING_PROFILE.store(false, Ordering::Release);
|
||||||
});
|
});
|
||||||
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
|
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
|
||||||
|
crate::config::profile_storage::check().stringify_err()?;
|
||||||
|
|
||||||
let target_profile = profiles.current.as_ref();
|
let target_profile = profiles.current.as_ref();
|
||||||
|
|
||||||
@@ -457,6 +463,7 @@ pub async fn patch_profile(index: std::string::String, profile: ProfilePatch) ->
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn view_profile(index: std::string::String) -> CmdResult {
|
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 = Config::profiles().await;
|
||||||
let profiles_ref = profiles.latest_arc();
|
let profiles_ref = profiles.latest_arc();
|
||||||
let file = profiles_ref
|
let file = profiles_ref
|
||||||
@@ -482,6 +489,7 @@ pub async fn view_profile(index: std::string::String) -> CmdResult {
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::string::String> {
|
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 file = {
|
||||||
let profiles = Config::profiles().await;
|
let profiles = Config::profiles().await;
|
||||||
let profiles_ref = profiles.latest_arc();
|
let profiles_ref = profiles.latest_arc();
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use super::CmdResult;
|
|||||||
use crate::{
|
use crate::{
|
||||||
cmd::StringifyErr as _,
|
cmd::StringifyErr as _,
|
||||||
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
|
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
|
||||||
config::{Config, IProfiles, read_profile_item_file},
|
config::{Config, IProfiles, profile_storage, profiles::PROFILE_WRITE_LOCK, read_profile_item_file},
|
||||||
core::auto_backup::{self, AutoBackupTrigger},
|
core::auto_backup::{self, AutoBackupTrigger},
|
||||||
core::{
|
core::{
|
||||||
CoreManager, handle,
|
CoreManager, handle,
|
||||||
@@ -34,6 +34,9 @@ pub async fn save_profile_file(
|
|||||||
_ => None,
|
_ => 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 (rel_path, is_merge_file, is_script_file, affects_runtime) = {
|
||||||
let profiles = Config::profiles().await;
|
let profiles = Config::profiles().await;
|
||||||
@@ -65,12 +68,18 @@ pub async fn save_profile_file(
|
|||||||
|
|
||||||
// 保存新的配置文件
|
// 保存新的配置文件
|
||||||
fs::write(&file_path, &file_data).await.stringify_err()?;
|
fs::write(&file_path, &file_data).await.stringify_err()?;
|
||||||
|
drop(profile_guard);
|
||||||
|
|
||||||
|
let original = OriginalProfileFile {
|
||||||
|
content: &original_content,
|
||||||
|
existed: original_existed,
|
||||||
|
written: &file_data,
|
||||||
|
};
|
||||||
|
|
||||||
let changes_applied = handle_saved_profile_file(
|
let changes_applied = handle_saved_profile_file(
|
||||||
&file_path_str,
|
&file_path_str,
|
||||||
&file_path,
|
&file_path,
|
||||||
&original_content,
|
&original,
|
||||||
original_existed,
|
|
||||||
is_merge_file,
|
is_merge_file,
|
||||||
is_script_file,
|
is_script_file,
|
||||||
affects_runtime,
|
affects_runtime,
|
||||||
@@ -86,13 +95,19 @@ pub async fn save_profile_file(
|
|||||||
Ok(changes_applied)
|
Ok(changes_applied)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn restore_original(
|
struct OriginalProfileFile<'a> {
|
||||||
file_path: &std::path::Path,
|
content: &'a str,
|
||||||
original_content: &str,
|
existed: bool,
|
||||||
original_existed: bool,
|
written: &'a str,
|
||||||
) -> CmdResult<()> {
|
}
|
||||||
if original_existed {
|
|
||||||
fs::write(file_path, original_content).await.stringify_err()
|
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 original.existed {
|
||||||
|
fs::write(file_path, original.content).await.stringify_err()
|
||||||
} else {
|
} else {
|
||||||
fs::remove_file(file_path).await.stringify_err()
|
fs::remove_file(file_path).await.stringify_err()
|
||||||
}
|
}
|
||||||
@@ -122,8 +137,7 @@ fn profile_affects_runtime(profiles: &IProfiles, index: &str) -> bool {
|
|||||||
async fn handle_saved_profile_file(
|
async fn handle_saved_profile_file(
|
||||||
file_path_str: &str,
|
file_path_str: &str,
|
||||||
file_path: &std::path::Path,
|
file_path: &std::path::Path,
|
||||||
original_content: &str,
|
original: &OriginalProfileFile<'_>,
|
||||||
original_existed: bool,
|
|
||||||
is_merge_file: bool,
|
is_merge_file: bool,
|
||||||
is_script_file: bool,
|
is_script_file: bool,
|
||||||
affects_runtime: bool,
|
affects_runtime: bool,
|
||||||
@@ -140,13 +154,13 @@ async fn handle_saved_profile_file(
|
|||||||
Ok(outcome) if outcome.is_valid() => {}
|
Ok(outcome) if outcome.is_valid() => {}
|
||||||
Ok(outcome) => {
|
Ok(outcome) => {
|
||||||
logging!(warn, Type::Config, "[cmd配置save] 文件验证失败: {}", outcome);
|
logging!(warn, Type::Config, "[cmd配置save] 文件验证失败: {}", outcome);
|
||||||
restore_original(file_path, original_content, original_existed).await?;
|
restore_original(file_path, original).await?;
|
||||||
handle_validation_notice(&outcome, target, file_type);
|
handle_validation_notice(&outcome, target, file_type);
|
||||||
return Ok(outcome);
|
return Ok(outcome);
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
logging!(error, Type::Config, "[cmd配置save] 验证过程发生错误: {e:#}");
|
logging!(error, Type::Config, "[cmd配置save] 验证过程发生错误: {e:#}");
|
||||||
restore_original(file_path, original_content, original_existed).await?;
|
restore_original(file_path, original).await?;
|
||||||
return Err(e.to_string().into());
|
return Err(e.to_string().into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -167,13 +181,13 @@ async fn handle_saved_profile_file(
|
|||||||
}
|
}
|
||||||
Ok(outcome) => {
|
Ok(outcome) => {
|
||||||
logging!(warn, Type::Config, "[cmd配置save] 运行时配置应用失败: {}", outcome);
|
logging!(warn, Type::Config, "[cmd配置save] 运行时配置应用失败: {}", outcome);
|
||||||
restore_original(file_path, original_content, original_existed).await?;
|
restore_original(file_path, original).await?;
|
||||||
handle_validation_notice(&outcome, ValidationNoticeTarget::Runtime, "运行时配置");
|
handle_validation_notice(&outcome, ValidationNoticeTarget::Runtime, "运行时配置");
|
||||||
Ok(outcome)
|
Ok(outcome)
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
logging!(error, Type::Config, "[cmd配置save] 运行时配置应用错误: {err:#}");
|
logging!(error, Type::Config, "[cmd配置save] 运行时配置应用错误: {err:#}");
|
||||||
restore_original(file_path, original_content, original_existed).await?;
|
restore_original(file_path, original).await?;
|
||||||
Err(err.to_string().into())
|
Err(err.to_string().into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ use crate::core::notify::NoticeStatus;
|
|||||||
use crate::{
|
use crate::{
|
||||||
config::{
|
config::{
|
||||||
prfitem::{build_merge_profile, build_script_profile},
|
prfitem::{build_merge_profile, build_script_profile},
|
||||||
profiles::{append_to_profile_index, load_profiles, save_profiles},
|
profile_storage,
|
||||||
|
profiles::{append_to_profile_index, load_profiles, save_profiles_unlocked},
|
||||||
runtime::IRuntime,
|
runtime::IRuntime,
|
||||||
},
|
},
|
||||||
constants::{files, timing},
|
constants::{files, timing},
|
||||||
@@ -84,6 +85,7 @@ impl Config {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn init_config_before_window() -> Result<()> {
|
pub async fn init_config_before_window() -> Result<()> {
|
||||||
|
profile_storage::check()?;
|
||||||
Self::ensure_default_profile_items().await?;
|
Self::ensure_default_profile_items().await?;
|
||||||
|
|
||||||
let verge = Self::verge().await.latest_arc();
|
let verge = Self::verge().await.latest_arc();
|
||||||
@@ -245,12 +247,24 @@ impl Config {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn generate() -> Result<()> {
|
pub async fn generate() -> Result<()> {
|
||||||
let profiles = Self::profiles().await.latest_arc();
|
let profiles = Self::profiles().await;
|
||||||
Self::generate_with_profiles(&profiles).await
|
let inputs = {
|
||||||
|
let _guard = profile_storage::read().await?;
|
||||||
|
enhance::collect_render_inputs(&profiles.latest_arc()).await?
|
||||||
|
};
|
||||||
|
Self::generate_from_inputs(inputs).await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn generate_with_profiles(profiles: &IProfiles) -> Result<()> {
|
pub(crate) async fn generate_with_profiles(profiles: &IProfiles) -> Result<()> {
|
||||||
let (mut config, exists_keys, logs, dns_override) = enhance::render_runtime_config(profiles).await?;
|
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;
|
||||||
|
|
||||||
resolve_provider_path_conflicts(&mut config, &dirs::app_home_dir()?)?;
|
resolve_provider_path_conflicts(&mut config, &dirs::app_home_dir()?)?;
|
||||||
sanitize_tunnels_proxy(&mut config);
|
sanitize_tunnels_proxy(&mut config);
|
||||||
@@ -313,8 +327,20 @@ impl Config {
|
|||||||
let save_profiles_task = AsyncHandler::spawn(|| async {
|
let save_profiles_task = AsyncHandler::spawn(|| async {
|
||||||
let _profile_write = super::profiles::PROFILE_WRITE_LOCK.lock().await;
|
let _profile_write = super::profiles::PROFILE_WRITE_LOCK.lock().await;
|
||||||
let profiles = Self::profiles().await;
|
let profiles = Self::profiles().await;
|
||||||
profiles.apply();
|
let mut storage_guard = None;
|
||||||
logging_error!(Type::Config, save_profiles(&profiles.data_arc()).await);
|
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));
|
||||||
});
|
});
|
||||||
|
|
||||||
let _ = tokio::join!(save_clash_task, save_verge_task, save_profiles_task);
|
let _ = tokio::join!(save_clash_task, save_verge_task, save_profiles_task);
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ pub(crate) mod mihomo_yaml;
|
|||||||
mod mixed_port;
|
mod mixed_port;
|
||||||
mod port;
|
mod port;
|
||||||
mod prfitem;
|
mod prfitem;
|
||||||
|
pub(crate) mod profile_storage;
|
||||||
pub mod profiles;
|
pub mod profiles;
|
||||||
pub mod runtime;
|
pub mod runtime;
|
||||||
pub(crate) mod snapshot;
|
pub(crate) mod snapshot;
|
||||||
@@ -14,7 +15,7 @@ mod verge;
|
|||||||
|
|
||||||
pub(crate) use self::config::Config;
|
pub(crate) use self::config::Config;
|
||||||
pub(crate) use self::prfitem::{
|
pub(crate) use self::prfitem::{
|
||||||
build_remote_profile, download_subscription, prepare_remote_refresh, read_profile_item_file, subscription_proxy,
|
build_remote_profile, download_subscription, read_profile_item_file, subscription_proxy,
|
||||||
};
|
};
|
||||||
pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*};
|
pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*};
|
||||||
pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected};
|
pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected};
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
use anyhow::{Result, anyhow};
|
||||||
|
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(String),
|
||||||
|
Restore(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn check() -> Result<()> {
|
||||||
|
match BLOCKED.lock().as_ref() {
|
||||||
|
Some(StorageBlock::Transaction(reason) | StorageBlock::Restore(reason)) => {
|
||||||
|
Err(anyhow!("Profile storage requires recovery before use: {reason}"))
|
||||||
|
}
|
||||||
|
None => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn block(error: &anyhow::Error) {
|
||||||
|
let mut blocked = BLOCKED.lock();
|
||||||
|
if !matches!(*blocked, Some(StorageBlock::Transaction(_))) {
|
||||||
|
*blocked = Some(StorageBlock::Transaction(format!("{error:#}")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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(anyhow!("Profile storage requires recovery before use: {reason}"));
|
||||||
|
}
|
||||||
|
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().inspect_err(block)?;
|
||||||
|
let result: Result<()> = async {
|
||||||
|
if !journal_exists(&root).await? {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
|
||||||
|
return tokio::task::spawn_blocking(move || clash_verge_profile_store::recover_pending(&root))
|
||||||
|
.await?
|
||||||
|
.map_err(Into::into);
|
||||||
|
#[cfg(not(any(unix, all(windows, feature = "profile-store-windows"))))]
|
||||||
|
return Err(anyhow!(
|
||||||
|
"restore the pending profile transaction with redo support enabled"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
if let Err(error) = &result {
|
||||||
|
block(error);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
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")))]
|
||||||
|
return commit_recoverable_refresh(uid, candidate, body).await;
|
||||||
|
#[cfg(not(any(unix, all(windows, feature = "profile-store-windows"))))]
|
||||||
|
{
|
||||||
|
write_legacy_refresh(&uid, &candidate, body.as_bytes()).await?;
|
||||||
|
Ok(candidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
async fn write_legacy_refresh(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 = crate::utils::dirs::app_profiles_dir()?.join(file);
|
||||||
|
tokio::fs::write(path, body)
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("failed to write to file \"{file}\""))?;
|
||||||
|
super::profiles::save_profiles_unlocked(candidate).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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");
|
||||||
|
block(&error);
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
write_legacy_refresh(&uid, &candidate, body.as_bytes()).await?;
|
||||||
|
return Ok(candidate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let result = tokio::task::spawn_blocking(move || {
|
||||||
|
let session = Session::open(&root).map_err(anyhow::Error::from).inspect_err(|error| {
|
||||||
|
match std::fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)) {
|
||||||
|
Err(status) if status.kind() == std::io::ErrorKind::NotFound => {}
|
||||||
|
_ => block(error),
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
let item = candidate.get_item(&uid)?;
|
||||||
|
if let Some(file) = item.file.as_deref()
|
||||||
|
&& !file.contains(['/', '\\', ':', '\0'])
|
||||||
|
&& !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) => {
|
||||||
|
block(&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);
|
||||||
|
block(&error);
|
||||||
|
Err(error.context("failed to discard the incomplete profile refresh"))
|
||||||
|
}
|
||||||
|
CommitOutcome::NeedsRecovery(error) => {
|
||||||
|
let error = anyhow::Error::from(error);
|
||||||
|
block(&error);
|
||||||
|
Err(error.context("profile refresh requires recovery"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
match result {
|
||||||
|
Ok(result) => result,
|
||||||
|
Err(error) => {
|
||||||
|
let error = anyhow::Error::from(error).context("profile storage worker stopped unexpectedly");
|
||||||
|
block(&error);
|
||||||
|
Err(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
use super::{
|
use super::{
|
||||||
PrfItem, PrfOption, PrfSelected, patch_opt_field,
|
PrfItem, PrfOption, PrfSelected, patch_opt_field,
|
||||||
prfitem::{RemoteProfileRefresh, build_profile},
|
prfitem::{DownloadedSubscription, build_profile, prepare_remote_refresh},
|
||||||
|
profile_storage,
|
||||||
};
|
};
|
||||||
use crate::core::notify::{Refresh, announce};
|
use crate::core::notify::{Refresh, announce};
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -70,52 +71,57 @@ pub(crate) async fn cleanup_profile_files(files: Vec<String>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn load_profiles() -> IProfiles {
|
pub(crate) async fn load_profiles() -> IProfiles {
|
||||||
let path = match dirs::profiles_path() {
|
match load_profiles_checked().await {
|
||||||
Ok(p) => p,
|
Ok(profiles) => profiles,
|
||||||
Err(err) => {
|
Err(error) => {
|
||||||
logging!(error, Type::Config, "failed to get profiles path: {err:#}");
|
logging!(error, Type::Config, "failed to load profiles: {error:#}");
|
||||||
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()
|
IProfiles::default()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) 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<()> {
|
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<()> {
|
||||||
help::save_yaml(
|
help::save_yaml(
|
||||||
&dirs::profiles_path()?,
|
&dirs::profiles_path()?,
|
||||||
profiles,
|
profiles,
|
||||||
@@ -177,7 +183,7 @@ async fn patch_item(profiles: &mut IProfiles, uid: &str, item: &PrfItem) -> Resu
|
|||||||
bail!("failed to find the profile item \"uid:{uid}\"")
|
bail!("failed to find the profile item \"uid:{uid}\"")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn validate_profile_file(file: &str) -> Result<()> {
|
pub(crate) fn validate_profile_file(file: &str) -> Result<()> {
|
||||||
let mut components = Path::new(file).components();
|
let mut components = Path::new(file).components();
|
||||||
if file.is_empty()
|
if file.is_empty()
|
||||||
|| file.contains('/')
|
|| file.contains('/')
|
||||||
@@ -261,6 +267,7 @@ 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<()> {
|
pub(super) async fn append_to_profile_index(profiles: &Draft<IProfiles>, item: &mut PrfItem) -> Result<()> {
|
||||||
profiles
|
profiles
|
||||||
.with_data_modify(|mut profiles| async move {
|
.with_data_modify(|mut profiles| async move {
|
||||||
|
let _guard = profile_storage::write().await?;
|
||||||
append_item(&mut profiles, item).await?;
|
append_item(&mut profiles, item).await?;
|
||||||
Ok((profiles, ()))
|
Ok((profiles, ()))
|
||||||
})
|
})
|
||||||
@@ -289,28 +296,68 @@ pub(crate) async fn save_committed_profiles() -> Result<()> {
|
|||||||
with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await
|
with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn save_remote_refresh(uid: &str, url: &str, refresh: RemoteProfileRefresh) -> Result<()> {
|
fn check_refresh_source(current: &PrfItem, url: &str, file: Option<&String>) -> Result<()> {
|
||||||
with_profiles_edit(|mut profiles| async move {
|
anyhow::ensure!(
|
||||||
let profile = profiles.get_item_mut(uid)?;
|
current.itype.as_deref() == Some("remote")
|
||||||
anyhow::ensure!(
|
&& current.url.as_deref() == Some(url)
|
||||||
profile.itype.as_deref() == Some("remote") && profile.url.as_deref() == Some(url),
|
&& current.file.as_ref() == file,
|
||||||
"profile source changed during refresh"
|
"profile source or filename changed during refresh"
|
||||||
);
|
);
|
||||||
profile.extra = refresh.extra;
|
Ok(())
|
||||||
profile.updated = Some(refresh.updated);
|
}
|
||||||
profile.home = refresh.home;
|
|
||||||
profile.option = PrfOption::merge(profile.option.as_ref(), Some(&refresh.option));
|
pub(crate) async fn save_remote_refresh(
|
||||||
let file = profile
|
uid: &str,
|
||||||
.file
|
url: &str,
|
||||||
.get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into());
|
file: Option<String>,
|
||||||
let path = dirs::app_profiles_dir()?.join(file.as_str());
|
downloaded: DownloadedSubscription,
|
||||||
fs::write(&path, refresh.body.as_bytes())
|
options: Option<PrfOption>,
|
||||||
.await
|
) -> Result<()> {
|
||||||
.with_context(|| format!("failed to write to file \"{file}\""))?;
|
let uid = uid.to_owned();
|
||||||
save_profiles(&profiles).await?;
|
let url = url.to_owned();
|
||||||
Ok(profiles)
|
// 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;
|
||||||
|
check_refresh_source(draft.data_arc().get_item(&uid)?, &url, file.as_ref())?;
|
||||||
|
let refresh = prepare_remote_refresh(downloaded, options.as_ref()).await?;
|
||||||
|
let mut storage_guard = None;
|
||||||
|
let mut persisted = false;
|
||||||
|
let result = {
|
||||||
|
let storage_guard = &mut storage_guard;
|
||||||
|
let persisted = &mut persisted;
|
||||||
|
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())?;
|
||||||
|
profile.extra = refresh.extra;
|
||||||
|
profile.updated = Some(refresh.updated);
|
||||||
|
profile.home = refresh.home;
|
||||||
|
profile.option = PrfOption::merge(profile.option.as_ref(), Some(&refresh.option));
|
||||||
|
profile
|
||||||
|
.file
|
||||||
|
.get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into());
|
||||||
|
let candidate = profile_storage::commit_refresh(uid, candidate, refresh.body).await?;
|
||||||
|
*persisted = true;
|
||||||
|
Ok((candidate, ()))
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
};
|
||||||
|
if let Err(error) = &result
|
||||||
|
&& persisted
|
||||||
|
{
|
||||||
|
profile_storage::block(error);
|
||||||
|
return Err(anyhow::anyhow!(
|
||||||
|
"Profile refresh is saved, but its Draft could not be published: {error:#}"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
drop(storage_guard);
|
||||||
|
result?;
|
||||||
|
profile_storage::check().context("Profile refresh was saved")
|
||||||
})
|
})
|
||||||
.await
|
.await?
|
||||||
}
|
}
|
||||||
|
|
||||||
fn selected_group<'a>(snapshot: &'a Proxies, name: &str) -> Option<SelectedGroup<'a>> {
|
fn selected_group<'a>(snapshot: &'a Proxies, name: &str) -> Option<SelectedGroup<'a>> {
|
||||||
|
|||||||
@@ -277,20 +277,22 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
|
|||||||
let file = AsyncHandler::spawn_blocking(move || std::fs::File::create(&value)).await??;
|
let file = AsyncHandler::spawn_blocking(move || std::fs::File::create(&value)).await??;
|
||||||
let mut archive = BackupWriter::new(file)?;
|
let mut archive = BackupWriter::new(file)?;
|
||||||
|
|
||||||
if let Ok(mut entries) = fs::read_dir(dirs::app_profiles_dir()?).await {
|
let profile_guard = crate::config::profile_storage::read().await?;
|
||||||
while let Some(entry) = entries.next_entry().await? {
|
let mut entries = fs::read_dir(dirs::app_profiles_dir()?).await?;
|
||||||
let path = entry.path();
|
while let Some(entry) = entries.next_entry().await? {
|
||||||
if path.is_file() {
|
let path = entry.path();
|
||||||
let file_name_os = entry.file_name();
|
if path.is_file() {
|
||||||
let file_name = file_name_os
|
let file_name_os = entry.file_name();
|
||||||
.to_str()
|
let file_name = file_name_os
|
||||||
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
|
.to_str()
|
||||||
let mut entry = archive.start_profile(file_name)?;
|
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
|
||||||
let file_content = fs::read(&path).await?;
|
let mut entry = archive.start_profile(file_name)?;
|
||||||
entry.write_all(&file_content)?;
|
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
|
archive
|
||||||
.start_file(dirs::CLASH_CONFIG)?
|
.start_file(dirs::CLASH_CONFIG)?
|
||||||
@@ -314,9 +316,7 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
|
|||||||
.write_all(&fs::read(&dns_config_path).await?)?;
|
.write_all(&fs::read(&dns_config_path).await?)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
archive
|
archive.start_file(dirs::PROFILE_YAML)?.write_all(&profile_index)?;
|
||||||
.start_file(dirs::PROFILE_YAML)?
|
|
||||||
.write_all(&fs::read(dirs::profiles_path()?).await?)?;
|
|
||||||
archive.finish()?;
|
archive.finish()?;
|
||||||
Ok((zip_file_name, zip_path))
|
Ok((zip_file_name, zip_path))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -231,6 +231,8 @@ impl CoreManager {
|
|||||||
pub async fn init(&self) -> Result<bool> {
|
pub async fn init(&self) -> Result<bool> {
|
||||||
const MAX_PORT_FALLBACK_RETRIES: usize = 3;
|
const MAX_PORT_FALLBACK_RETRIES: usize = 3;
|
||||||
|
|
||||||
|
crate::config::profile_storage::check()?;
|
||||||
|
|
||||||
if let Some(reason) = crate::config::Config::startup_core_block_reason() {
|
if let Some(reason) = crate::config::Config::startup_core_block_reason() {
|
||||||
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
|
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -246,10 +246,14 @@ async fn read_dns_settings(enabled: bool) -> Option<Mapping> {
|
|||||||
serde_yaml_ng::from_str(&yaml).ok()
|
serde_yaml_ng::from_str(&yaml).ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the enhanced profile, its original keys, script logs, and DNS override decision.
|
pub(crate) struct ProfileRenderInputs {
|
||||||
pub async fn render_runtime_config(
|
profile: RenderProfile,
|
||||||
profiles: &IProfiles,
|
settings: RenderSettings,
|
||||||
) -> Result<(Mapping, HashSet<String>, HashMap<String, ResultLog>, DnsOverrideState)> {
|
dns_config: Option<Mapping>,
|
||||||
|
dns_override: DnsOverrideState,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn collect_render_inputs(profiles: &IProfiles) -> Result<ProfileRenderInputs> {
|
||||||
let profile_uid = profiles.current.as_deref().unwrap_or_default();
|
let profile_uid = profiles.current.as_deref().unwrap_or_default();
|
||||||
let settings = get_config_values(profile_uid).await;
|
let settings = get_config_values(profile_uid).await;
|
||||||
let profile = collect_profile_items(profiles).await?;
|
let profile = collect_profile_items(profiles).await?;
|
||||||
@@ -260,19 +264,30 @@ pub async fn render_runtime_config(
|
|||||||
settings.dns_override_confirmation,
|
settings.dns_override_confirmation,
|
||||||
);
|
);
|
||||||
let dns_config = read_dns_settings(dns_override.enabled).await;
|
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 {
|
let RenderedConfig {
|
||||||
config,
|
config,
|
||||||
exists_keys,
|
exists_keys,
|
||||||
logs,
|
logs,
|
||||||
discarded_keys,
|
discarded_keys,
|
||||||
} = render(
|
} = render(
|
||||||
profile,
|
inputs.profile,
|
||||||
settings.render,
|
inputs.settings,
|
||||||
dns_config,
|
inputs.dns_config,
|
||||||
clash_verge_profile_script::execute,
|
clash_verge_profile_script::execute,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
notify_discarded_keys(discarded_keys);
|
notify_discarded_keys(discarded_keys);
|
||||||
|
(config, exists_keys, logs, inputs.dns_override)
|
||||||
Ok((config, exists_keys, logs, dns_override))
|
|
||||||
}
|
}
|
||||||
|
|||||||
+194
-49
@@ -1,18 +1,29 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
config::{Config, IClashTemp, IVerge, profiles::load_profiles},
|
config::{
|
||||||
|
Config, IClashTemp, IProfiles, IVerge, profile_storage,
|
||||||
|
profiles::{load_profiles_unlocked, validate_profile_file},
|
||||||
|
},
|
||||||
core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
|
core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
|
||||||
process::AsyncHandler,
|
process::AsyncHandler,
|
||||||
utils::{
|
utils::{
|
||||||
dirs::{PathBufExec as _, app_home_dir, local_backup_dir, verge_path},
|
dirs::{
|
||||||
|
PROFILE_YAML, PROFILES_DIR, PathBufExec as _, VERGE_CONFIG, app_home_dir, local_backup_dir, verge_path,
|
||||||
|
},
|
||||||
help,
|
help,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use anyhow::{Result, anyhow};
|
use anyhow::{Context as _, Result, anyhow};
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
|
use clash_verge_backup_archive::ValidatedBackup;
|
||||||
|
use clash_verge_draft::DraftConflict;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
|
use clash_verge_profile_store::RECOVERY_ENTRY_NAMES;
|
||||||
use reqwest_dav::list_cmd::ListFile;
|
use reqwest_dav::list_cmd::ListFile;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use std::path::PathBuf;
|
use std::{
|
||||||
|
fs::File,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
};
|
||||||
use tokio::fs;
|
use tokio::fs;
|
||||||
use tristr::alias::String;
|
use tristr::alias::String;
|
||||||
|
|
||||||
@@ -29,16 +40,36 @@ async fn finalize_restored_verge_config(
|
|||||||
webdav_url: Option<String>,
|
webdav_url: Option<String>,
|
||||||
webdav_username: Option<String>,
|
webdav_username: Option<String>,
|
||||||
webdav_password: Option<String>,
|
webdav_password: Option<String>,
|
||||||
|
archive: ValidatedBackup<File>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let config_write = Config::lock_config_write().await;
|
let config_write = Config::lock_config_write().await;
|
||||||
|
let profiles_draft = Config::profiles().await;
|
||||||
// A broken restored `verge.yaml` is a restore failure, not a reason to load defaults.
|
let mut profile_guard = None;
|
||||||
let mut restored = help::read_yaml::<IVerge>(&verge_path()?).await?;
|
let restored = {
|
||||||
restored.webdav_url = webdav_url;
|
let guard = &mut profile_guard;
|
||||||
restored.webdav_username = webdav_username;
|
let draft = &profiles_draft;
|
||||||
restored.webdav_password = webdav_password;
|
profiles_draft
|
||||||
restored.save_file().await?;
|
.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 = webdav_url;
|
||||||
|
restored.webdav_username = webdav_username;
|
||||||
|
restored.webdav_password = webdav_password;
|
||||||
|
if let Err(error) = restored.save_file().await {
|
||||||
|
profile_storage::block_restore(&error);
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
draft.discard();
|
||||||
|
Ok((profiles, restored))
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.inspect_err(|error: &anyhow::Error| {
|
||||||
|
if error.is::<DraftConflict>() {
|
||||||
|
profile_storage::block_restore(error);
|
||||||
|
}
|
||||||
|
})?
|
||||||
|
};
|
||||||
let restored_clash = IClashTemp::new().await;
|
let restored_clash = IClashTemp::new().await;
|
||||||
let clash_draft = Config::clash().await;
|
let clash_draft = Config::clash().await;
|
||||||
clash_draft.edit_draft(|d| {
|
clash_draft.edit_draft(|d| {
|
||||||
@@ -46,18 +77,15 @@ async fn finalize_restored_verge_config(
|
|||||||
});
|
});
|
||||||
clash_draft.apply();
|
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;
|
let verge_draft = Config::verge().await;
|
||||||
verge_draft.edit_draft(|d| {
|
verge_draft.edit_draft(|d| {
|
||||||
*d = restored.clone();
|
*d = restored.clone();
|
||||||
});
|
});
|
||||||
verge_draft.apply();
|
verge_draft.apply();
|
||||||
|
if let Some(guard) = &profile_guard {
|
||||||
|
profile_storage::finish_restore(guard);
|
||||||
|
}
|
||||||
|
drop(profile_guard);
|
||||||
auto_backup::publish_settings(&verge_draft.data_arc());
|
auto_backup::publish_settings(&verge_draft.data_arc());
|
||||||
|
|
||||||
// Turn it off here; a failing core side effect below would otherwise skip this step.
|
// Turn it off here; a failing core side effect below would otherwise skip this step.
|
||||||
@@ -132,8 +160,85 @@ pub async fn delete_webdav_backup(filename: String) -> Result<()> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn restore_config_path(staged: &Path, home: &Path, name: &str, retry: bool) -> Result<PathBuf> {
|
||||||
|
let path = staged.join(name);
|
||||||
|
if !retry && !fs::try_exists(&path).await? {
|
||||||
|
return Ok(home.join(name));
|
||||||
|
}
|
||||||
|
Ok(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn validate_restore(
|
||||||
|
mut archive: ValidatedBackup<File>,
|
||||||
|
home_dir: &Path,
|
||||||
|
retry: bool,
|
||||||
|
) -> Result<ValidatedBackup<File>> {
|
||||||
|
let staging_root = home_dir.to_owned();
|
||||||
|
let (staged, archive) = AsyncHandler::spawn_blocking(move || -> Result<_> {
|
||||||
|
let staged = tempfile::tempdir_in(staging_root)?;
|
||||||
|
archive.extract_to(staged.path())?;
|
||||||
|
Ok((staged, archive))
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|join| anyhow!("backup staging task failed: {join}"))??;
|
||||||
|
let validated: Result<()> = async {
|
||||||
|
let verge = restore_config_path(staged.path(), home_dir, VERGE_CONFIG, retry).await?;
|
||||||
|
let profiles_path = restore_config_path(staged.path(), home_dir, PROFILE_YAML, retry).await?;
|
||||||
|
help::read_yaml::<IVerge>(&verge).await?;
|
||||||
|
let profiles: IProfiles = help::read_yaml(&profiles_path).await?;
|
||||||
|
if retry {
|
||||||
|
let bodies = staged.path().join(PROFILES_DIR);
|
||||||
|
for file in profiles.items.iter().flatten().filter_map(|item| item.file.as_deref()) {
|
||||||
|
validate_profile_file(file)?;
|
||||||
|
let body = fs::symlink_metadata(bodies.join(file))
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("failed to inspect recovery backup profile body {file}"))?;
|
||||||
|
anyhow::ensure!(body.is_file(), "recovery backup profile body {file} is not a file");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
AsyncHandler::spawn_blocking(move || drop(staged)).await?;
|
||||||
|
validated?;
|
||||||
|
Ok(archive)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn restore_files(archive: ValidatedBackup<File>, retry: bool) -> Result<(IProfiles, IVerge)> {
|
||||||
|
let home_dir = app_home_dir()?;
|
||||||
|
let mut archive = validate_restore(archive, &home_dir, retry).await?;
|
||||||
|
AsyncHandler::spawn_blocking(move || -> Result<()> {
|
||||||
|
let extracted = archive.extract_to(&home_dir).map_err(anyhow::Error::from);
|
||||||
|
if let Err(error) = &extracted {
|
||||||
|
profile_storage::block_restore(error);
|
||||||
|
}
|
||||||
|
extracted
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|join| {
|
||||||
|
let error = anyhow!("backup extraction task failed: {join}");
|
||||||
|
profile_storage::block_restore(&error);
|
||||||
|
error
|
||||||
|
})??;
|
||||||
|
let loaded = async {
|
||||||
|
let verge = help::read_yaml::<IVerge>(&verge_path()?).await?;
|
||||||
|
let profiles = load_profiles_unlocked().await?;
|
||||||
|
Ok((profiles, verge))
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
if let Err(error) = &loaded {
|
||||||
|
profile_storage::block_restore(error);
|
||||||
|
}
|
||||||
|
loaded
|
||||||
|
}
|
||||||
|
|
||||||
/// Backup creation strips the WebDAV credentials, so the live ones are kept.
|
/// Backup creation strips the WebDAV credentials, so the live ones are kept.
|
||||||
async fn restore_backup_archive(path: PathBuf) -> Result<()> {
|
async fn restore_backup_archive(path: PathBuf) -> Result<()> {
|
||||||
|
let archive = AsyncHandler::spawn_blocking(move || -> Result<_> {
|
||||||
|
Ok(ValidatedBackup::open(File::open(path)?, RECOVERY_ENTRY_NAMES)?)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|join| anyhow!("backup preflight task failed: {join}"))??;
|
||||||
let (webdav_url, webdav_username, webdav_password) = {
|
let (webdav_url, webdav_username, webdav_password) = {
|
||||||
let verge = Config::verge().await;
|
let verge = Config::verge().await;
|
||||||
let verge = verge.latest_arc();
|
let verge = verge.latest_arc();
|
||||||
@@ -144,41 +249,35 @@ async fn restore_backup_archive(path: PathBuf) -> Result<()> {
|
|||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
let home_dir = app_home_dir()?;
|
tokio::spawn(async move {
|
||||||
AsyncHandler::spawn_blocking(move || -> Result<()> {
|
let _profile_write = crate::config::profiles::PROFILE_WRITE_LOCK.lock().await;
|
||||||
let file = std::fs::File::open(&path)?;
|
finalize_restored_verge_config(webdav_url, webdav_username, webdav_password, archive).await
|
||||||
let mut zip = zip::ZipArchive::new(file)?;
|
|
||||||
zip.extract(&home_dir)?;
|
|
||||||
Ok(())
|
|
||||||
})
|
})
|
||||||
.await
|
.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))]
|
#[tracing::instrument(skip_all, level = "info", fields(filename = %filename))]
|
||||||
pub async fn restore_webdav_backup(filename: String) -> Result<()> {
|
pub async fn restore_webdav_backup(filename: String) -> Result<()> {
|
||||||
let backup_storage_path = app_home_dir()
|
tokio::spawn(async move {
|
||||||
.map_err(|e| anyhow::anyhow!("Failed to get app home dir: {e}"))?
|
let archive_dir = tempfile::tempdir()?;
|
||||||
.join(filename.as_str());
|
let archive = archive_dir.path().join("backup.zip");
|
||||||
let name = filename.clone();
|
let name = filename.clone();
|
||||||
backup::WebDavClient::global()
|
backup::WebDavClient::global()
|
||||||
.download(filename, backup_storage_path.clone())
|
.download(filename, archive.clone())
|
||||||
.await
|
.await
|
||||||
.map_err(|err| {
|
.map_err(|err| {
|
||||||
logging!(
|
logging!(
|
||||||
error,
|
error,
|
||||||
Type::Backup,
|
Type::Backup,
|
||||||
"Failed to download WebDAV backup file {name}: {err:#}"
|
"Failed to download WebDAV backup file {name}: {err:#}"
|
||||||
);
|
);
|
||||||
err
|
err
|
||||||
})?;
|
})?;
|
||||||
|
let result = restore_backup_archive(archive).await;
|
||||||
let res = restore_backup_archive(backup_storage_path.clone()).await;
|
drop(archive_dir);
|
||||||
let _ = backup_storage_path.remove_if_exists().await;
|
result
|
||||||
res
|
})
|
||||||
|
.await?
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn create_local_backup() -> Result<()> {
|
pub async fn create_local_backup() -> Result<()> {
|
||||||
@@ -365,3 +464,49 @@ pub async fn export_local_backup(filename: String, destination: String) -> Resul
|
|||||||
.map_err(|err| anyhow!("Failed to export backup file: {err:#}"))?;
|
.map_err(|err| anyhow!("Failed to export backup file: {err:#}"))?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use clash_verge_backup_archive::BackupWriter;
|
||||||
|
use std::io::Write as _;
|
||||||
|
|
||||||
|
#[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(ValidatedBackup::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()
|
||||||
|
);
|
||||||
|
validate_restore(open_backup(Some(index), true)?, home.path(), true).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -34,10 +34,13 @@ pub async fn set_dns_override(
|
|||||||
profiles.current.as_ref() == Some(&profile_uid),
|
profiles.current.as_ref() == Some(&profile_uid),
|
||||||
"The active profile changed; retry the DNS setting"
|
"The active profile changed; retry the DNS setting"
|
||||||
);
|
);
|
||||||
let source = dns_override_source(
|
let source = {
|
||||||
profiles.current.as_deref().unwrap_or_default(),
|
let _guard = crate::config::profile_storage::read().await?;
|
||||||
¤t_mapping(&profiles).await?,
|
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()) {
|
if enabled && let Some(source) = source.as_ref().filter(|source| Some(*source) != confirmation.as_ref()) {
|
||||||
return Ok(DnsOverrideOutcome::ConfirmationRequired { source: source.clone() });
|
return Ok(DnsOverrideOutcome::ConfirmationRequired { source: source.clone() });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
config::{
|
config::{
|
||||||
Config, PrfOption, download_subscription, prepare_remote_refresh, profiles::save_remote_refresh,
|
Config, PrfOption, download_subscription, profile_storage, profiles::save_remote_refresh, subscription_proxy,
|
||||||
subscription_proxy,
|
|
||||||
},
|
},
|
||||||
core::{
|
core::{
|
||||||
CoreManager, handle,
|
CoreManager, handle,
|
||||||
@@ -17,8 +16,15 @@ use anyhow::{Result, bail};
|
|||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use tristr::alias::String;
|
use tristr::alias::String;
|
||||||
|
|
||||||
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
|
struct RefreshSource {
|
||||||
|
url: String,
|
||||||
|
file: Option<String>,
|
||||||
|
option: Option<PrfOption>,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<RefreshSource>> {
|
||||||
let profiles = Config::profiles().await;
|
let profiles = Config::profiles().await;
|
||||||
|
let _guard = profile_storage::read().await?;
|
||||||
let profiles = profiles.latest_arc();
|
let profiles = profiles.latest_arc();
|
||||||
let item = profiles.get_item(uid)?;
|
let item = profiles.get_item(uid)?;
|
||||||
let is_remote = item.itype.as_ref().is_some_and(|s| s == "remote");
|
let is_remote = item.itype.as_ref().is_some_and(|s| s == "remote");
|
||||||
@@ -43,24 +49,25 @@ async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Op
|
|||||||
.ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?
|
.ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
Ok(Some((
|
Ok(Some(RefreshSource {
|
||||||
item.url.clone().ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?,
|
url: item.url.clone().ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?,
|
||||||
item.option.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))]
|
#[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(
|
async fn perform_profile_update(
|
||||||
uid: &str,
|
uid: &str,
|
||||||
url: &str,
|
source: &RefreshSource,
|
||||||
profile_options: Option<&PrfOption>,
|
|
||||||
overrides: Option<&PrfOption>,
|
overrides: Option<&PrfOption>,
|
||||||
is_manual_trigger: bool,
|
is_manual_trigger: bool,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let options = PrfOption::merge(profile_options, overrides);
|
let url = source.url.as_str();
|
||||||
let options = options.as_ref();
|
let options = PrfOption::merge(source.option.as_ref(), overrides);
|
||||||
let configured_proxy = subscription_proxy(options);
|
let download_options = options.as_ref();
|
||||||
|
let configured_proxy = subscription_proxy(download_options);
|
||||||
let profiles = Config::profiles().await;
|
let profiles = Config::profiles().await;
|
||||||
let profiles_arc = profiles.latest_arc();
|
let profiles_arc = profiles.latest_arc();
|
||||||
let profile_name = profiles_arc
|
let profile_name = profiles_arc
|
||||||
@@ -105,7 +112,7 @@ async fn perform_profile_update(
|
|||||||
};
|
};
|
||||||
tracing::Span::current().record("strategy", name);
|
tracing::Span::current().record("strategy", name);
|
||||||
let started = std::time::Instant::now();
|
let started = std::time::Instant::now();
|
||||||
let result = download_subscription(url, options, proxy).await;
|
let result = download_subscription(url, download_options, proxy).await;
|
||||||
tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed()));
|
tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed()));
|
||||||
match &result {
|
match &result {
|
||||||
Ok(_) => logging!(info, Type::Config, "{success}"),
|
Ok(_) => logging!(info, Type::Config, "{success}"),
|
||||||
@@ -123,15 +130,7 @@ async fn perform_profile_update(
|
|||||||
let last_err = match result {
|
let last_err = match result {
|
||||||
Ok((strategy, downloaded)) => {
|
Ok((strategy, downloaded)) => {
|
||||||
// A persistence error must not replay a successful download with another transport.
|
// A persistence error must not replay a successful download with another transport.
|
||||||
let profiles = Config::profiles().await;
|
save_remote_refresh(uid, url, source.file.clone(), downloaded, options).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) {
|
if !matches!(strategy, Strategy::Configured) {
|
||||||
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str());
|
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str());
|
||||||
}
|
}
|
||||||
@@ -155,8 +154,8 @@ pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_tri
|
|||||||
let subscription = should_update_profile(uid, is_manual_trigger).await?;
|
let subscription = should_update_profile(uid, is_manual_trigger).await?;
|
||||||
|
|
||||||
let profile_persisted = match subscription {
|
let profile_persisted = match subscription {
|
||||||
Some((url, profile_options)) => {
|
Some(source) => {
|
||||||
perform_profile_update(uid, &url, profile_options.as_ref(), option, is_manual_trigger).await?;
|
perform_profile_update(uid, &source, option, is_manual_trigger).await?;
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
None => false,
|
None => false,
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ pub static BACKUP_DIR: &str = "clash-verge-rev-backup-dev";
|
|||||||
pub static CLASH_CONFIG: &str = "config.yaml";
|
pub static CLASH_CONFIG: &str = "config.yaml";
|
||||||
pub static VERGE_CONFIG: &str = "verge.yaml";
|
pub static VERGE_CONFIG: &str = "verge.yaml";
|
||||||
pub static PROFILE_YAML: &str = "profiles.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.
|
/// Marks that the one-shot raise of too-short auto-update intervals has already run.
|
||||||
pub static UPDATE_INTERVAL_MIGRATED: &str = ".update-interval-migrated";
|
pub static UPDATE_INTERVAL_MIGRATED: &str = ".update-interval-migrated";
|
||||||
|
|
||||||
@@ -48,7 +49,7 @@ pub fn app_resources_dir() -> Result<PathBuf> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn app_profiles_dir() -> Result<PathBuf> {
|
pub fn app_profiles_dir() -> Result<PathBuf> {
|
||||||
Ok(app_home_dir()?.join("profiles"))
|
Ok(app_home_dir()?.join(PROFILES_DIR))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn app_icons_dir() -> Result<PathBuf> {
|
pub fn app_icons_dir() -> Result<PathBuf> {
|
||||||
|
|||||||
@@ -470,7 +470,8 @@ async fn initialize_config_files() -> Result<()> {
|
|||||||
logging!(info, Type::Setup, "Created verge config at {:?}", path);
|
logging!(info, Type::Setup, "Created verge config at {:?}", path);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Ok(path) = dirs::profiles_path()
|
if crate::config::profile_storage::check().is_ok()
|
||||||
|
&& let Ok(path) = dirs::profiles_path()
|
||||||
&& !path.exists()
|
&& !path.exists()
|
||||||
{
|
{
|
||||||
let template = IProfiles::default();
|
let template = IProfiles::default();
|
||||||
@@ -489,6 +490,10 @@ async fn initialize_config_files() -> Result<()> {
|
|||||||
|
|
||||||
/// Initializes configuration required before Tauri setup.
|
/// Initializes configuration required before Tauri setup.
|
||||||
pub async fn init_config() -> Result<()> {
|
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")]
|
#[cfg(target_os = "macos")]
|
||||||
migrate_legacy_macos_logs().await?;
|
migrate_legacy_macos_logs().await?;
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user