1mod priority;
4mod request_stream;
5pub mod web_transport;
6use crate::{
7 ArcHandler, ArcedQuicEndpoint, BoxedBidiStream, QuicConnection, QuicTransportReceive,
8 QuicTransportSend, RuntimeTrait, unmap_ipv4,
9};
10use priority::{PrioritizedStream, PriorityRegistry, transport_priority};
11use request_stream::RequestStream;
12use std::{any::Any, sync::Arc};
13use trillium::{Handler, KnownHeaderName, Listener, Transport, Upgrade};
14use trillium_http::{
15 HttpContext,
16 h3::{H3Connection, H3Error, H3ErrorCode, H3StreamResult, UniStreamResult},
17};
18use web_transport::{WebTransportDispatcher, WebTransportStream};
19
20#[derive(Clone, Copy, Debug)]
22pub struct StreamId(u64);
23impl From<StreamId> for u64 {
24 fn from(val: StreamId) -> Self {
25 val.0
26 }
27}
28
29impl From<u64> for StreamId {
30 fn from(value: u64) -> Self {
31 Self(value)
32 }
33}
34
35pub(crate) async fn run_h3(
36 quic_binding: ArcedQuicEndpoint,
37 context: Arc<HttpContext>,
38 handler: ArcHandler<impl Handler>,
39 runtime: impl RuntimeTrait,
40 listener: Option<Listener>,
41 local_alt_svc: Option<&'static str>,
42) {
43 let swansong = context.swansong();
44 while let Some(connection) = swansong.interrupt(quic_binding.accept()).await.flatten() {
45 let h3 = H3Connection::new(context.clone());
46 let handler = handler.clone();
47 let runtime = runtime.clone();
48 runtime.clone().spawn_detached(run_h3_connection(
49 connection,
50 h3,
51 handler,
52 runtime,
53 listener.as_ref().map(Listener::unshared_clone),
54 local_alt_svc,
55 ));
56 }
57}
58
59async fn run_h3_connection(
60 connection: QuicConnection,
61 h3: Arc<H3Connection>,
62 handler: ArcHandler<impl Handler>,
63 runtime: impl RuntimeTrait,
64 listener: Option<Listener>,
65 local_alt_svc: Option<&'static str>,
66) {
67 let wt_dispatcher = h3
68 .context()
69 .config()
70 .webtransport_enabled()
71 .then(WebTransportDispatcher::new);
72
73 log::trace!("new quic connection from {}", connection.remote_address());
74
75 let priorities = PriorityRegistry::default();
76 h3.register_priority_callback({
77 let priorities = priorities.clone();
78 move |stream_id, priority, is_update| {
79 priorities.apply(stream_id, transport_priority(priority), is_update)
80 }
81 });
82
83 spawn_outbound_control_stream(&connection, &h3, &runtime);
84 spawn_qpack_encoder_stream(&connection, &h3, &runtime);
85 spawn_qpack_decoder_stream(&connection, &h3, &runtime);
86 spawn_inbound_uni_streams(&connection, &h3, &runtime, &wt_dispatcher);
87 handle_inbound_bidi_streams(
91 connection,
92 h3.clone(),
93 ArcHandler::new(handler),
94 runtime,
95 wt_dispatcher,
96 listener,
97 local_alt_svc,
98 priorities,
99 )
100 .await;
101}
102
103#[allow(clippy::too_many_arguments)]
104async fn handle_inbound_bidi_streams(
105 connection: QuicConnection,
106 h3: Arc<H3Connection>,
107 handler: ArcHandler<impl Handler>,
108 runtime: impl RuntimeTrait,
109 wt_dispatcher: Option<WebTransportDispatcher>,
110 listener: Option<Listener>,
111 local_alt_svc: Option<&'static str>,
112 priorities: PriorityRegistry,
113) {
114 loop {
115 match h3.swansong().interrupt(connection.accept_bidi()).await {
116 None => {
117 log::trace!("H3 bidi accept loop: interrupted by swansong shutdown");
118 break;
119 }
120 Some(Err(e)) => {
121 log::debug!("H3 bidi accept loop: accept_bidi error: {e}");
122 break;
123 }
124 Some(Ok((stream_id, transport))) => {
125 handle_bidi_stream(
126 stream_id,
127 transport,
128 &h3,
129 &handler,
130 &connection,
131 &runtime,
132 &wt_dispatcher,
133 listener.clone(),
134 local_alt_svc,
135 &priorities,
136 );
137 }
138 }
139 }
140
141 h3.shut_down();
142}
143
144#[allow(clippy::too_many_arguments)]
145fn handle_bidi_stream(
146 stream_id: u64,
147 transport: BoxedBidiStream,
148 h3: &Arc<H3Connection>,
149 handler: &ArcHandler<impl Handler>,
150 connection: &QuicConnection,
151 runtime: &impl RuntimeTrait,
152 wt_dispatcher: &Option<WebTransportDispatcher>,
153 listener: Option<Listener>,
154 local_alt_svc: Option<&'static str>,
155 priorities: &PriorityRegistry,
156) {
157 log::trace!("H3 bidi stream {stream_id}: spawning handler task");
158 let (h3, handler, connection, wt_dispatcher, priorities) = (
159 h3.clone(),
160 handler.clone(),
161 connection.clone(),
162 wt_dispatcher.clone(),
163 priorities.clone(),
164 );
165
166 let slot = priorities.register(stream_id);
170
171 let peer_gone = transport.stopped();
174
175 let transport: Box<dyn Transport> = Box::new(RequestStream::new(PrioritizedStream::new(
179 transport, slot, stream_id,
180 )));
181
182 runtime.spawn_detached(async move {
183 let peer_ip = unmap_ipv4(connection.remote_address().ip());
187 let quic_connection = connection.clone();
188 let wt_dispatcher = wt_dispatcher.clone();
189
190 let handler_fn = {
191 let handler = handler.clone();
192 let wt_dispatcher = wt_dispatcher.clone();
193 move |mut conn: trillium_http::Conn<_>| async move {
194 conn.set_peer_ip(Some(peer_ip));
195 conn.set_secure(true);
196
197 let state = conn.state_mut();
198 state.insert(quic_connection);
199 state.insert(StreamId(stream_id));
200 if let Some(listener) = listener {
201 if let Some(addr) = listener.socket_addr() {
202 state.insert(addr);
203 }
204 state.insert(listener);
205 }
206 if let Some(dispatcher) = wt_dispatcher {
207 state.insert(dispatcher);
208 }
209 if let Some(alt_svc) = local_alt_svc {
210 conn.response_headers_mut()
211 .try_insert(KnownHeaderName::AltSvc, alt_svc);
212 }
213
214 let conn = handler.run(conn.into()).await;
215 let conn = handler.before_send(conn).await;
216
217 conn.into_inner()
218 }
219 };
220
221 let result = h3
222 .clone()
223 .process_inbound_bidi(transport, handler_fn, stream_id)
224 .with_reset(|transport, code| {
225 if let Some(stream) = request_stream(transport) {
230 let raw = u64::from(code);
231 stream.stop(raw);
232 stream.reset(raw);
233 }
234 });
235
236 let result = match peer_gone {
237 Some(peer_gone) => result.with_peer_gone(peer_gone).await,
238 None => result.await,
239 };
240
241 match result {
242 Ok(H3StreamResult::Request(conn)) if conn.should_upgrade() => {
243 let mut upgrade = Upgrade::from(conn);
244 if handler.has_upgrade(&upgrade) {
245 log::debug!("upgrading h3 stream");
246 if let Some(stream) = RequestStream::from_transport(upgrade.transport_mut().1) {
247 stream.hand_off();
248 }
249 handler.upgrade(upgrade).await;
250 } else {
251 log::error!("h3 upgrade specified but no upgrade handler provided");
252 }
253 }
254
255 Ok(H3StreamResult::Request(_)) => {}
256
257 Ok(H3StreamResult::WebTransport {
258 session_id,
259 transport,
260 buffer,
261 }) => {
262 if let Some(mut stream) = into_request_stream(transport) {
263 if let Some(dispatcher) = &wt_dispatcher {
264 stream.hand_off();
265 dispatcher.dispatch(WebTransportStream::Bidi {
266 session_id,
267 stream,
268 buffer: buffer.into(),
269 });
270 } else {
271 stream.stop(H3ErrorCode::StreamCreationError.into());
272 stream.reset(H3ErrorCode::StreamCreationError.into());
273 }
274 }
275 }
276
277 Err(error) => {
278 log::debug!("H3 bidi stream {stream_id}: error: {error}");
279 handle_h3_error(error, &connection, &h3);
280 }
281 }
282
283 priorities.deregister(stream_id);
284 });
285}
286
287fn request_stream(transport: &mut Box<dyn Transport>) -> Option<&mut RequestStream> {
288 RequestStream::from_transport(&mut **transport)
289}
290
291fn into_request_stream(transport: Box<dyn Transport>) -> Option<Box<RequestStream>> {
292 (transport as Box<dyn Any>).downcast().ok()
293}
294
295fn spawn_inbound_uni_streams(
296 connection: &QuicConnection,
297 h3: &Arc<H3Connection>,
298 runtime: &impl RuntimeTrait,
299 wt_dispatcher: &Option<WebTransportDispatcher>,
300) {
301 let (connection, h3, runtime, wt_dispatcher) = (
302 connection.clone(),
303 h3.clone(),
304 runtime.clone(),
305 wt_dispatcher.clone(),
306 );
307 runtime.clone().spawn_detached(async move {
308 while let Some(Ok((_stream_id, recv))) =
309 h3.swansong().interrupt(connection.accept_uni()).await
310 {
311 let (connection, h3, wt_dispatcher) =
312 (connection.clone(), h3.clone(), wt_dispatcher.clone());
313
314 runtime.spawn_detached(async move {
315 let close_connection = {
323 let connection = connection.clone();
324 let h3 = h3.clone();
325 move |code: H3ErrorCode| {
326 connection.close(code.into(), code.reason().as_bytes());
327 h3.shut_down();
328 }
329 };
330 let result = h3
331 .process_inbound_uni_with_close(recv, close_connection)
332 .await;
333
334 match result {
335 Ok(UniStreamResult::Handled) => {}
336 Ok(UniStreamResult::WebTransport {
337 session_id,
338 mut stream,
339 buffer,
340 }) => {
341 if let Some(dispatcher) = &wt_dispatcher {
342 dispatcher.dispatch(WebTransportStream::Uni {
343 session_id,
344 stream: Box::new(stream),
345 buffer: buffer.into(),
346 });
347 } else {
348 stream.stop(H3ErrorCode::StreamCreationError.into());
349 }
350 }
351
352 Ok(UniStreamResult::Unknown { mut stream, .. }) => {
353 stream.stop(H3ErrorCode::StreamCreationError.into());
354 }
355
356 Err(error) => {
357 handle_h3_error(error, &connection, &h3);
361 }
362 }
363 });
364 }
365
366 h3.shut_down();
367 });
368}
369
370fn spawn_qpack_decoder_stream(
371 connection: &QuicConnection,
372 h3: &Arc<H3Connection>,
373 runtime: &impl RuntimeTrait,
374) {
375 let (connection, h3) = (connection.clone(), h3.clone());
376
377 runtime.spawn_detached(async move {
378 log::trace!("H3: opening outbound QPACK decoder stream");
379 let stream = match connection.open_uni().await {
380 Ok((_stream_id, stream)) => stream,
381 Err(err) => {
382 log::error!("H3: open_uni for QPACK decoder stream failed: {err:?}");
383 h3.shut_down();
384 return;
385 }
386 };
387
388 let result = h3.run_decoder(stream).await;
389
390 if let Err(error) = result {
391 handle_h3_error(error, &connection, &h3);
392 }
393 });
395}
396
397fn spawn_qpack_encoder_stream(
398 connection: &QuicConnection,
399 h3: &Arc<H3Connection>,
400 runtime: &impl RuntimeTrait,
401) {
402 let (connection, h3) = (connection.clone(), h3.clone());
403 runtime.spawn_detached(async move {
404 log::trace!("H3: opening outbound QPACK encoder stream");
405 let stream = match connection.open_uni().await {
406 Ok((_stream_id, stream)) => stream,
407 Err(err) => {
408 log::error!("H3: open_uni for QPACK encoder stream failed: {err:?}");
409 h3.shut_down();
410 return;
411 }
412 };
413
414 let result = h3.run_encoder(stream).await;
415
416 if let Err(error) = result {
417 handle_h3_error(error, &connection, &h3);
418 }
419 });
421}
422
423fn spawn_outbound_control_stream(
424 connection: &QuicConnection,
425 h3: &Arc<H3Connection>,
426 runtime: &impl RuntimeTrait,
427) {
428 let (connection, h3) = (connection.clone(), h3.clone());
429 runtime.spawn_detached(async move {
430 log::trace!("H3: opening outbound control stream");
431 let stream = match connection.open_uni().await {
432 Ok((_stream_id, stream)) => stream,
433 Err(err) => {
434 log::error!("H3: open_uni for outbound control stream failed: {err:?}");
435 h3.shut_down();
436 return;
437 }
438 };
439
440 let result = h3.run_outbound_control(stream).await;
441
442 if let Err(error) = result {
443 handle_h3_error(error, &connection, &h3);
444 }
445 });
447}
448
449fn handle_h3_error(error: H3Error, connection: &QuicConnection, h3: &H3Connection) {
450 log::debug!("H3 error: {error}");
451 if let H3Error::Protocol(code) = error
452 && code.is_connection_error()
453 {
454 connection.close(code.into(), code.reason().as_bytes());
455 h3.shut_down();
456 }
457}
458
459#[cfg(test)]
460mod tests {
461 use super::{
462 RequestStream, into_request_stream,
463 priority::{PrioritizedStream, PriorityRegistry},
464 request_stream,
465 };
466 use crate::{BoxedBidiStream, QuicTransportBidi, QuicTransportReceive, QuicTransportSend};
467 use futures_lite::{AsyncRead, AsyncWrite};
468 use std::{
469 io,
470 pin::Pin,
471 sync::{Arc, Mutex},
472 task::{Context, Poll},
473 };
474 use trillium::Transport;
475
476 struct RecordingBidi(Arc<Mutex<Vec<String>>>);
478
479 impl AsyncRead for RecordingBidi {
480 fn poll_read(
481 self: Pin<&mut Self>,
482 _: &mut Context<'_>,
483 _: &mut [u8],
484 ) -> Poll<io::Result<usize>> {
485 Poll::Ready(Ok(0))
486 }
487 }
488
489 impl AsyncWrite for RecordingBidi {
490 fn poll_write(
491 self: Pin<&mut Self>,
492 _: &mut Context<'_>,
493 buf: &[u8],
494 ) -> Poll<io::Result<usize>> {
495 Poll::Ready(Ok(buf.len()))
496 }
497
498 fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
499 Poll::Ready(Ok(()))
500 }
501
502 fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
503 Poll::Ready(Ok(()))
504 }
505 }
506
507 impl QuicTransportReceive for RecordingBidi {
508 fn stop(&mut self, code: u64) {
509 self.0.lock().unwrap().push(format!("stop {code}"));
510 }
511 }
512
513 impl QuicTransportSend for RecordingBidi {
514 fn reset(&mut self, code: u64) {
515 self.0.lock().unwrap().push(format!("reset {code}"));
516 }
517 }
518
519 impl Transport for RecordingBidi {}
520 impl QuicTransportBidi for RecordingBidi {}
521
522 #[test]
523 fn a_request_stream_is_recoverable_from_its_erased_transport() {
524 let signals = Arc::new(Mutex::new(Vec::new()));
525 let registry = PriorityRegistry::default();
526 let quic_stream: BoxedBidiStream = Box::new(RecordingBidi(Arc::clone(&signals)));
527 let mut transport: Box<dyn Transport> = Box::new(RequestStream::new(
528 PrioritizedStream::new(quic_stream, registry.register(0), 0),
529 ));
530
531 let stream = request_stream(&mut transport).expect("erased as a RequestStream");
532 stream.stop(1);
533 stream.reset(2);
534 assert_eq!(*signals.lock().unwrap(), ["stop 1", "reset 2"]);
535
536 assert!(into_request_stream(transport).is_some());
537 }
538}