use crate::parse::IPV4_RE;
use indexmap::IndexMap;
use rand::Rng;
use regex::Regex;
use std::collections::BTreeSet;
use std::net::IpAddr;
use std::sync::LazyLock;
static IPV6_CANDIDATE_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"[0-9A-Fa-f:][0-9A-Fa-f:.]*(?:%[A-Za-z0-9_.\-]+)?").unwrap());
pub fn request_headers(marker: Option<&str>) -> IndexMap<&'static str, String> {
let rv = marker.unwrap_or("");
let mut h = IndexMap::with_capacity(7);
h.insert(
"User-Agent",
format!("PxBroker/{}/{}", env!("CARGO_PKG_VERSION"), rv),
);
h.insert("Accept", "*/*".to_owned());
h.insert("Accept-Encoding", "gzip, deflate".to_owned());
h.insert("Pragma", "no-cache".to_owned());
h.insert("Cache-control", "no-cache".to_owned());
h.insert("Cookie", "cookie=ok".to_owned());
h.insert("Referer", "https://www.google.com/".to_owned());
h
}
pub fn fresh_marker() -> String {
(1000 + rand::rng().random_range(0..9000)).to_string()
}
pub fn canonicalize_ip(s: &str) -> Option<String> {
if let Some((base, zone)) = s.split_once('%') {
let addr: IpAddr = base.parse().ok()?;
if !addr.is_ipv6() {
return None;
}
return Some(format!("{addr}%{zone}"));
}
s.parse::<IpAddr>().ok().map(|ip| ip.to_string())
}
pub fn get_all_ip(page: &str) -> BTreeSet<String> {
let mut found: BTreeSet<String> = IPV4_RE
.find_iter(page)
.map(|m| m.as_str().to_owned())
.collect();
for tok in IPV6_CANDIDATE_RE.find_iter(page) {
let tok = tok.as_str();
if !tok.contains(':') {
continue; }
if let Some(c) = canonicalize_ip(tok.trim_end_matches('.')) {
found.insert(c);
}
}
found
}
pub fn get_status_code(resp: &[u8], start: usize, stop: usize) -> u16 {
let end = stop.min(resp.len());
if start >= end {
return 400;
}
match std::str::from_utf8(&resp[start..end]) {
Ok(s) => s.trim().parse::<u16>().unwrap_or(400),
Err(_) => 400,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn headers_are_in_wire_order() {
let h = request_headers(None);
let keys: Vec<_> = h.keys().copied().collect();
assert_eq!(
keys,
[
"User-Agent",
"Accept",
"Accept-Encoding",
"Pragma",
"Cache-control",
"Cookie",
"Referer"
]
);
}
#[test]
fn marker_is_folded_into_user_agent() {
let h = request_headers(Some("4242"));
assert!(h["User-Agent"].ends_with("/4242"), "{}", h["User-Agent"]);
assert!(request_headers(None)["User-Agent"].ends_with('/'));
}
#[test]
fn fresh_marker_is_four_digits() {
let m = fresh_marker();
let n: u32 = m.parse().unwrap();
assert!((1000..=9999).contains(&n), "{m}");
}
#[test]
fn zone_id_that_is_not_ipv6_is_rejected() {
assert_eq!(canonicalize_ip("1.2.3.4%eth0"), None);
}
}