use std::collections::HashMap;
use thiserror::Error;
use crate::core::int2bytes;
const MAX_TLV_DEPTH: usize = 32;
const MAX_TAG_BYTES: usize = 4;
#[derive(Debug, Error)]
pub enum TlvError {
#[error("Invalid encoding of tag/length")]
InvalidEncoding,
#[error("Incorrect TLV length")]
IncorrectLength,
#[error("Wrong tag, got 0x{got:02x} expected 0x{expected:02x}")]
WrongTag {
got: u32,
expected: u32,
},
}
pub fn tlv_parse(data: &[u8], offset: usize) -> Result<(u32, usize, usize, usize), TlvError> {
tlv_parse_inner(data, offset, 0)
}
fn tlv_parse_inner(
data: &[u8],
mut offset: usize,
depth: usize,
) -> Result<(u32, usize, usize, usize), TlvError> {
fn checked_add(a: usize, b: usize) -> Result<usize, TlvError> {
a.checked_add(b).ok_or(TlvError::InvalidEncoding)
}
let get = |i: usize| -> Result<u8, TlvError> {
data.get(i).copied().ok_or(TlvError::InvalidEncoding)
};
let mut tag = get(offset)? as u32;
offset += 1;
if tag & 0x1F == 0x1F {
let mut tag_bytes = 1;
loop {
if tag_bytes >= MAX_TAG_BYTES {
return Err(TlvError::InvalidEncoding);
}
let next = get(offset)?;
tag = (tag << 8) | next as u32;
tag_bytes += 1;
offset += 1;
if next & 0x80 == 0 {
break;
}
}
}
let ln_byte = get(offset)? as usize;
offset += 1;
let (ln, end) = if ln_byte == 0x80 {
if depth >= MAX_TLV_DEPTH {
return Err(TlvError::InvalidEncoding);
}
let mut end = offset;
while get(end)? != 0 || get(checked_add(end, 1)?)? != 0 {
let (_, _, _, next_end) = tlv_parse_inner(data, end, depth + 1)?;
if next_end <= end {
return Err(TlvError::InvalidEncoding);
}
end = next_end;
}
let ln = end.checked_sub(offset).ok_or(TlvError::InvalidEncoding)?;
(ln, checked_add(end, 2)?)
} else if ln_byte > 0x80 {
let n_bytes = ln_byte - 0x80;
let mut ln: usize = 0;
for i in 0..n_bytes {
ln = ln.checked_mul(0x100).ok_or(TlvError::InvalidEncoding)?
| get(checked_add(offset, i)?)? as usize;
}
offset = checked_add(offset, n_bytes)?;
(ln, checked_add(offset, ln)?)
} else {
(ln_byte, checked_add(offset, ln_byte)?)
};
if end > data.len() {
return Err(TlvError::InvalidEncoding);
}
Ok((tag, offset, ln, end))
}
pub fn parse_tlv_list(data: &[u8]) -> Result<Vec<(u32, Vec<u8>)>, TlvError> {
let mut result = Vec::new();
let mut offset = 0;
while offset < data.len() {
let (tag, val_offset, val_len, end) = tlv_parse(data, offset)?;
let val_end = val_offset
.checked_add(val_len)
.ok_or(TlvError::InvalidEncoding)?;
let value = data
.get(val_offset..val_end)
.ok_or(TlvError::IncorrectLength)?;
result.push((tag, value.to_vec()));
offset = end;
}
Ok(result)
}
pub fn parse_tlv_dict(data: &[u8]) -> Result<HashMap<u32, Vec<u8>>, TlvError> {
let entries = parse_tlv_list(data)?;
Ok(entries.into_iter().collect())
}
pub fn tlv_unpack(expected_tag: u32, data: &[u8]) -> Result<Vec<u8>, TlvError> {
let (tag, val_offset, val_len, _) = tlv_parse(data, 0)?;
if tag != expected_tag {
return Err(TlvError::WrongTag {
got: tag,
expected: expected_tag,
});
}
let val_end = val_offset
.checked_add(val_len)
.ok_or(TlvError::InvalidEncoding)?;
data.get(val_offset..val_end)
.map(|v| v.to_vec())
.ok_or(TlvError::IncorrectLength)
}
pub(crate) fn tlv_get(tlvs: &[(u32, Vec<u8>)], tag: u32) -> Option<&[u8]> {
tlvs.iter()
.find(|(t, _)| *t == tag)
.map(|(_, v)| v.as_slice())
}
pub fn tlv_encode(tag: u32, value: &[u8]) -> Vec<u8> {
let mut buf = Vec::new();
tlv_append(&mut buf, tag, value);
buf
}
pub fn tlv_append(buf: &mut Vec<u8>, tag: u32, value: &[u8]) {
if tag > 0xFFFF {
buf.push((tag >> 24) as u8);
buf.push((tag >> 16) as u8);
buf.push((tag >> 8) as u8);
buf.push(tag as u8);
} else if tag > 0xFF {
buf.push((tag >> 8) as u8);
buf.push(tag as u8);
} else {
buf.push(tag as u8);
}
let length = value.len();
if length < 0x80 {
buf.push(length as u8);
} else {
let ln_bytes = int2bytes(length as u64);
buf.push(0x80 | ln_bytes.len() as u8);
buf.extend_from_slice(&ln_bytes);
}
buf.extend_from_slice(value);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tlv_roundtrip() {
let encoded = tlv_encode(0x71, b"hello");
let (tag, offset, ln, end) = tlv_parse(&encoded, 0).unwrap();
assert_eq!(tag, 0x71);
assert_eq!(&encoded[offset..offset + ln], b"hello");
assert_eq!(end, encoded.len());
}
#[test]
fn test_tlv_rejects_oversized_length() {
let mut encoded = vec![0x71, 0x88];
encoded.extend_from_slice(&usize::MAX.to_be_bytes());
assert!(matches!(
tlv_parse(&encoded, 0),
Err(TlvError::InvalidEncoding)
));
}
#[test]
fn test_parse_tlv_list_rejects_truncated_value() {
let encoded = [0x71, 0x02, 0xAA];
assert!(matches!(
parse_tlv_list(&encoded),
Err(TlvError::InvalidEncoding | TlvError::IncorrectLength)
));
}
#[test]
fn test_tlv_rejects_too_deep_indefinite_nesting() {
let mut encoded = Vec::new();
for _ in 0..=MAX_TLV_DEPTH {
encoded.extend_from_slice(&[0xE0, 0x80]);
}
for _ in 0..=MAX_TLV_DEPTH {
encoded.extend_from_slice(&[0x00, 0x00]);
}
assert!(matches!(
tlv_parse(&encoded, 0),
Err(TlvError::InvalidEncoding)
));
}
#[test]
fn test_tlv_rejects_tags_larger_than_u32() {
let encoded = [0x1F, 0x81, 0x82, 0x83, 0x04, 0x00];
assert!(matches!(
tlv_parse(&encoded, 0),
Err(TlvError::InvalidEncoding)
));
}
#[test]
fn test_int2bytes() {
assert_eq!(int2bytes(0), vec![0]);
assert_eq!(int2bytes(255), vec![0xFF]);
assert_eq!(int2bytes(256), vec![0x01, 0x00]);
}
}