tobogganSe connecter

louise

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

547 lignes · 20714 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::{SocketAddr, ToSocketAddrs};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30
31use mio::net::{TcpListener, TcpStream};
32use mio::{Interest, Token};
33
34use crate::abi::{Ctx, UNIT, Value, YIELD_NONE, int};
35use crate::heap::drop_value;
36use crate::int::saturating;
37use crate::otp::Wait;
38use crate::resource::{tl_resource_get, tl_resource_new};
39use crate::sched::{park, this};
40use crate::values::{bytes_from, bytes_of, cell, error, list, ok, string, text};
41
42enum Socket {
43 Listener(TcpListener),
44 Stream(Arc<TcpStream>),
45}
46
47/// A socket resource. Any actor may hold it, so nothing here changes
48/// after it is made but `upgraded`.
49struct Handle {
50 socket: Socket,
51 token: Token,
52 /// The other end of a connection, recorded when it was accepted or
53 /// made (issue #308): a reset connection may no longer say.
54 peer: Option<SocketAddr>,
55 /// Given to a TLS stream, with the token (`upgrade`).
56 upgraded: AtomicBool,
57 /// A listener closed by `tl_net_close_listener`: `accept` fails.
58 closed: AtomicBool,
59}
60
61unsafe extern "C" fn finalize(p: *mut std::ffi::c_void) {
62 // SAFETY: made by `wrap`, finalized once; dropping closes the socket
63 // (and removes it from the reactor). Finalizers never run under the
64 // scheduler lock.
65 unsafe {
66 drop(Box::from_raw(p.cast::<Handle>()));
67 }
68}
69
70/// Register a socket with the reactor and wrap it as a resource.
71///
72/// # Safety
73/// `ctx` must be the running actor's context.
74unsafe fn wrap(
75 ctx: *mut Ctx,
76 mut socket: Socket,
77 peer: Option<SocketAddr>,
78) -> Result<Value, String> {
79 // SAFETY: forwarded caller guarantee.
80 let (_, sched) = unsafe { this(ctx) };
81 let token = sched.io_token();
82 sched
83 .with_registry(|registry| {
84 let interest = Interest::READABLE | Interest::WRITABLE;
85 match &mut socket {
86 Socket::Listener(l) => registry.register(l, token, interest),
87 Socket::Stream(st) => {
88 // Not shared yet: registered before anyone else has it.
89 let st = Arc::get_mut(st).expect("a new socket");
90 registry.register(st, token, interest)
91 }
92 }
93 })
94 .map_err(|e| e.to_string())?;
95 let handle = Box::into_raw(Box::new(Handle {
96 socket,
97 token,
98 peer,
99 upgraded: AtomicBool::new(false),
100 closed: AtomicBool::new(false),
101 }));
102 Ok(tl_resource_new(ctx, handle.cast(), Some(finalize), true))
103}
104
105/// # Safety
106/// `r` must be a live socket resource.
107unsafe fn handle<'a>(r: Value) -> &'a Handle {
108 // SAFETY: caller guarantees a socket resource.
109 unsafe { &*tl_resource_get(r).cast::<Handle>() }
110}
111
112/// The connection of `h`, unless it is a listener or was upgraded.
113fn stream(h: &Handle) -> Result<&TcpStream, &'static str> {
114 match &h.socket {
115 Socket::Stream(_) if h.upgraded.load(Ordering::Acquire) => Err(UPGRADED),
116 Socket::Stream(s) => Ok(s),
117 Socket::Listener(_) => Err("not a connection: a listener"),
118 }
119}
120
121/// The reactor's event count, read before an operation that may find
122/// `WouldBlock`, for [`wait_for`].
123///
124/// # Safety
125/// `ctx` must be the running actor's context.
126pub(crate) unsafe fn io_events(ctx: *mut Ctx) -> u64 {
127 // SAFETY: forwarded caller guarantee.
128 unsafe { this(ctx).1.io_events() }
129}
130
131/// Park until the socket's token fires (or the actor is stopped: false).
132/// `seen` is the event count read before the operation that blocked
133/// ([`io_events`]): if it moved since, this returns at once, to retry.
134///
135/// # Safety
136/// `ctx` must be the running actor's context.
137pub(crate) unsafe fn wait_for(ctx: *mut Ctx, token: Token, seen: u64) -> bool {
138 // SAFETY: forwarded caller guarantee.
139 unsafe {
140 let (a, sched) = this(ctx);
141 // Waiting first, then registered: an event in between moves the
142 // count, which `io_wait` checks.
143 a.with_proc(|p| p.park_as(Wait::Io));
144 if !sched.io_wait(token, a.pid, seen) {
145 a.with_proc(|p| p.wait = Wait::Ready);
146 return true; // An event meanwhile: retry.
147 }
148 let v = park(ctx);
149 drop_value(ctx, v);
150 sched.io_unwait(token, a.pid);
151 (*ctx).yielding == YIELD_NONE
152 }
153}
154
155/// `resolve(host)`: the addresses `host` names, as text (`127.0.0.1`,
156/// `::1`), in the resolver's order. A lookup can take seconds, so this is
157/// a `blocking` extern: it runs on the blocking pool while its actor waits
158/// (ADR 0012, Revision 2), and must not panic.
159///
160/// # Safety
161/// `host` must be a live string.
162#[unsafe(no_mangle)]
163pub unsafe extern "C" fn tl_net_resolve(ctx: *mut Ctx, host: Value) -> Value {
164 // SAFETY: caller guarantees a live string.
165 let host = unsafe { text(host) };
166 match (host, 0).to_socket_addrs() {
167 Ok(addrs) => {
168 let addrs: Vec<Value> = addrs.map(|a| string(ctx, &a.ip().to_string())).collect();
169 ok(ctx, list(ctx, addrs.into_iter()))
170 }
171 Err(e) => error(ctx, &e.to_string()),
172 }
173}
174
175/// A port given as an Int: 0 to 65535, else the error.
176fn port_number(port: i64) -> Result<u16, String> {
177 u16::try_from(port).map_err(|_| format!("port out of range: {port}"))
178}
179
180/// `listen(address, port)`: a listening socket. `std/net` resolves the
181/// host first ([`tl_net_resolve`]), so `address` is an IP address, which
182/// needs no lookup here.
183///
184/// # Safety
185/// `ctx` must be the running actor's context; `host` a live string.
186#[unsafe(no_mangle)]
187pub unsafe extern "C" fn tl_net_listen(ctx: *mut Ctx, host: Value, port: Value) -> Value {
188 // SAFETY: caller guarantees a live string and a live Int.
189 let (host, port) = unsafe { (text(host), saturating(port)) };
190 let port = match port_number(port) {
191 Ok(p) => p,
192 Err(e) => return error(ctx, &e),
193 };
194 let addr = match (host, port).to_socket_addrs().map(|mut a| a.next()) {
195 Ok(Some(a)) => a,
196 Ok(None) => return error(ctx, "no address"),
197 Err(e) => return error(ctx, &e.to_string()),
198 };
199 match TcpListener::bind(addr) {
200 // SAFETY: forwarded caller guarantee.
201 Ok(l) => match unsafe { wrap(ctx, Socket::Listener(l), None) } {
202 Ok(r) => ok(ctx, r),
203 Err(e) => error(ctx, &e),
204 },
205 Err(e) => error(ctx, &e.to_string()),
206 }
207}
208
209/// The local port of a listening socket (useful after binding port 0).
210///
211/// # Safety
212/// `listener` must be a live listening socket.
213#[unsafe(no_mangle)]
214pub unsafe extern "C" fn tl_net_port(_ctx: *mut Ctx, listener: Value) -> Value {
215 // SAFETY: caller guarantees a socket.
216 match unsafe { &handle(listener).socket } {
217 Socket::Listener(l) => int(l.local_addr().map_or(0, |a| i64::from(a.port()))),
218 Socket::Stream(s) => int(s.local_addr().map_or(0, |a| i64::from(a.port()))),
219 }
220}
221
222/// `accept(listener)`: the next connection.
223///
224/// # Safety
225/// `ctx` must be the running actor's context; `listener` a live socket.
226#[unsafe(no_mangle)]
227pub unsafe extern "C" fn tl_net_accept(ctx: *mut Ctx, listener: Value) -> Value {
228 // SAFETY: caller guarantees a socket on this actor.
229 unsafe {
230 loop {
231 let h = handle(listener);
232 let Socket::Listener(l) = &h.socket else {
233 return error(ctx, "accept on a connection");
234 };
235 if h.closed.load(Ordering::Acquire) {
236 return error(ctx, CLOSED);
237 }
238 let seen = io_events(ctx);
239 match l.accept() {
240 Ok((stream, peer)) => {
241 // A server answers a request with one write, and a
242 // streamed response flushes a write per chunk (ADR
243 // 0053): Nagle would hold each back for a delayed ACK
244 // (40 ms stalls). A failure keeps the connection.
245 let _ = stream.set_nodelay(true);
246 return match wrap(ctx, Socket::Stream(Arc::new(stream)), Some(peer)) {
247 Ok(r) => ok(ctx, r),
248 Err(e) => error(ctx, &e),
249 };
250 }
251 Err(e) if e.kind() == ErrorKind::WouldBlock => {
252 if !wait_for(ctx, h.token, seen) {
253 return UNIT;
254 }
255 }
256 Err(e) if e.kind() == ErrorKind::Interrupted => {}
257 Err(e) => return error(ctx, &e.to_string()),
258 }
259 }
260 }
261}
262
263/// `connect(address, port)`: a connection to a server. `std/net`
264/// resolves the host first ([`tl_net_resolve`]) and tries each address in
265/// turn, so `address` is an IP address, which needs no lookup here.
266///
267/// # Safety
268/// `ctx` must be the running actor's context; `host` a live string.
269#[unsafe(no_mangle)]
270pub unsafe extern "C" fn tl_net_connect(ctx: *mut Ctx, host: Value, port: Value) -> Value {
271 // SAFETY: caller guarantees a live string and a live Int.
272 let (host, port) = unsafe { (text(host), saturating(port)) };
273 let port = match port_number(port) {
274 Ok(p) => p,
275 Err(e) => return error(ctx, &e),
276 };
277 let addrs: Vec<SocketAddr> = match (host, port).to_socket_addrs() {
278 Ok(a) => a.collect(),
279 Err(e) => return error(ctx, &e.to_string()),
280 };
281 let mut last = String::from("no address");
282 for addr in addrs {
283 // SAFETY: forwarded caller guarantee.
284 match unsafe { connect_to(ctx, addr) } {
285 Ok(r) => return ok(ctx, r),
286 Err(Some(e)) => last = e,
287 // Stopped while waiting: unwinding.
288 Err(None) => return UNIT,
289 }
290 }
291 error(ctx, &last)
292}
293
294/// A connection to `addr`, once established. `Err(None)`: the actor was
295/// stopped while waiting.
296///
297/// # Safety
298/// `ctx` must be the running actor's context.
299unsafe fn connect_to(ctx: *mut Ctx, addr: SocketAddr) -> Result<Value, Option<String>> {
300 let stream = TcpStream::connect(addr).map_err(|e| Some(e.to_string()))?;
301 // As on accept: clients write a request and wait, so Nagle only adds
302 // a delayed-ACK stall. A failure keeps the connection.
303 let _ = stream.set_nodelay(true);
304 // SAFETY: forwarded caller guarantee.
305 unsafe {
306 let r = wrap(ctx, Socket::Stream(Arc::new(stream)), Some(addr)).map_err(Some)?;
307 // Connected once writable (or failed).
308 loop {
309 let h = handle(r);
310 let Socket::Stream(s) = &h.socket else {
311 unreachable!()
312 };
313 let seen = io_events(ctx);
314 let failed = match s.peer_addr() {
315 Ok(_) => return Ok(r),
316 Err(e) if e.kind() == ErrorKind::NotConnected => match s.take_error() {
317 Ok(Some(e)) | Err(e) => Some(Some(e.to_string())),
318 Ok(None) if !wait_for(ctx, h.token, seen) => Some(None),
319 Ok(None) => None,
320 },
321 Err(e) => Some(Some(e.to_string())),
322 };
323 if let Some(failure) = failed {
324 drop_value(ctx, r);
325 return Err(failure);
326 }
327 }
328 }
329}
330
331/// `read(conn, max)`: up to `max` bytes, as `Bytes`; empty at the end of
332/// the stream.
333///
334/// # Safety
335/// `ctx` must be the running actor's context; `conn` a live connection.
336#[unsafe(no_mangle)]
337pub unsafe extern "C" fn tl_net_read(ctx: *mut Ctx, conn: Value, max: Value) -> Value {
338 // SAFETY: caller guarantees a live Int.
339 let max = unsafe { saturating(max) };
340 let mut buf = vec![0u8; max.clamp(1, 1 << 20) as usize];
341 // SAFETY: caller guarantees a connection on this actor.
342 unsafe {
343 loop {
344 let h = handle(conn);
345 let mut s = match stream(h) {
346 Ok(s) => s,
347 Err(e) => return error(ctx, e),
348 };
349 let seen = io_events(ctx);
350 match s.read(&mut buf) {
351 Ok(n) => return ok(ctx, bytes_from(ctx, &buf[..n])),
352 Err(e) if e.kind() == ErrorKind::WouldBlock => {
353 if !wait_for(ctx, h.token, seen) {
354 return UNIT;
355 }
356 }
357 Err(e) if e.kind() == ErrorKind::Interrupted => {}
358 Err(e) => return error(ctx, &e.to_string()),
359 }
360 }
361 }
362}
363
364/// `write(conn, data)`: all of `data` (`Bytes`).
365///
366/// # Safety
367/// `ctx` must be the running actor's context; `conn` a live connection;
368/// `data` live `Bytes`.
369#[unsafe(no_mangle)]
370pub unsafe extern "C" fn tl_net_write(ctx: *mut Ctx, conn: Value, data: Value) -> Value {
371 // SAFETY: forwarded caller guarantees.
372 unsafe { write_all(ctx, conn, data) }
373}
374
375/// `write_string(conn, s)`: all of `s` (UTF-8).
376///
377/// # Safety
378/// `ctx` must be the running actor's context; `conn` a live connection;
379/// `s` a live string.
380#[unsafe(no_mangle)]
381pub unsafe extern "C" fn tl_net_write_string(ctx: *mut Ctx, conn: Value, s: Value) -> Value {
382 // SAFETY: forwarded caller guarantees.
383 unsafe { write_all(ctx, conn, s) }
384}
385
386/// # Safety
387/// `ctx` must be the running actor's context; `conn` a live connection;
388/// `data` a live string or `Bytes`.
389unsafe fn write_all(ctx: *mut Ctx, conn: Value, data: Value) -> Value {
390 // SAFETY: caller guarantees a connection on this actor and data kept
391 // alive by the parked caller.
392 unsafe {
393 let bytes = bytes_of(data);
394 let mut sent = 0;
395 while sent < bytes.len() {
396 let h = handle(conn);
397 let mut s = match stream(h) {
398 Ok(s) => s,
399 Err(e) => return error(ctx, e),
400 };
401 let seen = io_events(ctx);
402 match s.write(&bytes[sent..]) {
403 Ok(0) => return error(ctx, "connection closed"),
404 Ok(n) => sent += n,
405 Err(e) if e.kind() == ErrorKind::WouldBlock => {
406 if !wait_for(ctx, h.token, seen) {
407 return UNIT;
408 }
409 }
410 Err(e) if e.kind() == ErrorKind::Interrupted => {}
411 Err(e) => return error(ctx, &e.to_string()),
412 }
413 }
414 ok(ctx, UNIT)
415 }
416}
417
418/// `peer(conn)`: `Ok((host, port))`, the other end of a connection, as
419/// it was when accepted or made; the host is an IP address as text
420/// (`127.0.0.1`, `::1`).
421///
422/// # Safety
423/// `ctx` must be the running actor's context; `conn` a live socket.
424#[unsafe(no_mangle)]
425pub unsafe extern "C" fn tl_net_peer(ctx: *mut Ctx, conn: Value) -> Value {
426 // SAFETY: caller guarantees a socket.
427 let h = unsafe { handle(conn) };
428 match (&h.socket, h.peer) {
429 (Socket::Stream(_), Some(peer)) => {
430 let host = string(ctx, &peer.ip().to_string());
431 let address = cell(ctx, 0, &[host, int(i64::from(peer.port()))]);
432 ok(ctx, address)
433 }
434 (Socket::Stream(_), None) => error(ctx, "the connection's peer is not known"),
435 (Socket::Listener(_), _) => error(ctx, "not a connection: a listener"),
436 }
437}
438
439/// `close(conn)`: shut the connection down (the socket is released when
440/// its last reference is dropped).
441///
442/// # Safety
443/// `conn` must be a live socket.
444#[unsafe(no_mangle)]
445pub unsafe extern "C" fn tl_net_close(_ctx: *mut Ctx, conn: Value) -> Value {
446 // SAFETY: caller guarantees a socket.
447 if let Socket::Stream(s) = unsafe { &handle(conn).socket } {
448 let _ = s.shutdown(std::net::Shutdown::Both);
449 }
450 UNIT
451}
452
453/// `close_listener(listener)`: stop listening. New clients are refused
454/// (the socket is shut down), and `accept`, including one an actor is
455/// parked in, fails with "the listener is closed". The socket is released
456/// when its last reference is dropped.
457///
458/// # Safety
459/// `ctx` must be the running actor's context; `listener` a live socket.
460#[unsafe(no_mangle)]
461pub unsafe extern "C" fn tl_net_close_listener(ctx: *mut Ctx, listener: Value) -> Value {
462 // SAFETY: caller guarantees a socket on this actor.
463 let h = unsafe { handle(listener) };
464 if let Socket::Listener(l) = &h.socket
465 && !h.closed.swap(true, Ordering::AcqRel)
466 {
467 use std::os::fd::AsRawFd;
468 // SAFETY: the descriptor is the listener's, open while `h` is.
469 unsafe { libc::shutdown(l.as_raw_fd(), libc::SHUT_RDWR) };
470 // SAFETY: forwarded caller guarantee.
471 let (_, sched) = unsafe { this(ctx) };
472 sched.wake_token(h.token);
473 }
474 UNIT
475}
476
477/// What `accept` on a closed listener answers.
478const CLOSED: &str = "the listener is closed";
479
480/// What reading or writing an upgraded connection answers.
481const UPGRADED: &str = "this connection was upgraded to TLS: use the TLS stream";
482
483/// Give `conn`'s socket and token to a TLS stream (`tls.rs`): the
484/// connection keeps the socket only to shut it down.
485///
486/// # Safety
487/// `conn` must be a live socket resource.
488#[cfg_attr(not(feature = "tls"), allow(dead_code))]
489pub(crate) unsafe fn upgrade(conn: Value) -> Result<(Arc<TcpStream>, Token), String> {
490 // SAFETY: caller guarantees a socket resource.
491 let h = unsafe { handle(conn) };
492 let Socket::Stream(s) = &h.socket else {
493 return Err("a listener can't be a TLS stream".into());
494 };
495 // Once: a second upgrade (or one racing it) finds it taken.
496 if h.upgraded.swap(true, Ordering::AcqRel) {
497 return Err("this connection is already a TLS stream's".into());
498 }
499 Ok((s.clone(), h.token))
500}
501
502#[cfg(test)]
503mod tests {
504 use super::*;
505 use crate::abi::{Block, UNIT, int};
506 use crate::values::string;
507
508 /// The one field of the `Ok` cell an extern returned.
509 unsafe fn ok0(v: Value) -> Value {
510 // SAFETY: the test reads the cell the extern just made.
511 unsafe { *Block::fields_ptr(v as *mut Block) }
512 }
513
514 /// Accepted and connected sockets both have Nagle off: a response is
515 /// one flushed write per chunk (ADR 0053), which Nagle would hold
516 /// back for a delayed ACK.
517 unsafe extern "C" fn accepted_sockets_disable_nagle(ctx: *mut Ctx) -> Value {
518 // SAFETY: the test follows the generated-code convention; every
519 // value it makes is dropped below. Loopback: the connect is
520 // established at once, so the accept never parks.
521 unsafe {
522 let host = string(ctx, "127.0.0.1");
523 let listener = tl_net_listen(ctx, host, int(0));
524 let port = tl_net_port(ctx, ok0(listener));
525 let conn = tl_net_connect(ctx, host, port);
526 let accepted = tl_net_accept(ctx, ok0(listener));
527 for end in [ok0(conn), ok0(accepted)] {
528 let Socket::Stream(s) = &handle(end).socket else {
529 panic!("a connection");
530 };
531 assert!(s.nodelay().expect("nodelay is readable"));
532 }
533 for v in [host, listener, conn, accepted] {
534 drop_value(ctx, v);
535 }
536 }
537 assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0);
538 UNIT
539 }
540
541 #[test]
542 fn sockets_disable_nagle() {
543 // SAFETY: the test follows the generated-code convention.
544 let code = unsafe { crate::sched::run_test_actor(accepted_sockets_disable_nagle) };
545 assert_eq!(code, 0);
546 }
547}