1mod priority;
4pub mod web_transport;
5use crate::{
6 ArcHandler, ArcedQuicEndpoint, BoxedBidiStream, QuicConnection, QuicTransportReceive,
7 QuicTransportSend, RuntimeTrait, unmap_ipv4,
8};
9use priority::{PrioritizedStream, PriorityRegistry, transport_priority};
10use std::sync::Arc;
11use trillium::{Handler, KnownHeaderName, Listener, Upgrade};
12use trillium_http::{
13 HttpContext,
14 h3::{H3Connection, H3Error, H3ErrorCode, H3StreamResult, UniStreamResult},
15};
16use web_transport::{WebTransportDispatcher, WebTransportStream};
17
18#[derive(Clone, Copy, Debug)]
20pub struct StreamId(u64);
21impl From<StreamId> for u64 {
22 fn from(val: StreamId) -> Self {
23 val.0
24 }
25}
26
27impl From<u64> for StreamId {
28 fn from(value: u64) -> Self {
29 Self(value)
30 }
31}
32
33pub(crate) async fn run_h3(
34 quic_binding: ArcedQuicEndpoint,
35 context: Arc<HttpContext>,
36 handler: ArcHandler<impl Handler>,
37 runtime: impl RuntimeTrait,
38 listener: Option<Listener>,
39 local_alt_svc: Option<&'static str>,
40) {
41 let swansong = context.swansong();
42 while let Some(connection) = swansong.interrupt(quic_binding.accept()).await.flatten() {
43 let h3 = H3Connection::new(context.clone());
44 let handler = handler.clone();
45 let runtime = runtime.clone();
46 runtime.clone().spawn(run_h3_connection(
47 connection,
48 h3,
49 handler,
50 runtime,
51 listener.clone(),
52 local_alt_svc,
53 ));
54 }
55}
56
57async fn run_h3_connection(
58 connection: QuicConnection,
59 h3: Arc<H3Connection>,
60 handler: ArcHandler<impl Handler>,
61 runtime: impl RuntimeTrait,
62 listener: Option<Listener>,
63 local_alt_svc: Option<&'static str>,
64) {
65 let wt_dispatcher = h3
66 .context()
67 .config()
68 .webtransport_enabled()
69 .then(WebTransportDispatcher::new);
70
71 log::trace!("new quic connection from {}", connection.remote_address());
72
73 let priorities = PriorityRegistry::default();
74 h3.register_priority_callback({
75 let priorities = priorities.clone();
76 move |stream_id, priority, is_update| {
77 priorities.apply(stream_id, transport_priority(priority), is_update)
78 }
79 });
80
81 spawn_outbound_control_stream(&connection, &h3, &runtime);
82 spawn_qpack_encoder_stream(&connection, &h3, &runtime);
83 spawn_qpack_decoder_stream(&connection, &h3, &runtime);
84 spawn_inbound_uni_streams(&connection, &h3, &runtime, &wt_dispatcher);
85 handle_inbound_bidi_streams(
86 connection,
87 h3.clone(),
88 handler,
89 runtime,
90 wt_dispatcher,
91 listener,
92 local_alt_svc,
93 priorities,
94 )
95 .await;
96}
97
98#[allow(clippy::too_many_arguments)]
99async fn handle_inbound_bidi_streams(
100 connection: QuicConnection,
101 h3: Arc<H3Connection>,
102 handler: ArcHandler<impl Handler>,
103 runtime: impl RuntimeTrait,
104 wt_dispatcher: Option<WebTransportDispatcher>,
105 listener: Option<Listener>,
106 local_alt_svc: Option<&'static str>,
107 priorities: PriorityRegistry,
108) {
109 loop {
110 match h3.swansong().interrupt(connection.accept_bidi()).await {
111 None => {
112 log::trace!("H3 bidi accept loop: interrupted by swansong shutdown");
113 break;
114 }
115 Some(Err(e)) => {
116 log::debug!("H3 bidi accept loop: accept_bidi error: {e}");
117 break;
118 }
119 Some(Ok((stream_id, transport))) => {
120 handle_bidi_stream(
121 stream_id,
122 transport,
123 &h3,
124 &handler,
125 &connection,
126 &runtime,
127 &wt_dispatcher,
128 listener.clone(),
129 local_alt_svc,
130 &priorities,
131 );
132 }
133 }
134 }
135
136 h3.shut_down();
137}
138
139#[allow(clippy::too_many_arguments)]
140fn handle_bidi_stream(
141 stream_id: u64,
142 transport: BoxedBidiStream,
143 h3: &Arc<H3Connection>,
144 handler: &ArcHandler<impl Handler>,
145 connection: &QuicConnection,
146 runtime: &impl RuntimeTrait,
147 wt_dispatcher: &Option<WebTransportDispatcher>,
148 listener: Option<Listener>,
149 local_alt_svc: Option<&'static str>,
150 priorities: &PriorityRegistry,
151) {
152 log::trace!("H3 bidi stream {stream_id}: spawning handler task");
153 let (h3, handler, connection, wt_dispatcher, priorities) = (
154 h3.clone(),
155 handler.clone(),
156 connection.clone(),
157 wt_dispatcher.clone(),
158 priorities.clone(),
159 );
160
161 let slot = priorities.register(stream_id);
165 let transport: BoxedBidiStream = Box::new(PrioritizedStream::new(transport, slot, stream_id));
166
167 runtime.spawn(async move {
168 let peer_ip = unmap_ipv4(connection.remote_address().ip());
172 let quic_connection = connection.clone();
173 let wt_dispatcher = wt_dispatcher.clone();
174
175 let handler_fn = {
176 let handler = handler.clone();
177 let wt_dispatcher = wt_dispatcher.clone();
178 move |mut conn: trillium_http::Conn<_>| async move {
179 conn.set_peer_ip(Some(peer_ip));
180 conn.set_secure(true);
181
182 let state = conn.state_mut();
183 state.insert(quic_connection);
184 state.insert(StreamId(stream_id));
185 if let Some(listener) = listener {
186 if let Some(addr) = listener.socket_addr() {
187 state.insert(addr);
188 }
189 state.insert(listener);
190 }
191 if let Some(dispatcher) = wt_dispatcher {
192 state.insert(dispatcher);
193 }
194 if let Some(alt_svc) = local_alt_svc {
195 conn.response_headers_mut()
196 .try_insert(KnownHeaderName::AltSvc, alt_svc);
197 }
198
199 let conn = handler.run(conn.into()).await;
200 let conn = handler.before_send(conn).await;
201
202 conn.into_inner()
203 }
204 };
205
206 let result = h3
207 .clone()
208 .process_inbound_bidi(transport, handler_fn, stream_id)
209 .with_reset(|t, code| {
210 let raw = u64::from(code);
215 t.stop(raw);
216 t.reset(raw);
217 })
218 .await;
219
220 match result {
221 Ok(H3StreamResult::Request(conn)) if conn.should_upgrade() => {
222 let upgrade = Upgrade::from(conn);
223 if handler.has_upgrade(&upgrade) {
224 log::debug!("upgrading h3 stream");
225 handler.upgrade(upgrade).await;
226 } else {
227 log::error!("h3 upgrade specified but no upgrade handler provided");
228 }
229 }
230
231 Ok(H3StreamResult::Request(_)) => {}
232
233 Ok(H3StreamResult::WebTransport {
234 session_id,
235 mut transport,
236 buffer,
237 }) => {
238 if let Some(dispatcher) = &wt_dispatcher {
239 dispatcher.dispatch(WebTransportStream::Bidi {
240 session_id,
241 stream: Box::new(transport),
242 buffer: buffer.into(),
243 });
244 } else {
245 transport.stop(H3ErrorCode::StreamCreationError.into());
246 transport.reset(H3ErrorCode::StreamCreationError.into());
247 }
248 }
249
250 Err(error) => {
251 log::debug!("H3 bidi stream {stream_id}: error: {error}");
252 handle_h3_error(error, &connection, &h3);
253 }
254 }
255
256 priorities.deregister(stream_id);
257 });
258}
259
260fn spawn_inbound_uni_streams(
261 connection: &QuicConnection,
262 h3: &Arc<H3Connection>,
263 runtime: &impl RuntimeTrait,
264 wt_dispatcher: &Option<WebTransportDispatcher>,
265) {
266 let (connection, h3, runtime, wt_dispatcher) = (
267 connection.clone(),
268 h3.clone(),
269 runtime.clone(),
270 wt_dispatcher.clone(),
271 );
272 runtime.clone().spawn(async move {
273 while let Some(Ok((_stream_id, recv))) =
274 h3.swansong().interrupt(connection.accept_uni()).await
275 {
276 let (connection, h3, wt_dispatcher) =
277 (connection.clone(), h3.clone(), wt_dispatcher.clone());
278
279 runtime.spawn(async move {
280 let close_connection = {
288 let connection = connection.clone();
289 let h3 = h3.clone();
290 move |code: H3ErrorCode| {
291 connection.close(code.into(), code.reason().as_bytes());
292 h3.shut_down();
293 }
294 };
295 let result = h3
296 .process_inbound_uni_with_close(recv, close_connection)
297 .await;
298
299 match result {
300 Ok(UniStreamResult::Handled) => {}
301 Ok(UniStreamResult::WebTransport {
302 session_id,
303 mut stream,
304 buffer,
305 }) => {
306 if let Some(dispatcher) = &wt_dispatcher {
307 dispatcher.dispatch(WebTransportStream::Uni {
308 session_id,
309 stream: Box::new(stream),
310 buffer: buffer.into(),
311 });
312 } else {
313 stream.stop(H3ErrorCode::StreamCreationError.into());
314 }
315 }
316
317 Ok(UniStreamResult::Unknown { mut stream, .. }) => {
318 stream.stop(H3ErrorCode::StreamCreationError.into());
319 }
320
321 Err(error) => {
322 handle_h3_error(error, &connection, &h3);
326 }
327 }
328 });
329 }
330
331 h3.shut_down();
332 });
333}
334
335fn spawn_qpack_decoder_stream(
336 connection: &QuicConnection,
337 h3: &Arc<H3Connection>,
338 runtime: &impl RuntimeTrait,
339) {
340 let (connection, h3) = (connection.clone(), h3.clone());
341
342 runtime.spawn(async move {
343 log::trace!("H3: opening outbound QPACK decoder stream");
344 let stream = match connection.open_uni().await {
345 Ok((_stream_id, stream)) => stream,
346 Err(err) => {
347 log::error!("H3: open_uni for QPACK decoder stream failed: {err:?}");
348 h3.shut_down();
349 return;
350 }
351 };
352
353 let result = h3.run_decoder(stream).await;
354
355 if let Err(error) = result {
356 handle_h3_error(error, &connection, &h3);
357 }
358 });
360}
361
362fn spawn_qpack_encoder_stream(
363 connection: &QuicConnection,
364 h3: &Arc<H3Connection>,
365 runtime: &impl RuntimeTrait,
366) {
367 let (connection, h3) = (connection.clone(), h3.clone());
368 runtime.spawn(async move {
369 log::trace!("H3: opening outbound QPACK encoder stream");
370 let stream = match connection.open_uni().await {
371 Ok((_stream_id, stream)) => stream,
372 Err(err) => {
373 log::error!("H3: open_uni for QPACK encoder stream failed: {err:?}");
374 h3.shut_down();
375 return;
376 }
377 };
378
379 let result = h3.run_encoder(stream).await;
380
381 if let Err(error) = result {
382 handle_h3_error(error, &connection, &h3);
383 }
384 });
386}
387
388fn spawn_outbound_control_stream(
389 connection: &QuicConnection,
390 h3: &Arc<H3Connection>,
391 runtime: &impl RuntimeTrait,
392) {
393 let (connection, h3) = (connection.clone(), h3.clone());
394 runtime.spawn(async move {
395 log::trace!("H3: opening outbound control stream");
396 let stream = match connection.open_uni().await {
397 Ok((_stream_id, stream)) => stream,
398 Err(err) => {
399 log::error!("H3: open_uni for outbound control stream failed: {err:?}");
400 h3.shut_down();
401 return;
402 }
403 };
404
405 let result = h3.run_outbound_control(stream).await;
406
407 if let Err(error) = result {
408 handle_h3_error(error, &connection, &h3);
409 }
410 });
412}
413
414fn handle_h3_error(error: H3Error, connection: &QuicConnection, h3: &H3Connection) {
415 log::debug!("H3 error: {error}");
416 if let H3Error::Protocol(code) = error
417 && code.is_connection_error()
418 {
419 connection.close(code.into(), code.reason().as_bytes());
420 h3.shut_down();
421 }
422}