1#![allow(unused_variables)]
12
13#[cfg(not(feature = "qlog"))]
14use std::marker::PhantomData;
15#[cfg(feature = "qlog")]
16use std::sync::{Arc, Mutex};
17use std::{
18 net::{IpAddr, SocketAddr},
19 time::Duration,
20};
21
22#[cfg(feature = "qlog")]
23use qlog::{
24 CommonFields, HexSlice, TokenType, VantagePoint,
25 events::{
26 ApplicationError, ConnectionClosedFrameError, Event, EventData, RawInfo, TupleEndpointInfo,
27 quic::{
28 self, AckRange, AddressDiscoveryRole, ConnectionStarted, ErrorSpace, PacketHeader,
29 PacketLost, PacketLostTrigger, PacketReceived, PacketSent, PacketType,
30 ParametersRestored, ParametersSet, PreferredAddress, QlogTimerType, QuicFrame,
31 StreamType, TimerEventType, TimerType, TimerUpdated, TransportInitiator, TupleAssigned,
32 },
33 },
34 streamer::QlogStreamer,
35};
36#[cfg(feature = "qlog")]
37use tracing::warn;
38
39use crate::{
40 Connection, ConnectionId, FourTuple, Frame, Instant, PathId,
41 connection::{EncryptionLevel, PathData, SentPacket, SpaceKind, timer::Timer},
42 frame::EncodableFrame,
43 packet::Header,
44 transport_parameters::TransportParameters,
45};
46#[cfg(feature = "qlog")]
47use crate::{
48 QlogConfig, Side, TransportErrorCode,
49 connection::timer::{ConnTimer, PathTimer},
50 frame::{self, DataBlocked, StreamDataBlocked, StreamsBlocked},
51};
52
53#[cfg(feature = "qlog")]
55#[derive(Clone)]
56pub(crate) struct QlogStream(Arc<Mutex<QlogStreamer>>);
57
58#[cfg(feature = "qlog")]
59impl QlogStream {
60 pub(crate) fn new(
61 config: QlogConfig,
62 initial_dst_cid: ConnectionId,
63 side: Side,
64 now: Instant,
65 ) -> Result<Self, qlog::Error> {
66 let vantage_point = VantagePoint {
67 name: None,
68 ty: match side {
69 Side::Client => qlog::VantagePointType::Client,
70 Side::Server => qlog::VantagePointType::Server,
71 },
72 flow: None,
73 };
74
75 let common_fields = CommonFields {
76 group_id: Some(initial_dst_cid.to_string()),
77 ..Default::default()
78 };
79
80 let trace = qlog::TraceSeq::new(
81 config.title.clone(),
82 config.description.clone(),
83 Some(common_fields),
84 Some(vantage_point),
85 vec![],
86 );
87
88 let start_time = config.start_time.unwrap_or(now);
89
90 let mut streamer = QlogStreamer::new(
91 config.title,
92 config.description,
93 start_time,
94 trace,
95 qlog::events::EventImportance::Extra,
96 qlog::streamer::EventTimePrecision::MicroSeconds,
97 config.writer,
98 );
99
100 streamer.start_log()?;
101 Ok(Self(Arc::new(Mutex::new(streamer))))
102 }
103
104 fn emit_event(&self, event: EventData, now: Instant) {
105 self.emit_event_with_tuple_id(event, now, None);
106 }
107
108 fn emit_event_with_tuple_id(
109 &self,
110 event: EventData,
111 now: Instant,
112 network_path: Option<String>,
113 ) {
114 let mut event = Event::with_time(0.0, event);
116 event.tuple = network_path;
117 let mut qlog_streamer = self.0.lock().unwrap();
118 if let Err(e) = qlog_streamer.add_event_with_instant(event, now) {
119 warn!("could not emit qlog event: {e}");
120 }
121 }
122}
123
124#[derive(Clone, Default)]
126pub(crate) struct QlogSink {
127 #[cfg(feature = "qlog")]
128 stream: Option<QlogStream>,
129}
130
131impl QlogSink {
132 #[cfg(feature = "qlog")]
133 pub(crate) fn new(
134 config: QlogConfig,
135 initial_dst_cid: ConnectionId,
136 side: Side,
137 now: Instant,
138 ) -> Self {
139 let stream = QlogStream::new(config, initial_dst_cid, side, now)
140 .inspect_err(|err| warn!("failed to initialize qlog streamer: {err}"))
141 .ok();
142 Self { stream }
143 }
144
145 pub(crate) fn emit_connection_started(
146 &self,
147 now: Instant,
148 local_cid: ConnectionId,
149 remote_cid: ConnectionId,
150 remote: SocketAddr,
151 local_ip: Option<IpAddr>,
152 transport_params: &TransportParameters,
153 ) {
154 #[cfg(feature = "qlog")]
155 {
156 let Some(stream) = self.stream.as_ref() else {
157 return;
158 };
159 stream.emit_event(
160 EventData::QuicConnectionStarted(ConnectionStarted {
161 local: tuple_endpoint_info(local_ip, None, Some(local_cid)),
162 remote: tuple_endpoint_info(
163 Some(remote.ip()),
164 Some(remote.port()),
165 Some(remote_cid),
166 ),
167 }),
168 now,
169 );
170
171 let params = transport_params.to_qlog(TransportInitiator::Local);
172 let event = EventData::QuicParametersSet(Box::new(params));
173 stream.emit_event(event, now);
174 }
175 }
176
177 pub(super) fn emit_recovery_metrics(&self, path_id: PathId, path: &mut PathData, now: Instant) {
178 #[cfg(feature = "qlog")]
179 {
180 let Some(stream) = self.stream.as_ref() else {
181 return;
182 };
183
184 let Some(metrics) = path.qlog_recovery_metrics(path_id) else {
185 return;
186 };
187
188 stream.emit_event(EventData::QuicMetricsUpdated(metrics), now);
189 }
190 }
191
192 pub(super) fn emit_packet_lost(
193 &self,
194 pn: u64,
195 info: &SentPacket,
196 loss_delay: Duration,
197 space: SpaceKind,
198 now: Instant,
199 ) {
200 #[cfg(feature = "qlog")]
201 {
202 let Some(stream) = self.stream.as_ref() else {
203 return;
204 };
205
206 let event = PacketLost {
207 header: Some(PacketHeader {
208 packet_number: Some(pn),
209 packet_type: packet_type(space, false),
210 length: Some(info.size),
211 ..Default::default()
212 }),
213 frames: None,
214 trigger: Some(
215 match info.time_sent.saturating_duration_since(now) >= loss_delay {
216 true => PacketLostTrigger::TimeThreshold,
217 false => PacketLostTrigger::ReorderingThreshold,
218 },
219 ),
220 is_mtu_probe_packet: None,
221 };
222
223 stream.emit_event(EventData::QuicPacketLost(event), now);
224 }
225 }
226
227 pub(super) fn emit_peer_transport_params_restored(&self, conn: &Connection, now: Instant) {
228 #[cfg(feature = "qlog")]
229 {
230 let Some(stream) = self.stream.as_ref() else {
231 return;
232 };
233 let params = conn.peer_params.to_qlog_restored();
234 let event = EventData::QuicParametersRestored(params);
235 stream.emit_event(event, now);
236 }
237 }
238
239 pub(super) fn emit_peer_transport_params_received(&self, conn: &Connection, now: Instant) {
240 #[cfg(feature = "qlog")]
241 {
242 let Some(stream) = self.stream.as_ref() else {
243 return;
244 };
245 let params = conn.peer_params.to_qlog(TransportInitiator::Remote);
246 let event = EventData::QuicParametersSet(Box::new(params));
247 stream.emit_event(event, now);
248 }
249 }
250
251 pub(super) fn emit_tuple_assigned(&self, path_id: PathId, tuple: FourTuple, now: Instant) {
252 #[cfg(feature = "qlog")]
253 {
254 let Some(stream) = self.stream.as_ref() else {
255 return;
256 };
257 let tuple_id = fmt_tuple_id(path_id.as_u32() as u64);
258 let event = TupleAssigned {
259 tuple_id,
260 tuple_local: tuple
261 .local_ip
262 .map(|local_ip| tuple_endpoint_info(Some(local_ip), None, None)),
263 tuple_remote: Some(tuple_endpoint_info(
264 Some(tuple.remote.ip()),
265 Some(tuple.remote.port()),
266 None,
267 )),
268 };
269
270 stream.emit_event(EventData::QuicTupleAssigned(event), now);
271 }
272 }
273
274 pub(super) fn emit_packet_sent(&self, packet: QlogSentPacket, now: Instant) {
275 #[cfg(feature = "qlog")]
276 {
277 let Some(stream) = self.stream.as_ref() else {
278 return;
279 };
280 let tuple_id = packet.inner.header.path_id.map(fmt_tuple_id);
281 stream.emit_event_with_tuple_id(EventData::QuicPacketSent(packet.inner), now, tuple_id);
282 }
283 }
284
285 pub(super) fn emit_packet_received(&self, packet: QlogRecvPacket, now: Instant) {
286 #[cfg(feature = "qlog")]
287 {
288 let Some(stream) = self.stream.as_ref() else {
289 return;
290 };
291 let mut packet = packet;
292 packet.emit_padding();
293 let tuple_id = packet.inner.header.path_id.map(fmt_tuple_id);
294 let event = packet.inner;
295 stream.emit_event_with_tuple_id(EventData::QuicPacketReceived(event), now, tuple_id);
296 }
297 }
298
299 #[cfg(feature = "qlog")]
304 fn emit_timer(&self, timer: Timer, op: TimerOp, now: Instant) {
305 let Some(stream) = self.stream.as_ref() else {
306 return;
307 };
308
309 let timer_type: Option<TimerType> = match timer {
310 Timer::Conn(conn_timer) => match conn_timer {
311 ConnTimer::Idle => Some(QlogTimerType::IdleTimeout.into()),
312 ConnTimer::Close => Some(TimerType::custom("close")),
313 ConnTimer::KeyDiscard => Some(TimerType::custom("key_discard")),
314 ConnTimer::KeepAlive => Some(TimerType::custom("keep_alive")),
315 ConnTimer::PushNewCid => Some(TimerType::custom("push_new_cid")),
316 ConnTimer::NoAvailablePath => Some(TimerType::custom("no_available_path")),
317 ConnTimer::NatTraversalProbeRetry => {
318 Some(TimerType::custom("nat_traversal_probe_retry"))
319 }
320 },
321 Timer::PerPath(_, path_timer) => match path_timer {
322 PathTimer::LossDetection => Some(QlogTimerType::LossTimeout.into()),
323 PathTimer::PathIdle => Some(TimerType::custom("path_idle")),
324 PathTimer::PathValidationFailed => Some(QlogTimerType::PathValidation.into()),
325 PathTimer::PathChallengeLost => Some(TimerType::custom("path_challenge_lost")),
326 PathTimer::PathKeepAlive => Some(TimerType::custom("path_keep_alive")),
327 PathTimer::Pacing => Some(TimerType::custom("pacing")),
328 PathTimer::MaxAckDelay => Some(QlogTimerType::Ack.into()),
329 PathTimer::PathDrained => Some(TimerType::custom("discard_path")),
330 },
331 };
332
333 let Some(timer_type) = timer_type else {
334 return;
335 };
336
337 let delta = match op {
338 TimerOp::Set(instant) => instant
339 .checked_duration_since(now)
340 .map(|dur| dur.as_secs_f32() * 1000.),
341 _ => None,
342 };
343 let path_id = match timer {
344 Timer::Conn(_) => None,
345 Timer::PerPath(path_id, _) => Some(path_id.as_u32() as u64),
346 };
347
348 let event_type = match op {
349 TimerOp::Set(_) => TimerEventType::Set,
350 TimerOp::Expire => TimerEventType::Expired,
351 TimerOp::Cancelled => TimerEventType::Cancelled,
352 };
353
354 let event = TimerUpdated {
355 path_id,
356 timer_type: Some(timer_type),
357 timer_id: None,
358 packet_number_space: None,
359 event_type,
360 delta,
361 };
362 stream.emit_event(EventData::QuicTimerUpdated(event), now);
363 }
364
365 pub(super) fn with_time(&self, now: Instant) -> QlogSinkWithTime<'_> {
371 #[cfg(feature = "qlog")]
372 let s = QlogSinkWithTime { sink: self, now };
373 #[cfg(not(feature = "qlog"))]
374 let s = QlogSinkWithTime {
375 _phantom: PhantomData,
376 };
377 s
378 }
379}
380
381#[derive(Clone)]
383pub(super) struct QlogSinkWithTime<'a> {
384 #[cfg(feature = "qlog")]
385 sink: &'a QlogSink,
386 #[cfg(feature = "qlog")]
387 now: Instant,
388 #[cfg(not(feature = "qlog"))]
389 _phantom: PhantomData<&'a ()>,
390}
391
392impl<'a> QlogSinkWithTime<'a> {
393 pub(super) fn emit_timer_stop(&self, timer: Timer) {
394 #[cfg(feature = "qlog")]
395 self.sink.emit_timer(timer, TimerOp::Cancelled, self.now)
396 }
397
398 pub(super) fn emit_timer_set(&self, timer: Timer, expire_at: Instant) {
399 #[cfg(feature = "qlog")]
400 self.sink
401 .emit_timer(timer, TimerOp::Set(expire_at), self.now)
402 }
403
404 pub(super) fn emit_timer_expire(&self, timer: Timer) {
405 #[cfg(feature = "qlog")]
406 self.sink.emit_timer(timer, TimerOp::Expire, self.now)
407 }
408}
409
410#[cfg(feature = "qlog")]
411enum TimerOp {
412 Set(Instant),
413 Expire,
414 Cancelled,
415}
416
417#[derive(Default)]
419pub(crate) struct QlogSentPacket {
420 #[cfg(feature = "qlog")]
421 inner: PacketSent,
422}
423
424impl QlogSentPacket {
425 pub(crate) fn header(
427 &mut self,
428 header: &Header,
429 pn: Option<u64>,
430 encryption_level: EncryptionLevel,
431 path_id: PathId,
432 ) {
433 #[cfg(feature = "qlog")]
434 {
435 self.inner.header.scid = header.src_cid().map(stringify_cid);
436 self.inner.header.dcid = Some(stringify_cid(header.dst_cid()));
437 self.inner.header.packet_number = pn;
438 self.inner.header.packet_type = encryption_level.into();
439 self.inner.header.path_id = Some(path_id.as_u32() as u64);
440 }
441 }
442
443 pub(crate) fn frame_padding(&mut self, count: usize) {
447 #[cfg(feature = "qlog")]
448 self.frame_raw(QuicFrame::Padding {
449 raw: Some(Box::new(RawInfo {
450 length: Some(count as u64),
451 payload_length: Some(count as u64),
452 data: None,
453 })),
454 });
455 }
456
457 #[cfg(feature = "qlog")]
462 fn frame_raw(&mut self, frame: QuicFrame) {
463 self.inner.frames.get_or_insert_default().push(frame);
464 }
465
466 pub(super) fn finalize(&mut self, len: usize) {
468 #[cfg(feature = "qlog")]
469 {
470 self.inner.header.length = Some(len as u16);
471 }
472 }
473
474 pub(crate) fn record<'a>(&mut self, frame: &EncodableFrame<'a>) {
475 #[cfg(feature = "qlog")]
476 self.frame_raw(frame.to_qlog());
477 }
478}
479
480pub(crate) struct QlogRecvPacket {
482 #[cfg(feature = "qlog")]
483 inner: PacketReceived,
484 #[cfg(feature = "qlog")]
485 padding: usize,
486}
487
488impl QlogRecvPacket {
489 pub(crate) fn new(len: usize) -> Self {
493 #[cfg(not(feature = "qlog"))]
494 let this = Self {};
495
496 #[cfg(feature = "qlog")]
497 let this = {
498 let mut this = Self {
499 inner: Default::default(),
500 padding: 0,
501 };
502 this.inner.header.length = Some(len as u16);
503 this
504 };
505
506 this
507 }
508
509 pub(crate) fn header(&mut self, header: &Header, pn: Option<u64>, path_id: PathId) {
511 #[cfg(feature = "qlog")]
512 {
513 let is_0rtt = !header.is_1rtt();
514 self.inner.header.scid = header.src_cid().map(stringify_cid);
515 self.inner.header.dcid = Some(stringify_cid(header.dst_cid()));
516 self.inner.header.packet_number = pn;
517 self.inner.header.packet_type = packet_type(header.space(), is_0rtt);
518 self.inner.header.path_id = Some(path_id.as_u32() as u64);
519 }
520 }
521
522 pub(crate) fn frame(&mut self, frame: &Frame) {
524 #[cfg(feature = "qlog")]
525 {
526 if matches!(frame, Frame::Padding) {
527 self.padding += 1;
528 } else {
529 self.emit_padding();
530 self.inner
531 .frames
532 .get_or_insert_default()
533 .push(frame.to_qlog())
534 }
535 }
536 }
537
538 #[cfg(feature = "qlog")]
539 fn emit_padding(&mut self) {
540 if self.padding > 0 {
541 self.inner
542 .frames
543 .get_or_insert_default()
544 .push(QuicFrame::Padding {
545 raw: Some(Box::new(RawInfo {
546 length: Some(self.padding as u64),
547 payload_length: Some(self.padding as u64),
548 data: None,
549 })),
550 });
551 self.padding = 0;
552 }
553 }
554}
555
556#[cfg(feature = "qlog")]
558pub(crate) trait ToQlog {
559 fn to_qlog(&self) -> QuicFrame;
560}
561
562#[cfg(feature = "qlog")]
563impl<'a> ToQlog for frame::AckEncoder<'a> {
564 fn to_qlog(&self) -> QuicFrame {
565 QuicFrame::Ack {
566 ack_delay: Some(self.delay as f32),
567 acked_ranges: Some(
568 self.ranges
569 .iter()
570 .map(|range| AckRange::new(range.start, range.end))
571 .collect(),
572 ),
573 ect1: self.ecn.map(|e| e.ect1),
574 ect0: self.ecn.map(|e| e.ect0),
575 ce: self.ecn.map(|e| e.ce),
576 raw: None,
577 }
578 }
579}
580
581#[cfg(feature = "qlog")]
582impl ToQlog for frame::AckFrequency {
583 fn to_qlog(&self) -> QuicFrame {
584 QuicFrame::AckFrequency {
585 sequence_number: self.sequence.into_inner(),
586 ack_eliciting_threshold: self.ack_eliciting_threshold.into_inner(),
587 requested_max_ack_delay: self.request_max_ack_delay.into_inner(),
588 reordering_threshold: self.reordering_threshold.into_inner(),
589 raw: None,
590 }
591 }
592}
593
594#[cfg(feature = "qlog")]
595impl ToQlog for frame::AddAddress {
596 fn to_qlog(&self) -> QuicFrame {
597 QuicFrame::AddAddress {
598 sequence_number: self.seq_no.into_inner(),
599 ip_v4: match self.ip {
600 IpAddr::V4(ipv4_addr) => Some(ipv4_addr.to_string()),
601 IpAddr::V6(ipv6_addr) => None,
602 },
603 ip_v6: match self.ip {
604 IpAddr::V4(ipv4_addr) => None,
605 IpAddr::V6(ipv6_addr) => Some(ipv6_addr.to_string()),
606 },
607 port: self.port,
608 }
609 }
610}
611
612#[cfg(feature = "qlog")]
613impl ToQlog for frame::CloseEncoder<'_> {
614 fn to_qlog(&self) -> QuicFrame {
615 self.close.to_qlog()
616 }
617}
618
619#[cfg(feature = "qlog")]
620impl ToQlog for frame::Close {
621 fn to_qlog(&self) -> QuicFrame {
622 match self {
623 Self::Connection(f) => {
624 let (error, error_code) = transport_error(f.error_code);
625 let error = error.map(|transport_error| {
626 ConnectionClosedFrameError::TransportError(transport_error)
627 });
628 QuicFrame::ConnectionClose {
629 error_space: Some(ErrorSpace::Transport),
630 error,
631 error_code,
632 reason: String::from_utf8(f.reason.to_vec()).ok(),
633 reason_bytes: None,
634 trigger_frame_type: None,
635 }
636 }
637 Self::Application(f) => QuicFrame::ConnectionClose {
638 error_space: Some(ErrorSpace::Application),
639 error: None,
640 error_code: Some(f.error_code.into_inner()),
641 reason: String::from_utf8(f.reason.to_vec()).ok(),
642 reason_bytes: None,
643 trigger_frame_type: None,
644 },
645 }
646 }
647}
648
649#[cfg(feature = "qlog")]
650impl ToQlog for frame::Crypto {
651 fn to_qlog(&self) -> QuicFrame {
652 QuicFrame::Crypto {
653 offset: self.offset,
654 raw: Some(Box::new(RawInfo {
655 length: Some(self.data.len() as u64),
656 ..Default::default()
657 })),
658 }
659 }
660}
661
662#[cfg(feature = "qlog")]
663impl ToQlog for frame::Datagram {
664 fn to_qlog(&self) -> QuicFrame {
665 QuicFrame::Datagram {
666 raw: Some(Box::new(RawInfo {
667 length: Some(self.data.len() as u64),
668 ..Default::default()
669 })),
670 }
671 }
672}
673
674#[cfg(feature = "qlog")]
675impl ToQlog for frame::HandshakeDone {
676 fn to_qlog(&self) -> QuicFrame {
677 QuicFrame::HandshakeDone { raw: None }
678 }
679}
680
681#[cfg(feature = "qlog")]
682impl ToQlog for frame::ImmediateAck {
683 fn to_qlog(&self) -> QuicFrame {
684 QuicFrame::ImmediateAck { raw: None }
685 }
686}
687
688#[cfg(feature = "qlog")]
689impl ToQlog for frame::MaxData {
690 fn to_qlog(&self) -> QuicFrame {
691 QuicFrame::MaxData {
692 maximum: self.0.into(),
693 raw: None,
694 }
695 }
696}
697
698#[cfg(feature = "qlog")]
699impl ToQlog for frame::MaxPathId {
700 fn to_qlog(&self) -> QuicFrame {
701 QuicFrame::MaxPathId {
702 maximum_path_id: self.0.as_u32().into(),
703 raw: None,
704 }
705 }
706}
707
708#[cfg(feature = "qlog")]
709impl ToQlog for frame::MaxStreamData {
710 fn to_qlog(&self) -> QuicFrame {
711 QuicFrame::MaxStreamData {
712 stream_id: self.id.into(),
713 maximum: self.offset,
714 raw: None,
715 }
716 }
717}
718
719#[cfg(feature = "qlog")]
720impl ToQlog for frame::MaxStreams {
721 fn to_qlog(&self) -> QuicFrame {
722 QuicFrame::MaxStreams {
723 maximum: self.count,
724 stream_type: self.dir.into(),
725 raw: None,
726 }
727 }
728}
729
730#[cfg(feature = "qlog")]
731impl ToQlog for StreamsBlocked {
732 fn to_qlog(&self) -> QuicFrame {
733 QuicFrame::StreamsBlocked {
734 stream_type: self.dir.into(),
735 limit: self.limit,
736 raw: None,
737 }
738 }
739}
740
741#[cfg(feature = "qlog")]
742impl ToQlog for frame::NewConnectionId {
743 fn to_qlog(&self) -> QuicFrame {
744 match self.path_id {
745 None => QuicFrame::NewConnectionId {
746 sequence_number: self.sequence,
747 retire_prior_to: self.retire_prior_to,
748 connection_id_length: Some(self.id.len() as u8),
749 connection_id: self.id.to_string(),
750 stateless_reset_token: Some(self.reset_token.to_string()),
751 raw: None,
752 },
753 Some(path_id) => QuicFrame::PathNewConnectionId {
754 path_id: path_id.0 as u64,
755 sequence_number: self.sequence,
756 retire_prior_to: self.retire_prior_to,
757 connection_id_length: Some(self.id.len() as u8),
758 connection_id: self.id.to_string(),
759 stateless_reset_token: Some(self.reset_token.to_string()),
760 raw: None,
761 },
762 }
763 }
764}
765
766#[cfg(feature = "qlog")]
767impl ToQlog for frame::NewToken {
768 fn to_qlog(&self) -> QuicFrame {
769 QuicFrame::NewToken {
770 token: qlog::Token {
771 ty: Some(TokenType::Retry),
772 raw: Some(RawInfo {
773 data: HexSlice::maybe_string(Some(&self.token)).map(Box::new),
774 length: Some(self.token.len() as u64),
775 payload_length: None,
776 }),
777 details: None,
778 },
779 raw: None,
780 }
781 }
782}
783
784#[cfg(feature = "qlog")]
785impl ToQlog for frame::ObservedAddr {
786 fn to_qlog(&self) -> QuicFrame {
787 QuicFrame::ObservedAddress {
788 sequence_number: self.seq_no.into_inner(),
789 ip_v4: match self.ip {
790 IpAddr::V4(ipv4_addr) => Some(ipv4_addr.to_string()),
791 IpAddr::V6(ipv6_addr) => None,
792 },
793 ip_v6: match self.ip {
794 IpAddr::V4(ipv4_addr) => None,
795 IpAddr::V6(ipv6_addr) => Some(ipv6_addr.to_string()),
796 },
797 port: self.port,
798 raw: None,
799 }
800 }
801}
802
803#[cfg(feature = "qlog")]
804impl ToQlog for frame::PathAbandon {
805 fn to_qlog(&self) -> QuicFrame {
806 QuicFrame::PathAbandon {
807 path_id: self.path_id.as_u32().into(),
808 error_code: self.error_code.into(),
809 raw: None,
810 }
811 }
812}
813
814#[cfg(feature = "qlog")]
815impl ToQlog for frame::PathAckEncoder<'_> {
816 fn to_qlog(&self) -> QuicFrame {
817 QuicFrame::PathAck {
818 path_id: self.path_id.as_u32() as u64,
819 ack_delay: Some(self.delay as f32),
820 acked_ranges: Some(
821 self.ranges
822 .iter()
823 .map(|range| AckRange::new(range.start, range.end))
824 .collect(),
825 ),
826 ect1: self.ecn.map(|e| e.ect1),
827 ect0: self.ecn.map(|e| e.ect0),
828 ce: self.ecn.map(|e| e.ce),
829 raw: None,
830 }
831 }
832}
833
834#[cfg(feature = "qlog")]
835impl ToQlog for frame::PathChallenge {
836 #[cfg(feature = "qlog")]
837 fn to_qlog(&self) -> QuicFrame {
838 QuicFrame::PathChallenge {
839 data: Some(self.to_string()),
840 raw: None,
841 }
842 }
843}
844
845#[cfg(feature = "qlog")]
846impl ToQlog for frame::PathCidsBlocked {
847 fn to_qlog(&self) -> QuicFrame {
848 QuicFrame::PathCidsBlocked {
849 path_id: self.path_id.as_u32().into(),
850 next_sequence_number: self.next_seq.into(),
851 raw: None,
852 }
853 }
854}
855
856#[cfg(feature = "qlog")]
857impl ToQlog for frame::PathResponse {
858 fn to_qlog(&self) -> QuicFrame {
859 QuicFrame::PathResponse {
860 data: Some(self.to_string()),
861 raw: None,
862 }
863 }
864}
865
866#[cfg(feature = "qlog")]
867impl ToQlog for frame::ReachOut {
868 fn to_qlog(&self) -> QuicFrame {
869 QuicFrame::ReachOut {
870 round: self.round.into_inner(),
871 ip_v4: match self.ip {
872 IpAddr::V4(ipv4_addr) => Some(ipv4_addr.to_string()),
873 IpAddr::V6(ipv6_addr) => None,
874 },
875 ip_v6: match self.ip {
876 IpAddr::V4(ipv4_addr) => None,
877 IpAddr::V6(ipv6_addr) => Some(ipv6_addr.to_string()),
878 },
879 port: self.port,
880 }
881 }
882}
883
884#[cfg(feature = "qlog")]
885impl ToQlog for frame::Ping {
886 fn to_qlog(&self) -> QuicFrame {
887 QuicFrame::Ping { raw: None }
888 }
889}
890
891#[cfg(feature = "qlog")]
892impl ToQlog for frame::PathStatusAvailable {
893 fn to_qlog(&self) -> QuicFrame {
894 QuicFrame::PathStatusAvailable {
895 path_id: self.path_id.as_u32().into(),
896 path_status_sequence_number: self.status_seq_no.into(),
897 raw: None,
898 }
899 }
900}
901
902#[cfg(feature = "qlog")]
903impl ToQlog for frame::PathStatusBackup {
904 fn to_qlog(&self) -> QuicFrame {
905 QuicFrame::PathStatusBackup {
906 path_id: self.path_id.as_u32().into(),
907 path_status_sequence_number: self.status_seq_no.into(),
908 raw: None,
909 }
910 }
911}
912
913#[cfg(feature = "qlog")]
914impl ToQlog for frame::PathsBlocked {
915 fn to_qlog(&self) -> QuicFrame {
916 QuicFrame::PathsBlocked {
917 maximum_path_id: self.0.as_u32().into(),
918 raw: None,
919 }
920 }
921}
922
923#[cfg(feature = "qlog")]
924impl ToQlog for frame::ResetStream {
925 fn to_qlog(&self) -> QuicFrame {
926 QuicFrame::ResetStream {
927 stream_id: self.id.into(),
928 error_code: Some(self.error_code.into_inner()),
929 final_size: self.final_offset.into(),
930 error: ApplicationError::Unknown,
931 raw: None,
932 }
933 }
934}
935
936#[cfg(feature = "qlog")]
937impl ToQlog for frame::StopSending {
938 fn to_qlog(&self) -> QuicFrame {
939 QuicFrame::StopSending {
940 stream_id: self.id.into(),
941 error_code: Some(self.error_code.into_inner()),
942 error: ApplicationError::Unknown,
943 raw: None,
944 }
945 }
946}
947
948#[cfg(feature = "qlog")]
949impl ToQlog for frame::RetireConnectionId {
950 fn to_qlog(&self) -> QuicFrame {
951 match self.path_id {
952 None => QuicFrame::RetireConnectionId {
953 sequence_number: self.sequence,
954 raw: None,
955 },
956 Some(path_id) => QuicFrame::PathRetireConnectionId {
957 path_id: path_id.0 as u64,
958 sequence_number: self.sequence,
959 raw: None,
960 },
961 }
962 }
963}
964
965#[cfg(feature = "qlog")]
966impl ToQlog for frame::RemoveAddress {
967 fn to_qlog(&self) -> QuicFrame {
968 QuicFrame::RemoveAddress {
969 sequence_number: self.seq_no.into_inner(),
970 }
971 }
972}
973
974#[cfg(feature = "qlog")]
975impl ToQlog for frame::StreamMetaEncoder {
976 fn to_qlog(&self) -> QuicFrame {
977 let meta = &self.meta;
978 QuicFrame::Stream {
979 stream_id: meta.id.into(),
980 offset: Some(meta.offsets.start),
981 fin: Some(meta.fin),
982 raw: Some(Box::new(RawInfo {
983 length: Some(meta.offsets.end - meta.offsets.start),
984 ..Default::default()
985 })),
986 }
987 }
988}
989
990#[cfg(feature = "qlog")]
991impl Frame {
992 pub(crate) fn to_qlog(&self) -> QuicFrame {
994 match self {
995 Self::Padding => QuicFrame::Padding {
996 raw: Some(Box::new(RawInfo {
997 length: None,
998 payload_length: Some(1),
999 data: None,
1000 })),
1001 },
1002 Self::Ping => frame::Ping.to_qlog(),
1003 Self::Ack(f) => QuicFrame::Ack {
1004 ack_delay: Some(f.delay as f32),
1005 acked_ranges: Some(
1006 f.iter()
1007 .map(|range| AckRange::new(range.start, range.end))
1008 .collect(),
1009 ),
1010 ect1: f.ecn.as_ref().map(|e| e.ect1),
1011 ect0: f.ecn.as_ref().map(|e| e.ect0),
1012 ce: f.ecn.as_ref().map(|e| e.ce),
1013 raw: None,
1014 },
1015 Self::ResetStream(f) => f.to_qlog(),
1016 Self::StopSending(f) => f.to_qlog(),
1017 Self::Crypto(f) => f.to_qlog(),
1018 Self::NewToken(f) => f.to_qlog(),
1019 Self::Stream(s) => QuicFrame::Stream {
1020 stream_id: s.id.into(),
1021 offset: Some(s.offset),
1022 fin: Some(s.fin),
1023 raw: Some(Box::new(RawInfo {
1024 length: Some(s.data.len() as u64),
1025 ..Default::default()
1026 })),
1027 },
1028 Self::MaxData(v) => v.to_qlog(),
1029 Self::MaxStreamData(f) => f.to_qlog(),
1030 Self::MaxStreams(f) => f.to_qlog(),
1031 Self::DataBlocked(DataBlocked(offset)) => QuicFrame::DataBlocked {
1032 limit: *offset,
1033 raw: None,
1034 },
1035 Self::StreamDataBlocked(StreamDataBlocked { id, offset }) => {
1036 QuicFrame::StreamDataBlocked {
1037 stream_id: (*id).into(),
1038 limit: *offset,
1039 raw: None,
1040 }
1041 }
1042 Self::StreamsBlocked(StreamsBlocked { dir, limit }) => QuicFrame::StreamsBlocked {
1043 stream_type: (*dir).into(),
1044 limit: *limit,
1045 raw: None,
1046 },
1047 Self::NewConnectionId(f) => f.to_qlog(),
1048 Self::RetireConnectionId(f) => f.to_qlog(),
1049 Self::PathChallenge(f) => f.to_qlog(),
1050 Self::PathResponse(f) => f.to_qlog(),
1051 Self::Close(close) => close.to_qlog(),
1052 Self::Datagram(d) => d.to_qlog(),
1053 Self::HandshakeDone => frame::HandshakeDone.to_qlog(),
1054 Self::PathAck(ack) => QuicFrame::PathAck {
1055 path_id: ack.path_id.as_u32().into(),
1056 ack_delay: Some(ack.delay as f32),
1057 ect1: ack.ecn.as_ref().map(|e| e.ect1),
1058 ect0: ack.ecn.as_ref().map(|e| e.ect0),
1059 ce: ack.ecn.as_ref().map(|e| e.ce),
1060 raw: None,
1061 acked_ranges: Some(
1062 ack.ranges
1063 .iter()
1064 .map(|range| AckRange::new(range.start, range.end))
1065 .collect(),
1066 ),
1067 },
1068 Self::PathAbandon(frame) => frame.to_qlog(),
1069 Self::PathStatusAvailable(frame) => frame.to_qlog(),
1070 Self::PathStatusBackup(frame) => frame.to_qlog(),
1071 Self::PathsBlocked(frame) => frame.to_qlog(),
1072 Self::PathCidsBlocked(frame) => frame.to_qlog(),
1073 Self::MaxPathId(f) => f.to_qlog(),
1074 Self::AckFrequency(f) => f.to_qlog(),
1075 Self::ImmediateAck => frame::ImmediateAck.to_qlog(),
1076 Self::ObservedAddr(f) => f.to_qlog(),
1077 Self::AddAddress(f) => f.to_qlog(),
1078 Self::ReachOut(f) => f.to_qlog(),
1079 Self::RemoveAddress(f) => f.to_qlog(),
1080 }
1081 }
1082}
1083
1084#[cfg(feature = "qlog")]
1085impl From<crate::Dir> for StreamType {
1086 fn from(value: crate::Dir) -> Self {
1087 match value {
1088 crate::Dir::Bi => Self::Bidirectional,
1089 crate::Dir::Uni => Self::Unidirectional,
1090 }
1091 }
1092}
1093
1094#[cfg(feature = "qlog")]
1095fn packet_type(space: SpaceKind, is_0rtt: bool) -> PacketType {
1096 match space {
1097 SpaceKind::Initial => PacketType::Initial,
1098 SpaceKind::Handshake => PacketType::Handshake,
1099 SpaceKind::Data if is_0rtt => PacketType::ZeroRtt,
1100 SpaceKind::Data => PacketType::OneRtt,
1101 }
1102}
1103
1104#[cfg(feature = "qlog")]
1105impl From<EncryptionLevel> for PacketType {
1106 fn from(encryption_level: EncryptionLevel) -> Self {
1107 match encryption_level {
1108 EncryptionLevel::Initial => Self::Initial,
1109 EncryptionLevel::Handshake => Self::Handshake,
1110 EncryptionLevel::ZeroRtt => Self::ZeroRtt,
1111 EncryptionLevel::OneRtt => Self::OneRtt,
1112 }
1113 }
1114}
1115
1116#[cfg(feature = "qlog")]
1117fn stringify_cid(cid: ConnectionId) -> String {
1118 format!("{cid}")
1119}
1120
1121#[cfg(feature = "qlog")]
1122fn tuple_endpoint_info(
1123 ip: Option<IpAddr>,
1124 port: Option<u16>,
1125 cid: Option<ConnectionId>,
1126) -> TupleEndpointInfo {
1127 let (ip_v4, port_v4, ip_v6, port_v6) = match ip {
1128 Some(addr) => match addr {
1129 IpAddr::V4(ipv4_addr) => (Some(ipv4_addr.to_string()), port, None, None),
1130 IpAddr::V6(ipv6_addr) => (None, None, Some(ipv6_addr.to_string()), port),
1131 },
1132 None => (None, None, None, None),
1133 };
1134 TupleEndpointInfo {
1135 ip_v4,
1136 port_v4,
1137 ip_v6,
1138 port_v6,
1139 connection_ids: cid.map(|cid| vec![cid.to_string()]),
1140 }
1141}
1142
1143#[cfg(feature = "qlog")]
1144fn transport_error(code: TransportErrorCode) -> (Option<quic::TransportError>, Option<u64>) {
1145 let transport_error = match code {
1146 TransportErrorCode::NO_ERROR => Some(quic::TransportError::NoError),
1147 TransportErrorCode::INTERNAL_ERROR => Some(quic::TransportError::InternalError),
1148 TransportErrorCode::CONNECTION_REFUSED => Some(quic::TransportError::ConnectionRefused),
1149 TransportErrorCode::FLOW_CONTROL_ERROR => Some(quic::TransportError::FlowControlError),
1150 TransportErrorCode::STREAM_LIMIT_ERROR => Some(quic::TransportError::StreamLimitError),
1151 TransportErrorCode::STREAM_STATE_ERROR => Some(quic::TransportError::StreamStateError),
1152 TransportErrorCode::FINAL_SIZE_ERROR => Some(quic::TransportError::FinalSizeError),
1153 TransportErrorCode::FRAME_ENCODING_ERROR => Some(quic::TransportError::FrameEncodingError),
1154 TransportErrorCode::TRANSPORT_PARAMETER_ERROR => {
1155 Some(quic::TransportError::TransportParameterError)
1156 }
1157 TransportErrorCode::CONNECTION_ID_LIMIT_ERROR => {
1158 Some(quic::TransportError::ConnectionIdLimitError)
1159 }
1160 TransportErrorCode::PROTOCOL_VIOLATION => Some(quic::TransportError::ProtocolViolation),
1161 TransportErrorCode::INVALID_TOKEN => Some(quic::TransportError::InvalidToken),
1162 TransportErrorCode::APPLICATION_ERROR => Some(quic::TransportError::ApplicationError),
1163 TransportErrorCode::CRYPTO_BUFFER_EXCEEDED => {
1164 Some(quic::TransportError::CryptoBufferExceeded)
1165 }
1166 TransportErrorCode::KEY_UPDATE_ERROR => Some(quic::TransportError::KeyUpdateError),
1167 TransportErrorCode::AEAD_LIMIT_REACHED => Some(quic::TransportError::AeadLimitReached),
1168 TransportErrorCode::NO_VIABLE_PATH => Some(quic::TransportError::NoViablePath),
1169 TransportErrorCode::APPLICATION_ABANDON_PATH => {
1171 Some(quic::TransportError::ApplicationAbandonPath)
1172 }
1173 TransportErrorCode::PATH_RESOURCE_LIMIT_REACHED => {
1174 Some(quic::TransportError::PathResourceLimitReached)
1175 }
1176 TransportErrorCode::PATH_UNSTABLE_OR_POOR => Some(quic::TransportError::PathUnstableOrPoor),
1177 TransportErrorCode::NO_CID_AVAILABLE_FOR_PATH => {
1178 Some(quic::TransportError::NoCidsAvailableForPath)
1179 }
1180 _ => None,
1181 };
1182 let code = match transport_error {
1183 None => Some(code.into()),
1184 Some(_) => None,
1185 };
1186 (transport_error, code)
1187}
1188
1189#[cfg(feature = "qlog")]
1190fn fmt_tuple_id(path_id: u64) -> String {
1191 format!("p{path_id}")
1192}
1193
1194#[cfg(feature = "qlog")]
1195impl TransportParameters {
1196 fn to_qlog(self, initiator: TransportInitiator) -> ParametersSet {
1197 ParametersSet {
1198 initiator: Some(initiator),
1199 resumption_allowed: None,
1200 early_data_enabled: None,
1201 tls_cipher: None,
1202 original_destination_connection_id: self
1203 .original_dst_cid
1204 .as_ref()
1205 .map(ToString::to_string),
1206 initial_source_connection_id: self.initial_src_cid.as_ref().map(ToString::to_string),
1207 retry_source_connection_id: self.retry_src_cid.as_ref().map(ToString::to_string),
1208 stateless_reset_token: self.stateless_reset_token.as_ref().map(ToString::to_string),
1209 disable_active_migration: Some(self.disable_active_migration),
1210 max_idle_timeout: Some(self.max_idle_timeout.into()),
1211 max_udp_payload_size: Some(self.max_udp_payload_size.into()),
1212 ack_delay_exponent: Some(self.ack_delay_exponent.into()),
1213 max_ack_delay: Some(self.max_ack_delay.into()),
1214 active_connection_id_limit: Some(self.active_connection_id_limit.into()),
1215 initial_max_data: Some(self.initial_max_data.into()),
1216 initial_max_stream_data_bidi_local: Some(
1217 self.initial_max_stream_data_bidi_local.into(),
1218 ),
1219 initial_max_stream_data_bidi_remote: Some(
1220 self.initial_max_stream_data_bidi_remote.into(),
1221 ),
1222 initial_max_stream_data_uni: Some(self.initial_max_stream_data_uni.into()),
1223 initial_max_streams_bidi: Some(self.initial_max_streams_bidi.into()),
1224 initial_max_streams_uni: Some(self.initial_max_streams_uni.into()),
1225 preferred_address: self.preferred_address.as_ref().map(Into::into),
1226 min_ack_delay: self.min_ack_delay.map(Into::into),
1227 address_discovery: self.address_discovery_role.to_qlog(),
1228 initial_max_path_id: self.initial_max_path_id.map(|p| p.as_u32() as u64),
1229 max_remote_nat_traversal_addresses: self
1230 .max_remote_nat_traversal_addresses
1231 .map(|v| u64::from(v.get())),
1232 max_datagram_frame_size: self.max_datagram_frame_size.map(Into::into),
1233 grease_quic_bit: Some(self.grease_quic_bit),
1234 unknown_parameters: Default::default(),
1235 }
1236 }
1237
1238 fn to_qlog_restored(self) -> ParametersRestored {
1239 ParametersRestored {
1240 disable_active_migration: Some(self.disable_active_migration),
1241 max_idle_timeout: Some(self.max_idle_timeout.into()),
1242 max_udp_payload_size: Some(self.max_udp_payload_size.into()),
1243 active_connection_id_limit: Some(self.active_connection_id_limit.into()),
1244 initial_max_data: Some(self.initial_max_data.into()),
1245 initial_max_stream_data_bidi_local: Some(
1246 self.initial_max_stream_data_bidi_local.into(),
1247 ),
1248 initial_max_stream_data_bidi_remote: Some(
1249 self.initial_max_stream_data_bidi_remote.into(),
1250 ),
1251 initial_max_stream_data_uni: Some(self.initial_max_stream_data_uni.into()),
1252 initial_max_streams_bidi: Some(self.initial_max_streams_bidi.into()),
1253 initial_max_streams_uni: Some(self.initial_max_streams_uni.into()),
1254 max_datagram_frame_size: self.max_datagram_frame_size.map(Into::into),
1255 grease_quic_bit: Some(self.grease_quic_bit),
1256 }
1257 }
1258}
1259
1260#[cfg(feature = "qlog")]
1261impl From<&crate::transport_parameters::PreferredAddress> for PreferredAddress {
1262 fn from(value: &crate::transport_parameters::PreferredAddress) -> Self {
1263 let port_v4 = value.address_v4.map(|addr| addr.port()).unwrap_or_default();
1264 let port_v6 = value.address_v6.map(|addr| addr.port()).unwrap_or_default();
1265 let ip_v4 = value
1266 .address_v4
1267 .map(|addr| addr.ip().to_string())
1268 .unwrap_or_default();
1269 let ip_v6 = value
1270 .address_v6
1271 .map(|addr| addr.ip().to_string())
1272 .unwrap_or_default();
1273 let connection_id = value.connection_id.to_string();
1274 let stateless_reset_token = value.stateless_reset_token.to_string();
1275
1276 Self {
1277 ip_v4,
1278 ip_v6,
1279 port_v4,
1280 port_v6,
1281 connection_id,
1282 stateless_reset_token,
1283 }
1284 }
1285}
1286
1287#[cfg(feature = "qlog")]
1288impl crate::address_discovery::Role {
1289 fn to_qlog(self) -> Option<AddressDiscoveryRole> {
1290 match (self.send, self.receive) {
1291 (false, false) => None,
1292 (true, false) => Some(AddressDiscoveryRole::SendOnly),
1293 (false, true) => Some(AddressDiscoveryRole::ReceiveOnly),
1294 (true, true) => Some(AddressDiscoveryRole::Both),
1295 }
1296 }
1297}