From 618cb9874dc4978b29659e382e7e561d31f305cb Mon Sep 17 00:00:00 2001 From: yhx-12243 Date: Wed, 14 Aug 2024 10:18:57 -0400 Subject: [PATCH] fix: reject invalid binary event (resolve #357) (#358) --- socketioxide/src/packet.rs | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/socketioxide/src/packet.rs b/socketioxide/src/packet.rs index 3968775c..261414a9 100644 --- a/socketioxide/src/packet.rs +++ b/socketioxide/src/packet.rs @@ -445,19 +445,21 @@ impl<'a> TryFrom for Packet<'a> { fn try_from(value: Str) -> Result { let chars = value.as_bytes(); // It is possible to parse the packet from a byte slice because separators are only ASCII - let mut i = 1; let index = (b'0'..=b'6') .contains(&chars[0]) .then_some(chars[0]) .ok_or(Error::InvalidPacketType)?; // Move the cursor to skip the payload count if it is a binary packet - if index == b'5' || index == b'6' { - while chars.get(i) != Some(&b'-') { - i += 1; - } - i += 1; - } + let mut i = if index == b'5' || index == b'6' { + chars + .iter() + .position(|x| *x == b'-') + .ok_or(Error::InvalidPacketType)? + + 1 + } else { + 1 + }; let start_index = i; // Custom nsps will start with a slash @@ -919,4 +921,12 @@ mod test { let packet = Packet::bin_ack("/", json!("data"), vec![Bytes::from_static(&[1])], 54); assert_eq!(packet.get_size_hint(), 5); } + + #[test] + fn packet_reject_invalid_binary_event() { + let payload = "5invalid".to_owned(); + let err = Packet::try_from(payload).unwrap_err(); + + assert!(matches!(err, Error::InvalidPacketType)); + } }