From 5a89b8d11d0c575d2428639dc43c391238ed8a4c Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 27 Oct 2026 16:31:29 +0300 Subject: [PATCH] windows: autoProxy As upstream's prober: the sites apps reach directly (the Clash API's direct connections here; upstream's inbound access log) are probed through each exit, direct first, every interval and at once for proxy-ctl proxy auto learn. One blocked directly but reached through an exit is routed through it: its exit's local rule-set, which sing-box reloads. Upstream's judgement, ported and tested: block pages, the walk over paths and exits, one exit per network first, strikes against exits that refuse, a new egress discarding what was learned, rechecks once per TTL. Blocks zapret can fix stay direct. The config gains a loopback probe listener per exit (with the hop login, pinned behind the loopback guard) and the learned rules after the user's. proxy-ctl proxy auto list|probe|learn|forget|clear over new API requests (autoProxy scope). Slow sites (slowBelowKiBps) are not routed yet. Co-Authored-By: Claude Opus 5.5 --- windows/Cargo.lock | 16 + windows/README.md | 11 +- windows/crates/ps-core/Cargo.toml | 1 + windows/crates/ps-core/src/autoproxy.rs | 666 ++++++++++++++++++ windows/crates/ps-core/src/config/validate.rs | 4 +- windows/crates/ps-core/src/lib.rs | 1 + .../crates/ps-core/src/render/autoproxy.rs | 94 +++ windows/crates/ps-core/src/render/mod.rs | 11 +- windows/crates/ps-core/src/render/routing.rs | 7 +- windows/crates/ps-core/src/render/sing_box.rs | 10 +- windows/crates/ps-core/tests/render.rs | 37 + windows/crates/ps-ctl/src/main.rs | 105 +++ windows/crates/ps-ipc/src/lib.rs | 20 + windows/crates/ps-service/src/api.rs | 43 ++ windows/crates/ps-service/src/autoproxy.rs | 605 ++++++++++++++++ windows/crates/ps-service/src/clash.rs | 5 + windows/crates/ps-service/src/main.rs | 3 + windows/crates/ps-service/src/service.rs | 8 + windows/release-notes/0.2.0-pre.1.md | 3 +- 19 files changed, 1640 insertions(+), 10 deletions(-) create mode 100644 windows/crates/ps-core/src/autoproxy.rs create mode 100644 windows/crates/ps-core/src/render/autoproxy.rs create mode 100644 windows/crates/ps-service/src/autoproxy.rs diff --git a/windows/Cargo.lock b/windows/Cargo.lock index 8d02e7e..03a26f6 100644 --- a/windows/Cargo.lock +++ b/windows/Cargo.lock @@ -4992,6 +4992,7 @@ dependencies = [ "indexmap", "ipnet", "percent-encoding", + "psl", "regex", "serde", "serde_json", @@ -5065,6 +5066,21 @@ dependencies = [ "zip", ] +[[package]] +name = "psl" +version = "2.1.245" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46cce9bc841c0eeb395275a775d11e3cc91b904e6ab370a9a42369e111b3038e" +dependencies = [ + "psl-types", +] + +[[package]] +name = "psl-types" +version = "2.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac" + [[package]] name = "pulp" version = "0.22.3" diff --git a/windows/README.md b/windows/README.md index fc3b83f..4892c55 100644 --- a/windows/README.md +++ b/windows/README.md @@ -26,14 +26,15 @@ tray icon) or with `proxy-ctl`, as upstream's is. | Tor | `tor`: the Tor Project's own Windows build (the Expert Bundle, signed, pinned), with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy | | AmneziaWG | `amneziaWg` profiles as outbounds, from a `.conf`, an AmneziaVPN `vpn://` link or settings: `"userspace"` (wireproxy-awg, built from upstream's source, AmneziaWG's obfuscation kept, no driver) or `"singBox"` (plain WireGuard). WARP devices take either kind too | | WARP | `warp` with `asOutbound = "singBox"` or `"userspace"`: each device registered with Cloudflare as wgcf registers (through the local proxy first, then directly, then `generatorUrl`), or a profile given; a sing-box WireGuard endpoint, several grouped as `warp` | +| autoProxy | `proxy.autoProxy`: the sites apps reach directly are probed through each exit in turn (direct first); one blocked directly but reached through an exit is routed through it, as upstream's prober decides (block pages, one exit per network first, strikes against exits that refuse). Blocks zapret can fix stay direct. `proxy-ctl proxy auto` shows, probes, learns and forgets | | whitelist-bypass | `whitelistBypass`: [whitelist-bypass](https://github.com/kulikov0/whitelist-bypass)'s headless creators and joiners (WB Stream, Telemost, DION, Bitrix; VK creators), built from upstream's source: a joiner is an outbound of the proxy tunnelled through a video call, a creator the call's free end. `proxy-ctl wl` gives the links and logins | | SSH tunnel | `sshProxy`: Windows' own OpenSSH as a SOCKS listener (`ssh -D`) for other programs, and, with `asOutbound`, an outbound of the proxy (sing-box's SSH client) | | TUN | sing-box's TUN (wintun), `proxy-ctl proxy tun on` — **see the caveats** | | The app | **Proxy Suite** in the Start Menu, and a tray icon from sign-in: the proxy, DPI bypass and Telegram proxy at a glance and a click; outbounds, subscriptions and the routing mode; zapret's presets and sites; tg-ws-proxy's links; whitelist-bypass's joiners and creators (links, logins); the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy | Not in this release, still to come: AmneziaWG as a system-wide VPN (its driver), Tor's onion service, -the kill switch, server inbounds, the XRay-only backend, autoProxy, zapret2's extended -detection and z2k strategies. Their options are accepted (they are upstream's), but the +the kill switch, server inbounds, the XRay-only backend, autoProxy's routing of slow sites +(`slowBelowKiBps`), zapret2's extended detection and z2k strategies. Their options are accepted (they are upstream's), but the service says, in its status and in the app, that it does not run them yet. Needs 64-bit Windows 10 (1903 or later) or 11. @@ -52,6 +53,7 @@ Needs 64-bit Windows 10 (1903 or later) or 11. | SSH tunnel | end to end on Linux: an sshd of the test's own, a page through the `ssh -D` listener and through sing-box's SSH outbound, each logging in with the service's copy of the key (`an_ssh_tunnel`) | | Tor | its Windows `tor.exe` (under Wine) accepts the torrc the service writes, bridges and transports included; on Linux the service runs Tor with it and Tor starts bootstrapping (where Tor's relays are blocked, it needs bridges) | | AmneziaWG | profiles from `.conf`, `vpn://` links and settings converted exactly as upstream's script converts them (its own encoder's links as test vectors); end to end on Linux: sing-box as a WireGuard server, the service running wireproxy-awg, a page through its listener and through the proxy's outbound (`an_amneziawg_tunnel`) | +| autoProxy | its judgement (upstream's verdicts, walk, exit order, strikes, state) by unit tests; the config with its probe listeners and learned rule-sets accepted by `sing-box check`; on Linux with a local exit: probes through direct and the exit, a learn request, a site an app reached directly queued from the Clash API and probed at the next run, the state and the rule-set files written. A site blocked here and reached through an exit needs a remote exit, so none was routed | | whitelist-bypass | its Windows programs built from upstream's tag with upstream's patches (links and passwords from the environment, never the command line); on Linux the service runs a joiner and a creator with their flags, the link and the login reaching them (`proxy-ctl wl join`, `wl auth`, `wl new`, `wl link`); a real call needs an account on a platform, so none was made | | WARP | a device registered live with Cloudflare by the service, its profile rendered as a sing-box endpoint and accepted; traffic through it not (this test machine blocks outgoing UDP) | | zapret's hostlist rules | every preset with sample rules, checked by `winws.exe --dry-run` (a preset without the profile a rule copies is refused, as upstream refuses it) | @@ -132,6 +134,11 @@ proxy-ctl proxy pin wl proxy-ctl wl auth laptop cookies.json proxy-ctl wl link laptop +# autoProxy (set "proxy": { "autoProxy": { "enable": true } }): +proxy-ctl proxy auto # what it routed, and where +proxy-ctl proxy auto probe example.com # how a site answers through each exit +proxy-ctl proxy auto learn example.com # probe it now, route it if it needs it + proxy-ctl logs -f # everything, following proxy-ctl --help ``` diff --git a/windows/crates/ps-core/Cargo.toml b/windows/crates/ps-core/Cargo.toml index 0364efb..dc83efe 100644 --- a/windows/crates/ps-core/Cargo.toml +++ b/windows/crates/ps-core/Cargo.toml @@ -15,5 +15,6 @@ thiserror.workspace = true percent-encoding.workspace = true ipnet.workspace = true indexmap.workspace = true +psl = "2" [dev-dependencies] diff --git a/windows/crates/ps-core/src/autoproxy.rs b/windows/crates/ps-core/src/autoproxy.rs new file mode 100644 index 0000000..fd85e24 --- /dev/null +++ b/windows/crates/ps-core/src/autoproxy.rs @@ -0,0 +1,666 @@ +//! autoProxy's judgement, as upstream decides it: what one fetch through an exit says +//! (proxy_ctl.py's `proxy auto probe`), the walk over the exits for a destination, the order +//! they are walked in (autoproxy-rounds.jq), the strikes against exits a destination refused +//! (autoproxy-strike.jq), what is remembered (autoproxy-run.template.sh, autoproxy-edit.jq) +//! and the rule-sets sing-box takes it from (autoproxy-render.template.sh). +//! +//! The fetches themselves are the service's; this is the deciding, so it is tested here. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::LazyLock; + +use regex::Regex; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::links::subscription::{nearness, url_parts}; + +/// The exit that is this host: always the first. +pub const DIRECT: &str = "direct"; + +/// The paths a destination is probed at: the page, then robots.txt, which some sites serve +/// where their front page refuses a client that is not a browser. +pub const PATHS: [&str; 2] = ["/", "/robots.txt"]; + +/// One fetch through one exit, at the first hop that is not a same-site redirect. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Fetch { + /// The answer's status; none when no answer came (TLS or the connection failed first). + pub status: Option, + /// The PROBE_BLOCK_PAGES name a refusal's page matched, "" for none. + #[serde(default)] + pub block: String, + /// A redirect's Location. + #[serde(default)] + pub location: String, + /// Bytes read of the body (at most what was read to judge it). + #[serde(default)] + pub bytes: u64, + /// Why no answer came. + #[serde(default)] + pub error: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Judgement { + /// Content. + Ok, + /// Failed before the origin spoke: the censor's doing, zapret's job. + Dead, + /// The site's security layer refused this address: an exit past it helps. + Wall, + /// The origin answered and refused: another exit can fix it. + Blocked, +} + +/// Block pages, by name: (kind, pattern over a refusal's headers and the first 8 KiB of its +/// body). "address": the address itself was refused, so an exit that gets past it reaches the +/// site; "geo": its country was, which is an ordinary refusal. +static BLOCK_PAGES: LazyLock> = LazyLock::new(|| { + [ + ("aws-waf", "address", r"(?ims)^server: cloudfront\b.*Request blocked\."), + ("cloudfront-geo", "geo", r"(?i)configured to block access from your country"), + ("cloudflare", "address", r#"(?im)^cf-mitigated: challenge|cf-error-code">10(06|07|08|20)<|error code: 10(06|07|08|20)\b"#), + ("cloudflare-geo", "geo", r#"(?i)cf-error-code">1009<|error code: 1009\b"#), + ("akamai", "address", r"(?ims)^server: AkamaiGHost\b.*Access Denied"), + ("imperva", "address", r"(?i)Incapsula incident ID"), + ("datadome", "address", r"(?im)^x-datadome:"), + ] + .into_iter() + .map(|(name, kind, re)| (name, kind, Regex::new(re).expect("a valid pattern"))) + .collect() +}); + +static BLOCK_REDIRECT: LazyLock = LazyLock::new(|| Regex::new(r"(?i)unavailable|not-available|blocked|geo|region|restricted").unwrap()); +static HOST: LazyLock = LazyLock::new(|| Regex::new(r"^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$").unwrap()); + +/// A host name autoProxy probes or routes: letters, digits, dots, '_' and '-', with a TLD. +pub fn host_ok(host: &str) -> bool { + host.len() <= 253 && HOST.is_match(host) +} + +/// The name of the block page a refusal (`status` 4xx or 5xx) shows, "" for none. `head` is +/// its headers as received, `body` its first bytes. +pub fn block_page(status: u16, head: &str, body: &[u8]) -> String { + if !(400..600).contains(&status) { + return String::new(); + } + let body: String = body.iter().take(8192).map(|&b| b as char).collect(); + let text = format!("{head}\n\n{body}\n\n"); + BLOCK_PAGES.iter().find(|(_, _, re)| re.is_match(&text)).map(|(name, _, _)| (*name).to_owned()).unwrap_or_default() +} + +/// The last two labels: a redirect is followed only within them. +pub fn site(url: &str) -> String { + let host = url_parts::split(url).ok().and_then(|u| u.hostname).unwrap_or_default(); + let labels: Vec<&str> = host.split('.').collect(); + labels[labels.len().saturating_sub(2)..].join(".") +} + +/// Whether a Location names this host or its LAN (localhost, or an address literal in any of +/// the forms curl takes): never followed. +pub fn local_target(url: &str) -> bool { + match url_parts::split(url) { + Ok(u) => nearness(u.hostname.as_deref()) > 0, + Err(_) => true, + } +} + +/// Whether a redirect's target says the content is refused (a "not available" page). +pub fn redirect_is_block(location: &str) -> bool { + BLOCK_REDIRECT.is_match(location) +} + +fn http_ok(f: &Fetch) -> bool { + match f.status { + Some(s) if (200..300).contains(&s) || s == 401 || s == 404 => true, + Some(s) if (300..400).contains(&s) => !redirect_is_block(&f.location), + _ => false, + } +} + +pub fn judge(f: &Fetch) -> Judgement { + if f.status.is_none() { + return Judgement::Dead; + } + if http_ok(f) { + return Judgement::Ok; + } + let address = BLOCK_PAGES.iter().any(|(name, kind, _)| *name == f.block && *kind == "address"); + if address { Judgement::Wall } else { Judgement::Blocked } +} + +/// Content; or, where direct hit a wall, any answer from the origin past it. +pub fn reaches(direct: Judgement, j: Judgement) -> bool { + j == Judgement::Ok || (direct == Judgement::Wall && j == Judgement::Blocked) +} + +/// "ok": direct gets it. "destination": an exit reaches what direct does not, past a refusal: +/// route through it. "censor": direct dies on the way while an exit reaches it, which zapret +/// is for: it stays direct. "both-fail" and "unreachable": no exit helps. +pub fn verdict(direct: &Fetch, via: &Fetch) -> &'static str { + let d = judge(direct); + if d == Judgement::Ok { + return "ok"; + } + if reaches(d, judge(via)) { + return if d == Judgement::Dead { "censor" } else { "destination" }; + } + if d == Judgement::Dead { "unreachable" } else { "both-fail" } +} + +pub fn verdict_text(verdict: &str, exit: Option<&str>) -> String { + match verdict { + "ok" => "reachable directly - nothing to do".into(), + "destination" => format!("destination-side block - route via {}", exit.unwrap_or("proxy")), + "censor" => "censor-side block - zapret's territory, not proxied".into(), + "both-fail" => "fails through every egress - not an egress problem".into(), + "unreachable" => "no egress reaches it at all".into(), + _ => "inconclusive".into(), + } +} + +pub fn describe(f: &Fetch) -> String { + let Some(status) = f.status else { + return if f.error.is_empty() { "no answer".into() } else { format!("no answer ({})", f.error) }; + }; + let mut text = format!("{status}, {} bytes", f.bytes); + if !f.block.is_empty() { + text.push_str(&format!(", {} page", f.block)); + } + if !f.location.is_empty() { + text.push_str(&format!(" -> {}", f.location)); + } + text +} + +/// One request of a walk. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Row { + pub tag: String, + pub path: String, + pub fetch: Fetch, + pub judgement: Judgement, +} + +/// What a probe found: the verdict, the exit that reached it (none for "ok" and the failures), +/// the path it was judged on, and every request made. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Probe { + pub domain: String, + pub verdict: String, + pub exit: Option, + pub path: String, + pub rows: Vec, +} + +/// Walks the exits (`exits[0]` is direct) and stops at the first that reaches `domain`: gets +/// content, or gets past a wall direct hit. `keep_going` still tries the rest, keeping that +/// first one. `fetch(tag, path)` is one request through one exit. +pub async fn walk(domain: &str, exits: &[String], paths: &[&str], keep_going: bool, mut fetch: F) -> Probe +where + F: FnMut(String, String) -> Fut, + Fut: Future, +{ + let mut p = Probe { domain: domain.to_owned(), ..Default::default() }; + let Some((direct_tag, others)) = exits.split_first() else { + p.verdict = "error".into(); + return p; + }; + let mut first_direct: Option = None; + for path in paths { + let direct = fetch(direct_tag.clone(), (*path).to_owned()).await; + let dj = judge(&direct); + p.rows.push(Row { tag: direct_tag.clone(), path: (*path).to_owned(), fetch: direct.clone(), judgement: dj }); + first_direct.get_or_insert_with(|| direct.clone()); + if dj == Judgement::Ok && p.verdict.is_empty() { + p.verdict = "ok".into(); + p.path = (*path).to_owned(); + if !keep_going { + return p; + } + } + for tag in others { + let via = fetch(tag.clone(), (*path).to_owned()).await; + let j = judge(&via); + p.rows.push(Row { tag: tag.clone(), path: (*path).to_owned(), fetch: via.clone(), judgement: j }); + if reaches(dj, j) && p.verdict.is_empty() { + p.verdict = verdict(&direct, &via).into(); + p.exit = Some(tag.clone()); + p.path = (*path).to_owned(); + if !keep_going { + return p; + } + } + } + } + if p.verdict.is_empty() { + let dead = first_direct.as_ref().is_none_or(|f| judge(f) == Judgement::Dead); + p.verdict = if dead { "unreachable" } else { "both-fail" }.into(); + p.path = paths.first().map(|s| (*s).to_owned()).unwrap_or_default(); + } + p +} + +/// `--via`: can `via` carry what direct reaches? It must get content on some path and fail on +/// none where direct succeeds. Verdict "ok" or "blocked". +pub async fn stand_in(domain: &str, via: &str, paths: &[&str], mut fetch: F) -> Probe +where + F: FnMut(String, String) -> Fut, + Fut: Future, +{ + let mut p = Probe { + domain: domain.to_owned(), + verdict: "ok".into(), + exit: Some(via.to_owned()), + path: paths.first().map(|s| (*s).to_owned()).unwrap_or_default(), + rows: Vec::new(), + }; + let mut got = false; + for path in paths { + let direct = fetch(DIRECT.to_owned(), (*path).to_owned()).await; + let through = fetch(via.to_owned(), (*path).to_owned()).await; + let (dj, vj) = (judge(&direct), judge(&through)); + p.rows.push(Row { tag: DIRECT.into(), path: (*path).to_owned(), fetch: direct, judgement: dj }); + p.rows.push(Row { tag: via.to_owned(), path: (*path).to_owned(), fetch: through, judgement: vj }); + got |= vj == Judgement::Ok; + if dj == Judgement::Ok && vj != Judgement::Ok { + p.verdict = "blocked".into(); + } + } + if !got { + p.verdict = "blocked".into(); + } + p +} + +/// The registrable domain of `host` (its site: example.co.uk, foo.workers.dev), by the public +/// suffix list with its private section; none for a public suffix itself, or a bare label. +pub fn registrable(host: &str) -> Option { + let host = host.trim_end_matches('.').to_ascii_lowercase(); + if !host.contains('.') { + return None; + } + let domain = psl::domain_str(&host)?; + Some(domain.to_owned()) +} + +// --- the state ----------------------------------------------------------------------------- + +/// A destination routed through an exit: probed blocked directly ("destination"). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Route { + pub verdict: String, + pub exit: String, + pub host: String, + #[serde(default)] + pub path: String, + pub at: u64, +} + +/// What the last probe of a host found. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HostVerdict { + pub domain: String, + pub verdict: String, + #[serde(default)] + pub exit: Option, + pub at: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Strike { + pub why: String, + pub at: u64, +} + +/// An exit: where it leaves from (its network, by AS), and the destinations that refused it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct ExitInfo { + pub ip: Option, + pub asn: Option, + pub at: u64, + pub strikes: BTreeMap, + pub bad: bool, + pub bad_by: Vec, +} + +/// A host dialled directly, not yet probed: how often, and since when. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Queued { + pub domain: String, + pub hits: u64, + pub first: u64, +} + +/// state.json. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct State { + /// This host's public address the verdicts are about. + pub egress: Option, + /// Registrable domain -> the exit it is routed through. + pub domains: BTreeMap, + pub hosts: BTreeMap, + pub exits: BTreeMap, + pub backlog: BTreeMap, + pub last_run: u64, +} + +/// Most entries the backlog keeps: every distinct name dialled is one. +const BACKLOG_MAX: usize = 5000; + +impl State { + /// `domain` refused `tags` at `now` (`why`: "wall:", "refused" or "slow"), and every + /// strike older than `ttl` goes. A domain counts once per exit; two make an exit bad. + pub fn strike(&mut self, tags: &[String], domain: &str, why: &str, now: u64, ttl: u64) { + for t in tags { + self.exits.entry(t.clone()).or_default().strikes.insert(domain.to_owned(), Strike { why: why.to_owned(), at: now }); + } + for e in self.exits.values_mut() { + e.strikes.retain(|_, s| s.at + ttl > now); + rebad(e); + } + } + + /// `domain` back to direct, every verdict and strike about it gone. + pub fn forget(&mut self, domain: &str) { + self.domains.remove(domain); + self.hosts.retain(|_, h| h.domain != domain); + self.backlog.retain(|_, q| q.domain != domain); + for e in self.exits.values_mut() { + if e.strikes.remove(domain).is_some() { + rebad(e); + } + } + } + + /// Everything learned forgotten; what each exit is, the backlog and the egress stay. + pub fn clear(&mut self) { + self.domains.clear(); + self.hosts.clear(); + for e in self.exits.values_mut() { + e.strikes.clear(); + rebad(e); + } + } + + /// A new public address: every verdict was about the old one. + pub fn new_egress(&mut self, egress: &str) { + *self = State { egress: Some(egress.to_owned()), backlog: std::mem::take(&mut self.backlog), last_run: self.last_run, ..Default::default() }; + } + + /// What probing `host` (of `domain`) found. A route applies to the whole domain (blocks + /// are drawn around sites); a verdict to the host. Exits refused on the path the winner + /// reached are struck: by a block page, or by the origin where the winner got content. + pub fn record(&mut self, domain: &str, host: &str, p: &Probe, now: u64, ttl: u64) { + if p.verdict == "destination" + && let Some(exit) = &p.exit + { + self.domains.insert(domain.to_owned(), Route { verdict: p.verdict.clone(), exit: exit.clone(), host: host.to_owned(), path: p.path.clone(), at: now }); + } + let exit = if p.verdict == "destination" { p.exit.clone() } else { None }; + self.hosts.insert(host.to_owned(), HostVerdict { domain: domain.to_owned(), verdict: p.verdict.clone(), exit, at: now }); + self.backlog.remove(host); + let Some(winner) = &p.exit else { return }; + let won = p.rows.iter().find(|r| &r.tag == winner && r.path == p.path).map(|r| r.judgement); + let mut struck: BTreeMap = BTreeMap::new(); + for r in p.rows.iter().filter(|r| r.path == p.path && r.tag != DIRECT && &r.tag != winner) { + let why = match r.judgement { + Judgement::Wall => format!("wall:{}", r.fetch.block), + Judgement::Blocked if won == Some(Judgement::Ok) => "refused".into(), + _ => continue, + }; + struck.entry(r.tag.clone()).or_insert(why); + } + for (tag, why) in struck { + self.strike(&[tag], domain, &why, now, ttl); + } + } + + /// Hosts dialled directly since the last run (`counts`: host -> (domain, hits)) into the + /// backlog, skipping those a route covers or a verdict within the TTL judged; entries past + /// the TTL, or covered since, go; the most dialled 5000 stay. + pub fn queue(&mut self, counts: &BTreeMap, now: u64, ttl: u64) { + self.last_run = now; + self.hosts.retain(|_, h| h.at + ttl > now); + for (host, (domain, hits)) in counts { + if self.domains.contains_key(domain) || self.hosts.get(host).is_some_and(|h| h.at + ttl > now) { + continue; + } + let q = self.backlog.entry(host.clone()).or_insert(Queued { domain: domain.clone(), hits: 0, first: now }); + q.hits += hits; + } + let domains = &self.domains; + self.backlog.retain(|_, q| q.first + ttl > now && !domains.contains_key(&q.domain)); + if self.backlog.len() > BACKLOG_MAX { + let mut v: Vec<(String, Queued)> = std::mem::take(&mut self.backlog).into_iter().collect(); + v.sort_by_key(|a| std::cmp::Reverse(a.1.hits)); + v.truncate(BACKLOG_MAX); + self.backlog = v.into_iter().collect(); + } + } + + /// The backlog to probe, most dialled first: (domain, host). + pub fn backlog_order(&self, now: u64, ttl: u64) -> Vec<(String, String)> { + let mut v: Vec<(&String, &Queued)> = self + .backlog + .iter() + .filter(|(h, q)| !self.domains.contains_key(&q.domain) && self.hosts.get(*h).is_none_or(|v| v.at + ttl <= now)) + .collect(); + v.sort_by(|a, b| b.1.hits.cmp(&a.1.hits).then_with(|| a.0.cmp(b.0))); + v.into_iter().map(|(h, q)| (q.domain.clone(), h.clone())).collect() + } + + /// Routes to probe again, once per TTL: (domain, host, exit). + pub fn due(&self, now: u64, ttl: u64) -> Vec<(String, String, String)> { + self.domains + .iter() + .filter(|(_, r)| r.verdict == "destination" && now.saturating_sub(r.at) >= ttl) + .map(|(d, r)| (d.clone(), r.host.clone(), r.exit.clone())) + .collect() + } +} + +fn rebad(e: &mut ExitInfo) { + e.bad = e.strikes.len() >= 2; + let mut s: Vec<(&String, &Strike)> = e.strikes.iter().collect(); + s.sort_by_key(|(_, v)| v.at); + e.bad_by = s.into_iter().map(|(d, v)| format!("{d} {}", v.why)).collect(); +} + +/// The probe order of the exits after direct: round 1, one exit per network (AS); round 2, +/// walked only when round 1 all refused, the rest; bad exits never take a network's round-1 +/// place and go last. Also the whole order. +pub fn rounds(exits: &[String], state: &State) -> (Vec, Vec, Vec) { + let info = |t: &str| state.exits.get(t); + let bad = |t: &str| info(t).is_some_and(|e| e.bad); + let mut ordered: Vec = exits.iter().filter(|t| t.as_str() != DIRECT && !bad(t)).cloned().collect(); + ordered.extend(exits.iter().filter(|t| t.as_str() != DIRECT && bad(t)).cloned()); + let (mut r1, mut r2) = (Vec::new(), Vec::new()); + let mut seen = BTreeSet::new(); + for t in &ordered { + let asn = info(t).and_then(|e| e.asn.clone()).unwrap_or_default(); + if bad(t) { + r2.push(t.clone()); + } else if asn.is_empty() || seen.insert(asn) { + r1.push(t.clone()); + } else { + r2.push(t.clone()); + } + } + (r1, r2, ordered) +} + +/// The sing-box rule-set (source format) of the domains routed through `exit`. +pub fn rule_set(state: &State, exit: &str) -> Value { + let domains: Vec<&String> = state.domains.iter().filter(|(_, r)| r.exit == exit).map(|(d, _)| d).collect(); + if domains.is_empty() { + json!({ "version": 1, "rules": [] }) + } else { + json!({ "version": 1, "rules": [{ "domain_suffix": domains }] }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ok() -> Fetch { + Fetch { status: Some(200), bytes: 1000, ..Default::default() } + } + fn dead() -> Fetch { + Fetch { status: None, error: "reset".into(), ..Default::default() } + } + fn refused() -> Fetch { + Fetch { status: Some(403), ..Default::default() } + } + fn wall() -> Fetch { + Fetch { status: Some(403), block: "cloudflare".into(), ..Default::default() } + } + + /// Runs a future that never waits (the fetches here answer at once). + fn now(f: F) -> F::Output { + let mut f = std::pin::pin!(f); + let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); + match f.as_mut().poll(&mut cx) { + std::task::Poll::Ready(v) => v, + std::task::Poll::Pending => panic!("a test fetch waited"), + } + } + + fn exits(tags: &[&str]) -> Vec { + tags.iter().map(|s| (*s).to_owned()).collect() + } + + #[test] + fn judgements_follow_upstream() { + assert_eq!(judge(&ok()), Judgement::Ok); + assert_eq!(judge(&Fetch { status: Some(404), ..Default::default() }), Judgement::Ok); + assert_eq!(judge(&Fetch { status: Some(302), location: "https://x.example/why-not-available".into(), ..Default::default() }), Judgement::Blocked); + assert_eq!(judge(&Fetch { status: Some(301), location: "https://www.x.example/".into(), ..Default::default() }), Judgement::Ok); + assert_eq!(judge(&dead()), Judgement::Dead); + assert_eq!(judge(&wall()), Judgement::Wall); + assert_eq!(judge(&Fetch { status: Some(403), block: "cloudflare-geo".into(), ..Default::default() }), Judgement::Blocked); + assert_eq!(verdict(&refused(), &ok()), "destination"); + assert_eq!(verdict(&dead(), &ok()), "censor"); + assert_eq!(verdict(&wall(), &refused()), "destination"); + assert_eq!(verdict(&dead(), &dead()), "unreachable"); + assert_eq!(verdict(&refused(), &refused()), "both-fail"); + } + + #[test] + fn block_pages_are_recognised() { + assert_eq!(block_page(403, "HTTP/1.1 403\r\nserver: cloudflare\r\ncf-mitigated: challenge\r\n", b""), "cloudflare"); + assert_eq!(block_page(403, "", b"1009"), "cloudflare-geo"); + assert_eq!(block_page(403, "Server: CloudFront\r\n", b"

Request blocked.

"), "aws-waf"); + assert_eq!(block_page(200, "x-datadome: 1\r\n", b""), ""); + } + + #[test] + fn a_walk_stops_at_the_first_exit_that_reaches() { + let answers = |tag: &str, _path: &str| match tag { + "direct" => refused(), + "a" => refused(), + _ => ok(), + }; + let p = now(walk("x.example", &exits(&["direct", "a", "b", "c"]), &PATHS, false, |t: String, p: String| std::future::ready(answers(&t, &p)))); + assert_eq!(p.verdict, "destination"); + assert_eq!(p.exit.as_deref(), Some("b")); + assert_eq!(p.rows.len(), 3, "c is never asked"); + let p = now(walk("x.example", &exits(&["direct", "a"]), &PATHS, false, |_: String, _: String| std::future::ready(ok()))); + assert_eq!((p.verdict.as_str(), p.rows.len()), ("ok", 1)); + let p = now(walk("x.example", &exits(&["direct", "a"]), &PATHS, false, |_: String, _: String| std::future::ready(dead()))); + assert_eq!((p.verdict.as_str(), p.rows.len()), ("unreachable", 4)); + } + + #[test] + fn robots_txt_can_decide_what_the_page_did_not() { + let p = now(walk("x.example", &exits(&["direct", "a"]), &PATHS, false, |t: String, path: String| std::future::ready(match (t.as_str(), path.as_str()) { + ("direct", _) => refused(), + ("a", "/") => refused(), + _ => ok(), + }))); + assert_eq!((p.verdict.as_str(), p.exit.as_deref(), p.path.as_str()), ("destination", Some("a"), "/robots.txt")); + } + + #[test] + fn a_stand_in_must_carry_everything_direct_gets() { + let p = now(stand_in("x.example", "a", &PATHS, |t: String, path: String| std::future::ready(if t == "a" && path == "/robots.txt" { refused() } else { ok() }))); + assert_eq!(p.verdict, "blocked"); + let p = now(stand_in("x.example", "a", &PATHS, |_: String, _: String| std::future::ready(ok()))); + assert_eq!(p.verdict, "ok"); + } + + #[test] + fn recording_routes_the_domain_and_strikes_who_refused() { + let mut s = State::default(); + let p = now(walk("www.x.example", &exits(&["direct", "a", "b"]), &PATHS, false, |t: String, _: String| std::future::ready(match t.as_str() { + "a" => wall(), + "b" => ok(), + _ => refused(), + }))); + s.record("x.example", "www.x.example", &p, 100, 1000); + assert_eq!(s.domains["x.example"].exit, "b"); + assert_eq!(s.exits["a"].strikes["x.example"].why, "wall:cloudflare"); + assert!(!s.exits["a"].bad); + s.strike(&exits(&["a"]), "y.example", "refused", 200, 1000); + assert!(s.exits["a"].bad, "two domains make an exit bad"); + assert_eq!(s.exits["a"].bad_by, ["x.example wall:cloudflare", "y.example refused"]); + s.strike(&[], "", "", 1150, 1000); + assert!(!s.exits["a"].bad, "a strike past the TTL stops counting"); + s.forget("x.example"); + assert!(s.domains.is_empty() && s.hosts.is_empty()); + assert_eq!(rule_set(&s, "b"), json!({ "version": 1, "rules": [] })); + } + + #[test] + fn rounds_take_one_exit_per_network_first_and_bad_ones_last() { + let mut s = State::default(); + for (t, asn) in [("a", "AS1"), ("b", "AS1"), ("c", "AS2")] { + s.exits.insert(t.into(), ExitInfo { asn: Some(asn.into()), ..Default::default() }); + } + s.exits.insert("d".into(), ExitInfo { bad: true, ..Default::default() }); + let (r1, r2, ordered) = rounds(&exits(&["direct", "d", "a", "b", "c", "e"]), &s); + assert_eq!(r1, ["a", "c", "e"]); + assert_eq!(r2, ["b", "d"]); + assert_eq!(ordered, ["a", "b", "c", "e", "d"]); + } + + #[test] + fn the_backlog_skips_what_is_known_and_keeps_counting() { + let mut s = State::default(); + s.domains.insert("routed.example".into(), Route { verdict: "destination".into(), exit: "a".into(), host: "routed.example".into(), path: "/".into(), at: 0 }); + let counts: BTreeMap = [ + ("www.routed.example".to_owned(), ("routed.example".to_owned(), 5)), + ("cdn.new.example".to_owned(), ("new.example".to_owned(), 2)), + ("api.other.example".to_owned(), ("other.example".to_owned(), 7)), + ] + .into(); + s.queue(&counts, 10, 1000); + s.queue(&counts, 20, 1000); + assert_eq!(s.backlog.len(), 2); + assert_eq!(s.backlog["cdn.new.example"].hits, 4); + assert_eq!(s.backlog_order(20, 1000)[0], ("other.example".to_owned(), "api.other.example".to_owned())); + s.new_egress("203.0.113.9"); + assert!(s.domains.is_empty()); + assert_eq!(s.backlog.len(), 2, "the backlog is about the clients, not the address"); + } + + #[test] + fn sites_and_local_targets() { + assert_eq!(registrable("www.example.co.uk").as_deref(), Some("example.co.uk")); + assert_eq!(registrable("foo.workers.dev").as_deref(), Some("foo.workers.dev")); + assert_eq!(registrable("co.uk"), None); + assert_eq!(site("https://accounts.spotify.com/why"), "spotify.com"); + assert!(local_target("http://127.1/")); + assert!(local_target("https://192.168.0.1/admin")); + assert!(local_target("http://localhost:8080/")); + assert!(!local_target("https://example.com/")); + assert!(host_ok("www.example.com") && !host_ok("127.0.0.1") && !host_ok("example") && !host_ok("a b.com")); + } +} diff --git a/windows/crates/ps-core/src/config/validate.rs b/windows/crates/ps-core/src/config/validate.rs index fdaf9c4..8a56bb0 100644 --- a/windows/crates/ps-core/src/config/validate.rs +++ b/windows/crates/ps-core/src/config/validate.rs @@ -126,12 +126,14 @@ fn not_ported(cfg: &Config, v: &mut Issues) { (cfg.warp.enable && cfg.warp.as_amnezia_wg, "warp.asAmneziaWg", "WARP as an AmneziaWG profile"), (cfg.tor.enable && cfg.tor.onion_service.enable, "tor.onionService.enable", "Tor's onion service (it serves the inbounds)"), (cfg.inbounds.enable, "inbounds.enable", "Serving inbounds"), - (cfg.proxy.auto_proxy.enable, "proxy.autoProxy.enable", "autoProxy"), ] { if on { v.warn(path, format!("{what} {IGNORED}")); } } + if cfg.proxy.enable && cfg.proxy.auto_proxy.enable && cfg.proxy.auto_proxy.slow_below_kibps > 0 { + v.warn("proxy.autoProxy.slowBelowKiBps", "routing slow destinations is not on Windows yet: autoProxy routes the blocked ones"); + } if cfg.proxy.enable && cfg.proxy.backend == Backend::Xray { v.warn("proxy.backend", "the xray backend is not on Windows yet: the proxy does not start with it (sing-box or hybrid do)"); } diff --git a/windows/crates/ps-core/src/lib.rs b/windows/crates/ps-core/src/lib.rs index fbb1b03..40385cc 100644 --- a/windows/crates/ps-core/src/lib.rs +++ b/windows/crates/ps-core/src/lib.rs @@ -4,6 +4,7 @@ //! subscription parsing, and the sing-box and XRay configs the service runs. Nothing here //! touches the network, the file system or processes; the service does that. +pub mod autoproxy; pub mod awg; pub mod components; pub mod config; diff --git a/windows/crates/ps-core/src/render/autoproxy.rs b/windows/crates/ps-core/src/render/autoproxy.rs new file mode 100644 index 0000000..c14ffa3 --- /dev/null +++ b/windows/crates/ps-core/src/render/autoproxy.rs @@ -0,0 +1,94 @@ +//! autoProxy in sing-box's config, as upstream's start script adds it: a loopback listener +//! per exit (direct first) that the prober fetches through, pinned to that exit; and per exit +//! a local rule-set of the domains learned blocked directly, routed through it after every +//! rule of the user's. sing-box reloads a rule-set file when it changes, so what the prober +//! learns takes effect without a restart. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use super::outbounds::Inventory; +use super::{Input, RouteMode}; +use crate::autoproxy::DIRECT; + +/// One exit the prober fetches through. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProbeExit { + pub tag: String, + /// Its loopback listener. + pub port: u16, + /// Its rule-set's tag and file (none for direct: nothing is routed there). + pub rule_set: Option, + pub path: Option, +} + +fn inbound(i: usize) -> String { + format!("probe-in-{i}") +} + +/// direct, then the exits that are not disabled, `maxExits` in all. The state is kept by tag, +/// so an index that shifts is harmless. +pub fn probe_exits(input: &Input, inv: &Inventory) -> Vec { + let a = &input.cfg.proxy.auto_proxy; + let Some(dir) = input.env.autoproxy_rules_dir.as_deref().filter(|_| a.enable) else { + return Vec::new(); + }; + let dir = dir.trim_end_matches(['/', '\\']); + let sep = if input.env.windows { '\\' } else { '/' }; + std::iter::once(DIRECT.to_owned()) + .chain(inv.exits.iter().filter(|t| t.as_str() != DIRECT && !inv.disabled.contains(t)).cloned()) + .take(a.max_exits.max(1) as usize) + .enumerate() + .map(|(i, tag)| ProbeExit { + port: a.probe_base_port.saturating_add(i as u16), + rule_set: (i > 0).then(|| format!("autoproxy-{i}")), + path: (i > 0).then(|| format!("{dir}{sep}rs-{i}.json")), + tag, + }) + .collect() +} + +/// Adds the listeners (with the hop login: they reach every exit), their pins at `pin_at` +/// (after the loopback guard, ahead of every rule that picks an outbound), the rule-sets, and +/// the learned rules after the rest, unless the mode sends everything direct. What an exit +/// carries is looked up through the proxy too, as every proxied name is. +#[allow(clippy::too_many_arguments)] +pub(super) fn apply( + input: &Input, + exits: &[ProbeExit], + inbounds: &mut Vec, + rules: &mut Vec, + pin_at: usize, + rule_sets: &mut Vec, + dns_rules: &mut Vec, + mode: RouteMode, +) { + if exits.is_empty() { + return; + } + for (i, e) in exits.iter().enumerate() { + let mut l = json!({ "type": "mixed", "tag": inbound(i), "listen": "127.0.0.1", "listen_port": e.port }); + if let Some((user, password)) = &input.env.hop_login { + l["users"] = json!([{ "username": user, "password": password }]); + } + inbounds.push(l); + } + // The direct probe resolves as a direct dial would, and never reaches this host's LAN: the + // hosts probed are ones apps dialled, or anyone with the autoProxy scope asked for. + let mut pins = vec![ + json!({ "inbound": [inbound(0)], "action": "resolve", "server": "local" }), + json!({ "inbound": [inbound(0)], "ip_is_private": true, "action": "reject" }), + ]; + pins.extend(exits.iter().enumerate().map(|(i, e)| json!({ "inbound": [inbound(i)], "outbound": e.tag }))); + let at = pin_at.min(rules.len()); + rules.splice(at..at, pins); + + for e in exits { + let (Some(tag), Some(path)) = (&e.rule_set, &e.path) else { continue }; + rule_sets.push(json!({ "type": "local", "format": "source", "tag": tag, "path": path })); + if mode != RouteMode::AllBypass { + rules.push(json!({ "rule_set": [tag], "outbound": e.tag })); + } + dns_rules.push(json!({ "rule_set": [tag], "server": "remote" })); + } +} diff --git a/windows/crates/ps-core/src/render/mod.rs b/windows/crates/ps-core/src/render/mod.rs index 1247a29..b1dd11d 100644 --- a/windows/crates/ps-core/src/render/mod.rs +++ b/windows/crates/ps-core/src/render/mod.rs @@ -2,6 +2,7 @@ //! what it has fetched. Upstream builds these in its start scripts (bash and jq over the //! Nix templates); here it is one pure function the service calls before every (re)start. +mod autoproxy; pub mod groups; mod outbounds; mod routing; @@ -15,6 +16,7 @@ use serde_json::Value; use crate::config::{Config, RouteMatch, RuleSetFormat}; +pub use autoproxy::ProbeExit; pub use outbounds::Inventory; pub use routing::{WantedRuleSet, wanted_rule_sets}; @@ -101,6 +103,8 @@ pub struct Env { pub sidecar_secret: String, /// Running on Windows: the TUN takes Windows' fields only. pub windows: bool, + /// Where autoProxy's learned rule-sets are (one file per exit), when it runs. + pub autoproxy_rules_dir: Option, } pub struct Input<'a> { @@ -123,6 +127,8 @@ pub struct Rendered { /// XRay's: the whole proxy on the "xray" backend, the sidecar on "hybrid". pub xray: Option, pub inventory: Inventory, + /// autoProxy's exits and their probe listeners; empty when it is off. + pub probe_exits: Vec, pub warnings: Vec, } @@ -143,8 +149,9 @@ pub fn render(input: &Input) -> Result { let assembly = outbounds::assemble(input, &mut warnings)?; match input.cfg.proxy.backend { crate::config::Backend::SingBox | crate::config::Backend::Hybrid => { - let (config, sidecar) = sing_box::config(input, &assembly, &mut warnings)?; - Ok(Rendered { sing_box: Some(config), xray: sidecar, inventory: assembly.inventory, warnings }) + let probe_exits = autoproxy::probe_exits(input, &assembly.inventory); + let (config, sidecar) = sing_box::config(input, &assembly, &probe_exits, &mut warnings)?; + Ok(Rendered { sing_box: Some(config), xray: sidecar, inventory: assembly.inventory, probe_exits, warnings }) } crate::config::Backend::Xray => Err(RenderError( "the \"xray\" backend is not rendered yet on Windows; use \"sing-box\" or \"hybrid\"".into(), diff --git a/windows/crates/ps-core/src/render/routing.rs b/windows/crates/ps-core/src/render/routing.rs index 9a4f5ab..7b301a7 100644 --- a/windows/crates/ps-core/src/render/routing.rs +++ b/windows/crates/ps-core/src/render/routing.rs @@ -177,6 +177,10 @@ pub(super) fn per_app_inbound(name: &str) -> String { /// Every route and DNS rule, in order, and the final outbound and resolver. pub(super) struct Route { pub rules: Vec, + /// Where rules pinned to an inbound go: after the loopback guard, ahead of every rule that + /// picks an outbound. + pub pin_at: usize, + pub mode: RouteMode, pub dns_rules: Vec, pub final_outbound: &'static str, pub dns_final: &'static str, @@ -204,6 +208,7 @@ pub(super) fn route(input: &Input, hop_ports: &[u16], known: &dyn Fn(&str) -> bo let _ = hop_ports; common.push(json!({ "ip_cidr": LOOPBACK, "action": "reject" })); common.push(json!({ "domain": ["localhost"], "domain_suffix": [".localhost"], "action": "reject" })); + let pin_at = common.len(); common.extend(always_rules(input, known, warnings)); // The custom rules: each outbound's own routing, then routing.rules, at their priority. @@ -321,7 +326,7 @@ pub(super) fn route(input: &Input, hop_ports: &[u16], known: &dyn Fn(&str) -> bo dns_rules_out.push(json!({ "inbound": ["tun-in"], "query_type": ["A", "AAAA"], "server": "fakeip" })); } - Route { rules, dns_rules: dns_rules_out, final_outbound, dns_final, rule_set: rule_set_defs(input, warnings) } + Route { rules, pin_at, mode, dns_rules: dns_rules_out, final_outbound, dns_final, rule_set: rule_set_defs(input, warnings) } } fn custom_section(priority: i64, outbound: &str, m: &RouteMatch, names: &[String], paths: &[String]) -> Section { diff --git a/windows/crates/ps-core/src/render/sing_box.rs b/windows/crates/ps-core/src/render/sing_box.rs index 4bc3a6f..29485a7 100644 --- a/windows/crates/ps-core/src/render/sing_box.rs +++ b/windows/crates/ps-core/src/render/sing_box.rs @@ -3,6 +3,7 @@ use serde_json::{Map, Value, json}; +use super::autoproxy::{self, ProbeExit}; use super::outbounds::Assembly; use super::routing::{self, per_app_inbound}; use super::{Input, RenderError}; @@ -64,7 +65,7 @@ fn listener_users(input: &Input) -> Result, RenderError> { Ok(Some(json!([{ "username": user, "password": password }]))) } -pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec) -> Result<(Value, Option), RenderError> { +pub(super) fn config(input: &Input, asm: &Assembly, probe_exits: &[ProbeExit], warnings: &mut Vec) -> Result<(Value, Option), RenderError> { let cfg = input.cfg; let p = &cfg.proxy; let env = input.env; @@ -142,6 +143,9 @@ pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec) test_members.extend(asm.inventory.exits.iter().map(|t| Value::from(t.clone()))); outbounds.push(json!({ "type": "selector", "tag": "proxy-suite-test", "outbounds": test_members, "default": "block" })); let mut rules = route.rules; + let mut rule_sets = route.rule_set; + let mut dns_rules = route.dns_rules; + autoproxy::apply(input, probe_exits, &mut inbounds, &mut rules, route.pin_at, &mut rule_sets, &mut dns_rules, route.mode); let after_sniff = rules.iter().position(|r| r["action"] == "sniff").map_or(0, |i| i + 1); rules.insert(after_sniff, json!({ "inbound": ["proxy-suite-test-in"], "outbound": "proxy-suite-test" })); if hybrid { @@ -156,7 +160,7 @@ pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec) servers.push(json!({ "type": "fakeip", "tag": "fakeip", "inet4_range": p.dns.fake_ip.inet4_range })); } servers.extend(p.dns.sing_box.servers.iter().map(|s| Value::Object(s.clone()))); - let mut dns = json!({ "servers": servers, "rules": route.dns_rules, "final": route.dns_final }); + let mut dns = json!({ "servers": servers, "rules": dns_rules, "final": route.dns_final }); if let Some(s) = p.dns.strategy { dns["strategy"] = s.as_str().into(); } @@ -166,7 +170,7 @@ pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec) let mut route_obj = json!({ "default_domain_resolver": "local", - "rule_set": route.rule_set, + "rule_set": rule_sets, "rules": rules, "final": route.final_outbound, }); diff --git a/windows/crates/ps-core/tests/render.rs b/windows/crates/ps-core/tests/render.rs index 8fc8232..4bbd2cf 100644 --- a/windows/crates/ps-core/tests/render.rs +++ b/windows/crates/ps-core/tests/render.rs @@ -230,3 +230,40 @@ fn no_outbounds_is_an_error() { let err = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &env(&dir), read_file: &no_files, tun: false }).unwrap_err(); assert!(err.0.contains("no proxy outbounds")); } + +#[test] +fn auto_proxy_adds_probe_listeners_and_learned_rules() { + let dir = scratch("autoproxy"); + let mut cfg = base(); + cfg.proxy.auto_proxy.enable = true; + cfg.proxy.auto_proxy.max_exits = 2; + let rules_dir = dir.join("rules"); + std::fs::create_dir_all(&rules_dir).unwrap(); + std::fs::write(rules_dir.join("rs-1.json"), r#"{"version":1,"rules":[{"domain_suffix":["blocked.example"]}]}"#).unwrap(); + let mut e = env(&dir); + e.autoproxy_rules_dir = Some(rules_dir.to_string_lossy().into()); + e.windows = false; + let mut state = State::default(); + let render_with = |state: &State| { + render(&Input { cfg: &cfg, state, subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap() + }; + let r = render_with(&state); + // direct, then the first exit: maxExits 2. + assert_eq!(r.probe_exits.iter().map(|x| (x.tag.as_str(), x.port)).collect::>(), [("direct", 18540), ("nl", 18541)]); + let sb = r.sing_box.unwrap(); + let probe_in: Vec<&Value> = sb["inbounds"].as_array().unwrap().iter().filter(|i| i["tag"].as_str().unwrap().starts_with("probe-in-")).collect(); + assert_eq!(probe_in.len(), 2); + assert_eq!(probe_in[1]["users"], json!([{ "username": "hop", "password": "hop-pass" }])); + let rules = sb["route"]["rules"].as_array().unwrap(); + let guard = rules.iter().position(|r| r["domain"] == json!(["localhost"])).unwrap(); + let pin = rules.iter().position(|r| r["inbound"] == json!(["probe-in-1"])).unwrap(); + assert!(pin > guard, "the probes stay behind the loopback guard"); + assert_eq!(rules.last().unwrap(), &json!({ "rule_set": ["autoproxy-1"], "outbound": "nl" })); + assert!(sb["dns"]["rules"].as_array().unwrap().contains(&json!({ "rule_set": ["autoproxy-1"], "server": "remote" }))); + check_sing_box(&sb, &dir); + + // all-bypass: everything direct, learned routes too. + state.route_mode = Some(RouteMode::AllBypass); + let sb = render_with(&state).sing_box.unwrap(); + assert!(!sb["route"]["rules"].as_array().unwrap().iter().any(|r| r["rule_set"] == json!(["autoproxy-1"]) && r.get("outbound").is_some())); +} diff --git a/windows/crates/ps-ctl/src/main.rs b/windows/crates/ps-ctl/src/main.rs index e968ceb..9a6fc45 100644 --- a/windows/crates/ps-ctl/src/main.rs +++ b/windows/crates/ps-ctl/src/main.rs @@ -170,6 +170,39 @@ enum ProxyVerb { }, /// The config the backend runs. Config, + /// autoProxy: what it routed and where; probing, learning, forgetting. + Auto { + #[command(subcommand)] + verb: Option, + }, +} + +#[derive(Subcommand)] +enum AutoVerb { + /// The routes learned, the exits, what waits. + List, + /// Probe a site (host, or host/path) through the exits, as autoProxy does. + Probe { + target: String, + /// Only these exits (comma-separated), in this order. + #[arg(long, value_delimiter = ',')] + exits: Option>, + /// Whether this exit carries what direct reaches. + #[arg(long)] + via: Option, + /// Try every exit, not only up to the first that reaches it. + #[arg(long)] + keep_going: bool, + }, + /// Probe these hosts now, and route them if they need it. + Learn { + #[arg(required = true)] + hosts: Vec, + }, + /// Forget a domain's route: it is probed again when next dialled. + Forget { domain: String }, + /// Forget everything learned. + Clear, } #[derive(Subcommand)] @@ -523,6 +556,78 @@ async fn proxy(ctl: &Ctl, verb: Option) -> Result<()> { } }, ProxyVerb::Config => ctl.print(&ctl.call(Request::RenderedConfig).await?), + ProxyVerb::Auto { verb } => auto(ctl, verb).await?, + } + Ok(()) +} + +async fn auto(ctl: &Ctl, verb: Option) -> Result<()> { + match verb.unwrap_or(AutoVerb::List) { + AutoVerb::List => { + let r = ctl.call(Request::AutoList).await?; + if ctl.json { + ctl.print(&r); + return Ok(()); + } + let state = match (r["enabled"] == true, r["running"] == true) { + (false, _) => "off (proxy.autoProxy.enable)", + (true, false) => "on, waiting for the local proxy", + (true, true) => "running", + }; + println!("autoProxy: {state}"); + if let Some(e) = r["egress"].as_str() { + println!(" egress {e}"); + } + let domains = r["domains"].as_array().cloned().unwrap_or_default(); + if domains.is_empty() { + println!(" nothing routed yet"); + } else { + println!(" {:<32} {:<20} PROBED AS", "DOMAIN", "EXIT"); + for d in &domains { + println!(" {:<32} {:<20} {}", d["domain"].as_str().unwrap_or(""), d["exit"].as_str().unwrap_or(""), d["host"].as_str().unwrap_or("")); + } + } + for e in r["exits"].as_array().into_iter().flatten().filter(|e| e["bad"] == true) { + let by: Vec<&str> = e["badBy"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + println!(" bad exit {} (probed last): {}", e["tag"].as_str().unwrap_or(""), by.join(", ")); + } + let censored = r["censored"].as_array().map_or(0, Vec::len); + println!(" {} host(s) judged, {censored} left to zapret, {} waiting to be probed", r["hostsJudged"], r["backlog"]); + } + AutoVerb::Probe { target, exits, via, keep_going } => { + let r = ctl.call(Request::AutoProbe { target, exits, via: via.clone(), keep_going }).await?; + if ctl.json { + ctl.print(&r); + return Ok(()); + } + println!(" domain {}", r["domain"].as_str().unwrap_or("")); + let chosen = (r["exit"].as_str().unwrap_or(""), r["path"].as_str().unwrap_or("")); + println!(" exits"); + for row in r["rows"].as_array().into_iter().flatten() { + let (tag, path) = (row["tag"].as_str().unwrap_or(""), row["path"].as_str().unwrap_or("")); + let f: ps_core::autoproxy::Fetch = serde_json::from_value(row["fetch"].clone()).unwrap_or_default(); + let mark = if (tag, path) == chosen { " <- chosen" } else { "" }; + println!(" {tag:<18} {path:<12} {:<44} {}{mark}", ps_core::autoproxy::describe(&f), row["judgement"].as_str().unwrap_or("")); + } + let verdict = r["verdict"].as_str().unwrap_or(""); + match via { + Some(v) if verdict == "ok" => println!(" verdict {v} answers it as well as direct does - it can carry it"), + Some(v) => println!(" verdict {v} answers it worse than direct does"), + None => println!(" verdict {}", ps_core::autoproxy::verdict_text(verdict, r["exit"].as_str())), + } + } + AutoVerb::Learn { hosts } => { + let r = ctl.call(Request::AutoLearn { hosts }).await?; + println!("{} host(s) queued; the prober runs now (proxy-ctl logs proxy-suite-autoproxy)", r["queued"]); + } + AutoVerb::Forget { domain } => { + ctl.call(Request::AutoForget { domain: Some(domain.clone()) }).await?; + println!("forgot {domain}"); + } + AutoVerb::Clear => { + ctl.call(Request::AutoForget { domain: None }).await?; + println!("forgot everything learned"); + } } Ok(()) } diff --git a/windows/crates/ps-ipc/src/lib.rs b/windows/crates/ps-ipc/src/lib.rs index f4ba357..4a72684 100644 --- a/windows/crates/ps-ipc/src/lib.rs +++ b/windows/crates/ps-ipc/src/lib.rs @@ -76,6 +76,26 @@ pub enum Request { WlJoin { name: String, link: String }, /// Drops the call a creator rejoins: it makes a new one. WlNew { name: String }, + /// autoProxy: the routes it learned, its exits, what waits. + AutoList, + /// Probes a destination (a host, or host/path) through the exits as the prober does: + /// through `exits` (all, without), or whether `via` carries what direct reaches. + AutoProbe { + target: String, + #[serde(default)] + exits: Option>, + #[serde(default)] + via: Option, + #[serde(default)] + keep_going: bool, + }, + /// Hosts to probe now. + AutoLearn { hosts: Vec }, + /// Forgets a domain's route and verdicts; without one, everything learned. + AutoForget { + #[serde(default)] + domain: Option, + }, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] diff --git a/windows/crates/ps-service/src/api.rs b/windows/crates/ps-service/src/api.rs index aa70a33..124af1e 100644 --- a/windows/crates/ps-service/src/api.rs +++ b/windows/crates/ps-service/src/api.rs @@ -136,6 +136,7 @@ fn scope_of(req: &Request) -> Option { Request::RenderedConfig | Request::Logs { .. } | Request::TgLinks => Some(Scope::Secrets), Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services), Request::WlList | Request::WlLink { .. } | Request::WlAuth { .. } | Request::WlJoin { .. } | Request::WlNew { .. } => Some(Scope::WhitelistBypass), + Request::AutoList | Request::AutoProbe { .. } | Request::AutoLearn { .. } | Request::AutoForget { .. } => Some(Scope::AutoProxy), _ => None, } } @@ -577,6 +578,48 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response { wl_restart(&mut s, &format!("{}{name}", crate::wl::CREATOR_PREFIX)).await } + Request::AutoList => { + let s = shared.lock().await; + let exits = crate::autoproxy::exits(&s); + Response::ok(crate::autoproxy::listing(s.paths(), exits.as_ref(), &s.cfg().proxy.auto_proxy)) + } + + Request::AutoProbe { target, exits, via, keep_going } => { + let Some(probe_exits) = crate::autoproxy::exits(&*shared.lock().await) else { + return Response::err("autoProxy is not running: it needs proxy.autoProxy.enable and the local proxy on"); + }; + // The network, outside the lock. + match probe_exits.probe(&target, exits.as_deref(), via.as_deref(), keep_going).await { + Ok(p) => Response::ok(serde_json::to_value(&p).unwrap()), + Err(e) => Response::err(format!("{e:#}")), + } + } + + Request::AutoLearn { hosts } => { + let s = shared.lock().await; + if crate::autoproxy::exits(&s).is_none() { + return Response::err("autoProxy is not running: it needs proxy.autoProxy.enable and the local proxy on"); + } + let bad: Vec<&String> = hosts.iter().filter(|h| !ps_core::autoproxy::host_ok(h.trim())).collect(); + if !bad.is_empty() { + return Response::err(format!("not host names: {}", bad.iter().map(|h| h.as_str()).collect::>().join(", "))); + } + let queued = { + let mut r = s.ap.requests.lock().unwrap(); + // Bounded: every request is a probe. + let room = 10_000usize.saturating_sub(r.len()); + r.extend(hosts.iter().take(room).map(|h| h.trim().to_owned())); + hosts.len().min(room) + }; + s.ap.wake.notify_one(); + Response::ok(json!({ "queued": queued })) + } + + Request::AutoForget { domain } => match crate::autoproxy::edit(shared, domain.as_deref()).await { + Ok(()) => Response::ok(json!({ "forgot": domain.unwrap_or_else(|| "everything".into()) })), + Err(e) => Response::err(format!("{e:#}")), + }, + Request::ComponentsInstall { names } => { // Programs the service runs as SYSTEM: an administrator's call, whatever the scopes. if !peer.admin { diff --git a/windows/crates/ps-service/src/autoproxy.rs b/windows/crates/ps-service/src/autoproxy.rs new file mode 100644 index 0000000..c15781e --- /dev/null +++ b/windows/crates/ps-service/src/autoproxy.rs @@ -0,0 +1,605 @@ +//! autoProxy's prober, as upstream's autoproxy-run.template.sh runs it: every `interval`, and +//! at once for `proxy-ctl proxy auto learn`, it probes the hosts apps dialled directly (and +//! those asked for) through each exit in turn, remembers the first exit that reaches what +//! direct does not, and publishes it as that exit's rule-set, which sing-box reloads. +//! +//! Upstream learns the hosts from its server inbounds' access log; on a desktop they are the +//! local proxy's own direct connections, which the Clash API lists (`sample`). The judging is +//! ps_core::autoproxy's. + +use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use anyhow::{Context, Result, bail}; +use ps_core::autoproxy::{self as ap, Fetch, PATHS, Probe, State}; +use ps_core::config::AutoProxy as Options; +use ps_core::render::ProbeExit; +use serde_json::{Value, json}; + +use crate::paths::{Paths, write_atomic}; +use crate::service::{SOCKS_UNIT, Shared}; +use crate::units::UnitState; + +/// Where the prober's lines go: `proxy-ctl logs proxy-suite-autoproxy`. +pub const UNIT: &str = "proxy-suite-autoproxy"; + +const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) proxy-suite-probe"; + +/// What the service and the prober share. +#[derive(Default)] +pub struct AutoProxy { + /// Runs and edits take turns on the state. + pub lock: tokio::sync::Mutex<()>, + /// Hosts asked for, probed at the next run, which asking wakes. + pub requests: std::sync::Mutex>, + /// Hosts apps dialled directly since the last run, with how often. + pub dialled: std::sync::Mutex>, + pub wake: tokio::sync::Notify, +} + +pub fn dir(paths: &Paths) -> PathBuf { + paths.root.join("autoproxy") +} + +pub fn rules_dir(paths: &Paths) -> PathBuf { + dir(paths).join("rules") +} + +fn now() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) +} + +/// The state, or a fresh one; an unreadable one is set aside as state.json.broken. +pub fn load(paths: &Paths) -> State { + let file = dir(paths).join("state.json"); + match std::fs::read(&file) { + Ok(bytes) => match serde_json::from_slice(&bytes) { + Ok(s) => s, + Err(e) => { + tracing::warn!("{} is unreadable ({e}); set aside, starting fresh", file.display()); + let _ = std::fs::rename(&file, file.with_extension("json.broken")); + State::default() + } + }, + Err(_) => State::default(), + } +} + +pub fn save(paths: &Paths, state: &State) -> Result<()> { + let d = dir(paths); + std::fs::create_dir_all(&d)?; + write_atomic(&d.join("state.json"), &serde_json::to_vec_pretty(state)?)?; + Ok(()) +} + +/// Every exit's rule-set file from the state: before sing-box starts (it refuses a missing +/// one), and after each route learned (it reloads a file replaced). +pub fn publish(exits: &[ProbeExit], state: &State) -> Result<()> { + for e in exits { + let Some(path) = &e.path else { continue }; + let path = Path::new(path); + if let Some(d) = path.parent() { + std::fs::create_dir_all(d)?; + } + let body = serde_json::to_vec(&ap::rule_set(state, &e.tag))?; + if std::fs::read(path).is_ok_and(|old| old == body) { + continue; + } + write_atomic(path, &body).with_context(|| format!("writing {}", path.display()))?; + } + Ok(()) +} + +/// The probe listeners and their login, while the proxy and autoProxy run. +#[derive(Clone)] +pub struct Exits { + pub list: Vec, + pub login: (String, String), +} + +impl Exits { + fn port(&self, tag: &str) -> Option { + self.list.iter().find(|e| e.tag == tag).map(|e| e.port) + } + + fn tags(&self) -> Vec { + self.list.iter().map(|e| e.tag.clone()).collect() + } + + /// `domain` at `path` through `tag`'s listener. + pub async fn fetch(&self, tag: &str, domain: &str, path: &str) -> Fetch { + match self.port(tag) { + Some(port) => fetch(port, &self.login, domain, path).await, + None => Fetch { error: format!("no exit {tag}"), ..Default::default() }, + } + } + + /// Whether the direct listener answers at all: a probe through a listener that is not + /// there would judge every site unreachable. + async fn up(&self) -> bool { + let Some(e) = self.list.first() else { return false }; + tokio::time::timeout(Duration::from_secs(3), tokio::net::TcpStream::connect(("127.0.0.1", e.port))).await.is_ok_and(|r| r.is_ok()) + } + + /// A probe of `domain` (a host, or host/path), as `proxy-ctl proxy auto probe` asks it: + /// through `wanted` (all, without), or whether `via` carries what direct reaches. + pub async fn probe(&self, target: &str, wanted: Option<&[String]>, via: Option<&str>, keep_going: bool) -> Result { + let target = target.split("://").last().unwrap_or(target); + let (domain, paths): (&str, Vec) = match target.split_once('/') { + Some((d, p)) => (d, vec![format!("/{p}")]), + None => (target, PATHS.iter().map(|p| (*p).to_owned()).collect()), + }; + if !ap::host_ok(domain) { + bail!("'{domain}' is not a host name"); + } + if !self.up().await { + bail!("the probe listeners are not up: is the local proxy running?"); + } + let paths: Vec<&str> = paths.iter().map(String::as_str).collect(); + let fetch = |tag: String, path: String| async move { self.fetch(&tag, domain, &path).await }; + if let Some(via) = via { + if via == ap::DIRECT || self.port(via).is_none() { + bail!("no exit named {via} other than direct"); + } + return Ok(ap::stand_in(domain, via, &paths, fetch).await); + } + let mut exits = vec![ap::DIRECT.to_owned()]; + match wanted { + Some(w) => exits.extend(w.iter().filter(|t| t.as_str() != ap::DIRECT && self.port(t).is_some()).cloned()), + None => exits.extend(self.list.iter().skip(1).map(|e| e.tag.clone())), + } + Ok(ap::walk(domain, &exits, &paths, keep_going, fetch).await) + } +} + +/// One request through a probe listener: the first hop that is not a same-site redirect +/// (a block can sit at the end of a chain: spotify.com -> www -> open -> why-not-available). +async fn fetch(port: u16, login: &(String, String), domain: &str, path: &str) -> Fetch { + let client = reqwest::Client::builder() + .proxy(match reqwest::Proxy::all(format!("socks5h://{}:{}@127.0.0.1:{port}", login.0, login.1)) { + Ok(p) => p, + Err(e) => return Fetch { error: e.to_string(), ..Default::default() }, + }) + .redirect(reqwest::redirect::Policy::none()) + .user_agent(USER_AGENT) + .connect_timeout(Duration::from_secs(8)) + .timeout(Duration::from_secs(15)) + .build(); + let client = match client { + Ok(c) => c, + Err(e) => return Fetch { error: e.to_string(), ..Default::default() }, + }; + let mut url = format!("https://{domain}{path}"); + let site = ap::site(&url); + let mut result = Fetch::default(); + for _ in 0..6 { + result = match client.get(&url).send().await { + Err(e) => return Fetch { error: short_error(&e), ..Default::default() }, + Ok(mut resp) => { + let status = resp.status().as_u16(); + let head: String = resp.headers().iter().map(|(k, v)| format!("{k}: {}\r\n", String::from_utf8_lossy(v.as_bytes()))).collect(); + let location = resp + .headers() + .get(reqwest::header::LOCATION) + .and_then(|l| l.to_str().ok()) + .and_then(|l| resp.url().join(l).ok()) + .map(|u| u.to_string()) + .unwrap_or_default(); + // Enough to judge a refusal by (its first 8 KiB) and to count what came. + let mut body = Vec::new(); + while body.len() < 64 * 1024 { + match resp.chunk().await { + Ok(Some(c)) => body.extend_from_slice(&c), + _ => break, + } + } + Fetch { status: Some(status), block: ap::block_page(status, &head, &body), location, bytes: body.len() as u64, error: String::new() } + } + }; + let redirect = result.status.is_some_and(|s| (300..400).contains(&s)); + if !redirect || ap::redirect_is_block(&result.location) || result.location.is_empty() { + break; + } + if ap::site(&result.location) != site || ap::local_target(&result.location) || !result.location.starts_with("http") { + break; + } + url = result.location.clone(); + } + result +} + +fn short_error(e: &reqwest::Error) -> String { + if e.is_timeout() { + "timed out".into() + } else if e.is_connect() { + "could not connect".into() + } else { + let mut s = e.to_string(); + let mut src = std::error::Error::source(e); + while let Some(inner) = src { + s = inner.to_string(); + src = inner.source(); + } + s.chars().take(120).collect() + } +} + +/// A plain GET through a probe listener, for the egress address and an exit's network. +async fn get_text(port: u16, login: &(String, String), url: &str) -> Option { + let client = reqwest::Client::builder() + .proxy(reqwest::Proxy::all(format!("socks5h://{}:{}@127.0.0.1:{port}", login.0, login.1)).ok()?) + .user_agent(USER_AGENT) + .timeout(Duration::from_secs(10)) + .build() + .ok()?; + let resp = client.get(url).send().await.ok()?; + if !resp.status().is_success() { + return None; + } + let text = resp.text().await.ok()?; + (text.len() < 64 * 1024).then_some(text) +} + +/// The probe listeners, when autoProxy runs with the local proxy. +pub fn exits(s: &crate::service::Service) -> Option { + let cfg = s.cfg(); + if !(cfg.enable && cfg.proxy.enable && cfg.proxy.auto_proxy.enable) || s.sup.state_of(SOCKS_UNIT) != UnitState::Active { + return None; + } + let list = s.last.as_ref()?.probe_exits.clone(); + (!list.is_empty()).then(|| Exits { list, login: (s.store.secrets.hop_user.clone(), s.store.secrets.hop_password.clone()) }) +} + +fn excluded(opts: &Options, host: &str) -> bool { + opts.exclude.iter().any(|x| { + let x = x.trim_start_matches('.').to_ascii_lowercase(); + host == x || host.ends_with(&format!(".{x}")) + }) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Mode { + /// Everything: rechecks, the backlog, the requests. + Full, + /// `proxy-ctl proxy auto learn`'s hosts only. + Requests, +} + +/// One run. Each verdict is saved as it comes: a run cut short keeps what it learned. +pub async fn run(shared: &Shared, mode: Mode) { + let (exits, opts, paths, disabled, auto) = { + let s = shared.lock().await; + let Some(exits) = exits(&s) else { return }; + let disabled = s.last.as_ref().map(|r| r.inventory.disabled.clone()).unwrap_or_default(); + (exits, s.cfg().proxy.auto_proxy.clone(), s.paths().clone(), disabled, s.ap.clone()) + }; + let _turn = auto.lock.lock().await; + let note = async |line: String| shared.lock().await.sup.note(UNIT, line); + if !exits.up().await { + note("no probe listeners: is the local proxy running?".into()).await; + return; + } + let ttl = u64::from(opts.ttl_days) * 86400; + let now = now(); + let mut state = load(&paths); + let save_and = async |state: &State, publish_too: bool| { + if let Err(e) = save(&paths, state) { + tracing::warn!("autoProxy's state: {e:#}"); + } + if publish_too && let Err(e) = publish(&exits.list, state) { + tracing::warn!("autoProxy's rule-sets: {e:#}"); + } + }; + + // Routes through an exit disabled since: probed again without it. + let gone: Vec<(String, String)> = state.domains.iter().filter(|(_, r)| disabled.contains(&r.exit)).map(|(d, r)| (d.clone(), r.exit.clone())).collect(); + for (d, exit) in &gone { + state.forget(d); + note(format!("forgot {d}: its exit {exit} is disabled")).await; + } + + // Verdicts are about this host's address: a new one discards them. An error page or a + // captive portal must not pass for one. + let direct_port = exits.list[0].port; + if let Some(egress) = get_text(direct_port, &exits.login, "https://api.ipify.org").await.map(|t| t.trim().to_owned()) + && !egress.is_empty() + && egress.chars().all(|c| c.is_ascii_hexdigit() || c == '.' || c == ':') + && state.egress.as_deref() != Some(egress.as_str()) + { + if state.egress.is_some() { + note(format!("egress is now {egress}; discarding everything learned for the old address")).await; + } + state.new_egress(&egress); + } + + // Which network (AS) each exit leaves from, once per TTL. + for e in &exits.list { + if now.saturating_sub(state.exits.get(&e.tag).map_or(0, |x| x.at)) < ttl { + continue; + } + let Some(info) = get_text(e.port, &exits.login, "https://ipinfo.io/json").await.and_then(|t| serde_json::from_str::(&t).ok()) else { + continue; + }; + let Some(ip) = info["ip"].as_str() else { continue }; + let x = state.exits.entry(e.tag.clone()).or_default(); + x.ip = Some(ip.to_owned()); + x.asn = info["org"].as_str().and_then(|o| o.split_whitespace().next()).map(str::to_owned); + x.at = now; + } + state.strike(&[], "", "", now, ttl); + let (r1, r2, _) = ap::rounds(&exits.tags(), &state); + save_and(&state, !gone.is_empty()).await; + + // Walks round 1; round 2 only when it all refused, round 1's refusals kept. + let exits = &exits; + let walk = async |host: &str| -> Probe { + let fetch = |tag: String, path: String| async move { exits.fetch(&tag, host, &path).await }; + let first: Vec = std::iter::once(ap::DIRECT.to_owned()).chain(r1.iter().cloned()).collect(); + let p = ap::walk(host, &first, &PATHS, false, fetch).await; + if matches!(p.verdict.as_str(), "both-fail" | "unreachable") && !r2.is_empty() { + let fetch = |tag: String, path: String| async move { exits.fetch(&tag, host, &path).await }; + let second: Vec = std::iter::once(ap::DIRECT.to_owned()).chain(r2.iter().cloned()).collect(); + let mut q = ap::walk(host, &second, &PATHS, false, fetch).await; + let mut rows = p.rows; + rows.append(&mut q.rows); + q.rows = rows; + return q; + } + p + }; + + let mut requeue: Vec<(String, String)> = Vec::new(); + if mode == Mode::Full { + // Remembered routes, once per TTL. + for (dom, host, exit) in state.due(now, ttl) { + let h = host.as_str(); + let fetch = |tag: String, path: String| async move { exits.fetch(&tag, h, &path).await }; + let p = ap::walk(&host, &[ap::DIRECT.to_owned(), exit.clone()], &PATHS, false, fetch).await; + if p.verdict == "destination" && p.exit.as_deref() == Some(exit.as_str()) { + if let Some(r) = state.domains.get_mut(&dom) { + r.at = now; + } + } else if p.verdict == "ok" { + note(format!("recheck {dom}: reachable directly now, dropping {exit}")).await; + state.domains.remove(&dom); + state.record(&dom, &host, &p, now, ttl); + save_and(&state, true).await; + } else { + note(format!("recheck {dom}: {exit} no longer works ({}), walking again", p.verdict)).await; + state.domains.remove(&dom); + save_and(&state, true).await; + requeue.push((dom, host)); + } + } + // What apps dialled directly since the last run, per host. + let dialled = std::mem::take(&mut *auto.dialled.lock().unwrap()); + let counts: BTreeMap = dialled + .into_iter() + .filter(|(h, _)| ap::host_ok(h) && !excluded(&opts, h)) + .filter_map(|(h, n)| ap::registrable(&h).map(|d| (h, (d, n)))) + .collect(); + state.queue(&counts, now, ttl); + save_and(&state, false).await; + } + + // Probe: the requests, then broken routes, then the backlog. + let mut asked: Vec<(String, String)> = Vec::new(); + { + let mut requests = auto.requests.lock().unwrap(); + let mut seen = BTreeSet::new(); + let taken: Vec = std::mem::take(&mut *requests); + for h in taken { + let h = h.trim().to_ascii_lowercase(); + if !ap::host_ok(&h) || !seen.insert(h.clone()) { + continue; + } + if let Some(d) = ap::registrable(&h) { + asked.push((d, h)); + } + } + let max = opts.probes_per_run as usize; + if asked.len() > max { + requests.extend(asked.split_off(max).into_iter().map(|(_, h)| h)); + } + } + let left = auto.requests.lock().unwrap().len(); + if left > 0 { + note(format!("{left} requested host(s) past probesPerRun wait for the next run")).await; + } + let backlog = if mode == Mode::Full { state.backlog_order(now, ttl) } else { Vec::new() }; + + let mut seen: HashSet = HashSet::new(); + let mut routed: HashSet = HashSet::new(); + let started = Instant::now(); + let mut probed = 0usize; + let rows = asked.iter().map(|r| (r, true)).chain(requeue.iter().chain(backlog.iter()).map(|r| (r, false))); + for ((dom, host), was_asked) in rows { + if !was_asked && probed >= opts.probes_per_run as usize { + break; + } + // A run of tarpits must not go on for good: what is left waits for the next. + if started.elapsed() > Duration::from_secs(2 * 3600) { + note("a run ends after two hours; the rest wait for the next".into()).await; + break; + } + if !seen.insert(host.clone()) || routed.contains(dom) { + continue; + } + if !was_asked { + probed += 1; + } + if !exits.up().await { + note("the probe listeners went away; the run ends".into()).await; + break; + } + let p = walk(host).await; + state.record(dom, host, &p, now, ttl); + let destination = p.verdict == "destination"; + if destination { + routed.insert(dom.clone()); + } + save_and(&state, destination).await; + let how = match (&p.verdict[..], &p.exit) { + ("destination", Some(x)) => format!("destination via {x}"), + ("censor", Some(x)) => format!("censor ({x} reaches it; left to zapret)"), + (v, _) => v.to_owned(), + }; + note(format!("probe {host} -> {how}")).await; + } + if mode == Mode::Full || !asked.is_empty() { + note(format!("probed {} requested and {probed} queued host(s); {} still waiting", asked.len(), state.backlog.len())).await; + } + save_and(&state, true).await; +} + +/// The prober's schedule: a first run ten minutes after start (as upstream's timer; sooner with +/// a shorter `interval`), then every `interval`; a learn request wakes it for the requests alone. +pub async fn runner(shared: Shared) { + let (auto, every) = { + let s = shared.lock().await; + (s.ap.clone(), interval(&s.cfg().proxy.auto_proxy)) + }; + let mut next = Instant::now() + every.min(Duration::from_secs(600)); + loop { + tokio::select! { + _ = tokio::time::sleep_until(next.into()) => { + run(&shared, Mode::Full).await; + next = Instant::now() + interval(&shared.lock().await.cfg().proxy.auto_proxy); + } + _ = auto.wake.notified() => run(&shared, Mode::Requests).await, + } + } +} + +/// `interval`, a minute at least. +fn interval(opts: &Options) -> Duration { + ps_core::duration::parse(&opts.interval).unwrap_or(Duration::from_secs(600)).max(Duration::from_secs(60)) +} + +/// The hosts the local proxy's clients dial directly, from the Clash API's connections, every +/// ten seconds while autoProxy runs: what the prober's backlog is made of. +pub async fn sample(shared: Shared) { + let mut seen: HashSet = HashSet::new(); + loop { + tokio::time::sleep(Duration::from_secs(10)).await; + let (clash, auto) = { + let s = shared.lock().await; + let cfg = s.cfg(); + if exits(&s).is_none() { + continue; + } + (crate::clash::Clash::new(cfg.proxy.sing_box.clash_api_port, &s.store.secrets.clash_secret), s.ap.clone()) + }; + let Ok(v) = clash.connections().await else { continue }; + let mut dialled = auto.dialled.lock().unwrap(); + for c in v["connections"].as_array().into_iter().flatten() { + let Some(id) = c["id"].as_str() else { continue }; + if !seen.insert(id.to_owned()) { + continue; + } + let m = &c["metadata"]; + let inbound = m["type"].as_str().unwrap_or(""); + if inbound.contains("probe-in-") || inbound.contains("proxy-suite-test-in") { + continue; + } + // Only what went direct: the rest is routed already. + let chains: Vec<&str> = c["chains"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + if chains != [ap::DIRECT] { + continue; + } + let port = m["destinationPort"].as_str().map(str::to_owned).or_else(|| m["destinationPort"].as_u64().map(|p| p.to_string())); + if !matches!(port.as_deref(), Some("443" | "80")) { + continue; + } + let host = m["host"].as_str().unwrap_or("").to_ascii_lowercase(); + if ap::host_ok(&host) { + *dialled.entry(host).or_insert(0) += 1; + } + } + if seen.len() > 50_000 { + seen.clear(); + } + // Bounded between runs, as the backlog is. + if dialled.len() > 20_000 { + let mut v: Vec<(String, u64)> = std::mem::take(&mut *dialled).into_iter().collect(); + v.sort_by_key(|a| std::cmp::Reverse(a.1)); + v.truncate(10_000); + *dialled = v.into_iter().collect(); + } + } +} + +/// What `proxy-ctl proxy auto` lists. +pub fn listing(paths: &Paths, exits: Option<&Exits>, opts: &Options) -> Value { + let s = load(paths); + let domains: Vec = s.domains.iter().map(|(d, r)| json!({ "domain": d, "exit": r.exit, "verdict": r.verdict, "host": r.host, "at": r.at })).collect(); + let exit_list: Vec = s + .exits + .iter() + .map(|(t, e)| json!({ "tag": t, "ip": e.ip, "asn": e.asn, "bad": e.bad, "badBy": e.bad_by })) + .collect(); + let censored: Vec<&String> = s.hosts.iter().filter(|(_, h)| h.verdict == "censor").map(|(h, _)| h).collect(); + json!({ + "enabled": opts.enable, + "running": exits.is_some(), + "egress": s.egress, + "lastRun": s.last_run, + "domains": domains, + "exits": exit_list, + "probeExits": exits.map(|e| e.tags()).unwrap_or_default(), + "hostsJudged": s.hosts.len(), + "censored": censored, + "backlog": s.backlog.len(), + }) +} + +/// `forget ` or `clear`, under the prober's lock, published at once. +pub async fn edit(shared: &Shared, forget: Option<&str>) -> Result<()> { + let (paths, auto, list) = { + let s = shared.lock().await; + (s.paths().clone(), s.ap.clone(), s.last.as_ref().map(|r| r.probe_exits.clone()).unwrap_or_default()) + }; + let _turn = auto.lock.lock().await; + let mut state = load(&paths); + match forget { + Some(d) => { + if !ap::host_ok(d) { + bail!("'{d}' is not a domain"); + } + state.forget(&d.to_ascii_lowercase()); + } + None => state.clear(), + } + save(&paths, &state)?; + publish(&list, &state) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exclusions_take_subdomains() { + let opts = Options { exclude: vec!["internal.example".into()], ..Default::default() }; + assert!(excluded(&opts, "internal.example")); + assert!(excluded(&opts, "a.internal.example")); + assert!(!excluded(&opts, "notinternal.example")); + } + + #[test] + fn published_rule_sets_follow_the_state() { + let d = std::env::temp_dir().join(format!("ps-ap-{}", std::process::id())); + let path = d.join("rs-1.json"); + let exits = [ + ProbeExit { tag: "direct".into(), port: 1, rule_set: None, path: None }, + ProbeExit { tag: "nl".into(), port: 2, rule_set: Some("autoproxy-1".into()), path: Some(path.to_string_lossy().into()) }, + ]; + let mut s = State::default(); + s.domains.insert("x.example".into(), ap::Route { verdict: "destination".into(), exit: "nl".into(), host: "x.example".into(), path: "/".into(), at: 1 }); + publish(&exits, &s).unwrap(); + let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(v, json!({ "version": 1, "rules": [{ "domain_suffix": ["x.example"] }] })); + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/windows/crates/ps-service/src/clash.rs b/windows/crates/ps-service/src/clash.rs index bc8c959..52b95a2 100644 --- a/windows/crates/ps-service/src/clash.rs +++ b/windows/crates/ps-service/src/clash.rs @@ -44,6 +44,11 @@ impl Clash { Ok(body) } + /// The connections open now, with where each goes and through what. + pub async fn connections(&self) -> Result { + self.get("/connections").await + } + /// Every proxy (outbound or group) with what a selector holds now. pub async fn proxies(&self) -> Result { self.get("/proxies").await.map(|v| v["proxies"].clone()) diff --git a/windows/crates/ps-service/src/main.rs b/windows/crates/ps-service/src/main.rs index 9c9930e..6babe00 100644 --- a/windows/crates/ps-service/src/main.rs +++ b/windows/crates/ps-service/src/main.rs @@ -4,6 +4,7 @@ //! it); `--console` runs it in the foreground, which is also how it runs off Windows. mod api; +mod autoproxy; mod awg; mod clash; mod components; @@ -103,6 +104,8 @@ pub async fn run( tracing::warn!("not starting the proxy yet: {e}"); } tokio::spawn(api::serve(server, shared.clone())); + tokio::spawn(autoproxy::runner(shared.clone())); + tokio::spawn(autoproxy::sample(shared.clone())); // First fetches: what the configuration needs and has not got yet. { let shared = shared.clone(); diff --git a/windows/crates/ps-service/src/service.rs b/windows/crates/ps-service/src/service.rs index e3e2cfe..940cf66 100644 --- a/windows/crates/ps-service/src/service.rs +++ b/windows/crates/ps-service/src/service.rs @@ -39,6 +39,8 @@ pub struct Service { tcp_timestamps_on: bool, /// What whitelist-bypass's units waited for at the last apply, said when it first did. wl_waiting: BTreeSet, + /// autoProxy's requests and the hosts its prober learns from (crate::autoproxy). + pub ap: Arc, } fn digest(data: &[u8]) -> String { @@ -62,6 +64,7 @@ impl Service { last_fetch: BTreeMap::new(), tcp_timestamps_on: false, wl_waiting: BTreeSet::new(), + ap: Arc::default(), store, }) } @@ -136,6 +139,7 @@ impl Service { ssh_identity_path: cfg.ssh_proxy.identity_file.as_ref().map(|_| crate::ssh::identity_path(paths).to_string_lossy().into_owned()), ssh_host_keys: if cfg.ssh_proxy.enable { crate::ssh::host_keys(cfg, |f| std::fs::read_to_string(f).ok()) } else { Vec::new() }, windows: cfg!(windows), + autoproxy_rules_dir: cfg.proxy.auto_proxy.enable.then(|| crate::autoproxy::rules_dir(paths).to_string_lossy().into_owned()), } } @@ -357,6 +361,10 @@ impl Service { for w in &rendered.warnings { self.sup.note(SOCKS_UNIT, format!("proxy-suite: warning: {w}")); } + // sing-box refuses a local rule-set file that is not there: autoProxy's, written first. + if !rendered.probe_exits.is_empty() { + crate::autoproxy::publish(&rendered.probe_exits, &crate::autoproxy::load(self.paths()))?; + } let backend = self.cfg().proxy.backend; let main_program = match backend { diff --git a/windows/release-notes/0.2.0-pre.1.md b/windows/release-notes/0.2.0-pre.1.md index 684530b..a1ebaae 100644 --- a/windows/release-notes/0.2.0-pre.1.md +++ b/windows/release-notes/0.2.0-pre.1.md @@ -22,6 +22,7 @@ The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ct - The SSH tunnel (`sshProxy`): Windows' own OpenSSH as a SOCKS listener for other programs, and, with `asOutbound`, an outbound of the proxy. Needs Windows' "OpenSSH Client" (there by default since Windows 10 1809). - Tor (`tor`): the Tor Project's own Windows build, with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy. - AmneziaWG as outbounds (`amneziaWg`): profiles from a `.conf`, an AmneziaVPN `vpn://` link or settings; `"userspace"` runs wireproxy-awg (AmneziaWG's obfuscation kept, no driver), `"singBox"` plain WireGuard. WARP devices can be either. +- autoProxy (`proxy.autoProxy`): sites apps reach directly are probed through each exit; one blocked directly but reached through an exit is routed through it, as upstream decides. `proxy-ctl proxy auto` (list, probe, learn, forget, clear). Slow sites (`slowBelowKiBps`) are not routed yet. - whitelist-bypass (`whitelistBypass`): its creators and joiners, built from upstream's source; a joiner is an outbound of the proxy through a video call (WB Stream, Telemost, DION, Bitrix), a creator the call's other end. `proxy-ctl wl join|auth|link|new`. - WARP (`warp`, as a sing-box outbound): devices registered with Cloudflare as wgcf registers them (through the local proxy first, where its API is blocked), or profiles given; several grouped as `warp`. - What is not on Windows yet (the kill switch, AmneziaWG, WARP, Tor, the SSH tunnel, …) is no longer accepted silently: the service warns while it is configured, and the app shows it. @@ -36,7 +37,7 @@ Download `ProxySuite-0.2.0-pre.1-windows-x64-setup.exe` and run it (its SHA-256 The zip is still there, the same files with `install.cmd`. ### Not yet -AmneziaWG as a system-wide VPN, Tor's onion service, the kill switch, server inbounds, the XRay-only backend, zapret2's extended detection and the z2k strategies. +AmneziaWG as a system-wide VPN, Tor's onion service, the kill switch, server inbounds, the XRay-only backend, autoProxy's routing of slow sites, zapret2's extended detection and the z2k strategies. ### Note Unlike upstream, the signed-in user may change every setting by default (`userControl`), except the ones that could run programs or read files as SYSTEM: those always need an administrator. On a shared computer, restrict `userControl.scopes`.