tokio_quiche/quic/raw.rs
1// Copyright (C) 2025, Cloudflare, Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright notice,
9// this list of conditions and the following disclaimer.
10//
11// * Redistributions in binary form must reproduce the above copyright
12// notice, this list of conditions and the following disclaimer in the
13// documentation and/or other materials provided with the distribution.
14//
15// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
27//! Helper to wrap existing [quiche::Connection]s.
28//!
29//! This is a low-level interface for users who either need to heavily customize
30//! the [`quiche::Connection`] beyond what is possible via the crate's
31//! [`settings`](crate::settings), or need more control over how to pass data
32//! into the connection.
33//!
34//! Most use cases are much better served by our
35//! [`connect`](crate::quic::connect) (for clients) or [`listen`](crate::listen)
36//! (for servers) API.
37
38use datagram_socket::DatagramSocketSend;
39use std::sync::Arc;
40use std::task::ready;
41use std::task::Context;
42use std::task::Poll;
43use std::time::Instant;
44use tokio::sync::mpsc;
45
46use super::connection::IncomingPacketReceiver;
47use super::connection::InitialQuicConnection;
48use super::connection::QuicConnectionParams;
49use super::io::worker::WriterConfig;
50use super::router::ConnectionMapCommand;
51use crate::metrics::Metrics;
52use crate::quic::HandshakeInfo;
53use crate::quic::Incoming;
54use crate::quic::QuicheConnection;
55use crate::socket::Socket;
56
57/// Result of manually wrapping a [`quiche::Connection`] in an
58/// [`InitialQuicConnection`].
59///
60/// This struct bundles the interfaces which interact with the connection.
61pub struct ConnWrapperResult<Tx, M>
62where
63 Tx: DatagramSocketSend + Send + 'static + ?Sized,
64 M: Metrics,
65{
66 /// The connection wrapper.
67 pub conn: InitialQuicConnection<Tx, M>,
68 /// Sender for inbound packets on the connection.
69 pub incoming_tx: mpsc::Sender<Incoming>,
70 /// Receiver for `connection closed` notifications. This fires
71 /// after a `CONNECTION_CLOSE` frame has been sent on the connection,
72 /// but before `worker_shutdown_rx`.
73 pub conn_close_rx: ConnCloseReceiver,
74 /// Receiver which fires only when its associated sender is dropped.
75 /// This happens when the connection's IO task exits.
76 pub worker_shutdown_rx: mpsc::Receiver<()>,
77}
78
79/// Wraps an existing [`quiche::Connection`] in an [`InitialQuicConnection`],
80/// bypassing the regular packet router workflow.
81///
82/// Connections wrapped in this way require the user to manually pass inbound
83/// packets via the channel returned in [`ConnWrapperResult`]. The passed
84/// `tx_socket` is only used to _send_ outbound packets and to extract the
85/// endpoint's addresses.
86///
87/// # Note
88/// This function does not attempt any I/O when wrapping the
89/// [`quiche::Connection`]. To start handshaking and consuming packets from the
90/// returned channel, use the methods on [`InitialQuicConnection`].
91pub fn wrap_quiche_conn<Tx, R, M>(
92 quiche_conn: QuicheConnection, tx_socket: Socket<Arc<Tx>, R>, metrics: M,
93) -> ConnWrapperResult<Tx, M>
94where
95 Tx: DatagramSocketSend + Send + 'static + ?Sized,
96 M: Metrics,
97{
98 let Socket {
99 send: socket,
100 local_addr,
101 peer_addr,
102 ..
103 } = tx_socket;
104 let (shutdown_tx, worker_shutdown_rx) = mpsc::channel(1);
105 let (conn_map_cmd_tx, conn_map_rx) = mpsc::unbounded_channel();
106 let (incoming_tx, incoming_pkt_receiver) =
107 IncomingPacketReceiver::new(&quiche_conn.source_id(), conn_map_cmd_tx);
108
109 let writer_cfg = WriterConfig {
110 peer_addr,
111 local_addr,
112 // TODO: try to read Tx' SocketCaps. false is always a safe default.
113 with_gso: false,
114 pacing_offload: false,
115 with_pktinfo: false,
116 // Match the default `QuicSettings::pool_send_buffer` (pooling on).
117 pool_send_buffer: true,
118 };
119
120 let conn_params = QuicConnectionParams {
121 writer_cfg,
122 pending_cid: None, // only used for unmapping in IPR
123 original_dcid: None,
124 initial_pkt: None,
125 dscp_handle: None,
126 shutdown_tx,
127 incoming_pkt_receiver,
128 cid_generator: None,
129 metrics,
130 connection_hook: None,
131 #[cfg(feature = "perf-quic-listener-metrics")]
132 init_rx_time: None,
133 handshake_info: HandshakeInfo::new(Instant::now(), None),
134 quiche_conn: Box::new(quiche_conn),
135 socket,
136 };
137
138 let conn = InitialQuicConnection::new(conn_params);
139
140 ConnWrapperResult {
141 conn,
142 incoming_tx,
143 conn_close_rx: ConnCloseReceiver(conn_map_rx),
144 worker_shutdown_rx,
145 }
146}
147
148/// Pollable receiver for `connection closed` notifications from a QUIC
149/// connection.
150///
151/// This receiver also fires if the corresponding sender has been dropped
152/// without a `CONNECTION_CLOSE` frame on the connection.
153pub struct ConnCloseReceiver(mpsc::UnboundedReceiver<ConnectionMapCommand>);
154
155impl ConnCloseReceiver {
156 /// Polls to receive a `connection closed` notification.
157 pub fn poll_recv(&mut self, cx: &mut Context) -> Poll<()> {
158 loop {
159 let cmd = ready!(self.0.poll_recv(cx));
160 if matches!(cmd, None | Some(ConnectionMapCommand::UnmapCid(_))) {
161 // Raw connections have neither a `pending_cid` nor a
162 // `cid_generator`. The only time they unmap a CID is when the
163 // connection is closed.
164 return Poll::Ready(());
165 }
166 }
167 }
168
169 /// Waits for a `connection closed` notification.
170 pub async fn recv(&mut self) {
171 std::future::poll_fn(|cx| self.poll_recv(cx)).await
172 }
173}