chore(runtime): sync the profile refactor

This commit is contained in:
Tunglies
2026-12-03 19:42:46 +08:00
54 changed files with 2276 additions and 1670 deletions
@@ -4,10 +4,4 @@ pub enum ArchiveError {
Zip(#[from] zip::result::ZipError),
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("backup contains a symbolic link")]
Symlink,
#[error("backup contains an invalid path")]
InvalidPath,
#[error("archive contains profile recovery data")]
ReservedEntry,
}
+6 -45
View File
@@ -2,11 +2,8 @@ mod error;
pub use error::ArchiveError;
use std::{
io::{self, Read, Seek, Write},
path::{Component, Path},
};
use zip::{CompressionMethod, ZipArchive, ZipWriter, write::SimpleFileOptions};
use std::io::{Seek, Write};
use zip::{CompressionMethod, ZipWriter, write::SimpleFileOptions};
pub struct BackupWriter<W: Write + Seek> {
zip: ZipWriter<W>,
@@ -35,55 +32,20 @@ impl<W: Write + Seek> BackupWriter<W> {
}
}
pub struct ValidatedBackup<R: Read + Seek> {
zip: ZipArchive<R>,
}
impl<R: Read + Seek> ValidatedBackup<R> {
pub fn open(source: R, reserved_names: &[&str]) -> Result<Self, ArchiveError> {
let mut zip = ZipArchive::new(source)?;
for index in 0..zip.len() {
let mut entry = zip.by_index(index)?;
if entry.is_symlink() {
return Err(ArchiveError::Symlink);
}
let path = entry.enclosed_name().ok_or(ArchiveError::InvalidPath)?;
for component in path.components() {
let Component::Normal(name) = component else {
continue;
};
let name = name.to_string_lossy();
if reserved_names
.iter()
.any(|reserved| name.eq_ignore_ascii_case(reserved))
{
return Err(ArchiveError::ReservedEntry);
}
}
io::copy(&mut entry, &mut io::sink())?;
}
Ok(Self { zip })
}
pub fn extract_to(mut self, destination: &Path) -> Result<(), ArchiveError> {
self.zip.extract(destination)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
use std::io::{Cursor, Read as _};
use zip::ZipArchive;
#[test]
fn writes_and_validates_the_backup_layout() -> Result<(), ArchiveError> {
fn writes_the_backup_layout() -> Result<(), ArchiveError> {
let mut writer = BackupWriter::new(Cursor::new(Vec::new()))?;
writer.start_profile("example.yaml")?.write_all(b"proxies: []\n")?;
writer.start_file("profiles.yaml")?.write_all(b"items: []\n")?;
let source = writer.finish()?;
let mut zip = ZipArchive::new(source.clone())?;
let mut zip = ZipArchive::new(source)?;
assert_eq!(zip.len(), 3);
assert_eq!(zip.by_index(0)?.name()?, "profiles/");
let profile_time = {
@@ -98,7 +60,6 @@ mod tests {
let index = zip.by_index(2)?;
assert_eq!(index.name()?, "profiles.yaml");
assert_eq!(index.last_modified(), profile_time);
ValidatedBackup::open(source, &[".profile-refresh", ".profile-refresh.lock"])?;
Ok(())
}
}
+57 -4
View File
@@ -1,7 +1,14 @@
use std::sync::Arc;
use std::{
pin::pin,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
task::{Context, Poll, Wake, Waker},
};
use clash_verge_draft::{Draft, DraftBusy, DraftConflict, DraftTransaction};
use tokio::sync::Notify;
use tokio::sync::{Notify, oneshot};
#[derive(Clone, Debug, Default, PartialEq)]
struct Config {
@@ -83,6 +90,47 @@ async fn async_update_rejects_a_changed_committed_value() -> Result<(), Box<dyn
Ok(())
}
#[test]
fn parked_async_update_is_woken_after_optimistic_conflict() {
#[derive(Default)]
struct WakeFlag(AtomicBool);
impl Wake for WakeFlag {
fn wake(self: Arc<Self>) {
self.0.store(true, Ordering::Relaxed);
}
}
let draft = Draft::new(1);
let (finish, finished) = oneshot::channel();
let mut owner = pin!(draft.with_data_modify(|value| async move {
finished.await.expect("owner completion signal");
Ok::<_, DraftConflict>((value + 10, ()))
}));
let mut owner_context = Context::from_waker(Waker::noop());
assert!(owner.as_mut().poll(&mut owner_context).is_pending());
let wake_flag = Arc::new(WakeFlag::default());
let waker = Waker::from(Arc::clone(&wake_flag));
let mut waiter_context = Context::from_waker(&waker);
let mut waiter = pin!(draft.with_data_modify(|value| async move { Ok::<_, DraftConflict>((value + 1, value)) }));
// The fast retry wakes once before the waiter parks on Notify.
assert!(waiter.as_mut().poll(&mut waiter_context).is_pending());
assert!(wake_flag.0.swap(false, Ordering::Relaxed), "fast retry did not wake");
assert!(waiter.as_mut().poll(&mut waiter_context).is_pending());
assert!(!wake_flag.0.load(Ordering::Relaxed), "waiter did not park");
draft.edit_draft(|value| *value = 7);
draft.apply();
assert!(finish.send(()).is_ok());
assert!(matches!(owner.as_mut().poll(&mut owner_context), Poll::Ready(Err(_))));
assert_eq!(**draft.data_arc(), 7);
assert!(wake_flag.0.load(Ordering::Relaxed), "parked waiter was not notified");
assert!(matches!(waiter.as_mut().poll(&mut waiter_context), Poll::Ready(Ok(7))));
assert_eq!(**draft.data_arc(), 8);
}
#[test]
fn transaction_commits_every_layer() -> Result<(), DraftBusy> {
let first = Draft::new(1_u8);
@@ -117,10 +165,15 @@ fn dropped_transaction_rolls_every_layer_back() -> Result<(), DraftBusy> {
#[test]
fn transaction_claims_are_exclusive_and_release_partial_claims() -> Result<(), DraftBusy> {
let first = Draft::new(1_u8);
let second = Draft::new(2_u8);
let second = Draft::new(2_u16);
let held = DraftTransaction::begin(vec![&second])?;
assert!(DraftTransaction::begin(vec![&first, &second]).is_err());
let busy = DraftTransaction::begin(vec![&first, &second])
.err()
.expect("transaction claimed an already-held layer");
let layer = std::any::type_name::<u16>();
assert_eq!(busy.layer, layer);
assert!(busy.to_string().contains(layer));
let available = DraftTransaction::begin(vec![&first])?;
drop(available);
+8 -5
View File
@@ -23,17 +23,20 @@ fn resolve_supported_language(language: &str) -> Option<Cow<'static, str>> {
return None;
}
let normalized = language.to_lowercase().replace('_', "-");
let segments: Vec<&str> = normalized.split('-').collect();
for i in (1..=segments.len()).rev() {
let prefix = segments[..i].join("-");
if let Some(alias) = locale_alias(&prefix)
let mut prefix = normalized.as_str();
loop {
if let Some(alias) = locale_alias(prefix)
&& let Some(found) = SUPPORTED_LOCALES.iter().find(|l| l.eq_ignore_ascii_case(alias))
{
return Some(found.clone());
}
if let Some(found) = SUPPORTED_LOCALES.iter().find(|l| l.eq_ignore_ascii_case(&prefix)) {
if let Some(found) = SUPPORTED_LOCALES.iter().find(|l| l.eq_ignore_ascii_case(prefix)) {
return Some(found.clone());
}
let Some((shorter, _)) = prefix.rsplit_once('-') else {
break;
};
prefix = shorter;
}
None
}
+6
View File
@@ -5,5 +5,11 @@ edition = "2024"
[dependencies]
[dev-dependencies]
proptest = { workspace = true }
[target.'cfg(loom)'.dependencies]
loom = { workspace = true }
[lints]
workspace = true
+43 -6
View File
@@ -1,5 +1,12 @@
#[cfg(loom)]
use loom::sync::Arc;
#[cfg(loom)]
use loom::sync::atomic::AtomicU64;
#[cfg(not(loom))]
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(not(loom))]
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub type SystemLimiter = Limiter<SystemClock>;
@@ -38,6 +45,7 @@ pub struct Limiter<C: Clock = SystemClock> {
}
impl<C: Clock> Limiter<C> {
#[cfg(not(loom))]
pub const fn new(period: Duration, clock: C) -> Self {
Self {
last_run_ms: AtomicU64::new(0),
@@ -46,11 +54,21 @@ impl<C: Clock> Limiter<C> {
}
}
pub fn check(&self) -> bool {
let now = self.clock.now_ms();
let last = self.last_run_ms.load(Ordering::Relaxed);
#[cfg(loom)]
pub fn new(period: Duration, clock: C) -> Self {
Self {
last_run_ms: AtomicU64::new(0),
period_ms: period.as_millis() as u64,
clock,
}
}
if now < last + self.period_ms && now >= last {
pub fn check(&self) -> bool {
// Load before sampling so a stale sample cannot move a newer admission backward.
let last = self.last_run_ms.load(Ordering::Relaxed);
let now = self.clock.now_ms();
if now >= last && now - last < self.period_ms {
return false;
}
@@ -74,6 +92,22 @@ mod tests {
}
}
#[test]
fn system_clock_reports_unix_epoch_milliseconds() {
const MAX_DRIFT_MS: u64 = 5 * 60 * 1_000;
let wall_clock_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
let clock_ms = SystemClock.now_ms();
assert!(
clock_ms.abs_diff(wall_clock_ms) <= MAX_DRIFT_MS,
"SystemClock::now_ms() should return Unix epoch milliseconds, got {clock_ms} while wall clock is {wall_clock_ms}"
);
}
#[test]
fn enforces_the_period_boundary() {
let clock = MockClock(AtomicU64::new(1_000));
@@ -100,7 +134,10 @@ mod tests {
}
let admitted = handles
.into_iter()
.map(|handle| handle.join().unwrap_or(false))
.map(|handle| match handle.join() {
Ok(admitted) => admitted,
Err(panic) => std::panic::resume_unwind(panic),
})
.filter(|passed| *passed)
.count();
+225
View File
@@ -0,0 +1,225 @@
#![cfg(loom)]
use std::sync::atomic::Ordering;
use std::time::Duration;
use clash_verge_limiter::{Clock, Limiter};
use loom::sync::Arc;
use loom::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize};
const PERIOD_MS: u64 = 100;
const START_MS: u64 = 1_000;
struct MockClock(AtomicU64);
impl Clock for MockClock {
fn now_ms(&self) -> u64 {
self.0.load(Ordering::SeqCst)
}
}
type TestLimiter = Limiter<Arc<MockClock>>;
struct AdvancingClock(AtomicU64);
impl Clock for AdvancingClock {
fn now_ms(&self) -> u64 {
self.0.fetch_add(1, Ordering::SeqCst)
}
}
fn limiter_at(now_ms: u64) -> (Arc<MockClock>, Arc<TestLimiter>) {
let clock = Arc::new(MockClock(AtomicU64::new(now_ms)));
let limiter = Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock));
(clock, Arc::new(limiter))
}
fn run_two_concurrent_checks<C: Clock + 'static>(limiter: &Arc<Limiter<C>>) -> usize {
let handles: [_; 2] = std::array::from_fn(|_| {
let limiter = Arc::clone(limiter);
loom::thread::spawn(move || limiter.check())
});
handles
.into_iter()
.map(|handle| match handle.join() {
Ok(admitted) => admitted,
Err(panic) => std::panic::resume_unwind(panic),
})
.filter(|admitted| *admitted)
.count()
}
#[test]
fn admits_exactly_one_caller_in_an_eligible_window() {
loom::model(|| {
let (_clock, limiter) = limiter_at(START_MS);
assert_eq!(run_two_concurrent_checks(&limiter), 1);
});
}
#[test]
fn rejects_concurrent_callers_inside_the_restricted_period() {
loom::model(|| {
let (clock, limiter) = limiter_at(START_MS);
assert!(limiter.check());
clock.0.store(START_MS + PERIOD_MS - 1, Ordering::SeqCst);
assert_eq!(run_two_concurrent_checks(&limiter), 0);
});
}
#[test]
fn admits_exactly_one_caller_at_the_period_boundary() {
loom::model(|| {
let (clock, limiter) = limiter_at(START_MS);
assert!(limiter.check());
clock.0.store(START_MS + PERIOD_MS, Ordering::SeqCst);
assert_eq!(run_two_concurrent_checks(&limiter), 1);
});
}
#[test]
fn concurrent_clock_advancement_admits_exactly_one_caller() {
loom::model(|| {
let clock = Arc::new(AdvancingClock(AtomicU64::new(START_MS)));
let limiter = Arc::new(Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock)));
assert_eq!(run_two_concurrent_checks(&limiter), 1);
});
}
struct StaleClock {
current: AtomicU64,
reads: AtomicUsize,
stale_reads: usize,
sampled: AtomicUsize,
released: AtomicBool,
}
impl StaleClock {
fn new(now_ms: u64, stale_reads: usize) -> Self {
Self {
current: AtomicU64::new(now_ms),
reads: AtomicUsize::new(0),
stale_reads,
sampled: AtomicUsize::new(0),
released: AtomicBool::new(false),
}
}
fn release(&self) {
self.released.store(true, Ordering::SeqCst);
}
}
impl Clock for StaleClock {
fn now_ms(&self) -> u64 {
if self.reads.fetch_add(1, Ordering::SeqCst) < self.stale_reads {
let stale = self.current.load(Ordering::SeqCst);
self.sampled.fetch_add(1, Ordering::SeqCst);
// Parking can wake spuriously; re-check the release flag on each
// wake. Unparking after setting the flag avoids a lost wakeup.
while !self.released.load(Ordering::SeqCst) {
loom::thread::park();
}
stale
} else {
self.current.load(Ordering::SeqCst)
}
}
}
/// Regression: a caller that sampled the clock before a newer admission must
/// not overwrite that admission when it resumes.
#[test]
fn stale_clock_sample_does_not_reopen_the_period() {
loom::model(|| {
const LATER_MS: u64 = START_MS + PERIOD_MS * 10;
let clock = Arc::new(StaleClock::new(START_MS, 1));
let limiter = Arc::new(Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock)));
let stale_caller = {
let limiter = Arc::clone(&limiter);
loom::thread::spawn(move || limiter.check())
};
while clock.sampled.load(Ordering::SeqCst) < 1 {
loom::thread::yield_now();
}
clock.current.store(LATER_MS, Ordering::SeqCst);
let later_caller = {
let limiter = Arc::clone(&limiter);
loom::thread::spawn(move || limiter.check())
};
let later_admitted = later_caller.join().unwrap();
assert!(
later_admitted,
"the later caller must be admitted before the stale caller resumes"
);
clock.release();
stale_caller.thread().unpark();
let stale_admitted = stale_caller.join().unwrap();
let reopened = limiter.check();
assert!(
!stale_admitted,
"stale caller must not be admitted after the later caller"
);
assert!(
!reopened,
"stale caller admitted={stale_admitted} moved last_run_ms from {LATER_MS} back to {START_MS}"
);
});
}
#[test]
fn multiple_stale_clock_samples_cannot_reopen_the_period() {
loom::model(|| {
const LATER_MS: u64 = START_MS + PERIOD_MS * 10;
let clock = Arc::new(StaleClock::new(START_MS, 2));
let limiter = Arc::new(Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock)));
let stale_callers: [_; 2] = std::array::from_fn(|_| {
let limiter = Arc::clone(&limiter);
loom::thread::spawn(move || limiter.check())
});
while clock.sampled.load(Ordering::SeqCst) < 2 {
loom::thread::yield_now();
}
clock.current.store(LATER_MS, Ordering::SeqCst);
assert!(
limiter.check(),
"the later caller must be admitted before the stale callers resume"
);
clock.release();
for caller in &stale_callers {
caller.thread().unpark();
}
let stale_admitted = stale_callers
.into_iter()
.map(|caller| caller.join().unwrap())
.filter(|admitted| *admitted)
.count();
assert_eq!(
stale_admitted, 0,
"stale callers must not be admitted after the later caller"
);
assert!(!limiter.check(), "stale callers reopened the period at {LATER_MS}");
});
}
@@ -0,0 +1,7 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc 0139d921e3faaf32821ee0c596b0d495ffc72ce94200b8d5a795883db56305e6 # shrinks to period = 56, start = 18446744073709551560
@@ -0,0 +1,211 @@
#![cfg(not(loom))]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use clash_verge_limiter::{Clock, Limiter};
use proptest::prelude::*;
use proptest::test_runner::FileFailurePersistence;
const CASES: u32 = 10_000;
const MAX_PERIOD_MS: u64 = 100_000;
const MAX_START_MS: u64 = 1_000_000;
const MAX_DELTA_MS: u64 = 10_000;
/// Returns one clock value per call, in order. The test supplies exactly as
/// many values as the limiter will read.
struct SequenceClock {
values: Vec<u64>,
next: AtomicUsize,
}
impl SequenceClock {
const fn new(values: Vec<u64>) -> Self {
Self {
values,
next: AtomicUsize::new(0),
}
}
}
impl Clock for SequenceClock {
fn now_ms(&self) -> u64 {
let index = self.next.fetch_add(1, Ordering::SeqCst);
self.values[index]
}
}
fn timestamps(start: u64, deltas: &[u64]) -> Vec<u64> {
let mut now = start;
let mut values = Vec::with_capacity(deltas.len() + 1);
values.push(now);
for delta in deltas {
now += delta;
values.push(now);
}
values
}
proptest! {
#![proptest_config(ProptestConfig {
cases: CASES,
failure_persistence: Some(Box::new(FileFailurePersistence::Direct(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/properties.proptest-regressions"
)))),
..ProptestConfig::default()
})]
/// For positive periods and nondecreasing time, admission is equivalent to
/// reaching the next allowed timestamp after the previous admission.
#[test]
fn sequential_results_match_the_next_allowed_time_contract(
period in 1u64..=MAX_PERIOD_MS,
start in MAX_PERIOD_MS..=MAX_START_MS,
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
) {
let times = timestamps(start, &deltas);
let clock = SequenceClock::new(times.clone());
let limiter = Limiter::new(Duration::from_millis(period), &clock);
let mut last_admitted = None;
for now in times {
let expected = match last_admitted {
None => true,
Some(last) => now >= last + period,
};
let actual = limiter.check();
prop_assert!(
actual == expected,
"period={} now={} last={:?}",
period,
now,
last_admitted
);
if actual {
last_admitted = Some(now);
}
}
}
/// An admission at the period boundary is accepted, while a repeated or
/// pre-boundary check is rejected.
#[test]
fn period_boundary_and_repeated_checks_follow_the_period(
period in 1u64..=MAX_PERIOD_MS,
start in MAX_PERIOD_MS..=MAX_START_MS,
) {
let boundary = start + period;
let clock = SequenceClock::new(vec![start, start, boundary - 1, boundary]);
let limiter = Limiter::new(Duration::from_millis(period), &clock);
prop_assert!(limiter.check(), "first check at {}", start);
prop_assert!(!limiter.check(), "repeated check at {}", start);
prop_assert!(!limiter.check(), "pre-boundary check at {}", boundary - 1);
prop_assert!(limiter.check(), "boundary check at {}", boundary);
}
/// Any two admitted timestamps in a monotonic sequence are separated by at
/// least one configured period.
#[test]
fn admitted_timestamps_are_at_least_one_period_apart(
period in 1u64..=MAX_PERIOD_MS,
start in MAX_PERIOD_MS..=MAX_START_MS,
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
) {
let times = timestamps(start, &deltas);
let clock = SequenceClock::new(times.clone());
let limiter = Limiter::new(Duration::from_millis(period), &clock);
let mut admitted = Vec::new();
for now in times {
if limiter.check() {
admitted.push(now);
}
}
for pair in admitted.windows(2) {
prop_assert!(
pair[1] - pair[0] >= period,
"period={} admitted pair={:?}",
period,
pair
);
}
}
/// A rejected duplicate at the current admission timestamp must not change
/// the outcomes of later checks.
#[test]
fn rejected_checks_do_not_change_future_admissions(
period in 1u64..=MAX_PERIOD_MS,
start in MAX_PERIOD_MS..=MAX_START_MS,
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
) {
let base_times = timestamps(start, &deltas);
let base_clock = SequenceClock::new(base_times.clone());
let base = Limiter::new(Duration::from_millis(period), &base_clock);
let base_results: Vec<bool> = base_times.iter().map(|_| base.check()).collect();
let mut repeated_times = vec![start, start];
repeated_times.extend_from_slice(&base_times[1..]);
let repeated_len = repeated_times.len();
let repeated_clock = SequenceClock::new(repeated_times);
let repeated = Limiter::new(Duration::from_millis(period), &repeated_clock);
let repeated_results: Vec<bool> = (0..repeated_len).map(|_| repeated.check()).collect();
prop_assert!(repeated_results[0]);
prop_assert!(!repeated_results[1]);
prop_assert_eq!(&base_results[1..], &repeated_results[2..]);
}
/// Every sub-millisecond period is represented as zero milliseconds, so it
/// must produce the same admissions as `Duration::ZERO`. This deliberately
/// does not assert a policy for zero periods.
#[test]
fn zero_and_submillisecond_periods_are_equivalent(
nanos in 0u64..1_000_000,
start in 0u64..=MAX_START_MS,
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
) {
let times = timestamps(start, &deltas);
let zero_clock = SequenceClock::new(times.clone());
let zero = Limiter::new(Duration::ZERO, &zero_clock);
let submillisecond_clock = SequenceClock::new(times.clone());
let submillisecond =
Limiter::new(Duration::from_nanos(nanos), &submillisecond_clock);
for now in times {
prop_assert_eq!(
zero.check(),
submillisecond.check(),
"nanos={} now={}",
nanos,
now
);
}
}
/// Regression: timestamp arithmetic must not overflow near `u64::MAX`.
#[test]
fn extreme_timestamp_and_period_do_not_overflow(
period in 1u64..=1_000,
start in (u64::MAX - 1_000)..=u64::MAX,
) {
let clock = SequenceClock::new(vec![start, start]);
let limiter = Limiter::new(Duration::from_millis(period), &clock);
prop_assert!(limiter.check());
prop_assert!(!limiter.check());
}
}
#[test]
fn max_timestamp_boundary_does_not_overflow() {
let clock = SequenceClock::new(vec![u64::MAX - 1, u64::MAX, u64::MAX]);
let limiter = Limiter::new(Duration::from_millis(1), &clock);
assert!(limiter.check());
assert!(limiter.check());
assert!(!limiter.check());
}
+35 -48
View File
@@ -20,7 +20,6 @@ macro_rules! patch_opt_field {
#[serde(default)]
pub struct PrfItem {
pub uid: Option<String>,
/// enum value: remote | local | script | merge
#[serde(rename = "type")]
pub itype: Option<String>,
@@ -157,21 +156,20 @@ impl IProfiles {
}
pub fn get_item(&self, uid: impl AsRef<str>) -> Result<&PrfItem, ProfileNotFound> {
let uid_str = uid.as_ref();
let uid = uid.as_ref();
self.items
.iter()
.flatten()
.find(|item| item.uid.as_deref() == Some(uid))
.ok_or_else(|| ProfileNotFound { uid: uid.to_owned() })
}
if let Some(items) = self.items.as_ref() {
for each in items.iter() {
if let Some(uid_val) = &each.uid
&& uid_val.as_str() == uid_str
{
return Ok(each);
}
}
}
Err(ProfileNotFound {
uid: uid_str.to_owned(),
})
pub fn get_item_mut(&mut self, uid: &str) -> Result<&mut PrfItem, ProfileNotFound> {
self.items
.iter_mut()
.flatten()
.find(|item| item.uid.as_deref() == Some(uid))
.ok_or_else(|| ProfileNotFound { uid: uid.to_owned() })
}
/// Inserts a prepared entry after any required body write.
@@ -200,41 +198,30 @@ impl IProfiles {
pub fn plan_delete_item(&mut self, uid: &str) -> Result<ProfileDeletePlan, ProfileNotFound> {
let deleting_current = self.current.as_deref().is_none_or(|current| current == uid);
let delete_uids = self.get_item(uid)?.option.as_ref().map_or_else(Vec::new, |op| {
[
op.merge.clone(),
op.script.clone(),
op.rules.clone(),
op.proxies.clone(),
op.groups.clone(),
]
.into_iter()
.collect::<Vec<_>>()
});
let mut items = self.items.take().unwrap_or_default();
let mut files = Vec::new();
if let Some(file) = take_item_file_by_uid(&mut items, Some(uid)) {
files.push(file);
}
for delete_uid in delete_uids {
if let Some(file) = take_item_file_by_uid(&mut items, delete_uid.as_deref()) {
files.push(file);
}
}
if deleting_current {
self.current = None;
for item in items.iter() {
if matches!(item.itype.as_deref(), Some("remote" | "local")) {
self.current = item.uid.clone();
break;
let missing_profile = || ProfileNotFound { uid: uid.to_owned() };
let items = self.items.as_mut().ok_or_else(missing_profile)?;
let profile = remove_item(items, Some(uid)).ok_or_else(missing_profile)?;
let mut files = Vec::from_iter(profile.file);
if let Some(options) = profile.option {
for companion_uid in [
options.merge,
options.script,
options.rules,
options.proxies,
options.groups,
] {
if let Some(file) = remove_item(items, companion_uid.as_deref()).and_then(|item| item.file) {
files.push(file);
}
}
}
self.items = Some(items);
if deleting_current {
self.current = items
.iter()
.find(|item| matches!(item.itype.as_deref(), Some("remote" | "local")))
.and_then(|item| item.uid.clone());
}
Ok(ProfileDeletePlan {
deleting_current,
files,
@@ -259,9 +246,9 @@ impl IProfiles {
}
}
fn take_item_file_by_uid(items: &mut Vec<PrfItem>, target_uid: Option<&str>) -> Option<String> {
fn remove_item(items: &mut Vec<PrfItem>, target_uid: Option<&str>) -> Option<PrfItem> {
let index = items.iter().position(|item| item.uid.as_deref() == target_uid)?;
items.remove(index).file
Some(items.remove(index))
}
#[cfg(test)]
@@ -28,7 +28,7 @@ impl SubscriptionSchedule {
let full = Self::interval_duration(interval_minutes);
let elapsed = updated
.filter(|updated| *updated > 0)
.map_or(0, |updated| now.saturating_sub(updated as i64).max(0) as u64);
.map_or(0, |updated| (now.max(0) as u64).saturating_sub(updated as u64));
Self {
interval_minutes,
@@ -13,7 +13,11 @@ pub fn decode_subscription_link(link: &Url) -> Option<SubscriptionLink<'_>> {
}
// The embedded URL can contain unescaped query separators of its own.
let raw_url = link.query()?.split_once("url=")?.1.trim();
let query = link.query()?;
let raw_url = query
.strip_prefix("url=")
.or_else(|| query.split_once("&url=").map(|(_, url)| url))?
.trim();
let name = link.query_pairs().find(|(key, _)| key == "name").map(|(_, name)| name);
Some(SubscriptionLink {
url: decode_subscription_url(raw_url),
@@ -22,10 +26,16 @@ pub fn decode_subscription_link(link: &Url) -> Option<SubscriptionLink<'_>> {
}
fn decode_subscription_url(raw_url: &str) -> Cow<'_, str> {
let mut candidate = Cow::Borrowed(raw_url);
if Url::parse(raw_url).is_ok() {
return candidate;
return Cow::Borrowed(raw_url);
}
// Only the outer name has meaning here. Partly encoded URLs can still contain literal path and query delimiters.
let mut candidate = Cow::Borrowed(
raw_url
.split_once("&name=")
.filter(|(value, _)| !value.contains(['/', '?', '&']))
.map_or(raw_url, |(value, _)| value),
);
for _ in 0..2 {
let decoded = percent_decode_str(&candidate).decode_utf8_lossy();
@@ -51,7 +61,22 @@ mod tests {
assert_eq!(link.name.as_deref(), Some("Work VPN"));
assert!(matches!(link.url, Cow::Borrowed("https://example.invalid/sub?a=1&b=2")));
let encoded = Url::parse("clash-verge://install-config?url=https%253A%252F%252Fexample.invalid%252Fsub")?;
let partial = Url::parse("clash://install-config?url=https%3A%2F%2Fexample.invalid/a&b/file?token=abc")?;
assert_eq!(
decode_subscription_link(&partial).expect("partially encoded link").url,
"https://example.invalid/a&b/file?token=abc"
);
let missing = Url::parse("clash://install-config?name=myurl=notes")?;
assert!(decode_subscription_link(&missing).is_none());
let named = Url::parse("clash://install-config?name=myurl=notes&url=https://example.invalid/work")?;
assert_eq!(
decode_subscription_link(&named).expect("named link").url,
"https://example.invalid/work"
);
let encoded =
Url::parse("clash-verge://install-config?url=https%253A%252F%252Fexample.invalid%252Fsub&name=Work")?;
let link = decode_subscription_link(&encoded).expect("double-encoded subscription link");
assert_eq!(link.url, "https://example.invalid/sub");
Ok(())
+70 -19
View File
@@ -69,26 +69,10 @@ pub fn decode_subscription<'a>(
}
fn subscription_filename(url: &Url, headers: &HeaderMap) -> Option<String> {
if let Some(value) = headers.get("content-disposition") {
let disposition = format!("{value:?}");
let disposition = disposition.trim_matches('"');
if let Some(encoded) = find_field(disposition, "filename*", Some)
&& let Ok(decoded) = percent_decode_str(encoded).decode_utf8()
&& let Some(filename) = decoded.split("''").last()
&& !filename.trim().is_empty()
{
return Some(filename.to_owned());
}
if let Some(filename) = find_field(disposition, "filename", Some).map(|name| name.trim_matches('"'))
&& !filename.trim().is_empty()
{
return Some(filename.to_owned());
}
if let Some(filename) = headers.get("content-disposition").and_then(disposition_filename) {
return Some(filename);
}
let url = url.as_str();
let path = url.split_once('?').map_or(url, |(path, _)| path);
let filename = path.rsplit_once('/').map_or(path, |(_, filename)| filename);
let filename = url.path().rsplit('/').next()?;
let filename = percent_decode_str(filename).decode_utf8_lossy();
if filename.trim().is_empty() {
return None;
@@ -96,6 +80,57 @@ fn subscription_filename(url: &Url, headers: &HeaderMap) -> Option<String> {
Some(filename.into_owned())
}
fn disposition_filename(header: &http::HeaderValue) -> Option<String> {
let mut quoted = false;
let mut escaped = false;
let fields = header.as_bytes().split(|&byte| {
if escaped {
escaped = false;
} else if quoted && byte == b'\\' {
escaped = true;
} else if byte == b'"' {
quoted = !quoted;
} else if !quoted && byte == b';' {
return true;
}
false
});
let mut plain = None;
for field in fields {
let Some((key, value)) = std::str::from_utf8(field).ok().and_then(|s| s.split_once('=')) else {
continue;
};
let value = value.trim();
if key.trim().eq_ignore_ascii_case("filename*") {
let encoded = value.splitn(3, '\'').nth(2).unwrap_or(value);
if let Ok(name) = percent_decode_str(encoded).decode_utf8()
&& !name.trim().is_empty()
{
return Some(name.into_owned());
}
} else if plain.is_none() && key.trim().eq_ignore_ascii_case("filename") {
let name = unquote_filename(value);
if !name.trim().is_empty() {
plain = Some(name);
}
}
}
plain
}
fn unquote_filename(value: &str) -> String {
let Some(inner) = value.strip_prefix('"').and_then(|s| s.strip_suffix('"')) else {
return value.to_owned();
};
let mut chars = inner.chars();
let mut name = String::with_capacity(inner.len());
while let Some(ch) = chars.next() {
name.push(if ch == '\\' { chars.next().unwrap_or(ch) } else { ch });
}
name
}
pub fn normalize_profile_home_url(raw: &str) -> Option<String> {
let url = Url::parse(raw.trim()).ok()?;
@@ -179,6 +214,22 @@ mod tests {
Ok(())
}
#[test]
fn reads_filename_parameters_before_falling_back_to_the_url_path() -> Result<(), Box<dyn std::error::Error>> {
let url = Url::parse("https://example.invalid/sub.yaml#my/notes")?;
for (disposition, expected) in [
(r#"attachment; FileName="My; \"Work\".yaml""#, r#"My; "Work".yaml"#),
("attachment; filename*=UTF-8'en'Work%27%27s.yaml", "Work''s.yaml"),
("attachment", "sub.yaml"),
] {
let mut headers = HeaderMap::new();
headers.insert("content-disposition", HeaderValue::from_static(disposition));
let document = decode_subscription(&url, &headers, "proxies: []")?;
assert_eq!(document.filename.as_deref(), Some(expected));
}
Ok(())
}
#[test]
fn ignores_overflowing_server_interval() -> Result<(), Box<dyn std::error::Error>> {
let url = Url::parse("https://example.com/My%20Profile.yaml?token=value")?;
@@ -12,7 +12,7 @@ parking_lot = { workspace = true }
serde = { workspace = true, features = ["derive"] }
# sysinfo 0.38.2 conflicts with dark-light
# see https://github.com/GuillaumeGomez/sysinfo/issues/1623
sysinfo = { version = "0.40.4", default-features = false, features = ["network", "system"] }
sysinfo = { version = "0.40.5", default-features = false, features = ["network", "system"] }
[target.'cfg(not(windows))'.dependencies]
libc = "0.2.191"