Skip to main content

h3_quinn/
lib.rs

1//! QUIC Transport implementation with Quinn
2//!
3//! This module implements QUIC traits with Quinn.
4#![deny(missing_docs)]
5
6use std::{
7    convert::TryInto,
8    future::Future,
9    pin::Pin,
10    sync::Arc,
11    task::{self, ready, Poll},
12};
13
14use bytes::{Buf, Bytes};
15
16use futures_util::{
17    stream::{self},
18    Stream, StreamExt,
19};
20
21use quinn::ReadError;
22pub use quinn::{self, AcceptBi, AcceptUni, Endpoint, OpenBi, OpenUni, VarInt};
23
24use h3::{
25    error::Code,
26    quic::{self, ConnectionErrorIncoming, StreamErrorIncoming, StreamId, WriteBuf},
27};
28
29#[cfg(feature = "tracing")]
30use tracing::instrument;
31
32#[cfg(feature = "datagram")]
33pub mod datagram;
34
35/// BoxStream with Sync trait
36type BoxStreamSync<'a, T> = Pin<Box<dyn Stream<Item = T> + Sync + Send + 'a>>;
37
38/// A QUIC connection backed by Quinn
39///
40/// Implements a [`quic::Connection`] backed by a [`quinn::Connection`].
41pub struct Connection {
42    conn: quinn::Connection,
43    incoming_bi: BoxStreamSync<'static, <AcceptBi<'static> as Future>::Output>,
44    opening_bi: Option<BoxStreamSync<'static, <OpenBi<'static> as Future>::Output>>,
45    incoming_uni: BoxStreamSync<'static, <AcceptUni<'static> as Future>::Output>,
46    opening_uni: Option<BoxStreamSync<'static, <OpenUni<'static> as Future>::Output>>,
47}
48
49impl Connection {
50    /// Create a [`Connection`] from a [`quinn::Connection`]
51    pub fn new(conn: quinn::Connection) -> Self {
52        Self {
53            conn: conn.clone(),
54            incoming_bi: Box::pin(stream::unfold(conn.clone(), |conn| async {
55                Some((conn.accept_bi().await, conn))
56            })),
57            opening_bi: None,
58            incoming_uni: Box::pin(stream::unfold(conn.clone(), |conn| async {
59                Some((conn.accept_uni().await, conn))
60            })),
61            opening_uni: None,
62        }
63    }
64}
65
66impl<B> quic::Connection<B> for Connection
67where
68    B: Buf,
69{
70    type RecvStream = RecvStream;
71    type OpenStreams = OpenStreams;
72
73    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
74    fn poll_accept_bidi(
75        &mut self,
76        cx: &mut task::Context<'_>,
77    ) -> Poll<Result<Self::BidiStream, ConnectionErrorIncoming>> {
78        let (send, recv) = ready!(self.incoming_bi.poll_next_unpin(cx))
79            .expect("self.incoming_bi BoxStream never returns None")
80            .map_err(convert_connection_error)?;
81        Poll::Ready(Ok(Self::BidiStream {
82            send: Self::SendStream::new(send),
83            recv: Self::RecvStream::new(recv),
84        }))
85    }
86
87    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
88    fn poll_accept_recv(
89        &mut self,
90        cx: &mut task::Context<'_>,
91    ) -> Poll<Result<Self::RecvStream, ConnectionErrorIncoming>> {
92        let recv = ready!(self.incoming_uni.poll_next_unpin(cx))
93            .expect("self.incoming_uni BoxStream never returns None")
94            .map_err(convert_connection_error)?;
95        Poll::Ready(Ok(Self::RecvStream::new(recv)))
96    }
97
98    fn opener(&self) -> Self::OpenStreams {
99        OpenStreams {
100            conn: self.conn.clone(),
101            opening_bi: None,
102            opening_uni: None,
103        }
104    }
105}
106
107fn convert_connection_error(e: quinn::ConnectionError) -> h3::quic::ConnectionErrorIncoming {
108    match e {
109        quinn::ConnectionError::ApplicationClosed(application_close) => {
110            ConnectionErrorIncoming::ApplicationClose {
111                error_code: application_close.error_code.into(),
112            }
113        }
114        quinn::ConnectionError::ConnectionClosed(connection_close) => {
115            ConnectionErrorIncoming::ConnectionClosed {
116                error_code: connection_close.error_code.into(),
117            }
118        }
119        quinn::ConnectionError::TimedOut => ConnectionErrorIncoming::Timeout,
120
121        error @ quinn::ConnectionError::VersionMismatch
122        | error @ quinn::ConnectionError::Reset
123        | error @ quinn::ConnectionError::LocallyClosed
124        | error @ quinn::ConnectionError::CidsExhausted
125        | error @ quinn::ConnectionError::TransportError(_) => {
126            ConnectionErrorIncoming::Undefined(Arc::new(error))
127        }
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::convert_connection_error;
134    use h3::quic::ConnectionErrorIncoming;
135    use quinn::{ConnectionClose, ConnectionError, TransportErrorCode};
136
137    #[test]
138    fn connection_closed_is_mapped_to_structured_variant() {
139        let error = ConnectionError::ConnectionClosed(ConnectionClose {
140            error_code: TransportErrorCode::NO_ERROR,
141            frame_type: None,
142            reason: Default::default(),
143        });
144
145        assert!(matches!(
146            convert_connection_error(error),
147            ConnectionErrorIncoming::ConnectionClosed { error_code: 0 }
148        ));
149    }
150}
151
152impl<B> quic::OpenStreams<B> for Connection
153where
154    B: Buf,
155{
156    type SendStream = SendStream<B>;
157    type BidiStream = BidiStream<B>;
158
159    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
160    fn poll_open_bidi(
161        &mut self,
162        cx: &mut task::Context<'_>,
163    ) -> Poll<Result<Self::BidiStream, StreamErrorIncoming>> {
164        let bi = self.opening_bi.get_or_insert_with(|| {
165            Box::pin(stream::unfold(self.conn.clone(), |conn| async {
166                Some((conn.open_bi().await, conn))
167            }))
168        });
169        let (send, recv) = ready!(bi.poll_next_unpin(cx))
170            .expect("BoxStream does not return None")
171            .map_err(|e| StreamErrorIncoming::ConnectionErrorIncoming {
172                connection_error: convert_connection_error(e),
173            })?;
174        Poll::Ready(Ok(Self::BidiStream {
175            send: Self::SendStream::new(send),
176            recv: RecvStream::new(recv),
177        }))
178    }
179
180    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
181    fn poll_open_send(
182        &mut self,
183        cx: &mut task::Context<'_>,
184    ) -> Poll<Result<Self::SendStream, StreamErrorIncoming>> {
185        let uni = self.opening_uni.get_or_insert_with(|| {
186            Box::pin(stream::unfold(self.conn.clone(), |conn| async {
187                Some((conn.open_uni().await, conn))
188            }))
189        });
190
191        let send = ready!(uni.poll_next_unpin(cx))
192            .expect("BoxStream does not return None")
193            .map_err(|e| StreamErrorIncoming::ConnectionErrorIncoming {
194                connection_error: convert_connection_error(e),
195            })?;
196        Poll::Ready(Ok(Self::SendStream::new(send)))
197    }
198
199    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
200    fn close(&mut self, code: Code, reason: &[u8]) {
201        self.conn.close(
202            VarInt::from_u64(code.value()).expect("error code VarInt"),
203            reason,
204        );
205    }
206}
207
208/// Stream opener backed by a Quinn connection
209///
210/// Implements [`quic::OpenStreams`] using [`quinn::Connection`],
211/// [`quinn::OpenBi`], [`quinn::OpenUni`].
212pub struct OpenStreams {
213    conn: quinn::Connection,
214    opening_bi: Option<BoxStreamSync<'static, <OpenBi<'static> as Future>::Output>>,
215    opening_uni: Option<BoxStreamSync<'static, <OpenUni<'static> as Future>::Output>>,
216}
217
218impl<B> quic::OpenStreams<B> for OpenStreams
219where
220    B: Buf,
221{
222    type SendStream = SendStream<B>;
223    type BidiStream = BidiStream<B>;
224
225    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
226    fn poll_open_bidi(
227        &mut self,
228        cx: &mut task::Context<'_>,
229    ) -> Poll<Result<Self::BidiStream, StreamErrorIncoming>> {
230        let bi = self.opening_bi.get_or_insert_with(|| {
231            Box::pin(stream::unfold(self.conn.clone(), |conn| async {
232                Some((conn.open_bi().await, conn))
233            }))
234        });
235
236        let (send, recv) = ready!(bi.poll_next_unpin(cx))
237            .expect("BoxStream does not return None")
238            .map_err(|e| StreamErrorIncoming::ConnectionErrorIncoming {
239                connection_error: convert_connection_error(e),
240            })?;
241        Poll::Ready(Ok(Self::BidiStream {
242            send: Self::SendStream::new(send),
243            recv: RecvStream::new(recv),
244        }))
245    }
246
247    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
248    fn poll_open_send(
249        &mut self,
250        cx: &mut task::Context<'_>,
251    ) -> Poll<Result<Self::SendStream, StreamErrorIncoming>> {
252        let uni = self.opening_uni.get_or_insert_with(|| {
253            Box::pin(stream::unfold(self.conn.clone(), |conn| async {
254                Some((conn.open_uni().await, conn))
255            }))
256        });
257
258        let send = ready!(uni.poll_next_unpin(cx))
259            .expect("BoxStream does not return None")
260            .map_err(|e| StreamErrorIncoming::ConnectionErrorIncoming {
261                connection_error: convert_connection_error(e),
262            })?;
263        Poll::Ready(Ok(Self::SendStream::new(send)))
264    }
265
266    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
267    fn close(&mut self, code: Code, reason: &[u8]) {
268        self.conn.close(
269            VarInt::from_u64(code.value()).expect("error code VarInt"),
270            reason,
271        );
272    }
273}
274
275impl Clone for OpenStreams {
276    fn clone(&self) -> Self {
277        Self {
278            conn: self.conn.clone(),
279            opening_bi: None,
280            opening_uni: None,
281        }
282    }
283}
284
285/// Quinn-backed bidirectional stream
286///
287/// Implements [`quic::BidiStream`] which allows the stream to be split
288/// into two structs each implementing one direction.
289pub struct BidiStream<B>
290where
291    B: Buf,
292{
293    send: SendStream<B>,
294    recv: RecvStream,
295}
296
297impl<B> quic::BidiStream<B> for BidiStream<B>
298where
299    B: Buf,
300{
301    type SendStream = SendStream<B>;
302    type RecvStream = RecvStream;
303
304    fn split(self) -> (Self::SendStream, Self::RecvStream) {
305        (self.send, self.recv)
306    }
307}
308
309impl<B: Buf> quic::RecvStream for BidiStream<B> {
310    type Buf = Bytes;
311
312    fn poll_data(
313        &mut self,
314        cx: &mut task::Context<'_>,
315    ) -> Poll<Result<Option<Self::Buf>, StreamErrorIncoming>> {
316        self.recv.poll_data(cx)
317    }
318
319    fn stop_sending(&mut self, error_code: u64) {
320        self.recv.stop_sending(error_code)
321    }
322
323    fn recv_id(&self) -> StreamId {
324        self.recv.recv_id()
325    }
326}
327
328impl<B> quic::SendStream<B> for BidiStream<B>
329where
330    B: Buf,
331{
332    fn poll_ready(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), StreamErrorIncoming>> {
333        self.send.poll_ready(cx)
334    }
335
336    fn poll_finish(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), StreamErrorIncoming>> {
337        self.send.poll_finish(cx)
338    }
339
340    fn reset(&mut self, reset_code: u64) {
341        self.send.reset(reset_code)
342    }
343
344    fn send_data<D: Into<WriteBuf<B>>>(&mut self, data: D) -> Result<(), StreamErrorIncoming> {
345        self.send.send_data(data)
346    }
347
348    fn send_id(&self) -> StreamId {
349        self.send.send_id()
350    }
351}
352impl<B> quic::SendStreamUnframed<B> for BidiStream<B>
353where
354    B: Buf,
355{
356    fn poll_send<D: Buf>(
357        &mut self,
358        cx: &mut task::Context<'_>,
359        buf: &mut D,
360    ) -> Poll<Result<usize, StreamErrorIncoming>> {
361        self.send.poll_send(cx, buf)
362    }
363}
364
365impl<B> quic::Is0rtt for BidiStream<B>
366where
367    B: Buf,
368{
369    fn is_0rtt(&self) -> bool {
370        self.recv.is_0rtt()
371    }
372}
373
374/// Quinn-backed receive stream
375///
376/// Implements a [`quic::RecvStream`] backed by a [`quinn::RecvStream`].
377pub struct RecvStream {
378    stream: quinn::RecvStream,
379    id: StreamId,
380    is_0rtt: bool,
381}
382
383impl RecvStream {
384    fn new(stream: quinn::RecvStream) -> Self {
385        let id = u64::from(stream.id())
386            .try_into()
387            .expect("invalid stream id");
388        let is_0rtt = stream.is_0rtt();
389        Self {
390            stream,
391            id,
392            is_0rtt,
393        }
394    }
395}
396
397impl quic::RecvStream for RecvStream {
398    type Buf = Bytes;
399
400    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
401    fn poll_data(
402        &mut self,
403        cx: &mut task::Context<'_>,
404    ) -> Poll<Result<Option<Self::Buf>, StreamErrorIncoming>> {
405        // read_chunk is cancel-safe. Borrow it only for this poll so that
406        // STOP_SENDING can reach the stream even while a read is pending.
407        let read = self.stream.read_chunk(usize::MAX, true);
408        let mut read = std::pin::pin!(read);
409        read.as_mut()
410            .poll(cx)
411            .map(|result| result.map(|chunk| chunk.map(|c| c.bytes)))
412            .map_err(convert_read_error_to_stream_error)
413    }
414
415    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
416    fn stop_sending(&mut self, error_code: u64) {
417        let error_code = VarInt::from_u64(error_code).expect("invalid error_code");
418        let _ = self.stream.stop(error_code);
419    }
420
421    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
422    fn recv_id(&self) -> StreamId {
423        self.id
424    }
425}
426
427impl quic::Is0rtt for RecvStream {
428    /// Check if this stream has been opened during 0-RTT.
429    ///
430    /// In which case any non-idempotent request should be considered dangerous at the application
431    /// level. Because read data is subject to replay attacks.
432    fn is_0rtt(&self) -> bool {
433        self.is_0rtt
434    }
435}
436
437fn convert_read_error_to_stream_error(error: ReadError) -> StreamErrorIncoming {
438    match error {
439        ReadError::Reset(var_int) => StreamErrorIncoming::StreamTerminated {
440            error_code: var_int.into_inner(),
441        },
442        ReadError::ConnectionLost(connection_error) => {
443            StreamErrorIncoming::ConnectionErrorIncoming {
444                connection_error: convert_connection_error(connection_error),
445            }
446        }
447        error @ ReadError::ClosedStream => StreamErrorIncoming::Unknown(Box::new(error)),
448        ReadError::IllegalOrderedRead => panic!("h3-quinn only performs ordered reads"),
449        error @ ReadError::ZeroRttRejected => StreamErrorIncoming::Unknown(Box::new(error)),
450    }
451}
452
453fn convert_write_error_to_stream_error(error: quinn::WriteError) -> StreamErrorIncoming {
454    match error {
455        quinn::WriteError::Stopped(var_int) => StreamErrorIncoming::StreamTerminated {
456            error_code: var_int.into_inner(),
457        },
458        quinn::WriteError::ConnectionLost(connection_error) => {
459            StreamErrorIncoming::ConnectionErrorIncoming {
460                connection_error: convert_connection_error(connection_error),
461            }
462        }
463        error @ quinn::WriteError::ClosedStream | error @ quinn::WriteError::ZeroRttRejected => {
464            StreamErrorIncoming::Unknown(Box::new(error))
465        }
466    }
467}
468
469/// Quinn-backed send stream
470///
471/// Implements a [`quic::SendStream`] backed by a [`quinn::SendStream`].
472pub struct SendStream<B: Buf> {
473    stream: quinn::SendStream,
474    writing: Option<WriteBuf<B>>,
475}
476
477impl<B> SendStream<B>
478where
479    B: Buf,
480{
481    fn new(stream: quinn::SendStream) -> SendStream<B> {
482        Self {
483            stream,
484            writing: None,
485        }
486    }
487}
488
489impl<B> quic::SendStream<B> for SendStream<B>
490where
491    B: Buf,
492{
493    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
494    fn poll_ready(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), StreamErrorIncoming>> {
495        if let Some(ref mut data) = self.writing {
496            while data.has_remaining() {
497                let stream = Pin::new(&mut self.stream);
498                let written = ready!(stream.poll_write(cx, data.chunk()))
499                    .map_err(convert_write_error_to_stream_error)?;
500                data.advance(written);
501            }
502        }
503        // all data is written
504        self.writing = None;
505        Poll::Ready(Ok(()))
506    }
507
508    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
509    fn poll_finish(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), StreamErrorIncoming>> {
510        // Flush whatever `send_data` buffered before sending FIN, otherwise the tail of the
511        // last frame is dropped and the peer sees a truncated stream.
512        ready!(self.poll_ready(cx))?;
513        Poll::Ready(
514            self.stream
515                .finish()
516                .map_err(|e| StreamErrorIncoming::Unknown(Box::new(e))),
517        )
518    }
519
520    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
521    fn reset(&mut self, reset_code: u64) {
522        let _ = self
523            .stream
524            .reset(VarInt::from_u64(reset_code).unwrap_or(VarInt::MAX));
525    }
526
527    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
528    fn send_data<D: Into<WriteBuf<B>>>(&mut self, data: D) -> Result<(), StreamErrorIncoming> {
529        if self.writing.is_some() {
530            // This can only happen if the traits are misused by h3 itself
531            // If this happens log an error and close the connection with H3_INTERNAL_ERROR
532
533            #[cfg(feature = "tracing")]
534            tracing::error!("send_data called while send stream is not ready");
535            return Err(StreamErrorIncoming::ConnectionErrorIncoming {
536                connection_error: ConnectionErrorIncoming::InternalError(
537                    "internal error in the http stack".to_string(),
538                ),
539            });
540        }
541        self.writing = Some(data.into());
542        Ok(())
543    }
544
545    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
546    fn send_id(&self) -> StreamId {
547        let num: u64 = self.stream.id().into();
548        num.try_into().expect("invalid stream id")
549    }
550}
551
552impl<B> quic::SendStreamUnframed<B> for SendStream<B>
553where
554    B: Buf,
555{
556    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
557    fn poll_send<D: Buf>(
558        &mut self,
559        cx: &mut task::Context<'_>,
560        buf: &mut D,
561    ) -> Poll<Result<usize, StreamErrorIncoming>> {
562        if self.writing.is_some() {
563            // This signifies a bug in implementation
564            panic!("poll_send called while send stream is not ready")
565        }
566
567        let s = Pin::new(&mut self.stream);
568
569        let res = ready!(s.poll_write(cx, buf.chunk()));
570        match res {
571            Ok(written) => {
572                buf.advance(written);
573                Poll::Ready(Ok(written))
574            }
575            Err(err) => Poll::Ready(Err(convert_write_error_to_stream_error(err))),
576        }
577    }
578}