use crate::error::{Error, ProxyError};
use crate::judge::{Judge, JudgePool};
use crate::negotiator::{negotiate, Target};
use crate::proxy::Proxy;
use crate::resolver::Resolver;
use crate::types::{AnonLevel, Caps, JudgeScheme, Proto, TypeSpec};
use crate::utils::{fresh_marker, get_all_ip, get_status_code, request_headers};
use rand::Rng;
use std::collections::{BTreeMap, HashSet};
use std::net::IpAddr;
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
pub struct Checker {
judges: JudgePool,
real_ext_ips: HashSet<IpAddr>,
requested: Vec<TypeSpec>,
timeout: Duration,
post: bool,
strict: bool,
relaxed_validity: bool,
trust_check: bool,
dnsbl: Vec<String>,
resolver: std::sync::Arc<Resolver>,
mode: CheckMode,
retry: RetryPolicy,
}
enum CheckMode {
Judged,
Liveness(LivenessTarget),
}
struct LivenessTarget {
host: String,
path: String,
ip: IpAddr,
scheme: JudgeScheme,
}
impl LivenessTarget {
async fn resolve(url: &str, resolver: &Resolver) -> Option<LivenessTarget> {
let judge = Judge::parse(url)?;
if judge.scheme == JudgeScheme::Smtp {
return None;
}
let ip = resolver.resolve(&judge.host).await.ok()?;
Some(LivenessTarget {
host: judge.host,
path: judge.path,
ip,
scheme: judge.scheme,
})
}
}
enum Probe<'a> {
Judged(&'a Judge),
Liveness(&'a LivenessTarget),
}
impl std::fmt::Debug for Checker {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Checker")
.field("judges", &self.judges.counts())
.field("requested", &self.requested)
.field("strict", &self.strict)
.field("dnsbl", &self.dnsbl)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct RetryPolicy {
pub max_tries: usize,
pub retry_on: HashSet<ProxyError>,
pub backoff: Duration,
pub factor: f64,
pub jitter: f64,
pub max_backoff: Duration,
}
impl Default for RetryPolicy {
fn default() -> Self {
RetryPolicy {
max_tries: 3,
retry_on: HashSet::from([ProxyError::Timeout]),
backoff: Duration::ZERO,
factor: 1.0,
jitter: 0.0,
max_backoff: Duration::ZERO,
}
}
}
impl RetryPolicy {
pub fn tries(max_tries: usize) -> Self {
RetryPolicy {
max_tries,
..Default::default()
}
}
pub fn transient(max_tries: usize) -> Self {
RetryPolicy {
max_tries,
retry_on: HashSet::from([
ProxyError::Timeout,
ProxyError::Reset,
ProxyError::ConnFailed,
ProxyError::EmptyRecv,
]),
..Default::default()
}
}
pub fn backoff_for(&self, i: usize) -> Duration {
if self.backoff.is_zero() {
return Duration::ZERO;
}
let mut d = self.backoff.as_secs_f64() * self.factor.powi(i as i32);
if self.jitter > 0.0 {
let r: f64 = rand::rng().random_range(-1.0..=1.0);
d *= 1.0 + self.jitter * r;
}
if !self.max_backoff.is_zero() {
d = d.min(self.max_backoff.as_secs_f64());
}
Duration::from_secs_f64(d.max(0.0))
}
}
#[derive(Debug, Clone, Default)]
pub struct CheckerConfig {
pub judges: Vec<String>,
pub types: Vec<TypeSpec>,
pub timeout: Duration,
pub retry: RetryPolicy,
pub post: bool,
pub strict: bool,
pub relaxed_validity: bool,
pub trust_check: bool,
pub dnsbl: Vec<String>,
pub liveness_url: Option<String>,
}
impl Checker {
pub async fn new(
cfg: CheckerConfig,
resolver: std::sync::Arc<Resolver>,
client: &reqwest::Client,
real_ext_ips: HashSet<IpAddr>,
) -> Result<Checker, Error> {
if cfg.types.is_empty() {
return Err(Error::NoTypes);
}
let urls = if cfg.judges.is_empty() {
crate::judge::default_judges()
} else {
cfg.judges.clone()
};
let candidates: Vec<Judge> = urls.iter().filter_map(|u| Judge::parse(u)).collect();
let judges =
JudgePool::probe_all(candidates, &resolver, client, &real_ext_ips, cfg.timeout).await;
let mode = if judges.is_empty() {
match &cfg.liveness_url {
Some(url) => CheckMode::Liveness(
LivenessTarget::resolve(url, &resolver)
.await
.ok_or(Error::NoJudges)?,
),
None => return Err(Error::NoJudges),
}
} else {
CheckMode::Judged
};
Ok(Checker {
judges,
real_ext_ips,
requested: cfg.types,
timeout: cfg.timeout,
retry: cfg.retry,
post: cfg.post,
strict: cfg.strict,
relaxed_validity: cfg.relaxed_validity,
trust_check: cfg.trust_check,
dnsbl: cfg.dnsbl,
resolver,
mode,
})
}
pub async fn check(&self, proxy: &mut Proxy) -> bool {
if !self.dnsbl.is_empty() && self.in_dnsbl(proxy.host).await {
tracing::debug!(addr = %proxy.addr(), "rejected: found in DNSBL");
return false;
}
let requested: HashSet<Proto> = self.requested.iter().map(|t| t.proto).collect();
let ngtrs: Vec<Proto> = Proto::ALL
.into_iter()
.filter(|p| {
requested.contains(p)
&& (proxy.expected_types.is_empty() || proxy.expected_types.contains(p))
})
.collect();
let mut any = false;
for proto in ngtrs {
if self.check_one(proxy, proto).await {
any = true;
}
}
any && self.types_passed(proxy)
}
async fn in_dnsbl(&self, host: IpAddr) -> bool {
let queries: Vec<String> = self
.dnsbl
.iter()
.filter_map(|zone| dnsbl_query(host, zone))
.collect();
if queries.is_empty() {
return false;
}
let probes = queries.iter().map(|q| self.resolver.resolve(q));
futures_util::future::join_all(probes)
.await
.iter()
.any(|r| r.is_ok())
}
async fn check_one(&self, proxy: &mut Proxy, proto: Proto) -> bool {
let scheme = proto.judge_scheme();
let judge; let (probe, target) = match &self.mode {
CheckMode::Judged => {
let Some(j) = self.judges.random(scheme) else {
return false; };
judge = j;
let target = Target {
host: judge.host.clone(),
ip: judge.ip,
port: scheme.default_port(),
};
(Probe::Judged(&judge), target)
}
CheckMode::Liveness(lt) => {
let target = Target {
host: lt.host.clone(),
ip: Some(lt.ip),
port: lt.scheme.default_port(),
};
(Probe::Liveness(lt), target)
}
};
for i in 0..self.retry.max_tries {
let start = Instant::now();
match self.attempt(proxy, proto, &probe, &target).await {
Ok(Attempt::Working(obs)) => {
let rtt = start.elapsed().as_secs_f64();
tracing::info!(
target: "proxybroker::check",
addr = %proxy.addr(),
proto = proto.as_str(),
outcome = "working",
rtt,
"check outcome",
);
proxy.record_attempt(Some(rtt), None);
proxy.record_probe_latency(rtt);
proxy.add_type(proto, obs.level);
proxy.record_caps(obs.caps);
proxy.record_trust(obs.trust);
return true;
}
Ok(Attempt::Invalid) => {
tracing::info!(
target: "proxybroker::check",
addr = %proxy.addr(),
proto = proto.as_str(),
outcome = "invalid",
"check outcome",
);
proxy.record_attempt(None, Some(ProxyError::BadResponse));
return false;
}
Err(e) => {
let outcome = if e == ProxyError::Timeout {
"timeout"
} else {
"error"
};
tracing::info!(
target: "proxybroker::check",
addr = %proxy.addr(),
proto = proto.as_str(),
outcome,
error = e.as_str(),
"check outcome",
);
proxy.record_attempt(None, Some(e));
if self.retry.retry_on.contains(&e) && i + 1 < self.retry.max_tries {
tokio::time::sleep(self.retry.backoff_for(i)).await;
continue;
}
return false;
}
}
}
false
}
async fn attempt(
&self,
proxy: &Proxy,
proto: Proto,
probe: &Probe<'_>,
target: &Target,
) -> Result<Attempt, ProxyError> {
let tcp = tokio::time::timeout(self.timeout, TcpStream::connect((proxy.host, proxy.port)))
.await
.map_err(|_| ProxyError::Timeout)?
.map_err(|_| ProxyError::ConnFailed)?;
let mut stream = negotiate(proto, tcp, target, self.timeout, None).await?;
if proto == Proto::Connect25 {
return Ok(Attempt::Working(Observation::default()));
}
let (request, marker) = match probe {
Probe::Judged(judge) => {
let (req, marker) = self.build_request(judge, proto);
(req, Some(marker))
}
Probe::Liveness(lt) => (self.build_liveness_request(lt, proto), None),
};
tokio::time::timeout(self.timeout, stream.write_all(&request))
.await
.map_err(|_| ProxyError::Timeout)?
.map_err(|_| ProxyError::Reset)?;
let raw = read_response(&mut stream, self.timeout).await?;
let (head, body) = split_head_body(&raw);
if get_status_code(head, 9, 12) != 200 {
return Err(ProxyError::BadStatus);
}
match probe {
Probe::Liveness(_) => Ok(Attempt::Working(Observation::default())),
Probe::Judged(judge) => {
let content = decompress(head, body);
let marker = marker.expect("judged mode always builds a marker");
let caps = caps_from_content(&content);
let valid = if self.relaxed_validity {
content.contains(&marker) && !get_all_ip(&content).is_empty()
} else {
response_is_valid(&content, &marker)
};
if !valid {
return Ok(Attempt::Invalid);
}
let level = if proto.checks_anon_level() {
Some(self.anonymity_level(&content, judge))
} else {
None
};
let trust = if self.trust_check {
TrustReport::assess(&sent_header_names(), &marker, &content)
} else {
TrustReport::default()
};
Ok(Attempt::Working(Observation { level, caps, trust }))
}
}
}
fn build_liveness_request(&self, lt: &LivenessTarget, proto: Proto) -> Vec<u8> {
let mut hdrs = request_headers(None);
hdrs.insert("Host", lt.host.clone());
hdrs.insert("Connection", "close".to_owned());
let path = if proto.uses_full_path() {
format!("http://{}{}", lt.host, lt.path)
} else {
lt.path.clone()
};
let headers: String = hdrs
.iter()
.map(|(k, v)| format!("{k}: {v}"))
.collect::<Vec<_>>()
.join("\r\n");
format!("GET {path} HTTP/1.1\r\n{headers}\r\n\r\n").into_bytes()
}
fn build_request(&self, judge: &Judge, proto: Proto) -> (Vec<u8>, String) {
let marker = fresh_marker();
let mut hdrs = request_headers(Some(&marker));
hdrs.insert("Host", judge.host.clone());
hdrs.insert("Connection", "close".to_owned());
hdrs.insert("Content-Length", "0".to_owned());
let method = if self.post { "POST" } else { "GET" };
let path = if proto.uses_full_path() {
format!("http://{}{}", judge.host, judge.path)
} else {
judge.path.clone()
};
let headers: String = hdrs
.iter()
.map(|(k, v)| format!("{k}: {v}"))
.collect::<Vec<_>>()
.join("\r\n");
let req = format!("{method} {path} HTTP/1.1\r\n{headers}\r\n\r\n").into_bytes();
(req, marker)
}
fn anonymity_level(&self, content: &str, judge: &Judge) -> AnonLevel {
let lower = content.to_lowercase();
let found = get_all_ip(&lower);
let real_visible = self
.real_ext_ips
.iter()
.any(|ip| found.contains(&ip.to_string()));
let via = lower.matches("via").count() > judge.marks.via
|| lower.matches("proxy").count() > judge.marks.proxy;
if real_visible {
AnonLevel::Transparent
} else if via {
AnonLevel::Anonymous
} else {
AnonLevel::High
}
}
fn types_passed(&self, proxy: &mut Proxy) -> bool {
if self.requested.is_empty() {
return true;
}
let requested: BTreeMap<Proto, Option<Vec<AnonLevel>>> = self
.requested
.iter()
.map(|t| (t.proto, t.levels.clone()))
.collect();
let confirmed: Vec<(Proto, Option<AnonLevel>)> =
proxy.types().iter().map(|(p, l)| (*p, *l)).collect();
let mut to_remove = Vec::new();
for (proto, lvl) in confirmed {
let matches = match requested.get(&proto) {
None | Some(None) => true,
Some(Some(levels)) if levels.is_empty() => true,
Some(Some(levels)) => lvl.is_some_and(|l| levels.contains(&l)),
};
if matches {
if !self.strict {
return true;
}
} else if self.strict {
to_remove.push(proto);
}
}
for p in to_remove {
proxy.remove_type(p);
}
self.strict && !proxy.types().is_empty()
}
}
enum Attempt {
Working(Observation),
Invalid,
}
#[derive(Debug, Default)]
struct Observation {
level: Option<AnonLevel>,
caps: Caps,
trust: TrustReport,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrustSignal {
CanaryMismatch,
InjectedHeader,
CertMismatch,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TrustReport {
pub signals: Vec<TrustSignal>,
}
impl TrustReport {
pub fn trusted(&self) -> bool {
self.signals.is_empty()
}
pub fn assess(sent_header_names: &[&str], canary: &str, content: &str) -> TrustReport {
let mut signals = Vec::new();
if !content.contains(canary) {
signals.push(TrustSignal::CanaryMismatch);
}
const BENIGN: &[&str] = &[
"host",
"connection",
"content-length",
"x-forwarded-for",
"via",
];
let sent: HashSet<String> = sent_header_names
.iter()
.map(|h| h.to_ascii_lowercase())
.collect();
for line in content.lines() {
let Some((name, _)) = line.split_once(": ") else {
continue;
};
let name = name.trim().to_ascii_lowercase();
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') {
continue;
}
if !sent.contains(&name) && !BENIGN.contains(&name.as_str()) {
signals.push(TrustSignal::InjectedHeader);
break;
}
}
TrustReport { signals }
}
}
fn sent_header_names() -> Vec<&'static str> {
request_headers(None)
.keys()
.copied()
.chain(["Host", "Connection", "Content-Length"])
.collect()
}
async fn read_response(
stream: &mut crate::negotiator::Stream,
deadline: Duration,
) -> Result<Vec<u8>, ProxyError> {
let mut buf = Vec::with_capacity(4096);
let n = tokio::time::timeout(deadline, stream.read_to_end(&mut buf))
.await
.map_err(|_| ProxyError::Timeout)?
.map_err(|_| ProxyError::Reset)?;
if n == 0 {
return Err(ProxyError::EmptyRecv);
}
Ok(buf)
}
fn split_head_body(raw: &[u8]) -> (&[u8], &[u8]) {
match raw.windows(4).position(|w| w == b"\r\n\r\n") {
Some(i) => (&raw[..i], &raw[i + 4..]),
None => (raw, &[]),
}
}
fn decompress(head: &[u8], body: &[u8]) -> String {
use flate2::read::{DeflateDecoder, GzDecoder};
use std::io::Read;
let head_lower = String::from_utf8_lossy(head).to_lowercase();
let enc = head_lower
.lines()
.find_map(|l| l.strip_prefix("content-encoding:"))
.map(|v| v.trim());
let decoded = match enc {
Some("gzip") => {
let mut out = String::new();
GzDecoder::new(body)
.read_to_string(&mut out)
.ok()
.map(|_| out)
}
Some("deflate") => {
let mut out = String::new();
DeflateDecoder::new(body)
.read_to_string(&mut out)
.ok()
.map(|_| out)
}
_ => None,
};
decoded.unwrap_or_else(|| String::from_utf8_lossy(body).into_owned())
}
fn dnsbl_query(ip: IpAddr, zone: &str) -> Option<String> {
match ip {
IpAddr::V4(v4) => {
let o = v4.octets();
Some(format!("{}.{}.{}.{}.{}", o[3], o[2], o[1], o[0], zone))
}
IpAddr::V6(_) => None,
}
}
fn caps_from_content(content: &str) -> Caps {
Caps {
cookie_echo: content.contains("cookie=ok"),
referer_echo: content.contains("https://www.google.com/"),
}
}
fn response_is_valid(content: &str, marker: &str) -> bool {
let caps = caps_from_content(content);
content.contains(marker)
&& !get_all_ip(content).is_empty()
&& caps.referer_echo
&& caps.cookie_echo
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn split_head_body_splits_on_blank_line() {
let (h, b) = split_head_body(b"HTTP/1.1 200 OK\r\nX: y\r\n\r\nbody here");
assert_eq!(h, b"HTTP/1.1 200 OK\r\nX: y");
assert_eq!(b, b"body here");
}
#[test]
fn dnsbl_query_reverses_ipv4_octets() {
assert_eq!(
dnsbl_query("1.2.3.4".parse().unwrap(), "zen.spamhaus.org").as_deref(),
Some("4.3.2.1.zen.spamhaus.org")
);
assert_eq!(
dnsbl_query("2001:db8::1".parse().unwrap(), "zen.spamhaus.org"),
None
);
}
#[test]
fn response_valid_requires_all_markers() {
let good = "REMOTE_ADDR=1.2.3.4 UA=PxBroker/x/5555 \
Referer=https://www.google.com/ Cookie=cookie=ok";
assert!(response_is_valid(good, "5555"));
let no_cookie = "1.2.3.4 5555 https://www.google.com/";
assert!(!response_is_valid(no_cookie, "5555"));
assert!(!response_is_valid(good, "9999"));
}
#[test]
fn caps_extracted_from_content() {
let both = "REMOTE_ADDR=1.2.3.4 cookie=ok Referer=https://www.google.com/";
assert_eq!(
caps_from_content(both),
Caps {
cookie_echo: true,
referer_echo: true
}
);
let no_cookie = "REMOTE_ADDR=1.2.3.4 Referer=https://www.google.com/";
assert_eq!(
caps_from_content(no_cookie),
Caps {
cookie_echo: false,
referer_echo: true
}
);
assert_eq!(caps_from_content("nothing here"), Caps::default());
}
#[test]
fn default_policy_retries_only_timeout() {
let p = RetryPolicy::default();
assert_eq!(p.max_tries, 3);
assert_eq!(p.retry_on, HashSet::from([ProxyError::Timeout]));
assert!(!p.retry_on.contains(&ProxyError::Reset));
assert!(p.backoff.is_zero());
}
#[test]
fn retry_policy_backoff_schedule() {
let c = RetryPolicy {
backoff: Duration::from_millis(100),
factor: 1.0,
..Default::default()
};
for i in 0..=2 {
assert_eq!(c.backoff_for(i).as_millis(), 100);
}
let e = RetryPolicy {
backoff: Duration::from_millis(100),
factor: 2.0,
..Default::default()
};
assert_eq!(e.backoff_for(0).as_millis(), 100);
assert_eq!(e.backoff_for(1).as_millis(), 200);
assert_eq!(e.backoff_for(2).as_millis(), 400);
let cap = RetryPolicy {
backoff: Duration::from_millis(100),
factor: 2.0,
max_backoff: Duration::from_millis(250),
..Default::default()
};
assert_eq!(cap.backoff_for(2).as_millis(), 250);
let j = RetryPolicy {
backoff: Duration::from_millis(100),
jitter: 0.5,
..Default::default()
};
for _ in 0..64 {
let ms = j.backoff_for(0).as_secs_f64() * 1000.0;
assert!((50.0..=150.0).contains(&ms), "jitter out of band: {ms}ms");
}
let capped_jitter = RetryPolicy {
backoff: Duration::from_millis(100),
factor: 2.0,
jitter: 0.5,
max_backoff: Duration::from_millis(250),
..Default::default()
};
for i in 0..=4 {
for _ in 0..32 {
assert!(
capped_jitter.backoff_for(i) <= Duration::from_millis(250),
"backoff exceeded the cap at i={i}"
);
}
}
assert_eq!(RetryPolicy::default().backoff_for(0), Duration::ZERO);
}
const SENT: &[&str] = &[
"User-Agent",
"Accept",
"Accept-Encoding",
"Pragma",
"Cache-control",
"Cookie",
"Referer",
"Host",
"Connection",
"Content-Length",
];
#[test]
fn sent_header_names_matches_the_request() {
let mut got = sent_header_names();
got.sort_unstable();
let mut want = SENT.to_vec();
want.sort_unstable();
assert_eq!(got, want);
}
#[test]
fn trust_clean_response_is_trusted() {
let content = "User-Agent: PxBroker/0.1/CANARY42\n\
Cookie: cookie=ok\n\
Referer: https://www.google.com/\n\
Host: judge.example\n\
REMOTE_ADDR = 8.8.8.8\n";
let r = TrustReport::assess(SENT, "CANARY42", content);
assert!(r.trusted(), "unexpected signals: {:?}", r.signals);
}
#[test]
fn trust_injected_header_is_flagged() {
let content = "User-Agent: PxBroker/0.1/CANARY42\n\
Cookie: cookie=ok\n\
X-Ad-Inject: buy now\n";
let r = TrustReport::assess(SENT, "CANARY42", content);
assert_eq!(r.signals, vec![TrustSignal::InjectedHeader]);
}
#[test]
fn trust_canary_mutation_is_flagged() {
let content = "User-Agent: PxBroker/0.1/MUTATED\n\
Cookie: cookie=ok\n\
Host: judge.example\n";
let r = TrustReport::assess(SENT, "CANARY42", content);
assert_eq!(r.signals, vec![TrustSignal::CanaryMismatch]);
}
#[test]
fn trust_forwarded_via_headers_are_not_injection() {
let content = "User-Agent: PxBroker/0.1/CANARY42\n\
Via: 1.1 someproxy\n\
X-Forwarded-For: 8.8.8.8\n\
Host: judge.example\n";
let r = TrustReport::assess(SENT, "CANARY42", content);
assert!(r.trusted(), "unexpected signals: {:?}", r.signals);
}
#[test]
fn trust_url_value_on_its_own_is_not_a_header() {
let content = "User-Agent: PxBroker/0.1/CANARY42\nhttps://www.google.com/\n";
let r = TrustReport::assess(SENT, "CANARY42", content);
assert!(r.trusted(), "unexpected signals: {:?}", r.signals);
}
}