proxybroker 0.4.7

Find, check, and serve public HTTP(S) and SOCKS4/5 proxies. Library + CLI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Proxy providers: where candidate proxies come from.
//!
//! Data-driven by design. Provider sites rot continuously — measurement on 2026-07-15 found
//! ~10 of proxybroker2's 38 registry entries already dead — so a provider is a
//! [`ProviderSpec`] (deserializable from YAML/JSON), not a hardcoded Rust type. A dead
//! provider is a config edit, not a recompile-and-republish. See `decisions.md`.
//!
//! Extraction defaults to the whole-text IP:port scanner ([`crate::parse::find_addrs_global`]),
//! which subsumes plain-text, `ip:port`-per-line, and HTML-table formats — so no per-format
//! parser zoo is needed (design critique #36). A provider that needs bespoke extraction
//! supplies a `pattern` (a 2-capture-group regex).

use crate::parse::find_addrs_global;
use crate::types::Proto;
use crate::utils::canonicalize_ip;
use regex::Regex;
use serde::Deserialize;
use std::collections::BTreeSet;

/// A provider definition. Serializable, so the bundled registry and user configs share one
/// shape. Extraction (the whole-text scanner, or a custom `pattern`) is common to all.
#[derive(Debug, Clone, Deserialize)]
pub struct ProviderSpec {
    /// The page to fetch.
    pub url: String,
    /// Protocols proxies from this source may support. Empty = unknown (checked against all).
    #[serde(default)]
    pub protocols: Vec<Proto>,
    /// Optional bespoke extraction: a regex with two capture groups, `(host, port)`. When
    /// absent, the default whole-text IP:port scanner is used.
    #[serde(default)]
    pub pattern: Option<String>,
    /// Request timeout, seconds.
    #[serde(default = "default_timeout")]
    pub timeout: u64,
    /// proxybroker2's config `type` field (`simple` / `paginated` / `api`). Only `simple`
    /// (the default) is supported; the loader warns and skips the others rather than loading
    /// them as silently-broken simple GETs. `None`/`simple` both mean plain.
    #[serde(default, rename = "type")]
    pub kind: Option<String>,
}

fn default_timeout() -> u64 {
    20
}

/// A candidate proxy scraped from a provider: a canonical IP, a port, and the protocols the
/// provider claims for it. Not yet a [`crate::Proxy`] — it has not been checked.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Candidate {
    pub host: String,
    pub port: u16,
    pub protocols: BTreeSet<Proto>,
}

impl ProviderSpec {
    /// A convenience constructor for the bundled registry.
    pub fn new(url: &str, protocols: &[Proto]) -> Self {
        ProviderSpec {
            url: url.to_owned(),
            protocols: protocols.to_vec(),
            pattern: None,
            timeout: default_timeout(),
            kind: None,
        }
    }

    /// Extract candidate proxies from a fetched page body.
    ///
    /// Mirrors the Provider→`find_proxies`→`proxies.setter` path in `providers.py`: pairs are
    /// found, then filtered — `providers.py:78` keeps only pairs with a truthy port. IPs are
    /// canonicalized (`canonicalize_ip`), which drops the leading-zero and out-of-range matches
    /// the scanner permits, exactly as the Python pipeline does. Deduplicated.
    pub fn extract(&self, body: &str) -> Vec<Candidate> {
        let protocols: BTreeSet<Proto> = self.protocols.iter().copied().collect();
        let pairs = match &self.pattern {
            Some(pat) => extract_with_pattern(pat, body),
            None => find_addrs_global(body),
        };

        let mut seen = BTreeSet::new();
        let mut out = Vec::new();
        for (raw_host, raw_port) in pairs {
            // providers.py:78 — `for host, port in new if port`: drop empty/zero ports.
            let Ok(port) = raw_port.parse::<u16>() else {
                continue;
            };
            if port == 0 {
                continue;
            }
            let Some(host) = canonicalize_ip(&raw_host) else {
                continue;
            };
            // Drop the unspecified address (`0.0.0.0` / `::`): some lists ship it as a sentinel
            // line and it is never a routable proxy. `canonicalize_ip` stays Python-parity-faithful
            // (it accepts it, matching `ipaddress`); this non-routable policy lives at the provider
            // layer, not in the shared primitive. `host` is a canonical IP, so the parse succeeds.
            if host
                .parse::<std::net::IpAddr>()
                .is_ok_and(|ip| ip.is_unspecified())
            {
                continue;
            }
            let cand = Candidate {
                host,
                port,
                protocols: protocols.clone(),
            };
            if seen.insert((cand.host.clone(), cand.port)) {
                out.push(cand);
            }
        }
        out
    }
}

/// The bundled default providers, parsed from the embedded `data/providers.yaml`. Only
/// sources confirmed live on 2026-07-15; proxybroker2's dead entries are not carried over.
pub fn bundled_registry() -> Vec<ProviderSpec> {
    const YAML: &str = include_str!("../data/providers.yaml");
    serde_yaml_ng::from_str(YAML).expect("bundled providers.yaml is valid")
}

/// Load provider configs from a directory: every `*.yaml` / `*.yml` / `*.json` file, one
/// provider per file, sorted by name, skipping files whose name starts with `_` (the rename
/// -to-disable convention). Mirrors `provider_utils.load_provider_configs_from_directory`.
///
/// A file that fails to parse is logged and skipped so one bad config does not sink the rest.
/// Harmless unknown fields (Python's `name`, `format`, `max_connections`) are ignored, so a
/// `type: simple` (or type-less) proxybroker2 config loads directly.
///
/// **Deviation — only `type: simple` is supported.** proxybroker2 has `paginated` and `api`
/// provider types with distinct fetch logic. This port implements neither; a config declaring
/// one is **warned about and skipped** rather than loaded as a silently-broken plain GET (which
/// would fetch the `?page={}` URL verbatim, or ignore `api_key`/`headers`, and yield nothing).
///
/// **Deviation — no Python execution.** proxybroker2's `load_python_providers_from_directory`
/// *executes* `.py` files; there is no safe Rust equivalent (we do not run arbitrary code), so
/// only data files are loaded — also the safer default.
pub fn load_provider_dir(dir: &std::path::Path) -> Vec<ProviderSpec> {
    if !dir.is_dir() {
        tracing::warn!(dir = %dir.display(), "provider directory does not exist");
        return Vec::new();
    }
    let mut paths: Vec<std::path::PathBuf> = match std::fs::read_dir(dir) {
        Ok(entries) => entries
            .filter_map(|e| e.ok().map(|e| e.path()))
            .filter(|p| {
                let ext_ok = matches!(
                    p.extension().and_then(|e| e.to_str()),
                    Some("yaml" | "yml" | "json")
                );
                let named = p
                    .file_name()
                    .and_then(|n| n.to_str())
                    .is_some_and(|n| !n.starts_with('_'));
                ext_ok && named
            })
            .collect(),
        Err(e) => {
            tracing::warn!(dir = %dir.display(), error = %e, "cannot read provider directory");
            return Vec::new();
        }
    };
    paths.sort();

    paths
        .into_iter()
        .filter_map(|p| match std::fs::read_to_string(&p) {
            Ok(text) => match serde_yaml_ng::from_str::<ProviderSpec>(&text) {
                // serde_yaml_ng parses JSON too (JSON is a YAML subset), so one path covers both.
                Ok(spec) => match spec.kind.as_deref() {
                    None | Some("simple") => Some(spec),
                    Some(other) => {
                        tracing::warn!(
                            path = %p.display(),
                            kind = other,
                            "unsupported provider type (only 'simple' is supported) — skipping"
                        );
                        None
                    }
                },
                Err(e) => {
                    tracing::warn!(path = %p.display(), error = %e, "skipping invalid provider config");
                    None
                }
            },
            Err(e) => {
                tracing::warn!(path = %p.display(), error = %e, "cannot read provider config");
                None
            }
        })
        .collect()
}

/// A YAML config template for a provider, to help users write their own.
/// `provider_utils.create_provider_config_template`.
pub fn config_template() -> &'static str {
    "# proxybroker provider config — one provider per file.\n\
     # Drop this in a directory and pass it with --provider-dir.\n\
     # A filename starting with `_` is skipped (rename to disable).\n\
     url: \"http://example.com/proxy-list.txt\"\n\
     # Protocols proxies from this source may support (empty = check all):\n\
     protocols: [HTTP, HTTPS]\n\
     # Optional 2-group (host, port) regex; omit to use the default IP:port scanner:\n\
     # pattern: \"(\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+):(\\\\d+)\"\n\
     timeout: 20\n"
}

/// Fetch a provider's page and extract candidate proxies. Network I/O; the pure extraction
/// it wraps is [`ProviderSpec::extract`]. On any fetch error the provider yields nothing —
/// one dead source must never sink a grab (mirrors `providers.py`, which swallows request
/// errors per provider).
pub async fn fetch(spec: &ProviderSpec, client: &reqwest::Client) -> Vec<Candidate> {
    match fetch_body(spec, client).await {
        Ok(body) => spec.extract(&body),
        Err(e) => {
            tracing::debug!(url = %spec.url, error = %e, "provider fetch failed");
            Vec::new()
        }
    }
}

async fn fetch_body(spec: &ProviderSpec, client: &reqwest::Client) -> reqwest::Result<String> {
    client
        .get(&spec.url)
        .timeout(std::time::Duration::from_secs(spec.timeout))
        .send()
        .await?
        .error_for_status()?
        .text()
        .await
}

/// Apply a 2-capture-group `(host, port)` regex, mirroring `SimpleProvider`'s custom-pattern
/// path (`provider_utils.py`): a match with ≥2 groups yields `(g1, g2)`; a single string
/// match containing `:` is split on the last colon; anything else is dropped.
fn extract_with_pattern(pattern: &str, body: &str) -> Vec<(String, String)> {
    let Ok(re) = Regex::new(pattern) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    for caps in re.captures_iter(body) {
        match (caps.get(1), caps.get(2)) {
            (Some(h), Some(p)) => out.push((h.as_str().to_owned(), p.as_str().to_owned())),
            _ => {
                let whole = caps.get(0).map(|m| m.as_str()).unwrap_or("");
                if let Some((h, p)) = whole.rsplit_once(':') {
                    out.push((h.to_owned(), p.to_owned()));
                }
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn spec(protocols: &[Proto]) -> ProviderSpec {
        ProviderSpec::new("http://example/", protocols)
    }

    #[test]
    fn extracts_from_plain_text_list() {
        let body = "8.8.8.8:8080\n1.1.1.1:3128\n";
        let got = spec(&[Proto::Http]).extract(body);
        assert_eq!(got.len(), 2);
        assert_eq!(got[0].host, "8.8.8.8");
        assert_eq!(got[0].port, 8080);
        assert!(got[0].protocols.contains(&Proto::Http));
    }

    #[test]
    fn extracts_from_html_table() {
        let body = "<tr><td>66.55.44.33</td><td>8888</td></tr>\
                    <tr><td>22.33.44.55</td><td>9999</td></tr>";
        let got = spec(&[]).extract(body);
        assert_eq!(got.len(), 2);
        assert_eq!(got[0].host, "66.55.44.33");
        assert_eq!(got[1].port, 9999);
    }

    #[test]
    fn matches_python_pipeline_on_messy_input() {
        // Verified against proxybroker2's actual regex + canonicalize pipeline:
        //   raw pairs: [('99.1.1.1','80'), ('5.5.5.5',''), ('010.1.1.1','80'), ('7.7.7.7','1234')]
        //   kept:      [('99.1.1.1','80'), ('7.7.7.7','1234')]
        // - 999.1.1.1 → the scanner greedily extracts the valid substring 99.1.1.1 (same as
        //   300.1.2.3 → 00.1.2.3); it is a real, canonicalizable IP, so it is KEPT.
        // - 5.5.5.5 gets an empty port (the nearest following token is the IP 010.1.1.1), dropped.
        // - 010.1.1.1 canonicalizes to None (leading zero), dropped.
        let body = "999.1.1.1:80 5.5.5.5:0 010.1.1.1:80 7.7.7.7:1234";
        let got = spec(&[]).extract(body);
        assert_eq!(got.len(), 2, "{got:?}");
        assert_eq!(got[0].host, "99.1.1.1");
        assert_eq!(got[0].port, 80);
        assert_eq!(got[1].host, "7.7.7.7");
        assert_eq!(got[1].port, 1234);
    }

    #[test]
    fn deduplicates_repeated_addresses() {
        let body = "9.9.9.9:53\n9.9.9.9:53\n9.9.9.9:53";
        assert_eq!(spec(&[]).extract(body).len(), 1);
    }

    #[test]
    fn drops_the_unspecified_sentinel() {
        // Some lists (e.g. openproxylist) lead with a `0.0.0.0:80` sentinel that is never a routable
        // proxy. It must not become a candidate, while real rows on either side survive.
        let body = "0.0.0.0:80\n8.8.8.8:8080\n1.1.1.1:3128";
        let got = spec(&[Proto::Http]).extract(body);
        assert!(
            got.iter().all(|c| c.host != "0.0.0.0"),
            "unspecified address leaked into candidates: {got:?}"
        );
        assert_eq!(got.len(), 2, "both real rows must be kept: {got:?}");
        assert!(got.iter().any(|c| c.host == "8.8.8.8" && c.port == 8080));
    }

    #[test]
    fn custom_pattern_with_two_groups() {
        let body = "IP=1.2.3.4 PORT=8080; IP=5.6.7.8 PORT=3128";
        let mut s = spec(&[Proto::Socks5]);
        s.pattern = Some(r"IP=(\d+\.\d+\.\d+\.\d+) PORT=(\d+)".to_owned());
        let got = s.extract(body);
        assert_eq!(got.len(), 2);
        assert_eq!(got[0].host, "1.2.3.4");
        assert_eq!(got[1].port, 3128);
        assert!(got[1].protocols.contains(&Proto::Socks5));
    }

    #[test]
    fn spec_deserializes_from_yaml() {
        let yaml = "url: https://example.com/list\nprotocols: [HTTP, SOCKS5]\ntimeout: 15";
        let s: ProviderSpec = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(s.url, "https://example.com/list");
        assert_eq!(s.protocols, vec![Proto::Http, Proto::Socks5]);
        assert_eq!(s.timeout, 15);
        assert!(s.pattern.is_none());
    }

    #[test]
    fn python_config_extra_fields_are_ignored() {
        // A proxybroker2 config with name/type/format/max_connections must still load.
        let yaml = "name: My List\ntype: simple\nformat: text\nurl: http://x/list\n\
                    protocols: [HTTP]\nmax_connections: 4\ntimeout: 30";
        let s: ProviderSpec = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(s.url, "http://x/list");
        assert_eq!(s.timeout, 30);
    }

    #[test]
    fn config_template_is_a_valid_provider_spec() {
        let s: ProviderSpec = serde_yaml_ng::from_str(config_template()).unwrap();
        assert_eq!(s.protocols, vec![Proto::Http, Proto::Https]);
    }

    #[test]
    fn load_provider_dir_reads_sorted_skips_underscore_and_bad() {
        let dir = std::env::temp_dir().join(format!("pb_prov_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("b.yaml"), "url: http://b/\nprotocols: [SOCKS5]").unwrap();
        std::fs::write(
            dir.join("a.json"),
            r#"{"url":"http://a/","protocols":["HTTP"]}"#,
        )
        .unwrap();
        std::fs::write(dir.join("_disabled.yaml"), "url: http://skip/").unwrap();
        std::fs::write(dir.join("broken.yaml"), "url: [not a string").unwrap();
        std::fs::write(dir.join("notconfig.txt"), "ignored").unwrap();

        let specs = load_provider_dir(&dir);
        // sorted by filename: a.json then b.yaml; _disabled, broken, and .txt excluded.
        assert_eq!(specs.len(), 2, "{specs:?}");
        assert_eq!(specs[0].url, "http://a/");
        assert_eq!(specs[0].protocols, vec![Proto::Http]);
        assert_eq!(specs[1].url, "http://b/");

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_provider_dir_missing_dir_is_empty() {
        let dir = std::env::temp_dir().join("pb_prov_definitely_missing_xyz");
        assert!(load_provider_dir(&dir).is_empty());
    }

    #[test]
    fn unsupported_provider_types_are_skipped_not_loaded_broken() {
        // A paginated/api config would load as a silently-broken simple GET without the
        // kind check; it must be skipped instead (review F1).
        let dir = std::env::temp_dir().join(format!("pb_prov_kind_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("ok.yaml"),
            "type: simple\nurl: http://ok/\nprotocols: [HTTP]",
        )
        .unwrap();
        std::fs::write(
            dir.join("paginated.yaml"),
            "type: paginated\nurl: http://p/?page={}",
        )
        .unwrap();
        std::fs::write(
            dir.join("api.yaml"),
            "type: api\nurl: http://a/\napi_key: secret",
        )
        .unwrap();
        std::fs::write(
            dir.join("typeless.yaml"),
            "url: http://t/\nprotocols: [HTTP]",
        )
        .unwrap();

        let specs = load_provider_dir(&dir);
        // Only 'simple' and type-less load; paginated and api are skipped.
        let urls: Vec<_> = specs.iter().map(|s| s.url.as_str()).collect();
        assert_eq!(urls, vec!["http://ok/", "http://t/"], "{specs:?}");

        let _ = std::fs::remove_dir_all(&dir);
    }
}