//! The board, live, over a WebSocket (RFC 6455): `GET /v1/stream`. //! //! The hub sends JSON text messages, the state of things (board.rs), never //! what happened: //! //! * `{"type":"snapshot","version":1,"entities":{key: entity, …},"page":tag}` first, //! and again whenever the page asks; `page` names the build of the page this //! hub serves (web.rs `build`), for a page left open to load a new one; //! * `{"type":"patch","version":n,"upsert":{key: entity, …},"remove":[key, …]}` //! for each change after, every changed entity whole — a page replaces what it //! has and is right again. Versions count up by one on a connection; a page //! that sees a gap sends `{"type":"resync"}` and gets a snapshot. //! //! A new kind of entity is a new key prefix, which an older page ignores. The //! page may send `resync`, and `{"type":"follow","session":id,"after":n}` to //! get one agent session's log as it is written (`{"type":"log",…}`, from line //! n). What changes the workspace stays on the HTTP API, behind the caller key //! or the login and its role. //! //! Messages are compressed when the page offers permessage-deflate (RFC 7692). //! A thread per connection like the rest of the hub: a reader thread //! answers pings and hears the page; the writer checks the shared board every //! second and pings every 25 s, which also keeps a proxy from timing it out. use std::io::{BufRead, Read, Write}; use std::net::TcpStream; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::{self, RecvTimeoutError}; use std::sync::Mutex; use std::time::{Duration, Instant}; use anyhow::{bail, Result}; use serde_json::{json, Value}; use sha1::{Digest, Sha1}; use crate::board; const GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; /// A page's own messages are small; anything bigger is not one. const MAX_IN: u64 = 64 * 1024; /// Open streams at most: each holds a thread. const MAX_STREAMS: usize = 32; const PING: Duration = Duration::from_secs(25); static OPEN: AtomicUsize = AtomicUsize::new(0); /// `Sec-WebSocket-Accept` for a `Sec-WebSocket-Key`. pub fn accept(key: &str) -> String { let mut h = Sha1::new(); h.update(key.trim().as_bytes()); h.update(GUID.as_bytes()); data_encoding::BASE64.encode(&h.finalize()) } /// One frame, unmasked (a server's). pub fn frame(opcode: u8, payload: &[u8]) -> Vec { let mut f = vec![0x80 | opcode]; match payload.len() { n if n < 126 => f.push(n as u8), n if n <= 0xffff => { f.push(126); f.extend_from_slice(&(n as u16).to_be_bytes()); } n => { f.push(127); f.extend_from_slice(&(n as u64).to_be_bytes()); } } f.extend_from_slice(payload); f } /// One message frame, compressed (RFC 7692): RSV1 says so. fn frame_deflated(opcode: u8, payload: &[u8]) -> Vec { let mut f = frame(opcode, &deflate(payload)); f[0] |= 0x40; f } /// A message's payload as permessage-deflate sends it, each on its own (no context /// kept between them): raw DEFLATE ending in a sync flush, its `00 00 ff ff` cut off. pub fn deflate(payload: &[u8]) -> Vec { use miniz_oxide::deflate::core::{compress, create_comp_flags_from_zip_params, CompressorOxide, TDEFLFlush, TDEFLStatus}; // Level 6, raw (negative window bits: no zlib header), the default strategy. let mut c = CompressorOxide::new(create_comp_flags_from_zip_params(6, -15, 0)); let mut out = vec![0u8; payload.len() / 2 + 64]; let (mut read, mut wrote) = (0, 0); loop { let (status, r, w) = compress(&mut c, &payload[read..], &mut out[wrote..], TDEFLFlush::Sync); read += r; wrote += w; // All in and flushed, with room to spare: a sync flush that filled the buffer may have more. if status != TDEFLStatus::Okay || (read == payload.len() && wrote < out.len()) { break; } out.resize(out.len() * 2, 0); } out.truncate(wrote); if out.ends_with(&[0, 0, 0xff, 0xff]) { out.truncate(out.len() - 4); } out } /// A compressed message from the page, as it was: the cut-off sync flush put back, /// and an empty final block after it so the stream ends. pub fn inflate(payload: &[u8]) -> Result> { let mut whole = payload.to_vec(); whole.extend_from_slice(&[0, 0, 0xff, 0xff, 0x01, 0, 0, 0xff, 0xff]); miniz_oxide::inflate::decompress_to_vec_with_limit(&whole, MAX_IN as usize).map_err(|e| anyhow::anyhow!("a compressed frame that would not inflate: {e:?}")) } /// One frame from the page: `(opcode, payload)`, unmasked. A client's frames /// are always masked (RFC 6455 §5.1). #[cfg(test)] fn read_frame(r: &mut impl Read) -> Result<(u8, Vec)> { let (h0, payload) = read_raw(r, MAX_IN)?; Ok((h0 & 0x0f, payload)) } /// One frame from a client that may send up to `max` bytes in it (a device's /// answer, device.rs): `(opcode, payload)`, unmasked. Uncompressed, unfragmented. pub fn read_client_frame(r: &mut impl Read, max: u64) -> Result<(u8, Vec)> { let (h0, payload) = read_raw(r, max)?; if h0 & 0x40 != 0 { bail!("a compressed frame, which was not offered"); } if h0 & 0x80 == 0 { bail!("a fragmented message: send each whole"); } Ok((h0 & 0x0f, payload)) } /// One frame from the page, inflated when it says it was compressed. fn read_message(r: &mut impl Read) -> Result<(u8, Vec)> { let (h0, payload) = read_raw(r, MAX_IN)?; if h0 & 0x40 != 0 { return Ok((h0 & 0x0f, inflate(&payload)?)); } Ok((h0 & 0x0f, payload)) } /// A frame's first byte (FIN, RSV, opcode) and its payload, unmasked. fn read_raw(r: &mut impl Read, max: u64) -> Result<(u8, Vec)> { let mut h = [0u8; 2]; r.read_exact(&mut h)?; let opcode = h[0]; if h[1] & 0x80 == 0 { bail!("an unmasked frame from a client"); } let len = match h[1] & 0x7f { 126 => { let mut b = [0u8; 2]; r.read_exact(&mut b)?; u16::from_be_bytes(b) as u64 } 127 => { let mut b = [0u8; 8]; r.read_exact(&mut b)?; u64::from_be_bytes(b) } n => n as u64, }; if len > max { bail!("a {len}-byte frame"); } let mut mask = [0u8; 4]; r.read_exact(&mut mask)?; let mut payload = vec![0u8; len as usize]; r.read_exact(&mut payload)?; for (i, b) in payload.iter_mut().enumerate() { *b ^= mask[i % 4]; } Ok((opcode, payload)) } enum In { Resync, /// The page is following one agent session's log, from line `after`. Follow(String, u64), Ping(Vec), Closed, /// Something was written ([`nudge`]): look now rather than at the next tick. Wake, } /// Every open stream's writer, to wake. static WRITERS: Mutex>> = Mutex::new(Vec::new()); /// Wake every open stream to look at the board and its followed log now: the /// hub wrote an event or a session's log. Without it a change waited for the /// writer's next tick, up to a second, before a page saw it. pub fn nudge() { WRITERS.lock().unwrap_or_else(|p| p.into_inner()).retain(|tx| tx.send(In::Wake).is_ok()); } /// Answer the upgrade and stream until the page goes. `reader` is the /// request's, past its headers; `extensions` its `Sec-WebSocket-Extensions`. /// /// A page that offers permessage-deflate (every browser does) gets its messages /// compressed, each on its own: the first snapshot was 262 KB as text and 41 KB /// so, and a long session's log, sent whole when it is opened, a megabyte or more. pub fn serve(mut stream: TcpStream, mut reader: impl BufRead + Send + 'static, key: &str, extensions: &str) -> Result<()> { let deflated = extensions.split(',').any(|e| e.split(';').next().unwrap_or("").trim() == "permessage-deflate"); if OPEN.fetch_add(1, Ordering::SeqCst) >= MAX_STREAMS { OPEN.fetch_sub(1, Ordering::SeqCst); write!(stream, "HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")?; return Ok(()); } struct Open; impl Drop for Open { fn drop(&mut self) { OPEN.fetch_sub(1, Ordering::SeqCst); } } let _open = Open; write!(stream, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\ Sec-WebSocket-Accept: {}\r\n{}\r\n", accept(key), if deflated { "Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n" } else { "" })?; // A page may say nothing for hours, but its browser answers every ping (`PING`) with a pong: // nothing at all for this long is a page gone without closing (a phone off the network), // which with no limit held its stream and two threads until TCP gave up, a quarter of an hour. stream.set_read_timeout(Some(PING * 2 + Duration::from_secs(10)))?; stream.set_write_timeout(Some(Duration::from_secs(10)))?; // When this side ends (a write timed out) the socket is shut, or the reader waits on it // until its timeout, a thread and a descriptor held with nobody there. struct Shut(TcpStream); impl Drop for Shut { fn drop(&mut self) { let _ = self.0.shutdown(std::net::Shutdown::Both); } } let _shut = Shut(stream.try_clone()?); let (tx, rx) = mpsc::channel(); WRITERS.lock().unwrap_or_else(|p| p.into_inner()).push(tx.clone()); std::thread::Builder::new().spawn(move || { let said = loop { match read_message(&mut reader) { Ok((0x1, text)) => { let v: Value = serde_json::from_slice(&text).unwrap_or(Value::Null); let msg = match v["type"].as_str() { Some("resync") => Some(In::Resync), Some("follow") => v["session"].as_str().map(|s| In::Follow(s.to_string(), v["after"].as_u64().unwrap_or(0))), _ => None, }; if let Some(m) = msg { if tx.send(m).is_err() { return; } } } Ok((0x9, p)) => if tx.send(In::Ping(p)).is_err() { return }, Ok((0x8, _)) | Err(_) => break In::Closed, Ok(_) => {} // pongs, binary, continuations: nothing a page sends us } }; let _ = tx.send(said); })?; // Small ones as they are: compressing a few bytes saves nothing. let send = |s: &mut TcpStream, v: &Value| { let text = v.to_string(); s.write_all(&if deflated && text.len() > 256 { frame_deflated(0x1, text.as_bytes()) } else { frame(0x1, text.as_bytes()) }) }; let mut version = 1u64; let mut have = board::current(); send(&mut stream, &json!({"type": "snapshot", "version": version, "entities": *have, "page": crate::web::build()}))?; let mut pinged = Instant::now(); // The followed session, the last line the page has, and where the last look ended. let mut following: Option<(String, u64, (u64, u64))> = None; // The followed log's size when last read: read again only once it grows. let mut read_at: Option = None; loop { // A followed session's text arrives as it is written: look often then. // What the hub writes itself wakes this at once (`nudge`). let wait = if following.is_some() { Duration::from_millis(250) } else { Duration::from_secs(1) }; match rx.recv_timeout(wait) { Ok(In::Closed) | Err(RecvTimeoutError::Disconnected) => { let _ = stream.write_all(&frame(0x8, &[])); return Ok(()); } Ok(In::Ping(p)) => stream.write_all(&frame(0xA, &p))?, Ok(In::Follow(id, after)) => { following = Some((id, after, (0, 0))); read_at = None; } Ok(In::Resync) => { version += 1; have = board::current(); send(&mut stream, &json!({"type": "snapshot", "version": version, "entities": *have, "page": crate::web::build()}))?; } Ok(In::Wake) | Err(RecvTimeoutError::Timeout) => {} } let now = board::current(); if !std::sync::Arc::ptr_eq(&now, &have) { let (upsert, remove) = board::diff(&have, &now); have = now; if !upsert.is_empty() || !remove.is_empty() { version += 1; send(&mut stream, &json!({"type": "patch", "version": version, "upsert": upsert, "remove": remove}))?; } } if let Some((id, after, at)) = &mut following { // Each look read the whole log again, four times a second, a megabyte for a long // session: now only once it grew, and only what it grew by. let size = crate::sessions::log_size(id); if size != read_at { read_at = size; if let Some((items, next)) = crate::sessions::tail(id, at, *after) { send(&mut stream, &json!({"type": "log", "session": id, "items": items, "next": next}))?; *after = next; } } } if pinged.elapsed() >= PING { stream.write_all(&frame(0x9, b"midas"))?; pinged = Instant::now(); } } } #[cfg(test)] mod tests { use super::*; #[test] fn the_handshake_and_frames_are_rfc_6455s() { // RFC 6455 §1.3's example. assert_eq!(accept("dGhlIHNhbXBsZSBub25jZQ=="), "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="); assert_eq!(frame(0x1, b"Hi"), [0x81, 2, b'H', b'i']); assert_eq!(&frame(0x1, &[0u8; 300])[..4], &[0x81, 126, 1, 44]); assert_eq!(&frame(0x1, &vec![0u8; 70000])[..10], &[0x81, 127, 0, 0, 0, 0, 0, 1, 0x11, 0x70]); // §5.7: a masked "Hello" from a client. let masked = [0x81u8, 0x85, 0x37, 0xfa, 0x21, 0x3d, 0x7f, 0x9f, 0x4d, 0x51, 0x58]; assert_eq!(read_frame(&mut &masked[..]).unwrap(), (0x1, b"Hello".to_vec())); assert!(read_frame(&mut &[0x81u8, 0x05, b'H', b'e', b'l', b'l', b'o'][..]).is_err(), "a client must mask"); } #[test] fn compressed_messages_are_rfc_7692s() { // §7.2.3.1's example: "Hello", compressed, as a browser sends it. assert_eq!(inflate(&[0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00]).unwrap(), b"Hello"); // What the hub sends inflates back as a browser would, and has its sync flush cut off. let board = serde_json::to_vec(&json!({"type": "snapshot", "entities": (0..500).map(|i| json!({"kind": "hosted", "id": format!("s{i}"), "title": "a session", "status": "stopped"})).collect::>()})).unwrap(); let sent = deflate(&board); assert!(sent.len() < board.len() / 5, "{} of {}", sent.len(), board.len()); assert!(!sent.ends_with(&[0, 0, 0xff, 0xff])); let mut whole = sent.clone(); whole.extend_from_slice(&[0, 0, 0xff, 0xff]); assert_eq!(miniz_oxide::inflate::decompress_to_vec(&[whole.as_slice(), &[0x01, 0, 0, 0xff, 0xff]].concat()).unwrap(), board); assert_eq!(deflate(b"").is_empty() || inflate(&deflate(b"")).unwrap().is_empty(), true); // The frame says it is compressed (RSV1), and a page's masked compressed frame reads back whole. assert_eq!(frame_deflated(0x1, b"Hello")[0], 0xc1); let mask = [1u8, 2, 3, 4]; let body = [0xf2u8, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00]; let mut f = vec![0xc1u8, 0x80 | body.len() as u8]; f.extend_from_slice(&mask); f.extend(body.iter().enumerate().map(|(i, b)| b ^ mask[i % 4])); assert_eq!(read_message(&mut &f[..]).unwrap(), (0x1, b"Hello".to_vec())); } }