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
21 changes: 21 additions & 0 deletions neqo-transport/src/connection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1067,6 +1067,27 @@ impl Connection {
qlog::packets_lost(&mut self.qlog, &lost, now);
}

// Declare the connection broken if too many consecutive PTOs have gone
// unacknowledged, i.e. the path is a black hole. This closes the connection
// sooner than, and with a distinct reason from, the idle timeout.
//
// We only do this once connected, i.e. after the handshake completes. A
// black hole during the handshake is the job of happy eyeballs, which races
// multiple connection attempts and does not need us to give up on any single
// one early. Requiring `connected()` also guarantees we have an RTT sample,
// so the PTO backoff we are counting is based on a real estimate.
if let Some(max_pto) = self.conn_params.get_max_pto()
&& self.state.connected()
&& self.loss_recovery.pto_count() >= max_pto.get()
{
qinfo!("[{self}] {max_pto} consecutive PTOs, declaring connection broken");
self.set_state(
State::Closed(CloseReason::Transport(Error::TooManyPtos)),
now,
);
return;
}

if self.release_resumption_token_timer.is_some() {
self.create_resumption_token(now);
}
Expand Down
27 changes: 26 additions & 1 deletion neqo-transport/src/connection/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::{cmp::max, time::Duration};
use std::{cmp::max, num::NonZeroUsize, time::Duration};

pub use crate::recovery::FAST_PTO_SCALE;
use crate::{
Expand Down Expand Up @@ -133,6 +133,11 @@ pub struct ConnectionParameters {
ack_ratio: u8,
/// The duration of the idle timeout for the connection.
idle_timeout: Duration,
/// Maximum number of consecutive PTOs (probe timeouts) without an
/// acknowledgement before the connection is declared broken and closed
/// locally. `None` (the default) disables the check, leaving the idle timeout
/// as the only backstop.
max_pto: Option<NonZeroUsize>,
preferred_address: PreferredAddressConfig,
datagram_size: u64,
outgoing_datagram_queue: usize,
Expand Down Expand Up @@ -177,6 +182,7 @@ impl Default for ConnectionParameters {
max_streams_uni: LOCAL_STREAM_LIMIT_UNI,
ack_ratio: Self::DEFAULT_ACK_RATIO,
idle_timeout: Self::DEFAULT_IDLE_TIMEOUT,
max_pto: None,
preferred_address: PreferredAddressConfig::Default,
datagram_size: MAX_DATAGRAM_FRAME_SIZE,
outgoing_datagram_queue: MAX_QUEUED_DATAGRAMS_DEFAULT,
Expand Down Expand Up @@ -365,6 +371,25 @@ impl ConnectionParameters {
self.idle_timeout
}

/// Close the connection once `count` consecutive PTOs have fired without any
/// acknowledgement, treating the path as a black hole. `None` disables the
/// check, leaving the idle timeout as the only backstop.
///
/// A value of `7` matches mvfst's `maxNumPTOs` and Google QUICHE's default
/// "5-RTO" blackhole detection (2 tail-loss probes + 5 RTOs). msquic instead
/// uses a fixed-time `DisconnectTimeoutMs` of 16s, which, being independent of
/// the RTT, only lines up with a PTO count on one specific RTT.
#[must_use]
pub const fn max_pto(mut self, count: Option<NonZeroUsize>) -> Self {
self.max_pto = count;
self
}

#[must_use]
pub const fn get_max_pto(&self) -> Option<NonZeroUsize> {
self.max_pto
}

#[must_use]
pub const fn get_initial_rtt(&self) -> Duration {
self.initial_rtt
Expand Down
125 changes: 122 additions & 3 deletions neqo-transport/src/connection/tests/idle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,22 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::time::{Duration, Instant};
use std::{
num::NonZeroUsize,
time::{Duration, Instant},
};

use neqo_common::{Encoder, qtrace, qwarn};
use test_fixture::now;

use super::{
super::{Connection, ConnectionParameters, IdleTimeout, Output, State},
AT_LEAST_PTO, DEFAULT_STREAM_DATA, connect, connect_force_idle, connect_rtt_idle,
AT_LEAST_PTO, DEFAULT_RTT, DEFAULT_STREAM_DATA, connect, connect_force_idle, connect_rtt_idle,
connect_with_rtt, default_client, default_server, maybe_authenticate, new_client, new_server,
send_and_receive, send_something,
};
use crate::{
packet, recovery,
CloseReason, Error, packet, recovery,
stats::FrameStats,
stream_id::{StreamId, StreamType},
tparams::{TransportParameter, TransportParameterId},
Expand Down Expand Up @@ -801,3 +804,119 @@ fn keep_alive_with_unresponsive_server() {
// Connection should be closed due to idle timeout.
assert!(matches!(client.state(), State::Closed(_)));
}

/// A connection whose packets are all dropped (a black hole) is declared broken
/// after `max_pto` consecutive PTOs, and crucially does so earlier than the idle
/// timeout would have.
#[test]
fn declare_broken_after_max_pto() {
const MAX_PTO: usize = 7;
// For this test to prove anything, the whole PTO backoff ladder must fit inside
// the idle timeout; otherwise "closed before the idle timeout" is vacuously true.
assert!(DEFAULT_RTT * (1_u32 << (MAX_PTO - 1)) * 3 < default_timeout());

let mut client =
new_client(ConnectionParameters::default().max_pto(NonZeroUsize::new(MAX_PTO)));
let mut server = default_server();
let start = connect_rtt_idle(&mut client, &mut server, DEFAULT_RTT);

// The client sends data that never reaches the server: a black hole.
let mut now = start;
drop(send_something(&mut client, now));

// Advance through PTOs, dropping every probe the client emits.
for _ in 0..=MAX_PTO {
let cb = loop {
match client.process_output(now) {
// Drop the PTO probe(s) without advancing time.
Output::Datagram(_) => {}
Output::Callback(t) => break t,
Output::None => break Duration::ZERO,
}
};
now += cb;
}

assert!(
matches!(
client.state(),
State::Closed(CloseReason::Transport(Error::TooManyPtos))
),
"expected TooManyPtos, got {:?}",
client.state()
);
assert_eq!(client.loss_recovery.pto_count(), MAX_PTO);
// The whole point: we gave up well before the idle timeout would have fired.
assert!(
now - start < default_timeout(),
"closed after {:?}, which is not earlier than the {:?} idle timeout",
now - start,
default_timeout()
);
Comment thread
mxinden marked this conversation as resolved.
Resolved
}
Comment thread
mxinden marked this conversation as resolved.
Resolved

/// A received acknowledgement resets the consecutive-PTO counter, so a transient
/// loss burst followed by recovery does not accumulate toward `max_pto`: a second,
/// independent black hole counts fresh from zero rather than adding to the first
/// (the property a fixed timer lacks). That a full fresh ladder then closes the
/// connection is covered by `declare_broken_after_max_pto`.
#[test]
fn max_pto_counter_resets_on_ack() {
const MAX_PTO: usize = 7;
let mut client =
new_client(ConnectionParameters::default().max_pto(NonZeroUsize::new(MAX_PTO)));
let mut server = default_server();
let mut now = connect_rtt_idle(&mut client, &mut server, DEFAULT_RTT);

// Black-hole a flight and let a couple of PTOs fire, staying below MAX_PTO.
drop(send_something(&mut client, now));
while client.loss_recovery.pto_count() < 2 {
let cb = loop {
match client.process_output(now) {
// Drop the PTO probe(s) without advancing time.
Output::Datagram(_) => {}
Output::Callback(t) => break t,
Output::None => break Duration::ZERO,
}
};
now += cb;
}
assert!(!matches!(client.state(), State::Closed(_)));

// A fresh client packet reaches the server, whose ACK reaches the client and
// resets the counter. Flush any ACK the server delays behind its ack timer.
let d = send_something(&mut client, now);
let mut out = server.process(Some(d), now);
let ack = loop {
match out {
Output::Datagram(d) => break Some(d),
Output::Callback(t) => {
now += t;
out = server.process_output(now);
}
Output::None => break None,
}
};
drop(client.process(ack, now));

// The received ACK reset the counter, so the connection survives.
assert_eq!(client.loss_recovery.pto_count(), 0);
assert!(!matches!(client.state(), State::Closed(_)));

// A second, independent black hole counts fresh from zero: after two more
// PTOs the count is 2, not 2 + the earlier 2, so separate episodes do not
// accumulate toward the threshold and the connection stays open.
drop(send_something(&mut client, now));
while client.loss_recovery.pto_count() < 2 {
let cb = loop {
match client.process_output(now) {
Output::Datagram(_) => {}
Output::Callback(t) => break t,
Output::None => break Duration::ZERO,
}
};
now += cb;
}
assert_eq!(client.loss_recovery.pto_count(), 2);
assert!(!matches!(client.state(), State::Closed(_)));
}
8 changes: 7 additions & 1 deletion neqo-transport/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,11 @@ pub enum Error {
Peer(TransportError),
#[error("stateless reset")]
StatelessReset,
/// Too many consecutive PTOs went unacknowledged, so the path is assumed to be
/// a black hole. A distinct variant so the application can tell this apart, but
/// reported on the wire as `NO_VIABLE_PATH` (there is no dedicated code).
#[error("too many PTOs without acknowledgement; connection assumed broken")]
TooManyPtos,
#[error("too much data")]
TooMuchData,
#[error("unexpected message")]
Expand Down Expand Up @@ -213,7 +218,7 @@ impl Error {
Self::InvalidToken => 11,
Self::KeysExhausted => ERROR_AEAD_LIMIT_REACHED,
Self::Application => ERROR_APPLICATION_CLOSE,
Self::NoAvailablePath => 16,
Self::NoAvailablePath | Self::TooManyPtos => 16,
Self::CryptoBufferExceeded => ERROR_CRYPTO_BUFFER_EXCEEDED,
Self::CryptoAlert(a) => 0x100 + u64::from(*a),
// As we have a special error code for ECH fallbacks, we lose the alert.
Expand Down Expand Up @@ -294,6 +299,7 @@ mod tests {
(Error::EchRetry(vec![]), 0x179),
(Error::VersionNegotiation, 0x53f8),
(Error::Internal, 1),
(Error::TooManyPtos, 16),
] {
assert_eq!(err.code(), code);
}
Expand Down
6 changes: 6 additions & 0 deletions neqo-transport/src/recovery/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -823,6 +823,12 @@ impl Loss {
)
}

/// The number of consecutive PTOs that have fired without being acknowledged.
/// The value is reset to `0` whenever an acknowledgement is received.
pub(crate) fn pto_count(&self) -> usize {
self.pto_state.as_ref().map_or(0, PtoState::count)
}

// Calculate PTO time for the given space.
fn pto_time(&self, rtt: &RttEstimate, pn_space: PacketNumberSpace) -> Option<Instant> {
self.spaces
Expand Down
Loading