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,666 @@
|
||||
//! autoProxy's judgement, as upstream decides it: what one fetch through an exit says
|
||||
//! (proxy_ctl.py's `proxy auto probe`), the walk over the exits for a destination, the order
|
||||
//! they are walked in (autoproxy-rounds.jq), the strikes against exits a destination refused
|
||||
//! (autoproxy-strike.jq), what is remembered (autoproxy-run.template.sh, autoproxy-edit.jq)
|
||||
//! and the rule-sets sing-box takes it from (autoproxy-render.template.sh).
|
||||
//!
|
||||
//! The fetches themselves are the service's; this is the deciding, so it is tested here.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::links::subscription::{nearness, url_parts};
|
||||
|
||||
/// The exit that is this host: always the first.
|
||||
pub const DIRECT: &str = "direct";
|
||||
|
||||
/// The paths a destination is probed at: the page, then robots.txt, which some sites serve
|
||||
/// where their front page refuses a client that is not a browser.
|
||||
pub const PATHS: [&str; 2] = ["/", "/robots.txt"];
|
||||
|
||||
/// One fetch through one exit, at the first hop that is not a same-site redirect.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Fetch {
|
||||
/// The answer's status; none when no answer came (TLS or the connection failed first).
|
||||
pub status: Option<u16>,
|
||||
/// The PROBE_BLOCK_PAGES name a refusal's page matched, "" for none.
|
||||
#[serde(default)]
|
||||
pub block: String,
|
||||
/// A redirect's Location.
|
||||
#[serde(default)]
|
||||
pub location: String,
|
||||
/// Bytes read of the body (at most what was read to judge it).
|
||||
#[serde(default)]
|
||||
pub bytes: u64,
|
||||
/// Why no answer came.
|
||||
#[serde(default)]
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Judgement {
|
||||
/// Content.
|
||||
Ok,
|
||||
/// Failed before the origin spoke: the censor's doing, zapret's job.
|
||||
Dead,
|
||||
/// The site's security layer refused this address: an exit past it helps.
|
||||
Wall,
|
||||
/// The origin answered and refused: another exit can fix it.
|
||||
Blocked,
|
||||
}
|
||||
|
||||
/// Block pages, by name: (kind, pattern over a refusal's headers and the first 8 KiB of its
|
||||
/// body). "address": the address itself was refused, so an exit that gets past it reaches the
|
||||
/// site; "geo": its country was, which is an ordinary refusal.
|
||||
static BLOCK_PAGES: LazyLock<Vec<(&str, &str, Regex)>> = LazyLock::new(|| {
|
||||
[
|
||||
("aws-waf", "address", r"(?ims)^server: cloudfront\b.*Request blocked\."),
|
||||
("cloudfront-geo", "geo", r"(?i)configured to block access from your country"),
|
||||
("cloudflare", "address", r#"(?im)^cf-mitigated: challenge|cf-error-code">10(06|07|08|20)<|error code: 10(06|07|08|20)\b"#),
|
||||
("cloudflare-geo", "geo", r#"(?i)cf-error-code">1009<|error code: 1009\b"#),
|
||||
("akamai", "address", r"(?ims)^server: AkamaiGHost\b.*Access Denied"),
|
||||
("imperva", "address", r"(?i)Incapsula incident ID"),
|
||||
("datadome", "address", r"(?im)^x-datadome:"),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(name, kind, re)| (name, kind, Regex::new(re).expect("a valid pattern")))
|
||||
.collect()
|
||||
});
|
||||
|
||||
static BLOCK_REDIRECT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)unavailable|not-available|blocked|geo|region|restricted").unwrap());
|
||||
static HOST: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$").unwrap());
|
||||
|
||||
/// A host name autoProxy probes or routes: letters, digits, dots, '_' and '-', with a TLD.
|
||||
pub fn host_ok(host: &str) -> bool {
|
||||
host.len() <= 253 && HOST.is_match(host)
|
||||
}
|
||||
|
||||
/// The name of the block page a refusal (`status` 4xx or 5xx) shows, "" for none. `head` is
|
||||
/// its headers as received, `body` its first bytes.
|
||||
pub fn block_page(status: u16, head: &str, body: &[u8]) -> String {
|
||||
if !(400..600).contains(&status) {
|
||||
return String::new();
|
||||
}
|
||||
let body: String = body.iter().take(8192).map(|&b| b as char).collect();
|
||||
let text = format!("{head}\n\n{body}\n\n");
|
||||
BLOCK_PAGES.iter().find(|(_, _, re)| re.is_match(&text)).map(|(name, _, _)| (*name).to_owned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The last two labels: a redirect is followed only within them.
|
||||
pub fn site(url: &str) -> String {
|
||||
let host = url_parts::split(url).ok().and_then(|u| u.hostname).unwrap_or_default();
|
||||
let labels: Vec<&str> = host.split('.').collect();
|
||||
labels[labels.len().saturating_sub(2)..].join(".")
|
||||
}
|
||||
|
||||
/// Whether a Location names this host or its LAN (localhost, or an address literal in any of
|
||||
/// the forms curl takes): never followed.
|
||||
pub fn local_target(url: &str) -> bool {
|
||||
match url_parts::split(url) {
|
||||
Ok(u) => nearness(u.hostname.as_deref()) > 0,
|
||||
Err(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a redirect's target says the content is refused (a "not available" page).
|
||||
pub fn redirect_is_block(location: &str) -> bool {
|
||||
BLOCK_REDIRECT.is_match(location)
|
||||
}
|
||||
|
||||
fn http_ok(f: &Fetch) -> bool {
|
||||
match f.status {
|
||||
Some(s) if (200..300).contains(&s) || s == 401 || s == 404 => true,
|
||||
Some(s) if (300..400).contains(&s) => !redirect_is_block(&f.location),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn judge(f: &Fetch) -> Judgement {
|
||||
if f.status.is_none() {
|
||||
return Judgement::Dead;
|
||||
}
|
||||
if http_ok(f) {
|
||||
return Judgement::Ok;
|
||||
}
|
||||
let address = BLOCK_PAGES.iter().any(|(name, kind, _)| *name == f.block && *kind == "address");
|
||||
if address { Judgement::Wall } else { Judgement::Blocked }
|
||||
}
|
||||
|
||||
/// Content; or, where direct hit a wall, any answer from the origin past it.
|
||||
pub fn reaches(direct: Judgement, j: Judgement) -> bool {
|
||||
j == Judgement::Ok || (direct == Judgement::Wall && j == Judgement::Blocked)
|
||||
}
|
||||
|
||||
/// "ok": direct gets it. "destination": an exit reaches what direct does not, past a refusal:
|
||||
/// route through it. "censor": direct dies on the way while an exit reaches it, which zapret
|
||||
/// is for: it stays direct. "both-fail" and "unreachable": no exit helps.
|
||||
pub fn verdict(direct: &Fetch, via: &Fetch) -> &'static str {
|
||||
let d = judge(direct);
|
||||
if d == Judgement::Ok {
|
||||
return "ok";
|
||||
}
|
||||
if reaches(d, judge(via)) {
|
||||
return if d == Judgement::Dead { "censor" } else { "destination" };
|
||||
}
|
||||
if d == Judgement::Dead { "unreachable" } else { "both-fail" }
|
||||
}
|
||||
|
||||
pub fn verdict_text(verdict: &str, exit: Option<&str>) -> String {
|
||||
match verdict {
|
||||
"ok" => "reachable directly - nothing to do".into(),
|
||||
"destination" => format!("destination-side block - route via {}", exit.unwrap_or("proxy")),
|
||||
"censor" => "censor-side block - zapret's territory, not proxied".into(),
|
||||
"both-fail" => "fails through every egress - not an egress problem".into(),
|
||||
"unreachable" => "no egress reaches it at all".into(),
|
||||
_ => "inconclusive".into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn describe(f: &Fetch) -> String {
|
||||
let Some(status) = f.status else {
|
||||
return if f.error.is_empty() { "no answer".into() } else { format!("no answer ({})", f.error) };
|
||||
};
|
||||
let mut text = format!("{status}, {} bytes", f.bytes);
|
||||
if !f.block.is_empty() {
|
||||
text.push_str(&format!(", {} page", f.block));
|
||||
}
|
||||
if !f.location.is_empty() {
|
||||
text.push_str(&format!(" -> {}", f.location));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// One request of a walk.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Row {
|
||||
pub tag: String,
|
||||
pub path: String,
|
||||
pub fetch: Fetch,
|
||||
pub judgement: Judgement,
|
||||
}
|
||||
|
||||
/// What a probe found: the verdict, the exit that reached it (none for "ok" and the failures),
|
||||
/// the path it was judged on, and every request made.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Probe {
|
||||
pub domain: String,
|
||||
pub verdict: String,
|
||||
pub exit: Option<String>,
|
||||
pub path: String,
|
||||
pub rows: Vec<Row>,
|
||||
}
|
||||
|
||||
/// Walks the exits (`exits[0]` is direct) and stops at the first that reaches `domain`: gets
|
||||
/// content, or gets past a wall direct hit. `keep_going` still tries the rest, keeping that
|
||||
/// first one. `fetch(tag, path)` is one request through one exit.
|
||||
pub async fn walk<F, Fut>(domain: &str, exits: &[String], paths: &[&str], keep_going: bool, mut fetch: F) -> Probe
|
||||
where
|
||||
F: FnMut(String, String) -> Fut,
|
||||
Fut: Future<Output = Fetch>,
|
||||
{
|
||||
let mut p = Probe { domain: domain.to_owned(), ..Default::default() };
|
||||
let Some((direct_tag, others)) = exits.split_first() else {
|
||||
p.verdict = "error".into();
|
||||
return p;
|
||||
};
|
||||
let mut first_direct: Option<Fetch> = None;
|
||||
for path in paths {
|
||||
let direct = fetch(direct_tag.clone(), (*path).to_owned()).await;
|
||||
let dj = judge(&direct);
|
||||
p.rows.push(Row { tag: direct_tag.clone(), path: (*path).to_owned(), fetch: direct.clone(), judgement: dj });
|
||||
first_direct.get_or_insert_with(|| direct.clone());
|
||||
if dj == Judgement::Ok && p.verdict.is_empty() {
|
||||
p.verdict = "ok".into();
|
||||
p.path = (*path).to_owned();
|
||||
if !keep_going {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
for tag in others {
|
||||
let via = fetch(tag.clone(), (*path).to_owned()).await;
|
||||
let j = judge(&via);
|
||||
p.rows.push(Row { tag: tag.clone(), path: (*path).to_owned(), fetch: via.clone(), judgement: j });
|
||||
if reaches(dj, j) && p.verdict.is_empty() {
|
||||
p.verdict = verdict(&direct, &via).into();
|
||||
p.exit = Some(tag.clone());
|
||||
p.path = (*path).to_owned();
|
||||
if !keep_going {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if p.verdict.is_empty() {
|
||||
let dead = first_direct.as_ref().is_none_or(|f| judge(f) == Judgement::Dead);
|
||||
p.verdict = if dead { "unreachable" } else { "both-fail" }.into();
|
||||
p.path = paths.first().map(|s| (*s).to_owned()).unwrap_or_default();
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// `--via`: can `via` carry what direct reaches? It must get content on some path and fail on
|
||||
/// none where direct succeeds. Verdict "ok" or "blocked".
|
||||
pub async fn stand_in<F, Fut>(domain: &str, via: &str, paths: &[&str], mut fetch: F) -> Probe
|
||||
where
|
||||
F: FnMut(String, String) -> Fut,
|
||||
Fut: Future<Output = Fetch>,
|
||||
{
|
||||
let mut p = Probe {
|
||||
domain: domain.to_owned(),
|
||||
verdict: "ok".into(),
|
||||
exit: Some(via.to_owned()),
|
||||
path: paths.first().map(|s| (*s).to_owned()).unwrap_or_default(),
|
||||
rows: Vec::new(),
|
||||
};
|
||||
let mut got = false;
|
||||
for path in paths {
|
||||
let direct = fetch(DIRECT.to_owned(), (*path).to_owned()).await;
|
||||
let through = fetch(via.to_owned(), (*path).to_owned()).await;
|
||||
let (dj, vj) = (judge(&direct), judge(&through));
|
||||
p.rows.push(Row { tag: DIRECT.into(), path: (*path).to_owned(), fetch: direct, judgement: dj });
|
||||
p.rows.push(Row { tag: via.to_owned(), path: (*path).to_owned(), fetch: through, judgement: vj });
|
||||
got |= vj == Judgement::Ok;
|
||||
if dj == Judgement::Ok && vj != Judgement::Ok {
|
||||
p.verdict = "blocked".into();
|
||||
}
|
||||
}
|
||||
if !got {
|
||||
p.verdict = "blocked".into();
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// The registrable domain of `host` (its site: example.co.uk, foo.workers.dev), by the public
|
||||
/// suffix list with its private section; none for a public suffix itself, or a bare label.
|
||||
pub fn registrable(host: &str) -> Option<String> {
|
||||
let host = host.trim_end_matches('.').to_ascii_lowercase();
|
||||
if !host.contains('.') {
|
||||
return None;
|
||||
}
|
||||
let domain = psl::domain_str(&host)?;
|
||||
Some(domain.to_owned())
|
||||
}
|
||||
|
||||
// --- the state -----------------------------------------------------------------------------
|
||||
|
||||
/// A destination routed through an exit: probed blocked directly ("destination").
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Route {
|
||||
pub verdict: String,
|
||||
pub exit: String,
|
||||
pub host: String,
|
||||
#[serde(default)]
|
||||
pub path: String,
|
||||
pub at: u64,
|
||||
}
|
||||
|
||||
/// What the last probe of a host found.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HostVerdict {
|
||||
pub domain: String,
|
||||
pub verdict: String,
|
||||
#[serde(default)]
|
||||
pub exit: Option<String>,
|
||||
pub at: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Strike {
|
||||
pub why: String,
|
||||
pub at: u64,
|
||||
}
|
||||
|
||||
/// An exit: where it leaves from (its network, by AS), and the destinations that refused it.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct ExitInfo {
|
||||
pub ip: Option<String>,
|
||||
pub asn: Option<String>,
|
||||
pub at: u64,
|
||||
pub strikes: BTreeMap<String, Strike>,
|
||||
pub bad: bool,
|
||||
pub bad_by: Vec<String>,
|
||||
}
|
||||
|
||||
/// A host dialled directly, not yet probed: how often, and since when.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Queued {
|
||||
pub domain: String,
|
||||
pub hits: u64,
|
||||
pub first: u64,
|
||||
}
|
||||
|
||||
/// state.json.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct State {
|
||||
/// This host's public address the verdicts are about.
|
||||
pub egress: Option<String>,
|
||||
/// Registrable domain -> the exit it is routed through.
|
||||
pub domains: BTreeMap<String, Route>,
|
||||
pub hosts: BTreeMap<String, HostVerdict>,
|
||||
pub exits: BTreeMap<String, ExitInfo>,
|
||||
pub backlog: BTreeMap<String, Queued>,
|
||||
pub last_run: u64,
|
||||
}
|
||||
|
||||
/// Most entries the backlog keeps: every distinct name dialled is one.
|
||||
const BACKLOG_MAX: usize = 5000;
|
||||
|
||||
impl State {
|
||||
/// `domain` refused `tags` at `now` (`why`: "wall:<page>", "refused" or "slow"), and every
|
||||
/// strike older than `ttl` goes. A domain counts once per exit; two make an exit bad.
|
||||
pub fn strike(&mut self, tags: &[String], domain: &str, why: &str, now: u64, ttl: u64) {
|
||||
for t in tags {
|
||||
self.exits.entry(t.clone()).or_default().strikes.insert(domain.to_owned(), Strike { why: why.to_owned(), at: now });
|
||||
}
|
||||
for e in self.exits.values_mut() {
|
||||
e.strikes.retain(|_, s| s.at + ttl > now);
|
||||
rebad(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// `domain` back to direct, every verdict and strike about it gone.
|
||||
pub fn forget(&mut self, domain: &str) {
|
||||
self.domains.remove(domain);
|
||||
self.hosts.retain(|_, h| h.domain != domain);
|
||||
self.backlog.retain(|_, q| q.domain != domain);
|
||||
for e in self.exits.values_mut() {
|
||||
if e.strikes.remove(domain).is_some() {
|
||||
rebad(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything learned forgotten; what each exit is, the backlog and the egress stay.
|
||||
pub fn clear(&mut self) {
|
||||
self.domains.clear();
|
||||
self.hosts.clear();
|
||||
for e in self.exits.values_mut() {
|
||||
e.strikes.clear();
|
||||
rebad(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new public address: every verdict was about the old one.
|
||||
pub fn new_egress(&mut self, egress: &str) {
|
||||
*self = State { egress: Some(egress.to_owned()), backlog: std::mem::take(&mut self.backlog), last_run: self.last_run, ..Default::default() };
|
||||
}
|
||||
|
||||
/// What probing `host` (of `domain`) found. A route applies to the whole domain (blocks
|
||||
/// are drawn around sites); a verdict to the host. Exits refused on the path the winner
|
||||
/// reached are struck: by a block page, or by the origin where the winner got content.
|
||||
pub fn record(&mut self, domain: &str, host: &str, p: &Probe, now: u64, ttl: u64) {
|
||||
if p.verdict == "destination"
|
||||
&& let Some(exit) = &p.exit
|
||||
{
|
||||
self.domains.insert(domain.to_owned(), Route { verdict: p.verdict.clone(), exit: exit.clone(), host: host.to_owned(), path: p.path.clone(), at: now });
|
||||
}
|
||||
let exit = if p.verdict == "destination" { p.exit.clone() } else { None };
|
||||
self.hosts.insert(host.to_owned(), HostVerdict { domain: domain.to_owned(), verdict: p.verdict.clone(), exit, at: now });
|
||||
self.backlog.remove(host);
|
||||
let Some(winner) = &p.exit else { return };
|
||||
let won = p.rows.iter().find(|r| &r.tag == winner && r.path == p.path).map(|r| r.judgement);
|
||||
let mut struck: BTreeMap<String, String> = BTreeMap::new();
|
||||
for r in p.rows.iter().filter(|r| r.path == p.path && r.tag != DIRECT && &r.tag != winner) {
|
||||
let why = match r.judgement {
|
||||
Judgement::Wall => format!("wall:{}", r.fetch.block),
|
||||
Judgement::Blocked if won == Some(Judgement::Ok) => "refused".into(),
|
||||
_ => continue,
|
||||
};
|
||||
struck.entry(r.tag.clone()).or_insert(why);
|
||||
}
|
||||
for (tag, why) in struck {
|
||||
self.strike(&[tag], domain, &why, now, ttl);
|
||||
}
|
||||
}
|
||||
|
||||
/// Hosts dialled directly since the last run (`counts`: host -> (domain, hits)) into the
|
||||
/// backlog, skipping those a route covers or a verdict within the TTL judged; entries past
|
||||
/// the TTL, or covered since, go; the most dialled 5000 stay.
|
||||
pub fn queue(&mut self, counts: &BTreeMap<String, (String, u64)>, now: u64, ttl: u64) {
|
||||
self.last_run = now;
|
||||
self.hosts.retain(|_, h| h.at + ttl > now);
|
||||
for (host, (domain, hits)) in counts {
|
||||
if self.domains.contains_key(domain) || self.hosts.get(host).is_some_and(|h| h.at + ttl > now) {
|
||||
continue;
|
||||
}
|
||||
let q = self.backlog.entry(host.clone()).or_insert(Queued { domain: domain.clone(), hits: 0, first: now });
|
||||
q.hits += hits;
|
||||
}
|
||||
let domains = &self.domains;
|
||||
self.backlog.retain(|_, q| q.first + ttl > now && !domains.contains_key(&q.domain));
|
||||
if self.backlog.len() > BACKLOG_MAX {
|
||||
let mut v: Vec<(String, Queued)> = std::mem::take(&mut self.backlog).into_iter().collect();
|
||||
v.sort_by_key(|a| std::cmp::Reverse(a.1.hits));
|
||||
v.truncate(BACKLOG_MAX);
|
||||
self.backlog = v.into_iter().collect();
|
||||
}
|
||||
}
|
||||
|
||||
/// The backlog to probe, most dialled first: (domain, host).
|
||||
pub fn backlog_order(&self, now: u64, ttl: u64) -> Vec<(String, String)> {
|
||||
let mut v: Vec<(&String, &Queued)> = self
|
||||
.backlog
|
||||
.iter()
|
||||
.filter(|(h, q)| !self.domains.contains_key(&q.domain) && self.hosts.get(*h).is_none_or(|v| v.at + ttl <= now))
|
||||
.collect();
|
||||
v.sort_by(|a, b| b.1.hits.cmp(&a.1.hits).then_with(|| a.0.cmp(b.0)));
|
||||
v.into_iter().map(|(h, q)| (q.domain.clone(), h.clone())).collect()
|
||||
}
|
||||
|
||||
/// Routes to probe again, once per TTL: (domain, host, exit).
|
||||
pub fn due(&self, now: u64, ttl: u64) -> Vec<(String, String, String)> {
|
||||
self.domains
|
||||
.iter()
|
||||
.filter(|(_, r)| r.verdict == "destination" && now.saturating_sub(r.at) >= ttl)
|
||||
.map(|(d, r)| (d.clone(), r.host.clone(), r.exit.clone()))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn rebad(e: &mut ExitInfo) {
|
||||
e.bad = e.strikes.len() >= 2;
|
||||
let mut s: Vec<(&String, &Strike)> = e.strikes.iter().collect();
|
||||
s.sort_by_key(|(_, v)| v.at);
|
||||
e.bad_by = s.into_iter().map(|(d, v)| format!("{d} {}", v.why)).collect();
|
||||
}
|
||||
|
||||
/// The probe order of the exits after direct: round 1, one exit per network (AS); round 2,
|
||||
/// walked only when round 1 all refused, the rest; bad exits never take a network's round-1
|
||||
/// place and go last. Also the whole order.
|
||||
pub fn rounds(exits: &[String], state: &State) -> (Vec<String>, Vec<String>, Vec<String>) {
|
||||
let info = |t: &str| state.exits.get(t);
|
||||
let bad = |t: &str| info(t).is_some_and(|e| e.bad);
|
||||
let mut ordered: Vec<String> = exits.iter().filter(|t| t.as_str() != DIRECT && !bad(t)).cloned().collect();
|
||||
ordered.extend(exits.iter().filter(|t| t.as_str() != DIRECT && bad(t)).cloned());
|
||||
let (mut r1, mut r2) = (Vec::new(), Vec::new());
|
||||
let mut seen = BTreeSet::new();
|
||||
for t in &ordered {
|
||||
let asn = info(t).and_then(|e| e.asn.clone()).unwrap_or_default();
|
||||
if bad(t) {
|
||||
r2.push(t.clone());
|
||||
} else if asn.is_empty() || seen.insert(asn) {
|
||||
r1.push(t.clone());
|
||||
} else {
|
||||
r2.push(t.clone());
|
||||
}
|
||||
}
|
||||
(r1, r2, ordered)
|
||||
}
|
||||
|
||||
/// The sing-box rule-set (source format) of the domains routed through `exit`.
|
||||
pub fn rule_set(state: &State, exit: &str) -> Value {
|
||||
let domains: Vec<&String> = state.domains.iter().filter(|(_, r)| r.exit == exit).map(|(d, _)| d).collect();
|
||||
if domains.is_empty() {
|
||||
json!({ "version": 1, "rules": [] })
|
||||
} else {
|
||||
json!({ "version": 1, "rules": [{ "domain_suffix": domains }] })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ok() -> Fetch {
|
||||
Fetch { status: Some(200), bytes: 1000, ..Default::default() }
|
||||
}
|
||||
fn dead() -> Fetch {
|
||||
Fetch { status: None, error: "reset".into(), ..Default::default() }
|
||||
}
|
||||
fn refused() -> Fetch {
|
||||
Fetch { status: Some(403), ..Default::default() }
|
||||
}
|
||||
fn wall() -> Fetch {
|
||||
Fetch { status: Some(403), block: "cloudflare".into(), ..Default::default() }
|
||||
}
|
||||
|
||||
/// Runs a future that never waits (the fetches here answer at once).
|
||||
fn now<F: Future>(f: F) -> F::Output {
|
||||
let mut f = std::pin::pin!(f);
|
||||
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
|
||||
match f.as_mut().poll(&mut cx) {
|
||||
std::task::Poll::Ready(v) => v,
|
||||
std::task::Poll::Pending => panic!("a test fetch waited"),
|
||||
}
|
||||
}
|
||||
|
||||
fn exits(tags: &[&str]) -> Vec<String> {
|
||||
tags.iter().map(|s| (*s).to_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn judgements_follow_upstream() {
|
||||
assert_eq!(judge(&ok()), Judgement::Ok);
|
||||
assert_eq!(judge(&Fetch { status: Some(404), ..Default::default() }), Judgement::Ok);
|
||||
assert_eq!(judge(&Fetch { status: Some(302), location: "https://x.example/why-not-available".into(), ..Default::default() }), Judgement::Blocked);
|
||||
assert_eq!(judge(&Fetch { status: Some(301), location: "https://www.x.example/".into(), ..Default::default() }), Judgement::Ok);
|
||||
assert_eq!(judge(&dead()), Judgement::Dead);
|
||||
assert_eq!(judge(&wall()), Judgement::Wall);
|
||||
assert_eq!(judge(&Fetch { status: Some(403), block: "cloudflare-geo".into(), ..Default::default() }), Judgement::Blocked);
|
||||
assert_eq!(verdict(&refused(), &ok()), "destination");
|
||||
assert_eq!(verdict(&dead(), &ok()), "censor");
|
||||
assert_eq!(verdict(&wall(), &refused()), "destination");
|
||||
assert_eq!(verdict(&dead(), &dead()), "unreachable");
|
||||
assert_eq!(verdict(&refused(), &refused()), "both-fail");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_pages_are_recognised() {
|
||||
assert_eq!(block_page(403, "HTTP/1.1 403\r\nserver: cloudflare\r\ncf-mitigated: challenge\r\n", b""), "cloudflare");
|
||||
assert_eq!(block_page(403, "", b"<span class=\"cf-error-code\">1009</span>"), "cloudflare-geo");
|
||||
assert_eq!(block_page(403, "Server: CloudFront\r\n", b"<h1>Request blocked.</h1>"), "aws-waf");
|
||||
assert_eq!(block_page(200, "x-datadome: 1\r\n", b""), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_walk_stops_at_the_first_exit_that_reaches() {
|
||||
let answers = |tag: &str, _path: &str| match tag {
|
||||
"direct" => refused(),
|
||||
"a" => refused(),
|
||||
_ => ok(),
|
||||
};
|
||||
let p = now(walk("x.example", &exits(&["direct", "a", "b", "c"]), &PATHS, false, |t: String, p: String| std::future::ready(answers(&t, &p))));
|
||||
assert_eq!(p.verdict, "destination");
|
||||
assert_eq!(p.exit.as_deref(), Some("b"));
|
||||
assert_eq!(p.rows.len(), 3, "c is never asked");
|
||||
let p = now(walk("x.example", &exits(&["direct", "a"]), &PATHS, false, |_: String, _: String| std::future::ready(ok())));
|
||||
assert_eq!((p.verdict.as_str(), p.rows.len()), ("ok", 1));
|
||||
let p = now(walk("x.example", &exits(&["direct", "a"]), &PATHS, false, |_: String, _: String| std::future::ready(dead())));
|
||||
assert_eq!((p.verdict.as_str(), p.rows.len()), ("unreachable", 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn robots_txt_can_decide_what_the_page_did_not() {
|
||||
let p = now(walk("x.example", &exits(&["direct", "a"]), &PATHS, false, |t: String, path: String| std::future::ready(match (t.as_str(), path.as_str()) {
|
||||
("direct", _) => refused(),
|
||||
("a", "/") => refused(),
|
||||
_ => ok(),
|
||||
})));
|
||||
assert_eq!((p.verdict.as_str(), p.exit.as_deref(), p.path.as_str()), ("destination", Some("a"), "/robots.txt"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stand_in_must_carry_everything_direct_gets() {
|
||||
let p = now(stand_in("x.example", "a", &PATHS, |t: String, path: String| std::future::ready(if t == "a" && path == "/robots.txt" { refused() } else { ok() })));
|
||||
assert_eq!(p.verdict, "blocked");
|
||||
let p = now(stand_in("x.example", "a", &PATHS, |_: String, _: String| std::future::ready(ok())));
|
||||
assert_eq!(p.verdict, "ok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recording_routes_the_domain_and_strikes_who_refused() {
|
||||
let mut s = State::default();
|
||||
let p = now(walk("www.x.example", &exits(&["direct", "a", "b"]), &PATHS, false, |t: String, _: String| std::future::ready(match t.as_str() {
|
||||
"a" => wall(),
|
||||
"b" => ok(),
|
||||
_ => refused(),
|
||||
})));
|
||||
s.record("x.example", "www.x.example", &p, 100, 1000);
|
||||
assert_eq!(s.domains["x.example"].exit, "b");
|
||||
assert_eq!(s.exits["a"].strikes["x.example"].why, "wall:cloudflare");
|
||||
assert!(!s.exits["a"].bad);
|
||||
s.strike(&exits(&["a"]), "y.example", "refused", 200, 1000);
|
||||
assert!(s.exits["a"].bad, "two domains make an exit bad");
|
||||
assert_eq!(s.exits["a"].bad_by, ["x.example wall:cloudflare", "y.example refused"]);
|
||||
s.strike(&[], "", "", 1150, 1000);
|
||||
assert!(!s.exits["a"].bad, "a strike past the TTL stops counting");
|
||||
s.forget("x.example");
|
||||
assert!(s.domains.is_empty() && s.hosts.is_empty());
|
||||
assert_eq!(rule_set(&s, "b"), json!({ "version": 1, "rules": [] }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rounds_take_one_exit_per_network_first_and_bad_ones_last() {
|
||||
let mut s = State::default();
|
||||
for (t, asn) in [("a", "AS1"), ("b", "AS1"), ("c", "AS2")] {
|
||||
s.exits.insert(t.into(), ExitInfo { asn: Some(asn.into()), ..Default::default() });
|
||||
}
|
||||
s.exits.insert("d".into(), ExitInfo { bad: true, ..Default::default() });
|
||||
let (r1, r2, ordered) = rounds(&exits(&["direct", "d", "a", "b", "c", "e"]), &s);
|
||||
assert_eq!(r1, ["a", "c", "e"]);
|
||||
assert_eq!(r2, ["b", "d"]);
|
||||
assert_eq!(ordered, ["a", "b", "c", "e", "d"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_backlog_skips_what_is_known_and_keeps_counting() {
|
||||
let mut s = State::default();
|
||||
s.domains.insert("routed.example".into(), Route { verdict: "destination".into(), exit: "a".into(), host: "routed.example".into(), path: "/".into(), at: 0 });
|
||||
let counts: BTreeMap<String, (String, u64)> = [
|
||||
("www.routed.example".to_owned(), ("routed.example".to_owned(), 5)),
|
||||
("cdn.new.example".to_owned(), ("new.example".to_owned(), 2)),
|
||||
("api.other.example".to_owned(), ("other.example".to_owned(), 7)),
|
||||
]
|
||||
.into();
|
||||
s.queue(&counts, 10, 1000);
|
||||
s.queue(&counts, 20, 1000);
|
||||
assert_eq!(s.backlog.len(), 2);
|
||||
assert_eq!(s.backlog["cdn.new.example"].hits, 4);
|
||||
assert_eq!(s.backlog_order(20, 1000)[0], ("other.example".to_owned(), "api.other.example".to_owned()));
|
||||
s.new_egress("203.0.113.9");
|
||||
assert!(s.domains.is_empty());
|
||||
assert_eq!(s.backlog.len(), 2, "the backlog is about the clients, not the address");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sites_and_local_targets() {
|
||||
assert_eq!(registrable("www.example.co.uk").as_deref(), Some("example.co.uk"));
|
||||
assert_eq!(registrable("foo.workers.dev").as_deref(), Some("foo.workers.dev"));
|
||||
assert_eq!(registrable("co.uk"), None);
|
||||
assert_eq!(site("https://accounts.spotify.com/why"), "spotify.com");
|
||||
assert!(local_target("http://127.1/"));
|
||||
assert!(local_target("https://192.168.0.1/admin"));
|
||||
assert!(local_target("http://localhost:8080/"));
|
||||
assert!(!local_target("https://example.com/"));
|
||||
assert!(host_ok("www.example.com") && !host_ok("127.0.0.1") && !host_ok("example") && !host_ok("a b.com"));
|
||||
}
|
||||
}
|
||||
@@ -126,12 +126,14 @@ fn not_ported(cfg: &Config, v: &mut Issues) {
|
||||
(cfg.warp.enable && cfg.warp.as_amnezia_wg, "warp.asAmneziaWg", "WARP as an AmneziaWG profile"),
|
||||
(cfg.tor.enable && cfg.tor.onion_service.enable, "tor.onionService.enable", "Tor's onion service (it serves the inbounds)"),
|
||||
(cfg.inbounds.enable, "inbounds.enable", "Serving inbounds"),
|
||||
(cfg.proxy.auto_proxy.enable, "proxy.autoProxy.enable", "autoProxy"),
|
||||
] {
|
||||
if on {
|
||||
v.warn(path, format!("{what} {IGNORED}"));
|
||||
}
|
||||
}
|
||||
if cfg.proxy.enable && cfg.proxy.auto_proxy.enable && cfg.proxy.auto_proxy.slow_below_kibps > 0 {
|
||||
v.warn("proxy.autoProxy.slowBelowKiBps", "routing slow destinations is not on Windows yet: autoProxy routes the blocked ones");
|
||||
}
|
||||
if cfg.proxy.enable && cfg.proxy.backend == Backend::Xray {
|
||||
v.warn("proxy.backend", "the xray backend is not on Windows yet: the proxy does not start with it (sing-box or hybrid do)");
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! subscription parsing, and the sing-box and XRay configs the service runs. Nothing here
|
||||
//! touches the network, the file system or processes; the service does that.
|
||||
|
||||
pub mod autoproxy;
|
||||
pub mod awg;
|
||||
pub mod components;
|
||||
pub mod config;
|
||||
|
||||
@@ -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