use clap::{Parser, Subcommand, ValueEnum};
use futures_util::StreamExt;
use proxybroker::broker::{Broker, FindQuery, GrabQuery};
use proxybroker::types::{AnonLevel, ParseProtoError, Proto, TypeSpec};
use proxybroker::{Proxy, ProxyError, RetryPolicy};
use std::collections::HashSet;
use std::io::Write;
use std::path::PathBuf;
use std::time::Duration;
use tokio::io::AsyncWriteExt;
fn parse_proto(s: &str) -> Result<Proto, ParseProtoError> {
s.parse()
}
fn parse_lvl(s: &str) -> Result<AnonLevel, ParseProtoError> {
s.parse()
}
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
"\nIP Geolocation by DB-IP (https://db-ip.com), licensed CC BY 4.0"
);
#[derive(Parser)]
#[command(
name = "proxybroker",
version = VERSION,
about = "Find, check, and serve public HTTP(S) and SOCKS4/5 proxies.",
long_about = "Find, check, and serve public HTTP(S) and SOCKS4/5 proxies.\n\n\
A Rust rewrite of proxybroker2. Geo data: DB-IP Country Lite (CC BY 4.0)."
)]
struct Cli {
#[arg(long, global = true, default_value = "warn")]
log: String,
#[arg(long, global = true, value_enum, default_value_t = LogFormat::Text)]
log_format: LogFormat,
#[arg(long, global = true, value_name = "PATH")]
geo_db: Option<PathBuf>,
#[arg(long, global = true, value_name = "PATH")]
asn_db: Option<PathBuf>,
#[arg(long, global = true, value_name = "DIR")]
provider_dir: Vec<PathBuf>,
#[arg(long, global = true)]
providers_only: bool,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
Grab(GrabArgs),
Find(FindArgs),
Check(CheckArgs),
#[cfg(feature = "server")]
Serve(ServeArgs),
#[cfg(feature = "mcp")]
Mcp(McpArgs),
#[cfg(feature = "tui")]
Top(TopArgs),
}
#[cfg(feature = "server")]
#[derive(Clone, Copy, Default, ValueEnum)]
enum SelectStrategy {
#[default]
Best,
RoundRobin,
Random,
Sticky,
}
#[cfg(feature = "server")]
impl SelectStrategy {
fn to_server(self) -> proxybroker::server::Strategy {
use proxybroker::server::Strategy;
match self {
SelectStrategy::Best => Strategy::Best,
SelectStrategy::RoundRobin => Strategy::RoundRobin,
SelectStrategy::Random => Strategy::Random,
SelectStrategy::Sticky => Strategy::Sticky,
}
}
}
#[cfg(feature = "server")]
#[derive(clap::Args, Default)]
struct ServeArgs {
#[arg(long, default_value = "127.0.0.1:8888")]
host: String,
#[arg(long, num_args = 1.., required_unless_present = "load", value_name = "TYPE", value_parser = parse_proto)]
types: Vec<Proto>,
#[arg(long, value_name = "PATH", conflicts_with = "types")]
load: Option<PathBuf>,
#[arg(long, num_args = 1.., value_name = "LVL", value_parser = parse_lvl)]
lvl: Vec<AnonLevel>,
#[arg(long, num_args = 1.., value_name = "ZONE")]
dnsbl: Vec<String>,
#[arg(long)]
post: bool,
#[arg(long)]
strict: bool,
#[arg(long, value_enum, default_value_t = SelectStrategy::Best)]
strategy: SelectStrategy,
#[arg(long, value_name = "HEADER")]
sticky_header: Option<String>,
#[arg(long, default_value_t = 100)]
limit: usize,
#[arg(long, visible_alias = "only-cc", num_args = 1.., value_delimiter = ',', value_name = "CC")]
countries: Vec<String>,
#[arg(long, default_value_t = 8)]
timeout: u64,
#[arg(long, default_value_t = 0.5)]
max_error_rate: f64,
#[arg(long, default_value_t = 8.0)]
max_resp_time: f64,
#[arg(long, default_value_t = 30)]
fail_timeout: u64,
#[arg(long)]
prefer_connect: bool,
#[arg(long, num_args = 1.., value_name = "CODE")]
http_allowed_codes: Vec<u16>,
#[arg(long, default_value_t = 0)]
min_queue: usize,
#[arg(long, default_value_t = 1024)]
backlog: u32,
#[arg(long, default_value_t = 1024)]
max_clients: usize,
#[arg(long, value_name = "USER:PASS")]
auth: Option<String>,
#[arg(long, default_value_t = 3)]
max_tries: usize,
#[cfg(feature = "metrics")]
#[arg(long, value_name = "ADDR")]
metrics: Option<std::net::SocketAddr>,
#[arg(long, value_name = "PATH_OR_URL")]
state: Option<String>,
#[arg(long)]
recheck: bool,
#[arg(long, default_value_t = 5.0)]
recheck_rate: f64,
#[arg(long, default_value_t = 60)]
recheck_min: u64,
#[arg(long, default_value_t = 3600)]
recheck_max: u64,
#[arg(long, default_value_t = 21600)]
decay_halflife: u64,
#[arg(long)]
watch: bool,
}
#[derive(clap::Args)]
struct GrabArgs {
#[arg(long, default_value_t = 0)]
limit: usize,
#[arg(long, visible_alias = "only-cc", num_args = 1.., value_delimiter = ',', value_name = "CC")]
countries: Vec<String>,
#[arg(long, value_enum, default_value_t = Format::Default)]
format: Format,
#[arg(long, value_name = "TEMPLATE")]
output_format: Option<String>,
#[arg(long, value_name = "PATH")]
outfile: Option<PathBuf>,
}
#[derive(clap::Args)]
struct FindArgs {
#[arg(long, num_args = 1.., required = true, value_name = "TYPE", value_parser = parse_proto)]
types: Vec<Proto>,
#[arg(long, num_args = 1.., value_name = "LVL", value_parser = parse_lvl)]
lvl: Vec<AnonLevel>,
#[arg(long, default_value_t = 0)]
limit: usize,
#[arg(long, visible_alias = "only-cc", num_args = 1.., value_delimiter = ',', value_name = "CC")]
countries: Vec<String>,
#[arg(long, num_args = 1.., value_name = "URL")]
judges: Vec<String>,
#[arg(long, num_args = 1.., value_name = "ZONE")]
dnsbl: Vec<String>,
#[arg(long, default_value_t = 8)]
timeout: u64,
#[arg(long, default_value_t = 200)]
max_conn: usize,
#[arg(long, default_value_t = 3)]
max_tries: usize,
#[arg(long)]
post: bool,
#[arg(long)]
strict: bool,
#[arg(long, value_name = "URL")]
liveness_url: Option<String>,
#[arg(long, value_enum, default_value_t = RetryOn::Timeout)]
retry_on: RetryOn,
#[arg(long, default_value_t = 0)]
backoff_ms: u64,
#[arg(long)]
relaxed_validity: bool,
#[arg(long)]
require_cookie: bool,
#[arg(long)]
require_referer: bool,
#[arg(long)]
require_connect25: bool,
#[arg(long)]
trust_check: bool,
#[arg(long)]
require_trusted: bool,
#[arg(long)]
show_stats: bool,
#[arg(long, value_enum, default_value_t = StatsFormat::Text)]
stats_format: StatsFormat,
#[arg(long, value_enum, default_value_t = Format::Default)]
format: Format,
#[arg(long, value_name = "TEMPLATE")]
output_format: Option<String>,
#[arg(long, value_name = "PATH")]
outfile: Option<PathBuf>,
#[arg(long, value_name = "PATH")]
save: Option<PathBuf>,
#[arg(long)]
progress: bool,
#[arg(long, value_name = "PATH_OR_URL")]
state: Option<String>,
}
#[derive(clap::Args)]
struct CheckArgs {
#[arg(long, num_args = 1.., required_unless_present = "load", value_name = "TYPE", value_parser = parse_proto)]
types: Vec<Proto>,
#[arg(long, value_name = "PATH")]
infile: Option<PathBuf>,
#[arg(long, value_name = "PATH", conflicts_with_all = ["infile", "types"])]
load: Option<PathBuf>,
#[arg(long, num_args = 1.., value_name = "LVL", value_parser = parse_lvl)]
lvl: Vec<AnonLevel>,
#[arg(long, default_value_t = 0)]
limit: usize,
#[arg(long, visible_alias = "only-cc", num_args = 1.., value_delimiter = ',', value_name = "CC")]
countries: Vec<String>,
#[arg(long, num_args = 1.., value_name = "URL")]
judges: Vec<String>,
#[arg(long, num_args = 1.., value_name = "ZONE")]
dnsbl: Vec<String>,
#[arg(long, default_value_t = 8)]
timeout: u64,
#[arg(long, default_value_t = 200)]
max_conn: usize,
#[arg(long, default_value_t = 3)]
max_tries: usize,
#[arg(long)]
post: bool,
#[arg(long)]
strict: bool,
#[arg(long)]
show_stats: bool,
#[arg(long, value_enum, default_value_t = StatsFormat::Text)]
stats_format: StatsFormat,
#[arg(long, value_enum, default_value_t = Format::Default)]
format: Format,
#[arg(long, value_name = "TEMPLATE")]
output_format: Option<String>,
#[arg(long, value_name = "PATH")]
outfile: Option<PathBuf>,
#[arg(long, value_name = "PATH")]
save: Option<PathBuf>,
}
#[derive(Clone, Copy, Default, ValueEnum)]
enum LogFormat {
#[default]
Text,
Json,
}
#[derive(Clone, Copy, Default, ValueEnum)]
enum RetryOn {
#[default]
Timeout,
Transient,
All,
}
fn retry_policy(max_tries: usize, on: RetryOn, backoff_ms: u64) -> RetryPolicy {
let mut p = match on {
RetryOn::Timeout => RetryPolicy::tries(max_tries),
RetryOn::Transient => RetryPolicy::transient(max_tries),
RetryOn::All => RetryPolicy {
max_tries,
retry_on: HashSet::from([
ProxyError::Timeout,
ProxyError::Reset,
ProxyError::ConnFailed,
ProxyError::EmptyRecv,
ProxyError::BadStatus,
]),
..Default::default()
},
};
p.backoff = Duration::from_millis(backoff_ms);
p
}
#[derive(Clone, Copy, Default, ValueEnum)]
enum StatsFormat {
#[default]
Text,
Json,
}
#[derive(Clone, Copy, ValueEnum)]
enum Format {
Default,
Txt,
Json,
JsonArray,
Url,
Csv,
}
struct Emitter<'a> {
format: Format,
template: Option<&'a str>,
started: bool,
}
impl<'a> Emitter<'a> {
fn new(format: Format, template: Option<&'a str>) -> Self {
Emitter {
format,
template,
started: false,
}
}
fn prefix(&self) -> Option<String> {
if self.template.is_some() {
return None;
}
match self.format {
Format::JsonArray => Some("[".into()),
Format::Csv => Some("host,port,protocols,anon,country,resp_time,error_rate\n".into()),
Format::Default | Format::Txt | Format::Json | Format::Url => None,
}
}
fn item(&mut self, proxy: &Proxy) -> String {
if let Some(tmpl) = self.template {
return format!("{}\n", render_template(tmpl, proxy));
}
match self.format {
Format::Default | Format::Txt => format!("{}\n", proxy.addr()),
Format::Json => format!("{}\n", serde_json::to_string(proxy).unwrap()),
Format::Url => format!("{}://{}\n", scheme_str(proxy), proxy.addr()),
Format::Csv => format!("{}\n", csv_row(proxy)),
Format::JsonArray => {
let sep = if self.started { "," } else { "" };
self.started = true;
format!("{sep}{}", serde_json::to_string(proxy).unwrap())
}
}
}
fn suffix(&self) -> Option<String> {
if self.template.is_some() {
return None;
}
match self.format {
Format::JsonArray => Some("]\n".into()),
Format::Default | Format::Txt | Format::Json | Format::Url | Format::Csv => None,
}
}
}
fn scheme_str(p: &Proxy) -> &'static str {
let protos = p.types();
if protos.contains_key(&Proto::Socks5) {
"socks5"
} else if protos.contains_key(&Proto::Socks4) {
"socks4"
} else {
"http"
}
}
fn proto_list(p: &Proxy) -> String {
p.types()
.keys()
.map(|proto| proto.as_str())
.collect::<Vec<_>>()
.join("|")
}
fn anon_str(p: &Proxy) -> &'static str {
p.types()
.get(&Proto::Http)
.and_then(|l| *l)
.map(AnonLevel::as_str)
.unwrap_or("")
}
fn country_str(p: &Proxy) -> &str {
p.geo.as_ref().map(|c| c.code.as_str()).unwrap_or("")
}
fn asn_str(p: &Proxy) -> String {
p.asn
.as_ref()
.map(|a| a.number.to_string())
.unwrap_or_default()
}
fn asn_org_str(p: &Proxy) -> &str {
p.asn.as_ref().and_then(|a| a.org.as_deref()).unwrap_or("")
}
fn render_template(tmpl: &str, p: &Proxy) -> String {
tmpl.replace("{{proxy}}", &p.addr())
.replace("{{host}}", &p.host.to_string())
.replace("{{port}}", &p.port.to_string())
.replace("{{scheme}}", scheme_str(p))
.replace("{{protocols}}", &proto_list(p))
.replace("{{anon}}", anon_str(p))
.replace("{{country}}", country_str(p))
.replace("{{asn}}", &asn_str(p))
.replace("{{asn_org}}", asn_org_str(p))
.replace("{{duration}}", &p.avg_resp_time().to_string())
.replace("{{error_rate}}", &p.error_rate().to_string())
}
fn csv_row(p: &Proxy) -> String {
format!(
"{},{},{},{},{},{},{}",
p.host,
p.port,
proto_list(p),
anon_str(p),
country_str(p),
p.avg_resp_time(),
p.error_rate()
)
}
#[tokio::main]
async fn main() -> std::process::ExitCode {
let cli = Cli::parse();
init_tracing(&cli.log, matches!(cli.log_format, LogFormat::Json));
match run(cli).await {
Ok(()) => std::process::ExitCode::SUCCESS,
Err(e) => {
eprintln!("error: {e}");
std::process::ExitCode::FAILURE
}
}
}
async fn run(cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
let mut builder = Broker::builder();
if !cli.provider_dir.is_empty() || cli.providers_only {
let mut providers = if cli.providers_only {
Vec::new()
} else {
proxybroker::provider::bundled_registry()
};
for dir in &cli.provider_dir {
providers.extend(proxybroker::load_provider_dir(dir));
}
if providers.is_empty() {
return Err(
"no providers: --providers-only with no valid --provider-dir configs".into(),
);
}
builder = builder.providers(providers);
}
#[cfg(feature = "geo")]
{
use proxybroker::geo::GeoDb;
let db = match &cli.geo_db {
Some(path) => Some(GeoDb::open(path)?),
None => GeoDb::bundled().ok(),
};
if let Some(db) = db {
builder = builder.geo(db);
}
if let Some(path) = &cli.asn_db {
builder = builder.asn_db(GeoDb::open(path)?);
}
}
let broker = builder.build();
match cli.command {
Command::Grab(args) => grab(broker, args).await,
Command::Find(args) => find(broker, args).await,
Command::Check(args) => check(broker, args).await,
#[cfg(feature = "server")]
Command::Serve(args) => serve_cmd(broker, args).await,
#[cfg(feature = "mcp")]
Command::Mcp(args) => mcp_cmd(broker, args).await,
#[cfg(feature = "tui")]
Command::Top(args) => top_cmd(broker, args).await,
}
}
#[cfg(feature = "server")]
async fn serve_cmd(broker: Broker, args: ServeArgs) -> Result<(), Box<dyn std::error::Error>> {
use proxybroker::resolver::Resolver;
use proxybroker::server::{serve, Pool, PoolConfig};
use std::sync::Arc;
let addr: std::net::SocketAddr = args.host.parse()?;
if args.auth.is_none() && !addr.ip().is_loopback() {
eprintln!(
"warning: serving on {} without --auth — anyone who can reach this address can relay \
traffic through the pool; pass --auth USER:PASS or bind to 127.0.0.1",
addr
);
}
let (broker, history) = open_state(broker, args.state.as_deref())?;
let pool_config = PoolConfig {
max_tries: args.max_tries,
max_clients: args.max_clients,
max_error_rate: args.max_error_rate,
max_resp_time: args.max_resp_time,
countries: (!args.countries.is_empty())
.then(|| args.countries.iter().map(|c| c.to_uppercase()).collect()),
strategy: args.strategy.to_server(),
sticky_header: args.sticky_header.clone(),
fail_timeout: Duration::from_secs(args.fail_timeout),
prefer_connect: args.prefer_connect,
http_allowed_codes: (!args.http_allowed_codes.is_empty())
.then(|| args.http_allowed_codes.clone()),
..Default::default()
};
let pool = if let Some(path) = &args.load {
let loaded = proxybroker::read_ndjson(std::io::BufReader::new(std::fs::File::open(path)?))?;
eprintln!("loaded {} proxies from {}", loaded.len(), path.display());
Pool::from_proxies(union_dedup(history, loaded), pool_config)
} else {
let stream = broker.find(serve_query(&args)).await?;
Pool::spawn(
futures_util::stream::iter(history).chain(stream),
pool_config,
)
};
let resolver = Arc::new(Resolver::new(Duration::from_secs(args.timeout))?);
#[cfg(feature = "metrics")]
let _metrics = match args.metrics {
Some(maddr) => {
let h = proxybroker::serve_metrics(maddr, pool.clone()).await?;
eprintln!("metrics on {}", h.local_addr());
Some(h)
}
None => None,
};
#[cfg(feature = "persist")]
let _rechecker = if args.recheck {
let store = recheck_store(args.state.as_deref())?;
let checker = broker.build_checker(&serve_query(&args)).await?;
let cfg = proxybroker::RecheckConfig {
min_interval: Duration::from_secs(args.recheck_min),
max_interval: Duration::from_secs(args.recheck_max),
rate_per_sec: args.recheck_rate,
decay_halflife: Duration::from_secs(args.decay_halflife),
};
eprintln!(
"adaptive re-checking enabled (rate {}/s)",
args.recheck_rate
);
Some(proxybroker::spawn_rechecker(
pool.clone(),
checker,
store,
cfg,
))
} else {
None
};
#[cfg(feature = "watch")]
let _watcher = if args.watch {
match args.load.as_ref() {
Some(path) => {
eprintln!("live-reloading {} on change", path.display());
Some(proxybroker::spawn_watch(pool.clone(), path.clone())?)
}
None => {
eprintln!("--watch requires --load; live-reload disabled");
None
}
}
} else {
None
};
#[cfg(not(feature = "persist"))]
if args.recheck {
eprintln!("--recheck requires a persistence feature; rebuild with --features persist (or store-sqlite/store-redis)");
}
#[cfg(not(feature = "watch"))]
if args.watch {
eprintln!("--watch requires the watch feature; rebuild with --features watch");
}
let handle = serve(
addr,
pool,
resolver,
Duration::from_secs(args.timeout),
args.min_queue,
args.backlog,
args.auth,
)
.await?;
eprintln!(
"proxybroker serving on {} — Ctrl-C to stop",
handle.local_addr()
);
tokio::signal::ctrl_c().await?;
handle.shutdown();
eprintln!("shutting down");
Ok(())
}
#[cfg(feature = "mcp")]
#[derive(clap::Args)]
struct McpArgs {
#[arg(long, num_args = 1.., required = true, value_name = "TYPE", value_parser = parse_proto)]
types: Vec<Proto>,
#[arg(long, default_value_t = 100)]
limit: usize,
#[arg(long, visible_alias = "only-cc", num_args = 1.., value_delimiter = ',', value_name = "CC")]
countries: Vec<String>,
#[arg(long, default_value_t = 8)]
timeout: u64,
}
#[cfg(feature = "mcp")]
async fn mcp_cmd(broker: Broker, args: McpArgs) -> Result<(), Box<dyn std::error::Error>> {
use proxybroker::server::{Pool, PoolConfig};
let pool_config = PoolConfig {
countries: (!args.countries.is_empty())
.then(|| args.countries.iter().map(|c| c.to_uppercase()).collect()),
..Default::default()
};
let mut b = FindQuery::builder()
.types(types_from(args.types.clone(), Vec::new()))
.limit(args.limit.max(1))
.timeout(Duration::from_secs(args.timeout));
if !args.countries.is_empty() {
b = b.countries(args.countries.clone());
}
let stream = broker.find(b.build()).await?;
let pool = Pool::spawn(stream, pool_config);
eprintln!(
"mcp: filling pool (limit {}); serving get_proxy/pool_status/report_dead over stdio",
args.limit
);
proxybroker::mcp::serve_stdio(pool).await
}
#[cfg(feature = "tui")]
#[derive(clap::Args)]
struct TopArgs {
#[arg(long, num_args = 1.., required = true, value_name = "TYPE", value_parser = parse_proto)]
types: Vec<Proto>,
#[arg(long, default_value_t = 100)]
limit: usize,
#[arg(long, visible_alias = "only-cc", num_args = 1.., value_delimiter = ',', value_name = "CC")]
countries: Vec<String>,
#[arg(long, default_value_t = 8)]
timeout: u64,
#[arg(long, default_value_t = 2)]
refresh: u64,
#[arg(long, value_name = "PATH_OR_URL")]
state: Option<String>,
}
#[cfg(feature = "tui")]
async fn top_cmd(broker: Broker, args: TopArgs) -> Result<(), Box<dyn std::error::Error>> {
use proxybroker::server::{Pool, PoolConfig};
let (broker, history) = open_state(broker, args.state.as_deref())?;
let pool_config = PoolConfig {
countries: (!args.countries.is_empty())
.then(|| args.countries.iter().map(|c| c.to_uppercase()).collect()),
..Default::default()
};
let mut b = FindQuery::builder()
.types(types_from(args.types.clone(), Vec::new()))
.limit(args.limit.max(1))
.timeout(Duration::from_secs(args.timeout));
if !args.countries.is_empty() {
b = b.countries(args.countries.clone());
}
let stream = broker.find(b.build()).await?;
let pool = Pool::spawn(
futures_util::stream::iter(history).chain(stream),
pool_config,
);
proxybroker::tui::run_top(pool, Duration::from_secs(args.refresh)).await?;
Ok(())
}
#[cfg(feature = "server")]
fn serve_query(args: &ServeArgs) -> FindQuery {
let mut b = FindQuery::builder()
.types(types_from(args.types.clone(), args.lvl.clone()))
.limit(args.limit.max(1))
.dnsbl(args.dnsbl.clone())
.timeout(Duration::from_secs(args.timeout))
.post(args.post)
.strict(args.strict);
if !args.countries.is_empty() {
b = b.countries(args.countries.clone());
}
b.build()
}
async fn grab(broker: Broker, args: GrabArgs) -> Result<(), Box<dyn std::error::Error>> {
let query = GrabQuery {
countries: (!args.countries.is_empty()).then_some(args.countries),
limit: (args.limit > 0).then_some(args.limit),
};
let mut stream = broker.grab(query);
write_stream(
&mut stream,
args.format,
args.output_format.as_deref(),
args.outfile.as_deref(),
None, None, )
.await
}
fn types_from(protos: Vec<Proto>, lvl: Vec<AnonLevel>) -> Vec<TypeSpec> {
let levels = (!lvl.is_empty()).then_some(lvl);
protos
.into_iter()
.map(|proto| TypeSpec {
proto,
levels: levels.clone(),
})
.collect()
}
#[cfg(any(feature = "store-sqlite", feature = "store-redis"))]
fn select_store(
spec: &str,
) -> Result<std::sync::Arc<dyn proxybroker::Store>, Box<dyn std::error::Error>> {
if spec.starts_with("redis://") || spec.starts_with("rediss://") {
#[cfg(feature = "store-redis")]
return Ok(std::sync::Arc::new(proxybroker::RedisStore::open(spec)?));
#[cfg(not(feature = "store-redis"))]
return Err(format!("--state {spec}: a redis:// URL needs --features store-redis").into());
}
#[cfg(feature = "store-sqlite")]
return Ok(std::sync::Arc::new(proxybroker::SqliteStore::open(spec)?));
#[cfg(not(feature = "store-sqlite"))]
Err(format!("--state {spec}: a file path needs --features store-sqlite").into())
}
#[cfg(all(feature = "server", feature = "persist"))]
fn recheck_store(
state: Option<&str>,
) -> Result<std::sync::Arc<dyn proxybroker::Store>, Box<dyn std::error::Error>> {
#[cfg(any(feature = "store-sqlite", feature = "store-redis"))]
if let Some(spec) = state {
return select_store(spec); }
let _ = state; eprintln!("re-checking into memory only (no durable --state); scores reset on restart");
Ok(std::sync::Arc::new(proxybroker::MemoryStore::new()))
}
#[cfg(any(feature = "store-sqlite", feature = "store-redis"))]
fn open_state(
broker: Broker,
spec: Option<&str>,
) -> Result<(Broker, Vec<Proxy>), Box<dyn std::error::Error>> {
match spec {
Some(s) => {
let store = select_store(s)?; let history = store.load()?;
let writer = store.clone();
let obs: proxybroker::broker::CheckObserver = std::sync::Arc::new(move |px: &Proxy| {
if let Err(e) = writer.upsert(px) {
tracing::warn!(error = %e, "state upsert failed");
}
});
Ok((broker.with_observer(Some(obs)), history))
}
None => Ok((broker, Vec::new())),
}
}
#[cfg(not(any(feature = "store-sqlite", feature = "store-redis")))]
fn open_state(
broker: Broker,
spec: Option<&str>,
) -> Result<(Broker, Vec<Proxy>), Box<dyn std::error::Error>> {
if spec.is_some() {
eprintln!("--state requires a store backend; rebuild with --features store-sqlite (or store-redis)");
}
Ok((broker, Vec::new()))
}
#[cfg(feature = "server")]
fn union_dedup(primary: Vec<Proxy>, secondary: Vec<Proxy>) -> Vec<Proxy> {
let seen: std::collections::HashSet<_> = primary.iter().map(|p| (p.host, p.port)).collect();
primary
.into_iter()
.chain(
secondary
.into_iter()
.filter(|p| !seen.contains(&(p.host, p.port))),
)
.collect()
}
async fn find(broker: Broker, args: FindArgs) -> Result<(), Box<dyn std::error::Error>> {
let (broker, _history) = open_state(broker, args.state.as_deref())?;
let mut builder = FindQuery::builder()
.types(types_from(args.types, args.lvl))
.limit(args.limit)
.judges(args.judges)
.dnsbl(args.dnsbl)
.timeout(Duration::from_secs(args.timeout))
.max_conn(args.max_conn)
.retry(retry_policy(args.max_tries, args.retry_on, args.backoff_ms))
.post(args.post)
.strict(args.strict)
.liveness_url(args.liveness_url);
if !args.countries.is_empty() {
builder = builder.countries(args.countries);
}
let mut query = builder.build();
query.relaxed_validity = args.relaxed_validity;
query.require_cookie = args.require_cookie;
query.require_referer = args.require_referer;
query.require_connect25 = args.require_connect25;
query.trust_check = args.trust_check;
query.require_trusted = args.require_trusted;
let progress = make_progress(args.progress);
let mut stream = broker.find(query).await?;
write_stream(
&mut stream,
args.format,
args.output_format.as_deref(),
args.outfile.as_deref(),
args.save.as_deref(),
progress.as_ref(),
)
.await?;
if args.show_stats {
if let Some(s) = stream.stats() {
match args.stats_format {
StatsFormat::Text => eprint!("\n{s}"),
StatsFormat::Json => eprintln!("{}", serde_json::to_string(&s)?),
}
}
}
Ok(())
}
async fn check(broker: Broker, args: CheckArgs) -> Result<(), Box<dyn std::error::Error>> {
use tokio::io::AsyncReadExt;
if let Some(path) = &args.load {
let loaded = proxybroker::read_ndjson(std::io::BufReader::new(std::fs::File::open(path)?))?;
let stats = args
.show_stats
.then(|| proxybroker::Stats::from_proxies(&loaded));
let mut stream = futures_util::stream::iter(loaded);
write_stream(
&mut stream,
args.format,
args.output_format.as_deref(),
args.outfile.as_deref(),
args.save.as_deref(),
None,
)
.await?;
if let Some(s) = stats {
match args.stats_format {
StatsFormat::Text => eprint!("\n{s}"),
StatsFormat::Json => eprintln!("{}", serde_json::to_string(&s)?),
}
}
return Ok(());
}
let text = match &args.infile {
Some(path) => tokio::fs::read_to_string(path).await?,
None => {
let mut buf = String::new();
tokio::io::stdin().read_to_string(&mut buf).await?;
buf
}
};
let proxies = proxybroker::parse_proxy_lines(&text);
if proxies.is_empty() {
eprintln!("no proxy addresses parsed from input");
}
let query = FindQuery {
types: types_from(args.types, args.lvl),
countries: (!args.countries.is_empty()).then_some(args.countries),
limit: (args.limit > 0).then_some(args.limit),
judges: args.judges,
dnsbl: args.dnsbl,
timeout: Duration::from_secs(args.timeout),
max_conn: args.max_conn,
retry: RetryPolicy::tries(args.max_tries),
post: args.post,
strict: args.strict,
liveness_url: None, relaxed_validity: false, require_cookie: false,
require_referer: false,
require_connect25: false,
trust_check: false,
require_trusted: false,
};
let mut stream = broker
.check(futures_util::stream::iter(proxies), query)
.await?;
write_stream(
&mut stream,
args.format,
args.output_format.as_deref(),
args.outfile.as_deref(),
args.save.as_deref(),
None,
)
.await?;
if args.show_stats {
if let Some(s) = stream.stats() {
match args.stats_format {
StatsFormat::Text => eprint!("\n{s}"),
StatsFormat::Json => eprintln!("{}", serde_json::to_string(&s)?),
}
}
}
Ok(())
}
#[cfg(feature = "progress")]
fn render_progress(s: &proxybroker::Stats) -> String {
format!(
"checked {} · working {} · avg {:.2}s",
s.total, s.working, s.avg_resp_time
)
}
struct Progress {
#[cfg(feature = "progress")]
bar: indicatif::ProgressBar,
}
impl Progress {
fn inc(&self) {
#[cfg(feature = "progress")]
self.bar.inc(1);
}
fn tick(&self, _stats: &proxybroker::Stats) {
#[cfg(feature = "progress")]
self.bar.set_message(render_progress(_stats));
}
fn finish(&self) {
#[cfg(feature = "progress")]
self.bar.finish_and_clear();
}
}
#[cfg(feature = "progress")]
fn make_progress(on: bool) -> Option<Progress> {
on.then(|| {
let bar = indicatif::ProgressBar::new_spinner();
bar.set_draw_target(indicatif::ProgressDrawTarget::stderr());
Progress { bar }
})
}
#[cfg(not(feature = "progress"))]
fn make_progress(_on: bool) -> Option<Progress> {
None
}
trait DrainStats {
fn drain_stats(&self) -> Option<proxybroker::Stats> {
None
}
}
impl DrainStats for proxybroker::ProxyStream {
fn drain_stats(&self) -> Option<proxybroker::Stats> {
self.stats()
}
}
impl<I: Iterator<Item = Proxy>> DrainStats for futures_util::stream::Iter<I> {}
async fn write_stream<S>(
stream: &mut S,
format: Format,
template: Option<&str>,
outfile: Option<&std::path::Path>,
save: Option<&std::path::Path>,
progress: Option<&Progress>,
) -> Result<(), Box<dyn std::error::Error>>
where
S: futures_util::Stream<Item = Proxy> + Unpin + DrainStats,
{
let mut save_file = match save {
Some(path) => Some(std::fs::File::create(path)?),
None => None,
};
let mut save_line = |proxy: &Proxy| -> std::io::Result<()> {
if let Some(f) = save_file.as_mut() {
proxybroker::write_ndjson(f, std::slice::from_ref(proxy))?;
}
Ok(())
};
let mut emitter = Emitter::new(format, template);
if let Some(path) = outfile {
let mut file = tokio::fs::File::create(path).await?;
if let Some(p) = emitter.prefix() {
file.write_all(p.as_bytes()).await?;
}
let mut count = 0u64;
match progress {
None => {
while let Some(proxy) = stream.next().await {
file.write_all(emitter.item(&proxy).as_bytes()).await?;
save_line(&proxy)?;
count += 1;
}
}
Some(bar) => {
let mut tick = tokio::time::interval(Duration::from_millis(120));
loop {
tokio::select! {
maybe = stream.next() => match maybe {
Some(proxy) => {
file.write_all(emitter.item(&proxy).as_bytes()).await?;
save_line(&proxy)?;
count += 1;
bar.inc();
}
None => break,
},
_ = tick.tick() => {
if let Some(s) = stream.drain_stats() { bar.tick(&s); }
}
}
}
bar.finish();
}
}
if let Some(s) = emitter.suffix() {
file.write_all(s.as_bytes()).await?;
}
file.flush().await?;
eprintln!("wrote {count} proxies to {}", path.display());
} else {
let stdout = std::io::stdout();
let mut lock = stdout.lock();
if let Some(p) = emitter.prefix() {
write!(lock, "{p}")?;
}
match progress {
None => {
while let Some(proxy) = stream.next().await {
write!(lock, "{}", emitter.item(&proxy))?;
save_line(&proxy)?;
}
}
Some(bar) => {
let mut tick = tokio::time::interval(Duration::from_millis(120));
loop {
tokio::select! {
maybe = stream.next() => match maybe {
Some(proxy) => {
write!(lock, "{}", emitter.item(&proxy))?;
save_line(&proxy)?;
bar.inc();
}
None => break,
},
_ = tick.tick() => {
if let Some(s) = stream.drain_stats() { bar.tick(&s); }
}
}
}
bar.finish();
}
}
if let Some(s) = emitter.suffix() {
write!(lock, "{s}")?;
}
}
Ok(())
}
fn init_tracing(level: &str, json: bool) {
use tracing_subscriber::{fmt, EnvFilter};
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new(format!("proxybroker={level}")));
let builder = fmt().with_env_filter(filter).with_writer(std::io::stderr);
if json {
let _ = builder.json().try_init();
} else {
let _ = builder.try_init();
}
}
#[cfg(all(test, feature = "server"))]
mod tests {
use super::*;
#[cfg(feature = "persist")]
#[test]
fn recheck_store_without_state_is_in_memory() {
use std::collections::BTreeMap;
let mut types = BTreeMap::new();
types.insert(Proto::Http, None);
let px = Proxy::restored("1.2.3.4".parse().unwrap(), 8080, types, 1, 0, 100.0);
let first = recheck_store(None).unwrap();
first.upsert(&px).unwrap();
assert_eq!(first.load().unwrap().len(), 1);
let second = recheck_store(None).unwrap();
assert!(
second.load().unwrap().is_empty(),
"no --state must not persist across store handles"
);
}
#[cfg(feature = "progress")]
#[test]
fn render_progress_formats_counts() {
let s = proxybroker::Stats {
total: 128,
working: 34,
avg_resp_time: 0.72,
..Default::default()
};
let out = render_progress(&s);
assert!(out.contains("checked 128"), "{out}");
assert!(out.contains("working 34"), "{out}");
assert!(out.contains("0.72s"), "{out}");
}
#[test]
fn serve_query_threads_lvl_and_strict() {
let args = ServeArgs {
types: vec![Proto::Http],
lvl: vec![AnonLevel::High],
strict: true,
post: true,
dnsbl: vec!["zen.spamhaus.org".into()],
..Default::default()
};
let q = serve_query(&args);
assert_eq!(q.types[0].levels, Some(vec![AnonLevel::High]));
assert!(q.strict);
assert!(q.post);
assert_eq!(q.dnsbl, vec!["zen.spamhaus.org".to_string()]);
}
fn serve_countries(argv: &[&str]) -> Vec<String> {
match Cli::try_parse_from(argv).unwrap().command {
Command::Serve(a) => a.countries,
_ => panic!("expected serve"),
}
}
#[test]
fn only_cc_alias_splits_on_comma() {
let comma = serve_countries(&[
"proxybroker",
"serve",
"--types",
"HTTP",
"--only-cc",
"US,DE",
]);
let space = serve_countries(&[
"proxybroker",
"serve",
"--types",
"HTTP",
"--countries",
"US",
"DE",
]);
assert_eq!(comma, vec!["US".to_string(), "DE".to_string()]);
assert_eq!(comma, space);
}
}
#[cfg(test)]
mod format_tests {
use super::*;
use proxybroker::{AnonLevel, Country, Proto, Proxy};
use std::collections::BTreeSet;
fn proxy_fixture() -> Proxy {
let mut p = Proxy::new("1.2.3.4".parse().unwrap(), 8080, BTreeSet::new());
p.geo = Some(Country {
code: "US".into(),
name: "United States".into(),
..Default::default()
});
p.add_type(Proto::Http, Some(AnonLevel::High));
p.record_attempt(Some(0.42), None);
p
}
#[test]
fn emitter_default_is_addr_per_line() {
let mut e = Emitter::new(Format::Default, None);
assert!(e.prefix().is_none());
assert_eq!(e.item(&proxy_fixture()), "1.2.3.4:8080\n");
assert!(e.suffix().is_none());
}
#[test]
fn emitter_json_is_ndjson() {
let mut e = Emitter::new(Format::Json, None);
assert!(e.prefix().is_none() && e.suffix().is_none());
let line = e.item(&proxy_fixture());
assert!(line.ends_with('\n'), "{line:?}");
assert_eq!(
line.matches('\n').count(),
1,
"exactly one object per line: {line:?}"
);
assert!(line.trim_end().starts_with('{'), "{line:?}");
}
#[test]
fn url_format_prefixes_scheme() {
assert_eq!(
Emitter::new(Format::Url, None).item(&proxy_fixture()),
"http://1.2.3.4:8080\n"
);
let mut https = Proxy::new("9.9.9.9".parse().unwrap(), 8080, BTreeSet::new());
https.add_type(Proto::Https, None);
assert_eq!(
Emitter::new(Format::Url, None).item(&https),
"http://9.9.9.9:8080\n"
);
let mut p = Proxy::new("5.6.7.8".parse().unwrap(), 1080, BTreeSet::new());
p.add_type(Proto::Socks5, None);
assert_eq!(
Emitter::new(Format::Url, None).item(&p),
"socks5://5.6.7.8:1080\n"
);
let mut p4 = Proxy::new("5.6.7.8".parse().unwrap(), 1080, BTreeSet::new());
p4.add_type(Proto::Socks4, None);
assert_eq!(
Emitter::new(Format::Url, None).item(&p4),
"socks4://5.6.7.8:1080\n"
);
}
#[test]
fn csv_header_and_row() {
let mut e = Emitter::new(Format::Csv, None);
assert_eq!(
e.prefix().unwrap(),
"host,port,protocols,anon,country,resp_time,error_rate\n"
);
let row = e.item(&proxy_fixture());
let row = row.trim_end();
let fields: Vec<&str> = row.split(',').collect();
assert_eq!(fields.len(), 7, "{row}");
assert_eq!(&fields[..5], ["1.2.3.4", "8080", "HTTP", "High", "US"]);
}
#[test]
fn csv_unchecked_proxy_has_empty_type_columns() {
let p = Proxy::new("1.2.3.4".parse().unwrap(), 8080, BTreeSet::new());
let row = Emitter::new(Format::Csv, None).item(&p);
assert_eq!(row.trim_end(), "1.2.3.4,8080,,,,0,0");
}
#[test]
fn json_array_emits_bracketed_comma_separated() {
let mut e = Emitter::new(Format::JsonArray, None);
let mut out = e.prefix().unwrap();
out.push_str(&e.item(&proxy_fixture()));
out.push_str(&e.item(&proxy_fixture()));
out.push_str(&e.suffix().unwrap());
assert!(out.starts_with('['), "{out}");
assert!(out.ends_with("]\n"), "{out}");
let v: Vec<serde_json::Value> = serde_json::from_str(out.trim_end()).unwrap();
assert_eq!(v.len(), 2, "parses as a 2-element array: {out}");
}
#[test]
fn json_array_empty_stream_is_empty_array() {
let e = Emitter::new(Format::JsonArray, None);
let out = format!("{}{}", e.prefix().unwrap(), e.suffix().unwrap());
assert_eq!(out, "[]\n");
assert!(
serde_json::from_str::<Vec<serde_json::Value>>(out.trim_end())
.unwrap()
.is_empty()
);
}
#[test]
fn ndjson_still_one_object_per_line() {
let mut e = Emitter::new(Format::Json, None);
let a = e.item(&proxy_fixture());
let b = e.item(&proxy_fixture());
assert!(
a.trim_end().starts_with('{') && a.trim_end().ends_with('}'),
"{a:?}"
);
assert!(
b.starts_with('{'),
"NDJSON element must not have a leading separator: {b:?}"
);
}
#[test]
fn template_renders_known_fields() {
assert_eq!(
render_template("{{proxy}}/{{country}}/{{duration}}", &proxy_fixture()),
"1.2.3.4:8080/US/0.42"
);
}
#[test]
fn template_leaves_unknown_tokens_literal() {
assert_eq!(render_template("{{nope}}", &proxy_fixture()), "{{nope}}");
}
#[test]
fn template_renders_asn_tokens() {
let mut p = proxy_fixture();
p.asn = Some(proxybroker::Asn {
number: 15169,
org: Some("Google LLC".into()),
});
assert_eq!(
render_template("{{asn}} {{asn_org}}", &p),
"15169 Google LLC"
);
assert_eq!(render_template("{{asn}}{{asn_org}}", &proxy_fixture()), "");
}
#[test]
fn output_format_overrides_format() {
let mut e = Emitter::new(Format::JsonArray, Some("{{host}}"));
assert!(e.prefix().is_none() && e.suffix().is_none());
assert_eq!(e.item(&proxy_fixture()), "1.2.3.4\n");
}
}