From 93446c078ee9ae82f9dddff53e71d1803b15a95a Mon Sep 17 00:00:00 2001 From: Wiktor Mazur Date: Sat, 2 Nov 2019 18:08:26 +0100 Subject: [PATCH] Photon fragments --- .gitignore | 3 +- backend/lib/photon-protocol/Cargo.lock | 2 +- backend/lib/photon-protocol/src/decode.rs | 442 ++++++++++ backend/lib/photon-protocol/src/layout.rs | 94 ++ backend/lib/photon-protocol/src/lib.rs | 804 ++---------------- backend/lib/photon-protocol/src/types.rs | 117 --- .../photon-protocol/tests/decoding_tests.rs | 361 ++++++++ .../tests/integration_tests.rs | 277 ++++++ backend/src/core.rs | 38 +- backend/src/game_protocol/message.rs | 2 + backend/src/game_protocol/mod.rs | 3 +- 11 files changed, 1292 insertions(+), 851 deletions(-) create mode 100644 backend/lib/photon-protocol/src/decode.rs create mode 100644 backend/lib/photon-protocol/src/layout.rs delete mode 100644 backend/lib/photon-protocol/src/types.rs create mode 100644 backend/lib/photon-protocol/tests/decoding_tests.rs create mode 100644 backend/lib/photon-protocol/tests/integration_tests.rs diff --git a/.gitignore b/.gitignore index 734fc1b..cf2fe19 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ -backend/target -/target +**/target **/*.rs.bk **/target damage-meter.log diff --git a/backend/lib/photon-protocol/Cargo.lock b/backend/lib/photon-protocol/Cargo.lock index 6e18a0d..e6bc75a 100644 --- a/backend/lib/photon-protocol/Cargo.lock +++ b/backend/lib/photon-protocol/Cargo.lock @@ -29,7 +29,7 @@ version = "0.2.60" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] -name = "protocol16" +name = "photon_protocol" version = "0.1.0" dependencies = [ "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)", diff --git a/backend/lib/photon-protocol/src/decode.rs b/backend/lib/photon-protocol/src/decode.rs new file mode 100644 index 0000000..6432229 --- /dev/null +++ b/backend/lib/photon-protocol/src/decode.rs @@ -0,0 +1,442 @@ +use std::collections::HashMap; +use std::io::{Cursor, Read}; +use std::mem::size_of; + +use bytes::Buf; + +use crate::layout::*; + +pub type PhotonDecodeError = &'static str; +pub type PhotonDecodeResult = std::result::Result; +pub type PhotonCursor<'a> = Cursor<&'a [u8]>; + +pub trait Decode { + fn decode(&mut self) -> PhotonDecodeResult; +} + +trait TypedDecode { + fn typed_decode(&mut self, type_code: u8) -> PhotonDecodeResult; +} + +macro_rules! impl_decode { + ($type:ty, $decode_func:ident, $bytes_to_consume:expr) => { + impl Decode<$type> for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult<$type> { + let v = if self.remaining() >= $bytes_to_consume { + self.$decode_func() + } else { + return Err(concat!( + "Failed to decode", + stringify!($type), + ", not enough bytes" + )); + }; + Ok(v) + } + } + }; +} + +impl_decode!(u8, get_u8, 1); +impl_decode!(f32, get_f32_be, 4); +impl_decode!(u32, get_u32_be, 4); +impl_decode!(i64, get_i64_be, 8); +impl_decode!(i16, get_i16_be, 2); +impl_decode!(f64, get_f64_be, 8); + +impl Decode for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult { + let v = if self.remaining() >= 1 { + self.get_u8() + } else { + return Err("Failed to decode bool, not enough bytes"); + }; + Ok(v != 0) + } +} + +impl Decode for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult { + let size: i16 = self.decode()?; + if size < 0 { + return Err("Failed to decode String, unreasonable size"); + } + + let mut local_buffer = vec![0; size as usize]; + if let Ok(_) = self.read_exact(&mut local_buffer[..]) { + if let Ok(s) = String::from_utf8(local_buffer) { + return Ok(s); + } + } + + Err("Failed to decode String, not enough bytes") + } +} + +impl Decode> for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult> { + let size: i16 = self.decode()?; + if size < 0 { + return Err("Failed to decode String, unreasonable size"); + } + let mut value: Vec = vec![]; + for _ in 0..size { + value.push(self.decode()?); + } + + Ok(value) + } +} + +impl Decode> for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult> { + let size: u32 = self.decode()?; + let mut value: Vec = vec![]; + for _ in 0..size { + value.push(self.decode()?); + } + + Ok(value) + } +} + +impl Decode> for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult> { + let size: i16 = self.decode()?; + if size <= 0 { + return Err("Failed to decode Vec, unreasonable size"); + } + let type_code: u8 = self.decode()?; + + let mut value: Vec = vec![]; + for _ in 0..size { + if let Ok(v) = self.typed_decode(type_code) { + value.push(v); + } else { + break; + } + } + + Ok(value) + } +} + +impl Decode> for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult> { + let key_type_code: u8 = self.decode()?; + let value_type_code: u8 = self.decode()?; + let size: i16 = self.decode()?; + if size <= 0 { + return Err("Failed to decode HashMap, unreasonable size"); + } + + let mut value: HashMap = HashMap::new(); + for _ in 0..size { + let key_code: u8 = if key_type_code == 0 || key_type_code == 42 { + self.decode()? + } else { + key_type_code + }; + + let key = self.typed_decode(key_code); + + let value_code: u8 = if value_type_code == 0 || value_type_code == 42 { + self.decode()? + } else { + value_type_code + }; + let val = self.typed_decode(value_code); + value.insert(format!("{}", key.unwrap()), val.unwrap()); + } + + Ok(value) + } +} + +impl Decode> for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult> { + let size: i16 = self.decode()?; + if size <= 0 { + return Err("Failed to decode HashMap, unreasonable size"); + } + + let mut value: HashMap = HashMap::new(); + for _ in 0..size { + let key_type_code: u8 = if let Ok(v) = self.decode() { + v + } else { + break; + }; + let val: Value = if let Ok(v) = self.decode() { + v + } else { + break; + }; + value.insert(key_type_code, val); + } + + Ok(value) + } +} + +impl Decode for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult { + let code: u8 = self.decode()?; + let parameters: HashMap = self.decode()?; + Ok(EventData { code, parameters }) + } +} + +impl Decode for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult { + let code: u8 = self.decode()?; + let return_code: i16 = self.decode()?; + let maybe_debug_message: Value = self.decode()?; + let debug_message = if let Value::String(s) = maybe_debug_message { + s + } else { + "None".to_owned() + }; + let parameters: HashMap = self.decode()?; + + Ok(OperationResponse { + code, + return_code, + debug_message, + parameters, + }) + } +} + +impl Decode for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult { + let code: u8 = self.decode()?; + let parameters: HashMap = self.decode()?; + Ok(OperationRequest { code, parameters }) + } +} + +impl Decode>> for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult>> { + let size: i16 = self.decode()?; + if size <= 0 { + return Err("Failed to decode Vec>, unreasonable size"); + } + let mut value = vec![]; + for _ in 0..size { + let type_code: u8 = if let Ok(v) = self.decode() { + v + } else { + break; + }; + value.push(Box::new(self.typed_decode(type_code).unwrap())); + } + Ok(value) + } +} + +impl Decode> for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult> { + let size: i16 = self.decode()?; + if size <= 0 { + return Err("Failed to decode Vec, unreasonable size"); + } + let mut value = vec![]; + for _ in 0..size { + value.push(self.decode()?); + } + Ok(value) + } +} + +impl TypedDecode for PhotonCursor<'_> { + fn typed_decode(&mut self, type_code: u8) -> PhotonDecodeResult { + match TypeCode::from(type_code) { + TypeCode::Null => Ok(Value::None), + TypeCode::Boolean => Ok(Value::Boolean(self.decode()?)), + TypeCode::Byte => Ok(Value::Byte(self.decode()?)), + TypeCode::Double => Ok(Value::Double(self.decode()?)), + TypeCode::Float => Ok(Value::Float(self.decode()?)), + TypeCode::Integer => Ok(Value::Integer(self.decode()?)), + TypeCode::Long => Ok(Value::Long(self.decode()?)), + TypeCode::Short => Ok(Value::Short(self.decode()?)), + TypeCode::String => Ok(Value::String(self.decode()?)), + TypeCode::StringArray => Ok(Value::StringArray(self.decode()?)), + TypeCode::ByteArray => Ok(Value::ByteArray(self.decode()?)), + TypeCode::Dictionary => Ok(Value::Dictionary(self.decode()?)), + TypeCode::EventData => Ok(Value::EventData(self.decode()?)), + TypeCode::OperationRequest => Ok(Value::OperationRequest(self.decode()?)), + TypeCode::OperationResponse => Ok(Value::OperationResponse(self.decode()?)), + TypeCode::BooleanArray => Ok(Value::BooleanArray(self.decode()?)), + TypeCode::Array => Ok(Value::Array(self.decode()?)), + TypeCode::ObjectArray => Ok(Value::ObjectArray(self.decode()?)), + _ => Err("Failed to decode Value, unknown type code"), + } + } +} + +impl Decode for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult { + let type_code: u8 = self.decode()?; + self.typed_decode(type_code) + } +} + +impl Decode for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult { + let peer_id = self.decode()?; + let crc_enabled = self.decode()?; + let command_count = self.decode()?; + let timestamp = self.decode()?; + let challenge = self.decode()?; + + Ok(PhotonHeader { + peer_id, + crc_enabled, + command_count, + timestamp, + challenge, + }) + } +} + +impl Decode for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult { + let channel_id = self.decode()?; + let flags = self.decode()?; + let reserved_byte = self.decode()?; + let length: u32 = self.decode()?; + let reliable_sequence_number = self.decode()?; + let msg_len = length - size_of::() as u32; + Ok(ReliableCommand { + channel_id, + flags, + reserved_byte, + msg_len, + reliable_sequence_number, + }) + } +} + +impl Decode for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult { + let mut reliable_command: ReliableCommand = self.decode()?; + let unknown = self.decode()?; + reliable_command.msg_len = reliable_command.msg_len - size_of::() as u32; + Ok(UnreliableCommand { + reliable_command, + unknown, + }) + } +} + +impl Decode for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult { + let mut reliable_command: ReliableCommand = self.decode()?; + let sequence_number = self.decode()?; + let fragment_count = self.decode()?; + let fragment_number = self.decode()?; + let total_length = self.decode()?; + let operation_length = self.decode()?; + + reliable_command.msg_len = reliable_command.msg_len - (size_of::() * 5) as u32; + let mut payload = vec![0u8; reliable_command.msg_len as usize]; + self.read_exact(&mut payload).unwrap(); + + Ok(ReliableFragment { + reliable_command, + sequence_number, + fragment_count, + fragment_number, + total_length, + operation_length, + payload, + }) + } +} + +impl Decode for PhotonCursor<'_> { + fn decode(&mut self) -> PhotonDecodeResult { + let cmd_type_id: u8 = self.decode()?; + match cmd_type_id { + 4 => Ok(Command::LogOut), + 6 => Ok(Command::SendReliable(self.decode()?)), + 7 => Ok(Command::SendUnreliable( + Decode::::decode(self)?.reliable_command, + )), + 8 => Ok(Command::SendReliableFragment(self.decode()?)), + _ => Ok(Command::SendReliable(self.decode()?)), + } + } +} + +pub enum TypeCode { + Unknown = 0, + Null = 42, + Dictionary = 68, + StringArray = 97, + Byte = 98, + Double = 100, + EventData = 101, + Float = 102, + Integer = 105, + Short = 107, + Long = 108, + BooleanArray = 110, + Boolean = 111, + OperationResponse = 112, + OperationRequest = 113, + String = 115, + ByteArray = 120, + Array = 121, + ObjectArray = 122, +} + +impl From for TypeCode { + fn from(v: u8) -> Self { + match v { + 0 => TypeCode::Unknown, + 42 => TypeCode::Null, + 68 => TypeCode::Dictionary, + 97 => TypeCode::StringArray, + 98 => TypeCode::Byte, + 100 => TypeCode::Double, + 101 => TypeCode::EventData, + 102 => TypeCode::Float, + 105 => TypeCode::Integer, + 107 => TypeCode::Short, + 108 => TypeCode::Long, + 110 => TypeCode::BooleanArray, + 111 => TypeCode::Boolean, + 112 => TypeCode::OperationResponse, + 113 => TypeCode::OperationRequest, + 115 => TypeCode::String, + 120 => TypeCode::ByteArray, + 121 => TypeCode::Array, + 122 => TypeCode::ObjectArray, + _ => TypeCode::Unknown, + } + } +} + +impl std::ops::Index for Value { + type Output = Value; + + fn index(&self, index: usize) -> &Self::Output { + match self { + Value::Array(v) => &v[index], + _ => panic!("Non indexable type"), + } + } +} + +impl std::fmt::Display for Value { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Value::String(v) => write!(f, "{}", v), + Value::Byte(v) => write!(f, "{}", v), + Value::Integer(v) => write!(f, "{}", v), + v => write!(f, "{:?}", v), + } + } +} diff --git a/backend/lib/photon-protocol/src/layout.rs b/backend/lib/photon-protocol/src/layout.rs new file mode 100644 index 0000000..955aca1 --- /dev/null +++ b/backend/lib/photon-protocol/src/layout.rs @@ -0,0 +1,94 @@ +use std::collections::HashMap; + +#[derive(Clone, Debug, PartialEq)] +pub enum Value { + None, + Dictionary(HashMap), + StringArray(Vec), + Byte(u8), + Double(f64), + EventData(EventData), + Float(f32), + Integer(u32), + Short(i16), + Long(i64), + BooleanArray(Vec), + Boolean(bool), + OperationResponse(OperationResponse), + OperationRequest(OperationRequest), + String(String), + ByteArray(Vec), + Array(Vec), + Object(Box), + ObjectArray(Vec>), +} + +pub type Parameters = HashMap; + +#[derive(Clone, Debug, PartialEq)] +pub struct EventData { + pub code: u8, + pub parameters: Parameters, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct OperationResponse { + pub code: u8, + pub return_code: i16, + pub debug_message: String, + pub parameters: Parameters, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct OperationRequest { + pub code: u8, + pub parameters: Parameters, +} + +#[derive(Debug, PartialEq)] +pub enum Message { + Request(OperationRequest), + Response(OperationResponse), + Event(EventData), +} + +#[derive(Debug)] +pub struct PhotonHeader { + pub peer_id: i16, + pub crc_enabled: bool, + pub command_count: u8, + pub timestamp: u32, + pub challenge: u32, +} + +#[derive(Debug, Clone)] +pub struct ReliableCommand { + pub channel_id: u8, + pub flags: u8, + pub reserved_byte: u8, + pub msg_len: u32, + pub reliable_sequence_number: u32, +} + +pub struct UnreliableCommand { + pub reliable_command: ReliableCommand, + pub unknown: u32, +} + +#[derive(Debug, Clone)] +pub struct ReliableFragment { + pub reliable_command: ReliableCommand, + pub sequence_number: u32, + pub fragment_count: u32, + pub fragment_number: u32, + pub total_length: u32, + pub operation_length: u32, + pub payload: Vec, +} + +pub enum Command { + LogOut, + SendUnreliable(ReliableCommand), + SendReliable(ReliableCommand), + SendReliableFragment(ReliableFragment), +} diff --git a/backend/lib/photon-protocol/src/lib.rs b/backend/lib/photon-protocol/src/lib.rs index b98971b..94a723d 100644 --- a/backend/lib/photon-protocol/src/lib.rs +++ b/backend/lib/photon-protocol/src/lib.rs @@ -1,747 +1,101 @@ -extern crate bytes; -mod types; +mod decode; +mod layout; + +pub use decode::*; +pub use layout::*; -use std::{error, fmt}; -use std::io::{Read, Cursor}; use std::collections::HashMap; +use std::convert::TryFrom; +use std::io::{Cursor, Read}; -use bytes::Buf; +impl TryFrom<(&ReliableCommand, &mut Cursor<&[u8]>)> for Message { + type Error = &'static str; - -use types::TypeCode; - -pub use types::Parameters; -pub use types::Value; - -#[derive(Debug, Clone)] -pub struct DeserializationError { - type_code: u8, -} - -impl fmt::Display for DeserializationError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Failed to deserialize type_code {}", self.type_code) - } -} - -impl error::Error for DeserializationError { - fn source(&self) -> Option<&(dyn error::Error + 'static)> { - None - } -} - -pub fn deserialize_boolean(buf: &mut Cursor<&[u8]>) -> Option { - let v = if buf.remaining() > 0 { - buf.get_u8() - } else { - return None; - }; - Some(v != 0) -} - -pub fn deserialize_byte(buf: &mut Cursor<&[u8]>) -> Option { - let v = if buf.remaining() > 0 { - buf.get_u8() - } else { - return None; - }; - Some(v) -} - -pub fn deserialize_float(buf: &mut Cursor<&[u8]>) -> Option { - let v = if buf.remaining() >= 4 { - buf.get_f32_be() - } else { - return None; - }; - Some(v) -} - -pub fn deserialize_integer(buf: &mut Cursor<&[u8]>) -> Option { - let v = if buf.remaining() >= 4 { - buf.get_u32_be() - } else { - return None; - }; - Some(v) -} - -pub fn deserialize_long(buf: &mut Cursor<&[u8]>) -> Option { - let v = if buf.remaining() >= 8 { - buf.get_i64_be() - } else { - return None; - }; - Some(v) -} - -pub fn deserialize_short(buf: &mut Cursor<&[u8]>) -> Option { - let v = if buf.remaining() >= 2 { - buf.get_i16_be() - } else { - return None; - }; - Some(v) -} - -pub fn deserialize_double(buf: &mut Cursor<&[u8]>) -> Option { - let v = if buf.remaining() >= 8 { - buf.get_f64_be() - } else { - return None; - }; - Some(v) -} - -pub fn deserialize_string(buf: &mut Cursor<&[u8]>) -> Option { - let size = if buf.remaining() >= 2 { - buf.get_i16_be() - } else { - return None; - }; - let mut local_buffer = vec![0; size as usize]; - - if let Ok(_) = buf.read_exact(&mut local_buffer[..]) { - if let Ok(s) = String::from_utf8(local_buffer) { - return Some(s); - } - } - None -} - -pub fn deserialize_string_array(buf: &mut Cursor<&[u8]>) -> Option> { - let size = if buf.remaining() >= 2 { - buf.get_i16_be() as usize - } else { - return None; - }; - let mut value = vec![]; - - for _ in 0..size { - if let Some(v) = deserialize_string(buf) { - value.push(v); - } - } - - Some(value) -} - -pub fn deserialize_byte_array(buf: &mut Cursor<&[u8]>) -> Option> { - let size = buf.get_u32_be() as usize; - let mut value = vec![]; - - for _ in 0..size { - if buf.remaining() > 0 { - value.push(buf.get_u8()); - } else { - return None; - } - } - - Some(value) -} - -pub fn deserialize_array(buf: &mut Cursor<&[u8]>) -> Option> { - let size = if buf.remaining() >= 2 { - buf.get_i16_be() - } else { - return None; - }; - let mut value = vec![]; - - if size == 0 { - return None; - } - - let type_code = buf.get_u8(); - - for _ in 0..size { - if let Ok(v) = deserialize(type_code, buf) { - value.push(v); - } else { - break; - } - } - - Some(value) -} - -pub fn deserialize_dictionary(buf: &mut Cursor<&[u8]>) -> Option> { - let key_type_code = buf.get_u8(); - let value_type_code = buf.get_u8(); - let size = if buf.remaining() >= 2 { - buf.get_i16_be() - } else { - return None; - }; - - if size == 0 { - return None; - } - - let mut value: HashMap = HashMap::new(); - - for _ in 0..size { - let key_code = if key_type_code == 0 || key_type_code == 42 { - buf.get_u8() - } else { - key_type_code - }; - - let key = deserialize(key_code, buf); - - let value_code = if value_type_code == 0 || value_type_code == 42 { - buf.get_u8() - } else { - value_type_code - }; - let val = deserialize(value_code, buf); - value.insert(format!("{}", key.unwrap()), val.unwrap()); - } - - Some(value) -} - -fn deserialize_parameter_table(buf: &mut Cursor<&[u8]>) -> HashMap { - let mut value: HashMap = HashMap::new(); - - let size = if buf.remaining() >= 2 { - buf.get_i16_be() - } else { - return value; - }; - - for _ in 0..size { - let key_type_code = if buf.remaining() > 0 { - buf.get_u8() - } else { - break; - }; - let value_type_code = if buf.remaining() > 0 { - buf.get_u8() - } else { - break; - }; - let val = deserialize(value_type_code, buf); - if let Ok(val) = val { - value.insert(key_type_code, val); - } - } - - value -} - -pub fn deserialize_event_data(buf: &mut Cursor<&[u8]>) -> Option { - let code = buf.get_u8(); - - Some(types::EventData { - code, - parameters: deserialize_parameter_table(buf), - }) -} - -pub fn deserialize_operation_response(buf: &mut Cursor<&[u8]>) -> Option { - let code = buf.get_u8(); - let return_code = buf.get_i16_be(); - let debug_message = if let Value::String(s) = deserialize(buf.get_u8(), buf).unwrap() { - s - } else { - "None".to_owned() - }; - let parameters = deserialize_parameter_table(buf); - Some(types::OperationResponse { - code, - return_code, - debug_message, - parameters, - }) -} - -pub fn deserialize_operation_request(buf: &mut Cursor<&[u8]>) -> Option { - let code = buf.get_u8(); - - Some(types::OperationRequest { - code, - parameters: deserialize_parameter_table(buf), - }) -} - -pub fn deserialize_object_array(buf: &mut Cursor<&[u8]>) -> Option> { - let size = if buf.remaining() >= 2 { - buf.get_i16_be() - } else { - return None; - }; - let mut value = vec![]; - - if size == 0 { - return None; - } - - for _ in 0..size { - let type_code = if buf.remaining() > 0 { - buf.get_u8() - } else { - break; - }; - value.push(deserialize(type_code, buf).unwrap()); - } - - Some(value) -} - -pub fn deserialize(type_code: u8, buf: &mut Cursor<&[u8]>) -> Result { - match TypeCode::from(type_code) { - TypeCode::Null => Ok(Value::None), - TypeCode::Boolean => deserialize_boolean(buf) - .map(|v| Ok(Value::Boolean(v))) - .unwrap_or(Err(DeserializationError { type_code })), - TypeCode::Byte => deserialize_byte(buf) - .map(|v| Ok(Value::Byte(v))) - .unwrap_or(Err(DeserializationError { type_code })), - TypeCode::Double => deserialize_double(buf) - .map(|v| Ok(Value::Double(v))) - .unwrap_or(Err(DeserializationError { type_code })), - TypeCode::Float => deserialize_float(buf) - .map(|v| Ok(Value::Float(v))) - .unwrap_or(Err(DeserializationError { type_code })), - TypeCode::Integer => deserialize_integer(buf) - .map(|v| Ok(Value::Integer(v))) - .unwrap_or(Err(DeserializationError { type_code })), - TypeCode::Long => deserialize_long(buf) - .map(|v| Ok(Value::Long(v))) - .unwrap_or(Err(DeserializationError { type_code })), - TypeCode::Short => deserialize_short(buf) - .map(|v| Ok(Value::Short(v))) - .unwrap_or(Err(DeserializationError { type_code })), - TypeCode::String => deserialize_string(buf) - .map(|v| Ok(Value::String(v))) - .unwrap_or(Err(DeserializationError { type_code })), - TypeCode::StringArray => deserialize_string_array(buf) - .map(|v| Ok(Value::StringArray(v))) - .unwrap_or(Err(DeserializationError { type_code })), - TypeCode::ByteArray => deserialize_byte_array(buf) - .map(|v| Ok(Value::ByteArray(v))) - .unwrap_or(Err(DeserializationError { type_code })), - TypeCode::Array => deserialize_array(buf) - .map(|v| Ok(Value::Array(v))) - .unwrap_or(Err(DeserializationError { type_code })), - TypeCode::Dictionary => deserialize_dictionary(buf) - .map(|v| Ok(Value::Dictionary(v))) - .unwrap_or(Err(DeserializationError { type_code })), - TypeCode::OperationRequest => deserialize_operation_request(buf) - .map(|v| Ok(Value::OperationRequest(v))) - .unwrap_or(Err(DeserializationError { type_code })), - TypeCode::OperationResponse => deserialize_operation_response(buf) - .map(|v| Ok(Value::OperationResponse(v))) - .unwrap_or(Err(DeserializationError { type_code })), - TypeCode::EventData => deserialize_event_data(buf) - .map(|v| Ok(Value::EventData(v))) - .unwrap_or(Err(DeserializationError { type_code })), - TypeCode::ObjectArray => deserialize_object_array(buf) - .map(|v| Ok(Value::ObjectArray(v))) - .unwrap_or(Err(DeserializationError { type_code })), - _ => Err(DeserializationError { type_code }), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn deserialize_dictionary() { - let value = vec![ - 68, 115, 115, 0, 2, 0, 8, 116, 101, 115, 116, 75, 101, 121, 49, 0, 10, 116, 101, 115, - 116, 86, 97, 108, 117, 101, 49, 0, 8, 116, 101, 115, 116, 75, 101, 121, 50, 0, 10, 116, - 101, 115, 116, 86, 97, 108, 117, 101, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::Dictionary(v) => { - return assert_eq!( - v.get("testKey1"), - Some(&Value::String("testValue1".to_owned())) - ) + fn try_from(message: (&ReliableCommand, &mut Cursor<&[u8]>)) -> Result { + let (command, cursor) = message; + let _: u8 = cursor.decode()?; + let msg_type: u8 = cursor.decode()?; + match msg_type { + 2 => { + let v = cursor.decode()?; + Ok(Message::Request(v)) } - _ => assert!(false), + 3 => { + let v = cursor.decode()?; + Ok(Message::Response(v)) + } + 4 => { + let v = cursor.decode()?; + Ok(Message::Event(v)) + } + _ => { + cursor.set_position(cursor.position() + command.msg_len as u64 - 2); + Err("Unknown message") + } + } + } +} + +pub struct Photon { + fragments: HashMap>, +} + +impl Photon { + pub fn new() -> Self { + Self { + fragments: HashMap::new(), } } - #[test] - fn deserialize_string_array() { - let value = vec![ - 121, 0, 2, 115, 0, 5, 116, 101, 115, 116, 49, 0, 5, 116, 101, 115, 116, 50, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - - match value { - Value::Array(v) => { - if let Value::String(val) = &v[0] { - assert_eq!(val, &"test1".to_owned()); + pub fn try_decode(&mut self, payload: &[u8]) -> PhotonDecodeResult> { + let mut result: Vec = vec![]; + let mut cursor = Cursor::new(payload); + for _ in 0..Decode::::decode(&mut cursor)?.command_count { + let command = Decode::::decode(&mut cursor)?; + match command { + Command::SendReliable(c) | Command::SendUnreliable(c) => { + if let Ok(message) = Message::try_from((&c, &mut cursor)) { + result.push(message); + } } - if let Value::String(val) = &v[1] { - assert_eq!(val, &"test2".to_owned()); + Command::SendReliableFragment(fragment) => { + self.fragments + .entry(fragment.sequence_number) + .or_insert(vec![]) + .push(fragment.clone()); + if let Ok(message) = self.decode_reliable_fragment(&fragment) { + result.push(message); + self.fragments.remove(&fragment.sequence_number).unwrap(); + } } - return; + _ => {} } - Value::StringArray(v) => { - return assert_eq!(vec!["test1".to_owned(), "test2".to_owned()], v) - } - _ => assert!(false), } + + Ok(result) } - #[test] - fn test_deserialize_byte() { - let value = vec![98, 6]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::Byte(v) => return assert_eq!(v, 6), - _ => assert!(false), + pub fn decode(&mut self, payload: &[u8]) -> Vec { + if let Ok(messages) = self.try_decode(payload) { + return messages; } + vec![] } - #[test] - fn deserialize_double() { - let value = vec![100, 64, 147, 74, 51, 51, 51, 51, 51, 0, 0, 0, 0, 0, 0, 0]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::Double(v) => return assert_eq!(v, 1234.55), - _ => assert!(false), - } - } - - #[test] - fn deserialize_event_data() { - let value = vec![ - 101, 100, 0, 2, 0, 115, 0, 5, 116, 101, 115, 116, 49, 1, 115, 0, 5, 116, 101, 115, 116, - 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::EventData(v) => { - assert_eq!(v.code, 100); - assert_eq!( - v.parameters.get(&0).unwrap(), - &Value::String("test1".to_owned()) - ); - return; - } - _ => assert!(false), - } - } - - #[test] - fn deserialize_float() { - let value = vec![102, 68, 154, 81, 154, 0, 0, 0]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::Float(v) => return assert_eq!(v, 1234.55), - _ => assert!(false), - } - } - - #[test] - fn deserialize_integer() { - let value = vec![105, 0, 0, 4, 210, 0, 0, 0]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::Integer(v) => return assert_eq!(v, 1234), - _ => assert!(false), - } - } - - #[test] - fn deserialize_short() { - let value = vec![107, 4, 210, 0]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::Short(v) => return assert_eq!(v, 1234), - _ => assert!(false), - } - } - - #[test] - fn deserialize_long() { - let value = vec![108, 0, 0, 0, 0, 0, 0, 4, 210, 0, 0, 0, 0, 0, 0, 0]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::Long(v) => return assert_eq!(v, 1234), - _ => assert!(false), - } - } - - #[test] - fn deserialize_integer_array() { - let value = vec![121, 0, 2, 105, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::Array(v) => { - if let Value::Integer(val) = v[0] { - assert_eq!(val, 0); + fn decode_reliable_fragment( + &mut self, + fragment: &ReliableFragment, + ) -> PhotonDecodeResult { + if let Some(fragments) = self.fragments.get(&fragment.sequence_number) { + if fragments.len() == fragment.fragment_count as usize { + let mut buf = Vec::::new(); + for fragment in fragments { + buf.extend(fragment.payload.iter()); } - if let Value::Integer(val) = v[1] { - assert_eq!(val, 1); - } - return; + let mut c = Cursor::new(&buf[..]); + return Message::try_from((&fragment.reliable_command, &mut c)); } - _ => assert!(false), } - } - - #[test] - fn deserialize_boolean() { - let value = vec![111, 1]; - let mut buf = Cursor::new(&value[..]); - - let type_code = buf.get_u8(); - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::Boolean(v) => return assert_eq!(v, true), - _ => assert!(false), - } - } - - #[test] - fn deserialize_operation_response() { - let value = vec![ - 112, 100, 0, 100, 42, 0, 2, 0, 115, 0, 5, 116, 101, 115, 116, 49, 1, 115, 0, 5, 116, - 101, 115, 116, 50, 0, 0, 0, 0, 0, 0, 0, - ]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::OperationResponse(v) => { - assert_eq!(v.code, 100); - assert_eq!(v.return_code, 100); - assert_eq!( - v.parameters.get(&1).unwrap(), - &Value::String("test2".to_owned()) - ); - return; - } - _ => assert!(false), - } - } - - #[test] - fn deserialize_operation_request() { - let value = vec![ - 113, 100, 0, 2, 0, 115, 0, 5, 116, 101, 115, 116, 49, 1, 115, 0, 5, 116, 101, 115, 116, - 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::OperationRequest(v) => { - assert_eq!(v.code, 100); - assert_eq!( - v.parameters.get(&1).unwrap(), - &Value::String("test2".to_owned()) - ); - return; - } - _ => assert!(false), - } - } - - #[test] - fn deserialize_string() { - let value = vec![ - 115, 0, 12, 116, 101, 115, 116, 95, 109, 101, 115, 115, 97, 103, 101, 0, - ]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::String(v) => return assert_eq!(&v, "test_message"), - _ => assert!(false), - } - } - - #[test] - fn deserialize_byte_array() { - let value = vec![120, 0, 0, 0, 2, 6, 7, 0]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::ByteArray(v) => { - assert_eq!(&v[0], &6); - assert_eq!(&v[1], &7); - return; - } - _ => assert!(false), - } - } - - #[test] - fn deserialize_array_dictionary() { - let value = vec![ - 121, 0, 1, 68, 105, 115, 0, 1, 0, 0, 0, 0, 0, 5, 116, 101, 115, 116, 49, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - ]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::Array(v) => { - if let Value::Dictionary(val) = &v[0] { - assert_eq!(val.get("0").unwrap(), &Value::String("test1".to_owned())); - } - return; - } - _ => assert!(false), - } - } - - #[test] - fn deserialize_array_byte_array() { - let value = vec![121, 0, 1, 120, 0, 0, 0, 4, 0, 2, 4, 8, 0, 0, 0, 0]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - - match value { - Value::Array(v) => { - if let Value::ByteArray(val) = &v[0] { - assert_eq!(val[0], 0); - assert_eq!(val[1], 2); - assert_eq!(val[2], 4); - assert_eq!(val[3], 8); - return; - } - } - _ => assert!(false), - } - } - - #[test] - fn deserialize_array_array() { - let value = vec![ - 121, 0, 1, 121, 0, 3, 105, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - ]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - match value { - Value::Array(v) => { - if let Value::Integer(val) = &v[0][0] { - assert_eq!(val, &1); - } - if let Value::Integer(val) = &v[0][1] { - assert_eq!(val, &2); - } - if let Value::Integer(val) = &v[0][2] { - assert_eq!(val, &3); - } - return; - } - _ => assert!(false), - } - } - - #[test] - fn deserialize_object_array() { - let value = vec![ - 122, 0, 2, 115, 0, 5, 116, 101, 115, 116, 49, 115, 0, 5, 116, 101, 115, 116, 50, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - let mut buf = Cursor::new(&value[..]); - let type_code = buf.get_u8(); - - let result = deserialize(type_code, &mut buf); - assert!(result.is_ok(), "Unimplemented!"); - let value = result.unwrap(); - - match value { - Value::ObjectArray(v) => { - if let Value::String(val) = &v[0] { - assert_eq!(val, &"test1".to_owned()); - } - if let Value::String(val) = &v[1] { - assert_eq!(val, &"test2".to_owned()); - } - } - _ => assert!(false), - }; + Err("Not enough information to decode the fragment") } } diff --git a/backend/lib/photon-protocol/src/types.rs b/backend/lib/photon-protocol/src/types.rs deleted file mode 100644 index 8cbcb57..0000000 --- a/backend/lib/photon-protocol/src/types.rs +++ /dev/null @@ -1,117 +0,0 @@ -use std::collections::HashMap; - -pub type Parameters = HashMap; - -pub enum TypeCode { - Unknown = 0, - Null = 42, - Dictionary = 68, - StringArray = 97, - Byte = 98, - Double = 100, - EventData = 101, - Float = 102, - Integer = 105, - Short = 107, - Long = 108, - BooleanArray = 110, - Boolean = 111, - OperationResponse = 112, - OperationRequest = 113, - String = 115, - ByteArray = 120, - Array = 121, - ObjectArray = 122, -} - -impl From for TypeCode { - fn from(v: u8) -> Self { - match v { - 0 => TypeCode::Unknown, - 42 => TypeCode::Null, - 68 => TypeCode::Dictionary, - 97 => TypeCode::StringArray, - 98 => TypeCode::Byte, - 100 => TypeCode::Double, - 101 => TypeCode::EventData, - 102 => TypeCode::Float, - 105 => TypeCode::Integer, - 107 => TypeCode::Short, - 108 => TypeCode::Long, - 110 => TypeCode::BooleanArray, - 111 => TypeCode::Boolean, - 112 => TypeCode::OperationResponse, - 113 => TypeCode::OperationRequest, - 115 => TypeCode::String, - 120 => TypeCode::ByteArray, - 121 => TypeCode::Array, - 122 => TypeCode::ObjectArray, - _ => TypeCode::Unknown - } - } -} - -#[derive(Clone, Debug, PartialEq)] -pub struct EventData { - pub code: u8, - pub parameters: Parameters -} - -#[derive(Clone, Debug, PartialEq)] -pub struct OperationResponse { - pub code: u8, - pub return_code: i16, - pub debug_message: String, - pub parameters: Parameters -} - -#[derive(Clone, Debug, PartialEq)] -pub struct OperationRequest { - pub code: u8, - pub parameters: Parameters -} - - -#[derive(Clone, Debug, PartialEq)] -pub enum Value { - None, - Dictionary(HashMap), - StringArray(Vec), - Byte(u8), - Double(f64), - EventData(EventData), - Float(f32), - Integer(u32), - Short(i16), - Long(i64), - BooleanArray(Vec), - Boolean(bool), - OperationResponse(OperationResponse), - OperationRequest(OperationRequest), - String(String), - ByteArray(Vec), - Array(Vec), - ObjectArray(Vec) -} - -impl std::ops::Index for Value { - type Output = Value; - - fn index(&self, index: usize) -> &Self::Output { - match self { - Value::Array(v) => &v[index], - _ => panic!("Non indexable type") - } - } -} - -impl std::fmt::Display for Value { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Value::String(v) => write!(f, "{}", v), - Value::Byte(v) => write!(f, "{}", v), - Value::Integer(v) => write!(f, "{}", v), - v => write!(f, "{:?}", v) - } - } -} diff --git a/backend/lib/photon-protocol/tests/decoding_tests.rs b/backend/lib/photon-protocol/tests/decoding_tests.rs new file mode 100644 index 0000000..f8b9ab1 --- /dev/null +++ b/backend/lib/photon-protocol/tests/decoding_tests.rs @@ -0,0 +1,361 @@ +use photon_protocol::*; + +use std::io::{Read, Cursor}; + +#[test] +fn deserialize_dictionary() { + let value = vec![ + 68, 115, 115, 0, 2, 0, 8, 116, 101, 115, 116, 75, 101, 121, 49, 0, 10, 116, 101, 115, + 116, 86, 97, 108, 117, 101, 49, 0, 8, 116, 101, 115, 116, 75, 101, 121, 50, 0, 10, 116, + 101, 115, 116, 86, 97, 108, 117, 101, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::Dictionary(v) => { + return assert_eq!( + v.get("testKey1"), + Some(&Value::String("testValue1".to_owned())) + ) + } + _ => assert!(false), + } +} + +#[test] +fn deserialize_string_array() { + let value = vec![ + 121, 0, 2, 115, 0, 5, 116, 101, 115, 116, 49, 0, 5, 116, 101, 115, 116, 50, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + + match value { + Value::Array(v) => { + if let Value::String(val) = &v[0] { + assert_eq!(val, &"test1".to_owned()); + } + if let Value::String(val) = &v[1] { + assert_eq!(val, &"test2".to_owned()); + } + return; + } + Value::StringArray(v) => { + return assert_eq!(vec!["test1".to_owned(), "test2".to_owned()], v) + } + _ => assert!(false), + } +} + +#[test] +fn test_deserialize_byte() { + let value = vec![98, 6]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::Byte(v) => return assert_eq!(v, 6), + _ => assert!(false), + } +} + +#[test] +fn deserialize_double() { + let value = vec![100, 64, 147, 74, 51, 51, 51, 51, 51, 0, 0, 0, 0, 0, 0, 0]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::Double(v) => return assert_eq!(v, 1234.55), + _ => assert!(false), + } +} + +#[test] +fn deserialize_event_data() { + let value = vec![ + 101, 100, 0, 2, 0, 115, 0, 5, 116, 101, 115, 116, 49, 1, 115, 0, 5, 116, 101, 115, 116, + 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::EventData(v) => { + assert_eq!(v.code, 100); + assert_eq!( + v.parameters.get(&0).unwrap(), + &Value::String("test1".to_owned()) + ); + return; + } + _ => assert!(false), + } +} + +#[test] +fn deserialize_float() { + let value = vec![102, 68, 154, 81, 154, 0, 0, 0]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::Float(v) => return assert_eq!(v, 1234.55), + _ => assert!(false), + } +} + +#[test] +fn deserialize_integer() { + let value = vec![105, 0, 0, 4, 210, 0, 0, 0]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::Integer(v) => return assert_eq!(v, 1234), + _ => assert!(false), + } +} + +#[test] +fn deserialize_short() { + let value = vec![107, 4, 210, 0]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::Short(v) => return assert_eq!(v, 1234), + _ => assert!(false), + } +} + +#[test] +fn deserialize_long() { + let value = vec![108, 0, 0, 0, 0, 0, 0, 4, 210, 0, 0, 0, 0, 0, 0, 0]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::Long(v) => return assert_eq!(v, 1234), + _ => assert!(false), + } +} + +#[test] +fn deserialize_integer_array() { + let value = vec![121, 0, 2, 105, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::Array(v) => { + if let Value::Integer(val) = v[0] { + assert_eq!(val, 0); + } + if let Value::Integer(val) = v[1] { + assert_eq!(val, 1); + } + return; + } + _ => assert!(false), + } +} + +#[test] +fn deserialize_boolean() { + let value = vec![111, 1]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::Boolean(v) => return assert_eq!(v, true), + _ => assert!(false), + } +} + +#[test] +fn deserialize_operation_response() { + let value = vec![ + 112, 100, 0, 100, 42, 0, 2, 0, 115, 0, 5, 116, 101, 115, 116, 49, 1, 115, 0, 5, 116, + 101, 115, 116, 50, 0, 0, 0, 0, 0, 0, 0, + ]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::OperationResponse(v) => { + assert_eq!(v.code, 100); + assert_eq!(v.return_code, 100); + assert_eq!( + v.parameters.get(&1).unwrap(), + &Value::String("test2".to_owned()) + ); + return; + } + _ => assert!(false), + } +} + +#[test] +fn deserialize_operation_request() { + let value = vec![ + 113, 100, 0, 2, 0, 115, 0, 5, 116, 101, 115, 116, 49, 1, 115, 0, 5, 116, 101, 115, 116, + 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::OperationRequest(v) => { + assert_eq!(v.code, 100); + assert_eq!( + v.parameters.get(&1).unwrap(), + &Value::String("test2".to_owned()) + ); + return; + } + _ => assert!(false), + } +} + +#[test] +fn deserialize_string() { + let value = vec![ + 115, 0, 12, 116, 101, 115, 116, 95, 109, 101, 115, 115, 97, 103, 101, 0, + ]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::String(v) => return assert_eq!(&v, "test_message"), + _ => assert!(false), + } +} + +#[test] +fn deserialize_byte_array() { + let value = vec![120, 0, 0, 0, 2, 6, 7, 0]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::ByteArray(v) => { + assert_eq!(&v[0], &6); + assert_eq!(&v[1], &7); + return; + } + _ => assert!(false), + } +} + +#[test] +fn deserialize_array_dictionary() { + let value = vec![ + 121, 0, 1, 68, 105, 115, 0, 1, 0, 0, 0, 0, 0, 5, 116, 101, 115, 116, 49, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + ]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::Array(v) => { + if let Value::Dictionary(val) = &v[0] { + assert_eq!(val.get("0").unwrap(), &Value::String("test1".to_owned())); + } + return; + } + _ => assert!(false), + } +} + +#[test] +fn deserialize_array_byte_array() { + let value = vec![121, 0, 1, 120, 0, 0, 0, 4, 0, 2, 4, 8, 0, 0, 0, 0]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + + match value { + Value::Array(v) => { + if let Value::ByteArray(val) = &v[0] { + assert_eq!(val[0], 0); + assert_eq!(val[1], 2); + assert_eq!(val[2], 4); + assert_eq!(val[3], 8); + return; + } + } + _ => assert!(false), + } +} + +#[test] +fn deserialize_array_array() { + let value = vec![ + 121, 0, 1, 121, 0, 3, 105, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + ]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + match value { + Value::Array(v) => { + if let Value::Integer(val) = &v[0][0] { + assert_eq!(val, &1); + } + if let Value::Integer(val) = &v[0][1] { + assert_eq!(val, &2); + } + if let Value::Integer(val) = &v[0][2] { + assert_eq!(val, &3); + } + return; + } + _ => assert!(false), + } +} + +#[test] +fn deserialize_object_array() { + let value = vec![ + 122, 0, 2, 115, 0, 5, 116, 101, 115, 116, 49, 115, 0, 5, 116, 101, 115, 116, 50, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + let mut buf = Cursor::new(&value[..]); + let result = buf.decode(); + assert!(result.is_ok(), "Unimplemented!"); + let value = result.unwrap(); + + match value { + Value::ObjectArray(v) => { + if let Value::Object(val) = &*v[0] { + assert_eq!(**val, Value::String("test1".to_owned())); + } + if let Value::Object(val) = &*v[1] { + assert_eq!(**val, Value::String("test2".to_owned())); + } + } + _ => assert!(false), + }; +} \ No newline at end of file diff --git a/backend/lib/photon-protocol/tests/integration_tests.rs b/backend/lib/photon-protocol/tests/integration_tests.rs new file mode 100644 index 0000000..e0694a6 --- /dev/null +++ b/backend/lib/photon-protocol/tests/integration_tests.rs @@ -0,0 +1,277 @@ +use photon_protocol; + +use photon_protocol::Message; +use photon_protocol::EventData; +use photon_protocol::OperationRequest; +use photon_protocol::OperationResponse; +use photon_protocol::Value; +use photon_protocol::Parameters; + +#[test] +fn test_single_event_message() +{ + let header = vec![ + 0x00, 0x01, // PeerID + 0x01, // CrcEnabled + 0x01, // CommandCount + 0x00, 0x00, 0x00, 0x01, // Timestamp + 0x00, 0x00, 0x00, 0x01, // Challenge + ]; + + let photon_command = vec![ + 0x06, // Type + 0x01, // ChannelID + 0x01, // Flags + 0x04, // ReservedByte + 0x00, 0x00, 0x00, 0x1a, // Length + 0x00, 0x00, 0x00, 0x01, // ReliableSequenceNumber + ]; + + let message = vec![ + 0x01, // ?? + 0x04, // MsgType (Event) + // Payload + 0x64, 0x00, 0x02, // Key + 0x00, 0x73, // String type + 0x00, 0x05, // String length + 0x74, 0x65, 0x73, 0x74, 0x31 //test1 + ]; + + let mut photon = photon_protocol::Photon::new(); + + let decoded = photon.decode( + &[&header[..], &photon_command[..], &message[..]].concat()); + + assert!(decoded.len() == 1); + let parameters: Parameters = + [(0, Value::String("test1".to_owned()))] + .iter().cloned().collect(); + assert_eq!(decoded[0], Message::Event(EventData{ code: 100, parameters})); +} + +#[test] +fn test_fragmented_event_message() +{ + let header = vec![ + 0x00, 0x01, // PeerID + 0x01, // CrcEnabled + 0x01, // CommandCount + 0x00, 0x00, 0x00, 0x01, // Timestamp + 0x00, 0x00, 0x00, 0x01, // Challenge + ]; + + let mut photon = photon_protocol::Photon::new(); + + let photon_command = vec![ + 0x08, // Type + 0x01, // ChannelID + 0x01, // Flags + 0x04, // ReservedByte + 0x00, 0x00, 0x00, 0x22, // Length + 0x00, 0x00, 0x00, 0x01, // ReliableSequenceNumber + 0x00, 0x00, 0x00, 0x01, // SequenceNumber + 0x00, 0x00, 0x00, 0x03, // FragmentCount + 0x00, 0x00, 0x00, 0x01, // FragmentNumber + 0x00, 0x00, 0x00, 0x1a, // TotalLength + 0x00, 0x00, 0x00, 0x01, // OperationLength + ]; + + let message = vec![ + 0x01, // ?? + 0x04, // MsgType (Event) + // Payload + ]; + + let decoded = photon.decode( + &[&header[..], &photon_command[..], &message[..]].concat()); + assert!(decoded.len() == 0); + + let photon_command = vec![ + 0x08, // Type + 0x01, // ChannelID + 0x01, // Flags + 0x04, // ReservedByte + 0x00, 0x00, 0x00, 0x27, // Length + 0x00, 0x00, 0x00, 0x01, // ReliableSequenceNumber + 0x00, 0x00, 0x00, 0x01, // SequenceNumber + 0x00, 0x00, 0x00, 0x03, // FragmentCount + 0x00, 0x00, 0x00, 0x02, // FragmentNumber + 0x00, 0x00, 0x00, 0x1a, // TotalLength + 0x00, 0x00, 0x00, 0x01, // OperationLength + ]; + + let message = vec![ + // Payload + 0x64, 0x00, 0x02, // Key + 0x00, 0x73, // String type + 0x00, 0x05, // String length + ]; + + let decoded = photon.decode( + &[&header[..], &photon_command[..], &message[..]].concat()); + assert!(decoded.len() == 0); + + let photon_command = vec![ + 0x08, // Type + 0x01, // ChannelID + 0x01, // Flags + 0x04, // ReservedByte + 0x00, 0x00, 0x00, 0x25, // Length + 0x00, 0x00, 0x00, 0x01, // ReliableSequenceNumber + 0x00, 0x00, 0x00, 0x01, // SequenceNumber + 0x00, 0x00, 0x00, 0x03, // FragmentCount + 0x00, 0x00, 0x00, 0x03, // FragmentNumber + 0x00, 0x00, 0x00, 0x1a, // TotalLength + 0x00, 0x00, 0x00, 0x01, // OperationLength + ]; + + let message = vec![ + 0x74, 0x65, 0x73, 0x74, 0x31 //test1 + ]; + + let decoded = photon.decode( + &[&header[..], &photon_command[..], &message[..]].concat()); + assert_eq!(decoded.len(), 1); + + let parameters: Parameters = + [(0, Value::String("test1".to_owned()))] + .iter().cloned().collect(); + assert_eq!(decoded[0], Message::Event(EventData{ code: 100, parameters})); +} + + +#[test] +fn test_two_event_messages() +{ + let payload = vec![ + 0x00, 0x00, + 0x00, + 0x02, + 0x72, 0xe9, 0xe2, 0x84, + 0x11, 0x63, 0x88, 0x88, + + 0x07, + 0x00, + 0x00, + 0x00, + 0x00, 0x00, 0x00, 0x45, + 0x00, 0x00, 0x16, 0x8e, + 0x00, 0x00, 0x45, 0x2b, + 0xf3, 0x04, 0x02, 0x00, 0x02, 0x00, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa, 0xb7, 0x36, 0x01, 0x78, 0x00, 0x00, 0x00, 0x20, 0x03, 0x6b, 0xc9, 0x04, 0xc1, 0xe2, 0x62, 0xd7, 0x08, 0x6b, 0xb0, 0x91, 0xc1, 0x2a, 0x80, 0x1b, 0xc2, 0x26, 0x00, 0x00, 0xb0, 0x40, 0xd8, 0xe6, 0x53, 0xc1, 0x8f, 0xcd, 0xc, 0xc2, 0x00, 0x00, + + 0x06, + 0x00, + 0x01, + 0x00, + 0x00, 0x00, 0x00, 0x1b, + 0x00, 0x00, 0x16, 0x8f, + 0xf3, 0x04, 0x01, 0x00, 0x02, 0x00, 0x69, 0x00, 0xa, 0xf6, 0xdf, 0xfc, 0x6b, 0x00, 0x01 + ]; + + let mut photon = photon_protocol::Photon::new(); + + let decoded = photon.decode(&payload); + + assert!(decoded.len() == 2); + let parameters: Parameters = + [ + (0x01, Value::ByteArray(vec![ + 3, 107, 201, 4, 193, 226, 98, 215, 8, 107, 176, 145, 193, + 42, 128, 27, 194, 38, 0, 0, 176, 64, 216, 230, 83, 193, + 143, 205, 12, 194, 0, 0])), + (0x00, Value::Long(702262)) + ] + .iter().cloned().collect(); + assert_eq!(decoded[0], Message::Event(EventData{ code: 2, parameters})); + + let parameters: Parameters = + [ + (0x00, Value::Integer(718559)), + (0xfc, Value::Short(1)) + ] + .iter().cloned().collect(); + assert_eq!(decoded[1], Message::Event(EventData{ code: 1, parameters})); + +} + +#[test] +fn test_request_message() +{ + let payload = vec![ + 0x7d, 0xd3, + 0x00, + 0x01, + 0x00, 0x04, 0xcc, 0xb6, + 0x11, 0x63, 0x88, 0x88, + + 0x06, + 0x00, + 0x01, + 0x04, + 0x00, 0x00, 0x00, 0x2a, + 0x00, 0x00, 0x00, 0x19, + 0xf3, 0x02, 0x01, 0x00, 0x03, 0x00, + 0x79, 0x00, 0x02, 0x66, 0xc1, 0xd3, 0x61, 0x20, 0xc2, 0x27, 0xc, 0xcd, 0x01, 0x62, + 0x00, 0xfd, // key + 0x73, // String type + 0x00, 0x05, // String length + 0x74, 0x65, 0x73, 0x74, 0x31 // test1 + ]; + + let mut photon = photon_protocol::Photon::new(); + let decoded = photon.decode(&payload); + + assert!(decoded.len() == 1); + let parameters: Parameters = + [ + (0x00, Value::Array(vec![Value::Float(-26.422424), Value::Float(-41.7625)])), + (0x01, Value::Byte(0)), + (0xfd, Value::String("test1".to_owned())) + + ] + .iter().cloned().collect(); + assert_eq!(decoded[0], Message::Request(OperationRequest { code: 1, parameters})); +} + +#[test] +fn test_response_message() +{ + let payload = vec![ + 0x00, 0x00, + 0x00, + 0x02, + 0x72, 0xea, 0x1d, 0x6a, + 0x11, 0x63, 0x88, 0x88, + + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, 0x00, 0x00, 0x14, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x24, 0x00, 0x04, 0xd7, 0x1a, + + 0x06, + 0x00, + 0x01, + 0x00, + 0x00, 0x00, 0x00, 0xb2, + 0x00, 0x00, 0x17, 0x71, + 0xf3, 0x03, 0x01, 0x00, 0x00, 0x2a, 0x00, 0xa, 0x00, 0x69, 0x18, 0xf2, 0x79, 0x68, 0x01, 0x73, 0x00, 0x5d, 0x40, 0x49, 0x53, 0x4c, 0x41, 0x4e, 0x44, 0x40, 0x65, 0x66, 0x33, 0x37, 0x39, 0x34, 0x64, 0x61, 0x2d, 0x38, 0x66, 0x38, 0x33, 0x2d, 0x34, 0x33, 0x34, 0x30, 0x2d, 0x62, 0x66, 0x35, 0x32, 0x2d, 0x36, 0x38, 0x31, 0x31, 0x37, 0x61, 0x30, 0x36, 0x37, 0x32, 0x65, 0x34, 0x7c, 0x57, 0x65, 0x64, 0x72, 0x6f, 0x77, 0x79, 0x63, 0x7a, 0x4a, 0x61, 0x6b, 0x75, 0x62, 0x7c, 0x36, 0x33, 0x37, 0x30, 0x37, 0x35, 0x33, 0x37, 0x38, 0x38, 0x30, 0x33, 0x31, 0x38, 0x33, 0x39, 0x33, 0x35, 0x7c, 0x57, 0x65, 0x64, 0x72, 0x6f, 0x77, 0x79, 0x63, 0x7a, 0x4a, 0x61, 0x6b, 0x75, 0x62, 0x02, 0x79, 0x00, 0x00, 0x78, 0x03, 0x79, 0x00, 0x00, 0x73, 0x04, 0x79, 0x00, 0x00, 0x73, 0x05, 0x78, 0x00, 0x00, 0x00, 0x00, 0x06, 0x79, 0x00, 0x01, 0x79, 0x00, 0x01, 0x69, 0xff, 0xff, 0xff, 0xff, 0x07, 0x79, 0x00, 0x01, 0x79, 0x00, 0x01, 0x69, 0xff, 0xff, 0xff, 0xff, 0x08, 0x78, 0x00, 0x00, 0x00, 0x00, 0xfd, 0x6b, 0x00, 0xa6 + ]; + + let mut photon = photon_protocol::Photon::new(); + + let decoded = photon.decode(&payload); + + assert_eq!(decoded.len(), 1); + let parameters: Parameters = + [ + (0x00, Value::Integer(418543976)), + (0x01, Value::String("@ISLAND@ef3794da-8f83-4340-bf52-68117a0672e4|WedrowyczJakub|637075378803183935|WedrowyczJakub".to_owned())) + + ] + .iter().cloned().collect(); + assert_eq!(decoded[0], Message::Response(OperationResponse { code: 1, return_code: 0, debug_message: "None".to_owned(), parameters})); +} + diff --git a/backend/src/core.rs b/backend/src/core.rs index 4dd4b3b..05f1cbd 100644 --- a/backend/src/core.rs +++ b/backend/src/core.rs @@ -8,6 +8,9 @@ use simplelog::*; use packet_sniffer::UdpPacket; +use photon_protocol; +use photon_protocol::Photon; + use crate::game_protocol; use crate::meter; pub use meter::GameStats; @@ -78,6 +81,8 @@ pub fn initialize() -> Arc> { thread::spawn(move || { let (tx, rx): (Sender, Receiver) = channel(); + let mut photon = Photon::new(); + packet_sniffer::receive(tx); info!("Listening to network packets..."); loop { @@ -86,9 +91,9 @@ pub fn initialize() -> Arc> { continue; } let meter = &mut cloned_meter.lock().unwrap(); - if let Some(messages) = game_protocol::decode(&packet.payload) { - register_messages(meter, &messages); - } + let game_messages = photon.decode(&packet.payload) + .into_iter().filter_map(into_game_message).collect(); + register_messages(meter, &game_messages); } } }); @@ -96,7 +101,7 @@ pub fn initialize() -> Arc> { meter } -fn register_messages(meter: &mut meter::Meter, messages: &Vec) { +pub fn register_messages(meter: &mut meter::Meter, messages: &Vec) { messages .iter() .for_each(|message| register_message(meter, &message)); @@ -136,6 +141,31 @@ fn register_message(events: &mut meter::Meter, message: &game_protocol::Message) } } +fn into_game_message(photon_message : photon_protocol::Message) -> Option +{ + static REQUEST_CONSTANT: usize = 10000; + static RESPONSE_CONSTANT: usize = 1000; + + match photon_message { + photon_protocol::Message::Event(e) => { + if e.code != 2 && e.parameters.get(&252u8).is_some() { + if let photon_protocol::Value::Short(event_code) = e.parameters.get(&252u8).unwrap() { + return game_protocol::Packet{code: *event_code as usize, parameters: e.parameters}.decode() + } + } + game_protocol::Packet{code: 0, parameters: e.parameters} + }, + photon_protocol::Message::Request(r) => { + let code = r.code as usize + REQUEST_CONSTANT; + game_protocol::Packet{code, parameters: r.parameters} + }, + photon_protocol::Message::Response(r) => { + let code = r.code as usize + RESPONSE_CONSTANT; + game_protocol::Packet{code, parameters: r.parameters} + } + }.decode() +} + #[cfg(test)] mod tests { use super::*; diff --git a/backend/src/game_protocol/message.rs b/backend/src/game_protocol/message.rs index a40bdf3..c36e348 100644 --- a/backend/src/game_protocol/message.rs +++ b/backend/src/game_protocol/message.rs @@ -334,6 +334,8 @@ pub enum Message { impl Packet { pub fn decode(self) -> Option { + debug!("Decode: {:?}", &self); + match self.code { 1 => Leave::encode(self.parameters), 6 => HealthUpdate::encode(self.parameters), diff --git a/backend/src/game_protocol/mod.rs b/backend/src/game_protocol/mod.rs index 8dfdbeb..c7114c6 100644 --- a/backend/src/game_protocol/mod.rs +++ b/backend/src/game_protocol/mod.rs @@ -1,6 +1,5 @@ mod packet; -mod protocol; pub mod message; -pub use protocol::decode; pub use message::Message; +pub use packet::Packet;