Skip to content

Commit

Permalink
(feat): Add packet passing from Client <-> GroupServer
Browse files Browse the repository at this point in the history
  • Loading branch information
Perseus committed Feb 25, 2024
1 parent 6843a31 commit c9091ed
Show file tree
Hide file tree
Showing 15 changed files with 595 additions and 157 deletions.
14 changes: 14 additions & 0 deletions common_utils/src/network/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,12 @@ pub struct RPCManager {
logger: Logger,
}

impl Drop for RPCManager {
fn drop(&mut self) {
self.logger.debug("RPCManager dropped");
}
}

impl RPCManager {
pub fn new(rpc_send_tx: mpsc::Sender<BasePacket>) -> Self {
RPCManager {
Expand Down Expand Up @@ -148,6 +154,14 @@ impl RPCManager {
rpc_call.finished_notification.notify_one();

return Ok(());
} else {
self.logger.debug(
format!(
"[sess_id={}] Received RPC reply for unknown session id",
session_id
)
.as_str(),
);
}
}

Expand Down
8 changes: 1 addition & 7 deletions common_utils/src/network/tcp_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,7 @@ impl TcpClient {
}
}

pub async fn connect<HandlerType, ApplicationContextType, CommandChannelType>(
&mut self,
retry_interval_in_secs: u64,
) -> anyhow::Result<TcpStream>
where
HandlerType: ConnectionHandler<ApplicationContextType, CommandChannelType>,
{
pub async fn connect(&mut self, retry_interval_in_secs: u64) -> anyhow::Result<TcpStream> {
loop {
match TcpStream::connect(format!("{}:{}", self.target_ip, self.target_port)).await {
Ok(stream) => {
Expand Down
16 changes: 16 additions & 0 deletions common_utils/src/network/tcp_connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,15 @@ pub struct TcpConnection<T> {

const MAX_PACKET_SIZE: usize = 8192;

impl<T> Drop for TcpConnection<T> {
fn drop(&mut self) {
self.logger.info(&format!(
"Dropping connection for {}.{}",
self.connection_type, self.id
));
}
}

impl<T> TcpConnection<T> {
pub fn new(
id: u32,
Expand Down Expand Up @@ -192,10 +201,12 @@ impl<T> TcpConnection<T> {


let packet = BasePacket::parse_frame(&mut buffer, n).unwrap();
logger.debug("Received packet from connection");
let mut rpc_mgr = rpc_mgr.lock().await;

let is_for_rpc = rpc_mgr.check_packet_for_rpc_response(&packet).await;
if is_for_rpc {
logger.debug("packet is for rpc");
if let Ok(()) = rpc_mgr.handle_rpc_reply(packet).await {
buffer.advance(n);
continue;
Expand All @@ -205,6 +216,7 @@ impl<T> TcpConnection<T> {
}

buffer.advance(n);

data_recv_tx.send(packet).await.unwrap();
}
}
Expand Down Expand Up @@ -252,6 +264,10 @@ impl<T> TcpConnection<T> {

pub async fn close(&mut self, delay_in_ms: Duration) {
tokio::time::sleep(delay_in_ms).await;
self.logger.info(&format!(
"Closing connection for {}.{}",
self.connection_type, self.id
));
self.cancellation_token.cancel();
}

Expand Down
2 changes: 0 additions & 2 deletions common_utils/src/network/tcp_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ impl TcpServer {
),
};

println!("started server at port at {:?}", connect_addr);

loop {
let (socket, socket_addr) = server.accept().await?;
client_comm_channel_tracker_tx.send(socket).await.unwrap();
Expand Down
12 changes: 12 additions & 0 deletions common_utils/src/packet/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ use num_enum::{IntoPrimitive, TryFromPrimitive};
pub enum Command {
None,

// Client to GameServer
// CTGMBeginAction = 6,

// Client to GateServer
CTGTLogin = 431,
CTGTSelectCharacter = 433,
Expand All @@ -29,11 +32,20 @@ pub enum Command {

// GameServer to GateServer
GMTGTInit = 1501,
GMTGTMapEntry = 1506,

// GateServer to GameServer
GTTGMPlayerLeaveMap = 1004,
GTTGMInitAcknowledge = 1005,
GTTGMMapEntry = 1007,
GTTGMPlayerEnterMap = 1003,
GTTGMKickCharacter = 1009,

// GameServer to GroupServer
GMTGPPlayerEnterMap = 5501,

// Client to GroupServer
CTGPPing = 6020,
}

impl Display for Command {
Expand Down
31 changes: 21 additions & 10 deletions common_utils/src/packet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,10 +237,15 @@ impl BasePacket {
/// Removes all bytes in the range from the buffer
/// RESETS THE OFFSET
pub fn remove_range(&mut self, range: std::ops::Range<usize>) {
// we don't allow removing bytes before the data
if range.start < 8 {
return;
}

let mut remaining_bytes = self.data.split_off(range.start);
let end_bytes = remaining_bytes.split_off(range.end - range.start);
self.data.unsplit(end_bytes);
self.offset = 0;
self.offset = 8;

self.set_len(self.data.len() as u16);
}
Expand All @@ -258,21 +263,27 @@ impl BasePacket {
}

pub fn inspect_with_logger(&self, logger: &Logger) {
logger.debug("------ Inspected Packet -------");
logger.debug(format!("[Packet] Size: {}", self.size).as_str());
logger.debug(format!("[Packet] Header: {:?}", self.data.get(2..6)).as_str());
logger.debug(format!("[Packet] Command: {:?}", self.data.get(6..8)).as_str());
logger.debug(format!("[Packet] Data: {:?}", self.data.get(8..self.size as usize)).as_str());
logger.debug(format!("[Packet] Offset: {:?}", self.offset).as_str());
logger.debug(format!("[Packet] Reverse Offset: {:?}", self.reverse_offset).as_str());
logger.debug("-------------------------------");
logger.debug(
&format!(
"------ Inspected Packet -------\n\t\t\t\t\t[Packet] Size: {}\n\t\t\t\t\t[Packet] Header: {:?}\n\t\t\t\t\t[Packet] Command: {:?}\n\t\t\t\t\t[Packet] Raw Command: {}\n\t\t\t\t\t[Packet] Data: {:?}\n\t\t\t\t\t[Packet] Offset: {:?}\n\t\t\t\t\t[Packet] Reverse Offset: {:?}\n\t\t\t\t\t-------------------------------",
self.size,
self.data.get(2..6),
self.data.get(6..8),
self.raw_cmd,
self.data.get(8..self.size as usize),
self.offset,
self.reverse_offset

)
);
}

pub fn inspect(&self) {
println!("------ Inspected Packet -------");
println!("[Packet] Size: {}", self.size);
println!("[Packet] Header: {:?}", self.data.get(2..6));
println!("[Packet] Command: {:?}", self.data.get(6..8));
println!("[Packet] Raw Command: {}", self.raw_cmd);
println!("[Packet] Data: {:?}", self.data.get(8..self.size as usize));
println!("[Packet] Offset: {:?}", self.offset);
println!("[Packet] Reverse Offset: {:?}", self.reverse_offset);
Expand Down Expand Up @@ -306,7 +317,6 @@ impl PacketReader for BasePacket {

return Some(command);
} else {
println!("Unknown command -> {}", primitive_command);
self.increment_offset::<u16>();
self.cmd = Command::None;

Expand Down Expand Up @@ -647,6 +657,7 @@ impl PacketWriter for BasePacket {

self.data = byte_buffer;
self.is_built = true;
self.size = size;

Ok(())
}
Expand Down
106 changes: 55 additions & 51 deletions common_utils/src/parser/config_parser.rs
Original file line number Diff line number Diff line change
@@ -1,72 +1,76 @@
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::env::current_dir;
use std::fs;
use std::path::Path;
use serde::{Serialize, Deserialize};
use serde::de::DeserializeOwned;

#[derive(Debug, Serialize, Deserialize)]
pub struct ConfigParser<T> {
data: T
data: T,
}

impl<T> ConfigParser<T> {
pub fn parse_file(file_path: &Path) -> Self
where
T: DeserializeOwned {
let contents = match fs::read_to_string (file_path) {
Ok(contents) => contents,
Err(err) => panic!("Could not find config file at {:?}, error - {}", file_path, err)
};
pub fn parse_file(file_path: &Path) -> Self
where
T: DeserializeOwned,
{
println!("{:?} {:?}", current_dir(), file_path);
let contents = match fs::read_to_string(file_path) {
Ok(contents) => contents,
Err(err) => panic!(
"Could not find config file at {:?}, error - {}",
file_path, err
),
};

let data: T = match serde_yaml::from_str(&contents) {
Ok(yaml) => yaml,
Err(err) => panic!("Unable to parse the YAML config, err - {}", err)
};
let data: T = match serde_yaml::from_str(&contents) {
Ok(yaml) => yaml,
Err(err) => panic!("Unable to parse the YAML config, err - {}", err),
};

let config_parser: ConfigParser<T> = ConfigParser {
data
};
let config_parser: ConfigParser<T> = ConfigParser { data };

config_parser
}
config_parser
}

pub fn get_data(self) -> T {
self.data
}
pub fn get_data(self) -> T {
self.data
}
}


#[cfg(test)]
mod tests {
use std::path::Path;
use std::path::Path;

use super::ConfigParser;
use super::ConfigParser;

use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct ConfigStructure {
name: String,
id: u64
}

#[test]
#[should_panic]
fn it_throws_an_error_if_file_doesnt_exist() {
ConfigParser::<ConfigStructure>::parse_file(Path::new("./tests/yada.yml"));
}
#[derive(Serialize, Deserialize)]
struct ConfigStructure {
name: String,
id: u64,
}

#[test]
#[should_panic]
fn it_throws_an_error_if_the_file_is_not_valid_yaml() {
ConfigParser::<ConfigStructure>::parse_file(Path::new("./tests/invalid_yaml.yml"));
}
#[test]
#[should_panic]
fn it_throws_an_error_if_file_doesnt_exist() {
ConfigParser::<ConfigStructure>::parse_file(Path::new("./tests/yada.yml"));
}

#[test]
fn it_parses_a_valid_yml_file_correctly() {
let contents = ConfigParser::<ConfigStructure>::parse_file(Path::new("./tests/valid_yaml.yml"));
let data = contents.get_data();

assert_eq!(data.id, 5);
assert_eq!(data.name, "This is the name");
}
}
#[test]
#[should_panic]
fn it_throws_an_error_if_the_file_is_not_valid_yaml() {
ConfigParser::<ConfigStructure>::parse_file(Path::new("./tests/invalid_yaml.yml"));
}

#[test]
fn it_parses_a_valid_yml_file_correctly() {
let contents =
ConfigParser::<ConfigStructure>::parse_file(Path::new("./tests/valid_yaml.yml"));
let data = contents.get_data();

assert_eq!(data.id, 5);
assert_eq!(data.name, "This is the name");
}
}
23 changes: 23 additions & 0 deletions config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
main:
name: "GateServer2"

client_config:
ip: "127.0.0.1"
ddos_protection: true
max_connections: 500
max_login_per_ip: 50
ping_duration: 180
port: 1973
wpe_protection: true
wpe_version: 30

group_config:
ip: "172.24.80.1"
port: 1975
ping_duration: 180

game_server_config:
ip: "127.0.0.1"
port: 3002
ping_duration: 180

Loading

0 comments on commit c9091ed

Please sign in to comment.