tungstenite/protocol/
mod.rs

1//! Generic WebSocket message stream.
2
3pub mod frame;
4
5mod message;
6
7pub use self::{frame::CloseFrame, message::Message};
8
9use self::{
10    frame::{
11        coding::{CloseCode, Control as OpCtl, Data as OpData, OpCode},
12        Frame, FrameCodec,
13    },
14    message::{IncompleteMessage, MessageType},
15};
16use crate::{
17    error::{CapacityError, Error, ProtocolError, Result},
18    protocol::frame::Utf8Bytes,
19};
20use log::*;
21use std::{
22    io::{self, Read, Write},
23    mem::replace,
24};
25
26/// Indicates a Client or Server role of the websocket
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Role {
29    /// This socket is a server
30    Server,
31    /// This socket is a client
32    Client,
33}
34
35/// The configuration for WebSocket connection.
36///
37/// # Example
38/// ```
39/// # use tungstenite::protocol::WebSocketConfig;;
40/// let conf = WebSocketConfig::default()
41///     .read_buffer_size(256 * 1024)
42///     .write_buffer_size(256 * 1024);
43/// ```
44#[derive(Debug, Clone, Copy)]
45#[non_exhaustive]
46pub struct WebSocketConfig {
47    /// Read buffer capacity. This buffer is eagerly allocated and used for receiving
48    /// messages.
49    ///
50    /// For high read load scenarios a larger buffer, e.g. 128 KiB, improves performance.
51    ///
52    /// For scenarios where you expect a lot of connections and don't need high read load
53    /// performance a smaller buffer, e.g. 4 KiB, would be appropriate to lower total
54    /// memory usage.
55    ///
56    /// The default value is 128 KiB.
57    pub read_buffer_size: usize,
58    /// The target minimum size of the write buffer to reach before writing the data
59    /// to the underlying stream.
60    /// The default value is 128 KiB.
61    ///
62    /// If set to `0` each message will be eagerly written to the underlying stream.
63    /// It is often more optimal to allow them to buffer a little, hence the default value.
64    ///
65    /// Note: [`flush`](WebSocket::flush) will always fully write the buffer regardless.
66    pub write_buffer_size: usize,
67    /// The max size of the write buffer in bytes. Setting this can provide backpressure
68    /// in the case the write buffer is filling up due to write errors.
69    /// The default value is unlimited.
70    ///
71    /// Note: The write buffer only builds up past [`write_buffer_size`](Self::write_buffer_size)
72    /// when writes to the underlying stream are failing. So the **write buffer can not
73    /// fill up if you are not observing write errors even if not flushing**.
74    ///
75    /// Note: Should always be at least [`write_buffer_size + 1 message`](Self::write_buffer_size)
76    /// and probably a little more depending on error handling strategy.
77    pub max_write_buffer_size: usize,
78    /// The maximum size of an incoming message. `None` means no size limit. The default value is 64 MiB
79    /// which should be reasonably big for all normal use-cases but small enough to prevent
80    /// memory eating by a malicious user.
81    pub max_message_size: Option<usize>,
82    /// The maximum size of a single incoming message frame. `None` means no size limit. The limit is for
83    /// frame payload NOT including the frame header. The default value is 16 MiB which should
84    /// be reasonably big for all normal use-cases but small enough to prevent memory eating
85    /// by a malicious user.
86    pub max_frame_size: Option<usize>,
87    /// When set to `true`, the server will accept and handle unmasked frames
88    /// from the client. According to the RFC 6455, the server must close the
89    /// connection to the client in such cases, however it seems like there are
90    /// some popular libraries that are sending unmasked frames, ignoring the RFC.
91    /// By default this option is set to `false`, i.e. according to RFC 6455.
92    pub accept_unmasked_frames: bool,
93}
94
95impl Default for WebSocketConfig {
96    fn default() -> Self {
97        Self {
98            read_buffer_size: 128 * 1024,
99            write_buffer_size: 128 * 1024,
100            max_write_buffer_size: usize::MAX,
101            max_message_size: Some(64 << 20),
102            max_frame_size: Some(16 << 20),
103            accept_unmasked_frames: false,
104        }
105    }
106}
107
108impl WebSocketConfig {
109    /// Set [`Self::read_buffer_size`].
110    pub fn read_buffer_size(mut self, read_buffer_size: usize) -> Self {
111        self.read_buffer_size = read_buffer_size;
112        self
113    }
114
115    /// Set [`Self::write_buffer_size`].
116    pub fn write_buffer_size(mut self, write_buffer_size: usize) -> Self {
117        self.write_buffer_size = write_buffer_size;
118        self
119    }
120
121    /// Set [`Self::max_write_buffer_size`].
122    pub fn max_write_buffer_size(mut self, max_write_buffer_size: usize) -> Self {
123        self.max_write_buffer_size = max_write_buffer_size;
124        self
125    }
126
127    /// Set [`Self::max_message_size`].
128    pub fn max_message_size(mut self, max_message_size: Option<usize>) -> Self {
129        self.max_message_size = max_message_size;
130        self
131    }
132
133    /// Set [`Self::max_frame_size`].
134    pub fn max_frame_size(mut self, max_frame_size: Option<usize>) -> Self {
135        self.max_frame_size = max_frame_size;
136        self
137    }
138
139    /// Set [`Self::accept_unmasked_frames`].
140    pub fn accept_unmasked_frames(mut self, accept_unmasked_frames: bool) -> Self {
141        self.accept_unmasked_frames = accept_unmasked_frames;
142        self
143    }
144
145    /// Panic if values are invalid.
146    pub(crate) fn assert_valid(&self) {
147        assert!(
148            self.max_write_buffer_size > self.write_buffer_size,
149            "WebSocketConfig::max_write_buffer_size must be greater than write_buffer_size, \
150            see WebSocketConfig docs`"
151        );
152    }
153}
154
155/// WebSocket input-output stream.
156///
157/// This is THE structure you want to create to be able to speak the WebSocket protocol.
158/// It may be created by calling `connect`, `accept` or `client` functions.
159///
160/// Use [`WebSocket::read`], [`WebSocket::send`] to received and send messages.
161#[derive(Debug)]
162pub struct WebSocket<Stream> {
163    /// The underlying socket.
164    socket: Stream,
165    /// The context for managing a WebSocket.
166    context: WebSocketContext,
167}
168
169impl<Stream> WebSocket<Stream> {
170    /// Convert a raw socket into a WebSocket without performing a handshake.
171    ///
172    /// Call this function if you're using Tungstenite as a part of a web framework
173    /// or together with an existing one. If you need an initial handshake, use
174    /// `connect()` or `accept()` functions of the crate to construct a websocket.
175    ///
176    /// # Panics
177    /// Panics if config is invalid e.g. `max_write_buffer_size <= write_buffer_size`.
178    pub fn from_raw_socket(stream: Stream, role: Role, config: Option<WebSocketConfig>) -> Self {
179        WebSocket { socket: stream, context: WebSocketContext::new(role, config) }
180    }
181
182    /// Convert a raw socket into a WebSocket without performing a handshake.
183    ///
184    /// Call this function if you're using Tungstenite as a part of a web framework
185    /// or together with an existing one. If you need an initial handshake, use
186    /// `connect()` or `accept()` functions of the crate to construct a websocket.
187    ///
188    /// # Panics
189    /// Panics if config is invalid e.g. `max_write_buffer_size <= write_buffer_size`.
190    pub fn from_partially_read(
191        stream: Stream,
192        part: Vec<u8>,
193        role: Role,
194        config: Option<WebSocketConfig>,
195    ) -> Self {
196        WebSocket {
197            socket: stream,
198            context: WebSocketContext::from_partially_read(part, role, config),
199        }
200    }
201
202    /// Consumes the `WebSocket` and returns the underlying stream.
203    pub fn into_inner(self) -> Stream {
204        self.socket
205    }
206
207    /// Returns a shared reference to the inner stream.
208    pub fn get_ref(&self) -> &Stream {
209        &self.socket
210    }
211    /// Returns a mutable reference to the inner stream.
212    pub fn get_mut(&mut self) -> &mut Stream {
213        &mut self.socket
214    }
215
216    /// Change the configuration.
217    ///
218    /// # Panics
219    /// Panics if config is invalid e.g. `max_write_buffer_size <= write_buffer_size`.
220    pub fn set_config(&mut self, set_func: impl FnOnce(&mut WebSocketConfig)) {
221        self.context.set_config(set_func);
222    }
223
224    /// Read the configuration.
225    pub fn get_config(&self) -> &WebSocketConfig {
226        self.context.get_config()
227    }
228
229    /// Check if it is possible to read messages.
230    ///
231    /// Reading is impossible after receiving `Message::Close`. It is still possible after
232    /// sending close frame since the peer still may send some data before confirming close.
233    pub fn can_read(&self) -> bool {
234        self.context.can_read()
235    }
236
237    /// Check if it is possible to write messages.
238    ///
239    /// Writing gets impossible immediately after sending or receiving `Message::Close`.
240    pub fn can_write(&self) -> bool {
241        self.context.can_write()
242    }
243}
244
245impl<Stream: Read + Write> WebSocket<Stream> {
246    /// Read a message from stream, if possible.
247    ///
248    /// This will also queue responses to ping and close messages. These responses
249    /// will be written and flushed on the next call to [`read`](Self::read),
250    /// [`write`](Self::write) or [`flush`](Self::flush).
251    ///
252    /// # Closing the connection
253    /// When the remote endpoint decides to close the connection this will return
254    /// the close message with an optional close frame.
255    ///
256    /// You should continue calling [`read`](Self::read), [`write`](Self::write) or
257    /// [`flush`](Self::flush) to drive the reply to the close frame until [`Error::ConnectionClosed`]
258    /// is returned. Once that happens it is safe to drop the underlying connection.
259    pub fn read(&mut self) -> Result<Message> {
260        self.context.read(&mut self.socket)
261    }
262
263    /// Writes and immediately flushes a message.
264    /// Equivalent to calling [`write`](Self::write) then [`flush`](Self::flush).
265    pub fn send(&mut self, message: Message) -> Result<()> {
266        self.write(message)?;
267        self.flush()
268    }
269
270    /// Write a message to the provided stream, if possible.
271    ///
272    /// A subsequent call should be made to [`flush`](Self::flush) to flush writes.
273    ///
274    /// In the event of stream write failure the message frame will be stored
275    /// in the write buffer and will try again on the next call to [`write`](Self::write)
276    /// or [`flush`](Self::flush).
277    ///
278    /// If the write buffer would exceed the configured [`WebSocketConfig::max_write_buffer_size`]
279    /// [`Err(WriteBufferFull(msg_frame))`](Error::WriteBufferFull) is returned.
280    ///
281    /// This call will generally not flush. However, if there are queued automatic messages
282    /// they will be written and eagerly flushed.
283    ///
284    /// For example, upon receiving ping messages tungstenite queues pong replies automatically.
285    /// The next call to [`read`](Self::read), [`write`](Self::write) or [`flush`](Self::flush)
286    /// will write & flush the pong reply. This means you should not respond to ping frames manually.
287    ///
288    /// You can however send pong frames manually in order to indicate a unidirectional heartbeat
289    /// as described in [RFC 6455](https://tools.ietf.org/html/rfc6455#section-5.5.3). Note that
290    /// if [`read`](Self::read) returns a ping, you should [`flush`](Self::flush) before passing
291    /// a custom pong to [`write`](Self::write), otherwise the automatic queued response to the
292    /// ping will not be sent as it will be replaced by your custom pong message.
293    ///
294    /// # Errors
295    /// - If the WebSocket's write buffer is full, [`Error::WriteBufferFull`] will be returned
296    ///   along with the equivalent passed message frame.
297    /// - If the connection is closed and should be dropped, this will return [`Error::ConnectionClosed`].
298    /// - If you try again after [`Error::ConnectionClosed`] was returned either from here or from
299    ///   [`read`](Self::read), [`Error::AlreadyClosed`] will be returned. This indicates a program
300    ///   error on your part.
301    /// - [`Error::Io`] is returned if the underlying connection returns an error
302    ///   (consider these fatal except for WouldBlock).
303    /// - [`Error::Capacity`] if your message size is bigger than the configured max message size.
304    pub fn write(&mut self, message: Message) -> Result<()> {
305        self.context.write(&mut self.socket, message)
306    }
307
308    /// Flush writes.
309    ///
310    /// Ensures all messages previously passed to [`write`](Self::write) and automatic
311    /// queued pong responses are written & flushed into the underlying stream.
312    pub fn flush(&mut self) -> Result<()> {
313        self.context.flush(&mut self.socket)
314    }
315
316    /// Close the connection.
317    ///
318    /// This function guarantees that the close frame will be queued.
319    /// There is no need to call it again. Calling this function is
320    /// the same as calling `write(Message::Close(..))`.
321    ///
322    /// After queuing the close frame you should continue calling [`read`](Self::read) or
323    /// [`flush`](Self::flush) to drive the close handshake to completion.
324    ///
325    /// The websocket RFC defines that the underlying connection should be closed
326    /// by the server. Tungstenite takes care of this asymmetry for you.
327    ///
328    /// When the close handshake is finished (we have both sent and received
329    /// a close message), [`read`](Self::read) or [`flush`](Self::flush) will return
330    /// [Error::ConnectionClosed] if this endpoint is the server.
331    ///
332    /// If this endpoint is a client, [Error::ConnectionClosed] will only be
333    /// returned after the server has closed the underlying connection.
334    ///
335    /// It is thus safe to drop the underlying connection as soon as [Error::ConnectionClosed]
336    /// is returned from [`read`](Self::read) or [`flush`](Self::flush).
337    pub fn close(&mut self, code: Option<CloseFrame>) -> Result<()> {
338        self.context.close(&mut self.socket, code)
339    }
340
341    /// Old name for [`read`](Self::read).
342    #[deprecated(note = "Use `read`")]
343    pub fn read_message(&mut self) -> Result<Message> {
344        self.read()
345    }
346
347    /// Old name for [`send`](Self::send).
348    #[deprecated(note = "Use `send`")]
349    pub fn write_message(&mut self, message: Message) -> Result<()> {
350        self.send(message)
351    }
352
353    /// Old name for [`flush`](Self::flush).
354    #[deprecated(note = "Use `flush`")]
355    pub fn write_pending(&mut self) -> Result<()> {
356        self.flush()
357    }
358}
359
360/// A context for managing WebSocket stream.
361#[derive(Debug)]
362pub struct WebSocketContext {
363    /// Server or client?
364    role: Role,
365    /// encoder/decoder of frame.
366    frame: FrameCodec,
367    /// The state of processing, either "active" or "closing".
368    state: WebSocketState,
369    /// Receive: an incomplete message being processed.
370    incomplete: Option<IncompleteMessage>,
371    /// Send in addition to regular messages E.g. "pong" or "close".
372    additional_send: Option<Frame>,
373    /// True indicates there is an additional message (like a pong)
374    /// that failed to flush previously and we should try again.
375    unflushed_additional: bool,
376    /// The configuration for the websocket session.
377    config: WebSocketConfig,
378}
379
380impl WebSocketContext {
381    /// Create a WebSocket context that manages a post-handshake stream.
382    ///
383    /// # Panics
384    /// Panics if config is invalid e.g. `max_write_buffer_size <= write_buffer_size`.
385    pub fn new(role: Role, config: Option<WebSocketConfig>) -> Self {
386        let conf = config.unwrap_or_default();
387        Self::_new(role, FrameCodec::new(conf.read_buffer_size), conf)
388    }
389
390    /// Create a WebSocket context that manages an post-handshake stream.
391    ///
392    /// # Panics
393    /// Panics if config is invalid e.g. `max_write_buffer_size <= write_buffer_size`.
394    pub fn from_partially_read(part: Vec<u8>, role: Role, config: Option<WebSocketConfig>) -> Self {
395        let conf = config.unwrap_or_default();
396        Self::_new(role, FrameCodec::from_partially_read(part, conf.read_buffer_size), conf)
397    }
398
399    fn _new(role: Role, mut frame: FrameCodec, config: WebSocketConfig) -> Self {
400        config.assert_valid();
401        frame.set_max_out_buffer_len(config.max_write_buffer_size);
402        frame.set_out_buffer_write_len(config.write_buffer_size);
403        Self {
404            role,
405            frame,
406            state: WebSocketState::Active,
407            incomplete: None,
408            additional_send: None,
409            unflushed_additional: false,
410            config,
411        }
412    }
413
414    /// Change the configuration.
415    ///
416    /// # Panics
417    /// Panics if config is invalid e.g. `max_write_buffer_size <= write_buffer_size`.
418    pub fn set_config(&mut self, set_func: impl FnOnce(&mut WebSocketConfig)) {
419        set_func(&mut self.config);
420        self.config.assert_valid();
421        self.frame.set_max_out_buffer_len(self.config.max_write_buffer_size);
422        self.frame.set_out_buffer_write_len(self.config.write_buffer_size);
423    }
424
425    /// Read the configuration.
426    pub fn get_config(&self) -> &WebSocketConfig {
427        &self.config
428    }
429
430    /// Check if it is possible to read messages.
431    ///
432    /// Reading is impossible after receiving `Message::Close`. It is still possible after
433    /// sending close frame since the peer still may send some data before confirming close.
434    pub fn can_read(&self) -> bool {
435        self.state.can_read()
436    }
437
438    /// Check if it is possible to write messages.
439    ///
440    /// Writing gets impossible immediately after sending or receiving `Message::Close`.
441    pub fn can_write(&self) -> bool {
442        self.state.is_active()
443    }
444
445    /// Read a message from the provided stream, if possible.
446    ///
447    /// This function sends pong and close responses automatically.
448    /// However, it never blocks on write.
449    pub fn read<Stream>(&mut self, stream: &mut Stream) -> Result<Message>
450    where
451        Stream: Read + Write,
452    {
453        // Do not read from already closed connections.
454        self.state.check_not_terminated()?;
455
456        loop {
457            if self.additional_send.is_some() || self.unflushed_additional {
458                // Since we may get ping or close, we need to reply to the messages even during read.
459                match self.flush(stream) {
460                    Ok(_) => {}
461                    Err(Error::Io(err)) if err.kind() == io::ErrorKind::WouldBlock => {
462                        // If blocked continue reading, but try again later
463                        self.unflushed_additional = true;
464                    }
465                    Err(err) => return Err(err),
466                }
467            } else if self.role == Role::Server && !self.state.can_read() {
468                self.state = WebSocketState::Terminated;
469                return Err(Error::ConnectionClosed);
470            }
471
472            // If we get here, either write blocks or we have nothing to write.
473            // Thus if read blocks, just let it return WouldBlock.
474            if let Some(message) = self.read_message_frame(stream)? {
475                trace!("Received message {message}");
476                return Ok(message);
477            }
478        }
479    }
480
481    /// Write a message to the provided stream.
482    ///
483    /// A subsequent call should be made to [`flush`](Self::flush) to flush writes.
484    ///
485    /// In the event of stream write failure the message frame will be stored
486    /// in the write buffer and will try again on the next call to [`write`](Self::write)
487    /// or [`flush`](Self::flush).
488    ///
489    /// If the write buffer would exceed the configured [`WebSocketConfig::max_write_buffer_size`]
490    /// [`Err(WriteBufferFull(msg_frame))`](Error::WriteBufferFull) is returned.
491    pub fn write<Stream>(&mut self, stream: &mut Stream, message: Message) -> Result<()>
492    where
493        Stream: Read + Write,
494    {
495        // When terminated, return AlreadyClosed.
496        self.state.check_not_terminated()?;
497
498        // Do not write after sending a close frame.
499        if !self.state.is_active() {
500            return Err(Error::Protocol(ProtocolError::SendAfterClosing));
501        }
502
503        let frame = match message {
504            Message::Text(data) => Frame::message(data, OpCode::Data(OpData::Text), true),
505            Message::Binary(data) => Frame::message(data, OpCode::Data(OpData::Binary), true),
506            Message::Ping(data) => Frame::ping(data),
507            Message::Pong(data) => {
508                self.set_additional(Frame::pong(data));
509                // Note: user pongs can be user flushed so no need to flush here
510                return self._write(stream, None).map(|_| ());
511            }
512            Message::Close(code) => return self.close(stream, code),
513            Message::Frame(f) => f,
514        };
515
516        let should_flush = self._write(stream, Some(frame))?;
517        if should_flush {
518            self.flush(stream)?;
519        }
520        Ok(())
521    }
522
523    /// Flush writes.
524    ///
525    /// Ensures all messages previously passed to [`write`](Self::write) and automatically
526    /// queued pong responses are written & flushed into the `stream`.
527    #[inline]
528    pub fn flush<Stream>(&mut self, stream: &mut Stream) -> Result<()>
529    where
530        Stream: Read + Write,
531    {
532        self._write(stream, None)?;
533        self.frame.write_out_buffer(stream)?;
534        stream.flush()?;
535        self.unflushed_additional = false;
536        Ok(())
537    }
538
539    /// Writes any data in the out_buffer, `additional_send` and given `data`.
540    ///
541    /// Does **not** flush.
542    ///
543    /// Returns true if the write contents indicate we should flush immediately.
544    fn _write<Stream>(&mut self, stream: &mut Stream, data: Option<Frame>) -> Result<bool>
545    where
546        Stream: Read + Write,
547    {
548        if let Some(data) = data {
549            self.buffer_frame(stream, data)?;
550        }
551
552        // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in
553        // response, unless it already received a Close frame. It SHOULD
554        // respond with Pong frame as soon as is practical. (RFC 6455)
555        let should_flush = if let Some(msg) = self.additional_send.take() {
556            trace!("Sending pong/close");
557            match self.buffer_frame(stream, msg) {
558                Err(Error::WriteBufferFull(msg)) => {
559                    // if an system message would exceed the buffer put it back in
560                    // `additional_send` for retry. Otherwise returning this error
561                    // may not make sense to the user, e.g. calling `flush`.
562                    if let Message::Frame(msg) = *msg {
563                        self.set_additional(msg);
564                        false
565                    } else {
566                        unreachable!()
567                    }
568                }
569                Err(err) => return Err(err),
570                Ok(_) => true,
571            }
572        } else {
573            self.unflushed_additional
574        };
575
576        // If we're closing and there is nothing to send anymore, we should close the connection.
577        if self.role == Role::Server && !self.state.can_read() {
578            // The underlying TCP connection, in most normal cases, SHOULD be closed
579            // first by the server, so that it holds the TIME_WAIT state and not the
580            // client (as this would prevent it from re-opening the connection for 2
581            // maximum segment lifetimes (2MSL), while there is no corresponding
582            // server impact as a TIME_WAIT connection is immediately reopened upon
583            // a new SYN with a higher seq number). (RFC 6455)
584            self.frame.write_out_buffer(stream)?;
585            self.state = WebSocketState::Terminated;
586            Err(Error::ConnectionClosed)
587        } else {
588            Ok(should_flush)
589        }
590    }
591
592    /// Close the connection.
593    ///
594    /// This function guarantees that the close frame will be queued.
595    /// There is no need to call it again. Calling this function is
596    /// the same as calling `send(Message::Close(..))`.
597    pub fn close<Stream>(&mut self, stream: &mut Stream, code: Option<CloseFrame>) -> Result<()>
598    where
599        Stream: Read + Write,
600    {
601        if let WebSocketState::Active = self.state {
602            self.state = WebSocketState::ClosedByUs;
603            let frame = Frame::close(code);
604            self._write(stream, Some(frame))?;
605        }
606        self.flush(stream)
607    }
608
609    /// Try to decode one message frame. May return None.
610    fn read_message_frame(&mut self, stream: &mut impl Read) -> Result<Option<Message>> {
611        let frame = match self
612            .frame
613            .read_frame(
614                stream,
615                self.config.max_frame_size,
616                matches!(self.role, Role::Server),
617                self.config.accept_unmasked_frames,
618            )
619            .check_connection_reset(self.state)?
620        {
621            None => {
622                // Connection closed by peer
623                return match replace(&mut self.state, WebSocketState::Terminated) {
624                    WebSocketState::ClosedByPeer | WebSocketState::CloseAcknowledged => {
625                        Err(Error::ConnectionClosed)
626                    }
627                    _ => Err(Error::Protocol(ProtocolError::ResetWithoutClosingHandshake)),
628                };
629            }
630            Some(frame) => frame,
631        };
632
633        if !self.state.can_read() {
634            return Err(Error::Protocol(ProtocolError::ReceivedAfterClosing));
635        }
636        // MUST be 0 unless an extension is negotiated that defines meanings
637        // for non-zero values.  If a nonzero value is received and none of
638        // the negotiated extensions defines the meaning of such a nonzero
639        // value, the receiving endpoint MUST _Fail the WebSocket
640        // Connection_.
641        {
642            let hdr = frame.header();
643            if hdr.rsv1 || hdr.rsv2 || hdr.rsv3 {
644                return Err(Error::Protocol(ProtocolError::NonZeroReservedBits));
645            }
646        }
647
648        if self.role == Role::Client && frame.is_masked() {
649            // A client MUST close a connection if it detects a masked frame. (RFC 6455)
650            return Err(Error::Protocol(ProtocolError::MaskedFrameFromServer));
651        }
652
653        match frame.header().opcode {
654            OpCode::Control(ctl) => {
655                match ctl {
656                    // All control frames MUST have a payload length of 125 bytes or less
657                    // and MUST NOT be fragmented. (RFC 6455)
658                    _ if !frame.header().is_final => {
659                        Err(Error::Protocol(ProtocolError::FragmentedControlFrame))
660                    }
661                    _ if frame.payload().len() > 125 => {
662                        Err(Error::Protocol(ProtocolError::ControlFrameTooBig))
663                    }
664                    OpCtl::Close => Ok(self.do_close(frame.into_close()?).map(Message::Close)),
665                    OpCtl::Reserved(i) => {
666                        Err(Error::Protocol(ProtocolError::UnknownControlFrameType(i)))
667                    }
668                    OpCtl::Ping => {
669                        let data = frame.into_payload();
670                        // No ping processing after we sent a close frame.
671                        if self.state.is_active() {
672                            self.set_additional(Frame::pong(data.clone()));
673                        }
674                        Ok(Some(Message::Ping(data)))
675                    }
676                    OpCtl::Pong => Ok(Some(Message::Pong(frame.into_payload()))),
677                }
678            }
679
680            OpCode::Data(data) => {
681                let fin = frame.header().is_final;
682
683                let payload = match (data, self.incomplete.as_mut()) {
684                    (OpData::Continue, None) => Err(ProtocolError::UnexpectedContinueFrame),
685                    (OpData::Continue, Some(incomplete)) => {
686                        incomplete.extend(frame.into_payload(), self.config.max_message_size)?;
687                        Ok(None)
688                    }
689                    (_, Some(_)) => Err(ProtocolError::ExpectedFragment(data)),
690                    (OpData::Text, _) => Ok(Some((frame.into_payload(), MessageType::Text))),
691                    (OpData::Binary, _) => Ok(Some((frame.into_payload(), MessageType::Binary))),
692                    (OpData::Reserved(i), _) => Err(ProtocolError::UnknownDataFrameType(i)),
693                }?;
694
695                match (payload, fin) {
696                    (None, true) => Ok(Some(self.incomplete.take().unwrap().complete()?)),
697                    (None, false) => Ok(None),
698                    (Some((payload, t)), true) => {
699                        check_max_size(payload.len(), self.config.max_message_size)?;
700                        match t {
701                            MessageType::Text => Ok(Some(Message::Text(payload.try_into()?))),
702                            MessageType::Binary => Ok(Some(Message::Binary(payload))),
703                        }
704                    }
705                    (Some((payload, t)), false) => {
706                        let mut incomplete = IncompleteMessage::new(t);
707                        incomplete.extend(payload, self.config.max_message_size)?;
708                        self.incomplete = Some(incomplete);
709                        Ok(None)
710                    }
711                }
712            }
713        } // match opcode
714    }
715
716    /// Received a close frame. Tells if we need to return a close frame to the user.
717    #[allow(clippy::option_option)]
718    fn do_close(&mut self, close: Option<CloseFrame>) -> Option<Option<CloseFrame>> {
719        debug!("Received close frame: {close:?}");
720        match self.state {
721            WebSocketState::Active => {
722                self.state = WebSocketState::ClosedByPeer;
723
724                let close = close.map(|frame| {
725                    if !frame.code.is_allowed() {
726                        CloseFrame {
727                            code: CloseCode::Protocol,
728                            reason: Utf8Bytes::from_static("Protocol violation"),
729                        }
730                    } else {
731                        frame
732                    }
733                });
734
735                let reply = Frame::close(close.clone());
736                debug!("Replying to close with {reply:?}");
737                self.set_additional(reply);
738
739                Some(close)
740            }
741            WebSocketState::ClosedByPeer | WebSocketState::CloseAcknowledged => {
742                // It is already closed, just ignore.
743                None
744            }
745            WebSocketState::ClosedByUs => {
746                // We received a reply.
747                self.state = WebSocketState::CloseAcknowledged;
748                Some(close)
749            }
750            WebSocketState::Terminated => unreachable!(),
751        }
752    }
753
754    /// Write a single frame into the write-buffer.
755    fn buffer_frame<Stream>(&mut self, stream: &mut Stream, mut frame: Frame) -> Result<()>
756    where
757        Stream: Read + Write,
758    {
759        match self.role {
760            Role::Server => {}
761            Role::Client => {
762                // 5.  If the data is being sent by the client, the frame(s) MUST be
763                // masked as defined in Section 5.3. (RFC 6455)
764                frame.set_random_mask();
765            }
766        }
767
768        trace!("Sending frame: {frame:?}");
769        self.frame.buffer_frame(stream, frame).check_connection_reset(self.state)
770    }
771
772    /// Replace `additional_send` if it is currently a `Pong` message.
773    fn set_additional(&mut self, add: Frame) {
774        let empty_or_pong = self
775            .additional_send
776            .as_ref()
777            .map_or(true, |f| f.header().opcode == OpCode::Control(OpCtl::Pong));
778        if empty_or_pong {
779            self.additional_send.replace(add);
780        }
781    }
782}
783
784fn check_max_size(size: usize, max_size: Option<usize>) -> crate::Result<()> {
785    if let Some(max_size) = max_size {
786        if size > max_size {
787            return Err(Error::Capacity(CapacityError::MessageTooLong { size, max_size }));
788        }
789    }
790    Ok(())
791}
792
793/// The current connection state.
794#[derive(Debug, PartialEq, Eq, Clone, Copy)]
795enum WebSocketState {
796    /// The connection is active.
797    Active,
798    /// We initiated a close handshake.
799    ClosedByUs,
800    /// The peer initiated a close handshake.
801    ClosedByPeer,
802    /// The peer replied to our close handshake.
803    CloseAcknowledged,
804    /// The connection does not exist anymore.
805    Terminated,
806}
807
808impl WebSocketState {
809    /// Tell if we're allowed to process normal messages.
810    fn is_active(self) -> bool {
811        matches!(self, WebSocketState::Active)
812    }
813
814    /// Tell if we should process incoming data. Note that if we send a close frame
815    /// but the remote hasn't confirmed, they might have sent data before they receive our
816    /// close frame, so we should still pass those to client code, hence ClosedByUs is valid.
817    fn can_read(self) -> bool {
818        matches!(self, WebSocketState::Active | WebSocketState::ClosedByUs)
819    }
820
821    /// Check if the state is active, return error if not.
822    fn check_not_terminated(self) -> Result<()> {
823        match self {
824            WebSocketState::Terminated => Err(Error::AlreadyClosed),
825            _ => Ok(()),
826        }
827    }
828}
829
830/// Translate "Connection reset by peer" into `ConnectionClosed` if appropriate.
831trait CheckConnectionReset {
832    fn check_connection_reset(self, state: WebSocketState) -> Self;
833}
834
835impl<T> CheckConnectionReset for Result<T> {
836    fn check_connection_reset(self, state: WebSocketState) -> Self {
837        match self {
838            Err(Error::Io(io_error)) => Err({
839                if !state.can_read() && io_error.kind() == io::ErrorKind::ConnectionReset {
840                    Error::ConnectionClosed
841                } else {
842                    Error::Io(io_error)
843                }
844            }),
845            x => x,
846        }
847    }
848}
849
850#[cfg(test)]
851mod tests {
852    use super::{Message, Role, WebSocket, WebSocketConfig};
853    use crate::error::{CapacityError, Error};
854
855    use std::{io, io::Cursor};
856
857    struct WriteMoc<Stream>(Stream);
858
859    impl<Stream> io::Write for WriteMoc<Stream> {
860        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
861            Ok(buf.len())
862        }
863        fn flush(&mut self) -> io::Result<()> {
864            Ok(())
865        }
866    }
867
868    impl<Stream: io::Read> io::Read for WriteMoc<Stream> {
869        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
870            self.0.read(buf)
871        }
872    }
873
874    #[test]
875    fn receive_messages() {
876        let incoming = Cursor::new(vec![
877            0x89, 0x02, 0x01, 0x02, 0x8a, 0x01, 0x03, 0x01, 0x07, 0x48, 0x65, 0x6c, 0x6c, 0x6f,
878            0x2c, 0x20, 0x80, 0x06, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21, 0x82, 0x03, 0x01, 0x02,
879            0x03,
880        ]);
881        let mut socket = WebSocket::from_raw_socket(WriteMoc(incoming), Role::Client, None);
882        assert_eq!(socket.read().unwrap(), Message::Ping(vec![1, 2].into()));
883        assert_eq!(socket.read().unwrap(), Message::Pong(vec![3].into()));
884        assert_eq!(socket.read().unwrap(), Message::Text("Hello, World!".into()));
885        assert_eq!(socket.read().unwrap(), Message::Binary(vec![0x01, 0x02, 0x03].into()));
886    }
887
888    #[test]
889    fn size_limiting_text_fragmented() {
890        let incoming = Cursor::new(vec![
891            0x01, 0x07, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x80, 0x06, 0x57, 0x6f, 0x72,
892            0x6c, 0x64, 0x21,
893        ]);
894        let limit = WebSocketConfig { max_message_size: Some(10), ..WebSocketConfig::default() };
895        let mut socket = WebSocket::from_raw_socket(WriteMoc(incoming), Role::Client, Some(limit));
896
897        assert!(matches!(
898            socket.read(),
899            Err(Error::Capacity(CapacityError::MessageTooLong { size: 13, max_size: 10 }))
900        ));
901    }
902
903    #[test]
904    fn size_limiting_binary() {
905        let incoming = Cursor::new(vec![0x82, 0x03, 0x01, 0x02, 0x03]);
906        let limit = WebSocketConfig { max_message_size: Some(2), ..WebSocketConfig::default() };
907        let mut socket = WebSocket::from_raw_socket(WriteMoc(incoming), Role::Client, Some(limit));
908
909        assert!(matches!(
910            socket.read(),
911            Err(Error::Capacity(CapacityError::MessageTooLong { size: 3, max_size: 2 }))
912        ));
913    }
914}