use std::net::{Ipv4Addr, SocketAddr};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};
pub struct MappedSessionPort {
pub id: u64,
pub external_ip: Ipv4Addr,
pub external_port: u16,
pub internal_port: u16,
pub lease: Duration,
}
#[derive(Debug, PartialEq, Eq)]
pub enum MapRefusal {
AutomapOff,
NotPublic,
Limit,
Refused(String),
Timeout,
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",
}
}
}
pub trait SessionPortMapper: Send + Sync {
fn map(&self, internal_port: u16, description: &str) -> Result<MappedSessionPort, MapRefusal>;
fn unmap(&self, id: u64);
}
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;
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}"
);
}
}
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 });
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
}
}