From 17ba68ff570df21b8df795dc3fda3c00791259bc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 11:29:47 -0800 Subject: [PATCH 1/2] craft-control: read request lines with craft-control-protocol's bounded reader The server's private line reader is replaced by craft_control_protocol::read_bounded_line, and client::outcome now returns craft_control_protocol::reply_result. craft-control and craft-control-protocol read the same request framing with one reader. Behavior changes in the server's reader: - A line longer than the server's max_line is refused even when its newline arrives in the same read. Before, the limit was checked only between reads, so such a line was accepted and up to one buffer past the limit was allocated. - A read interrupted by a signal is retried instead of closing the connection. - A \r before the newline is dropped from the line. - The refusal names the limit: "request line longer than N bytes; closing the connection" instead of "request too large". --- Cargo.lock | 1 + crates/control/Cargo.toml | 2 + crates/control/src/client.rs | 9 ++-- crates/control/src/server.rs | 90 +++++++++++++++++++++++++----------- 4 files changed, 68 insertions(+), 34 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 673ffe4f87..2e8787f494 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1713,6 +1713,7 @@ version = "0.1.0" dependencies = [ "craft-ai-agents", "craft-atomic", + "craft-control-protocol", "craft-flags", "dirs", "getrandom 0.3.4", diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 3e756aff75..efe1f1e446 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -24,6 +24,8 @@ serde_json = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] # The per-launch control token: 32 random bytes from the operating system (MIT OR Apache-2.0). getrandom = "0.3" +# The request-line reader and the reply's result, shared with servers built on it (MIT OR Apache-2.0, ours). +craft-control-protocol = { workspace = true } # The launcher's app list, read in one place for the launcher, the gateway and every app (MIT OR Apache-2.0, ours). craft-ai-agents = { workspace = true, optional = true } craft-atomic = { workspace = true, optional = true } diff --git a/crates/control/src/client.rs b/crates/control/src/client.rs index cbad788504..346602759b 100644 --- a/crates/control/src/client.rs +++ b/crates/control/src/client.rs @@ -117,13 +117,10 @@ impl Request { } } -/// A control reply as a call's result: its `result`, or its `error`. +/// A control reply as a call's result: its `result`, or its `error` +/// ([`craft_control_protocol::reply_result`]). pub fn outcome(v: &Value) -> Result { - if v.get("ok").and_then(Value::as_bool) == Some(true) { - Ok(v.get("result").cloned().unwrap_or(Value::Null)) - } else { - Err(v.get("error").and_then(Value::as_str).unwrap_or("error").to_string()) - } + craft_control_protocol::reply_result(v) } /// A request the app said is still running. Its reply will come on this connection, through diff --git a/crates/control/src/server.rs b/crates/control/src/server.rs index 85664a1aa9..521be789b4 100644 --- a/crates/control/src/server.rs +++ b/crates/control/src/server.rs @@ -10,6 +10,7 @@ use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::time::{Duration, Instant}; +use craft_control_protocol::ReadFailure; use serde_json::{Value, json}; use crate::Effect; @@ -215,35 +216,18 @@ pub fn new_token() -> Option { Some(bytes.iter().map(|b| format!("{b:02x}")).collect()) } -/// One line without its newline, or `None` at the end of the stream. A client that sends -/// gigabytes with no newline would otherwise make this thread allocate until the process is -/// killed, so the line is refused as soon as it passes `max`. +/// One line without its newline (and a `\r` before it), or `None` at the end of the stream, read +/// with [`craft_control_protocol::read_bounded_line`]. A line of more than `max` bytes is refused +/// with `InvalidData`, and at most `max + 1` bytes of it are buffered, so a client that sends +/// gigabytes with no newline cannot make this thread allocate until the process is killed. A read +/// that times out (the token deadline) fails with `TimedOut`. fn read_line(r: &mut impl BufRead, max: usize) -> std::io::Result>> { let mut line = Vec::new(); - loop { - let (done, used) = { - let available = r.fill_buf()?; - if available.is_empty() { - return Ok((!line.is_empty()).then_some(line)); - } - match available.iter().position(|b| *b == b'\n') { - Some(i) => { - line.extend_from_slice(available.get(..i).unwrap_or(&[])); - (true, i + 1) - } - None => { - line.extend_from_slice(available); - (false, available.len()) - } - } - }; - r.consume(used); - if done { - return Ok(Some(line)); - } - if line.len() > max { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "request too large")); - } + match craft_control_protocol::read_bounded_line(r, &mut line, max) { + Ok(true) => Ok(Some(line)), + Ok(false) => Ok(None), + Err(ReadFailure::Timeout) => Err(std::io::ErrorKind::TimedOut.into()), + Err(ReadFailure::Rejected(e)) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)), } } @@ -1335,7 +1319,57 @@ mod tests { let mut r = BufReader::new(flood.as_slice()); let e = read_line(&mut r, MAX_LINE).unwrap_err(); assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); - assert!(e.to_string().contains("request too large"), "{e}"); + assert!(e.to_string().contains(&format!("longer than {MAX_LINE} bytes")), "{e}"); + } + + /// The cap is exact: a line of `max` bytes is read, and one byte more is refused even when its + /// newline arrives in the same read as the rest of it. + #[test] + fn the_cap_holds_for_a_line_read_at_once() { + let mut fits = vec![b'A'; 1000]; + fits.push(b'\n'); + assert_eq!(read_line(&mut BufReader::new(fits.as_slice()), 1000).unwrap().unwrap().len(), 1000); + let mut over = vec![b'A'; 1001]; + over.push(b'\n'); + let e = read_line(&mut BufReader::new(over.as_slice()), 1000).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); + } + + /// A read interrupted by a signal is tried again instead of ending the connection, and a + /// `\r` before the newline is not part of the line. + #[test] + fn interrupted_reads_are_retried() { + struct Interrupting(Vec<&'static [u8]>); + impl std::io::Read for Interrupting { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if self.0.is_empty() { + return Ok(0); + } + let chunk = self.0.remove(0); + if chunk.is_empty() { + return Err(std::io::ErrorKind::Interrupted.into()); + } + buf[..chunk.len()].copy_from_slice(chunk); + Ok(chunk.len()) + } + } + let mut r = BufReader::new(Interrupting(vec![b"", b"{\"a\"", b"", b":1}\r\n"])); + assert_eq!(read_line(&mut r, MAX_LINE).unwrap().unwrap(), b"{\"a\":1}"); + assert!(read_line(&mut r, MAX_LINE).unwrap().is_none()); + } + + /// A read that times out before the token is shown fails with `TimedOut`, which closes the + /// connection without a reply. + #[test] + fn timed_out_reads_report_timed_out() { + struct Slow; + impl std::io::Read for Slow { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + Err(std::io::ErrorKind::WouldBlock.into()) + } + } + let e = read_line(&mut BufReader::new(Slow), MAX_LINE).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::TimedOut); } /// Ordinary framing: lines split on newlines, blank lines kept, no trailing newline needed. From 8a13f644db20782711d745f5cdfa6d969c90f1b3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:46:45 -0800 Subject: [PATCH 2/2] craft-control-protocol: the line cap does not count the line's \r\n read_bounded_line read at most max + 1 bytes, so a line of exactly max bytes followed by \r\n stopped after the \r and was refused, while the same line followed by \n was read. It now reads up to max + 2 bytes, strips the \n and a \r before it, and then checks the line against max. A line of max + 1 bytes is still refused with either ending. --- crates/control-protocol/src/lib.rs | 16 +++++++++++----- crates/control/src/server.rs | 28 ++++++++++++++++------------ 2 files changed, 27 insertions(+), 17 deletions(-) diff --git a/crates/control-protocol/src/lib.rs b/crates/control-protocol/src/lib.rs index 8bdb08d660..99de6f07c8 100644 --- a/crates/control-protocol/src/lib.rs +++ b/crates/control-protocol/src/lib.rs @@ -72,12 +72,14 @@ pub enum ReadFailure { Rejected(String), } -/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped). +/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped, and a `\r` +/// before it). The `\r\n` or `\n` does not count toward `max`. /// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails. pub fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usize) -> Result { buf.clear(); - // `take` bounds the bytes buffered for one line: a peer can't make us allocate more than `max`. - let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1); + // `take` bounds the bytes buffered for one line: a peer can't make us allocate more than + // `max + 2`, the line and its `\r\n`. + let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(2); let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| match e.kind() { std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => ReadFailure::Timeout, _ => ReadFailure::Rejected(e.to_string()), @@ -90,12 +92,11 @@ pub fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usiz if buf.last() == Some(&b'\r') { buf.pop(); } - return Ok(true); } if buf.len() > max { return Err(ReadFailure::Rejected(format!("request line longer than {max} bytes; closing the connection"))); } - // Last line without a newline, then end of stream. + // A complete line, or the last line without a newline, then end of stream. Ok(true) } @@ -226,6 +227,11 @@ mod tests { assert_eq!(read_bounded_line(&mut &b"abc"[..], &mut buf, 3), Ok(true)); assert_eq!(buf, b"abc"); assert!(matches!(read_bounded_line(&mut &b"abcd"[..], &mut buf, 3), Err(ReadFailure::Rejected(_)))); + // The cap counts the line without its `\r\n` or `\n`. + assert_eq!(read_bounded_line(&mut &b"abc\r\n"[..], &mut buf, 3), Ok(true)); + assert_eq!(buf, b"abc"); + assert!(matches!(read_bounded_line(&mut &b"abcd\n"[..], &mut buf, 3), Err(ReadFailure::Rejected(_)))); + assert!(matches!(read_bounded_line(&mut &b"abcd\r\n"[..], &mut buf, 3), Err(ReadFailure::Rejected(_)))); let mut out = Vec::new(); serve_lines(&b"{broken}\n"[..], &mut out, "secret", 1024, |_, _| panic!("must not dispatch")); let reply: Value = serde_json::from_slice(&out).unwrap(); diff --git a/crates/control/src/server.rs b/crates/control/src/server.rs index 521be789b4..a09482f04d 100644 --- a/crates/control/src/server.rs +++ b/crates/control/src/server.rs @@ -217,10 +217,11 @@ pub fn new_token() -> Option { } /// One line without its newline (and a `\r` before it), or `None` at the end of the stream, read -/// with [`craft_control_protocol::read_bounded_line`]. A line of more than `max` bytes is refused -/// with `InvalidData`, and at most `max + 1` bytes of it are buffered, so a client that sends -/// gigabytes with no newline cannot make this thread allocate until the process is killed. A read -/// that times out (the token deadline) fails with `TimedOut`. +/// with [`craft_control_protocol::read_bounded_line`]. A line of more than `max` bytes, not +/// counting its `\r\n` or `\n`, is refused with `InvalidData`, and at most `max + 2` bytes of it +/// are buffered, so a client that sends gigabytes with no newline cannot make this thread +/// allocate until the process is killed. A read that times out (the token deadline) fails with +/// `TimedOut`. fn read_line(r: &mut impl BufRead, max: usize) -> std::io::Result>> { let mut line = Vec::new(); match craft_control_protocol::read_bounded_line(r, &mut line, max) { @@ -1323,16 +1324,19 @@ mod tests { } /// The cap is exact: a line of `max` bytes is read, and one byte more is refused even when its - /// newline arrives in the same read as the rest of it. + /// newline arrives in the same read as the rest of it. The `\r\n` or `\n` after the line does + /// not count toward the cap. #[test] fn the_cap_holds_for_a_line_read_at_once() { - let mut fits = vec![b'A'; 1000]; - fits.push(b'\n'); - assert_eq!(read_line(&mut BufReader::new(fits.as_slice()), 1000).unwrap().unwrap().len(), 1000); - let mut over = vec![b'A'; 1001]; - over.push(b'\n'); - let e = read_line(&mut BufReader::new(over.as_slice()), 1000).unwrap_err(); - assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); + for end in [&b"\n"[..], &b"\r\n"[..]] { + let mut fits = vec![b'A'; 1000]; + fits.extend_from_slice(end); + assert_eq!(read_line(&mut BufReader::new(fits.as_slice()), 1000).unwrap().unwrap().len(), 1000); + let mut over = vec![b'A'; 1001]; + over.extend_from_slice(end); + let e = read_line(&mut BufReader::new(over.as_slice()), 1000).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); + } } /// A read interrupted by a signal is tried again instead of ending the connection, and a