Skip to content
Open
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
36 changes: 31 additions & 5 deletions neqo-transport/src/connection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,10 @@ pub struct Connection {
/// when they are either just reordered or we haven't been able to install keys yet.
/// In particular, this occurs when asynchronous certificate validation happens.
saved_datagrams: SavedDatagrams,
/// Whether a client received a Handshake or 1-RTT packet for one of its
/// connection IDs before the server's Initial, e.g. because that Initial
/// was lost. See [`ConnectionParameters::single_handshake_flight`].
server_packet_before_initial: bool,
/// Some packets were received, but not tracked.
received_untracked: bool,

Expand Down Expand Up @@ -458,6 +462,7 @@ impl Connection {
remote_initial_source_cid: None,
original_destination_cid: None,
saved_datagrams: SavedDatagrams::default(),
server_packet_before_initial: false,
received_untracked: false,
crypto,
acks: AckTracker::default(),
Expand Down Expand Up @@ -1091,12 +1096,30 @@ impl Connection {
let res = self.crypto.states_mut().check_key_update(now);
self.absorb_error(now, res);

if let Some(path) = self.paths.primary() {
let lost = self
.loss_recovery
.timeout(&path, now, self.crypto.has_handshake_keys());
let pto_fired = self.paths.primary().is_some_and(|path| {
let (lost, pto_fired) =
self.loss_recovery
.timeout(&path, now, self.crypto.has_handshake_keys());
self.handle_lost_packets(&lost);
qlog::packets_lost(&mut self.qlog, &lost, now);
pto_fired
});

// With a single handshake flight, give up when the first PTO fires
// without any response from the server, before any probe is sent.
if pto_fired
&& self.conn_params.single_handshake_flight_enabled()
&& self.role == Role::Client
&& self.state == State::WaitInitial
&& !matches!(self.address_validation, AddressValidationInfo::Retry { .. })
&& !self.server_packet_before_initial

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like the length of this check. I'd recommend a new state for this: SingleFlightSent, which would encapsulate a lot of these checks. There is no case I'm aware of where the server gets to interrupt that flight with something that would disable the feature, so this is safe.

Then, receipt of any(*) packet from the server would flip the client into a new state and you wouldn't need to check so many things here.

{
debug!("[{self}] no response to the first handshake flight, closing");
self.set_state(
State::Closed(CloseReason::Transport(Error::NoHandshakeResponse)),
now,
);
return;
}

// Declare the connection broken if too many consecutive PTOs have gone
Expand Down Expand Up @@ -1516,7 +1539,9 @@ impl Connection {
let conn_params = self
.conn_params
.clone()
.versions(version, self.conn_params.get_versions().all().to_vec());
.versions(version, self.conn_params.get_versions().all().to_vec())
// The server responded, so it speaks QUIC: no reason to give up early.
.single_handshake_flight(false);
let mut c = Self::new_client(
self.crypto.server_name().ok_or(Error::VersionNegotiation)?,
self.crypto.protocols(),
Expand Down Expand Up @@ -1643,6 +1668,7 @@ impl Connection {
&& self.cid_manager.is_valid(packet.dcid())
&& !self.saved_datagrams.is_either_full()
=> {
self.server_packet_before_initial = true;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is where I think a new state saves you. Receiving a packet in that state (even an unvalidated one) flips the state back to the normal path.

self.crypto.resend_unacked_early();
self.resend_0rtt(now);
}
Expand Down
26 changes: 26 additions & 0 deletions neqo-transport/src/connection/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,9 @@ pub struct ConnectionParameters {
/// locally. `None` (the default) disables the check, leaving the idle timeout
/// as the only backstop.
max_pto: Option<NonZeroUsize>,
/// Whether a client sends its first handshake flight only once. See
/// [`ConnectionParameters::single_handshake_flight`].
single_handshake_flight: bool,
preferred_address: PreferredAddressConfig,
datagram_size: u64,
initial_rtt: Duration,
Expand Down Expand Up @@ -197,6 +200,7 @@ impl Default for ConnectionParameters {
ack_ratio: Self::DEFAULT_ACK_RATIO,
idle_timeout: Self::DEFAULT_IDLE_TIMEOUT,
max_pto: None,
single_handshake_flight: false,
preferred_address: PreferredAddressConfig::Default,
datagram_size: MAX_DATAGRAM_FRAME_SIZE,
initial_rtt: DEFAULT_INITIAL_RTT,
Expand Down Expand Up @@ -380,6 +384,28 @@ impl ConnectionParameters {
self.max_pto
}

/// Send the client's first handshake flight only once. If the first PTO fires
/// before the server has responded in any way (Initial, Handshake, 1-RTT,
/// Retry or Version Negotiation packet), close the connection with
/// [`Error::NoHandshakeResponse`] instead of retransmitting.
///
/// Use this when the client does not know whether the server supports QUIC,
/// e.g. when there is no Alt-Svc and no HTTPS DNS record. If the server does
/// not respond, it most likely does not support QUIC, and retransmitting
/// would only waste resources.
///
/// [`Error::NoHandshakeResponse`]: crate::Error::NoHandshakeResponse
#[must_use]
pub const fn single_handshake_flight(mut self, single_handshake_flight: bool) -> Self {
self.single_handshake_flight = single_handshake_flight;
self
}

#[must_use]
pub const fn single_handshake_flight_enabled(&self) -> bool {
self.single_handshake_flight
}

#[must_use]
pub const fn get_initial_rtt(&self) -> Duration {
self.initial_rtt
Expand Down
96 changes: 96 additions & 0 deletions neqo-transport/src/connection/tests/handshake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2688,3 +2688,99 @@ fn client_omits_transport_parameters_0rtt() {
assert_eq!(server.stats().frame_rx.stream, 0);
assert_error(&server, &CloseReason::Transport(Error::CryptoAlert(109)));
}

/// With `single_handshake_flight`, a client whose first flight goes unanswered closes at
/// the first PTO without sending any probe.
#[test]
fn single_handshake_flight_no_response() {
let mut client = new_client(ConnectionParameters::default().single_handshake_flight(true));
let mut now = now();

assert!(client.process_output(now).dgram().is_some());
assert!(client.process_output(now).dgram().is_some());

// The pacing timer, then the PTO.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are you expecting pacing, when nothing follows that?

now += client.process_output(now).callback();
now += client.process_output(now).callback();
assert!(!client.state().closed());

assert_eq!(client.process_output(now), Output::None);
assert!(matches!(
client.state(),
State::Closed(CloseReason::Transport(Error::NoHandshakeResponse))
));
}

/// With `single_handshake_flight`, a server response disables the early close, so the
/// client retransmits as usual when later packets are lost.
#[test]
fn single_handshake_flight_server_responds() {
let mut client = new_client(
ConnectionParameters::default()
.single_handshake_flight(true)
.mlkem(false),
);
let mut server = default_server();
let mut now = now();

let c1 = client.process_output(now).dgram();
let s1 = server.process(c1, now).dgram();
assert!(s1.is_some());
client.process_input(s1.unwrap(), now);
assert!(!matches!(
client.state(),
State::WaitInitial | State::Closed(_)
));

// Drop whatever the client sends next and let the PTO fire.
let sent = loop {
match client.process_output(now) {
Output::Datagram(_) => {}
Output::Callback(t) => {
now += t;
break client.stats().packets_tx;
}
Output::None => panic!("expected a PTO timer"),
}
};
assert!(client.process_output(now).dgram().is_some());
assert!(client.stats().packets_tx > sent);
assert!(!matches!(client.state(), State::Closed(_)));
}

/// With `single_handshake_flight`, a server Handshake packet that arrives before
/// the server's Initial, e.g. because that Initial was lost, counts as a response:
/// the client keeps the connection open and retransmits as usual.
#[test]
fn single_handshake_flight_initial_lost() {
let mut client = new_client(
ConnectionParameters::default()
.single_handshake_flight(true)
.mlkem(false),
);
let mut server = default_server();
let mut now = now();

let c1 = client.process_output(now).dgram();
let s1 = server.process(c1, now).dgram().unwrap();
let (_s_initial, s_hs) = split_datagram(&s1);
client.process_input(s_hs.unwrap(), now);
assert_eq!(*client.state(), State::WaitInitial);

// The client resends its Initial right away.
assert!(client.process_output(now).dgram().is_some());

// The pacing timer, then the PTO, which sends a probe.
now += client.process_output(now).callback();
now += client.process_output(now).callback();
assert!(client.process_output(now).dgram().is_some());
assert!(!client.state().closed());
}

/// `single_handshake_flight` does not prevent a normal handshake.
#[test]
fn single_handshake_flight_connects() {
let mut client = new_client(ConnectionParameters::default().single_handshake_flight(true));
let mut server = default_server();
connect(&mut client, &mut server);
}
8 changes: 7 additions & 1 deletion neqo-transport/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,11 @@ pub enum Error {
KeyUpdateBlocked,
#[error("no available path")]
NoAvailablePath,
/// The server did not respond to the client's first handshake flight before
/// the first PTO, and [`ConnectionParameters::single_handshake_flight`] is
/// enabled. The client closes the connection without sending anything.
#[error("no response to the first handshake flight")]
NoHandshakeResponse,
#[error("no more data")]
NoMoreData,
#[error("not available")]
Expand Down Expand Up @@ -229,7 +234,7 @@ impl Error {
Self::InvalidToken => 11,
Self::KeysExhausted => ERROR_AEAD_LIMIT_REACHED,
Self::Application => ERROR_APPLICATION_CLOSE,
Self::NoAvailablePath | Self::TooManyPtos => 16,
Self::NoAvailablePath | Self::TooManyPtos | Self::NoHandshakeResponse => 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 @@ -311,6 +316,7 @@ mod tests {
(Error::VersionNegotiation, 17),
(Error::Internal, 1),
(Error::TooManyPtos, 16),
(Error::NoHandshakeResponse, 16),
] {
assert_eq!(err.code(), code);
}
Expand Down
20 changes: 13 additions & 7 deletions neqo-transport/src/recovery/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -930,16 +930,18 @@ impl Loss {
/// When it has, mark packets as "lost" for the purposes of having frames
/// regenerated in subsequent packets. The packets aren't truly lost, so
/// we have to clone the `sent::Packet` instance.
///
/// Returns whether the PTO fired.
fn maybe_fire_pto(
&mut self,
primary_path: &PathRef,
now: Instant,
lost: &mut Vec<sent::Packet>,
has_handshake_keys: bool,
) {
) -> bool {
// As in `next_timeout`, which does not arm the timer then (RFC 9002, Section 6.2.2.1).
if !primary_path.borrow().pto_possible() {
return;
return false;
}
let mut pto_space = None;
// The spaces in which we will allow probing.
Expand Down Expand Up @@ -969,7 +971,7 @@ impl Loss {
// This has to happen outside the loop. Increasing the PTO count here causes the
// pto_time to increase which might cause PTO for later packet number spaces to not fire.
let Some(pn_space) = pto_space else {
return;
return false;
};

// Collect packets for retransmission.
Expand All @@ -996,14 +998,17 @@ impl Loss {
if pn_space == PacketNumberSpace::Initial {
self.maybe_prime_handshake_pto(now, has_handshake_keys);
}
true
}

/// Process the loss detection and PTO timers. Returns the packets to treat
/// as lost, and whether the PTO fired.
pub fn timeout(
&mut self,
primary_path: &PathRef,
now: Instant,
has_handshake_keys: bool,
) -> Vec<sent::Packet> {
) -> (Vec<sent::Packet>, bool) {
trace!("[{self}] timeout {now:?}");
if let Some(timer_type) = self
.pending_timer_type
Expand Down Expand Up @@ -1037,8 +1042,9 @@ impl Loss {
}
self.count_lost(&lost_packets);

self.maybe_fire_pto(primary_path, now, &mut lost_packets, has_handshake_keys);
lost_packets
let pto_fired =
self.maybe_fire_pto(primary_path, now, &mut lost_packets, has_handshake_keys);
(lost_packets, pto_fired)
}

/// Check how packets should be sent, based on whether there is a PTO,
Expand Down Expand Up @@ -1153,7 +1159,7 @@ mod tests {
}

pub fn timeout(&mut self, now: Instant) -> Vec<sent::Packet> {
self.lr.timeout(&self.path, now, true)
self.lr.timeout(&self.path, now, true).0
}

pub fn note_timeout_type(&mut self, now: Instant) {
Expand Down