node-device-session 7.7.3

Shared server for /econ-v1/device-session/1 behind transport-neutral traits (C-5)
Documentation
//! Carrier-neutral session UDP port mapping for ICE srflx candidates.
use std::net::{Ipv4Addr, SocketAddr};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};

/// A granted external mapping for one ICE session socket.
pub struct MappedSessionPort {
    /// Provider-assigned mapping id (used to unmap).
    pub id: u64,
    /// External IPv4 advertised as srflx.
    pub external_ip: Ipv4Addr,
    /// External UDP port.
    pub external_port: u16,
    /// Internal UDP port that must match the session socket.
    pub internal_port: u16,
    /// Lease duration; zero leases are rejected.
    pub lease: Duration,
}

/// Why a mapping request failed.
#[derive(Debug, PartialEq, Eq)]
pub enum MapRefusal {
    /// Carrier automap is disabled.
    AutomapOff,
    /// Node is not a public mapper.
    NotPublic,
    /// Concurrent mapping limit reached.
    Limit,
    /// Upstream refused with a reason.
    Refused(String),
    /// Provider did not answer in time.
    Timeout,
    /// No mapper / unavailable.
    Unavailable,
}

impl MapRefusal {
    fn kind(&self) -> &'static str {
        match self {
            Self::AutomapOff => "automap_off",
            Self::NotPublic => "not_public",
            Self::Limit => "limit",
            Self::Refused(_) => "refused",
            Self::Timeout => "timeout",
            Self::Unavailable => "unavailable",
        }
    }
}

/// Carrier-owned UDP session port mapper (UPnP, relay map, etc.).
pub trait SessionPortMapper: Send + Sync {
    /// Blocking, bounded by the provider (typically five seconds). Owns renewal.
    fn map(&self, internal_port: u16, description: &str) -> Result<MappedSessionPort, MapRefusal>;
    /// Release a previously granted mapping.
    fn unmap(&self, id: u64);
}

/// Mapper that always refuses (host / STUN-only ICE).
pub struct NoSessionPortMapper;

impl SessionPortMapper for NoSessionPortMapper {
    fn map(&self, _: u16, _: &str) -> Result<MappedSessionPort, MapRefusal> {
        Err(MapRefusal::Unavailable)
    }
    fn unmap(&self, _: u64) {}
}

pub(super) struct Mapping {
    port: MappedSessionPort,
    mapper: Arc<dyn SessionPortMapper>,
}

impl Mapping {
    pub(super) fn candidate(&self, base: SocketAddr) -> Option<str0m::Candidate> {
        let ip = self.port.external_ip;
        let [a, b, _, _] = ip.octets();
        if ip.is_private()
            || (a == 100 && (64..=127).contains(&b))
            || ip.is_loopback()
            || ip.is_link_local()
            || ip.is_unspecified()
            || ip.is_multicast()
            || ip.is_documentation()
            || a == 0
            || a >= 240
            || (a == 198 && (b == 18 || b == 19))
            || (a == 192 && b == 0 && ip.octets()[2] == 0)
            || self.port.external_port == 0
            || self.port.internal_port != base.port()
            || self.port.lease.is_zero()
        {
            return None;
        }
        str0m::Candidate::server_reflexive((ip, self.port.external_port).into(), base, "udp").ok()
    }
}

impl Drop for Mapping {
    fn drop(&mut self) {
        let mapper = self.mapper.clone();
        let id = self.port.id;
        // Drop also runs on cancellation and when an abandoned worker returns.
        // Router deletion must never block the session's runtime thread.
        tokio::task::spawn_blocking(move || mapper.unmap(id));
    }
}

fn log_refusal(refusal: &MapRefusal) {
    static LAST: OnceLock<parking_lot::Mutex<std::collections::HashMap<&'static str, Instant>>> =
        OnceLock::new();
    let mut last = LAST.get_or_init(Default::default).lock();
    let now = Instant::now();
    let kind = refusal.kind();
    if last.get(kind).map_or(true, |at| {
        now.duration_since(*at) >= Duration::from_secs(60)
    }) {
        last.insert(kind, now);
        tracing::info!(
            target: "node_device_session::webrtc",
            "ICE session port mapping refused kind={kind}"
        );
    }
}

/// Start immediately, but never hold up the answer. An abandoned result still
/// owns a Mapping guard, so even a provider returning after timeout is unmapped.
pub(super) fn request_mapping(
    mapper: Arc<dyn SessionPortMapper>,
    internal_port: u16,
    description: String,
    deadline: Duration,
) -> impl std::future::Future<Output = Result<Mapping, MapRefusal>> {
    let (send, receive) = tokio::sync::oneshot::channel();
    let until = tokio::time::Instant::now() + deadline;
    tokio::task::spawn_blocking(move || {
        let result = mapper
            .map(internal_port, &description)
            .map(|port| Mapping { port, mapper });
        // A dropped receiver drops the guard on this blocking worker.
        let _ = send.send(result);
    });
    async move {
        let result = match tokio::time::timeout_at(until, receive).await {
            Ok(Ok(result)) => result,
            Ok(Err(_)) => Err(MapRefusal::Unavailable),
            Err(_) => Err(MapRefusal::Timeout),
        };
        if let Err(refusal) = &result {
            log_refusal(refusal);
        }
        result
    }
}