Skip to main content

web_transport_quinn/
connect.rs

1use std::ops::Deref;
2
3use web_transport_proto::{ConnectRequest, ConnectResponse, VarInt};
4
5use thiserror::Error;
6
7#[derive(Error, Debug, Clone)]
8pub enum ConnectError {
9    #[error("quic stream was closed early")]
10    UnexpectedEnd,
11
12    #[error("protocol error: {0}")]
13    ProtoError(#[from] web_transport_proto::ConnectError),
14
15    #[error("connection error")]
16    ConnectionError(#[from] quinn::ConnectionError),
17
18    #[error("read error")]
19    ReadError(#[from] quinn::ReadError),
20
21    #[error("write error")]
22    WriteError(#[from] quinn::WriteError),
23
24    #[error("http error status: {0}")]
25    ErrorStatus(http::StatusCode),
26
27    #[error("server returned protocol not in request: {0}")]
28    ProtocolMismatch(String),
29}
30
31/// An HTTP/3 CONNECT request/response for establishing a WebTransport session.
32pub struct Connecting {
33    // The request that was sent by the client.
34    pub request: ConnectRequest,
35
36    // A reference to the send/recv stream, so we don't close it until dropped.
37    pub(crate) send: quinn::SendStream,
38    pub(crate) recv: quinn::RecvStream,
39}
40
41impl Connecting {
42    pub async fn accept(conn: &quinn::Connection) -> Result<Self, ConnectError> {
43        // Accept the stream that will be used to send the HTTP CONNECT request.
44        // If they try to send any other type of HTTP request, we will error out.
45        let (send, mut recv) = conn.accept_bi().await?;
46
47        let request = web_transport_proto::ConnectRequest::read(&mut recv).await?;
48        tracing::debug!(?request, "received CONNECT request");
49
50        // The request was successfully decoded, so we can send a response.
51        Ok(Self {
52            request,
53            send,
54            recv,
55        })
56    }
57
58    // Called by the server to send a response to the client and establish the session.
59    pub async fn respond(
60        mut self,
61        response: impl Into<ConnectResponse>,
62    ) -> Result<Connected, ConnectError> {
63        let response = response.into();
64
65        // Validate that our protocol was in the client's request.
66        if let Some(protocol) = &response.protocol {
67            if !self.request.protocols.contains(protocol) {
68                return Err(ConnectError::ProtocolMismatch(protocol.clone()));
69            }
70        }
71
72        tracing::debug!(?response, "sending CONNECT response");
73        response.write(&mut self.send).await?;
74
75        Ok(Connected {
76            request: self.request,
77            response,
78            send: self.send,
79            recv: self.recv,
80        })
81    }
82
83    pub async fn reject(self, status: http::StatusCode) -> Result<(), ConnectError> {
84        let mut connect = self.respond(status).await?;
85        connect.send.finish().ok();
86        Ok(())
87    }
88}
89
90impl Deref for Connecting {
91    type Target = ConnectRequest;
92
93    fn deref(&self) -> &Self::Target {
94        &self.request
95    }
96}
97
98pub struct Connected {
99    // The request that was sent by the client.
100    pub request: ConnectRequest,
101
102    // The response sent by the server.
103    pub response: ConnectResponse,
104
105    // A reference to the send/recv stream, so we don't close it until dropped.
106    pub(crate) send: quinn::SendStream,
107    pub(crate) recv: quinn::RecvStream,
108}
109
110impl Connected {
111    /// Open a new WebTransport session on the given connection for the given URL.
112    ///
113    /// You may add any number of subprotocols allowing the server to select from.
114    /// If the list is empty the field will be omitted in the request header.
115    pub async fn open(
116        conn: &quinn::Connection,
117        request: impl Into<ConnectRequest>,
118    ) -> Result<Self, ConnectError> {
119        let request = request.into();
120
121        // Create a new stream that will be used to send the CONNECT frame.
122        let (mut send, mut recv) = conn.open_bi().await?;
123
124        tracing::debug!(?request, "sending CONNECT request");
125        request.write(&mut send).await?;
126
127        let response = web_transport_proto::ConnectResponse::read(&mut recv).await?;
128        tracing::debug!(?response, "received CONNECT response");
129
130        // Throw an error if we didn't get a 200 OK.
131        if response.status != http::StatusCode::OK {
132            return Err(ConnectError::ErrorStatus(response.status));
133        }
134
135        // Validate that the server's protocol was in our request.
136        if let Some(protocol) = &response.protocol {
137            if !request.protocols.contains(protocol) {
138                return Err(ConnectError::ProtocolMismatch(protocol.clone()));
139            }
140        }
141
142        Ok(Self {
143            request,
144            response,
145            send,
146            recv,
147        })
148    }
149
150    // The session ID is the stream ID of the CONNECT request.
151    pub fn session_id(&self) -> VarInt {
152        // We gotta convert from the Quinn VarInt to the (forked) WebTransport VarInt.
153        // We don't use the quinn::VarInt because that would mean a quinn dependency in web-transport-proto
154        let stream_id = quinn::VarInt::from(self.send.id());
155        VarInt::try_from(stream_id.into_inner()).unwrap()
156    }
157}