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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
#[cfg(test)]
use crate::ambient_authority;
use crate::net::pool::net::ToSocketAddrs;
use crate::AmbientAuthority;
use ipnet::IpNet;
#[cfg(test)]
use std::str::FromStr;
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,
    ports_start: u16,
    ports_end: Option<u16>,
}

impl IpGrant {
    fn contains(&self, addr: &net::SocketAddr) -> bool {
        if !self.set.contains(addr.ip()) {
            return false;
        }

        let port = addr.port();
        if port < self.ports_start {
            return false;
        }
        if let Some(ports_end) = self.ports_end {
            if port >= ports_end {
                return false;
            }
        }

        true
    }
}

/// 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.
///
/// `Pool` implements `Clone`, which creates new independent entities that
/// carry the full authority of the originals. This means that in a borrow
/// of a `Pool`, the scope of the authority is not necessarily limited to
/// the scope of the borrow.
///
/// Similarly, the [`cap_net_ext::PoolExt`] class allows creating "binder"
/// and "connecter" objects which represent capabilities to bind and
/// connect to addresses.
///
/// [`cap_net_ext::PoolExt`]: https://docs.rs/cap-net-ext/latest/cap_net_ext/trait.PoolExt.html
#[derive(Clone, Default)]
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 addresses to the pool.
    ///
    /// # Ambient Authority
    ///
    /// This function allows ambient access to any IP address.
    pub fn insert<A: ToSocketAddrs>(
        &mut self,
        addrs: A,
        ambient_authority: AmbientAuthority,
    ) -> io::Result<()> {
        for addr in addrs.to_socket_addrs()? {
            self.insert_socket_addr(addr, ambient_authority);
        }
        Ok(())
    }

    /// 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,
        ambient_authority: AmbientAuthority,
    ) {
        self.insert_ip_net(addr.ip().into(), addr.port(), ambient_authority)
    }

    /// Add a range of network addresses, accepting any port, to the pool.
    ///
    /// # Ambient Authority
    ///
    /// This function allows ambient access to any IP address.
    pub fn insert_ip_net_port_any(
        &mut self,
        ip_net: ipnet::IpNet,
        ambient_authority: AmbientAuthority,
    ) {
        self.insert_ip_net_port_range(ip_net, 0, None, ambient_authority)
    }

    /// Add a range of network addresses, accepting a range of ports, to the
    /// pool.
    ///
    /// This grants access to the port range starting at `ports_start` and,
    /// if `ports_end` is provided, ending before `ports_end`.
    ///
    /// # Ambient Authority
    ///
    /// This function allows ambient access to any IP address.
    pub fn insert_ip_net_port_range(
        &mut self,
        ip_net: ipnet::IpNet,
        ports_start: u16,
        ports_end: Option<u16>,
        ambient_authority: AmbientAuthority,
    ) {
        let _ = ambient_authority;

        self.grants.push(IpGrant {
            set: AddrSet::Net(ip_net),
            ports_start,
            ports_end,
        })
    }

    /// 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,
        ambient_authority: AmbientAuthority,
    ) {
        self.insert_ip_net_port_range(ip_net, port, port.checked_add(1), ambient_authority)
    }

    /// 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] = &[];

/// Return an error for reporting that no socket addresses were available.
#[cold]
pub fn no_socket_addrs() -> io::Error {
    std::net::TcpListener::bind(&NO_SOCKET_ADDRS).unwrap_err()
}

#[test]
fn test_empty() {
    let p = Pool::new();

    p.check_addr(&net::SocketAddr::from_str("[::1]:0").unwrap())
        .unwrap_err();
    p.check_addr(&net::SocketAddr::from_str("[::1]:1023").unwrap())
        .unwrap_err();
    p.check_addr(&net::SocketAddr::from_str("[::1]:1024").unwrap())
        .unwrap_err();
    p.check_addr(&net::SocketAddr::from_str("[::1]:8080").unwrap())
        .unwrap_err();
    p.check_addr(&net::SocketAddr::from_str("[::1]:65535").unwrap())
        .unwrap_err();
}

#[test]
fn test_port_any() {
    let mut p = Pool::new();
    p.insert_ip_net_port_any(
        IpNet::new(net::IpAddr::V6(net::Ipv6Addr::LOCALHOST), 48).unwrap(),
        ambient_authority(),
    );

    p.check_addr(&net::SocketAddr::from_str("[::1]:0").unwrap())
        .unwrap();
    p.check_addr(&net::SocketAddr::from_str("[::1]:1023").unwrap())
        .unwrap();
    p.check_addr(&net::SocketAddr::from_str("[::1]:1024").unwrap())
        .unwrap();
    p.check_addr(&net::SocketAddr::from_str("[::1]:8080").unwrap())
        .unwrap();
    p.check_addr(&net::SocketAddr::from_str("[::1]:65535").unwrap())
        .unwrap();
}

#[test]
fn test_port_range() {
    let mut p = Pool::new();
    p.insert_ip_net_port_range(
        IpNet::new(net::IpAddr::V6(net::Ipv6Addr::LOCALHOST), 48).unwrap(),
        1024,
        Some(9000),
        ambient_authority(),
    );

    p.check_addr(&net::SocketAddr::from_str("[::1]:0").unwrap())
        .unwrap_err();
    p.check_addr(&net::SocketAddr::from_str("[::1]:1023").unwrap())
        .unwrap_err();
    p.check_addr(&net::SocketAddr::from_str("[::1]:1024").unwrap())
        .unwrap();
    p.check_addr(&net::SocketAddr::from_str("[::1]:8080").unwrap())
        .unwrap();
    p.check_addr(&net::SocketAddr::from_str("[::1]:65535").unwrap())
        .unwrap_err();
}

#[test]
fn test_port_one() {
    let mut p = Pool::new();
    p.insert_ip_net(
        IpNet::new(net::IpAddr::V6(net::Ipv6Addr::LOCALHOST), 48).unwrap(),
        8080,
        ambient_authority(),
    );

    p.check_addr(&net::SocketAddr::from_str("[::1]:0").unwrap())
        .unwrap_err();
    p.check_addr(&net::SocketAddr::from_str("[::1]:1023").unwrap())
        .unwrap_err();
    p.check_addr(&net::SocketAddr::from_str("[::1]:1024").unwrap())
        .unwrap_err();
    p.check_addr(&net::SocketAddr::from_str("[::1]:8080").unwrap())
        .unwrap();
    p.check_addr(&net::SocketAddr::from_str("[::1]:65535").unwrap())
        .unwrap_err();
}

#[test]
fn test_addrs() {
    let mut p = Pool::new();
    match p.insert("example.com:80", ambient_authority()) {
        Ok(()) => (),
        Err(_) => return, // not all test environments have DNS
    }

    p.check_addr(&net::SocketAddr::from_str("[::1]:0").unwrap())
        .unwrap_err();
    p.check_addr(&net::SocketAddr::from_str("[::1]:1023").unwrap())
        .unwrap_err();
    p.check_addr(&net::SocketAddr::from_str("[::1]:1024").unwrap())
        .unwrap_err();
    p.check_addr(&net::SocketAddr::from_str("[::1]:8080").unwrap())
        .unwrap_err();
    p.check_addr(&net::SocketAddr::from_str("[::1]:65535").unwrap())
        .unwrap_err();

    for addr in "example.com:80".to_socket_addrs().unwrap() {
        p.check_addr(&addr).unwrap();
    }
}