Skip to main content

node_device_session/webrtc/
portmap.rs

1//! Carrier-neutral session UDP port mapping for ICE srflx candidates.
2use std::net::{Ipv4Addr, SocketAddr};
3use std::sync::{Arc, OnceLock};
4use std::time::{Duration, Instant};
5
6/// A granted external mapping for one ICE session socket.
7pub struct MappedSessionPort {
8    /// Provider-assigned mapping id (used to unmap).
9    pub id: u64,
10    /// External IPv4 advertised as srflx.
11    pub external_ip: Ipv4Addr,
12    /// External UDP port.
13    pub external_port: u16,
14    /// Internal UDP port that must match the session socket.
15    pub internal_port: u16,
16    /// Lease duration; zero leases are rejected.
17    pub lease: Duration,
18}
19
20/// Why a mapping request failed.
21#[derive(Debug, PartialEq, Eq)]
22pub enum MapRefusal {
23    /// Carrier automap is disabled.
24    AutomapOff,
25    /// Node is not a public mapper.
26    NotPublic,
27    /// Concurrent mapping limit reached.
28    Limit,
29    /// Upstream refused with a reason.
30    Refused(String),
31    /// Provider did not answer in time.
32    Timeout,
33    /// No mapper / unavailable.
34    Unavailable,
35}
36
37impl MapRefusal {
38    fn kind(&self) -> &'static str {
39        match self {
40            Self::AutomapOff => "automap_off",
41            Self::NotPublic => "not_public",
42            Self::Limit => "limit",
43            Self::Refused(_) => "refused",
44            Self::Timeout => "timeout",
45            Self::Unavailable => "unavailable",
46        }
47    }
48}
49
50/// Carrier-owned UDP session port mapper (UPnP, relay map, etc.).
51pub trait SessionPortMapper: Send + Sync {
52    /// Blocking, bounded by the provider (typically five seconds). Owns renewal.
53    fn map(&self, internal_port: u16, description: &str) -> Result<MappedSessionPort, MapRefusal>;
54    /// Release a previously granted mapping.
55    fn unmap(&self, id: u64);
56}
57
58/// Mapper that always refuses (host / STUN-only ICE).
59pub struct NoSessionPortMapper;
60
61impl SessionPortMapper for NoSessionPortMapper {
62    fn map(&self, _: u16, _: &str) -> Result<MappedSessionPort, MapRefusal> {
63        Err(MapRefusal::Unavailable)
64    }
65    fn unmap(&self, _: u64) {}
66}
67
68pub(super) struct Mapping {
69    port: MappedSessionPort,
70    mapper: Arc<dyn SessionPortMapper>,
71}
72
73impl Mapping {
74    pub(super) fn candidate(&self, base: SocketAddr) -> Option<str0m::Candidate> {
75        let ip = self.port.external_ip;
76        let [a, b, _, _] = ip.octets();
77        if ip.is_private()
78            || (a == 100 && (64..=127).contains(&b))
79            || ip.is_loopback()
80            || ip.is_link_local()
81            || ip.is_unspecified()
82            || ip.is_multicast()
83            || ip.is_documentation()
84            || a == 0
85            || a >= 240
86            || (a == 198 && (b == 18 || b == 19))
87            || (a == 192 && b == 0 && ip.octets()[2] == 0)
88            || self.port.external_port == 0
89            || self.port.internal_port != base.port()
90            || self.port.lease.is_zero()
91        {
92            return None;
93        }
94        str0m::Candidate::server_reflexive((ip, self.port.external_port).into(), base, "udp").ok()
95    }
96}
97
98impl Drop for Mapping {
99    fn drop(&mut self) {
100        let mapper = self.mapper.clone();
101        let id = self.port.id;
102        // Drop also runs on cancellation and when an abandoned worker returns.
103        // Router deletion must never block the session's runtime thread.
104        tokio::task::spawn_blocking(move || mapper.unmap(id));
105    }
106}
107
108fn log_refusal(refusal: &MapRefusal) {
109    static LAST: OnceLock<parking_lot::Mutex<std::collections::HashMap<&'static str, Instant>>> =
110        OnceLock::new();
111    let mut last = LAST.get_or_init(Default::default).lock();
112    let now = Instant::now();
113    let kind = refusal.kind();
114    if last.get(kind).map_or(true, |at| {
115        now.duration_since(*at) >= Duration::from_secs(60)
116    }) {
117        last.insert(kind, now);
118        tracing::info!(
119            target: "node_device_session::webrtc",
120            "ICE session port mapping refused kind={kind}"
121        );
122    }
123}
124
125/// Start immediately, but never hold up the answer. An abandoned result still
126/// owns a Mapping guard, so even a provider returning after timeout is unmapped.
127pub(super) fn request_mapping(
128    mapper: Arc<dyn SessionPortMapper>,
129    internal_port: u16,
130    description: String,
131    deadline: Duration,
132) -> impl std::future::Future<Output = Result<Mapping, MapRefusal>> {
133    let (send, receive) = tokio::sync::oneshot::channel();
134    let until = tokio::time::Instant::now() + deadline;
135    tokio::task::spawn_blocking(move || {
136        let result = mapper
137            .map(internal_port, &description)
138            .map(|port| Mapping { port, mapper });
139        // A dropped receiver drops the guard on this blocking worker.
140        let _ = send.send(result);
141    });
142    async move {
143        let result = match tokio::time::timeout_at(until, receive).await {
144            Ok(Ok(result)) => result,
145            Ok(Err(_)) => Err(MapRefusal::Unavailable),
146            Err(_) => Err(MapRefusal::Timeout),
147        };
148        if let Err(refusal) = &result {
149            log_refusal(refusal);
150        }
151        result
152    }
153}