Skip to main content

fetchlet_net/websocket/
transport.rs

1use std::sync::Arc;
2
3use tokio::io::{AsyncRead, AsyncWrite};
4use tokio_rustls::rustls::ClientConfig;
5use tokio_tungstenite::tungstenite::client::IntoClientRequest;
6use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
7
8use fetchlet::http::{HeaderValue, header};
9use fetchlet::{
10    ChannelEnd, Error, WebSocketAccept, WebSocketFuture, WebSocketRequest, WebSocketTransport,
11};
12
13use super::relay::relay;
14use crate::network::{Connector, runtime};
15
16/// A [`WebSocketTransport`] that opens client WebSockets over TCP, with TLS
17/// for `wss:`.
18///
19/// Pair it with a `FetchPolicy` in a `WebSocketService`: the policy
20/// authorizes the origins JavaScript connects to, and this transport
21/// resolves their hosts and refuses any resolved address that is not
22/// public, such as loopback, private and link-local networks, unless
23/// [`allow_private_addresses`](Self::allow_private_addresses). A host that
24/// resolves to no allowed address fails with `PermissionDenied`.
25///
26/// The opening handshake asks for the subprotocols JavaScript requested and
27/// carries the service's credential headers; tungstenite performs it and
28/// the framing, answers pings and validates the server's selection. No
29/// extensions are requested. `Limits::channel_message_bytes` bounds each
30/// message and frame from the server. Connecting and relaying run on the
31/// Tokio runtime that polls the host pump; an App without one fails each
32/// connection with `Configuration`. TLS verifies the server against the
33/// Mozilla roots in `webpki-roots`, or the configuration from
34/// [`with_tls_config`](Self::with_tls_config).
35#[derive(Clone)]
36pub struct WebSocketClient {
37    connector: Connector,
38}
39
40impl WebSocketClient {
41    /// Connect to public addresses, verifying `wss:` servers against the
42    /// `webpki-roots` certificates.
43    pub fn new() -> Self {
44        Self {
45            connector: Connector::new(),
46        }
47    }
48
49    /// Connect to public addresses, using `config` for `wss:`, such as one
50    /// that trusts a private certificate authority.
51    pub fn with_tls_config(config: Arc<ClientConfig>) -> Self {
52        Self {
53            connector: Connector::with_tls_config(config),
54        }
55    }
56
57    /// Also connect to loopback, private and other non-public addresses,
58    /// for a host whose services run beside it.
59    pub fn allow_private_addresses(mut self) -> Self {
60        self.connector.allow_private_addresses();
61        self
62    }
63}
64
65impl Default for WebSocketClient {
66    fn default() -> Self {
67        Self::new()
68    }
69}
70
71impl std::fmt::Debug for WebSocketClient {
72    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        formatter
74            .debug_struct("WebSocketClient")
75            .field(
76                "allow_private_addresses",
77                &self.connector.allows_private_addresses(),
78            )
79            .finish_non_exhaustive()
80    }
81}
82
83impl WebSocketTransport for WebSocketClient {
84    fn connect(&self, request: WebSocketRequest) -> WebSocketFuture {
85        let connector = self.connector.clone();
86        Box::pin(async move {
87            let runtime = runtime("WebSocketClient")?;
88            let WebSocketRequest {
89                url,
90                protocols,
91                headers,
92                end,
93                ..
94            } = request;
95            // The host without the brackets of an IPv6 literal.
96            let host = url
97                .host_str()
98                .map(|host| {
99                    host.trim_start_matches('[')
100                        .trim_end_matches(']')
101                        .to_owned()
102                })
103                .ok_or_else(|| Error::InvalidRequest("a WebSocket URL needs a host".into()))?;
104            let port = url
105                .port_or_known_default()
106                .ok_or_else(|| Error::InvalidRequest("a WebSocket URL needs a port".into()))?;
107
108            let mut handshake = url
109                .as_str()
110                .into_client_request()
111                .map_err(|_| Error::InvalidRequest("invalid WebSocket URL".into()))?;
112            handshake.headers_mut().extend(headers);
113            if !protocols.is_empty() {
114                let value = HeaderValue::from_str(&protocols.join(", "))
115                    .map_err(|_| Error::InvalidRequest("invalid WebSocket subprotocol".into()))?;
116                handshake
117                    .headers_mut()
118                    .insert(header::SEC_WEBSOCKET_PROTOCOL, value);
119            }
120
121            let stream = connector.connect(&host, port).await?;
122            if url.scheme() == "wss" {
123                let stream = connector.secure(stream, &host).await?;
124                open(runtime, handshake, stream, end).await
125            } else {
126                open(runtime, handshake, stream, end).await
127            }
128        })
129    }
130}
131
132/// Perform the opening handshake over `stream`, then relay on a task.
133async fn open<S>(
134    runtime: tokio::runtime::Handle,
135    handshake: fetchlet::http::Request<()>,
136    stream: S,
137    end: ChannelEnd,
138) -> fetchlet::Result<WebSocketAccept>
139where
140    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
141{
142    let limit = end.max_message_bytes();
143    let config = WebSocketConfig::default()
144        .max_message_size(limit)
145        .max_frame_size(limit);
146    let (socket, response) =
147        tokio_tungstenite::client_async_with_config(handshake, stream, Some(config))
148            .await
149            .map_err(|error| Error::Transport(format!("WebSocket handshake failed: {error}")))?;
150    let header = |name| {
151        response
152            .headers()
153            .get(name)
154            .and_then(|value| value.to_str().ok())
155            .unwrap_or_default()
156            .to_owned()
157    };
158    let accepted = WebSocketAccept {
159        protocol: header(header::SEC_WEBSOCKET_PROTOCOL),
160        extensions: header(header::SEC_WEBSOCKET_EXTENSIONS),
161    };
162    runtime.spawn(relay(socket, end));
163    Ok(accepted)
164}