From 3665f7f5a0c7c5f9ab82961fe59778c408ef67b0 Mon Sep 17 00:00:00 2001 From: faumaray Date: Mon, 26 Oct 2026 22:51:30 +0300 Subject: [PATCH] windows: render sing-box and hybrid configs ps-core::render builds what upstream's start scripts assemble with bash and jq: every outbound (declared, subscriptions, SSH, Tor, WARP and AWG as WireGuard endpoints, joiners, wireproxy hops), chains, groups, the pin and the 'proxy' selector per selection mode, routing sections by priority with route modes and the DNS mirror, rule sets, TUN with fake IP, the Clash API, per-app rules by program, and the hybrid XRay sidecar. Integration tests run sing-box check and xray -test on the results. Co-Authored-By: Claude Opus 5.5 --- .../crates/ps-core/src/config/privilege.rs | 4 +- windows/crates/ps-core/src/lib.rs | 1 + windows/crates/ps-core/src/render/groups.rs | 303 ++++++++++ windows/crates/ps-core/src/render/mod.rs | 155 +++++ .../crates/ps-core/src/render/outbounds.rs | 566 ++++++++++++++++++ windows/crates/ps-core/src/render/routing.rs | 396 ++++++++++++ windows/crates/ps-core/src/render/sing_box.rs | 265 ++++++++ windows/crates/ps-core/tests/render.rs | 230 +++++++ 8 files changed, 1918 insertions(+), 2 deletions(-) create mode 100644 windows/crates/ps-core/src/render/groups.rs create mode 100644 windows/crates/ps-core/src/render/mod.rs create mode 100644 windows/crates/ps-core/src/render/outbounds.rs create mode 100644 windows/crates/ps-core/src/render/routing.rs create mode 100644 windows/crates/ps-core/src/render/sing_box.rs create mode 100644 windows/crates/ps-core/tests/render.rs diff --git a/windows/crates/ps-core/src/config/privilege.rs b/windows/crates/ps-core/src/config/privilege.rs index e969622..9cb4287 100644 --- a/windows/crates/ps-core/src/config/privilege.rs +++ b/windows/crates/ps-core/src/config/privilege.rs @@ -38,7 +38,7 @@ fn walk(path: &mut Vec, old: Option<&Value>, new: Option<&Value>, found: if old == new { return; } - match privileged_here(path, new) { + match privileged_here(path) { Some(true) => { found.push(path.join(".")); return; @@ -85,7 +85,7 @@ fn walk_new(path: &mut Vec, value: &Value, found: &mut Vec) { /// `Some(true)`: a change at `path` is privileged. `Some(false)`: it is not, and nothing /// below it is either. `None`: look deeper. -fn privileged_here(path: &[String], new: Option<&Value>) -> Option { +fn privileged_here(path: &[String]) -> Option { if PRIVILEGED_PATHS.iter().any(|p| matches_path(p, path)) { return Some(true); } diff --git a/windows/crates/ps-core/src/lib.rs b/windows/crates/ps-core/src/lib.rs index d1bb56b..9e2e0d8 100644 --- a/windows/crates/ps-core/src/lib.rs +++ b/windows/crates/ps-core/src/lib.rs @@ -7,4 +7,5 @@ pub mod config; pub mod derived; pub mod links; +pub mod render; pub mod wg; diff --git a/windows/crates/ps-core/src/render/groups.rs b/windows/crates/ps-core/src/render/groups.rs new file mode 100644 index 0000000..ee17e69 --- /dev/null +++ b/windows/crates/ps-core/src/render/groups.rs @@ -0,0 +1,303 @@ +//! Outbound groups, resolved against the outbounds a start has: upstream's +//! `outbound-groups.jq`. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use regex::Regex; +use serde::Serialize; +use serde_json::{Value, json}; + +use crate::config::{Group, GroupStrategy}; + +/// What the groups came to. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Resolved { + pub groups: BTreeMap, + /// The sing-box group outbounds, inner groups first. + pub outbounds: Vec, + /// What the top level picks among: outbounds in no group, and outermost groups, in + /// priority order. + pub top: Vec, + /// Groups inside themselves. + pub loops: Vec, + pub warnings: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct GroupInfo { + pub strategy: GroupStrategy, + pub failback: bool, + pub interval: String, + pub members: Vec, + /// The members the group names itself, which the front ends edit. + pub listed: Vec, + pub pinned: String, +} + +/// `*` and `?` over tags. +fn glob_regex(pattern: &str) -> Regex { + let mut out = String::from("^"); + for c in pattern.chars() { + match c { + '*' => out.push_str(".*"), + '?' => out.push('.'), + c => out.push_str(®ex::escape(&c.to_string())), + } + } + out.push('$'); + Regex::new(&out).expect("an escaped pattern") +} + +const LAST: i64 = 1_000_000_000; + +pub struct Inputs<'a> { + /// Every outbound tag, in build order. + pub tags: &'a [String], + /// tag -> where it came from ("sub:" for a subscription entry). + pub sources: &'a HashMap, + pub groups: &'a BTreeMap, + pub priority: &'a BTreeMap, + pub disabled: &'a [String], + /// group -> the member pinned in it. + pub pins: &'a BTreeMap, + pub url: &'a str, + pub interval: &'a str, + pub tolerance: i64, + /// Whether the service drives failover groups through the Clash API; without it a + /// failover group is sing-box's own urltest. + pub watched: bool, +} + +pub fn resolve(inp: &Inputs) -> Resolved { + let names: Vec<&String> = inp.groups.keys().collect(); + let is_group = |t: &str| inp.groups.contains_key(t); + let position: HashMap<&str, i64> = inp.tags.iter().enumerate().map(|(i, t)| (t.as_str(), i as i64)).collect(); + let prio = |t: &str| inp.priority.get(t).copied().unwrap_or(LAST); + let pos = |t: &str| position.get(t).copied().unwrap_or(LAST); + let mut warnings = Vec::new(); + + // Members as configured: the explicit list in its order, then the rest by priority, + // then build order. A member that names nothing is dropped with a warning. + let mut members: BTreeMap> = BTreeMap::new(); + for g in &names { + let cfg = &inp.groups[*g]; + let explicit: Vec<&String> = cfg.outbounds.iter().filter(|t| *t != *g).collect(); + let missing: Vec<&String> = + explicit.iter().copied().filter(|t| !inp.tags.contains(t) && !is_group(t)).collect(); + let patterns: Vec = cfg.match_.iter().map(|p| glob_regex(p)).collect(); + let mut pulled: Vec = inp + .tags + .iter() + .filter(|t| { + cfg.subscriptions.iter().any(|s| inp.sources.get(*t).is_some_and(|src| *src == format!("sub:{s}"))) + }) + .cloned() + .collect(); + pulled.extend( + inp.tags + .iter() + .chain(names.iter().copied()) + .filter(|t| *t != *g && patterns.iter().any(|p| p.is_match(t))) + .cloned(), + ); + pulled.sort(); + pulled.dedup(); + let mut rest: Vec = pulled.into_iter().filter(|t| !explicit.contains(&t)).collect(); + rest.sort_by(|a, b| (prio(a), pos(a), a.as_str()).cmp(&(prio(b), pos(b), b.as_str()))); + let mut list: Vec = explicit.iter().filter(|t| !missing.contains(t)).map(|t| (*t).clone()).collect(); + list.extend(rest); + members.insert((*g).clone(), list); + for m in missing { + warnings.push(format!("group '{g}': member '{m}' is not available; leaving it out")); + } + } + + // A group inside itself, however deep, has no member to end on. + fn reach(g: &str, seen: &mut Vec, members: &BTreeMap>, out: &mut Vec) { + let subs: Vec<&String> = members[g].iter().filter(|m| members.contains_key(*m)).collect(); + for m in &subs { + out.push((*m).clone()); + } + for m in subs { + if !seen.contains(m) { + seen.push(m.clone()); + reach(m, seen, members, out); + } + } + } + let reach_of = |g: &str| { + let mut out = Vec::new(); + reach(g, &mut vec![g.to_owned()], &members, &mut out); + out + }; + let loops: Vec = names.iter().filter(|g| reach_of(g).contains(g)).map(|g| (*g).clone()).collect(); + + // Where a group sits when nothing sets its priority: where its first member would have. + fn spot(g: &str, seen: &mut Vec, members: &BTreeMap>, position: &HashMap<&str, i64>) -> Option { + members[g] + .iter() + .filter_map(|m| { + if members.contains_key(m) && !seen.contains(m) { + seen.push(m.clone()); + spot(m, seen, members, position) + } else { + position.get(m.as_str()).copied() + } + }) + .min() + } + let spots: HashMap<&str, i64> = names + .iter() + .map(|g| (g.as_str(), spot(g, &mut vec![(*g).clone()], &members, &position).unwrap_or(LAST))) + .collect(); + + let grouped: HashSet<&String> = members.values().flatten().collect(); + let mut top: Vec = + inp.tags.iter().chain(names.iter().copied()).filter(|t| !grouped.contains(t)).cloned().collect(); + top.sort_by_key(|t| (prio(t), position.get(t.as_str()).or(spots.get(t.as_str())).copied().unwrap_or(LAST))); + + let mut groups = BTreeMap::new(); + let mut outbounds = Vec::new(); + for g in &names { + let cfg = &inp.groups[*g]; + let all = &members[*g]; + let usable: Vec<&String> = all.iter().filter(|t| !inp.disabled.contains(t)).collect(); + let pin = inp.pins.get(*g).cloned().unwrap_or_default(); + let pinned = if pin.is_empty() { + String::new() + } else if !all.contains(&pin) { + warnings.push(format!("group '{g}': pinned member '{pin}' is not in it; picking automatically")); + String::new() + } else if inp.disabled.contains(&pin) { + warnings.push(format!("group '{g}': pinned member '{pin}' is disabled; picking automatically")); + String::new() + } else { + pin + }; + if usable.is_empty() { + // With nothing to pick, the group blocks rather than disappear: rules naming it + // must not fall through to direct. + warnings.push(format!("group '{g}' has no available member; it blocks until one is")); + } + let all_or_block: Vec = if all.is_empty() { vec!["block".into()] } else { all.clone() }; + let usable_or_block: Vec = + if usable.is_empty() { vec!["block".into()] } else { usable.iter().map(|t| (*t).clone()).collect() }; + let interval = cfg.interval.clone().unwrap_or_else(|| { + if cfg.strategy == GroupStrategy::Urltest { inp.interval.to_owned() } else { "30s".into() } + }); + groups.insert( + (*g).clone(), + GroupInfo { + strategy: cfg.strategy, + failback: cfg.failback, + interval: interval.clone(), + members: all_or_block.clone(), + listed: cfg.outbounds.iter().filter(|t| *t != *g).cloned().collect(), + pinned: pinned.clone(), + }, + ); + let as_urltest = (cfg.strategy == GroupStrategy::Urltest + || (cfg.strategy == GroupStrategy::Failover && !inp.watched)) + && pinned.is_empty(); + outbounds.push(if as_urltest { + json!({ + "type": "urltest", "tag": g, "outbounds": usable_or_block, "url": inp.url, + "interval": cfg.interval.clone().unwrap_or_else(|| inp.interval.to_owned()), "tolerance": inp.tolerance, + }) + } else { + // A pin holds any strategy: a selector the Clash API switches. + let mut sel = json!({ + "type": "selector", "tag": g, "outbounds": all_or_block, + "default": if pinned.is_empty() { usable_or_block[0].clone() } else { pinned.clone() }, + }); + if cfg.strategy == GroupStrategy::Failover { + sel["interrupt_exist_connections"] = true.into(); + } + sel + }); + } + // Inner groups first: sing-box wants an outbound defined before a group names it. + let depth = |t: &str| names.iter().filter(|g| reach_of(g).iter().any(|r| r == t)).count(); + outbounds.sort_by_key(|o| std::cmp::Reverse(depth(o["tag"].as_str().unwrap_or("")))); + + Resolved { groups, outbounds, top, loops, warnings } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn group(outbounds: &[&str], strategy: GroupStrategy) -> Group { + Group { outbounds: outbounds.iter().map(|s| s.to_string()).collect(), strategy, ..Default::default() } + } + + fn run(tags: &[&str], groups: BTreeMap, sources: &[(&str, &str)]) -> Resolved { + let tags: Vec = tags.iter().map(|s| s.to_string()).collect(); + let sources = sources.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect(); + resolve(&Inputs { + tags: &tags, + sources: &sources, + groups: &groups, + priority: &BTreeMap::new(), + disabled: &[], + pins: &BTreeMap::new(), + url: "https://www.gstatic.com/generate_204", + interval: "3m", + tolerance: 50, + watched: true, + }) + } + + #[test] + fn members_leave_the_top_level() { + let mut groups = BTreeMap::new(); + groups.insert("eu".into(), group(&["de", "nl"], GroupStrategy::Failover)); + let r = run(&["de", "nl", "us"], groups, &[]); + assert_eq!(r.top, ["eu", "us"]); + assert_eq!(r.groups["eu"].members, ["de", "nl"]); + assert_eq!(r.outbounds[0]["type"], "selector"); + assert_eq!(r.outbounds[0]["interrupt_exist_connections"], true); + } + + #[test] + fn subscriptions_and_patterns_pull_members_in() { + let mut groups = BTreeMap::new(); + groups.insert( + "pool".into(), + Group { subscriptions: vec!["s".into()], match_: vec!["de-*".into()], strategy: GroupStrategy::Urltest, ..Default::default() }, + ); + let r = run(&["de-1", "s-a", "s-b", "us"], groups, &[("s-a", "sub:s"), ("s-b", "sub:s")]); + assert_eq!(r.groups["pool"].members, ["de-1", "s-a", "s-b"]); + assert_eq!(r.outbounds[0]["type"], "urltest"); + assert_eq!(r.outbounds[0]["interval"], "3m"); + } + + #[test] + fn loops_and_missing_members_are_reported() { + let mut groups = BTreeMap::new(); + groups.insert("a".into(), group(&["b", "ghost"], GroupStrategy::Failover)); + groups.insert("b".into(), group(&["a"], GroupStrategy::Failover)); + let r = run(&["x"], groups, &[]); + assert_eq!(r.loops, ["a", "b"]); + assert!(r.warnings.iter().any(|w| w.contains("'ghost'"))); + } + + #[test] + fn an_empty_group_blocks() { + let mut groups = BTreeMap::new(); + groups.insert("g".into(), group(&[], GroupStrategy::Selector)); + let r = run(&["x"], groups, &[]); + assert_eq!(r.outbounds[0]["outbounds"], json!(["block"])); + assert_eq!(r.outbounds[0]["default"], "block"); + } + + #[test] + fn inner_groups_come_first() { + let mut groups = BTreeMap::new(); + groups.insert("a-outer".into(), group(&["z-inner"], GroupStrategy::Selector)); + groups.insert("z-inner".into(), group(&["x"], GroupStrategy::Selector)); + let r = run(&["x"], groups, &[]); + assert_eq!(r.outbounds[0]["tag"], "z-inner"); + assert_eq!(r.top, ["a-outer"]); + } +} diff --git a/windows/crates/ps-core/src/render/mod.rs b/windows/crates/ps-core/src/render/mod.rs new file mode 100644 index 0000000..1247a29 --- /dev/null +++ b/windows/crates/ps-core/src/render/mod.rs @@ -0,0 +1,155 @@ +//! The configs the backends run, from the configuration, the service's runtime state and +//! 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. + +pub mod groups; +mod outbounds; +mod routing; +mod sing_box; + +use std::collections::{BTreeMap, HashMap}; +use std::fmt; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::config::{Config, RouteMatch, RuleSetFormat}; + +pub use outbounds::Inventory; +pub use routing::{WantedRuleSet, wanted_rule_sets}; + +/// `proxy-ctl proxy mode`: an override of `proxy.routing.default` and the lists it keeps. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum RouteMode { + /// Everything proxied but the direct lists (`routing.default = "proxy"`). + Blacklist, + /// Everything direct but the proxy lists (`routing.default = "direct"`). + Whitelist, + /// Everything proxied: only the proxy and block lists are kept. + AllProxy, + /// Everything direct: only the block lists and private addresses are kept. + AllBypass, +} + +impl RouteMode { + pub fn as_str(self) -> &'static str { + match self { + Self::Blacklist => "blacklist", + Self::Whitelist => "whitelist", + Self::AllProxy => "all-proxy", + Self::AllBypass => "all-bypass", + } + } +} + +/// What the service keeps between starts and changes without touching the configuration: +/// upstream's state files. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct State { + /// `proxy-ctl proxy pin`: the outbound or group "proxy" stands for. + pub pin: Option, + /// `proxy-ctl proxy pin --in `. + pub group_pins: BTreeMap, + /// `proxy-ctl proxy outbounds disable`: kept out of selection and autoProxy, still usable + /// by name. Subscription entries too, which the configuration does not list. + pub disabled: Vec, + pub route_mode: Option, +} + +/// A rule set file the service has downloaded. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RuleSetFile { + pub path: String, + pub format: RuleSetFormat, +} + +/// What the service provides beyond the configuration: files it fetched or generated, and +/// where things live on this host. +#[derive(Debug, Clone, Default)] +pub struct Env { + /// Downloaded rule sets by tag (`geosite-google`, `geoip-ru`, `ruleset-`, + /// `ruleset--dns`). + pub rule_sets: BTreeMap, + /// An empty source rule set, for one not downloaded yet: it matches nothing until it is. + pub empty_rule_set: String, + /// Where sing-box keeps its fake IP cache. + pub cache_dir: String, + /// The Clash API's secret: the API is on loopback, where any local program could reach it. + pub clash_secret: Option, + /// The login of the loopback SOCKS hops the service runs (wireproxy, joiners), so other + /// local users cannot use them to get past the routing. + pub hop_login: Option<(String, String)>, + /// WARP profiles by device tag: given in the configuration or registered. + pub warp_profiles: BTreeMap, + /// AmneziaWG `.conf` text of the "singBox" outbounds, by profile name. + pub awg_profiles: BTreeMap, + /// Full paths of the helper programs whose own connections must go direct under TUN + /// (Tor, the XRay sidecar, wireproxy, …), as Linux upstream does with socket marks. + pub direct_processes: Vec, + /// zapret's domains and addresses for `zapret.directSync`, read from its lists. + pub zapret_direct: RouteMatch, + /// Whether the service drives failover through the Clash API. Without it, failover is + /// sing-box's own urltest. + pub groups_watched: bool, + /// The SSH outbound's key and the server's host keys, read by the service. + pub ssh_identity_path: Option, + pub ssh_host_keys: Vec, + /// A UUID drawn per start: the hybrid sidecar's client ids are made from it, so no other + /// local user can guess one. + pub sidecar_secret: String, + /// Running on Windows: the TUN takes Windows' fields only. + pub windows: bool, +} + +pub struct Input<'a> { + pub cfg: &'a Config, + pub state: &'a State, + /// Each subscription's cached links, by tag, as fetched last. + pub subscriptions: &'a BTreeMap>, + pub env: &'a Env, + /// Reads a file an option names (`urlFile`, `passwordFile`, …). + pub read_file: &'a dyn Fn(&str) -> Result, + /// Render for the global TUN as well as the local proxy. + pub tun: bool, +} + +/// What the backends run, and what proxy-ctl and the app show about it. +#[derive(Debug, Clone, PartialEq)] +pub struct Rendered { + /// sing-box's config (the "sing-box" and "hybrid" backends). + pub sing_box: Option, + /// XRay's: the whole proxy on the "xray" backend, the sidecar on "hybrid". + pub xray: Option, + pub inventory: Inventory, + pub warnings: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RenderError(pub String); + +impl fmt::Display for RenderError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for RenderError {} + +/// The proxy's backend configs. +pub fn render(input: &Input) -> Result { + let mut warnings = Vec::new(); + 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 }) + } + crate::config::Backend::Xray => Err(RenderError( + "the \"xray\" backend is not rendered yet on Windows; use \"sing-box\" or \"hybrid\"".into(), + )), + } +} + +pub(crate) type Sources = HashMap; diff --git a/windows/crates/ps-core/src/render/outbounds.rs b/windows/crates/ps-core/src/render/outbounds.rs new file mode 100644 index 0000000..a48efb8 --- /dev/null +++ b/windows/crates/ps-core/src/render/outbounds.rs @@ -0,0 +1,566 @@ +//! Every outbound a start has, chained, grouped, and behind the "proxy" selector: upstream's +//! `service/script-blocks/outbounds.nix`. +//! +//! Upstream fails the start over a declared outbound it cannot build and skips a runtime one +//! with a warning. Here everything is edited at runtime, so an outbound that cannot be built +//! is left out with a warning, and what names it (a chain, a rule) is left out after it. Only +//! having no outbound at all, or nothing selection may pick, stops the start. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use serde::Serialize; +use serde_json::{Value, json}; + +use super::groups::{self, GroupInfo}; +use super::{Input, RenderError, Sources}; +use crate::config::{Backend, OutboundBackend, Selection}; +use crate::derived::{self, ExtraKind}; +use crate::links::{self, LinkBackend, subscription}; + +/// What proxy-ctl and the app read about the outbounds: upstream's `outbounds.json`. +#[derive(Debug, Clone, Default, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Inventory { + /// Every outbound tag, in build order. + pub tags: Vec, + /// tag -> where it came from: "static", "sub:", "ssh", "warp", "tor", "awg", + /// "whitelist-bypass". + pub sources: BTreeMap, + pub pinned: String, + pub selection: String, + /// tag -> the outbound it chains through. + pub detours: BTreeMap, + /// Top-level tags selection leaves alone (`selectionExclude`, Tor). + pub excluded: Vec, + pub disabled: Vec, + pub groups: BTreeMap, + pub top: Vec, + pub priority: BTreeMap, + pub url: String, + /// The outbounds that are real exits (no selector or urltest), for autoProxy and tests. + pub exits: Vec, + /// tag -> the link it came from, to share it back. + pub links: BTreeMap, + /// tag -> the backend that runs it, on hybrid. + pub runs_on: BTreeMap, +} + +/// The outbounds, before the backend template takes them. +pub(super) struct Assembly { + /// sing-box outbounds (on hybrid, the sidecar's appear here as hops to it), "proxy" first. + pub outbounds: Vec, + /// sing-box endpoints (WireGuard). + pub endpoints: Vec, + /// The hybrid sidecar's XRay outbounds. + pub xray: Vec, + pub inventory: Inventory, +} + +struct Builder<'a> { + input: &'a Input<'a>, + backend: Backend, + outbounds: Vec, + endpoints: Vec, + xray: Vec, + sources: Sources, + order: Vec, + links: BTreeMap, + runs_on: BTreeMap, +} + +impl Builder<'_> { + fn taken(&self, tag: &str) -> bool { + self.sources.contains_key(tag) || derived::BUILTIN_TAGS.contains(&tag) || tag.starts_with("proxy-suite-") + } + + fn record(&mut self, tag: &str, source: &str) { + self.sources.insert(tag.to_owned(), source.to_owned()); + self.order.push(tag.to_owned()); + } + + fn push(&mut self, ob: Value, source: &str) { + let tag = ob["tag"].as_str().unwrap_or_default().to_owned(); + self.outbounds.push(ob); + self.record(&tag, source); + } + + fn push_endpoint(&mut self, ep: Value, source: &str) { + let tag = ep["tag"].as_str().unwrap_or_default().to_owned(); + self.endpoints.push(ep); + self.record(&tag, source); + } + + /// An XRay outbound on the hybrid backend's sidecar; sing-box reaches it as a hop. + fn push_sidecar(&mut self, ob: Value, source: &str) { + let tag = ob["tag"].as_str().unwrap_or_default().to_owned(); + self.xray.push(ob); + self.runs_on.insert(tag.clone(), "xray".into()); + self.record(&tag, source); + } + + /// A link as this backend's outbound. On hybrid, sing-box first unless the outbound + /// asks for XRay, XRay when sing-box cannot take it. + fn add_url(&mut self, tag: &str, url: &str, pref: OutboundBackend, source: &str) -> Result<(), String> { + match self.backend { + Backend::SingBox => { + let ob = links::build_outbound(url, tag, LinkBackend::SingBox).map_err(|e| e.to_string())?; + self.push(ob, source); + } + Backend::Xray => { + let ob = links::build_outbound(url, tag, LinkBackend::Xray).map_err(|e| e.to_string())?; + self.push(ob, source); + } + Backend::Hybrid => { + let sing = || links::build_outbound(url, tag, LinkBackend::SingBox); + let xray = || links::build_outbound(url, tag, LinkBackend::Xray); + match pref { + OutboundBackend::SingBox => self.push(sing().map_err(|e| e.to_string())?, source), + OutboundBackend::Xray => self.push_sidecar(xray().map_err(|e| e.to_string())?, source), + OutboundBackend::Auto => match sing() { + Ok(ob) => self.push(ob, source), + Err(sing_err) => match xray() { + Ok(ob) => self.push_sidecar(ob, source), + Err(xray_err) => { + return Err(format!( + "cannot be parsed by sing-box ({sing_err}) or XRay ({xray_err})" + )); + } + }, + }, + } + } + } + self.links.insert(tag.to_owned(), url.to_owned()); + Ok(()) + } + + /// A loopback SOCKS hop to a helper the service runs. + fn hop(&self, tag: &str, port: u16, login: bool) -> Value { + let mut ob = json!({ "type": "socks", "tag": tag, "server": "127.0.0.1", "server_port": port }); + if let (true, Some((user, pass))) = (login, &self.input.env.hop_login) { + ob["username"] = user.clone().into(); + ob["password"] = pass.clone().into(); + } + ob + } +} + +pub(super) fn assemble(input: &Input, warnings: &mut Vec) -> Result { + let cfg = input.cfg; + let p = &cfg.proxy; + let mut b = Builder { + input, + backend: p.backend, + outbounds: Vec::new(), + endpoints: Vec::new(), + xray: Vec::new(), + sources: HashMap::new(), + order: Vec::new(), + links: BTreeMap::new(), + runs_on: BTreeMap::new(), + }; + + // Declared outbounds. + for ob in &p.outbounds { + if b.taken(&ob.tag) { + warnings.push(format!("outbound '{}': the tag is taken; leaving it out", ob.tag)); + continue; + } + let result = if let Some(json) = &ob.sing_box_json { + let mut j = json.clone(); + j.insert("tag".into(), ob.tag.clone().into()); + match p.backend { + Backend::Xray => Err("sing-box JSON cannot run on the xray backend".to_owned()), + _ => { + b.push(Value::Object(j), "static"); + Ok(()) + } + } + } else if let Some(json) = &ob.xray_json { + let mut j = json.clone(); + j.insert("tag".into(), ob.tag.clone().into()); + match p.backend { + Backend::SingBox => Err("XRay JSON cannot run on the sing-box backend".to_owned()), + Backend::Xray => { + b.push(Value::Object(j), "static"); + Ok(()) + } + Backend::Hybrid => { + b.push_sidecar(Value::Object(j), "static"); + Ok(()) + } + } + } else { + let url = match (&ob.url, &ob.url_file) { + (Some(url), _) => Ok(url.trim().to_owned()), + (None, Some(file)) => (input.read_file)(file).map(|s| s.trim().to_owned()), + (None, None) => Err("it has no url, urlFile, singBoxJson or xrayJson".to_owned()), + }; + url.and_then(|url| b.add_url(&ob.tag, &url, ob.backend, "static")) + }; + if let Err(e) = result { + warnings.push(format!("outbound '{}': {e}; leaving it out", ob.tag)); + } + } + + // Subscriptions, as last fetched. + let link_backends: Vec = match p.backend { + Backend::SingBox => vec![LinkBackend::SingBox], + Backend::Xray => vec![LinkBackend::Xray], + Backend::Hybrid => vec![LinkBackend::SingBox, LinkBackend::Xray], + }; + for sub in &p.subscriptions { + let Some(lines) = input.subscriptions.get(&sub.tag) else { + warnings.push(format!("subscription '{}' has not been fetched yet", sub.tag)); + continue; + }; + let opts = subscription::Options { allow_private: sub.allow_private_servers, allow_insecure: sub.allow_insecure }; + let parsed = subscription::walk(lines, &sub.tag, &link_backends, opts); + warnings.extend(parsed.warnings.into_iter().map(|w| format!("subscription '{}': {w}", sub.tag))); + let source = format!("sub:{}", sub.tag); + let links: HashMap = parsed.links.into_iter().collect(); + for (backend, ob) in parsed.outbounds { + let tag = ob["tag"].as_str().unwrap_or_default().to_owned(); + if b.taken(&tag) { + warnings.push(format!("subscription '{}': entry '{tag}' takes a tag already in use; leaving it out", sub.tag)); + continue; + } + match (p.backend, backend) { + (Backend::Hybrid, LinkBackend::Xray) => b.push_sidecar(ob, &source), + _ => b.push(ob, &source), + } + if let Some(line) = links.get(&tag) { + b.links.insert(tag, line.clone()); + } + } + } + + // What the tunnels add. + let sing_box = p.backend.runs_sing_box(); + for extra in derived::extra_outbounds(cfg) { + if b.taken(&extra.tag) { + warnings.push(format!("'{}': the tag is taken by an outbound; leaving the tunnel's outbound out", extra.tag)); + continue; + } + match extra.kind { + ExtraKind::Ssh => { + let s = &cfg.ssh_proxy; + if sing_box { + let mut ob = json!({ + "type": "ssh", + "tag": extra.tag, + "server": s.server.host.clone().unwrap_or_default(), + "server_port": s.server.port, + "user": s.server.user.clone().unwrap_or_default(), + }); + let keys = if input.env.ssh_host_keys.is_empty() { &s.host_key } else { &input.env.ssh_host_keys }; + if !keys.is_empty() { + ob["host_key"] = json!(keys); + } + if let Some(path) = &input.env.ssh_identity_path { + ob["private_key_path"] = path.clone().into(); + } + b.push(ob, "ssh"); + } else { + let ob = b.hop(&extra.tag, s.listener.port, false); + b.push(ob, "ssh"); + } + } + ExtraKind::Tor { port } => { + let ob = b.hop(&extra.tag, port, false); + b.push(ob, "tor"); + } + ExtraKind::WlJoiner { port, .. } => { + let ob = b.hop(&extra.tag, port, true); + b.push(ob, "whitelist-bypass"); + } + ExtraKind::Warp { device } => match device.kind { + crate::config::WarpOutboundKind::SingBox => { + let Some(profile) = input.env.warp_profiles.get(&device.tag) else { + warnings.push(format!("WARP device '{}' is not registered yet; it joins once it is", device.tag)); + continue; + }; + match crate::wg::sing_box_endpoint(profile, &device.tag, device.endpoint.as_deref()) { + Ok((mut ep, _)) => { + ep["domain_resolver"] = + json!({ "server": "local", "strategy": cfg.warp.domain_strategy.as_str() }); + b.push_endpoint(ep, "warp"); + } + Err(e) => warnings.push(format!("WARP device '{}': {e}; leaving it out", device.tag)), + } + } + crate::config::WarpOutboundKind::Userspace => { + let ob = b.hop(&device.tag, device.port, true); + b.push(ob, "warp"); + } + }, + ExtraKind::Awg { profile, kind, port } => match kind { + crate::config::AwgOutboundKind::SingBox => { + let Some(conf) = input.env.awg_profiles.get(&profile) else { + warnings.push(format!("AmneziaWG outbound '{profile}': its config could not be read; leaving it out")); + continue; + }; + let endpoint = cfg.amnezia_wg.profiles.get(&profile).and_then(|p| p.endpoint.as_deref()); + match crate::wg::sing_box_endpoint(conf, &profile, endpoint) { + Ok((mut ep, dropped)) => { + if !dropped.is_empty() { + warnings.push(format!( + "AmneziaWG outbound '{profile}': sing-box speaks plain WireGuard; dropping {}. A server that expects them will not answer", + dropped.join(", ") + )); + } + let strategy = cfg.amnezia_wg.profiles.get(&profile).and_then(|p| p.domain_strategy); + ep["domain_resolver"] = match strategy { + Some(s) => json!({ "server": "local", "strategy": s.as_str() }), + None => json!("local"), + }; + b.push_endpoint(ep, "awg"); + } + Err(e) => warnings.push(format!("AmneziaWG outbound '{profile}': {e}; leaving it out")), + } + } + crate::config::AwgOutboundKind::Userspace => { + let ob = b.hop(&profile, port, true); + b.push(ob, "awg"); + } + }, + } + } + + chain(&mut b, warnings); + + if b.order.is_empty() { + return Err(RenderError( + "no proxy outbounds are available; add one, or a subscription that has been fetched".into(), + )); + } + + let disabled: Vec = + input.state.disabled.iter().filter(|t| b.sources.contains_key(*t)).cloned().collect(); + + // Groups, against the outbounds this start has. A group whose name an outbound took, or + // that contains itself, is left out. + let mut group_cfg = p.groups.clone(); + if let Some(warp) = warp_group(cfg) { + group_cfg.entry(derived::WARP_TAG.into()).or_insert(warp); + } + group_cfg.retain(|name, _| { + let free = !b.sources.contains_key(name); + if !free { + warnings.push(format!("group '{name}': an outbound has that tag; leaving the group out")); + } + free + }); + let resolved = loop { + let r = groups::resolve(&groups::Inputs { + tags: &b.order, + sources: &b.sources, + groups: &group_cfg, + priority: &p.priority, + disabled: &disabled, + pins: &input.state.group_pins, + url: &p.url_test.url, + interval: &p.url_test.interval, + tolerance: p.url_test.tolerance, + watched: input.env.groups_watched, + }); + if r.loops.is_empty() { + break r; + } + for g in &r.loops { + warnings.push(format!("group '{g}' contains itself; leaving it out")); + group_cfg.remove(g); + } + }; + warnings.extend(resolved.warnings.iter().cloned()); + + // The pin. + let all_tags: Vec<&String> = b.order.iter().chain(resolved.groups.keys()).collect(); + let mut pinned = input.state.pin.clone().unwrap_or_default(); + if !pinned.is_empty() && !all_tags.contains(&&pinned) { + warnings.push(format!("pinned outbound '{pinned}' is not available; picking automatically")); + pinned.clear(); + } + if !pinned.is_empty() && disabled.contains(&pinned) { + warnings.push(format!("pinned outbound '{pinned}' is disabled; picking automatically")); + pinned.clear(); + } + + // What selection may pick on its own. Tor is only for what is routed to it, unless it is + // the one outbound there is. + let tor_out = derived::extra_outbounds(cfg).iter().any(|o| o.tag == derived::TOR_OUTBOUND_TAG); + let top = &resolved.top; + let selectable: Vec = top + .iter() + .filter(|t| { + !p.selection_exclude.contains(t) + && !disabled.contains(t) + && !(tor_out && top.len() > 1 && *t == derived::TOR_OUTBOUND_TAG) + }) + .cloned() + .collect(); + if pinned.is_empty() && selectable.is_empty() { + return Err(RenderError( + "every outbound is in proxy.selectionExclude or disabled, so there is nothing to select; pin one, enable one, or exclude fewer".into(), + )); + } + + // The detours as they stand, for the inventory. + let detours: BTreeMap = b + .outbounds + .iter() + .chain(&b.endpoints) + .chain(&b.xray) + .filter_map(|o| { + let hop = o.get("detour").or_else(|| o.pointer("/streamSettings/sockopt/dialerProxy"))?; + Some((o["tag"].as_str()?.to_owned(), hop.as_str()?.to_owned())) + }) + .collect(); + + let exits: Vec = b + .order + .iter() + .filter(|t| !(tor_out && *t == derived::TOR_OUTBOUND_TAG)) + .cloned() + .collect(); + + // "proxy", as the selection mode has it, ahead of everything; the groups after the rest. + let mut every: Vec = b.order.clone(); + every.extend(resolved.groups.keys().cloned()); + let default = if pinned.is_empty() { selectable[0].clone() } else { pinned.clone() }; + let wrapper = match p.selection { + Selection::First => json!({ "type": "selector", "tag": "proxy", "outbounds": [default], "default": default }), + Selection::Failover if pinned.is_empty() && !input.env.groups_watched => json!({ + "type": "urltest", "tag": "proxy", "outbounds": selectable, "url": p.url_test.url, + "interval": "30s", "tolerance": p.url_test.tolerance, + }), + Selection::Failover => json!({ + "type": "selector", "tag": "proxy", "outbounds": every, "default": default, + "interrupt_exist_connections": true, + }), + Selection::Selector => json!({ "type": "selector", "tag": "proxy", "outbounds": every, "default": default }), + Selection::Urltest if !pinned.is_empty() => { + json!({ "type": "selector", "tag": "proxy", "outbounds": every, "default": pinned }) + } + Selection::Urltest => json!({ + "type": "urltest", "tag": "proxy", "outbounds": selectable, "url": p.url_test.url, + "interval": p.url_test.interval, "tolerance": p.url_test.tolerance, + }), + }; + let mut outbounds = vec![wrapper]; + outbounds.append(&mut b.outbounds); + outbounds.extend(resolved.outbounds.iter().cloned()); + + let excluded: Vec = top.iter().filter(|t| !selectable.contains(t)).cloned().collect(); + let inventory = Inventory { + tags: b.order.clone(), + sources: b.sources.iter().map(|(k, v)| (k.clone(), v.clone())).collect(), + pinned, + selection: p.selection.as_str().into(), + detours, + excluded, + disabled, + groups: resolved.groups.clone(), + top: top.clone(), + priority: p.priority.clone(), + url: p.url_test.url.clone(), + exits, + links: b.links, + runs_on: b + .order + .iter() + .map(|t| (t.clone(), b.runs_on.get(t).cloned().unwrap_or_else(|| p.backend.as_str().to_owned()))) + .collect(), + }; + Ok(Assembly { outbounds, endpoints: b.endpoints, xray: b.xray, inventory }) +} + +/// With two or more WARP devices, "warp" names a group of them. +fn warp_group(cfg: &crate::config::Config) -> Option { + let devices = derived::warp_devices(cfg); + (devices.len() > 1).then(|| crate::config::Group { + outbounds: devices.into_iter().map(|d| d.tag).collect(), + strategy: cfg.warp.group.strategy, + failback: cfg.warp.group.failback, + ..Default::default() + }) +} + +/// Chains outbounds through their detour hop: upstream's `outbound-detours.jq`. An outbound +/// whose chain cannot be built is left out, and what chained through it is checked again. +fn chain(b: &mut Builder, warnings: &mut Vec) { + let p = &b.input.cfg.proxy; + let declared: HashMap<&str, &str> = + p.outbounds.iter().filter_map(|o| Some((o.tag.as_str(), o.detour.as_deref()?))).collect(); + let by_sub: HashMap = + p.subscriptions.iter().filter_map(|s| Some((format!("sub:{}", s.tag), s.detour.as_deref()?))).collect(); + loop { + let hops: BTreeMap = b + .order + .iter() + .filter_map(|t| { + let hop = declared.get(t.as_str()).copied().or_else(|| by_sub.get(&b.sources[t]).copied())?; + Some((t.clone(), hop.to_owned())) + }) + .collect(); + let tags: HashSet<&String> = b.order.iter().collect(); + let xray_tags: HashSet = b.xray.iter().filter_map(|o| o["tag"].as_str().map(str::to_owned)).collect(); + let mut drop: BTreeMap = BTreeMap::new(); + for (t, hop) in &hops { + if !tags.contains(hop) { + drop.insert(t.clone(), format!("it chains through '{hop}', which is not an outbound")); + continue; + } + // Upstream's test: the chain from t, as long as there are hops plus one, meets t again. + let mut cur = hop.clone(); + let mut back = false; + for _ in 0..=hops.len() { + if cur == *t { + back = true; + break; + } + match hops.get(&cur) { + Some(next) => cur = next.clone(), + None => break, + } + } + if back { + drop.insert(t.clone(), "it chains back to itself".into()); + continue; + } + if b.backend == Backend::Hybrid && xray_tags.contains(t) && !xray_tags.contains(hop) { + drop.insert( + t.clone(), + format!("it runs on XRay and can only chain through another XRay outbound, not '{hop}'"), + ); + } + } + if drop.is_empty() { + for (t, hop) in &hops { + let set = |ob: &mut Value| { + if ob["tag"] == Value::from(t.as_str()) { + if xray_tags.contains(t) || b.backend == Backend::Xray { + ob["streamSettings"]["sockopt"]["dialerProxy"] = hop.clone().into(); + } else { + ob["detour"] = hop.clone().into(); + } + } + }; + b.outbounds.iter_mut().for_each(set); + b.endpoints.iter_mut().for_each(set); + b.xray.iter_mut().for_each(set); + } + return; + } + for (t, why) in drop { + warnings.push(format!("outbound '{t}': {why}; leaving it out")); + let keep = |o: &Value| o["tag"] != Value::from(t.as_str()); + b.outbounds.retain(keep); + b.endpoints.retain(keep); + b.xray.retain(keep); + b.order.retain(|x| *x != t); + b.sources.remove(&t); + b.links.remove(&t); + } + } +} diff --git a/windows/crates/ps-core/src/render/routing.rs b/windows/crates/ps-core/src/render/routing.rs new file mode 100644 index 0000000..ef19ae5 --- /dev/null +++ b/windows/crates/ps-core/src/render/routing.rs @@ -0,0 +1,396 @@ +//! sing-box's route and DNS rules: upstream's `rules/sing-box.nix`, composed by section +//! and priority as `routing-compose.jq` does, with the route mode applied. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; + +use super::{Input, RouteMode}; +use crate::config::{Config, RouteDefault, RouteMatch, RuleSetFormat}; +use crate::derived; + +/// Loopback, as a client of the local proxy could ask for it. +pub(super) const LOOPBACK: [&str; 4] = ["127.0.0.0/8", "::1/128", "0.0.0.0/32", "::/128"]; + +/// A rule set the service should keep downloaded. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WantedRuleSet { + /// The tag the config names it by. + pub tag: String, + pub url: String, + pub format: RuleSetFormat, + /// For a `ruleset--dns` copy: the rule set whose domain rules it holds. Its URL + /// is the original's. + pub dns_copy_of: Option, + /// Fetch through the proxy rather than directly. + pub via_proxy: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Category { + Proxy, + Direct, + Block, + /// Private addresses and the Telegram relay's: direct, but kept in every mode. + Safety, +} + +fn category(target: &str) -> Category { + match target { + "direct" => Category::Direct, + "block" => Category::Block, + _ => Category::Proxy, + } +} + +struct Section { + priority: i64, + category: Category, + rules: Vec, + dns: Vec, +} + +fn geosite(name: &str) -> String { + format!("geosite-{name}") +} + +fn geoip(name: &str) -> String { + format!("geoip-{name}") +} + +fn remote(name: &str) -> String { + format!("ruleset-{name}") +} + +fn remote_dns(name: &str) -> String { + format!("ruleset-{name}-dns") +} + +/// A rule sending what it matches to `outbound` ("block" is the block outbound, which groups +/// with nothing to pick fall back to as well). +fn target(rule: Value, outbound: &str) -> Value { + let mut rule = rule; + rule["outbound"] = outbound.into(); + rule +} + +/// One rule per kind of match, as upstream's `mkCustomRuleEntries`: a rule matches any of +/// them, not all. +fn match_rules(outbound: &str, m: &RouteMatch) -> Vec { + let mut rules = Vec::new(); + if !m.domains.is_empty() { + rules.push(target(json!({ "domain_suffix": m.domains }), outbound)); + } + if !m.ips.is_empty() { + rules.push(target(json!({ "ip_cidr": m.ips }), outbound)); + } + if !m.geosites.is_empty() { + rules.push(target(json!({ "rule_set": m.geosites.iter().map(|s| geosite(s)).collect::>() }), outbound)); + } + if !m.geoips.is_empty() { + rules.push(target(json!({ "rule_set": m.geoips.iter().map(|s| geoip(s)).collect::>() }), outbound)); + } + if !m.rule_sets.is_empty() { + rules.push(target(json!({ "rule_set": m.rule_sets.iter().map(|s| remote(s)).collect::>() }), outbound)); + } + rules +} + +/// The DNS mirror of a match: a name that goes through the proxy is looked up through it. +fn dns_rules(server: &str, domains: &[String], geosites: &[String], rule_sets: &[String]) -> Vec { + let mut rules = Vec::new(); + if !domains.is_empty() { + rules.push(json!({ "domain_suffix": domains, "server": server })); + } + let tags: Vec = geosites.iter().map(|s| geosite(s)).chain(rule_sets.iter().map(|s| remote_dns(s))).collect(); + if !tags.is_empty() { + rules.push(json!({ "rule_set": tags, "server": server })); + } + rules +} + +fn dns_server_for(c: Category) -> &'static str { + if c == Category::Direct { "local" } else { "remote" } +} + +/// The direct lists: the configuration's, zapret's (`zapret.directSync`) and the Russian +/// ones (`routing.directRu`). +pub(super) fn direct_match(input: &Input) -> RouteMatch { + let r = &input.cfg.proxy.routing; + let z = &input.env.zapret_direct; + let uniq = |a: &[String], b: &[String], extra: Option<&str>| { + let mut out: Vec = Vec::new(); + for v in a.iter().chain(b).map(String::as_str).chain(extra) { + if !out.iter().any(|x| x == v) { + out.push(v.to_owned()); + } + } + out + }; + let ru = r.direct_ru; + RouteMatch { + domains: uniq(&r.direct.domains, &z.domains, None), + ips: uniq(&r.direct.ips, &z.ips, None), + geosites: uniq(&r.direct.geosites, &[], ru.then_some("category-ru")), + geoips: uniq(&r.direct.geoips, &[], ru.then_some("ru")), + rule_sets: r.direct.rule_sets.clone(), + } +} + +/// The rules that pick an outbound by program, and the loopback hops' guard: kept in every +/// route mode, ahead of everything that picks by destination, as upstream's pin rules are. +fn always_rules(input: &Input) -> Vec { + let cfg = input.cfg; + let mut rules = Vec::new(); + if !input.env.direct_processes.is_empty() { + rules.push(json!({ "process_path": input.env.direct_processes, "outbound": "direct" })); + } + if cfg.per_app_routing.enable { + for (i, prof) in cfg.per_app_routing.profiles.iter().enumerate() { + let _ = i; + let inbound = per_app_inbound(&prof.name); + rules.push(target(json!({ "inbound": [inbound] }), &prof.outbound)); + if !prof.process_names.is_empty() { + rules.push(target(json!({ "process_name": prof.process_names }), &prof.outbound)); + } + if !prof.process_paths.is_empty() { + rules.push(target(json!({ "process_path": prof.process_paths }), &prof.outbound)); + } + } + } + rules +} + +pub(super) fn per_app_inbound(name: &str) -> String { + format!("per-app-{name}") +} + +/// Every route and DNS rule, in order, and the final outbound and resolver. +pub(super) struct Route { + pub rules: Vec, + pub dns_rules: Vec, + pub final_outbound: &'static str, + pub dns_final: &'static str, + pub rule_set: Vec, +} + +pub(super) fn route(input: &Input, hop_ports: &[u16], known: &dyn Fn(&str) -> bool, warnings: &mut Vec) -> Route { + let cfg = input.cfg; + let r = &cfg.proxy.routing; + let direct = direct_match(input); + + let mut common = vec![ + json!({ "network": ["tcp", "udp"], "port": 53, "action": "hijack-dns" }), + json!({ "action": "sniff" }), + ]; + let onion = derived::tor_route_onion(cfg) && known(derived::TOR_OUTBOUND_TAG); + if onion { + common.push(json!({ "domain_suffix": ["onion"], "outbound": derived::TOR_OUTBOUND_TAG })); + } + // A client asking for a loopback hop would have sing-box dial the helpers' listeners + // for it, past the routing. + if !hop_ports.is_empty() { + common.push(json!({ "ip_cidr": LOOPBACK, "port": hop_ports, "action": "reject" })); + } + common.extend(always_rules(input)); + + // The custom rules: each outbound's own routing, then routing.rules, at their priority. + let mut sections = Vec::new(); + for ob in &cfg.proxy.outbounds { + if ob.routing.is_empty() { + continue; + } + if !known(&ob.tag) { + warnings.push(format!("outbound '{}' is not running: its routing is left out", ob.tag)); + continue; + } + sections.push(custom_section(100, &ob.tag, &ob.routing, &[], &[])); + } + for (i, rule) in r.rules.iter().enumerate() { + if rule.disabled { + continue; + } + let name = rule.name.clone().unwrap_or_else(|| format!("#{i}")); + if !derived::BUILTIN_TAGS.contains(&rule.outbound.as_str()) && !known(&rule.outbound) { + warnings.push(format!("routing rule {name}: no outbound or group named '{}' is running; the rule is left out", rule.outbound)); + continue; + } + sections.push(custom_section( + rule.priority.unwrap_or(100), + &rule.outbound, + &rule.matches, + &rule.process_names, + &rule.process_paths, + )); + } + + let proxy_primary = RouteMatch { domains: r.proxy.domains.clone(), ips: r.proxy.ips.clone(), ..Default::default() }; + let proxy_geo = RouteMatch { + geosites: r.proxy.geosites.clone(), + geoips: r.proxy.geoips.clone(), + rule_sets: r.proxy.rule_sets.clone(), + ..Default::default() + }; + sections.push(Section { + priority: 200, + category: Category::Proxy, + rules: match_rules("proxy", &proxy_primary), + dns: dns_rules("remote", &r.proxy.domains, &[], &[]), + }); + // Block ahead of the direct lists (category-ru's ad domains are in category-ads-all too). + sections.push(Section { priority: 300, category: Category::Block, rules: match_rules("block", &r.block), dns: Vec::new() }); + sections.push(Section { + priority: 400, + category: Category::Direct, + rules: match_rules("direct", &direct), + dns: dns_rules("local", &direct.domains, &direct.geosites, &r.direct.rule_sets), + }); + let mut safety = vec![json!({ "ip_is_private": true, "outbound": "direct" })]; + let tg = &cfg.tg_ws_proxy; + if tg.enable && tg.bypass_transparent_proxy && !tg.dc_ips.is_empty() { + let ips: BTreeSet<&String> = tg.dc_ips.values().collect(); + safety.push(json!({ "ip_cidr": ips, "outbound": "direct" })); + } + sections.push(Section { priority: 400, category: Category::Safety, rules: safety, dns: Vec::new() }); + sections.push(Section { + priority: 500, + category: Category::Proxy, + rules: match_rules("proxy", &proxy_geo), + dns: dns_rules("remote", &[], &r.proxy.geosites, &r.proxy.rule_sets), + }); + + // The mode: the configured default, or proxy-ctl's override. + let mode = input.state.route_mode.unwrap_or(match r.default { + RouteDefault::Proxy => RouteMode::Blacklist, + RouteDefault::Direct => RouteMode::Whitelist, + }); + let (final_outbound, dns_final, clear_dns) = match mode { + RouteMode::Blacklist => ("proxy", "remote", false), + RouteMode::Whitelist => ("direct", "local", false), + RouteMode::AllProxy => ("proxy", "remote", true), + RouteMode::AllBypass => ("direct", "local", true), + }; + let keep = |c: Category| match mode { + RouteMode::AllProxy => c != Category::Direct, + RouteMode::AllBypass => matches!(c, Category::Block | Category::Safety), + _ => true, + }; + // A stable sort: among equals, the list's own order. + sections.sort_by_key(|s| s.priority); + let sections: Vec
= sections.into_iter().filter(|s| keep(s.category)).collect(); + + let mut rules = common; + rules.extend(sections.iter().flat_map(|s| s.rules.iter().cloned())); + + // DNS: the user's rules first (they stay in every mode), then .onion, which no resolver + // may see, then the mirror of the routing. + let mut dns_rules_out: Vec = cfg.proxy.dns.sing_box.rules.iter().map(|r| Value::Object(r.clone())).collect(); + if derived::tor_route_onion(cfg) { + if input.tun && onion { + dns_rules_out.push(json!({ + "inbound": ["tun-in"], "domain_suffix": ["onion"], "query_type": ["A", "AAAA"], "server": "fakeip", + })); + } + dns_rules_out.push(json!({ "domain_suffix": ["onion"], "action": "predefined", "rcode": "NXDOMAIN" })); + } + if !clear_dns { + dns_rules_out.extend(sections.iter().flat_map(|s| s.dns.iter().cloned())); + } + if input.tun && cfg.proxy.dns.fake_ip.enable { + 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) } +} + +fn custom_section(priority: i64, outbound: &str, m: &RouteMatch, names: &[String], paths: &[String]) -> Section { + let c = category(outbound); + let mut rules = match_rules(outbound, m); + if !names.is_empty() { + rules.push(target(json!({ "process_name": names }), outbound)); + } + if !paths.is_empty() { + rules.push(target(json!({ "process_path": paths }), outbound)); + } + let dns = if c == Category::Block { Vec::new() } else { dns_rules(dns_server_for(c), &m.domains, &m.geosites, &m.rule_sets) }; + Section { priority, category: c, rules, dns } +} + +/// Every geosite, geoip and declared rule set the routing names. +fn referenced(cfg: &Config) -> (BTreeSet, BTreeSet) { + let r = &cfg.proxy.routing; + let mut sites = BTreeSet::new(); + let mut ips = BTreeSet::new(); + let mut add = |m: &RouteMatch| { + sites.extend(m.geosites.iter().cloned()); + ips.extend(m.geoips.iter().cloned()); + }; + add(&r.proxy); + add(&r.direct); + add(&r.block); + r.rules.iter().filter(|x| !x.disabled).for_each(|x| add(&x.matches)); + cfg.proxy.outbounds.iter().for_each(|o| add(&o.routing)); + if r.direct_ru { + sites.insert("category-ru".into()); + ips.insert("ru".into()); + } + (sites, ips) +} + +/// What the service should keep downloaded for this configuration. +pub fn wanted_rule_sets(cfg: &Config) -> Vec { + if !cfg.proxy.enable || !cfg.proxy.backend.runs_sing_box() { + return Vec::new(); + } + let (sites, ips) = referenced(cfg); + let g = &cfg.geodata.sing_box; + let mut out: Vec = sites + .iter() + .map(|s| WantedRuleSet { + tag: geosite(s), + url: format!("{}/{}.srs", g.geosite.trim_end_matches('/'), geosite(s)), + format: RuleSetFormat::Binary, + dns_copy_of: None, + via_proxy: false, + }) + .chain(ips.iter().map(|s| WantedRuleSet { + tag: geoip(s), + url: format!("{}/{}.srs", g.geoip.trim_end_matches('/'), geoip(s)), + format: RuleSetFormat::Binary, + dns_copy_of: None, + via_proxy: false, + })) + .collect(); + for (name, rs) in &cfg.proxy.routing.rule_sets { + let via_proxy = rs.detour == crate::config::RuleSetDetour::Proxy; + out.push(WantedRuleSet { tag: remote(name), url: rs.url.clone(), format: rs.effective_format(), dns_copy_of: None, via_proxy }); + out.push(WantedRuleSet { + tag: remote_dns(name), + url: rs.url.clone(), + format: RuleSetFormat::Source, + dns_copy_of: Some(remote(name)), + via_proxy, + }); + } + out +} + +fn rule_set_defs(input: &Input, warnings: &mut Vec) -> Vec { + wanted_rule_sets(input.cfg) + .into_iter() + .map(|w| match input.env.rule_sets.get(&w.tag) { + Some(file) => json!({ + "tag": w.tag, + "type": "local", + "format": if file.format == RuleSetFormat::Binary { "binary" } else { "source" }, + "path": file.path, + }), + None => { + if w.dns_copy_of.is_none() { + warnings.push(format!("rule set '{}' is not downloaded yet; it matches nothing until it is", w.tag)); + } + json!({ "tag": w.tag, "type": "local", "format": "source", "path": input.env.empty_rule_set }) + } + }) + .collect() +} diff --git a/windows/crates/ps-core/src/render/sing_box.rs b/windows/crates/ps-core/src/render/sing_box.rs new file mode 100644 index 0000000..9b57a75 --- /dev/null +++ b/windows/crates/ps-core/src/render/sing_box.rs @@ -0,0 +1,265 @@ +//! sing-box's whole config, and the hybrid backend's XRay sidecar: upstream's +//! `config-templates/sing-box.nix` with what its start script fills in. + +use serde_json::{Map, Value, json}; + +use super::outbounds::Assembly; +use super::routing::{self, per_app_inbound}; +use super::{Input, RenderError}; +use crate::config::{Backend, DnsUpstream}; +use crate::derived::{self, ExtraKind, ports}; + +/// The global TUN's IPv6 address, as upstream numbers it. +pub const TUN_IPV6_ADDRESS: &str = "fd66:19::1/64"; +/// Where the hybrid sidecar asks sing-box for names. +pub const XRAY_DNS_BRIDGE_PORT: u16 = 18533; + +fn dns_server(tag: &str, upstream: &DnsUpstream, detour: Option<&str>) -> Value { + let mut s = json!({ + "type": upstream.transport.as_str(), + "tag": tag, + "server": upstream.address, + "server_port": upstream.port, + }); + if let Some(d) = detour { + s["detour"] = d.into(); + } + s +} + +/// The loopback listeners of the helpers sing-box dials: no client of the local proxy may +/// ask sing-box to dial them for it. +fn hop_ports(input: &Input) -> Vec { + let cfg = input.cfg; + let mut out = Vec::new(); + for extra in derived::extra_outbounds(cfg) { + match extra.kind { + ExtraKind::Tor { port } | ExtraKind::WlJoiner { port, .. } => out.push(port), + ExtraKind::Awg { port, kind: crate::config::AwgOutboundKind::Userspace, .. } => out.push(port), + ExtraKind::Warp { device } if device.kind == crate::config::WarpOutboundKind::Userspace => { + out.push(device.port) + } + ExtraKind::Ssh if !cfg.proxy.backend.runs_sing_box() => out.push(cfg.ssh_proxy.listener.port), + _ => {} + } + } + if cfg.proxy.backend == Backend::Hybrid { + out.push(ports::XRAY_SIDECAR_SOCKS); + } + out.sort_unstable(); + out.dedup(); + out +} + +fn listener_users(input: &Input) -> Result, RenderError> { + let auth = &input.cfg.proxy.listener.auth; + let Some(user) = &auth.username else { return Ok(None) }; + let password = match (&auth.password, &auth.password_file) { + (Some(p), _) => p.clone(), + (None, Some(file)) => (input.read_file)(file) + .map(|p| p.trim().to_owned()) + .map_err(|e| RenderError(format!("proxy.listener.auth.passwordFile: {e}")))?, + (None, None) => return Err(RenderError("proxy.listener.auth has a username without a password".into())), + }; + Ok(Some(json!([{ "username": user, "password": password }]))) +} + +pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec) -> Result<(Value, Option), RenderError> { + let cfg = input.cfg; + let p = &cfg.proxy; + let env = input.env; + let hybrid = p.backend == Backend::Hybrid && !asm.xray.is_empty(); + + // Outbounds: "proxy" and the rest, the sidecar's as hops to it, then direct and block. + let sidecar = hybrid.then(|| sidecar(input, asm)); + let mut outbounds = asm.outbounds.clone(); + if let Some((_, hops)) = &sidecar { + outbounds.splice(1..1, hops.iter().cloned()); + } + outbounds.push(json!({ "type": "direct", "tag": "direct" })); + outbounds.push(json!({ "type": "block", "tag": "block" })); + + let known_tags: std::collections::HashSet = asm + .inventory + .tags + .iter() + .chain(asm.inventory.groups.keys()) + .cloned() + .collect(); + let known = |t: &str| known_tags.contains(t); + let route = routing::route(input, &hop_ports(input), &known, warnings); + + // Inbounds. + let mut inbounds = Vec::new(); + if hybrid { + inbounds.push(json!({ "type": "direct", "tag": "xray-dns-in", "listen": "127.0.0.1", "listen_port": XRAY_DNS_BRIDGE_PORT })); + } + let mut mixed = json!({ + "type": "mixed", "tag": "mixed-in", "listen": p.listener.address, "listen_port": p.listener.port, + }); + let users = listener_users(input)?; + if let Some(users) = &users { + mixed["users"] = users.clone(); + } + inbounds.push(mixed); + // The test listener `proxy-ctl proxy outbounds test` dials each outbound through, by the + // Clash API's switching of its selector. + let mut test_in = json!({ "type": "mixed", "tag": "proxy-suite-test-in", "listen": "127.0.0.1", "listen_port": ports::OUTBOUND_TEST }); + if let Some(users) = &users { + test_in["users"] = users.clone(); + } + inbounds.push(test_in); + if cfg.per_app_routing.enable { + for (i, prof) in cfg.per_app_routing.profiles.iter().enumerate() { + let mut l = json!({ + "type": "mixed", "tag": per_app_inbound(&prof.name), "listen": "127.0.0.1", + "listen_port": cfg.per_app_routing.listener_base_port.saturating_add(i as u16), + }); + if let Some(users) = &users { + l["users"] = users.clone(); + } + inbounds.push(l); + } + } + if input.tun { + let t = &p.tun; + let mut address = vec![Value::from(t.address.clone())]; + if p.ipv6 { + address.push(TUN_IPV6_ADDRESS.into()); + } + let mut tun = json!({ + "type": "tun", "tag": "tun-in", "interface_name": t.interface, "address": address, "mtu": t.mtu, + "auto_route": true, "strict_route": true, "stack": "mixed", + }); + if !env.windows { + tun["auto_redirect"] = true.into(); + } + inbounds.push(tun); + } + + // The test selector: every exit, block first so an unswitched test reaches nothing. + let mut test_members = vec![Value::from("block")]; + 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 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 { + rules.insert(0, json!({ "inbound": ["xray-dns-in"], "network": ["tcp", "udp"], "action": "hijack-dns" })); + } + + // DNS. + let fake_ip = input.tun && p.dns.fake_ip.enable; + let onion_fake = input.tun && derived::tor_route_onion(cfg); + let mut servers = vec![dns_server("remote", &p.dns.remote, Some("proxy")), dns_server("local", &p.dns.local, None)]; + if fake_ip || onion_fake { + 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 }); + if let Some(s) = p.dns.strategy { + dns["strategy"] = s.as_str().into(); + } + if let Some(cs) = &p.dns.client_subnet { + dns["client_subnet"] = cs.clone().into(); + } + + let mut route_obj = json!({ + "default_domain_resolver": "local", + "rule_set": route.rule_set, + "rules": rules, + "final": route.final_outbound, + }); + if input.tun { + route_obj["auto_detect_interface"] = true.into(); + } + + let mut clash = json!({ "external_controller": format!("127.0.0.1:{}", p.sing_box.clash_api_port) }); + if let Some(secret) = &env.clash_secret { + clash["secret"] = secret.clone().into(); + } + let mut experimental = json!({ "clash_api": clash }); + if fake_ip || onion_fake { + // Fake addresses handed out survive a restart, so apps still holding one keep working. + experimental["cache_file"] = json!({ + "enabled": true, + "path": format!("{}/tun.db", env.cache_dir.trim_end_matches(['/', '\\'])), + "store_fakeip": true, + }); + } + + let mut config = Map::new(); + config.insert("log".into(), json!({ "level": cfg.debug.log_level.as_str() })); + config.insert("dns".into(), dns); + config.insert("inbounds".into(), Value::Array(inbounds)); + config.insert("outbounds".into(), Value::Array(outbounds)); + if !asm.endpoints.is_empty() { + config.insert("endpoints".into(), Value::Array(asm.endpoints.clone())); + } + config.insert("route".into(), route_obj); + config.insert("experimental".into(), experimental); + Ok((Value::Object(config), sidecar.map(|(c, _)| c))) +} + +/// The hybrid backend's XRay sidecar: one loopback VLESS inbound, a client per XRay +/// outbound routed to it by its email, and the sing-box hops that reach each. VLESS rather +/// than SOCKS: UDP rides the stream (XUDP) with the client id, where SOCKS UDP datagrams carry +/// no user to route by. +fn sidecar(input: &Input, asm: &Assembly) -> (Value, Vec) { + let prefix: String = input.env.sidecar_secret.chars().take(24).collect(); + let mut outbounds = Vec::new(); + let mut clients = Vec::new(); + let mut rules = Vec::new(); + let mut hops = Vec::new(); + for (i, ob) in asm.xray.iter().enumerate() { + let tag = ob["tag"].as_str().unwrap_or_default().to_owned(); + let id = format!("{prefix}{i:012x}"); + let mut ob = ob.clone(); + apply_xmux(input, &mut ob); + if ob.pointer("/streamSettings/sockopt/domainStrategy").is_none() { + ob["streamSettings"]["sockopt"]["domainStrategy"] = "UseIP".into(); + } + outbounds.push(ob); + clients.push(json!({ "id": id, "email": tag })); + rules.push(json!({ "type": "field", "inboundTag": ["sidecar-in"], "user": [tag], "outboundTag": tag })); + hops.push(json!({ + "type": "vless", "tag": tag, "server": "127.0.0.1", "server_port": ports::XRAY_SIDECAR_SOCKS, + "uuid": id, "packet_encoding": "xudp", + })); + } + outbounds.push(json!({ "protocol": "freedom", "tag": "direct" })); + rules.push(json!({ "type": "field", "ip": ["127.0.0.1"], "port": XRAY_DNS_BRIDGE_PORT, "outboundTag": "direct" })); + let config = json!({ + "log": { "loglevel": xray_log_level(input), "access": "none" }, + "dns": { "servers": [{ "address": "127.0.0.1", "port": XRAY_DNS_BRIDGE_PORT, "queryStrategy": "UseIP", "skipFallBack": true }] }, + "inbounds": [{ + "tag": "sidecar-in", "listen": "127.0.0.1", "port": ports::XRAY_SIDECAR_SOCKS, "protocol": "vless", + "settings": { "clients": clients, "decryption": "none" }, + }], + "outbounds": outbounds, + "routing": { "domainStrategy": "AsIs", "rules": rules }, + }); + (config, hops) +} + +/// `debug.logLevel` in XRay's words: it has no "trace". +pub(super) fn xray_log_level(input: &Input) -> &'static str { + use crate::config::LogLevel; + match input.cfg.debug.log_level { + LogLevel::Warn => "warning", + LogLevel::Info => "info", + LogLevel::Debug | LogLevel::Trace => "debug", + } +} + +/// `proxy.xray.xhttpXmux` for an XHTTP outbound whose link set no xmux. +pub(super) fn apply_xmux(input: &Input, ob: &mut Value) { + let Some(xmux) = &input.cfg.proxy.xray.xhttp_xmux else { return }; + if ob.pointer("/streamSettings/network").and_then(Value::as_str) != Some("xhttp") { + return; + } + let current = ob.pointer("/streamSettings/xhttpSettings/extra/xmux"); + if current.is_none_or(|v| v.as_object().is_some_and(|o| o.is_empty())) { + ob["streamSettings"]["xhttpSettings"]["extra"]["xmux"] = json!(xmux); + } +} diff --git a/windows/crates/ps-core/tests/render.rs b/windows/crates/ps-core/tests/render.rs new file mode 100644 index 0000000..634cd6a --- /dev/null +++ b/windows/crates/ps-core/tests/render.rs @@ -0,0 +1,230 @@ +//! Rendered configs, checked by the backends themselves: `sing-box check` and +//! `xray run -test`, when they are on PATH (the dev shell has both). + +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::process::Command; + +use ps_core::config::*; +use ps_core::render::{Env, Input, RouteMode, State, render}; +use serde_json::{Value, json}; + +const PBK: &str = "SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc"; +const WGCF: &str = "[Interface]\nPrivateKey = yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=\nAddress = 172.16.0.2/32, 2606:4700:110:8a36::2/128\nMTU = 1280\n\n[Peer]\nPublicKey = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = engage.cloudflareclient.com:2408\n"; + +fn have(bin: &str) -> bool { + Command::new(bin).arg("version").output().is_ok() +} + +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("ps-core-render-{}-{name}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn env(dir: &PathBuf) -> Env { + let empty = dir.join("empty.json"); + std::fs::write(&empty, r#"{"version":1,"rules":[]}"#).unwrap(); + let mut warp = BTreeMap::new(); + warp.insert("warp".to_owned(), WGCF.to_owned()); + Env { + empty_rule_set: empty.to_string_lossy().into(), + cache_dir: dir.to_string_lossy().into(), + clash_secret: Some("s3cret".into()), + hop_login: Some(("hop".into(), "hop-pass".into())), + warp_profiles: warp, + direct_processes: vec![r"C:\ProgramData\ProxySuite\bin\tor\tor.exe".into()], + groups_watched: true, + sidecar_secret: "0b1c2d3e-4f50-6172-8394-a5b6c7d8e9f0".into(), + windows: true, + ..Default::default() + } +} + +fn no_files(path: &str) -> Result { + Err(format!("{path}: not found")) +} + +fn check_sing_box(config: &Value, dir: &PathBuf) { + if !have("sing-box") { + eprintln!("sing-box not on PATH: skipping the check"); + return; + } + let path = dir.join("sing-box.json"); + std::fs::write(&path, serde_json::to_string_pretty(config).unwrap()).unwrap(); + let out = Command::new("sing-box").args(["check", "-c"]).arg(&path).output().unwrap(); + assert!( + out.status.success(), + "sing-box check failed:\n{}\n{}", + String::from_utf8_lossy(&out.stderr), + serde_json::to_string_pretty(config).unwrap() + ); +} + +fn check_xray(config: &Value, dir: &PathBuf) { + if !have("xray") { + return; + } + let path = dir.join("xray.json"); + std::fs::write(&path, serde_json::to_string_pretty(config).unwrap()).unwrap(); + let out = Command::new("xray").args(["run", "-test", "-c"]).arg(&path).output().unwrap(); + assert!( + out.status.success(), + "xray -test failed:\n{}{}\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + serde_json::to_string_pretty(config).unwrap() + ); +} + +fn outbound(tag: &str, url: &str) -> Outbound { + Outbound { tag: tag.into(), url: Some(url.into()), ..Default::default() } +} + +fn base() -> Config { + let mut cfg = Config::default(); + cfg.proxy.enable = true; + cfg.proxy.outbounds = vec![ + outbound("nl", "hy2://pw@nl.example.com:443?sni=nl.example.com"), + outbound("de", &format!("vless://00000000-0000-0000-0000-000000000000@de.example.com:443?security=reality&pbk={PBK}&sid=ab&sni=www.microsoft.com&fp=chrome&flow=xtls-rprx-vision")), + ]; + cfg +} + +#[test] +fn a_minimal_proxy_checks() { + let dir = scratch("minimal"); + let cfg = base(); + let r = render(&Input { + cfg: &cfg, + state: &State::default(), + subscriptions: &BTreeMap::new(), + env: &env(&dir), + read_file: &no_files, + tun: false, + }) + .unwrap(); + let sb = r.sing_box.unwrap(); + assert_eq!(sb["outbounds"][0], json!({ "type": "selector", "tag": "proxy", "outbounds": ["nl"], "default": "nl" })); + assert_eq!(sb["route"]["final"], "proxy"); + assert_eq!(r.inventory.top, ["nl", "de"]); + check_sing_box(&sb, &dir); +} + +#[test] +fn everything_at_once_checks() { + let dir = scratch("full"); + let mut cfg = base(); + let p = &mut cfg.proxy; + p.selection = Selection::Urltest; + p.listener.auth = ListenerAuth { username: Some("me".into()), password: Some("pw".into()), password_file: None }; + p.outbounds.push(Outbound { detour: Some("nl".into()), ..outbound("chained", "trojan://pw@t.example.com:443?sni=t.example.com") }); + p.outbounds.push(outbound("broken", "vless://uuid@x.example.com:70000")); + p.outbounds[1].routing.geosites = vec!["netflix".into()]; + p.subscriptions.push(Subscription { tag: "sub".into(), url: Some("https://sub.example.com/x".into()), ..Default::default() }); + p.groups.insert("eu".into(), Group { outbounds: vec!["de".into()], subscriptions: vec!["sub".into()], ..Default::default() }); + p.groups.insert("fast".into(), Group { match_: vec!["sub-*".into()], strategy: GroupStrategy::Urltest, ..Default::default() }); + p.routing.rules.push(RoutingRule { + outbound: "eu".into(), + matches: RouteMatch { domains: vec!["example.org".into()], ips: vec!["203.0.113.0/24".into()], ..Default::default() }, + process_names: vec!["Telegram.exe".into()], + ..Default::default() + }); + p.routing.rules.push(RoutingRule { name: Some("early".into()), priority: Some(10), outbound: "direct".into(), matches: RouteMatch { domains: vec!["bank.example".into()], ..Default::default() }, ..Default::default() }); + p.routing.rules.push(RoutingRule { outbound: "gone".into(), matches: RouteMatch { domains: vec!["x.example".into()], ..Default::default() }, ..Default::default() }); + p.routing.block.geosites = vec!["category-ads-all".into()]; + p.routing.rule_sets.insert("antifilter".into(), RuleSet { url: "https://example.com/antifilter.srs".into(), format: None, detour: RuleSetDetour::Proxy }); + p.routing.proxy.rule_sets = vec!["antifilter".into()]; + p.tun.enable = true; + p.dns.fake_ip.enable = true; + p.dns.strategy = Some(DomainStrategy::Ipv4Only); + cfg.per_app_routing.enable = true; + cfg.per_app_routing.profiles.push(PerAppProfile { name: "games".into(), outbound: "direct".into(), process_names: vec!["steam.exe".into()], ..Default::default() }); + cfg.tor.enable = true; + cfg.tor.as_outbound = true; + cfg.warp.enable = true; + cfg.warp.as_outbound = Some(WarpOutboundKind::SingBox); + cfg.ssh_proxy.enable = true; + cfg.ssh_proxy.as_outbound = true; + cfg.ssh_proxy.server = SshServer { user: Some("root".into()), host: Some("ssh.example.com".into()), port: 22 }; + cfg.ssh_proxy.host_key = vec!["ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl".into()]; + cfg.whitelist_bypass.enable = true; + cfg.whitelist_bypass.joiners.insert("wl".into(), WlJoiner { platform: WlPlatform::Wbstream, link_file: None }); + + let mut subs = BTreeMap::new(); + subs.insert("sub".to_owned(), vec![ + "hy2://pw@a.example.com:443#A".to_owned(), + "hy2://pw@b.example.com:443#B".to_owned(), + "hy2://pw@127.0.0.1:443#Loop".to_owned(), + ]); + let mut state = State::default(); + state.disabled.push("sub-B".into()); + let r = render(&Input { cfg: &cfg, state: &state, subscriptions: &subs, env: &env(&dir), read_file: &no_files, tun: true }).unwrap(); + let sb = r.sing_box.unwrap(); + let tags: Vec<&str> = sb["outbounds"].as_array().unwrap().iter().map(|o| o["tag"].as_str().unwrap()).collect(); + assert!(tags.contains(&"chained") && !tags.contains(&"broken"), "{tags:?}"); + assert!(r.warnings.iter().any(|w| w.contains("'broken'")), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("'gone'")), "{:?}", r.warnings); + assert_eq!(sb["endpoints"][0]["tag"], "warp"); + assert_eq!(r.inventory.detours["chained"], "nl"); + assert!(r.inventory.excluded.contains(&"tor".to_owned())); + assert!(r.inventory.disabled.contains(&"sub-B".to_owned())); + // The early rule sorts ahead of the configuration's own. + let rules = sb["route"]["rules"].as_array().unwrap(); + let early = rules.iter().position(|r| r["domain_suffix"] == json!(["bank.example"])).unwrap(); + let eu = rules.iter().position(|r| r["domain_suffix"] == json!(["example.org"])).unwrap(); + assert!(early < eu); + assert_eq!(sb["inbounds"].as_array().unwrap().last().unwrap()["type"], "tun"); + check_sing_box(&sb, &dir); +} + +#[test] +fn hybrid_hands_xhttp_to_the_sidecar() { + let dir = scratch("hybrid"); + let mut cfg = base(); + cfg.proxy.backend = Backend::Hybrid; + cfg.proxy.outbounds.push(outbound("xh", "vless://00000000-0000-0000-0000-000000000000@x.example.com:443?security=tls&sni=x.example.com&type=xhttp&path=%2Fx&mode=packet-up")); + cfg.proxy.xray.xhttp_xmux = Some(BTreeMap::from([("maxConnections".to_owned(), json!(3))])); + cfg.proxy.selection = Selection::Selector; + let r = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &env(&dir), read_file: &no_files, tun: false }).unwrap(); + let sb = r.sing_box.unwrap(); + let hop = sb["outbounds"].as_array().unwrap().iter().find(|o| o["tag"] == "xh").unwrap(); + assert_eq!(hop["type"], "vless"); + assert_eq!(r.inventory.runs_on["xh"], "xray"); + let xray = r.xray.unwrap(); + assert_eq!(xray["outbounds"][0]["streamSettings"]["xhttpSettings"]["extra"]["xmux"]["maxConnections"], 3); + check_sing_box(&sb, &dir); + check_xray(&xray, &dir); +} + +#[test] +fn route_modes_change_the_final_and_the_lists() { + let dir = scratch("modes"); + let mut cfg = base(); + cfg.proxy.routing.direct.domains = vec!["direct.example".into()]; + cfg.proxy.routing.block.domains = vec!["ads.example".into()]; + for (mode, final_ob, has_direct) in [ + (None, "proxy", true), + (Some(RouteMode::Whitelist), "direct", true), + (Some(RouteMode::AllProxy), "proxy", false), + (Some(RouteMode::AllBypass), "direct", false), + ] { + let state = State { route_mode: mode, ..Default::default() }; + let r = render(&Input { cfg: &cfg, state: &state, subscriptions: &BTreeMap::new(), env: &env(&dir), read_file: &no_files, tun: false }).unwrap(); + let sb = r.sing_box.unwrap(); + assert_eq!(sb["route"]["final"], final_ob, "{mode:?}"); + let rules = sb["route"]["rules"].as_array().unwrap(); + assert_eq!(rules.iter().any(|r| r["domain_suffix"] == json!(["direct.example"])), has_direct, "{mode:?}"); + assert!(rules.iter().any(|r| r["domain_suffix"] == json!(["ads.example"])), "{mode:?}"); + check_sing_box(&sb, &dir); + } +} + +#[test] +fn no_outbounds_is_an_error() { + let dir = scratch("none"); + let mut cfg = Config::default(); + cfg.proxy.enable = true; + 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")); +}