Skip to main content

socketio_next/protocol/
socketio.rs

1//! The socket.io packet codec (socket.io-parser 4.2 rules), without I/O.
2//!
3//! `data` always holds the JSON payload exactly as it goes over the wire. For BINARY_EVENT and
4//! BINARY_ACK that JSON contains `{"_placeholder":true,"num":n}` objects that refer to
5//! `attachments[n]` (socket.io-parser `deconstructPacket` / `reconstructPacket`).
6
7use crate::protocol::Payload;
8use crate::protocol::error::{Error, Result};
9use bytes::Bytes;
10use serde_json::{Value, json};
11
12use std::convert::TryFrom;
13use std::fmt::Write;
14use std::str::from_utf8 as str_from_utf8;
15
16/// socket.io-parser `Decoder` default `maxAttachments`.
17pub const MAX_ATTACHMENTS: u8 = 10;
18
19/// An enumeration of the different `Packet` types in the `socket.io` protocol.
20#[derive(Debug, Copy, Clone, Eq, PartialEq)]
21pub enum PacketId {
22    Connect = 0,
23    Disconnect = 1,
24    Event = 2,
25    Ack = 3,
26    ConnectError = 4,
27    BinaryEvent = 5,
28    BinaryAck = 6,
29}
30
31/// A packet which gets sent or received during in the `socket.io` protocol.
32#[derive(Debug, PartialEq, Eq, Clone)]
33pub struct Packet {
34    pub packet_type: PacketId,
35    pub nsp: String,
36    /// The JSON payload as text, placeholders included.
37    pub data: Option<String>,
38    pub id: Option<u64>,
39    pub attachment_count: u8,
40    pub attachments: Option<Vec<Bytes>>,
41}
42
43/// The placeholder for `attachments[num]`.
44pub fn placeholder(num: usize) -> Value {
45    json!({ "_placeholder": true, "num": num })
46}
47
48fn is_placeholder(value: &Value) -> bool {
49    value.get("_placeholder") == Some(&Value::Bool(true))
50}
51
52/// Every placeholder refers to an attachment that exists (socket.io-parser throws
53/// "illegal attachments" otherwise).
54fn placeholders_valid(value: &Value, attachments: usize) -> bool {
55    if is_placeholder(value) {
56        return value
57            .get("num")
58            .and_then(Value::as_u64)
59            .is_some_and(|num| (num as usize) < attachments);
60    }
61    match value {
62        Value::Array(items) => items.iter().all(|v| placeholders_valid(v, attachments)),
63        Value::Object(map) => map.values().all(|v| placeholders_valid(v, attachments)),
64        _ => true,
65    }
66}
67
68/// Splits a payload into its JSON arguments and binary attachments.
69fn deconstruct(payload: Payload) -> Result<(Vec<Value>, Vec<Bytes>)> {
70    match payload {
71        Payload::Text(args) => Ok((args, Vec::new())),
72        Payload::Binary(bytes) => Ok((vec![placeholder(0)], vec![bytes])),
73        Payload::Mixed { args, attachments } => {
74            if attachments.len() > usize::from(MAX_ATTACHMENTS) {
75                return Err(Error::InvalidPacket("more than 10 attachments"));
76            }
77            if !args
78                .iter()
79                .all(|v| placeholders_valid(v, attachments.len()))
80            {
81                return Err(Error::InvalidPacket("placeholder without an attachment"));
82            }
83            Ok((args, attachments))
84        }
85    }
86}
87
88/// The payload for received arguments: a lone buffer stays [`Payload::Binary`] (0.6 behaviour),
89/// anything else with attachments is [`Payload::Mixed`].
90fn reconstruct(args: Vec<Value>, mut attachments: Vec<Bytes>) -> Result<Payload> {
91    if attachments.is_empty() {
92        return Ok(Payload::Text(args));
93    }
94    if !args
95        .iter()
96        .all(|v| placeholders_valid(v, attachments.len()))
97    {
98        return Err(Error::InvalidPacket("placeholder without an attachment"));
99    }
100    if attachments.len() == 1 && args.len() == 1 && is_placeholder(&args[0]) {
101        return Ok(Payload::Binary(attachments.remove(0)));
102    }
103    Ok(Payload::Mixed { args, attachments })
104}
105
106impl Packet {
107    /// An EVENT (or BINARY_EVENT when the payload carries buffers) for `event`.
108    pub fn new_event(payload: Payload, event: &str, nsp: &str, id: Option<u64>) -> Result<Packet> {
109        let (args, attachments) = deconstruct(payload)?;
110        let mut data = Vec::with_capacity(args.len() + 1);
111        data.push(Value::String(event.to_owned()));
112        data.extend(args);
113        Ok(Self::with_attachments(
114            (PacketId::Event, PacketId::BinaryEvent),
115            nsp,
116            Value::Array(data),
117            id,
118            attachments,
119        ))
120    }
121
122    /// The ACK (or BINARY_ACK) that answers the server's event `id`.
123    pub fn new_ack(payload: Payload, nsp: &str, id: u64) -> Result<Packet> {
124        let (args, attachments) = deconstruct(payload)?;
125        Ok(Self::with_attachments(
126            (PacketId::Ack, PacketId::BinaryAck),
127            nsp,
128            Value::Array(args),
129            Some(id),
130            attachments,
131        ))
132    }
133
134    fn with_attachments(
135        (text, binary): (PacketId, PacketId),
136        nsp: &str,
137        data: Value,
138        id: Option<u64>,
139        attachments: Vec<Bytes>,
140    ) -> Packet {
141        let (packet_type, count, attachments) = if attachments.is_empty() {
142            (text, 0, None)
143        } else {
144            // deconstruct() bounds the count by MAX_ATTACHMENTS
145            (binary, attachments.len() as u8, Some(attachments))
146        };
147        Packet::new(
148            packet_type,
149            nsp.to_owned(),
150            Some(data.to_string()),
151            id,
152            count,
153            attachments,
154        )
155    }
156
157    /// The JSON arguments of an EVENT/ACK (empty when there is no payload).
158    fn args(&self) -> Result<Vec<Value>> {
159        match self.data.as_deref() {
160            None => Ok(Vec::new()),
161            Some(data) => match serde_json::from_str::<Value>(data)? {
162                Value::Array(args) => Ok(args),
163                _ => Err(Error::InvalidPacket("EVENT/ACK payload is not an array")),
164            },
165        }
166    }
167
168    fn attachment_list(&self) -> Vec<Bytes> {
169        self.attachments.clone().unwrap_or_default()
170    }
171
172    /// Event name and arguments of an EVENT / BINARY_EVENT.
173    ///
174    /// The first argument is the name when it is a string (or a number, which socket.io-parser
175    /// also accepts). Deliberate difference from socket.io-client, kept from rust_socketio: a
176    /// binary event without a name (`emit(buffer)` on the server) is named `"message"`.
177    pub fn event_payload(&self) -> Result<(String, Payload)> {
178        let mut args = self.args()?;
179        let event = match args.first() {
180            Some(Value::String(name)) => Some(name.clone()),
181            Some(Value::Number(n)) => Some(n.to_string()),
182            _ => None,
183        };
184        let event = match event {
185            Some(event) => {
186                args.remove(0);
187                event
188            }
189            None => "message".to_owned(),
190        };
191        Ok((event, reconstruct(args, self.attachment_list())?))
192    }
193
194    /// The arguments of an ACK / BINARY_ACK.
195    pub fn ack_payload(&self) -> Result<Payload> {
196        reconstruct(self.args()?, self.attachment_list())
197    }
198
199    /// Event name of an EVENT / BINARY_EVENT (see [`Packet::event_payload`]).
200    #[cfg(test)]
201    pub(crate) fn binary_event_name(&self) -> String {
202        self.event_payload()
203            .map(|(event, _)| event)
204            .unwrap_or_else(|_| "message".to_owned())
205    }
206}
207
208impl Default for Packet {
209    fn default() -> Self {
210        Self {
211            packet_type: PacketId::Event,
212            nsp: String::from("/"),
213            data: None,
214            id: None,
215            attachment_count: 0,
216            attachments: None,
217        }
218    }
219}
220
221impl TryFrom<u8> for PacketId {
222    type Error = Error;
223    fn try_from(b: u8) -> Result<Self> {
224        PacketId::try_from(b as char)
225    }
226}
227
228impl TryFrom<char> for PacketId {
229    type Error = Error;
230    fn try_from(b: char) -> Result<Self> {
231        match b {
232            '0' => Ok(PacketId::Connect),
233            '1' => Ok(PacketId::Disconnect),
234            '2' => Ok(PacketId::Event),
235            '3' => Ok(PacketId::Ack),
236            '4' => Ok(PacketId::ConnectError),
237            '5' => Ok(PacketId::BinaryEvent),
238            '6' => Ok(PacketId::BinaryAck),
239            _ => Err(Error::InvalidPacketType(b)),
240        }
241    }
242}
243
244impl Packet {
245    /// Creates an instance.
246    pub const fn new(
247        packet_type: PacketId,
248        nsp: String,
249        data: Option<String>,
250        id: Option<u64>,
251        attachment_count: u8,
252        attachments: Option<Vec<Bytes>>,
253    ) -> Self {
254        Packet {
255            packet_type,
256            nsp,
257            data,
258            id,
259            attachment_count,
260            attachments,
261        }
262    }
263}
264
265impl From<Packet> for Bytes {
266    fn from(packet: Packet) -> Self {
267        Bytes::from(&packet)
268    }
269}
270
271impl From<&Packet> for Bytes {
272    /// socket.io-parser `encodeAsString`: type, `<attachments>-`, `<nsp>,` (unless `/`), id,
273    /// JSON. The attachments themselves are sent by the socket as separate binary messages.
274    fn from(packet: &Packet) -> Bytes {
275        let mut buffer = String::new();
276        buffer.push((packet.packet_type as u8 + b'0') as char);
277
278        if let PacketId::BinaryAck | PacketId::BinaryEvent = packet.packet_type {
279            let _ = write!(buffer, "{}-", packet.attachment_count);
280        }
281
282        if packet.nsp != "/" {
283            buffer.push_str(&packet.nsp);
284            buffer.push(',');
285        }
286
287        if let Some(id) = packet.id {
288            let _ = write!(buffer, "{id}");
289        }
290
291        if let Some(data) = packet.data.as_ref() {
292            buffer.push_str(data);
293        }
294
295        Bytes::from(buffer)
296    }
297}
298
299impl TryFrom<Bytes> for Packet {
300    type Error = Error;
301    fn try_from(value: Bytes) -> Result<Self> {
302        Packet::try_from(&value)
303    }
304}
305
306impl TryFrom<&Bytes> for Packet {
307    type Error = Error;
308    /// socket.io-parser `decodeString`. The attachments of a binary packet arrive as separate
309    /// engine.io messages; the socket fills `attachments` in.
310    fn try_from(payload: &Bytes) -> Result<Packet> {
311        let mut payload = str_from_utf8(payload).map_err(Error::InvalidUtf8)?;
312        let mut packet = Packet::default();
313
314        // packet_type
315        let id_char = payload.chars().next().ok_or(Error::IncompletePacket)?;
316        packet.packet_type = PacketId::try_from(id_char)?;
317        payload = &payload[id_char.len_utf8()..];
318
319        // attachment_count: a positive integer up to MAX_ATTACHMENTS, then '-'
320        if let PacketId::BinaryAck | PacketId::BinaryEvent = packet.packet_type {
321            let (prefix, rest) = payload.split_once('-').ok_or(Error::IncompletePacket)?;
322            payload = rest;
323            if prefix.is_empty() || !prefix.bytes().all(|b| b.is_ascii_digit()) {
324                return Err(Error::InvalidPacket("attachment count is not a number"));
325            }
326            let count: u32 = prefix
327                .parse()
328                .map_err(|_| Error::InvalidPacket("attachment count is not a number"))?;
329            if count == 0 || count > u32::from(MAX_ATTACHMENTS) {
330                return Err(Error::InvalidPacket("attachment count must be 1..=10"));
331            }
332            packet.attachment_count = count as u8;
333        }
334
335        // namespace: up to ',' or the end
336        if payload.starts_with('/') {
337            let (nsp, rest) = payload.split_once(',').unwrap_or((payload, ""));
338            packet.nsp = nsp.to_owned();
339            payload = rest;
340        }
341
342        // id
343        let digits = payload.bytes().take_while(u8::is_ascii_digit).count();
344        if digits > 0 {
345            let (id, rest) = payload.split_at(digits);
346            packet.id = Some(
347                id.parse()
348                    .map_err(|_| Error::InvalidPacket("ack id out of range"))?,
349            );
350            payload = rest;
351        }
352
353        if payload.is_empty() {
354            return Ok(packet);
355        }
356
357        // validate json, then the payload shape for the packet type (socket.io-parser's
358        // isPayloadValid): a server event must not pose as a reserved client event like `connect`
359        let json = serde_json::from_str::<Value>(payload).map_err(Error::from)?;
360        if !is_payload_valid(packet.packet_type, &json) {
361            return Err(Error::InvalidPacket(
362                "payload shape not allowed for this packet type",
363            ));
364        }
365        packet.data = Some(payload.to_owned());
366
367        Ok(packet)
368    }
369}
370
371/// Event names the socket.io client and server reserve (socket.io-parser `RESERVED_EVENTS`).
372pub const RESERVED_EVENTS: [&str; 6] = [
373    "connect",
374    "connect_error",
375    "disconnect",
376    "disconnecting",
377    "newListener",
378    "removeListener",
379];
380
381/// Whether socket.io reserves `name` (it cannot be emitted or received as an event).
382pub fn is_reserved_event(name: &str) -> bool {
383    RESERVED_EVENTS.contains(&name)
384}
385
386fn is_payload_valid(packet_type: PacketId, payload: &Value) -> bool {
387    match packet_type {
388        PacketId::Connect => payload.is_object(),
389        PacketId::Disconnect => false,
390        PacketId::ConnectError => payload.is_string() || payload.is_object(),
391        PacketId::Event | PacketId::BinaryEvent => match payload.as_array().and_then(|a| a.first())
392        {
393            Some(Value::Number(_)) => true,
394            Some(Value::String(name)) => !RESERVED_EVENTS.contains(&name.as_str()),
395            // Deliberate difference from socket.io-client: a binary event without a name
396            // (`emit(buffer)` on the server) is delivered as `message`, as in 0.6.0.
397            Some(first) => packet_type == PacketId::BinaryEvent && is_placeholder(first),
398            None => false,
399        },
400        PacketId::Ack | PacketId::BinaryAck => payload.is_array(),
401    }
402}
403
404#[cfg(test)]
405mod test {
406    use super::*;
407
408    fn decode(raw: &str) -> Result<Packet> {
409        Packet::try_from(&Bytes::from(raw.to_owned()))
410    }
411
412    fn encode(packet: &Packet) -> String {
413        String::from_utf8(Bytes::from(packet).to_vec()).unwrap()
414    }
415
416    #[test]
417    fn protocol_examples_roundtrip() {
418        // https://github.com/socketio/socket.io-protocol examples
419        let cases = [
420            (
421                "0{\"token\":\"123\"}",
422                PacketId::Connect,
423                "/",
424                Some("{\"token\":\"123\"}"),
425                None,
426            ),
427            (
428                "0/admin™,{\"token™\":\"123\"}",
429                PacketId::Connect,
430                "/admin™",
431                Some("{\"token™\":\"123\"}"),
432                None,
433            ),
434            ("1/admin,", PacketId::Disconnect, "/admin", None, None),
435            (
436                "2[\"hello\",1]",
437                PacketId::Event,
438                "/",
439                Some("[\"hello\",1]"),
440                None,
441            ),
442            (
443                "2/admin,456[\"project:delete\",123]",
444                PacketId::Event,
445                "/admin",
446                Some("[\"project:delete\",123]"),
447                Some(456),
448            ),
449            (
450                "3/admin,456[]",
451                PacketId::Ack,
452                "/admin",
453                Some("[]"),
454                Some(456),
455            ),
456            (
457                "4/admin,{\"message\":\"Not authorized\"}",
458                PacketId::ConnectError,
459                "/admin",
460                Some("{\"message\":\"Not authorized\"}"),
461                None,
462            ),
463        ];
464        for (raw, packet_type, nsp, data, id) in cases {
465            let packet = decode(raw).unwrap();
466            assert_eq!(
467                packet,
468                Packet::new(
469                    packet_type,
470                    nsp.to_owned(),
471                    data.map(str::to_owned),
472                    id,
473                    0,
474                    None
475                ),
476                "{raw}"
477            );
478            assert_eq!(encode(&packet), raw);
479        }
480    }
481
482    #[test]
483    fn namespace_without_comma_runs_to_the_end() {
484        // socket.io-parser reads the namespace up to ',' or the end of the string
485        let packet = decode("1/admin").unwrap();
486        assert_eq!(packet.packet_type, PacketId::Disconnect);
487        assert_eq!(packet.nsp, "/admin");
488    }
489
490    #[test]
491    fn binary_packets_keep_placeholders() {
492        let raw = "51-[\"hello\",{\"_placeholder\":true,\"num\":0}]";
493        let mut packet = decode(raw).unwrap();
494        assert_eq!(packet.packet_type, PacketId::BinaryEvent);
495        assert_eq!(packet.attachment_count, 1);
496        assert_eq!(
497            packet.data.as_deref(),
498            Some("[\"hello\",{\"_placeholder\":true,\"num\":0}]")
499        );
500        packet.attachments = Some(vec![Bytes::from_static(&[1, 2, 3])]);
501        assert_eq!(encode(&packet), raw);
502        let (event, payload) = packet.event_payload().unwrap();
503        assert_eq!(event, "hello".to_owned());
504        assert_eq!(payload, Payload::Binary(Bytes::from_static(&[1, 2, 3])));
505
506        let raw = "61-/admin,456[{\"_placeholder\":true,\"num\":0}]";
507        let packet = decode(raw).unwrap();
508        assert_eq!(packet.packet_type, PacketId::BinaryAck);
509        assert_eq!((packet.nsp.as_str(), packet.id), ("/admin", Some(456)));
510        assert_eq!(encode(&packet), raw);
511    }
512
513    #[test]
514    fn nested_and_multiple_attachments() {
515        // socket.io-parser "encodes a deep binary" / "encodes mixed binary and json"
516        let raw = r#"52-["ev",{"a":[{"_placeholder":true,"num":0}],"b":"x"},{"_placeholder":true,"num":1},3]"#;
517        let mut packet = decode(raw).unwrap();
518        assert_eq!(packet.attachment_count, 2);
519        let a = Bytes::from_static(b"one");
520        let b = Bytes::from_static(b"two");
521        packet.attachments = Some(vec![a.clone(), b.clone()]);
522        let (event, payload) = packet.event_payload().unwrap();
523        assert_eq!(event, "ev".to_owned());
524        let expected = Payload::Mixed {
525            args: vec![
526                json!({"a": [placeholder(0)], "b": "x"}),
527                placeholder(1),
528                json!(3),
529            ],
530            attachments: vec![a, b],
531        };
532        assert_eq!(payload, expected);
533        // and back
534        let encoded = Packet::new_event(expected, "ev", "/", None).unwrap();
535        assert_eq!(encode(&encoded), raw);
536        assert_eq!(encoded.attachment_count, 2);
537    }
538
539    #[test]
540    fn placeholder_out_of_range_is_rejected() {
541        let mut packet = decode(r#"51-["ev",{"_placeholder":true,"num":1}]"#).unwrap();
542        packet.attachments = Some(vec![Bytes::from_static(b"x")]);
543        assert!(packet.event_payload().is_err());
544        let bad = Payload::Mixed {
545            args: vec![placeholder(2)],
546            attachments: vec![Bytes::new()],
547        };
548        assert!(Packet::new_event(bad, "ev", "/", None).is_err());
549    }
550
551    #[test]
552    fn attachment_count_rules() {
553        // socket.io-parser: integer >= 1, at most maxAttachments (10), followed by '-'
554        for raw in [
555            "5",
556            "51",
557            "50-",
558            "5a-",
559            "51.23-",
560            "511-[\"a\"]",
561            "5+1-[\"a\"]",
562        ] {
563            assert!(decode(raw).is_err(), "{raw}");
564        }
565        assert!(decode(r#"510-["a"]"#).is_ok());
566        let too_many = Payload::Mixed {
567            args: vec![],
568            attachments: vec![Bytes::new(); 11],
569        };
570        assert!(Packet::new_event(too_many, "ev", "/", None).is_err());
571    }
572
573    #[test]
574    fn event_names() {
575        let name = |raw: &str| decode(raw).unwrap().event_payload().unwrap();
576        // a lone name is the event, with no arguments (socket.io-client)
577        assert_eq!(
578            name(r#"2["ERROR_VERSION"]"#),
579            ("ERROR_VERSION".to_owned(), Payload::Text(vec![]))
580        );
581        // a numeric name is accepted by socket.io-parser
582        assert_eq!(
583            name("2[42,\"x\"]"),
584            ("42".to_owned(), Payload::Text(vec![json!("x")]))
585        );
586        // the binary event without a name (0.6 compatibility) is `message`
587        let mut packet = decode(r#"51-[{"_placeholder":true,"num":0}]"#).unwrap();
588        packet.attachments = Some(vec![Bytes::from_static(b"b")]);
589        assert_eq!(
590            packet.event_payload().unwrap(),
591            (
592                "message".to_owned(),
593                Payload::Binary(Bytes::from_static(b"b"))
594            )
595        );
596        // extra arguments around the buffer
597        let mut packet =
598            decode(r#"51-["tts:audio","extra",{"_placeholder":true,"num":0}]"#).unwrap();
599        packet.attachments = Some(vec![Bytes::from_static(b"b")]);
600        assert_eq!(packet.binary_event_name(), "tts:audio".to_owned());
601    }
602
603    #[test]
604    fn ack_arguments_are_the_array_items() {
605        let packet = decode("3/admin,1[\"woot\",2]").unwrap();
606        assert_eq!(
607            packet.ack_payload().unwrap(),
608            Payload::Text(vec![json!("woot"), json!(2)])
609        );
610    }
611
612    #[test]
613    fn encode_from_payloads() {
614        let ev = || "ev";
615        let p = Packet::new_event(
616            Payload::Binary(Bytes::from_static(&[0, 4, 9])),
617            ev(),
618            "/admin",
619            None,
620        )
621        .unwrap();
622        assert_eq!(
623            encode(&p),
624            r#"51-/admin,["ev",{"_placeholder":true,"num":0}]"#
625        );
626        assert_eq!(p.attachments, Some(vec![Bytes::from_static(&[0, 4, 9])]));
627        // with an ack id it is still BINARY_EVENT, never BINARY_ACK (#422)
628        let p = Packet::new_event(
629            Payload::Binary(Bytes::from_static(b"x")),
630            "upload",
631            "/",
632            Some(3),
633        )
634        .unwrap();
635        assert_eq!(
636            encode(&p),
637            r#"51-3["upload",{"_placeholder":true,"num":0}]"#
638        );
639        let p = Packet::new_event(
640            Payload::Text(vec![json!({"a":1}), json!("b")]),
641            ev(),
642            "/",
643            Some(7),
644        )
645        .unwrap();
646        assert_eq!(encode(&p), r#"27["ev",{"a":1},"b"]"#);
647        let p = Packet::new_event(Payload::from("plain"), ev(), "/", None).unwrap();
648        assert_eq!(encode(&p), r#"2["ev","plain"]"#);
649        let p = Packet::new_event(Payload::empty(), ev(), "/", None).unwrap();
650        assert_eq!(encode(&p), r#"2["ev"]"#);
651        // acks
652        let p = Packet::new_ack(Payload::Text(vec![json!("ok")]), "/", 5).unwrap();
653        assert_eq!(encode(&p), r#"35["ok"]"#);
654        let p = Packet::new_ack(Payload::Binary(Bytes::from_static(b"x")), "/n", 5).unwrap();
655        assert_eq!(encode(&p), r#"61-/n,5[{"_placeholder":true,"num":0}]"#);
656    }
657
658    #[test]
659    fn illegal_packet_id() {
660        assert!(matches!(decode("7"), Err(Error::InvalidPacketType('7'))));
661        assert!(decode("").is_err());
662    }
663}