From d2fcffbd7604ce46d675fc644fb466712661fd80 Mon Sep 17 00:00:00 2001 From: eric Date: Wed, 9 Sep 2026 21:19:29 +0800 Subject: [PATCH] feat(ws): let a websocket transport signal the end of a request A client that has finished sending says so by closing its write side and goes on reading, and plenty of protocols end a request that way and no other. Over a websocket transport that signal went nowhere: `poll_shutdown` returned without sending anything, so the far end learned the request had ended only when the connection itself went away -- when the downlink grace expires, ten seconds later, by which time the reply has nowhere to go. The comment above it said as much. A Close frame is the obvious candidate and the wrong one. RFC 6455 makes it the start of closing the whole connection, and tungstenite enforces that at both ends: once a Close has been received the connection will not carry another data frame, so the reply still on its way back is lost. Measured, not assumed -- the server read the origin's answer and then failed to forward it. An empty binary frame says the same thing and costs nothing. It is an ordinary data frame carrying no bytes, so a peer that does not understand it hands nothing to its application and carries on, which is exactly today's behaviour. This transport's read side has always turned a frame with no bytes into an end of stream, so between two leaf nodes it is precisely the missing signal. A write of no bytes now returns early rather than sending one by accident. Still behind WS_HALF_CLOSE, off by default, for the peer that would rather error than ignore it. Booleans now also accept 1/yes/on: an option that is silently ignored, as WS_HALF_CLOSE=1 was, is worse than one that is missing. --- leaf/src/option/mod.rs | 44 ++++++++++++- leaf/src/proxy/ws/stream.rs | 124 +++++++++++++++++++++++++++++++++--- 2 files changed, 157 insertions(+), 11 deletions(-) diff --git a/leaf/src/option/mod.rs b/leaf/src/option/mod.rs index 59aa333..256cf65 100644 --- a/leaf/src/option/mod.rs +++ b/leaf/src/option/mod.rs @@ -19,6 +19,22 @@ where default } +/// Reads a boolean option, accepting the spellings people actually use. +/// +/// `bool::from_str` takes `true` and `false` and nothing else, so a `FOO=1` +/// reads as the default and says nothing about it. An option that is silently +/// ignored is worse than one that is missing. +pub fn get_env_bool(key: &str, default: bool) -> bool { + match env::var(key) { + Ok(value) => match value.trim().to_ascii_lowercase().as_str() { + "1" | "true" | "yes" | "on" => true, + "0" | "false" | "no" | "off" => false, + _ => default, + }, + Err(_) => default, + } +} + fn get_env_var_or_else(key: &str, f: F) -> T where T: FromStr, @@ -170,7 +186,33 @@ lazy_static! { /// So turn this on where a device cannot afford the sockets, not as a /// matter of course. pub static ref TCP_INBOUND_ABORT_ON_CLOSE: bool = { - get_env_var_or("TCP_INBOUND_ABORT_ON_CLOSE", false) + get_env_bool("TCP_INBOUND_ABORT_ON_CLOSE", false) + }; + + /// Whether a websocket transport tells the far end when its side of the + /// conversation has ended. + /// + /// A client that has finished sending says so by closing its write side + /// and going on reading, and plenty of protocols end a request that way + /// and no other. WebSocket has no half-close: the nearest thing is a Close + /// frame, which RFC 6455 defines as the start of closing the whole + /// connection. leaf's own websocket transport reads a Close frame as the + /// end of the peer's side alone and keeps carrying the other direction, so + /// between two leaf nodes a Close frame is exactly the missing signal. + /// + /// Against anything else it may not be. A strict peer answers a Close + /// frame with its own and closes, which would cut off a reply that is + /// still coming -- and that reply arrives today, because leaf sends + /// nothing and lets the session run on until its downlink grace expires. + /// Turning a working session into a broken one is worse than a request + /// whose end never arrives, so this is off unless a deployment knows what + /// is at the other end. + /// + /// With it off, a request that ends in a half-close is never signalled + /// over a websocket transport at all: the far end learns only when the + /// connection itself goes away. + pub static ref WS_HALF_CLOSE: bool = { + get_env_bool("WS_HALF_CLOSE", false) }; /// Buffer size for uplink and downlink connections, in KB. diff --git a/leaf/src/proxy/ws/stream.rs b/leaf/src/proxy/ws/stream.rs index 4fc5ae6..8642d14 100644 --- a/leaf/src/proxy/ws/stream.rs +++ b/leaf/src/proxy/ws/stream.rs @@ -17,6 +17,10 @@ use tungstenite::Message; pub struct WebSocketToStream { buf: BytesMut, inner: S, + /// Whether the frame that stands in for a half-close has been handed to + /// the sink yet. `poll_shutdown` can be polled more than once, and the + /// frame goes out exactly once. + end_signalled: bool, } impl WebSocketToStream { @@ -24,6 +28,7 @@ impl WebSocketToStream { WebSocketToStream { buf: BytesMut::new(), inner: stream, + end_signalled: false, } } } @@ -54,7 +59,7 @@ impl> + Sink + Unpin> AsyncRe Err(broken_pipe()), |item| { item.map_or(Err(broken_pipe()), |msg| match msg { - Message::Binary(data) => { + Message::Binary(data) if !data.is_empty() => { let to_read = min(buf.remaining(), data.len()); buf.put_slice(&data[..to_read]); if data.len() > to_read { @@ -63,7 +68,10 @@ impl> + Sink + Unpin> AsyncRe trace!("poll_read {} bytes", buf.filled().len()); Ok(()) } - Message::Close(_) => Ok(()), + // Either shape of "nothing more from this side": a Close + // frame, or the empty frame `poll_shutdown` sends. Both + // fill no bytes, which is what an end of stream is. + Message::Binary(_) | Message::Close(_) => Ok(()), _ => Err(invalid_frame()), }) }, @@ -78,6 +86,11 @@ impl + Unpin> AsyncWrite for WebSocketToStream { buf: &[u8], ) -> Poll> { trace!("poll_write {} bytes", buf.len()); + if buf.is_empty() { + // An empty frame is how `poll_shutdown` says this side has + // finished. Nobody should be able to say it by accident. + return Poll::Ready(Ok(0)); + } ready!(Pin::new(&mut self.inner) .poll_ready(cx) .map_err(|_| broken_pipe()))?; @@ -98,13 +111,104 @@ impl + Unpin> AsyncWrite for WebSocketToStream { .map_err(|_| broken_pipe()) } - fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context) -> Poll> { - // We're using WebSocket as a transport, a shutdown on the write side - // means a half close of the stream, it seems that WebSocket lacks this - // half closing capability, sending a close frame means closing the - // whole socket. In order to support half close connections, we do not - // call poll_close() and instead wait for downlink timeout to cancel - // the underlying connection. - Poll::Ready(Ok(())) + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + // WebSocket is a transport here, and a shutdown of the write side is a + // half close: this side has finished sending and goes on reading. + // WebSocket has no such thing of its own. + // + // A Close frame is the obvious candidate and the wrong one. RFC 6455 + // makes it the start of closing the whole connection, and tungstenite + // enforces that on both ends: once a Close has been received, the + // connection will not carry another data frame, so the reply still on + // its way back is lost. That is worse than saying nothing. + // + // An empty binary frame says the same thing and costs nothing. It is + // an ordinary data frame carrying no bytes, so a peer that does not + // understand it delivers nothing to its application and carries on -- + // exactly today's behaviour. The read side above has always turned a + // frame with no bytes into an end of stream, so between two leaf nodes + // this is precisely the signal that was missing. + // + // Still behind an option, because a peer that treats an empty frame as + // an error rather than as nothing would end a session that works + // today. `poll_close` is not called either way: closing the sink would + // end the direction that is still carrying the reply. + if !*crate::option::WS_HALF_CLOSE { + return Poll::Ready(Ok(())); + } + if !self.end_signalled { + ready!(Pin::new(&mut self.inner) + .poll_ready(cx) + .map_err(|_| broken_pipe()))?; + Pin::new(&mut self.inner) + .start_send(Message::Binary(Vec::new())) + .map_err(|_| broken_pipe())?; + self.end_signalled = true; + } + Pin::new(&mut self.inner) + .poll_flush(cx) + .map_err(|_| broken_pipe()) + } +} + +#[cfg(test)] +mod tests { + use futures::channel::mpsc; + use tokio::io::AsyncWriteExt; + + use super::*; + + fn runtime() -> tokio::runtime::Runtime { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + } + + /// A shutdown of the write side emits a Close frame, or nothing at all, + /// according to the option -- and never closes the sink, which would end + /// the direction still carrying the reply. + #[test] + fn shutdown_signals_the_end_of_this_side_only_when_asked_to() { + runtime().block_on(async { + let (sink, mut frames) = mpsc::channel::(4); + let mut stream = WebSocketToStream::new(sink); + + stream.write_all(b"a request").await.unwrap(); + stream.shutdown().await.unwrap(); + + // Nothing here is awaited: whatever the shutdown had to say has + // been said by the time it returns, and awaiting what is not + // coming would hang rather than fail. + assert!( + matches!(frames.try_recv(), Ok(Message::Binary(ref data)) if data == b"a request"), + "the request itself should arrive as one binary frame" + ); + let closing = frames.try_recv(); + if *crate::option::WS_HALF_CLOSE { + assert!( + matches!(closing, Ok(Message::Binary(ref data)) if data.is_empty()), + "a half close should be signalled with an empty frame, got {:?}", + closing + ); + } else { + // Nothing sent, and the channel still open: the sink was not + // closed either, so the direction carrying the reply survives. + assert!( + closing.is_err(), + "nothing should be sent and the sink should stay open, got {:?}", + closing + ); + } + }); + } + + #[test] + fn half_close_is_off_unless_asked_for() { + if std::env::var("WS_HALF_CLOSE").is_ok() { + // The environment chose; the case above covers both ways. + return; + } + assert!(!*crate::option::WS_HALF_CLOSE); } }