Skip to content

Commit

Permalink
nice
Browse files Browse the repository at this point in the history
  • Loading branch information
Dima Dorezyuk committed Dec 8, 2023
1 parent f6bcc46 commit 060abdd
Show file tree
Hide file tree
Showing 7 changed files with 125 additions and 104 deletions.
1 change: 0 additions & 1 deletion zvt/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,3 @@ serde = { version = "1.0.185", features = ["derive"] }
serde_json = "1.0.105"
futures = "0.3.28"
async-trait = "0.1.74"

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, logging, 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 = logging::PacketWriter { 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::{logging, 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 = logging::PacketWriter { source };

let request = packets::Registration {
password: args.password,
Expand Down
18 changes: 8 additions & 10 deletions zvt/src/feig/sequences.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::logging::{AsyncReadExt, AsyncWriteExt};
use crate::sequences::{read_packet_async, write_with_ack_async, Sequence};
use crate::logging::{AsyncReadPacket, AsyncWritePacket};
use crate::sequences::{write_with_ack_async, Sequence};
use crate::{packets, ZvtEnum, ZvtParser, ZvtSerializer};
use anyhow::Result;
use async_stream::try_stream;
Expand Down Expand Up @@ -97,7 +97,7 @@ impl WriteFile {
src: &mut Source,
) -> Pin<Box<impl Stream<Item = Result<WriteFileResponse>> + '_>>
where
Source: AsyncReadExt + AsyncWriteExt + Unpin,
Source: AsyncReadPacket + AsyncWritePacket + 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 +108,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 +131,26 @@ impl WriteFile {
};

// 1.1. and 1.2
write_with_ack_async(&packet, &mut src).await?;
write_with_ack_async(&packet, src).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?;
let bytes = src.read_packet().await?;
println!("The packet is {:?}", bytes);

let response = WriteFileResponse::zvt_parse(&bytes)?;

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

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

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

yield response;
}
Expand Down
2 changes: 1 addition & 1 deletion zvt/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
pub mod constants;
pub mod feig;
pub mod logging;
pub mod packets;
pub mod sequences;
pub mod logging;

// Reexport everything so we can just use this crate for importing the internals.
pub use zvt_builder::*;
Expand Down
62 changes: 48 additions & 14 deletions zvt/src/logging.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,59 @@
use anyhow::Result;
use async_trait::async_trait;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

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

#[async_trait]
pub trait AsyncReadPacket {
async fn read_packet(&mut self) -> Result<Vec<u8>>;
}

/// Trait which will log the byte payload after receiving.
#[async_trait]
pub trait AsyncReadExt: tokio::io::AsyncReadExt + Unpin + Send {
async fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> tokio::io::Result<usize> {
let res = <Self as tokio::io::AsyncReadExt>::read_exact(self, buf).await;
log::debug!("The length is {} and the result is {:?}", buf.len(), res);
impl<S> AsyncReadPacket for PacketWriter<S>
where
S: AsyncReadExt + Unpin + Send,
{
async fn read_packet(&mut self) -> Result<Vec<u8>> {
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);
res

Ok(buf.to_vec())
}
}

impl<R: tokio::io::AsyncReadExt + ?Sized + Unpin + Send> AsyncReadExt for R {}
#[async_trait]
pub trait AsyncWritePacket {
async fn write_packet<'a>(&mut self, buf: &'a [u8]) -> Result<()>;
}

/// Trait which will log the byte payload before transmitting.
#[async_trait]
pub trait AsyncWriteExt: tokio::io::AsyncWriteExt + Unpin + Send {
async fn write_all<'a>(&'a mut self, src: &'a [u8]) -> tokio::io::Result<()> {
log::debug!("Write {src:?}");
<Self as tokio::io::AsyncWriteExt>::write_all(self, src).await
impl<S> AsyncWritePacket for PacketWriter<S>
where
S: AsyncWriteExt + Unpin + Send,
{
async fn write_packet<'a>(&mut self, src: &'a [u8]) -> Result<()> {
log::debug!("Write {:?}", src);
self.source
.write_all(src)
.await
.map_err(|e| anyhow::anyhow!("Failed to write {:?}", e))
}
}

impl<W: tokio::io::AsyncWriteExt + ?Sized + Unpin + Send> AsyncWriteExt for W {}
Loading

0 comments on commit 060abdd

Please sign in to comment.