Skip to main content

rust_web_server/websocket/
connection.rs

1//! WebSocket endpoints in an ordinary handler: [`WebSocket::upgrade`]
2//! returns the `101 Switching Protocols` response, and once the server has
3//! sent it, the connection goes to the handler as a [`WebSocketConnection`]
4//! on a thread of its own (tokio's blocking pool in async builds, a new
5//! thread in the `http1` build). HTTP/1.1 only: an HTTP/2 or HTTP/3 request
6//! can't upgrade and gets `426 Upgrade Required`.
7//!
8//! How the handler reaches the server: the response carries an internal
9//! header with a random token, and the handler waits under that token in a
10//! process-wide table. The server removes the header, takes the handler and
11//! hands it the socket (with any bytes the client sent after the request).
12//! A response that never reaches a client (replaced by a middleware) leaves
13//! its handler behind for at most [`UPGRADE_TTL`]. An upstream can't use
14//! the header: tokens are random, and unknown ones do nothing.
15
16use std::collections::HashMap;
17use std::hash::{BuildHasher, Hasher};
18use std::io::{Read, Write};
19use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
20use std::sync::{Arc, Mutex, OnceLock};
21use std::time::{Duration, Instant};
22
23use super::{close_payload, encode_frame, read_raw_frame, Frame, RawFrame, WebSocket};
24use crate::core::New;
25use crate::header::Header;
26use crate::request::Request;
27use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
28
29/// The internal header carrying the token from handler to server.
30const UPGRADE_HEADER: &str = "X-Rws-WebSocket-Upgrade";
31/// How long a handler waits for its response to be sent.
32pub const UPGRADE_TTL: Duration = Duration::from_secs(60);
33/// The default limit on one message (all its fragments): 16 MiB.
34pub const MAX_MESSAGE: usize = 16 * 1024 * 1024;
35
36/// Runs on the upgraded connection's reader and writer.
37type Handler = Box<dyn FnOnce(Box<dyn Read + Send>, Box<dyn Write + Send>) + Send>;
38
39/// A complete message from the client: fragments joined, text checked to
40/// be UTF-8.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum Message {
43    Text(String),
44    Binary(Vec<u8>),
45}
46
47/// An upgraded connection. [`recv`](Self::recv) returns the client's
48/// messages, answering pings and the closing handshake itself; send with
49/// the methods here or a [`WebSocketSender`] from [`sender`](Self::sender),
50/// which another thread can use while this one waits in `recv`.
51pub struct WebSocketConnection {
52    reader: Box<dyn Read + Send>,
53    sender: WebSocketSender,
54    max_message: usize,
55    closed: bool,
56}
57
58/// Sends to one WebSocket client; cheap to clone, usable from any thread.
59#[derive(Clone)]
60pub struct WebSocketSender {
61    writer: Arc<Mutex<Box<dyn Write + Send>>>,
62    closed: Arc<AtomicBool>,
63}
64
65impl WebSocketSender {
66    fn send(&self, frame: Frame) -> Result<(), String> {
67        let closing = matches!(frame, Frame::Close(..));
68        if self.closed.load(Ordering::Acquire) {
69            return Err("the WebSocket is closed".to_string());
70        }
71        if closing {
72            self.closed.store(true, Ordering::Release);
73        }
74        let bytes = encode_frame(frame);
75        let mut writer = self.writer.lock().unwrap_or_else(|e| e.into_inner());
76        writer.write_all(&bytes).and_then(|_| writer.flush()).map_err(|e| format!("write error: {e}"))
77    }
78
79    /// Send a text message.
80    pub fn send_text(&self, text: &str) -> Result<(), String> {
81        self.send(Frame::Text(text.to_string()))
82    }
83
84    /// Send a binary message.
85    pub fn send_binary(&self, data: &[u8]) -> Result<(), String> {
86        self.send(Frame::Binary(data.to_vec()))
87    }
88
89    /// Send a ping (at most 125 bytes); the client's pong is consumed by
90    /// [`WebSocketConnection::recv`].
91    pub fn ping(&self, payload: &[u8]) -> Result<(), String> {
92        if payload.len() > 125 {
93            return Err("a ping payload is at most 125 bytes".to_string());
94        }
95        self.send(Frame::Ping(payload.to_vec()))
96    }
97
98    /// Start the closing handshake with `code` (1000 = normal) and `reason`;
99    /// nothing more can be sent after it.
100    pub fn close(&self, code: u16, reason: &str) -> Result<(), String> {
101        self.send(Frame::Close(Some(code), reason.to_string()))
102    }
103
104    /// Whether a close frame was sent (by either side's handshake).
105    pub fn is_closed(&self) -> bool {
106        self.closed.load(Ordering::Acquire)
107    }
108}
109
110/// A close code the client may send (RFC 6455 §7.4).
111fn valid_close_code(code: u16) -> bool {
112    matches!(code, 1000..=1003 | 1007..=1011 | 3000..=4999)
113}
114
115impl WebSocketConnection {
116    /// A connection over `reader` (client → server) and `writer`.
117    pub(crate) fn new(reader: Box<dyn Read + Send>, writer: Box<dyn Write + Send>) -> Self {
118        WebSocketConnection {
119            reader,
120            sender: WebSocketSender { writer: Arc::new(Mutex::new(writer)), closed: Arc::new(AtomicBool::new(false)) },
121            max_message: MAX_MESSAGE,
122            closed: false,
123        }
124    }
125
126    /// Refuse messages over `bytes` (default [`MAX_MESSAGE`]) with close
127    /// code 1009.
128    pub fn max_message_size(mut self, bytes: usize) -> Self {
129        self.max_message = bytes;
130        self
131    }
132
133    /// A sender for this connection, for other threads.
134    pub fn sender(&self) -> WebSocketSender {
135        self.sender.clone()
136    }
137
138    /// Send a text message.
139    pub fn send_text(&self, text: &str) -> Result<(), String> {
140        self.sender.send_text(text)
141    }
142
143    /// Send a binary message.
144    pub fn send_binary(&self, data: &[u8]) -> Result<(), String> {
145        self.sender.send_binary(data)
146    }
147
148    /// Start the closing handshake; [`recv`](Self::recv) then returns
149    /// `Ok(None)` when the client answers.
150    pub fn close(&self, code: u16, reason: &str) -> Result<(), String> {
151        self.sender.close(code, reason)
152    }
153
154    /// Fail the connection: a close frame with `code`, then `Err(reason)`.
155    fn fail<T>(&mut self, code: u16, reason: String) -> Result<T, String> {
156        self.closed = true;
157        let _ = self.sender.close(code, "");
158        Err(reason)
159    }
160
161    /// The next message; `Ok(None)` once the connection closed cleanly
162    /// (the closing handshake done, whoever started it). Pings are
163    /// answered and pongs dropped on the way. A protocol error — an
164    /// unmasked frame, a bad fragment, invalid UTF-8, an oversized message
165    /// — closes the connection with the matching code and is returned as
166    /// `Err`, as is the client disappearing without a close frame.
167    pub fn recv(&mut self) -> Result<Option<Message>, String> {
168        if self.closed {
169            return Ok(None);
170        }
171        let mut message: Option<(u8, Vec<u8>)> = None;
172        loop {
173            let assembled = message.as_ref().map_or(0, |(_, data)| data.len());
174            let limit = self.max_message.saturating_sub(assembled) as u64;
175            let RawFrame { fin, rsv, opcode, masked, payload } = match read_raw_frame(&mut self.reader, limit) {
176                Ok(frame) => frame,
177                Err(e) if e.contains("exceeds") => return self.fail(1009, format!("message over {} bytes", self.max_message)),
178                Err(e) => {
179                    self.closed = true;
180                    return Err(e);
181                }
182            };
183            if rsv != 0 {
184                return self.fail(1002, "reserved bits set (no extension was negotiated)".to_string());
185            }
186            if !masked {
187                return self.fail(1002, "a client frame wasn't masked".to_string());
188            }
189            if opcode >= 0x8 && (!fin || payload.len() > 125) {
190                return self.fail(1002, "a control frame was fragmented or over 125 bytes".to_string());
191            }
192            match opcode {
193                0x8 => {
194                    let (code, _) = match close_payload(&payload) {
195                        Ok(close) => close,
196                        Err(e) => return self.fail(1007, e),
197                    };
198                    if payload.len() == 1 || code.is_some_and(|c| !valid_close_code(c)) {
199                        return self.fail(1002, format!("invalid close code {code:?}"));
200                    }
201                    self.closed = true;
202                    // Answer the client's close, unless this ends ours.
203                    if !self.sender.is_closed() {
204                        let _ = self.sender.close(code.unwrap_or(1000), "");
205                    }
206                    return Ok(None);
207                }
208                0x9 => {
209                    let _ = self.sender.send(Frame::Pong(payload));
210                }
211                0xA => {}
212                0x1 | 0x2 if message.is_some() => return self.fail(1002, "a new message began inside a fragmented one".to_string()),
213                0x1 | 0x2 => message = Some((opcode, payload)),
214                0x0 => match message.as_mut() {
215                    Some((_, data)) => data.extend_from_slice(&payload),
216                    None => return self.fail(1002, "a continuation frame with no message".to_string()),
217                },
218                other => return self.fail(1002, format!("unknown opcode 0x{other:X}")),
219            }
220            if fin && opcode < 0x8 {
221                let Some((kind, data)) = message.take() else { continue };
222                return match kind {
223                    0x1 => match String::from_utf8(data) {
224                        Ok(text) => Ok(Some(Message::Text(text))),
225                        Err(_) => self.fail(1007, "a text message isn't UTF-8".to_string()),
226                    },
227                    _ => Ok(Some(Message::Binary(data))),
228                };
229            }
230        }
231    }
232}
233
234// ── Upgrade ───────────────────────────────────────────────────────────────────
235
236/// A handler waiting for its connection.
237pub(crate) struct Upgrade(Handler);
238
239impl Upgrade {
240    /// Run the handler on `reader` / `writer` (blocks for the connection's
241    /// life).
242    pub(crate) fn run(self, reader: Box<dyn Read + Send>, writer: Box<dyn Write + Send>) {
243        (self.0)(reader, writer)
244    }
245}
246
247fn waiting() -> &'static Mutex<HashMap<String, (Instant, Handler)>> {
248    static WAITING: OnceLock<Mutex<HashMap<String, (Instant, Handler)>>> = OnceLock::new();
249    WAITING.get_or_init(Default::default)
250}
251
252/// 128 random bits as hex: SipHash with the process's random keys over a
253/// counter and the time.
254fn token() -> String {
255    static KEYS: OnceLock<std::collections::hash_map::RandomState> = OnceLock::new();
256    static COUNTER: AtomicU64 = AtomicU64::new(0);
257    let keys = KEYS.get_or_init(Default::default);
258    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
259    let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
260    let half = |salt: u8| {
261        let mut hasher = keys.build_hasher();
262        hasher.write_u8(salt);
263        hasher.write_u64(n);
264        hasher.write_u128(nanos);
265        hasher.finish()
266    };
267    format!("{:016x}{:016x}", half(1), half(2))
268}
269
270impl WebSocket {
271    /// Answer a WebSocket upgrade request: returns the `101` response to
272    /// return from the handler, and runs `handler` with the connection once
273    /// it's sent. A request that isn't a valid upgrade (or comes over HTTP/2
274    /// or HTTP/3) gets `426 Upgrade Required` and `handler` never runs.
275    ///
276    /// ```rust,no_run
277    /// use rust_web_server::app::App;
278    /// use rust_web_server::websocket::{Message, WebSocket};
279    ///
280    /// let app = App::with_state(()).get("/echo", |request, _params, _conn, _state| {
281    ///     WebSocket::upgrade(request, |mut ws| {
282    ///         while let Ok(Some(message)) = ws.recv() {
283    ///             let _ = match message {
284    ///                 Message::Text(text) => ws.send_text(&text),
285    ///                 Message::Binary(data) => ws.send_binary(&data),
286    ///             };
287    ///         }
288    ///     })
289    /// });
290    /// ```
291    pub fn upgrade<F>(request: &Request, handler: F) -> Response
292    where
293        F: FnOnce(WebSocketConnection) + Send + 'static,
294    {
295        let version = request.header("Sec-WebSocket-Version").map(|h| h.value.trim().to_string()).unwrap_or_default();
296        let mut response = match WebSocket::handshake_response(request) {
297            Ok(response) if Self::is_upgrade_request(request) && version == "13" && request.method == "GET" => response,
298            _ => {
299                let mut refused = Response::new();
300                refused.status_code = *STATUS_CODE_REASON_PHRASE.n426_upgrade_required.status_code;
301                refused.reason_phrase = STATUS_CODE_REASON_PHRASE.n426_upgrade_required.reason_phrase.to_string();
302                refused.headers.push(Header { name: "Upgrade".into(), value: "websocket".into() });
303                refused.headers.push(Header { name: "Sec-WebSocket-Version".into(), value: "13".into() });
304                return refused;
305            }
306        };
307        Self::register(&mut response, Box::new(move |reader, writer| handler(WebSocketConnection::new(reader, writer))));
308        response
309    }
310
311    /// Put `handler` behind `response` (a `101`): the server gives it the
312    /// raw connection once the response is sent.
313    fn register(response: &mut Response, handler: Handler) {
314        let token = token();
315        let mut waiting = waiting().lock().unwrap_or_else(|e| e.into_inner());
316        let now = Instant::now();
317        waiting.retain(|_, (since, _)| now.duration_since(*since) < UPGRADE_TTL);
318        waiting.insert(token.clone(), (now, handler));
319        response.headers.push(Header { name: UPGRADE_HEADER.into(), value: token.into() });
320    }
321
322    /// Like [`WebSocket::upgrade`] for a proxy: `response` is the backend's
323    /// `101`, and `relay` gets the client connection's raw bytes.
324    #[cfg(feature = "gateway-api")]
325    pub(crate) fn upgrade_raw<F>(mut response: Response, relay: F) -> Response
326    where
327        F: FnOnce(Box<dyn Read + Send>, Box<dyn Write + Send>) + Send + 'static,
328    {
329        Self::register(&mut response, Box::new(relay));
330        response
331    }
332}
333
334/// The handler waiting for `response`, if it's a `101` from
335/// [`WebSocket::upgrade`]; the internal header is removed either way.
336pub(crate) fn take_upgrade(response: &mut Response) -> Option<Upgrade> {
337    let at = response.headers.iter().position(|h| h.name.eq_ignore_ascii_case(UPGRADE_HEADER))?;
338    let token = response.headers.remove(at).value;
339    if response.status_code != 101 {
340        return None;
341    }
342    let (_, handler) = waiting().lock().unwrap_or_else(|e| e.into_inner()).remove(token.as_ref())?;
343    Some(Upgrade(handler))
344}
345
346/// The `101` response head as sent: the status line and the response's
347/// headers — no body, no `Content-Length` (RFC 9110 §8.6).
348pub(crate) fn upgrade_head(response: &Response) -> Vec<u8> {
349    let mut head = format!("HTTP/1.1 101 {}\r\n", response.reason_phrase);
350    for header in &response.headers {
351        if header.name.eq_ignore_ascii_case("content-length") || header.name.eq_ignore_ascii_case("transfer-encoding") {
352            continue;
353        }
354        head.push_str(&header.name);
355        head.push_str(": ");
356        head.push_str(&header.value);
357        head.push_str("\r\n");
358    }
359    head.push_str("\r\n");
360    head.into_bytes()
361}
362
363/// Blocking `Read`/`Write` over one half of an async stream, for a handler
364/// on the blocking pool.
365#[cfg(feature = "http2")]
366struct Blocking<T> {
367    inner: T,
368    handle: tokio::runtime::Handle,
369}
370
371#[cfg(feature = "http2")]
372impl<T: tokio::io::AsyncRead + Unpin> Read for Blocking<T> {
373    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
374        self.handle.block_on(tokio::io::AsyncReadExt::read(&mut self.inner, buf))
375    }
376}
377
378#[cfg(feature = "http2")]
379impl<T: tokio::io::AsyncWrite + Unpin> Write for Blocking<T> {
380    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
381        self.handle.block_on(tokio::io::AsyncWriteExt::write(&mut self.inner, buf))
382    }
383
384    fn flush(&mut self) -> std::io::Result<()> {
385        self.handle.block_on(tokio::io::AsyncWriteExt::flush(&mut self.inner))
386    }
387}
388
389/// Give an async connection (plain or TLS) to `upgrade` on the blocking
390/// pool, `pending` (bytes already read past the request) first.
391#[cfg(feature = "http2")]
392pub(crate) fn hand_over_async<S>(stream: S, pending: Vec<u8>, upgrade: Upgrade)
393where
394    S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + 'static,
395{
396    let handle = tokio::runtime::Handle::current();
397    let (read, write) = tokio::io::split(stream);
398    let reader = std::io::Cursor::new(pending).chain(Blocking { inner: read, handle: handle.clone() });
399    let writer = Blocking { inner: write, handle };
400    tokio::task::spawn_blocking(move || upgrade.run(Box::new(reader), Box::new(writer)));
401}