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, IncompleteMessageType},
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 /// Returns a shared reference to the inner stream.
203 pub fn get_ref(&self) -> &Stream {
204 &self.socket
205 }
206 /// Returns a mutable reference to the inner stream.
207 pub fn get_mut(&mut self) -> &mut Stream {
208 &mut self.socket
209 }
210
211 /// Change the configuration.
212 ///
213 /// # Panics
214 /// Panics if config is invalid e.g. `max_write_buffer_size <= write_buffer_size`.
215 pub fn set_config(&mut self, set_func: impl FnOnce(&mut WebSocketConfig)) {
216 self.context.set_config(set_func);
217 }
218
219 /// Read the configuration.
220 pub fn get_config(&self) -> &WebSocketConfig {
221 self.context.get_config()
222 }
223
224 /// Check if it is possible to read messages.
225 ///
226 /// Reading is impossible after receiving `Message::Close`. It is still possible after
227 /// sending close frame since the peer still may send some data before confirming close.
228 pub fn can_read(&self) -> bool {
229 self.context.can_read()
230 }
231
232 /// Check if it is possible to write messages.
233 ///
234 /// Writing gets impossible immediately after sending or receiving `Message::Close`.
235 pub fn can_write(&self) -> bool {
236 self.context.can_write()
237 }
238}
239
240impl<Stream: Read + Write> WebSocket<Stream> {
241 /// Read a message from stream, if possible.
242 ///
243 /// This will also queue responses to ping and close messages. These responses
244 /// will be written and flushed on the next call to [`read`](Self::read),
245 /// [`write`](Self::write) or [`flush`](Self::flush).
246 ///
247 /// # Closing the connection
248 /// When the remote endpoint decides to close the connection this will return
249 /// the close message with an optional close frame.
250 ///
251 /// You should continue calling [`read`](Self::read), [`write`](Self::write) or
252 /// [`flush`](Self::flush) to drive the reply to the close frame until [`Error::ConnectionClosed`]
253 /// is returned. Once that happens it is safe to drop the underlying connection.
254 pub fn read(&mut self) -> Result<Message> {
255 self.context.read(&mut self.socket)
256 }
257
258 /// Writes and immediately flushes a message.
259 /// Equivalent to calling [`write`](Self::write) then [`flush`](Self::flush).
260 pub fn send(&mut self, message: Message) -> Result<()> {
261 self.write(message)?;
262 self.flush()
263 }
264
265 /// Write a message to the provided stream, if possible.
266 ///
267 /// A subsequent call should be made to [`flush`](Self::flush) to flush writes.
268 ///
269 /// In the event of stream write failure the message frame will be stored
270 /// in the write buffer and will try again on the next call to [`write`](Self::write)
271 /// or [`flush`](Self::flush).
272 ///
273 /// If the write buffer would exceed the configured [`WebSocketConfig::max_write_buffer_size`]
274 /// [`Err(WriteBufferFull(msg_frame))`](Error::WriteBufferFull) is returned.
275 ///
276 /// This call will generally not flush. However, if there are queued automatic messages
277 /// they will be written and eagerly flushed.
278 ///
279 /// For example, upon receiving ping messages tungstenite queues pong replies automatically.
280 /// The next call to [`read`](Self::read), [`write`](Self::write) or [`flush`](Self::flush)
281 /// will write & flush the pong reply. This means you should not respond to ping frames manually.
282 ///
283 /// You can however send pong frames manually in order to indicate a unidirectional heartbeat
284 /// as described in [RFC 6455](https://tools.ietf.org/html/rfc6455#section-5.5.3). Note that
285 /// if [`read`](Self::read) returns a ping, you should [`flush`](Self::flush) before passing
286 /// a custom pong to [`write`](Self::write), otherwise the automatic queued response to the
287 /// ping will not be sent as it will be replaced by your custom pong message.
288 ///
289 /// # Errors
290 /// - If the WebSocket's write buffer is full, [`Error::WriteBufferFull`] will be returned
291 /// along with the equivalent passed message frame.
292 /// - If the connection is closed and should be dropped, this will return [`Error::ConnectionClosed`].
293 /// - If you try again after [`Error::ConnectionClosed`] was returned either from here or from
294 /// [`read`](Self::read), [`Error::AlreadyClosed`] will be returned. This indicates a program
295 /// error on your part.
296 /// - [`Error::Io`] is returned if the underlying connection returns an error
297 /// (consider these fatal except for WouldBlock).
298 /// - [`Error::Capacity`] if your message size is bigger than the configured max message size.
299 pub fn write(&mut self, message: Message) -> Result<()> {
300 self.context.write(&mut self.socket, message)
301 }
302
303 /// Flush writes.
304 ///
305 /// Ensures all messages previously passed to [`write`](Self::write) and automatic
306 /// queued pong responses are written & flushed into the underlying stream.
307 pub fn flush(&mut self) -> Result<()> {
308 self.context.flush(&mut self.socket)
309 }
310
311 /// Close the connection.
312 ///
313 /// This function guarantees that the close frame will be queued.
314 /// There is no need to call it again. Calling this function is
315 /// the same as calling `write(Message::Close(..))`.
316 ///
317 /// After queuing the close frame you should continue calling [`read`](Self::read) or
318 /// [`flush`](Self::flush) to drive the close handshake to completion.
319 ///
320 /// The websocket RFC defines that the underlying connection should be closed
321 /// by the server. Tungstenite takes care of this asymmetry for you.
322 ///
323 /// When the close handshake is finished (we have both sent and received
324 /// a close message), [`read`](Self::read) or [`flush`](Self::flush) will return
325 /// [Error::ConnectionClosed] if this endpoint is the server.
326 ///
327 /// If this endpoint is a client, [Error::ConnectionClosed] will only be
328 /// returned after the server has closed the underlying connection.
329 ///
330 /// It is thus safe to drop the underlying connection as soon as [Error::ConnectionClosed]
331 /// is returned from [`read`](Self::read) or [`flush`](Self::flush).
332 pub fn close(&mut self, code: Option<CloseFrame>) -> Result<()> {
333 self.context.close(&mut self.socket, code)
334 }
335
336 /// Old name for [`read`](Self::read).
337 #[deprecated(note = "Use `read`")]
338 pub fn read_message(&mut self) -> Result<Message> {
339 self.read()
340 }
341
342 /// Old name for [`send`](Self::send).
343 #[deprecated(note = "Use `send`")]
344 pub fn write_message(&mut self, message: Message) -> Result<()> {
345 self.send(message)
346 }
347
348 /// Old name for [`flush`](Self::flush).
349 #[deprecated(note = "Use `flush`")]
350 pub fn write_pending(&mut self) -> Result<()> {
351 self.flush()
352 }
353}
354
355/// A context for managing WebSocket stream.
356#[derive(Debug)]
357pub struct WebSocketContext {
358 /// Server or client?
359 role: Role,
360 /// encoder/decoder of frame.
361 frame: FrameCodec,
362 /// The state of processing, either "active" or "closing".
363 state: WebSocketState,
364 /// Receive: an incomplete message being processed.
365 incomplete: Option<IncompleteMessage>,
366 /// Send in addition to regular messages E.g. "pong" or "close".
367 additional_send: Option<Frame>,
368 /// True indicates there is an additional message (like a pong)
369 /// that failed to flush previously and we should try again.
370 unflushed_additional: bool,
371 /// The configuration for the websocket session.
372 config: WebSocketConfig,
373}
374
375impl WebSocketContext {
376 /// Create a WebSocket context that manages a post-handshake stream.
377 ///
378 /// # Panics
379 /// Panics if config is invalid e.g. `max_write_buffer_size <= write_buffer_size`.
380 pub fn new(role: Role, config: Option<WebSocketConfig>) -> Self {
381 let conf = config.unwrap_or_default();
382 Self::_new(role, FrameCodec::new(conf.read_buffer_size), conf)
383 }
384
385 /// Create a WebSocket context that manages an post-handshake stream.
386 ///
387 /// # Panics
388 /// Panics if config is invalid e.g. `max_write_buffer_size <= write_buffer_size`.
389 pub fn from_partially_read(part: Vec<u8>, role: Role, config: Option<WebSocketConfig>) -> Self {
390 let conf = config.unwrap_or_default();
391 Self::_new(role, FrameCodec::from_partially_read(part, conf.read_buffer_size), conf)
392 }
393
394 fn _new(role: Role, mut frame: FrameCodec, config: WebSocketConfig) -> Self {
395 config.assert_valid();
396 frame.set_max_out_buffer_len(config.max_write_buffer_size);
397 frame.set_out_buffer_write_len(config.write_buffer_size);
398 Self {
399 role,
400 frame,
401 state: WebSocketState::Active,
402 incomplete: None,
403 additional_send: None,
404 unflushed_additional: false,
405 config,
406 }
407 }
408
409 /// Change the configuration.
410 ///
411 /// # Panics
412 /// Panics if config is invalid e.g. `max_write_buffer_size <= write_buffer_size`.
413 pub fn set_config(&mut self, set_func: impl FnOnce(&mut WebSocketConfig)) {
414 set_func(&mut self.config);
415 self.config.assert_valid();
416 self.frame.set_max_out_buffer_len(self.config.max_write_buffer_size);
417 self.frame.set_out_buffer_write_len(self.config.write_buffer_size);
418 }
419
420 /// Read the configuration.
421 pub fn get_config(&self) -> &WebSocketConfig {
422 &self.config
423 }
424
425 /// Check if it is possible to read messages.
426 ///
427 /// Reading is impossible after receiving `Message::Close`. It is still possible after
428 /// sending close frame since the peer still may send some data before confirming close.
429 pub fn can_read(&self) -> bool {
430 self.state.can_read()
431 }
432
433 /// Check if it is possible to write messages.
434 ///
435 /// Writing gets impossible immediately after sending or receiving `Message::Close`.
436 pub fn can_write(&self) -> bool {
437 self.state.is_active()
438 }
439
440 /// Read a message from the provided stream, if possible.
441 ///
442 /// This function sends pong and close responses automatically.
443 /// However, it never blocks on write.
444 pub fn read<Stream>(&mut self, stream: &mut Stream) -> Result<Message>
445 where
446 Stream: Read + Write,
447 {
448 // Do not read from already closed connections.
449 self.state.check_not_terminated()?;
450
451 loop {
452 if self.additional_send.is_some() || self.unflushed_additional {
453 // Since we may get ping or close, we need to reply to the messages even during read.
454 match self.flush(stream) {
455 Ok(_) => {}
456 Err(Error::Io(err)) if err.kind() == io::ErrorKind::WouldBlock => {
457 // If blocked continue reading, but try again later
458 self.unflushed_additional = true;
459 }
460 Err(err) => return Err(err),
461 }
462 } else if self.role == Role::Server && !self.state.can_read() {
463 self.state = WebSocketState::Terminated;
464 return Err(Error::ConnectionClosed);
465 }
466
467 // If we get here, either write blocks or we have nothing to write.
468 // Thus if read blocks, just let it return WouldBlock.
469 if let Some(message) = self.read_message_frame(stream)? {
470 trace!("Received message {message}");
471 return Ok(message);
472 }
473 }
474 }
475
476 /// Write a message to the provided stream.
477 ///
478 /// A subsequent call should be made to [`flush`](Self::flush) to flush writes.
479 ///
480 /// In the event of stream write failure the message frame will be stored
481 /// in the write buffer and will try again on the next call to [`write`](Self::write)
482 /// or [`flush`](Self::flush).
483 ///
484 /// If the write buffer would exceed the configured [`WebSocketConfig::max_write_buffer_size`]
485 /// [`Err(WriteBufferFull(msg_frame))`](Error::WriteBufferFull) is returned.
486 pub fn write<Stream>(&mut self, stream: &mut Stream, message: Message) -> Result<()>
487 where
488 Stream: Read + Write,
489 {
490 // When terminated, return AlreadyClosed.
491 self.state.check_not_terminated()?;
492
493 // Do not write after sending a close frame.
494 if !self.state.is_active() {
495 return Err(Error::Protocol(ProtocolError::SendAfterClosing));
496 }
497
498 let frame = match message {
499 Message::Text(data) => Frame::message(data, OpCode::Data(OpData::Text), true),
500 Message::Binary(data) => Frame::message(data, OpCode::Data(OpData::Binary), true),
501 Message::Ping(data) => Frame::ping(data),
502 Message::Pong(data) => {
503 self.set_additional(Frame::pong(data));
504 // Note: user pongs can be user flushed so no need to flush here
505 return self._write(stream, None).map(|_| ());
506 }
507 Message::Close(code) => return self.close(stream, code),
508 Message::Frame(f) => f,
509 };
510
511 let should_flush = self._write(stream, Some(frame))?;
512 if should_flush {
513 self.flush(stream)?;
514 }
515 Ok(())
516 }
517
518 /// Flush writes.
519 ///
520 /// Ensures all messages previously passed to [`write`](Self::write) and automatically
521 /// queued pong responses are written & flushed into the `stream`.
522 #[inline]
523 pub fn flush<Stream>(&mut self, stream: &mut Stream) -> Result<()>
524 where
525 Stream: Read + Write,
526 {
527 self._write(stream, None)?;
528 self.frame.write_out_buffer(stream)?;
529 stream.flush()?;
530 self.unflushed_additional = false;
531 Ok(())
532 }
533
534 /// Writes any data in the out_buffer, `additional_send` and given `data`.
535 ///
536 /// Does **not** flush.
537 ///
538 /// Returns true if the write contents indicate we should flush immediately.
539 fn _write<Stream>(&mut self, stream: &mut Stream, data: Option<Frame>) -> Result<bool>
540 where
541 Stream: Read + Write,
542 {
543 if let Some(data) = data {
544 self.buffer_frame(stream, data)?;
545 }
546
547 // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in
548 // response, unless it already received a Close frame. It SHOULD
549 // respond with Pong frame as soon as is practical. (RFC 6455)
550 let should_flush = if let Some(msg) = self.additional_send.take() {
551 trace!("Sending pong/close");
552 match self.buffer_frame(stream, msg) {
553 Err(Error::WriteBufferFull(Message::Frame(msg))) => {
554 // if an system message would exceed the buffer put it back in
555 // `additional_send` for retry. Otherwise returning this error
556 // may not make sense to the user, e.g. calling `flush`.
557 self.set_additional(msg);
558 false
559 }
560 Err(err) => return Err(err),
561 Ok(_) => true,
562 }
563 } else {
564 self.unflushed_additional
565 };
566
567 // If we're closing and there is nothing to send anymore, we should close the connection.
568 if self.role == Role::Server && !self.state.can_read() {
569 // The underlying TCP connection, in most normal cases, SHOULD be closed
570 // first by the server, so that it holds the TIME_WAIT state and not the
571 // client (as this would prevent it from re-opening the connection for 2
572 // maximum segment lifetimes (2MSL), while there is no corresponding
573 // server impact as a TIME_WAIT connection is immediately reopened upon
574 // a new SYN with a higher seq number). (RFC 6455)
575 self.frame.write_out_buffer(stream)?;
576 self.state = WebSocketState::Terminated;
577 Err(Error::ConnectionClosed)
578 } else {
579 Ok(should_flush)
580 }
581 }
582
583 /// Close the connection.
584 ///
585 /// This function guarantees that the close frame will be queued.
586 /// There is no need to call it again. Calling this function is
587 /// the same as calling `send(Message::Close(..))`.
588 pub fn close<Stream>(&mut self, stream: &mut Stream, code: Option<CloseFrame>) -> Result<()>
589 where
590 Stream: Read + Write,
591 {
592 if let WebSocketState::Active = self.state {
593 self.state = WebSocketState::ClosedByUs;
594 let frame = Frame::close(code);
595 self._write(stream, Some(frame))?;
596 }
597 self.flush(stream)
598 }
599
600 /// Try to decode one message frame. May return None.
601 fn read_message_frame(&mut self, stream: &mut impl Read) -> Result<Option<Message>> {
602 if let Some(frame) = self
603 .frame
604 .read_frame(
605 stream,
606 self.config.max_frame_size,
607 matches!(self.role, Role::Server),
608 self.config.accept_unmasked_frames,
609 )
610 .check_connection_reset(self.state)?
611 {
612 if !self.state.can_read() {
613 return Err(Error::Protocol(ProtocolError::ReceivedAfterClosing));
614 }
615 // MUST be 0 unless an extension is negotiated that defines meanings
616 // for non-zero values. If a nonzero value is received and none of
617 // the negotiated extensions defines the meaning of such a nonzero
618 // value, the receiving endpoint MUST _Fail the WebSocket
619 // Connection_.
620 {
621 let hdr = frame.header();
622 if hdr.rsv1 || hdr.rsv2 || hdr.rsv3 {
623 return Err(Error::Protocol(ProtocolError::NonZeroReservedBits));
624 }
625 }
626
627 if self.role == Role::Client && frame.is_masked() {
628 // A client MUST close a connection if it detects a masked frame. (RFC 6455)
629 return Err(Error::Protocol(ProtocolError::MaskedFrameFromServer));
630 }
631
632 match frame.header().opcode {
633 OpCode::Control(ctl) => {
634 match ctl {
635 // All control frames MUST have a payload length of 125 bytes or less
636 // and MUST NOT be fragmented. (RFC 6455)
637 _ if !frame.header().is_final => {
638 Err(Error::Protocol(ProtocolError::FragmentedControlFrame))
639 }
640 _ if frame.payload().len() > 125 => {
641 Err(Error::Protocol(ProtocolError::ControlFrameTooBig))
642 }
643 OpCtl::Close => Ok(self.do_close(frame.into_close()?).map(Message::Close)),
644 OpCtl::Reserved(i) => {
645 Err(Error::Protocol(ProtocolError::UnknownControlFrameType(i)))
646 }
647 OpCtl::Ping => {
648 let data = frame.into_payload();
649 // No ping processing after we sent a close frame.
650 if self.state.is_active() {
651 self.set_additional(Frame::pong(data.clone()));
652 }
653 Ok(Some(Message::Ping(data)))
654 }
655 OpCtl::Pong => Ok(Some(Message::Pong(frame.into_payload()))),
656 }
657 }
658
659 OpCode::Data(data) => {
660 let fin = frame.header().is_final;
661 match data {
662 OpData::Continue => {
663 if let Some(ref mut msg) = self.incomplete {
664 msg.extend(frame.into_payload(), self.config.max_message_size)?;
665 } else {
666 return Err(Error::Protocol(
667 ProtocolError::UnexpectedContinueFrame,
668 ));
669 }
670 if fin {
671 Ok(Some(self.incomplete.take().unwrap().complete()?))
672 } else {
673 Ok(None)
674 }
675 }
676 c if self.incomplete.is_some() => {
677 Err(Error::Protocol(ProtocolError::ExpectedFragment(c)))
678 }
679 OpData::Text if fin => {
680 check_max_size(frame.payload().len(), self.config.max_message_size)?;
681 Ok(Some(Message::Text(frame.into_text()?)))
682 }
683 OpData::Binary if fin => {
684 check_max_size(frame.payload().len(), self.config.max_message_size)?;
685 Ok(Some(Message::Binary(frame.into_payload())))
686 }
687 OpData::Text | OpData::Binary => {
688 let message_type = match data {
689 OpData::Text => IncompleteMessageType::Text,
690 OpData::Binary => IncompleteMessageType::Binary,
691 _ => panic!("Bug: message is not text nor binary"),
692 };
693 let mut incomplete = IncompleteMessage::new(message_type);
694 incomplete
695 .extend(frame.into_payload(), self.config.max_message_size)?;
696 self.incomplete = Some(incomplete);
697 Ok(None)
698 }
699 OpData::Reserved(i) => {
700 Err(Error::Protocol(ProtocolError::UnknownDataFrameType(i)))
701 }
702 }
703 }
704 } // match opcode
705 } else {
706 // Connection closed by peer
707 match replace(&mut self.state, WebSocketState::Terminated) {
708 WebSocketState::ClosedByPeer | WebSocketState::CloseAcknowledged => {
709 Err(Error::ConnectionClosed)
710 }
711 _ => Err(Error::Protocol(ProtocolError::ResetWithoutClosingHandshake)),
712 }
713 }
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}