Moved configuration to LazyLock

This commit is contained in:
DaniD3v 2024-08-31 17:24:36 +02:00
parent e48ca3b99f
commit bb543b7178
6 changed files with 39 additions and 46 deletions

View File

@ -8,7 +8,10 @@ use serde::{Deserialize, Serialize};
use thiserror::Error; use thiserror::Error;
use uuid::Uuid; use uuid::Uuid;
use crate::{config::auth::TextureConfig, server::Server}; use crate::{
config::{auth::TextureConfig, ADVANCED_CONFIG},
server::Server,
};
#[derive(Deserialize, Clone, Debug)] #[derive(Deserialize, Clone, Debug)]
#[allow(non_snake_case)] #[allow(non_snake_case)]
@ -52,13 +55,9 @@ pub async fn authenticate(
ip: &IpAddr, ip: &IpAddr,
server: &mut Server, server: &mut Server,
) -> Result<GameProfile, AuthError> { ) -> Result<GameProfile, AuthError> {
assert!(server.advanced_config.authentication.enabled); assert!(ADVANCED_CONFIG.authentication.enabled);
assert!(server.auth_client.is_some()); assert!(server.auth_client.is_some());
let address = if server let address = if ADVANCED_CONFIG.authentication.prevent_proxy_connections {
.advanced_config
.authentication
.prevent_proxy_connections
{
format!("https://sessionserver.mojang.com/session/minecraft/hasJoined?username={username}&serverId={server_hash}&ip={ip}") format!("https://sessionserver.mojang.com/session/minecraft/hasJoined?username={username}&serverId={server_hash}&ip={ip}")
} else { } else {
format!("https://sessionserver.mojang.com/session/minecraft/hasJoined?username={username}&serverId={server_hash}") format!("https://sessionserver.mojang.com/session/minecraft/hasJoined?username={username}&serverId={server_hash}")

View File

@ -19,6 +19,7 @@ use sha1::{Digest, Sha1};
use crate::{ use crate::{
client::authentication::{self, GameProfile}, client::authentication::{self, GameProfile},
config::{ADVANCED_CONFIG, BASIC_CONFIG},
entity::player::{ChatMode, Hand}, entity::player::{ChatMode, Hand},
proxy::velocity::velocity_login, proxy::velocity::velocity_login,
server::{Server, CURRENT_MC_VERSION}, server::{Server, CURRENT_MC_VERSION},
@ -81,7 +82,7 @@ impl Client {
properties: vec![], properties: vec![],
profile_actions: None, profile_actions: None,
}); });
let proxy = &server.advanced_config.proxy; let proxy = &ADVANCED_CONFIG.proxy;
if proxy.enabled { if proxy.enabled {
if proxy.velocity.enabled { if proxy.velocity.enabled {
velocity_login(self) velocity_login(self)
@ -96,7 +97,7 @@ impl Client {
"", "",
public_key_der, public_key_der,
&verify_token, &verify_token,
server.base_config.online_mode, // TODO BASIC_CONFIG.online_mode, // TODO
); );
self.send_packet(&packet); self.send_packet(&packet);
} }
@ -114,7 +115,7 @@ impl Client {
self.enable_encryption(&shared_secret) self.enable_encryption(&shared_secret)
.unwrap_or_else(|e| self.kick(&e.to_string())); .unwrap_or_else(|e| self.kick(&e.to_string()));
if server.base_config.online_mode { if BASIC_CONFIG.online_mode {
let hash = Sha1::new() let hash = Sha1::new()
.chain_update(&shared_secret) .chain_update(&shared_secret)
.chain_update(&server.public_key_der) .chain_update(&server.public_key_der)
@ -132,8 +133,7 @@ impl Client {
Ok(p) => { Ok(p) => {
// Check if player should join // Check if player should join
if let Some(p) = &p.profile_actions { if let Some(p) = &p.profile_actions {
if !server if !ADVANCED_CONFIG
.advanced_config
.authentication .authentication
.player_profile .player_profile
.allow_banned_players .allow_banned_players
@ -142,8 +142,7 @@ impl Client {
self.kick("Your account can't join"); self.kick("Your account can't join");
} }
} else { } else {
for allowed in server for allowed in ADVANCED_CONFIG
.advanced_config
.authentication .authentication
.player_profile .player_profile
.allowed_actions .allowed_actions
@ -162,16 +161,13 @@ impl Client {
} }
for ele in self.gameprofile.as_ref().unwrap().properties.clone() { for ele in self.gameprofile.as_ref().unwrap().properties.clone() {
// todo, use this // todo, use this
unpack_textures(ele, &server.advanced_config.authentication.textures); unpack_textures(ele, &ADVANCED_CONFIG.authentication.textures);
} }
// enable compression // enable compression
if server.advanced_config.packet_compression.enabled { if ADVANCED_CONFIG.packet_compression.enabled {
let threshold = server let threshold = ADVANCED_CONFIG.packet_compression.compression_threshold;
.advanced_config let level = ADVANCED_CONFIG.packet_compression.compression_level;
.packet_compression
.compression_threshold;
let level = server.advanced_config.packet_compression.compression_level;
self.send_packet(&CSetCompression::new(threshold.into())); self.send_packet(&CSetCompression::new(threshold.into()));
self.set_compression(Some((threshold, level))); self.set_compression(Some((threshold, level)));
} }
@ -199,7 +195,7 @@ impl Client {
self.connection_state = ConnectionState::Config; self.connection_state = ConnectionState::Config;
server.send_brand(self); server.send_brand(self);
let resource_config = &server.advanced_config.resource_pack; let resource_config = &ADVANCED_CONFIG.resource_pack;
if resource_config.enabled { if resource_config.enabled {
let prompt_message = if resource_config.prompt_message.is_empty() { let prompt_message = if resource_config.prompt_message.is_empty() {
None None

View File

@ -2,6 +2,7 @@ use std::f32::consts::PI;
use crate::{ use crate::{
commands::{handle_command, CommandSender}, commands::{handle_command, CommandSender},
config::ADVANCED_CONFIG,
entity::player::{ChatMode, GameMode, Hand, Player}, entity::player::{ChatMode, GameMode, Hand, Player},
server::Server, server::Server,
util::math::wrap_degrees, util::math::wrap_degrees,
@ -313,7 +314,7 @@ impl Player {
} }
} }
pub async fn handle_interact(&mut self, server: &mut Server, interact: SInteract) { pub async fn handle_interact(&mut self, _: &mut Server, interact: SInteract) {
let sneaking = interact.sneaking; let sneaking = interact.sneaking;
if self.sneaking != sneaking { if self.sneaking != sneaking {
self.set_sneaking(sneaking).await; self.set_sneaking(sneaking).await;
@ -323,7 +324,7 @@ impl Player {
ActionType::Attack => { ActionType::Attack => {
let entity_id = interact.entity_id; let entity_id = interact.entity_id;
// TODO: do validation and stuff // TODO: do validation and stuff
let config = &server.advanced_config.pvp; let config = &ADVANCED_CONFIG.pvp;
if config.enabled { if config.enabled {
let world = self.world.clone(); let world = self.world.clone();
let world = world.lock().await; let world = world.lock().await;

View File

@ -6,6 +6,7 @@ use std::{
fs, fs,
net::{Ipv4Addr, SocketAddr}, net::{Ipv4Addr, SocketAddr},
path::Path, path::Path,
sync::LazyLock,
}; };
use crate::{entity::player::GameMode, server::Difficulty}; use crate::{entity::player::GameMode, server::Difficulty};
@ -28,6 +29,11 @@ pub use rcon::RCONConfig;
/// Current Config version of the Base Config /// Current Config version of the Base Config
const CURRENT_BASE_VERSION: &str = "1.0.0"; const CURRENT_BASE_VERSION: &str = "1.0.0";
pub static ADVANCED_CONFIG: LazyLock<AdvancedConfiguration> =
LazyLock::new(AdvancedConfiguration::load);
pub static BASIC_CONFIG: LazyLock<BasicConfiguration> = LazyLock::new(BasicConfiguration::load);
/// The idea is that Pumpkin should very customizable. /// The idea is that Pumpkin should very customizable.
/// You can Enable or Disable Features depending on your needs. /// You can Enable or Disable Features depending on your needs.
/// ///
@ -94,7 +100,7 @@ impl Default for BasicConfiguration {
} }
} }
pub trait LoadConfiguration { trait LoadConfiguration {
fn load() -> Self fn load() -> Self
where where
Self: Sized + Default + Serialize + DeserializeOwned, Self: Sized + Default + Serialize + DeserializeOwned,

View File

@ -12,7 +12,6 @@ use std::io::{self};
use client::{interrupted, Client}; use client::{interrupted, Client};
use commands::handle_command; use commands::handle_command;
use config::{AdvancedConfiguration, BasicConfiguration, LoadConfiguration};
use server::Server; use server::Server;
// Setup some tokens to allow us to identify which event is for which socket. // Setup some tokens to allow us to identify which event is for which socket.
@ -30,6 +29,7 @@ pub mod world;
fn main() -> io::Result<()> { fn main() -> io::Result<()> {
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use config::{ADVANCED_CONFIG, BASIC_CONFIG};
use entity::player::Player; use entity::player::Player;
use pumpkin_core::text::{color::NamedColor, TextComponent}; use pumpkin_core::text::{color::NamedColor, TextComponent};
use rcon::RCONServer; use rcon::RCONServer;
@ -61,9 +61,6 @@ fn main() -> io::Result<()> {
use std::time::Instant; use std::time::Instant;
let time = Instant::now(); let time = Instant::now();
let basic_config = BasicConfiguration::load();
let advanced_configuration = AdvancedConfiguration::load();
// Create a poll instance. // Create a poll instance.
let mut poll = Poll::new()?; let mut poll = Poll::new()?;
@ -71,7 +68,7 @@ fn main() -> io::Result<()> {
let mut events = Events::with_capacity(128); let mut events = Events::with_capacity(128);
// Setup the TCP server socket. // Setup the TCP server socket.
let addr = basic_config.server_address; let addr = BASIC_CONFIG.server_address;
let mut listener = TcpListener::bind(addr)?; let mut listener = TcpListener::bind(addr)?;
// Register the server with poll we can receive events for it. // Register the server with poll we can receive events for it.
@ -81,16 +78,13 @@ fn main() -> io::Result<()> {
// Unique token for each incoming connection. // Unique token for each incoming connection.
let mut unique_token = Token(SERVER.0 + 1); let mut unique_token = Token(SERVER.0 + 1);
let use_console = advanced_configuration.commands.use_console; let use_console = ADVANCED_CONFIG.commands.use_console;
let rcon = advanced_configuration.rcon.clone(); let rcon = ADVANCED_CONFIG.rcon.clone();
let mut clients: HashMap<Token, Client> = HashMap::new(); let mut clients: HashMap<Token, Client> = HashMap::new();
let mut players: HashMap<Arc<Token>, Arc<Mutex<Player>>> = HashMap::new(); let mut players: HashMap<Arc<Token>, Arc<Mutex<Player>>> = HashMap::new();
let server = Arc::new(tokio::sync::Mutex::new(Server::new(( let server = Arc::new(tokio::sync::Mutex::new(Server::new()));
basic_config,
advanced_configuration,
))));
log::info!("Started Server took {}ms", time.elapsed().as_millis()); log::info!("Started Server took {}ms", time.elapsed().as_millis());
log::info!("You now can connect to the server, Listening on {}", addr); log::info!("You now can connect to the server, Listening on {}", addr);
@ -204,7 +198,7 @@ fn main() -> io::Result<()> {
server.add_player(token.clone(), client).await; server.add_player(token.clone(), client).await;
players.insert(token, player.clone()); players.insert(token, player.clone());
let mut world = world.lock().await; let mut world = world.lock().await;
world.spawn_player(&server.base_config, player).await; world.spawn_player(&BASIC_CONFIG, player).await;
} }
} }
} }

View File

@ -25,7 +25,7 @@ use serde::{Deserialize, Serialize};
use crate::{ use crate::{
client::Client, client::Client,
config::{AdvancedConfiguration, BasicConfiguration}, config::{BasicConfiguration, BASIC_CONFIG},
entity::player::{GameMode, Player}, entity::player::{GameMode, Player},
world::World, world::World,
}; };
@ -52,16 +52,15 @@ pub struct Server {
pub cached_registry: Vec<Registry>, pub cached_registry: Vec<Registry>,
entity_id: AtomicI32, entity_id: AtomicI32,
pub base_config: BasicConfiguration,
pub advanced_config: AdvancedConfiguration,
/// Used for Authentication, None is Online mode is disabled /// Used for Authentication, None is Online mode is disabled
pub auth_client: Option<reqwest::Client>, pub auth_client: Option<reqwest::Client>,
} }
impl Server { impl Server {
pub fn new(config: (BasicConfiguration, AdvancedConfiguration)) -> Self { #[allow(clippy::new_without_default)]
let status_response = Self::build_response(&config.0); pub fn new() -> Self {
let status_response = Self::build_response(&BASIC_CONFIG);
let status_response_json = serde_json::to_string(&status_response) let status_response_json = serde_json::to_string(&status_response)
.expect("Failed to parse Status response into JSON"); .expect("Failed to parse Status response into JSON");
let cached_server_brand = Self::build_brand(); let cached_server_brand = Self::build_brand();
@ -75,7 +74,7 @@ impl Server {
&private_key.e().to_bytes_be(), &private_key.e().to_bytes_be(),
) )
.into_boxed_slice(); .into_boxed_slice();
let auth_client = if config.0.online_mode { let auth_client = if BASIC_CONFIG.online_mode {
Some( Some(
reqwest::Client::builder() reqwest::Client::builder()
.timeout(Duration::from_millis(5000)) .timeout(Duration::from_millis(5000))
@ -106,9 +105,7 @@ impl Server {
status_response, status_response,
status_response_json, status_response_json,
public_key_der, public_key_der,
base_config: config.0,
auth_client, auth_client,
advanced_config: config.1,
} }
} }
@ -118,7 +115,7 @@ impl Server {
client: Client, client: Client,
) -> (Arc<Mutex<Player>>, Arc<tokio::sync::Mutex<World>>) { ) -> (Arc<Mutex<Player>>, Arc<tokio::sync::Mutex<World>>) {
let entity_id = self.new_entity_id(); let entity_id = self.new_entity_id();
let gamemode = match self.base_config.default_gamemode { let gamemode = match BASIC_CONFIG.default_gamemode {
GameMode::Undefined => GameMode::Survival, GameMode::Undefined => GameMode::Survival,
game_mode => game_mode, game_mode => game_mode,
}; };