From 2cd7ee735b2a58b85924d63f2c0a573afe5e99d9 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 19:39:01 +0000 Subject: [PATCH 1/2] fix(appd): keep a component's message whole when the relay also forwards one from the page The session's IPC relay read component messages with read_line inside select!, into a buffer created anew on each pass. When a message from the page won the select while a component message was half read, the read part was lost, and the page received the remainder as a message of its own. The line was also unbounded. The relay now keeps the frame being read across passes and fills it with read_until, which keeps partial reads when cancelled. It ends the relay on a line longer than any message the runtime sends. A new test writes half a component message, has the relay forward a page message, then completes it and checks that it arrives whole. On the previous code the test receives only the second half. It also checks that an overlong line ends the relay. --- crates/weft-appd/src/runtime.rs | 66 +++++++++++++++++++++++++++++++-- 1 file changed, 62 insertions(+), 4 deletions(-) diff --git a/crates/weft-appd/src/runtime.rs b/crates/weft-appd/src/runtime.rs index 6f9cce9..1ce6cf1 100644 --- a/crates/weft-appd/src/runtime.rs +++ b/crates/weft-appd/src/runtime.rs @@ -1,7 +1,7 @@ use std::path::PathBuf; use std::time::Duration; -use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, BufWriter}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, BufWriter}; use weft_ipc_types::AppdToCompositor; use crate::Registry; @@ -37,6 +37,10 @@ impl Drop for IpcRelay { /// newline-delimited messages between it and the returned sender (towards /// the component) and the broadcast channel (from the component). #[cfg(unix)] +/// The longest message from a component, its line break included: the +/// runtime refuses longer ones, so a longer line ends the relay. +const MAX_RELAY_FRAME: usize = 64 * 1024 + 2; + pub(crate) fn spawn_ipc_relay( session_id: u64, socket_path: PathBuf, @@ -65,14 +69,26 @@ pub(crate) fn spawn_ipc_relay( let (reader, writer) = tokio::io::split(stream); let mut reader = BufReader::new(reader); let mut writer = BufWriter::new(writer); + // The frame being read lives outside the loop: `read_until` keeps + // what it has read when the other branch wins, so a message from the + // page never splits a message from the component. + let mut frame = Vec::new(); loop { - let mut line = String::new(); + let mut limited = (&mut reader).take((MAX_RELAY_FRAME + 1 - frame.len()) as u64); tokio::select! { - n = reader.read_line(&mut line) => { + n = limited.read_until(b'\n', &mut frame) => { match n { Ok(0) | Err(_) => break, + Ok(_) if !frame.ends_with(b"\n") => { + if frame.len() > MAX_RELAY_FRAME { + tracing::warn!(session_id, "IPC relay: message over the size limit"); + break; + } + } Ok(_) => { - let payload = line.trim_end().to_owned(); + let line = std::mem::take(&mut frame); + let text = String::from_utf8_lossy(&line); + let payload = text.trim_end_matches(['\n', '\r']).to_owned(); let _ = broadcast.send(Response::IpcMessage { session_id, payload }); } } @@ -566,6 +582,48 @@ async fn drain_stderr(stderr: tokio::process::ChildStderr, session_id: u64, proc mod tests { use super::SYSTEMD_SCOPE_ARGS; + fn relay_socket(name: &str) -> std::path::PathBuf { + std::env::temp_dir().join(format!("weft-relay-{name}-{}.sock", std::process::id())) + } + + #[tokio::test] + async fn a_message_from_the_page_does_not_split_one_from_the_component() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let path = relay_socket("split"); + let (broadcast, mut messages) = tokio::sync::broadcast::channel(16); + let (to_component, mut relay) = super::spawn_ipc_relay(7, path.clone(), broadcast).unwrap(); + let mut component = tokio::net::UnixStream::connect(&path).await.unwrap(); + component.write_all(b"{\"half\":").await.unwrap(); + // The relay starts reading the component's message, then the page's + // message wins the select. + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + to_component.send("from the page".to_owned()).await.unwrap(); + let mut received = vec![0; 14]; + component.read_exact(&mut received).await.unwrap(); + assert_eq!(received, b"from the page\n"); + component.write_all(b"\"whole\"}\n").await.unwrap(); + let message = tokio::time::timeout(std::time::Duration::from_secs(5), messages.recv()) + .await + .unwrap() + .unwrap(); + assert!( + matches!(&message, crate::ipc::Response::IpcMessage { session_id: 7, payload } if payload == "{\"half\":\"whole\"}"), + "{message:?}" + ); + + // A line longer than any message ends the relay. + component + .write_all(&vec![b'x'; super::MAX_RELAY_FRAME + 1]) + .await + .unwrap(); + tokio::time::timeout(std::time::Duration::from_secs(5), relay.ended()) + .await + .expect("the relay did not end on an overlong line"); + assert!(messages.try_recv().is_err()); + drop(relay); + assert!(!path.exists()); + } + /// systemd-run checks its options and their combinations before it /// connects to the service manager. Run against an empty runtime /// directory and bus address, it must get as far as the connection From 8c476fdf154e98aab44c9a7c53865d9f683b1a57 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 19:43:20 +0000 Subject: [PATCH 2/2] fix(appd): keep the relay's platform attribute on the function and bound frames exactly The frame limit constant was inserted between spawn_ipc_relay's doc comment and its cfg(unix) attribute, so the attribute applied to the constant instead. A non-Unix build would have had two definitions of the function. The size is now checked before the line ending, so a frame one byte over the limit is refused even when its line break arrives in the same read. A message that is not UTF-8 ends the relay, as it did before, rather than reaching the page with replacement characters. The test now also covers a message at exactly the limit ending in CRLF. --- crates/weft-appd/src/runtime.rs | 44 +++++++++++++++++++++++---------- 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/crates/weft-appd/src/runtime.rs b/crates/weft-appd/src/runtime.rs index 1ce6cf1..286821d 100644 --- a/crates/weft-appd/src/runtime.rs +++ b/crates/weft-appd/src/runtime.rs @@ -33,14 +33,15 @@ impl Drop for IpcRelay { } } +/// The longest message from a component, its line break included: the +/// runtime refuses longer ones, so a longer line ends the relay. +#[cfg(unix)] +const MAX_RELAY_FRAME: usize = 64 * 1024 + 2; + /// Listens on `socket_path` for the session's component and relays /// newline-delimited messages between it and the returned sender (towards /// the component) and the broadcast channel (from the component). #[cfg(unix)] -/// The longest message from a component, its line break included: the -/// runtime refuses longer ones, so a longer line ends the relay. -const MAX_RELAY_FRAME: usize = 64 * 1024 + 2; - pub(crate) fn spawn_ipc_relay( session_id: u64, socket_path: PathBuf, @@ -79,15 +80,18 @@ pub(crate) fn spawn_ipc_relay( n = limited.read_until(b'\n', &mut frame) => { match n { Ok(0) | Err(_) => break, - Ok(_) if !frame.ends_with(b"\n") => { - if frame.len() > MAX_RELAY_FRAME { - tracing::warn!(session_id, "IPC relay: message over the size limit"); - break; - } + Ok(_) if frame.len() > MAX_RELAY_FRAME => { + tracing::warn!(session_id, "IPC relay: message over the size limit"); + break; } + // The rest of the message is still to come. + Ok(_) if !frame.ends_with(b"\n") => {} Ok(_) => { let line = std::mem::take(&mut frame); - let text = String::from_utf8_lossy(&line); + let Ok(text) = String::from_utf8(line) else { + tracing::warn!(session_id, "IPC relay: message is not UTF-8"); + break; + }; let payload = text.trim_end_matches(['\n', '\r']).to_owned(); let _ = broadcast.send(Response::IpcMessage { session_id, payload }); } @@ -611,11 +615,25 @@ mod tests { "{message:?}" ); - // A line longer than any message ends the relay. - component - .write_all(&vec![b'x'; super::MAX_RELAY_FRAME + 1]) + // A message at the limit, ending in a carriage return and line + // feed, arrives whole. + let mut at_limit = vec![b'y'; super::MAX_RELAY_FRAME - 2]; + at_limit.extend_from_slice(b"\r\n"); + component.write_all(&at_limit).await.unwrap(); + let message = tokio::time::timeout(std::time::Duration::from_secs(5), messages.recv()) .await + .unwrap() .unwrap(); + assert!( + matches!(&message, crate::ipc::Response::IpcMessage { payload, .. } if payload.len() == super::MAX_RELAY_FRAME - 2), + "a message at the limit did not arrive whole" + ); + + // A line longer than any message ends the relay, even when its line + // break comes in the same read. + let mut over = vec![b'x'; super::MAX_RELAY_FRAME]; + over.push(b'\n'); + component.write_all(&over).await.unwrap(); tokio::time::timeout(std::time::Duration::from_secs(5), relay.ended()) .await .expect("the relay did not end on an overlong line");