wa-wire-codec 0.1.0

Zero-copy parser for WhatsApp's binary-node encoding, over pluggable token tables
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//! Parsing a frame into a navigable node tree.
//!
//! A node is `[list tag][size][tag][attr pairs...][content?]`. The size counts
//! every slot after the list header, so an even remainder means attributes
//! only and an odd one means a trailing body.
//!
//! Nothing is copied and nothing is allocated. A [`NodeRef`] holds the slice
//! starting at its own list tag and re-walks it on demand; the encoding is
//! self-delimiting, so a node does not need to know where it ends. Parsing
//! validates the whole tree up front, which is what makes every accessor
//! afterwards infallible.

use crate::error::ParseError;
use crate::jid::{Jid, User};
use crate::packed::{Alphabet, Packed};
use crate::reader::Reader;
use crate::token::{
    self, BINARY_8, BINARY_20, BINARY_32, DICTIONARY_0, DICTIONARY_3, HEX_8, JID_FB, JID_INTEROP,
    JID_PAIR, JID_USER, LIST_8, LIST_16, LIST_EMPTY, NIBBLE_8, TokenTable,
};
use crate::value::Value;

/// How deep a frame may nest before the parser refuses it.
///
/// Real stanzas reach depth 9 at the extreme, so this is generous. It exists to
/// bound recursion on a hostile frame, not to constrain real ones.
pub const DEFAULT_MAX_DEPTH: usize = 64;

/// What a node carries after its attributes.
///
/// Not `Copy`: the child variant holds an iterator, and a silently duplicated
/// iterator is a bug waiting to happen.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Content<'a> {
    /// No body at all.
    None,
    /// A scalar body.
    Value(Value<'a>),
    /// Child nodes.
    Children(Children<'a>),
}

impl<'a> Content<'a> {
    /// Whether the node has no body.
    #[must_use]
    pub const fn is_none(&self) -> bool {
        matches!(self, Self::None)
    }

    /// The scalar body, if there is one.
    #[must_use]
    pub const fn as_value(&self) -> Option<Value<'a>> {
        match self {
            Self::Value(value) => Some(*value),
            _ => None,
        }
    }

    /// The body's bytes, when it is a raw payload — the `<enc>` case.
    #[must_use]
    pub const fn as_bytes(&self) -> Option<&'a [u8]> {
        match self {
            Self::Value(value) => value.as_bytes(),
            _ => None,
        }
    }

    /// The children, if the body is a list.
    #[must_use]
    pub fn as_children(self) -> Option<Children<'a>> {
        match self {
            Self::Children(children) => Some(children),
            _ => None,
        }
    }
}

/// A node, borrowing from the frame it was parsed from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NodeRef<'a> {
    table: TokenTable<'a>,
    /// From this node's list tag to the end of the buffer. The encoding is
    /// self-delimiting, so the tail beyond this node is harmless.
    bytes: &'a [u8],
    tag: Value<'a>,
    attr_count: usize,
    has_content: bool,
    depth_budget: usize,
}

impl<'a> NodeRef<'a> {
    /// The node's tag.
    #[must_use]
    pub const fn tag(&self) -> Value<'a> {
        self.tag
    }

    /// How many attributes the node carries.
    #[must_use]
    pub const fn attr_count(&self) -> usize {
        self.attr_count
    }

    /// Whether the node has a body.
    #[must_use]
    pub const fn has_content(&self) -> bool {
        self.has_content
    }

    /// The attributes, in the order the frame carried them.
    #[must_use]
    pub fn attrs(&self) -> Attrs<'a> {
        let mut reader = Reader::new(self.bytes);
        // The tree was validated at parse time, so re-walking the header
        // cannot fail. A zeroed count on the impossible branch yields an empty
        // iterator rather than a panic.
        let remaining = skip_header(&mut reader, self.table).map_or(0, |()| self.attr_count);
        Attrs {
            table: self.table,
            reader,
            remaining,
        }
    }

    /// The first value for `key`.
    ///
    /// Attribute keys are tokens or short strings, so a linear scan over the
    /// handful a stanza carries beats building an index.
    #[must_use]
    pub fn attr(&self, key: &str) -> Option<Value<'a>> {
        self.attrs()
            .find(|(name, _)| name.eq_str(key))
            .map(|(_, value)| value)
    }

    /// Whether an attribute equals `expected` — the comparison L1 derivation
    /// leans on, done without allocating.
    #[must_use]
    pub fn attr_eq(&self, key: &str, expected: &str) -> bool {
        self.attr(key).is_some_and(|value| value.eq_str(expected))
    }

    /// The node's body.
    #[must_use]
    pub fn content(&self) -> Content<'a> {
        self.content_inner().unwrap_or(Content::None)
    }

    fn content_inner(&self) -> Option<Content<'a>> {
        if !self.has_content {
            return Some(Content::None);
        }
        let mut reader = Reader::new(self.bytes);
        skip_header(&mut reader, self.table).ok()?;
        for _ in 0..self.attr_count {
            skip_value(&mut reader, self.table).ok()?;
            skip_value(&mut reader, self.table).ok()?;
        }
        parse_content(&mut reader, self.table, self.depth_budget).ok()
    }

    /// The child nodes, or an empty iterator when the body is not a list.
    #[must_use]
    pub fn children(&self) -> Children<'a> {
        self.content().as_children().unwrap_or(Children::empty())
    }

    /// The child at `index`.
    #[must_use]
    pub fn child_at(&self, index: usize) -> Option<NodeRef<'a>> {
        self.children().nth(index)
    }

    /// The first child whose tag is `tag`.
    #[must_use]
    pub fn child(&self, tag: &str) -> Option<NodeRef<'a>> {
        self.children().find(|child| child.tag().eq_str(tag))
    }

    /// Follow a path of child indices from this node.
    ///
    /// This is how an envelope's plaintext entries find the node they belong
    /// to: the path in a [`PlaintextEntry`] addresses exactly this walk.
    ///
    /// [`PlaintextEntry`]: https://docs.rs/wa-wire-contract
    #[must_use]
    pub fn at_path<I>(&self, path: I) -> Option<NodeRef<'a>>
    where
        I: IntoIterator<Item = u16>,
    {
        let mut node = *self;
        for component in path {
            node = node.child_at(usize::from(component))?;
        }
        Some(node)
    }
}

/// Iterator over a node's attributes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attrs<'a> {
    table: TokenTable<'a>,
    reader: Reader<'a>,
    remaining: usize,
}

impl<'a> Iterator for Attrs<'a> {
    type Item = (Value<'a>, Value<'a>);

    fn next(&mut self) -> Option<Self::Item> {
        self.remaining = self.remaining.checked_sub(1)?;
        // Validated at parse time; the `ok()` arms are unreachable from a
        // parsed tree and are exercised directly in this module's tests.
        let key = parse_value_next(&mut self.reader, self.table).ok()?;
        let value = parse_value_next(&mut self.reader, self.table).ok()?;
        Some((key, value))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

impl ExactSizeIterator for Attrs<'_> {}

/// Iterator over a node's children.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Children<'a> {
    table: TokenTable<'a>,
    reader: Reader<'a>,
    remaining: usize,
    depth_budget: usize,
}

impl Children<'_> {
    const fn empty() -> Self {
        Self {
            table: TokenTable::empty(),
            reader: Reader::new(&[]),
            remaining: 0,
            depth_budget: 0,
        }
    }

    /// How many children are left.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.remaining
    }

    /// Whether there are no children left.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.remaining == 0
    }
}

impl<'a> Iterator for Children<'a> {
    type Item = NodeRef<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        self.remaining = self.remaining.checked_sub(1)?;
        let node = parse_node(&mut self.reader, self.table, self.depth_budget).ok()?;
        // Skipping past the child leaves the cursor on its sibling.
        skip_node_body(&mut self.reader, self.table, &node).ok()?;
        Some(node)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

impl ExactSizeIterator for Children<'_> {}

/// Parses frames into node trees.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Parser<'a> {
    table: TokenTable<'a>,
    max_depth: usize,
}

impl<'a> Parser<'a> {
    /// A parser over `table`, at the default depth limit.
    #[must_use]
    pub const fn new(table: TokenTable<'a>) -> Self {
        Self {
            table,
            max_depth: DEFAULT_MAX_DEPTH,
        }
    }

    /// Set how deep a frame may nest.
    #[must_use]
    pub const fn with_max_depth(mut self, max_depth: usize) -> Self {
        self.max_depth = max_depth;
        self
    }

    /// The token table in use.
    #[must_use]
    pub const fn table(&self) -> TokenTable<'a> {
        self.table
    }

    /// The depth limit in use.
    #[must_use]
    pub const fn max_depth(&self) -> usize {
        self.max_depth
    }

    /// Parse one node from `frame`, requiring it to consume the whole buffer.
    ///
    /// The whole tree is validated here, so every accessor on the result is
    /// infallible.
    pub fn parse(&self, frame: &'a [u8]) -> Result<NodeRef<'a>, ParseError> {
        let mut reader = Reader::new(frame);
        let node = parse_node(&mut reader, self.table, self.max_depth)?;
        skip_node_body(&mut reader, self.table, &node)?;
        if !reader.is_empty() {
            return Err(ParseError::TrailingBytes(reader.remaining()));
        }
        Ok(node)
    }

    /// Parse the first node in `frame`, allowing bytes to follow.
    ///
    /// Useful when a caller frames several nodes back to back and wants to
    /// handle the remainder itself.
    pub fn parse_prefix(&self, frame: &'a [u8]) -> Result<(NodeRef<'a>, &'a [u8]), ParseError> {
        let mut reader = Reader::new(frame);
        let node = parse_node(&mut reader, self.table, self.max_depth)?;
        skip_node_body(&mut reader, self.table, &node)?;
        Ok((node, reader.tail()))
    }
}

// ---------------------------------------------------------------------------
// Parsing primitives
// ---------------------------------------------------------------------------

/// Read a node's list header and tag, leaving the cursor on its attributes.
fn parse_node<'a>(
    reader: &mut Reader<'a>,
    table: TokenTable<'a>,
    depth_budget: usize,
) -> Result<NodeRef<'a>, ParseError> {
    let depth_budget = depth_budget
        .checked_sub(1)
        .ok_or(ParseError::DepthLimitExceeded {
            limit: DEFAULT_MAX_DEPTH,
        })?;

    let bytes = reader.tail();
    let size = parse_list_size(reader)?;
    let slots = size.checked_sub(1).ok_or(ParseError::EmptyNode)?;

    let tag = parse_value_next(reader, table)?;
    if !tag.is_textual() {
        return Err(ParseError::NonStringTag);
    }

    let attr_count = slots / 2;
    let has_content = slots % 2 == 1;

    Ok(NodeRef {
        table,
        bytes,
        tag,
        attr_count,
        has_content,
        depth_budget,
    })
}

/// Consume a node's attributes and body, leaving the cursor on its sibling.
fn skip_node_body<'a>(
    reader: &mut Reader<'a>,
    table: TokenTable<'a>,
    node: &NodeRef<'a>,
) -> Result<(), ParseError> {
    for _ in 0..node.attr_count {
        let key = parse_value_next(reader, table)?;
        let value = parse_value_next(reader, table)?;
        if !key.is_textual() || !value.is_textual() {
            return Err(ParseError::NonStringAttr);
        }
    }
    if node.has_content {
        match parse_content(reader, table, node.depth_budget)? {
            Content::Children(children) => {
                // Walked here rather than through `Children`'s iterator so a
                // malformed child is reported instead of ending iteration.
                let mut cursor = children.reader;
                for _ in 0..children.remaining {
                    let child = parse_node(&mut cursor, table, children.depth_budget)?;
                    skip_node_body(&mut cursor, table, &child)?;
                }
                *reader = cursor;
            }
            Content::None | Content::Value(_) => {}
        }
    }
    Ok(())
}

/// Re-read a node's list header and tag without producing them.
fn skip_header<'a>(reader: &mut Reader<'a>, table: TokenTable<'a>) -> Result<(), ParseError> {
    parse_list_size(reader)?;
    parse_value_next(reader, table)?;
    Ok(())
}

fn skip_value<'a>(reader: &mut Reader<'a>, table: TokenTable<'a>) -> Result<(), ParseError> {
    parse_value_next(reader, table)?;
    Ok(())
}

fn parse_list_size(reader: &mut Reader<'_>) -> Result<usize, ParseError> {
    let tag = reader.u8()?;
    match tag {
        LIST_8 => Ok(usize::from(reader.u8()?)),
        LIST_16 => Ok(usize::from(reader.u16()?)),
        found => Err(ParseError::ExpectedList { found }),
    }
}

fn parse_content<'a>(
    reader: &mut Reader<'a>,
    table: TokenTable<'a>,
    depth_budget: usize,
) -> Result<Content<'a>, ParseError> {
    let tag = reader.u8()?;
    match tag {
        LIST_EMPTY => Ok(Content::None),
        LIST_8 | LIST_16 => {
            let count = if tag == LIST_8 {
                usize::from(reader.u8()?)
            } else {
                usize::from(reader.u16()?)
            };
            Ok(Content::Children(Children {
                table,
                reader: *reader,
                remaining: count,
                depth_budget,
            }))
        }
        other => Ok(Content::Value(parse_value(reader, table, other)?)),
    }
}

fn parse_value_next<'a>(
    reader: &mut Reader<'a>,
    table: TokenTable<'a>,
) -> Result<Value<'a>, ParseError> {
    let tag = reader.u8()?;
    parse_value(reader, table, tag)
}

fn parse_value<'a>(
    reader: &mut Reader<'a>,
    table: TokenTable<'a>,
    tag: u8,
) -> Result<Value<'a>, ParseError> {
    match tag {
        LIST_EMPTY => Ok(Value::Nil),
        JID_PAIR => Ok(Value::Jid(parse_jid_pair(reader, table)?)),
        JID_USER => Ok(Value::Jid(parse_jid_user(reader, table)?)),
        JID_INTEROP => Ok(Value::Jid(parse_jid_interop(reader, table)?)),
        JID_FB => Ok(Value::Jid(parse_jid_messenger(reader, table)?)),
        BINARY_8 | BINARY_20 | BINARY_32 => Ok(Value::Bytes(parse_binary(reader, tag)?)),
        NIBBLE_8 => Ok(Value::Packed(parse_packed(reader, Alphabet::Nibble)?)),
        HEX_8 => Ok(Value::Packed(parse_packed(reader, Alphabet::Hex)?)),
        _ => Ok(Value::Token(parse_token(reader, table, tag)?)),
    }
}

fn parse_token<'a>(
    reader: &mut Reader<'a>,
    table: TokenTable<'a>,
    tag: u8,
) -> Result<&'a str, ParseError> {
    if (DICTIONARY_0..=DICTIONARY_3).contains(&tag) {
        let dictionary = tag.wrapping_sub(DICTIONARY_0);
        let index = reader.u8()?;
        return table
            .dictionary(dictionary, index)
            .ok_or(ParseError::UnknownToken {
                dictionary: Some(dictionary),
                index: u16::from(index),
            });
    }
    table.single_byte(tag).ok_or(ParseError::UnknownToken {
        dictionary: None,
        index: u16::from(tag),
    })
}

fn parse_binary<'a>(reader: &mut Reader<'a>, tag: u8) -> Result<&'a [u8], ParseError> {
    let length = match tag {
        BINARY_8 => u32::from(reader.u8()?),
        BINARY_20 => reader.u20()?,
        // `parse_value` only routes the three binary tags here.
        _ => reader.u32()?,
    };
    reader.take(length as usize)
}

fn parse_packed<'a>(reader: &mut Reader<'a>, alphabet: Alphabet) -> Result<Packed<'a>, ParseError> {
    let length_byte = reader.u8()?;
    let (count, odd) = Packed::split_length_byte(length_byte)?;
    let bytes = reader.take(count)?;
    Ok(Packed::new(alphabet, bytes, odd))
}

/// A JID's user slot, which may be absent.
fn parse_jid_user_part<'a>(
    reader: &mut Reader<'a>,
    table: TokenTable<'a>,
) -> Result<User<'a>, ParseError> {
    let tag = reader.u8()?;
    match parse_value(reader, table, tag)? {
        Value::Nil => Ok(User::None),
        Value::Token(token) => Ok(User::Token(token)),
        Value::Packed(packed) => Ok(User::Packed(packed)),
        Value::Bytes(bytes) => Ok(User::Bytes(bytes)),
        Value::Jid(_) => Err(ParseError::UnexpectedTag { tag }),
    }
}

/// A JID's server, in any form the wire may carry it.
///
/// Not every server is in a dictionary. `newsletter`, `bot`, `interop` and
/// `hosted.lid` are in none of the five, so each arrives spelled out — and a
/// reader that only resolves tokens refuses a `@newsletter` JID, which is
/// ordinary current traffic. The client reads this position with
/// `decodeString` (`WA/Wap.js`, `ge()`), which takes a token or a string
/// indifferently, and so does every other engine.
fn parse_server<'a>(reader: &mut Reader<'a>, table: TokenTable<'a>) -> Result<&'a str, ParseError> {
    let tag = reader.u8()?;
    match parse_value(reader, table, tag)? {
        Value::Token(token) => Ok(token),
        Value::Bytes(bytes) => core::str::from_utf8(bytes).map_err(|_| ParseError::NonStringAttr),
        // A server is neither digits nor hexadecimal, and a JID cannot be one.
        Value::Packed(_) | Value::Jid(_) | Value::Nil => Err(ParseError::UnexpectedTag { tag }),
    }
}

fn parse_jid_pair<'a>(
    reader: &mut Reader<'a>,
    table: TokenTable<'a>,
) -> Result<Jid<'a>, ParseError> {
    let user = parse_jid_user_part(reader, table)?;
    let server = parse_server(reader, table)?;
    Ok(Jid::pair(user, server))
}

fn parse_jid_user<'a>(
    reader: &mut Reader<'a>,
    table: TokenTable<'a>,
) -> Result<Jid<'a>, ParseError> {
    let domain_type = reader.u8()?;
    let device = u16::from(reader.u8()?);
    let user = parse_jid_user_part(reader, table)?;
    Ok(Jid::with_device(user, server_for(domain_type), device))
}

const fn server_for(domain_type: u8) -> &'static str {
    if domain_type == token::DOMAIN_TYPE_LID {
        token::SERVER_LID
    } else if domain_type == token::DOMAIN_TYPE_HOSTED_LID {
        token::SERVER_HOSTED_LID
    } else if domain_type & token::DOMAIN_TYPE_HOSTED_MASK != 0
        && domain_type & token::DOMAIN_TYPE_LID_MASK == 0
    {
        token::SERVER_HOSTED
    } else {
        token::SERVER_PN
    }
}

fn parse_jid_interop<'a>(
    reader: &mut Reader<'a>,
    table: TokenTable<'a>,
) -> Result<Jid<'a>, ParseError> {
    let user = parse_jid_user_part(reader, table)?;
    let device = reader.u16()?;
    let integrator = reader.u16()?;
    // The trailing server token is on the wire *inbound* and must be consumed.
    //
    // The two directions of this JID genuinely differ, which is easy to get
    // backwards. The client's reader takes user, device, integrator and then a
    // string it discards (`WA/Wap.js`, `be()`); its writer emits user, device,
    // integrator and stops (`ne()`, the `JID_INTEROP` arm). Reading the writer
    // and concluding the token does not exist breaks every inbound interop JID
    // by one attribute. `whatsapp-rust`, `whatsmeow`, `zapo` and Baileys all
    // read it, and `whatsapp-rust`'s own marshal tests say why they must.
    parse_server(reader, table)?;
    Ok(Jid::interop(user, device, integrator))
}

fn parse_jid_messenger<'a>(
    reader: &mut Reader<'a>,
    table: TokenTable<'a>,
) -> Result<Jid<'a>, ParseError> {
    let user = parse_jid_user_part(reader, table)?;
    let device = reader.u16()?;
    parse_server(reader, table)?;
    Ok(Jid::messenger(user, device))
}

#[cfg(test)]
#[path = "node_tests.rs"]
mod tests;