matc/
tlv.rs

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
616
617
618
//! Utilities to decode/encode matter tlv

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use core::fmt;
use std::io::{Cursor, Read, Result, Write};

/// Buffer to encode matter tlv. Create buffer, write elements then use data member which contains encoded tlv.
/// Example how to commission device using certificates pre-created in pem directory:
/// ```
/// # use matc::tlv;
/// # use anyhow::Result;
/// # fn main() -> Result<()> {
/// let mut tlv = tlv::TlvBuffer::new();
/// tlv.write_struct(1)?;
/// tlv.write_uint8(0, 100)?;
/// tlv.write_string(0, "test")?;
/// tlv.write_struct_end()?;
/// // now tlv.data contains encoded tlv buffer
/// # Ok(())
/// # }
/// ```
pub struct TlvBuffer {
    pub data: Vec<u8>,
}

const TYPE_INT_1: u8 = 0;
const TYPE_INT_4: u8 = 2;
const TYPE_UINT_1: u8 = 4;
const TYPE_UINT_2: u8 = 5;
const TYPE_UINT_4: u8 = 6;
const TYPE_UINT_8: u8 = 7;
const TYPE_BOOL_FALSE: u8 = 8;
const TYPE_BOOL_TRUE: u8 = 9;
const TYPE_UTF8_L1: u8 = 0xC;
const TYPE_OCTET_STRING_L1: u8 = 0x10;
const TYPE_OCTET_STRING_L2: u8 = 0x11;

const TYPE_STRUCT: u8 = 0x15;
const TYPE_ARRAY: u8 = 0x16;
const TYPE_LIST: u8 = 0x17;
const TYPE_END_CONTAINER: u8 = 0x18;

const CTRL_CTX_L1: u8 = 1 << 5;

impl TlvBuffer {
    pub fn new() -> Self {
        Self {
            data: Vec::with_capacity(1024),
        }
    }
    pub fn from_vec(v: Vec<u8>) -> Self {
        Self { data: v }
    }
    pub fn write_raw(&mut self, data: &[u8]) -> Result<()> {
        self.data.write_all(data)
    }
    pub fn write_anon_struct(&mut self) -> Result<()> {
        self.data.write_u8(TYPE_STRUCT)?;
        Ok(())
    }
    pub fn write_anon_list(&mut self) -> Result<()> {
        self.data.write_u8(TYPE_LIST)?;
        Ok(())
    }
    pub fn write_struct(&mut self, tag: u8) -> Result<()> {
        self.data.write_u8(CTRL_CTX_L1 | TYPE_STRUCT)?;
        self.data.write_u8(tag)?;
        Ok(())
    }
    pub fn write_array(&mut self, tag: u8) -> Result<()> {
        self.data.write_u8(CTRL_CTX_L1 | TYPE_ARRAY)?;
        self.data.write_u8(tag)?;
        Ok(())
    }
    pub fn write_list(&mut self, tag: u8) -> Result<()> {
        self.data.write_u8(CTRL_CTX_L1 | TYPE_LIST)?;
        self.data.write_u8(tag)?;
        Ok(())
    }
    pub fn write_struct_end(&mut self) -> Result<()> {
        self.data.write_u8(TYPE_END_CONTAINER)?;
        Ok(())
    }
    pub fn write_string(&mut self, tag: u8, data: &str) -> Result<()> {
        let ctrl = CTRL_CTX_L1 | TYPE_UTF8_L1;
        let bytes = data.as_bytes();
        self.data.write_u8(ctrl)?;
        self.data.write_u8(tag)?;
        self.data.write_u8(bytes.len() as u8)?;
        self.data.write_all(bytes)?;
        Ok(())
    }
    pub fn write_octetstring(&mut self, tag: u8, data: &[u8]) -> Result<()> {
        if data.len() > 0xff {
            self.data.write_u8(CTRL_CTX_L1 | TYPE_OCTET_STRING_L2)?;
            self.data.write_u8(tag)?;
            self.data.write_u16::<LittleEndian>(data.len() as u16)?;
        } else {
            self.data.write_u8(CTRL_CTX_L1 | TYPE_OCTET_STRING_L1)?;
            self.data.write_u8(tag)?;
            self.data.write_u8(data.len() as u8)?;
        }
        self.data.write_all(data)?;
        Ok(())
    }
    pub fn write_int8(&mut self, tag: u8, value: i8) -> Result<()> {
        self.data.write_u8(CTRL_CTX_L1 | TYPE_INT_1)?;
        self.data.write_u8(tag)?;
        self.data.write_i8(value)
    }
    pub fn write_uint8(&mut self, tag: u8, value: u8) -> Result<()> {
        self.data.write_u8(CTRL_CTX_L1 | TYPE_UINT_1)?;
        self.data.write_u8(tag)?;
        self.data.write_u8(value)
    }
    pub fn write_uint8_notag(&mut self, value: u8) -> Result<()> {
        self.data.write_u8(TYPE_UINT_1)?;
        self.data.write_u8(value)
    }
    pub fn write_uint16(&mut self, tag: u8, value: u16) -> Result<()> {
        self.data.write_u8(CTRL_CTX_L1 | TYPE_UINT_2)?;
        self.data.write_u8(tag)?;
        self.data.write_u16::<LittleEndian>(value)
    }
    pub fn write_uint32(&mut self, tag: u8, value: u32) -> Result<()> {
        self.data.write_u8(CTRL_CTX_L1 | TYPE_UINT_4)?;
        self.data.write_u8(tag)?;
        self.data.write_u32::<LittleEndian>(value)
    }
    pub fn write_uint64(&mut self, tag: u8, value: u64) -> Result<()> {
        self.data.write_u8(CTRL_CTX_L1 | TYPE_UINT_8)?;
        self.data.write_u8(tag)?;
        self.data.write_u64::<LittleEndian>(value)
    }
    pub fn write_bool(&mut self, tag: u8, value: bool) -> Result<()> {
        if value {
            self.data.write_u8(CTRL_CTX_L1 | TYPE_BOOL_TRUE)?;
        } else {
            self.data.write_u8(CTRL_CTX_L1 | TYPE_BOOL_FALSE)?;
        }
        self.data.write_u8(tag)
    }
}

impl Default for TlvBuffer {
    fn default() -> Self {
        Self::new()
    }
}

/// Enum containing data of decoded tlv element
#[derive(Clone, PartialEq)]
pub enum TlvItemValue {
    Int(u64),
    Bool(bool),
    String(String),
    OctetString(Vec<u8>),
    List(Vec<TlvItem>),
    Nil(),
    Invalid(),
}

/// Decoded tlv element returned by [decode_tlv]
#[derive(Debug, Clone, PartialEq)]
pub struct TlvItem {
    pub tag: u8,
    pub value: TlvItemValue,
}

impl fmt::Debug for TlvItemValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Int(arg0) => f.debug_tuple("Int").field(arg0).finish(),
            Self::Bool(arg0) => f.debug_tuple("Bool").field(arg0).finish(),
            Self::String(arg0) => f.debug_tuple("String").field(arg0).finish(),
            Self::OctetString(arg0) => f.debug_tuple("OctetString").field(&hex::encode(arg0)).finish(),
            Self::List(arg0) => f.debug_tuple("List").field(arg0).finish(),
            Self::Nil() => f.debug_tuple("Nil").finish(),
            Self::Invalid() => f.debug_tuple("Invalid").finish(),
        }
    }
}


impl TlvItem {
    pub fn get(&self, tag: &[u8]) -> Option<&TlvItemValue> {
        if !tag.is_empty() {
            if let TlvItemValue::List(lst) = &self.value {
                for l in lst {
                    if l.tag == tag[0] {
                        return l.get(&tag[1..]);
                    };
                }
            }
            None
        } else {
            Some(&self.value)
        }
    }
    pub fn get_item(&self, tag: &[u8]) -> Option<&TlvItem> {
        if !tag.is_empty() {
            if let TlvItemValue::List(lst) = &self.value {
                for l in lst {
                    if l.tag == tag[0] {
                        return l.get_item(&tag[1..]);
                    };
                }
            }
            None
        } else {
            Some(self)
        }
    }
    pub fn get_int(&self, tag: &[u8]) -> Option<u64> {
        let found = self.get(tag);
        if let Some(TlvItemValue::Int(i)) = found {
            Some(*i)
        } else {
            None
        }
    }
    pub fn get_bool(&self, tag: &[u8]) -> Option<bool> {
        let found = self.get(tag);
        if let Some(TlvItemValue::Bool(i)) = found {
            Some(*i)
        } else {
            None
        }
    }
    pub fn get_u8(&self, tag: &[u8]) -> Option<u8> {
        let found = self.get(tag);
        if let Some(TlvItemValue::Int(i)) = found {
            Some(*i as u8)
        } else {
            None
        }
    }
    pub fn get_u16(&self, tag: &[u8]) -> Option<u16> {
        let found = self.get(tag);
        if let Some(TlvItemValue::Int(i)) = found {
            Some(*i as u16)
        } else {
            None
        }
    }
    pub fn get_u32(&self, tag: &[u8]) -> Option<u32> {
        let found = self.get(tag);
        if let Some(TlvItemValue::Int(i)) = found {
            Some(*i as u32)
        } else {
            None
        }
    }
    pub fn get_u64(&self, tag: &[u8]) -> Option<u64> {
        let found = self.get(tag);
        if let Some(TlvItemValue::Int(i)) = found {
            Some(*i)
        } else {
            None
        }
    }
    pub fn get_octet_string(&self, tag: &[u8]) -> Option<&[u8]> {
        let found = self.get(tag);
        if let Some(TlvItemValue::OctetString(o)) = found {
            Some(o)
        } else {
            None
        }
    }
    pub fn get_octet_string_owned(&self, tag: &[u8]) -> Option<Vec<u8>> {
        let found = self.get(tag);
        if let Some(TlvItemValue::OctetString(o)) = found {
            Some(o.to_owned())
        } else {
            None
        }
    }
    pub fn get_string_owned(&self, tag: &[u8]) -> Option<String> {
        let found = self.get(tag);
        if let Some(TlvItemValue::String(o)) = found {
            Some(o.clone())
        } else {
            None
        }
    }
    pub fn dump(&self, indent: usize) {
        match &self.value {
            TlvItemValue::List(vec) => {
                println!("{} {}", " ".to_owned().repeat(indent), self.tag);
                for v in vec {
                    v.dump(indent + 1);
                }
            }
            _ => {
                println!(
                    "{} {} {:?}",
                    " ".to_owned().repeat(indent),
                    self.tag,
                    self.value
                );
            }
        }
    }
}

fn read_tag(tagctrl: u8, cursor: &mut Cursor<&[u8]>) -> Result<u8> {
    if tagctrl == 1 {
        cursor.read_u8()
    } else {
        Ok(0)
    }
}

fn decode(cursor: &mut Cursor<&[u8]>, container: &mut Vec<TlvItem>) -> Result<()> {
    while cursor.position() < cursor.get_ref().len() as u64 {
        let fb = cursor.read_u8()?;
        let tp = fb & 0x1f;
        let tagctrl = fb >> 5;
        match tp {
            TYPE_INT_1 => {
                let tag = read_tag(tagctrl, cursor)?;
                let value = cursor.read_u8()?;
                let item = TlvItem {
                    tag,
                    value: TlvItemValue::Int(value as u64),
                };
                container.push(item);
            }
            TYPE_INT_4 => {
                let tag = read_tag(tagctrl, cursor)?;
                let value = cursor.read_i32::<LittleEndian>()?;
                let item = TlvItem {
                    tag,
                    value: TlvItemValue::Int(value as u64),
                };
                container.push(item);
            }
            TYPE_UINT_1 => {
                let tag = read_tag(tagctrl, cursor)?;
                let value = cursor.read_u8()?;
                let item = TlvItem {
                    tag,
                    value: TlvItemValue::Int(value as u64),
                };
                container.push(item);
            }
            TYPE_UINT_2 => {
                let tag = read_tag(tagctrl, cursor)?;
                let value = cursor.read_u16::<LittleEndian>()?;
                let item = TlvItem {
                    tag,
                    value: TlvItemValue::Int(value as u64),
                };
                container.push(item);
            }
            TYPE_UINT_4 => {
                let tag = read_tag(tagctrl, cursor)?;
                let value = cursor.read_u32::<LittleEndian>()?;
                let item = TlvItem {
                    tag,
                    value: TlvItemValue::Int(value as u64),
                };
                container.push(item);
            }
            TYPE_BOOL_FALSE => {
                let tag = read_tag(tagctrl, cursor)?;
                let item = TlvItem {
                    tag,
                    value: TlvItemValue::Bool(false),
                };
                container.push(item);
            }
            TYPE_BOOL_TRUE => {
                let tag = read_tag(tagctrl, cursor)?;
                let item = TlvItem {
                    tag,
                    value: TlvItemValue::Bool(true),
                };
                container.push(item);
            }
            TYPE_UTF8_L1 => {
                // utf8 string
                let tag = read_tag(tagctrl, cursor)?;
                let size = cursor.read_u8()?;
                let mut value = vec![0; size as usize];
                cursor.read_exact(&mut value)?;
                let str = String::from_utf8(value);
                let typ = match str {
                    Ok(s) => TlvItemValue::String(s),
                    Err(_) => TlvItemValue::Invalid(),
                };
                let item = TlvItem { tag, value: typ };
                container.push(item);
            }
            TYPE_OCTET_STRING_L1 => {
                // octet string
                let tag = read_tag(tagctrl, cursor)?;
                let size = cursor.read_u8()?;
                let mut value = vec![0; size as usize];
                cursor.read_exact(&mut value)?;
                let item = TlvItem {
                    tag,
                    value: TlvItemValue::OctetString(value),
                };
                container.push(item);
            }
            TYPE_OCTET_STRING_L2 => {
                // octet string large
                let tag = read_tag(tagctrl, cursor)?;
                let size = cursor.read_u16::<LittleEndian>()?;
                let mut value = vec![0; size as usize];
                cursor.read_exact(&mut value)?;
                let item = TlvItem {
                    tag,
                    value: TlvItemValue::OctetString(value),
                };
                container.push(item);
            }
            TYPE_STRUCT => {
                //list
                let tag = read_tag(tagctrl, cursor)?;
                let mut c2 = Vec::new();
                decode(cursor, &mut c2)?;
                let item = TlvItem {
                    tag,
                    value: TlvItemValue::List(c2),
                };
                container.push(item);
            }
            TYPE_ARRAY => {
                //list
                let tag = read_tag(tagctrl, cursor)?;
                let mut c2 = Vec::new();
                decode(cursor, &mut c2)?;
                let item = TlvItem {
                    tag,
                    value: TlvItemValue::List(c2),
                };
                container.push(item);
            }
            TYPE_LIST => {
                //list
                let tag = read_tag(tagctrl, cursor)?;
                let mut c2 = Vec::new();
                decode(cursor, &mut c2)?;
                let item = TlvItem {
                    tag,
                    value: TlvItemValue::List(c2),
                };
                container.push(item);
            }
            TYPE_END_CONTAINER => return Ok(()),
            0x14 => {
                let tag = read_tag(tagctrl, cursor)?;
                let item = TlvItem {
                    tag,
                    value: TlvItemValue::Nil(),
                };
                container.push(item);
            }
            _ => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("unknown tlv type 0x{:x}", tp),
                ))
            }
        }
    }
    Ok(())
}

/// decode raw buffer with tlv data
pub fn decode_tlv(data: &[u8]) -> Result<TlvItem> {
    let mut container = Vec::new();
    let mut cursor = std::io::Cursor::new(data);
    decode(&mut cursor, &mut container)?;
    if container.len() == 1 {
        if let Some(i) = container.pop() {
            Ok(i)
        } else {
            Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "no data found",
            ))
        }
    } else {
        Ok(TlvItem {
            tag: 0,
            value: TlvItemValue::List(container),
        })
    }
}

#[derive(Debug)]
pub enum TlvItemValueEnc {
    Int8(i8),
    UInt8(u8),
    UInt16(u16),
    UInt32(u32),
    UInt64(u64),
    Bool(bool),
    String(String),
    OctetString(Vec<u8>),
    StructAnon(Vec<TlvItemEnc>),
    StructInvisible(Vec<TlvItemEnc>),
    Invalid(),
}

/// Structure used for document style encoding.
///
/// ```
/// # use matc::tlv;
/// let t1 = tlv::TlvItemEnc {
///   tag: 0,
///   value: tlv::TlvItemValueEnc::StructAnon(vec![
///     tlv::TlvItemEnc { tag: 0, value: tlv::TlvItemValueEnc::UInt8(6) },
///     tlv::TlvItemEnc { tag: 1, value: tlv::TlvItemValueEnc::UInt8(7) }
///   ]),
/// };
/// let o = t1.encode().unwrap();
/// ```
#[derive(Debug)]
pub struct TlvItemEnc {
    pub tag: u8,
    pub value: TlvItemValueEnc,
}

impl TlvItemEnc {
    fn encode_internal(&self, buf: &mut TlvBuffer) -> Result<()> {
        match &self.value {
            TlvItemValueEnc::Int8(i) => {
                buf.write_int8(self.tag, *i)?;
            }
            TlvItemValueEnc::UInt8(i) => {
                buf.write_uint8(self.tag, *i)?;
            }
            TlvItemValueEnc::UInt16(i) => {
                buf.write_uint16(self.tag, *i)?;
            }
            TlvItemValueEnc::UInt32(i) => {
                buf.write_uint32(self.tag, *i)?;
            }
            TlvItemValueEnc::UInt64(i) => {
                buf.write_uint64(self.tag, *i)?;
            }
            TlvItemValueEnc::Bool(v) => {
                buf.write_bool(self.tag, *v)?;
            }
            TlvItemValueEnc::String(s) => {
                buf.write_string(self.tag, s)?;
            }
            TlvItemValueEnc::OctetString(vec) => {
                buf.write_octetstring(self.tag, vec)?;
            }
            TlvItemValueEnc::StructAnon(vec) => {
                buf.write_anon_struct()?;
                for i in vec {
                    i.encode_internal(buf)?;
                }
                buf.write_struct_end()?;
            }
            TlvItemValueEnc::StructInvisible(vec) => {
                for i in vec {
                    i.encode_internal(buf)?;
                }
            }
            TlvItemValueEnc::Invalid() => todo!(),
        }
        Ok(())
    }

    pub fn encode(&self) -> Result<Vec<u8>> {
        let mut tlv = TlvBuffer::new();
        self.encode_internal(&mut tlv)?;
        Ok(tlv.data)
    }
}

#[cfg(test)]
mod tests {
    use super::{TlvBuffer, TlvItemEnc, TlvItemValueEnc};

    #[test]
    fn test_1() {
        let t1 = TlvItemEnc {
            tag: 0,
            value: TlvItemValueEnc::StructAnon(vec![
                TlvItemEnc {
                    tag: 0,
                    value: TlvItemValueEnc::UInt8(6),
                },
                TlvItemEnc {
                    tag: 1,
                    value: TlvItemValueEnc::UInt8(7),
                },
            ]),
        };
        let o = t1.encode().unwrap();
        assert_eq!(hex::encode(o), "1524000624010718");

        let mut tlv = TlvBuffer::new();
        tlv.write_anon_struct().unwrap();
        tlv.write_octetstring(0x1, &[1, 2, 3]).unwrap();
        tlv.write_struct_end().unwrap();
        assert_eq!(hex::encode(tlv.data), "1530010301020318");

        let t1 = TlvItemEnc {
            tag: 0,
            value: TlvItemValueEnc::StructAnon(vec![TlvItemEnc {
                tag: 1,
                value: TlvItemValueEnc::OctetString(vec![1, 2, 3]),
            }]),
        }
        .encode()
        .unwrap();
        assert_eq!(hex::encode(t1), "1530010301020318");
    }
}