torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
use std::time::Duration;

use igd_next::{search_gateway, PortMappingProtocol, SearchOptions};
use natpmp::{Natpmp, Protocol, Response};
use tracing::{info, warn};

use crate::error::{Error, Result};

const LEASE_SECS: u32 = 3600;

fn local_ipv4() -> Ipv4Addr {
    if let Ok(socket) = std::net::UdpSocket::bind("0.0.0.0:0") {
        if socket.connect("8.8.8.8:80").is_ok() {
            if let Ok(addr) = socket.local_addr() {
                if let std::net::IpAddr::V4(v4) = addr.ip() {
                    return v4;
                }
            }
        }
    }
    Ipv4Addr::LOCALHOST
}

#[allow(dead_code)]
pub enum PortMapping {
    Upnp(UpnpMapping),
    NatPmp(NatPmpMapping),
}

pub struct UpnpMapping {
    gateway: igd_next::Gateway,
    protocol: PortMappingProtocol,
    external_port: u16,
}

pub struct NatPmpMapping {
    _gateway: Ipv4Addr,
    protocol: Protocol,
    _external_port: u16,
    internal_port: u16,
}

impl UpnpMapping {
    fn map(listen_port: u16, protocol: PortMappingProtocol) -> Result<Self> {
        let gateway = search_gateway(SearchOptions::default())
            .map_err(|err| Error::Config(format!("UPnP gateway search failed: {err}")))?;

        let external_ip = gateway
            .get_external_ip()
            .map_err(|err| Error::Config(format!("UPnP get external ip failed: {err}")))?;
        let label = format!("torrentdht-{listen_port}");
        let internal = SocketAddr::V4(SocketAddrV4::new(local_ipv4(), listen_port));

        gateway
            .add_port(protocol, listen_port, internal, LEASE_SECS, &label)
            .map_err(|err| Error::Config(format!("UPnP add_port failed: {err}")))?;

        info!(
            %listen_port,
            protocol = ?protocol,
            %external_ip,
            "UPnP port mapped"
        );

        Ok(Self {
            gateway,
            protocol,
            external_port: listen_port,
        })
    }
}

impl Drop for UpnpMapping {
    fn drop(&mut self) {
        if let Err(err) = self
            .gateway
            .remove_port(self.protocol, self.external_port)
        {
            warn!(
                port = self.external_port,
                protocol = ?self.protocol,
                %err,
                "UPnP port unmap failed"
            );
        }
    }
}

impl NatPmpMapping {
    fn map(listen_port: u16, protocol: Protocol) -> Result<Self> {
        let mut client = Natpmp::new().map_err(|err| Error::Config(format!("NAT-PMP init: {err}")))?;
        client
            .send_port_mapping_request(protocol, listen_port, listen_port, LEASE_SECS)
            .map_err(|err| Error::Config(format!("NAT-PMP map request: {err}")))?;
        std::thread::sleep(Duration::from_millis(250));
        let response = client
            .read_response_or_retry()
            .map_err(|err| Error::Config(format!("NAT-PMP map response: {err}")))?;

        let external_port = match response {
            Response::UDP(mapping) if protocol == Protocol::UDP => mapping.public_port(),
            Response::TCP(mapping) if protocol == Protocol::TCP => mapping.public_port(),
            other => {
                return Err(Error::Config(format!(
                    "NAT-PMP unexpected response: {other:?}"
                )));
            }
        };

        let gateway = natpmp::get_default_gateway().unwrap_or(Ipv4Addr::LOCALHOST);
        info!(
            %listen_port,
            %external_port,
            ?protocol,
            %gateway,
            "NAT-PMP port mapped"
        );

        Ok(Self {
            _gateway: gateway,
            protocol,
            _external_port: external_port,
            internal_port: listen_port,
        })
    }
}

impl Drop for NatPmpMapping {
    fn drop(&mut self) {
        if let Ok(mut client) = Natpmp::new() {
            let _ = client.send_port_mapping_request(
                self.protocol,
                self.internal_port,
                0,
                0,
            );
            std::thread::sleep(Duration::from_millis(100));
            let _ = client.read_response_or_retry();
        }
    }
}

pub async fn map_listen_ports(
    listen_port: u16,
    map_tcp: bool,
    map_udp: bool,
    use_upnp: bool,
    use_natpmp: bool,
) -> Result<Vec<PortMapping>> {
    let mut mappings = Vec::new();

    if use_upnp {
        if map_tcp {
            match tokio::time::timeout(
                Duration::from_secs(5),
                tokio::task::spawn_blocking(move || {
                    UpnpMapping::map(listen_port, PortMappingProtocol::TCP)
                }),
            )
            .await
            {
                Ok(Ok(Ok(mapping))) => mappings.push(PortMapping::Upnp(mapping)),
                Ok(Ok(Err(err))) => warn!(%err, "TCP UPnP mapping skipped"),
                Ok(Err(err)) => warn!(%err, "TCP UPnP mapping task failed"),
                Err(_) => warn!("TCP UPnP mapping timed out"),
            }
        }
        if map_udp {
            match tokio::time::timeout(
                Duration::from_secs(5),
                tokio::task::spawn_blocking(move || {
                    UpnpMapping::map(listen_port, PortMappingProtocol::UDP)
                }),
            )
            .await
            {
                Ok(Ok(Ok(mapping))) => mappings.push(PortMapping::Upnp(mapping)),
                Ok(Ok(Err(err))) => warn!(%err, "UDP UPnP mapping skipped"),
                Ok(Err(err)) => warn!(%err, "UDP UPnP mapping task failed"),
                Err(_) => warn!("UDP UPnP mapping timed out"),
            }
        }
    }

    if use_natpmp {
        if map_tcp {
            match tokio::time::timeout(
                Duration::from_secs(5),
                tokio::task::spawn_blocking(move || NatPmpMapping::map(listen_port, Protocol::TCP)),
            )
            .await
            {
                Ok(Ok(Ok(mapping))) => mappings.push(PortMapping::NatPmp(mapping)),
                Ok(Ok(Err(err))) => warn!(%err, "TCP NAT-PMP mapping skipped"),
                Ok(Err(err)) => warn!(%err, "TCP NAT-PMP mapping task failed"),
                Err(_) => warn!("TCP NAT-PMP mapping timed out"),
            }
        }
        if map_udp {
            match tokio::time::timeout(
                Duration::from_secs(5),
                tokio::task::spawn_blocking(move || NatPmpMapping::map(listen_port, Protocol::UDP)),
            )
            .await
            {
                Ok(Ok(Ok(mapping))) => mappings.push(PortMapping::NatPmp(mapping)),
                Ok(Ok(Err(err))) => warn!(%err, "UDP NAT-PMP mapping skipped"),
                Ok(Err(err)) => warn!(%err, "UDP NAT-PMP mapping task failed"),
                Err(_) => warn!("UDP NAT-PMP mapping timed out"),
            }
        }
    }

    Ok(mappings)
}

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

    #[test]
    fn local_ipv4_is_not_unspecified() {
        let ip = local_ipv4();
        assert_ne!(ip, Ipv4Addr::UNSPECIFIED);
    }
}