Skip to main content

socketio_next/protocol/
engineio.rs

1use base64::{Engine as _, engine::general_purpose};
2use bytes::{BufMut, Bytes, BytesMut};
3use serde::{Deserialize, Serialize};
4use std::char;
5use std::convert::TryFrom;
6use std::convert::TryInto;
7use std::fmt::{Display, Formatter, Result as FmtResult, Write};
8use std::ops::Index;
9
10use crate::protocol::error::{Error, Result};
11/// Enumeration of the `engine.io` `Packet` types.
12#[derive(Copy, Clone, Eq, PartialEq, Debug)]
13pub enum PacketId {
14    Open,
15    Close,
16    Ping,
17    Pong,
18    Message,
19    // A type of message that is base64 encoded
20    MessageBinary,
21    Upgrade,
22    Noop,
23}
24
25impl PacketId {
26    /// Returns the byte that represents the [`PacketId`] as a [`char`].
27    fn to_string_byte(self) -> u8 {
28        match self {
29            Self::MessageBinary => b'b',
30            _ => u8::from(self) + b'0',
31        }
32    }
33}
34
35impl Display for PacketId {
36    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
37        f.write_char(self.to_string_byte() as char)
38    }
39}
40
41impl From<PacketId> for u8 {
42    fn from(packet_id: PacketId) -> Self {
43        match packet_id {
44            PacketId::Open => 0,
45            PacketId::Close => 1,
46            PacketId::Ping => 2,
47            PacketId::Pong => 3,
48            PacketId::Message => 4,
49            PacketId::MessageBinary => 4,
50            PacketId::Upgrade => 5,
51            PacketId::Noop => 6,
52        }
53    }
54}
55
56impl TryFrom<u8> for PacketId {
57    type Error = Error;
58    /// Converts a byte into the corresponding `PacketId`.
59    fn try_from(b: u8) -> Result<PacketId> {
60        match b {
61            b'0' => Ok(PacketId::Open),
62            b'1' => Ok(PacketId::Close),
63            b'2' => Ok(PacketId::Ping),
64            b'3' => Ok(PacketId::Pong),
65            b'4' => Ok(PacketId::Message),
66            b'5' => Ok(PacketId::Upgrade),
67            b'6' => Ok(PacketId::Noop),
68            _ => Err(Error::InvalidPacketType(b as char)),
69        }
70    }
71}
72
73/// A `Packet` sent via the `engine.io` protocol.
74#[derive(Debug, Clone, Eq, PartialEq)]
75pub struct Packet {
76    pub packet_id: PacketId,
77    pub data: Bytes,
78}
79
80/// Data which gets exchanged in a handshake as defined by the server.
81#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
82pub struct HandshakePacket {
83    pub sid: String,
84    pub upgrades: Vec<String>,
85    #[serde(rename = "pingInterval")]
86    pub ping_interval: u64,
87    #[serde(rename = "pingTimeout")]
88    pub ping_timeout: u64,
89    /// Largest payload the server accepts in one request (engine.io `maxPayload`, bytes).
90    #[serde(
91        rename = "maxPayload",
92        default,
93        skip_serializing_if = "Option::is_none"
94    )]
95    pub max_payload: Option<u64>,
96}
97
98impl TryFrom<Packet> for HandshakePacket {
99    type Error = Error;
100    fn try_from(packet: Packet) -> Result<HandshakePacket> {
101        Ok(serde_json::from_slice(packet.data[..].as_ref())?)
102    }
103}
104
105impl Packet {
106    /// The text encoding of a packet with string data (`2probe`, `5`).
107    pub(crate) fn text(packet_id: PacketId, data: &str) -> String {
108        format!("{packet_id}{data}")
109    }
110
111    /// Creates a new `Packet`.
112    pub fn new<T: Into<Bytes>>(packet_id: PacketId, data: T) -> Self {
113        Packet {
114            packet_id,
115            data: data.into(),
116        }
117    }
118}
119
120impl TryFrom<Bytes> for Packet {
121    type Error = Error;
122    /// Decodes a single `Packet` from an `u8` byte stream.
123    fn try_from(
124        bytes: Bytes,
125    ) -> std::result::Result<Self, <Self as std::convert::TryFrom<Bytes>>::Error> {
126        if bytes.is_empty() {
127            return Err(Error::IncompletePacket);
128        }
129
130        let is_base64 = *bytes.first().ok_or(Error::IncompletePacket)? == b'b';
131
132        // only 'messages' packets could be encoded
133        let packet_id = if is_base64 {
134            PacketId::MessageBinary
135        } else {
136            (*bytes.first().ok_or(Error::IncompletePacket)?).try_into()?
137        };
138
139        // `4` alone is a message with empty data (engine.io-parser accepts it).
140        let data: Bytes = bytes.slice(1..);
141
142        Ok(Packet {
143            packet_id,
144            data: if is_base64 {
145                Bytes::from(general_purpose::STANDARD.decode(data.as_ref())?)
146            } else {
147                data
148            },
149        })
150    }
151}
152
153impl From<Packet> for Bytes {
154    /// Encodes a `Packet` into an `u8` byte stream.
155    fn from(packet: Packet) -> Self {
156        let mut result = BytesMut::with_capacity(packet.data.len() + 1);
157        result.put_u8(packet.packet_id.to_string_byte());
158        if packet.packet_id == PacketId::MessageBinary {
159            result.extend(general_purpose::STANDARD.encode(packet.data).into_bytes());
160        } else {
161            result.put(packet.data);
162        }
163        result.freeze()
164    }
165}
166
167#[derive(Debug, Clone)]
168pub struct Batch(pub Vec<Packet>);
169
170impl Batch {
171    // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
172    pub(crate) const SEPARATOR: char = '\x1e';
173
174    /// Number of packets.
175    pub fn len(&self) -> usize {
176        self.0.len()
177    }
178
179    /// No packets.
180    pub fn is_empty(&self) -> bool {
181        self.0.is_empty()
182    }
183}
184
185/// A websocket frame is exactly one packet (whose binary data may contain the separator).
186impl From<Packet> for Batch {
187    fn from(packet: Packet) -> Self {
188        Self(vec![packet])
189    }
190}
191
192impl TryFrom<Bytes> for Batch {
193    type Error = Error;
194    /// Decodes a `payload` which in the `engine.io` context means a chain of normal
195    /// packets separated by a certain SEPARATOR, in this case the delimiter `\x30`.
196    fn try_from(payload: Bytes) -> Result<Self> {
197        payload
198            .split(|&c| c as char == Self::SEPARATOR)
199            .map(|slice| Packet::try_from(payload.slice_ref(slice)))
200            .collect::<Result<Vec<_>>>()
201            .map(Self)
202    }
203}
204
205impl TryFrom<Batch> for Bytes {
206    type Error = Error;
207    /// Encodes a payload. Batch in the `engine.io` context means a chain of
208    /// normal `packets` separated by a SEPARATOR, in this case the delimiter
209    /// `\x30`.
210    fn try_from(packets: Batch) -> Result<Self> {
211        let mut buf = BytesMut::new();
212        for (i, packet) in packets.into_iter().enumerate() {
213            if i > 0 {
214                buf.put_u8(Batch::SEPARATOR as u8);
215            }
216            // binary packets go as `b` + base64 (engine.io-parser encodePayload)
217            buf.extend(Bytes::from(packet));
218        }
219        Ok(buf.freeze())
220    }
221}
222
223#[derive(Clone, Debug)]
224pub struct IntoIter {
225    iter: std::vec::IntoIter<Packet>,
226}
227
228impl Iterator for IntoIter {
229    type Item = Packet;
230    fn next(&mut self) -> std::option::Option<<Self as std::iter::Iterator>::Item> {
231        self.iter.next()
232    }
233}
234
235impl IntoIterator for Batch {
236    type Item = Packet;
237    type IntoIter = IntoIter;
238    fn into_iter(self) -> <Self as std::iter::IntoIterator>::IntoIter {
239        IntoIter {
240            iter: self.0.into_iter(),
241        }
242    }
243}
244
245impl Index<usize> for Batch {
246    type Output = Packet;
247    fn index(&self, index: usize) -> &Packet {
248        &self.0[index]
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255
256    #[test]
257    fn test_packet_error() {
258        let err = Packet::try_from(BytesMut::with_capacity(10).freeze());
259        assert!(err.is_err())
260    }
261
262    #[test]
263    fn test_is_reflexive() {
264        let data = Bytes::from_static(b"1Hello World");
265        let packet = Packet::try_from(data).unwrap();
266
267        assert_eq!(packet.packet_id, PacketId::Close);
268        assert_eq!(packet.data, Bytes::from_static(b"Hello World"));
269
270        let data = Bytes::from_static(b"1Hello World");
271        assert_eq!(Bytes::from(packet), data);
272    }
273
274    #[test]
275    fn test_binary_packet() {
276        // SGVsbG8= is the encoded string for 'Hello'
277        let data = Bytes::from_static(b"bSGVsbG8=");
278        let packet = Packet::try_from(data.clone()).unwrap();
279
280        assert_eq!(packet.packet_id, PacketId::MessageBinary);
281        assert_eq!(packet.data, Bytes::from_static(b"Hello"));
282
283        assert_eq!(Bytes::from(packet), data);
284    }
285
286    #[test]
287    fn test_decode_payload() -> Result<()> {
288        let data = Bytes::from_static(b"1Hello\x1e1HelloWorld");
289        let packets = Batch::try_from(data)?;
290
291        assert_eq!(packets[0].packet_id, PacketId::Close);
292        assert_eq!(packets[0].data, Bytes::from_static(b"Hello"));
293        assert_eq!(packets[1].packet_id, PacketId::Close);
294        assert_eq!(packets[1].data, Bytes::from_static(b"HelloWorld"));
295
296        let data = "1Hello\x1e1HelloWorld".to_owned().into_bytes();
297        assert_eq!(Bytes::try_from(packets).unwrap(), data);
298
299        Ok(())
300    }
301
302    #[test]
303    fn test_binary_payload() {
304        let data = Bytes::from_static(b"bSGVsbG8=\x1ebSGVsbG9Xb3JsZA==\x1ebSGVsbG8=");
305        let packets = Batch::try_from(data.clone()).unwrap();
306
307        assert!(packets.len() == 3);
308        assert_eq!(packets[0].packet_id, PacketId::MessageBinary);
309        assert_eq!(packets[0].data, Bytes::from_static(b"Hello"));
310        assert_eq!(packets[1].packet_id, PacketId::MessageBinary);
311        assert_eq!(packets[1].data, Bytes::from_static(b"HelloWorld"));
312        assert_eq!(packets[2].packet_id, PacketId::MessageBinary);
313        assert_eq!(packets[2].data, Bytes::from_static(b"Hello"));
314
315        assert_eq!(Bytes::try_from(packets).unwrap(), data);
316    }
317
318    #[test]
319    fn test_packet_id_conversion_and_incompl_packet() -> Result<()> {
320        // engine.io-parser: an empty input is an error, `4` alone an empty message
321        assert!(matches!(
322            Packet::try_from(Bytes::new()),
323            Err(Error::IncompletePacket)
324        ));
325
326        assert_eq!(PacketId::MessageBinary.to_string(), "b");
327
328        let sut = PacketId::try_from(b'0')?;
329        assert_eq!(sut, PacketId::Open);
330        assert_eq!(sut.to_string(), "0");
331
332        let sut = PacketId::try_from(b'1')?;
333        assert_eq!(sut, PacketId::Close);
334        assert_eq!(sut.to_string(), "1");
335
336        let sut = PacketId::try_from(b'2')?;
337        assert_eq!(sut, PacketId::Ping);
338        assert_eq!(sut.to_string(), "2");
339
340        let sut = PacketId::try_from(b'3')?;
341        assert_eq!(sut, PacketId::Pong);
342        assert_eq!(sut.to_string(), "3");
343
344        let sut = PacketId::try_from(b'4')?;
345        assert_eq!(sut, PacketId::Message);
346        assert_eq!(sut.to_string(), "4");
347
348        let sut = PacketId::try_from(b'5')?;
349        assert_eq!(sut, PacketId::Upgrade);
350        assert_eq!(sut.to_string(), "5");
351
352        let sut = PacketId::try_from(b'6')?;
353        assert_eq!(sut, PacketId::Noop);
354        assert_eq!(sut.to_string(), "6");
355
356        // raw bytes are not packet types (only the ASCII digits are)
357        assert!(PacketId::try_from(4u8).is_err());
358        assert_eq!(
359            Packet::try_from(Bytes::from_static(b"4")).unwrap(),
360            Packet::new(PacketId::Message, Bytes::new())
361        );
362        assert_eq!(Bytes::try_from(Batch(Vec::new())).unwrap(), Bytes::new());
363        let sut = PacketId::try_from(42);
364        assert!(sut.is_err());
365        assert!(matches!(sut.unwrap_err(), Error::InvalidPacketType('*')));
366
367        Ok(())
368    }
369
370    #[test]
371    fn test_handshake_packet() {
372        assert!(
373            HandshakePacket::try_from(Packet::new(PacketId::Message, Bytes::from("test"))).is_err()
374        );
375        let packet = HandshakePacket {
376            ping_interval: 10000,
377            ping_timeout: 1000,
378            sid: "Test".to_owned(),
379            upgrades: vec!["websocket".to_owned(), "test".to_owned()],
380            max_payload: Some(1_000_000),
381        };
382        let encoded: String = serde_json::to_string(&packet).unwrap();
383
384        assert_eq!(
385            packet,
386            HandshakePacket::try_from(Packet::new(PacketId::Message, Bytes::from(encoded)))
387                .unwrap()
388        );
389    }
390}