Skip to main content

rocket_ws/
websocket.rs

1use std::io;
2use std::time::Duration;
3
4use rocket::data::{IoHandler, IoStream};
5use rocket::futures::{self, StreamExt, SinkExt, future::BoxFuture, stream::SplitStream};
6use rocket::response::{self, Responder, Response};
7use rocket::request::{FromRequest, Request, Outcome};
8use rocket::http::Status;
9
10use crate::{Config, Message};
11use crate::stream::DuplexStream;
12use crate::result::{Result, Error};
13use crate::tungstenite::error::ProtocolError::{SendAfterClosing, ResetWithoutClosingHandshake};
14
15/// How long to wait to send a `Close` and receive the peer's reply.
16const CLOSE_TIMEOUT: Duration = Duration::from_secs(5);
17
18/// A request guard identifying WebSocket requests. Converts into a [`Channel`]
19/// or [`MessageStream`].
20///
21/// For example usage, see the [crate docs](crate#usage).
22///
23/// ## Details
24///
25/// This is the entrypoint to the library. Every WebSocket response _must_
26/// initiate via the `WebSocket` request guard. The guard identifies valid
27/// WebSocket connection requests and, if the request is valid, succeeds to be
28/// converted into a streaming WebSocket response via
29/// [`Stream!`](crate::Stream!), [`WebSocket::channel()`], or
30/// [`WebSocket::stream()`]. The connection can be configured via
31/// [`WebSocket::config()`]; see [`Config`] for details on configuring a
32/// connection.
33///
34/// ### Forwarding
35///
36/// If the incoming request is not a valid WebSocket request, the guard
37/// forwards with a status of `BadRequest`. The guard never fails.
38pub struct WebSocket {
39    config: Config,
40    key: String,
41}
42
43impl WebSocket {
44    fn new(key: String) -> WebSocket {
45        // `Config::default()` eagerly allocates a 128KiB read buffer for each
46        // connection. A smaller buffer keeps idle connections inexpensive.
47        let config = Config::default().read_buffer_size(8 * 1024);
48        WebSocket { config, key }
49    }
50
51    /// Change the default connection configuration to `config`.
52    ///
53    /// `config` replaces the default configuration entirely. By default, each
54    /// connection allocates an 8KiB read buffer, while [`Config::default()`]
55    /// uses a 128KiB read buffer. To keep a small buffer, set its size
56    /// explicitly with [`Config::read_buffer_size()`]. See [`Config`] for
57    /// details.
58    ///
59    /// # Example
60    ///
61    /// ```rust
62    /// # use rocket::get;
63    /// # use rocket_ws as ws;
64    /// #
65    /// #[get("/echo")]
66    /// fn echo_stream(ws: ws::WebSocket) -> ws::Stream!['static] {
67    ///     let config = ws::Config::default()
68    ///         .max_message_size(Some(4 << 20))
69    ///         .read_buffer_size(8 * 1024);
70    ///
71    ///     let ws = ws.config(config);
72    ///
73    ///     ws::Stream! { ws =>
74    ///         for await message in ws {
75    ///             yield message?;
76    ///         }
77    ///     }
78    /// }
79    /// ```
80    pub fn config(mut self, config: Config) -> Self {
81        self.config = config;
82        self
83    }
84
85    /// Create a read/write channel to the client and call `handler` with it.
86    ///
87    /// This method takes a `FnOnce`, `handler`, that consumes a read/write
88    /// WebSocket channel, [`DuplexStream`] to the client. See [`DuplexStream`]
89    /// for details on how to make use of the channel.
90    ///
91    /// The `handler` must return a `Box`ed and `Pin`ned future: calling
92    /// [`Box::pin()`] with a future does just this as is the preferred
93    /// mechanism to create a `Box<Pin<Future>>`. The future must return a
94    /// [`Result<()>`](crate::result::Result). The WebSocket connection is
95    /// closed successfully if the future returns `Ok` and with an error if
96    /// the future returns `Err`.
97    ///
98    /// # Lifetimes
99    ///
100    /// The `Channel` may borrow from the request. If it does, the lifetime
101    /// should be specified as something other than `'static`. Otherwise, the
102    /// `'static` lifetime should be used.
103    ///
104    /// # Example
105    ///
106    /// ```rust
107    /// # use rocket::get;
108    /// # use rocket_ws as ws;
109    /// use rocket::futures::{SinkExt, StreamExt};
110    ///
111    /// #[get("/hello/<name>")]
112    /// fn hello(ws: ws::WebSocket, name: &str) -> ws::Channel<'_> {
113    ///     ws.channel(move |mut stream| Box::pin(async move {
114    ///         let message = format!("Hello, {}!", name);
115    ///         let _ = stream.send(message.into()).await;
116    ///         Ok(())
117    ///     }))
118    /// }
119    ///
120    /// #[get("/echo")]
121    /// fn echo(ws: ws::WebSocket) -> ws::Channel<'static> {
122    ///     ws.channel(move |mut stream| Box::pin(async move {
123    ///         while let Some(message) = stream.next().await {
124    ///             let _ = stream.send(message?).await;
125    ///         }
126    ///
127    ///         Ok(())
128    ///     }))
129    /// }
130    /// ```
131    pub fn channel<'r, F>(self, handler: F) -> Channel<'r>
132        where F: FnOnce(DuplexStream) -> BoxFuture<'r, Result<()>> + Send + 'r
133    {
134        Channel { ws: self, handler: Box::new(handler), }
135    }
136
137    /// Create a stream that consumes client [`Message`]s and emits its own.
138    ///
139    /// This method takes a `FnOnce` `stream` that consumes a read-only stream
140    /// and returns a stream of [`Message`]s. While the returned stream can be
141    /// constructed in any manner, the [`Stream!`](crate::Stream!) macro is the
142    /// preferred method. In any case, the stream must be `Send`.
143    ///
144    /// The returned stream must emit items of type `Result<Message>`. Items
145    /// that are `Ok(Message)` are sent to the client while items of type
146    /// `Err(Error)` result in the connection being closed and the remainder of
147    /// the stream discarded.
148    ///
149    /// A stream that ends sends the client a [`Message::Close`]; a yielded
150    /// `Close` ends the stream with that message. The server then waits
151    /// briefly for the client's reply before closing the connection.
152    ///
153    /// # Example
154    ///
155    /// ```rust
156    /// # use rocket::get;
157    /// # use rocket_ws as ws;
158    ///
159    /// // Use `Stream!`, which internally calls `WebSocket::stream()`.
160    /// #[get("/echo?stream")]
161    /// fn echo_stream(ws: ws::WebSocket) -> ws::Stream!['static] {
162    ///     ws::Stream! { ws =>
163    ///         for await message in ws {
164    ///             yield message?;
165    ///         }
166    ///     }
167    /// }
168    ///
169    /// // Use a raw stream.
170    /// #[get("/echo?compose")]
171    /// fn echo_compose(ws: ws::WebSocket) -> ws::Stream!['static] {
172    ///     ws.stream(|io| io)
173    /// }
174    /// ```
175    pub fn stream<'r, F, S>(self, stream: F) -> MessageStream<'r, S>
176        where F: FnOnce(SplitStream<DuplexStream>) -> S + Send + 'r,
177              S: futures::Stream<Item = Result<Message>> + Send + 'r
178    {
179        MessageStream { ws: self, handler: Box::new(stream), }
180    }
181
182    /// Returns the server's fully computed and encoded WebSocket handshake
183    /// accept key.
184    ///
185    /// > The server takes the value of the `Sec-WebSocket-Key` sent in the
186    /// > handshake request, appends `258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,
187    /// > SHA-1 of the new value, and is then base64 encoded.
188    /// >
189    /// > -- [`Sec-WebSocket-Accept`]
190    ///
191    /// This is the value returned via the [`Sec-WebSocket-Accept`] header
192    /// during the acceptance response.
193    ///
194    /// [`Sec-WebSocket-Accept`]:
195    /// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-WebSocket-Accept
196    ///
197    /// # Example
198    ///
199    /// ```rust
200    /// # use rocket::get;
201    /// # use rocket_ws as ws;
202    /// #
203    /// #[get("/echo")]
204    /// fn echo_stream(ws: ws::WebSocket) -> ws::Stream!['static] {
205    ///     let accept_key = ws.accept_key();
206    ///     ws.stream(|io| io)
207    /// }
208    /// ```
209    pub fn accept_key(&self) -> &str {
210        &self.key
211    }
212
213}
214
215/// A streaming channel, returned by [`WebSocket::channel()`].
216///
217/// `Channel` has no methods or functionality beyond its trait implementations.
218pub struct Channel<'r> {
219    ws: WebSocket,
220    handler: Box<dyn FnOnce(DuplexStream) -> BoxFuture<'r, Result<()>> + Send + 'r>,
221}
222
223/// A [`Stream`](futures::Stream) of [`Message`]s, returned by
224/// [`WebSocket::stream()`], used via [`Stream!`].
225///
226/// This type should not be used directly. Instead, it is used via the
227/// [`Stream!`] macro, which expands to both the type itself and an expression
228/// which evaluates to this type. See [`Stream!`] for details.
229///
230/// [`Stream!`]: crate::Stream!
231// TODO: Get rid of this or `Channel` via a single `enum`.
232pub struct MessageStream<'r, S> {
233    ws: WebSocket,
234    handler: Box<dyn FnOnce(SplitStream<DuplexStream>) -> S + Send + 'r>
235}
236
237#[rocket::async_trait]
238impl<'r> FromRequest<'r> for WebSocket {
239    type Error = std::convert::Infallible;
240
241    async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
242        use crate::tungstenite::handshake::derive_accept_key;
243        use rocket::http::uncased::eq;
244
245        let headers = req.headers();
246        let is_upgrade = headers.get("Connection")
247            .any(|h| h.split(',').any(|v| eq(v.trim(), "upgrade")));
248
249        let is_ws = headers.get("Upgrade")
250            .any(|h| h.split(',').any(|v| eq(v.trim(), "websocket")));
251
252        let is_13 = headers.get_one("Sec-WebSocket-Version").map_or(false, |v| v == "13");
253        let key = headers.get_one("Sec-WebSocket-Key").filter(|key| {
254            key.len() == 24 && data_encoding::BASE64.decode(key.as_bytes())
255                .is_ok_and(|bytes| bytes.len() == 16)
256        }).map(|key| derive_accept_key(key.as_bytes()));
257        match key {
258            Some(key) if is_upgrade && is_ws && is_13 => Outcome::Success(WebSocket::new(key)),
259            Some(_) | None => Outcome::Forward(Status::BadRequest)
260        }
261    }
262}
263
264impl<'r, 'o: 'r> Responder<'r, 'o> for Channel<'o> {
265    fn respond_to(self, _: &'r Request<'_>) -> response::Result<'o> {
266        Response::build()
267            .raw_header("Sec-Websocket-Version", "13")
268            .raw_header("Sec-WebSocket-Accept", self.ws.key.clone())
269            .upgrade("websocket", self)
270            .ok()
271    }
272}
273
274impl<'r, 'o: 'r, S> Responder<'r, 'o> for MessageStream<'o, S>
275    where S: futures::Stream<Item = Result<Message>> + Send + 'o
276{
277    fn respond_to(self, _: &'r Request<'_>) -> response::Result<'o> {
278        Response::build()
279            .raw_header("Sec-Websocket-Version", "13")
280            .raw_header("Sec-WebSocket-Accept", self.ws.key.clone())
281            .upgrade("websocket", self)
282            .ok()
283    }
284}
285
286#[rocket::async_trait]
287impl IoHandler for Channel<'_> {
288    async fn io(self: Box<Self>, io: IoStream) -> io::Result<()> {
289        let stream = DuplexStream::new(io, self.ws.config, false).await;
290        let result = (self.handler)(stream).await;
291        handle_result(result).map(|_| ())
292    }
293}
294
295#[rocket::async_trait]
296impl<'r, S> IoHandler for MessageStream<'r, S>
297    where S: futures::Stream<Item = Result<Message>> + Send + 'r
298{
299    async fn io(self: Box<Self>, io: IoStream) -> io::Result<()> {
300        let (mut sink, source) = DuplexStream::new(io, self.ws.config, true).await.split();
301
302        // Drop the stream as soon as it yields a `Close` or ends.
303        let close = {
304            let stream = (self.handler)(source);
305            rocket::tokio::pin!(stream);
306            loop {
307                let result = match stream.next().await {
308                    Some(Ok(msg)) if msg.is_close() => break msg,
309                    Some(Ok(msg)) => sink.send(msg).await,
310                    Some(Err(e)) => Err(e),
311                    None => break Message::Close(None),
312                };
313
314                if !handle_result(result)? {
315                    return Ok(());
316                }
317            }
318        };
319
320        let closing = async {
321            match sink.send(close).await {
322                // Wait for the peer's reply.
323                Ok(()) => sink.close().await,
324                // The peer closed first. Flush the queued reply.
325                Err(Error::Protocol(SendAfterClosing)) => sink.flush().await,
326                // The closing handshake has already completed.
327                Err(Error::AlreadyClosed) => Ok(()),
328                Err(e) => Err(e),
329            }
330        };
331
332        // The stream has ended. A peer that's gone, I/O cancelled by shutdown,
333        // or a peer that doesn't reply in time ends the connection normally.
334        match rocket::tokio::time::timeout(CLOSE_TIMEOUT, closing).await {
335            Ok(Err(Error::Protocol(ResetWithoutClosingHandshake) | Error::Io(_))) => Ok(()),
336            Ok(result) => handle_result(result).map(|_| ()),
337            Err(_) => Ok(()),
338        }
339    }
340}
341
342/// Returns `Ok(true)` if processing should continue, `Ok(false)` if processing
343/// has terminated without error, and `Err(e)` if an error has occurred.
344fn handle_result(result: Result<()>) -> io::Result<bool> {
345    match result {
346        Ok(_) => Ok(true),
347        Err(Error::ConnectionClosed) => Ok(false),
348        Err(Error::Io(e)) => Err(e),
349        Err(e) => Err(io::Error::new(io::ErrorKind::Other, e))
350    }
351}