mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-18 09:52:13 +08:00
fix(port): stop the mixed port climbing on every restart
The startup fallback persisted its replacement, so a port blocked once was never asked for again. It now overrides the Runtime Config for the session only. Most of those conflicts were not real: SO_REUSEADDR cannot reuse a TIME_WAIT socket owned by another user, and a service-managed core runs as root while the app does not. A refused bind is now confirmed by asking whether anything answers. Also restores the borrowed port when saving proxy ports fails.
This commit is contained in:
@@ -1,10 +1,11 @@
|
||||
use super::{IClashTemp, IProfiles, IVerge};
|
||||
use super::{IClashTemp, IProfiles, IVerge, MixedPort};
|
||||
use crate::{
|
||||
config::{PrfItem, profiles_append_item_to_safe, runtime::IRuntime},
|
||||
constants::{files, timing},
|
||||
core::{
|
||||
CoreManager,
|
||||
handle::{self, Handle},
|
||||
listener::MIXED_PORT_KEY,
|
||||
tray,
|
||||
validate::CoreConfigValidator,
|
||||
},
|
||||
@@ -258,6 +259,11 @@ impl Config {
|
||||
let (mut config, exists_keys, logs) = enhance::enhance(profiles).await?;
|
||||
|
||||
sanitize_tunnels_proxy(&mut config);
|
||||
// Applied here rather than in the Merge Config: this is the only place the Core's config
|
||||
// is built, and `config.yaml` must stay unaware so the next launch asks for the original.
|
||||
if let Some(port) = MixedPort::session_fallback() {
|
||||
config.insert(MIXED_PORT_KEY.into(), port.into());
|
||||
}
|
||||
|
||||
Self::runtime().await.edit_draft(|d| {
|
||||
*d = IRuntime {
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
//! Resolving the Mixed Port.
|
||||
//!
|
||||
//! Two different questions were being asked with one answer:
|
||||
//!
|
||||
//! - *What have we configured?* — the user's selection, else the Merge Config. Everything that
|
||||
//! writes configuration or decides what to start needs this, and it has to be answerable
|
||||
//! before the Core exists.
|
||||
//! - *What is the Core actually serving on?* — what the Core reports, else what we configured.
|
||||
//! Anything that points a client at the proxy wants this, because the two can differ: a
|
||||
//! startup fallback moves the port, and a hand-edited Core config can move it too.
|
||||
//!
|
||||
//! Before, six call sites hand-copied the first chain (one of them skipping the Merge Config
|
||||
//! entirely) and the frontend hand-copied a version of the second.
|
||||
//! Two questions, deliberately kept apart because the answers can differ:
|
||||
//! [`MixedPort::desired`] — what we configured, answerable before the Core exists;
|
||||
//! [`MixedPort::effective`] — what the Core reports it is serving on.
|
||||
|
||||
use std::sync::atomic::{AtomicU16, Ordering};
|
||||
|
||||
use anyhow::Result;
|
||||
|
||||
@@ -20,33 +14,49 @@ use crate::core::handle::Handle;
|
||||
/// The port mihomo listens on when nothing else is configured.
|
||||
pub const DEFAULT_MIXED_PORT: u16 = 7897;
|
||||
|
||||
/// The port a startup fallback moved this session to, or 0 for none.
|
||||
///
|
||||
/// Never persisted: the user's port stays in `verge.yaml` and `config.yaml` so the next launch
|
||||
/// asks for it again. Persisting it instead made a once-blocked port climb on every launch.
|
||||
static SESSION_FALLBACK: AtomicU16 = AtomicU16::new(0);
|
||||
|
||||
/// Resolving the Mixed Port.
|
||||
pub struct MixedPort;
|
||||
|
||||
impl MixedPort {
|
||||
/// The Mixed Port the app has configured.
|
||||
/// Read by [`Self::desired`] and by runtime config generation — the two places that decide
|
||||
/// what the Core is asked to listen on.
|
||||
pub(crate) fn session_fallback() -> Option<u16> {
|
||||
match SESSION_FALLBACK.load(Ordering::Acquire) {
|
||||
0 => None,
|
||||
port => Some(port),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_session_fallback(port: u16) {
|
||||
SESSION_FALLBACK.store(port, Ordering::Release);
|
||||
}
|
||||
|
||||
pub(crate) fn clear_session_fallback() {
|
||||
SESSION_FALLBACK.store(0, Ordering::Release);
|
||||
}
|
||||
|
||||
/// The Mixed Port the app has configured. Safe before the Core exists.
|
||||
///
|
||||
/// Reads the draft layer, so an edit in progress is visible to the code applying it. Safe
|
||||
/// to call before the Core is running, unlike [`Self::effective`].
|
||||
///
|
||||
/// Reading the draft means a caller that hands this to something *outside* the app — the
|
||||
/// PAC endpoint is the one that does — can name a port the Core has not moved to yet.
|
||||
/// What makes that safe is that the only path staging a listener port,
|
||||
/// `feat::listener::save_proxy_ports`, closes PAC across the staging with `core_starting`
|
||||
/// and reopens it with `core_start_settled`. A second path that stages a listener port
|
||||
/// while the Core is serving would have to do the same.
|
||||
/// Reads the draft layer, so this can name a port the Core has not moved to yet — which
|
||||
/// matters because the PAC endpoint hands it outside the app. Safe only because
|
||||
/// `feat::listener::save_proxy_ports` closes PAC across the staging (`core_starting` /
|
||||
/// `core_start_settled`); any other path staging a listener port must do the same.
|
||||
pub async fn desired() -> u16 {
|
||||
let selected = Config::verge().await.latest_arc().verge_mixed_port;
|
||||
// `get_mixed_port` already falls back to the default when the Merge Config is silent.
|
||||
let merged = Config::clash().await.latest_arc().get_mixed_port();
|
||||
resolve_desired(selected, merged)
|
||||
resolve_desired(Self::session_fallback(), selected, merged)
|
||||
}
|
||||
|
||||
/// The Mixed Port the Core is actually serving on.
|
||||
///
|
||||
/// Costs one round-trip to the Core, so it belongs on paths a user triggers rather than on
|
||||
/// paths served per request. Falls back to [`Self::desired`] when the Core cannot be asked,
|
||||
/// which is the right answer whenever the Core is not running anyway.
|
||||
/// Costs a round-trip, so use it on user-triggered paths, not per-request ones.
|
||||
pub async fn effective() -> u16 {
|
||||
let desired = Self::desired().await;
|
||||
resolve_effective(
|
||||
@@ -57,11 +67,12 @@ impl MixedPort {
|
||||
}
|
||||
}
|
||||
|
||||
/// Prefer what the user selected, else what the Merge Config resolved to.
|
||||
const fn resolve_desired(selected: Option<u16>, merged: u16) -> u16 {
|
||||
match selected {
|
||||
Some(port) => port,
|
||||
None => merged,
|
||||
/// Fallback first — it is the only value not written down, so the files still name the port the
|
||||
/// user asked for while this session serves another.
|
||||
const fn resolve_desired(session_fallback: Option<u16>, selected: Option<u16>, merged: u16) -> u16 {
|
||||
match (session_fallback, selected) {
|
||||
(Some(port), _) | (None, Some(port)) => port,
|
||||
(None, None) => merged,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,17 +96,21 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_selected_port_wins_over_the_merge_config() {
|
||||
assert_eq!(resolve_desired(Some(9000), 7897), 9000);
|
||||
assert_eq!(resolve_desired(None, Some(9000), 7897), 9000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_merge_config_answers_when_nothing_is_selected() {
|
||||
assert_eq!(resolve_desired(None, 8080), 8080);
|
||||
assert_eq!(resolve_desired(None, None, 8080), 8080);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_fallback_outranks_the_port_still_written_down() {
|
||||
assert_eq!(resolve_desired(Some(7900), Some(7897), 7897), 7900);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_reporting_core_overrides_what_we_configured() {
|
||||
// This is the startup-fallback case: we asked for 7897 and the Core landed on 7898.
|
||||
assert_eq!(resolve_effective(|| async { Ok(7898) }, 7897).await, 7898);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
use super::{
|
||||
Config, ConfigType, IClashTemp, IVerge,
|
||||
snapshot::{capture_config_files, restore_files},
|
||||
};
|
||||
use super::{Config, ConfigType, IClashTemp, IVerge, MixedPort};
|
||||
use crate::{
|
||||
constants::timing,
|
||||
core::{
|
||||
handle::Handle,
|
||||
listener::{ListenerBindScope, MIXED_PORT_KEY, proxy_listener_keys},
|
||||
listener::{ListenerBindScope, ListenerProbeOutcome, MIXED_PORT_KEY, proxy_listener_keys},
|
||||
owner_identity::current_owner_credentials,
|
||||
service::{SERVICE_MANAGER, ServiceStatus},
|
||||
validate::CoreConfigValidator,
|
||||
@@ -50,7 +47,9 @@ impl Config {
|
||||
let _config_write = Self::lock_config_write().await;
|
||||
let clash = Self::clash().await.latest_arc();
|
||||
let verge = Self::verge().await.latest_arc();
|
||||
let selected_port = clash.get_mixed_port();
|
||||
// A retry must re-examine the port this session actually tried, not the one still named
|
||||
// on disk, or it keeps picking the same replacement instead of walking past it.
|
||||
let selected_port = MixedPort::session_fallback().unwrap_or_else(|| clash.get_mixed_port());
|
||||
let bind_scope =
|
||||
ListenerBindScope::from_mapping(&clash.0).context("failed to derive mixed proxy listener scope")?;
|
||||
|
||||
@@ -65,11 +64,24 @@ impl Config {
|
||||
}
|
||||
|
||||
let selected_scope = bind_scope.clone();
|
||||
let port_in_use = AsyncHandler::spawn_blocking(move || !selected_scope.mixed_port_is_available(selected_port))
|
||||
let outcome = AsyncHandler::spawn_blocking(move || selected_scope.probe_mixed_port(selected_port))
|
||||
.await
|
||||
.context("mixed proxy port probe task failed")?;
|
||||
if !port_in_use {
|
||||
return Ok(false);
|
||||
// Only a proven conflict may move the port; an answer the probe could not reach is not
|
||||
// evidence. A `Conflict` here also means the probe confirmed something is serving.
|
||||
match outcome {
|
||||
ListenerProbeOutcome::Conflict { .. } => {}
|
||||
ListenerProbeOutcome::Available => return Ok(false),
|
||||
ListenerProbeOutcome::Invalid { message } | ListenerProbeOutcome::Indeterminate { message } => {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Setup,
|
||||
"Could not establish whether mixed proxy port {} is free ({}); keeping it",
|
||||
selected_port,
|
||||
message
|
||||
);
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
|
||||
let reserved = configured_listener_ports(&clash, &verge);
|
||||
@@ -86,20 +98,41 @@ impl Config {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Move this session onto `new_port` without touching what is on disk.
|
||||
///
|
||||
/// Only the Runtime Configuration changes — the Core is its only reader and it is rebuilt
|
||||
/// every launch. `config.yaml` and `verge.yaml` keep naming `old_port` so the next launch
|
||||
/// asks for it again.
|
||||
async fn apply_startup_mixed_port_fallback(old_port: u16, new_port: u16) -> Result<()> {
|
||||
let clash = Self::clash().await;
|
||||
let verge = Self::verge().await;
|
||||
let runtime = Self::runtime().await;
|
||||
// Roll back all three drafts if fallback fails.
|
||||
let transaction = DraftTransaction::begin(vec![&clash, &verge, &runtime])?;
|
||||
let transaction = DraftTransaction::begin(vec![&runtime])?;
|
||||
|
||||
clash.edit_draft(|draft| {
|
||||
draft.0.insert(MIXED_PORT_KEY.into(), new_port.into());
|
||||
});
|
||||
verge.edit_draft(|draft| {
|
||||
draft.verge_mixed_port = Some(new_port);
|
||||
});
|
||||
// On a later hop the uncommitted transaction restores the Runtime Config to the previous
|
||||
// hop, so restore the override to match rather than dropping to what is on disk.
|
||||
let previous_port = MixedPort::session_fallback();
|
||||
MixedPort::set_session_fallback(new_port);
|
||||
if let Err(error) = Self::stage_fallback_runtime().await {
|
||||
match previous_port {
|
||||
Some(port) => MixedPort::set_session_fallback(port),
|
||||
None => MixedPort::clear_session_fallback(),
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
transaction.commit();
|
||||
record_fallback(old_port, new_port);
|
||||
Handle::refresh_clash();
|
||||
logging!(
|
||||
warn,
|
||||
Type::Config,
|
||||
"Mixed proxy port {} is externally occupied; serving on {} for this session only",
|
||||
old_port,
|
||||
new_port
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn stage_fallback_runtime() -> Result<()> {
|
||||
Self::generate()
|
||||
.await
|
||||
.context("failed to materialize runtime configuration with fallback port")?;
|
||||
@@ -112,46 +145,9 @@ impl Config {
|
||||
bail!("runtime configuration with fallback port is invalid: {validation}");
|
||||
}
|
||||
|
||||
let snapshots = capture_config_files().await?;
|
||||
let candidate_clash = clash.latest_arc();
|
||||
let candidate_verge = verge.latest_arc();
|
||||
|
||||
let persist_result = async {
|
||||
candidate_clash
|
||||
.save_config()
|
||||
.await
|
||||
.context("failed to persist Application Merge Configuration")?;
|
||||
candidate_verge
|
||||
.save_file()
|
||||
.await
|
||||
.context("failed to persist selected mixed proxy port")?;
|
||||
Self::generate_file(ConfigType::Run)
|
||||
.await
|
||||
.context("failed to persist Runtime Configuration")?;
|
||||
Ok::<(), anyhow::Error>(())
|
||||
}
|
||||
.await;
|
||||
|
||||
// Restore files after rollback so regeneration sees committed values.
|
||||
if let Err(error) = persist_result {
|
||||
transaction.rollback();
|
||||
return match restore_files(&snapshots).await {
|
||||
Ok(()) => Err(error),
|
||||
Err(rollback_error) => Err(anyhow!("{error:#}; configuration rollback failed: {rollback_error:#}")),
|
||||
};
|
||||
}
|
||||
|
||||
transaction.commit();
|
||||
record_fallback(old_port, new_port);
|
||||
Handle::refresh_clash();
|
||||
Handle::refresh_verge();
|
||||
logging!(
|
||||
warn,
|
||||
Type::Config,
|
||||
"Mixed proxy port {} is externally occupied; switched to {} and persisted all configuration layers",
|
||||
old_port,
|
||||
new_port
|
||||
);
|
||||
Self::generate_file(ConfigType::Run)
|
||||
.await
|
||||
.context("failed to write Runtime Configuration")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -209,9 +205,16 @@ fn report_fallback_error(message: String) {
|
||||
});
|
||||
}
|
||||
|
||||
// Only a service-managed core can still be running during startup.
|
||||
// Only a service-managed core can still be running during startup. Every exit here decides
|
||||
// whether the app may renumber a port the user chose, so each one logs why.
|
||||
async fn owned_service_core_uses_port(port: u16) -> bool {
|
||||
if !matches!(SERVICE_MANAGER.current().await, ServiceStatus::Ready) {
|
||||
let service_status = SERVICE_MANAGER.current().await;
|
||||
if !matches!(service_status, ServiceStatus::Ready) {
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
"Service is {service_status:?}, so no managed core can hold mixed proxy port {port}"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -238,9 +241,26 @@ async fn owned_service_core_uses_port(port: u16) -> bool {
|
||||
}
|
||||
};
|
||||
let Some(status) = response.data else {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"Service returned no status while checking mixed proxy port {port}"
|
||||
);
|
||||
return false;
|
||||
};
|
||||
if response.code > 0 || !status.is_active || status.core_pid.is_none() {
|
||||
// Normal after a clean quit: the service drops the owner session and forgets the core, so
|
||||
// it can no longer vouch for whatever holds the port. This guard only covers dirty exits.
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
"Service no longer tracks a core for this owner (code {}, active {}, pid {:?}); \
|
||||
mixed proxy port {} is unattributed",
|
||||
response.code,
|
||||
status.is_active,
|
||||
status.core_pid,
|
||||
port
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user