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 <noreply@anthropic.com>
This commit is contained in:
1 parent
69e70d6f74
commit
5a89b8d11d
19 files changed
+1640
-10
No files matched your search
@@ -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<String>,
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
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<ProbeExit> {
|
||||
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<Value>,
|
||||
rules: &mut Vec<Value>,
|
||||
pin_at: usize,
|
||||
rule_sets: &mut Vec<Value>,
|
||||
dns_rules: &mut Vec<Value>,
|
||||
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" }));
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
}
|
||||
|
||||
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<Value>,
|
||||
pub inventory: Inventory,
|
||||
/// autoProxy's exits and their probe listeners; empty when it is off.
|
||||
pub probe_exits: Vec<ProbeExit>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -143,8 +149,9 @@ pub fn render(input: &Input) -> Result<Rendered, RenderError> {
|
||||
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(),
|
||||
|
||||
@@ -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<Value>,
|
||||
/// 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<Value>,
|
||||
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 {
|
||||
|
||||
@@ -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<Option<Value>, RenderError> {
|
||||
Ok(Some(json!([{ "username": user, "password": password }])))
|
||||
}
|
||||
|
||||
pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec<String>) -> Result<(Value, Option<Value>), RenderError> {
|
||||
pub(super) fn config(input: &Input, asm: &Assembly, probe_exits: &[ProbeExit], warnings: &mut Vec<String>) -> Result<(Value, Option<Value>), 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<String>)
|
||||
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<String>)
|
||||
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<String>)
|
||||
|
||||
let mut route_obj = json!({
|
||||
"default_domain_resolver": "local",
|
||||
"rule_set": route.rule_set,
|
||||
"rule_set": rule_sets,
|
||||
"rules": rules,
|
||||
"final": route.final_outbound,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user