diff --git a/AGENTS.md b/AGENTS.md index 4aeeff3..c217399 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,6 +37,7 @@ If a required command fails or emits a warning from project code, fix it in the - Read the current per-user `biflow/debug.log` first when diagnosing a runtime report. It is permanent newline-delimited JSON across application sessions and is also included by **Diagnostics → Export**. Do not assume it exists before the app has launched, and do not commit a generated `debug.log`. - Every new or changed desktop user action, background task, platform/helper boundary, warning, ignored failure, and error path in Rust must emit structured `tracing` events that reach `debug.log`. Reuse the command trace helpers in `src-tauri/src/diagnostics.rs` at Tauri boundaries. The separately privileged helper must emit the same safe fields to its service journal; the desktop records each helper request and result in `debug.log` without making the root service write into a user's data directory. +- A command or check that repeats on a timer uses `diagnostics::trace_poll` or `record_poll`, which log only a change of outcome (ADR 0143). Never put `trace_action` or an `info!` success event on a timer. - Action events must identify `event`, `section`, `initiator`, `cause`, and `trace_route`; use a stable operation/request UUID as `trace_id` when available. Never log passwords, controller secrets, tokens, credentials, subscription links, raw URLs, full settings, direct-rule values, diagnostic targets, or unredacted user content. - Do not ignore fallible Rust operations with `let _ =` unless failure is provably irrelevant. Log the warning/error and cause when execution continues, and preserve a regression test for diagnostic lifecycle, redaction, and file-size behavior. - `debug.log` stays in append mode across process launches and is flushed after every event. Do not truncate, rotate, cap, or delete it automatically on startup or shutdown. Only the explicit Diagnostics delete action clears its contents; it must keep the active file handle usable and resume logging immediately. @@ -71,6 +72,36 @@ If a required command fails or emits a warning from project code, fix it in the ## Lessons +- A path or a file that reaches the helper over IPC is attacker input, even + from the authorized user: the helper is root and the desktop is not. "Regular, + non-symlink file" is not trust. Check who can change the file and every + directory above it (ADR 0141). +- Do not filter another program's config language with a list of bad words. + OpenVPN quotes, includes, escapes, `setenv opt`, and closes an inline block on + a prefix. Parse it once, allow a known list, and run the rendered copy. +- A dropped future is not a rollback. A timeout around a multi-step operation + needs its own cleanup step and a test that asserts the released state, not + only that the lifecycle lock cleared (ADR 0144). +- Returning Ok because "the same kind of operation is already busy" lets two + callers run together. Serialize work that shares a prepared generation, and + re-check the phase after waiting. +- Replacing an application folder deletes whatever the app keeps beside its + executable. Hiddify's portable build stores subscriptions there. Read the + upstream source for its data folder before removing the old one. +- Go encodes a nil slice as `null`. `#[serde(default)]` does not accept it, so + an idle Mihomo produced "error decoding response body". Run the bundled + binary with no traffic when writing a controller fixture. +- A permanent log plus a one-second poll grew to 4.8 GB. Measure bytes per + minute with the window open when adding an event. +- Never print files from the side-tunnel data folder while diagnosing. They can + hold VPN credentials; list names and sizes only. `NamedTempFile` is not + deleted by a crash, so clear leftovers at startup. +- A runtime `cfg!(target_os = "macos")` branch changes what shared tests see on + a Mac while Linux and Windows stay green. Give each platform list its own + function and test that function by name on every host. +- `cfg(unix)` constants used by a shared type are dead code in the Windows + library build. Run `cargo xwin clippy` after changing the helper. + - Hiddify can rename Linux release assets and wrap its Windows portable files in an outer directory. Verify the publisher's asset names and SHA-256 values, assert the real ZIP layout in the installer fixture, and publish the complete diff --git a/Cargo.lock b/Cargo.lock index 02f8caf..da2b6cd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2044,7 +2044,7 @@ dependencies = [ [[package]] name = "iran-split-cli" -version = "6.2.96" +version = "6.3.0" dependencies = [ "async-trait", "clap", @@ -2062,7 +2062,7 @@ dependencies = [ [[package]] name = "iran-split-clients" -version = "6.2.96" +version = "6.3.0" dependencies = [ "async-trait", "ipnet", @@ -2074,11 +2074,12 @@ dependencies = [ "thiserror 2.0.20", "tokio", "tokio-util", + "uuid", ] [[package]] name = "iran-split-config" -version = "6.2.96" +version = "6.3.0" dependencies = [ "hex", "rand 0.9.5", @@ -2091,7 +2092,7 @@ dependencies = [ [[package]] name = "iran-split-core" -version = "6.2.96" +version = "6.3.0" dependencies = [ "async-trait", "iran-split-config", @@ -2108,7 +2109,7 @@ dependencies = [ [[package]] name = "iran-split-desktop" -version = "6.2.96" +version = "6.3.0" dependencies = [ "dirs 6.0.0", "flate2", @@ -2150,7 +2151,7 @@ dependencies = [ [[package]] name = "iran-split-helper" -version = "6.2.96" +version = "6.3.0" dependencies = [ "clap", "hex", @@ -2175,7 +2176,7 @@ dependencies = [ [[package]] name = "iran-split-helper-winacl" -version = "6.2.96" +version = "6.3.0" dependencies = [ "tokio", "windows", @@ -2183,7 +2184,7 @@ dependencies = [ [[package]] name = "iran-split-ipc" -version = "6.2.96" +version = "6.3.0" dependencies = [ "bytes", "serde", @@ -2195,7 +2196,7 @@ dependencies = [ [[package]] name = "iran-split-mihomo" -version = "6.2.96" +version = "6.3.0" dependencies = [ "futures-util", "hex", @@ -2218,7 +2219,7 @@ dependencies = [ [[package]] name = "iran-split-netstats" -version = "6.2.96" +version = "6.3.0" dependencies = [ "libc", "tempfile", @@ -2227,7 +2228,7 @@ dependencies = [ [[package]] name = "iran-split-platform-linux" -version = "6.2.96" +version = "6.3.0" dependencies = [ "async-trait", "hex", @@ -2251,7 +2252,7 @@ dependencies = [ [[package]] name = "iran-split-platform-macos" -version = "6.2.96" +version = "6.3.0" dependencies = [ "async-trait", "hex", @@ -2275,7 +2276,7 @@ dependencies = [ [[package]] name = "iran-split-platform-win" -version = "6.2.96" +version = "6.3.0" dependencies = [ "async-trait", "iran-split-clients", @@ -2298,7 +2299,7 @@ dependencies = [ [[package]] name = "iran-split-rules" -version = "6.2.96" +version = "6.3.0" dependencies = [ "async-trait", "hex", @@ -2320,7 +2321,7 @@ dependencies = [ [[package]] name = "iran-split-taskbar" -version = "6.2.96" +version = "6.3.0" dependencies = [ "iran-split-config", "objc2", diff --git a/Cargo.toml b/Cargo.toml index 4fcaad1..3b89383 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ members = [ ] [workspace.package] -version = "6.2.96" +version = "6.3.0" edition = "2021" license = "MIT OR Apache-2.0" rust-version = "1.88" diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 4fc7155..7dfa1ec 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@iran-split/desktop", - "version": "6.2.96", + "version": "6.3.0", "private": true, "type": "module", "scripts": { diff --git a/apps/desktop/src/App.test.tsx b/apps/desktop/src/App.test.tsx index ead3adc..1b441bb 100644 --- a/apps/desktop/src/App.test.tsx +++ b/apps/desktop/src/App.test.tsx @@ -1,4 +1,4 @@ -import { render, screen, within } from "@testing-library/react"; +import { act, render, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { beforeEach, describe, expect, it } from "vitest"; import { App } from "./App"; @@ -79,6 +79,20 @@ describe("App", () => { ); }); + it("says so when startup replaced unreadable settings", async () => { + render(); + await waitFor(() => expect(useAppStore.getState().boot).not.toBeNull()); + const { boot } = useAppStore.getState(); + act(() => { + useAppStore.setState({ + boot: boot && { ...boot, settings_recovered: "defaults" }, + }); + }); + expect( + await screen.findByText(/The settings file was damaged/), + ).toBeInTheDocument(); + }); + it("opens the legacy About page as the Settings About tab", async () => { render(); await homeHeading(); diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index c8af2bd..bc187f1 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -73,6 +73,17 @@ export function App() { // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + const settingsRecovered = store.boot?.settings_recovered ?? null; + useEffect(() => { + if (settingsRecovered) { + useAppStore.setState({ + error: t(`settingsRecovered_${settingsRecovered}`), + }); + } + // Shown once per start; changing the language must not reopen it. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [settingsRecovered]); + useEffect(() => { let unsubscribe: () => void = () => undefined; void desktop diff --git a/apps/desktop/src/api/models.ts b/apps/desktop/src/api/models.ts index d380b8b..b25e741 100644 --- a/apps/desktop/src/api/models.ts +++ b/apps/desktop/src/api/models.ts @@ -317,6 +317,8 @@ export interface BootstrapResult { cloud_rules: CloudRulesStatus; dependencies: DependencyStatus[]; network_status: NetworkStatus; + /** Set when startup replaced settings it could not read. */ + settings_recovered?: "last_saved" | "defaults" | null; } export type InternetState = "checking" | "online" | "offline"; diff --git a/apps/desktop/src/i18n/config.ts b/apps/desktop/src/i18n/config.ts index e04d3b8..182b9be 100644 --- a/apps/desktop/src/i18n/config.ts +++ b/apps/desktop/src/i18n/config.ts @@ -169,6 +169,10 @@ const resources = { downloadInstall: "Download & install", downloadOpenVpn: "Download OpenVPN", downloadPageUnavailable: "Could not open the download page.", + settingsRecovered_last_saved: + "The settings file was damaged. BiFlow loaded your last saved settings.", + settingsRecovered_defaults: + "The settings file was damaged. BiFlow started with default settings; check your clients.", downloadWindscribeConfig: "Get Windscribe config", directTooltip: "Traffic leaves over your physical network with your real IP.", @@ -593,6 +597,10 @@ const resources = { downloadInstall: "دانلود و نصب", downloadOpenVpn: "دانلود OpenVPN", downloadPageUnavailable: "صفحهٔ دانلود باز نشد.", + settingsRecovered_last_saved: + "فایل تنظیمات خراب بود. آخرین تنظیمات ذخیره‌شده بارگذاری شد.", + settingsRecovered_defaults: + "فایل تنظیمات خراب بود. برنامه با تنظیمات پیش‌فرض باز شد؛ کلاینت‌ها را بررسی کنید.", downloadWindscribeConfig: "دانلود کانفیگ Windscribe", directTooltip: "ترافیک با آی‌پی واقعی از شبکه فیزیکی خارج می‌شود.", clientDetails: "تنظیمات و میزبان‌های سنجاق‌شده", diff --git a/crates/iran-split-cli/src/main.rs b/crates/iran-split-cli/src/main.rs index 6bed4c1..5801a6c 100644 --- a/crates/iran-split-cli/src/main.rs +++ b/crates/iran-split-cli/src/main.rs @@ -182,6 +182,7 @@ impl PlatformBackend for DemoBackend { available: true, authorized: true, version: Some("demo".into()), + tun_name: None, }) } async fn ensure_hiddify(&self, _cancel: CancellationToken) -> Result<(), CoreError> { diff --git a/crates/iran-split-clients/Cargo.toml b/crates/iran-split-clients/Cargo.toml index c4e2421..0e77c51 100644 --- a/crates/iran-split-clients/Cargo.toml +++ b/crates/iran-split-clients/Cargo.toml @@ -15,6 +15,7 @@ serde.workspace = true serde_json.workspace = true thiserror.workspace = true tokio-util.workspace = true +uuid.workspace = true [dev-dependencies] tempfile.workspace = true diff --git a/crates/iran-split-clients/src/lib.rs b/crates/iran-split-clients/src/lib.rs index 7a22900..77e5679 100644 --- a/crates/iran-split-clients/src/lib.rs +++ b/crates/iran-split-clients/src/lib.rs @@ -6,6 +6,7 @@ mod local_proxy; mod openvpn; mod profile_audit; +mod profile_parse; mod remote_pin; mod remote_resolver; @@ -19,9 +20,10 @@ use tokio_util::sync::CancellationToken; pub use local_proxy::LocalProxyDriver; pub use openvpn::OpenVpnDriver; pub use profile_audit::{ - audit_openvpn_profile, openvpn_arguments, sanitize_openvpn_profile, OpenVpnProfileError, + audit_openvpn_profile, load_openvpn_profile, openvpn_arguments, OpenVpnProfileError, OpenVpnProfileFacts, }; +pub use profile_parse::CheckedProfile; pub use remote_pin::{ pin_profile_remote, recall_remote_pin, remember_remote_pin, select_remote_pin, PinnedRemote, }; @@ -153,6 +155,89 @@ pub fn process_bypass_union( rules } +/// Drops local-proxy handles whose client was removed, disabled, or moved to +/// another endpoint, and returns their ids. A handle keeps the endpoint it was +/// verified with, so without this a live apply keeps routing to the old port. +pub fn drop_outdated_handles( + clients: &[ClientInstance], + handles: &mut Vec, +) -> Vec { + let mut dropped = Vec::new(); + handles.retain(|handle| { + if handle.kind != EgressKind::LocalProxy { + return true; + } + let current = clients + .iter() + .find(|client| client.id == handle.client_id && client.enabled) + .and_then(local_proxy_endpoint); + let verified = handle + .outbound + .as_ref() + .and_then(|outbound| Some((outbound.server.clone()?, outbound.port?))); + let keep = current.is_some() && current == verified; + if !keep { + dropped.push(handle.client_id); + } + keep + }); + dropped +} + +/// Drops side-tunnel handles whose process the helper no longer runs, and +/// returns their ids. +pub fn drop_exited_tunnels( + running: &[uuid::Uuid], + handles: &mut Vec, +) -> Vec { + let mut dropped = Vec::new(); + handles.retain(|handle| { + let keep = handle.kind != EgressKind::OwnedSideTunnel + || running.contains(&handle.client_id.into()); + if !keep { + dropped.push(handle.client_id); + } + keep + }); + dropped +} + +/// Shown on a client card after its tunnel process ended on its own. +pub const SIDE_TUNNEL_EXITED: &str = "the tunnel stopped on its own; connect this client again"; + +/// Removes credential files left by a run that did not exit cleanly. +/// +/// `OpenVPN` re-reads the file on a soft restart, so a run keeps it until the +/// tunnel stops. After a crash nothing owns it any more, and startup recovery +/// has already ended the tunnel it belonged to. +/// +/// # Errors +/// +/// Returns the I/O error that kept the directory or a file from being cleared. +pub fn clear_stale_auth_files(directory: &std::path::Path) -> std::io::Result { + let entries = match std::fs::read_dir(directory) { + Ok(entries) => entries, + Err(cause) if cause.kind() == std::io::ErrorKind::NotFound => return Ok(0), + Err(cause) => return Err(cause), + }; + let mut removed = 0; + for entry in entries { + let entry = entry?; + let name = entry.file_name(); + let owned = name + .to_str() + .is_some_and(|name| name.starts_with(".tmp") || name.starts_with(AUTH_FILE_PREFIX)); + if owned && entry.file_type()?.is_file() { + std::fs::remove_file(entry.path())?; + removed += 1; + } + } + Ok(removed) +} + +/// Name prefix of a side-tunnel credential file. +pub const AUTH_FILE_PREFIX: &str = "auth-"; + /// Local-proxy endpoint from an instance, when the config is that kind. #[must_use] pub fn local_proxy_endpoint(instance: &ClientInstance) -> Option<(String, u16)> { @@ -263,6 +348,64 @@ pub fn synthesized_egress_handle(instance: &ClientInstance) -> Option ClientInstance { + ClientInstance { + preset, + config: ClientConfig::from_preset(preset), + ..ClientInstance::hiddify_default(ClientId::new()) + } + } + + #[test] + fn a_moved_or_disabled_proxy_loses_its_verified_handle() { + let mut moved = client_for(PresetId::Hiddify); + let kept = client_for(PresetId::Happ); + let mut disabled = client_for(PresetId::Happ); + let mut handles: Vec<_> = [&moved, &kept, &disabled] + .into_iter() + .filter_map(synthesized_local_handle) + .collect(); + assert_eq!(handles.len(), 3); + let ClientConfig::LocalProxy { port, .. } = &mut moved.config else { + panic!("local proxy fixture"); + }; + *port += 1; + disabled.enabled = false; + let (moved_id, kept_id, disabled_id) = (moved.id, kept.id, disabled.id); + let dropped = drop_outdated_handles(&[moved, kept, disabled], &mut handles); + assert_eq!(dropped, [moved_id, disabled_id]); + assert_eq!(handles.len(), 1); + assert_eq!(handles[0].client_id, kept_id); + } + + #[test] + fn only_a_tunnel_the_helper_still_runs_keeps_its_handle() { + let proxy = synthesized_local_handle(&client_for(PresetId::Hiddify)).expect("proxy handle"); + let tunnel = |id| EgressHandle { + client_id: id, + kind: EgressKind::OwnedSideTunnel, + ..proxy.clone() + }; + let (alive, dead) = (ClientId::new(), ClientId::new()); + let mut handles = vec![proxy.clone(), tunnel(alive), tunnel(dead)]; + assert_eq!(drop_exited_tunnels(&[alive.into()], &mut handles), [dead]); + assert_eq!(handles.len(), 2); + } + + #[test] + fn leftover_credential_files_are_removed_and_nothing_else() { + let directory = tempfile::tempdir().expect("tempdir"); + for name in [".tmpAb12", "auth-Cd34", "office.ovpn"] { + std::fs::write(directory.path().join(name), b"x").expect("fixture"); + } + assert_eq!(clear_stale_auth_files(directory.path()).expect("clear"), 2); + assert!(directory.path().join("office.ovpn").is_file()); + assert_eq!( + clear_stale_auth_files(&directory.path().join("missing")).expect("missing"), + 0 + ); + } + #[test] fn catalog_lists_every_planned_preset() { let rows = catalog(); diff --git a/crates/iran-split-clients/src/profile_audit.rs b/crates/iran-split-clients/src/profile_audit.rs index fa20261..70a3885 100644 --- a/crates/iran-split-clients/src/profile_audit.rs +++ b/crates/iran-split-clients/src/profile_audit.rs @@ -1,3 +1,4 @@ +use crate::profile_parse::CheckedProfile; use ipnet::IpNet; use std::{ net::IpAddr, @@ -5,36 +6,20 @@ use std::{ }; use thiserror::Error; -/// Directives that let a profile run code, or steal the interface. -const FORBIDDEN_DIRECTIVES: [&str; 16] = [ - "up", - "down", - "up-restart", - "route-up", - "route-pre-down", - "ipchange", - "learn-address", - "tls-verify", - "auth-user-pass-verify", - "client-connect", - "client-disconnect", - "plugin", - "script-security", - "daemon", - "log", - "log-append", -]; - #[derive(Debug, Error)] pub enum OpenVpnProfileError { #[error("profile is unreadable")] Unreadable, #[error("profile must be a regular, non-symlink file")] NotRegularFile, - #[error("profile uses the '{0}' directive, which would run commands as root")] + #[error("profile uses '{0}', which BiFlow does not allow because OpenVPN runs as root")] ForbiddenDirective(String), #[error("profile has an unterminated inline block")] UnterminatedBlock, + #[error("profile has a line longer than OpenVPN accepts")] + LineTooLong, + #[error("profile has quoting or an inline block that cannot be read safely")] + Ambiguous, #[error("profile declares no remote server")] NoRemote, } @@ -48,148 +33,52 @@ pub struct OpenVpnProfileFacts { pub server_networks: Vec, } -/// Reads a `.ovpn` file and rejects anything that would run code as root. +/// Reads a `.ovpn` file and rejects anything outside the directive allowlist. /// /// # Errors /// /// Returns [`OpenVpnProfileError`] when the file is missing, not a regular -/// file, carries a script directive, or declares no `remote`. +/// file, uses a directive a client profile does not need, or declares no +/// `remote`. pub fn audit_openvpn_profile(path: &Path) -> Result { + load_openvpn_profile(path).map(|(facts, _)| facts) +} + +/// Reads and checks a profile once, so the copy `OpenVPN` runs is rendered +/// from the same bytes that were checked. +/// +/// # Errors +/// +/// Same conditions as [`audit_openvpn_profile`]. +pub fn load_openvpn_profile( + path: &Path, +) -> Result<(OpenVpnProfileFacts, CheckedProfile), OpenVpnProfileError> { let metadata = std::fs::symlink_metadata(path).map_err(|_| OpenVpnProfileError::Unreadable)?; if !metadata.file_type().is_file() || metadata.file_type().is_symlink() { return Err(OpenVpnProfileError::NotRegularFile); } let text = std::fs::read_to_string(path).map_err(|_| OpenVpnProfileError::Unreadable)?; - let mut remote_hosts = Vec::new(); - let mut remote_port = None; - let mut inline_block: Option = None; - for line in text.lines() { - let line = line.trim(); - if let Some(open) = inline_block.as_deref() { - if line.eq_ignore_ascii_case(&format!("")) { - inline_block = None; - } - continue; - } - if line.is_empty() || line.starts_with('#') || line.starts_with(';') { - continue; - } - if let Some(tag) = line - .strip_prefix('<') - .and_then(|rest| rest.strip_suffix('>')) - { - if !tag.starts_with('/') { - inline_block = Some(tag.to_ascii_lowercase()); - } - continue; - } - let mut parts = line.split_whitespace(); - let Some(directive) = parts.next() else { - continue; - }; - let directive = directive.trim_start_matches("--").to_ascii_lowercase(); - if FORBIDDEN_DIRECTIVES.contains(&directive.as_str()) { - return Err(OpenVpnProfileError::ForbiddenDirective(directive)); - } - if directive == "remote" { - if let Some(host) = parts.next() { - remote_hosts.push(host.to_owned()); - if remote_port.is_none() { - remote_port = parts.next().and_then(|port| port.parse::().ok()); - } - } - } - } - if inline_block.is_some() { - return Err(OpenVpnProfileError::UnterminatedBlock); - } - if remote_hosts.is_empty() { - return Err(OpenVpnProfileError::NoRemote); - } - let server_networks = remote_hosts + let profile = CheckedProfile::parse(&text)?; + let remotes = profile.remotes(); + let server_networks = remotes .iter() - .filter_map(|host| host.parse::().ok()) - .filter_map(|address| match address { - IpAddr::V4(address) => IpNet::new(address.into(), 32).ok(), - IpAddr::V6(address) => IpNet::new(address.into(), 128).ok(), - }) + .filter_map(|(host, _)| host.parse::().ok()) + .filter_map(|address| crate::public_host_exclude(address).ok()) .collect(); - Ok(OpenVpnProfileFacts { - remote_hosts, - remote_port, + let facts = OpenVpnProfileFacts { + remote_port: remotes.first().and_then(|(_, port)| *port), + remote_hosts: remotes.into_iter().map(|(host, _)| host).collect(), server_networks, - }) -} - -const CONFLICTING_DIRECTIVES: [&str; 12] = [ - "redirect-gateway", - "redirect-private", - "block-outside-dns", - "block-ipv6", - "register-dns", - "dhcp-option", - "route", - "route-ipv6", - "route-metric", - "dev-node", - "ip-win32", - "resolv-retry", -]; - -/// Drops directives that would steal the system default route, DNS, or an -/// existing TUN adapter, and legacy cipher negotiation that disables DCO. -/// Inline certificates and keys are kept verbatim. Server pushes of the same -/// options are ignored separately on the command line. -#[must_use] -pub fn sanitize_openvpn_profile(text: &str, windows: bool) -> String { - let mut sanitized = String::new(); - let mut inline_block: Option = None; - for line in text.lines() { - let trimmed = line.trim(); - if let Some(open) = inline_block.as_deref() { - sanitized.push_str(line); - sanitized.push('\n'); - if trimmed.eq_ignore_ascii_case(&format!("")) { - inline_block = None; - } - continue; - } - if let Some(tag) = trimmed - .strip_prefix('<') - .and_then(|rest| rest.strip_suffix('>')) - { - if !tag.starts_with('/') { - inline_block = Some(tag.to_ascii_lowercase()); - } - sanitized.push_str(line); - sanitized.push('\n'); - continue; - } - let directive = trimmed - .split_whitespace() - .next() - .unwrap_or_default() - .trim_start_matches("--") - .to_ascii_lowercase(); - // A legacy Windows `ncp-ciphers` list can include CBC even when the - // helper sets AEAD-only `data-ciphers`. OpenVPN 2.7 then disables DCO. - if CONFLICTING_DIRECTIVES.contains(&directive.as_str()) - || (windows && directive == "ncp-ciphers") - { - continue; - } - sanitized.push_str(line); - sanitized.push('\n'); - } - sanitized + }; + Ok((facts, profile)) } /// Helper-owned `OpenVPN` argv. Always includes `--route-noexec` and pins /// `--script-security 2` after `--config`. /// /// Level 2 is the minimum `OpenVPN` 2.7 accepts for its own `netsh` address -/// setup. Level 0 blocks that command and the tunnel exits. The sanitized -/// profile still has no `up` or `down` scripts, so user scripts are not run. +/// setup. Level 0 blocks that command and the tunnel exits. The checked profile +/// cannot name a script, so none is run. /// /// `pinned_remote` goes **before** `--config` so it becomes the first entry in /// `OpenVPN`'s connection list and wins over the profile's own `remote`. The @@ -374,8 +263,10 @@ resolv-retry infinite not a real certificate "; - let sanitized = sanitize_openvpn_profile(source, true); - assert!(sanitized.contains("remote vpn.example.com 443")); + let sanitized = CheckedProfile::parse(source) + .expect("profile") + .render(Path::new("/profiles"), true); + assert!(sanitized.contains("remote \"vpn.example.com\" \"443\"")); assert!(sanitized.contains("auth-user-pass")); assert!(sanitized.contains("not a real certificate")); assert!(!sanitized.contains("ncp-ciphers")); @@ -417,7 +308,9 @@ not a real certificate #[test] fn linux_profile_keeps_its_cipher_negotiation() { let source = "client\nremote vpn.example.com 443\nncp-ciphers AES-256-CBC\n"; - let sanitized = sanitize_openvpn_profile(source, false); - assert!(sanitized.contains("ncp-ciphers AES-256-CBC")); + let sanitized = CheckedProfile::parse(source) + .expect("profile") + .render(Path::new("/profiles"), false); + assert!(sanitized.contains("ncp-ciphers \"AES-256-CBC\"")); } } diff --git a/crates/iran-split-clients/src/profile_parse.rs b/crates/iran-split-clients/src/profile_parse.rs new file mode 100644 index 0000000..c30ec2a --- /dev/null +++ b/crates/iran-split-clients/src/profile_parse.rs @@ -0,0 +1,616 @@ +//! Parses an imported `.ovpn` the way `OpenVPN` does, against an allowlist. +//! +//! The helper runs `OpenVPN` as root, so a profile must not be able to say +//! anything `BiFlow` did not expect. A denylist over the raw text cannot +//! promise that: `OpenVPN` accepts quoted directive names, `config` includes, +//! `setenv opt`, loadable providers, and closes an inline block on a looser +//! match than a line comparison. Everything here is therefore parsed once, +//! checked against a list of directives a client profile needs, and written +//! out again in a canonical form. The bytes `OpenVPN` reads are the ones that +//! were checked (ADR 0141). + +use crate::OpenVpnProfileError; +use std::path::Path; + +/// `OpenVPN` refuses a line of 256 bytes and splits inline data at that size. +/// Staying below it keeps both parsers looking at the same lines. +const MAX_LINE_BYTES: usize = 250; + +/// Directives a client profile may use. Anything else is refused by name. +const ALLOWED_DIRECTIVES: &[&str] = &[ + "allow-compression", + "allow-recursive-routing", + "auth", + "auth-nocache", + "auth-retry", + "auth-user-pass", + "bind", + "ca", + "cert", + "cipher", + "client", + "comp-lzo", + "comp-noadapt", + "compress", + "connect-retry", + "connect-retry-max", + "connect-timeout", + "crl-verify", + "data-ciphers", + "data-ciphers-fallback", + "dev", + "dev-type", + "disable-dco", + "disable-occ", + "ecdh-curve", + "explicit-exit-notify", + "extra-certs", + "fast-io", + "float", + "fragment", + "hand-window", + "http-proxy", + "http-proxy-option", + "http-proxy-retry", + "http-proxy-timeout", + "ifconfig", + "ifconfig-ipv6", + "ifconfig-nowarn", + "inactive", + "keepalive", + "key", + "key-direction", + "key-method", + "keysize", + "link-mtu", + "local", + "lport", + "max-packet-size", + "mlock", + "mssfix", + "mtu-disc", + "mtu-test", + "multihome", + "mute", + "mute-replay-warnings", + "ncp-ciphers", + "ncp-disable", + "nice", + "nobind", + "ns-cert-type", + "passtos", + "peer-fingerprint", + "persist-key", + "persist-local-ip", + "persist-remote-ip", + "persist-tun", + "ping", + "ping-exit", + "ping-restart", + "ping-timer-rem", + "pkcs12", + "port", + "proto", + "proto-force", + "pull", + "rcvbuf", + "remap-usr1", + "remote", + "remote-cert-eku", + "remote-cert-ku", + "remote-cert-tls", + "remote-random", + "remote-random-hostname", + "reneg-bytes", + "reneg-pkts", + "reneg-sec", + "replay-window", + "route-delay", + "route-nopull", + "rport", + "secret", + "server-poll-timeout", + "session-timeout", + "single-session", + "sndbuf", + "socket-flags", + "socks-proxy", + "socks-proxy-retry", + "static-challenge", + "tcp-nodelay", + "tls-auth", + "tls-cert-profile", + "tls-cipher", + "tls-ciphersuites", + "tls-client", + "tls-crypt", + "tls-crypt-v2", + "tls-exit", + "tls-groups", + "tls-timeout", + "tls-version-max", + "tls-version-min", + "topology", + "tran-window", + "tun-ipv6", + "tun-mtu", + "tun-mtu-extra", + "txqueuelen", + "verb", + "verify-client-cert", + "verify-hash", + "verify-x509-name", + "x509-username-field", +]; + +/// Accepted in an import and left out of the copy `OpenVPN` runs: they would +/// take over routes or DNS, pick an existing adapter, set script variables, +/// write files as root, or drop to another account. +const DROPPED_DIRECTIVES: &[&str] = &[ + "block-ipv6", + "block-outside-dns", + "dev-node", + "dhcp-option", + "dhcp-release", + "dhcp-renew", + "group", + "ifconfig-noexec", + "ignore-unknown-option", + "ip-win32", + "machine-readable-output", + "max-routes", + "pull-filter", + "push-peer-info", + "redirect-gateway", + "redirect-private", + "register-dns", + "resolv-retry", + "route", + "route-gateway", + "route-ipv6", + "route-method", + "route-metric", + "route-noexec", + "setenv", + "setenv-safe", + "show-net-up", + "status", + "status-version", + "suppress-timestamps", + "syslog", + "tap-sleep", + "user", + "win-sys", + "windows-driver", + "writepid", +]; + +/// Directives that may carry a path the profile author wrote relative to the +/// profile's own directory. +const FILE_DIRECTIVES: &[&str] = &[ + "auth-user-pass", + "ca", + "cert", + "crl-verify", + "extra-certs", + "key", + "pkcs12", + "secret", + "tls-auth", + "tls-crypt", + "tls-crypt-v2", +]; + +const INLINE_BLOCKS: &[&str] = &[ + "auth-user-pass", + "ca", + "cert", + "crl-verify", + "extra-certs", + "http-proxy-user-pass", + "key", + "peer-fingerprint", + "pkcs12", + "secret", + "tls-auth", + "tls-crypt", + "tls-crypt-v2", + "verify-hash", +]; + +/// The only directives `OpenVPN` documents inside ``. +const CONNECTION_DIRECTIVES: &[&str] = &[ + "bind", + "connect-retry", + "connect-retry-max", + "connect-timeout", + "explicit-exit-notify", + "float", + "fragment", + "http-proxy", + "http-proxy-option", + "link-mtu", + "local", + "lport", + "mssfix", + "mtu-disc", + "nobind", + "port", + "proto", + "remote", + "rport", + "socks-proxy", + "tun-mtu", + "tun-mtu-extra", +]; + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Entry { + Directive(Vec), + Inline { tag: String, lines: Vec }, + Connection(Vec>), +} + +/// A profile whose every directive is on the allowlist. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CheckedProfile { + entries: Vec, +} + +impl CheckedProfile { + /// Parses and checks profile text. + /// + /// # Errors + /// + /// Returns [`OpenVpnProfileError`] for a directive or inline block outside + /// the allowlist, an ambiguous or oversized line, or a missing remote. + pub fn parse(text: &str) -> Result { + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + let mut entries = Vec::new(); + let mut lines = text.lines(); + while let Some(raw) = lines.next() { + let line = checked_line(raw)?; + if let Some(tag) = open_tag(line) { + entries.push(parse_block(tag, &mut lines)?); + continue; + } + if let Some(entry) = parse_directive(line, ALLOWED_DIRECTIVES)? { + entries.push(Entry::Directive(entry)); + } + } + let profile = Self { entries }; + if profile.remotes().is_empty() { + return Err(OpenVpnProfileError::NoRemote); + } + Ok(profile) + } + + /// Every `remote` as host and optional port, in file order. + pub(crate) fn remotes(&self) -> Vec<(String, Option)> { + let mut found = Vec::new(); + let mut collect = |tokens: &[String]| { + if tokens.first().is_some_and(|name| name == "remote") { + if let Some(host) = tokens.get(1) { + let port = tokens.get(2).and_then(|port| port.parse().ok()); + found.push((host.clone(), port)); + } + } + }; + for entry in &self.entries { + match entry { + Entry::Directive(tokens) => collect(tokens), + Entry::Connection(directives) => { + directives.iter().for_each(|tokens| collect(tokens)); + } + Entry::Inline { .. } => {} + } + } + found + } + + /// The text `OpenVPN` runs. `base` is the imported profile's directory, so + /// relative key files keep resolving from the copy's new location. + #[must_use] + pub fn render(&self, base: &Path, windows: bool) -> String { + let mut text = String::new(); + for entry in &self.entries { + match entry { + Entry::Directive(tokens) => { + // A legacy Windows `ncp-ciphers` list can include CBC even + // when the helper sets AEAD-only `data-ciphers`. `OpenVPN` + // 2.7 then disables DCO (ADR 0106). + if windows && tokens[0] == "ncp-ciphers" { + continue; + } + push_directive(&mut text, tokens, base); + } + Entry::Inline { tag, lines } => { + text.push_str(&["<", tag, ">\n"].concat()); + for line in lines { + text.push_str(line); + text.push('\n'); + } + text.push_str(&["\n"].concat()); + } + Entry::Connection(directives) => { + text.push_str("\n"); + for tokens in directives { + push_directive(&mut text, tokens, base); + } + text.push_str("\n"); + } + } + } + text + } +} + +fn push_directive(text: &mut String, tokens: &[String], base: &Path) { + text.push_str(&tokens[0]); + for (index, token) in tokens.iter().enumerate().skip(1) { + text.push_str(" \""); + let resolved = if index == 1 && FILE_DIRECTIVES.contains(&tokens[0].as_str()) { + resolve_file(token, base) + } else { + token.clone() + }; + for character in resolved.chars() { + if matches!(character, '"' | '\\') { + text.push('\\'); + } + text.push(character); + } + text.push('"'); + } + text.push('\n'); +} + +fn resolve_file(token: &str, base: &Path) -> String { + if token == "[inline]" || Path::new(token).is_absolute() { + return token.to_owned(); + } + base.join(token).to_string_lossy().into_owned() +} + +fn checked_line(raw: &str) -> Result<&str, OpenVpnProfileError> { + if raw.len() > MAX_LINE_BYTES { + return Err(OpenVpnProfileError::LineTooLong); + } + if raw + .chars() + .any(|character| character.is_control() && character != '\t' && character != '\r') + { + return Err(OpenVpnProfileError::Ambiguous); + } + Ok(raw.trim()) +} + +/// `` on a line of its own. `OpenVPN` compares tags case-sensitively. +fn open_tag(line: &str) -> Option<&str> { + line.strip_prefix('<') + .and_then(|rest| rest.strip_suffix('>')) + .filter(|tag| !tag.is_empty()) +} + +fn parse_block<'text>( + tag: &str, + lines: &mut impl Iterator, +) -> Result { + let connection = tag == "connection"; + if !connection && !INLINE_BLOCKS.contains(&tag) { + return Err(OpenVpnProfileError::ForbiddenDirective(tag.to_owned())); + } + let close = format!(""); + let mut directives = Vec::new(); + let mut content = Vec::new(); + for raw in lines { + let line = checked_line(raw)?; + if line == close { + return Ok(if connection { + Entry::Connection(directives) + } else { + Entry::Inline { + tag: tag.to_owned(), + lines: content, + } + }); + } + // `OpenVPN` ends a block on a prefix match. Key material never starts + // with `<`, so any such line is an attempt to disagree about the end. + if line.starts_with('<') { + return Err(OpenVpnProfileError::Ambiguous); + } + if connection { + if let Some(tokens) = parse_directive(line, CONNECTION_DIRECTIVES)? { + directives.push(tokens); + } + } else { + content.push(line.to_owned()); + } + } + Err(OpenVpnProfileError::UnterminatedBlock) +} + +/// `None` for a blank line, a comment, or a directive the copy leaves out. +fn parse_directive( + line: &str, + allowed: &[&str], +) -> Result>, OpenVpnProfileError> { + let mut tokens = tokenize(line)?; + let Some(first) = tokens.first_mut() else { + return Ok(None); + }; + if let Some(stripped) = first.strip_prefix("--") { + *first = stripped.to_owned(); + } + if DROPPED_DIRECTIVES.contains(&first.as_str()) { + return Ok(None); + } + if !allowed.contains(&first.as_str()) { + let name: String = first + .chars() + .filter(char::is_ascii_graphic) + .take(40) + .collect(); + return Err(OpenVpnProfileError::ForbiddenDirective(name)); + } + Ok(Some(tokens)) +} + +/// Splits a line with `OpenVPN`'s rules: whitespace separates, `"` and `'` +/// quote, a backslash escapes outside single quotes, and `#` or `;` starts a +/// comment only at the beginning of a token. +fn tokenize(line: &str) -> Result, OpenVpnProfileError> { + let mut tokens = Vec::new(); + let mut characters = line.chars().peekable(); + loop { + while characters.next_if(|next| next.is_whitespace()).is_some() {} + match characters.peek() { + None | Some('#' | ';') => return Ok(tokens), + Some(_) => {} + } + let mut token = String::new(); + if let Some(quote) = characters.next_if(|next| matches!(next, '"' | '\'')) { + loop { + match characters.next() { + None => return Err(OpenVpnProfileError::Ambiguous), + Some(next) if next == quote => break, + Some('\\') if quote == '"' => { + token.push(characters.next().ok_or(OpenVpnProfileError::Ambiguous)?); + } + Some(next) => token.push(next), + } + } + if characters.peek().is_some_and(|next| !next.is_whitespace()) { + return Err(OpenVpnProfileError::Ambiguous); + } + } else { + while let Some(next) = characters.next_if(|next| !next.is_whitespace()) { + match next { + '\\' => token.push(characters.next().ok_or(OpenVpnProfileError::Ambiguous)?), + '"' | '\'' => return Err(OpenVpnProfileError::Ambiguous), + _ => token.push(next), + } + } + } + tokens.push(token); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const REMOTE: &str = "client\nremote vpn.example.com 443\n"; + + fn refused(extra: &str) -> OpenVpnProfileError { + CheckedProfile::parse(&format!("{REMOTE}{extra}")).expect_err(extra) + } + + #[test] + fn every_way_to_reach_a_script_or_library_is_refused() { + for extra in [ + "up /tmp/evil.sh\n", + "\"up\" /tmp/evil.sh\n", + "'up' /tmp/evil.sh\n", + "u\\p /tmp/evil.sh\n", + "--up /tmp/evil.sh\n", + " up /tmp/evil.sh\n", + "config /tmp/inner.ovpn\n", + "iproute /tmp/evil.sh\n", + "plugin /tmp/evil.so\n", + "engine /tmp/evil.so\n", + "providers /tmp/evil.so\n", + "pkcs11-providers /tmp/evil.so\n", + "tls-verify /tmp/evil.sh\n", + "tls-crypt-v2-verify /tmp/evil.sh\n", + "client-crresponse /tmp/evil.sh\n", + "management 127.0.0.1 7505\n", + "replay-persist /etc/passwd\n", + "tls-export-cert /etc\n", + "askpass /etc/shadow\n", + "cd /tmp\n", + "chroot /tmp\n", + "log /etc/passwd\n", + "script-security 3\n", + "\n/tmp/evil.sh\n\n", + ] { + assert!( + matches!(refused(extra), OpenVpnProfileError::ForbiddenDirective(_)), + "{extra}" + ); + } + } + + #[test] + fn inline_blocks_cannot_hide_directives_from_the_check() { + // `OpenVPN` closes on a prefix match, so it would leave the block here. + for extra in [ + "\nAAAA\n junk\nup /tmp/evil.sh\n\n", + "\nAAAA\n\n\n\nup /tmp/evil.sh\n\n", + "\nAAAA\n x\nup /tmp/evil.sh\n\n", + ] { + assert!( + matches!(refused(extra), OpenVpnProfileError::Ambiguous), + "{extra}" + ); + } + let long = format!("\n{}\nup /tmp/evil.sh\n\n", "A".repeat(256)); + assert!(matches!(refused(&long), OpenVpnProfileError::LineTooLong)); + assert!(matches!( + refused("\nAAAA\n"), + OpenVpnProfileError::UnterminatedBlock + )); + assert!(matches!( + refused("\nremote vpn.example.com 443\nup /tmp/evil.sh\n\n"), + OpenVpnProfileError::ForbiddenDirective(_) + )); + } + + #[test] + fn setenv_opt_cannot_smuggle_a_directive() { + let profile = + CheckedProfile::parse(&format!("{REMOTE}setenv opt up /tmp/evil.sh\n")).expect("parse"); + assert!(!profile.render(Path::new("/p"), false).contains("evil")); + } + + #[test] + fn quotes_and_control_characters_never_reach_openvpn_unescaped() { + let profile = + CheckedProfile::parse("remote \"a b\\\"c\" 443\nverb 3 # note\n").expect("parse"); + let text = profile.render(Path::new("/p"), false); + assert!(text.contains("remote \"a b\\\"c\" \"443\"")); + assert!(text.contains("verb \"3\"\n")); + assert!(matches!( + refused("auth \"SHA512\n"), + OpenVpnProfileError::Ambiguous + )); + assert!(matches!( + refused("auth SHA\u{0}512\n"), + OpenVpnProfileError::Ambiguous + )); + } + + #[test] + fn rendered_profile_is_stable_when_checked_again() { + let source = "\u{feff}client\r\ndev tun\r\nremote vpn.example.com 443\r\n\ + ; comment\r\nca keys/ca.crt\r\nauth-user-pass\r\n\ + \r\nremote 203.0.113.9 1194 udp\r\n\r\n\ + \r\n-----BEGIN CERTIFICATE-----\r\nAAAA\r\n-----END CERTIFICATE-----\r\n\r\n"; + let profile = CheckedProfile::parse(source).expect("parse"); + assert_eq!( + profile.remotes(), + [ + ("vpn.example.com".to_owned(), Some(443)), + ("203.0.113.9".to_owned(), Some(1194)), + ] + ); + let base = Path::new(if cfg!(windows) { r"C:\vpn" } else { "/vpn" }); + let rendered = profile.render(base, false); + assert!(rendered.contains("-----BEGIN CERTIFICATE-----\nAAAA\n")); + let again = CheckedProfile::parse(&rendered).expect("rendered profile"); + assert_eq!(again.render(base, false), rendered); + assert!(rendered.contains("ca.crt")); + assert!(!rendered.contains("ca \"keys/ca.crt\""), "{rendered}"); + } +} diff --git a/crates/iran-split-config/src/lib.rs b/crates/iran-split-config/src/lib.rs index 1d2e364..f8a47fa 100644 --- a/crates/iran-split-config/src/lib.rs +++ b/crates/iran-split-config/src/lib.rs @@ -608,6 +608,30 @@ pub enum ConfigError { Persist(#[from] tempfile::PersistError), } +/// What replaced settings that could not be read. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RecoveredFrom { + LastSaved, + Defaults, +} + +impl RecoveredFrom { + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::LastSaved => "last_saved", + Self::Defaults => "defaults", + } + } +} + +/// Why settings were replaced at startup. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ConfigRecovery { + pub source: RecoveredFrom, + pub cause: &'static str, +} + #[derive(Debug, Clone)] pub struct ConfigStore { path: PathBuf, @@ -645,6 +669,60 @@ impl ConfigStore { self.load() } + /// Loads settings for startup, and never lets an unreadable file keep the + /// application from opening (ADR 0142). + /// + /// The unreadable file is kept as `.corrupt`. The last settings that were + /// saved successfully are used, or defaults when there are none. + /// + /// # Errors + /// + /// Returns [`ConfigError`] when the file cannot be read from disk, set + /// aside, or replaced. + pub fn load_or_recover(&self) -> Result<(AppConfig, Option), ConfigError> { + // A parser message can quote the offending line, which may hold a + // password, so only the kind of failure leaves this function. + let cause = match self.load_or_create() { + Ok(config) => return Ok((config, None)), + Err(ConfigError::Parse(_)) => "not_valid_toml", + Err(ConfigError::Validation(_)) => "invalid_values", + Err(ConfigError::UnsupportedSchema(_)) => "newer_schema", + Err(ConfigError::Io(cause)) if cause.kind() == std::io::ErrorKind::InvalidData => { + "not_text" + } + Err(cause) => return Err(cause), + }; + fs::copy(&self.path, self.path.with_extension("toml.corrupt"))?; + let saved = Self { + path: self.last_good_path(), + profile: self.profile.clone(), + }; + let restored = saved + .path + .is_file() + .then(|| saved.load()) + .and_then(Result::ok); + let source = if restored.is_some() { + RecoveredFrom::LastSaved + } else { + RecoveredFrom::Defaults + }; + let config = restored.unwrap_or_else(|| { + let mut config = AppConfig::default(); + config.mihomo.isolate_from_installed_app(&self.profile); + config + }); + self.write_atomic(&config)?; + // Platform normalization belongs to a load, so the caller sees the + // same values a later load returns. + let config = self.load()?; + Ok((config, Some(ConfigRecovery { source, cause }))) + } + + fn last_good_path(&self) -> PathBuf { + self.path.with_extension("toml.last-good") + } + /// Loads, migrates, and validates the stored configuration. /// /// # Errors @@ -705,9 +783,18 @@ impl ConfigStore { config.schema_version = CURRENT_SCHEMA_VERSION; config.revision = current.revision.saturating_add(1); self.write_atomic(&config)?; + self.remember_last_good(&config)?; Ok(config) } + fn remember_last_good(&self, config: &AppConfig) -> Result<(), ConfigError> { + Self { + path: self.last_good_path(), + profile: self.profile.clone(), + } + .write_atomic(config) + } + fn backup(&self) -> Result<(), ConfigError> { let backup = self.path.with_extension("toml.bak"); fs::copy(&self.path, backup)?; @@ -969,6 +1056,48 @@ mod tests { ConfigStore::new(path, RuntimeProfile::Production) } + #[test] + fn an_unreadable_settings_file_never_stops_startup() { + let directory = tempfile::tempdir().expect("tempdir"); + let path = directory.path().join("config.toml"); + let store = store(&path); + let mut config = store.load_or_create().expect("create"); + config.behavior.show_taskbar_speed = !config.behavior.show_taskbar_speed; + let saved = store.save(config, 0).expect("save"); + for (broken, cause) in [ + (b"password = \"secret".as_slice(), "not_valid_toml"), + (b"\xff\xfe\x00".as_slice(), "not_text"), + (b"schema_version = 9999\n".as_slice(), "newer_schema"), + ] { + fs::write(&path, broken).expect("break"); + let (loaded, recovery) = store.load_or_recover().expect("recover"); + let recovery = recovery.expect("recovered"); + assert_eq!(recovery.cause, cause); + assert_eq!(recovery.source, RecoveredFrom::LastSaved); + assert_eq!(loaded, saved); + assert_eq!( + fs::read(path.with_extension("toml.corrupt")).expect("kept"), + broken + ); + assert_eq!(store.load().expect("load"), saved); + } + } + + #[test] + fn settings_without_a_saved_copy_fall_back_to_defaults() { + let directory = tempfile::tempdir().expect("tempdir"); + let path = directory.path().join("config.toml"); + fs::write(&path, "[[").expect("break"); + let store = store(&path); + let (config, recovery) = store.load_or_recover().expect("recover"); + assert_eq!(recovery.expect("recovered").source, RecoveredFrom::Defaults); + assert!(config.validate().is_empty()); + assert_eq!( + store.load_or_recover().expect("second start"), + (config, None) + ); + } + #[test] fn defaults_are_valid_and_secret_is_random() { let first = AppConfig::default(); diff --git a/crates/iran-split-core/src/lib.rs b/crates/iran-split-core/src/lib.rs index 3426bde..b6e7ad4 100644 --- a/crates/iran-split-core/src/lib.rs +++ b/crates/iran-split-core/src/lib.rs @@ -11,7 +11,7 @@ use std::{ use thiserror::Error; use tokio::sync::{mpsc, watch, Mutex}; use tokio_util::sync::CancellationToken; -use tracing::{error, info, warn}; +use tracing::{debug, error, info, warn}; use uuid::Uuid; mod proxy_match; @@ -331,6 +331,8 @@ pub struct HelperStatus { pub available: bool, pub authorized: bool, pub version: Option, + /// TUN name the helper was installed with, when it reports one. + pub tun_name: Option, } #[derive(Debug, Clone, PartialEq, Eq, Default)] @@ -750,6 +752,9 @@ pub struct Engine { side_tunnel_connect_timeout: Mutex>, shutting_down: AtomicBool, maintenance: Mutex<()>, + /// One live apply at a time. Two at once overwrite each other's prepared + /// generation, and the loser reverts the user's change. + live_apply: Mutex<()>, } /// Health ticks run every ~10s; three consecutive egress failures (~30s) @@ -796,6 +801,7 @@ impl Engine { side_tunnel_connect_timeout: Mutex::new(None), shutting_down: AtomicBool::new(false), maintenance: Mutex::new(()), + live_apply: Mutex::new(()), }); runtime.spawn(Self::worker(Arc::clone(&engine), receiver)); engine @@ -831,7 +837,7 @@ impl Engine { } pub async fn refresh_health(&self) { - info!( + debug!( event = "health.refresh_started", section = "runtime_health", initiator = "engine", @@ -869,7 +875,7 @@ impl Engine { ), } } - info!( + debug!( event = "health.refresh_completed", section = "runtime_health", initiator = "engine", @@ -912,9 +918,9 @@ impl Engine { event = "client.recovered", section = "clients", initiator = "engine", - cause = "egress_probe_succeeded", + cause = "client_egress_changed", trace_route = "engine->platform_backend->recover_clients", - "an optional client egress came back; refreshing live routing" + "the live client egresses changed; refreshing live routing" ); self.route_refresh_pending.store(true, Ordering::SeqCst); } @@ -1311,6 +1317,9 @@ impl Engine { &self, rebind_host: Option, ) -> Result<(), CoreError> { + let _live_apply = self.live_apply.lock().await; + // Checked after the wait: the stack can stop meanwhile, and a reload + // of a stopped stack would start it again. if !matches!( self.snapshot().phase, StackPhase::Running | StackPhase::Degraded @@ -1620,7 +1629,60 @@ impl Engine { kind = ?item.kind, "operation exceeded its time budget" ); - Err(CoreError::OperationTimeout) + self.clean_up_after_timeout(item).await + } + } + + /// The timed-out work was dropped wherever it happened to be, so nothing + /// rolled it back. A half-started tunnel left behind captures all traffic + /// with no working way out (ADR 0141). + async fn clean_up_after_timeout(&self, item: &WorkItem) -> Result<(), CoreError> { + let rollback = async { + match item.kind { + OperationKind::Start => self.rollback(item.id).await, + OperationKind::Resume => { + self.rollback_pause(item.id).await?; + self.set_paused(self.backend.runtime_health().await); + Ok(()) + } + OperationKind::Reconcile + | OperationKind::Stop + | OperationKind::Pause + | OperationKind::ApplyRules => Ok(()), + } + }; + let cleaned = tokio::time::timeout(self.timeouts.stop, rollback) + .await + .unwrap_or(Err(CoreError::OperationTimeout)); + match cleaned { + Ok(()) => { + info!( + event = "operation.timeout_cleaned", + section = "engine", + initiator = "operation_worker", + cause = "timeout", + trace_id = %item.id, + trace_route = "operation_queue->worker->timeout->rollback", + kind = ?item.kind, + "released owned networking after the timeout" + ); + Err(CoreError::OperationTimeout) + } + Err(cause) => { + error!( + event = "operation.timeout_cleanup_failed", + section = "engine", + initiator = "operation_worker", + cause = %cause, + trace_id = %item.id, + trace_route = "operation_queue->worker->timeout->rollback", + kind = ?item.kind, + "owned networking could not be released after the timeout" + ); + Err(CoreError::TunCleanupFailed(format!( + "operation timed out; rollback failed ({cause})" + ))) + } } } @@ -1930,8 +1992,10 @@ impl Engine { snapshot.tun = ComponentStatus::new(ComponentPhase::Starting, None); snapshot.dns = ComponentStatus::new(ComponentPhase::Starting, None); }); - self.backend.start_core(&generation).await?; + // A failed or timed-out reply does not prove the helper did nothing, + // so a start attempt is rolled back like a started core. *core_started = true; + self.backend.start_core(&generation).await?; self.publish_connect_core_health().await; check_cancelled(cancel)?; @@ -2566,6 +2630,11 @@ mod tests { dns_restore_fails: AtomicBool, kill_proxy_after_handoff: AtomicBool, proxy_client_alive: AtomicBool, + hang_readiness: AtomicBool, + fail_start_reply: AtomicBool, + slow_reload: AtomicBool, + reloading: AtomicUsize, + overlapping_reloads: AtomicUsize, } #[async_trait] @@ -2643,6 +2712,7 @@ mod tests { available: true, authorized: true, version: Some("test".into()), + tun_name: None, }) } @@ -2705,6 +2775,9 @@ mod tests { async fn start_core(&self, _generation: &RuntimeGeneration) -> Result<(), CoreError> { self.starts.fetch_add(1, Ordering::SeqCst); self.process.store(true, Ordering::SeqCst); + if self.fail_start_reply.load(Ordering::SeqCst) { + return Err(CoreError::Platform("helper request timed out".into())); + } Ok(()) } @@ -2714,6 +2787,13 @@ mod tests { _rebind_host: Option, ) -> Result<(), CoreError> { self.reloads.fetch_add(1, Ordering::SeqCst); + if self.reloading.fetch_add(1, Ordering::SeqCst) > 0 { + self.overlapping_reloads.fetch_add(1, Ordering::SeqCst); + } + if self.slow_reload.load(Ordering::SeqCst) { + tokio::time::sleep(Duration::from_millis(60)).await; + } + self.reloading.fetch_sub(1, Ordering::SeqCst); Ok(()) } @@ -2796,6 +2876,9 @@ mod tests { &self, cancel: CancellationToken, ) -> Result { + if self.hang_readiness.load(Ordering::SeqCst) { + tokio::time::sleep(Duration::from_secs(30)).await; + } tokio::select! { () = cancel.cancelled() => return Err(CoreError::Cancelled), () = tokio::time::sleep(Duration::from_millis(300)) => {} @@ -3426,6 +3509,76 @@ mod tests { assert_eq!(backend.starts.load(Ordering::SeqCst), 1); } + async fn wait_until_idle_error(engine: &Engine) -> AppError { + let mut receiver = engine.subscribe(); + tokio::time::timeout(Duration::from_secs(3), async { + loop { + let snapshot = receiver.borrow().clone(); + if snapshot.busy.is_none() { + if let Some(error) = snapshot.last_error { + return error; + } + } + receiver.changed().await.expect("snapshot update"); + } + }) + .await + .expect("operation finished with an error") + } + + #[tokio::test] + async fn a_connect_that_times_out_does_not_leave_the_tunnel_up() { + let backend = Arc::new(FakeBackend::default()); + backend.hang_readiness.store(true, Ordering::SeqCst); + let engine = Engine::new_with_timeouts( + Arc::clone(&backend), + &tokio::runtime::Handle::current(), + Duration::from_millis(150), + Duration::from_secs(1), + ); + engine.start_stack(None).await.expect("start accepted"); + let error = wait_until_idle_error(&engine).await; + assert_eq!(error.code, ErrorCode::OperationTimeout); + assert_eq!(backend.starts.load(Ordering::SeqCst), 1); + assert!(!backend.process.load(Ordering::SeqCst)); + assert!(!backend.tun.load(Ordering::SeqCst)); + assert!(backend.cleanups.load(Ordering::SeqCst) > 0); + } + + #[tokio::test] + async fn a_lost_start_reply_is_rolled_back() { + let backend = Arc::new(FakeBackend::default()); + backend.fail_start_reply.store(true, Ordering::SeqCst); + let engine = Engine::new(Arc::clone(&backend), &tokio::runtime::Handle::current()); + engine.start_stack(None).await.expect("start accepted"); + wait_until_idle_error(&engine).await; + assert!(!backend.process.load(Ordering::SeqCst)); + assert!(backend.cleanups.load(Ordering::SeqCst) > 0); + } + + #[tokio::test] + async fn live_rule_changes_are_applied_one_at_a_time() { + let backend = Arc::new(FakeBackend::default()); + let engine = Engine::new(Arc::clone(&backend), &tokio::runtime::Handle::current()); + engine.start_stack(None).await.expect("start accepted"); + engine + .wait_for_phase(StackPhase::Running, Duration::from_secs(3)) + .await + .expect("running"); + backend.slow_reload.store(true, Ordering::SeqCst); + let (first, second, third) = tokio::join!( + engine.apply_user_rules(), + engine.apply_user_rules(), + engine.apply_user_rules() + ); + first.expect("first apply"); + second.expect("second apply"); + third.expect("third apply"); + assert_eq!(backend.reloads.load(Ordering::SeqCst), 3); + assert_eq!(backend.overlapping_reloads.load(Ordering::SeqCst), 0); + assert_eq!(engine.snapshot().busy, None); + } + #[tokio::test] async fn operation_timeout_clears_the_lifecycle_lock() { let backend = Arc::new(FakeBackend::default()); diff --git a/crates/iran-split-helper-winacl/src/lib.rs b/crates/iran-split-helper-winacl/src/lib.rs index d2e47a6..9288775 100644 --- a/crates/iran-split-helper-winacl/src/lib.rs +++ b/crates/iran-split-helper-winacl/src/lib.rs @@ -4,11 +4,12 @@ //! require an `unsafe` `SECURITY_ATTRIBUTES` pointer when creating a pipe that //! Medium-integrity desktop clients can open. -/// SDDL allowing SYSTEM, Administrators, and local Users at Medium integrity. +/// SDDL allowing SYSTEM, Administrators, and interactively signed-in users at +/// Medium integrity. /// /// `ME` (Medium) is required so a non-elevated desktop process can connect to a /// pipe created by SYSTEM. Remote clients are rejected by the pipe mode flags. -pub const HELPER_PIPE_SDDL: &str = "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GRGW;;;BU)S:(ML;;NW;;;ME)"; +pub const HELPER_PIPE_SDDL: &str = "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GRGW;;;IU)S:(ML;;NW;;;ME)"; #[cfg(windows)] mod windows_impl; @@ -21,8 +22,9 @@ mod tests { use super::HELPER_PIPE_SDDL; #[test] - fn packaged_sddl_allows_users_at_medium_integrity() { - assert!(HELPER_PIPE_SDDL.contains("BU")); + fn packaged_sddl_allows_only_signed_in_users_at_medium_integrity() { + assert!(HELPER_PIPE_SDDL.contains(";;;IU)")); + assert!(!HELPER_PIPE_SDDL.contains("BU") && !HELPER_PIPE_SDDL.contains("WD")); assert!(HELPER_PIPE_SDDL.contains("ME")); assert!(HELPER_PIPE_SDDL.contains("SY")); } diff --git a/crates/iran-split-helper/src/commands.rs b/crates/iran-split-helper/src/commands.rs index dda93d9..5d9640a 100644 --- a/crates/iran-split-helper/src/commands.rs +++ b/crates/iran-split-helper/src/commands.rs @@ -92,6 +92,7 @@ async fn dispatch( protocol_version: PROTOCOL_VERSION, authorized: true, active_generation: supervisor.status().await?.generation_id, + tun_name: Some(supervisor.settings().tun_name.clone()), }), HelperCommand::RegisterRuntimeGeneration { generation_id, @@ -165,6 +166,9 @@ async fn dispatch( HelperCommand::StopSideTunnel { client_id } => { HelperReply::SideTunnel(supervisor.stop_side_tunnel(client_id).await?) } + HelperCommand::ListSideTunnels => { + HelperReply::SideTunnels(supervisor.side_tunnel_statuses().await) + } HelperCommand::EnsureInterfaceRoute { device } => { supervisor.ensure_interface_route(&device).await?; HelperReply::Ack diff --git a/crates/iran-split-helper/src/core_control.rs b/crates/iran-split-helper/src/core_control.rs new file mode 100644 index 0000000..6fb04c8 --- /dev/null +++ b/crates/iran-split-helper/src/core_control.rs @@ -0,0 +1,118 @@ +//! Asks a running Mihomo to drop its TUN before the process is ended. +//! +//! Windows has no signal a windowless process can receive: `taskkill` without +//! `/F` always fails for Mihomo. Disabling the TUN through the controller lets +//! it remove its own routes and firewall filters first (ADR 0141). + +use std::{path::Path, time::Duration}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpStream, +}; + +const REQUEST_TIMEOUT: Duration = Duration::from_secs(2); + +#[derive(Debug, PartialEq, Eq)] +struct Controller { + address: String, + secret: String, +} + +/// Top-level controller address and secret of a generated config. +fn controller(yaml: &str) -> Option { + let value = |key: &str| { + yaml.lines().find_map(|line| { + let rest = line.strip_prefix(key)?.strip_prefix(':')?; + Some(rest.trim().trim_matches(['"', '\'']).to_owned()) + }) + }; + let address = value("external-controller")?; + let secret = value("secret")?; + let plain = |text: &str| !text.is_empty() && text.chars().all(|c| c.is_ascii_graphic()); + (address.starts_with("127.0.0.1:") && plain(&address) && plain(&secret)) + .then_some(Controller { address, secret }) +} + +/// Returns whether Mihomo confirmed that its TUN is disabled. +pub(crate) async fn disable_tun(config: &Path) -> bool { + let Ok(yaml) = std::fs::read_to_string(config) else { + return false; + }; + let Some(controller) = controller(&yaml) else { + return false; + }; + matches!( + tokio::time::timeout(REQUEST_TIMEOUT, request(&controller)).await, + Ok(Ok(true)) + ) +} + +async fn request(controller: &Controller) -> std::io::Result { + const BODY: &str = r#"{"tun":{"enable":false}}"#; + let mut stream = TcpStream::connect(&controller.address).await?; + let message = format!( + "PATCH /configs HTTP/1.1\r\nHost: {}\r\nAuthorization: Bearer {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{BODY}", + controller.address, + controller.secret, + BODY.len() + ); + stream.write_all(message.as_bytes()).await?; + let mut status = [0_u8; 12]; + stream.read_exact(&mut status).await?; + Ok(&status[9..10] == b"2") +} + +#[cfg(test)] +mod tests { + use super::*; + use tokio::net::TcpListener; + + #[test] + fn only_a_loopback_controller_with_a_secret_is_used() { + assert_eq!( + controller("mode: rule\nexternal-controller: 127.0.0.1:19090\nsecret: abc\n"), + Some(Controller { + address: "127.0.0.1:19090".into(), + secret: "abc".into(), + }) + ); + assert_eq!( + controller("external-controller: 10.0.0.1:1\nsecret: a\n"), + None + ); + assert_eq!( + controller("external-controller: 127.0.0.1:1\n secret: nested\n"), + None + ); + } + + #[tokio::test] + async fn the_request_disables_the_tun_and_reads_the_answer() { + for (status, expected) in [("204 No Content", true), ("401 Unauthorized", false)] { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("listen"); + let address = listener.local_addr().expect("address"); + let directory = tempfile::tempdir().expect("tempdir"); + let config = directory.path().join("config.yaml"); + std::fs::write( + &config, + format!("external-controller: {address}\nsecret: s3cret\n"), + ) + .expect("config"); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.expect("accept"); + let mut buffer = vec![0_u8; 1024]; + let size = stream.read(&mut buffer).await.expect("read"); + stream + .write_all(format!("HTTP/1.1 {status}\r\n\r\n").as_bytes()) + .await + .expect("reply"); + String::from_utf8_lossy(&buffer[..size]).into_owned() + }); + assert_eq!(disable_tun(&config).await, expected); + let request = server.await.expect("server"); + assert!(request.starts_with("PATCH /configs HTTP/1.1\r\n")); + assert!(request.contains("Authorization: Bearer s3cret")); + assert!(request.ends_with(r#"{"tun":{"enable":false}}"#)); + } + } +} diff --git a/crates/iran-split-helper/src/lib.rs b/crates/iran-split-helper/src/lib.rs index ca0de19..3c907cf 100644 --- a/crates/iran-split-helper/src/lib.rs +++ b/crates/iran-split-helper/src/lib.rs @@ -1,4 +1,7 @@ +#[cfg(any(windows, test))] +mod core_control; mod openvpn; +mod trusted_binary; use iran_split_ipc::{CleanupReport, ProcessStatus, ServiceLogEntry}; use regex::Regex; @@ -32,6 +35,8 @@ const GRACEFUL_STOP_TIMEOUT: Duration = Duration::from_secs(2); const DESKTOP_ABSENCE_LIMIT: Duration = Duration::from_secs(90); const MIHOMO_STAY_ALIVE: Duration = Duration::from_millis(400); const MAX_LOG_ENTRIES: usize = 2_000; +/// Newest runtime generations left on disk besides the running one. +const GENERATIONS_KEPT: usize = 4; const FIXED_GENERATION_FILES: [&str; 8] = [ "config.yaml", "private.txt", @@ -182,6 +187,7 @@ pub struct Supervisor { registered: Mutex>, logs: Arc>>, pub(crate) side_tunnels: Mutex>, + pub(crate) side_tunnel_slots: Mutex>, desktop_contact: Mutex>, commands_in_flight: AtomicUsize, network_release_pending: AtomicBool, @@ -198,6 +204,7 @@ impl Supervisor { registered: Mutex::new(HashMap::new()), logs: Arc::new(Mutex::new(VecDeque::with_capacity(MAX_LOG_ENTRIES))), side_tunnels: Mutex::new(HashMap::new()), + side_tunnel_slots: Mutex::new(HashMap::new()), desktop_contact: Mutex::new(None), commands_in_flight: AtomicUsize::new(0), network_release_pending: AtomicBool::new(false), @@ -304,11 +311,53 @@ impl Supervisor { .lock() .await .insert(generation_id, expected_sha256.into()); + self.prune_generations(&generations_root, generation_id) + .await; self.push_log("info", "runtime_generation_registered", BTreeMap::new()) .await; Ok(()) } + /// Every Connect and every live rule change publishes about 1 MB. Keep the + /// running generation and the newest few, and drop the rest (ADR 0141). + async fn prune_generations(&self, root: &Path, newest: Uuid) { + let running = match self.child.lock().await.as_ref() { + Some(managed) => Some(managed.generation_id), + // A core that outlived a helper restart has no child record here, + // so its directory cannot be identified and nothing is removed. + None if self.registered.lock().await.len() <= 1 => return, + None => None, + }; + let removed = prune_generation_directories(root, &[Some(newest), running]); + match removed { + Ok(removed) => { + let mut registered = self.registered.lock().await; + for id in &removed { + registered.remove(id); + } + if !removed.is_empty() { + tracing::info!( + event = "helper.generations_pruned", + section = "helper_runtime", + initiator = "helper_command", + cause = "generation_registered", + trace_route = "helper_command->register_generation->prune", + removed = removed.len(), + "removed old runtime generations" + ); + } + } + Err(cause) => tracing::warn!( + event = "helper.generations_prune_failed", + section = "helper_runtime", + initiator = "helper_command", + cause = %cause, + trace_route = "helper_command->register_generation->prune", + "old runtime generations could not be listed" + ), + } + } + /// Starts Mihomo from a previously registered runtime generation. /// /// # Errors @@ -343,7 +392,7 @@ impl Supervisor { if managed.child.try_wait()?.is_none() && managed.generation_id == generation_id { return Ok(process_status(Some(managed))); } - stop_managed_child(managed).await?; + stop_managed_child(&self.settings, managed).await?; *current = None; } @@ -493,7 +542,7 @@ impl Supervisor { async fn stop_inner(&self) -> Result { let mut current = self.child.lock().await; if let Some(managed) = current.as_mut() { - stop_managed_child(managed).await?; + stop_managed_child(&self.settings, managed).await?; } *current = None; // Hold the child lock across the orphan kill so a concurrent start @@ -794,11 +843,14 @@ fn process_status(managed: Option<&ManagedChild>) -> ProcessStatus { ) } -async fn stop_managed_child(managed: &mut ManagedChild) -> Result<(), HelperServiceError> { +async fn stop_managed_child( + settings: &HelperSettings, + managed: &mut ManagedChild, +) -> Result<(), HelperServiceError> { if managed.child.try_wait()?.is_some() { return Ok(()); } - request_graceful_stop(&managed.child); + request_graceful_stop(settings, managed).await; match tokio::time::timeout(GRACEFUL_STOP_TIMEOUT, managed.child.wait()).await { Ok(Ok(_)) => return Ok(()), Ok(Err(error)) => return Err(HelperServiceError::Process(error.to_string())), @@ -819,8 +871,9 @@ async fn stop_managed_child(managed: &mut ManagedChild) -> Result<(), HelperServ } #[cfg(unix)] -fn request_graceful_stop(child: &Child) { - let Some(pid) = child.id() else { +#[allow(clippy::unused_async)] // Windows twin awaits the controller; keep one async call site. +async fn request_graceful_stop(_settings: &HelperSettings, managed: &ManagedChild) { + let Some(pid) = managed.child.id() else { return; }; let Ok(pid) = i32::try_from(pid) else { @@ -844,33 +897,45 @@ fn request_graceful_stop(child: &Child) { } } +/// A windowless process has no graceful stop signal on Windows, so Mihomo is +/// asked to drop its TUN and is then ended. Waiting for it to exit on its own +/// would only use up the timeout. #[cfg(windows)] -fn request_graceful_stop(child: &Child) { - use std::os::windows::process::CommandExt; - const CREATE_NO_WINDOW: u32 = 0x0800_0000; - let Some(pid) = child.id() else { - return; - }; - let result = std::process::Command::new("taskkill") - .args(["/PID", &pid.to_string()]) - .creation_flags(CREATE_NO_WINDOW) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status(); - let cause = match result { - Ok(status) if status.success() => return, - Ok(_) => "taskkill_failed", - Err(_) => "taskkill_spawn_failed", - }; - tracing::warn!( - event = "helper.graceful_stop_failed", - section = "helper_process", - initiator = "helper_process", - cause, - trace_route = "helper_process->stop->taskkill", - "graceful stop failed; the bounded force-stop fallback remains active" - ); +async fn request_graceful_stop(settings: &HelperSettings, managed: &mut ManagedChild) { + let config = settings + .runtime_dir + .join("generations") + .join(managed.generation_id.to_string()) + .join("config.yaml"); + if core_control::disable_tun(&config).await { + tracing::info!( + event = "helper.tun_disabled_before_stop", + section = "helper_process", + initiator = "helper_process", + cause = "controller_confirmed", + trace_route = "helper_process->stop->mihomo_controller", + "Mihomo released its tunnel before the process is ended" + ); + } else { + tracing::warn!( + event = "helper.graceful_stop_failed", + section = "helper_process", + initiator = "helper_process", + cause = "controller_unavailable", + trace_route = "helper_process->stop->mihomo_controller", + "Mihomo did not confirm the tunnel release; ending the process" + ); + } + if let Err(cause) = managed.child.start_kill() { + tracing::warn!( + event = "helper.process_kill_failed", + section = "helper_process", + initiator = "helper_process", + cause = %cause, + trace_route = "helper_process->stop->terminate", + "Mihomo could not be ended; the bounded force-stop fallback remains active" + ); + } } /// Drops cached fake-ip answers (`198.18.0.0/16`) so lookups work again after @@ -1106,6 +1171,45 @@ pub(crate) fn spawn_absence_watch(supervisor: Arc) { }); } +/// Removes every generation except `keep` and the newest few, and returns the +/// removed ids. Entries that are not a generation are never touched. +fn prune_generation_directories(root: &Path, keep: &[Option]) -> io::Result> { + let mut found = Vec::new(); + for entry in fs::read_dir(root)? { + let entry = entry?; + if !entry.file_type()?.is_dir() { + continue; + } + let Some(id) = entry + .file_name() + .to_str() + .and_then(|name| name.parse::().ok()) + else { + continue; + }; + found.push((entry.metadata()?.modified()?, id, entry.path())); + } + found.sort_by(|left, right| right.0.cmp(&left.0)); + let mut removed = Vec::new(); + for (_, id, path) in found.into_iter().skip(GENERATIONS_KEPT) { + if keep.contains(&Some(id)) { + continue; + } + match fs::remove_dir_all(&path) { + Ok(()) => removed.push(id), + Err(cause) => tracing::warn!( + event = "helper.generation_remove_failed", + section = "helper_runtime", + initiator = "helper_command", + cause = %cause.kind(), + trace_route = "helper_command->register_generation->prune", + "an old runtime generation could not be removed" + ), + } + } + Ok(removed) +} + fn collect_generation_files(root: &Path) -> Result, HelperServiceError> { let mut names: Vec = FIXED_GENERATION_FILES .iter() @@ -1776,7 +1880,18 @@ mod tests { started_at: String::new(), }; let started = Instant::now(); - stop_managed_child(&mut managed) + let root = tempfile::tempdir().expect("tempdir"); + let settings = HelperSettings { + authorized_uid: 1000, + authorized_gid: 1000, + socket_path: root.path().join("helper.sock"), + staging_dir: root.path().join("staging"), + runtime_dir: root.path().join("runtime"), + mihomo_binary: root.path().join("mihomo"), + mihomo_sha256: "0".repeat(64), + tun_name: "biflow-test".into(), + }; + stop_managed_child(&settings, &mut managed) .await .expect("process stopped"); let elapsed = started.elapsed(); @@ -2121,6 +2236,38 @@ tun_name = "clash-iran" .expect("identical locked destination should not be overwritten"); } + #[test] + fn old_generations_are_removed_but_never_the_kept_ones() { + let root = tempfile::tempdir().expect("tempdir"); + let mut ids = Vec::new(); + for age in 0..8_u64 { + let id = Uuid::new_v4(); + let path = root.path().join(id.to_string()); + fs::create_dir(&path).expect("generation"); + fs::write(path.join("config.yaml"), b"x").expect("config"); + let directory = fs::File::open(&path); + if let Ok(directory) = directory { + let when = std::time::SystemTime::now() - Duration::from_secs(age * 60); + // Opening a directory for this is Unix-only; elsewhere the + // creation order below is what the count assertion relies on. + drop(directory.set_modified(when)); + } + ids.push(id); + } + fs::create_dir(root.path().join("not-a-generation")).expect("other"); + let running = ids[7]; + let removed = + prune_generation_directories(root.path(), &[Some(ids[0]), Some(running), None]) + .expect("prune"); + assert!(!removed.contains(&ids[0]) && !removed.contains(&running)); + assert!(root.path().join(running.to_string()).is_dir()); + assert!(root.path().join("not-a-generation").is_dir()); + assert!((2..=3).contains(&removed.len()), "{}", removed.len()); + for id in removed { + assert!(!root.path().join(id.to_string()).exists()); + } + } + #[test] fn generation_allowlist_accepts_client_uuid_files_and_rejects_paths() { let id = "11111111-1111-1111-1111-111111111111"; diff --git a/crates/iran-split-helper/src/openvpn.rs b/crates/iran-split-helper/src/openvpn.rs index f4d227f..26b796f 100644 --- a/crates/iran-split-helper/src/openvpn.rs +++ b/crates/iran-split-helper/src/openvpn.rs @@ -4,12 +4,12 @@ //! helper-installed scoped routes only, reject `0.0.0.0/0`, Linux fwmark //! policy table, Windows `interface-name` bind (no policy table). -use super::{redact, HelperServiceError, Supervisor}; +use super::{redact, trusted_binary::trusted_openvpn, HelperServiceError, Supervisor}; use ipnet::IpNet; -use iran_split_clients::{audit_openvpn_profile, openvpn_arguments, sanitize_openvpn_profile}; +use iran_split_clients::{load_openvpn_profile, openvpn_arguments, CheckedProfile}; use iran_split_ipc::SideTunnelStatus; use std::{ - collections::BTreeMap, + collections::{BTreeMap, HashMap}, net::IpAddr, path::{Path, PathBuf}, process::Stdio, @@ -21,8 +21,44 @@ use uuid::Uuid; const DEVICE_POLL_INTERVAL: Duration = Duration::from_millis(250); const OPENVPN_STOP_TIMEOUT: Duration = Duration::from_secs(10); -const DEFAULT_MARK: u32 = 0x1780; -const DEFAULT_TABLE: u32 = 178; +/// First fwmark and routing table. Each running tunnel takes its own pair, so +/// a second tunnel cannot move the first one's marked traffic (ADR 0141). +const FIRST_MARK: u32 = 0x1780; +#[cfg(any(unix, test))] +const FIRST_TABLE: u32 = 178; +#[cfg(any(unix, test))] +const FIRST_RULE_PRIORITY: u32 = 17_800; +const MAX_SIDE_TUNNELS: u32 = 16; + +/// Policy-routing identity of one side tunnel. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct RouteSlot(u32); + +impl RouteSlot { + const fn mark(self) -> u32 { + FIRST_MARK + self.0 + } + + #[cfg(any(unix, test))] + const fn table(self) -> u32 { + FIRST_TABLE + self.0 + } + + #[cfg(any(unix, test))] + const fn priority(self) -> u32 { + FIRST_RULE_PRIORITY + self.0 + } +} + +/// Lowest slot no other tunnel holds. A restarting client keeps its own. +fn claim_slot(slots: &mut HashMap, client_id: Uuid) -> Option { + if let Some(slot) = slots.get(&client_id) { + return Some(RouteSlot(*slot)); + } + let free = (0..MAX_SIDE_TUNNELS).find(|slot| !slots.values().any(|taken| taken == slot))?; + slots.insert(client_id, free); + Some(RouteSlot(free)) +} /// One `StartSideTunnel` request, grouped so the privileged entry point keeps /// a single argument instead of a long positional list. @@ -42,8 +78,7 @@ pub struct SideTunnelRequest<'a> { pub(crate) struct RunningSideTunnel { child: Child, device: String, - routing_mark: u32, - routing_table: u32, + slot: RouteSlot, routes: Vec, policy_installed: bool, /// `OpenVPN` `route-gateway`. Required for a TAP adapter; an on-link @@ -86,10 +121,10 @@ impl Supervisor { "unsupported side-tunnel driver".into(), )); } - let facts = audit_openvpn_profile(profile) + let (facts, checked) = load_openvpn_profile(profile) .map_err(|error| HelperServiceError::SideTunnel(error.to_string()))?; - self.stop_side_tunnel(client_id).await?; let binary = resolve_binary(executable)?; + self.stop_side_tunnel(client_id).await?; let device = format!("tun-{}", &client_id.to_string()[..8]); // Never spawn with an address the engine could not vouch for: a // poisoned or fake-ip answer must not become a --remote. @@ -102,7 +137,7 @@ impl Supervisor { } let auth = auth_file.map(PathBuf::from); let sanitized_profile = - sanitized_profile_copy(&self.settings.runtime_dir, client_id, profile)?; + sanitized_profile_copy(&self.settings.runtime_dir, client_id, profile, &checked)?; let profile = sanitized_profile.as_path(); let (mut child, opened) = self .launch_openvpn(OpenVpnLaunch { @@ -127,17 +162,26 @@ impl Supervisor { )); } install_scoped_routes(&device, &routes).await?; - revert_policy_routing(DEFAULT_MARK, DEFAULT_TABLE).await; - let policy_installed = - install_policy_routing(&device, DEFAULT_MARK, DEFAULT_TABLE, gateway.as_deref()) - .await?; + let slot = + claim_slot(&mut *self.side_tunnel_slots.lock().await, client_id).ok_or_else(|| { + HelperServiceError::SideTunnel("too many side tunnels are running".into()) + })?; + revert_policy_routing(slot).await; + let policy_installed = match install_policy_routing(&device, slot, gateway.as_deref()).await + { + Ok(installed) => installed, + Err(cause) => { + revert_policy_routing(slot).await; + self.side_tunnel_slots.lock().await.remove(&client_id); + return Err(cause); + } + }; self.side_tunnels.lock().await.insert( client_id, RunningSideTunnel { child, device: device.clone(), - routing_mark: DEFAULT_MARK, - routing_table: DEFAULT_TABLE, + slot, routes, policy_installed, sanitized_profile, @@ -158,7 +202,7 @@ impl Supervisor { driver: "openvpn".into(), running: true, device: Some(device), - routing_mark: Some(DEFAULT_MARK), + routing_mark: Some(slot.mark()), }) } @@ -182,7 +226,7 @@ impl Supervisor { .and_then(|tunnel| tunnel.gateway.clone()); #[cfg(windows)] { - install_policy_routing(device, DEFAULT_MARK, DEFAULT_TABLE, gateway.as_deref()).await?; + install_policy_routing(device, RouteSlot(0), gateway.as_deref()).await?; } #[cfg(not(windows))] { @@ -203,10 +247,7 @@ impl Supervisor { ) -> Result { let running = self.side_tunnels.lock().await.remove(&client_id); if let Some(mut running) = running { - revert_scoped_routes(&running.device, &running.routes).await; - if running.policy_installed { - revert_policy_routing(running.routing_mark, running.routing_table).await; - } + self.release_side_tunnel(client_id, &running).await; terminate(&mut running.child).await?; self.push_log( "info", @@ -224,6 +265,62 @@ impl Supervisor { }) } + async fn release_side_tunnel(&self, client_id: Uuid, running: &RunningSideTunnel) { + revert_scoped_routes(&running.device, &running.routes).await; + if running.policy_installed { + revert_policy_routing(running.slot).await; + } + self.side_tunnel_slots.lock().await.remove(&client_id); + } + + /// Reports every side tunnel this helper started. One whose `OpenVPN` + /// process has exited is released here and reported as not running, so + /// the desktop stops showing a dead tunnel as connected (ADR 0141). + pub async fn side_tunnel_statuses(&self) -> Vec { + let mut exited = Vec::new(); + let mut statuses = Vec::new(); + { + let mut tunnels = self.side_tunnels.lock().await; + let mut dead = Vec::new(); + for (id, tunnel) in tunnels.iter_mut() { + let running = matches!(tunnel.child.try_wait(), Ok(None)); + if !running { + dead.push(*id); + } + statuses.push(SideTunnelStatus { + client_id: Some(*id), + driver: "openvpn".into(), + running, + device: running.then(|| tunnel.device.clone()), + routing_mark: running.then(|| tunnel.slot.mark()), + }); + } + for id in dead { + if let Some(tunnel) = tunnels.remove(&id) { + exited.push((id, tunnel)); + } + } + } + for (id, tunnel) in exited { + self.release_side_tunnel(id, &tunnel).await; + tracing::warn!( + event = "side_tunnel.process_exited", + section = "side_tunnel", + initiator = "helper_process", + cause = "openvpn_process_exited", + trace_route = "helper_command->side_tunnel_statuses->release", + "a side tunnel stopped on its own; its routes were released" + ); + self.push_log( + "warn", + "side_tunnel_exited", + BTreeMap::from([("driver".into(), "openvpn".into())]), + ) + .await; + } + statuses + } + pub async fn stop_all_side_tunnels(&self) { let ids: Vec = self.side_tunnels.lock().await.keys().copied().collect(); for id in ids { @@ -330,19 +427,38 @@ fn sanitized_profile_copy( runtime_dir: &Path, client_id: Uuid, profile: &Path, + checked: &CheckedProfile, ) -> Result { - let text = std::fs::read_to_string(profile) - .map_err(|_| HelperServiceError::SideTunnel("profile is unreadable".into()))?; + let base = profile.parent().unwrap_or_else(|| Path::new("/")); std::fs::create_dir_all(runtime_dir).map_err(|error| { HelperServiceError::SideTunnel(format!("could not stage a sanitized profile: {error}")) })?; let copy = runtime_dir.join(format!("openvpn-{client_id}.ovpn")); - std::fs::write(©, sanitize_openvpn_profile(&text, cfg!(windows))).map_err(|error| { + write_private(©, &checked.render(base, cfg!(windows))).map_err(|error| { HelperServiceError::SideTunnel(format!("could not write the sanitized profile: {error}")) })?; Ok(copy) } +/// The copy can hold the profile's private key, so it is never created with +/// the process umask and never follows an existing link. +fn write_private(path: &Path, text: &str) -> std::io::Result<()> { + use std::io::Write; + match std::fs::remove_file(path) { + Ok(()) => {} + Err(cause) if cause.kind() == std::io::ErrorKind::NotFound => {} + Err(cause) => return Err(cause), + } + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + options.open(path)?.write_all(text.as_bytes()) +} + struct OpenedAdapter { name: String, gateway: Option, @@ -513,17 +629,7 @@ async fn wait_for_device( fn resolve_binary(configured: Option<&Path>) -> Result { if let Some(path) = configured { - // Same policy as the Mihomo binary: a configured executable must be a - // regular, non-symlink file before the helper will spawn it as root. - let metadata = std::fs::symlink_metadata(path).map_err(|_| { - HelperServiceError::SideTunnel("the openvpn executable is unreadable".into()) - })?; - if !metadata.file_type().is_file() || metadata.file_type().is_symlink() { - return Err(HelperServiceError::SideTunnel( - "the openvpn executable must be a regular, non-symlink file".into(), - )); - } - return Ok(path.to_path_buf()); + return trusted_openvpn(path); } candidate_binaries() .into_iter() @@ -625,19 +731,19 @@ async fn install_scoped_routes(device: &str, routes: &[IpNet]) -> Result<(), Hel #[cfg(unix)] async fn install_policy_routing( device: &str, - mark: u32, - table: u32, + slot: RouteSlot, _gateway: Option<&str>, ) -> Result { - let table = table.to_string(); - let mark = format!("{mark:#x}"); + let table = slot.table().to_string(); + let mark = format!("{:#x}", slot.mark()); + let priority = slot.priority().to_string(); let installed = ip_command(&[ "route", "replace", "default", "dev", device, "table", &table, ]) .await .is_some() && ip_command(&[ - "rule", "add", "fwmark", &mark, "lookup", &table, "priority", "17800", + "rule", "add", "fwmark", &mark, "lookup", &table, "priority", &priority, ]) .await .is_some(); @@ -652,8 +758,7 @@ async fn install_policy_routing( #[cfg(windows)] async fn install_policy_routing( device: &str, - _mark: u32, - _table: u32, + _slot: RouteSlot, gateway: Option<&str>, ) -> Result { // A high metric keeps this off the system default route. Sockets that @@ -731,16 +836,16 @@ async fn revert_scoped_routes(device: &str, routes: &[IpNet]) { } #[cfg(unix)] -async fn revert_policy_routing(mark: u32, table: u32) { - let table = table.to_string(); - let mark = format!("{mark:#x}"); +async fn revert_policy_routing(slot: RouteSlot) { + let table = slot.table().to_string(); + let mark = format!("{:#x}", slot.mark()); drop(ip_command(&["rule", "del", "fwmark", &mark, "lookup", &table]).await); drop(ip_command(&["route", "flush", "table", &table]).await); } #[cfg(windows)] #[allow(clippy::unused_async)] -async fn revert_policy_routing(_mark: u32, _table: u32) { +async fn revert_policy_routing(_slot: RouteSlot) { // The interface name is not available here. The route is active-only // (`store=active`) and disappears when the adapter closes. } @@ -1067,11 +1172,90 @@ mod tests { } #[test] - fn resolve_binary_accepts_configured_regular_file() { + fn resolve_binary_refuses_a_file_its_owner_can_replace() { + let directory = tempfile::tempdir().expect("tempdir"); + let name = if cfg!(windows) { + "openvpn.exe" + } else { + "openvpn" + }; + let binary = write_regular_file(directory.path(), name, "not really a binary"); + let error = resolve_binary(Some(&binary)).expect_err("user-writable file refused"); + assert!(error.to_string().contains("only an administrator")); + } + + #[test] + fn every_running_tunnel_has_its_own_mark_and_table() { + let mut slots = HashMap::new(); + let (first, second) = (Uuid::new_v4(), Uuid::new_v4()); + let one = claim_slot(&mut slots, first).expect("first"); + let two = claim_slot(&mut slots, second).expect("second"); + assert_ne!(one.mark(), two.mark()); + assert_ne!(one.table(), two.table()); + assert_ne!(one.priority(), two.priority()); + assert_eq!(claim_slot(&mut slots, first), Some(one)); + slots.remove(&first); + assert_eq!(claim_slot(&mut slots, Uuid::new_v4()), Some(one)); + for _ in 0..MAX_SIDE_TUNNELS { + claim_slot(&mut slots, Uuid::new_v4()); + } + assert_eq!(claim_slot(&mut slots, Uuid::new_v4()), None); + } + + #[cfg(unix)] + #[tokio::test] + async fn an_exited_openvpn_is_reported_as_stopped_once() { + let directory = tempfile::tempdir().expect("tempdir"); + let supervisor = Supervisor::new(HelperSettings { + authorized_uid: 1_000, + authorized_gid: 1_000, + socket_path: directory.path().join("helper.sock"), + staging_dir: directory.path().join("staging"), + runtime_dir: directory.path().join("runtime"), + mihomo_binary: directory.path().join("mihomo"), + mihomo_sha256: "0".repeat(64), + tun_name: "biflow-tun".into(), + }); + let mut child = Command::new("/bin/sh") + .args(["-c", "exit 0"]) + .spawn() + .expect("fixture process"); + child.wait().await.expect("fixture exit"); + let client_id = Uuid::new_v4(); + let slot = + claim_slot(&mut *supervisor.side_tunnel_slots.lock().await, client_id).expect("slot"); + supervisor.side_tunnels.lock().await.insert( + client_id, + RunningSideTunnel { + child, + device: "biflow-absent".into(), + slot, + routes: Vec::new(), + policy_installed: false, + gateway: None, + sanitized_profile: directory.path().join("copy.ovpn"), + }, + ); + let statuses = supervisor.side_tunnel_statuses().await; + assert_eq!(statuses.len(), 1); + assert!(!statuses[0].running); + assert_eq!(statuses[0].client_id, Some(client_id)); + assert!(supervisor.side_tunnel_statuses().await.is_empty()); + assert!(supervisor.side_tunnel_slots.lock().await.is_empty()); + } + + #[cfg(unix)] + #[test] + fn the_profile_copy_is_private_and_replaces_a_link() { + use std::os::unix::fs::PermissionsExt; let directory = tempfile::tempdir().expect("tempdir"); - let binary = write_regular_file(directory.path(), "openvpn", "not really a binary"); - let resolved = resolve_binary(Some(&binary)).expect("regular file accepted"); - assert_eq!(resolved, binary); + let victim = write_regular_file(directory.path(), "victim", "keep"); + let copy = directory.path().join("copy.ovpn"); + std::os::unix::fs::symlink(&victim, ©).expect("symlink"); + write_private(©, "client\n").expect("write"); + assert_eq!(fs::read_to_string(&victim).expect("victim"), "keep"); + let mode = fs::metadata(©).expect("metadata").permissions().mode(); + assert_eq!(mode & 0o777, 0o600); } #[test] diff --git a/crates/iran-split-helper/src/trusted_binary.rs b/crates/iran-split-helper/src/trusted_binary.rs new file mode 100644 index 0000000..eb57008 --- /dev/null +++ b/crates/iran-split-helper/src/trusted_binary.rs @@ -0,0 +1,133 @@ +//! Decides which `OpenVPN` executable the helper may run as root or SYSTEM. +//! +//! The path arrives over IPC from an unprivileged desktop process. Running +//! whatever it names would hand that user's account full control of the +//! machine, so only an administrator-installed `openvpn` is accepted: the file +//! and every directory above it must be writable by administrators alone +//! (ADR 0141). + +use super::HelperServiceError; +use std::path::{Path, PathBuf}; + +/// Returns the canonical path of a configured executable, or why it is refused. +pub(crate) fn trusted_openvpn(path: &Path) -> Result { + let refuse = |reason: &str| Err(HelperServiceError::SideTunnel(reason.to_owned())); + let Ok(metadata) = std::fs::symlink_metadata(path) else { + return refuse("the openvpn executable is unreadable"); + }; + if !metadata.file_type().is_file() || metadata.file_type().is_symlink() { + return refuse("the openvpn executable must be a regular, non-symlink file"); + } + let Ok(canonical) = path.canonicalize() else { + return refuse("the openvpn executable is unreadable"); + }; + if !has_openvpn_name(&canonical) { + return refuse("the openvpn executable must be named openvpn"); + } + if !administrators_only(&canonical) { + return refuse( + "the openvpn executable must be installed where only an administrator can change it", + ); + } + Ok(canonical) +} + +fn has_openvpn_name(path: &Path) -> bool { + let expected = if cfg!(windows) { + "openvpn.exe" + } else { + "openvpn" + }; + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| { + if cfg!(windows) { + name.eq_ignore_ascii_case(expected) + } else { + name == expected + } + }) +} + +#[cfg(unix)] +fn administrators_only(canonical: &Path) -> bool { + use std::os::unix::fs::MetadataExt; + canonical.ancestors().all(|part| { + std::fs::symlink_metadata(part) + .is_ok_and(|metadata| root_controlled(metadata.uid(), metadata.mode())) + }) +} + +/// A sticky world-writable directory such as `/tmp` still lets its owner swap +/// the entry, so the sticky bit does not make it acceptable. +#[cfg(unix)] +fn root_controlled(uid: u32, mode: u32) -> bool { + uid == 0 && mode & 0o022 == 0 +} + +#[cfg(windows)] +fn administrators_only(canonical: &Path) -> bool { + under_program_files(&canonical.to_string_lossy()) +} + +/// `Program Files` grants ordinary users read and execute only. The roots are +/// literal because the helper must not take them from a caller's environment. +#[cfg(any(windows, test))] +fn under_program_files(canonical: &str) -> bool { + let path = canonical + .strip_prefix(r"\\?\") + .unwrap_or(canonical) + .to_ascii_lowercase(); + [r"c:\program files\", r"c:\program files (x86)\"] + .iter() + .any(|root| path.starts_with(root)) + && !path.split('\\').any(|part| part == "..") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn program_files_is_the_only_windows_location() { + assert!(under_program_files( + r"\\?\C:\Program Files\OpenVPN\bin\openvpn.exe" + )); + assert!(under_program_files( + r"C:\Program Files (x86)\OpenVPN\bin\openvpn.exe" + )); + for path in [ + r"\\?\C:\Users\me\openvpn.exe", + r"C:\ProgramData\openvpn.exe", + r"C:\Program Files Evil\openvpn.exe", + r"C:\Program Files\..\Users\me\openvpn.exe", + r"\\server\share\Program Files\openvpn.exe", + ] { + assert!(!under_program_files(path), "{path}"); + } + } + + #[cfg(unix)] + #[test] + fn a_user_writable_file_or_directory_is_not_trusted() { + assert!(root_controlled(0, 0o100_755)); + assert!(!root_controlled(1_000, 0o100_755)); + assert!(!root_controlled(0, 0o100_775)); + assert!(!root_controlled(0, 0o041_777)); + let directory = tempfile::tempdir().expect("tempdir"); + let file = directory.path().join("openvpn"); + std::fs::write(&file, b"fixture").expect("fixture"); + let error = trusted_openvpn(&file).expect_err("user-owned file refused"); + assert!(error.to_string().contains("only an administrator")); + } + + #[cfg(target_os = "linux")] + #[test] + fn another_system_program_is_not_openvpn() { + let shell = Path::new("/usr/bin/env"); + if shell.is_file() && !shell.is_symlink() { + let error = trusted_openvpn(shell).expect_err("wrong program"); + assert!(error.to_string().contains("named openvpn")); + } + } +} diff --git a/crates/iran-split-helper/src/windows.rs b/crates/iran-split-helper/src/windows.rs index f80e26f..1e2bf16 100644 --- a/crates/iran-split-helper/src/windows.rs +++ b/crates/iran-split-helper/src/windows.rs @@ -20,6 +20,12 @@ const INSTALL_LOG: &str = r"C:\ProgramData\iran-split\install.log"; /// Builtin\Users. Medium-integrity desktop processes can then write generations /// that the SYSTEM helper later publishes. `(OI)(CI)M` is modify, inherited. const USERS_MODIFY_ACE: &str = "*S-1-5-32-545:(OI)(CI)M"; +/// SYSTEM and Administrators full control; `Builtin\Users` read and execute. +const ADMINISTRATORS_ONLY_ACES: [&str; 3] = [ + "*S-1-5-18:(OI)(CI)F", + "*S-1-5-32-544:(OI)(CI)F", + "*S-1-5-32-545:(OI)(CI)RX", +]; const TASK_NAME: &str = "BiFlowHelper"; const PIPE_READY_TIMEOUT: Duration = Duration::from_secs(15); const PIPE_READY_POLL: Duration = Duration::from_millis(100); @@ -142,6 +148,8 @@ fn install_inner( fs::create_dir_all(&bin)?; fs::create_dir_all(root.join("runtime"))?; fs::create_dir_all(&staging_dir)?; + restrict_to_administrators(&bin)?; + restrict_to_administrators(&root.join("runtime"))?; grant_users_modify(&staging_dir)?; stop_previous_helper(); super::copy_file_unless_same(&helper_src, &helper_dest)?; @@ -256,6 +264,28 @@ fn grant_users_modify(path: &Path) -> Result<(), HelperServiceError> { ))) } +/// `ProgramData` lets ordinary users add files to a new directory. SYSTEM +/// loads its executables from `bin`, so nobody else may place a file there. +fn restrict_to_administrators(path: &Path) -> Result<(), HelperServiceError> { + let output = Command::new("icacls") + .arg(path) + .args(["/inheritance:r", "/grant:r"]) + .args(ADMINISTRATORS_ONLY_ACES) + .creation_flags(CREATE_NO_WINDOW) + .output()?; + if output.status.success() { + return Ok(()); + } + let mut detail = super::single_line(&super::decode_console_output(&output.stderr)); + if detail.is_empty() { + detail = super::single_line(&super::decode_console_output(&output.stdout)); + } + Err(HelperServiceError::Install(format!( + "could not protect the helper directory: {}", + detail.chars().take(300).collect::() + ))) +} + fn register_and_start_task(helper: &Path, config: &Path) -> Result<(), HelperServiceError> { // Keep the task manifest paired with the unique config. A previous NSIS // install can leave the legacy helper-task.xml open while Defender scans diff --git a/crates/iran-split-ipc/src/lib.rs b/crates/iran-split-ipc/src/lib.rs index 46303ee..0c309f9 100644 --- a/crates/iran-split-ipc/src/lib.rs +++ b/crates/iran-split-ipc/src/lib.rs @@ -127,6 +127,8 @@ pub enum HelperCommand { StopSideTunnel { client_id: Uuid, }, + /// Reports which side tunnels still have a live process. + ListSideTunnels, /// Adds the high-metric default route on an adapter Mihomo binds with /// `interface-name`. A TAP adapter must use the `OpenVPN` gateway; an /// existing on-link route is not success. @@ -192,6 +194,13 @@ impl HelperCommand { } } + /// Asked on every health tick. A successful answer changes nothing, so it + /// is not worth a permanent log line; a failure still is. + #[must_use] + pub const fn is_status_poll(&self) -> bool { + matches!(self, Self::GetServiceStatus | Self::ListSideTunnels) + } + #[must_use] pub const fn audit_name(&self) -> &'static str { match self { @@ -208,6 +217,7 @@ impl HelperCommand { Self::PrepareForUpdate => "prepare_for_update", Self::StartSideTunnel { .. } => "start_side_tunnel", Self::StopSideTunnel { .. } => "stop_side_tunnel", + Self::ListSideTunnels => "list_side_tunnels", Self::EnsureInterfaceRoute { .. } => "ensure_interface_route", } } @@ -239,6 +249,7 @@ pub enum HelperReply { Logs(Vec), ReadyForUpdate, SideTunnel(SideTunnelStatus), + SideTunnels(Vec), Ack, Error(HelperError), } @@ -265,6 +276,10 @@ pub struct ServiceStatus { pub protocol_version: u16, pub authorized: bool, pub active_generation: Option, + /// TUN name in the helper's own configuration. `None` from a helper that + /// predates the field. + #[serde(default)] + pub tun_name: Option, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/iran-split-mihomo/src/lib.rs b/crates/iran-split-mihomo/src/lib.rs index d0e5626..33b0586 100644 --- a/crates/iran-split-mihomo/src/lib.rs +++ b/crates/iran-split-mihomo/src/lib.rs @@ -1361,10 +1361,19 @@ struct ConnectionsSnapshot { upload_total: u64, #[serde(rename = "downloadTotal", default)] download_total: u64, - #[serde(default)] + /// Mihomo sends `null`, not an empty list, while nothing is connected. + #[serde(default, deserialize_with = "null_as_empty")] connections: Vec, } +fn null_as_empty<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, + T: Deserialize<'de>, +{ + Option::>::deserialize(deserializer).map(Option::unwrap_or_default) +} + #[derive(Debug, Clone, Deserialize)] struct ConnectionEntry { #[serde(default)] @@ -2415,6 +2424,15 @@ mod tests { assert_eq!(overhead, vec!["a"]); } + #[test] + fn an_idle_core_sends_null_instead_of_a_list() { + let parsed: ConnectionsSnapshot = serde_json::from_str( + r#"{"downloadTotal":0,"uploadTotal":0,"connections":null,"memory":0}"#, + ) + .expect("idle snapshot"); + assert!(parsed.connections.is_empty()); + } + #[test] fn connection_totals_read_clash_field_names() { let parsed: ConnectionsSnapshot = serde_json::from_value(serde_json::json!({ diff --git a/crates/iran-split-platform-linux/src/lib.rs b/crates/iran-split-platform-linux/src/lib.rs index bfbea39..2c6a701 100644 --- a/crates/iran-split-platform-linux/src/lib.rs +++ b/crates/iran-split-platform-linux/src/lib.rs @@ -83,16 +83,19 @@ impl HelperClient { pub async fn request(&self, command: HelperCommand) -> Result { let command_name = command.audit_name(); let request_id = Uuid::new_v4(); - info!( - event = "helper.request_started", - section = "helper_ipc", - initiator = "linux_platform_backend", - cause = "backend_operation", - trace_id = %request_id, - trace_route = "desktop_engine->linux_platform_backend->helper_ipc", - command = command_name, - "helper request started" - ); + let poll = command.is_status_poll(); + if !poll { + info!( + event = "helper.request_started", + section = "helper_ipc", + initiator = "linux_platform_backend", + cause = "backend_operation", + trace_id = %request_id, + trace_route = "desktop_engine->linux_platform_backend->helper_ipc", + command = command_name, + "helper request started" + ); + } if let Err(cause) = command.validate() { error!( event = "helper.request_failed", @@ -108,6 +111,7 @@ impl HelperClient { } let result = self.request_validated(command).await; match &result { + Ok(_) if poll => {} Ok(_) => info!( event = "helper.request_completed", section = "helper_ipc", @@ -251,9 +255,71 @@ impl LinuxBackend { } pub async fn update_config(&self, config: AppConfig) { + let outdated = iran_split_clients::drop_outdated_handles( + &config.clients, + &mut *self.egress_handles.lock().await, + ); + for id in &outdated { + self.client_exit_ips.lock().await.remove(id); + } + if !outdated.is_empty() { + info!( + event = "client.endpoint_changed", + section = "clients", + initiator = "linux_platform_backend", + cause = "settings_saved", + trace_route = "tauri_command->linux_platform_backend->update_config", + clients = outdated.len(), + "dropped verified egress handles that no longer match the saved settings" + ); + } *self.config.write().await = config; } + /// Forgets side tunnels whose process ended on its own (ADR 0141). + async fn drop_exited_side_tunnels(&self) -> bool { + let tracked = self + .egress_handles + .lock() + .await + .iter() + .any(|handle| handle.kind == EgressKind::OwnedSideTunnel); + if !tracked { + return false; + } + // An unreachable helper is not evidence that a tunnel stopped. + let Ok(HelperReply::SideTunnels(statuses)) = + self.helper.request(HelperCommand::ListSideTunnels).await + else { + return false; + }; + let running: Vec = statuses + .iter() + .filter(|status| status.running) + .filter_map(|status| status.client_id) + .collect(); + let exited = iran_split_clients::drop_exited_tunnels( + &running, + &mut *self.egress_handles.lock().await, + ); + for id in &exited { + self.client_exit_ips.lock().await.remove(id); + self.client_failures + .lock() + .await + .insert(*id, iran_split_clients::SIDE_TUNNEL_EXITED.into()); + warn!( + event = "side_tunnel.stopped_unexpectedly", + section = "clients", + initiator = "recover_clients", + cause = "process_exited", + trace_route = "engine->linux_platform_backend->helper", + "a side tunnel is no longer running; its traffic stays blocked until it reconnects" + ); + } + !exited.is_empty() + } + /// Reads at most `maximum` recent helper service log entries. /// /// # Errors @@ -1338,6 +1404,7 @@ impl PlatformBackend for LinuxBackend { available: true, authorized: status.authorized, version: Some(status.helper_version), + tun_name: status.tun_name, }), Ok(_) => Err(CoreError::Platform("unexpected helper status reply".into())), Err(LinuxBackendError::Io(error)) @@ -1365,7 +1432,8 @@ impl PlatformBackend for LinuxBackend { } async fn recover_clients(&self) -> Result { - self.recover_local_proxy_clients().await + let exited = self.drop_exited_side_tunnels().await; + Ok(self.recover_local_proxy_clients().await? || exited) } async fn retry_failed_side_tunnels( @@ -2082,7 +2150,10 @@ fn write_side_tunnel_auth( } let directory = user_data_dir.join("side-tunnel"); fs::create_dir_all(&directory).map_err(|error| platform_error(&error))?; - let mut file = NamedTempFile::new_in(&directory).map_err(|error| platform_error(&error))?; + let mut file = tempfile::Builder::new() + .prefix(iran_split_clients::AUTH_FILE_PREFIX) + .tempfile_in(&directory) + .map_err(|error| platform_error(&error))?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; diff --git a/crates/iran-split-platform-linux/src/system_proxy.rs b/crates/iran-split-platform-linux/src/system_proxy.rs index 0a8b5e2..31bca10 100644 --- a/crates/iran-split-platform-linux/src/system_proxy.rs +++ b/crates/iran-split-platform-linux/src/system_proxy.rs @@ -155,109 +155,163 @@ fn unchanged_after_clear(original: &Snapshot, current: &Snapshot) -> bool { matches!(current.mode.as_str(), "none" | "0" | "") && current == &disabled } -async fn read_current() -> Result, CoreError> { - if which("gsettings") { - return Ok(Some(read_gnome().await?)); +/// Where this desktop session keeps its proxy settings. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Desktop { + Gnome, + /// KDE with the `kreadconfig` / `kwriteconfig` generation that is installed. + Kde(KdeTools), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum KdeTools { + Five, + Six, +} + +impl KdeTools { + const fn read(self) -> &'static str { + match self { + Self::Five => "kreadconfig5", + Self::Six => "kreadconfig6", + } } - if which("kreadconfig5") { - return Ok(Some(read_kde().await?)); + + const fn write(self) -> &'static str { + match self { + Self::Five => "kwriteconfig5", + Self::Six => "kwriteconfig6", + } } - Ok(None) } -async fn apply_disabled() -> Result<(), CoreError> { - if which("gsettings") { - run_ok( - "gsettings", - &["set", "org.gnome.system.proxy", "mode", "none"], - ) - .await?; +/// `gsettings` is installed on most KDE systems too, so its presence does not +/// say which desktop is in use. The session names itself. +fn select_desktop(session: &str, installed: impl Fn(&str) -> bool) -> Option { + let kde = [KdeTools::Six, KdeTools::Five] + .into_iter() + .find(|tools| installed(tools.read()) && installed(tools.write())) + .map(Desktop::Kde); + let gnome = installed("gsettings").then_some(Desktop::Gnome); + let is_kde = session + .split(':') + .any(|name| name.eq_ignore_ascii_case("kde")); + if is_kde { + kde.or(gnome) + } else { + gnome.or(kde) } - if which("kwriteconfig5") { - kde_write("ProxyType", "0").await?; +} + +fn current_desktop() -> Option { + let session = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default(); + select_desktop(&session, which) +} + +async fn read_current() -> Result, CoreError> { + Ok(match current_desktop() { + Some(Desktop::Gnome) => Some(read_gnome().await?), + Some(Desktop::Kde(tools)) => Some(read_kde(tools).await?), + None => None, + }) +} + +async fn apply_disabled() -> Result<(), CoreError> { + match current_desktop() { + Some(Desktop::Gnome) => { + run_ok( + "gsettings", + &["set", "org.gnome.system.proxy", "mode", "none"], + ) + .await + } + Some(Desktop::Kde(tools)) => kde_write(tools, "ProxyType", "0").await, + None => Ok(()), } - Ok(()) } async fn apply_snapshot(snapshot: &Snapshot) -> Result<(), CoreError> { - if which("gsettings") { - run_ok( - "gsettings", - &[ - "set", - "org.gnome.system.proxy.http", - "host", - &snapshot.http_host, - ], - ) - .await?; - run_ok( - "gsettings", - &[ - "set", - "org.gnome.system.proxy.http", - "port", - &snapshot.http_port, - ], - ) - .await?; - run_ok( - "gsettings", - &[ - "set", - "org.gnome.system.proxy.https", - "host", - &snapshot.https_host, - ], - ) - .await?; - run_ok( - "gsettings", - &[ - "set", - "org.gnome.system.proxy.https", - "port", - &snapshot.https_port, - ], - ) - .await?; - run_ok( - "gsettings", - &[ - "set", - "org.gnome.system.proxy.socks", - "host", - &snapshot.socks_host, - ], - ) - .await?; - run_ok( - "gsettings", - &[ - "set", - "org.gnome.system.proxy.socks", - "port", - &snapshot.socks_port, - ], - ) - .await?; - run_ok( - "gsettings", - &["set", "org.gnome.system.proxy", "mode", &snapshot.mode], - ) - .await?; - } - if which("kwriteconfig5") { - apply_kde_snapshot(snapshot).await?; + match current_desktop() { + Some(Desktop::Gnome) => apply_gnome_snapshot(snapshot).await, + Some(Desktop::Kde(tools)) => apply_kde_snapshot(tools, snapshot).await, + None => Ok(()), } +} + +async fn apply_gnome_snapshot(snapshot: &Snapshot) -> Result<(), CoreError> { + run_ok( + "gsettings", + &[ + "set", + "org.gnome.system.proxy.http", + "host", + &snapshot.http_host, + ], + ) + .await?; + run_ok( + "gsettings", + &[ + "set", + "org.gnome.system.proxy.http", + "port", + &snapshot.http_port, + ], + ) + .await?; + run_ok( + "gsettings", + &[ + "set", + "org.gnome.system.proxy.https", + "host", + &snapshot.https_host, + ], + ) + .await?; + run_ok( + "gsettings", + &[ + "set", + "org.gnome.system.proxy.https", + "port", + &snapshot.https_port, + ], + ) + .await?; + run_ok( + "gsettings", + &[ + "set", + "org.gnome.system.proxy.socks", + "host", + &snapshot.socks_host, + ], + ) + .await?; + run_ok( + "gsettings", + &[ + "set", + "org.gnome.system.proxy.socks", + "port", + &snapshot.socks_port, + ], + ) + .await?; + run_ok( + "gsettings", + &["set", "org.gnome.system.proxy", "mode", &snapshot.mode], + ) + .await?; Ok(()) } -async fn read_kde() -> Result { - let proxy_type = kde_read("ProxyType").await?; - let http = parse_kde_proxy(&kde_read("httpProxy").await?); - let https = parse_kde_proxy(&kde_read("httpsProxy").await?); - let socks = parse_kde_proxy(&kde_read("socksProxy").await?); +async fn read_kde(tools: KdeTools) -> Result { + let proxy_type = kde_read(tools, "ProxyType").await?; + let http = parse_kde_proxy(&kde_read(tools, "httpProxy").await?); + let https = parse_kde_proxy(&kde_read(tools, "httpsProxy").await?); + let socks = parse_kde_proxy(&kde_read(tools, "socksProxy").await?); Ok(Snapshot { mode: if proxy_type == "1" { "manual".into() @@ -273,31 +327,48 @@ async fn read_kde() -> Result { }) } -async fn apply_kde_snapshot(snapshot: &Snapshot) -> Result<(), CoreError> { - kde_write( - "httpProxy", - &format!("http://{}:{}", snapshot.http_host, snapshot.http_port), - ) - .await?; - kde_write( - "httpsProxy", - &format!("http://{}:{}", snapshot.https_host, snapshot.https_port), - ) - .await?; - kde_write( - "socksProxy", - &format!("socks://{}:{}", snapshot.socks_host, snapshot.socks_port), - ) - .await?; +async fn apply_kde_snapshot(tools: KdeTools, snapshot: &Snapshot) -> Result<(), CoreError> { + for (key, scheme, host, port) in [ + ( + "httpProxy", + "http", + &snapshot.http_host, + &snapshot.http_port, + ), + ( + "httpsProxy", + "http", + &snapshot.https_host, + &snapshot.https_port, + ), + ( + "socksProxy", + "socks", + &snapshot.socks_host, + &snapshot.socks_port, + ), + ] { + kde_write(tools, key, &kde_proxy_value(scheme, host, port)).await?; + } kde_write( + tools, "ProxyType", if snapshot.mode == "manual" { "1" } else { "0" }, ) .await } -async fn kde_read(key: &str) -> Result { - let output = Command::new("kreadconfig5") +/// KDE separates host and port with a space. An unset entry stays empty. +fn kde_proxy_value(scheme: &str, host: &str, port: &str) -> String { + if host.is_empty() { + String::new() + } else { + format!("{scheme}://{host} {port}") + } +} + +async fn kde_read(tools: KdeTools, key: &str) -> Result { + let output = Command::new(tools.read()) .args([ "--file", "kioslaverc", @@ -318,9 +389,9 @@ async fn kde_read(key: &str) -> Result { } } -async fn kde_write(key: &str, value: &str) -> Result<(), CoreError> { +async fn kde_write(tools: KdeTools, key: &str, value: &str) -> Result<(), CoreError> { run_ok( - "kwriteconfig5", + tools.write(), &[ "--file", "kioslaverc", @@ -338,7 +409,7 @@ fn parse_kde_proxy(value: &str) -> (String, String) { let trimmed = value.trim(); let without_scheme = trimmed.rsplit("://").next().unwrap_or(trimmed); without_scheme - .rsplit_once(':') + .rsplit_once([' ', ':']) .map_or((without_scheme.to_owned(), "0".into()), |(host, port)| { (host.to_owned(), port.to_owned()) }) @@ -486,6 +557,50 @@ mod tests { assert!(saved_proxy_uses(&persist, "127.0.0.1", 12334).unwrap()); } + #[test] + fn the_session_decides_which_desktop_is_read() { + let everything = |_: &str| true; + let only = |names: &'static [&'static str]| move |name: &str| names.contains(&name); + assert_eq!( + select_desktop("KDE", everything), + Some(Desktop::Kde(KdeTools::Six)) + ); + assert_eq!( + select_desktop("ubuntu:GNOME", everything), + Some(Desktop::Gnome) + ); + assert_eq!( + select_desktop("KDE", only(&["gsettings", "kreadconfig5", "kwriteconfig5"])), + Some(Desktop::Kde(KdeTools::Five)) + ); + assert_eq!( + select_desktop("KDE", only(&["gsettings"])), + Some(Desktop::Gnome) + ); + assert_eq!( + select_desktop("", only(&["kreadconfig6", "kwriteconfig6"])), + Some(Desktop::Kde(KdeTools::Six)) + ); + assert_eq!(select_desktop("KDE", only(&[])), None); + } + + #[test] + fn kde_proxy_values_are_read_in_both_forms_and_round_trip() { + for value in ["http://127.0.0.1 12334", "http://127.0.0.1:12334"] { + assert_eq!( + parse_kde_proxy(value), + ("127.0.0.1".to_owned(), "12334".to_owned()) + ); + } + let value = kde_proxy_value("socks", "127.0.0.1", "12334"); + assert_eq!( + parse_kde_proxy(&value), + ("127.0.0.1".to_owned(), "12334".to_owned()) + ); + assert_eq!(kde_proxy_value("http", "", "0"), ""); + assert_eq!(parse_kde_proxy(""), (String::new(), "0".to_owned())); + } + #[test] fn matches_hiddify_http_or_socks() { let snapshot = Snapshot { diff --git a/crates/iran-split-platform-macos/src/lib.rs b/crates/iran-split-platform-macos/src/lib.rs index 54065db..a885398 100644 --- a/crates/iran-split-platform-macos/src/lib.rs +++ b/crates/iran-split-platform-macos/src/lib.rs @@ -83,16 +83,19 @@ impl HelperClient { pub async fn request(&self, command: HelperCommand) -> Result { let command_name = command.audit_name(); let request_id = Uuid::new_v4(); - info!( - event = "helper.request_started", - section = "helper_ipc", - initiator = "macos_platform_backend", - cause = "backend_operation", - trace_id = %request_id, - trace_route = "desktop_engine->macos_platform_backend->helper_ipc", - command = command_name, - "helper request started" - ); + let poll = command.is_status_poll(); + if !poll { + info!( + event = "helper.request_started", + section = "helper_ipc", + initiator = "macos_platform_backend", + cause = "backend_operation", + trace_id = %request_id, + trace_route = "desktop_engine->macos_platform_backend->helper_ipc", + command = command_name, + "helper request started" + ); + } if let Err(cause) = command.validate() { error!( event = "helper.request_failed", @@ -108,6 +111,7 @@ impl HelperClient { } let result = self.request_validated(command).await; match &result { + Ok(_) if poll => {} Ok(_) => info!( event = "helper.request_completed", section = "helper_ipc", @@ -251,9 +255,71 @@ impl MacosBackend { } pub async fn update_config(&self, config: AppConfig) { + let outdated = iran_split_clients::drop_outdated_handles( + &config.clients, + &mut *self.egress_handles.lock().await, + ); + for id in &outdated { + self.client_exit_ips.lock().await.remove(id); + } + if !outdated.is_empty() { + info!( + event = "client.endpoint_changed", + section = "clients", + initiator = "macos_platform_backend", + cause = "settings_saved", + trace_route = "tauri_command->macos_platform_backend->update_config", + clients = outdated.len(), + "dropped verified egress handles that no longer match the saved settings" + ); + } *self.config.write().await = config; } + /// Forgets side tunnels whose process ended on its own (ADR 0141). + async fn drop_exited_side_tunnels(&self) -> bool { + let tracked = self + .egress_handles + .lock() + .await + .iter() + .any(|handle| handle.kind == EgressKind::OwnedSideTunnel); + if !tracked { + return false; + } + // An unreachable helper is not evidence that a tunnel stopped. + let Ok(HelperReply::SideTunnels(statuses)) = + self.helper.request(HelperCommand::ListSideTunnels).await + else { + return false; + }; + let running: Vec = statuses + .iter() + .filter(|status| status.running) + .filter_map(|status| status.client_id) + .collect(); + let exited = iran_split_clients::drop_exited_tunnels( + &running, + &mut *self.egress_handles.lock().await, + ); + for id in &exited { + self.client_exit_ips.lock().await.remove(id); + self.client_failures + .lock() + .await + .insert(*id, iran_split_clients::SIDE_TUNNEL_EXITED.into()); + warn!( + event = "side_tunnel.stopped_unexpectedly", + section = "clients", + initiator = "recover_clients", + cause = "process_exited", + trace_route = "engine->macos_platform_backend->helper", + "a side tunnel is no longer running; its traffic stays blocked until it reconnects" + ); + } + !exited.is_empty() + } + /// Reads at most `maximum` recent helper service log entries. /// /// # Errors @@ -1439,6 +1505,7 @@ impl PlatformBackend for MacosBackend { available: true, authorized: status.authorized, version: Some(status.helper_version), + tun_name: status.tun_name, }), Ok(_) => Err(CoreError::Platform("unexpected helper status reply".into())), Err(MacosBackendError::Io(error)) @@ -1466,7 +1533,8 @@ impl PlatformBackend for MacosBackend { } async fn recover_clients(&self) -> Result { - self.recover_local_proxy_clients().await + let exited = self.drop_exited_side_tunnels().await; + Ok(self.recover_local_proxy_clients().await? || exited) } async fn retry_failed_side_tunnels( @@ -2304,7 +2372,10 @@ fn write_side_tunnel_auth( } let directory = user_data_dir.join("side-tunnel"); fs::create_dir_all(&directory).map_err(|error| platform_error(&error))?; - let mut file = NamedTempFile::new_in(&directory).map_err(|error| platform_error(&error))?; + let mut file = tempfile::Builder::new() + .prefix(iran_split_clients::AUTH_FILE_PREFIX) + .tempfile_in(&directory) + .map_err(|error| platform_error(&error))?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; diff --git a/crates/iran-split-platform-win/src/lib.rs b/crates/iran-split-platform-win/src/lib.rs index efbe100..b23194d 100644 --- a/crates/iran-split-platform-win/src/lib.rs +++ b/crates/iran-split-platform-win/src/lib.rs @@ -102,16 +102,19 @@ impl HelperClient { ) -> Result { let command_name = command.audit_name(); let request_id = Uuid::new_v4(); - info!( - event = "helper.request_started", - section = "helper_ipc", - initiator = "windows_platform_backend", - cause = "backend_operation", - trace_id = %request_id, - trace_route = "desktop_engine->windows_platform_backend->helper_ipc", - command = command_name, - "helper request started" - ); + let poll = command.is_status_poll(); + if !poll { + info!( + event = "helper.request_started", + section = "helper_ipc", + initiator = "windows_platform_backend", + cause = "backend_operation", + trace_id = %request_id, + trace_route = "desktop_engine->windows_platform_backend->helper_ipc", + command = command_name, + "helper request started" + ); + } if let Err(cause) = command.validate() { error!( event = "helper.request_failed", @@ -127,6 +130,7 @@ impl HelperClient { } let result = self.request_validated(command).await; match &result { + Ok(_) if poll => {} Ok(_) => info!( event = "helper.request_completed", section = "helper_ipc", @@ -313,9 +317,71 @@ impl WindowsBackend { } pub async fn update_config(&self, config: AppConfig) { + let outdated = iran_split_clients::drop_outdated_handles( + &config.clients, + &mut *self.egress_handles.lock().await, + ); + for id in &outdated { + self.client_exit_ips.lock().await.remove(id); + } + if !outdated.is_empty() { + info!( + event = "client.endpoint_changed", + section = "clients", + initiator = "windows_platform_backend", + cause = "settings_saved", + trace_route = "tauri_command->windows_platform_backend->update_config", + clients = outdated.len(), + "dropped verified egress handles that no longer match the saved settings" + ); + } *self.config.write().await = config; } + /// Forgets side tunnels whose process ended on its own (ADR 0141). + async fn drop_exited_side_tunnels(&self) -> bool { + let tracked = self + .egress_handles + .lock() + .await + .iter() + .any(|handle| handle.kind == EgressKind::OwnedSideTunnel); + if !tracked { + return false; + } + // An unreachable helper is not evidence that a tunnel stopped. + let Ok(HelperReply::SideTunnels(statuses)) = + self.helper.request(HelperCommand::ListSideTunnels).await + else { + return false; + }; + let running: Vec = statuses + .iter() + .filter(|status| status.running) + .filter_map(|status| status.client_id) + .collect(); + let exited = iran_split_clients::drop_exited_tunnels( + &running, + &mut *self.egress_handles.lock().await, + ); + for id in &exited { + self.client_exit_ips.lock().await.remove(id); + self.client_failures + .lock() + .await + .insert(*id, iran_split_clients::SIDE_TUNNEL_EXITED.into()); + warn!( + event = "side_tunnel.stopped_unexpectedly", + section = "clients", + initiator = "recover_clients", + cause = "process_exited", + trace_route = "engine->windows_platform_backend->helper", + "a side tunnel is no longer running; its traffic stays blocked until it reconnects" + ); + } + !exited.is_empty() + } + /// Reads at most `maximum` recent helper service log entries. /// /// # Errors @@ -588,7 +654,11 @@ impl WindowsBackend { ExecutableSetting::Auto => None, ExecutableSetting::Path(path) => Some(path.clone()), }; - let auth_file = write_side_tunnel_auth(username.as_deref(), password.as_deref())?; + let auth_file = write_side_tunnel_auth( + &self.paths.user_data_dir, + username.as_deref(), + password.as_deref(), + )?; let proxy = self.ready_proxy_endpoint(ready).await; let pinned_remote = self .pin_side_tunnel_remote(&profile, proxy.as_ref()) @@ -1494,6 +1564,7 @@ impl PlatformBackend for WindowsBackend { available: true, authorized: status.authorized, version: Some(status.helper_version), + tun_name: status.tun_name, }), Ok(_) => Err(CoreError::Platform("unexpected helper status reply".into())), Err(WindowsBackendError::Io(error)) if is_helper_absent(&error) => { @@ -1523,7 +1594,8 @@ impl PlatformBackend for WindowsBackend { } async fn recover_clients(&self) -> Result { - self.recover_local_proxy_clients().await + let exited = self.drop_exited_side_tunnels().await; + Ok(self.recover_local_proxy_clients().await? || exited) } async fn retry_failed_side_tunnels( @@ -2301,6 +2373,7 @@ fn discover_local_proxy_binary_in( /// Writes `username\npassword` to a private temp file for `--auth-user-pass`. /// Returns `None` when the instance has no credentials. fn write_side_tunnel_auth( + user_data_dir: &Path, username: Option<&str>, password: Option<&str>, ) -> Result, CoreError> { @@ -2310,7 +2383,12 @@ fn write_side_tunnel_auth( if username.is_empty() { return Ok(None); } - let mut file = NamedTempFile::new().map_err(|error| platform_error(&error))?; + let directory = user_data_dir.join("side-tunnel"); + fs::create_dir_all(&directory).map_err(|error| platform_error(&error))?; + let mut file = tempfile::Builder::new() + .prefix(iran_split_clients::AUTH_FILE_PREFIX) + .tempfile_in(&directory) + .map_err(|error| platform_error(&error))?; writeln!(file, "{username}") .and_then(|()| writeln!(file, "{password}")) .and_then(|()| file.flush()) diff --git a/crates/iran-split-rules/src/lib.rs b/crates/iran-split-rules/src/lib.rs index 9d98196..5739c0c 100644 --- a/crates/iran-split-rules/src/lib.rs +++ b/crates/iran-split-rules/src/lib.rs @@ -870,8 +870,10 @@ impl RuleManager { pub async fn restore( &self, document: DirectRulesDocument, + replaced_revision: u64, ) -> Result { let mut current = self.document.lock().await; + ensure_revision(¤t, replaced_revision)?; self.publish_and_replace(&mut current, document) } @@ -1502,15 +1504,47 @@ mod tests { assert!(manager.add("example.com", 0).await.is_err()); assert_eq!(manager.list().await, previous); assert!(manager - .restore(RoutePinsDocument { - revision: 42, - ..RoutePinsDocument::default() - }) + .restore( + RoutePinsDocument { + revision: 42, + ..RoutePinsDocument::default() + }, + previous.revision, + ) .await .is_err()); assert_eq!(manager.list().await, previous); } + #[tokio::test] + async fn undoing_a_failed_apply_never_removes_a_newer_change() { + let directory = tempfile::tempdir().expect("tempdir"); + let manager = RuleManager::load( + directory.path().join("direct-rules.json"), + Arc::new(FixedResolver), + ) + .expect("manager"); + let before = manager.list().await; + let first = manager + .add("example.com", before.revision) + .await + .expect("first"); + let second = manager + .add("example.org", first.revision) + .await + .expect("second"); + assert!(matches!( + manager.restore(before.clone(), first.revision).await, + Err(RuleError::RevisionConflict { .. }) + )); + assert_eq!(manager.list().await, second); + manager + .restore(first.clone(), second.revision) + .await + .expect("latest change is undone"); + assert_eq!(manager.list().await.pins, first.pins); + } + #[tokio::test] async fn named_lists_cover_create_pin_rebind_and_delete() { let directory = tempfile::tempdir().expect("tempdir"); diff --git a/docs/adr/0013-session-debug-log.md b/docs/adr/0013-session-debug-log.md index 87ef378..3cb72e3 100644 --- a/docs/adr/0013-session-debug-log.md +++ b/docs/adr/0013-session-debug-log.md @@ -40,6 +40,8 @@ subscription links, or other credentials. and result at its side of the IPC boundary. - Include an immediately flushed copy of `debug.log` in every support bundle. +- Periodic polls are logged only when their outcome changes (ADR 0143). + ## Consequences The desktop has one persistent causal trail that a user can locate and send for diff --git a/docs/adr/0141-privileged-helper-trust.md b/docs/adr/0141-privileged-helper-trust.md new file mode 100644 index 0000000..b9c195d --- /dev/null +++ b/docs/adr/0141-privileged-helper-trust.md @@ -0,0 +1,47 @@ +# ADR 0141: Limit what the desktop can ask the privileged helper to run + +## Status + +Accepted + +## Context + +The helper runs as root, or as SYSTEM on Windows, and takes commands from an +unprivileged desktop. `StartSideTunnel` accepted any regular file as the +OpenVPN executable, so a program running as the user could gain full control of +the machine. On Windows the pipe was open to every local account. The profile +check was a list of forbidden words over raw text; `config` includes, quoted +names, `setenv opt`, loadable providers, and a loosely closed inline block all +passed it. + +Two side tunnels shared one firewall mark and routing table, a tunnel that +stopped on its own stayed connected in the interface, and every published +runtime generation stayed on disk. + +## Decision + +- Accept only an executable named `openvpn` whose file and parent directories + are root-owned and not writable by others. On Windows it must be under + `Program Files`. +- Parse a profile once with OpenVPN's own quoting rules, accept only an + allowlist of client directives and inline blocks, and run a copy rendered + from that parse. Routes, DNS, scripts, and file-writing options are refused + or left out. Relative key paths resolve from the imported profile's folder. +- Limit the Windows pipe to SYSTEM, administrators, and interactively signed-in + users. Remove other users' write access to the helper's `bin` and `runtime`. +- Give every running side tunnel its own mark, table, and rule priority. +- `ListSideTunnels` reports live processes. The desktop drops a handle whose + process ended, shows the reason on the card, and reloads routing. Its traffic + stays blocked until it reconnects. +- Keep the running generation and the newest four, and remove the rest. +- Report the helper's TUN name; a Connect after a rename reinstalls the helper. +- Windows cannot signal a windowless process. Ask Mihomo to disable its TUN + through the controller before ending it. +- Remove credential files that a crashed run left behind at the next start. + +## Consequences + +An OpenVPN build in a user-writable folder, including Homebrew's, is refused. A +profile with an uncommon directive is refused by name. The Windows pipe and +directory rules, and the controller request, need a check on a real Windows +host; unit tests cover their inputs only. diff --git a/docs/adr/0142-recover-unreadable-settings.md b/docs/adr/0142-recover-unreadable-settings.md new file mode 100644 index 0000000..4c2a6b1 --- /dev/null +++ b/docs/adr/0142-recover-unreadable-settings.md @@ -0,0 +1,26 @@ +# ADR 0142: Open the app when the settings file is unreadable + +## Status + +Accepted + +## Context + +A damaged or newer `config.toml` stopped application startup. Route pins +already had a recovery path; settings did not. + +## Decision + +- Keep a copy of each successful save as `config.toml.last-good`. +- On startup, set an unreadable file aside as `config.toml.corrupt` and use the + last saved copy, or defaults when there is none. Other I/O errors still stop + startup, because replacing the file would not fix them. +- Tell the user, log `settings.recovered` with a kind of failure only, and add + a `settings_recovered` finding. A parser message can quote a password. +- Refuse a change to the controller, mixed, or DNS port, or to the TUN name, + while the stack is up. Mihomo binds them once at start. + +## Consequences + +The user can always open BiFlow. Edits made by hand after the last save inside +the app are only in the `.corrupt` copy. diff --git a/docs/adr/0143-log-poll-transitions.md b/docs/adr/0143-log-poll-transitions.md new file mode 100644 index 0000000..d6a04b9 --- /dev/null +++ b/docs/adr/0143-log-poll-transitions.md @@ -0,0 +1,26 @@ +# ADR 0143: Log a poll only when its outcome changes + +## Status + +Accepted. Narrows ADR 0013 and ADR 0010 for periodic polls. + +## Context + +`debug.log` is permanent. The interface polls traffic, connections, and network +status every one to thirty seconds, and each poll wrote a start, a result, and +often a third event. One host reached 4.8 GB; an open window added about 5 KB +every second. Real events were hard to find. + +## Decision + +- Polled commands use `trace_poll`: the first failure, a reminder every five + minutes while it lasts, and the recovery. A success writes nothing. +- Health refresh markers and successful helper status requests are `debug` + events, which the file filter leaves out. Failures keep their level. +- User actions, lifecycle steps, and other helper commands still log every + start and result. The file is still never truncated or rotated. + +## Consequences + +The file grows with what happens, not with time. A missing poll event means the +poll kept its last recorded outcome. diff --git a/docs/adr/0144-complete-failed-and-overlapping-operations.md b/docs/adr/0144-complete-failed-and-overlapping-operations.md new file mode 100644 index 0000000..a068424 --- /dev/null +++ b/docs/adr/0144-complete-failed-and-overlapping-operations.md @@ -0,0 +1,42 @@ +# ADR 0144: Finish what a failed or overlapping operation started + +## Status + +Accepted + +## Context + +A timed-out Connect or Resume was dropped where it stood, with no rollback, so +a half-started tunnel could keep capturing traffic. A start whose reply was +lost was treated as never started. Two live rule changes could run together and +replace each other's prepared generation; the loser reverted the user's change, +and that revert could remove a newer one. A verified client handle kept its old +endpoint after the user moved the client to another port. + +A reinstall of portable Hiddify replaced its folder, where that build keeps +subscriptions. On macOS discovery missed the application and stored the Linux +file instead. + +## Decision + +- Roll back a timed-out Start or Resume inside the stop budget, and report a + failed rollback as an incomplete cleanup. +- Treat a start attempt as started for rollback. +- Apply live changes one at a time and check the phase after the wait. Undo a + failed change only while it is still the latest revision. +- Saving settings drops local-proxy handles whose client was removed, disabled, + or moved. +- Carry `hiddify_portable_data` into the new folder before the old one is + removed; if that fails, restore the old folder. Diagnostics and Fresh Hiddify + start use that folder for the portable build. +- macOS discovers `Hiddify.app`, accepts a plain file only when it is a macOS + program, and opens the publisher's disk image instead of installing. +- Read KDE or GNOME proxy settings according to the session, with the Plasma 6 + or 5 tools that are installed. +- Write update scripts beside the privately staged package. +- Treat Mihomo's `null` connection list as empty. + +## Consequences + +A cancelled, timed-out, or failed start ends detached or says why it could not. +Waiting for another live change can delay a pin by up to 30 seconds. diff --git a/docs/adr/README.md b/docs/adr/README.md index 8786177..979dc97 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -144,3 +144,7 @@ Keep this index current. Add a new ADR for each non-obvious change, or update th | [0138](./0138-maintained-timestamps.md) | Use maintained timestamp and URL dependencies | Accepted | | [0139](./0139-hiddify-5-5-5.md) | Use Hiddify 5.5.5 for managed installation | Accepted | | [0140](./0140-hiddify-5-9-15.md) | Verify managed Hiddify 5.9.15 packages | Accepted | +| [0141](./0141-privileged-helper-trust.md) | Limit what the desktop can ask the helper to run | Accepted | +| [0142](./0142-recover-unreadable-settings.md) | Open the app when the settings file is unreadable | Accepted | +| [0143](./0143-log-poll-transitions.md) | Log a poll only when its outcome changes | Accepted | +| [0144](./0144-complete-failed-and-overlapping-operations.md) | Finish what a failed or overlapping operation started | Accepted | diff --git a/package.json b/package.json index 9dec49a..c592b16 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iran-split-desktop-workspace", - "version": "6.2.96", + "version": "6.3.0", "private": true, "packageManager": "pnpm@9.0.1", "engines": { diff --git a/src-tauri/src/deps.rs b/src-tauri/src/deps.rs index ca783f0..c688bca 100644 --- a/src-tauri/src/deps.rs +++ b/src-tauri/src/deps.rs @@ -16,6 +16,9 @@ const USER_AGENT: &str = concat!("BiFlow/", env!("CARGO_PKG_VERSION")); const MAX_DOWNLOAD_BYTES: usize = 180 * 1024 * 1024; const HIDDIFY_VERSION: &str = "v5.9.15"; const HIDDIFY_LINUX_APPIMAGE: &str = "Hiddify-Linux-x64.AppImage"; +const HIDDIFY_MACOS_DMG: &str = "Hiddify-MacOS.dmg"; +/// Where the portable Windows build keeps subscriptions and settings. +const HIDDIFY_PORTABLE_DATA: &str = "hiddify_portable_data"; const HIDDIFY_LINUX_SHA256: &str = "07e6565e8479a6789ca6456924a91ce886e7167f83864f0ba20bc328e9b6e4cb"; const HIDDIFY_WINDOWS_ZIP_SHA256: &str = @@ -107,6 +110,14 @@ pub struct InstallResult { #[must_use] pub fn hiddify_candidates(data: &Path) -> Vec { + if cfg!(target_os = "macos") { + return macos_hiddify_candidates(data, dirs::home_dir().as_deref()); + } + linux_windows_hiddify_candidates(data) +} + +/// Kept separate so every host can test it; macOS never uses this list. +fn linux_windows_hiddify_candidates(data: &Path) -> Vec { let mut candidates = vec![ data.join("bin").join("hiddify"), data.join("bin").join("hiddify-app"), @@ -156,6 +167,38 @@ pub fn hiddify_candidates(data: &Path) -> Vec { candidates } +/// Hiddify on macOS is an application bundle. A plain binary in the managed +/// folder is accepted only when it is a macOS program: an earlier release +/// stored the Linux `AppImage` there (ADR 0141). +fn macos_hiddify_candidates(data: &Path, home: Option<&Path>) -> Vec { + let inner = |bundle: PathBuf| bundle.join("Contents").join("MacOS").join("Hiddify"); + let mut bundles = vec![ + data.join("apps").join("Hiddify.app"), + PathBuf::from("/Applications").join("Hiddify.app"), + ]; + if let Some(home) = home { + bundles.push(home.join("Applications").join("Hiddify.app")); + } + let mut candidates: Vec = bundles.into_iter().map(inner).collect(); + candidates.extend( + [ + data.join("bin").join("hiddify"), + PathBuf::from("/usr/local/bin/hiddify"), + PathBuf::from("/opt/homebrew/bin/hiddify"), + ] + .into_iter() + .filter(|path| starts_like_macos_program(path)), + ); + candidates +} + +fn starts_like_macos_program(path: &Path) -> bool { + let mut magic = [0_u8; 4]; + fs::File::open(path) + .and_then(|mut file| file.read_exact(&mut magic)) + .is_ok_and(|()| is_macho(&magic)) +} + #[must_use] pub fn mihomo_candidates(data: &Path) -> Vec { let mut candidates = Vec::new(); @@ -287,6 +330,16 @@ pub fn install_guide(id: DependencyId) -> InstallGuide { "Finish setup, then restart BiFlow and press Connect.".into(), ], }, + (DependencyId::Hiddify, "macos") => InstallGuide { + id: id.as_str(), + title: "Install Hiddify on macOS".into(), + download_url: hiddify_macos_url(), + steps: vec![ + format!("Download {HIDDIFY_MACOS_DMG} from the official GitHub release."), + "Open it and drag Hiddify into Applications.".into(), + "Open Hiddify once, then return to BiFlow and press Connect.".into(), + ], + }, (DependencyId::Hiddify, _) => InstallGuide { id: id.as_str(), title: "Install Hiddify on Linux".into(), @@ -349,6 +402,25 @@ pub async fn install_dependency( ); fs::create_dir_all(data.join("bin"))?; fs::create_dir_all(data.join("apps"))?; + if id == DependencyId::Hiddify && cfg!(target_os = "macos") { + // The publisher ships a disk image the user drags into Applications. + // The guide opens it; there is nothing BiFlow can install by itself. + warn!( + event = "dependency.manual_install_required", + section = "dependencies", + initiator = "dependency_installer", + cause = "macos_disk_image", + trace_route = "tauri_command->dependency_installer->install_guide", + dependency_id = "hiddify", + "Hiddify must be installed by hand on macOS" + ); + return Ok(InstallResult { + id: id.as_str(), + installed: false, + path: None, + guide: install_guide(id), + }); + } let path = match id { DependencyId::Hiddify => install_hiddify(data).await?, DependencyId::Mihomo => install_mihomo(data, bundled_dependencies).await?, @@ -411,15 +483,18 @@ async fn install_hiddify_linux(data: &Path) -> Result { } async fn install_hiddify_windows(data: &Path) -> Result { - if let Ok(bytes) = download(&hiddify_windows_portable_url()).await { - verify_sha256(&bytes, HIDDIFY_WINDOWS_ZIP_SHA256)?; - return install_hiddify_portable(&bytes, &data.join("apps")); - } + let portable_error = match download(&hiddify_windows_portable_url()).await { + Ok(bytes) => { + verify_sha256(&bytes, HIDDIFY_WINDOWS_ZIP_SHA256)?; + return install_hiddify_portable(&bytes, &data.join("apps")); + } + Err(cause) => cause, + }; warn!( event = "dependency.portable_download_failed", section = "dependencies", initiator = "dependency_installer", - cause = "portable_fetch_failed", + cause = %portable_error, trace_route = "dependency_installer->hiddify_setup_fallback", dependency_id = "hiddify", "portable Hiddify download failed; fetching the setup executable" @@ -496,6 +571,25 @@ fn install_hiddify_portable(bytes: &[u8], apps: &Path) -> Result Result std::io::Result<()> { + let sources = [ + previous.join(HIDDIFY_PORTABLE_DATA), + previous.join("Hiddify").join(HIDDIFY_PORTABLE_DATA), + ]; + let mut names = [ + HIDDIFY_PORTABLE_DATA.to_owned(), + format!("{HIDDIFY_PORTABLE_DATA}.nested"), + ] + .into_iter(); + for source in sources.iter().filter(|source| source.is_dir()) { + let Some(name) = names.next() else { break }; + fs::rename(source, installed.join(name))?; + } + Ok(()) +} + +/// Puts the previous folder back after its data could not be carried over. +fn restore_previous_portable( + staging: tempfile::TempDir, + destination: &Path, + backup: &Path, + cause: std::io::Error, +) -> DepsError { + let rejected = staging.path().join("rejected"); + let restored = carry_portable_data(destination, backup) + .and_then(|()| fs::rename(destination, rejected)) + .and_then(|()| fs::rename(backup, destination)); + if restored.is_err() { + // Everything stays on disk: neither copy of the data may be deleted. + let _retained_backup_directory = staging.keep(); + } + cause.into() +} + async fn install_mihomo(data: &Path, bundled_dependencies: &Path) -> Result { let dest = mihomo_install_path(data); if cfg!(target_os = "windows") { @@ -644,6 +776,12 @@ fn hiddify_linux_appimage_url() -> String { ) } +fn hiddify_macos_url() -> String { + format!( + "https://github.com/hiddify/hiddify-app/releases/download/{HIDDIFY_VERSION}/{HIDDIFY_MACOS_DMG}" + ) +} + fn hiddify_windows_setup_url() -> String { format!( "https://github.com/hiddify/hiddify-app/releases/download/{HIDDIFY_VERSION}/Hiddify-Windows-Setup-x64.exe" @@ -748,8 +886,18 @@ async fn download_with_client(url: &str, direct: bool) -> Result, String Ok(bytes.to_vec()) } +/// Keeps the reason (DNS, TLS, refused) and leaves the address out. fn download_error(error: reqwest::Error) -> String { - error.without_url().to_string() + use std::error::Error as _; + let error = error.without_url(); + let mut message = error.to_string(); + let mut source = error.source(); + while let Some(cause) = source { + message.push_str(": "); + message.push_str(&cause.to_string()); + source = cause.source(); + } + message } fn gunzip(bytes: &[u8]) -> Result, DepsError> { @@ -896,7 +1044,13 @@ fn external_url_command(url: &str, platform: &str) -> Result Result<(), DepsError> { let platform = std::env::consts::OS; let mut command = external_url_command(url, platform)?; - wait_for_browser_handoff(&mut command, platform, Duration::from_secs(5)).await + wait_for_browser_handoff(&mut command, platform, browser_handoff_limit(platform)).await +} + +/// Windows starts `PowerShell` for the handoff, and a cold start behind a virus +/// scanner can take far longer than the handoff itself. +fn browser_handoff_limit(platform: &str) -> Duration { + Duration::from_secs(if platform == "windows" { 30 } else { 5 }) } async fn wait_for_browser_handoff( @@ -997,6 +1151,8 @@ mod tests { guide.download_url, if cfg!(target_os = "windows") { hiddify_windows_setup_url() + } else if cfg!(target_os = "macos") { + hiddify_macos_url() } else { hiddify_linux_appimage_url() } @@ -1025,7 +1181,7 @@ mod tests { let installed = install_hiddify_portable(&bytes, &apps).unwrap(); assert_eq!(installed, destination.join("Hiddify.exe")); assert_eq!( - first_existing(&hiddify_candidates(root.path())), + first_existing(&linux_windows_hiddify_candidates(root.path())), Some(installed.clone()) ); assert!(destination.join("data").join("icudtl.dat").is_file()); @@ -1035,6 +1191,139 @@ mod tests { assert_eq!(fs::read(installed).unwrap(), b"fixture"); } + fn portable_archive() -> Vec { + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + writer + .start_file( + "Hiddify/Hiddify.exe", + zip::write::SimpleFileOptions::default(), + ) + .unwrap(); + writer.write_all(b"new").unwrap(); + writer.finish().unwrap().into_inner() + } + + #[test] + fn reinstalling_portable_hiddify_keeps_the_users_subscriptions() { + for nested in [false, true] { + let root = tempfile::tempdir().unwrap(); + let apps = root.path().join("apps"); + let destination = apps.join("Hiddify"); + let owner = if nested { + destination.join("Hiddify") + } else { + destination.clone() + }; + let data = owner.join(HIDDIFY_PORTABLE_DATA); + fs::create_dir_all(&data).unwrap(); + fs::write(data.join("db.sqlite"), b"subscriptions").unwrap(); + install_hiddify_portable(&portable_archive(), &apps).unwrap(); + let kept = destination.join(HIDDIFY_PORTABLE_DATA).join("db.sqlite"); + assert_eq!(fs::read(kept).unwrap(), b"subscriptions", "nested={nested}"); + assert_eq!(fs::read(destination.join("Hiddify.exe")).unwrap(), b"new"); + } + } + + #[test] + fn both_portable_data_folders_survive_a_reinstall() { + let root = tempfile::tempdir().unwrap(); + let destination = root.path().join("Hiddify"); + for (folder, text) in [ + (destination.clone(), "outer"), + (destination.join("Hiddify"), "inner"), + ] { + let data = folder.join(HIDDIFY_PORTABLE_DATA); + fs::create_dir_all(&data).unwrap(); + fs::write(data.join("db.sqlite"), text).unwrap(); + } + install_hiddify_portable(&portable_archive(), root.path()).unwrap(); + for (folder, text) in [ + (HIDDIFY_PORTABLE_DATA.to_owned(), "outer"), + (format!("{HIDDIFY_PORTABLE_DATA}.nested"), "inner"), + ] { + let kept = destination.join(folder).join("db.sqlite"); + assert_eq!(fs::read_to_string(kept).unwrap(), text); + } + } + + #[test] + fn a_failed_data_move_restores_the_previous_folder() { + let staging = tempfile::tempdir().unwrap(); + let root = tempfile::tempdir().unwrap(); + let destination = root.path().join("Hiddify"); + let backup = staging.path().join("previous"); + fs::create_dir_all(destination.join(HIDDIFY_PORTABLE_DATA)).unwrap(); + fs::write( + destination.join(HIDDIFY_PORTABLE_DATA).join("db.sqlite"), + b"subscriptions", + ) + .unwrap(); + fs::create_dir_all(&backup).unwrap(); + fs::write(backup.join("old.txt"), b"old").unwrap(); + let cause = std::io::Error::other("locked"); + restore_previous_portable(staging, &destination, &backup, cause); + assert!(destination.join("old.txt").is_file()); + assert!(destination + .join(HIDDIFY_PORTABLE_DATA) + .join("db.sqlite") + .is_file()); + } + + #[test] + fn macos_finds_the_application_and_ignores_a_stored_linux_file() { + let root = tempfile::tempdir().unwrap(); + let data = root.path().join("data"); + let home = root.path().join("home"); + fs::create_dir_all(data.join("bin")).unwrap(); + fs::write(data.join("bin").join("hiddify"), b"\x7fELF linux").unwrap(); + let binary = home + .join("Applications") + .join("Hiddify.app") + .join("Contents") + .join("MacOS") + .join("Hiddify"); + fs::create_dir_all(binary.parent().unwrap()).unwrap(); + fs::write(&binary, b"app").unwrap(); + let candidates = macos_hiddify_candidates(&data, Some(&home)); + assert!(candidates.contains(&binary)); + assert!(!candidates.contains(&data.join("bin").join("hiddify"))); + assert!(candidates + .iter() + .all(|path| !path.to_string_lossy().contains("AppImage"))); + fs::write( + data.join("bin").join("hiddify"), + [0xcf, 0xfa, 0xed, 0xfe, 0, 0], + ) + .unwrap(); + assert!(macos_hiddify_candidates(&data, Some(&home)) + .contains(&data.join("bin").join("hiddify"))); + } + + #[test] + fn windows_gets_time_to_start_powershell() { + assert!(browser_handoff_limit("windows") >= Duration::from_secs(20)); + assert_eq!(browser_handoff_limit("linux"), Duration::from_secs(5)); + } + + #[tokio::test] + async fn a_failed_download_names_its_reason_but_not_the_address() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + drop(listener); + let url = format!("http://{address}/private-path"); + let error = reqwest::Client::builder() + .no_proxy() + .build() + .unwrap() + .get(&url) + .send() + .await + .expect_err("nothing listens"); + let message = download_error(error); + assert!(!message.contains("private-path"), "{message}"); + assert!(message.contains(": "), "{message}"); + } + #[test] fn opens_biflow_repository_links() { assert!(open_url_allowed("https://github.com/devlifeX/BiFlow")); @@ -1117,7 +1406,7 @@ mod tests { #[test] fn linux_install_paths_are_under_user_data() { let data = PathBuf::from("/tmp/biflow-user"); - let hiddify = hiddify_candidates(&data); + let hiddify = linux_windows_hiddify_candidates(&data); assert!(hiddify.iter().any(|path| path.ends_with("Hiddify.AppImage") && path.parent().is_some_and(|parent| parent.ends_with("apps")))); assert_eq!(mihomo_candidates(&data)[0], mihomo_install_path(&data)); diff --git a/src-tauri/src/diagnostics.rs b/src-tauri/src/diagnostics.rs index 2679ef9..050190a 100644 --- a/src-tauri/src/diagnostics.rs +++ b/src-tauri/src/diagnostics.rs @@ -3,6 +3,7 @@ use regex::Regex; use serde::Serialize; use serde_json::Value; use std::{ + collections::BTreeMap, fmt::Display, fs::{self, File, OpenOptions}, future::Future, @@ -13,9 +14,9 @@ use std::{ atomic::{AtomicBool, Ordering}, Arc, Mutex, OnceLock, }, - time::Instant, + time::{Duration, Instant}, }; -use tracing::{error, info, info_span, Instrument, Subscriber}; +use tracing::{error, info, info_span, warn, Instrument, Subscriber}; use tracing_subscriber::{fmt::MakeWriter, EnvFilter}; use uuid::Uuid; @@ -492,6 +493,107 @@ where .await } +/// How long a poll that keeps failing stays quiet before it is logged again. +const POLL_FAILURE_REPEAT: Duration = Duration::from_secs(300); + +#[derive(Debug, Clone, Copy)] +struct FailingPoll { + failures: u64, + logged_at: Instant, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PollEvent { + Quiet, + Failed { failures: u64 }, + Recovered { failures: u64 }, +} + +fn poll_event(state: &mut Option, failed: bool, now: Instant) -> PollEvent { + match (state.as_mut(), failed) { + (None, false) => PollEvent::Quiet, + (None, true) => { + *state = Some(FailingPoll { + failures: 1, + logged_at: now, + }); + PollEvent::Failed { failures: 1 } + } + (Some(poll), true) => { + poll.failures += 1; + if now.saturating_duration_since(poll.logged_at) < POLL_FAILURE_REPEAT { + return PollEvent::Quiet; + } + poll.logged_at = now; + PollEvent::Failed { + failures: poll.failures, + } + } + (Some(poll), false) => { + let failures = poll.failures; + *state = None; + PollEvent::Recovered { failures } + } + } +} + +/// Records a poll the interface or a background loop repeats every second or +/// two. Only a change is written: the first failure, a reminder while it lasts, +/// and the recovery. Logging each success grew `debug.log` by hundreds of +/// megabytes a day (ADR 0143). +pub fn record_poll(section: &'static str, action: &'static str, failure: Option<&str>) { + static POLLS: Mutex> = Mutex::new(BTreeMap::new()); + let Ok(mut polls) = POLLS.lock() else { + return; + }; + let mut state = polls.remove(action); + let event = poll_event(&mut state, failure.is_some(), Instant::now()); + if let Some(state) = state { + polls.insert(action, state); + } + drop(polls); + let trace_route = format!("poll->{section}->{action}"); + match event { + PollEvent::Quiet => {} + PollEvent::Failed { failures } => warn!( + event = "poll.failed", + section, + initiator = "periodic_poll", + cause = failure.unwrap_or("unspecified"), + trace_route, + action, + failures, + "a periodic check is failing; repeats stay quiet for a while" + ), + PollEvent::Recovered { failures } => info!( + event = "poll.recovered", + section, + initiator = "periodic_poll", + cause = "check_succeeded", + trace_route, + action, + failures, + "a periodic check works again" + ), + } +} + +/// Runs a command the interface polls. See [`record_poll`]. +pub async fn trace_poll( + section: &'static str, + action: &'static str, + future: F, +) -> Result +where + E: Display, + F: Future>, +{ + let result = future.await; + let failure = result.as_ref().err().map(ToString::to_string); + record_poll(section, action, failure.as_deref()); + result +} + pub fn trace_sync( section: &'static str, initiator: &'static str, @@ -746,6 +848,29 @@ mod tests { assert!(timestamp.parse::().is_ok()); } + #[test] + fn a_poll_is_logged_only_when_its_outcome_changes() { + let start = Instant::now(); + let mut state = None; + assert_eq!(poll_event(&mut state, false, start), PollEvent::Quiet); + assert_eq!( + poll_event(&mut state, true, start), + PollEvent::Failed { failures: 1 } + ); + for _ in 0..50 { + assert_eq!(poll_event(&mut state, true, start), PollEvent::Quiet); + } + assert_eq!( + poll_event(&mut state, true, start + POLL_FAILURE_REPEAT), + PollEvent::Failed { failures: 52 } + ); + assert_eq!( + poll_event(&mut state, false, start), + PollEvent::Recovered { failures: 52 } + ); + assert_eq!(poll_event(&mut state, false, start), PollEvent::Quiet); + } + #[test] fn malformed_event_fallback_keeps_the_explicit_utc_offset() { let sanitized = sanitize_formatted_events(b"invalid JSON\n"); diff --git a/src-tauri/src/environment/apps.rs b/src-tauri/src/environment/apps.rs index 9868336..b5adbc3 100644 --- a/src-tauri/src/environment/apps.rs +++ b/src-tauri/src/environment/apps.rs @@ -328,7 +328,13 @@ pub(super) fn installed_hiddify(context: &CollectContext) -> HiddifyInfo { }); info.misplaced_portable_executable = cfg!(windows) && executable.is_none() - && data_dir.is_some_and(|dir| dir.join("apps/Hiddify/Hiddify/Hiddify.exe").is_file()); + && data_dir.is_some_and(|dir| { + dir.join("apps") + .join("Hiddify") + .join("Hiddify") + .join("Hiddify.exe") + .is_file() + }); info } @@ -340,18 +346,30 @@ fn hiddify_info(data_dir: Option<&Path>) -> HiddifyInfo { data_dir_found: true, ..HiddifyInfo::default() }; - let preferences = dir.join("shared_preferences.json"); + // The portable build keeps its files beside the executable, but Flutter + // still writes its preferences to the per-user folder, under a prefix. + let portable = dir.ends_with("hiddify_portable_data"); + let prefix = if portable { "portable" } else { "flutter" }; + let preferences = if portable { + crate::hiddify_reset::data_dir_candidates() + .into_iter() + .map(|candidate| candidate.join("shared_preferences.json")) + .find(|path| path.is_file()) + .unwrap_or_else(|| dir.join("shared_preferences.json")) + } else { + dir.join("shared_preferences.json") + }; if let Some(value) = read_json(&preferences) { let text = |key: &str| { value - .get(key) + .get(format!("{prefix}.{key}")) .and_then(Value::as_str) .map(|text| text.chars().take(40).collect()) }; - info.service_mode = text("flutter.service-mode"); - info.region = text("flutter.region"); + info.service_mode = text("service-mode"); + info.region = text("region"); info.started_by_user = value - .get("flutter.started_by_user") + .get(format!("{prefix}.started_by_user")) .and_then(Value::as_bool); info.preferences_modified = modified(&preferences); } @@ -951,6 +969,7 @@ mod tests { available: true, authorized: true, version: Some("6.2.0".into()), + tun_name: None, })), ); let encoded = serde_json::to_string(&info).unwrap(); diff --git a/src-tauri/src/environment/mod.rs b/src-tauri/src/environment/mod.rs index 7402906..769af86 100644 --- a/src-tauri/src/environment/mod.rs +++ b/src-tauri/src/environment/mod.rs @@ -180,6 +180,7 @@ pub struct EnvironmentReport { pub clock: ClockInfo, pub install: InstallInfo, pub external_url_opener_available: Option, + pub settings_recovered: Option<&'static str>, pub findings: Vec, pub collection_errors: Vec, } @@ -557,6 +558,7 @@ async fn collect(context: CollectContext) -> EnvironmentReport { report.taskbar_adapter = Some(crate::taskbar::adapter_state()); report.taskbar_speed = Some(crate::taskbar::panel_state()); } + report.settings_recovered = crate::settings_recovered(); report.external_url_opener_available = Some(crate::deps::external_url_opener_available()); report.findings = findings(&report, context.config.as_ref()); report.collection_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); @@ -1211,6 +1213,9 @@ fn findings(report: &EnvironmentReport, config: Option<&AppConfig>) -> Vec P #[cfg(test)] mod tests { + #[test] + fn replaced_settings_are_a_finding() { + let report = EnvironmentReport { + settings_recovered: Some("defaults"), + ..EnvironmentReport::default() + }; + assert!(findings(&report, None).contains(&"settings_recovered:defaults".to_owned())); + } + #[test] fn missing_external_url_opener_is_a_finding_without_vpn_configuration() { for available in [None, Some(true), Some(false)] { @@ -2098,7 +2112,7 @@ clusters: install_kind: "deb", mihomo_path: None, hiddify_executable: None, - hiddify_data_dir: crate::hiddify_reset::resolve_data_dir(), + hiddify_data_dir: crate::hiddify_reset::resolve_data_dir(None), }) .await; assert_eq!(report.system.os, std::env::consts::OS); diff --git a/src-tauri/src/github_update.rs b/src-tauri/src/github_update.rs index b6c56c9..2c3eb00 100644 --- a/src-tauri/src/github_update.rs +++ b/src-tauri/src/github_update.rs @@ -412,19 +412,22 @@ async fn install_deb(package: &Path) -> Result<(), String> { } } +/// The package sits in a folder created for this update alone. A fixed name in +/// the shared temporary folder could be prepared by another local user first. +fn beside_package(package: &Path, name: &str) -> Result { + package + .parent() + .filter(|parent| parent.is_absolute()) + .map(|parent| parent.join(name)) + .ok_or_else(|| "the update package has no staging folder".to_owned()) +} + async fn install_appimage(package: &Path) -> Result<(), String> { let Some(appimage) = std::env::var_os("APPIMAGE") else { return Err("APPIMAGE is not set".into()); }; let dest = PathBuf::from(appimage); - let script = std::env::temp_dir() - .join("biflow-update") - .join("apply-update.sh"); - if let Some(parent) = script.parent() { - tokio::fs::create_dir_all(parent) - .await - .map_err(|error| error.to_string())?; - } + let script = beside_package(package, "apply-update.sh")?; let body = format!( "#!/bin/sh\nPID={}\nSRC={}\nDST={}\nwhile kill -0 \"$PID\" 2>/dev/null; do sleep 1; done\nmv -f \"$SRC\" \"$DST\"\nchmod +x \"$DST\"\nexec \"$DST\"\n", std::process::id(), @@ -458,15 +461,8 @@ async fn install_nsis( current_exe: &Path, expected_version: &str, ) -> Result<(), String> { - let script = std::env::temp_dir() - .join("biflow-update") - .join("apply-update.ps1"); + let script = beside_package(package, "apply-update.ps1")?; let body = nsis_update_script(std::process::id(), package, current_exe, expected_version); - if let Some(parent) = script.parent() { - tokio::fs::create_dir_all(parent) - .await - .map_err(|error| error.to_string())?; - } tokio::fs::write(&script, body) .await .map_err(|error| error.to_string())?; @@ -558,6 +554,17 @@ fn sh_single_quote(value: &str) -> String { mod tests { use super::*; + #[test] + fn update_scripts_are_written_beside_the_package() { + let directory = tempfile::tempdir().expect("tempdir"); + let package = directory.path().join("BiFlow.AppImage"); + assert_eq!( + beside_package(&package, "apply-update.sh").expect("script path"), + directory.path().join("apply-update.sh") + ); + assert!(beside_package(Path::new("BiFlow.AppImage"), "apply-update.sh").is_err()); + } + #[test] fn normalize_strips_v_and_pads() { assert_eq!(normalize_version("v3.6"), "3.6.0"); diff --git a/src-tauri/src/hiddify_reset.rs b/src-tauri/src/hiddify_reset.rs index 12d2b51..a019d60 100644 --- a/src-tauri/src/hiddify_reset.rs +++ b/src-tauri/src/hiddify_reset.rs @@ -45,14 +45,14 @@ pub struct FreshStartReport { /// cannot be moved into the backup, or the executable cannot be launched. pub async fn fresh_start(app: &AppHandle) -> Result { let services = services(app)?; - let data_dir = resolve_data_dir().ok_or_else(|| { + let executable = first_existing(&hiddify_candidates(&services.paths.data)) + .ok_or_else(|| "Hiddify is not installed".to_owned())?; + let data_dir = resolve_data_dir(Some(&executable)).ok_or_else(|| { format!( "could not find Hiddify's data folder (looked in {})", describe(&data_dir_candidates()) ) })?; - let executable = first_existing(&hiddify_candidates(&services.paths.data)) - .ok_or_else(|| "Hiddify is not installed".to_owned())?; info!( event = "hiddify.fresh_start_requested", section = "hiddify_reset", @@ -134,8 +134,19 @@ pub fn data_dir_candidates() -> Vec { candidates } +/// The portable Windows build keeps its data beside its own executable. Using +/// another installation's folder would clear the wrong copy of Hiddify. +#[must_use] +pub fn portable_data_dir(executable: &Path) -> Option { + let directory = executable.parent()?.join("hiddify_portable_data"); + directory.is_dir().then_some(directory) +} + #[must_use] -pub fn resolve_data_dir() -> Option { +pub fn resolve_data_dir(executable: Option<&Path>) -> Option { + if let Some(portable) = executable.and_then(portable_data_dir) { + return Some(portable); + } data_dir_candidates() .into_iter() .find(|path| is_hiddify_dir(path)) @@ -212,8 +223,24 @@ fn copy_dir(source: &Path, destination: &Path) -> Result<(), String> { Ok(()) } +/// A macOS application has to go through Launch Services; its inner program +/// often never opens the proxy port when started directly. +fn launch_command(executable: &Path) -> Command { + let bundle = executable + .ancestors() + .find(|path| path.extension().is_some_and(|extension| extension == "app")); + match bundle { + Some(bundle) if cfg!(target_os = "macos") => { + let mut command = Command::new("/usr/bin/open"); + command.arg(bundle); + command + } + _ => Command::new(executable), + } +} + fn start_hiddify(executable: &Path) -> Result { - Command::new(executable) + launch_command(executable) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()) @@ -270,6 +297,10 @@ async fn stop_hiddify(executable: &Path) -> bool { #[cfg(target_os = "linux")] fn linux_pids_for(executable: &Path) -> Vec { + // The managed entry is a link; `/proc//exe` names the real file. + let executable = executable + .canonicalize() + .unwrap_or_else(|_| executable.to_path_buf()); let Ok(listing) = fs::read_dir("/proc") else { return Vec::new(); }; @@ -453,6 +484,26 @@ mod tests { assert!(!is_hiddify_dir(&unrelated.path().join("missing"))); } + #[test] + fn portable_hiddify_uses_the_folder_beside_its_executable() { + let directory = tempfile::tempdir().expect("tempdir"); + let executable = directory.path().join("Hiddify.exe"); + assert_eq!(super::portable_data_dir(&executable), None); + let data = directory.path().join("hiddify_portable_data"); + fs::create_dir(&data).expect("portable data"); + assert_eq!(super::resolve_data_dir(Some(&executable)), Some(data)); + } + + #[cfg(target_os = "linux")] + #[test] + fn a_linked_executable_still_matches_its_process() { + let directory = tempfile::tempdir().expect("tempdir"); + let link = directory.path().join("hiddify"); + let current = std::env::current_exe().expect("current executable"); + std::os::unix::fs::symlink(current, &link).expect("link"); + assert!(super::linux_pids_for(&link).contains(&std::process::id())); + } + #[test] fn probes_each_candidate_directory_once() { let candidates = super::data_dir_candidates(); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 1e8e8a2..dd6bcae 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -403,6 +403,9 @@ struct BootstrapResult { cloud_rules: CloudRulesStatus, dependencies: Vec, network_status: network::NetworkStatus, + /// Why the settings differ from what the user saved: `last_saved` or + /// `defaults`. `None` on a normal start. + settings_recovered: Option<&'static str>, } #[derive(Debug, Clone, Serialize)] @@ -605,6 +608,7 @@ async fn bootstrap_app(app: AppHandle) -> Result { .map_err(|error| error.to_string())?, dependencies: deps::dependency_status(&services.paths.data), network_status: network::NetworkStatus::default(), + settings_recovered: settings_recovered(), }) }) .await @@ -612,12 +616,9 @@ async fn bootstrap_app(app: AppHandle) -> Result { #[tauri::command] async fn get_network_status(app: AppHandle) -> Result { - diagnostics::trace_action( - "network", - "tauri_command", - "get_network_status", - async move { Ok(services(&app)?.network.check().await) }, - ) + diagnostics::trace_poll("network", "get_network_status", async move { + Ok(services(&app)?.network.check().await) + }) .await } @@ -679,12 +680,9 @@ const TRAFFIC_PROBE_TIMEOUT: Duration = Duration::from_secs(3); #[tauri::command] async fn get_traffic_totals(app: AppHandle) -> Result { - diagnostics::trace_action( - "traffic", - "tauri_command", - "get_traffic_totals", - async move { Ok::<_, String>(sample_traffic(services(&app)?).await) }, - ) + diagnostics::trace_poll("traffic", "get_traffic_totals", async move { + Ok::<_, String>(sample_traffic(services(&app)?).await) + }) .await } @@ -701,16 +699,12 @@ async fn sample_traffic(services: &AppServices) -> traffic::TrafficTotals { ); let (sample, bypass_names) = if connected { match session_traffic_sample(services).await { - Ok((sample, names)) => (Some(sample), names), + Ok((sample, names)) => { + diagnostics::record_poll("traffic", "sample_traffic", None); + (Some(sample), names) + } Err(cause) => { - warn!( - event = "traffic.session_probe_failed", - section = "traffic", - initiator = "get_traffic_totals", - cause = %cause, - trace_route = "tauri_command->mihomo_controller", - "session traffic sample was unavailable; keeping the last total" - ); + diagnostics::record_poll("traffic", "sample_traffic", Some(&cause)); (None, std::collections::BTreeSet::new()) } } @@ -742,6 +736,8 @@ async fn session_traffic_sample( .map_err(|error| error.to_string())?; let platform = if cfg!(windows) { iran_split_mihomo::Platform::Windows + } else if cfg!(target_os = "macos") { + iran_split_mihomo::Platform::Macos } else { iran_split_mihomo::Platform::Linux }; @@ -757,31 +753,17 @@ async fn session_traffic_sample( #[tauri::command] async fn list_active_connections(app: AppHandle) -> Result, String> { - diagnostics::trace_action( - "connections", - "tauri_command", - "list_active_connections", - async move { - let services = services(&app)?; - if !matches!( - services.engine.snapshot().phase, - StackPhase::Running | StackPhase::Degraded - ) { - return Ok(Vec::new()); - } - let rows = active_mihomo_connections(services).await?; - info!( - event = "connections.listed", - section = "connections", - initiator = "tauri_command", - cause = "diagnostics_poll", - trace_route = "tauri_command->mihomo_controller", - count = rows.len(), - "listed live Mihomo connections without host values" - ); - Ok(rows) - }, - ) + diagnostics::trace_poll("connections", "list_active_connections", async move { + let services = services(&app)?; + if !matches!( + services.engine.snapshot().phase, + StackPhase::Running | StackPhase::Degraded + ) { + return Ok(Vec::new()); + } + let rows = active_mihomo_connections(services).await?; + Ok(rows) + }) .await } @@ -979,7 +961,8 @@ async fn prepare_stack_start(app: &AppHandle) -> Result<(), Strin .helper_version .as_deref() .is_some_and(|version| version == version::app_version()); - let helper_needs_reinstall = helper_ready && !helper_version_matches; + let helper_needs_reinstall = + helper_ready && (!helper_version_matches || helper_tun_name_differs(services).await); let statuses = deps::dependency_status(&services.paths.data); let hiddify_required = services .config_store @@ -1029,7 +1012,7 @@ async fn prepare_stack_start(app: &AppHandle) -> Result<(), Strin event = "connect.helper_reinstall_required", section = "stack", initiator = "prepare_stack_start", - cause = "helper_version_mismatch", + cause = "helper_version_or_tun_name_mismatch", trace_route = "start_stack->prepare_stack_start->install_helper", "reinstalling the privileged helper to match the app version" ); @@ -1043,6 +1026,45 @@ async fn prepare_stack_start(app: &AppHandle) -> Result<(), Strin Ok(()) } +/// The helper only manages the TUN named in its own configuration. After a +/// rename in Settings it has to be reinstalled, or cleanup looks for the old +/// interface (ADR 0141). A helper that reports no name is left alone. +async fn helper_tun_name_differs(services: &AppServices) -> bool { + let Ok(status) = services.backend.helper_status().await else { + return false; + }; + let Ok(config) = services.config_store.load() else { + return false; + }; + status + .tun_name + .is_some_and(|name| name != config.mihomo.tun_name) +} + +/// Mihomo binds these once, when it starts. Saving new values under a running +/// stack points every controller call at a port nothing listens on. +fn changes_bound_endpoints( + current: &iran_split_config::MihomoConfig, + draft: &iran_split_config::MihomoConfig, +) -> bool { + current.controller_host != draft.controller_host + || current.controller_port != draft.controller_port + || current.mixed_port != draft.mixed_port + || current.dns_port != draft.dns_port + || current.tun_name != draft.tun_name +} + +/// A failed start counts as detached: a port that is already taken can only +/// be fixed by choosing another one. +fn settings_endpoints_are_free(snapshot: &StackSnapshot) -> bool { + snapshot.busy.is_none() + && match snapshot.phase { + StackPhase::Stopped | StackPhase::Uninitialized | StackPhase::Paused => true, + StackPhase::Error => snapshot.mihomo.phase != ComponentPhase::Running, + _ => false, + } +} + async fn install_required_dependency( services: &AppServices, id: deps::DependencyId, @@ -1197,6 +1219,22 @@ async fn save_settings( .controller_secret .clone_from(¤t.mihomo.controller_secret); draft.sanitize_default_route(); + let snapshot = services.engine.snapshot(); + let detached = settings_endpoints_are_free(&snapshot); + if !detached && changes_bound_endpoints(¤t.mihomo, &draft.mihomo) { + warn!( + event = "settings.save_refused", + section = "settings", + initiator = "tauri_command", + cause = "stack_is_running", + trace_route = "tauri_command->save_settings", + "port and tunnel-name changes wait until the stack is stopped" + ); + return Err( + "Disconnect before changing the ports or the tunnel name, then save again." + .to_owned(), + ); + } let saved = services .config_store .save(draft, expected_revision) @@ -1246,7 +1284,7 @@ async fn discard_client_pins( document.revision = document.revision.saturating_add(1); services .rules - .restore(document.clone()) + .restore(document.clone(), expected_revision) .await .map_err(|error| error.to_string())?; } @@ -1282,7 +1320,7 @@ async fn reassign_client_pins( document.revision = document.revision.saturating_add(1); services .rules - .restore(document.clone()) + .restore(document.clone(), expected_revision) .await .map_err(|error| error.to_string())?; } @@ -1612,11 +1650,18 @@ async fn persist_and_apply_rules( trace_route = "tauri_command->engine->apply_user_rules", "live rule apply failed; restoring the previous document" ); - services - .rules - .restore(previous) - .await - .map_err(|error| error.to_string())?; + // A change saved meanwhile is newer than this one and stays. + if let Err(restore_error) = services.rules.restore(previous, next.revision).await { + warn!( + event = "rules.restore_skipped", + section = "rules", + initiator = "tauri_command", + cause = %restore_error, + trace_route = "tauri_command->rule_manager->restore", + "the previous document was not restored" + ); + return Err(format!("{cause}; {restore_error}")); + } return Err(cause.to_string()); } Ok(next) @@ -2140,6 +2185,7 @@ fn spawn_environment_snapshot(app: &AppHandle, trigger: &'static Err(_) => Err("helper status timed out".to_owned()), }; let data = services.paths.data.clone(); + let hiddify_executable = deps::first_existing(&deps::hiddify_candidates(&data)); let context = environment::CollectContext { app_version: version::app_version().to_owned(), config, @@ -2153,8 +2199,8 @@ fn spawn_environment_snapshot(app: &AppHandle, trigger: &'static github_update::InstallKind::Dmg => "dmg", }, mihomo_path: deps::first_existing(&deps::mihomo_candidates(&data)), - hiddify_executable: deps::first_existing(&deps::hiddify_candidates(&data)), - hiddify_data_dir: hiddify_reset::resolve_data_dir(), + hiddify_data_dir: hiddify_reset::resolve_data_dir(hiddify_executable.as_deref()), + hiddify_executable, data_dir: Some(data), }; environment::snapshot(trigger, context).await; @@ -3348,9 +3394,21 @@ fn create_services(app: &AppHandle) -> Result { let paths = AppPaths::discover(app)?; verify_diagnostics_path(&paths); let config_store = ConfigStore::new(&paths.config, RuntimeProfile::clone(profile::runtime())); - let config = config_store - .load_or_create() + let (config, recovery) = config_store + .load_or_recover() .map_err(|error| error.to_string())?; + if let Some(recovery) = recovery { + SETTINGS_RECOVERED.set(recovery.source.as_str()).ok(); + warn!( + event = "settings.recovered", + section = "startup", + initiator = "create_services", + cause = recovery.cause, + trace_route = "application_process->create_services->config_store", + source = recovery.source.as_str(), + "unreadable settings were set aside and replaced" + ); + } let legacy_pins = iran_split_rules::LegacyPinClients { vpn: config.hiddify_client().map(|client| client.id), openvpn: config @@ -3464,6 +3522,26 @@ fn create_services(app: &AppHandle) -> Result { }, )) }; + match iran_split_clients::clear_stale_auth_files(&paths.data.join("side-tunnel")) { + Ok(0) => {} + Ok(removed) => info!( + event = "side_tunnel.stale_credentials_removed", + section = "startup", + initiator = "create_services", + cause = "previous_run_did_not_exit_cleanly", + trace_route = "application_process->create_services->side_tunnel", + removed, + "removed side-tunnel credential files left by an earlier run" + ), + Err(cause) => warn!( + event = "side_tunnel.stale_credentials_kept", + section = "startup", + initiator = "create_services", + cause = %cause.kind(), + trace_route = "application_process->create_services->side_tunnel", + "side-tunnel credential files from an earlier run could not be removed" + ), + } let runtime = tauri::async_runtime::handle(); let engine = Engine::new(Arc::clone(&backend), runtime.inner()); let rules = RuleManager::load_with_legacy( @@ -3749,6 +3827,13 @@ fn replace_tray_menu(app: &AppHandle, key: tray::TrayMenuKey) -> true } +/// Set once when startup had to replace unreadable settings. +static SETTINGS_RECOVERED: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new(); + +fn settings_recovered() -> Option<&'static str> { + SETTINGS_RECOVERED.get().copied() +} + static TRAY_MENU: std::sync::Mutex> = std::sync::Mutex::new(None); fn setup_tray(app: &tauri::App) -> tauri::Result<()> { @@ -4442,6 +4527,50 @@ mod tests { /// Controller port, TUN name, and generation identity are three separate /// axes of isolation. Remapping the ports must not disturb the TUN name or /// leave the production identity partially applied. + #[test] + fn ports_can_be_changed_after_a_failed_start_but_not_while_running() { + let mut snapshot = StackSnapshot { + phase: StackPhase::Error, + ..StackSnapshot::default() + }; + assert!(settings_endpoints_are_free(&snapshot)); + snapshot.mihomo.phase = ComponentPhase::Running; + assert!(!settings_endpoints_are_free(&snapshot)); + snapshot.mihomo.phase = ComponentPhase::Stopped; + for (phase, free) in [ + (StackPhase::Stopped, true), + (StackPhase::Paused, true), + (StackPhase::Running, false), + (StackPhase::Degraded, false), + ] { + snapshot.phase = phase; + assert_eq!(settings_endpoints_are_free(&snapshot), free, "{phase:?}"); + } + snapshot.phase = StackPhase::Stopped; + snapshot.busy = Some(LifecycleBusy::Connecting); + assert!(!settings_endpoints_are_free(&snapshot)); + } + + #[test] + fn only_values_mihomo_binds_at_start_wait_for_a_disconnect() { + let current = iran_split_config::MihomoConfig::default(); + assert!(!changes_bound_endpoints(¤t, ¤t)); + let mut logging = current.clone(); + logging.direct_dns_servers = vec!["192.0.2.1".into()]; + assert!(!changes_bound_endpoints(¤t, &logging)); + let edits: [fn(&mut iran_split_config::MihomoConfig); 4] = [ + |config| config.controller_port += 1, + |config| config.mixed_port += 1, + |config| config.dns_port += 1, + |config| config.tun_name = "renamed".into(), + ]; + for edit in edits { + let mut draft = current.clone(); + edit(&mut draft); + assert!(changes_bound_endpoints(¤t, &draft)); + } + } + #[test] fn development_remaps_ports_and_tun_without_partial_state() { let mut mihomo = iran_split_config::MihomoConfig::default(); diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index bba7f69..086cac0 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "BiFlow", - "version": "6.2.96", + "version": "6.3.0", "identifier": "app.biflow.desktop", "build": { "beforeDevCommand": "pnpm bundle:check && pnpm --dir apps/desktop dev", diff --git a/version b/version index 971c4de..e7e42a4 100644 --- a/version +++ b/version @@ -1 +1 @@ -6.2.96 +6.3.0 \ No newline at end of file