use std::net::IpAddr;
use tracing::debug;
use super::LpdPeer;
pub fn parse_lpd_announcement(data: &[u8], sender_ip: IpAddr) -> Option<LpdPeer> {
let text = std::str::from_utf8(data).ok()?;
let mut info_hash = String::new();
let mut port = 0u16;
let first_line = text.lines().next()?;
if !first_line.starts_with("BT-SEARCH ") {
return parse_lpd_announcement_legacy(data, sender_ip);
}
for line in text.lines() {
let line = line.trim_end_matches('\r');
if let Some(rest) = line.strip_prefix("Infohash:") {
let val = rest.trim();
if val.len() == 40 && val.chars().all(|c| c.is_ascii_hexdigit()) {
info_hash = val.to_lowercase(); } else {
debug!(infohash = %val, "LPD: invalid infohash format");
return None;
}
} else if let Some(rest) = line.strip_prefix("Port:") {
let val = rest.trim();
match val.parse::<u16>() {
Ok(p) if p > 0 => port = p,
_ => {
debug!(port = %val, "LPD: invalid port");
return None;
}
}
}
}
if !info_hash.is_empty() && port > 0 {
debug!(
info_hash = %&info_hash[..8],
port,
addr = %sender_ip,
"Received valid BEP14 LPD announcement"
);
Some(LpdPeer::new(info_hash, port, sender_ip))
} else {
debug!(
has_hash = !info_hash.is_empty(),
has_port = port > 0,
"Incomplete BEP14 LPD announcement ignored"
);
None
}
}
fn parse_lpd_announcement_legacy(data: &[u8], sender_ip: IpAddr) -> Option<LpdPeer> {
let text = std::str::from_utf8(data).ok()?;
let mut info_hash = String::new();
let mut port = 0u16;
for line in text.lines() {
let line = line.trim();
if let Some(rest) = line.strip_prefix("Hash:") {
let val = rest.trim();
if val.len() == 40 && val.chars().all(|c| c.is_ascii_hexdigit()) {
info_hash = val.to_lowercase();
} else {
return None;
}
} else if let Some(rest) = line.strip_prefix("Port:") {
port = rest.trim().parse().ok()?;
if port == 0 {
return None;
}
}
}
if !info_hash.is_empty() && port > 0 {
Some(LpdPeer::new(info_hash, port, sender_ip))
} else {
None
}
}
pub fn is_private_address(addr: &IpAddr) -> bool {
match addr {
IpAddr::V4(v4) => {
let octets = v4.octets();
octets[0] == 10
|| (octets[0] == 172 && (octets[1] & 0xf0) == 16)
|| (octets[0] == 192 && octets[1] == 168)
|| octets[0] == 127
|| (octets[0] == 169 && octets[1] == 254)
}
IpAddr::V6(v6) => {
let segments = v6.segments();
(segments[0] & 0xfe00) == 0xfc00
|| v6.is_loopback()
}
}
}