Skip to main content

rocket_ws/
websocket.rs

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