Merge remote-tracking branch 'upstream/master'

This commit is contained in:
lukas0008 committed 2024-08-12 20:30:52 +02:00
commit 5d6c38d1b2
60 files changed
+1371 -344

No files matched your search

+5 -1
View File
@@ -5,6 +5,8 @@ description = "Empowering everyone to host fast and efficient Minecraft servers.
edition = "2021"
[dependencies]
pumpkin-text = { path = "../pumpkin-text" }
pumpkin-inventory = { path = "../pumpkin-inventory"}
pumpkin-world = { path = "../pumpkin-world"}
pumpkin-entity = { path = "../pumpkin-entity"}
pumpkin-protocol = { path = "../pumpkin-protocol"}
@@ -15,6 +17,8 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
toml = "0.8.19"
bytes = "1.7"
rand = "0.8.5"
num-traits = "0.2"
@@ -45,6 +49,6 @@ log = "0.4"
mio = { version = "1.0.1", features = ["os-poll", "net"]}
crossbeam-channel = "0.5.13"
uuid = { version = "1.10", features = ["serde"]}
uuid = { version = "1.10", features = ["serde", "v3"]}
tokio.workspace = true
+4 -2
View File
@@ -52,14 +52,16 @@ pub async fn authenticate(
ip: &IpAddr,
server: &mut Server,
) -> Result<GameProfile, AuthError> {
assert!(server.advanced_config.authentication.use_authentication);
assert!(server.advanced_config.authentication.enabled);
assert!(server.auth_client.is_some());
let address = if server
.advanced_config
.authentication
.prevent_proxy_connections
{
format!("https://sessionserver.mojang.com/session/minecraft/hasJoined?username={username}&serverId={server_hash}&ip={ip}")
let test = format!("https://sessionserver.mojang.com/session/minecraft/hasJoined?username={username}&serverId={server_hash}&ip={ip}");
dbg!(&test);
test
} else {
format!("https://sessionserver.mojang.com/session/minecraft/hasJoined?username={username}&serverId={server_hash}")
};
+37 -16
View File
@@ -1,7 +1,9 @@
use std::str::FromStr;
use num_traits::FromPrimitive;
use pumpkin_protocol::{
client::{
config::{CFinishConfig, CKnownPacks, CRegistryData},
config::{CConfigAddResourcePack, CFinishConfig, CKnownPacks, CRegistryData},
login::{CEncryptionRequest, CLoginSuccess, CSetCompression},
status::{CPingResponse, CStatusResponse},
},
@@ -11,9 +13,9 @@ use pumpkin_protocol::{
login::{SEncryptionResponse, SLoginAcknowledged, SLoginPluginResponse, SLoginStart},
status::{SPingRequest, SStatusRequest},
},
ConnectionState, KnownPack, RawBytes,
ConnectionState, KnownPack,
};
use pumpkin_registry::Registry;
use pumpkin_text::TextComponent;
use rsa::Pkcs1v15Encrypt;
use sha1::{Digest, Sha1};
@@ -38,12 +40,12 @@ impl Client {
}
pub fn handle_status_request(&mut self, server: &mut Server, _status_request: SStatusRequest) {
self.send_packet(CStatusResponse::new(&server.status_response_json));
self.send_packet(&CStatusResponse::new(&server.status_response_json));
}
pub fn handle_ping_request(&mut self, _server: &mut Server, ping_request: SPingRequest) {
dbg!("ping");
self.send_packet(CPingResponse::new(ping_request.payload));
self.send_packet(&CPingResponse::new(ping_request.payload));
self.close();
}
@@ -64,11 +66,11 @@ impl Client {
let public_key_der = &server.public_key_der;
let packet = CEncryptionRequest::new(
"",
RawBytes(public_key_der),
RawBytes(&verify_token),
public_key_der,
&verify_token,
server.base_config.online_mode, // TODO
);
self.send_packet(packet);
self.send_packet(&packet);
}
pub async fn handle_encryption_response(
@@ -131,6 +133,7 @@ impl Client {
}
}
for ele in self.gameprofile.as_ref().unwrap().properties.clone() {
// todo, use this
unpack_textures(ele, &server.advanced_config.authentication.textures);
}
@@ -141,13 +144,13 @@ impl Client {
.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)));
}
if let Some(profile) = self.gameprofile.as_ref().cloned() {
let packet = CLoginSuccess::new(profile.id, profile.name, &profile.properties, false);
self.send_packet(packet);
let packet = CLoginSuccess::new(profile.id, &profile.name, &profile.properties, false);
self.send_packet(&packet);
} else {
self.kick("game profile is none");
}
@@ -167,8 +170,25 @@ impl Client {
) {
self.connection_state = ConnectionState::Config;
server.send_brand(self);
let resource_config = &server.advanced_config.resource_pack;
if resource_config.enabled {
let prompt_message = if resource_config.prompt_message.is_empty() {
None
} else {
Some(TextComponent::from(resource_config.prompt_message.clone()))
};
self.send_packet(&CConfigAddResourcePack::new(
uuid::Uuid::from_str(&resource_config.resource_pack_url).unwrap(),
resource_config.resource_pack_url.clone(),
resource_config.resource_pack_sha1.clone(),
resource_config.force,
prompt_message,
));
}
// known data packs
self.send_packet(CKnownPacks::new(&[KnownPack {
self.send_packet(&CKnownPacks::new(&[KnownPack {
namespace: "minecraft",
id: "core",
version: "1.21",
@@ -180,6 +200,7 @@ impl Client {
_server: &mut Server,
client_information: SClientInformation,
) {
dbg!("got client settings");
self.config = Some(PlayerConfig {
locale: client_information.locale,
view_distance: client_information.view_distance,
@@ -204,9 +225,9 @@ impl Client {
}
}
pub fn handle_known_packs(&mut self, _server: &mut Server, _config_acknowledged: SKnownPacks) {
for registry in Registry::get_static() {
self.send_packet(CRegistryData::new(
pub fn handle_known_packs(&mut self, server: &mut Server, _config_acknowledged: SKnownPacks) {
for registry in &server.cached_registry {
self.send_packet(&CRegistryData::new(
&registry.registry_id,
&registry.registry_entries,
));
@@ -214,7 +235,7 @@ impl Client {
// We are done with configuring
dbg!("finish config");
self.send_packet(CFinishConfig::new());
self.send_packet(&CFinishConfig::new());
}
pub async fn handle_config_acknowledged(
+11 -15
View File
@@ -32,9 +32,9 @@ use pumpkin_protocol::{
},
status::{SPingRequest, SStatusRequest},
},
text::TextComponent,
ClientPacket, ConnectionState, PacketError, RawPacket, ServerPacket,
};
use pumpkin_text::TextComponent;
use std::io::Read;
use thiserror::Error;
@@ -122,7 +122,7 @@ impl Client {
}
/// Send a Clientbound Packet to the Client
pub fn send_packet<P: ClientPacket>(&mut self, packet: P) {
pub fn send_packet<P: ClientPacket>(&mut self, packet: &P) {
self.enc
.append_packet(packet)
.unwrap_or_else(|e| self.kick(&e.to_string()));
@@ -132,7 +132,7 @@ impl Client {
.unwrap_or_else(|e| self.kick(&e.to_string()));
}
pub fn try_send_packet<P: ClientPacket>(&mut self, packet: P) -> Result<(), PacketError> {
pub fn try_send_packet<P: ClientPacket>(&mut self, packet: &P) -> Result<(), PacketError> {
self.enc.append_packet(packet)?;
self.connection
.write_all(&self.enc.take())
@@ -155,11 +155,11 @@ impl Client {
entity.yaw = yaw;
entity.pitch = pitch;
player.awaiting_teleport = Some(id.into());
self.send_packet(CSyncPlayerPostion::new(x, y, z, yaw, pitch, 0, id.into()));
self.send_packet(&CSyncPlayerPostion::new(x, y, z, yaw, pitch, 0, id.into()));
}
pub fn set_gamemode(&mut self, gamemode: GameMode) {
self.send_packet(CGameEvent::new(3, gamemode.to_f32().unwrap()));
self.send_packet(&CGameEvent::new(3, gamemode.to_f32().unwrap()));
}
pub async fn process_packets(&mut self, server: &mut Server) {
@@ -294,9 +294,7 @@ impl Client {
}
Ok(n) => {
bytes_read += n;
if bytes_read == received_data.len() {
received_data.resize(received_data.len() + 1024, 0);
}
received_data.extend(&vec![0; n]);
}
// Would block "errors" are the OS's way of saying that the
// connection is not actually ready to perform this I/O operation.
@@ -325,7 +323,7 @@ impl Client {
}
pub fn send_system_message(&mut self, text: TextComponent) {
self.send_packet(CSystemChatMessge::new(text, false));
self.send_packet(&CSystemChatMessge::new(text, false));
}
/// Kicks the Client with a reason depending on the connection state
@@ -333,20 +331,18 @@ impl Client {
dbg!(reason);
match self.connection_state {
ConnectionState::Login => {
self.try_send_packet(CLoginDisconnect::new(
self.try_send_packet(&CLoginDisconnect::new(
&serde_json::to_string_pretty(&reason).unwrap(),
))
.unwrap_or_else(|_| self.close());
}
ConnectionState::Config => {
self.try_send_packet(CConfigDisconnect::new(reason))
self.try_send_packet(&CConfigDisconnect::new(reason))
.unwrap_or_else(|_| self.close());
}
ConnectionState::Play => {
self.try_send_packet(CPlayDisconnect::new(TextComponent {
text: reason.to_string(),
}))
.unwrap_or_else(|_| self.close());
self.try_send_packet(&CPlayDisconnect::new(TextComponent::from(reason)))
.unwrap_or_else(|_| self.close());
}
_ => {
log::warn!("Cant't kick in {:?} State", self.connection_state)
+69 -43
View File
@@ -1,20 +1,23 @@
use num_traits::FromPrimitive;
use pumpkin_inventory::WindowType;
use pumpkin_protocol::{
client::play::{
Animation, CEntityAnimation, CHeadRot, CSystemChatMessge, CUpdateEntityPos,
CUpdateEntityPosRot, CUpdateEntityRot,
Animation, CEntityAnimation, CHeadRot, COpenScreen, CUpdateEntityPos, CUpdateEntityPosRot,
CUpdateEntityRot,
},
server::play::{
SChatCommand, SChatMessage, SConfirmTeleport, SPlayerCommand, SPlayerPosition,
SPlayerPositionRotation, SPlayerRotation, SSwingArm,
},
text::TextComponent,
VarInt,
};
use pumpkin_text::TextComponent;
use crate::{
commands::{handle_command, CommandSender},
entity::player::Hand,
server::Server,
util::math::wrap_degrees,
};
use super::Client;
@@ -38,18 +41,27 @@ impl Client {
}
}
fn clamp_horizontal(pos: f64) -> f64 {
pos.clamp(-3.0E7, 3.0E7)
}
fn clamp_vertical(pos: f64) -> f64 {
pos.clamp(-2.0E7, 2.0E7)
}
pub fn handle_position(&mut self, server: &mut Server, position: SPlayerPosition) {
if position.x.is_nan() || position.feet_y.is_nan() || position.z.is_nan() {
self.kick("Invalid movement");
return;
}
let player = self.player.as_mut().unwrap();
let entity = &mut player.entity;
entity.lastx = entity.x;
entity.lasty = entity.y;
entity.lastz = entity.z;
entity.x = position.x;
entity.y = position.feet_y;
entity.z = position.z;
entity.x = Self::clamp_horizontal(position.x);
entity.y = Self::clamp_vertical(position.feet_y);
entity.z = Self::clamp_horizontal(position.z);
// TODO: teleport when moving > 8 block
// send new position to all other players
@@ -61,7 +73,7 @@ impl Client {
server.broadcast_packet(
self,
CUpdateEntityPos::new(
&CUpdateEntityPos::new(
entity_id.into(),
(x * 4096.0 - lastx * 4096.0) as i16,
(y * 4096.0 - lasty * 4096.0) as i16,
@@ -81,18 +93,23 @@ impl Client {
|| position_rotation.z.is_nan()
{
self.kick("Invalid movement");
return;
}
if !position_rotation.yaw.is_finite() || !position_rotation.pitch.is_finite() {
self.kick("Invalid rotation");
return;
}
let player = self.player.as_mut().unwrap();
let entity = &mut player.entity;
entity.x = position_rotation.x;
entity.y = position_rotation.feet_y;
entity.z = position_rotation.z;
entity.yaw = position_rotation.yaw % 360.0;
entity.pitch = position_rotation.pitch.clamp(-90.0, 90.0) % 360.0;
entity.lastx = entity.x;
entity.lasty = entity.y;
entity.lastz = entity.z;
entity.x = Self::clamp_horizontal(position_rotation.x);
entity.y = Self::clamp_vertical(position_rotation.feet_y);
entity.z = Self::clamp_horizontal(position_rotation.z);
entity.yaw = wrap_degrees(position_rotation.yaw);
entity.pitch = wrap_degrees(position_rotation.pitch);
// send new position to all other players
let on_ground = player.on_ground;
@@ -106,7 +123,7 @@ impl Client {
server.broadcast_packet(
self,
CUpdateEntityPosRot::new(
&CUpdateEntityPosRot::new(
entity_id.into(),
(x * 4096.0 - lastx * 4096.0) as i16,
(y * 4096.0 - lasty * 4096.0) as i16,
@@ -116,32 +133,34 @@ impl Client {
on_ground,
),
);
server.broadcast_packet(self, CHeadRot::new(entity_id.into(), head_yaw as u8));
server.broadcast_packet(self, &CHeadRot::new(entity_id.into(), head_yaw as u8));
}
pub fn handle_rotation(&mut self, server: &mut Server, rotation: SPlayerRotation) {
if !rotation.yaw.is_finite() || !rotation.pitch.is_finite() {
self.kick("Invalid rotation");
return;
}
let player = self.player.as_mut().unwrap();
let entity = &mut player.entity;
entity.yaw = rotation.yaw % 360.0;
entity.pitch = rotation.pitch.clamp(-90.0, 90.0) % 360.0;
entity.yaw = wrap_degrees(rotation.yaw);
entity.pitch = wrap_degrees(rotation.pitch);
// send new position to all other players
let on_ground = player.on_ground;
let entity_id = entity.entity_id;
let yaw = entity.yaw;
let pitch = entity.pitch;
let yaw = (entity.yaw * 256.0 / 360.0).floor();
let pitch = (entity.pitch * 256.0 / 360.0).floor();
let head_yaw = (entity.head_yaw * 256.0 / 360.0).floor();
server.broadcast_packet(
self,
CUpdateEntityRot::new(entity_id.into(), yaw as u8, pitch as u8, on_ground),
&CUpdateEntityRot::new(entity_id.into(), yaw as u8, pitch as u8, on_ground),
);
server.broadcast_packet(self, CHeadRot::new(entity_id.into(), yaw as u8));
server.broadcast_packet(self, &CHeadRot::new(entity_id.into(), head_yaw as u8));
}
pub fn handle_chat_command(&mut self, _server: &mut Server, command: SChatCommand) {
handle_command(&mut CommandSender::Player(self), command.command);
handle_command(&mut CommandSender::Player(self), &command.command);
}
pub fn handle_player_command(&mut self, _server: &mut Server, command: SPlayerCommand) {
@@ -170,39 +189,46 @@ impl Client {
};
let player = self.player.as_mut().unwrap();
let id = player.entity_id();
server.broadcast_packet_expect(self, CEntityAnimation::new(id.into(), animation as u8))
server.broadcast_packet_expect(self, &CEntityAnimation::new(id.into(), animation as u8))
}
pub fn handle_chat_message(&mut self, server: &mut Server, chat_message: SChatMessage) {
let message = chat_message.message;
self.send_packet(&COpenScreen::new(
VarInt(0),
VarInt(WindowType::CraftingTable as i32),
TextComponent::from("Test Crafter"),
));
// TODO: filter message & validation
let gameprofile = self.gameprofile.as_ref().unwrap();
dbg!("got message");
// yeah a "raw system message", the ugly way to do that, but it works
server.broadcast_packet(
// server.broadcast_packet(
// self,
// CSystemChatMessge::new(
// TextComponent::from(format!("{}: {}", gameprofile.name, message)),
// false,
// ),
// );
/* server.broadcast_packet(
self,
CSystemChatMessge::new(
TextComponent::from(format!("{}: {}", gameprofile.name, message)),
false,
CPlayerChatMessage::new(
pumpkin_protocol::uuid::UUID(gameprofile.id),
0.into(),
None,
message.clone(),
chat_message.timestamp,
chat_message.salt,
&[],
Some(TextComponent::from(message.clone())),
pumpkin_protocol::VarInt(FilterType::PassThrough as i32),
0.into(),
TextComponent::from(gameprofile.name.clone()),
None,
),
)
/*server.broadcast_packet(
self,
CPlayerChatMessage::new(
gameprofile.id,
0.into(),
None,
message.clone(),
chat_message.timestamp,
chat_message.salt,
&[],
Some(TextComponent::from(message.clone())),
pumpkin_protocol::VarInt(FilterType::PassThrough as i32),
0.into(),
TextComponent::from(gameprofile.name.clone()),
None,
),
) */
*/
/* server.broadcast_packet(
self,
CDisguisedChatMessage::new(
-6
View File
@@ -2,12 +2,6 @@ use super::Command;
pub struct GamemodeCommand {}
impl GamemodeCommand {
pub fn new() -> Self {
Self {}
}
}
impl<'a> Command<'a> for GamemodeCommand {
const NAME: &'a str = "gamemode";
+8 -3
View File
@@ -1,6 +1,6 @@
use gamemode::GamemodeCommand;
use pumpkin::PumpkinCommand;
use pumpkin_protocol::text::TextComponent;
use pumpkin_text::TextComponent;
use crate::client::Client;
@@ -23,6 +23,7 @@ pub trait Command<'a> {
}
pub enum CommandSender<'a> {
Rcon(&'a mut Vec<String>),
Console,
Player(&'a mut Client),
}
@@ -31,8 +32,9 @@ impl<'a> CommandSender<'a> {
pub fn send_message(&mut self, text: TextComponent) {
match self {
// TODO: add color and stuff to console
CommandSender::Console => log::info!("{}", text.text),
CommandSender::Console => log::info!("{:?}", text.content),
CommandSender::Player(c) => c.send_system_message(text),
CommandSender::Rcon(s) => s.push(format!("{:?}", text.content)),
}
}
@@ -40,6 +42,7 @@ impl<'a> CommandSender<'a> {
match self {
CommandSender::Console => false,
CommandSender::Player(_) => true,
CommandSender::Rcon(_) => false,
}
}
@@ -47,16 +50,18 @@ impl<'a> CommandSender<'a> {
match self {
CommandSender::Console => true,
CommandSender::Player(_) => false,
CommandSender::Rcon(_) => true,
}
}
pub fn as_mut_player(&mut self) -> Option<&mut Client> {
match self {
CommandSender::Player(client) => Some(client),
CommandSender::Console => None,
CommandSender::Rcon(_) => None,
}
}
}
pub fn handle_command(sender: &mut CommandSender, command: String) {
pub fn handle_command(sender: &mut CommandSender, command: &str) {
let command = command.to_lowercase();
// an ugly mess i know
if command.starts_with(PumpkinCommand::NAME) {
+3 -8
View File
@@ -1,4 +1,5 @@
use pumpkin_protocol::{text::TextComponent, CURRENT_MC_PROTOCOL};
use pumpkin_protocol::CURRENT_MC_PROTOCOL;
use pumpkin_text::{color::NamedColor, TextComponent};
use crate::server::CURRENT_MC_VERSION;
@@ -6,12 +7,6 @@ use super::Command;
pub struct PumpkinCommand {}
impl PumpkinCommand {
pub fn new() -> Self {
Self {}
}
}
impl<'a> Command<'a> for PumpkinCommand {
const NAME: &'a str = "pumpkin";
@@ -20,6 +15,6 @@ impl<'a> Command<'a> for PumpkinCommand {
fn on_execute(sender: &mut super::CommandSender<'a>, _command: String) {
let version = env!("CARGO_PKG_VERSION");
let description = env!("CARGO_PKG_DESCRIPTION");
sender.send_message(TextComponent::from(format!("Pumpkin {version}, {description} (Minecraft {CURRENT_MC_VERSION}, Protocol {CURRENT_MC_PROTOCOL})")))
sender.send_message(TextComponent::from(format!("Pumpkin {version}, {description} (Minecraft {CURRENT_MC_VERSION}, Protocol {CURRENT_MC_PROTOCOL})")).color_named(NamedColor::Green).bold())
}
}
+3 -3
View File
@@ -5,7 +5,7 @@ use crate::client::authentication::ProfileAction;
#[derive(Deserialize, Serialize)]
pub struct Authentication {
/// Whether to use Mojang authentication.
pub use_authentication: bool,
pub enabled: bool,
/// Prevent proxy connections.
pub prevent_proxy_connections: bool,
@@ -84,8 +84,8 @@ impl Default for TextureTypes {
impl Default for Authentication {
fn default() -> Self {
Self {
use_authentication: true,
prevent_proxy_connections: true,
enabled: true,
prevent_proxy_connections: false,
player_profile: Default::default(),
textures: Default::default(),
}
+37 -14
View File
@@ -1,11 +1,13 @@
use std::path::Path;
use auth_config::Authentication;
use resource_pack::ResourcePack;
use serde::{Deserialize, Serialize};
use crate::{entity::player::GameMode, server::Difficulty};
pub mod auth_config;
pub mod resource_pack;
/// Current Config version of the Base Config
const CURRENT_BASE_VERSION: &str = "1.0.0";
@@ -18,6 +20,27 @@ pub struct AdvancedConfiguration {
pub commands: Commands,
pub authentication: Authentication,
pub packet_compression: Compression,
pub resource_pack: ResourcePack,
pub rcon: RCONConfig,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct RCONConfig {
pub enabled: bool,
pub ip: String,
pub port: u16,
pub password: String,
}
impl Default for RCONConfig {
fn default() -> Self {
Self {
enabled: false,
ip: "0.0.0.0".to_string(),
port: 25575,
password: "".to_string(),
}
}
}
#[derive(Deserialize, Serialize)]
@@ -63,6 +86,8 @@ impl Default for AdvancedConfiguration {
authentication: Authentication::default(),
commands: Commands::default(),
packet_compression: Compression::default(),
resource_pack: ResourcePack::default(),
rcon: RCONConfig::default(),
}
}
}
@@ -83,10 +108,6 @@ pub struct BasicConfiguration {
pub view_distance: u8,
/// The maximum simulated view distance.
pub simulation_distance: u8,
/// The path to the resource pack.
pub resource_pack: String,
/// The SHA1 hash of the resource pack.
pub resource_pack_sha1: String,
/// The default game difficulty.
pub default_difficulty: Difficulty,
/// Whether the Nether dimension is enabled.
@@ -107,14 +128,12 @@ impl Default for BasicConfiguration {
fn default() -> Self {
Self {
config_version: CURRENT_BASE_VERSION.to_string(),
server_address: "127.0.0.1".to_string(),
server_address: "0.0.0.0".to_string(),
server_port: 25565,
seed: "".to_string(),
max_players: 100000,
view_distance: 10,
simulation_distance: 10,
resource_pack: "".to_string(),
resource_pack_sha1: "".to_string(),
default_difficulty: Difficulty::Normal,
allow_nether: true,
hardcore: false,
@@ -130,21 +149,30 @@ impl AdvancedConfiguration {
pub fn load<P: AsRef<Path>>(path: P) -> AdvancedConfiguration {
if path.as_ref().exists() {
let toml = std::fs::read_to_string(path).expect("Couldn't read configuration");
toml::from_str(toml.as_str()).expect("Couldn't parse, Proberbly old config")
let config: AdvancedConfiguration =
toml::from_str(toml.as_str()).expect("Couldn't parse features.toml, Proberbly old config, Replacing with a new one or just delete it");
config.validate();
config
} else {
let config = AdvancedConfiguration::default();
let toml = toml::to_string(&config).expect("Couldn't create toml!");
std::fs::write(path, toml).expect("Couldn't save configuration");
config.validate();
config
}
}
pub fn validate(&self) {
self.resource_pack.validate()
}
}
impl BasicConfiguration {
pub fn load<P: AsRef<Path>>(path: P) -> BasicConfiguration {
if path.as_ref().exists() {
let toml = std::fs::read_to_string(path).expect("Couldn't read configuration");
toml::from_str(toml.as_str()).expect("Couldn't parse")
let config: BasicConfiguration = toml::from_str(toml.as_str()).expect("Couldn't parse configuration.toml, Proberbly old config, Replacing with a new one or just delete it");
config.validate();
config
} else {
let config = BasicConfiguration::default();
let toml = toml::to_string(&config).expect("Couldn't create toml!");
@@ -170,10 +198,5 @@ impl BasicConfiguration {
"When Online Mode is enabled, Encryption must be enabled"
)
}
assert_eq!(
!self.resource_pack.is_empty(),
!self.resource_pack_sha1.is_empty(),
"Resource Pack path or Sha1 hash is missing"
);
}
}
+40
View File
@@ -0,0 +1,40 @@
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
pub struct ResourcePack {
pub enabled: bool,
/// The path to the resource pack.
pub resource_pack_url: String,
/// The SHA1 hash (40) of the resource pack.
pub resource_pack_sha1: String,
/// Custom propmt Text component, Leave blank for none
pub prompt_message: String,
/// Will force the Player to accept the resource pack
pub force: bool,
}
impl ResourcePack {
pub fn validate(&self) {
assert_eq!(
!self.resource_pack_url.is_empty(),
!self.resource_pack_sha1.is_empty(),
"Resource Pack path or Sha1 hash is missing"
);
assert!(
self.resource_pack_sha1.len() <= 40,
"Resource pack sha1 hash is too long (max. 40)"
)
}
}
impl Default for ResourcePack {
fn default() -> Self {
Self {
enabled: false,
resource_pack_url: "".into(),
resource_pack_sha1: "".into(),
force: false,
prompt_message: "".into(),
}
}
}
+10 -1
View File
@@ -18,6 +18,7 @@ pub mod client;
pub mod commands;
pub mod config;
pub mod entity;
pub mod rcon;
pub mod server;
pub mod util;
@@ -27,6 +28,8 @@ async fn main() -> io::Result<()> {
const SERVER: Token = Token(0);
use std::{cell::RefCell, time::Instant};
use rcon::RCONServer;
let time = Instant::now();
let basic_config = BasicConfiguration::load("configuration.toml");
@@ -58,6 +61,7 @@ async fn main() -> io::Result<()> {
let mut unique_token = Token(SERVER.0 + 1);
let use_console = advanced_configuration.commands.use_console;
let rcon = advanced_configuration.rcon.clone();
let mut connections: HashMap<Token, Rc<RefCell<Client>>> = HashMap::new();
@@ -73,10 +77,15 @@ async fn main() -> io::Result<()> {
stdin
.read_line(&mut out)
.expect("Failed to read console line");
handle_command(&mut commands::CommandSender::Console, out);
handle_command(&mut commands::CommandSender::Console, &out);
}
});
}
if rcon.enabled {
tokio::spawn(async move {
RCONServer::new(&rcon).await.unwrap();
});
}
loop {
if let Err(err) = poll.poll(&mut events, None) {
if interrupted(&err) {
+220
View File
@@ -0,0 +1,220 @@
use std::{
collections::HashMap,
io::{self, Read},
};
use mio::{
net::{TcpListener, TcpStream},
Events, Interest, Poll, Token,
};
use packet::{Packet, PacketError, PacketType};
use thiserror::Error;
use crate::{commands::handle_command, config::RCONConfig};
mod packet;
#[derive(Debug, Error)]
pub enum RCONError {
#[error("authentication failed")]
Auth,
#[error("command exceeds the maximum length")]
CommandTooLong,
#[error("{}", _0)]
Io(io::Error),
}
const SERVER: Token = Token(0);
pub struct RCONServer {}
impl RCONServer {
pub async fn new(config: &RCONConfig) -> Result<Self, io::Error> {
assert!(config.enabled, "RCON is not enabled");
let addr = format!("{}:{}", config.ip, config.port)
.parse()
.expect("Failed to parse RCON address");
let mut poll = Poll::new().unwrap();
let mut listener = TcpListener::bind(addr).unwrap();
poll.registry()
.register(&mut listener, SERVER, Interest::READABLE)
.unwrap();
let mut unique_token = Token(SERVER.0 + 1);
let mut events = Events::with_capacity(128);
let mut connections: HashMap<Token, RCONClient> = HashMap::new();
let password = config.password.clone();
loop {
poll.poll(&mut events, None).unwrap();
for event in events.iter() {
match event.token() {
SERVER => loop {
// Received an event for the TCP server socket, which
// indicates we can accept an connection.
let (mut connection, address) = match listener.accept() {
Ok((connection, address)) => (connection, address),
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
// If we get a `WouldBlock` error we know our
// listener has no more incoming connections queued,
// so we can return to polling and wait for some
// more.
break;
}
Err(e) => {
// If it was any other kind of error, something went
// wrong and we terminate with an error.
return Err(e);
}
};
log::info!("Accepted connection from: {}", address);
let token = Self::next(&mut unique_token);
poll.registry()
.register(
&mut connection,
token,
Interest::READABLE.add(Interest::WRITABLE),
)
.unwrap();
connections.insert(token, RCONClient::new(connection));
},
token => {
let done = if let Some(client) = connections.get_mut(&token) {
client.handle(&password).await
} else {
false
};
if done {
if let Some(mut client) = connections.remove(&token) {
poll.registry().deregister(&mut client.connection)?;
}
}
}
}
}
}
}
fn next(current: &mut Token) -> Token {
let next = current.0;
current.0 += 1;
Token(next)
}
}
pub struct RCONClient {
connection: TcpStream,
logged_in: bool,
incoming: Vec<u8>,
closed: bool,
}
impl RCONClient {
pub fn new(connection: TcpStream) -> Self {
Self {
connection,
logged_in: false,
incoming: Vec::new(),
closed: false,
}
}
pub async fn handle(&mut self, password: &str) -> bool {
if !self.closed {
loop {
match self.read_bytes() {
// Stream closed, so we can't reply, so we just close everything.
Ok(true) => return true,
Ok(false) => {}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
Err(e) => {
log::error!("could not read packet: {e}");
return true;
}
}
}
// If we get a close here, we might have a reply, which we still want to write.
match self.poll(password).await {
Ok(()) => {}
Err(e) => {
log::error!("rcon error: {e}");
self.closed = true;
}
}
}
self.closed
}
async fn poll(&mut self, password: &str) -> Result<(), PacketError> {
loop {
let packet = match self.receive_packet().await? {
Some(p) => p,
None => return Ok(()),
};
match packet.get_type() {
PacketType::Auth => {
let body = packet.get_body();
if !body.is_empty() && packet.get_body() == password {
self.send(&mut Packet::new(
packet.get_id(),
PacketType::AuthResponse,
"".into(),
))
.await
.unwrap();
log::info!("RCON Client logged in successfully");
self.logged_in = true;
} else {
log::warn!("RCON Client has tried wrong password");
self.send(&mut Packet::new(-1, PacketType::AuthResponse, "".into()))
.await
.unwrap();
return Err(PacketError::WrongPassword);
}
}
PacketType::ExecCommand => {
if self.logged_in {
let mut output = Vec::new();
handle_command(
&mut crate::commands::CommandSender::Rcon(&mut output),
packet.get_body(),
);
for line in output {
self.send(&mut Packet::new(packet.get_id(), PacketType::Output, line))
.await
.unwrap();
}
}
}
PacketType::Output => todo!(),
PacketType::AuthResponse => unreachable!(),
}
}
}
fn read_bytes(&mut self) -> io::Result<bool> {
let mut buf = [0; 1460];
let n = self.connection.read(&mut buf)?;
if n == 0 {
return Ok(true);
}
self.incoming.extend_from_slice(&buf[..n]);
Ok(false)
}
async fn send(&mut self, packet: &mut Packet) -> io::Result<()> {
packet.send_packet(&mut self.connection).await
}
async fn receive_packet(&mut self) -> Result<Option<Packet>, PacketError> {
Packet::deserialize(&mut self.incoming).await
}
}
+113
View File
@@ -0,0 +1,113 @@
use std::io::{self, BufRead, Cursor, Write};
use bytes::{BufMut, BytesMut};
use mio::net::TcpStream;
use thiserror::Error;
use tokio::io::AsyncReadExt;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PacketType {
Auth,
AuthResponse,
ExecCommand,
Output,
}
#[derive(Error, Debug)]
pub enum PacketError {
#[error("invalid length")]
InvalidLength,
#[error("expected terminating NUL byte")]
NoNullTermination,
#[error("wrong password")]
WrongPassword,
}
impl PacketType {
fn to_i32(self) -> i32 {
match self {
PacketType::Auth => 3,
PacketType::AuthResponse => 2,
PacketType::ExecCommand => 2,
PacketType::Output => 0,
}
}
pub fn from_i32(n: i32) -> PacketType {
match n {
3 => PacketType::Auth,
2 => PacketType::ExecCommand,
_ => PacketType::Output,
}
}
}
#[derive(Debug)]
pub struct Packet {
id: i32,
ptype: PacketType,
body: String,
}
impl Packet {
pub fn new(id: i32, ptype: PacketType, body: String) -> Packet {
Packet { id, ptype, body }
}
pub async fn send_packet(&mut self, connection: &mut TcpStream) -> io::Result<()> {
// let len = outgoing.len() as u64;
let mut buf = BytesMut::new();
// 10 is for 4 bytes ty, 4 bytes id, and 2 terminating nul bytes.
buf.put_i32_le(10 + self.get_body().len() as i32);
buf.put_i32_le(self.id);
buf.put_i32_le(self.get_type().to_i32());
let bytes = self.get_body().as_bytes();
buf.put_slice(bytes);
buf.put_u8(0);
buf.put_u8(0);
connection.write(&buf).unwrap();
Ok(())
}
pub async fn deserialize(incoming: &mut Vec<u8>) -> Result<Option<Packet>, PacketError> {
if incoming.len() < 4 {
return Ok(None);
}
let mut buf = Cursor::new(&incoming);
let len = buf.read_i32_le().await.unwrap() + 4;
if !(0..=1460).contains(&len) {
return Err(PacketError::InvalidLength);
}
let id = buf.read_i32_le().await.unwrap();
let ty = buf.read_i32_le().await.unwrap();
let mut payload = vec![];
let _ = buf.read_until(b'\0', &mut payload).unwrap();
payload.pop();
if buf.read_u8().await.unwrap() != 0 {
return Err(PacketError::NoNullTermination);
}
if buf.position() != len as u64 {
return Err(PacketError::InvalidLength);
}
incoming.drain(0..len as usize);
let packet = Packet {
id,
ptype: PacketType::from_i32(ty),
body: String::from_utf8(payload).unwrap(),
};
Ok(Some(packet))
}
pub fn get_body(&self) -> &str {
&self.body
}
pub fn get_type(&self) -> PacketType {
self.ptype
}
pub fn get_id(&self) -> i32 {
self.id
}
}
+72 -45
View File
@@ -4,6 +4,7 @@ use std::{
io::Cursor,
rc::Rc,
sync::atomic::{AtomicI32, Ordering},
time::Duration,
};
use base64::{engine::general_purpose, Engine};
@@ -21,6 +22,9 @@ use pumpkin_protocol::{
}, BitSet, ClientPacket, Players, Sample, StatusResponse, VarInt, Version, CURRENT_MC_PROTOCOL
};
use pumpkin_world::dimension::Dimension;
use pumpkin_registry::Registry;
use pumpkin_world::chunk::TestChunk;
use rsa::{traits::PublicKeyParts, RsaPrivateKey, RsaPublicKey};
use serde::{Deserialize, Serialize};
@@ -48,6 +52,9 @@ pub struct Server {
/// Cache the Server brand buffer so we don't have to rebuild them every time a player joins
pub cached_server_brand: Vec<u8>,
/// Cache the registry so we don't have to parse it every time a player joins
pub cached_registry: Vec<Registry>,
pub current_clients: HashMap<Rc<Token>, Rc<RefCell<Client>>>,
// TODO: replace with HashMap <World, Player>
@@ -76,12 +83,18 @@ impl Server {
)
.into_boxed_slice();
let auth_client = if config.0.online_mode {
Some(reqwest::Client::new())
Some(
reqwest::Client::builder()
.timeout(Duration::from_millis(5000))
.build()
.expect("Failed to to make reqwest client"),
)
} else {
None
};
Self {
cached_registry: Registry::get_static(),
// 0 is invalid
entity_id: 2.into(),
// world: World::load(""),
@@ -116,7 +129,12 @@ impl Server {
// todo: put this into the entitiy struct
if client.is_player() {
let id = client.player.as_ref().unwrap().entity_id();
self.broadcast_packet(&mut client, CRemoveEntities::new(vec![id.into()]))
let uuid = client.gameprofile.as_ref().unwrap().id;
self.broadcast_packet_expect(
&mut client,
&CRemovePlayerInfo::new(1.into(), &[UUID(uuid)]),
);
self.broadcast_packet_expect(&mut client, &CRemoveEntities::new(&[id.into()]))
}
}
@@ -130,10 +148,10 @@ impl Server {
client.player = Some(player);
// login packet for our new player
client.send_packet(CLogin::new(
client.send_packet(&CLogin::new(
entity_id,
self.base_config.hardcore,
vec!["minecraft:overworld".into()],
&["minecraft:overworld"],
self.base_config.max_players.into(),
self.base_config.view_distance.into(), // TODO: view distance
self.base_config.simulation_distance.into(), // TODO: sim view dinstance
@@ -141,7 +159,7 @@ impl Server {
false,
false,
0.into(),
"minecraft:overworld".into(),
"minecraft:overworld",
0, // seed
match self.base_config.default_gamemode {
GameMode::Undefined => GameMode::Survival,
@@ -158,26 +176,31 @@ impl Server {
));
dbg!("sending abilities");
// player abilities
client.send_packet(CPlayerAbilities::new(0x02, 00.2, 0.1));
client.send_packet(&CPlayerAbilities::new(0x02, 00.2, 0.1));
// teleport
let x = 10.0;
let y = 120.0;
let z = 10.0;
let yaw = 10.0;
let pitch = 10.0;
client.teleport(x, y, z, 10.0, 10.0);
let gameprofile = client.gameprofile.as_ref().unwrap();
// first send info update to our new player, So he can see his Skin
// also send his info to everyone else
self.broadcast_packet(
client,
CPlayerInfoUpdate::new(
0x01,
&CPlayerInfoUpdate::new(
0x01 | 0x08,
&[pumpkin_protocol::client::play::Player {
uuid: gameprofile.id,
actions: vec![PlayerAction::AddPlayer {
name: gameprofile.name.clone(),
properties: gameprofile.properties.clone(),
}],
actions: vec![
PlayerAction::AddPlayer {
name: gameprofile.name.clone(),
properties: gameprofile.properties.clone(),
},
PlayerAction::UpdateListed { listed: true },
],
}],
),
);
@@ -190,37 +213,41 @@ impl Server {
let gameprofile = client.gameprofile.as_ref().unwrap();
entries.push(pumpkin_protocol::client::play::Player {
uuid: gameprofile.id,
actions: vec![PlayerAction::AddPlayer {
name: gameprofile.name.clone(),
properties: gameprofile.properties.clone(),
}],
actions: vec![
PlayerAction::AddPlayer {
name: gameprofile.name.clone(),
properties: gameprofile.properties.clone(),
},
PlayerAction::UpdateListed { listed: true },
],
})
}
}
client.send_packet(CPlayerInfoUpdate::new(0x01, &entries));
client.send_packet(&CPlayerInfoUpdate::new(0x01 | 0x08, &entries));
// Start waiting for level chunks
client.send_packet(CGameEvent::new(13, 0.0));
client.send_packet(&CGameEvent::new(13, 0.0));
let gameprofile = client.gameprofile.as_ref().unwrap();
// spawn player for every client
self.broadcast_packet_expect(
client,
CSpawnEntity::new(
// TODO: add velo
&CSpawnEntity::new(
entity_id.into(),
gameprofile.id,
UUID(gameprofile.id),
EntityType::Player.to_i32().unwrap().into(),
x,
y,
z,
0,
0,
0,
pitch,
yaw,
yaw,
0.into(),
0,
0,
0,
0.0,
0.0,
0.0,
),
);
// spawn players for our client
@@ -230,64 +257,64 @@ impl Server {
if let Some(player) = &existing_client.player {
let entity = &player.entity;
let gameprofile = existing_client.gameprofile.as_ref().unwrap();
client.send_packet(CSpawnEntity::new(
client.send_packet(&CSpawnEntity::new(
player.entity_id().into(),
gameprofile.id,
UUID(gameprofile.id),
EntityType::Player.to_i32().unwrap().into(),
entity.x,
entity.y,
entity.z,
entity.yaw as u8,
entity.pitch as u8,
0,
entity.yaw,
entity.pitch,
entity.pitch,
0.into(),
0,
0,
0,
0.0,
0.0,
0.0,
))
}
}
// entity meta data
/* if let Some(config) = &client.config {
if let Some(config) = &client.config {
self.broadcast_packet(
client,
CSetEntityMetadata::new(entity_id.into(), vec![Metadata::new(18, VarInt(0), 0)]),
&CSetEntityMetadata::new(
entity_id.into(),
Metadata::new(17, VarInt(0), config.skin_parts),
),
)
}
*/
Server::spawn_test_chunk(client).await;
}
/// Sends a Packet to all Players
pub fn broadcast_packet<P>(&mut self, from: &mut Client, packet: P)
pub fn broadcast_packet<P>(&mut self, from: &mut Client, packet: &P)
where
P: ClientPacket,
P: Clone,
{
// we can't borrow twice at same time
from.send_packet(packet.clone());
from.send_packet(packet);
for (_, client) in self.current_clients.iter().filter(|c| c.0 != &from.token) {
// Check if client is a player
let mut client = client.borrow_mut();
if client.is_player() {
// we need to clone, Because we send a new packet to every client
client.send_packet(packet.clone());
client.send_packet(packet);
}
}
}
pub fn broadcast_packet_expect<P>(&mut self, from: &mut Client, packet: P)
pub fn broadcast_packet_expect<P>(&mut self, from: &mut Client, packet: &P)
where
P: ClientPacket,
P: Clone,
{
for (_, client) in self.current_clients.iter().filter(|c| c.0 != &from.token) {
// Check if client is a player
let mut client = client.borrow_mut();
if client.is_player() {
// we need to clone, Because we send a new packet to every client
client.send_packet(packet.clone());
client.send_packet(packet);
}
}
}
@@ -363,7 +390,7 @@ impl Server {
pub fn send_brand(&self, client: &mut Client) {
// send server brand
client.send_packet(CPluginMessage::new(
client.send_packet(&CPluginMessage::new(
"minecraft:brand",
&self.cached_server_brand,
));
+12
View File
@@ -0,0 +1,12 @@
pub fn wrap_degrees(var: f32) -> f32 {
let mut var1 = var % 360.0;
if var1 >= 180.0 {
var1 -= 360.0;
}
if var1 < -180.0 {
var1 += 360.0;
}
var1
}
+1 -1
View File
@@ -1 +1 @@
pub mod math;