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 <noreply@anthropic.com>
304 lines
12 KiB
Rust
304 lines
12 KiB
Rust
//! 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<String, GroupInfo>,
|
|
/// The sing-box group outbounds, inner groups first.
|
|
pub outbounds: Vec<Value>,
|
|
/// What the top level picks among: outbounds in no group, and outermost groups, in
|
|
/// priority order.
|
|
pub top: Vec<String>,
|
|
/// Groups inside themselves.
|
|
pub loops: Vec<String>,
|
|
pub warnings: Vec<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize)]
|
|
pub struct GroupInfo {
|
|
pub strategy: GroupStrategy,
|
|
pub failback: bool,
|
|
pub interval: String,
|
|
pub members: Vec<String>,
|
|
/// The members the group names itself, which the front ends edit.
|
|
pub listed: Vec<String>,
|
|
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:<tag>" for a subscription entry).
|
|
pub sources: &'a HashMap<String, String>,
|
|
pub groups: &'a BTreeMap<String, Group>,
|
|
pub priority: &'a BTreeMap<String, i64>,
|
|
pub disabled: &'a [String],
|
|
/// group -> the member pinned in it.
|
|
pub pins: &'a BTreeMap<String, String>,
|
|
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<String, Vec<String>> = 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<Regex> = cfg.match_.iter().map(|p| glob_regex(p)).collect();
|
|
let mut pulled: Vec<String> = 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<String> = 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<String> = 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<String>, members: &BTreeMap<String, Vec<String>>, out: &mut Vec<String>) {
|
|
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<String> = 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<String>, members: &BTreeMap<String, Vec<String>>, position: &HashMap<&str, i64>) -> Option<i64> {
|
|
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<String> =
|
|
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<String> = if all.is_empty() { vec!["block".into()] } else { all.clone() };
|
|
let usable_or_block: Vec<String> =
|
|
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<String, Group>, sources: &[(&str, &str)]) -> Resolved {
|
|
let tags: Vec<String> = 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"]);
|
|
}
|
|
}
|