use std::fmt;
use std::future::Future;
use std::net::IpAddr;
use std::net::SocketAddr;
use std::pin::Pin;
use std::time::Duration;
pub type LocalBoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Proto {
Udp,
Tcp,
Tls,
}
impl Proto {
pub fn as_str(self) -> &'static str {
match self {
Proto::Udp => "udp",
Proto::Tcp => "tcp",
Proto::Tls => "tls",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Direction {
Connect,
Listen,
}
impl Direction {
pub fn as_str(self) -> &'static str {
match self {
Direction::Connect => "connect",
Direction::Listen => "listen",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ReachKind {
IceServer,
IceServerResolved,
RemoteCandidate,
SendTo,
TcpDial,
Bind,
Mdns,
}
impl ReachKind {
pub fn as_str(self) -> &'static str {
match self {
ReachKind::IceServer => "iceServer",
ReachKind::IceServerResolved => "iceServerResolved",
ReachKind::RemoteCandidate => "remoteCandidate",
ReachKind::SendTo => "sendTo",
ReachKind::TcpDial => "tcpDial",
ReachKind::Bind => "bind",
ReachKind::Mdns => "mdns",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Host {
Name(String),
Ip(IpAddr),
}
impl fmt::Display for Host {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Host::Name(name) => f.write_str(name),
Host::Ip(ip) => ip.fmt(f),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Reach {
pub kind: ReachKind,
pub dir: Direction,
pub proto: Proto,
pub host: Host,
pub port: Option<u16>,
pub resolved_from: Option<String>,
}
impl Reach {
pub fn connect(kind: ReachKind, proto: Proto, addr: SocketAddr) -> Self {
Self {
kind,
dir: Direction::Connect,
proto,
host: Host::Ip(addr.ip()),
port: Some(addr.port()),
resolved_from: None,
}
}
pub fn bind(kind: ReachKind, proto: Proto, ip: IpAddr) -> Self {
Self {
kind,
dir: Direction::Listen,
proto,
host: Host::Ip(ip),
port: None,
resolved_from: None,
}
}
pub fn ice_server(proto: Proto, host: &str, port: u16) -> Self {
Self {
kind: ReachKind::IceServer,
dir: Direction::Connect,
proto,
host: Host::Name(host.to_string()),
port: Some(port),
resolved_from: None,
}
}
pub fn socket_addr(&self) -> Option<SocketAddr> {
match (&self.host, self.port) {
(Host::Ip(ip), Some(port)) => Some(SocketAddr::new(*ip, port)),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Verdict {
Allow,
Deny(String),
}
impl Verdict {
pub fn is_allow(&self) -> bool {
matches!(self, Verdict::Allow)
}
pub fn into_result(self) -> Result<(), String> {
match self {
Verdict::Allow => Ok(()),
Verdict::Deny(message) => Err(message),
}
}
}
pub const DEFAULT_ASK_TIMEOUT: Duration = Duration::from_secs(10);
pub trait NetGate {
fn decide(&self, reach: &Reach) -> Option<Verdict>;
fn ask(&self, reach: Reach) -> LocalBoxFuture<'static, Verdict> {
let verdict = self.decide(&reach).unwrap_or_else(|| pending(&reach));
Box::pin(std::future::ready(verdict))
}
fn interfaces(&self) -> Option<Verdict>;
fn ask_interfaces(&self) -> LocalBoxFuture<'static, Verdict> {
let verdict = self.interfaces().unwrap_or_else(|| {
Verdict::Deny("The network interfaces were not allowed".to_string())
});
Box::pin(std::future::ready(verdict))
}
fn ask_timeout(&self) -> Duration {
DEFAULT_ASK_TIMEOUT
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GateToken {
reach: Reach,
}
impl GateToken {
pub(crate) fn new(reach: Reach) -> Self {
Self { reach }
}
pub fn reach(&self) -> &Reach {
&self.reach
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct ReachKey {
dir: Direction,
proto: Proto,
host: Host,
port: Option<u16>,
resolved_from: Option<String>,
}
impl From<&Reach> for ReachKey {
fn from(r: &Reach) -> Self {
Self {
dir: r.dir,
proto: r.proto,
host: r.host.clone(),
port: r.port,
resolved_from: r.resolved_from.clone(),
}
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct DenyAllGate;
impl NetGate for DenyAllGate {
fn decide(&self, reach: &Reach) -> Option<Verdict> {
Some(Verdict::Deny(format!(
"Requires net access to \"{}\"",
describe(reach)
)))
}
fn interfaces(&self) -> Option<Verdict> {
Some(Verdict::Deny(
"Requires sys access to \"networkInterfaces\"".to_string(),
))
}
}
pub(crate) fn pending(reach: &Reach) -> Verdict {
Verdict::Deny(format!(
"Net access to \"{}\" was not decided",
describe(reach)
))
}
pub(crate) fn describe(reach: &Reach) -> String {
match (&reach.host, reach.port) {
(Host::Ip(IpAddr::V6(ip)), Some(port)) => format!("[{ip}]:{port}"),
(host, Some(port)) => format!("{host}:{port}"),
(host, None) => host.to_string(),
}
}
pub(crate) fn interfaces_pending() -> Verdict {
Verdict::Deny("The network interfaces were not allowed".to_string())
}
pub(crate) trait GateExt {
fn check(&self, reach: &Reach) -> Result<(), String>;
fn check_interfaces(&self) -> Result<(), String>;
}
impl<G: NetGate + ?Sized> GateExt for G {
fn check(&self, reach: &Reach) -> Result<(), String> {
self
.decide(reach)
.unwrap_or_else(|| pending(reach))
.into_result()
}
fn check_interfaces(&self) -> Result<(), String> {
self
.interfaces()
.unwrap_or_else(|| {
Verdict::Deny("The network interfaces were not allowed".to_string())
})
.into_result()
}
}