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 uuid::Uuid;
use crate::{config::auth::TextureConfig, server::Server};
use crate::{
config::{auth::TextureConfig, ADVANCED_CONFIG},
server::Server,
};
#[derive(Deserialize, Clone, Debug)]
#[allow(non_snake_case)]
@ -52,13 +55,9 @@ pub async fn authenticate(
ip: &IpAddr,
server: &mut Server,
) -> Result<GameProfile, AuthError> {
assert!(server.advanced_config.authentication.enabled);
assert!(ADVANCED_CONFIG.authentication.enabled);
assert!(server.auth_client.is_some());
let address = if server
.advanced_config
.authentication
.prevent_proxy_connections
{
let address = if ADVANCED_CONFIG.authentication.prevent_proxy_connections {
format!("https://sessionserver.mojang.com/session/minecraft/hasJoined?username={username}&serverId={server_hash}&ip={ip}")
} else {
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::{
client::authentication::{self, GameProfile},
config::{ADVANCED_CONFIG, BASIC_CONFIG},
entity::player::{ChatMode, Hand},
proxy::velocity::velocity_login,
server::{Server, CURRENT_MC_VERSION},
@ -81,7 +82,7 @@ impl Client {
properties: vec![],
profile_actions: None,
});
let proxy = &server.advanced_config.proxy;
let proxy = &ADVANCED_CONFIG.proxy;
if proxy.enabled {
if proxy.velocity.enabled {
velocity_login(self)
@ -96,7 +97,7 @@ impl Client {
"",
public_key_der,
&verify_token,
server.base_config.online_mode, // TODO
BASIC_CONFIG.online_mode, // TODO
);
self.send_packet(&packet);
}
@ -114,7 +115,7 @@ impl Client {
self.enable_encryption(&shared_secret)
.unwrap_or_else(|e| self.kick(&e.to_string()));
if server.base_config.online_mode {
if BASIC_CONFIG.online_mode {
let hash = Sha1::new()
.chain_update(&shared_secret)
.chain_update(&server.public_key_der)
@ -132,8 +133,7 @@ impl Client {
Ok(p) => {
// Check if player should join
if let Some(p) = &p.profile_actions {
if !server
.advanced_config
if !ADVANCED_CONFIG
.authentication
.player_profile
.allow_banned_players
@ -142,8 +142,7 @@ impl Client {
self.kick("Your account can't join");
}
} else {
for allowed in server
.advanced_config
for allowed in ADVANCED_CONFIG
.authentication
.player_profile
.allowed_actions
@ -162,16 +161,13 @@ impl Client {
}
for ele in self.gameprofile.as_ref().unwrap().properties.clone() {
// todo, use this
unpack_textures(ele, &server.advanced_config.authentication.textures);
unpack_textures(ele, &ADVANCED_CONFIG.authentication.textures);
}
// enable compression
if server.advanced_config.packet_compression.enabled {
let threshold = server
.advanced_config
.packet_compression
.compression_threshold;
let level = server.advanced_config.packet_compression.compression_level;
if ADVANCED_CONFIG.packet_compression.enabled {
let threshold = ADVANCED_CONFIG.packet_compression.compression_threshold;
let level = ADVANCED_CONFIG.packet_compression.compression_level;
self.send_packet(&CSetCompression::new(threshold.into()));
self.set_compression(Some((threshold, level)));
}
@ -199,7 +195,7 @@ impl Client {
self.connection_state = ConnectionState::Config;
server.send_brand(self);
let resource_config = &server.advanced_config.resource_pack;
let resource_config = &ADVANCED_CONFIG.resource_pack;
if resource_config.enabled {
let prompt_message = if resource_config.prompt_message.is_empty() {
None

View File

@ -2,6 +2,7 @@ use std::f32::consts::PI;
use crate::{
commands::{handle_command, CommandSender},
config::ADVANCED_CONFIG,
entity::player::{ChatMode, GameMode, Hand, Player},
server::Server,
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;
if self.sneaking != sneaking {
self.set_sneaking(sneaking).await;
@ -323,7 +324,7 @@ impl Player {
ActionType::Attack => {
let entity_id = interact.entity_id;
// TODO: do validation and stuff
let config = &server.advanced_config.pvp;
let config = &ADVANCED_CONFIG.pvp;
if config.enabled {
let world = self.world.clone();
let world = world.lock().await;

View File

@ -6,6 +6,7 @@ use std::{
fs,
net::{Ipv4Addr, SocketAddr},
path::Path,
sync::LazyLock,
};
use crate::{entity::player::GameMode, server::Difficulty};
@ -28,6 +29,11 @@ pub use rcon::RCONConfig;
/// Current Config version of the Base Config
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.
/// 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
where
Self: Sized + Default + Serialize + DeserializeOwned,

View File

@ -12,7 +12,6 @@ use std::io::{self};
use client::{interrupted, Client};
use commands::handle_command;
use config::{AdvancedConfiguration, BasicConfiguration, LoadConfiguration};
use server::Server;
// 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<()> {
use std::sync::{Arc, Mutex};
use config::{ADVANCED_CONFIG, BASIC_CONFIG};
use entity::player::Player;
use pumpkin_core::text::{color::NamedColor, TextComponent};
use rcon::RCONServer;
@ -61,9 +61,6 @@ fn main() -> io::Result<()> {
use std::time::Instant;
let time = Instant::now();
let basic_config = BasicConfiguration::load();
let advanced_configuration = AdvancedConfiguration::load();
// Create a poll instance.
let mut poll = Poll::new()?;
@ -71,7 +68,7 @@ fn main() -> io::Result<()> {
let mut events = Events::with_capacity(128);
// Setup the TCP server socket.
let addr = basic_config.server_address;
let addr = BASIC_CONFIG.server_address;
let mut listener = TcpListener::bind(addr)?;
// 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.
let mut unique_token = Token(SERVER.0 + 1);
let use_console = advanced_configuration.commands.use_console;
let rcon = advanced_configuration.rcon.clone();
let use_console = ADVANCED_CONFIG.commands.use_console;
let rcon = ADVANCED_CONFIG.rcon.clone();
let mut clients: HashMap<Token, Client> = HashMap::new();
let mut players: HashMap<Arc<Token>, Arc<Mutex<Player>>> = HashMap::new();
let server = Arc::new(tokio::sync::Mutex::new(Server::new((
basic_config,
advanced_configuration,
))));
let server = Arc::new(tokio::sync::Mutex::new(Server::new()));
log::info!("Started Server took {}ms", time.elapsed().as_millis());
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;
players.insert(token, player.clone());
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::{
client::Client,
config::{AdvancedConfiguration, BasicConfiguration},
config::{BasicConfiguration, BASIC_CONFIG},
entity::player::{GameMode, Player},
world::World,
};
@ -52,16 +52,15 @@ pub struct Server {
pub cached_registry: Vec<Registry>,
entity_id: AtomicI32,
pub base_config: BasicConfiguration,
pub advanced_config: AdvancedConfiguration,
/// Used for Authentication, None is Online mode is disabled
pub auth_client: Option<reqwest::Client>,
}
impl Server {
pub fn new(config: (BasicConfiguration, AdvancedConfiguration)) -> Self {
let status_response = Self::build_response(&config.0);
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
let status_response = Self::build_response(&BASIC_CONFIG);
let status_response_json = serde_json::to_string(&status_response)
.expect("Failed to parse Status response into JSON");
let cached_server_brand = Self::build_brand();
@ -75,7 +74,7 @@ impl Server {
&private_key.e().to_bytes_be(),
)
.into_boxed_slice();
let auth_client = if config.0.online_mode {
let auth_client = if BASIC_CONFIG.online_mode {
Some(
reqwest::Client::builder()
.timeout(Duration::from_millis(5000))
@ -106,9 +105,7 @@ impl Server {
status_response,
status_response_json,
public_key_der,
base_config: config.0,
auth_client,
advanced_config: config.1,
}
}
@ -118,7 +115,7 @@ impl Server {
client: Client,
) -> (Arc<Mutex<Player>>, Arc<tokio::sync::Mutex<World>>) {
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,
game_mode => game_mode,
};