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
//! This module provides tools and utilities for handling SIMPLE-TLV data as
//! defined in [ISO7819-4][iso7816-4].
//!
//!
//!
//!
//! [iso7816-4]: https://www.iso.org/standard/54550.html
//!
use std::convert::TryFrom;
use untrusted::{Input, Reader};

use crate::{Result, TlvError};

/// Tag for SIMPLE-TLV data as defined in [ISO7819-4].
/// > The tag field consists of a single byte encoding a tag number from 1 to 254.
/// > The values '00' and 'FF' are invalid for tag fields.
///
/// Tags can be generated using the [TryFrom][TryFrom] trait
/// from u8 or hex [str][str].
///
/// [TryFrom]: https://doc.rust-lang.org/std/convert/trait.TryFrom.html
/// [str]:https://doc.rust-lang.org/std/str/
///
/// # Example
/// ```rust
/// use std::convert::TryFrom;
/// use iso7816_tlv::simple::Tag;
/// # use iso7816_tlv::TlvError;
/// # fn main() -> () {
///
/// assert!(Tag::try_from("80").is_ok());
/// assert!(Tag::try_from(8u8).is_ok());
/// assert!(Tag::try_from(0x80).is_ok());
/// assert!(Tag::try_from(127).is_ok());
///
/// assert!(Tag::try_from("er").is_err());
/// assert!(Tag::try_from("00").is_err());
/// assert!(Tag::try_from("ff").is_err());
/// # }
/// #
/// ```
#[derive(PartialEq, Debug, Clone)]
pub struct Tag(u8);

/// Value for SIMPLE-TLV data as defined in [ISO7819-4].
/// > the value field consists of N consecutive bytes.
/// N may be zero. In this case there is no value field
#[derive(PartialEq, Debug, Clone)]
pub struct Value(Vec<u8>);

/// SIMPLE-TLV data object representation.
/// > Each SIMPLE-TLV data object shall consist of two or three consecutive fields:
/// a mandatory tag field, a mandatory length field and a conditional value field
#[derive(PartialEq, Debug, Clone)]
pub struct Tlv {
  tag: Tag,
  value: Value,
}

impl TryFrom<u8> for Tag {
  type Error = TlvError;
  fn try_from(v: u8) -> Result<Self> {
    match v {
      0x00 | 0xFF => Err(TlvError::InvalidInput),
      _ => Ok(Tag(v)),
    }
  }
}

impl TryFrom<&str> for Tag {
  type Error = TlvError;
  fn try_from(v: &str) -> Result<Self> {
    let x = u8::from_str_radix(v, 16)?;
    Tag::try_from(x)
  }
}

impl Tlv {
  /// Create a SIMPLE-TLV data object from valid tag and value.
  /// A value has a maximum size of 65_535 bytes.
  /// Otherwise this fonction fails with TlvError::InvalidLength.
  pub fn new(tag: Tag, value: Value) -> Result<Self> {
    if value.0.len() > 65_536 {
      Err(TlvError::InvalidLength)
    } else {
      Ok(Tlv { tag, value: value })
    }
  }

  /// serializes self into a byte vector.
  pub fn to_vec(&self) -> Vec<u8> {
    let mut ret = Vec::new();
    ret.push(self.tag.0);
    let len = self.value.0.len();
    match len {
      0..=254 => ret.push(len as u8),
      _ => {
        ret.push(0xFF);
        ret.push((len >> 8) as u8);
        ret.push(len as u8);
      }
    };
    ret.extend(&self.value.0);
    ret
  }

  fn read_len(r: &mut Reader) -> Result<usize> {
    let mut ret: usize = 0;
    let x = r.read_byte()?;
    if x == 0xFF {
      for _ in 0..2 {
        let x = r.read_byte()?;
        ret = ret << 8 | x as usize;
      }
    } else {
      ret = x as usize;
    }
    Ok(ret)
  }

  fn read(r: &mut Reader) -> Result<Self> {
    let tag = Tag::try_from(r.read_byte()?)?;
    let len = Tlv::read_len(r)?;
    let content = r.read_bytes(len)?;

    Ok(Tlv {
      tag,
      value: Value(content.as_slice_less_safe().to_vec()),
    })
  }

  /// Parses a byte array into a SIMPLE-TLV structure.
  /// This also returns the unprocessed data.
  pub fn parse(input: &[u8]) -> (Result<Self>, &[u8]) {
    let mut r = Reader::new(Input::from(input));
    (
      Tlv::read(&mut r),
      r.read_bytes_to_end().as_slice_less_safe(),
    )
  }

  /// Parses a byte array into a SIMPLE-TLV structure.
  /// Input must exactly match a SIMPLE-TLV object.
  pub fn from_bytes(input: &[u8]) -> Result<Self> {
    let (r, n) = Tlv::parse(input);
    if n.len() != 0 {
      Err(TlvError::InvalidInput)
    } else {
      r
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use std::convert::TryFrom;

  #[test]
  fn tag_import() {
    assert!(Tag::try_from("80").is_ok());
    assert!(Tag::try_from(8u8).is_ok());
    assert!(Tag::try_from(0x80).is_ok());
    assert!(Tag::try_from(127).is_ok());

    assert!(Tag::try_from("er").is_err());
    assert!(Tag::try_from("00").is_err());
    assert!(Tag::try_from("ff").is_err());
  }
}