Skip to content

Commit

Permalink
Small fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
artemijan committed Dec 15, 2024
1 parent 0ed741c commit 692e556
Show file tree
Hide file tree
Showing 16 changed files with 71 additions and 63 deletions.
20 changes: 11 additions & 9 deletions src/game_server/dto/config.rs → src/common/config/gs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,22 +36,14 @@ pub struct GSServer {
#[serde(default)]
pub ip_config: Vec<ServerHost>,
}
impl GSServer {
pub fn get_hosts(&self) -> Vec<String> {
self.ip_config
.iter()
.flat_map(|h| vec![h.subnet.to_string(), h.ip.to_string()])
.collect()
}
}

fn deserialize_hex_to_bigint<'de, D>(deserializer: D) -> Result<BigInt, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
BigInt::from_str_radix(&s, 16).map_err(Error::custom)
}

fn deserialize_server_type<'de, D>(deserializer: D) -> Result<ServerType, D::Error>
where
D: Deserializer<'de>,
Expand All @@ -60,6 +52,15 @@ where
ServerType::from_str(&s).map_err(Error::custom)
}

impl GSServer {
pub fn get_hosts(&self) -> Vec<String> {
self.ip_config
.iter()
.flat_map(|h| vec![h.subnet.to_string(), h.ip.to_string()])
.collect()
}
}

impl GSServer {
fn auto_ip_config(&mut self) {
// Get all network interfaces
Expand Down Expand Up @@ -94,6 +95,7 @@ impl GSServer {
}
}
}

impl ServerConfig for GSServer {
fn load(file_name: &str) -> Self {
let file = File::open(file_name)
Expand Down
22 changes: 12 additions & 10 deletions src/login_server/dto/config.rs → src/common/config/login.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
use crate::common::dto::{Database, InboundConnection, Runtime};
use crate::common::traits::ServerConfig;
use num::{BigInt, Num};
use num::BigInt;
use num_traits::Num;
use serde::de::Error;
use serde::{Deserialize, Deserializer};
use std::fs::File;
use std::io::BufReader;
use tracing::info;

#[derive(Debug, Clone, Deserialize)]
pub struct Server {
pub struct LoginServer {
pub name: String,
pub blowfish_key: String,
pub runtime: Option<Runtime>,
Expand All @@ -20,19 +21,19 @@ pub struct Server {
pub client: Client,
}

impl ServerConfig for Server {
impl ServerConfig for LoginServer {
fn load(file_name: &str) -> Self {
let file = File::open(file_name)
.unwrap_or_else(|e| panic!("Failed to open config file: {file_name}. Error: {e}"));
let reader = BufReader::new(file);
let config: Server = serde_yaml::from_reader(reader).unwrap_or_else(|e| {
let config: LoginServer = serde_yaml::from_reader(reader).unwrap_or_else(|e| {
panic!("Unable to parse {file_name}, the format is incorrect, {e}")
});
info!("Configuration ok, starting application: {}", config.name);
config
}
fn from_string(conf: &str) -> Self {
serde_yaml::from_str::<Server>(conf)
serde_yaml::from_str::<LoginServer>(conf)
.unwrap_or_else(|e| panic!("Unable to parse {conf}, the format is incorrect, {e}"))
}

Expand All @@ -43,6 +44,7 @@ impl ServerConfig for Server {
&self.database
}
}

// Custom deserialization function to validate that all keys in the HashMap are valid hex strings
fn validate_allowed_gs_keys<'de, D>(deserializer: D) -> Result<Option<Vec<BigInt>>, D::Error>
where
Expand Down Expand Up @@ -70,11 +72,6 @@ where
Ok(None)
}

#[derive(Debug, Clone, Deserialize)]
pub struct GSMessages {
pub timeout: u8,
}

#[derive(Debug, Clone, Deserialize)]
pub struct GSListener {
pub connection: InboundConnection,
Expand All @@ -98,3 +95,8 @@ pub struct Client {
pub show_licence: bool,
pub enable_cmdline_login: bool,
}

#[derive(Debug, Clone, Deserialize)]
pub struct GSMessages {
pub timeout: u8,
}
4 changes: 4 additions & 0 deletions src/common/config/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/// All config DTO must be inside common module,
/// as they might be shared between components as arguments
pub mod gs;
pub mod login;
1 change: 1 addition & 0 deletions src/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub mod str;
#[cfg(test)]
pub mod tests;
pub mod traits;
pub mod config;

pub async fn hash_password(password: &str) -> anyhow::Result<String> {
let pwd = password.to_owned();
Expand Down
20 changes: 18 additions & 2 deletions src/common/packets/gs_2_ls/gs_status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ use crate::common::packets::common::{GSStatus, ReadablePacket, SendablePacket};
use crate::common::packets::read::ReadablePacketBuffer;
use crate::common::packets::write::SendablePacketBuffer;
use crate::common::traits::handlers::PacketHandler;
use crate::common::config::gs::GSServer;

#[derive(Clone, Debug, Default)]
pub struct GSStatusUpdate {
pub buffer: SendablePacketBuffer,
buffer: SendablePacketBuffer,
pub status: GSStatus,
pub use_square_brackets: bool,
pub max_players: u32,
Expand All @@ -20,7 +21,22 @@ impl GSStatusUpdate {
const MAX_PLAYERS: i32 = 0x04;
const TEST_SERVER: i32 = 0x05;
const SERVER_AGE: i32 = 0x06;

pub fn new(cfg: &GSServer) -> anyhow::Result<Self> {
let mut inst = Self {
buffer: SendablePacketBuffer::new(),
status: if cfg.gm_only {
GSStatus::GmOnly
} else {
GSStatus::Auto
},
use_square_brackets: cfg.use_brackets,
max_players: cfg.max_players,
server_type: cfg.server_type as i32,
server_age: cfg.server_age,
};
inst.write_all()?;
Ok(inst)
}
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
pub fn write_all(&mut self) -> Result<(), anyhow::Error> {
self.buffer.write(0x06)?;
Expand Down
2 changes: 1 addition & 1 deletion src/game_server/controller.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::common::traits::IpBan;
use crate::game_server::dto::config::GSServer;
use std::sync::Arc;
use crate::common::config::gs::GSServer;

#[derive(Clone, Debug)]
pub struct Controller {
Expand Down
1 change: 0 additions & 1 deletion src/game_server/dto/mod.rs

This file was deleted.

2 changes: 1 addition & 1 deletion src/game_server/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::common::traits::Shutdown;
use crate::crypt::login::Encryption;
use crate::database::DBPool;
use crate::game_server::controller::Controller;
use crate::game_server::dto::config::GSServer;
use crate::common::config::gs::GSServer;
use crate::game_server::lsp_factory::build_ls_packet;
use anyhow::{bail, Error};
use std::sync::Arc;
Expand Down
3 changes: 1 addition & 2 deletions src/game_server/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use crate::common::traits::server::Server;
use crate::game_server::controller::Controller;
use crate::game_server::dto::config::GSServer;
use crate::common::config::gs::GSServer;
pub mod lsp_factory;
pub mod dto;
pub mod controller;
pub mod handlers;
pub mod packets;
Expand Down
20 changes: 4 additions & 16 deletions src/game_server/packets/handleable/gs_auth_response.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use async_trait::async_trait;
use tracing::{info, instrument};
use crate::common::packets::common::GSStatus;
use crate::common::packets::error::PacketRun;
use crate::common::packets::gs_2_ls::{GSStatusUpdate, PlayerInGame};
Expand All @@ -9,11 +7,13 @@ use crate::{
common::packets::{common::HandleablePacket, ls_2_gs},
game_server::handlers::LoginHandler,
};
use async_trait::async_trait;
use tracing::{info, instrument};

#[async_trait]
impl HandleablePacket for ls_2_gs::AuthGS {
type HandlerType = LoginHandler;

#[instrument(skip_all)]
async fn handle(&self, lh: &mut Self::HandlerType) -> Result<(), PacketRun> {
let controller = lh.get_controller();
Expand All @@ -26,19 +26,7 @@ impl HandleablePacket for ls_2_gs::AuthGS {
)),
});
}
let mut gsu = GSStatusUpdate {
buffer: SendablePacketBuffer::new(),
status: if cfg.gm_only {
GSStatus::GmOnly
} else {
GSStatus::Auto
},
use_square_brackets: cfg.use_brackets,
max_players: cfg.max_players,
server_type: cfg.server_type as i32,
server_age: cfg.server_age,
};
gsu.write_all()?;
let gsu = GSStatusUpdate::new(&cfg)?;
lh.send_packet(Box::new(gsu)).await?;
info!(
"Registered on Login server: {:} ({:})",
Expand Down
7 changes: 2 additions & 5 deletions src/game_server/packets/handleable/player_auth_response.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
use async_trait::async_trait;

use crate::common::packets::error::PacketRun;
use crate::{
common::packets::{
common::HandleablePacket
, ls_2_gs,
},
common::packets::{common::HandleablePacket, ls_2_gs},
game_server::handlers::LoginHandler,
};
use crate::common::packets::error::PacketRun;

#[async_trait]
impl HandleablePacket for ls_2_gs::PlayerAuthResponse {
Expand Down
10 changes: 5 additions & 5 deletions src/login_server/client_thread/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::crypt::login::Encryption;
use crate::crypt::{generate_blowfish_key, rsa};
use crate::database::DBPool;
use crate::login_server::controller::Login;
use crate::login_server::dto::config::Server;
use crate::common::config::login::LoginServer;
use crate::login_server::packet::cp_factory::build_client_packet;
use crate::login_server::packet::to_client::Init;
use anyhow::{Context, Error};
Expand Down Expand Up @@ -82,7 +82,7 @@ impl Shutdown for Client {

#[async_trait]
impl PacketHandler for Client {
type ConfigType = Server;
type ConfigType = LoginServer;
type ControllerType = Login;
fn get_handler_name() -> &'static str {
"Login client handler"
Expand Down Expand Up @@ -176,7 +176,7 @@ impl PacketHandler for Client {
}

impl InboundHandler for Client {
type ConfigType = Server;
type ConfigType = LoginServer;

fn get_connection_config(cfg: &Self::ConfigType) -> &InboundConnection {
&cfg.listeners.clients.connection
Expand All @@ -188,7 +188,7 @@ mod test {
use super::*;
use crate::common::tests::get_test_db;
use crate::common::traits::ServerConfig;
use crate::login_server::dto::config::Server;
use crate::common::config::login::LoginServer;
use tokio::net::TcpListener;

#[tokio::test]
Expand All @@ -197,7 +197,7 @@ mod test {
let listener = TcpListener::bind("127.0.0.1:3333").await.unwrap();
let addr = listener.local_addr().unwrap();
let db_pool = get_test_db().await;
let cfg = Server::from_string(include_str!("../../test_data/test_config.yaml"));
let cfg = LoginServer::from_string(include_str!("../../test_data/test_config.yaml"));
let lc = Arc::new(Login::new(Arc::new(cfg)));
let cloned_lc = lc.clone();
// Spawn a server task to handle a single connection
Expand Down
11 changes: 6 additions & 5 deletions src/login_server/controller/data.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::common::config::login;
use crate::crypt::rsa::{generate_rsa_key_pair, ScrambledRSAKeyPair};
use crate::login_server::dto::game_server::GSInfo;
use crate::login_server::dto::{config, player};
use crate::login_server::dto::player;
use crate::login_server::message::Request;
use crate::crypt::rsa::{generate_rsa_key_pair, ScrambledRSAKeyPair};
use dashmap::DashMap;
use rand::Rng;
use std::sync::Arc;
Expand All @@ -11,15 +12,15 @@ use tracing::info;
#[derive(Clone, Debug)]
pub struct Login {
key_pairs: Vec<ScrambledRSAKeyPair>,
pub(super) config: Arc<config::Server>,
pub(super) config: Arc<login::LoginServer>,
pub(super) game_servers: DashMap<u8, GSInfo>,
pub(super) ip_ban_list: DashMap<String, i64>,
pub(super) players: DashMap<String, player::Info>,
pub(super) gs_channels: DashMap<u8, Sender<(u8, Request)>>,
}

impl Login {
pub fn new(config: Arc<config::Server>) -> Login {
pub fn new(config: Arc<login::LoginServer>) -> Login {
info!("Loading LoginController...");
Login {
key_pairs: Login::generate_rsa_key_pairs(10),
Expand All @@ -30,7 +31,7 @@ impl Login {
gs_channels: DashMap::new(),
}
}
pub fn get_config(&self) -> &config::Server {
pub fn get_config(&self) -> &login::LoginServer {
&self.config
}
pub fn get_game_server(&self, gs_id: u8) -> Option<GSInfo> {
Expand Down
1 change: 0 additions & 1 deletion src/login_server/dto/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
pub mod config;
pub mod game_server;
pub mod player;
6 changes: 3 additions & 3 deletions src/login_server/gs_thread/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::crypt::login::Encryption;
use crate::crypt::rsa::ScrambledRSAKeyPair;
use crate::database::DBPool;
use crate::login_server::controller::Login;
use crate::login_server::dto::config::Server;
use crate::common::config::login::LoginServer;
use crate::login_server::gs_thread::enums;
use crate::login_server::message::Request;
use crate::login_server::packet::gs_factory::build_gs_packet;
Expand Down Expand Up @@ -129,7 +129,7 @@ impl Shutdown for GameServer {

#[async_trait]
impl PacketHandler for GameServer {
type ConfigType = Server;
type ConfigType = LoginServer;
type ControllerType = Login;
fn get_handler_name() -> &'static str {
"Game server handler"
Expand Down Expand Up @@ -215,7 +215,7 @@ impl PacketHandler for GameServer {
}

impl InboundHandler for GameServer {
type ConfigType = Server;
type ConfigType = LoginServer;

fn get_connection_config(cfg: &Self::ConfigType) -> &InboundConnection {
&cfg.listeners.game_servers.connection
Expand Down
4 changes: 2 additions & 2 deletions src/login_server/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::common::config::login;
use crate::common::traits::handlers::PacketHandler;
use crate::common::traits::server::Server;
use crate::common::traits::IpBan;
use crate::login_server::controller::Login;
use crate::login_server::dto::config;
pub mod client_thread;
pub mod controller;
pub mod dto;
Expand All @@ -13,6 +13,6 @@ mod packet;
pub struct LoginServer;

impl Server for LoginServer {
type ConfigType = config::Server;
type ConfigType = login::LoginServer;
type ControllerType = Login;
}

0 comments on commit 692e556

Please sign in to comment.