1use std::cell::Cell;
2#[cfg(feature = "compress")]
3use std::rc::Rc;
4
5use crate::codec::{Decoder, Encoder};
6use crate::util::{BytePage, BytePages, ByteString, Bytes, BytesMut};
7
8#[cfg(feature = "compress")]
9use super::deflate::{Deflate, DeflateConfig};
10use super::error::ProtocolError;
11use super::frame::Parser;
12use super::proto::{CloseCode, CloseReason, OpCode};
13
14#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum Message {
17 Text(ByteString),
19 Binary(Bytes),
21 Continuation(Item),
23 Ping(Bytes),
25 Pong(Bytes),
27 Close(Option<CloseReason>),
29}
30
31#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum Frame {
34 Text(Bytes),
39 Binary(Bytes),
41 Continuation(Item),
43 Ping(Bytes),
45 Pong(Bytes),
47 Close(Option<CloseReason>),
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum Item {
59 FirstText(Bytes),
61 FirstBinary(Bytes),
63 Continue(Bytes),
65 Last(Bytes),
67}
68
69#[derive(Debug, Clone)]
70pub struct Codec {
81 flags: Cell<Flags>,
82 max_size: usize,
83 max_message_size: usize,
84 validate_utf8: bool,
85 msg_size: Cell<usize>,
87 utf8_tail: Cell<Utf8Tail>,
89 #[cfg(feature = "compress")]
90 deflate: Option<Rc<Deflate>>,
91}
92
93bitflags::bitflags! {
94 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
95 struct Flags: u8 {
96 const SERVER = 0b0000_0001;
97 const R_CONTINUATION = 0b0000_0010;
98 const W_CONTINUATION = 0b0000_0100;
99 const CLOSED = 0b0000_1000;
100 const R_CLOSED = 0b0001_0000;
101 const R_COMPRESSED = 0b0010_0000;
102 const R_TEXT = 0b0100_0000;
103 const W_PONG = 0b1000_0000;
105 }
106}
107
108#[derive(Copy, Clone, Debug, Default)]
109struct Utf8Tail {
110 buf: [u8; 3],
111 len: u8,
112}
113
114fn validate_utf8(tail: Utf8Tail, mut data: &[u8], fin: bool) -> Result<Utf8Tail, ProtocolError> {
120 if tail.len > 0 {
121 let mut ch = [0; 4];
123 let mut len = usize::from(tail.len);
124 ch[..len].copy_from_slice(&tail.buf[..len]);
125 loop {
126 let Some((&b, rest)) = data.split_first() else {
127 return if fin {
128 Err(ProtocolError::InvalidUtf8)
129 } else {
130 Ok(Utf8Tail {
131 buf: [ch[0], ch[1], ch[2]],
132 len: len as u8,
133 })
134 };
135 };
136 ch[len] = b;
138 len += 1;
139 data = rest;
140 match simdutf8::compat::from_utf8(&ch[..len]) {
141 Ok(_) => break,
142 Err(e) if e.error_len().is_some() => return Err(ProtocolError::InvalidUtf8),
143 Err(_) => {}
144 }
145 }
146 }
147
148 if simdutf8::basic::from_utf8(data).is_ok() {
149 return Ok(Utf8Tail::default());
150 }
151 match simdutf8::compat::from_utf8(data) {
152 Err(e) if e.error_len().is_none() && !fin => {
153 let rest = &data[e.valid_up_to()..];
154 let mut tail = Utf8Tail {
155 len: rest.len() as u8,
156 ..Utf8Tail::default()
157 };
158 tail.buf[..rest.len()].copy_from_slice(rest);
159 Ok(tail)
160 }
161 _ => Err(ProtocolError::InvalidUtf8),
162 }
163}
164
165impl Codec {
166 #[must_use]
171 pub fn new() -> Codec {
172 Codec {
173 max_size: 65_536,
174 max_message_size: 4 * 1024 * 1024,
175 validate_utf8: true,
176 msg_size: Cell::new(0),
177 utf8_tail: Cell::new(Utf8Tail::default()),
178 flags: Cell::new(Flags::SERVER),
179 #[cfg(feature = "compress")]
180 deflate: None,
181 }
182 }
183
184 #[must_use]
193 pub fn max_size(mut self, size: usize) -> Self {
194 self.max_size = size;
195 self
196 }
197
198 #[must_use]
211 pub fn max_message_size(mut self, size: usize) -> Self {
212 self.max_message_size = size;
213 self
214 }
215
216 #[must_use]
226 pub fn validate_utf8(mut self, enabled: bool) -> Self {
227 self.validate_utf8 = enabled;
228 self
229 }
230
231 #[must_use]
236 pub fn set_client_mode(self) -> Self {
237 self.remove_flags(Flags::SERVER);
238 self
239 }
240
241 #[cfg(feature = "compress")]
242 #[must_use]
249 pub fn set_deflate(mut self, cfg: DeflateConfig) -> Self {
250 self.deflate = Some(Rc::new(Deflate::new(cfg)));
251 self
252 }
253
254 #[cfg(feature = "compress")]
255 pub fn deflate(&self) -> Option<&DeflateConfig> {
257 self.deflate.as_deref().map(Deflate::config)
258 }
259
260 pub fn is_closed(&self) -> bool {
262 self.flags().contains(Flags::CLOSED)
263 }
264
265 fn flags(&self) -> Flags {
266 self.flags.get()
267 }
268
269 fn insert_flags(&self, f: Flags) {
270 self.flags.set(self.flags() | f);
271 }
272
273 fn remove_flags(&self, f: Flags) {
274 self.flags.set(self.flags() - f);
275 }
276
277 fn is_server(&self) -> bool {
278 self.flags().contains(Flags::SERVER)
279 }
280
281 pub(crate) fn auto_reply(&self, frame: &Frame) -> Option<Message> {
289 match frame {
290 Frame::Ping(data) => {
291 self.remove_flags(Flags::W_PONG);
292 Some(Message::Pong(data.clone()))
293 }
294 Frame::Close(reason) => Some(Message::Close(reason.as_ref().map(|r| {
295 if self.is_server() && r.code == CloseCode::Extension {
296 CloseCode::Normal.into()
297 } else {
298 r.code.into()
299 }
300 }))),
301 _ => None,
302 }
303 }
304
305 pub(crate) fn unanswered(
312 &self,
313 res: Option<Message>,
314 reply: Option<Message>,
315 ) -> Option<Message> {
316 res.or_else(|| match reply {
317 _ if self.is_closed() => None,
318 Some(Message::Pong(_)) if self.flags().contains(Flags::W_PONG) => None,
319 reply => reply,
320 })
321 }
322
323 #[cfg_attr(not(feature = "compress"), allow(clippy::unused_self))]
324 fn is_compressed(&self) -> bool {
325 #[cfg(feature = "compress")]
326 {
327 self.deflate.is_some()
328 }
329 #[cfg(not(feature = "compress"))]
330 {
331 false
332 }
333 }
334
335 fn write_data<B>(
339 &self,
340 dst: &mut BytePages,
341 payload: B,
342 op: OpCode,
343 first: bool,
344 fin: bool,
345 ) -> Result<(), ProtocolError>
346 where
347 BytePage: From<B>,
348 {
349 let payload = BytePage::from(payload);
350 #[cfg(feature = "compress")]
351 if let Some(deflate) = &self.deflate
352 && !(first && fin && deflate.is_skipped(payload.len(), self.is_server()))
353 {
354 let payload = deflate.compress(payload.as_ref(), fin, self.is_server());
355 return Parser::write_frame(dst, payload.into(), op, fin, first, !self.is_server());
356 }
357 let _ = first;
358 Parser::write_frame(dst, payload, op, fin, false, !self.is_server())
359 }
360
361 #[cfg_attr(
364 not(feature = "compress"),
365 allow(clippy::unused_self, clippy::unnecessary_wraps)
366 )]
367 #[inline]
368 fn read_data(&self, payload: Option<Bytes>, fin: bool) -> Result<Bytes, ProtocolError> {
369 #[cfg(feature = "compress")]
371 if self.flags().contains(Flags::R_COMPRESSED) {
372 return self.decompress(payload, fin);
373 }
374 let _ = fin;
375 Ok(payload.unwrap_or_default())
376 }
377
378 #[cfg(feature = "compress")]
379 #[inline(never)]
380 fn decompress(&self, payload: Option<Bytes>, fin: bool) -> Result<Bytes, ProtocolError> {
381 let payload = payload.unwrap_or_default();
382 if fin {
383 self.remove_flags(Flags::R_COMPRESSED);
384 }
385 self.deflate
386 .as_ref()
387 .expect("compressed messages require the extension")
388 .decompress(&payload, fin, self.is_server(), self.max_size)
389 .map(BytesMut::freeze)
390 }
391
392 fn check_data(
397 &self,
398 data: Bytes,
399 first: Option<bool>,
400 fin: bool,
401 ) -> Result<Bytes, ProtocolError> {
402 let (size, text) = match first {
403 Some(text) => (data.len(), text),
404 None => (
405 self.msg_size.get().saturating_add(data.len()),
406 self.flags().contains(Flags::R_TEXT),
407 ),
408 };
409 if size > self.max_message_size {
410 return Err(ProtocolError::Overflow);
411 }
412 if text && self.validate_utf8 {
413 let tail = if first.is_some() {
414 Utf8Tail::default()
415 } else {
416 self.utf8_tail.get()
417 };
418 self.utf8_tail.set(validate_utf8(tail, &data, fin)?);
419 }
420
421 if !fin {
422 self.msg_size.set(size);
423 if text {
424 self.insert_flags(Flags::R_TEXT);
425 } else {
426 self.remove_flags(Flags::R_TEXT);
427 }
428 }
429 Ok(data)
430 }
431
432 pub fn encode_page(&self, page: BytePage, dst: &mut BytePages) -> Result<(), ProtocolError> {
440 if self.is_closed() {
441 return Err(ProtocolError::Closed);
442 }
443 if self.flags().contains(Flags::W_CONTINUATION) {
444 return Err(ProtocolError::ContinuationStarted);
445 }
446 self.write_data(dst, page, OpCode::Binary, true, true)
447 .expect("binary frames are always valid");
448 Ok(())
449 }
450}
451
452impl Default for Codec {
453 fn default() -> Self {
454 Self::new()
455 }
456}
457
458impl Encoder for Codec {
459 type Item = Message;
460 type Error = ProtocolError;
461
462 fn encode(&self, item: Message, dst: &mut BytePages) -> Result<(), Self::Error> {
463 if self.is_closed() {
464 return Err(ProtocolError::Closed);
465 }
466
467 match item {
468 Message::Text(txt) => {
469 if self.flags().contains(Flags::W_CONTINUATION) {
470 return Err(ProtocolError::ContinuationStarted);
471 }
472 self.write_data(dst, txt, OpCode::Text, true, true)?;
473 }
474 Message::Binary(bin) => {
475 if self.flags().contains(Flags::W_CONTINUATION) {
476 return Err(ProtocolError::ContinuationStarted);
477 }
478 self.write_data(dst, bin, OpCode::Binary, true, true)?;
479 }
480 Message::Ping(txt) => {
481 Parser::write_message(dst, txt, OpCode::Ping, true, !self.is_server())?;
482 }
483 Message::Pong(txt) => {
484 Parser::write_message(dst, txt, OpCode::Pong, true, !self.is_server())?;
485 self.insert_flags(Flags::W_PONG);
486 }
487 Message::Close(reason) => {
488 Parser::write_close(dst, reason, !self.is_server())?;
489 self.insert_flags(Flags::CLOSED);
490 }
491 Message::Continuation(cont) => match cont {
492 Item::FirstText(data) => {
493 if self.flags().contains(Flags::W_CONTINUATION) {
494 return Err(ProtocolError::ContinuationStarted);
495 }
496 self.insert_flags(Flags::W_CONTINUATION);
497 self.write_data(dst, data, OpCode::Text, true, false)?;
498 }
499 Item::FirstBinary(data) => {
500 if self.flags().contains(Flags::W_CONTINUATION) {
501 return Err(ProtocolError::ContinuationStarted);
502 }
503 self.insert_flags(Flags::W_CONTINUATION);
504 self.write_data(dst, data, OpCode::Binary, true, false)?;
505 }
506 Item::Continue(data) => {
507 if self.flags().contains(Flags::W_CONTINUATION) {
508 self.write_data(dst, data, OpCode::Continue, false, false)?;
509 } else {
510 return Err(ProtocolError::ContinuationNotStarted);
511 }
512 }
513 Item::Last(data) => {
514 if self.flags().contains(Flags::W_CONTINUATION) {
515 self.remove_flags(Flags::W_CONTINUATION);
516 self.write_data(dst, data, OpCode::Continue, false, true)?;
517 } else {
518 return Err(ProtocolError::ContinuationNotStarted);
519 }
520 }
521 },
522 }
523 Ok(())
524 }
525}
526
527impl Decoder for Codec {
528 type Item = Frame;
529 type Error = ProtocolError;
530
531 fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
532 if self.flags().contains(Flags::R_CLOSED) {
534 src.clear();
535 return Ok(None);
536 }
537
538 let Some((finished, rsv1, opcode, payload)) =
539 Parser::parse_frame(src, self.is_server(), self.max_size, self.is_compressed())?
540 else {
541 return Ok(None);
542 };
543
544 if rsv1 {
546 if !matches!(opcode, OpCode::Text | OpCode::Binary) {
547 return Err(ProtocolError::ReservedBits(0b100));
548 }
549 if !self.flags().contains(Flags::R_CONTINUATION) {
550 self.insert_flags(Flags::R_COMPRESSED);
551 }
552 }
553
554 if finished {
556 match opcode {
557 OpCode::Continue => {
558 if self.flags().contains(Flags::R_CONTINUATION) {
559 self.remove_flags(Flags::R_CONTINUATION);
560 let data = self.read_data(payload, true)?;
561 Ok(Some(Frame::Continuation(Item::Last(
562 self.check_data(data, None, true)?,
563 ))))
564 } else {
565 Err(ProtocolError::ContinuationNotStarted)
566 }
567 }
568 OpCode::Close => {
569 let reason = if let Some(pl) = payload {
570 Parser::parse_close_payload(&pl)?
571 } else {
572 None
573 };
574 self.insert_flags(Flags::R_CLOSED);
575 Ok(Some(Frame::Close(reason)))
576 }
577 OpCode::Ping => Ok(Some(Frame::Ping(payload.unwrap_or_default()))),
578 OpCode::Pong => Ok(Some(Frame::Pong(payload.unwrap_or_default()))),
579 OpCode::Binary => {
580 if self.flags().contains(Flags::R_CONTINUATION) {
581 Err(ProtocolError::ContinuationStarted)
582 } else {
583 let data = self.read_data(payload, true)?;
584 Ok(Some(Frame::Binary(self.check_data(
585 data,
586 Some(false),
587 true,
588 )?)))
589 }
590 }
591 OpCode::Text => {
592 if self.flags().contains(Flags::R_CONTINUATION) {
593 Err(ProtocolError::ContinuationStarted)
594 } else {
595 let data = self.read_data(payload, true)?;
596 Ok(Some(Frame::Text(self.check_data(
597 data,
598 Some(true),
599 true,
600 )?)))
601 }
602 }
603 }
604 } else {
605 match opcode {
606 OpCode::Continue => {
607 if self.flags().contains(Flags::R_CONTINUATION) {
608 let data = self.read_data(payload, false)?;
609 Ok(Some(Frame::Continuation(Item::Continue(
610 self.check_data(data, None, false)?,
611 ))))
612 } else {
613 Err(ProtocolError::ContinuationNotStarted)
614 }
615 }
616 OpCode::Binary => {
617 if self.flags().contains(Flags::R_CONTINUATION) {
618 Err(ProtocolError::ContinuationStarted)
619 } else {
620 self.insert_flags(Flags::R_CONTINUATION);
621 let data = self.read_data(payload, false)?;
622 Ok(Some(Frame::Continuation(Item::FirstBinary(
623 self.check_data(data, Some(false), false)?,
624 ))))
625 }
626 }
627 OpCode::Text => {
628 if self.flags().contains(Flags::R_CONTINUATION) {
629 Err(ProtocolError::ContinuationStarted)
630 } else {
631 self.insert_flags(Flags::R_CONTINUATION);
632 let data = self.read_data(payload, false)?;
633 Ok(Some(Frame::Continuation(Item::FirstText(
634 self.check_data(data, Some(true), false)?,
635 ))))
636 }
637 }
638 OpCode::Ping | OpCode::Pong | OpCode::Close => {
640 Err(ProtocolError::FragmentedControlFrame(opcode))
641 }
642 }
643 }
644 }
645}
646
647#[cfg(test)]
648mod tests {
649 use super::*;
650 use crate::ws::CloseCode;
651
652 #[test]
660 fn text_payload_is_validated() {
661 let codec = Codec::new().set_client_mode();
662 assert!(matches!(
663 decode(&codec, &[0x81, 0x01, 0xff]),
664 Err(ProtocolError::InvalidUtf8)
665 ));
666 assert!(matches!(
667 decode(&Codec::new().set_client_mode(), b"\x81\x02a\xe2"),
668 Err(ProtocolError::InvalidUtf8)
669 ));
670 assert!(matches!(
671 decode(&Codec::new().set_client_mode(), b"\x81\x03a\xc3\xa9"),
672 Ok(Some(Frame::Text(data))) if data == "a\u{e9}".as_bytes()
673 ));
674
675 let codec = Codec::new().set_client_mode().validate_utf8(false);
676 assert!(matches!(
677 decode(&codec, &[0x81, 0x01, 0xff]),
678 Ok(Some(Frame::Text(data))) if data == Bytes::from_static(&[0xff])
679 ));
680 }
681
682 #[test]
689 fn fragmented_text_is_validated() {
690 let codec = Codec::new().set_client_mode();
691 for frame in [
692 &b"\x01\x02a\xe2"[..],
693 b"\x00\x00",
694 b"\x00\x01\x82",
695 b"\x80\x02\xacb",
696 ] {
697 assert!(matches!(
698 decode(&codec, frame),
699 Ok(Some(Frame::Continuation(_)))
700 ));
701 }
702
703 let codec = Codec::new().set_client_mode();
704 assert!(decode(&codec, b"\x01\x01\xe2").is_ok());
705 assert!(matches!(
706 decode(&codec, b"\x80\x01a"),
707 Err(ProtocolError::InvalidUtf8)
708 ));
709
710 let codec = Codec::new().set_client_mode();
711 assert!(decode(&codec, b"\x01\x02a\xe2").is_ok());
712 assert!(decode(&codec, b"\x00\x01\x82").is_ok());
713 assert!(matches!(
714 decode(&codec, b"\x80\x00"),
715 Err(ProtocolError::InvalidUtf8)
716 ));
717
718 let codec = Codec::new().set_client_mode();
719 assert!(decode(&codec, b"\x01\x01a").is_ok());
720 assert!(matches!(
721 decode(&codec, b"\x00\x02b\xff"),
722 Err(ProtocolError::InvalidUtf8)
723 ));
724
725 let codec = Codec::new().set_client_mode();
726 assert!(decode(&codec, b"\x02\x01\xe2").is_ok());
727 assert!(matches!(
728 decode(&codec, b"\x80\x01\xff"),
729 Ok(Some(Frame::Continuation(Item::Last(_))))
730 ));
731 }
732
733 #[test]
739 fn message_size_limit() {
740 let codec = Codec::new().set_client_mode().max_message_size(3);
741 for _ in 0..2 {
742 assert!(decode(&codec, b"\x02\x02ab").is_ok());
743 assert!(matches!(
744 decode(&codec, b"\x89\x04ping"),
745 Ok(Some(Frame::Ping(_)))
746 ));
747 assert!(matches!(
748 decode(&codec, b"\x80\x01c"),
749 Ok(Some(Frame::Continuation(Item::Last(_))))
750 ));
751 }
752
753 assert!(decode(&codec, b"\x01\x02ab").is_ok());
754 assert!(decode(&codec, b"\x00\x01c").is_ok());
755 assert!(matches!(
756 decode(&codec, b"\x80\x01d"),
757 Err(ProtocolError::Overflow)
758 ));
759
760 let codec = Codec::new().set_client_mode().max_message_size(3);
761 assert!(matches!(
762 decode(&codec, b"\x82\x04abcd"),
763 Err(ProtocolError::Overflow)
764 ));
765 }
766
767 #[test]
772 fn input_after_close_is_discarded() {
773 let codec = Codec::new().set_client_mode();
774 let mut src = BytesMut::from(&[0x88, 0x00, 0x81, 0x01, b'a'][..]);
776 assert!(matches!(
777 codec.decode(&mut src),
778 Ok(Some(Frame::Close(None)))
779 ));
780 assert!(matches!(codec.decode(&mut src), Ok(None)));
781 assert!(src.is_empty());
782
783 src.extend_from_slice(&[0x81, 0x01, b'b']);
784 assert!(matches!(codec.decode(&mut src), Ok(None)));
785 assert!(src.is_empty());
786 }
787
788 #[test]
793 fn accepts_extension_close_code() {
794 let codec = Codec::new().set_client_mode();
796 let mut close = BytesMut::from(&[0x88, 0x02, 0x03, 0xf2][..]);
797 assert!(matches!(
798 codec.decode(&mut close),
799 Ok(Some(Frame::Close(Some(CloseReason {
800 code: CloseCode::Extension,
801 ..
802 }))))
803 ));
804
805 let codec = Codec::new();
807 let mut dst = BytePages::default();
808 assert!(matches!(
809 codec.encode(Message::Close(Some(CloseCode::Extension.into())), &mut dst),
810 Err(ProtocolError::InvalidCloseCode(1010))
811 ));
812 }
813
814 #[test]
819 fn validates_outgoing_continuations() {
820 let codec = Codec::new();
821 let mut dst = BytePages::default();
822 codec
823 .encode(
824 Message::Continuation(Item::FirstBinary(Bytes::new())),
825 &mut dst,
826 )
827 .unwrap();
828 assert!(matches!(
829 codec.encode(Message::Text("text".into()), &mut dst),
830 Err(ProtocolError::ContinuationStarted)
831 ));
832 assert!(matches!(
833 codec.encode_page(BytePage::from(Bytes::new()), &mut dst),
834 Err(ProtocolError::ContinuationStarted)
835 ));
836
837 codec
838 .encode(Message::Continuation(Item::Last(Bytes::new())), &mut dst)
839 .unwrap();
840 codec
841 .encode_page(BytePage::from(Bytes::new()), &mut dst)
842 .unwrap();
843 }
844
845 #[test]
850 fn rejects_messages_after_close() {
851 let codec = Codec::new();
852 let mut dst = BytePages::default();
853 codec.encode(Message::Close(None), &mut dst).unwrap();
854
855 assert!(matches!(
856 codec.encode(Message::Text("text".into()), &mut dst),
857 Err(ProtocolError::Closed)
858 ));
859 assert!(matches!(
860 codec.encode_page(BytePage::from(Bytes::new()), &mut dst),
861 Err(ProtocolError::Closed)
862 ));
863 }
864
865 #[test]
870 fn encode_errors() {
871 let codec = Codec::new();
872 let mut dst = BytePages::default();
873 let big = Bytes::from(vec![0; 126]);
874 assert!(matches!(
875 codec.encode(Message::Ping(big.clone()), &mut dst),
876 Err(ProtocolError::InvalidLength(126))
877 ));
878 assert!(matches!(
879 codec.encode(Message::Pong(big), &mut dst),
880 Err(ProtocolError::InvalidLength(126))
881 ));
882
883 codec
884 .encode(Message::Continuation(Item::FirstText("a".into())), &mut dst)
885 .unwrap();
886 assert!(matches!(
887 codec.encode(Message::Binary("b".into()), &mut dst),
888 Err(ProtocolError::ContinuationStarted)
889 ));
890 assert!(matches!(
891 codec.encode(
892 Message::Continuation(Item::FirstBinary("b".into())),
893 &mut dst
894 ),
895 Err(ProtocolError::ContinuationStarted)
896 ));
897 codec
898 .encode(Message::Continuation(Item::Last("c".into())), &mut dst)
899 .unwrap();
900 assert!(matches!(
901 codec.encode(Message::Continuation(Item::Continue("d".into())), &mut dst),
902 Err(ProtocolError::ContinuationNotStarted)
903 ));
904 }
905
906 fn decode(codec: &Codec, frame: &[u8]) -> Result<Option<Frame>, ProtocolError> {
907 codec.decode(&mut BytesMut::from(frame))
908 }
909
910 #[test]
916 fn decode_continuation_errors() {
917 let codec = Codec::new().set_client_mode();
918 assert!(matches!(
920 decode(&codec, &[0x80, 0x01, b'a']),
921 Err(ProtocolError::ContinuationNotStarted)
922 ));
923 assert!(matches!(
924 decode(&codec, &[0x00, 0x01, b'a']),
925 Err(ProtocolError::ContinuationNotStarted)
926 ));
927
928 assert!(matches!(
930 decode(&codec, &[0x02, 0x01, b'a']),
931 Ok(Some(Frame::Continuation(Item::FirstBinary(_))))
932 ));
933 for frame in [
934 &[0x82, 0x01, b'a'],
935 &[0x81, 0x01, b'a'],
936 &[0x02, 0x01, b'a'],
937 &[0x01, 0x01, b'a'],
938 ] {
939 assert!(matches!(
940 decode(&codec, frame),
941 Err(ProtocolError::ContinuationStarted)
942 ));
943 }
944 assert!(matches!(
945 decode(&codec, &[0x00, 0x01, b'b']),
946 Ok(Some(Frame::Continuation(Item::Continue(_))))
947 ));
948 assert!(matches!(
949 decode(&codec, &[0x80, 0x00]),
950 Ok(Some(Frame::Continuation(Item::Last(data)))) if data.is_empty()
951 ));
952 }
953
954 #[cfg(feature = "compress")]
955 mod deflate {
956 use super::*;
957 use crate::ws::DeflateConfig;
958
959 fn client() -> Codec {
960 Codec::new()
961 .set_client_mode()
962 .set_deflate(DeflateConfig::new())
963 }
964
965 fn server() -> Codec {
966 Codec::new().set_deflate(DeflateConfig::new())
967 }
968
969 fn encode(codec: &Codec, msg: Message) -> BytesMut {
970 let mut dst = BytePages::default();
971 codec.encode(msg, &mut dst).unwrap();
972 BytesMut::from(&Bytes::from(dst)[..])
973 }
974
975 fn decode_all(codec: &Codec, mut src: BytesMut) -> Vec<Frame> {
976 let mut frames = Vec::new();
977 while let Some(frame) = codec.decode(&mut src).unwrap() {
978 frames.push(frame);
979 }
980 assert!(src.is_empty());
981 frames
982 }
983
984 fn text(data: &'static str) -> Frame {
985 Frame::Text(Bytes::from_static(data.as_bytes()))
986 }
987
988 #[test]
994 fn rfc7692_examples() {
995 let frames = decode_all(
997 &client(),
998 BytesMut::from(&[0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00][..]),
999 );
1000 assert_eq!(frames, [text("Hello")]);
1001 let frames = decode_all(
1002 &client(),
1003 BytesMut::from(
1004 &[
1005 0x41, 0x03, 0xf2, 0x48, 0xcd, 0x80, 0x04, 0xc9, 0xc9, 0x07, 0x00,
1006 ][..],
1007 ),
1008 );
1009 assert_eq!(
1010 frames,
1011 [
1012 Frame::Continuation(Item::FirstText(Bytes::from_static(b"He"))),
1013 Frame::Continuation(Item::Last(Bytes::from_static(b"llo"))),
1014 ]
1015 );
1016
1017 let frames = decode_all(
1019 &client(),
1020 BytesMut::from(
1021 &[
1022 0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00, 0xc1, 0x05, 0xf2,
1023 0x00, 0x11, 0x00, 0x00,
1024 ][..],
1025 ),
1026 );
1027 assert_eq!(frames, [text("Hello"), text("Hello")]);
1028
1029 let frames = decode_all(
1034 &client(),
1035 BytesMut::from(
1036 &[
1037 0xc1, 0x0b, 0x00, 0x05, 0x00, 0xfa, 0xff, 0x48, 0x65, 0x6c, 0x6c, 0x6f,
1038 0x00, 0xc1, 0x08, 0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00, 0x00, 0xc1,
1039 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00, 0xc1, 0x0d, 0xf2, 0x48,
1040 0x05, 0x00, 0x00, 0x00, 0xff, 0xff, 0xca, 0xc9, 0xc9, 0x07, 0x00, 0xc1,
1041 0x01, 0x00, 0xc1, 0x00,
1042 ][..],
1043 ),
1044 );
1045 assert_eq!(
1046 frames,
1047 [
1048 text("Hello"),
1049 text("Hello"),
1050 text("Hello"),
1051 text("Hello"),
1052 text(""),
1053 text("")
1054 ]
1055 );
1056 }
1057
1058 #[test]
1064 fn small_messages_without_context_takeover() {
1065 let cfg = DeflateConfig::new().set_server_no_context_takeover(true);
1066 let server = Codec::new().set_deflate(cfg.clone());
1067 let client = Codec::new().set_client_mode().set_deflate(cfg);
1068
1069 for (len, first) in [(0, 0x82), (32, 0x82), (33, 0xc2)] {
1071 let data = Bytes::from("a".repeat(len));
1072 let frame = encode(&server, Message::Binary(data.clone()));
1073 assert_eq!(frame[0], first);
1074 assert_eq!(decode_all(&client, frame), [Frame::Binary(data)]);
1075 }
1076
1077 let frame = encode(
1079 &server,
1080 Message::Continuation(Item::FirstText(Bytes::from_static(b"a"))),
1081 );
1082 assert_eq!(frame[0], 0x41);
1083
1084 let frame = encode(&client, Message::Text("Hello".into()));
1086 assert_eq!(frame[0], 0xc1);
1087 }
1088
1089 #[test]
1094 fn encode_rfc7692_example() {
1095 let codec = Codec::new().set_deflate(DeflateConfig::new());
1096 assert_eq!(
1097 &encode(&codec, Message::Text("Hello".into()))[..],
1098 &[0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00]
1099 );
1100 }
1101
1102 #[test]
1108 fn roundtrip() {
1109 let (client, server) = (client(), server());
1110 let data: Vec<u8> = (0..60_000u32)
1111 .map(|i| if i % 7 == 0 { (i >> 3) as u8 } else { b'a' })
1112 .collect();
1113 let data = Bytes::from(data);
1114
1115 for _ in 0..3 {
1116 for (from, to) in [(&client, &server), (&server, &client)] {
1117 let msgs = [
1118 Message::Text("text message".into()),
1119 Message::Binary(data.clone()),
1120 Message::Binary(Bytes::new()),
1121 Message::Ping("ping".into()),
1122 Message::Continuation(Item::FirstBinary(data.slice(..1000))),
1123 Message::Pong("pong".into()),
1124 Message::Continuation(Item::Continue(Bytes::new())),
1125 Message::Continuation(Item::Continue(data.slice(1000..30_000))),
1126 Message::Continuation(Item::Last(data.slice(30_000..))),
1127 Message::Continuation(Item::FirstText("a".into())),
1128 Message::Continuation(Item::Last("b".into())),
1129 ];
1130 let mut src = BytesMut::new();
1131 for msg in msgs {
1132 src.extend_from_slice(&encode(from, msg));
1133 }
1134 assert_eq!(
1135 decode_all(to, src),
1136 [
1137 text("text message"),
1138 Frame::Binary(data.clone()),
1139 Frame::Binary(Bytes::new()),
1140 Frame::Ping("ping".into()),
1141 Frame::Continuation(Item::FirstBinary(data.slice(..1000))),
1142 Frame::Pong("pong".into()),
1143 Frame::Continuation(Item::Continue(Bytes::new())),
1144 Frame::Continuation(Item::Continue(data.slice(1000..30_000))),
1145 Frame::Continuation(Item::Last(data.slice(30_000..))),
1146 Frame::Continuation(Item::FirstText("a".into())),
1147 Frame::Continuation(Item::Last("b".into())),
1148 ]
1149 );
1150 }
1151 }
1152 }
1153
1154 #[test]
1160 fn fragmented_compressed_payload() {
1161 let sender = server();
1164 let codec = client();
1165 let data = Bytes::from(b"Hello, Hello, Hello".repeat(40));
1166 for _ in 0..3 {
1167 let mut frame = encode(&sender, Message::Binary(data.clone()));
1168 frame.advance_to(2);
1169 let len = frame.len();
1170 frame.advance_to(if len < 126 { 0 } else { 2 });
1171 let payload = frame.freeze();
1172 let chunks: Vec<_> = payload.chunks(16).chain([&[][..]]).collect();
1173
1174 let mut src = BytesMut::new();
1175 for (i, chunk) in chunks.iter().enumerate() {
1176 let mut first = if i == 0 { 0x42 } else { 0x00 };
1177 if i == chunks.len() - 1 {
1178 first |= 0x80;
1179 }
1180 src.extend_from_slice(&[first, chunk.len() as u8]);
1181 src.extend_from_slice(chunk);
1182 }
1183 let mut out = BytesMut::new();
1184 for frame in decode_all(&codec, src) {
1185 match frame {
1186 Frame::Continuation(
1187 Item::FirstBinary(b) | Item::Continue(b) | Item::Last(b),
1188 ) => out.extend_from_slice(&b),
1189 f => panic!("{f:?}"),
1190 }
1191 }
1192 assert_eq!(out, data);
1193 }
1194 }
1195
1196 #[test]
1202 fn rsv1_only_on_first_data_frame() {
1203 let codec = server();
1204 let data = Bytes::from(vec![b'x'; 1000]);
1205 let frame = encode(&codec, Message::Binary(data.clone()));
1206 assert_eq!(frame[0], 0xc2);
1207 assert!(frame.len() < 100);
1208
1209 let frame = encode(&codec, Message::Continuation(Item::FirstText("a".into())));
1210 assert_eq!(frame[0], 0x41);
1211 let frame = encode(&codec, Message::Continuation(Item::Continue("b".into())));
1212 assert_eq!(frame[0], 0x00);
1213 let frame = encode(&codec, Message::Continuation(Item::Last("c".into())));
1214 assert_eq!(frame[0], 0x80);
1215
1216 let frame = encode(&codec, Message::Ping("ping".into()));
1218 assert_eq!(&frame[..], b"\x89\x04ping");
1219 let frame = encode(&codec, Message::Close(None));
1220 assert_eq!(&frame[..], &[0x88, 0x00]);
1221
1222 let mut dst = BytePages::default();
1224 server()
1225 .encode_page(BytePage::from(data.clone()), &mut dst)
1226 .unwrap();
1227 let mut src = BytesMut::from(&Bytes::from(dst)[..]);
1228 assert_eq!(src[0], 0xc2);
1229 assert_eq!(
1230 client().decode(&mut src).unwrap(),
1231 Some(Frame::Binary(data))
1232 );
1233 }
1234
1235 #[test]
1241 fn uncompressed_messages() {
1242 let codec = client();
1244 let frames = decode_all(
1245 &codec,
1246 BytesMut::from(&b"\x81\x05Hello\x01\x01a\x80\x01b\xc1\x01\x00\x82\x01c"[..]),
1247 );
1248 assert_eq!(
1249 frames,
1250 [
1251 text("Hello"),
1252 Frame::Continuation(Item::FirstText("a".into())),
1253 Frame::Continuation(Item::Last("b".into())),
1254 text(""),
1255 Frame::Binary("c".into()),
1256 ]
1257 );
1258 }
1259
1260 #[test]
1266 fn reserved_bits() {
1267 for frame in [
1268 &b"\xc9\x00"[..],
1270 b"\xca\x00",
1271 b"\xc8\x00",
1272 b"\xa1\x00",
1274 b"\x91\x00",
1275 b"\xe1\x00",
1276 ] {
1277 assert!(
1278 matches!(
1279 decode(&client(), frame),
1280 Err(ProtocolError::ReservedBits(_))
1281 ),
1282 "{frame:?}"
1283 );
1284 }
1285
1286 let codec = client();
1287 assert!(matches!(
1288 decode(&codec, b"\x01\x01a"),
1289 Ok(Some(Frame::Continuation(Item::FirstText(_))))
1290 ));
1291 assert!(matches!(
1292 decode(&codec, b"\xc0\x01\x00"),
1293 Err(ProtocolError::ReservedBits(0b100))
1294 ));
1295
1296 assert!(matches!(
1298 decode(
1299 &Codec::new().set_client_mode(),
1300 &[0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00]
1301 ),
1302 Err(ProtocolError::ReservedBits(0b100))
1303 ));
1304 }
1305
1306 #[test]
1311 fn invalid_data() {
1312 assert!(matches!(
1313 decode(&client(), b"\xc1\x02\xff\xff"),
1314 Err(ProtocolError::InvalidCompressedData)
1315 ));
1316 assert!(matches!(
1317 decode(&client(), b"\x41\x02\xff\xff"),
1318 Err(ProtocolError::InvalidCompressedData)
1319 ));
1320 }
1321
1322 #[test]
1328 fn decompressed_size_limit() {
1329 let data = Bytes::from(vec![0; 1024 * 1024]);
1330 let frame = encode(&server(), Message::Binary(data.clone()));
1331 assert!(frame.len() < 2048);
1332
1333 let codec = Codec::new()
1334 .set_client_mode()
1335 .max_size(data.len() - 1)
1336 .set_deflate(DeflateConfig::new());
1337 assert!(matches!(
1338 codec.decode(&mut frame.clone()),
1339 Err(ProtocolError::Overflow)
1340 ));
1341
1342 let codec = Codec::new()
1343 .set_client_mode()
1344 .max_size(data.len())
1345 .set_deflate(DeflateConfig::new());
1346 assert_eq!(
1347 codec.decode(&mut frame.clone()).unwrap(),
1348 Some(Frame::Binary(data))
1349 );
1350
1351 let codec = Codec::new()
1353 .set_client_mode()
1354 .max_size(1000)
1355 .set_deflate(DeflateConfig::new());
1356 let sender = server();
1357 let mut src = encode(
1358 &sender,
1359 Message::Continuation(Item::FirstBinary(vec![0; 1000].into())),
1360 );
1361 src.extend_from_slice(&encode(
1362 &sender,
1363 Message::Continuation(Item::Last(vec![0; 1001].into())),
1364 ));
1365 assert!(matches!(
1366 codec.decode(&mut src),
1367 Ok(Some(Frame::Continuation(Item::FirstBinary(_))))
1368 ));
1369 assert!(matches!(
1370 codec.decode(&mut src),
1371 Err(ProtocolError::Overflow)
1372 ));
1373 }
1374
1375 #[test]
1381 fn message_limits_after_decompression() {
1382 let sender = server();
1383 let codec = client().max_message_size(1500);
1384 let mut src = encode(
1385 &sender,
1386 Message::Continuation(Item::FirstBinary(vec![0; 1000].into())),
1387 );
1388 src.extend_from_slice(&encode(
1389 &sender,
1390 Message::Continuation(Item::Last(vec![0; 1000].into())),
1391 ));
1392 assert!(src.len() < 1500);
1393 assert!(matches!(
1394 codec.decode(&mut src),
1395 Ok(Some(Frame::Continuation(Item::FirstBinary(_))))
1396 ));
1397 assert!(matches!(
1398 codec.decode(&mut src),
1399 Err(ProtocolError::Overflow)
1400 ));
1401
1402 let src = encode(
1403 &server(),
1404 Message::Continuation(Item::FirstText(Bytes::from_static(&[0xff]))),
1405 );
1406 assert!(matches!(
1407 client().decode(&mut src.clone()),
1408 Err(ProtocolError::InvalidUtf8)
1409 ));
1410 }
1411
1412 #[test]
1418 fn context_takeover() {
1419 let cfg = DeflateConfig::new().set_server_no_context_takeover(true);
1422 let server = Codec::new().set_deflate(cfg.clone());
1423 let client = Codec::new().set_client_mode().set_deflate(cfg);
1424 let first = encode(&server, Message::Text("Hello".into()));
1425 assert_eq!(encode(&server, Message::Text("Hello".into())), first);
1426 let mut src = first.clone();
1427 src.extend_from_slice(&first);
1428 assert_eq!(decode_all(&client, src), [text("Hello"), text("Hello")]);
1429
1430 assert!(matches!(
1432 decode(&client, &[0xc1, 0x05, 0xf2, 0x00, 0x11, 0x00, 0x00]),
1433 Err(ProtocolError::InvalidCompressedData)
1434 ));
1435
1436 let first = encode(&client, Message::Text("Hello".into()));
1438 assert!(encode(&client, Message::Text("Hello".into())).len() < first.len());
1439 }
1440
1441 #[test]
1446 fn clones_share_state() {
1447 let (client, server) = (client(), server());
1448 let server2 = server.clone();
1449 assert_eq!(server2.deflate(), Some(&DeflateConfig::new()));
1450 assert_eq!(Codec::new().deflate(), None);
1451
1452 let mut src = encode(&server, Message::Text("Hello".into()));
1453 src.extend_from_slice(&encode(&server2, Message::Text("Hello".into())));
1454 assert_eq!(decode_all(&client, src), [text("Hello"), text("Hello")]);
1455 }
1456 }
1457}