logo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use ambient_authority::AmbientAuthority;
use ipnet::IpNet;
use std::{io, net};

// TODO: Perhaps we should have our own version of `ToSocketAddrs` which
// returns hostnames rather than parsing them, so we can add unresolved
// hostnames to the pool.
#[derive(Clone)]
enum AddrSet {
    Net(IpNet),
}

impl AddrSet {
    fn contains(&self, addr: net::IpAddr) -> bool {
        match self {
            Self::Net(ip_net) => ip_net.contains(&addr),
        }
    }
}

#[derive(Clone)]
struct IpGrant {
    set: AddrSet,
    port: u16, // TODO: IANA port names, TODO: range
}

impl IpGrant {
    fn contains(&self, addr: &net::SocketAddr) -> bool {
        self.set.contains(addr.ip()) && addr.port() == self.port
    }
}

/// A representation of a set of network resources that may be accessed.
///
/// This is presently a very simple concept, though it could grow in
/// sophistication in the future.
#[derive(Clone)]
pub struct Pool {
    // TODO: when compiling for WASI, use WASI-specific handle instead
    grants: Vec<IpGrant>,
}

impl Pool {
    /// Construct a new empty pool.
    pub fn new() -> Self {
        Self { grants: Vec::new() }
    }

    /// Add a range of network addresses with a specific port to the pool.
    ///
    /// # Ambient Authority
    ///
    /// This function allows ambient access to any IP address.
    pub fn insert_ip_net(&mut self, ip_net: ipnet::IpNet, port: u16, _: AmbientAuthority) {
        self.grants.push(IpGrant {
            set: AddrSet::Net(ip_net),
            port,
        })
    }

    /// Add a specific [`net::SocketAddr`] to the pool.
    ///
    /// # Ambient Authority
    ///
    /// This function allows ambient access to any IP address.
    pub fn insert_socket_addr(&mut self, addr: net::SocketAddr, _: AmbientAuthority) {
        self.grants.push(IpGrant {
            set: AddrSet::Net(addr.ip().into()),
            port: addr.port(),
        })
    }

    /// Check whether the given address is within the pool.
    pub fn check_addr(&self, addr: &net::SocketAddr) -> io::Result<()> {
        if self.grants.iter().any(|grant| grant.contains(addr)) {
            Ok(())
        } else {
            Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "An address was outside the pool",
            ))
        }
    }
}

/// An empty array of `SocketAddr`s.
pub const NO_SOCKET_ADDRS: &[net::SocketAddr] = &[];