std

source of std::net

1// TCP connections: a listener accepts connections on IPv4, and a2// connection reaches a host by its name, IPv6 or IPv4; each is read and3// written as bytes, through the compiler's al_sys_* functions, one C file4// a platform (alloyc/src/support/system.c). Natively only: the interpreter5// has no sockets, and WASI preview 1 opens none.67import std::option;8import std::result;9import std::dispose;10import std::time;1112extern al_sys_tcp_listen(address: c_string, port: u32) -> i64;13extern al_sys_tcp_connect(host: c_string, port: u32, milliseconds: u64) -> i64;14extern al_sys_tcp_shutdown(socket: i64);15extern al_sys_tcp_port(socket: i64) -> u32;16extern al_sys_tcp_accept(socket: i64) -> i64;17extern al_sys_tcp_read(socket: i64, buffer: &var [u8], length: u64) -> i64;18extern al_sys_tcp_write(socket: i64, bytes: &[u8], length: u64) -> i64;19extern al_sys_tcp_timeout(socket: i64, milliseconds: u64);20extern al_sys_tcp_close(socket: i64);2122// A socket listening for connections, closed by disposing it.23exp type Listener : Disposable = struct {24    socket: i6425};2627// One end of a connection, closed by disposing it.28exp type Connection : Disposable = struct {29    socket: i6430};3132// Why a connection was not made.33exp type NetError = enum {34    Resolve, // the host has no address35    Connect, // no address took the connection36    Timeout, // the time ran out first37    Unsupported, // no sockets here: WASI, the interpreter38};3940// Looks the host up (IPv6 and IPv4, in the order the resolver gives) and41// connects to the first address taking the connection, each tried for at42// most 3 seconds within the timeout, the last for what is left. A statically linked Linux program43// resolves through /etc/hosts and /etc/resolv.conf alone, so mDNS's44// `.local` names do not resolve there.45exp fn Connection::connect(46    host: &[u8],47    port: u16,48    timeout: Duration49) -> Result<Connection, NetError> {50    var text: [u8 : 256] = [0 : 256];51    if (host.length() >= 256) {52        return ::Err(::Resolve);53    }54    text[..host.length()] = host;55    const milliseconds = milliseconds_of(timeout);56    const s = al_sys_tcp_connect(&text[..host.length() + 1], port to u32, milliseconds);57    return match (s) {58        -1 ::Err(NetError::Resolve);59        -2 ::Err(NetError::Connect);60        -3 ::Err(NetError::Timeout);61        -4 ::Err(NetError::Unsupported);62        else ::Ok(Connection { .socket = s });63    };64}6566// Listens on the IPv4 address (`127.0.0.1`, or `0.0.0.0` for every67// interface) and port, 0 for any free one; None when it cannot.68exp fn Listener::open(address: &[u8], port: u16) -> Option<Listener> {69    var text: [u8 : 64] = [0 : 64];70    if (address.length() >= 64) {71        return ::None;72    }73    text[..address.length()] = address;74    const s = al_sys_tcp_listen(&text[..address.length() + 1], port to u32);75    if (s < 0) {76        return ::None;77    }78    return ::Some(Listener { .socket = s });79}8081// The port it listens on.82exp fn port(self listener: &Listener) -> u16 {83    return al_sys_tcp_port(listener.socket) to u16;84}8586// Waits for the next connection; None when accepting fails. Several87// tasks may wait on one listener, each taking its own connections.88exp fn next_connection(self listener: &Listener) -> Option<Connection> {89    const s = al_sys_tcp_accept(listener.socket);90    if (s < 0) {91        return ::None;92    }93    return ::Some(Connection { .socket = s });94}9596exp fn dispose(self listener: &var Listener) {97    al_sys_tcp_close(listener.socket);98    listener.socket = -1;99}100101// Reads what has arrived into the buffer, waiting for some; how many102// bytes, 0 when the other end closed or after an error or a timeout.103exp fn read(self connection: &var Connection, buffer: &var [u8]) -> u64 {104    const count = al_sys_tcp_read(connection.socket, &var buffer, buffer.length());105    return if (count > 0) count to u64 else 0;106}107108// As `read`, but 0 only when the other end closed, -1 after an error or109// a timeout: for std::http, telling a body's end from a failure.110pub fn read_or_fail(self connection: &var Connection, buffer: &var [u8]) -> i64 {111    return al_sys_tcp_read(connection.socket, &var buffer, buffer.length());112}113114// Writes all the bytes; false when the connection failed.115exp fn write(self connection: &var Connection, bytes: &[u8]) -> bool {116    var at: u64 = 0;117    while (at < bytes.length()) {118        const count = al_sys_tcp_write(connection.socket, &bytes[at..], bytes.length() - at);119        if (count <= 0) {120            return false;121        }122        at += count to u64;123    }124    return true;125}126127// Makes reads and writes waiting longer than the seconds fail.128exp fn set_timeout(self connection: &var Connection, seconds: u64) {129    al_sys_tcp_timeout(connection.socket, seconds * 1000);130}131132// Makes reads and writes waiting longer than the limit, to the133// millisecond, fail; none waits for ever.134exp fn set_timeout(self connection: &var Connection, limit: Duration) {135    al_sys_tcp_timeout(connection.socket, milliseconds_of(limit));136}137138// Ends the connection both ways, from any task: a read or write waiting139// on it returns at once, failed. How another task cancels an exchange.140exp fn shutdown(self connection: &Connection) {141    al_sys_tcp_shutdown(connection.socket);142}143144// Shuts a connection down by its handle, for std::http's Control, which145// keeps the handle of the connection an exchange is using.146pub fn shutdown_handle(socket: i64) {147    al_sys_tcp_shutdown(socket);148}149150// The operating system's handle, for code layering a protocol over it.151exp fn handle(self connection: &Connection) -> i64 {152    return connection.socket;153}154155exp fn dispose(self connection: &var Connection) {156    al_sys_tcp_close(connection.socket);157    connection.socket = -1;158}159160// The duration in milliseconds, rounded up.161fn milliseconds_of(d: Duration) -> u64 {162    return d.nanoseconds / 1000000 + (if (d.nanoseconds % 1000000 != 0) 1 else 0);163}