node_device_session/webrtc/
portmap.rs1use std::net::{Ipv4Addr, SocketAddr};
3use std::sync::{Arc, OnceLock};
4use std::time::{Duration, Instant};
5
6pub struct MappedSessionPort {
8 pub id: u64,
10 pub external_ip: Ipv4Addr,
12 pub external_port: u16,
14 pub internal_port: u16,
16 pub lease: Duration,
18}
19
20#[derive(Debug, PartialEq, Eq)]
22pub enum MapRefusal {
23 AutomapOff,
25 NotPublic,
27 Limit,
29 Refused(String),
31 Timeout,
33 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
50pub trait SessionPortMapper: Send + Sync {
52 fn map(&self, internal_port: u16, description: &str) -> Result<MappedSessionPort, MapRefusal>;
54 fn unmap(&self, id: u64);
56}
57
58pub 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 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
125pub(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 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}