//! 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::{IpAddr, SocketAddr, ToSocketAddrs}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, OnceLock}; use mio::net::{TcpListener, TcpStream}; use mio::{Interest, Token}; use crate::abi::{Ctx, UNIT, Value, YIELD_NONE, int}; use crate::blocking::{IO, Thunk, tl_call_blocking}; use crate::heap::drop_value; use crate::int::saturating; use crate::otp::Wait; use crate::process::Code; 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, tl_borrowed1, tl_borrowed2, }; 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 } } /// The clauses of `std/net.net`, in `louise_rt_prims::NET_OPS` order. Only /// resolution and the two address-level opening operations belong to this root. /// Socket values returned by it retain their existing handle-mediated `` /// operations (`accept`, `read`, `write`, `peer` and close). const NET_CLAUSES: [(Code, Code); louise_rt_prims::NET_OPS.len()] = [ (op_resolve, tl_borrowed1), (op_listen_at, tl_borrowed2), (op_connect_to, tl_borrowed2), ]; /// The immortal root capability for `net`: three stateless clauses, shared by /// every actor, outside the counted heap (ADR 0084). pub(crate) fn net_cap() -> Value { static CAP: OnceLock = OnceLock::new(); *CAP.get_or_init(|| crate::clock::immortal_cap(&NET_CLAUSES)) } /// Consume an owned remote-denied invocation without inspecting its host or /// entering either the resolver pool or socket code. All three net operations /// have a `Result<_, String>` result. unsafe fn deny_result(ctx: *mut Ctx, this_: Value, args: &[Value]) -> Value { // SAFETY: the root invocation owns `this_` and every argument. unsafe { drop_value(ctx, this_); for &arg in args { drop_value(ctx, arg); } } error(ctx, louise_rt_prims::NET_REMOTE_DENIED) } unsafe extern "C" fn resolve_thunk(ctx: *mut Ctx, args: *const Value) -> Value { #[cfg(test)] note_io_thread(); // SAFETY: the I/O pool passes one live borrowed host string. The retained // C ABI has no capability argument and receives exactly the old arguments. unsafe { tl_net_resolve(ctx, args.read()) } } unsafe extern "C" fn op_resolve( ctx: *mut Ctx, this_: Value, host: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: an owned root-clause invocation on the running actor. unsafe { if crate::sched::remote_net_denied(ctx) { return deny_result(ctx, this_, &[host]); } drop_value(ctx, this_); // Only this blocking DNS step leaves the scheduler. Address opening // below keeps using the existing nonblocking reactor paths. let out = tl_call_blocking(ctx, IO, resolve_thunk as Thunk, 1, &host); drop_value(ctx, host); out } } /// Call an old borrowed two-argument socket kernel from its owned root clause. /// The arguments stay live across reactor parking; a stopped actor returns /// through the same unwind path and still releases its owned references once. unsafe fn opening2( ctx: *mut Ctx, this_: Value, address: Value, port: Value, kernel: unsafe extern "C" fn(*mut Ctx, Value, Value) -> Value, ) -> Value { // SAFETY: the root owns all inputs; the old kernels merely borrow the two // operation arguments and have their original fixed C arity. unsafe { // The root deliberately exposes address-level operations. Refuse a // hostname rather than letting ToSocketAddrs do scheduler-thread DNS; // high-level listen/connect still resolve through the I/O pool first. let literal = text(address).parse::().is_ok(); if !literal { drop_value(ctx, this_); drop_value(ctx, address); drop_value(ctx, port); return error(ctx, "address is not an IP literal"); } drop_value(ctx, this_); let out = kernel(ctx, address, port); drop_value(ctx, address); drop_value(ctx, port); out } } unsafe extern "C" fn op_listen_at( ctx: *mut Ctx, this_: Value, address: Value, port: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: an owned root-clause invocation on the running actor. unsafe { if crate::sched::remote_net_denied(ctx) { return deny_result(ctx, this_, &[address, port]); } opening2(ctx, this_, address, port, tl_net_listen) } } unsafe extern "C" fn op_connect_to( ctx: *mut Ctx, this_: Value, address: Value, port: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: an owned root-clause invocation on the running actor. unsafe { if crate::sched::remote_net_denied(ctx) { return deny_result(ctx, this_, &[address, port]); } opening2(ctx, this_, address, port, tl_net_connect) } } #[cfg(test)] fn note_io_thread() { note_io_threads().lock().expect("net test threads").push( std::thread::current() .name() .unwrap_or("unnamed") .to_owned(), ); } #[cfg(test)] fn io_threads() -> Vec { let mut threads = Vec::new(); // Bounded by the two explicit resolver calls in the root roundtrip. std::mem::swap( &mut threads, &mut *note_io_threads().lock().expect("net test threads"), ); threads } #[cfg(test)] fn note_io_threads() -> &'static std::sync::Mutex> { use std::sync::Mutex; static THREADS: Mutex> = Mutex::new(Vec::new()); &THREADS } /// `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}; #[cfg(test)] use crate::heap::dup_value; use crate::values::{closure_code_borrowed, string}; #[test] fn the_net_capability_is_immortal_and_built_once() { let cap = net_cap(); assert_eq!(cap, net_cap()); // Construction returns the same static clauses without mutating their // parameters or allocating replacements in the counted heap. // SAFETY: `net_cap` constructs the immutable block and its statically // declared three clauses. The tested layout has the known field count. unsafe { let b = cap as *mut Block; assert_eq!((*b).header.rc, 0); let n = (*b).header.scan_fsize as usize; assert_eq!(n, louise_rt_prims::NET_OPS.len() + 1); let fields = Block::fields_ptr(b); assert_eq!(fields.add(n - 1).read(), int(0), "the marker"); for i in 0..n - 1 { let clause = fields.add(i).read() as *mut Block; assert_eq!((*clause).header.rc, 0); } } } /// Perform an operation through its actual root clause, either through the /// owned general call or the fixed-arity borrowed adapter. At most two /// arguments, never a reinterpreted hidden capability argument. unsafe fn perform(ctx: *mut Ctx, op: &str, args: &[Value], owned: bool) -> Value { // SAFETY: callers provide the active context and correctly typed live // arguments. The root outlives the call; its declared closure carries // the actual C function with five fixed argument registers. unsafe { assert!(args.len() <= 2); let i = louise_rt_prims::NET_OPS .iter() .position(|name| *name == op) .expect("a net operation"); let cap = crate::process::root_cap(crate::process::RootCap::Net); let clause = Block::fields_ptr(cap as *mut Block).add(i).read(); if owned { let clause = dup_value(clause); drop_value(ctx, cap); return crate::prims::call_closure(ctx, clause, args); } let mut regs = [UNIT; 5]; regs[..args.len()].copy_from_slice(args); let code: Code = std::mem::transmute(closure_code_borrowed(clause)); let out = code(ctx, clause, regs[0], regs[1], regs[2], regs[3], regs[4]); drop_value(ctx, cap); out } } /// The one field of the `Ok` cell an operation returned. unsafe fn ok0(v: Value) -> Value { // SAFETY: the test reads the cell the operation just made. unsafe { *Block::fields_ptr(v as *mut Block) } } /// Resolve, open, connect and accept through the real root, on loopback only. /// Both owned and borrowed root adapters are exercised and the returned /// socket Resources are then used by the same handle-mediated io kernels. unsafe extern "C" fn root_roundtrip(ctx: *mut Ctx) -> Value { // SAFETY: generated-code convention; every result is released below. // Loopback connect is established before the matching accept here. unsafe { let host = string(ctx, "127.0.0.1"); let resolved = perform(ctx, "resolve", &[dup_value(host)], true); assert_eq!((*(resolved as *mut Block)).header.tag, 0, "resolver Ok"); let resolved_borrowed = perform(ctx, "resolve", &[host], false); assert_eq!( (*(resolved_borrowed as *mut Block)).header.tag, 0, "borrowed resolver Ok" ); let hostname = string(ctx, "not-a-literal.invalid"); let bad_listen = perform(ctx, "listen_at", &[dup_value(hostname), int(0)], true); let bad_connect = perform(ctx, "connect_to", &[hostname, int(443)], false); for refused in [bad_listen, bad_connect] { assert_eq!( (*(refused as *mut Block)).header.tag, 1, "address-level roots must not do scheduler DNS" ); let why = Block::fields_ptr(refused as *mut Block).read(); assert_eq!( text(why), "address is not an IP literal", "a resolver error is not the deterministic guard" ); } let listener = perform(ctx, "listen_at", &[dup_value(host), int(0)], true); assert_eq!((*(listener as *mut Block)).header.tag, 0, "listener Ok"); let port = tl_net_port(ctx, ok0(listener)); let conn = perform(ctx, "connect_to", &[host, port], false); assert_eq!((*(conn as *mut Block)).header.tag, 0, "connection Ok"); 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")); } tl_net_close(ctx, ok0(conn)); tl_net_close(ctx, ok0(accepted)); tl_net_close_listener(ctx, ok0(listener)); for v in [ resolved, resolved_borrowed, bad_listen, bad_connect, hostname, host, listener, conn, accepted, ] { drop_value(ctx, v); } let threads = io_threads(); assert_eq!(threads.len(), 2, "one record per resolution: {threads:?}"); assert!( threads .iter() .all(|name| name.starts_with("louise-blocking-io-")), "DNS must not run on a scheduler: {threads:?}" ); } assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); UNIT } #[test] fn root_adapters_resolve_and_open_loopback_sockets_without_leaks() { // SAFETY: the test follows the generated-code convention. let code = unsafe { crate::sched::run_test_actor(root_roundtrip) }; assert_eq!(code, 0); } }