diff --git a/src/main.rs b/src/main.rs index 502524d..c13e273 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1077,6 +1077,18 @@ impl App { &format!("pid_record={}", pid.trim()), ); } + // A system proxy still pointing at the core that just died sends + // every proxy-aware app on the machine to a closed port. Drop our + // own entry here; the user turns it back on once the core is up. + if snapshot.sysproxy_enabled { + if let Ok(Some(note)) = mihomo::release_stale_sysproxy(&config.controller) { + crate::diagnostics::record( + &config.controller, + "sysproxy-stale-released", + ¬e, + ); + } + } } let mut app = Self::from_snapshot(config, snapshot); app.load_core_log(); diff --git a/src/mihomo.rs b/src/mihomo.rs index c57ae8c..7159540 100644 --- a/src/mihomo.rs +++ b/src/mihomo.rs @@ -3922,13 +3922,7 @@ pub fn stop_core_service(cfg: &ControllerConfig) -> Result { "core-stop-complete", &format!("pid={pid} source=core-service"), ); - let (_, enabled) = detect_sysproxy(); - if enabled { - let ports = read_config_text(cfg) - .map(|raw| yaml_listener_ports(&raw)) - .unwrap_or_default(); - release_sysproxy(&ports)?; - } + release_stale_sysproxy(cfg)?; Ok("Stopped managed Mihomo core".into()) } @@ -3974,6 +3968,20 @@ fn refuse_sysproxy_in_tests() -> Result<(), String> { } } +/// Turn the system proxy off when it is ours and the core it points at is not +/// running. A stale entry sends every proxy-aware app to a closed port, so this +/// runs whenever terc finds the core gone: on a stop, and at launch. +pub fn release_stale_sysproxy(cfg: &ControllerConfig) -> Result, String> { + let (_, enabled) = detect_sysproxy(); + if !enabled { + return Ok(None); + } + let ports = read_config_text(cfg) + .map(|raw| yaml_listener_ports(&raw)) + .unwrap_or_default(); + release_sysproxy(&ports) +} + /// Turn off the system proxy entries that still point at this core. fn release_sysproxy(ports: &[u16]) -> Result, String> { refuse_sysproxy_in_tests()?;