Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/logging2 #9

Merged
merged 7 commits into from
Dec 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion zvt/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,3 @@ async-stream = "0.3.5"
serde = { version = "1.0.185", features = ["derive"] }
serde_json = "1.0.105"
futures = "0.3.28"

dorezyuk marked this conversation as resolved.
Show resolved Hide resolved
5 changes: 3 additions & 2 deletions zvt/src/bin/feig_update/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::fs::read_to_string;
use std::path::PathBuf;
use tokio::net::TcpStream;
use tokio_stream::StreamExt;
use zvt::{feig, packets, sequences, sequences::Sequence};
use zvt::{feig, io, packets, sequences, sequences::Sequence};

/// Updates a feig terminal.
#[derive(Parser)]
Expand Down Expand Up @@ -53,7 +53,8 @@ async fn main() -> Result<()> {
let args = Args::parse();

// Connect to the payment terminal.
let mut socket = TcpStream::connect(&args.ip_address).await?;
let source = TcpStream::connect(&args.ip_address).await?;
let mut socket = io::PacketTransport { source };
const MAX_LEN_ADPU: u16 = 1u16 << 15;
let registration = packets::Registration {
password: args.password,
Expand Down
5 changes: 3 additions & 2 deletions zvt/src/bin/status/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use log::info;
use std::io::Write;
use tokio::net::TcpStream;
use tokio_stream::StreamExt;
use zvt::{packets, sequences, sequences::Sequence};
use zvt::{io, packets, sequences, sequences::Sequence};

#[derive(Parser, Debug)]
struct Args {
Expand Down Expand Up @@ -57,7 +57,8 @@ async fn main() -> std::io::Result<()> {
let args = Args::parse();

info!("Using the args {:?}", args);
let mut socket = TcpStream::connect(args.ip).await?;
let source = TcpStream::connect(args.ip).await?;
let mut socket = io::PacketTransport { source };

let request = packets::Registration {
password: args.password,
Expand Down
24 changes: 10 additions & 14 deletions zvt/src/feig/sequences.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::sequences::{read_packet_async, write_with_ack_async, Sequence};
use crate::{packets, ZvtEnum, ZvtParser, ZvtSerializer};
use crate::io::PacketTransport;
use crate::sequences::Sequence;
use crate::{packets, ZvtEnum};
use anyhow::Result;
use async_stream::try_stream;
use std::boxed::Box;
Expand Down Expand Up @@ -94,10 +95,10 @@ impl WriteFile {
path: PathBuf,
password: usize,
adpu_size: u32,
src: &mut Source,
src: &mut PacketTransport<Source>,
) -> Pin<Box<impl Stream<Item = Result<WriteFileResponse>> + '_>>
where
Source: AsyncReadExt + AsyncWriteExt + Unpin,
Source: AsyncReadExt + AsyncWriteExt + Unpin + Send,
{
// Protocol from the handbook (the numbering is not part of the handbook)
// 1.1 ECR->PT: Send over the list of all files with their sizes.
Expand All @@ -108,8 +109,6 @@ impl WriteFile {
// 3.0 PT->ERC replies with Completion.

let s = try_stream! {
tokio::pin!(src);

use super::packets::tlv::File as TlvFile;
let files = convert_dir(&path)?;
let mut packets = Vec::with_capacity(files.len());
Expand All @@ -133,26 +132,23 @@ impl WriteFile {
};

// 1.1. and 1.2
write_with_ack_async(&packet, &mut src).await?;
src.write_packet_with_ack(&packet).await?;
let mut buf = vec![0; adpu_size as usize];
println!("the length is {}", buf.len());

loop {
// Get the data.
let bytes = read_packet_async(&mut src).await?;
println!("The packet is {:?}", bytes);

let response = WriteFileResponse::zvt_parse(&bytes)?;
let response = src.read_packet().await?;

match response {
WriteFileResponse::CompletionData(_) => {
src.write_all(&packets::Ack {}.zvt_serialize()).await?;
src.write_packet(&packets::Ack {}).await?;

yield response;
break;
}
WriteFileResponse::Abort(_) => {
src.write_all(&packets::Ack {}.zvt_serialize()).await?;
src.write_packet(&packets::Ack {}).await?;

yield response;
break;
Expand Down Expand Up @@ -195,7 +191,7 @@ impl WriteFile {
}),
}),
};
src.write_all(&packet.zvt_serialize()).await?;
src.write_packet(&packet).await?;

yield response;
}
Expand Down
95 changes: 95 additions & 0 deletions zvt/src/io.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
use crate::packets;
use crate::ZvtEnum;
use crate::ZvtParser;
use anyhow::Result;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use zvt_builder::encoding;
use zvt_builder::ZvtSerializer;

#[derive(ZvtEnum)]
pub enum Ack {
Ack(packets::Ack),
}

pub struct PacketTransport<Source> {
pub source: Source,
}

impl<S> PacketTransport<S>
where
S: AsyncReadExt + Unpin + Send,
{
/// Reads an ADPU packet from the PT.
pub async fn read_packet<T>(&mut self) -> Result<T>
where
T: ZvtParser + Send,
{
let mut buf = vec![0; 3];
self.source.read_exact(&mut buf).await?;

// Get the len.
let len = if buf[2] == 0xff {
buf.resize(5, 0);
self.source.read_exact(&mut buf[3..5]).await?;
u16::from_le_bytes(buf[3..5].try_into().unwrap()) as usize
} else {
buf[2] as usize
};

let start = buf.len();
buf.resize(start + len, 0);
self.source.read_exact(&mut buf[start..]).await?;

log::debug!("Read {:?}", buf);

Ok(T::zvt_parse(&buf)?)
}
}

impl<S> PacketTransport<S>
where
S: AsyncWriteExt + Unpin + Send,
{
/// Writes an ADPU packet to the PT.
pub async fn write_packet<'a, T>(&mut self, msg: &T) -> Result<()>
where
T: ZvtSerializer + Sync + Send,
encoding::Default: encoding::Encoding<T>,
{
let bytes = msg.zvt_serialize();
log::debug!("Write {:?}", bytes);
self.source
.write_all(&bytes)
.await
.map_err(|e| anyhow::anyhow!("Failed to write {:?}", e))
}
}

impl<S> PacketTransport<S>
where
S: AsyncWriteExt + AsyncReadExt + Unpin + Send,
{
/// Reads an ADPU packet from the PT and send an [packets::Ack].
pub async fn read_packet_with_ack<'a, T>(&mut self) -> Result<T>
where
T: ZvtParser + Send,
{
let packet = self.read_packet::<T>().await?;
self.write_packet(&packets::Ack {}).await?;

Ok(packet)
}

/// Writes an ADPU packet to the PT and awaits its [packets::Ack].
pub async fn write_packet_with_ack<'a, T>(&mut self, msg: &T) -> Result<()>
where
T: ZvtSerializer + Sync + Send,
encoding::Default: encoding::Encoding<T>,
{
self.write_packet(msg).await?;

let _ = self.read_packet::<Ack>().await?;

Ok(())
}
}
1 change: 1 addition & 0 deletions zvt/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod constants;
pub mod feig;
pub mod io;
pub mod packets;
pub mod sequences;

Expand Down
Loading