Debian Codegraph @

third_party/rust/neqo-transport/src/qlog.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 // Functions that handle capturing QLOG traces.
8
9 use std::{
10 ops::{Deref as _, RangeInclusive},
11 time::{Duration, Instant},
12 };
13
14 use neqo_common::{hex, qinfo, qlog::NeqoQlog, Decoder, IpTosEcn};
15 use qlog::events::{
16 connectivity::{ConnectionStarted, ConnectionState, ConnectionStateUpdated},
17 quic::{
18 AckedRanges, ErrorSpace, MetricsUpdated, PacketDropped, PacketHeader, PacketLost,
19 PacketReceived, PacketSent, QuicFrame, StreamType, VersionInformation,
20 },
21 EventData, RawInfo,
22 };
23 use smallvec::SmallVec;
24
25 use crate::{
26 connection::State,
27 frame::{CloseError, Frame},
28 packet::{self, metadata::Direction, PacketType, PublicPacket},
29 path::PathRef,
30 recovery::SentPacket,
31 stream_id::StreamType as NeqoStreamType,
32 tparams::{
33 TransportParameterId::{
34 self, AckDelayExponent, ActiveConnectionIdLimit, DisableMigration, InitialMaxData,
35 InitialMaxStreamDataBidiLocal, InitialMaxStreamDataBidiRemote, InitialMaxStreamDataUni,
36 InitialMaxStreamsBidi, InitialMaxStreamsUni, MaxAckDelay, MaxUdpPayloadSize,
37 OriginalDestinationConnectionId, StatelessResetToken,
38 },
39 TransportParametersHandler,
40 },
41 version::{Version, VersionConfig, WireVersion},
42 };
43
44 pub fn connection_tparams_set(qlog: &NeqoQlog, tph: &TransportParametersHandler, now: Instant) {
45 qlog.add_event_data_with_instant(
46 || {
47 let remote = tph.remote();
48 #[expect(clippy::cast_possible_truncation, reason = "These are OK.")]
49 let ev_data =
50 EventData::TransportParametersSet(qlog::events::quic::TransportParametersSet {
51 original_destination_connection_id: remote
52 .get_bytes(OriginalDestinationConnectionId)
53 .map(hex),
54 stateless_reset_token: remote.get_bytes(StatelessResetToken).map(hex),
55 disable_active_migration: remote.get_empty(DisableMigration).then_some(true),
56 max_idle_timeout: Some(remote.get_integer(TransportParameterId::IdleTimeout)),
57 max_udp_payload_size: Some(remote.get_integer(MaxUdpPayloadSize) as u32),
58 ack_delay_exponent: Some(remote.get_integer(AckDelayExponent) as u16),
59 max_ack_delay: Some(remote.get_integer(MaxAckDelay) as u16),
60 active_connection_id_limit: Some(
61 remote.get_integer(ActiveConnectionIdLimit) as u32
62 ),
63 initial_max_data: Some(remote.get_integer(InitialMaxData)),
64 initial_max_stream_data_bidi_local: Some(
65 remote.get_integer(InitialMaxStreamDataBidiLocal),
66 ),
67 initial_max_stream_data_bidi_remote: Some(
68 remote.get_integer(InitialMaxStreamDataBidiRemote),
69 ),
70 initial_max_stream_data_uni: Some(remote.get_integer(InitialMaxStreamDataUni)),
71 initial_max_streams_bidi: Some(remote.get_integer(InitialMaxStreamsBidi)),
72 initial_max_streams_uni: Some(remote.get_integer(InitialMaxStreamsUni)),
73 preferred_address: remote.get_preferred_address().and_then(|(paddr, cid)| {
74 Some(qlog::events::quic::PreferredAddress {
75 ip_v4: paddr.ipv4()?.ip().to_string(),
76 ip_v6: paddr.ipv6()?.ip().to_string(),
77 port_v4: paddr.ipv4()?.port(),
78 port_v6: paddr.ipv6()?.port(),
79 connection_id: cid.connection_id().to_string(),
80 stateless_reset_token: hex(cid.reset_token()),
81 })
82 }),
83 ..Default::default()
84 });
85
86 Some(ev_data)
87 },
88 now,
89 );
90 }
91
92 pub fn server_connection_started(qlog: &NeqoQlog, path: &PathRef, now: Instant) {
93 connection_started(qlog, path, now);
94 }
95
96 pub fn client_connection_started(qlog: &NeqoQlog, path: &PathRef, now: Instant) {
97 connection_started(qlog, path, now);
98 }
99
100 fn connection_started(qlog: &NeqoQlog, path: &PathRef, now: Instant) {
101 qlog.add_event_data_with_instant(
102 || {
103 let p = path.deref().borrow();
104 let ev_data = EventData::ConnectionStarted(ConnectionStarted {
105 ip_version: if p.local_address().ip().is_ipv4() {
106 Some("ipv4".into())
107 } else {
108 Some("ipv6".into())
109 },
110 src_ip: format!("{}", p.local_address().ip()),
111 dst_ip: format!("{}", p.remote_address().ip()),
112 protocol: Some("QUIC".into()),
113 src_port: p.local_address().port().into(),
114 dst_port: p.remote_address().port().into(),
115 src_cid: p.local_cid().map(ToString::to_string),
116 dst_cid: p.remote_cid().map(ToString::to_string),
117 });
118
119 Some(ev_data)
120 },
121 now,
122 );
123 }
124
125 #[expect(clippy::similar_names, reason = "new and now are similar.")]
126 pub fn connection_state_updated(qlog: &NeqoQlog, new: &State, now: Instant) {
127 qlog.add_event_data_with_instant(
128 || {
129 let ev_data = EventData::ConnectionStateUpdated(ConnectionStateUpdated {
130 old: None,
131 new: match new {
132 State::Init | State::WaitInitial => ConnectionState::Attempted,
133 State::WaitVersion | State::Handshaking => ConnectionState::HandshakeStarted,
134 State::Connected => ConnectionState::HandshakeCompleted,
135 State::Confirmed => ConnectionState::HandshakeConfirmed,
136 State::Closing { .. } => ConnectionState::Closing,
137 State::Draining { .. } => ConnectionState::Draining,
138 State::Closed { .. } => ConnectionState::Closed,
139 },
140 });
141
142 Some(ev_data)
143 },
144 now,
145 );
146 }
147
148 pub fn client_version_information_initiated(
149 qlog: &NeqoQlog,
150 version_config: &VersionConfig,
151 now: Instant,
152 ) {
153 qlog.add_event_data_with_instant(
154 || {
155 Some(EventData::VersionInformation(VersionInformation {
156 client_versions: Some(
157 version_config
158 .all()
159 .iter()
160 .map(|v| format!("{:02x}", v.wire_version()))
161 .collect(),
162 ),
163 chosen_version: Some(format!("{:02x}", version_config.initial().wire_version())),
164 ..Default::default()
165 }))
166 },
167 now,
168 );
169 }
170
171 pub fn client_version_information_negotiated(
172 qlog: &NeqoQlog,
173 client: &[Version],
174 server: &[WireVersion],
175 chosen: Version,
176 now: Instant,
177 ) {
178 qlog.add_event_data_with_instant(
179 || {
180 Some(EventData::VersionInformation(VersionInformation {
181 client_versions: Some(
182 client
183 .iter()
184 .map(|v| format!("{:02x}", v.wire_version()))
185 .collect(),
186 ),
187 server_versions: Some(server.iter().map(|v| format!("{v:02x}")).collect()),
188 chosen_version: Some(format!("{:02x}", chosen.wire_version())),
189 }))
190 },
191 now,
192 );
193 }
194
195 pub fn server_version_information_failed(
196 qlog: &NeqoQlog,
197 server: &[Version],
198 client: WireVersion,
199 now: Instant,
200 ) {
201 qlog.add_event_data_with_instant(
202 || {
203 Some(EventData::VersionInformation(VersionInformation {
204 client_versions: Some(vec![format!("{client:02x}")]),
205 server_versions: Some(
206 server
207 .iter()
208 .map(|v| format!("{:02x}", v.wire_version()))
209 .collect(),
210 ),
211 ..Default::default()
212 }))
213 },
214 now,
215 );
216 }
217
218 pub fn packet_io(qlog: &NeqoQlog, meta: packet::MetaData, now: Instant) {
219 qlog.add_event_data_with_instant(
220 || {
221 let mut d = Decoder::from(meta.payload());
222 let raw = RawInfo {
223 length: Some(meta.length() as u64),
224 payload_length: None,
225 data: None,
226 };
227
228 let mut frames = SmallVec::new();
229 while d.remaining() > 0 {
230 if let Ok(f) = Frame::decode(&mut d) {
231 frames.push(QuicFrame::from(f));
232 } else {
233 qinfo!("qlog: invalid frame");
234 break;
235 }
236 }
237
238 match meta.direction() {
239 Direction::Tx => Some(EventData::PacketSent(PacketSent {
240 header: meta.into(),
241 frames: Some(frames),
242 raw: Some(raw),
243 ..Default::default()
244 })),
245 Direction::Rx => Some(EventData::PacketReceived(PacketReceived {
246 header: meta.into(),
247 frames: Some(frames.to_vec()),
248 raw: Some(raw),
249 ..Default::default()
250 })),
251 }
252 },
253 now,
254 );
255 }
256
257 pub fn packet_dropped(qlog: &NeqoQlog, public_packet: &PublicPacket, now: Instant) {
258 qlog.add_event_data_with_instant(
259 || {
260 let header =
261 PacketHeader::with_type(public_packet.packet_type().into(), None, None, None, None);
262 let raw = RawInfo {
263 length: Some(public_packet.len() as u64),
264 ..Default::default()
265 };
266
267 let ev_data = EventData::PacketDropped(PacketDropped {
268 header: Some(header),
269 raw: Some(raw),
270 ..Default::default()
271 });
272
273 Some(ev_data)
274 },
275 now,
276 );
277 }
278
279 pub fn packets_lost(qlog: &NeqoQlog, pkts: &[SentPacket], now: Instant) {
280 qlog.add_event_with_stream(|stream| {
281 for pkt in pkts {
282 let header =
283 PacketHeader::with_type(pkt.packet_type().into(), Some(pkt.pn()), None, None, None);
284
285 let ev_data = EventData::PacketLost(PacketLost {
286 header: Some(header),
287 ..Default::default()
288 });
289
290 stream.add_event_data_with_instant(ev_data, now)?;
291 }
292 Ok(())
293 });
294 }
295
296 #[expect(dead_code, reason = "TODO: Construct all variants.")]
297 pub enum QlogMetric {
298 MinRtt(Duration),
299 SmoothedRtt(Duration),
300 LatestRtt(Duration),
301 RttVariance(Duration),
302 MaxAckDelay(u64),
303 PtoCount(usize),
304 CongestionWindow(usize),
305 BytesInFlight(usize),
306 SsThresh(usize),
307 PacketsInFlight(u64),
308 InRecovery(bool),
309 PacingRate(u64),
310 }
311
312 pub fn metrics_updated(qlog: &NeqoQlog, updated_metrics: &[QlogMetric], now: Instant) {
313 debug_assert!(!updated_metrics.is_empty());
314
315 qlog.add_event_data_with_instant(
316 || {
317 let mut min_rtt: Option<f32> = None;
318 let mut smoothed_rtt: Option<f32> = None;
319 let mut latest_rtt: Option<f32> = None;
320 let mut rtt_variance: Option<f32> = None;
321 let mut pto_count: Option<u16> = None;
322 let mut congestion_window: Option<u64> = None;
323 let mut bytes_in_flight: Option<u64> = None;
324 let mut ssthresh: Option<u64> = None;
325 let mut packets_in_flight: Option<u64> = None;
326 let mut pacing_rate: Option<u64> = None;
327
328 for metric in updated_metrics {
329 match metric {
330 QlogMetric::MinRtt(v) => min_rtt = Some(v.as_secs_f32() * 1000.0),
331 QlogMetric::SmoothedRtt(v) => smoothed_rtt = Some(v.as_secs_f32() * 1000.0),
332 QlogMetric::LatestRtt(v) => latest_rtt = Some(v.as_secs_f32() * 1000.0),
333 QlogMetric::RttVariance(v) => rtt_variance = Some(v.as_secs_f32() * 1000.0),
334 QlogMetric::PtoCount(v) => {
335 pto_count = Some(u16::try_from(*v).expect("fits in u16"));
336 }
337 QlogMetric::CongestionWindow(v) => {
338 congestion_window = Some(u64::try_from(*v).expect("fits in u64"));
339 }
340 QlogMetric::BytesInFlight(v) => {
341 bytes_in_flight = Some(u64::try_from(*v).expect("fits in u64"));
342 }
343 QlogMetric::SsThresh(v) => {
344 ssthresh = Some(u64::try_from(*v).expect("fits in u64"));
345 }
346 QlogMetric::PacketsInFlight(v) => packets_in_flight = Some(*v),
347 QlogMetric::PacingRate(v) => pacing_rate = Some(*v),
348 _ => (),
349 }
350 }
351
352 let ev_data = EventData::MetricsUpdated(MetricsUpdated {
353 min_rtt,
354 smoothed_rtt,
355 latest_rtt,
356 rtt_variance,
357 pto_count,
358 congestion_window,
359 bytes_in_flight,
360 ssthresh,
361 packets_in_flight,
362 pacing_rate,
363 });
364
365 Some(ev_data)
366 },
367 now,
368 );
369 }
370
371 // Helper functions
372
373 #[expect(clippy::too_many_lines, reason = "Yeah, but it's a nice match.")]
374 #[expect(
375 clippy::cast_precision_loss,
376 clippy::cast_possible_truncation,
377 reason = "We need to truncate here."
378 )]
379 impl From<Frame<'_>> for QuicFrame {
380 fn from(frame: Frame) -> Self {
381 match frame {
382 Frame::Padding(len) => Self::Padding {
383 length: None,
384 payload_length: u32::from(len),
385 },
386 Frame::Ping => Self::Ping {
387 length: None,
388 payload_length: None,
389 },
390 Frame::Ack {
391 largest_acknowledged,
392 ack_delay,
393 first_ack_range,
394 ack_ranges,
395 ecn_count,
396 } => {
397 let ranges =
398 Frame::decode_ack_frame(largest_acknowledged, first_ack_range, &ack_ranges)
399 .ok();
400
401 let acked_ranges = ranges.map(|all| {
402 AckedRanges::Double(
403 all.into_iter()
404 .map(RangeInclusive::into_inner)
405 .collect::<Vec<_>>(),
406 )
407 });
408
409 Self::Ack {
410 ack_delay: Some(ack_delay as f32 / 1000.0),
411 acked_ranges,
412 ect1: ecn_count.map(|c| c[IpTosEcn::Ect1]),
413 ect0: ecn_count.map(|c| c[IpTosEcn::Ect0]),
414 ce: ecn_count.map(|c| c[IpTosEcn::Ce]),
415 length: None,
416 payload_length: None,
417 }
418 }
419 Frame::ResetStream {
420 stream_id,
421 application_error_code,
422 final_size,
423 } => Self::ResetStream {
424 stream_id: stream_id.as_u64(),
425 error_code: application_error_code,
426 final_size,
427 length: None,
428 payload_length: None,
429 },
430 Frame::StopSending {
431 stream_id,
432 application_error_code,
433 } => Self::StopSending {
434 stream_id: stream_id.as_u64(),
435 error_code: application_error_code,
436 length: None,
437 payload_length: None,
438 },
439 Frame::Crypto { offset, data } => Self::Crypto {
440 offset,
441 length: data.len() as u64,
442 },
443 Frame::NewToken { token } => Self::NewToken {
444 token: qlog::Token {
445 ty: Some(qlog::TokenType::Retry),
446 details: None,
447 raw: Some(RawInfo {
448 data: Some(hex(token)),
449 length: Some(token.len() as u64),
450 payload_length: None,
451 }),
452 },
453 },
454 Frame::Stream {
455 fin,
456 stream_id,
457 offset,
458 data,
459 ..
460 } => Self::Stream {
461 stream_id: stream_id.as_u64(),
462 offset,
463 length: data.len() as u64,
464 fin: Some(fin),
465 raw: None,
466 },
467 Frame::MaxData { maximum_data } => Self::MaxData {
468 maximum: maximum_data,
469 },
470 Frame::MaxStreamData {
471 stream_id,
472 maximum_stream_data,
473 } => Self::MaxStreamData {
474 stream_id: stream_id.as_u64(),
475 maximum: maximum_stream_data,
476 },
477 Frame::MaxStreams {
478 stream_type,
479 maximum_streams,
480 } => Self::MaxStreams {
481 stream_type: match stream_type {
482 NeqoStreamType::BiDi => StreamType::Bidirectional,
483 NeqoStreamType::UniDi => StreamType::Unidirectional,
484 },
485 maximum: maximum_streams,
486 },
487 Frame::DataBlocked { data_limit } => Self::DataBlocked { limit: data_limit },
488 Frame::StreamDataBlocked {
489 stream_id,
490 stream_data_limit,
491 } => Self::StreamDataBlocked {
492 stream_id: stream_id.as_u64(),
493 limit: stream_data_limit,
494 },
495 Frame::StreamsBlocked {
496 stream_type,
497 stream_limit,
498 } => Self::StreamsBlocked {
499 stream_type: match stream_type {
500 NeqoStreamType::BiDi => StreamType::Bidirectional,
501 NeqoStreamType::UniDi => StreamType::Unidirectional,
502 },
503 limit: stream_limit,
504 },
505 Frame::NewConnectionId {
506 sequence_number,
507 retire_prior,
508 connection_id,
509 stateless_reset_token,
510 } => Self::NewConnectionId {
511 sequence_number: sequence_number as u32,
512 retire_prior_to: retire_prior as u32,
513 connection_id_length: Some(connection_id.len() as u8),
514 connection_id: hex(connection_id),
515 stateless_reset_token: Some(hex(stateless_reset_token)),
516 },
517 Frame::RetireConnectionId { sequence_number } => Self::RetireConnectionId {
518 sequence_number: sequence_number as u32,
519 },
520 Frame::PathChallenge { data } => Self::PathChallenge {
521 data: Some(hex(data)),
522 },
523 Frame::PathResponse { data } => Self::PathResponse {
524 data: Some(hex(data)),
525 },
526 Frame::ConnectionClose {
527 error_code,
528 frame_type,
529 reason_phrase,
530 } => Self::ConnectionClose {
531 error_space: match error_code {
532 CloseError::Transport(_) => Some(ErrorSpace::TransportError),
533 CloseError::Application(_) => Some(ErrorSpace::ApplicationError),
534 },
535 error_code: Some(error_code.code()),
536 error_code_value: Some(0),
537 reason: Some(reason_phrase),
538 trigger_frame_type: Some(frame_type),
539 },
540 Frame::HandshakeDone => Self::HandshakeDone,
541 Frame::AckFrequency { .. } => Self::Unknown {
542 frame_type_value: None,
543 raw_frame_type: frame.get_type().into(),
544 raw: None,
545 },
546 Frame::Datagram { data, .. } => Self::Datagram {
547 length: data.len() as u64,
548 raw: None,
549 },
550 }
551 }
552 }
553
554 impl From<PacketType> for qlog::events::quic::PacketType {
555 fn from(value: PacketType) -> Self {
556 match value {
557 PacketType::Initial => Self::Initial,
558 PacketType::Handshake => Self::Handshake,
559 PacketType::ZeroRtt => Self::ZeroRtt,
560 PacketType::Short => Self::OneRtt,
561 PacketType::Retry => Self::Retry,
562 PacketType::VersionNegotiation => Self::VersionNegotiation,
563 PacketType::OtherVersion => Self::Unknown,
564 }
565 }
566 }