From e0d271d7035a6b81878d296de857d7afeee4dbd7 Mon Sep 17 00:00:00 2001 From: jake Date: Sun, 3 Nov 2019 10:47:23 -0800 Subject: [PATCH] throw errors if there isnt enough data to read in PSOPacketData --- src/lib.rs | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index c0d3e2b..7da5366 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,14 +10,13 @@ use std::io::Read; pub enum PacketParseError { NotEnoughBytes, WrongPacketCommand, - WrongPacketForServerType, + WrongPacketForServerType(u16), WrongPacketSize(u16, usize), DataStructNotLargeEnough(u64, usize), InvalidValue, ReadError, } - trait PSOPacketData { //fn size(&self) -> usize; fn from_bytes(cursor: &mut R) -> Result where Self: Sized; @@ -27,8 +26,12 @@ trait PSOPacketData { impl PSOPacketData for u8 { fn from_bytes(cursor: &mut R) -> Result { let mut bytes = [0u8; 1]; - cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?; - Ok(bytes[0]) + let len = cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?; + if len == 1 { + Ok(bytes[0]) + } else{ + Err(PacketParseError::NotEnoughBytes) + } } fn as_bytes(&self) -> Vec { vec![*self] @@ -38,8 +41,13 @@ impl PSOPacketData for u8 { impl PSOPacketData for u32 { fn from_bytes(cursor: &mut R) -> Result { let mut bytes = [0u8; 4]; - cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?; - Ok(u32::from_le_bytes(bytes)) + let len = cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?; + if len == 4 { + Ok(u32::from_le_bytes(bytes)) + } + else { + Err(PacketParseError::NotEnoughBytes) + } } fn as_bytes(&self) -> Vec { u32::to_le_bytes(*self).to_vec() @@ -49,8 +57,13 @@ impl PSOPacketData for u32 { impl PSOPacketData for u16 { fn from_bytes(cursor: &mut R) -> Result { let mut bytes = [0u8; 2]; - cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?; - Ok(u16::from_le_bytes(bytes)) + let len = cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?; + if len == 2 { + Ok(u16::from_le_bytes(bytes)) + } + else { + Err(PacketParseError::NotEnoughBytes) + } } fn as_bytes(&self) -> Vec { u16::to_le_bytes(*self).to_vec()