mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-06 23:00:15 +08:00
refactor(config): move DNS and tunnel rules into clash-verge-config-render
override_source, needs_public_dns and sanitize_tunnels_proxy are pure rules over a rendered Mapping; the app keeps the DNS override state, IPC and file access.
This commit is contained in:
@@ -86,7 +86,6 @@ flate2 = "1.1.11"
|
||||
reqwest_dav = "0.4.0"
|
||||
aes-gcm = { version = "0.11.1" }
|
||||
base64 = "0.23.1"
|
||||
sha2 = { workspace = true }
|
||||
getrandom = "0.4.3"
|
||||
futures = { workspace = true }
|
||||
gethostname = "1.1.0"
|
||||
|
||||
@@ -20,11 +20,11 @@ use crate::{
|
||||
};
|
||||
use anyhow::{Result, anyhow};
|
||||
use backon::{ExponentialBuilder, Retryable as _};
|
||||
use clash_verge_config_render::sanitize_tunnels_proxy;
|
||||
use clash_verge_draft::Draft;
|
||||
use clash_verge_logging::{Type, logging, logging_error};
|
||||
use clash_verge_runtime_bundle::resolve_provider_path_conflicts;
|
||||
use serde_yaml_ng::{Mapping, Value};
|
||||
use std::{collections::HashSet, path::PathBuf};
|
||||
use std::path::PathBuf;
|
||||
use tokio::sync::{Mutex, MutexGuard, OnceCell};
|
||||
use tokio::time::sleep;
|
||||
use tristr::alias::String;
|
||||
@@ -321,66 +321,3 @@ impl Config {
|
||||
logging!(info, Type::Config, "save all draft data finished");
|
||||
}
|
||||
}
|
||||
|
||||
fn sanitize_tunnels_proxy(config: &mut Mapping) {
|
||||
if !config
|
||||
.get("tunnels")
|
||||
.and_then(|v| v.as_sequence())
|
||||
.is_some_and(|t| tunnels_need_validation(t))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let mut valid: HashSet<String> = HashSet::with_capacity(64);
|
||||
collect_names(config, "proxies", &mut valid);
|
||||
collect_names(config, "proxy-groups", &mut valid);
|
||||
|
||||
valid.insert("DIRECT".into());
|
||||
valid.insert("REJECT".into());
|
||||
|
||||
let Some(tunnels) = config.get_mut("tunnels").and_then(|v| v.as_sequence_mut()) else {
|
||||
return;
|
||||
};
|
||||
|
||||
for item in tunnels {
|
||||
let Some(tunnel) = item.as_mapping_mut() else { continue };
|
||||
|
||||
let Some(proxy_name) = tunnel.get("proxy").and_then(|v| v.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if proxy_name == "DIRECT" || proxy_name == "REJECT" {
|
||||
continue;
|
||||
}
|
||||
|
||||
if !valid.contains(proxy_name) {
|
||||
tunnel.remove("proxy");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn tunnels_need_validation(tunnels: &[Value]) -> bool {
|
||||
tunnels.iter().any(|item| {
|
||||
item.as_mapping()
|
||||
.and_then(|t| t.get("proxy"))
|
||||
.and_then(|p| p.as_str())
|
||||
.is_some_and(|name| name != "DIRECT" && name != "REJECT")
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_names(config: &Mapping, list_key: &str, out: &mut HashSet<String>) {
|
||||
let Some(Value::Sequence(seq)) = config.get(list_key) else {
|
||||
return;
|
||||
};
|
||||
|
||||
for item in seq {
|
||||
let Value::Mapping(map) = item else {
|
||||
continue;
|
||||
};
|
||||
if let Some(Value::String(n)) = map.get("name")
|
||||
&& !n.is_empty()
|
||||
{
|
||||
out.insert(n.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
use crate::core::notify::NoticeStatus;
|
||||
use crate::utils::help;
|
||||
use anyhow::Result;
|
||||
use clash_verge_draft::DraftTransaction;
|
||||
use clash_verge_logging::{Type, logging, logging_error};
|
||||
use clash_verge_task::scheduled_task::{self, CoalescingJob};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml_ng::{Mapping, Value};
|
||||
use sha2::{Digest as _, Sha256};
|
||||
use std::sync::{
|
||||
LazyLock,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
@@ -22,42 +19,6 @@ pub(crate) fn take_dns_override_notice() -> bool {
|
||||
PENDING_DNS_OVERRIDE_NOTICE.swap(false, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
const PROVIDER_DNS_FIELDS: [&str; 3] = [
|
||||
"proxy-server-nameserver",
|
||||
"proxy-server-nameserver-policy",
|
||||
"nameserver-policy",
|
||||
];
|
||||
|
||||
pub(crate) fn dns_override_source(profile_uid: &str, config: &Mapping) -> Result<Option<String>> {
|
||||
let Some(dns) = config.get("dns").and_then(Value::as_mapping) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let fields: Mapping = PROVIDER_DNS_FIELDS
|
||||
.iter()
|
||||
.filter_map(|key| {
|
||||
let value = dns.get(*key)?;
|
||||
let nonempty = match value {
|
||||
Value::Sequence(values) => !values.is_empty(),
|
||||
Value::Mapping(values) => !values.is_empty(),
|
||||
Value::String(value) => !value.trim().is_empty(),
|
||||
_ => false,
|
||||
};
|
||||
nonempty.then(|| (Value::from(*key), value.clone()))
|
||||
})
|
||||
.collect();
|
||||
if fields.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut canonical = serde_json::to_value(fields)?;
|
||||
canonical.sort_all_objects();
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(profile_uid.as_bytes());
|
||||
digest.update([0]);
|
||||
digest.update(serde_json::to_vec(&canonical)?);
|
||||
Ok(Some(help::hex_encode(&digest.finalize()).into()))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct DnsOverrideState {
|
||||
profile_uid: String,
|
||||
@@ -167,46 +128,27 @@ impl Config {
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
|
||||
mod tests {
|
||||
use super::{DnsOverrideState, ProfileDnsSettings, dns_override_source};
|
||||
use super::{DnsOverrideState, ProfileDnsSettings};
|
||||
use crate::config::IVerge;
|
||||
use anyhow::Result;
|
||||
use clash_verge_config_render::override_source;
|
||||
use serde_yaml_ng::Mapping;
|
||||
|
||||
fn mapping(yaml: &str) -> Mapping {
|
||||
serde_yaml_ng::from_str(yaml).expect("valid fixture")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dns_override_detects_each_original_field_but_not_empty_placeholders() -> Result<()> {
|
||||
for field in [
|
||||
"proxy-server-nameserver: [https://doh.pub/dns-query]",
|
||||
"proxy-server-nameserver-policy: {'www.yournode.com': '114.114.114.114'}",
|
||||
"nameserver-policy: {'+.quandao.com': ['https://doh.dohcore.com:2096/dns-query/#skip-cert-verify=true']}",
|
||||
] {
|
||||
assert!(dns_override_source("profile", &mapping(&format!("dns: {{{field}}}")))?.is_some());
|
||||
assert!(dns_override_source("profile", &mapping(field))?.is_none());
|
||||
}
|
||||
for yaml in [
|
||||
"{}",
|
||||
"dns: {nameserver: [1.1.1.1]}",
|
||||
"dns: {proxy-server-nameserver: [], proxy-server-nameserver-policy: null, nameserver-policy: {}}",
|
||||
] {
|
||||
assert!(dns_override_source("profile", &mapping(yaml))?.is_none());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dns_override_confirmation_survives_formatting_but_not_a_different_source() -> Result<()> {
|
||||
let original = mapping("dns: {nameserver-policy: {a.example: 1.1.1.1, b.example: [8.8.8.8]}}");
|
||||
let source = dns_override_source("one", &original)?;
|
||||
let source = override_source("one", &original)?;
|
||||
let reordered =
|
||||
mapping("dns:\n nameserver-policy:\n b.example: [8.8.8.8]\n a.example: 1.1.1.1\nport: 7890");
|
||||
assert_eq!(source, dns_override_source("one", &reordered)?);
|
||||
assert_eq!(source, override_source("one", &reordered)?);
|
||||
assert!(DnsOverrideState::new("one", source.clone(), true, source.clone()).enabled);
|
||||
assert!(!DnsOverrideState::new("two", dns_override_source("two", &original)?, true, source.clone()).enabled);
|
||||
assert!(!DnsOverrideState::new("two", override_source("two", &original)?, true, source.clone()).enabled);
|
||||
let changed = mapping("dns: {nameserver-policy: {a.example: 9.9.9.9, b.example: [8.8.8.8]}}");
|
||||
assert!(!DnsOverrideState::new("one", dns_override_source("one", &changed)?, true, source).enabled);
|
||||
assert!(!DnsOverrideState::new("one", override_source("one", &changed)?, true, source).enabled);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
mod chain;
|
||||
|
||||
use self::chain::load_chain_item;
|
||||
use crate::config::dns::{DnsOverrideState, dns_override_source};
|
||||
use crate::config::dns::DnsOverrideState;
|
||||
use crate::core::handle::Handle;
|
||||
use crate::core::notify::NoticeStatus;
|
||||
use crate::utils::dirs;
|
||||
@@ -12,7 +12,7 @@ use crate::{
|
||||
};
|
||||
use anyhow::{Context as _, Result};
|
||||
use clash_verge_config_render::{
|
||||
ChainItem, ChainType, RenderProfile, RenderSettings, RenderedConfig, ResultLog, SeqMap, render,
|
||||
ChainItem, ChainType, RenderProfile, RenderSettings, RenderedConfig, ResultLog, SeqMap, override_source, render,
|
||||
};
|
||||
use parking_lot::Mutex;
|
||||
use serde_yaml_ng::Mapping;
|
||||
@@ -253,7 +253,7 @@ pub async fn render_runtime_config(
|
||||
let profile = collect_profile_items(profiles).await?;
|
||||
let dns_override = DnsOverrideState::new(
|
||||
profile_uid,
|
||||
dns_override_source(profile_uid, &profile.config)?,
|
||||
override_source(profile_uid, &profile.config)?,
|
||||
settings.enable_dns_settings,
|
||||
settings.dns_override_confirmation,
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::core::notify::{Refresh, announce};
|
||||
use anyhow::{Result, ensure};
|
||||
use clash_verge_config_render::override_source;
|
||||
use clash_verge_draft::DraftTransaction;
|
||||
use serde::Serialize;
|
||||
use tristr::alias::String;
|
||||
@@ -7,7 +8,7 @@ use tristr::alias::String;
|
||||
use crate::{
|
||||
config::{
|
||||
Config,
|
||||
dns::{ProfileDnsSettings, dns_override_source},
|
||||
dns::ProfileDnsSettings,
|
||||
profiles::{PROFILE_WRITE_LOCK, current_mapping},
|
||||
},
|
||||
constants::files::DNS_CONFIG,
|
||||
@@ -34,7 +35,7 @@ pub async fn set_dns_override(
|
||||
profiles.current.as_ref() == Some(&profile_uid),
|
||||
"The active profile changed; retry the DNS setting"
|
||||
);
|
||||
let source = dns_override_source(
|
||||
let source = override_source(
|
||||
profiles.current.as_deref().unwrap_or_default(),
|
||||
¤t_mapping(&profiles).await?,
|
||||
)?;
|
||||
|
||||
@@ -143,16 +143,6 @@ pub fn get_uid(prefix: &str) -> String {
|
||||
format!("{prefix}{id}")
|
||||
}
|
||||
|
||||
pub fn hex_encode(bytes: &[u8]) -> String {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let mut out = String::with_capacity(bytes.len() * 2);
|
||||
for &byte in bytes {
|
||||
out.push(HEX[usize::from(byte >> 4)] as char);
|
||||
out.push(HEX[usize::from(byte & 0x0f)] as char);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Masks query values and token-like path segments for logging.
|
||||
pub fn mask_url(url: &str) -> String {
|
||||
let (path_part, query_part) = match url.find('?') {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use anyhow::{Context as _, bail, ensure};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use serde_yaml_ng::{Mapping, Value};
|
||||
use std::{
|
||||
io::Read as _,
|
||||
os::unix::process::CommandExt as _,
|
||||
@@ -24,23 +23,6 @@ fn dns_state_dir() -> anyhow::Result<PathBuf> {
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
// Without the placeholder, a LAN resolver is reached outside TUN and fake-ip is bypassed.
|
||||
fn needs_public_dns(config: &Mapping) -> bool {
|
||||
let section = |name: &str| config.get(name).and_then(Value::as_mapping);
|
||||
let enabled = |name: &str| {
|
||||
section(name)
|
||||
.and_then(|map| map.get("enable"))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
};
|
||||
enabled("tun")
|
||||
&& enabled("dns")
|
||||
&& section("dns")
|
||||
.and_then(|dns| dns.get("enhanced-mode"))
|
||||
.and_then(Value::as_str)
|
||||
== Some("fake-ip")
|
||||
}
|
||||
|
||||
/// Sets the placeholder DNS while the running config needs it, and restores the system DNS otherwise.
|
||||
#[allow(
|
||||
clippy::significant_drop_tightening,
|
||||
@@ -59,7 +41,12 @@ pub async fn sync_public_dns() {
|
||||
}
|
||||
let core_running = !matches!(*CoreManager::global().get_running_mode(), RunningMode::NotRunning);
|
||||
let runtime = Config::runtime().await.latest_arc();
|
||||
if core_running && runtime.config.as_ref().is_some_and(needs_public_dns) {
|
||||
if core_running
|
||||
&& runtime
|
||||
.config
|
||||
.as_ref()
|
||||
.is_some_and(clash_verge_config_render::needs_public_dns)
|
||||
{
|
||||
set_public_dns(guard).await;
|
||||
} else {
|
||||
let _ = unset_public_dns(guard).await;
|
||||
|
||||
Reference in New Issue
Block a user