oscall 0.1.0

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! `net` on WASI preview 1: the four `sock_*` calls, on sockets the host
//! opened. There is no way to create, bind or connect one, to learn an
//! address or to set an option.

use core::time::Duration;

use crate::io::{IoSlice, IoSliceMut};
use crate::net::{Direction, Family, Opt, Protocol, RawAddr, RecvFlags, SendFlags, Shutdown, Type};
use crate::sys::cvt;
use crate::{ErrorKind, Result};

pub(crate) type RawSocket = i32;

// No address ever reaches the host: these only keep the portable code whole.
pub(crate) const AF_UNIX: u16 = 1;
pub(crate) const AF_INET: u16 = 2;
pub(crate) const AF_INET6: u16 = 10;
pub(crate) const SOCKADDR_LEN_BYTE: bool = false;
pub(crate) const UNIX_PATH_MAX: usize = 108;
pub(crate) const UNIX_ABSTRACT: bool = false;

/// `riflags`.
const RECV_PEEK: i32 = 1;
const RECV_WAITALL: i32 = 2;
/// `roflags`.
const RECV_DATA_TRUNCATED: u16 = 1;
/// `sdflags`.
const SHUT_RD: i32 = 1;
const SHUT_WR: i32 = 2;
/// `fdflags`.
const FDFLAGS_NONBLOCK: u16 = 4;
/// `filetype`.
const FILETYPE_SOCKET_DGRAM: u8 = 5;
const FILETYPE_SOCKET_STREAM: u8 = 6;

/// `iovec` and `ciovec`.
#[repr(C)]
struct IoVec {
    buf: *const u8,
    len: usize,
}

/// `fdstat`.
#[repr(C)]
struct FdStat {
    filetype: u8,
    flags: u16,
    rights_base: u64,
    rights_inheriting: u64,
}

#[link(wasm_import_module = "wasi_snapshot_preview1")]
unsafe extern "C" {
    fn sock_accept(fd: i32, flags: i32, new: *mut i32) -> i32;
    fn sock_recv(
        fd: i32,
        data: *const IoVec,
        data_len: usize,
        flags: i32,
        received: *mut usize,
        out_flags: *mut u16,
    ) -> i32;
    fn sock_send(fd: i32, data: *const IoVec, data_len: usize, flags: i32, sent: *mut usize)
    -> i32;
    fn sock_shutdown(fd: i32, how: i32) -> i32;
    fn fd_fdstat_get(fd: i32, stat: *mut FdStat) -> i32;
    fn fd_fdstat_set_flags(fd: i32, flags: i32) -> i32;
}

fn unsupported<T>() -> Result<T> {
    Err(ErrorKind::Unsupported.into())
}

/// # Safety
///
/// `socket` must be an open descriptor that nothing uses afterwards.
pub(crate) unsafe fn close(socket: RawSocket) {
    // SAFETY: the caller's contract is that of `sys::close`.
    unsafe { crate::sys::close(socket) }
}

pub(crate) fn socket(_: Family, _: Type, _: Protocol) -> Result<RawSocket> {
    unsupported()
}

pub(crate) fn bind(_: RawSocket, _: &RawAddr) -> Result<()> {
    unsupported()
}

pub(crate) fn connect(_: RawSocket, _: &RawAddr) -> Result<()> {
    unsupported()
}

pub(crate) fn listen(_: RawSocket, _: i32) -> Result<()> {
    unsupported()
}

pub(crate) fn accept(socket: RawSocket, _addr: &mut RawAddr) -> Result<RawSocket> {
    let mut new = -1;
    // No flag: the new socket is blocking. WASI reports no address.
    // SAFETY: sock_accept writes the new descriptor to `new`.
    cvt(unsafe { sock_accept(socket, 0, &raw mut new) })?;
    Ok(new)
}

pub(crate) fn send(
    socket: RawSocket,
    buf: &[u8],
    flags: SendFlags,
    addr: Option<&RawAddr>,
) -> Result<usize> {
    // WASI defines no send flag, and has no `sendto`.
    if !flags.is_empty() || addr.is_some() {
        return unsupported();
    }
    let data = IoVec {
        buf: buf.as_ptr(),
        len: buf.len(),
    };
    let mut sent = 0;
    // SAFETY: the host reads the one buffer `data` describes, and writes
    // the count to `sent`.
    cvt(unsafe { sock_send(socket, &data, 1, 0, &raw mut sent) })?;
    Ok(sent)
}

pub(crate) fn recv(
    socket: RawSocket,
    buf: &mut [u8],
    flags: RecvFlags,
    addr: Option<&mut RawAddr>,
) -> Result<usize> {
    if flags.contains(RecvFlags::OUT_OF_BAND) || addr.is_some() {
        return unsupported();
    }
    let mut raw = 0;
    if flags.contains(RecvFlags::PEEK) {
        raw |= RECV_PEEK;
    }
    if flags.contains(RecvFlags::WAIT_ALL) {
        raw |= RECV_WAITALL;
    }
    let data = IoVec {
        buf: buf.as_mut_ptr(),
        len: buf.len(),
    };
    let mut received = 0;
    let mut out_flags = 0;
    // SAFETY: the host writes to the one buffer `data` describes, and the
    // count and flags to the two variables.
    cvt(unsafe { sock_recv(socket, &data, 1, raw, &raw mut received, &raw mut out_flags) })?;
    Ok(received)
}

pub(crate) fn send_vectored(
    socket: RawSocket,
    bufs: &[IoSlice<'_>],
    flags: SendFlags,
    addr: Option<&RawAddr>,
) -> Result<usize> {
    if !flags.is_empty() || addr.is_some() {
        return unsupported();
    }
    let mut sent = 0;
    // SAFETY: `IoSlice` is a transparent `ciovec` over a readable buffer;
    // the host writes the count to `sent`.
    cvt(unsafe { sock_send(socket, bufs.as_ptr().cast(), bufs.len(), 0, &raw mut sent) })?;
    Ok(sent)
}

pub(crate) fn recv_vectored(
    socket: RawSocket,
    bufs: &mut [IoSliceMut<'_>],
    flags: RecvFlags,
    addr: Option<&mut RawAddr>,
) -> Result<(usize, bool)> {
    if flags.contains(RecvFlags::OUT_OF_BAND) || addr.is_some() {
        return unsupported();
    }
    let mut raw = 0;
    if flags.contains(RecvFlags::PEEK) {
        raw |= RECV_PEEK;
    }
    if flags.contains(RecvFlags::WAIT_ALL) {
        raw |= RECV_WAITALL;
    }
    let mut received = 0;
    let mut out_flags = 0;
    let (ptr, count) = (bufs.as_mut_ptr().cast_const().cast(), bufs.len());
    // SAFETY: `IoSliceMut` is a transparent `iovec` over a writable buffer;
    // the host writes the count and flags to the two variables.
    cvt(unsafe {
        sock_recv(
            socket,
            ptr,
            count,
            raw,
            &raw mut received,
            &raw mut out_flags,
        )
    })?;
    Ok((received, out_flags & RECV_DATA_TRUNCATED != 0))
}

pub(crate) fn shutdown(socket: RawSocket, how: Shutdown) -> Result<()> {
    let how = match how {
        Shutdown::Read => SHUT_RD,
        Shutdown::Write => SHUT_WR,
        Shutdown::Both => SHUT_RD | SHUT_WR,
    };
    // SAFETY: sock_shutdown takes two integers.
    cvt(unsafe { sock_shutdown(socket, how) })
}

pub(crate) fn local_addr(_: RawSocket, _: &mut RawAddr) -> Result<()> {
    unsupported()
}

pub(crate) fn peer_addr(_: RawSocket, _: &mut RawAddr) -> Result<()> {
    unsupported()
}

fn fdstat(socket: RawSocket) -> Result<FdStat> {
    let mut stat = FdStat {
        filetype: 0,
        flags: 0,
        rights_base: 0,
        rights_inheriting: 0,
    };
    // SAFETY: fd_fdstat_get fills `stat`.
    cvt(unsafe { fd_fdstat_get(socket, &raw mut stat) })?;
    Ok(stat)
}

pub(crate) fn set_nonblocking(socket: RawSocket, nonblocking: bool) -> Result<()> {
    // The flags are set as a whole: keep the others.
    let flags = fdstat(socket)?.flags;
    let new = if nonblocking {
        flags | FDFLAGS_NONBLOCK
    } else {
        flags & !FDFLAGS_NONBLOCK
    };
    // SAFETY: fd_fdstat_set_flags takes two integers.
    cvt(unsafe { fd_fdstat_set_flags(socket, new as i32) })
}

pub(crate) fn socket_type(socket: RawSocket) -> Result<Type> {
    match fdstat(socket)?.filetype {
        FILETYPE_SOCKET_STREAM => Ok(Type::Stream),
        FILETYPE_SOCKET_DGRAM => Ok(Type::Datagram),
        _ => Err(ErrorKind::BadHandle.into()),
    }
}

pub(crate) fn set_opt(_: RawSocket, _: Opt, _: i32) -> Result<()> {
    unsupported()
}

pub(crate) fn get_opt(_: RawSocket, _: Opt) -> Result<i32> {
    unsupported()
}

pub(crate) fn bind_interface(_: RawSocket, _: u32) -> Result<()> {
    unsupported()
}

pub(crate) fn set_linger(_: RawSocket, _: Option<u32>) -> Result<()> {
    unsupported()
}

pub(crate) fn linger(_: RawSocket) -> Result<Option<u32>> {
    unsupported()
}

pub(crate) fn set_timeout(_: RawSocket, _: Direction, _: Option<Duration>) -> Result<()> {
    unsupported()
}

pub(crate) fn timeout(_: RawSocket, _: Direction) -> Result<Option<Duration>> {
    unsupported()
}

pub(crate) fn membership_v4(_: RawSocket, _: bool, _: [u8; 4], _: [u8; 4]) -> Result<()> {
    unsupported()
}

pub(crate) fn membership_v6(_: RawSocket, _: bool, _: [u8; 16], _: u32) -> Result<()> {
    unsupported()
}

pub(crate) fn interfaces(_: &mut crate::net::InterfaceVisitor<'_>) -> Result<()> {
    unsupported()
}

pub(crate) fn interface_addrs(_: &mut crate::net::AddrVisitor<'_>) -> Result<()> {
    unsupported()
}