Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion quest/a0/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ The Required list is ordered by priority. Independent children may proceed concu
- [Quinn final Session drop](/quest/a0/quinn-session-drop.md) - close the connection and release the capsule reader
- [Quiche lifecycle](/quest/a0/quiche/README.md) - deterministic harness and retirement handling
- [QMux socket teardown](/quest/a0/qmux-socket-teardown.md) - release retained stats descriptors
- [WebSocket handshake timeout](/quest/a0/qmux-ws-handshake-timeout.md) - close sessions whose peer never sends parameters
- [QMux initial stream-count bound](/quest/a0/qmux-max-streams-param.md) - refuse initial_max_streams parameters above 2^60
- [QMux stream-state checks](/quest/a0/qmux-stream-state.md) - refuse MAX_STREAM_DATA and STOP_SENDING for unopened local streams
- [Node Server.close()](/quest/a0/node-server-close.md) - close completes while an accept is pending
Expand Down
11 changes: 0 additions & 11 deletions quest/a0/qmux-ws-handshake-timeout.md

This file was deleted.

7 changes: 7 additions & 0 deletions rs/qmux/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,13 @@ builder or the handshake. The default grants a peer 100 concurrent streams in
each direction; raise `max_streams_bidi` and `max_streams_uni` if your
application holds more streams open at once.

`Config::handshake_timeout` bounds the wait for peer transport parameters after
the transport connects, including WebSocket sessions. A silent peer closes the
session with `Error::HandshakeTimeout`; WebSocket builders return before this
exchange, so observe the error through session operations or `Session::closed`.
The default is 10 seconds, zero disables the deadline, and the legacy
`webtransport` format exchanges no parameters and is exempt.

To run QMux over something the built-in modules don't cover, wrap any
`AsyncRead + AsyncWrite` byte stream in `transport::Stream`, or implement
`transport::Transport` yourself, then pass it to `Session::connect` /
Expand Down
12 changes: 6 additions & 6 deletions rs/qmux/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,12 @@ pub struct Config {
/// 16382 bytes.
pub max_datagram_frame_size: u64,

/// How long [`Session::connect`](crate::Session::connect) /
/// [`accept`](crate::Session::accept) waits for the peer's transport
/// parameters before giving up. Bounds the handshake so a peer that completes
/// the transport connection but never sends its parameters can't hang
/// establishment forever. Default: 10s; a zero duration disables the timeout
/// (wait indefinitely).
/// How long a session waits for the peer's transport parameters before
/// closing with [`Error::HandshakeTimeout`](crate::Error::HandshakeTimeout).
/// Starts when the session is created, after the transport handshake,
/// including for WebSocket sessions that return before parameters arrive.
/// The legacy `webtransport` format exchanges no parameters and is exempt.
/// Default: 10s; a zero duration disables the timeout (wait indefinitely).
pub handshake_timeout: Duration,

/// How often to send a `QX_PING` request purely to measure round-trip time,
Expand Down
5 changes: 3 additions & 2 deletions rs/qmux/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,11 @@ impl Error {
/// The wire error code to send on a CONNECTION_CLOSE (0x1c) when *we* tear the
/// session down because of this error, or `None` when the peer should not (or
/// cannot) be told: a graceful close, a close the peer already sent us, an idle
/// timeout (silent, like QUIC), or a dead transport. Every protocol/transport
/// violation we detect maps to 1002, matching the JS QMux polyfill.
/// timeout (silent, like QUIC), or a dead transport. Handshake expiry uses 0;
/// protocol/transport violations map to 1002, matching the JS QMux polyfill.
pub(crate) fn transport_close(&self) -> Option<u32> {
match self {
Error::HandshakeTimeout => Some(0),
Error::ProtocolViolation
| Error::FrameEncoding
| Error::TransportParameter
Expand Down
153 changes: 127 additions & 26 deletions rs/qmux/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2107,32 +2107,12 @@ impl Session {
return Ok(());
}

let wait = async { established.wait_for(|&done| done).await.is_ok() };
let timeout = self.config.handshake_timeout;
// A zero timeout disables the bound (wait indefinitely).
let outcome = if timeout.is_zero() {
Some(wait.await)
if established.wait_for(|&done| done).await.is_ok() {
Ok(())
} else {
tokio::time::timeout(timeout, wait).await.ok()
};

match outcome {
// Established.
Some(true) => Ok(()),
// The backend task ended before establishing — surface the close reason.
Some(false) => Err(self.close_reason().await),
// Timed out waiting for the peer's parameters: abort the half-open
// handshake, notifying the peer, and fail rather than hang.
// If the session closed first, report that reason instead.
None => {
// Abnormal: a CONNECTION_CLOSE (0x1c) so the peer's session rejects
// rather than seeing a graceful close.
let frame = ConnectionClose {
code: VarInt::from(0u32),
reason: "handshake timeout".to_string(),
};
Err(self.close_with(frame.into(), Error::HandshakeTimeout))
}
// The backend enforces the handshake deadline and records its error
// before dropping the establishment sender.
Err(self.close_reason().await)
}
}

Expand Down Expand Up @@ -2323,8 +2303,33 @@ impl Session {
tokio::spawn(timer.run());
}

let handshake_deadline = if version.is_qmux() && !config.handshake_timeout.is_zero() {
// A deadline beyond the clock's range cannot expire.
base.checked_add(config.handshake_timeout)
} else {
None
};
let mut established = established_rx.clone();
tokio::spawn(async move {
let err = backend.run().await.err().unwrap_or(Error::Closed);
let handshake = async {
if let Some(deadline) = handshake_deadline {
if tokio::time::timeout_at(deadline, established.wait_for(|&done| done))
.await
.is_err()
{
return Error::HandshakeTimeout;
}
}
std::future::pending().await
};
// The deadline starts at construction and remains pollable even if
// the reader is parked on application backpressure. Already-readable
// peer input wins over an expired deadline.
let err = tokio::select! {
biased;
result = backend.run() => result.err().unwrap_or(Error::Closed),
err = handshake => err,
};
// If we tore down because of a protocol/transport violation *we*
// detected, tell the peer with a CONNECTION_CLOSE (0x1c) so their
// session rejects too, rather than seeing a bare drop. Enqueue on the
Expand Down Expand Up @@ -3676,6 +3681,48 @@ mod recv_open_tests {
scripted_session_with_config(Config::new(Version::QMux01))
}

#[tokio::test(start_paused = true)]
async fn queued_handshake_frames_win_after_delayed_poll() {
for version in [Version::QMux00, Version::QMux01, Version::QMux02] {
for peer_closed in [false, true] {
let mut config = Config::new(version);
config.handshake_timeout = Duration::from_secs(1);
config.max_idle_timeout = 0;
config.rtt_interval = Duration::ZERO;
let params = config.to_transport_params();
let (session, incoming) = scripted_session_with_config(config);
incoming
.send(Frame::TransportParameters(params).encode(version).unwrap())
.unwrap();
if peer_closed {
let frame = Frame::ConnectionClose(crate::proto::ConnectionClose {
code: VarInt::from_u32(42),
reason: "peer closed".into(),
});
incoming.send(frame.encode(version).unwrap()).unwrap();
}
// No spawned session task is polled until the clock has passed
// its deadline, with the peer's frame already readable.
tokio::time::advance(Duration::from_secs(2)).await;
if peer_closed {
let error = tokio::time::timeout(Duration::from_secs(1), session.closed())
.await
.unwrap();
assert!(
matches!(error, Error::ConnectionReset { code, .. } if code.into_inner() == 42)
);
} else {
session.established().await.unwrap();
assert!(
tokio::time::timeout(Duration::from_secs(1), session.closed())
.await
.is_err()
);
}
}
}
}

/// Encode a STREAM frame on a server-initiated uni stream (peer-initiated and
/// receivable, since we're the client).
fn uni_stream(index: u64, data: &'static [u8], fin: bool) -> Bytes {
Expand Down Expand Up @@ -5007,6 +5054,60 @@ mod teardown_tests {
}
}

#[tokio::test(start_paused = true)]
async fn handshake_timeout_releases_wedged_writer_with_retained_session() {
use web_transport_trait::Session as _;

for version in [Version::QMux00, Version::QMux01, Version::QMux02] {
let (entered_tx, mut entered_rx) = mpsc::unbounded_channel();
let (dropped_tx, mut dropped_rx) = mpsc::unbounded_channel();
let mut config = Config::new(version);
config.handshake_timeout = Duration::from_secs(1);
let session = Session::new(
WedgedTransport {
entered_send: entered_tx,
dropped: dropped_tx,
},
false,
config,
);
entered_rx.recv().await.unwrap();
let error = tokio::time::timeout(Duration::from_secs(2), session.closed())
.await
.unwrap();
assert!(matches!(error, Error::HandshakeTimeout), "{error:?}");
tokio::time::timeout(Duration::from_secs(1), dropped_rx.recv())
.await
.unwrap()
.unwrap();
}
}

#[tokio::test(start_paused = true)]
async fn async_entrypoints_report_shared_handshake_timeout() {
for is_server in [false, true] {
let (entered_send, _entered_rx) = mpsc::unbounded_channel();
let (dropped, _dropped_rx) = mpsc::unbounded_channel();
let transport = WedgedTransport {
entered_send,
dropped,
};
let mut config = Config::new(Version::QMux02);
config.handshake_timeout = Duration::from_secs(1);
let establish = async {
if is_server {
Session::accept(transport, config).await
} else {
Session::connect(transport, config).await
}
};
let result = tokio::time::timeout(Duration::from_secs(2), establish)
.await
.expect("establishment stayed pending");
assert!(matches!(result, Err(Error::HandshakeTimeout)));
}
}

/// A writer parked inside `send()` on a wedged transport must still observe
/// teardown when the last `Session` clone drops, cancelling the in-flight
/// write instead of staying alive until the transport eventually errors.
Expand Down
Loading
Loading