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
@@ -136,6 +136,7 @@ fn scope_of(req: &Request) -> Option<Scope> {
|
||||
Request::RenderedConfig | Request::Logs { .. } | Request::TgLinks => Some(Scope::Secrets),
|
||||
Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services),
|
||||
Request::WlList | Request::WlLink { .. } | Request::WlAuth { .. } | Request::WlJoin { .. } | Request::WlNew { .. } => Some(Scope::WhitelistBypass),
|
||||
Request::AutoList | Request::AutoProbe { .. } | Request::AutoLearn { .. } | Request::AutoForget { .. } => Some(Scope::AutoProxy),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -577,6 +578,48 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
|
||||
wl_restart(&mut s, &format!("{}{name}", crate::wl::CREATOR_PREFIX)).await
|
||||
}
|
||||
|
||||
Request::AutoList => {
|
||||
let s = shared.lock().await;
|
||||
let exits = crate::autoproxy::exits(&s);
|
||||
Response::ok(crate::autoproxy::listing(s.paths(), exits.as_ref(), &s.cfg().proxy.auto_proxy))
|
||||
}
|
||||
|
||||
Request::AutoProbe { target, exits, via, keep_going } => {
|
||||
let Some(probe_exits) = crate::autoproxy::exits(&*shared.lock().await) else {
|
||||
return Response::err("autoProxy is not running: it needs proxy.autoProxy.enable and the local proxy on");
|
||||
};
|
||||
// The network, outside the lock.
|
||||
match probe_exits.probe(&target, exits.as_deref(), via.as_deref(), keep_going).await {
|
||||
Ok(p) => Response::ok(serde_json::to_value(&p).unwrap()),
|
||||
Err(e) => Response::err(format!("{e:#}")),
|
||||
}
|
||||
}
|
||||
|
||||
Request::AutoLearn { hosts } => {
|
||||
let s = shared.lock().await;
|
||||
if crate::autoproxy::exits(&s).is_none() {
|
||||
return Response::err("autoProxy is not running: it needs proxy.autoProxy.enable and the local proxy on");
|
||||
}
|
||||
let bad: Vec<&String> = hosts.iter().filter(|h| !ps_core::autoproxy::host_ok(h.trim())).collect();
|
||||
if !bad.is_empty() {
|
||||
return Response::err(format!("not host names: {}", bad.iter().map(|h| h.as_str()).collect::<Vec<_>>().join(", ")));
|
||||
}
|
||||
let queued = {
|
||||
let mut r = s.ap.requests.lock().unwrap();
|
||||
// Bounded: every request is a probe.
|
||||
let room = 10_000usize.saturating_sub(r.len());
|
||||
r.extend(hosts.iter().take(room).map(|h| h.trim().to_owned()));
|
||||
hosts.len().min(room)
|
||||
};
|
||||
s.ap.wake.notify_one();
|
||||
Response::ok(json!({ "queued": queued }))
|
||||
}
|
||||
|
||||
Request::AutoForget { domain } => match crate::autoproxy::edit(shared, domain.as_deref()).await {
|
||||
Ok(()) => Response::ok(json!({ "forgot": domain.unwrap_or_else(|| "everything".into()) })),
|
||||
Err(e) => Response::err(format!("{e:#}")),
|
||||
},
|
||||
|
||||
Request::ComponentsInstall { names } => {
|
||||
// Programs the service runs as SYSTEM: an administrator's call, whatever the scopes.
|
||||
if !peer.admin {
|
||||
|
||||
@@ -0,0 +1,605 @@
|
||||
//! 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<Vec<String>>,
|
||||
/// Hosts apps dialled directly since the last run, with how often.
|
||||
pub dialled: std::sync::Mutex<BTreeMap<String, u64>>,
|
||||
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<ProbeExit>,
|
||||
pub login: (String, String),
|
||||
}
|
||||
|
||||
impl Exits {
|
||||
fn port(&self, tag: &str) -> Option<u16> {
|
||||
self.list.iter().find(|e| e.tag == tag).map(|e| e.port)
|
||||
}
|
||||
|
||||
fn tags(&self) -> Vec<String> {
|
||||
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<Probe> {
|
||||
let target = target.split("://").last().unwrap_or(target);
|
||||
let (domain, paths): (&str, Vec<String>) = 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 !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<String> {
|
||||
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<Exits> {
|
||||
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()) })
|
||||
}
|
||||
|
||||
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::<Value>(&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<String> = 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<String> = 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<String, (String, u64)> = 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;
|
||||
}
|
||||
|
||||
// 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<String> = std::mem::take(&mut *requests);
|
||||
for h in taken {
|
||||
let h = h.trim().to_ascii_lowercase();
|
||||
if !ap::host_ok(&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<String> = HashSet::new();
|
||||
let mut routed: HashSet<String> = 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<String> = 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What `proxy-ctl proxy auto` lists.
|
||||
pub fn listing(paths: &Paths, exits: Option<&Exits>, opts: &Options) -> Value {
|
||||
let s = load(paths);
|
||||
let domains: Vec<Value> = s.domains.iter().map(|(d, r)| json!({ "domain": d, "exit": r.exit, "verdict": r.verdict, "host": r.host, "at": r.at })).collect();
|
||||
let exit_list: Vec<Value> = s
|
||||
.exits
|
||||
.iter()
|
||||
.map(|(t, e)| json!({ "tag": t, "ip": e.ip, "asn": e.asn, "bad": e.bad, "badBy": e.bad_by }))
|
||||
.collect();
|
||||
let censored: Vec<&String> = s.hosts.iter().filter(|(_, h)| h.verdict == "censor").map(|(h, _)| h).collect();
|
||||
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(),
|
||||
})
|
||||
}
|
||||
|
||||
/// `forget <domain>` 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 });
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,11 @@ impl Clash {
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
/// The connections open now, with where each goes and through what.
|
||||
pub async fn connections(&self) -> Result<Value> {
|
||||
self.get("/connections").await
|
||||
}
|
||||
|
||||
/// Every proxy (outbound or group) with what a selector holds now.
|
||||
pub async fn proxies(&self) -> Result<Value> {
|
||||
self.get("/proxies").await.map(|v| v["proxies"].clone())
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! it); `--console` runs it in the foreground, which is also how it runs off Windows.
|
||||
|
||||
mod api;
|
||||
mod autoproxy;
|
||||
mod awg;
|
||||
mod clash;
|
||||
mod components;
|
||||
@@ -103,6 +104,8 @@ pub async fn run(
|
||||
tracing::warn!("not starting the proxy yet: {e}");
|
||||
}
|
||||
tokio::spawn(api::serve(server, shared.clone()));
|
||||
tokio::spawn(autoproxy::runner(shared.clone()));
|
||||
tokio::spawn(autoproxy::sample(shared.clone()));
|
||||
// First fetches: what the configuration needs and has not got yet.
|
||||
{
|
||||
let shared = shared.clone();
|
||||
|
||||
@@ -39,6 +39,8 @@ pub struct Service {
|
||||
tcp_timestamps_on: bool,
|
||||
/// What whitelist-bypass's units waited for at the last apply, said when it first did.
|
||||
wl_waiting: BTreeSet<String>,
|
||||
/// autoProxy's requests and the hosts its prober learns from (crate::autoproxy).
|
||||
pub ap: Arc<crate::autoproxy::AutoProxy>,
|
||||
}
|
||||
|
||||
fn digest(data: &[u8]) -> String {
|
||||
@@ -62,6 +64,7 @@ impl Service {
|
||||
last_fetch: BTreeMap::new(),
|
||||
tcp_timestamps_on: false,
|
||||
wl_waiting: BTreeSet::new(),
|
||||
ap: Arc::default(),
|
||||
store,
|
||||
})
|
||||
}
|
||||
@@ -136,6 +139,7 @@ impl Service {
|
||||
ssh_identity_path: cfg.ssh_proxy.identity_file.as_ref().map(|_| crate::ssh::identity_path(paths).to_string_lossy().into_owned()),
|
||||
ssh_host_keys: if cfg.ssh_proxy.enable { crate::ssh::host_keys(cfg, |f| std::fs::read_to_string(f).ok()) } else { Vec::new() },
|
||||
windows: cfg!(windows),
|
||||
autoproxy_rules_dir: cfg.proxy.auto_proxy.enable.then(|| crate::autoproxy::rules_dir(paths).to_string_lossy().into_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -357,6 +361,10 @@ impl Service {
|
||||
for w in &rendered.warnings {
|
||||
self.sup.note(SOCKS_UNIT, format!("proxy-suite: warning: {w}"));
|
||||
}
|
||||
// sing-box refuses a local rule-set file that is not there: autoProxy's, written first.
|
||||
if !rendered.probe_exits.is_empty() {
|
||||
crate::autoproxy::publish(&rendered.probe_exits, &crate::autoproxy::load(self.paths()))?;
|
||||
}
|
||||
|
||||
let backend = self.cfg().proxy.backend;
|
||||
let main_program = match backend {
|
||||
|
||||
Reference in new issue
Block a user