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 4 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
12 changes: 12 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion zvt/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@ 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
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,4 +1,5 @@
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 All @@ -10,7 +11,6 @@ use std::marker::Unpin;
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio_stream::Stream;
use zvt_builder::ZVTError;

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
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 logging;
dorezyuk marked this conversation as resolved.
Show resolved Hide resolved
pub mod packets;
pub mod sequences;

Expand Down
59 changes: 59 additions & 0 deletions zvt/src/logging.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use anyhow::Result;
use async_trait::async_trait;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

pub struct PacketWriter<Source> {
dorezyuk marked this conversation as resolved.
Show resolved Hide resolved
pub source: Source,
}

#[async_trait]
pub trait AsyncReadPacket {
dorezyuk marked this conversation as resolved.
Show resolved Hide resolved
async fn read_packet(&mut self) -> Result<Vec<u8>>;
}

#[async_trait]
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);

Ok(buf.to_vec())
}
}

#[async_trait]
pub trait AsyncWritePacket {
async fn write_packet<'a>(&mut self, buf: &'a [u8]) -> Result<()>;
}

#[async_trait]
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))
}
}
Loading