use crate::bytes::Cursor;
use crate::error::{ErrorCode, Result, bail};
pub const AID: [u8; 9] = [0xA0, 0x00, 0x00, 0x09, 0x09, 0x8A, 0x77, 0xE4, 0x01];
pub const VERSION: u8 = 0x01;
pub const INS_SELECT: u8 = 0xA4;
pub const INS_TRANSPORT: u8 = 0x20;
pub const INS_GET_RESPONSE: u8 = 0xC0;
pub const CLA_TRANSPORT_LAST: u8 = 0x80;
pub const CLA_TRANSPORT_CHAINED: u8 = 0x90;
pub const MAX_FRAGMENT: usize = 255;
pub const MAX_MESSAGE: usize = 0xFFFF;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Status {
pub sw1: u8,
pub sw2: u8,
}
impl Status {
pub const OK: Self = Self {
sw1: 0x90,
sw2: 0x00,
};
pub const CONDITIONS_NOT_SATISFIED: Self = Self {
sw1: 0x69,
sw2: 0x85,
};
pub const NOT_ENOUGH_MEMORY: Self = Self {
sw1: 0x6A,
sw2: 0x84,
};
#[must_use]
pub const fn more(remaining: u8) -> Self {
Self {
sw1: 0x61,
sw2: remaining,
}
}
#[must_use]
pub const fn remaining(&self) -> Option<u8> {
if self.sw1 == 0x61 {
Some(self.sw2)
} else {
None
}
}
#[must_use]
pub const fn is_ok(&self) -> bool {
matches!(self.sw1, 0x90 | 0x61)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Selected<'a> {
pub version: u8,
pub discriminator: u16,
pub vendor_id: u16,
pub product_id: u16,
pub extended: &'a [u8],
}
impl<'a> Selected<'a> {
pub const LEN: usize = 7;
pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
let mut w = Cursor::writer(out);
w.u8(self.version)?;
w.u8(0)?;
w.u8(u8::try_from(self.discriminator >> 8).unwrap_or(0) & 0x0F)?;
w.u8(u8::try_from(self.discriminator & 0xFF).unwrap_or(0))?;
w.u8(u8::try_from(self.vendor_id >> 8).unwrap_or(0))?;
w.u8(u8::try_from(self.vendor_id & 0xFF).unwrap_or(0))?;
w.u8(u8::try_from(self.product_id >> 8).unwrap_or(0))?;
w.u8(u8::try_from(self.product_id & 0xFF).unwrap_or(0))?;
w.put(self.extended)?;
Ok(w.position())
}
pub fn decode(data: &'a [u8]) -> Result<Self> {
let mut r = Cursor::reader(data, ErrorCode::MessageTruncated);
let version = r.read_u8()?;
let _reserved = r.read_u8()?;
let high = r.read_u8()?;
let low = r.read_u8()?;
if high >> 4 != 0 {
bail!(UnsupportedVersion)
}
let discriminator = (u16::from(high & 0x0F) << 8) | u16::from(low);
let vendor_hi = r.read_u8()?;
let vendor_lo = r.read_u8()?;
let product_hi = r.read_u8()?;
let product_lo = r.read_u8()?;
let vendor_id = (u16::from(vendor_hi) << 8) | u16::from(vendor_lo);
let product_id = (u16::from(product_hi) << 8) | u16::from(product_lo);
if vendor_id == 0 && product_id != 0 {
bail!(MessageReserved)
}
Ok(Self {
version,
discriminator,
vendor_id,
product_id,
extended: r.rest(),
})
}
}
pub fn select(out: &mut [u8]) -> Result<usize> {
let mut w = Cursor::writer(out);
w.u8(0x00)?;
w.u8(INS_SELECT)?;
w.u8(0x04)?;
w.u8(0x0C)?;
w.u8(u8::try_from(AID.len()).unwrap_or(0))?;
for byte in AID {
w.u8(byte)?;
}
w.u8(0x00)?;
Ok(w.position())
}
#[must_use]
pub fn is_select(apdu: &[u8]) -> bool {
let Some(&[cla, ins, p1, p2, lc]) = apdu.get(..5).and_then(|h| <&[u8; 5]>::try_from(h).ok())
else {
return false;
};
cla == 0x00
&& ins == INS_SELECT
&& p1 == 0x04
&& p2 == 0x0C
&& usize::from(lc) == AID.len()
&& apdu.get(5..5usize.saturating_add(AID.len())) == Some(&AID[..])
}
pub fn get_response(le: u8, out: &mut [u8]) -> Result<usize> {
let mut w = Cursor::writer(out);
w.u8(0x00)?;
w.u8(INS_GET_RESPONSE)?;
w.u8(0x00)?;
w.u8(0x00)?;
w.u8(le)?;
Ok(w.position())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Transport<'a> {
pub chained: bool,
pub message_length: u16,
pub fragment: &'a [u8],
pub le: u8,
}
impl<'a> Transport<'a> {
pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
if self.fragment.len() > MAX_FRAGMENT {
bail!(BufferTooSmall)
}
if usize::from(self.message_length) < self.fragment.len() {
bail!(InvalidArgument)
}
let mut w = Cursor::writer(out);
w.u8(if self.chained {
CLA_TRANSPORT_CHAINED
} else {
CLA_TRANSPORT_LAST
})?;
w.u8(INS_TRANSPORT)?;
w.u8(u8::try_from(self.message_length >> 8).unwrap_or(0))?;
w.u8(u8::try_from(self.message_length & 0xFF).unwrap_or(0))?;
w.u8(u8::try_from(self.fragment.len()).unwrap_or(0))?;
w.put(self.fragment)?;
w.u8(self.le)?;
Ok(w.position())
}
pub fn decode(apdu: &'a [u8]) -> Result<Self> {
let mut r = Cursor::reader(apdu, ErrorCode::MessageTruncated);
let cla = r.read_u8()?;
let chained = match cla {
CLA_TRANSPORT_LAST => false,
CLA_TRANSPORT_CHAINED => true,
_ => bail!(MessageReserved),
};
if r.read_u8()? != INS_TRANSPORT {
bail!(MessageReserved)
}
let p1 = r.read_u8()?;
let p2 = r.read_u8()?;
let lc = usize::from(r.read_u8()?);
let fragment = r.take(lc)?;
let le = r.read_u8()?;
Ok(Self {
chained,
message_length: (u16::from(p1) << 8) | u16::from(p2),
fragment,
le,
})
}
}
#[derive(Debug)]
pub struct Reassembler<const N: usize> {
buf: heapless::Vec<u8, N>,
expecting: Option<u16>,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Reassembled {
More,
Message,
}
impl<const N: usize> Default for Reassembler<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> Reassembler<N> {
#[must_use]
pub const fn new() -> Self {
Self {
buf: heapless::Vec::new(),
expecting: None,
}
}
pub fn push(&mut self, command: &Transport<'_>) -> core::result::Result<Reassembled, Status> {
let length = command.message_length;
if usize::from(length) > N {
self.reset();
return Err(Status::NOT_ENOUGH_MEMORY);
}
match self.expecting {
Some(expected) if expected != length => {
self.reset();
return Err(Status::CONDITIONS_NOT_SATISFIED);
}
_ => self.expecting = Some(length),
}
let total = self.buf.len().saturating_add(command.fragment.len());
if total > usize::from(length) {
self.reset();
return Err(Status::CONDITIONS_NOT_SATISFIED);
}
if self.buf.extend_from_slice(command.fragment).is_err() {
self.reset();
return Err(Status::NOT_ENOUGH_MEMORY);
}
if command.chained {
return Ok(Reassembled::More);
}
if self.buf.len() != usize::from(length) {
self.reset();
return Err(Status::CONDITIONS_NOT_SATISFIED);
}
Ok(Reassembled::Message)
}
#[must_use]
pub fn message(&self) -> &[u8] {
&self.buf
}
pub fn take_message(&mut self) {
self.reset();
}
fn reset(&mut self) {
self.buf.clear();
self.expecting = None;
}
}
#[derive(Debug)]
pub struct Responder<'a> {
message: &'a [u8],
sent: usize,
}
impl<'a> Responder<'a> {
#[must_use]
pub const fn new(message: &'a [u8]) -> Self {
Self { message, sent: 0 }
}
#[must_use]
pub const fn is_done(&self) -> bool {
self.sent >= self.message.len()
}
pub fn next(&mut self, le: u8) -> (&'a [u8], Status) {
let room = if le == 0 { 256 } else { usize::from(le) };
let remaining = self.message.len().saturating_sub(self.sent);
let take = room.min(remaining);
let fragment = self
.message
.get(self.sent..self.sent.saturating_add(take))
.unwrap_or(&[]);
self.sent = self.sent.saturating_add(take);
let left = self.message.len().saturating_sub(self.sent);
let status = if left == 0 {
Status::OK
} else {
Status::more(u8::try_from(left).unwrap_or(0xFF))
};
(fragment, status)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_select_command_is_table_44() {
let mut buf = [0u8; 32];
let n = select(&mut buf).expect("encode");
assert_eq!(
&buf[..n],
&[
0x00, 0xA4, 0x04, 0x0C, 0x09, 0xA0, 0x00, 0x00, 0x09, 0x09, 0x8A, 0x77, 0xE4, 0x01,
0x00
]
);
assert!(is_select(&buf[..n]));
let mut other = buf;
other[5] = 0xA1;
assert!(!is_select(&other[..n]));
}
#[test]
fn the_select_response_carries_discovery_information() {
let selected = Selected {
version: VERSION,
discriminator: 0xF00,
vendor_id: 0xFFF1,
product_id: 0x8000,
extended: &[],
};
let mut buf = [0u8; 32];
let n = selected.encode(&mut buf).expect("encode");
assert_eq!(n, Selected::LEN + 1);
assert_eq!(&buf[..n], &[0x01, 0x00, 0x0F, 0x00, 0xFF, 0xF1, 0x80, 0x00]);
assert_eq!(Selected::decode(&buf[..n]).expect("decode"), selected);
}
#[test]
fn a_product_id_without_a_vendor_id_is_refused() {
let data = [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00];
assert!(Selected::decode(&data).is_err());
let quiet = [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
assert_eq!(Selected::decode(&quiet).expect("decode").vendor_id, 0);
}
#[test]
fn a_transport_command_round_trips() {
let command = Transport {
chained: true,
message_length: 0x0140,
fragment: &[1, 2, 3],
le: 0x00,
};
let mut buf = [0u8; 32];
let n = command.encode(&mut buf).expect("encode");
assert_eq!(&buf[..n], &[0x90, 0x20, 0x01, 0x40, 0x03, 1, 2, 3, 0x00]);
assert_eq!(Transport::decode(&buf[..n]).expect("decode"), command);
let last = Transport {
chained: false,
..command
};
let n = last.encode(&mut buf).expect("encode");
assert_eq!(buf[0], CLA_TRANSPORT_LAST);
assert_eq!(Transport::decode(&buf[..n]).expect("decode"), last);
}
#[test]
fn a_status_word_says_what_is_left() {
assert!(Status::OK.is_ok());
assert_eq!(Status::OK.remaining(), None);
assert!(Status::more(42).is_ok());
assert_eq!(Status::more(42).remaining(), Some(42));
assert!(!Status::CONDITIONS_NOT_SATISFIED.is_ok());
assert!(!Status::NOT_ENOUGH_MEMORY.is_ok());
}
}