| @@ -0,0 +1,368 @@ |
| 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. |
| 10 | +//! - A kill wakes a parked actor, which unwinds. |
| 11 | +//! |
| 12 | +//! Results are `Result`s (`Ok` 0, `Error` 1) with the error text. |
| 13 | + |
| 14 | +use std::io::{ErrorKind, Read, Write}; |
| 15 | +use std::net::ToSocketAddrs; |
| 16 | + |
| 17 | +use mio::net::{TcpListener, TcpStream}; |
| 18 | +use mio::{Interest, Token}; |
| 19 | + |
| 20 | +use crate::abi::{Block, Ctx, UNIT, Value, YIELD_NONE, int, int_get}; |
| 21 | +use crate::heap::{drop_value, tl_alloc}; |
| 22 | +use crate::prims::{text_of, tl_resource_get, tl_resource_new}; |
| 23 | +use crate::sched::{Wait, park, this}; |
| 24 | +use crate::values::{string_bytes, tl_string_from}; |
| 25 | + |
| 26 | +enum Socket { |
| 27 | + Listener(TcpListener), |
| 28 | + Stream(TcpStream), |
| 29 | +} |
| 30 | + |
| 31 | +struct Handle { |
| 32 | + socket: Socket, |
| 33 | + token: Token, |
| 34 | +} |
| 35 | + |
| 36 | +unsafe extern "C" fn finalize(p: *mut std::ffi::c_void) { |
| 37 | + // SAFETY: made by `wrap`, finalized once; dropping closes the socket |
| 38 | + // (and removes it from the reactor). |
| 39 | + drop(unsafe { Box::from_raw(p.cast::<Handle>()) }); |
| 40 | +} |
| 41 | + |
| 42 | +fn wrap1(tag: u16, v: Value) -> Value { |
| 43 | + let b = tl_alloc(std::ptr::null_mut(), tag, 1, 0); |
| 44 | + // SAFETY: a fresh block with one field. |
| 45 | + unsafe { Block::fields_ptr(b).write(v) }; |
| 46 | + b as Value |
| 47 | +} |
| 48 | + |
| 49 | +fn ok(v: Value) -> Value { |
| 50 | + wrap1(0, v) |
| 51 | +} |
| 52 | + |
| 53 | +fn error(ctx: *mut Ctx, message: &str) -> Value { |
| 54 | + // SAFETY: `message` is valid for its length. |
| 55 | + wrap1(1, unsafe { |
| 56 | + tl_string_from(ctx, message.as_ptr().cast(), message.len()) |
| 57 | + }) |
| 58 | +} |
| 59 | + |
| 60 | +/// Register a socket with the reactor and wrap it as a resource. |
| 61 | +/// |
| 62 | +/// # Safety |
| 63 | +/// `ctx` must be the running actor's context. |
| 64 | +unsafe fn wrap(ctx: *mut Ctx, mut socket: Socket) -> Result<Value, String> { |
| 65 | + // SAFETY: forwarded caller guarantee. |
| 66 | + let (_, sched) = unsafe { this(ctx) }; |
| 67 | + let token = sched.borrow_mut().io_token(); |
| 68 | + { |
| 69 | + let s = sched.borrow(); |
| 70 | + let registry = s.reactor().registry(); |
| 71 | + let interest = Interest::READABLE | Interest::WRITABLE; |
| 72 | + match &mut socket { |
| 73 | + Socket::Listener(l) => registry.register(l, token, interest), |
| 74 | + Socket::Stream(st) => registry.register(st, token, interest), |
| 75 | + } |
| 76 | + .map_err(|e| e.to_string())?; |
| 77 | + } |
| 78 | + let handle = Box::into_raw(Box::new(Handle { socket, token })); |
| 79 | + Ok(tl_resource_new(ctx, handle.cast(), Some(finalize), true)) |
| 80 | +} |
| 81 | + |
| 82 | +/// # Safety |
| 83 | +/// `r` must be a live socket resource. |
| 84 | +unsafe fn handle<'a>(r: Value) -> &'a mut Handle { |
| 85 | + // SAFETY: caller guarantees a socket resource. |
| 86 | + unsafe { &mut *tl_resource_get(r).cast::<Handle>() } |
| 87 | +} |
| 88 | + |
| 89 | +/// Park until the socket's token fires (or the actor is stopped: false). |
| 90 | +/// |
| 91 | +/// # Safety |
| 92 | +/// `ctx` must be the running actor's context. |
| 93 | +unsafe fn wait_for(ctx: *mut Ctx, token: Token) -> bool { |
| 94 | + // SAFETY: forwarded caller guarantee. |
| 95 | + unsafe { |
| 96 | + let (a, sched) = this(ctx); |
| 97 | + a.wait = Wait::Io; |
| 98 | + sched.borrow_mut().io_waiters.insert(token, a.pid); |
| 99 | + let v = park(ctx); |
| 100 | + drop_value(ctx, v); |
| 101 | + sched.borrow_mut().io_waiters.remove(&token); |
| 102 | + (*ctx).yielding == YIELD_NONE |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +/// `listen(host, port)`: a listening socket. |
| 107 | +/// |
| 108 | +/// # Safety |
| 109 | +/// `ctx` must be the running actor's context; `host` a live string. |
| 110 | +#[unsafe(no_mangle)] |
| 111 | +pub unsafe extern "C" fn tl_net_listen(ctx: *mut Ctx, host: Value, port: Value) -> Value { |
| 112 | + // SAFETY: caller guarantees a live string. |
| 113 | + let host = unsafe { text_of(host) }; |
| 114 | + let addr = match (host, int_get(port) as u16) |
| 115 | + .to_socket_addrs() |
| 116 | + .map(|mut a| a.next()) |
| 117 | + { |
| 118 | + Ok(Some(a)) => a, |
| 119 | + Ok(None) => return error(ctx, "no address"), |
| 120 | + Err(e) => return error(ctx, &e.to_string()), |
| 121 | + }; |
| 122 | + match TcpListener::bind(addr) { |
| 123 | + // SAFETY: forwarded caller guarantee. |
| 124 | + Ok(l) => match unsafe { wrap(ctx, Socket::Listener(l)) } { |
| 125 | + Ok(r) => ok(r), |
| 126 | + Err(e) => error(ctx, &e), |
| 127 | + }, |
| 128 | + Err(e) => error(ctx, &e.to_string()), |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +/// The local port of a listening socket (useful after binding port 0). |
| 133 | +/// |
| 134 | +/// # Safety |
| 135 | +/// `listener` must be a live listening socket. |
| 136 | +#[unsafe(no_mangle)] |
| 137 | +pub unsafe extern "C" fn tl_net_port(_ctx: *mut Ctx, listener: Value) -> Value { |
| 138 | + // SAFETY: caller guarantees a socket. |
| 139 | + match unsafe { &handle(listener).socket } { |
| 140 | + Socket::Listener(l) => int(l.local_addr().map_or(0, |a| i64::from(a.port()))), |
| 141 | + Socket::Stream(s) => int(s.local_addr().map_or(0, |a| i64::from(a.port()))), |
| 142 | + } |
| 143 | +} |
| 144 | + |
| 145 | +/// `accept(listener)`: the next connection. |
| 146 | +/// |
| 147 | +/// # Safety |
| 148 | +/// `ctx` must be the running actor's context; `listener` a live socket. |
| 149 | +#[unsafe(no_mangle)] |
| 150 | +pub unsafe extern "C" fn tl_net_accept(ctx: *mut Ctx, listener: Value) -> Value { |
| 151 | + // SAFETY: caller guarantees a socket on this actor. |
| 152 | + unsafe { |
| 153 | + loop { |
| 154 | + let h = handle(listener); |
| 155 | + let Socket::Listener(l) = &h.socket else { |
| 156 | + return error(ctx, "accept on a connection"); |
| 157 | + }; |
| 158 | + match l.accept() { |
| 159 | + Ok((stream, _)) => { |
| 160 | + return match wrap(ctx, Socket::Stream(stream)) { |
| 161 | + Ok(r) => ok(r), |
| 162 | + Err(e) => error(ctx, &e), |
| 163 | + }; |
| 164 | + } |
| 165 | + Err(e) if e.kind() == ErrorKind::WouldBlock => { |
| 166 | + if !wait_for(ctx, h.token) { |
| 167 | + return UNIT; |
| 168 | + } |
| 169 | + } |
| 170 | + Err(e) if e.kind() == ErrorKind::Interrupted => {} |
| 171 | + Err(e) => return error(ctx, &e.to_string()), |
| 172 | + } |
| 173 | + } |
| 174 | + } |
| 175 | +} |
| 176 | + |
| 177 | +/// `connect(host, port)`: a connection to a server. |
| 178 | +/// |
| 179 | +/// # Safety |
| 180 | +/// `ctx` must be the running actor's context; `host` a live string. |
| 181 | +#[unsafe(no_mangle)] |
| 182 | +pub unsafe extern "C" fn tl_net_connect(ctx: *mut Ctx, host: Value, port: Value) -> Value { |
| 183 | + // SAFETY: caller guarantees a live string. |
| 184 | + let host = unsafe { text_of(host) }; |
| 185 | + let addr = match (host, int_get(port) as u16) |
| 186 | + .to_socket_addrs() |
| 187 | + .map(|mut a| a.next()) |
| 188 | + { |
| 189 | + Ok(Some(a)) => a, |
| 190 | + Ok(None) => return error(ctx, "no address"), |
| 191 | + Err(e) => return error(ctx, &e.to_string()), |
| 192 | + }; |
| 193 | + let stream = match TcpStream::connect(addr) { |
| 194 | + Ok(s) => s, |
| 195 | + Err(e) => return error(ctx, &e.to_string()), |
| 196 | + }; |
| 197 | + // SAFETY: forwarded caller guarantee. |
| 198 | + unsafe { |
| 199 | + let r = match wrap(ctx, Socket::Stream(stream)) { |
| 200 | + Ok(r) => r, |
| 201 | + Err(e) => return error(ctx, &e), |
| 202 | + }; |
| 203 | + // Connected once writable (or failed). |
| 204 | + loop { |
| 205 | + let h = handle(r); |
| 206 | + let Socket::Stream(s) = &h.socket else { |
| 207 | + unreachable!() |
| 208 | + }; |
| 209 | + match s.peer_addr() { |
| 210 | + Ok(_) => return ok(r), |
| 211 | + Err(e) if e.kind() == ErrorKind::NotConnected => { |
| 212 | + if let Ok(Some(e)) | Err(e) = s.take_error() { |
| 213 | + drop_value(ctx, r); |
| 214 | + return error(ctx, &e.to_string()); |
| 215 | + } |
| 216 | + if !wait_for(ctx, h.token) { |
| 217 | + drop_value(ctx, r); |
| 218 | + return UNIT; |
| 219 | + } |
| 220 | + } |
| 221 | + Err(e) => { |
| 222 | + drop_value(ctx, r); |
| 223 | + return error(ctx, &e.to_string()); |
| 224 | + } |
| 225 | + } |
| 226 | + } |
| 227 | + } |
| 228 | +} |
| 229 | + |
| 230 | +/// `read(conn, max)`: up to `max` bytes (invalid UTF-8 replaced); `""` at |
| 231 | +/// the end of the stream. |
| 232 | +/// |
| 233 | +/// # Safety |
| 234 | +/// `ctx` must be the running actor's context; `conn` a live connection. |
| 235 | +#[unsafe(no_mangle)] |
| 236 | +pub unsafe extern "C" fn tl_net_read(ctx: *mut Ctx, conn: Value, max: Value) -> Value { |
| 237 | + let mut buf = vec![0u8; int_get(max).clamp(1, 1 << 20) as usize]; |
| 238 | + // SAFETY: caller guarantees a connection on this actor. |
| 239 | + unsafe { |
| 240 | + loop { |
| 241 | + let h = handle(conn); |
| 242 | + let Socket::Stream(s) = &mut h.socket else { |
| 243 | + return error(ctx, "read on a listener"); |
| 244 | + }; |
| 245 | + match s.read(&mut buf) { |
| 246 | + Ok(n) => { |
| 247 | + let text = String::from_utf8_lossy(&buf[..n]); |
| 248 | + return ok(tl_string_from(ctx, text.as_ptr().cast(), text.len())); |
| 249 | + } |
| 250 | + Err(e) if e.kind() == ErrorKind::WouldBlock => { |
| 251 | + if !wait_for(ctx, h.token) { |
| 252 | + return UNIT; |
| 253 | + } |
| 254 | + } |
| 255 | + Err(e) if e.kind() == ErrorKind::Interrupted => {} |
| 256 | + Err(e) => return error(ctx, &e.to_string()), |
| 257 | + } |
| 258 | + } |
| 259 | + } |
| 260 | +} |
| 261 | + |
| 262 | +/// `write(conn, data)`: all of `data`. |
| 263 | +/// |
| 264 | +/// # Safety |
| 265 | +/// `ctx` must be the running actor's context; `conn` a live connection; |
| 266 | +/// `data` a live string. |
| 267 | +#[unsafe(no_mangle)] |
| 268 | +pub unsafe extern "C" fn tl_net_write(ctx: *mut Ctx, conn: Value, data: Value) -> Value { |
| 269 | + // SAFETY: caller guarantees a connection on this actor and a string, |
| 270 | + // kept alive by the parked caller. |
| 271 | + unsafe { |
| 272 | + let bytes = string_bytes(data); |
| 273 | + let mut sent = 0; |
| 274 | + while sent < bytes.len() { |
| 275 | + let h = handle(conn); |
| 276 | + let Socket::Stream(s) = &mut h.socket else { |
| 277 | + return error(ctx, "write on a listener"); |
| 278 | + }; |
| 279 | + match s.write(&bytes[sent..]) { |
| 280 | + Ok(0) => return error(ctx, "connection closed"), |
| 281 | + Ok(n) => sent += n, |
| 282 | + Err(e) if e.kind() == ErrorKind::WouldBlock => { |
| 283 | + if !wait_for(ctx, h.token) { |
| 284 | + return UNIT; |
| 285 | + } |
| 286 | + } |
| 287 | + Err(e) if e.kind() == ErrorKind::Interrupted => {} |
| 288 | + Err(e) => return error(ctx, &e.to_string()), |
| 289 | + } |
| 290 | + } |
| 291 | + ok(UNIT) |
| 292 | + } |
| 293 | +} |
| 294 | + |
| 295 | +/// `close(conn)`: shut the connection down (the socket is released when |
| 296 | +/// its last reference is dropped). |
| 297 | +/// |
| 298 | +/// # Safety |
| 299 | +/// `conn` must be a live socket. |
| 300 | +#[unsafe(no_mangle)] |
| 301 | +pub unsafe extern "C" fn tl_net_close(_ctx: *mut Ctx, conn: Value) -> Value { |
| 302 | + // SAFETY: caller guarantees a socket. |
| 303 | + if let Socket::Stream(s) = unsafe { &handle(conn).socket } { |
| 304 | + let _ = s.shutdown(std::net::Shutdown::Both); |
| 305 | + } |
| 306 | + UNIT |
| 307 | +} |
| 308 | + |
| 309 | +// ---- HTTP request heads (httparse, a port of picohttpparser) ---------------------- |
| 310 | + |
| 311 | +/// Parse the head of an HTTP/1.x request at the start of `buffer`: |
| 312 | +/// - `Partial` (0) if more bytes are needed; |
| 313 | +/// - `Invalid(reason)` (1); |
| 314 | +/// - `Complete(method, path, headers, rest, content_length)` (2), where |
| 315 | +/// `rest` is what follows the head and `content_length` is -1 when |
| 316 | +/// absent. |
| 317 | +/// |
| 318 | +/// # Safety |
| 319 | +/// `buffer` must be a live string. |
| 320 | +#[unsafe(no_mangle)] |
| 321 | +pub unsafe extern "C" fn tl_http_parse_request(ctx: *mut Ctx, buffer: Value) -> Value { |
| 322 | + // SAFETY: caller guarantees a live string. |
| 323 | + let bytes = unsafe { string_bytes(buffer) }; |
| 324 | + let mut headers = [httparse::EMPTY_HEADER; 64]; |
| 325 | + let mut req = httparse::Request::new(&mut headers); |
| 326 | + let consumed = match req.parse(bytes) { |
| 327 | + Ok(httparse::Status::Partial) => return int(0), |
| 328 | + Ok(httparse::Status::Complete(n)) => n, |
| 329 | + Err(e) => return wrap1(1, string(ctx, &e.to_string())), |
| 330 | + }; |
| 331 | + let mut content_length = -1i64; |
| 332 | + let mut list = int(0); // Nil |
| 333 | + for h in req.headers.iter().rev() { |
| 334 | + let value = String::from_utf8_lossy(h.value); |
| 335 | + if h.name.eq_ignore_ascii_case("content-length") { |
| 336 | + content_length = value.trim().parse().unwrap_or(-1); |
| 337 | + } |
| 338 | + let pair = tl_alloc(std::ptr::null_mut(), 0, 2, 0); |
| 339 | + let cell = tl_alloc(std::ptr::null_mut(), 1, 2, 0); |
| 340 | + // SAFETY: fresh blocks with two fields each. |
| 341 | + unsafe { |
| 342 | + let p = Block::fields_ptr(pair); |
| 343 | + p.write(string(ctx, h.name)); |
| 344 | + p.add(1).write(string(ctx, &value)); |
| 345 | + let c = Block::fields_ptr(cell); |
| 346 | + c.write(pair as Value); |
| 347 | + c.add(1).write(list); |
| 348 | + } |
| 349 | + list = cell as Value; |
| 350 | + } |
| 351 | + let rest = String::from_utf8_lossy(&bytes[consumed..]); |
| 352 | + let b = tl_alloc(std::ptr::null_mut(), 2, 5, 0); |
| 353 | + // SAFETY: a fresh block with five fields. |
| 354 | + unsafe { |
| 355 | + let f = Block::fields_ptr(b); |
| 356 | + f.write(string(ctx, req.method.unwrap_or(""))); |
| 357 | + f.add(1).write(string(ctx, req.path.unwrap_or(""))); |
| 358 | + f.add(2).write(list); |
| 359 | + f.add(3).write(string(ctx, &rest)); |
| 360 | + f.add(4).write(int(content_length)); |
| 361 | + } |
| 362 | + b as Value |
| 363 | +} |
| 364 | + |
| 365 | +fn string(ctx: *mut Ctx, s: &str) -> Value { |
| 366 | + // SAFETY: `s` is valid for its length. |
| 367 | + unsafe { tl_string_from(ctx, s.as_ptr().cast(), s.len()) } |
| 368 | +} |