torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
//! Central outbound dial / contact policy.
//!
//! All untrusted peer/node addresses (tracker compact lists, DHT nodes, magnet
//! `x.pe`, PEX, webseed targets already go through tracker policy) must pass
//! through [`DialGate`] before connect or routing-table insert. Host-configured
//! static peers use [`DialGate::allow_static`] explicitly.

use std::net::SocketAddr;

use crate::tracker::is_blocked_ip;

/// Policy for accepting outbound contact addresses from untrusted discovery.
#[derive(Debug, Clone, Copy)]
pub struct DialGate {
    /// When true, blocked address classes (loopback, RFC1918, …) are refused.
    pub block_private: bool,
}

impl DialGate {
    pub fn from_block_private(block_private: bool) -> Self {
        Self { block_private }
    }

    /// Whether an untrusted discovery address may be dialed or stored as a contact.
    pub fn allows(&self, addr: SocketAddr) -> bool {
        if self.block_private && is_blocked_ip(addr.ip()) {
            tracing::debug!(%addr, "dial gate rejected blocked address class");
            false
        } else {
            true
        }
    }

    pub fn filter(&self, peers: impl IntoIterator<Item = SocketAddr>) -> Vec<SocketAddr> {
        peers.into_iter().filter(|a| self.allows(*a)).collect()
    }

    /// Host-configured static peers — never filtered by this gate.
    pub fn allow_static(peers: impl IntoIterator<Item = SocketAddr>) -> Vec<SocketAddr> {
        peers.into_iter().collect()
    }

    /// Refuse connect when the gate would block (defense in depth at dial site).
    pub fn ensure_dialable(&self, addr: SocketAddr) -> crate::error::Result<()> {
        if self.allows(addr) {
            Ok(())
        } else {
            Err(crate::error::Error::Session(format!(
                "refusing dial to blocked address {addr}"
            )))
        }
    }
}

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

    #[test]
    fn blocks_private_when_configured() {
        let gate = DialGate::from_block_private(true);
        let loopback: SocketAddr = "127.0.0.1:6881".parse().unwrap();
        let public: SocketAddr = "203.0.113.9:6881".parse().unwrap();
        assert!(!gate.allows(loopback));
        assert!(gate.allows(public));
        assert!(DialGate::from_block_private(false).allows(loopback));
    }
}