Skip to main content

net/
websocket_loader.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! The websocket handler has three main responsibilities:
6//! 1) initiate the initial HTTP connection and process the response
7//! 2) ensure any DOM requests for sending/closing are propagated to the network
8//! 3) transmit any incoming messages/closing to the DOM
9//!
10//! In order to accomplish this, the handler uses a long-running loop that selects
11//! over events from the network and events from the DOM, using async/await to avoid
12//! the need for a dedicated thread per websocket.
13
14use std::sync::Arc;
15use std::sync::atomic::{AtomicBool, Ordering};
16
17use async_tungstenite::WebSocketStream;
18use async_tungstenite::tokio::{ConnectStream, client_async_tls_with_connector_and_config};
19use futures::stream::StreamExt;
20use headers::{
21    Authorization, Connection, HeaderMapExt, SecWebsocketKey, SecWebsocketVersion, Upgrade,
22};
23use http::HeaderMap;
24use http::header::{self, HeaderName, HeaderValue};
25use log::{debug, trace, warn};
26use net_traits::request::{RequestBuilder, RequestMode};
27use net_traits::{CookieSource, MessageData, WebSocketDomAction, WebSocketNetworkEvent};
28use profile_traits::generic_callback::GenericCallback as ProfileGenericCallback;
29use servo_base::generic_channel::CallbackSetter;
30use servo_url::ServoUrl;
31use tokio::net::TcpStream;
32use tokio::select;
33use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
34use tokio_rustls::TlsConnector;
35use tungstenite::error::{Error, ProtocolError, UrlError};
36use tungstenite::handshake::client::Response;
37use tungstenite::protocol::CloseFrame;
38use tungstenite::{ClientRequestBuilder, Message};
39
40use crate::async_runtime::spawn_task;
41use crate::connector::TlsConfig;
42use crate::cookie::ServoCookie;
43use crate::hosts::replace_host;
44use crate::http_loader::HttpState;
45
46/// Create a Request object for the initial HTTP request.
47/// This request contains `Origin`, `Sec-WebSocket-Protocol`, `Authorization`,
48/// and `Cookie` headers as appropriate.
49/// Returns an error if any header values are invalid or tungstenite cannot create
50/// the desired request.
51pub fn create_handshake_request(
52    request: RequestBuilder,
53    http_state: Arc<HttpState>,
54) -> Result<net_traits::request::Request, Error> {
55    let origin = request.url.origin();
56
57    let mut headers = HeaderMap::new();
58    headers.insert(
59        "Origin",
60        HeaderValue::from_str(request.url.origin().ascii_serialization().as_ref())?,
61    );
62
63    let host = format!(
64        "{}",
65        origin
66            .host()
67            .ok_or_else(|| Error::Url(UrlError::NoHostName))?
68    );
69    headers.insert("Host", HeaderValue::from_str(&host)?);
70
71    // https://websockets.spec.whatwg.org/#concept-websocket-establish
72    // 3. Append (`Upgrade`, `websocket`) to request’s header list.
73    headers.typed_insert(Upgrade::websocket());
74
75    // 4. Append (`Connection`, `Upgrade`) to request’s header list.
76    headers.typed_insert(Connection::upgrade());
77
78    // 5. Let keyValue be a nonce consisting of a randomly selected 16-byte value that has been
79    // forgiving-base64-encoded and isomorphic encoded.
80    let mut nonce: [u8; 16] = [0; 16];
81    rand::fill(&mut nonce);
82    let sec_websocket_key_header: SecWebsocketKey = nonce.into();
83
84    // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s header list.
85    headers.typed_insert(sec_websocket_key_header);
86
87    // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s header list.
88    headers.typed_insert(SecWebsocketVersion::V13);
89
90    // 8. For each protocol in protocols, combine (`Sec-WebSocket-Protocol`, protocol) in request’s
91    // header list.
92    let protocols = match request.mode {
93        RequestMode::WebSocket {
94            ref protocols,
95            original_url: _,
96        } => protocols,
97        _ => unreachable!("How did we get here?"),
98    };
99    if !protocols.is_empty() {
100        let protocols = protocols.join(",");
101        headers.insert("Sec-WebSocket-Protocol", HeaderValue::from_str(&protocols)?);
102    }
103
104    let mut cookie_jar = http_state.cookie_jar.write();
105    cookie_jar.remove_expired_cookies_for_url(&request.url);
106    if let Some(cookie_list) = cookie_jar.cookies_for_url(&request.url, CookieSource::HTTP) {
107        headers.insert("Cookie", HeaderValue::from_str(&cookie_list)?);
108    }
109
110    if request.url.password().is_some() || request.url.username() != "" {
111        headers.typed_insert(Authorization::basic(
112            request.url.username(),
113            request.url.password().unwrap_or(""),
114        ));
115    }
116    Ok(request.headers(headers).build())
117}
118
119/// Process an HTTP response resulting from a WS handshake.
120/// This ensures that any `Cookie` or HSTS headers are recognized.
121/// Returns an error if the protocol selected by the handshake doesn't
122/// match the list of provided protocols in the original request.
123fn process_ws_response(
124    http_state: &HttpState,
125    response: &Response,
126    resource_url: &ServoUrl,
127    protocols: &[String],
128) -> Result<Option<String>, Error> {
129    trace!("processing websocket http response for {}", resource_url);
130    let mut protocol_in_use = None;
131    if let Some(protocol_name) = response.headers().get("Sec-WebSocket-Protocol") {
132        let protocol_name = protocol_name.to_str().unwrap_or("");
133        if !protocols.is_empty() && !protocols.iter().any(|p| protocol_name == (*p)) {
134            return Err(Error::Protocol(ProtocolError::InvalidHeader(Box::new(
135                HeaderName::from_static("sec-websocket-protocol"),
136            ))));
137        }
138        protocol_in_use = Some(protocol_name.to_string());
139    }
140
141    let mut jar = http_state.cookie_jar.write();
142    // TODO(eijebong): Replace thise once typed headers settled on a cookie impl
143    for cookie in response.headers().get_all(header::SET_COOKIE) {
144        let cookie_bytes = cookie.as_bytes();
145        if !ServoCookie::is_valid_name_or_value(cookie_bytes) {
146            continue;
147        }
148        if let Ok(s) = std::str::from_utf8(cookie_bytes) &&
149            let Some(cookie) =
150                ServoCookie::from_cookie_string(s, resource_url, CookieSource::HTTP)
151        {
152            jar.push(cookie, resource_url, CookieSource::HTTP);
153        }
154    }
155
156    http_state
157        .hsts_list
158        .write()
159        .update_hsts_list_from_response(resource_url, response.headers());
160
161    Ok(protocol_in_use)
162}
163
164#[derive(Debug)]
165enum DomMsg {
166    Abort,
167    Send(Message),
168    Close(Option<(u16, String)>),
169}
170
171/// Initialize a listener for DOM actions. These are routed from the IPC channel
172/// to a tokio channel that the main WS client task uses to receive them.
173fn setup_dom_listener(
174    dom_action_receiver: CallbackSetter<WebSocketDomAction>,
175    initiated_close: Arc<AtomicBool>,
176) -> UnboundedReceiver<DomMsg> {
177    let (sender, receiver) = unbounded_channel();
178
179    dom_action_receiver.set_callback(move |message| {
180        let dom_action = message.expect("Ws dom_action message to deserialize");
181        trace!("handling WS DOM action: {:?}", dom_action);
182        match dom_action {
183            WebSocketDomAction::Abort => {
184                initiated_close.store(true, Ordering::SeqCst);
185                let _ = sender.send(DomMsg::Abort);
186            },
187            WebSocketDomAction::SendMessage(MessageData::Text(data)) => {
188                if let Err(e) = sender.send(DomMsg::Send(Message::Text(data.into()))) {
189                    warn!("Error sending websocket message: {:?}", e);
190                }
191            },
192            WebSocketDomAction::SendMessage(MessageData::Binary(data)) => {
193                if let Err(e) = sender.send(DomMsg::Send(Message::Binary(data.into()))) {
194                    warn!("Error sending websocket message: {:?}", e);
195                }
196            },
197            WebSocketDomAction::Close(code, reason) => {
198                if initiated_close.fetch_or(true, Ordering::SeqCst) {
199                    return;
200                }
201                let frame = code.map(move |c| (c, reason.unwrap_or_default()));
202                if let Err(e) = sender.send(DomMsg::Close(frame)) {
203                    warn!("Error closing websocket: {:?}", e);
204                }
205            },
206        }
207    });
208
209    receiver
210}
211
212/// Listen for WS events from the DOM and the network until one side
213/// closes the connection or an error occurs. Since this is an async
214/// function that uses the select operation, it will run as a task
215/// on the WS tokio runtime.
216async fn run_ws_loop(
217    mut dom_receiver: UnboundedReceiver<DomMsg>,
218    resource_event_sender: ProfileGenericCallback<WebSocketNetworkEvent>,
219    mut stream: WebSocketStream<ConnectStream>,
220) {
221    loop {
222        select! {
223            dom_msg = dom_receiver.recv() => {
224                trace!("processing dom msg: {:?}", dom_msg);
225                let dom_msg = match dom_msg {
226                    Some(msg) => msg,
227                    None => break,
228                };
229                match dom_msg {
230                    DomMsg::Abort => break,
231                    DomMsg::Send(m) => {
232                        if let Err(e) = stream.send(m).await {
233                            warn!("error sending websocket message: {:?}", e);
234                        }
235                    },
236                    DomMsg::Close(frame) => {
237                        if let Err(e) = stream.close(frame.map(|(code, reason)| {
238                            CloseFrame {
239                                code: code.into(),
240                                reason: reason.into(),
241                            }
242                        })).await {
243                            warn!("error closing websocket: {:?}", e);
244                        }
245                    },
246                }
247            }
248            ws_msg = stream.next() => {
249                trace!("processing WS stream: {:?}", ws_msg);
250                let msg = match ws_msg {
251                    Some(Ok(msg)) => msg,
252                    Some(Err(e)) => {
253                        warn!("Error in WebSocket communication: {:?}", e);
254                        let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail);
255                        break;
256                    },
257                    None => {
258                        warn!("Error in WebSocket communication");
259                        let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail);
260                        break;
261                    }
262                };
263                match msg {
264                    Message::Text(s) => {
265                        let message = MessageData::Text(s.as_str().to_owned());
266                        if let Err(e) = resource_event_sender
267                            .send(WebSocketNetworkEvent::MessageReceived(message))
268                        {
269                            warn!("Error sending websocket notification: {:?}", e);
270                            break;
271                        }
272                    }
273
274                    Message::Binary(v) => {
275                        let message = MessageData::Binary(v.to_vec());
276                        if let Err(e) = resource_event_sender
277                            .send(WebSocketNetworkEvent::MessageReceived(message))
278                        {
279                            warn!("Error sending websocket notification: {:?}", e);
280                            break;
281                        }
282                    }
283
284                    Message::Ping(_) | Message::Pong(_) => {}
285
286                    Message::Close(frame) => {
287                        let (reason, code) = match frame {
288                            Some(frame) => (frame.reason, Some(frame.code.into())),
289                            None => ("".into(), None),
290                        };
291                        debug!("Websocket connection closing due to ({:?}) {}", code, reason);
292                        let _ = resource_event_sender.send(WebSocketNetworkEvent::Close(
293                            code,
294                            reason.to_string(),
295                        ));
296                        break;
297                    }
298
299                    Message::Frame(_) => {
300                        warn!("Unexpected websocket frame message");
301                    }
302                }
303            }
304        }
305    }
306}
307
308/// Initiate a new async WS connection. Returns an error if the connection fails
309/// for any reason, or if the response isn't valid. Otherwise, the endless WS
310/// listening loop will be started.
311pub(crate) async fn start_websocket(
312    http_state: Arc<HttpState>,
313    resource_event_sender: ProfileGenericCallback<WebSocketNetworkEvent>,
314    protocols: &[String],
315    client: &net_traits::request::Request,
316    tls_config: TlsConfig,
317    dom_action_receiver: CallbackSetter<WebSocketDomAction>,
318) -> Result<Response, Error> {
319    trace!("starting WS connection to {}", client.url());
320
321    let initiated_close = Arc::new(AtomicBool::new(false));
322    let mut dom_receiver = setup_dom_listener(dom_action_receiver, initiated_close.clone());
323
324    let url = client.url();
325    let host = replace_host(url.host_str().expect("URL has no host"));
326    let mut net_url = client.url().into_url();
327    net_url
328        .set_host(Some(&host))
329        .map_err(|e| Error::Url(UrlError::UnableToConnect(e.to_string())))?;
330
331    let domain = net_url
332        .host()
333        .ok_or_else(|| Error::Url(UrlError::NoHostName))?;
334    let port = net_url
335        .port_or_known_default()
336        .ok_or_else(|| Error::Url(UrlError::UnableToConnect("Unknown port".into())))?;
337
338    // Race the entire connection attempt (including DNS, TCP and TLS) against
339    // cancellation, so a stalled handshake cannot retain the DOM callback.
340    let connection = async {
341        let try_socket = TcpStream::connect((&*domain.to_string(), port)).await;
342        let socket = try_socket.map_err(Error::Io)?;
343        let connector = TlsConnector::from(Arc::new(tls_config));
344
345        // TODO(pylbrecht): move request conversion to a separate function
346        let mut original_url = client.original_url();
347        if original_url.scheme() == "ws" && url.scheme() == "https" {
348            original_url.as_mut_url().set_scheme("wss").unwrap();
349        }
350        let mut builder =
351            ClientRequestBuilder::new(original_url.as_str().parse().expect("unable to parse URI"));
352        for (key, value) in client.headers.iter() {
353            builder = builder.with_header(
354                key.as_str(),
355                value
356                    .to_str()
357                    .expect("unable to convert header value to string"),
358            );
359        }
360
361        client_async_tls_with_connector_and_config(builder, socket, Some(connector), None).await
362    };
363    let (stream, response) = select! {
364        biased;
365        // No messages can be sent while CONNECTING, so the first DOM action
366        // must be Abort or Close. Dropping `connection` releases the pending socket.
367        _ = dom_receiver.recv() => return Err(Error::ConnectionClosed),
368        result = connection => result?,
369    };
370
371    let protocol_in_use = process_ws_response(&http_state, &response, &url, protocols)?;
372
373    if !initiated_close.load(Ordering::SeqCst) {
374        if resource_event_sender
375            .send(WebSocketNetworkEvent::ConnectionEstablished { protocol_in_use })
376            .is_err()
377        {
378            return Ok(response);
379        }
380
381        trace!("about to start ws loop for {}", url);
382        spawn_task(run_ws_loop(dom_receiver, resource_event_sender, stream));
383    } else {
384        trace!("client closed connection for {}, not running loop", url);
385    }
386    Ok(response)
387}