use std::collections::HashSet;
use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
use std::time::{Duration, Instant};
use tracing::{debug, warn};
use crate::constants;
use super::LpdPeer;
use super::discovery::parse_lpd_announcement;
pub struct LpdAnnouncer {
socket: UdpSocket,
multicast_addr: SocketAddr,
enabled: bool,
interface: Option<Ipv4Addr>,
announce_interval: Duration,
}
impl LpdAnnouncer {
pub fn new() -> Result<Self, String> {
Self::with_config(constants::LPD_DEFAULT_ANNOUNCE_INTERVAL_SECS)
}
pub fn with_config(announce_interval_secs: u64) -> Result<Self, String> {
Self::with_interface(announce_interval_secs, None)
}
pub fn with_interface(
announce_interval_secs: u64,
interface: Option<Ipv4Addr>,
) -> Result<Self, String> {
let socket = UdpSocket::bind("0.0.0.0:0")
.map_err(|e| format!("Failed to bind UDP socket: {}", e))?;
socket
.set_broadcast(true)
.map_err(|e| format!("Failed to enable broadcast: {}", e))?;
#[cfg(unix)]
{
use std::os::unix::io::AsRawFd;
let fd = socket.as_raw_fd();
unsafe {
libc::setsockopt(
fd,
libc::SOL_SOCKET,
libc::SO_REUSEADDR,
&1i32 as *const i32 as *const libc::c_void,
std::mem::size_of::<i32>() as libc::socklen_t,
);
}
}
let multicast_addr: SocketAddr = format!(
"{}:{}",
constants::LPD_MULTICAST_ADDRESS,
constants::LPD_PORT
)
.parse()
.map_err(|e| format!("Invalid LPD multicast address: {}", e))?;
let multicast_ip: Ipv4Addr = constants::LPD_MULTICAST_ADDRESS
.parse()
.map_err(|e| format!("Invalid LPD multicast IP: {}", e))?;
let local_interface = interface.unwrap_or(Ipv4Addr::UNSPECIFIED);
socket
.join_multicast_v4(&multicast_ip, &local_interface)
.map_err(|e| format!("Failed to join LPD multicast group: {}", e))?;
debug!(
local = ?socket.local_addr().ok(),
multicast = %multicast_addr,
"LpdAnnouncer created successfully"
);
Ok(Self {
socket,
multicast_addr,
enabled: true,
interface,
announce_interval: Duration::from_secs(announce_interval_secs),
})
}
pub fn disable(&mut self) {
self.enabled = false;
}
pub fn enable(&mut self) {
self.enabled = true;
}
pub fn is_enabled(&self) -> bool {
self.enabled
}
pub fn announce_interval(&self) -> Duration {
self.announce_interval
}
pub fn local_addr(&self) -> Result<SocketAddr, String> {
self.socket
.local_addr()
.map_err(|e| format!("Failed to get local address: {}", e))
}
pub fn interface(&self) -> Option<Ipv4Addr> {
self.interface
}
pub fn announce(&self, info_hash: &str, port: u16) -> Result<(), String> {
if !self.enabled {
return Ok(()); }
if info_hash.len() != 40 || !info_hash.chars().all(|c| c.is_ascii_hexdigit()) {
return Err(format!(
"Invalid info_hash format: expected 40 hex chars, got {} chars",
info_hash.len()
));
}
let msg = format!(
"BT-SEARCH * HTTP/1.1\r\nHost: {}:{}\r\nPort: {}\r\nInfohash: {}\r\n\r\n\r\n",
constants::LPD_MULTICAST_ADDRESS,
constants::LPD_PORT,
port,
info_hash
);
debug!(
info_hash = %&info_hash[..8],
port,
"Sending BEP14 LPD announcement"
);
self.socket
.send_to(msg.as_bytes(), self.multicast_addr)
.map_err(|e| format!("LPD announce send failed: {}", e))?;
Ok(())
}
pub fn receive_announcements(&self, timeout: Duration) -> Vec<LpdPeer> {
let mut buf = [0u8; constants::LPD_RECEIVE_BUFFER_SIZE];
let mut peers = Vec::new();
let mut seen: HashSet<(String, IpAddr)> = HashSet::new();
self.socket
.set_read_timeout(Some(timeout))
.expect("set_read_timeout should not fail");
let deadline = Instant::now() + timeout;
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
break;
}
match self.socket.recv_from(&mut buf) {
Ok((len, src_addr)) => {
if len == 0 {
continue;
}
if let Some(peer) = parse_lpd_announcement(&buf[..len], src_addr.ip()) {
let key = (peer.info_hash.clone(), peer.addr);
if seen.insert(key) {
debug!(
info_hash = %peer.info_hash[..8.min(peer.info_hash.len())],
addr = %src_addr.ip(),
port = peer.port,
"Discovered peer via LPD"
);
peers.push(peer);
}
}
}
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
break;
}
Err(ref e) if e.kind() == std::io::ErrorKind::TimedOut => {
break;
}
Err(e) => {
warn!(error = %e, "LPD receive error");
break;
}
}
}
peers
}
}