1use std::net::SocketAddr;
28use std::ops::ControlFlow;
29use std::sync::Arc;
30use std::task::Poll;
31use std::time::Duration;
32use std::time::Instant;
33#[cfg(feature = "perf-quic-listener-metrics")]
34use std::time::SystemTime;
35
36use super::connection_stage::Close;
37use super::connection_stage::ConnectionStage;
38use super::connection_stage::ConnectionStageContext;
39use super::connection_stage::Handshake;
40use super::connection_stage::RunningApplication;
41use super::gso::*;
42use super::utilization_estimator::BandwidthReporter;
43
44use crate::metrics::labels;
45use crate::metrics::Metrics;
46use crate::quic::connection::ApplicationOverQuic;
47use crate::quic::connection::HandshakeError;
48use crate::quic::connection::HandshakeInfo;
49use crate::quic::connection::Incoming;
50use crate::quic::connection::IncomingPacketReceiver;
51use crate::quic::connection::QuicConnectionStats;
52use crate::quic::connection::SharedConnectionIdGenerator;
53use crate::quic::hooks::ConnectionHook;
54use crate::quic::DscpHandle;
55use crate::quic::QuicheConnection;
56use crate::QuicResult;
57
58use boring::ssl::SslRef;
59use datagram_socket::DatagramSocketSend;
60use datagram_socket::DatagramSocketSendExt;
61use datagram_socket::MaybeConnectedSocket;
62use datagram_socket::QuicAuditStats;
63use foundations::telemetry::log;
64use foundations::telemetry::metrics::Gauge;
65use foundations::telemetry::metrics::GaugeGuard;
66use quiche::Error as QuicheError;
67use quiche::SendInfo;
68use tokio::select;
69use tokio::sync::mpsc;
70use tokio::time;
71
72pub(crate) const INCOMING_QUEUE_SIZE: usize = 2048;
74
75pub(crate) const CHECK_INCOMING_QUEUE_RATIO: usize = INCOMING_QUEUE_SIZE / 16;
78
79const RELEASE_TIMER_THRESHOLD: Duration = Duration::from_micros(250);
80
81const GSO_THRESHOLD: usize = 1_000;
83
84const SEND_BUFFER_SIZE: usize = crate::buf_factory::BufFactory::MAX_BUF_SIZE;
92
93const TRANSIENT_SEND_BUFFER_SIZE: usize = 1500;
99
100fn alloc_send_buffer() -> Box<[u8]> {
108 vec![0u8; SEND_BUFFER_SIZE].into_boxed_slice()
109}
110
111thread_local! {
112 static SEND_BUF_POOL: std::cell::RefCell<Vec<Box<[u8]>>> =
120 const { std::cell::RefCell::new(Vec::new()) };
121}
122
123const SEND_BUF_POOL_CAP: usize = 16;
134
135struct PooledSendBuf(Box<[u8]>);
142
143impl PooledSendBuf {
144 fn acquire() -> Self {
145 let buf = SEND_BUF_POOL
146 .with(|pool| pool.borrow_mut().pop())
147 .unwrap_or_else(|| {
148 crate::metrics::quic::send_buffer_pool_allocated().inc();
152 alloc_send_buffer()
153 });
154 Self(buf)
158 }
159}
160
161impl Drop for PooledSendBuf {
162 fn drop(&mut self) {
163 let buf = std::mem::take(&mut self.0);
168 SEND_BUF_POOL.with(|pool| {
173 let mut pool = pool.borrow_mut();
174 if pool.len() < SEND_BUF_POOL_CAP {
175 pool.push(buf);
176 } else {
177 crate::metrics::quic::send_buffer_pool_discarded().inc();
182 }
183 });
184 }
185}
186
187impl std::ops::Deref for PooledSendBuf {
188 type Target = [u8];
189
190 fn deref(&self) -> &[u8] {
191 &self.0
192 }
193}
194
195impl std::ops::DerefMut for PooledSendBuf {
196 fn deref_mut(&mut self) -> &mut [u8] {
197 &mut self.0
198 }
199}
200
201enum TransientSendBuf {
207 Pooled(PooledSendBuf),
208 Unpooled(Box<[u8]>),
209}
210
211impl TransientSendBuf {
212 fn acquire(pool_send_buffer: bool) -> Self {
213 if pool_send_buffer {
214 Self::Pooled(PooledSendBuf::acquire())
215 } else {
216 Self::Unpooled(
217 vec![0u8; TRANSIENT_SEND_BUFFER_SIZE].into_boxed_slice(),
218 )
219 }
220 }
221}
222
223impl AsRef<[u8]> for TransientSendBuf {
224 fn as_ref(&self) -> &[u8] {
225 match self {
226 Self::Pooled(buf) => &buf[..],
227 Self::Unpooled(buf) => &buf[..],
228 }
229 }
230}
231
232impl AsMut<[u8]> for TransientSendBuf {
233 fn as_mut(&mut self) -> &mut [u8] {
234 match self {
235 Self::Pooled(buf) => &mut buf[..],
236 Self::Unpooled(buf) => &mut buf[..],
237 }
238 }
239}
240
241pub struct WriterConfig {
242 pub peer_addr: SocketAddr,
243 pub local_addr: SocketAddr,
244 pub with_gso: bool,
245 pub pacing_offload: bool,
246 pub with_pktinfo: bool,
247 pub pool_send_buffer: bool,
251}
252
253#[derive(Default)]
254pub(crate) struct WriteState {
255 conn_established: bool,
256 bytes_written: usize,
257 segment_size: usize,
258 num_pkts: usize,
259 tx_time: Option<Instant>,
260 has_pending_data: bool,
261 next_release_time: Option<Instant>,
264 selected_path: Option<(SocketAddr, SocketAddr)>,
267 pending_paths: quiche::SocketAddrIter,
269}
270
271pub(crate) struct IoWorkerParams<Tx, M> {
272 pub(crate) socket: MaybeConnectedSocket<Tx>,
273 pub(crate) shutdown_tx: mpsc::Sender<()>,
274 pub(crate) cfg: WriterConfig,
275 pub(crate) audit_log_stats: Arc<QuicAuditStats>,
276 pub(crate) write_state: WriteState,
277 pub(crate) dscp_handle: Option<DscpHandle>,
278 pub(crate) cid_generator: Option<SharedConnectionIdGenerator>,
279 #[cfg(feature = "perf-quic-listener-metrics")]
280 pub(crate) init_rx_time: Option<SystemTime>,
281 pub(crate) metrics: M,
282 pub(crate) handshake_info: HandshakeInfo,
283 pub(crate) active_conn_guard: GaugeGuard<Gauge>,
284}
285
286fn notify_path_events(
287 connection_hook: Option<&(dyn ConnectionHook + Send + Sync + 'static)>,
288 qconn: &mut QuicheConnection,
289) {
290 while let Some(path_event) = qconn.path_event_next() {
291 if let Some(hook) = connection_hook {
292 hook.on_path_event(qconn, &path_event);
293 }
294 }
295}
296
297pub(crate) struct IoWorker<Tx, M, S> {
298 socket: MaybeConnectedSocket<Tx>,
299 shutdown_tx: mpsc::Sender<()>,
303 cfg: WriterConfig,
304 audit_log_stats: Arc<QuicAuditStats>,
305 write_state: WriteState,
306 dscp_handle: Option<DscpHandle>,
307 cid_generator: Option<SharedConnectionIdGenerator>,
308 #[cfg(feature = "perf-quic-listener-metrics")]
309 init_rx_time: Option<SystemTime>,
310 metrics: M,
311 handshake_info: HandshakeInfo,
317 conn_stage: S,
318 bw_estimator: BandwidthReporter,
319 active_conn_guard: GaugeGuard<Gauge>,
321}
322
323impl<Tx, M, S> IoWorker<Tx, M, S>
324where
325 Tx: DatagramSocketSend + Send,
326 M: Metrics,
327 S: ConnectionStage,
328{
329 pub(crate) fn new(params: IoWorkerParams<Tx, M>, conn_stage: S) -> Self {
330 let bw_estimator =
331 BandwidthReporter::new(params.metrics.utilized_bandwidth());
332
333 log::trace!("Creating IoWorker with stage: {conn_stage:?}");
334
335 Self {
336 socket: params.socket,
337 shutdown_tx: params.shutdown_tx,
338 cfg: params.cfg,
339 audit_log_stats: params.audit_log_stats,
340 write_state: params.write_state,
341 dscp_handle: params.dscp_handle,
342 cid_generator: params.cid_generator,
343 #[cfg(feature = "perf-quic-listener-metrics")]
344 init_rx_time: params.init_rx_time,
345 metrics: params.metrics,
346 handshake_info: params.handshake_info,
347 conn_stage,
348 bw_estimator,
349 active_conn_guard: params.active_conn_guard,
350 }
351 }
352
353 fn fill_available_scids(
354 &self, qconn: &mut QuicheConnection,
355 incoming_pkt_receiver: &mut IncomingPacketReceiver,
356 ) {
357 if qconn.scids_left() == 0 {
358 return;
359 }
360 let Some(cid_generator) = self.cid_generator.as_deref() else {
361 return;
362 };
363
364 for _ in 0..qconn.scids_left() {
365 let reset_token = random_u128();
367 let new_cid = cid_generator.new_connection_id();
368
369 if !incoming_pkt_receiver.map_cid(&new_cid) {
370 return;
372 }
373
374 if qconn.new_scid(&new_cid, reset_token, false).is_err() {
375 return;
377 }
378 }
379 }
380
381 fn refresh_connection_ids(
382 &self, qconn: &mut QuicheConnection,
383 incoming_pkt_receiver: &mut IncomingPacketReceiver,
384 ) {
385 self.fill_available_scids(qconn, incoming_pkt_receiver);
387
388 while let Some(retired_cid) = qconn.retired_scid_next() {
390 incoming_pkt_receiver.unmap_cid(&retired_cid);
391 }
392 }
393
394 async fn work_loop<A: ApplicationOverQuic>(
395 &mut self, qconn: &mut QuicheConnection,
396 ctx: &mut ConnectionStageContext<A>,
397 ) -> QuicResult<()> {
398 const DEFAULT_SLEEP: Duration = Duration::from_secs(60);
399 let mut current_deadline: Option<Instant> = None;
400 let sleep = time::sleep(DEFAULT_SLEEP);
401 tokio::pin!(sleep);
402
403 let mut persistent_send_buf: Option<Box<[u8]>> =
407 (!self.cfg.pool_send_buffer).then(alloc_send_buffer);
408
409 loop {
410 let now = Instant::now();
411
412 self.write_state.has_pending_data = true;
413
414 let mut pooled_send_buf: Option<PooledSendBuf> = None;
420
421 while self.write_state.has_pending_data {
422 let mut packets_sent = 0;
423
424 let mut did_recv = false;
427 while let Some(pkt) = ctx
428 .in_pkt
429 .take()
430 .or_else(|| ctx.incoming_pkt_receiver.rx.try_recv().ok())
431 {
432 self.process_incoming(qconn, pkt)?;
433 did_recv = true;
434 }
435
436 notify_path_events(ctx.connection_hook.as_deref(), qconn);
439
440 self.conn_stage.on_read(did_recv, qconn, ctx)?;
441
442 notify_path_events(ctx.connection_hook.as_deref(), qconn);
444 self.refresh_connection_ids(
445 qconn,
446 &mut ctx.incoming_pkt_receiver,
447 );
448
449 let can_release = match self.write_state.next_release_time {
450 None => true,
451 Some(next_release) =>
452 next_release
453 .checked_duration_since(now)
454 .unwrap_or_default() <
455 RELEASE_TIMER_THRESHOLD,
456 };
457
458 self.write_state.has_pending_data &= can_release;
459
460 while self.write_state.has_pending_data &&
461 packets_sent < CHECK_INCOMING_QUEUE_RATIO
462 {
463 let send_buf: &mut [u8] =
470 if let Some(buf) = persistent_send_buf.as_deref_mut() {
471 buf
472 } else {
473 &mut pooled_send_buf
474 .get_or_insert_with(PooledSendBuf::acquire)[..]
475 };
476
477 self.gather_data_from_quiche_conn(qconn, send_buf, false)?;
478
479 if qconn.is_closed() {
481 return Ok(());
482 }
483
484 let mut flush_operation_token =
485 TrackMidHandshakeFlush::new(self.metrics.clone());
486
487 self.flush_buffer_to_socket(&send_buf[..]).await;
488
489 flush_operation_token.mark_complete();
490
491 packets_sent += self.write_state.num_pkts;
492
493 if let ControlFlow::Break(reason) =
494 self.conn_stage.on_flush(qconn, ctx)
495 {
496 return reason;
497 }
498 }
499 }
500
501 drop(pooled_send_buf);
506
507 self.bw_estimator.update(qconn, now);
508
509 self.audit_log_stats
510 .set_max_bandwidth(self.bw_estimator.max_bandwidth);
511 self.audit_log_stats.set_max_loss_pct(
512 (self.bw_estimator.max_loss_pct * 100_f32).round() as u8,
513 );
514
515 let new_deadline = min_of_some(
516 qconn.timeout_instant(),
517 self.write_state.next_release_time,
518 );
519 let new_deadline =
520 min_of_some(new_deadline, self.handshake_deadline(qconn));
521
522 if new_deadline != current_deadline {
523 current_deadline = new_deadline;
524
525 sleep
526 .as_mut()
527 .reset(new_deadline.unwrap_or(now + DEFAULT_SLEEP).into());
528 }
529
530 let incoming_recv = &mut ctx.incoming_pkt_receiver.rx;
531 let application = &mut ctx.application;
532
533 select! {
534 biased;
535 () = &mut sleep => {
536 qconn.on_timeout();
543
544 self.write_state.next_release_time = None;
545 current_deadline = None;
546 sleep.as_mut().reset((now + DEFAULT_SLEEP).into());
547 }
548 Some(pkt) = incoming_recv.recv() => ctx.in_pkt = Some(pkt),
549 directive = self.wait_for_data_or_handshake(qconn, application) => {
550 match directive? {
551 WaitForDataOrHandshakeDirective::Flush(send_buf) => {
552 self.flush_buffer_to_socket(send_buf.as_ref()).await;
557 }
558 WaitForDataOrHandshakeDirective::Noop => {}
559 }
560 },
561 };
562
563 self.enforce_handshake_deadline(qconn)?;
564 }
565 }
566
567 #[cfg(feature = "perf-quic-listener-metrics")]
568 fn measure_complete_handshake_time(&mut self) {
569 if let Some(init_rx_time) = self.init_rx_time.take() {
570 if let Ok(delta) = init_rx_time.elapsed() {
571 self.metrics
572 .handshake_time_seconds(
573 labels::QuicHandshakeStage::HandshakeResponse,
574 )
575 .observe(delta.as_nanos() as u64);
576 }
577 }
578 }
579
580 fn gather_data_from_quiche_conn(
585 &mut self, qconn: &mut QuicheConnection, send_buf: &mut [u8],
586 single_packet: bool,
587 ) -> QuicResult<usize> {
588 let mut segment_size = None;
589 let mut send_info = None;
590
591 self.write_state.num_pkts = 0;
592 self.write_state.bytes_written = 0;
593
594 self.write_state.selected_path = None;
595
596 let now = Instant::now();
597
598 let send_buf = {
599 let trunc = UDP_MAX_GSO_PACKET_SIZE.min(send_buf.len());
600 &mut send_buf[..trunc]
601 };
602
603 #[cfg(feature = "gcongestion")]
604 let gcongestion_enabled = true;
605
606 #[cfg(not(feature = "gcongestion"))]
607 let gcongestion_enabled = qconn.gcongestion_enabled().unwrap_or(false);
608
609 let initial_release_decision = if gcongestion_enabled {
610 let initial_release_decision = qconn
611 .get_next_release_time()
612 .filter(|_| self.pacing_enabled(qconn));
613
614 if let Some(future_release_time) =
615 initial_release_decision.as_ref().and_then(|v| v.time(now))
616 {
617 let max_into_fut = qconn.max_release_into_future();
618
619 if future_release_time.duration_since(now) >= max_into_fut {
620 self.write_state.next_release_time =
621 Some(now + max_into_fut.mul_f32(0.8));
622 self.write_state.has_pending_data = false;
623 return Ok(0);
624 }
625 }
626
627 initial_release_decision
628 } else {
629 None
630 };
631
632 let buffer_write_outcome = loop {
633 let outcome = self.write_packet_to_buffer(
634 qconn,
635 send_buf,
636 &mut send_info,
637 segment_size,
638 );
639
640 let packet_size = match outcome {
641 Ok(0) => break Ok(0),
642
643 Ok(bytes_written) => bytes_written,
644
645 Err(e) => break Err(e),
646 };
647
648 if single_packet || !self.cfg.with_gso {
651 break outcome;
652 }
653
654 #[cfg(not(feature = "gcongestion"))]
655 let max_send_size = if !gcongestion_enabled {
656 tune_max_send_size(
658 segment_size,
659 qconn.send_quantum(),
660 send_buf.len(),
661 )
662 } else {
663 usize::MAX
664 };
665
666 #[cfg(feature = "gcongestion")]
667 let max_send_size = usize::MAX;
668
669 let buffer_is_full = self.write_state.num_pkts ==
673 UDP_MAX_SEGMENT_COUNT ||
674 self.write_state.bytes_written >= max_send_size;
675
676 if buffer_is_full {
677 break outcome;
678 }
679
680 match segment_size {
685 Some(size)
686 if packet_size != size || packet_size < GSO_THRESHOLD =>
687 break outcome,
688 None => segment_size = Some(packet_size),
689 _ => (),
690 }
691
692 if gcongestion_enabled {
693 if let Some(initial_release_decision) = initial_release_decision {
696 match qconn.get_next_release_time() {
697 Some(release)
698 if release.can_burst() ||
699 release.time_eq(
700 &initial_release_decision,
701 now,
702 ) => {},
703 _ => break outcome,
704 }
705 }
706 }
707 };
708
709 let tx_time = if gcongestion_enabled {
710 initial_release_decision
711 .filter(|_| self.pacing_enabled(qconn))
712 .and_then(|v| v.time(now))
715 } else {
716 send_info
717 .filter(|_| self.pacing_enabled(qconn))
718 .map(|v| v.at)
719 };
720
721 self.write_state.conn_established = qconn.is_established();
722 self.write_state.tx_time = tx_time;
723 self.write_state.segment_size =
724 segment_size.unwrap_or(self.write_state.bytes_written);
725
726 if !gcongestion_enabled {
727 if let Some(time) = tx_time {
728 const DEFAULT_MAX_INTO_FUTURE: Duration =
729 Duration::from_millis(1);
730 if time
731 .checked_duration_since(now)
732 .map(|d| d > DEFAULT_MAX_INTO_FUTURE)
733 .unwrap_or(false)
734 {
735 self.write_state.next_release_time =
736 Some(now + DEFAULT_MAX_INTO_FUTURE.mul_f32(0.8));
737 self.write_state.has_pending_data = false;
738 return Ok(0);
739 }
740 }
741 }
742
743 buffer_write_outcome
744 }
745
746 fn select_path(
756 &mut self, qconn: &QuicheConnection,
757 ) -> Option<(SocketAddr, SocketAddr)> {
758 if self.write_state.selected_path.is_some() {
759 return self.write_state.selected_path;
760 }
761
762 let from = self.cfg.local_addr;
763
764 if self.write_state.pending_paths.len() == 0 {
766 self.write_state.pending_paths = qconn.paths_iter(from);
767 }
768
769 let to = self.write_state.pending_paths.next()?;
770
771 Some((from, to))
772 }
773
774 #[cfg(not(feature = "gcongestion"))]
775 fn pacing_enabled(&self, qconn: &QuicheConnection) -> bool {
776 self.cfg.pacing_offload && qconn.pacing_enabled()
777 }
778
779 #[cfg(feature = "gcongestion")]
780 fn pacing_enabled(&self, _qconn: &QuicheConnection) -> bool {
781 self.cfg.pacing_offload
782 }
783
784 fn write_packet_to_buffer(
785 &mut self, qconn: &mut QuicheConnection, send_buf: &mut [u8],
786 send_info: &mut Option<SendInfo>, segment_size: Option<usize>,
787 ) -> QuicResult<usize> {
788 let mut send_buf = &mut send_buf[self.write_state.bytes_written..];
789 if send_buf.len() > segment_size.unwrap_or(usize::MAX) {
790 send_buf = &mut send_buf[..segment_size.unwrap_or(usize::MAX)];
793 }
794
795 let (from, to) = self.select_path(qconn).unzip();
806
807 match qconn.send_on_path(send_buf, from, to) {
808 Ok((packet_size, info)) => {
809 let _ = send_info.get_or_insert(info);
810
811 self.write_state.bytes_written += packet_size;
812 self.write_state.num_pkts += 1;
813
814 let from = send_info.as_ref().map(|info| info.from);
815 let to = send_info.as_ref().map(|info| info.to);
816
817 self.write_state.selected_path = from.zip(to);
818
819 self.write_state.has_pending_data = true;
820
821 Ok(packet_size)
822 },
823
824 Err(QuicheError::Done) => {
825 let has_pending_paths = self.write_state.pending_paths.len() > 0;
831
832 self.write_state.has_pending_data = has_pending_paths;
834
835 Ok(0)
836 },
837
838 Err(e) => {
839 let error_code = if let Some(local_error) = qconn.local_error() {
840 local_error.error_code
841 } else {
842 let internal_error_code =
843 quiche::WireErrorCode::InternalError as u64;
844 let _ = qconn.close(false, internal_error_code, &[]);
845
846 internal_error_code
847 };
848
849 self.audit_log_stats
850 .set_sent_conn_close_transport_error_code(error_code as i64);
851
852 Err(Box::new(e))
853 },
854 }
855 }
856
857 async fn flush_buffer_to_socket(&mut self, send_buf: &[u8]) {
858 if self.write_state.bytes_written > 0 {
859 let current_send_buf = &send_buf[..self.write_state.bytes_written];
860
861 let (from, to) = self.write_state.selected_path.unzip();
862
863 let to = to.unwrap_or(self.cfg.peer_addr);
864 let from = from.filter(|_| self.cfg.with_pktinfo);
865
866 let dscp = self.dscp_handle.as_ref().and_then(DscpHandle::get);
867 let needs_dscp_cmsg =
869 cfg!(all(target_os = "linux", not(feature = "fuzzing"))) &&
870 dscp.is_some();
871
872 let send_res = if let (Some(udp_socket), true) = (
873 self.socket.as_udp_socket(),
874 self.cfg.with_gso || needs_dscp_cmsg,
875 ) {
876 let (segment_size, tx_time) = if self.cfg.with_gso {
878 (
879 Some(self.write_state.segment_size),
880 self.write_state.tx_time,
881 )
882 } else {
883 (None, None)
884 };
885 send_to(
886 udp_socket,
887 to,
888 from,
889 current_send_buf,
890 segment_size,
891 tx_time,
892 dscp,
893 self.metrics
894 .write_errors(labels::QuicWriteError::WouldBlock),
895 self.metrics.send_to_wouldblock_duration_s(),
896 )
897 .await
898 } else {
899 self.socket.send_to(current_send_buf, to).await
900 };
901
902 #[cfg(feature = "perf-quic-listener-metrics")]
903 self.measure_complete_handshake_time();
904
905 match send_res {
906 Ok(n) =>
907 if n < self.write_state.bytes_written {
908 self.metrics
909 .write_errors(labels::QuicWriteError::Partial)
910 .inc();
911 },
912
913 Err(_) => {
914 self.metrics.write_errors(labels::QuicWriteError::Err).inc();
915 },
916 }
917 }
918 }
919
920 fn handshake_deadline(&self, qconn: &QuicheConnection) -> Option<Instant> {
923 if qconn.is_established() {
924 return None;
925 }
926
927 self.handshake_info.deadline()
928 }
929
930 fn enforce_handshake_deadline(
933 &self, qconn: &mut QuicheConnection,
934 ) -> QuicResult<()> {
935 if !qconn.is_established() && self.handshake_info.is_expired() {
936 let err = quiche::WireErrorCode::ApplicationError as u64;
937 let _ = qconn.close(false, err, &[]);
938 return Err(HandshakeError::Timeout.into());
939 }
940
941 Ok(())
942 }
943
944 fn process_incoming(
946 &mut self, qconn: &mut QuicheConnection, mut pkt: Incoming,
947 ) -> QuicResult<()> {
948 self.enforce_handshake_deadline(qconn)?;
951
952 let recv_info = quiche::RecvInfo {
953 from: pkt.peer_addr,
954 to: pkt.local_addr,
955 };
956
957 if let Some(gro) = pkt.gro {
958 for dgram in pkt.buf.chunks_mut(gro as usize) {
959 qconn.recv(dgram, recv_info)?;
960 }
961 } else {
962 qconn.recv(&mut pkt.buf, recv_info)?;
963 }
964
965 Ok(())
966 }
967
968 async fn wait_for_data_or_handshake<A: ApplicationOverQuic>(
984 &mut self, qconn: &mut QuicheConnection, quic_application: &mut A,
985 ) -> QuicResult<WaitForDataOrHandshakeDirective> {
986 if quic_application.should_act() {
987 quic_application.wait_for_data(qconn).await?;
997 Ok(WaitForDataOrHandshakeDirective::Noop)
998 } else {
999 let send_buf = self.wait_for_quiche(qconn).await?;
1004 Ok(WaitForDataOrHandshakeDirective::Flush(send_buf))
1005 }
1006 }
1007
1008 async fn wait_for_quiche(
1029 &mut self, qconn: &mut QuicheConnection,
1030 ) -> QuicResult<TransientSendBuf> {
1031 let send_buf = std::future::poll_fn(|_| {
1032 let mut send_buf =
1036 TransientSendBuf::acquire(self.cfg.pool_send_buffer);
1037
1038 match self.gather_data_from_quiche_conn(
1039 qconn,
1040 send_buf.as_mut(),
1041 true,
1042 ) {
1043 Ok(bytes_written) => {
1044 if bytes_written == 0 && self.write_state.bytes_written == 0 {
1048 Poll::Pending
1049 } else {
1050 Poll::Ready(Ok(send_buf))
1051 }
1052 },
1053 _ => Poll::Ready(Err(quiche::Error::TlsFail)),
1054 }
1055 })
1056 .await?;
1057 Ok(send_buf)
1058 }
1059}
1060
1061#[must_use]
1067enum WaitForDataOrHandshakeDirective {
1068 Noop,
1069 Flush(TransientSendBuf),
1070}
1071
1072pub struct Running<Tx, M, A> {
1073 pub(crate) params: IoWorkerParams<Tx, M>,
1074 pub(crate) context: ConnectionStageContext<A>,
1075 pub(crate) qconn: Box<QuicheConnection>,
1077}
1078
1079impl<Tx, M, A> Running<Tx, M, A> {
1080 pub fn ssl(&mut self) -> &mut SslRef {
1081 (*self.qconn).as_mut()
1083 }
1084}
1085
1086pub(crate) struct Closing<Tx, M, A> {
1087 pub(crate) params: IoWorkerParams<Tx, M>,
1088 pub(crate) context: ConnectionStageContext<A>,
1089 pub(crate) work_loop_result: QuicResult<()>,
1090 pub(crate) qconn: Box<QuicheConnection>,
1092}
1093
1094pub enum RunningOrClosing<Tx, M, A> {
1095 Running(Running<Tx, M, A>),
1096 Closing(Closing<Tx, M, A>),
1097}
1098
1099impl<Tx, M> IoWorker<Tx, M, Handshake>
1100where
1101 Tx: DatagramSocketSend + Send,
1102 M: Metrics,
1103{
1104 pub(crate) async fn run<A>(
1105 mut self, mut qconn: Box<QuicheConnection>,
1106 mut ctx: ConnectionStageContext<A>,
1107 ) -> RunningOrClosing<Tx, M, A>
1108 where
1109 A: ApplicationOverQuic,
1110 {
1111 std::future::poll_fn(|cx| {
1115 let ssl = (*qconn).as_mut();
1117 ssl.set_task_waker(Some(cx.waker().clone()));
1118
1119 Poll::Ready(())
1120 })
1121 .await;
1122
1123 #[cfg(target_os = "linux")]
1124 if let Some(incoming) = ctx.in_pkt.as_mut() {
1125 self.audit_log_stats
1126 .set_initial_so_mark_data(incoming.so_mark_data.take());
1127 }
1128
1129 let mut work_loop_result = self.work_loop(&mut qconn, &mut ctx).await;
1130 notify_path_events(ctx.connection_hook.as_deref(), &mut qconn);
1131 if work_loop_result.is_ok() && qconn.is_closed() {
1132 work_loop_result = Err(HandshakeError::ConnectionClosed.into());
1133 }
1134
1135 if let Err(err) = &work_loop_result {
1136 self.metrics.failed_handshakes(err.into()).inc();
1137
1138 return RunningOrClosing::Closing(Closing {
1139 params: self.into(),
1140 context: ctx,
1141 work_loop_result,
1142 qconn,
1143 });
1144 };
1145
1146 let on_conn_established_result =
1147 self.on_conn_established(&mut qconn, &mut ctx);
1148 notify_path_events(ctx.connection_hook.as_deref(), &mut qconn);
1149
1150 match on_conn_established_result {
1151 Ok(()) => RunningOrClosing::Running(Running {
1152 params: self.into(),
1153 context: ctx,
1154 qconn,
1155 }),
1156 Err(e) => {
1157 foundations::telemetry::log::warn!(
1158 "Handshake stage on_connection_established failed"; "error"=>%e
1159 );
1160
1161 RunningOrClosing::Closing(Closing {
1162 params: self.into(),
1163 context: ctx,
1164 work_loop_result,
1165 qconn,
1166 })
1167 },
1168 }
1169 }
1170
1171 fn on_conn_established<A: ApplicationOverQuic>(
1172 &mut self, qconn: &mut QuicheConnection,
1173 ctx: &mut ConnectionStageContext<A>,
1174 ) -> QuicResult<()> {
1175 if self.audit_log_stats.transport_handshake_duration_us() == -1 {
1179 self.handshake_info.set_elapsed();
1180 let handshake_info = &self.handshake_info;
1181
1182 self.audit_log_stats
1183 .set_transport_handshake_duration(handshake_info.elapsed());
1184
1185 ctx.application.on_conn_established(qconn, handshake_info)?;
1186 }
1187
1188 if let Some(cid) = self.conn_stage.pending_cid.take() {
1189 ctx.incoming_pkt_receiver.unmap_cid(&cid);
1190 }
1191
1192 Ok(())
1193 }
1194}
1195
1196impl<Tx, M, S> From<IoWorker<Tx, M, S>> for IoWorkerParams<Tx, M> {
1197 fn from(value: IoWorker<Tx, M, S>) -> Self {
1198 Self {
1199 socket: value.socket,
1200 shutdown_tx: value.shutdown_tx,
1201 cfg: value.cfg,
1202 audit_log_stats: value.audit_log_stats,
1203 write_state: value.write_state,
1204 dscp_handle: value.dscp_handle,
1205 cid_generator: value.cid_generator,
1206 #[cfg(feature = "perf-quic-listener-metrics")]
1207 init_rx_time: value.init_rx_time,
1208 metrics: value.metrics,
1209 handshake_info: value.handshake_info,
1210 active_conn_guard: value.active_conn_guard,
1211 }
1212 }
1213}
1214
1215impl<Tx, M> IoWorker<Tx, M, RunningApplication>
1216where
1217 Tx: DatagramSocketSend + Send,
1218 M: Metrics,
1219{
1220 pub(crate) async fn run<A: ApplicationOverQuic>(
1221 mut self, mut qconn: Box<QuicheConnection>,
1222 mut ctx: ConnectionStageContext<A>,
1223 ) -> Closing<Tx, M, A> {
1224 let mut work_loop_result = self.enforce_handshake_deadline(&mut qconn);
1227
1228 if work_loop_result.is_ok() {
1229 work_loop_result =
1234 self.conn_stage.on_read(true, &mut qconn, &mut ctx);
1235 notify_path_events(ctx.connection_hook.as_deref(), &mut qconn);
1236 }
1237
1238 if work_loop_result.is_ok() {
1239 work_loop_result = self.work_loop(&mut qconn, &mut ctx).await;
1240 notify_path_events(ctx.connection_hook.as_deref(), &mut qconn);
1241 }
1242
1243 if !qconn.is_established() {
1247 let reason = match &work_loop_result {
1248 Err(err) => err.into(),
1249 Ok(()) => labels::HandshakeError::Disconnect,
1250 };
1251
1252 self.metrics.failed_handshakes(reason).inc();
1253 }
1254
1255 Closing {
1256 params: self.into(),
1257 context: ctx,
1258 work_loop_result,
1259 qconn,
1260 }
1261 }
1262}
1263
1264impl<Tx, M> IoWorker<Tx, M, Close>
1265where
1266 Tx: DatagramSocketSend + Send,
1267 M: Metrics,
1268{
1269 pub(crate) async fn close<A: ApplicationOverQuic>(
1270 mut self, qconn: &mut QuicheConnection,
1271 ctx: &mut ConnectionStageContext<A>,
1272 ) {
1273 if self.conn_stage.work_loop_result.is_ok() &&
1274 self.bw_estimator.max_bandwidth > 0
1275 {
1276 let metrics = &self.metrics;
1277
1278 metrics
1279 .max_bandwidth_mbps()
1280 .observe(self.bw_estimator.max_bandwidth as f64 * 1e-6);
1281
1282 metrics
1283 .max_loss_pct()
1284 .observe(self.bw_estimator.max_loss_pct as f64 * 100.);
1285 }
1286
1287 if ctx.application.should_act() {
1288 ctx.application.on_conn_close(
1289 qconn,
1290 &self.metrics,
1291 &self.conn_stage.work_loop_result,
1292 );
1293 notify_path_events(ctx.connection_hook.as_deref(), qconn);
1294 }
1295
1296 let mut send_buf = TransientSendBuf::acquire(self.cfg.pool_send_buffer);
1304 let _ =
1305 self.gather_data_from_quiche_conn(qconn, send_buf.as_mut(), false);
1306 self.flush_buffer_to_socket(send_buf.as_ref()).await;
1307
1308 *ctx.stats.lock().unwrap() = QuicConnectionStats::from_conn(qconn);
1309
1310 if let Some(err) = qconn.peer_error() {
1311 if err.is_app {
1312 self.audit_log_stats
1313 .set_recvd_conn_close_application_error_code(
1314 err.error_code as _,
1315 );
1316 } else {
1317 self.audit_log_stats
1318 .set_recvd_conn_close_transport_error_code(
1319 err.error_code as _,
1320 );
1321 }
1322 }
1323
1324 if let Some(err) = qconn.local_error() {
1325 if err.is_app {
1326 self.audit_log_stats
1327 .set_sent_conn_close_application_error_code(
1328 err.error_code as _,
1329 );
1330 } else {
1331 self.audit_log_stats
1332 .set_sent_conn_close_transport_error_code(
1333 err.error_code as _,
1334 );
1335 }
1336 }
1337
1338 self.close_connection(qconn, &mut ctx.incoming_pkt_receiver);
1339
1340 if let Err(work_loop_error) = self.conn_stage.work_loop_result {
1341 self.audit_log_stats
1342 .set_connection_close_reason(work_loop_error);
1343 }
1344 }
1345
1346 fn close_connection(
1347 &mut self, qconn: &mut QuicheConnection,
1348 incoming_pkt_receiver: &mut IncomingPacketReceiver,
1349 ) {
1350 while let Some(retired_cid) = qconn.retired_scid_next() {
1351 incoming_pkt_receiver.unmap_cid(&retired_cid);
1352 }
1353 for cid in qconn.source_ids() {
1354 incoming_pkt_receiver.unmap_cid(cid);
1355 }
1356 }
1357}
1358
1359fn min_of_some<T: Ord>(v1: Option<T>, v2: Option<T>) -> Option<T> {
1361 match (v1, v2) {
1362 (Some(a), Some(b)) => Some(a.min(b)),
1363 (Some(v), _) | (_, Some(v)) => Some(v),
1364 (None, None) => None,
1365 }
1366}
1367
1368struct TrackMidHandshakeFlush<M: Metrics> {
1371 complete: bool,
1372 metrics: M,
1373}
1374
1375impl<M: Metrics> TrackMidHandshakeFlush<M> {
1376 fn new(metrics: M) -> Self {
1377 Self {
1378 complete: false,
1379 metrics,
1380 }
1381 }
1382
1383 fn mark_complete(&mut self) {
1384 self.complete = true;
1385 }
1386}
1387
1388impl<M: Metrics> Drop for TrackMidHandshakeFlush<M> {
1389 fn drop(&mut self) {
1390 if !self.complete {
1391 self.metrics.skipped_mid_handshake_flush_count().inc();
1392 }
1393 }
1394}
1395
1396fn random_u128() -> u128 {
1397 let mut buf = [0; 16];
1398 boring::rand::rand_bytes(&mut buf).expect("boring's RAND_bytes never fails");
1399 u128::from_ne_bytes(buf)
1400}
1401
1402#[cfg(test)]
1403mod pooled_send_buf_tests {
1404 use super::*;
1405
1406 #[test]
1411 fn caps_retained_buffers() {
1412 std::thread::spawn(|| {
1413 let bufs: Vec<PooledSendBuf> = (0..SEND_BUF_POOL_CAP + 4)
1417 .map(|_| PooledSendBuf::acquire())
1418 .collect();
1419 drop(bufs);
1420
1421 let retained = SEND_BUF_POOL.with(|pool| pool.borrow().len());
1422 assert_eq!(retained, SEND_BUF_POOL_CAP);
1423 })
1424 .join()
1425 .unwrap();
1426 }
1427
1428 #[test]
1429 fn reuses_a_returned_buffer() {
1430 std::thread::spawn(|| {
1431 let first_ptr = {
1432 let buf = PooledSendBuf::acquire();
1433 assert_eq!(buf.len(), SEND_BUFFER_SIZE);
1434 buf.as_ptr()
1435 }; let reused = PooledSendBuf::acquire();
1438 assert_eq!(
1439 reused.as_ptr(),
1440 first_ptr,
1441 "acquire should hand back the pooled allocation"
1442 );
1443 })
1444 .join()
1445 .unwrap();
1446 }
1447
1448 #[test]
1449 fn returns_to_the_dropping_thread() {
1450 let buf = std::thread::spawn(PooledSendBuf::acquire).join().unwrap();
1454
1455 std::thread::spawn(move || {
1456 assert_eq!(SEND_BUF_POOL.with(|pool| pool.borrow().len()), 0);
1457 drop(buf);
1458 assert_eq!(SEND_BUF_POOL.with(|pool| pool.borrow().len()), 1);
1459 })
1460 .join()
1461 .unwrap();
1462 }
1463}