wasmtime_wasi/
net.rs

1use std::future::Future;
2use std::net::SocketAddr;
3use std::pin::Pin;
4use std::sync::Arc;
5
6/// Value taken from rust std library.
7pub const DEFAULT_TCP_BACKLOG: u32 = 128;
8
9pub struct Network {
10    pub socket_addr_check: SocketAddrCheck,
11    pub allow_ip_name_lookup: bool,
12}
13
14impl Network {
15    pub async fn check_socket_addr(
16        &self,
17        addr: SocketAddr,
18        reason: SocketAddrUse,
19    ) -> std::io::Result<()> {
20        self.socket_addr_check.check(addr, reason).await
21    }
22}
23
24/// A check that will be called for each socket address that is used of whether the address is permitted.
25#[derive(Clone)]
26pub struct SocketAddrCheck(
27    pub(crate)  Arc<
28        dyn Fn(SocketAddr, SocketAddrUse) -> Pin<Box<dyn Future<Output = bool> + Send + Sync>>
29            + Send
30            + Sync,
31    >,
32);
33
34impl SocketAddrCheck {
35    pub async fn check(&self, addr: SocketAddr, reason: SocketAddrUse) -> std::io::Result<()> {
36        if (self.0)(addr, reason).await {
37            Ok(())
38        } else {
39            Err(std::io::Error::new(
40                std::io::ErrorKind::PermissionDenied,
41                "An address was not permitted by the socket address check.",
42            ))
43        }
44    }
45}
46
47impl Default for SocketAddrCheck {
48    fn default() -> Self {
49        Self(Arc::new(|_, _| Box::pin(async { false })))
50    }
51}
52
53/// The reason what a socket address is being used for.
54#[derive(Clone, Copy, Debug)]
55pub enum SocketAddrUse {
56    /// Binding TCP socket
57    TcpBind,
58    /// Connecting TCP socket
59    TcpConnect,
60    /// Binding UDP socket
61    UdpBind,
62    /// Connecting UDP socket
63    UdpConnect,
64    /// Sending datagram on non-connected UDP socket
65    UdpOutgoingDatagram,
66}
67
68#[derive(Copy, Clone)]
69pub enum SocketAddressFamily {
70    Ipv4,
71    Ipv6,
72}