diff --git a/Cargo.lock b/Cargo.lock index 4ceb52f2fe..5f4b353bd1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2275,6 +2275,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 04f8983550..a276060c81 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,54 +216,19 @@ pub fn new_token() -> Option { Some(bytes.iter().map(|b| format!("{b:02x}")).collect()) } -/// One line without its newline (and a `\r` before it), or `None` at the end of the stream. A -/// line of more than `max` bytes, not counting its `\r\n` or `\n`, is refused with `InvalidData`. -/// A client that sends gigabytes with no newline would otherwise make this thread allocate until -/// the process is killed, so a line with no newline yet is refused once it holds more than -/// `max + 1` bytes. A read interrupted by a signal is tried again, and a read that times out (the -/// token deadline) fails with `TimedOut`. +/// 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, 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 too_long = || std::io::Error::new(std::io::ErrorKind::InvalidData, format!("request line longer than {max} bytes; closing the connection")); let mut line = Vec::new(); - loop { - let (done, used) = { - let available = match r.fill_buf() { - Ok(available) => available, - Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => return Err(std::io::ErrorKind::TimedOut.into()), - Err(e) => return Err(e), - }; - if available.is_empty() { - if line.len() > max { - return Err(too_long()); - } - 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 { - if line.last() == Some(&b'\r') { - line.pop(); - } - if line.len() > max { - return Err(too_long()); - } - return Ok(Some(line)); - } - // One byte past `max` may be the `\r` of a `\r\n` whose `\n` has not arrived yet. - if line.len() > max.saturating_add(1) { - return Err(too_long()); - } + 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)), } }