use zeroize::Zeroize;
use crate::{Command, Error, Response};
pub trait Transport {
fn transmit_raw(&mut self, apdu: &[u8]) -> Result<Vec<u8>, Error>;
fn reset(&mut self) -> Result<Vec<u8>, Error>;
fn transaction<R>(
&mut self,
body: impl FnOnce(&mut dyn Transport) -> Result<R, Error>,
) -> Result<R, Error>
where
Self: Sized;
fn transmit(&mut self, command: &Command) -> Result<Response, Error> {
let mut resent = None;
let result = follow(self, command, &mut resent);
if let Some(mut copy) = resent {
copy.data.zeroize();
}
result
}
}
fn follow<T: Transport + ?Sized>(
transport: &mut T,
command: &Command,
resent: &mut Option<Command>,
) -> Result<Response, Error> {
let mut data = Vec::new();
let mut get_responses = 0;
let mut resends = 0;
loop {
let sent = resent.as_ref().unwrap_or(command);
let response = Response::parse(&transport.transmit_raw(&sent.to_bytes()?)?)?;
let [sw1, sw2] = response.status.0.to_be_bytes();
if sw1 == WRONG_LENGTH && sent.cla == PLAIN_CLA {
if resends == MAX_RESENDS {
return Err(Error::Status(response.status));
}
resends += 1;
let next = Command {
le: Some(short_le(sw2)),
..sent.clone()
};
if let Some(mut old) = resent.replace(next) {
old.data.zeroize();
}
continue;
}
resends = 0;
data.extend(response.data);
if sw1 != RESPONSE_PENDING {
return Ok(Response {
data,
status: response.status,
});
}
if get_responses == MAX_GET_RESPONSES {
return Err(Error::Status(response.status));
}
get_responses += 1;
if let Some(mut old) = resent.replace(get_response(sw2)) {
old.data.zeroize();
}
}
}
const RESPONSE_PENDING: u8 = 0x61;
const MAX_GET_RESPONSES: usize = 256;
pub(crate) const MAX_RESENDS: usize = 2;
pub(crate) const WRONG_LENGTH: u8 = 0x6C;
const PLAIN_CLA: u8 = 0x00;
fn get_response(le: u8) -> Command {
Command {
cla: PLAIN_CLA,
ins: 0xC0,
p1: 0x00,
p2: 0x00,
data: vec![],
le: Some(short_le(le)),
}
}
pub(crate) fn short_le(le: u8) -> u16 {
match le {
0 => 256,
le => le.into(),
}
}