1use std::fmt;
23use std::future::Future;
24use std::net::IpAddr;
25use std::net::SocketAddr;
26use std::pin::Pin;
27use std::time::Duration;
28
29pub type LocalBoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
31
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub enum Proto {
35 Udp,
36 Tcp,
37 Tls,
38}
39
40impl Proto {
41 pub fn as_str(self) -> &'static str {
43 match self {
44 Proto::Udp => "udp",
45 Proto::Tcp => "tcp",
46 Proto::Tls => "tls",
47 }
48 }
49}
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
53pub enum Direction {
54 Connect,
55 Listen,
56}
57
58impl Direction {
59 pub fn as_str(self) -> &'static str {
61 match self {
62 Direction::Connect => "connect",
63 Direction::Listen => "listen",
64 }
65 }
66}
67
68#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
73#[non_exhaustive]
74pub enum ReachKind {
75 IceServer,
77 IceServerResolved,
79 RemoteCandidate,
82 SendTo,
85 TcpDial,
87 Bind,
89 Mdns,
92}
93
94impl ReachKind {
95 pub fn as_str(self) -> &'static str {
99 match self {
100 ReachKind::IceServer => "iceServer",
101 ReachKind::IceServerResolved => "iceServerResolved",
102 ReachKind::RemoteCandidate => "remoteCandidate",
103 ReachKind::SendTo => "sendTo",
104 ReachKind::TcpDial => "tcpDial",
105 ReachKind::Bind => "bind",
106 ReachKind::Mdns => "mdns",
107 }
108 }
109}
110
111#[derive(Clone, Debug, PartialEq, Eq, Hash)]
114pub enum Host {
115 Name(String),
116 Ip(IpAddr),
117}
118
119impl fmt::Display for Host {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 match self {
122 Host::Name(name) => f.write_str(name),
123 Host::Ip(ip) => ip.fmt(f),
124 }
125 }
126}
127
128#[derive(Clone, Debug, PartialEq, Eq, Hash)]
130pub struct Reach {
131 pub kind: ReachKind,
132 pub dir: Direction,
133 pub proto: Proto,
134 pub host: Host,
135 pub port: Option<u16>,
138 pub resolved_from: Option<String>,
141}
142
143impl Reach {
144 pub fn connect(kind: ReachKind, proto: Proto, addr: SocketAddr) -> Self {
146 Self {
147 kind,
148 dir: Direction::Connect,
149 proto,
150 host: Host::Ip(addr.ip()),
151 port: Some(addr.port()),
152 resolved_from: None,
153 }
154 }
155
156 pub fn bind(kind: ReachKind, proto: Proto, ip: IpAddr) -> Self {
158 Self {
159 kind,
160 dir: Direction::Listen,
161 proto,
162 host: Host::Ip(ip),
163 port: None,
164 resolved_from: None,
165 }
166 }
167
168 pub fn ice_server(proto: Proto, host: &str, port: u16) -> Self {
170 Self {
171 kind: ReachKind::IceServer,
172 dir: Direction::Connect,
173 proto,
174 host: Host::Name(host.to_string()),
175 port: Some(port),
176 resolved_from: None,
177 }
178 }
179
180 pub fn socket_addr(&self) -> Option<SocketAddr> {
182 match (&self.host, self.port) {
183 (Host::Ip(ip), Some(port)) => Some(SocketAddr::new(*ip, port)),
184 _ => None,
185 }
186 }
187}
188
189#[derive(Clone, Debug, PartialEq, Eq)]
191pub enum Verdict {
192 Allow,
193 Deny(String),
198}
199
200impl Verdict {
201 pub fn is_allow(&self) -> bool {
202 matches!(self, Verdict::Allow)
203 }
204
205 pub fn into_result(self) -> Result<(), String> {
207 match self {
208 Verdict::Allow => Ok(()),
209 Verdict::Deny(message) => Err(message),
210 }
211 }
212}
213
214pub const DEFAULT_ASK_TIMEOUT: Duration = Duration::from_secs(10);
217
218pub trait NetGate {
223 fn decide(&self, reach: &Reach) -> Option<Verdict>;
228
229 fn ask(&self, reach: Reach) -> LocalBoxFuture<'static, Verdict> {
236 let verdict = self.decide(&reach).unwrap_or_else(|| pending(&reach));
237 Box::pin(std::future::ready(verdict))
238 }
239
240 fn interfaces(&self) -> Option<Verdict>;
243
244 fn ask_interfaces(&self) -> LocalBoxFuture<'static, Verdict> {
247 let verdict = self.interfaces().unwrap_or_else(|| {
248 Verdict::Deny("The network interfaces were not allowed".to_string())
249 });
250 Box::pin(std::future::ready(verdict))
251 }
252
253 fn ask_timeout(&self) -> Duration {
257 DEFAULT_ASK_TIMEOUT
258 }
259}
260
261#[derive(Clone, Debug, PartialEq, Eq)]
267pub struct GateToken {
268 reach: Reach,
269}
270
271impl GateToken {
272 pub(crate) fn new(reach: Reach) -> Self {
274 Self { reach }
275 }
276
277 pub fn reach(&self) -> &Reach {
279 &self.reach
280 }
281}
282
283#[derive(Clone, Debug, PartialEq, Eq, Hash)]
285pub(crate) struct ReachKey {
286 dir: Direction,
287 proto: Proto,
288 host: Host,
289 port: Option<u16>,
290 resolved_from: Option<String>,
291}
292
293impl From<&Reach> for ReachKey {
294 fn from(r: &Reach) -> Self {
295 Self {
296 dir: r.dir,
297 proto: r.proto,
298 host: r.host.clone(),
299 port: r.port,
300 resolved_from: r.resolved_from.clone(),
301 }
302 }
303}
304
305#[derive(Clone, Copy, Debug, Default)]
307pub struct DenyAllGate;
308
309impl NetGate for DenyAllGate {
310 fn decide(&self, reach: &Reach) -> Option<Verdict> {
311 Some(Verdict::Deny(format!(
312 "Requires net access to \"{}\"",
313 describe(reach)
314 )))
315 }
316
317 fn interfaces(&self) -> Option<Verdict> {
318 Some(Verdict::Deny(
319 "Requires sys access to \"networkInterfaces\"".to_string(),
320 ))
321 }
322}
323
324pub(crate) fn pending(reach: &Reach) -> Verdict {
326 Verdict::Deny(format!(
327 "Net access to \"{}\" was not decided",
328 describe(reach)
329 ))
330}
331
332pub(crate) fn describe(reach: &Reach) -> String {
333 match (&reach.host, reach.port) {
334 (Host::Ip(IpAddr::V6(ip)), Some(port)) => format!("[{ip}]:{port}"),
335 (host, Some(port)) => format!("{host}:{port}"),
336 (host, None) => host.to_string(),
337 }
338}
339
340pub(crate) fn interfaces_pending() -> Verdict {
342 Verdict::Deny("The network interfaces were not allowed".to_string())
343}
344
345pub(crate) trait GateExt {
348 fn check(&self, reach: &Reach) -> Result<(), String>;
349 fn check_interfaces(&self) -> Result<(), String>;
350}
351
352impl<G: NetGate + ?Sized> GateExt for G {
353 fn check(&self, reach: &Reach) -> Result<(), String> {
354 self
355 .decide(reach)
356 .unwrap_or_else(|| pending(reach))
357 .into_result()
358 }
359
360 fn check_interfaces(&self) -> Result<(), String> {
361 self
362 .interfaces()
363 .unwrap_or_else(|| {
364 Verdict::Deny("The network interfaces were not allowed".to_string())
365 })
366 .into_result()
367 }
368}