Skip to main content

turnloop_websocket/
lib.rs

1//! WebSocket protocol over in-memory Read/Write views, never sockets. HTTP upgrade
2//! heads come from turnloop-http; pass unconsumed upgrade bytes to `receive`.
3//! permessage-deflate is deliberately not negotiated (tungstenite has no support).
4//!
5//! # Getting started on turnloop
6//! Enable the `turnloop` feature for the `asynchronous` module. The embedding
7//! host owns `LocalExecutor` and calls `turn`; adapters await its streams and
8//! deadline futures. See the crate README and turnloop-io for ownership, streaming
9//! and cancellation examples. Default features retain the sans-I/O API.
10#![deny(unsafe_op_in_unsafe_fn)]
11#[cfg(all(target_os = "wasi", target_env = "p3"))]
12use turnloop_wasi_random as _;
13
14use base64::{Engine, engine::general_purpose::STANDARD};
15use std::{
16    io::{self, Read, Write},
17    time::Instant,
18};
19use tungstenite::protocol::WebSocketContext;
20pub use tungstenite::{
21    Error, Message,
22    protocol::{CloseFrame, Role, WebSocketConfig},
23};
24use turnloop_http::{
25    Error as HttpError,
26    http1::{Head, Header},
27};
28struct Memory<'a> {
29    input: &'a [u8],
30    output: &'a mut Vec<u8>,
31    read: usize,
32}
33impl Read for Memory<'_> {
34    fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
35        if out.is_empty() {
36            return Ok(0);
37        }
38        if self.input.is_empty() {
39            return Err(io::ErrorKind::WouldBlock.into());
40        }
41        let n = out.len().min(self.input.len());
42        out[..n].copy_from_slice(&self.input[..n]);
43        self.input = &self.input[n..];
44        self.read += n;
45        Ok(n)
46    }
47}
48impl Write for Memory<'_> {
49    fn write(&mut self, input: &[u8]) -> io::Result<usize> {
50        self.output.extend_from_slice(input);
51        Ok(input.len())
52    }
53    fn flush(&mut self) -> io::Result<()> {
54        Ok(())
55    }
56}
57pub struct Connection {
58    context: WebSocketContext,
59    deadline: Option<Instant>,
60    terminal: bool,
61    peer_close: Option<u16>,
62}
63/// One [`Connection::receive`] step: how much of `input` was taken, and the
64/// message it completed, if any.
65///
66/// **`consumed` and `message` are independent**, as they are for
67/// `turnloop_http`'s `Step`. `receive` reads input into the connection's own
68/// buffer and parses from that buffer before it reads again, so the bytes a
69/// message is made of may have been consumed by an earlier call:
70///
71/// | `consumed` | `message` | meaning |
72/// |---|---|---|
73/// | `0` | `None` | **stop.** Nothing complete is buffered and the input is empty; read more from the transport before calling again. |
74/// | `> 0` | `None` | **keep going.** The input was taken in, all of it, but completes no message yet: a partial frame, or a non-final fragment. The next call returns the stop shape unless more input arrived. |
75/// | `> 0` | `Some` | a message, possibly with input left over. |
76/// | `0` | `Some` | a message completed from bytes an earlier call consumed - the second of two frames that arrived in one read, say. Normal, and easy to drop. |
77///
78/// So the loop condition is the same one-liner, `consumed > 0 ||
79/// message.is_some()`:
80///
81/// ```
82/// # use turnloop_websocket::*;
83/// # let mut connection = Connection::new(Role::Server, WebSocketConfig::default());
84/// # let (mut input, mut replies) = (Vec::new(), Vec::new());
85/// loop {
86///     let step = connection.receive(&input, &mut replies)?;
87///     input.drain(..step.consumed);
88///     let progressed = step.consumed > 0 || step.message.is_some();
89///     if let Some(message) = step.message {
90///         let _ = message;
91///     }
92///     connection.flush(&mut replies)?; // automatic pong/close replies
93///     if !progressed {
94///         break; // read more bytes from the transport, then continue
95///     }
96/// }
97/// # Ok::<(), Error>(())
98/// ```
99///
100/// Looping while `consumed > 0` **drops messages**: the `0`/`Some` step reads
101/// as "stop" and its message is never looked at. Reading the transport
102/// whenever `input` is empty **stalls** on the same step: no input is left,
103/// yet a message is waiting, and a peer waiting for its answer never sends
104/// the bytes that would wake the host. Looping while a message came back is,
105/// for this type, safe - a step with no message has always taken in all of
106/// its input, so nothing is stranded - but it is not the documented
107/// condition, and the one above works for every step type in the workspace.
108///
109/// `receive` is not idempotent. The `consumed` bytes are in the connection's
110/// buffer once it returns, so input that is fed again without being drained
111/// is parsed again: a complete message in it is delivered twice, with no
112/// error to notice.
113pub struct Received {
114    pub consumed: usize,
115    pub message: Option<Message>,
116}
117impl Connection {
118    pub fn new(role: Role, config: WebSocketConfig) -> Self {
119        Self {
120            context: WebSocketContext::new(role, Some(config)),
121            deadline: None,
122            terminal: false,
123            peer_close: None,
124        }
125    }
126    /// One decode step. `consumed` and `message` are independent, and
127    /// `consumed == 0` does not by itself mean "stop": see [`Received`].
128    pub fn receive(&mut self, input: &[u8], output: &mut Vec<u8>) -> Result<Received, Error> {
129        if self.terminal {
130            return Err(Error::AlreadyClosed);
131        }
132        let mut memory = Memory {
133            input,
134            output,
135            read: 0,
136        };
137        let message = match self.context.read(&mut memory) {
138            Ok(message) => {
139                if let Message::Close(frame) = &message {
140                    self.peer_close = Some(frame.as_ref().map_or(1005, |f| u16::from(f.code)));
141                    self.deadline = None;
142                }
143                Some(message)
144            }
145            Err(Error::Io(e)) if e.kind() == io::ErrorKind::WouldBlock => None,
146            Err(e) => {
147                self.terminal = true;
148                return Err(e);
149            }
150        };
151        Ok(Received {
152            consumed: memory.read,
153            message,
154        })
155    }
156    pub fn send(&mut self, message: Message, output: &mut Vec<u8>) -> Result<(), Error> {
157        if self.terminal {
158            return Err(Error::AlreadyClosed);
159        }
160        let mut memory = Memory {
161            input: &[],
162            output,
163            read: 0,
164        };
165        self.context.write(&mut memory, message)?;
166        self.context.flush(&mut memory)
167    }
168    /// Flush automatic pong/close replies after consuming an incoming message.
169    pub fn flush(&mut self, output: &mut Vec<u8>) -> Result<(), Error> {
170        if self.terminal {
171            return Err(Error::AlreadyClosed);
172        }
173        let mut memory = Memory {
174            input: &[],
175            output,
176            read: 0,
177        };
178        let result = self.context.flush(&mut memory);
179        if matches!(result, Err(Error::ConnectionClosed | Error::AlreadyClosed)) {
180            self.terminal = true;
181            self.deadline = None;
182        }
183        result
184    }
185    pub fn close(
186        &mut self,
187        frame: Option<CloseFrame>,
188        deadline: Instant,
189        output: &mut Vec<u8>,
190    ) -> Result<(), Error> {
191        let mut memory = Memory {
192            input: &[],
193            output,
194            read: 0,
195        };
196        self.context.close(&mut memory, frame)?;
197        self.deadline = Some(deadline);
198        Ok(())
199    }
200    pub fn next_timeout(&self) -> Option<Instant> {
201        if self.terminal { None } else { self.deadline }
202    }
203    pub fn handle_timeout(&mut self, now: Instant) -> Option<u16> {
204        if self.next_timeout().is_some_and(|d| d <= now) {
205            self.terminal = true;
206            self.deadline = None;
207            Some(1006)
208        } else {
209            None
210        }
211    }
212    pub fn eof(&mut self) -> Option<u16> {
213        if self.terminal {
214            None
215        } else {
216            self.terminal = true;
217            self.peer_close.or(Some(1006))
218        }
219    }
220}
221fn invalid(message: &'static str) -> HttpError {
222    HttpError::new("WS_ERR_INVALID_HANDSHAKE", message)
223}
224fn unique<'a>(head: &'a Head, name: &str) -> Result<&'a [u8], HttpError> {
225    let mut values = head
226        .headers
227        .iter()
228        .filter(|h| h.name.eq_ignore_ascii_case(name));
229    let value = values.next().ok_or(invalid("missing handshake header"))?;
230    if values.next().is_some() {
231        return Err(invalid("duplicate handshake header"));
232    }
233    Ok(&value.value)
234}
235fn protocol_token(value: &str) -> bool {
236    !value.is_empty()
237        && value
238            .bytes()
239            .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b))
240}
241pub struct ClientHandshake {
242    key: String,
243    protocols: Vec<String>,
244}
245impl ClientHandshake {
246    /// The host supplies a fresh cryptographic random nonce.
247    pub fn new(
248        host: &str,
249        target: &str,
250        nonce: [u8; 16],
251        protocols: Vec<String>,
252    ) -> Result<(Self, Head), HttpError> {
253        for (i, p) in protocols.iter().enumerate() {
254            if !protocol_token(p) || protocols[..i].contains(p) {
255                return Err(invalid("invalid or duplicate subprotocol"));
256            }
257        }
258        let key = STANDARD.encode(nonce);
259        let mut headers = vec![
260            Header::new("host", host),
261            Header::new("connection", "Upgrade"),
262            Header::new("upgrade", "websocket"),
263            Header::new("sec-websocket-version", "13"),
264            Header::new("sec-websocket-key", &key),
265        ];
266        if !protocols.is_empty() {
267            headers.push(Header::new("sec-websocket-protocol", protocols.join(", ")));
268        }
269        Ok((
270            Self { key, protocols },
271            Head {
272                method: "GET".into(),
273                target: target.into(),
274                status: 0,
275                version: 1,
276                headers,
277                keep_alive: true,
278            },
279        ))
280    }
281    pub fn verify(&self, response: &Head) -> Result<Option<String>, HttpError> {
282        if response.status != 101
283            || response.version != 1
284            || !response.token("connection", "upgrade")
285            || !unique(response, "upgrade")?.eq_ignore_ascii_case(b"websocket")
286        {
287            return Err(invalid("invalid upgrade response"));
288        }
289        if unique(response, "sec-websocket-accept")?
290            != tungstenite::handshake::derive_accept_key(self.key.as_bytes()).as_bytes()
291        {
292            return Err(invalid("invalid accept key"));
293        }
294        if response.get("sec-websocket-extensions").is_some() {
295            return Err(invalid("unsolicited extension"));
296        }
297        if response.get("sec-websocket-protocol").is_some() {
298            let protocol = std::str::from_utf8(unique(response, "sec-websocket-protocol")?)
299                .map_err(|_| invalid("invalid protocol"))?;
300            if !self.protocols.iter().any(|p| p == protocol) {
301                return Err(invalid("unsolicited subprotocol"));
302            }
303            Ok(Some(protocol.into()))
304        } else if !self.protocols.is_empty() {
305            Err(invalid("server did not select subprotocol"))
306        } else {
307            Ok(None)
308        }
309    }
310}
311pub fn accept(request: &Head, protocols: &[&str]) -> Result<(Head, Option<String>), HttpError> {
312    if request.method != "GET"
313        || request.version != 1
314        || !request.token("connection", "upgrade")
315        || !unique(request, "upgrade")?.eq_ignore_ascii_case(b"websocket")
316        || unique(request, "sec-websocket-version")? != b"13"
317    {
318        return Err(invalid("invalid upgrade request"));
319    }
320    let key = unique(request, "sec-websocket-key")?;
321    let mut decoded = [0; 18];
322    if STANDARD
323        .decode_slice(key, &mut decoded)
324        .map_err(|_| invalid("invalid key"))?
325        != 16
326    {
327        return Err(invalid("invalid key length"));
328    }
329    let offered = request
330        .get("sec-websocket-protocol")
331        .map(std::str::from_utf8)
332        .transpose()
333        .map_err(|_| invalid("invalid protocol"))?
334        .unwrap_or("");
335    if !offered.is_empty() {
336        let mut seen = Vec::new();
337        for p in offered.split(',').map(str::trim) {
338            if !protocol_token(p) || seen.contains(&p) {
339                return Err(invalid("invalid or duplicate subprotocol"));
340            }
341            seen.push(p);
342        }
343    }
344    let selected = protocols
345        .iter()
346        .find(|p| offered.split(',').map(str::trim).any(|x| x == **p))
347        .map(|p| p.to_string());
348    let mut headers = vec![
349        Header::new("connection", "Upgrade"),
350        Header::new("upgrade", "websocket"),
351        Header::new(
352            "sec-websocket-accept",
353            tungstenite::handshake::derive_accept_key(key),
354        ),
355    ];
356    if let Some(p) = &selected {
357        headers.push(Header::new("sec-websocket-protocol", p));
358    }
359    Ok((
360        Head {
361            method: String::new(),
362            target: String::new(),
363            status: 101,
364            version: 1,
365            headers,
366            keep_alive: false,
367        },
368        selected,
369    ))
370}
371pub fn node_error_code(error: &Error) -> &'static str {
372    match error {
373        Error::Capacity(_) => "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",
374        Error::Utf8(_) => "WS_ERR_INVALID_UTF8",
375        Error::Protocol(_) => "WS_ERR_PROTOCOL_ERROR",
376        Error::ConnectionClosed | Error::AlreadyClosed => "WS_ERR_CLOSED",
377        _ => "WS_ERR_SOCKET",
378    }
379}
380
381#[cfg(feature = "turnloop")]
382pub mod asynchronous;
383#[cfg(feature = "turnloop")]
384pub use asynchronous::WebSocketStream;