- fix: no longer fail to parse packet if multiple were received in one read call
- update: max packet size to match client
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
use bincode::{Encode, Decode};
|
||||
use crate::packet_type::PacketType;
|
||||
use bincode::{Decode, Encode};
|
||||
use std::error::Error;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpStream;
|
||||
use tracing::{debug, error};
|
||||
use crate::packet_type::PacketType;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Packet {
|
||||
@@ -15,8 +15,7 @@ pub struct Packet {
|
||||
|
||||
pub trait PacketPayload: Encode + Decode {
|
||||
fn encode(&self) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let config = bincode::config::standard()
|
||||
.with_fixed_int_encoding();
|
||||
let config = bincode::config::standard().with_fixed_int_encoding();
|
||||
Ok(bincode::encode_to_vec(self, config)?)
|
||||
}
|
||||
|
||||
@@ -24,8 +23,7 @@ pub trait PacketPayload: Encode + Decode {
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
let config = bincode::config::standard()
|
||||
.with_fixed_int_encoding();
|
||||
let config = bincode::config::standard().with_fixed_int_encoding();
|
||||
Ok(bincode::decode_from_slice(data, config)?.0)
|
||||
}
|
||||
}
|
||||
@@ -47,6 +45,7 @@ impl Packet {
|
||||
|
||||
pub fn from_raw(data: &[u8]) -> Result<Self, Box<dyn Error + Send + Sync>> {
|
||||
if data.len() < 6 {
|
||||
error!("Invalid packet: Size too small {}", data.len());
|
||||
return Err("Invalid packet: Too short".into());
|
||||
}
|
||||
|
||||
@@ -56,18 +55,26 @@ impl Packet {
|
||||
let packet_crc = u16::from_le_bytes(data[4..6].try_into()?);
|
||||
|
||||
// Validate the size
|
||||
if packet_size as usize != data.len() {
|
||||
error!("Invalid packet: Size mismatch, expected: {}, actual: {}", packet_size, data.len());
|
||||
if packet_size as usize > data.len() {
|
||||
error!(
|
||||
"Invalid packet {:#X}: Size mismatch, expected: {}, received: {}",
|
||||
raw_packet_type,
|
||||
packet_size,
|
||||
data.len()
|
||||
);
|
||||
return Err("Invalid packet: Size mismatch".into());
|
||||
}
|
||||
|
||||
debug!("size: {:#X}, raw_type: {:#X}, crc: {:#X}", packet_size, raw_packet_type, packet_crc);
|
||||
|
||||
debug!(
|
||||
"size: {:#X}, raw_type: {:#X}, crc: {:#X}",
|
||||
packet_size, raw_packet_type, packet_crc
|
||||
);
|
||||
|
||||
// Convert raw packet type into `PacketType` enum
|
||||
let packet_type = PacketType::try_from(raw_packet_type)?;
|
||||
|
||||
// Extract the payload
|
||||
let payload = data[6..].to_vec();
|
||||
let payload = data[6..packet_size as usize].to_vec();
|
||||
|
||||
Ok(Self {
|
||||
packet_size,
|
||||
@@ -89,7 +96,7 @@ impl Packet {
|
||||
|
||||
raw
|
||||
}
|
||||
|
||||
|
||||
pub fn parse<T: PacketPayload>(&self) -> Result<T, Box<dyn Error + Send + Sync>> {
|
||||
<T as PacketPayload>::decode(&self.payload)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user