//! autoProxy's prober, as upstream's autoproxy-run.template.sh runs it: every `interval`, and //! at once for `proxy-ctl proxy auto learn`, it probes the hosts apps dialled directly (and //! those asked for) through each exit in turn, remembers the first exit that reaches what //! direct does not, and publishes it as that exit's rule-set, which sing-box reloads. //! //! Upstream learns the hosts from its server inbounds' access log; on a desktop they are the //! local proxy's own direct connections, which the Clash API lists (`sample`). The judging is //! ps_core::autoproxy's. use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use anyhow::{Context, Result, bail}; use ps_core::autoproxy::{self as ap, Fetch, PATHS, Probe, State}; use ps_core::config::AutoProxy as Options; use ps_core::render::ProbeExit; use serde_json::{Value, json}; use crate::paths::{Paths, write_atomic}; use crate::service::{SOCKS_UNIT, Shared}; use crate::units::UnitState; /// Where the prober's lines go: `proxy-ctl logs proxy-suite-autoproxy`. pub const UNIT: &str = "proxy-suite-autoproxy"; const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) proxy-suite-probe"; /// What the service and the prober share. #[derive(Default)] pub struct AutoProxy { /// Runs and edits take turns on the state. pub lock: tokio::sync::Mutex<()>, /// Hosts asked for, probed at the next run, which asking wakes. pub requests: std::sync::Mutex>, /// Hosts apps dialled directly since the last run, with how often. pub dialled: std::sync::Mutex>, /// What the transfer sampler saw since the last run: host, exit, crawling, fastest second. pub samples: std::sync::Mutex>, pub wake: tokio::sync::Notify, } pub fn dir(paths: &Paths) -> PathBuf { paths.root.join("autoproxy") } pub fn rules_dir(paths: &Paths) -> PathBuf { dir(paths).join("rules") } fn now() -> u64 { SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) } /// The state, or a fresh one; an unreadable one is set aside as state.json.broken. pub fn load(paths: &Paths) -> State { let file = dir(paths).join("state.json"); match std::fs::read(&file) { Ok(bytes) => match serde_json::from_slice(&bytes) { Ok(s) => s, Err(e) => { tracing::warn!("{} is unreadable ({e}); set aside, starting fresh", file.display()); let _ = std::fs::rename(&file, file.with_extension("json.broken")); State::default() } }, Err(_) => State::default(), } } pub fn save(paths: &Paths, state: &State) -> Result<()> { let d = dir(paths); std::fs::create_dir_all(&d)?; write_atomic(&d.join("state.json"), &serde_json::to_vec_pretty(state)?)?; Ok(()) } /// Every exit's rule-set file from the state: before sing-box starts (it refuses a missing /// one), and after each route learned (it reloads a file replaced). pub fn publish(exits: &[ProbeExit], state: &State) -> Result<()> { for e in exits { let Some(path) = &e.path else { continue }; let path = Path::new(path); if let Some(d) = path.parent() { std::fs::create_dir_all(d)?; } let body = serde_json::to_vec(&ap::rule_set(state, &e.tag))?; if std::fs::read(path).is_ok_and(|old| old == body) { continue; } write_atomic(path, &body).with_context(|| format!("writing {}", path.display()))?; } Ok(()) } /// The probe listeners and their login, while the proxy and autoProxy run. #[derive(Clone)] pub struct Exits { pub list: Vec, pub login: (String, String), /// autoProxy.exclude: never probed. pub opts: Options, } impl Exits { fn port(&self, tag: &str) -> Option { self.list.iter().find(|e| e.tag == tag).map(|e| e.port) } fn tags(&self) -> Vec { self.list.iter().map(|e| e.tag.clone()).collect() } /// `domain` at `path` through `tag`'s listener. pub async fn fetch(&self, tag: &str, domain: &str, path: &str) -> Fetch { match self.port(tag) { Some(port) => fetch(port, &self.login, domain, path).await, None => Fetch { error: format!("no exit {tag}"), ..Default::default() }, } } /// Whether the direct listener answers at all: a probe through a listener that is not /// there would judge every site unreachable. async fn up(&self) -> bool { let Some(e) = self.list.first() else { return false }; tokio::time::timeout(Duration::from_secs(3), tokio::net::TcpStream::connect(("127.0.0.1", e.port))).await.is_ok_and(|r| r.is_ok()) } /// A probe of `domain` (a host, or host/path), as `proxy-ctl proxy auto probe` asks it: /// through `wanted` (all, without), or whether `via` carries what direct reaches. pub async fn probe(&self, target: &str, wanted: Option<&[String]>, via: Option<&str>, keep_going: bool) -> Result { let target = target.split("://").last().unwrap_or(target); let (domain, paths): (&str, Vec) = match target.split_once('/') { Some((d, p)) => (d, vec![format!("/{p}")]), None => (target, PATHS.iter().map(|p| (*p).to_owned()).collect()), }; if !ap::host_ok(domain) { bail!("'{domain}' is not a host name"); } if excluded(&self.opts, &domain.to_ascii_lowercase()) { bail!("{domain} is in proxy.autoProxy.exclude: never probed"); } if !self.up().await { bail!("the probe listeners are not up: is the local proxy running?"); } let paths: Vec<&str> = paths.iter().map(String::as_str).collect(); let fetch = |tag: String, path: String| async move { self.fetch(&tag, domain, &path).await }; if let Some(via) = via { if via == ap::DIRECT || self.port(via).is_none() { bail!("no exit named {via} other than direct"); } return Ok(ap::stand_in(domain, via, &paths, fetch).await); } let mut exits = vec![ap::DIRECT.to_owned()]; match wanted { Some(w) => exits.extend(w.iter().filter(|t| t.as_str() != ap::DIRECT && self.port(t).is_some()).cloned()), None => exits.extend(self.list.iter().skip(1).map(|e| e.tag.clone())), } Ok(ap::walk(domain, &exits, &paths, keep_going, fetch).await) } } /// One request through a probe listener: the first hop that is not a same-site redirect /// (a block can sit at the end of a chain: spotify.com -> www -> open -> why-not-available). async fn fetch(port: u16, login: &(String, String), domain: &str, path: &str) -> Fetch { let client = reqwest::Client::builder() .proxy(match reqwest::Proxy::all(format!("socks5h://{}:{}@127.0.0.1:{port}", login.0, login.1)) { Ok(p) => p, Err(e) => return Fetch { error: e.to_string(), ..Default::default() }, }) .redirect(reqwest::redirect::Policy::none()) .user_agent(USER_AGENT) .connect_timeout(Duration::from_secs(8)) .timeout(Duration::from_secs(15)) .build(); let client = match client { Ok(c) => c, Err(e) => return Fetch { error: e.to_string(), ..Default::default() }, }; let mut url = format!("https://{domain}{path}"); let site = ap::site(&url); let mut result = Fetch::default(); for _ in 0..6 { result = match client.get(&url).send().await { Err(e) => return Fetch { error: short_error(&e), ..Default::default() }, Ok(mut resp) => { let status = resp.status().as_u16(); let head: String = resp.headers().iter().map(|(k, v)| format!("{k}: {}\r\n", String::from_utf8_lossy(v.as_bytes()))).collect(); let location = resp .headers() .get(reqwest::header::LOCATION) .and_then(|l| l.to_str().ok()) .and_then(|l| resp.url().join(l).ok()) .map(|u| u.to_string()) .unwrap_or_default(); // Enough to judge a refusal by (its first 8 KiB) and to count what came. let mut body = Vec::new(); while body.len() < 64 * 1024 { match resp.chunk().await { Ok(Some(c)) => body.extend_from_slice(&c), _ => break, } } Fetch { status: Some(status), block: ap::block_page(status, &head, &body), location, bytes: body.len() as u64, error: String::new() } } }; let redirect = result.status.is_some_and(|s| (300..400).contains(&s)); if !redirect || ap::redirect_is_block(&result.location) || result.location.is_empty() { break; } if ap::site(&result.location) != site || ap::local_target(&result.location) || !result.location.starts_with("http") { break; } url = result.location.clone(); } result } fn short_error(e: &reqwest::Error) -> String { if e.is_timeout() { "timed out".into() } else if e.is_connect() { "could not connect".into() } else { let mut s = e.to_string(); let mut src = std::error::Error::source(e); while let Some(inner) = src { s = inner.to_string(); src = inner.source(); } s.chars().take(120).collect() } } /// A plain GET through a probe listener, for the egress address and an exit's network. async fn get_text(port: u16, login: &(String, String), url: &str) -> Option { let client = reqwest::Client::builder() .proxy(reqwest::Proxy::all(format!("socks5h://{}:{}@127.0.0.1:{port}", login.0, login.1)).ok()?) .user_agent(USER_AGENT) .timeout(Duration::from_secs(10)) .build() .ok()?; let resp = client.get(url).send().await.ok()?; if !resp.status().is_success() { return None; } let text = resp.text().await.ok()?; (text.len() < 64 * 1024).then_some(text) } /// The probe listeners, when autoProxy runs with the local proxy. pub fn exits(s: &crate::service::Service) -> Option { let cfg = s.cfg(); if !(cfg.enable && cfg.proxy.enable && cfg.proxy.auto_proxy.enable) || s.sup.state_of(SOCKS_UNIT) != UnitState::Active { return None; } let list = s.last.as_ref()?.probe_exits.clone(); (!list.is_empty()).then(|| Exits { list, login: (s.store.secrets.hop_user.clone(), s.store.secrets.hop_password.clone()), opts: cfg.proxy.auto_proxy.clone(), }) } pub fn excluded(opts: &Options, host: &str) -> bool { opts.exclude.iter().any(|x| { let x = x.trim_start_matches('.').to_ascii_lowercase(); host == x || host.ends_with(&format!(".{x}")) }) } #[derive(Clone, Copy, PartialEq, Eq)] pub enum Mode { /// Everything: rechecks, the backlog, the requests. Full, /// `proxy-ctl proxy auto learn`'s hosts only. Requests, } /// One run. Each verdict is saved as it comes: a run cut short keeps what it learned. pub async fn run(shared: &Shared, mode: Mode) { let (exits, opts, paths, disabled, auto) = { let s = shared.lock().await; let Some(exits) = exits(&s) else { return }; let disabled = s.last.as_ref().map(|r| r.inventory.disabled.clone()).unwrap_or_default(); (exits, s.cfg().proxy.auto_proxy.clone(), s.paths().clone(), disabled, s.ap.clone()) }; let _turn = auto.lock.lock().await; let note = async |line: String| shared.lock().await.sup.note(UNIT, line); if !exits.up().await { note("no probe listeners: is the local proxy running?".into()).await; return; } let ttl = u64::from(opts.ttl_days) * 86400; let now = now(); let mut state = load(&paths); let save_and = async |state: &State, publish_too: bool| { if let Err(e) = save(&paths, state) { tracing::warn!("autoProxy's state: {e:#}"); } if publish_too && let Err(e) = publish(&exits.list, state) { tracing::warn!("autoProxy's rule-sets: {e:#}"); } }; // Routes through an exit disabled since: probed again without it. let gone: Vec<(String, String)> = state.domains.iter().filter(|(_, r)| disabled.contains(&r.exit)).map(|(d, r)| (d.clone(), r.exit.clone())).collect(); for (d, exit) in &gone { state.forget(d); note(format!("forgot {d}: its exit {exit} is disabled")).await; } // Verdicts are about this host's address: a new one discards them. An error page or a // captive portal must not pass for one. let direct_port = exits.list[0].port; if let Some(egress) = get_text(direct_port, &exits.login, "https://api.ipify.org").await.map(|t| t.trim().to_owned()) && !egress.is_empty() && egress.chars().all(|c| c.is_ascii_hexdigit() || c == '.' || c == ':') && state.egress.as_deref() != Some(egress.as_str()) { if state.egress.is_some() { note(format!("egress is now {egress}; discarding everything learned for the old address")).await; } state.new_egress(&egress); } // Which network (AS) each exit leaves from, once per TTL. for e in &exits.list { if now.saturating_sub(state.exits.get(&e.tag).map_or(0, |x| x.at)) < ttl { continue; } let Some(info) = get_text(e.port, &exits.login, "https://ipinfo.io/json").await.and_then(|t| serde_json::from_str::(&t).ok()) else { continue; }; let Some(ip) = info["ip"].as_str() else { continue }; let x = state.exits.entry(e.tag.clone()).or_default(); x.ip = Some(ip.to_owned()); x.asn = info["org"].as_str().and_then(|o| o.split_whitespace().next()).map(str::to_owned); x.at = now; } state.strike(&[], "", "", now, ttl); let (r1, r2, _) = ap::rounds(&exits.tags(), &state); save_and(&state, !gone.is_empty()).await; // Walks round 1; round 2 only when it all refused, round 1's refusals kept. let exits = &exits; let walk = async |host: &str| -> Probe { let fetch = |tag: String, path: String| async move { exits.fetch(&tag, host, &path).await }; let first: Vec = std::iter::once(ap::DIRECT.to_owned()).chain(r1.iter().cloned()).collect(); let p = ap::walk(host, &first, &PATHS, false, fetch).await; if matches!(p.verdict.as_str(), "both-fail" | "unreachable") && !r2.is_empty() { let fetch = |tag: String, path: String| async move { exits.fetch(&tag, host, &path).await }; let second: Vec = std::iter::once(ap::DIRECT.to_owned()).chain(r2.iter().cloned()).collect(); let mut q = ap::walk(host, &second, &PATHS, false, fetch).await; let mut rows = p.rows; rows.append(&mut q.rows); q.rows = rows; return q; } p }; let mut requeue: Vec<(String, String)> = Vec::new(); if mode == Mode::Full { // Remembered routes, once per TTL. for (dom, host, exit) in state.due(now, ttl) { let h = host.as_str(); let fetch = |tag: String, path: String| async move { exits.fetch(&tag, h, &path).await }; let p = ap::walk(&host, &[ap::DIRECT.to_owned(), exit.clone()], &PATHS, false, fetch).await; if p.verdict == "destination" && p.exit.as_deref() == Some(exit.as_str()) { if let Some(r) = state.domains.get_mut(&dom) { r.at = now; } } else if p.verdict == "ok" { note(format!("recheck {dom}: reachable directly now, dropping {exit}")).await; state.domains.remove(&dom); state.record(&dom, &host, &p, now, ttl); save_and(&state, true).await; } else { note(format!("recheck {dom}: {exit} no longer works ({}), walking again", p.verdict)).await; state.domains.remove(&dom); save_and(&state, true).await; requeue.push((dom, host)); } } // What apps dialled directly since the last run, per host. let dialled = std::mem::take(&mut *auto.dialled.lock().unwrap()); let counts: BTreeMap = dialled .into_iter() .filter(|(h, _)| ap::host_ok(h) && !excluded(&opts, h)) .filter_map(|(h, n)| ap::registrable(&h).map(|d| (h, (d, n)))) .collect(); state.queue(&counts, now, ttl); save_and(&state, false).await; // What the sampler saw crawl: each such site gets the next exit, in probe order, that // answers it as well as direct does; none left, it stays direct for a TTL. let samples = std::mem::take(&mut *auto.samples.lock().unwrap()); if opts.slow_below_kibps > 0 && !samples.is_empty() { let obs: Vec = samples .into_iter() .filter(|(h, ..)| ap::host_ok(h) && !excluded(&opts, h)) .filter_map(|(host, exit, slow, peak)| ap::registrable(&host).map(|domain| ap::Observation { domain, host, exit, slow, peak })) .collect(); let before = state.domains.clone(); state.judge_slow(&obs, now, 3); let (_, _, ordered) = ap::rounds(&exits.tags(), &state); let wanted: Vec<(String, ap::SlowWant)> = state.slow_want.iter().take(20).map(|(d, w)| (d.clone(), w.clone())).collect(); for (dom, want) in wanted { let mut tried = want.tried.clone(); let was = tried.last().cloned(); // It crawled twice on the exit it was routed through. if let Some(was) = &was { state.strike(std::slice::from_ref(was), &dom, "slow", now, ttl); } let mut via = None; for tag in &ordered { if tried.contains(tag) { continue; } tried.push(tag.clone()); let host = want.host.as_str(); let fetch = |t: String, path: String| async move { exits.fetch(&t, host, &path).await }; let p = ap::stand_in(host, tag, &PATHS, fetch).await; if p.verdict == "ok" { via = Some(tag.clone()); break; } // Refused what direct gets: by a block page, or by the origin. let rows: Vec<&ap::Row> = p.rows.iter().filter(|r| &r.tag == tag).collect(); let why = rows .iter() .find(|r| r.judgement == ap::Judgement::Wall) .map(|r| format!("wall:{}", r.fetch.block)) .or_else(|| rows.iter().any(|r| r.judgement == ap::Judgement::Blocked).then(|| "refused".to_owned())); if let Some(why) = why { state.strike(std::slice::from_ref(tag), &dom, &why, now, ttl); } } let how = was.as_deref().map_or("directly".to_owned(), |w| format!("via {w}")); match via { Some(v) => { note(format!("slow {dom}: crawls {how}, routed via {v}")).await; state.route_slow(&dom, &want.host, &v, tried, now); } None => { note(format!("slow {dom}: crawls {how}, and no other exit reaches it; left direct")).await; state.skip_slow(&dom, now, ttl); } } } save_and(&state, state.domains != before).await; } } // Probe: the requests, then broken routes, then the backlog. let mut asked: Vec<(String, String)> = Vec::new(); { let mut requests = auto.requests.lock().unwrap(); let mut seen = BTreeSet::new(); let taken: Vec = std::mem::take(&mut *requests); for h in taken { let h = h.trim().to_ascii_lowercase(); if !ap::host_ok(&h) || excluded(&opts, &h) || !seen.insert(h.clone()) { continue; } if let Some(d) = ap::registrable(&h) { asked.push((d, h)); } } let max = opts.probes_per_run as usize; if asked.len() > max { requests.extend(asked.split_off(max).into_iter().map(|(_, h)| h)); } } let left = auto.requests.lock().unwrap().len(); if left > 0 { note(format!("{left} requested host(s) past probesPerRun wait for the next run")).await; } let backlog = if mode == Mode::Full { state.backlog_order(now, ttl) } else { Vec::new() }; let mut seen: HashSet = HashSet::new(); let mut routed: HashSet = HashSet::new(); let started = Instant::now(); let mut probed = 0usize; let rows = asked.iter().map(|r| (r, true)).chain(requeue.iter().chain(backlog.iter()).map(|r| (r, false))); for ((dom, host), was_asked) in rows { if !was_asked && probed >= opts.probes_per_run as usize { break; } // A run of tarpits must not go on for good: what is left waits for the next. if started.elapsed() > Duration::from_secs(2 * 3600) { note("a run ends after two hours; the rest wait for the next".into()).await; break; } if !seen.insert(host.clone()) || routed.contains(dom) { continue; } if !was_asked { probed += 1; } if !exits.up().await { note("the probe listeners went away; the run ends".into()).await; break; } let p = walk(host).await; state.record(dom, host, &p, now, ttl); let destination = p.verdict == "destination"; if destination { routed.insert(dom.clone()); } save_and(&state, destination).await; let how = match (&p.verdict[..], &p.exit) { ("destination", Some(x)) => format!("destination via {x}"), ("censor", Some(x)) => format!("censor ({x} reaches it; left to zapret)"), (v, _) => v.to_owned(), }; note(format!("probe {host} -> {how}")).await; } if mode == Mode::Full || !asked.is_empty() { note(format!("probed {} requested and {probed} queued host(s); {} still waiting", asked.len(), state.backlog.len())).await; } save_and(&state, true).await; } /// The prober's schedule: a first run ten minutes after start (as upstream's timer; sooner with /// a shorter `interval`), then every `interval`; a learn request wakes it for the requests alone. pub async fn runner(shared: Shared) { let (auto, every) = { let s = shared.lock().await; (s.ap.clone(), interval(&s.cfg().proxy.auto_proxy)) }; let mut next = Instant::now() + every.min(Duration::from_secs(600)); loop { tokio::select! { _ = tokio::time::sleep_until(next.into()) => { run(&shared, Mode::Full).await; next = Instant::now() + interval(&shared.lock().await.cfg().proxy.auto_proxy); } _ = auto.wake.notified() => run(&shared, Mode::Requests).await, } } } /// `interval`, a minute at least. fn interval(opts: &Options) -> Duration { ps_core::duration::parse(&opts.interval).unwrap_or(Duration::from_secs(600)).max(Duration::from_secs(60)) } /// The hosts the local proxy's clients dial directly, from the Clash API's connections, every /// ten seconds while autoProxy runs: what the prober's backlog is made of. pub async fn sample(shared: Shared) { let mut seen: HashSet = HashSet::new(); loop { tokio::time::sleep(Duration::from_secs(10)).await; let (clash, auto) = { let s = shared.lock().await; let cfg = s.cfg(); if exits(&s).is_none() { continue; } (crate::clash::Clash::new(cfg.proxy.sing_box.clash_api_port, &s.store.secrets.clash_secret), s.ap.clone()) }; let Ok(v) = clash.connections().await else { continue }; let mut dialled = auto.dialled.lock().unwrap(); for c in v["connections"].as_array().into_iter().flatten() { let Some(id) = c["id"].as_str() else { continue }; if !seen.insert(id.to_owned()) { continue; } let m = &c["metadata"]; let inbound = m["type"].as_str().unwrap_or(""); if inbound.contains("probe-in-") || inbound.contains("proxy-suite-test-in") { continue; } // Only what went direct: the rest is routed already. let chains: Vec<&str> = c["chains"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); if chains != [ap::DIRECT] { continue; } let port = m["destinationPort"].as_str().map(str::to_owned).or_else(|| m["destinationPort"].as_u64().map(|p| p.to_string())); if !matches!(port.as_deref(), Some("443" | "80")) { continue; } let host = m["host"].as_str().unwrap_or("").to_ascii_lowercase(); if ap::host_ok(&host) { *dialled.entry(host).or_insert(0) += 1; } } if seen.len() > 50_000 { seen.clear(); } // Bounded between runs, as the backlog is. if dialled.len() > 20_000 { let mut v: Vec<(String, u64)> = std::mem::take(&mut *dialled).into_iter().collect(); v.sort_by_key(|a| std::cmp::Reverse(a.1)); v.truncate(10_000); *dialled = v.into_iter().collect(); } } } /// Live transfers every minute while slow sites are routed (`slowBelowKiBps`): eleven Clash /// API snapshots a second apart, the transfers that moved enough kept for the next run, as /// upstream's sampler timer does. pub async fn sample_slow(shared: Shared) { loop { tokio::time::sleep(Duration::from_secs(60)).await; let (clash, auto, below) = { let s = shared.lock().await; let cfg = s.cfg(); let below = cfg.proxy.auto_proxy.slow_below_kibps; if below == 0 || exits(&s).is_none() { continue; } (crate::clash::Clash::new(cfg.proxy.sing_box.clash_api_port, &s.store.secrets.clash_secret), s.ap.clone(), below) }; let mut snapshots = Vec::with_capacity(11); for i in 0..11 { if i > 0 { tokio::time::sleep(Duration::from_secs(1)).await; } snapshots.push(clash.connections().await.unwrap_or(Value::Null)); } let seen = ap::sample_transfers(&snapshots, 300 * 1024, u64::from(below) * 1024); let mut samples = auto.samples.lock().unwrap(); samples.extend(seen); let over = samples.len().saturating_sub(10_000); samples.drain(..over); } } /// What `proxy-ctl proxy auto` lists. Without `detail` (the secrets scope) the sites routed /// and the counts only: the hosts probed, those left to zapret and the sites behind each /// strike are browsing history, as the logs are. pub fn listing(paths: &Paths, exits: Option<&Exits>, opts: &Options, detail: bool) -> Value { let s = load(paths); let domains: Vec = s .domains .iter() .map(|(d, r)| { let mut v = json!({ "domain": d, "exit": r.exit, "verdict": r.verdict, "at": r.at }); if detail { v["host"] = r.host.clone().into(); } v }) .collect(); let exit_list: Vec = s .exits .iter() .map(|(t, e)| { let mut v = json!({ "tag": t, "ip": e.ip, "asn": e.asn, "bad": e.bad, "strikes": e.strikes.len() }); if detail { v["badBy"] = json!(e.bad_by); } v }) .collect(); let censored: Vec<&String> = s.hosts.iter().filter(|(_, h)| h.verdict == "censor").map(|(h, _)| h).collect(); let censored = if detail { json!(censored) } else { json!(censored.len()) }; json!({ "enabled": opts.enable, "running": exits.is_some(), "egress": s.egress, "lastRun": s.last_run, "domains": domains, "exits": exit_list, "probeExits": exits.map(|e| e.tags()).unwrap_or_default(), "hostsJudged": s.hosts.len(), "censored": censored, "backlog": s.backlog.len(), "slowWaiting": s.slow_want.len(), }) } /// `forget ` or `clear`, under the prober's lock, published at once. pub async fn edit(shared: &Shared, forget: Option<&str>) -> Result<()> { let (paths, auto, list) = { let s = shared.lock().await; (s.paths().clone(), s.ap.clone(), s.last.as_ref().map(|r| r.probe_exits.clone()).unwrap_or_default()) }; let _turn = auto.lock.lock().await; let mut state = load(&paths); match forget { Some(d) => { if !ap::host_ok(d) { bail!("'{d}' is not a domain"); } state.forget(&d.to_ascii_lowercase()); } None => state.clear(), } save(&paths, &state)?; publish(&list, &state) } #[cfg(test)] mod tests { use super::*; #[test] fn exclusions_take_subdomains() { let opts = Options { exclude: vec!["internal.example".into()], ..Default::default() }; assert!(excluded(&opts, "internal.example")); assert!(excluded(&opts, "a.internal.example")); assert!(!excluded(&opts, "notinternal.example")); } #[test] fn published_rule_sets_follow_the_state() { let d = std::env::temp_dir().join(format!("ps-ap-{}", std::process::id())); let path = d.join("rs-1.json"); let exits = [ ProbeExit { tag: "direct".into(), port: 1, rule_set: None, path: None }, ProbeExit { tag: "nl".into(), port: 2, rule_set: Some("autoproxy-1".into()), path: Some(path.to_string_lossy().into()) }, ]; let mut s = State::default(); s.domains.insert("x.example".into(), ap::Route { verdict: "destination".into(), exit: "nl".into(), host: "x.example".into(), path: "/".into(), at: 1, bad: 0, tried: Vec::new() }); publish(&exits, &s).unwrap(); let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); assert_eq!(v, json!({ "version": 1, "rules": [{ "domain_suffix": ["x.example"] }] })); let _ = std::fs::remove_dir_all(&d); } }