Skip to main content

wacore_binary/
util.rs

1use crate::error::{BinaryError, Result};
2use crate::zlib_pool::decompress_zlib_pooled;
3use bytes::{Buf, Bytes, BytesMut};
4use std::borrow::Cow;
5
6/// Protocol frames larger than 16 MiB after decompression are rejected.
7pub(crate) const MAX_DECOMPRESSED_SIZE: u64 = 16 * 1024 * 1024;
8
9/// A plaintext frame is a format byte followed by the node bytes the decoder
10/// reads. The byte is a flag set with a single defined bit, [`FORMAT_COMPRESSED`];
11/// `FORMAT_PLAIN` is the uncompressed form and the only one we emit.
12///
13/// `Encoder` writes this byte, [`unpack`] strips it, and the decoder never sees
14/// it. That is the whole reason a decoded buffer is one byte shorter than the
15/// marshal output it came from: [`pack`] is the conversion back.
16pub const FORMAT_PLAIN: u8 = 0;
17
18/// Set in the format byte when the node bytes after it are zlib-compressed.
19/// Only inbound payloads ever set it.
20pub const FORMAT_COMPRESSED: u8 = 2;
21
22/// Check that `data` is a packed payload in the form we produce: a
23/// [`FORMAT_PLAIN`] byte followed by at least one node byte.
24///
25/// The compressed form is a legitimate inbound frame but nothing any `marshal*`
26/// writes, so anything that only ever handles our own output holds a buffer it
27/// did not build if it sees one. A shape check, not a decode: it exists because
28/// passing node bytes where a packed payload is expected fails nowhere locally,
29/// and the peer answers by dropping the connection.
30pub fn check_plain_payload(data: &[u8]) -> Result<()> {
31    match data.split_first() {
32        Some((&format, _)) if format != FORMAT_PLAIN => {
33            Err(BinaryError::UnexpectedFormatByte(format))
34        }
35        Some((_, node_bytes)) if !node_bytes.is_empty() => Ok(()),
36        // No format byte at all, or one with nothing behind it.
37        _ => Err(BinaryError::EmptyData),
38    }
39}
40
41/// Prefix node bytes with the format byte: the inverse of [`unpack`], turning a
42/// buffer the decoder consumed back into one a send path accepts.
43pub fn pack(node_bytes: &[u8]) -> Vec<u8> {
44    let mut packed = Vec::with_capacity(node_bytes.len() + 1);
45    packed.push(FORMAT_PLAIN);
46    packed.extend_from_slice(node_bytes);
47    packed
48}
49
50fn decompress_zlib(compressed: &[u8]) -> Result<Vec<u8>> {
51    decompress_zlib_pooled(compressed, MAX_DECOMPRESSED_SIZE)
52        .map_err(|e| BinaryError::Zlib(e.to_string()))
53}
54
55/// Strip the format byte from a packed payload, decompressing the node bytes
56/// when it says they are.
57pub fn unpack(data: &[u8]) -> Result<Cow<'_, [u8]>> {
58    if data.is_empty() {
59        return Err(BinaryError::EmptyData);
60    }
61    let data_type = data[0];
62    let data = &data[1..];
63
64    if (data_type & FORMAT_COMPRESSED) > 0 {
65        Ok(Cow::Owned(decompress_zlib(data)?))
66    } else {
67        Ok(Cow::Borrowed(data))
68    }
69}
70
71/// Unpack a network payload into an owned `Bytes` buffer.
72///
73/// Uncompressed payloads reuse the existing `BytesMut` allocation
74/// and freeze it without copying. Compressed payloads allocate a
75/// decompression buffer which is then wrapped as `Bytes`.
76pub fn unpack_bytes(mut data: BytesMut) -> Result<Bytes> {
77    if data.is_empty() {
78        return Err(BinaryError::EmptyData);
79    }
80    let data_type = data[0];
81
82    if (data_type & FORMAT_COMPRESSED) > 0 {
83        Ok(Bytes::from(decompress_zlib(&data[1..])?))
84    } else {
85        data.advance(1);
86        Ok(data.freeze())
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93    use crate::marshal::{marshal, unmarshal_packed_ref, unmarshal_ref};
94    use crate::node::{Attrs, Node, NodeContent, NodeValue, OwnedNodeRef};
95
96    /// One shape per thing the encoder does differently: a child list, a binary
97    /// body, and attributes that take the packed hex/nibble tokens.
98    fn shapes() -> Vec<(&'static str, Node)> {
99        let mut attrs = Attrs::with_capacity(3);
100        attrs.push("id".to_string(), "ABC123");
101        attrs.push("hex".to_string(), NodeValue::from("DEADBEEF"));
102        attrs.push("nibble".to_string(), NodeValue::from("12-345.6"));
103
104        vec![
105            (
106                "children",
107                Node::new(
108                    "iq",
109                    attrs.clone(),
110                    Some(NodeContent::Nodes(vec![
111                        Node::new("ping", Attrs::new(), None),
112                        Node::new(
113                            "text",
114                            Attrs::new(),
115                            Some(NodeContent::String("hello".into())),
116                        ),
117                    ])),
118                ),
119            ),
120            (
121                "binary body",
122                Node::new(
123                    "message",
124                    Attrs::new(),
125                    Some(NodeContent::Bytes(vec![0xAB; 512])),
126                ),
127            ),
128            ("packed attrs", Node::new("receipt", attrs, None)),
129        ]
130    }
131
132    /// The round trip a forwarding consumer performs: marshal, take it apart the
133    /// way the receive path does, then hand what the decoder holds back to a send
134    /// path. The bytes that reach the send point must be the ones marshal wrote.
135    #[test]
136    fn a_decoded_stanza_packs_back_to_the_bytes_it_arrived_as() {
137        for (shape, node) in shapes() {
138            let packed = marshal(&node).expect("marshal");
139            let node_bytes = unpack(&packed).expect("unpack").into_owned();
140            let owned = OwnedNodeRef::new(node_bytes).expect("decode");
141
142            let forwarded = pack(&owned.backing_bytes());
143            assert_eq!(
144                forwarded, packed,
145                "{shape}: pack(backing_bytes) must reproduce the marshal output"
146            );
147            assert_eq!(
148                unmarshal_packed_ref(&forwarded)
149                    .expect("the forwarded payload decodes")
150                    .to_owned(),
151                owned.to_owned_node(),
152                "{shape}: the forwarded stanza is still the same node"
153            );
154        }
155    }
156
157    /// `unpack_bytes` is what the read loop actually calls, so it has to agree
158    /// with `unpack` byte for byte or only one of the two round-trips.
159    #[test]
160    fn unpack_bytes_strips_the_same_byte_as_unpack() {
161        for (shape, node) in shapes() {
162            let packed = marshal(&node).expect("marshal");
163            let owned = unpack_bytes(BytesMut::from(&packed[..])).expect("unpack_bytes");
164
165            assert_eq!(
166                owned.as_ref(),
167                unpack(&packed).expect("unpack").as_ref(),
168                "{shape}"
169            );
170            assert_eq!(pack(&owned), packed, "{shape}");
171        }
172    }
173
174    /// Nails down the byte itself: the encoder writes an uncompressed format
175    /// byte, and the decoder neither consumes nor requires it. Change either and
176    /// every packed payload we send or forward is off by one.
177    #[test]
178    fn the_format_byte_is_uncompressed_and_the_decoder_never_reads_it() {
179        let node = Node::new("iq", Attrs::new(), None);
180        let packed = marshal(&node).expect("marshal");
181
182        assert_eq!(packed[0], FORMAT_PLAIN);
183        assert_eq!(FORMAT_PLAIN, 0);
184        assert_eq!(FORMAT_COMPRESSED, 2);
185
186        // Not required: node bytes alone decode.
187        assert!(unmarshal_ref(&packed[1..]).is_ok());
188        // Not consumed: the same bytes with it still attached do not.
189        assert!(unmarshal_ref(&packed).is_err());
190    }
191
192    /// The failure the asymmetry causes, made local: node bytes offered where a
193    /// packed payload belongs are refused, and the error names the byte.
194    #[test]
195    fn node_bytes_are_refused_where_a_packed_payload_belongs() {
196        let node = Node::new(
197            "iq",
198            Attrs::new(),
199            Some(NodeContent::Nodes(vec![Node::new(
200                "ping",
201                Attrs::new(),
202                None,
203            )])),
204        );
205        let packed = marshal(&node).expect("marshal");
206        let node_bytes = unpack(&packed).expect("unpack").into_owned();
207
208        assert!(check_plain_payload(&packed).is_ok());
209        assert!(matches!(
210            check_plain_payload(&node_bytes),
211            Err(BinaryError::UnexpectedFormatByte(byte)) if byte == node_bytes[0]
212        ));
213        // No format byte, and a format byte with no stanza behind it: both are
214        // shaped like a packed payload only if the length is not checked.
215        assert!(matches!(
216            check_plain_payload(&[]),
217            Err(BinaryError::EmptyData)
218        ));
219        assert!(matches!(
220            check_plain_payload(&[FORMAT_PLAIN]),
221            Err(BinaryError::EmptyData)
222        ));
223        // Compressed is a legitimate inbound frame, so it is refused by byte
224        // rather than by shape: nothing we produce is compressed.
225        let mut compressed = packed.clone();
226        compressed[0] = FORMAT_COMPRESSED;
227        assert!(matches!(
228            check_plain_payload(&compressed),
229            Err(BinaryError::UnexpectedFormatByte(FORMAT_COMPRESSED))
230        ));
231
232        assert!(unmarshal_packed_ref(&packed).is_ok());
233        assert!(matches!(
234            unmarshal_packed_ref(&node_bytes),
235            Err(BinaryError::UnexpectedFormatByte(byte)) if byte == node_bytes[0]
236        ));
237        assert!(matches!(
238            unmarshal_packed_ref(&[]),
239            Err(BinaryError::EmptyData)
240        ));
241    }
242}