tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

808 lignes · 30501 octetsBrut · Historique
1//! TCP for compiled programs (`std/net`, `std/http`): non-blocking sockets
2//! on the scheduler's reactor (mio).
3//!
4//! - A socket is a `Resource` whose finalizer closes it.
5//! - An operation that would block parks the actor on the socket's token.
6//! When nothing can run, the scheduler polls the reactor (see `sched`),
7//! then retries the operation.
8//! - Sockets are registered once, edge-triggered, for reading and writing.
9//! A wake-up may be spurious; the retry then parks again. Every actor
10//! waiting on a socket is woken by its events. An operation reads the
11//! reactor's event count before it tries ([`io_events`]); if an event
12//! came before the actor parks (another thread polled), the count moved,
13//! and the actor retries instead of parking (`Shared::io_wait`, issue
14//! #221).
15//! - A kill wakes a parked actor, which unwinds.
16//!
17//! Results are `Result`s (`Ok` 0, `Error` 1) with the error text. Data
18//! read is `Bytes`; data written is `Bytes` or a `String` (the same
19//! layout up to the string's NUL).
20//!
21//! A connection can be **upgraded** to TLS (`tls.rs`, ADR 0038): the TLS
22//! stream takes the socket and its reactor token. The connection then
23//! refuses to read or write, but `close` still shuts the socket down, so
24//! another actor holding it can stop a handshake that hangs.
25
26use std::io::{ErrorKind, Read, Write};
27use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
28use std::sync::atomic::{AtomicBool, Ordering};
29use std::sync::{Arc, OnceLock};
30
31use mio::net::{TcpListener, TcpStream};
32use mio::{Interest, Token};
33
34use crate::abi::{Ctx, UNIT, Value, YIELD_NONE, int};
35use crate::blocking::{IO, Thunk, tl_call_blocking};
36use crate::heap::drop_value;
37use crate::int::saturating;
38use crate::otp::Wait;
39use crate::process::Code;
40use crate::resource::{tl_resource_get, tl_resource_new};
41use crate::sched::{park, this};
42use crate::values::{
43 bytes_from, bytes_of, cell, error, list, ok, string, text, tl_borrowed1, tl_borrowed2,
44};
45
46enum Socket {
47 Listener(TcpListener),
48 Stream(Arc<TcpStream>),
49}
50
51/// A socket resource. Any actor may hold it, so nothing here changes
52/// after it is made but `upgraded`.
53struct Handle {
54 socket: Socket,
55 token: Token,
56 /// The other end of a connection, recorded when it was accepted or
57 /// made (issue #308): a reset connection may no longer say.
58 peer: Option<SocketAddr>,
59 /// Given to a TLS stream, with the token (`upgrade`).
60 upgraded: AtomicBool,
61 /// A listener closed by `tl_net_close_listener`: `accept` fails.
62 closed: AtomicBool,
63}
64
65unsafe extern "C" fn finalize(p: *mut std::ffi::c_void) {
66 // SAFETY: made by `wrap`, finalized once; dropping closes the socket
67 // (and removes it from the reactor). Finalizers never run under the
68 // scheduler lock.
69 unsafe {
70 drop(Box::from_raw(p.cast::<Handle>()));
71 }
72}
73
74/// Register a socket with the reactor and wrap it as a resource.
75///
76/// # Safety
77/// `ctx` must be the running actor's context.
78unsafe fn wrap(
79 ctx: *mut Ctx,
80 mut socket: Socket,
81 peer: Option<SocketAddr>,
82) -> Result<Value, String> {
83 // SAFETY: forwarded caller guarantee.
84 let (_, sched) = unsafe { this(ctx) };
85 let token = sched.io_token();
86 sched
87 .with_registry(|registry| {
88 let interest = Interest::READABLE | Interest::WRITABLE;
89 match &mut socket {
90 Socket::Listener(l) => registry.register(l, token, interest),
91 Socket::Stream(st) => {
92 // Not shared yet: registered before anyone else has it.
93 let st = Arc::get_mut(st).expect("a new socket");
94 registry.register(st, token, interest)
95 }
96 }
97 })
98 .map_err(|e| e.to_string())?;
99 let handle = Box::into_raw(Box::new(Handle {
100 socket,
101 token,
102 peer,
103 upgraded: AtomicBool::new(false),
104 closed: AtomicBool::new(false),
105 }));
106 Ok(tl_resource_new(ctx, handle.cast(), Some(finalize), true))
107}
108
109/// # Safety
110/// `r` must be a live socket resource.
111unsafe fn handle<'a>(r: Value) -> &'a Handle {
112 // SAFETY: caller guarantees a socket resource.
113 unsafe { &*tl_resource_get(r).cast::<Handle>() }
114}
115
116/// The connection of `h`, unless it is a listener or was upgraded.
117fn stream(h: &Handle) -> Result<&TcpStream, &'static str> {
118 match &h.socket {
119 Socket::Stream(_) if h.upgraded.load(Ordering::Acquire) => Err(UPGRADED),
120 Socket::Stream(s) => Ok(s),
121 Socket::Listener(_) => Err("not a connection: a listener"),
122 }
123}
124
125/// The reactor's event count, read before an operation that may find
126/// `WouldBlock`, for [`wait_for`].
127///
128/// # Safety
129/// `ctx` must be the running actor's context.
130pub(crate) unsafe fn io_events(ctx: *mut Ctx) -> u64 {
131 // SAFETY: forwarded caller guarantee.
132 unsafe { this(ctx).1.io_events() }
133}
134
135/// Park until the socket's token fires (or the actor is stopped: false).
136/// `seen` is the event count read before the operation that blocked
137/// ([`io_events`]): if it moved since, this returns at once, to retry.
138///
139/// # Safety
140/// `ctx` must be the running actor's context.
141pub(crate) unsafe fn wait_for(ctx: *mut Ctx, token: Token, seen: u64) -> bool {
142 // SAFETY: forwarded caller guarantee.
143 unsafe {
144 let (a, sched) = this(ctx);
145 // Waiting first, then registered: an event in between moves the
146 // count, which `io_wait` checks.
147 a.with_proc(|p| p.park_as(Wait::Io));
148 if !sched.io_wait(token, a.pid, seen) {
149 a.with_proc(|p| p.wait = Wait::Ready);
150 return true; // An event meanwhile: retry.
151 }
152 let v = park(ctx);
153 drop_value(ctx, v);
154 sched.io_unwait(token, a.pid);
155 (*ctx).yielding == YIELD_NONE
156 }
157}
158
159/// The clauses of `std/net.net`, in `louise_rt_prims::NET_OPS` order. Only
160/// resolution and the two address-level opening operations belong to this root.
161/// Socket values returned by it retain their existing handle-mediated `<io>`
162/// operations (`accept`, `read`, `write`, `peer` and close).
163const NET_CLAUSES: [(Code, Code); louise_rt_prims::NET_OPS.len()] = [
164 (op_resolve, tl_borrowed1),
165 (op_listen_at, tl_borrowed2),
166 (op_connect_to, tl_borrowed2),
167];
168
169/// The immortal root capability for `net`: three stateless clauses, shared by
170/// every actor, outside the counted heap (ADR 0084).
171pub(crate) fn net_cap() -> Value {
172 static CAP: OnceLock<Value> = OnceLock::new();
173 *CAP.get_or_init(|| crate::clock::immortal_cap(&NET_CLAUSES))
174}
175
176/// Consume an owned remote-denied invocation without inspecting its host or
177/// entering either the resolver pool or socket code. All three net operations
178/// have a `Result<_, String>` result.
179unsafe fn deny_result(ctx: *mut Ctx, this_: Value, args: &[Value]) -> Value {
180 // SAFETY: the root invocation owns `this_` and every argument.
181 unsafe {
182 drop_value(ctx, this_);
183 for &arg in args {
184 drop_value(ctx, arg);
185 }
186 }
187 error(ctx, louise_rt_prims::NET_REMOTE_DENIED)
188}
189
190unsafe extern "C" fn resolve_thunk(ctx: *mut Ctx, args: *const Value) -> Value {
191 #[cfg(test)]
192 note_io_thread();
193 // SAFETY: the I/O pool passes one live borrowed host string. The retained
194 // C ABI has no capability argument and receives exactly the old arguments.
195 unsafe { tl_net_resolve(ctx, args.read()) }
196}
197
198unsafe extern "C" fn op_resolve(
199 ctx: *mut Ctx,
200 this_: Value,
201 host: Value,
202 _: Value,
203 _: Value,
204 _: Value,
205 _: Value,
206) -> Value {
207 // SAFETY: an owned root-clause invocation on the running actor.
208 unsafe {
209 if crate::sched::remote_net_denied(ctx) {
210 return deny_result(ctx, this_, &[host]);
211 }
212 drop_value(ctx, this_);
213 // Only this blocking DNS step leaves the scheduler. Address opening
214 // below keeps using the existing nonblocking reactor paths.
215 let out = tl_call_blocking(ctx, IO, resolve_thunk as Thunk, 1, &host);
216 drop_value(ctx, host);
217 out
218 }
219}
220
221/// Call an old borrowed two-argument socket kernel from its owned root clause.
222/// The arguments stay live across reactor parking; a stopped actor returns
223/// through the same unwind path and still releases its owned references once.
224unsafe fn opening2(
225 ctx: *mut Ctx,
226 this_: Value,
227 address: Value,
228 port: Value,
229 kernel: unsafe extern "C" fn(*mut Ctx, Value, Value) -> Value,
230) -> Value {
231 // SAFETY: the root owns all inputs; the old kernels merely borrow the two
232 // operation arguments and have their original fixed C arity.
233 unsafe {
234 // The root deliberately exposes address-level operations. Refuse a
235 // hostname rather than letting ToSocketAddrs do scheduler-thread DNS;
236 // high-level listen/connect still resolve through the I/O pool first.
237 let literal = text(address).parse::<IpAddr>().is_ok();
238 if !literal {
239 drop_value(ctx, this_);
240 drop_value(ctx, address);
241 drop_value(ctx, port);
242 return error(ctx, "address is not an IP literal");
243 }
244 drop_value(ctx, this_);
245 let out = kernel(ctx, address, port);
246 drop_value(ctx, address);
247 drop_value(ctx, port);
248 out
249 }
250}
251
252unsafe extern "C" fn op_listen_at(
253 ctx: *mut Ctx,
254 this_: Value,
255 address: Value,
256 port: Value,
257 _: Value,
258 _: Value,
259 _: Value,
260) -> Value {
261 // SAFETY: an owned root-clause invocation on the running actor.
262 unsafe {
263 if crate::sched::remote_net_denied(ctx) {
264 return deny_result(ctx, this_, &[address, port]);
265 }
266 opening2(ctx, this_, address, port, tl_net_listen)
267 }
268}
269
270unsafe extern "C" fn op_connect_to(
271 ctx: *mut Ctx,
272 this_: Value,
273 address: Value,
274 port: Value,
275 _: Value,
276 _: Value,
277 _: Value,
278) -> Value {
279 // SAFETY: an owned root-clause invocation on the running actor.
280 unsafe {
281 if crate::sched::remote_net_denied(ctx) {
282 return deny_result(ctx, this_, &[address, port]);
283 }
284 opening2(ctx, this_, address, port, tl_net_connect)
285 }
286}
287
288#[cfg(test)]
289fn note_io_thread() {
290 note_io_threads().lock().expect("net test threads").push(
291 std::thread::current()
292 .name()
293 .unwrap_or("unnamed")
294 .to_owned(),
295 );
296}
297
298#[cfg(test)]
299fn io_threads() -> Vec<String> {
300 let mut threads = Vec::new();
301 // Bounded by the two explicit resolver calls in the root roundtrip.
302 std::mem::swap(
303 &mut threads,
304 &mut *note_io_threads().lock().expect("net test threads"),
305 );
306 threads
307}
308
309#[cfg(test)]
310fn note_io_threads() -> &'static std::sync::Mutex<Vec<String>> {
311 use std::sync::Mutex;
312 static THREADS: Mutex<Vec<String>> = Mutex::new(Vec::new());
313 &THREADS
314}
315
316/// `resolve(host)`: the addresses `host` names, as text (`127.0.0.1`,
317/// `::1`), in the resolver's order. A lookup can take seconds, so this is
318/// a `blocking` extern: it runs on the blocking pool while its actor waits
319/// (ADR 0012, Revision 2), and must not panic.
320///
321/// # Safety
322/// `host` must be a live string.
323#[unsafe(no_mangle)]
324pub unsafe extern "C" fn tl_net_resolve(ctx: *mut Ctx, host: Value) -> Value {
325 // SAFETY: caller guarantees a live string.
326 let host = unsafe { text(host) };
327 match (host, 0).to_socket_addrs() {
328 Ok(addrs) => {
329 let addrs: Vec<Value> = addrs.map(|a| string(ctx, &a.ip().to_string())).collect();
330 ok(ctx, list(ctx, addrs.into_iter()))
331 }
332 Err(e) => error(ctx, &e.to_string()),
333 }
334}
335
336/// A port given as an Int: 0 to 65535, else the error.
337fn port_number(port: i64) -> Result<u16, String> {
338 u16::try_from(port).map_err(|_| format!("port out of range: {port}"))
339}
340
341/// `listen(address, port)`: a listening socket. `std/net` resolves the
342/// host first ([`tl_net_resolve`]), so `address` is an IP address, which
343/// needs no lookup here.
344///
345/// # Safety
346/// `ctx` must be the running actor's context; `host` a live string.
347#[unsafe(no_mangle)]
348pub unsafe extern "C" fn tl_net_listen(ctx: *mut Ctx, host: Value, port: Value) -> Value {
349 // SAFETY: caller guarantees a live string and a live Int.
350 let (host, port) = unsafe { (text(host), saturating(port)) };
351 let port = match port_number(port) {
352 Ok(p) => p,
353 Err(e) => return error(ctx, &e),
354 };
355 let addr = match (host, port).to_socket_addrs().map(|mut a| a.next()) {
356 Ok(Some(a)) => a,
357 Ok(None) => return error(ctx, "no address"),
358 Err(e) => return error(ctx, &e.to_string()),
359 };
360 match TcpListener::bind(addr) {
361 // SAFETY: forwarded caller guarantee.
362 Ok(l) => match unsafe { wrap(ctx, Socket::Listener(l), None) } {
363 Ok(r) => ok(ctx, r),
364 Err(e) => error(ctx, &e),
365 },
366 Err(e) => error(ctx, &e.to_string()),
367 }
368}
369
370/// The local port of a listening socket (useful after binding port 0).
371///
372/// # Safety
373/// `listener` must be a live listening socket.
374#[unsafe(no_mangle)]
375pub unsafe extern "C" fn tl_net_port(_ctx: *mut Ctx, listener: Value) -> Value {
376 // SAFETY: caller guarantees a socket.
377 match unsafe { &handle(listener).socket } {
378 Socket::Listener(l) => int(l.local_addr().map_or(0, |a| i64::from(a.port()))),
379 Socket::Stream(s) => int(s.local_addr().map_or(0, |a| i64::from(a.port()))),
380 }
381}
382
383/// `accept(listener)`: the next connection.
384///
385/// # Safety
386/// `ctx` must be the running actor's context; `listener` a live socket.
387#[unsafe(no_mangle)]
388pub unsafe extern "C" fn tl_net_accept(ctx: *mut Ctx, listener: Value) -> Value {
389 // SAFETY: caller guarantees a socket on this actor.
390 unsafe {
391 loop {
392 let h = handle(listener);
393 let Socket::Listener(l) = &h.socket else {
394 return error(ctx, "accept on a connection");
395 };
396 if h.closed.load(Ordering::Acquire) {
397 return error(ctx, CLOSED);
398 }
399 let seen = io_events(ctx);
400 match l.accept() {
401 Ok((stream, peer)) => {
402 // A server answers a request with one write, and a
403 // streamed response flushes a write per chunk (ADR
404 // 0053): Nagle would hold each back for a delayed ACK
405 // (40 ms stalls). A failure keeps the connection.
406 let _ = stream.set_nodelay(true);
407 return match wrap(ctx, Socket::Stream(Arc::new(stream)), Some(peer)) {
408 Ok(r) => ok(ctx, r),
409 Err(e) => error(ctx, &e),
410 };
411 }
412 Err(e) if e.kind() == ErrorKind::WouldBlock => {
413 if !wait_for(ctx, h.token, seen) {
414 return UNIT;
415 }
416 }
417 Err(e) if e.kind() == ErrorKind::Interrupted => {}
418 Err(e) => return error(ctx, &e.to_string()),
419 }
420 }
421 }
422}
423
424/// `connect(address, port)`: a connection to a server. `std/net`
425/// resolves the host first ([`tl_net_resolve`]) and tries each address in
426/// turn, so `address` is an IP address, which needs no lookup here.
427///
428/// # Safety
429/// `ctx` must be the running actor's context; `host` a live string.
430#[unsafe(no_mangle)]
431pub unsafe extern "C" fn tl_net_connect(ctx: *mut Ctx, host: Value, port: Value) -> Value {
432 // SAFETY: caller guarantees a live string and a live Int.
433 let (host, port) = unsafe { (text(host), saturating(port)) };
434 let port = match port_number(port) {
435 Ok(p) => p,
436 Err(e) => return error(ctx, &e),
437 };
438 let addrs: Vec<SocketAddr> = match (host, port).to_socket_addrs() {
439 Ok(a) => a.collect(),
440 Err(e) => return error(ctx, &e.to_string()),
441 };
442 let mut last = String::from("no address");
443 for addr in addrs {
444 // SAFETY: forwarded caller guarantee.
445 match unsafe { connect_to(ctx, addr) } {
446 Ok(r) => return ok(ctx, r),
447 Err(Some(e)) => last = e,
448 // Stopped while waiting: unwinding.
449 Err(None) => return UNIT,
450 }
451 }
452 error(ctx, &last)
453}
454
455/// A connection to `addr`, once established. `Err(None)`: the actor was
456/// stopped while waiting.
457///
458/// # Safety
459/// `ctx` must be the running actor's context.
460unsafe fn connect_to(ctx: *mut Ctx, addr: SocketAddr) -> Result<Value, Option<String>> {
461 let stream = TcpStream::connect(addr).map_err(|e| Some(e.to_string()))?;
462 // As on accept: clients write a request and wait, so Nagle only adds
463 // a delayed-ACK stall. A failure keeps the connection.
464 let _ = stream.set_nodelay(true);
465 // SAFETY: forwarded caller guarantee.
466 unsafe {
467 let r = wrap(ctx, Socket::Stream(Arc::new(stream)), Some(addr)).map_err(Some)?;
468 // Connected once writable (or failed).
469 loop {
470 let h = handle(r);
471 let Socket::Stream(s) = &h.socket else {
472 unreachable!()
473 };
474 let seen = io_events(ctx);
475 let failed = match s.peer_addr() {
476 Ok(_) => return Ok(r),
477 Err(e) if e.kind() == ErrorKind::NotConnected => match s.take_error() {
478 Ok(Some(e)) | Err(e) => Some(Some(e.to_string())),
479 Ok(None) if !wait_for(ctx, h.token, seen) => Some(None),
480 Ok(None) => None,
481 },
482 Err(e) => Some(Some(e.to_string())),
483 };
484 if let Some(failure) = failed {
485 drop_value(ctx, r);
486 return Err(failure);
487 }
488 }
489 }
490}
491
492/// `read(conn, max)`: up to `max` bytes, as `Bytes`; empty at the end of
493/// the stream.
494///
495/// # Safety
496/// `ctx` must be the running actor's context; `conn` a live connection.
497#[unsafe(no_mangle)]
498pub unsafe extern "C" fn tl_net_read(ctx: *mut Ctx, conn: Value, max: Value) -> Value {
499 // SAFETY: caller guarantees a live Int.
500 let max = unsafe { saturating(max) };
501 let mut buf = vec![0u8; max.clamp(1, 1 << 20) as usize];
502 // SAFETY: caller guarantees a connection on this actor.
503 unsafe {
504 loop {
505 let h = handle(conn);
506 let mut s = match stream(h) {
507 Ok(s) => s,
508 Err(e) => return error(ctx, e),
509 };
510 let seen = io_events(ctx);
511 match s.read(&mut buf) {
512 Ok(n) => return ok(ctx, bytes_from(ctx, &buf[..n])),
513 Err(e) if e.kind() == ErrorKind::WouldBlock => {
514 if !wait_for(ctx, h.token, seen) {
515 return UNIT;
516 }
517 }
518 Err(e) if e.kind() == ErrorKind::Interrupted => {}
519 Err(e) => return error(ctx, &e.to_string()),
520 }
521 }
522 }
523}
524
525/// `write(conn, data)`: all of `data` (`Bytes`).
526///
527/// # Safety
528/// `ctx` must be the running actor's context; `conn` a live connection;
529/// `data` live `Bytes`.
530#[unsafe(no_mangle)]
531pub unsafe extern "C" fn tl_net_write(ctx: *mut Ctx, conn: Value, data: Value) -> Value {
532 // SAFETY: forwarded caller guarantees.
533 unsafe { write_all(ctx, conn, data) }
534}
535
536/// `write_string(conn, s)`: all of `s` (UTF-8).
537///
538/// # Safety
539/// `ctx` must be the running actor's context; `conn` a live connection;
540/// `s` a live string.
541#[unsafe(no_mangle)]
542pub unsafe extern "C" fn tl_net_write_string(ctx: *mut Ctx, conn: Value, s: Value) -> Value {
543 // SAFETY: forwarded caller guarantees.
544 unsafe { write_all(ctx, conn, s) }
545}
546
547/// # Safety
548/// `ctx` must be the running actor's context; `conn` a live connection;
549/// `data` a live string or `Bytes`.
550unsafe fn write_all(ctx: *mut Ctx, conn: Value, data: Value) -> Value {
551 // SAFETY: caller guarantees a connection on this actor and data kept
552 // alive by the parked caller.
553 unsafe {
554 let bytes = bytes_of(data);
555 let mut sent = 0;
556 while sent < bytes.len() {
557 let h = handle(conn);
558 let mut s = match stream(h) {
559 Ok(s) => s,
560 Err(e) => return error(ctx, e),
561 };
562 let seen = io_events(ctx);
563 match s.write(&bytes[sent..]) {
564 Ok(0) => return error(ctx, "connection closed"),
565 Ok(n) => sent += n,
566 Err(e) if e.kind() == ErrorKind::WouldBlock => {
567 if !wait_for(ctx, h.token, seen) {
568 return UNIT;
569 }
570 }
571 Err(e) if e.kind() == ErrorKind::Interrupted => {}
572 Err(e) => return error(ctx, &e.to_string()),
573 }
574 }
575 ok(ctx, UNIT)
576 }
577}
578
579/// `peer(conn)`: `Ok((host, port))`, the other end of a connection, as
580/// it was when accepted or made; the host is an IP address as text
581/// (`127.0.0.1`, `::1`).
582///
583/// # Safety
584/// `ctx` must be the running actor's context; `conn` a live socket.
585#[unsafe(no_mangle)]
586pub unsafe extern "C" fn tl_net_peer(ctx: *mut Ctx, conn: Value) -> Value {
587 // SAFETY: caller guarantees a socket.
588 let h = unsafe { handle(conn) };
589 match (&h.socket, h.peer) {
590 (Socket::Stream(_), Some(peer)) => {
591 let host = string(ctx, &peer.ip().to_string());
592 let address = cell(ctx, 0, &[host, int(i64::from(peer.port()))]);
593 ok(ctx, address)
594 }
595 (Socket::Stream(_), None) => error(ctx, "the connection's peer is not known"),
596 (Socket::Listener(_), _) => error(ctx, "not a connection: a listener"),
597 }
598}
599
600/// `close(conn)`: shut the connection down (the socket is released when
601/// its last reference is dropped).
602///
603/// # Safety
604/// `conn` must be a live socket.
605#[unsafe(no_mangle)]
606pub unsafe extern "C" fn tl_net_close(_ctx: *mut Ctx, conn: Value) -> Value {
607 // SAFETY: caller guarantees a socket.
608 if let Socket::Stream(s) = unsafe { &handle(conn).socket } {
609 let _ = s.shutdown(std::net::Shutdown::Both);
610 }
611 UNIT
612}
613
614/// `close_listener(listener)`: stop listening. New clients are refused
615/// (the socket is shut down), and `accept`, including one an actor is
616/// parked in, fails with "the listener is closed". The socket is released
617/// when its last reference is dropped.
618///
619/// # Safety
620/// `ctx` must be the running actor's context; `listener` a live socket.
621#[unsafe(no_mangle)]
622pub unsafe extern "C" fn tl_net_close_listener(ctx: *mut Ctx, listener: Value) -> Value {
623 // SAFETY: caller guarantees a socket on this actor.
624 let h = unsafe { handle(listener) };
625 if let Socket::Listener(l) = &h.socket
626 && !h.closed.swap(true, Ordering::AcqRel)
627 {
628 use std::os::fd::AsRawFd;
629 // SAFETY: the descriptor is the listener's, open while `h` is.
630 unsafe { libc::shutdown(l.as_raw_fd(), libc::SHUT_RDWR) };
631 // SAFETY: forwarded caller guarantee.
632 let (_, sched) = unsafe { this(ctx) };
633 sched.wake_token(h.token);
634 }
635 UNIT
636}
637
638/// What `accept` on a closed listener answers.
639const CLOSED: &str = "the listener is closed";
640
641/// What reading or writing an upgraded connection answers.
642const UPGRADED: &str = "this connection was upgraded to TLS: use the TLS stream";
643
644/// Give `conn`'s socket and token to a TLS stream (`tls.rs`): the
645/// connection keeps the socket only to shut it down.
646///
647/// # Safety
648/// `conn` must be a live socket resource.
649#[cfg_attr(not(feature = "tls"), allow(dead_code))]
650pub(crate) unsafe fn upgrade(conn: Value) -> Result<(Arc<TcpStream>, Token), String> {
651 // SAFETY: caller guarantees a socket resource.
652 let h = unsafe { handle(conn) };
653 let Socket::Stream(s) = &h.socket else {
654 return Err("a listener can't be a TLS stream".into());
655 };
656 // Once: a second upgrade (or one racing it) finds it taken.
657 if h.upgraded.swap(true, Ordering::AcqRel) {
658 return Err("this connection is already a TLS stream's".into());
659 }
660 Ok((s.clone(), h.token))
661}
662
663#[cfg(test)]
664mod tests {
665 use super::*;
666 use crate::abi::{Block, UNIT, int};
667 #[cfg(test)]
668 use crate::heap::dup_value;
669 use crate::values::{closure_code_borrowed, string};
670
671 #[test]
672 fn the_net_capability_is_immortal_and_built_once() {
673 let cap = net_cap();
674 assert_eq!(cap, net_cap());
675 // Construction returns the same static clauses without mutating their
676 // parameters or allocating replacements in the counted heap.
677 // SAFETY: `net_cap` constructs the immutable block and its statically
678 // declared three clauses. The tested layout has the known field count.
679 unsafe {
680 let b = cap as *mut Block;
681 assert_eq!((*b).header.rc, 0);
682 let n = (*b).header.scan_fsize as usize;
683 assert_eq!(n, louise_rt_prims::NET_OPS.len() + 1);
684 let fields = Block::fields_ptr(b);
685 assert_eq!(fields.add(n - 1).read(), int(0), "the marker");
686 for i in 0..n - 1 {
687 let clause = fields.add(i).read() as *mut Block;
688 assert_eq!((*clause).header.rc, 0);
689 }
690 }
691 }
692
693 /// Perform an operation through its actual root clause, either through the
694 /// owned general call or the fixed-arity borrowed adapter. At most two
695 /// arguments, never a reinterpreted hidden capability argument.
696 unsafe fn perform(ctx: *mut Ctx, op: &str, args: &[Value], owned: bool) -> Value {
697 // SAFETY: callers provide the active context and correctly typed live
698 // arguments. The root outlives the call; its declared closure carries
699 // the actual C function with five fixed argument registers.
700 unsafe {
701 assert!(args.len() <= 2);
702 let i = louise_rt_prims::NET_OPS
703 .iter()
704 .position(|name| *name == op)
705 .expect("a net operation");
706 let cap = crate::process::root_cap(crate::process::RootCap::Net);
707 let clause = Block::fields_ptr(cap as *mut Block).add(i).read();
708 if owned {
709 let clause = dup_value(clause);
710 drop_value(ctx, cap);
711 return crate::prims::call_closure(ctx, clause, args);
712 }
713 let mut regs = [UNIT; 5];
714 regs[..args.len()].copy_from_slice(args);
715 let code: Code = std::mem::transmute(closure_code_borrowed(clause));
716 let out = code(ctx, clause, regs[0], regs[1], regs[2], regs[3], regs[4]);
717 drop_value(ctx, cap);
718 out
719 }
720 }
721
722 /// The one field of the `Ok` cell an operation returned.
723 unsafe fn ok0(v: Value) -> Value {
724 // SAFETY: the test reads the cell the operation just made.
725 unsafe { *Block::fields_ptr(v as *mut Block) }
726 }
727
728 /// Resolve, open, connect and accept through the real root, on loopback only.
729 /// Both owned and borrowed root adapters are exercised and the returned
730 /// socket Resources are then used by the same handle-mediated io kernels.
731 unsafe extern "C" fn root_roundtrip(ctx: *mut Ctx) -> Value {
732 // SAFETY: generated-code convention; every result is released below.
733 // Loopback connect is established before the matching accept here.
734 unsafe {
735 let host = string(ctx, "127.0.0.1");
736 let resolved = perform(ctx, "resolve", &[dup_value(host)], true);
737 assert_eq!((*(resolved as *mut Block)).header.tag, 0, "resolver Ok");
738 let resolved_borrowed = perform(ctx, "resolve", &[host], false);
739 assert_eq!(
740 (*(resolved_borrowed as *mut Block)).header.tag,
741 0,
742 "borrowed resolver Ok"
743 );
744 let hostname = string(ctx, "not-a-literal.invalid");
745 let bad_listen = perform(ctx, "listen_at", &[dup_value(hostname), int(0)], true);
746 let bad_connect = perform(ctx, "connect_to", &[hostname, int(443)], false);
747 for refused in [bad_listen, bad_connect] {
748 assert_eq!(
749 (*(refused as *mut Block)).header.tag,
750 1,
751 "address-level roots must not do scheduler DNS"
752 );
753 let why = Block::fields_ptr(refused as *mut Block).read();
754 assert_eq!(
755 text(why),
756 "address is not an IP literal",
757 "a resolver error is not the deterministic guard"
758 );
759 }
760
761 let listener = perform(ctx, "listen_at", &[dup_value(host), int(0)], true);
762 assert_eq!((*(listener as *mut Block)).header.tag, 0, "listener Ok");
763 let port = tl_net_port(ctx, ok0(listener));
764 let conn = perform(ctx, "connect_to", &[host, port], false);
765 assert_eq!((*(conn as *mut Block)).header.tag, 0, "connection Ok");
766 let accepted = tl_net_accept(ctx, ok0(listener));
767 for end in [ok0(conn), ok0(accepted)] {
768 let Socket::Stream(s) = &handle(end).socket else {
769 panic!("a connection");
770 };
771 assert!(s.nodelay().expect("nodelay is readable"));
772 }
773 tl_net_close(ctx, ok0(conn));
774 tl_net_close(ctx, ok0(accepted));
775 tl_net_close_listener(ctx, ok0(listener));
776 for v in [
777 resolved,
778 resolved_borrowed,
779 bad_listen,
780 bad_connect,
781 hostname,
782 host,
783 listener,
784 conn,
785 accepted,
786 ] {
787 drop_value(ctx, v);
788 }
789 let threads = io_threads();
790 assert_eq!(threads.len(), 2, "one record per resolution: {threads:?}");
791 assert!(
792 threads
793 .iter()
794 .all(|name| name.starts_with("louise-blocking-io-")),
795 "DNS must not run on a scheduler: {threads:?}"
796 );
797 }
798 assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0);
799 UNIT
800 }
801
802 #[test]
803 fn root_adapters_resolve_and_open_loopback_sockets_without_leaks() {
804 // SAFETY: the test follows the generated-code convention.
805 let code = unsafe { crate::sched::run_test_actor(root_roundtrip) };
806 assert_eq!(code, 0);
807 }
808}