JFLib

plat/net.rs#

Source: lib/plat/net.rs

net -- TCP, UDP and Unix domain sockets (IPv4 and IPv6) with timeouts

  IpAddr / SocketAddr: parse ("10.0.0.5:9443", "[::1]:80", "[fe80::1%eth0]:53"), Display,
            loopback / unspecified; SocketAddr::scope: the IPv6 zone (sin6_scope_id, the
            interface index of a link-local address; 0 none)
  ip_scope_parse("fe80::1%eth0") -> (address, interface index): a zone by name (Linux:
            /sys/class/net/NAME/ifindex, else ioctl SIOCGIFINDEX; Windows: if_nametoindex) or
            by number ("%2")
  local_addrs() -> this computer's addresses (port 0, link-local ones with their scope):
            Windows GetAdaptersAddresses; Linux and Android SIOCGIFCONF (IPv4),
            /proc/net/if_inet6 (IPv6; an Android app may not read it: then IPv4 only)
  dns_servers() -> (Windows) the DNS servers of the adapters that are up, with their scope
            (the well-known site-local fec0:0:0:ffff::1..3 Windows lists without IPv6 DNS
            are left out); Linux: empty (netio::dns reads /etc/resolv.conf); Android: empty
            (netd keeps them, names go through getaddrinfo)
  TcpListener::bind(&addr) / accept() / accept_timeout(ms) / local_addr()
  TcpStream::connect(&addr, timeout_ms) / read / write / write_all / read_exact,
            set_read_timeout / set_write_timeout (ms, None = block), set_nodelay,
            shutdown_write, peer_addr / local_addr, wait_readable(ms)
  UdpSocket::bind / send_to / recv_from(buf, timeout_ms); answers_to(addr), answer_peers()
            (the answers a socket net.listen allows may send without net.connect, AnswerSet)
  UnixListener::bind(path) / accept() / accept_timeout(ms); connect_unix(path, timeout_ms)
            (bind removes only a socket file nobody listens on; the drop only its own)
            -> UnixStream (the stream calls of TcpStream; addresses and nodelay do not apply)
            Linux, and Windows 10 1803 and later (AF_UNIX); not on Android yet (plat::fs, AN3)
  resolve(host, port): numeric addresses, "localhost" and names under .localhost (the loopback
            addresses, RFC 6761; with a final dot as well); Windows, macOS, iOS and Android
            also the system resolver (GetAddrInfoW, getaddrinfo; on Android Bionic's, which asks
            netd: private DNS, VPNs, the network of the app).  Linux: other names NotFound, since
            there is no libc here: netio::dns resolves them (/etc/hosts, the name servers).
  NetError: the kinds callers act on, with the OS code

(G7d) Everywhere: the addresses, NetError and host_port.  The sockets, names and interfaces are
Windows', Linux's, Apple's and Android's; the browser has WebSocket instead (web_net.rs: the
page's WebSocket through the JS host, net.connect checked on the URL's host and port).

Android (docs/ANDROID.md AN2) takes the Linux sockets with rt::kernel's numbers, names through
Bionic's getaddrinfo (there is no /etc/resolv.conf), interfaces without netlink and without MAC
addresses.  An app whose manifest lacks android.permission.INTERNET gets no IPv4 or IPv6 socket:
socket() answers EACCES where the kernel checks the group inet, EPERM where netd's eBPF program
checks (Android 15 on the emulator).  Either becomes NetErrorKind::Denied with that code and a
word on the manifest (NetError::no_internet; a lookup that fails checks for it as well).

The app's permissions (policy.rs, net.connect / net.listen) are checked before connect,
bind, send_to and a name lookup; Unix sockets follow the file rules (fs.write on the path).
A refusal is NetErrorKind::Denied.  A UDP socket whose address net.listen allows may answer
without net.connect: send_to an address it received a datagram from in the last 60 s
(AnswerSet, at most 1024 addresses per socket: forged sources cannot grow it).

Timeouts are readiness waits (WSAPoll / poll) before each call, never SO_RCVTIMEO: after a
timed-out blocking receive Windows leaves the connection in an undefined state.  Sockets are
not inherited by child processes; sends never raise SIGPIPE.  Every method takes &self, so
one thread may read while another writes (Arc<TcpStream>).
  • enum IpAddr
    • V4([u8; 4])
    • V6([u8; 16])

impl IpAddr

  • const LOCALHOST_V4: IpAddr = IpAddr::V4([127, 0, 0, 1])

  • const UNSPECIFIED_V4: IpAddr = IpAddr::V4([0, 0, 0, 0])

  • const LOCALHOST_V6: IpAddr = IpAddr::V6([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])

  • fn is_loopback(&self) -> bool

  • fn is_unspecified(&self) -> bool

  • fn mapped_v4(&self) -> Option<IpAddr> the IPv4 address inside an IPv4-mapped IPv6 address (::ffff:a.b.c.d)

  • fn parse(s: &str) -> Option<IpAddr> "192.168.1.2" or "fe80::1" (RFC 5952 shortening)

  • struct SocketAddr an IP address and a port

    • ip: IpAddr
    • port: u16
    • scope: u32 -- IPv6: the zone of a link-local (or other scoped) address, the interface index the socket address carries as sin6_scope_id (0: none)

impl SocketAddr

  • const fn new(ip: IpAddr, port: u16) -> SocketAddr

  • const fn with_scope(ip: IpAddr, port: u16, scope: u32) -> SocketAddr an IPv6 address with its zone (the interface index; ip_scope_parse)

  • fn parse(s: &str) -> Option<SocketAddr> "1.2.3.4:80", "[::1]:80", "[fe80::1%eth0]:53" (a zone by name or number)

  • fn ip_scope_parse(s: &str) -> Option<(IpAddr, u32)> an IP address with an optional IPv6 zone ("fe80::1%eth0", "fe80::1%2") -> the address and the zone's interface index (0: none). None: not an address, or a zone that names no interface of this computer (a zone on an IPv4 address too)

  • fn if_index(name: &str) -> Option<u32> the index of a network interface by its name (Linux: "eth0"; Windows: the NDIS name, e.g. "ethernet_32769") -> None: there is none

  • fn local_addrs() -> Vec<SocketAddr> this computer's addresses (port 0; link-local IPv6 addresses with their scope), see the top of this file

  • fn dns_servers() -> Vec<SocketAddr> (Windows) the DNS servers of the network adapters that are up (port 53, link-local ones with their scope), in the system's adapter order; Linux: empty (netio::dns reads /etc/resolv.conf); Android: empty (netd keeps them)

  • enum NetErrorKind

    • TimedOut
    • Refused
    • Reset
    • AddrInUse
    • AddrNotAvailable
    • Unreachable
    • NotFound
    • Eof -- the peer closed the connection before all bytes arrived (read_exact)
    • Denied -- the app's permissions (apps/NAME/PERMISSIONS) do not allow the address or name; on Android with code 13 (EACCES) or 1 (EPERM): the app's manifest lacks android.permission.INTERNET (NetError::no_internet)
    • Other
  • struct NetError

    • kind: NetErrorKind
    • code: i32 -- the OS error code (0 when the library detected the condition)

impl NetError

  • const fn new(kind: NetErrorKind, code: i32) -> NetError

  • fn no_internet(&self) -> bool (Android) the app's manifest lacks android.permission.INTERNET: Android refuses it every IPv4 and IPv6 socket (EACCES or EPERM), and the system's resolver every name. The manifest cargo jflib android writes has it when the app has no PERMISSIONS or names net.connect or net.listen there; an own AndroidManifest.xml needs it too. Always false elsewhere

  • type NetResult<T> = Result<T, NetError>

  • struct TcpListener

impl TcpListener

  • fn bind(addr: &SocketAddr) -> NetResult<TcpListener> listen on an address (port 0: any free port, see local_addr)

  • fn local_addr(&self) -> NetResult<SocketAddr>

  • fn accept(&self) -> NetResult<(TcpStream, SocketAddr)> the next connection (blocks)

  • fn accept_timeout(&self, ms: u32) -> NetResult<Option<(TcpStream, SocketAddr)>> the next connection within ms milliseconds (None: none came)

  • struct TcpStream

impl TcpStream

  • fn connect(addr: &SocketAddr, timeout_ms: u32) -> NetResult<TcpStream> connect within timeout_ms (0: the system's own timeout)

  • fn connect_any(addrs: &[SocketAddr], timeout_ms: u32) -> NetResult<TcpStream> connect to the first reachable of several addresses

  • fn set_read_timeout(&self, ms: Option<u32>) read timeout in ms for every read (None: block)

  • fn set_write_timeout(&self, ms: Option<u32>)

  • fn set_nodelay(&self, on: bool) -> NetResult<()>

  • fn set_keepalive(&self, on: bool) -> NetResult<()>

  • fn peer_uid(&self) -> Option<u32> the user id of the process at the other end of a Unix socket, as the kernel recorded it when it connected or listened (Linux SO_PEERCRED, macOS getpeereid): not what the socket file's owner claims. Unix sockets only (TCP has no meaningful answer); None on Windows

  • fn read(&self, buf: &mut [u8]) -> NetResult<usize> up to buf.len() bytes; Ok(0) = the peer closed its side

  • fn read_exact(&self, buf: &mut [u8]) -> NetResult<()> exactly buf.len() bytes (NetErrorKind::Eof if the peer closes first)

  • fn write(&self, buf: &[u8]) -> NetResult<usize>

  • fn write_all(&self, mut buf: &[u8]) -> NetResult<()>

  • fn wait_readable(&self, ms: u32) -> NetResult<bool> whether data (or the end) is waiting, within ms

  • fn shutdown_write(&self) -> NetResult<()> no more writes from this side (the peer reads the end)

  • fn peer_addr(&self) -> NetResult<SocketAddr>

  • fn local_addr(&self) -> NetResult<SocketAddr>

  • struct AnswerSet (permissions) the peers a UDP socket that net.listen allows may answer without a net.connect rule: the addresses it received a datagram from in the last [AnswerSet::KEEP_MS] (a datagram renews its address; sending to it does not). At most [AnswerSet::MAX] of them: two generations of MAX / 2, a full one becomes the old one and the old one goes (so does a generation older than KEEP_MS). Source addresses are not proven: whoever can forge one can open the way to that address for this socket -- as any UDP server answers whoever writes -- but not grow the set past MAX; a flood of forged addresses pushes older ones out, and their peers are answered again after their next datagram. UdpSocket keeps one when a manifest restricts the process ([UdpSocket::bind]); the times are the caller's (ms of a monotonic clock), so tests drive it directly.

impl AnswerSet

  • const MAX: usize = 1024 the most addresses kept (two generations of half)

  • const KEEP_MS: u64 = 60_000 how long an address may be answered after its last datagram (ms)

  • fn new(now_ms: u64) -> AnswerSet

  • fn heard(&mut self, from: &SocketAddr, now_ms: u64) a datagram came from from (a port of 0 or an unspecified address is no peer)

  • fn may_answer(&mut self, to: &SocketAddr, now_ms: u64) -> bool whether to sent a datagram within KEEP_MS (and is still kept)

  • fn len(&self) -> usize the addresses kept now (expired ones included until their generation goes)

  • fn is_empty(&self) -> bool

  • struct UdpSocket

impl UdpSocket

  • fn bind(addr: &SocketAddr) -> NetResult<UdpSocket> a socket on addr; a fixed port needs net.listen, port 0 (a client's) does not. A socket whose address net.listen allows (a fixed port through the check, port 0 when a rule covers it: checked quietly) may answer the addresses it receives datagrams from without a net.connect rule (an [AnswerSet] per socket)

  • fn send_to(&self, buf: &[u8], to: &SocketAddr) -> NetResult<usize> one datagram to to: an answer to an address this socket heard from (see bind), else net.connect decides

  • fn recv_from(&self, buf: &mut [u8], timeout_ms: u32) -> NetResult<(usize, SocketAddr)> one datagram within timeout_ms (0: block)

  • fn local_addr(&self) -> NetResult<SocketAddr>

  • fn answers_to(&self, to: &SocketAddr) -> bool (permissions) whether a datagram to to is an answer this socket may send without net.connect: it heard from to within AnswerSet::KEEP_MS, and inside a plugin's scope the plugin's net.listen covers the socket's address

  • fn answer_peers(&self) -> Option<usize> (permissions, tests) the addresses this socket keeps for answers; None: it keeps none (no manifest, or its address is not one net.listen allows)

  • type UnixStream = TcpStream a connected Unix domain stream socket (the stream calls of TcpStream)

  • struct UnixListener

impl UnixListener

  • fn bind(path: &str) -> NetResult<UnixListener> listen on a socket file. A socket file left at path by a listener that is gone (a connection to it is refused) is removed first; anything else there -- a file, a folder, a socket that is listened on -- stays, and bind fails (AddrInUse; a folder on Windows: Other).

  • fn path(&self) -> &str

  • fn accept(&self) -> NetResult<UnixStream>

  • fn accept_timeout(&self, ms: u32) -> NetResult<Option<UnixStream>> the next connection within ms milliseconds (None: none came)

  • fn connect_unix(path: &str, timeout_ms: u32) -> NetResult<UnixStream> connect to a socket file within timeout_ms (0: block)

  • fn resolve(host: &str, port: u16) -> NetResult<Vec<SocketAddr>> the addresses of a host: numeric forms, "localhost" and names under .localhost, with a final dot as well (both loopback addresses, RFC 6761 6.3, as netio::dns answers them) everywhere; on Windows, macOS, iOS and Android other names through the system resolver, on Linux NotFound for them (no libc here: netio::dns::resolve reads /etc/hosts and asks the name servers). The addresses of a name are registered with the app's rules (policy::net_resolved), so a rule for the name (app.localhost:8080) covers connections to them

  • fn hostname() -> String the host name of this computer

  • fn host_port(host: &str, port: u16) -> String "host:port" with brackets around IPv6 literals

Source: docs/API.md in the JFLib repository.