use crate::proxy::Proxy;
use crate::resolver::parse_ip_lenient;
use regex::Regex;
use std::collections::BTreeSet;
use std::sync::LazyLock;
const IPV4: &str = r"(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)";
pub(crate) static IPV4_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(IPV4).unwrap());
static PORT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\d{2,5}").unwrap());
pub fn find_addrs_line(text: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
for line in text.split('\n') {
let Some(ip) = IPV4_RE.find(line) else {
continue;
};
if let Some(port) = PORT_RE.find(&line[ip.end()..]) {
out.push((ip.as_str().to_owned(), port.as_str().to_owned()));
}
}
out
}
pub fn find_addrs_global(text: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
let mut search_from = 0usize;
while let Some(ip) = IPV4_RE.find_at(text, search_from) {
let after = ip.end();
let next_ip = IPV4_RE.find_at(text, after);
let next_port = PORT_RE.find_at(text, after);
let port = match (next_port, next_ip) {
(Some(p), Some(i)) if p.start() < i.start() => Some(p.as_str().to_owned()),
(Some(p), None) => Some(p.as_str().to_owned()),
(_, Some(_)) => Some(String::new()),
(None, None) => None,
};
if let Some(port) = port {
out.push((ip.as_str().to_owned(), port));
}
search_from = after;
}
out
}
pub fn parse_proxy_lines(text: &str) -> Vec<Proxy> {
find_addrs_line(text)
.into_iter()
.filter_map(|(ip_str, port_str)| {
let ip = parse_ip_lenient(&ip_str)?;
let port: u16 = port_str.parse().ok()?; Some(Proxy::new(ip, port, BTreeSet::new()))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_addr_lines_into_proxies() {
let text = "1.2.3.4:8080\n010.0.0.1:3128\ngarbage\n5.6.7.8:99999\n";
let proxies = parse_proxy_lines(text);
let addrs: Vec<String> = proxies.iter().map(|p| p.addr()).collect();
assert_eq!(addrs, ["1.2.3.4:8080", "10.0.0.1:3128"]);
assert!(proxies[0].expected_types.is_empty());
}
#[test]
fn empty_and_junk_input_yields_nothing() {
assert!(parse_proxy_lines("").is_empty());
assert!(parse_proxy_lines("no proxies here\njust text\n").is_empty());
}
}