Files
clash-verge-rev/src-tauri/src/utils/network.rs
T
Tunglies 9a904af3aa refactor: backend cleanup (#8436)
* refactor(utils): drop dead reset helper and tidy init_resources

- remove resolve_reset_async, which had no callers
- drop the duplicated time.*.com entry from the default fake-ip-filter
- init_resources no longer recreates app_home (ensure_directories during
  init_config already created it) and now propagates res_dir creation errors

* refactor(profile): remove identical blind retry when switching node

The second select_node_for_group call in switch_proxy_node was a
zero-interval retry with identical arguments. Its success path was a
degraded copy of the first (missing the Refresh::Proxies announcement
ever since the old force-refresh emit was removed), and its distinct
"回退/最终失败" log wording misled maintainers. Keep a single call,
the primary success aftermath, and one error log.

* refactor(enhance): simplify tun mode check and lowercase helpers

- Drop the always-true second clause in use_tun's enhanced-mode check:
  the key is absent only when the unwrap_or default already makes
  current_mode == "fake-ip" true.
- Collapse use_lowercase into a delegation to use_lowercase_owned.

* refactor(core): drop unreachable hotkey dtor and dedupe tray predicate

Remove impl Drop for Hotkey: the instance lives in a OnceLock static via
the singleton! macro and is never dropped; exit-time unregistration is
already handled by Hotkey::reset().

Spell the include_proxy_groups/display-mode predicate identically at
both evaluation sites in tray menu building; behavior is unchanged
(Option != Some("disable") is equivalent to unwrap_or("default") != "disable").

* refactor(config): fold port guards into single helper

The five IClashTemp port guards duplicated the same read/parse/default
logic with drifting defaults: some hardcoded 7895/7898/7899 while others
referenced network::ports constants. Route them all through one
guard_port_value helper and use the constants everywhere, keeping each
guard's name, key and cfg attributes.

* refactor(config): dedupe prfitem factories and companion seeding

from_rules/from_proxies/from_groups differed only in uid prefix, type
string and template, so they now delegate to a shared from_seq_item.
The five current_* accessors collapse into a local macro. The identical
five-block companion seeding in from_local and from_url moves into
ensure_companion_items, preserving seeding order and error propagation.

* refactor(config): share patch macro and profiles helpers

IVerge::patch_config, IProfiles::patch_item and PrfOption::merge each
hand-rolled the same copy-Some-overwrite pattern; they now share one
patch_opt_field macro (the or-else merge form is field-for-field
equivalent for Option fields). The four profiles *_safe wrappers that
inlined Config::profiles().with_data_modify boilerplate delegate to a
with_profiles_edit helper, and record/forget_selected_node share the
current-item lookup prelude via current_item_mut.

* refactor(enhance): merge chain processing and drop unused builtin js payload

- collapse the identical process_global_items/process_profile_items into
  one parameterized process_override_items (entry uid sources unchanged)
- fold the identical rules/proxies/groups arms of ChainItem::from_async
  into a single arm with an inner dispatch
- stop embedding builtin JS payloads never executed by any path: the
  enhance loop dispatches builtin items by uid to native implementations,
  so ChainItem::builtin now carries empty script data (uids unchanged)
- source ProfileItems fallback literals from Default instead of a second
  hand-written copy in collect_profile_items

* refactor(net): reuse webpki tls config and fallback

Extract build_webpki_rooted_tls_config so the delay-test TLS connector
and the reqwest clients share one static-webpki-roots builder; ALPN
stays caller-specific (only reqwest offers h2).

Collapse the duplicated platform-verifier -> static-webpki-roots retry
in get/get_bytes into request_with_static_webpki_fallback, gated by the
caller's certificate-verification setting.

* refactor(app): extract common exit cleanup

restart_app and quit duplicate the whole exit preparation: set the
exiting flag, persist configs, run interactive cleanup, and on a failed
core stop clear the flag, restore public DNS under the lifecycle lock
on macOS, and send the stop-failed notice.

Move that flow into run_exit_cleanup_flow next to clean_async, taking
the notice variant as a parameter and returning the CleanupResult so
each caller keeps its own tail: restart aborts before shutdown, quit
always shuts down and exits with the cleanup code.

* refactor(backup): share restore finalize path

restore_webdav_backup and restore_local_backup duplicated the
credential extraction (backup creation strips the WebDAV credentials,
so both re-inject the live ones), the archive extraction and the
finalize tail. Move that tail into a private restore_backup_archive
helper so the two entries keep only their download/locate logic; the
config-write lock scope and the off-runtime extraction land in one
place. The webdav entry keeps its downloaded-file cleanup.

* refactor(sysopt): drop redundant lock and busy-wait

The proxy target pair sat behind an Arc<RwLock> with no readers and an
Arc that was never cloned; both writers already serialize on
update_lock, so store the pair inside that mutex and delete the RwLock.

refresh_guard waited for the guard to become ready with a yield_now spin
at full CPU while holding guard_operation_lock; a 10 ms sleep keeps the
same wait condition and lock scope without the spin.

* refactor(sysopt): share macos bypass formatting

The macOS default bypass list and its three-way composition (empty ->
default, default + custom, custom only) were maintained twice: in
sysopt's format_bypass and inline in proxy_control's service_bypass.
Keep the literal once in constants and compose both paths through
format_bypass; service_bypass keeps its NUL check and UTF-8 truncation.

* refactor(core): dedupe window listeners, elevated runners, backup settings

- Collapse the close/focus window listener pairs in lightweight.rs onto a shared WindowListener with per-listener event and log label.
- Extract the windows runas-or-direct execution into service::run_maybe_elevated, shared by win_uwp and the service uninstaller, and factor the common uninstaller path resolution and status check shared across platforms.
- Make the auto-backup watch channel the single settings source, replacing the duplicate Arc<RwLock> copy with a stored receiver.

* refactor(enhance): fold lowercase helpers into single owned function

use_lowercase_owned disappears; the surviving use_lowercase takes the
owned Mapping and borrowed callers clone at the call site.

* refactor(enhance): rename ChainSupport variants to Mihomo names

Clash is a legacy name; the variants match the verge-mihomo and
verge-mihomo-alpha cores they gate.

* refactor(enhance): lowercase takes a reference and chain support is copy

use_lowercase borrows the mapping and clones only the values; call
sites no longer clone whole configs. ChainSupport is a fieldless enum
and now Copy; builtin() registers each support pair without clones.

* refactor(config): name prfitem constructor for what it builds

new_seq_item states that a fresh item is built from a template; the
from_ prefix wrongly implied an existing source. append_companion_item
returns the uid directly: append_item bails on a missing uid, so the
Option was always Some on the Ok path.

* refactor(sysopt): name the proxy state lock for its full role

The lock now owns the (Sysproxy, Autoproxy) state, so proxy_state_lock
says what it guards; the guard locals follow. constants::proxy held a
single sysproxy constant and is renamed sysproxy.

* refactor: replace remaining clash meta naming with mihomo

Doc comment, generated bindings and the prebuild sidecar helpers stop
referring to the legacy Clash Meta name; installer legacy-process
cleanup keeps the old executable names on purpose.

* refactor(enhance): drop builtin core filtering that never discriminates

Both valid cores matched a different ChainSupport variant, yet each
variant registered the same uid pair, so the filtered builtin list was
identical for stable and alpha. Invalid cores are coerced at startup
(validate_and_fix_config / get_valid_clash_core) and the None arm of
is_support was unreachable. builtin() now returns the items directly
and the clash_core threading through ConfigValues goes away; re-add
core discrimination when a builtin actually differs per core.

* refactor(enhance): drop unreachable mode script guard

merge_default_config overwrites the profile's mode with the verge-owned
clash config, whose mode is always present (template seeds rule and
patch semantics never clear it) and restricted to rule/global/direct;
change_clash_mode is rejected by the core before persisting anything
else. mode:script can therefore only arrive through a hand-crafted
patch_clash call, and for that path an explicit invalid-mode validation
error is more honest than silently rewriting to rule. mihomo rejects
mode:script outright (invalid mode), and user merge/script chains run
after the builtins, so the guard never covered them anyway.

* refactor(enhance): call the hysteria alpn builtin directly

builtin() existed to feed the uid-dispatch loop; with a single
builtin the vec and match are ceremony. apply_builtin_scripts calls
builtin_hy_alpn directly and to_script goes away; tests construct
ChainItem literals the way the merge items already did.
2026-11-03 10:48:44 +00:00

359 lines
11 KiB
Rust

use crate::config::MixedPort;
use anyhow::Result;
use base64::{Engine as _, engine::general_purpose};
use reqwest::{
Client, Proxy, StatusCode,
header::{HeaderMap, HeaderValue, USER_AGENT},
};
use smartstring::alias::String;
use std::{sync::Arc, time::Duration};
use sysproxy::Sysproxy;
use tauri::Url;
#[derive(Debug)]
pub struct HttpResponse {
status: StatusCode,
headers: HeaderMap,
body: String,
}
impl HttpResponse {
const fn new(status: StatusCode, headers: HeaderMap, body: String) -> Self {
Self { status, headers, body }
}
pub const fn status(&self) -> StatusCode {
self.status
}
pub const fn headers(&self) -> &HeaderMap {
&self.headers
}
pub fn text(&self) -> &str {
&self.body
}
}
#[derive(Debug, Clone, Copy)]
pub enum ProxyType {
None,
Localhost,
System,
}
#[derive(Debug, Clone, Copy)]
enum TlsRootMode {
PlatformVerifier,
StaticWebpkiRoots,
}
/// ALPN stays unset: raw TLS connectors offer none, while reqwest needs the h2 offer.
pub(crate) fn build_webpki_rooted_tls_config() -> Result<rustls::ClientConfig> {
let root_store = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
let config = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
.with_safe_default_protocol_versions()?
.with_root_certificates(root_store)
.with_no_client_auth();
Ok(config)
}
pub struct NetworkManager;
impl NetworkManager {
pub const fn new() -> Self {
Self
}
fn build_client(
&self,
proxy_url: Option<std::string::String>,
default_headers: HeaderMap,
accept_invalid_certs: bool,
timeout_secs: Option<u64>,
tls_root_mode: TlsRootMode,
) -> Result<Client> {
let mut builder = Client::builder()
.tls_backend_rustls()
.redirect(reqwest::redirect::Policy::limited(10))
.tcp_keepalive(Duration::from_secs(60))
.pool_max_idle_per_host(0)
.pool_idle_timeout(None);
if matches!(tls_root_mode, TlsRootMode::StaticWebpkiRoots) {
builder = builder.tls_backend_preconfigured(Self::build_static_webpki_tls_config()?);
}
// 设置代理
if let Some(proxy_str) = proxy_url {
let proxy = Proxy::all(proxy_str)?;
builder = builder.proxy(proxy);
} else {
builder = builder.no_proxy();
}
builder = builder.default_headers(default_headers);
// SSL/TLS
if accept_invalid_certs {
builder = builder
.danger_accept_invalid_certs(true)
.danger_accept_invalid_hostnames(true);
}
// 超时设置
if let Some(secs) = timeout_secs {
builder = builder
.timeout(Duration::from_secs(secs))
.connect_timeout(Duration::from_secs(secs.min(30)));
}
Ok(builder.build()?)
}
fn build_static_webpki_tls_config() -> Result<rustls::ClientConfig> {
let mut config = build_webpki_rooted_tls_config()?;
config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
Ok(config)
}
fn should_retry_with_static_webpki_roots(err: &anyhow::Error) -> bool {
if err.chain().any(Self::is_legacy_tls_protocol_error) {
return false;
}
err.chain().any(|e| {
let msg = e.to_string().to_ascii_lowercase();
[
"certificate",
"cert",
"tls",
"ssl",
"rustls",
"webpki",
"revocation",
"ocsp",
"crl",
"issuer",
"unknownissuer",
]
.iter()
.any(|kw| msg.contains(kw))
})
}
fn context_reqwest_error(err: reqwest::Error, context: &'static str) -> anyhow::Error {
let legacy_tls = Self::is_legacy_tls_protocol_error(&err);
let err = anyhow::Error::new(err).context(context);
if legacy_tls {
err.context("Subscription server uses legacy TLS; only TLS 1.2/1.3 is supported. TLS 1.0/1.1 is insecure")
} else {
err
}
}
fn is_legacy_tls_protocol_error(err: &(dyn std::error::Error + 'static)) -> bool {
let detail = format!("{err:#?}").to_ascii_lowercase();
detail.contains("protocolversion") || detail.contains("protocol version")
}
/// `allow_fallback` stays false when the caller already disabled certificate verification.
async fn request_with_static_webpki_fallback<T, F, Fut>(allow_fallback: bool, mut request: F) -> Result<T>
where
F: FnMut(TlsRootMode) -> Fut,
Fut: std::future::Future<Output = Result<T>>,
{
match request(TlsRootMode::PlatformVerifier).await {
Ok(value) => Ok(value),
Err(err) if allow_fallback && Self::should_retry_with_static_webpki_roots(&err) => {
request(TlsRootMode::StaticWebpkiRoots).await.map_err(|fallback_err| {
fallback_err.context("static webpki roots fallback failed after platform TLS verifier failed")
})
}
Err(err) => Err(err),
}
}
async fn get_with_tls_mode(
&self,
url: &str,
proxy_type: ProxyType,
timeout_secs: Option<u64>,
user_agent: Option<String>,
accept_invalid_certs: bool,
tls_root_mode: TlsRootMode,
) -> Result<HttpResponse> {
let mut parsed = Url::parse(url)?;
let mut extra_headers = HeaderMap::new();
if !parsed.username().is_empty() {
let username = percent_encoding::percent_decode_str(parsed.username())
.decode_utf8_lossy()
.into_owned();
let password = percent_encoding::percent_decode_str(parsed.password().unwrap_or_default())
.decode_utf8_lossy()
.into_owned();
let auth_str = format!("{}:{}", username, password);
let encoded = general_purpose::STANDARD.encode(auth_str);
extra_headers.insert("Authorization", HeaderValue::from_str(&format!("Basic {}", encoded))?);
}
parsed.set_username("").ok();
parsed.set_password(None).ok();
// 创建请求
let client = self
.create_request_with_tls_mode(
proxy_type,
timeout_secs,
user_agent,
accept_invalid_certs,
tls_root_mode,
)
.await?;
let mut request_builder = client.get(parsed);
for (key, value) in extra_headers.iter() {
request_builder = request_builder.header(key, value);
}
let response = match request_builder.send().await {
Ok(resp) => resp,
Err(e) => {
return Err(Self::context_reqwest_error(e, "Request failed"));
}
};
let status = response.status();
let headers = response.headers().to_owned();
let body = match response.text().await {
Ok(text) => text.into(),
Err(e) => {
return Err(Self::context_reqwest_error(e, "Failed to read response body"));
}
};
Ok(HttpResponse::new(status, headers, body))
}
async fn create_request_with_tls_mode(
&self,
proxy_type: ProxyType,
timeout_secs: Option<u64>,
user_agent: Option<String>,
accept_invalid_certs: bool,
tls_root_mode: TlsRootMode,
) -> Result<Client> {
let proxy_url: Option<std::string::String> = match proxy_type {
ProxyType::None => None,
ProxyType::Localhost => {
let port = MixedPort::desired().await;
Some(format!("http://127.0.0.1:{port}"))
}
ProxyType::System => {
if let Ok(p @ Sysproxy { enable: true, .. }) = Sysproxy::get_system_proxy() {
Some(format!("http://{}:{}", p.host, p.port))
} else {
None
}
}
};
let mut headers = HeaderMap::new();
// 设置 User-Agent
if let Some(ua) = user_agent {
headers.insert(USER_AGENT, HeaderValue::from_str(ua.as_str())?);
} else {
headers.insert(
USER_AGENT,
HeaderValue::from_str(&format!("clash-verge/v{}", env!("CARGO_PKG_VERSION")))?,
);
}
self.build_client(proxy_url, headers, accept_invalid_certs, timeout_secs, tls_root_mode)
}
pub async fn get(
&self,
url: &str,
proxy_type: ProxyType,
timeout_secs: Option<u64>,
user_agent: Option<String>,
accept_invalid_certs: bool,
) -> Result<HttpResponse> {
Self::request_with_static_webpki_fallback(!accept_invalid_certs, |tls_root_mode| {
let user_agent = user_agent.clone();
async move {
self.get_with_tls_mode(
url,
proxy_type,
timeout_secs,
user_agent,
accept_invalid_certs,
tls_root_mode,
)
.await
}
})
.await
}
async fn get_bytes_with_tls_mode(
&self,
url: &str,
proxy_type: ProxyType,
timeout_secs: Option<u64>,
max_bytes: usize,
tls_root_mode: TlsRootMode,
) -> Result<Vec<u8>> {
let client = self
.create_request_with_tls_mode(proxy_type, timeout_secs, None, false, tls_root_mode)
.await?;
let mut response = client
.get(url)
.send()
.await
.map_err(|e| Self::context_reqwest_error(e, "Request failed"))?;
let status = response.status();
if !status.is_success() {
anyhow::bail!("request failed with status {status}");
}
let mut body = Vec::new();
while let Some(chunk) = response
.chunk()
.await
.map_err(|e| Self::context_reqwest_error(e, "Failed to read response body"))?
{
if body.len() + chunk.len() > max_bytes {
anyhow::bail!("response exceeded the {max_bytes} byte limit");
}
body.extend_from_slice(&chunk);
}
Ok(body)
}
/// Downloads a binary body, mirroring the TLS fallback of [`Self::get`].
pub async fn get_bytes(
&self,
url: &str,
proxy_type: ProxyType,
timeout_secs: Option<u64>,
max_bytes: usize,
) -> Result<Vec<u8>> {
Self::request_with_static_webpki_fallback(true, |tls_root_mode| async move {
self.get_bytes_with_tls_mode(url, proxy_type, timeout_secs, max_bytes, tls_root_mode)
.await
})
.await
}
}