//! TCP for compiled programs (`std/net`, `std/http`): non-blocking sockets //! on the scheduler's reactor (mio). //! //! - A socket is a `Resource` whose finalizer closes it. //! - An operation that would block parks the actor on the socket's token. //! When nothing can run, the scheduler polls the reactor (see `sched`), //! then retries the operation. //! - Sockets are registered once, edge-triggered, for reading and writing. //! A wake-up may be spurious; the retry then parks again. Every actor //! waiting on a socket is woken by its events. An operation reads the //! reactor's event count before it tries ([`io_events`]); if an event //! came before the actor parks (another thread polled), the count moved, //! and the actor retries instead of parking (`Shared::io_wait`, issue //! #221). //! - A kill wakes a parked actor, which unwinds. //! //! Results are `Result`s (`Ok` 0, `Error` 1) with the error text. Data //! read is `Bytes`; data written is `Bytes` or a `String` (the same //! layout up to the string's NUL). //! //! A connection can be **upgraded** to TLS (`tls.rs`, ADR 0038): the TLS //! stream takes the socket and its reactor token. The connection then //! refuses to read or write, but `close` still shuts the socket down, so //! another actor holding it can stop a handshake that hangs. use std::io::{ErrorKind, Read, Write}; use std::net::{SocketAddr, ToSocketAddrs}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use mio::net::{TcpListener, TcpStream}; use mio::{Interest, Token}; use crate::abi::{Ctx, UNIT, Value, YIELD_NONE, int}; use crate::heap::drop_value; use crate::int::saturating; use crate::otp::Wait; use crate::resource::{tl_resource_get, tl_resource_new}; use crate::sched::{park, this}; use crate::values::{bytes_from, bytes_of, cell, error, list, ok, string, text}; enum Socket { Listener(TcpListener), Stream(Arc), } /// A socket resource. Any actor may hold it, so nothing here changes /// after it is made but `upgraded`. struct Handle { socket: Socket, token: Token, /// The other end of a connection, recorded when it was accepted or /// made (issue #308): a reset connection may no longer say. peer: Option, /// Given to a TLS stream, with the token (`upgrade`). upgraded: AtomicBool, /// A listener closed by `tl_net_close_listener`: `accept` fails. closed: AtomicBool, } unsafe extern "C" fn finalize(p: *mut std::ffi::c_void) { // SAFETY: made by `wrap`, finalized once; dropping closes the socket // (and removes it from the reactor). Finalizers never run under the // scheduler lock. unsafe { drop(Box::from_raw(p.cast::())); } } /// Register a socket with the reactor and wrap it as a resource. /// /// # Safety /// `ctx` must be the running actor's context. unsafe fn wrap( ctx: *mut Ctx, mut socket: Socket, peer: Option, ) -> Result { // SAFETY: forwarded caller guarantee. let (_, sched) = unsafe { this(ctx) }; let token = sched.io_token(); sched .with_registry(|registry| { let interest = Interest::READABLE | Interest::WRITABLE; match &mut socket { Socket::Listener(l) => registry.register(l, token, interest), Socket::Stream(st) => { // Not shared yet: registered before anyone else has it. let st = Arc::get_mut(st).expect("a new socket"); registry.register(st, token, interest) } } }) .map_err(|e| e.to_string())?; let handle = Box::into_raw(Box::new(Handle { socket, token, peer, upgraded: AtomicBool::new(false), closed: AtomicBool::new(false), })); Ok(tl_resource_new(ctx, handle.cast(), Some(finalize), true)) } /// # Safety /// `r` must be a live socket resource. unsafe fn handle<'a>(r: Value) -> &'a Handle { // SAFETY: caller guarantees a socket resource. unsafe { &*tl_resource_get(r).cast::() } } /// The connection of `h`, unless it is a listener or was upgraded. fn stream(h: &Handle) -> Result<&TcpStream, &'static str> { match &h.socket { Socket::Stream(_) if h.upgraded.load(Ordering::Acquire) => Err(UPGRADED), Socket::Stream(s) => Ok(s), Socket::Listener(_) => Err("not a connection: a listener"), } } /// The reactor's event count, read before an operation that may find /// `WouldBlock`, for [`wait_for`]. /// /// # Safety /// `ctx` must be the running actor's context. pub(crate) unsafe fn io_events(ctx: *mut Ctx) -> u64 { // SAFETY: forwarded caller guarantee. unsafe { this(ctx).1.io_events() } } /// Park until the socket's token fires (or the actor is stopped: false). /// `seen` is the event count read before the operation that blocked /// ([`io_events`]): if it moved since, this returns at once, to retry. /// /// # Safety /// `ctx` must be the running actor's context. pub(crate) unsafe fn wait_for(ctx: *mut Ctx, token: Token, seen: u64) -> bool { // SAFETY: forwarded caller guarantee. unsafe { let (a, sched) = this(ctx); // Waiting first, then registered: an event in between moves the // count, which `io_wait` checks. a.with_proc(|p| p.park_as(Wait::Io)); if !sched.io_wait(token, a.pid, seen) { a.with_proc(|p| p.wait = Wait::Ready); return true; // An event meanwhile: retry. } let v = park(ctx); drop_value(ctx, v); sched.io_unwait(token, a.pid); (*ctx).yielding == YIELD_NONE } } /// `resolve(host)`: the addresses `host` names, as text (`127.0.0.1`, /// `::1`), in the resolver's order. A lookup can take seconds, so this is /// a `blocking` extern: it runs on the blocking pool while its actor waits /// (ADR 0012, Revision 2), and must not panic. /// /// # Safety /// `host` must be a live string. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_net_resolve(ctx: *mut Ctx, host: Value) -> Value { // SAFETY: caller guarantees a live string. let host = unsafe { text(host) }; match (host, 0).to_socket_addrs() { Ok(addrs) => { let addrs: Vec = addrs.map(|a| string(ctx, &a.ip().to_string())).collect(); ok(ctx, list(ctx, addrs.into_iter())) } Err(e) => error(ctx, &e.to_string()), } } /// A port given as an Int: 0 to 65535, else the error. fn port_number(port: i64) -> Result { u16::try_from(port).map_err(|_| format!("port out of range: {port}")) } /// `listen(address, port)`: a listening socket. `std/net` resolves the /// host first ([`tl_net_resolve`]), so `address` is an IP address, which /// needs no lookup here. /// /// # Safety /// `ctx` must be the running actor's context; `host` a live string. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_net_listen(ctx: *mut Ctx, host: Value, port: Value) -> Value { // SAFETY: caller guarantees a live string and a live Int. let (host, port) = unsafe { (text(host), saturating(port)) }; let port = match port_number(port) { Ok(p) => p, Err(e) => return error(ctx, &e), }; let addr = match (host, port).to_socket_addrs().map(|mut a| a.next()) { Ok(Some(a)) => a, Ok(None) => return error(ctx, "no address"), Err(e) => return error(ctx, &e.to_string()), }; match TcpListener::bind(addr) { // SAFETY: forwarded caller guarantee. Ok(l) => match unsafe { wrap(ctx, Socket::Listener(l), None) } { Ok(r) => ok(ctx, r), Err(e) => error(ctx, &e), }, Err(e) => error(ctx, &e.to_string()), } } /// The local port of a listening socket (useful after binding port 0). /// /// # Safety /// `listener` must be a live listening socket. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_net_port(_ctx: *mut Ctx, listener: Value) -> Value { // SAFETY: caller guarantees a socket. match unsafe { &handle(listener).socket } { Socket::Listener(l) => int(l.local_addr().map_or(0, |a| i64::from(a.port()))), Socket::Stream(s) => int(s.local_addr().map_or(0, |a| i64::from(a.port()))), } } /// `accept(listener)`: the next connection. /// /// # Safety /// `ctx` must be the running actor's context; `listener` a live socket. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_net_accept(ctx: *mut Ctx, listener: Value) -> Value { // SAFETY: caller guarantees a socket on this actor. unsafe { loop { let h = handle(listener); let Socket::Listener(l) = &h.socket else { return error(ctx, "accept on a connection"); }; if h.closed.load(Ordering::Acquire) { return error(ctx, CLOSED); } let seen = io_events(ctx); match l.accept() { Ok((stream, peer)) => { // A server answers a request with one write, and a // streamed response flushes a write per chunk (ADR // 0053): Nagle would hold each back for a delayed ACK // (40 ms stalls). A failure keeps the connection. let _ = stream.set_nodelay(true); return match wrap(ctx, Socket::Stream(Arc::new(stream)), Some(peer)) { Ok(r) => ok(ctx, r), Err(e) => error(ctx, &e), }; } Err(e) if e.kind() == ErrorKind::WouldBlock => { if !wait_for(ctx, h.token, seen) { return UNIT; } } Err(e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => return error(ctx, &e.to_string()), } } } } /// `connect(address, port)`: a connection to a server. `std/net` /// resolves the host first ([`tl_net_resolve`]) and tries each address in /// turn, so `address` is an IP address, which needs no lookup here. /// /// # Safety /// `ctx` must be the running actor's context; `host` a live string. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_net_connect(ctx: *mut Ctx, host: Value, port: Value) -> Value { // SAFETY: caller guarantees a live string and a live Int. let (host, port) = unsafe { (text(host), saturating(port)) }; let port = match port_number(port) { Ok(p) => p, Err(e) => return error(ctx, &e), }; let addrs: Vec = match (host, port).to_socket_addrs() { Ok(a) => a.collect(), Err(e) => return error(ctx, &e.to_string()), }; let mut last = String::from("no address"); for addr in addrs { // SAFETY: forwarded caller guarantee. match unsafe { connect_to(ctx, addr) } { Ok(r) => return ok(ctx, r), Err(Some(e)) => last = e, // Stopped while waiting: unwinding. Err(None) => return UNIT, } } error(ctx, &last) } /// A connection to `addr`, once established. `Err(None)`: the actor was /// stopped while waiting. /// /// # Safety /// `ctx` must be the running actor's context. unsafe fn connect_to(ctx: *mut Ctx, addr: SocketAddr) -> Result> { let stream = TcpStream::connect(addr).map_err(|e| Some(e.to_string()))?; // As on accept: clients write a request and wait, so Nagle only adds // a delayed-ACK stall. A failure keeps the connection. let _ = stream.set_nodelay(true); // SAFETY: forwarded caller guarantee. unsafe { let r = wrap(ctx, Socket::Stream(Arc::new(stream)), Some(addr)).map_err(Some)?; // Connected once writable (or failed). loop { let h = handle(r); let Socket::Stream(s) = &h.socket else { unreachable!() }; let seen = io_events(ctx); let failed = match s.peer_addr() { Ok(_) => return Ok(r), Err(e) if e.kind() == ErrorKind::NotConnected => match s.take_error() { Ok(Some(e)) | Err(e) => Some(Some(e.to_string())), Ok(None) if !wait_for(ctx, h.token, seen) => Some(None), Ok(None) => None, }, Err(e) => Some(Some(e.to_string())), }; if let Some(failure) = failed { drop_value(ctx, r); return Err(failure); } } } } /// `read(conn, max)`: up to `max` bytes, as `Bytes`; empty at the end of /// the stream. /// /// # Safety /// `ctx` must be the running actor's context; `conn` a live connection. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_net_read(ctx: *mut Ctx, conn: Value, max: Value) -> Value { // SAFETY: caller guarantees a live Int. let max = unsafe { saturating(max) }; let mut buf = vec![0u8; max.clamp(1, 1 << 20) as usize]; // SAFETY: caller guarantees a connection on this actor. unsafe { loop { let h = handle(conn); let mut s = match stream(h) { Ok(s) => s, Err(e) => return error(ctx, e), }; let seen = io_events(ctx); match s.read(&mut buf) { Ok(n) => return ok(ctx, bytes_from(ctx, &buf[..n])), Err(e) if e.kind() == ErrorKind::WouldBlock => { if !wait_for(ctx, h.token, seen) { return UNIT; } } Err(e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => return error(ctx, &e.to_string()), } } } } /// `write(conn, data)`: all of `data` (`Bytes`). /// /// # Safety /// `ctx` must be the running actor's context; `conn` a live connection; /// `data` live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_net_write(ctx: *mut Ctx, conn: Value, data: Value) -> Value { // SAFETY: forwarded caller guarantees. unsafe { write_all(ctx, conn, data) } } /// `write_string(conn, s)`: all of `s` (UTF-8). /// /// # Safety /// `ctx` must be the running actor's context; `conn` a live connection; /// `s` a live string. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_net_write_string(ctx: *mut Ctx, conn: Value, s: Value) -> Value { // SAFETY: forwarded caller guarantees. unsafe { write_all(ctx, conn, s) } } /// # Safety /// `ctx` must be the running actor's context; `conn` a live connection; /// `data` a live string or `Bytes`. unsafe fn write_all(ctx: *mut Ctx, conn: Value, data: Value) -> Value { // SAFETY: caller guarantees a connection on this actor and data kept // alive by the parked caller. unsafe { let bytes = bytes_of(data); let mut sent = 0; while sent < bytes.len() { let h = handle(conn); let mut s = match stream(h) { Ok(s) => s, Err(e) => return error(ctx, e), }; let seen = io_events(ctx); match s.write(&bytes[sent..]) { Ok(0) => return error(ctx, "connection closed"), Ok(n) => sent += n, Err(e) if e.kind() == ErrorKind::WouldBlock => { if !wait_for(ctx, h.token, seen) { return UNIT; } } Err(e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => return error(ctx, &e.to_string()), } } ok(ctx, UNIT) } } /// `peer(conn)`: `Ok((host, port))`, the other end of a connection, as /// it was when accepted or made; the host is an IP address as text /// (`127.0.0.1`, `::1`). /// /// # Safety /// `ctx` must be the running actor's context; `conn` a live socket. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_net_peer(ctx: *mut Ctx, conn: Value) -> Value { // SAFETY: caller guarantees a socket. let h = unsafe { handle(conn) }; match (&h.socket, h.peer) { (Socket::Stream(_), Some(peer)) => { let host = string(ctx, &peer.ip().to_string()); let address = cell(ctx, 0, &[host, int(i64::from(peer.port()))]); ok(ctx, address) } (Socket::Stream(_), None) => error(ctx, "the connection's peer is not known"), (Socket::Listener(_), _) => error(ctx, "not a connection: a listener"), } } /// `close(conn)`: shut the connection down (the socket is released when /// its last reference is dropped). /// /// # Safety /// `conn` must be a live socket. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_net_close(_ctx: *mut Ctx, conn: Value) -> Value { // SAFETY: caller guarantees a socket. if let Socket::Stream(s) = unsafe { &handle(conn).socket } { let _ = s.shutdown(std::net::Shutdown::Both); } UNIT } /// `close_listener(listener)`: stop listening. New clients are refused /// (the socket is shut down), and `accept`, including one an actor is /// parked in, fails with "the listener is closed". The socket is released /// when its last reference is dropped. /// /// # Safety /// `ctx` must be the running actor's context; `listener` a live socket. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_net_close_listener(ctx: *mut Ctx, listener: Value) -> Value { // SAFETY: caller guarantees a socket on this actor. let h = unsafe { handle(listener) }; if let Socket::Listener(l) = &h.socket && !h.closed.swap(true, Ordering::AcqRel) { use std::os::fd::AsRawFd; // SAFETY: the descriptor is the listener's, open while `h` is. unsafe { libc::shutdown(l.as_raw_fd(), libc::SHUT_RDWR) }; // SAFETY: forwarded caller guarantee. let (_, sched) = unsafe { this(ctx) }; sched.wake_token(h.token); } UNIT } /// What `accept` on a closed listener answers. const CLOSED: &str = "the listener is closed"; /// What reading or writing an upgraded connection answers. const UPGRADED: &str = "this connection was upgraded to TLS: use the TLS stream"; /// Give `conn`'s socket and token to a TLS stream (`tls.rs`): the /// connection keeps the socket only to shut it down. /// /// # Safety /// `conn` must be a live socket resource. #[cfg_attr(not(feature = "tls"), allow(dead_code))] pub(crate) unsafe fn upgrade(conn: Value) -> Result<(Arc, Token), String> { // SAFETY: caller guarantees a socket resource. let h = unsafe { handle(conn) }; let Socket::Stream(s) = &h.socket else { return Err("a listener can't be a TLS stream".into()); }; // Once: a second upgrade (or one racing it) finds it taken. if h.upgraded.swap(true, Ordering::AcqRel) { return Err("this connection is already a TLS stream's".into()); } Ok((s.clone(), h.token)) } #[cfg(test)] mod tests { use super::*; use crate::abi::{Block, UNIT, int}; use crate::values::string; /// The one field of the `Ok` cell an extern returned. unsafe fn ok0(v: Value) -> Value { // SAFETY: the test reads the cell the extern just made. unsafe { *Block::fields_ptr(v as *mut Block) } } /// Accepted and connected sockets both have Nagle off: a response is /// one flushed write per chunk (ADR 0053), which Nagle would hold /// back for a delayed ACK. unsafe extern "C" fn accepted_sockets_disable_nagle(ctx: *mut Ctx) -> Value { // SAFETY: the test follows the generated-code convention; every // value it makes is dropped below. Loopback: the connect is // established at once, so the accept never parks. unsafe { let host = string(ctx, "127.0.0.1"); let listener = tl_net_listen(ctx, host, int(0)); let port = tl_net_port(ctx, ok0(listener)); let conn = tl_net_connect(ctx, host, port); let accepted = tl_net_accept(ctx, ok0(listener)); for end in [ok0(conn), ok0(accepted)] { let Socket::Stream(s) = &handle(end).socket else { panic!("a connection"); }; assert!(s.nodelay().expect("nodelay is readable")); } for v in [host, listener, conn, accepted] { drop_value(ctx, v); } } assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); UNIT } #[test] fn sockets_disable_nagle() { // SAFETY: the test follows the generated-code convention. let code = unsafe { crate::sched::run_test_actor(accepted_sockets_disable_nagle) }; assert_eq!(code, 0); } }